repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
somcom3x/tw_herc_kernel | drivers/media/video/cx18/cx18-av-audio.c | 12747 | 13482 | /*
* cx18 ADEC audio functions
*
* Derived from cx25840-audio.c
*
* Copyright (C) 2007 Hans Verkuil <hverkuil@xs4all.nl>
* Copyright (C) 2008 Andy Walls <awalls@md.metrocast.net>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include "cx18-driver.h"
static int set_audclk_freq(struct cx18 *cx, u32 freq)
{
struct cx18_av_state *state = &cx->av_state;
if (freq != 32000 && freq != 44100 && freq != 48000)
return -EINVAL;
/*
* The PLL parameters are based on the external crystal frequency that
* would ideally be:
*
* NTSC Color subcarrier freq * 8 =
* 4.5 MHz/286 * 455/2 * 8 = 28.63636363... MHz
*
* The accidents of history and rationale that explain from where this
* combination of magic numbers originate can be found in:
*
* [1] Abrahams, I. C., "Choice of Chrominance Subcarrier Frequency in
* the NTSC Standards", Proceedings of the I-R-E, January 1954, pp 79-80
*
* [2] Abrahams, I. C., "The 'Frequency Interleaving' Principle in the
* NTSC Standards", Proceedings of the I-R-E, January 1954, pp 81-83
*
* As Mike Bradley has rightly pointed out, it's not the exact crystal
* frequency that matters, only that all parts of the driver and
* firmware are using the same value (close to the ideal value).
*
* Since I have a strong suspicion that, if the firmware ever assumes a
* crystal value at all, it will assume 28.636360 MHz, the crystal
* freq used in calculations in this driver will be:
*
* xtal_freq = 28.636360 MHz
*
* an error of less than 0.13 ppm which is way, way better than any off
* the shelf crystal will have for accuracy anyway.
*
* Below I aim to run the PLLs' VCOs near 400 MHz to minimze error.
*
* Many thanks to Jeff Campbell and Mike Bradley for their extensive
* investigation, experimentation, testing, and suggested solutions of
* of audio/video sync problems with SVideo and CVBS captures.
*/
if (state->aud_input > CX18_AV_AUDIO_SERIAL2) {
switch (freq) {
case 32000:
/*
* VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04
* AUX_PLL Integer = 0x0d, AUX PLL Post Divider = 0x20
*/
cx18_av_write4(cx, 0x108, 0x200d040f);
/* VID_PLL Fraction = 0x2be2fe */
/* xtal * 0xf.15f17f0/4 = 108 MHz: 432 MHz pre-postdiv*/
cx18_av_write4(cx, 0x10c, 0x002be2fe);
/* AUX_PLL Fraction = 0x176740c */
/* xtal * 0xd.bb3a060/0x20 = 32000 * 384: 393 MHz p-pd*/
cx18_av_write4(cx, 0x110, 0x0176740c);
/* src3/4/6_ctl */
/* 0x1.f77f = (4 * xtal/8*2/455) / 32000 */
cx18_av_write4(cx, 0x900, 0x0801f77f);
cx18_av_write4(cx, 0x904, 0x0801f77f);
cx18_av_write4(cx, 0x90c, 0x0801f77f);
/* SA_MCLK_SEL=1, SA_MCLK_DIV=0x20 */
cx18_av_write(cx, 0x127, 0x60);
/* AUD_COUNT = 0x2fff = 8 samples * 4 * 384 - 1 */
cx18_av_write4(cx, 0x12c, 0x11202fff);
/*
* EN_AV_LOCK = 0
* VID_COUNT = 0x0d2ef8 = 107999.000 * 8 =
* ((8 samples/32,000) * (13,500,000 * 8) * 4 - 1) * 8
*/
cx18_av_write4(cx, 0x128, 0xa00d2ef8);
break;
case 44100:
/*
* VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04
* AUX_PLL Integer = 0x0e, AUX PLL Post Divider = 0x18
*/
cx18_av_write4(cx, 0x108, 0x180e040f);
/* VID_PLL Fraction = 0x2be2fe */
/* xtal * 0xf.15f17f0/4 = 108 MHz: 432 MHz pre-postdiv*/
cx18_av_write4(cx, 0x10c, 0x002be2fe);
/* AUX_PLL Fraction = 0x062a1f2 */
/* xtal * 0xe.3150f90/0x18 = 44100 * 384: 406 MHz p-pd*/
cx18_av_write4(cx, 0x110, 0x0062a1f2);
/* src3/4/6_ctl */
/* 0x1.6d59 = (4 * xtal/8*2/455) / 44100 */
cx18_av_write4(cx, 0x900, 0x08016d59);
cx18_av_write4(cx, 0x904, 0x08016d59);
cx18_av_write4(cx, 0x90c, 0x08016d59);
/* SA_MCLK_SEL=1, SA_MCLK_DIV=0x18 */
cx18_av_write(cx, 0x127, 0x58);
/* AUD_COUNT = 0x92ff = 49 samples * 2 * 384 - 1 */
cx18_av_write4(cx, 0x12c, 0x112092ff);
/*
* EN_AV_LOCK = 0
* VID_COUNT = 0x1d4bf8 = 239999.000 * 8 =
* ((49 samples/44,100) * (13,500,000 * 8) * 2 - 1) * 8
*/
cx18_av_write4(cx, 0x128, 0xa01d4bf8);
break;
case 48000:
/*
* VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04
* AUX_PLL Integer = 0x0e, AUX PLL Post Divider = 0x16
*/
cx18_av_write4(cx, 0x108, 0x160e040f);
/* VID_PLL Fraction = 0x2be2fe */
/* xtal * 0xf.15f17f0/4 = 108 MHz: 432 MHz pre-postdiv*/
cx18_av_write4(cx, 0x10c, 0x002be2fe);
/* AUX_PLL Fraction = 0x05227ad */
/* xtal * 0xe.2913d68/0x16 = 48000 * 384: 406 MHz p-pd*/
cx18_av_write4(cx, 0x110, 0x005227ad);
/* src3/4/6_ctl */
/* 0x1.4faa = (4 * xtal/8*2/455) / 48000 */
cx18_av_write4(cx, 0x900, 0x08014faa);
cx18_av_write4(cx, 0x904, 0x08014faa);
cx18_av_write4(cx, 0x90c, 0x08014faa);
/* SA_MCLK_SEL=1, SA_MCLK_DIV=0x16 */
cx18_av_write(cx, 0x127, 0x56);
/* AUD_COUNT = 0x5fff = 4 samples * 16 * 384 - 1 */
cx18_av_write4(cx, 0x12c, 0x11205fff);
/*
* EN_AV_LOCK = 0
* VID_COUNT = 0x1193f8 = 143999.000 * 8 =
* ((4 samples/48,000) * (13,500,000 * 8) * 16 - 1) * 8
*/
cx18_av_write4(cx, 0x128, 0xa01193f8);
break;
}
} else {
switch (freq) {
case 32000:
/*
* VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04
* AUX_PLL Integer = 0x0d, AUX PLL Post Divider = 0x30
*/
cx18_av_write4(cx, 0x108, 0x300d040f);
/* VID_PLL Fraction = 0x2be2fe */
/* xtal * 0xf.15f17f0/4 = 108 MHz: 432 MHz pre-postdiv*/
cx18_av_write4(cx, 0x10c, 0x002be2fe);
/* AUX_PLL Fraction = 0x176740c */
/* xtal * 0xd.bb3a060/0x30 = 32000 * 256: 393 MHz p-pd*/
cx18_av_write4(cx, 0x110, 0x0176740c);
/* src1_ctl */
/* 0x1.0000 = 32000/32000 */
cx18_av_write4(cx, 0x8f8, 0x08010000);
/* src3/4/6_ctl */
/* 0x2.0000 = 2 * (32000/32000) */
cx18_av_write4(cx, 0x900, 0x08020000);
cx18_av_write4(cx, 0x904, 0x08020000);
cx18_av_write4(cx, 0x90c, 0x08020000);
/* SA_MCLK_SEL=1, SA_MCLK_DIV=0x30 */
cx18_av_write(cx, 0x127, 0x70);
/* AUD_COUNT = 0x1fff = 8 samples * 4 * 256 - 1 */
cx18_av_write4(cx, 0x12c, 0x11201fff);
/*
* EN_AV_LOCK = 0
* VID_COUNT = 0x0d2ef8 = 107999.000 * 8 =
* ((8 samples/32,000) * (13,500,000 * 8) * 4 - 1) * 8
*/
cx18_av_write4(cx, 0x128, 0xa00d2ef8);
break;
case 44100:
/*
* VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04
* AUX_PLL Integer = 0x0e, AUX PLL Post Divider = 0x24
*/
cx18_av_write4(cx, 0x108, 0x240e040f);
/* VID_PLL Fraction = 0x2be2fe */
/* xtal * 0xf.15f17f0/4 = 108 MHz: 432 MHz pre-postdiv*/
cx18_av_write4(cx, 0x10c, 0x002be2fe);
/* AUX_PLL Fraction = 0x062a1f2 */
/* xtal * 0xe.3150f90/0x24 = 44100 * 256: 406 MHz p-pd*/
cx18_av_write4(cx, 0x110, 0x0062a1f2);
/* src1_ctl */
/* 0x1.60cd = 44100/32000 */
cx18_av_write4(cx, 0x8f8, 0x080160cd);
/* src3/4/6_ctl */
/* 0x1.7385 = 2 * (32000/44100) */
cx18_av_write4(cx, 0x900, 0x08017385);
cx18_av_write4(cx, 0x904, 0x08017385);
cx18_av_write4(cx, 0x90c, 0x08017385);
/* SA_MCLK_SEL=1, SA_MCLK_DIV=0x24 */
cx18_av_write(cx, 0x127, 0x64);
/* AUD_COUNT = 0x61ff = 49 samples * 2 * 256 - 1 */
cx18_av_write4(cx, 0x12c, 0x112061ff);
/*
* EN_AV_LOCK = 0
* VID_COUNT = 0x1d4bf8 = 239999.000 * 8 =
* ((49 samples/44,100) * (13,500,000 * 8) * 2 - 1) * 8
*/
cx18_av_write4(cx, 0x128, 0xa01d4bf8);
break;
case 48000:
/*
* VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04
* AUX_PLL Integer = 0x0d, AUX PLL Post Divider = 0x20
*/
cx18_av_write4(cx, 0x108, 0x200d040f);
/* VID_PLL Fraction = 0x2be2fe */
/* xtal * 0xf.15f17f0/4 = 108 MHz: 432 MHz pre-postdiv*/
cx18_av_write4(cx, 0x10c, 0x002be2fe);
/* AUX_PLL Fraction = 0x176740c */
/* xtal * 0xd.bb3a060/0x20 = 48000 * 256: 393 MHz p-pd*/
cx18_av_write4(cx, 0x110, 0x0176740c);
/* src1_ctl */
/* 0x1.8000 = 48000/32000 */
cx18_av_write4(cx, 0x8f8, 0x08018000);
/* src3/4/6_ctl */
/* 0x1.5555 = 2 * (32000/48000) */
cx18_av_write4(cx, 0x900, 0x08015555);
cx18_av_write4(cx, 0x904, 0x08015555);
cx18_av_write4(cx, 0x90c, 0x08015555);
/* SA_MCLK_SEL=1, SA_MCLK_DIV=0x20 */
cx18_av_write(cx, 0x127, 0x60);
/* AUD_COUNT = 0x3fff = 4 samples * 16 * 256 - 1 */
cx18_av_write4(cx, 0x12c, 0x11203fff);
/*
* EN_AV_LOCK = 0
* VID_COUNT = 0x1193f8 = 143999.000 * 8 =
* ((4 samples/48,000) * (13,500,000 * 8) * 16 - 1) * 8
*/
cx18_av_write4(cx, 0x128, 0xa01193f8);
break;
}
}
state->audclk_freq = freq;
return 0;
}
void cx18_av_audio_set_path(struct cx18 *cx)
{
struct cx18_av_state *state = &cx->av_state;
u8 v;
/* stop microcontroller */
v = cx18_av_read(cx, 0x803) & ~0x10;
cx18_av_write_expect(cx, 0x803, v, v, 0x1f);
/* assert soft reset */
v = cx18_av_read(cx, 0x810) | 0x01;
cx18_av_write_expect(cx, 0x810, v, v, 0x0f);
/* Mute everything to prevent the PFFT! */
cx18_av_write(cx, 0x8d3, 0x1f);
if (state->aud_input <= CX18_AV_AUDIO_SERIAL2) {
/* Set Path1 to Serial Audio Input */
cx18_av_write4(cx, 0x8d0, 0x01011012);
/* The microcontroller should not be started for the
* non-tuner inputs: autodetection is specific for
* TV audio. */
} else {
/* Set Path1 to Analog Demod Main Channel */
cx18_av_write4(cx, 0x8d0, 0x1f063870);
}
set_audclk_freq(cx, state->audclk_freq);
/* deassert soft reset */
v = cx18_av_read(cx, 0x810) & ~0x01;
cx18_av_write_expect(cx, 0x810, v, v, 0x0f);
if (state->aud_input > CX18_AV_AUDIO_SERIAL2) {
/* When the microcontroller detects the
* audio format, it will unmute the lines */
v = cx18_av_read(cx, 0x803) | 0x10;
cx18_av_write_expect(cx, 0x803, v, v, 0x1f);
}
}
static void set_volume(struct cx18 *cx, int volume)
{
/* First convert the volume to msp3400 values (0-127) */
int vol = volume >> 9;
/* now scale it up to cx18_av values
* -114dB to -96dB maps to 0
* this should be 19, but in my testing that was 4dB too loud */
if (vol <= 23)
vol = 0;
else
vol -= 23;
/* PATH1_VOLUME */
cx18_av_write(cx, 0x8d4, 228 - (vol * 2));
}
static void set_bass(struct cx18 *cx, int bass)
{
/* PATH1_EQ_BASS_VOL */
cx18_av_and_or(cx, 0x8d9, ~0x3f, 48 - (bass * 48 / 0xffff));
}
static void set_treble(struct cx18 *cx, int treble)
{
/* PATH1_EQ_TREBLE_VOL */
cx18_av_and_or(cx, 0x8db, ~0x3f, 48 - (treble * 48 / 0xffff));
}
static void set_balance(struct cx18 *cx, int balance)
{
int bal = balance >> 8;
if (bal > 0x80) {
/* PATH1_BAL_LEFT */
cx18_av_and_or(cx, 0x8d5, 0x7f, 0x80);
/* PATH1_BAL_LEVEL */
cx18_av_and_or(cx, 0x8d5, ~0x7f, bal & 0x7f);
} else {
/* PATH1_BAL_LEFT */
cx18_av_and_or(cx, 0x8d5, 0x7f, 0x00);
/* PATH1_BAL_LEVEL */
cx18_av_and_or(cx, 0x8d5, ~0x7f, 0x80 - bal);
}
}
static void set_mute(struct cx18 *cx, int mute)
{
struct cx18_av_state *state = &cx->av_state;
u8 v;
if (state->aud_input > CX18_AV_AUDIO_SERIAL2) {
/* Must turn off microcontroller in order to mute sound.
* Not sure if this is the best method, but it does work.
* If the microcontroller is running, then it will undo any
* changes to the mute register. */
v = cx18_av_read(cx, 0x803);
if (mute) {
/* disable microcontroller */
v &= ~0x10;
cx18_av_write_expect(cx, 0x803, v, v, 0x1f);
cx18_av_write(cx, 0x8d3, 0x1f);
} else {
/* enable microcontroller */
v |= 0x10;
cx18_av_write_expect(cx, 0x803, v, v, 0x1f);
}
} else {
/* SRC1_MUTE_EN */
cx18_av_and_or(cx, 0x8d3, ~0x2, mute ? 0x02 : 0x00);
}
}
int cx18_av_s_clock_freq(struct v4l2_subdev *sd, u32 freq)
{
struct cx18 *cx = v4l2_get_subdevdata(sd);
struct cx18_av_state *state = &cx->av_state;
int retval;
u8 v;
if (state->aud_input > CX18_AV_AUDIO_SERIAL2) {
v = cx18_av_read(cx, 0x803) & ~0x10;
cx18_av_write_expect(cx, 0x803, v, v, 0x1f);
cx18_av_write(cx, 0x8d3, 0x1f);
}
v = cx18_av_read(cx, 0x810) | 0x1;
cx18_av_write_expect(cx, 0x810, v, v, 0x0f);
retval = set_audclk_freq(cx, freq);
v = cx18_av_read(cx, 0x810) & ~0x1;
cx18_av_write_expect(cx, 0x810, v, v, 0x0f);
if (state->aud_input > CX18_AV_AUDIO_SERIAL2) {
v = cx18_av_read(cx, 0x803) | 0x10;
cx18_av_write_expect(cx, 0x803, v, v, 0x1f);
}
return retval;
}
static int cx18_av_audio_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct v4l2_subdev *sd = to_sd(ctrl);
struct cx18 *cx = v4l2_get_subdevdata(sd);
switch (ctrl->id) {
case V4L2_CID_AUDIO_VOLUME:
set_volume(cx, ctrl->val);
break;
case V4L2_CID_AUDIO_BASS:
set_bass(cx, ctrl->val);
break;
case V4L2_CID_AUDIO_TREBLE:
set_treble(cx, ctrl->val);
break;
case V4L2_CID_AUDIO_BALANCE:
set_balance(cx, ctrl->val);
break;
case V4L2_CID_AUDIO_MUTE:
set_mute(cx, ctrl->val);
break;
default:
return -EINVAL;
}
return 0;
}
const struct v4l2_ctrl_ops cx18_av_audio_ctrl_ops = {
.s_ctrl = cx18_av_audio_s_ctrl,
};
| gpl-2.0 |
Phreya/phreya_kernel_bacon_cm | arch/arm/kernel/arthur.c | 13515 | 2275 | /*
* linux/arch/arm/kernel/arthur.c
*
* Copyright (C) 1998, 1999, 2000, 2001 Philip Blundell
*
* Arthur personality
*/
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/personality.h>
#include <linux/stddef.h>
#include <linux/signal.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <asm/ptrace.h>
/* Arthur doesn't have many signals, and a lot of those that it does
have don't map easily to any Linux equivalent. Never mind. */
#define ARTHUR_SIGABRT 1
#define ARTHUR_SIGFPE 2
#define ARTHUR_SIGILL 3
#define ARTHUR_SIGINT 4
#define ARTHUR_SIGSEGV 5
#define ARTHUR_SIGTERM 6
#define ARTHUR_SIGSTAK 7
#define ARTHUR_SIGUSR1 8
#define ARTHUR_SIGUSR2 9
#define ARTHUR_SIGOSERROR 10
static unsigned long arthur_to_linux_signals[32] = {
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31
};
static unsigned long linux_to_arthur_signals[32] = {
0, -1, ARTHUR_SIGINT, -1,
ARTHUR_SIGILL, 5, ARTHUR_SIGABRT, 7,
ARTHUR_SIGFPE, 9, ARTHUR_SIGUSR1, ARTHUR_SIGSEGV,
ARTHUR_SIGUSR2, 13, 14, ARTHUR_SIGTERM,
16, 17, 18, 19,
20, 21, 22, 23,
24, 25, 26, 27,
28, 29, 30, 31
};
static void arthur_lcall7(int nr, struct pt_regs *regs)
{
struct siginfo info;
info.si_signo = SIGSWI;
info.si_errno = nr;
/* Bounce it to the emulator */
send_sig_info(SIGSWI, &info, current);
}
static struct exec_domain arthur_exec_domain = {
.name = "Arthur",
.handler = arthur_lcall7,
.pers_low = PER_RISCOS,
.pers_high = PER_RISCOS,
.signal_map = arthur_to_linux_signals,
.signal_invmap = linux_to_arthur_signals,
.module = THIS_MODULE,
};
/*
* We could do with some locking to stop Arthur being removed while
* processes are using it.
*/
static int __init arthur_init(void)
{
return register_exec_domain(&arthur_exec_domain);
}
static void __exit arthur_exit(void)
{
unregister_exec_domain(&arthur_exec_domain);
}
module_init(arthur_init);
module_exit(arthur_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
bq/aquaris-M4.5 | arch/mn10300/kernel/signal.c | 460 | 11015 | /* MN10300 Signal handling
*
* 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 <linux/sched.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/wait.h>
#include <linux/ptrace.h>
#include <linux/unistd.h>
#include <linux/stddef.h>
#include <linux/tty.h>
#include <linux/personality.h>
#include <linux/suspend.h>
#include <linux/tracehook.h>
#include <asm/cacheflush.h>
#include <asm/ucontext.h>
#include <asm/uaccess.h>
#include <asm/fpu.h>
#include "sigframe.h"
#define DEBUG_SIG 0
/*
* do a signal return; undo the signal stack.
*/
static int restore_sigcontext(struct pt_regs *regs,
struct sigcontext __user *sc, long *_d0)
{
unsigned int err = 0;
/* Always make any pending restarted system calls return -EINTR */
current_thread_info()->restart_block.fn = do_no_restart_syscall;
if (is_using_fpu(current))
fpu_kill_state(current);
#define COPY(x) err |= __get_user(regs->x, &sc->x)
COPY(d1); COPY(d2); COPY(d3);
COPY(a0); COPY(a1); COPY(a2); COPY(a3);
COPY(e0); COPY(e1); COPY(e2); COPY(e3);
COPY(e4); COPY(e5); COPY(e6); COPY(e7);
COPY(lar); COPY(lir);
COPY(mdr); COPY(mdrq);
COPY(mcvf); COPY(mcrl); COPY(mcrh);
COPY(sp); COPY(pc);
#undef COPY
{
unsigned int tmpflags;
#ifndef CONFIG_MN10300_USING_JTAG
#define USER_EPSW (EPSW_FLAG_Z | EPSW_FLAG_N | EPSW_FLAG_C | EPSW_FLAG_V | \
EPSW_T | EPSW_nAR)
#else
#define USER_EPSW (EPSW_FLAG_Z | EPSW_FLAG_N | EPSW_FLAG_C | EPSW_FLAG_V | \
EPSW_nAR)
#endif
err |= __get_user(tmpflags, &sc->epsw);
regs->epsw = (regs->epsw & ~USER_EPSW) |
(tmpflags & USER_EPSW);
regs->orig_d0 = -1; /* disable syscall checks */
}
{
struct fpucontext *buf;
err |= __get_user(buf, &sc->fpucontext);
if (buf) {
if (verify_area(VERIFY_READ, buf, sizeof(*buf)))
goto badframe;
err |= fpu_restore_sigcontext(buf);
}
}
err |= __get_user(*_d0, &sc->d0);
return err;
badframe:
return 1;
}
/*
* standard signal return syscall
*/
asmlinkage long sys_sigreturn(void)
{
struct sigframe __user *frame;
sigset_t set;
long d0;
frame = (struct sigframe __user *) current_frame()->sp;
if (verify_area(VERIFY_READ, frame, sizeof(*frame)))
goto badframe;
if (__get_user(set.sig[0], &frame->sc.oldmask))
goto badframe;
if (_NSIG_WORDS > 1 &&
__copy_from_user(&set.sig[1], &frame->extramask,
sizeof(frame->extramask)))
goto badframe;
set_current_blocked(&set);
if (restore_sigcontext(current_frame(), &frame->sc, &d0))
goto badframe;
return d0;
badframe:
force_sig(SIGSEGV, current);
return 0;
}
/*
* realtime signal return syscall
*/
asmlinkage long sys_rt_sigreturn(void)
{
struct rt_sigframe __user *frame;
sigset_t set;
long d0;
frame = (struct rt_sigframe __user *) current_frame()->sp;
if (verify_area(VERIFY_READ, frame, sizeof(*frame)))
goto badframe;
if (__copy_from_user(&set, &frame->uc.uc_sigmask, sizeof(set)))
goto badframe;
set_current_blocked(&set);
if (restore_sigcontext(current_frame(), &frame->uc.uc_mcontext, &d0))
goto badframe;
if (restore_altstack(&frame->uc.uc_stack))
goto badframe;
return d0;
badframe:
force_sig(SIGSEGV, current);
return 0;
}
/*
* store the userspace context into a signal frame
*/
static int setup_sigcontext(struct sigcontext __user *sc,
struct fpucontext *fpuctx,
struct pt_regs *regs,
unsigned long mask)
{
int tmp, err = 0;
#define COPY(x) err |= __put_user(regs->x, &sc->x)
COPY(d0); COPY(d1); COPY(d2); COPY(d3);
COPY(a0); COPY(a1); COPY(a2); COPY(a3);
COPY(e0); COPY(e1); COPY(e2); COPY(e3);
COPY(e4); COPY(e5); COPY(e6); COPY(e7);
COPY(lar); COPY(lir);
COPY(mdr); COPY(mdrq);
COPY(mcvf); COPY(mcrl); COPY(mcrh);
COPY(sp); COPY(epsw); COPY(pc);
#undef COPY
tmp = fpu_setup_sigcontext(fpuctx);
if (tmp < 0)
err = 1;
else
err |= __put_user(tmp ? fpuctx : NULL, &sc->fpucontext);
/* non-iBCS2 extensions.. */
err |= __put_user(mask, &sc->oldmask);
return err;
}
/*
* determine which stack to use..
*/
static inline void __user *get_sigframe(struct ksignal *ksig,
struct pt_regs *regs,
size_t frame_size)
{
unsigned long sp = sigsp(regs->sp, ksig);
return (void __user *) ((sp - frame_size) & ~7UL);
}
/*
* set up a normal signal frame
*/
static int setup_frame(struct ksignal *ksig, sigset_t *set,
struct pt_regs *regs)
{
struct sigframe __user *frame;
int rsig, sig = ksig->sig;
frame = get_sigframe(ksig, regs, sizeof(*frame));
if (!access_ok(VERIFY_WRITE, frame, sizeof(*frame)))
return -EFAULT;
rsig = sig;
if (sig < 32 &&
current_thread_info()->exec_domain &&
current_thread_info()->exec_domain->signal_invmap)
rsig = current_thread_info()->exec_domain->signal_invmap[sig];
if (__put_user(rsig, &frame->sig) < 0 ||
__put_user(&frame->sc, &frame->psc) < 0)
return -EFAULT;
if (setup_sigcontext(&frame->sc, &frame->fpuctx, regs, set->sig[0]))
return -EFAULT;
if (_NSIG_WORDS > 1) {
if (__copy_to_user(frame->extramask, &set->sig[1],
sizeof(frame->extramask)))
return -EFAULT;
}
/* set up to return from userspace. If provided, use a stub already in
* userspace */
if (ksig->ka.sa.sa_flags & SA_RESTORER) {
if (__put_user(ksig->ka.sa.sa_restorer, &frame->pretcode))
return -EFAULT;
} else {
if (__put_user((void (*)(void))frame->retcode,
&frame->pretcode))
return -EFAULT;
/* this is mov $,d0; syscall 0 */
if (__put_user(0x2c, (char *)(frame->retcode + 0)) ||
__put_user(__NR_sigreturn, (char *)(frame->retcode + 1)) ||
__put_user(0x00, (char *)(frame->retcode + 2)) ||
__put_user(0xf0, (char *)(frame->retcode + 3)) ||
__put_user(0xe0, (char *)(frame->retcode + 4)))
return -EFAULT;
flush_icache_range((unsigned long) frame->retcode,
(unsigned long) frame->retcode + 5);
}
/* set up registers for signal handler */
regs->sp = (unsigned long) frame;
regs->pc = (unsigned long) ksig->ka.sa.sa_handler;
regs->d0 = sig;
regs->d1 = (unsigned long) &frame->sc;
#if DEBUG_SIG
printk(KERN_DEBUG "SIG deliver %d (%s:%d): sp=%p pc=%lx ra=%p\n",
sig, current->comm, current->pid, frame, regs->pc,
frame->pretcode);
#endif
return 0;
}
/*
* set up a realtime signal frame
*/
static int setup_rt_frame(struct ksignal *ksig, sigset_t *set,
struct pt_regs *regs)
{
struct rt_sigframe __user *frame;
int rsig, sig = ksig->sig;
frame = get_sigframe(ksig, regs, sizeof(*frame));
if (!access_ok(VERIFY_WRITE, frame, sizeof(*frame)))
return -EFAULT;
rsig = sig;
if (sig < 32 &&
current_thread_info()->exec_domain &&
current_thread_info()->exec_domain->signal_invmap)
rsig = current_thread_info()->exec_domain->signal_invmap[sig];
if (__put_user(rsig, &frame->sig) ||
__put_user(&frame->info, &frame->pinfo) ||
__put_user(&frame->uc, &frame->puc) ||
copy_siginfo_to_user(&frame->info, &ksig->info))
return -EFAULT;
/* create the ucontext. */
if (__put_user(0, &frame->uc.uc_flags) ||
__put_user(0, &frame->uc.uc_link) ||
__save_altstack(&frame->uc.uc_stack, regs->sp) ||
setup_sigcontext(&frame->uc.uc_mcontext,
&frame->fpuctx, regs, set->sig[0]) ||
__copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set)))
return -EFAULT;
/* set up to return from userspace. If provided, use a stub already in
* userspace */
if (ksig->ka.sa.sa_flags & SA_RESTORER) {
if (__put_user(ksig->ka.sa.sa_restorer, &frame->pretcode))
return -EFAULT;
} else {
if (__put_user((void(*)(void))frame->retcode,
&frame->pretcode) ||
/* This is mov $,d0; syscall 0 */
__put_user(0x2c, (char *)(frame->retcode + 0)) ||
__put_user(__NR_rt_sigreturn,
(char *)(frame->retcode + 1)) ||
__put_user(0x00, (char *)(frame->retcode + 2)) ||
__put_user(0xf0, (char *)(frame->retcode + 3)) ||
__put_user(0xe0, (char *)(frame->retcode + 4)))
return -EFAULT;
flush_icache_range((u_long) frame->retcode,
(u_long) frame->retcode + 5);
}
/* Set up registers for signal handler */
regs->sp = (unsigned long) frame;
regs->pc = (unsigned long) ksig->ka.sa.sa_handler;
regs->d0 = sig;
regs->d1 = (long) &frame->info;
#if DEBUG_SIG
printk(KERN_DEBUG "SIG deliver %d (%s:%d): sp=%p pc=%lx ra=%p\n",
sig, current->comm, current->pid, frame, regs->pc,
frame->pretcode);
#endif
return 0;
}
static inline void stepback(struct pt_regs *regs)
{
regs->pc -= 2;
regs->orig_d0 = -1;
}
/*
* handle the actual delivery of a signal to userspace
*/
static int handle_signal(struct ksignal *ksig, struct pt_regs *regs)
{
sigset_t *oldset = sigmask_to_save();
int ret;
/* Are we from a system call? */
if (regs->orig_d0 >= 0) {
/* If so, check system call restarting.. */
switch (regs->d0) {
case -ERESTART_RESTARTBLOCK:
case -ERESTARTNOHAND:
regs->d0 = -EINTR;
break;
case -ERESTARTSYS:
if (!(ksig->ka.sa.sa_flags & SA_RESTART)) {
regs->d0 = -EINTR;
break;
}
/* fallthrough */
case -ERESTARTNOINTR:
regs->d0 = regs->orig_d0;
stepback(regs);
}
}
/* Set up the stack frame */
if (ksig->ka.sa.sa_flags & SA_SIGINFO)
ret = setup_rt_frame(ksig, oldset, regs);
else
ret = setup_frame(ksig, oldset, regs);
signal_setup_done(ret, ksig, test_thread_flag(TIF_SINGLESTEP));
return 0;
}
/*
* handle a potential signal
*/
static void do_signal(struct pt_regs *regs)
{
struct ksignal ksig;
if (get_signal(&ksig)) {
handle_signal(&ksig, regs);
return;
}
/* did we come from a system call? */
if (regs->orig_d0 >= 0) {
/* restart the system call - no handlers present */
switch (regs->d0) {
case -ERESTARTNOHAND:
case -ERESTARTSYS:
case -ERESTARTNOINTR:
regs->d0 = regs->orig_d0;
stepback(regs);
break;
case -ERESTART_RESTARTBLOCK:
regs->d0 = __NR_restart_syscall;
stepback(regs);
break;
}
}
/* if there's no signal to deliver, we just put the saved sigmask
* back */
restore_saved_sigmask();
}
/*
* notification of userspace execution resumption
* - triggered by current->work.notify_resume
*/
asmlinkage void do_notify_resume(struct pt_regs *regs, u32 thread_info_flags)
{
/* Pending single-step? */
if (thread_info_flags & _TIF_SINGLESTEP) {
#ifndef CONFIG_MN10300_USING_JTAG
regs->epsw |= EPSW_T;
clear_thread_flag(TIF_SINGLESTEP);
#else
BUG(); /* no h/w single-step if using JTAG unit */
#endif
}
/* deal with pending signal delivery */
if (thread_info_flags & _TIF_SIGPENDING)
do_signal(regs);
if (thread_info_flags & _TIF_NOTIFY_RESUME) {
clear_thread_flag(TIF_NOTIFY_RESUME);
tracehook_notify_resume(current_frame());
}
}
| gpl-2.0 |
weritos666/Vee7 | drivers/video/msm/lcdc_toshiba_fwvga_pt.c | 460 | 10932 | /* Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/delay.h>
#include <linux/module.h>
#include <mach/gpio.h>
#include <mach/pmic.h>
#include <mach/socinfo.h>
#include "msm_fb.h"
static int spi_cs0_N;
static int spi_sclk;
static int spi_mosi;
static int spi_miso;
struct toshiba_state_type {
boolean disp_initialized;
boolean display_on;
boolean disp_powered_up;
};
static struct toshiba_state_type toshiba_state = { 0 };
static struct msm_panel_common_pdata *lcdc_toshiba_pdata;
static int toshiba_spi_write(char data1, char data2, int rs)
{
uint32 bitdata = 0, bnum = 24, bmask = 0x800000;
gpio_set_value_cansleep(spi_cs0_N, 0); /* cs* low */
udelay(1);
if (rs)
bitdata = (0x72 << 16);
else
bitdata = (0x70 << 16);
bitdata |= ((data1 << 8) | data2);
while (bnum) {
gpio_set_value_cansleep(spi_sclk, 0); /* clk low */
udelay(1);
if (bitdata & bmask)
gpio_set_value_cansleep(spi_mosi, 1);
else
gpio_set_value_cansleep(spi_mosi, 0);
udelay(1);
gpio_set_value_cansleep(spi_sclk, 1); /* clk high */
udelay(1);
bmask >>= 1;
bnum--;
}
gpio_set_value_cansleep(spi_cs0_N, 1); /* cs* high */
udelay(1);
return 0;
}
static void spi_pin_assign(void)
{
/* Setting the Default GPIO's */
spi_mosi = *(lcdc_toshiba_pdata->gpio_num);
spi_miso = *(lcdc_toshiba_pdata->gpio_num + 1);
spi_sclk = *(lcdc_toshiba_pdata->gpio_num + 2);
spi_cs0_N = *(lcdc_toshiba_pdata->gpio_num + 3);
}
static void toshiba_disp_powerup(void)
{
if (!toshiba_state.disp_powered_up && !toshiba_state.display_on) {
/* Reset the hardware first */
/* Include DAC power up implementation here */
toshiba_state.disp_powered_up = TRUE;
}
}
static void toshiba_disp_on(void)
{
if (toshiba_state.disp_powered_up && !toshiba_state.display_on) {
toshiba_spi_write(0x01, 0x00, 0);
toshiba_spi_write(0x30, 0x00, 1);
udelay(500);
toshiba_spi_write(0x01, 0x01, 0);
toshiba_spi_write(0x40, 0x10, 1);
#ifdef TOSHIBA_FWVGA_FULL_INIT
udelay(500);
toshiba_spi_write(0x01, 0x06, 0);
toshiba_spi_write(0x00, 0x00, 1);
msleep(20);
toshiba_spi_write(0x00, 0x01, 0);
toshiba_spi_write(0x03, 0x10, 1);
udelay(500);
toshiba_spi_write(0x00, 0x02, 0);
toshiba_spi_write(0x01, 0x00, 1);
udelay(500);
toshiba_spi_write(0x00, 0x03, 0);
toshiba_spi_write(0x00, 0x00, 1);
udelay(500);
toshiba_spi_write(0x00, 0x07, 0);
toshiba_spi_write(0x00, 0x00, 1);
udelay(500);
toshiba_spi_write(0x00, 0x08, 0);
toshiba_spi_write(0x00, 0x04, 1);
udelay(500);
toshiba_spi_write(0x00, 0x09, 0);
toshiba_spi_write(0x00, 0x0c, 1);
#endif
udelay(500);
toshiba_spi_write(0x00, 0x0c, 0);
toshiba_spi_write(0x40, 0x10, 1);
udelay(500);
toshiba_spi_write(0x00, 0x0e, 0);
toshiba_spi_write(0x00, 0x00, 1);
udelay(500);
toshiba_spi_write(0x00, 0x20, 0);
toshiba_spi_write(0x01, 0x3f, 1);
udelay(500);
toshiba_spi_write(0x00, 0x22, 0);
toshiba_spi_write(0x76, 0x00, 1);
udelay(500);
toshiba_spi_write(0x00, 0x23, 0);
toshiba_spi_write(0x1c, 0x0a, 1);
udelay(500);
toshiba_spi_write(0x00, 0x24, 0);
toshiba_spi_write(0x1c, 0x2c, 1);
udelay(500);
toshiba_spi_write(0x00, 0x25, 0);
toshiba_spi_write(0x1c, 0x4e, 1);
udelay(500);
toshiba_spi_write(0x00, 0x27, 0);
toshiba_spi_write(0x00, 0x00, 1);
udelay(500);
toshiba_spi_write(0x00, 0x28, 0);
toshiba_spi_write(0x76, 0x0c, 1);
#ifdef TOSHIBA_FWVGA_FULL_INIT
udelay(500);
toshiba_spi_write(0x03, 0x00, 0);
toshiba_spi_write(0x00, 0x00, 1);
udelay(500);
toshiba_spi_write(0x03, 0x01, 0);
toshiba_spi_write(0x05, 0x02, 1);
udelay(500);
toshiba_spi_write(0x03, 0x02, 0);
toshiba_spi_write(0x07, 0x05, 1);
udelay(500);
toshiba_spi_write(0x03, 0x03, 0);
toshiba_spi_write(0x00, 0x00, 1);
udelay(500);
toshiba_spi_write(0x03, 0x04, 0);
toshiba_spi_write(0x02, 0x00, 1);
udelay(500);
toshiba_spi_write(0x03, 0x05, 0);
toshiba_spi_write(0x07, 0x07, 1);
udelay(500);
toshiba_spi_write(0x03, 0x06, 0);
toshiba_spi_write(0x10, 0x10, 1);
udelay(500);
toshiba_spi_write(0x03, 0x07, 0);
toshiba_spi_write(0x02, 0x02, 1);
udelay(500);
toshiba_spi_write(0x03, 0x08, 0);
toshiba_spi_write(0x07, 0x04, 1);
udelay(500);
toshiba_spi_write(0x03, 0x09, 0);
toshiba_spi_write(0x07, 0x07, 1);
udelay(500);
toshiba_spi_write(0x03, 0x0a, 0);
toshiba_spi_write(0x00, 0x00, 1);
udelay(500);
toshiba_spi_write(0x03, 0x0b, 0);
toshiba_spi_write(0x00, 0x00, 1);
udelay(500);
toshiba_spi_write(0x03, 0x0c, 0);
toshiba_spi_write(0x07, 0x07, 1);
udelay(500);
toshiba_spi_write(0x03, 0x0d, 0);
toshiba_spi_write(0x10, 0x10, 1);
udelay(500);
toshiba_spi_write(0x03, 0x10, 0);
toshiba_spi_write(0x01, 0x04, 1);
udelay(500);
toshiba_spi_write(0x03, 0x11, 0);
toshiba_spi_write(0x05, 0x03, 1);
udelay(500);
toshiba_spi_write(0x03, 0x12, 0);
toshiba_spi_write(0x03, 0x04, 1);
udelay(500);
toshiba_spi_write(0x03, 0x15, 0);
toshiba_spi_write(0x03, 0x04, 1);
udelay(500);
toshiba_spi_write(0x03, 0x16, 0);
toshiba_spi_write(0x03, 0x1c, 1);
udelay(500);
toshiba_spi_write(0x03, 0x17, 0);
toshiba_spi_write(0x02, 0x04, 1);
udelay(500);
toshiba_spi_write(0x03, 0x18, 0);
toshiba_spi_write(0x04, 0x02, 1);
udelay(500);
toshiba_spi_write(0x03, 0x19, 0);
toshiba_spi_write(0x03, 0x05, 1);
udelay(500);
toshiba_spi_write(0x03, 0x1c, 0);
toshiba_spi_write(0x07, 0x07, 1);
udelay(500);
toshiba_spi_write(0x03, 0x1d, 0);
toshiba_spi_write(0x02, 0x1f, 1);
udelay(500);
toshiba_spi_write(0x03, 0x20, 0);
toshiba_spi_write(0x05, 0x07, 1);
udelay(500);
toshiba_spi_write(0x03, 0x21, 0);
toshiba_spi_write(0x06, 0x04, 1);
udelay(500);
toshiba_spi_write(0x03, 0x22, 0);
toshiba_spi_write(0x04, 0x05, 1);
udelay(500);
toshiba_spi_write(0x03, 0x27, 0);
toshiba_spi_write(0x02, 0x03, 1);
udelay(500);
toshiba_spi_write(0x03, 0x28, 0);
toshiba_spi_write(0x03, 0x00, 1);
udelay(500);
toshiba_spi_write(0x03, 0x29, 0);
toshiba_spi_write(0x00, 0x02, 1);
#endif
udelay(500);
toshiba_spi_write(0x01, 0x00, 0);
toshiba_spi_write(0x36, 0x3c, 1);
udelay(500);
toshiba_spi_write(0x01, 0x01, 0);
toshiba_spi_write(0x40, 0x03, 1);
udelay(500);
toshiba_spi_write(0x01, 0x02, 0);
toshiba_spi_write(0x00, 0x01, 1);
udelay(500);
toshiba_spi_write(0x01, 0x03, 0);
toshiba_spi_write(0x3c, 0x58, 1);
udelay(500);
toshiba_spi_write(0x01, 0x0c, 0);
toshiba_spi_write(0x01, 0x35, 1);
udelay(500);
toshiba_spi_write(0x01, 0x06, 0);
toshiba_spi_write(0x00, 0x02, 1);
udelay(500);
toshiba_spi_write(0x00, 0x29, 0);
toshiba_spi_write(0x03, 0xbf, 1);
udelay(500);
toshiba_spi_write(0x01, 0x06, 0);
toshiba_spi_write(0x00, 0x03, 1);
msleep(32);
toshiba_spi_write(0x01, 0x01, 0);
toshiba_spi_write(0x40, 0x10, 1);
msleep(80);
toshiba_state.display_on = TRUE;
}
}
static int lcdc_toshiba_panel_on(struct platform_device *pdev)
{
if (!toshiba_state.disp_initialized) {
/* Configure reset GPIO that drives DAC */
if (lcdc_toshiba_pdata->panel_config_gpio)
lcdc_toshiba_pdata->panel_config_gpio(1);
toshiba_disp_powerup();
toshiba_disp_on();
toshiba_state.disp_initialized = TRUE;
}
return 0;
}
static int lcdc_toshiba_panel_off(struct platform_device *pdev)
{
if (toshiba_state.disp_powered_up && toshiba_state.display_on) {
toshiba_spi_write(0x01, 0x06, 1);
toshiba_spi_write(0x00, 0x02, 1);
msleep(80);
toshiba_spi_write(0x01, 0x06, 1);
toshiba_spi_write(0x00, 0x00, 1);
toshiba_spi_write(0x00, 0x29, 1);
toshiba_spi_write(0x00, 0x02, 1);
toshiba_spi_write(0x01, 0x00, 1);
toshiba_spi_write(0x30, 0x00, 1);
if (lcdc_toshiba_pdata->panel_config_gpio)
lcdc_toshiba_pdata->panel_config_gpio(0);
toshiba_state.display_on = FALSE;
toshiba_state.disp_initialized = FALSE;
}
return 0;
}
static void lcdc_toshiba_set_backlight(struct msm_fb_data_type *mfd)
{
int ret;
int bl_level;
bl_level = mfd->bl_level;
if (lcdc_toshiba_pdata && lcdc_toshiba_pdata->pmic_backlight)
ret = lcdc_toshiba_pdata->pmic_backlight(bl_level);
else
pr_err("%s(): Backlight level set failed", __func__);
return;
}
static int __devinit toshiba_probe(struct platform_device *pdev)
{
if (pdev->id == 0) {
lcdc_toshiba_pdata = pdev->dev.platform_data;
spi_pin_assign();
return 0;
}
msm_fb_add_device(pdev);
return 0;
}
static struct platform_driver this_driver = {
.probe = toshiba_probe,
.driver = {
.name = "lcdc_toshiba_fwvga_pt",
},
};
static struct msm_fb_panel_data toshiba_panel_data = {
.on = lcdc_toshiba_panel_on,
.off = lcdc_toshiba_panel_off,
.set_backlight = lcdc_toshiba_set_backlight,
};
static struct platform_device this_device = {
.name = "lcdc_toshiba_fwvga_pt",
.id = 1,
.dev = {
.platform_data = &toshiba_panel_data,
}
};
static int __init lcdc_toshiba_panel_init(void)
{
int ret;
struct msm_panel_info *pinfo;
ret = msm_fb_detect_client("lcdc_toshiba_fwvga_pt");
if (ret)
return 0;
ret = platform_driver_register(&this_driver);
if (ret)
return ret;
pinfo = &toshiba_panel_data.panel_info;
pinfo->xres = 480;
pinfo->yres = 864;
MSM_FB_SINGLE_MODE_PANEL(pinfo);
pinfo->type = LCDC_PANEL;
pinfo->pdest = DISPLAY_1;
pinfo->wait_cycle = 0;
pinfo->bpp = 18;
pinfo->fb_num = 2;
/* 30Mhz mdp_lcdc_pclk and mdp_lcdc_pad_pcl */
pinfo->clk_rate = 30720000;
pinfo->bl_max = 100;
pinfo->bl_min = 1;
if (cpu_is_msm7x25a() || cpu_is_msm7x25aa() || cpu_is_msm7x25ab()) {
pinfo->yres = 320;
pinfo->lcdc.h_back_porch = 10;
pinfo->lcdc.h_front_porch = 21;
pinfo->lcdc.h_pulse_width = 5;
pinfo->lcdc.v_back_porch = 8;
pinfo->lcdc.v_front_porch = 540;
pinfo->lcdc.v_pulse_width = 42;
pinfo->lcdc.border_clr = 0; /* blk */
pinfo->lcdc.underflow_clr = 0xff; /* blue */
pinfo->lcdc.hsync_skew = 0;
} else {
pinfo->lcdc.h_back_porch = 8;
pinfo->lcdc.h_front_porch = 16;
pinfo->lcdc.h_pulse_width = 8;
pinfo->lcdc.v_back_porch = 2;
pinfo->lcdc.v_front_porch = 2;
pinfo->lcdc.v_pulse_width = 2;
pinfo->lcdc.border_clr = 0; /* blk */
pinfo->lcdc.underflow_clr = 0xff; /* blue */
pinfo->lcdc.hsync_skew = 0;
}
ret = platform_device_register(&this_device);
if (ret) {
printk(KERN_ERR "%s not able to register the device\n",
__func__);
platform_driver_unregister(&this_driver);
}
return ret;
}
device_initcall(lcdc_toshiba_panel_init);
| gpl-2.0 |
notro/linux-staging | drivers/staging/comedi/drivers/ni_atmio.c | 716 | 9434 | /*
comedi/drivers/ni_atmio.c
Hardware driver for NI AT-MIO E series cards
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 1997-2001 David A. Schleef <ds@schleef.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
/*
Driver: ni_atmio
Description: National Instruments AT-MIO-E series
Author: ds
Devices: [National Instruments] AT-MIO-16E-1 (ni_atmio),
AT-MIO-16E-2, AT-MIO-16E-10, AT-MIO-16DE-10, AT-MIO-64E-3,
AT-MIO-16XE-50, AT-MIO-16XE-10, AT-AI-16XE-10
Status: works
Updated: Thu May 1 20:03:02 CDT 2003
The driver has 2.6 kernel isapnp support, and
will automatically probe for a supported board if the
I/O base is left unspecified with comedi_config.
However, many of
the isapnp id numbers are unknown. If your board is not
recognized, please send the output of 'cat /proc/isapnp'
(you may need to modprobe the isa-pnp module for
/proc/isapnp to exist) so the
id numbers for your board can be added to the driver.
Otherwise, you can use the isapnptools package to configure
your board. Use isapnp to
configure the I/O base and IRQ for the board, and then pass
the same values as
parameters in comedi_config. A sample isapnp.conf file is included
in the etc/ directory of Comedilib.
Comedilib includes a utility to autocalibrate these boards. The
boards seem to boot into a state where the all calibration DACs
are at one extreme of their range, thus the default calibration
is terrible. Calibration at boot is strongly encouraged.
To use the extended digital I/O on some of the boards, enable the
8255 driver when configuring the Comedi source tree.
External triggering is supported for some events. The channel index
(scan_begin_arg, etc.) maps to PFI0 - PFI9.
Some of the more esoteric triggering possibilities of these boards
are not supported.
*/
/*
The real guts of the driver is in ni_mio_common.c, which is included
both here and in ni_pcimio.c
Interrupt support added by Truxton Fulton <trux@truxton.com>
References for specifications:
340747b.pdf Register Level Programmer Manual (obsolete)
340747c.pdf Register Level Programmer Manual (new)
DAQ-STC reference manual
Other possibly relevant info:
320517c.pdf User manual (obsolete)
320517f.pdf User manual (new)
320889a.pdf delete
320906c.pdf maximum signal ratings
321066a.pdf about 16x
321791a.pdf discontinuation of at-mio-16e-10 rev. c
321808a.pdf about at-mio-16e-10 rev P
321837a.pdf discontinuation of at-mio-16de-10 rev d
321838a.pdf about at-mio-16de-10 rev N
ISSUES:
need to deal with external reference for DAC, and other DAC
properties in board properties
deal with at-mio-16de-10 revision D to N changes, etc.
*/
#include <linux/module.h>
#include <linux/interrupt.h>
#include "../comedidev.h"
#include <linux/isapnp.h>
#include "ni_stc.h"
#include "8255.h"
/*
* AT specific setup
*/
static const struct ni_board_struct ni_boards[] = {
{
.name = "at-mio-16e-1",
.device_id = 44,
.isapnp_id = 0x0000, /* XXX unknown */
.n_adchan = 16,
.ai_maxdata = 0x0fff,
.ai_fifo_depth = 8192,
.gainlkup = ai_gain_16,
.ai_speed = 800,
.n_aochan = 2,
.ao_maxdata = 0x0fff,
.ao_fifo_depth = 2048,
.ao_range_table = &range_ni_E_ao_ext,
.ao_speed = 1000,
.caldac = { mb88341 },
}, {
.name = "at-mio-16e-2",
.device_id = 25,
.isapnp_id = 0x1900,
.n_adchan = 16,
.ai_maxdata = 0x0fff,
.ai_fifo_depth = 2048,
.gainlkup = ai_gain_16,
.ai_speed = 2000,
.n_aochan = 2,
.ao_maxdata = 0x0fff,
.ao_fifo_depth = 2048,
.ao_range_table = &range_ni_E_ao_ext,
.ao_speed = 1000,
.caldac = { mb88341 },
}, {
.name = "at-mio-16e-10",
.device_id = 36,
.isapnp_id = 0x2400,
.n_adchan = 16,
.ai_maxdata = 0x0fff,
.ai_fifo_depth = 512,
.gainlkup = ai_gain_16,
.ai_speed = 10000,
.n_aochan = 2,
.ao_maxdata = 0x0fff,
.ao_range_table = &range_ni_E_ao_ext,
.ao_speed = 10000,
.caldac = { ad8804_debug },
}, {
.name = "at-mio-16de-10",
.device_id = 37,
.isapnp_id = 0x2500,
.n_adchan = 16,
.ai_maxdata = 0x0fff,
.ai_fifo_depth = 512,
.gainlkup = ai_gain_16,
.ai_speed = 10000,
.n_aochan = 2,
.ao_maxdata = 0x0fff,
.ao_range_table = &range_ni_E_ao_ext,
.ao_speed = 10000,
.caldac = { ad8804_debug },
.has_8255 = 1,
}, {
.name = "at-mio-64e-3",
.device_id = 38,
.isapnp_id = 0x2600,
.n_adchan = 64,
.ai_maxdata = 0x0fff,
.ai_fifo_depth = 2048,
.gainlkup = ai_gain_16,
.ai_speed = 2000,
.n_aochan = 2,
.ao_maxdata = 0x0fff,
.ao_fifo_depth = 2048,
.ao_range_table = &range_ni_E_ao_ext,
.ao_speed = 1000,
.caldac = { ad8804_debug },
}, {
.name = "at-mio-16xe-50",
.device_id = 39,
.isapnp_id = 0x2700,
.n_adchan = 16,
.ai_maxdata = 0xffff,
.ai_fifo_depth = 512,
.alwaysdither = 1,
.gainlkup = ai_gain_8,
.ai_speed = 50000,
.n_aochan = 2,
.ao_maxdata = 0x0fff,
.ao_range_table = &range_bipolar10,
.ao_speed = 50000,
.caldac = { dac8800, dac8043 },
}, {
.name = "at-mio-16xe-10",
.device_id = 50,
.isapnp_id = 0x0000, /* XXX unknown */
.n_adchan = 16,
.ai_maxdata = 0xffff,
.ai_fifo_depth = 512,
.alwaysdither = 1,
.gainlkup = ai_gain_14,
.ai_speed = 10000,
.n_aochan = 2,
.ao_maxdata = 0xffff,
.ao_fifo_depth = 2048,
.ao_range_table = &range_ni_E_ao_ext,
.ao_speed = 1000,
.caldac = { dac8800, dac8043, ad8522 },
}, {
.name = "at-ai-16xe-10",
.device_id = 51,
.isapnp_id = 0x0000, /* XXX unknown */
.n_adchan = 16,
.ai_maxdata = 0xffff,
.ai_fifo_depth = 512,
.alwaysdither = 1, /* unknown */
.gainlkup = ai_gain_14,
.ai_speed = 10000,
.caldac = { dac8800, dac8043, ad8522 },
},
};
static const int ni_irqpin[] = {
-1, -1, -1, 0, 1, 2, -1, 3, -1, -1, 4, 5, 6, -1, -1, 7
};
#include "ni_mio_common.c"
static struct pnp_device_id device_ids[] = {
{.id = "NIC1900", .driver_data = 0},
{.id = "NIC2400", .driver_data = 0},
{.id = "NIC2500", .driver_data = 0},
{.id = "NIC2600", .driver_data = 0},
{.id = "NIC2700", .driver_data = 0},
{.id = ""}
};
MODULE_DEVICE_TABLE(pnp, device_ids);
static int ni_isapnp_find_board(struct pnp_dev **dev)
{
struct pnp_dev *isapnp_dev = NULL;
int i;
for (i = 0; i < ARRAY_SIZE(ni_boards); i++) {
isapnp_dev = pnp_find_dev(NULL,
ISAPNP_VENDOR('N', 'I', 'C'),
ISAPNP_FUNCTION(ni_boards[i].
isapnp_id), NULL);
if (!isapnp_dev || !isapnp_dev->card)
continue;
if (pnp_device_attach(isapnp_dev) < 0)
continue;
if (pnp_activate_dev(isapnp_dev) < 0) {
pnp_device_detach(isapnp_dev);
return -EAGAIN;
}
if (!pnp_port_valid(isapnp_dev, 0) ||
!pnp_irq_valid(isapnp_dev, 0)) {
pnp_device_detach(isapnp_dev);
return -ENOMEM;
}
break;
}
if (i == ARRAY_SIZE(ni_boards))
return -ENODEV;
*dev = isapnp_dev;
return 0;
}
static const struct ni_board_struct *ni_atmio_probe(struct comedi_device *dev)
{
int device_id = ni_read_eeprom(dev, 511);
int i;
for (i = 0; i < ARRAY_SIZE(ni_boards); i++) {
const struct ni_board_struct *board = &ni_boards[i];
if (board->device_id == device_id)
return board;
}
if (device_id == 255)
dev_err(dev->class_dev, "can't find board\n");
else if (device_id == 0)
dev_err(dev->class_dev,
"EEPROM read error (?) or device not found\n");
else
dev_err(dev->class_dev,
"unknown device ID %d -- contact author\n", device_id);
return NULL;
}
static int ni_atmio_attach(struct comedi_device *dev,
struct comedi_devconfig *it)
{
const struct ni_board_struct *board;
struct pnp_dev *isapnp_dev;
int ret;
unsigned long iobase;
unsigned int irq;
ret = ni_alloc_private(dev);
if (ret)
return ret;
iobase = it->options[0];
irq = it->options[1];
isapnp_dev = NULL;
if (iobase == 0) {
ret = ni_isapnp_find_board(&isapnp_dev);
if (ret < 0)
return ret;
iobase = pnp_port_start(isapnp_dev, 0);
irq = pnp_irq(isapnp_dev, 0);
comedi_set_hw_dev(dev, &isapnp_dev->dev);
}
ret = comedi_request_region(dev, iobase, 0x20);
if (ret)
return ret;
board = ni_atmio_probe(dev);
if (!board)
return -ENODEV;
dev->board_ptr = board;
dev->board_name = board->name;
/* irq stuff */
if (irq != 0) {
if (irq > 15 || ni_irqpin[irq] == -1)
return -EINVAL;
ret = request_irq(irq, ni_E_interrupt, 0,
dev->board_name, dev);
if (ret < 0)
return -EINVAL;
dev->irq = irq;
}
/* generic E series stuff in ni_mio_common.c */
ret = ni_E_init(dev, ni_irqpin[dev->irq], 0);
if (ret < 0)
return ret;
return 0;
}
static void ni_atmio_detach(struct comedi_device *dev)
{
struct pnp_dev *isapnp_dev;
mio_common_detach(dev);
comedi_legacy_detach(dev);
isapnp_dev = dev->hw_dev ? to_pnp_dev(dev->hw_dev) : NULL;
if (isapnp_dev)
pnp_device_detach(isapnp_dev);
}
static struct comedi_driver ni_atmio_driver = {
.driver_name = "ni_atmio",
.module = THIS_MODULE,
.attach = ni_atmio_attach,
.detach = ni_atmio_detach,
};
module_comedi_driver(ni_atmio_driver);
| gpl-2.0 |
simex31/BC_Kernel_LP_STOCK_D802 | drivers/media/platform/msm/camera_v2/sensor/csiphy/msm_csiphy.c | 716 | 22198 | /* Copyright (c) 2011-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/module.h>
#include <linux/ratelimit.h>
#include <linux/irqreturn.h>
#include <mach/vreg.h>
#include "msm_csiphy.h"
#include "msm_sd.h"
#include "msm_csiphy_hwreg.h"
#include "msm_camera_io_util.h"
#define DBG_CSIPHY 0
#define V4L2_IDENT_CSIPHY 50003
#define CSIPHY_VERSION_V22 0x01
#define CSIPHY_VERSION_V20 0x00
#define CSIPHY_VERSION_V30 0x10
#define MSM_CSIPHY_DRV_NAME "msm_csiphy"
#undef CDBG
#ifdef CONFIG_MSMB_CAMERA_DEBUG
#define CDBG(fmt, args...) pr_err(fmt, ##args)
#else
#define CDBG(fmt, args...) do { } while (0)
#endif
static int msm_csiphy_lane_config(struct csiphy_device *csiphy_dev,
struct msm_camera_csiphy_params *csiphy_params)
{
int rc = 0;
int j = 0;
uint32_t val = 0;
uint8_t lane_cnt = 0;
uint16_t lane_mask = 0;
void __iomem *csiphybase;
uint8_t csiphy_id = csiphy_dev->pdev->id;
csiphybase = csiphy_dev->base;
if (!csiphybase) {
pr_err("%s: csiphybase NULL\n", __func__);
return -EINVAL;
}
csiphy_dev->lane_mask[csiphy_id] |= csiphy_params->lane_mask;
lane_mask = csiphy_dev->lane_mask[csiphy_id];
lane_cnt = csiphy_params->lane_cnt;
if (csiphy_params->lane_cnt < 1 || csiphy_params->lane_cnt > 4) {
pr_err("%s: unsupported lane cnt %d\n",
__func__, csiphy_params->lane_cnt);
return rc;
}
CDBG("%s csiphy_params, mask = %x cnt = %d settle cnt = %x csid %d\n",
__func__,
csiphy_params->lane_mask,
csiphy_params->lane_cnt,
csiphy_params->settle_cnt,
csiphy_params->csid_core);
if (csiphy_dev->hw_version >= CSIPHY_VERSION_V30) {
val = msm_camera_io_r(csiphy_dev->clk_mux_base);
if (csiphy_params->combo_mode &&
(csiphy_params->lane_mask & 0x18)) {
val &= ~0xf0;
val |= csiphy_params->csid_core << 4;
} else {
val &= ~0xf;
val |= csiphy_params->csid_core;
}
msm_camera_io_w(val, csiphy_dev->clk_mux_base);
CDBG("%s clk mux addr %p val 0x%x\n", __func__,
csiphy_dev->clk_mux_base, val);
mb();
}
msm_camera_io_w(0x1, csiphybase + MIPI_CSIPHY_GLBL_T_INIT_CFG0_ADDR);
msm_camera_io_w(0x1, csiphybase + MIPI_CSIPHY_T_WAKEUP_CFG0_ADDR);
if (csiphy_dev->hw_version < CSIPHY_VERSION_V30) {
val = 0x3;
msm_camera_io_w((lane_mask << 2) | val,
csiphybase + MIPI_CSIPHY_GLBL_PWR_CFG_ADDR);
msm_camera_io_w(0x10, csiphybase + MIPI_CSIPHY_LNCK_CFG2_ADDR);
msm_camera_io_w(csiphy_params->settle_cnt,
csiphybase + MIPI_CSIPHY_LNCK_CFG3_ADDR);
msm_camera_io_w(0x24,
csiphybase + MIPI_CSIPHY_INTERRUPT_MASK0_ADDR);
msm_camera_io_w(0x24,
csiphybase + MIPI_CSIPHY_INTERRUPT_CLEAR0_ADDR);
} else {
val = 0x1;
msm_camera_io_w((lane_mask << 1) | val,
csiphybase + MIPI_CSIPHY_GLBL_PWR_CFG_ADDR);
msm_camera_io_w(csiphy_params->combo_mode <<
MIPI_CSIPHY_MODE_CONFIG_SHIFT,
csiphybase + MIPI_CSIPHY_GLBL_RESET_ADDR);
}
lane_mask &= 0x1f;
while (lane_mask & 0x1f) {
if (!(lane_mask & 0x1)) {
j++;
lane_mask >>= 1;
continue;
}
msm_camera_io_w(0x10,
csiphybase + MIPI_CSIPHY_LNn_CFG2_ADDR + 0x40*j);
msm_camera_io_w(csiphy_params->settle_cnt,
csiphybase + MIPI_CSIPHY_LNn_CFG3_ADDR + 0x40*j);
msm_camera_io_w(MIPI_CSIPHY_INTERRUPT_MASK_VAL, csiphybase +
MIPI_CSIPHY_INTERRUPT_MASK_ADDR + 0x4*j);
msm_camera_io_w(MIPI_CSIPHY_INTERRUPT_MASK_VAL, csiphybase +
MIPI_CSIPHY_INTERRUPT_CLEAR_ADDR + 0x4*j);
j++;
lane_mask >>= 1;
}
return rc;
}
static irqreturn_t msm_csiphy_irq(int irq_num, void *data)
{
uint32_t irq;
int i;
struct csiphy_device *csiphy_dev = data;
for (i = 0; i < 8; i++) {
irq = msm_camera_io_r(
csiphy_dev->base +
MIPI_CSIPHY_INTERRUPT_STATUS0_ADDR + 0x4*i);
msm_camera_io_w(irq,
csiphy_dev->base +
MIPI_CSIPHY_INTERRUPT_CLEAR0_ADDR + 0x4*i);
pr_err("%s MIPI_CSIPHY%d_INTERRUPT_STATUS%d = 0x%x\n",
__func__, csiphy_dev->pdev->id, i, irq);
msm_camera_io_w(0x1, csiphy_dev->base +
MIPI_CSIPHY_GLBL_IRQ_CMD_ADDR);
msm_camera_io_w(0x0, csiphy_dev->base +
MIPI_CSIPHY_GLBL_IRQ_CMD_ADDR);
msm_camera_io_w(0x0,
csiphy_dev->base +
MIPI_CSIPHY_INTERRUPT_CLEAR0_ADDR + 0x4*i);
}
return IRQ_HANDLED;
}
static void msm_csiphy_reset(struct csiphy_device *csiphy_dev)
{
msm_camera_io_w(0x1, csiphy_dev->base + MIPI_CSIPHY_GLBL_RESET_ADDR);
usleep_range(5000, 8000);
msm_camera_io_w(0x0, csiphy_dev->base + MIPI_CSIPHY_GLBL_RESET_ADDR);
}
static int msm_csiphy_subdev_g_chip_ident(struct v4l2_subdev *sd,
struct v4l2_dbg_chip_ident *chip)
{
BUG_ON(!chip);
chip->ident = V4L2_IDENT_CSIPHY;
chip->revision = 0;
return 0;
}
static struct msm_cam_clk_info csiphy_8960_clk_info[] = {
{"csiphy_timer_src_clk", 177780000},
{"csiphy_timer_clk", -1},
};
static struct msm_cam_clk_info csiphy_8610_clk_info[] = {
{"csiphy_timer_src_clk", 200000000},
{"csiphy_timer_clk", -1},
{"csi_ahb_clk", -1},
};
static struct msm_cam_clk_info csiphy_8974_clk_info[] = {
{"camss_top_ahb_clk", -1},
{"ispif_ahb_clk", -1},
{"csiphy_timer_src_clk", 200000000},
{"csiphy_timer_clk", -1},
};
#if DBG_CSIPHY
static int msm_csiphy_init(struct csiphy_device *csiphy_dev)
{
int rc = 0;
if (csiphy_dev == NULL) {
pr_err("%s: csiphy_dev NULL\n", __func__);
rc = -ENOMEM;
return rc;
}
CDBG("%s:%d called\n", __func__, __LINE__);
if (csiphy_dev->csiphy_state == CSIPHY_POWER_UP) {
pr_err("%s: csiphy invalid state %d\n", __func__,
csiphy_dev->csiphy_state);
rc = -EINVAL;
return rc;
}
CDBG("%s:%d called\n", __func__, __LINE__);
if (csiphy_dev->ref_count++) {
CDBG("%s csiphy refcount = %d\n", __func__,
csiphy_dev->ref_count);
return rc;
}
CDBG("%s:%d called\n", __func__, __LINE__);
csiphy_dev->base = ioremap(csiphy_dev->mem->start,
resource_size(csiphy_dev->mem));
if (!csiphy_dev->base) {
pr_err("%s: csiphy_dev->base NULL\n", __func__);
csiphy_dev->ref_count--;
rc = -ENOMEM;
return rc;
}
CDBG("%s:%d called\n", __func__, __LINE__);
if (CSIPHY_VERSION == CSIPHY_VERSION_V20) {
CDBG("%s:%d called\n", __func__, __LINE__);
rc = msm_cam_clk_enable(&csiphy_dev->pdev->dev,
csiphy_8960_clk_info, csiphy_dev->csiphy_clk,
ARRAY_SIZE(csiphy_8960_clk_info), 1);
} else if (CSIPHY_VERSION == CSIPHY_VERSION_V22) {
CDBG("%s:%d called\n", __func__, __LINE__);
rc = msm_cam_clk_enable(&csiphy_dev->pdev->dev,
csiphy_8610_clk_info, csiphy_dev->csiphy_clk,
ARRAY_SIZE(csiphy_8610_clk_info), 1);
} else if (CSIPHY_VERSION == CSIPHY_VERSION_V30) {
if (!csiphy_dev->clk_mux_mem || !csiphy_dev->clk_mux_io) {
pr_err("%s clk mux mem %p io %p\n", __func__,
csiphy_dev->clk_mux_mem,
csiphy_dev->clk_mux_io);
rc = -ENOMEM;
return rc;
}
csiphy_dev->clk_mux_base = ioremap(
csiphy_dev->clk_mux_mem->start,
resource_size(csiphy_dev->clk_mux_mem));
if (!csiphy_dev->clk_mux_base) {
pr_err("%s: ERROR %d\n", __func__, __LINE__);
rc = -ENOMEM;
return rc;
}
CDBG("%s:%d called\n", __func__, __LINE__);
rc = msm_cam_clk_enable(&csiphy_dev->pdev->dev,
csiphy_8974_clk_info, csiphy_dev->csiphy_clk,
ARRAY_SIZE(csiphy_8974_clk_info), 1);
} else {
pr_err("%s: ERROR Invalid CSIPHY Version %d",
__func__, __LINE__);
rc = -EINVAL;
return rc;
}
CDBG("%s:%d called\n", __func__, __LINE__);
if (rc < 0) {
pr_err("%s: csiphy clk enable failed\n", __func__);
csiphy_dev->ref_count--;
iounmap(csiphy_dev->base);
csiphy_dev->base = NULL;
return rc;
}
CDBG("%s:%d called\n", __func__, __LINE__);
enable_irq(csiphy_dev->irq->start);
msm_csiphy_reset(csiphy_dev);
CDBG("%s:%d called\n", __func__, __LINE__);
if (CSIPHY_VERSION == CSIPHY_VERSION_V30)
csiphy_dev->hw_version =
msm_camera_io_r(csiphy_dev->base +
MIPI_CSIPHY_HW_VERSION_ADDR);
else
csiphy_dev->hw_version = CSIPHY_VERSION;
CDBG("%s:%d called csiphy_dev->hw_version %x\n", __func__, __LINE__,
csiphy_dev->hw_version);
csiphy_dev->csiphy_state = CSIPHY_POWER_UP;
return 0;
}
#else
static int msm_csiphy_init(struct csiphy_device *csiphy_dev)
{
int rc = 0;
if (csiphy_dev == NULL) {
pr_err("%s: csiphy_dev NULL\n", __func__);
rc = -ENOMEM;
return rc;
}
CDBG("%s:%d called\n", __func__, __LINE__);
if (csiphy_dev->csiphy_state == CSIPHY_POWER_UP) {
pr_err("%s: csiphy invalid state %d\n", __func__,
csiphy_dev->csiphy_state);
rc = -EINVAL;
return rc;
}
CDBG("%s:%d called\n", __func__, __LINE__);
if (csiphy_dev->ref_count++) {
CDBG("%s csiphy refcount = %d\n", __func__,
csiphy_dev->ref_count);
return rc;
}
CDBG("%s:%d called\n", __func__, __LINE__);
csiphy_dev->base = ioremap(csiphy_dev->mem->start,
resource_size(csiphy_dev->mem));
if (!csiphy_dev->base) {
pr_err("%s: csiphy_dev->base NULL\n", __func__);
csiphy_dev->ref_count--;
rc = -ENOMEM;
return rc;
}
CDBG("%s:%d called\n", __func__, __LINE__);
if (CSIPHY_VERSION == CSIPHY_VERSION_V20) {
CDBG("%s:%d called\n", __func__, __LINE__);
rc = msm_cam_clk_enable(&csiphy_dev->pdev->dev,
csiphy_8960_clk_info, csiphy_dev->csiphy_clk,
ARRAY_SIZE(csiphy_8960_clk_info), 1);
} else if (CSIPHY_VERSION == CSIPHY_VERSION_V22) {
CDBG("%s:%d called\n", __func__, __LINE__);
rc = msm_cam_clk_enable(&csiphy_dev->pdev->dev,
csiphy_8610_clk_info, csiphy_dev->csiphy_clk,
ARRAY_SIZE(csiphy_8610_clk_info), 1);
} else if (CSIPHY_VERSION == CSIPHY_VERSION_V30) {
if (!csiphy_dev->clk_mux_mem || !csiphy_dev->clk_mux_io) {
pr_err("%s clk mux mem %p io %p\n", __func__,
csiphy_dev->clk_mux_mem,
csiphy_dev->clk_mux_io);
rc = -ENOMEM;
return rc;
}
csiphy_dev->clk_mux_base = ioremap(
csiphy_dev->clk_mux_mem->start,
resource_size(csiphy_dev->clk_mux_mem));
if (!csiphy_dev->clk_mux_base) {
pr_err("%s: ERROR %d\n", __func__, __LINE__);
rc = -ENOMEM;
return rc;
}
CDBG("%s:%d called\n", __func__, __LINE__);
rc = msm_cam_clk_enable(&csiphy_dev->pdev->dev,
csiphy_8974_clk_info, csiphy_dev->csiphy_clk,
ARRAY_SIZE(csiphy_8974_clk_info), 1);
} else {
pr_err("%s: ERROR Invalid CSIPHY Version %d",
__func__, __LINE__);
rc = -EINVAL;
return rc;
}
CDBG("%s:%d called\n", __func__, __LINE__);
if (rc < 0) {
pr_err("%s: csiphy clk enable failed\n", __func__);
csiphy_dev->ref_count--;
iounmap(csiphy_dev->base);
csiphy_dev->base = NULL;
return rc;
}
CDBG("%s:%d called\n", __func__, __LINE__);
msm_csiphy_reset(csiphy_dev);
CDBG("%s:%d called\n", __func__, __LINE__);
if (CSIPHY_VERSION == CSIPHY_VERSION_V30)
csiphy_dev->hw_version =
msm_camera_io_r(csiphy_dev->base +
MIPI_CSIPHY_HW_VERSION_ADDR);
else
csiphy_dev->hw_version = CSIPHY_VERSION;
CDBG("%s:%d called csiphy_dev->hw_version %x\n", __func__, __LINE__,
csiphy_dev->hw_version);
csiphy_dev->csiphy_state = CSIPHY_POWER_UP;
return 0;
}
#endif
#if DBG_CSIPHY
static int msm_csiphy_release(struct csiphy_device *csiphy_dev, void *arg)
{
int i = 0;
struct msm_camera_csi_lane_params *csi_lane_params;
uint16_t csi_lane_mask;
csi_lane_params = (struct msm_camera_csi_lane_params *)arg;
if (!csiphy_dev || !csiphy_dev->ref_count) {
pr_err("%s csiphy dev NULL / ref_count ZERO\n", __func__);
return 0;
}
if (csiphy_dev->csiphy_state != CSIPHY_POWER_UP) {
pr_err("%s: csiphy invalid state %d\n", __func__,
csiphy_dev->csiphy_state);
return -EINVAL;
}
if (csiphy_dev->hw_version < CSIPHY_VERSION_V30) {
csiphy_dev->lane_mask[csiphy_dev->pdev->id] = 0;
for (i = 0; i < 4; i++)
msm_camera_io_w(0x0, csiphy_dev->base +
MIPI_CSIPHY_LNn_CFG2_ADDR + 0x40*i);
} else {
if (!csi_lane_params) {
pr_err("%s:%d failed: csi_lane_params %p\n", __func__,
__LINE__, csi_lane_params);
return -EINVAL;
}
csi_lane_mask = (csi_lane_params->csi_lane_mask & 0x1F);
CDBG("%s csiphy_params, lane assign %x mask = %x\n",
__func__,
csi_lane_params->csi_lane_assign,
csi_lane_params->csi_lane_mask);
if (!csi_lane_mask)
csi_lane_mask = 0x1f;
csiphy_dev->lane_mask[csiphy_dev->pdev->id] &=
~(csi_lane_mask);
i = 0;
while (csi_lane_mask) {
if (csi_lane_mask & 0x1) {
msm_camera_io_w(0x0, csiphy_dev->base +
MIPI_CSIPHY_LNn_CFG2_ADDR + 0x40*i);
}
csi_lane_mask >>= 1;
i++;
}
}
if (--csiphy_dev->ref_count) {
CDBG("%s csiphy refcount = %d\n", __func__,
csiphy_dev->ref_count);
return 0;
}
msm_camera_io_w(0x0, csiphy_dev->base + MIPI_CSIPHY_LNCK_CFG2_ADDR);
msm_camera_io_w(0x0, csiphy_dev->base + MIPI_CSIPHY_GLBL_PWR_CFG_ADDR);
disable_irq(csiphy_dev->irq->start);
if (CSIPHY_VERSION == CSIPHY_VERSION_V20) {
msm_cam_clk_enable(&csiphy_dev->pdev->dev,
csiphy_8960_clk_info, csiphy_dev->csiphy_clk,
ARRAY_SIZE(csiphy_8960_clk_info), 0);
} else if (CSIPHY_VERSION == CSIPHY_VERSION_V22) {
msm_cam_clk_enable(&csiphy_dev->pdev->dev,
csiphy_8610_clk_info, csiphy_dev->csiphy_clk,
ARRAY_SIZE(csiphy_8610_clk_info), 0);
} else if (CSIPHY_VERSION == CSIPHY_VERSION_V30) {
msm_cam_clk_enable(&csiphy_dev->pdev->dev,
csiphy_8974_clk_info, csiphy_dev->csiphy_clk,
ARRAY_SIZE(csiphy_8974_clk_info), 0);
iounmap(csiphy_dev->clk_mux_base);
}
iounmap(csiphy_dev->base);
csiphy_dev->base = NULL;
csiphy_dev->csiphy_state = CSIPHY_POWER_DOWN;
return 0;
}
#else
static int msm_csiphy_release(struct csiphy_device *csiphy_dev, void *arg)
{
int i = 0;
struct msm_camera_csi_lane_params *csi_lane_params;
uint16_t csi_lane_mask;
csi_lane_params = (struct msm_camera_csi_lane_params *)arg;
if (!csiphy_dev || !csiphy_dev->ref_count) {
pr_err("%s csiphy dev NULL / ref_count ZERO\n", __func__);
return 0;
}
if (csiphy_dev->csiphy_state != CSIPHY_POWER_UP) {
pr_err("%s: csiphy invalid state %d\n", __func__,
csiphy_dev->csiphy_state);
return -EINVAL;
}
if (csiphy_dev->hw_version < CSIPHY_VERSION_V30) {
csiphy_dev->lane_mask[csiphy_dev->pdev->id] = 0;
for (i = 0; i < 4; i++)
msm_camera_io_w(0x0, csiphy_dev->base +
MIPI_CSIPHY_LNn_CFG2_ADDR + 0x40*i);
} else {
if (!csi_lane_params) {
pr_err("%s:%d failed: csi_lane_params %p\n", __func__,
__LINE__, csi_lane_params);
return -EINVAL;
}
csi_lane_mask = (csi_lane_params->csi_lane_mask & 0x1F);
CDBG("%s csiphy_params, lane assign %x mask = %x\n",
__func__,
csi_lane_params->csi_lane_assign,
csi_lane_params->csi_lane_mask);
if (!csi_lane_mask)
csi_lane_mask = 0x1f;
csiphy_dev->lane_mask[csiphy_dev->pdev->id] &=
~(csi_lane_mask);
i = 0;
while (csi_lane_mask) {
if (csi_lane_mask & 0x1) {
msm_camera_io_w(0x0, csiphy_dev->base +
MIPI_CSIPHY_LNn_CFG2_ADDR + 0x40*i);
}
csi_lane_mask >>= 1;
i++;
}
}
if (--csiphy_dev->ref_count) {
CDBG("%s csiphy refcount = %d\n", __func__,
csiphy_dev->ref_count);
return 0;
}
msm_camera_io_w(0x0, csiphy_dev->base + MIPI_CSIPHY_LNCK_CFG2_ADDR);
msm_camera_io_w(0x0, csiphy_dev->base + MIPI_CSIPHY_GLBL_PWR_CFG_ADDR);
if (CSIPHY_VERSION == CSIPHY_VERSION_V20) {
msm_cam_clk_enable(&csiphy_dev->pdev->dev,
csiphy_8960_clk_info, csiphy_dev->csiphy_clk,
ARRAY_SIZE(csiphy_8960_clk_info), 0);
} else if (CSIPHY_VERSION == CSIPHY_VERSION_V22) {
msm_cam_clk_enable(&csiphy_dev->pdev->dev,
csiphy_8610_clk_info, csiphy_dev->csiphy_clk,
ARRAY_SIZE(csiphy_8610_clk_info), 0);
} else if (CSIPHY_VERSION == CSIPHY_VERSION_V30) {
msm_cam_clk_enable(&csiphy_dev->pdev->dev,
csiphy_8974_clk_info, csiphy_dev->csiphy_clk,
ARRAY_SIZE(csiphy_8974_clk_info), 0);
iounmap(csiphy_dev->clk_mux_base);
}
iounmap(csiphy_dev->base);
csiphy_dev->base = NULL;
csiphy_dev->csiphy_state = CSIPHY_POWER_DOWN;
return 0;
}
#endif
static long msm_csiphy_cmd(struct csiphy_device *csiphy_dev, void *arg)
{
int rc = 0;
struct csiphy_cfg_data *cdata = (struct csiphy_cfg_data *)arg;
struct msm_camera_csiphy_params csiphy_params;
struct msm_camera_csi_lane_params csi_lane_params;
if (!csiphy_dev || !cdata) {
pr_err("%s: csiphy_dev NULL\n", __func__);
return -EINVAL;
}
switch (cdata->cfgtype) {
case CSIPHY_INIT:
rc = msm_csiphy_init(csiphy_dev);
break;
case CSIPHY_CFG:
if (copy_from_user(&csiphy_params,
(void *)cdata->cfg.csiphy_params,
sizeof(struct msm_camera_csiphy_params))) {
pr_err("%s: %d failed\n", __func__, __LINE__);
rc = -EFAULT;
break;
}
rc = msm_csiphy_lane_config(csiphy_dev, &csiphy_params);
break;
case CSIPHY_RELEASE:
if (copy_from_user(&csi_lane_params,
(void *)cdata->cfg.csi_lane_params,
sizeof(struct msm_camera_csi_lane_params))) {
pr_err("%s: %d failed\n", __func__, __LINE__);
rc = -EFAULT;
break;
}
rc = msm_csiphy_release(csiphy_dev, &csi_lane_params);
break;
default:
pr_err_ratelimited("%s: %d failed\n", __func__, __LINE__);
rc = -ENOIOCTLCMD;
break;
}
return rc;
}
static int32_t msm_csiphy_get_subdev_id(struct csiphy_device *csiphy_dev,
void *arg)
{
uint32_t *subdev_id = (uint32_t *)arg;
if (!subdev_id) {
pr_err("%s:%d failed\n", __func__, __LINE__);
return -EINVAL;
}
*subdev_id = csiphy_dev->pdev->id;
pr_debug("%s:%d subdev_id %d\n", __func__, __LINE__, *subdev_id);
return 0;
}
static long msm_csiphy_subdev_ioctl(struct v4l2_subdev *sd,
unsigned int cmd, void *arg)
{
int rc = -ENOIOCTLCMD;
struct csiphy_device *csiphy_dev = v4l2_get_subdevdata(sd);
CDBG("%s:%d id %d\n", __func__, __LINE__, csiphy_dev->pdev->id);
mutex_lock(&csiphy_dev->mutex);
switch (cmd) {
case VIDIOC_MSM_SENSOR_GET_SUBDEV_ID:
rc = msm_csiphy_get_subdev_id(csiphy_dev, arg);
break;
case VIDIOC_MSM_CSIPHY_IO_CFG:
rc = msm_csiphy_cmd(csiphy_dev, arg);
break;
case VIDIOC_MSM_CSIPHY_RELEASE:
case MSM_SD_SHUTDOWN:
rc = msm_csiphy_release(csiphy_dev, arg);
break;
default:
pr_err("%s: command not found\n", __func__);
}
mutex_unlock(&csiphy_dev->mutex);
CDBG("%s:%d\n", __func__, __LINE__);
return rc;
}
static const struct v4l2_subdev_internal_ops msm_csiphy_internal_ops;
static struct v4l2_subdev_core_ops msm_csiphy_subdev_core_ops = {
.g_chip_ident = &msm_csiphy_subdev_g_chip_ident,
.ioctl = &msm_csiphy_subdev_ioctl,
};
static const struct v4l2_subdev_ops msm_csiphy_subdev_ops = {
.core = &msm_csiphy_subdev_core_ops,
};
static int __devinit csiphy_probe(struct platform_device *pdev)
{
struct csiphy_device *new_csiphy_dev;
int rc = 0;
new_csiphy_dev = kzalloc(sizeof(struct csiphy_device), GFP_KERNEL);
if (!new_csiphy_dev) {
pr_err("%s: no enough memory\n", __func__);
return -ENOMEM;
}
v4l2_subdev_init(&new_csiphy_dev->msm_sd.sd, &msm_csiphy_subdev_ops);
v4l2_set_subdevdata(&new_csiphy_dev->msm_sd.sd, new_csiphy_dev);
platform_set_drvdata(pdev, &new_csiphy_dev->msm_sd.sd);
mutex_init(&new_csiphy_dev->mutex);
if (pdev->dev.of_node)
of_property_read_u32((&pdev->dev)->of_node,
"cell-index", &pdev->id);
CDBG("%s: device id = %d\n", __func__, pdev->id);
new_csiphy_dev->mem = platform_get_resource_byname(pdev,
IORESOURCE_MEM, "csiphy");
if (!new_csiphy_dev->mem) {
pr_err("%s: no mem resource?\n", __func__);
rc = -ENODEV;
goto csiphy_no_resource;
}
new_csiphy_dev->irq = platform_get_resource_byname(pdev,
IORESOURCE_IRQ, "csiphy");
if (!new_csiphy_dev->irq) {
pr_err("%s: no irq resource?\n", __func__);
rc = -ENODEV;
goto csiphy_no_resource;
}
new_csiphy_dev->io = request_mem_region(new_csiphy_dev->mem->start,
resource_size(new_csiphy_dev->mem), pdev->name);
if (!new_csiphy_dev->io) {
pr_err("%s: no valid mem region\n", __func__);
rc = -EBUSY;
goto csiphy_no_resource;
}
rc = request_irq(new_csiphy_dev->irq->start, msm_csiphy_irq,
IRQF_TRIGGER_RISING, "csiphy", new_csiphy_dev);
if (rc < 0) {
release_mem_region(new_csiphy_dev->mem->start,
resource_size(new_csiphy_dev->mem));
pr_err("%s: irq request fail\n", __func__);
rc = -EBUSY;
goto csiphy_no_resource;
}
disable_irq(new_csiphy_dev->irq->start);
new_csiphy_dev->clk_mux_mem = platform_get_resource_byname(pdev,
IORESOURCE_MEM, "csiphy_clk_mux");
if (new_csiphy_dev->clk_mux_mem) {
new_csiphy_dev->clk_mux_io = request_mem_region(
new_csiphy_dev->clk_mux_mem->start,
resource_size(new_csiphy_dev->clk_mux_mem),
new_csiphy_dev->clk_mux_mem->name);
if (!new_csiphy_dev->clk_mux_io)
pr_err("%s: ERROR %d\n", __func__, __LINE__);
}
new_csiphy_dev->pdev = pdev;
new_csiphy_dev->msm_sd.sd.internal_ops = &msm_csiphy_internal_ops;
new_csiphy_dev->msm_sd.sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
snprintf(new_csiphy_dev->msm_sd.sd.name,
ARRAY_SIZE(new_csiphy_dev->msm_sd.sd.name), "msm_csiphy");
media_entity_init(&new_csiphy_dev->msm_sd.sd.entity, 0, NULL, 0);
new_csiphy_dev->msm_sd.sd.entity.type = MEDIA_ENT_T_V4L2_SUBDEV;
new_csiphy_dev->msm_sd.sd.entity.group_id = MSM_CAMERA_SUBDEV_CSIPHY;
new_csiphy_dev->msm_sd.close_seq = MSM_SD_CLOSE_2ND_CATEGORY | 0x4;
msm_sd_register(&new_csiphy_dev->msm_sd);
new_csiphy_dev->csiphy_state = CSIPHY_POWER_DOWN;
return 0;
csiphy_no_resource:
mutex_destroy(&new_csiphy_dev->mutex);
kfree(new_csiphy_dev);
return 0;
}
static const struct of_device_id msm_csiphy_dt_match[] = {
{.compatible = "qcom,csiphy"},
{}
};
MODULE_DEVICE_TABLE(of, msm_csiphy_dt_match);
static struct platform_driver csiphy_driver = {
.probe = csiphy_probe,
.driver = {
.name = MSM_CSIPHY_DRV_NAME,
.owner = THIS_MODULE,
.of_match_table = msm_csiphy_dt_match,
},
};
static int __init msm_csiphy_init_module(void)
{
return platform_driver_register(&csiphy_driver);
}
static void __exit msm_csiphy_exit_module(void)
{
platform_driver_unregister(&csiphy_driver);
}
module_init(msm_csiphy_init_module);
module_exit(msm_csiphy_exit_module);
MODULE_DESCRIPTION("MSM CSIPHY driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
hazard209/Charge_Kernel | sound/soc/omap/osk5912.c | 972 | 5543 | /*
* osk5912.c -- SoC audio for OSK 5912
*
* Copyright (C) 2008 Mistral Solutions
*
* Contact: Arun KS <arunks@mistralsolutions.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <linux/clk.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <asm/mach-types.h>
#include <mach/hardware.h>
#include <linux/gpio.h>
#include <plat/mcbsp.h>
#include "omap-mcbsp.h"
#include "omap-pcm.h"
#include "../codecs/tlv320aic23.h"
#define CODEC_CLOCK 12000000
static struct clk *tlv320aic23_mclk;
static int osk_startup(struct snd_pcm_substream *substream)
{
return clk_enable(tlv320aic23_mclk);
}
static void osk_shutdown(struct snd_pcm_substream *substream)
{
clk_disable(tlv320aic23_mclk);
}
static int osk_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->dai->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->dai->cpu_dai;
int err;
/* Set codec DAI configuration */
err = snd_soc_dai_set_fmt(codec_dai,
SND_SOC_DAIFMT_DSP_B |
SND_SOC_DAIFMT_NB_NF |
SND_SOC_DAIFMT_CBM_CFM);
if (err < 0) {
printk(KERN_ERR "can't set codec DAI configuration\n");
return err;
}
/* Set cpu DAI configuration */
err = snd_soc_dai_set_fmt(cpu_dai,
SND_SOC_DAIFMT_DSP_B |
SND_SOC_DAIFMT_NB_NF |
SND_SOC_DAIFMT_CBM_CFM);
if (err < 0) {
printk(KERN_ERR "can't set cpu DAI configuration\n");
return err;
}
/* Set the codec system clock for DAC and ADC */
err =
snd_soc_dai_set_sysclk(codec_dai, 0, CODEC_CLOCK, SND_SOC_CLOCK_IN);
if (err < 0) {
printk(KERN_ERR "can't set codec system clock\n");
return err;
}
return err;
}
static struct snd_soc_ops osk_ops = {
.startup = osk_startup,
.hw_params = osk_hw_params,
.shutdown = osk_shutdown,
};
static const struct snd_soc_dapm_widget tlv320aic23_dapm_widgets[] = {
SND_SOC_DAPM_HP("Headphone Jack", NULL),
SND_SOC_DAPM_LINE("Line In", NULL),
SND_SOC_DAPM_MIC("Mic Jack", NULL),
};
static const struct snd_soc_dapm_route audio_map[] = {
{"Headphone Jack", NULL, "LHPOUT"},
{"Headphone Jack", NULL, "RHPOUT"},
{"LLINEIN", NULL, "Line In"},
{"RLINEIN", NULL, "Line In"},
{"MICIN", NULL, "Mic Jack"},
};
static int osk_tlv320aic23_init(struct snd_soc_codec *codec)
{
/* Add osk5912 specific widgets */
snd_soc_dapm_new_controls(codec, tlv320aic23_dapm_widgets,
ARRAY_SIZE(tlv320aic23_dapm_widgets));
/* Set up osk5912 specific audio path audio_map */
snd_soc_dapm_add_routes(codec, audio_map, ARRAY_SIZE(audio_map));
snd_soc_dapm_enable_pin(codec, "Headphone Jack");
snd_soc_dapm_enable_pin(codec, "Line In");
snd_soc_dapm_enable_pin(codec, "Mic Jack");
snd_soc_dapm_sync(codec);
return 0;
}
/* Digital audio interface glue - connects codec <--> CPU */
static struct snd_soc_dai_link osk_dai = {
.name = "TLV320AIC23",
.stream_name = "AIC23",
.cpu_dai = &omap_mcbsp_dai[0],
.codec_dai = &tlv320aic23_dai,
.init = osk_tlv320aic23_init,
.ops = &osk_ops,
};
/* Audio machine driver */
static struct snd_soc_card snd_soc_card_osk = {
.name = "OSK5912",
.platform = &omap_soc_platform,
.dai_link = &osk_dai,
.num_links = 1,
};
/* Audio subsystem */
static struct snd_soc_device osk_snd_devdata = {
.card = &snd_soc_card_osk,
.codec_dev = &soc_codec_dev_tlv320aic23,
};
static struct platform_device *osk_snd_device;
static int __init osk_soc_init(void)
{
int err;
u32 curRate;
struct device *dev;
if (!(machine_is_omap_osk()))
return -ENODEV;
osk_snd_device = platform_device_alloc("soc-audio", -1);
if (!osk_snd_device)
return -ENOMEM;
platform_set_drvdata(osk_snd_device, &osk_snd_devdata);
osk_snd_devdata.dev = &osk_snd_device->dev;
*(unsigned int *)osk_dai.cpu_dai->private_data = 0; /* McBSP1 */
err = platform_device_add(osk_snd_device);
if (err)
goto err1;
dev = &osk_snd_device->dev;
tlv320aic23_mclk = clk_get(dev, "mclk");
if (IS_ERR(tlv320aic23_mclk)) {
printk(KERN_ERR "Could not get mclk clock\n");
return -ENODEV;
}
/*
* Configure 12 MHz output on MCLK.
*/
curRate = (uint) clk_get_rate(tlv320aic23_mclk);
if (curRate != CODEC_CLOCK) {
if (clk_set_rate(tlv320aic23_mclk, CODEC_CLOCK)) {
printk(KERN_ERR "Cannot set MCLK for AIC23 CODEC\n");
err = -ECANCELED;
goto err1;
}
}
printk(KERN_INFO "MCLK = %d [%d]\n",
(uint) clk_get_rate(tlv320aic23_mclk), CODEC_CLOCK);
return 0;
err1:
clk_put(tlv320aic23_mclk);
platform_device_del(osk_snd_device);
platform_device_put(osk_snd_device);
return err;
}
static void __exit osk_soc_exit(void)
{
platform_device_unregister(osk_snd_device);
}
module_init(osk_soc_init);
module_exit(osk_soc_exit);
MODULE_AUTHOR("Arun KS <arunks@mistralsolutions.com>");
MODULE_DESCRIPTION("ALSA SoC OSK 5912");
MODULE_LICENSE("GPL");
| gpl-2.0 |
tobetter/android_hardware_backports | drivers/net/wireless/zd1211rw/zd_mac.c | 1228 | 41342 | /* ZD1211 USB-WLAN driver for Linux
*
* Copyright (C) 2005-2007 Ulrich Kunitz <kune@deine-taler.de>
* Copyright (C) 2006-2007 Daniel Drake <dsd@gentoo.org>
* Copyright (C) 2006-2007 Michael Wu <flamingice@sourmilk.net>
* Copyright (C) 2007-2008 Luis R. Rodriguez <mcgrof@winlab.rutgers.edu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/jiffies.h>
#include <net/ieee80211_radiotap.h>
#include "zd_def.h"
#include "zd_chip.h"
#include "zd_mac.h"
#include "zd_rf.h"
struct zd_reg_alpha2_map {
u32 reg;
char alpha2[2];
};
static struct zd_reg_alpha2_map reg_alpha2_map[] = {
{ ZD_REGDOMAIN_FCC, "US" },
{ ZD_REGDOMAIN_IC, "CA" },
{ ZD_REGDOMAIN_ETSI, "DE" }, /* Generic ETSI, use most restrictive */
{ ZD_REGDOMAIN_JAPAN, "JP" },
{ ZD_REGDOMAIN_JAPAN_2, "JP" },
{ ZD_REGDOMAIN_JAPAN_3, "JP" },
{ ZD_REGDOMAIN_SPAIN, "ES" },
{ ZD_REGDOMAIN_FRANCE, "FR" },
};
/* This table contains the hardware specific values for the modulation rates. */
static const struct ieee80211_rate zd_rates[] = {
{ .bitrate = 10,
.hw_value = ZD_CCK_RATE_1M, },
{ .bitrate = 20,
.hw_value = ZD_CCK_RATE_2M,
.hw_value_short = ZD_CCK_RATE_2M | ZD_CCK_PREA_SHORT,
.flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 55,
.hw_value = ZD_CCK_RATE_5_5M,
.hw_value_short = ZD_CCK_RATE_5_5M | ZD_CCK_PREA_SHORT,
.flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 110,
.hw_value = ZD_CCK_RATE_11M,
.hw_value_short = ZD_CCK_RATE_11M | ZD_CCK_PREA_SHORT,
.flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 60,
.hw_value = ZD_OFDM_RATE_6M,
.flags = 0 },
{ .bitrate = 90,
.hw_value = ZD_OFDM_RATE_9M,
.flags = 0 },
{ .bitrate = 120,
.hw_value = ZD_OFDM_RATE_12M,
.flags = 0 },
{ .bitrate = 180,
.hw_value = ZD_OFDM_RATE_18M,
.flags = 0 },
{ .bitrate = 240,
.hw_value = ZD_OFDM_RATE_24M,
.flags = 0 },
{ .bitrate = 360,
.hw_value = ZD_OFDM_RATE_36M,
.flags = 0 },
{ .bitrate = 480,
.hw_value = ZD_OFDM_RATE_48M,
.flags = 0 },
{ .bitrate = 540,
.hw_value = ZD_OFDM_RATE_54M,
.flags = 0 },
};
/*
* Zydas retry rates table. Each line is listed in the same order as
* in zd_rates[] and contains all the rate used when a packet is sent
* starting with a given rates. Let's consider an example :
*
* "11 Mbits : 4, 3, 2, 1, 0" means :
* - packet is sent using 4 different rates
* - 1st rate is index 3 (ie 11 Mbits)
* - 2nd rate is index 2 (ie 5.5 Mbits)
* - 3rd rate is index 1 (ie 2 Mbits)
* - 4th rate is index 0 (ie 1 Mbits)
*/
static const struct tx_retry_rate zd_retry_rates[] = {
{ /* 1 Mbits */ 1, { 0 }},
{ /* 2 Mbits */ 2, { 1, 0 }},
{ /* 5.5 Mbits */ 3, { 2, 1, 0 }},
{ /* 11 Mbits */ 4, { 3, 2, 1, 0 }},
{ /* 6 Mbits */ 5, { 4, 3, 2, 1, 0 }},
{ /* 9 Mbits */ 6, { 5, 4, 3, 2, 1, 0}},
{ /* 12 Mbits */ 5, { 6, 3, 2, 1, 0 }},
{ /* 18 Mbits */ 6, { 7, 6, 3, 2, 1, 0 }},
{ /* 24 Mbits */ 6, { 8, 6, 3, 2, 1, 0 }},
{ /* 36 Mbits */ 7, { 9, 8, 6, 3, 2, 1, 0 }},
{ /* 48 Mbits */ 8, {10, 9, 8, 6, 3, 2, 1, 0 }},
{ /* 54 Mbits */ 9, {11, 10, 9, 8, 6, 3, 2, 1, 0 }}
};
static const struct ieee80211_channel zd_channels[] = {
{ .center_freq = 2412, .hw_value = 1 },
{ .center_freq = 2417, .hw_value = 2 },
{ .center_freq = 2422, .hw_value = 3 },
{ .center_freq = 2427, .hw_value = 4 },
{ .center_freq = 2432, .hw_value = 5 },
{ .center_freq = 2437, .hw_value = 6 },
{ .center_freq = 2442, .hw_value = 7 },
{ .center_freq = 2447, .hw_value = 8 },
{ .center_freq = 2452, .hw_value = 9 },
{ .center_freq = 2457, .hw_value = 10 },
{ .center_freq = 2462, .hw_value = 11 },
{ .center_freq = 2467, .hw_value = 12 },
{ .center_freq = 2472, .hw_value = 13 },
{ .center_freq = 2484, .hw_value = 14 },
};
static void housekeeping_init(struct zd_mac *mac);
static void housekeeping_enable(struct zd_mac *mac);
static void housekeeping_disable(struct zd_mac *mac);
static void beacon_init(struct zd_mac *mac);
static void beacon_enable(struct zd_mac *mac);
static void beacon_disable(struct zd_mac *mac);
static void set_rts_cts(struct zd_mac *mac, unsigned int short_preamble);
static int zd_mac_config_beacon(struct ieee80211_hw *hw,
struct sk_buff *beacon, bool in_intr);
static int zd_reg2alpha2(u8 regdomain, char *alpha2)
{
unsigned int i;
struct zd_reg_alpha2_map *reg_map;
for (i = 0; i < ARRAY_SIZE(reg_alpha2_map); i++) {
reg_map = ®_alpha2_map[i];
if (regdomain == reg_map->reg) {
alpha2[0] = reg_map->alpha2[0];
alpha2[1] = reg_map->alpha2[1];
return 0;
}
}
return 1;
}
static int zd_check_signal(struct ieee80211_hw *hw, int signal)
{
struct zd_mac *mac = zd_hw_mac(hw);
dev_dbg_f_cond(zd_mac_dev(mac), signal < 0 || signal > 100,
"%s: signal value from device not in range 0..100, "
"but %d.\n", __func__, signal);
if (signal < 0)
signal = 0;
else if (signal > 100)
signal = 100;
return signal;
}
int zd_mac_preinit_hw(struct ieee80211_hw *hw)
{
int r;
u8 addr[ETH_ALEN];
struct zd_mac *mac = zd_hw_mac(hw);
r = zd_chip_read_mac_addr_fw(&mac->chip, addr);
if (r)
return r;
SET_IEEE80211_PERM_ADDR(hw, addr);
return 0;
}
int zd_mac_init_hw(struct ieee80211_hw *hw)
{
int r;
struct zd_mac *mac = zd_hw_mac(hw);
struct zd_chip *chip = &mac->chip;
char alpha2[2];
u8 default_regdomain;
r = zd_chip_enable_int(chip);
if (r)
goto out;
r = zd_chip_init_hw(chip);
if (r)
goto disable_int;
ZD_ASSERT(!irqs_disabled());
r = zd_read_regdomain(chip, &default_regdomain);
if (r)
goto disable_int;
spin_lock_irq(&mac->lock);
mac->regdomain = mac->default_regdomain = default_regdomain;
spin_unlock_irq(&mac->lock);
/* We must inform the device that we are doing encryption/decryption in
* software at the moment. */
r = zd_set_encryption_type(chip, ENC_SNIFFER);
if (r)
goto disable_int;
r = zd_reg2alpha2(mac->regdomain, alpha2);
if (r)
goto disable_int;
r = regulatory_hint(hw->wiphy, alpha2);
disable_int:
zd_chip_disable_int(chip);
out:
return r;
}
void zd_mac_clear(struct zd_mac *mac)
{
flush_workqueue(zd_workqueue);
zd_chip_clear(&mac->chip);
ZD_ASSERT(!spin_is_locked(&mac->lock));
ZD_MEMCLEAR(mac, sizeof(struct zd_mac));
}
static int set_rx_filter(struct zd_mac *mac)
{
unsigned long flags;
u32 filter = STA_RX_FILTER;
spin_lock_irqsave(&mac->lock, flags);
if (mac->pass_ctrl)
filter |= RX_FILTER_CTRL;
spin_unlock_irqrestore(&mac->lock, flags);
return zd_iowrite32(&mac->chip, CR_RX_FILTER, filter);
}
static int set_mac_and_bssid(struct zd_mac *mac)
{
int r;
if (!mac->vif)
return -1;
r = zd_write_mac_addr(&mac->chip, mac->vif->addr);
if (r)
return r;
/* Vendor driver after setting MAC either sets BSSID for AP or
* filter for other modes.
*/
if (mac->type != NL80211_IFTYPE_AP)
return set_rx_filter(mac);
else
return zd_write_bssid(&mac->chip, mac->vif->addr);
}
static int set_mc_hash(struct zd_mac *mac)
{
struct zd_mc_hash hash;
zd_mc_clear(&hash);
return zd_chip_set_multicast_hash(&mac->chip, &hash);
}
int zd_op_start(struct ieee80211_hw *hw)
{
struct zd_mac *mac = zd_hw_mac(hw);
struct zd_chip *chip = &mac->chip;
struct zd_usb *usb = &chip->usb;
int r;
if (!usb->initialized) {
r = zd_usb_init_hw(usb);
if (r)
goto out;
}
r = zd_chip_enable_int(chip);
if (r < 0)
goto out;
r = zd_chip_set_basic_rates(chip, CR_RATES_80211B | CR_RATES_80211G);
if (r < 0)
goto disable_int;
r = set_rx_filter(mac);
if (r)
goto disable_int;
r = set_mc_hash(mac);
if (r)
goto disable_int;
/* Wait after setting the multicast hash table and powering on
* the radio otherwise interface bring up will fail. This matches
* what the vendor driver did.
*/
msleep(10);
r = zd_chip_switch_radio_on(chip);
if (r < 0) {
dev_err(zd_chip_dev(chip),
"%s: failed to set radio on\n", __func__);
goto disable_int;
}
r = zd_chip_enable_rxtx(chip);
if (r < 0)
goto disable_radio;
r = zd_chip_enable_hwint(chip);
if (r < 0)
goto disable_rxtx;
housekeeping_enable(mac);
beacon_enable(mac);
set_bit(ZD_DEVICE_RUNNING, &mac->flags);
return 0;
disable_rxtx:
zd_chip_disable_rxtx(chip);
disable_radio:
zd_chip_switch_radio_off(chip);
disable_int:
zd_chip_disable_int(chip);
out:
return r;
}
void zd_op_stop(struct ieee80211_hw *hw)
{
struct zd_mac *mac = zd_hw_mac(hw);
struct zd_chip *chip = &mac->chip;
struct sk_buff *skb;
struct sk_buff_head *ack_wait_queue = &mac->ack_wait_queue;
clear_bit(ZD_DEVICE_RUNNING, &mac->flags);
/* The order here deliberately is a little different from the open()
* method, since we need to make sure there is no opportunity for RX
* frames to be processed by mac80211 after we have stopped it.
*/
zd_chip_disable_rxtx(chip);
beacon_disable(mac);
housekeeping_disable(mac);
flush_workqueue(zd_workqueue);
zd_chip_disable_hwint(chip);
zd_chip_switch_radio_off(chip);
zd_chip_disable_int(chip);
while ((skb = skb_dequeue(ack_wait_queue)))
dev_kfree_skb_any(skb);
}
int zd_restore_settings(struct zd_mac *mac)
{
struct sk_buff *beacon;
struct zd_mc_hash multicast_hash;
unsigned int short_preamble;
int r, beacon_interval, beacon_period;
u8 channel;
dev_dbg_f(zd_mac_dev(mac), "\n");
spin_lock_irq(&mac->lock);
multicast_hash = mac->multicast_hash;
short_preamble = mac->short_preamble;
beacon_interval = mac->beacon.interval;
beacon_period = mac->beacon.period;
channel = mac->channel;
spin_unlock_irq(&mac->lock);
r = set_mac_and_bssid(mac);
if (r < 0) {
dev_dbg_f(zd_mac_dev(mac), "set_mac_and_bssid failed, %d\n", r);
return r;
}
r = zd_chip_set_channel(&mac->chip, channel);
if (r < 0) {
dev_dbg_f(zd_mac_dev(mac), "zd_chip_set_channel failed, %d\n",
r);
return r;
}
set_rts_cts(mac, short_preamble);
r = zd_chip_set_multicast_hash(&mac->chip, &multicast_hash);
if (r < 0) {
dev_dbg_f(zd_mac_dev(mac),
"zd_chip_set_multicast_hash failed, %d\n", r);
return r;
}
if (mac->type == NL80211_IFTYPE_MESH_POINT ||
mac->type == NL80211_IFTYPE_ADHOC ||
mac->type == NL80211_IFTYPE_AP) {
if (mac->vif != NULL) {
beacon = ieee80211_beacon_get(mac->hw, mac->vif);
if (beacon)
zd_mac_config_beacon(mac->hw, beacon, false);
}
zd_set_beacon_interval(&mac->chip, beacon_interval,
beacon_period, mac->type);
spin_lock_irq(&mac->lock);
mac->beacon.last_update = jiffies;
spin_unlock_irq(&mac->lock);
}
return 0;
}
/**
* zd_mac_tx_status - reports tx status of a packet if required
* @hw - a &struct ieee80211_hw pointer
* @skb - a sk-buffer
* @flags: extra flags to set in the TX status info
* @ackssi: ACK signal strength
* @success - True for successful transmission of the frame
*
* This information calls ieee80211_tx_status_irqsafe() if required by the
* control information. It copies the control information into the status
* information.
*
* If no status information has been requested, the skb is freed.
*/
static void zd_mac_tx_status(struct ieee80211_hw *hw, struct sk_buff *skb,
int ackssi, struct tx_status *tx_status)
{
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
int i;
int success = 1, retry = 1;
int first_idx;
const struct tx_retry_rate *retries;
ieee80211_tx_info_clear_status(info);
if (tx_status) {
success = !tx_status->failure;
retry = tx_status->retry + success;
}
if (success) {
/* success */
info->flags |= IEEE80211_TX_STAT_ACK;
} else {
/* failure */
info->flags &= ~IEEE80211_TX_STAT_ACK;
}
first_idx = info->status.rates[0].idx;
ZD_ASSERT(0<=first_idx && first_idx<ARRAY_SIZE(zd_retry_rates));
retries = &zd_retry_rates[first_idx];
ZD_ASSERT(1 <= retry && retry <= retries->count);
info->status.rates[0].idx = retries->rate[0];
info->status.rates[0].count = 1; // (retry > 1 ? 2 : 1);
for (i=1; i<IEEE80211_TX_MAX_RATES-1 && i<retry; i++) {
info->status.rates[i].idx = retries->rate[i];
info->status.rates[i].count = 1; // ((i==retry-1) && success ? 1:2);
}
for (; i<IEEE80211_TX_MAX_RATES && i<retry; i++) {
info->status.rates[i].idx = retries->rate[retry - 1];
info->status.rates[i].count = 1; // (success ? 1:2);
}
if (i<IEEE80211_TX_MAX_RATES)
info->status.rates[i].idx = -1; /* terminate */
info->status.ack_signal = zd_check_signal(hw, ackssi);
ieee80211_tx_status_irqsafe(hw, skb);
}
/**
* zd_mac_tx_failed - callback for failed frames
* @dev: the mac80211 wireless device
*
* This function is called if a frame couldn't be successfully
* transferred. The first frame from the tx queue, will be selected and
* reported as error to the upper layers.
*/
void zd_mac_tx_failed(struct urb *urb)
{
struct ieee80211_hw * hw = zd_usb_to_hw(urb->context);
struct zd_mac *mac = zd_hw_mac(hw);
struct sk_buff_head *q = &mac->ack_wait_queue;
struct sk_buff *skb;
struct tx_status *tx_status = (struct tx_status *)urb->transfer_buffer;
unsigned long flags;
int success = !tx_status->failure;
int retry = tx_status->retry + success;
int found = 0;
int i, position = 0;
q = &mac->ack_wait_queue;
spin_lock_irqsave(&q->lock, flags);
skb_queue_walk(q, skb) {
struct ieee80211_hdr *tx_hdr;
struct ieee80211_tx_info *info;
int first_idx, final_idx;
const struct tx_retry_rate *retries;
u8 final_rate;
position ++;
/* if the hardware reports a failure and we had a 802.11 ACK
* pending, then we skip the first skb when searching for a
* matching frame */
if (tx_status->failure && mac->ack_pending &&
skb_queue_is_first(q, skb)) {
continue;
}
tx_hdr = (struct ieee80211_hdr *)skb->data;
/* we skip all frames not matching the reported destination */
if (unlikely(!ether_addr_equal(tx_hdr->addr1, tx_status->mac)))
continue;
/* we skip all frames not matching the reported final rate */
info = IEEE80211_SKB_CB(skb);
first_idx = info->status.rates[0].idx;
ZD_ASSERT(0<=first_idx && first_idx<ARRAY_SIZE(zd_retry_rates));
retries = &zd_retry_rates[first_idx];
if (retry <= 0 || retry > retries->count)
continue;
final_idx = retries->rate[retry - 1];
final_rate = zd_rates[final_idx].hw_value;
if (final_rate != tx_status->rate) {
continue;
}
found = 1;
break;
}
if (found) {
for (i=1; i<=position; i++) {
skb = __skb_dequeue(q);
zd_mac_tx_status(hw, skb,
mac->ack_pending ? mac->ack_signal : 0,
i == position ? tx_status : NULL);
mac->ack_pending = 0;
}
}
spin_unlock_irqrestore(&q->lock, flags);
}
/**
* zd_mac_tx_to_dev - callback for USB layer
* @skb: a &sk_buff pointer
* @error: error value, 0 if transmission successful
*
* Informs the MAC layer that the frame has successfully transferred to the
* device. If an ACK is required and the transfer to the device has been
* successful, the packets are put on the @ack_wait_queue with
* the control set removed.
*/
void zd_mac_tx_to_dev(struct sk_buff *skb, int error)
{
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct ieee80211_hw *hw = info->rate_driver_data[0];
struct zd_mac *mac = zd_hw_mac(hw);
ieee80211_tx_info_clear_status(info);
skb_pull(skb, sizeof(struct zd_ctrlset));
if (unlikely(error ||
(info->flags & IEEE80211_TX_CTL_NO_ACK))) {
/*
* FIXME : do we need to fill in anything ?
*/
ieee80211_tx_status_irqsafe(hw, skb);
} else {
struct sk_buff_head *q = &mac->ack_wait_queue;
skb_queue_tail(q, skb);
while (skb_queue_len(q) > ZD_MAC_MAX_ACK_WAITERS) {
zd_mac_tx_status(hw, skb_dequeue(q),
mac->ack_pending ? mac->ack_signal : 0,
NULL);
mac->ack_pending = 0;
}
}
}
static int zd_calc_tx_length_us(u8 *service, u8 zd_rate, u16 tx_length)
{
/* ZD_PURE_RATE() must be used to remove the modulation type flag of
* the zd-rate values.
*/
static const u8 rate_divisor[] = {
[ZD_PURE_RATE(ZD_CCK_RATE_1M)] = 1,
[ZD_PURE_RATE(ZD_CCK_RATE_2M)] = 2,
/* Bits must be doubled. */
[ZD_PURE_RATE(ZD_CCK_RATE_5_5M)] = 11,
[ZD_PURE_RATE(ZD_CCK_RATE_11M)] = 11,
[ZD_PURE_RATE(ZD_OFDM_RATE_6M)] = 6,
[ZD_PURE_RATE(ZD_OFDM_RATE_9M)] = 9,
[ZD_PURE_RATE(ZD_OFDM_RATE_12M)] = 12,
[ZD_PURE_RATE(ZD_OFDM_RATE_18M)] = 18,
[ZD_PURE_RATE(ZD_OFDM_RATE_24M)] = 24,
[ZD_PURE_RATE(ZD_OFDM_RATE_36M)] = 36,
[ZD_PURE_RATE(ZD_OFDM_RATE_48M)] = 48,
[ZD_PURE_RATE(ZD_OFDM_RATE_54M)] = 54,
};
u32 bits = (u32)tx_length * 8;
u32 divisor;
divisor = rate_divisor[ZD_PURE_RATE(zd_rate)];
if (divisor == 0)
return -EINVAL;
switch (zd_rate) {
case ZD_CCK_RATE_5_5M:
bits = (2*bits) + 10; /* round up to the next integer */
break;
case ZD_CCK_RATE_11M:
if (service) {
u32 t = bits % 11;
*service &= ~ZD_PLCP_SERVICE_LENGTH_EXTENSION;
if (0 < t && t <= 3) {
*service |= ZD_PLCP_SERVICE_LENGTH_EXTENSION;
}
}
bits += 10; /* round up to the next integer */
break;
}
return bits/divisor;
}
static void cs_set_control(struct zd_mac *mac, struct zd_ctrlset *cs,
struct ieee80211_hdr *header,
struct ieee80211_tx_info *info)
{
/*
* CONTROL TODO:
* - if backoff needed, enable bit 0
* - if burst (backoff not needed) disable bit 0
*/
cs->control = 0;
/* First fragment */
if (info->flags & IEEE80211_TX_CTL_FIRST_FRAGMENT)
cs->control |= ZD_CS_NEED_RANDOM_BACKOFF;
/* No ACK expected (multicast, etc.) */
if (info->flags & IEEE80211_TX_CTL_NO_ACK)
cs->control |= ZD_CS_NO_ACK;
/* PS-POLL */
if (ieee80211_is_pspoll(header->frame_control))
cs->control |= ZD_CS_PS_POLL_FRAME;
if (info->control.rates[0].flags & IEEE80211_TX_RC_USE_RTS_CTS)
cs->control |= ZD_CS_RTS;
if (info->control.rates[0].flags & IEEE80211_TX_RC_USE_CTS_PROTECT)
cs->control |= ZD_CS_SELF_CTS;
/* FIXME: Management frame? */
}
static bool zd_mac_match_cur_beacon(struct zd_mac *mac, struct sk_buff *beacon)
{
if (!mac->beacon.cur_beacon)
return false;
if (mac->beacon.cur_beacon->len != beacon->len)
return false;
return !memcmp(beacon->data, mac->beacon.cur_beacon->data, beacon->len);
}
static void zd_mac_free_cur_beacon_locked(struct zd_mac *mac)
{
ZD_ASSERT(mutex_is_locked(&mac->chip.mutex));
kfree_skb(mac->beacon.cur_beacon);
mac->beacon.cur_beacon = NULL;
}
static void zd_mac_free_cur_beacon(struct zd_mac *mac)
{
mutex_lock(&mac->chip.mutex);
zd_mac_free_cur_beacon_locked(mac);
mutex_unlock(&mac->chip.mutex);
}
static int zd_mac_config_beacon(struct ieee80211_hw *hw, struct sk_buff *beacon,
bool in_intr)
{
struct zd_mac *mac = zd_hw_mac(hw);
int r, ret, num_cmds, req_pos = 0;
u32 tmp, j = 0;
/* 4 more bytes for tail CRC */
u32 full_len = beacon->len + 4;
unsigned long end_jiffies, message_jiffies;
struct zd_ioreq32 *ioreqs;
mutex_lock(&mac->chip.mutex);
/* Check if hw already has this beacon. */
if (zd_mac_match_cur_beacon(mac, beacon)) {
r = 0;
goto out_nofree;
}
/* Alloc memory for full beacon write at once. */
num_cmds = 1 + zd_chip_is_zd1211b(&mac->chip) + full_len;
ioreqs = kmalloc(num_cmds * sizeof(struct zd_ioreq32), GFP_KERNEL);
if (!ioreqs) {
r = -ENOMEM;
goto out_nofree;
}
r = zd_iowrite32_locked(&mac->chip, 0, CR_BCN_FIFO_SEMAPHORE);
if (r < 0)
goto out;
r = zd_ioread32_locked(&mac->chip, &tmp, CR_BCN_FIFO_SEMAPHORE);
if (r < 0)
goto release_sema;
if (in_intr && tmp & 0x2) {
r = -EBUSY;
goto release_sema;
}
end_jiffies = jiffies + HZ / 2; /*~500ms*/
message_jiffies = jiffies + HZ / 10; /*~100ms*/
while (tmp & 0x2) {
r = zd_ioread32_locked(&mac->chip, &tmp, CR_BCN_FIFO_SEMAPHORE);
if (r < 0)
goto release_sema;
if (time_is_before_eq_jiffies(message_jiffies)) {
message_jiffies = jiffies + HZ / 10;
dev_err(zd_mac_dev(mac),
"CR_BCN_FIFO_SEMAPHORE not ready\n");
if (time_is_before_eq_jiffies(end_jiffies)) {
dev_err(zd_mac_dev(mac),
"Giving up beacon config.\n");
r = -ETIMEDOUT;
goto reset_device;
}
}
msleep(20);
}
ioreqs[req_pos].addr = CR_BCN_FIFO;
ioreqs[req_pos].value = full_len - 1;
req_pos++;
if (zd_chip_is_zd1211b(&mac->chip)) {
ioreqs[req_pos].addr = CR_BCN_LENGTH;
ioreqs[req_pos].value = full_len - 1;
req_pos++;
}
for (j = 0 ; j < beacon->len; j++) {
ioreqs[req_pos].addr = CR_BCN_FIFO;
ioreqs[req_pos].value = *((u8 *)(beacon->data + j));
req_pos++;
}
for (j = 0; j < 4; j++) {
ioreqs[req_pos].addr = CR_BCN_FIFO;
ioreqs[req_pos].value = 0x0;
req_pos++;
}
BUG_ON(req_pos != num_cmds);
r = zd_iowrite32a_locked(&mac->chip, ioreqs, num_cmds);
release_sema:
/*
* Try very hard to release device beacon semaphore, as otherwise
* device/driver can be left in unusable state.
*/
end_jiffies = jiffies + HZ / 2; /*~500ms*/
ret = zd_iowrite32_locked(&mac->chip, 1, CR_BCN_FIFO_SEMAPHORE);
while (ret < 0) {
if (in_intr || time_is_before_eq_jiffies(end_jiffies)) {
ret = -ETIMEDOUT;
break;
}
msleep(20);
ret = zd_iowrite32_locked(&mac->chip, 1, CR_BCN_FIFO_SEMAPHORE);
}
if (ret < 0)
dev_err(zd_mac_dev(mac), "Could not release "
"CR_BCN_FIFO_SEMAPHORE!\n");
if (r < 0 || ret < 0) {
if (r >= 0)
r = ret;
/* We don't know if beacon was written successfully or not,
* so clear current. */
zd_mac_free_cur_beacon_locked(mac);
goto out;
}
/* Beacon has now been written successfully, update current. */
zd_mac_free_cur_beacon_locked(mac);
mac->beacon.cur_beacon = beacon;
beacon = NULL;
/* 802.11b/g 2.4G CCK 1Mb
* 802.11a, not yet implemented, uses different values (see GPL vendor
* driver)
*/
r = zd_iowrite32_locked(&mac->chip, 0x00000400 | (full_len << 19),
CR_BCN_PLCP_CFG);
out:
kfree(ioreqs);
out_nofree:
kfree_skb(beacon);
mutex_unlock(&mac->chip.mutex);
return r;
reset_device:
zd_mac_free_cur_beacon_locked(mac);
kfree_skb(beacon);
mutex_unlock(&mac->chip.mutex);
kfree(ioreqs);
/* semaphore stuck, reset device to avoid fw freeze later */
dev_warn(zd_mac_dev(mac), "CR_BCN_FIFO_SEMAPHORE stuck, "
"resetting device...");
usb_queue_reset_device(mac->chip.usb.intf);
return r;
}
static int fill_ctrlset(struct zd_mac *mac,
struct sk_buff *skb)
{
int r;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
unsigned int frag_len = skb->len + FCS_LEN;
unsigned int packet_length;
struct ieee80211_rate *txrate;
struct zd_ctrlset *cs = (struct zd_ctrlset *)
skb_push(skb, sizeof(struct zd_ctrlset));
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
ZD_ASSERT(frag_len <= 0xffff);
/*
* Firmware computes the duration itself (for all frames except PSPoll)
* and needs the field set to 0 at input, otherwise firmware messes up
* duration_id and sets bits 14 and 15 on.
*/
if (!ieee80211_is_pspoll(hdr->frame_control))
hdr->duration_id = 0;
txrate = ieee80211_get_tx_rate(mac->hw, info);
cs->modulation = txrate->hw_value;
if (info->control.rates[0].flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE)
cs->modulation = txrate->hw_value_short;
cs->tx_length = cpu_to_le16(frag_len);
cs_set_control(mac, cs, hdr, info);
packet_length = frag_len + sizeof(struct zd_ctrlset) + 10;
ZD_ASSERT(packet_length <= 0xffff);
/* ZD1211B: Computing the length difference this way, gives us
* flexibility to compute the packet length.
*/
cs->packet_length = cpu_to_le16(zd_chip_is_zd1211b(&mac->chip) ?
packet_length - frag_len : packet_length);
/*
* CURRENT LENGTH:
* - transmit frame length in microseconds
* - seems to be derived from frame length
* - see Cal_Us_Service() in zdinlinef.h
* - if macp->bTxBurstEnable is enabled, then multiply by 4
* - bTxBurstEnable is never set in the vendor driver
*
* SERVICE:
* - "for PLCP configuration"
* - always 0 except in some situations at 802.11b 11M
* - see line 53 of zdinlinef.h
*/
cs->service = 0;
r = zd_calc_tx_length_us(&cs->service, ZD_RATE(cs->modulation),
le16_to_cpu(cs->tx_length));
if (r < 0)
return r;
cs->current_length = cpu_to_le16(r);
cs->next_frame_length = 0;
return 0;
}
/**
* zd_op_tx - transmits a network frame to the device
*
* @dev: mac80211 hardware device
* @skb: socket buffer
* @control: the control structure
*
* This function transmit an IEEE 802.11 network frame to the device. The
* control block of the skbuff will be initialized. If necessary the incoming
* mac80211 queues will be stopped.
*/
static void zd_op_tx(struct ieee80211_hw *hw,
struct ieee80211_tx_control *control,
struct sk_buff *skb)
{
struct zd_mac *mac = zd_hw_mac(hw);
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
int r;
r = fill_ctrlset(mac, skb);
if (r)
goto fail;
info->rate_driver_data[0] = hw;
r = zd_usb_tx(&mac->chip.usb, skb);
if (r)
goto fail;
return;
fail:
dev_kfree_skb(skb);
}
/**
* filter_ack - filters incoming packets for acknowledgements
* @dev: the mac80211 device
* @rx_hdr: received header
* @stats: the status for the received packet
*
* This functions looks for ACK packets and tries to match them with the
* frames in the tx queue. If a match is found the frame will be dequeued and
* the upper layers is informed about the successful transmission. If
* mac80211 queues have been stopped and the number of frames still to be
* transmitted is low the queues will be opened again.
*
* Returns 1 if the frame was an ACK, 0 if it was ignored.
*/
static int filter_ack(struct ieee80211_hw *hw, struct ieee80211_hdr *rx_hdr,
struct ieee80211_rx_status *stats)
{
struct zd_mac *mac = zd_hw_mac(hw);
struct sk_buff *skb;
struct sk_buff_head *q;
unsigned long flags;
int found = 0;
int i, position = 0;
if (!ieee80211_is_ack(rx_hdr->frame_control))
return 0;
q = &mac->ack_wait_queue;
spin_lock_irqsave(&q->lock, flags);
skb_queue_walk(q, skb) {
struct ieee80211_hdr *tx_hdr;
position ++;
if (mac->ack_pending && skb_queue_is_first(q, skb))
continue;
tx_hdr = (struct ieee80211_hdr *)skb->data;
if (likely(ether_addr_equal(tx_hdr->addr2, rx_hdr->addr1)))
{
found = 1;
break;
}
}
if (found) {
for (i=1; i<position; i++) {
skb = __skb_dequeue(q);
zd_mac_tx_status(hw, skb,
mac->ack_pending ? mac->ack_signal : 0,
NULL);
mac->ack_pending = 0;
}
mac->ack_pending = 1;
mac->ack_signal = stats->signal;
/* Prevent pending tx-packet on AP-mode */
if (mac->type == NL80211_IFTYPE_AP) {
skb = __skb_dequeue(q);
zd_mac_tx_status(hw, skb, mac->ack_signal, NULL);
mac->ack_pending = 0;
}
}
spin_unlock_irqrestore(&q->lock, flags);
return 1;
}
int zd_mac_rx(struct ieee80211_hw *hw, const u8 *buffer, unsigned int length)
{
struct zd_mac *mac = zd_hw_mac(hw);
struct ieee80211_rx_status stats;
const struct rx_status *status;
struct sk_buff *skb;
int bad_frame = 0;
__le16 fc;
int need_padding;
int i;
u8 rate;
if (length < ZD_PLCP_HEADER_SIZE + 10 /* IEEE80211_1ADDR_LEN */ +
FCS_LEN + sizeof(struct rx_status))
return -EINVAL;
memset(&stats, 0, sizeof(stats));
/* Note about pass_failed_fcs and pass_ctrl access below:
* mac locking intentionally omitted here, as this is the only unlocked
* reader and the only writer is configure_filter. Plus, if there were
* any races accessing these variables, it wouldn't really matter.
* If mac80211 ever provides a way for us to access filter flags
* from outside configure_filter, we could improve on this. Also, this
* situation may change once we implement some kind of DMA-into-skb
* RX path. */
/* Caller has to ensure that length >= sizeof(struct rx_status). */
status = (struct rx_status *)
(buffer + (length - sizeof(struct rx_status)));
if (status->frame_status & ZD_RX_ERROR) {
if (mac->pass_failed_fcs &&
(status->frame_status & ZD_RX_CRC32_ERROR)) {
stats.flag |= RX_FLAG_FAILED_FCS_CRC;
bad_frame = 1;
} else {
return -EINVAL;
}
}
stats.freq = zd_channels[_zd_chip_get_channel(&mac->chip) - 1].center_freq;
stats.band = IEEE80211_BAND_2GHZ;
stats.signal = zd_check_signal(hw, status->signal_strength);
rate = zd_rx_rate(buffer, status);
/* todo: return index in the big switches in zd_rx_rate instead */
for (i = 0; i < mac->band.n_bitrates; i++)
if (rate == mac->band.bitrates[i].hw_value)
stats.rate_idx = i;
length -= ZD_PLCP_HEADER_SIZE + sizeof(struct rx_status);
buffer += ZD_PLCP_HEADER_SIZE;
/* Except for bad frames, filter each frame to see if it is an ACK, in
* which case our internal TX tracking is updated. Normally we then
* bail here as there's no need to pass ACKs on up to the stack, but
* there is also the case where the stack has requested us to pass
* control frames on up (pass_ctrl) which we must consider. */
if (!bad_frame &&
filter_ack(hw, (struct ieee80211_hdr *)buffer, &stats)
&& !mac->pass_ctrl)
return 0;
fc = get_unaligned((__le16*)buffer);
need_padding = ieee80211_is_data_qos(fc) ^ ieee80211_has_a4(fc);
skb = dev_alloc_skb(length + (need_padding ? 2 : 0));
if (skb == NULL)
return -ENOMEM;
if (need_padding) {
/* Make sure the payload data is 4 byte aligned. */
skb_reserve(skb, 2);
}
/* FIXME : could we avoid this big memcpy ? */
memcpy(skb_put(skb, length), buffer, length);
memcpy(IEEE80211_SKB_RXCB(skb), &stats, sizeof(stats));
ieee80211_rx_irqsafe(hw, skb);
return 0;
}
static int zd_op_add_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct zd_mac *mac = zd_hw_mac(hw);
/* using NL80211_IFTYPE_UNSPECIFIED to indicate no mode selected */
if (mac->type != NL80211_IFTYPE_UNSPECIFIED)
return -EOPNOTSUPP;
switch (vif->type) {
case NL80211_IFTYPE_MONITOR:
case NL80211_IFTYPE_MESH_POINT:
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_AP:
mac->type = vif->type;
break;
default:
return -EOPNOTSUPP;
}
mac->vif = vif;
return set_mac_and_bssid(mac);
}
static void zd_op_remove_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct zd_mac *mac = zd_hw_mac(hw);
mac->type = NL80211_IFTYPE_UNSPECIFIED;
mac->vif = NULL;
zd_set_beacon_interval(&mac->chip, 0, 0, NL80211_IFTYPE_UNSPECIFIED);
zd_write_mac_addr(&mac->chip, NULL);
zd_mac_free_cur_beacon(mac);
}
static int zd_op_config(struct ieee80211_hw *hw, u32 changed)
{
struct zd_mac *mac = zd_hw_mac(hw);
struct ieee80211_conf *conf = &hw->conf;
spin_lock_irq(&mac->lock);
mac->channel = conf->chandef.chan->hw_value;
spin_unlock_irq(&mac->lock);
return zd_chip_set_channel(&mac->chip, conf->chandef.chan->hw_value);
}
static void zd_beacon_done(struct zd_mac *mac)
{
struct sk_buff *skb, *beacon;
if (!test_bit(ZD_DEVICE_RUNNING, &mac->flags))
return;
if (!mac->vif || mac->vif->type != NL80211_IFTYPE_AP)
return;
/*
* Send out buffered broad- and multicast frames.
*/
while (!ieee80211_queue_stopped(mac->hw, 0)) {
skb = ieee80211_get_buffered_bc(mac->hw, mac->vif);
if (!skb)
break;
zd_op_tx(mac->hw, NULL, skb);
}
/*
* Fetch next beacon so that tim_count is updated.
*/
beacon = ieee80211_beacon_get(mac->hw, mac->vif);
if (beacon)
zd_mac_config_beacon(mac->hw, beacon, true);
spin_lock_irq(&mac->lock);
mac->beacon.last_update = jiffies;
spin_unlock_irq(&mac->lock);
}
static void zd_process_intr(struct work_struct *work)
{
u16 int_status;
unsigned long flags;
struct zd_mac *mac = container_of(work, struct zd_mac, process_intr);
spin_lock_irqsave(&mac->lock, flags);
int_status = le16_to_cpu(*(__le16 *)(mac->intr_buffer + 4));
spin_unlock_irqrestore(&mac->lock, flags);
if (int_status & INT_CFG_NEXT_BCN) {
/*dev_dbg_f_limit(zd_mac_dev(mac), "INT_CFG_NEXT_BCN\n");*/
zd_beacon_done(mac);
} else {
dev_dbg_f(zd_mac_dev(mac), "Unsupported interrupt\n");
}
zd_chip_enable_hwint(&mac->chip);
}
static u64 zd_op_prepare_multicast(struct ieee80211_hw *hw,
struct netdev_hw_addr_list *mc_list)
{
struct zd_mac *mac = zd_hw_mac(hw);
struct zd_mc_hash hash;
struct netdev_hw_addr *ha;
zd_mc_clear(&hash);
netdev_hw_addr_list_for_each(ha, mc_list) {
dev_dbg_f(zd_mac_dev(mac), "mc addr %pM\n", ha->addr);
zd_mc_add_addr(&hash, ha->addr);
}
return hash.low | ((u64)hash.high << 32);
}
#define SUPPORTED_FIF_FLAGS \
(FIF_PROMISC_IN_BSS | FIF_ALLMULTI | FIF_FCSFAIL | FIF_CONTROL | \
FIF_OTHER_BSS | FIF_BCN_PRBRESP_PROMISC)
static void zd_op_configure_filter(struct ieee80211_hw *hw,
unsigned int changed_flags,
unsigned int *new_flags,
u64 multicast)
{
struct zd_mc_hash hash = {
.low = multicast,
.high = multicast >> 32,
};
struct zd_mac *mac = zd_hw_mac(hw);
unsigned long flags;
int r;
/* Only deal with supported flags */
changed_flags &= SUPPORTED_FIF_FLAGS;
*new_flags &= SUPPORTED_FIF_FLAGS;
/*
* If multicast parameter (as returned by zd_op_prepare_multicast)
* has changed, no bit in changed_flags is set. To handle this
* situation, we do not return if changed_flags is 0. If we do so,
* we will have some issue with IPv6 which uses multicast for link
* layer address resolution.
*/
if (*new_flags & (FIF_PROMISC_IN_BSS | FIF_ALLMULTI))
zd_mc_add_all(&hash);
spin_lock_irqsave(&mac->lock, flags);
mac->pass_failed_fcs = !!(*new_flags & FIF_FCSFAIL);
mac->pass_ctrl = !!(*new_flags & FIF_CONTROL);
mac->multicast_hash = hash;
spin_unlock_irqrestore(&mac->lock, flags);
zd_chip_set_multicast_hash(&mac->chip, &hash);
if (changed_flags & FIF_CONTROL) {
r = set_rx_filter(mac);
if (r)
dev_err(zd_mac_dev(mac), "set_rx_filter error %d\n", r);
}
/* no handling required for FIF_OTHER_BSS as we don't currently
* do BSSID filtering */
/* FIXME: in future it would be nice to enable the probe response
* filter (so that the driver doesn't see them) until
* FIF_BCN_PRBRESP_PROMISC is set. however due to atomicity here, we'd
* have to schedule work to enable prbresp reception, which might
* happen too late. For now we'll just listen and forward them all the
* time. */
}
static void set_rts_cts(struct zd_mac *mac, unsigned int short_preamble)
{
mutex_lock(&mac->chip.mutex);
zd_chip_set_rts_cts_rate_locked(&mac->chip, short_preamble);
mutex_unlock(&mac->chip.mutex);
}
static void zd_op_bss_info_changed(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *bss_conf,
u32 changes)
{
struct zd_mac *mac = zd_hw_mac(hw);
int associated;
dev_dbg_f(zd_mac_dev(mac), "changes: %x\n", changes);
if (mac->type == NL80211_IFTYPE_MESH_POINT ||
mac->type == NL80211_IFTYPE_ADHOC ||
mac->type == NL80211_IFTYPE_AP) {
associated = true;
if (changes & BSS_CHANGED_BEACON) {
struct sk_buff *beacon = ieee80211_beacon_get(hw, vif);
if (beacon) {
zd_chip_disable_hwint(&mac->chip);
zd_mac_config_beacon(hw, beacon, false);
zd_chip_enable_hwint(&mac->chip);
}
}
if (changes & BSS_CHANGED_BEACON_ENABLED) {
u16 interval = 0;
u8 period = 0;
if (bss_conf->enable_beacon) {
period = bss_conf->dtim_period;
interval = bss_conf->beacon_int;
}
spin_lock_irq(&mac->lock);
mac->beacon.period = period;
mac->beacon.interval = interval;
mac->beacon.last_update = jiffies;
spin_unlock_irq(&mac->lock);
zd_set_beacon_interval(&mac->chip, interval, period,
mac->type);
}
} else
associated = is_valid_ether_addr(bss_conf->bssid);
spin_lock_irq(&mac->lock);
mac->associated = associated;
spin_unlock_irq(&mac->lock);
/* TODO: do hardware bssid filtering */
if (changes & BSS_CHANGED_ERP_PREAMBLE) {
spin_lock_irq(&mac->lock);
mac->short_preamble = bss_conf->use_short_preamble;
spin_unlock_irq(&mac->lock);
set_rts_cts(mac, bss_conf->use_short_preamble);
}
}
static u64 zd_op_get_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
{
struct zd_mac *mac = zd_hw_mac(hw);
return zd_chip_get_tsf(&mac->chip);
}
static const struct ieee80211_ops zd_ops = {
.tx = zd_op_tx,
.start = zd_op_start,
.stop = zd_op_stop,
.add_interface = zd_op_add_interface,
.remove_interface = zd_op_remove_interface,
.config = zd_op_config,
.prepare_multicast = zd_op_prepare_multicast,
.configure_filter = zd_op_configure_filter,
.bss_info_changed = zd_op_bss_info_changed,
.get_tsf = zd_op_get_tsf,
};
struct ieee80211_hw *zd_mac_alloc_hw(struct usb_interface *intf)
{
struct zd_mac *mac;
struct ieee80211_hw *hw;
hw = ieee80211_alloc_hw(sizeof(struct zd_mac), &zd_ops);
if (!hw) {
dev_dbg_f(&intf->dev, "out of memory\n");
return NULL;
}
mac = zd_hw_mac(hw);
memset(mac, 0, sizeof(*mac));
spin_lock_init(&mac->lock);
mac->hw = hw;
mac->type = NL80211_IFTYPE_UNSPECIFIED;
memcpy(mac->channels, zd_channels, sizeof(zd_channels));
memcpy(mac->rates, zd_rates, sizeof(zd_rates));
mac->band.n_bitrates = ARRAY_SIZE(zd_rates);
mac->band.bitrates = mac->rates;
mac->band.n_channels = ARRAY_SIZE(zd_channels);
mac->band.channels = mac->channels;
hw->wiphy->bands[IEEE80211_BAND_2GHZ] = &mac->band;
hw->flags = IEEE80211_HW_RX_INCLUDES_FCS |
IEEE80211_HW_SIGNAL_UNSPEC |
IEEE80211_HW_HOST_BROADCAST_PS_BUFFERING |
IEEE80211_HW_MFP_CAPABLE;
hw->wiphy->interface_modes =
BIT(NL80211_IFTYPE_MESH_POINT) |
BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_ADHOC) |
BIT(NL80211_IFTYPE_AP);
hw->max_signal = 100;
hw->queues = 1;
hw->extra_tx_headroom = sizeof(struct zd_ctrlset);
/*
* Tell mac80211 that we support multi rate retries
*/
hw->max_rates = IEEE80211_TX_MAX_RATES;
hw->max_rate_tries = 18; /* 9 rates * 2 retries/rate */
skb_queue_head_init(&mac->ack_wait_queue);
mac->ack_pending = 0;
zd_chip_init(&mac->chip, hw, intf);
housekeeping_init(mac);
beacon_init(mac);
INIT_WORK(&mac->process_intr, zd_process_intr);
SET_IEEE80211_DEV(hw, &intf->dev);
return hw;
}
#define BEACON_WATCHDOG_DELAY round_jiffies_relative(HZ)
static void beacon_watchdog_handler(struct work_struct *work)
{
struct zd_mac *mac =
container_of(work, struct zd_mac, beacon.watchdog_work.work);
struct sk_buff *beacon;
unsigned long timeout;
int interval, period;
if (!test_bit(ZD_DEVICE_RUNNING, &mac->flags))
goto rearm;
if (mac->type != NL80211_IFTYPE_AP || !mac->vif)
goto rearm;
spin_lock_irq(&mac->lock);
interval = mac->beacon.interval;
period = mac->beacon.period;
timeout = mac->beacon.last_update +
msecs_to_jiffies(interval * 1024 / 1000) * 3;
spin_unlock_irq(&mac->lock);
if (interval > 0 && time_is_before_jiffies(timeout)) {
dev_dbg_f(zd_mac_dev(mac), "beacon interrupt stalled, "
"restarting. "
"(interval: %d, dtim: %d)\n",
interval, period);
zd_chip_disable_hwint(&mac->chip);
beacon = ieee80211_beacon_get(mac->hw, mac->vif);
if (beacon) {
zd_mac_free_cur_beacon(mac);
zd_mac_config_beacon(mac->hw, beacon, false);
}
zd_set_beacon_interval(&mac->chip, interval, period, mac->type);
zd_chip_enable_hwint(&mac->chip);
spin_lock_irq(&mac->lock);
mac->beacon.last_update = jiffies;
spin_unlock_irq(&mac->lock);
}
rearm:
queue_delayed_work(zd_workqueue, &mac->beacon.watchdog_work,
BEACON_WATCHDOG_DELAY);
}
static void beacon_init(struct zd_mac *mac)
{
INIT_DELAYED_WORK(&mac->beacon.watchdog_work, beacon_watchdog_handler);
}
static void beacon_enable(struct zd_mac *mac)
{
dev_dbg_f(zd_mac_dev(mac), "\n");
mac->beacon.last_update = jiffies;
queue_delayed_work(zd_workqueue, &mac->beacon.watchdog_work,
BEACON_WATCHDOG_DELAY);
}
static void beacon_disable(struct zd_mac *mac)
{
dev_dbg_f(zd_mac_dev(mac), "\n");
cancel_delayed_work_sync(&mac->beacon.watchdog_work);
zd_mac_free_cur_beacon(mac);
}
#define LINK_LED_WORK_DELAY HZ
static void link_led_handler(struct work_struct *work)
{
struct zd_mac *mac =
container_of(work, struct zd_mac, housekeeping.link_led_work.work);
struct zd_chip *chip = &mac->chip;
int is_associated;
int r;
if (!test_bit(ZD_DEVICE_RUNNING, &mac->flags))
goto requeue;
spin_lock_irq(&mac->lock);
is_associated = mac->associated;
spin_unlock_irq(&mac->lock);
r = zd_chip_control_leds(chip,
is_associated ? ZD_LED_ASSOCIATED : ZD_LED_SCANNING);
if (r)
dev_dbg_f(zd_mac_dev(mac), "zd_chip_control_leds error %d\n", r);
requeue:
queue_delayed_work(zd_workqueue, &mac->housekeeping.link_led_work,
LINK_LED_WORK_DELAY);
}
static void housekeeping_init(struct zd_mac *mac)
{
INIT_DELAYED_WORK(&mac->housekeeping.link_led_work, link_led_handler);
}
static void housekeeping_enable(struct zd_mac *mac)
{
dev_dbg_f(zd_mac_dev(mac), "\n");
queue_delayed_work(zd_workqueue, &mac->housekeeping.link_led_work,
0);
}
static void housekeeping_disable(struct zd_mac *mac)
{
dev_dbg_f(zd_mac_dev(mac), "\n");
cancel_delayed_work_sync(&mac->housekeeping.link_led_work);
zd_chip_control_leds(&mac->chip, ZD_LED_OFF);
}
| gpl-2.0 |
lnfamous/Kernel_Htc_Pico_Stock | drivers/staging/speakup/speakup_soft.c | 1740 | 9912 | /* speakup_soft.c - speakup driver to register and make available
* a user space device for software synthesizers. written by: Kirk
* Reiser <kirk@braille.uwo.ca>
*
* Copyright (C) 2003 Kirk Reiser.
*
* 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
*
* this code is specificly written as a driver for the speakup screenreview
* package and is not a general device driver. */
#include <linux/unistd.h>
#include <linux/miscdevice.h> /* for misc_register, and SYNTH_MINOR */
#include <linux/poll.h> /* for poll_wait() */
#include <linux/sched.h> /* schedule(), signal_pending(), TASK_INTERRUPTIBLE */
#include "spk_priv.h"
#include "speakup.h"
#define DRV_VERSION "2.6"
#define SOFTSYNTH_MINOR 26 /* might as well give it one more than /dev/synth */
#define PROCSPEECH 0x0d
#define CLEAR_SYNTH 0x18
static int softsynth_probe(struct spk_synth *synth);
static void softsynth_release(void);
static int softsynth_is_alive(struct spk_synth *synth);
static unsigned char get_index(void);
static struct miscdevice synth_device;
static int initialized;
static int misc_registered;
static struct var_t vars[] = {
{ CAPS_START, .u.s = {"\x01+3p" } },
{ CAPS_STOP, .u.s = {"\x01-3p" } },
{ RATE, .u.n = {"\x01%ds", 5, 0, 9, 0, 0, NULL } },
{ PITCH, .u.n = {"\x01%dp", 5, 0, 9, 0, 0, NULL } },
{ VOL, .u.n = {"\x01%dv", 5, 0, 9, 0, 0, NULL } },
{ TONE, .u.n = {"\x01%dx", 1, 0, 2, 0, 0, NULL } },
{ PUNCT, .u.n = {"\x01%db", 0, 0, 2, 0, 0, NULL } },
{ VOICE, .u.n = {"\x01%do", 0, 0, 7, 0, 0, NULL } },
{ FREQUENCY, .u.n = {"\x01%df", 5, 0, 9, 0, 0, NULL } },
{ DIRECT, .u.n = {NULL, 0, 0, 1, 0, 0, NULL } },
V_LAST_VAR
};
/*
* These attributes will appear in /sys/accessibility/speakup/soft.
*/
static struct kobj_attribute caps_start_attribute =
__ATTR(caps_start, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute caps_stop_attribute =
__ATTR(caps_stop, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute freq_attribute =
__ATTR(freq, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute pitch_attribute =
__ATTR(pitch, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute punct_attribute =
__ATTR(punct, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute rate_attribute =
__ATTR(rate, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute tone_attribute =
__ATTR(tone, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute voice_attribute =
__ATTR(voice, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute vol_attribute =
__ATTR(vol, USER_RW, spk_var_show, spk_var_store);
/*
* We should uncomment the following definition, when we agree on a
* method of passing a language designation to the software synthesizer.
* static struct kobj_attribute lang_attribute =
* __ATTR(lang, USER_RW, spk_var_show, spk_var_store);
*/
static struct kobj_attribute delay_time_attribute =
__ATTR(delay_time, ROOT_W, spk_var_show, spk_var_store);
static struct kobj_attribute direct_attribute =
__ATTR(direct, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute full_time_attribute =
__ATTR(full_time, ROOT_W, spk_var_show, spk_var_store);
static struct kobj_attribute jiffy_delta_attribute =
__ATTR(jiffy_delta, ROOT_W, spk_var_show, spk_var_store);
static struct kobj_attribute trigger_time_attribute =
__ATTR(trigger_time, ROOT_W, spk_var_show, spk_var_store);
/*
* Create a group of attributes so that we can create and destroy them all
* at once.
*/
static struct attribute *synth_attrs[] = {
&caps_start_attribute.attr,
&caps_stop_attribute.attr,
&freq_attribute.attr,
/* &lang_attribute.attr, */
&pitch_attribute.attr,
&punct_attribute.attr,
&rate_attribute.attr,
&tone_attribute.attr,
&voice_attribute.attr,
&vol_attribute.attr,
&delay_time_attribute.attr,
&direct_attribute.attr,
&full_time_attribute.attr,
&jiffy_delta_attribute.attr,
&trigger_time_attribute.attr,
NULL, /* need to NULL terminate the list of attributes */
};
static struct spk_synth synth_soft = {
.name = "soft",
.version = DRV_VERSION,
.long_name = "software synth",
.init = "\01@\x01\x31y\n",
.procspeech = PROCSPEECH,
.delay = 0,
.trigger = 0,
.jiffies = 0,
.full = 0,
.startup = SYNTH_START,
.checkval = SYNTH_CHECK,
.vars = vars,
.probe = softsynth_probe,
.release = softsynth_release,
.synth_immediate = NULL,
.catch_up = NULL,
.flush = NULL,
.is_alive = softsynth_is_alive,
.synth_adjust = NULL,
.read_buff_add = NULL,
.get_index = get_index,
.indexing = {
.command = "\x01%di",
.lowindex = 1,
.highindex = 5,
.currindex = 1,
},
.attributes = {
.attrs = synth_attrs,
.name = "soft",
},
};
static char *get_initstring(void)
{
static char buf[40];
char *cp;
struct var_t *var;
memset(buf, 0, sizeof(buf));
cp = buf;
var = synth_soft.vars;
while (var->var_id != MAXVARS) {
if (var->var_id != CAPS_START && var->var_id != CAPS_STOP
&& var->var_id != DIRECT)
cp = cp + sprintf(cp, var->u.n.synth_fmt,
var->u.n.value);
var++;
}
cp = cp + sprintf(cp, "\n");
return buf;
}
static int softsynth_open(struct inode *inode, struct file *fp)
{
unsigned long flags;
/*if ((fp->f_flags & O_ACCMODE) != O_RDONLY) */
/* return -EPERM; */
spk_lock(flags);
if (synth_soft.alive) {
spk_unlock(flags);
return -EBUSY;
}
synth_soft.alive = 1;
spk_unlock(flags);
return 0;
}
static int softsynth_close(struct inode *inode, struct file *fp)
{
unsigned long flags;
spk_lock(flags);
synth_soft.alive = 0;
initialized = 0;
spk_unlock(flags);
/* Make sure we let applications go before leaving */
speakup_start_ttys();
return 0;
}
static ssize_t softsynth_read(struct file *fp, char *buf, size_t count,
loff_t *pos)
{
int chars_sent = 0;
char *cp;
char *init;
char ch;
int empty;
unsigned long flags;
DEFINE_WAIT(wait);
spk_lock(flags);
while (1) {
prepare_to_wait(&speakup_event, &wait, TASK_INTERRUPTIBLE);
if (!synth_buffer_empty() || speakup_info.flushing)
break;
spk_unlock(flags);
if (fp->f_flags & O_NONBLOCK) {
finish_wait(&speakup_event, &wait);
return -EAGAIN;
}
if (signal_pending(current)) {
finish_wait(&speakup_event, &wait);
return -ERESTARTSYS;
}
schedule();
spk_lock(flags);
}
finish_wait(&speakup_event, &wait);
cp = buf;
init = get_initstring();
while (chars_sent < count) {
if (speakup_info.flushing) {
speakup_info.flushing = 0;
ch = '\x18';
} else if (synth_buffer_empty()) {
break;
} else if (!initialized) {
if (*init) {
ch = *init;
init++;
} else {
initialized = 1;
}
} else {
ch = synth_buffer_getc();
}
spk_unlock(flags);
if (copy_to_user(cp, &ch, 1))
return -EFAULT;
spk_lock(flags);
chars_sent++;
cp++;
}
*pos += chars_sent;
empty = synth_buffer_empty();
spk_unlock(flags);
if (empty) {
speakup_start_ttys();
*pos = 0;
}
return chars_sent;
}
static int last_index;
static ssize_t softsynth_write(struct file *fp, const char *buf, size_t count,
loff_t *pos)
{
unsigned long supplied_index = 0;
int converted;
char indbuf[5];
if (count >= sizeof(indbuf))
return -EINVAL;
if (copy_from_user(indbuf, buf, count))
return -EFAULT;
indbuf[count] = '\0';
converted = strict_strtoul(indbuf, 0, &supplied_index);
if (converted < 0)
return converted;
last_index = supplied_index;
return count;
}
static unsigned int softsynth_poll(struct file *fp,
struct poll_table_struct *wait)
{
unsigned long flags;
int ret = 0;
poll_wait(fp, &speakup_event, wait);
spk_lock(flags);
if (!synth_buffer_empty() || speakup_info.flushing)
ret = POLLIN | POLLRDNORM;
spk_unlock(flags);
return ret;
}
static unsigned char get_index(void)
{
int rv;
rv = last_index;
last_index = 0;
return rv;
}
static const struct file_operations softsynth_fops = {
.owner = THIS_MODULE,
.poll = softsynth_poll,
.read = softsynth_read,
.write = softsynth_write,
.open = softsynth_open,
.release = softsynth_close,
};
static int softsynth_probe(struct spk_synth *synth)
{
if (misc_registered != 0)
return 0;
memset(&synth_device, 0, sizeof(synth_device));
synth_device.minor = SOFTSYNTH_MINOR;
synth_device.name = "softsynth";
synth_device.fops = &softsynth_fops;
if (misc_register(&synth_device)) {
pr_warn("Couldn't initialize miscdevice /dev/softsynth.\n");
return -ENODEV;
}
misc_registered = 1;
pr_info("initialized device: /dev/softsynth, node (MAJOR 10, MINOR 26)\n");
return 0;
}
static void softsynth_release(void)
{
misc_deregister(&synth_device);
misc_registered = 0;
pr_info("unregistered /dev/softsynth\n");
}
static int softsynth_is_alive(struct spk_synth *synth)
{
if (synth_soft.alive)
return 1;
return 0;
}
module_param_named(start, synth_soft.startup, short, S_IRUGO);
MODULE_PARM_DESC(start, "Start the synthesizer once it is loaded.");
static int __init soft_init(void)
{
return synth_add(&synth_soft);
}
static void __exit soft_exit(void)
{
synth_remove(&synth_soft);
}
module_init(soft_init);
module_exit(soft_exit);
MODULE_AUTHOR("Kirk Reiser <kirk@braille.uwo.ca>");
MODULE_DESCRIPTION("Speakup userspace software synthesizer support");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
| gpl-2.0 |
pseudonymous-foss/clydefs | drivers/gpu/drm/i915/intel_fb.c | 1996 | 8569 | /*
* Copyright © 2007 David Airlie
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Authors:
* David Airlie
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/tty.h>
#include <linux/sysrq.h>
#include <linux/delay.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/vga_switcheroo.h>
#include <drm/drmP.h>
#include <drm/drm_crtc.h>
#include <drm/drm_fb_helper.h>
#include "intel_drv.h"
#include <drm/i915_drm.h>
#include "i915_drv.h"
static struct fb_ops intelfb_ops = {
.owner = THIS_MODULE,
.fb_check_var = drm_fb_helper_check_var,
.fb_set_par = drm_fb_helper_set_par,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
.fb_pan_display = drm_fb_helper_pan_display,
.fb_blank = drm_fb_helper_blank,
.fb_setcmap = drm_fb_helper_setcmap,
.fb_debug_enter = drm_fb_helper_debug_enter,
.fb_debug_leave = drm_fb_helper_debug_leave,
};
static int intelfb_create(struct drm_fb_helper *helper,
struct drm_fb_helper_surface_size *sizes)
{
struct intel_fbdev *ifbdev = (struct intel_fbdev *)helper;
struct drm_device *dev = ifbdev->helper.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct fb_info *info;
struct drm_framebuffer *fb;
struct drm_mode_fb_cmd2 mode_cmd = {};
struct drm_i915_gem_object *obj;
struct device *device = &dev->pdev->dev;
int size, ret;
/* we don't do packed 24bpp */
if (sizes->surface_bpp == 24)
sizes->surface_bpp = 32;
mode_cmd.width = sizes->surface_width;
mode_cmd.height = sizes->surface_height;
mode_cmd.pitches[0] = ALIGN(mode_cmd.width * ((sizes->surface_bpp + 7) /
8), 64);
mode_cmd.pixel_format = drm_mode_legacy_fb_format(sizes->surface_bpp,
sizes->surface_depth);
size = mode_cmd.pitches[0] * mode_cmd.height;
size = ALIGN(size, PAGE_SIZE);
obj = i915_gem_object_create_stolen(dev, size);
if (obj == NULL)
obj = i915_gem_alloc_object(dev, size);
if (!obj) {
DRM_ERROR("failed to allocate framebuffer\n");
ret = -ENOMEM;
goto out;
}
mutex_lock(&dev->struct_mutex);
/* Flush everything out, we'll be doing GTT only from now on */
ret = intel_pin_and_fence_fb_obj(dev, obj, NULL);
if (ret) {
DRM_ERROR("failed to pin fb: %d\n", ret);
goto out_unref;
}
info = framebuffer_alloc(0, device);
if (!info) {
ret = -ENOMEM;
goto out_unpin;
}
info->par = ifbdev;
ret = intel_framebuffer_init(dev, &ifbdev->ifb, &mode_cmd, obj);
if (ret)
goto out_unpin;
fb = &ifbdev->ifb.base;
ifbdev->helper.fb = fb;
ifbdev->helper.fbdev = info;
strcpy(info->fix.id, "inteldrmfb");
info->flags = FBINFO_DEFAULT | FBINFO_CAN_FORCE_OUTPUT;
info->fbops = &intelfb_ops;
ret = fb_alloc_cmap(&info->cmap, 256, 0);
if (ret) {
ret = -ENOMEM;
goto out_unpin;
}
/* setup aperture base/size for vesafb takeover */
info->apertures = alloc_apertures(1);
if (!info->apertures) {
ret = -ENOMEM;
goto out_unpin;
}
info->apertures->ranges[0].base = dev->mode_config.fb_base;
info->apertures->ranges[0].size = dev_priv->gtt.mappable_end;
info->fix.smem_start = dev->mode_config.fb_base + obj->gtt_offset;
info->fix.smem_len = size;
info->screen_base =
ioremap_wc(dev_priv->gtt.mappable_base + obj->gtt_offset,
size);
if (!info->screen_base) {
ret = -ENOSPC;
goto out_unpin;
}
info->screen_size = size;
/* This driver doesn't need a VT switch to restore the mode on resume */
info->skip_vt_switch = true;
drm_fb_helper_fill_fix(info, fb->pitches[0], fb->depth);
drm_fb_helper_fill_var(info, &ifbdev->helper, sizes->fb_width, sizes->fb_height);
/* If the object is shmemfs backed, it will have given us zeroed pages.
* If the object is stolen however, it will be full of whatever
* garbage was left in there.
*/
if (ifbdev->ifb.obj->stolen)
memset_io(info->screen_base, 0, info->screen_size);
/* Use default scratch pixmap (info->pixmap.flags = FB_PIXMAP_SYSTEM) */
DRM_DEBUG_KMS("allocated %dx%d fb: 0x%08x, bo %p\n",
fb->width, fb->height,
obj->gtt_offset, obj);
mutex_unlock(&dev->struct_mutex);
vga_switcheroo_client_fb_set(dev->pdev, info);
return 0;
out_unpin:
i915_gem_object_unpin(obj);
out_unref:
drm_gem_object_unreference(&obj->base);
mutex_unlock(&dev->struct_mutex);
out:
return ret;
}
static struct drm_fb_helper_funcs intel_fb_helper_funcs = {
.gamma_set = intel_crtc_fb_gamma_set,
.gamma_get = intel_crtc_fb_gamma_get,
.fb_probe = intelfb_create,
};
static void intel_fbdev_destroy(struct drm_device *dev,
struct intel_fbdev *ifbdev)
{
struct fb_info *info;
struct intel_framebuffer *ifb = &ifbdev->ifb;
if (ifbdev->helper.fbdev) {
info = ifbdev->helper.fbdev;
unregister_framebuffer(info);
iounmap(info->screen_base);
if (info->cmap.len)
fb_dealloc_cmap(&info->cmap);
framebuffer_release(info);
}
drm_fb_helper_fini(&ifbdev->helper);
drm_framebuffer_unregister_private(&ifb->base);
drm_framebuffer_cleanup(&ifb->base);
if (ifb->obj) {
drm_gem_object_unreference_unlocked(&ifb->obj->base);
ifb->obj = NULL;
}
}
int intel_fbdev_init(struct drm_device *dev)
{
struct intel_fbdev *ifbdev;
drm_i915_private_t *dev_priv = dev->dev_private;
int ret;
ifbdev = kzalloc(sizeof(struct intel_fbdev), GFP_KERNEL);
if (!ifbdev)
return -ENOMEM;
dev_priv->fbdev = ifbdev;
ifbdev->helper.funcs = &intel_fb_helper_funcs;
ret = drm_fb_helper_init(dev, &ifbdev->helper,
INTEL_INFO(dev)->num_pipes,
INTELFB_CONN_LIMIT);
if (ret) {
kfree(ifbdev);
return ret;
}
drm_fb_helper_single_add_all_connectors(&ifbdev->helper);
return 0;
}
void intel_fbdev_initial_config(struct drm_device *dev)
{
drm_i915_private_t *dev_priv = dev->dev_private;
/* Due to peculiar init order wrt to hpd handling this is separate. */
drm_fb_helper_initial_config(&dev_priv->fbdev->helper, 32);
}
void intel_fbdev_fini(struct drm_device *dev)
{
drm_i915_private_t *dev_priv = dev->dev_private;
if (!dev_priv->fbdev)
return;
intel_fbdev_destroy(dev, dev_priv->fbdev);
kfree(dev_priv->fbdev);
dev_priv->fbdev = NULL;
}
void intel_fbdev_set_suspend(struct drm_device *dev, int state)
{
drm_i915_private_t *dev_priv = dev->dev_private;
struct intel_fbdev *ifbdev = dev_priv->fbdev;
struct fb_info *info;
if (!ifbdev)
return;
info = ifbdev->helper.fbdev;
/* On resume from hibernation: If the object is shmemfs backed, it has
* been restored from swap. If the object is stolen however, it will be
* full of whatever garbage was left in there.
*/
if (!state && ifbdev->ifb.obj->stolen)
memset_io(info->screen_base, 0, info->screen_size);
fb_set_suspend(info, state);
}
MODULE_LICENSE("GPL and additional rights");
void intel_fb_output_poll_changed(struct drm_device *dev)
{
drm_i915_private_t *dev_priv = dev->dev_private;
drm_fb_helper_hotplug_event(&dev_priv->fbdev->helper);
}
void intel_fb_restore_mode(struct drm_device *dev)
{
int ret;
drm_i915_private_t *dev_priv = dev->dev_private;
struct drm_mode_config *config = &dev->mode_config;
struct drm_plane *plane;
if (INTEL_INFO(dev)->num_pipes == 0)
return;
drm_modeset_lock_all(dev);
ret = drm_fb_helper_restore_fbdev_mode(&dev_priv->fbdev->helper);
if (ret)
DRM_DEBUG("failed to restore crtc mode\n");
/* Be sure to shut off any planes that may be active */
list_for_each_entry(plane, &config->plane_list, head)
if (plane->enabled)
plane->funcs->disable_plane(plane);
drm_modeset_unlock_all(dev);
}
| gpl-2.0 |
bju2000/android_kernel_samsung_slteskt | drivers/media/usb/gspca/sq905c.c | 2252 | 9818 | /*
* SQ905C subdriver
*
* Copyright (C) 2009 Theodore Kilgore
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
*
* This driver uses work done in
* libgphoto2/camlibs/digigr8, Copyright (C) Theodore Kilgore.
*
* This driver has also used as a base the sq905c driver
* and may contain code fragments from it.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define MODULE_NAME "sq905c"
#include <linux/workqueue.h>
#include <linux/slab.h>
#include "gspca.h"
MODULE_AUTHOR("Theodore Kilgore <kilgota@auburn.edu>");
MODULE_DESCRIPTION("GSPCA/SQ905C USB Camera Driver");
MODULE_LICENSE("GPL");
/* Default timeouts, in ms */
#define SQ905C_CMD_TIMEOUT 500
#define SQ905C_DATA_TIMEOUT 1000
/* Maximum transfer size to use. */
#define SQ905C_MAX_TRANSFER 0x8000
#define FRAME_HEADER_LEN 0x50
/* Commands. These go in the "value" slot. */
#define SQ905C_CLEAR 0xa0 /* clear everything */
#define SQ905C_GET_ID 0x14f4 /* Read version number */
#define SQ905C_CAPTURE_LOW 0xa040 /* Starts capture at 160x120 */
#define SQ905C_CAPTURE_MED 0x1440 /* Starts capture at 320x240 */
#define SQ905C_CAPTURE_HI 0x2840 /* Starts capture at 320x240 */
/* For capture, this must go in the "index" slot. */
#define SQ905C_CAPTURE_INDEX 0x110f
/* Structure to hold all of our device specific stuff */
struct sd {
struct gspca_dev gspca_dev; /* !! must be the first item */
const struct v4l2_pix_format *cap_mode;
/* Driver stuff */
struct work_struct work_struct;
struct workqueue_struct *work_thread;
};
/*
* Most of these cameras will do 640x480 and 320x240. 160x120 works
* in theory but gives very poor output. Therefore, not supported.
* The 0x2770:0x9050 cameras have max resolution of 320x240.
*/
static struct v4l2_pix_format sq905c_mode[] = {
{ 320, 240, V4L2_PIX_FMT_SQ905C, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 0},
{ 640, 480, V4L2_PIX_FMT_SQ905C, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 0}
};
/* Send a command to the camera. */
static int sq905c_command(struct gspca_dev *gspca_dev, u16 command, u16 index)
{
int ret;
ret = usb_control_msg(gspca_dev->dev,
usb_sndctrlpipe(gspca_dev->dev, 0),
USB_REQ_SYNCH_FRAME, /* request */
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
command, index, NULL, 0,
SQ905C_CMD_TIMEOUT);
if (ret < 0) {
pr_err("%s: usb_control_msg failed (%d)\n", __func__, ret);
return ret;
}
return 0;
}
static int sq905c_read(struct gspca_dev *gspca_dev, u16 command, u16 index,
int size)
{
int ret;
ret = usb_control_msg(gspca_dev->dev,
usb_rcvctrlpipe(gspca_dev->dev, 0),
USB_REQ_SYNCH_FRAME, /* request */
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
command, index, gspca_dev->usb_buf, size,
SQ905C_CMD_TIMEOUT);
if (ret < 0) {
pr_err("%s: usb_control_msg failed (%d)\n", __func__, ret);
return ret;
}
return 0;
}
/*
* This function is called as a workqueue function and runs whenever the camera
* is streaming data. Because it is a workqueue function it is allowed to sleep
* so we can use synchronous USB calls. To avoid possible collisions with other
* threads attempting to use gspca_dev->usb_buf we take the usb_lock when
* performing USB operations using it. In practice we don't really need this
* as the camera doesn't provide any controls.
*/
static void sq905c_dostream(struct work_struct *work)
{
struct sd *dev = container_of(work, struct sd, work_struct);
struct gspca_dev *gspca_dev = &dev->gspca_dev;
int bytes_left; /* bytes remaining in current frame. */
int data_len; /* size to use for the next read. */
int act_len;
int packet_type;
int ret;
u8 *buffer;
buffer = kmalloc(SQ905C_MAX_TRANSFER, GFP_KERNEL | GFP_DMA);
if (!buffer) {
pr_err("Couldn't allocate USB buffer\n");
goto quit_stream;
}
while (gspca_dev->present && gspca_dev->streaming) {
#ifdef CONFIG_PM
if (gspca_dev->frozen)
break;
#endif
/* Request the header, which tells the size to download */
ret = usb_bulk_msg(gspca_dev->dev,
usb_rcvbulkpipe(gspca_dev->dev, 0x81),
buffer, FRAME_HEADER_LEN, &act_len,
SQ905C_DATA_TIMEOUT);
PDEBUG(D_STREAM,
"Got %d bytes out of %d for header",
act_len, FRAME_HEADER_LEN);
if (ret < 0 || act_len < FRAME_HEADER_LEN)
goto quit_stream;
/* size is read from 4 bytes starting 0x40, little endian */
bytes_left = buffer[0x40]|(buffer[0x41]<<8)|(buffer[0x42]<<16)
|(buffer[0x43]<<24);
PDEBUG(D_STREAM, "bytes_left = 0x%x", bytes_left);
/* We keep the header. It has other information, too. */
packet_type = FIRST_PACKET;
gspca_frame_add(gspca_dev, packet_type,
buffer, FRAME_HEADER_LEN);
while (bytes_left > 0 && gspca_dev->present) {
data_len = bytes_left > SQ905C_MAX_TRANSFER ?
SQ905C_MAX_TRANSFER : bytes_left;
ret = usb_bulk_msg(gspca_dev->dev,
usb_rcvbulkpipe(gspca_dev->dev, 0x81),
buffer, data_len, &act_len,
SQ905C_DATA_TIMEOUT);
if (ret < 0 || act_len < data_len)
goto quit_stream;
PDEBUG(D_STREAM,
"Got %d bytes out of %d for frame",
data_len, bytes_left);
bytes_left -= data_len;
if (bytes_left == 0)
packet_type = LAST_PACKET;
else
packet_type = INTER_PACKET;
gspca_frame_add(gspca_dev, packet_type,
buffer, data_len);
}
}
quit_stream:
if (gspca_dev->present) {
mutex_lock(&gspca_dev->usb_lock);
sq905c_command(gspca_dev, SQ905C_CLEAR, 0);
mutex_unlock(&gspca_dev->usb_lock);
}
kfree(buffer);
}
/* This function is called at probe time just before sd_init */
static int sd_config(struct gspca_dev *gspca_dev,
const struct usb_device_id *id)
{
struct cam *cam = &gspca_dev->cam;
struct sd *dev = (struct sd *) gspca_dev;
int ret;
PDEBUG(D_PROBE,
"SQ9050 camera detected"
" (vid/pid 0x%04X:0x%04X)", id->idVendor, id->idProduct);
ret = sq905c_command(gspca_dev, SQ905C_GET_ID, 0);
if (ret < 0) {
PERR("Get version command failed");
return ret;
}
ret = sq905c_read(gspca_dev, 0xf5, 0, 20);
if (ret < 0) {
PERR("Reading version command failed");
return ret;
}
/* Note we leave out the usb id and the manufacturing date */
PDEBUG(D_PROBE,
"SQ9050 ID string: %02x - %*ph",
gspca_dev->usb_buf[3], 6, gspca_dev->usb_buf + 14);
cam->cam_mode = sq905c_mode;
cam->nmodes = 2;
if (gspca_dev->usb_buf[15] == 0)
cam->nmodes = 1;
/* We don't use the buffer gspca allocates so make it small. */
cam->bulk_size = 32;
cam->bulk = 1;
INIT_WORK(&dev->work_struct, sq905c_dostream);
return 0;
}
/* called on streamoff with alt==0 and on disconnect */
/* the usb_lock is held at entry - restore on exit */
static void sd_stop0(struct gspca_dev *gspca_dev)
{
struct sd *dev = (struct sd *) gspca_dev;
/* wait for the work queue to terminate */
mutex_unlock(&gspca_dev->usb_lock);
/* This waits for sq905c_dostream to finish */
destroy_workqueue(dev->work_thread);
dev->work_thread = NULL;
mutex_lock(&gspca_dev->usb_lock);
}
/* this function is called at probe and resume time */
static int sd_init(struct gspca_dev *gspca_dev)
{
int ret;
/* connect to the camera and reset it. */
ret = sq905c_command(gspca_dev, SQ905C_CLEAR, 0);
return ret;
}
/* Set up for getting frames. */
static int sd_start(struct gspca_dev *gspca_dev)
{
struct sd *dev = (struct sd *) gspca_dev;
int ret;
dev->cap_mode = gspca_dev->cam.cam_mode;
/* "Open the shutter" and set size, to start capture */
switch (gspca_dev->width) {
case 640:
PDEBUG(D_STREAM, "Start streaming at high resolution");
dev->cap_mode++;
ret = sq905c_command(gspca_dev, SQ905C_CAPTURE_HI,
SQ905C_CAPTURE_INDEX);
break;
default: /* 320 */
PDEBUG(D_STREAM, "Start streaming at medium resolution");
ret = sq905c_command(gspca_dev, SQ905C_CAPTURE_MED,
SQ905C_CAPTURE_INDEX);
}
if (ret < 0) {
PERR("Start streaming command failed");
return ret;
}
/* Start the workqueue function to do the streaming */
dev->work_thread = create_singlethread_workqueue(MODULE_NAME);
queue_work(dev->work_thread, &dev->work_struct);
return 0;
}
/* Table of supported USB devices */
static const struct usb_device_id device_table[] = {
{USB_DEVICE(0x2770, 0x905c)},
{USB_DEVICE(0x2770, 0x9050)},
{USB_DEVICE(0x2770, 0x9051)},
{USB_DEVICE(0x2770, 0x9052)},
{USB_DEVICE(0x2770, 0x913d)},
{}
};
MODULE_DEVICE_TABLE(usb, device_table);
/* sub-driver description */
static const struct sd_desc sd_desc = {
.name = MODULE_NAME,
.config = sd_config,
.init = sd_init,
.start = sd_start,
.stop0 = sd_stop0,
};
/* -- device connect -- */
static int sd_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
return gspca_dev_probe(intf, id,
&sd_desc,
sizeof(struct sd),
THIS_MODULE);
}
static struct usb_driver sd_driver = {
.name = MODULE_NAME,
.id_table = device_table,
.probe = sd_probe,
.disconnect = gspca_disconnect,
#ifdef CONFIG_PM
.suspend = gspca_suspend,
.resume = gspca_resume,
.reset_resume = gspca_resume,
#endif
};
module_usb_driver(sd_driver);
| gpl-2.0 |
zparallax/amplitude-kk-tw | drivers/net/ethernet/intel/e1000e/mac.c | 2764 | 47876 | /*******************************************************************************
Intel PRO/1000 Linux driver
Copyright(c) 1999 - 2012 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
Linux NICS <linux.nics@intel.com>
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#include "e1000.h"
/**
* e1000e_get_bus_info_pcie - Get PCIe bus information
* @hw: pointer to the HW structure
*
* Determines and stores the system bus information for a particular
* network interface. The following bus information is determined and stored:
* bus speed, bus width, type (PCIe), and PCIe function.
**/
s32 e1000e_get_bus_info_pcie(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
struct e1000_bus_info *bus = &hw->bus;
struct e1000_adapter *adapter = hw->adapter;
u16 pcie_link_status, cap_offset;
cap_offset = adapter->pdev->pcie_cap;
if (!cap_offset) {
bus->width = e1000_bus_width_unknown;
} else {
pci_read_config_word(adapter->pdev,
cap_offset + PCIE_LINK_STATUS,
&pcie_link_status);
bus->width = (enum e1000_bus_width)((pcie_link_status &
PCIE_LINK_WIDTH_MASK) >>
PCIE_LINK_WIDTH_SHIFT);
}
mac->ops.set_lan_id(hw);
return 0;
}
/**
* e1000_set_lan_id_multi_port_pcie - Set LAN id for PCIe multiple port devices
*
* @hw: pointer to the HW structure
*
* Determines the LAN function id by reading memory-mapped registers
* and swaps the port value if requested.
**/
void e1000_set_lan_id_multi_port_pcie(struct e1000_hw *hw)
{
struct e1000_bus_info *bus = &hw->bus;
u32 reg;
/*
* The status register reports the correct function number
* for the device regardless of function swap state.
*/
reg = er32(STATUS);
bus->func = (reg & E1000_STATUS_FUNC_MASK) >> E1000_STATUS_FUNC_SHIFT;
}
/**
* e1000_set_lan_id_single_port - Set LAN id for a single port device
* @hw: pointer to the HW structure
*
* Sets the LAN function id to zero for a single port device.
**/
void e1000_set_lan_id_single_port(struct e1000_hw *hw)
{
struct e1000_bus_info *bus = &hw->bus;
bus->func = 0;
}
/**
* e1000_clear_vfta_generic - Clear VLAN filter table
* @hw: pointer to the HW structure
*
* Clears the register array which contains the VLAN filter table by
* setting all the values to 0.
**/
void e1000_clear_vfta_generic(struct e1000_hw *hw)
{
u32 offset;
for (offset = 0; offset < E1000_VLAN_FILTER_TBL_SIZE; offset++) {
E1000_WRITE_REG_ARRAY(hw, E1000_VFTA, offset, 0);
e1e_flush();
}
}
/**
* e1000_write_vfta_generic - Write value to VLAN filter table
* @hw: pointer to the HW structure
* @offset: register offset in VLAN filter table
* @value: register value written to VLAN filter table
*
* Writes value at the given offset in the register array which stores
* the VLAN filter table.
**/
void e1000_write_vfta_generic(struct e1000_hw *hw, u32 offset, u32 value)
{
E1000_WRITE_REG_ARRAY(hw, E1000_VFTA, offset, value);
e1e_flush();
}
/**
* e1000e_init_rx_addrs - Initialize receive address's
* @hw: pointer to the HW structure
* @rar_count: receive address registers
*
* Setup the receive address registers by setting the base receive address
* register to the devices MAC address and clearing all the other receive
* address registers to 0.
**/
void e1000e_init_rx_addrs(struct e1000_hw *hw, u16 rar_count)
{
u32 i;
u8 mac_addr[ETH_ALEN] = { 0 };
/* Setup the receive address */
e_dbg("Programming MAC Address into RAR[0]\n");
e1000e_rar_set(hw, hw->mac.addr, 0);
/* Zero out the other (rar_entry_count - 1) receive addresses */
e_dbg("Clearing RAR[1-%u]\n", rar_count - 1);
for (i = 1; i < rar_count; i++)
e1000e_rar_set(hw, mac_addr, i);
}
/**
* e1000_check_alt_mac_addr_generic - Check for alternate MAC addr
* @hw: pointer to the HW structure
*
* Checks the nvm for an alternate MAC address. An alternate MAC address
* can be setup by pre-boot software and must be treated like a permanent
* address and must override the actual permanent MAC address. If an
* alternate MAC address is found it is programmed into RAR0, replacing
* the permanent address that was installed into RAR0 by the Si on reset.
* This function will return SUCCESS unless it encounters an error while
* reading the EEPROM.
**/
s32 e1000_check_alt_mac_addr_generic(struct e1000_hw *hw)
{
u32 i;
s32 ret_val = 0;
u16 offset, nvm_alt_mac_addr_offset, nvm_data;
u8 alt_mac_addr[ETH_ALEN];
ret_val = e1000_read_nvm(hw, NVM_COMPAT, 1, &nvm_data);
if (ret_val)
return ret_val;
/* not supported on 82573 */
if (hw->mac.type == e1000_82573)
return 0;
ret_val = e1000_read_nvm(hw, NVM_ALT_MAC_ADDR_PTR, 1,
&nvm_alt_mac_addr_offset);
if (ret_val) {
e_dbg("NVM Read Error\n");
return ret_val;
}
if ((nvm_alt_mac_addr_offset == 0xFFFF) ||
(nvm_alt_mac_addr_offset == 0x0000))
/* There is no Alternate MAC Address */
return 0;
if (hw->bus.func == E1000_FUNC_1)
nvm_alt_mac_addr_offset += E1000_ALT_MAC_ADDRESS_OFFSET_LAN1;
for (i = 0; i < ETH_ALEN; i += 2) {
offset = nvm_alt_mac_addr_offset + (i >> 1);
ret_val = e1000_read_nvm(hw, offset, 1, &nvm_data);
if (ret_val) {
e_dbg("NVM Read Error\n");
return ret_val;
}
alt_mac_addr[i] = (u8)(nvm_data & 0xFF);
alt_mac_addr[i + 1] = (u8)(nvm_data >> 8);
}
/* if multicast bit is set, the alternate address will not be used */
if (is_multicast_ether_addr(alt_mac_addr)) {
e_dbg("Ignoring Alternate Mac Address with MC bit set\n");
return 0;
}
/*
* We have a valid alternate MAC address, and we want to treat it the
* same as the normal permanent MAC address stored by the HW into the
* RAR. Do this by mapping this address into RAR0.
*/
e1000e_rar_set(hw, alt_mac_addr, 0);
return 0;
}
/**
* e1000e_rar_set - Set receive address register
* @hw: pointer to the HW structure
* @addr: pointer to the receive address
* @index: receive address array register
*
* Sets the receive address array register at index to the address passed
* in by addr.
**/
void e1000e_rar_set(struct e1000_hw *hw, u8 *addr, u32 index)
{
u32 rar_low, rar_high;
/*
* HW expects these in little endian so we reverse the byte order
* from network order (big endian) to little endian
*/
rar_low = ((u32)addr[0] | ((u32)addr[1] << 8) |
((u32)addr[2] << 16) | ((u32)addr[3] << 24));
rar_high = ((u32)addr[4] | ((u32)addr[5] << 8));
/* If MAC address zero, no need to set the AV bit */
if (rar_low || rar_high)
rar_high |= E1000_RAH_AV;
/*
* Some bridges will combine consecutive 32-bit writes into
* a single burst write, which will malfunction on some parts.
* The flushes avoid this.
*/
ew32(RAL(index), rar_low);
e1e_flush();
ew32(RAH(index), rar_high);
e1e_flush();
}
/**
* e1000_hash_mc_addr - Generate a multicast hash value
* @hw: pointer to the HW structure
* @mc_addr: pointer to a multicast address
*
* Generates a multicast address hash value which is used to determine
* the multicast filter table array address and new table value.
**/
static u32 e1000_hash_mc_addr(struct e1000_hw *hw, u8 *mc_addr)
{
u32 hash_value, hash_mask;
u8 bit_shift = 0;
/* Register count multiplied by bits per register */
hash_mask = (hw->mac.mta_reg_count * 32) - 1;
/*
* For a mc_filter_type of 0, bit_shift is the number of left-shifts
* where 0xFF would still fall within the hash mask.
*/
while (hash_mask >> bit_shift != 0xFF)
bit_shift++;
/*
* The portion of the address that is used for the hash table
* is determined by the mc_filter_type setting.
* The algorithm is such that there is a total of 8 bits of shifting.
* The bit_shift for a mc_filter_type of 0 represents the number of
* left-shifts where the MSB of mc_addr[5] would still fall within
* the hash_mask. Case 0 does this exactly. Since there are a total
* of 8 bits of shifting, then mc_addr[4] will shift right the
* remaining number of bits. Thus 8 - bit_shift. The rest of the
* cases are a variation of this algorithm...essentially raising the
* number of bits to shift mc_addr[5] left, while still keeping the
* 8-bit shifting total.
*
* For example, given the following Destination MAC Address and an
* mta register count of 128 (thus a 4096-bit vector and 0xFFF mask),
* we can see that the bit_shift for case 0 is 4. These are the hash
* values resulting from each mc_filter_type...
* [0] [1] [2] [3] [4] [5]
* 01 AA 00 12 34 56
* LSB MSB
*
* case 0: hash_value = ((0x34 >> 4) | (0x56 << 4)) & 0xFFF = 0x563
* case 1: hash_value = ((0x34 >> 3) | (0x56 << 5)) & 0xFFF = 0xAC6
* case 2: hash_value = ((0x34 >> 2) | (0x56 << 6)) & 0xFFF = 0x163
* case 3: hash_value = ((0x34 >> 0) | (0x56 << 8)) & 0xFFF = 0x634
*/
switch (hw->mac.mc_filter_type) {
default:
case 0:
break;
case 1:
bit_shift += 1;
break;
case 2:
bit_shift += 2;
break;
case 3:
bit_shift += 4;
break;
}
hash_value = hash_mask & (((mc_addr[4] >> (8 - bit_shift)) |
(((u16)mc_addr[5]) << bit_shift)));
return hash_value;
}
/**
* e1000e_update_mc_addr_list_generic - Update Multicast addresses
* @hw: pointer to the HW structure
* @mc_addr_list: array of multicast addresses to program
* @mc_addr_count: number of multicast addresses to program
*
* Updates entire Multicast Table Array.
* The caller must have a packed mc_addr_list of multicast addresses.
**/
void e1000e_update_mc_addr_list_generic(struct e1000_hw *hw,
u8 *mc_addr_list, u32 mc_addr_count)
{
u32 hash_value, hash_bit, hash_reg;
int i;
/* clear mta_shadow */
memset(&hw->mac.mta_shadow, 0, sizeof(hw->mac.mta_shadow));
/* update mta_shadow from mc_addr_list */
for (i = 0; (u32)i < mc_addr_count; i++) {
hash_value = e1000_hash_mc_addr(hw, mc_addr_list);
hash_reg = (hash_value >> 5) & (hw->mac.mta_reg_count - 1);
hash_bit = hash_value & 0x1F;
hw->mac.mta_shadow[hash_reg] |= (1 << hash_bit);
mc_addr_list += (ETH_ALEN);
}
/* replace the entire MTA table */
for (i = hw->mac.mta_reg_count - 1; i >= 0; i--)
E1000_WRITE_REG_ARRAY(hw, E1000_MTA, i, hw->mac.mta_shadow[i]);
e1e_flush();
}
/**
* e1000e_clear_hw_cntrs_base - Clear base hardware counters
* @hw: pointer to the HW structure
*
* Clears the base hardware counters by reading the counter registers.
**/
void e1000e_clear_hw_cntrs_base(struct e1000_hw *hw)
{
er32(CRCERRS);
er32(SYMERRS);
er32(MPC);
er32(SCC);
er32(ECOL);
er32(MCC);
er32(LATECOL);
er32(COLC);
er32(DC);
er32(SEC);
er32(RLEC);
er32(XONRXC);
er32(XONTXC);
er32(XOFFRXC);
er32(XOFFTXC);
er32(FCRUC);
er32(GPRC);
er32(BPRC);
er32(MPRC);
er32(GPTC);
er32(GORCL);
er32(GORCH);
er32(GOTCL);
er32(GOTCH);
er32(RNBC);
er32(RUC);
er32(RFC);
er32(ROC);
er32(RJC);
er32(TORL);
er32(TORH);
er32(TOTL);
er32(TOTH);
er32(TPR);
er32(TPT);
er32(MPTC);
er32(BPTC);
}
/**
* e1000e_check_for_copper_link - Check for link (Copper)
* @hw: pointer to the HW structure
*
* Checks to see of the link status of the hardware has changed. If a
* change in link status has been detected, then we read the PHY registers
* to get the current speed/duplex if link exists.
**/
s32 e1000e_check_for_copper_link(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
s32 ret_val;
bool link;
/*
* We only want to go out to the PHY registers to see if Auto-Neg
* has completed and/or if our link status has changed. The
* get_link_status flag is set upon receiving a Link Status
* Change or Rx Sequence Error interrupt.
*/
if (!mac->get_link_status)
return 0;
/*
* First we want to see if the MII Status Register reports
* link. If so, then we want to get the current speed/duplex
* of the PHY.
*/
ret_val = e1000e_phy_has_link_generic(hw, 1, 0, &link);
if (ret_val)
return ret_val;
if (!link)
return 0; /* No link detected */
mac->get_link_status = false;
/*
* Check if there was DownShift, must be checked
* immediately after link-up
*/
e1000e_check_downshift(hw);
/*
* If we are forcing speed/duplex, then we simply return since
* we have already determined whether we have link or not.
*/
if (!mac->autoneg)
return -E1000_ERR_CONFIG;
/*
* Auto-Neg is enabled. Auto Speed Detection takes care
* of MAC speed/duplex configuration. So we only need to
* configure Collision Distance in the MAC.
*/
mac->ops.config_collision_dist(hw);
/*
* Configure Flow Control now that Auto-Neg has completed.
* First, we need to restore the desired flow control
* settings because we may have had to re-autoneg with a
* different link partner.
*/
ret_val = e1000e_config_fc_after_link_up(hw);
if (ret_val)
e_dbg("Error configuring flow control\n");
return ret_val;
}
/**
* e1000e_check_for_fiber_link - Check for link (Fiber)
* @hw: pointer to the HW structure
*
* Checks for link up on the hardware. If link is not up and we have
* a signal, then we need to force link up.
**/
s32 e1000e_check_for_fiber_link(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
u32 rxcw;
u32 ctrl;
u32 status;
s32 ret_val;
ctrl = er32(CTRL);
status = er32(STATUS);
rxcw = er32(RXCW);
/*
* If we don't have link (auto-negotiation failed or link partner
* cannot auto-negotiate), the cable is plugged in (we have signal),
* and our link partner is not trying to auto-negotiate with us (we
* are receiving idles or data), we need to force link up. We also
* need to give auto-negotiation time to complete, in case the cable
* was just plugged in. The autoneg_failed flag does this.
*/
/* (ctrl & E1000_CTRL_SWDPIN1) == 1 == have signal */
if ((ctrl & E1000_CTRL_SWDPIN1) && !(status & E1000_STATUS_LU) &&
!(rxcw & E1000_RXCW_C)) {
if (!mac->autoneg_failed) {
mac->autoneg_failed = true;
return 0;
}
e_dbg("NOT Rx'ing /C/, disable AutoNeg and force link.\n");
/* Disable auto-negotiation in the TXCW register */
ew32(TXCW, (mac->txcw & ~E1000_TXCW_ANE));
/* Force link-up and also force full-duplex. */
ctrl = er32(CTRL);
ctrl |= (E1000_CTRL_SLU | E1000_CTRL_FD);
ew32(CTRL, ctrl);
/* Configure Flow Control after forcing link up. */
ret_val = e1000e_config_fc_after_link_up(hw);
if (ret_val) {
e_dbg("Error configuring flow control\n");
return ret_val;
}
} else if ((ctrl & E1000_CTRL_SLU) && (rxcw & E1000_RXCW_C)) {
/*
* If we are forcing link and we are receiving /C/ ordered
* sets, re-enable auto-negotiation in the TXCW register
* and disable forced link in the Device Control register
* in an attempt to auto-negotiate with our link partner.
*/
e_dbg("Rx'ing /C/, enable AutoNeg and stop forcing link.\n");
ew32(TXCW, mac->txcw);
ew32(CTRL, (ctrl & ~E1000_CTRL_SLU));
mac->serdes_has_link = true;
}
return 0;
}
/**
* e1000e_check_for_serdes_link - Check for link (Serdes)
* @hw: pointer to the HW structure
*
* Checks for link up on the hardware. If link is not up and we have
* a signal, then we need to force link up.
**/
s32 e1000e_check_for_serdes_link(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
u32 rxcw;
u32 ctrl;
u32 status;
s32 ret_val;
ctrl = er32(CTRL);
status = er32(STATUS);
rxcw = er32(RXCW);
/*
* If we don't have link (auto-negotiation failed or link partner
* cannot auto-negotiate), and our link partner is not trying to
* auto-negotiate with us (we are receiving idles or data),
* we need to force link up. We also need to give auto-negotiation
* time to complete.
*/
/* (ctrl & E1000_CTRL_SWDPIN1) == 1 == have signal */
if (!(status & E1000_STATUS_LU) && !(rxcw & E1000_RXCW_C)) {
if (!mac->autoneg_failed) {
mac->autoneg_failed = true;
return 0;
}
e_dbg("NOT Rx'ing /C/, disable AutoNeg and force link.\n");
/* Disable auto-negotiation in the TXCW register */
ew32(TXCW, (mac->txcw & ~E1000_TXCW_ANE));
/* Force link-up and also force full-duplex. */
ctrl = er32(CTRL);
ctrl |= (E1000_CTRL_SLU | E1000_CTRL_FD);
ew32(CTRL, ctrl);
/* Configure Flow Control after forcing link up. */
ret_val = e1000e_config_fc_after_link_up(hw);
if (ret_val) {
e_dbg("Error configuring flow control\n");
return ret_val;
}
} else if ((ctrl & E1000_CTRL_SLU) && (rxcw & E1000_RXCW_C)) {
/*
* If we are forcing link and we are receiving /C/ ordered
* sets, re-enable auto-negotiation in the TXCW register
* and disable forced link in the Device Control register
* in an attempt to auto-negotiate with our link partner.
*/
e_dbg("Rx'ing /C/, enable AutoNeg and stop forcing link.\n");
ew32(TXCW, mac->txcw);
ew32(CTRL, (ctrl & ~E1000_CTRL_SLU));
mac->serdes_has_link = true;
} else if (!(E1000_TXCW_ANE & er32(TXCW))) {
/*
* If we force link for non-auto-negotiation switch, check
* link status based on MAC synchronization for internal
* serdes media type.
*/
/* SYNCH bit and IV bit are sticky. */
udelay(10);
rxcw = er32(RXCW);
if (rxcw & E1000_RXCW_SYNCH) {
if (!(rxcw & E1000_RXCW_IV)) {
mac->serdes_has_link = true;
e_dbg("SERDES: Link up - forced.\n");
}
} else {
mac->serdes_has_link = false;
e_dbg("SERDES: Link down - force failed.\n");
}
}
if (E1000_TXCW_ANE & er32(TXCW)) {
status = er32(STATUS);
if (status & E1000_STATUS_LU) {
/* SYNCH bit and IV bit are sticky, so reread rxcw. */
udelay(10);
rxcw = er32(RXCW);
if (rxcw & E1000_RXCW_SYNCH) {
if (!(rxcw & E1000_RXCW_IV)) {
mac->serdes_has_link = true;
e_dbg("SERDES: Link up - autoneg completed successfully.\n");
} else {
mac->serdes_has_link = false;
e_dbg("SERDES: Link down - invalid codewords detected in autoneg.\n");
}
} else {
mac->serdes_has_link = false;
e_dbg("SERDES: Link down - no sync.\n");
}
} else {
mac->serdes_has_link = false;
e_dbg("SERDES: Link down - autoneg failed\n");
}
}
return 0;
}
/**
* e1000_set_default_fc_generic - Set flow control default values
* @hw: pointer to the HW structure
*
* Read the EEPROM for the default values for flow control and store the
* values.
**/
static s32 e1000_set_default_fc_generic(struct e1000_hw *hw)
{
s32 ret_val;
u16 nvm_data;
/*
* Read and store word 0x0F of the EEPROM. This word contains bits
* that determine the hardware's default PAUSE (flow control) mode,
* a bit that determines whether the HW defaults to enabling or
* disabling auto-negotiation, and the direction of the
* SW defined pins. If there is no SW over-ride of the flow
* control setting, then the variable hw->fc will
* be initialized based on a value in the EEPROM.
*/
ret_val = e1000_read_nvm(hw, NVM_INIT_CONTROL2_REG, 1, &nvm_data);
if (ret_val) {
e_dbg("NVM Read Error\n");
return ret_val;
}
if ((nvm_data & NVM_WORD0F_PAUSE_MASK) == 0)
hw->fc.requested_mode = e1000_fc_none;
else if ((nvm_data & NVM_WORD0F_PAUSE_MASK) == NVM_WORD0F_ASM_DIR)
hw->fc.requested_mode = e1000_fc_tx_pause;
else
hw->fc.requested_mode = e1000_fc_full;
return 0;
}
/**
* e1000e_setup_link_generic - Setup flow control and link settings
* @hw: pointer to the HW structure
*
* Determines which flow control settings to use, then configures flow
* control. Calls the appropriate media-specific link configuration
* function. Assuming the adapter has a valid link partner, a valid link
* should be established. Assumes the hardware has previously been reset
* and the transmitter and receiver are not enabled.
**/
s32 e1000e_setup_link_generic(struct e1000_hw *hw)
{
s32 ret_val;
/*
* In the case of the phy reset being blocked, we already have a link.
* We do not need to set it up again.
*/
if (hw->phy.ops.check_reset_block(hw))
return 0;
/*
* If requested flow control is set to default, set flow control
* based on the EEPROM flow control settings.
*/
if (hw->fc.requested_mode == e1000_fc_default) {
ret_val = e1000_set_default_fc_generic(hw);
if (ret_val)
return ret_val;
}
/*
* Save off the requested flow control mode for use later. Depending
* on the link partner's capabilities, we may or may not use this mode.
*/
hw->fc.current_mode = hw->fc.requested_mode;
e_dbg("After fix-ups FlowControl is now = %x\n", hw->fc.current_mode);
/* Call the necessary media_type subroutine to configure the link. */
ret_val = hw->mac.ops.setup_physical_interface(hw);
if (ret_val)
return ret_val;
/*
* Initialize the flow control address, type, and PAUSE timer
* registers to their default values. This is done even if flow
* control is disabled, because it does not hurt anything to
* initialize these registers.
*/
e_dbg("Initializing the Flow Control address, type and timer regs\n");
ew32(FCT, FLOW_CONTROL_TYPE);
ew32(FCAH, FLOW_CONTROL_ADDRESS_HIGH);
ew32(FCAL, FLOW_CONTROL_ADDRESS_LOW);
ew32(FCTTV, hw->fc.pause_time);
return e1000e_set_fc_watermarks(hw);
}
/**
* e1000_commit_fc_settings_generic - Configure flow control
* @hw: pointer to the HW structure
*
* Write the flow control settings to the Transmit Config Word Register (TXCW)
* base on the flow control settings in e1000_mac_info.
**/
static s32 e1000_commit_fc_settings_generic(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
u32 txcw;
/*
* Check for a software override of the flow control settings, and
* setup the device accordingly. If auto-negotiation is enabled, then
* software will have to set the "PAUSE" bits to the correct value in
* the Transmit Config Word Register (TXCW) and re-start auto-
* negotiation. However, if auto-negotiation is disabled, then
* software will have to manually configure the two flow control enable
* bits in the CTRL register.
*
* The possible values of the "fc" parameter are:
* 0: Flow control is completely disabled
* 1: Rx flow control is enabled (we can receive pause frames,
* but not send pause frames).
* 2: Tx flow control is enabled (we can send pause frames but we
* do not support receiving pause frames).
* 3: Both Rx and Tx flow control (symmetric) are enabled.
*/
switch (hw->fc.current_mode) {
case e1000_fc_none:
/* Flow control completely disabled by a software over-ride. */
txcw = (E1000_TXCW_ANE | E1000_TXCW_FD);
break;
case e1000_fc_rx_pause:
/*
* Rx Flow control is enabled and Tx Flow control is disabled
* by a software over-ride. Since there really isn't a way to
* advertise that we are capable of Rx Pause ONLY, we will
* advertise that we support both symmetric and asymmetric Rx
* PAUSE. Later, we will disable the adapter's ability to send
* PAUSE frames.
*/
txcw = (E1000_TXCW_ANE | E1000_TXCW_FD | E1000_TXCW_PAUSE_MASK);
break;
case e1000_fc_tx_pause:
/*
* Tx Flow control is enabled, and Rx Flow control is disabled,
* by a software over-ride.
*/
txcw = (E1000_TXCW_ANE | E1000_TXCW_FD | E1000_TXCW_ASM_DIR);
break;
case e1000_fc_full:
/*
* Flow control (both Rx and Tx) is enabled by a software
* over-ride.
*/
txcw = (E1000_TXCW_ANE | E1000_TXCW_FD | E1000_TXCW_PAUSE_MASK);
break;
default:
e_dbg("Flow control param set incorrectly\n");
return -E1000_ERR_CONFIG;
break;
}
ew32(TXCW, txcw);
mac->txcw = txcw;
return 0;
}
/**
* e1000_poll_fiber_serdes_link_generic - Poll for link up
* @hw: pointer to the HW structure
*
* Polls for link up by reading the status register, if link fails to come
* up with auto-negotiation, then the link is forced if a signal is detected.
**/
static s32 e1000_poll_fiber_serdes_link_generic(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
u32 i, status;
s32 ret_val;
/*
* If we have a signal (the cable is plugged in, or assumed true for
* serdes media) then poll for a "Link-Up" indication in the Device
* Status Register. Time-out if a link isn't seen in 500 milliseconds
* seconds (Auto-negotiation should complete in less than 500
* milliseconds even if the other end is doing it in SW).
*/
for (i = 0; i < FIBER_LINK_UP_LIMIT; i++) {
usleep_range(10000, 20000);
status = er32(STATUS);
if (status & E1000_STATUS_LU)
break;
}
if (i == FIBER_LINK_UP_LIMIT) {
e_dbg("Never got a valid link from auto-neg!!!\n");
mac->autoneg_failed = true;
/*
* AutoNeg failed to achieve a link, so we'll call
* mac->check_for_link. This routine will force the
* link up if we detect a signal. This will allow us to
* communicate with non-autonegotiating link partners.
*/
ret_val = mac->ops.check_for_link(hw);
if (ret_val) {
e_dbg("Error while checking for link\n");
return ret_val;
}
mac->autoneg_failed = false;
} else {
mac->autoneg_failed = false;
e_dbg("Valid Link Found\n");
}
return 0;
}
/**
* e1000e_setup_fiber_serdes_link - Setup link for fiber/serdes
* @hw: pointer to the HW structure
*
* Configures collision distance and flow control for fiber and serdes
* links. Upon successful setup, poll for link.
**/
s32 e1000e_setup_fiber_serdes_link(struct e1000_hw *hw)
{
u32 ctrl;
s32 ret_val;
ctrl = er32(CTRL);
/* Take the link out of reset */
ctrl &= ~E1000_CTRL_LRST;
hw->mac.ops.config_collision_dist(hw);
ret_val = e1000_commit_fc_settings_generic(hw);
if (ret_val)
return ret_val;
/*
* Since auto-negotiation is enabled, take the link out of reset (the
* link will be in reset, because we previously reset the chip). This
* will restart auto-negotiation. If auto-negotiation is successful
* then the link-up status bit will be set and the flow control enable
* bits (RFCE and TFCE) will be set according to their negotiated value.
*/
e_dbg("Auto-negotiation enabled\n");
ew32(CTRL, ctrl);
e1e_flush();
usleep_range(1000, 2000);
/*
* For these adapters, the SW definable pin 1 is set when the optics
* detect a signal. If we have a signal, then poll for a "Link-Up"
* indication.
*/
if (hw->phy.media_type == e1000_media_type_internal_serdes ||
(er32(CTRL) & E1000_CTRL_SWDPIN1)) {
ret_val = e1000_poll_fiber_serdes_link_generic(hw);
} else {
e_dbg("No signal detected\n");
}
return ret_val;
}
/**
* e1000e_config_collision_dist_generic - Configure collision distance
* @hw: pointer to the HW structure
*
* Configures the collision distance to the default value and is used
* during link setup.
**/
void e1000e_config_collision_dist_generic(struct e1000_hw *hw)
{
u32 tctl;
tctl = er32(TCTL);
tctl &= ~E1000_TCTL_COLD;
tctl |= E1000_COLLISION_DISTANCE << E1000_COLD_SHIFT;
ew32(TCTL, tctl);
e1e_flush();
}
/**
* e1000e_set_fc_watermarks - Set flow control high/low watermarks
* @hw: pointer to the HW structure
*
* Sets the flow control high/low threshold (watermark) registers. If
* flow control XON frame transmission is enabled, then set XON frame
* transmission as well.
**/
s32 e1000e_set_fc_watermarks(struct e1000_hw *hw)
{
u32 fcrtl = 0, fcrth = 0;
/*
* Set the flow control receive threshold registers. Normally,
* these registers will be set to a default threshold that may be
* adjusted later by the driver's runtime code. However, if the
* ability to transmit pause frames is not enabled, then these
* registers will be set to 0.
*/
if (hw->fc.current_mode & e1000_fc_tx_pause) {
/*
* We need to set up the Receive Threshold high and low water
* marks as well as (optionally) enabling the transmission of
* XON frames.
*/
fcrtl = hw->fc.low_water;
if (hw->fc.send_xon)
fcrtl |= E1000_FCRTL_XONE;
fcrth = hw->fc.high_water;
}
ew32(FCRTL, fcrtl);
ew32(FCRTH, fcrth);
return 0;
}
/**
* e1000e_force_mac_fc - Force the MAC's flow control settings
* @hw: pointer to the HW structure
*
* Force the MAC's flow control settings. Sets the TFCE and RFCE bits in the
* device control register to reflect the adapter settings. TFCE and RFCE
* need to be explicitly set by software when a copper PHY is used because
* autonegotiation is managed by the PHY rather than the MAC. Software must
* also configure these bits when link is forced on a fiber connection.
**/
s32 e1000e_force_mac_fc(struct e1000_hw *hw)
{
u32 ctrl;
ctrl = er32(CTRL);
/*
* Because we didn't get link via the internal auto-negotiation
* mechanism (we either forced link or we got link via PHY
* auto-neg), we have to manually enable/disable transmit an
* receive flow control.
*
* The "Case" statement below enables/disable flow control
* according to the "hw->fc.current_mode" parameter.
*
* The possible values of the "fc" parameter are:
* 0: Flow control is completely disabled
* 1: Rx flow control is enabled (we can receive pause
* frames but not send pause frames).
* 2: Tx flow control is enabled (we can send pause frames
* frames but we do not receive pause frames).
* 3: Both Rx and Tx flow control (symmetric) is enabled.
* other: No other values should be possible at this point.
*/
e_dbg("hw->fc.current_mode = %u\n", hw->fc.current_mode);
switch (hw->fc.current_mode) {
case e1000_fc_none:
ctrl &= (~(E1000_CTRL_TFCE | E1000_CTRL_RFCE));
break;
case e1000_fc_rx_pause:
ctrl &= (~E1000_CTRL_TFCE);
ctrl |= E1000_CTRL_RFCE;
break;
case e1000_fc_tx_pause:
ctrl &= (~E1000_CTRL_RFCE);
ctrl |= E1000_CTRL_TFCE;
break;
case e1000_fc_full:
ctrl |= (E1000_CTRL_TFCE | E1000_CTRL_RFCE);
break;
default:
e_dbg("Flow control param set incorrectly\n");
return -E1000_ERR_CONFIG;
}
ew32(CTRL, ctrl);
return 0;
}
/**
* e1000e_config_fc_after_link_up - Configures flow control after link
* @hw: pointer to the HW structure
*
* Checks the status of auto-negotiation after link up to ensure that the
* speed and duplex were not forced. If the link needed to be forced, then
* flow control needs to be forced also. If auto-negotiation is enabled
* and did not fail, then we configure flow control based on our link
* partner.
**/
s32 e1000e_config_fc_after_link_up(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
s32 ret_val = 0;
u16 mii_status_reg, mii_nway_adv_reg, mii_nway_lp_ability_reg;
u16 speed, duplex;
/*
* Check for the case where we have fiber media and auto-neg failed
* so we had to force link. In this case, we need to force the
* configuration of the MAC to match the "fc" parameter.
*/
if (mac->autoneg_failed) {
if (hw->phy.media_type == e1000_media_type_fiber ||
hw->phy.media_type == e1000_media_type_internal_serdes)
ret_val = e1000e_force_mac_fc(hw);
} else {
if (hw->phy.media_type == e1000_media_type_copper)
ret_val = e1000e_force_mac_fc(hw);
}
if (ret_val) {
e_dbg("Error forcing flow control settings\n");
return ret_val;
}
/*
* Check for the case where we have copper media and auto-neg is
* enabled. In this case, we need to check and see if Auto-Neg
* has completed, and if so, how the PHY and link partner has
* flow control configured.
*/
if ((hw->phy.media_type == e1000_media_type_copper) && mac->autoneg) {
/*
* Read the MII Status Register and check to see if AutoNeg
* has completed. We read this twice because this reg has
* some "sticky" (latched) bits.
*/
ret_val = e1e_rphy(hw, PHY_STATUS, &mii_status_reg);
if (ret_val)
return ret_val;
ret_val = e1e_rphy(hw, PHY_STATUS, &mii_status_reg);
if (ret_val)
return ret_val;
if (!(mii_status_reg & MII_SR_AUTONEG_COMPLETE)) {
e_dbg("Copper PHY and Auto Neg has not completed.\n");
return ret_val;
}
/*
* The AutoNeg process has completed, so we now need to
* read both the Auto Negotiation Advertisement
* Register (Address 4) and the Auto_Negotiation Base
* Page Ability Register (Address 5) to determine how
* flow control was negotiated.
*/
ret_val = e1e_rphy(hw, PHY_AUTONEG_ADV, &mii_nway_adv_reg);
if (ret_val)
return ret_val;
ret_val =
e1e_rphy(hw, PHY_LP_ABILITY, &mii_nway_lp_ability_reg);
if (ret_val)
return ret_val;
/*
* Two bits in the Auto Negotiation Advertisement Register
* (Address 4) and two bits in the Auto Negotiation Base
* Page Ability Register (Address 5) determine flow control
* for both the PHY and the link partner. The following
* table, taken out of the IEEE 802.3ab/D6.0 dated March 25,
* 1999, describes these PAUSE resolution bits and how flow
* control is determined based upon these settings.
* NOTE: DC = Don't Care
*
* LOCAL DEVICE | LINK PARTNER
* PAUSE | ASM_DIR | PAUSE | ASM_DIR | NIC Resolution
*-------|---------|-------|---------|--------------------
* 0 | 0 | DC | DC | e1000_fc_none
* 0 | 1 | 0 | DC | e1000_fc_none
* 0 | 1 | 1 | 0 | e1000_fc_none
* 0 | 1 | 1 | 1 | e1000_fc_tx_pause
* 1 | 0 | 0 | DC | e1000_fc_none
* 1 | DC | 1 | DC | e1000_fc_full
* 1 | 1 | 0 | 0 | e1000_fc_none
* 1 | 1 | 0 | 1 | e1000_fc_rx_pause
*
* Are both PAUSE bits set to 1? If so, this implies
* Symmetric Flow Control is enabled at both ends. The
* ASM_DIR bits are irrelevant per the spec.
*
* For Symmetric Flow Control:
*
* LOCAL DEVICE | LINK PARTNER
* PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result
*-------|---------|-------|---------|--------------------
* 1 | DC | 1 | DC | E1000_fc_full
*
*/
if ((mii_nway_adv_reg & NWAY_AR_PAUSE) &&
(mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE)) {
/*
* Now we need to check if the user selected Rx ONLY
* of pause frames. In this case, we had to advertise
* FULL flow control because we could not advertise Rx
* ONLY. Hence, we must now check to see if we need to
* turn OFF the TRANSMISSION of PAUSE frames.
*/
if (hw->fc.requested_mode == e1000_fc_full) {
hw->fc.current_mode = e1000_fc_full;
e_dbg("Flow Control = FULL.\n");
} else {
hw->fc.current_mode = e1000_fc_rx_pause;
e_dbg("Flow Control = Rx PAUSE frames only.\n");
}
}
/*
* For receiving PAUSE frames ONLY.
*
* LOCAL DEVICE | LINK PARTNER
* PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result
*-------|---------|-------|---------|--------------------
* 0 | 1 | 1 | 1 | e1000_fc_tx_pause
*/
else if (!(mii_nway_adv_reg & NWAY_AR_PAUSE) &&
(mii_nway_adv_reg & NWAY_AR_ASM_DIR) &&
(mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE) &&
(mii_nway_lp_ability_reg & NWAY_LPAR_ASM_DIR)) {
hw->fc.current_mode = e1000_fc_tx_pause;
e_dbg("Flow Control = Tx PAUSE frames only.\n");
}
/*
* For transmitting PAUSE frames ONLY.
*
* LOCAL DEVICE | LINK PARTNER
* PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result
*-------|---------|-------|---------|--------------------
* 1 | 1 | 0 | 1 | e1000_fc_rx_pause
*/
else if ((mii_nway_adv_reg & NWAY_AR_PAUSE) &&
(mii_nway_adv_reg & NWAY_AR_ASM_DIR) &&
!(mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE) &&
(mii_nway_lp_ability_reg & NWAY_LPAR_ASM_DIR)) {
hw->fc.current_mode = e1000_fc_rx_pause;
e_dbg("Flow Control = Rx PAUSE frames only.\n");
} else {
/*
* Per the IEEE spec, at this point flow control
* should be disabled.
*/
hw->fc.current_mode = e1000_fc_none;
e_dbg("Flow Control = NONE.\n");
}
/*
* Now we need to do one last check... If we auto-
* negotiated to HALF DUPLEX, flow control should not be
* enabled per IEEE 802.3 spec.
*/
ret_val = mac->ops.get_link_up_info(hw, &speed, &duplex);
if (ret_val) {
e_dbg("Error getting link speed and duplex\n");
return ret_val;
}
if (duplex == HALF_DUPLEX)
hw->fc.current_mode = e1000_fc_none;
/*
* Now we call a subroutine to actually force the MAC
* controller to use the correct flow control settings.
*/
ret_val = e1000e_force_mac_fc(hw);
if (ret_val) {
e_dbg("Error forcing flow control settings\n");
return ret_val;
}
}
return 0;
}
/**
* e1000e_get_speed_and_duplex_copper - Retrieve current speed/duplex
* @hw: pointer to the HW structure
* @speed: stores the current speed
* @duplex: stores the current duplex
*
* Read the status register for the current speed/duplex and store the current
* speed and duplex for copper connections.
**/
s32 e1000e_get_speed_and_duplex_copper(struct e1000_hw *hw, u16 *speed,
u16 *duplex)
{
u32 status;
status = er32(STATUS);
if (status & E1000_STATUS_SPEED_1000)
*speed = SPEED_1000;
else if (status & E1000_STATUS_SPEED_100)
*speed = SPEED_100;
else
*speed = SPEED_10;
if (status & E1000_STATUS_FD)
*duplex = FULL_DUPLEX;
else
*duplex = HALF_DUPLEX;
e_dbg("%u Mbps, %s Duplex\n",
*speed == SPEED_1000 ? 1000 : *speed == SPEED_100 ? 100 : 10,
*duplex == FULL_DUPLEX ? "Full" : "Half");
return 0;
}
/**
* e1000e_get_speed_and_duplex_fiber_serdes - Retrieve current speed/duplex
* @hw: pointer to the HW structure
* @speed: stores the current speed
* @duplex: stores the current duplex
*
* Sets the speed and duplex to gigabit full duplex (the only possible option)
* for fiber/serdes links.
**/
s32 e1000e_get_speed_and_duplex_fiber_serdes(struct e1000_hw *hw, u16 *speed,
u16 *duplex)
{
*speed = SPEED_1000;
*duplex = FULL_DUPLEX;
return 0;
}
/**
* e1000e_get_hw_semaphore - Acquire hardware semaphore
* @hw: pointer to the HW structure
*
* Acquire the HW semaphore to access the PHY or NVM
**/
s32 e1000e_get_hw_semaphore(struct e1000_hw *hw)
{
u32 swsm;
s32 timeout = hw->nvm.word_size + 1;
s32 i = 0;
/* Get the SW semaphore */
while (i < timeout) {
swsm = er32(SWSM);
if (!(swsm & E1000_SWSM_SMBI))
break;
udelay(50);
i++;
}
if (i == timeout) {
e_dbg("Driver can't access device - SMBI bit is set.\n");
return -E1000_ERR_NVM;
}
/* Get the FW semaphore. */
for (i = 0; i < timeout; i++) {
swsm = er32(SWSM);
ew32(SWSM, swsm | E1000_SWSM_SWESMBI);
/* Semaphore acquired if bit latched */
if (er32(SWSM) & E1000_SWSM_SWESMBI)
break;
udelay(50);
}
if (i == timeout) {
/* Release semaphores */
e1000e_put_hw_semaphore(hw);
e_dbg("Driver can't access the NVM\n");
return -E1000_ERR_NVM;
}
return 0;
}
/**
* e1000e_put_hw_semaphore - Release hardware semaphore
* @hw: pointer to the HW structure
*
* Release hardware semaphore used to access the PHY or NVM
**/
void e1000e_put_hw_semaphore(struct e1000_hw *hw)
{
u32 swsm;
swsm = er32(SWSM);
swsm &= ~(E1000_SWSM_SMBI | E1000_SWSM_SWESMBI);
ew32(SWSM, swsm);
}
/**
* e1000e_get_auto_rd_done - Check for auto read completion
* @hw: pointer to the HW structure
*
* Check EEPROM for Auto Read done bit.
**/
s32 e1000e_get_auto_rd_done(struct e1000_hw *hw)
{
s32 i = 0;
while (i < AUTO_READ_DONE_TIMEOUT) {
if (er32(EECD) & E1000_EECD_AUTO_RD)
break;
usleep_range(1000, 2000);
i++;
}
if (i == AUTO_READ_DONE_TIMEOUT) {
e_dbg("Auto read by HW from NVM has not completed.\n");
return -E1000_ERR_RESET;
}
return 0;
}
/**
* e1000e_valid_led_default - Verify a valid default LED config
* @hw: pointer to the HW structure
* @data: pointer to the NVM (EEPROM)
*
* Read the EEPROM for the current default LED configuration. If the
* LED configuration is not valid, set to a valid LED configuration.
**/
s32 e1000e_valid_led_default(struct e1000_hw *hw, u16 *data)
{
s32 ret_val;
ret_val = e1000_read_nvm(hw, NVM_ID_LED_SETTINGS, 1, data);
if (ret_val) {
e_dbg("NVM Read Error\n");
return ret_val;
}
if (*data == ID_LED_RESERVED_0000 || *data == ID_LED_RESERVED_FFFF)
*data = ID_LED_DEFAULT;
return 0;
}
/**
* e1000e_id_led_init_generic -
* @hw: pointer to the HW structure
*
**/
s32 e1000e_id_led_init_generic(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
s32 ret_val;
const u32 ledctl_mask = 0x000000FF;
const u32 ledctl_on = E1000_LEDCTL_MODE_LED_ON;
const u32 ledctl_off = E1000_LEDCTL_MODE_LED_OFF;
u16 data, i, temp;
const u16 led_mask = 0x0F;
ret_val = hw->nvm.ops.valid_led_default(hw, &data);
if (ret_val)
return ret_val;
mac->ledctl_default = er32(LEDCTL);
mac->ledctl_mode1 = mac->ledctl_default;
mac->ledctl_mode2 = mac->ledctl_default;
for (i = 0; i < 4; i++) {
temp = (data >> (i << 2)) & led_mask;
switch (temp) {
case ID_LED_ON1_DEF2:
case ID_LED_ON1_ON2:
case ID_LED_ON1_OFF2:
mac->ledctl_mode1 &= ~(ledctl_mask << (i << 3));
mac->ledctl_mode1 |= ledctl_on << (i << 3);
break;
case ID_LED_OFF1_DEF2:
case ID_LED_OFF1_ON2:
case ID_LED_OFF1_OFF2:
mac->ledctl_mode1 &= ~(ledctl_mask << (i << 3));
mac->ledctl_mode1 |= ledctl_off << (i << 3);
break;
default:
/* Do nothing */
break;
}
switch (temp) {
case ID_LED_DEF1_ON2:
case ID_LED_ON1_ON2:
case ID_LED_OFF1_ON2:
mac->ledctl_mode2 &= ~(ledctl_mask << (i << 3));
mac->ledctl_mode2 |= ledctl_on << (i << 3);
break;
case ID_LED_DEF1_OFF2:
case ID_LED_ON1_OFF2:
case ID_LED_OFF1_OFF2:
mac->ledctl_mode2 &= ~(ledctl_mask << (i << 3));
mac->ledctl_mode2 |= ledctl_off << (i << 3);
break;
default:
/* Do nothing */
break;
}
}
return 0;
}
/**
* e1000e_setup_led_generic - Configures SW controllable LED
* @hw: pointer to the HW structure
*
* This prepares the SW controllable LED for use and saves the current state
* of the LED so it can be later restored.
**/
s32 e1000e_setup_led_generic(struct e1000_hw *hw)
{
u32 ledctl;
if (hw->mac.ops.setup_led != e1000e_setup_led_generic)
return -E1000_ERR_CONFIG;
if (hw->phy.media_type == e1000_media_type_fiber) {
ledctl = er32(LEDCTL);
hw->mac.ledctl_default = ledctl;
/* Turn off LED0 */
ledctl &= ~(E1000_LEDCTL_LED0_IVRT | E1000_LEDCTL_LED0_BLINK |
E1000_LEDCTL_LED0_MODE_MASK);
ledctl |= (E1000_LEDCTL_MODE_LED_OFF <<
E1000_LEDCTL_LED0_MODE_SHIFT);
ew32(LEDCTL, ledctl);
} else if (hw->phy.media_type == e1000_media_type_copper) {
ew32(LEDCTL, hw->mac.ledctl_mode1);
}
return 0;
}
/**
* e1000e_cleanup_led_generic - Set LED config to default operation
* @hw: pointer to the HW structure
*
* Remove the current LED configuration and set the LED configuration
* to the default value, saved from the EEPROM.
**/
s32 e1000e_cleanup_led_generic(struct e1000_hw *hw)
{
ew32(LEDCTL, hw->mac.ledctl_default);
return 0;
}
/**
* e1000e_blink_led_generic - Blink LED
* @hw: pointer to the HW structure
*
* Blink the LEDs which are set to be on.
**/
s32 e1000e_blink_led_generic(struct e1000_hw *hw)
{
u32 ledctl_blink = 0;
u32 i;
if (hw->phy.media_type == e1000_media_type_fiber) {
/* always blink LED0 for PCI-E fiber */
ledctl_blink = E1000_LEDCTL_LED0_BLINK |
(E1000_LEDCTL_MODE_LED_ON << E1000_LEDCTL_LED0_MODE_SHIFT);
} else {
/*
* set the blink bit for each LED that's "on" (0x0E)
* in ledctl_mode2
*/
ledctl_blink = hw->mac.ledctl_mode2;
for (i = 0; i < 4; i++)
if (((hw->mac.ledctl_mode2 >> (i * 8)) & 0xFF) ==
E1000_LEDCTL_MODE_LED_ON)
ledctl_blink |= (E1000_LEDCTL_LED0_BLINK <<
(i * 8));
}
ew32(LEDCTL, ledctl_blink);
return 0;
}
/**
* e1000e_led_on_generic - Turn LED on
* @hw: pointer to the HW structure
*
* Turn LED on.
**/
s32 e1000e_led_on_generic(struct e1000_hw *hw)
{
u32 ctrl;
switch (hw->phy.media_type) {
case e1000_media_type_fiber:
ctrl = er32(CTRL);
ctrl &= ~E1000_CTRL_SWDPIN0;
ctrl |= E1000_CTRL_SWDPIO0;
ew32(CTRL, ctrl);
break;
case e1000_media_type_copper:
ew32(LEDCTL, hw->mac.ledctl_mode2);
break;
default:
break;
}
return 0;
}
/**
* e1000e_led_off_generic - Turn LED off
* @hw: pointer to the HW structure
*
* Turn LED off.
**/
s32 e1000e_led_off_generic(struct e1000_hw *hw)
{
u32 ctrl;
switch (hw->phy.media_type) {
case e1000_media_type_fiber:
ctrl = er32(CTRL);
ctrl |= E1000_CTRL_SWDPIN0;
ctrl |= E1000_CTRL_SWDPIO0;
ew32(CTRL, ctrl);
break;
case e1000_media_type_copper:
ew32(LEDCTL, hw->mac.ledctl_mode1);
break;
default:
break;
}
return 0;
}
/**
* e1000e_set_pcie_no_snoop - Set PCI-express capabilities
* @hw: pointer to the HW structure
* @no_snoop: bitmap of snoop events
*
* Set the PCI-express register to snoop for events enabled in 'no_snoop'.
**/
void e1000e_set_pcie_no_snoop(struct e1000_hw *hw, u32 no_snoop)
{
u32 gcr;
if (no_snoop) {
gcr = er32(GCR);
gcr &= ~(PCIE_NO_SNOOP_ALL);
gcr |= no_snoop;
ew32(GCR, gcr);
}
}
/**
* e1000e_disable_pcie_master - Disables PCI-express master access
* @hw: pointer to the HW structure
*
* Returns 0 if successful, else returns -10
* (-E1000_ERR_MASTER_REQUESTS_PENDING) if master disable bit has not caused
* the master requests to be disabled.
*
* Disables PCI-Express master access and verifies there are no pending
* requests.
**/
s32 e1000e_disable_pcie_master(struct e1000_hw *hw)
{
u32 ctrl;
s32 timeout = MASTER_DISABLE_TIMEOUT;
ctrl = er32(CTRL);
ctrl |= E1000_CTRL_GIO_MASTER_DISABLE;
ew32(CTRL, ctrl);
while (timeout) {
if (!(er32(STATUS) & E1000_STATUS_GIO_MASTER_ENABLE))
break;
udelay(100);
timeout--;
}
if (!timeout) {
e_dbg("Master requests are pending.\n");
return -E1000_ERR_MASTER_REQUESTS_PENDING;
}
return 0;
}
/**
* e1000e_reset_adaptive - Reset Adaptive Interframe Spacing
* @hw: pointer to the HW structure
*
* Reset the Adaptive Interframe Spacing throttle to default values.
**/
void e1000e_reset_adaptive(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
if (!mac->adaptive_ifs) {
e_dbg("Not in Adaptive IFS mode!\n");
return;
}
mac->current_ifs_val = 0;
mac->ifs_min_val = IFS_MIN;
mac->ifs_max_val = IFS_MAX;
mac->ifs_step_size = IFS_STEP;
mac->ifs_ratio = IFS_RATIO;
mac->in_ifs_mode = false;
ew32(AIT, 0);
}
/**
* e1000e_update_adaptive - Update Adaptive Interframe Spacing
* @hw: pointer to the HW structure
*
* Update the Adaptive Interframe Spacing Throttle value based on the
* time between transmitted packets and time between collisions.
**/
void e1000e_update_adaptive(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
if (!mac->adaptive_ifs) {
e_dbg("Not in Adaptive IFS mode!\n");
return;
}
if ((mac->collision_delta * mac->ifs_ratio) > mac->tx_packet_delta) {
if (mac->tx_packet_delta > MIN_NUM_XMITS) {
mac->in_ifs_mode = true;
if (mac->current_ifs_val < mac->ifs_max_val) {
if (!mac->current_ifs_val)
mac->current_ifs_val = mac->ifs_min_val;
else
mac->current_ifs_val +=
mac->ifs_step_size;
ew32(AIT, mac->current_ifs_val);
}
}
} else {
if (mac->in_ifs_mode &&
(mac->tx_packet_delta <= MIN_NUM_XMITS)) {
mac->current_ifs_val = 0;
mac->in_ifs_mode = false;
ew32(AIT, 0);
}
}
}
| gpl-2.0 |
ngiordano/ics_3.1.10 | drivers/hwmon/f71882fg.c | 2764 | 84597 | /***************************************************************************
* Copyright (C) 2006 by Hans Edgington <hans@edgington.nl> *
* Copyright (C) 2007-2011 Hans de Goede <hdegoede@redhat.com> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/platform_device.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/io.h>
#include <linux/acpi.h>
#define DRVNAME "f71882fg"
#define SIO_F71858FG_LD_HWM 0x02 /* Hardware monitor logical device */
#define SIO_F71882FG_LD_HWM 0x04 /* Hardware monitor logical device */
#define SIO_UNLOCK_KEY 0x87 /* Key to enable Super-I/O */
#define SIO_LOCK_KEY 0xAA /* Key to disable Super-I/O */
#define SIO_REG_LDSEL 0x07 /* Logical device select */
#define SIO_REG_DEVID 0x20 /* Device ID (2 bytes) */
#define SIO_REG_DEVREV 0x22 /* Device revision */
#define SIO_REG_MANID 0x23 /* Fintek ID (2 bytes) */
#define SIO_REG_ENABLE 0x30 /* Logical device enable */
#define SIO_REG_ADDR 0x60 /* Logical device address (2 bytes) */
#define SIO_FINTEK_ID 0x1934 /* Manufacturers ID */
#define SIO_F71808E_ID 0x0901 /* Chipset ID */
#define SIO_F71808A_ID 0x1001 /* Chipset ID */
#define SIO_F71858_ID 0x0507 /* Chipset ID */
#define SIO_F71862_ID 0x0601 /* Chipset ID */
#define SIO_F71869_ID 0x0814 /* Chipset ID */
#define SIO_F71869A_ID 0x1007 /* Chipset ID */
#define SIO_F71882_ID 0x0541 /* Chipset ID */
#define SIO_F71889_ID 0x0723 /* Chipset ID */
#define SIO_F71889E_ID 0x0909 /* Chipset ID */
#define SIO_F71889A_ID 0x1005 /* Chipset ID */
#define SIO_F8000_ID 0x0581 /* Chipset ID */
#define SIO_F81865_ID 0x0704 /* Chipset ID */
#define REGION_LENGTH 8
#define ADDR_REG_OFFSET 5
#define DATA_REG_OFFSET 6
#define F71882FG_REG_IN_STATUS 0x12 /* f7188x only */
#define F71882FG_REG_IN_BEEP 0x13 /* f7188x only */
#define F71882FG_REG_IN(nr) (0x20 + (nr))
#define F71882FG_REG_IN1_HIGH 0x32 /* f7188x only */
#define F71882FG_REG_FAN(nr) (0xA0 + (16 * (nr)))
#define F71882FG_REG_FAN_TARGET(nr) (0xA2 + (16 * (nr)))
#define F71882FG_REG_FAN_FULL_SPEED(nr) (0xA4 + (16 * (nr)))
#define F71882FG_REG_FAN_STATUS 0x92
#define F71882FG_REG_FAN_BEEP 0x93
#define F71882FG_REG_TEMP(nr) (0x70 + 2 * (nr))
#define F71882FG_REG_TEMP_OVT(nr) (0x80 + 2 * (nr))
#define F71882FG_REG_TEMP_HIGH(nr) (0x81 + 2 * (nr))
#define F71882FG_REG_TEMP_STATUS 0x62
#define F71882FG_REG_TEMP_BEEP 0x63
#define F71882FG_REG_TEMP_CONFIG 0x69
#define F71882FG_REG_TEMP_HYST(nr) (0x6C + (nr))
#define F71882FG_REG_TEMP_TYPE 0x6B
#define F71882FG_REG_TEMP_DIODE_OPEN 0x6F
#define F71882FG_REG_PWM(nr) (0xA3 + (16 * (nr)))
#define F71882FG_REG_PWM_TYPE 0x94
#define F71882FG_REG_PWM_ENABLE 0x96
#define F71882FG_REG_FAN_HYST(nr) (0x98 + (nr))
#define F71882FG_REG_FAN_FAULT_T 0x9F
#define F71882FG_FAN_NEG_TEMP_EN 0x20
#define F71882FG_FAN_PROG_SEL 0x80
#define F71882FG_REG_POINT_PWM(pwm, point) (0xAA + (point) + (16 * (pwm)))
#define F71882FG_REG_POINT_TEMP(pwm, point) (0xA6 + (point) + (16 * (pwm)))
#define F71882FG_REG_POINT_MAPPING(nr) (0xAF + 16 * (nr))
#define F71882FG_REG_START 0x01
#define F71882FG_MAX_INS 9
#define FAN_MIN_DETECT 366 /* Lowest detectable fanspeed */
static unsigned short force_id;
module_param(force_id, ushort, 0);
MODULE_PARM_DESC(force_id, "Override the detected device ID");
enum chips { f71808e, f71808a, f71858fg, f71862fg, f71869, f71869a, f71882fg,
f71889fg, f71889ed, f71889a, f8000, f81865f };
static const char *f71882fg_names[] = {
"f71808e",
"f71808a",
"f71858fg",
"f71862fg",
"f71869", /* Both f71869f and f71869e, reg. compatible and same id */
"f71869a",
"f71882fg",
"f71889fg", /* f81801u too, same id */
"f71889ed",
"f71889a",
"f8000",
"f81865f",
};
static const char f71882fg_has_in[][F71882FG_MAX_INS] = {
[f71808e] = { 1, 1, 1, 1, 1, 1, 0, 1, 1 },
[f71808a] = { 1, 1, 1, 1, 0, 0, 0, 1, 1 },
[f71858fg] = { 1, 1, 1, 0, 0, 0, 0, 0, 0 },
[f71862fg] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
[f71869] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
[f71869a] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
[f71882fg] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
[f71889fg] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
[f71889ed] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
[f71889a] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
[f8000] = { 1, 1, 1, 0, 0, 0, 0, 0, 0 },
[f81865f] = { 1, 1, 1, 1, 1, 1, 1, 0, 0 },
};
static const char f71882fg_has_in1_alarm[] = {
[f71808e] = 0,
[f71808a] = 0,
[f71858fg] = 0,
[f71862fg] = 0,
[f71869] = 0,
[f71869a] = 0,
[f71882fg] = 1,
[f71889fg] = 1,
[f71889ed] = 1,
[f71889a] = 1,
[f8000] = 0,
[f81865f] = 1,
};
static const char f71882fg_fan_has_beep[] = {
[f71808e] = 0,
[f71808a] = 0,
[f71858fg] = 0,
[f71862fg] = 1,
[f71869] = 1,
[f71869a] = 1,
[f71882fg] = 1,
[f71889fg] = 1,
[f71889ed] = 1,
[f71889a] = 1,
[f8000] = 0,
[f81865f] = 1,
};
static const char f71882fg_nr_fans[] = {
[f71808e] = 3,
[f71808a] = 2, /* +1 fan which is monitor + simple pwm only */
[f71858fg] = 3,
[f71862fg] = 3,
[f71869] = 3,
[f71869a] = 3,
[f71882fg] = 4,
[f71889fg] = 3,
[f71889ed] = 3,
[f71889a] = 3,
[f8000] = 3, /* +1 fan which is monitor only */
[f81865f] = 2,
};
static const char f71882fg_temp_has_beep[] = {
[f71808e] = 0,
[f71808a] = 1,
[f71858fg] = 0,
[f71862fg] = 1,
[f71869] = 1,
[f71869a] = 1,
[f71882fg] = 1,
[f71889fg] = 1,
[f71889ed] = 1,
[f71889a] = 1,
[f8000] = 0,
[f81865f] = 1,
};
static const char f71882fg_nr_temps[] = {
[f71808e] = 2,
[f71808a] = 2,
[f71858fg] = 3,
[f71862fg] = 3,
[f71869] = 3,
[f71869a] = 3,
[f71882fg] = 3,
[f71889fg] = 3,
[f71889ed] = 3,
[f71889a] = 3,
[f8000] = 3,
[f81865f] = 2,
};
static struct platform_device *f71882fg_pdev;
/* Super-I/O Function prototypes */
static inline int superio_inb(int base, int reg);
static inline int superio_inw(int base, int reg);
static inline int superio_enter(int base);
static inline void superio_select(int base, int ld);
static inline void superio_exit(int base);
struct f71882fg_sio_data {
enum chips type;
};
struct f71882fg_data {
unsigned short addr;
enum chips type;
struct device *hwmon_dev;
struct mutex update_lock;
int temp_start; /* temp numbering start (0 or 1) */
char valid; /* !=0 if following fields are valid */
char auto_point_temp_signed;
unsigned long last_updated; /* In jiffies */
unsigned long last_limits; /* In jiffies */
/* Register Values */
u8 in[F71882FG_MAX_INS];
u8 in1_max;
u8 in_status;
u8 in_beep;
u16 fan[4];
u16 fan_target[4];
u16 fan_full_speed[4];
u8 fan_status;
u8 fan_beep;
/* Note: all models have max 3 temperature channels, but on some
they are addressed as 0-2 and on others as 1-3, so for coding
convenience we reserve space for 4 channels */
u16 temp[4];
u8 temp_ovt[4];
u8 temp_high[4];
u8 temp_hyst[2]; /* 2 hysts stored per reg */
u8 temp_type[4];
u8 temp_status;
u8 temp_beep;
u8 temp_diode_open;
u8 temp_config;
u8 pwm[4];
u8 pwm_enable;
u8 pwm_auto_point_hyst[2];
u8 pwm_auto_point_mapping[4];
u8 pwm_auto_point_pwm[4][5];
s8 pwm_auto_point_temp[4][4];
};
/* Sysfs in */
static ssize_t show_in(struct device *dev, struct device_attribute *devattr,
char *buf);
static ssize_t show_in_max(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t store_in_max(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count);
static ssize_t show_in_beep(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t store_in_beep(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count);
static ssize_t show_in_alarm(struct device *dev, struct device_attribute
*devattr, char *buf);
/* Sysfs Fan */
static ssize_t show_fan(struct device *dev, struct device_attribute *devattr,
char *buf);
static ssize_t show_fan_full_speed(struct device *dev,
struct device_attribute *devattr, char *buf);
static ssize_t store_fan_full_speed(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count);
static ssize_t show_fan_beep(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t store_fan_beep(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count);
static ssize_t show_fan_alarm(struct device *dev, struct device_attribute
*devattr, char *buf);
/* Sysfs Temp */
static ssize_t show_temp(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t show_temp_max(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t store_temp_max(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count);
static ssize_t show_temp_max_hyst(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t store_temp_max_hyst(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count);
static ssize_t show_temp_crit(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t store_temp_crit(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count);
static ssize_t show_temp_crit_hyst(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t show_temp_type(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t show_temp_beep(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t store_temp_beep(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count);
static ssize_t show_temp_alarm(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t show_temp_fault(struct device *dev, struct device_attribute
*devattr, char *buf);
/* PWM and Auto point control */
static ssize_t show_pwm(struct device *dev, struct device_attribute *devattr,
char *buf);
static ssize_t store_pwm(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count);
static ssize_t show_simple_pwm(struct device *dev,
struct device_attribute *devattr, char *buf);
static ssize_t store_simple_pwm(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count);
static ssize_t show_pwm_enable(struct device *dev,
struct device_attribute *devattr, char *buf);
static ssize_t store_pwm_enable(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count);
static ssize_t show_pwm_interpolate(struct device *dev,
struct device_attribute *devattr, char *buf);
static ssize_t store_pwm_interpolate(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count);
static ssize_t show_pwm_auto_point_channel(struct device *dev,
struct device_attribute *devattr, char *buf);
static ssize_t store_pwm_auto_point_channel(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count);
static ssize_t show_pwm_auto_point_temp_hyst(struct device *dev,
struct device_attribute *devattr, char *buf);
static ssize_t store_pwm_auto_point_temp_hyst(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count);
static ssize_t show_pwm_auto_point_pwm(struct device *dev,
struct device_attribute *devattr, char *buf);
static ssize_t store_pwm_auto_point_pwm(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count);
static ssize_t show_pwm_auto_point_temp(struct device *dev,
struct device_attribute *devattr, char *buf);
static ssize_t store_pwm_auto_point_temp(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count);
/* Sysfs misc */
static ssize_t show_name(struct device *dev, struct device_attribute *devattr,
char *buf);
static int __devinit f71882fg_probe(struct platform_device * pdev);
static int f71882fg_remove(struct platform_device *pdev);
static struct platform_driver f71882fg_driver = {
.driver = {
.owner = THIS_MODULE,
.name = DRVNAME,
},
.probe = f71882fg_probe,
.remove = f71882fg_remove,
};
static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
/* Temp attr for the f71858fg, the f71858fg is special as it has its
temperature indexes start at 0 (the others start at 1) */
static struct sensor_device_attribute_2 f71858fg_temp_attr[] = {
SENSOR_ATTR_2(temp1_input, S_IRUGO, show_temp, NULL, 0, 0),
SENSOR_ATTR_2(temp1_max, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 0),
SENSOR_ATTR_2(temp1_max_hyst, S_IRUGO|S_IWUSR, show_temp_max_hyst,
store_temp_max_hyst, 0, 0),
SENSOR_ATTR_2(temp1_max_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 0),
SENSOR_ATTR_2(temp1_crit, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 0),
SENSOR_ATTR_2(temp1_crit_hyst, S_IRUGO, show_temp_crit_hyst, NULL,
0, 0),
SENSOR_ATTR_2(temp1_crit_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 4),
SENSOR_ATTR_2(temp1_fault, S_IRUGO, show_temp_fault, NULL, 0, 0),
SENSOR_ATTR_2(temp2_input, S_IRUGO, show_temp, NULL, 0, 1),
SENSOR_ATTR_2(temp2_max, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 1),
SENSOR_ATTR_2(temp2_max_hyst, S_IRUGO|S_IWUSR, show_temp_max_hyst,
store_temp_max_hyst, 0, 1),
SENSOR_ATTR_2(temp2_max_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 1),
SENSOR_ATTR_2(temp2_crit, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 1),
SENSOR_ATTR_2(temp2_crit_hyst, S_IRUGO, show_temp_crit_hyst, NULL,
0, 1),
SENSOR_ATTR_2(temp2_crit_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 5),
SENSOR_ATTR_2(temp2_fault, S_IRUGO, show_temp_fault, NULL, 0, 1),
SENSOR_ATTR_2(temp3_input, S_IRUGO, show_temp, NULL, 0, 2),
SENSOR_ATTR_2(temp3_max, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 2),
SENSOR_ATTR_2(temp3_max_hyst, S_IRUGO|S_IWUSR, show_temp_max_hyst,
store_temp_max_hyst, 0, 2),
SENSOR_ATTR_2(temp3_max_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 2),
SENSOR_ATTR_2(temp3_crit, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 2),
SENSOR_ATTR_2(temp3_crit_hyst, S_IRUGO, show_temp_crit_hyst, NULL,
0, 2),
SENSOR_ATTR_2(temp3_crit_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 6),
SENSOR_ATTR_2(temp3_fault, S_IRUGO, show_temp_fault, NULL, 0, 2),
};
/* Temp attr for the standard models */
static struct sensor_device_attribute_2 fxxxx_temp_attr[3][9] = { {
SENSOR_ATTR_2(temp1_input, S_IRUGO, show_temp, NULL, 0, 1),
SENSOR_ATTR_2(temp1_max, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 1),
SENSOR_ATTR_2(temp1_max_hyst, S_IRUGO|S_IWUSR, show_temp_max_hyst,
store_temp_max_hyst, 0, 1),
/* Should really be temp1_max_alarm, but older versions did not handle
the max and crit alarms separately and lm_sensors v2 depends on the
presence of temp#_alarm files. The same goes for temp2/3 _alarm. */
SENSOR_ATTR_2(temp1_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 1),
SENSOR_ATTR_2(temp1_crit, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 1),
SENSOR_ATTR_2(temp1_crit_hyst, S_IRUGO, show_temp_crit_hyst, NULL,
0, 1),
SENSOR_ATTR_2(temp1_crit_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 5),
SENSOR_ATTR_2(temp1_type, S_IRUGO, show_temp_type, NULL, 0, 1),
SENSOR_ATTR_2(temp1_fault, S_IRUGO, show_temp_fault, NULL, 0, 1),
}, {
SENSOR_ATTR_2(temp2_input, S_IRUGO, show_temp, NULL, 0, 2),
SENSOR_ATTR_2(temp2_max, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 2),
SENSOR_ATTR_2(temp2_max_hyst, S_IRUGO|S_IWUSR, show_temp_max_hyst,
store_temp_max_hyst, 0, 2),
/* Should be temp2_max_alarm, see temp1_alarm note */
SENSOR_ATTR_2(temp2_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 2),
SENSOR_ATTR_2(temp2_crit, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 2),
SENSOR_ATTR_2(temp2_crit_hyst, S_IRUGO, show_temp_crit_hyst, NULL,
0, 2),
SENSOR_ATTR_2(temp2_crit_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 6),
SENSOR_ATTR_2(temp2_type, S_IRUGO, show_temp_type, NULL, 0, 2),
SENSOR_ATTR_2(temp2_fault, S_IRUGO, show_temp_fault, NULL, 0, 2),
}, {
SENSOR_ATTR_2(temp3_input, S_IRUGO, show_temp, NULL, 0, 3),
SENSOR_ATTR_2(temp3_max, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 3),
SENSOR_ATTR_2(temp3_max_hyst, S_IRUGO|S_IWUSR, show_temp_max_hyst,
store_temp_max_hyst, 0, 3),
/* Should be temp3_max_alarm, see temp1_alarm note */
SENSOR_ATTR_2(temp3_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 3),
SENSOR_ATTR_2(temp3_crit, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 3),
SENSOR_ATTR_2(temp3_crit_hyst, S_IRUGO, show_temp_crit_hyst, NULL,
0, 3),
SENSOR_ATTR_2(temp3_crit_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 7),
SENSOR_ATTR_2(temp3_type, S_IRUGO, show_temp_type, NULL, 0, 3),
SENSOR_ATTR_2(temp3_fault, S_IRUGO, show_temp_fault, NULL, 0, 3),
} };
/* Temp attr for models which can beep on temp alarm */
static struct sensor_device_attribute_2 fxxxx_temp_beep_attr[3][2] = { {
SENSOR_ATTR_2(temp1_max_beep, S_IRUGO|S_IWUSR, show_temp_beep,
store_temp_beep, 0, 1),
SENSOR_ATTR_2(temp1_crit_beep, S_IRUGO|S_IWUSR, show_temp_beep,
store_temp_beep, 0, 5),
}, {
SENSOR_ATTR_2(temp2_max_beep, S_IRUGO|S_IWUSR, show_temp_beep,
store_temp_beep, 0, 2),
SENSOR_ATTR_2(temp2_crit_beep, S_IRUGO|S_IWUSR, show_temp_beep,
store_temp_beep, 0, 6),
}, {
SENSOR_ATTR_2(temp3_max_beep, S_IRUGO|S_IWUSR, show_temp_beep,
store_temp_beep, 0, 3),
SENSOR_ATTR_2(temp3_crit_beep, S_IRUGO|S_IWUSR, show_temp_beep,
store_temp_beep, 0, 7),
} };
/* Temp attr for the f8000
Note on the f8000 temp_ovt (crit) is used as max, and temp_high (max)
is used as hysteresis value to clear alarms
Also like the f71858fg its temperature indexes start at 0
*/
static struct sensor_device_attribute_2 f8000_temp_attr[] = {
SENSOR_ATTR_2(temp1_input, S_IRUGO, show_temp, NULL, 0, 0),
SENSOR_ATTR_2(temp1_max, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 0),
SENSOR_ATTR_2(temp1_max_hyst, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 0),
SENSOR_ATTR_2(temp1_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 4),
SENSOR_ATTR_2(temp1_fault, S_IRUGO, show_temp_fault, NULL, 0, 0),
SENSOR_ATTR_2(temp2_input, S_IRUGO, show_temp, NULL, 0, 1),
SENSOR_ATTR_2(temp2_max, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 1),
SENSOR_ATTR_2(temp2_max_hyst, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 1),
SENSOR_ATTR_2(temp2_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 5),
SENSOR_ATTR_2(temp2_fault, S_IRUGO, show_temp_fault, NULL, 0, 1),
SENSOR_ATTR_2(temp3_input, S_IRUGO, show_temp, NULL, 0, 2),
SENSOR_ATTR_2(temp3_max, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 2),
SENSOR_ATTR_2(temp3_max_hyst, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 2),
SENSOR_ATTR_2(temp3_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 6),
SENSOR_ATTR_2(temp3_fault, S_IRUGO, show_temp_fault, NULL, 0, 2),
};
/* in attr for all models */
static struct sensor_device_attribute_2 fxxxx_in_attr[] = {
SENSOR_ATTR_2(in0_input, S_IRUGO, show_in, NULL, 0, 0),
SENSOR_ATTR_2(in1_input, S_IRUGO, show_in, NULL, 0, 1),
SENSOR_ATTR_2(in2_input, S_IRUGO, show_in, NULL, 0, 2),
SENSOR_ATTR_2(in3_input, S_IRUGO, show_in, NULL, 0, 3),
SENSOR_ATTR_2(in4_input, S_IRUGO, show_in, NULL, 0, 4),
SENSOR_ATTR_2(in5_input, S_IRUGO, show_in, NULL, 0, 5),
SENSOR_ATTR_2(in6_input, S_IRUGO, show_in, NULL, 0, 6),
SENSOR_ATTR_2(in7_input, S_IRUGO, show_in, NULL, 0, 7),
SENSOR_ATTR_2(in8_input, S_IRUGO, show_in, NULL, 0, 8),
};
/* For models with in1 alarm capability */
static struct sensor_device_attribute_2 fxxxx_in1_alarm_attr[] = {
SENSOR_ATTR_2(in1_max, S_IRUGO|S_IWUSR, show_in_max, store_in_max,
0, 1),
SENSOR_ATTR_2(in1_beep, S_IRUGO|S_IWUSR, show_in_beep, store_in_beep,
0, 1),
SENSOR_ATTR_2(in1_alarm, S_IRUGO, show_in_alarm, NULL, 0, 1),
};
/* Fan / PWM attr common to all models */
static struct sensor_device_attribute_2 fxxxx_fan_attr[4][6] = { {
SENSOR_ATTR_2(fan1_input, S_IRUGO, show_fan, NULL, 0, 0),
SENSOR_ATTR_2(fan1_full_speed, S_IRUGO|S_IWUSR,
show_fan_full_speed,
store_fan_full_speed, 0, 0),
SENSOR_ATTR_2(fan1_alarm, S_IRUGO, show_fan_alarm, NULL, 0, 0),
SENSOR_ATTR_2(pwm1, S_IRUGO|S_IWUSR, show_pwm, store_pwm, 0, 0),
SENSOR_ATTR_2(pwm1_enable, S_IRUGO|S_IWUSR, show_pwm_enable,
store_pwm_enable, 0, 0),
SENSOR_ATTR_2(pwm1_interpolate, S_IRUGO|S_IWUSR,
show_pwm_interpolate, store_pwm_interpolate, 0, 0),
}, {
SENSOR_ATTR_2(fan2_input, S_IRUGO, show_fan, NULL, 0, 1),
SENSOR_ATTR_2(fan2_full_speed, S_IRUGO|S_IWUSR,
show_fan_full_speed,
store_fan_full_speed, 0, 1),
SENSOR_ATTR_2(fan2_alarm, S_IRUGO, show_fan_alarm, NULL, 0, 1),
SENSOR_ATTR_2(pwm2, S_IRUGO|S_IWUSR, show_pwm, store_pwm, 0, 1),
SENSOR_ATTR_2(pwm2_enable, S_IRUGO|S_IWUSR, show_pwm_enable,
store_pwm_enable, 0, 1),
SENSOR_ATTR_2(pwm2_interpolate, S_IRUGO|S_IWUSR,
show_pwm_interpolate, store_pwm_interpolate, 0, 1),
}, {
SENSOR_ATTR_2(fan3_input, S_IRUGO, show_fan, NULL, 0, 2),
SENSOR_ATTR_2(fan3_full_speed, S_IRUGO|S_IWUSR,
show_fan_full_speed,
store_fan_full_speed, 0, 2),
SENSOR_ATTR_2(fan3_alarm, S_IRUGO, show_fan_alarm, NULL, 0, 2),
SENSOR_ATTR_2(pwm3, S_IRUGO|S_IWUSR, show_pwm, store_pwm, 0, 2),
SENSOR_ATTR_2(pwm3_enable, S_IRUGO|S_IWUSR, show_pwm_enable,
store_pwm_enable, 0, 2),
SENSOR_ATTR_2(pwm3_interpolate, S_IRUGO|S_IWUSR,
show_pwm_interpolate, store_pwm_interpolate, 0, 2),
}, {
SENSOR_ATTR_2(fan4_input, S_IRUGO, show_fan, NULL, 0, 3),
SENSOR_ATTR_2(fan4_full_speed, S_IRUGO|S_IWUSR,
show_fan_full_speed,
store_fan_full_speed, 0, 3),
SENSOR_ATTR_2(fan4_alarm, S_IRUGO, show_fan_alarm, NULL, 0, 3),
SENSOR_ATTR_2(pwm4, S_IRUGO|S_IWUSR, show_pwm, store_pwm, 0, 3),
SENSOR_ATTR_2(pwm4_enable, S_IRUGO|S_IWUSR, show_pwm_enable,
store_pwm_enable, 0, 3),
SENSOR_ATTR_2(pwm4_interpolate, S_IRUGO|S_IWUSR,
show_pwm_interpolate, store_pwm_interpolate, 0, 3),
} };
/* Attr for the third fan of the f71808a, which only has manual pwm */
static struct sensor_device_attribute_2 f71808a_fan3_attr[] = {
SENSOR_ATTR_2(fan3_input, S_IRUGO, show_fan, NULL, 0, 2),
SENSOR_ATTR_2(fan3_alarm, S_IRUGO, show_fan_alarm, NULL, 0, 2),
SENSOR_ATTR_2(pwm3, S_IRUGO|S_IWUSR,
show_simple_pwm, store_simple_pwm, 0, 2),
};
/* Attr for models which can beep on Fan alarm */
static struct sensor_device_attribute_2 fxxxx_fan_beep_attr[] = {
SENSOR_ATTR_2(fan1_beep, S_IRUGO|S_IWUSR, show_fan_beep,
store_fan_beep, 0, 0),
SENSOR_ATTR_2(fan2_beep, S_IRUGO|S_IWUSR, show_fan_beep,
store_fan_beep, 0, 1),
SENSOR_ATTR_2(fan3_beep, S_IRUGO|S_IWUSR, show_fan_beep,
store_fan_beep, 0, 2),
SENSOR_ATTR_2(fan4_beep, S_IRUGO|S_IWUSR, show_fan_beep,
store_fan_beep, 0, 3),
};
/* PWM attr for the f71862fg, fewer pwms and fewer zones per pwm than the
standard models */
static struct sensor_device_attribute_2 f71862fg_auto_pwm_attr[] = {
SENSOR_ATTR_2(pwm1_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 0),
SENSOR_ATTR_2(pwm1_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 0),
SENSOR_ATTR_2(pwm1_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 0),
SENSOR_ATTR_2(pwm1_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 0),
SENSOR_ATTR_2(pwm1_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 0),
SENSOR_ATTR_2(pwm1_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 0),
SENSOR_ATTR_2(pwm1_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 0),
SENSOR_ATTR_2(pwm2_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 1),
SENSOR_ATTR_2(pwm2_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 1),
SENSOR_ATTR_2(pwm2_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 1),
SENSOR_ATTR_2(pwm2_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 1),
SENSOR_ATTR_2(pwm2_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 1),
SENSOR_ATTR_2(pwm2_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 1),
SENSOR_ATTR_2(pwm2_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 1),
SENSOR_ATTR_2(pwm3_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 2),
SENSOR_ATTR_2(pwm3_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 2),
SENSOR_ATTR_2(pwm3_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 2),
SENSOR_ATTR_2(pwm3_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 2),
SENSOR_ATTR_2(pwm3_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 2),
SENSOR_ATTR_2(pwm3_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 2),
SENSOR_ATTR_2(pwm3_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 2),
};
/* PWM attr for the f71808e/f71869, almost identical to the f71862fg, but the
pwm setting when the temperature is above the pwmX_auto_point1_temp can be
programmed instead of being hardcoded to 0xff */
static struct sensor_device_attribute_2 f71869_auto_pwm_attr[] = {
SENSOR_ATTR_2(pwm1_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 0),
SENSOR_ATTR_2(pwm1_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 0),
SENSOR_ATTR_2(pwm1_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 0),
SENSOR_ATTR_2(pwm1_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 0),
SENSOR_ATTR_2(pwm1_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 0),
SENSOR_ATTR_2(pwm1_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 0),
SENSOR_ATTR_2(pwm1_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 0),
SENSOR_ATTR_2(pwm1_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 0),
SENSOR_ATTR_2(pwm2_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 1),
SENSOR_ATTR_2(pwm2_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 1),
SENSOR_ATTR_2(pwm2_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 1),
SENSOR_ATTR_2(pwm2_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 1),
SENSOR_ATTR_2(pwm2_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 1),
SENSOR_ATTR_2(pwm2_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 1),
SENSOR_ATTR_2(pwm2_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 1),
SENSOR_ATTR_2(pwm2_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 1),
SENSOR_ATTR_2(pwm3_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 2),
SENSOR_ATTR_2(pwm3_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 2),
SENSOR_ATTR_2(pwm3_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 2),
SENSOR_ATTR_2(pwm3_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 2),
SENSOR_ATTR_2(pwm3_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 2),
SENSOR_ATTR_2(pwm3_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 2),
SENSOR_ATTR_2(pwm3_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 2),
SENSOR_ATTR_2(pwm3_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 2),
};
/* PWM attr for the standard models */
static struct sensor_device_attribute_2 fxxxx_auto_pwm_attr[4][14] = { {
SENSOR_ATTR_2(pwm1_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 0),
SENSOR_ATTR_2(pwm1_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 0),
SENSOR_ATTR_2(pwm1_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 0),
SENSOR_ATTR_2(pwm1_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
2, 0),
SENSOR_ATTR_2(pwm1_auto_point4_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
3, 0),
SENSOR_ATTR_2(pwm1_auto_point5_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 0),
SENSOR_ATTR_2(pwm1_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 0),
SENSOR_ATTR_2(pwm1_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
1, 0),
SENSOR_ATTR_2(pwm1_auto_point3_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
2, 0),
SENSOR_ATTR_2(pwm1_auto_point4_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 0),
SENSOR_ATTR_2(pwm1_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 0),
SENSOR_ATTR_2(pwm1_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 1, 0),
SENSOR_ATTR_2(pwm1_auto_point3_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 2, 0),
SENSOR_ATTR_2(pwm1_auto_point4_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 0),
}, {
SENSOR_ATTR_2(pwm2_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 1),
SENSOR_ATTR_2(pwm2_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 1),
SENSOR_ATTR_2(pwm2_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 1),
SENSOR_ATTR_2(pwm2_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
2, 1),
SENSOR_ATTR_2(pwm2_auto_point4_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
3, 1),
SENSOR_ATTR_2(pwm2_auto_point5_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 1),
SENSOR_ATTR_2(pwm2_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 1),
SENSOR_ATTR_2(pwm2_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
1, 1),
SENSOR_ATTR_2(pwm2_auto_point3_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
2, 1),
SENSOR_ATTR_2(pwm2_auto_point4_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 1),
SENSOR_ATTR_2(pwm2_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 1),
SENSOR_ATTR_2(pwm2_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 1, 1),
SENSOR_ATTR_2(pwm2_auto_point3_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 2, 1),
SENSOR_ATTR_2(pwm2_auto_point4_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 1),
}, {
SENSOR_ATTR_2(pwm3_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 2),
SENSOR_ATTR_2(pwm3_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 2),
SENSOR_ATTR_2(pwm3_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 2),
SENSOR_ATTR_2(pwm3_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
2, 2),
SENSOR_ATTR_2(pwm3_auto_point4_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
3, 2),
SENSOR_ATTR_2(pwm3_auto_point5_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 2),
SENSOR_ATTR_2(pwm3_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 2),
SENSOR_ATTR_2(pwm3_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
1, 2),
SENSOR_ATTR_2(pwm3_auto_point3_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
2, 2),
SENSOR_ATTR_2(pwm3_auto_point4_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 2),
SENSOR_ATTR_2(pwm3_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 2),
SENSOR_ATTR_2(pwm3_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 1, 2),
SENSOR_ATTR_2(pwm3_auto_point3_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 2, 2),
SENSOR_ATTR_2(pwm3_auto_point4_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 2),
}, {
SENSOR_ATTR_2(pwm4_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 3),
SENSOR_ATTR_2(pwm4_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 3),
SENSOR_ATTR_2(pwm4_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 3),
SENSOR_ATTR_2(pwm4_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
2, 3),
SENSOR_ATTR_2(pwm4_auto_point4_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
3, 3),
SENSOR_ATTR_2(pwm4_auto_point5_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 3),
SENSOR_ATTR_2(pwm4_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 3),
SENSOR_ATTR_2(pwm4_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
1, 3),
SENSOR_ATTR_2(pwm4_auto_point3_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
2, 3),
SENSOR_ATTR_2(pwm4_auto_point4_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 3),
SENSOR_ATTR_2(pwm4_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 3),
SENSOR_ATTR_2(pwm4_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 1, 3),
SENSOR_ATTR_2(pwm4_auto_point3_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 2, 3),
SENSOR_ATTR_2(pwm4_auto_point4_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 3),
} };
/* Fan attr specific to the f8000 (4th fan input can only measure speed) */
static struct sensor_device_attribute_2 f8000_fan_attr[] = {
SENSOR_ATTR_2(fan4_input, S_IRUGO, show_fan, NULL, 0, 3),
};
/* PWM attr for the f8000, zones mapped to temp instead of to pwm!
Also the register block at offset A0 maps to TEMP1 (so our temp2, as the
F8000 starts counting temps at 0), B0 maps the TEMP2 and C0 maps to TEMP0 */
static struct sensor_device_attribute_2 f8000_auto_pwm_attr[] = {
SENSOR_ATTR_2(pwm1_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 0),
SENSOR_ATTR_2(temp1_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 2),
SENSOR_ATTR_2(temp1_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 2),
SENSOR_ATTR_2(temp1_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
2, 2),
SENSOR_ATTR_2(temp1_auto_point4_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
3, 2),
SENSOR_ATTR_2(temp1_auto_point5_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 2),
SENSOR_ATTR_2(temp1_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 2),
SENSOR_ATTR_2(temp1_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
1, 2),
SENSOR_ATTR_2(temp1_auto_point3_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
2, 2),
SENSOR_ATTR_2(temp1_auto_point4_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 2),
SENSOR_ATTR_2(temp1_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 2),
SENSOR_ATTR_2(temp1_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 1, 2),
SENSOR_ATTR_2(temp1_auto_point3_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 2, 2),
SENSOR_ATTR_2(temp1_auto_point4_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 2),
SENSOR_ATTR_2(pwm2_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 1),
SENSOR_ATTR_2(temp2_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 0),
SENSOR_ATTR_2(temp2_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 0),
SENSOR_ATTR_2(temp2_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
2, 0),
SENSOR_ATTR_2(temp2_auto_point4_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
3, 0),
SENSOR_ATTR_2(temp2_auto_point5_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 0),
SENSOR_ATTR_2(temp2_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 0),
SENSOR_ATTR_2(temp2_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
1, 0),
SENSOR_ATTR_2(temp2_auto_point3_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
2, 0),
SENSOR_ATTR_2(temp2_auto_point4_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 0),
SENSOR_ATTR_2(temp2_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 0),
SENSOR_ATTR_2(temp2_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 1, 0),
SENSOR_ATTR_2(temp2_auto_point3_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 2, 0),
SENSOR_ATTR_2(temp2_auto_point4_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 0),
SENSOR_ATTR_2(pwm3_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 2),
SENSOR_ATTR_2(temp3_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 1),
SENSOR_ATTR_2(temp3_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 1),
SENSOR_ATTR_2(temp3_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
2, 1),
SENSOR_ATTR_2(temp3_auto_point4_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
3, 1),
SENSOR_ATTR_2(temp3_auto_point5_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 1),
SENSOR_ATTR_2(temp3_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 1),
SENSOR_ATTR_2(temp3_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
1, 1),
SENSOR_ATTR_2(temp3_auto_point3_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
2, 1),
SENSOR_ATTR_2(temp3_auto_point4_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 1),
SENSOR_ATTR_2(temp3_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 1),
SENSOR_ATTR_2(temp3_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 1, 1),
SENSOR_ATTR_2(temp3_auto_point3_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 2, 1),
SENSOR_ATTR_2(temp3_auto_point4_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 1),
};
/* Super I/O functions */
static inline int superio_inb(int base, int reg)
{
outb(reg, base);
return inb(base + 1);
}
static int superio_inw(int base, int reg)
{
int val;
val = superio_inb(base, reg) << 8;
val |= superio_inb(base, reg + 1);
return val;
}
static inline int superio_enter(int base)
{
/* Don't step on other drivers' I/O space by accident */
if (!request_muxed_region(base, 2, DRVNAME)) {
pr_err("I/O address 0x%04x already in use\n", base);
return -EBUSY;
}
/* according to the datasheet the key must be send twice! */
outb(SIO_UNLOCK_KEY, base);
outb(SIO_UNLOCK_KEY, base);
return 0;
}
static inline void superio_select(int base, int ld)
{
outb(SIO_REG_LDSEL, base);
outb(ld, base + 1);
}
static inline void superio_exit(int base)
{
outb(SIO_LOCK_KEY, base);
release_region(base, 2);
}
static inline int fan_from_reg(u16 reg)
{
return reg ? (1500000 / reg) : 0;
}
static inline u16 fan_to_reg(int fan)
{
return fan ? (1500000 / fan) : 0;
}
static u8 f71882fg_read8(struct f71882fg_data *data, u8 reg)
{
u8 val;
outb(reg, data->addr + ADDR_REG_OFFSET);
val = inb(data->addr + DATA_REG_OFFSET);
return val;
}
static u16 f71882fg_read16(struct f71882fg_data *data, u8 reg)
{
u16 val;
val = f71882fg_read8(data, reg) << 8;
val |= f71882fg_read8(data, reg + 1);
return val;
}
static void f71882fg_write8(struct f71882fg_data *data, u8 reg, u8 val)
{
outb(reg, data->addr + ADDR_REG_OFFSET);
outb(val, data->addr + DATA_REG_OFFSET);
}
static void f71882fg_write16(struct f71882fg_data *data, u8 reg, u16 val)
{
f71882fg_write8(data, reg, val >> 8);
f71882fg_write8(data, reg + 1, val & 0xff);
}
static u16 f71882fg_read_temp(struct f71882fg_data *data, int nr)
{
if (data->type == f71858fg)
return f71882fg_read16(data, F71882FG_REG_TEMP(nr));
else
return f71882fg_read8(data, F71882FG_REG_TEMP(nr));
}
static struct f71882fg_data *f71882fg_update_device(struct device *dev)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int nr_fans = f71882fg_nr_fans[data->type];
int nr_temps = f71882fg_nr_temps[data->type];
int nr, reg, point;
mutex_lock(&data->update_lock);
/* Update once every 60 seconds */
if (time_after(jiffies, data->last_limits + 60 * HZ) ||
!data->valid) {
if (f71882fg_has_in1_alarm[data->type]) {
data->in1_max =
f71882fg_read8(data, F71882FG_REG_IN1_HIGH);
data->in_beep =
f71882fg_read8(data, F71882FG_REG_IN_BEEP);
}
/* Get High & boundary temps*/
for (nr = data->temp_start; nr < nr_temps + data->temp_start;
nr++) {
data->temp_ovt[nr] = f71882fg_read8(data,
F71882FG_REG_TEMP_OVT(nr));
data->temp_high[nr] = f71882fg_read8(data,
F71882FG_REG_TEMP_HIGH(nr));
}
if (data->type != f8000) {
data->temp_hyst[0] = f71882fg_read8(data,
F71882FG_REG_TEMP_HYST(0));
data->temp_hyst[1] = f71882fg_read8(data,
F71882FG_REG_TEMP_HYST(1));
}
/* All but the f71858fg / f8000 have this register */
if ((data->type != f71858fg) && (data->type != f8000)) {
reg = f71882fg_read8(data, F71882FG_REG_TEMP_TYPE);
data->temp_type[1] = (reg & 0x02) ? 2 : 4;
data->temp_type[2] = (reg & 0x04) ? 2 : 4;
data->temp_type[3] = (reg & 0x08) ? 2 : 4;
}
if (f71882fg_fan_has_beep[data->type])
data->fan_beep = f71882fg_read8(data,
F71882FG_REG_FAN_BEEP);
if (f71882fg_temp_has_beep[data->type])
data->temp_beep = f71882fg_read8(data,
F71882FG_REG_TEMP_BEEP);
data->pwm_enable = f71882fg_read8(data,
F71882FG_REG_PWM_ENABLE);
data->pwm_auto_point_hyst[0] =
f71882fg_read8(data, F71882FG_REG_FAN_HYST(0));
data->pwm_auto_point_hyst[1] =
f71882fg_read8(data, F71882FG_REG_FAN_HYST(1));
for (nr = 0; nr < nr_fans; nr++) {
data->pwm_auto_point_mapping[nr] =
f71882fg_read8(data,
F71882FG_REG_POINT_MAPPING(nr));
switch (data->type) {
default:
for (point = 0; point < 5; point++) {
data->pwm_auto_point_pwm[nr][point] =
f71882fg_read8(data,
F71882FG_REG_POINT_PWM
(nr, point));
}
for (point = 0; point < 4; point++) {
data->pwm_auto_point_temp[nr][point] =
f71882fg_read8(data,
F71882FG_REG_POINT_TEMP
(nr, point));
}
break;
case f71808e:
case f71869:
data->pwm_auto_point_pwm[nr][0] =
f71882fg_read8(data,
F71882FG_REG_POINT_PWM(nr, 0));
/* Fall through */
case f71862fg:
data->pwm_auto_point_pwm[nr][1] =
f71882fg_read8(data,
F71882FG_REG_POINT_PWM
(nr, 1));
data->pwm_auto_point_pwm[nr][4] =
f71882fg_read8(data,
F71882FG_REG_POINT_PWM
(nr, 4));
data->pwm_auto_point_temp[nr][0] =
f71882fg_read8(data,
F71882FG_REG_POINT_TEMP
(nr, 0));
data->pwm_auto_point_temp[nr][3] =
f71882fg_read8(data,
F71882FG_REG_POINT_TEMP
(nr, 3));
break;
}
}
data->last_limits = jiffies;
}
/* Update every second */
if (time_after(jiffies, data->last_updated + HZ) || !data->valid) {
data->temp_status = f71882fg_read8(data,
F71882FG_REG_TEMP_STATUS);
data->temp_diode_open = f71882fg_read8(data,
F71882FG_REG_TEMP_DIODE_OPEN);
for (nr = data->temp_start; nr < nr_temps + data->temp_start;
nr++)
data->temp[nr] = f71882fg_read_temp(data, nr);
data->fan_status = f71882fg_read8(data,
F71882FG_REG_FAN_STATUS);
for (nr = 0; nr < nr_fans; nr++) {
data->fan[nr] = f71882fg_read16(data,
F71882FG_REG_FAN(nr));
data->fan_target[nr] =
f71882fg_read16(data, F71882FG_REG_FAN_TARGET(nr));
data->fan_full_speed[nr] =
f71882fg_read16(data,
F71882FG_REG_FAN_FULL_SPEED(nr));
data->pwm[nr] =
f71882fg_read8(data, F71882FG_REG_PWM(nr));
}
/* Some models have 1 more fan with limited capabilities */
if (data->type == f71808a) {
data->fan[2] = f71882fg_read16(data,
F71882FG_REG_FAN(2));
data->pwm[2] = f71882fg_read8(data,
F71882FG_REG_PWM(2));
}
if (data->type == f8000)
data->fan[3] = f71882fg_read16(data,
F71882FG_REG_FAN(3));
if (f71882fg_has_in1_alarm[data->type])
data->in_status = f71882fg_read8(data,
F71882FG_REG_IN_STATUS);
for (nr = 0; nr < F71882FG_MAX_INS; nr++)
if (f71882fg_has_in[data->type][nr])
data->in[nr] = f71882fg_read8(data,
F71882FG_REG_IN(nr));
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
/* Sysfs Interface */
static ssize_t show_fan(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
int speed = fan_from_reg(data->fan[nr]);
if (speed == FAN_MIN_DETECT)
speed = 0;
return sprintf(buf, "%d\n", speed);
}
static ssize_t show_fan_full_speed(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
int speed = fan_from_reg(data->fan_full_speed[nr]);
return sprintf(buf, "%d\n", speed);
}
static ssize_t store_fan_full_speed(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
long val;
err = strict_strtol(buf, 10, &val);
if (err)
return err;
val = SENSORS_LIMIT(val, 23, 1500000);
val = fan_to_reg(val);
mutex_lock(&data->update_lock);
f71882fg_write16(data, F71882FG_REG_FAN_FULL_SPEED(nr), val);
data->fan_full_speed[nr] = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_fan_beep(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
if (data->fan_beep & (1 << nr))
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static ssize_t store_fan_beep(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
unsigned long val;
err = strict_strtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->fan_beep = f71882fg_read8(data, F71882FG_REG_FAN_BEEP);
if (val)
data->fan_beep |= 1 << nr;
else
data->fan_beep &= ~(1 << nr);
f71882fg_write8(data, F71882FG_REG_FAN_BEEP, data->fan_beep);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_fan_alarm(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
if (data->fan_status & (1 << nr))
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static ssize_t show_in(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
return sprintf(buf, "%d\n", data->in[nr] * 8);
}
static ssize_t show_in_max(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
return sprintf(buf, "%d\n", data->in1_max * 8);
}
static ssize_t store_in_max(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err;
long val;
err = strict_strtol(buf, 10, &val);
if (err)
return err;
val /= 8;
val = SENSORS_LIMIT(val, 0, 255);
mutex_lock(&data->update_lock);
f71882fg_write8(data, F71882FG_REG_IN1_HIGH, val);
data->in1_max = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_in_beep(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
if (data->in_beep & (1 << nr))
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static ssize_t store_in_beep(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
unsigned long val;
err = strict_strtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_beep = f71882fg_read8(data, F71882FG_REG_IN_BEEP);
if (val)
data->in_beep |= 1 << nr;
else
data->in_beep &= ~(1 << nr);
f71882fg_write8(data, F71882FG_REG_IN_BEEP, data->in_beep);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_in_alarm(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
if (data->in_status & (1 << nr))
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static ssize_t show_temp(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
int sign, temp;
if (data->type == f71858fg) {
/* TEMP_TABLE_SEL 1 or 3 ? */
if (data->temp_config & 1) {
sign = data->temp[nr] & 0x0001;
temp = (data->temp[nr] >> 5) & 0x7ff;
} else {
sign = data->temp[nr] & 0x8000;
temp = (data->temp[nr] >> 5) & 0x3ff;
}
temp *= 125;
if (sign)
temp -= 128000;
} else
temp = data->temp[nr] * 1000;
return sprintf(buf, "%d\n", temp);
}
static ssize_t show_temp_max(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
return sprintf(buf, "%d\n", data->temp_high[nr] * 1000);
}
static ssize_t store_temp_max(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
long val;
err = strict_strtol(buf, 10, &val);
if (err)
return err;
val /= 1000;
val = SENSORS_LIMIT(val, 0, 255);
mutex_lock(&data->update_lock);
f71882fg_write8(data, F71882FG_REG_TEMP_HIGH(nr), val);
data->temp_high[nr] = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_temp_max_hyst(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
int temp_max_hyst;
mutex_lock(&data->update_lock);
if (nr & 1)
temp_max_hyst = data->temp_hyst[nr / 2] >> 4;
else
temp_max_hyst = data->temp_hyst[nr / 2] & 0x0f;
temp_max_hyst = (data->temp_high[nr] - temp_max_hyst) * 1000;
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", temp_max_hyst);
}
static ssize_t store_temp_max_hyst(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
ssize_t ret = count;
u8 reg;
long val;
err = strict_strtol(buf, 10, &val);
if (err)
return err;
val /= 1000;
mutex_lock(&data->update_lock);
/* convert abs to relative and check */
data->temp_high[nr] = f71882fg_read8(data, F71882FG_REG_TEMP_HIGH(nr));
val = SENSORS_LIMIT(val, data->temp_high[nr] - 15,
data->temp_high[nr]);
val = data->temp_high[nr] - val;
/* convert value to register contents */
reg = f71882fg_read8(data, F71882FG_REG_TEMP_HYST(nr / 2));
if (nr & 1)
reg = (reg & 0x0f) | (val << 4);
else
reg = (reg & 0xf0) | val;
f71882fg_write8(data, F71882FG_REG_TEMP_HYST(nr / 2), reg);
data->temp_hyst[nr / 2] = reg;
mutex_unlock(&data->update_lock);
return ret;
}
static ssize_t show_temp_crit(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
return sprintf(buf, "%d\n", data->temp_ovt[nr] * 1000);
}
static ssize_t store_temp_crit(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
long val;
err = strict_strtol(buf, 10, &val);
if (err)
return err;
val /= 1000;
val = SENSORS_LIMIT(val, 0, 255);
mutex_lock(&data->update_lock);
f71882fg_write8(data, F71882FG_REG_TEMP_OVT(nr), val);
data->temp_ovt[nr] = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_temp_crit_hyst(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
int temp_crit_hyst;
mutex_lock(&data->update_lock);
if (nr & 1)
temp_crit_hyst = data->temp_hyst[nr / 2] >> 4;
else
temp_crit_hyst = data->temp_hyst[nr / 2] & 0x0f;
temp_crit_hyst = (data->temp_ovt[nr] - temp_crit_hyst) * 1000;
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", temp_crit_hyst);
}
static ssize_t show_temp_type(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
return sprintf(buf, "%d\n", data->temp_type[nr]);
}
static ssize_t show_temp_beep(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
if (data->temp_beep & (1 << nr))
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static ssize_t store_temp_beep(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
unsigned long val;
err = strict_strtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_beep = f71882fg_read8(data, F71882FG_REG_TEMP_BEEP);
if (val)
data->temp_beep |= 1 << nr;
else
data->temp_beep &= ~(1 << nr);
f71882fg_write8(data, F71882FG_REG_TEMP_BEEP, data->temp_beep);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_temp_alarm(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
if (data->temp_status & (1 << nr))
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static ssize_t show_temp_fault(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
if (data->temp_diode_open & (1 << nr))
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static ssize_t show_pwm(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int val, nr = to_sensor_dev_attr_2(devattr)->index;
mutex_lock(&data->update_lock);
if (data->pwm_enable & (1 << (2 * nr)))
/* PWM mode */
val = data->pwm[nr];
else {
/* RPM mode */
val = 255 * fan_from_reg(data->fan_target[nr])
/ fan_from_reg(data->fan_full_speed[nr]);
}
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", val);
}
static ssize_t store_pwm(struct device *dev,
struct device_attribute *devattr, const char *buf,
size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
long val;
err = strict_strtol(buf, 10, &val);
if (err)
return err;
val = SENSORS_LIMIT(val, 0, 255);
mutex_lock(&data->update_lock);
data->pwm_enable = f71882fg_read8(data, F71882FG_REG_PWM_ENABLE);
if ((data->type == f8000 && ((data->pwm_enable >> 2 * nr) & 3) != 2) ||
(data->type != f8000 && !((data->pwm_enable >> 2 * nr) & 2))) {
count = -EROFS;
goto leave;
}
if (data->pwm_enable & (1 << (2 * nr))) {
/* PWM mode */
f71882fg_write8(data, F71882FG_REG_PWM(nr), val);
data->pwm[nr] = val;
} else {
/* RPM mode */
int target, full_speed;
full_speed = f71882fg_read16(data,
F71882FG_REG_FAN_FULL_SPEED(nr));
target = fan_to_reg(val * fan_from_reg(full_speed) / 255);
f71882fg_write16(data, F71882FG_REG_FAN_TARGET(nr), target);
data->fan_target[nr] = target;
data->fan_full_speed[nr] = full_speed;
}
leave:
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_simple_pwm(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int val, nr = to_sensor_dev_attr_2(devattr)->index;
val = data->pwm[nr];
return sprintf(buf, "%d\n", val);
}
static ssize_t store_simple_pwm(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
long val;
err = strict_strtol(buf, 10, &val);
if (err)
return err;
val = SENSORS_LIMIT(val, 0, 255);
mutex_lock(&data->update_lock);
f71882fg_write8(data, F71882FG_REG_PWM(nr), val);
data->pwm[nr] = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm_enable(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int result = 0;
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
switch ((data->pwm_enable >> 2 * nr) & 3) {
case 0:
case 1:
result = 2; /* Normal auto mode */
break;
case 2:
result = 1; /* Manual mode */
break;
case 3:
if (data->type == f8000)
result = 3; /* Thermostat mode */
else
result = 1; /* Manual mode */
break;
}
return sprintf(buf, "%d\n", result);
}
static ssize_t store_pwm_enable(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
long val;
err = strict_strtol(buf, 10, &val);
if (err)
return err;
/* Special case for F8000 pwm channel 3 which only does auto mode */
if (data->type == f8000 && nr == 2 && val != 2)
return -EINVAL;
mutex_lock(&data->update_lock);
data->pwm_enable = f71882fg_read8(data, F71882FG_REG_PWM_ENABLE);
/* Special case for F8000 auto PWM mode / Thermostat mode */
if (data->type == f8000 && ((data->pwm_enable >> 2 * nr) & 1)) {
switch (val) {
case 2:
data->pwm_enable &= ~(2 << (2 * nr));
break; /* Normal auto mode */
case 3:
data->pwm_enable |= 2 << (2 * nr);
break; /* Thermostat mode */
default:
count = -EINVAL;
goto leave;
}
} else {
switch (val) {
case 1:
/* The f71858fg does not support manual RPM mode */
if (data->type == f71858fg &&
((data->pwm_enable >> (2 * nr)) & 1)) {
count = -EINVAL;
goto leave;
}
data->pwm_enable |= 2 << (2 * nr);
break; /* Manual */
case 2:
data->pwm_enable &= ~(2 << (2 * nr));
break; /* Normal auto mode */
default:
count = -EINVAL;
goto leave;
}
}
f71882fg_write8(data, F71882FG_REG_PWM_ENABLE, data->pwm_enable);
leave:
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm_auto_point_pwm(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
int result;
struct f71882fg_data *data = f71882fg_update_device(dev);
int pwm = to_sensor_dev_attr_2(devattr)->index;
int point = to_sensor_dev_attr_2(devattr)->nr;
mutex_lock(&data->update_lock);
if (data->pwm_enable & (1 << (2 * pwm))) {
/* PWM mode */
result = data->pwm_auto_point_pwm[pwm][point];
} else {
/* RPM mode */
result = 32 * 255 / (32 + data->pwm_auto_point_pwm[pwm][point]);
}
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", result);
}
static ssize_t store_pwm_auto_point_pwm(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, pwm = to_sensor_dev_attr_2(devattr)->index;
int point = to_sensor_dev_attr_2(devattr)->nr;
long val;
err = strict_strtol(buf, 10, &val);
if (err)
return err;
val = SENSORS_LIMIT(val, 0, 255);
mutex_lock(&data->update_lock);
data->pwm_enable = f71882fg_read8(data, F71882FG_REG_PWM_ENABLE);
if (data->pwm_enable & (1 << (2 * pwm))) {
/* PWM mode */
} else {
/* RPM mode */
if (val < 29) /* Prevent negative numbers */
val = 255;
else
val = (255 - val) * 32 / val;
}
f71882fg_write8(data, F71882FG_REG_POINT_PWM(pwm, point), val);
data->pwm_auto_point_pwm[pwm][point] = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm_auto_point_temp_hyst(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
int result = 0;
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
int point = to_sensor_dev_attr_2(devattr)->nr;
mutex_lock(&data->update_lock);
if (nr & 1)
result = data->pwm_auto_point_hyst[nr / 2] >> 4;
else
result = data->pwm_auto_point_hyst[nr / 2] & 0x0f;
result = 1000 * (data->pwm_auto_point_temp[nr][point] - result);
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", result);
}
static ssize_t store_pwm_auto_point_temp_hyst(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
int point = to_sensor_dev_attr_2(devattr)->nr;
u8 reg;
long val;
err = strict_strtol(buf, 10, &val);
if (err)
return err;
val /= 1000;
mutex_lock(&data->update_lock);
data->pwm_auto_point_temp[nr][point] =
f71882fg_read8(data, F71882FG_REG_POINT_TEMP(nr, point));
val = SENSORS_LIMIT(val, data->pwm_auto_point_temp[nr][point] - 15,
data->pwm_auto_point_temp[nr][point]);
val = data->pwm_auto_point_temp[nr][point] - val;
reg = f71882fg_read8(data, F71882FG_REG_FAN_HYST(nr / 2));
if (nr & 1)
reg = (reg & 0x0f) | (val << 4);
else
reg = (reg & 0xf0) | val;
f71882fg_write8(data, F71882FG_REG_FAN_HYST(nr / 2), reg);
data->pwm_auto_point_hyst[nr / 2] = reg;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm_interpolate(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int result;
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
result = (data->pwm_auto_point_mapping[nr] >> 4) & 1;
return sprintf(buf, "%d\n", result);
}
static ssize_t store_pwm_interpolate(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
unsigned long val;
err = strict_strtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->pwm_auto_point_mapping[nr] =
f71882fg_read8(data, F71882FG_REG_POINT_MAPPING(nr));
if (val)
val = data->pwm_auto_point_mapping[nr] | (1 << 4);
else
val = data->pwm_auto_point_mapping[nr] & (~(1 << 4));
f71882fg_write8(data, F71882FG_REG_POINT_MAPPING(nr), val);
data->pwm_auto_point_mapping[nr] = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm_auto_point_channel(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
int result;
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
result = 1 << ((data->pwm_auto_point_mapping[nr] & 3) -
data->temp_start);
return sprintf(buf, "%d\n", result);
}
static ssize_t store_pwm_auto_point_channel(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
long val;
err = strict_strtol(buf, 10, &val);
if (err)
return err;
switch (val) {
case 1:
val = 0;
break;
case 2:
val = 1;
break;
case 4:
val = 2;
break;
default:
return -EINVAL;
}
val += data->temp_start;
mutex_lock(&data->update_lock);
data->pwm_auto_point_mapping[nr] =
f71882fg_read8(data, F71882FG_REG_POINT_MAPPING(nr));
val = (data->pwm_auto_point_mapping[nr] & 0xfc) | val;
f71882fg_write8(data, F71882FG_REG_POINT_MAPPING(nr), val);
data->pwm_auto_point_mapping[nr] = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm_auto_point_temp(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
int result;
struct f71882fg_data *data = f71882fg_update_device(dev);
int pwm = to_sensor_dev_attr_2(devattr)->index;
int point = to_sensor_dev_attr_2(devattr)->nr;
result = data->pwm_auto_point_temp[pwm][point];
return sprintf(buf, "%d\n", 1000 * result);
}
static ssize_t store_pwm_auto_point_temp(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, pwm = to_sensor_dev_attr_2(devattr)->index;
int point = to_sensor_dev_attr_2(devattr)->nr;
long val;
err = strict_strtol(buf, 10, &val);
if (err)
return err;
val /= 1000;
if (data->auto_point_temp_signed)
val = SENSORS_LIMIT(val, -128, 127);
else
val = SENSORS_LIMIT(val, 0, 127);
mutex_lock(&data->update_lock);
f71882fg_write8(data, F71882FG_REG_POINT_TEMP(pwm, point), val);
data->pwm_auto_point_temp[pwm][point] = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_name(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%s\n", f71882fg_names[data->type]);
}
static int __devinit f71882fg_create_sysfs_files(struct platform_device *pdev,
struct sensor_device_attribute_2 *attr, int count)
{
int err, i;
for (i = 0; i < count; i++) {
err = device_create_file(&pdev->dev, &attr[i].dev_attr);
if (err)
return err;
}
return 0;
}
static void f71882fg_remove_sysfs_files(struct platform_device *pdev,
struct sensor_device_attribute_2 *attr, int count)
{
int i;
for (i = 0; i < count; i++)
device_remove_file(&pdev->dev, &attr[i].dev_attr);
}
static int __devinit f71882fg_probe(struct platform_device *pdev)
{
struct f71882fg_data *data;
struct f71882fg_sio_data *sio_data = pdev->dev.platform_data;
int nr_fans = f71882fg_nr_fans[sio_data->type];
int nr_temps = f71882fg_nr_temps[sio_data->type];
int err, i;
u8 start_reg, reg;
data = kzalloc(sizeof(struct f71882fg_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
data->addr = platform_get_resource(pdev, IORESOURCE_IO, 0)->start;
data->type = sio_data->type;
data->temp_start =
(data->type == f71858fg || data->type == f8000) ? 0 : 1;
mutex_init(&data->update_lock);
platform_set_drvdata(pdev, data);
start_reg = f71882fg_read8(data, F71882FG_REG_START);
if (start_reg & 0x04) {
dev_warn(&pdev->dev, "Hardware monitor is powered down\n");
err = -ENODEV;
goto exit_free;
}
if (!(start_reg & 0x03)) {
dev_warn(&pdev->dev, "Hardware monitoring not activated\n");
err = -ENODEV;
goto exit_free;
}
/* Register sysfs interface files */
err = device_create_file(&pdev->dev, &dev_attr_name);
if (err)
goto exit_unregister_sysfs;
if (start_reg & 0x01) {
switch (data->type) {
case f71858fg:
data->temp_config =
f71882fg_read8(data, F71882FG_REG_TEMP_CONFIG);
if (data->temp_config & 0x10)
/* The f71858fg temperature alarms behave as
the f8000 alarms in this mode */
err = f71882fg_create_sysfs_files(pdev,
f8000_temp_attr,
ARRAY_SIZE(f8000_temp_attr));
else
err = f71882fg_create_sysfs_files(pdev,
f71858fg_temp_attr,
ARRAY_SIZE(f71858fg_temp_attr));
break;
case f8000:
err = f71882fg_create_sysfs_files(pdev,
f8000_temp_attr,
ARRAY_SIZE(f8000_temp_attr));
break;
default:
err = f71882fg_create_sysfs_files(pdev,
&fxxxx_temp_attr[0][0],
ARRAY_SIZE(fxxxx_temp_attr[0]) * nr_temps);
}
if (err)
goto exit_unregister_sysfs;
if (f71882fg_temp_has_beep[data->type]) {
err = f71882fg_create_sysfs_files(pdev,
&fxxxx_temp_beep_attr[0][0],
ARRAY_SIZE(fxxxx_temp_beep_attr[0])
* nr_temps);
if (err)
goto exit_unregister_sysfs;
}
for (i = 0; i < F71882FG_MAX_INS; i++) {
if (f71882fg_has_in[data->type][i]) {
err = device_create_file(&pdev->dev,
&fxxxx_in_attr[i].dev_attr);
if (err)
goto exit_unregister_sysfs;
}
}
if (f71882fg_has_in1_alarm[data->type]) {
err = f71882fg_create_sysfs_files(pdev,
fxxxx_in1_alarm_attr,
ARRAY_SIZE(fxxxx_in1_alarm_attr));
if (err)
goto exit_unregister_sysfs;
}
}
if (start_reg & 0x02) {
switch (data->type) {
case f71808e:
case f71808a:
case f71869:
case f71869a:
/* These always have signed auto point temps */
data->auto_point_temp_signed = 1;
/* Fall through to select correct fan/pwm reg bank! */
case f71889fg:
case f71889ed:
case f71889a:
reg = f71882fg_read8(data, F71882FG_REG_FAN_FAULT_T);
if (reg & F71882FG_FAN_NEG_TEMP_EN)
data->auto_point_temp_signed = 1;
/* Ensure banked pwm registers point to right bank */
reg &= ~F71882FG_FAN_PROG_SEL;
f71882fg_write8(data, F71882FG_REG_FAN_FAULT_T, reg);
break;
default:
break;
}
data->pwm_enable =
f71882fg_read8(data, F71882FG_REG_PWM_ENABLE);
/* Sanity check the pwm settings */
switch (data->type) {
case f71858fg:
err = 0;
for (i = 0; i < nr_fans; i++)
if (((data->pwm_enable >> (i * 2)) & 3) == 3)
err = 1;
break;
case f71862fg:
err = (data->pwm_enable & 0x15) != 0x15;
break;
case f8000:
err = data->pwm_enable & 0x20;
break;
default:
err = 0;
break;
}
if (err) {
dev_err(&pdev->dev,
"Invalid (reserved) pwm settings: 0x%02x\n",
(unsigned int)data->pwm_enable);
err = -ENODEV;
goto exit_unregister_sysfs;
}
err = f71882fg_create_sysfs_files(pdev, &fxxxx_fan_attr[0][0],
ARRAY_SIZE(fxxxx_fan_attr[0]) * nr_fans);
if (err)
goto exit_unregister_sysfs;
if (f71882fg_fan_has_beep[data->type]) {
err = f71882fg_create_sysfs_files(pdev,
fxxxx_fan_beep_attr, nr_fans);
if (err)
goto exit_unregister_sysfs;
}
switch (data->type) {
case f71808e:
case f71808a:
case f71869:
case f71869a:
case f71889fg:
case f71889ed:
case f71889a:
for (i = 0; i < nr_fans; i++) {
data->pwm_auto_point_mapping[i] =
f71882fg_read8(data,
F71882FG_REG_POINT_MAPPING(i));
if ((data->pwm_auto_point_mapping[i] & 0x80) ||
(data->pwm_auto_point_mapping[i] & 3) == 0)
break;
}
if (i != nr_fans) {
dev_warn(&pdev->dev,
"Auto pwm controlled by raw digital "
"data, disabling pwm auto_point "
"sysfs attributes\n");
goto no_pwm_auto_point;
}
break;
default:
break;
}
switch (data->type) {
case f71808a:
err = f71882fg_create_sysfs_files(pdev,
&fxxxx_auto_pwm_attr[0][0],
ARRAY_SIZE(fxxxx_auto_pwm_attr[0]) * nr_fans);
if (err)
goto exit_unregister_sysfs;
err = f71882fg_create_sysfs_files(pdev,
f71808a_fan3_attr,
ARRAY_SIZE(f71808a_fan3_attr));
break;
case f71862fg:
err = f71882fg_create_sysfs_files(pdev,
f71862fg_auto_pwm_attr,
ARRAY_SIZE(f71862fg_auto_pwm_attr));
break;
case f71808e:
case f71869:
err = f71882fg_create_sysfs_files(pdev,
f71869_auto_pwm_attr,
ARRAY_SIZE(f71869_auto_pwm_attr));
break;
case f8000:
err = f71882fg_create_sysfs_files(pdev,
f8000_fan_attr,
ARRAY_SIZE(f8000_fan_attr));
if (err)
goto exit_unregister_sysfs;
err = f71882fg_create_sysfs_files(pdev,
f8000_auto_pwm_attr,
ARRAY_SIZE(f8000_auto_pwm_attr));
break;
default:
err = f71882fg_create_sysfs_files(pdev,
&fxxxx_auto_pwm_attr[0][0],
ARRAY_SIZE(fxxxx_auto_pwm_attr[0]) * nr_fans);
}
if (err)
goto exit_unregister_sysfs;
no_pwm_auto_point:
for (i = 0; i < nr_fans; i++)
dev_info(&pdev->dev, "Fan: %d is in %s mode\n", i + 1,
(data->pwm_enable & (1 << 2 * i)) ?
"duty-cycle" : "RPM");
}
data->hwmon_dev = hwmon_device_register(&pdev->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
data->hwmon_dev = NULL;
goto exit_unregister_sysfs;
}
return 0;
exit_unregister_sysfs:
f71882fg_remove(pdev); /* Will unregister the sysfs files for us */
return err; /* f71882fg_remove() also frees our data */
exit_free:
kfree(data);
return err;
}
static int f71882fg_remove(struct platform_device *pdev)
{
struct f71882fg_data *data = platform_get_drvdata(pdev);
int nr_fans = f71882fg_nr_fans[data->type];
int nr_temps = f71882fg_nr_temps[data->type];
int i;
u8 start_reg = f71882fg_read8(data, F71882FG_REG_START);
if (data->hwmon_dev)
hwmon_device_unregister(data->hwmon_dev);
device_remove_file(&pdev->dev, &dev_attr_name);
if (start_reg & 0x01) {
switch (data->type) {
case f71858fg:
if (data->temp_config & 0x10)
f71882fg_remove_sysfs_files(pdev,
f8000_temp_attr,
ARRAY_SIZE(f8000_temp_attr));
else
f71882fg_remove_sysfs_files(pdev,
f71858fg_temp_attr,
ARRAY_SIZE(f71858fg_temp_attr));
break;
case f8000:
f71882fg_remove_sysfs_files(pdev,
f8000_temp_attr,
ARRAY_SIZE(f8000_temp_attr));
break;
default:
f71882fg_remove_sysfs_files(pdev,
&fxxxx_temp_attr[0][0],
ARRAY_SIZE(fxxxx_temp_attr[0]) * nr_temps);
}
if (f71882fg_temp_has_beep[data->type]) {
f71882fg_remove_sysfs_files(pdev,
&fxxxx_temp_beep_attr[0][0],
ARRAY_SIZE(fxxxx_temp_beep_attr[0]) * nr_temps);
}
for (i = 0; i < F71882FG_MAX_INS; i++) {
if (f71882fg_has_in[data->type][i]) {
device_remove_file(&pdev->dev,
&fxxxx_in_attr[i].dev_attr);
}
}
if (f71882fg_has_in1_alarm[data->type]) {
f71882fg_remove_sysfs_files(pdev,
fxxxx_in1_alarm_attr,
ARRAY_SIZE(fxxxx_in1_alarm_attr));
}
}
if (start_reg & 0x02) {
f71882fg_remove_sysfs_files(pdev, &fxxxx_fan_attr[0][0],
ARRAY_SIZE(fxxxx_fan_attr[0]) * nr_fans);
if (f71882fg_fan_has_beep[data->type]) {
f71882fg_remove_sysfs_files(pdev,
fxxxx_fan_beep_attr, nr_fans);
}
switch (data->type) {
case f71808a:
f71882fg_remove_sysfs_files(pdev,
&fxxxx_auto_pwm_attr[0][0],
ARRAY_SIZE(fxxxx_auto_pwm_attr[0]) * nr_fans);
f71882fg_remove_sysfs_files(pdev,
f71808a_fan3_attr,
ARRAY_SIZE(f71808a_fan3_attr));
break;
case f71862fg:
f71882fg_remove_sysfs_files(pdev,
f71862fg_auto_pwm_attr,
ARRAY_SIZE(f71862fg_auto_pwm_attr));
break;
case f71808e:
case f71869:
f71882fg_remove_sysfs_files(pdev,
f71869_auto_pwm_attr,
ARRAY_SIZE(f71869_auto_pwm_attr));
break;
case f8000:
f71882fg_remove_sysfs_files(pdev,
f8000_fan_attr,
ARRAY_SIZE(f8000_fan_attr));
f71882fg_remove_sysfs_files(pdev,
f8000_auto_pwm_attr,
ARRAY_SIZE(f8000_auto_pwm_attr));
break;
default:
f71882fg_remove_sysfs_files(pdev,
&fxxxx_auto_pwm_attr[0][0],
ARRAY_SIZE(fxxxx_auto_pwm_attr[0]) * nr_fans);
}
}
platform_set_drvdata(pdev, NULL);
kfree(data);
return 0;
}
static int __init f71882fg_find(int sioaddr, unsigned short *address,
struct f71882fg_sio_data *sio_data)
{
u16 devid;
int err = superio_enter(sioaddr);
if (err)
return err;
devid = superio_inw(sioaddr, SIO_REG_MANID);
if (devid != SIO_FINTEK_ID) {
pr_debug("Not a Fintek device\n");
err = -ENODEV;
goto exit;
}
devid = force_id ? force_id : superio_inw(sioaddr, SIO_REG_DEVID);
switch (devid) {
case SIO_F71808E_ID:
sio_data->type = f71808e;
break;
case SIO_F71808A_ID:
sio_data->type = f71808a;
break;
case SIO_F71858_ID:
sio_data->type = f71858fg;
break;
case SIO_F71862_ID:
sio_data->type = f71862fg;
break;
case SIO_F71869_ID:
sio_data->type = f71869;
break;
case SIO_F71869A_ID:
sio_data->type = f71869a;
break;
case SIO_F71882_ID:
sio_data->type = f71882fg;
break;
case SIO_F71889_ID:
sio_data->type = f71889fg;
break;
case SIO_F71889E_ID:
sio_data->type = f71889ed;
break;
case SIO_F71889A_ID:
sio_data->type = f71889a;
break;
case SIO_F8000_ID:
sio_data->type = f8000;
break;
case SIO_F81865_ID:
sio_data->type = f81865f;
break;
default:
pr_info("Unsupported Fintek device: %04x\n",
(unsigned int)devid);
err = -ENODEV;
goto exit;
}
if (sio_data->type == f71858fg)
superio_select(sioaddr, SIO_F71858FG_LD_HWM);
else
superio_select(sioaddr, SIO_F71882FG_LD_HWM);
if (!(superio_inb(sioaddr, SIO_REG_ENABLE) & 0x01)) {
pr_warn("Device not activated\n");
err = -ENODEV;
goto exit;
}
*address = superio_inw(sioaddr, SIO_REG_ADDR);
if (*address == 0) {
pr_warn("Base address not set\n");
err = -ENODEV;
goto exit;
}
*address &= ~(REGION_LENGTH - 1); /* Ignore 3 LSB */
err = 0;
pr_info("Found %s chip at %#x, revision %d\n",
f71882fg_names[sio_data->type], (unsigned int)*address,
(int)superio_inb(sioaddr, SIO_REG_DEVREV));
exit:
superio_exit(sioaddr);
return err;
}
static int __init f71882fg_device_add(unsigned short address,
const struct f71882fg_sio_data *sio_data)
{
struct resource res = {
.start = address,
.end = address + REGION_LENGTH - 1,
.flags = IORESOURCE_IO,
};
int err;
f71882fg_pdev = platform_device_alloc(DRVNAME, address);
if (!f71882fg_pdev)
return -ENOMEM;
res.name = f71882fg_pdev->name;
err = acpi_check_resource_conflict(&res);
if (err)
goto exit_device_put;
err = platform_device_add_resources(f71882fg_pdev, &res, 1);
if (err) {
pr_err("Device resource addition failed\n");
goto exit_device_put;
}
err = platform_device_add_data(f71882fg_pdev, sio_data,
sizeof(struct f71882fg_sio_data));
if (err) {
pr_err("Platform data allocation failed\n");
goto exit_device_put;
}
err = platform_device_add(f71882fg_pdev);
if (err) {
pr_err("Device addition failed\n");
goto exit_device_put;
}
return 0;
exit_device_put:
platform_device_put(f71882fg_pdev);
return err;
}
static int __init f71882fg_init(void)
{
int err = -ENODEV;
unsigned short address;
struct f71882fg_sio_data sio_data;
memset(&sio_data, 0, sizeof(sio_data));
if (f71882fg_find(0x2e, &address, &sio_data) &&
f71882fg_find(0x4e, &address, &sio_data))
goto exit;
err = platform_driver_register(&f71882fg_driver);
if (err)
goto exit;
err = f71882fg_device_add(address, &sio_data);
if (err)
goto exit_driver;
return 0;
exit_driver:
platform_driver_unregister(&f71882fg_driver);
exit:
return err;
}
static void __exit f71882fg_exit(void)
{
platform_device_unregister(f71882fg_pdev);
platform_driver_unregister(&f71882fg_driver);
}
MODULE_DESCRIPTION("F71882FG Hardware Monitoring Driver");
MODULE_AUTHOR("Hans Edgington, Hans de Goede <hdegoede@redhat.com>");
MODULE_LICENSE("GPL");
module_init(f71882fg_init);
module_exit(f71882fg_exit);
| gpl-2.0 |
MoKee/android_kernel_amazon_otter-common | sound/soc/codecs/tlv320aic23.c | 2764 | 21156 | /*
* ALSA SoC TLV320AIC23 codec driver
*
* Author: Arun KS, <arunks@mistralsolutions.com>
* Copyright: (C) 2008 Mistral Solutions Pvt Ltd.,
*
* Based on sound/soc/codecs/wm8731.c by Richard Purdie
*
* 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.
*
* Notes:
* The AIC23 is a driver for a low power stereo audio
* codec tlv320aic23
*
* The machine layer should disable unsupported inputs/outputs by
* snd_soc_dapm_disable_pin(codec, "LHPOUT"), etc.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/i2c.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/tlv.h>
#include <sound/initval.h>
#include "tlv320aic23.h"
#define AIC23_VERSION "0.1"
/*
* AIC23 register cache
*/
static const u16 tlv320aic23_reg[] = {
0x0097, 0x0097, 0x00F9, 0x00F9, /* 0 */
0x001A, 0x0004, 0x0007, 0x0001, /* 4 */
0x0020, 0x0000, 0x0000, 0x0000, /* 8 */
0x0000, 0x0000, 0x0000, 0x0000, /* 12 */
};
/*
* read tlv320aic23 register cache
*/
static inline unsigned int tlv320aic23_read_reg_cache(struct snd_soc_codec
*codec, unsigned int reg)
{
u16 *cache = codec->reg_cache;
if (reg >= ARRAY_SIZE(tlv320aic23_reg))
return -1;
return cache[reg];
}
/*
* write tlv320aic23 register cache
*/
static inline void tlv320aic23_write_reg_cache(struct snd_soc_codec *codec,
u8 reg, u16 value)
{
u16 *cache = codec->reg_cache;
if (reg >= ARRAY_SIZE(tlv320aic23_reg))
return;
cache[reg] = value;
}
/*
* write to the tlv320aic23 register space
*/
static int tlv320aic23_write(struct snd_soc_codec *codec, unsigned int reg,
unsigned int value)
{
u8 data[2];
/* TLV320AIC23 has 7 bit address and 9 bits of data
* so we need to switch one data bit into reg and rest
* of data into val
*/
if (reg > 9 && reg != 15) {
printk(KERN_WARNING "%s Invalid register R%u\n", __func__, reg);
return -1;
}
data[0] = (reg << 1) | (value >> 8 & 0x01);
data[1] = value & 0xff;
tlv320aic23_write_reg_cache(codec, reg, value);
if (codec->hw_write(codec->control_data, data, 2) == 2)
return 0;
printk(KERN_ERR "%s cannot write %03x to register R%u\n", __func__,
value, reg);
return -EIO;
}
static const char *rec_src_text[] = { "Line", "Mic" };
static const char *deemph_text[] = {"None", "32Khz", "44.1Khz", "48Khz"};
static const struct soc_enum rec_src_enum =
SOC_ENUM_SINGLE(TLV320AIC23_ANLG, 2, 2, rec_src_text);
static const struct snd_kcontrol_new tlv320aic23_rec_src_mux_controls =
SOC_DAPM_ENUM("Input Select", rec_src_enum);
static const struct soc_enum tlv320aic23_rec_src =
SOC_ENUM_SINGLE(TLV320AIC23_ANLG, 2, 2, rec_src_text);
static const struct soc_enum tlv320aic23_deemph =
SOC_ENUM_SINGLE(TLV320AIC23_DIGT, 1, 4, deemph_text);
static const DECLARE_TLV_DB_SCALE(out_gain_tlv, -12100, 100, 0);
static const DECLARE_TLV_DB_SCALE(input_gain_tlv, -1725, 75, 0);
static const DECLARE_TLV_DB_SCALE(sidetone_vol_tlv, -1800, 300, 0);
static int snd_soc_tlv320aic23_put_volsw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
u16 val, reg;
val = (ucontrol->value.integer.value[0] & 0x07);
/* linear conversion to userspace
* 000 = -6db
* 001 = -9db
* 010 = -12db
* 011 = -18db (Min)
* 100 = 0db (Max)
*/
val = (val >= 4) ? 4 : (3 - val);
reg = tlv320aic23_read_reg_cache(codec, TLV320AIC23_ANLG) & (~0x1C0);
tlv320aic23_write(codec, TLV320AIC23_ANLG, reg | (val << 6));
return 0;
}
static int snd_soc_tlv320aic23_get_volsw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
u16 val;
val = tlv320aic23_read_reg_cache(codec, TLV320AIC23_ANLG) & (0x1C0);
val = val >> 6;
val = (val >= 4) ? 4 : (3 - val);
ucontrol->value.integer.value[0] = val;
return 0;
}
#define SOC_TLV320AIC23_SINGLE_TLV(xname, reg, shift, max, invert, tlv_array) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.access = SNDRV_CTL_ELEM_ACCESS_TLV_READ |\
SNDRV_CTL_ELEM_ACCESS_READWRITE,\
.tlv.p = (tlv_array), \
.info = snd_soc_info_volsw, .get = snd_soc_tlv320aic23_get_volsw,\
.put = snd_soc_tlv320aic23_put_volsw, \
.private_value = SOC_SINGLE_VALUE(reg, shift, max, invert) }
static const struct snd_kcontrol_new tlv320aic23_snd_controls[] = {
SOC_DOUBLE_R_TLV("Digital Playback Volume", TLV320AIC23_LCHNVOL,
TLV320AIC23_RCHNVOL, 0, 127, 0, out_gain_tlv),
SOC_SINGLE("Digital Playback Switch", TLV320AIC23_DIGT, 3, 1, 1),
SOC_DOUBLE_R("Line Input Switch", TLV320AIC23_LINVOL,
TLV320AIC23_RINVOL, 7, 1, 0),
SOC_DOUBLE_R_TLV("Line Input Volume", TLV320AIC23_LINVOL,
TLV320AIC23_RINVOL, 0, 31, 0, input_gain_tlv),
SOC_SINGLE("Mic Input Switch", TLV320AIC23_ANLG, 1, 1, 1),
SOC_SINGLE("Mic Booster Switch", TLV320AIC23_ANLG, 0, 1, 0),
SOC_TLV320AIC23_SINGLE_TLV("Sidetone Volume", TLV320AIC23_ANLG,
6, 4, 0, sidetone_vol_tlv),
SOC_ENUM("Playback De-emphasis", tlv320aic23_deemph),
};
/* PGA Mixer controls for Line and Mic switch */
static const struct snd_kcontrol_new tlv320aic23_output_mixer_controls[] = {
SOC_DAPM_SINGLE("Line Bypass Switch", TLV320AIC23_ANLG, 3, 1, 0),
SOC_DAPM_SINGLE("Mic Sidetone Switch", TLV320AIC23_ANLG, 5, 1, 0),
SOC_DAPM_SINGLE("Playback Switch", TLV320AIC23_ANLG, 4, 1, 0),
};
static const struct snd_soc_dapm_widget tlv320aic23_dapm_widgets[] = {
SND_SOC_DAPM_DAC("DAC", "Playback", TLV320AIC23_PWR, 3, 1),
SND_SOC_DAPM_ADC("ADC", "Capture", TLV320AIC23_PWR, 2, 1),
SND_SOC_DAPM_MUX("Capture Source", SND_SOC_NOPM, 0, 0,
&tlv320aic23_rec_src_mux_controls),
SND_SOC_DAPM_MIXER("Output Mixer", TLV320AIC23_PWR, 4, 1,
&tlv320aic23_output_mixer_controls[0],
ARRAY_SIZE(tlv320aic23_output_mixer_controls)),
SND_SOC_DAPM_PGA("Line Input", TLV320AIC23_PWR, 0, 1, NULL, 0),
SND_SOC_DAPM_PGA("Mic Input", TLV320AIC23_PWR, 1, 1, NULL, 0),
SND_SOC_DAPM_OUTPUT("LHPOUT"),
SND_SOC_DAPM_OUTPUT("RHPOUT"),
SND_SOC_DAPM_OUTPUT("LOUT"),
SND_SOC_DAPM_OUTPUT("ROUT"),
SND_SOC_DAPM_INPUT("LLINEIN"),
SND_SOC_DAPM_INPUT("RLINEIN"),
SND_SOC_DAPM_INPUT("MICIN"),
};
static const struct snd_soc_dapm_route tlv320aic23_intercon[] = {
/* Output Mixer */
{"Output Mixer", "Line Bypass Switch", "Line Input"},
{"Output Mixer", "Playback Switch", "DAC"},
{"Output Mixer", "Mic Sidetone Switch", "Mic Input"},
/* Outputs */
{"RHPOUT", NULL, "Output Mixer"},
{"LHPOUT", NULL, "Output Mixer"},
{"LOUT", NULL, "Output Mixer"},
{"ROUT", NULL, "Output Mixer"},
/* Inputs */
{"Line Input", "NULL", "LLINEIN"},
{"Line Input", "NULL", "RLINEIN"},
{"Mic Input", "NULL", "MICIN"},
/* input mux */
{"Capture Source", "Line", "Line Input"},
{"Capture Source", "Mic", "Mic Input"},
{"ADC", NULL, "Capture Source"},
};
/* AIC23 driver data */
struct aic23 {
enum snd_soc_control_type control_type;
void *control_data;
int mclk;
int requested_adc;
int requested_dac;
};
/*
* Common Crystals used
* 11.2896 Mhz /128 = *88.2k /192 = 58.8k
* 12.0000 Mhz /125 = *96k /136 = 88.235K
* 12.2880 Mhz /128 = *96k /192 = 64k
* 16.9344 Mhz /128 = 132.3k /192 = *88.2k
* 18.4320 Mhz /128 = 144k /192 = *96k
*/
/*
* Normal BOSR 0-256/2 = 128, 1-384/2 = 192
* USB BOSR 0-250/2 = 125, 1-272/2 = 136
*/
static const int bosr_usb_divisor_table[] = {
128, 125, 192, 136
};
#define LOWER_GROUP ((1<<0) | (1<<1) | (1<<2) | (1<<3) | (1<<6) | (1<<7))
#define UPPER_GROUP ((1<<8) | (1<<9) | (1<<10) | (1<<11) | (1<<15))
static const unsigned short sr_valid_mask[] = {
LOWER_GROUP|UPPER_GROUP, /* Normal, bosr - 0*/
LOWER_GROUP, /* Usb, bosr - 0*/
LOWER_GROUP|UPPER_GROUP, /* Normal, bosr - 1*/
UPPER_GROUP, /* Usb, bosr - 1*/
};
/*
* Every divisor is a factor of 11*12
*/
#define SR_MULT (11*12)
#define A(x) (SR_MULT/x)
static const unsigned char sr_adc_mult_table[] = {
A(2), A(2), A(12), A(12), 0, 0, A(3), A(1),
A(2), A(2), A(11), A(11), 0, 0, 0, A(1)
};
static const unsigned char sr_dac_mult_table[] = {
A(2), A(12), A(2), A(12), 0, 0, A(3), A(1),
A(2), A(11), A(2), A(11), 0, 0, 0, A(1)
};
static unsigned get_score(int adc, int adc_l, int adc_h, int need_adc,
int dac, int dac_l, int dac_h, int need_dac)
{
if ((adc >= adc_l) && (adc <= adc_h) &&
(dac >= dac_l) && (dac <= dac_h)) {
int diff_adc = need_adc - adc;
int diff_dac = need_dac - dac;
return abs(diff_adc) + abs(diff_dac);
}
return UINT_MAX;
}
static int find_rate(int mclk, u32 need_adc, u32 need_dac)
{
int i, j;
int best_i = -1;
int best_j = -1;
int best_div = 0;
unsigned best_score = UINT_MAX;
int adc_l, adc_h, dac_l, dac_h;
need_adc *= SR_MULT;
need_dac *= SR_MULT;
/*
* rates given are +/- 1/32
*/
adc_l = need_adc - (need_adc >> 5);
adc_h = need_adc + (need_adc >> 5);
dac_l = need_dac - (need_dac >> 5);
dac_h = need_dac + (need_dac >> 5);
for (i = 0; i < ARRAY_SIZE(bosr_usb_divisor_table); i++) {
int base = mclk / bosr_usb_divisor_table[i];
int mask = sr_valid_mask[i];
for (j = 0; j < ARRAY_SIZE(sr_adc_mult_table);
j++, mask >>= 1) {
int adc;
int dac;
int score;
if ((mask & 1) == 0)
continue;
adc = base * sr_adc_mult_table[j];
dac = base * sr_dac_mult_table[j];
score = get_score(adc, adc_l, adc_h, need_adc,
dac, dac_l, dac_h, need_dac);
if (best_score > score) {
best_score = score;
best_i = i;
best_j = j;
best_div = 0;
}
score = get_score((adc >> 1), adc_l, adc_h, need_adc,
(dac >> 1), dac_l, dac_h, need_dac);
/* prefer to have a /2 */
if ((score != UINT_MAX) && (best_score >= score)) {
best_score = score;
best_i = i;
best_j = j;
best_div = 1;
}
}
}
return (best_j << 2) | best_i | (best_div << TLV320AIC23_CLKIN_SHIFT);
}
#ifdef DEBUG
static void get_current_sample_rates(struct snd_soc_codec *codec, int mclk,
u32 *sample_rate_adc, u32 *sample_rate_dac)
{
int src = tlv320aic23_read_reg_cache(codec, TLV320AIC23_SRATE);
int sr = (src >> 2) & 0x0f;
int val = (mclk / bosr_usb_divisor_table[src & 3]);
int adc = (val * sr_adc_mult_table[sr]) / SR_MULT;
int dac = (val * sr_dac_mult_table[sr]) / SR_MULT;
if (src & TLV320AIC23_CLKIN_HALF) {
adc >>= 1;
dac >>= 1;
}
*sample_rate_adc = adc;
*sample_rate_dac = dac;
}
#endif
static int set_sample_rate_control(struct snd_soc_codec *codec, int mclk,
u32 sample_rate_adc, u32 sample_rate_dac)
{
/* Search for the right sample rate */
int data = find_rate(mclk, sample_rate_adc, sample_rate_dac);
if (data < 0) {
printk(KERN_ERR "%s:Invalid rate %u,%u requested\n",
__func__, sample_rate_adc, sample_rate_dac);
return -EINVAL;
}
tlv320aic23_write(codec, TLV320AIC23_SRATE, data);
#ifdef DEBUG
{
u32 adc, dac;
get_current_sample_rates(codec, mclk, &adc, &dac);
printk(KERN_DEBUG "actual samplerate = %u,%u reg=%x\n",
adc, dac, data);
}
#endif
return 0;
}
static int tlv320aic23_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_codec *codec = rtd->codec;
u16 iface_reg;
int ret;
struct aic23 *aic23 = snd_soc_codec_get_drvdata(codec);
u32 sample_rate_adc = aic23->requested_adc;
u32 sample_rate_dac = aic23->requested_dac;
u32 sample_rate = params_rate(params);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
aic23->requested_dac = sample_rate_dac = sample_rate;
if (!sample_rate_adc)
sample_rate_adc = sample_rate;
} else {
aic23->requested_adc = sample_rate_adc = sample_rate;
if (!sample_rate_dac)
sample_rate_dac = sample_rate;
}
ret = set_sample_rate_control(codec, aic23->mclk, sample_rate_adc,
sample_rate_dac);
if (ret < 0)
return ret;
iface_reg =
tlv320aic23_read_reg_cache(codec,
TLV320AIC23_DIGT_FMT) & ~(0x03 << 2);
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
break;
case SNDRV_PCM_FORMAT_S20_3LE:
iface_reg |= (0x01 << 2);
break;
case SNDRV_PCM_FORMAT_S24_LE:
iface_reg |= (0x02 << 2);
break;
case SNDRV_PCM_FORMAT_S32_LE:
iface_reg |= (0x03 << 2);
break;
}
tlv320aic23_write(codec, TLV320AIC23_DIGT_FMT, iface_reg);
return 0;
}
static int tlv320aic23_pcm_prepare(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_codec *codec = rtd->codec;
/* set active */
tlv320aic23_write(codec, TLV320AIC23_ACTIVE, 0x0001);
return 0;
}
static void tlv320aic23_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_codec *codec = rtd->codec;
struct aic23 *aic23 = snd_soc_codec_get_drvdata(codec);
/* deactivate */
if (!codec->active) {
udelay(50);
tlv320aic23_write(codec, TLV320AIC23_ACTIVE, 0x0);
}
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
aic23->requested_dac = 0;
else
aic23->requested_adc = 0;
}
static int tlv320aic23_mute(struct snd_soc_dai *dai, int mute)
{
struct snd_soc_codec *codec = dai->codec;
u16 reg;
reg = tlv320aic23_read_reg_cache(codec, TLV320AIC23_DIGT);
if (mute)
reg |= TLV320AIC23_DACM_MUTE;
else
reg &= ~TLV320AIC23_DACM_MUTE;
tlv320aic23_write(codec, TLV320AIC23_DIGT, reg);
return 0;
}
static int tlv320aic23_set_dai_fmt(struct snd_soc_dai *codec_dai,
unsigned int fmt)
{
struct snd_soc_codec *codec = codec_dai->codec;
u16 iface_reg;
iface_reg =
tlv320aic23_read_reg_cache(codec, TLV320AIC23_DIGT_FMT) & (~0x03);
/* set master/slave audio interface */
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
iface_reg |= TLV320AIC23_MS_MASTER;
break;
case SND_SOC_DAIFMT_CBS_CFS:
break;
default:
return -EINVAL;
}
/* interface format */
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
iface_reg |= TLV320AIC23_FOR_I2S;
break;
case SND_SOC_DAIFMT_DSP_A:
iface_reg |= TLV320AIC23_LRP_ON;
case SND_SOC_DAIFMT_DSP_B:
iface_reg |= TLV320AIC23_FOR_DSP;
break;
case SND_SOC_DAIFMT_RIGHT_J:
break;
case SND_SOC_DAIFMT_LEFT_J:
iface_reg |= TLV320AIC23_FOR_LJUST;
break;
default:
return -EINVAL;
}
tlv320aic23_write(codec, TLV320AIC23_DIGT_FMT, iface_reg);
return 0;
}
static int tlv320aic23_set_dai_sysclk(struct snd_soc_dai *codec_dai,
int clk_id, unsigned int freq, int dir)
{
struct aic23 *aic23 = snd_soc_dai_get_drvdata(codec_dai);
aic23->mclk = freq;
return 0;
}
static int tlv320aic23_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
u16 reg = tlv320aic23_read_reg_cache(codec, TLV320AIC23_PWR) & 0xff7f;
switch (level) {
case SND_SOC_BIAS_ON:
/* vref/mid, osc on, dac unmute */
reg &= ~(TLV320AIC23_DEVICE_PWR_OFF | TLV320AIC23_OSC_OFF | \
TLV320AIC23_DAC_OFF);
tlv320aic23_write(codec, TLV320AIC23_PWR, reg);
break;
case SND_SOC_BIAS_PREPARE:
break;
case SND_SOC_BIAS_STANDBY:
/* everything off except vref/vmid, */
tlv320aic23_write(codec, TLV320AIC23_PWR, reg | \
TLV320AIC23_CLK_OFF);
break;
case SND_SOC_BIAS_OFF:
/* everything off, dac mute, inactive */
tlv320aic23_write(codec, TLV320AIC23_ACTIVE, 0x0);
tlv320aic23_write(codec, TLV320AIC23_PWR, 0xffff);
break;
}
codec->dapm.bias_level = level;
return 0;
}
#define AIC23_RATES SNDRV_PCM_RATE_8000_96000
#define AIC23_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE | \
SNDRV_PCM_FMTBIT_S24_3LE | SNDRV_PCM_FMTBIT_S32_LE)
static struct snd_soc_dai_ops tlv320aic23_dai_ops = {
.prepare = tlv320aic23_pcm_prepare,
.hw_params = tlv320aic23_hw_params,
.shutdown = tlv320aic23_shutdown,
.digital_mute = tlv320aic23_mute,
.set_fmt = tlv320aic23_set_dai_fmt,
.set_sysclk = tlv320aic23_set_dai_sysclk,
};
static struct snd_soc_dai_driver tlv320aic23_dai = {
.name = "tlv320aic23-hifi",
.playback = {
.stream_name = "Playback",
.channels_min = 2,
.channels_max = 2,
.rates = AIC23_RATES,
.formats = AIC23_FORMATS,},
.capture = {
.stream_name = "Capture",
.channels_min = 2,
.channels_max = 2,
.rates = AIC23_RATES,
.formats = AIC23_FORMATS,},
.ops = &tlv320aic23_dai_ops,
};
static int tlv320aic23_suspend(struct snd_soc_codec *codec,
pm_message_t state)
{
tlv320aic23_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static int tlv320aic23_resume(struct snd_soc_codec *codec)
{
u16 reg;
/* Sync reg_cache with the hardware */
for (reg = 0; reg <= TLV320AIC23_ACTIVE; reg++) {
u16 val = tlv320aic23_read_reg_cache(codec, reg);
tlv320aic23_write(codec, reg, val);
}
tlv320aic23_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return 0;
}
static int tlv320aic23_probe(struct snd_soc_codec *codec)
{
struct aic23 *aic23 = snd_soc_codec_get_drvdata(codec);
int reg;
printk(KERN_INFO "AIC23 Audio Codec %s\n", AIC23_VERSION);
codec->control_data = aic23->control_data;
codec->hw_write = (hw_write_t)i2c_master_send;
codec->hw_read = NULL;
/* Reset codec */
tlv320aic23_write(codec, TLV320AIC23_RESET, 0);
/* power on device */
tlv320aic23_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
tlv320aic23_write(codec, TLV320AIC23_DIGT, TLV320AIC23_DEEMP_44K);
/* Unmute input */
reg = tlv320aic23_read_reg_cache(codec, TLV320AIC23_LINVOL);
tlv320aic23_write(codec, TLV320AIC23_LINVOL,
(reg & (~TLV320AIC23_LIM_MUTED)) |
(TLV320AIC23_LRS_ENABLED));
reg = tlv320aic23_read_reg_cache(codec, TLV320AIC23_RINVOL);
tlv320aic23_write(codec, TLV320AIC23_RINVOL,
(reg & (~TLV320AIC23_LIM_MUTED)) |
TLV320AIC23_LRS_ENABLED);
reg = tlv320aic23_read_reg_cache(codec, TLV320AIC23_ANLG);
tlv320aic23_write(codec, TLV320AIC23_ANLG,
(reg) & (~TLV320AIC23_BYPASS_ON) &
(~TLV320AIC23_MICM_MUTED));
/* Default output volume */
tlv320aic23_write(codec, TLV320AIC23_LCHNVOL,
TLV320AIC23_DEFAULT_OUT_VOL &
TLV320AIC23_OUT_VOL_MASK);
tlv320aic23_write(codec, TLV320AIC23_RCHNVOL,
TLV320AIC23_DEFAULT_OUT_VOL &
TLV320AIC23_OUT_VOL_MASK);
tlv320aic23_write(codec, TLV320AIC23_ACTIVE, 0x1);
snd_soc_add_controls(codec, tlv320aic23_snd_controls,
ARRAY_SIZE(tlv320aic23_snd_controls));
return 0;
}
static int tlv320aic23_remove(struct snd_soc_codec *codec)
{
tlv320aic23_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_tlv320aic23 = {
.reg_cache_size = ARRAY_SIZE(tlv320aic23_reg),
.reg_word_size = sizeof(u16),
.reg_cache_default = tlv320aic23_reg,
.probe = tlv320aic23_probe,
.remove = tlv320aic23_remove,
.suspend = tlv320aic23_suspend,
.resume = tlv320aic23_resume,
.read = tlv320aic23_read_reg_cache,
.write = tlv320aic23_write,
.set_bias_level = tlv320aic23_set_bias_level,
.dapm_widgets = tlv320aic23_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(tlv320aic23_dapm_widgets),
.dapm_routes = tlv320aic23_intercon,
.num_dapm_routes = ARRAY_SIZE(tlv320aic23_intercon),
};
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
/*
* If the i2c layer weren't so broken, we could pass this kind of data
* around
*/
static int tlv320aic23_codec_probe(struct i2c_client *i2c,
const struct i2c_device_id *i2c_id)
{
struct aic23 *aic23;
int ret;
if (!i2c_check_functionality(i2c->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -EINVAL;
aic23 = kzalloc(sizeof(struct aic23), GFP_KERNEL);
if (aic23 == NULL)
return -ENOMEM;
i2c_set_clientdata(i2c, aic23);
aic23->control_data = i2c;
aic23->control_type = SND_SOC_I2C;
ret = snd_soc_register_codec(&i2c->dev,
&soc_codec_dev_tlv320aic23, &tlv320aic23_dai, 1);
if (ret < 0)
kfree(aic23);
return ret;
}
static int __exit tlv320aic23_i2c_remove(struct i2c_client *i2c)
{
snd_soc_unregister_codec(&i2c->dev);
kfree(i2c_get_clientdata(i2c));
return 0;
}
static const struct i2c_device_id tlv320aic23_id[] = {
{"tlv320aic23", 0},
{}
};
MODULE_DEVICE_TABLE(i2c, tlv320aic23_id);
static struct i2c_driver tlv320aic23_i2c_driver = {
.driver = {
.name = "tlv320aic23-codec",
},
.probe = tlv320aic23_codec_probe,
.remove = __exit_p(tlv320aic23_i2c_remove),
.id_table = tlv320aic23_id,
};
#endif
static int __init tlv320aic23_modinit(void)
{
int ret;
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
ret = i2c_add_driver(&tlv320aic23_i2c_driver);
if (ret != 0) {
printk(KERN_ERR "Failed to register TLV320AIC23 I2C driver: %d\n",
ret);
}
#endif
return ret;
}
module_init(tlv320aic23_modinit);
static void __exit tlv320aic23_exit(void)
{
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
i2c_del_driver(&tlv320aic23_i2c_driver);
#endif
}
module_exit(tlv320aic23_exit);
MODULE_DESCRIPTION("ASoC TLV320AIC23 codec driver");
MODULE_AUTHOR("Arun KS <arunks@mistralsolutions.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
NoelMacwan/SXDNickiKat | drivers/scsi/megaraid/megaraid_sas_base.c | 3276 | 143996 | /*
* Linux MegaRAID driver for SAS based RAID controllers
*
* Copyright (c) 2009-2011 LSI Corporation.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* FILE: megaraid_sas_base.c
* Version : v00.00.06.14-rc1
*
* Authors: LSI Corporation
* Sreenivas Bagalkote
* Sumant Patro
* Bo Yang
* Adam Radford <linuxraid@lsi.com>
*
* Send feedback to: <megaraidlinux@lsi.com>
*
* Mail to: LSI Corporation, 1621 Barber Lane, Milpitas, CA 95035
* ATTN: Linuxraid
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/list.h>
#include <linux/moduleparam.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/uio.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <linux/fs.h>
#include <linux/compat.h>
#include <linux/blkdev.h>
#include <linux/mutex.h>
#include <linux/poll.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_tcq.h>
#include "megaraid_sas_fusion.h"
#include "megaraid_sas.h"
/*
* Number of sectors per IO command
* Will be set in megasas_init_mfi if user does not provide
*/
static unsigned int max_sectors;
module_param_named(max_sectors, max_sectors, int, 0);
MODULE_PARM_DESC(max_sectors,
"Maximum number of sectors per IO command");
static int msix_disable;
module_param(msix_disable, int, S_IRUGO);
MODULE_PARM_DESC(msix_disable, "Disable MSI-X interrupt handling. Default: 0");
MODULE_LICENSE("GPL");
MODULE_VERSION(MEGASAS_VERSION);
MODULE_AUTHOR("megaraidlinux@lsi.com");
MODULE_DESCRIPTION("LSI MegaRAID SAS Driver");
int megasas_transition_to_ready(struct megasas_instance *instance, int ocr);
static int megasas_get_pd_list(struct megasas_instance *instance);
static int megasas_issue_init_mfi(struct megasas_instance *instance);
static int megasas_register_aen(struct megasas_instance *instance,
u32 seq_num, u32 class_locale_word);
/*
* PCI ID table for all supported controllers
*/
static struct pci_device_id megasas_pci_table[] = {
{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1064R)},
/* xscale IOP */
{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078R)},
/* ppc IOP */
{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078DE)},
/* ppc IOP */
{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078GEN2)},
/* gen2*/
{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0079GEN2)},
/* gen2*/
{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0073SKINNY)},
/* skinny*/
{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0071SKINNY)},
/* skinny*/
{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VERDE_ZCR)},
/* xscale IOP, vega */
{PCI_DEVICE(PCI_VENDOR_ID_DELL, PCI_DEVICE_ID_DELL_PERC5)},
/* xscale IOP */
{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FUSION)},
/* Fusion */
{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INVADER)},
/* Invader */
{}
};
MODULE_DEVICE_TABLE(pci, megasas_pci_table);
static int megasas_mgmt_majorno;
static struct megasas_mgmt_info megasas_mgmt_info;
static struct fasync_struct *megasas_async_queue;
static DEFINE_MUTEX(megasas_async_queue_mutex);
static int megasas_poll_wait_aen;
static DECLARE_WAIT_QUEUE_HEAD(megasas_poll_wait);
static u32 support_poll_for_event;
u32 megasas_dbg_lvl;
static u32 support_device_change;
/* define lock for aen poll */
spinlock_t poll_aen_lock;
void
megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
u8 alt_status);
static u32
megasas_read_fw_status_reg_gen2(struct megasas_register_set __iomem *regs);
static int
megasas_adp_reset_gen2(struct megasas_instance *instance,
struct megasas_register_set __iomem *reg_set);
static irqreturn_t megasas_isr(int irq, void *devp);
static u32
megasas_init_adapter_mfi(struct megasas_instance *instance);
u32
megasas_build_and_issue_cmd(struct megasas_instance *instance,
struct scsi_cmnd *scmd);
static void megasas_complete_cmd_dpc(unsigned long instance_addr);
void
megasas_release_fusion(struct megasas_instance *instance);
int
megasas_ioc_init_fusion(struct megasas_instance *instance);
void
megasas_free_cmds_fusion(struct megasas_instance *instance);
u8
megasas_get_map_info(struct megasas_instance *instance);
int
megasas_sync_map_info(struct megasas_instance *instance);
int
wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd);
void megasas_reset_reply_desc(struct megasas_instance *instance);
u8 MR_ValidateMapInfo(struct MR_FW_RAID_MAP_ALL *map,
struct LD_LOAD_BALANCE_INFO *lbInfo);
int megasas_reset_fusion(struct Scsi_Host *shost);
void megasas_fusion_ocr_wq(struct work_struct *work);
void
megasas_issue_dcmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
{
instance->instancet->fire_cmd(instance,
cmd->frame_phys_addr, 0, instance->reg_set);
}
/**
* megasas_get_cmd - Get a command from the free pool
* @instance: Adapter soft state
*
* Returns a free command from the pool
*/
struct megasas_cmd *megasas_get_cmd(struct megasas_instance
*instance)
{
unsigned long flags;
struct megasas_cmd *cmd = NULL;
spin_lock_irqsave(&instance->cmd_pool_lock, flags);
if (!list_empty(&instance->cmd_pool)) {
cmd = list_entry((&instance->cmd_pool)->next,
struct megasas_cmd, list);
list_del_init(&cmd->list);
} else {
printk(KERN_ERR "megasas: Command pool empty!\n");
}
spin_unlock_irqrestore(&instance->cmd_pool_lock, flags);
return cmd;
}
/**
* megasas_return_cmd - Return a cmd to free command pool
* @instance: Adapter soft state
* @cmd: Command packet to be returned to free command pool
*/
inline void
megasas_return_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
{
unsigned long flags;
spin_lock_irqsave(&instance->cmd_pool_lock, flags);
cmd->scmd = NULL;
cmd->frame_count = 0;
if ((instance->pdev->device != PCI_DEVICE_ID_LSI_FUSION) &&
(instance->pdev->device != PCI_DEVICE_ID_LSI_INVADER) &&
(reset_devices))
cmd->frame->hdr.cmd = MFI_CMD_INVALID;
list_add_tail(&cmd->list, &instance->cmd_pool);
spin_unlock_irqrestore(&instance->cmd_pool_lock, flags);
}
/**
* The following functions are defined for xscale
* (deviceid : 1064R, PERC5) controllers
*/
/**
* megasas_enable_intr_xscale - Enables interrupts
* @regs: MFI register set
*/
static inline void
megasas_enable_intr_xscale(struct megasas_register_set __iomem * regs)
{
writel(0, &(regs)->outbound_intr_mask);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_mask);
}
/**
* megasas_disable_intr_xscale -Disables interrupt
* @regs: MFI register set
*/
static inline void
megasas_disable_intr_xscale(struct megasas_register_set __iomem * regs)
{
u32 mask = 0x1f;
writel(mask, ®s->outbound_intr_mask);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_mask);
}
/**
* megasas_read_fw_status_reg_xscale - returns the current FW status value
* @regs: MFI register set
*/
static u32
megasas_read_fw_status_reg_xscale(struct megasas_register_set __iomem * regs)
{
return readl(&(regs)->outbound_msg_0);
}
/**
* megasas_clear_interrupt_xscale - Check & clear interrupt
* @regs: MFI register set
*/
static int
megasas_clear_intr_xscale(struct megasas_register_set __iomem * regs)
{
u32 status;
u32 mfiStatus = 0;
/*
* Check if it is our interrupt
*/
status = readl(®s->outbound_intr_status);
if (status & MFI_OB_INTR_STATUS_MASK)
mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
if (status & MFI_XSCALE_OMR0_CHANGE_INTERRUPT)
mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
/*
* Clear the interrupt by writing back the same value
*/
if (mfiStatus)
writel(status, ®s->outbound_intr_status);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_status);
return mfiStatus;
}
/**
* megasas_fire_cmd_xscale - Sends command to the FW
* @frame_phys_addr : Physical address of cmd
* @frame_count : Number of frames for the command
* @regs : MFI register set
*/
static inline void
megasas_fire_cmd_xscale(struct megasas_instance *instance,
dma_addr_t frame_phys_addr,
u32 frame_count,
struct megasas_register_set __iomem *regs)
{
unsigned long flags;
spin_lock_irqsave(&instance->hba_lock, flags);
writel((frame_phys_addr >> 3)|(frame_count),
&(regs)->inbound_queue_port);
spin_unlock_irqrestore(&instance->hba_lock, flags);
}
/**
* megasas_adp_reset_xscale - For controller reset
* @regs: MFI register set
*/
static int
megasas_adp_reset_xscale(struct megasas_instance *instance,
struct megasas_register_set __iomem *regs)
{
u32 i;
u32 pcidata;
writel(MFI_ADP_RESET, ®s->inbound_doorbell);
for (i = 0; i < 3; i++)
msleep(1000); /* sleep for 3 secs */
pcidata = 0;
pci_read_config_dword(instance->pdev, MFI_1068_PCSR_OFFSET, &pcidata);
printk(KERN_NOTICE "pcidata = %x\n", pcidata);
if (pcidata & 0x2) {
printk(KERN_NOTICE "mfi 1068 offset read=%x\n", pcidata);
pcidata &= ~0x2;
pci_write_config_dword(instance->pdev,
MFI_1068_PCSR_OFFSET, pcidata);
for (i = 0; i < 2; i++)
msleep(1000); /* need to wait 2 secs again */
pcidata = 0;
pci_read_config_dword(instance->pdev,
MFI_1068_FW_HANDSHAKE_OFFSET, &pcidata);
printk(KERN_NOTICE "1068 offset handshake read=%x\n", pcidata);
if ((pcidata & 0xffff0000) == MFI_1068_FW_READY) {
printk(KERN_NOTICE "1068 offset pcidt=%x\n", pcidata);
pcidata = 0;
pci_write_config_dword(instance->pdev,
MFI_1068_FW_HANDSHAKE_OFFSET, pcidata);
}
}
return 0;
}
/**
* megasas_check_reset_xscale - For controller reset check
* @regs: MFI register set
*/
static int
megasas_check_reset_xscale(struct megasas_instance *instance,
struct megasas_register_set __iomem *regs)
{
u32 consumer;
consumer = *instance->consumer;
if ((instance->adprecovery != MEGASAS_HBA_OPERATIONAL) &&
(*instance->consumer == MEGASAS_ADPRESET_INPROG_SIGN)) {
return 1;
}
return 0;
}
static struct megasas_instance_template megasas_instance_template_xscale = {
.fire_cmd = megasas_fire_cmd_xscale,
.enable_intr = megasas_enable_intr_xscale,
.disable_intr = megasas_disable_intr_xscale,
.clear_intr = megasas_clear_intr_xscale,
.read_fw_status_reg = megasas_read_fw_status_reg_xscale,
.adp_reset = megasas_adp_reset_xscale,
.check_reset = megasas_check_reset_xscale,
.service_isr = megasas_isr,
.tasklet = megasas_complete_cmd_dpc,
.init_adapter = megasas_init_adapter_mfi,
.build_and_issue_cmd = megasas_build_and_issue_cmd,
.issue_dcmd = megasas_issue_dcmd,
};
/**
* This is the end of set of functions & definitions specific
* to xscale (deviceid : 1064R, PERC5) controllers
*/
/**
* The following functions are defined for ppc (deviceid : 0x60)
* controllers
*/
/**
* megasas_enable_intr_ppc - Enables interrupts
* @regs: MFI register set
*/
static inline void
megasas_enable_intr_ppc(struct megasas_register_set __iomem * regs)
{
writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
writel(~0x80000000, &(regs)->outbound_intr_mask);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_mask);
}
/**
* megasas_disable_intr_ppc - Disable interrupt
* @regs: MFI register set
*/
static inline void
megasas_disable_intr_ppc(struct megasas_register_set __iomem * regs)
{
u32 mask = 0xFFFFFFFF;
writel(mask, ®s->outbound_intr_mask);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_mask);
}
/**
* megasas_read_fw_status_reg_ppc - returns the current FW status value
* @regs: MFI register set
*/
static u32
megasas_read_fw_status_reg_ppc(struct megasas_register_set __iomem * regs)
{
return readl(&(regs)->outbound_scratch_pad);
}
/**
* megasas_clear_interrupt_ppc - Check & clear interrupt
* @regs: MFI register set
*/
static int
megasas_clear_intr_ppc(struct megasas_register_set __iomem * regs)
{
u32 status, mfiStatus = 0;
/*
* Check if it is our interrupt
*/
status = readl(®s->outbound_intr_status);
if (status & MFI_REPLY_1078_MESSAGE_INTERRUPT)
mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT)
mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
/*
* Clear the interrupt by writing back the same value
*/
writel(status, ®s->outbound_doorbell_clear);
/* Dummy readl to force pci flush */
readl(®s->outbound_doorbell_clear);
return mfiStatus;
}
/**
* megasas_fire_cmd_ppc - Sends command to the FW
* @frame_phys_addr : Physical address of cmd
* @frame_count : Number of frames for the command
* @regs : MFI register set
*/
static inline void
megasas_fire_cmd_ppc(struct megasas_instance *instance,
dma_addr_t frame_phys_addr,
u32 frame_count,
struct megasas_register_set __iomem *regs)
{
unsigned long flags;
spin_lock_irqsave(&instance->hba_lock, flags);
writel((frame_phys_addr | (frame_count<<1))|1,
&(regs)->inbound_queue_port);
spin_unlock_irqrestore(&instance->hba_lock, flags);
}
/**
* megasas_check_reset_ppc - For controller reset check
* @regs: MFI register set
*/
static int
megasas_check_reset_ppc(struct megasas_instance *instance,
struct megasas_register_set __iomem *regs)
{
if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL)
return 1;
return 0;
}
static struct megasas_instance_template megasas_instance_template_ppc = {
.fire_cmd = megasas_fire_cmd_ppc,
.enable_intr = megasas_enable_intr_ppc,
.disable_intr = megasas_disable_intr_ppc,
.clear_intr = megasas_clear_intr_ppc,
.read_fw_status_reg = megasas_read_fw_status_reg_ppc,
.adp_reset = megasas_adp_reset_xscale,
.check_reset = megasas_check_reset_ppc,
.service_isr = megasas_isr,
.tasklet = megasas_complete_cmd_dpc,
.init_adapter = megasas_init_adapter_mfi,
.build_and_issue_cmd = megasas_build_and_issue_cmd,
.issue_dcmd = megasas_issue_dcmd,
};
/**
* megasas_enable_intr_skinny - Enables interrupts
* @regs: MFI register set
*/
static inline void
megasas_enable_intr_skinny(struct megasas_register_set __iomem *regs)
{
writel(0xFFFFFFFF, &(regs)->outbound_intr_mask);
writel(~MFI_SKINNY_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_mask);
}
/**
* megasas_disable_intr_skinny - Disables interrupt
* @regs: MFI register set
*/
static inline void
megasas_disable_intr_skinny(struct megasas_register_set __iomem *regs)
{
u32 mask = 0xFFFFFFFF;
writel(mask, ®s->outbound_intr_mask);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_mask);
}
/**
* megasas_read_fw_status_reg_skinny - returns the current FW status value
* @regs: MFI register set
*/
static u32
megasas_read_fw_status_reg_skinny(struct megasas_register_set __iomem *regs)
{
return readl(&(regs)->outbound_scratch_pad);
}
/**
* megasas_clear_interrupt_skinny - Check & clear interrupt
* @regs: MFI register set
*/
static int
megasas_clear_intr_skinny(struct megasas_register_set __iomem *regs)
{
u32 status;
u32 mfiStatus = 0;
/*
* Check if it is our interrupt
*/
status = readl(®s->outbound_intr_status);
if (!(status & MFI_SKINNY_ENABLE_INTERRUPT_MASK)) {
return 0;
}
/*
* Check if it is our interrupt
*/
if ((megasas_read_fw_status_reg_gen2(regs) & MFI_STATE_MASK) ==
MFI_STATE_FAULT) {
mfiStatus = MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
} else
mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
/*
* Clear the interrupt by writing back the same value
*/
writel(status, ®s->outbound_intr_status);
/*
* dummy read to flush PCI
*/
readl(®s->outbound_intr_status);
return mfiStatus;
}
/**
* megasas_fire_cmd_skinny - Sends command to the FW
* @frame_phys_addr : Physical address of cmd
* @frame_count : Number of frames for the command
* @regs : MFI register set
*/
static inline void
megasas_fire_cmd_skinny(struct megasas_instance *instance,
dma_addr_t frame_phys_addr,
u32 frame_count,
struct megasas_register_set __iomem *regs)
{
unsigned long flags;
spin_lock_irqsave(&instance->hba_lock, flags);
writel(0, &(regs)->inbound_high_queue_port);
writel((frame_phys_addr | (frame_count<<1))|1,
&(regs)->inbound_low_queue_port);
spin_unlock_irqrestore(&instance->hba_lock, flags);
}
/**
* megasas_check_reset_skinny - For controller reset check
* @regs: MFI register set
*/
static int
megasas_check_reset_skinny(struct megasas_instance *instance,
struct megasas_register_set __iomem *regs)
{
if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL)
return 1;
return 0;
}
static struct megasas_instance_template megasas_instance_template_skinny = {
.fire_cmd = megasas_fire_cmd_skinny,
.enable_intr = megasas_enable_intr_skinny,
.disable_intr = megasas_disable_intr_skinny,
.clear_intr = megasas_clear_intr_skinny,
.read_fw_status_reg = megasas_read_fw_status_reg_skinny,
.adp_reset = megasas_adp_reset_gen2,
.check_reset = megasas_check_reset_skinny,
.service_isr = megasas_isr,
.tasklet = megasas_complete_cmd_dpc,
.init_adapter = megasas_init_adapter_mfi,
.build_and_issue_cmd = megasas_build_and_issue_cmd,
.issue_dcmd = megasas_issue_dcmd,
};
/**
* The following functions are defined for gen2 (deviceid : 0x78 0x79)
* controllers
*/
/**
* megasas_enable_intr_gen2 - Enables interrupts
* @regs: MFI register set
*/
static inline void
megasas_enable_intr_gen2(struct megasas_register_set __iomem *regs)
{
writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
/* write ~0x00000005 (4 & 1) to the intr mask*/
writel(~MFI_GEN2_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_mask);
}
/**
* megasas_disable_intr_gen2 - Disables interrupt
* @regs: MFI register set
*/
static inline void
megasas_disable_intr_gen2(struct megasas_register_set __iomem *regs)
{
u32 mask = 0xFFFFFFFF;
writel(mask, ®s->outbound_intr_mask);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_mask);
}
/**
* megasas_read_fw_status_reg_gen2 - returns the current FW status value
* @regs: MFI register set
*/
static u32
megasas_read_fw_status_reg_gen2(struct megasas_register_set __iomem *regs)
{
return readl(&(regs)->outbound_scratch_pad);
}
/**
* megasas_clear_interrupt_gen2 - Check & clear interrupt
* @regs: MFI register set
*/
static int
megasas_clear_intr_gen2(struct megasas_register_set __iomem *regs)
{
u32 status;
u32 mfiStatus = 0;
/*
* Check if it is our interrupt
*/
status = readl(®s->outbound_intr_status);
if (status & MFI_GEN2_ENABLE_INTERRUPT_MASK) {
mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
}
if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT) {
mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
}
/*
* Clear the interrupt by writing back the same value
*/
if (mfiStatus)
writel(status, ®s->outbound_doorbell_clear);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_status);
return mfiStatus;
}
/**
* megasas_fire_cmd_gen2 - Sends command to the FW
* @frame_phys_addr : Physical address of cmd
* @frame_count : Number of frames for the command
* @regs : MFI register set
*/
static inline void
megasas_fire_cmd_gen2(struct megasas_instance *instance,
dma_addr_t frame_phys_addr,
u32 frame_count,
struct megasas_register_set __iomem *regs)
{
unsigned long flags;
spin_lock_irqsave(&instance->hba_lock, flags);
writel((frame_phys_addr | (frame_count<<1))|1,
&(regs)->inbound_queue_port);
spin_unlock_irqrestore(&instance->hba_lock, flags);
}
/**
* megasas_adp_reset_gen2 - For controller reset
* @regs: MFI register set
*/
static int
megasas_adp_reset_gen2(struct megasas_instance *instance,
struct megasas_register_set __iomem *reg_set)
{
u32 retry = 0 ;
u32 HostDiag;
u32 *seq_offset = ®_set->seq_offset;
u32 *hostdiag_offset = ®_set->host_diag;
if (instance->instancet == &megasas_instance_template_skinny) {
seq_offset = ®_set->fusion_seq_offset;
hostdiag_offset = ®_set->fusion_host_diag;
}
writel(0, seq_offset);
writel(4, seq_offset);
writel(0xb, seq_offset);
writel(2, seq_offset);
writel(7, seq_offset);
writel(0xd, seq_offset);
msleep(1000);
HostDiag = (u32)readl(hostdiag_offset);
while ( !( HostDiag & DIAG_WRITE_ENABLE) ) {
msleep(100);
HostDiag = (u32)readl(hostdiag_offset);
printk(KERN_NOTICE "RESETGEN2: retry=%x, hostdiag=%x\n",
retry, HostDiag);
if (retry++ >= 100)
return 1;
}
printk(KERN_NOTICE "ADP_RESET_GEN2: HostDiag=%x\n", HostDiag);
writel((HostDiag | DIAG_RESET_ADAPTER), hostdiag_offset);
ssleep(10);
HostDiag = (u32)readl(hostdiag_offset);
while ( ( HostDiag & DIAG_RESET_ADAPTER) ) {
msleep(100);
HostDiag = (u32)readl(hostdiag_offset);
printk(KERN_NOTICE "RESET_GEN2: retry=%x, hostdiag=%x\n",
retry, HostDiag);
if (retry++ >= 1000)
return 1;
}
return 0;
}
/**
* megasas_check_reset_gen2 - For controller reset check
* @regs: MFI register set
*/
static int
megasas_check_reset_gen2(struct megasas_instance *instance,
struct megasas_register_set __iomem *regs)
{
if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) {
return 1;
}
return 0;
}
static struct megasas_instance_template megasas_instance_template_gen2 = {
.fire_cmd = megasas_fire_cmd_gen2,
.enable_intr = megasas_enable_intr_gen2,
.disable_intr = megasas_disable_intr_gen2,
.clear_intr = megasas_clear_intr_gen2,
.read_fw_status_reg = megasas_read_fw_status_reg_gen2,
.adp_reset = megasas_adp_reset_gen2,
.check_reset = megasas_check_reset_gen2,
.service_isr = megasas_isr,
.tasklet = megasas_complete_cmd_dpc,
.init_adapter = megasas_init_adapter_mfi,
.build_and_issue_cmd = megasas_build_and_issue_cmd,
.issue_dcmd = megasas_issue_dcmd,
};
/**
* This is the end of set of functions & definitions
* specific to gen2 (deviceid : 0x78, 0x79) controllers
*/
/*
* Template added for TB (Fusion)
*/
extern struct megasas_instance_template megasas_instance_template_fusion;
/**
* megasas_issue_polled - Issues a polling command
* @instance: Adapter soft state
* @cmd: Command packet to be issued
*
* For polling, MFI requires the cmd_status to be set to 0xFF before posting.
*/
int
megasas_issue_polled(struct megasas_instance *instance, struct megasas_cmd *cmd)
{
struct megasas_header *frame_hdr = &cmd->frame->hdr;
frame_hdr->cmd_status = 0xFF;
frame_hdr->flags |= MFI_FRAME_DONT_POST_IN_REPLY_QUEUE;
/*
* Issue the frame using inbound queue port
*/
instance->instancet->issue_dcmd(instance, cmd);
/*
* Wait for cmd_status to change
*/
return wait_and_poll(instance, cmd);
}
/**
* megasas_issue_blocked_cmd - Synchronous wrapper around regular FW cmds
* @instance: Adapter soft state
* @cmd: Command to be issued
*
* This function waits on an event for the command to be returned from ISR.
* Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
* Used to issue ioctl commands.
*/
static int
megasas_issue_blocked_cmd(struct megasas_instance *instance,
struct megasas_cmd *cmd)
{
cmd->cmd_status = ENODATA;
instance->instancet->issue_dcmd(instance, cmd);
wait_event(instance->int_cmd_wait_q, cmd->cmd_status != ENODATA);
return 0;
}
/**
* megasas_issue_blocked_abort_cmd - Aborts previously issued cmd
* @instance: Adapter soft state
* @cmd_to_abort: Previously issued cmd to be aborted
*
* MFI firmware can abort previously issued AEN command (automatic event
* notification). The megasas_issue_blocked_abort_cmd() issues such abort
* cmd and waits for return status.
* Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
*/
static int
megasas_issue_blocked_abort_cmd(struct megasas_instance *instance,
struct megasas_cmd *cmd_to_abort)
{
struct megasas_cmd *cmd;
struct megasas_abort_frame *abort_fr;
cmd = megasas_get_cmd(instance);
if (!cmd)
return -1;
abort_fr = &cmd->frame->abort;
/*
* Prepare and issue the abort frame
*/
abort_fr->cmd = MFI_CMD_ABORT;
abort_fr->cmd_status = 0xFF;
abort_fr->flags = 0;
abort_fr->abort_context = cmd_to_abort->index;
abort_fr->abort_mfi_phys_addr_lo = cmd_to_abort->frame_phys_addr;
abort_fr->abort_mfi_phys_addr_hi = 0;
cmd->sync_cmd = 1;
cmd->cmd_status = 0xFF;
instance->instancet->issue_dcmd(instance, cmd);
/*
* Wait for this cmd to complete
*/
wait_event(instance->abort_cmd_wait_q, cmd->cmd_status != 0xFF);
cmd->sync_cmd = 0;
megasas_return_cmd(instance, cmd);
return 0;
}
/**
* megasas_make_sgl32 - Prepares 32-bit SGL
* @instance: Adapter soft state
* @scp: SCSI command from the mid-layer
* @mfi_sgl: SGL to be filled in
*
* If successful, this function returns the number of SG elements. Otherwise,
* it returnes -1.
*/
static int
megasas_make_sgl32(struct megasas_instance *instance, struct scsi_cmnd *scp,
union megasas_sgl *mfi_sgl)
{
int i;
int sge_count;
struct scatterlist *os_sgl;
sge_count = scsi_dma_map(scp);
BUG_ON(sge_count < 0);
if (sge_count) {
scsi_for_each_sg(scp, os_sgl, sge_count, i) {
mfi_sgl->sge32[i].length = sg_dma_len(os_sgl);
mfi_sgl->sge32[i].phys_addr = sg_dma_address(os_sgl);
}
}
return sge_count;
}
/**
* megasas_make_sgl64 - Prepares 64-bit SGL
* @instance: Adapter soft state
* @scp: SCSI command from the mid-layer
* @mfi_sgl: SGL to be filled in
*
* If successful, this function returns the number of SG elements. Otherwise,
* it returnes -1.
*/
static int
megasas_make_sgl64(struct megasas_instance *instance, struct scsi_cmnd *scp,
union megasas_sgl *mfi_sgl)
{
int i;
int sge_count;
struct scatterlist *os_sgl;
sge_count = scsi_dma_map(scp);
BUG_ON(sge_count < 0);
if (sge_count) {
scsi_for_each_sg(scp, os_sgl, sge_count, i) {
mfi_sgl->sge64[i].length = sg_dma_len(os_sgl);
mfi_sgl->sge64[i].phys_addr = sg_dma_address(os_sgl);
}
}
return sge_count;
}
/**
* megasas_make_sgl_skinny - Prepares IEEE SGL
* @instance: Adapter soft state
* @scp: SCSI command from the mid-layer
* @mfi_sgl: SGL to be filled in
*
* If successful, this function returns the number of SG elements. Otherwise,
* it returnes -1.
*/
static int
megasas_make_sgl_skinny(struct megasas_instance *instance,
struct scsi_cmnd *scp, union megasas_sgl *mfi_sgl)
{
int i;
int sge_count;
struct scatterlist *os_sgl;
sge_count = scsi_dma_map(scp);
if (sge_count) {
scsi_for_each_sg(scp, os_sgl, sge_count, i) {
mfi_sgl->sge_skinny[i].length = sg_dma_len(os_sgl);
mfi_sgl->sge_skinny[i].phys_addr =
sg_dma_address(os_sgl);
mfi_sgl->sge_skinny[i].flag = 0;
}
}
return sge_count;
}
/**
* megasas_get_frame_count - Computes the number of frames
* @frame_type : type of frame- io or pthru frame
* @sge_count : number of sg elements
*
* Returns the number of frames required for numnber of sge's (sge_count)
*/
static u32 megasas_get_frame_count(struct megasas_instance *instance,
u8 sge_count, u8 frame_type)
{
int num_cnt;
int sge_bytes;
u32 sge_sz;
u32 frame_count=0;
sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
sizeof(struct megasas_sge32);
if (instance->flag_ieee) {
sge_sz = sizeof(struct megasas_sge_skinny);
}
/*
* Main frame can contain 2 SGEs for 64-bit SGLs and
* 3 SGEs for 32-bit SGLs for ldio &
* 1 SGEs for 64-bit SGLs and
* 2 SGEs for 32-bit SGLs for pthru frame
*/
if (unlikely(frame_type == PTHRU_FRAME)) {
if (instance->flag_ieee == 1) {
num_cnt = sge_count - 1;
} else if (IS_DMA64)
num_cnt = sge_count - 1;
else
num_cnt = sge_count - 2;
} else {
if (instance->flag_ieee == 1) {
num_cnt = sge_count - 1;
} else if (IS_DMA64)
num_cnt = sge_count - 2;
else
num_cnt = sge_count - 3;
}
if(num_cnt>0){
sge_bytes = sge_sz * num_cnt;
frame_count = (sge_bytes / MEGAMFI_FRAME_SIZE) +
((sge_bytes % MEGAMFI_FRAME_SIZE) ? 1 : 0) ;
}
/* Main frame */
frame_count +=1;
if (frame_count > 7)
frame_count = 8;
return frame_count;
}
/**
* megasas_build_dcdb - Prepares a direct cdb (DCDB) command
* @instance: Adapter soft state
* @scp: SCSI command
* @cmd: Command to be prepared in
*
* This function prepares CDB commands. These are typcially pass-through
* commands to the devices.
*/
static int
megasas_build_dcdb(struct megasas_instance *instance, struct scsi_cmnd *scp,
struct megasas_cmd *cmd)
{
u32 is_logical;
u32 device_id;
u16 flags = 0;
struct megasas_pthru_frame *pthru;
is_logical = MEGASAS_IS_LOGICAL(scp);
device_id = MEGASAS_DEV_INDEX(instance, scp);
pthru = (struct megasas_pthru_frame *)cmd->frame;
if (scp->sc_data_direction == PCI_DMA_TODEVICE)
flags = MFI_FRAME_DIR_WRITE;
else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
flags = MFI_FRAME_DIR_READ;
else if (scp->sc_data_direction == PCI_DMA_NONE)
flags = MFI_FRAME_DIR_NONE;
if (instance->flag_ieee == 1) {
flags |= MFI_FRAME_IEEE;
}
/*
* Prepare the DCDB frame
*/
pthru->cmd = (is_logical) ? MFI_CMD_LD_SCSI_IO : MFI_CMD_PD_SCSI_IO;
pthru->cmd_status = 0x0;
pthru->scsi_status = 0x0;
pthru->target_id = device_id;
pthru->lun = scp->device->lun;
pthru->cdb_len = scp->cmd_len;
pthru->timeout = 0;
pthru->pad_0 = 0;
pthru->flags = flags;
pthru->data_xfer_len = scsi_bufflen(scp);
memcpy(pthru->cdb, scp->cmnd, scp->cmd_len);
/*
* If the command is for the tape device, set the
* pthru timeout to the os layer timeout value.
*/
if (scp->device->type == TYPE_TAPE) {
if ((scp->request->timeout / HZ) > 0xFFFF)
pthru->timeout = 0xFFFF;
else
pthru->timeout = scp->request->timeout / HZ;
}
/*
* Construct SGL
*/
if (instance->flag_ieee == 1) {
pthru->flags |= MFI_FRAME_SGL64;
pthru->sge_count = megasas_make_sgl_skinny(instance, scp,
&pthru->sgl);
} else if (IS_DMA64) {
pthru->flags |= MFI_FRAME_SGL64;
pthru->sge_count = megasas_make_sgl64(instance, scp,
&pthru->sgl);
} else
pthru->sge_count = megasas_make_sgl32(instance, scp,
&pthru->sgl);
if (pthru->sge_count > instance->max_num_sge) {
printk(KERN_ERR "megasas: DCDB two many SGE NUM=%x\n",
pthru->sge_count);
return 0;
}
/*
* Sense info specific
*/
pthru->sense_len = SCSI_SENSE_BUFFERSIZE;
pthru->sense_buf_phys_addr_hi = 0;
pthru->sense_buf_phys_addr_lo = cmd->sense_phys_addr;
/*
* Compute the total number of frames this command consumes. FW uses
* this number to pull sufficient number of frames from host memory.
*/
cmd->frame_count = megasas_get_frame_count(instance, pthru->sge_count,
PTHRU_FRAME);
return cmd->frame_count;
}
/**
* megasas_build_ldio - Prepares IOs to logical devices
* @instance: Adapter soft state
* @scp: SCSI command
* @cmd: Command to be prepared
*
* Frames (and accompanying SGLs) for regular SCSI IOs use this function.
*/
static int
megasas_build_ldio(struct megasas_instance *instance, struct scsi_cmnd *scp,
struct megasas_cmd *cmd)
{
u32 device_id;
u8 sc = scp->cmnd[0];
u16 flags = 0;
struct megasas_io_frame *ldio;
device_id = MEGASAS_DEV_INDEX(instance, scp);
ldio = (struct megasas_io_frame *)cmd->frame;
if (scp->sc_data_direction == PCI_DMA_TODEVICE)
flags = MFI_FRAME_DIR_WRITE;
else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
flags = MFI_FRAME_DIR_READ;
if (instance->flag_ieee == 1) {
flags |= MFI_FRAME_IEEE;
}
/*
* Prepare the Logical IO frame: 2nd bit is zero for all read cmds
*/
ldio->cmd = (sc & 0x02) ? MFI_CMD_LD_WRITE : MFI_CMD_LD_READ;
ldio->cmd_status = 0x0;
ldio->scsi_status = 0x0;
ldio->target_id = device_id;
ldio->timeout = 0;
ldio->reserved_0 = 0;
ldio->pad_0 = 0;
ldio->flags = flags;
ldio->start_lba_hi = 0;
ldio->access_byte = (scp->cmd_len != 6) ? scp->cmnd[1] : 0;
/*
* 6-byte READ(0x08) or WRITE(0x0A) cdb
*/
if (scp->cmd_len == 6) {
ldio->lba_count = (u32) scp->cmnd[4];
ldio->start_lba_lo = ((u32) scp->cmnd[1] << 16) |
((u32) scp->cmnd[2] << 8) | (u32) scp->cmnd[3];
ldio->start_lba_lo &= 0x1FFFFF;
}
/*
* 10-byte READ(0x28) or WRITE(0x2A) cdb
*/
else if (scp->cmd_len == 10) {
ldio->lba_count = (u32) scp->cmnd[8] |
((u32) scp->cmnd[7] << 8);
ldio->start_lba_lo = ((u32) scp->cmnd[2] << 24) |
((u32) scp->cmnd[3] << 16) |
((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
}
/*
* 12-byte READ(0xA8) or WRITE(0xAA) cdb
*/
else if (scp->cmd_len == 12) {
ldio->lba_count = ((u32) scp->cmnd[6] << 24) |
((u32) scp->cmnd[7] << 16) |
((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
ldio->start_lba_lo = ((u32) scp->cmnd[2] << 24) |
((u32) scp->cmnd[3] << 16) |
((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
}
/*
* 16-byte READ(0x88) or WRITE(0x8A) cdb
*/
else if (scp->cmd_len == 16) {
ldio->lba_count = ((u32) scp->cmnd[10] << 24) |
((u32) scp->cmnd[11] << 16) |
((u32) scp->cmnd[12] << 8) | (u32) scp->cmnd[13];
ldio->start_lba_lo = ((u32) scp->cmnd[6] << 24) |
((u32) scp->cmnd[7] << 16) |
((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
ldio->start_lba_hi = ((u32) scp->cmnd[2] << 24) |
((u32) scp->cmnd[3] << 16) |
((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
}
/*
* Construct SGL
*/
if (instance->flag_ieee) {
ldio->flags |= MFI_FRAME_SGL64;
ldio->sge_count = megasas_make_sgl_skinny(instance, scp,
&ldio->sgl);
} else if (IS_DMA64) {
ldio->flags |= MFI_FRAME_SGL64;
ldio->sge_count = megasas_make_sgl64(instance, scp, &ldio->sgl);
} else
ldio->sge_count = megasas_make_sgl32(instance, scp, &ldio->sgl);
if (ldio->sge_count > instance->max_num_sge) {
printk(KERN_ERR "megasas: build_ld_io: sge_count = %x\n",
ldio->sge_count);
return 0;
}
/*
* Sense info specific
*/
ldio->sense_len = SCSI_SENSE_BUFFERSIZE;
ldio->sense_buf_phys_addr_hi = 0;
ldio->sense_buf_phys_addr_lo = cmd->sense_phys_addr;
/*
* Compute the total number of frames this command consumes. FW uses
* this number to pull sufficient number of frames from host memory.
*/
cmd->frame_count = megasas_get_frame_count(instance,
ldio->sge_count, IO_FRAME);
return cmd->frame_count;
}
/**
* megasas_is_ldio - Checks if the cmd is for logical drive
* @scmd: SCSI command
*
* Called by megasas_queue_command to find out if the command to be queued
* is a logical drive command
*/
inline int megasas_is_ldio(struct scsi_cmnd *cmd)
{
if (!MEGASAS_IS_LOGICAL(cmd))
return 0;
switch (cmd->cmnd[0]) {
case READ_10:
case WRITE_10:
case READ_12:
case WRITE_12:
case READ_6:
case WRITE_6:
case READ_16:
case WRITE_16:
return 1;
default:
return 0;
}
}
/**
* megasas_dump_pending_frames - Dumps the frame address of all pending cmds
* in FW
* @instance: Adapter soft state
*/
static inline void
megasas_dump_pending_frames(struct megasas_instance *instance)
{
struct megasas_cmd *cmd;
int i,n;
union megasas_sgl *mfi_sgl;
struct megasas_io_frame *ldio;
struct megasas_pthru_frame *pthru;
u32 sgcount;
u32 max_cmd = instance->max_fw_cmds;
printk(KERN_ERR "\nmegasas[%d]: Dumping Frame Phys Address of all pending cmds in FW\n",instance->host->host_no);
printk(KERN_ERR "megasas[%d]: Total OS Pending cmds : %d\n",instance->host->host_no,atomic_read(&instance->fw_outstanding));
if (IS_DMA64)
printk(KERN_ERR "\nmegasas[%d]: 64 bit SGLs were sent to FW\n",instance->host->host_no);
else
printk(KERN_ERR "\nmegasas[%d]: 32 bit SGLs were sent to FW\n",instance->host->host_no);
printk(KERN_ERR "megasas[%d]: Pending OS cmds in FW : \n",instance->host->host_no);
for (i = 0; i < max_cmd; i++) {
cmd = instance->cmd_list[i];
if(!cmd->scmd)
continue;
printk(KERN_ERR "megasas[%d]: Frame addr :0x%08lx : ",instance->host->host_no,(unsigned long)cmd->frame_phys_addr);
if (megasas_is_ldio(cmd->scmd)){
ldio = (struct megasas_io_frame *)cmd->frame;
mfi_sgl = &ldio->sgl;
sgcount = ldio->sge_count;
printk(KERN_ERR "megasas[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, lba lo : 0x%x, lba_hi : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",instance->host->host_no, cmd->frame_count,ldio->cmd,ldio->target_id, ldio->start_lba_lo,ldio->start_lba_hi,ldio->sense_buf_phys_addr_lo,sgcount);
}
else {
pthru = (struct megasas_pthru_frame *) cmd->frame;
mfi_sgl = &pthru->sgl;
sgcount = pthru->sge_count;
printk(KERN_ERR "megasas[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, lun : 0x%x, cdb_len : 0x%x, data xfer len : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",instance->host->host_no,cmd->frame_count,pthru->cmd,pthru->target_id,pthru->lun,pthru->cdb_len , pthru->data_xfer_len,pthru->sense_buf_phys_addr_lo,sgcount);
}
if(megasas_dbg_lvl & MEGASAS_DBG_LVL){
for (n = 0; n < sgcount; n++){
if (IS_DMA64)
printk(KERN_ERR "megasas: sgl len : 0x%x, sgl addr : 0x%08lx ",mfi_sgl->sge64[n].length , (unsigned long)mfi_sgl->sge64[n].phys_addr) ;
else
printk(KERN_ERR "megasas: sgl len : 0x%x, sgl addr : 0x%x ",mfi_sgl->sge32[n].length , mfi_sgl->sge32[n].phys_addr) ;
}
}
printk(KERN_ERR "\n");
} /*for max_cmd*/
printk(KERN_ERR "\nmegasas[%d]: Pending Internal cmds in FW : \n",instance->host->host_no);
for (i = 0; i < max_cmd; i++) {
cmd = instance->cmd_list[i];
if(cmd->sync_cmd == 1){
printk(KERN_ERR "0x%08lx : ", (unsigned long)cmd->frame_phys_addr);
}
}
printk(KERN_ERR "megasas[%d]: Dumping Done.\n\n",instance->host->host_no);
}
u32
megasas_build_and_issue_cmd(struct megasas_instance *instance,
struct scsi_cmnd *scmd)
{
struct megasas_cmd *cmd;
u32 frame_count;
cmd = megasas_get_cmd(instance);
if (!cmd)
return SCSI_MLQUEUE_HOST_BUSY;
/*
* Logical drive command
*/
if (megasas_is_ldio(scmd))
frame_count = megasas_build_ldio(instance, scmd, cmd);
else
frame_count = megasas_build_dcdb(instance, scmd, cmd);
if (!frame_count)
goto out_return_cmd;
cmd->scmd = scmd;
scmd->SCp.ptr = (char *)cmd;
/*
* Issue the command to the FW
*/
atomic_inc(&instance->fw_outstanding);
instance->instancet->fire_cmd(instance, cmd->frame_phys_addr,
cmd->frame_count-1, instance->reg_set);
return 0;
out_return_cmd:
megasas_return_cmd(instance, cmd);
return 1;
}
/**
* megasas_queue_command - Queue entry point
* @scmd: SCSI command to be queued
* @done: Callback entry point
*/
static int
megasas_queue_command_lck(struct scsi_cmnd *scmd, void (*done) (struct scsi_cmnd *))
{
struct megasas_instance *instance;
unsigned long flags;
instance = (struct megasas_instance *)
scmd->device->host->hostdata;
if (instance->issuepend_done == 0)
return SCSI_MLQUEUE_HOST_BUSY;
spin_lock_irqsave(&instance->hba_lock, flags);
if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) {
spin_unlock_irqrestore(&instance->hba_lock, flags);
return SCSI_MLQUEUE_HOST_BUSY;
}
spin_unlock_irqrestore(&instance->hba_lock, flags);
scmd->scsi_done = done;
scmd->result = 0;
if (MEGASAS_IS_LOGICAL(scmd) &&
(scmd->device->id >= MEGASAS_MAX_LD || scmd->device->lun)) {
scmd->result = DID_BAD_TARGET << 16;
goto out_done;
}
switch (scmd->cmnd[0]) {
case SYNCHRONIZE_CACHE:
/*
* FW takes care of flush cache on its own
* No need to send it down
*/
scmd->result = DID_OK << 16;
goto out_done;
default:
break;
}
if (instance->instancet->build_and_issue_cmd(instance, scmd)) {
printk(KERN_ERR "megasas: Err returned from build_and_issue_cmd\n");
return SCSI_MLQUEUE_HOST_BUSY;
}
return 0;
out_done:
done(scmd);
return 0;
}
static DEF_SCSI_QCMD(megasas_queue_command)
static struct megasas_instance *megasas_lookup_instance(u16 host_no)
{
int i;
for (i = 0; i < megasas_mgmt_info.max_index; i++) {
if ((megasas_mgmt_info.instance[i]) &&
(megasas_mgmt_info.instance[i]->host->host_no == host_no))
return megasas_mgmt_info.instance[i];
}
return NULL;
}
static int megasas_slave_configure(struct scsi_device *sdev)
{
u16 pd_index = 0;
struct megasas_instance *instance ;
instance = megasas_lookup_instance(sdev->host->host_no);
/*
* Don't export physical disk devices to the disk driver.
*
* FIXME: Currently we don't export them to the midlayer at all.
* That will be fixed once LSI engineers have audited the
* firmware for possible issues.
*/
if (sdev->channel < MEGASAS_MAX_PD_CHANNELS &&
sdev->type == TYPE_DISK) {
pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
sdev->id;
if (instance->pd_list[pd_index].driveState ==
MR_PD_STATE_SYSTEM) {
blk_queue_rq_timeout(sdev->request_queue,
MEGASAS_DEFAULT_CMD_TIMEOUT * HZ);
return 0;
}
return -ENXIO;
}
/*
* The RAID firmware may require extended timeouts.
*/
blk_queue_rq_timeout(sdev->request_queue,
MEGASAS_DEFAULT_CMD_TIMEOUT * HZ);
return 0;
}
static int megasas_slave_alloc(struct scsi_device *sdev)
{
u16 pd_index = 0;
struct megasas_instance *instance ;
instance = megasas_lookup_instance(sdev->host->host_no);
if ((sdev->channel < MEGASAS_MAX_PD_CHANNELS) &&
(sdev->type == TYPE_DISK)) {
/*
* Open the OS scan to the SYSTEM PD
*/
pd_index =
(sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
sdev->id;
if ((instance->pd_list[pd_index].driveState ==
MR_PD_STATE_SYSTEM) &&
(instance->pd_list[pd_index].driveType ==
TYPE_DISK)) {
return 0;
}
return -ENXIO;
}
return 0;
}
void megaraid_sas_kill_hba(struct megasas_instance *instance)
{
if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
(instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
(instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
(instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)) {
writel(MFI_STOP_ADP, &instance->reg_set->doorbell);
} else {
writel(MFI_STOP_ADP, &instance->reg_set->inbound_doorbell);
}
}
/**
* megasas_check_and_restore_queue_depth - Check if queue depth needs to be
* restored to max value
* @instance: Adapter soft state
*
*/
void
megasas_check_and_restore_queue_depth(struct megasas_instance *instance)
{
unsigned long flags;
if (instance->flag & MEGASAS_FW_BUSY
&& time_after(jiffies, instance->last_time + 5 * HZ)
&& atomic_read(&instance->fw_outstanding) < 17) {
spin_lock_irqsave(instance->host->host_lock, flags);
instance->flag &= ~MEGASAS_FW_BUSY;
if ((instance->pdev->device ==
PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
(instance->pdev->device ==
PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
instance->host->can_queue =
instance->max_fw_cmds - MEGASAS_SKINNY_INT_CMDS;
} else
instance->host->can_queue =
instance->max_fw_cmds - MEGASAS_INT_CMDS;
spin_unlock_irqrestore(instance->host->host_lock, flags);
}
}
/**
* megasas_complete_cmd_dpc - Returns FW's controller structure
* @instance_addr: Address of adapter soft state
*
* Tasklet to complete cmds
*/
static void megasas_complete_cmd_dpc(unsigned long instance_addr)
{
u32 producer;
u32 consumer;
u32 context;
struct megasas_cmd *cmd;
struct megasas_instance *instance =
(struct megasas_instance *)instance_addr;
unsigned long flags;
/* If we have already declared adapter dead, donot complete cmds */
if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR )
return;
spin_lock_irqsave(&instance->completion_lock, flags);
producer = *instance->producer;
consumer = *instance->consumer;
while (consumer != producer) {
context = instance->reply_queue[consumer];
if (context >= instance->max_fw_cmds) {
printk(KERN_ERR "Unexpected context value %x\n",
context);
BUG();
}
cmd = instance->cmd_list[context];
megasas_complete_cmd(instance, cmd, DID_OK);
consumer++;
if (consumer == (instance->max_fw_cmds + 1)) {
consumer = 0;
}
}
*instance->consumer = producer;
spin_unlock_irqrestore(&instance->completion_lock, flags);
/*
* Check if we can restore can_queue
*/
megasas_check_and_restore_queue_depth(instance);
}
static void
megasas_internal_reset_defer_cmds(struct megasas_instance *instance);
static void
process_fw_state_change_wq(struct work_struct *work);
void megasas_do_ocr(struct megasas_instance *instance)
{
if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) ||
(instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) ||
(instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)) {
*instance->consumer = MEGASAS_ADPRESET_INPROG_SIGN;
}
instance->instancet->disable_intr(instance->reg_set);
instance->adprecovery = MEGASAS_ADPRESET_SM_INFAULT;
instance->issuepend_done = 0;
atomic_set(&instance->fw_outstanding, 0);
megasas_internal_reset_defer_cmds(instance);
process_fw_state_change_wq(&instance->work_init);
}
/**
* megasas_wait_for_outstanding - Wait for all outstanding cmds
* @instance: Adapter soft state
*
* This function waits for up to MEGASAS_RESET_WAIT_TIME seconds for FW to
* complete all its outstanding commands. Returns error if one or more IOs
* are pending after this time period. It also marks the controller dead.
*/
static int megasas_wait_for_outstanding(struct megasas_instance *instance)
{
int i;
u32 reset_index;
u32 wait_time = MEGASAS_RESET_WAIT_TIME;
u8 adprecovery;
unsigned long flags;
struct list_head clist_local;
struct megasas_cmd *reset_cmd;
u32 fw_state;
u8 kill_adapter_flag;
spin_lock_irqsave(&instance->hba_lock, flags);
adprecovery = instance->adprecovery;
spin_unlock_irqrestore(&instance->hba_lock, flags);
if (adprecovery != MEGASAS_HBA_OPERATIONAL) {
INIT_LIST_HEAD(&clist_local);
spin_lock_irqsave(&instance->hba_lock, flags);
list_splice_init(&instance->internal_reset_pending_q,
&clist_local);
spin_unlock_irqrestore(&instance->hba_lock, flags);
printk(KERN_NOTICE "megasas: HBA reset wait ...\n");
for (i = 0; i < wait_time; i++) {
msleep(1000);
spin_lock_irqsave(&instance->hba_lock, flags);
adprecovery = instance->adprecovery;
spin_unlock_irqrestore(&instance->hba_lock, flags);
if (adprecovery == MEGASAS_HBA_OPERATIONAL)
break;
}
if (adprecovery != MEGASAS_HBA_OPERATIONAL) {
printk(KERN_NOTICE "megasas: reset: Stopping HBA.\n");
spin_lock_irqsave(&instance->hba_lock, flags);
instance->adprecovery = MEGASAS_HW_CRITICAL_ERROR;
spin_unlock_irqrestore(&instance->hba_lock, flags);
return FAILED;
}
reset_index = 0;
while (!list_empty(&clist_local)) {
reset_cmd = list_entry((&clist_local)->next,
struct megasas_cmd, list);
list_del_init(&reset_cmd->list);
if (reset_cmd->scmd) {
reset_cmd->scmd->result = DID_RESET << 16;
printk(KERN_NOTICE "%d:%p reset [%02x]\n",
reset_index, reset_cmd,
reset_cmd->scmd->cmnd[0]);
reset_cmd->scmd->scsi_done(reset_cmd->scmd);
megasas_return_cmd(instance, reset_cmd);
} else if (reset_cmd->sync_cmd) {
printk(KERN_NOTICE "megasas:%p synch cmds"
"reset queue\n",
reset_cmd);
reset_cmd->cmd_status = ENODATA;
instance->instancet->fire_cmd(instance,
reset_cmd->frame_phys_addr,
0, instance->reg_set);
} else {
printk(KERN_NOTICE "megasas: %p unexpected"
"cmds lst\n",
reset_cmd);
}
reset_index++;
}
return SUCCESS;
}
for (i = 0; i < wait_time; i++) {
int outstanding = atomic_read(&instance->fw_outstanding);
if (!outstanding)
break;
if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
printk(KERN_NOTICE "megasas: [%2d]waiting for %d "
"commands to complete\n",i,outstanding);
/*
* Call cmd completion routine. Cmd to be
* be completed directly without depending on isr.
*/
megasas_complete_cmd_dpc((unsigned long)instance);
}
msleep(1000);
}
i = 0;
kill_adapter_flag = 0;
do {
fw_state = instance->instancet->read_fw_status_reg(
instance->reg_set) & MFI_STATE_MASK;
if ((fw_state == MFI_STATE_FAULT) &&
(instance->disableOnlineCtrlReset == 0)) {
if (i == 3) {
kill_adapter_flag = 2;
break;
}
megasas_do_ocr(instance);
kill_adapter_flag = 1;
/* wait for 1 secs to let FW finish the pending cmds */
msleep(1000);
}
i++;
} while (i <= 3);
if (atomic_read(&instance->fw_outstanding) &&
!kill_adapter_flag) {
if (instance->disableOnlineCtrlReset == 0) {
megasas_do_ocr(instance);
/* wait for 5 secs to let FW finish the pending cmds */
for (i = 0; i < wait_time; i++) {
int outstanding =
atomic_read(&instance->fw_outstanding);
if (!outstanding)
return SUCCESS;
msleep(1000);
}
}
}
if (atomic_read(&instance->fw_outstanding) ||
(kill_adapter_flag == 2)) {
printk(KERN_NOTICE "megaraid_sas: pending cmds after reset\n");
/*
* Send signal to FW to stop processing any pending cmds.
* The controller will be taken offline by the OS now.
*/
if ((instance->pdev->device ==
PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
(instance->pdev->device ==
PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
writel(MFI_STOP_ADP,
&instance->reg_set->doorbell);
} else {
writel(MFI_STOP_ADP,
&instance->reg_set->inbound_doorbell);
}
megasas_dump_pending_frames(instance);
spin_lock_irqsave(&instance->hba_lock, flags);
instance->adprecovery = MEGASAS_HW_CRITICAL_ERROR;
spin_unlock_irqrestore(&instance->hba_lock, flags);
return FAILED;
}
printk(KERN_NOTICE "megaraid_sas: no pending cmds after reset\n");
return SUCCESS;
}
/**
* megasas_generic_reset - Generic reset routine
* @scmd: Mid-layer SCSI command
*
* This routine implements a generic reset handler for device, bus and host
* reset requests. Device, bus and host specific reset handlers can use this
* function after they do their specific tasks.
*/
static int megasas_generic_reset(struct scsi_cmnd *scmd)
{
int ret_val;
struct megasas_instance *instance;
instance = (struct megasas_instance *)scmd->device->host->hostdata;
scmd_printk(KERN_NOTICE, scmd, "megasas: RESET cmd=%x retries=%x\n",
scmd->cmnd[0], scmd->retries);
if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
printk(KERN_ERR "megasas: cannot recover from previous reset "
"failures\n");
return FAILED;
}
ret_val = megasas_wait_for_outstanding(instance);
if (ret_val == SUCCESS)
printk(KERN_NOTICE "megasas: reset successful \n");
else
printk(KERN_ERR "megasas: failed to do reset\n");
return ret_val;
}
/**
* megasas_reset_timer - quiesce the adapter if required
* @scmd: scsi cmnd
*
* Sets the FW busy flag and reduces the host->can_queue if the
* cmd has not been completed within the timeout period.
*/
static enum
blk_eh_timer_return megasas_reset_timer(struct scsi_cmnd *scmd)
{
struct megasas_instance *instance;
unsigned long flags;
if (time_after(jiffies, scmd->jiffies_at_alloc +
(MEGASAS_DEFAULT_CMD_TIMEOUT * 2) * HZ)) {
return BLK_EH_NOT_HANDLED;
}
instance = (struct megasas_instance *)scmd->device->host->hostdata;
if (!(instance->flag & MEGASAS_FW_BUSY)) {
/* FW is busy, throttle IO */
spin_lock_irqsave(instance->host->host_lock, flags);
instance->host->can_queue = 16;
instance->last_time = jiffies;
instance->flag |= MEGASAS_FW_BUSY;
spin_unlock_irqrestore(instance->host->host_lock, flags);
}
return BLK_EH_RESET_TIMER;
}
/**
* megasas_reset_device - Device reset handler entry point
*/
static int megasas_reset_device(struct scsi_cmnd *scmd)
{
int ret;
/*
* First wait for all commands to complete
*/
ret = megasas_generic_reset(scmd);
return ret;
}
/**
* megasas_reset_bus_host - Bus & host reset handler entry point
*/
static int megasas_reset_bus_host(struct scsi_cmnd *scmd)
{
int ret;
struct megasas_instance *instance;
instance = (struct megasas_instance *)scmd->device->host->hostdata;
/*
* First wait for all commands to complete
*/
if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
(instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER))
ret = megasas_reset_fusion(scmd->device->host);
else
ret = megasas_generic_reset(scmd);
return ret;
}
/**
* megasas_bios_param - Returns disk geometry for a disk
* @sdev: device handle
* @bdev: block device
* @capacity: drive capacity
* @geom: geometry parameters
*/
static int
megasas_bios_param(struct scsi_device *sdev, struct block_device *bdev,
sector_t capacity, int geom[])
{
int heads;
int sectors;
sector_t cylinders;
unsigned long tmp;
/* Default heads (64) & sectors (32) */
heads = 64;
sectors = 32;
tmp = heads * sectors;
cylinders = capacity;
sector_div(cylinders, tmp);
/*
* Handle extended translation size for logical drives > 1Gb
*/
if (capacity >= 0x200000) {
heads = 255;
sectors = 63;
tmp = heads*sectors;
cylinders = capacity;
sector_div(cylinders, tmp);
}
geom[0] = heads;
geom[1] = sectors;
geom[2] = cylinders;
return 0;
}
static void megasas_aen_polling(struct work_struct *work);
/**
* megasas_service_aen - Processes an event notification
* @instance: Adapter soft state
* @cmd: AEN command completed by the ISR
*
* For AEN, driver sends a command down to FW that is held by the FW till an
* event occurs. When an event of interest occurs, FW completes the command
* that it was previously holding.
*
* This routines sends SIGIO signal to processes that have registered with the
* driver for AEN.
*/
static void
megasas_service_aen(struct megasas_instance *instance, struct megasas_cmd *cmd)
{
unsigned long flags;
/*
* Don't signal app if it is just an aborted previously registered aen
*/
if ((!cmd->abort_aen) && (instance->unload == 0)) {
spin_lock_irqsave(&poll_aen_lock, flags);
megasas_poll_wait_aen = 1;
spin_unlock_irqrestore(&poll_aen_lock, flags);
wake_up(&megasas_poll_wait);
kill_fasync(&megasas_async_queue, SIGIO, POLL_IN);
}
else
cmd->abort_aen = 0;
instance->aen_cmd = NULL;
megasas_return_cmd(instance, cmd);
if ((instance->unload == 0) &&
((instance->issuepend_done == 1))) {
struct megasas_aen_event *ev;
ev = kzalloc(sizeof(*ev), GFP_ATOMIC);
if (!ev) {
printk(KERN_ERR "megasas_service_aen: out of memory\n");
} else {
ev->instance = instance;
instance->ev = ev;
INIT_WORK(&ev->hotplug_work, megasas_aen_polling);
schedule_delayed_work(
(struct delayed_work *)&ev->hotplug_work, 0);
}
}
}
static int megasas_change_queue_depth(struct scsi_device *sdev,
int queue_depth, int reason)
{
if (reason != SCSI_QDEPTH_DEFAULT)
return -EOPNOTSUPP;
if (queue_depth > sdev->host->can_queue)
queue_depth = sdev->host->can_queue;
scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev),
queue_depth);
return queue_depth;
}
/*
* Scsi host template for megaraid_sas driver
*/
static struct scsi_host_template megasas_template = {
.module = THIS_MODULE,
.name = "LSI SAS based MegaRAID driver",
.proc_name = "megaraid_sas",
.slave_configure = megasas_slave_configure,
.slave_alloc = megasas_slave_alloc,
.queuecommand = megasas_queue_command,
.eh_device_reset_handler = megasas_reset_device,
.eh_bus_reset_handler = megasas_reset_bus_host,
.eh_host_reset_handler = megasas_reset_bus_host,
.eh_timed_out = megasas_reset_timer,
.bios_param = megasas_bios_param,
.use_clustering = ENABLE_CLUSTERING,
.change_queue_depth = megasas_change_queue_depth,
};
/**
* megasas_complete_int_cmd - Completes an internal command
* @instance: Adapter soft state
* @cmd: Command to be completed
*
* The megasas_issue_blocked_cmd() function waits for a command to complete
* after it issues a command. This function wakes up that waiting routine by
* calling wake_up() on the wait queue.
*/
static void
megasas_complete_int_cmd(struct megasas_instance *instance,
struct megasas_cmd *cmd)
{
cmd->cmd_status = cmd->frame->io.cmd_status;
if (cmd->cmd_status == ENODATA) {
cmd->cmd_status = 0;
}
wake_up(&instance->int_cmd_wait_q);
}
/**
* megasas_complete_abort - Completes aborting a command
* @instance: Adapter soft state
* @cmd: Cmd that was issued to abort another cmd
*
* The megasas_issue_blocked_abort_cmd() function waits on abort_cmd_wait_q
* after it issues an abort on a previously issued command. This function
* wakes up all functions waiting on the same wait queue.
*/
static void
megasas_complete_abort(struct megasas_instance *instance,
struct megasas_cmd *cmd)
{
if (cmd->sync_cmd) {
cmd->sync_cmd = 0;
cmd->cmd_status = 0;
wake_up(&instance->abort_cmd_wait_q);
}
return;
}
/**
* megasas_complete_cmd - Completes a command
* @instance: Adapter soft state
* @cmd: Command to be completed
* @alt_status: If non-zero, use this value as status to
* SCSI mid-layer instead of the value returned
* by the FW. This should be used if caller wants
* an alternate status (as in the case of aborted
* commands)
*/
void
megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
u8 alt_status)
{
int exception = 0;
struct megasas_header *hdr = &cmd->frame->hdr;
unsigned long flags;
struct fusion_context *fusion = instance->ctrl_context;
/* flag for the retry reset */
cmd->retry_for_fw_reset = 0;
if (cmd->scmd)
cmd->scmd->SCp.ptr = NULL;
switch (hdr->cmd) {
case MFI_CMD_INVALID:
/* Some older 1068 controller FW may keep a pended
MR_DCMD_CTRL_EVENT_GET_INFO left over from the main kernel
when booting the kdump kernel. Ignore this command to
prevent a kernel panic on shutdown of the kdump kernel. */
printk(KERN_WARNING "megaraid_sas: MFI_CMD_INVALID command "
"completed.\n");
printk(KERN_WARNING "megaraid_sas: If you have a controller "
"other than PERC5, please upgrade your firmware.\n");
break;
case MFI_CMD_PD_SCSI_IO:
case MFI_CMD_LD_SCSI_IO:
/*
* MFI_CMD_PD_SCSI_IO and MFI_CMD_LD_SCSI_IO could have been
* issued either through an IO path or an IOCTL path. If it
* was via IOCTL, we will send it to internal completion.
*/
if (cmd->sync_cmd) {
cmd->sync_cmd = 0;
megasas_complete_int_cmd(instance, cmd);
break;
}
case MFI_CMD_LD_READ:
case MFI_CMD_LD_WRITE:
if (alt_status) {
cmd->scmd->result = alt_status << 16;
exception = 1;
}
if (exception) {
atomic_dec(&instance->fw_outstanding);
scsi_dma_unmap(cmd->scmd);
cmd->scmd->scsi_done(cmd->scmd);
megasas_return_cmd(instance, cmd);
break;
}
switch (hdr->cmd_status) {
case MFI_STAT_OK:
cmd->scmd->result = DID_OK << 16;
break;
case MFI_STAT_SCSI_IO_FAILED:
case MFI_STAT_LD_INIT_IN_PROGRESS:
cmd->scmd->result =
(DID_ERROR << 16) | hdr->scsi_status;
break;
case MFI_STAT_SCSI_DONE_WITH_ERROR:
cmd->scmd->result = (DID_OK << 16) | hdr->scsi_status;
if (hdr->scsi_status == SAM_STAT_CHECK_CONDITION) {
memset(cmd->scmd->sense_buffer, 0,
SCSI_SENSE_BUFFERSIZE);
memcpy(cmd->scmd->sense_buffer, cmd->sense,
hdr->sense_len);
cmd->scmd->result |= DRIVER_SENSE << 24;
}
break;
case MFI_STAT_LD_OFFLINE:
case MFI_STAT_DEVICE_NOT_FOUND:
cmd->scmd->result = DID_BAD_TARGET << 16;
break;
default:
printk(KERN_DEBUG "megasas: MFI FW status %#x\n",
hdr->cmd_status);
cmd->scmd->result = DID_ERROR << 16;
break;
}
atomic_dec(&instance->fw_outstanding);
scsi_dma_unmap(cmd->scmd);
cmd->scmd->scsi_done(cmd->scmd);
megasas_return_cmd(instance, cmd);
break;
case MFI_CMD_SMP:
case MFI_CMD_STP:
case MFI_CMD_DCMD:
/* Check for LD map update */
if ((cmd->frame->dcmd.opcode == MR_DCMD_LD_MAP_GET_INFO) &&
(cmd->frame->dcmd.mbox.b[1] == 1)) {
spin_lock_irqsave(instance->host->host_lock, flags);
if (cmd->frame->hdr.cmd_status != 0) {
if (cmd->frame->hdr.cmd_status !=
MFI_STAT_NOT_FOUND)
printk(KERN_WARNING "megasas: map sync"
"failed, status = 0x%x.\n",
cmd->frame->hdr.cmd_status);
else {
megasas_return_cmd(instance, cmd);
spin_unlock_irqrestore(
instance->host->host_lock,
flags);
break;
}
} else
instance->map_id++;
megasas_return_cmd(instance, cmd);
if (MR_ValidateMapInfo(
fusion->ld_map[(instance->map_id & 1)],
fusion->load_balance_info))
fusion->fast_path_io = 1;
else
fusion->fast_path_io = 0;
megasas_sync_map_info(instance);
spin_unlock_irqrestore(instance->host->host_lock,
flags);
break;
}
if (cmd->frame->dcmd.opcode == MR_DCMD_CTRL_EVENT_GET_INFO ||
cmd->frame->dcmd.opcode == MR_DCMD_CTRL_EVENT_GET) {
spin_lock_irqsave(&poll_aen_lock, flags);
megasas_poll_wait_aen = 0;
spin_unlock_irqrestore(&poll_aen_lock, flags);
}
/*
* See if got an event notification
*/
if (cmd->frame->dcmd.opcode == MR_DCMD_CTRL_EVENT_WAIT)
megasas_service_aen(instance, cmd);
else
megasas_complete_int_cmd(instance, cmd);
break;
case MFI_CMD_ABORT:
/*
* Cmd issued to abort another cmd returned
*/
megasas_complete_abort(instance, cmd);
break;
default:
printk("megasas: Unknown command completed! [0x%X]\n",
hdr->cmd);
break;
}
}
/**
* megasas_issue_pending_cmds_again - issue all pending cmds
* in FW again because of the fw reset
* @instance: Adapter soft state
*/
static inline void
megasas_issue_pending_cmds_again(struct megasas_instance *instance)
{
struct megasas_cmd *cmd;
struct list_head clist_local;
union megasas_evt_class_locale class_locale;
unsigned long flags;
u32 seq_num;
INIT_LIST_HEAD(&clist_local);
spin_lock_irqsave(&instance->hba_lock, flags);
list_splice_init(&instance->internal_reset_pending_q, &clist_local);
spin_unlock_irqrestore(&instance->hba_lock, flags);
while (!list_empty(&clist_local)) {
cmd = list_entry((&clist_local)->next,
struct megasas_cmd, list);
list_del_init(&cmd->list);
if (cmd->sync_cmd || cmd->scmd) {
printk(KERN_NOTICE "megaraid_sas: command %p, %p:%d"
"detected to be pending while HBA reset.\n",
cmd, cmd->scmd, cmd->sync_cmd);
cmd->retry_for_fw_reset++;
if (cmd->retry_for_fw_reset == 3) {
printk(KERN_NOTICE "megaraid_sas: cmd %p, %p:%d"
"was tried multiple times during reset."
"Shutting down the HBA\n",
cmd, cmd->scmd, cmd->sync_cmd);
megaraid_sas_kill_hba(instance);
instance->adprecovery =
MEGASAS_HW_CRITICAL_ERROR;
return;
}
}
if (cmd->sync_cmd == 1) {
if (cmd->scmd) {
printk(KERN_NOTICE "megaraid_sas: unexpected"
"cmd attached to internal command!\n");
}
printk(KERN_NOTICE "megasas: %p synchronous cmd"
"on the internal reset queue,"
"issue it again.\n", cmd);
cmd->cmd_status = ENODATA;
instance->instancet->fire_cmd(instance,
cmd->frame_phys_addr ,
0, instance->reg_set);
} else if (cmd->scmd) {
printk(KERN_NOTICE "megasas: %p scsi cmd [%02x]"
"detected on the internal queue, issue again.\n",
cmd, cmd->scmd->cmnd[0]);
atomic_inc(&instance->fw_outstanding);
instance->instancet->fire_cmd(instance,
cmd->frame_phys_addr,
cmd->frame_count-1, instance->reg_set);
} else {
printk(KERN_NOTICE "megasas: %p unexpected cmd on the"
"internal reset defer list while re-issue!!\n",
cmd);
}
}
if (instance->aen_cmd) {
printk(KERN_NOTICE "megaraid_sas: aen_cmd in def process\n");
megasas_return_cmd(instance, instance->aen_cmd);
instance->aen_cmd = NULL;
}
/*
* Initiate AEN (Asynchronous Event Notification)
*/
seq_num = instance->last_seq_num;
class_locale.members.reserved = 0;
class_locale.members.locale = MR_EVT_LOCALE_ALL;
class_locale.members.class = MR_EVT_CLASS_DEBUG;
megasas_register_aen(instance, seq_num, class_locale.word);
}
/**
* Move the internal reset pending commands to a deferred queue.
*
* We move the commands pending at internal reset time to a
* pending queue. This queue would be flushed after successful
* completion of the internal reset sequence. if the internal reset
* did not complete in time, the kernel reset handler would flush
* these commands.
**/
static void
megasas_internal_reset_defer_cmds(struct megasas_instance *instance)
{
struct megasas_cmd *cmd;
int i;
u32 max_cmd = instance->max_fw_cmds;
u32 defer_index;
unsigned long flags;
defer_index = 0;
spin_lock_irqsave(&instance->cmd_pool_lock, flags);
for (i = 0; i < max_cmd; i++) {
cmd = instance->cmd_list[i];
if (cmd->sync_cmd == 1 || cmd->scmd) {
printk(KERN_NOTICE "megasas: moving cmd[%d]:%p:%d:%p"
"on the defer queue as internal\n",
defer_index, cmd, cmd->sync_cmd, cmd->scmd);
if (!list_empty(&cmd->list)) {
printk(KERN_NOTICE "megaraid_sas: ERROR while"
" moving this cmd:%p, %d %p, it was"
"discovered on some list?\n",
cmd, cmd->sync_cmd, cmd->scmd);
list_del_init(&cmd->list);
}
defer_index++;
list_add_tail(&cmd->list,
&instance->internal_reset_pending_q);
}
}
spin_unlock_irqrestore(&instance->cmd_pool_lock, flags);
}
static void
process_fw_state_change_wq(struct work_struct *work)
{
struct megasas_instance *instance =
container_of(work, struct megasas_instance, work_init);
u32 wait;
unsigned long flags;
if (instance->adprecovery != MEGASAS_ADPRESET_SM_INFAULT) {
printk(KERN_NOTICE "megaraid_sas: error, recovery st %x \n",
instance->adprecovery);
return ;
}
if (instance->adprecovery == MEGASAS_ADPRESET_SM_INFAULT) {
printk(KERN_NOTICE "megaraid_sas: FW detected to be in fault"
"state, restarting it...\n");
instance->instancet->disable_intr(instance->reg_set);
atomic_set(&instance->fw_outstanding, 0);
atomic_set(&instance->fw_reset_no_pci_access, 1);
instance->instancet->adp_reset(instance, instance->reg_set);
atomic_set(&instance->fw_reset_no_pci_access, 0 );
printk(KERN_NOTICE "megaraid_sas: FW restarted successfully,"
"initiating next stage...\n");
printk(KERN_NOTICE "megaraid_sas: HBA recovery state machine,"
"state 2 starting...\n");
/*waitting for about 20 second before start the second init*/
for (wait = 0; wait < 30; wait++) {
msleep(1000);
}
if (megasas_transition_to_ready(instance, 1)) {
printk(KERN_NOTICE "megaraid_sas:adapter not ready\n");
megaraid_sas_kill_hba(instance);
instance->adprecovery = MEGASAS_HW_CRITICAL_ERROR;
return ;
}
if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) ||
(instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) ||
(instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)
) {
*instance->consumer = *instance->producer;
} else {
*instance->consumer = 0;
*instance->producer = 0;
}
megasas_issue_init_mfi(instance);
spin_lock_irqsave(&instance->hba_lock, flags);
instance->adprecovery = MEGASAS_HBA_OPERATIONAL;
spin_unlock_irqrestore(&instance->hba_lock, flags);
instance->instancet->enable_intr(instance->reg_set);
megasas_issue_pending_cmds_again(instance);
instance->issuepend_done = 1;
}
return ;
}
/**
* megasas_deplete_reply_queue - Processes all completed commands
* @instance: Adapter soft state
* @alt_status: Alternate status to be returned to
* SCSI mid-layer instead of the status
* returned by the FW
* Note: this must be called with hba lock held
*/
static int
megasas_deplete_reply_queue(struct megasas_instance *instance,
u8 alt_status)
{
u32 mfiStatus;
u32 fw_state;
if ((mfiStatus = instance->instancet->check_reset(instance,
instance->reg_set)) == 1) {
return IRQ_HANDLED;
}
if ((mfiStatus = instance->instancet->clear_intr(
instance->reg_set)
) == 0) {
/* Hardware may not set outbound_intr_status in MSI-X mode */
if (!instance->msix_vectors)
return IRQ_NONE;
}
instance->mfiStatus = mfiStatus;
if ((mfiStatus & MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE)) {
fw_state = instance->instancet->read_fw_status_reg(
instance->reg_set) & MFI_STATE_MASK;
if (fw_state != MFI_STATE_FAULT) {
printk(KERN_NOTICE "megaraid_sas: fw state:%x\n",
fw_state);
}
if ((fw_state == MFI_STATE_FAULT) &&
(instance->disableOnlineCtrlReset == 0)) {
printk(KERN_NOTICE "megaraid_sas: wait adp restart\n");
if ((instance->pdev->device ==
PCI_DEVICE_ID_LSI_SAS1064R) ||
(instance->pdev->device ==
PCI_DEVICE_ID_DELL_PERC5) ||
(instance->pdev->device ==
PCI_DEVICE_ID_LSI_VERDE_ZCR)) {
*instance->consumer =
MEGASAS_ADPRESET_INPROG_SIGN;
}
instance->instancet->disable_intr(instance->reg_set);
instance->adprecovery = MEGASAS_ADPRESET_SM_INFAULT;
instance->issuepend_done = 0;
atomic_set(&instance->fw_outstanding, 0);
megasas_internal_reset_defer_cmds(instance);
printk(KERN_NOTICE "megasas: fwState=%x, stage:%d\n",
fw_state, instance->adprecovery);
schedule_work(&instance->work_init);
return IRQ_HANDLED;
} else {
printk(KERN_NOTICE "megasas: fwstate:%x, dis_OCR=%x\n",
fw_state, instance->disableOnlineCtrlReset);
}
}
tasklet_schedule(&instance->isr_tasklet);
return IRQ_HANDLED;
}
/**
* megasas_isr - isr entry point
*/
static irqreturn_t megasas_isr(int irq, void *devp)
{
struct megasas_irq_context *irq_context = devp;
struct megasas_instance *instance = irq_context->instance;
unsigned long flags;
irqreturn_t rc;
if (atomic_read(&instance->fw_reset_no_pci_access))
return IRQ_HANDLED;
spin_lock_irqsave(&instance->hba_lock, flags);
rc = megasas_deplete_reply_queue(instance, DID_OK);
spin_unlock_irqrestore(&instance->hba_lock, flags);
return rc;
}
/**
* megasas_transition_to_ready - Move the FW to READY state
* @instance: Adapter soft state
*
* During the initialization, FW passes can potentially be in any one of
* several possible states. If the FW in operational, waiting-for-handshake
* states, driver must take steps to bring it to ready state. Otherwise, it
* has to wait for the ready state.
*/
int
megasas_transition_to_ready(struct megasas_instance *instance, int ocr)
{
int i;
u8 max_wait;
u32 fw_state;
u32 cur_state;
u32 abs_state, curr_abs_state;
fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) & MFI_STATE_MASK;
if (fw_state != MFI_STATE_READY)
printk(KERN_INFO "megasas: Waiting for FW to come to ready"
" state\n");
while (fw_state != MFI_STATE_READY) {
abs_state =
instance->instancet->read_fw_status_reg(instance->reg_set);
switch (fw_state) {
case MFI_STATE_FAULT:
printk(KERN_DEBUG "megasas: FW in FAULT state!!\n");
if (ocr) {
max_wait = MEGASAS_RESET_WAIT_TIME;
cur_state = MFI_STATE_FAULT;
break;
} else
return -ENODEV;
case MFI_STATE_WAIT_HANDSHAKE:
/*
* Set the CLR bit in inbound doorbell
*/
if ((instance->pdev->device ==
PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
(instance->pdev->device ==
PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
(instance->pdev->device ==
PCI_DEVICE_ID_LSI_FUSION) ||
(instance->pdev->device ==
PCI_DEVICE_ID_LSI_INVADER)) {
writel(
MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
&instance->reg_set->doorbell);
} else {
writel(
MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
&instance->reg_set->inbound_doorbell);
}
max_wait = MEGASAS_RESET_WAIT_TIME;
cur_state = MFI_STATE_WAIT_HANDSHAKE;
break;
case MFI_STATE_BOOT_MESSAGE_PENDING:
if ((instance->pdev->device ==
PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
(instance->pdev->device ==
PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
(instance->pdev->device ==
PCI_DEVICE_ID_LSI_FUSION) ||
(instance->pdev->device ==
PCI_DEVICE_ID_LSI_INVADER)) {
writel(MFI_INIT_HOTPLUG,
&instance->reg_set->doorbell);
} else
writel(MFI_INIT_HOTPLUG,
&instance->reg_set->inbound_doorbell);
max_wait = MEGASAS_RESET_WAIT_TIME;
cur_state = MFI_STATE_BOOT_MESSAGE_PENDING;
break;
case MFI_STATE_OPERATIONAL:
/*
* Bring it to READY state; assuming max wait 10 secs
*/
instance->instancet->disable_intr(instance->reg_set);
if ((instance->pdev->device ==
PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
(instance->pdev->device ==
PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
(instance->pdev->device
== PCI_DEVICE_ID_LSI_FUSION) ||
(instance->pdev->device
== PCI_DEVICE_ID_LSI_INVADER)) {
writel(MFI_RESET_FLAGS,
&instance->reg_set->doorbell);
if ((instance->pdev->device ==
PCI_DEVICE_ID_LSI_FUSION) ||
(instance->pdev->device ==
PCI_DEVICE_ID_LSI_INVADER)) {
for (i = 0; i < (10 * 1000); i += 20) {
if (readl(
&instance->
reg_set->
doorbell) & 1)
msleep(20);
else
break;
}
}
} else
writel(MFI_RESET_FLAGS,
&instance->reg_set->inbound_doorbell);
max_wait = MEGASAS_RESET_WAIT_TIME;
cur_state = MFI_STATE_OPERATIONAL;
break;
case MFI_STATE_UNDEFINED:
/*
* This state should not last for more than 2 seconds
*/
max_wait = MEGASAS_RESET_WAIT_TIME;
cur_state = MFI_STATE_UNDEFINED;
break;
case MFI_STATE_BB_INIT:
max_wait = MEGASAS_RESET_WAIT_TIME;
cur_state = MFI_STATE_BB_INIT;
break;
case MFI_STATE_FW_INIT:
max_wait = MEGASAS_RESET_WAIT_TIME;
cur_state = MFI_STATE_FW_INIT;
break;
case MFI_STATE_FW_INIT_2:
max_wait = MEGASAS_RESET_WAIT_TIME;
cur_state = MFI_STATE_FW_INIT_2;
break;
case MFI_STATE_DEVICE_SCAN:
max_wait = MEGASAS_RESET_WAIT_TIME;
cur_state = MFI_STATE_DEVICE_SCAN;
break;
case MFI_STATE_FLUSH_CACHE:
max_wait = MEGASAS_RESET_WAIT_TIME;
cur_state = MFI_STATE_FLUSH_CACHE;
break;
default:
printk(KERN_DEBUG "megasas: Unknown state 0x%x\n",
fw_state);
return -ENODEV;
}
/*
* The cur_state should not last for more than max_wait secs
*/
for (i = 0; i < (max_wait * 1000); i++) {
fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) &
MFI_STATE_MASK ;
curr_abs_state =
instance->instancet->read_fw_status_reg(instance->reg_set);
if (abs_state == curr_abs_state) {
msleep(1);
} else
break;
}
/*
* Return error if fw_state hasn't changed after max_wait
*/
if (curr_abs_state == abs_state) {
printk(KERN_DEBUG "FW state [%d] hasn't changed "
"in %d secs\n", fw_state, max_wait);
return -ENODEV;
}
}
printk(KERN_INFO "megasas: FW now in Ready state\n");
return 0;
}
/**
* megasas_teardown_frame_pool - Destroy the cmd frame DMA pool
* @instance: Adapter soft state
*/
static void megasas_teardown_frame_pool(struct megasas_instance *instance)
{
int i;
u32 max_cmd = instance->max_mfi_cmds;
struct megasas_cmd *cmd;
if (!instance->frame_dma_pool)
return;
/*
* Return all frames to pool
*/
for (i = 0; i < max_cmd; i++) {
cmd = instance->cmd_list[i];
if (cmd->frame)
pci_pool_free(instance->frame_dma_pool, cmd->frame,
cmd->frame_phys_addr);
if (cmd->sense)
pci_pool_free(instance->sense_dma_pool, cmd->sense,
cmd->sense_phys_addr);
}
/*
* Now destroy the pool itself
*/
pci_pool_destroy(instance->frame_dma_pool);
pci_pool_destroy(instance->sense_dma_pool);
instance->frame_dma_pool = NULL;
instance->sense_dma_pool = NULL;
}
/**
* megasas_create_frame_pool - Creates DMA pool for cmd frames
* @instance: Adapter soft state
*
* Each command packet has an embedded DMA memory buffer that is used for
* filling MFI frame and the SG list that immediately follows the frame. This
* function creates those DMA memory buffers for each command packet by using
* PCI pool facility.
*/
static int megasas_create_frame_pool(struct megasas_instance *instance)
{
int i;
u32 max_cmd;
u32 sge_sz;
u32 sgl_sz;
u32 total_sz;
u32 frame_count;
struct megasas_cmd *cmd;
max_cmd = instance->max_mfi_cmds;
/*
* Size of our frame is 64 bytes for MFI frame, followed by max SG
* elements and finally SCSI_SENSE_BUFFERSIZE bytes for sense buffer
*/
sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
sizeof(struct megasas_sge32);
if (instance->flag_ieee) {
sge_sz = sizeof(struct megasas_sge_skinny);
}
/*
* Calculated the number of 64byte frames required for SGL
*/
sgl_sz = sge_sz * instance->max_num_sge;
frame_count = (sgl_sz + MEGAMFI_FRAME_SIZE - 1) / MEGAMFI_FRAME_SIZE;
frame_count = 15;
/*
* We need one extra frame for the MFI command
*/
frame_count++;
total_sz = MEGAMFI_FRAME_SIZE * frame_count;
/*
* Use DMA pool facility provided by PCI layer
*/
instance->frame_dma_pool = pci_pool_create("megasas frame pool",
instance->pdev, total_sz, 64,
0);
if (!instance->frame_dma_pool) {
printk(KERN_DEBUG "megasas: failed to setup frame pool\n");
return -ENOMEM;
}
instance->sense_dma_pool = pci_pool_create("megasas sense pool",
instance->pdev, 128, 4, 0);
if (!instance->sense_dma_pool) {
printk(KERN_DEBUG "megasas: failed to setup sense pool\n");
pci_pool_destroy(instance->frame_dma_pool);
instance->frame_dma_pool = NULL;
return -ENOMEM;
}
/*
* Allocate and attach a frame to each of the commands in cmd_list.
* By making cmd->index as the context instead of the &cmd, we can
* always use 32bit context regardless of the architecture
*/
for (i = 0; i < max_cmd; i++) {
cmd = instance->cmd_list[i];
cmd->frame = pci_pool_alloc(instance->frame_dma_pool,
GFP_KERNEL, &cmd->frame_phys_addr);
cmd->sense = pci_pool_alloc(instance->sense_dma_pool,
GFP_KERNEL, &cmd->sense_phys_addr);
/*
* megasas_teardown_frame_pool() takes care of freeing
* whatever has been allocated
*/
if (!cmd->frame || !cmd->sense) {
printk(KERN_DEBUG "megasas: pci_pool_alloc failed \n");
megasas_teardown_frame_pool(instance);
return -ENOMEM;
}
memset(cmd->frame, 0, total_sz);
cmd->frame->io.context = cmd->index;
cmd->frame->io.pad_0 = 0;
if ((instance->pdev->device != PCI_DEVICE_ID_LSI_FUSION) &&
(instance->pdev->device != PCI_DEVICE_ID_LSI_INVADER) &&
(reset_devices))
cmd->frame->hdr.cmd = MFI_CMD_INVALID;
}
return 0;
}
/**
* megasas_free_cmds - Free all the cmds in the free cmd pool
* @instance: Adapter soft state
*/
void megasas_free_cmds(struct megasas_instance *instance)
{
int i;
/* First free the MFI frame pool */
megasas_teardown_frame_pool(instance);
/* Free all the commands in the cmd_list */
for (i = 0; i < instance->max_mfi_cmds; i++)
kfree(instance->cmd_list[i]);
/* Free the cmd_list buffer itself */
kfree(instance->cmd_list);
instance->cmd_list = NULL;
INIT_LIST_HEAD(&instance->cmd_pool);
}
/**
* megasas_alloc_cmds - Allocates the command packets
* @instance: Adapter soft state
*
* Each command that is issued to the FW, whether IO commands from the OS or
* internal commands like IOCTLs, are wrapped in local data structure called
* megasas_cmd. The frame embedded in this megasas_cmd is actually issued to
* the FW.
*
* Each frame has a 32-bit field called context (tag). This context is used
* to get back the megasas_cmd from the frame when a frame gets completed in
* the ISR. Typically the address of the megasas_cmd itself would be used as
* the context. But we wanted to keep the differences between 32 and 64 bit
* systems to the mininum. We always use 32 bit integers for the context. In
* this driver, the 32 bit values are the indices into an array cmd_list.
* This array is used only to look up the megasas_cmd given the context. The
* free commands themselves are maintained in a linked list called cmd_pool.
*/
int megasas_alloc_cmds(struct megasas_instance *instance)
{
int i;
int j;
u32 max_cmd;
struct megasas_cmd *cmd;
max_cmd = instance->max_mfi_cmds;
/*
* instance->cmd_list is an array of struct megasas_cmd pointers.
* Allocate the dynamic array first and then allocate individual
* commands.
*/
instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);
if (!instance->cmd_list) {
printk(KERN_DEBUG "megasas: out of memory\n");
return -ENOMEM;
}
memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd);
for (i = 0; i < max_cmd; i++) {
instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
GFP_KERNEL);
if (!instance->cmd_list[i]) {
for (j = 0; j < i; j++)
kfree(instance->cmd_list[j]);
kfree(instance->cmd_list);
instance->cmd_list = NULL;
return -ENOMEM;
}
}
/*
* Add all the commands to command pool (instance->cmd_pool)
*/
for (i = 0; i < max_cmd; i++) {
cmd = instance->cmd_list[i];
memset(cmd, 0, sizeof(struct megasas_cmd));
cmd->index = i;
cmd->scmd = NULL;
cmd->instance = instance;
list_add_tail(&cmd->list, &instance->cmd_pool);
}
/*
* Create a frame pool and assign one frame to each cmd
*/
if (megasas_create_frame_pool(instance)) {
printk(KERN_DEBUG "megasas: Error creating frame DMA pool\n");
megasas_free_cmds(instance);
}
return 0;
}
/*
* megasas_get_pd_list_info - Returns FW's pd_list structure
* @instance: Adapter soft state
* @pd_list: pd_list structure
*
* Issues an internal command (DCMD) to get the FW's controller PD
* list structure. This information is mainly used to find out SYSTEM
* supported by the FW.
*/
static int
megasas_get_pd_list(struct megasas_instance *instance)
{
int ret = 0, pd_index = 0;
struct megasas_cmd *cmd;
struct megasas_dcmd_frame *dcmd;
struct MR_PD_LIST *ci;
struct MR_PD_ADDRESS *pd_addr;
dma_addr_t ci_h = 0;
cmd = megasas_get_cmd(instance);
if (!cmd) {
printk(KERN_DEBUG "megasas (get_pd_list): Failed to get cmd\n");
return -ENOMEM;
}
dcmd = &cmd->frame->dcmd;
ci = pci_alloc_consistent(instance->pdev,
MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST), &ci_h);
if (!ci) {
printk(KERN_DEBUG "Failed to alloc mem for pd_list\n");
megasas_return_cmd(instance, cmd);
return -ENOMEM;
}
memset(ci, 0, sizeof(*ci));
memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
dcmd->mbox.b[0] = MR_PD_QUERY_TYPE_EXPOSED_TO_HOST;
dcmd->mbox.b[1] = 0;
dcmd->cmd = MFI_CMD_DCMD;
dcmd->cmd_status = 0xFF;
dcmd->sge_count = 1;
dcmd->flags = MFI_FRAME_DIR_READ;
dcmd->timeout = 0;
dcmd->pad_0 = 0;
dcmd->data_xfer_len = MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST);
dcmd->opcode = MR_DCMD_PD_LIST_QUERY;
dcmd->sgl.sge32[0].phys_addr = ci_h;
dcmd->sgl.sge32[0].length = MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST);
if (!megasas_issue_polled(instance, cmd)) {
ret = 0;
} else {
ret = -1;
}
/*
* the following function will get the instance PD LIST.
*/
pd_addr = ci->addr;
if ( ret == 0 &&
(ci->count <
(MEGASAS_MAX_PD_CHANNELS * MEGASAS_MAX_DEV_PER_CHANNEL))) {
memset(instance->pd_list, 0,
MEGASAS_MAX_PD * sizeof(struct megasas_pd_list));
for (pd_index = 0; pd_index < ci->count; pd_index++) {
instance->pd_list[pd_addr->deviceId].tid =
pd_addr->deviceId;
instance->pd_list[pd_addr->deviceId].driveType =
pd_addr->scsiDevType;
instance->pd_list[pd_addr->deviceId].driveState =
MR_PD_STATE_SYSTEM;
pd_addr++;
}
}
pci_free_consistent(instance->pdev,
MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST),
ci, ci_h);
megasas_return_cmd(instance, cmd);
return ret;
}
/*
* megasas_get_ld_list_info - Returns FW's ld_list structure
* @instance: Adapter soft state
* @ld_list: ld_list structure
*
* Issues an internal command (DCMD) to get the FW's controller PD
* list structure. This information is mainly used to find out SYSTEM
* supported by the FW.
*/
static int
megasas_get_ld_list(struct megasas_instance *instance)
{
int ret = 0, ld_index = 0, ids = 0;
struct megasas_cmd *cmd;
struct megasas_dcmd_frame *dcmd;
struct MR_LD_LIST *ci;
dma_addr_t ci_h = 0;
cmd = megasas_get_cmd(instance);
if (!cmd) {
printk(KERN_DEBUG "megasas_get_ld_list: Failed to get cmd\n");
return -ENOMEM;
}
dcmd = &cmd->frame->dcmd;
ci = pci_alloc_consistent(instance->pdev,
sizeof(struct MR_LD_LIST),
&ci_h);
if (!ci) {
printk(KERN_DEBUG "Failed to alloc mem in get_ld_list\n");
megasas_return_cmd(instance, cmd);
return -ENOMEM;
}
memset(ci, 0, sizeof(*ci));
memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
dcmd->cmd = MFI_CMD_DCMD;
dcmd->cmd_status = 0xFF;
dcmd->sge_count = 1;
dcmd->flags = MFI_FRAME_DIR_READ;
dcmd->timeout = 0;
dcmd->data_xfer_len = sizeof(struct MR_LD_LIST);
dcmd->opcode = MR_DCMD_LD_GET_LIST;
dcmd->sgl.sge32[0].phys_addr = ci_h;
dcmd->sgl.sge32[0].length = sizeof(struct MR_LD_LIST);
dcmd->pad_0 = 0;
if (!megasas_issue_polled(instance, cmd)) {
ret = 0;
} else {
ret = -1;
}
/* the following function will get the instance PD LIST */
if ((ret == 0) && (ci->ldCount <= MAX_LOGICAL_DRIVES)) {
memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
for (ld_index = 0; ld_index < ci->ldCount; ld_index++) {
if (ci->ldList[ld_index].state != 0) {
ids = ci->ldList[ld_index].ref.targetId;
instance->ld_ids[ids] =
ci->ldList[ld_index].ref.targetId;
}
}
}
pci_free_consistent(instance->pdev,
sizeof(struct MR_LD_LIST),
ci,
ci_h);
megasas_return_cmd(instance, cmd);
return ret;
}
/**
* megasas_get_controller_info - Returns FW's controller structure
* @instance: Adapter soft state
* @ctrl_info: Controller information structure
*
* Issues an internal command (DCMD) to get the FW's controller structure.
* This information is mainly used to find out the maximum IO transfer per
* command supported by the FW.
*/
static int
megasas_get_ctrl_info(struct megasas_instance *instance,
struct megasas_ctrl_info *ctrl_info)
{
int ret = 0;
struct megasas_cmd *cmd;
struct megasas_dcmd_frame *dcmd;
struct megasas_ctrl_info *ci;
dma_addr_t ci_h = 0;
cmd = megasas_get_cmd(instance);
if (!cmd) {
printk(KERN_DEBUG "megasas: Failed to get a free cmd\n");
return -ENOMEM;
}
dcmd = &cmd->frame->dcmd;
ci = pci_alloc_consistent(instance->pdev,
sizeof(struct megasas_ctrl_info), &ci_h);
if (!ci) {
printk(KERN_DEBUG "Failed to alloc mem for ctrl info\n");
megasas_return_cmd(instance, cmd);
return -ENOMEM;
}
memset(ci, 0, sizeof(*ci));
memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
dcmd->cmd = MFI_CMD_DCMD;
dcmd->cmd_status = 0xFF;
dcmd->sge_count = 1;
dcmd->flags = MFI_FRAME_DIR_READ;
dcmd->timeout = 0;
dcmd->pad_0 = 0;
dcmd->data_xfer_len = sizeof(struct megasas_ctrl_info);
dcmd->opcode = MR_DCMD_CTRL_GET_INFO;
dcmd->sgl.sge32[0].phys_addr = ci_h;
dcmd->sgl.sge32[0].length = sizeof(struct megasas_ctrl_info);
if (!megasas_issue_polled(instance, cmd)) {
ret = 0;
memcpy(ctrl_info, ci, sizeof(struct megasas_ctrl_info));
} else {
ret = -1;
}
pci_free_consistent(instance->pdev, sizeof(struct megasas_ctrl_info),
ci, ci_h);
megasas_return_cmd(instance, cmd);
return ret;
}
/**
* megasas_issue_init_mfi - Initializes the FW
* @instance: Adapter soft state
*
* Issues the INIT MFI cmd
*/
static int
megasas_issue_init_mfi(struct megasas_instance *instance)
{
u32 context;
struct megasas_cmd *cmd;
struct megasas_init_frame *init_frame;
struct megasas_init_queue_info *initq_info;
dma_addr_t init_frame_h;
dma_addr_t initq_info_h;
/*
* Prepare a init frame. Note the init frame points to queue info
* structure. Each frame has SGL allocated after first 64 bytes. For
* this frame - since we don't need any SGL - we use SGL's space as
* queue info structure
*
* We will not get a NULL command below. We just created the pool.
*/
cmd = megasas_get_cmd(instance);
init_frame = (struct megasas_init_frame *)cmd->frame;
initq_info = (struct megasas_init_queue_info *)
((unsigned long)init_frame + 64);
init_frame_h = cmd->frame_phys_addr;
initq_info_h = init_frame_h + 64;
context = init_frame->context;
memset(init_frame, 0, MEGAMFI_FRAME_SIZE);
memset(initq_info, 0, sizeof(struct megasas_init_queue_info));
init_frame->context = context;
initq_info->reply_queue_entries = instance->max_fw_cmds + 1;
initq_info->reply_queue_start_phys_addr_lo = instance->reply_queue_h;
initq_info->producer_index_phys_addr_lo = instance->producer_h;
initq_info->consumer_index_phys_addr_lo = instance->consumer_h;
init_frame->cmd = MFI_CMD_INIT;
init_frame->cmd_status = 0xFF;
init_frame->queue_info_new_phys_addr_lo = initq_info_h;
init_frame->data_xfer_len = sizeof(struct megasas_init_queue_info);
/*
* disable the intr before firing the init frame to FW
*/
instance->instancet->disable_intr(instance->reg_set);
/*
* Issue the init frame in polled mode
*/
if (megasas_issue_polled(instance, cmd)) {
printk(KERN_ERR "megasas: Failed to init firmware\n");
megasas_return_cmd(instance, cmd);
goto fail_fw_init;
}
megasas_return_cmd(instance, cmd);
return 0;
fail_fw_init:
return -EINVAL;
}
static u32
megasas_init_adapter_mfi(struct megasas_instance *instance)
{
struct megasas_register_set __iomem *reg_set;
u32 context_sz;
u32 reply_q_sz;
reg_set = instance->reg_set;
/*
* Get various operational parameters from status register
*/
instance->max_fw_cmds = instance->instancet->read_fw_status_reg(reg_set) & 0x00FFFF;
/*
* Reduce the max supported cmds by 1. This is to ensure that the
* reply_q_sz (1 more than the max cmd that driver may send)
* does not exceed max cmds that the FW can support
*/
instance->max_fw_cmds = instance->max_fw_cmds-1;
instance->max_mfi_cmds = instance->max_fw_cmds;
instance->max_num_sge = (instance->instancet->read_fw_status_reg(reg_set) & 0xFF0000) >>
0x10;
/*
* Create a pool of commands
*/
if (megasas_alloc_cmds(instance))
goto fail_alloc_cmds;
/*
* Allocate memory for reply queue. Length of reply queue should
* be _one_ more than the maximum commands handled by the firmware.
*
* Note: When FW completes commands, it places corresponding contex
* values in this circular reply queue. This circular queue is a fairly
* typical producer-consumer queue. FW is the producer (of completed
* commands) and the driver is the consumer.
*/
context_sz = sizeof(u32);
reply_q_sz = context_sz * (instance->max_fw_cmds + 1);
instance->reply_queue = pci_alloc_consistent(instance->pdev,
reply_q_sz,
&instance->reply_queue_h);
if (!instance->reply_queue) {
printk(KERN_DEBUG "megasas: Out of DMA mem for reply queue\n");
goto fail_reply_queue;
}
if (megasas_issue_init_mfi(instance))
goto fail_fw_init;
instance->fw_support_ieee = 0;
instance->fw_support_ieee =
(instance->instancet->read_fw_status_reg(reg_set) &
0x04000000);
printk(KERN_NOTICE "megasas_init_mfi: fw_support_ieee=%d",
instance->fw_support_ieee);
if (instance->fw_support_ieee)
instance->flag_ieee = 1;
return 0;
fail_fw_init:
pci_free_consistent(instance->pdev, reply_q_sz,
instance->reply_queue, instance->reply_queue_h);
fail_reply_queue:
megasas_free_cmds(instance);
fail_alloc_cmds:
return 1;
}
/**
* megasas_init_fw - Initializes the FW
* @instance: Adapter soft state
*
* This is the main function for initializing firmware
*/
static int megasas_init_fw(struct megasas_instance *instance)
{
u32 max_sectors_1;
u32 max_sectors_2;
u32 tmp_sectors, msix_enable;
struct megasas_register_set __iomem *reg_set;
struct megasas_ctrl_info *ctrl_info;
unsigned long bar_list;
int i;
/* Find first memory bar */
bar_list = pci_select_bars(instance->pdev, IORESOURCE_MEM);
instance->bar = find_first_bit(&bar_list, sizeof(unsigned long));
instance->base_addr = pci_resource_start(instance->pdev, instance->bar);
if (pci_request_selected_regions(instance->pdev, instance->bar,
"megasas: LSI")) {
printk(KERN_DEBUG "megasas: IO memory region busy!\n");
return -EBUSY;
}
instance->reg_set = ioremap_nocache(instance->base_addr, 8192);
if (!instance->reg_set) {
printk(KERN_DEBUG "megasas: Failed to map IO mem\n");
goto fail_ioremap;
}
reg_set = instance->reg_set;
switch (instance->pdev->device) {
case PCI_DEVICE_ID_LSI_FUSION:
case PCI_DEVICE_ID_LSI_INVADER:
instance->instancet = &megasas_instance_template_fusion;
break;
case PCI_DEVICE_ID_LSI_SAS1078R:
case PCI_DEVICE_ID_LSI_SAS1078DE:
instance->instancet = &megasas_instance_template_ppc;
break;
case PCI_DEVICE_ID_LSI_SAS1078GEN2:
case PCI_DEVICE_ID_LSI_SAS0079GEN2:
instance->instancet = &megasas_instance_template_gen2;
break;
case PCI_DEVICE_ID_LSI_SAS0073SKINNY:
case PCI_DEVICE_ID_LSI_SAS0071SKINNY:
instance->instancet = &megasas_instance_template_skinny;
break;
case PCI_DEVICE_ID_LSI_SAS1064R:
case PCI_DEVICE_ID_DELL_PERC5:
default:
instance->instancet = &megasas_instance_template_xscale;
break;
}
/*
* We expect the FW state to be READY
*/
if (megasas_transition_to_ready(instance, 0))
goto fail_ready_state;
/* Check if MSI-X is supported while in ready state */
msix_enable = (instance->instancet->read_fw_status_reg(reg_set) &
0x4000000) >> 0x1a;
if (msix_enable && !msix_disable) {
/* Check max MSI-X vectors */
if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
(instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)) {
instance->msix_vectors = (readl(&instance->reg_set->
outbound_scratch_pad_2
) & 0x1F) + 1;
} else
instance->msix_vectors = 1;
/* Don't bother allocating more MSI-X vectors than cpus */
instance->msix_vectors = min(instance->msix_vectors,
(unsigned int)num_online_cpus());
for (i = 0; i < instance->msix_vectors; i++)
instance->msixentry[i].entry = i;
i = pci_enable_msix(instance->pdev, instance->msixentry,
instance->msix_vectors);
if (i >= 0) {
if (i) {
if (!pci_enable_msix(instance->pdev,
instance->msixentry, i))
instance->msix_vectors = i;
else
instance->msix_vectors = 0;
}
} else
instance->msix_vectors = 0;
}
/* Get operational params, sge flags, send init cmd to controller */
if (instance->instancet->init_adapter(instance))
goto fail_init_adapter;
printk(KERN_ERR "megasas: INIT adapter done\n");
/** for passthrough
* the following function will get the PD LIST.
*/
memset(instance->pd_list, 0 ,
(MEGASAS_MAX_PD * sizeof(struct megasas_pd_list)));
megasas_get_pd_list(instance);
memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
megasas_get_ld_list(instance);
ctrl_info = kmalloc(sizeof(struct megasas_ctrl_info), GFP_KERNEL);
/*
* Compute the max allowed sectors per IO: The controller info has two
* limits on max sectors. Driver should use the minimum of these two.
*
* 1 << stripe_sz_ops.min = max sectors per strip
*
* Note that older firmwares ( < FW ver 30) didn't report information
* to calculate max_sectors_1. So the number ended up as zero always.
*/
tmp_sectors = 0;
if (ctrl_info && !megasas_get_ctrl_info(instance, ctrl_info)) {
max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) *
ctrl_info->max_strips_per_io;
max_sectors_2 = ctrl_info->max_request_size;
tmp_sectors = min_t(u32, max_sectors_1 , max_sectors_2);
instance->disableOnlineCtrlReset =
ctrl_info->properties.OnOffProperties.disableOnlineCtrlReset;
}
instance->max_sectors_per_req = instance->max_num_sge *
PAGE_SIZE / 512;
if (tmp_sectors && (instance->max_sectors_per_req > tmp_sectors))
instance->max_sectors_per_req = tmp_sectors;
kfree(ctrl_info);
/*
* Setup tasklet for cmd completion
*/
tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet,
(unsigned long)instance);
return 0;
fail_init_adapter:
fail_ready_state:
iounmap(instance->reg_set);
fail_ioremap:
pci_release_selected_regions(instance->pdev, instance->bar);
return -EINVAL;
}
/**
* megasas_release_mfi - Reverses the FW initialization
* @intance: Adapter soft state
*/
static void megasas_release_mfi(struct megasas_instance *instance)
{
u32 reply_q_sz = sizeof(u32) *(instance->max_mfi_cmds + 1);
if (instance->reply_queue)
pci_free_consistent(instance->pdev, reply_q_sz,
instance->reply_queue, instance->reply_queue_h);
megasas_free_cmds(instance);
iounmap(instance->reg_set);
pci_release_selected_regions(instance->pdev, instance->bar);
}
/**
* megasas_get_seq_num - Gets latest event sequence numbers
* @instance: Adapter soft state
* @eli: FW event log sequence numbers information
*
* FW maintains a log of all events in a non-volatile area. Upper layers would
* usually find out the latest sequence number of the events, the seq number at
* the boot etc. They would "read" all the events below the latest seq number
* by issuing a direct fw cmd (DCMD). For the future events (beyond latest seq
* number), they would subsribe to AEN (asynchronous event notification) and
* wait for the events to happen.
*/
static int
megasas_get_seq_num(struct megasas_instance *instance,
struct megasas_evt_log_info *eli)
{
struct megasas_cmd *cmd;
struct megasas_dcmd_frame *dcmd;
struct megasas_evt_log_info *el_info;
dma_addr_t el_info_h = 0;
cmd = megasas_get_cmd(instance);
if (!cmd) {
return -ENOMEM;
}
dcmd = &cmd->frame->dcmd;
el_info = pci_alloc_consistent(instance->pdev,
sizeof(struct megasas_evt_log_info),
&el_info_h);
if (!el_info) {
megasas_return_cmd(instance, cmd);
return -ENOMEM;
}
memset(el_info, 0, sizeof(*el_info));
memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
dcmd->cmd = MFI_CMD_DCMD;
dcmd->cmd_status = 0x0;
dcmd->sge_count = 1;
dcmd->flags = MFI_FRAME_DIR_READ;
dcmd->timeout = 0;
dcmd->pad_0 = 0;
dcmd->data_xfer_len = sizeof(struct megasas_evt_log_info);
dcmd->opcode = MR_DCMD_CTRL_EVENT_GET_INFO;
dcmd->sgl.sge32[0].phys_addr = el_info_h;
dcmd->sgl.sge32[0].length = sizeof(struct megasas_evt_log_info);
megasas_issue_blocked_cmd(instance, cmd);
/*
* Copy the data back into callers buffer
*/
memcpy(eli, el_info, sizeof(struct megasas_evt_log_info));
pci_free_consistent(instance->pdev, sizeof(struct megasas_evt_log_info),
el_info, el_info_h);
megasas_return_cmd(instance, cmd);
return 0;
}
/**
* megasas_register_aen - Registers for asynchronous event notification
* @instance: Adapter soft state
* @seq_num: The starting sequence number
* @class_locale: Class of the event
*
* This function subscribes for AEN for events beyond the @seq_num. It requests
* to be notified if and only if the event is of type @class_locale
*/
static int
megasas_register_aen(struct megasas_instance *instance, u32 seq_num,
u32 class_locale_word)
{
int ret_val;
struct megasas_cmd *cmd;
struct megasas_dcmd_frame *dcmd;
union megasas_evt_class_locale curr_aen;
union megasas_evt_class_locale prev_aen;
/*
* If there an AEN pending already (aen_cmd), check if the
* class_locale of that pending AEN is inclusive of the new
* AEN request we currently have. If it is, then we don't have
* to do anything. In other words, whichever events the current
* AEN request is subscribing to, have already been subscribed
* to.
*
* If the old_cmd is _not_ inclusive, then we have to abort
* that command, form a class_locale that is superset of both
* old and current and re-issue to the FW
*/
curr_aen.word = class_locale_word;
if (instance->aen_cmd) {
prev_aen.word = instance->aen_cmd->frame->dcmd.mbox.w[1];
/*
* A class whose enum value is smaller is inclusive of all
* higher values. If a PROGRESS (= -1) was previously
* registered, then a new registration requests for higher
* classes need not be sent to FW. They are automatically
* included.
*
* Locale numbers don't have such hierarchy. They are bitmap
* values
*/
if ((prev_aen.members.class <= curr_aen.members.class) &&
!((prev_aen.members.locale & curr_aen.members.locale) ^
curr_aen.members.locale)) {
/*
* Previously issued event registration includes
* current request. Nothing to do.
*/
return 0;
} else {
curr_aen.members.locale |= prev_aen.members.locale;
if (prev_aen.members.class < curr_aen.members.class)
curr_aen.members.class = prev_aen.members.class;
instance->aen_cmd->abort_aen = 1;
ret_val = megasas_issue_blocked_abort_cmd(instance,
instance->
aen_cmd);
if (ret_val) {
printk(KERN_DEBUG "megasas: Failed to abort "
"previous AEN command\n");
return ret_val;
}
}
}
cmd = megasas_get_cmd(instance);
if (!cmd)
return -ENOMEM;
dcmd = &cmd->frame->dcmd;
memset(instance->evt_detail, 0, sizeof(struct megasas_evt_detail));
/*
* Prepare DCMD for aen registration
*/
memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
dcmd->cmd = MFI_CMD_DCMD;
dcmd->cmd_status = 0x0;
dcmd->sge_count = 1;
dcmd->flags = MFI_FRAME_DIR_READ;
dcmd->timeout = 0;
dcmd->pad_0 = 0;
instance->last_seq_num = seq_num;
dcmd->data_xfer_len = sizeof(struct megasas_evt_detail);
dcmd->opcode = MR_DCMD_CTRL_EVENT_WAIT;
dcmd->mbox.w[0] = seq_num;
dcmd->mbox.w[1] = curr_aen.word;
dcmd->sgl.sge32[0].phys_addr = (u32) instance->evt_detail_h;
dcmd->sgl.sge32[0].length = sizeof(struct megasas_evt_detail);
if (instance->aen_cmd != NULL) {
megasas_return_cmd(instance, cmd);
return 0;
}
/*
* Store reference to the cmd used to register for AEN. When an
* application wants us to register for AEN, we have to abort this
* cmd and re-register with a new EVENT LOCALE supplied by that app
*/
instance->aen_cmd = cmd;
/*
* Issue the aen registration frame
*/
instance->instancet->issue_dcmd(instance, cmd);
return 0;
}
/**
* megasas_start_aen - Subscribes to AEN during driver load time
* @instance: Adapter soft state
*/
static int megasas_start_aen(struct megasas_instance *instance)
{
struct megasas_evt_log_info eli;
union megasas_evt_class_locale class_locale;
/*
* Get the latest sequence number from FW
*/
memset(&eli, 0, sizeof(eli));
if (megasas_get_seq_num(instance, &eli))
return -1;
/*
* Register AEN with FW for latest sequence number plus 1
*/
class_locale.members.reserved = 0;
class_locale.members.locale = MR_EVT_LOCALE_ALL;
class_locale.members.class = MR_EVT_CLASS_DEBUG;
return megasas_register_aen(instance, eli.newest_seq_num + 1,
class_locale.word);
}
/**
* megasas_io_attach - Attaches this driver to SCSI mid-layer
* @instance: Adapter soft state
*/
static int megasas_io_attach(struct megasas_instance *instance)
{
struct Scsi_Host *host = instance->host;
/*
* Export parameters required by SCSI mid-layer
*/
host->irq = instance->pdev->irq;
host->unique_id = instance->unique_id;
if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
(instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
host->can_queue =
instance->max_fw_cmds - MEGASAS_SKINNY_INT_CMDS;
} else
host->can_queue =
instance->max_fw_cmds - MEGASAS_INT_CMDS;
host->this_id = instance->init_id;
host->sg_tablesize = instance->max_num_sge;
if (instance->fw_support_ieee)
instance->max_sectors_per_req = MEGASAS_MAX_SECTORS_IEEE;
/*
* Check if the module parameter value for max_sectors can be used
*/
if (max_sectors && max_sectors < instance->max_sectors_per_req)
instance->max_sectors_per_req = max_sectors;
else {
if (max_sectors) {
if (((instance->pdev->device ==
PCI_DEVICE_ID_LSI_SAS1078GEN2) ||
(instance->pdev->device ==
PCI_DEVICE_ID_LSI_SAS0079GEN2)) &&
(max_sectors <= MEGASAS_MAX_SECTORS)) {
instance->max_sectors_per_req = max_sectors;
} else {
printk(KERN_INFO "megasas: max_sectors should be > 0"
"and <= %d (or < 1MB for GEN2 controller)\n",
instance->max_sectors_per_req);
}
}
}
host->max_sectors = instance->max_sectors_per_req;
host->cmd_per_lun = MEGASAS_DEFAULT_CMD_PER_LUN;
host->max_channel = MEGASAS_MAX_CHANNELS - 1;
host->max_id = MEGASAS_MAX_DEV_PER_CHANNEL;
host->max_lun = MEGASAS_MAX_LUN;
host->max_cmd_len = 16;
/* Fusion only supports host reset */
if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
(instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)) {
host->hostt->eh_device_reset_handler = NULL;
host->hostt->eh_bus_reset_handler = NULL;
}
/*
* Notify the mid-layer about the new controller
*/
if (scsi_add_host(host, &instance->pdev->dev)) {
printk(KERN_DEBUG "megasas: scsi_add_host failed\n");
return -ENODEV;
}
/*
* Trigger SCSI to scan our drives
*/
scsi_scan_host(host);
return 0;
}
static int
megasas_set_dma_mask(struct pci_dev *pdev)
{
/*
* All our contollers are capable of performing 64-bit DMA
*/
if (IS_DMA64) {
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64)) != 0) {
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0)
goto fail_set_dma_mask;
}
} else {
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0)
goto fail_set_dma_mask;
}
return 0;
fail_set_dma_mask:
return 1;
}
/**
* megasas_probe_one - PCI hotplug entry point
* @pdev: PCI device structure
* @id: PCI ids of supported hotplugged adapter
*/
static int __devinit
megasas_probe_one(struct pci_dev *pdev, const struct pci_device_id *id)
{
int rval, pos, i, j;
struct Scsi_Host *host;
struct megasas_instance *instance;
u16 control = 0;
/* Reset MSI-X in the kdump kernel */
if (reset_devices) {
pos = pci_find_capability(pdev, PCI_CAP_ID_MSIX);
if (pos) {
pci_read_config_word(pdev, msi_control_reg(pos),
&control);
if (control & PCI_MSIX_FLAGS_ENABLE) {
dev_info(&pdev->dev, "resetting MSI-X\n");
pci_write_config_word(pdev,
msi_control_reg(pos),
control &
~PCI_MSIX_FLAGS_ENABLE);
}
}
}
/*
* Announce PCI information
*/
printk(KERN_INFO "megasas: %#4.04x:%#4.04x:%#4.04x:%#4.04x: ",
pdev->vendor, pdev->device, pdev->subsystem_vendor,
pdev->subsystem_device);
printk("bus %d:slot %d:func %d\n",
pdev->bus->number, PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
/*
* PCI prepping: enable device set bus mastering and dma mask
*/
rval = pci_enable_device_mem(pdev);
if (rval) {
return rval;
}
pci_set_master(pdev);
if (megasas_set_dma_mask(pdev))
goto fail_set_dma_mask;
host = scsi_host_alloc(&megasas_template,
sizeof(struct megasas_instance));
if (!host) {
printk(KERN_DEBUG "megasas: scsi_host_alloc failed\n");
goto fail_alloc_instance;
}
instance = (struct megasas_instance *)host->hostdata;
memset(instance, 0, sizeof(*instance));
atomic_set( &instance->fw_reset_no_pci_access, 0 );
instance->pdev = pdev;
switch (instance->pdev->device) {
case PCI_DEVICE_ID_LSI_FUSION:
case PCI_DEVICE_ID_LSI_INVADER:
{
struct fusion_context *fusion;
instance->ctrl_context =
kzalloc(sizeof(struct fusion_context), GFP_KERNEL);
if (!instance->ctrl_context) {
printk(KERN_DEBUG "megasas: Failed to allocate "
"memory for Fusion context info\n");
goto fail_alloc_dma_buf;
}
fusion = instance->ctrl_context;
INIT_LIST_HEAD(&fusion->cmd_pool);
spin_lock_init(&fusion->cmd_pool_lock);
}
break;
default: /* For all other supported controllers */
instance->producer =
pci_alloc_consistent(pdev, sizeof(u32),
&instance->producer_h);
instance->consumer =
pci_alloc_consistent(pdev, sizeof(u32),
&instance->consumer_h);
if (!instance->producer || !instance->consumer) {
printk(KERN_DEBUG "megasas: Failed to allocate"
"memory for producer, consumer\n");
goto fail_alloc_dma_buf;
}
*instance->producer = 0;
*instance->consumer = 0;
break;
}
megasas_poll_wait_aen = 0;
instance->flag_ieee = 0;
instance->ev = NULL;
instance->issuepend_done = 1;
instance->adprecovery = MEGASAS_HBA_OPERATIONAL;
megasas_poll_wait_aen = 0;
instance->evt_detail = pci_alloc_consistent(pdev,
sizeof(struct
megasas_evt_detail),
&instance->evt_detail_h);
if (!instance->evt_detail) {
printk(KERN_DEBUG "megasas: Failed to allocate memory for "
"event detail structure\n");
goto fail_alloc_dma_buf;
}
/*
* Initialize locks and queues
*/
INIT_LIST_HEAD(&instance->cmd_pool);
INIT_LIST_HEAD(&instance->internal_reset_pending_q);
atomic_set(&instance->fw_outstanding,0);
init_waitqueue_head(&instance->int_cmd_wait_q);
init_waitqueue_head(&instance->abort_cmd_wait_q);
spin_lock_init(&instance->cmd_pool_lock);
spin_lock_init(&instance->hba_lock);
spin_lock_init(&instance->completion_lock);
spin_lock_init(&poll_aen_lock);
mutex_init(&instance->aen_mutex);
mutex_init(&instance->reset_mutex);
/*
* Initialize PCI related and misc parameters
*/
instance->host = host;
instance->unique_id = pdev->bus->number << 8 | pdev->devfn;
instance->init_id = MEGASAS_DEFAULT_INIT_ID;
if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
(instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
instance->flag_ieee = 1;
sema_init(&instance->ioctl_sem, MEGASAS_SKINNY_INT_CMDS);
} else
sema_init(&instance->ioctl_sem, MEGASAS_INT_CMDS);
megasas_dbg_lvl = 0;
instance->flag = 0;
instance->unload = 1;
instance->last_time = 0;
instance->disableOnlineCtrlReset = 1;
if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
(instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER))
INIT_WORK(&instance->work_init, megasas_fusion_ocr_wq);
else
INIT_WORK(&instance->work_init, process_fw_state_change_wq);
/*
* Initialize MFI Firmware
*/
if (megasas_init_fw(instance))
goto fail_init_mfi;
/*
* Register IRQ
*/
if (instance->msix_vectors) {
for (i = 0 ; i < instance->msix_vectors; i++) {
instance->irq_context[i].instance = instance;
instance->irq_context[i].MSIxIndex = i;
if (request_irq(instance->msixentry[i].vector,
instance->instancet->service_isr, 0,
"megasas",
&instance->irq_context[i])) {
printk(KERN_DEBUG "megasas: Failed to "
"register IRQ for vector %d.\n", i);
for (j = 0 ; j < i ; j++)
free_irq(
instance->msixentry[j].vector,
&instance->irq_context[j]);
goto fail_irq;
}
}
} else {
instance->irq_context[0].instance = instance;
instance->irq_context[0].MSIxIndex = 0;
if (request_irq(pdev->irq, instance->instancet->service_isr,
IRQF_SHARED, "megasas",
&instance->irq_context[0])) {
printk(KERN_DEBUG "megasas: Failed to register IRQ\n");
goto fail_irq;
}
}
instance->instancet->enable_intr(instance->reg_set);
/*
* Store instance in PCI softstate
*/
pci_set_drvdata(pdev, instance);
/*
* Add this controller to megasas_mgmt_info structure so that it
* can be exported to management applications
*/
megasas_mgmt_info.count++;
megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = instance;
megasas_mgmt_info.max_index++;
/*
* Register with SCSI mid-layer
*/
if (megasas_io_attach(instance))
goto fail_io_attach;
instance->unload = 0;
/*
* Initiate AEN (Asynchronous Event Notification)
*/
if (megasas_start_aen(instance)) {
printk(KERN_DEBUG "megasas: start aen failed\n");
goto fail_start_aen;
}
return 0;
fail_start_aen:
fail_io_attach:
megasas_mgmt_info.count--;
megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = NULL;
megasas_mgmt_info.max_index--;
pci_set_drvdata(pdev, NULL);
instance->instancet->disable_intr(instance->reg_set);
if (instance->msix_vectors)
for (i = 0 ; i < instance->msix_vectors; i++)
free_irq(instance->msixentry[i].vector,
&instance->irq_context[i]);
else
free_irq(instance->pdev->irq, &instance->irq_context[0]);
fail_irq:
if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
(instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER))
megasas_release_fusion(instance);
else
megasas_release_mfi(instance);
fail_init_mfi:
if (instance->msix_vectors)
pci_disable_msix(instance->pdev);
fail_alloc_dma_buf:
if (instance->evt_detail)
pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
instance->evt_detail,
instance->evt_detail_h);
if (instance->producer)
pci_free_consistent(pdev, sizeof(u32), instance->producer,
instance->producer_h);
if (instance->consumer)
pci_free_consistent(pdev, sizeof(u32), instance->consumer,
instance->consumer_h);
scsi_host_put(host);
fail_alloc_instance:
fail_set_dma_mask:
pci_disable_device(pdev);
return -ENODEV;
}
/**
* megasas_flush_cache - Requests FW to flush all its caches
* @instance: Adapter soft state
*/
static void megasas_flush_cache(struct megasas_instance *instance)
{
struct megasas_cmd *cmd;
struct megasas_dcmd_frame *dcmd;
if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR)
return;
cmd = megasas_get_cmd(instance);
if (!cmd)
return;
dcmd = &cmd->frame->dcmd;
memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
dcmd->cmd = MFI_CMD_DCMD;
dcmd->cmd_status = 0x0;
dcmd->sge_count = 0;
dcmd->flags = MFI_FRAME_DIR_NONE;
dcmd->timeout = 0;
dcmd->pad_0 = 0;
dcmd->data_xfer_len = 0;
dcmd->opcode = MR_DCMD_CTRL_CACHE_FLUSH;
dcmd->mbox.b[0] = MR_FLUSH_CTRL_CACHE | MR_FLUSH_DISK_CACHE;
megasas_issue_blocked_cmd(instance, cmd);
megasas_return_cmd(instance, cmd);
return;
}
/**
* megasas_shutdown_controller - Instructs FW to shutdown the controller
* @instance: Adapter soft state
* @opcode: Shutdown/Hibernate
*/
static void megasas_shutdown_controller(struct megasas_instance *instance,
u32 opcode)
{
struct megasas_cmd *cmd;
struct megasas_dcmd_frame *dcmd;
if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR)
return;
cmd = megasas_get_cmd(instance);
if (!cmd)
return;
if (instance->aen_cmd)
megasas_issue_blocked_abort_cmd(instance, instance->aen_cmd);
if (instance->map_update_cmd)
megasas_issue_blocked_abort_cmd(instance,
instance->map_update_cmd);
dcmd = &cmd->frame->dcmd;
memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
dcmd->cmd = MFI_CMD_DCMD;
dcmd->cmd_status = 0x0;
dcmd->sge_count = 0;
dcmd->flags = MFI_FRAME_DIR_NONE;
dcmd->timeout = 0;
dcmd->pad_0 = 0;
dcmd->data_xfer_len = 0;
dcmd->opcode = opcode;
megasas_issue_blocked_cmd(instance, cmd);
megasas_return_cmd(instance, cmd);
return;
}
#ifdef CONFIG_PM
/**
* megasas_suspend - driver suspend entry point
* @pdev: PCI device structure
* @state: PCI power state to suspend routine
*/
static int
megasas_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct Scsi_Host *host;
struct megasas_instance *instance;
int i;
instance = pci_get_drvdata(pdev);
host = instance->host;
instance->unload = 1;
megasas_flush_cache(instance);
megasas_shutdown_controller(instance, MR_DCMD_HIBERNATE_SHUTDOWN);
/* cancel the delayed work if this work still in queue */
if (instance->ev != NULL) {
struct megasas_aen_event *ev = instance->ev;
cancel_delayed_work_sync(
(struct delayed_work *)&ev->hotplug_work);
instance->ev = NULL;
}
tasklet_kill(&instance->isr_tasklet);
pci_set_drvdata(instance->pdev, instance);
instance->instancet->disable_intr(instance->reg_set);
if (instance->msix_vectors)
for (i = 0 ; i < instance->msix_vectors; i++)
free_irq(instance->msixentry[i].vector,
&instance->irq_context[i]);
else
free_irq(instance->pdev->irq, &instance->irq_context[0]);
if (instance->msix_vectors)
pci_disable_msix(instance->pdev);
pci_save_state(pdev);
pci_disable_device(pdev);
pci_set_power_state(pdev, pci_choose_state(pdev, state));
return 0;
}
/**
* megasas_resume- driver resume entry point
* @pdev: PCI device structure
*/
static int
megasas_resume(struct pci_dev *pdev)
{
int rval, i, j;
struct Scsi_Host *host;
struct megasas_instance *instance;
instance = pci_get_drvdata(pdev);
host = instance->host;
pci_set_power_state(pdev, PCI_D0);
pci_enable_wake(pdev, PCI_D0, 0);
pci_restore_state(pdev);
/*
* PCI prepping: enable device set bus mastering and dma mask
*/
rval = pci_enable_device_mem(pdev);
if (rval) {
printk(KERN_ERR "megasas: Enable device failed\n");
return rval;
}
pci_set_master(pdev);
if (megasas_set_dma_mask(pdev))
goto fail_set_dma_mask;
/*
* Initialize MFI Firmware
*/
atomic_set(&instance->fw_outstanding, 0);
/*
* We expect the FW state to be READY
*/
if (megasas_transition_to_ready(instance, 0))
goto fail_ready_state;
/* Now re-enable MSI-X */
if (instance->msix_vectors)
pci_enable_msix(instance->pdev, instance->msixentry,
instance->msix_vectors);
switch (instance->pdev->device) {
case PCI_DEVICE_ID_LSI_FUSION:
case PCI_DEVICE_ID_LSI_INVADER:
{
megasas_reset_reply_desc(instance);
if (megasas_ioc_init_fusion(instance)) {
megasas_free_cmds(instance);
megasas_free_cmds_fusion(instance);
goto fail_init_mfi;
}
if (!megasas_get_map_info(instance))
megasas_sync_map_info(instance);
}
break;
default:
*instance->producer = 0;
*instance->consumer = 0;
if (megasas_issue_init_mfi(instance))
goto fail_init_mfi;
break;
}
tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet,
(unsigned long)instance);
/*
* Register IRQ
*/
if (instance->msix_vectors) {
for (i = 0 ; i < instance->msix_vectors; i++) {
instance->irq_context[i].instance = instance;
instance->irq_context[i].MSIxIndex = i;
if (request_irq(instance->msixentry[i].vector,
instance->instancet->service_isr, 0,
"megasas",
&instance->irq_context[i])) {
printk(KERN_DEBUG "megasas: Failed to "
"register IRQ for vector %d.\n", i);
for (j = 0 ; j < i ; j++)
free_irq(
instance->msixentry[j].vector,
&instance->irq_context[j]);
goto fail_irq;
}
}
} else {
instance->irq_context[0].instance = instance;
instance->irq_context[0].MSIxIndex = 0;
if (request_irq(pdev->irq, instance->instancet->service_isr,
IRQF_SHARED, "megasas",
&instance->irq_context[0])) {
printk(KERN_DEBUG "megasas: Failed to register IRQ\n");
goto fail_irq;
}
}
instance->instancet->enable_intr(instance->reg_set);
instance->unload = 0;
/*
* Initiate AEN (Asynchronous Event Notification)
*/
if (megasas_start_aen(instance))
printk(KERN_ERR "megasas: Start AEN failed\n");
return 0;
fail_irq:
fail_init_mfi:
if (instance->evt_detail)
pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
instance->evt_detail,
instance->evt_detail_h);
if (instance->producer)
pci_free_consistent(pdev, sizeof(u32), instance->producer,
instance->producer_h);
if (instance->consumer)
pci_free_consistent(pdev, sizeof(u32), instance->consumer,
instance->consumer_h);
scsi_host_put(host);
fail_set_dma_mask:
fail_ready_state:
pci_disable_device(pdev);
return -ENODEV;
}
#else
#define megasas_suspend NULL
#define megasas_resume NULL
#endif
/**
* megasas_detach_one - PCI hot"un"plug entry point
* @pdev: PCI device structure
*/
static void __devexit megasas_detach_one(struct pci_dev *pdev)
{
int i;
struct Scsi_Host *host;
struct megasas_instance *instance;
struct fusion_context *fusion;
instance = pci_get_drvdata(pdev);
instance->unload = 1;
host = instance->host;
fusion = instance->ctrl_context;
scsi_remove_host(instance->host);
megasas_flush_cache(instance);
megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
/* cancel the delayed work if this work still in queue*/
if (instance->ev != NULL) {
struct megasas_aen_event *ev = instance->ev;
cancel_delayed_work_sync(
(struct delayed_work *)&ev->hotplug_work);
instance->ev = NULL;
}
tasklet_kill(&instance->isr_tasklet);
/*
* Take the instance off the instance array. Note that we will not
* decrement the max_index. We let this array be sparse array
*/
for (i = 0; i < megasas_mgmt_info.max_index; i++) {
if (megasas_mgmt_info.instance[i] == instance) {
megasas_mgmt_info.count--;
megasas_mgmt_info.instance[i] = NULL;
break;
}
}
pci_set_drvdata(instance->pdev, NULL);
instance->instancet->disable_intr(instance->reg_set);
if (instance->msix_vectors)
for (i = 0 ; i < instance->msix_vectors; i++)
free_irq(instance->msixentry[i].vector,
&instance->irq_context[i]);
else
free_irq(instance->pdev->irq, &instance->irq_context[0]);
if (instance->msix_vectors)
pci_disable_msix(instance->pdev);
switch (instance->pdev->device) {
case PCI_DEVICE_ID_LSI_FUSION:
case PCI_DEVICE_ID_LSI_INVADER:
megasas_release_fusion(instance);
for (i = 0; i < 2 ; i++)
if (fusion->ld_map[i])
dma_free_coherent(&instance->pdev->dev,
fusion->map_sz,
fusion->ld_map[i],
fusion->
ld_map_phys[i]);
kfree(instance->ctrl_context);
break;
default:
megasas_release_mfi(instance);
pci_free_consistent(pdev,
sizeof(struct megasas_evt_detail),
instance->evt_detail,
instance->evt_detail_h);
pci_free_consistent(pdev, sizeof(u32),
instance->producer,
instance->producer_h);
pci_free_consistent(pdev, sizeof(u32),
instance->consumer,
instance->consumer_h);
break;
}
scsi_host_put(host);
pci_set_drvdata(pdev, NULL);
pci_disable_device(pdev);
return;
}
/**
* megasas_shutdown - Shutdown entry point
* @device: Generic device structure
*/
static void megasas_shutdown(struct pci_dev *pdev)
{
int i;
struct megasas_instance *instance = pci_get_drvdata(pdev);
instance->unload = 1;
megasas_flush_cache(instance);
megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
instance->instancet->disable_intr(instance->reg_set);
if (instance->msix_vectors)
for (i = 0 ; i < instance->msix_vectors; i++)
free_irq(instance->msixentry[i].vector,
&instance->irq_context[i]);
else
free_irq(instance->pdev->irq, &instance->irq_context[0]);
if (instance->msix_vectors)
pci_disable_msix(instance->pdev);
}
/**
* megasas_mgmt_open - char node "open" entry point
*/
static int megasas_mgmt_open(struct inode *inode, struct file *filep)
{
/*
* Allow only those users with admin rights
*/
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
return 0;
}
/**
* megasas_mgmt_fasync - Async notifier registration from applications
*
* This function adds the calling process to a driver global queue. When an
* event occurs, SIGIO will be sent to all processes in this queue.
*/
static int megasas_mgmt_fasync(int fd, struct file *filep, int mode)
{
int rc;
mutex_lock(&megasas_async_queue_mutex);
rc = fasync_helper(fd, filep, mode, &megasas_async_queue);
mutex_unlock(&megasas_async_queue_mutex);
if (rc >= 0) {
/* For sanity check when we get ioctl */
filep->private_data = filep;
return 0;
}
printk(KERN_DEBUG "megasas: fasync_helper failed [%d]\n", rc);
return rc;
}
/**
* megasas_mgmt_poll - char node "poll" entry point
* */
static unsigned int megasas_mgmt_poll(struct file *file, poll_table *wait)
{
unsigned int mask;
unsigned long flags;
poll_wait(file, &megasas_poll_wait, wait);
spin_lock_irqsave(&poll_aen_lock, flags);
if (megasas_poll_wait_aen)
mask = (POLLIN | POLLRDNORM);
else
mask = 0;
spin_unlock_irqrestore(&poll_aen_lock, flags);
return mask;
}
/**
* megasas_mgmt_fw_ioctl - Issues management ioctls to FW
* @instance: Adapter soft state
* @argp: User's ioctl packet
*/
static int
megasas_mgmt_fw_ioctl(struct megasas_instance *instance,
struct megasas_iocpacket __user * user_ioc,
struct megasas_iocpacket *ioc)
{
struct megasas_sge32 *kern_sge32;
struct megasas_cmd *cmd;
void *kbuff_arr[MAX_IOCTL_SGE];
dma_addr_t buf_handle = 0;
int error = 0, i;
void *sense = NULL;
dma_addr_t sense_handle;
unsigned long *sense_ptr;
memset(kbuff_arr, 0, sizeof(kbuff_arr));
if (ioc->sge_count > MAX_IOCTL_SGE) {
printk(KERN_DEBUG "megasas: SGE count [%d] > max limit [%d]\n",
ioc->sge_count, MAX_IOCTL_SGE);
return -EINVAL;
}
cmd = megasas_get_cmd(instance);
if (!cmd) {
printk(KERN_DEBUG "megasas: Failed to get a cmd packet\n");
return -ENOMEM;
}
/*
* User's IOCTL packet has 2 frames (maximum). Copy those two
* frames into our cmd's frames. cmd->frame's context will get
* overwritten when we copy from user's frames. So set that value
* alone separately
*/
memcpy(cmd->frame, ioc->frame.raw, 2 * MEGAMFI_FRAME_SIZE);
cmd->frame->hdr.context = cmd->index;
cmd->frame->hdr.pad_0 = 0;
cmd->frame->hdr.flags &= ~(MFI_FRAME_IEEE | MFI_FRAME_SGL64 |
MFI_FRAME_SENSE64);
/*
* The management interface between applications and the fw uses
* MFI frames. E.g, RAID configuration changes, LD property changes
* etc are accomplishes through different kinds of MFI frames. The
* driver needs to care only about substituting user buffers with
* kernel buffers in SGLs. The location of SGL is embedded in the
* struct iocpacket itself.
*/
kern_sge32 = (struct megasas_sge32 *)
((unsigned long)cmd->frame + ioc->sgl_off);
/*
* For each user buffer, create a mirror buffer and copy in
*/
for (i = 0; i < ioc->sge_count; i++) {
if (!ioc->sgl[i].iov_len)
continue;
kbuff_arr[i] = dma_alloc_coherent(&instance->pdev->dev,
ioc->sgl[i].iov_len,
&buf_handle, GFP_KERNEL);
if (!kbuff_arr[i]) {
printk(KERN_DEBUG "megasas: Failed to alloc "
"kernel SGL buffer for IOCTL \n");
error = -ENOMEM;
goto out;
}
/*
* We don't change the dma_coherent_mask, so
* pci_alloc_consistent only returns 32bit addresses
*/
kern_sge32[i].phys_addr = (u32) buf_handle;
kern_sge32[i].length = ioc->sgl[i].iov_len;
/*
* We created a kernel buffer corresponding to the
* user buffer. Now copy in from the user buffer
*/
if (copy_from_user(kbuff_arr[i], ioc->sgl[i].iov_base,
(u32) (ioc->sgl[i].iov_len))) {
error = -EFAULT;
goto out;
}
}
if (ioc->sense_len) {
sense = dma_alloc_coherent(&instance->pdev->dev, ioc->sense_len,
&sense_handle, GFP_KERNEL);
if (!sense) {
error = -ENOMEM;
goto out;
}
sense_ptr =
(unsigned long *) ((unsigned long)cmd->frame + ioc->sense_off);
*sense_ptr = sense_handle;
}
/*
* Set the sync_cmd flag so that the ISR knows not to complete this
* cmd to the SCSI mid-layer
*/
cmd->sync_cmd = 1;
megasas_issue_blocked_cmd(instance, cmd);
cmd->sync_cmd = 0;
/*
* copy out the kernel buffers to user buffers
*/
for (i = 0; i < ioc->sge_count; i++) {
if (copy_to_user(ioc->sgl[i].iov_base, kbuff_arr[i],
ioc->sgl[i].iov_len)) {
error = -EFAULT;
goto out;
}
}
/*
* copy out the sense
*/
if (ioc->sense_len) {
/*
* sense_ptr points to the location that has the user
* sense buffer address
*/
sense_ptr = (unsigned long *) ((unsigned long)ioc->frame.raw +
ioc->sense_off);
if (copy_to_user((void __user *)((unsigned long)(*sense_ptr)),
sense, ioc->sense_len)) {
printk(KERN_ERR "megasas: Failed to copy out to user "
"sense data\n");
error = -EFAULT;
goto out;
}
}
/*
* copy the status codes returned by the fw
*/
if (copy_to_user(&user_ioc->frame.hdr.cmd_status,
&cmd->frame->hdr.cmd_status, sizeof(u8))) {
printk(KERN_DEBUG "megasas: Error copying out cmd_status\n");
error = -EFAULT;
}
out:
if (sense) {
dma_free_coherent(&instance->pdev->dev, ioc->sense_len,
sense, sense_handle);
}
for (i = 0; i < ioc->sge_count && kbuff_arr[i]; i++) {
dma_free_coherent(&instance->pdev->dev,
kern_sge32[i].length,
kbuff_arr[i], kern_sge32[i].phys_addr);
}
megasas_return_cmd(instance, cmd);
return error;
}
static int megasas_mgmt_ioctl_fw(struct file *file, unsigned long arg)
{
struct megasas_iocpacket __user *user_ioc =
(struct megasas_iocpacket __user *)arg;
struct megasas_iocpacket *ioc;
struct megasas_instance *instance;
int error;
int i;
unsigned long flags;
u32 wait_time = MEGASAS_RESET_WAIT_TIME;
ioc = kmalloc(sizeof(*ioc), GFP_KERNEL);
if (!ioc)
return -ENOMEM;
if (copy_from_user(ioc, user_ioc, sizeof(*ioc))) {
error = -EFAULT;
goto out_kfree_ioc;
}
instance = megasas_lookup_instance(ioc->host_no);
if (!instance) {
error = -ENODEV;
goto out_kfree_ioc;
}
if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
printk(KERN_ERR "Controller in crit error\n");
error = -ENODEV;
goto out_kfree_ioc;
}
if (instance->unload == 1) {
error = -ENODEV;
goto out_kfree_ioc;
}
/*
* We will allow only MEGASAS_INT_CMDS number of parallel ioctl cmds
*/
if (down_interruptible(&instance->ioctl_sem)) {
error = -ERESTARTSYS;
goto out_kfree_ioc;
}
for (i = 0; i < wait_time; i++) {
spin_lock_irqsave(&instance->hba_lock, flags);
if (instance->adprecovery == MEGASAS_HBA_OPERATIONAL) {
spin_unlock_irqrestore(&instance->hba_lock, flags);
break;
}
spin_unlock_irqrestore(&instance->hba_lock, flags);
if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
printk(KERN_NOTICE "megasas: waiting"
"for controller reset to finish\n");
}
msleep(1000);
}
spin_lock_irqsave(&instance->hba_lock, flags);
if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) {
spin_unlock_irqrestore(&instance->hba_lock, flags);
printk(KERN_ERR "megaraid_sas: timed out while"
"waiting for HBA to recover\n");
error = -ENODEV;
goto out_kfree_ioc;
}
spin_unlock_irqrestore(&instance->hba_lock, flags);
error = megasas_mgmt_fw_ioctl(instance, user_ioc, ioc);
up(&instance->ioctl_sem);
out_kfree_ioc:
kfree(ioc);
return error;
}
static int megasas_mgmt_ioctl_aen(struct file *file, unsigned long arg)
{
struct megasas_instance *instance;
struct megasas_aen aen;
int error;
int i;
unsigned long flags;
u32 wait_time = MEGASAS_RESET_WAIT_TIME;
if (file->private_data != file) {
printk(KERN_DEBUG "megasas: fasync_helper was not "
"called first\n");
return -EINVAL;
}
if (copy_from_user(&aen, (void __user *)arg, sizeof(aen)))
return -EFAULT;
instance = megasas_lookup_instance(aen.host_no);
if (!instance)
return -ENODEV;
if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
return -ENODEV;
}
if (instance->unload == 1) {
return -ENODEV;
}
for (i = 0; i < wait_time; i++) {
spin_lock_irqsave(&instance->hba_lock, flags);
if (instance->adprecovery == MEGASAS_HBA_OPERATIONAL) {
spin_unlock_irqrestore(&instance->hba_lock,
flags);
break;
}
spin_unlock_irqrestore(&instance->hba_lock, flags);
if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
printk(KERN_NOTICE "megasas: waiting for"
"controller reset to finish\n");
}
msleep(1000);
}
spin_lock_irqsave(&instance->hba_lock, flags);
if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) {
spin_unlock_irqrestore(&instance->hba_lock, flags);
printk(KERN_ERR "megaraid_sas: timed out while waiting"
"for HBA to recover.\n");
return -ENODEV;
}
spin_unlock_irqrestore(&instance->hba_lock, flags);
mutex_lock(&instance->aen_mutex);
error = megasas_register_aen(instance, aen.seq_num,
aen.class_locale_word);
mutex_unlock(&instance->aen_mutex);
return error;
}
/**
* megasas_mgmt_ioctl - char node ioctl entry point
*/
static long
megasas_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
switch (cmd) {
case MEGASAS_IOC_FIRMWARE:
return megasas_mgmt_ioctl_fw(file, arg);
case MEGASAS_IOC_GET_AEN:
return megasas_mgmt_ioctl_aen(file, arg);
}
return -ENOTTY;
}
#ifdef CONFIG_COMPAT
static int megasas_mgmt_compat_ioctl_fw(struct file *file, unsigned long arg)
{
struct compat_megasas_iocpacket __user *cioc =
(struct compat_megasas_iocpacket __user *)arg;
struct megasas_iocpacket __user *ioc =
compat_alloc_user_space(sizeof(struct megasas_iocpacket));
int i;
int error = 0;
compat_uptr_t ptr;
if (clear_user(ioc, sizeof(*ioc)))
return -EFAULT;
if (copy_in_user(&ioc->host_no, &cioc->host_no, sizeof(u16)) ||
copy_in_user(&ioc->sgl_off, &cioc->sgl_off, sizeof(u32)) ||
copy_in_user(&ioc->sense_off, &cioc->sense_off, sizeof(u32)) ||
copy_in_user(&ioc->sense_len, &cioc->sense_len, sizeof(u32)) ||
copy_in_user(ioc->frame.raw, cioc->frame.raw, 128) ||
copy_in_user(&ioc->sge_count, &cioc->sge_count, sizeof(u32)))
return -EFAULT;
/*
* The sense_ptr is used in megasas_mgmt_fw_ioctl only when
* sense_len is not null, so prepare the 64bit value under
* the same condition.
*/
if (ioc->sense_len) {
void __user **sense_ioc_ptr =
(void __user **)(ioc->frame.raw + ioc->sense_off);
compat_uptr_t *sense_cioc_ptr =
(compat_uptr_t *)(cioc->frame.raw + cioc->sense_off);
if (get_user(ptr, sense_cioc_ptr) ||
put_user(compat_ptr(ptr), sense_ioc_ptr))
return -EFAULT;
}
for (i = 0; i < MAX_IOCTL_SGE; i++) {
if (get_user(ptr, &cioc->sgl[i].iov_base) ||
put_user(compat_ptr(ptr), &ioc->sgl[i].iov_base) ||
copy_in_user(&ioc->sgl[i].iov_len,
&cioc->sgl[i].iov_len, sizeof(compat_size_t)))
return -EFAULT;
}
error = megasas_mgmt_ioctl_fw(file, (unsigned long)ioc);
if (copy_in_user(&cioc->frame.hdr.cmd_status,
&ioc->frame.hdr.cmd_status, sizeof(u8))) {
printk(KERN_DEBUG "megasas: error copy_in_user cmd_status\n");
return -EFAULT;
}
return error;
}
static long
megasas_mgmt_compat_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
switch (cmd) {
case MEGASAS_IOC_FIRMWARE32:
return megasas_mgmt_compat_ioctl_fw(file, arg);
case MEGASAS_IOC_GET_AEN:
return megasas_mgmt_ioctl_aen(file, arg);
}
return -ENOTTY;
}
#endif
/*
* File operations structure for management interface
*/
static const struct file_operations megasas_mgmt_fops = {
.owner = THIS_MODULE,
.open = megasas_mgmt_open,
.fasync = megasas_mgmt_fasync,
.unlocked_ioctl = megasas_mgmt_ioctl,
.poll = megasas_mgmt_poll,
#ifdef CONFIG_COMPAT
.compat_ioctl = megasas_mgmt_compat_ioctl,
#endif
.llseek = noop_llseek,
};
/*
* PCI hotplug support registration structure
*/
static struct pci_driver megasas_pci_driver = {
.name = "megaraid_sas",
.id_table = megasas_pci_table,
.probe = megasas_probe_one,
.remove = __devexit_p(megasas_detach_one),
.suspend = megasas_suspend,
.resume = megasas_resume,
.shutdown = megasas_shutdown,
};
/*
* Sysfs driver attributes
*/
static ssize_t megasas_sysfs_show_version(struct device_driver *dd, char *buf)
{
return snprintf(buf, strlen(MEGASAS_VERSION) + 2, "%s\n",
MEGASAS_VERSION);
}
static DRIVER_ATTR(version, S_IRUGO, megasas_sysfs_show_version, NULL);
static ssize_t
megasas_sysfs_show_release_date(struct device_driver *dd, char *buf)
{
return snprintf(buf, strlen(MEGASAS_RELDATE) + 2, "%s\n",
MEGASAS_RELDATE);
}
static DRIVER_ATTR(release_date, S_IRUGO, megasas_sysfs_show_release_date,
NULL);
static ssize_t
megasas_sysfs_show_support_poll_for_event(struct device_driver *dd, char *buf)
{
return sprintf(buf, "%u\n", support_poll_for_event);
}
static DRIVER_ATTR(support_poll_for_event, S_IRUGO,
megasas_sysfs_show_support_poll_for_event, NULL);
static ssize_t
megasas_sysfs_show_support_device_change(struct device_driver *dd, char *buf)
{
return sprintf(buf, "%u\n", support_device_change);
}
static DRIVER_ATTR(support_device_change, S_IRUGO,
megasas_sysfs_show_support_device_change, NULL);
static ssize_t
megasas_sysfs_show_dbg_lvl(struct device_driver *dd, char *buf)
{
return sprintf(buf, "%u\n", megasas_dbg_lvl);
}
static ssize_t
megasas_sysfs_set_dbg_lvl(struct device_driver *dd, const char *buf, size_t count)
{
int retval = count;
if(sscanf(buf,"%u",&megasas_dbg_lvl)<1){
printk(KERN_ERR "megasas: could not set dbg_lvl\n");
retval = -EINVAL;
}
return retval;
}
static DRIVER_ATTR(dbg_lvl, S_IRUGO|S_IWUSR, megasas_sysfs_show_dbg_lvl,
megasas_sysfs_set_dbg_lvl);
static void
megasas_aen_polling(struct work_struct *work)
{
struct megasas_aen_event *ev =
container_of(work, struct megasas_aen_event, hotplug_work);
struct megasas_instance *instance = ev->instance;
union megasas_evt_class_locale class_locale;
struct Scsi_Host *host;
struct scsi_device *sdev1;
u16 pd_index = 0;
u16 ld_index = 0;
int i, j, doscan = 0;
u32 seq_num;
int error;
if (!instance) {
printk(KERN_ERR "invalid instance!\n");
kfree(ev);
return;
}
instance->ev = NULL;
host = instance->host;
if (instance->evt_detail) {
switch (instance->evt_detail->code) {
case MR_EVT_PD_INSERTED:
if (megasas_get_pd_list(instance) == 0) {
for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
for (j = 0;
j < MEGASAS_MAX_DEV_PER_CHANNEL;
j++) {
pd_index =
(i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
sdev1 =
scsi_device_lookup(host, i, j, 0);
if (instance->pd_list[pd_index].driveState
== MR_PD_STATE_SYSTEM) {
if (!sdev1) {
scsi_add_device(host, i, j, 0);
}
if (sdev1)
scsi_device_put(sdev1);
}
}
}
}
doscan = 0;
break;
case MR_EVT_PD_REMOVED:
if (megasas_get_pd_list(instance) == 0) {
megasas_get_pd_list(instance);
for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
for (j = 0;
j < MEGASAS_MAX_DEV_PER_CHANNEL;
j++) {
pd_index =
(i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
sdev1 =
scsi_device_lookup(host, i, j, 0);
if (instance->pd_list[pd_index].driveState
== MR_PD_STATE_SYSTEM) {
if (sdev1) {
scsi_device_put(sdev1);
}
} else {
if (sdev1) {
scsi_remove_device(sdev1);
scsi_device_put(sdev1);
}
}
}
}
}
doscan = 0;
break;
case MR_EVT_LD_OFFLINE:
case MR_EVT_CFG_CLEARED:
case MR_EVT_LD_DELETED:
megasas_get_ld_list(instance);
for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
for (j = 0;
j < MEGASAS_MAX_DEV_PER_CHANNEL;
j++) {
ld_index =
(i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
sdev1 = scsi_device_lookup(host,
i + MEGASAS_MAX_LD_CHANNELS,
j,
0);
if (instance->ld_ids[ld_index] != 0xff) {
if (sdev1) {
scsi_device_put(sdev1);
}
} else {
if (sdev1) {
scsi_remove_device(sdev1);
scsi_device_put(sdev1);
}
}
}
}
doscan = 0;
break;
case MR_EVT_LD_CREATED:
megasas_get_ld_list(instance);
for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
for (j = 0;
j < MEGASAS_MAX_DEV_PER_CHANNEL;
j++) {
ld_index =
(i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
sdev1 = scsi_device_lookup(host,
i+MEGASAS_MAX_LD_CHANNELS,
j, 0);
if (instance->ld_ids[ld_index] !=
0xff) {
if (!sdev1) {
scsi_add_device(host,
i + 2,
j, 0);
}
}
if (sdev1) {
scsi_device_put(sdev1);
}
}
}
doscan = 0;
break;
case MR_EVT_CTRL_HOST_BUS_SCAN_REQUESTED:
case MR_EVT_FOREIGN_CFG_IMPORTED:
case MR_EVT_LD_STATE_CHANGE:
doscan = 1;
break;
default:
doscan = 0;
break;
}
} else {
printk(KERN_ERR "invalid evt_detail!\n");
kfree(ev);
return;
}
if (doscan) {
printk(KERN_INFO "scanning ...\n");
megasas_get_pd_list(instance);
for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) {
pd_index = i*MEGASAS_MAX_DEV_PER_CHANNEL + j;
sdev1 = scsi_device_lookup(host, i, j, 0);
if (instance->pd_list[pd_index].driveState ==
MR_PD_STATE_SYSTEM) {
if (!sdev1) {
scsi_add_device(host, i, j, 0);
}
if (sdev1)
scsi_device_put(sdev1);
} else {
if (sdev1) {
scsi_remove_device(sdev1);
scsi_device_put(sdev1);
}
}
}
}
megasas_get_ld_list(instance);
for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) {
ld_index =
(i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
sdev1 = scsi_device_lookup(host,
i+MEGASAS_MAX_LD_CHANNELS, j, 0);
if (instance->ld_ids[ld_index] != 0xff) {
if (!sdev1) {
scsi_add_device(host,
i+2,
j, 0);
} else {
scsi_device_put(sdev1);
}
} else {
if (sdev1) {
scsi_remove_device(sdev1);
scsi_device_put(sdev1);
}
}
}
}
}
if ( instance->aen_cmd != NULL ) {
kfree(ev);
return ;
}
seq_num = instance->evt_detail->seq_num + 1;
/* Register AEN with FW for latest sequence number plus 1 */
class_locale.members.reserved = 0;
class_locale.members.locale = MR_EVT_LOCALE_ALL;
class_locale.members.class = MR_EVT_CLASS_DEBUG;
mutex_lock(&instance->aen_mutex);
error = megasas_register_aen(instance, seq_num,
class_locale.word);
mutex_unlock(&instance->aen_mutex);
if (error)
printk(KERN_ERR "register aen failed error %x\n", error);
kfree(ev);
}
/**
* megasas_init - Driver load entry point
*/
static int __init megasas_init(void)
{
int rval;
/*
* Announce driver version and other information
*/
printk(KERN_INFO "megasas: %s %s\n", MEGASAS_VERSION,
MEGASAS_EXT_VERSION);
support_poll_for_event = 2;
support_device_change = 1;
memset(&megasas_mgmt_info, 0, sizeof(megasas_mgmt_info));
/*
* Register character device node
*/
rval = register_chrdev(0, "megaraid_sas_ioctl", &megasas_mgmt_fops);
if (rval < 0) {
printk(KERN_DEBUG "megasas: failed to open device node\n");
return rval;
}
megasas_mgmt_majorno = rval;
/*
* Register ourselves as PCI hotplug module
*/
rval = pci_register_driver(&megasas_pci_driver);
if (rval) {
printk(KERN_DEBUG "megasas: PCI hotplug regisration failed \n");
goto err_pcidrv;
}
rval = driver_create_file(&megasas_pci_driver.driver,
&driver_attr_version);
if (rval)
goto err_dcf_attr_ver;
rval = driver_create_file(&megasas_pci_driver.driver,
&driver_attr_release_date);
if (rval)
goto err_dcf_rel_date;
rval = driver_create_file(&megasas_pci_driver.driver,
&driver_attr_support_poll_for_event);
if (rval)
goto err_dcf_support_poll_for_event;
rval = driver_create_file(&megasas_pci_driver.driver,
&driver_attr_dbg_lvl);
if (rval)
goto err_dcf_dbg_lvl;
rval = driver_create_file(&megasas_pci_driver.driver,
&driver_attr_support_device_change);
if (rval)
goto err_dcf_support_device_change;
return rval;
err_dcf_support_device_change:
driver_remove_file(&megasas_pci_driver.driver,
&driver_attr_dbg_lvl);
err_dcf_dbg_lvl:
driver_remove_file(&megasas_pci_driver.driver,
&driver_attr_support_poll_for_event);
err_dcf_support_poll_for_event:
driver_remove_file(&megasas_pci_driver.driver,
&driver_attr_release_date);
err_dcf_rel_date:
driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
err_dcf_attr_ver:
pci_unregister_driver(&megasas_pci_driver);
err_pcidrv:
unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
return rval;
}
/**
* megasas_exit - Driver unload entry point
*/
static void __exit megasas_exit(void)
{
driver_remove_file(&megasas_pci_driver.driver,
&driver_attr_dbg_lvl);
driver_remove_file(&megasas_pci_driver.driver,
&driver_attr_support_poll_for_event);
driver_remove_file(&megasas_pci_driver.driver,
&driver_attr_support_device_change);
driver_remove_file(&megasas_pci_driver.driver,
&driver_attr_release_date);
driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
pci_unregister_driver(&megasas_pci_driver);
unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
}
module_init(megasas_init);
module_exit(megasas_exit);
| gpl-2.0 |
rukin5197/android_kernel_htc_msm7x30 | arch/sh/kernel/cpufreq.c | 4044 | 4113 | /*
* arch/sh/kernel/cpufreq.c
*
* cpufreq driver for the SuperH processors.
*
* Copyright (C) 2002 - 2007 Paul Mundt
* Copyright (C) 2002 M. R. Brown
*
* Clock framework bits from arch/avr32/mach-at32ap/cpufreq.c
*
* Copyright (C) 2004-2007 Atmel Corporation
*
* 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/types.h>
#include <linux/cpufreq.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/cpumask.h>
#include <linux/smp.h>
#include <linux/sched.h> /* set_cpus_allowed() */
#include <linux/clk.h>
static struct clk *cpuclk;
static unsigned int sh_cpufreq_get(unsigned int cpu)
{
return (clk_get_rate(cpuclk) + 500) / 1000;
}
/*
* Here we notify other drivers of the proposed change and the final change.
*/
static int sh_cpufreq_target(struct cpufreq_policy *policy,
unsigned int target_freq,
unsigned int relation)
{
unsigned int cpu = policy->cpu;
cpumask_t cpus_allowed;
struct cpufreq_freqs freqs;
long freq;
if (!cpu_online(cpu))
return -ENODEV;
cpus_allowed = current->cpus_allowed;
set_cpus_allowed_ptr(current, cpumask_of(cpu));
BUG_ON(smp_processor_id() != cpu);
/* Convert target_freq from kHz to Hz */
freq = clk_round_rate(cpuclk, target_freq * 1000);
if (freq < (policy->min * 1000) || freq > (policy->max * 1000))
return -EINVAL;
pr_debug("cpufreq: requested frequency %u Hz\n", target_freq * 1000);
freqs.cpu = cpu;
freqs.old = sh_cpufreq_get(cpu);
freqs.new = (freq + 500) / 1000;
freqs.flags = 0;
cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE);
set_cpus_allowed_ptr(current, &cpus_allowed);
clk_set_rate(cpuclk, freq);
cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
pr_debug("cpufreq: set frequency %lu Hz\n", freq);
return 0;
}
static int sh_cpufreq_cpu_init(struct cpufreq_policy *policy)
{
if (!cpu_online(policy->cpu))
return -ENODEV;
cpuclk = clk_get(NULL, "cpu_clk");
if (IS_ERR(cpuclk)) {
printk(KERN_ERR "cpufreq: couldn't get CPU#%d clk\n",
policy->cpu);
return PTR_ERR(cpuclk);
}
/* cpuinfo and default policy values */
policy->cpuinfo.min_freq = (clk_round_rate(cpuclk, 1) + 500) / 1000;
policy->cpuinfo.max_freq = (clk_round_rate(cpuclk, ~0UL) + 500) / 1000;
policy->cpuinfo.transition_latency = CPUFREQ_ETERNAL;
policy->cur = sh_cpufreq_get(policy->cpu);
policy->min = policy->cpuinfo.min_freq;
policy->max = policy->cpuinfo.max_freq;
/*
* Catch the cases where the clock framework hasn't been wired up
* properly to support scaling.
*/
if (unlikely(policy->min == policy->max)) {
printk(KERN_ERR "cpufreq: clock framework rate rounding "
"not supported on CPU#%d.\n", policy->cpu);
clk_put(cpuclk);
return -EINVAL;
}
printk(KERN_INFO "cpufreq: CPU#%d Frequencies - Minimum %u.%03u MHz, "
"Maximum %u.%03u MHz.\n",
policy->cpu, policy->min / 1000, policy->min % 1000,
policy->max / 1000, policy->max % 1000);
return 0;
}
static int sh_cpufreq_verify(struct cpufreq_policy *policy)
{
cpufreq_verify_within_limits(policy, policy->cpuinfo.min_freq,
policy->cpuinfo.max_freq);
return 0;
}
static int sh_cpufreq_exit(struct cpufreq_policy *policy)
{
clk_put(cpuclk);
return 0;
}
static struct cpufreq_driver sh_cpufreq_driver = {
.owner = THIS_MODULE,
.name = "sh",
.init = sh_cpufreq_cpu_init,
.verify = sh_cpufreq_verify,
.target = sh_cpufreq_target,
.get = sh_cpufreq_get,
.exit = sh_cpufreq_exit,
};
static int __init sh_cpufreq_module_init(void)
{
printk(KERN_INFO "cpufreq: SuperH CPU frequency driver.\n");
return cpufreq_register_driver(&sh_cpufreq_driver);
}
static void __exit sh_cpufreq_module_exit(void)
{
cpufreq_unregister_driver(&sh_cpufreq_driver);
}
module_init(sh_cpufreq_module_init);
module_exit(sh_cpufreq_module_exit);
MODULE_AUTHOR("Paul Mundt <lethal@linux-sh.org>");
MODULE_DESCRIPTION("cpufreq driver for SuperH");
MODULE_LICENSE("GPL");
| gpl-2.0 |
estiko/android_kernel_lenovo_armani_row | drivers/net/team/team.c | 4044 | 39569 | /*
* net/drivers/team/team.c - Network team device driver
* Copyright (c) 2011 Jiri Pirko <jpirko@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/rcupdate.h>
#include <linux/errno.h>
#include <linux/ctype.h>
#include <linux/notifier.h>
#include <linux/netdevice.h>
#include <linux/if_vlan.h>
#include <linux/if_arp.h>
#include <linux/socket.h>
#include <linux/etherdevice.h>
#include <linux/rtnetlink.h>
#include <net/rtnetlink.h>
#include <net/genetlink.h>
#include <net/netlink.h>
#include <linux/if_team.h>
#define DRV_NAME "team"
/**********
* Helpers
**********/
#define team_port_exists(dev) (dev->priv_flags & IFF_TEAM_PORT)
static struct team_port *team_port_get_rcu(const struct net_device *dev)
{
struct team_port *port = rcu_dereference(dev->rx_handler_data);
return team_port_exists(dev) ? port : NULL;
}
static struct team_port *team_port_get_rtnl(const struct net_device *dev)
{
struct team_port *port = rtnl_dereference(dev->rx_handler_data);
return team_port_exists(dev) ? port : NULL;
}
/*
* Since the ability to change mac address for open port device is tested in
* team_port_add, this function can be called without control of return value
*/
static int __set_port_mac(struct net_device *port_dev,
const unsigned char *dev_addr)
{
struct sockaddr addr;
memcpy(addr.sa_data, dev_addr, ETH_ALEN);
addr.sa_family = ARPHRD_ETHER;
return dev_set_mac_address(port_dev, &addr);
}
int team_port_set_orig_mac(struct team_port *port)
{
return __set_port_mac(port->dev, port->orig.dev_addr);
}
int team_port_set_team_mac(struct team_port *port)
{
return __set_port_mac(port->dev, port->team->dev->dev_addr);
}
EXPORT_SYMBOL(team_port_set_team_mac);
/*******************
* Options handling
*******************/
struct team_option *__team_find_option(struct team *team, const char *opt_name)
{
struct team_option *option;
list_for_each_entry(option, &team->option_list, list) {
if (strcmp(option->name, opt_name) == 0)
return option;
}
return NULL;
}
int __team_options_register(struct team *team,
const struct team_option *option,
size_t option_count)
{
int i;
struct team_option **dst_opts;
int err;
dst_opts = kzalloc(sizeof(struct team_option *) * option_count,
GFP_KERNEL);
if (!dst_opts)
return -ENOMEM;
for (i = 0; i < option_count; i++, option++) {
if (__team_find_option(team, option->name)) {
err = -EEXIST;
goto rollback;
}
dst_opts[i] = kmemdup(option, sizeof(*option), GFP_KERNEL);
if (!dst_opts[i]) {
err = -ENOMEM;
goto rollback;
}
}
for (i = 0; i < option_count; i++) {
dst_opts[i]->changed = true;
dst_opts[i]->removed = false;
list_add_tail(&dst_opts[i]->list, &team->option_list);
}
kfree(dst_opts);
return 0;
rollback:
for (i = 0; i < option_count; i++)
kfree(dst_opts[i]);
kfree(dst_opts);
return err;
}
static void __team_options_mark_removed(struct team *team,
const struct team_option *option,
size_t option_count)
{
int i;
for (i = 0; i < option_count; i++, option++) {
struct team_option *del_opt;
del_opt = __team_find_option(team, option->name);
if (del_opt) {
del_opt->changed = true;
del_opt->removed = true;
}
}
}
static void __team_options_unregister(struct team *team,
const struct team_option *option,
size_t option_count)
{
int i;
for (i = 0; i < option_count; i++, option++) {
struct team_option *del_opt;
del_opt = __team_find_option(team, option->name);
if (del_opt) {
list_del(&del_opt->list);
kfree(del_opt);
}
}
}
static void __team_options_change_check(struct team *team);
int team_options_register(struct team *team,
const struct team_option *option,
size_t option_count)
{
int err;
err = __team_options_register(team, option, option_count);
if (err)
return err;
__team_options_change_check(team);
return 0;
}
EXPORT_SYMBOL(team_options_register);
void team_options_unregister(struct team *team,
const struct team_option *option,
size_t option_count)
{
__team_options_mark_removed(team, option, option_count);
__team_options_change_check(team);
__team_options_unregister(team, option, option_count);
}
EXPORT_SYMBOL(team_options_unregister);
static int team_option_get(struct team *team, struct team_option *option,
void *arg)
{
return option->getter(team, arg);
}
static int team_option_set(struct team *team, struct team_option *option,
void *arg)
{
int err;
err = option->setter(team, arg);
if (err)
return err;
option->changed = true;
__team_options_change_check(team);
return err;
}
/****************
* Mode handling
****************/
static LIST_HEAD(mode_list);
static DEFINE_SPINLOCK(mode_list_lock);
static struct team_mode *__find_mode(const char *kind)
{
struct team_mode *mode;
list_for_each_entry(mode, &mode_list, list) {
if (strcmp(mode->kind, kind) == 0)
return mode;
}
return NULL;
}
static bool is_good_mode_name(const char *name)
{
while (*name != '\0') {
if (!isalpha(*name) && !isdigit(*name) && *name != '_')
return false;
name++;
}
return true;
}
int team_mode_register(struct team_mode *mode)
{
int err = 0;
if (!is_good_mode_name(mode->kind) ||
mode->priv_size > TEAM_MODE_PRIV_SIZE)
return -EINVAL;
spin_lock(&mode_list_lock);
if (__find_mode(mode->kind)) {
err = -EEXIST;
goto unlock;
}
list_add_tail(&mode->list, &mode_list);
unlock:
spin_unlock(&mode_list_lock);
return err;
}
EXPORT_SYMBOL(team_mode_register);
int team_mode_unregister(struct team_mode *mode)
{
spin_lock(&mode_list_lock);
list_del_init(&mode->list);
spin_unlock(&mode_list_lock);
return 0;
}
EXPORT_SYMBOL(team_mode_unregister);
static struct team_mode *team_mode_get(const char *kind)
{
struct team_mode *mode;
spin_lock(&mode_list_lock);
mode = __find_mode(kind);
if (!mode) {
spin_unlock(&mode_list_lock);
request_module("team-mode-%s", kind);
spin_lock(&mode_list_lock);
mode = __find_mode(kind);
}
if (mode)
if (!try_module_get(mode->owner))
mode = NULL;
spin_unlock(&mode_list_lock);
return mode;
}
static void team_mode_put(const struct team_mode *mode)
{
module_put(mode->owner);
}
static bool team_dummy_transmit(struct team *team, struct sk_buff *skb)
{
dev_kfree_skb_any(skb);
return false;
}
rx_handler_result_t team_dummy_receive(struct team *team,
struct team_port *port,
struct sk_buff *skb)
{
return RX_HANDLER_ANOTHER;
}
static void team_adjust_ops(struct team *team)
{
/*
* To avoid checks in rx/tx skb paths, ensure here that non-null and
* correct ops are always set.
*/
if (list_empty(&team->port_list) ||
!team->mode || !team->mode->ops->transmit)
team->ops.transmit = team_dummy_transmit;
else
team->ops.transmit = team->mode->ops->transmit;
if (list_empty(&team->port_list) ||
!team->mode || !team->mode->ops->receive)
team->ops.receive = team_dummy_receive;
else
team->ops.receive = team->mode->ops->receive;
}
/*
* We can benefit from the fact that it's ensured no port is present
* at the time of mode change. Therefore no packets are in fly so there's no
* need to set mode operations in any special way.
*/
static int __team_change_mode(struct team *team,
const struct team_mode *new_mode)
{
/* Check if mode was previously set and do cleanup if so */
if (team->mode) {
void (*exit_op)(struct team *team) = team->ops.exit;
/* Clear ops area so no callback is called any longer */
memset(&team->ops, 0, sizeof(struct team_mode_ops));
team_adjust_ops(team);
if (exit_op)
exit_op(team);
team_mode_put(team->mode);
team->mode = NULL;
/* zero private data area */
memset(&team->mode_priv, 0,
sizeof(struct team) - offsetof(struct team, mode_priv));
}
if (!new_mode)
return 0;
if (new_mode->ops->init) {
int err;
err = new_mode->ops->init(team);
if (err)
return err;
}
team->mode = new_mode;
memcpy(&team->ops, new_mode->ops, sizeof(struct team_mode_ops));
team_adjust_ops(team);
return 0;
}
static int team_change_mode(struct team *team, const char *kind)
{
struct team_mode *new_mode;
struct net_device *dev = team->dev;
int err;
if (!list_empty(&team->port_list)) {
netdev_err(dev, "No ports can be present during mode change\n");
return -EBUSY;
}
if (team->mode && strcmp(team->mode->kind, kind) == 0) {
netdev_err(dev, "Unable to change to the same mode the team is in\n");
return -EINVAL;
}
new_mode = team_mode_get(kind);
if (!new_mode) {
netdev_err(dev, "Mode \"%s\" not found\n", kind);
return -EINVAL;
}
err = __team_change_mode(team, new_mode);
if (err) {
netdev_err(dev, "Failed to change to mode \"%s\"\n", kind);
team_mode_put(new_mode);
return err;
}
netdev_info(dev, "Mode changed to \"%s\"\n", kind);
return 0;
}
/************************
* Rx path frame handler
************************/
/* note: already called with rcu_read_lock */
static rx_handler_result_t team_handle_frame(struct sk_buff **pskb)
{
struct sk_buff *skb = *pskb;
struct team_port *port;
struct team *team;
rx_handler_result_t res;
skb = skb_share_check(skb, GFP_ATOMIC);
if (!skb)
return RX_HANDLER_CONSUMED;
*pskb = skb;
port = team_port_get_rcu(skb->dev);
team = port->team;
res = team->ops.receive(team, port, skb);
if (res == RX_HANDLER_ANOTHER) {
struct team_pcpu_stats *pcpu_stats;
pcpu_stats = this_cpu_ptr(team->pcpu_stats);
u64_stats_update_begin(&pcpu_stats->syncp);
pcpu_stats->rx_packets++;
pcpu_stats->rx_bytes += skb->len;
if (skb->pkt_type == PACKET_MULTICAST)
pcpu_stats->rx_multicast++;
u64_stats_update_end(&pcpu_stats->syncp);
skb->dev = team->dev;
} else {
this_cpu_inc(team->pcpu_stats->rx_dropped);
}
return res;
}
/****************
* Port handling
****************/
static bool team_port_find(const struct team *team,
const struct team_port *port)
{
struct team_port *cur;
list_for_each_entry(cur, &team->port_list, list)
if (cur == port)
return true;
return false;
}
/*
* Add/delete port to the team port list. Write guarded by rtnl_lock.
* Takes care of correct port->index setup (might be racy).
*/
static void team_port_list_add_port(struct team *team,
struct team_port *port)
{
port->index = team->port_count++;
hlist_add_head_rcu(&port->hlist,
team_port_index_hash(team, port->index));
list_add_tail_rcu(&port->list, &team->port_list);
}
static void __reconstruct_port_hlist(struct team *team, int rm_index)
{
int i;
struct team_port *port;
for (i = rm_index + 1; i < team->port_count; i++) {
port = team_get_port_by_index(team, i);
hlist_del_rcu(&port->hlist);
port->index--;
hlist_add_head_rcu(&port->hlist,
team_port_index_hash(team, port->index));
}
}
static void team_port_list_del_port(struct team *team,
struct team_port *port)
{
int rm_index = port->index;
hlist_del_rcu(&port->hlist);
list_del_rcu(&port->list);
__reconstruct_port_hlist(team, rm_index);
team->port_count--;
}
#define TEAM_VLAN_FEATURES (NETIF_F_ALL_CSUM | NETIF_F_SG | \
NETIF_F_FRAGLIST | NETIF_F_ALL_TSO | \
NETIF_F_HIGHDMA | NETIF_F_LRO)
static void __team_compute_features(struct team *team)
{
struct team_port *port;
u32 vlan_features = TEAM_VLAN_FEATURES;
unsigned short max_hard_header_len = ETH_HLEN;
list_for_each_entry(port, &team->port_list, list) {
vlan_features = netdev_increment_features(vlan_features,
port->dev->vlan_features,
TEAM_VLAN_FEATURES);
if (port->dev->hard_header_len > max_hard_header_len)
max_hard_header_len = port->dev->hard_header_len;
}
team->dev->vlan_features = vlan_features;
team->dev->hard_header_len = max_hard_header_len;
netdev_change_features(team->dev);
}
static void team_compute_features(struct team *team)
{
mutex_lock(&team->lock);
__team_compute_features(team);
mutex_unlock(&team->lock);
}
static int team_port_enter(struct team *team, struct team_port *port)
{
int err = 0;
dev_hold(team->dev);
port->dev->priv_flags |= IFF_TEAM_PORT;
if (team->ops.port_enter) {
err = team->ops.port_enter(team, port);
if (err) {
netdev_err(team->dev, "Device %s failed to enter team mode\n",
port->dev->name);
goto err_port_enter;
}
}
return 0;
err_port_enter:
port->dev->priv_flags &= ~IFF_TEAM_PORT;
dev_put(team->dev);
return err;
}
static void team_port_leave(struct team *team, struct team_port *port)
{
if (team->ops.port_leave)
team->ops.port_leave(team, port);
port->dev->priv_flags &= ~IFF_TEAM_PORT;
dev_put(team->dev);
}
static void __team_port_change_check(struct team_port *port, bool linkup);
static int team_port_add(struct team *team, struct net_device *port_dev)
{
struct net_device *dev = team->dev;
struct team_port *port;
char *portname = port_dev->name;
int err;
if (port_dev->flags & IFF_LOOPBACK ||
port_dev->type != ARPHRD_ETHER) {
netdev_err(dev, "Device %s is of an unsupported type\n",
portname);
return -EINVAL;
}
if (team_port_exists(port_dev)) {
netdev_err(dev, "Device %s is already a port "
"of a team device\n", portname);
return -EBUSY;
}
if (port_dev->flags & IFF_UP) {
netdev_err(dev, "Device %s is up. Set it down before adding it as a team port\n",
portname);
return -EBUSY;
}
port = kzalloc(sizeof(struct team_port), GFP_KERNEL);
if (!port)
return -ENOMEM;
port->dev = port_dev;
port->team = team;
port->orig.mtu = port_dev->mtu;
err = dev_set_mtu(port_dev, dev->mtu);
if (err) {
netdev_dbg(dev, "Error %d calling dev_set_mtu\n", err);
goto err_set_mtu;
}
memcpy(port->orig.dev_addr, port_dev->dev_addr, ETH_ALEN);
err = team_port_enter(team, port);
if (err) {
netdev_err(dev, "Device %s failed to enter team mode\n",
portname);
goto err_port_enter;
}
err = dev_open(port_dev);
if (err) {
netdev_dbg(dev, "Device %s opening failed\n",
portname);
goto err_dev_open;
}
err = vlan_vids_add_by_dev(port_dev, dev);
if (err) {
netdev_err(dev, "Failed to add vlan ids to device %s\n",
portname);
goto err_vids_add;
}
err = netdev_set_master(port_dev, dev);
if (err) {
netdev_err(dev, "Device %s failed to set master\n", portname);
goto err_set_master;
}
err = netdev_rx_handler_register(port_dev, team_handle_frame,
port);
if (err) {
netdev_err(dev, "Device %s failed to register rx_handler\n",
portname);
goto err_handler_register;
}
team_port_list_add_port(team, port);
team_adjust_ops(team);
__team_compute_features(team);
__team_port_change_check(port, !!netif_carrier_ok(port_dev));
netdev_info(dev, "Port device %s added\n", portname);
return 0;
err_handler_register:
netdev_set_master(port_dev, NULL);
err_set_master:
vlan_vids_del_by_dev(port_dev, dev);
err_vids_add:
dev_close(port_dev);
err_dev_open:
team_port_leave(team, port);
team_port_set_orig_mac(port);
err_port_enter:
dev_set_mtu(port_dev, port->orig.mtu);
err_set_mtu:
kfree(port);
return err;
}
static int team_port_del(struct team *team, struct net_device *port_dev)
{
struct net_device *dev = team->dev;
struct team_port *port;
char *portname = port_dev->name;
port = team_port_get_rtnl(port_dev);
if (!port || !team_port_find(team, port)) {
netdev_err(dev, "Device %s does not act as a port of this team\n",
portname);
return -ENOENT;
}
port->removed = true;
__team_port_change_check(port, false);
team_port_list_del_port(team, port);
team_adjust_ops(team);
netdev_rx_handler_unregister(port_dev);
netdev_set_master(port_dev, NULL);
vlan_vids_del_by_dev(port_dev, dev);
dev_close(port_dev);
team_port_leave(team, port);
team_port_set_orig_mac(port);
dev_set_mtu(port_dev, port->orig.mtu);
synchronize_rcu();
kfree(port);
netdev_info(dev, "Port device %s removed\n", portname);
__team_compute_features(team);
return 0;
}
/*****************
* Net device ops
*****************/
static const char team_no_mode_kind[] = "*NOMODE*";
static int team_mode_option_get(struct team *team, void *arg)
{
const char **str = arg;
*str = team->mode ? team->mode->kind : team_no_mode_kind;
return 0;
}
static int team_mode_option_set(struct team *team, void *arg)
{
const char **str = arg;
return team_change_mode(team, *str);
}
static const struct team_option team_options[] = {
{
.name = "mode",
.type = TEAM_OPTION_TYPE_STRING,
.getter = team_mode_option_get,
.setter = team_mode_option_set,
},
};
static int team_init(struct net_device *dev)
{
struct team *team = netdev_priv(dev);
int i;
int err;
team->dev = dev;
mutex_init(&team->lock);
team->pcpu_stats = alloc_percpu(struct team_pcpu_stats);
if (!team->pcpu_stats)
return -ENOMEM;
for (i = 0; i < TEAM_PORT_HASHENTRIES; i++)
INIT_HLIST_HEAD(&team->port_hlist[i]);
INIT_LIST_HEAD(&team->port_list);
team_adjust_ops(team);
INIT_LIST_HEAD(&team->option_list);
err = team_options_register(team, team_options, ARRAY_SIZE(team_options));
if (err)
goto err_options_register;
netif_carrier_off(dev);
return 0;
err_options_register:
free_percpu(team->pcpu_stats);
return err;
}
static void team_uninit(struct net_device *dev)
{
struct team *team = netdev_priv(dev);
struct team_port *port;
struct team_port *tmp;
mutex_lock(&team->lock);
list_for_each_entry_safe(port, tmp, &team->port_list, list)
team_port_del(team, port->dev);
__team_change_mode(team, NULL); /* cleanup */
__team_options_unregister(team, team_options, ARRAY_SIZE(team_options));
mutex_unlock(&team->lock);
}
static void team_destructor(struct net_device *dev)
{
struct team *team = netdev_priv(dev);
free_percpu(team->pcpu_stats);
free_netdev(dev);
}
static int team_open(struct net_device *dev)
{
netif_carrier_on(dev);
return 0;
}
static int team_close(struct net_device *dev)
{
netif_carrier_off(dev);
return 0;
}
/*
* note: already called with rcu_read_lock
*/
static netdev_tx_t team_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct team *team = netdev_priv(dev);
bool tx_success = false;
unsigned int len = skb->len;
tx_success = team->ops.transmit(team, skb);
if (tx_success) {
struct team_pcpu_stats *pcpu_stats;
pcpu_stats = this_cpu_ptr(team->pcpu_stats);
u64_stats_update_begin(&pcpu_stats->syncp);
pcpu_stats->tx_packets++;
pcpu_stats->tx_bytes += len;
u64_stats_update_end(&pcpu_stats->syncp);
} else {
this_cpu_inc(team->pcpu_stats->tx_dropped);
}
return NETDEV_TX_OK;
}
static void team_change_rx_flags(struct net_device *dev, int change)
{
struct team *team = netdev_priv(dev);
struct team_port *port;
int inc;
rcu_read_lock();
list_for_each_entry_rcu(port, &team->port_list, list) {
if (change & IFF_PROMISC) {
inc = dev->flags & IFF_PROMISC ? 1 : -1;
dev_set_promiscuity(port->dev, inc);
}
if (change & IFF_ALLMULTI) {
inc = dev->flags & IFF_ALLMULTI ? 1 : -1;
dev_set_allmulti(port->dev, inc);
}
}
rcu_read_unlock();
}
static void team_set_rx_mode(struct net_device *dev)
{
struct team *team = netdev_priv(dev);
struct team_port *port;
rcu_read_lock();
list_for_each_entry_rcu(port, &team->port_list, list) {
dev_uc_sync(port->dev, dev);
dev_mc_sync(port->dev, dev);
}
rcu_read_unlock();
}
static int team_set_mac_address(struct net_device *dev, void *p)
{
struct team *team = netdev_priv(dev);
struct team_port *port;
struct sockaddr *addr = p;
dev->addr_assign_type &= ~NET_ADDR_RANDOM;
memcpy(dev->dev_addr, addr->sa_data, ETH_ALEN);
rcu_read_lock();
list_for_each_entry_rcu(port, &team->port_list, list)
if (team->ops.port_change_mac)
team->ops.port_change_mac(team, port);
rcu_read_unlock();
return 0;
}
static int team_change_mtu(struct net_device *dev, int new_mtu)
{
struct team *team = netdev_priv(dev);
struct team_port *port;
int err;
/*
* Alhough this is reader, it's guarded by team lock. It's not possible
* to traverse list in reverse under rcu_read_lock
*/
mutex_lock(&team->lock);
list_for_each_entry(port, &team->port_list, list) {
err = dev_set_mtu(port->dev, new_mtu);
if (err) {
netdev_err(dev, "Device %s failed to change mtu",
port->dev->name);
goto unwind;
}
}
mutex_unlock(&team->lock);
dev->mtu = new_mtu;
return 0;
unwind:
list_for_each_entry_continue_reverse(port, &team->port_list, list)
dev_set_mtu(port->dev, dev->mtu);
mutex_unlock(&team->lock);
return err;
}
static struct rtnl_link_stats64 *
team_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats)
{
struct team *team = netdev_priv(dev);
struct team_pcpu_stats *p;
u64 rx_packets, rx_bytes, rx_multicast, tx_packets, tx_bytes;
u32 rx_dropped = 0, tx_dropped = 0;
unsigned int start;
int i;
for_each_possible_cpu(i) {
p = per_cpu_ptr(team->pcpu_stats, i);
do {
start = u64_stats_fetch_begin_bh(&p->syncp);
rx_packets = p->rx_packets;
rx_bytes = p->rx_bytes;
rx_multicast = p->rx_multicast;
tx_packets = p->tx_packets;
tx_bytes = p->tx_bytes;
} while (u64_stats_fetch_retry_bh(&p->syncp, start));
stats->rx_packets += rx_packets;
stats->rx_bytes += rx_bytes;
stats->multicast += rx_multicast;
stats->tx_packets += tx_packets;
stats->tx_bytes += tx_bytes;
/*
* rx_dropped & tx_dropped are u32, updated
* without syncp protection.
*/
rx_dropped += p->rx_dropped;
tx_dropped += p->tx_dropped;
}
stats->rx_dropped = rx_dropped;
stats->tx_dropped = tx_dropped;
return stats;
}
static int team_vlan_rx_add_vid(struct net_device *dev, uint16_t vid)
{
struct team *team = netdev_priv(dev);
struct team_port *port;
int err;
/*
* Alhough this is reader, it's guarded by team lock. It's not possible
* to traverse list in reverse under rcu_read_lock
*/
mutex_lock(&team->lock);
list_for_each_entry(port, &team->port_list, list) {
err = vlan_vid_add(port->dev, vid);
if (err)
goto unwind;
}
mutex_unlock(&team->lock);
return 0;
unwind:
list_for_each_entry_continue_reverse(port, &team->port_list, list)
vlan_vid_del(port->dev, vid);
mutex_unlock(&team->lock);
return err;
}
static int team_vlan_rx_kill_vid(struct net_device *dev, uint16_t vid)
{
struct team *team = netdev_priv(dev);
struct team_port *port;
rcu_read_lock();
list_for_each_entry_rcu(port, &team->port_list, list)
vlan_vid_del(port->dev, vid);
rcu_read_unlock();
return 0;
}
static int team_add_slave(struct net_device *dev, struct net_device *port_dev)
{
struct team *team = netdev_priv(dev);
int err;
mutex_lock(&team->lock);
err = team_port_add(team, port_dev);
mutex_unlock(&team->lock);
return err;
}
static int team_del_slave(struct net_device *dev, struct net_device *port_dev)
{
struct team *team = netdev_priv(dev);
int err;
mutex_lock(&team->lock);
err = team_port_del(team, port_dev);
mutex_unlock(&team->lock);
return err;
}
static netdev_features_t team_fix_features(struct net_device *dev,
netdev_features_t features)
{
struct team_port *port;
struct team *team = netdev_priv(dev);
netdev_features_t mask;
mask = features;
features &= ~NETIF_F_ONE_FOR_ALL;
features |= NETIF_F_ALL_FOR_ALL;
rcu_read_lock();
list_for_each_entry_rcu(port, &team->port_list, list) {
features = netdev_increment_features(features,
port->dev->features,
mask);
}
rcu_read_unlock();
return features;
}
static const struct net_device_ops team_netdev_ops = {
.ndo_init = team_init,
.ndo_uninit = team_uninit,
.ndo_open = team_open,
.ndo_stop = team_close,
.ndo_start_xmit = team_xmit,
.ndo_change_rx_flags = team_change_rx_flags,
.ndo_set_rx_mode = team_set_rx_mode,
.ndo_set_mac_address = team_set_mac_address,
.ndo_change_mtu = team_change_mtu,
.ndo_get_stats64 = team_get_stats64,
.ndo_vlan_rx_add_vid = team_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = team_vlan_rx_kill_vid,
.ndo_add_slave = team_add_slave,
.ndo_del_slave = team_del_slave,
.ndo_fix_features = team_fix_features,
};
/***********************
* rt netlink interface
***********************/
static void team_setup(struct net_device *dev)
{
ether_setup(dev);
dev->netdev_ops = &team_netdev_ops;
dev->destructor = team_destructor;
dev->tx_queue_len = 0;
dev->flags |= IFF_MULTICAST;
dev->priv_flags &= ~(IFF_XMIT_DST_RELEASE | IFF_TX_SKB_SHARING);
/*
* Indicate we support unicast address filtering. That way core won't
* bring us to promisc mode in case a unicast addr is added.
* Let this up to underlay drivers.
*/
dev->priv_flags |= IFF_UNICAST_FLT;
dev->features |= NETIF_F_LLTX;
dev->features |= NETIF_F_GRO;
dev->hw_features = NETIF_F_HW_VLAN_TX |
NETIF_F_HW_VLAN_RX |
NETIF_F_HW_VLAN_FILTER;
dev->features |= dev->hw_features;
}
static int team_newlink(struct net *src_net, struct net_device *dev,
struct nlattr *tb[], struct nlattr *data[])
{
int err;
if (tb[IFLA_ADDRESS] == NULL)
eth_hw_addr_random(dev);
err = register_netdevice(dev);
if (err)
return err;
return 0;
}
static int team_validate(struct nlattr *tb[], struct nlattr *data[])
{
if (tb[IFLA_ADDRESS]) {
if (nla_len(tb[IFLA_ADDRESS]) != ETH_ALEN)
return -EINVAL;
if (!is_valid_ether_addr(nla_data(tb[IFLA_ADDRESS])))
return -EADDRNOTAVAIL;
}
return 0;
}
static struct rtnl_link_ops team_link_ops __read_mostly = {
.kind = DRV_NAME,
.priv_size = sizeof(struct team),
.setup = team_setup,
.newlink = team_newlink,
.validate = team_validate,
};
/***********************************
* Generic netlink custom interface
***********************************/
static struct genl_family team_nl_family = {
.id = GENL_ID_GENERATE,
.name = TEAM_GENL_NAME,
.version = TEAM_GENL_VERSION,
.maxattr = TEAM_ATTR_MAX,
.netnsok = true,
};
static const struct nla_policy team_nl_policy[TEAM_ATTR_MAX + 1] = {
[TEAM_ATTR_UNSPEC] = { .type = NLA_UNSPEC, },
[TEAM_ATTR_TEAM_IFINDEX] = { .type = NLA_U32 },
[TEAM_ATTR_LIST_OPTION] = { .type = NLA_NESTED },
[TEAM_ATTR_LIST_PORT] = { .type = NLA_NESTED },
};
static const struct nla_policy
team_nl_option_policy[TEAM_ATTR_OPTION_MAX + 1] = {
[TEAM_ATTR_OPTION_UNSPEC] = { .type = NLA_UNSPEC, },
[TEAM_ATTR_OPTION_NAME] = {
.type = NLA_STRING,
.len = TEAM_STRING_MAX_LEN,
},
[TEAM_ATTR_OPTION_CHANGED] = { .type = NLA_FLAG },
[TEAM_ATTR_OPTION_TYPE] = { .type = NLA_U8 },
[TEAM_ATTR_OPTION_DATA] = {
.type = NLA_BINARY,
.len = TEAM_STRING_MAX_LEN,
},
};
static int team_nl_cmd_noop(struct sk_buff *skb, struct genl_info *info)
{
struct sk_buff *msg;
void *hdr;
int err;
msg = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = genlmsg_put(msg, info->snd_pid, info->snd_seq,
&team_nl_family, 0, TEAM_CMD_NOOP);
if (IS_ERR(hdr)) {
err = PTR_ERR(hdr);
goto err_msg_put;
}
genlmsg_end(msg, hdr);
return genlmsg_unicast(genl_info_net(info), msg, info->snd_pid);
err_msg_put:
nlmsg_free(msg);
return err;
}
/*
* Netlink cmd functions should be locked by following two functions.
* Since dev gets held here, that ensures dev won't disappear in between.
*/
static struct team *team_nl_team_get(struct genl_info *info)
{
struct net *net = genl_info_net(info);
int ifindex;
struct net_device *dev;
struct team *team;
if (!info->attrs[TEAM_ATTR_TEAM_IFINDEX])
return NULL;
ifindex = nla_get_u32(info->attrs[TEAM_ATTR_TEAM_IFINDEX]);
dev = dev_get_by_index(net, ifindex);
if (!dev || dev->netdev_ops != &team_netdev_ops) {
if (dev)
dev_put(dev);
return NULL;
}
team = netdev_priv(dev);
mutex_lock(&team->lock);
return team;
}
static void team_nl_team_put(struct team *team)
{
mutex_unlock(&team->lock);
dev_put(team->dev);
}
static int team_nl_send_generic(struct genl_info *info, struct team *team,
int (*fill_func)(struct sk_buff *skb,
struct genl_info *info,
int flags, struct team *team))
{
struct sk_buff *skb;
int err;
skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
if (!skb)
return -ENOMEM;
err = fill_func(skb, info, NLM_F_ACK, team);
if (err < 0)
goto err_fill;
err = genlmsg_unicast(genl_info_net(info), skb, info->snd_pid);
return err;
err_fill:
nlmsg_free(skb);
return err;
}
static int team_nl_fill_options_get(struct sk_buff *skb,
u32 pid, u32 seq, int flags,
struct team *team, bool fillall)
{
struct nlattr *option_list;
void *hdr;
struct team_option *option;
hdr = genlmsg_put(skb, pid, seq, &team_nl_family, flags,
TEAM_CMD_OPTIONS_GET);
if (IS_ERR(hdr))
return PTR_ERR(hdr);
NLA_PUT_U32(skb, TEAM_ATTR_TEAM_IFINDEX, team->dev->ifindex);
option_list = nla_nest_start(skb, TEAM_ATTR_LIST_OPTION);
if (!option_list)
return -EMSGSIZE;
list_for_each_entry(option, &team->option_list, list) {
struct nlattr *option_item;
long arg;
/* Include only changed options if fill all mode is not on */
if (!fillall && !option->changed)
continue;
option_item = nla_nest_start(skb, TEAM_ATTR_ITEM_OPTION);
if (!option_item)
goto nla_put_failure;
NLA_PUT_STRING(skb, TEAM_ATTR_OPTION_NAME, option->name);
if (option->changed) {
NLA_PUT_FLAG(skb, TEAM_ATTR_OPTION_CHANGED);
option->changed = false;
}
if (option->removed)
NLA_PUT_FLAG(skb, TEAM_ATTR_OPTION_REMOVED);
switch (option->type) {
case TEAM_OPTION_TYPE_U32:
NLA_PUT_U8(skb, TEAM_ATTR_OPTION_TYPE, NLA_U32);
team_option_get(team, option, &arg);
NLA_PUT_U32(skb, TEAM_ATTR_OPTION_DATA, arg);
break;
case TEAM_OPTION_TYPE_STRING:
NLA_PUT_U8(skb, TEAM_ATTR_OPTION_TYPE, NLA_STRING);
team_option_get(team, option, &arg);
NLA_PUT_STRING(skb, TEAM_ATTR_OPTION_DATA,
(char *) arg);
break;
default:
BUG();
}
nla_nest_end(skb, option_item);
}
nla_nest_end(skb, option_list);
return genlmsg_end(skb, hdr);
nla_put_failure:
genlmsg_cancel(skb, hdr);
return -EMSGSIZE;
}
static int team_nl_fill_options_get_all(struct sk_buff *skb,
struct genl_info *info, int flags,
struct team *team)
{
return team_nl_fill_options_get(skb, info->snd_pid,
info->snd_seq, NLM_F_ACK,
team, true);
}
static int team_nl_cmd_options_get(struct sk_buff *skb, struct genl_info *info)
{
struct team *team;
int err;
team = team_nl_team_get(info);
if (!team)
return -EINVAL;
err = team_nl_send_generic(info, team, team_nl_fill_options_get_all);
team_nl_team_put(team);
return err;
}
static int team_nl_cmd_options_set(struct sk_buff *skb, struct genl_info *info)
{
struct team *team;
int err = 0;
int i;
struct nlattr *nl_option;
team = team_nl_team_get(info);
if (!team)
return -EINVAL;
err = -EINVAL;
if (!info->attrs[TEAM_ATTR_LIST_OPTION]) {
err = -EINVAL;
goto team_put;
}
nla_for_each_nested(nl_option, info->attrs[TEAM_ATTR_LIST_OPTION], i) {
struct nlattr *mode_attrs[TEAM_ATTR_OPTION_MAX + 1];
enum team_option_type opt_type;
struct team_option *option;
char *opt_name;
bool opt_found = false;
if (nla_type(nl_option) != TEAM_ATTR_ITEM_OPTION) {
err = -EINVAL;
goto team_put;
}
err = nla_parse_nested(mode_attrs, TEAM_ATTR_OPTION_MAX,
nl_option, team_nl_option_policy);
if (err)
goto team_put;
if (!mode_attrs[TEAM_ATTR_OPTION_NAME] ||
!mode_attrs[TEAM_ATTR_OPTION_TYPE] ||
!mode_attrs[TEAM_ATTR_OPTION_DATA]) {
err = -EINVAL;
goto team_put;
}
switch (nla_get_u8(mode_attrs[TEAM_ATTR_OPTION_TYPE])) {
case NLA_U32:
opt_type = TEAM_OPTION_TYPE_U32;
break;
case NLA_STRING:
opt_type = TEAM_OPTION_TYPE_STRING;
break;
default:
goto team_put;
}
opt_name = nla_data(mode_attrs[TEAM_ATTR_OPTION_NAME]);
list_for_each_entry(option, &team->option_list, list) {
long arg;
struct nlattr *opt_data_attr;
if (option->type != opt_type ||
strcmp(option->name, opt_name))
continue;
opt_found = true;
opt_data_attr = mode_attrs[TEAM_ATTR_OPTION_DATA];
switch (opt_type) {
case TEAM_OPTION_TYPE_U32:
arg = nla_get_u32(opt_data_attr);
break;
case TEAM_OPTION_TYPE_STRING:
arg = (long) nla_data(opt_data_attr);
break;
default:
BUG();
}
err = team_option_set(team, option, &arg);
if (err)
goto team_put;
}
if (!opt_found) {
err = -ENOENT;
goto team_put;
}
}
team_put:
team_nl_team_put(team);
return err;
}
static int team_nl_fill_port_list_get(struct sk_buff *skb,
u32 pid, u32 seq, int flags,
struct team *team,
bool fillall)
{
struct nlattr *port_list;
void *hdr;
struct team_port *port;
hdr = genlmsg_put(skb, pid, seq, &team_nl_family, flags,
TEAM_CMD_PORT_LIST_GET);
if (IS_ERR(hdr))
return PTR_ERR(hdr);
NLA_PUT_U32(skb, TEAM_ATTR_TEAM_IFINDEX, team->dev->ifindex);
port_list = nla_nest_start(skb, TEAM_ATTR_LIST_PORT);
if (!port_list)
return -EMSGSIZE;
list_for_each_entry(port, &team->port_list, list) {
struct nlattr *port_item;
/* Include only changed ports if fill all mode is not on */
if (!fillall && !port->changed)
continue;
port_item = nla_nest_start(skb, TEAM_ATTR_ITEM_PORT);
if (!port_item)
goto nla_put_failure;
NLA_PUT_U32(skb, TEAM_ATTR_PORT_IFINDEX, port->dev->ifindex);
if (port->changed) {
NLA_PUT_FLAG(skb, TEAM_ATTR_PORT_CHANGED);
port->changed = false;
}
if (port->removed)
NLA_PUT_FLAG(skb, TEAM_ATTR_PORT_REMOVED);
if (port->linkup)
NLA_PUT_FLAG(skb, TEAM_ATTR_PORT_LINKUP);
NLA_PUT_U32(skb, TEAM_ATTR_PORT_SPEED, port->speed);
NLA_PUT_U8(skb, TEAM_ATTR_PORT_DUPLEX, port->duplex);
nla_nest_end(skb, port_item);
}
nla_nest_end(skb, port_list);
return genlmsg_end(skb, hdr);
nla_put_failure:
genlmsg_cancel(skb, hdr);
return -EMSGSIZE;
}
static int team_nl_fill_port_list_get_all(struct sk_buff *skb,
struct genl_info *info, int flags,
struct team *team)
{
return team_nl_fill_port_list_get(skb, info->snd_pid,
info->snd_seq, NLM_F_ACK,
team, true);
}
static int team_nl_cmd_port_list_get(struct sk_buff *skb,
struct genl_info *info)
{
struct team *team;
int err;
team = team_nl_team_get(info);
if (!team)
return -EINVAL;
err = team_nl_send_generic(info, team, team_nl_fill_port_list_get_all);
team_nl_team_put(team);
return err;
}
static struct genl_ops team_nl_ops[] = {
{
.cmd = TEAM_CMD_NOOP,
.doit = team_nl_cmd_noop,
.policy = team_nl_policy,
},
{
.cmd = TEAM_CMD_OPTIONS_SET,
.doit = team_nl_cmd_options_set,
.policy = team_nl_policy,
.flags = GENL_ADMIN_PERM,
},
{
.cmd = TEAM_CMD_OPTIONS_GET,
.doit = team_nl_cmd_options_get,
.policy = team_nl_policy,
.flags = GENL_ADMIN_PERM,
},
{
.cmd = TEAM_CMD_PORT_LIST_GET,
.doit = team_nl_cmd_port_list_get,
.policy = team_nl_policy,
.flags = GENL_ADMIN_PERM,
},
};
static struct genl_multicast_group team_change_event_mcgrp = {
.name = TEAM_GENL_CHANGE_EVENT_MC_GRP_NAME,
};
static int team_nl_send_event_options_get(struct team *team)
{
struct sk_buff *skb;
int err;
struct net *net = dev_net(team->dev);
skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
if (!skb)
return -ENOMEM;
err = team_nl_fill_options_get(skb, 0, 0, 0, team, false);
if (err < 0)
goto err_fill;
err = genlmsg_multicast_netns(net, skb, 0, team_change_event_mcgrp.id,
GFP_KERNEL);
return err;
err_fill:
nlmsg_free(skb);
return err;
}
static int team_nl_send_event_port_list_get(struct team *team)
{
struct sk_buff *skb;
int err;
struct net *net = dev_net(team->dev);
skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
if (!skb)
return -ENOMEM;
err = team_nl_fill_port_list_get(skb, 0, 0, 0, team, false);
if (err < 0)
goto err_fill;
err = genlmsg_multicast_netns(net, skb, 0, team_change_event_mcgrp.id,
GFP_KERNEL);
return err;
err_fill:
nlmsg_free(skb);
return err;
}
static int team_nl_init(void)
{
int err;
err = genl_register_family_with_ops(&team_nl_family, team_nl_ops,
ARRAY_SIZE(team_nl_ops));
if (err)
return err;
err = genl_register_mc_group(&team_nl_family, &team_change_event_mcgrp);
if (err)
goto err_change_event_grp_reg;
return 0;
err_change_event_grp_reg:
genl_unregister_family(&team_nl_family);
return err;
}
static void team_nl_fini(void)
{
genl_unregister_family(&team_nl_family);
}
/******************
* Change checkers
******************/
static void __team_options_change_check(struct team *team)
{
int err;
err = team_nl_send_event_options_get(team);
if (err)
netdev_warn(team->dev, "Failed to send options change via netlink\n");
}
/* rtnl lock is held */
static void __team_port_change_check(struct team_port *port, bool linkup)
{
int err;
if (!port->removed && port->linkup == linkup)
return;
port->changed = true;
port->linkup = linkup;
if (linkup) {
struct ethtool_cmd ecmd;
err = __ethtool_get_settings(port->dev, &ecmd);
if (!err) {
port->speed = ethtool_cmd_speed(&ecmd);
port->duplex = ecmd.duplex;
goto send_event;
}
}
port->speed = 0;
port->duplex = 0;
send_event:
err = team_nl_send_event_port_list_get(port->team);
if (err)
netdev_warn(port->team->dev, "Failed to send port change of device %s via netlink\n",
port->dev->name);
}
static void team_port_change_check(struct team_port *port, bool linkup)
{
struct team *team = port->team;
mutex_lock(&team->lock);
__team_port_change_check(port, linkup);
mutex_unlock(&team->lock);
}
/************************************
* Net device notifier event handler
************************************/
static int team_device_event(struct notifier_block *unused,
unsigned long event, void *ptr)
{
struct net_device *dev = (struct net_device *) ptr;
struct team_port *port;
port = team_port_get_rtnl(dev);
if (!port)
return NOTIFY_DONE;
switch (event) {
case NETDEV_UP:
if (netif_carrier_ok(dev))
team_port_change_check(port, true);
case NETDEV_DOWN:
team_port_change_check(port, false);
case NETDEV_CHANGE:
if (netif_running(port->dev))
team_port_change_check(port,
!!netif_carrier_ok(port->dev));
break;
case NETDEV_UNREGISTER:
team_del_slave(port->team->dev, dev);
break;
case NETDEV_FEAT_CHANGE:
team_compute_features(port->team);
break;
case NETDEV_CHANGEMTU:
/* Forbid to change mtu of underlaying device */
return NOTIFY_BAD;
case NETDEV_PRE_TYPE_CHANGE:
/* Forbid to change type of underlaying device */
return NOTIFY_BAD;
}
return NOTIFY_DONE;
}
static struct notifier_block team_notifier_block __read_mostly = {
.notifier_call = team_device_event,
};
/***********************
* Module init and exit
***********************/
static int __init team_module_init(void)
{
int err;
register_netdevice_notifier(&team_notifier_block);
err = rtnl_link_register(&team_link_ops);
if (err)
goto err_rtnl_reg;
err = team_nl_init();
if (err)
goto err_nl_init;
return 0;
err_nl_init:
rtnl_link_unregister(&team_link_ops);
err_rtnl_reg:
unregister_netdevice_notifier(&team_notifier_block);
return err;
}
static void __exit team_module_exit(void)
{
team_nl_fini();
rtnl_link_unregister(&team_link_ops);
unregister_netdevice_notifier(&team_notifier_block);
}
module_init(team_module_init);
module_exit(team_module_exit);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Jiri Pirko <jpirko@redhat.com>");
MODULE_DESCRIPTION("Ethernet team device driver");
MODULE_ALIAS_RTNL_LINK(DRV_NAME);
| gpl-2.0 |
davidmueller13/kernel_lt03lte_twv2_5.1.1 | arch/arm/mach-omap2/timer.c | 4556 | 13221 | /*
* linux/arch/arm/mach-omap2/timer.c
*
* OMAP2 GP timer support.
*
* Copyright (C) 2009 Nokia Corporation
*
* Update to use new clocksource/clockevent layers
* Author: Kevin Hilman, MontaVista Software, Inc. <source@mvista.com>
* Copyright (C) 2007 MontaVista Software, Inc.
*
* Original driver:
* Copyright (C) 2005 Nokia Corporation
* Author: Paul Mundt <paul.mundt@nokia.com>
* Juha Yrjölä <juha.yrjola@nokia.com>
* OMAP Dual-mode timer framework support by Timo Teras
*
* Some parts based off of TI's 24xx code:
*
* Copyright (C) 2004-2009 Texas Instruments, Inc.
*
* Roughly modelled after the OMAP1 MPU timer code.
* Added OMAP4 support - Santosh Shilimkar <santosh.shilimkar@ti.com>
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/time.h>
#include <linux/interrupt.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/clocksource.h>
#include <linux/clockchips.h>
#include <linux/slab.h>
#include <asm/mach/time.h>
#include <plat/dmtimer.h>
#include <asm/smp_twd.h>
#include <asm/sched_clock.h>
#include "common.h"
#include <plat/omap_hwmod.h>
#include <plat/omap_device.h>
#include <plat/omap-pm.h>
#include "powerdomain.h"
/* Parent clocks, eventually these will come from the clock framework */
#define OMAP2_MPU_SOURCE "sys_ck"
#define OMAP3_MPU_SOURCE OMAP2_MPU_SOURCE
#define OMAP4_MPU_SOURCE "sys_clkin_ck"
#define OMAP2_32K_SOURCE "func_32k_ck"
#define OMAP3_32K_SOURCE "omap_32k_fck"
#define OMAP4_32K_SOURCE "sys_32k_ck"
#ifdef CONFIG_OMAP_32K_TIMER
#define OMAP2_CLKEV_SOURCE OMAP2_32K_SOURCE
#define OMAP3_CLKEV_SOURCE OMAP3_32K_SOURCE
#define OMAP4_CLKEV_SOURCE OMAP4_32K_SOURCE
#define OMAP3_SECURE_TIMER 12
#else
#define OMAP2_CLKEV_SOURCE OMAP2_MPU_SOURCE
#define OMAP3_CLKEV_SOURCE OMAP3_MPU_SOURCE
#define OMAP4_CLKEV_SOURCE OMAP4_MPU_SOURCE
#define OMAP3_SECURE_TIMER 1
#endif
/* MAX_GPTIMER_ID: number of GPTIMERs on the chip */
#define MAX_GPTIMER_ID 12
static u32 sys_timer_reserved;
/* Clockevent code */
static struct omap_dm_timer clkev;
static struct clock_event_device clockevent_gpt;
static irqreturn_t omap2_gp_timer_interrupt(int irq, void *dev_id)
{
struct clock_event_device *evt = &clockevent_gpt;
__omap_dm_timer_write_status(&clkev, OMAP_TIMER_INT_OVERFLOW);
evt->event_handler(evt);
return IRQ_HANDLED;
}
static struct irqaction omap2_gp_timer_irq = {
.name = "gp timer",
.flags = IRQF_DISABLED | IRQF_TIMER | IRQF_IRQPOLL,
.handler = omap2_gp_timer_interrupt,
};
static int omap2_gp_timer_set_next_event(unsigned long cycles,
struct clock_event_device *evt)
{
__omap_dm_timer_load_start(&clkev, OMAP_TIMER_CTRL_ST,
0xffffffff - cycles, 1);
return 0;
}
static void omap2_gp_timer_set_mode(enum clock_event_mode mode,
struct clock_event_device *evt)
{
u32 period;
__omap_dm_timer_stop(&clkev, 1, clkev.rate);
switch (mode) {
case CLOCK_EVT_MODE_PERIODIC:
period = clkev.rate / HZ;
period -= 1;
/* Looks like we need to first set the load value separately */
__omap_dm_timer_write(&clkev, OMAP_TIMER_LOAD_REG,
0xffffffff - period, 1);
__omap_dm_timer_load_start(&clkev,
OMAP_TIMER_CTRL_AR | OMAP_TIMER_CTRL_ST,
0xffffffff - period, 1);
break;
case CLOCK_EVT_MODE_ONESHOT:
break;
case CLOCK_EVT_MODE_UNUSED:
case CLOCK_EVT_MODE_SHUTDOWN:
case CLOCK_EVT_MODE_RESUME:
break;
}
}
static struct clock_event_device clockevent_gpt = {
.name = "gp timer",
.features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT,
.shift = 32,
.set_next_event = omap2_gp_timer_set_next_event,
.set_mode = omap2_gp_timer_set_mode,
};
static int __init omap_dm_timer_init_one(struct omap_dm_timer *timer,
int gptimer_id,
const char *fck_source)
{
char name[10]; /* 10 = sizeof("gptXX_Xck0") */
struct omap_hwmod *oh;
size_t size;
int res = 0;
sprintf(name, "timer%d", gptimer_id);
omap_hwmod_setup_one(name);
oh = omap_hwmod_lookup(name);
if (!oh)
return -ENODEV;
timer->irq = oh->mpu_irqs[0].irq;
timer->phys_base = oh->slaves[0]->addr->pa_start;
size = oh->slaves[0]->addr->pa_end - timer->phys_base;
/* Static mapping, never released */
timer->io_base = ioremap(timer->phys_base, size);
if (!timer->io_base)
return -ENXIO;
/* After the dmtimer is using hwmod these clocks won't be needed */
sprintf(name, "gpt%d_fck", gptimer_id);
timer->fclk = clk_get(NULL, name);
if (IS_ERR(timer->fclk))
return -ENODEV;
sprintf(name, "gpt%d_ick", gptimer_id);
timer->iclk = clk_get(NULL, name);
if (IS_ERR(timer->iclk)) {
clk_put(timer->fclk);
return -ENODEV;
}
omap_hwmod_enable(oh);
sys_timer_reserved |= (1 << (gptimer_id - 1));
if (gptimer_id != 12) {
struct clk *src;
src = clk_get(NULL, fck_source);
if (IS_ERR(src)) {
res = -EINVAL;
} else {
res = __omap_dm_timer_set_source(timer->fclk, src);
if (IS_ERR_VALUE(res))
pr_warning("%s: timer%i cannot set source\n",
__func__, gptimer_id);
clk_put(src);
}
}
__omap_dm_timer_init_regs(timer);
__omap_dm_timer_reset(timer, 1, 1);
timer->posted = 1;
timer->rate = clk_get_rate(timer->fclk);
timer->reserved = 1;
return res;
}
static void __init omap2_gp_clockevent_init(int gptimer_id,
const char *fck_source)
{
int res;
res = omap_dm_timer_init_one(&clkev, gptimer_id, fck_source);
BUG_ON(res);
omap2_gp_timer_irq.dev_id = (void *)&clkev;
setup_irq(clkev.irq, &omap2_gp_timer_irq);
__omap_dm_timer_int_enable(&clkev, OMAP_TIMER_INT_OVERFLOW);
clockevent_gpt.mult = div_sc(clkev.rate, NSEC_PER_SEC,
clockevent_gpt.shift);
clockevent_gpt.max_delta_ns =
clockevent_delta2ns(0xffffffff, &clockevent_gpt);
clockevent_gpt.min_delta_ns =
clockevent_delta2ns(3, &clockevent_gpt);
/* Timer internal resynch latency. */
clockevent_gpt.cpumask = cpumask_of(0);
clockevents_register_device(&clockevent_gpt);
pr_info("OMAP clockevent source: GPTIMER%d at %lu Hz\n",
gptimer_id, clkev.rate);
}
/* Clocksource code */
#ifdef CONFIG_OMAP_32K_TIMER
/*
* When 32k-timer is enabled, don't use GPTimer for clocksource
* instead, just leave default clocksource which uses the 32k
* sync counter. See clocksource setup in plat-omap/counter_32k.c
*/
static void __init omap2_gp_clocksource_init(int unused, const char *dummy)
{
omap_init_clocksource_32k();
}
#else
static struct omap_dm_timer clksrc;
/*
* clocksource
*/
static cycle_t clocksource_read_cycles(struct clocksource *cs)
{
return (cycle_t)__omap_dm_timer_read_counter(&clksrc, 1);
}
static struct clocksource clocksource_gpt = {
.name = "gp timer",
.rating = 300,
.read = clocksource_read_cycles,
.mask = CLOCKSOURCE_MASK(32),
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
static u32 notrace dmtimer_read_sched_clock(void)
{
if (clksrc.reserved)
return __omap_dm_timer_read_counter(&clksrc, 1);
return 0;
}
/* Setup free-running counter for clocksource */
static void __init omap2_gp_clocksource_init(int gptimer_id,
const char *fck_source)
{
int res;
res = omap_dm_timer_init_one(&clksrc, gptimer_id, fck_source);
BUG_ON(res);
pr_info("OMAP clocksource: GPTIMER%d at %lu Hz\n",
gptimer_id, clksrc.rate);
__omap_dm_timer_load_start(&clksrc,
OMAP_TIMER_CTRL_ST | OMAP_TIMER_CTRL_AR, 0, 1);
setup_sched_clock(dmtimer_read_sched_clock, 32, clksrc.rate);
if (clocksource_register_hz(&clocksource_gpt, clksrc.rate))
pr_err("Could not register clocksource %s\n",
clocksource_gpt.name);
}
#endif
#define OMAP_SYS_TIMER_INIT(name, clkev_nr, clkev_src, \
clksrc_nr, clksrc_src) \
static void __init omap##name##_timer_init(void) \
{ \
omap2_gp_clockevent_init((clkev_nr), clkev_src); \
omap2_gp_clocksource_init((clksrc_nr), clksrc_src); \
}
#define OMAP_SYS_TIMER(name) \
struct sys_timer omap##name##_timer = { \
.init = omap##name##_timer_init, \
};
#ifdef CONFIG_ARCH_OMAP2
OMAP_SYS_TIMER_INIT(2, 1, OMAP2_CLKEV_SOURCE, 2, OMAP2_MPU_SOURCE)
OMAP_SYS_TIMER(2)
#endif
#ifdef CONFIG_ARCH_OMAP3
OMAP_SYS_TIMER_INIT(3, 1, OMAP3_CLKEV_SOURCE, 2, OMAP3_MPU_SOURCE)
OMAP_SYS_TIMER(3)
OMAP_SYS_TIMER_INIT(3_secure, OMAP3_SECURE_TIMER, OMAP3_CLKEV_SOURCE,
2, OMAP3_MPU_SOURCE)
OMAP_SYS_TIMER(3_secure)
#endif
#ifdef CONFIG_ARCH_OMAP4
#ifdef CONFIG_LOCAL_TIMERS
static DEFINE_TWD_LOCAL_TIMER(twd_local_timer,
OMAP44XX_LOCAL_TWD_BASE,
OMAP44XX_IRQ_LOCALTIMER);
#endif
static void __init omap4_timer_init(void)
{
omap2_gp_clockevent_init(1, OMAP4_CLKEV_SOURCE);
omap2_gp_clocksource_init(2, OMAP4_MPU_SOURCE);
#ifdef CONFIG_LOCAL_TIMERS
/* Local timers are not supprted on OMAP4430 ES1.0 */
if (omap_rev() != OMAP4430_REV_ES1_0) {
int err;
err = twd_local_timer_register(&twd_local_timer);
if (err)
pr_err("twd_local_timer_register failed %d\n", err);
}
#endif
}
OMAP_SYS_TIMER(4)
#endif
/**
* omap2_dm_timer_set_src - change the timer input clock source
* @pdev: timer platform device pointer
* @source: array index of parent clock source
*/
static int omap2_dm_timer_set_src(struct platform_device *pdev, int source)
{
int ret;
struct dmtimer_platform_data *pdata = pdev->dev.platform_data;
struct clk *fclk, *parent;
char *parent_name = NULL;
fclk = clk_get(&pdev->dev, "fck");
if (IS_ERR_OR_NULL(fclk)) {
dev_err(&pdev->dev, "%s: %d: clk_get() FAILED\n",
__func__, __LINE__);
return -EINVAL;
}
switch (source) {
case OMAP_TIMER_SRC_SYS_CLK:
parent_name = "sys_ck";
break;
case OMAP_TIMER_SRC_32_KHZ:
parent_name = "32k_ck";
break;
case OMAP_TIMER_SRC_EXT_CLK:
if (pdata->timer_ip_version == OMAP_TIMER_IP_VERSION_1) {
parent_name = "alt_ck";
break;
}
dev_err(&pdev->dev, "%s: %d: invalid clk src.\n",
__func__, __LINE__);
clk_put(fclk);
return -EINVAL;
}
parent = clk_get(&pdev->dev, parent_name);
if (IS_ERR_OR_NULL(parent)) {
dev_err(&pdev->dev, "%s: %d: clk_get() %s FAILED\n",
__func__, __LINE__, parent_name);
clk_put(fclk);
return -EINVAL;
}
ret = clk_set_parent(fclk, parent);
if (IS_ERR_VALUE(ret)) {
dev_err(&pdev->dev, "%s: clk_set_parent() to %s FAILED\n",
__func__, parent_name);
ret = -EINVAL;
}
clk_put(parent);
clk_put(fclk);
return ret;
}
/**
* omap_timer_init - build and register timer device with an
* associated timer hwmod
* @oh: timer hwmod pointer to be used to build timer device
* @user: parameter that can be passed from calling hwmod API
*
* Called by omap_hwmod_for_each_by_class to register each of the timer
* devices present in the system. The number of timer devices is known
* by parsing through the hwmod database for a given class name. At the
* end of function call memory is allocated for timer device and it is
* registered to the framework ready to be proved by the driver.
*/
static int __init omap_timer_init(struct omap_hwmod *oh, void *unused)
{
int id;
int ret = 0;
char *name = "omap_timer";
struct dmtimer_platform_data *pdata;
struct platform_device *pdev;
struct omap_timer_capability_dev_attr *timer_dev_attr;
struct powerdomain *pwrdm;
pr_debug("%s: %s\n", __func__, oh->name);
/* on secure device, do not register secure timer */
timer_dev_attr = oh->dev_attr;
if (omap_type() != OMAP2_DEVICE_TYPE_GP && timer_dev_attr)
if (timer_dev_attr->timer_capability == OMAP_TIMER_SECURE)
return ret;
pdata = kzalloc(sizeof(*pdata), GFP_KERNEL);
if (!pdata) {
pr_err("%s: No memory for [%s]\n", __func__, oh->name);
return -ENOMEM;
}
/*
* Extract the IDs from name field in hwmod database
* and use the same for constructing ids' for the
* timer devices. In a way, we are avoiding usage of
* static variable witin the function to do the same.
* CAUTION: We have to be careful and make sure the
* name in hwmod database does not change in which case
* we might either make corresponding change here or
* switch back static variable mechanism.
*/
sscanf(oh->name, "timer%2d", &id);
pdata->set_timer_src = omap2_dm_timer_set_src;
pdata->timer_ip_version = oh->class->rev;
/* Mark clocksource and clockevent timers as reserved */
if ((sys_timer_reserved >> (id - 1)) & 0x1)
pdata->reserved = 1;
pwrdm = omap_hwmod_get_pwrdm(oh);
pdata->loses_context = pwrdm_can_ever_lose_context(pwrdm);
#ifdef CONFIG_PM
pdata->get_context_loss_count = omap_pm_get_dev_context_loss_count;
#endif
pdev = omap_device_build(name, id, oh, pdata, sizeof(*pdata),
NULL, 0, 0);
if (IS_ERR(pdev)) {
pr_err("%s: Can't build omap_device for %s: %s.\n",
__func__, name, oh->name);
ret = -EINVAL;
}
kfree(pdata);
return ret;
}
/**
* omap2_dm_timer_init - top level regular device initialization
*
* Uses dedicated hwmod api to parse through hwmod database for
* given class name and then build and register the timer device.
*/
static int __init omap2_dm_timer_init(void)
{
int ret;
ret = omap_hwmod_for_each_by_class("timer", omap_timer_init, NULL);
if (unlikely(ret)) {
pr_err("%s: device registration failed.\n", __func__);
return -EINVAL;
}
return 0;
}
arch_initcall(omap2_dm_timer_init);
| gpl-2.0 |
vinay94185vinay/Hybrid | drivers/net/ethernet/amd/ariadne.c | 4812 | 22283 | /*
* Amiga Linux/m68k Ariadne Ethernet Driver
*
* © Copyright 1995-2003 by Geert Uytterhoeven (geert@linux-m68k.org)
* Peter De Schrijver (p2@mind.be)
*
* ---------------------------------------------------------------------------
*
* This program is based on
*
* lance.c: An AMD LANCE ethernet driver for linux.
* Written 1993-94 by Donald Becker.
*
* Am79C960: PCnet(tm)-ISA Single-Chip Ethernet Controller
* Advanced Micro Devices
* Publication #16907, Rev. B, Amendment/0, May 1994
*
* MC68230: Parallel Interface/Timer (PI/T)
* Motorola Semiconductors, December, 1983
*
* ---------------------------------------------------------------------------
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of the Linux
* distribution for more details.
*
* ---------------------------------------------------------------------------
*
* The Ariadne is a Zorro-II board made by Village Tronic. It contains:
*
* - an Am79C960 PCnet-ISA Single-Chip Ethernet Controller with both
* 10BASE-2 (thin coax) and 10BASE-T (UTP) connectors
*
* - an MC68230 Parallel Interface/Timer configured as 2 parallel ports
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
/*#define DEBUG*/
#include <linux/module.h>
#include <linux/stddef.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/interrupt.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/zorro.h>
#include <linux/bitops.h>
#include <asm/amigaints.h>
#include <asm/amigahw.h>
#include <asm/irq.h>
#include "ariadne.h"
#ifdef ARIADNE_DEBUG
int ariadne_debug = ARIADNE_DEBUG;
#else
int ariadne_debug = 1;
#endif
/* Macros to Fix Endianness problems */
/* Swap the Bytes in a WORD */
#define swapw(x) (((x >> 8) & 0x00ff) | ((x << 8) & 0xff00))
/* Get the Low BYTE in a WORD */
#define lowb(x) (x & 0xff)
/* Get the Swapped High WORD in a LONG */
#define swhighw(x) ((((x) >> 8) & 0xff00) | (((x) >> 24) & 0x00ff))
/* Get the Swapped Low WORD in a LONG */
#define swloww(x) ((((x) << 8) & 0xff00) | (((x) >> 8) & 0x00ff))
/* Transmit/Receive Ring Definitions */
#define TX_RING_SIZE 5
#define RX_RING_SIZE 16
#define PKT_BUF_SIZE 1520
/* Private Device Data */
struct ariadne_private {
volatile struct TDRE *tx_ring[TX_RING_SIZE];
volatile struct RDRE *rx_ring[RX_RING_SIZE];
volatile u_short *tx_buff[TX_RING_SIZE];
volatile u_short *rx_buff[RX_RING_SIZE];
int cur_tx, cur_rx; /* The next free ring entry */
int dirty_tx; /* The ring entries to be free()ed */
char tx_full;
};
/* Structure Created in the Ariadne's RAM Buffer */
struct lancedata {
struct TDRE tx_ring[TX_RING_SIZE];
struct RDRE rx_ring[RX_RING_SIZE];
u_short tx_buff[TX_RING_SIZE][PKT_BUF_SIZE / sizeof(u_short)];
u_short rx_buff[RX_RING_SIZE][PKT_BUF_SIZE / sizeof(u_short)];
};
static void memcpyw(volatile u_short *dest, u_short *src, int len)
{
while (len >= 2) {
*(dest++) = *(src++);
len -= 2;
}
if (len == 1)
*dest = (*(u_char *)src) << 8;
}
static void ariadne_init_ring(struct net_device *dev)
{
struct ariadne_private *priv = netdev_priv(dev);
volatile struct lancedata *lancedata = (struct lancedata *)dev->mem_start;
int i;
netif_stop_queue(dev);
priv->tx_full = 0;
priv->cur_rx = priv->cur_tx = 0;
priv->dirty_tx = 0;
/* Set up TX Ring */
for (i = 0; i < TX_RING_SIZE; i++) {
volatile struct TDRE *t = &lancedata->tx_ring[i];
t->TMD0 = swloww(ARIADNE_RAM +
offsetof(struct lancedata, tx_buff[i]));
t->TMD1 = swhighw(ARIADNE_RAM +
offsetof(struct lancedata, tx_buff[i])) |
TF_STP | TF_ENP;
t->TMD2 = swapw((u_short)-PKT_BUF_SIZE);
t->TMD3 = 0;
priv->tx_ring[i] = &lancedata->tx_ring[i];
priv->tx_buff[i] = lancedata->tx_buff[i];
netdev_dbg(dev, "TX Entry %2d at %p, Buf at %p\n",
i, &lancedata->tx_ring[i], lancedata->tx_buff[i]);
}
/* Set up RX Ring */
for (i = 0; i < RX_RING_SIZE; i++) {
volatile struct RDRE *r = &lancedata->rx_ring[i];
r->RMD0 = swloww(ARIADNE_RAM +
offsetof(struct lancedata, rx_buff[i]));
r->RMD1 = swhighw(ARIADNE_RAM +
offsetof(struct lancedata, rx_buff[i])) |
RF_OWN;
r->RMD2 = swapw((u_short)-PKT_BUF_SIZE);
r->RMD3 = 0x0000;
priv->rx_ring[i] = &lancedata->rx_ring[i];
priv->rx_buff[i] = lancedata->rx_buff[i];
netdev_dbg(dev, "RX Entry %2d at %p, Buf at %p\n",
i, &lancedata->rx_ring[i], lancedata->rx_buff[i]);
}
}
static int ariadne_rx(struct net_device *dev)
{
struct ariadne_private *priv = netdev_priv(dev);
int entry = priv->cur_rx % RX_RING_SIZE;
int i;
/* If we own the next entry, it's a new packet. Send it up */
while (!(lowb(priv->rx_ring[entry]->RMD1) & RF_OWN)) {
int status = lowb(priv->rx_ring[entry]->RMD1);
if (status != (RF_STP | RF_ENP)) { /* There was an error */
/* There is a tricky error noted by
* John Murphy <murf@perftech.com> to Russ Nelson:
* Even with full-sized buffers it's possible for a
* jabber packet to use two buffers, with only the
* last correctly noting the error
*/
/* Only count a general error at the end of a packet */
if (status & RF_ENP)
dev->stats.rx_errors++;
if (status & RF_FRAM)
dev->stats.rx_frame_errors++;
if (status & RF_OFLO)
dev->stats.rx_over_errors++;
if (status & RF_CRC)
dev->stats.rx_crc_errors++;
if (status & RF_BUFF)
dev->stats.rx_fifo_errors++;
priv->rx_ring[entry]->RMD1 &= 0xff00 | RF_STP | RF_ENP;
} else {
/* Malloc up new buffer, compatible with net-3 */
short pkt_len = swapw(priv->rx_ring[entry]->RMD3);
struct sk_buff *skb;
skb = netdev_alloc_skb(dev, pkt_len + 2);
if (skb == NULL) {
netdev_warn(dev, "Memory squeeze, deferring packet\n");
for (i = 0; i < RX_RING_SIZE; i++)
if (lowb(priv->rx_ring[(entry + i) % RX_RING_SIZE]->RMD1) & RF_OWN)
break;
if (i > RX_RING_SIZE - 2) {
dev->stats.rx_dropped++;
priv->rx_ring[entry]->RMD1 |= RF_OWN;
priv->cur_rx++;
}
break;
}
skb_reserve(skb, 2); /* 16 byte align */
skb_put(skb, pkt_len); /* Make room */
skb_copy_to_linear_data(skb,
(const void *)priv->rx_buff[entry],
pkt_len);
skb->protocol = eth_type_trans(skb, dev);
netdev_dbg(dev, "RX pkt type 0x%04x from %pM to %pM data 0x%08x len %d\n",
((u_short *)skb->data)[6],
skb->data + 6, skb->data,
(int)skb->data, (int)skb->len);
netif_rx(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += pkt_len;
}
priv->rx_ring[entry]->RMD1 |= RF_OWN;
entry = (++priv->cur_rx) % RX_RING_SIZE;
}
priv->cur_rx = priv->cur_rx % RX_RING_SIZE;
/* We should check that at least two ring entries are free.
* If not, we should free one and mark stats->rx_dropped++
*/
return 0;
}
static irqreturn_t ariadne_interrupt(int irq, void *data)
{
struct net_device *dev = (struct net_device *)data;
volatile struct Am79C960 *lance = (struct Am79C960 *)dev->base_addr;
struct ariadne_private *priv;
int csr0, boguscnt;
int handled = 0;
lance->RAP = CSR0; /* PCnet-ISA Controller Status */
if (!(lance->RDP & INTR)) /* Check if any interrupt has been */
return IRQ_NONE; /* generated by the board */
priv = netdev_priv(dev);
boguscnt = 10;
while ((csr0 = lance->RDP) & (ERR | RINT | TINT) && --boguscnt >= 0) {
/* Acknowledge all of the current interrupt sources ASAP */
lance->RDP = csr0 & ~(INEA | TDMD | STOP | STRT | INIT);
#ifdef DEBUG
if (ariadne_debug > 5) {
netdev_dbg(dev, "interrupt csr0=%#02x new csr=%#02x [",
csr0, lance->RDP);
if (csr0 & INTR)
pr_cont(" INTR");
if (csr0 & INEA)
pr_cont(" INEA");
if (csr0 & RXON)
pr_cont(" RXON");
if (csr0 & TXON)
pr_cont(" TXON");
if (csr0 & TDMD)
pr_cont(" TDMD");
if (csr0 & STOP)
pr_cont(" STOP");
if (csr0 & STRT)
pr_cont(" STRT");
if (csr0 & INIT)
pr_cont(" INIT");
if (csr0 & ERR)
pr_cont(" ERR");
if (csr0 & BABL)
pr_cont(" BABL");
if (csr0 & CERR)
pr_cont(" CERR");
if (csr0 & MISS)
pr_cont(" MISS");
if (csr0 & MERR)
pr_cont(" MERR");
if (csr0 & RINT)
pr_cont(" RINT");
if (csr0 & TINT)
pr_cont(" TINT");
if (csr0 & IDON)
pr_cont(" IDON");
pr_cont(" ]\n");
}
#endif
if (csr0 & RINT) { /* Rx interrupt */
handled = 1;
ariadne_rx(dev);
}
if (csr0 & TINT) { /* Tx-done interrupt */
int dirty_tx = priv->dirty_tx;
handled = 1;
while (dirty_tx < priv->cur_tx) {
int entry = dirty_tx % TX_RING_SIZE;
int status = lowb(priv->tx_ring[entry]->TMD1);
if (status & TF_OWN)
break; /* It still hasn't been Txed */
priv->tx_ring[entry]->TMD1 &= 0xff00;
if (status & TF_ERR) {
/* There was an major error, log it */
int err_status = priv->tx_ring[entry]->TMD3;
dev->stats.tx_errors++;
if (err_status & EF_RTRY)
dev->stats.tx_aborted_errors++;
if (err_status & EF_LCAR)
dev->stats.tx_carrier_errors++;
if (err_status & EF_LCOL)
dev->stats.tx_window_errors++;
if (err_status & EF_UFLO) {
/* Ackk! On FIFO errors the Tx unit is turned off! */
dev->stats.tx_fifo_errors++;
/* Remove this verbosity later! */
netdev_err(dev, "Tx FIFO error! Status %04x\n",
csr0);
/* Restart the chip */
lance->RDP = STRT;
}
} else {
if (status & (TF_MORE | TF_ONE))
dev->stats.collisions++;
dev->stats.tx_packets++;
}
dirty_tx++;
}
#ifndef final_version
if (priv->cur_tx - dirty_tx >= TX_RING_SIZE) {
netdev_err(dev, "out-of-sync dirty pointer, %d vs. %d, full=%d\n",
dirty_tx, priv->cur_tx,
priv->tx_full);
dirty_tx += TX_RING_SIZE;
}
#endif
if (priv->tx_full && netif_queue_stopped(dev) &&
dirty_tx > priv->cur_tx - TX_RING_SIZE + 2) {
/* The ring is no longer full */
priv->tx_full = 0;
netif_wake_queue(dev);
}
priv->dirty_tx = dirty_tx;
}
/* Log misc errors */
if (csr0 & BABL) {
handled = 1;
dev->stats.tx_errors++; /* Tx babble */
}
if (csr0 & MISS) {
handled = 1;
dev->stats.rx_errors++; /* Missed a Rx frame */
}
if (csr0 & MERR) {
handled = 1;
netdev_err(dev, "Bus master arbitration failure, status %04x\n",
csr0);
/* Restart the chip */
lance->RDP = STRT;
}
}
/* Clear any other interrupt, and set interrupt enable */
lance->RAP = CSR0; /* PCnet-ISA Controller Status */
lance->RDP = INEA | BABL | CERR | MISS | MERR | IDON;
if (ariadne_debug > 4)
netdev_dbg(dev, "exiting interrupt, csr%d=%#04x\n",
lance->RAP, lance->RDP);
return IRQ_RETVAL(handled);
}
static int ariadne_open(struct net_device *dev)
{
volatile struct Am79C960 *lance = (struct Am79C960 *)dev->base_addr;
u_short in;
u_long version;
int i;
/* Reset the LANCE */
in = lance->Reset;
/* Stop the LANCE */
lance->RAP = CSR0; /* PCnet-ISA Controller Status */
lance->RDP = STOP;
/* Check the LANCE version */
lance->RAP = CSR88; /* Chip ID */
version = swapw(lance->RDP);
lance->RAP = CSR89; /* Chip ID */
version |= swapw(lance->RDP) << 16;
if ((version & 0x00000fff) != 0x00000003) {
pr_warn("Couldn't find AMD Ethernet Chip\n");
return -EAGAIN;
}
if ((version & 0x0ffff000) != 0x00003000) {
pr_warn("Couldn't find Am79C960 (Wrong part number = %ld)\n",
(version & 0x0ffff000) >> 12);
return -EAGAIN;
}
netdev_dbg(dev, "Am79C960 (PCnet-ISA) Revision %ld\n",
(version & 0xf0000000) >> 28);
ariadne_init_ring(dev);
/* Miscellaneous Stuff */
lance->RAP = CSR3; /* Interrupt Masks and Deferral Control */
lance->RDP = 0x0000;
lance->RAP = CSR4; /* Test and Features Control */
lance->RDP = DPOLL | APAD_XMT | MFCOM | RCVCCOM | TXSTRTM | JABM;
/* Set the Multicast Table */
lance->RAP = CSR8; /* Logical Address Filter, LADRF[15:0] */
lance->RDP = 0x0000;
lance->RAP = CSR9; /* Logical Address Filter, LADRF[31:16] */
lance->RDP = 0x0000;
lance->RAP = CSR10; /* Logical Address Filter, LADRF[47:32] */
lance->RDP = 0x0000;
lance->RAP = CSR11; /* Logical Address Filter, LADRF[63:48] */
lance->RDP = 0x0000;
/* Set the Ethernet Hardware Address */
lance->RAP = CSR12; /* Physical Address Register, PADR[15:0] */
lance->RDP = ((u_short *)&dev->dev_addr[0])[0];
lance->RAP = CSR13; /* Physical Address Register, PADR[31:16] */
lance->RDP = ((u_short *)&dev->dev_addr[0])[1];
lance->RAP = CSR14; /* Physical Address Register, PADR[47:32] */
lance->RDP = ((u_short *)&dev->dev_addr[0])[2];
/* Set the Init Block Mode */
lance->RAP = CSR15; /* Mode Register */
lance->RDP = 0x0000;
/* Set the Transmit Descriptor Ring Pointer */
lance->RAP = CSR30; /* Base Address of Transmit Ring */
lance->RDP = swloww(ARIADNE_RAM + offsetof(struct lancedata, tx_ring));
lance->RAP = CSR31; /* Base Address of transmit Ring */
lance->RDP = swhighw(ARIADNE_RAM + offsetof(struct lancedata, tx_ring));
/* Set the Receive Descriptor Ring Pointer */
lance->RAP = CSR24; /* Base Address of Receive Ring */
lance->RDP = swloww(ARIADNE_RAM + offsetof(struct lancedata, rx_ring));
lance->RAP = CSR25; /* Base Address of Receive Ring */
lance->RDP = swhighw(ARIADNE_RAM + offsetof(struct lancedata, rx_ring));
/* Set the Number of RX and TX Ring Entries */
lance->RAP = CSR76; /* Receive Ring Length */
lance->RDP = swapw(((u_short)-RX_RING_SIZE));
lance->RAP = CSR78; /* Transmit Ring Length */
lance->RDP = swapw(((u_short)-TX_RING_SIZE));
/* Enable Media Interface Port Auto Select (10BASE-2/10BASE-T) */
lance->RAP = ISACSR2; /* Miscellaneous Configuration */
lance->IDP = ASEL;
/* LED Control */
lance->RAP = ISACSR5; /* LED1 Status */
lance->IDP = PSE|XMTE;
lance->RAP = ISACSR6; /* LED2 Status */
lance->IDP = PSE|COLE;
lance->RAP = ISACSR7; /* LED3 Status */
lance->IDP = PSE|RCVE;
netif_start_queue(dev);
i = request_irq(IRQ_AMIGA_PORTS, ariadne_interrupt, IRQF_SHARED,
dev->name, dev);
if (i)
return i;
lance->RAP = CSR0; /* PCnet-ISA Controller Status */
lance->RDP = INEA | STRT;
return 0;
}
static int ariadne_close(struct net_device *dev)
{
volatile struct Am79C960 *lance = (struct Am79C960 *)dev->base_addr;
netif_stop_queue(dev);
lance->RAP = CSR112; /* Missed Frame Count */
dev->stats.rx_missed_errors = swapw(lance->RDP);
lance->RAP = CSR0; /* PCnet-ISA Controller Status */
if (ariadne_debug > 1) {
netdev_dbg(dev, "Shutting down ethercard, status was %02x\n",
lance->RDP);
netdev_dbg(dev, "%lu packets missed\n",
dev->stats.rx_missed_errors);
}
/* We stop the LANCE here -- it occasionally polls memory if we don't */
lance->RDP = STOP;
free_irq(IRQ_AMIGA_PORTS, dev);
return 0;
}
static inline void ariadne_reset(struct net_device *dev)
{
volatile struct Am79C960 *lance = (struct Am79C960 *)dev->base_addr;
lance->RAP = CSR0; /* PCnet-ISA Controller Status */
lance->RDP = STOP;
ariadne_init_ring(dev);
lance->RDP = INEA | STRT;
netif_start_queue(dev);
}
static void ariadne_tx_timeout(struct net_device *dev)
{
volatile struct Am79C960 *lance = (struct Am79C960 *)dev->base_addr;
netdev_err(dev, "transmit timed out, status %04x, resetting\n",
lance->RDP);
ariadne_reset(dev);
netif_wake_queue(dev);
}
static netdev_tx_t ariadne_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct ariadne_private *priv = netdev_priv(dev);
volatile struct Am79C960 *lance = (struct Am79C960 *)dev->base_addr;
int entry;
unsigned long flags;
int len = skb->len;
#if 0
if (ariadne_debug > 3) {
lance->RAP = CSR0; /* PCnet-ISA Controller Status */
netdev_dbg(dev, "%s: csr0 %04x\n", __func__, lance->RDP);
lance->RDP = 0x0000;
}
#endif
/* FIXME: is the 79C960 new enough to do its own padding right ? */
if (skb->len < ETH_ZLEN) {
if (skb_padto(skb, ETH_ZLEN))
return NETDEV_TX_OK;
len = ETH_ZLEN;
}
/* Fill in a Tx ring entry */
netdev_dbg(dev, "TX pkt type 0x%04x from %pM to %pM data 0x%08x len %d\n",
((u_short *)skb->data)[6],
skb->data + 6, skb->data,
(int)skb->data, (int)skb->len);
local_irq_save(flags);
entry = priv->cur_tx % TX_RING_SIZE;
/* Caution: the write order is important here, set the base address with
the "ownership" bits last */
priv->tx_ring[entry]->TMD2 = swapw((u_short)-skb->len);
priv->tx_ring[entry]->TMD3 = 0x0000;
memcpyw(priv->tx_buff[entry], (u_short *)skb->data, len);
#ifdef DEBUG
print_hex_dump(KERN_DEBUG, "tx_buff: ", DUMP_PREFIX_OFFSET, 16, 1,
(void *)priv->tx_buff[entry],
skb->len > 64 ? 64 : skb->len, true);
#endif
priv->tx_ring[entry]->TMD1 = (priv->tx_ring[entry]->TMD1 & 0xff00)
| TF_OWN | TF_STP | TF_ENP;
dev_kfree_skb(skb);
priv->cur_tx++;
if ((priv->cur_tx >= TX_RING_SIZE) &&
(priv->dirty_tx >= TX_RING_SIZE)) {
netdev_dbg(dev, "*** Subtracting TX_RING_SIZE from cur_tx (%d) and dirty_tx (%d)\n",
priv->cur_tx, priv->dirty_tx);
priv->cur_tx -= TX_RING_SIZE;
priv->dirty_tx -= TX_RING_SIZE;
}
dev->stats.tx_bytes += len;
/* Trigger an immediate send poll */
lance->RAP = CSR0; /* PCnet-ISA Controller Status */
lance->RDP = INEA | TDMD;
if (lowb(priv->tx_ring[(entry + 1) % TX_RING_SIZE]->TMD1) != 0) {
netif_stop_queue(dev);
priv->tx_full = 1;
}
local_irq_restore(flags);
return NETDEV_TX_OK;
}
static struct net_device_stats *ariadne_get_stats(struct net_device *dev)
{
volatile struct Am79C960 *lance = (struct Am79C960 *)dev->base_addr;
short saved_addr;
unsigned long flags;
local_irq_save(flags);
saved_addr = lance->RAP;
lance->RAP = CSR112; /* Missed Frame Count */
dev->stats.rx_missed_errors = swapw(lance->RDP);
lance->RAP = saved_addr;
local_irq_restore(flags);
return &dev->stats;
}
/* Set or clear the multicast filter for this adaptor.
* num_addrs == -1 Promiscuous mode, receive all packets
* num_addrs == 0 Normal mode, clear multicast list
* num_addrs > 0 Multicast mode, receive normal and MC packets,
* and do best-effort filtering.
*/
static void set_multicast_list(struct net_device *dev)
{
volatile struct Am79C960 *lance = (struct Am79C960 *)dev->base_addr;
if (!netif_running(dev))
return;
netif_stop_queue(dev);
/* We take the simple way out and always enable promiscuous mode */
lance->RAP = CSR0; /* PCnet-ISA Controller Status */
lance->RDP = STOP; /* Temporarily stop the lance */
ariadne_init_ring(dev);
if (dev->flags & IFF_PROMISC) {
lance->RAP = CSR15; /* Mode Register */
lance->RDP = PROM; /* Set promiscuous mode */
} else {
short multicast_table[4];
int num_addrs = netdev_mc_count(dev);
int i;
/* We don't use the multicast table,
* but rely on upper-layer filtering
*/
memset(multicast_table, (num_addrs == 0) ? 0 : -1,
sizeof(multicast_table));
for (i = 0; i < 4; i++) {
lance->RAP = CSR8 + (i << 8);
/* Logical Address Filter */
lance->RDP = swapw(multicast_table[i]);
}
lance->RAP = CSR15; /* Mode Register */
lance->RDP = 0x0000; /* Unset promiscuous mode */
}
lance->RAP = CSR0; /* PCnet-ISA Controller Status */
lance->RDP = INEA | STRT | IDON;/* Resume normal operation */
netif_wake_queue(dev);
}
static void __devexit ariadne_remove_one(struct zorro_dev *z)
{
struct net_device *dev = zorro_get_drvdata(z);
unregister_netdev(dev);
release_mem_region(ZTWO_PADDR(dev->base_addr), sizeof(struct Am79C960));
release_mem_region(ZTWO_PADDR(dev->mem_start), ARIADNE_RAM_SIZE);
free_netdev(dev);
}
static struct zorro_device_id ariadne_zorro_tbl[] __devinitdata = {
{ ZORRO_PROD_VILLAGE_TRONIC_ARIADNE },
{ 0 }
};
MODULE_DEVICE_TABLE(zorro, ariadne_zorro_tbl);
static const struct net_device_ops ariadne_netdev_ops = {
.ndo_open = ariadne_open,
.ndo_stop = ariadne_close,
.ndo_start_xmit = ariadne_start_xmit,
.ndo_tx_timeout = ariadne_tx_timeout,
.ndo_get_stats = ariadne_get_stats,
.ndo_set_rx_mode = set_multicast_list,
.ndo_validate_addr = eth_validate_addr,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
};
static int __devinit ariadne_init_one(struct zorro_dev *z,
const struct zorro_device_id *ent)
{
unsigned long board = z->resource.start;
unsigned long base_addr = board + ARIADNE_LANCE;
unsigned long mem_start = board + ARIADNE_RAM;
struct resource *r1, *r2;
struct net_device *dev;
struct ariadne_private *priv;
int err;
r1 = request_mem_region(base_addr, sizeof(struct Am79C960), "Am79C960");
if (!r1)
return -EBUSY;
r2 = request_mem_region(mem_start, ARIADNE_RAM_SIZE, "RAM");
if (!r2) {
release_mem_region(base_addr, sizeof(struct Am79C960));
return -EBUSY;
}
dev = alloc_etherdev(sizeof(struct ariadne_private));
if (dev == NULL) {
release_mem_region(base_addr, sizeof(struct Am79C960));
release_mem_region(mem_start, ARIADNE_RAM_SIZE);
return -ENOMEM;
}
priv = netdev_priv(dev);
r1->name = dev->name;
r2->name = dev->name;
dev->dev_addr[0] = 0x00;
dev->dev_addr[1] = 0x60;
dev->dev_addr[2] = 0x30;
dev->dev_addr[3] = (z->rom.er_SerialNumber >> 16) & 0xff;
dev->dev_addr[4] = (z->rom.er_SerialNumber >> 8) & 0xff;
dev->dev_addr[5] = z->rom.er_SerialNumber & 0xff;
dev->base_addr = ZTWO_VADDR(base_addr);
dev->mem_start = ZTWO_VADDR(mem_start);
dev->mem_end = dev->mem_start + ARIADNE_RAM_SIZE;
dev->netdev_ops = &ariadne_netdev_ops;
dev->watchdog_timeo = 5 * HZ;
err = register_netdev(dev);
if (err) {
release_mem_region(base_addr, sizeof(struct Am79C960));
release_mem_region(mem_start, ARIADNE_RAM_SIZE);
free_netdev(dev);
return err;
}
zorro_set_drvdata(z, dev);
netdev_info(dev, "Ariadne at 0x%08lx, Ethernet Address %pM\n",
board, dev->dev_addr);
return 0;
}
static struct zorro_driver ariadne_driver = {
.name = "ariadne",
.id_table = ariadne_zorro_tbl,
.probe = ariadne_init_one,
.remove = __devexit_p(ariadne_remove_one),
};
static int __init ariadne_init_module(void)
{
return zorro_register_driver(&ariadne_driver);
}
static void __exit ariadne_cleanup_module(void)
{
zorro_unregister_driver(&ariadne_driver);
}
module_init(ariadne_init_module);
module_exit(ariadne_cleanup_module);
MODULE_LICENSE("GPL");
| gpl-2.0 |
Droid-Concepts/DC-Elite_kernel_jf | drivers/media/video/cx231xx/cx231xx-417.c | 4812 | 57973 | /*
*
* Support for a cx23417 mpeg encoder via cx231xx host port.
*
* (c) 2004 Jelle Foks <jelle@foks.us>
* (c) 2004 Gerd Knorr <kraxel@bytesex.org>
* (c) 2008 Steven Toth <stoth@linuxtv.org>
* - CX23885/7/8 support
*
* Includes parts from the ivtv driver( http://ivtv.sourceforge.net/),
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/firmware.h>
#include <linux/vmalloc.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include <media/cx2341x.h>
#include <linux/usb.h>
#include "cx231xx.h"
/*#include "cx23885-ioctl.h"*/
#define CX231xx_FIRM_IMAGE_SIZE 376836
#define CX231xx_FIRM_IMAGE_NAME "v4l-cx23885-enc.fw"
/* for polaris ITVC */
#define ITVC_WRITE_DIR 0x03FDFC00
#define ITVC_READ_DIR 0x0001FC00
#define MCI_MEMORY_DATA_BYTE0 0x00
#define MCI_MEMORY_DATA_BYTE1 0x08
#define MCI_MEMORY_DATA_BYTE2 0x10
#define MCI_MEMORY_DATA_BYTE3 0x18
#define MCI_MEMORY_ADDRESS_BYTE2 0x20
#define MCI_MEMORY_ADDRESS_BYTE1 0x28
#define MCI_MEMORY_ADDRESS_BYTE0 0x30
#define MCI_REGISTER_DATA_BYTE0 0x40
#define MCI_REGISTER_DATA_BYTE1 0x48
#define MCI_REGISTER_DATA_BYTE2 0x50
#define MCI_REGISTER_DATA_BYTE3 0x58
#define MCI_REGISTER_ADDRESS_BYTE0 0x60
#define MCI_REGISTER_ADDRESS_BYTE1 0x68
#define MCI_REGISTER_MODE 0x70
/* Read and write modes for polaris ITVC */
#define MCI_MODE_REGISTER_READ 0x000
#define MCI_MODE_REGISTER_WRITE 0x100
#define MCI_MODE_MEMORY_READ 0x000
#define MCI_MODE_MEMORY_WRITE 0x4000
static unsigned int mpegbufs = 8;
module_param(mpegbufs, int, 0644);
MODULE_PARM_DESC(mpegbufs, "number of mpeg buffers, range 2-32");
static unsigned int mpeglines = 128;
module_param(mpeglines, int, 0644);
MODULE_PARM_DESC(mpeglines, "number of lines in an MPEG buffer, range 2-32");
static unsigned int mpeglinesize = 512;
module_param(mpeglinesize, int, 0644);
MODULE_PARM_DESC(mpeglinesize,
"number of bytes in each line of an MPEG buffer, range 512-1024");
static unsigned int v4l_debug = 1;
module_param(v4l_debug, int, 0644);
MODULE_PARM_DESC(v4l_debug, "enable V4L debug messages");
struct cx231xx_dmaqueue *dma_qq;
#define dprintk(level, fmt, arg...)\
do { if (v4l_debug >= level) \
printk(KERN_INFO "%s: " fmt, \
(dev) ? dev->name : "cx231xx[?]", ## arg); \
} while (0)
static struct cx231xx_tvnorm cx231xx_tvnorms[] = {
{
.name = "NTSC-M",
.id = V4L2_STD_NTSC_M,
}, {
.name = "NTSC-JP",
.id = V4L2_STD_NTSC_M_JP,
}, {
.name = "PAL-BG",
.id = V4L2_STD_PAL_BG,
}, {
.name = "PAL-DK",
.id = V4L2_STD_PAL_DK,
}, {
.name = "PAL-I",
.id = V4L2_STD_PAL_I,
}, {
.name = "PAL-M",
.id = V4L2_STD_PAL_M,
}, {
.name = "PAL-N",
.id = V4L2_STD_PAL_N,
}, {
.name = "PAL-Nc",
.id = V4L2_STD_PAL_Nc,
}, {
.name = "PAL-60",
.id = V4L2_STD_PAL_60,
}, {
.name = "SECAM-L",
.id = V4L2_STD_SECAM_L,
}, {
.name = "SECAM-DK",
.id = V4L2_STD_SECAM_DK,
}
};
/* ------------------------------------------------------------------ */
enum cx231xx_capture_type {
CX231xx_MPEG_CAPTURE,
CX231xx_RAW_CAPTURE,
CX231xx_RAW_PASSTHRU_CAPTURE
};
enum cx231xx_capture_bits {
CX231xx_RAW_BITS_NONE = 0x00,
CX231xx_RAW_BITS_YUV_CAPTURE = 0x01,
CX231xx_RAW_BITS_PCM_CAPTURE = 0x02,
CX231xx_RAW_BITS_VBI_CAPTURE = 0x04,
CX231xx_RAW_BITS_PASSTHRU_CAPTURE = 0x08,
CX231xx_RAW_BITS_TO_HOST_CAPTURE = 0x10
};
enum cx231xx_capture_end {
CX231xx_END_AT_GOP, /* stop at the end of gop, generate irq */
CX231xx_END_NOW, /* stop immediately, no irq */
};
enum cx231xx_framerate {
CX231xx_FRAMERATE_NTSC_30, /* NTSC: 30fps */
CX231xx_FRAMERATE_PAL_25 /* PAL: 25fps */
};
enum cx231xx_stream_port {
CX231xx_OUTPUT_PORT_MEMORY,
CX231xx_OUTPUT_PORT_STREAMING,
CX231xx_OUTPUT_PORT_SERIAL
};
enum cx231xx_data_xfer_status {
CX231xx_MORE_BUFFERS_FOLLOW,
CX231xx_LAST_BUFFER,
};
enum cx231xx_picture_mask {
CX231xx_PICTURE_MASK_NONE,
CX231xx_PICTURE_MASK_I_FRAMES,
CX231xx_PICTURE_MASK_I_P_FRAMES = 0x3,
CX231xx_PICTURE_MASK_ALL_FRAMES = 0x7,
};
enum cx231xx_vbi_mode_bits {
CX231xx_VBI_BITS_SLICED,
CX231xx_VBI_BITS_RAW,
};
enum cx231xx_vbi_insertion_bits {
CX231xx_VBI_BITS_INSERT_IN_XTENSION_USR_DATA,
CX231xx_VBI_BITS_INSERT_IN_PRIVATE_PACKETS = 0x1 << 1,
CX231xx_VBI_BITS_SEPARATE_STREAM = 0x2 << 1,
CX231xx_VBI_BITS_SEPARATE_STREAM_USR_DATA = 0x4 << 1,
CX231xx_VBI_BITS_SEPARATE_STREAM_PRV_DATA = 0x5 << 1,
};
enum cx231xx_dma_unit {
CX231xx_DMA_BYTES,
CX231xx_DMA_FRAMES,
};
enum cx231xx_dma_transfer_status_bits {
CX231xx_DMA_TRANSFER_BITS_DONE = 0x01,
CX231xx_DMA_TRANSFER_BITS_ERROR = 0x04,
CX231xx_DMA_TRANSFER_BITS_LL_ERROR = 0x10,
};
enum cx231xx_pause {
CX231xx_PAUSE_ENCODING,
CX231xx_RESUME_ENCODING,
};
enum cx231xx_copyright {
CX231xx_COPYRIGHT_OFF,
CX231xx_COPYRIGHT_ON,
};
enum cx231xx_notification_type {
CX231xx_NOTIFICATION_REFRESH,
};
enum cx231xx_notification_status {
CX231xx_NOTIFICATION_OFF,
CX231xx_NOTIFICATION_ON,
};
enum cx231xx_notification_mailbox {
CX231xx_NOTIFICATION_NO_MAILBOX = -1,
};
enum cx231xx_field1_lines {
CX231xx_FIELD1_SAA7114 = 0x00EF, /* 239 */
CX231xx_FIELD1_SAA7115 = 0x00F0, /* 240 */
CX231xx_FIELD1_MICRONAS = 0x0105, /* 261 */
};
enum cx231xx_field2_lines {
CX231xx_FIELD2_SAA7114 = 0x00EF, /* 239 */
CX231xx_FIELD2_SAA7115 = 0x00F0, /* 240 */
CX231xx_FIELD2_MICRONAS = 0x0106, /* 262 */
};
enum cx231xx_custom_data_type {
CX231xx_CUSTOM_EXTENSION_USR_DATA,
CX231xx_CUSTOM_PRIVATE_PACKET,
};
enum cx231xx_mute {
CX231xx_UNMUTE,
CX231xx_MUTE,
};
enum cx231xx_mute_video_mask {
CX231xx_MUTE_VIDEO_V_MASK = 0x0000FF00,
CX231xx_MUTE_VIDEO_U_MASK = 0x00FF0000,
CX231xx_MUTE_VIDEO_Y_MASK = 0xFF000000,
};
enum cx231xx_mute_video_shift {
CX231xx_MUTE_VIDEO_V_SHIFT = 8,
CX231xx_MUTE_VIDEO_U_SHIFT = 16,
CX231xx_MUTE_VIDEO_Y_SHIFT = 24,
};
/* defines below are from ivtv-driver.h */
#define IVTV_CMD_HW_BLOCKS_RST 0xFFFFFFFF
/* Firmware API commands */
#define IVTV_API_STD_TIMEOUT 500
/* Registers */
/* IVTV_REG_OFFSET */
#define IVTV_REG_ENC_SDRAM_REFRESH (0x07F8)
#define IVTV_REG_ENC_SDRAM_PRECHARGE (0x07FC)
#define IVTV_REG_SPU (0x9050)
#define IVTV_REG_HW_BLOCKS (0x9054)
#define IVTV_REG_VPU (0x9058)
#define IVTV_REG_APU (0xA064)
/*
* Bit definitions for MC417_RWD and MC417_OEN registers
*
* bits 31-16
*+-----------+
*| Reserved |
*|+-----------+
*| bit 15 bit 14 bit 13 bit 12 bit 11 bit 10 bit 9 bit 8
*|+-------+-------+-------+-------+-------+-------+-------+-------+
*|| MIWR# | MIRD# | MICS# |MIRDY# |MIADDR3|MIADDR2|MIADDR1|MIADDR0|
*|+-------+-------+-------+-------+-------+-------+-------+-------+
*| bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0
*|+-------+-------+-------+-------+-------+-------+-------+-------+
*||MIDATA7|MIDATA6|MIDATA5|MIDATA4|MIDATA3|MIDATA2|MIDATA1|MIDATA0|
*|+-------+-------+-------+-------+-------+-------+-------+-------+
*/
#define MC417_MIWR 0x8000
#define MC417_MIRD 0x4000
#define MC417_MICS 0x2000
#define MC417_MIRDY 0x1000
#define MC417_MIADDR 0x0F00
#define MC417_MIDATA 0x00FF
/* Bit definitions for MC417_CTL register ****
*bits 31-6 bits 5-4 bit 3 bits 2-1 Bit 0
*+--------+-------------+--------+--------------+------------+
*|Reserved|MC417_SPD_CTL|Reserved|MC417_GPIO_SEL|UART_GPIO_EN|
*+--------+-------------+--------+--------------+------------+
*/
#define MC417_SPD_CTL(x) (((x) << 4) & 0x00000030)
#define MC417_GPIO_SEL(x) (((x) << 1) & 0x00000006)
#define MC417_UART_GPIO_EN 0x00000001
/* Values for speed control */
#define MC417_SPD_CTL_SLOW 0x1
#define MC417_SPD_CTL_MEDIUM 0x0
#define MC417_SPD_CTL_FAST 0x3 /* b'1x, but we use b'11 */
/* Values for GPIO select */
#define MC417_GPIO_SEL_GPIO3 0x3
#define MC417_GPIO_SEL_GPIO2 0x2
#define MC417_GPIO_SEL_GPIO1 0x1
#define MC417_GPIO_SEL_GPIO0 0x0
#define CX23417_GPIO_MASK 0xFC0003FF
static int setITVCReg(struct cx231xx *dev, u32 gpio_direction, u32 value)
{
int status = 0;
u32 _gpio_direction = 0;
_gpio_direction = _gpio_direction & CX23417_GPIO_MASK;
_gpio_direction = _gpio_direction|gpio_direction;
status = cx231xx_send_gpio_cmd(dev, _gpio_direction,
(u8 *)&value, 4, 0, 0);
return status;
}
static int getITVCReg(struct cx231xx *dev, u32 gpio_direction, u32 *pValue)
{
int status = 0;
u32 _gpio_direction = 0;
_gpio_direction = _gpio_direction & CX23417_GPIO_MASK;
_gpio_direction = _gpio_direction|gpio_direction;
status = cx231xx_send_gpio_cmd(dev, _gpio_direction,
(u8 *)pValue, 4, 0, 1);
return status;
}
static int waitForMciComplete(struct cx231xx *dev)
{
u32 gpio;
u32 gpio_driection = 0;
u8 count = 0;
getITVCReg(dev, gpio_driection, &gpio);
while (!(gpio&0x020000)) {
msleep(10);
getITVCReg(dev, gpio_driection, &gpio);
if (count++ > 100) {
dprintk(3, "ERROR: Timeout - gpio=%x\n", gpio);
return -1;
}
}
return 0;
}
static int mc417_register_write(struct cx231xx *dev, u16 address, u32 value)
{
u32 temp;
int status = 0;
temp = 0x82|MCI_REGISTER_DATA_BYTE0|((value&0x000000FF)<<8);
temp = temp<<10;
status = setITVCReg(dev, ITVC_WRITE_DIR, temp);
if (status < 0)
return status;
temp = temp|((0x05)<<10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/*write data byte 1;*/
temp = 0x82|MCI_REGISTER_DATA_BYTE1|(value&0x0000FF00);
temp = temp<<10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp|((0x05)<<10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/*write data byte 2;*/
temp = 0x82|MCI_REGISTER_DATA_BYTE2|((value&0x00FF0000)>>8);
temp = temp<<10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp|((0x05)<<10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/*write data byte 3;*/
temp = 0x82|MCI_REGISTER_DATA_BYTE3|((value&0xFF000000)>>16);
temp = temp<<10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp|((0x05)<<10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/*write address byte 0;*/
temp = 0x82|MCI_REGISTER_ADDRESS_BYTE0|((address&0x000000FF)<<8);
temp = temp<<10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp|((0x05)<<10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/*write address byte 1;*/
temp = 0x82|MCI_REGISTER_ADDRESS_BYTE1|(address&0x0000FF00);
temp = temp<<10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp|((0x05)<<10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/*Write that the mode is write.*/
temp = 0x82 | MCI_REGISTER_MODE | MCI_MODE_REGISTER_WRITE;
temp = temp<<10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp|((0x05)<<10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
return waitForMciComplete(dev);
}
static int mc417_register_read(struct cx231xx *dev, u16 address, u32 *value)
{
/*write address byte 0;*/
u32 temp;
u32 return_value = 0;
int ret = 0;
temp = 0x82 | MCI_REGISTER_ADDRESS_BYTE0 | ((address & 0x00FF) << 8);
temp = temp << 10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp | ((0x05) << 10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/*write address byte 1;*/
temp = 0x82 | MCI_REGISTER_ADDRESS_BYTE1 | (address & 0xFF00);
temp = temp << 10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp | ((0x05) << 10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/*write that the mode is read;*/
temp = 0x82 | MCI_REGISTER_MODE | MCI_MODE_REGISTER_READ;
temp = temp << 10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp | ((0x05) << 10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/*wait for the MIRDY line to be asserted ,
signalling that the read is done;*/
ret = waitForMciComplete(dev);
/*switch the DATA- GPIO to input mode;*/
/*Read data byte 0;*/
temp = (0x82 | MCI_REGISTER_DATA_BYTE0) << 10;
setITVCReg(dev, ITVC_READ_DIR, temp);
temp = ((0x81 | MCI_REGISTER_DATA_BYTE0) << 10);
setITVCReg(dev, ITVC_READ_DIR, temp);
getITVCReg(dev, ITVC_READ_DIR, &temp);
return_value |= ((temp & 0x03FC0000) >> 18);
setITVCReg(dev, ITVC_READ_DIR, (0x87 << 10));
/* Read data byte 1;*/
temp = (0x82 | MCI_REGISTER_DATA_BYTE1) << 10;
setITVCReg(dev, ITVC_READ_DIR, temp);
temp = ((0x81 | MCI_REGISTER_DATA_BYTE1) << 10);
setITVCReg(dev, ITVC_READ_DIR, temp);
getITVCReg(dev, ITVC_READ_DIR, &temp);
return_value |= ((temp & 0x03FC0000) >> 10);
setITVCReg(dev, ITVC_READ_DIR, (0x87 << 10));
/*Read data byte 2;*/
temp = (0x82 | MCI_REGISTER_DATA_BYTE2) << 10;
setITVCReg(dev, ITVC_READ_DIR, temp);
temp = ((0x81 | MCI_REGISTER_DATA_BYTE2) << 10);
setITVCReg(dev, ITVC_READ_DIR, temp);
getITVCReg(dev, ITVC_READ_DIR, &temp);
return_value |= ((temp & 0x03FC0000) >> 2);
setITVCReg(dev, ITVC_READ_DIR, (0x87 << 10));
/*Read data byte 3;*/
temp = (0x82 | MCI_REGISTER_DATA_BYTE3) << 10;
setITVCReg(dev, ITVC_READ_DIR, temp);
temp = ((0x81 | MCI_REGISTER_DATA_BYTE3) << 10);
setITVCReg(dev, ITVC_READ_DIR, temp);
getITVCReg(dev, ITVC_READ_DIR, &temp);
return_value |= ((temp & 0x03FC0000) << 6);
setITVCReg(dev, ITVC_READ_DIR, (0x87 << 10));
*value = return_value;
return ret;
}
static int mc417_memory_write(struct cx231xx *dev, u32 address, u32 value)
{
/*write data byte 0;*/
u32 temp;
int ret = 0;
temp = 0x82 | MCI_MEMORY_DATA_BYTE0|((value & 0x000000FF) << 8);
temp = temp << 10;
ret = setITVCReg(dev, ITVC_WRITE_DIR, temp);
if (ret < 0)
return ret;
temp = temp | ((0x05) << 10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/*write data byte 1;*/
temp = 0x82 | MCI_MEMORY_DATA_BYTE1 | (value & 0x0000FF00);
temp = temp << 10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp | ((0x05) << 10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/*write data byte 2;*/
temp = 0x82|MCI_MEMORY_DATA_BYTE2|((value&0x00FF0000)>>8);
temp = temp<<10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp|((0x05)<<10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/*write data byte 3;*/
temp = 0x82|MCI_MEMORY_DATA_BYTE3|((value&0xFF000000)>>16);
temp = temp<<10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp|((0x05)<<10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/* write address byte 2;*/
temp = 0x82|MCI_MEMORY_ADDRESS_BYTE2 | MCI_MODE_MEMORY_WRITE |
((address & 0x003F0000)>>8);
temp = temp<<10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp|((0x05)<<10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/* write address byte 1;*/
temp = 0x82|MCI_MEMORY_ADDRESS_BYTE1 | (address & 0xFF00);
temp = temp<<10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp|((0x05)<<10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/* write address byte 0;*/
temp = 0x82|MCI_MEMORY_ADDRESS_BYTE0|((address & 0x00FF)<<8);
temp = temp<<10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp|((0x05)<<10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/*wait for MIRDY line;*/
waitForMciComplete(dev);
return 0;
}
static int mc417_memory_read(struct cx231xx *dev, u32 address, u32 *value)
{
u32 temp = 0;
u32 return_value = 0;
int ret = 0;
/*write address byte 2;*/
temp = 0x82|MCI_MEMORY_ADDRESS_BYTE2 | MCI_MODE_MEMORY_READ |
((address & 0x003F0000)>>8);
temp = temp<<10;
ret = setITVCReg(dev, ITVC_WRITE_DIR, temp);
if (ret < 0)
return ret;
temp = temp|((0x05)<<10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/*write address byte 1*/
temp = 0x82|MCI_MEMORY_ADDRESS_BYTE1 | (address & 0xFF00);
temp = temp<<10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp|((0x05)<<10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/*write address byte 0*/
temp = 0x82|MCI_MEMORY_ADDRESS_BYTE0 | ((address & 0x00FF)<<8);
temp = temp<<10;
setITVCReg(dev, ITVC_WRITE_DIR, temp);
temp = temp|((0x05)<<10);
setITVCReg(dev, ITVC_WRITE_DIR, temp);
/*Wait for MIRDY line*/
ret = waitForMciComplete(dev);
/*Read data byte 3;*/
temp = (0x82|MCI_MEMORY_DATA_BYTE3)<<10;
setITVCReg(dev, ITVC_READ_DIR, temp);
temp = ((0x81|MCI_MEMORY_DATA_BYTE3)<<10);
setITVCReg(dev, ITVC_READ_DIR, temp);
getITVCReg(dev, ITVC_READ_DIR, &temp);
return_value |= ((temp&0x03FC0000)<<6);
setITVCReg(dev, ITVC_READ_DIR, (0x87<<10));
/*Read data byte 2;*/
temp = (0x82|MCI_MEMORY_DATA_BYTE2)<<10;
setITVCReg(dev, ITVC_READ_DIR, temp);
temp = ((0x81|MCI_MEMORY_DATA_BYTE2)<<10);
setITVCReg(dev, ITVC_READ_DIR, temp);
getITVCReg(dev, ITVC_READ_DIR, &temp);
return_value |= ((temp&0x03FC0000)>>2);
setITVCReg(dev, ITVC_READ_DIR, (0x87<<10));
/* Read data byte 1;*/
temp = (0x82|MCI_MEMORY_DATA_BYTE1)<<10;
setITVCReg(dev, ITVC_READ_DIR, temp);
temp = ((0x81|MCI_MEMORY_DATA_BYTE1)<<10);
setITVCReg(dev, ITVC_READ_DIR, temp);
getITVCReg(dev, ITVC_READ_DIR, &temp);
return_value |= ((temp&0x03FC0000)>>10);
setITVCReg(dev, ITVC_READ_DIR, (0x87<<10));
/*Read data byte 0;*/
temp = (0x82|MCI_MEMORY_DATA_BYTE0)<<10;
setITVCReg(dev, ITVC_READ_DIR, temp);
temp = ((0x81|MCI_MEMORY_DATA_BYTE0)<<10);
setITVCReg(dev, ITVC_READ_DIR, temp);
getITVCReg(dev, ITVC_READ_DIR, &temp);
return_value |= ((temp&0x03FC0000)>>18);
setITVCReg(dev, ITVC_READ_DIR, (0x87<<10));
*value = return_value;
return ret;
}
/* ------------------------------------------------------------------ */
/* MPEG encoder API */
static char *cmd_to_str(int cmd)
{
switch (cmd) {
case CX2341X_ENC_PING_FW:
return "PING_FW";
case CX2341X_ENC_START_CAPTURE:
return "START_CAPTURE";
case CX2341X_ENC_STOP_CAPTURE:
return "STOP_CAPTURE";
case CX2341X_ENC_SET_AUDIO_ID:
return "SET_AUDIO_ID";
case CX2341X_ENC_SET_VIDEO_ID:
return "SET_VIDEO_ID";
case CX2341X_ENC_SET_PCR_ID:
return "SET_PCR_PID";
case CX2341X_ENC_SET_FRAME_RATE:
return "SET_FRAME_RATE";
case CX2341X_ENC_SET_FRAME_SIZE:
return "SET_FRAME_SIZE";
case CX2341X_ENC_SET_BIT_RATE:
return "SET_BIT_RATE";
case CX2341X_ENC_SET_GOP_PROPERTIES:
return "SET_GOP_PROPERTIES";
case CX2341X_ENC_SET_ASPECT_RATIO:
return "SET_ASPECT_RATIO";
case CX2341X_ENC_SET_DNR_FILTER_MODE:
return "SET_DNR_FILTER_PROPS";
case CX2341X_ENC_SET_DNR_FILTER_PROPS:
return "SET_DNR_FILTER_PROPS";
case CX2341X_ENC_SET_CORING_LEVELS:
return "SET_CORING_LEVELS";
case CX2341X_ENC_SET_SPATIAL_FILTER_TYPE:
return "SET_SPATIAL_FILTER_TYPE";
case CX2341X_ENC_SET_VBI_LINE:
return "SET_VBI_LINE";
case CX2341X_ENC_SET_STREAM_TYPE:
return "SET_STREAM_TYPE";
case CX2341X_ENC_SET_OUTPUT_PORT:
return "SET_OUTPUT_PORT";
case CX2341X_ENC_SET_AUDIO_PROPERTIES:
return "SET_AUDIO_PROPERTIES";
case CX2341X_ENC_HALT_FW:
return "HALT_FW";
case CX2341X_ENC_GET_VERSION:
return "GET_VERSION";
case CX2341X_ENC_SET_GOP_CLOSURE:
return "SET_GOP_CLOSURE";
case CX2341X_ENC_GET_SEQ_END:
return "GET_SEQ_END";
case CX2341X_ENC_SET_PGM_INDEX_INFO:
return "SET_PGM_INDEX_INFO";
case CX2341X_ENC_SET_VBI_CONFIG:
return "SET_VBI_CONFIG";
case CX2341X_ENC_SET_DMA_BLOCK_SIZE:
return "SET_DMA_BLOCK_SIZE";
case CX2341X_ENC_GET_PREV_DMA_INFO_MB_10:
return "GET_PREV_DMA_INFO_MB_10";
case CX2341X_ENC_GET_PREV_DMA_INFO_MB_9:
return "GET_PREV_DMA_INFO_MB_9";
case CX2341X_ENC_SCHED_DMA_TO_HOST:
return "SCHED_DMA_TO_HOST";
case CX2341X_ENC_INITIALIZE_INPUT:
return "INITIALIZE_INPUT";
case CX2341X_ENC_SET_FRAME_DROP_RATE:
return "SET_FRAME_DROP_RATE";
case CX2341X_ENC_PAUSE_ENCODER:
return "PAUSE_ENCODER";
case CX2341X_ENC_REFRESH_INPUT:
return "REFRESH_INPUT";
case CX2341X_ENC_SET_COPYRIGHT:
return "SET_COPYRIGHT";
case CX2341X_ENC_SET_EVENT_NOTIFICATION:
return "SET_EVENT_NOTIFICATION";
case CX2341X_ENC_SET_NUM_VSYNC_LINES:
return "SET_NUM_VSYNC_LINES";
case CX2341X_ENC_SET_PLACEHOLDER:
return "SET_PLACEHOLDER";
case CX2341X_ENC_MUTE_VIDEO:
return "MUTE_VIDEO";
case CX2341X_ENC_MUTE_AUDIO:
return "MUTE_AUDIO";
case CX2341X_ENC_MISC:
return "MISC";
default:
return "UNKNOWN";
}
}
static int cx231xx_mbox_func(void *priv,
u32 command,
int in,
int out,
u32 data[CX2341X_MBOX_MAX_DATA])
{
struct cx231xx *dev = priv;
unsigned long timeout;
u32 value, flag, retval = 0;
int i;
dprintk(3, "%s: command(0x%X) = %s\n", __func__, command,
cmd_to_str(command));
/* this may not be 100% safe if we can't read any memory location
without side effects */
mc417_memory_read(dev, dev->cx23417_mailbox - 4, &value);
if (value != 0x12345678) {
dprintk(3,
"Firmware and/or mailbox pointer not initialized "
"or corrupted, signature = 0x%x, cmd = %s\n", value,
cmd_to_str(command));
return -1;
}
/* This read looks at 32 bits, but flag is only 8 bits.
* Seems we also bail if CMD or TIMEOUT bytes are set???
*/
mc417_memory_read(dev, dev->cx23417_mailbox, &flag);
if (flag) {
dprintk(3, "ERROR: Mailbox appears to be in use "
"(%x), cmd = %s\n", flag, cmd_to_str(command));
return -1;
}
flag |= 1; /* tell 'em we're working on it */
mc417_memory_write(dev, dev->cx23417_mailbox, flag);
/* write command + args + fill remaining with zeros */
/* command code */
mc417_memory_write(dev, dev->cx23417_mailbox + 1, command);
mc417_memory_write(dev, dev->cx23417_mailbox + 3,
IVTV_API_STD_TIMEOUT); /* timeout */
for (i = 0; i < in; i++) {
mc417_memory_write(dev, dev->cx23417_mailbox + 4 + i, data[i]);
dprintk(3, "API Input %d = %d\n", i, data[i]);
}
for (; i < CX2341X_MBOX_MAX_DATA; i++)
mc417_memory_write(dev, dev->cx23417_mailbox + 4 + i, 0);
flag |= 3; /* tell 'em we're done writing */
mc417_memory_write(dev, dev->cx23417_mailbox, flag);
/* wait for firmware to handle the API command */
timeout = jiffies + msecs_to_jiffies(10);
for (;;) {
mc417_memory_read(dev, dev->cx23417_mailbox, &flag);
if (0 != (flag & 4))
break;
if (time_after(jiffies, timeout)) {
dprintk(3, "ERROR: API Mailbox timeout\n");
return -1;
}
udelay(10);
}
/* read output values */
for (i = 0; i < out; i++) {
mc417_memory_read(dev, dev->cx23417_mailbox + 4 + i, data + i);
dprintk(3, "API Output %d = %d\n", i, data[i]);
}
mc417_memory_read(dev, dev->cx23417_mailbox + 2, &retval);
dprintk(3, "API result = %d\n", retval);
flag = 0;
mc417_memory_write(dev, dev->cx23417_mailbox, flag);
return retval;
}
/* We don't need to call the API often, so using just one
* mailbox will probably suffice
*/
static int cx231xx_api_cmd(struct cx231xx *dev,
u32 command,
u32 inputcnt,
u32 outputcnt,
...)
{
u32 data[CX2341X_MBOX_MAX_DATA];
va_list vargs;
int i, err;
dprintk(3, "%s() cmds = 0x%08x\n", __func__, command);
va_start(vargs, outputcnt);
for (i = 0; i < inputcnt; i++)
data[i] = va_arg(vargs, int);
err = cx231xx_mbox_func(dev, command, inputcnt, outputcnt, data);
for (i = 0; i < outputcnt; i++) {
int *vptr = va_arg(vargs, int *);
*vptr = data[i];
}
va_end(vargs);
return err;
}
static int cx231xx_find_mailbox(struct cx231xx *dev)
{
u32 signature[4] = {
0x12345678, 0x34567812, 0x56781234, 0x78123456
};
int signaturecnt = 0;
u32 value;
int i;
int ret = 0;
dprintk(2, "%s()\n", __func__);
for (i = 0; i < 0x100; i++) {/*CX231xx_FIRM_IMAGE_SIZE*/
ret = mc417_memory_read(dev, i, &value);
if (ret < 0)
return ret;
if (value == signature[signaturecnt])
signaturecnt++;
else
signaturecnt = 0;
if (4 == signaturecnt) {
dprintk(1, "Mailbox signature found at 0x%x\n", i+1);
return i+1;
}
}
dprintk(3, "Mailbox signature values not found!\n");
return -1;
}
static void mciWriteMemoryToGPIO(struct cx231xx *dev, u32 address, u32 value,
u32 *p_fw_image)
{
u32 temp = 0;
int i = 0;
temp = 0x82|MCI_MEMORY_DATA_BYTE0|((value&0x000000FF)<<8);
temp = temp<<10;
*p_fw_image = temp;
p_fw_image++;
temp = temp|((0x05)<<10);
*p_fw_image = temp;
p_fw_image++;
/*write data byte 1;*/
temp = 0x82|MCI_MEMORY_DATA_BYTE1|(value&0x0000FF00);
temp = temp<<10;
*p_fw_image = temp;
p_fw_image++;
temp = temp|((0x05)<<10);
*p_fw_image = temp;
p_fw_image++;
/*write data byte 2;*/
temp = 0x82|MCI_MEMORY_DATA_BYTE2|((value&0x00FF0000)>>8);
temp = temp<<10;
*p_fw_image = temp;
p_fw_image++;
temp = temp|((0x05)<<10);
*p_fw_image = temp;
p_fw_image++;
/*write data byte 3;*/
temp = 0x82|MCI_MEMORY_DATA_BYTE3|((value&0xFF000000)>>16);
temp = temp<<10;
*p_fw_image = temp;
p_fw_image++;
temp = temp|((0x05)<<10);
*p_fw_image = temp;
p_fw_image++;
/* write address byte 2;*/
temp = 0x82|MCI_MEMORY_ADDRESS_BYTE2 | MCI_MODE_MEMORY_WRITE |
((address & 0x003F0000)>>8);
temp = temp<<10;
*p_fw_image = temp;
p_fw_image++;
temp = temp|((0x05)<<10);
*p_fw_image = temp;
p_fw_image++;
/* write address byte 1;*/
temp = 0x82|MCI_MEMORY_ADDRESS_BYTE1 | (address & 0xFF00);
temp = temp<<10;
*p_fw_image = temp;
p_fw_image++;
temp = temp|((0x05)<<10);
*p_fw_image = temp;
p_fw_image++;
/* write address byte 0;*/
temp = 0x82|MCI_MEMORY_ADDRESS_BYTE0|((address & 0x00FF)<<8);
temp = temp<<10;
*p_fw_image = temp;
p_fw_image++;
temp = temp|((0x05)<<10);
*p_fw_image = temp;
p_fw_image++;
for (i = 0; i < 6; i++) {
*p_fw_image = 0xFFFFFFFF;
p_fw_image++;
}
}
static int cx231xx_load_firmware(struct cx231xx *dev)
{
static const unsigned char magic[8] = {
0xa7, 0x0d, 0x00, 0x00, 0x66, 0xbb, 0x55, 0xaa
};
const struct firmware *firmware;
int i, retval = 0;
u32 value = 0;
u32 gpio_output = 0;
/*u32 checksum = 0;*/
/*u32 *dataptr;*/
u32 transfer_size = 0;
u32 fw_data = 0;
u32 address = 0;
/*u32 current_fw[800];*/
u32 *p_current_fw, *p_fw;
u32 *p_fw_data;
int frame = 0;
u16 _buffer_size = 4096;
u8 *p_buffer;
p_current_fw = vmalloc(1884180 * 4);
p_fw = p_current_fw;
if (p_current_fw == NULL) {
dprintk(2, "FAIL!!!\n");
return -1;
}
p_buffer = vmalloc(4096);
if (p_buffer == NULL) {
dprintk(2, "FAIL!!!\n");
return -1;
}
dprintk(2, "%s()\n", __func__);
/* Save GPIO settings before reset of APU */
retval |= mc417_memory_read(dev, 0x9020, &gpio_output);
retval |= mc417_memory_read(dev, 0x900C, &value);
retval = mc417_register_write(dev,
IVTV_REG_VPU, 0xFFFFFFED);
retval |= mc417_register_write(dev,
IVTV_REG_HW_BLOCKS, IVTV_CMD_HW_BLOCKS_RST);
retval |= mc417_register_write(dev,
IVTV_REG_ENC_SDRAM_REFRESH, 0x80000800);
retval |= mc417_register_write(dev,
IVTV_REG_ENC_SDRAM_PRECHARGE, 0x1A);
retval |= mc417_register_write(dev,
IVTV_REG_APU, 0);
if (retval != 0) {
printk(KERN_ERR "%s: Error with mc417_register_write\n",
__func__);
return -1;
}
retval = request_firmware(&firmware, CX231xx_FIRM_IMAGE_NAME,
&dev->udev->dev);
if (retval != 0) {
printk(KERN_ERR
"ERROR: Hotplug firmware request failed (%s).\n",
CX231xx_FIRM_IMAGE_NAME);
printk(KERN_ERR "Please fix your hotplug setup, the board will "
"not work without firmware loaded!\n");
return -1;
}
if (firmware->size != CX231xx_FIRM_IMAGE_SIZE) {
printk(KERN_ERR "ERROR: Firmware size mismatch "
"(have %zd, expected %d)\n",
firmware->size, CX231xx_FIRM_IMAGE_SIZE);
release_firmware(firmware);
return -1;
}
if (0 != memcmp(firmware->data, magic, 8)) {
printk(KERN_ERR
"ERROR: Firmware magic mismatch, wrong file?\n");
release_firmware(firmware);
return -1;
}
initGPIO(dev);
/* transfer to the chip */
dprintk(2, "Loading firmware to GPIO...\n");
p_fw_data = (u32 *)firmware->data;
dprintk(2, "firmware->size=%zd\n", firmware->size);
for (transfer_size = 0; transfer_size < firmware->size;
transfer_size += 4) {
fw_data = *p_fw_data;
mciWriteMemoryToGPIO(dev, address, fw_data, p_current_fw);
address = address + 1;
p_current_fw += 20;
p_fw_data += 1;
}
/*download the firmware by ep5-out*/
for (frame = 0; frame < (int)(CX231xx_FIRM_IMAGE_SIZE*20/_buffer_size);
frame++) {
for (i = 0; i < _buffer_size; i++) {
*(p_buffer + i) = (u8)(*(p_fw + (frame * 128 * 8 + (i / 4))) & 0x000000FF);
i++;
*(p_buffer + i) = (u8)((*(p_fw + (frame * 128 * 8 + (i / 4))) & 0x0000FF00) >> 8);
i++;
*(p_buffer + i) = (u8)((*(p_fw + (frame * 128 * 8 + (i / 4))) & 0x00FF0000) >> 16);
i++;
*(p_buffer + i) = (u8)((*(p_fw + (frame * 128 * 8 + (i / 4))) & 0xFF000000) >> 24);
}
cx231xx_ep5_bulkout(dev, p_buffer, _buffer_size);
}
p_current_fw = p_fw;
vfree(p_current_fw);
p_current_fw = NULL;
uninitGPIO(dev);
release_firmware(firmware);
dprintk(1, "Firmware upload successful.\n");
retval |= mc417_register_write(dev, IVTV_REG_HW_BLOCKS,
IVTV_CMD_HW_BLOCKS_RST);
if (retval < 0) {
printk(KERN_ERR "%s: Error with mc417_register_write\n",
__func__);
return retval;
}
/* F/W power up disturbs the GPIOs, restore state */
retval |= mc417_register_write(dev, 0x9020, gpio_output);
retval |= mc417_register_write(dev, 0x900C, value);
retval |= mc417_register_read(dev, IVTV_REG_VPU, &value);
retval |= mc417_register_write(dev, IVTV_REG_VPU, value & 0xFFFFFFE8);
if (retval < 0) {
printk(KERN_ERR "%s: Error with mc417_register_write\n",
__func__);
return retval;
}
return 0;
}
static void cx231xx_417_check_encoder(struct cx231xx *dev)
{
u32 status, seq;
status = 0;
seq = 0;
cx231xx_api_cmd(dev, CX2341X_ENC_GET_SEQ_END, 0, 2, &status, &seq);
dprintk(1, "%s() status = %d, seq = %d\n", __func__, status, seq);
}
static void cx231xx_codec_settings(struct cx231xx *dev)
{
dprintk(1, "%s()\n", __func__);
/* assign frame size */
cx231xx_api_cmd(dev, CX2341X_ENC_SET_FRAME_SIZE, 2, 0,
dev->ts1.height, dev->ts1.width);
dev->mpeg_params.width = dev->ts1.width;
dev->mpeg_params.height = dev->ts1.height;
cx2341x_update(dev, cx231xx_mbox_func, NULL, &dev->mpeg_params);
cx231xx_api_cmd(dev, CX2341X_ENC_MISC, 2, 0, 3, 1);
cx231xx_api_cmd(dev, CX2341X_ENC_MISC, 2, 0, 4, 1);
}
static int cx231xx_initialize_codec(struct cx231xx *dev)
{
int version;
int retval;
u32 i, data[7];
u32 val = 0;
dprintk(1, "%s()\n", __func__);
cx231xx_disable656(dev);
retval = cx231xx_api_cmd(dev, CX2341X_ENC_PING_FW, 0, 0); /* ping */
if (retval < 0) {
dprintk(2, "%s() PING OK\n", __func__);
retval = cx231xx_load_firmware(dev);
if (retval < 0) {
printk(KERN_ERR "%s() f/w load failed\n", __func__);
return retval;
}
retval = cx231xx_find_mailbox(dev);
if (retval < 0) {
printk(KERN_ERR "%s() mailbox < 0, error\n",
__func__);
return -1;
}
dev->cx23417_mailbox = retval;
retval = cx231xx_api_cmd(dev, CX2341X_ENC_PING_FW, 0, 0);
if (retval < 0) {
printk(KERN_ERR
"ERROR: cx23417 firmware ping failed!\n");
return -1;
}
retval = cx231xx_api_cmd(dev, CX2341X_ENC_GET_VERSION, 0, 1,
&version);
if (retval < 0) {
printk(KERN_ERR "ERROR: cx23417 firmware get encoder :"
"version failed!\n");
return -1;
}
dprintk(1, "cx23417 firmware version is 0x%08x\n", version);
msleep(200);
}
for (i = 0; i < 1; i++) {
retval = mc417_register_read(dev, 0x20f8, &val);
dprintk(3, "***before enable656() VIM Capture Lines =%d ***\n",
val);
if (retval < 0)
return retval;
}
cx231xx_enable656(dev);
/* stop mpeg capture */
cx231xx_api_cmd(dev, CX2341X_ENC_STOP_CAPTURE,
3, 0, 1, 3, 4);
cx231xx_codec_settings(dev);
msleep(60);
/* cx231xx_api_cmd(dev, CX2341X_ENC_SET_NUM_VSYNC_LINES, 2, 0,
CX231xx_FIELD1_SAA7115, CX231xx_FIELD2_SAA7115);
cx231xx_api_cmd(dev, CX2341X_ENC_SET_PLACEHOLDER, 12, 0,
CX231xx_CUSTOM_EXTENSION_USR_DATA, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0);
*/
/* Setup to capture VBI */
data[0] = 0x0001BD00;
data[1] = 1; /* frames per interrupt */
data[2] = 4; /* total bufs */
data[3] = 0x91559155; /* start codes */
data[4] = 0x206080C0; /* stop codes */
data[5] = 6; /* lines */
data[6] = 64; /* BPL */
/*
cx231xx_api_cmd(dev, CX2341X_ENC_SET_VBI_CONFIG, 7, 0, data[0], data[1],
data[2], data[3], data[4], data[5], data[6]);
for (i = 2; i <= 24; i++) {
int valid;
valid = ((i >= 19) && (i <= 21));
cx231xx_api_cmd(dev, CX2341X_ENC_SET_VBI_LINE, 5, 0, i,
valid, 0 , 0, 0);
cx231xx_api_cmd(dev, CX2341X_ENC_SET_VBI_LINE, 5, 0,
i | 0x80000000, valid, 0, 0, 0);
}
*/
/* cx231xx_api_cmd(dev, CX2341X_ENC_MUTE_AUDIO, 1, 0, CX231xx_UNMUTE);
msleep(60);
*/
/* initialize the video input */
retval = cx231xx_api_cmd(dev, CX2341X_ENC_INITIALIZE_INPUT, 0, 0);
if (retval < 0)
return retval;
msleep(60);
/* Enable VIP style pixel invalidation so we work with scaled mode */
mc417_memory_write(dev, 2120, 0x00000080);
/* start capturing to the host interface */
retval = cx231xx_api_cmd(dev, CX2341X_ENC_START_CAPTURE, 2, 0,
CX231xx_MPEG_CAPTURE, CX231xx_RAW_BITS_NONE);
if (retval < 0)
return retval;
msleep(10);
for (i = 0; i < 1; i++) {
mc417_register_read(dev, 0x20f8, &val);
dprintk(3, "***VIM Capture Lines =%d ***\n", val);
}
return 0;
}
/* ------------------------------------------------------------------ */
static int bb_buf_setup(struct videobuf_queue *q,
unsigned int *count, unsigned int *size)
{
struct cx231xx_fh *fh = q->priv_data;
fh->dev->ts1.ts_packet_size = mpeglinesize;
fh->dev->ts1.ts_packet_count = mpeglines;
*size = fh->dev->ts1.ts_packet_size * fh->dev->ts1.ts_packet_count;
*count = mpegbufs;
return 0;
}
static void free_buffer(struct videobuf_queue *vq, struct cx231xx_buffer *buf)
{
struct cx231xx_fh *fh = vq->priv_data;
struct cx231xx *dev = fh->dev;
unsigned long flags = 0;
if (in_interrupt())
BUG();
spin_lock_irqsave(&dev->video_mode.slock, flags);
if (dev->USE_ISO) {
if (dev->video_mode.isoc_ctl.buf == buf)
dev->video_mode.isoc_ctl.buf = NULL;
} else {
if (dev->video_mode.bulk_ctl.buf == buf)
dev->video_mode.bulk_ctl.buf = NULL;
}
spin_unlock_irqrestore(&dev->video_mode.slock, flags);
videobuf_waiton(vq, &buf->vb, 0, 0);
videobuf_vmalloc_free(&buf->vb);
buf->vb.state = VIDEOBUF_NEEDS_INIT;
}
static void buffer_copy(struct cx231xx *dev, char *data, int len, struct urb *urb,
struct cx231xx_dmaqueue *dma_q)
{
void *vbuf;
struct cx231xx_buffer *buf;
u32 tail_data = 0;
char *p_data;
if (dma_q->mpeg_buffer_done == 0) {
if (list_empty(&dma_q->active))
return;
buf = list_entry(dma_q->active.next,
struct cx231xx_buffer, vb.queue);
dev->video_mode.isoc_ctl.buf = buf;
dma_q->mpeg_buffer_done = 1;
}
/* Fill buffer */
buf = dev->video_mode.isoc_ctl.buf;
vbuf = videobuf_to_vmalloc(&buf->vb);
if ((dma_q->mpeg_buffer_completed+len) <
mpeglines*mpeglinesize) {
if (dma_q->add_ps_package_head ==
CX231XX_NEED_ADD_PS_PACKAGE_HEAD) {
memcpy(vbuf+dma_q->mpeg_buffer_completed,
dma_q->ps_head, 3);
dma_q->mpeg_buffer_completed =
dma_q->mpeg_buffer_completed + 3;
dma_q->add_ps_package_head =
CX231XX_NONEED_PS_PACKAGE_HEAD;
}
memcpy(vbuf+dma_q->mpeg_buffer_completed, data, len);
dma_q->mpeg_buffer_completed =
dma_q->mpeg_buffer_completed + len;
} else {
dma_q->mpeg_buffer_done = 0;
tail_data =
mpeglines*mpeglinesize - dma_q->mpeg_buffer_completed;
memcpy(vbuf+dma_q->mpeg_buffer_completed,
data, tail_data);
buf->vb.state = VIDEOBUF_DONE;
buf->vb.field_count++;
do_gettimeofday(&buf->vb.ts);
list_del(&buf->vb.queue);
wake_up(&buf->vb.done);
dma_q->mpeg_buffer_completed = 0;
if (len - tail_data > 0) {
p_data = data + tail_data;
dma_q->left_data_count = len - tail_data;
memcpy(dma_q->p_left_data,
p_data, len - tail_data);
}
}
return;
}
static void buffer_filled(char *data, int len, struct urb *urb,
struct cx231xx_dmaqueue *dma_q)
{
void *vbuf;
struct cx231xx_buffer *buf;
if (list_empty(&dma_q->active))
return;
buf = list_entry(dma_q->active.next,
struct cx231xx_buffer, vb.queue);
/* Fill buffer */
vbuf = videobuf_to_vmalloc(&buf->vb);
memcpy(vbuf, data, len);
buf->vb.state = VIDEOBUF_DONE;
buf->vb.field_count++;
do_gettimeofday(&buf->vb.ts);
list_del(&buf->vb.queue);
wake_up(&buf->vb.done);
return;
}
static inline int cx231xx_isoc_copy(struct cx231xx *dev, struct urb *urb)
{
struct cx231xx_dmaqueue *dma_q = urb->context;
unsigned char *p_buffer;
u32 buffer_size = 0;
u32 i = 0;
for (i = 0; i < urb->number_of_packets; i++) {
if (dma_q->left_data_count > 0) {
buffer_copy(dev, dma_q->p_left_data,
dma_q->left_data_count, urb, dma_q);
dma_q->mpeg_buffer_completed = dma_q->left_data_count;
dma_q->left_data_count = 0;
}
p_buffer = urb->transfer_buffer +
urb->iso_frame_desc[i].offset;
buffer_size = urb->iso_frame_desc[i].actual_length;
if (buffer_size > 0)
buffer_copy(dev, p_buffer, buffer_size, urb, dma_q);
}
return 0;
}
static inline int cx231xx_bulk_copy(struct cx231xx *dev, struct urb *urb)
{
/*char *outp;*/
/*struct cx231xx_buffer *buf;*/
struct cx231xx_dmaqueue *dma_q = urb->context;
unsigned char *p_buffer, *buffer;
u32 buffer_size = 0;
p_buffer = urb->transfer_buffer;
buffer_size = urb->actual_length;
buffer = kmalloc(buffer_size, GFP_ATOMIC);
memcpy(buffer, dma_q->ps_head, 3);
memcpy(buffer+3, p_buffer, buffer_size-3);
memcpy(dma_q->ps_head, p_buffer+buffer_size-3, 3);
p_buffer = buffer;
buffer_filled(p_buffer, buffer_size, urb, dma_q);
kfree(buffer);
return 0;
}
static int bb_buf_prepare(struct videobuf_queue *q,
struct videobuf_buffer *vb, enum v4l2_field field)
{
struct cx231xx_fh *fh = q->priv_data;
struct cx231xx_buffer *buf =
container_of(vb, struct cx231xx_buffer, vb);
struct cx231xx *dev = fh->dev;
int rc = 0, urb_init = 0;
int size = fh->dev->ts1.ts_packet_size * fh->dev->ts1.ts_packet_count;
dma_qq = &dev->video_mode.vidq;
if (0 != buf->vb.baddr && buf->vb.bsize < size)
return -EINVAL;
buf->vb.width = fh->dev->ts1.ts_packet_size;
buf->vb.height = fh->dev->ts1.ts_packet_count;
buf->vb.size = size;
buf->vb.field = field;
if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
rc = videobuf_iolock(q, &buf->vb, NULL);
if (rc < 0)
goto fail;
}
if (dev->USE_ISO) {
if (!dev->video_mode.isoc_ctl.num_bufs)
urb_init = 1;
} else {
if (!dev->video_mode.bulk_ctl.num_bufs)
urb_init = 1;
}
/*cx231xx_info("urb_init=%d dev->video_mode.max_pkt_size=%d\n",
urb_init, dev->video_mode.max_pkt_size);*/
dev->mode_tv = 1;
if (urb_init) {
rc = cx231xx_set_mode(dev, CX231XX_DIGITAL_MODE);
rc = cx231xx_unmute_audio(dev);
if (dev->USE_ISO) {
cx231xx_set_alt_setting(dev, INDEX_TS1, 4);
rc = cx231xx_init_isoc(dev, mpeglines,
mpegbufs,
dev->ts1_mode.max_pkt_size,
cx231xx_isoc_copy);
} else {
cx231xx_set_alt_setting(dev, INDEX_TS1, 0);
rc = cx231xx_init_bulk(dev, mpeglines,
mpegbufs,
dev->ts1_mode.max_pkt_size,
cx231xx_bulk_copy);
}
if (rc < 0)
goto fail;
}
buf->vb.state = VIDEOBUF_PREPARED;
return 0;
fail:
free_buffer(q, buf);
return rc;
}
static void bb_buf_queue(struct videobuf_queue *q,
struct videobuf_buffer *vb)
{
struct cx231xx_fh *fh = q->priv_data;
struct cx231xx_buffer *buf =
container_of(vb, struct cx231xx_buffer, vb);
struct cx231xx *dev = fh->dev;
struct cx231xx_dmaqueue *vidq = &dev->video_mode.vidq;
buf->vb.state = VIDEOBUF_QUEUED;
list_add_tail(&buf->vb.queue, &vidq->active);
}
static void bb_buf_release(struct videobuf_queue *q,
struct videobuf_buffer *vb)
{
struct cx231xx_buffer *buf =
container_of(vb, struct cx231xx_buffer, vb);
/*struct cx231xx_fh *fh = q->priv_data;*/
/*struct cx231xx *dev = (struct cx231xx *)fh->dev;*/
free_buffer(q, buf);
}
static struct videobuf_queue_ops cx231xx_qops = {
.buf_setup = bb_buf_setup,
.buf_prepare = bb_buf_prepare,
.buf_queue = bb_buf_queue,
.buf_release = bb_buf_release,
};
/* ------------------------------------------------------------------ */
static const u32 *ctrl_classes[] = {
cx2341x_mpeg_ctrls,
NULL
};
static int cx231xx_queryctrl(struct cx231xx *dev,
struct v4l2_queryctrl *qctrl)
{
qctrl->id = v4l2_ctrl_next(ctrl_classes, qctrl->id);
if (qctrl->id == 0)
return -EINVAL;
/* MPEG V4L2 controls */
if (cx2341x_ctrl_query(&dev->mpeg_params, qctrl))
qctrl->flags |= V4L2_CTRL_FLAG_DISABLED;
return 0;
}
static int cx231xx_querymenu(struct cx231xx *dev,
struct v4l2_querymenu *qmenu)
{
struct v4l2_queryctrl qctrl;
qctrl.id = qmenu->id;
cx231xx_queryctrl(dev, &qctrl);
return v4l2_ctrl_query_menu(qmenu, &qctrl,
cx2341x_ctrl_get_menu(&dev->mpeg_params, qmenu->id));
}
static int vidioc_g_std(struct file *file, void *fh0, v4l2_std_id *norm)
{
struct cx231xx_fh *fh = file->private_data;
struct cx231xx *dev = fh->dev;
*norm = dev->encodernorm.id;
return 0;
}
static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id *id)
{
struct cx231xx_fh *fh = file->private_data;
struct cx231xx *dev = fh->dev;
unsigned int i;
for (i = 0; i < ARRAY_SIZE(cx231xx_tvnorms); i++)
if (*id & cx231xx_tvnorms[i].id)
break;
if (i == ARRAY_SIZE(cx231xx_tvnorms))
return -EINVAL;
dev->encodernorm = cx231xx_tvnorms[i];
if (dev->encodernorm.id & 0xb000) {
dprintk(3, "encodernorm set to NTSC\n");
dev->norm = V4L2_STD_NTSC;
dev->ts1.height = 480;
dev->mpeg_params.is_50hz = 0;
} else {
dprintk(3, "encodernorm set to PAL\n");
dev->norm = V4L2_STD_PAL_B;
dev->ts1.height = 576;
dev->mpeg_params.is_50hz = 1;
}
call_all(dev, core, s_std, dev->norm);
/* do mode control overrides */
cx231xx_do_mode_ctrl_overrides(dev);
dprintk(3, "exit vidioc_s_std() i=0x%x\n", i);
return 0;
}
static int vidioc_g_audio(struct file *file, void *fh,
struct v4l2_audio *a)
{
struct v4l2_audio *vin = a;
int ret = -EINVAL;
if (vin->index > 0)
return ret;
strncpy(vin->name, "VideoGrabber Audio", 14);
vin->capability = V4L2_AUDCAP_STEREO;
return 0;
}
static int vidioc_enumaudio(struct file *file, void *fh,
struct v4l2_audio *a)
{
struct v4l2_audio *vin = a;
int ret = -EINVAL;
if (vin->index > 0)
return ret;
strncpy(vin->name, "VideoGrabber Audio", 14);
vin->capability = V4L2_AUDCAP_STEREO;
return 0;
}
static const char *iname[] = {
[CX231XX_VMUX_COMPOSITE1] = "Composite1",
[CX231XX_VMUX_SVIDEO] = "S-Video",
[CX231XX_VMUX_TELEVISION] = "Television",
[CX231XX_VMUX_CABLE] = "Cable TV",
[CX231XX_VMUX_DVB] = "DVB",
[CX231XX_VMUX_DEBUG] = "for debug only",
};
static int vidioc_enum_input(struct file *file, void *priv,
struct v4l2_input *i)
{
struct cx231xx_fh *fh = file->private_data;
struct cx231xx *dev = fh->dev;
struct cx231xx_input *input;
int n;
dprintk(3, "enter vidioc_enum_input()i->index=%d\n", i->index);
if (i->index >= 4)
return -EINVAL;
input = &cx231xx_boards[dev->model].input[i->index];
if (input->type == 0)
return -EINVAL;
/* FIXME
* strcpy(i->name, input->name); */
n = i->index;
strcpy(i->name, iname[INPUT(n)->type]);
if (input->type == CX231XX_VMUX_TELEVISION ||
input->type == CX231XX_VMUX_CABLE)
i->type = V4L2_INPUT_TYPE_TUNER;
else
i->type = V4L2_INPUT_TYPE_CAMERA;
return 0;
}
static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
{
*i = 0;
return 0;
}
static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
{
struct cx231xx_fh *fh = file->private_data;
struct cx231xx *dev = fh->dev;
dprintk(3, "enter vidioc_s_input() i=%d\n", i);
mutex_lock(&dev->lock);
video_mux(dev, i);
mutex_unlock(&dev->lock);
if (i >= 4)
return -EINVAL;
dev->input = i;
dprintk(3, "exit vidioc_s_input()\n");
return 0;
}
static int vidioc_g_tuner(struct file *file, void *priv,
struct v4l2_tuner *t)
{
return 0;
}
static int vidioc_s_tuner(struct file *file, void *priv,
struct v4l2_tuner *t)
{
return 0;
}
static int vidioc_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
return 0;
}
static int vidioc_s_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
return 0;
}
static int vidioc_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctl)
{
struct cx231xx_fh *fh = file->private_data;
struct cx231xx *dev = fh->dev;
dprintk(3, "enter vidioc_s_ctrl()\n");
/* Update the A/V core */
call_all(dev, core, s_ctrl, ctl);
dprintk(3, "exit vidioc_s_ctrl()\n");
return 0;
}
static struct v4l2_capability pvr_capability = {
.driver = "cx231xx",
.card = "VideoGrabber",
.bus_info = "usb",
.version = 1,
.capabilities = (V4L2_CAP_VIDEO_CAPTURE |
V4L2_CAP_TUNER | V4L2_CAP_AUDIO | V4L2_CAP_RADIO |
V4L2_CAP_STREAMING | V4L2_CAP_READWRITE),
};
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
memcpy(cap, &pvr_capability, sizeof(struct v4l2_capability));
return 0;
}
static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
if (f->index != 0)
return -EINVAL;
strlcpy(f->description, "MPEG", sizeof(f->description));
f->pixelformat = V4L2_PIX_FMT_MPEG;
return 0;
}
static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct cx231xx_fh *fh = file->private_data;
struct cx231xx *dev = fh->dev;
dprintk(3, "enter vidioc_g_fmt_vid_cap()\n");
f->fmt.pix.pixelformat = V4L2_PIX_FMT_MPEG;
f->fmt.pix.bytesperline = 0;
f->fmt.pix.sizeimage =
dev->ts1.ts_packet_size * dev->ts1.ts_packet_count;
f->fmt.pix.colorspace = 0;
f->fmt.pix.width = dev->ts1.width;
f->fmt.pix.height = dev->ts1.height;
f->fmt.pix.field = fh->vidq.field;
dprintk(1, "VIDIOC_G_FMT: w: %d, h: %d, f: %d\n",
dev->ts1.width, dev->ts1.height, fh->vidq.field);
dprintk(3, "exit vidioc_g_fmt_vid_cap()\n");
return 0;
}
static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct cx231xx_fh *fh = file->private_data;
struct cx231xx *dev = fh->dev;
dprintk(3, "enter vidioc_try_fmt_vid_cap()\n");
f->fmt.pix.pixelformat = V4L2_PIX_FMT_MPEG;
f->fmt.pix.bytesperline = 0;
f->fmt.pix.sizeimage =
dev->ts1.ts_packet_size * dev->ts1.ts_packet_count;
f->fmt.pix.colorspace = 0;
dprintk(1, "VIDIOC_TRY_FMT: w: %d, h: %d, f: %d\n",
dev->ts1.width, dev->ts1.height, fh->vidq.field);
dprintk(3, "exit vidioc_try_fmt_vid_cap()\n");
return 0;
}
static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
return 0;
}
static int vidioc_reqbufs(struct file *file, void *priv,
struct v4l2_requestbuffers *p)
{
struct cx231xx_fh *fh = file->private_data;
return videobuf_reqbufs(&fh->vidq, p);
}
static int vidioc_querybuf(struct file *file, void *priv,
struct v4l2_buffer *p)
{
struct cx231xx_fh *fh = file->private_data;
return videobuf_querybuf(&fh->vidq, p);
}
static int vidioc_qbuf(struct file *file, void *priv,
struct v4l2_buffer *p)
{
struct cx231xx_fh *fh = file->private_data;
return videobuf_qbuf(&fh->vidq, p);
}
static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b)
{
struct cx231xx_fh *fh = priv;
return videobuf_dqbuf(&fh->vidq, b, file->f_flags & O_NONBLOCK);
}
static int vidioc_streamon(struct file *file, void *priv,
enum v4l2_buf_type i)
{
struct cx231xx_fh *fh = file->private_data;
struct cx231xx *dev = fh->dev;
int rc = 0;
dprintk(3, "enter vidioc_streamon()\n");
cx231xx_set_alt_setting(dev, INDEX_TS1, 0);
rc = cx231xx_set_mode(dev, CX231XX_DIGITAL_MODE);
if (dev->USE_ISO)
rc = cx231xx_init_isoc(dev, CX231XX_NUM_PACKETS,
CX231XX_NUM_BUFS,
dev->video_mode.max_pkt_size,
cx231xx_isoc_copy);
else {
rc = cx231xx_init_bulk(dev, 320,
5,
dev->ts1_mode.max_pkt_size,
cx231xx_bulk_copy);
}
dprintk(3, "exit vidioc_streamon()\n");
return videobuf_streamon(&fh->vidq);
}
static int vidioc_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
{
struct cx231xx_fh *fh = file->private_data;
return videobuf_streamoff(&fh->vidq);
}
static int vidioc_g_ext_ctrls(struct file *file, void *priv,
struct v4l2_ext_controls *f)
{
struct cx231xx_fh *fh = priv;
struct cx231xx *dev = fh->dev;
dprintk(3, "enter vidioc_g_ext_ctrls()\n");
if (f->ctrl_class != V4L2_CTRL_CLASS_MPEG)
return -EINVAL;
dprintk(3, "exit vidioc_g_ext_ctrls()\n");
return cx2341x_ext_ctrls(&dev->mpeg_params, 0, f, VIDIOC_G_EXT_CTRLS);
}
static int vidioc_s_ext_ctrls(struct file *file, void *priv,
struct v4l2_ext_controls *f)
{
struct cx231xx_fh *fh = priv;
struct cx231xx *dev = fh->dev;
struct cx2341x_mpeg_params p;
int err;
dprintk(3, "enter vidioc_s_ext_ctrls()\n");
if (f->ctrl_class != V4L2_CTRL_CLASS_MPEG)
return -EINVAL;
p = dev->mpeg_params;
err = cx2341x_ext_ctrls(&p, 0, f, VIDIOC_TRY_EXT_CTRLS);
if (err == 0) {
err = cx2341x_update(dev, cx231xx_mbox_func,
&dev->mpeg_params, &p);
dev->mpeg_params = p;
}
return err;
return 0;
}
static int vidioc_try_ext_ctrls(struct file *file, void *priv,
struct v4l2_ext_controls *f)
{
struct cx231xx_fh *fh = priv;
struct cx231xx *dev = fh->dev;
struct cx2341x_mpeg_params p;
int err;
dprintk(3, "enter vidioc_try_ext_ctrls()\n");
if (f->ctrl_class != V4L2_CTRL_CLASS_MPEG)
return -EINVAL;
p = dev->mpeg_params;
err = cx2341x_ext_ctrls(&p, 0, f, VIDIOC_TRY_EXT_CTRLS);
dprintk(3, "exit vidioc_try_ext_ctrls() err=%d\n", err);
return err;
}
static int vidioc_log_status(struct file *file, void *priv)
{
struct cx231xx_fh *fh = priv;
struct cx231xx *dev = fh->dev;
char name[32 + 2];
snprintf(name, sizeof(name), "%s/2", dev->name);
dprintk(3,
"%s/2: ============ START LOG STATUS ============\n",
dev->name);
call_all(dev, core, log_status);
cx2341x_log_status(&dev->mpeg_params, name);
dprintk(3,
"%s/2: ============= END LOG STATUS =============\n",
dev->name);
return 0;
}
static int vidioc_querymenu(struct file *file, void *priv,
struct v4l2_querymenu *a)
{
struct cx231xx_fh *fh = priv;
struct cx231xx *dev = fh->dev;
dprintk(3, "enter vidioc_querymenu()\n");
dprintk(3, "exit vidioc_querymenu()\n");
return cx231xx_querymenu(dev, a);
}
static int vidioc_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *c)
{
struct cx231xx_fh *fh = priv;
struct cx231xx *dev = fh->dev;
dprintk(3, "enter vidioc_queryctrl()\n");
dprintk(3, "exit vidioc_queryctrl()\n");
return cx231xx_queryctrl(dev, c);
}
static int mpeg_open(struct file *file)
{
int minor = video_devdata(file)->minor;
struct cx231xx *h, *dev = NULL;
/*struct list_head *list;*/
struct cx231xx_fh *fh;
/*u32 value = 0;*/
dprintk(2, "%s()\n", __func__);
list_for_each_entry(h, &cx231xx_devlist, devlist) {
if (h->v4l_device->minor == minor)
dev = h;
}
if (dev == NULL)
return -ENODEV;
mutex_lock(&dev->lock);
/* allocate + initialize per filehandle data */
fh = kzalloc(sizeof(*fh), GFP_KERNEL);
if (NULL == fh) {
mutex_unlock(&dev->lock);
return -ENOMEM;
}
file->private_data = fh;
fh->dev = dev;
videobuf_queue_vmalloc_init(&fh->vidq, &cx231xx_qops,
NULL, &dev->video_mode.slock,
V4L2_BUF_TYPE_VIDEO_CAPTURE, V4L2_FIELD_INTERLACED,
sizeof(struct cx231xx_buffer), fh, NULL);
/*
videobuf_queue_sg_init(&fh->vidq, &cx231xx_qops,
&dev->udev->dev, &dev->ts1.slock,
V4L2_BUF_TYPE_VIDEO_CAPTURE,
V4L2_FIELD_INTERLACED,
sizeof(struct cx231xx_buffer),
fh, NULL);
*/
cx231xx_set_alt_setting(dev, INDEX_VANC, 1);
cx231xx_set_gpio_value(dev, 2, 0);
cx231xx_initialize_codec(dev);
mutex_unlock(&dev->lock);
cx231xx_start_TS1(dev);
return 0;
}
static int mpeg_release(struct file *file)
{
struct cx231xx_fh *fh = file->private_data;
struct cx231xx *dev = fh->dev;
dprintk(3, "mpeg_release()! dev=0x%p\n", dev);
if (!dev) {
dprintk(3, "abort!!!\n");
return 0;
}
mutex_lock(&dev->lock);
cx231xx_stop_TS1(dev);
/* do this before setting alternate! */
if (dev->USE_ISO)
cx231xx_uninit_isoc(dev);
else
cx231xx_uninit_bulk(dev);
cx231xx_set_mode(dev, CX231XX_SUSPEND);
cx231xx_api_cmd(fh->dev, CX2341X_ENC_STOP_CAPTURE, 3, 0,
CX231xx_END_NOW, CX231xx_MPEG_CAPTURE,
CX231xx_RAW_BITS_NONE);
/* FIXME: Review this crap */
/* Shut device down on last close */
if (atomic_cmpxchg(&fh->v4l_reading, 1, 0) == 1) {
if (atomic_dec_return(&dev->v4l_reader_count) == 0) {
/* stop mpeg capture */
msleep(500);
cx231xx_417_check_encoder(dev);
}
}
if (fh->vidq.streaming)
videobuf_streamoff(&fh->vidq);
if (fh->vidq.reading)
videobuf_read_stop(&fh->vidq);
videobuf_mmap_free(&fh->vidq);
file->private_data = NULL;
kfree(fh);
mutex_unlock(&dev->lock);
return 0;
}
static ssize_t mpeg_read(struct file *file, char __user *data,
size_t count, loff_t *ppos)
{
struct cx231xx_fh *fh = file->private_data;
struct cx231xx *dev = fh->dev;
/* Deal w/ A/V decoder * and mpeg encoder sync issues. */
/* Start mpeg encoder on first read. */
if (atomic_cmpxchg(&fh->v4l_reading, 0, 1) == 0) {
if (atomic_inc_return(&dev->v4l_reader_count) == 1) {
if (cx231xx_initialize_codec(dev) < 0)
return -EINVAL;
}
}
return videobuf_read_stream(&fh->vidq, data, count, ppos, 0,
file->f_flags & O_NONBLOCK);
}
static unsigned int mpeg_poll(struct file *file,
struct poll_table_struct *wait)
{
struct cx231xx_fh *fh = file->private_data;
/*struct cx231xx *dev = fh->dev;*/
/*dprintk(2, "%s\n", __func__);*/
return videobuf_poll_stream(file, &fh->vidq, wait);
}
static int mpeg_mmap(struct file *file, struct vm_area_struct *vma)
{
struct cx231xx_fh *fh = file->private_data;
struct cx231xx *dev = fh->dev;
dprintk(2, "%s()\n", __func__);
return videobuf_mmap_mapper(&fh->vidq, vma);
}
static struct v4l2_file_operations mpeg_fops = {
.owner = THIS_MODULE,
.open = mpeg_open,
.release = mpeg_release,
.read = mpeg_read,
.poll = mpeg_poll,
.mmap = mpeg_mmap,
.ioctl = video_ioctl2,
};
static const struct v4l2_ioctl_ops mpeg_ioctl_ops = {
.vidioc_s_std = vidioc_s_std,
.vidioc_g_std = vidioc_g_std,
.vidioc_enum_input = vidioc_enum_input,
.vidioc_enumaudio = vidioc_enumaudio,
.vidioc_g_audio = vidioc_g_audio,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
.vidioc_g_tuner = vidioc_g_tuner,
.vidioc_s_tuner = vidioc_s_tuner,
.vidioc_g_frequency = vidioc_g_frequency,
.vidioc_s_frequency = vidioc_s_frequency,
.vidioc_s_ctrl = vidioc_s_ctrl,
.vidioc_querycap = vidioc_querycap,
.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
.vidioc_reqbufs = vidioc_reqbufs,
.vidioc_querybuf = vidioc_querybuf,
.vidioc_qbuf = vidioc_qbuf,
.vidioc_dqbuf = vidioc_dqbuf,
.vidioc_streamon = vidioc_streamon,
.vidioc_streamoff = vidioc_streamoff,
.vidioc_g_ext_ctrls = vidioc_g_ext_ctrls,
.vidioc_s_ext_ctrls = vidioc_s_ext_ctrls,
.vidioc_try_ext_ctrls = vidioc_try_ext_ctrls,
.vidioc_log_status = vidioc_log_status,
.vidioc_querymenu = vidioc_querymenu,
.vidioc_queryctrl = vidioc_queryctrl,
/* .vidioc_g_chip_ident = cx231xx_g_chip_ident,*/
#ifdef CONFIG_VIDEO_ADV_DEBUG
/* .vidioc_g_register = cx231xx_g_register,*/
/* .vidioc_s_register = cx231xx_s_register,*/
#endif
};
static struct video_device cx231xx_mpeg_template = {
.name = "cx231xx",
.fops = &mpeg_fops,
.ioctl_ops = &mpeg_ioctl_ops,
.minor = -1,
.tvnorms = CX231xx_NORMS,
.current_norm = V4L2_STD_NTSC_M,
};
void cx231xx_417_unregister(struct cx231xx *dev)
{
dprintk(1, "%s()\n", __func__);
dprintk(3, "%s()\n", __func__);
if (dev->v4l_device) {
if (-1 != dev->v4l_device->minor)
video_unregister_device(dev->v4l_device);
else
video_device_release(dev->v4l_device);
dev->v4l_device = NULL;
}
}
static struct video_device *cx231xx_video_dev_alloc(
struct cx231xx *dev,
struct usb_device *usbdev,
struct video_device *template,
char *type)
{
struct video_device *vfd;
dprintk(1, "%s()\n", __func__);
vfd = video_device_alloc();
if (NULL == vfd)
return NULL;
*vfd = *template;
vfd->minor = -1;
snprintf(vfd->name, sizeof(vfd->name), "%s %s (%s)", dev->name,
type, cx231xx_boards[dev->model].name);
vfd->v4l2_dev = &dev->v4l2_dev;
vfd->release = video_device_release;
return vfd;
}
int cx231xx_417_register(struct cx231xx *dev)
{
/* FIXME: Port1 hardcoded here */
int err = -ENODEV;
struct cx231xx_tsport *tsport = &dev->ts1;
dprintk(1, "%s()\n", __func__);
/* Set default TV standard */
dev->encodernorm = cx231xx_tvnorms[0];
if (dev->encodernorm.id & V4L2_STD_525_60)
tsport->height = 480;
else
tsport->height = 576;
tsport->width = 720;
cx2341x_fill_defaults(&dev->mpeg_params);
dev->norm = V4L2_STD_NTSC;
dev->mpeg_params.port = CX2341X_PORT_SERIAL;
/* Allocate and initialize V4L video device */
dev->v4l_device = cx231xx_video_dev_alloc(dev,
dev->udev, &cx231xx_mpeg_template, "mpeg");
err = video_register_device(dev->v4l_device,
VFL_TYPE_GRABBER, -1);
if (err < 0) {
dprintk(3, "%s: can't register mpeg device\n", dev->name);
return err;
}
dprintk(3, "%s: registered device video%d [mpeg]\n",
dev->name, dev->v4l_device->num);
return 0;
}
| gpl-2.0 |
obek/linux-sunxi | drivers/media/video/saa7134/saa7134-input.c | 4812 | 27293 | /*
*
* handle saa7134 IR remotes via linux kernel input layer.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include "saa7134-reg.h"
#include "saa7134.h"
#define MODULE_NAME "saa7134"
static unsigned int disable_ir;
module_param(disable_ir, int, 0444);
MODULE_PARM_DESC(disable_ir,"disable infrared remote support");
static unsigned int ir_debug;
module_param(ir_debug, int, 0644);
MODULE_PARM_DESC(ir_debug,"enable debug messages [IR]");
static int pinnacle_remote;
module_param(pinnacle_remote, int, 0644); /* Choose Pinnacle PCTV remote */
MODULE_PARM_DESC(pinnacle_remote, "Specify Pinnacle PCTV remote: 0=coloured, 1=grey (defaults to 0)");
#define dprintk(fmt, arg...) if (ir_debug) \
printk(KERN_DEBUG "%s/ir: " fmt, dev->name , ## arg)
#define i2cdprintk(fmt, arg...) if (ir_debug) \
printk(KERN_DEBUG "%s/ir: " fmt, ir->name , ## arg)
/* Helper function for raw decoding at GPIO16 or GPIO18 */
static int saa7134_raw_decode_irq(struct saa7134_dev *dev);
/* -------------------- GPIO generic keycode builder -------------------- */
static int build_key(struct saa7134_dev *dev)
{
struct saa7134_card_ir *ir = dev->remote;
u32 gpio, data;
/* here comes the additional handshake steps for some cards */
switch (dev->board) {
case SAA7134_BOARD_GOTVIEW_7135:
saa_setb(SAA7134_GPIO_GPSTATUS1, 0x80);
saa_clearb(SAA7134_GPIO_GPSTATUS1, 0x80);
break;
}
/* rising SAA7134_GPIO_GPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3,SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3,SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
if (ir->polling) {
if (ir->last_gpio == gpio)
return 0;
ir->last_gpio = gpio;
}
data = ir_extract_bits(gpio, ir->mask_keycode);
dprintk("build_key gpio=0x%x mask=0x%x data=%d\n",
gpio, ir->mask_keycode, data);
switch (dev->board) {
case SAA7134_BOARD_KWORLD_PLUS_TV_ANALOG:
if (data == ir->mask_keycode)
rc_keyup(ir->dev);
else
rc_keydown_notimeout(ir->dev, data, 0);
return 0;
}
if (ir->polling) {
if ((ir->mask_keydown && (0 != (gpio & ir->mask_keydown))) ||
(ir->mask_keyup && (0 == (gpio & ir->mask_keyup)))) {
rc_keydown_notimeout(ir->dev, data, 0);
} else {
rc_keyup(ir->dev);
}
}
else { /* IRQ driven mode - handle key press and release in one go */
if ((ir->mask_keydown && (0 != (gpio & ir->mask_keydown))) ||
(ir->mask_keyup && (0 == (gpio & ir->mask_keyup)))) {
rc_keydown_notimeout(ir->dev, data, 0);
rc_keyup(ir->dev);
}
}
return 0;
}
/* --------------------- Chip specific I2C key builders ----------------- */
static int get_key_flydvb_trio(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
int gpio;
int attempt = 0;
unsigned char b;
/* We need this to access GPI Used by the saa_readl macro. */
struct saa7134_dev *dev = ir->c->adapter->algo_data;
if (dev == NULL) {
i2cdprintk("get_key_flydvb_trio: "
"ir->c->adapter->algo_data is NULL!\n");
return -EIO;
}
/* rising SAA7134_GPIGPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
if (0x40000 & ~gpio)
return 0; /* No button press */
/* No button press - only before first key pressed */
if (b == 0xFF)
return 0;
/* poll IR chip */
/* weak up the IR chip */
b = 0;
while (1 != i2c_master_send(ir->c, &b, 1)) {
if ((attempt++) < 10) {
/*
* wait a bit for next attempt -
* I don't know how make it better
*/
msleep(10);
continue;
}
i2cdprintk("send wake up byte to pic16C505 (IR chip)"
"failed %dx\n", attempt);
return -EIO;
}
if (1 != i2c_master_recv(ir->c, &b, 1)) {
i2cdprintk("read error\n");
return -EIO;
}
*ir_key = b;
*ir_raw = b;
return 1;
}
static int get_key_msi_tvanywhere_plus(struct IR_i2c *ir, u32 *ir_key,
u32 *ir_raw)
{
unsigned char b;
int gpio;
/* <dev> is needed to access GPIO. Used by the saa_readl macro. */
struct saa7134_dev *dev = ir->c->adapter->algo_data;
if (dev == NULL) {
i2cdprintk("get_key_msi_tvanywhere_plus: "
"ir->c->adapter->algo_data is NULL!\n");
return -EIO;
}
/* rising SAA7134_GPIO_GPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
/* GPIO&0x40 is pulsed low when a button is pressed. Don't do
I2C receive if gpio&0x40 is not low. */
if (gpio & 0x40)
return 0; /* No button press */
/* GPIO says there is a button press. Get it. */
if (1 != i2c_master_recv(ir->c, &b, 1)) {
i2cdprintk("read error\n");
return -EIO;
}
/* No button press */
if (b == 0xff)
return 0;
/* Button pressed */
dprintk("get_key_msi_tvanywhere_plus: Key = 0x%02X\n", b);
*ir_key = b;
*ir_raw = b;
return 1;
}
/* copied and modified from get_key_msi_tvanywhere_plus() */
static int get_key_kworld_pc150u(struct IR_i2c *ir, u32 *ir_key,
u32 *ir_raw)
{
unsigned char b;
unsigned int gpio;
/* <dev> is needed to access GPIO. Used by the saa_readl macro. */
struct saa7134_dev *dev = ir->c->adapter->algo_data;
if (dev == NULL) {
i2cdprintk("get_key_kworld_pc150u: "
"ir->c->adapter->algo_data is NULL!\n");
return -EIO;
}
/* rising SAA7134_GPIO_GPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
/* GPIO&0x100 is pulsed low when a button is pressed. Don't do
I2C receive if gpio&0x100 is not low. */
if (gpio & 0x100)
return 0; /* No button press */
/* GPIO says there is a button press. Get it. */
if (1 != i2c_master_recv(ir->c, &b, 1)) {
i2cdprintk("read error\n");
return -EIO;
}
/* No button press */
if (b == 0xff)
return 0;
/* Button pressed */
dprintk("get_key_kworld_pc150u: Key = 0x%02X\n", b);
*ir_key = b;
*ir_raw = b;
return 1;
}
static int get_key_purpletv(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
unsigned char b;
/* poll IR chip */
if (1 != i2c_master_recv(ir->c, &b, 1)) {
i2cdprintk("read error\n");
return -EIO;
}
/* no button press */
if (b==0)
return 0;
/* repeating */
if (b & 0x80)
return 1;
*ir_key = b;
*ir_raw = b;
return 1;
}
static int get_key_hvr1110(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
unsigned char buf[5];
/* poll IR chip */
if (5 != i2c_master_recv(ir->c, buf, 5))
return -EIO;
/* Check if some key were pressed */
if (!(buf[0] & 0x80))
return 0;
/*
* buf[3] & 0x80 is always high.
* buf[3] & 0x40 is a parity bit. A repeat event is marked
* by preserving it into two separate readings
* buf[4] bits 0 and 1, and buf[1] and buf[2] are always
* zero.
*/
*ir_key = 0x1fff & ((buf[3] << 8) | (buf[4] >> 2));
*ir_raw = *ir_key;
return 1;
}
static int get_key_beholdm6xx(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
unsigned char data[12];
u32 gpio;
struct saa7134_dev *dev = ir->c->adapter->algo_data;
/* rising SAA7134_GPIO_GPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
if (0x400000 & ~gpio)
return 0; /* No button press */
ir->c->addr = 0x5a >> 1;
if (12 != i2c_master_recv(ir->c, data, 12)) {
i2cdprintk("read error\n");
return -EIO;
}
if (data[9] != (unsigned char)(~data[8]))
return 0;
*ir_raw = ((data[10] << 16) | (data[11] << 8) | (data[9] << 0));
*ir_key = *ir_raw;
return 1;
}
/* Common (grey or coloured) pinnacle PCTV remote handling
*
*/
static int get_key_pinnacle(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw,
int parity_offset, int marker, int code_modulo)
{
unsigned char b[4];
unsigned int start = 0,parity = 0,code = 0;
/* poll IR chip */
if (4 != i2c_master_recv(ir->c, b, 4)) {
i2cdprintk("read error\n");
return -EIO;
}
for (start = 0; start < ARRAY_SIZE(b); start++) {
if (b[start] == marker) {
code=b[(start+parity_offset + 1) % 4];
parity=b[(start+parity_offset) % 4];
}
}
/* Empty Request */
if (parity == 0)
return 0;
/* Repeating... */
if (ir->old == parity)
return 0;
ir->old = parity;
/* drop special codes when a key is held down a long time for the grey controller
In this case, the second bit of the code is asserted */
if (marker == 0xfe && (code & 0x40))
return 0;
code %= code_modulo;
*ir_raw = code;
*ir_key = code;
i2cdprintk("Pinnacle PCTV key %02x\n", code);
return 1;
}
/* The grey pinnacle PCTV remote
*
* There are one issue with this remote:
* - I2c packet does not change when the same key is pressed quickly. The workaround
* is to hold down each key for about half a second, so that another code is generated
* in the i2c packet, and the function can distinguish key presses.
*
* Sylvain Pasche <sylvain.pasche@gmail.com>
*/
static int get_key_pinnacle_grey(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
return get_key_pinnacle(ir, ir_key, ir_raw, 1, 0xfe, 0xff);
}
/* The new pinnacle PCTV remote (with the colored buttons)
*
* Ricardo Cerqueira <v4l@cerqueira.org>
*/
static int get_key_pinnacle_color(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
/* code_modulo parameter (0x88) is used to reduce code value to fit inside IR_KEYTAB_SIZE
*
* this is the only value that results in 42 unique
* codes < 128
*/
return get_key_pinnacle(ir, ir_key, ir_raw, 2, 0x80, 0x88);
}
void saa7134_input_irq(struct saa7134_dev *dev)
{
struct saa7134_card_ir *ir;
if (!dev || !dev->remote)
return;
ir = dev->remote;
if (!ir->running)
return;
if (!ir->polling && !ir->raw_decode) {
build_key(dev);
} else if (ir->raw_decode) {
saa7134_raw_decode_irq(dev);
}
}
static void saa7134_input_timer(unsigned long data)
{
struct saa7134_dev *dev = (struct saa7134_dev *)data;
struct saa7134_card_ir *ir = dev->remote;
build_key(dev);
mod_timer(&ir->timer, jiffies + msecs_to_jiffies(ir->polling));
}
static void ir_raw_decode_timer_end(unsigned long data)
{
struct saa7134_dev *dev = (struct saa7134_dev *)data;
struct saa7134_card_ir *ir = dev->remote;
ir_raw_event_handle(dev->remote->dev);
ir->active = false;
}
static int __saa7134_ir_start(void *priv)
{
struct saa7134_dev *dev = priv;
struct saa7134_card_ir *ir;
if (!dev || !dev->remote)
return -EINVAL;
ir = dev->remote;
if (ir->running)
return 0;
/* Moved here from saa7134_input_init1() because the latter
* is not called on device resume */
switch (dev->board) {
case SAA7134_BOARD_MD2819:
case SAA7134_BOARD_KWORLD_VSTREAM_XPERT:
case SAA7134_BOARD_AVERMEDIA_305:
case SAA7134_BOARD_AVERMEDIA_307:
case SAA7134_BOARD_AVERMEDIA_STUDIO_305:
case SAA7134_BOARD_AVERMEDIA_STUDIO_505:
case SAA7134_BOARD_AVERMEDIA_STUDIO_307:
case SAA7134_BOARD_AVERMEDIA_STUDIO_507:
case SAA7134_BOARD_AVERMEDIA_STUDIO_507UA:
case SAA7134_BOARD_AVERMEDIA_GO_007_FM:
case SAA7134_BOARD_AVERMEDIA_M102:
case SAA7134_BOARD_AVERMEDIA_GO_007_FM_PLUS:
/* Without this we won't receive key up events */
saa_setb(SAA7134_GPIO_GPMODE0, 0x4);
saa_setb(SAA7134_GPIO_GPSTATUS0, 0x4);
break;
case SAA7134_BOARD_AVERMEDIA_777:
case SAA7134_BOARD_AVERMEDIA_A16AR:
/* Without this we won't receive key up events */
saa_setb(SAA7134_GPIO_GPMODE1, 0x1);
saa_setb(SAA7134_GPIO_GPSTATUS1, 0x1);
break;
case SAA7134_BOARD_AVERMEDIA_A16D:
/* Without this we won't receive key up events */
saa_setb(SAA7134_GPIO_GPMODE1, 0x1);
saa_setb(SAA7134_GPIO_GPSTATUS1, 0x1);
break;
case SAA7134_BOARD_GOTVIEW_7135:
saa_setb(SAA7134_GPIO_GPMODE1, 0x80);
break;
}
ir->running = true;
ir->active = false;
if (ir->polling) {
setup_timer(&ir->timer, saa7134_input_timer,
(unsigned long)dev);
ir->timer.expires = jiffies + HZ;
add_timer(&ir->timer);
} else if (ir->raw_decode) {
/* set timer_end for code completion */
setup_timer(&ir->timer, ir_raw_decode_timer_end,
(unsigned long)dev);
}
return 0;
}
static void __saa7134_ir_stop(void *priv)
{
struct saa7134_dev *dev = priv;
struct saa7134_card_ir *ir;
if (!dev || !dev->remote)
return;
ir = dev->remote;
if (!ir->running)
return;
if (ir->polling || ir->raw_decode)
del_timer_sync(&ir->timer);
ir->active = false;
ir->running = false;
return;
}
int saa7134_ir_start(struct saa7134_dev *dev)
{
if (dev->remote->users)
return __saa7134_ir_start(dev);
return 0;
}
void saa7134_ir_stop(struct saa7134_dev *dev)
{
if (dev->remote->users)
__saa7134_ir_stop(dev);
}
static int saa7134_ir_open(struct rc_dev *rc)
{
struct saa7134_dev *dev = rc->priv;
dev->remote->users++;
return __saa7134_ir_start(dev);
}
static void saa7134_ir_close(struct rc_dev *rc)
{
struct saa7134_dev *dev = rc->priv;
dev->remote->users--;
if (!dev->remote->users)
__saa7134_ir_stop(dev);
}
int saa7134_input_init1(struct saa7134_dev *dev)
{
struct saa7134_card_ir *ir;
struct rc_dev *rc;
char *ir_codes = NULL;
u32 mask_keycode = 0;
u32 mask_keydown = 0;
u32 mask_keyup = 0;
unsigned polling = 0;
bool raw_decode = false;
int err;
if (dev->has_remote != SAA7134_REMOTE_GPIO)
return -ENODEV;
if (disable_ir)
return -ENODEV;
/* detect & configure */
switch (dev->board) {
case SAA7134_BOARD_FLYVIDEO2000:
case SAA7134_BOARD_FLYVIDEO3000:
case SAA7134_BOARD_FLYTVPLATINUM_FM:
case SAA7134_BOARD_FLYTVPLATINUM_MINI2:
case SAA7134_BOARD_ROVERMEDIA_LINK_PRO_FM:
ir_codes = RC_MAP_FLYVIDEO;
mask_keycode = 0xEC00000;
mask_keydown = 0x0040000;
break;
case SAA7134_BOARD_CINERGY400:
case SAA7134_BOARD_CINERGY600:
case SAA7134_BOARD_CINERGY600_MK3:
ir_codes = RC_MAP_CINERGY;
mask_keycode = 0x00003f;
mask_keyup = 0x040000;
break;
case SAA7134_BOARD_ECS_TVP3XP:
case SAA7134_BOARD_ECS_TVP3XP_4CB5:
ir_codes = RC_MAP_EZTV;
mask_keycode = 0x00017c;
mask_keyup = 0x000002;
polling = 50; // ms
break;
case SAA7134_BOARD_KWORLD_XPERT:
case SAA7134_BOARD_AVACSSMARTTV:
ir_codes = RC_MAP_PIXELVIEW;
mask_keycode = 0x00001F;
mask_keyup = 0x000020;
polling = 50; // ms
break;
case SAA7134_BOARD_MD2819:
case SAA7134_BOARD_KWORLD_VSTREAM_XPERT:
case SAA7134_BOARD_AVERMEDIA_305:
case SAA7134_BOARD_AVERMEDIA_307:
case SAA7134_BOARD_AVERMEDIA_STUDIO_305:
case SAA7134_BOARD_AVERMEDIA_STUDIO_505:
case SAA7134_BOARD_AVERMEDIA_STUDIO_307:
case SAA7134_BOARD_AVERMEDIA_STUDIO_507:
case SAA7134_BOARD_AVERMEDIA_STUDIO_507UA:
case SAA7134_BOARD_AVERMEDIA_GO_007_FM:
case SAA7134_BOARD_AVERMEDIA_M102:
case SAA7134_BOARD_AVERMEDIA_GO_007_FM_PLUS:
ir_codes = RC_MAP_AVERMEDIA;
mask_keycode = 0x0007C8;
mask_keydown = 0x000010;
polling = 50; // ms
/* GPIO stuff moved to __saa7134_ir_start() */
break;
case SAA7134_BOARD_AVERMEDIA_M135A:
ir_codes = RC_MAP_AVERMEDIA_M135A;
mask_keydown = 0x0040000; /* Enable GPIO18 line on both edges */
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = true;
break;
case SAA7134_BOARD_AVERMEDIA_M733A:
ir_codes = RC_MAP_AVERMEDIA_M733A_RM_K6;
mask_keydown = 0x0040000;
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = true;
break;
case SAA7134_BOARD_AVERMEDIA_777:
case SAA7134_BOARD_AVERMEDIA_A16AR:
ir_codes = RC_MAP_AVERMEDIA;
mask_keycode = 0x02F200;
mask_keydown = 0x000400;
polling = 50; // ms
/* GPIO stuff moved to __saa7134_ir_start() */
break;
case SAA7134_BOARD_AVERMEDIA_A16D:
ir_codes = RC_MAP_AVERMEDIA_A16D;
mask_keycode = 0x02F200;
mask_keydown = 0x000400;
polling = 50; /* ms */
/* GPIO stuff moved to __saa7134_ir_start() */
break;
case SAA7134_BOARD_KWORLD_TERMINATOR:
ir_codes = RC_MAP_PIXELVIEW;
mask_keycode = 0x00001f;
mask_keyup = 0x000060;
polling = 50; // ms
break;
case SAA7134_BOARD_MANLI_MTV001:
case SAA7134_BOARD_MANLI_MTV002:
ir_codes = RC_MAP_MANLI;
mask_keycode = 0x001f00;
mask_keyup = 0x004000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_BEHOLD_409FM:
case SAA7134_BOARD_BEHOLD_401:
case SAA7134_BOARD_BEHOLD_403:
case SAA7134_BOARD_BEHOLD_403FM:
case SAA7134_BOARD_BEHOLD_405:
case SAA7134_BOARD_BEHOLD_405FM:
case SAA7134_BOARD_BEHOLD_407:
case SAA7134_BOARD_BEHOLD_407FM:
case SAA7134_BOARD_BEHOLD_409:
case SAA7134_BOARD_BEHOLD_505FM:
case SAA7134_BOARD_BEHOLD_505RDS_MK5:
case SAA7134_BOARD_BEHOLD_505RDS_MK3:
case SAA7134_BOARD_BEHOLD_507_9FM:
case SAA7134_BOARD_BEHOLD_507RDS_MK3:
case SAA7134_BOARD_BEHOLD_507RDS_MK5:
ir_codes = RC_MAP_MANLI;
mask_keycode = 0x003f00;
mask_keyup = 0x004000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_BEHOLD_COLUMBUS_TVFM:
ir_codes = RC_MAP_BEHOLD_COLUMBUS;
mask_keycode = 0x003f00;
mask_keyup = 0x004000;
polling = 50; // ms
break;
case SAA7134_BOARD_SEDNA_PC_TV_CARDBUS:
ir_codes = RC_MAP_PCTV_SEDNA;
mask_keycode = 0x001f00;
mask_keyup = 0x004000;
polling = 50; // ms
break;
case SAA7134_BOARD_GOTVIEW_7135:
ir_codes = RC_MAP_GOTVIEW7135;
mask_keycode = 0x0003CC;
mask_keydown = 0x000010;
polling = 5; /* ms */
/* GPIO stuff moved to __saa7134_ir_start() */
break;
case SAA7134_BOARD_VIDEOMATE_TV_PVR:
case SAA7134_BOARD_VIDEOMATE_GOLD_PLUS:
case SAA7134_BOARD_VIDEOMATE_TV_GOLD_PLUSII:
ir_codes = RC_MAP_VIDEOMATE_TV_PVR;
mask_keycode = 0x00003F;
mask_keyup = 0x400000;
polling = 50; // ms
break;
case SAA7134_BOARD_PROTEUS_2309:
ir_codes = RC_MAP_PROTEUS_2309;
mask_keycode = 0x00007F;
mask_keyup = 0x000080;
polling = 50; // ms
break;
case SAA7134_BOARD_VIDEOMATE_DVBT_300:
case SAA7134_BOARD_VIDEOMATE_DVBT_200:
ir_codes = RC_MAP_VIDEOMATE_TV_PVR;
mask_keycode = 0x003F00;
mask_keyup = 0x040000;
break;
case SAA7134_BOARD_FLYDVBS_LR300:
case SAA7134_BOARD_FLYDVBT_LR301:
case SAA7134_BOARD_FLYDVBTDUO:
ir_codes = RC_MAP_FLYDVB;
mask_keycode = 0x0001F00;
mask_keydown = 0x0040000;
break;
case SAA7134_BOARD_ASUSTeK_P7131_DUAL:
case SAA7134_BOARD_ASUSTeK_P7131_HYBRID_LNA:
case SAA7134_BOARD_ASUSTeK_P7131_ANALOG:
ir_codes = RC_MAP_ASUS_PC39;
mask_keydown = 0x0040000; /* Enable GPIO18 line on both edges */
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = true;
break;
case SAA7134_BOARD_ENCORE_ENLTV:
case SAA7134_BOARD_ENCORE_ENLTV_FM:
ir_codes = RC_MAP_ENCORE_ENLTV;
mask_keycode = 0x00007f;
mask_keyup = 0x040000;
polling = 50; // ms
break;
case SAA7134_BOARD_ENCORE_ENLTV_FM53:
case SAA7134_BOARD_ENCORE_ENLTV_FM3:
ir_codes = RC_MAP_ENCORE_ENLTV_FM53;
mask_keydown = 0x0040000; /* Enable GPIO18 line on both edges */
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = true;
break;
case SAA7134_BOARD_10MOONSTVMASTER3:
ir_codes = RC_MAP_ENCORE_ENLTV;
mask_keycode = 0x5f80000;
mask_keyup = 0x8000000;
polling = 50; //ms
break;
case SAA7134_BOARD_GENIUS_TVGO_A11MCE:
ir_codes = RC_MAP_GENIUS_TVGO_A11MCE;
mask_keycode = 0xff;
mask_keydown = 0xf00000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_REAL_ANGEL_220:
ir_codes = RC_MAP_REAL_AUDIO_220_32_KEYS;
mask_keycode = 0x3f00;
mask_keyup = 0x4000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_KWORLD_PLUS_TV_ANALOG:
ir_codes = RC_MAP_KWORLD_PLUS_TV_ANALOG;
mask_keycode = 0x7f;
polling = 40; /* ms */
break;
case SAA7134_BOARD_VIDEOMATE_S350:
ir_codes = RC_MAP_VIDEOMATE_S350;
mask_keycode = 0x003f00;
mask_keydown = 0x040000;
break;
case SAA7134_BOARD_LEADTEK_WINFAST_DTV1000S:
ir_codes = RC_MAP_WINFAST;
mask_keycode = 0x5f00;
mask_keyup = 0x020000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_VIDEOMATE_M1F:
ir_codes = RC_MAP_VIDEOMATE_K100;
mask_keycode = 0x0ff00;
mask_keyup = 0x040000;
break;
case SAA7134_BOARD_HAUPPAUGE_HVR1150:
case SAA7134_BOARD_HAUPPAUGE_HVR1120:
ir_codes = RC_MAP_HAUPPAUGE;
mask_keydown = 0x0040000; /* Enable GPIO18 line on both edges */
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = true;
break;
}
if (NULL == ir_codes) {
printk("%s: Oops: IR config error [card=%d]\n",
dev->name, dev->board);
return -ENODEV;
}
ir = kzalloc(sizeof(*ir), GFP_KERNEL);
rc = rc_allocate_device();
if (!ir || !rc) {
err = -ENOMEM;
goto err_out_free;
}
ir->dev = rc;
dev->remote = ir;
/* init hardware-specific stuff */
ir->mask_keycode = mask_keycode;
ir->mask_keydown = mask_keydown;
ir->mask_keyup = mask_keyup;
ir->polling = polling;
ir->raw_decode = raw_decode;
/* init input device */
snprintf(ir->name, sizeof(ir->name), "saa7134 IR (%s)",
saa7134_boards[dev->board].name);
snprintf(ir->phys, sizeof(ir->phys), "pci-%s/ir0",
pci_name(dev->pci));
rc->priv = dev;
rc->open = saa7134_ir_open;
rc->close = saa7134_ir_close;
if (raw_decode)
rc->driver_type = RC_DRIVER_IR_RAW;
rc->input_name = ir->name;
rc->input_phys = ir->phys;
rc->input_id.bustype = BUS_PCI;
rc->input_id.version = 1;
if (dev->pci->subsystem_vendor) {
rc->input_id.vendor = dev->pci->subsystem_vendor;
rc->input_id.product = dev->pci->subsystem_device;
} else {
rc->input_id.vendor = dev->pci->vendor;
rc->input_id.product = dev->pci->device;
}
rc->dev.parent = &dev->pci->dev;
rc->map_name = ir_codes;
rc->driver_name = MODULE_NAME;
err = rc_register_device(rc);
if (err)
goto err_out_free;
return 0;
err_out_free:
rc_free_device(rc);
dev->remote = NULL;
kfree(ir);
return err;
}
void saa7134_input_fini(struct saa7134_dev *dev)
{
if (NULL == dev->remote)
return;
saa7134_ir_stop(dev);
rc_unregister_device(dev->remote->dev);
kfree(dev->remote);
dev->remote = NULL;
}
void saa7134_probe_i2c_ir(struct saa7134_dev *dev)
{
struct i2c_board_info info;
struct i2c_msg msg_msi = {
.addr = 0x50,
.flags = I2C_M_RD,
.len = 0,
.buf = NULL,
};
int rc;
if (disable_ir) {
dprintk("IR has been disabled, not probing for i2c remote\n");
return;
}
memset(&info, 0, sizeof(struct i2c_board_info));
memset(&dev->init_data, 0, sizeof(dev->init_data));
strlcpy(info.type, "ir_video", I2C_NAME_SIZE);
switch (dev->board) {
case SAA7134_BOARD_PINNACLE_PCTV_110i:
case SAA7134_BOARD_PINNACLE_PCTV_310i:
dev->init_data.name = "Pinnacle PCTV";
if (pinnacle_remote == 0) {
dev->init_data.get_key = get_key_pinnacle_color;
dev->init_data.ir_codes = RC_MAP_PINNACLE_COLOR;
info.addr = 0x47;
} else {
dev->init_data.get_key = get_key_pinnacle_grey;
dev->init_data.ir_codes = RC_MAP_PINNACLE_GREY;
info.addr = 0x47;
}
break;
case SAA7134_BOARD_UPMOST_PURPLE_TV:
dev->init_data.name = "Purple TV";
dev->init_data.get_key = get_key_purpletv;
dev->init_data.ir_codes = RC_MAP_PURPLETV;
info.addr = 0x7a;
break;
case SAA7134_BOARD_MSI_TVATANYWHERE_PLUS:
dev->init_data.name = "MSI TV@nywhere Plus";
dev->init_data.get_key = get_key_msi_tvanywhere_plus;
dev->init_data.ir_codes = RC_MAP_MSI_TVANYWHERE_PLUS;
/*
* MSI TV@nyware Plus requires more frequent polling
* otherwise it will miss some keypresses
*/
dev->init_data.polling_interval = 50;
info.addr = 0x30;
/* MSI TV@nywhere Plus controller doesn't seem to
respond to probes unless we read something from
an existing device. Weird...
REVISIT: might no longer be needed */
rc = i2c_transfer(&dev->i2c_adap, &msg_msi, 1);
dprintk("probe 0x%02x @ %s: %s\n",
msg_msi.addr, dev->i2c_adap.name,
(1 == rc) ? "yes" : "no");
break;
case SAA7134_BOARD_KWORLD_PC150U:
/* copied and modified from MSI TV@nywhere Plus */
dev->init_data.name = "Kworld PC150-U";
dev->init_data.get_key = get_key_kworld_pc150u;
dev->init_data.ir_codes = RC_MAP_KWORLD_PC150U;
info.addr = 0x30;
/* MSI TV@nywhere Plus controller doesn't seem to
respond to probes unless we read something from
an existing device. Weird...
REVISIT: might no longer be needed */
rc = i2c_transfer(&dev->i2c_adap, &msg_msi, 1);
dprintk("probe 0x%02x @ %s: %s\n",
msg_msi.addr, dev->i2c_adap.name,
(1 == rc) ? "yes" : "no");
break;
case SAA7134_BOARD_HAUPPAUGE_HVR1110:
dev->init_data.name = "HVR 1110";
dev->init_data.get_key = get_key_hvr1110;
dev->init_data.ir_codes = RC_MAP_HAUPPAUGE;
info.addr = 0x71;
break;
case SAA7134_BOARD_BEHOLD_607FM_MK3:
case SAA7134_BOARD_BEHOLD_607FM_MK5:
case SAA7134_BOARD_BEHOLD_609FM_MK3:
case SAA7134_BOARD_BEHOLD_609FM_MK5:
case SAA7134_BOARD_BEHOLD_607RDS_MK3:
case SAA7134_BOARD_BEHOLD_607RDS_MK5:
case SAA7134_BOARD_BEHOLD_609RDS_MK3:
case SAA7134_BOARD_BEHOLD_609RDS_MK5:
case SAA7134_BOARD_BEHOLD_M6:
case SAA7134_BOARD_BEHOLD_M63:
case SAA7134_BOARD_BEHOLD_M6_EXTRA:
case SAA7134_BOARD_BEHOLD_H6:
case SAA7134_BOARD_BEHOLD_X7:
case SAA7134_BOARD_BEHOLD_H7:
case SAA7134_BOARD_BEHOLD_A7:
dev->init_data.name = "BeholdTV";
dev->init_data.get_key = get_key_beholdm6xx;
dev->init_data.ir_codes = RC_MAP_BEHOLD;
dev->init_data.type = RC_TYPE_NEC;
info.addr = 0x2d;
break;
case SAA7134_BOARD_AVERMEDIA_CARDBUS_501:
case SAA7134_BOARD_AVERMEDIA_CARDBUS_506:
info.addr = 0x40;
break;
case SAA7134_BOARD_FLYDVB_TRIO:
dev->init_data.name = "FlyDVB Trio";
dev->init_data.get_key = get_key_flydvb_trio;
dev->init_data.ir_codes = RC_MAP_FLYDVB;
info.addr = 0x0b;
break;
default:
dprintk("No I2C IR support for board %x\n", dev->board);
return;
}
if (dev->init_data.name)
info.platform_data = &dev->init_data;
i2c_new_device(&dev->i2c_adap, &info);
}
static int saa7134_raw_decode_irq(struct saa7134_dev *dev)
{
struct saa7134_card_ir *ir = dev->remote;
unsigned long timeout;
int space;
/* Generate initial event */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
space = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2) & ir->mask_keydown;
ir_raw_event_store_edge(dev->remote->dev, space ? IR_SPACE : IR_PULSE);
/*
* Wait 15 ms from the start of the first IR event before processing
* the event. This time is enough for NEC protocol. May need adjustments
* to work with other protocols.
*/
if (!ir->active) {
timeout = jiffies + msecs_to_jiffies(15);
mod_timer(&ir->timer, timeout);
ir->active = true;
}
return 1;
}
| gpl-2.0 |
crdroid-devices/android_kernel_htc_msm8960 | fs/xfs/xfs_inode.c | 4812 | 109738 | /*
* Copyright (c) 2000-2006 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* 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 <linux/log2.h>
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_trans_priv.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_bmap_btree.h"
#include "xfs_alloc_btree.h"
#include "xfs_ialloc_btree.h"
#include "xfs_attr_sf.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_buf_item.h"
#include "xfs_inode_item.h"
#include "xfs_btree.h"
#include "xfs_alloc.h"
#include "xfs_ialloc.h"
#include "xfs_bmap.h"
#include "xfs_error.h"
#include "xfs_utils.h"
#include "xfs_quota.h"
#include "xfs_filestream.h"
#include "xfs_vnodeops.h"
#include "xfs_trace.h"
kmem_zone_t *xfs_ifork_zone;
kmem_zone_t *xfs_inode_zone;
/*
* Used in xfs_itruncate_extents(). This is the maximum number of extents
* freed from a file in a single transaction.
*/
#define XFS_ITRUNC_MAX_EXTENTS 2
STATIC int xfs_iflush_int(xfs_inode_t *, xfs_buf_t *);
STATIC int xfs_iformat_local(xfs_inode_t *, xfs_dinode_t *, int, int);
STATIC int xfs_iformat_extents(xfs_inode_t *, xfs_dinode_t *, int);
STATIC int xfs_iformat_btree(xfs_inode_t *, xfs_dinode_t *, int);
#ifdef DEBUG
/*
* Make sure that the extents in the given memory buffer
* are valid.
*/
STATIC void
xfs_validate_extents(
xfs_ifork_t *ifp,
int nrecs,
xfs_exntfmt_t fmt)
{
xfs_bmbt_irec_t irec;
xfs_bmbt_rec_host_t rec;
int i;
for (i = 0; i < nrecs; i++) {
xfs_bmbt_rec_host_t *ep = xfs_iext_get_ext(ifp, i);
rec.l0 = get_unaligned(&ep->l0);
rec.l1 = get_unaligned(&ep->l1);
xfs_bmbt_get_all(&rec, &irec);
if (fmt == XFS_EXTFMT_NOSTATE)
ASSERT(irec.br_state == XFS_EXT_NORM);
}
}
#else /* DEBUG */
#define xfs_validate_extents(ifp, nrecs, fmt)
#endif /* DEBUG */
/*
* Check that none of the inode's in the buffer have a next
* unlinked field of 0.
*/
#if defined(DEBUG)
void
xfs_inobp_check(
xfs_mount_t *mp,
xfs_buf_t *bp)
{
int i;
int j;
xfs_dinode_t *dip;
j = mp->m_inode_cluster_size >> mp->m_sb.sb_inodelog;
for (i = 0; i < j; i++) {
dip = (xfs_dinode_t *)xfs_buf_offset(bp,
i * mp->m_sb.sb_inodesize);
if (!dip->di_next_unlinked) {
xfs_alert(mp,
"Detected bogus zero next_unlinked field in incore inode buffer 0x%p.",
bp);
ASSERT(dip->di_next_unlinked);
}
}
}
#endif
/*
* Find the buffer associated with the given inode map
* We do basic validation checks on the buffer once it has been
* retrieved from disk.
*/
STATIC int
xfs_imap_to_bp(
xfs_mount_t *mp,
xfs_trans_t *tp,
struct xfs_imap *imap,
xfs_buf_t **bpp,
uint buf_flags,
uint iget_flags)
{
int error;
int i;
int ni;
xfs_buf_t *bp;
error = xfs_trans_read_buf(mp, tp, mp->m_ddev_targp, imap->im_blkno,
(int)imap->im_len, buf_flags, &bp);
if (error) {
if (error != EAGAIN) {
xfs_warn(mp,
"%s: xfs_trans_read_buf() returned error %d.",
__func__, error);
} else {
ASSERT(buf_flags & XBF_TRYLOCK);
}
return error;
}
/*
* Validate the magic number and version of every inode in the buffer
* (if DEBUG kernel) or the first inode in the buffer, otherwise.
*/
#ifdef DEBUG
ni = BBTOB(imap->im_len) >> mp->m_sb.sb_inodelog;
#else /* usual case */
ni = 1;
#endif
for (i = 0; i < ni; i++) {
int di_ok;
xfs_dinode_t *dip;
dip = (xfs_dinode_t *)xfs_buf_offset(bp,
(i << mp->m_sb.sb_inodelog));
di_ok = dip->di_magic == cpu_to_be16(XFS_DINODE_MAGIC) &&
XFS_DINODE_GOOD_VERSION(dip->di_version);
if (unlikely(XFS_TEST_ERROR(!di_ok, mp,
XFS_ERRTAG_ITOBP_INOTOBP,
XFS_RANDOM_ITOBP_INOTOBP))) {
if (iget_flags & XFS_IGET_UNTRUSTED) {
xfs_trans_brelse(tp, bp);
return XFS_ERROR(EINVAL);
}
XFS_CORRUPTION_ERROR("xfs_imap_to_bp",
XFS_ERRLEVEL_HIGH, mp, dip);
#ifdef DEBUG
xfs_emerg(mp,
"bad inode magic/vsn daddr %lld #%d (magic=%x)",
(unsigned long long)imap->im_blkno, i,
be16_to_cpu(dip->di_magic));
ASSERT(0);
#endif
xfs_trans_brelse(tp, bp);
return XFS_ERROR(EFSCORRUPTED);
}
}
xfs_inobp_check(mp, bp);
*bpp = bp;
return 0;
}
/*
* This routine is called to map an inode number within a file
* system to the buffer containing the on-disk version of the
* inode. It returns a pointer to the buffer containing the
* on-disk inode in the bpp parameter, and in the dip parameter
* it returns a pointer to the on-disk inode within that buffer.
*
* If a non-zero error is returned, then the contents of bpp and
* dipp are undefined.
*
* Use xfs_imap() to determine the size and location of the
* buffer to read from disk.
*/
int
xfs_inotobp(
xfs_mount_t *mp,
xfs_trans_t *tp,
xfs_ino_t ino,
xfs_dinode_t **dipp,
xfs_buf_t **bpp,
int *offset,
uint imap_flags)
{
struct xfs_imap imap;
xfs_buf_t *bp;
int error;
imap.im_blkno = 0;
error = xfs_imap(mp, tp, ino, &imap, imap_flags);
if (error)
return error;
error = xfs_imap_to_bp(mp, tp, &imap, &bp, XBF_LOCK, imap_flags);
if (error)
return error;
*dipp = (xfs_dinode_t *)xfs_buf_offset(bp, imap.im_boffset);
*bpp = bp;
*offset = imap.im_boffset;
return 0;
}
/*
* This routine is called to map an inode to the buffer containing
* the on-disk version of the inode. It returns a pointer to the
* buffer containing the on-disk inode in the bpp parameter, and in
* the dip parameter it returns a pointer to the on-disk inode within
* that buffer.
*
* If a non-zero error is returned, then the contents of bpp and
* dipp are undefined.
*
* The inode is expected to already been mapped to its buffer and read
* in once, thus we can use the mapping information stored in the inode
* rather than calling xfs_imap(). This allows us to avoid the overhead
* of looking at the inode btree for small block file systems
* (see xfs_imap()).
*/
int
xfs_itobp(
xfs_mount_t *mp,
xfs_trans_t *tp,
xfs_inode_t *ip,
xfs_dinode_t **dipp,
xfs_buf_t **bpp,
uint buf_flags)
{
xfs_buf_t *bp;
int error;
ASSERT(ip->i_imap.im_blkno != 0);
error = xfs_imap_to_bp(mp, tp, &ip->i_imap, &bp, buf_flags, 0);
if (error)
return error;
if (!bp) {
ASSERT(buf_flags & XBF_TRYLOCK);
ASSERT(tp == NULL);
*bpp = NULL;
return EAGAIN;
}
*dipp = (xfs_dinode_t *)xfs_buf_offset(bp, ip->i_imap.im_boffset);
*bpp = bp;
return 0;
}
/*
* Move inode type and inode format specific information from the
* on-disk inode to the in-core inode. For fifos, devs, and sockets
* this means set if_rdev to the proper value. For files, directories,
* and symlinks this means to bring in the in-line data or extent
* pointers. For a file in B-tree format, only the root is immediately
* brought in-core. The rest will be in-lined in if_extents when it
* is first referenced (see xfs_iread_extents()).
*/
STATIC int
xfs_iformat(
xfs_inode_t *ip,
xfs_dinode_t *dip)
{
xfs_attr_shortform_t *atp;
int size;
int error = 0;
xfs_fsize_t di_size;
if (unlikely(be32_to_cpu(dip->di_nextents) +
be16_to_cpu(dip->di_anextents) >
be64_to_cpu(dip->di_nblocks))) {
xfs_warn(ip->i_mount,
"corrupt dinode %Lu, extent total = %d, nblocks = %Lu.",
(unsigned long long)ip->i_ino,
(int)(be32_to_cpu(dip->di_nextents) +
be16_to_cpu(dip->di_anextents)),
(unsigned long long)
be64_to_cpu(dip->di_nblocks));
XFS_CORRUPTION_ERROR("xfs_iformat(1)", XFS_ERRLEVEL_LOW,
ip->i_mount, dip);
return XFS_ERROR(EFSCORRUPTED);
}
if (unlikely(dip->di_forkoff > ip->i_mount->m_sb.sb_inodesize)) {
xfs_warn(ip->i_mount, "corrupt dinode %Lu, forkoff = 0x%x.",
(unsigned long long)ip->i_ino,
dip->di_forkoff);
XFS_CORRUPTION_ERROR("xfs_iformat(2)", XFS_ERRLEVEL_LOW,
ip->i_mount, dip);
return XFS_ERROR(EFSCORRUPTED);
}
if (unlikely((ip->i_d.di_flags & XFS_DIFLAG_REALTIME) &&
!ip->i_mount->m_rtdev_targp)) {
xfs_warn(ip->i_mount,
"corrupt dinode %Lu, has realtime flag set.",
ip->i_ino);
XFS_CORRUPTION_ERROR("xfs_iformat(realtime)",
XFS_ERRLEVEL_LOW, ip->i_mount, dip);
return XFS_ERROR(EFSCORRUPTED);
}
switch (ip->i_d.di_mode & S_IFMT) {
case S_IFIFO:
case S_IFCHR:
case S_IFBLK:
case S_IFSOCK:
if (unlikely(dip->di_format != XFS_DINODE_FMT_DEV)) {
XFS_CORRUPTION_ERROR("xfs_iformat(3)", XFS_ERRLEVEL_LOW,
ip->i_mount, dip);
return XFS_ERROR(EFSCORRUPTED);
}
ip->i_d.di_size = 0;
ip->i_df.if_u2.if_rdev = xfs_dinode_get_rdev(dip);
break;
case S_IFREG:
case S_IFLNK:
case S_IFDIR:
switch (dip->di_format) {
case XFS_DINODE_FMT_LOCAL:
/*
* no local regular files yet
*/
if (unlikely(S_ISREG(be16_to_cpu(dip->di_mode)))) {
xfs_warn(ip->i_mount,
"corrupt inode %Lu (local format for regular file).",
(unsigned long long) ip->i_ino);
XFS_CORRUPTION_ERROR("xfs_iformat(4)",
XFS_ERRLEVEL_LOW,
ip->i_mount, dip);
return XFS_ERROR(EFSCORRUPTED);
}
di_size = be64_to_cpu(dip->di_size);
if (unlikely(di_size > XFS_DFORK_DSIZE(dip, ip->i_mount))) {
xfs_warn(ip->i_mount,
"corrupt inode %Lu (bad size %Ld for local inode).",
(unsigned long long) ip->i_ino,
(long long) di_size);
XFS_CORRUPTION_ERROR("xfs_iformat(5)",
XFS_ERRLEVEL_LOW,
ip->i_mount, dip);
return XFS_ERROR(EFSCORRUPTED);
}
size = (int)di_size;
error = xfs_iformat_local(ip, dip, XFS_DATA_FORK, size);
break;
case XFS_DINODE_FMT_EXTENTS:
error = xfs_iformat_extents(ip, dip, XFS_DATA_FORK);
break;
case XFS_DINODE_FMT_BTREE:
error = xfs_iformat_btree(ip, dip, XFS_DATA_FORK);
break;
default:
XFS_ERROR_REPORT("xfs_iformat(6)", XFS_ERRLEVEL_LOW,
ip->i_mount);
return XFS_ERROR(EFSCORRUPTED);
}
break;
default:
XFS_ERROR_REPORT("xfs_iformat(7)", XFS_ERRLEVEL_LOW, ip->i_mount);
return XFS_ERROR(EFSCORRUPTED);
}
if (error) {
return error;
}
if (!XFS_DFORK_Q(dip))
return 0;
ASSERT(ip->i_afp == NULL);
ip->i_afp = kmem_zone_zalloc(xfs_ifork_zone, KM_SLEEP | KM_NOFS);
switch (dip->di_aformat) {
case XFS_DINODE_FMT_LOCAL:
atp = (xfs_attr_shortform_t *)XFS_DFORK_APTR(dip);
size = be16_to_cpu(atp->hdr.totsize);
if (unlikely(size < sizeof(struct xfs_attr_sf_hdr))) {
xfs_warn(ip->i_mount,
"corrupt inode %Lu (bad attr fork size %Ld).",
(unsigned long long) ip->i_ino,
(long long) size);
XFS_CORRUPTION_ERROR("xfs_iformat(8)",
XFS_ERRLEVEL_LOW,
ip->i_mount, dip);
return XFS_ERROR(EFSCORRUPTED);
}
error = xfs_iformat_local(ip, dip, XFS_ATTR_FORK, size);
break;
case XFS_DINODE_FMT_EXTENTS:
error = xfs_iformat_extents(ip, dip, XFS_ATTR_FORK);
break;
case XFS_DINODE_FMT_BTREE:
error = xfs_iformat_btree(ip, dip, XFS_ATTR_FORK);
break;
default:
error = XFS_ERROR(EFSCORRUPTED);
break;
}
if (error) {
kmem_zone_free(xfs_ifork_zone, ip->i_afp);
ip->i_afp = NULL;
xfs_idestroy_fork(ip, XFS_DATA_FORK);
}
return error;
}
/*
* The file is in-lined in the on-disk inode.
* If it fits into if_inline_data, then copy
* it there, otherwise allocate a buffer for it
* and copy the data there. Either way, set
* if_data to point at the data.
* If we allocate a buffer for the data, make
* sure that its size is a multiple of 4 and
* record the real size in i_real_bytes.
*/
STATIC int
xfs_iformat_local(
xfs_inode_t *ip,
xfs_dinode_t *dip,
int whichfork,
int size)
{
xfs_ifork_t *ifp;
int real_size;
/*
* If the size is unreasonable, then something
* is wrong and we just bail out rather than crash in
* kmem_alloc() or memcpy() below.
*/
if (unlikely(size > XFS_DFORK_SIZE(dip, ip->i_mount, whichfork))) {
xfs_warn(ip->i_mount,
"corrupt inode %Lu (bad size %d for local fork, size = %d).",
(unsigned long long) ip->i_ino, size,
XFS_DFORK_SIZE(dip, ip->i_mount, whichfork));
XFS_CORRUPTION_ERROR("xfs_iformat_local", XFS_ERRLEVEL_LOW,
ip->i_mount, dip);
return XFS_ERROR(EFSCORRUPTED);
}
ifp = XFS_IFORK_PTR(ip, whichfork);
real_size = 0;
if (size == 0)
ifp->if_u1.if_data = NULL;
else if (size <= sizeof(ifp->if_u2.if_inline_data))
ifp->if_u1.if_data = ifp->if_u2.if_inline_data;
else {
real_size = roundup(size, 4);
ifp->if_u1.if_data = kmem_alloc(real_size, KM_SLEEP | KM_NOFS);
}
ifp->if_bytes = size;
ifp->if_real_bytes = real_size;
if (size)
memcpy(ifp->if_u1.if_data, XFS_DFORK_PTR(dip, whichfork), size);
ifp->if_flags &= ~XFS_IFEXTENTS;
ifp->if_flags |= XFS_IFINLINE;
return 0;
}
/*
* The file consists of a set of extents all
* of which fit into the on-disk inode.
* If there are few enough extents to fit into
* the if_inline_ext, then copy them there.
* Otherwise allocate a buffer for them and copy
* them into it. Either way, set if_extents
* to point at the extents.
*/
STATIC int
xfs_iformat_extents(
xfs_inode_t *ip,
xfs_dinode_t *dip,
int whichfork)
{
xfs_bmbt_rec_t *dp;
xfs_ifork_t *ifp;
int nex;
int size;
int i;
ifp = XFS_IFORK_PTR(ip, whichfork);
nex = XFS_DFORK_NEXTENTS(dip, whichfork);
size = nex * (uint)sizeof(xfs_bmbt_rec_t);
/*
* If the number of extents is unreasonable, then something
* is wrong and we just bail out rather than crash in
* kmem_alloc() or memcpy() below.
*/
if (unlikely(size < 0 || size > XFS_DFORK_SIZE(dip, ip->i_mount, whichfork))) {
xfs_warn(ip->i_mount, "corrupt inode %Lu ((a)extents = %d).",
(unsigned long long) ip->i_ino, nex);
XFS_CORRUPTION_ERROR("xfs_iformat_extents(1)", XFS_ERRLEVEL_LOW,
ip->i_mount, dip);
return XFS_ERROR(EFSCORRUPTED);
}
ifp->if_real_bytes = 0;
if (nex == 0)
ifp->if_u1.if_extents = NULL;
else if (nex <= XFS_INLINE_EXTS)
ifp->if_u1.if_extents = ifp->if_u2.if_inline_ext;
else
xfs_iext_add(ifp, 0, nex);
ifp->if_bytes = size;
if (size) {
dp = (xfs_bmbt_rec_t *) XFS_DFORK_PTR(dip, whichfork);
xfs_validate_extents(ifp, nex, XFS_EXTFMT_INODE(ip));
for (i = 0; i < nex; i++, dp++) {
xfs_bmbt_rec_host_t *ep = xfs_iext_get_ext(ifp, i);
ep->l0 = get_unaligned_be64(&dp->l0);
ep->l1 = get_unaligned_be64(&dp->l1);
}
XFS_BMAP_TRACE_EXLIST(ip, nex, whichfork);
if (whichfork != XFS_DATA_FORK ||
XFS_EXTFMT_INODE(ip) == XFS_EXTFMT_NOSTATE)
if (unlikely(xfs_check_nostate_extents(
ifp, 0, nex))) {
XFS_ERROR_REPORT("xfs_iformat_extents(2)",
XFS_ERRLEVEL_LOW,
ip->i_mount);
return XFS_ERROR(EFSCORRUPTED);
}
}
ifp->if_flags |= XFS_IFEXTENTS;
return 0;
}
/*
* The file has too many extents to fit into
* the inode, so they are in B-tree format.
* Allocate a buffer for the root of the B-tree
* and copy the root into it. The i_extents
* field will remain NULL until all of the
* extents are read in (when they are needed).
*/
STATIC int
xfs_iformat_btree(
xfs_inode_t *ip,
xfs_dinode_t *dip,
int whichfork)
{
xfs_bmdr_block_t *dfp;
xfs_ifork_t *ifp;
/* REFERENCED */
int nrecs;
int size;
ifp = XFS_IFORK_PTR(ip, whichfork);
dfp = (xfs_bmdr_block_t *)XFS_DFORK_PTR(dip, whichfork);
size = XFS_BMAP_BROOT_SPACE(dfp);
nrecs = be16_to_cpu(dfp->bb_numrecs);
/*
* blow out if -- fork has less extents than can fit in
* fork (fork shouldn't be a btree format), root btree
* block has more records than can fit into the fork,
* or the number of extents is greater than the number of
* blocks.
*/
if (unlikely(XFS_IFORK_NEXTENTS(ip, whichfork) <=
XFS_IFORK_MAXEXT(ip, whichfork) ||
XFS_BMDR_SPACE_CALC(nrecs) >
XFS_DFORK_SIZE(dip, ip->i_mount, whichfork) ||
XFS_IFORK_NEXTENTS(ip, whichfork) > ip->i_d.di_nblocks)) {
xfs_warn(ip->i_mount, "corrupt inode %Lu (btree).",
(unsigned long long) ip->i_ino);
XFS_CORRUPTION_ERROR("xfs_iformat_btree", XFS_ERRLEVEL_LOW,
ip->i_mount, dip);
return XFS_ERROR(EFSCORRUPTED);
}
ifp->if_broot_bytes = size;
ifp->if_broot = kmem_alloc(size, KM_SLEEP | KM_NOFS);
ASSERT(ifp->if_broot != NULL);
/*
* Copy and convert from the on-disk structure
* to the in-memory structure.
*/
xfs_bmdr_to_bmbt(ip->i_mount, dfp,
XFS_DFORK_SIZE(dip, ip->i_mount, whichfork),
ifp->if_broot, size);
ifp->if_flags &= ~XFS_IFEXTENTS;
ifp->if_flags |= XFS_IFBROOT;
return 0;
}
STATIC void
xfs_dinode_from_disk(
xfs_icdinode_t *to,
xfs_dinode_t *from)
{
to->di_magic = be16_to_cpu(from->di_magic);
to->di_mode = be16_to_cpu(from->di_mode);
to->di_version = from ->di_version;
to->di_format = from->di_format;
to->di_onlink = be16_to_cpu(from->di_onlink);
to->di_uid = be32_to_cpu(from->di_uid);
to->di_gid = be32_to_cpu(from->di_gid);
to->di_nlink = be32_to_cpu(from->di_nlink);
to->di_projid_lo = be16_to_cpu(from->di_projid_lo);
to->di_projid_hi = be16_to_cpu(from->di_projid_hi);
memcpy(to->di_pad, from->di_pad, sizeof(to->di_pad));
to->di_flushiter = be16_to_cpu(from->di_flushiter);
to->di_atime.t_sec = be32_to_cpu(from->di_atime.t_sec);
to->di_atime.t_nsec = be32_to_cpu(from->di_atime.t_nsec);
to->di_mtime.t_sec = be32_to_cpu(from->di_mtime.t_sec);
to->di_mtime.t_nsec = be32_to_cpu(from->di_mtime.t_nsec);
to->di_ctime.t_sec = be32_to_cpu(from->di_ctime.t_sec);
to->di_ctime.t_nsec = be32_to_cpu(from->di_ctime.t_nsec);
to->di_size = be64_to_cpu(from->di_size);
to->di_nblocks = be64_to_cpu(from->di_nblocks);
to->di_extsize = be32_to_cpu(from->di_extsize);
to->di_nextents = be32_to_cpu(from->di_nextents);
to->di_anextents = be16_to_cpu(from->di_anextents);
to->di_forkoff = from->di_forkoff;
to->di_aformat = from->di_aformat;
to->di_dmevmask = be32_to_cpu(from->di_dmevmask);
to->di_dmstate = be16_to_cpu(from->di_dmstate);
to->di_flags = be16_to_cpu(from->di_flags);
to->di_gen = be32_to_cpu(from->di_gen);
}
void
xfs_dinode_to_disk(
xfs_dinode_t *to,
xfs_icdinode_t *from)
{
to->di_magic = cpu_to_be16(from->di_magic);
to->di_mode = cpu_to_be16(from->di_mode);
to->di_version = from ->di_version;
to->di_format = from->di_format;
to->di_onlink = cpu_to_be16(from->di_onlink);
to->di_uid = cpu_to_be32(from->di_uid);
to->di_gid = cpu_to_be32(from->di_gid);
to->di_nlink = cpu_to_be32(from->di_nlink);
to->di_projid_lo = cpu_to_be16(from->di_projid_lo);
to->di_projid_hi = cpu_to_be16(from->di_projid_hi);
memcpy(to->di_pad, from->di_pad, sizeof(to->di_pad));
to->di_flushiter = cpu_to_be16(from->di_flushiter);
to->di_atime.t_sec = cpu_to_be32(from->di_atime.t_sec);
to->di_atime.t_nsec = cpu_to_be32(from->di_atime.t_nsec);
to->di_mtime.t_sec = cpu_to_be32(from->di_mtime.t_sec);
to->di_mtime.t_nsec = cpu_to_be32(from->di_mtime.t_nsec);
to->di_ctime.t_sec = cpu_to_be32(from->di_ctime.t_sec);
to->di_ctime.t_nsec = cpu_to_be32(from->di_ctime.t_nsec);
to->di_size = cpu_to_be64(from->di_size);
to->di_nblocks = cpu_to_be64(from->di_nblocks);
to->di_extsize = cpu_to_be32(from->di_extsize);
to->di_nextents = cpu_to_be32(from->di_nextents);
to->di_anextents = cpu_to_be16(from->di_anextents);
to->di_forkoff = from->di_forkoff;
to->di_aformat = from->di_aformat;
to->di_dmevmask = cpu_to_be32(from->di_dmevmask);
to->di_dmstate = cpu_to_be16(from->di_dmstate);
to->di_flags = cpu_to_be16(from->di_flags);
to->di_gen = cpu_to_be32(from->di_gen);
}
STATIC uint
_xfs_dic2xflags(
__uint16_t di_flags)
{
uint flags = 0;
if (di_flags & XFS_DIFLAG_ANY) {
if (di_flags & XFS_DIFLAG_REALTIME)
flags |= XFS_XFLAG_REALTIME;
if (di_flags & XFS_DIFLAG_PREALLOC)
flags |= XFS_XFLAG_PREALLOC;
if (di_flags & XFS_DIFLAG_IMMUTABLE)
flags |= XFS_XFLAG_IMMUTABLE;
if (di_flags & XFS_DIFLAG_APPEND)
flags |= XFS_XFLAG_APPEND;
if (di_flags & XFS_DIFLAG_SYNC)
flags |= XFS_XFLAG_SYNC;
if (di_flags & XFS_DIFLAG_NOATIME)
flags |= XFS_XFLAG_NOATIME;
if (di_flags & XFS_DIFLAG_NODUMP)
flags |= XFS_XFLAG_NODUMP;
if (di_flags & XFS_DIFLAG_RTINHERIT)
flags |= XFS_XFLAG_RTINHERIT;
if (di_flags & XFS_DIFLAG_PROJINHERIT)
flags |= XFS_XFLAG_PROJINHERIT;
if (di_flags & XFS_DIFLAG_NOSYMLINKS)
flags |= XFS_XFLAG_NOSYMLINKS;
if (di_flags & XFS_DIFLAG_EXTSIZE)
flags |= XFS_XFLAG_EXTSIZE;
if (di_flags & XFS_DIFLAG_EXTSZINHERIT)
flags |= XFS_XFLAG_EXTSZINHERIT;
if (di_flags & XFS_DIFLAG_NODEFRAG)
flags |= XFS_XFLAG_NODEFRAG;
if (di_flags & XFS_DIFLAG_FILESTREAM)
flags |= XFS_XFLAG_FILESTREAM;
}
return flags;
}
uint
xfs_ip2xflags(
xfs_inode_t *ip)
{
xfs_icdinode_t *dic = &ip->i_d;
return _xfs_dic2xflags(dic->di_flags) |
(XFS_IFORK_Q(ip) ? XFS_XFLAG_HASATTR : 0);
}
uint
xfs_dic2xflags(
xfs_dinode_t *dip)
{
return _xfs_dic2xflags(be16_to_cpu(dip->di_flags)) |
(XFS_DFORK_Q(dip) ? XFS_XFLAG_HASATTR : 0);
}
/*
* Read the disk inode attributes into the in-core inode structure.
*/
int
xfs_iread(
xfs_mount_t *mp,
xfs_trans_t *tp,
xfs_inode_t *ip,
uint iget_flags)
{
xfs_buf_t *bp;
xfs_dinode_t *dip;
int error;
/*
* Fill in the location information in the in-core inode.
*/
error = xfs_imap(mp, tp, ip->i_ino, &ip->i_imap, iget_flags);
if (error)
return error;
/*
* Get pointers to the on-disk inode and the buffer containing it.
*/
error = xfs_imap_to_bp(mp, tp, &ip->i_imap, &bp,
XBF_LOCK, iget_flags);
if (error)
return error;
dip = (xfs_dinode_t *)xfs_buf_offset(bp, ip->i_imap.im_boffset);
/*
* If we got something that isn't an inode it means someone
* (nfs or dmi) has a stale handle.
*/
if (dip->di_magic != cpu_to_be16(XFS_DINODE_MAGIC)) {
#ifdef DEBUG
xfs_alert(mp,
"%s: dip->di_magic (0x%x) != XFS_DINODE_MAGIC (0x%x)",
__func__, be16_to_cpu(dip->di_magic), XFS_DINODE_MAGIC);
#endif /* DEBUG */
error = XFS_ERROR(EINVAL);
goto out_brelse;
}
/*
* If the on-disk inode is already linked to a directory
* entry, copy all of the inode into the in-core inode.
* xfs_iformat() handles copying in the inode format
* specific information.
* Otherwise, just get the truly permanent information.
*/
if (dip->di_mode) {
xfs_dinode_from_disk(&ip->i_d, dip);
error = xfs_iformat(ip, dip);
if (error) {
#ifdef DEBUG
xfs_alert(mp, "%s: xfs_iformat() returned error %d",
__func__, error);
#endif /* DEBUG */
goto out_brelse;
}
} else {
ip->i_d.di_magic = be16_to_cpu(dip->di_magic);
ip->i_d.di_version = dip->di_version;
ip->i_d.di_gen = be32_to_cpu(dip->di_gen);
ip->i_d.di_flushiter = be16_to_cpu(dip->di_flushiter);
/*
* Make sure to pull in the mode here as well in
* case the inode is released without being used.
* This ensures that xfs_inactive() will see that
* the inode is already free and not try to mess
* with the uninitialized part of it.
*/
ip->i_d.di_mode = 0;
}
/*
* The inode format changed when we moved the link count and
* made it 32 bits long. If this is an old format inode,
* convert it in memory to look like a new one. If it gets
* flushed to disk we will convert back before flushing or
* logging it. We zero out the new projid field and the old link
* count field. We'll handle clearing the pad field (the remains
* of the old uuid field) when we actually convert the inode to
* the new format. We don't change the version number so that we
* can distinguish this from a real new format inode.
*/
if (ip->i_d.di_version == 1) {
ip->i_d.di_nlink = ip->i_d.di_onlink;
ip->i_d.di_onlink = 0;
xfs_set_projid(ip, 0);
}
ip->i_delayed_blks = 0;
/*
* Mark the buffer containing the inode as something to keep
* around for a while. This helps to keep recently accessed
* meta-data in-core longer.
*/
xfs_buf_set_ref(bp, XFS_INO_REF);
/*
* Use xfs_trans_brelse() to release the buffer containing the
* on-disk inode, because it was acquired with xfs_trans_read_buf()
* in xfs_itobp() above. If tp is NULL, this is just a normal
* brelse(). If we're within a transaction, then xfs_trans_brelse()
* will only release the buffer if it is not dirty within the
* transaction. It will be OK to release the buffer in this case,
* because inodes on disk are never destroyed and we will be
* locking the new in-core inode before putting it in the hash
* table where other processes can find it. Thus we don't have
* to worry about the inode being changed just because we released
* the buffer.
*/
out_brelse:
xfs_trans_brelse(tp, bp);
return error;
}
/*
* Read in extents from a btree-format inode.
* Allocate and fill in if_extents. Real work is done in xfs_bmap.c.
*/
int
xfs_iread_extents(
xfs_trans_t *tp,
xfs_inode_t *ip,
int whichfork)
{
int error;
xfs_ifork_t *ifp;
xfs_extnum_t nextents;
if (unlikely(XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE)) {
XFS_ERROR_REPORT("xfs_iread_extents", XFS_ERRLEVEL_LOW,
ip->i_mount);
return XFS_ERROR(EFSCORRUPTED);
}
nextents = XFS_IFORK_NEXTENTS(ip, whichfork);
ifp = XFS_IFORK_PTR(ip, whichfork);
/*
* We know that the size is valid (it's checked in iformat_btree)
*/
ifp->if_bytes = ifp->if_real_bytes = 0;
ifp->if_flags |= XFS_IFEXTENTS;
xfs_iext_add(ifp, 0, nextents);
error = xfs_bmap_read_extents(tp, ip, whichfork);
if (error) {
xfs_iext_destroy(ifp);
ifp->if_flags &= ~XFS_IFEXTENTS;
return error;
}
xfs_validate_extents(ifp, nextents, XFS_EXTFMT_INODE(ip));
return 0;
}
/*
* Allocate an inode on disk and return a copy of its in-core version.
* The in-core inode is locked exclusively. Set mode, nlink, and rdev
* appropriately within the inode. The uid and gid for the inode are
* set according to the contents of the given cred structure.
*
* Use xfs_dialloc() to allocate the on-disk inode. If xfs_dialloc()
* has a free inode available, call xfs_iget()
* to obtain the in-core version of the allocated inode. Finally,
* fill in the inode and log its initial contents. In this case,
* ialloc_context would be set to NULL and call_again set to false.
*
* If xfs_dialloc() does not have an available inode,
* it will replenish its supply by doing an allocation. Since we can
* only do one allocation within a transaction without deadlocks, we
* must commit the current transaction before returning the inode itself.
* In this case, therefore, we will set call_again to true and return.
* The caller should then commit the current transaction, start a new
* transaction, and call xfs_ialloc() again to actually get the inode.
*
* To ensure that some other process does not grab the inode that
* was allocated during the first call to xfs_ialloc(), this routine
* also returns the [locked] bp pointing to the head of the freelist
* as ialloc_context. The caller should hold this buffer across
* the commit and pass it back into this routine on the second call.
*
* If we are allocating quota inodes, we do not have a parent inode
* to attach to or associate with (i.e. pip == NULL) because they
* are not linked into the directory structure - they are attached
* directly to the superblock - and so have no parent.
*/
int
xfs_ialloc(
xfs_trans_t *tp,
xfs_inode_t *pip,
umode_t mode,
xfs_nlink_t nlink,
xfs_dev_t rdev,
prid_t prid,
int okalloc,
xfs_buf_t **ialloc_context,
boolean_t *call_again,
xfs_inode_t **ipp)
{
xfs_ino_t ino;
xfs_inode_t *ip;
uint flags;
int error;
timespec_t tv;
int filestreams = 0;
/*
* Call the space management code to pick
* the on-disk inode to be allocated.
*/
error = xfs_dialloc(tp, pip ? pip->i_ino : 0, mode, okalloc,
ialloc_context, call_again, &ino);
if (error)
return error;
if (*call_again || ino == NULLFSINO) {
*ipp = NULL;
return 0;
}
ASSERT(*ialloc_context == NULL);
/*
* Get the in-core inode with the lock held exclusively.
* This is because we're setting fields here we need
* to prevent others from looking at until we're done.
*/
error = xfs_iget(tp->t_mountp, tp, ino, XFS_IGET_CREATE,
XFS_ILOCK_EXCL, &ip);
if (error)
return error;
ASSERT(ip != NULL);
ip->i_d.di_mode = mode;
ip->i_d.di_onlink = 0;
ip->i_d.di_nlink = nlink;
ASSERT(ip->i_d.di_nlink == nlink);
ip->i_d.di_uid = current_fsuid();
ip->i_d.di_gid = current_fsgid();
xfs_set_projid(ip, prid);
memset(&(ip->i_d.di_pad[0]), 0, sizeof(ip->i_d.di_pad));
/*
* If the superblock version is up to where we support new format
* inodes and this is currently an old format inode, then change
* the inode version number now. This way we only do the conversion
* here rather than here and in the flush/logging code.
*/
if (xfs_sb_version_hasnlink(&tp->t_mountp->m_sb) &&
ip->i_d.di_version == 1) {
ip->i_d.di_version = 2;
/*
* We've already zeroed the old link count, the projid field,
* and the pad field.
*/
}
/*
* Project ids won't be stored on disk if we are using a version 1 inode.
*/
if ((prid != 0) && (ip->i_d.di_version == 1))
xfs_bump_ino_vers2(tp, ip);
if (pip && XFS_INHERIT_GID(pip)) {
ip->i_d.di_gid = pip->i_d.di_gid;
if ((pip->i_d.di_mode & S_ISGID) && S_ISDIR(mode)) {
ip->i_d.di_mode |= S_ISGID;
}
}
/*
* If the group ID of the new file does not match the effective group
* ID or one of the supplementary group IDs, the S_ISGID bit is cleared
* (and only if the irix_sgid_inherit compatibility variable is set).
*/
if ((irix_sgid_inherit) &&
(ip->i_d.di_mode & S_ISGID) &&
(!in_group_p((gid_t)ip->i_d.di_gid))) {
ip->i_d.di_mode &= ~S_ISGID;
}
ip->i_d.di_size = 0;
ip->i_d.di_nextents = 0;
ASSERT(ip->i_d.di_nblocks == 0);
nanotime(&tv);
ip->i_d.di_mtime.t_sec = (__int32_t)tv.tv_sec;
ip->i_d.di_mtime.t_nsec = (__int32_t)tv.tv_nsec;
ip->i_d.di_atime = ip->i_d.di_mtime;
ip->i_d.di_ctime = ip->i_d.di_mtime;
/*
* di_gen will have been taken care of in xfs_iread.
*/
ip->i_d.di_extsize = 0;
ip->i_d.di_dmevmask = 0;
ip->i_d.di_dmstate = 0;
ip->i_d.di_flags = 0;
flags = XFS_ILOG_CORE;
switch (mode & S_IFMT) {
case S_IFIFO:
case S_IFCHR:
case S_IFBLK:
case S_IFSOCK:
ip->i_d.di_format = XFS_DINODE_FMT_DEV;
ip->i_df.if_u2.if_rdev = rdev;
ip->i_df.if_flags = 0;
flags |= XFS_ILOG_DEV;
break;
case S_IFREG:
/*
* we can't set up filestreams until after the VFS inode
* is set up properly.
*/
if (pip && xfs_inode_is_filestream(pip))
filestreams = 1;
/* fall through */
case S_IFDIR:
if (pip && (pip->i_d.di_flags & XFS_DIFLAG_ANY)) {
uint di_flags = 0;
if (S_ISDIR(mode)) {
if (pip->i_d.di_flags & XFS_DIFLAG_RTINHERIT)
di_flags |= XFS_DIFLAG_RTINHERIT;
if (pip->i_d.di_flags & XFS_DIFLAG_EXTSZINHERIT) {
di_flags |= XFS_DIFLAG_EXTSZINHERIT;
ip->i_d.di_extsize = pip->i_d.di_extsize;
}
} else if (S_ISREG(mode)) {
if (pip->i_d.di_flags & XFS_DIFLAG_RTINHERIT)
di_flags |= XFS_DIFLAG_REALTIME;
if (pip->i_d.di_flags & XFS_DIFLAG_EXTSZINHERIT) {
di_flags |= XFS_DIFLAG_EXTSIZE;
ip->i_d.di_extsize = pip->i_d.di_extsize;
}
}
if ((pip->i_d.di_flags & XFS_DIFLAG_NOATIME) &&
xfs_inherit_noatime)
di_flags |= XFS_DIFLAG_NOATIME;
if ((pip->i_d.di_flags & XFS_DIFLAG_NODUMP) &&
xfs_inherit_nodump)
di_flags |= XFS_DIFLAG_NODUMP;
if ((pip->i_d.di_flags & XFS_DIFLAG_SYNC) &&
xfs_inherit_sync)
di_flags |= XFS_DIFLAG_SYNC;
if ((pip->i_d.di_flags & XFS_DIFLAG_NOSYMLINKS) &&
xfs_inherit_nosymlinks)
di_flags |= XFS_DIFLAG_NOSYMLINKS;
if (pip->i_d.di_flags & XFS_DIFLAG_PROJINHERIT)
di_flags |= XFS_DIFLAG_PROJINHERIT;
if ((pip->i_d.di_flags & XFS_DIFLAG_NODEFRAG) &&
xfs_inherit_nodefrag)
di_flags |= XFS_DIFLAG_NODEFRAG;
if (pip->i_d.di_flags & XFS_DIFLAG_FILESTREAM)
di_flags |= XFS_DIFLAG_FILESTREAM;
ip->i_d.di_flags |= di_flags;
}
/* FALLTHROUGH */
case S_IFLNK:
ip->i_d.di_format = XFS_DINODE_FMT_EXTENTS;
ip->i_df.if_flags = XFS_IFEXTENTS;
ip->i_df.if_bytes = ip->i_df.if_real_bytes = 0;
ip->i_df.if_u1.if_extents = NULL;
break;
default:
ASSERT(0);
}
/*
* Attribute fork settings for new inode.
*/
ip->i_d.di_aformat = XFS_DINODE_FMT_EXTENTS;
ip->i_d.di_anextents = 0;
/*
* Log the new values stuffed into the inode.
*/
xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
xfs_trans_log_inode(tp, ip, flags);
/* now that we have an i_mode we can setup inode ops and unlock */
xfs_setup_inode(ip);
/* now we have set up the vfs inode we can associate the filestream */
if (filestreams) {
error = xfs_filestream_associate(pip, ip);
if (error < 0)
return -error;
if (!error)
xfs_iflags_set(ip, XFS_IFILESTREAM);
}
*ipp = ip;
return 0;
}
/*
* Free up the underlying blocks past new_size. The new size must be smaller
* than the current size. This routine can be used both for the attribute and
* data fork, and does not modify the inode size, which is left to the caller.
*
* The transaction passed to this routine must have made a permanent log
* reservation of at least XFS_ITRUNCATE_LOG_RES. This routine may commit the
* given transaction and start new ones, so make sure everything involved in
* the transaction is tidy before calling here. Some transaction will be
* returned to the caller to be committed. The incoming transaction must
* already include the inode, and both inode locks must be held exclusively.
* The inode must also be "held" within the transaction. On return the inode
* will be "held" within the returned transaction. This routine does NOT
* require any disk space to be reserved for it within the transaction.
*
* If we get an error, we must return with the inode locked and linked into the
* current transaction. This keeps things simple for the higher level code,
* because it always knows that the inode is locked and held in the transaction
* that returns to it whether errors occur or not. We don't mark the inode
* dirty on error so that transactions can be easily aborted if possible.
*/
int
xfs_itruncate_extents(
struct xfs_trans **tpp,
struct xfs_inode *ip,
int whichfork,
xfs_fsize_t new_size)
{
struct xfs_mount *mp = ip->i_mount;
struct xfs_trans *tp = *tpp;
struct xfs_trans *ntp;
xfs_bmap_free_t free_list;
xfs_fsblock_t first_block;
xfs_fileoff_t first_unmap_block;
xfs_fileoff_t last_block;
xfs_filblks_t unmap_len;
int committed;
int error = 0;
int done = 0;
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL|XFS_IOLOCK_EXCL));
ASSERT(new_size <= XFS_ISIZE(ip));
ASSERT(tp->t_flags & XFS_TRANS_PERM_LOG_RES);
ASSERT(ip->i_itemp != NULL);
ASSERT(ip->i_itemp->ili_lock_flags == 0);
ASSERT(!XFS_NOT_DQATTACHED(mp, ip));
trace_xfs_itruncate_extents_start(ip, new_size);
/*
* Since it is possible for space to become allocated beyond
* the end of the file (in a crash where the space is allocated
* but the inode size is not yet updated), simply remove any
* blocks which show up between the new EOF and the maximum
* possible file size. If the first block to be removed is
* beyond the maximum file size (ie it is the same as last_block),
* then there is nothing to do.
*/
first_unmap_block = XFS_B_TO_FSB(mp, (xfs_ufsize_t)new_size);
last_block = XFS_B_TO_FSB(mp, (xfs_ufsize_t)XFS_MAXIOFFSET(mp));
if (first_unmap_block == last_block)
return 0;
ASSERT(first_unmap_block < last_block);
unmap_len = last_block - first_unmap_block + 1;
while (!done) {
xfs_bmap_init(&free_list, &first_block);
error = xfs_bunmapi(tp, ip,
first_unmap_block, unmap_len,
xfs_bmapi_aflag(whichfork),
XFS_ITRUNC_MAX_EXTENTS,
&first_block, &free_list,
&done);
if (error)
goto out_bmap_cancel;
/*
* Duplicate the transaction that has the permanent
* reservation and commit the old transaction.
*/
error = xfs_bmap_finish(&tp, &free_list, &committed);
if (committed)
xfs_trans_ijoin(tp, ip, 0);
if (error)
goto out_bmap_cancel;
if (committed) {
/*
* Mark the inode dirty so it will be logged and
* moved forward in the log as part of every commit.
*/
xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
}
ntp = xfs_trans_dup(tp);
error = xfs_trans_commit(tp, 0);
tp = ntp;
xfs_trans_ijoin(tp, ip, 0);
if (error)
goto out;
/*
* Transaction commit worked ok so we can drop the extra ticket
* reference that we gained in xfs_trans_dup()
*/
xfs_log_ticket_put(tp->t_ticket);
error = xfs_trans_reserve(tp, 0,
XFS_ITRUNCATE_LOG_RES(mp), 0,
XFS_TRANS_PERM_LOG_RES,
XFS_ITRUNCATE_LOG_COUNT);
if (error)
goto out;
}
/*
* Always re-log the inode so that our permanent transaction can keep
* on rolling it forward in the log.
*/
xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
trace_xfs_itruncate_extents_end(ip, new_size);
out:
*tpp = tp;
return error;
out_bmap_cancel:
/*
* If the bunmapi call encounters an error, return to the caller where
* the transaction can be properly aborted. We just need to make sure
* we're not holding any resources that we were not when we came in.
*/
xfs_bmap_cancel(&free_list);
goto out;
}
/*
* This is called when the inode's link count goes to 0.
* We place the on-disk inode on a list in the AGI. It
* will be pulled from this list when the inode is freed.
*/
int
xfs_iunlink(
xfs_trans_t *tp,
xfs_inode_t *ip)
{
xfs_mount_t *mp;
xfs_agi_t *agi;
xfs_dinode_t *dip;
xfs_buf_t *agibp;
xfs_buf_t *ibp;
xfs_agino_t agino;
short bucket_index;
int offset;
int error;
ASSERT(ip->i_d.di_nlink == 0);
ASSERT(ip->i_d.di_mode != 0);
mp = tp->t_mountp;
/*
* Get the agi buffer first. It ensures lock ordering
* on the list.
*/
error = xfs_read_agi(mp, tp, XFS_INO_TO_AGNO(mp, ip->i_ino), &agibp);
if (error)
return error;
agi = XFS_BUF_TO_AGI(agibp);
/*
* Get the index into the agi hash table for the
* list this inode will go on.
*/
agino = XFS_INO_TO_AGINO(mp, ip->i_ino);
ASSERT(agino != 0);
bucket_index = agino % XFS_AGI_UNLINKED_BUCKETS;
ASSERT(agi->agi_unlinked[bucket_index]);
ASSERT(be32_to_cpu(agi->agi_unlinked[bucket_index]) != agino);
if (agi->agi_unlinked[bucket_index] != cpu_to_be32(NULLAGINO)) {
/*
* There is already another inode in the bucket we need
* to add ourselves to. Add us at the front of the list.
* Here we put the head pointer into our next pointer,
* and then we fall through to point the head at us.
*/
error = xfs_itobp(mp, tp, ip, &dip, &ibp, XBF_LOCK);
if (error)
return error;
ASSERT(dip->di_next_unlinked == cpu_to_be32(NULLAGINO));
dip->di_next_unlinked = agi->agi_unlinked[bucket_index];
offset = ip->i_imap.im_boffset +
offsetof(xfs_dinode_t, di_next_unlinked);
xfs_trans_inode_buf(tp, ibp);
xfs_trans_log_buf(tp, ibp, offset,
(offset + sizeof(xfs_agino_t) - 1));
xfs_inobp_check(mp, ibp);
}
/*
* Point the bucket head pointer at the inode being inserted.
*/
ASSERT(agino != 0);
agi->agi_unlinked[bucket_index] = cpu_to_be32(agino);
offset = offsetof(xfs_agi_t, agi_unlinked) +
(sizeof(xfs_agino_t) * bucket_index);
xfs_trans_log_buf(tp, agibp, offset,
(offset + sizeof(xfs_agino_t) - 1));
return 0;
}
/*
* Pull the on-disk inode from the AGI unlinked list.
*/
STATIC int
xfs_iunlink_remove(
xfs_trans_t *tp,
xfs_inode_t *ip)
{
xfs_ino_t next_ino;
xfs_mount_t *mp;
xfs_agi_t *agi;
xfs_dinode_t *dip;
xfs_buf_t *agibp;
xfs_buf_t *ibp;
xfs_agnumber_t agno;
xfs_agino_t agino;
xfs_agino_t next_agino;
xfs_buf_t *last_ibp;
xfs_dinode_t *last_dip = NULL;
short bucket_index;
int offset, last_offset = 0;
int error;
mp = tp->t_mountp;
agno = XFS_INO_TO_AGNO(mp, ip->i_ino);
/*
* Get the agi buffer first. It ensures lock ordering
* on the list.
*/
error = xfs_read_agi(mp, tp, agno, &agibp);
if (error)
return error;
agi = XFS_BUF_TO_AGI(agibp);
/*
* Get the index into the agi hash table for the
* list this inode will go on.
*/
agino = XFS_INO_TO_AGINO(mp, ip->i_ino);
ASSERT(agino != 0);
bucket_index = agino % XFS_AGI_UNLINKED_BUCKETS;
ASSERT(agi->agi_unlinked[bucket_index] != cpu_to_be32(NULLAGINO));
ASSERT(agi->agi_unlinked[bucket_index]);
if (be32_to_cpu(agi->agi_unlinked[bucket_index]) == agino) {
/*
* We're at the head of the list. Get the inode's
* on-disk buffer to see if there is anyone after us
* on the list. Only modify our next pointer if it
* is not already NULLAGINO. This saves us the overhead
* of dealing with the buffer when there is no need to
* change it.
*/
error = xfs_itobp(mp, tp, ip, &dip, &ibp, XBF_LOCK);
if (error) {
xfs_warn(mp, "%s: xfs_itobp() returned error %d.",
__func__, error);
return error;
}
next_agino = be32_to_cpu(dip->di_next_unlinked);
ASSERT(next_agino != 0);
if (next_agino != NULLAGINO) {
dip->di_next_unlinked = cpu_to_be32(NULLAGINO);
offset = ip->i_imap.im_boffset +
offsetof(xfs_dinode_t, di_next_unlinked);
xfs_trans_inode_buf(tp, ibp);
xfs_trans_log_buf(tp, ibp, offset,
(offset + sizeof(xfs_agino_t) - 1));
xfs_inobp_check(mp, ibp);
} else {
xfs_trans_brelse(tp, ibp);
}
/*
* Point the bucket head pointer at the next inode.
*/
ASSERT(next_agino != 0);
ASSERT(next_agino != agino);
agi->agi_unlinked[bucket_index] = cpu_to_be32(next_agino);
offset = offsetof(xfs_agi_t, agi_unlinked) +
(sizeof(xfs_agino_t) * bucket_index);
xfs_trans_log_buf(tp, agibp, offset,
(offset + sizeof(xfs_agino_t) - 1));
} else {
/*
* We need to search the list for the inode being freed.
*/
next_agino = be32_to_cpu(agi->agi_unlinked[bucket_index]);
last_ibp = NULL;
while (next_agino != agino) {
/*
* If the last inode wasn't the one pointing to
* us, then release its buffer since we're not
* going to do anything with it.
*/
if (last_ibp != NULL) {
xfs_trans_brelse(tp, last_ibp);
}
next_ino = XFS_AGINO_TO_INO(mp, agno, next_agino);
error = xfs_inotobp(mp, tp, next_ino, &last_dip,
&last_ibp, &last_offset, 0);
if (error) {
xfs_warn(mp,
"%s: xfs_inotobp() returned error %d.",
__func__, error);
return error;
}
next_agino = be32_to_cpu(last_dip->di_next_unlinked);
ASSERT(next_agino != NULLAGINO);
ASSERT(next_agino != 0);
}
/*
* Now last_ibp points to the buffer previous to us on
* the unlinked list. Pull us from the list.
*/
error = xfs_itobp(mp, tp, ip, &dip, &ibp, XBF_LOCK);
if (error) {
xfs_warn(mp, "%s: xfs_itobp(2) returned error %d.",
__func__, error);
return error;
}
next_agino = be32_to_cpu(dip->di_next_unlinked);
ASSERT(next_agino != 0);
ASSERT(next_agino != agino);
if (next_agino != NULLAGINO) {
dip->di_next_unlinked = cpu_to_be32(NULLAGINO);
offset = ip->i_imap.im_boffset +
offsetof(xfs_dinode_t, di_next_unlinked);
xfs_trans_inode_buf(tp, ibp);
xfs_trans_log_buf(tp, ibp, offset,
(offset + sizeof(xfs_agino_t) - 1));
xfs_inobp_check(mp, ibp);
} else {
xfs_trans_brelse(tp, ibp);
}
/*
* Point the previous inode on the list to the next inode.
*/
last_dip->di_next_unlinked = cpu_to_be32(next_agino);
ASSERT(next_agino != 0);
offset = last_offset + offsetof(xfs_dinode_t, di_next_unlinked);
xfs_trans_inode_buf(tp, last_ibp);
xfs_trans_log_buf(tp, last_ibp, offset,
(offset + sizeof(xfs_agino_t) - 1));
xfs_inobp_check(mp, last_ibp);
}
return 0;
}
/*
* A big issue when freeing the inode cluster is is that we _cannot_ skip any
* inodes that are in memory - they all must be marked stale and attached to
* the cluster buffer.
*/
STATIC int
xfs_ifree_cluster(
xfs_inode_t *free_ip,
xfs_trans_t *tp,
xfs_ino_t inum)
{
xfs_mount_t *mp = free_ip->i_mount;
int blks_per_cluster;
int nbufs;
int ninodes;
int i, j;
xfs_daddr_t blkno;
xfs_buf_t *bp;
xfs_inode_t *ip;
xfs_inode_log_item_t *iip;
xfs_log_item_t *lip;
struct xfs_perag *pag;
pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, inum));
if (mp->m_sb.sb_blocksize >= XFS_INODE_CLUSTER_SIZE(mp)) {
blks_per_cluster = 1;
ninodes = mp->m_sb.sb_inopblock;
nbufs = XFS_IALLOC_BLOCKS(mp);
} else {
blks_per_cluster = XFS_INODE_CLUSTER_SIZE(mp) /
mp->m_sb.sb_blocksize;
ninodes = blks_per_cluster * mp->m_sb.sb_inopblock;
nbufs = XFS_IALLOC_BLOCKS(mp) / blks_per_cluster;
}
for (j = 0; j < nbufs; j++, inum += ninodes) {
blkno = XFS_AGB_TO_DADDR(mp, XFS_INO_TO_AGNO(mp, inum),
XFS_INO_TO_AGBNO(mp, inum));
/*
* We obtain and lock the backing buffer first in the process
* here, as we have to ensure that any dirty inode that we
* can't get the flush lock on is attached to the buffer.
* If we scan the in-memory inodes first, then buffer IO can
* complete before we get a lock on it, and hence we may fail
* to mark all the active inodes on the buffer stale.
*/
bp = xfs_trans_get_buf(tp, mp->m_ddev_targp, blkno,
mp->m_bsize * blks_per_cluster,
XBF_LOCK);
if (!bp)
return ENOMEM;
/*
* Walk the inodes already attached to the buffer and mark them
* stale. These will all have the flush locks held, so an
* in-memory inode walk can't lock them. By marking them all
* stale first, we will not attempt to lock them in the loop
* below as the XFS_ISTALE flag will be set.
*/
lip = bp->b_fspriv;
while (lip) {
if (lip->li_type == XFS_LI_INODE) {
iip = (xfs_inode_log_item_t *)lip;
ASSERT(iip->ili_logged == 1);
lip->li_cb = xfs_istale_done;
xfs_trans_ail_copy_lsn(mp->m_ail,
&iip->ili_flush_lsn,
&iip->ili_item.li_lsn);
xfs_iflags_set(iip->ili_inode, XFS_ISTALE);
}
lip = lip->li_bio_list;
}
/*
* For each inode in memory attempt to add it to the inode
* buffer and set it up for being staled on buffer IO
* completion. This is safe as we've locked out tail pushing
* and flushing by locking the buffer.
*
* We have already marked every inode that was part of a
* transaction stale above, which means there is no point in
* even trying to lock them.
*/
for (i = 0; i < ninodes; i++) {
retry:
rcu_read_lock();
ip = radix_tree_lookup(&pag->pag_ici_root,
XFS_INO_TO_AGINO(mp, (inum + i)));
/* Inode not in memory, nothing to do */
if (!ip) {
rcu_read_unlock();
continue;
}
/*
* because this is an RCU protected lookup, we could
* find a recently freed or even reallocated inode
* during the lookup. We need to check under the
* i_flags_lock for a valid inode here. Skip it if it
* is not valid, the wrong inode or stale.
*/
spin_lock(&ip->i_flags_lock);
if (ip->i_ino != inum + i ||
__xfs_iflags_test(ip, XFS_ISTALE)) {
spin_unlock(&ip->i_flags_lock);
rcu_read_unlock();
continue;
}
spin_unlock(&ip->i_flags_lock);
/*
* Don't try to lock/unlock the current inode, but we
* _cannot_ skip the other inodes that we did not find
* in the list attached to the buffer and are not
* already marked stale. If we can't lock it, back off
* and retry.
*/
if (ip != free_ip &&
!xfs_ilock_nowait(ip, XFS_ILOCK_EXCL)) {
rcu_read_unlock();
delay(1);
goto retry;
}
rcu_read_unlock();
xfs_iflock(ip);
xfs_iflags_set(ip, XFS_ISTALE);
/*
* we don't need to attach clean inodes or those only
* with unlogged changes (which we throw away, anyway).
*/
iip = ip->i_itemp;
if (!iip || xfs_inode_clean(ip)) {
ASSERT(ip != free_ip);
xfs_ifunlock(ip);
xfs_iunlock(ip, XFS_ILOCK_EXCL);
continue;
}
iip->ili_last_fields = iip->ili_fields;
iip->ili_fields = 0;
iip->ili_logged = 1;
xfs_trans_ail_copy_lsn(mp->m_ail, &iip->ili_flush_lsn,
&iip->ili_item.li_lsn);
xfs_buf_attach_iodone(bp, xfs_istale_done,
&iip->ili_item);
if (ip != free_ip)
xfs_iunlock(ip, XFS_ILOCK_EXCL);
}
xfs_trans_stale_inode_buf(tp, bp);
xfs_trans_binval(tp, bp);
}
xfs_perag_put(pag);
return 0;
}
/*
* This is called to return an inode to the inode free list.
* The inode should already be truncated to 0 length and have
* no pages associated with it. This routine also assumes that
* the inode is already a part of the transaction.
*
* The on-disk copy of the inode will have been added to the list
* of unlinked inodes in the AGI. We need to remove the inode from
* that list atomically with respect to freeing it here.
*/
int
xfs_ifree(
xfs_trans_t *tp,
xfs_inode_t *ip,
xfs_bmap_free_t *flist)
{
int error;
int delete;
xfs_ino_t first_ino;
xfs_dinode_t *dip;
xfs_buf_t *ibp;
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
ASSERT(ip->i_d.di_nlink == 0);
ASSERT(ip->i_d.di_nextents == 0);
ASSERT(ip->i_d.di_anextents == 0);
ASSERT(ip->i_d.di_size == 0 || !S_ISREG(ip->i_d.di_mode));
ASSERT(ip->i_d.di_nblocks == 0);
/*
* Pull the on-disk inode from the AGI unlinked list.
*/
error = xfs_iunlink_remove(tp, ip);
if (error != 0) {
return error;
}
error = xfs_difree(tp, ip->i_ino, flist, &delete, &first_ino);
if (error != 0) {
return error;
}
ip->i_d.di_mode = 0; /* mark incore inode as free */
ip->i_d.di_flags = 0;
ip->i_d.di_dmevmask = 0;
ip->i_d.di_forkoff = 0; /* mark the attr fork not in use */
ip->i_d.di_format = XFS_DINODE_FMT_EXTENTS;
ip->i_d.di_aformat = XFS_DINODE_FMT_EXTENTS;
/*
* Bump the generation count so no one will be confused
* by reincarnations of this inode.
*/
ip->i_d.di_gen++;
xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
error = xfs_itobp(ip->i_mount, tp, ip, &dip, &ibp, XBF_LOCK);
if (error)
return error;
/*
* Clear the on-disk di_mode. This is to prevent xfs_bulkstat
* from picking up this inode when it is reclaimed (its incore state
* initialzed but not flushed to disk yet). The in-core di_mode is
* already cleared and a corresponding transaction logged.
* The hack here just synchronizes the in-core to on-disk
* di_mode value in advance before the actual inode sync to disk.
* This is OK because the inode is already unlinked and would never
* change its di_mode again for this inode generation.
* This is a temporary hack that would require a proper fix
* in the future.
*/
dip->di_mode = 0;
if (delete) {
error = xfs_ifree_cluster(ip, tp, first_ino);
}
return error;
}
/*
* Reallocate the space for if_broot based on the number of records
* being added or deleted as indicated in rec_diff. Move the records
* and pointers in if_broot to fit the new size. When shrinking this
* will eliminate holes between the records and pointers created by
* the caller. When growing this will create holes to be filled in
* by the caller.
*
* The caller must not request to add more records than would fit in
* the on-disk inode root. If the if_broot is currently NULL, then
* if we adding records one will be allocated. The caller must also
* not request that the number of records go below zero, although
* it can go to zero.
*
* ip -- the inode whose if_broot area is changing
* ext_diff -- the change in the number of records, positive or negative,
* requested for the if_broot array.
*/
void
xfs_iroot_realloc(
xfs_inode_t *ip,
int rec_diff,
int whichfork)
{
struct xfs_mount *mp = ip->i_mount;
int cur_max;
xfs_ifork_t *ifp;
struct xfs_btree_block *new_broot;
int new_max;
size_t new_size;
char *np;
char *op;
/*
* Handle the degenerate case quietly.
*/
if (rec_diff == 0) {
return;
}
ifp = XFS_IFORK_PTR(ip, whichfork);
if (rec_diff > 0) {
/*
* If there wasn't any memory allocated before, just
* allocate it now and get out.
*/
if (ifp->if_broot_bytes == 0) {
new_size = (size_t)XFS_BMAP_BROOT_SPACE_CALC(rec_diff);
ifp->if_broot = kmem_alloc(new_size, KM_SLEEP | KM_NOFS);
ifp->if_broot_bytes = (int)new_size;
return;
}
/*
* If there is already an existing if_broot, then we need
* to realloc() it and shift the pointers to their new
* location. The records don't change location because
* they are kept butted up against the btree block header.
*/
cur_max = xfs_bmbt_maxrecs(mp, ifp->if_broot_bytes, 0);
new_max = cur_max + rec_diff;
new_size = (size_t)XFS_BMAP_BROOT_SPACE_CALC(new_max);
ifp->if_broot = kmem_realloc(ifp->if_broot, new_size,
(size_t)XFS_BMAP_BROOT_SPACE_CALC(cur_max), /* old size */
KM_SLEEP | KM_NOFS);
op = (char *)XFS_BMAP_BROOT_PTR_ADDR(mp, ifp->if_broot, 1,
ifp->if_broot_bytes);
np = (char *)XFS_BMAP_BROOT_PTR_ADDR(mp, ifp->if_broot, 1,
(int)new_size);
ifp->if_broot_bytes = (int)new_size;
ASSERT(ifp->if_broot_bytes <=
XFS_IFORK_SIZE(ip, whichfork) + XFS_BROOT_SIZE_ADJ);
memmove(np, op, cur_max * (uint)sizeof(xfs_dfsbno_t));
return;
}
/*
* rec_diff is less than 0. In this case, we are shrinking the
* if_broot buffer. It must already exist. If we go to zero
* records, just get rid of the root and clear the status bit.
*/
ASSERT((ifp->if_broot != NULL) && (ifp->if_broot_bytes > 0));
cur_max = xfs_bmbt_maxrecs(mp, ifp->if_broot_bytes, 0);
new_max = cur_max + rec_diff;
ASSERT(new_max >= 0);
if (new_max > 0)
new_size = (size_t)XFS_BMAP_BROOT_SPACE_CALC(new_max);
else
new_size = 0;
if (new_size > 0) {
new_broot = kmem_alloc(new_size, KM_SLEEP | KM_NOFS);
/*
* First copy over the btree block header.
*/
memcpy(new_broot, ifp->if_broot, XFS_BTREE_LBLOCK_LEN);
} else {
new_broot = NULL;
ifp->if_flags &= ~XFS_IFBROOT;
}
/*
* Only copy the records and pointers if there are any.
*/
if (new_max > 0) {
/*
* First copy the records.
*/
op = (char *)XFS_BMBT_REC_ADDR(mp, ifp->if_broot, 1);
np = (char *)XFS_BMBT_REC_ADDR(mp, new_broot, 1);
memcpy(np, op, new_max * (uint)sizeof(xfs_bmbt_rec_t));
/*
* Then copy the pointers.
*/
op = (char *)XFS_BMAP_BROOT_PTR_ADDR(mp, ifp->if_broot, 1,
ifp->if_broot_bytes);
np = (char *)XFS_BMAP_BROOT_PTR_ADDR(mp, new_broot, 1,
(int)new_size);
memcpy(np, op, new_max * (uint)sizeof(xfs_dfsbno_t));
}
kmem_free(ifp->if_broot);
ifp->if_broot = new_broot;
ifp->if_broot_bytes = (int)new_size;
ASSERT(ifp->if_broot_bytes <=
XFS_IFORK_SIZE(ip, whichfork) + XFS_BROOT_SIZE_ADJ);
return;
}
/*
* This is called when the amount of space needed for if_data
* is increased or decreased. The change in size is indicated by
* the number of bytes that need to be added or deleted in the
* byte_diff parameter.
*
* If the amount of space needed has decreased below the size of the
* inline buffer, then switch to using the inline buffer. Otherwise,
* use kmem_realloc() or kmem_alloc() to adjust the size of the buffer
* to what is needed.
*
* ip -- the inode whose if_data area is changing
* byte_diff -- the change in the number of bytes, positive or negative,
* requested for the if_data array.
*/
void
xfs_idata_realloc(
xfs_inode_t *ip,
int byte_diff,
int whichfork)
{
xfs_ifork_t *ifp;
int new_size;
int real_size;
if (byte_diff == 0) {
return;
}
ifp = XFS_IFORK_PTR(ip, whichfork);
new_size = (int)ifp->if_bytes + byte_diff;
ASSERT(new_size >= 0);
if (new_size == 0) {
if (ifp->if_u1.if_data != ifp->if_u2.if_inline_data) {
kmem_free(ifp->if_u1.if_data);
}
ifp->if_u1.if_data = NULL;
real_size = 0;
} else if (new_size <= sizeof(ifp->if_u2.if_inline_data)) {
/*
* If the valid extents/data can fit in if_inline_ext/data,
* copy them from the malloc'd vector and free it.
*/
if (ifp->if_u1.if_data == NULL) {
ifp->if_u1.if_data = ifp->if_u2.if_inline_data;
} else if (ifp->if_u1.if_data != ifp->if_u2.if_inline_data) {
ASSERT(ifp->if_real_bytes != 0);
memcpy(ifp->if_u2.if_inline_data, ifp->if_u1.if_data,
new_size);
kmem_free(ifp->if_u1.if_data);
ifp->if_u1.if_data = ifp->if_u2.if_inline_data;
}
real_size = 0;
} else {
/*
* Stuck with malloc/realloc.
* For inline data, the underlying buffer must be
* a multiple of 4 bytes in size so that it can be
* logged and stay on word boundaries. We enforce
* that here.
*/
real_size = roundup(new_size, 4);
if (ifp->if_u1.if_data == NULL) {
ASSERT(ifp->if_real_bytes == 0);
ifp->if_u1.if_data = kmem_alloc(real_size,
KM_SLEEP | KM_NOFS);
} else if (ifp->if_u1.if_data != ifp->if_u2.if_inline_data) {
/*
* Only do the realloc if the underlying size
* is really changing.
*/
if (ifp->if_real_bytes != real_size) {
ifp->if_u1.if_data =
kmem_realloc(ifp->if_u1.if_data,
real_size,
ifp->if_real_bytes,
KM_SLEEP | KM_NOFS);
}
} else {
ASSERT(ifp->if_real_bytes == 0);
ifp->if_u1.if_data = kmem_alloc(real_size,
KM_SLEEP | KM_NOFS);
memcpy(ifp->if_u1.if_data, ifp->if_u2.if_inline_data,
ifp->if_bytes);
}
}
ifp->if_real_bytes = real_size;
ifp->if_bytes = new_size;
ASSERT(ifp->if_bytes <= XFS_IFORK_SIZE(ip, whichfork));
}
void
xfs_idestroy_fork(
xfs_inode_t *ip,
int whichfork)
{
xfs_ifork_t *ifp;
ifp = XFS_IFORK_PTR(ip, whichfork);
if (ifp->if_broot != NULL) {
kmem_free(ifp->if_broot);
ifp->if_broot = NULL;
}
/*
* If the format is local, then we can't have an extents
* array so just look for an inline data array. If we're
* not local then we may or may not have an extents list,
* so check and free it up if we do.
*/
if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) {
if ((ifp->if_u1.if_data != ifp->if_u2.if_inline_data) &&
(ifp->if_u1.if_data != NULL)) {
ASSERT(ifp->if_real_bytes != 0);
kmem_free(ifp->if_u1.if_data);
ifp->if_u1.if_data = NULL;
ifp->if_real_bytes = 0;
}
} else if ((ifp->if_flags & XFS_IFEXTENTS) &&
((ifp->if_flags & XFS_IFEXTIREC) ||
((ifp->if_u1.if_extents != NULL) &&
(ifp->if_u1.if_extents != ifp->if_u2.if_inline_ext)))) {
ASSERT(ifp->if_real_bytes != 0);
xfs_iext_destroy(ifp);
}
ASSERT(ifp->if_u1.if_extents == NULL ||
ifp->if_u1.if_extents == ifp->if_u2.if_inline_ext);
ASSERT(ifp->if_real_bytes == 0);
if (whichfork == XFS_ATTR_FORK) {
kmem_zone_free(xfs_ifork_zone, ip->i_afp);
ip->i_afp = NULL;
}
}
/*
* This is called to unpin an inode. The caller must have the inode locked
* in at least shared mode so that the buffer cannot be subsequently pinned
* once someone is waiting for it to be unpinned.
*/
static void
xfs_iunpin(
struct xfs_inode *ip)
{
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL|XFS_ILOCK_SHARED));
trace_xfs_inode_unpin_nowait(ip, _RET_IP_);
/* Give the log a push to start the unpinning I/O */
xfs_log_force_lsn(ip->i_mount, ip->i_itemp->ili_last_lsn, 0);
}
static void
__xfs_iunpin_wait(
struct xfs_inode *ip)
{
wait_queue_head_t *wq = bit_waitqueue(&ip->i_flags, __XFS_IPINNED_BIT);
DEFINE_WAIT_BIT(wait, &ip->i_flags, __XFS_IPINNED_BIT);
xfs_iunpin(ip);
do {
prepare_to_wait(wq, &wait.wait, TASK_UNINTERRUPTIBLE);
if (xfs_ipincount(ip))
io_schedule();
} while (xfs_ipincount(ip));
finish_wait(wq, &wait.wait);
}
void
xfs_iunpin_wait(
struct xfs_inode *ip)
{
if (xfs_ipincount(ip))
__xfs_iunpin_wait(ip);
}
/*
* xfs_iextents_copy()
*
* This is called to copy the REAL extents (as opposed to the delayed
* allocation extents) from the inode into the given buffer. It
* returns the number of bytes copied into the buffer.
*
* If there are no delayed allocation extents, then we can just
* memcpy() the extents into the buffer. Otherwise, we need to
* examine each extent in turn and skip those which are delayed.
*/
int
xfs_iextents_copy(
xfs_inode_t *ip,
xfs_bmbt_rec_t *dp,
int whichfork)
{
int copied;
int i;
xfs_ifork_t *ifp;
int nrecs;
xfs_fsblock_t start_block;
ifp = XFS_IFORK_PTR(ip, whichfork);
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL|XFS_ILOCK_SHARED));
ASSERT(ifp->if_bytes > 0);
nrecs = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
XFS_BMAP_TRACE_EXLIST(ip, nrecs, whichfork);
ASSERT(nrecs > 0);
/*
* There are some delayed allocation extents in the
* inode, so copy the extents one at a time and skip
* the delayed ones. There must be at least one
* non-delayed extent.
*/
copied = 0;
for (i = 0; i < nrecs; i++) {
xfs_bmbt_rec_host_t *ep = xfs_iext_get_ext(ifp, i);
start_block = xfs_bmbt_get_startblock(ep);
if (isnullstartblock(start_block)) {
/*
* It's a delayed allocation extent, so skip it.
*/
continue;
}
/* Translate to on disk format */
put_unaligned(cpu_to_be64(ep->l0), &dp->l0);
put_unaligned(cpu_to_be64(ep->l1), &dp->l1);
dp++;
copied++;
}
ASSERT(copied != 0);
xfs_validate_extents(ifp, copied, XFS_EXTFMT_INODE(ip));
return (copied * (uint)sizeof(xfs_bmbt_rec_t));
}
/*
* Each of the following cases stores data into the same region
* of the on-disk inode, so only one of them can be valid at
* any given time. While it is possible to have conflicting formats
* and log flags, e.g. having XFS_ILOG_?DATA set when the fork is
* in EXTENTS format, this can only happen when the fork has
* changed formats after being modified but before being flushed.
* In these cases, the format always takes precedence, because the
* format indicates the current state of the fork.
*/
/*ARGSUSED*/
STATIC void
xfs_iflush_fork(
xfs_inode_t *ip,
xfs_dinode_t *dip,
xfs_inode_log_item_t *iip,
int whichfork,
xfs_buf_t *bp)
{
char *cp;
xfs_ifork_t *ifp;
xfs_mount_t *mp;
#ifdef XFS_TRANS_DEBUG
int first;
#endif
static const short brootflag[2] =
{ XFS_ILOG_DBROOT, XFS_ILOG_ABROOT };
static const short dataflag[2] =
{ XFS_ILOG_DDATA, XFS_ILOG_ADATA };
static const short extflag[2] =
{ XFS_ILOG_DEXT, XFS_ILOG_AEXT };
if (!iip)
return;
ifp = XFS_IFORK_PTR(ip, whichfork);
/*
* This can happen if we gave up in iformat in an error path,
* for the attribute fork.
*/
if (!ifp) {
ASSERT(whichfork == XFS_ATTR_FORK);
return;
}
cp = XFS_DFORK_PTR(dip, whichfork);
mp = ip->i_mount;
switch (XFS_IFORK_FORMAT(ip, whichfork)) {
case XFS_DINODE_FMT_LOCAL:
if ((iip->ili_fields & dataflag[whichfork]) &&
(ifp->if_bytes > 0)) {
ASSERT(ifp->if_u1.if_data != NULL);
ASSERT(ifp->if_bytes <= XFS_IFORK_SIZE(ip, whichfork));
memcpy(cp, ifp->if_u1.if_data, ifp->if_bytes);
}
break;
case XFS_DINODE_FMT_EXTENTS:
ASSERT((ifp->if_flags & XFS_IFEXTENTS) ||
!(iip->ili_fields & extflag[whichfork]));
if ((iip->ili_fields & extflag[whichfork]) &&
(ifp->if_bytes > 0)) {
ASSERT(xfs_iext_get_ext(ifp, 0));
ASSERT(XFS_IFORK_NEXTENTS(ip, whichfork) > 0);
(void)xfs_iextents_copy(ip, (xfs_bmbt_rec_t *)cp,
whichfork);
}
break;
case XFS_DINODE_FMT_BTREE:
if ((iip->ili_fields & brootflag[whichfork]) &&
(ifp->if_broot_bytes > 0)) {
ASSERT(ifp->if_broot != NULL);
ASSERT(ifp->if_broot_bytes <=
(XFS_IFORK_SIZE(ip, whichfork) +
XFS_BROOT_SIZE_ADJ));
xfs_bmbt_to_bmdr(mp, ifp->if_broot, ifp->if_broot_bytes,
(xfs_bmdr_block_t *)cp,
XFS_DFORK_SIZE(dip, mp, whichfork));
}
break;
case XFS_DINODE_FMT_DEV:
if (iip->ili_fields & XFS_ILOG_DEV) {
ASSERT(whichfork == XFS_DATA_FORK);
xfs_dinode_put_rdev(dip, ip->i_df.if_u2.if_rdev);
}
break;
case XFS_DINODE_FMT_UUID:
if (iip->ili_fields & XFS_ILOG_UUID) {
ASSERT(whichfork == XFS_DATA_FORK);
memcpy(XFS_DFORK_DPTR(dip),
&ip->i_df.if_u2.if_uuid,
sizeof(uuid_t));
}
break;
default:
ASSERT(0);
break;
}
}
STATIC int
xfs_iflush_cluster(
xfs_inode_t *ip,
xfs_buf_t *bp)
{
xfs_mount_t *mp = ip->i_mount;
struct xfs_perag *pag;
unsigned long first_index, mask;
unsigned long inodes_per_cluster;
int ilist_size;
xfs_inode_t **ilist;
xfs_inode_t *iq;
int nr_found;
int clcount = 0;
int bufwasdelwri;
int i;
pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, ip->i_ino));
inodes_per_cluster = XFS_INODE_CLUSTER_SIZE(mp) >> mp->m_sb.sb_inodelog;
ilist_size = inodes_per_cluster * sizeof(xfs_inode_t *);
ilist = kmem_alloc(ilist_size, KM_MAYFAIL|KM_NOFS);
if (!ilist)
goto out_put;
mask = ~(((XFS_INODE_CLUSTER_SIZE(mp) >> mp->m_sb.sb_inodelog)) - 1);
first_index = XFS_INO_TO_AGINO(mp, ip->i_ino) & mask;
rcu_read_lock();
/* really need a gang lookup range call here */
nr_found = radix_tree_gang_lookup(&pag->pag_ici_root, (void**)ilist,
first_index, inodes_per_cluster);
if (nr_found == 0)
goto out_free;
for (i = 0; i < nr_found; i++) {
iq = ilist[i];
if (iq == ip)
continue;
/*
* because this is an RCU protected lookup, we could find a
* recently freed or even reallocated inode during the lookup.
* We need to check under the i_flags_lock for a valid inode
* here. Skip it if it is not valid or the wrong inode.
*/
spin_lock(&ip->i_flags_lock);
if (!ip->i_ino ||
(XFS_INO_TO_AGINO(mp, iq->i_ino) & mask) != first_index) {
spin_unlock(&ip->i_flags_lock);
continue;
}
spin_unlock(&ip->i_flags_lock);
/*
* Do an un-protected check to see if the inode is dirty and
* is a candidate for flushing. These checks will be repeated
* later after the appropriate locks are acquired.
*/
if (xfs_inode_clean(iq) && xfs_ipincount(iq) == 0)
continue;
/*
* Try to get locks. If any are unavailable or it is pinned,
* then this inode cannot be flushed and is skipped.
*/
if (!xfs_ilock_nowait(iq, XFS_ILOCK_SHARED))
continue;
if (!xfs_iflock_nowait(iq)) {
xfs_iunlock(iq, XFS_ILOCK_SHARED);
continue;
}
if (xfs_ipincount(iq)) {
xfs_ifunlock(iq);
xfs_iunlock(iq, XFS_ILOCK_SHARED);
continue;
}
/*
* arriving here means that this inode can be flushed. First
* re-check that it's dirty before flushing.
*/
if (!xfs_inode_clean(iq)) {
int error;
error = xfs_iflush_int(iq, bp);
if (error) {
xfs_iunlock(iq, XFS_ILOCK_SHARED);
goto cluster_corrupt_out;
}
clcount++;
} else {
xfs_ifunlock(iq);
}
xfs_iunlock(iq, XFS_ILOCK_SHARED);
}
if (clcount) {
XFS_STATS_INC(xs_icluster_flushcnt);
XFS_STATS_ADD(xs_icluster_flushinode, clcount);
}
out_free:
rcu_read_unlock();
kmem_free(ilist);
out_put:
xfs_perag_put(pag);
return 0;
cluster_corrupt_out:
/*
* Corruption detected in the clustering loop. Invalidate the
* inode buffer and shut down the filesystem.
*/
rcu_read_unlock();
/*
* Clean up the buffer. If it was B_DELWRI, just release it --
* brelse can handle it with no problems. If not, shut down the
* filesystem before releasing the buffer.
*/
bufwasdelwri = XFS_BUF_ISDELAYWRITE(bp);
if (bufwasdelwri)
xfs_buf_relse(bp);
xfs_force_shutdown(mp, SHUTDOWN_CORRUPT_INCORE);
if (!bufwasdelwri) {
/*
* Just like incore_relse: if we have b_iodone functions,
* mark the buffer as an error and call them. Otherwise
* mark it as stale and brelse.
*/
if (bp->b_iodone) {
XFS_BUF_UNDONE(bp);
xfs_buf_stale(bp);
xfs_buf_ioerror(bp, EIO);
xfs_buf_ioend(bp, 0);
} else {
xfs_buf_stale(bp);
xfs_buf_relse(bp);
}
}
/*
* Unlocks the flush lock
*/
xfs_iflush_abort(iq);
kmem_free(ilist);
xfs_perag_put(pag);
return XFS_ERROR(EFSCORRUPTED);
}
/*
* xfs_iflush() will write a modified inode's changes out to the
* inode's on disk home. The caller must have the inode lock held
* in at least shared mode and the inode flush completion must be
* active as well. The inode lock will still be held upon return from
* the call and the caller is free to unlock it.
* The inode flush will be completed when the inode reaches the disk.
* The flags indicate how the inode's buffer should be written out.
*/
int
xfs_iflush(
xfs_inode_t *ip,
uint flags)
{
xfs_inode_log_item_t *iip;
xfs_buf_t *bp;
xfs_dinode_t *dip;
xfs_mount_t *mp;
int error;
XFS_STATS_INC(xs_iflush_count);
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL|XFS_ILOCK_SHARED));
ASSERT(xfs_isiflocked(ip));
ASSERT(ip->i_d.di_format != XFS_DINODE_FMT_BTREE ||
ip->i_d.di_nextents > XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK));
iip = ip->i_itemp;
mp = ip->i_mount;
/*
* We can't flush the inode until it is unpinned, so wait for it if we
* are allowed to block. We know no one new can pin it, because we are
* holding the inode lock shared and you need to hold it exclusively to
* pin the inode.
*
* If we are not allowed to block, force the log out asynchronously so
* that when we come back the inode will be unpinned. If other inodes
* in the same cluster are dirty, they will probably write the inode
* out for us if they occur after the log force completes.
*/
if (!(flags & SYNC_WAIT) && xfs_ipincount(ip)) {
xfs_iunpin(ip);
xfs_ifunlock(ip);
return EAGAIN;
}
xfs_iunpin_wait(ip);
/*
* For stale inodes we cannot rely on the backing buffer remaining
* stale in cache for the remaining life of the stale inode and so
* xfs_itobp() below may give us a buffer that no longer contains
* inodes below. We have to check this after ensuring the inode is
* unpinned so that it is safe to reclaim the stale inode after the
* flush call.
*/
if (xfs_iflags_test(ip, XFS_ISTALE)) {
xfs_ifunlock(ip);
return 0;
}
/*
* This may have been unpinned because the filesystem is shutting
* down forcibly. If that's the case we must not write this inode
* to disk, because the log record didn't make it to disk!
*/
if (XFS_FORCED_SHUTDOWN(mp)) {
if (iip)
iip->ili_fields = 0;
xfs_ifunlock(ip);
return XFS_ERROR(EIO);
}
/*
* Get the buffer containing the on-disk inode.
*/
error = xfs_itobp(mp, NULL, ip, &dip, &bp,
(flags & SYNC_TRYLOCK) ? XBF_TRYLOCK : XBF_LOCK);
if (error || !bp) {
xfs_ifunlock(ip);
return error;
}
/*
* First flush out the inode that xfs_iflush was called with.
*/
error = xfs_iflush_int(ip, bp);
if (error)
goto corrupt_out;
/*
* If the buffer is pinned then push on the log now so we won't
* get stuck waiting in the write for too long.
*/
if (xfs_buf_ispinned(bp))
xfs_log_force(mp, 0);
/*
* inode clustering:
* see if other inodes can be gathered into this write
*/
error = xfs_iflush_cluster(ip, bp);
if (error)
goto cluster_corrupt_out;
if (flags & SYNC_WAIT)
error = xfs_bwrite(bp);
else
xfs_buf_delwri_queue(bp);
xfs_buf_relse(bp);
return error;
corrupt_out:
xfs_buf_relse(bp);
xfs_force_shutdown(mp, SHUTDOWN_CORRUPT_INCORE);
cluster_corrupt_out:
/*
* Unlocks the flush lock
*/
xfs_iflush_abort(ip);
return XFS_ERROR(EFSCORRUPTED);
}
STATIC int
xfs_iflush_int(
xfs_inode_t *ip,
xfs_buf_t *bp)
{
xfs_inode_log_item_t *iip;
xfs_dinode_t *dip;
xfs_mount_t *mp;
#ifdef XFS_TRANS_DEBUG
int first;
#endif
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL|XFS_ILOCK_SHARED));
ASSERT(xfs_isiflocked(ip));
ASSERT(ip->i_d.di_format != XFS_DINODE_FMT_BTREE ||
ip->i_d.di_nextents > XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK));
iip = ip->i_itemp;
mp = ip->i_mount;
/* set *dip = inode's place in the buffer */
dip = (xfs_dinode_t *)xfs_buf_offset(bp, ip->i_imap.im_boffset);
if (XFS_TEST_ERROR(dip->di_magic != cpu_to_be16(XFS_DINODE_MAGIC),
mp, XFS_ERRTAG_IFLUSH_1, XFS_RANDOM_IFLUSH_1)) {
xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
"%s: Bad inode %Lu magic number 0x%x, ptr 0x%p",
__func__, ip->i_ino, be16_to_cpu(dip->di_magic), dip);
goto corrupt_out;
}
if (XFS_TEST_ERROR(ip->i_d.di_magic != XFS_DINODE_MAGIC,
mp, XFS_ERRTAG_IFLUSH_2, XFS_RANDOM_IFLUSH_2)) {
xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
"%s: Bad inode %Lu, ptr 0x%p, magic number 0x%x",
__func__, ip->i_ino, ip, ip->i_d.di_magic);
goto corrupt_out;
}
if (S_ISREG(ip->i_d.di_mode)) {
if (XFS_TEST_ERROR(
(ip->i_d.di_format != XFS_DINODE_FMT_EXTENTS) &&
(ip->i_d.di_format != XFS_DINODE_FMT_BTREE),
mp, XFS_ERRTAG_IFLUSH_3, XFS_RANDOM_IFLUSH_3)) {
xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
"%s: Bad regular inode %Lu, ptr 0x%p",
__func__, ip->i_ino, ip);
goto corrupt_out;
}
} else if (S_ISDIR(ip->i_d.di_mode)) {
if (XFS_TEST_ERROR(
(ip->i_d.di_format != XFS_DINODE_FMT_EXTENTS) &&
(ip->i_d.di_format != XFS_DINODE_FMT_BTREE) &&
(ip->i_d.di_format != XFS_DINODE_FMT_LOCAL),
mp, XFS_ERRTAG_IFLUSH_4, XFS_RANDOM_IFLUSH_4)) {
xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
"%s: Bad directory inode %Lu, ptr 0x%p",
__func__, ip->i_ino, ip);
goto corrupt_out;
}
}
if (XFS_TEST_ERROR(ip->i_d.di_nextents + ip->i_d.di_anextents >
ip->i_d.di_nblocks, mp, XFS_ERRTAG_IFLUSH_5,
XFS_RANDOM_IFLUSH_5)) {
xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
"%s: detected corrupt incore inode %Lu, "
"total extents = %d, nblocks = %Ld, ptr 0x%p",
__func__, ip->i_ino,
ip->i_d.di_nextents + ip->i_d.di_anextents,
ip->i_d.di_nblocks, ip);
goto corrupt_out;
}
if (XFS_TEST_ERROR(ip->i_d.di_forkoff > mp->m_sb.sb_inodesize,
mp, XFS_ERRTAG_IFLUSH_6, XFS_RANDOM_IFLUSH_6)) {
xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
"%s: bad inode %Lu, forkoff 0x%x, ptr 0x%p",
__func__, ip->i_ino, ip->i_d.di_forkoff, ip);
goto corrupt_out;
}
/*
* bump the flush iteration count, used to detect flushes which
* postdate a log record during recovery.
*/
ip->i_d.di_flushiter++;
/*
* Copy the dirty parts of the inode into the on-disk
* inode. We always copy out the core of the inode,
* because if the inode is dirty at all the core must
* be.
*/
xfs_dinode_to_disk(dip, &ip->i_d);
/* Wrap, we never let the log put out DI_MAX_FLUSH */
if (ip->i_d.di_flushiter == DI_MAX_FLUSH)
ip->i_d.di_flushiter = 0;
/*
* If this is really an old format inode and the superblock version
* has not been updated to support only new format inodes, then
* convert back to the old inode format. If the superblock version
* has been updated, then make the conversion permanent.
*/
ASSERT(ip->i_d.di_version == 1 || xfs_sb_version_hasnlink(&mp->m_sb));
if (ip->i_d.di_version == 1) {
if (!xfs_sb_version_hasnlink(&mp->m_sb)) {
/*
* Convert it back.
*/
ASSERT(ip->i_d.di_nlink <= XFS_MAXLINK_1);
dip->di_onlink = cpu_to_be16(ip->i_d.di_nlink);
} else {
/*
* The superblock version has already been bumped,
* so just make the conversion to the new inode
* format permanent.
*/
ip->i_d.di_version = 2;
dip->di_version = 2;
ip->i_d.di_onlink = 0;
dip->di_onlink = 0;
memset(&(ip->i_d.di_pad[0]), 0, sizeof(ip->i_d.di_pad));
memset(&(dip->di_pad[0]), 0,
sizeof(dip->di_pad));
ASSERT(xfs_get_projid(ip) == 0);
}
}
xfs_iflush_fork(ip, dip, iip, XFS_DATA_FORK, bp);
if (XFS_IFORK_Q(ip))
xfs_iflush_fork(ip, dip, iip, XFS_ATTR_FORK, bp);
xfs_inobp_check(mp, bp);
/*
* We've recorded everything logged in the inode, so we'd like to clear
* the ili_fields bits so we don't log and flush things unnecessarily.
* However, we can't stop logging all this information until the data
* we've copied into the disk buffer is written to disk. If we did we
* might overwrite the copy of the inode in the log with all the data
* after re-logging only part of it, and in the face of a crash we
* wouldn't have all the data we need to recover.
*
* What we do is move the bits to the ili_last_fields field. When
* logging the inode, these bits are moved back to the ili_fields field.
* In the xfs_iflush_done() routine we clear ili_last_fields, since we
* know that the information those bits represent is permanently on
* disk. As long as the flush completes before the inode is logged
* again, then both ili_fields and ili_last_fields will be cleared.
*
* We can play with the ili_fields bits here, because the inode lock
* must be held exclusively in order to set bits there and the flush
* lock protects the ili_last_fields bits. Set ili_logged so the flush
* done routine can tell whether or not to look in the AIL. Also, store
* the current LSN of the inode so that we can tell whether the item has
* moved in the AIL from xfs_iflush_done(). In order to read the lsn we
* need the AIL lock, because it is a 64 bit value that cannot be read
* atomically.
*/
if (iip != NULL && iip->ili_fields != 0) {
iip->ili_last_fields = iip->ili_fields;
iip->ili_fields = 0;
iip->ili_logged = 1;
xfs_trans_ail_copy_lsn(mp->m_ail, &iip->ili_flush_lsn,
&iip->ili_item.li_lsn);
/*
* Attach the function xfs_iflush_done to the inode's
* buffer. This will remove the inode from the AIL
* and unlock the inode's flush lock when the inode is
* completely written to disk.
*/
xfs_buf_attach_iodone(bp, xfs_iflush_done, &iip->ili_item);
ASSERT(bp->b_fspriv != NULL);
ASSERT(bp->b_iodone != NULL);
} else {
/*
* We're flushing an inode which is not in the AIL and has
* not been logged. For this case we can immediately drop
* the inode flush lock because we can avoid the whole
* AIL state thing. It's OK to drop the flush lock now,
* because we've already locked the buffer and to do anything
* you really need both.
*/
if (iip != NULL) {
ASSERT(iip->ili_logged == 0);
ASSERT(iip->ili_last_fields == 0);
ASSERT((iip->ili_item.li_flags & XFS_LI_IN_AIL) == 0);
}
xfs_ifunlock(ip);
}
return 0;
corrupt_out:
return XFS_ERROR(EFSCORRUPTED);
}
void
xfs_promote_inode(
struct xfs_inode *ip)
{
struct xfs_buf *bp;
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL|XFS_ILOCK_SHARED));
bp = xfs_incore(ip->i_mount->m_ddev_targp, ip->i_imap.im_blkno,
ip->i_imap.im_len, XBF_TRYLOCK);
if (!bp)
return;
if (XFS_BUF_ISDELAYWRITE(bp)) {
xfs_buf_delwri_promote(bp);
wake_up_process(ip->i_mount->m_ddev_targp->bt_task);
}
xfs_buf_relse(bp);
}
/*
* Return a pointer to the extent record at file index idx.
*/
xfs_bmbt_rec_host_t *
xfs_iext_get_ext(
xfs_ifork_t *ifp, /* inode fork pointer */
xfs_extnum_t idx) /* index of target extent */
{
ASSERT(idx >= 0);
ASSERT(idx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t));
if ((ifp->if_flags & XFS_IFEXTIREC) && (idx == 0)) {
return ifp->if_u1.if_ext_irec->er_extbuf;
} else if (ifp->if_flags & XFS_IFEXTIREC) {
xfs_ext_irec_t *erp; /* irec pointer */
int erp_idx = 0; /* irec index */
xfs_extnum_t page_idx = idx; /* ext index in target list */
erp = xfs_iext_idx_to_irec(ifp, &page_idx, &erp_idx, 0);
return &erp->er_extbuf[page_idx];
} else if (ifp->if_bytes) {
return &ifp->if_u1.if_extents[idx];
} else {
return NULL;
}
}
/*
* Insert new item(s) into the extent records for incore inode
* fork 'ifp'. 'count' new items are inserted at index 'idx'.
*/
void
xfs_iext_insert(
xfs_inode_t *ip, /* incore inode pointer */
xfs_extnum_t idx, /* starting index of new items */
xfs_extnum_t count, /* number of inserted items */
xfs_bmbt_irec_t *new, /* items to insert */
int state) /* type of extent conversion */
{
xfs_ifork_t *ifp = (state & BMAP_ATTRFORK) ? ip->i_afp : &ip->i_df;
xfs_extnum_t i; /* extent record index */
trace_xfs_iext_insert(ip, idx, new, state, _RET_IP_);
ASSERT(ifp->if_flags & XFS_IFEXTENTS);
xfs_iext_add(ifp, idx, count);
for (i = idx; i < idx + count; i++, new++)
xfs_bmbt_set_all(xfs_iext_get_ext(ifp, i), new);
}
/*
* This is called when the amount of space required for incore file
* extents needs to be increased. The ext_diff parameter stores the
* number of new extents being added and the idx parameter contains
* the extent index where the new extents will be added. If the new
* extents are being appended, then we just need to (re)allocate and
* initialize the space. Otherwise, if the new extents are being
* inserted into the middle of the existing entries, a bit more work
* is required to make room for the new extents to be inserted. The
* caller is responsible for filling in the new extent entries upon
* return.
*/
void
xfs_iext_add(
xfs_ifork_t *ifp, /* inode fork pointer */
xfs_extnum_t idx, /* index to begin adding exts */
int ext_diff) /* number of extents to add */
{
int byte_diff; /* new bytes being added */
int new_size; /* size of extents after adding */
xfs_extnum_t nextents; /* number of extents in file */
nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
ASSERT((idx >= 0) && (idx <= nextents));
byte_diff = ext_diff * sizeof(xfs_bmbt_rec_t);
new_size = ifp->if_bytes + byte_diff;
/*
* If the new number of extents (nextents + ext_diff)
* fits inside the inode, then continue to use the inline
* extent buffer.
*/
if (nextents + ext_diff <= XFS_INLINE_EXTS) {
if (idx < nextents) {
memmove(&ifp->if_u2.if_inline_ext[idx + ext_diff],
&ifp->if_u2.if_inline_ext[idx],
(nextents - idx) * sizeof(xfs_bmbt_rec_t));
memset(&ifp->if_u2.if_inline_ext[idx], 0, byte_diff);
}
ifp->if_u1.if_extents = ifp->if_u2.if_inline_ext;
ifp->if_real_bytes = 0;
}
/*
* Otherwise use a linear (direct) extent list.
* If the extents are currently inside the inode,
* xfs_iext_realloc_direct will switch us from
* inline to direct extent allocation mode.
*/
else if (nextents + ext_diff <= XFS_LINEAR_EXTS) {
xfs_iext_realloc_direct(ifp, new_size);
if (idx < nextents) {
memmove(&ifp->if_u1.if_extents[idx + ext_diff],
&ifp->if_u1.if_extents[idx],
(nextents - idx) * sizeof(xfs_bmbt_rec_t));
memset(&ifp->if_u1.if_extents[idx], 0, byte_diff);
}
}
/* Indirection array */
else {
xfs_ext_irec_t *erp;
int erp_idx = 0;
int page_idx = idx;
ASSERT(nextents + ext_diff > XFS_LINEAR_EXTS);
if (ifp->if_flags & XFS_IFEXTIREC) {
erp = xfs_iext_idx_to_irec(ifp, &page_idx, &erp_idx, 1);
} else {
xfs_iext_irec_init(ifp);
ASSERT(ifp->if_flags & XFS_IFEXTIREC);
erp = ifp->if_u1.if_ext_irec;
}
/* Extents fit in target extent page */
if (erp && erp->er_extcount + ext_diff <= XFS_LINEAR_EXTS) {
if (page_idx < erp->er_extcount) {
memmove(&erp->er_extbuf[page_idx + ext_diff],
&erp->er_extbuf[page_idx],
(erp->er_extcount - page_idx) *
sizeof(xfs_bmbt_rec_t));
memset(&erp->er_extbuf[page_idx], 0, byte_diff);
}
erp->er_extcount += ext_diff;
xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, ext_diff);
}
/* Insert a new extent page */
else if (erp) {
xfs_iext_add_indirect_multi(ifp,
erp_idx, page_idx, ext_diff);
}
/*
* If extent(s) are being appended to the last page in
* the indirection array and the new extent(s) don't fit
* in the page, then erp is NULL and erp_idx is set to
* the next index needed in the indirection array.
*/
else {
int count = ext_diff;
while (count) {
erp = xfs_iext_irec_new(ifp, erp_idx);
erp->er_extcount = count;
count -= MIN(count, (int)XFS_LINEAR_EXTS);
if (count) {
erp_idx++;
}
}
}
}
ifp->if_bytes = new_size;
}
/*
* This is called when incore extents are being added to the indirection
* array and the new extents do not fit in the target extent list. The
* erp_idx parameter contains the irec index for the target extent list
* in the indirection array, and the idx parameter contains the extent
* index within the list. The number of extents being added is stored
* in the count parameter.
*
* |-------| |-------|
* | | | | idx - number of extents before idx
* | idx | | count |
* | | | | count - number of extents being inserted at idx
* |-------| |-------|
* | count | | nex2 | nex2 - number of extents after idx + count
* |-------| |-------|
*/
void
xfs_iext_add_indirect_multi(
xfs_ifork_t *ifp, /* inode fork pointer */
int erp_idx, /* target extent irec index */
xfs_extnum_t idx, /* index within target list */
int count) /* new extents being added */
{
int byte_diff; /* new bytes being added */
xfs_ext_irec_t *erp; /* pointer to irec entry */
xfs_extnum_t ext_diff; /* number of extents to add */
xfs_extnum_t ext_cnt; /* new extents still needed */
xfs_extnum_t nex2; /* extents after idx + count */
xfs_bmbt_rec_t *nex2_ep = NULL; /* temp list for nex2 extents */
int nlists; /* number of irec's (lists) */
ASSERT(ifp->if_flags & XFS_IFEXTIREC);
erp = &ifp->if_u1.if_ext_irec[erp_idx];
nex2 = erp->er_extcount - idx;
nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
/*
* Save second part of target extent list
* (all extents past */
if (nex2) {
byte_diff = nex2 * sizeof(xfs_bmbt_rec_t);
nex2_ep = (xfs_bmbt_rec_t *) kmem_alloc(byte_diff, KM_NOFS);
memmove(nex2_ep, &erp->er_extbuf[idx], byte_diff);
erp->er_extcount -= nex2;
xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, -nex2);
memset(&erp->er_extbuf[idx], 0, byte_diff);
}
/*
* Add the new extents to the end of the target
* list, then allocate new irec record(s) and
* extent buffer(s) as needed to store the rest
* of the new extents.
*/
ext_cnt = count;
ext_diff = MIN(ext_cnt, (int)XFS_LINEAR_EXTS - erp->er_extcount);
if (ext_diff) {
erp->er_extcount += ext_diff;
xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, ext_diff);
ext_cnt -= ext_diff;
}
while (ext_cnt) {
erp_idx++;
erp = xfs_iext_irec_new(ifp, erp_idx);
ext_diff = MIN(ext_cnt, (int)XFS_LINEAR_EXTS);
erp->er_extcount = ext_diff;
xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, ext_diff);
ext_cnt -= ext_diff;
}
/* Add nex2 extents back to indirection array */
if (nex2) {
xfs_extnum_t ext_avail;
int i;
byte_diff = nex2 * sizeof(xfs_bmbt_rec_t);
ext_avail = XFS_LINEAR_EXTS - erp->er_extcount;
i = 0;
/*
* If nex2 extents fit in the current page, append
* nex2_ep after the new extents.
*/
if (nex2 <= ext_avail) {
i = erp->er_extcount;
}
/*
* Otherwise, check if space is available in the
* next page.
*/
else if ((erp_idx < nlists - 1) &&
(nex2 <= (ext_avail = XFS_LINEAR_EXTS -
ifp->if_u1.if_ext_irec[erp_idx+1].er_extcount))) {
erp_idx++;
erp++;
/* Create a hole for nex2 extents */
memmove(&erp->er_extbuf[nex2], erp->er_extbuf,
erp->er_extcount * sizeof(xfs_bmbt_rec_t));
}
/*
* Final choice, create a new extent page for
* nex2 extents.
*/
else {
erp_idx++;
erp = xfs_iext_irec_new(ifp, erp_idx);
}
memmove(&erp->er_extbuf[i], nex2_ep, byte_diff);
kmem_free(nex2_ep);
erp->er_extcount += nex2;
xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, nex2);
}
}
/*
* This is called when the amount of space required for incore file
* extents needs to be decreased. The ext_diff parameter stores the
* number of extents to be removed and the idx parameter contains
* the extent index where the extents will be removed from.
*
* If the amount of space needed has decreased below the linear
* limit, XFS_IEXT_BUFSZ, then switch to using the contiguous
* extent array. Otherwise, use kmem_realloc() to adjust the
* size to what is needed.
*/
void
xfs_iext_remove(
xfs_inode_t *ip, /* incore inode pointer */
xfs_extnum_t idx, /* index to begin removing exts */
int ext_diff, /* number of extents to remove */
int state) /* type of extent conversion */
{
xfs_ifork_t *ifp = (state & BMAP_ATTRFORK) ? ip->i_afp : &ip->i_df;
xfs_extnum_t nextents; /* number of extents in file */
int new_size; /* size of extents after removal */
trace_xfs_iext_remove(ip, idx, state, _RET_IP_);
ASSERT(ext_diff > 0);
nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
new_size = (nextents - ext_diff) * sizeof(xfs_bmbt_rec_t);
if (new_size == 0) {
xfs_iext_destroy(ifp);
} else if (ifp->if_flags & XFS_IFEXTIREC) {
xfs_iext_remove_indirect(ifp, idx, ext_diff);
} else if (ifp->if_real_bytes) {
xfs_iext_remove_direct(ifp, idx, ext_diff);
} else {
xfs_iext_remove_inline(ifp, idx, ext_diff);
}
ifp->if_bytes = new_size;
}
/*
* This removes ext_diff extents from the inline buffer, beginning
* at extent index idx.
*/
void
xfs_iext_remove_inline(
xfs_ifork_t *ifp, /* inode fork pointer */
xfs_extnum_t idx, /* index to begin removing exts */
int ext_diff) /* number of extents to remove */
{
int nextents; /* number of extents in file */
ASSERT(!(ifp->if_flags & XFS_IFEXTIREC));
ASSERT(idx < XFS_INLINE_EXTS);
nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
ASSERT(((nextents - ext_diff) > 0) &&
(nextents - ext_diff) < XFS_INLINE_EXTS);
if (idx + ext_diff < nextents) {
memmove(&ifp->if_u2.if_inline_ext[idx],
&ifp->if_u2.if_inline_ext[idx + ext_diff],
(nextents - (idx + ext_diff)) *
sizeof(xfs_bmbt_rec_t));
memset(&ifp->if_u2.if_inline_ext[nextents - ext_diff],
0, ext_diff * sizeof(xfs_bmbt_rec_t));
} else {
memset(&ifp->if_u2.if_inline_ext[idx], 0,
ext_diff * sizeof(xfs_bmbt_rec_t));
}
}
/*
* This removes ext_diff extents from a linear (direct) extent list,
* beginning at extent index idx. If the extents are being removed
* from the end of the list (ie. truncate) then we just need to re-
* allocate the list to remove the extra space. Otherwise, if the
* extents are being removed from the middle of the existing extent
* entries, then we first need to move the extent records beginning
* at idx + ext_diff up in the list to overwrite the records being
* removed, then remove the extra space via kmem_realloc.
*/
void
xfs_iext_remove_direct(
xfs_ifork_t *ifp, /* inode fork pointer */
xfs_extnum_t idx, /* index to begin removing exts */
int ext_diff) /* number of extents to remove */
{
xfs_extnum_t nextents; /* number of extents in file */
int new_size; /* size of extents after removal */
ASSERT(!(ifp->if_flags & XFS_IFEXTIREC));
new_size = ifp->if_bytes -
(ext_diff * sizeof(xfs_bmbt_rec_t));
nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
if (new_size == 0) {
xfs_iext_destroy(ifp);
return;
}
/* Move extents up in the list (if needed) */
if (idx + ext_diff < nextents) {
memmove(&ifp->if_u1.if_extents[idx],
&ifp->if_u1.if_extents[idx + ext_diff],
(nextents - (idx + ext_diff)) *
sizeof(xfs_bmbt_rec_t));
}
memset(&ifp->if_u1.if_extents[nextents - ext_diff],
0, ext_diff * sizeof(xfs_bmbt_rec_t));
/*
* Reallocate the direct extent list. If the extents
* will fit inside the inode then xfs_iext_realloc_direct
* will switch from direct to inline extent allocation
* mode for us.
*/
xfs_iext_realloc_direct(ifp, new_size);
ifp->if_bytes = new_size;
}
/*
* This is called when incore extents are being removed from the
* indirection array and the extents being removed span multiple extent
* buffers. The idx parameter contains the file extent index where we
* want to begin removing extents, and the count parameter contains
* how many extents need to be removed.
*
* |-------| |-------|
* | nex1 | | | nex1 - number of extents before idx
* |-------| | count |
* | | | | count - number of extents being removed at idx
* | count | |-------|
* | | | nex2 | nex2 - number of extents after idx + count
* |-------| |-------|
*/
void
xfs_iext_remove_indirect(
xfs_ifork_t *ifp, /* inode fork pointer */
xfs_extnum_t idx, /* index to begin removing extents */
int count) /* number of extents to remove */
{
xfs_ext_irec_t *erp; /* indirection array pointer */
int erp_idx = 0; /* indirection array index */
xfs_extnum_t ext_cnt; /* extents left to remove */
xfs_extnum_t ext_diff; /* extents to remove in current list */
xfs_extnum_t nex1; /* number of extents before idx */
xfs_extnum_t nex2; /* extents after idx + count */
int page_idx = idx; /* index in target extent list */
ASSERT(ifp->if_flags & XFS_IFEXTIREC);
erp = xfs_iext_idx_to_irec(ifp, &page_idx, &erp_idx, 0);
ASSERT(erp != NULL);
nex1 = page_idx;
ext_cnt = count;
while (ext_cnt) {
nex2 = MAX((erp->er_extcount - (nex1 + ext_cnt)), 0);
ext_diff = MIN(ext_cnt, (erp->er_extcount - nex1));
/*
* Check for deletion of entire list;
* xfs_iext_irec_remove() updates extent offsets.
*/
if (ext_diff == erp->er_extcount) {
xfs_iext_irec_remove(ifp, erp_idx);
ext_cnt -= ext_diff;
nex1 = 0;
if (ext_cnt) {
ASSERT(erp_idx < ifp->if_real_bytes /
XFS_IEXT_BUFSZ);
erp = &ifp->if_u1.if_ext_irec[erp_idx];
nex1 = 0;
continue;
} else {
break;
}
}
/* Move extents up (if needed) */
if (nex2) {
memmove(&erp->er_extbuf[nex1],
&erp->er_extbuf[nex1 + ext_diff],
nex2 * sizeof(xfs_bmbt_rec_t));
}
/* Zero out rest of page */
memset(&erp->er_extbuf[nex1 + nex2], 0, (XFS_IEXT_BUFSZ -
((nex1 + nex2) * sizeof(xfs_bmbt_rec_t))));
/* Update remaining counters */
erp->er_extcount -= ext_diff;
xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, -ext_diff);
ext_cnt -= ext_diff;
nex1 = 0;
erp_idx++;
erp++;
}
ifp->if_bytes -= count * sizeof(xfs_bmbt_rec_t);
xfs_iext_irec_compact(ifp);
}
/*
* Create, destroy, or resize a linear (direct) block of extents.
*/
void
xfs_iext_realloc_direct(
xfs_ifork_t *ifp, /* inode fork pointer */
int new_size) /* new size of extents */
{
int rnew_size; /* real new size of extents */
rnew_size = new_size;
ASSERT(!(ifp->if_flags & XFS_IFEXTIREC) ||
((new_size >= 0) && (new_size <= XFS_IEXT_BUFSZ) &&
(new_size != ifp->if_real_bytes)));
/* Free extent records */
if (new_size == 0) {
xfs_iext_destroy(ifp);
}
/* Resize direct extent list and zero any new bytes */
else if (ifp->if_real_bytes) {
/* Check if extents will fit inside the inode */
if (new_size <= XFS_INLINE_EXTS * sizeof(xfs_bmbt_rec_t)) {
xfs_iext_direct_to_inline(ifp, new_size /
(uint)sizeof(xfs_bmbt_rec_t));
ifp->if_bytes = new_size;
return;
}
if (!is_power_of_2(new_size)){
rnew_size = roundup_pow_of_two(new_size);
}
if (rnew_size != ifp->if_real_bytes) {
ifp->if_u1.if_extents =
kmem_realloc(ifp->if_u1.if_extents,
rnew_size,
ifp->if_real_bytes, KM_NOFS);
}
if (rnew_size > ifp->if_real_bytes) {
memset(&ifp->if_u1.if_extents[ifp->if_bytes /
(uint)sizeof(xfs_bmbt_rec_t)], 0,
rnew_size - ifp->if_real_bytes);
}
}
/*
* Switch from the inline extent buffer to a direct
* extent list. Be sure to include the inline extent
* bytes in new_size.
*/
else {
new_size += ifp->if_bytes;
if (!is_power_of_2(new_size)) {
rnew_size = roundup_pow_of_two(new_size);
}
xfs_iext_inline_to_direct(ifp, rnew_size);
}
ifp->if_real_bytes = rnew_size;
ifp->if_bytes = new_size;
}
/*
* Switch from linear (direct) extent records to inline buffer.
*/
void
xfs_iext_direct_to_inline(
xfs_ifork_t *ifp, /* inode fork pointer */
xfs_extnum_t nextents) /* number of extents in file */
{
ASSERT(ifp->if_flags & XFS_IFEXTENTS);
ASSERT(nextents <= XFS_INLINE_EXTS);
/*
* The inline buffer was zeroed when we switched
* from inline to direct extent allocation mode,
* so we don't need to clear it here.
*/
memcpy(ifp->if_u2.if_inline_ext, ifp->if_u1.if_extents,
nextents * sizeof(xfs_bmbt_rec_t));
kmem_free(ifp->if_u1.if_extents);
ifp->if_u1.if_extents = ifp->if_u2.if_inline_ext;
ifp->if_real_bytes = 0;
}
/*
* Switch from inline buffer to linear (direct) extent records.
* new_size should already be rounded up to the next power of 2
* by the caller (when appropriate), so use new_size as it is.
* However, since new_size may be rounded up, we can't update
* if_bytes here. It is the caller's responsibility to update
* if_bytes upon return.
*/
void
xfs_iext_inline_to_direct(
xfs_ifork_t *ifp, /* inode fork pointer */
int new_size) /* number of extents in file */
{
ifp->if_u1.if_extents = kmem_alloc(new_size, KM_NOFS);
memset(ifp->if_u1.if_extents, 0, new_size);
if (ifp->if_bytes) {
memcpy(ifp->if_u1.if_extents, ifp->if_u2.if_inline_ext,
ifp->if_bytes);
memset(ifp->if_u2.if_inline_ext, 0, XFS_INLINE_EXTS *
sizeof(xfs_bmbt_rec_t));
}
ifp->if_real_bytes = new_size;
}
/*
* Resize an extent indirection array to new_size bytes.
*/
STATIC void
xfs_iext_realloc_indirect(
xfs_ifork_t *ifp, /* inode fork pointer */
int new_size) /* new indirection array size */
{
int nlists; /* number of irec's (ex lists) */
int size; /* current indirection array size */
ASSERT(ifp->if_flags & XFS_IFEXTIREC);
nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
size = nlists * sizeof(xfs_ext_irec_t);
ASSERT(ifp->if_real_bytes);
ASSERT((new_size >= 0) && (new_size != size));
if (new_size == 0) {
xfs_iext_destroy(ifp);
} else {
ifp->if_u1.if_ext_irec = (xfs_ext_irec_t *)
kmem_realloc(ifp->if_u1.if_ext_irec,
new_size, size, KM_NOFS);
}
}
/*
* Switch from indirection array to linear (direct) extent allocations.
*/
STATIC void
xfs_iext_indirect_to_direct(
xfs_ifork_t *ifp) /* inode fork pointer */
{
xfs_bmbt_rec_host_t *ep; /* extent record pointer */
xfs_extnum_t nextents; /* number of extents in file */
int size; /* size of file extents */
ASSERT(ifp->if_flags & XFS_IFEXTIREC);
nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
ASSERT(nextents <= XFS_LINEAR_EXTS);
size = nextents * sizeof(xfs_bmbt_rec_t);
xfs_iext_irec_compact_pages(ifp);
ASSERT(ifp->if_real_bytes == XFS_IEXT_BUFSZ);
ep = ifp->if_u1.if_ext_irec->er_extbuf;
kmem_free(ifp->if_u1.if_ext_irec);
ifp->if_flags &= ~XFS_IFEXTIREC;
ifp->if_u1.if_extents = ep;
ifp->if_bytes = size;
if (nextents < XFS_LINEAR_EXTS) {
xfs_iext_realloc_direct(ifp, size);
}
}
/*
* Free incore file extents.
*/
void
xfs_iext_destroy(
xfs_ifork_t *ifp) /* inode fork pointer */
{
if (ifp->if_flags & XFS_IFEXTIREC) {
int erp_idx;
int nlists;
nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
for (erp_idx = nlists - 1; erp_idx >= 0 ; erp_idx--) {
xfs_iext_irec_remove(ifp, erp_idx);
}
ifp->if_flags &= ~XFS_IFEXTIREC;
} else if (ifp->if_real_bytes) {
kmem_free(ifp->if_u1.if_extents);
} else if (ifp->if_bytes) {
memset(ifp->if_u2.if_inline_ext, 0, XFS_INLINE_EXTS *
sizeof(xfs_bmbt_rec_t));
}
ifp->if_u1.if_extents = NULL;
ifp->if_real_bytes = 0;
ifp->if_bytes = 0;
}
/*
* Return a pointer to the extent record for file system block bno.
*/
xfs_bmbt_rec_host_t * /* pointer to found extent record */
xfs_iext_bno_to_ext(
xfs_ifork_t *ifp, /* inode fork pointer */
xfs_fileoff_t bno, /* block number to search for */
xfs_extnum_t *idxp) /* index of target extent */
{
xfs_bmbt_rec_host_t *base; /* pointer to first extent */
xfs_filblks_t blockcount = 0; /* number of blocks in extent */
xfs_bmbt_rec_host_t *ep = NULL; /* pointer to target extent */
xfs_ext_irec_t *erp = NULL; /* indirection array pointer */
int high; /* upper boundary in search */
xfs_extnum_t idx = 0; /* index of target extent */
int low; /* lower boundary in search */
xfs_extnum_t nextents; /* number of file extents */
xfs_fileoff_t startoff = 0; /* start offset of extent */
nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
if (nextents == 0) {
*idxp = 0;
return NULL;
}
low = 0;
if (ifp->if_flags & XFS_IFEXTIREC) {
/* Find target extent list */
int erp_idx = 0;
erp = xfs_iext_bno_to_irec(ifp, bno, &erp_idx);
base = erp->er_extbuf;
high = erp->er_extcount - 1;
} else {
base = ifp->if_u1.if_extents;
high = nextents - 1;
}
/* Binary search extent records */
while (low <= high) {
idx = (low + high) >> 1;
ep = base + idx;
startoff = xfs_bmbt_get_startoff(ep);
blockcount = xfs_bmbt_get_blockcount(ep);
if (bno < startoff) {
high = idx - 1;
} else if (bno >= startoff + blockcount) {
low = idx + 1;
} else {
/* Convert back to file-based extent index */
if (ifp->if_flags & XFS_IFEXTIREC) {
idx += erp->er_extoff;
}
*idxp = idx;
return ep;
}
}
/* Convert back to file-based extent index */
if (ifp->if_flags & XFS_IFEXTIREC) {
idx += erp->er_extoff;
}
if (bno >= startoff + blockcount) {
if (++idx == nextents) {
ep = NULL;
} else {
ep = xfs_iext_get_ext(ifp, idx);
}
}
*idxp = idx;
return ep;
}
/*
* Return a pointer to the indirection array entry containing the
* extent record for filesystem block bno. Store the index of the
* target irec in *erp_idxp.
*/
xfs_ext_irec_t * /* pointer to found extent record */
xfs_iext_bno_to_irec(
xfs_ifork_t *ifp, /* inode fork pointer */
xfs_fileoff_t bno, /* block number to search for */
int *erp_idxp) /* irec index of target ext list */
{
xfs_ext_irec_t *erp = NULL; /* indirection array pointer */
xfs_ext_irec_t *erp_next; /* next indirection array entry */
int erp_idx; /* indirection array index */
int nlists; /* number of extent irec's (lists) */
int high; /* binary search upper limit */
int low; /* binary search lower limit */
ASSERT(ifp->if_flags & XFS_IFEXTIREC);
nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
erp_idx = 0;
low = 0;
high = nlists - 1;
while (low <= high) {
erp_idx = (low + high) >> 1;
erp = &ifp->if_u1.if_ext_irec[erp_idx];
erp_next = erp_idx < nlists - 1 ? erp + 1 : NULL;
if (bno < xfs_bmbt_get_startoff(erp->er_extbuf)) {
high = erp_idx - 1;
} else if (erp_next && bno >=
xfs_bmbt_get_startoff(erp_next->er_extbuf)) {
low = erp_idx + 1;
} else {
break;
}
}
*erp_idxp = erp_idx;
return erp;
}
/*
* Return a pointer to the indirection array entry containing the
* extent record at file extent index *idxp. Store the index of the
* target irec in *erp_idxp and store the page index of the target
* extent record in *idxp.
*/
xfs_ext_irec_t *
xfs_iext_idx_to_irec(
xfs_ifork_t *ifp, /* inode fork pointer */
xfs_extnum_t *idxp, /* extent index (file -> page) */
int *erp_idxp, /* pointer to target irec */
int realloc) /* new bytes were just added */
{
xfs_ext_irec_t *prev; /* pointer to previous irec */
xfs_ext_irec_t *erp = NULL; /* pointer to current irec */
int erp_idx; /* indirection array index */
int nlists; /* number of irec's (ex lists) */
int high; /* binary search upper limit */
int low; /* binary search lower limit */
xfs_extnum_t page_idx = *idxp; /* extent index in target list */
ASSERT(ifp->if_flags & XFS_IFEXTIREC);
ASSERT(page_idx >= 0);
ASSERT(page_idx <= ifp->if_bytes / sizeof(xfs_bmbt_rec_t));
ASSERT(page_idx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t) || realloc);
nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
erp_idx = 0;
low = 0;
high = nlists - 1;
/* Binary search extent irec's */
while (low <= high) {
erp_idx = (low + high) >> 1;
erp = &ifp->if_u1.if_ext_irec[erp_idx];
prev = erp_idx > 0 ? erp - 1 : NULL;
if (page_idx < erp->er_extoff || (page_idx == erp->er_extoff &&
realloc && prev && prev->er_extcount < XFS_LINEAR_EXTS)) {
high = erp_idx - 1;
} else if (page_idx > erp->er_extoff + erp->er_extcount ||
(page_idx == erp->er_extoff + erp->er_extcount &&
!realloc)) {
low = erp_idx + 1;
} else if (page_idx == erp->er_extoff + erp->er_extcount &&
erp->er_extcount == XFS_LINEAR_EXTS) {
ASSERT(realloc);
page_idx = 0;
erp_idx++;
erp = erp_idx < nlists ? erp + 1 : NULL;
break;
} else {
page_idx -= erp->er_extoff;
break;
}
}
*idxp = page_idx;
*erp_idxp = erp_idx;
return(erp);
}
/*
* Allocate and initialize an indirection array once the space needed
* for incore extents increases above XFS_IEXT_BUFSZ.
*/
void
xfs_iext_irec_init(
xfs_ifork_t *ifp) /* inode fork pointer */
{
xfs_ext_irec_t *erp; /* indirection array pointer */
xfs_extnum_t nextents; /* number of extents in file */
ASSERT(!(ifp->if_flags & XFS_IFEXTIREC));
nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
ASSERT(nextents <= XFS_LINEAR_EXTS);
erp = kmem_alloc(sizeof(xfs_ext_irec_t), KM_NOFS);
if (nextents == 0) {
ifp->if_u1.if_extents = kmem_alloc(XFS_IEXT_BUFSZ, KM_NOFS);
} else if (!ifp->if_real_bytes) {
xfs_iext_inline_to_direct(ifp, XFS_IEXT_BUFSZ);
} else if (ifp->if_real_bytes < XFS_IEXT_BUFSZ) {
xfs_iext_realloc_direct(ifp, XFS_IEXT_BUFSZ);
}
erp->er_extbuf = ifp->if_u1.if_extents;
erp->er_extcount = nextents;
erp->er_extoff = 0;
ifp->if_flags |= XFS_IFEXTIREC;
ifp->if_real_bytes = XFS_IEXT_BUFSZ;
ifp->if_bytes = nextents * sizeof(xfs_bmbt_rec_t);
ifp->if_u1.if_ext_irec = erp;
return;
}
/*
* Allocate and initialize a new entry in the indirection array.
*/
xfs_ext_irec_t *
xfs_iext_irec_new(
xfs_ifork_t *ifp, /* inode fork pointer */
int erp_idx) /* index for new irec */
{
xfs_ext_irec_t *erp; /* indirection array pointer */
int i; /* loop counter */
int nlists; /* number of irec's (ex lists) */
ASSERT(ifp->if_flags & XFS_IFEXTIREC);
nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
/* Resize indirection array */
xfs_iext_realloc_indirect(ifp, ++nlists *
sizeof(xfs_ext_irec_t));
/*
* Move records down in the array so the
* new page can use erp_idx.
*/
erp = ifp->if_u1.if_ext_irec;
for (i = nlists - 1; i > erp_idx; i--) {
memmove(&erp[i], &erp[i-1], sizeof(xfs_ext_irec_t));
}
ASSERT(i == erp_idx);
/* Initialize new extent record */
erp = ifp->if_u1.if_ext_irec;
erp[erp_idx].er_extbuf = kmem_alloc(XFS_IEXT_BUFSZ, KM_NOFS);
ifp->if_real_bytes = nlists * XFS_IEXT_BUFSZ;
memset(erp[erp_idx].er_extbuf, 0, XFS_IEXT_BUFSZ);
erp[erp_idx].er_extcount = 0;
erp[erp_idx].er_extoff = erp_idx > 0 ?
erp[erp_idx-1].er_extoff + erp[erp_idx-1].er_extcount : 0;
return (&erp[erp_idx]);
}
/*
* Remove a record from the indirection array.
*/
void
xfs_iext_irec_remove(
xfs_ifork_t *ifp, /* inode fork pointer */
int erp_idx) /* irec index to remove */
{
xfs_ext_irec_t *erp; /* indirection array pointer */
int i; /* loop counter */
int nlists; /* number of irec's (ex lists) */
ASSERT(ifp->if_flags & XFS_IFEXTIREC);
nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
erp = &ifp->if_u1.if_ext_irec[erp_idx];
if (erp->er_extbuf) {
xfs_iext_irec_update_extoffs(ifp, erp_idx + 1,
-erp->er_extcount);
kmem_free(erp->er_extbuf);
}
/* Compact extent records */
erp = ifp->if_u1.if_ext_irec;
for (i = erp_idx; i < nlists - 1; i++) {
memmove(&erp[i], &erp[i+1], sizeof(xfs_ext_irec_t));
}
/*
* Manually free the last extent record from the indirection
* array. A call to xfs_iext_realloc_indirect() with a size
* of zero would result in a call to xfs_iext_destroy() which
* would in turn call this function again, creating a nasty
* infinite loop.
*/
if (--nlists) {
xfs_iext_realloc_indirect(ifp,
nlists * sizeof(xfs_ext_irec_t));
} else {
kmem_free(ifp->if_u1.if_ext_irec);
}
ifp->if_real_bytes = nlists * XFS_IEXT_BUFSZ;
}
/*
* This is called to clean up large amounts of unused memory allocated
* by the indirection array. Before compacting anything though, verify
* that the indirection array is still needed and switch back to the
* linear extent list (or even the inline buffer) if possible. The
* compaction policy is as follows:
*
* Full Compaction: Extents fit into a single page (or inline buffer)
* Partial Compaction: Extents occupy less than 50% of allocated space
* No Compaction: Extents occupy at least 50% of allocated space
*/
void
xfs_iext_irec_compact(
xfs_ifork_t *ifp) /* inode fork pointer */
{
xfs_extnum_t nextents; /* number of extents in file */
int nlists; /* number of irec's (ex lists) */
ASSERT(ifp->if_flags & XFS_IFEXTIREC);
nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
if (nextents == 0) {
xfs_iext_destroy(ifp);
} else if (nextents <= XFS_INLINE_EXTS) {
xfs_iext_indirect_to_direct(ifp);
xfs_iext_direct_to_inline(ifp, nextents);
} else if (nextents <= XFS_LINEAR_EXTS) {
xfs_iext_indirect_to_direct(ifp);
} else if (nextents < (nlists * XFS_LINEAR_EXTS) >> 1) {
xfs_iext_irec_compact_pages(ifp);
}
}
/*
* Combine extents from neighboring extent pages.
*/
void
xfs_iext_irec_compact_pages(
xfs_ifork_t *ifp) /* inode fork pointer */
{
xfs_ext_irec_t *erp, *erp_next;/* pointers to irec entries */
int erp_idx = 0; /* indirection array index */
int nlists; /* number of irec's (ex lists) */
ASSERT(ifp->if_flags & XFS_IFEXTIREC);
nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
while (erp_idx < nlists - 1) {
erp = &ifp->if_u1.if_ext_irec[erp_idx];
erp_next = erp + 1;
if (erp_next->er_extcount <=
(XFS_LINEAR_EXTS - erp->er_extcount)) {
memcpy(&erp->er_extbuf[erp->er_extcount],
erp_next->er_extbuf, erp_next->er_extcount *
sizeof(xfs_bmbt_rec_t));
erp->er_extcount += erp_next->er_extcount;
/*
* Free page before removing extent record
* so er_extoffs don't get modified in
* xfs_iext_irec_remove.
*/
kmem_free(erp_next->er_extbuf);
erp_next->er_extbuf = NULL;
xfs_iext_irec_remove(ifp, erp_idx + 1);
nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
} else {
erp_idx++;
}
}
}
/*
* This is called to update the er_extoff field in the indirection
* array when extents have been added or removed from one of the
* extent lists. erp_idx contains the irec index to begin updating
* at and ext_diff contains the number of extents that were added
* or removed.
*/
void
xfs_iext_irec_update_extoffs(
xfs_ifork_t *ifp, /* inode fork pointer */
int erp_idx, /* irec index to update */
int ext_diff) /* number of new extents */
{
int i; /* loop counter */
int nlists; /* number of irec's (ex lists */
ASSERT(ifp->if_flags & XFS_IFEXTIREC);
nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
for (i = erp_idx; i < nlists; i++) {
ifp->if_u1.if_ext_irec[i].er_extoff += ext_diff;
}
}
| gpl-2.0 |
kartzan/android_kernel_samsung_msm8930-common | drivers/staging/rtl8192u/ieee80211/ieee80211_softmac.c | 5068 | 89859 | /* IEEE 802.11 SoftMAC layer
* Copyright (c) 2005 Andrea Merello <andreamrl@tiscali.it>
*
* Mostly extracted from the rtl8180-sa2400 driver for the
* in-kernel generic ieee802.11 stack.
*
* Few lines might be stolen from other part of the ieee80211
* stack. Copyright who own it's copyright
*
* WPA code stolen from the ipw2200 driver.
* Copyright who own it's copyright.
*
* released under the GPL
*/
#include "ieee80211.h"
#include <linux/random.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include "dot11d.h"
u8 rsn_authen_cipher_suite[16][4] = {
{0x00,0x0F,0xAC,0x00}, //Use group key, //Reserved
{0x00,0x0F,0xAC,0x01}, //WEP-40 //RSNA default
{0x00,0x0F,0xAC,0x02}, //TKIP //NONE //{used just as default}
{0x00,0x0F,0xAC,0x03}, //WRAP-historical
{0x00,0x0F,0xAC,0x04}, //CCMP
{0x00,0x0F,0xAC,0x05}, //WEP-104
};
short ieee80211_is_54g(const struct ieee80211_network *net)
{
return (net->rates_ex_len > 0) || (net->rates_len > 4);
}
short ieee80211_is_shortslot(const struct ieee80211_network *net)
{
return net->capability & WLAN_CAPABILITY_SHORT_SLOT;
}
/* returns the total length needed for pleacing the RATE MFIE
* tag and the EXTENDED RATE MFIE tag if needed.
* It encludes two bytes per tag for the tag itself and its len
*/
unsigned int ieee80211_MFIE_rate_len(struct ieee80211_device *ieee)
{
unsigned int rate_len = 0;
if (ieee->modulation & IEEE80211_CCK_MODULATION)
rate_len = IEEE80211_CCK_RATE_LEN + 2;
if (ieee->modulation & IEEE80211_OFDM_MODULATION)
rate_len += IEEE80211_OFDM_RATE_LEN + 2;
return rate_len;
}
/* pleace the MFIE rate, tag to the memory (double) poined.
* Then it updates the pointer so that
* it points after the new MFIE tag added.
*/
void ieee80211_MFIE_Brate(struct ieee80211_device *ieee, u8 **tag_p)
{
u8 *tag = *tag_p;
if (ieee->modulation & IEEE80211_CCK_MODULATION){
*tag++ = MFIE_TYPE_RATES;
*tag++ = 4;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_1MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_2MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_5MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_11MB;
}
/* We may add an option for custom rates that specific HW might support */
*tag_p = tag;
}
void ieee80211_MFIE_Grate(struct ieee80211_device *ieee, u8 **tag_p)
{
u8 *tag = *tag_p;
if (ieee->modulation & IEEE80211_OFDM_MODULATION){
*tag++ = MFIE_TYPE_RATES_EX;
*tag++ = 8;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_6MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_9MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_12MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_18MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_24MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_36MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_48MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_54MB;
}
/* We may add an option for custom rates that specific HW might support */
*tag_p = tag;
}
void ieee80211_WMM_Info(struct ieee80211_device *ieee, u8 **tag_p) {
u8 *tag = *tag_p;
*tag++ = MFIE_TYPE_GENERIC; //0
*tag++ = 7;
*tag++ = 0x00;
*tag++ = 0x50;
*tag++ = 0xf2;
*tag++ = 0x02;//5
*tag++ = 0x00;
*tag++ = 0x01;
#ifdef SUPPORT_USPD
if(ieee->current_network.wmm_info & 0x80) {
*tag++ = 0x0f|MAX_SP_Len;
} else {
*tag++ = MAX_SP_Len;
}
#else
*tag++ = MAX_SP_Len;
#endif
*tag_p = tag;
}
#ifdef THOMAS_TURBO
void ieee80211_TURBO_Info(struct ieee80211_device *ieee, u8 **tag_p) {
u8 *tag = *tag_p;
*tag++ = MFIE_TYPE_GENERIC; //0
*tag++ = 7;
*tag++ = 0x00;
*tag++ = 0xe0;
*tag++ = 0x4c;
*tag++ = 0x01;//5
*tag++ = 0x02;
*tag++ = 0x11;
*tag++ = 0x00;
*tag_p = tag;
printk(KERN_ALERT "This is enable turbo mode IE process\n");
}
#endif
void enqueue_mgmt(struct ieee80211_device *ieee, struct sk_buff *skb)
{
int nh;
nh = (ieee->mgmt_queue_head +1) % MGMT_QUEUE_NUM;
/*
* if the queue is full but we have newer frames then
* just overwrites the oldest.
*
* if (nh == ieee->mgmt_queue_tail)
* return -1;
*/
ieee->mgmt_queue_head = nh;
ieee->mgmt_queue_ring[nh] = skb;
//return 0;
}
struct sk_buff *dequeue_mgmt(struct ieee80211_device *ieee)
{
struct sk_buff *ret;
if(ieee->mgmt_queue_tail == ieee->mgmt_queue_head)
return NULL;
ret = ieee->mgmt_queue_ring[ieee->mgmt_queue_tail];
ieee->mgmt_queue_tail =
(ieee->mgmt_queue_tail+1) % MGMT_QUEUE_NUM;
return ret;
}
void init_mgmt_queue(struct ieee80211_device *ieee)
{
ieee->mgmt_queue_tail = ieee->mgmt_queue_head = 0;
}
u8 MgntQuery_MgntFrameTxRate(struct ieee80211_device *ieee)
{
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
u8 rate;
// 2008/01/25 MH For broadcom, MGNT frame set as OFDM 6M.
if(pHTInfo->IOTAction & HT_IOT_ACT_MGNT_USE_CCK_6M)
rate = 0x0c;
else
rate = ieee->basic_rate & 0x7f;
if(rate == 0){
// 2005.01.26, by rcnjko.
if(ieee->mode == IEEE_A||
ieee->mode== IEEE_N_5G||
(ieee->mode== IEEE_N_24G&&!pHTInfo->bCurSuppCCK))
rate = 0x0c;
else
rate = 0x02;
}
/*
// Data rate of ProbeReq is already decided. Annie, 2005-03-31
if( pMgntInfo->bScanInProgress || (pMgntInfo->bDualModeScanStep!=0) )
{
if(pMgntInfo->dot11CurrentWirelessMode==WIRELESS_MODE_A)
rate = 0x0c;
else
rate = 0x02;
}
*/
return rate;
}
void ieee80211_sta_wakeup(struct ieee80211_device *ieee, short nl);
inline void softmac_mgmt_xmit(struct sk_buff *skb, struct ieee80211_device *ieee)
{
unsigned long flags;
short single = ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE;
struct ieee80211_hdr_3addr *header=
(struct ieee80211_hdr_3addr *) skb->data;
cb_desc *tcb_desc = (cb_desc *)(skb->cb + 8);
spin_lock_irqsave(&ieee->lock, flags);
/* called with 2nd param 0, no mgmt lock required */
ieee80211_sta_wakeup(ieee,0);
tcb_desc->queue_index = MGNT_QUEUE;
tcb_desc->data_rate = MgntQuery_MgntFrameTxRate(ieee);
tcb_desc->RATRIndex = 7;
tcb_desc->bTxDisableRateFallBack = 1;
tcb_desc->bTxUseDriverAssingedRate = 1;
if(single){
if(ieee->queue_stop){
enqueue_mgmt(ieee,skb);
}else{
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0]<<4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
/* avoid watchdog triggers */
ieee->dev->trans_start = jiffies;
ieee->softmac_data_hard_start_xmit(skb,ieee->dev,ieee->basic_rate);
//dev_kfree_skb_any(skb);//edit by thomas
}
spin_unlock_irqrestore(&ieee->lock, flags);
}else{
spin_unlock_irqrestore(&ieee->lock, flags);
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags);
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
/* check wether the managed packet queued greater than 5 */
if(!ieee->check_nic_enough_desc(ieee->dev,tcb_desc->queue_index)||\
(skb_queue_len(&ieee->skb_waitQ[tcb_desc->queue_index]) != 0)||\
(ieee->queue_stop) ) {
/* insert the skb packet to the management queue */
/* as for the completion function, it does not need
* to check it any more.
* */
printk("%s():insert to waitqueue!\n",__FUNCTION__);
skb_queue_tail(&ieee->skb_waitQ[tcb_desc->queue_index], skb);
} else {
//printk("TX packet!\n");
ieee->softmac_hard_start_xmit(skb,ieee->dev);
//dev_kfree_skb_any(skb);//edit by thomas
}
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags);
}
}
inline void softmac_ps_mgmt_xmit(struct sk_buff *skb, struct ieee80211_device *ieee)
{
short single = ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE;
struct ieee80211_hdr_3addr *header =
(struct ieee80211_hdr_3addr *) skb->data;
if(single){
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
/* avoid watchdog triggers */
ieee->dev->trans_start = jiffies;
ieee->softmac_data_hard_start_xmit(skb,ieee->dev,ieee->basic_rate);
}else{
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
ieee->softmac_hard_start_xmit(skb,ieee->dev);
}
//dev_kfree_skb_any(skb);//edit by thomas
}
inline struct sk_buff *ieee80211_probe_req(struct ieee80211_device *ieee)
{
unsigned int len,rate_len;
u8 *tag;
struct sk_buff *skb;
struct ieee80211_probe_request *req;
len = ieee->current_network.ssid_len;
rate_len = ieee80211_MFIE_rate_len(ieee);
skb = dev_alloc_skb(sizeof(struct ieee80211_probe_request) +
2 + len + rate_len + ieee->tx_headroom);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
req = (struct ieee80211_probe_request *) skb_put(skb,sizeof(struct ieee80211_probe_request));
req->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_PROBE_REQ);
req->header.duration_id = 0; //FIXME: is this OK ?
memset(req->header.addr1, 0xff, ETH_ALEN);
memcpy(req->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memset(req->header.addr3, 0xff, ETH_ALEN);
tag = (u8 *) skb_put(skb,len+2+rate_len);
*tag++ = MFIE_TYPE_SSID;
*tag++ = len;
memcpy(tag, ieee->current_network.ssid, len);
tag += len;
ieee80211_MFIE_Brate(ieee,&tag);
ieee80211_MFIE_Grate(ieee,&tag);
return skb;
}
struct sk_buff *ieee80211_get_beacon_(struct ieee80211_device *ieee);
void ieee80211_send_beacon(struct ieee80211_device *ieee)
{
struct sk_buff *skb;
if(!ieee->ieee_up)
return;
//unsigned long flags;
skb = ieee80211_get_beacon_(ieee);
if (skb){
softmac_mgmt_xmit(skb, ieee);
ieee->softmac_stats.tx_beacons++;
//dev_kfree_skb_any(skb);//edit by thomas
}
// ieee->beacon_timer.expires = jiffies +
// (MSECS( ieee->current_network.beacon_interval -5));
//spin_lock_irqsave(&ieee->beacon_lock,flags);
if(ieee->beacon_txing && ieee->ieee_up){
// if(!timer_pending(&ieee->beacon_timer))
// add_timer(&ieee->beacon_timer);
mod_timer(&ieee->beacon_timer,jiffies+(MSECS(ieee->current_network.beacon_interval-5)));
}
//spin_unlock_irqrestore(&ieee->beacon_lock,flags);
}
void ieee80211_send_beacon_cb(unsigned long _ieee)
{
struct ieee80211_device *ieee =
(struct ieee80211_device *) _ieee;
unsigned long flags;
spin_lock_irqsave(&ieee->beacon_lock, flags);
ieee80211_send_beacon(ieee);
spin_unlock_irqrestore(&ieee->beacon_lock, flags);
}
void ieee80211_send_probe(struct ieee80211_device *ieee)
{
struct sk_buff *skb;
skb = ieee80211_probe_req(ieee);
if (skb){
softmac_mgmt_xmit(skb, ieee);
ieee->softmac_stats.tx_probe_rq++;
//dev_kfree_skb_any(skb);//edit by thomas
}
}
void ieee80211_send_probe_requests(struct ieee80211_device *ieee)
{
if (ieee->active_scan && (ieee->softmac_features & IEEE_SOFTMAC_PROBERQ)){
ieee80211_send_probe(ieee);
ieee80211_send_probe(ieee);
}
}
/* this performs syncro scan blocking the caller until all channels
* in the allowed channel map has been checked.
*/
void ieee80211_softmac_scan_syncro(struct ieee80211_device *ieee)
{
short ch = 0;
u8 channel_map[MAX_CHANNEL_NUMBER+1];
memcpy(channel_map, GET_DOT11D_INFO(ieee)->channel_map, MAX_CHANNEL_NUMBER+1);
down(&ieee->scan_sem);
while(1)
{
do{
ch++;
if (ch > MAX_CHANNEL_NUMBER)
goto out; /* scan completed */
}while(!channel_map[ch]);
/* this function can be called in two situations
* 1- We have switched to ad-hoc mode and we are
* performing a complete syncro scan before conclude
* there are no interesting cell and to create a
* new one. In this case the link state is
* IEEE80211_NOLINK until we found an interesting cell.
* If so the ieee8021_new_net, called by the RX path
* will set the state to IEEE80211_LINKED, so we stop
* scanning
* 2- We are linked and the root uses run iwlist scan.
* So we switch to IEEE80211_LINKED_SCANNING to remember
* that we are still logically linked (not interested in
* new network events, despite for updating the net list,
* but we are temporarly 'unlinked' as the driver shall
* not filter RX frames and the channel is changing.
* So the only situation in witch are interested is to check
* if the state become LINKED because of the #1 situation
*/
if (ieee->state == IEEE80211_LINKED)
goto out;
ieee->set_chan(ieee->dev, ch);
if(channel_map[ch] == 1)
ieee80211_send_probe_requests(ieee);
/* this prevent excessive time wait when we
* need to wait for a syncro scan to end..
*/
if(ieee->state < IEEE80211_LINKED)
;
else
if (ieee->sync_scan_hurryup)
goto out;
msleep_interruptible_rsl(IEEE80211_SOFTMAC_SCAN_TIME);
}
out:
if(ieee->state < IEEE80211_LINKED){
ieee->actscanning = false;
up(&ieee->scan_sem);
}
else{
ieee->sync_scan_hurryup = 0;
if(IS_DOT11D_ENABLE(ieee))
DOT11D_ScanComplete(ieee);
up(&ieee->scan_sem);
}
}
void ieee80211_softmac_scan_wq(struct work_struct *work)
{
struct delayed_work *dwork = container_of(work, struct delayed_work, work);
struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, softmac_scan_wq);
static short watchdog = 0;
u8 channel_map[MAX_CHANNEL_NUMBER+1];
memcpy(channel_map, GET_DOT11D_INFO(ieee)->channel_map, MAX_CHANNEL_NUMBER+1);
if(!ieee->ieee_up)
return;
down(&ieee->scan_sem);
do{
ieee->current_network.channel =
(ieee->current_network.channel + 1) % MAX_CHANNEL_NUMBER;
if (watchdog++ > MAX_CHANNEL_NUMBER)
{
//if current channel is not in channel map, set to default channel.
if (!channel_map[ieee->current_network.channel]) {
ieee->current_network.channel = 6;
goto out; /* no good chans */
}
}
}while(!channel_map[ieee->current_network.channel]);
if (ieee->scanning == 0 )
goto out;
ieee->set_chan(ieee->dev, ieee->current_network.channel);
if(channel_map[ieee->current_network.channel] == 1)
ieee80211_send_probe_requests(ieee);
queue_delayed_work(ieee->wq, &ieee->softmac_scan_wq, IEEE80211_SOFTMAC_SCAN_TIME);
up(&ieee->scan_sem);
return;
out:
if(IS_DOT11D_ENABLE(ieee))
DOT11D_ScanComplete(ieee);
ieee->actscanning = false;
watchdog = 0;
ieee->scanning = 0;
up(&ieee->scan_sem);
}
void ieee80211_beacons_start(struct ieee80211_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->beacon_lock,flags);
ieee->beacon_txing = 1;
ieee80211_send_beacon(ieee);
spin_unlock_irqrestore(&ieee->beacon_lock,flags);
}
void ieee80211_beacons_stop(struct ieee80211_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->beacon_lock,flags);
ieee->beacon_txing = 0;
del_timer_sync(&ieee->beacon_timer);
spin_unlock_irqrestore(&ieee->beacon_lock,flags);
}
void ieee80211_stop_send_beacons(struct ieee80211_device *ieee)
{
if(ieee->stop_send_beacons)
ieee->stop_send_beacons(ieee->dev);
if (ieee->softmac_features & IEEE_SOFTMAC_BEACONS)
ieee80211_beacons_stop(ieee);
}
void ieee80211_start_send_beacons(struct ieee80211_device *ieee)
{
if(ieee->start_send_beacons)
ieee->start_send_beacons(ieee->dev,ieee->basic_rate);
if(ieee->softmac_features & IEEE_SOFTMAC_BEACONS)
ieee80211_beacons_start(ieee);
}
void ieee80211_softmac_stop_scan(struct ieee80211_device *ieee)
{
// unsigned long flags;
//ieee->sync_scan_hurryup = 1;
down(&ieee->scan_sem);
// spin_lock_irqsave(&ieee->lock, flags);
if (ieee->scanning == 1){
ieee->scanning = 0;
cancel_delayed_work(&ieee->softmac_scan_wq);
}
// spin_unlock_irqrestore(&ieee->lock, flags);
up(&ieee->scan_sem);
}
void ieee80211_stop_scan(struct ieee80211_device *ieee)
{
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN)
ieee80211_softmac_stop_scan(ieee);
else
ieee->stop_scan(ieee->dev);
}
/* called with ieee->lock held */
void ieee80211_start_scan(struct ieee80211_device *ieee)
{
if(IS_DOT11D_ENABLE(ieee) )
{
if(IS_COUNTRY_IE_VALID(ieee))
{
RESET_CIE_WATCHDOG(ieee);
}
}
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN){
if (ieee->scanning == 0){
ieee->scanning = 1;
queue_delayed_work(ieee->wq, &ieee->softmac_scan_wq, 0);
}
}else
ieee->start_scan(ieee->dev);
}
/* called with wx_sem held */
void ieee80211_start_scan_syncro(struct ieee80211_device *ieee)
{
if(IS_DOT11D_ENABLE(ieee) )
{
if(IS_COUNTRY_IE_VALID(ieee))
{
RESET_CIE_WATCHDOG(ieee);
}
}
ieee->sync_scan_hurryup = 0;
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN)
ieee80211_softmac_scan_syncro(ieee);
else
ieee->scan_syncro(ieee->dev);
}
inline struct sk_buff *ieee80211_authentication_req(struct ieee80211_network *beacon,
struct ieee80211_device *ieee, int challengelen)
{
struct sk_buff *skb;
struct ieee80211_authentication *auth;
int len = sizeof(struct ieee80211_authentication) + challengelen + ieee->tx_headroom;
skb = dev_alloc_skb(len);
if (!skb) return NULL;
skb_reserve(skb, ieee->tx_headroom);
auth = (struct ieee80211_authentication *)
skb_put(skb, sizeof(struct ieee80211_authentication));
auth->header.frame_ctl = IEEE80211_STYPE_AUTH;
if (challengelen) auth->header.frame_ctl |= IEEE80211_FCTL_WEP;
auth->header.duration_id = 0x013a; //FIXME
memcpy(auth->header.addr1, beacon->bssid, ETH_ALEN);
memcpy(auth->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(auth->header.addr3, beacon->bssid, ETH_ALEN);
//auth->algorithm = ieee->open_wep ? WLAN_AUTH_OPEN : WLAN_AUTH_SHARED_KEY;
if(ieee->auth_mode == 0)
auth->algorithm = WLAN_AUTH_OPEN;
else if(ieee->auth_mode == 1)
auth->algorithm = WLAN_AUTH_SHARED_KEY;
else if(ieee->auth_mode == 2)
auth->algorithm = WLAN_AUTH_OPEN;//0x80;
printk("=================>%s():auth->algorithm is %d\n",__FUNCTION__,auth->algorithm);
auth->transaction = cpu_to_le16(ieee->associate_seq);
ieee->associate_seq++;
auth->status = cpu_to_le16(WLAN_STATUS_SUCCESS);
return skb;
}
static struct sk_buff* ieee80211_probe_resp(struct ieee80211_device *ieee, u8 *dest)
{
u8 *tag;
int beacon_size;
struct ieee80211_probe_response *beacon_buf;
struct sk_buff *skb = NULL;
int encrypt;
int atim_len,erp_len;
struct ieee80211_crypt_data* crypt;
char *ssid = ieee->current_network.ssid;
int ssid_len = ieee->current_network.ssid_len;
int rate_len = ieee->current_network.rates_len+2;
int rate_ex_len = ieee->current_network.rates_ex_len;
int wpa_ie_len = ieee->wpa_ie_len;
u8 erpinfo_content = 0;
u8* tmp_ht_cap_buf;
u8 tmp_ht_cap_len=0;
u8* tmp_ht_info_buf;
u8 tmp_ht_info_len=0;
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
u8* tmp_generic_ie_buf=NULL;
u8 tmp_generic_ie_len=0;
if(rate_ex_len > 0) rate_ex_len+=2;
if(ieee->current_network.capability & WLAN_CAPABILITY_IBSS)
atim_len = 4;
else
atim_len = 0;
if(ieee80211_is_54g(&ieee->current_network))
erp_len = 3;
else
erp_len = 0;
crypt = ieee->crypt[ieee->tx_keyidx];
encrypt = ieee->host_encrypt && crypt && crypt->ops &&
((0 == strcmp(crypt->ops->name, "WEP") || wpa_ie_len));
//HT ralated element
tmp_ht_cap_buf =(u8*) &(ieee->pHTInfo->SelfHTCap);
tmp_ht_cap_len = sizeof(ieee->pHTInfo->SelfHTCap);
tmp_ht_info_buf =(u8*) &(ieee->pHTInfo->SelfHTInfo);
tmp_ht_info_len = sizeof(ieee->pHTInfo->SelfHTInfo);
HTConstructCapabilityElement(ieee, tmp_ht_cap_buf, &tmp_ht_cap_len,encrypt);
HTConstructInfoElement(ieee,tmp_ht_info_buf,&tmp_ht_info_len, encrypt);
if(pHTInfo->bRegRT2RTAggregation)
{
tmp_generic_ie_buf = ieee->pHTInfo->szRT2RTAggBuffer;
tmp_generic_ie_len = sizeof(ieee->pHTInfo->szRT2RTAggBuffer);
HTConstructRT2RTAggElement(ieee, tmp_generic_ie_buf, &tmp_generic_ie_len);
}
// printk("===============>tmp_ht_cap_len is %d,tmp_ht_info_len is %d, tmp_generic_ie_len is %d\n",tmp_ht_cap_len,tmp_ht_info_len,tmp_generic_ie_len);
beacon_size = sizeof(struct ieee80211_probe_response)+2+
ssid_len
+3 //channel
+rate_len
+rate_ex_len
+atim_len
+erp_len
+wpa_ie_len
// +tmp_ht_cap_len
// +tmp_ht_info_len
// +tmp_generic_ie_len
// +wmm_len+2
+ieee->tx_headroom;
skb = dev_alloc_skb(beacon_size);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
beacon_buf = (struct ieee80211_probe_response*) skb_put(skb, (beacon_size - ieee->tx_headroom));
memcpy (beacon_buf->header.addr1, dest,ETH_ALEN);
memcpy (beacon_buf->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy (beacon_buf->header.addr3, ieee->current_network.bssid, ETH_ALEN);
beacon_buf->header.duration_id = 0; //FIXME
beacon_buf->beacon_interval =
cpu_to_le16(ieee->current_network.beacon_interval);
beacon_buf->capability =
cpu_to_le16(ieee->current_network.capability & WLAN_CAPABILITY_IBSS);
beacon_buf->capability |=
cpu_to_le16(ieee->current_network.capability & WLAN_CAPABILITY_SHORT_PREAMBLE); //add short preamble here
if(ieee->short_slot && (ieee->current_network.capability & WLAN_CAPABILITY_SHORT_SLOT))
beacon_buf->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_SLOT);
crypt = ieee->crypt[ieee->tx_keyidx];
if (encrypt)
beacon_buf->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
beacon_buf->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_PROBE_RESP);
beacon_buf->info_element[0].id = MFIE_TYPE_SSID;
beacon_buf->info_element[0].len = ssid_len;
tag = (u8*) beacon_buf->info_element[0].data;
memcpy(tag, ssid, ssid_len);
tag += ssid_len;
*(tag++) = MFIE_TYPE_RATES;
*(tag++) = rate_len-2;
memcpy(tag,ieee->current_network.rates,rate_len-2);
tag+=rate_len-2;
*(tag++) = MFIE_TYPE_DS_SET;
*(tag++) = 1;
*(tag++) = ieee->current_network.channel;
if(atim_len){
u16 val16;
*(tag++) = MFIE_TYPE_IBSS_SET;
*(tag++) = 2;
//*((u16*)(tag)) = cpu_to_le16(ieee->current_network.atim_window);
val16 = cpu_to_le16(ieee->current_network.atim_window);
memcpy((u8 *)tag, (u8 *)&val16, 2);
tag+=2;
}
if(erp_len){
*(tag++) = MFIE_TYPE_ERP;
*(tag++) = 1;
*(tag++) = erpinfo_content;
}
if(rate_ex_len){
*(tag++) = MFIE_TYPE_RATES_EX;
*(tag++) = rate_ex_len-2;
memcpy(tag,ieee->current_network.rates_ex,rate_ex_len-2);
tag+=rate_ex_len-2;
}
if (wpa_ie_len)
{
if (ieee->iw_mode == IW_MODE_ADHOC)
{//as Windows will set pairwise key same as the group key which is not allowed in Linux, so set this for IOT issue. WB 2008.07.07
memcpy(&ieee->wpa_ie[14], &ieee->wpa_ie[8], 4);
}
memcpy(tag, ieee->wpa_ie, ieee->wpa_ie_len);
tag += wpa_ie_len;
}
//skb->dev = ieee->dev;
return skb;
}
struct sk_buff* ieee80211_assoc_resp(struct ieee80211_device *ieee, u8 *dest)
{
struct sk_buff *skb;
u8* tag;
struct ieee80211_crypt_data* crypt;
struct ieee80211_assoc_response_frame *assoc;
short encrypt;
unsigned int rate_len = ieee80211_MFIE_rate_len(ieee);
int len = sizeof(struct ieee80211_assoc_response_frame) + rate_len + ieee->tx_headroom;
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
assoc = (struct ieee80211_assoc_response_frame *)
skb_put(skb,sizeof(struct ieee80211_assoc_response_frame));
assoc->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_ASSOC_RESP);
memcpy(assoc->header.addr1, dest,ETH_ALEN);
memcpy(assoc->header.addr3, ieee->dev->dev_addr, ETH_ALEN);
memcpy(assoc->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
assoc->capability = cpu_to_le16(ieee->iw_mode == IW_MODE_MASTER ?
WLAN_CAPABILITY_BSS : WLAN_CAPABILITY_IBSS);
if(ieee->short_slot)
assoc->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_SLOT);
if (ieee->host_encrypt)
crypt = ieee->crypt[ieee->tx_keyidx];
else crypt = NULL;
encrypt = ( crypt && crypt->ops);
if (encrypt)
assoc->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
assoc->status = 0;
assoc->aid = cpu_to_le16(ieee->assoc_id);
if (ieee->assoc_id == 0x2007) ieee->assoc_id=0;
else ieee->assoc_id++;
tag = (u8*) skb_put(skb, rate_len);
ieee80211_MFIE_Brate(ieee, &tag);
ieee80211_MFIE_Grate(ieee, &tag);
return skb;
}
struct sk_buff* ieee80211_auth_resp(struct ieee80211_device *ieee,int status, u8 *dest)
{
struct sk_buff *skb;
struct ieee80211_authentication *auth;
int len = ieee->tx_headroom + sizeof(struct ieee80211_authentication)+1;
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
skb->len = sizeof(struct ieee80211_authentication);
auth = (struct ieee80211_authentication *)skb->data;
auth->status = cpu_to_le16(status);
auth->transaction = cpu_to_le16(2);
auth->algorithm = cpu_to_le16(WLAN_AUTH_OPEN);
memcpy(auth->header.addr3, ieee->dev->dev_addr, ETH_ALEN);
memcpy(auth->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(auth->header.addr1, dest, ETH_ALEN);
auth->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_AUTH);
return skb;
}
struct sk_buff* ieee80211_null_func(struct ieee80211_device *ieee,short pwr)
{
struct sk_buff *skb;
struct ieee80211_hdr_3addr* hdr;
skb = dev_alloc_skb(sizeof(struct ieee80211_hdr_3addr));
if (!skb)
return NULL;
hdr = (struct ieee80211_hdr_3addr*)skb_put(skb,sizeof(struct ieee80211_hdr_3addr));
memcpy(hdr->addr1, ieee->current_network.bssid, ETH_ALEN);
memcpy(hdr->addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(hdr->addr3, ieee->current_network.bssid, ETH_ALEN);
hdr->frame_ctl = cpu_to_le16(IEEE80211_FTYPE_DATA |
IEEE80211_STYPE_NULLFUNC | IEEE80211_FCTL_TODS |
(pwr ? IEEE80211_FCTL_PM:0));
return skb;
}
void ieee80211_resp_to_assoc_rq(struct ieee80211_device *ieee, u8* dest)
{
struct sk_buff *buf = ieee80211_assoc_resp(ieee, dest);
if (buf)
softmac_mgmt_xmit(buf, ieee);
}
void ieee80211_resp_to_auth(struct ieee80211_device *ieee, int s, u8* dest)
{
struct sk_buff *buf = ieee80211_auth_resp(ieee, s, dest);
if (buf)
softmac_mgmt_xmit(buf, ieee);
}
void ieee80211_resp_to_probe(struct ieee80211_device *ieee, u8 *dest)
{
struct sk_buff *buf = ieee80211_probe_resp(ieee, dest);
if (buf)
softmac_mgmt_xmit(buf, ieee);
}
inline struct sk_buff *ieee80211_association_req(struct ieee80211_network *beacon,struct ieee80211_device *ieee)
{
struct sk_buff *skb;
//unsigned long flags;
struct ieee80211_assoc_request_frame *hdr;
u8 *tag;//,*rsn_ie;
//short info_addr = 0;
//int i;
//u16 suite_count = 0;
//u8 suit_select = 0;
//unsigned int wpa_len = beacon->wpa_ie_len;
//for HT
u8* ht_cap_buf = NULL;
u8 ht_cap_len=0;
u8* realtek_ie_buf=NULL;
u8 realtek_ie_len=0;
int wpa_ie_len= ieee->wpa_ie_len;
unsigned int ckip_ie_len=0;
unsigned int ccxrm_ie_len=0;
unsigned int cxvernum_ie_len=0;
struct ieee80211_crypt_data* crypt;
int encrypt;
unsigned int rate_len = ieee80211_MFIE_rate_len(ieee);
unsigned int wmm_info_len = beacon->qos_data.supported?9:0;
#ifdef THOMAS_TURBO
unsigned int turbo_info_len = beacon->Turbo_Enable?9:0;
#endif
int len = 0;
crypt = ieee->crypt[ieee->tx_keyidx];
encrypt = ieee->host_encrypt && crypt && crypt->ops && ((0 == strcmp(crypt->ops->name,"WEP") || wpa_ie_len));
//Include High Throuput capability && Realtek proprietary
if(ieee->pHTInfo->bCurrentHTSupport&&ieee->pHTInfo->bEnableHT)
{
ht_cap_buf = (u8*)&(ieee->pHTInfo->SelfHTCap);
ht_cap_len = sizeof(ieee->pHTInfo->SelfHTCap);
HTConstructCapabilityElement(ieee, ht_cap_buf, &ht_cap_len, encrypt);
if(ieee->pHTInfo->bCurrentRT2RTAggregation)
{
realtek_ie_buf = ieee->pHTInfo->szRT2RTAggBuffer;
realtek_ie_len = sizeof( ieee->pHTInfo->szRT2RTAggBuffer);
HTConstructRT2RTAggElement(ieee, realtek_ie_buf, &realtek_ie_len);
}
}
if(ieee->qos_support){
wmm_info_len = beacon->qos_data.supported?9:0;
}
if(beacon->bCkipSupported)
{
ckip_ie_len = 30+2;
}
if(beacon->bCcxRmEnable)
{
ccxrm_ie_len = 6+2;
}
if( beacon->BssCcxVerNumber >= 2 )
{
cxvernum_ie_len = 5+2;
}
#ifdef THOMAS_TURBO
len = sizeof(struct ieee80211_assoc_request_frame)+ 2
+ beacon->ssid_len//essid tagged val
+ rate_len//rates tagged val
+ wpa_ie_len
+ wmm_info_len
+ turbo_info_len
+ ht_cap_len
+ realtek_ie_len
+ ckip_ie_len
+ ccxrm_ie_len
+ cxvernum_ie_len
+ ieee->tx_headroom;
#else
len = sizeof(struct ieee80211_assoc_request_frame)+ 2
+ beacon->ssid_len//essid tagged val
+ rate_len//rates tagged val
+ wpa_ie_len
+ wmm_info_len
+ ht_cap_len
+ realtek_ie_len
+ ckip_ie_len
+ ccxrm_ie_len
+ cxvernum_ie_len
+ ieee->tx_headroom;
#endif
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
hdr = (struct ieee80211_assoc_request_frame *)
skb_put(skb, sizeof(struct ieee80211_assoc_request_frame)+2);
hdr->header.frame_ctl = IEEE80211_STYPE_ASSOC_REQ;
hdr->header.duration_id= 37; //FIXME
memcpy(hdr->header.addr1, beacon->bssid, ETH_ALEN);
memcpy(hdr->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(hdr->header.addr3, beacon->bssid, ETH_ALEN);
memcpy(ieee->ap_mac_addr, beacon->bssid, ETH_ALEN);//for HW security, John
hdr->capability = cpu_to_le16(WLAN_CAPABILITY_BSS);
if (beacon->capability & WLAN_CAPABILITY_PRIVACY )
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
if (beacon->capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_PREAMBLE); //add short_preamble here
if(ieee->short_slot)
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_SLOT);
if (wmm_info_len) //QOS
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_QOS);
hdr->listen_interval = 0xa; //FIXME
hdr->info_element[0].id = MFIE_TYPE_SSID;
hdr->info_element[0].len = beacon->ssid_len;
tag = skb_put(skb, beacon->ssid_len);
memcpy(tag, beacon->ssid, beacon->ssid_len);
tag = skb_put(skb, rate_len);
ieee80211_MFIE_Brate(ieee, &tag);
ieee80211_MFIE_Grate(ieee, &tag);
// For CCX 1 S13, CKIP. Added by Annie, 2006-08-14.
if( beacon->bCkipSupported )
{
static u8 AironetIeOui[] = {0x00, 0x01, 0x66}; // "4500-client"
u8 CcxAironetBuf[30];
OCTET_STRING osCcxAironetIE;
memset(CcxAironetBuf, 0,30);
osCcxAironetIE.Octet = CcxAironetBuf;
osCcxAironetIE.Length = sizeof(CcxAironetBuf);
//
// Ref. CCX test plan v3.61, 3.2.3.1 step 13.
// We want to make the device type as "4500-client". 060926, by CCW.
//
memcpy(osCcxAironetIE.Octet, AironetIeOui, sizeof(AironetIeOui));
// CCX1 spec V1.13, A01.1 CKIP Negotiation (page23):
// "The CKIP negotiation is started with the associate request from the client to the access point,
// containing an Aironet element with both the MIC and KP bits set."
osCcxAironetIE.Octet[IE_CISCO_FLAG_POSITION] |= (SUPPORT_CKIP_PK|SUPPORT_CKIP_MIC) ;
tag = skb_put(skb, ckip_ie_len);
*tag++ = MFIE_TYPE_AIRONET;
*tag++ = osCcxAironetIE.Length;
memcpy(tag,osCcxAironetIE.Octet,osCcxAironetIE.Length);
tag += osCcxAironetIE.Length;
}
if(beacon->bCcxRmEnable)
{
static u8 CcxRmCapBuf[] = {0x00, 0x40, 0x96, 0x01, 0x01, 0x00};
OCTET_STRING osCcxRmCap;
osCcxRmCap.Octet = CcxRmCapBuf;
osCcxRmCap.Length = sizeof(CcxRmCapBuf);
tag = skb_put(skb,ccxrm_ie_len);
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = osCcxRmCap.Length;
memcpy(tag,osCcxRmCap.Octet,osCcxRmCap.Length);
tag += osCcxRmCap.Length;
}
if( beacon->BssCcxVerNumber >= 2 )
{
u8 CcxVerNumBuf[] = {0x00, 0x40, 0x96, 0x03, 0x00};
OCTET_STRING osCcxVerNum;
CcxVerNumBuf[4] = beacon->BssCcxVerNumber;
osCcxVerNum.Octet = CcxVerNumBuf;
osCcxVerNum.Length = sizeof(CcxVerNumBuf);
tag = skb_put(skb,cxvernum_ie_len);
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = osCcxVerNum.Length;
memcpy(tag,osCcxVerNum.Octet,osCcxVerNum.Length);
tag += osCcxVerNum.Length;
}
//HT cap element
if(ieee->pHTInfo->bCurrentHTSupport&&ieee->pHTInfo->bEnableHT){
if(ieee->pHTInfo->ePeerHTSpecVer != HT_SPEC_VER_EWC)
{
tag = skb_put(skb, ht_cap_len);
*tag++ = MFIE_TYPE_HT_CAP;
*tag++ = ht_cap_len - 2;
memcpy(tag, ht_cap_buf,ht_cap_len -2);
tag += ht_cap_len -2;
}
}
//choose what wpa_supplicant gives to associate.
tag = skb_put(skb, wpa_ie_len);
if (wpa_ie_len){
memcpy(tag, ieee->wpa_ie, ieee->wpa_ie_len);
}
tag = skb_put(skb,wmm_info_len);
if(wmm_info_len) {
ieee80211_WMM_Info(ieee, &tag);
}
#ifdef THOMAS_TURBO
tag = skb_put(skb,turbo_info_len);
if(turbo_info_len) {
ieee80211_TURBO_Info(ieee, &tag);
}
#endif
if(ieee->pHTInfo->bCurrentHTSupport&&ieee->pHTInfo->bEnableHT){
if(ieee->pHTInfo->ePeerHTSpecVer == HT_SPEC_VER_EWC)
{
tag = skb_put(skb, ht_cap_len);
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = ht_cap_len - 2;
memcpy(tag, ht_cap_buf,ht_cap_len - 2);
tag += ht_cap_len -2;
}
if(ieee->pHTInfo->bCurrentRT2RTAggregation){
tag = skb_put(skb, realtek_ie_len);
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = realtek_ie_len - 2;
memcpy(tag, realtek_ie_buf,realtek_ie_len -2 );
}
}
// printk("<=====%s(), %p, %p\n", __FUNCTION__, ieee->dev, ieee->dev->dev_addr);
// IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA, skb->data, skb->len);
return skb;
}
void ieee80211_associate_abort(struct ieee80211_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->lock, flags);
ieee->associate_seq++;
/* don't scan, and avoid to have the RX path possibily
* try again to associate. Even do not react to AUTH or
* ASSOC response. Just wait for the retry wq to be scheduled.
* Here we will check if there are good nets to associate
* with, so we retry or just get back to NO_LINK and scanning
*/
if (ieee->state == IEEE80211_ASSOCIATING_AUTHENTICATING){
IEEE80211_DEBUG_MGMT("Authentication failed\n");
ieee->softmac_stats.no_auth_rs++;
}else{
IEEE80211_DEBUG_MGMT("Association failed\n");
ieee->softmac_stats.no_ass_rs++;
}
ieee->state = IEEE80211_ASSOCIATING_RETRY;
queue_delayed_work(ieee->wq, &ieee->associate_retry_wq, \
IEEE80211_SOFTMAC_ASSOC_RETRY_TIME);
spin_unlock_irqrestore(&ieee->lock, flags);
}
void ieee80211_associate_abort_cb(unsigned long dev)
{
ieee80211_associate_abort((struct ieee80211_device *) dev);
}
void ieee80211_associate_step1(struct ieee80211_device *ieee)
{
struct ieee80211_network *beacon = &ieee->current_network;
struct sk_buff *skb;
IEEE80211_DEBUG_MGMT("Stopping scan\n");
ieee->softmac_stats.tx_auth_rq++;
skb=ieee80211_authentication_req(beacon, ieee, 0);
if (!skb)
ieee80211_associate_abort(ieee);
else{
ieee->state = IEEE80211_ASSOCIATING_AUTHENTICATING ;
IEEE80211_DEBUG_MGMT("Sending authentication request\n");
//printk(KERN_WARNING "Sending authentication request\n");
softmac_mgmt_xmit(skb, ieee);
//BUGON when you try to add_timer twice, using mod_timer may be better, john0709
if(!timer_pending(&ieee->associate_timer)){
ieee->associate_timer.expires = jiffies + (HZ / 2);
add_timer(&ieee->associate_timer);
}
//dev_kfree_skb_any(skb);//edit by thomas
}
}
void ieee80211_auth_challenge(struct ieee80211_device *ieee, u8 *challenge, int chlen)
{
u8 *c;
struct sk_buff *skb;
struct ieee80211_network *beacon = &ieee->current_network;
// int hlen = sizeof(struct ieee80211_authentication);
ieee->associate_seq++;
ieee->softmac_stats.tx_auth_rq++;
skb = ieee80211_authentication_req(beacon, ieee, chlen+2);
if (!skb)
ieee80211_associate_abort(ieee);
else{
c = skb_put(skb, chlen+2);
*(c++) = MFIE_TYPE_CHALLENGE;
*(c++) = chlen;
memcpy(c, challenge, chlen);
IEEE80211_DEBUG_MGMT("Sending authentication challenge response\n");
ieee80211_encrypt_fragment(ieee, skb, sizeof(struct ieee80211_hdr_3addr ));
softmac_mgmt_xmit(skb, ieee);
mod_timer(&ieee->associate_timer, jiffies + (HZ/2));
//dev_kfree_skb_any(skb);//edit by thomas
}
kfree(challenge);
}
void ieee80211_associate_step2(struct ieee80211_device *ieee)
{
struct sk_buff* skb;
struct ieee80211_network *beacon = &ieee->current_network;
del_timer_sync(&ieee->associate_timer);
IEEE80211_DEBUG_MGMT("Sending association request\n");
ieee->softmac_stats.tx_ass_rq++;
skb=ieee80211_association_req(beacon, ieee);
if (!skb)
ieee80211_associate_abort(ieee);
else{
softmac_mgmt_xmit(skb, ieee);
mod_timer(&ieee->associate_timer, jiffies + (HZ/2));
//dev_kfree_skb_any(skb);//edit by thomas
}
}
void ieee80211_associate_complete_wq(struct work_struct *work)
{
struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, associate_complete_wq);
printk(KERN_INFO "Associated successfully\n");
if(ieee80211_is_54g(&ieee->current_network) &&
(ieee->modulation & IEEE80211_OFDM_MODULATION)){
ieee->rate = 108;
printk(KERN_INFO"Using G rates:%d\n", ieee->rate);
}else{
ieee->rate = 22;
printk(KERN_INFO"Using B rates:%d\n", ieee->rate);
}
if (ieee->pHTInfo->bCurrentHTSupport&&ieee->pHTInfo->bEnableHT)
{
printk("Successfully associated, ht enabled\n");
HTOnAssocRsp(ieee);
}
else
{
printk("Successfully associated, ht not enabled(%d, %d)\n", ieee->pHTInfo->bCurrentHTSupport, ieee->pHTInfo->bEnableHT);
memset(ieee->dot11HTOperationalRateSet, 0, 16);
//HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
}
ieee->LinkDetectInfo.SlotNum = 2 * (1 + ieee->current_network.beacon_interval/500);
// To prevent the immediately calling watch_dog after association.
if(ieee->LinkDetectInfo.NumRecvBcnInPeriod==0||ieee->LinkDetectInfo.NumRecvDataInPeriod==0 )
{
ieee->LinkDetectInfo.NumRecvBcnInPeriod = 1;
ieee->LinkDetectInfo.NumRecvDataInPeriod= 1;
}
ieee->link_change(ieee->dev);
if(ieee->is_silent_reset == 0){
printk("============>normal associate\n");
notify_wx_assoc_event(ieee);
}
else if(ieee->is_silent_reset == 1)
{
printk("==================>silent reset associate\n");
ieee->is_silent_reset = 0;
}
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
}
void ieee80211_associate_complete(struct ieee80211_device *ieee)
{
// int i;
// struct net_device* dev = ieee->dev;
del_timer_sync(&ieee->associate_timer);
ieee->state = IEEE80211_LINKED;
//ieee->UpdateHalRATRTableHandler(dev, ieee->dot11HTOperationalRateSet);
queue_work(ieee->wq, &ieee->associate_complete_wq);
}
void ieee80211_associate_procedure_wq(struct work_struct *work)
{
struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, associate_procedure_wq);
ieee->sync_scan_hurryup = 1;
down(&ieee->wx_sem);
if (ieee->data_hard_stop)
ieee->data_hard_stop(ieee->dev);
ieee80211_stop_scan(ieee);
printk("===>%s(), chan:%d\n", __FUNCTION__, ieee->current_network.channel);
//ieee->set_chan(ieee->dev, ieee->current_network.channel);
HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
ieee->associate_seq = 1;
ieee80211_associate_step1(ieee);
up(&ieee->wx_sem);
}
inline void ieee80211_softmac_new_net(struct ieee80211_device *ieee, struct ieee80211_network *net)
{
u8 tmp_ssid[IW_ESSID_MAX_SIZE+1];
int tmp_ssid_len = 0;
short apset,ssidset,ssidbroad,apmatch,ssidmatch;
/* we are interested in new new only if we are not associated
* and we are not associating / authenticating
*/
if (ieee->state != IEEE80211_NOLINK)
return;
if ((ieee->iw_mode == IW_MODE_INFRA) && !(net->capability & WLAN_CAPABILITY_BSS))
return;
if ((ieee->iw_mode == IW_MODE_ADHOC) && !(net->capability & WLAN_CAPABILITY_IBSS))
return;
if (ieee->iw_mode == IW_MODE_INFRA || ieee->iw_mode == IW_MODE_ADHOC){
/* if the user specified the AP MAC, we need also the essid
* This could be obtained by beacons or, if the network does not
* broadcast it, it can be put manually.
*/
apset = ieee->wap_set;//(memcmp(ieee->current_network.bssid, zero,ETH_ALEN)!=0 );
ssidset = ieee->ssid_set;//ieee->current_network.ssid[0] != '\0';
ssidbroad = !(net->ssid_len == 0 || net->ssid[0]== '\0');
apmatch = (memcmp(ieee->current_network.bssid, net->bssid, ETH_ALEN)==0);
ssidmatch = (ieee->current_network.ssid_len == net->ssid_len)&&\
(!strncmp(ieee->current_network.ssid, net->ssid, net->ssid_len));
if ( /* if the user set the AP check if match.
* if the network does not broadcast essid we check the user supplyed ANY essid
* if the network does broadcast and the user does not set essid it is OK
* if the network does broadcast and the user did set essid chech if essid match
*/
( apset && apmatch &&
((ssidset && ssidbroad && ssidmatch) || (ssidbroad && !ssidset) || (!ssidbroad && ssidset)) ) ||
/* if the ap is not set, check that the user set the bssid
* and the network does bradcast and that those two bssid matches
*/
(!apset && ssidset && ssidbroad && ssidmatch)
){
/* if the essid is hidden replace it with the
* essid provided by the user.
*/
if (!ssidbroad){
strncpy(tmp_ssid, ieee->current_network.ssid, IW_ESSID_MAX_SIZE);
tmp_ssid_len = ieee->current_network.ssid_len;
}
memcpy(&ieee->current_network, net, sizeof(struct ieee80211_network));
if (!ssidbroad){
strncpy(ieee->current_network.ssid, tmp_ssid, IW_ESSID_MAX_SIZE);
ieee->current_network.ssid_len = tmp_ssid_len;
}
printk(KERN_INFO"Linking with %s,channel:%d, qos:%d, myHT:%d, networkHT:%d\n",ieee->current_network.ssid,ieee->current_network.channel, ieee->current_network.qos_data.supported, ieee->pHTInfo->bEnableHT, ieee->current_network.bssht.bdSupportHT);
//ieee->pHTInfo->IOTAction = 0;
HTResetIOTSetting(ieee->pHTInfo);
if (ieee->iw_mode == IW_MODE_INFRA){
/* Join the network for the first time */
ieee->AsocRetryCount = 0;
//for HT by amy 080514
if((ieee->current_network.qos_data.supported == 1) &&
// (ieee->pHTInfo->bEnableHT && ieee->current_network.bssht.bdSupportHT))
ieee->current_network.bssht.bdSupportHT)
/*WB, 2008.09.09:bCurrentHTSupport and bEnableHT two flags are going to put together to check whether we are in HT now, so needn't to check bEnableHT flags here. That's is to say we will set to HT support whenever joined AP has the ability to support HT. And whether we are in HT or not, please check bCurrentHTSupport&&bEnableHT now please.*/
{
// ieee->pHTInfo->bCurrentHTSupport = true;
HTResetSelfAndSavePeerSetting(ieee, &(ieee->current_network));
}
else
{
ieee->pHTInfo->bCurrentHTSupport = false;
}
ieee->state = IEEE80211_ASSOCIATING;
queue_work(ieee->wq, &ieee->associate_procedure_wq);
}else{
if(ieee80211_is_54g(&ieee->current_network) &&
(ieee->modulation & IEEE80211_OFDM_MODULATION)){
ieee->rate = 108;
ieee->SetWirelessMode(ieee->dev, IEEE_G);
printk(KERN_INFO"Using G rates\n");
}else{
ieee->rate = 22;
ieee->SetWirelessMode(ieee->dev, IEEE_B);
printk(KERN_INFO"Using B rates\n");
}
memset(ieee->dot11HTOperationalRateSet, 0, 16);
//HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
ieee->state = IEEE80211_LINKED;
}
}
}
}
void ieee80211_softmac_check_all_nets(struct ieee80211_device *ieee)
{
unsigned long flags;
struct ieee80211_network *target;
spin_lock_irqsave(&ieee->lock, flags);
list_for_each_entry(target, &ieee->network_list, list) {
/* if the state become different that NOLINK means
* we had found what we are searching for
*/
if (ieee->state != IEEE80211_NOLINK)
break;
if (ieee->scan_age == 0 || time_after(target->last_scanned + ieee->scan_age, jiffies))
ieee80211_softmac_new_net(ieee, target);
}
spin_unlock_irqrestore(&ieee->lock, flags);
}
static inline u16 auth_parse(struct sk_buff *skb, u8** challenge, int *chlen)
{
struct ieee80211_authentication *a;
u8 *t;
if (skb->len < (sizeof(struct ieee80211_authentication)-sizeof(struct ieee80211_info_element))){
IEEE80211_DEBUG_MGMT("invalid len in auth resp: %d\n",skb->len);
return 0xcafe;
}
*challenge = NULL;
a = (struct ieee80211_authentication*) skb->data;
if(skb->len > (sizeof(struct ieee80211_authentication) +3)){
t = skb->data + sizeof(struct ieee80211_authentication);
if(*(t++) == MFIE_TYPE_CHALLENGE){
*chlen = *(t++);
*challenge = kmemdup(t, *chlen, GFP_ATOMIC);
if (!*challenge)
return -ENOMEM;
}
}
return cpu_to_le16(a->status);
}
int auth_rq_parse(struct sk_buff *skb,u8* dest)
{
struct ieee80211_authentication *a;
if (skb->len < (sizeof(struct ieee80211_authentication)-sizeof(struct ieee80211_info_element))){
IEEE80211_DEBUG_MGMT("invalid len in auth request: %d\n",skb->len);
return -1;
}
a = (struct ieee80211_authentication*) skb->data;
memcpy(dest,a->header.addr2, ETH_ALEN);
if (le16_to_cpu(a->algorithm) != WLAN_AUTH_OPEN)
return WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG;
return WLAN_STATUS_SUCCESS;
}
static short probe_rq_parse(struct ieee80211_device *ieee, struct sk_buff *skb, u8 *src)
{
u8 *tag;
u8 *skbend;
u8 *ssid=NULL;
u8 ssidlen = 0;
struct ieee80211_hdr_3addr *header =
(struct ieee80211_hdr_3addr *) skb->data;
if (skb->len < sizeof (struct ieee80211_hdr_3addr ))
return -1; /* corrupted */
memcpy(src,header->addr2, ETH_ALEN);
skbend = (u8*)skb->data + skb->len;
tag = skb->data + sizeof (struct ieee80211_hdr_3addr );
while (tag+1 < skbend){
if (*tag == 0){
ssid = tag+2;
ssidlen = *(tag+1);
break;
}
tag++; /* point to the len field */
tag = tag + *(tag); /* point to the last data byte of the tag */
tag++; /* point to the next tag */
}
//IEEE80211DMESG("Card MAC address is "MACSTR, MAC2STR(src));
if (ssidlen == 0) return 1;
if (!ssid) return 1; /* ssid not found in tagged param */
return (!strncmp(ssid, ieee->current_network.ssid, ssidlen));
}
int assoc_rq_parse(struct sk_buff *skb,u8* dest)
{
struct ieee80211_assoc_request_frame *a;
if (skb->len < (sizeof(struct ieee80211_assoc_request_frame) -
sizeof(struct ieee80211_info_element))) {
IEEE80211_DEBUG_MGMT("invalid len in auth request:%d \n", skb->len);
return -1;
}
a = (struct ieee80211_assoc_request_frame*) skb->data;
memcpy(dest,a->header.addr2,ETH_ALEN);
return 0;
}
static inline u16 assoc_parse(struct ieee80211_device *ieee, struct sk_buff *skb, int *aid)
{
struct ieee80211_assoc_response_frame *response_head;
u16 status_code;
if (skb->len < sizeof(struct ieee80211_assoc_response_frame)){
IEEE80211_DEBUG_MGMT("invalid len in auth resp: %d\n", skb->len);
return 0xcafe;
}
response_head = (struct ieee80211_assoc_response_frame*) skb->data;
*aid = le16_to_cpu(response_head->aid) & 0x3fff;
status_code = le16_to_cpu(response_head->status);
if((status_code==WLAN_STATUS_ASSOC_DENIED_RATES || \
status_code==WLAN_STATUS_CAPS_UNSUPPORTED)&&
((ieee->mode == IEEE_G) &&
(ieee->current_network.mode == IEEE_N_24G) &&
(ieee->AsocRetryCount++ < (RT_ASOC_RETRY_LIMIT-1)))) {
ieee->pHTInfo->IOTAction |= HT_IOT_ACT_PURE_N_MODE;
}else {
ieee->AsocRetryCount = 0;
}
return le16_to_cpu(response_head->status);
}
static inline void
ieee80211_rx_probe_rq(struct ieee80211_device *ieee, struct sk_buff *skb)
{
u8 dest[ETH_ALEN];
//IEEE80211DMESG("Rx probe");
ieee->softmac_stats.rx_probe_rq++;
//DMESG("Dest is "MACSTR, MAC2STR(dest));
if (probe_rq_parse(ieee, skb, dest)){
//IEEE80211DMESG("Was for me!");
ieee->softmac_stats.tx_probe_rs++;
ieee80211_resp_to_probe(ieee, dest);
}
}
static inline void
ieee80211_rx_auth_rq(struct ieee80211_device *ieee, struct sk_buff *skb)
{
u8 dest[ETH_ALEN];
int status;
//IEEE80211DMESG("Rx probe");
ieee->softmac_stats.rx_auth_rq++;
status = auth_rq_parse(skb, dest);
if (status != -1) {
ieee80211_resp_to_auth(ieee, status, dest);
}
//DMESG("Dest is "MACSTR, MAC2STR(dest));
}
static inline void
ieee80211_rx_assoc_rq(struct ieee80211_device *ieee, struct sk_buff *skb)
{
u8 dest[ETH_ALEN];
//unsigned long flags;
ieee->softmac_stats.rx_ass_rq++;
if (assoc_rq_parse(skb,dest) != -1){
ieee80211_resp_to_assoc_rq(ieee, dest);
}
printk(KERN_INFO"New client associated: %pM\n", dest);
//FIXME
}
void ieee80211_sta_ps_send_null_frame(struct ieee80211_device *ieee, short pwr)
{
struct sk_buff *buf = ieee80211_null_func(ieee, pwr);
if (buf)
softmac_ps_mgmt_xmit(buf, ieee);
}
short ieee80211_sta_ps_sleep(struct ieee80211_device *ieee, u32 *time_h, u32 *time_l)
{
int timeout = ieee->ps_timeout;
u8 dtim;
/*if(ieee->ps == IEEE80211_PS_DISABLED ||
ieee->iw_mode != IW_MODE_INFRA ||
ieee->state != IEEE80211_LINKED)
return 0;
*/
dtim = ieee->current_network.dtim_data;
//printk("DTIM\n");
if(!(dtim & IEEE80211_DTIM_VALID))
return 0;
timeout = ieee->current_network.beacon_interval; //should we use ps_timeout value or beacon_interval
//printk("VALID\n");
ieee->current_network.dtim_data = IEEE80211_DTIM_INVALID;
if(dtim & ((IEEE80211_DTIM_UCAST | IEEE80211_DTIM_MBCAST)& ieee->ps))
return 2;
if(!time_after(jiffies, ieee->dev->trans_start + MSECS(timeout)))
return 0;
if(!time_after(jiffies, ieee->last_rx_ps_time + MSECS(timeout)))
return 0;
if((ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE ) &&
(ieee->mgmt_queue_tail != ieee->mgmt_queue_head))
return 0;
if(time_l){
*time_l = ieee->current_network.last_dtim_sta_time[0]
+ (ieee->current_network.beacon_interval
* ieee->current_network.dtim_period) * 1000;
}
if(time_h){
*time_h = ieee->current_network.last_dtim_sta_time[1];
if(time_l && *time_l < ieee->current_network.last_dtim_sta_time[0])
*time_h += 1;
}
return 1;
}
inline void ieee80211_sta_ps(struct ieee80211_device *ieee)
{
u32 th,tl;
short sleep;
unsigned long flags,flags2;
spin_lock_irqsave(&ieee->lock, flags);
if((ieee->ps == IEEE80211_PS_DISABLED ||
ieee->iw_mode != IW_MODE_INFRA ||
ieee->state != IEEE80211_LINKED)){
// #warning CHECK_LOCK_HERE
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
ieee80211_sta_wakeup(ieee, 1);
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
sleep = ieee80211_sta_ps_sleep(ieee,&th, &tl);
/* 2 wake, 1 sleep, 0 do nothing */
if(sleep == 0)
goto out;
if(sleep == 1){
if(ieee->sta_sleep == 1)
ieee->enter_sleep_state(ieee->dev,th,tl);
else if(ieee->sta_sleep == 0){
// printk("send null 1\n");
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
if(ieee->ps_is_queue_empty(ieee->dev)){
ieee->sta_sleep = 2;
ieee->ps_request_tx_ack(ieee->dev);
ieee80211_sta_ps_send_null_frame(ieee,1);
ieee->ps_th = th;
ieee->ps_tl = tl;
}
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
}else if(sleep == 2){
//#warning CHECK_LOCK_HERE
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
ieee80211_sta_wakeup(ieee,1);
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
out:
spin_unlock_irqrestore(&ieee->lock, flags);
}
void ieee80211_sta_wakeup(struct ieee80211_device *ieee, short nl)
{
if(ieee->sta_sleep == 0){
if(nl){
printk("Warning: driver is probably failing to report TX ps error\n");
ieee->ps_request_tx_ack(ieee->dev);
ieee80211_sta_ps_send_null_frame(ieee, 0);
}
return;
}
if(ieee->sta_sleep == 1)
ieee->sta_wake_up(ieee->dev);
ieee->sta_sleep = 0;
if(nl){
ieee->ps_request_tx_ack(ieee->dev);
ieee80211_sta_ps_send_null_frame(ieee, 0);
}
}
void ieee80211_ps_tx_ack(struct ieee80211_device *ieee, short success)
{
unsigned long flags,flags2;
spin_lock_irqsave(&ieee->lock, flags);
if(ieee->sta_sleep == 2){
/* Null frame with PS bit set */
if(success){
ieee->sta_sleep = 1;
ieee->enter_sleep_state(ieee->dev,ieee->ps_th,ieee->ps_tl);
}
/* if the card report not success we can't be sure the AP
* has not RXed so we can't assume the AP believe us awake
*/
}
/* 21112005 - tx again null without PS bit if lost */
else {
if((ieee->sta_sleep == 0) && !success){
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
ieee80211_sta_ps_send_null_frame(ieee, 0);
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
}
spin_unlock_irqrestore(&ieee->lock, flags);
}
void ieee80211_process_action(struct ieee80211_device* ieee, struct sk_buff* skb)
{
struct ieee80211_hdr* header = (struct ieee80211_hdr*)skb->data;
u8* act = ieee80211_get_payload(header);
u8 tmp = 0;
// IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA|IEEE80211_DL_BA, skb->data, skb->len);
if (act == NULL)
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "error to get payload of action frame\n");
return;
}
tmp = *act;
act ++;
switch (tmp)
{
case ACT_CAT_BA:
if (*act == ACT_ADDBAREQ)
ieee80211_rx_ADDBAReq(ieee, skb);
else if (*act == ACT_ADDBARSP)
ieee80211_rx_ADDBARsp(ieee, skb);
else if (*act == ACT_DELBA)
ieee80211_rx_DELBA(ieee, skb);
break;
default:
// if (net_ratelimit())
// IEEE80211_DEBUG(IEEE80211_DL_BA, "unknown action frame(%d)\n", tmp);
break;
}
return;
}
inline int
ieee80211_rx_frame_softmac(struct ieee80211_device *ieee, struct sk_buff *skb,
struct ieee80211_rx_stats *rx_stats, u16 type,
u16 stype)
{
struct ieee80211_hdr_3addr *header = (struct ieee80211_hdr_3addr *) skb->data;
u16 errcode;
u8* challenge;
int chlen=0;
int aid;
struct ieee80211_assoc_response_frame *assoc_resp;
// struct ieee80211_info_element *info_element;
bool bSupportNmode = true, bHalfSupportNmode = false; //default support N mode, disable halfNmode
if(!ieee->proto_started)
return 0;
if(ieee->sta_sleep || (ieee->ps != IEEE80211_PS_DISABLED &&
ieee->iw_mode == IW_MODE_INFRA &&
ieee->state == IEEE80211_LINKED))
tasklet_schedule(&ieee->ps_task);
if(WLAN_FC_GET_STYPE(header->frame_ctl) != IEEE80211_STYPE_PROBE_RESP &&
WLAN_FC_GET_STYPE(header->frame_ctl) != IEEE80211_STYPE_BEACON)
ieee->last_rx_ps_time = jiffies;
switch (WLAN_FC_GET_STYPE(header->frame_ctl)) {
case IEEE80211_STYPE_ASSOC_RESP:
case IEEE80211_STYPE_REASSOC_RESP:
IEEE80211_DEBUG_MGMT("received [RE]ASSOCIATION RESPONSE (%d)\n",
WLAN_FC_GET_STYPE(header->frame_ctl));
if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
ieee->state == IEEE80211_ASSOCIATING_AUTHENTICATED &&
ieee->iw_mode == IW_MODE_INFRA){
struct ieee80211_network network_resp;
struct ieee80211_network *network = &network_resp;
if (0 == (errcode=assoc_parse(ieee,skb, &aid))){
ieee->state=IEEE80211_LINKED;
ieee->assoc_id = aid;
ieee->softmac_stats.rx_ass_ok++;
/* station support qos */
/* Let the register setting defaultly with Legacy station */
if(ieee->qos_support) {
assoc_resp = (struct ieee80211_assoc_response_frame*)skb->data;
memset(network, 0, sizeof(*network));
if (ieee80211_parse_info_param(ieee,assoc_resp->info_element,\
rx_stats->len - sizeof(*assoc_resp),\
network,rx_stats)){
return 1;
}
else
{ //filling the PeerHTCap. //maybe not necessary as we can get its info from current_network.
memcpy(ieee->pHTInfo->PeerHTCapBuf, network->bssht.bdHTCapBuf, network->bssht.bdHTCapLen);
memcpy(ieee->pHTInfo->PeerHTInfoBuf, network->bssht.bdHTInfoBuf, network->bssht.bdHTInfoLen);
}
if (ieee->handle_assoc_response != NULL)
ieee->handle_assoc_response(ieee->dev, (struct ieee80211_assoc_response_frame*)header, network);
}
ieee80211_associate_complete(ieee);
} else {
/* aid could not been allocated */
ieee->softmac_stats.rx_ass_err++;
printk(
"Association response status code 0x%x\n",
errcode);
IEEE80211_DEBUG_MGMT(
"Association response status code 0x%x\n",
errcode);
if(ieee->AsocRetryCount < RT_ASOC_RETRY_LIMIT) {
queue_work(ieee->wq, &ieee->associate_procedure_wq);
} else {
ieee80211_associate_abort(ieee);
}
}
}
break;
case IEEE80211_STYPE_ASSOC_REQ:
case IEEE80211_STYPE_REASSOC_REQ:
if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
ieee->iw_mode == IW_MODE_MASTER)
ieee80211_rx_assoc_rq(ieee, skb);
break;
case IEEE80211_STYPE_AUTH:
if (ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE){
if (ieee->state == IEEE80211_ASSOCIATING_AUTHENTICATING &&
ieee->iw_mode == IW_MODE_INFRA){
IEEE80211_DEBUG_MGMT("Received authentication response");
if (0 == (errcode=auth_parse(skb, &challenge, &chlen))){
if(ieee->open_wep || !challenge){
ieee->state = IEEE80211_ASSOCIATING_AUTHENTICATED;
ieee->softmac_stats.rx_auth_rs_ok++;
if(!(ieee->pHTInfo->IOTAction&HT_IOT_ACT_PURE_N_MODE))
{
if (!ieee->GetNmodeSupportBySecCfg(ieee->dev))
{
// WEP or TKIP encryption
if(IsHTHalfNmodeAPs(ieee))
{
bSupportNmode = true;
bHalfSupportNmode = true;
}
else
{
bSupportNmode = false;
bHalfSupportNmode = false;
}
printk("==========>to link with AP using SEC(%d, %d)", bSupportNmode, bHalfSupportNmode);
}
}
/* Dummy wirless mode setting to avoid encryption issue */
if(bSupportNmode) {
//N mode setting
ieee->SetWirelessMode(ieee->dev, \
ieee->current_network.mode);
}else{
//b/g mode setting
/*TODO*/
ieee->SetWirelessMode(ieee->dev, IEEE_G);
}
if (ieee->current_network.mode == IEEE_N_24G && bHalfSupportNmode == true)
{
printk("===============>entern half N mode\n");
ieee->bHalfWirelessN24GMode = true;
}
else
ieee->bHalfWirelessN24GMode = false;
ieee80211_associate_step2(ieee);
}else{
ieee80211_auth_challenge(ieee, challenge, chlen);
}
}else{
ieee->softmac_stats.rx_auth_rs_err++;
IEEE80211_DEBUG_MGMT("Authentication respose status code 0x%x",errcode);
ieee80211_associate_abort(ieee);
}
}else if (ieee->iw_mode == IW_MODE_MASTER){
ieee80211_rx_auth_rq(ieee, skb);
}
}
break;
case IEEE80211_STYPE_PROBE_REQ:
if ((ieee->softmac_features & IEEE_SOFTMAC_PROBERS) &&
((ieee->iw_mode == IW_MODE_ADHOC ||
ieee->iw_mode == IW_MODE_MASTER) &&
ieee->state == IEEE80211_LINKED)){
ieee80211_rx_probe_rq(ieee, skb);
}
break;
case IEEE80211_STYPE_DISASSOC:
case IEEE80211_STYPE_DEAUTH:
/* FIXME for now repeat all the association procedure
* both for disassociation and deauthentication
*/
if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
ieee->state == IEEE80211_LINKED &&
ieee->iw_mode == IW_MODE_INFRA){
ieee->state = IEEE80211_ASSOCIATING;
ieee->softmac_stats.reassoc++;
notify_wx_assoc_event(ieee);
//HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
RemovePeerTS(ieee, header->addr2);
queue_work(ieee->wq, &ieee->associate_procedure_wq);
}
break;
case IEEE80211_STYPE_MANAGE_ACT:
ieee80211_process_action(ieee,skb);
break;
default:
return -1;
break;
}
//dev_kfree_skb_any(skb);
return 0;
}
/* following are for a simpler TX queue management.
* Instead of using netif_[stop/wake]_queue the driver
* will uses these two function (plus a reset one), that
* will internally uses the kernel netif_* and takes
* care of the ieee802.11 fragmentation.
* So the driver receives a fragment per time and might
* call the stop function when it want without take care
* to have enought room to TX an entire packet.
* This might be useful if each fragment need it's own
* descriptor, thus just keep a total free memory > than
* the max fragmentation treshold is not enought.. If the
* ieee802.11 stack passed a TXB struct then you needed
* to keep N free descriptors where
* N = MAX_PACKET_SIZE / MIN_FRAG_TRESHOLD
* In this way you need just one and the 802.11 stack
* will take care of buffering fragments and pass them to
* to the driver later, when it wakes the queue.
*/
void ieee80211_softmac_xmit(struct ieee80211_txb *txb, struct ieee80211_device *ieee)
{
unsigned int queue_index = txb->queue_index;
unsigned long flags;
int i;
cb_desc *tcb_desc = NULL;
spin_lock_irqsave(&ieee->lock,flags);
/* called with 2nd parm 0, no tx mgmt lock required */
ieee80211_sta_wakeup(ieee,0);
/* update the tx status */
ieee->stats.tx_bytes += txb->payload_size;
ieee->stats.tx_packets++;
tcb_desc = (cb_desc *)(txb->fragments[0]->cb + MAX_DEV_ADDR_SIZE);
if(tcb_desc->bMulticast) {
ieee->stats.multicast++;
}
/* if xmit available, just xmit it immediately, else just insert it to the wait queue */
for(i = 0; i < txb->nr_frags; i++) {
#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
if ((skb_queue_len(&ieee->skb_drv_aggQ[queue_index]) != 0) ||
#else
if ((skb_queue_len(&ieee->skb_waitQ[queue_index]) != 0) ||
#endif
(!ieee->check_nic_enough_desc(ieee->dev,queue_index))||\
(ieee->queue_stop)) {
/* insert the skb packet to the wait queue */
/* as for the completion function, it does not need
* to check it any more.
* */
//printk("error:no descriptor left@queue_index %d\n", queue_index);
//ieee80211_stop_queue(ieee);
#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
skb_queue_tail(&ieee->skb_drv_aggQ[queue_index], txb->fragments[i]);
#else
skb_queue_tail(&ieee->skb_waitQ[queue_index], txb->fragments[i]);
#endif
}else{
ieee->softmac_data_hard_start_xmit(
txb->fragments[i],
ieee->dev,ieee->rate);
//ieee->stats.tx_packets++;
//ieee->stats.tx_bytes += txb->fragments[i]->len;
//ieee->dev->trans_start = jiffies;
}
}
ieee80211_txb_free(txb);
//exit:
spin_unlock_irqrestore(&ieee->lock,flags);
}
/* called with ieee->lock acquired */
void ieee80211_resume_tx(struct ieee80211_device *ieee)
{
int i;
for(i = ieee->tx_pending.frag; i < ieee->tx_pending.txb->nr_frags; i++) {
if (ieee->queue_stop){
ieee->tx_pending.frag = i;
return;
}else{
ieee->softmac_data_hard_start_xmit(
ieee->tx_pending.txb->fragments[i],
ieee->dev,ieee->rate);
//(i+1)<ieee->tx_pending.txb->nr_frags);
ieee->stats.tx_packets++;
ieee->dev->trans_start = jiffies;
}
}
ieee80211_txb_free(ieee->tx_pending.txb);
ieee->tx_pending.txb = NULL;
}
void ieee80211_reset_queue(struct ieee80211_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->lock,flags);
init_mgmt_queue(ieee);
if (ieee->tx_pending.txb){
ieee80211_txb_free(ieee->tx_pending.txb);
ieee->tx_pending.txb = NULL;
}
ieee->queue_stop = 0;
spin_unlock_irqrestore(&ieee->lock,flags);
}
void ieee80211_wake_queue(struct ieee80211_device *ieee)
{
unsigned long flags;
struct sk_buff *skb;
struct ieee80211_hdr_3addr *header;
spin_lock_irqsave(&ieee->lock,flags);
if (! ieee->queue_stop) goto exit;
ieee->queue_stop = 0;
if(ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE){
while (!ieee->queue_stop && (skb = dequeue_mgmt(ieee))){
header = (struct ieee80211_hdr_3addr *) skb->data;
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
ieee->softmac_data_hard_start_xmit(skb,ieee->dev,ieee->basic_rate);
//dev_kfree_skb_any(skb);//edit by thomas
}
}
if (!ieee->queue_stop && ieee->tx_pending.txb)
ieee80211_resume_tx(ieee);
if (!ieee->queue_stop && netif_queue_stopped(ieee->dev)){
ieee->softmac_stats.swtxawake++;
netif_wake_queue(ieee->dev);
}
exit :
spin_unlock_irqrestore(&ieee->lock,flags);
}
void ieee80211_stop_queue(struct ieee80211_device *ieee)
{
//unsigned long flags;
//spin_lock_irqsave(&ieee->lock,flags);
if (! netif_queue_stopped(ieee->dev)){
netif_stop_queue(ieee->dev);
ieee->softmac_stats.swtxstop++;
}
ieee->queue_stop = 1;
//spin_unlock_irqrestore(&ieee->lock,flags);
}
inline void ieee80211_randomize_cell(struct ieee80211_device *ieee)
{
get_random_bytes(ieee->current_network.bssid, ETH_ALEN);
/* an IBSS cell address must have the two less significant
* bits of the first byte = 2
*/
ieee->current_network.bssid[0] &= ~0x01;
ieee->current_network.bssid[0] |= 0x02;
}
/* called in user context only */
void ieee80211_start_master_bss(struct ieee80211_device *ieee)
{
ieee->assoc_id = 1;
if (ieee->current_network.ssid_len == 0){
strncpy(ieee->current_network.ssid,
IEEE80211_DEFAULT_TX_ESSID,
IW_ESSID_MAX_SIZE);
ieee->current_network.ssid_len = strlen(IEEE80211_DEFAULT_TX_ESSID);
ieee->ssid_set = 1;
}
memcpy(ieee->current_network.bssid, ieee->dev->dev_addr, ETH_ALEN);
ieee->set_chan(ieee->dev, ieee->current_network.channel);
ieee->state = IEEE80211_LINKED;
ieee->link_change(ieee->dev);
notify_wx_assoc_event(ieee);
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
}
void ieee80211_start_monitor_mode(struct ieee80211_device *ieee)
{
if(ieee->raw_tx){
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
}
}
void ieee80211_start_ibss_wq(struct work_struct *work)
{
struct delayed_work *dwork = container_of(work, struct delayed_work, work);
struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, start_ibss_wq);
/* iwconfig mode ad-hoc will schedule this and return
* on the other hand this will block further iwconfig SET
* operations because of the wx_sem hold.
* Anyway some most set operations set a flag to speed-up
* (abort) this wq (when syncro scanning) before sleeping
* on the semaphore
*/
if(!ieee->proto_started){
printk("==========oh driver down return\n");
return;
}
down(&ieee->wx_sem);
if (ieee->current_network.ssid_len == 0){
strcpy(ieee->current_network.ssid,IEEE80211_DEFAULT_TX_ESSID);
ieee->current_network.ssid_len = strlen(IEEE80211_DEFAULT_TX_ESSID);
ieee->ssid_set = 1;
}
/* check if we have this cell in our network list */
ieee80211_softmac_check_all_nets(ieee);
// if((IS_DOT11D_ENABLE(ieee)) && (ieee->state == IEEE80211_NOLINK))
if (ieee->state == IEEE80211_NOLINK)
ieee->current_network.channel = 6;
/* if not then the state is not linked. Maybe the user swithced to
* ad-hoc mode just after being in monitor mode, or just after
* being very few time in managed mode (so the card have had no
* time to scan all the chans..) or we have just run up the iface
* after setting ad-hoc mode. So we have to give another try..
* Here, in ibss mode, should be safe to do this without extra care
* (in bss mode we had to make sure no-one tryed to associate when
* we had just checked the ieee->state and we was going to start the
* scan) beacause in ibss mode the ieee80211_new_net function, when
* finds a good net, just set the ieee->state to IEEE80211_LINKED,
* so, at worst, we waste a bit of time to initiate an unneeded syncro
* scan, that will stop at the first round because it sees the state
* associated.
*/
if (ieee->state == IEEE80211_NOLINK)
ieee80211_start_scan_syncro(ieee);
/* the network definitively is not here.. create a new cell */
if (ieee->state == IEEE80211_NOLINK){
printk("creating new IBSS cell\n");
if(!ieee->wap_set)
ieee80211_randomize_cell(ieee);
if(ieee->modulation & IEEE80211_CCK_MODULATION){
ieee->current_network.rates_len = 4;
ieee->current_network.rates[0] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_1MB;
ieee->current_network.rates[1] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_2MB;
ieee->current_network.rates[2] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_5MB;
ieee->current_network.rates[3] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_11MB;
}else
ieee->current_network.rates_len = 0;
if(ieee->modulation & IEEE80211_OFDM_MODULATION){
ieee->current_network.rates_ex_len = 8;
ieee->current_network.rates_ex[0] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_6MB;
ieee->current_network.rates_ex[1] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_9MB;
ieee->current_network.rates_ex[2] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_12MB;
ieee->current_network.rates_ex[3] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_18MB;
ieee->current_network.rates_ex[4] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_24MB;
ieee->current_network.rates_ex[5] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_36MB;
ieee->current_network.rates_ex[6] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_48MB;
ieee->current_network.rates_ex[7] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_54MB;
ieee->rate = 108;
}else{
ieee->current_network.rates_ex_len = 0;
ieee->rate = 22;
}
// By default, WMM function will be disabled in IBSS mode
ieee->current_network.QoS_Enable = 0;
ieee->SetWirelessMode(ieee->dev, IEEE_G);
ieee->current_network.atim_window = 0;
ieee->current_network.capability = WLAN_CAPABILITY_IBSS;
if(ieee->short_slot)
ieee->current_network.capability |= WLAN_CAPABILITY_SHORT_SLOT;
}
ieee->state = IEEE80211_LINKED;
ieee->set_chan(ieee->dev, ieee->current_network.channel);
ieee->link_change(ieee->dev);
notify_wx_assoc_event(ieee);
ieee80211_start_send_beacons(ieee);
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
up(&ieee->wx_sem);
}
inline void ieee80211_start_ibss(struct ieee80211_device *ieee)
{
queue_delayed_work(ieee->wq, &ieee->start_ibss_wq, 150);
}
/* this is called only in user context, with wx_sem held */
void ieee80211_start_bss(struct ieee80211_device *ieee)
{
unsigned long flags;
//
// Ref: 802.11d 11.1.3.3
// STA shall not start a BSS unless properly formed Beacon frame including a Country IE.
//
if(IS_DOT11D_ENABLE(ieee) && !IS_COUNTRY_IE_VALID(ieee))
{
if(! ieee->bGlobalDomain)
{
return;
}
}
/* check if we have already found the net we
* are interested in (if any).
* if not (we are disassociated and we are not
* in associating / authenticating phase) start the background scanning.
*/
ieee80211_softmac_check_all_nets(ieee);
/* ensure no-one start an associating process (thus setting
* the ieee->state to ieee80211_ASSOCIATING) while we
* have just cheked it and we are going to enable scan.
* The ieee80211_new_net function is always called with
* lock held (from both ieee80211_softmac_check_all_nets and
* the rx path), so we cannot be in the middle of such function
*/
spin_lock_irqsave(&ieee->lock, flags);
if (ieee->state == IEEE80211_NOLINK){
ieee->actscanning = true;
ieee80211_start_scan(ieee);
}
spin_unlock_irqrestore(&ieee->lock, flags);
}
/* called only in userspace context */
void ieee80211_disassociate(struct ieee80211_device *ieee)
{
netif_carrier_off(ieee->dev);
if (ieee->softmac_features & IEEE_SOFTMAC_TX_QUEUE)
ieee80211_reset_queue(ieee);
if (ieee->data_hard_stop)
ieee->data_hard_stop(ieee->dev);
if(IS_DOT11D_ENABLE(ieee))
Dot11d_Reset(ieee);
ieee->state = IEEE80211_NOLINK;
ieee->is_set_key = false;
ieee->link_change(ieee->dev);
//HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
notify_wx_assoc_event(ieee);
}
void ieee80211_associate_retry_wq(struct work_struct *work)
{
struct delayed_work *dwork = container_of(work, struct delayed_work, work);
struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, associate_retry_wq);
unsigned long flags;
down(&ieee->wx_sem);
if(!ieee->proto_started)
goto exit;
if(ieee->state != IEEE80211_ASSOCIATING_RETRY)
goto exit;
/* until we do not set the state to IEEE80211_NOLINK
* there are no possibility to have someone else trying
* to start an association procdure (we get here with
* ieee->state = IEEE80211_ASSOCIATING).
* When we set the state to IEEE80211_NOLINK it is possible
* that the RX path run an attempt to associate, but
* both ieee80211_softmac_check_all_nets and the
* RX path works with ieee->lock held so there are no
* problems. If we are still disassociated then start a scan.
* the lock here is necessary to ensure no one try to start
* an association procedure when we have just checked the
* state and we are going to start the scan.
*/
ieee->state = IEEE80211_NOLINK;
ieee80211_softmac_check_all_nets(ieee);
spin_lock_irqsave(&ieee->lock, flags);
if(ieee->state == IEEE80211_NOLINK)
ieee80211_start_scan(ieee);
spin_unlock_irqrestore(&ieee->lock, flags);
exit:
up(&ieee->wx_sem);
}
struct sk_buff *ieee80211_get_beacon_(struct ieee80211_device *ieee)
{
u8 broadcast_addr[] = {0xff,0xff,0xff,0xff,0xff,0xff};
struct sk_buff *skb;
struct ieee80211_probe_response *b;
skb = ieee80211_probe_resp(ieee, broadcast_addr);
if (!skb)
return NULL;
b = (struct ieee80211_probe_response *) skb->data;
b->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_BEACON);
return skb;
}
struct sk_buff *ieee80211_get_beacon(struct ieee80211_device *ieee)
{
struct sk_buff *skb;
struct ieee80211_probe_response *b;
skb = ieee80211_get_beacon_(ieee);
if(!skb)
return NULL;
b = (struct ieee80211_probe_response *) skb->data;
b->header.seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
return skb;
}
void ieee80211_softmac_stop_protocol(struct ieee80211_device *ieee)
{
ieee->sync_scan_hurryup = 1;
down(&ieee->wx_sem);
ieee80211_stop_protocol(ieee);
up(&ieee->wx_sem);
}
void ieee80211_stop_protocol(struct ieee80211_device *ieee)
{
if (!ieee->proto_started)
return;
ieee->proto_started = 0;
ieee80211_stop_send_beacons(ieee);
del_timer_sync(&ieee->associate_timer);
cancel_delayed_work(&ieee->associate_retry_wq);
cancel_delayed_work(&ieee->start_ibss_wq);
ieee80211_stop_scan(ieee);
ieee80211_disassociate(ieee);
RemoveAllTS(ieee); //added as we disconnect from the previous BSS, Remove all TS
}
void ieee80211_softmac_start_protocol(struct ieee80211_device *ieee)
{
ieee->sync_scan_hurryup = 0;
down(&ieee->wx_sem);
ieee80211_start_protocol(ieee);
up(&ieee->wx_sem);
}
void ieee80211_start_protocol(struct ieee80211_device *ieee)
{
short ch = 0;
int i = 0;
if (ieee->proto_started)
return;
ieee->proto_started = 1;
if (ieee->current_network.channel == 0){
do{
ch++;
if (ch > MAX_CHANNEL_NUMBER)
return; /* no channel found */
}while(!GET_DOT11D_INFO(ieee)->channel_map[ch]);
ieee->current_network.channel = ch;
}
if (ieee->current_network.beacon_interval == 0)
ieee->current_network.beacon_interval = 100;
// printk("===>%s(), chan:%d\n", __FUNCTION__, ieee->current_network.channel);
// ieee->set_chan(ieee->dev,ieee->current_network.channel);
for(i = 0; i < 17; i++) {
ieee->last_rxseq_num[i] = -1;
ieee->last_rxfrag_num[i] = -1;
ieee->last_packet_time[i] = 0;
}
ieee->init_wmmparam_flag = 0;//reinitialize AC_xx_PARAM registers.
/* if the user set the MAC of the ad-hoc cell and then
* switch to managed mode, shall we make sure that association
* attempts does not fail just because the user provide the essid
* and the nic is still checking for the AP MAC ??
*/
if (ieee->iw_mode == IW_MODE_INFRA)
ieee80211_start_bss(ieee);
else if (ieee->iw_mode == IW_MODE_ADHOC)
ieee80211_start_ibss(ieee);
else if (ieee->iw_mode == IW_MODE_MASTER)
ieee80211_start_master_bss(ieee);
else if(ieee->iw_mode == IW_MODE_MONITOR)
ieee80211_start_monitor_mode(ieee);
}
#define DRV_NAME "Ieee80211"
void ieee80211_softmac_init(struct ieee80211_device *ieee)
{
int i;
memset(&ieee->current_network, 0, sizeof(struct ieee80211_network));
ieee->state = IEEE80211_NOLINK;
ieee->sync_scan_hurryup = 0;
for(i = 0; i < 5; i++) {
ieee->seq_ctrl[i] = 0;
}
ieee->pDot11dInfo = kzalloc(sizeof(RT_DOT11D_INFO), GFP_ATOMIC);
if (!ieee->pDot11dInfo)
IEEE80211_DEBUG(IEEE80211_DL_ERR, "can't alloc memory for DOT11D\n");
//added for AP roaming
ieee->LinkDetectInfo.SlotNum = 2;
ieee->LinkDetectInfo.NumRecvBcnInPeriod=0;
ieee->LinkDetectInfo.NumRecvDataInPeriod=0;
ieee->assoc_id = 0;
ieee->queue_stop = 0;
ieee->scanning = 0;
ieee->softmac_features = 0; //so IEEE2100-like driver are happy
ieee->wap_set = 0;
ieee->ssid_set = 0;
ieee->proto_started = 0;
ieee->basic_rate = IEEE80211_DEFAULT_BASIC_RATE;
ieee->rate = 22;
ieee->ps = IEEE80211_PS_DISABLED;
ieee->sta_sleep = 0;
ieee->Regdot11HTOperationalRateSet[0]= 0xff;//support MCS 0~7
ieee->Regdot11HTOperationalRateSet[1]= 0xff;//support MCS 8~15
ieee->Regdot11HTOperationalRateSet[4]= 0x01;
//added by amy
ieee->actscanning = false;
ieee->beinretry = false;
ieee->is_set_key = false;
init_mgmt_queue(ieee);
ieee->sta_edca_param[0] = 0x0000A403;
ieee->sta_edca_param[1] = 0x0000A427;
ieee->sta_edca_param[2] = 0x005E4342;
ieee->sta_edca_param[3] = 0x002F3262;
ieee->aggregation = true;
ieee->enable_rx_imm_BA = 1;
ieee->tx_pending.txb = NULL;
init_timer(&ieee->associate_timer);
ieee->associate_timer.data = (unsigned long)ieee;
ieee->associate_timer.function = ieee80211_associate_abort_cb;
init_timer(&ieee->beacon_timer);
ieee->beacon_timer.data = (unsigned long) ieee;
ieee->beacon_timer.function = ieee80211_send_beacon_cb;
ieee->wq = create_workqueue(DRV_NAME);
INIT_DELAYED_WORK(&ieee->start_ibss_wq,ieee80211_start_ibss_wq);
INIT_WORK(&ieee->associate_complete_wq, ieee80211_associate_complete_wq);
INIT_WORK(&ieee->associate_procedure_wq, ieee80211_associate_procedure_wq);
INIT_DELAYED_WORK(&ieee->softmac_scan_wq,ieee80211_softmac_scan_wq);
INIT_DELAYED_WORK(&ieee->associate_retry_wq, ieee80211_associate_retry_wq);
INIT_WORK(&ieee->wx_sync_scan_wq,ieee80211_wx_sync_scan_wq);
sema_init(&ieee->wx_sem, 1);
sema_init(&ieee->scan_sem, 1);
spin_lock_init(&ieee->mgmt_tx_lock);
spin_lock_init(&ieee->beacon_lock);
tasklet_init(&ieee->ps_task,
(void(*)(unsigned long)) ieee80211_sta_ps,
(unsigned long)ieee);
}
void ieee80211_softmac_free(struct ieee80211_device *ieee)
{
down(&ieee->wx_sem);
kfree(ieee->pDot11dInfo);
ieee->pDot11dInfo = NULL;
del_timer_sync(&ieee->associate_timer);
cancel_delayed_work(&ieee->associate_retry_wq);
destroy_workqueue(ieee->wq);
up(&ieee->wx_sem);
}
/********************************************************
* Start of WPA code. *
* this is stolen from the ipw2200 driver *
********************************************************/
static int ieee80211_wpa_enable(struct ieee80211_device *ieee, int value)
{
/* This is called when wpa_supplicant loads and closes the driver
* interface. */
printk("%s WPA\n",value ? "enabling" : "disabling");
ieee->wpa_enabled = value;
return 0;
}
void ieee80211_wpa_assoc_frame(struct ieee80211_device *ieee, char *wpa_ie, int wpa_ie_len)
{
/* make sure WPA is enabled */
ieee80211_wpa_enable(ieee, 1);
ieee80211_disassociate(ieee);
}
static int ieee80211_wpa_mlme(struct ieee80211_device *ieee, int command, int reason)
{
int ret = 0;
switch (command) {
case IEEE_MLME_STA_DEAUTH:
// silently ignore
break;
case IEEE_MLME_STA_DISASSOC:
ieee80211_disassociate(ieee);
break;
default:
printk("Unknown MLME request: %d\n", command);
ret = -EOPNOTSUPP;
}
return ret;
}
static int ieee80211_wpa_set_wpa_ie(struct ieee80211_device *ieee,
struct ieee_param *param, int plen)
{
u8 *buf;
if (param->u.wpa_ie.len > MAX_WPA_IE_LEN ||
(param->u.wpa_ie.len && param->u.wpa_ie.data == NULL))
return -EINVAL;
if (param->u.wpa_ie.len) {
buf = kmemdup(param->u.wpa_ie.data, param->u.wpa_ie.len,
GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
kfree(ieee->wpa_ie);
ieee->wpa_ie = buf;
ieee->wpa_ie_len = param->u.wpa_ie.len;
} else {
kfree(ieee->wpa_ie);
ieee->wpa_ie = NULL;
ieee->wpa_ie_len = 0;
}
ieee80211_wpa_assoc_frame(ieee, ieee->wpa_ie, ieee->wpa_ie_len);
return 0;
}
#define AUTH_ALG_OPEN_SYSTEM 0x1
#define AUTH_ALG_SHARED_KEY 0x2
static int ieee80211_wpa_set_auth_algs(struct ieee80211_device *ieee, int value)
{
struct ieee80211_security sec = {
.flags = SEC_AUTH_MODE,
};
int ret = 0;
if (value & AUTH_ALG_SHARED_KEY) {
sec.auth_mode = WLAN_AUTH_SHARED_KEY;
ieee->open_wep = 0;
ieee->auth_mode = 1;
} else if (value & AUTH_ALG_OPEN_SYSTEM){
sec.auth_mode = WLAN_AUTH_OPEN;
ieee->open_wep = 1;
ieee->auth_mode = 0;
}
else if (value & IW_AUTH_ALG_LEAP){
sec.auth_mode = WLAN_AUTH_LEAP;
ieee->open_wep = 1;
ieee->auth_mode = 2;
}
if (ieee->set_security)
ieee->set_security(ieee->dev, &sec);
//else
// ret = -EOPNOTSUPP;
return ret;
}
static int ieee80211_wpa_set_param(struct ieee80211_device *ieee, u8 name, u32 value)
{
int ret=0;
unsigned long flags;
switch (name) {
case IEEE_PARAM_WPA_ENABLED:
ret = ieee80211_wpa_enable(ieee, value);
break;
case IEEE_PARAM_TKIP_COUNTERMEASURES:
ieee->tkip_countermeasures=value;
break;
case IEEE_PARAM_DROP_UNENCRYPTED: {
/* HACK:
*
* wpa_supplicant calls set_wpa_enabled when the driver
* is loaded and unloaded, regardless of if WPA is being
* used. No other calls are made which can be used to
* determine if encryption will be used or not prior to
* association being expected. If encryption is not being
* used, drop_unencrypted is set to false, else true -- we
* can use this to determine if the CAP_PRIVACY_ON bit should
* be set.
*/
struct ieee80211_security sec = {
.flags = SEC_ENABLED,
.enabled = value,
};
ieee->drop_unencrypted = value;
/* We only change SEC_LEVEL for open mode. Others
* are set by ipw_wpa_set_encryption.
*/
if (!value) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_0;
}
else {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_1;
}
if (ieee->set_security)
ieee->set_security(ieee->dev, &sec);
break;
}
case IEEE_PARAM_PRIVACY_INVOKED:
ieee->privacy_invoked=value;
break;
case IEEE_PARAM_AUTH_ALGS:
ret = ieee80211_wpa_set_auth_algs(ieee, value);
break;
case IEEE_PARAM_IEEE_802_1X:
ieee->ieee802_1x=value;
break;
case IEEE_PARAM_WPAX_SELECT:
// added for WPA2 mixed mode
spin_lock_irqsave(&ieee->wpax_suitlist_lock,flags);
ieee->wpax_type_set = 1;
ieee->wpax_type_notify = value;
spin_unlock_irqrestore(&ieee->wpax_suitlist_lock,flags);
break;
default:
printk("Unknown WPA param: %d\n",name);
ret = -EOPNOTSUPP;
}
return ret;
}
/* implementation borrowed from hostap driver */
static int ieee80211_wpa_set_encryption(struct ieee80211_device *ieee,
struct ieee_param *param, int param_len)
{
int ret = 0;
struct ieee80211_crypto_ops *ops;
struct ieee80211_crypt_data **crypt;
struct ieee80211_security sec = {
.flags = 0,
};
param->u.crypt.err = 0;
param->u.crypt.alg[IEEE_CRYPT_ALG_NAME_LEN - 1] = '\0';
if (param_len !=
(int) ((char *) param->u.crypt.key - (char *) param) +
param->u.crypt.key_len) {
printk("Len mismatch %d, %d\n", param_len,
param->u.crypt.key_len);
return -EINVAL;
}
if (param->sta_addr[0] == 0xff && param->sta_addr[1] == 0xff &&
param->sta_addr[2] == 0xff && param->sta_addr[3] == 0xff &&
param->sta_addr[4] == 0xff && param->sta_addr[5] == 0xff) {
if (param->u.crypt.idx >= WEP_KEYS)
return -EINVAL;
crypt = &ieee->crypt[param->u.crypt.idx];
} else {
return -EINVAL;
}
if (strcmp(param->u.crypt.alg, "none") == 0) {
if (crypt) {
sec.enabled = 0;
// FIXME FIXME
//sec.encrypt = 0;
sec.level = SEC_LEVEL_0;
sec.flags |= SEC_ENABLED | SEC_LEVEL;
ieee80211_crypt_delayed_deinit(ieee, crypt);
}
goto done;
}
sec.enabled = 1;
// FIXME FIXME
// sec.encrypt = 1;
sec.flags |= SEC_ENABLED;
/* IPW HW cannot build TKIP MIC, host decryption still needed. */
if (!(ieee->host_encrypt || ieee->host_decrypt) &&
strcmp(param->u.crypt.alg, "TKIP"))
goto skip_host_crypt;
ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
if (ops == NULL && strcmp(param->u.crypt.alg, "WEP") == 0) {
request_module("ieee80211_crypt_wep");
ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
//set WEP40 first, it will be modified according to WEP104 or WEP40 at other place
} else if (ops == NULL && strcmp(param->u.crypt.alg, "TKIP") == 0) {
request_module("ieee80211_crypt_tkip");
ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
} else if (ops == NULL && strcmp(param->u.crypt.alg, "CCMP") == 0) {
request_module("ieee80211_crypt_ccmp");
ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
}
if (ops == NULL) {
printk("unknown crypto alg '%s'\n", param->u.crypt.alg);
param->u.crypt.err = IEEE_CRYPT_ERR_UNKNOWN_ALG;
ret = -EINVAL;
goto done;
}
if (*crypt == NULL || (*crypt)->ops != ops) {
struct ieee80211_crypt_data *new_crypt;
ieee80211_crypt_delayed_deinit(ieee, crypt);
new_crypt = kmalloc(sizeof(*new_crypt), GFP_KERNEL);
if (new_crypt == NULL) {
ret = -ENOMEM;
goto done;
}
memset(new_crypt, 0, sizeof(struct ieee80211_crypt_data));
new_crypt->ops = ops;
if (new_crypt->ops && try_module_get(new_crypt->ops->owner))
new_crypt->priv =
new_crypt->ops->init(param->u.crypt.idx);
if (new_crypt->priv == NULL) {
kfree(new_crypt);
param->u.crypt.err = IEEE_CRYPT_ERR_CRYPT_INIT_FAILED;
ret = -EINVAL;
goto done;
}
*crypt = new_crypt;
}
if (param->u.crypt.key_len > 0 && (*crypt)->ops->set_key &&
(*crypt)->ops->set_key(param->u.crypt.key,
param->u.crypt.key_len, param->u.crypt.seq,
(*crypt)->priv) < 0) {
printk("key setting failed\n");
param->u.crypt.err = IEEE_CRYPT_ERR_KEY_SET_FAILED;
ret = -EINVAL;
goto done;
}
skip_host_crypt:
if (param->u.crypt.set_tx) {
ieee->tx_keyidx = param->u.crypt.idx;
sec.active_key = param->u.crypt.idx;
sec.flags |= SEC_ACTIVE_KEY;
} else
sec.flags &= ~SEC_ACTIVE_KEY;
if (param->u.crypt.alg != NULL) {
memcpy(sec.keys[param->u.crypt.idx],
param->u.crypt.key,
param->u.crypt.key_len);
sec.key_sizes[param->u.crypt.idx] = param->u.crypt.key_len;
sec.flags |= (1 << param->u.crypt.idx);
if (strcmp(param->u.crypt.alg, "WEP") == 0) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_1;
} else if (strcmp(param->u.crypt.alg, "TKIP") == 0) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_2;
} else if (strcmp(param->u.crypt.alg, "CCMP") == 0) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_3;
}
}
done:
if (ieee->set_security)
ieee->set_security(ieee->dev, &sec);
/* Do not reset port if card is in Managed mode since resetting will
* generate new IEEE 802.11 authentication which may end up in looping
* with IEEE 802.1X. If your hardware requires a reset after WEP
* configuration (for example... Prism2), implement the reset_port in
* the callbacks structures used to initialize the 802.11 stack. */
if (ieee->reset_on_keychange &&
ieee->iw_mode != IW_MODE_INFRA &&
ieee->reset_port &&
ieee->reset_port(ieee->dev)) {
printk("reset_port failed\n");
param->u.crypt.err = IEEE_CRYPT_ERR_CARD_CONF_FAILED;
return -EINVAL;
}
return ret;
}
inline struct sk_buff *ieee80211_disassociate_skb(
struct ieee80211_network *beacon,
struct ieee80211_device *ieee,
u8 asRsn)
{
struct sk_buff *skb;
struct ieee80211_disassoc *disass;
skb = dev_alloc_skb(sizeof(struct ieee80211_disassoc));
if (!skb)
return NULL;
disass = (struct ieee80211_disassoc *) skb_put(skb,sizeof(struct ieee80211_disassoc));
disass->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_DISASSOC);
disass->header.duration_id = 0;
memcpy(disass->header.addr1, beacon->bssid, ETH_ALEN);
memcpy(disass->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(disass->header.addr3, beacon->bssid, ETH_ALEN);
disass->reason = asRsn;
return skb;
}
void
SendDisassociation(
struct ieee80211_device *ieee,
u8* asSta,
u8 asRsn
)
{
struct ieee80211_network *beacon = &ieee->current_network;
struct sk_buff *skb;
skb = ieee80211_disassociate_skb(beacon,ieee,asRsn);
if (skb){
softmac_mgmt_xmit(skb, ieee);
//dev_kfree_skb_any(skb);//edit by thomas
}
}
int ieee80211_wpa_supplicant_ioctl(struct ieee80211_device *ieee, struct iw_point *p)
{
struct ieee_param *param;
int ret=0;
down(&ieee->wx_sem);
//IEEE_DEBUG_INFO("wpa_supplicant: len=%d\n", p->length);
if (p->length < sizeof(struct ieee_param) || !p->pointer){
ret = -EINVAL;
goto out;
}
param = kmalloc(p->length, GFP_KERNEL);
if (param == NULL){
ret = -ENOMEM;
goto out;
}
if (copy_from_user(param, p->pointer, p->length)) {
kfree(param);
ret = -EFAULT;
goto out;
}
switch (param->cmd) {
case IEEE_CMD_SET_WPA_PARAM:
ret = ieee80211_wpa_set_param(ieee, param->u.wpa_param.name,
param->u.wpa_param.value);
break;
case IEEE_CMD_SET_WPA_IE:
ret = ieee80211_wpa_set_wpa_ie(ieee, param, p->length);
break;
case IEEE_CMD_SET_ENCRYPTION:
ret = ieee80211_wpa_set_encryption(ieee, param, p->length);
break;
case IEEE_CMD_MLME:
ret = ieee80211_wpa_mlme(ieee, param->u.mlme.command,
param->u.mlme.reason_code);
break;
default:
printk("Unknown WPA supplicant request: %d\n",param->cmd);
ret = -EOPNOTSUPP;
break;
}
if (ret == 0 && copy_to_user(p->pointer, param, p->length))
ret = -EFAULT;
kfree(param);
out:
up(&ieee->wx_sem);
return ret;
}
void notify_wx_assoc_event(struct ieee80211_device *ieee)
{
union iwreq_data wrqu;
wrqu.ap_addr.sa_family = ARPHRD_ETHER;
if (ieee->state == IEEE80211_LINKED)
memcpy(wrqu.ap_addr.sa_data, ieee->current_network.bssid, ETH_ALEN);
else
memset(wrqu.ap_addr.sa_data, 0, ETH_ALEN);
wireless_send_event(ieee->dev, SIOCGIWAP, &wrqu, NULL);
}
EXPORT_SYMBOL(ieee80211_get_beacon);
EXPORT_SYMBOL(ieee80211_wake_queue);
EXPORT_SYMBOL(ieee80211_stop_queue);
EXPORT_SYMBOL(ieee80211_reset_queue);
EXPORT_SYMBOL(ieee80211_softmac_stop_protocol);
EXPORT_SYMBOL(ieee80211_softmac_start_protocol);
EXPORT_SYMBOL(ieee80211_is_shortslot);
EXPORT_SYMBOL(ieee80211_is_54g);
EXPORT_SYMBOL(ieee80211_wpa_supplicant_ioctl);
EXPORT_SYMBOL(ieee80211_ps_tx_ack);
EXPORT_SYMBOL(ieee80211_softmac_xmit);
EXPORT_SYMBOL(ieee80211_stop_send_beacons);
EXPORT_SYMBOL(notify_wx_assoc_event);
EXPORT_SYMBOL(SendDisassociation);
EXPORT_SYMBOL(ieee80211_disassociate);
EXPORT_SYMBOL(ieee80211_start_send_beacons);
EXPORT_SYMBOL(ieee80211_stop_scan);
EXPORT_SYMBOL(ieee80211_send_probe_requests);
EXPORT_SYMBOL(ieee80211_softmac_scan_syncro);
EXPORT_SYMBOL(ieee80211_start_scan_syncro);
//EXPORT_SYMBOL(ieee80211_sta_ps_send_null_frame);
| gpl-2.0 |
chaosagent/DNA_JB_Kernel | arch/powerpc/perf/core-fsl-emb.c | 5068 | 14579 | /*
* Performance event support - Freescale Embedded Performance Monitor
*
* Copyright 2008-2009 Paul Mackerras, IBM Corporation.
* Copyright 2010 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/kernel.h>
#include <linux/sched.h>
#include <linux/perf_event.h>
#include <linux/percpu.h>
#include <linux/hardirq.h>
#include <asm/reg_fsl_emb.h>
#include <asm/pmc.h>
#include <asm/machdep.h>
#include <asm/firmware.h>
#include <asm/ptrace.h>
struct cpu_hw_events {
int n_events;
int disabled;
u8 pmcs_enabled;
struct perf_event *event[MAX_HWEVENTS];
};
static DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events);
static struct fsl_emb_pmu *ppmu;
/* Number of perf_events counting hardware events */
static atomic_t num_events;
/* Used to avoid races in calling reserve/release_pmc_hardware */
static DEFINE_MUTEX(pmc_reserve_mutex);
/*
* If interrupts were soft-disabled when a PMU interrupt occurs, treat
* it as an NMI.
*/
static inline int perf_intr_is_nmi(struct pt_regs *regs)
{
#ifdef __powerpc64__
return !regs->softe;
#else
return 0;
#endif
}
static void perf_event_interrupt(struct pt_regs *regs);
/*
* Read one performance monitor counter (PMC).
*/
static unsigned long read_pmc(int idx)
{
unsigned long val;
switch (idx) {
case 0:
val = mfpmr(PMRN_PMC0);
break;
case 1:
val = mfpmr(PMRN_PMC1);
break;
case 2:
val = mfpmr(PMRN_PMC2);
break;
case 3:
val = mfpmr(PMRN_PMC3);
break;
default:
printk(KERN_ERR "oops trying to read PMC%d\n", idx);
val = 0;
}
return val;
}
/*
* Write one PMC.
*/
static void write_pmc(int idx, unsigned long val)
{
switch (idx) {
case 0:
mtpmr(PMRN_PMC0, val);
break;
case 1:
mtpmr(PMRN_PMC1, val);
break;
case 2:
mtpmr(PMRN_PMC2, val);
break;
case 3:
mtpmr(PMRN_PMC3, val);
break;
default:
printk(KERN_ERR "oops trying to write PMC%d\n", idx);
}
isync();
}
/*
* Write one local control A register
*/
static void write_pmlca(int idx, unsigned long val)
{
switch (idx) {
case 0:
mtpmr(PMRN_PMLCA0, val);
break;
case 1:
mtpmr(PMRN_PMLCA1, val);
break;
case 2:
mtpmr(PMRN_PMLCA2, val);
break;
case 3:
mtpmr(PMRN_PMLCA3, val);
break;
default:
printk(KERN_ERR "oops trying to write PMLCA%d\n", idx);
}
isync();
}
/*
* Write one local control B register
*/
static void write_pmlcb(int idx, unsigned long val)
{
switch (idx) {
case 0:
mtpmr(PMRN_PMLCB0, val);
break;
case 1:
mtpmr(PMRN_PMLCB1, val);
break;
case 2:
mtpmr(PMRN_PMLCB2, val);
break;
case 3:
mtpmr(PMRN_PMLCB3, val);
break;
default:
printk(KERN_ERR "oops trying to write PMLCB%d\n", idx);
}
isync();
}
static void fsl_emb_pmu_read(struct perf_event *event)
{
s64 val, delta, prev;
if (event->hw.state & PERF_HES_STOPPED)
return;
/*
* Performance monitor interrupts come even when interrupts
* are soft-disabled, as long as interrupts are hard-enabled.
* Therefore we treat them like NMIs.
*/
do {
prev = local64_read(&event->hw.prev_count);
barrier();
val = read_pmc(event->hw.idx);
} while (local64_cmpxchg(&event->hw.prev_count, prev, val) != prev);
/* The counters are only 32 bits wide */
delta = (val - prev) & 0xfffffffful;
local64_add(delta, &event->count);
local64_sub(delta, &event->hw.period_left);
}
/*
* Disable all events to prevent PMU interrupts and to allow
* events to be added or removed.
*/
static void fsl_emb_pmu_disable(struct pmu *pmu)
{
struct cpu_hw_events *cpuhw;
unsigned long flags;
local_irq_save(flags);
cpuhw = &__get_cpu_var(cpu_hw_events);
if (!cpuhw->disabled) {
cpuhw->disabled = 1;
/*
* Check if we ever enabled the PMU on this cpu.
*/
if (!cpuhw->pmcs_enabled) {
ppc_enable_pmcs();
cpuhw->pmcs_enabled = 1;
}
if (atomic_read(&num_events)) {
/*
* Set the 'freeze all counters' bit, and disable
* interrupts. The barrier is to make sure the
* mtpmr has been executed and the PMU has frozen
* the events before we return.
*/
mtpmr(PMRN_PMGC0, PMGC0_FAC);
isync();
}
}
local_irq_restore(flags);
}
/*
* Re-enable all events if disable == 0.
* If we were previously disabled and events were added, then
* put the new config on the PMU.
*/
static void fsl_emb_pmu_enable(struct pmu *pmu)
{
struct cpu_hw_events *cpuhw;
unsigned long flags;
local_irq_save(flags);
cpuhw = &__get_cpu_var(cpu_hw_events);
if (!cpuhw->disabled)
goto out;
cpuhw->disabled = 0;
ppc_set_pmu_inuse(cpuhw->n_events != 0);
if (cpuhw->n_events > 0) {
mtpmr(PMRN_PMGC0, PMGC0_PMIE | PMGC0_FCECE);
isync();
}
out:
local_irq_restore(flags);
}
static int collect_events(struct perf_event *group, int max_count,
struct perf_event *ctrs[])
{
int n = 0;
struct perf_event *event;
if (!is_software_event(group)) {
if (n >= max_count)
return -1;
ctrs[n] = group;
n++;
}
list_for_each_entry(event, &group->sibling_list, group_entry) {
if (!is_software_event(event) &&
event->state != PERF_EVENT_STATE_OFF) {
if (n >= max_count)
return -1;
ctrs[n] = event;
n++;
}
}
return n;
}
/* context locked on entry */
static int fsl_emb_pmu_add(struct perf_event *event, int flags)
{
struct cpu_hw_events *cpuhw;
int ret = -EAGAIN;
int num_counters = ppmu->n_counter;
u64 val;
int i;
perf_pmu_disable(event->pmu);
cpuhw = &get_cpu_var(cpu_hw_events);
if (event->hw.config & FSL_EMB_EVENT_RESTRICTED)
num_counters = ppmu->n_restricted;
/*
* Allocate counters from top-down, so that restricted-capable
* counters are kept free as long as possible.
*/
for (i = num_counters - 1; i >= 0; i--) {
if (cpuhw->event[i])
continue;
break;
}
if (i < 0)
goto out;
event->hw.idx = i;
cpuhw->event[i] = event;
++cpuhw->n_events;
val = 0;
if (event->hw.sample_period) {
s64 left = local64_read(&event->hw.period_left);
if (left < 0x80000000L)
val = 0x80000000L - left;
}
local64_set(&event->hw.prev_count, val);
if (!(flags & PERF_EF_START)) {
event->hw.state = PERF_HES_STOPPED | PERF_HES_UPTODATE;
val = 0;
}
write_pmc(i, val);
perf_event_update_userpage(event);
write_pmlcb(i, event->hw.config >> 32);
write_pmlca(i, event->hw.config_base);
ret = 0;
out:
put_cpu_var(cpu_hw_events);
perf_pmu_enable(event->pmu);
return ret;
}
/* context locked on entry */
static void fsl_emb_pmu_del(struct perf_event *event, int flags)
{
struct cpu_hw_events *cpuhw;
int i = event->hw.idx;
perf_pmu_disable(event->pmu);
if (i < 0)
goto out;
fsl_emb_pmu_read(event);
cpuhw = &get_cpu_var(cpu_hw_events);
WARN_ON(event != cpuhw->event[event->hw.idx]);
write_pmlca(i, 0);
write_pmlcb(i, 0);
write_pmc(i, 0);
cpuhw->event[i] = NULL;
event->hw.idx = -1;
/*
* TODO: if at least one restricted event exists, and we
* just freed up a non-restricted-capable counter, and
* there is a restricted-capable counter occupied by
* a non-restricted event, migrate that event to the
* vacated counter.
*/
cpuhw->n_events--;
out:
perf_pmu_enable(event->pmu);
put_cpu_var(cpu_hw_events);
}
static void fsl_emb_pmu_start(struct perf_event *event, int ef_flags)
{
unsigned long flags;
s64 left;
if (event->hw.idx < 0 || !event->hw.sample_period)
return;
if (!(event->hw.state & PERF_HES_STOPPED))
return;
if (ef_flags & PERF_EF_RELOAD)
WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
local_irq_save(flags);
perf_pmu_disable(event->pmu);
event->hw.state = 0;
left = local64_read(&event->hw.period_left);
write_pmc(event->hw.idx, left);
perf_event_update_userpage(event);
perf_pmu_enable(event->pmu);
local_irq_restore(flags);
}
static void fsl_emb_pmu_stop(struct perf_event *event, int ef_flags)
{
unsigned long flags;
if (event->hw.idx < 0 || !event->hw.sample_period)
return;
if (event->hw.state & PERF_HES_STOPPED)
return;
local_irq_save(flags);
perf_pmu_disable(event->pmu);
fsl_emb_pmu_read(event);
event->hw.state |= PERF_HES_STOPPED | PERF_HES_UPTODATE;
write_pmc(event->hw.idx, 0);
perf_event_update_userpage(event);
perf_pmu_enable(event->pmu);
local_irq_restore(flags);
}
/*
* Release the PMU if this is the last perf_event.
*/
static void hw_perf_event_destroy(struct perf_event *event)
{
if (!atomic_add_unless(&num_events, -1, 1)) {
mutex_lock(&pmc_reserve_mutex);
if (atomic_dec_return(&num_events) == 0)
release_pmc_hardware();
mutex_unlock(&pmc_reserve_mutex);
}
}
/*
* Translate a generic cache event_id config to a raw event_id code.
*/
static int hw_perf_cache_event(u64 config, u64 *eventp)
{
unsigned long type, op, result;
int ev;
if (!ppmu->cache_events)
return -EINVAL;
/* unpack config */
type = config & 0xff;
op = (config >> 8) & 0xff;
result = (config >> 16) & 0xff;
if (type >= PERF_COUNT_HW_CACHE_MAX ||
op >= PERF_COUNT_HW_CACHE_OP_MAX ||
result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
return -EINVAL;
ev = (*ppmu->cache_events)[type][op][result];
if (ev == 0)
return -EOPNOTSUPP;
if (ev == -1)
return -EINVAL;
*eventp = ev;
return 0;
}
static int fsl_emb_pmu_event_init(struct perf_event *event)
{
u64 ev;
struct perf_event *events[MAX_HWEVENTS];
int n;
int err;
int num_restricted;
int i;
switch (event->attr.type) {
case PERF_TYPE_HARDWARE:
ev = event->attr.config;
if (ev >= ppmu->n_generic || ppmu->generic_events[ev] == 0)
return -EOPNOTSUPP;
ev = ppmu->generic_events[ev];
break;
case PERF_TYPE_HW_CACHE:
err = hw_perf_cache_event(event->attr.config, &ev);
if (err)
return err;
break;
case PERF_TYPE_RAW:
ev = event->attr.config;
break;
default:
return -ENOENT;
}
event->hw.config = ppmu->xlate_event(ev);
if (!(event->hw.config & FSL_EMB_EVENT_VALID))
return -EINVAL;
/*
* If this is in a group, check if it can go on with all the
* other hardware events in the group. We assume the event
* hasn't been linked into its leader's sibling list at this point.
*/
n = 0;
if (event->group_leader != event) {
n = collect_events(event->group_leader,
ppmu->n_counter - 1, events);
if (n < 0)
return -EINVAL;
}
if (event->hw.config & FSL_EMB_EVENT_RESTRICTED) {
num_restricted = 0;
for (i = 0; i < n; i++) {
if (events[i]->hw.config & FSL_EMB_EVENT_RESTRICTED)
num_restricted++;
}
if (num_restricted >= ppmu->n_restricted)
return -EINVAL;
}
event->hw.idx = -1;
event->hw.config_base = PMLCA_CE | PMLCA_FCM1 |
(u32)((ev << 16) & PMLCA_EVENT_MASK);
if (event->attr.exclude_user)
event->hw.config_base |= PMLCA_FCU;
if (event->attr.exclude_kernel)
event->hw.config_base |= PMLCA_FCS;
if (event->attr.exclude_idle)
return -ENOTSUPP;
event->hw.last_period = event->hw.sample_period;
local64_set(&event->hw.period_left, event->hw.last_period);
/*
* See if we need to reserve the PMU.
* If no events are currently in use, then we have to take a
* mutex to ensure that we don't race with another task doing
* reserve_pmc_hardware or release_pmc_hardware.
*/
err = 0;
if (!atomic_inc_not_zero(&num_events)) {
mutex_lock(&pmc_reserve_mutex);
if (atomic_read(&num_events) == 0 &&
reserve_pmc_hardware(perf_event_interrupt))
err = -EBUSY;
else
atomic_inc(&num_events);
mutex_unlock(&pmc_reserve_mutex);
mtpmr(PMRN_PMGC0, PMGC0_FAC);
isync();
}
event->destroy = hw_perf_event_destroy;
return err;
}
static struct pmu fsl_emb_pmu = {
.pmu_enable = fsl_emb_pmu_enable,
.pmu_disable = fsl_emb_pmu_disable,
.event_init = fsl_emb_pmu_event_init,
.add = fsl_emb_pmu_add,
.del = fsl_emb_pmu_del,
.start = fsl_emb_pmu_start,
.stop = fsl_emb_pmu_stop,
.read = fsl_emb_pmu_read,
};
/*
* A counter has overflowed; update its count and record
* things if requested. Note that interrupts are hard-disabled
* here so there is no possibility of being interrupted.
*/
static void record_and_restart(struct perf_event *event, unsigned long val,
struct pt_regs *regs)
{
u64 period = event->hw.sample_period;
s64 prev, delta, left;
int record = 0;
if (event->hw.state & PERF_HES_STOPPED) {
write_pmc(event->hw.idx, 0);
return;
}
/* we don't have to worry about interrupts here */
prev = local64_read(&event->hw.prev_count);
delta = (val - prev) & 0xfffffffful;
local64_add(delta, &event->count);
/*
* See if the total period for this event has expired,
* and update for the next period.
*/
val = 0;
left = local64_read(&event->hw.period_left) - delta;
if (period) {
if (left <= 0) {
left += period;
if (left <= 0)
left = period;
record = 1;
event->hw.last_period = event->hw.sample_period;
}
if (left < 0x80000000LL)
val = 0x80000000LL - left;
}
write_pmc(event->hw.idx, val);
local64_set(&event->hw.prev_count, val);
local64_set(&event->hw.period_left, left);
perf_event_update_userpage(event);
/*
* Finally record data if requested.
*/
if (record) {
struct perf_sample_data data;
perf_sample_data_init(&data, 0);
data.period = event->hw.last_period;
if (perf_event_overflow(event, &data, regs))
fsl_emb_pmu_stop(event, 0);
}
}
static void perf_event_interrupt(struct pt_regs *regs)
{
int i;
struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events);
struct perf_event *event;
unsigned long val;
int found = 0;
int nmi;
nmi = perf_intr_is_nmi(regs);
if (nmi)
nmi_enter();
else
irq_enter();
for (i = 0; i < ppmu->n_counter; ++i) {
event = cpuhw->event[i];
val = read_pmc(i);
if ((int)val < 0) {
if (event) {
/* event has overflowed */
found = 1;
record_and_restart(event, val, regs);
} else {
/*
* Disabled counter is negative,
* reset it just in case.
*/
write_pmc(i, 0);
}
}
}
/* PMM will keep counters frozen until we return from the interrupt. */
mtmsr(mfmsr() | MSR_PMM);
mtpmr(PMRN_PMGC0, PMGC0_PMIE | PMGC0_FCECE);
isync();
if (nmi)
nmi_exit();
else
irq_exit();
}
void hw_perf_event_setup(int cpu)
{
struct cpu_hw_events *cpuhw = &per_cpu(cpu_hw_events, cpu);
memset(cpuhw, 0, sizeof(*cpuhw));
}
int register_fsl_emb_pmu(struct fsl_emb_pmu *pmu)
{
if (ppmu)
return -EBUSY; /* something's already registered */
ppmu = pmu;
pr_info("%s performance monitor hardware support registered\n",
pmu->name);
perf_pmu_register(&fsl_emb_pmu, "cpu", PERF_TYPE_RAW);
return 0;
}
| gpl-2.0 |
EuphoriaOS/android_kernel_samsung_exynos5410 | drivers/net/wireless/ipw2x00/libipw_module.c | 7884 | 8960 | /*******************************************************************************
Copyright(c) 2004-2005 Intel Corporation. All rights reserved.
Portions of this file are based on the WEP enablement code provided by the
Host AP project hostap-drivers v0.1.3
Copyright (c) 2001-2002, SSH Communications Security Corp and Jouni Malinen
<j@w1.fi>
Copyright (c) 2002-2003, Jouni Malinen <j@w1.fi>
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., 59
Temple Place - Suite 330, Boston, MA 02111-1307, USA.
The full GNU General Public License is included in this distribution in the
file called LICENSE.
Contact Information:
Intel Linux Wireless <ilw@linux.intel.com>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#include <linux/compiler.h>
#include <linux/errno.h>
#include <linux/if_arp.h>
#include <linux/in6.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/proc_fs.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/tcp.h>
#include <linux/types.h>
#include <linux/wireless.h>
#include <linux/etherdevice.h>
#include <asm/uaccess.h>
#include <net/net_namespace.h>
#include <net/arp.h>
#include "libipw.h"
#define DRV_DESCRIPTION "802.11 data/management/control stack"
#define DRV_NAME "libipw"
#define DRV_PROCNAME "ieee80211"
#define DRV_VERSION LIBIPW_VERSION
#define DRV_COPYRIGHT "Copyright (C) 2004-2005 Intel Corporation <jketreno@linux.intel.com>"
MODULE_VERSION(DRV_VERSION);
MODULE_DESCRIPTION(DRV_DESCRIPTION);
MODULE_AUTHOR(DRV_COPYRIGHT);
MODULE_LICENSE("GPL");
static struct cfg80211_ops libipw_config_ops = { };
static void *libipw_wiphy_privid = &libipw_wiphy_privid;
static int libipw_networks_allocate(struct libipw_device *ieee)
{
int i, j;
for (i = 0; i < MAX_NETWORK_COUNT; i++) {
ieee->networks[i] = kzalloc(sizeof(struct libipw_network),
GFP_KERNEL);
if (!ieee->networks[i]) {
LIBIPW_ERROR("Out of memory allocating beacons\n");
for (j = 0; j < i; j++)
kfree(ieee->networks[j]);
return -ENOMEM;
}
}
return 0;
}
void libipw_network_reset(struct libipw_network *network)
{
if (!network)
return;
if (network->ibss_dfs) {
kfree(network->ibss_dfs);
network->ibss_dfs = NULL;
}
}
static inline void libipw_networks_free(struct libipw_device *ieee)
{
int i;
for (i = 0; i < MAX_NETWORK_COUNT; i++) {
if (ieee->networks[i]->ibss_dfs)
kfree(ieee->networks[i]->ibss_dfs);
kfree(ieee->networks[i]);
}
}
void libipw_networks_age(struct libipw_device *ieee,
unsigned long age_secs)
{
struct libipw_network *network = NULL;
unsigned long flags;
unsigned long age_jiffies = msecs_to_jiffies(age_secs * MSEC_PER_SEC);
spin_lock_irqsave(&ieee->lock, flags);
list_for_each_entry(network, &ieee->network_list, list) {
network->last_scanned -= age_jiffies;
}
spin_unlock_irqrestore(&ieee->lock, flags);
}
EXPORT_SYMBOL(libipw_networks_age);
static void libipw_networks_initialize(struct libipw_device *ieee)
{
int i;
INIT_LIST_HEAD(&ieee->network_free_list);
INIT_LIST_HEAD(&ieee->network_list);
for (i = 0; i < MAX_NETWORK_COUNT; i++)
list_add_tail(&ieee->networks[i]->list,
&ieee->network_free_list);
}
int libipw_change_mtu(struct net_device *dev, int new_mtu)
{
if ((new_mtu < 68) || (new_mtu > LIBIPW_DATA_LEN))
return -EINVAL;
dev->mtu = new_mtu;
return 0;
}
EXPORT_SYMBOL(libipw_change_mtu);
struct net_device *alloc_libipw(int sizeof_priv, int monitor)
{
struct libipw_device *ieee;
struct net_device *dev;
int err;
LIBIPW_DEBUG_INFO("Initializing...\n");
dev = alloc_etherdev(sizeof(struct libipw_device) + sizeof_priv);
if (!dev)
goto failed;
ieee = netdev_priv(dev);
ieee->dev = dev;
if (!monitor) {
ieee->wdev.wiphy = wiphy_new(&libipw_config_ops, 0);
if (!ieee->wdev.wiphy) {
LIBIPW_ERROR("Unable to allocate wiphy.\n");
goto failed_free_netdev;
}
ieee->dev->ieee80211_ptr = &ieee->wdev;
ieee->wdev.iftype = NL80211_IFTYPE_STATION;
/* Fill-out wiphy structure bits we know... Not enough info
here to call set_wiphy_dev or set MAC address or channel info
-- have to do that in ->ndo_init... */
ieee->wdev.wiphy->privid = libipw_wiphy_privid;
ieee->wdev.wiphy->max_scan_ssids = 1;
ieee->wdev.wiphy->max_scan_ie_len = 0;
ieee->wdev.wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION)
| BIT(NL80211_IFTYPE_ADHOC);
}
err = libipw_networks_allocate(ieee);
if (err) {
LIBIPW_ERROR("Unable to allocate beacon storage: %d\n", err);
goto failed_free_wiphy;
}
libipw_networks_initialize(ieee);
/* Default fragmentation threshold is maximum payload size */
ieee->fts = DEFAULT_FTS;
ieee->rts = DEFAULT_FTS;
ieee->scan_age = DEFAULT_MAX_SCAN_AGE;
ieee->open_wep = 1;
/* Default to enabling full open WEP with host based encrypt/decrypt */
ieee->host_encrypt = 1;
ieee->host_decrypt = 1;
ieee->host_mc_decrypt = 1;
/* Host fragmentation in Open mode. Default is enabled.
* Note: host fragmentation is always enabled if host encryption
* is enabled. For cards can do hardware encryption, they must do
* hardware fragmentation as well. So we don't need a variable
* like host_enc_frag. */
ieee->host_open_frag = 1;
ieee->ieee802_1x = 1; /* Default to supporting 802.1x */
spin_lock_init(&ieee->lock);
lib80211_crypt_info_init(&ieee->crypt_info, dev->name, &ieee->lock);
ieee->wpa_enabled = 0;
ieee->drop_unencrypted = 0;
ieee->privacy_invoked = 0;
return dev;
failed_free_wiphy:
if (!monitor)
wiphy_free(ieee->wdev.wiphy);
failed_free_netdev:
free_netdev(dev);
failed:
return NULL;
}
EXPORT_SYMBOL(alloc_libipw);
void free_libipw(struct net_device *dev, int monitor)
{
struct libipw_device *ieee = netdev_priv(dev);
lib80211_crypt_info_free(&ieee->crypt_info);
libipw_networks_free(ieee);
/* free cfg80211 resources */
if (!monitor)
wiphy_free(ieee->wdev.wiphy);
free_netdev(dev);
}
EXPORT_SYMBOL(free_libipw);
#ifdef CONFIG_LIBIPW_DEBUG
static int debug = 0;
u32 libipw_debug_level = 0;
EXPORT_SYMBOL_GPL(libipw_debug_level);
static struct proc_dir_entry *libipw_proc = NULL;
static int debug_level_proc_show(struct seq_file *m, void *v)
{
seq_printf(m, "0x%08X\n", libipw_debug_level);
return 0;
}
static int debug_level_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, debug_level_proc_show, NULL);
}
static ssize_t debug_level_proc_write(struct file *file,
const char __user *buffer, size_t count, loff_t *pos)
{
char buf[] = "0x00000000\n";
size_t len = min(sizeof(buf) - 1, count);
unsigned long val;
if (copy_from_user(buf, buffer, len))
return count;
buf[len] = 0;
if (sscanf(buf, "%li", &val) != 1)
printk(KERN_INFO DRV_NAME
": %s is not in hex or decimal form.\n", buf);
else
libipw_debug_level = val;
return strnlen(buf, len);
}
static const struct file_operations debug_level_proc_fops = {
.owner = THIS_MODULE,
.open = debug_level_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = debug_level_proc_write,
};
#endif /* CONFIG_LIBIPW_DEBUG */
static int __init libipw_init(void)
{
#ifdef CONFIG_LIBIPW_DEBUG
struct proc_dir_entry *e;
libipw_debug_level = debug;
libipw_proc = proc_mkdir(DRV_PROCNAME, init_net.proc_net);
if (libipw_proc == NULL) {
LIBIPW_ERROR("Unable to create " DRV_PROCNAME
" proc directory\n");
return -EIO;
}
e = proc_create("debug_level", S_IRUGO | S_IWUSR, libipw_proc,
&debug_level_proc_fops);
if (!e) {
remove_proc_entry(DRV_PROCNAME, init_net.proc_net);
libipw_proc = NULL;
return -EIO;
}
#endif /* CONFIG_LIBIPW_DEBUG */
printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION ", " DRV_VERSION "\n");
printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
return 0;
}
static void __exit libipw_exit(void)
{
#ifdef CONFIG_LIBIPW_DEBUG
if (libipw_proc) {
remove_proc_entry("debug_level", libipw_proc);
remove_proc_entry(DRV_PROCNAME, init_net.proc_net);
libipw_proc = NULL;
}
#endif /* CONFIG_LIBIPW_DEBUG */
}
#ifdef CONFIG_LIBIPW_DEBUG
#include <linux/moduleparam.h>
module_param(debug, int, 0444);
MODULE_PARM_DESC(debug, "debug output mask");
#endif /* CONFIG_LIBIPW_DEBUG */
module_exit(libipw_exit);
module_init(libipw_init);
| gpl-2.0 |
CTCaer/CTCaer-ICS-Xperia2011 | arch/mips/sgi-ip27/ip27-xtalk.c | 9164 | 3139 | /*
* Copyright (C) 1999, 2000 Ralf Baechle (ralf@gnu.org)
* Copyright (C) 1999, 2000 Silcon Graphics, Inc.
* Copyright (C) 2004 Christoph Hellwig.
* Released under GPL v2.
*
* Generic XTALK initialization code
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/smp.h>
#include <asm/sn/types.h>
#include <asm/sn/klconfig.h>
#include <asm/sn/hub.h>
#include <asm/pci/bridge.h>
#include <asm/xtalk/xtalk.h>
#define XBOW_WIDGET_PART_NUM 0x0
#define XXBOW_WIDGET_PART_NUM 0xd000 /* Xbow in Xbridge */
#define BASE_XBOW_PORT 8 /* Lowest external port */
extern int bridge_probe(nasid_t nasid, int widget, int masterwid);
static int __cpuinit probe_one_port(nasid_t nasid, int widget, int masterwid)
{
widgetreg_t widget_id;
xwidget_part_num_t partnum;
widget_id = *(volatile widgetreg_t *)
(RAW_NODE_SWIN_BASE(nasid, widget) + WIDGET_ID);
partnum = XWIDGET_PART_NUM(widget_id);
printk(KERN_INFO "Cpu %d, Nasid 0x%x, widget 0x%x (partnum 0x%x) is ",
smp_processor_id(), nasid, widget, partnum);
switch (partnum) {
case BRIDGE_WIDGET_PART_NUM:
case XBRIDGE_WIDGET_PART_NUM:
bridge_probe(nasid, widget, masterwid);
break;
default:
break;
}
return 0;
}
static int __cpuinit xbow_probe(nasid_t nasid)
{
lboard_t *brd;
klxbow_t *xbow_p;
unsigned masterwid, i;
printk("is xbow\n");
/*
* found xbow, so may have multiple bridges
* need to probe xbow
*/
brd = find_lboard((lboard_t *)KL_CONFIG_INFO(nasid), KLTYPE_MIDPLANE8);
if (!brd)
return -ENODEV;
xbow_p = (klxbow_t *)find_component(brd, NULL, KLSTRUCT_XBOW);
if (!xbow_p)
return -ENODEV;
/*
* Okay, here's a xbow. Lets arbitrate and find
* out if we should initialize it. Set enabled
* hub connected at highest or lowest widget as
* master.
*/
#ifdef WIDGET_A
i = HUB_WIDGET_ID_MAX + 1;
do {
i--;
} while ((!XBOW_PORT_TYPE_HUB(xbow_p, i)) ||
(!XBOW_PORT_IS_ENABLED(xbow_p, i)));
#else
i = HUB_WIDGET_ID_MIN - 1;
do {
i++;
} while ((!XBOW_PORT_TYPE_HUB(xbow_p, i)) ||
(!XBOW_PORT_IS_ENABLED(xbow_p, i)));
#endif
masterwid = i;
if (nasid != XBOW_PORT_NASID(xbow_p, i))
return 1;
for (i = HUB_WIDGET_ID_MIN; i <= HUB_WIDGET_ID_MAX; i++) {
if (XBOW_PORT_IS_ENABLED(xbow_p, i) &&
XBOW_PORT_TYPE_IO(xbow_p, i))
probe_one_port(nasid, i, masterwid);
}
return 0;
}
void __cpuinit xtalk_probe_node(cnodeid_t nid)
{
volatile u64 hubreg;
nasid_t nasid;
xwidget_part_num_t partnum;
widgetreg_t widget_id;
nasid = COMPACT_TO_NASID_NODEID(nid);
hubreg = REMOTE_HUB_L(nasid, IIO_LLP_CSR);
/* check whether the link is up */
if (!(hubreg & IIO_LLP_CSR_IS_UP))
return;
widget_id = *(volatile widgetreg_t *)
(RAW_NODE_SWIN_BASE(nasid, 0x0) + WIDGET_ID);
partnum = XWIDGET_PART_NUM(widget_id);
printk(KERN_INFO "Cpu %d, Nasid 0x%x: partnum 0x%x is ",
smp_processor_id(), nasid, partnum);
switch (partnum) {
case BRIDGE_WIDGET_PART_NUM:
bridge_probe(nasid, 0x8, 0xa);
break;
case XBOW_WIDGET_PART_NUM:
case XXBOW_WIDGET_PART_NUM:
xbow_probe(nasid);
break;
default:
printk(" unknown widget??\n");
break;
}
}
| gpl-2.0 |
n3ocort3x/m7_aosp_GE_merge | arch/mips/sgi-ip27/ip27-xtalk.c | 9164 | 3139 | /*
* Copyright (C) 1999, 2000 Ralf Baechle (ralf@gnu.org)
* Copyright (C) 1999, 2000 Silcon Graphics, Inc.
* Copyright (C) 2004 Christoph Hellwig.
* Released under GPL v2.
*
* Generic XTALK initialization code
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/smp.h>
#include <asm/sn/types.h>
#include <asm/sn/klconfig.h>
#include <asm/sn/hub.h>
#include <asm/pci/bridge.h>
#include <asm/xtalk/xtalk.h>
#define XBOW_WIDGET_PART_NUM 0x0
#define XXBOW_WIDGET_PART_NUM 0xd000 /* Xbow in Xbridge */
#define BASE_XBOW_PORT 8 /* Lowest external port */
extern int bridge_probe(nasid_t nasid, int widget, int masterwid);
static int __cpuinit probe_one_port(nasid_t nasid, int widget, int masterwid)
{
widgetreg_t widget_id;
xwidget_part_num_t partnum;
widget_id = *(volatile widgetreg_t *)
(RAW_NODE_SWIN_BASE(nasid, widget) + WIDGET_ID);
partnum = XWIDGET_PART_NUM(widget_id);
printk(KERN_INFO "Cpu %d, Nasid 0x%x, widget 0x%x (partnum 0x%x) is ",
smp_processor_id(), nasid, widget, partnum);
switch (partnum) {
case BRIDGE_WIDGET_PART_NUM:
case XBRIDGE_WIDGET_PART_NUM:
bridge_probe(nasid, widget, masterwid);
break;
default:
break;
}
return 0;
}
static int __cpuinit xbow_probe(nasid_t nasid)
{
lboard_t *brd;
klxbow_t *xbow_p;
unsigned masterwid, i;
printk("is xbow\n");
/*
* found xbow, so may have multiple bridges
* need to probe xbow
*/
brd = find_lboard((lboard_t *)KL_CONFIG_INFO(nasid), KLTYPE_MIDPLANE8);
if (!brd)
return -ENODEV;
xbow_p = (klxbow_t *)find_component(brd, NULL, KLSTRUCT_XBOW);
if (!xbow_p)
return -ENODEV;
/*
* Okay, here's a xbow. Lets arbitrate and find
* out if we should initialize it. Set enabled
* hub connected at highest or lowest widget as
* master.
*/
#ifdef WIDGET_A
i = HUB_WIDGET_ID_MAX + 1;
do {
i--;
} while ((!XBOW_PORT_TYPE_HUB(xbow_p, i)) ||
(!XBOW_PORT_IS_ENABLED(xbow_p, i)));
#else
i = HUB_WIDGET_ID_MIN - 1;
do {
i++;
} while ((!XBOW_PORT_TYPE_HUB(xbow_p, i)) ||
(!XBOW_PORT_IS_ENABLED(xbow_p, i)));
#endif
masterwid = i;
if (nasid != XBOW_PORT_NASID(xbow_p, i))
return 1;
for (i = HUB_WIDGET_ID_MIN; i <= HUB_WIDGET_ID_MAX; i++) {
if (XBOW_PORT_IS_ENABLED(xbow_p, i) &&
XBOW_PORT_TYPE_IO(xbow_p, i))
probe_one_port(nasid, i, masterwid);
}
return 0;
}
void __cpuinit xtalk_probe_node(cnodeid_t nid)
{
volatile u64 hubreg;
nasid_t nasid;
xwidget_part_num_t partnum;
widgetreg_t widget_id;
nasid = COMPACT_TO_NASID_NODEID(nid);
hubreg = REMOTE_HUB_L(nasid, IIO_LLP_CSR);
/* check whether the link is up */
if (!(hubreg & IIO_LLP_CSR_IS_UP))
return;
widget_id = *(volatile widgetreg_t *)
(RAW_NODE_SWIN_BASE(nasid, 0x0) + WIDGET_ID);
partnum = XWIDGET_PART_NUM(widget_id);
printk(KERN_INFO "Cpu %d, Nasid 0x%x: partnum 0x%x is ",
smp_processor_id(), nasid, partnum);
switch (partnum) {
case BRIDGE_WIDGET_PART_NUM:
bridge_probe(nasid, 0x8, 0xa);
break;
case XBOW_WIDGET_PART_NUM:
case XXBOW_WIDGET_PART_NUM:
xbow_probe(nasid);
break;
default:
printk(" unknown widget??\n");
break;
}
}
| gpl-2.0 |
assusdan/android_kernel_hs_zerasrs | drivers/pcmcia/rsrc_iodyn.c | 10444 | 3840 | /*
* rsrc_iodyn.c -- Resource management routines for MEM-static sockets.
*
* 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 initial developer of the original code is David A. Hinds
* <dahinds@users.sourceforge.net>. Portions created by David A. Hinds
* are Copyright (C) 1999 David A. Hinds. All Rights Reserved.
*
* (C) 1999 David A. Hinds
*/
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <pcmcia/ss.h>
#include <pcmcia/cistpl.h>
#include "cs_internal.h"
struct pcmcia_align_data {
unsigned long mask;
unsigned long offset;
};
static resource_size_t pcmcia_align(void *align_data,
const struct resource *res,
resource_size_t size, resource_size_t align)
{
struct pcmcia_align_data *data = align_data;
resource_size_t start;
start = (res->start & ~data->mask) + data->offset;
if (start < res->start)
start += data->mask + 1;
#ifdef CONFIG_X86
if (res->flags & IORESOURCE_IO) {
if (start & 0x300)
start = (start + 0x3ff) & ~0x3ff;
}
#endif
#ifdef CONFIG_M68K
if (res->flags & IORESOURCE_IO) {
if ((res->start + size - 1) >= 1024)
start = res->end;
}
#endif
return start;
}
static struct resource *__iodyn_find_io_region(struct pcmcia_socket *s,
unsigned long base, int num,
unsigned long align)
{
struct resource *res = pcmcia_make_resource(0, num, IORESOURCE_IO,
dev_name(&s->dev));
struct pcmcia_align_data data;
unsigned long min = base;
int ret;
data.mask = align - 1;
data.offset = base & data.mask;
#ifdef CONFIG_PCI
if (s->cb_dev) {
ret = pci_bus_alloc_resource(s->cb_dev->bus, res, num, 1,
min, 0, pcmcia_align, &data);
} else
#endif
ret = allocate_resource(&ioport_resource, res, num, min, ~0UL,
1, pcmcia_align, &data);
if (ret != 0) {
kfree(res);
res = NULL;
}
return res;
}
static int iodyn_find_io(struct pcmcia_socket *s, unsigned int attr,
unsigned int *base, unsigned int num,
unsigned int align, struct resource **parent)
{
int i, ret = 0;
/* Check for an already-allocated window that must conflict with
* what was asked for. It is a hack because it does not catch all
* potential conflicts, just the most obvious ones.
*/
for (i = 0; i < MAX_IO_WIN; i++) {
if (!s->io[i].res)
continue;
if (!*base)
continue;
if ((s->io[i].res->start & (align-1)) == *base)
return -EBUSY;
}
for (i = 0; i < MAX_IO_WIN; i++) {
struct resource *res = s->io[i].res;
unsigned int try;
if (res && (res->flags & IORESOURCE_BITS) !=
(attr & IORESOURCE_BITS))
continue;
if (!res) {
if (align == 0)
align = 0x10000;
res = s->io[i].res = __iodyn_find_io_region(s, *base,
num, align);
if (!res)
return -EINVAL;
*base = res->start;
s->io[i].res->flags =
((res->flags & ~IORESOURCE_BITS) |
(attr & IORESOURCE_BITS));
s->io[i].InUse = num;
*parent = res;
return 0;
}
/* Try to extend top of window */
try = res->end + 1;
if ((*base == 0) || (*base == try)) {
if (adjust_resource(s->io[i].res, res->start,
resource_size(res) + num))
continue;
*base = try;
s->io[i].InUse += num;
*parent = res;
return 0;
}
/* Try to extend bottom of window */
try = res->start - num;
if ((*base == 0) || (*base == try)) {
if (adjust_resource(s->io[i].res,
res->start - num,
resource_size(res) + num))
continue;
*base = try;
s->io[i].InUse += num;
*parent = res;
return 0;
}
}
return -EINVAL;
}
struct pccard_resource_ops pccard_iodyn_ops = {
.validate_mem = NULL,
.find_io = iodyn_find_io,
.find_mem = NULL,
.init = static_init,
.exit = NULL,
};
EXPORT_SYMBOL(pccard_iodyn_ops);
| gpl-2.0 |
nc543/linux-release | net/ipv6/netfilter/ip6t_ipv6header.c | 11724 | 3553 | /* ipv6header match - matches IPv6 packets based
on whether they contain certain headers */
/* Original idea: Brad Chapman
* Rewritten by: Andras Kis-Szabo <kisza@sch.bme.hu> */
/* (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.
*/
#include <linux/module.h>
#include <linux/skbuff.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_ipv6header.h>
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Xtables: IPv6 header types match");
MODULE_AUTHOR("Andras Kis-Szabo <kisza@sch.bme.hu>");
static bool
ipv6header_mt6(const struct sk_buff *skb, struct xt_action_param *par)
{
const struct ip6t_ipv6header_info *info = par->matchinfo;
unsigned int temp;
int len;
u8 nexthdr;
unsigned int ptr;
/* Make sure this isn't an evil packet */
/* type of the 1st exthdr */
nexthdr = ipv6_hdr(skb)->nexthdr;
/* pointer to the 1st exthdr */
ptr = sizeof(struct ipv6hdr);
/* available length */
len = skb->len - ptr;
temp = 0;
while (ip6t_ext_hdr(nexthdr)) {
const struct ipv6_opt_hdr *hp;
struct ipv6_opt_hdr _hdr;
int hdrlen;
/* No more exthdr -> evaluate */
if (nexthdr == NEXTHDR_NONE) {
temp |= MASK_NONE;
break;
}
/* Is there enough space for the next ext header? */
if (len < (int)sizeof(struct ipv6_opt_hdr))
return false;
/* ESP -> evaluate */
if (nexthdr == NEXTHDR_ESP) {
temp |= MASK_ESP;
break;
}
hp = skb_header_pointer(skb, ptr, sizeof(_hdr), &_hdr);
BUG_ON(hp == NULL);
/* Calculate the header length */
if (nexthdr == NEXTHDR_FRAGMENT)
hdrlen = 8;
else if (nexthdr == NEXTHDR_AUTH)
hdrlen = (hp->hdrlen + 2) << 2;
else
hdrlen = ipv6_optlen(hp);
/* set the flag */
switch (nexthdr) {
case NEXTHDR_HOP:
temp |= MASK_HOPOPTS;
break;
case NEXTHDR_ROUTING:
temp |= MASK_ROUTING;
break;
case NEXTHDR_FRAGMENT:
temp |= MASK_FRAGMENT;
break;
case NEXTHDR_AUTH:
temp |= MASK_AH;
break;
case NEXTHDR_DEST:
temp |= MASK_DSTOPTS;
break;
default:
return false;
break;
}
nexthdr = hp->nexthdr;
len -= hdrlen;
ptr += hdrlen;
if (ptr > skb->len)
break;
}
if (nexthdr != NEXTHDR_NONE && nexthdr != NEXTHDR_ESP)
temp |= MASK_PROTO;
if (info->modeflag)
return !((temp ^ info->matchflags ^ info->invflags)
& info->matchflags);
else {
if (info->invflags)
return temp != info->matchflags;
else
return temp == info->matchflags;
}
}
static int ipv6header_mt6_check(const struct xt_mtchk_param *par)
{
const struct ip6t_ipv6header_info *info = par->matchinfo;
/* invflags is 0 or 0xff in hard mode */
if ((!info->modeflag) && info->invflags != 0x00 &&
info->invflags != 0xFF)
return -EINVAL;
return 0;
}
static struct xt_match ipv6header_mt6_reg __read_mostly = {
.name = "ipv6header",
.family = NFPROTO_IPV6,
.match = ipv6header_mt6,
.matchsize = sizeof(struct ip6t_ipv6header_info),
.checkentry = ipv6header_mt6_check,
.destroy = NULL,
.me = THIS_MODULE,
};
static int __init ipv6header_mt6_init(void)
{
return xt_register_match(&ipv6header_mt6_reg);
}
static void __exit ipv6header_mt6_exit(void)
{
xt_unregister_match(&ipv6header_mt6_reg);
}
module_init(ipv6header_mt6_init);
module_exit(ipv6header_mt6_exit);
| gpl-2.0 |
novaspirit/tf101-linux-2.6.36 | net/ipv6/netfilter/ip6t_ipv6header.c | 11724 | 3553 | /* ipv6header match - matches IPv6 packets based
on whether they contain certain headers */
/* Original idea: Brad Chapman
* Rewritten by: Andras Kis-Szabo <kisza@sch.bme.hu> */
/* (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.
*/
#include <linux/module.h>
#include <linux/skbuff.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_ipv6header.h>
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Xtables: IPv6 header types match");
MODULE_AUTHOR("Andras Kis-Szabo <kisza@sch.bme.hu>");
static bool
ipv6header_mt6(const struct sk_buff *skb, struct xt_action_param *par)
{
const struct ip6t_ipv6header_info *info = par->matchinfo;
unsigned int temp;
int len;
u8 nexthdr;
unsigned int ptr;
/* Make sure this isn't an evil packet */
/* type of the 1st exthdr */
nexthdr = ipv6_hdr(skb)->nexthdr;
/* pointer to the 1st exthdr */
ptr = sizeof(struct ipv6hdr);
/* available length */
len = skb->len - ptr;
temp = 0;
while (ip6t_ext_hdr(nexthdr)) {
const struct ipv6_opt_hdr *hp;
struct ipv6_opt_hdr _hdr;
int hdrlen;
/* No more exthdr -> evaluate */
if (nexthdr == NEXTHDR_NONE) {
temp |= MASK_NONE;
break;
}
/* Is there enough space for the next ext header? */
if (len < (int)sizeof(struct ipv6_opt_hdr))
return false;
/* ESP -> evaluate */
if (nexthdr == NEXTHDR_ESP) {
temp |= MASK_ESP;
break;
}
hp = skb_header_pointer(skb, ptr, sizeof(_hdr), &_hdr);
BUG_ON(hp == NULL);
/* Calculate the header length */
if (nexthdr == NEXTHDR_FRAGMENT)
hdrlen = 8;
else if (nexthdr == NEXTHDR_AUTH)
hdrlen = (hp->hdrlen + 2) << 2;
else
hdrlen = ipv6_optlen(hp);
/* set the flag */
switch (nexthdr) {
case NEXTHDR_HOP:
temp |= MASK_HOPOPTS;
break;
case NEXTHDR_ROUTING:
temp |= MASK_ROUTING;
break;
case NEXTHDR_FRAGMENT:
temp |= MASK_FRAGMENT;
break;
case NEXTHDR_AUTH:
temp |= MASK_AH;
break;
case NEXTHDR_DEST:
temp |= MASK_DSTOPTS;
break;
default:
return false;
break;
}
nexthdr = hp->nexthdr;
len -= hdrlen;
ptr += hdrlen;
if (ptr > skb->len)
break;
}
if (nexthdr != NEXTHDR_NONE && nexthdr != NEXTHDR_ESP)
temp |= MASK_PROTO;
if (info->modeflag)
return !((temp ^ info->matchflags ^ info->invflags)
& info->matchflags);
else {
if (info->invflags)
return temp != info->matchflags;
else
return temp == info->matchflags;
}
}
static int ipv6header_mt6_check(const struct xt_mtchk_param *par)
{
const struct ip6t_ipv6header_info *info = par->matchinfo;
/* invflags is 0 or 0xff in hard mode */
if ((!info->modeflag) && info->invflags != 0x00 &&
info->invflags != 0xFF)
return -EINVAL;
return 0;
}
static struct xt_match ipv6header_mt6_reg __read_mostly = {
.name = "ipv6header",
.family = NFPROTO_IPV6,
.match = ipv6header_mt6,
.matchsize = sizeof(struct ip6t_ipv6header_info),
.checkentry = ipv6header_mt6_check,
.destroy = NULL,
.me = THIS_MODULE,
};
static int __init ipv6header_mt6_init(void)
{
return xt_register_match(&ipv6header_mt6_reg);
}
static void __exit ipv6header_mt6_exit(void)
{
xt_unregister_match(&ipv6header_mt6_reg);
}
module_init(ipv6header_mt6_init);
module_exit(ipv6header_mt6_exit);
| gpl-2.0 |
rostifaner/android_kernel_xiaomi_msm8956 | arch/powerpc/platforms/40x/virtex.c | 11980 | 1426 | /*
* Xilinx Virtex (IIpro & 4FX) based board support
*
* Copyright 2007 Secret Lab Technologies Ltd.
*
* This file is licensed under the terms of the GNU General Public License
* version 2. This program is licensed "as is" without any warranty of any
* kind, whether express or implied.
*/
#include <linux/init.h>
#include <linux/of_platform.h>
#include <asm/machdep.h>
#include <asm/prom.h>
#include <asm/time.h>
#include <asm/xilinx_intc.h>
#include <asm/xilinx_pci.h>
#include <asm/ppc4xx.h>
static struct of_device_id xilinx_of_bus_ids[] __initdata = {
{ .compatible = "xlnx,plb-v46-1.00.a", },
{ .compatible = "xlnx,plb-v34-1.01.a", },
{ .compatible = "xlnx,plb-v34-1.02.a", },
{ .compatible = "xlnx,opb-v20-1.10.c", },
{ .compatible = "xlnx,dcr-v29-1.00.a", },
{ .compatible = "xlnx,compound", },
{}
};
static int __init virtex_device_probe(void)
{
of_platform_bus_probe(NULL, xilinx_of_bus_ids, NULL);
return 0;
}
machine_device_initcall(virtex, virtex_device_probe);
static int __init virtex_probe(void)
{
unsigned long root = of_get_flat_dt_root();
if (!of_flat_dt_is_compatible(root, "xlnx,virtex"))
return 0;
return 1;
}
define_machine(virtex) {
.name = "Xilinx Virtex",
.probe = virtex_probe,
.setup_arch = xilinx_pci_init,
.init_IRQ = xilinx_intc_init_tree,
.get_irq = xilinx_intc_get_irq,
.restart = ppc4xx_reset_system,
.calibrate_decr = generic_calibrate_decr,
};
| gpl-2.0 |
Mathijsz/razdroid-kernel | arch/sparc/oprofile/init.c | 13772 | 1669 | /**
* @file init.c
*
* @remark Copyright 2002 OProfile authors
* @remark Read the file COPYING
*
* @author John Levon <levon@movementarian.org>
*/
#include <linux/kernel.h>
#include <linux/oprofile.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/param.h> /* for HZ */
#ifdef CONFIG_SPARC64
#include <linux/notifier.h>
#include <linux/rcupdate.h>
#include <linux/kdebug.h>
#include <asm/nmi.h>
static int profile_timer_exceptions_notify(struct notifier_block *self,
unsigned long val, void *data)
{
struct die_args *args = data;
int ret = NOTIFY_DONE;
switch (val) {
case DIE_NMI:
oprofile_add_sample(args->regs, 0);
ret = NOTIFY_STOP;
break;
default:
break;
}
return ret;
}
static struct notifier_block profile_timer_exceptions_nb = {
.notifier_call = profile_timer_exceptions_notify,
};
static int timer_start(void)
{
if (register_die_notifier(&profile_timer_exceptions_nb))
return 1;
nmi_adjust_hz(HZ);
return 0;
}
static void timer_stop(void)
{
nmi_adjust_hz(1);
unregister_die_notifier(&profile_timer_exceptions_nb);
synchronize_sched(); /* Allow already-started NMIs to complete. */
}
static int op_nmi_timer_init(struct oprofile_operations *ops)
{
if (atomic_read(&nmi_active) <= 0)
return -ENODEV;
ops->start = timer_start;
ops->stop = timer_stop;
ops->cpu_type = "timer";
printk(KERN_INFO "oprofile: Using perfctr NMI timer interrupt.\n");
return 0;
}
#endif
int __init oprofile_arch_init(struct oprofile_operations *ops)
{
int ret = -ENODEV;
#ifdef CONFIG_SPARC64
ret = op_nmi_timer_init(ops);
if (!ret)
return ret;
#endif
return ret;
}
void oprofile_arch_exit(void)
{
}
| gpl-2.0 |
skinner12/SkeRneL | net/ipv6/ip6mr.c | 717 | 52044 | /*
* Linux IPv6 multicast routing support for BSD pim6sd
* Based on net/ipv4/ipmr.c.
*
* (c) 2004 Mickael Hoerdt, <hoerdt@clarinet.u-strasbg.fr>
* LSIIT Laboratory, Strasbourg, France
* (c) 2004 Jean-Philippe Andriot, <jean-philippe.andriot@6WIND.com>
* 6WIND, Paris, France
* Copyright (C)2007,2008 USAGI/WIDE Project
* YOSHIFUJI Hideaki <yoshfuji@linux-ipv6.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
#include <asm/system.h>
#include <asm/uaccess.h>
#include <linux/types.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <linux/mm.h>
#include <linux/kernel.h>
#include <linux/fcntl.h>
#include <linux/stat.h>
#include <linux/socket.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/inetdevice.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/compat.h>
#include <net/protocol.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <net/raw.h>
#include <linux/notifier.h>
#include <linux/if_arp.h>
#include <net/checksum.h>
#include <net/netlink.h>
#include <net/fib_rules.h>
#include <net/ipv6.h>
#include <net/ip6_route.h>
#include <linux/mroute6.h>
#include <linux/pim.h>
#include <net/addrconf.h>
#include <linux/netfilter_ipv6.h>
#include <net/ip6_checksum.h>
struct mr6_table {
struct list_head list;
#ifdef CONFIG_NET_NS
struct net *net;
#endif
u32 id;
struct sock *mroute6_sk;
struct timer_list ipmr_expire_timer;
struct list_head mfc6_unres_queue;
struct list_head mfc6_cache_array[MFC6_LINES];
struct mif_device vif6_table[MAXMIFS];
int maxvif;
atomic_t cache_resolve_queue_len;
int mroute_do_assert;
int mroute_do_pim;
#ifdef CONFIG_IPV6_PIMSM_V2
int mroute_reg_vif_num;
#endif
};
struct ip6mr_rule {
struct fib_rule common;
};
struct ip6mr_result {
struct mr6_table *mrt;
};
/* Big lock, protecting vif table, mrt cache and mroute socket state.
Note that the changes are semaphored via rtnl_lock.
*/
static DEFINE_RWLOCK(mrt_lock);
/*
* Multicast router control variables
*/
#define MIF_EXISTS(_mrt, _idx) ((_mrt)->vif6_table[_idx].dev != NULL)
/* Special spinlock for queue of unresolved entries */
static DEFINE_SPINLOCK(mfc_unres_lock);
/* We return to original Alan's scheme. Hash table of resolved
entries is changed only in process context and protected
with weak lock mrt_lock. Queue of unresolved entries is protected
with strong spinlock mfc_unres_lock.
In this case data path is free of exclusive locks at all.
*/
static struct kmem_cache *mrt_cachep __read_mostly;
static struct mr6_table *ip6mr_new_table(struct net *net, u32 id);
static void ip6mr_free_table(struct mr6_table *mrt);
static int ip6_mr_forward(struct net *net, struct mr6_table *mrt,
struct sk_buff *skb, struct mfc6_cache *cache);
static int ip6mr_cache_report(struct mr6_table *mrt, struct sk_buff *pkt,
mifi_t mifi, int assert);
static int __ip6mr_fill_mroute(struct mr6_table *mrt, struct sk_buff *skb,
struct mfc6_cache *c, struct rtmsg *rtm);
static int ip6mr_rtm_dumproute(struct sk_buff *skb,
struct netlink_callback *cb);
static void mroute_clean_tables(struct mr6_table *mrt);
static void ipmr_expire_process(unsigned long arg);
#ifdef CONFIG_IPV6_MROUTE_MULTIPLE_TABLES
#define ip6mr_for_each_table(mrt, net) \
list_for_each_entry_rcu(mrt, &net->ipv6.mr6_tables, list)
static struct mr6_table *ip6mr_get_table(struct net *net, u32 id)
{
struct mr6_table *mrt;
ip6mr_for_each_table(mrt, net) {
if (mrt->id == id)
return mrt;
}
return NULL;
}
static int ip6mr_fib_lookup(struct net *net, struct flowi6 *flp6,
struct mr6_table **mrt)
{
struct ip6mr_result res;
struct fib_lookup_arg arg = { .result = &res, };
int err;
err = fib_rules_lookup(net->ipv6.mr6_rules_ops,
flowi6_to_flowi(flp6), 0, &arg);
if (err < 0)
return err;
*mrt = res.mrt;
return 0;
}
static int ip6mr_rule_action(struct fib_rule *rule, struct flowi *flp,
int flags, struct fib_lookup_arg *arg)
{
struct ip6mr_result *res = arg->result;
struct mr6_table *mrt;
switch (rule->action) {
case FR_ACT_TO_TBL:
break;
case FR_ACT_UNREACHABLE:
return -ENETUNREACH;
case FR_ACT_PROHIBIT:
return -EACCES;
case FR_ACT_BLACKHOLE:
default:
return -EINVAL;
}
mrt = ip6mr_get_table(rule->fr_net, rule->table);
if (mrt == NULL)
return -EAGAIN;
res->mrt = mrt;
return 0;
}
static int ip6mr_rule_match(struct fib_rule *rule, struct flowi *flp, int flags)
{
return 1;
}
static const struct nla_policy ip6mr_rule_policy[FRA_MAX + 1] = {
FRA_GENERIC_POLICY,
};
static int ip6mr_rule_configure(struct fib_rule *rule, struct sk_buff *skb,
struct fib_rule_hdr *frh, struct nlattr **tb)
{
return 0;
}
static int ip6mr_rule_compare(struct fib_rule *rule, struct fib_rule_hdr *frh,
struct nlattr **tb)
{
return 1;
}
static int ip6mr_rule_fill(struct fib_rule *rule, struct sk_buff *skb,
struct fib_rule_hdr *frh)
{
frh->dst_len = 0;
frh->src_len = 0;
frh->tos = 0;
return 0;
}
static const struct fib_rules_ops __net_initdata ip6mr_rules_ops_template = {
.family = RTNL_FAMILY_IP6MR,
.rule_size = sizeof(struct ip6mr_rule),
.addr_size = sizeof(struct in6_addr),
.action = ip6mr_rule_action,
.match = ip6mr_rule_match,
.configure = ip6mr_rule_configure,
.compare = ip6mr_rule_compare,
.default_pref = fib_default_rule_pref,
.fill = ip6mr_rule_fill,
.nlgroup = RTNLGRP_IPV6_RULE,
.policy = ip6mr_rule_policy,
.owner = THIS_MODULE,
};
static int __net_init ip6mr_rules_init(struct net *net)
{
struct fib_rules_ops *ops;
struct mr6_table *mrt;
int err;
ops = fib_rules_register(&ip6mr_rules_ops_template, net);
if (IS_ERR(ops))
return PTR_ERR(ops);
INIT_LIST_HEAD(&net->ipv6.mr6_tables);
mrt = ip6mr_new_table(net, RT6_TABLE_DFLT);
if (mrt == NULL) {
err = -ENOMEM;
goto err1;
}
err = fib_default_rule_add(ops, 0x7fff, RT6_TABLE_DFLT, 0);
if (err < 0)
goto err2;
net->ipv6.mr6_rules_ops = ops;
return 0;
err2:
kfree(mrt);
err1:
fib_rules_unregister(ops);
return err;
}
static void __net_exit ip6mr_rules_exit(struct net *net)
{
struct mr6_table *mrt, *next;
list_for_each_entry_safe(mrt, next, &net->ipv6.mr6_tables, list) {
list_del(&mrt->list);
ip6mr_free_table(mrt);
}
fib_rules_unregister(net->ipv6.mr6_rules_ops);
}
#else
#define ip6mr_for_each_table(mrt, net) \
for (mrt = net->ipv6.mrt6; mrt; mrt = NULL)
static struct mr6_table *ip6mr_get_table(struct net *net, u32 id)
{
return net->ipv6.mrt6;
}
static int ip6mr_fib_lookup(struct net *net, struct flowi6 *flp6,
struct mr6_table **mrt)
{
*mrt = net->ipv6.mrt6;
return 0;
}
static int __net_init ip6mr_rules_init(struct net *net)
{
net->ipv6.mrt6 = ip6mr_new_table(net, RT6_TABLE_DFLT);
return net->ipv6.mrt6 ? 0 : -ENOMEM;
}
static void __net_exit ip6mr_rules_exit(struct net *net)
{
ip6mr_free_table(net->ipv6.mrt6);
}
#endif
static struct mr6_table *ip6mr_new_table(struct net *net, u32 id)
{
struct mr6_table *mrt;
unsigned int i;
mrt = ip6mr_get_table(net, id);
if (mrt != NULL)
return mrt;
mrt = kzalloc(sizeof(*mrt), GFP_KERNEL);
if (mrt == NULL)
return NULL;
mrt->id = id;
write_pnet(&mrt->net, net);
/* Forwarding cache */
for (i = 0; i < MFC6_LINES; i++)
INIT_LIST_HEAD(&mrt->mfc6_cache_array[i]);
INIT_LIST_HEAD(&mrt->mfc6_unres_queue);
setup_timer(&mrt->ipmr_expire_timer, ipmr_expire_process,
(unsigned long)mrt);
#ifdef CONFIG_IPV6_PIMSM_V2
mrt->mroute_reg_vif_num = -1;
#endif
#ifdef CONFIG_IPV6_MROUTE_MULTIPLE_TABLES
list_add_tail_rcu(&mrt->list, &net->ipv6.mr6_tables);
#endif
return mrt;
}
static void ip6mr_free_table(struct mr6_table *mrt)
{
del_timer(&mrt->ipmr_expire_timer);
mroute_clean_tables(mrt);
kfree(mrt);
}
#ifdef CONFIG_PROC_FS
struct ipmr_mfc_iter {
struct seq_net_private p;
struct mr6_table *mrt;
struct list_head *cache;
int ct;
};
static struct mfc6_cache *ipmr_mfc_seq_idx(struct net *net,
struct ipmr_mfc_iter *it, loff_t pos)
{
struct mr6_table *mrt = it->mrt;
struct mfc6_cache *mfc;
read_lock(&mrt_lock);
for (it->ct = 0; it->ct < MFC6_LINES; it->ct++) {
it->cache = &mrt->mfc6_cache_array[it->ct];
list_for_each_entry(mfc, it->cache, list)
if (pos-- == 0)
return mfc;
}
read_unlock(&mrt_lock);
spin_lock_bh(&mfc_unres_lock);
it->cache = &mrt->mfc6_unres_queue;
list_for_each_entry(mfc, it->cache, list)
if (pos-- == 0)
return mfc;
spin_unlock_bh(&mfc_unres_lock);
it->cache = NULL;
return NULL;
}
/*
* The /proc interfaces to multicast routing /proc/ip6_mr_cache /proc/ip6_mr_vif
*/
struct ipmr_vif_iter {
struct seq_net_private p;
struct mr6_table *mrt;
int ct;
};
static struct mif_device *ip6mr_vif_seq_idx(struct net *net,
struct ipmr_vif_iter *iter,
loff_t pos)
{
struct mr6_table *mrt = iter->mrt;
for (iter->ct = 0; iter->ct < mrt->maxvif; ++iter->ct) {
if (!MIF_EXISTS(mrt, iter->ct))
continue;
if (pos-- == 0)
return &mrt->vif6_table[iter->ct];
}
return NULL;
}
static void *ip6mr_vif_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(mrt_lock)
{
struct ipmr_vif_iter *iter = seq->private;
struct net *net = seq_file_net(seq);
struct mr6_table *mrt;
mrt = ip6mr_get_table(net, RT6_TABLE_DFLT);
if (mrt == NULL)
return ERR_PTR(-ENOENT);
iter->mrt = mrt;
read_lock(&mrt_lock);
return *pos ? ip6mr_vif_seq_idx(net, seq->private, *pos - 1)
: SEQ_START_TOKEN;
}
static void *ip6mr_vif_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct ipmr_vif_iter *iter = seq->private;
struct net *net = seq_file_net(seq);
struct mr6_table *mrt = iter->mrt;
++*pos;
if (v == SEQ_START_TOKEN)
return ip6mr_vif_seq_idx(net, iter, 0);
while (++iter->ct < mrt->maxvif) {
if (!MIF_EXISTS(mrt, iter->ct))
continue;
return &mrt->vif6_table[iter->ct];
}
return NULL;
}
static void ip6mr_vif_seq_stop(struct seq_file *seq, void *v)
__releases(mrt_lock)
{
read_unlock(&mrt_lock);
}
static int ip6mr_vif_seq_show(struct seq_file *seq, void *v)
{
struct ipmr_vif_iter *iter = seq->private;
struct mr6_table *mrt = iter->mrt;
if (v == SEQ_START_TOKEN) {
seq_puts(seq,
"Interface BytesIn PktsIn BytesOut PktsOut Flags\n");
} else {
const struct mif_device *vif = v;
const char *name = vif->dev ? vif->dev->name : "none";
seq_printf(seq,
"%2td %-10s %8ld %7ld %8ld %7ld %05X\n",
vif - mrt->vif6_table,
name, vif->bytes_in, vif->pkt_in,
vif->bytes_out, vif->pkt_out,
vif->flags);
}
return 0;
}
static const struct seq_operations ip6mr_vif_seq_ops = {
.start = ip6mr_vif_seq_start,
.next = ip6mr_vif_seq_next,
.stop = ip6mr_vif_seq_stop,
.show = ip6mr_vif_seq_show,
};
static int ip6mr_vif_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &ip6mr_vif_seq_ops,
sizeof(struct ipmr_vif_iter));
}
static const struct file_operations ip6mr_vif_fops = {
.owner = THIS_MODULE,
.open = ip6mr_vif_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static void *ipmr_mfc_seq_start(struct seq_file *seq, loff_t *pos)
{
struct ipmr_mfc_iter *it = seq->private;
struct net *net = seq_file_net(seq);
struct mr6_table *mrt;
mrt = ip6mr_get_table(net, RT6_TABLE_DFLT);
if (mrt == NULL)
return ERR_PTR(-ENOENT);
it->mrt = mrt;
return *pos ? ipmr_mfc_seq_idx(net, seq->private, *pos - 1)
: SEQ_START_TOKEN;
}
static void *ipmr_mfc_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct mfc6_cache *mfc = v;
struct ipmr_mfc_iter *it = seq->private;
struct net *net = seq_file_net(seq);
struct mr6_table *mrt = it->mrt;
++*pos;
if (v == SEQ_START_TOKEN)
return ipmr_mfc_seq_idx(net, seq->private, 0);
if (mfc->list.next != it->cache)
return list_entry(mfc->list.next, struct mfc6_cache, list);
if (it->cache == &mrt->mfc6_unres_queue)
goto end_of_list;
BUG_ON(it->cache != &mrt->mfc6_cache_array[it->ct]);
while (++it->ct < MFC6_LINES) {
it->cache = &mrt->mfc6_cache_array[it->ct];
if (list_empty(it->cache))
continue;
return list_first_entry(it->cache, struct mfc6_cache, list);
}
/* exhausted cache_array, show unresolved */
read_unlock(&mrt_lock);
it->cache = &mrt->mfc6_unres_queue;
it->ct = 0;
spin_lock_bh(&mfc_unres_lock);
if (!list_empty(it->cache))
return list_first_entry(it->cache, struct mfc6_cache, list);
end_of_list:
spin_unlock_bh(&mfc_unres_lock);
it->cache = NULL;
return NULL;
}
static void ipmr_mfc_seq_stop(struct seq_file *seq, void *v)
{
struct ipmr_mfc_iter *it = seq->private;
struct mr6_table *mrt = it->mrt;
if (it->cache == &mrt->mfc6_unres_queue)
spin_unlock_bh(&mfc_unres_lock);
else if (it->cache == mrt->mfc6_cache_array)
read_unlock(&mrt_lock);
}
static int ipmr_mfc_seq_show(struct seq_file *seq, void *v)
{
int n;
if (v == SEQ_START_TOKEN) {
seq_puts(seq,
"Group "
"Origin "
"Iif Pkts Bytes Wrong Oifs\n");
} else {
const struct mfc6_cache *mfc = v;
const struct ipmr_mfc_iter *it = seq->private;
struct mr6_table *mrt = it->mrt;
seq_printf(seq, "%pI6 %pI6 %-3hd",
&mfc->mf6c_mcastgrp, &mfc->mf6c_origin,
mfc->mf6c_parent);
if (it->cache != &mrt->mfc6_unres_queue) {
seq_printf(seq, " %8lu %8lu %8lu",
mfc->mfc_un.res.pkt,
mfc->mfc_un.res.bytes,
mfc->mfc_un.res.wrong_if);
for (n = mfc->mfc_un.res.minvif;
n < mfc->mfc_un.res.maxvif; n++) {
if (MIF_EXISTS(mrt, n) &&
mfc->mfc_un.res.ttls[n] < 255)
seq_printf(seq,
" %2d:%-3d",
n, mfc->mfc_un.res.ttls[n]);
}
} else {
/* unresolved mfc_caches don't contain
* pkt, bytes and wrong_if values
*/
seq_printf(seq, " %8lu %8lu %8lu", 0ul, 0ul, 0ul);
}
seq_putc(seq, '\n');
}
return 0;
}
static const struct seq_operations ipmr_mfc_seq_ops = {
.start = ipmr_mfc_seq_start,
.next = ipmr_mfc_seq_next,
.stop = ipmr_mfc_seq_stop,
.show = ipmr_mfc_seq_show,
};
static int ipmr_mfc_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &ipmr_mfc_seq_ops,
sizeof(struct ipmr_mfc_iter));
}
static const struct file_operations ip6mr_mfc_fops = {
.owner = THIS_MODULE,
.open = ipmr_mfc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
#ifdef CONFIG_IPV6_PIMSM_V2
static int pim6_rcv(struct sk_buff *skb)
{
struct pimreghdr *pim;
struct ipv6hdr *encap;
struct net_device *reg_dev = NULL;
struct net *net = dev_net(skb->dev);
struct mr6_table *mrt;
struct flowi6 fl6 = {
.flowi6_iif = skb->dev->ifindex,
.flowi6_mark = skb->mark,
};
int reg_vif_num;
if (!pskb_may_pull(skb, sizeof(*pim) + sizeof(*encap)))
goto drop;
pim = (struct pimreghdr *)skb_transport_header(skb);
if (pim->type != ((PIM_VERSION << 4) | PIM_REGISTER) ||
(pim->flags & PIM_NULL_REGISTER) ||
(csum_ipv6_magic(&ipv6_hdr(skb)->saddr, &ipv6_hdr(skb)->daddr,
sizeof(*pim), IPPROTO_PIM,
csum_partial((void *)pim, sizeof(*pim), 0)) &&
csum_fold(skb_checksum(skb, 0, skb->len, 0))))
goto drop;
/* check if the inner packet is destined to mcast group */
encap = (struct ipv6hdr *)(skb_transport_header(skb) +
sizeof(*pim));
if (!ipv6_addr_is_multicast(&encap->daddr) ||
encap->payload_len == 0 ||
ntohs(encap->payload_len) + sizeof(*pim) > skb->len)
goto drop;
if (ip6mr_fib_lookup(net, &fl6, &mrt) < 0)
goto drop;
reg_vif_num = mrt->mroute_reg_vif_num;
read_lock(&mrt_lock);
if (reg_vif_num >= 0)
reg_dev = mrt->vif6_table[reg_vif_num].dev;
if (reg_dev)
dev_hold(reg_dev);
read_unlock(&mrt_lock);
if (reg_dev == NULL)
goto drop;
skb->mac_header = skb->network_header;
skb_pull(skb, (u8 *)encap - skb->data);
skb_reset_network_header(skb);
skb->protocol = htons(ETH_P_IPV6);
skb->ip_summed = CHECKSUM_NONE;
skb->pkt_type = PACKET_HOST;
skb_tunnel_rx(skb, reg_dev);
netif_rx(skb);
dev_put(reg_dev);
return 0;
drop:
kfree_skb(skb);
return 0;
}
static const struct inet6_protocol pim6_protocol = {
.handler = pim6_rcv,
};
/* Service routines creating virtual interfaces: PIMREG */
static netdev_tx_t reg_vif_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct net *net = dev_net(dev);
struct mr6_table *mrt;
struct flowi6 fl6 = {
.flowi6_oif = dev->ifindex,
.flowi6_iif = skb->skb_iif,
.flowi6_mark = skb->mark,
};
int err;
err = ip6mr_fib_lookup(net, &fl6, &mrt);
if (err < 0) {
kfree_skb(skb);
return err;
}
read_lock(&mrt_lock);
dev->stats.tx_bytes += skb->len;
dev->stats.tx_packets++;
ip6mr_cache_report(mrt, skb, mrt->mroute_reg_vif_num, MRT6MSG_WHOLEPKT);
read_unlock(&mrt_lock);
kfree_skb(skb);
return NETDEV_TX_OK;
}
static const struct net_device_ops reg_vif_netdev_ops = {
.ndo_start_xmit = reg_vif_xmit,
};
static void reg_vif_setup(struct net_device *dev)
{
dev->type = ARPHRD_PIMREG;
dev->mtu = 1500 - sizeof(struct ipv6hdr) - 8;
dev->flags = IFF_NOARP;
dev->netdev_ops = ®_vif_netdev_ops;
dev->destructor = free_netdev;
dev->features |= NETIF_F_NETNS_LOCAL;
}
static struct net_device *ip6mr_reg_vif(struct net *net, struct mr6_table *mrt)
{
struct net_device *dev;
char name[IFNAMSIZ];
if (mrt->id == RT6_TABLE_DFLT)
sprintf(name, "pim6reg");
else
sprintf(name, "pim6reg%u", mrt->id);
dev = alloc_netdev(0, name, reg_vif_setup);
if (dev == NULL)
return NULL;
dev_net_set(dev, net);
if (register_netdevice(dev)) {
free_netdev(dev);
return NULL;
}
dev->iflink = 0;
if (dev_open(dev))
goto failure;
dev_hold(dev);
return dev;
failure:
/* allow the register to be completed before unregistering. */
rtnl_unlock();
rtnl_lock();
unregister_netdevice(dev);
return NULL;
}
#endif
/*
* Delete a VIF entry
*/
static int mif6_delete(struct mr6_table *mrt, int vifi, struct list_head *head)
{
struct mif_device *v;
struct net_device *dev;
struct inet6_dev *in6_dev;
if (vifi < 0 || vifi >= mrt->maxvif)
return -EADDRNOTAVAIL;
v = &mrt->vif6_table[vifi];
write_lock_bh(&mrt_lock);
dev = v->dev;
v->dev = NULL;
if (!dev) {
write_unlock_bh(&mrt_lock);
return -EADDRNOTAVAIL;
}
#ifdef CONFIG_IPV6_PIMSM_V2
if (vifi == mrt->mroute_reg_vif_num)
mrt->mroute_reg_vif_num = -1;
#endif
if (vifi + 1 == mrt->maxvif) {
int tmp;
for (tmp = vifi - 1; tmp >= 0; tmp--) {
if (MIF_EXISTS(mrt, tmp))
break;
}
mrt->maxvif = tmp + 1;
}
write_unlock_bh(&mrt_lock);
dev_set_allmulti(dev, -1);
in6_dev = __in6_dev_get(dev);
if (in6_dev)
in6_dev->cnf.mc_forwarding--;
if (v->flags & MIFF_REGISTER)
unregister_netdevice_queue(dev, head);
dev_put(dev);
return 0;
}
static inline void ip6mr_cache_free(struct mfc6_cache *c)
{
kmem_cache_free(mrt_cachep, c);
}
/* Destroy an unresolved cache entry, killing queued skbs
and reporting error to netlink readers.
*/
static void ip6mr_destroy_unres(struct mr6_table *mrt, struct mfc6_cache *c)
{
struct net *net = read_pnet(&mrt->net);
struct sk_buff *skb;
atomic_dec(&mrt->cache_resolve_queue_len);
while((skb = skb_dequeue(&c->mfc_un.unres.unresolved)) != NULL) {
if (ipv6_hdr(skb)->version == 0) {
struct nlmsghdr *nlh = (struct nlmsghdr *)skb_pull(skb, sizeof(struct ipv6hdr));
nlh->nlmsg_type = NLMSG_ERROR;
nlh->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr));
skb_trim(skb, nlh->nlmsg_len);
((struct nlmsgerr *)NLMSG_DATA(nlh))->error = -ETIMEDOUT;
rtnl_unicast(skb, net, NETLINK_CB(skb).pid);
} else
kfree_skb(skb);
}
ip6mr_cache_free(c);
}
/* Timer process for all the unresolved queue. */
static void ipmr_do_expire_process(struct mr6_table *mrt)
{
unsigned long now = jiffies;
unsigned long expires = 10 * HZ;
struct mfc6_cache *c, *next;
list_for_each_entry_safe(c, next, &mrt->mfc6_unres_queue, list) {
if (time_after(c->mfc_un.unres.expires, now)) {
/* not yet... */
unsigned long interval = c->mfc_un.unres.expires - now;
if (interval < expires)
expires = interval;
continue;
}
list_del(&c->list);
ip6mr_destroy_unres(mrt, c);
}
if (!list_empty(&mrt->mfc6_unres_queue))
mod_timer(&mrt->ipmr_expire_timer, jiffies + expires);
}
static void ipmr_expire_process(unsigned long arg)
{
struct mr6_table *mrt = (struct mr6_table *)arg;
if (!spin_trylock(&mfc_unres_lock)) {
mod_timer(&mrt->ipmr_expire_timer, jiffies + 1);
return;
}
if (!list_empty(&mrt->mfc6_unres_queue))
ipmr_do_expire_process(mrt);
spin_unlock(&mfc_unres_lock);
}
/* Fill oifs list. It is called under write locked mrt_lock. */
static void ip6mr_update_thresholds(struct mr6_table *mrt, struct mfc6_cache *cache,
unsigned char *ttls)
{
int vifi;
cache->mfc_un.res.minvif = MAXMIFS;
cache->mfc_un.res.maxvif = 0;
memset(cache->mfc_un.res.ttls, 255, MAXMIFS);
for (vifi = 0; vifi < mrt->maxvif; vifi++) {
if (MIF_EXISTS(mrt, vifi) &&
ttls[vifi] && ttls[vifi] < 255) {
cache->mfc_un.res.ttls[vifi] = ttls[vifi];
if (cache->mfc_un.res.minvif > vifi)
cache->mfc_un.res.minvif = vifi;
if (cache->mfc_un.res.maxvif <= vifi)
cache->mfc_un.res.maxvif = vifi + 1;
}
}
}
static int mif6_add(struct net *net, struct mr6_table *mrt,
struct mif6ctl *vifc, int mrtsock)
{
int vifi = vifc->mif6c_mifi;
struct mif_device *v = &mrt->vif6_table[vifi];
struct net_device *dev;
struct inet6_dev *in6_dev;
int err;
/* Is vif busy ? */
if (MIF_EXISTS(mrt, vifi))
return -EADDRINUSE;
switch (vifc->mif6c_flags) {
#ifdef CONFIG_IPV6_PIMSM_V2
case MIFF_REGISTER:
/*
* Special Purpose VIF in PIM
* All the packets will be sent to the daemon
*/
if (mrt->mroute_reg_vif_num >= 0)
return -EADDRINUSE;
dev = ip6mr_reg_vif(net, mrt);
if (!dev)
return -ENOBUFS;
err = dev_set_allmulti(dev, 1);
if (err) {
unregister_netdevice(dev);
dev_put(dev);
return err;
}
break;
#endif
case 0:
dev = dev_get_by_index(net, vifc->mif6c_pifi);
if (!dev)
return -EADDRNOTAVAIL;
err = dev_set_allmulti(dev, 1);
if (err) {
dev_put(dev);
return err;
}
break;
default:
return -EINVAL;
}
in6_dev = __in6_dev_get(dev);
if (in6_dev)
in6_dev->cnf.mc_forwarding++;
/*
* Fill in the VIF structures
*/
v->rate_limit = vifc->vifc_rate_limit;
v->flags = vifc->mif6c_flags;
if (!mrtsock)
v->flags |= VIFF_STATIC;
v->threshold = vifc->vifc_threshold;
v->bytes_in = 0;
v->bytes_out = 0;
v->pkt_in = 0;
v->pkt_out = 0;
v->link = dev->ifindex;
if (v->flags & MIFF_REGISTER)
v->link = dev->iflink;
/* And finish update writing critical data */
write_lock_bh(&mrt_lock);
v->dev = dev;
#ifdef CONFIG_IPV6_PIMSM_V2
if (v->flags & MIFF_REGISTER)
mrt->mroute_reg_vif_num = vifi;
#endif
if (vifi + 1 > mrt->maxvif)
mrt->maxvif = vifi + 1;
write_unlock_bh(&mrt_lock);
return 0;
}
static struct mfc6_cache *ip6mr_cache_find(struct mr6_table *mrt,
const struct in6_addr *origin,
const struct in6_addr *mcastgrp)
{
int line = MFC6_HASH(mcastgrp, origin);
struct mfc6_cache *c;
list_for_each_entry(c, &mrt->mfc6_cache_array[line], list) {
if (ipv6_addr_equal(&c->mf6c_origin, origin) &&
ipv6_addr_equal(&c->mf6c_mcastgrp, mcastgrp))
return c;
}
return NULL;
}
/*
* Allocate a multicast cache entry
*/
static struct mfc6_cache *ip6mr_cache_alloc(void)
{
struct mfc6_cache *c = kmem_cache_zalloc(mrt_cachep, GFP_KERNEL);
if (c == NULL)
return NULL;
c->mfc_un.res.minvif = MAXMIFS;
return c;
}
static struct mfc6_cache *ip6mr_cache_alloc_unres(void)
{
struct mfc6_cache *c = kmem_cache_zalloc(mrt_cachep, GFP_ATOMIC);
if (c == NULL)
return NULL;
skb_queue_head_init(&c->mfc_un.unres.unresolved);
c->mfc_un.unres.expires = jiffies + 10 * HZ;
return c;
}
/*
* A cache entry has gone into a resolved state from queued
*/
static void ip6mr_cache_resolve(struct net *net, struct mr6_table *mrt,
struct mfc6_cache *uc, struct mfc6_cache *c)
{
struct sk_buff *skb;
/*
* Play the pending entries through our router
*/
while((skb = __skb_dequeue(&uc->mfc_un.unres.unresolved))) {
if (ipv6_hdr(skb)->version == 0) {
struct nlmsghdr *nlh = (struct nlmsghdr *)skb_pull(skb, sizeof(struct ipv6hdr));
if (__ip6mr_fill_mroute(mrt, skb, c, NLMSG_DATA(nlh)) > 0) {
nlh->nlmsg_len = skb_tail_pointer(skb) - (u8 *)nlh;
} else {
nlh->nlmsg_type = NLMSG_ERROR;
nlh->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr));
skb_trim(skb, nlh->nlmsg_len);
((struct nlmsgerr *)NLMSG_DATA(nlh))->error = -EMSGSIZE;
}
rtnl_unicast(skb, net, NETLINK_CB(skb).pid);
} else
ip6_mr_forward(net, mrt, skb, c);
}
}
/*
* Bounce a cache query up to pim6sd. We could use netlink for this but pim6sd
* expects the following bizarre scheme.
*
* Called under mrt_lock.
*/
static int ip6mr_cache_report(struct mr6_table *mrt, struct sk_buff *pkt,
mifi_t mifi, int assert)
{
struct sk_buff *skb;
struct mrt6msg *msg;
int ret;
#ifdef CONFIG_IPV6_PIMSM_V2
if (assert == MRT6MSG_WHOLEPKT)
skb = skb_realloc_headroom(pkt, -skb_network_offset(pkt)
+sizeof(*msg));
else
#endif
skb = alloc_skb(sizeof(struct ipv6hdr) + sizeof(*msg), GFP_ATOMIC);
if (!skb)
return -ENOBUFS;
/* I suppose that internal messages
* do not require checksums */
skb->ip_summed = CHECKSUM_UNNECESSARY;
#ifdef CONFIG_IPV6_PIMSM_V2
if (assert == MRT6MSG_WHOLEPKT) {
/* Ugly, but we have no choice with this interface.
Duplicate old header, fix length etc.
And all this only to mangle msg->im6_msgtype and
to set msg->im6_mbz to "mbz" :-)
*/
skb_push(skb, -skb_network_offset(pkt));
skb_push(skb, sizeof(*msg));
skb_reset_transport_header(skb);
msg = (struct mrt6msg *)skb_transport_header(skb);
msg->im6_mbz = 0;
msg->im6_msgtype = MRT6MSG_WHOLEPKT;
msg->im6_mif = mrt->mroute_reg_vif_num;
msg->im6_pad = 0;
ipv6_addr_copy(&msg->im6_src, &ipv6_hdr(pkt)->saddr);
ipv6_addr_copy(&msg->im6_dst, &ipv6_hdr(pkt)->daddr);
skb->ip_summed = CHECKSUM_UNNECESSARY;
} else
#endif
{
/*
* Copy the IP header
*/
skb_put(skb, sizeof(struct ipv6hdr));
skb_reset_network_header(skb);
skb_copy_to_linear_data(skb, ipv6_hdr(pkt), sizeof(struct ipv6hdr));
/*
* Add our header
*/
skb_put(skb, sizeof(*msg));
skb_reset_transport_header(skb);
msg = (struct mrt6msg *)skb_transport_header(skb);
msg->im6_mbz = 0;
msg->im6_msgtype = assert;
msg->im6_mif = mifi;
msg->im6_pad = 0;
ipv6_addr_copy(&msg->im6_src, &ipv6_hdr(pkt)->saddr);
ipv6_addr_copy(&msg->im6_dst, &ipv6_hdr(pkt)->daddr);
skb_dst_set(skb, dst_clone(skb_dst(pkt)));
skb->ip_summed = CHECKSUM_UNNECESSARY;
}
if (mrt->mroute6_sk == NULL) {
kfree_skb(skb);
return -EINVAL;
}
/*
* Deliver to user space multicast routing algorithms
*/
ret = sock_queue_rcv_skb(mrt->mroute6_sk, skb);
if (ret < 0) {
if (net_ratelimit())
printk(KERN_WARNING "mroute6: pending queue full, dropping entries.\n");
kfree_skb(skb);
}
return ret;
}
/*
* Queue a packet for resolution. It gets locked cache entry!
*/
static int
ip6mr_cache_unresolved(struct mr6_table *mrt, mifi_t mifi, struct sk_buff *skb)
{
bool found = false;
int err;
struct mfc6_cache *c;
spin_lock_bh(&mfc_unres_lock);
list_for_each_entry(c, &mrt->mfc6_unres_queue, list) {
if (ipv6_addr_equal(&c->mf6c_mcastgrp, &ipv6_hdr(skb)->daddr) &&
ipv6_addr_equal(&c->mf6c_origin, &ipv6_hdr(skb)->saddr)) {
found = true;
break;
}
}
if (!found) {
/*
* Create a new entry if allowable
*/
if (atomic_read(&mrt->cache_resolve_queue_len) >= 10 ||
(c = ip6mr_cache_alloc_unres()) == NULL) {
spin_unlock_bh(&mfc_unres_lock);
kfree_skb(skb);
return -ENOBUFS;
}
/*
* Fill in the new cache entry
*/
c->mf6c_parent = -1;
c->mf6c_origin = ipv6_hdr(skb)->saddr;
c->mf6c_mcastgrp = ipv6_hdr(skb)->daddr;
/*
* Reflect first query at pim6sd
*/
err = ip6mr_cache_report(mrt, skb, mifi, MRT6MSG_NOCACHE);
if (err < 0) {
/* If the report failed throw the cache entry
out - Brad Parker
*/
spin_unlock_bh(&mfc_unres_lock);
ip6mr_cache_free(c);
kfree_skb(skb);
return err;
}
atomic_inc(&mrt->cache_resolve_queue_len);
list_add(&c->list, &mrt->mfc6_unres_queue);
ipmr_do_expire_process(mrt);
}
/*
* See if we can append the packet
*/
if (c->mfc_un.unres.unresolved.qlen > 3) {
kfree_skb(skb);
err = -ENOBUFS;
} else {
skb_queue_tail(&c->mfc_un.unres.unresolved, skb);
err = 0;
}
spin_unlock_bh(&mfc_unres_lock);
return err;
}
/*
* MFC6 cache manipulation by user space
*/
static int ip6mr_mfc_delete(struct mr6_table *mrt, struct mf6cctl *mfc)
{
int line;
struct mfc6_cache *c, *next;
line = MFC6_HASH(&mfc->mf6cc_mcastgrp.sin6_addr, &mfc->mf6cc_origin.sin6_addr);
list_for_each_entry_safe(c, next, &mrt->mfc6_cache_array[line], list) {
if (ipv6_addr_equal(&c->mf6c_origin, &mfc->mf6cc_origin.sin6_addr) &&
ipv6_addr_equal(&c->mf6c_mcastgrp, &mfc->mf6cc_mcastgrp.sin6_addr)) {
write_lock_bh(&mrt_lock);
list_del(&c->list);
write_unlock_bh(&mrt_lock);
ip6mr_cache_free(c);
return 0;
}
}
return -ENOENT;
}
static int ip6mr_device_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct net_device *dev = ptr;
struct net *net = dev_net(dev);
struct mr6_table *mrt;
struct mif_device *v;
int ct;
LIST_HEAD(list);
if (event != NETDEV_UNREGISTER)
return NOTIFY_DONE;
ip6mr_for_each_table(mrt, net) {
v = &mrt->vif6_table[0];
for (ct = 0; ct < mrt->maxvif; ct++, v++) {
if (v->dev == dev)
mif6_delete(mrt, ct, &list);
}
}
unregister_netdevice_many(&list);
return NOTIFY_DONE;
}
static struct notifier_block ip6_mr_notifier = {
.notifier_call = ip6mr_device_event
};
/*
* Setup for IP multicast routing
*/
static int __net_init ip6mr_net_init(struct net *net)
{
int err;
err = ip6mr_rules_init(net);
if (err < 0)
goto fail;
#ifdef CONFIG_PROC_FS
err = -ENOMEM;
if (!proc_net_fops_create(net, "ip6_mr_vif", 0, &ip6mr_vif_fops))
goto proc_vif_fail;
if (!proc_net_fops_create(net, "ip6_mr_cache", 0, &ip6mr_mfc_fops))
goto proc_cache_fail;
#endif
return 0;
#ifdef CONFIG_PROC_FS
proc_cache_fail:
proc_net_remove(net, "ip6_mr_vif");
proc_vif_fail:
ip6mr_rules_exit(net);
#endif
fail:
return err;
}
static void __net_exit ip6mr_net_exit(struct net *net)
{
#ifdef CONFIG_PROC_FS
proc_net_remove(net, "ip6_mr_cache");
proc_net_remove(net, "ip6_mr_vif");
#endif
ip6mr_rules_exit(net);
}
static struct pernet_operations ip6mr_net_ops = {
.init = ip6mr_net_init,
.exit = ip6mr_net_exit,
};
int __init ip6_mr_init(void)
{
int err;
mrt_cachep = kmem_cache_create("ip6_mrt_cache",
sizeof(struct mfc6_cache),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (!mrt_cachep)
return -ENOMEM;
err = register_pernet_subsys(&ip6mr_net_ops);
if (err)
goto reg_pernet_fail;
err = register_netdevice_notifier(&ip6_mr_notifier);
if (err)
goto reg_notif_fail;
#ifdef CONFIG_IPV6_PIMSM_V2
if (inet6_add_protocol(&pim6_protocol, IPPROTO_PIM) < 0) {
printk(KERN_ERR "ip6_mr_init: can't add PIM protocol\n");
err = -EAGAIN;
goto add_proto_fail;
}
#endif
rtnl_register(RTNL_FAMILY_IP6MR, RTM_GETROUTE, NULL, ip6mr_rtm_dumproute);
return 0;
#ifdef CONFIG_IPV6_PIMSM_V2
add_proto_fail:
unregister_netdevice_notifier(&ip6_mr_notifier);
#endif
reg_notif_fail:
unregister_pernet_subsys(&ip6mr_net_ops);
reg_pernet_fail:
kmem_cache_destroy(mrt_cachep);
return err;
}
void ip6_mr_cleanup(void)
{
unregister_netdevice_notifier(&ip6_mr_notifier);
unregister_pernet_subsys(&ip6mr_net_ops);
kmem_cache_destroy(mrt_cachep);
}
static int ip6mr_mfc_add(struct net *net, struct mr6_table *mrt,
struct mf6cctl *mfc, int mrtsock)
{
bool found = false;
int line;
struct mfc6_cache *uc, *c;
unsigned char ttls[MAXMIFS];
int i;
if (mfc->mf6cc_parent >= MAXMIFS)
return -ENFILE;
memset(ttls, 255, MAXMIFS);
for (i = 0; i < MAXMIFS; i++) {
if (IF_ISSET(i, &mfc->mf6cc_ifset))
ttls[i] = 1;
}
line = MFC6_HASH(&mfc->mf6cc_mcastgrp.sin6_addr, &mfc->mf6cc_origin.sin6_addr);
list_for_each_entry(c, &mrt->mfc6_cache_array[line], list) {
if (ipv6_addr_equal(&c->mf6c_origin, &mfc->mf6cc_origin.sin6_addr) &&
ipv6_addr_equal(&c->mf6c_mcastgrp, &mfc->mf6cc_mcastgrp.sin6_addr)) {
found = true;
break;
}
}
if (found) {
write_lock_bh(&mrt_lock);
c->mf6c_parent = mfc->mf6cc_parent;
ip6mr_update_thresholds(mrt, c, ttls);
if (!mrtsock)
c->mfc_flags |= MFC_STATIC;
write_unlock_bh(&mrt_lock);
return 0;
}
if (!ipv6_addr_is_multicast(&mfc->mf6cc_mcastgrp.sin6_addr))
return -EINVAL;
c = ip6mr_cache_alloc();
if (c == NULL)
return -ENOMEM;
c->mf6c_origin = mfc->mf6cc_origin.sin6_addr;
c->mf6c_mcastgrp = mfc->mf6cc_mcastgrp.sin6_addr;
c->mf6c_parent = mfc->mf6cc_parent;
ip6mr_update_thresholds(mrt, c, ttls);
if (!mrtsock)
c->mfc_flags |= MFC_STATIC;
write_lock_bh(&mrt_lock);
list_add(&c->list, &mrt->mfc6_cache_array[line]);
write_unlock_bh(&mrt_lock);
/*
* Check to see if we resolved a queued list. If so we
* need to send on the frames and tidy up.
*/
found = false;
spin_lock_bh(&mfc_unres_lock);
list_for_each_entry(uc, &mrt->mfc6_unres_queue, list) {
if (ipv6_addr_equal(&uc->mf6c_origin, &c->mf6c_origin) &&
ipv6_addr_equal(&uc->mf6c_mcastgrp, &c->mf6c_mcastgrp)) {
list_del(&uc->list);
atomic_dec(&mrt->cache_resolve_queue_len);
found = true;
break;
}
}
if (list_empty(&mrt->mfc6_unres_queue))
del_timer(&mrt->ipmr_expire_timer);
spin_unlock_bh(&mfc_unres_lock);
if (found) {
ip6mr_cache_resolve(net, mrt, uc, c);
ip6mr_cache_free(uc);
}
return 0;
}
/*
* Close the multicast socket, and clear the vif tables etc
*/
static void mroute_clean_tables(struct mr6_table *mrt)
{
int i;
LIST_HEAD(list);
struct mfc6_cache *c, *next;
/*
* Shut down all active vif entries
*/
for (i = 0; i < mrt->maxvif; i++) {
if (!(mrt->vif6_table[i].flags & VIFF_STATIC))
mif6_delete(mrt, i, &list);
}
unregister_netdevice_many(&list);
/*
* Wipe the cache
*/
for (i = 0; i < MFC6_LINES; i++) {
list_for_each_entry_safe(c, next, &mrt->mfc6_cache_array[i], list) {
if (c->mfc_flags & MFC_STATIC)
continue;
write_lock_bh(&mrt_lock);
list_del(&c->list);
write_unlock_bh(&mrt_lock);
ip6mr_cache_free(c);
}
}
if (atomic_read(&mrt->cache_resolve_queue_len) != 0) {
spin_lock_bh(&mfc_unres_lock);
list_for_each_entry_safe(c, next, &mrt->mfc6_unres_queue, list) {
list_del(&c->list);
ip6mr_destroy_unres(mrt, c);
}
spin_unlock_bh(&mfc_unres_lock);
}
}
static int ip6mr_sk_init(struct mr6_table *mrt, struct sock *sk)
{
int err = 0;
struct net *net = sock_net(sk);
rtnl_lock();
write_lock_bh(&mrt_lock);
if (likely(mrt->mroute6_sk == NULL)) {
mrt->mroute6_sk = sk;
net->ipv6.devconf_all->mc_forwarding++;
}
else
err = -EADDRINUSE;
write_unlock_bh(&mrt_lock);
rtnl_unlock();
return err;
}
int ip6mr_sk_done(struct sock *sk)
{
int err = -EACCES;
struct net *net = sock_net(sk);
struct mr6_table *mrt;
rtnl_lock();
ip6mr_for_each_table(mrt, net) {
if (sk == mrt->mroute6_sk) {
write_lock_bh(&mrt_lock);
mrt->mroute6_sk = NULL;
net->ipv6.devconf_all->mc_forwarding--;
write_unlock_bh(&mrt_lock);
mroute_clean_tables(mrt);
err = 0;
break;
}
}
rtnl_unlock();
return err;
}
struct sock *mroute6_socket(struct net *net, struct sk_buff *skb)
{
struct mr6_table *mrt;
struct flowi6 fl6 = {
.flowi6_iif = skb->skb_iif,
.flowi6_oif = skb->dev->ifindex,
.flowi6_mark = skb->mark,
};
if (ip6mr_fib_lookup(net, &fl6, &mrt) < 0)
return NULL;
return mrt->mroute6_sk;
}
/*
* Socket options and virtual interface manipulation. The whole
* virtual interface system is a complete heap, but unfortunately
* that's how BSD mrouted happens to think. Maybe one day with a proper
* MOSPF/PIM router set up we can clean this up.
*/
int ip6_mroute_setsockopt(struct sock *sk, int optname, char __user *optval, unsigned int optlen)
{
int ret;
struct mif6ctl vif;
struct mf6cctl mfc;
mifi_t mifi;
struct net *net = sock_net(sk);
struct mr6_table *mrt;
mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT);
if (mrt == NULL)
return -ENOENT;
if (optname != MRT6_INIT) {
if (sk != mrt->mroute6_sk && !capable(CAP_NET_ADMIN))
return -EACCES;
}
switch (optname) {
case MRT6_INIT:
if (sk->sk_type != SOCK_RAW ||
inet_sk(sk)->inet_num != IPPROTO_ICMPV6)
return -EOPNOTSUPP;
if (optlen < sizeof(int))
return -EINVAL;
return ip6mr_sk_init(mrt, sk);
case MRT6_DONE:
return ip6mr_sk_done(sk);
case MRT6_ADD_MIF:
if (optlen < sizeof(vif))
return -EINVAL;
if (copy_from_user(&vif, optval, sizeof(vif)))
return -EFAULT;
if (vif.mif6c_mifi >= MAXMIFS)
return -ENFILE;
rtnl_lock();
ret = mif6_add(net, mrt, &vif, sk == mrt->mroute6_sk);
rtnl_unlock();
return ret;
case MRT6_DEL_MIF:
if (optlen < sizeof(mifi_t))
return -EINVAL;
if (copy_from_user(&mifi, optval, sizeof(mifi_t)))
return -EFAULT;
rtnl_lock();
ret = mif6_delete(mrt, mifi, NULL);
rtnl_unlock();
return ret;
/*
* Manipulate the forwarding caches. These live
* in a sort of kernel/user symbiosis.
*/
case MRT6_ADD_MFC:
case MRT6_DEL_MFC:
if (optlen < sizeof(mfc))
return -EINVAL;
if (copy_from_user(&mfc, optval, sizeof(mfc)))
return -EFAULT;
rtnl_lock();
if (optname == MRT6_DEL_MFC)
ret = ip6mr_mfc_delete(mrt, &mfc);
else
ret = ip6mr_mfc_add(net, mrt, &mfc, sk == mrt->mroute6_sk);
rtnl_unlock();
return ret;
/*
* Control PIM assert (to activate pim will activate assert)
*/
case MRT6_ASSERT:
{
int v;
if (get_user(v, (int __user *)optval))
return -EFAULT;
mrt->mroute_do_assert = !!v;
return 0;
}
#ifdef CONFIG_IPV6_PIMSM_V2
case MRT6_PIM:
{
int v;
if (get_user(v, (int __user *)optval))
return -EFAULT;
v = !!v;
rtnl_lock();
ret = 0;
if (v != mrt->mroute_do_pim) {
mrt->mroute_do_pim = v;
mrt->mroute_do_assert = v;
}
rtnl_unlock();
return ret;
}
#endif
#ifdef CONFIG_IPV6_MROUTE_MULTIPLE_TABLES
case MRT6_TABLE:
{
u32 v;
if (optlen != sizeof(u32))
return -EINVAL;
if (get_user(v, (u32 __user *)optval))
return -EFAULT;
if (sk == mrt->mroute6_sk)
return -EBUSY;
rtnl_lock();
ret = 0;
if (!ip6mr_new_table(net, v))
ret = -ENOMEM;
raw6_sk(sk)->ip6mr_table = v;
rtnl_unlock();
return ret;
}
#endif
/*
* Spurious command, or MRT6_VERSION which you cannot
* set.
*/
default:
return -ENOPROTOOPT;
}
}
/*
* Getsock opt support for the multicast routing system.
*/
int ip6_mroute_getsockopt(struct sock *sk, int optname, char __user *optval,
int __user *optlen)
{
int olr;
int val;
struct net *net = sock_net(sk);
struct mr6_table *mrt;
mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT);
if (mrt == NULL)
return -ENOENT;
switch (optname) {
case MRT6_VERSION:
val = 0x0305;
break;
#ifdef CONFIG_IPV6_PIMSM_V2
case MRT6_PIM:
val = mrt->mroute_do_pim;
break;
#endif
case MRT6_ASSERT:
val = mrt->mroute_do_assert;
break;
default:
return -ENOPROTOOPT;
}
if (get_user(olr, optlen))
return -EFAULT;
olr = min_t(int, olr, sizeof(int));
if (olr < 0)
return -EINVAL;
if (put_user(olr, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, olr))
return -EFAULT;
return 0;
}
/*
* The IP multicast ioctl support routines.
*/
int ip6mr_ioctl(struct sock *sk, int cmd, void __user *arg)
{
struct sioc_sg_req6 sr;
struct sioc_mif_req6 vr;
struct mif_device *vif;
struct mfc6_cache *c;
struct net *net = sock_net(sk);
struct mr6_table *mrt;
mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT);
if (mrt == NULL)
return -ENOENT;
switch (cmd) {
case SIOCGETMIFCNT_IN6:
if (copy_from_user(&vr, arg, sizeof(vr)))
return -EFAULT;
if (vr.mifi >= mrt->maxvif)
return -EINVAL;
read_lock(&mrt_lock);
vif = &mrt->vif6_table[vr.mifi];
if (MIF_EXISTS(mrt, vr.mifi)) {
vr.icount = vif->pkt_in;
vr.ocount = vif->pkt_out;
vr.ibytes = vif->bytes_in;
vr.obytes = vif->bytes_out;
read_unlock(&mrt_lock);
if (copy_to_user(arg, &vr, sizeof(vr)))
return -EFAULT;
return 0;
}
read_unlock(&mrt_lock);
return -EADDRNOTAVAIL;
case SIOCGETSGCNT_IN6:
if (copy_from_user(&sr, arg, sizeof(sr)))
return -EFAULT;
read_lock(&mrt_lock);
c = ip6mr_cache_find(mrt, &sr.src.sin6_addr, &sr.grp.sin6_addr);
if (c) {
sr.pktcnt = c->mfc_un.res.pkt;
sr.bytecnt = c->mfc_un.res.bytes;
sr.wrong_if = c->mfc_un.res.wrong_if;
read_unlock(&mrt_lock);
if (copy_to_user(arg, &sr, sizeof(sr)))
return -EFAULT;
return 0;
}
read_unlock(&mrt_lock);
return -EADDRNOTAVAIL;
default:
return -ENOIOCTLCMD;
}
}
#ifdef CONFIG_COMPAT
struct compat_sioc_sg_req6 {
struct sockaddr_in6 src;
struct sockaddr_in6 grp;
compat_ulong_t pktcnt;
compat_ulong_t bytecnt;
compat_ulong_t wrong_if;
};
struct compat_sioc_mif_req6 {
mifi_t mifi;
compat_ulong_t icount;
compat_ulong_t ocount;
compat_ulong_t ibytes;
compat_ulong_t obytes;
};
int ip6mr_compat_ioctl(struct sock *sk, unsigned int cmd, void __user *arg)
{
struct compat_sioc_sg_req6 sr;
struct compat_sioc_mif_req6 vr;
struct mif_device *vif;
struct mfc6_cache *c;
struct net *net = sock_net(sk);
struct mr6_table *mrt;
mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT);
if (mrt == NULL)
return -ENOENT;
switch (cmd) {
case SIOCGETMIFCNT_IN6:
if (copy_from_user(&vr, arg, sizeof(vr)))
return -EFAULT;
if (vr.mifi >= mrt->maxvif)
return -EINVAL;
read_lock(&mrt_lock);
vif = &mrt->vif6_table[vr.mifi];
if (MIF_EXISTS(mrt, vr.mifi)) {
vr.icount = vif->pkt_in;
vr.ocount = vif->pkt_out;
vr.ibytes = vif->bytes_in;
vr.obytes = vif->bytes_out;
read_unlock(&mrt_lock);
if (copy_to_user(arg, &vr, sizeof(vr)))
return -EFAULT;
return 0;
}
read_unlock(&mrt_lock);
return -EADDRNOTAVAIL;
case SIOCGETSGCNT_IN6:
if (copy_from_user(&sr, arg, sizeof(sr)))
return -EFAULT;
read_lock(&mrt_lock);
c = ip6mr_cache_find(mrt, &sr.src.sin6_addr, &sr.grp.sin6_addr);
if (c) {
sr.pktcnt = c->mfc_un.res.pkt;
sr.bytecnt = c->mfc_un.res.bytes;
sr.wrong_if = c->mfc_un.res.wrong_if;
read_unlock(&mrt_lock);
if (copy_to_user(arg, &sr, sizeof(sr)))
return -EFAULT;
return 0;
}
read_unlock(&mrt_lock);
return -EADDRNOTAVAIL;
default:
return -ENOIOCTLCMD;
}
}
#endif
static inline int ip6mr_forward2_finish(struct sk_buff *skb)
{
IP6_INC_STATS_BH(dev_net(skb_dst(skb)->dev), ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUTFORWDATAGRAMS);
return dst_output(skb);
}
/*
* Processing handlers for ip6mr_forward
*/
static int ip6mr_forward2(struct net *net, struct mr6_table *mrt,
struct sk_buff *skb, struct mfc6_cache *c, int vifi)
{
struct ipv6hdr *ipv6h;
struct mif_device *vif = &mrt->vif6_table[vifi];
struct net_device *dev;
struct dst_entry *dst;
struct flowi6 fl6;
if (vif->dev == NULL)
goto out_free;
#ifdef CONFIG_IPV6_PIMSM_V2
if (vif->flags & MIFF_REGISTER) {
vif->pkt_out++;
vif->bytes_out += skb->len;
vif->dev->stats.tx_bytes += skb->len;
vif->dev->stats.tx_packets++;
ip6mr_cache_report(mrt, skb, vifi, MRT6MSG_WHOLEPKT);
goto out_free;
}
#endif
ipv6h = ipv6_hdr(skb);
fl6 = (struct flowi6) {
.flowi6_oif = vif->link,
.daddr = ipv6h->daddr,
};
dst = ip6_route_output(net, NULL, &fl6);
if (!dst)
goto out_free;
skb_dst_drop(skb);
skb_dst_set(skb, dst);
/*
* RFC1584 teaches, that DVMRP/PIM router must deliver packets locally
* not only before forwarding, but after forwarding on all output
* interfaces. It is clear, if mrouter runs a multicasting
* program, it should receive packets not depending to what interface
* program is joined.
* If we will not make it, the program will have to join on all
* interfaces. On the other hand, multihoming host (or router, but
* not mrouter) cannot join to more than one interface - it will
* result in receiving multiple packets.
*/
dev = vif->dev;
skb->dev = dev;
vif->pkt_out++;
vif->bytes_out += skb->len;
/* We are about to write */
/* XXX: extension headers? */
if (skb_cow(skb, sizeof(*ipv6h) + LL_RESERVED_SPACE(dev)))
goto out_free;
ipv6h = ipv6_hdr(skb);
ipv6h->hop_limit--;
IP6CB(skb)->flags |= IP6SKB_FORWARDED;
return NF_HOOK(NFPROTO_IPV6, NF_INET_FORWARD, skb, skb->dev, dev,
ip6mr_forward2_finish);
out_free:
kfree_skb(skb);
return 0;
}
static int ip6mr_find_vif(struct mr6_table *mrt, struct net_device *dev)
{
int ct;
for (ct = mrt->maxvif - 1; ct >= 0; ct--) {
if (mrt->vif6_table[ct].dev == dev)
break;
}
return ct;
}
static int ip6_mr_forward(struct net *net, struct mr6_table *mrt,
struct sk_buff *skb, struct mfc6_cache *cache)
{
int psend = -1;
int vif, ct;
vif = cache->mf6c_parent;
cache->mfc_un.res.pkt++;
cache->mfc_un.res.bytes += skb->len;
/*
* Wrong interface: drop packet and (maybe) send PIM assert.
*/
if (mrt->vif6_table[vif].dev != skb->dev) {
int true_vifi;
cache->mfc_un.res.wrong_if++;
true_vifi = ip6mr_find_vif(mrt, skb->dev);
if (true_vifi >= 0 && mrt->mroute_do_assert &&
/* pimsm uses asserts, when switching from RPT to SPT,
so that we cannot check that packet arrived on an oif.
It is bad, but otherwise we would need to move pretty
large chunk of pimd to kernel. Ough... --ANK
*/
(mrt->mroute_do_pim ||
cache->mfc_un.res.ttls[true_vifi] < 255) &&
time_after(jiffies,
cache->mfc_un.res.last_assert + MFC_ASSERT_THRESH)) {
cache->mfc_un.res.last_assert = jiffies;
ip6mr_cache_report(mrt, skb, true_vifi, MRT6MSG_WRONGMIF);
}
goto dont_forward;
}
mrt->vif6_table[vif].pkt_in++;
mrt->vif6_table[vif].bytes_in += skb->len;
/*
* Forward the frame
*/
for (ct = cache->mfc_un.res.maxvif - 1; ct >= cache->mfc_un.res.minvif; ct--) {
if (ipv6_hdr(skb)->hop_limit > cache->mfc_un.res.ttls[ct]) {
if (psend != -1) {
struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
if (skb2)
ip6mr_forward2(net, mrt, skb2, cache, psend);
}
psend = ct;
}
}
if (psend != -1) {
ip6mr_forward2(net, mrt, skb, cache, psend);
return 0;
}
dont_forward:
kfree_skb(skb);
return 0;
}
/*
* Multicast packets for forwarding arrive here
*/
int ip6_mr_input(struct sk_buff *skb)
{
struct mfc6_cache *cache;
struct net *net = dev_net(skb->dev);
struct mr6_table *mrt;
struct flowi6 fl6 = {
.flowi6_iif = skb->dev->ifindex,
.flowi6_mark = skb->mark,
};
int err;
err = ip6mr_fib_lookup(net, &fl6, &mrt);
if (err < 0) {
kfree_skb(skb);
return err;
}
read_lock(&mrt_lock);
cache = ip6mr_cache_find(mrt,
&ipv6_hdr(skb)->saddr, &ipv6_hdr(skb)->daddr);
/*
* No usable cache entry
*/
if (cache == NULL) {
int vif;
vif = ip6mr_find_vif(mrt, skb->dev);
if (vif >= 0) {
int err = ip6mr_cache_unresolved(mrt, vif, skb);
read_unlock(&mrt_lock);
return err;
}
read_unlock(&mrt_lock);
kfree_skb(skb);
return -ENODEV;
}
ip6_mr_forward(net, mrt, skb, cache);
read_unlock(&mrt_lock);
return 0;
}
static int __ip6mr_fill_mroute(struct mr6_table *mrt, struct sk_buff *skb,
struct mfc6_cache *c, struct rtmsg *rtm)
{
int ct;
struct rtnexthop *nhp;
u8 *b = skb_tail_pointer(skb);
struct rtattr *mp_head;
/* If cache is unresolved, don't try to parse IIF and OIF */
if (c->mf6c_parent >= MAXMIFS)
return -ENOENT;
if (MIF_EXISTS(mrt, c->mf6c_parent))
RTA_PUT(skb, RTA_IIF, 4, &mrt->vif6_table[c->mf6c_parent].dev->ifindex);
mp_head = (struct rtattr *)skb_put(skb, RTA_LENGTH(0));
for (ct = c->mfc_un.res.minvif; ct < c->mfc_un.res.maxvif; ct++) {
if (MIF_EXISTS(mrt, ct) && c->mfc_un.res.ttls[ct] < 255) {
if (skb_tailroom(skb) < RTA_ALIGN(RTA_ALIGN(sizeof(*nhp)) + 4))
goto rtattr_failure;
nhp = (struct rtnexthop *)skb_put(skb, RTA_ALIGN(sizeof(*nhp)));
nhp->rtnh_flags = 0;
nhp->rtnh_hops = c->mfc_un.res.ttls[ct];
nhp->rtnh_ifindex = mrt->vif6_table[ct].dev->ifindex;
nhp->rtnh_len = sizeof(*nhp);
}
}
mp_head->rta_type = RTA_MULTIPATH;
mp_head->rta_len = skb_tail_pointer(skb) - (u8 *)mp_head;
rtm->rtm_type = RTN_MULTICAST;
return 1;
rtattr_failure:
nlmsg_trim(skb, b);
return -EMSGSIZE;
}
int ip6mr_get_route(struct net *net,
struct sk_buff *skb, struct rtmsg *rtm, int nowait)
{
int err;
struct mr6_table *mrt;
struct mfc6_cache *cache;
struct rt6_info *rt = (struct rt6_info *)skb_dst(skb);
mrt = ip6mr_get_table(net, RT6_TABLE_DFLT);
if (mrt == NULL)
return -ENOENT;
read_lock(&mrt_lock);
cache = ip6mr_cache_find(mrt, &rt->rt6i_src.addr, &rt->rt6i_dst.addr);
if (!cache) {
struct sk_buff *skb2;
struct ipv6hdr *iph;
struct net_device *dev;
int vif;
if (nowait) {
read_unlock(&mrt_lock);
return -EAGAIN;
}
dev = skb->dev;
if (dev == NULL || (vif = ip6mr_find_vif(mrt, dev)) < 0) {
read_unlock(&mrt_lock);
return -ENODEV;
}
/* really correct? */
skb2 = alloc_skb(sizeof(struct ipv6hdr), GFP_ATOMIC);
if (!skb2) {
read_unlock(&mrt_lock);
return -ENOMEM;
}
skb_reset_transport_header(skb2);
skb_put(skb2, sizeof(struct ipv6hdr));
skb_reset_network_header(skb2);
iph = ipv6_hdr(skb2);
iph->version = 0;
iph->priority = 0;
iph->flow_lbl[0] = 0;
iph->flow_lbl[1] = 0;
iph->flow_lbl[2] = 0;
iph->payload_len = 0;
iph->nexthdr = IPPROTO_NONE;
iph->hop_limit = 0;
ipv6_addr_copy(&iph->saddr, &rt->rt6i_src.addr);
ipv6_addr_copy(&iph->daddr, &rt->rt6i_dst.addr);
err = ip6mr_cache_unresolved(mrt, vif, skb2);
read_unlock(&mrt_lock);
return err;
}
if (!nowait && (rtm->rtm_flags&RTM_F_NOTIFY))
cache->mfc_flags |= MFC_NOTIFY;
err = __ip6mr_fill_mroute(mrt, skb, cache, rtm);
read_unlock(&mrt_lock);
return err;
}
static int ip6mr_fill_mroute(struct mr6_table *mrt, struct sk_buff *skb,
u32 pid, u32 seq, struct mfc6_cache *c)
{
struct nlmsghdr *nlh;
struct rtmsg *rtm;
nlh = nlmsg_put(skb, pid, seq, RTM_NEWROUTE, sizeof(*rtm), NLM_F_MULTI);
if (nlh == NULL)
return -EMSGSIZE;
rtm = nlmsg_data(nlh);
rtm->rtm_family = RTNL_FAMILY_IPMR;
rtm->rtm_dst_len = 128;
rtm->rtm_src_len = 128;
rtm->rtm_tos = 0;
rtm->rtm_table = mrt->id;
NLA_PUT_U32(skb, RTA_TABLE, mrt->id);
rtm->rtm_scope = RT_SCOPE_UNIVERSE;
rtm->rtm_protocol = RTPROT_UNSPEC;
rtm->rtm_flags = 0;
NLA_PUT(skb, RTA_SRC, 16, &c->mf6c_origin);
NLA_PUT(skb, RTA_DST, 16, &c->mf6c_mcastgrp);
if (__ip6mr_fill_mroute(mrt, skb, c, rtm) < 0)
goto nla_put_failure;
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static int ip6mr_rtm_dumproute(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct mr6_table *mrt;
struct mfc6_cache *mfc;
unsigned int t = 0, s_t;
unsigned int h = 0, s_h;
unsigned int e = 0, s_e;
s_t = cb->args[0];
s_h = cb->args[1];
s_e = cb->args[2];
read_lock(&mrt_lock);
ip6mr_for_each_table(mrt, net) {
if (t < s_t)
goto next_table;
if (t > s_t)
s_h = 0;
for (h = s_h; h < MFC6_LINES; h++) {
list_for_each_entry(mfc, &mrt->mfc6_cache_array[h], list) {
if (e < s_e)
goto next_entry;
if (ip6mr_fill_mroute(mrt, skb,
NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq,
mfc) < 0)
goto done;
next_entry:
e++;
}
e = s_e = 0;
}
s_h = 0;
next_table:
t++;
}
done:
read_unlock(&mrt_lock);
cb->args[2] = e;
cb->args[1] = h;
cb->args[0] = t;
return skb->len;
}
| gpl-2.0 |
TEAM-Gummy/android_kernel_samsung_d2 | drivers/media/video/msm_zsl/s5k4e1.c | 717 | 26348 | /* Copyright (c) 2011, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/delay.h>
#include <linux/debugfs.h>
#include <linux/types.h>
#include <linux/i2c.h>
#include <linux/uaccess.h>
#include <linux/miscdevice.h>
#include <linux/slab.h>
#include <linux/gpio.h>
#include <linux/bitops.h>
#include <mach/camera.h>
#include <media/msm_camera.h>
#include "s5k4e1.h"
/* 16bit address - 8 bit context register structure */
#define Q8 0x00000100
#define Q10 0x00000400
/* MCLK */
#define S5K4E1_MASTER_CLK_RATE 24000000
/* AF Total steps parameters */
#define S5K4E1_TOTAL_STEPS_NEAR_TO_FAR 32
#define S5K4E1_REG_PREV_FRAME_LEN_1 31
#define S5K4E1_REG_PREV_FRAME_LEN_2 32
#define S5K4E1_REG_PREV_LINE_LEN_1 33
#define S5K4E1_REG_PREV_LINE_LEN_2 34
#define S5K4E1_REG_SNAP_FRAME_LEN_1 15
#define S5K4E1_REG_SNAP_FRAME_LEN_2 16
#define S5K4E1_REG_SNAP_LINE_LEN_1 17
#define S5K4E1_REG_SNAP_LINE_LEN_2 18
#define MSB 1
#define LSB 0
struct s5k4e1_work_t {
struct work_struct work;
};
static struct s5k4e1_work_t *s5k4e1_sensorw;
static struct s5k4e1_work_t *s5k4e1_af_sensorw;
static struct i2c_client *s5k4e1_af_client;
static struct i2c_client *s5k4e1_client;
struct s5k4e1_ctrl_t {
const struct msm_camera_sensor_info *sensordata;
uint32_t sensormode;
uint32_t fps_divider;/* init to 1 * 0x00000400 */
uint32_t pict_fps_divider;/* init to 1 * 0x00000400 */
uint16_t fps;
uint16_t curr_lens_pos;
uint16_t curr_step_pos;
uint16_t my_reg_gain;
uint32_t my_reg_line_count;
uint16_t total_lines_per_frame;
enum s5k4e1_resolution_t prev_res;
enum s5k4e1_resolution_t pict_res;
enum s5k4e1_resolution_t curr_res;
enum s5k4e1_test_mode_t set_test;
};
static bool CSI_CONFIG;
static struct s5k4e1_ctrl_t *s5k4e1_ctrl;
static DECLARE_WAIT_QUEUE_HEAD(s5k4e1_wait_queue);
static DECLARE_WAIT_QUEUE_HEAD(s5k4e1_af_wait_queue);
DEFINE_MUTEX(s5k4e1_mut);
static uint16_t prev_line_length_pck;
static uint16_t prev_frame_length_lines;
static uint16_t snap_line_length_pck;
static uint16_t snap_frame_length_lines;
static int s5k4e1_i2c_rxdata(unsigned short saddr,
unsigned char *rxdata, int length)
{
struct i2c_msg msgs[] = {
{
.addr = saddr,
.flags = 0,
.len = 1,
.buf = rxdata,
},
{
.addr = saddr,
.flags = I2C_M_RD,
.len = 1,
.buf = rxdata,
},
};
if (i2c_transfer(s5k4e1_client->adapter, msgs, 2) < 0) {
CDBG("s5k4e1_i2c_rxdata faild 0x%x\n", saddr);
return -EIO;
}
return 0;
}
static int32_t s5k4e1_i2c_txdata(unsigned short saddr,
unsigned char *txdata, int length)
{
struct i2c_msg msg[] = {
{
.addr = saddr,
.flags = 0,
.len = length,
.buf = txdata,
},
};
if (i2c_transfer(s5k4e1_client->adapter, msg, 1) < 0) {
CDBG("s5k4e1_i2c_txdata faild 0x%x\n", saddr);
return -EIO;
}
return 0;
}
static int32_t s5k4e1_i2c_read(unsigned short raddr,
unsigned short *rdata, int rlen)
{
int32_t rc = 0;
unsigned char buf[2];
if (!rdata)
return -EIO;
memset(buf, 0, sizeof(buf));
buf[0] = (raddr & 0xFF00) >> 8;
buf[1] = (raddr & 0x00FF);
rc = s5k4e1_i2c_rxdata(s5k4e1_client->addr, buf, rlen);
if (rc < 0) {
CDBG("s5k4e1_i2c_read 0x%x failed!\n", raddr);
return rc;
}
*rdata = (rlen == 2 ? buf[0] << 8 | buf[1] : buf[0]);
CDBG("s5k4e1_i2c_read 0x%x val = 0x%x!\n", raddr, *rdata);
return rc;
}
static int32_t s5k4e1_i2c_write_b_sensor(unsigned short waddr, uint8_t bdata)
{
int32_t rc = -EFAULT;
unsigned char buf[3];
memset(buf, 0, sizeof(buf));
buf[0] = (waddr & 0xFF00) >> 8;
buf[1] = (waddr & 0x00FF);
buf[2] = bdata;
CDBG("i2c_write_b addr = 0x%x, val = 0x%x\n", waddr, bdata);
rc = s5k4e1_i2c_txdata(s5k4e1_client->addr, buf, 3);
if (rc < 0) {
CDBG("i2c_write_b failed, addr = 0x%x, val = 0x%x!\n",
waddr, bdata);
}
return rc;
}
static int32_t s5k4e1_i2c_write_b_table(struct s5k4e1_i2c_reg_conf const
*reg_conf_tbl, int num)
{
int i;
int32_t rc = -EIO;
for (i = 0; i < num; i++) {
rc = s5k4e1_i2c_write_b_sensor(reg_conf_tbl->waddr,
reg_conf_tbl->wdata);
if (rc < 0)
break;
reg_conf_tbl++;
}
return rc;
}
static int32_t s5k4e1_af_i2c_txdata(unsigned short saddr,
unsigned char *txdata, int length)
{
struct i2c_msg msg[] = {
{
.addr = saddr,
.flags = 0,
.len = length,
.buf = txdata,
},
};
if (i2c_transfer(s5k4e1_af_client->adapter, msg, 1) < 0) {
pr_err("s5k4e1_af_i2c_txdata faild 0x%x\n", saddr);
return -EIO;
}
return 0;
}
static int32_t s5k4e1_af_i2c_write_b_sensor(uint8_t waddr, uint8_t bdata)
{
int32_t rc = -EFAULT;
unsigned char buf[2];
memset(buf, 0, sizeof(buf));
buf[0] = waddr;
buf[1] = bdata;
CDBG("i2c_write_b addr = 0x%x, val = 0x%x\n", waddr, bdata);
rc = s5k4e1_af_i2c_txdata(s5k4e1_af_client->addr << 1, buf, 2);
if (rc < 0) {
pr_err("i2c_write_b failed, addr = 0x%x, val = 0x%x!\n",
waddr, bdata);
}
return rc;
}
static void s5k4e1_start_stream(void)
{
s5k4e1_i2c_write_b_sensor(0x0100, 0x01);/* streaming on */
}
static void s5k4e1_stop_stream(void)
{
s5k4e1_i2c_write_b_sensor(0x0100, 0x00);/* streaming off */
}
static void s5k4e1_group_hold_on(void)
{
s5k4e1_i2c_write_b_sensor(0x0104, 0x01);
}
static void s5k4e1_group_hold_off(void)
{
s5k4e1_i2c_write_b_sensor(0x0104, 0x0);
}
static void s5k4e1_get_pict_fps(uint16_t fps, uint16_t *pfps)
{
/* input fps is preview fps in Q8 format */
uint32_t divider, d1, d2;
d1 = (prev_frame_length_lines * 0x00000400) / snap_frame_length_lines;
d2 = (prev_line_length_pck * 0x00000400) / snap_line_length_pck;
divider = (d1 * d2) / 0x400;
/*Verify PCLK settings and frame sizes.*/
*pfps = (uint16_t) (fps * divider / 0x400);
}
static uint16_t s5k4e1_get_prev_lines_pf(void)
{
if (s5k4e1_ctrl->prev_res == QTR_SIZE)
return prev_frame_length_lines;
else
return snap_frame_length_lines;
}
static uint16_t s5k4e1_get_prev_pixels_pl(void)
{
if (s5k4e1_ctrl->prev_res == QTR_SIZE)
return prev_line_length_pck;
else
return snap_line_length_pck;
}
static uint16_t s5k4e1_get_pict_lines_pf(void)
{
if (s5k4e1_ctrl->pict_res == QTR_SIZE)
return prev_frame_length_lines;
else
return snap_frame_length_lines;
}
static uint16_t s5k4e1_get_pict_pixels_pl(void)
{
if (s5k4e1_ctrl->pict_res == QTR_SIZE)
return prev_line_length_pck;
else
return snap_line_length_pck;
}
static uint32_t s5k4e1_get_pict_max_exp_lc(void)
{
return snap_frame_length_lines * 24;
}
static int32_t s5k4e1_set_fps(struct fps_cfg *fps)
{
uint16_t total_lines_per_frame;
int32_t rc = 0;
s5k4e1_ctrl->fps_divider = fps->fps_div;
s5k4e1_ctrl->pict_fps_divider = fps->pict_fps_div;
if (s5k4e1_ctrl->sensormode == SENSOR_PREVIEW_MODE) {
total_lines_per_frame = (uint16_t)
((prev_frame_length_lines * s5k4e1_ctrl->fps_divider) / 0x400);
} else {
total_lines_per_frame = (uint16_t)
((snap_frame_length_lines * s5k4e1_ctrl->fps_divider) / 0x400);
}
s5k4e1_group_hold_on();
rc = s5k4e1_i2c_write_b_sensor(0x0340,
((total_lines_per_frame & 0xFF00) >> 8));
rc = s5k4e1_i2c_write_b_sensor(0x0341,
(total_lines_per_frame & 0x00FF));
s5k4e1_group_hold_off();
return rc;
}
static inline uint8_t s5k4e1_byte(uint16_t word, uint8_t offset)
{
return word >> (offset * BITS_PER_BYTE);
}
static int32_t s5k4e1_write_exp_gain(uint16_t gain, uint32_t line)
{
uint16_t max_legal_gain = 0x0200;
int32_t rc = 0;
static uint32_t fl_lines;
if (gain > max_legal_gain) {
pr_debug("Max legal gain Line:%d\n", __LINE__);
gain = max_legal_gain;
}
/* Analogue Gain */
s5k4e1_i2c_write_b_sensor(0x0204, s5k4e1_byte(gain, MSB));
s5k4e1_i2c_write_b_sensor(0x0205, s5k4e1_byte(gain, LSB));
if (line > (prev_frame_length_lines - 4)) {
fl_lines = line+4;
s5k4e1_group_hold_on();
s5k4e1_i2c_write_b_sensor(0x0340, s5k4e1_byte(fl_lines, MSB));
s5k4e1_i2c_write_b_sensor(0x0341, s5k4e1_byte(fl_lines, LSB));
/* Coarse Integration Time */
s5k4e1_i2c_write_b_sensor(0x0202, s5k4e1_byte(line, MSB));
s5k4e1_i2c_write_b_sensor(0x0203, s5k4e1_byte(line, LSB));
s5k4e1_group_hold_off();
} else if (line < (fl_lines - 4)) {
fl_lines = line+4;
if (fl_lines < prev_frame_length_lines)
fl_lines = prev_frame_length_lines;
s5k4e1_group_hold_on();
/* Coarse Integration Time */
s5k4e1_i2c_write_b_sensor(0x0202, s5k4e1_byte(line, MSB));
s5k4e1_i2c_write_b_sensor(0x0203, s5k4e1_byte(line, LSB));
s5k4e1_i2c_write_b_sensor(0x0340, s5k4e1_byte(fl_lines, MSB));
s5k4e1_i2c_write_b_sensor(0x0341, s5k4e1_byte(fl_lines, LSB));
s5k4e1_group_hold_off();
} else {
fl_lines = line+4;
s5k4e1_group_hold_on();
/* Coarse Integration Time */
s5k4e1_i2c_write_b_sensor(0x0202, s5k4e1_byte(line, MSB));
s5k4e1_i2c_write_b_sensor(0x0203, s5k4e1_byte(line, LSB));
s5k4e1_group_hold_off();
}
return rc;
}
static int32_t s5k4e1_set_pict_exp_gain(uint16_t gain, uint32_t line)
{
uint16_t max_legal_gain = 0x0200;
uint16_t min_ll_pck = 0x0AB2;
uint32_t ll_pck, fl_lines;
uint32_t ll_ratio;
int32_t rc = 0;
uint8_t gain_msb, gain_lsb;
uint8_t intg_time_msb, intg_time_lsb;
uint8_t ll_pck_msb, ll_pck_lsb;
if (gain > max_legal_gain) {
pr_debug("Max legal gain Line:%d\n", __LINE__);
gain = max_legal_gain;
}
pr_debug("s5k4e1_write_exp_gain : gain = %d line = %d\n", gain, line);
line = (uint32_t) (line * s5k4e1_ctrl->pict_fps_divider);
fl_lines = snap_frame_length_lines;
ll_pck = snap_line_length_pck;
if (fl_lines < (line / 0x400))
ll_ratio = (line / (fl_lines - 4));
else
ll_ratio = 0x400;
ll_pck = ll_pck * ll_ratio / 0x400;
line = line / ll_ratio;
if (ll_pck < min_ll_pck)
ll_pck = min_ll_pck;
gain_msb = (uint8_t) ((gain & 0xFF00) >> 8);
gain_lsb = (uint8_t) (gain & 0x00FF);
intg_time_msb = (uint8_t) ((line & 0xFF00) >> 8);
intg_time_lsb = (uint8_t) (line & 0x00FF);
ll_pck_msb = (uint8_t) ((ll_pck & 0xFF00) >> 8);
ll_pck_lsb = (uint8_t) (ll_pck & 0x00FF);
s5k4e1_group_hold_on();
s5k4e1_i2c_write_b_sensor(0x0204, gain_msb); /* Analogue Gain */
s5k4e1_i2c_write_b_sensor(0x0205, gain_lsb);
s5k4e1_i2c_write_b_sensor(0x0342, ll_pck_msb);
s5k4e1_i2c_write_b_sensor(0x0343, ll_pck_lsb);
/* Coarse Integration Time */
s5k4e1_i2c_write_b_sensor(0x0202, intg_time_msb);
s5k4e1_i2c_write_b_sensor(0x0203, intg_time_lsb);
s5k4e1_group_hold_off();
return rc;
}
static int32_t s5k4e1_move_focus(int direction,
int32_t num_steps)
{
int16_t step_direction, actual_step, next_position;
uint8_t code_val_msb, code_val_lsb;
if (direction == MOVE_NEAR)
step_direction = 16;
else
step_direction = -16;
actual_step = (int16_t) (step_direction * num_steps);
next_position = (int16_t) (s5k4e1_ctrl->curr_lens_pos + actual_step);
if (next_position > 1023)
next_position = 1023;
else if (next_position < 0)
next_position = 0;
code_val_msb = next_position >> 4;
code_val_lsb = (next_position & 0x000F) << 4;
if (s5k4e1_af_i2c_write_b_sensor(code_val_msb, code_val_lsb) < 0) {
pr_err("move_focus failed at line %d ...\n", __LINE__);
return -EBUSY;
}
s5k4e1_ctrl->curr_lens_pos = next_position;
return 0;
}
static int32_t s5k4e1_set_default_focus(uint8_t af_step)
{
int32_t rc = 0;
if (s5k4e1_ctrl->curr_step_pos != 0) {
rc = s5k4e1_move_focus(MOVE_FAR,
s5k4e1_ctrl->curr_step_pos);
} else {
s5k4e1_af_i2c_write_b_sensor(0x00, 0x00);
}
s5k4e1_ctrl->curr_lens_pos = 0;
s5k4e1_ctrl->curr_step_pos = 0;
return rc;
}
static int32_t s5k4e1_test(enum s5k4e1_test_mode_t mo)
{
int32_t rc = 0;
if (mo != TEST_OFF)
rc = s5k4e1_i2c_write_b_sensor(0x0601, (uint8_t) mo);
return rc;
}
static void s5k4e1_reset_sensor(void)
{
s5k4e1_i2c_write_b_sensor(0x103, 0x1);
}
static int32_t s5k4e1_sensor_setting(int update_type, int rt)
{
int32_t rc = 0;
struct msm_camera_csi_params s5k4e1_csi_params;
s5k4e1_stop_stream();
msleep(30);
if (update_type == REG_INIT) {
s5k4e1_reset_sensor();
s5k4e1_i2c_write_b_table(s5k4e1_regs.reg_mipi,
s5k4e1_regs.reg_mipi_size);
s5k4e1_i2c_write_b_table(s5k4e1_regs.rec_settings,
s5k4e1_regs.rec_size);
s5k4e1_i2c_write_b_table(s5k4e1_regs.reg_pll_p,
s5k4e1_regs.reg_pll_p_size);
CSI_CONFIG = 0;
} else if (update_type == UPDATE_PERIODIC) {
if (rt == RES_PREVIEW)
s5k4e1_i2c_write_b_table(s5k4e1_regs.reg_prev,
s5k4e1_regs.reg_prev_size);
else
s5k4e1_i2c_write_b_table(s5k4e1_regs.reg_snap,
s5k4e1_regs.reg_snap_size);
msleep(20);
if (!CSI_CONFIG) {
msm_camio_vfe_clk_rate_set(192000000);
s5k4e1_csi_params.data_format = CSI_10BIT;
s5k4e1_csi_params.lane_cnt = 1;
s5k4e1_csi_params.lane_assign = 0xe4;
s5k4e1_csi_params.dpcm_scheme = 0;
s5k4e1_csi_params.settle_cnt = 24;
rc = msm_camio_csi_config(&s5k4e1_csi_params);
msleep(20);
CSI_CONFIG = 1;
}
s5k4e1_start_stream();
msleep(30);
}
return rc;
}
static int32_t s5k4e1_video_config(int mode)
{
int32_t rc = 0;
int rt;
CDBG("video config\n");
/* change sensor resolution if needed */
if (s5k4e1_ctrl->prev_res == QTR_SIZE)
rt = RES_PREVIEW;
else
rt = RES_CAPTURE;
if (s5k4e1_sensor_setting(UPDATE_PERIODIC, rt) < 0)
return rc;
if (s5k4e1_ctrl->set_test) {
if (s5k4e1_test(s5k4e1_ctrl->set_test) < 0)
return rc;
}
s5k4e1_ctrl->curr_res = s5k4e1_ctrl->prev_res;
s5k4e1_ctrl->sensormode = mode;
return rc;
}
static int32_t s5k4e1_snapshot_config(int mode)
{
int32_t rc = 0;
int rt;
/*change sensor resolution if needed */
if (s5k4e1_ctrl->curr_res != s5k4e1_ctrl->pict_res) {
if (s5k4e1_ctrl->pict_res == QTR_SIZE)
rt = RES_PREVIEW;
else
rt = RES_CAPTURE;
if (s5k4e1_sensor_setting(UPDATE_PERIODIC, rt) < 0)
return rc;
}
s5k4e1_ctrl->curr_res = s5k4e1_ctrl->pict_res;
s5k4e1_ctrl->sensormode = mode;
return rc;
}
static int32_t s5k4e1_raw_snapshot_config(int mode)
{
int32_t rc = 0;
int rt;
/* change sensor resolution if needed */
if (s5k4e1_ctrl->curr_res != s5k4e1_ctrl->pict_res) {
if (s5k4e1_ctrl->pict_res == QTR_SIZE)
rt = RES_PREVIEW;
else
rt = RES_CAPTURE;
if (s5k4e1_sensor_setting(UPDATE_PERIODIC, rt) < 0)
return rc;
}
s5k4e1_ctrl->curr_res = s5k4e1_ctrl->pict_res;
s5k4e1_ctrl->sensormode = mode;
return rc;
}
static int32_t s5k4e1_set_sensor_mode(int mode,
int res)
{
int32_t rc = 0;
switch (mode) {
case SENSOR_PREVIEW_MODE:
rc = s5k4e1_video_config(mode);
break;
case SENSOR_SNAPSHOT_MODE:
rc = s5k4e1_snapshot_config(mode);
break;
case SENSOR_RAW_SNAPSHOT_MODE:
rc = s5k4e1_raw_snapshot_config(mode);
break;
default:
rc = -EINVAL;
break;
}
return rc;
}
static int32_t s5k4e1_power_down(void)
{
s5k4e1_stop_stream();
return 0;
}
static int s5k4e1_probe_init_done(const struct msm_camera_sensor_info *data)
{
CDBG("probe done\n");
gpio_free(data->sensor_reset);
return 0;
}
static int s5k4e1_probe_init_sensor(const struct msm_camera_sensor_info *data)
{
int32_t rc = 0;
uint16_t regaddress1 = 0x0000;
uint16_t regaddress2 = 0x0001;
uint16_t chipid1 = 0;
uint16_t chipid2 = 0;
CDBG("%s: %d\n", __func__, __LINE__);
CDBG(" s5k4e1_probe_init_sensor is called\n");
rc = gpio_request(data->sensor_reset, "s5k4e1");
CDBG(" s5k4e1_probe_init_sensor\n");
if (!rc) {
CDBG("sensor_reset = %d\n", rc);
gpio_direction_output(data->sensor_reset, 0);
msleep(50);
gpio_set_value_cansleep(data->sensor_reset, 1);
msleep(20);
} else
goto gpio_req_fail;
msleep(20);
s5k4e1_i2c_read(regaddress1, &chipid1, 1);
if (chipid1 != 0x4E) {
rc = -ENODEV;
CDBG("s5k4e1_probe_init_sensor fail chip id doesnot match\n");
goto init_probe_fail;
}
s5k4e1_i2c_read(regaddress2, &chipid2 , 1);
if (chipid2 != 0x10) {
rc = -ENODEV;
CDBG("s5k4e1_probe_init_sensor fail chip id doesnot match\n");
goto init_probe_fail;
}
CDBG("ID: %d\n", chipid1);
CDBG("ID: %d\n", chipid1);
return rc;
init_probe_fail:
CDBG(" s5k4e1_probe_init_sensor fails\n");
gpio_set_value_cansleep(data->sensor_reset, 0);
s5k4e1_probe_init_done(data);
if (data->vcm_enable) {
int ret = gpio_request(data->vcm_pwd, "s5k4e1_af");
if (!ret) {
gpio_direction_output(data->vcm_pwd, 0);
msleep(20);
gpio_free(data->vcm_pwd);
}
}
gpio_req_fail:
return rc;
}
int s5k4e1_sensor_open_init(const struct msm_camera_sensor_info *data)
{
int32_t rc = 0;
CDBG("%s: %d\n", __func__, __LINE__);
CDBG("Calling s5k4e1_sensor_open_init\n");
s5k4e1_ctrl = kzalloc(sizeof(struct s5k4e1_ctrl_t), GFP_KERNEL);
if (!s5k4e1_ctrl) {
CDBG("s5k4e1_init failed!\n");
rc = -ENOMEM;
goto init_done;
}
s5k4e1_ctrl->fps_divider = 1 * 0x00000400;
s5k4e1_ctrl->pict_fps_divider = 1 * 0x00000400;
s5k4e1_ctrl->set_test = TEST_OFF;
s5k4e1_ctrl->prev_res = QTR_SIZE;
s5k4e1_ctrl->pict_res = FULL_SIZE;
if (data)
s5k4e1_ctrl->sensordata = data;
prev_frame_length_lines =
((s5k4e1_regs.reg_prev[S5K4E1_REG_PREV_FRAME_LEN_1].wdata << 8) |
s5k4e1_regs.reg_prev[S5K4E1_REG_PREV_FRAME_LEN_2].wdata);
prev_line_length_pck =
(s5k4e1_regs.reg_prev[S5K4E1_REG_PREV_LINE_LEN_1].wdata << 8) |
s5k4e1_regs.reg_prev[S5K4E1_REG_PREV_LINE_LEN_2].wdata;
snap_frame_length_lines =
(s5k4e1_regs.reg_snap[S5K4E1_REG_SNAP_FRAME_LEN_1].wdata << 8) |
s5k4e1_regs.reg_snap[S5K4E1_REG_SNAP_FRAME_LEN_2].wdata;
snap_line_length_pck =
(s5k4e1_regs.reg_snap[S5K4E1_REG_SNAP_LINE_LEN_1].wdata << 8) |
s5k4e1_regs.reg_snap[S5K4E1_REG_SNAP_LINE_LEN_1].wdata;
/* enable mclk first */
msm_camio_clk_rate_set(S5K4E1_MASTER_CLK_RATE);
rc = s5k4e1_probe_init_sensor(data);
if (rc < 0)
goto init_fail;
CDBG("init settings\n");
if (s5k4e1_ctrl->prev_res == QTR_SIZE)
rc = s5k4e1_sensor_setting(REG_INIT, RES_PREVIEW);
else
rc = s5k4e1_sensor_setting(REG_INIT, RES_CAPTURE);
s5k4e1_ctrl->fps = 30 * Q8;
/* enable AF actuator */
if (s5k4e1_ctrl->sensordata->vcm_enable) {
CDBG("enable AF actuator, gpio = %d\n",
s5k4e1_ctrl->sensordata->vcm_pwd);
rc = gpio_request(s5k4e1_ctrl->sensordata->vcm_pwd,
"s5k4e1_af");
if (!rc)
gpio_direction_output(
s5k4e1_ctrl->sensordata->vcm_pwd,
1);
else {
pr_err("s5k4e1_ctrl gpio request failed!\n");
goto init_fail;
}
msleep(20);
rc = s5k4e1_set_default_focus(0);
if (rc < 0) {
gpio_direction_output(s5k4e1_ctrl->sensordata->vcm_pwd,
0);
gpio_free(s5k4e1_ctrl->sensordata->vcm_pwd);
}
}
if (rc < 0)
goto init_fail;
else
goto init_done;
init_fail:
CDBG("init_fail\n");
s5k4e1_probe_init_done(data);
init_done:
CDBG("init_done\n");
return rc;
}
static int s5k4e1_init_client(struct i2c_client *client)
{
/* Initialize the MSM_CAMI2C Chip */
init_waitqueue_head(&s5k4e1_wait_queue);
return 0;
}
static int s5k4e1_af_init_client(struct i2c_client *client)
{
/* Initialize the MSM_CAMI2C Chip */
init_waitqueue_head(&s5k4e1_af_wait_queue);
return 0;
}
static const struct i2c_device_id s5k4e1_af_i2c_id[] = {
{"s5k4e1_af", 0},
{ }
};
static int s5k4e1_af_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int rc = 0;
CDBG("s5k4e1_af_probe called!\n");
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
CDBG("i2c_check_functionality failed\n");
goto probe_failure;
}
s5k4e1_af_sensorw = kzalloc(sizeof(struct s5k4e1_work_t), GFP_KERNEL);
if (!s5k4e1_af_sensorw) {
CDBG("kzalloc failed.\n");
rc = -ENOMEM;
goto probe_failure;
}
i2c_set_clientdata(client, s5k4e1_af_sensorw);
s5k4e1_af_init_client(client);
s5k4e1_af_client = client;
msleep(50);
CDBG("s5k4e1_af_probe successed! rc = %d\n", rc);
return 0;
probe_failure:
CDBG("s5k4e1_af_probe failed! rc = %d\n", rc);
return rc;
}
static const struct i2c_device_id s5k4e1_i2c_id[] = {
{"s5k4e1", 0},
{ }
};
static int s5k4e1_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int rc = 0;
CDBG("s5k4e1_probe called!\n");
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
CDBG("i2c_check_functionality failed\n");
goto probe_failure;
}
s5k4e1_sensorw = kzalloc(sizeof(struct s5k4e1_work_t), GFP_KERNEL);
if (!s5k4e1_sensorw) {
CDBG("kzalloc failed.\n");
rc = -ENOMEM;
goto probe_failure;
}
i2c_set_clientdata(client, s5k4e1_sensorw);
s5k4e1_init_client(client);
s5k4e1_client = client;
msleep(50);
CDBG("s5k4e1_probe successed! rc = %d\n", rc);
return 0;
probe_failure:
CDBG("s5k4e1_probe failed! rc = %d\n", rc);
return rc;
}
static int __devexit s5k4e1_remove(struct i2c_client *client)
{
struct s5k4e1_work_t *sensorw = i2c_get_clientdata(client);
free_irq(client->irq, sensorw);
s5k4e1_client = NULL;
kfree(sensorw);
return 0;
}
static int __devexit s5k4e1_af_remove(struct i2c_client *client)
{
struct s5k4e1_work_t *s5k4e1_af = i2c_get_clientdata(client);
free_irq(client->irq, s5k4e1_af);
s5k4e1_af_client = NULL;
kfree(s5k4e1_af);
return 0;
}
static struct i2c_driver s5k4e1_i2c_driver = {
.id_table = s5k4e1_i2c_id,
.probe = s5k4e1_i2c_probe,
.remove = __exit_p(s5k4e1_i2c_remove),
.driver = {
.name = "s5k4e1",
},
};
static struct i2c_driver s5k4e1_af_i2c_driver = {
.id_table = s5k4e1_af_i2c_id,
.probe = s5k4e1_af_i2c_probe,
.remove = __exit_p(s5k4e1_af_i2c_remove),
.driver = {
.name = "s5k4e1_af",
},
};
int s5k4e1_sensor_config(void __user *argp)
{
struct sensor_cfg_data cdata;
long rc = 0;
if (copy_from_user(&cdata,
(void *)argp,
sizeof(struct sensor_cfg_data)))
return -EFAULT;
mutex_lock(&s5k4e1_mut);
CDBG("s5k4e1_sensor_config: cfgtype = %d\n",
cdata.cfgtype);
switch (cdata.cfgtype) {
case CFG_GET_PICT_FPS:
s5k4e1_get_pict_fps(
cdata.cfg.gfps.prevfps,
&(cdata.cfg.gfps.pictfps));
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_GET_PREV_L_PF:
cdata.cfg.prevl_pf =
s5k4e1_get_prev_lines_pf();
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_GET_PREV_P_PL:
cdata.cfg.prevp_pl =
s5k4e1_get_prev_pixels_pl();
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_GET_PICT_L_PF:
cdata.cfg.pictl_pf =
s5k4e1_get_pict_lines_pf();
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_GET_PICT_P_PL:
cdata.cfg.pictp_pl =
s5k4e1_get_pict_pixels_pl();
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_GET_PICT_MAX_EXP_LC:
cdata.cfg.pict_max_exp_lc =
s5k4e1_get_pict_max_exp_lc();
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_SET_FPS:
case CFG_SET_PICT_FPS:
rc = s5k4e1_set_fps(&(cdata.cfg.fps));
break;
case CFG_SET_EXP_GAIN:
rc = s5k4e1_write_exp_gain(cdata.cfg.exp_gain.gain,
cdata.cfg.exp_gain.line);
break;
case CFG_SET_PICT_EXP_GAIN:
rc = s5k4e1_set_pict_exp_gain(cdata.cfg.exp_gain.gain,
cdata.cfg.exp_gain.line);
break;
case CFG_SET_MODE:
rc = s5k4e1_set_sensor_mode(cdata.mode, cdata.rs);
break;
case CFG_PWR_DOWN:
rc = s5k4e1_power_down();
break;
case CFG_MOVE_FOCUS:
rc = s5k4e1_move_focus(cdata.cfg.focus.dir,
cdata.cfg.focus.steps);
break;
case CFG_SET_DEFAULT_FOCUS:
rc = s5k4e1_set_default_focus(cdata.cfg.focus.steps);
break;
case CFG_GET_AF_MAX_STEPS:
cdata.max_steps = S5K4E1_TOTAL_STEPS_NEAR_TO_FAR;
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_SET_EFFECT:
rc = s5k4e1_set_default_focus(cdata.cfg.effect);
break;
default:
rc = -EFAULT;
break;
}
mutex_unlock(&s5k4e1_mut);
return rc;
}
static int s5k4e1_sensor_release(void)
{
int rc = -EBADF;
mutex_lock(&s5k4e1_mut);
s5k4e1_power_down();
msleep(20);
gpio_set_value_cansleep(s5k4e1_ctrl->sensordata->sensor_reset, 0);
usleep_range(5000, 5100);
gpio_free(s5k4e1_ctrl->sensordata->sensor_reset);
if (s5k4e1_ctrl->sensordata->vcm_enable) {
gpio_set_value_cansleep(s5k4e1_ctrl->sensordata->vcm_pwd, 0);
gpio_free(s5k4e1_ctrl->sensordata->vcm_pwd);
}
kfree(s5k4e1_ctrl);
s5k4e1_ctrl = NULL;
CDBG("s5k4e1_release completed\n");
mutex_unlock(&s5k4e1_mut);
return rc;
}
static int s5k4e1_sensor_probe(const struct msm_camera_sensor_info *info,
struct msm_sensor_ctrl *s)
{
int rc = 0;
rc = i2c_add_driver(&s5k4e1_i2c_driver);
if (rc < 0 || s5k4e1_client == NULL) {
rc = -ENOTSUPP;
CDBG("I2C add driver failed");
goto probe_fail_1;
}
rc = i2c_add_driver(&s5k4e1_af_i2c_driver);
if (rc < 0 || s5k4e1_af_client == NULL) {
rc = -ENOTSUPP;
CDBG("I2C add driver failed");
goto probe_fail_2;
}
msm_camio_clk_rate_set(S5K4E1_MASTER_CLK_RATE);
rc = s5k4e1_probe_init_sensor(info);
if (rc < 0)
goto probe_fail_3;
s->s_init = s5k4e1_sensor_open_init;
s->s_release = s5k4e1_sensor_release;
s->s_config = s5k4e1_sensor_config;
s->s_mount_angle = info->sensor_platform_info->mount_angle;
gpio_set_value_cansleep(info->sensor_reset, 0);
s5k4e1_probe_init_done(info);
/* Keep vcm_pwd to OUT Low */
if (info->vcm_enable) {
rc = gpio_request(info->vcm_pwd, "s5k4e1_af");
if (!rc) {
gpio_direction_output(info->vcm_pwd, 0);
msleep(20);
gpio_free(info->vcm_pwd);
} else
return rc;
}
return rc;
probe_fail_3:
i2c_del_driver(&s5k4e1_af_i2c_driver);
probe_fail_2:
i2c_del_driver(&s5k4e1_i2c_driver);
probe_fail_1:
CDBG("s5k4e1_sensor_probe: SENSOR PROBE FAILS!\n");
return rc;
}
static int __devinit s5k4e1_probe(struct platform_device *pdev)
{
return msm_camera_drv_start(pdev, s5k4e1_sensor_probe);
}
static struct platform_driver msm_camera_driver = {
.probe = s5k4e1_probe,
.driver = {
.name = "msm_camera_s5k4e1",
.owner = THIS_MODULE,
},
};
static int __init s5k4e1_init(void)
{
return platform_driver_register(&msm_camera_driver);
}
module_init(s5k4e1_init);
MODULE_DESCRIPTION("Samsung 5 MP Bayer sensor driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
manumanfred/kernel_tegra | drivers/staging/vt6655/wpactl.c | 2765 | 27393 | /*
* Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*
* File: wpactl.c
*
* Purpose: handle wpa supplicant ioctl input/out functions
*
* Author: Lyndon Chen
*
* Date: Oct. 20, 2003
*
* Functions:
*
* Revision History:
*
*/
#include "wpactl.h"
#include "key.h"
#include "mac.h"
#include "device.h"
#include "wmgr.h"
#include "iocmd.h"
#include "iowpa.h"
#include "rf.h"
/*--------------------- Static Definitions -------------------------*/
#define VIAWGET_WPA_MAX_BUF_SIZE 1024
static const int frequency_list[] = {
2412, 2417, 2422, 2427, 2432, 2437, 2442,
2447, 2452, 2457, 2462, 2467, 2472, 2484
};
/*--------------------- Static Classes ----------------------------*/
/*--------------------- Static Variables --------------------------*/
//static int msglevel =MSG_LEVEL_DEBUG;
static int msglevel =MSG_LEVEL_INFO;
/*--------------------- Static Functions --------------------------*/
/*--------------------- Export Variables --------------------------*/
static void wpadev_setup(struct net_device *dev)
{
dev->type = ARPHRD_IEEE80211;
dev->hard_header_len = ETH_HLEN;
dev->mtu = 2048;
dev->addr_len = ETH_ALEN;
dev->tx_queue_len = 1000;
memset(dev->broadcast,0xFF, ETH_ALEN);
dev->flags = IFF_BROADCAST|IFF_MULTICAST;
}
/*
* Description:
* register netdev for wpa supplicant deamon
*
* Parameters:
* In:
* pDevice -
* enable -
* Out:
*
* Return Value:
*
*/
static int wpa_init_wpadev(PSDevice pDevice)
{
PSDevice wpadev_priv;
struct net_device *dev = pDevice->dev;
int ret=0;
pDevice->wpadev = alloc_netdev(sizeof(PSDevice), "vntwpa", wpadev_setup);
if (pDevice->wpadev == NULL)
return -ENOMEM;
wpadev_priv = netdev_priv(pDevice->wpadev);
*wpadev_priv = *pDevice;
memcpy(pDevice->wpadev->dev_addr, dev->dev_addr, ETH_ALEN);
pDevice->wpadev->base_addr = dev->base_addr;
pDevice->wpadev->irq = dev->irq;
pDevice->wpadev->mem_start = dev->mem_start;
pDevice->wpadev->mem_end = dev->mem_end;
ret = register_netdev(pDevice->wpadev);
if (ret) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%s: register_netdev(WPA) failed!\n",
dev->name);
free_netdev(pDevice->wpadev);
return -1;
}
if (pDevice->skb == NULL) {
pDevice->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
if (pDevice->skb == NULL)
return -ENOMEM;
}
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%s: Registered netdev %s for WPA management\n",
dev->name, pDevice->wpadev->name);
return 0;
}
/*
* Description:
* unregister net_device (wpadev)
*
* Parameters:
* In:
* pDevice -
* Out:
*
* Return Value:
*
*/
static int wpa_release_wpadev(PSDevice pDevice)
{
if (pDevice->skb) {
dev_kfree_skb(pDevice->skb);
pDevice->skb = NULL;
}
if (pDevice->wpadev) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%s: Netdevice %s unregistered\n",
pDevice->dev->name, pDevice->wpadev->name);
unregister_netdev(pDevice->wpadev);
free_netdev(pDevice->wpadev);
pDevice->wpadev = NULL;
}
return 0;
}
/*
* Description:
* Set enable/disable dev for wpa supplicant deamon
*
* Parameters:
* In:
* pDevice -
* val -
* Out:
*
* Return Value:
*
*/
int wpa_set_wpadev(PSDevice pDevice, int val)
{
if (val)
return wpa_init_wpadev(pDevice);
else
return wpa_release_wpadev(pDevice);
}
/*
* Description:
* Set WPA algorithm & keys
*
* Parameters:
* In:
* pDevice -
* param -
* Out:
*
* Return Value:
*
*/
int wpa_set_keys(PSDevice pDevice, void *ctx, bool fcpfkernel)
{
struct viawget_wpa_param *param=ctx;
PSMgmtObject pMgmt = pDevice->pMgmt;
unsigned long dwKeyIndex = 0;
unsigned char abyKey[MAX_KEY_LEN];
unsigned char abySeq[MAX_KEY_LEN];
QWORD KeyRSC;
// NDIS_802_11_KEY_RSC KeyRSC;
unsigned char byKeyDecMode = KEY_CTL_WEP;
int ret = 0;
int uu, ii;
if (param->u.wpa_key.alg_name > WPA_ALG_CCMP)
return -EINVAL;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "param->u.wpa_key.alg_name = %d \n", param->u.wpa_key.alg_name);
if (param->u.wpa_key.alg_name == WPA_ALG_NONE) {
pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
pDevice->bEncryptionEnable = false;
pDevice->byKeyIndex = 0;
pDevice->bTransmitKey = false;
KeyvRemoveAllWEPKey(&(pDevice->sKey), pDevice->PortOffset);
for (uu=0; uu<MAX_KEY_TABLE; uu++) {
MACvDisableKeyEntry(pDevice->PortOffset, uu);
}
return ret;
}
//spin_unlock_irq(&pDevice->lock);
if(param->u.wpa_key.key && fcpfkernel) {
memcpy(&abyKey[0], param->u.wpa_key.key, param->u.wpa_key.key_len);
}
else {
spin_unlock_irq(&pDevice->lock);
if (param->u.wpa_key.key &&
copy_from_user(&abyKey[0], param->u.wpa_key.key, param->u.wpa_key.key_len)) {
spin_lock_irq(&pDevice->lock);
return -EINVAL;
}
spin_lock_irq(&pDevice->lock);
}
dwKeyIndex = (unsigned long)(param->u.wpa_key.key_index);
if (param->u.wpa_key.alg_name == WPA_ALG_WEP) {
if (dwKeyIndex > 3) {
return -EINVAL;
}
else {
if (param->u.wpa_key.set_tx) {
pDevice->byKeyIndex = (unsigned char)dwKeyIndex;
pDevice->bTransmitKey = true;
dwKeyIndex |= (1 << 31);
}
KeybSetDefaultKey(&(pDevice->sKey),
dwKeyIndex & ~(BIT30 | USE_KEYRSC),
param->u.wpa_key.key_len,
NULL,
abyKey,
KEY_CTL_WEP,
pDevice->PortOffset,
pDevice->byLocalID);
}
pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
pDevice->bEncryptionEnable = true;
return ret;
}
//spin_unlock_irq(&pDevice->lock);
if(param->u.wpa_key.seq && fcpfkernel) {
memcpy(&abySeq[0], param->u.wpa_key.seq, param->u.wpa_key.seq_len);
}
else {
spin_unlock_irq(&pDevice->lock);
if (param->u.wpa_key.seq &&
copy_from_user(&abySeq[0], param->u.wpa_key.seq, param->u.wpa_key.seq_len)) {
spin_lock_irq(&pDevice->lock);
return -EINVAL;
}
spin_lock_irq(&pDevice->lock);
}
if (param->u.wpa_key.seq_len > 0) {
for (ii = 0 ; ii < param->u.wpa_key.seq_len ; ii++) {
if (ii < 4)
LODWORD(KeyRSC) |= (abySeq[ii] << (ii * 8));
else
HIDWORD(KeyRSC) |= (abySeq[ii] << ((ii-4) * 8));
//KeyRSC |= (abySeq[ii] << (ii * 8));
}
dwKeyIndex |= 1 << 29;
}
if (param->u.wpa_key.key_index >= MAX_GROUP_KEY) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "return dwKeyIndex > 3\n");
return -EINVAL;
}
if (param->u.wpa_key.alg_name == WPA_ALG_TKIP) {
pDevice->eEncryptionStatus = Ndis802_11Encryption2Enabled;
}
if (param->u.wpa_key.alg_name == WPA_ALG_CCMP) {
pDevice->eEncryptionStatus = Ndis802_11Encryption3Enabled;
}
if (param->u.wpa_key.set_tx)
dwKeyIndex |= (1 << 31);
if (pDevice->eEncryptionStatus == Ndis802_11Encryption3Enabled)
byKeyDecMode = KEY_CTL_CCMP;
else if (pDevice->eEncryptionStatus == Ndis802_11Encryption2Enabled)
byKeyDecMode = KEY_CTL_TKIP;
else
byKeyDecMode = KEY_CTL_WEP;
// Fix HCT test that set 256 bits KEY and Ndis802_11Encryption3Enabled
if (pDevice->eEncryptionStatus == Ndis802_11Encryption3Enabled) {
if (param->u.wpa_key.key_len == MAX_KEY_LEN)
byKeyDecMode = KEY_CTL_TKIP;
else if (param->u.wpa_key.key_len == WLAN_WEP40_KEYLEN)
byKeyDecMode = KEY_CTL_WEP;
else if (param->u.wpa_key.key_len == WLAN_WEP104_KEYLEN)
byKeyDecMode = KEY_CTL_WEP;
} else if (pDevice->eEncryptionStatus == Ndis802_11Encryption2Enabled) {
if (param->u.wpa_key.key_len == WLAN_WEP40_KEYLEN)
byKeyDecMode = KEY_CTL_WEP;
else if (param->u.wpa_key.key_len == WLAN_WEP104_KEYLEN)
byKeyDecMode = KEY_CTL_WEP;
}
// Check TKIP key length
if ((byKeyDecMode == KEY_CTL_TKIP) &&
(param->u.wpa_key.key_len != MAX_KEY_LEN)) {
// TKIP Key must be 256 bits
//DBG_PRN_WLAN03(("return NDIS_STATUS_INVALID_DATA - TKIP Key must be 256 bits\n"));
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "return- TKIP Key must be 256 bits!\n");
return -EINVAL;
}
// Check AES key length
if ((byKeyDecMode == KEY_CTL_CCMP) &&
(param->u.wpa_key.key_len != AES_KEY_LEN)) {
// AES Key must be 128 bits
//DBG_PRN_WLAN03(("return NDIS_STATUS_INVALID_DATA - AES Key must be 128 bits\n"));
return -EINVAL;
}
// spin_lock_irq(&pDevice->lock);
if (is_broadcast_ether_addr(¶m->addr[0]) || (param->addr == NULL)) {
// If is_broadcast_ether_addr, set the key as every key entry's group key.
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Groupe Key Assign.\n");
if ((KeybSetAllGroupKey(&(pDevice->sKey),
dwKeyIndex,
param->u.wpa_key.key_len,
(PQWORD) &(KeyRSC),
(unsigned char *)abyKey,
byKeyDecMode,
pDevice->PortOffset,
pDevice->byLocalID) == true) &&
(KeybSetDefaultKey(&(pDevice->sKey),
dwKeyIndex,
param->u.wpa_key.key_len,
(PQWORD) &(KeyRSC),
(unsigned char *)abyKey,
byKeyDecMode,
pDevice->PortOffset,
pDevice->byLocalID) == true) ) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "GROUP Key Assign.\n");
} else {
//DBG_PRN_WLAN03(("return NDIS_STATUS_INVALID_DATA -KeybSetDefaultKey Fail.0\n"));
// spin_unlock_irq(&pDevice->lock);
return -EINVAL;
}
} else {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Pairwise Key Assign.\n");
// BSSID not 0xffffffffffff
// Pairwise Key can't be WEP
if (byKeyDecMode == KEY_CTL_WEP) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Pairwise Key can't be WEP\n");
//spin_unlock_irq(&pDevice->lock);
return -EINVAL;
}
dwKeyIndex |= (1 << 30); // set pairwise key
if (pMgmt->eConfigMode == WMAC_CONFIG_IBSS_STA) {
//DBG_PRN_WLAN03(("return NDIS_STATUS_INVALID_DATA - WMAC_CONFIG_IBSS_STA\n"));
//spin_unlock_irq(&pDevice->lock);
return -EINVAL;
}
if (KeybSetKey(&(pDevice->sKey),
¶m->addr[0],
dwKeyIndex,
param->u.wpa_key.key_len,
(PQWORD) &(KeyRSC),
(unsigned char *)abyKey,
byKeyDecMode,
pDevice->PortOffset,
pDevice->byLocalID) == true) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Pairwise Key Set\n");
} else {
// Key Table Full
if (!compare_ether_addr(¶m->addr[0], pDevice->abyBSSID)) {
//DBG_PRN_WLAN03(("return NDIS_STATUS_INVALID_DATA -Key Table Full.2\n"));
//spin_unlock_irq(&pDevice->lock);
return -EINVAL;
} else {
// Save Key and configure just before associate/reassociate to BSSID
// we do not implement now
//spin_unlock_irq(&pDevice->lock);
return -EINVAL;
}
}
} // BSSID not 0xffffffffffff
if ((ret == 0) && ((param->u.wpa_key.set_tx) != 0)) {
pDevice->byKeyIndex = (unsigned char)param->u.wpa_key.key_index;
pDevice->bTransmitKey = true;
}
pDevice->bEncryptionEnable = true;
//spin_unlock_irq(&pDevice->lock);
/*
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " key=%x-%x-%x-%x-%x-xxxxx \n",
pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[byKeyIndex][0],
pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[byKeyIndex][1],
pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[byKeyIndex][2],
pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[byKeyIndex][3],
pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[byKeyIndex][4]
);
*/
return ret;
}
/*
* Description:
* enable wpa auth & mode
*
* Parameters:
* In:
* pDevice -
* param -
* Out:
*
* Return Value:
*
*/
static int wpa_set_wpa(PSDevice pDevice,
struct viawget_wpa_param *param)
{
PSMgmtObject pMgmt = pDevice->pMgmt;
int ret = 0;
pMgmt->eAuthenMode = WMAC_AUTH_OPEN;
pMgmt->bShareKeyAlgorithm = false;
return ret;
}
/*
* Description:
* set disassociate
*
* Parameters:
* In:
* pDevice -
* param -
* Out:
*
* Return Value:
*
*/
static int wpa_set_disassociate(PSDevice pDevice,
struct viawget_wpa_param *param)
{
PSMgmtObject pMgmt = pDevice->pMgmt;
int ret = 0;
spin_lock_irq(&pDevice->lock);
if (pDevice->bLinkPass) {
if (!memcmp(param->addr, pMgmt->abyCurrBSSID, 6))
bScheduleCommand((void *)pDevice, WLAN_CMD_DISASSOCIATE, NULL);
}
spin_unlock_irq(&pDevice->lock);
return ret;
}
/*
* Description:
* enable scan process
*
* Parameters:
* In:
* pDevice -
* param -
* Out:
*
* Return Value:
*
*/
static int wpa_set_scan(PSDevice pDevice,
struct viawget_wpa_param *param)
{
int ret = 0;
spin_lock_irq(&pDevice->lock);
BSSvClearBSSList((void *)pDevice, pDevice->bLinkPass);
bScheduleCommand((void *) pDevice, WLAN_CMD_BSSID_SCAN, NULL);
spin_unlock_irq(&pDevice->lock);
return ret;
}
/*
* Description:
* get bssid
*
* Parameters:
* In:
* pDevice -
* param -
* Out:
*
* Return Value:
*
*/
static int wpa_get_bssid(PSDevice pDevice,
struct viawget_wpa_param *param)
{
PSMgmtObject pMgmt = pDevice->pMgmt;
int ret = 0;
memcpy(param->u.wpa_associate.bssid, pMgmt->abyCurrBSSID , 6);
return ret;
}
/*
* Description:
* get bssid
*
* Parameters:
* In:
* pDevice -
* param -
* Out:
*
* Return Value:
*
*/
static int wpa_get_ssid(PSDevice pDevice,
struct viawget_wpa_param *param)
{
PSMgmtObject pMgmt = pDevice->pMgmt;
PWLAN_IE_SSID pItemSSID;
int ret = 0;
pItemSSID = (PWLAN_IE_SSID)pMgmt->abyCurrSSID;
memcpy(param->u.wpa_associate.ssid, pItemSSID->abySSID , pItemSSID->len);
param->u.wpa_associate.ssid_len = pItemSSID->len;
return ret;
}
/*
* Description:
* get scan results
*
* Parameters:
* In:
* pDevice -
* param -
* Out:
*
* Return Value:
*
*/
static int wpa_get_scan(PSDevice pDevice,
struct viawget_wpa_param *param)
{
struct viawget_scan_result *scan_buf;
PSMgmtObject pMgmt = pDevice->pMgmt;
PWLAN_IE_SSID pItemSSID;
PKnownBSS pBSS;
unsigned char *pBuf;
int ret = 0;
u16 count = 0;
u16 ii, jj;
#if 1
unsigned char *ptempBSS;
ptempBSS = kmalloc(sizeof(KnownBSS), (int)GFP_ATOMIC);
if (ptempBSS == NULL) {
printk("bubble sort kmalloc memory fail@@@\n");
ret = -ENOMEM;
return ret;
}
for (ii = 0; ii < MAX_BSS_NUM; ii++) {
for(jj=0;jj<MAX_BSS_NUM-ii-1;jj++) {
if((pMgmt->sBSSList[jj].bActive!=true) ||
((pMgmt->sBSSList[jj].uRSSI>pMgmt->sBSSList[jj+1].uRSSI) &&(pMgmt->sBSSList[jj+1].bActive!=false))) {
memcpy(ptempBSS,&pMgmt->sBSSList[jj],sizeof(KnownBSS));
memcpy(&pMgmt->sBSSList[jj],&pMgmt->sBSSList[jj+1],sizeof(KnownBSS));
memcpy(&pMgmt->sBSSList[jj+1],ptempBSS,sizeof(KnownBSS));
}
}
}
kfree(ptempBSS);
// printk("bubble sort result:\n");
//for (ii = 0; ii < MAX_BSS_NUM; ii++)
// printk("%d [%s]:RSSI=%d\n",ii,((PWLAN_IE_SSID)(pMgmt->sBSSList[ii].abySSID))->abySSID,
// pMgmt->sBSSList[ii].uRSSI);
#endif
//******mike:bubble sort by stronger RSSI*****//
count = 0;
pBSS = &(pMgmt->sBSSList[0]);
for (ii = 0; ii < MAX_BSS_NUM; ii++) {
pBSS = &(pMgmt->sBSSList[ii]);
if (!pBSS->bActive)
continue;
count++;
}
pBuf = kcalloc(count, sizeof(struct viawget_scan_result), (int)GFP_ATOMIC);
if (pBuf == NULL) {
ret = -ENOMEM;
return ret;
}
scan_buf = (struct viawget_scan_result *)pBuf;
pBSS = &(pMgmt->sBSSList[0]);
for (ii = 0, jj = 0; ii < MAX_BSS_NUM ; ii++) {
pBSS = &(pMgmt->sBSSList[ii]);
if (pBSS->bActive) {
if (jj >= count)
break;
memcpy(scan_buf->bssid, pBSS->abyBSSID, WLAN_BSSID_LEN);
pItemSSID = (PWLAN_IE_SSID)pBSS->abySSID;
memcpy(scan_buf->ssid, pItemSSID->abySSID, pItemSSID->len);
scan_buf->ssid_len = pItemSSID->len;
scan_buf->freq = frequency_list[pBSS->uChannel-1];
scan_buf->caps = pBSS->wCapInfo;
//scan_buf->caps = pBSS->wCapInfo;
//scan_buf->qual =
//scan_buf->noise =
//scan_buf->level =
//scan_buf->maxrate =
if (pBSS->wWPALen != 0) {
scan_buf->wpa_ie_len = pBSS->wWPALen;
memcpy(scan_buf->wpa_ie, pBSS->byWPAIE, pBSS->wWPALen);
}
if (pBSS->wRSNLen != 0) {
scan_buf->rsn_ie_len = pBSS->wRSNLen;
memcpy(scan_buf->rsn_ie, pBSS->byRSNIE, pBSS->wRSNLen);
}
scan_buf = (struct viawget_scan_result *)((unsigned char *)scan_buf + sizeof(struct viawget_scan_result));
jj ++;
}
}
if (jj < count)
count = jj;
if (copy_to_user(param->u.scan_results.buf, pBuf, sizeof(struct viawget_scan_result) * count)) {
ret = -EFAULT;
}
param->u.scan_results.scan_count = count;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " param->u.scan_results.scan_count = %d\n", count)
kfree(pBuf);
return ret;
}
/*
* Description:
* set associate with AP
*
* Parameters:
* In:
* pDevice -
* param -
* Out:
*
* Return Value:
*
*/
static int wpa_set_associate(PSDevice pDevice,
struct viawget_wpa_param *param)
{
PSMgmtObject pMgmt = pDevice->pMgmt;
PWLAN_IE_SSID pItemSSID;
unsigned char abyNullAddr[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
unsigned char abyWPAIE[64];
int ret = 0;
bool bWepEnabled=false;
// set key type & algorithm
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pairwise_suite = %d\n", param->u.wpa_associate.pairwise_suite);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "group_suite = %d\n", param->u.wpa_associate.group_suite);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "key_mgmt_suite = %d\n", param->u.wpa_associate.key_mgmt_suite);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "auth_alg = %d\n", param->u.wpa_associate.auth_alg);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "mode = %d\n", param->u.wpa_associate.mode);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "wpa_ie_len = %d\n", param->u.wpa_associate.wpa_ie_len);
if (param->u.wpa_associate.wpa_ie_len) {
if (!param->u.wpa_associate.wpa_ie)
return -EINVAL;
if (param->u.wpa_associate.wpa_ie_len > sizeof(abyWPAIE))
return -EINVAL;
if (copy_from_user(&abyWPAIE[0], param->u.wpa_associate.wpa_ie, param->u.wpa_associate.wpa_ie_len))
return -EFAULT;
}
if (param->u.wpa_associate.mode == 1)
pMgmt->eConfigMode = WMAC_CONFIG_IBSS_STA;
else
pMgmt->eConfigMode = WMAC_CONFIG_ESS_STA;
// set ssid
memset(pMgmt->abyDesireSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
pItemSSID = (PWLAN_IE_SSID)pMgmt->abyDesireSSID;
pItemSSID->byElementID = WLAN_EID_SSID;
pItemSSID->len = param->u.wpa_associate.ssid_len;
memcpy(pItemSSID->abySSID, param->u.wpa_associate.ssid, pItemSSID->len);
// set bssid
if (memcmp(param->u.wpa_associate.bssid, &abyNullAddr[0], 6) != 0)
memcpy(pMgmt->abyDesireBSSID, param->u.wpa_associate.bssid, 6);
else
{
bScheduleCommand((void *) pDevice, WLAN_CMD_BSSID_SCAN, pItemSSID->abySSID);
}
if (param->u.wpa_associate.wpa_ie_len == 0) {
if (param->u.wpa_associate.auth_alg & AUTH_ALG_SHARED_KEY)
pMgmt->eAuthenMode = WMAC_AUTH_SHAREKEY;
else
pMgmt->eAuthenMode = WMAC_AUTH_OPEN;
} else if (abyWPAIE[0] == RSN_INFO_ELEM) {
if (param->u.wpa_associate.key_mgmt_suite == KEY_MGMT_PSK)
pMgmt->eAuthenMode = WMAC_AUTH_WPA2PSK;
else
pMgmt->eAuthenMode = WMAC_AUTH_WPA2;
} else {
if (param->u.wpa_associate.key_mgmt_suite == KEY_MGMT_WPA_NONE)
pMgmt->eAuthenMode = WMAC_AUTH_WPANONE;
else if (param->u.wpa_associate.key_mgmt_suite == KEY_MGMT_PSK)
pMgmt->eAuthenMode = WMAC_AUTH_WPAPSK;
else
pMgmt->eAuthenMode = WMAC_AUTH_WPA;
}
switch (param->u.wpa_associate.pairwise_suite) {
case CIPHER_CCMP:
pDevice->eEncryptionStatus = Ndis802_11Encryption3Enabled;
break;
case CIPHER_TKIP:
pDevice->eEncryptionStatus = Ndis802_11Encryption2Enabled;
break;
case CIPHER_WEP40:
case CIPHER_WEP104:
pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
bWepEnabled=true;
break;
case CIPHER_NONE:
if (param->u.wpa_associate.group_suite == CIPHER_CCMP)
pDevice->eEncryptionStatus = Ndis802_11Encryption3Enabled;
else
pDevice->eEncryptionStatus = Ndis802_11Encryption2Enabled;
break;
default:
pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
}
//DavidWang add for WPA_supplicant support open/share mode
if (pMgmt->eAuthenMode == WMAC_AUTH_SHAREKEY) {
pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
//pMgmt->eAuthenMode = WMAC_AUTH_SHAREKEY;
pMgmt->bShareKeyAlgorithm = true;
}
else if (pMgmt->eAuthenMode == WMAC_AUTH_OPEN) {
if(!bWepEnabled) pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
else pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
//pMgmt->eAuthenMode = WMAC_AUTH_OPEN;
//pMgmt->bShareKeyAlgorithm = false; //20080717-06,<Modify> by chester//Fix Open mode, WEP encrytion
}
//mike save old encryption status
pDevice->eOldEncryptionStatus = pDevice->eEncryptionStatus;
if (pDevice->eEncryptionStatus != Ndis802_11EncryptionDisabled)
pDevice->bEncryptionEnable = true;
else
pDevice->bEncryptionEnable = false;
if (!((pMgmt->eAuthenMode == WMAC_AUTH_SHAREKEY) ||
((pMgmt->eAuthenMode == WMAC_AUTH_OPEN) && (bWepEnabled==true))) ) //DavidWang //20080717-06,<Modify> by chester//Not to initial WEP
KeyvInitTable(&pDevice->sKey, pDevice->PortOffset);
spin_lock_irq(&pDevice->lock);
pDevice->bLinkPass = false;
memset(pMgmt->abyCurrBSSID, 0, 6);
pMgmt->eCurrState = WMAC_STATE_IDLE;
netif_stop_queue(pDevice->dev);
//20080701-02,<Add> by Mike Liu
/*******search if ap_scan=2 ,which is associating request in hidden ssid mode ****/
{
PKnownBSS pCurr = NULL;
pCurr = BSSpSearchBSSList(pDevice,
pMgmt->abyDesireBSSID,
pMgmt->abyDesireSSID,
pMgmt->eConfigPHYMode
);
if (pCurr == NULL){
printk("wpa_set_associate---->hidden mode site survey before associate.......\n");
bScheduleCommand((void *) pDevice, WLAN_CMD_BSSID_SCAN, pMgmt->abyDesireSSID);
}
}
/****************************************************************/
bScheduleCommand((void *) pDevice, WLAN_CMD_SSID, NULL);
spin_unlock_irq(&pDevice->lock);
return ret;
}
/*
* Description:
* wpa_ioctl main function supported for wpa supplicant
*
* Parameters:
* In:
* pDevice -
* iw_point -
* Out:
*
* Return Value:
*
*/
int wpa_ioctl(PSDevice pDevice, struct iw_point *p)
{
struct viawget_wpa_param *param;
int ret = 0;
int wpa_ioctl = 0;
if (p->length < sizeof(struct viawget_wpa_param) ||
p->length > VIAWGET_WPA_MAX_BUF_SIZE || !p->pointer)
return -EINVAL;
param = kmalloc((int)p->length, (int)GFP_KERNEL);
if (param == NULL)
return -ENOMEM;
if (copy_from_user(param, p->pointer, p->length)) {
ret = -EFAULT;
goto out;
}
switch (param->cmd) {
case VIAWGET_SET_WPA:
ret = wpa_set_wpa(pDevice, param);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_SET_WPA \n");
break;
case VIAWGET_SET_KEY:
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_SET_KEY \n");
spin_lock_irq(&pDevice->lock);
ret = wpa_set_keys(pDevice, param, false);
spin_unlock_irq(&pDevice->lock);
break;
case VIAWGET_SET_SCAN:
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_SET_SCAN \n");
ret = wpa_set_scan(pDevice, param);
break;
case VIAWGET_GET_SCAN:
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_GET_SCAN\n");
ret = wpa_get_scan(pDevice, param);
wpa_ioctl = 1;
break;
case VIAWGET_GET_SSID:
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_GET_SSID \n");
ret = wpa_get_ssid(pDevice, param);
wpa_ioctl = 1;
break;
case VIAWGET_GET_BSSID:
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_GET_BSSID \n");
ret = wpa_get_bssid(pDevice, param);
wpa_ioctl = 1;
break;
case VIAWGET_SET_ASSOCIATE:
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_SET_ASSOCIATE \n");
ret = wpa_set_associate(pDevice, param);
break;
case VIAWGET_SET_DISASSOCIATE:
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_SET_DISASSOCIATE \n");
ret = wpa_set_disassociate(pDevice, param);
break;
case VIAWGET_SET_DROP_UNENCRYPT:
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_SET_DROP_UNENCRYPT \n");
break;
case VIAWGET_SET_DEAUTHENTICATE:
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_SET_DEAUTHENTICATE \n");
break;
default:
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "wpa_ioctl: unknown cmd=%d\n",
param->cmd);
return -EOPNOTSUPP;
break;
}
if ((ret == 0) && wpa_ioctl) {
if (copy_to_user(p->pointer, param, p->length)) {
ret = -EFAULT;
goto out;
}
}
out:
kfree(param);
return ret;
}
| gpl-2.0 |
CitrusB/android_kernel_samsung_s6810p | sound/spi/at73c213.c | 3021 | 28412 | /*
* Driver for AT73C213 16-bit stereo DAC connected to Atmel SSC
*
* Copyright (C) 2006-2007 Atmel Norway
*
* 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 DEBUG*/
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <sound/initval.h>
#include <sound/control.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <linux/atmel-ssc.h>
#include <linux/spi/spi.h>
#include <linux/spi/at73c213.h>
#include "at73c213.h"
#define BITRATE_MIN 8000 /* Hardware limit? */
#define BITRATE_TARGET CONFIG_SND_AT73C213_TARGET_BITRATE
#define BITRATE_MAX 50000 /* Hardware limit. */
/* Initial (hardware reset) AT73C213 register values. */
static u8 snd_at73c213_original_image[18] =
{
0x00, /* 00 - CTRL */
0x05, /* 01 - LLIG */
0x05, /* 02 - RLIG */
0x08, /* 03 - LPMG */
0x08, /* 04 - RPMG */
0x00, /* 05 - LLOG */
0x00, /* 06 - RLOG */
0x22, /* 07 - OLC */
0x09, /* 08 - MC */
0x00, /* 09 - CSFC */
0x00, /* 0A - MISC */
0x00, /* 0B - */
0x00, /* 0C - PRECH */
0x05, /* 0D - AUXG */
0x00, /* 0E - */
0x00, /* 0F - */
0x00, /* 10 - RST */
0x00, /* 11 - PA_CTRL */
};
struct snd_at73c213 {
struct snd_card *card;
struct snd_pcm *pcm;
struct snd_pcm_substream *substream;
struct at73c213_board_info *board;
int irq;
int period;
unsigned long bitrate;
struct ssc_device *ssc;
struct spi_device *spi;
u8 spi_wbuffer[2];
u8 spi_rbuffer[2];
/* Image of the SPI registers in AT73C213. */
u8 reg_image[18];
/* Protect SSC registers against concurrent access. */
spinlock_t lock;
/* Protect mixer registers against concurrent access. */
struct mutex mixer_lock;
};
#define get_chip(card) ((struct snd_at73c213 *)card->private_data)
static int
snd_at73c213_write_reg(struct snd_at73c213 *chip, u8 reg, u8 val)
{
struct spi_message msg;
struct spi_transfer msg_xfer = {
.len = 2,
.cs_change = 0,
};
int retval;
spi_message_init(&msg);
chip->spi_wbuffer[0] = reg;
chip->spi_wbuffer[1] = val;
msg_xfer.tx_buf = chip->spi_wbuffer;
msg_xfer.rx_buf = chip->spi_rbuffer;
spi_message_add_tail(&msg_xfer, &msg);
retval = spi_sync(chip->spi, &msg);
if (!retval)
chip->reg_image[reg] = val;
return retval;
}
static struct snd_pcm_hardware snd_at73c213_playback_hw = {
.info = SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER,
.formats = SNDRV_PCM_FMTBIT_S16_BE,
.rates = SNDRV_PCM_RATE_CONTINUOUS,
.rate_min = 8000, /* Replaced by chip->bitrate later. */
.rate_max = 50000, /* Replaced by chip->bitrate later. */
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = 64 * 1024 - 1,
.period_bytes_min = 512,
.period_bytes_max = 64 * 1024 - 1,
.periods_min = 4,
.periods_max = 1024,
};
/*
* Calculate and set bitrate and divisions.
*/
static int snd_at73c213_set_bitrate(struct snd_at73c213 *chip)
{
unsigned long ssc_rate = clk_get_rate(chip->ssc->clk);
unsigned long dac_rate_new, ssc_div;
int status;
unsigned long ssc_div_max, ssc_div_min;
int max_tries;
/*
* We connect two clocks here, picking divisors so the I2S clocks
* out data at the same rate the DAC clocks it in ... and as close
* as practical to the desired target rate.
*
* The DAC master clock (MCLK) is programmable, and is either 256
* or (not here) 384 times the I2S output clock (BCLK).
*/
/* SSC clock / (bitrate * stereo * 16-bit). */
ssc_div = ssc_rate / (BITRATE_TARGET * 2 * 16);
ssc_div_min = ssc_rate / (BITRATE_MAX * 2 * 16);
ssc_div_max = ssc_rate / (BITRATE_MIN * 2 * 16);
max_tries = (ssc_div_max - ssc_div_min) / 2;
if (max_tries < 1)
max_tries = 1;
/* ssc_div must be even. */
ssc_div = (ssc_div + 1) & ~1UL;
if ((ssc_rate / (ssc_div * 2 * 16)) < BITRATE_MIN) {
ssc_div -= 2;
if ((ssc_rate / (ssc_div * 2 * 16)) > BITRATE_MAX)
return -ENXIO;
}
/* Search for a possible bitrate. */
do {
/* SSC clock / (ssc divider * 16-bit * stereo). */
if ((ssc_rate / (ssc_div * 2 * 16)) < BITRATE_MIN)
return -ENXIO;
/* 256 / (2 * 16) = 8 */
dac_rate_new = 8 * (ssc_rate / ssc_div);
status = clk_round_rate(chip->board->dac_clk, dac_rate_new);
if (status < 0)
return status;
/* Ignore difference smaller than 256 Hz. */
if ((status/256) == (dac_rate_new/256))
goto set_rate;
ssc_div += 2;
} while (--max_tries);
/* Not able to find a valid bitrate. */
return -ENXIO;
set_rate:
status = clk_set_rate(chip->board->dac_clk, status);
if (status < 0)
return status;
/* Set divider in SSC device. */
ssc_writel(chip->ssc->regs, CMR, ssc_div/2);
/* SSC clock / (ssc divider * 16-bit * stereo). */
chip->bitrate = ssc_rate / (ssc_div * 16 * 2);
dev_info(&chip->spi->dev,
"at73c213: supported bitrate is %lu (%lu divider)\n",
chip->bitrate, ssc_div);
return 0;
}
static int snd_at73c213_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_at73c213 *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
/* ensure buffer_size is a multiple of period_size */
err = snd_pcm_hw_constraint_integer(runtime,
SNDRV_PCM_HW_PARAM_PERIODS);
if (err < 0)
return err;
snd_at73c213_playback_hw.rate_min = chip->bitrate;
snd_at73c213_playback_hw.rate_max = chip->bitrate;
runtime->hw = snd_at73c213_playback_hw;
chip->substream = substream;
return 0;
}
static int snd_at73c213_pcm_close(struct snd_pcm_substream *substream)
{
struct snd_at73c213 *chip = snd_pcm_substream_chip(substream);
chip->substream = NULL;
return 0;
}
static int snd_at73c213_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct snd_at73c213 *chip = snd_pcm_substream_chip(substream);
int channels = params_channels(hw_params);
int val;
val = ssc_readl(chip->ssc->regs, TFMR);
val = SSC_BFINS(TFMR_DATNB, channels - 1, val);
ssc_writel(chip->ssc->regs, TFMR, val);
return snd_pcm_lib_malloc_pages(substream,
params_buffer_bytes(hw_params));
}
static int snd_at73c213_pcm_hw_free(struct snd_pcm_substream *substream)
{
return snd_pcm_lib_free_pages(substream);
}
static int snd_at73c213_pcm_prepare(struct snd_pcm_substream *substream)
{
struct snd_at73c213 *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int block_size;
block_size = frames_to_bytes(runtime, runtime->period_size);
chip->period = 0;
ssc_writel(chip->ssc->regs, PDC_TPR,
(long)runtime->dma_addr);
ssc_writel(chip->ssc->regs, PDC_TCR,
runtime->period_size * runtime->channels);
ssc_writel(chip->ssc->regs, PDC_TNPR,
(long)runtime->dma_addr + block_size);
ssc_writel(chip->ssc->regs, PDC_TNCR,
runtime->period_size * runtime->channels);
return 0;
}
static int snd_at73c213_pcm_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct snd_at73c213 *chip = snd_pcm_substream_chip(substream);
int retval = 0;
spin_lock(&chip->lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
ssc_writel(chip->ssc->regs, IER, SSC_BIT(IER_ENDTX));
ssc_writel(chip->ssc->regs, PDC_PTCR, SSC_BIT(PDC_PTCR_TXTEN));
break;
case SNDRV_PCM_TRIGGER_STOP:
ssc_writel(chip->ssc->regs, PDC_PTCR, SSC_BIT(PDC_PTCR_TXTDIS));
ssc_writel(chip->ssc->regs, IDR, SSC_BIT(IDR_ENDTX));
break;
default:
dev_dbg(&chip->spi->dev, "spurious command %x\n", cmd);
retval = -EINVAL;
break;
}
spin_unlock(&chip->lock);
return retval;
}
static snd_pcm_uframes_t
snd_at73c213_pcm_pointer(struct snd_pcm_substream *substream)
{
struct snd_at73c213 *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
snd_pcm_uframes_t pos;
unsigned long bytes;
bytes = ssc_readl(chip->ssc->regs, PDC_TPR)
- (unsigned long)runtime->dma_addr;
pos = bytes_to_frames(runtime, bytes);
if (pos >= runtime->buffer_size)
pos -= runtime->buffer_size;
return pos;
}
static struct snd_pcm_ops at73c213_playback_ops = {
.open = snd_at73c213_pcm_open,
.close = snd_at73c213_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_at73c213_pcm_hw_params,
.hw_free = snd_at73c213_pcm_hw_free,
.prepare = snd_at73c213_pcm_prepare,
.trigger = snd_at73c213_pcm_trigger,
.pointer = snd_at73c213_pcm_pointer,
};
static int __devinit snd_at73c213_pcm_new(struct snd_at73c213 *chip, int device)
{
struct snd_pcm *pcm;
int retval;
retval = snd_pcm_new(chip->card, chip->card->shortname,
device, 1, 0, &pcm);
if (retval < 0)
goto out;
pcm->private_data = chip;
pcm->info_flags = SNDRV_PCM_INFO_BLOCK_TRANSFER;
strcpy(pcm->name, "at73c213");
chip->pcm = pcm;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &at73c213_playback_ops);
retval = snd_pcm_lib_preallocate_pages_for_all(chip->pcm,
SNDRV_DMA_TYPE_DEV, &chip->ssc->pdev->dev,
64 * 1024, 64 * 1024);
out:
return retval;
}
static irqreturn_t snd_at73c213_interrupt(int irq, void *dev_id)
{
struct snd_at73c213 *chip = dev_id;
struct snd_pcm_runtime *runtime = chip->substream->runtime;
u32 status;
int offset;
int block_size;
int next_period;
int retval = IRQ_NONE;
spin_lock(&chip->lock);
block_size = frames_to_bytes(runtime, runtime->period_size);
status = ssc_readl(chip->ssc->regs, IMR);
if (status & SSC_BIT(IMR_ENDTX)) {
chip->period++;
if (chip->period == runtime->periods)
chip->period = 0;
next_period = chip->period + 1;
if (next_period == runtime->periods)
next_period = 0;
offset = block_size * next_period;
ssc_writel(chip->ssc->regs, PDC_TNPR,
(long)runtime->dma_addr + offset);
ssc_writel(chip->ssc->regs, PDC_TNCR,
runtime->period_size * runtime->channels);
retval = IRQ_HANDLED;
}
ssc_readl(chip->ssc->regs, IMR);
spin_unlock(&chip->lock);
if (status & SSC_BIT(IMR_ENDTX))
snd_pcm_period_elapsed(chip->substream);
return retval;
}
/*
* Mixer functions.
*/
static int snd_at73c213_mono_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_at73c213 *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
mutex_lock(&chip->mixer_lock);
ucontrol->value.integer.value[0] =
(chip->reg_image[reg] >> shift) & mask;
if (invert)
ucontrol->value.integer.value[0] =
mask - ucontrol->value.integer.value[0];
mutex_unlock(&chip->mixer_lock);
return 0;
}
static int snd_at73c213_mono_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_at73c213 *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
int change, retval;
unsigned short val;
val = (ucontrol->value.integer.value[0] & mask);
if (invert)
val = mask - val;
val <<= shift;
mutex_lock(&chip->mixer_lock);
val = (chip->reg_image[reg] & ~(mask << shift)) | val;
change = val != chip->reg_image[reg];
retval = snd_at73c213_write_reg(chip, reg, val);
mutex_unlock(&chip->mixer_lock);
if (retval)
return retval;
return change;
}
static int snd_at73c213_stereo_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
int mask = (kcontrol->private_value >> 24) & 0xff;
if (mask == 1)
uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
else
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = mask;
return 0;
}
static int snd_at73c213_stereo_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_at73c213 *chip = snd_kcontrol_chip(kcontrol);
int left_reg = kcontrol->private_value & 0xff;
int right_reg = (kcontrol->private_value >> 8) & 0xff;
int shift_left = (kcontrol->private_value >> 16) & 0x07;
int shift_right = (kcontrol->private_value >> 19) & 0x07;
int mask = (kcontrol->private_value >> 24) & 0xff;
int invert = (kcontrol->private_value >> 22) & 1;
mutex_lock(&chip->mixer_lock);
ucontrol->value.integer.value[0] =
(chip->reg_image[left_reg] >> shift_left) & mask;
ucontrol->value.integer.value[1] =
(chip->reg_image[right_reg] >> shift_right) & mask;
if (invert) {
ucontrol->value.integer.value[0] =
mask - ucontrol->value.integer.value[0];
ucontrol->value.integer.value[1] =
mask - ucontrol->value.integer.value[1];
}
mutex_unlock(&chip->mixer_lock);
return 0;
}
static int snd_at73c213_stereo_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_at73c213 *chip = snd_kcontrol_chip(kcontrol);
int left_reg = kcontrol->private_value & 0xff;
int right_reg = (kcontrol->private_value >> 8) & 0xff;
int shift_left = (kcontrol->private_value >> 16) & 0x07;
int shift_right = (kcontrol->private_value >> 19) & 0x07;
int mask = (kcontrol->private_value >> 24) & 0xff;
int invert = (kcontrol->private_value >> 22) & 1;
int change, retval;
unsigned short val1, val2;
val1 = ucontrol->value.integer.value[0] & mask;
val2 = ucontrol->value.integer.value[1] & mask;
if (invert) {
val1 = mask - val1;
val2 = mask - val2;
}
val1 <<= shift_left;
val2 <<= shift_right;
mutex_lock(&chip->mixer_lock);
val1 = (chip->reg_image[left_reg] & ~(mask << shift_left)) | val1;
val2 = (chip->reg_image[right_reg] & ~(mask << shift_right)) | val2;
change = val1 != chip->reg_image[left_reg]
|| val2 != chip->reg_image[right_reg];
retval = snd_at73c213_write_reg(chip, left_reg, val1);
if (retval) {
mutex_unlock(&chip->mixer_lock);
goto out;
}
retval = snd_at73c213_write_reg(chip, right_reg, val2);
if (retval) {
mutex_unlock(&chip->mixer_lock);
goto out;
}
mutex_unlock(&chip->mixer_lock);
return change;
out:
return retval;
}
#define snd_at73c213_mono_switch_info snd_ctl_boolean_mono_info
static int snd_at73c213_mono_switch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_at73c213 *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
mutex_lock(&chip->mixer_lock);
ucontrol->value.integer.value[0] =
(chip->reg_image[reg] >> shift) & 0x01;
if (invert)
ucontrol->value.integer.value[0] =
0x01 - ucontrol->value.integer.value[0];
mutex_unlock(&chip->mixer_lock);
return 0;
}
static int snd_at73c213_mono_switch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_at73c213 *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
int change, retval;
unsigned short val;
if (ucontrol->value.integer.value[0])
val = mask;
else
val = 0;
if (invert)
val = mask - val;
val <<= shift;
mutex_lock(&chip->mixer_lock);
val |= (chip->reg_image[reg] & ~(mask << shift));
change = val != chip->reg_image[reg];
retval = snd_at73c213_write_reg(chip, reg, val);
mutex_unlock(&chip->mixer_lock);
if (retval)
return retval;
return change;
}
static int snd_at73c213_pa_volume_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = ((kcontrol->private_value >> 16) & 0xff) - 1;
return 0;
}
static int snd_at73c213_line_capture_volume_info(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
/* When inverted will give values 0x10001 => 0. */
uinfo->value.integer.min = 14;
uinfo->value.integer.max = 31;
return 0;
}
static int snd_at73c213_aux_capture_volume_info(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 1;
/* When inverted will give values 0x10001 => 0. */
uinfo->value.integer.min = 14;
uinfo->value.integer.max = 31;
return 0;
}
#define AT73C213_MONO_SWITCH(xname, xindex, reg, shift, mask, invert) \
{ \
.iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
.name = xname, \
.index = xindex, \
.info = snd_at73c213_mono_switch_info, \
.get = snd_at73c213_mono_switch_get, \
.put = snd_at73c213_mono_switch_put, \
.private_value = (reg | (shift << 8) | (mask << 16) | (invert << 24)) \
}
#define AT73C213_STEREO(xname, xindex, left_reg, right_reg, shift_left, shift_right, mask, invert) \
{ \
.iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
.name = xname, \
.index = xindex, \
.info = snd_at73c213_stereo_info, \
.get = snd_at73c213_stereo_get, \
.put = snd_at73c213_stereo_put, \
.private_value = (left_reg | (right_reg << 8) \
| (shift_left << 16) | (shift_right << 19) \
| (mask << 24) | (invert << 22)) \
}
static struct snd_kcontrol_new snd_at73c213_controls[] __devinitdata = {
AT73C213_STEREO("Master Playback Volume", 0, DAC_LMPG, DAC_RMPG, 0, 0, 0x1f, 1),
AT73C213_STEREO("Master Playback Switch", 0, DAC_LMPG, DAC_RMPG, 5, 5, 1, 1),
AT73C213_STEREO("PCM Playback Volume", 0, DAC_LLOG, DAC_RLOG, 0, 0, 0x1f, 1),
AT73C213_STEREO("PCM Playback Switch", 0, DAC_LLOG, DAC_RLOG, 5, 5, 1, 1),
AT73C213_MONO_SWITCH("Mono PA Playback Switch", 0, DAC_CTRL, DAC_CTRL_ONPADRV,
0x01, 0),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PA Playback Volume",
.index = 0,
.info = snd_at73c213_pa_volume_info,
.get = snd_at73c213_mono_get,
.put = snd_at73c213_mono_put,
.private_value = PA_CTRL | (PA_CTRL_APAGAIN << 8) | \
(0x0f << 16) | (1 << 24),
},
AT73C213_MONO_SWITCH("PA High Gain Playback Switch", 0, PA_CTRL, PA_CTRL_APALP,
0x01, 1),
AT73C213_MONO_SWITCH("PA Playback Switch", 0, PA_CTRL, PA_CTRL_APAON, 0x01, 0),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Aux Capture Volume",
.index = 0,
.info = snd_at73c213_aux_capture_volume_info,
.get = snd_at73c213_mono_get,
.put = snd_at73c213_mono_put,
.private_value = DAC_AUXG | (0 << 8) | (0x1f << 16) | (1 << 24),
},
AT73C213_MONO_SWITCH("Aux Capture Switch", 0, DAC_CTRL, DAC_CTRL_ONAUXIN,
0x01, 0),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Line Capture Volume",
.index = 0,
.info = snd_at73c213_line_capture_volume_info,
.get = snd_at73c213_stereo_get,
.put = snd_at73c213_stereo_put,
.private_value = DAC_LLIG | (DAC_RLIG << 8) | (0 << 16) | (0 << 19)
| (0x1f << 24) | (1 << 22),
},
AT73C213_MONO_SWITCH("Line Capture Switch", 0, DAC_CTRL, 0, 0x03, 0),
};
static int __devinit snd_at73c213_mixer(struct snd_at73c213 *chip)
{
struct snd_card *card;
int errval, idx;
if (chip == NULL || chip->pcm == NULL)
return -EINVAL;
card = chip->card;
strcpy(card->mixername, chip->pcm->name);
for (idx = 0; idx < ARRAY_SIZE(snd_at73c213_controls); idx++) {
errval = snd_ctl_add(card,
snd_ctl_new1(&snd_at73c213_controls[idx],
chip));
if (errval < 0)
goto cleanup;
}
return 0;
cleanup:
for (idx = 1; idx < ARRAY_SIZE(snd_at73c213_controls) + 1; idx++) {
struct snd_kcontrol *kctl;
kctl = snd_ctl_find_numid(card, idx);
if (kctl)
snd_ctl_remove(card, kctl);
}
return errval;
}
/*
* Device functions
*/
static int __devinit snd_at73c213_ssc_init(struct snd_at73c213 *chip)
{
/*
* Continuous clock output.
* Starts on falling TF.
* Delay 1 cycle (1 bit).
* Periode is 16 bit (16 - 1).
*/
ssc_writel(chip->ssc->regs, TCMR,
SSC_BF(TCMR_CKO, 1)
| SSC_BF(TCMR_START, 4)
| SSC_BF(TCMR_STTDLY, 1)
| SSC_BF(TCMR_PERIOD, 16 - 1));
/*
* Data length is 16 bit (16 - 1).
* Transmit MSB first.
* Transmit 2 words each transfer.
* Frame sync length is 16 bit (16 - 1).
* Frame starts on negative pulse.
*/
ssc_writel(chip->ssc->regs, TFMR,
SSC_BF(TFMR_DATLEN, 16 - 1)
| SSC_BIT(TFMR_MSBF)
| SSC_BF(TFMR_DATNB, 1)
| SSC_BF(TFMR_FSLEN, 16 - 1)
| SSC_BF(TFMR_FSOS, 1));
return 0;
}
static int __devinit snd_at73c213_chip_init(struct snd_at73c213 *chip)
{
int retval;
unsigned char dac_ctrl = 0;
retval = snd_at73c213_set_bitrate(chip);
if (retval)
goto out;
/* Enable DAC master clock. */
clk_enable(chip->board->dac_clk);
/* Initialize at73c213 on SPI bus. */
retval = snd_at73c213_write_reg(chip, DAC_RST, 0x04);
if (retval)
goto out_clk;
msleep(1);
retval = snd_at73c213_write_reg(chip, DAC_RST, 0x03);
if (retval)
goto out_clk;
/* Precharge everything. */
retval = snd_at73c213_write_reg(chip, DAC_PRECH, 0xff);
if (retval)
goto out_clk;
retval = snd_at73c213_write_reg(chip, PA_CTRL, (1<<PA_CTRL_APAPRECH));
if (retval)
goto out_clk;
retval = snd_at73c213_write_reg(chip, DAC_CTRL,
(1<<DAC_CTRL_ONLNOL) | (1<<DAC_CTRL_ONLNOR));
if (retval)
goto out_clk;
msleep(50);
/* Stop precharging PA. */
retval = snd_at73c213_write_reg(chip, PA_CTRL,
(1<<PA_CTRL_APALP) | 0x0f);
if (retval)
goto out_clk;
msleep(450);
/* Stop precharging DAC, turn on master power. */
retval = snd_at73c213_write_reg(chip, DAC_PRECH, (1<<DAC_PRECH_ONMSTR));
if (retval)
goto out_clk;
msleep(1);
/* Turn on DAC. */
dac_ctrl = (1<<DAC_CTRL_ONDACL) | (1<<DAC_CTRL_ONDACR)
| (1<<DAC_CTRL_ONLNOL) | (1<<DAC_CTRL_ONLNOR);
retval = snd_at73c213_write_reg(chip, DAC_CTRL, dac_ctrl);
if (retval)
goto out_clk;
/* Mute sound. */
retval = snd_at73c213_write_reg(chip, DAC_LMPG, 0x3f);
if (retval)
goto out_clk;
retval = snd_at73c213_write_reg(chip, DAC_RMPG, 0x3f);
if (retval)
goto out_clk;
retval = snd_at73c213_write_reg(chip, DAC_LLOG, 0x3f);
if (retval)
goto out_clk;
retval = snd_at73c213_write_reg(chip, DAC_RLOG, 0x3f);
if (retval)
goto out_clk;
retval = snd_at73c213_write_reg(chip, DAC_LLIG, 0x11);
if (retval)
goto out_clk;
retval = snd_at73c213_write_reg(chip, DAC_RLIG, 0x11);
if (retval)
goto out_clk;
retval = snd_at73c213_write_reg(chip, DAC_AUXG, 0x11);
if (retval)
goto out_clk;
/* Enable I2S device, i.e. clock output. */
ssc_writel(chip->ssc->regs, CR, SSC_BIT(CR_TXEN));
goto out;
out_clk:
clk_disable(chip->board->dac_clk);
out:
return retval;
}
static int snd_at73c213_dev_free(struct snd_device *device)
{
struct snd_at73c213 *chip = device->device_data;
ssc_writel(chip->ssc->regs, CR, SSC_BIT(CR_TXDIS));
if (chip->irq >= 0) {
free_irq(chip->irq, chip);
chip->irq = -1;
}
return 0;
}
static int __devinit snd_at73c213_dev_init(struct snd_card *card,
struct spi_device *spi)
{
static struct snd_device_ops ops = {
.dev_free = snd_at73c213_dev_free,
};
struct snd_at73c213 *chip = get_chip(card);
int irq, retval;
irq = chip->ssc->irq;
if (irq < 0)
return irq;
spin_lock_init(&chip->lock);
mutex_init(&chip->mixer_lock);
chip->card = card;
chip->irq = -1;
retval = request_irq(irq, snd_at73c213_interrupt, 0, "at73c213", chip);
if (retval) {
dev_dbg(&chip->spi->dev, "unable to request irq %d\n", irq);
goto out;
}
chip->irq = irq;
memcpy(&chip->reg_image, &snd_at73c213_original_image,
sizeof(snd_at73c213_original_image));
retval = snd_at73c213_ssc_init(chip);
if (retval)
goto out_irq;
retval = snd_at73c213_chip_init(chip);
if (retval)
goto out_irq;
retval = snd_at73c213_pcm_new(chip, 0);
if (retval)
goto out_irq;
retval = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
if (retval)
goto out_irq;
retval = snd_at73c213_mixer(chip);
if (retval)
goto out_snd_dev;
snd_card_set_dev(card, &spi->dev);
goto out;
out_snd_dev:
snd_device_free(card, chip);
out_irq:
free_irq(chip->irq, chip);
chip->irq = -1;
out:
return retval;
}
static int __devinit snd_at73c213_probe(struct spi_device *spi)
{
struct snd_card *card;
struct snd_at73c213 *chip;
struct at73c213_board_info *board;
int retval;
char id[16];
board = spi->dev.platform_data;
if (!board) {
dev_dbg(&spi->dev, "no platform_data\n");
return -ENXIO;
}
if (!board->dac_clk) {
dev_dbg(&spi->dev, "no DAC clk\n");
return -ENXIO;
}
if (IS_ERR(board->dac_clk)) {
dev_dbg(&spi->dev, "no DAC clk\n");
return PTR_ERR(board->dac_clk);
}
/* Allocate "card" using some unused identifiers. */
snprintf(id, sizeof id, "at73c213_%d", board->ssc_id);
retval = snd_card_create(-1, id, THIS_MODULE,
sizeof(struct snd_at73c213), &card);
if (retval < 0)
goto out;
chip = card->private_data;
chip->spi = spi;
chip->board = board;
chip->ssc = ssc_request(board->ssc_id);
if (IS_ERR(chip->ssc)) {
dev_dbg(&spi->dev, "could not get ssc%d device\n",
board->ssc_id);
retval = PTR_ERR(chip->ssc);
goto out_card;
}
retval = snd_at73c213_dev_init(card, spi);
if (retval)
goto out_ssc;
strcpy(card->driver, "at73c213");
strcpy(card->shortname, board->shortname);
sprintf(card->longname, "%s on irq %d", card->shortname, chip->irq);
retval = snd_card_register(card);
if (retval)
goto out_ssc;
dev_set_drvdata(&spi->dev, card);
goto out;
out_ssc:
ssc_free(chip->ssc);
out_card:
snd_card_free(card);
out:
return retval;
}
static int __devexit snd_at73c213_remove(struct spi_device *spi)
{
struct snd_card *card = dev_get_drvdata(&spi->dev);
struct snd_at73c213 *chip = card->private_data;
int retval;
/* Stop playback. */
ssc_writel(chip->ssc->regs, CR, SSC_BIT(CR_TXDIS));
/* Mute sound. */
retval = snd_at73c213_write_reg(chip, DAC_LMPG, 0x3f);
if (retval)
goto out;
retval = snd_at73c213_write_reg(chip, DAC_RMPG, 0x3f);
if (retval)
goto out;
retval = snd_at73c213_write_reg(chip, DAC_LLOG, 0x3f);
if (retval)
goto out;
retval = snd_at73c213_write_reg(chip, DAC_RLOG, 0x3f);
if (retval)
goto out;
retval = snd_at73c213_write_reg(chip, DAC_LLIG, 0x11);
if (retval)
goto out;
retval = snd_at73c213_write_reg(chip, DAC_RLIG, 0x11);
if (retval)
goto out;
retval = snd_at73c213_write_reg(chip, DAC_AUXG, 0x11);
if (retval)
goto out;
/* Turn off PA. */
retval = snd_at73c213_write_reg(chip, PA_CTRL,
chip->reg_image[PA_CTRL] | 0x0f);
if (retval)
goto out;
msleep(10);
retval = snd_at73c213_write_reg(chip, PA_CTRL,
(1 << PA_CTRL_APALP) | 0x0f);
if (retval)
goto out;
/* Turn off external DAC. */
retval = snd_at73c213_write_reg(chip, DAC_CTRL, 0x0c);
if (retval)
goto out;
msleep(2);
retval = snd_at73c213_write_reg(chip, DAC_CTRL, 0x00);
if (retval)
goto out;
/* Turn off master power. */
retval = snd_at73c213_write_reg(chip, DAC_PRECH, 0x00);
if (retval)
goto out;
out:
/* Stop DAC master clock. */
clk_disable(chip->board->dac_clk);
ssc_free(chip->ssc);
snd_card_free(card);
dev_set_drvdata(&spi->dev, NULL);
return 0;
}
#ifdef CONFIG_PM
static int snd_at73c213_suspend(struct spi_device *spi, pm_message_t msg)
{
struct snd_card *card = dev_get_drvdata(&spi->dev);
struct snd_at73c213 *chip = card->private_data;
ssc_writel(chip->ssc->regs, CR, SSC_BIT(CR_TXDIS));
clk_disable(chip->board->dac_clk);
return 0;
}
static int snd_at73c213_resume(struct spi_device *spi)
{
struct snd_card *card = dev_get_drvdata(&spi->dev);
struct snd_at73c213 *chip = card->private_data;
clk_enable(chip->board->dac_clk);
ssc_writel(chip->ssc->regs, CR, SSC_BIT(CR_TXEN));
return 0;
}
#else
#define snd_at73c213_suspend NULL
#define snd_at73c213_resume NULL
#endif
static struct spi_driver at73c213_driver = {
.driver = {
.name = "at73c213",
},
.probe = snd_at73c213_probe,
.suspend = snd_at73c213_suspend,
.resume = snd_at73c213_resume,
.remove = __devexit_p(snd_at73c213_remove),
};
static int __init at73c213_init(void)
{
return spi_register_driver(&at73c213_driver);
}
module_init(at73c213_init);
static void __exit at73c213_exit(void)
{
spi_unregister_driver(&at73c213_driver);
}
module_exit(at73c213_exit);
MODULE_AUTHOR("Hans-Christian Egtvedt <egtvedt@samfundet.no>");
MODULE_DESCRIPTION("Sound driver for AT73C213 with Atmel SSC");
MODULE_LICENSE("GPL");
| gpl-2.0 |
venkatkamesh/android_kernel_sonyz_msm8974 | fs/hfsplus/options.c | 4813 | 5227 | /*
* linux/fs/hfsplus/options.c
*
* Copyright (C) 2001
* Brad Boyer (flar@allandria.com)
* (C) 2003 Ardis Technologies <roman@ardistech.com>
*
* Option parsing
*/
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/parser.h>
#include <linux/nls.h>
#include <linux/mount.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include "hfsplus_fs.h"
enum {
opt_creator, opt_type,
opt_umask, opt_uid, opt_gid,
opt_part, opt_session, opt_nls,
opt_nodecompose, opt_decompose,
opt_barrier, opt_nobarrier,
opt_force, opt_err
};
static const match_table_t tokens = {
{ opt_creator, "creator=%s" },
{ opt_type, "type=%s" },
{ opt_umask, "umask=%o" },
{ opt_uid, "uid=%u" },
{ opt_gid, "gid=%u" },
{ opt_part, "part=%u" },
{ opt_session, "session=%u" },
{ opt_nls, "nls=%s" },
{ opt_decompose, "decompose" },
{ opt_nodecompose, "nodecompose" },
{ opt_barrier, "barrier" },
{ opt_nobarrier, "nobarrier" },
{ opt_force, "force" },
{ opt_err, NULL }
};
/* Initialize an options object to reasonable defaults */
void hfsplus_fill_defaults(struct hfsplus_sb_info *opts)
{
if (!opts)
return;
opts->creator = HFSPLUS_DEF_CR_TYPE;
opts->type = HFSPLUS_DEF_CR_TYPE;
opts->umask = current_umask();
opts->uid = current_uid();
opts->gid = current_gid();
opts->part = -1;
opts->session = -1;
}
/* convert a "four byte character" to a 32 bit int with error checks */
static inline int match_fourchar(substring_t *arg, u32 *result)
{
if (arg->to - arg->from != 4)
return -EINVAL;
memcpy(result, arg->from, 4);
return 0;
}
int hfsplus_parse_options_remount(char *input, int *force)
{
char *p;
substring_t args[MAX_OPT_ARGS];
int token;
if (!input)
return 0;
while ((p = strsep(&input, ",")) != NULL) {
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case opt_force:
*force = 1;
break;
default:
break;
}
}
return 1;
}
/* Parse options from mount. Returns 0 on failure */
/* input is the options passed to mount() as a string */
int hfsplus_parse_options(char *input, struct hfsplus_sb_info *sbi)
{
char *p;
substring_t args[MAX_OPT_ARGS];
int tmp, token;
if (!input)
goto done;
while ((p = strsep(&input, ",")) != NULL) {
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case opt_creator:
if (match_fourchar(&args[0], &sbi->creator)) {
printk(KERN_ERR "hfs: creator requires a 4 character value\n");
return 0;
}
break;
case opt_type:
if (match_fourchar(&args[0], &sbi->type)) {
printk(KERN_ERR "hfs: type requires a 4 character value\n");
return 0;
}
break;
case opt_umask:
if (match_octal(&args[0], &tmp)) {
printk(KERN_ERR "hfs: umask requires a value\n");
return 0;
}
sbi->umask = (umode_t)tmp;
break;
case opt_uid:
if (match_int(&args[0], &tmp)) {
printk(KERN_ERR "hfs: uid requires an argument\n");
return 0;
}
sbi->uid = (uid_t)tmp;
break;
case opt_gid:
if (match_int(&args[0], &tmp)) {
printk(KERN_ERR "hfs: gid requires an argument\n");
return 0;
}
sbi->gid = (gid_t)tmp;
break;
case opt_part:
if (match_int(&args[0], &sbi->part)) {
printk(KERN_ERR "hfs: part requires an argument\n");
return 0;
}
break;
case opt_session:
if (match_int(&args[0], &sbi->session)) {
printk(KERN_ERR "hfs: session requires an argument\n");
return 0;
}
break;
case opt_nls:
if (sbi->nls) {
printk(KERN_ERR "hfs: unable to change nls mapping\n");
return 0;
}
p = match_strdup(&args[0]);
if (p)
sbi->nls = load_nls(p);
if (!sbi->nls) {
printk(KERN_ERR "hfs: unable to load "
"nls mapping \"%s\"\n",
p);
kfree(p);
return 0;
}
kfree(p);
break;
case opt_decompose:
clear_bit(HFSPLUS_SB_NODECOMPOSE, &sbi->flags);
break;
case opt_nodecompose:
set_bit(HFSPLUS_SB_NODECOMPOSE, &sbi->flags);
break;
case opt_barrier:
clear_bit(HFSPLUS_SB_NOBARRIER, &sbi->flags);
break;
case opt_nobarrier:
set_bit(HFSPLUS_SB_NOBARRIER, &sbi->flags);
break;
case opt_force:
set_bit(HFSPLUS_SB_FORCE, &sbi->flags);
break;
default:
return 0;
}
}
done:
if (!sbi->nls) {
/* try utf8 first, as this is the old default behaviour */
sbi->nls = load_nls("utf8");
if (!sbi->nls)
sbi->nls = load_nls_default();
if (!sbi->nls)
return 0;
}
return 1;
}
int hfsplus_show_options(struct seq_file *seq, struct dentry *root)
{
struct hfsplus_sb_info *sbi = HFSPLUS_SB(root->d_sb);
if (sbi->creator != HFSPLUS_DEF_CR_TYPE)
seq_printf(seq, ",creator=%.4s", (char *)&sbi->creator);
if (sbi->type != HFSPLUS_DEF_CR_TYPE)
seq_printf(seq, ",type=%.4s", (char *)&sbi->type);
seq_printf(seq, ",umask=%o,uid=%u,gid=%u", sbi->umask,
sbi->uid, sbi->gid);
if (sbi->part >= 0)
seq_printf(seq, ",part=%u", sbi->part);
if (sbi->session >= 0)
seq_printf(seq, ",session=%u", sbi->session);
if (sbi->nls)
seq_printf(seq, ",nls=%s", sbi->nls->charset);
if (test_bit(HFSPLUS_SB_NODECOMPOSE, &sbi->flags))
seq_printf(seq, ",nodecompose");
if (test_bit(HFSPLUS_SB_NOBARRIER, &sbi->flags))
seq_printf(seq, ",nobarrier");
return 0;
}
| gpl-2.0 |
vk2rq/linux-stable | arch/m68k/hp300/config.c | 4813 | 6634 | /*
* linux/arch/m68k/hp300/config.c
*
* Copyright (C) 1998 Philip Blundell <philb@gnu.org>
*
* This file contains the HP300-specific initialisation code. It gets
* called by setup.c.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/console.h>
#include <asm/bootinfo.h>
#include <asm/machdep.h>
#include <asm/blinken.h>
#include <asm/io.h> /* readb() and writeb() */
#include <asm/hp300hw.h>
#include <asm/rtc.h>
#include "time.h"
unsigned long hp300_model;
unsigned long hp300_uart_scode = -1;
unsigned char ledstate;
static char s_hp330[] __initdata = "330";
static char s_hp340[] __initdata = "340";
static char s_hp345[] __initdata = "345";
static char s_hp360[] __initdata = "360";
static char s_hp370[] __initdata = "370";
static char s_hp375[] __initdata = "375";
static char s_hp380[] __initdata = "380";
static char s_hp385[] __initdata = "385";
static char s_hp400[] __initdata = "400";
static char s_hp425t[] __initdata = "425t";
static char s_hp425s[] __initdata = "425s";
static char s_hp425e[] __initdata = "425e";
static char s_hp433t[] __initdata = "433t";
static char s_hp433s[] __initdata = "433s";
static char *hp300_models[] __initdata = {
[HP_320] = NULL,
[HP_330] = s_hp330,
[HP_340] = s_hp340,
[HP_345] = s_hp345,
[HP_350] = NULL,
[HP_360] = s_hp360,
[HP_370] = s_hp370,
[HP_375] = s_hp375,
[HP_380] = s_hp380,
[HP_385] = s_hp385,
[HP_400] = s_hp400,
[HP_425T] = s_hp425t,
[HP_425S] = s_hp425s,
[HP_425E] = s_hp425e,
[HP_433T] = s_hp433t,
[HP_433S] = s_hp433s,
};
static char hp300_model_name[13] = "HP9000/";
extern void hp300_reset(void);
#ifdef CONFIG_SERIAL_8250_CONSOLE
extern int hp300_setup_serial_console(void) __init;
#endif
int __init hp300_parse_bootinfo(const struct bi_record *record)
{
int unknown = 0;
const unsigned long *data = record->data;
switch (record->tag) {
case BI_HP300_MODEL:
hp300_model = *data;
break;
case BI_HP300_UART_SCODE:
hp300_uart_scode = *data;
break;
case BI_HP300_UART_ADDR:
/* serial port address: ignored here */
break;
default:
unknown = 1;
}
return unknown;
}
#ifdef CONFIG_HEARTBEAT
static void hp300_pulse(int x)
{
if (x)
blinken_leds(0x10, 0);
else
blinken_leds(0, 0x10);
}
#endif
static void hp300_get_model(char *model)
{
strcpy(model, hp300_model_name);
}
#define RTCBASE 0xf0420000
#define RTC_DATA 0x1
#define RTC_CMD 0x3
#define RTC_BUSY 0x02
#define RTC_DATA_RDY 0x01
#define rtc_busy() (in_8(RTCBASE + RTC_CMD) & RTC_BUSY)
#define rtc_data_available() (in_8(RTCBASE + RTC_CMD) & RTC_DATA_RDY)
#define rtc_status() (in_8(RTCBASE + RTC_CMD))
#define rtc_command(x) out_8(RTCBASE + RTC_CMD, (x))
#define rtc_read_data() (in_8(RTCBASE + RTC_DATA))
#define rtc_write_data(x) out_8(RTCBASE + RTC_DATA, (x))
#define RTC_SETREG 0xe0
#define RTC_WRITEREG 0xc2
#define RTC_READREG 0xc3
#define RTC_REG_SEC2 0
#define RTC_REG_SEC1 1
#define RTC_REG_MIN2 2
#define RTC_REG_MIN1 3
#define RTC_REG_HOUR2 4
#define RTC_REG_HOUR1 5
#define RTC_REG_WDAY 6
#define RTC_REG_DAY2 7
#define RTC_REG_DAY1 8
#define RTC_REG_MON2 9
#define RTC_REG_MON1 10
#define RTC_REG_YEAR2 11
#define RTC_REG_YEAR1 12
#define RTC_HOUR1_24HMODE 0x8
#define RTC_STAT_MASK 0xf0
#define RTC_STAT_RDY 0x40
static inline unsigned char hp300_rtc_read(unsigned char reg)
{
unsigned char s, ret;
unsigned long flags;
local_irq_save(flags);
while (rtc_busy());
rtc_command(RTC_SETREG);
while (rtc_busy());
rtc_write_data(reg);
while (rtc_busy());
rtc_command(RTC_READREG);
do {
while (!rtc_data_available());
s = rtc_status();
ret = rtc_read_data();
} while ((s & RTC_STAT_MASK) != RTC_STAT_RDY);
local_irq_restore(flags);
return ret;
}
static inline unsigned char hp300_rtc_write(unsigned char reg,
unsigned char val)
{
unsigned char s, ret;
unsigned long flags;
local_irq_save(flags);
while (rtc_busy());
rtc_command(RTC_SETREG);
while (rtc_busy());
rtc_write_data((val << 4) | reg);
while (rtc_busy());
rtc_command(RTC_WRITEREG);
while (rtc_busy());
rtc_command(RTC_READREG);
do {
while (!rtc_data_available());
s = rtc_status();
ret = rtc_read_data();
} while ((s & RTC_STAT_MASK) != RTC_STAT_RDY);
local_irq_restore(flags);
return ret;
}
static int hp300_hwclk(int op, struct rtc_time *t)
{
if (!op) { /* read */
t->tm_sec = hp300_rtc_read(RTC_REG_SEC1) * 10 +
hp300_rtc_read(RTC_REG_SEC2);
t->tm_min = hp300_rtc_read(RTC_REG_MIN1) * 10 +
hp300_rtc_read(RTC_REG_MIN2);
t->tm_hour = (hp300_rtc_read(RTC_REG_HOUR1) & 3) * 10 +
hp300_rtc_read(RTC_REG_HOUR2);
t->tm_wday = -1;
t->tm_mday = hp300_rtc_read(RTC_REG_DAY1) * 10 +
hp300_rtc_read(RTC_REG_DAY2);
t->tm_mon = hp300_rtc_read(RTC_REG_MON1) * 10 +
hp300_rtc_read(RTC_REG_MON2) - 1;
t->tm_year = hp300_rtc_read(RTC_REG_YEAR1) * 10 +
hp300_rtc_read(RTC_REG_YEAR2);
if (t->tm_year <= 69)
t->tm_year += 100;
} else {
hp300_rtc_write(RTC_REG_SEC1, t->tm_sec / 10);
hp300_rtc_write(RTC_REG_SEC2, t->tm_sec % 10);
hp300_rtc_write(RTC_REG_MIN1, t->tm_min / 10);
hp300_rtc_write(RTC_REG_MIN2, t->tm_min % 10);
hp300_rtc_write(RTC_REG_HOUR1,
((t->tm_hour / 10) & 3) | RTC_HOUR1_24HMODE);
hp300_rtc_write(RTC_REG_HOUR2, t->tm_hour % 10);
hp300_rtc_write(RTC_REG_DAY1, t->tm_mday / 10);
hp300_rtc_write(RTC_REG_DAY2, t->tm_mday % 10);
hp300_rtc_write(RTC_REG_MON1, (t->tm_mon + 1) / 10);
hp300_rtc_write(RTC_REG_MON2, (t->tm_mon + 1) % 10);
if (t->tm_year >= 100)
t->tm_year -= 100;
hp300_rtc_write(RTC_REG_YEAR1, t->tm_year / 10);
hp300_rtc_write(RTC_REG_YEAR2, t->tm_year % 10);
}
return 0;
}
static unsigned int hp300_get_ss(void)
{
return hp300_rtc_read(RTC_REG_SEC1) * 10 +
hp300_rtc_read(RTC_REG_SEC2);
}
static void __init hp300_init_IRQ(void)
{
}
void __init config_hp300(void)
{
mach_sched_init = hp300_sched_init;
mach_init_IRQ = hp300_init_IRQ;
mach_get_model = hp300_get_model;
mach_gettimeoffset = hp300_gettimeoffset;
mach_hwclk = hp300_hwclk;
mach_get_ss = hp300_get_ss;
mach_reset = hp300_reset;
#ifdef CONFIG_HEARTBEAT
mach_heartbeat = hp300_pulse;
#endif
mach_max_dma_address = 0xffffffff;
if (hp300_model >= HP_330 && hp300_model <= HP_433S && hp300_model != HP_350) {
printk(KERN_INFO "Detected HP9000 model %s\n", hp300_models[hp300_model-HP_320]);
strcat(hp300_model_name, hp300_models[hp300_model-HP_320]);
}
else {
panic("Unknown HP9000 Model");
}
#ifdef CONFIG_SERIAL_8250_CONSOLE
hp300_setup_serial_console();
#endif
}
| gpl-2.0 |
DutchDanny/kernel_kk443_sense_m8ace | fs/xfs/xfs_vnodeops.c | 4813 | 58697 | /*
* Copyright (c) 2000-2006 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* 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_fs.h"
#include "xfs_types.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_dir2.h"
#include "xfs_mount.h"
#include "xfs_da_btree.h"
#include "xfs_bmap_btree.h"
#include "xfs_ialloc_btree.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_inode_item.h"
#include "xfs_itable.h"
#include "xfs_ialloc.h"
#include "xfs_alloc.h"
#include "xfs_bmap.h"
#include "xfs_acl.h"
#include "xfs_attr.h"
#include "xfs_rw.h"
#include "xfs_error.h"
#include "xfs_quota.h"
#include "xfs_utils.h"
#include "xfs_rtalloc.h"
#include "xfs_trans_space.h"
#include "xfs_log_priv.h"
#include "xfs_filestream.h"
#include "xfs_vnodeops.h"
#include "xfs_trace.h"
/*
* The maximum pathlen is 1024 bytes. Since the minimum file system
* blocksize is 512 bytes, we can get a max of 2 extents back from
* bmapi.
*/
#define SYMLINK_MAPS 2
STATIC int
xfs_readlink_bmap(
xfs_inode_t *ip,
char *link)
{
xfs_mount_t *mp = ip->i_mount;
int pathlen = ip->i_d.di_size;
int nmaps = SYMLINK_MAPS;
xfs_bmbt_irec_t mval[SYMLINK_MAPS];
xfs_daddr_t d;
int byte_cnt;
int n;
xfs_buf_t *bp;
int error = 0;
error = xfs_bmapi_read(ip, 0, XFS_B_TO_FSB(mp, pathlen), mval, &nmaps,
0);
if (error)
goto out;
for (n = 0; n < nmaps; n++) {
d = XFS_FSB_TO_DADDR(mp, mval[n].br_startblock);
byte_cnt = XFS_FSB_TO_B(mp, mval[n].br_blockcount);
bp = xfs_buf_read(mp->m_ddev_targp, d, BTOBB(byte_cnt),
XBF_LOCK | XBF_MAPPED | XBF_DONT_BLOCK);
if (!bp)
return XFS_ERROR(ENOMEM);
error = bp->b_error;
if (error) {
xfs_buf_ioerror_alert(bp, __func__);
xfs_buf_relse(bp);
goto out;
}
if (pathlen < byte_cnt)
byte_cnt = pathlen;
pathlen -= byte_cnt;
memcpy(link, bp->b_addr, byte_cnt);
xfs_buf_relse(bp);
}
link[ip->i_d.di_size] = '\0';
error = 0;
out:
return error;
}
int
xfs_readlink(
xfs_inode_t *ip,
char *link)
{
xfs_mount_t *mp = ip->i_mount;
xfs_fsize_t pathlen;
int error = 0;
trace_xfs_readlink(ip);
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
xfs_ilock(ip, XFS_ILOCK_SHARED);
pathlen = ip->i_d.di_size;
if (!pathlen)
goto out;
if (pathlen < 0 || pathlen > MAXPATHLEN) {
xfs_alert(mp, "%s: inode (%llu) bad symlink length (%lld)",
__func__, (unsigned long long) ip->i_ino,
(long long) pathlen);
ASSERT(0);
error = XFS_ERROR(EFSCORRUPTED);
goto out;
}
if (ip->i_df.if_flags & XFS_IFINLINE) {
memcpy(link, ip->i_df.if_u1.if_data, pathlen);
link[pathlen] = '\0';
} else {
error = xfs_readlink_bmap(ip, link);
}
out:
xfs_iunlock(ip, XFS_ILOCK_SHARED);
return error;
}
/*
* Flags for xfs_free_eofblocks
*/
#define XFS_FREE_EOF_TRYLOCK (1<<0)
/*
* This is called by xfs_inactive to free any blocks beyond eof
* when the link count isn't zero and by xfs_dm_punch_hole() when
* punching a hole to EOF.
*/
STATIC int
xfs_free_eofblocks(
xfs_mount_t *mp,
xfs_inode_t *ip,
int flags)
{
xfs_trans_t *tp;
int error;
xfs_fileoff_t end_fsb;
xfs_fileoff_t last_fsb;
xfs_filblks_t map_len;
int nimaps;
xfs_bmbt_irec_t imap;
/*
* Figure out if there are any blocks beyond the end
* of the file. If not, then there is nothing to do.
*/
end_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)XFS_ISIZE(ip));
last_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)XFS_MAXIOFFSET(mp));
if (last_fsb <= end_fsb)
return 0;
map_len = last_fsb - end_fsb;
nimaps = 1;
xfs_ilock(ip, XFS_ILOCK_SHARED);
error = xfs_bmapi_read(ip, end_fsb, map_len, &imap, &nimaps, 0);
xfs_iunlock(ip, XFS_ILOCK_SHARED);
if (!error && (nimaps != 0) &&
(imap.br_startblock != HOLESTARTBLOCK ||
ip->i_delayed_blks)) {
/*
* Attach the dquots to the inode up front.
*/
error = xfs_qm_dqattach(ip, 0);
if (error)
return error;
/*
* There are blocks after the end of file.
* Free them up now by truncating the file to
* its current size.
*/
tp = xfs_trans_alloc(mp, XFS_TRANS_INACTIVE);
if (flags & XFS_FREE_EOF_TRYLOCK) {
if (!xfs_ilock_nowait(ip, XFS_IOLOCK_EXCL)) {
xfs_trans_cancel(tp, 0);
return 0;
}
} else {
xfs_ilock(ip, XFS_IOLOCK_EXCL);
}
error = xfs_trans_reserve(tp, 0,
XFS_ITRUNCATE_LOG_RES(mp),
0, XFS_TRANS_PERM_LOG_RES,
XFS_ITRUNCATE_LOG_COUNT);
if (error) {
ASSERT(XFS_FORCED_SHUTDOWN(mp));
xfs_trans_cancel(tp, 0);
xfs_iunlock(ip, XFS_IOLOCK_EXCL);
return error;
}
xfs_ilock(ip, XFS_ILOCK_EXCL);
xfs_trans_ijoin(tp, ip, 0);
/*
* Do not update the on-disk file size. If we update the
* on-disk file size and then the system crashes before the
* contents of the file are flushed to disk then the files
* may be full of holes (ie NULL files bug).
*/
error = xfs_itruncate_extents(&tp, ip, XFS_DATA_FORK,
XFS_ISIZE(ip));
if (error) {
/*
* If we get an error at this point we simply don't
* bother truncating the file.
*/
xfs_trans_cancel(tp,
(XFS_TRANS_RELEASE_LOG_RES |
XFS_TRANS_ABORT));
} else {
error = xfs_trans_commit(tp,
XFS_TRANS_RELEASE_LOG_RES);
}
xfs_iunlock(ip, XFS_IOLOCK_EXCL|XFS_ILOCK_EXCL);
}
return error;
}
/*
* Free a symlink that has blocks associated with it.
*/
STATIC int
xfs_inactive_symlink_rmt(
xfs_inode_t *ip,
xfs_trans_t **tpp)
{
xfs_buf_t *bp;
int committed;
int done;
int error;
xfs_fsblock_t first_block;
xfs_bmap_free_t free_list;
int i;
xfs_mount_t *mp;
xfs_bmbt_irec_t mval[SYMLINK_MAPS];
int nmaps;
xfs_trans_t *ntp;
int size;
xfs_trans_t *tp;
tp = *tpp;
mp = ip->i_mount;
ASSERT(ip->i_d.di_size > XFS_IFORK_DSIZE(ip));
/*
* We're freeing a symlink that has some
* blocks allocated to it. Free the
* blocks here. We know that we've got
* either 1 or 2 extents and that we can
* free them all in one bunmapi call.
*/
ASSERT(ip->i_d.di_nextents > 0 && ip->i_d.di_nextents <= 2);
if ((error = xfs_trans_reserve(tp, 0, XFS_ITRUNCATE_LOG_RES(mp), 0,
XFS_TRANS_PERM_LOG_RES, XFS_ITRUNCATE_LOG_COUNT))) {
ASSERT(XFS_FORCED_SHUTDOWN(mp));
xfs_trans_cancel(tp, 0);
*tpp = NULL;
return error;
}
/*
* Lock the inode, fix the size, and join it to the transaction.
* Hold it so in the normal path, we still have it locked for
* the second transaction. In the error paths we need it
* held so the cancel won't rele it, see below.
*/
xfs_ilock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
size = (int)ip->i_d.di_size;
ip->i_d.di_size = 0;
xfs_trans_ijoin(tp, ip, 0);
xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
/*
* Find the block(s) so we can inval and unmap them.
*/
done = 0;
xfs_bmap_init(&free_list, &first_block);
nmaps = ARRAY_SIZE(mval);
error = xfs_bmapi_read(ip, 0, XFS_B_TO_FSB(mp, size),
mval, &nmaps, 0);
if (error)
goto error0;
/*
* Invalidate the block(s).
*/
for (i = 0; i < nmaps; i++) {
bp = xfs_trans_get_buf(tp, mp->m_ddev_targp,
XFS_FSB_TO_DADDR(mp, mval[i].br_startblock),
XFS_FSB_TO_BB(mp, mval[i].br_blockcount), 0);
if (!bp) {
error = ENOMEM;
goto error1;
}
xfs_trans_binval(tp, bp);
}
/*
* Unmap the dead block(s) to the free_list.
*/
if ((error = xfs_bunmapi(tp, ip, 0, size, XFS_BMAPI_METADATA, nmaps,
&first_block, &free_list, &done)))
goto error1;
ASSERT(done);
/*
* Commit the first transaction. This logs the EFI and the inode.
*/
if ((error = xfs_bmap_finish(&tp, &free_list, &committed)))
goto error1;
/*
* The transaction must have been committed, since there were
* actually extents freed by xfs_bunmapi. See xfs_bmap_finish.
* The new tp has the extent freeing and EFDs.
*/
ASSERT(committed);
/*
* The first xact was committed, so add the inode to the new one.
* Mark it dirty so it will be logged and moved forward in the log as
* part of every commit.
*/
xfs_trans_ijoin(tp, ip, 0);
xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
/*
* Get a new, empty transaction to return to our caller.
*/
ntp = xfs_trans_dup(tp);
/*
* Commit the transaction containing extent freeing and EFDs.
* If we get an error on the commit here or on the reserve below,
* we need to unlock the inode since the new transaction doesn't
* have the inode attached.
*/
error = xfs_trans_commit(tp, 0);
tp = ntp;
if (error) {
ASSERT(XFS_FORCED_SHUTDOWN(mp));
goto error0;
}
/*
* transaction commit worked ok so we can drop the extra ticket
* reference that we gained in xfs_trans_dup()
*/
xfs_log_ticket_put(tp->t_ticket);
/*
* Remove the memory for extent descriptions (just bookkeeping).
*/
if (ip->i_df.if_bytes)
xfs_idata_realloc(ip, -ip->i_df.if_bytes, XFS_DATA_FORK);
ASSERT(ip->i_df.if_bytes == 0);
/*
* Put an itruncate log reservation in the new transaction
* for our caller.
*/
if ((error = xfs_trans_reserve(tp, 0, XFS_ITRUNCATE_LOG_RES(mp), 0,
XFS_TRANS_PERM_LOG_RES, XFS_ITRUNCATE_LOG_COUNT))) {
ASSERT(XFS_FORCED_SHUTDOWN(mp));
goto error0;
}
/*
* Return with the inode locked but not joined to the transaction.
*/
*tpp = tp;
return 0;
error1:
xfs_bmap_cancel(&free_list);
error0:
/*
* Have to come here with the inode locked and either
* (held and in the transaction) or (not in the transaction).
* If the inode isn't held then cancel would iput it, but
* that's wrong since this is inactive and the vnode ref
* count is 0 already.
* Cancel won't do anything to the inode if held, but it still
* needs to be locked until the cancel is done, if it was
* joined to the transaction.
*/
xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
xfs_iunlock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
*tpp = NULL;
return error;
}
STATIC int
xfs_inactive_symlink_local(
xfs_inode_t *ip,
xfs_trans_t **tpp)
{
int error;
ASSERT(ip->i_d.di_size <= XFS_IFORK_DSIZE(ip));
/*
* We're freeing a symlink which fit into
* the inode. Just free the memory used
* to hold the old symlink.
*/
error = xfs_trans_reserve(*tpp, 0,
XFS_ITRUNCATE_LOG_RES(ip->i_mount),
0, XFS_TRANS_PERM_LOG_RES,
XFS_ITRUNCATE_LOG_COUNT);
if (error) {
xfs_trans_cancel(*tpp, 0);
*tpp = NULL;
return error;
}
xfs_ilock(ip, XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL);
/*
* Zero length symlinks _can_ exist.
*/
if (ip->i_df.if_bytes > 0) {
xfs_idata_realloc(ip,
-(ip->i_df.if_bytes),
XFS_DATA_FORK);
ASSERT(ip->i_df.if_bytes == 0);
}
return 0;
}
STATIC int
xfs_inactive_attrs(
xfs_inode_t *ip,
xfs_trans_t **tpp)
{
xfs_trans_t *tp;
int error;
xfs_mount_t *mp;
ASSERT(xfs_isilocked(ip, XFS_IOLOCK_EXCL));
tp = *tpp;
mp = ip->i_mount;
ASSERT(ip->i_d.di_forkoff != 0);
error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
xfs_iunlock(ip, XFS_ILOCK_EXCL);
if (error)
goto error_unlock;
error = xfs_attr_inactive(ip);
if (error)
goto error_unlock;
tp = xfs_trans_alloc(mp, XFS_TRANS_INACTIVE);
error = xfs_trans_reserve(tp, 0,
XFS_IFREE_LOG_RES(mp),
0, XFS_TRANS_PERM_LOG_RES,
XFS_INACTIVE_LOG_COUNT);
if (error)
goto error_cancel;
xfs_ilock(ip, XFS_ILOCK_EXCL);
xfs_trans_ijoin(tp, ip, 0);
xfs_idestroy_fork(ip, XFS_ATTR_FORK);
ASSERT(ip->i_d.di_anextents == 0);
*tpp = tp;
return 0;
error_cancel:
ASSERT(XFS_FORCED_SHUTDOWN(mp));
xfs_trans_cancel(tp, 0);
error_unlock:
*tpp = NULL;
xfs_iunlock(ip, XFS_IOLOCK_EXCL);
return error;
}
int
xfs_release(
xfs_inode_t *ip)
{
xfs_mount_t *mp = ip->i_mount;
int error;
if (!S_ISREG(ip->i_d.di_mode) || (ip->i_d.di_mode == 0))
return 0;
/* If this is a read-only mount, don't do this (would generate I/O) */
if (mp->m_flags & XFS_MOUNT_RDONLY)
return 0;
if (!XFS_FORCED_SHUTDOWN(mp)) {
int truncated;
/*
* If we are using filestreams, and we have an unlinked
* file that we are processing the last close on, then nothing
* will be able to reopen and write to this file. Purge this
* inode from the filestreams cache so that it doesn't delay
* teardown of the inode.
*/
if ((ip->i_d.di_nlink == 0) && xfs_inode_is_filestream(ip))
xfs_filestream_deassociate(ip);
/*
* If we previously truncated this file and removed old data
* in the process, we want to initiate "early" writeout on
* the last close. This is an attempt to combat the notorious
* NULL files problem which is particularly noticeable from a
* truncate down, buffered (re-)write (delalloc), followed by
* a crash. What we are effectively doing here is
* significantly reducing the time window where we'd otherwise
* be exposed to that problem.
*/
truncated = xfs_iflags_test_and_clear(ip, XFS_ITRUNCATED);
if (truncated) {
xfs_iflags_clear(ip, XFS_IDIRTY_RELEASE);
if (VN_DIRTY(VFS_I(ip)) && ip->i_delayed_blks > 0)
xfs_flush_pages(ip, 0, -1, XBF_ASYNC, FI_NONE);
}
}
if (ip->i_d.di_nlink == 0)
return 0;
if ((S_ISREG(ip->i_d.di_mode) &&
(VFS_I(ip)->i_size > 0 ||
(VN_CACHED(VFS_I(ip)) > 0 || ip->i_delayed_blks > 0)) &&
(ip->i_df.if_flags & XFS_IFEXTENTS)) &&
(!(ip->i_d.di_flags & (XFS_DIFLAG_PREALLOC | XFS_DIFLAG_APPEND)))) {
/*
* If we can't get the iolock just skip truncating the blocks
* past EOF because we could deadlock with the mmap_sem
* otherwise. We'll get another chance to drop them once the
* last reference to the inode is dropped, so we'll never leak
* blocks permanently.
*
* Further, check if the inode is being opened, written and
* closed frequently and we have delayed allocation blocks
* outstanding (e.g. streaming writes from the NFS server),
* truncating the blocks past EOF will cause fragmentation to
* occur.
*
* In this case don't do the truncation, either, but we have to
* be careful how we detect this case. Blocks beyond EOF show
* up as i_delayed_blks even when the inode is clean, so we
* need to truncate them away first before checking for a dirty
* release. Hence on the first dirty close we will still remove
* the speculative allocation, but after that we will leave it
* in place.
*/
if (xfs_iflags_test(ip, XFS_IDIRTY_RELEASE))
return 0;
error = xfs_free_eofblocks(mp, ip,
XFS_FREE_EOF_TRYLOCK);
if (error)
return error;
/* delalloc blocks after truncation means it really is dirty */
if (ip->i_delayed_blks)
xfs_iflags_set(ip, XFS_IDIRTY_RELEASE);
}
return 0;
}
/*
* xfs_inactive
*
* This is called when the vnode reference count for the vnode
* goes to zero. If the file has been unlinked, then it must
* now be truncated. Also, we clear all of the read-ahead state
* kept for the inode here since the file is now closed.
*/
int
xfs_inactive(
xfs_inode_t *ip)
{
xfs_bmap_free_t free_list;
xfs_fsblock_t first_block;
int committed;
xfs_trans_t *tp;
xfs_mount_t *mp;
int error;
int truncate;
/*
* If the inode is already free, then there can be nothing
* to clean up here.
*/
if (ip->i_d.di_mode == 0 || is_bad_inode(VFS_I(ip))) {
ASSERT(ip->i_df.if_real_bytes == 0);
ASSERT(ip->i_df.if_broot_bytes == 0);
return VN_INACTIVE_CACHE;
}
/*
* Only do a truncate if it's a regular file with
* some actual space in it. It's OK to look at the
* inode's fields without the lock because we're the
* only one with a reference to the inode.
*/
truncate = ((ip->i_d.di_nlink == 0) &&
((ip->i_d.di_size != 0) || XFS_ISIZE(ip) != 0 ||
(ip->i_d.di_nextents > 0) || (ip->i_delayed_blks > 0)) &&
S_ISREG(ip->i_d.di_mode));
mp = ip->i_mount;
error = 0;
/* If this is a read-only mount, don't do this (would generate I/O) */
if (mp->m_flags & XFS_MOUNT_RDONLY)
goto out;
if (ip->i_d.di_nlink != 0) {
if ((S_ISREG(ip->i_d.di_mode) &&
(VFS_I(ip)->i_size > 0 ||
(VN_CACHED(VFS_I(ip)) > 0 || ip->i_delayed_blks > 0)) &&
(ip->i_df.if_flags & XFS_IFEXTENTS) &&
(!(ip->i_d.di_flags &
(XFS_DIFLAG_PREALLOC | XFS_DIFLAG_APPEND)) ||
ip->i_delayed_blks != 0))) {
error = xfs_free_eofblocks(mp, ip, 0);
if (error)
return VN_INACTIVE_CACHE;
}
goto out;
}
ASSERT(ip->i_d.di_nlink == 0);
error = xfs_qm_dqattach(ip, 0);
if (error)
return VN_INACTIVE_CACHE;
tp = xfs_trans_alloc(mp, XFS_TRANS_INACTIVE);
if (truncate) {
xfs_ilock(ip, XFS_IOLOCK_EXCL);
error = xfs_trans_reserve(tp, 0,
XFS_ITRUNCATE_LOG_RES(mp),
0, XFS_TRANS_PERM_LOG_RES,
XFS_ITRUNCATE_LOG_COUNT);
if (error) {
/* Don't call itruncate_cleanup */
ASSERT(XFS_FORCED_SHUTDOWN(mp));
xfs_trans_cancel(tp, 0);
xfs_iunlock(ip, XFS_IOLOCK_EXCL);
return VN_INACTIVE_CACHE;
}
xfs_ilock(ip, XFS_ILOCK_EXCL);
xfs_trans_ijoin(tp, ip, 0);
ip->i_d.di_size = 0;
xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
error = xfs_itruncate_extents(&tp, ip, XFS_DATA_FORK, 0);
if (error) {
xfs_trans_cancel(tp,
XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
xfs_iunlock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
return VN_INACTIVE_CACHE;
}
ASSERT(ip->i_d.di_nextents == 0);
} else if (S_ISLNK(ip->i_d.di_mode)) {
/*
* If we get an error while cleaning up a
* symlink we bail out.
*/
error = (ip->i_d.di_size > XFS_IFORK_DSIZE(ip)) ?
xfs_inactive_symlink_rmt(ip, &tp) :
xfs_inactive_symlink_local(ip, &tp);
if (error) {
ASSERT(tp == NULL);
return VN_INACTIVE_CACHE;
}
xfs_trans_ijoin(tp, ip, 0);
} else {
error = xfs_trans_reserve(tp, 0,
XFS_IFREE_LOG_RES(mp),
0, XFS_TRANS_PERM_LOG_RES,
XFS_INACTIVE_LOG_COUNT);
if (error) {
ASSERT(XFS_FORCED_SHUTDOWN(mp));
xfs_trans_cancel(tp, 0);
return VN_INACTIVE_CACHE;
}
xfs_ilock(ip, XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL);
xfs_trans_ijoin(tp, ip, 0);
}
/*
* If there are attributes associated with the file
* then blow them away now. The code calls a routine
* that recursively deconstructs the attribute fork.
* We need to just commit the current transaction
* because we can't use it for xfs_attr_inactive().
*/
if (ip->i_d.di_anextents > 0) {
error = xfs_inactive_attrs(ip, &tp);
/*
* If we got an error, the transaction is already
* cancelled, and the inode is unlocked. Just get out.
*/
if (error)
return VN_INACTIVE_CACHE;
} else if (ip->i_afp) {
xfs_idestroy_fork(ip, XFS_ATTR_FORK);
}
/*
* Free the inode.
*/
xfs_bmap_init(&free_list, &first_block);
error = xfs_ifree(tp, ip, &free_list);
if (error) {
/*
* If we fail to free the inode, shut down. The cancel
* might do that, we need to make sure. Otherwise the
* inode might be lost for a long time or forever.
*/
if (!XFS_FORCED_SHUTDOWN(mp)) {
xfs_notice(mp, "%s: xfs_ifree returned error %d",
__func__, error);
xfs_force_shutdown(mp, SHUTDOWN_META_IO_ERROR);
}
xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES|XFS_TRANS_ABORT);
} else {
/*
* Credit the quota account(s). The inode is gone.
*/
xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_ICOUNT, -1);
/*
* Just ignore errors at this point. There is nothing we can
* do except to try to keep going. Make sure it's not a silent
* error.
*/
error = xfs_bmap_finish(&tp, &free_list, &committed);
if (error)
xfs_notice(mp, "%s: xfs_bmap_finish returned error %d",
__func__, error);
error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
if (error)
xfs_notice(mp, "%s: xfs_trans_commit returned error %d",
__func__, error);
}
/*
* Release the dquots held by inode, if any.
*/
xfs_qm_dqdetach(ip);
xfs_iunlock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
out:
return VN_INACTIVE_CACHE;
}
/*
* Lookups up an inode from "name". If ci_name is not NULL, then a CI match
* is allowed, otherwise it has to be an exact match. If a CI match is found,
* ci_name->name will point to a the actual name (caller must free) or
* will be set to NULL if an exact match is found.
*/
int
xfs_lookup(
xfs_inode_t *dp,
struct xfs_name *name,
xfs_inode_t **ipp,
struct xfs_name *ci_name)
{
xfs_ino_t inum;
int error;
uint lock_mode;
trace_xfs_lookup(dp, name);
if (XFS_FORCED_SHUTDOWN(dp->i_mount))
return XFS_ERROR(EIO);
lock_mode = xfs_ilock_map_shared(dp);
error = xfs_dir_lookup(NULL, dp, name, &inum, ci_name);
xfs_iunlock_map_shared(dp, lock_mode);
if (error)
goto out;
error = xfs_iget(dp->i_mount, NULL, inum, 0, 0, ipp);
if (error)
goto out_free_name;
return 0;
out_free_name:
if (ci_name)
kmem_free(ci_name->name);
out:
*ipp = NULL;
return error;
}
int
xfs_create(
xfs_inode_t *dp,
struct xfs_name *name,
umode_t mode,
xfs_dev_t rdev,
xfs_inode_t **ipp)
{
int is_dir = S_ISDIR(mode);
struct xfs_mount *mp = dp->i_mount;
struct xfs_inode *ip = NULL;
struct xfs_trans *tp = NULL;
int error;
xfs_bmap_free_t free_list;
xfs_fsblock_t first_block;
boolean_t unlock_dp_on_error = B_FALSE;
uint cancel_flags;
int committed;
prid_t prid;
struct xfs_dquot *udqp = NULL;
struct xfs_dquot *gdqp = NULL;
uint resblks;
uint log_res;
uint log_count;
trace_xfs_create(dp, name);
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
if (dp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT)
prid = xfs_get_projid(dp);
else
prid = XFS_PROJID_DEFAULT;
/*
* Make sure that we have allocated dquot(s) on disk.
*/
error = xfs_qm_vop_dqalloc(dp, current_fsuid(), current_fsgid(), prid,
XFS_QMOPT_QUOTALL | XFS_QMOPT_INHERIT, &udqp, &gdqp);
if (error)
return error;
if (is_dir) {
rdev = 0;
resblks = XFS_MKDIR_SPACE_RES(mp, name->len);
log_res = XFS_MKDIR_LOG_RES(mp);
log_count = XFS_MKDIR_LOG_COUNT;
tp = xfs_trans_alloc(mp, XFS_TRANS_MKDIR);
} else {
resblks = XFS_CREATE_SPACE_RES(mp, name->len);
log_res = XFS_CREATE_LOG_RES(mp);
log_count = XFS_CREATE_LOG_COUNT;
tp = xfs_trans_alloc(mp, XFS_TRANS_CREATE);
}
cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
/*
* Initially assume that the file does not exist and
* reserve the resources for that case. If that is not
* the case we'll drop the one we have and get a more
* appropriate transaction later.
*/
error = xfs_trans_reserve(tp, resblks, log_res, 0,
XFS_TRANS_PERM_LOG_RES, log_count);
if (error == ENOSPC) {
/* flush outstanding delalloc blocks and retry */
xfs_flush_inodes(dp);
error = xfs_trans_reserve(tp, resblks, log_res, 0,
XFS_TRANS_PERM_LOG_RES, log_count);
}
if (error == ENOSPC) {
/* No space at all so try a "no-allocation" reservation */
resblks = 0;
error = xfs_trans_reserve(tp, 0, log_res, 0,
XFS_TRANS_PERM_LOG_RES, log_count);
}
if (error) {
cancel_flags = 0;
goto out_trans_cancel;
}
xfs_ilock(dp, XFS_ILOCK_EXCL | XFS_ILOCK_PARENT);
unlock_dp_on_error = B_TRUE;
xfs_bmap_init(&free_list, &first_block);
/*
* Reserve disk quota and the inode.
*/
error = xfs_trans_reserve_quota(tp, mp, udqp, gdqp, resblks, 1, 0);
if (error)
goto out_trans_cancel;
error = xfs_dir_canenter(tp, dp, name, resblks);
if (error)
goto out_trans_cancel;
/*
* A newly created regular or special file just has one directory
* entry pointing to them, but a directory also the "." entry
* pointing to itself.
*/
error = xfs_dir_ialloc(&tp, dp, mode, is_dir ? 2 : 1, rdev,
prid, resblks > 0, &ip, &committed);
if (error) {
if (error == ENOSPC)
goto out_trans_cancel;
goto out_trans_abort;
}
/*
* Now we join the directory inode to the transaction. We do not do it
* earlier because xfs_dir_ialloc might commit the previous transaction
* (and release all the locks). An error from here on will result in
* the transaction cancel unlocking dp so don't do it explicitly in the
* error path.
*/
xfs_trans_ijoin(tp, dp, XFS_ILOCK_EXCL);
unlock_dp_on_error = B_FALSE;
error = xfs_dir_createname(tp, dp, name, ip->i_ino,
&first_block, &free_list, resblks ?
resblks - XFS_IALLOC_SPACE_RES(mp) : 0);
if (error) {
ASSERT(error != ENOSPC);
goto out_trans_abort;
}
xfs_trans_ichgtime(tp, dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
if (is_dir) {
error = xfs_dir_init(tp, ip, dp);
if (error)
goto out_bmap_cancel;
error = xfs_bumplink(tp, dp);
if (error)
goto out_bmap_cancel;
}
/*
* If this is a synchronous mount, make sure that the
* create transaction goes to disk before returning to
* the user.
*/
if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC))
xfs_trans_set_sync(tp);
/*
* Attach the dquot(s) to the inodes and modify them incore.
* These ids of the inode couldn't have changed since the new
* inode has been locked ever since it was created.
*/
xfs_qm_vop_create_dqattach(tp, ip, udqp, gdqp);
error = xfs_bmap_finish(&tp, &free_list, &committed);
if (error)
goto out_bmap_cancel;
error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
if (error)
goto out_release_inode;
xfs_qm_dqrele(udqp);
xfs_qm_dqrele(gdqp);
*ipp = ip;
return 0;
out_bmap_cancel:
xfs_bmap_cancel(&free_list);
out_trans_abort:
cancel_flags |= XFS_TRANS_ABORT;
out_trans_cancel:
xfs_trans_cancel(tp, cancel_flags);
out_release_inode:
/*
* Wait until after the current transaction is aborted to
* release the inode. This prevents recursive transactions
* and deadlocks from xfs_inactive.
*/
if (ip)
IRELE(ip);
xfs_qm_dqrele(udqp);
xfs_qm_dqrele(gdqp);
if (unlock_dp_on_error)
xfs_iunlock(dp, XFS_ILOCK_EXCL);
return error;
}
#ifdef DEBUG
int xfs_locked_n;
int xfs_small_retries;
int xfs_middle_retries;
int xfs_lots_retries;
int xfs_lock_delays;
#endif
/*
* Bump the subclass so xfs_lock_inodes() acquires each lock with
* a different value
*/
static inline int
xfs_lock_inumorder(int lock_mode, int subclass)
{
if (lock_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL))
lock_mode |= (subclass + XFS_LOCK_INUMORDER) << XFS_IOLOCK_SHIFT;
if (lock_mode & (XFS_ILOCK_SHARED|XFS_ILOCK_EXCL))
lock_mode |= (subclass + XFS_LOCK_INUMORDER) << XFS_ILOCK_SHIFT;
return lock_mode;
}
/*
* The following routine will lock n inodes in exclusive mode.
* We assume the caller calls us with the inodes in i_ino order.
*
* We need to detect deadlock where an inode that we lock
* is in the AIL and we start waiting for another inode that is locked
* by a thread in a long running transaction (such as truncate). This can
* result in deadlock since the long running trans might need to wait
* for the inode we just locked in order to push the tail and free space
* in the log.
*/
void
xfs_lock_inodes(
xfs_inode_t **ips,
int inodes,
uint lock_mode)
{
int attempts = 0, i, j, try_lock;
xfs_log_item_t *lp;
ASSERT(ips && (inodes >= 2)); /* we need at least two */
try_lock = 0;
i = 0;
again:
for (; i < inodes; i++) {
ASSERT(ips[i]);
if (i && (ips[i] == ips[i-1])) /* Already locked */
continue;
/*
* If try_lock is not set yet, make sure all locked inodes
* are not in the AIL.
* If any are, set try_lock to be used later.
*/
if (!try_lock) {
for (j = (i - 1); j >= 0 && !try_lock; j--) {
lp = (xfs_log_item_t *)ips[j]->i_itemp;
if (lp && (lp->li_flags & XFS_LI_IN_AIL)) {
try_lock++;
}
}
}
/*
* If any of the previous locks we have locked is in the AIL,
* we must TRY to get the second and subsequent locks. If
* we can't get any, we must release all we have
* and try again.
*/
if (try_lock) {
/* try_lock must be 0 if i is 0. */
/*
* try_lock means we have an inode locked
* that is in the AIL.
*/
ASSERT(i != 0);
if (!xfs_ilock_nowait(ips[i], xfs_lock_inumorder(lock_mode, i))) {
attempts++;
/*
* Unlock all previous guys and try again.
* xfs_iunlock will try to push the tail
* if the inode is in the AIL.
*/
for(j = i - 1; j >= 0; j--) {
/*
* Check to see if we've already
* unlocked this one.
* Not the first one going back,
* and the inode ptr is the same.
*/
if ((j != (i - 1)) && ips[j] ==
ips[j+1])
continue;
xfs_iunlock(ips[j], lock_mode);
}
if ((attempts % 5) == 0) {
delay(1); /* Don't just spin the CPU */
#ifdef DEBUG
xfs_lock_delays++;
#endif
}
i = 0;
try_lock = 0;
goto again;
}
} else {
xfs_ilock(ips[i], xfs_lock_inumorder(lock_mode, i));
}
}
#ifdef DEBUG
if (attempts) {
if (attempts < 5) xfs_small_retries++;
else if (attempts < 100) xfs_middle_retries++;
else xfs_lots_retries++;
} else {
xfs_locked_n++;
}
#endif
}
/*
* xfs_lock_two_inodes() can only be used to lock one type of lock
* at a time - the iolock or the ilock, but not both at once. If
* we lock both at once, lockdep will report false positives saying
* we have violated locking orders.
*/
void
xfs_lock_two_inodes(
xfs_inode_t *ip0,
xfs_inode_t *ip1,
uint lock_mode)
{
xfs_inode_t *temp;
int attempts = 0;
xfs_log_item_t *lp;
if (lock_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL))
ASSERT((lock_mode & (XFS_ILOCK_SHARED|XFS_ILOCK_EXCL)) == 0);
ASSERT(ip0->i_ino != ip1->i_ino);
if (ip0->i_ino > ip1->i_ino) {
temp = ip0;
ip0 = ip1;
ip1 = temp;
}
again:
xfs_ilock(ip0, xfs_lock_inumorder(lock_mode, 0));
/*
* If the first lock we have locked is in the AIL, we must TRY to get
* the second lock. If we can't get it, we must release the first one
* and try again.
*/
lp = (xfs_log_item_t *)ip0->i_itemp;
if (lp && (lp->li_flags & XFS_LI_IN_AIL)) {
if (!xfs_ilock_nowait(ip1, xfs_lock_inumorder(lock_mode, 1))) {
xfs_iunlock(ip0, lock_mode);
if ((++attempts % 5) == 0)
delay(1); /* Don't just spin the CPU */
goto again;
}
} else {
xfs_ilock(ip1, xfs_lock_inumorder(lock_mode, 1));
}
}
int
xfs_remove(
xfs_inode_t *dp,
struct xfs_name *name,
xfs_inode_t *ip)
{
xfs_mount_t *mp = dp->i_mount;
xfs_trans_t *tp = NULL;
int is_dir = S_ISDIR(ip->i_d.di_mode);
int error = 0;
xfs_bmap_free_t free_list;
xfs_fsblock_t first_block;
int cancel_flags;
int committed;
int link_zero;
uint resblks;
uint log_count;
trace_xfs_remove(dp, name);
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
error = xfs_qm_dqattach(dp, 0);
if (error)
goto std_return;
error = xfs_qm_dqattach(ip, 0);
if (error)
goto std_return;
if (is_dir) {
tp = xfs_trans_alloc(mp, XFS_TRANS_RMDIR);
log_count = XFS_DEFAULT_LOG_COUNT;
} else {
tp = xfs_trans_alloc(mp, XFS_TRANS_REMOVE);
log_count = XFS_REMOVE_LOG_COUNT;
}
cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
/*
* We try to get the real space reservation first,
* allowing for directory btree deletion(s) implying
* possible bmap insert(s). If we can't get the space
* reservation then we use 0 instead, and avoid the bmap
* btree insert(s) in the directory code by, if the bmap
* insert tries to happen, instead trimming the LAST
* block from the directory.
*/
resblks = XFS_REMOVE_SPACE_RES(mp);
error = xfs_trans_reserve(tp, resblks, XFS_REMOVE_LOG_RES(mp), 0,
XFS_TRANS_PERM_LOG_RES, log_count);
if (error == ENOSPC) {
resblks = 0;
error = xfs_trans_reserve(tp, 0, XFS_REMOVE_LOG_RES(mp), 0,
XFS_TRANS_PERM_LOG_RES, log_count);
}
if (error) {
ASSERT(error != ENOSPC);
cancel_flags = 0;
goto out_trans_cancel;
}
xfs_lock_two_inodes(dp, ip, XFS_ILOCK_EXCL);
xfs_trans_ijoin(tp, dp, XFS_ILOCK_EXCL);
xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
/*
* If we're removing a directory perform some additional validation.
*/
if (is_dir) {
ASSERT(ip->i_d.di_nlink >= 2);
if (ip->i_d.di_nlink != 2) {
error = XFS_ERROR(ENOTEMPTY);
goto out_trans_cancel;
}
if (!xfs_dir_isempty(ip)) {
error = XFS_ERROR(ENOTEMPTY);
goto out_trans_cancel;
}
}
xfs_bmap_init(&free_list, &first_block);
error = xfs_dir_removename(tp, dp, name, ip->i_ino,
&first_block, &free_list, resblks);
if (error) {
ASSERT(error != ENOENT);
goto out_bmap_cancel;
}
xfs_trans_ichgtime(tp, dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
if (is_dir) {
/*
* Drop the link from ip's "..".
*/
error = xfs_droplink(tp, dp);
if (error)
goto out_bmap_cancel;
/*
* Drop the "." link from ip to self.
*/
error = xfs_droplink(tp, ip);
if (error)
goto out_bmap_cancel;
} else {
/*
* When removing a non-directory we need to log the parent
* inode here. For a directory this is done implicitly
* by the xfs_droplink call for the ".." entry.
*/
xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
}
/*
* Drop the link from dp to ip.
*/
error = xfs_droplink(tp, ip);
if (error)
goto out_bmap_cancel;
/*
* Determine if this is the last link while
* we are in the transaction.
*/
link_zero = (ip->i_d.di_nlink == 0);
/*
* If this is a synchronous mount, make sure that the
* remove transaction goes to disk before returning to
* the user.
*/
if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC))
xfs_trans_set_sync(tp);
error = xfs_bmap_finish(&tp, &free_list, &committed);
if (error)
goto out_bmap_cancel;
error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
if (error)
goto std_return;
/*
* If we are using filestreams, kill the stream association.
* If the file is still open it may get a new one but that
* will get killed on last close in xfs_close() so we don't
* have to worry about that.
*/
if (!is_dir && link_zero && xfs_inode_is_filestream(ip))
xfs_filestream_deassociate(ip);
return 0;
out_bmap_cancel:
xfs_bmap_cancel(&free_list);
cancel_flags |= XFS_TRANS_ABORT;
out_trans_cancel:
xfs_trans_cancel(tp, cancel_flags);
std_return:
return error;
}
int
xfs_link(
xfs_inode_t *tdp,
xfs_inode_t *sip,
struct xfs_name *target_name)
{
xfs_mount_t *mp = tdp->i_mount;
xfs_trans_t *tp;
int error;
xfs_bmap_free_t free_list;
xfs_fsblock_t first_block;
int cancel_flags;
int committed;
int resblks;
trace_xfs_link(tdp, target_name);
ASSERT(!S_ISDIR(sip->i_d.di_mode));
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
error = xfs_qm_dqattach(sip, 0);
if (error)
goto std_return;
error = xfs_qm_dqattach(tdp, 0);
if (error)
goto std_return;
tp = xfs_trans_alloc(mp, XFS_TRANS_LINK);
cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
resblks = XFS_LINK_SPACE_RES(mp, target_name->len);
error = xfs_trans_reserve(tp, resblks, XFS_LINK_LOG_RES(mp), 0,
XFS_TRANS_PERM_LOG_RES, XFS_LINK_LOG_COUNT);
if (error == ENOSPC) {
resblks = 0;
error = xfs_trans_reserve(tp, 0, XFS_LINK_LOG_RES(mp), 0,
XFS_TRANS_PERM_LOG_RES, XFS_LINK_LOG_COUNT);
}
if (error) {
cancel_flags = 0;
goto error_return;
}
xfs_lock_two_inodes(sip, tdp, XFS_ILOCK_EXCL);
xfs_trans_ijoin(tp, sip, XFS_ILOCK_EXCL);
xfs_trans_ijoin(tp, tdp, XFS_ILOCK_EXCL);
/*
* If we are using project inheritance, we only allow hard link
* creation in our tree when the project IDs are the same; else
* the tree quota mechanism could be circumvented.
*/
if (unlikely((tdp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT) &&
(xfs_get_projid(tdp) != xfs_get_projid(sip)))) {
error = XFS_ERROR(EXDEV);
goto error_return;
}
error = xfs_dir_canenter(tp, tdp, target_name, resblks);
if (error)
goto error_return;
xfs_bmap_init(&free_list, &first_block);
error = xfs_dir_createname(tp, tdp, target_name, sip->i_ino,
&first_block, &free_list, resblks);
if (error)
goto abort_return;
xfs_trans_ichgtime(tp, tdp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
xfs_trans_log_inode(tp, tdp, XFS_ILOG_CORE);
error = xfs_bumplink(tp, sip);
if (error)
goto abort_return;
/*
* If this is a synchronous mount, make sure that the
* link transaction goes to disk before returning to
* the user.
*/
if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC)) {
xfs_trans_set_sync(tp);
}
error = xfs_bmap_finish (&tp, &free_list, &committed);
if (error) {
xfs_bmap_cancel(&free_list);
goto abort_return;
}
return xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
abort_return:
cancel_flags |= XFS_TRANS_ABORT;
error_return:
xfs_trans_cancel(tp, cancel_flags);
std_return:
return error;
}
int
xfs_symlink(
xfs_inode_t *dp,
struct xfs_name *link_name,
const char *target_path,
umode_t mode,
xfs_inode_t **ipp)
{
xfs_mount_t *mp = dp->i_mount;
xfs_trans_t *tp;
xfs_inode_t *ip;
int error;
int pathlen;
xfs_bmap_free_t free_list;
xfs_fsblock_t first_block;
boolean_t unlock_dp_on_error = B_FALSE;
uint cancel_flags;
int committed;
xfs_fileoff_t first_fsb;
xfs_filblks_t fs_blocks;
int nmaps;
xfs_bmbt_irec_t mval[SYMLINK_MAPS];
xfs_daddr_t d;
const char *cur_chunk;
int byte_cnt;
int n;
xfs_buf_t *bp;
prid_t prid;
struct xfs_dquot *udqp, *gdqp;
uint resblks;
*ipp = NULL;
error = 0;
ip = NULL;
tp = NULL;
trace_xfs_symlink(dp, link_name);
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
/*
* Check component lengths of the target path name.
*/
pathlen = strlen(target_path);
if (pathlen >= MAXPATHLEN) /* total string too long */
return XFS_ERROR(ENAMETOOLONG);
udqp = gdqp = NULL;
if (dp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT)
prid = xfs_get_projid(dp);
else
prid = XFS_PROJID_DEFAULT;
/*
* Make sure that we have allocated dquot(s) on disk.
*/
error = xfs_qm_vop_dqalloc(dp, current_fsuid(), current_fsgid(), prid,
XFS_QMOPT_QUOTALL | XFS_QMOPT_INHERIT, &udqp, &gdqp);
if (error)
goto std_return;
tp = xfs_trans_alloc(mp, XFS_TRANS_SYMLINK);
cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
/*
* The symlink will fit into the inode data fork?
* There can't be any attributes so we get the whole variable part.
*/
if (pathlen <= XFS_LITINO(mp))
fs_blocks = 0;
else
fs_blocks = XFS_B_TO_FSB(mp, pathlen);
resblks = XFS_SYMLINK_SPACE_RES(mp, link_name->len, fs_blocks);
error = xfs_trans_reserve(tp, resblks, XFS_SYMLINK_LOG_RES(mp), 0,
XFS_TRANS_PERM_LOG_RES, XFS_SYMLINK_LOG_COUNT);
if (error == ENOSPC && fs_blocks == 0) {
resblks = 0;
error = xfs_trans_reserve(tp, 0, XFS_SYMLINK_LOG_RES(mp), 0,
XFS_TRANS_PERM_LOG_RES, XFS_SYMLINK_LOG_COUNT);
}
if (error) {
cancel_flags = 0;
goto error_return;
}
xfs_ilock(dp, XFS_ILOCK_EXCL | XFS_ILOCK_PARENT);
unlock_dp_on_error = B_TRUE;
/*
* Check whether the directory allows new symlinks or not.
*/
if (dp->i_d.di_flags & XFS_DIFLAG_NOSYMLINKS) {
error = XFS_ERROR(EPERM);
goto error_return;
}
/*
* Reserve disk quota : blocks and inode.
*/
error = xfs_trans_reserve_quota(tp, mp, udqp, gdqp, resblks, 1, 0);
if (error)
goto error_return;
/*
* Check for ability to enter directory entry, if no space reserved.
*/
error = xfs_dir_canenter(tp, dp, link_name, resblks);
if (error)
goto error_return;
/*
* Initialize the bmap freelist prior to calling either
* bmapi or the directory create code.
*/
xfs_bmap_init(&free_list, &first_block);
/*
* Allocate an inode for the symlink.
*/
error = xfs_dir_ialloc(&tp, dp, S_IFLNK | (mode & ~S_IFMT), 1, 0,
prid, resblks > 0, &ip, NULL);
if (error) {
if (error == ENOSPC)
goto error_return;
goto error1;
}
/*
* An error after we've joined dp to the transaction will result in the
* transaction cancel unlocking dp so don't do it explicitly in the
* error path.
*/
xfs_trans_ijoin(tp, dp, XFS_ILOCK_EXCL);
unlock_dp_on_error = B_FALSE;
/*
* Also attach the dquot(s) to it, if applicable.
*/
xfs_qm_vop_create_dqattach(tp, ip, udqp, gdqp);
if (resblks)
resblks -= XFS_IALLOC_SPACE_RES(mp);
/*
* If the symlink will fit into the inode, write it inline.
*/
if (pathlen <= XFS_IFORK_DSIZE(ip)) {
xfs_idata_realloc(ip, pathlen, XFS_DATA_FORK);
memcpy(ip->i_df.if_u1.if_data, target_path, pathlen);
ip->i_d.di_size = pathlen;
/*
* The inode was initially created in extent format.
*/
ip->i_df.if_flags &= ~(XFS_IFEXTENTS | XFS_IFBROOT);
ip->i_df.if_flags |= XFS_IFINLINE;
ip->i_d.di_format = XFS_DINODE_FMT_LOCAL;
xfs_trans_log_inode(tp, ip, XFS_ILOG_DDATA | XFS_ILOG_CORE);
} else {
first_fsb = 0;
nmaps = SYMLINK_MAPS;
error = xfs_bmapi_write(tp, ip, first_fsb, fs_blocks,
XFS_BMAPI_METADATA, &first_block, resblks,
mval, &nmaps, &free_list);
if (error)
goto error2;
if (resblks)
resblks -= fs_blocks;
ip->i_d.di_size = pathlen;
xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
cur_chunk = target_path;
for (n = 0; n < nmaps; n++) {
d = XFS_FSB_TO_DADDR(mp, mval[n].br_startblock);
byte_cnt = XFS_FSB_TO_B(mp, mval[n].br_blockcount);
bp = xfs_trans_get_buf(tp, mp->m_ddev_targp, d,
BTOBB(byte_cnt), 0);
if (!bp) {
error = ENOMEM;
goto error2;
}
if (pathlen < byte_cnt) {
byte_cnt = pathlen;
}
pathlen -= byte_cnt;
memcpy(bp->b_addr, cur_chunk, byte_cnt);
cur_chunk += byte_cnt;
xfs_trans_log_buf(tp, bp, 0, byte_cnt - 1);
}
}
/*
* Create the directory entry for the symlink.
*/
error = xfs_dir_createname(tp, dp, link_name, ip->i_ino,
&first_block, &free_list, resblks);
if (error)
goto error2;
xfs_trans_ichgtime(tp, dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
/*
* If this is a synchronous mount, make sure that the
* symlink transaction goes to disk before returning to
* the user.
*/
if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC)) {
xfs_trans_set_sync(tp);
}
error = xfs_bmap_finish(&tp, &free_list, &committed);
if (error) {
goto error2;
}
error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
xfs_qm_dqrele(udqp);
xfs_qm_dqrele(gdqp);
*ipp = ip;
return 0;
error2:
IRELE(ip);
error1:
xfs_bmap_cancel(&free_list);
cancel_flags |= XFS_TRANS_ABORT;
error_return:
xfs_trans_cancel(tp, cancel_flags);
xfs_qm_dqrele(udqp);
xfs_qm_dqrele(gdqp);
if (unlock_dp_on_error)
xfs_iunlock(dp, XFS_ILOCK_EXCL);
std_return:
return error;
}
int
xfs_set_dmattrs(
xfs_inode_t *ip,
u_int evmask,
u_int16_t state)
{
xfs_mount_t *mp = ip->i_mount;
xfs_trans_t *tp;
int error;
if (!capable(CAP_SYS_ADMIN))
return XFS_ERROR(EPERM);
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
tp = xfs_trans_alloc(mp, XFS_TRANS_SET_DMATTRS);
error = xfs_trans_reserve(tp, 0, XFS_ICHANGE_LOG_RES (mp), 0, 0, 0);
if (error) {
xfs_trans_cancel(tp, 0);
return error;
}
xfs_ilock(ip, XFS_ILOCK_EXCL);
xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
ip->i_d.di_dmevmask = evmask;
ip->i_d.di_dmstate = state;
xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
error = xfs_trans_commit(tp, 0);
return error;
}
/*
* xfs_alloc_file_space()
* This routine allocates disk space for the given file.
*
* If alloc_type == 0, this request is for an ALLOCSP type
* request which will change the file size. In this case, no
* DMAPI event will be generated by the call. A TRUNCATE event
* will be generated later by xfs_setattr.
*
* If alloc_type != 0, this request is for a RESVSP type
* request, and a DMAPI DM_EVENT_WRITE will be generated if the
* lower block boundary byte address is less than the file's
* length.
*
* RETURNS:
* 0 on success
* errno on error
*
*/
STATIC int
xfs_alloc_file_space(
xfs_inode_t *ip,
xfs_off_t offset,
xfs_off_t len,
int alloc_type,
int attr_flags)
{
xfs_mount_t *mp = ip->i_mount;
xfs_off_t count;
xfs_filblks_t allocated_fsb;
xfs_filblks_t allocatesize_fsb;
xfs_extlen_t extsz, temp;
xfs_fileoff_t startoffset_fsb;
xfs_fsblock_t firstfsb;
int nimaps;
int quota_flag;
int rt;
xfs_trans_t *tp;
xfs_bmbt_irec_t imaps[1], *imapp;
xfs_bmap_free_t free_list;
uint qblocks, resblks, resrtextents;
int committed;
int error;
trace_xfs_alloc_file_space(ip);
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
error = xfs_qm_dqattach(ip, 0);
if (error)
return error;
if (len <= 0)
return XFS_ERROR(EINVAL);
rt = XFS_IS_REALTIME_INODE(ip);
extsz = xfs_get_extsz_hint(ip);
count = len;
imapp = &imaps[0];
nimaps = 1;
startoffset_fsb = XFS_B_TO_FSBT(mp, offset);
allocatesize_fsb = XFS_B_TO_FSB(mp, count);
/*
* Allocate file space until done or until there is an error
*/
while (allocatesize_fsb && !error) {
xfs_fileoff_t s, e;
/*
* Determine space reservations for data/realtime.
*/
if (unlikely(extsz)) {
s = startoffset_fsb;
do_div(s, extsz);
s *= extsz;
e = startoffset_fsb + allocatesize_fsb;
if ((temp = do_mod(startoffset_fsb, extsz)))
e += temp;
if ((temp = do_mod(e, extsz)))
e += extsz - temp;
} else {
s = 0;
e = allocatesize_fsb;
}
/*
* The transaction reservation is limited to a 32-bit block
* count, hence we need to limit the number of blocks we are
* trying to reserve to avoid an overflow. We can't allocate
* more than @nimaps extents, and an extent is limited on disk
* to MAXEXTLEN (21 bits), so use that to enforce the limit.
*/
resblks = min_t(xfs_fileoff_t, (e - s), (MAXEXTLEN * nimaps));
if (unlikely(rt)) {
resrtextents = qblocks = resblks;
resrtextents /= mp->m_sb.sb_rextsize;
resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
quota_flag = XFS_QMOPT_RES_RTBLKS;
} else {
resrtextents = 0;
resblks = qblocks = XFS_DIOSTRAT_SPACE_RES(mp, resblks);
quota_flag = XFS_QMOPT_RES_REGBLKS;
}
/*
* Allocate and setup the transaction.
*/
tp = xfs_trans_alloc(mp, XFS_TRANS_DIOSTRAT);
error = xfs_trans_reserve(tp, resblks,
XFS_WRITE_LOG_RES(mp), resrtextents,
XFS_TRANS_PERM_LOG_RES,
XFS_WRITE_LOG_COUNT);
/*
* Check for running out of space
*/
if (error) {
/*
* Free the transaction structure.
*/
ASSERT(error == ENOSPC || XFS_FORCED_SHUTDOWN(mp));
xfs_trans_cancel(tp, 0);
break;
}
xfs_ilock(ip, XFS_ILOCK_EXCL);
error = xfs_trans_reserve_quota_nblks(tp, ip, qblocks,
0, quota_flag);
if (error)
goto error1;
xfs_trans_ijoin(tp, ip, 0);
xfs_bmap_init(&free_list, &firstfsb);
error = xfs_bmapi_write(tp, ip, startoffset_fsb,
allocatesize_fsb, alloc_type, &firstfsb,
0, imapp, &nimaps, &free_list);
if (error) {
goto error0;
}
/*
* Complete the transaction
*/
error = xfs_bmap_finish(&tp, &free_list, &committed);
if (error) {
goto error0;
}
error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
xfs_iunlock(ip, XFS_ILOCK_EXCL);
if (error) {
break;
}
allocated_fsb = imapp->br_blockcount;
if (nimaps == 0) {
error = XFS_ERROR(ENOSPC);
break;
}
startoffset_fsb += allocated_fsb;
allocatesize_fsb -= allocated_fsb;
}
return error;
error0: /* Cancel bmap, unlock inode, unreserve quota blocks, cancel trans */
xfs_bmap_cancel(&free_list);
xfs_trans_unreserve_quota_nblks(tp, ip, qblocks, 0, quota_flag);
error1: /* Just cancel transaction */
xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
xfs_iunlock(ip, XFS_ILOCK_EXCL);
return error;
}
/*
* Zero file bytes between startoff and endoff inclusive.
* The iolock is held exclusive and no blocks are buffered.
*
* This function is used by xfs_free_file_space() to zero
* partial blocks when the range to free is not block aligned.
* When unreserving space with boundaries that are not block
* aligned we round up the start and round down the end
* boundaries and then use this function to zero the parts of
* the blocks that got dropped during the rounding.
*/
STATIC int
xfs_zero_remaining_bytes(
xfs_inode_t *ip,
xfs_off_t startoff,
xfs_off_t endoff)
{
xfs_bmbt_irec_t imap;
xfs_fileoff_t offset_fsb;
xfs_off_t lastoffset;
xfs_off_t offset;
xfs_buf_t *bp;
xfs_mount_t *mp = ip->i_mount;
int nimap;
int error = 0;
/*
* Avoid doing I/O beyond eof - it's not necessary
* since nothing can read beyond eof. The space will
* be zeroed when the file is extended anyway.
*/
if (startoff >= XFS_ISIZE(ip))
return 0;
if (endoff > XFS_ISIZE(ip))
endoff = XFS_ISIZE(ip);
bp = xfs_buf_get_uncached(XFS_IS_REALTIME_INODE(ip) ?
mp->m_rtdev_targp : mp->m_ddev_targp,
mp->m_sb.sb_blocksize, XBF_DONT_BLOCK);
if (!bp)
return XFS_ERROR(ENOMEM);
xfs_buf_unlock(bp);
for (offset = startoff; offset <= endoff; offset = lastoffset + 1) {
offset_fsb = XFS_B_TO_FSBT(mp, offset);
nimap = 1;
error = xfs_bmapi_read(ip, offset_fsb, 1, &imap, &nimap, 0);
if (error || nimap < 1)
break;
ASSERT(imap.br_blockcount >= 1);
ASSERT(imap.br_startoff == offset_fsb);
lastoffset = XFS_FSB_TO_B(mp, imap.br_startoff + 1) - 1;
if (lastoffset > endoff)
lastoffset = endoff;
if (imap.br_startblock == HOLESTARTBLOCK)
continue;
ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
if (imap.br_state == XFS_EXT_UNWRITTEN)
continue;
XFS_BUF_UNDONE(bp);
XFS_BUF_UNWRITE(bp);
XFS_BUF_READ(bp);
XFS_BUF_SET_ADDR(bp, xfs_fsb_to_db(ip, imap.br_startblock));
xfsbdstrat(mp, bp);
error = xfs_buf_iowait(bp);
if (error) {
xfs_buf_ioerror_alert(bp,
"xfs_zero_remaining_bytes(read)");
break;
}
memset(bp->b_addr +
(offset - XFS_FSB_TO_B(mp, imap.br_startoff)),
0, lastoffset - offset + 1);
XFS_BUF_UNDONE(bp);
XFS_BUF_UNREAD(bp);
XFS_BUF_WRITE(bp);
xfsbdstrat(mp, bp);
error = xfs_buf_iowait(bp);
if (error) {
xfs_buf_ioerror_alert(bp,
"xfs_zero_remaining_bytes(write)");
break;
}
}
xfs_buf_free(bp);
return error;
}
/*
* xfs_free_file_space()
* This routine frees disk space for the given file.
*
* This routine is only called by xfs_change_file_space
* for an UNRESVSP type call.
*
* RETURNS:
* 0 on success
* errno on error
*
*/
STATIC int
xfs_free_file_space(
xfs_inode_t *ip,
xfs_off_t offset,
xfs_off_t len,
int attr_flags)
{
int committed;
int done;
xfs_fileoff_t endoffset_fsb;
int error;
xfs_fsblock_t firstfsb;
xfs_bmap_free_t free_list;
xfs_bmbt_irec_t imap;
xfs_off_t ioffset;
xfs_extlen_t mod=0;
xfs_mount_t *mp;
int nimap;
uint resblks;
uint rounding;
int rt;
xfs_fileoff_t startoffset_fsb;
xfs_trans_t *tp;
int need_iolock = 1;
mp = ip->i_mount;
trace_xfs_free_file_space(ip);
error = xfs_qm_dqattach(ip, 0);
if (error)
return error;
error = 0;
if (len <= 0) /* if nothing being freed */
return error;
rt = XFS_IS_REALTIME_INODE(ip);
startoffset_fsb = XFS_B_TO_FSB(mp, offset);
endoffset_fsb = XFS_B_TO_FSBT(mp, offset + len);
if (attr_flags & XFS_ATTR_NOLOCK)
need_iolock = 0;
if (need_iolock) {
xfs_ilock(ip, XFS_IOLOCK_EXCL);
/* wait for the completion of any pending DIOs */
inode_dio_wait(VFS_I(ip));
}
rounding = max_t(uint, 1 << mp->m_sb.sb_blocklog, PAGE_CACHE_SIZE);
ioffset = offset & ~(rounding - 1);
if (VN_CACHED(VFS_I(ip)) != 0) {
error = xfs_flushinval_pages(ip, ioffset, -1, FI_REMAPF_LOCKED);
if (error)
goto out_unlock_iolock;
}
/*
* Need to zero the stuff we're not freeing, on disk.
* If it's a realtime file & can't use unwritten extents then we
* actually need to zero the extent edges. Otherwise xfs_bunmapi
* will take care of it for us.
*/
if (rt && !xfs_sb_version_hasextflgbit(&mp->m_sb)) {
nimap = 1;
error = xfs_bmapi_read(ip, startoffset_fsb, 1,
&imap, &nimap, 0);
if (error)
goto out_unlock_iolock;
ASSERT(nimap == 0 || nimap == 1);
if (nimap && imap.br_startblock != HOLESTARTBLOCK) {
xfs_daddr_t block;
ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
block = imap.br_startblock;
mod = do_div(block, mp->m_sb.sb_rextsize);
if (mod)
startoffset_fsb += mp->m_sb.sb_rextsize - mod;
}
nimap = 1;
error = xfs_bmapi_read(ip, endoffset_fsb - 1, 1,
&imap, &nimap, 0);
if (error)
goto out_unlock_iolock;
ASSERT(nimap == 0 || nimap == 1);
if (nimap && imap.br_startblock != HOLESTARTBLOCK) {
ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
mod++;
if (mod && (mod != mp->m_sb.sb_rextsize))
endoffset_fsb -= mod;
}
}
if ((done = (endoffset_fsb <= startoffset_fsb)))
/*
* One contiguous piece to clear
*/
error = xfs_zero_remaining_bytes(ip, offset, offset + len - 1);
else {
/*
* Some full blocks, possibly two pieces to clear
*/
if (offset < XFS_FSB_TO_B(mp, startoffset_fsb))
error = xfs_zero_remaining_bytes(ip, offset,
XFS_FSB_TO_B(mp, startoffset_fsb) - 1);
if (!error &&
XFS_FSB_TO_B(mp, endoffset_fsb) < offset + len)
error = xfs_zero_remaining_bytes(ip,
XFS_FSB_TO_B(mp, endoffset_fsb),
offset + len - 1);
}
/*
* free file space until done or until there is an error
*/
resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
while (!error && !done) {
/*
* allocate and setup the transaction. Allow this
* transaction to dip into the reserve blocks to ensure
* the freeing of the space succeeds at ENOSPC.
*/
tp = xfs_trans_alloc(mp, XFS_TRANS_DIOSTRAT);
tp->t_flags |= XFS_TRANS_RESERVE;
error = xfs_trans_reserve(tp,
resblks,
XFS_WRITE_LOG_RES(mp),
0,
XFS_TRANS_PERM_LOG_RES,
XFS_WRITE_LOG_COUNT);
/*
* check for running out of space
*/
if (error) {
/*
* Free the transaction structure.
*/
ASSERT(error == ENOSPC || XFS_FORCED_SHUTDOWN(mp));
xfs_trans_cancel(tp, 0);
break;
}
xfs_ilock(ip, XFS_ILOCK_EXCL);
error = xfs_trans_reserve_quota(tp, mp,
ip->i_udquot, ip->i_gdquot,
resblks, 0, XFS_QMOPT_RES_REGBLKS);
if (error)
goto error1;
xfs_trans_ijoin(tp, ip, 0);
/*
* issue the bunmapi() call to free the blocks
*/
xfs_bmap_init(&free_list, &firstfsb);
error = xfs_bunmapi(tp, ip, startoffset_fsb,
endoffset_fsb - startoffset_fsb,
0, 2, &firstfsb, &free_list, &done);
if (error) {
goto error0;
}
/*
* complete the transaction
*/
error = xfs_bmap_finish(&tp, &free_list, &committed);
if (error) {
goto error0;
}
error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
xfs_iunlock(ip, XFS_ILOCK_EXCL);
}
out_unlock_iolock:
if (need_iolock)
xfs_iunlock(ip, XFS_IOLOCK_EXCL);
return error;
error0:
xfs_bmap_cancel(&free_list);
error1:
xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
xfs_iunlock(ip, need_iolock ? (XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL) :
XFS_ILOCK_EXCL);
return error;
}
/*
* xfs_change_file_space()
* This routine allocates or frees disk space for the given file.
* The user specified parameters are checked for alignment and size
* limitations.
*
* RETURNS:
* 0 on success
* errno on error
*
*/
int
xfs_change_file_space(
xfs_inode_t *ip,
int cmd,
xfs_flock64_t *bf,
xfs_off_t offset,
int attr_flags)
{
xfs_mount_t *mp = ip->i_mount;
int clrprealloc;
int error;
xfs_fsize_t fsize;
int setprealloc;
xfs_off_t startoffset;
xfs_off_t llen;
xfs_trans_t *tp;
struct iattr iattr;
int prealloc_type;
if (!S_ISREG(ip->i_d.di_mode))
return XFS_ERROR(EINVAL);
switch (bf->l_whence) {
case 0: /*SEEK_SET*/
break;
case 1: /*SEEK_CUR*/
bf->l_start += offset;
break;
case 2: /*SEEK_END*/
bf->l_start += XFS_ISIZE(ip);
break;
default:
return XFS_ERROR(EINVAL);
}
llen = bf->l_len > 0 ? bf->l_len - 1 : bf->l_len;
if ( (bf->l_start < 0)
|| (bf->l_start > XFS_MAXIOFFSET(mp))
|| (bf->l_start + llen < 0)
|| (bf->l_start + llen > XFS_MAXIOFFSET(mp)))
return XFS_ERROR(EINVAL);
bf->l_whence = 0;
startoffset = bf->l_start;
fsize = XFS_ISIZE(ip);
/*
* XFS_IOC_RESVSP and XFS_IOC_UNRESVSP will reserve or unreserve
* file space.
* These calls do NOT zero the data space allocated to the file,
* nor do they change the file size.
*
* XFS_IOC_ALLOCSP and XFS_IOC_FREESP will allocate and free file
* space.
* These calls cause the new file data to be zeroed and the file
* size to be changed.
*/
setprealloc = clrprealloc = 0;
prealloc_type = XFS_BMAPI_PREALLOC;
switch (cmd) {
case XFS_IOC_ZERO_RANGE:
prealloc_type |= XFS_BMAPI_CONVERT;
xfs_tosspages(ip, startoffset, startoffset + bf->l_len, 0);
/* FALLTHRU */
case XFS_IOC_RESVSP:
case XFS_IOC_RESVSP64:
error = xfs_alloc_file_space(ip, startoffset, bf->l_len,
prealloc_type, attr_flags);
if (error)
return error;
setprealloc = 1;
break;
case XFS_IOC_UNRESVSP:
case XFS_IOC_UNRESVSP64:
if ((error = xfs_free_file_space(ip, startoffset, bf->l_len,
attr_flags)))
return error;
break;
case XFS_IOC_ALLOCSP:
case XFS_IOC_ALLOCSP64:
case XFS_IOC_FREESP:
case XFS_IOC_FREESP64:
if (startoffset > fsize) {
error = xfs_alloc_file_space(ip, fsize,
startoffset - fsize, 0, attr_flags);
if (error)
break;
}
iattr.ia_valid = ATTR_SIZE;
iattr.ia_size = startoffset;
error = xfs_setattr_size(ip, &iattr, attr_flags);
if (error)
return error;
clrprealloc = 1;
break;
default:
ASSERT(0);
return XFS_ERROR(EINVAL);
}
/*
* update the inode timestamp, mode, and prealloc flag bits
*/
tp = xfs_trans_alloc(mp, XFS_TRANS_WRITEID);
if ((error = xfs_trans_reserve(tp, 0, XFS_WRITEID_LOG_RES(mp),
0, 0, 0))) {
/* ASSERT(0); */
xfs_trans_cancel(tp, 0);
return error;
}
xfs_ilock(ip, XFS_ILOCK_EXCL);
xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
if ((attr_flags & XFS_ATTR_DMI) == 0) {
ip->i_d.di_mode &= ~S_ISUID;
/*
* Note that we don't have to worry about mandatory
* file locking being disabled here because we only
* clear the S_ISGID bit if the Group execute bit is
* on, but if it was on then mandatory locking wouldn't
* have been enabled.
*/
if (ip->i_d.di_mode & S_IXGRP)
ip->i_d.di_mode &= ~S_ISGID;
xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
}
if (setprealloc)
ip->i_d.di_flags |= XFS_DIFLAG_PREALLOC;
else if (clrprealloc)
ip->i_d.di_flags &= ~XFS_DIFLAG_PREALLOC;
xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
if (attr_flags & XFS_ATTR_SYNC)
xfs_trans_set_sync(tp);
return xfs_trans_commit(tp, 0);
}
| gpl-2.0 |
Evervolv/android_kernel_lge_mako | net/dccp/input.c | 5325 | 22109 | /*
* net/dccp/input.c
*
* An implementation of the DCCP protocol
* Arnaldo Carvalho de Melo <acme@conectiva.com.br>
*
* 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/dccp.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <net/sock.h>
#include "ackvec.h"
#include "ccid.h"
#include "dccp.h"
/* rate-limit for syncs in reply to sequence-invalid packets; RFC 4340, 7.5.4 */
int sysctl_dccp_sync_ratelimit __read_mostly = HZ / 8;
static void dccp_enqueue_skb(struct sock *sk, struct sk_buff *skb)
{
__skb_pull(skb, dccp_hdr(skb)->dccph_doff * 4);
__skb_queue_tail(&sk->sk_receive_queue, skb);
skb_set_owner_r(skb, sk);
sk->sk_data_ready(sk, 0);
}
static void dccp_fin(struct sock *sk, struct sk_buff *skb)
{
/*
* On receiving Close/CloseReq, both RD/WR shutdown are performed.
* RFC 4340, 8.3 says that we MAY send further Data/DataAcks after
* receiving the closing segment, but there is no guarantee that such
* data will be processed at all.
*/
sk->sk_shutdown = SHUTDOWN_MASK;
sock_set_flag(sk, SOCK_DONE);
dccp_enqueue_skb(sk, skb);
}
static int dccp_rcv_close(struct sock *sk, struct sk_buff *skb)
{
int queued = 0;
switch (sk->sk_state) {
/*
* We ignore Close when received in one of the following states:
* - CLOSED (may be a late or duplicate packet)
* - PASSIVE_CLOSEREQ (the peer has sent a CloseReq earlier)
* - RESPOND (already handled by dccp_check_req)
*/
case DCCP_CLOSING:
/*
* Simultaneous-close: receiving a Close after sending one. This
* can happen if both client and server perform active-close and
* will result in an endless ping-pong of crossing and retrans-
* mitted Close packets, which only terminates when one of the
* nodes times out (min. 64 seconds). Quicker convergence can be
* achieved when one of the nodes acts as tie-breaker.
* This is ok as both ends are done with data transfer and each
* end is just waiting for the other to acknowledge termination.
*/
if (dccp_sk(sk)->dccps_role != DCCP_ROLE_CLIENT)
break;
/* fall through */
case DCCP_REQUESTING:
case DCCP_ACTIVE_CLOSEREQ:
dccp_send_reset(sk, DCCP_RESET_CODE_CLOSED);
dccp_done(sk);
break;
case DCCP_OPEN:
case DCCP_PARTOPEN:
/* Give waiting application a chance to read pending data */
queued = 1;
dccp_fin(sk, skb);
dccp_set_state(sk, DCCP_PASSIVE_CLOSE);
/* fall through */
case DCCP_PASSIVE_CLOSE:
/*
* Retransmitted Close: we have already enqueued the first one.
*/
sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
}
return queued;
}
static int dccp_rcv_closereq(struct sock *sk, struct sk_buff *skb)
{
int queued = 0;
/*
* Step 7: Check for unexpected packet types
* If (S.is_server and P.type == CloseReq)
* Send Sync packet acknowledging P.seqno
* Drop packet and return
*/
if (dccp_sk(sk)->dccps_role != DCCP_ROLE_CLIENT) {
dccp_send_sync(sk, DCCP_SKB_CB(skb)->dccpd_seq, DCCP_PKT_SYNC);
return queued;
}
/* Step 13: process relevant Client states < CLOSEREQ */
switch (sk->sk_state) {
case DCCP_REQUESTING:
dccp_send_close(sk, 0);
dccp_set_state(sk, DCCP_CLOSING);
break;
case DCCP_OPEN:
case DCCP_PARTOPEN:
/* Give waiting application a chance to read pending data */
queued = 1;
dccp_fin(sk, skb);
dccp_set_state(sk, DCCP_PASSIVE_CLOSEREQ);
/* fall through */
case DCCP_PASSIVE_CLOSEREQ:
sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
}
return queued;
}
static u16 dccp_reset_code_convert(const u8 code)
{
const u16 error_code[] = {
[DCCP_RESET_CODE_CLOSED] = 0, /* normal termination */
[DCCP_RESET_CODE_UNSPECIFIED] = 0, /* nothing known */
[DCCP_RESET_CODE_ABORTED] = ECONNRESET,
[DCCP_RESET_CODE_NO_CONNECTION] = ECONNREFUSED,
[DCCP_RESET_CODE_CONNECTION_REFUSED] = ECONNREFUSED,
[DCCP_RESET_CODE_TOO_BUSY] = EUSERS,
[DCCP_RESET_CODE_AGGRESSION_PENALTY] = EDQUOT,
[DCCP_RESET_CODE_PACKET_ERROR] = ENOMSG,
[DCCP_RESET_CODE_BAD_INIT_COOKIE] = EBADR,
[DCCP_RESET_CODE_BAD_SERVICE_CODE] = EBADRQC,
[DCCP_RESET_CODE_OPTION_ERROR] = EILSEQ,
[DCCP_RESET_CODE_MANDATORY_ERROR] = EOPNOTSUPP,
};
return code >= DCCP_MAX_RESET_CODES ? 0 : error_code[code];
}
static void dccp_rcv_reset(struct sock *sk, struct sk_buff *skb)
{
u16 err = dccp_reset_code_convert(dccp_hdr_reset(skb)->dccph_reset_code);
sk->sk_err = err;
/* Queue the equivalent of TCP fin so that dccp_recvmsg exits the loop */
dccp_fin(sk, skb);
if (err && !sock_flag(sk, SOCK_DEAD))
sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR);
dccp_time_wait(sk, DCCP_TIME_WAIT, 0);
}
static void dccp_handle_ackvec_processing(struct sock *sk, struct sk_buff *skb)
{
struct dccp_ackvec *av = dccp_sk(sk)->dccps_hc_rx_ackvec;
if (av == NULL)
return;
if (DCCP_SKB_CB(skb)->dccpd_ack_seq != DCCP_PKT_WITHOUT_ACK_SEQ)
dccp_ackvec_clear_state(av, DCCP_SKB_CB(skb)->dccpd_ack_seq);
dccp_ackvec_input(av, skb);
}
static void dccp_deliver_input_to_ccids(struct sock *sk, struct sk_buff *skb)
{
const struct dccp_sock *dp = dccp_sk(sk);
/* Don't deliver to RX CCID when node has shut down read end. */
if (!(sk->sk_shutdown & RCV_SHUTDOWN))
ccid_hc_rx_packet_recv(dp->dccps_hc_rx_ccid, sk, skb);
/*
* Until the TX queue has been drained, we can not honour SHUT_WR, since
* we need received feedback as input to adjust congestion control.
*/
if (sk->sk_write_queue.qlen > 0 || !(sk->sk_shutdown & SEND_SHUTDOWN))
ccid_hc_tx_packet_recv(dp->dccps_hc_tx_ccid, sk, skb);
}
static int dccp_check_seqno(struct sock *sk, struct sk_buff *skb)
{
const struct dccp_hdr *dh = dccp_hdr(skb);
struct dccp_sock *dp = dccp_sk(sk);
u64 lswl, lawl, seqno = DCCP_SKB_CB(skb)->dccpd_seq,
ackno = DCCP_SKB_CB(skb)->dccpd_ack_seq;
/*
* Step 5: Prepare sequence numbers for Sync
* If P.type == Sync or P.type == SyncAck,
* If S.AWL <= P.ackno <= S.AWH and P.seqno >= S.SWL,
* / * P is valid, so update sequence number variables
* accordingly. After this update, P will pass the tests
* in Step 6. A SyncAck is generated if necessary in
* Step 15 * /
* Update S.GSR, S.SWL, S.SWH
* Otherwise,
* Drop packet and return
*/
if (dh->dccph_type == DCCP_PKT_SYNC ||
dh->dccph_type == DCCP_PKT_SYNCACK) {
if (between48(ackno, dp->dccps_awl, dp->dccps_awh) &&
dccp_delta_seqno(dp->dccps_swl, seqno) >= 0)
dccp_update_gsr(sk, seqno);
else
return -1;
}
/*
* Step 6: Check sequence numbers
* Let LSWL = S.SWL and LAWL = S.AWL
* If P.type == CloseReq or P.type == Close or P.type == Reset,
* LSWL := S.GSR + 1, LAWL := S.GAR
* If LSWL <= P.seqno <= S.SWH
* and (P.ackno does not exist or LAWL <= P.ackno <= S.AWH),
* Update S.GSR, S.SWL, S.SWH
* If P.type != Sync,
* Update S.GAR
*/
lswl = dp->dccps_swl;
lawl = dp->dccps_awl;
if (dh->dccph_type == DCCP_PKT_CLOSEREQ ||
dh->dccph_type == DCCP_PKT_CLOSE ||
dh->dccph_type == DCCP_PKT_RESET) {
lswl = ADD48(dp->dccps_gsr, 1);
lawl = dp->dccps_gar;
}
if (between48(seqno, lswl, dp->dccps_swh) &&
(ackno == DCCP_PKT_WITHOUT_ACK_SEQ ||
between48(ackno, lawl, dp->dccps_awh))) {
dccp_update_gsr(sk, seqno);
if (dh->dccph_type != DCCP_PKT_SYNC &&
ackno != DCCP_PKT_WITHOUT_ACK_SEQ &&
after48(ackno, dp->dccps_gar))
dp->dccps_gar = ackno;
} else {
unsigned long now = jiffies;
/*
* Step 6: Check sequence numbers
* Otherwise,
* If P.type == Reset,
* Send Sync packet acknowledging S.GSR
* Otherwise,
* Send Sync packet acknowledging P.seqno
* Drop packet and return
*
* These Syncs are rate-limited as per RFC 4340, 7.5.4:
* at most 1 / (dccp_sync_rate_limit * HZ) Syncs per second.
*/
if (time_before(now, (dp->dccps_rate_last +
sysctl_dccp_sync_ratelimit)))
return -1;
DCCP_WARN("Step 6 failed for %s packet, "
"(LSWL(%llu) <= P.seqno(%llu) <= S.SWH(%llu)) and "
"(P.ackno %s or LAWL(%llu) <= P.ackno(%llu) <= S.AWH(%llu), "
"sending SYNC...\n", dccp_packet_name(dh->dccph_type),
(unsigned long long) lswl, (unsigned long long) seqno,
(unsigned long long) dp->dccps_swh,
(ackno == DCCP_PKT_WITHOUT_ACK_SEQ) ? "doesn't exist"
: "exists",
(unsigned long long) lawl, (unsigned long long) ackno,
(unsigned long long) dp->dccps_awh);
dp->dccps_rate_last = now;
if (dh->dccph_type == DCCP_PKT_RESET)
seqno = dp->dccps_gsr;
dccp_send_sync(sk, seqno, DCCP_PKT_SYNC);
return -1;
}
return 0;
}
static int __dccp_rcv_established(struct sock *sk, struct sk_buff *skb,
const struct dccp_hdr *dh, const unsigned len)
{
struct dccp_sock *dp = dccp_sk(sk);
switch (dccp_hdr(skb)->dccph_type) {
case DCCP_PKT_DATAACK:
case DCCP_PKT_DATA:
/*
* FIXME: schedule DATA_DROPPED (RFC 4340, 11.7.2) if and when
* - sk_shutdown == RCV_SHUTDOWN, use Code 1, "Not Listening"
* - sk_receive_queue is full, use Code 2, "Receive Buffer"
*/
dccp_enqueue_skb(sk, skb);
return 0;
case DCCP_PKT_ACK:
goto discard;
case DCCP_PKT_RESET:
/*
* Step 9: Process Reset
* If P.type == Reset,
* Tear down connection
* S.state := TIMEWAIT
* Set TIMEWAIT timer
* Drop packet and return
*/
dccp_rcv_reset(sk, skb);
return 0;
case DCCP_PKT_CLOSEREQ:
if (dccp_rcv_closereq(sk, skb))
return 0;
goto discard;
case DCCP_PKT_CLOSE:
if (dccp_rcv_close(sk, skb))
return 0;
goto discard;
case DCCP_PKT_REQUEST:
/* Step 7
* or (S.is_server and P.type == Response)
* or (S.is_client and P.type == Request)
* or (S.state >= OPEN and P.type == Request
* and P.seqno >= S.OSR)
* or (S.state >= OPEN and P.type == Response
* and P.seqno >= S.OSR)
* or (S.state == RESPOND and P.type == Data),
* Send Sync packet acknowledging P.seqno
* Drop packet and return
*/
if (dp->dccps_role != DCCP_ROLE_LISTEN)
goto send_sync;
goto check_seq;
case DCCP_PKT_RESPONSE:
if (dp->dccps_role != DCCP_ROLE_CLIENT)
goto send_sync;
check_seq:
if (dccp_delta_seqno(dp->dccps_osr,
DCCP_SKB_CB(skb)->dccpd_seq) >= 0) {
send_sync:
dccp_send_sync(sk, DCCP_SKB_CB(skb)->dccpd_seq,
DCCP_PKT_SYNC);
}
break;
case DCCP_PKT_SYNC:
dccp_send_sync(sk, DCCP_SKB_CB(skb)->dccpd_seq,
DCCP_PKT_SYNCACK);
/*
* From RFC 4340, sec. 5.7
*
* As with DCCP-Ack packets, DCCP-Sync and DCCP-SyncAck packets
* MAY have non-zero-length application data areas, whose
* contents receivers MUST ignore.
*/
goto discard;
}
DCCP_INC_STATS_BH(DCCP_MIB_INERRS);
discard:
__kfree_skb(skb);
return 0;
}
int dccp_rcv_established(struct sock *sk, struct sk_buff *skb,
const struct dccp_hdr *dh, const unsigned len)
{
if (dccp_check_seqno(sk, skb))
goto discard;
if (dccp_parse_options(sk, NULL, skb))
return 1;
dccp_handle_ackvec_processing(sk, skb);
dccp_deliver_input_to_ccids(sk, skb);
return __dccp_rcv_established(sk, skb, dh, len);
discard:
__kfree_skb(skb);
return 0;
}
EXPORT_SYMBOL_GPL(dccp_rcv_established);
static int dccp_rcv_request_sent_state_process(struct sock *sk,
struct sk_buff *skb,
const struct dccp_hdr *dh,
const unsigned len)
{
/*
* Step 4: Prepare sequence numbers in REQUEST
* If S.state == REQUEST,
* If (P.type == Response or P.type == Reset)
* and S.AWL <= P.ackno <= S.AWH,
* / * Set sequence number variables corresponding to the
* other endpoint, so P will pass the tests in Step 6 * /
* Set S.GSR, S.ISR, S.SWL, S.SWH
* / * Response processing continues in Step 10; Reset
* processing continues in Step 9 * /
*/
if (dh->dccph_type == DCCP_PKT_RESPONSE) {
const struct inet_connection_sock *icsk = inet_csk(sk);
struct dccp_sock *dp = dccp_sk(sk);
long tstamp = dccp_timestamp();
if (!between48(DCCP_SKB_CB(skb)->dccpd_ack_seq,
dp->dccps_awl, dp->dccps_awh)) {
dccp_pr_debug("invalid ackno: S.AWL=%llu, "
"P.ackno=%llu, S.AWH=%llu\n",
(unsigned long long)dp->dccps_awl,
(unsigned long long)DCCP_SKB_CB(skb)->dccpd_ack_seq,
(unsigned long long)dp->dccps_awh);
goto out_invalid_packet;
}
/*
* If option processing (Step 8) failed, return 1 here so that
* dccp_v4_do_rcv() sends a Reset. The Reset code depends on
* the option type and is set in dccp_parse_options().
*/
if (dccp_parse_options(sk, NULL, skb))
return 1;
/* Obtain usec RTT sample from SYN exchange (used by TFRC). */
if (likely(dp->dccps_options_received.dccpor_timestamp_echo))
dp->dccps_syn_rtt = dccp_sample_rtt(sk, 10 * (tstamp -
dp->dccps_options_received.dccpor_timestamp_echo));
/* Stop the REQUEST timer */
inet_csk_clear_xmit_timer(sk, ICSK_TIME_RETRANS);
WARN_ON(sk->sk_send_head == NULL);
kfree_skb(sk->sk_send_head);
sk->sk_send_head = NULL;
/*
* Set ISR, GSR from packet. ISS was set in dccp_v{4,6}_connect
* and GSS in dccp_transmit_skb(). Setting AWL/AWH and SWL/SWH
* is done as part of activating the feature values below, since
* these settings depend on the local/remote Sequence Window
* features, which were undefined or not confirmed until now.
*/
dp->dccps_gsr = dp->dccps_isr = DCCP_SKB_CB(skb)->dccpd_seq;
dccp_sync_mss(sk, icsk->icsk_pmtu_cookie);
/*
* Step 10: Process REQUEST state (second part)
* If S.state == REQUEST,
* / * If we get here, P is a valid Response from the
* server (see Step 4), and we should move to
* PARTOPEN state. PARTOPEN means send an Ack,
* don't send Data packets, retransmit Acks
* periodically, and always include any Init Cookie
* from the Response * /
* S.state := PARTOPEN
* Set PARTOPEN timer
* Continue with S.state == PARTOPEN
* / * Step 12 will send the Ack completing the
* three-way handshake * /
*/
dccp_set_state(sk, DCCP_PARTOPEN);
/*
* If feature negotiation was successful, activate features now;
* an activation failure means that this host could not activate
* one ore more features (e.g. insufficient memory), which would
* leave at least one feature in an undefined state.
*/
if (dccp_feat_activate_values(sk, &dp->dccps_featneg))
goto unable_to_proceed;
/* Make sure socket is routed, for correct metrics. */
icsk->icsk_af_ops->rebuild_header(sk);
if (!sock_flag(sk, SOCK_DEAD)) {
sk->sk_state_change(sk);
sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
}
if (sk->sk_write_pending || icsk->icsk_ack.pingpong ||
icsk->icsk_accept_queue.rskq_defer_accept) {
/* Save one ACK. Data will be ready after
* several ticks, if write_pending is set.
*
* It may be deleted, but with this feature tcpdumps
* look so _wonderfully_ clever, that I was not able
* to stand against the temptation 8) --ANK
*/
/*
* OK, in DCCP we can as well do a similar trick, its
* even in the draft, but there is no need for us to
* schedule an ack here, as dccp_sendmsg does this for
* us, also stated in the draft. -acme
*/
__kfree_skb(skb);
return 0;
}
dccp_send_ack(sk);
return -1;
}
out_invalid_packet:
/* dccp_v4_do_rcv will send a reset */
DCCP_SKB_CB(skb)->dccpd_reset_code = DCCP_RESET_CODE_PACKET_ERROR;
return 1;
unable_to_proceed:
DCCP_SKB_CB(skb)->dccpd_reset_code = DCCP_RESET_CODE_ABORTED;
/*
* We mark this socket as no longer usable, so that the loop in
* dccp_sendmsg() terminates and the application gets notified.
*/
dccp_set_state(sk, DCCP_CLOSED);
sk->sk_err = ECOMM;
return 1;
}
static int dccp_rcv_respond_partopen_state_process(struct sock *sk,
struct sk_buff *skb,
const struct dccp_hdr *dh,
const unsigned len)
{
struct dccp_sock *dp = dccp_sk(sk);
u32 sample = dp->dccps_options_received.dccpor_timestamp_echo;
int queued = 0;
switch (dh->dccph_type) {
case DCCP_PKT_RESET:
inet_csk_clear_xmit_timer(sk, ICSK_TIME_DACK);
break;
case DCCP_PKT_DATA:
if (sk->sk_state == DCCP_RESPOND)
break;
case DCCP_PKT_DATAACK:
case DCCP_PKT_ACK:
/*
* FIXME: we should be reseting the PARTOPEN (DELACK) timer
* here but only if we haven't used the DELACK timer for
* something else, like sending a delayed ack for a TIMESTAMP
* echo, etc, for now were not clearing it, sending an extra
* ACK when there is nothing else to do in DELACK is not a big
* deal after all.
*/
/* Stop the PARTOPEN timer */
if (sk->sk_state == DCCP_PARTOPEN)
inet_csk_clear_xmit_timer(sk, ICSK_TIME_DACK);
/* Obtain usec RTT sample from SYN exchange (used by TFRC). */
if (likely(sample)) {
long delta = dccp_timestamp() - sample;
dp->dccps_syn_rtt = dccp_sample_rtt(sk, 10 * delta);
}
dp->dccps_osr = DCCP_SKB_CB(skb)->dccpd_seq;
dccp_set_state(sk, DCCP_OPEN);
if (dh->dccph_type == DCCP_PKT_DATAACK ||
dh->dccph_type == DCCP_PKT_DATA) {
__dccp_rcv_established(sk, skb, dh, len);
queued = 1; /* packet was queued
(by __dccp_rcv_established) */
}
break;
}
return queued;
}
int dccp_rcv_state_process(struct sock *sk, struct sk_buff *skb,
struct dccp_hdr *dh, unsigned len)
{
struct dccp_sock *dp = dccp_sk(sk);
struct dccp_skb_cb *dcb = DCCP_SKB_CB(skb);
const int old_state = sk->sk_state;
int queued = 0;
/*
* Step 3: Process LISTEN state
*
* If S.state == LISTEN,
* If P.type == Request or P contains a valid Init Cookie option,
* (* Must scan the packet's options to check for Init
* Cookies. Only Init Cookies are processed here,
* however; other options are processed in Step 8. This
* scan need only be performed if the endpoint uses Init
* Cookies *)
* (* Generate a new socket and switch to that socket *)
* Set S := new socket for this port pair
* S.state = RESPOND
* Choose S.ISS (initial seqno) or set from Init Cookies
* Initialize S.GAR := S.ISS
* Set S.ISR, S.GSR, S.SWL, S.SWH from packet or Init
* Cookies Continue with S.state == RESPOND
* (* A Response packet will be generated in Step 11 *)
* Otherwise,
* Generate Reset(No Connection) unless P.type == Reset
* Drop packet and return
*/
if (sk->sk_state == DCCP_LISTEN) {
if (dh->dccph_type == DCCP_PKT_REQUEST) {
if (inet_csk(sk)->icsk_af_ops->conn_request(sk,
skb) < 0)
return 1;
goto discard;
}
if (dh->dccph_type == DCCP_PKT_RESET)
goto discard;
/* Caller (dccp_v4_do_rcv) will send Reset */
dcb->dccpd_reset_code = DCCP_RESET_CODE_NO_CONNECTION;
return 1;
} else if (sk->sk_state == DCCP_CLOSED) {
dcb->dccpd_reset_code = DCCP_RESET_CODE_NO_CONNECTION;
return 1;
}
/* Step 6: Check sequence numbers (omitted in LISTEN/REQUEST state) */
if (sk->sk_state != DCCP_REQUESTING && dccp_check_seqno(sk, skb))
goto discard;
/*
* Step 7: Check for unexpected packet types
* If (S.is_server and P.type == Response)
* or (S.is_client and P.type == Request)
* or (S.state == RESPOND and P.type == Data),
* Send Sync packet acknowledging P.seqno
* Drop packet and return
*/
if ((dp->dccps_role != DCCP_ROLE_CLIENT &&
dh->dccph_type == DCCP_PKT_RESPONSE) ||
(dp->dccps_role == DCCP_ROLE_CLIENT &&
dh->dccph_type == DCCP_PKT_REQUEST) ||
(sk->sk_state == DCCP_RESPOND && dh->dccph_type == DCCP_PKT_DATA)) {
dccp_send_sync(sk, dcb->dccpd_seq, DCCP_PKT_SYNC);
goto discard;
}
/* Step 8: Process options */
if (dccp_parse_options(sk, NULL, skb))
return 1;
/*
* Step 9: Process Reset
* If P.type == Reset,
* Tear down connection
* S.state := TIMEWAIT
* Set TIMEWAIT timer
* Drop packet and return
*/
if (dh->dccph_type == DCCP_PKT_RESET) {
dccp_rcv_reset(sk, skb);
return 0;
} else if (dh->dccph_type == DCCP_PKT_CLOSEREQ) { /* Step 13 */
if (dccp_rcv_closereq(sk, skb))
return 0;
goto discard;
} else if (dh->dccph_type == DCCP_PKT_CLOSE) { /* Step 14 */
if (dccp_rcv_close(sk, skb))
return 0;
goto discard;
}
switch (sk->sk_state) {
case DCCP_REQUESTING:
queued = dccp_rcv_request_sent_state_process(sk, skb, dh, len);
if (queued >= 0)
return queued;
__kfree_skb(skb);
return 0;
case DCCP_PARTOPEN:
/* Step 8: if using Ack Vectors, mark packet acknowledgeable */
dccp_handle_ackvec_processing(sk, skb);
dccp_deliver_input_to_ccids(sk, skb);
/* fall through */
case DCCP_RESPOND:
queued = dccp_rcv_respond_partopen_state_process(sk, skb,
dh, len);
break;
}
if (dh->dccph_type == DCCP_PKT_ACK ||
dh->dccph_type == DCCP_PKT_DATAACK) {
switch (old_state) {
case DCCP_PARTOPEN:
sk->sk_state_change(sk);
sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
break;
}
} else if (unlikely(dh->dccph_type == DCCP_PKT_SYNC)) {
dccp_send_sync(sk, dcb->dccpd_seq, DCCP_PKT_SYNCACK);
goto discard;
}
if (!queued) {
discard:
__kfree_skb(skb);
}
return 0;
}
EXPORT_SYMBOL_GPL(dccp_rcv_state_process);
/**
* dccp_sample_rtt - Validate and finalise computation of RTT sample
* @delta: number of microseconds between packet and acknowledgment
* The routine is kept generic to work in different contexts. It should be
* called immediately when the ACK used for the RTT sample arrives.
*/
u32 dccp_sample_rtt(struct sock *sk, long delta)
{
/* dccpor_elapsed_time is either zeroed out or set and > 0 */
delta -= dccp_sk(sk)->dccps_options_received.dccpor_elapsed_time * 10;
if (unlikely(delta <= 0)) {
DCCP_WARN("unusable RTT sample %ld, using min\n", delta);
return DCCP_SANE_RTT_MIN;
}
if (unlikely(delta > DCCP_SANE_RTT_MAX)) {
DCCP_WARN("RTT sample %ld too large, using max\n", delta);
return DCCP_SANE_RTT_MAX;
}
return delta;
}
| gpl-2.0 |
DirtyDev/DirtyKernel-ANDROID | net/netfilter/nf_conntrack_irc.c | 7629 | 8099 | /* IRC extension for IP connection tracking, Version 1.21
* (C) 2000-2002 by Harald Welte <laforge@gnumonks.org>
* based on RR's ip_conntrack_ftp.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/skbuff.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/netfilter.h>
#include <linux/slab.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_expect.h>
#include <net/netfilter/nf_conntrack_helper.h>
#include <linux/netfilter/nf_conntrack_irc.h>
#define MAX_PORTS 8
static unsigned short ports[MAX_PORTS];
static unsigned int ports_c;
static unsigned int max_dcc_channels = 8;
static unsigned int dcc_timeout __read_mostly = 300;
/* This is slow, but it's simple. --RR */
static char *irc_buffer;
static DEFINE_SPINLOCK(irc_buffer_lock);
unsigned int (*nf_nat_irc_hook)(struct sk_buff *skb,
enum ip_conntrack_info ctinfo,
unsigned int matchoff,
unsigned int matchlen,
struct nf_conntrack_expect *exp) __read_mostly;
EXPORT_SYMBOL_GPL(nf_nat_irc_hook);
MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
MODULE_DESCRIPTION("IRC (DCC) connection tracking helper");
MODULE_LICENSE("GPL");
MODULE_ALIAS("ip_conntrack_irc");
MODULE_ALIAS_NFCT_HELPER("irc");
module_param_array(ports, ushort, &ports_c, 0400);
MODULE_PARM_DESC(ports, "port numbers of IRC servers");
module_param(max_dcc_channels, uint, 0400);
MODULE_PARM_DESC(max_dcc_channels, "max number of expected DCC channels per "
"IRC session");
module_param(dcc_timeout, uint, 0400);
MODULE_PARM_DESC(dcc_timeout, "timeout on for unestablished DCC channels");
static const char *const dccprotos[] = {
"SEND ", "CHAT ", "MOVE ", "TSEND ", "SCHAT "
};
#define MINMATCHLEN 5
/* tries to get the ip_addr and port out of a dcc command
* return value: -1 on failure, 0 on success
* data pointer to first byte of DCC command data
* data_end pointer to last byte of dcc command data
* ip returns parsed ip of dcc command
* port returns parsed port of dcc command
* ad_beg_p returns pointer to first byte of addr data
* ad_end_p returns pointer to last byte of addr data
*/
static int parse_dcc(char *data, const char *data_end, __be32 *ip,
u_int16_t *port, char **ad_beg_p, char **ad_end_p)
{
char *tmp;
/* at least 12: "AAAAAAAA P\1\n" */
while (*data++ != ' ')
if (data > data_end - 12)
return -1;
/* Make sure we have a newline character within the packet boundaries
* because simple_strtoul parses until the first invalid character. */
for (tmp = data; tmp <= data_end; tmp++)
if (*tmp == '\n')
break;
if (tmp > data_end || *tmp != '\n')
return -1;
*ad_beg_p = data;
*ip = cpu_to_be32(simple_strtoul(data, &data, 10));
/* skip blanks between ip and port */
while (*data == ' ') {
if (data >= data_end)
return -1;
data++;
}
*port = simple_strtoul(data, &data, 10);
*ad_end_p = data;
return 0;
}
static int help(struct sk_buff *skb, unsigned int protoff,
struct nf_conn *ct, enum ip_conntrack_info ctinfo)
{
unsigned int dataoff;
const struct iphdr *iph;
const struct tcphdr *th;
struct tcphdr _tcph;
const char *data_limit;
char *data, *ib_ptr;
int dir = CTINFO2DIR(ctinfo);
struct nf_conntrack_expect *exp;
struct nf_conntrack_tuple *tuple;
__be32 dcc_ip;
u_int16_t dcc_port;
__be16 port;
int i, ret = NF_ACCEPT;
char *addr_beg_p, *addr_end_p;
typeof(nf_nat_irc_hook) nf_nat_irc;
/* If packet is coming from IRC server */
if (dir == IP_CT_DIR_REPLY)
return NF_ACCEPT;
/* Until there's been traffic both ways, don't look in packets. */
if (ctinfo != IP_CT_ESTABLISHED && ctinfo != IP_CT_ESTABLISHED_REPLY)
return NF_ACCEPT;
/* Not a full tcp header? */
th = skb_header_pointer(skb, protoff, sizeof(_tcph), &_tcph);
if (th == NULL)
return NF_ACCEPT;
/* No data? */
dataoff = protoff + th->doff*4;
if (dataoff >= skb->len)
return NF_ACCEPT;
spin_lock_bh(&irc_buffer_lock);
ib_ptr = skb_header_pointer(skb, dataoff, skb->len - dataoff,
irc_buffer);
BUG_ON(ib_ptr == NULL);
data = ib_ptr;
data_limit = ib_ptr + skb->len - dataoff;
/* strlen("\1DCC SENT t AAAAAAAA P\1\n")=24
* 5+MINMATCHLEN+strlen("t AAAAAAAA P\1\n")=14 */
while (data < data_limit - (19 + MINMATCHLEN)) {
if (memcmp(data, "\1DCC ", 5)) {
data++;
continue;
}
data += 5;
/* we have at least (19+MINMATCHLEN)-5 bytes valid data left */
iph = ip_hdr(skb);
pr_debug("DCC found in master %pI4:%u %pI4:%u\n",
&iph->saddr, ntohs(th->source),
&iph->daddr, ntohs(th->dest));
for (i = 0; i < ARRAY_SIZE(dccprotos); i++) {
if (memcmp(data, dccprotos[i], strlen(dccprotos[i]))) {
/* no match */
continue;
}
data += strlen(dccprotos[i]);
pr_debug("DCC %s detected\n", dccprotos[i]);
/* we have at least
* (19+MINMATCHLEN)-5-dccprotos[i].matchlen bytes valid
* data left (== 14/13 bytes) */
if (parse_dcc(data, data_limit, &dcc_ip,
&dcc_port, &addr_beg_p, &addr_end_p)) {
pr_debug("unable to parse dcc command\n");
continue;
}
pr_debug("DCC bound ip/port: %pI4:%u\n",
&dcc_ip, dcc_port);
/* dcc_ip can be the internal OR external (NAT'ed) IP */
tuple = &ct->tuplehash[dir].tuple;
if (tuple->src.u3.ip != dcc_ip &&
tuple->dst.u3.ip != dcc_ip) {
if (net_ratelimit())
printk(KERN_WARNING
"Forged DCC command from %pI4: %pI4:%u\n",
&tuple->src.u3.ip,
&dcc_ip, dcc_port);
continue;
}
exp = nf_ct_expect_alloc(ct);
if (exp == NULL) {
ret = NF_DROP;
goto out;
}
tuple = &ct->tuplehash[!dir].tuple;
port = htons(dcc_port);
nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT,
tuple->src.l3num,
NULL, &tuple->dst.u3,
IPPROTO_TCP, NULL, &port);
nf_nat_irc = rcu_dereference(nf_nat_irc_hook);
if (nf_nat_irc && ct->status & IPS_NAT_MASK)
ret = nf_nat_irc(skb, ctinfo,
addr_beg_p - ib_ptr,
addr_end_p - addr_beg_p,
exp);
else if (nf_ct_expect_related(exp) != 0)
ret = NF_DROP;
nf_ct_expect_put(exp);
goto out;
}
}
out:
spin_unlock_bh(&irc_buffer_lock);
return ret;
}
static struct nf_conntrack_helper irc[MAX_PORTS] __read_mostly;
static char irc_names[MAX_PORTS][sizeof("irc-65535")] __read_mostly;
static struct nf_conntrack_expect_policy irc_exp_policy;
static void nf_conntrack_irc_fini(void);
static int __init nf_conntrack_irc_init(void)
{
int i, ret;
char *tmpname;
if (max_dcc_channels < 1) {
printk(KERN_ERR "nf_ct_irc: max_dcc_channels must not be zero\n");
return -EINVAL;
}
irc_exp_policy.max_expected = max_dcc_channels;
irc_exp_policy.timeout = dcc_timeout;
irc_buffer = kmalloc(65536, GFP_KERNEL);
if (!irc_buffer)
return -ENOMEM;
/* If no port given, default to standard irc port */
if (ports_c == 0)
ports[ports_c++] = IRC_PORT;
for (i = 0; i < ports_c; i++) {
irc[i].tuple.src.l3num = AF_INET;
irc[i].tuple.src.u.tcp.port = htons(ports[i]);
irc[i].tuple.dst.protonum = IPPROTO_TCP;
irc[i].expect_policy = &irc_exp_policy;
irc[i].me = THIS_MODULE;
irc[i].help = help;
tmpname = &irc_names[i][0];
if (ports[i] == IRC_PORT)
sprintf(tmpname, "irc");
else
sprintf(tmpname, "irc-%u", i);
irc[i].name = tmpname;
ret = nf_conntrack_helper_register(&irc[i]);
if (ret) {
printk(KERN_ERR "nf_ct_irc: failed to register helper "
"for pf: %u port: %u\n",
irc[i].tuple.src.l3num, ports[i]);
nf_conntrack_irc_fini();
return ret;
}
}
return 0;
}
/* This function is intentionally _NOT_ defined as __exit, because
* it is needed by the init function */
static void nf_conntrack_irc_fini(void)
{
int i;
for (i = 0; i < ports_c; i++)
nf_conntrack_helper_unregister(&irc[i]);
kfree(irc_buffer);
}
module_init(nf_conntrack_irc_init);
module_exit(nf_conntrack_irc_fini);
| gpl-2.0 |
learningendless/linux-xlnx | drivers/staging/comedi/drivers/amplc_pci263.c | 206 | 3221 | /*
comedi/drivers/amplc_pci263.c
Driver for Amplicon PCI263 relay board.
Copyright (C) 2002 MEV Ltd. <http://www.mev.co.uk/>
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 2000 David A. Schleef <ds@schleef.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
/*
Driver: amplc_pci263
Description: Amplicon PCI263
Author: Ian Abbott <abbotti@mev.co.uk>
Devices: [Amplicon] PCI263 (amplc_pci263)
Updated: Fri, 12 Apr 2013 15:19:36 +0100
Status: works
Configuration options: not applicable, uses PCI auto config
The board appears as one subdevice, with 16 digital outputs, each
connected to a reed-relay. Relay contacts are closed when output is 1.
The state of the outputs can be read.
*/
#include <linux/module.h>
#include <linux/pci.h>
#include "../comedidev.h"
static int pci263_do_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
if (comedi_dio_update_state(s, data)) {
outb(s->state & 0xff, dev->iobase);
outb((s->state >> 8) & 0xff, dev->iobase + 1);
}
data[1] = s->state;
return insn->n;
}
static int pci263_auto_attach(struct comedi_device *dev,
unsigned long context_unused)
{
struct pci_dev *pci_dev = comedi_to_pci_dev(dev);
struct comedi_subdevice *s;
int ret;
ret = comedi_pci_enable(dev);
if (ret)
return ret;
dev->iobase = pci_resource_start(pci_dev, 2);
ret = comedi_alloc_subdevices(dev, 1);
if (ret)
return ret;
s = &dev->subdevices[0];
/* digital output subdevice */
s->type = COMEDI_SUBD_DO;
s->subdev_flags = SDF_WRITABLE;
s->n_chan = 16;
s->maxdata = 1;
s->range_table = &range_digital;
s->insn_bits = pci263_do_insn_bits;
/* read initial relay state */
s->state = inb(dev->iobase) | (inb(dev->iobase + 1) << 8);
return 0;
}
static struct comedi_driver amplc_pci263_driver = {
.driver_name = "amplc_pci263",
.module = THIS_MODULE,
.auto_attach = pci263_auto_attach,
.detach = comedi_pci_detach,
};
static const struct pci_device_id pci263_pci_table[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_AMPLICON, 0x000c) },
{0}
};
MODULE_DEVICE_TABLE(pci, pci263_pci_table);
static int amplc_pci263_pci_probe(struct pci_dev *dev,
const struct pci_device_id *id)
{
return comedi_pci_auto_config(dev, &lc_pci263_driver,
id->driver_data);
}
static struct pci_driver amplc_pci263_pci_driver = {
.name = "amplc_pci263",
.id_table = pci263_pci_table,
.probe = &lc_pci263_pci_probe,
.remove = comedi_pci_auto_unconfig,
};
module_comedi_pci_driver(amplc_pci263_driver, amplc_pci263_pci_driver);
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi driver for Amplicon PCI263 relay board");
MODULE_LICENSE("GPL");
| gpl-2.0 |
bauner/kernel_n7000_tw_jb | arch/arm/common/gic.c | 462 | 11182 | /*
* linux/arch/arm/common/gic.c
*
* Copyright (C) 2002 ARM Limited, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Interrupt architecture for the GIC:
*
* o There is one Interrupt Distributor, which receives interrupts
* from system devices and sends them to the Interrupt Controllers.
*
* o There is one CPU Interface per CPU, which sends interrupts sent
* by the Distributor, and interrupts generated locally, to the
* associated CPU. The base address of the CPU interface is usually
* aliased so that the same address points to different chips depending
* on the CPU it is accessed from.
*
* Note that IRQs 0-31 are special - they are local to each CPU.
* As such, the enable set/clear, pending set/clear and active bit
* registers are banked per-cpu for these sources.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/smp.h>
#include <linux/cpumask.h>
#include <linux/io.h>
#include <asm/irq.h>
#include <asm/mach/irq.h>
#include <asm/hardware/gic.h>
struct gic_chip_data {
unsigned int irq_offset;
void __percpu __iomem **dist_base;
void __percpu __iomem **cpu_base;
#ifdef CONFIG_CPU_PM
u32 saved_spi_enable[DIV_ROUND_UP(1020, 32)];
u32 saved_spi_conf[DIV_ROUND_UP(1020, 16)];
u32 saved_spi_target[DIV_ROUND_UP(1020, 4)];
u32 __percpu *saved_ppi_enable;
u32 __percpu *saved_ppi_conf;
#endif
unsigned int gic_irqs;
};
static DEFINE_SPINLOCK(irq_controller_lock);
/* Address of GIC 0 CPU interface */
void __iomem *gic_cpu_base_addr __read_mostly;
/*
* Supported arch specific GIC irq extension.
* Default make them NULL.
*/
struct irq_chip gic_arch_extn = {
.irq_eoi = NULL,
.irq_mask = NULL,
.irq_unmask = NULL,
.irq_retrigger = NULL,
.irq_set_type = NULL,
.irq_set_wake = NULL,
};
#ifndef MAX_GIC_NR
#define MAX_GIC_NR 1
#endif
static struct gic_chip_data gic_data[MAX_GIC_NR] __read_mostly;
static inline void __iomem *gic_data_dist_base(struct gic_chip_data *data)
{
return *__this_cpu_ptr(data->dist_base);
}
static inline void __iomem *gic_dist_base(struct irq_data *d)
{
struct gic_chip_data *gic_data = irq_data_get_irq_chip_data(d);
return gic_data_dist_base(gic_data);
}
static inline void __iomem *gic_data_cpu_base(struct gic_chip_data *data)
{
return *__this_cpu_ptr(data->cpu_base);
}
static inline void __iomem *gic_cpu_base(struct irq_data *d)
{
struct gic_chip_data *gic_data = irq_data_get_irq_chip_data(d);
return gic_data_cpu_base(gic_data);
}
static inline unsigned int gic_irq(struct irq_data *d)
{
struct gic_chip_data *gic_data = irq_data_get_irq_chip_data(d);
return d->irq - gic_data->irq_offset;
}
/*
* Routines to acknowledge, disable and enable interrupts
*/
static void gic_mask_irq(struct irq_data *d)
{
u32 mask = 1 << (d->irq % 32);
spin_lock(&irq_controller_lock);
writel_relaxed(mask, gic_dist_base(d) + GIC_DIST_ENABLE_CLEAR + (gic_irq(d) / 32) * 4);
if (gic_arch_extn.irq_mask)
gic_arch_extn.irq_mask(d);
spin_unlock(&irq_controller_lock);
}
static void gic_unmask_irq(struct irq_data *d)
{
u32 mask = 1 << (d->irq % 32);
spin_lock(&irq_controller_lock);
if (gic_arch_extn.irq_unmask)
gic_arch_extn.irq_unmask(d);
writel_relaxed(mask, gic_dist_base(d) + GIC_DIST_ENABLE_SET + (gic_irq(d) / 32) * 4);
spin_unlock(&irq_controller_lock);
}
static void gic_eoi_irq(struct irq_data *d)
{
if (gic_arch_extn.irq_eoi) {
spin_lock(&irq_controller_lock);
gic_arch_extn.irq_eoi(d);
spin_unlock(&irq_controller_lock);
}
writel_relaxed(gic_irq(d), gic_cpu_base(d) + GIC_CPU_EOI);
}
static int gic_set_type(struct irq_data *d, unsigned int type)
{
void __iomem *base = gic_dist_base(d);
unsigned int gicirq = gic_irq(d);
u32 enablemask = 1 << (gicirq % 32);
u32 enableoff = (gicirq / 32) * 4;
u32 confmask = 0x2 << ((gicirq % 16) * 2);
u32 confoff = (gicirq / 16) * 4;
bool enabled = false;
u32 val;
/* Interrupt configuration for SGIs can't be changed */
if (gicirq < 16)
return -EINVAL;
if (type != IRQ_TYPE_LEVEL_HIGH && type != IRQ_TYPE_EDGE_RISING)
return -EINVAL;
spin_lock(&irq_controller_lock);
if (gic_arch_extn.irq_set_type)
gic_arch_extn.irq_set_type(d, type);
val = readl_relaxed(base + GIC_DIST_CONFIG + confoff);
if (type == IRQ_TYPE_LEVEL_HIGH)
val &= ~confmask;
else if (type == IRQ_TYPE_EDGE_RISING)
val |= confmask;
/*
* As recommended by the spec, disable the interrupt before changing
* the configuration
*/
if (readl_relaxed(base + GIC_DIST_ENABLE_SET + enableoff) & enablemask) {
writel_relaxed(enablemask, base + GIC_DIST_ENABLE_CLEAR + enableoff);
enabled = true;
}
writel_relaxed(val, base + GIC_DIST_CONFIG + confoff);
if (enabled)
writel_relaxed(enablemask, base + GIC_DIST_ENABLE_SET + enableoff);
spin_unlock(&irq_controller_lock);
return 0;
}
static int gic_retrigger(struct irq_data *d)
{
if (gic_arch_extn.irq_retrigger)
return gic_arch_extn.irq_retrigger(d);
return -ENXIO;
}
#ifdef CONFIG_SMP
static int gic_set_affinity(struct irq_data *d, const struct cpumask *mask_val,
bool force)
{
void __iomem *reg = gic_dist_base(d) + GIC_DIST_TARGET + (gic_irq(d) & ~3);
unsigned int shift = (d->irq % 4) * 8;
unsigned int cpu = cpumask_first(mask_val);
u32 val, mask, bit;
if (cpu >= 8)
return -EINVAL;
mask = 0xff << shift;
bit = 1 << (cpu + shift);
spin_lock(&irq_controller_lock);
d->node = cpu;
val = readl_relaxed(reg) & ~mask;
writel_relaxed(val | bit, reg);
spin_unlock(&irq_controller_lock);
return 0;
}
#endif
#ifdef CONFIG_PM
static int gic_set_wake(struct irq_data *d, unsigned int on)
{
int ret = -ENXIO;
if (gic_arch_extn.irq_set_wake)
ret = gic_arch_extn.irq_set_wake(d, on);
return ret;
}
#else
#define gic_set_wake NULL
#endif
static void gic_handle_cascade_irq(unsigned int irq, struct irq_desc *desc)
{
struct gic_chip_data *chip_data = irq_get_handler_data(irq);
struct irq_chip *chip = irq_get_chip(irq);
unsigned int cascade_irq, gic_irq;
unsigned long status;
chained_irq_enter(chip, desc);
spin_lock(&irq_controller_lock);
status = readl_relaxed(gic_data_cpu_base(chip_data) + GIC_CPU_INTACK);
spin_unlock(&irq_controller_lock);
gic_irq = (status & 0x3ff);
if (gic_irq == 1023)
goto out;
cascade_irq = gic_irq + chip_data->irq_offset;
if (unlikely(gic_irq < 32 || gic_irq > 1020 || cascade_irq >= NR_IRQS))
do_bad_IRQ(cascade_irq, desc);
else
generic_handle_irq(cascade_irq);
out:
chained_irq_exit(chip, desc);
}
static struct irq_chip gic_chip = {
.name = "GIC",
.irq_mask = gic_mask_irq,
.irq_unmask = gic_unmask_irq,
.irq_eoi = gic_eoi_irq,
.irq_set_type = gic_set_type,
.irq_retrigger = gic_retrigger,
#ifdef CONFIG_SMP
.irq_set_affinity = gic_set_affinity,
#endif
.irq_set_wake = gic_set_wake,
};
void __init gic_cascade_irq(unsigned int gic_nr, unsigned int irq)
{
if (gic_nr >= MAX_GIC_NR)
BUG();
if (irq_set_handler_data(irq, &gic_data[gic_nr]) != 0)
BUG();
irq_set_chained_handler(irq, gic_handle_cascade_irq);
}
static void __init gic_dist_init(struct gic_chip_data *gic,
unsigned int irq_start)
{
unsigned int gic_irqs, irq_limit, i;
void __iomem *base = gic_data_dist_base(gic);
u32 cpumask = 1 << smp_processor_id();
cpumask |= cpumask << 8;
cpumask |= cpumask << 16;
writel_relaxed(0, base + GIC_DIST_CTRL);
/*
* Find out how many interrupts are supported.
* The GIC only supports up to 1020 interrupt sources.
*/
gic_irqs = readl_relaxed(base + GIC_DIST_CTR) & 0x1f;
gic_irqs = (gic_irqs + 1) * 32;
if (gic_irqs > 1020)
gic_irqs = 1020;
/*
* Set all global interrupts to be level triggered, active low.
*/
for (i = 32; i < gic_irqs; i += 16)
writel_relaxed(0, base + GIC_DIST_CONFIG + i * 4 / 16);
/*
* Set all global interrupts to this CPU only.
*/
for (i = 32; i < gic_irqs; i += 4)
writel_relaxed(cpumask, base + GIC_DIST_TARGET + i * 4 / 4);
/*
* Set priority on all global interrupts.
*/
for (i = 32; i < gic_irqs; i += 4)
writel_relaxed(0xa0a0a0a0, base + GIC_DIST_PRI + i * 4 / 4);
/*
* Disable all interrupts. Leave the PPI and SGIs alone
* as these enables are banked registers.
*/
for (i = 32; i < gic_irqs; i += 32)
writel_relaxed(0xffffffff, base + GIC_DIST_ENABLE_CLEAR + i * 4 / 32);
/*
* Limit number of interrupts registered to the platform maximum
*/
irq_limit = gic->irq_offset + gic_irqs;
if (WARN_ON(irq_limit > NR_IRQS))
irq_limit = NR_IRQS;
/*
* Setup the Linux IRQ subsystem.
*/
for (i = irq_start; i < irq_limit; i++) {
irq_set_chip_and_handler(i, &gic_chip, handle_fasteoi_irq);
irq_set_chip_data(i, gic);
set_irq_flags(i, IRQF_VALID | IRQF_PROBE);
}
writel_relaxed(1, base + GIC_DIST_CTRL);
}
static void __cpuinit gic_cpu_init(struct gic_chip_data *gic)
{
void __iomem *dist_base = gic_data_dist_base(gic);
void __iomem *base = gic_data_cpu_base(gic);
int i;
/*
* Deal with the banked PPI and SGI interrupts - disable all
* PPI interrupts, ensure all SGI interrupts are enabled.
*/
writel_relaxed(0xffff0000, dist_base + GIC_DIST_ENABLE_CLEAR);
writel_relaxed(0x0000ffff, dist_base + GIC_DIST_ENABLE_SET);
/*
* Set priority on PPI and SGI interrupts
*/
for (i = 0; i < 32; i += 4)
writel_relaxed(0xa0a0a0a0, dist_base + GIC_DIST_PRI + i * 4 / 4);
writel_relaxed(0xf0, base + GIC_CPU_PRIMASK);
writel_relaxed(1, base + GIC_CPU_CTRL);
}
void __init gic_init(unsigned int gic_nr, unsigned int irq_start,
void __iomem *dist_base, void __iomem *cpu_base)
{
struct gic_chip_data *gic;
int cpu;
BUG_ON(gic_nr >= MAX_GIC_NR);
gic = &gic_data[gic_nr];
gic->dist_base = alloc_percpu(void __iomem *);
gic->cpu_base = alloc_percpu(void __iomem *);
if (WARN_ON(!gic->dist_base || !gic->cpu_base)) {
free_percpu(gic->dist_base);
free_percpu(gic->cpu_base);
return;
}
for_each_possible_cpu(cpu) {
*per_cpu_ptr(gic->dist_base, cpu) = dist_base;
*per_cpu_ptr(gic->cpu_base, cpu) = cpu_base;
}
gic->irq_offset = (irq_start - 1) & ~31;
if (gic_nr == 0)
gic_cpu_base_addr = cpu_base;
gic_dist_init(gic, irq_start);
gic_cpu_init(gic);
}
void __cpuinit gic_secondary_init_base(unsigned int gic_nr,
void __iomem *dist_base,
void __iomem *cpu_base)
{
BUG_ON(gic_nr >= MAX_GIC_NR);
if (dist_base)
*__this_cpu_ptr(gic_data[gic_nr].dist_base) = dist_base;
if (cpu_base)
*__this_cpu_ptr(gic_data[gic_nr].cpu_base) = cpu_base;
gic_cpu_init(&gic_data[gic_nr]);
}
void __cpuinit gic_enable_ppi(unsigned int irq)
{
unsigned long flags;
local_irq_save(flags);
irq_set_status_flags(irq, IRQ_NOPROBE);
gic_unmask_irq(irq_get_irq_data(irq));
local_irq_restore(flags);
}
#ifdef CONFIG_SMP
void gic_raise_softirq(const struct cpumask *mask, unsigned int irq)
{
unsigned long map = *cpus_addr(*mask);
/*
* Ensure that stores to Normal memory are visible to the
* other CPUs before issuing the IPI.
*/
dsb();
/* this always happens on GIC0 */
writel_relaxed(map << 16 | irq, gic_data_dist_base(&gic_data[0]) + GIC_DIST_SOFTINT);
}
#endif
| gpl-2.0 |
justsoso8/linux-2.6.32.9 | drivers/scsi/aic94xx/aic94xx_tmf.c | 718 | 20129 | /*
* Aic94xx Task Management Functions
*
* Copyright (C) 2005 Adaptec, Inc. All rights reserved.
* Copyright (C) 2005 Luben Tuikov <luben_tuikov@adaptec.com>
*
* This file is licensed under GPLv2.
*
* This file is part of the aic94xx driver.
*
* The aic94xx driver is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; version 2 of the
* License.
*
* The aic94xx driver 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 the aic94xx driver; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <linux/spinlock.h>
#include "aic94xx.h"
#include "aic94xx_sas.h"
#include "aic94xx_hwi.h"
/* ---------- Internal enqueue ---------- */
static int asd_enqueue_internal(struct asd_ascb *ascb,
void (*tasklet_complete)(struct asd_ascb *,
struct done_list_struct *),
void (*timed_out)(unsigned long))
{
int res;
ascb->tasklet_complete = tasklet_complete;
ascb->uldd_timer = 1;
ascb->timer.data = (unsigned long) ascb;
ascb->timer.function = timed_out;
ascb->timer.expires = jiffies + AIC94XX_SCB_TIMEOUT;
add_timer(&ascb->timer);
res = asd_post_ascb_list(ascb->ha, ascb, 1);
if (unlikely(res))
del_timer(&ascb->timer);
return res;
}
/* ---------- CLEAR NEXUS ---------- */
struct tasklet_completion_status {
int dl_opcode;
int tmf_state;
u8 tag_valid:1;
__be16 tag;
};
#define DECLARE_TCS(tcs) \
struct tasklet_completion_status tcs = { \
.dl_opcode = 0, \
.tmf_state = 0, \
.tag_valid = 0, \
.tag = 0, \
}
static void asd_clear_nexus_tasklet_complete(struct asd_ascb *ascb,
struct done_list_struct *dl)
{
struct tasklet_completion_status *tcs = ascb->uldd_task;
ASD_DPRINTK("%s: here\n", __func__);
if (!del_timer(&ascb->timer)) {
ASD_DPRINTK("%s: couldn't delete timer\n", __func__);
return;
}
ASD_DPRINTK("%s: opcode: 0x%x\n", __func__, dl->opcode);
tcs->dl_opcode = dl->opcode;
complete(ascb->completion);
asd_ascb_free(ascb);
}
static void asd_clear_nexus_timedout(unsigned long data)
{
struct asd_ascb *ascb = (void *)data;
struct tasklet_completion_status *tcs = ascb->uldd_task;
ASD_DPRINTK("%s: here\n", __func__);
tcs->dl_opcode = TMF_RESP_FUNC_FAILED;
complete(ascb->completion);
}
#define CLEAR_NEXUS_PRE \
struct asd_ascb *ascb; \
struct scb *scb; \
int res; \
DECLARE_COMPLETION_ONSTACK(completion); \
DECLARE_TCS(tcs); \
\
ASD_DPRINTK("%s: PRE\n", __func__); \
res = 1; \
ascb = asd_ascb_alloc_list(asd_ha, &res, GFP_KERNEL); \
if (!ascb) \
return -ENOMEM; \
\
ascb->completion = &completion; \
ascb->uldd_task = &tcs; \
scb = ascb->scb; \
scb->header.opcode = CLEAR_NEXUS
#define CLEAR_NEXUS_POST \
ASD_DPRINTK("%s: POST\n", __func__); \
res = asd_enqueue_internal(ascb, asd_clear_nexus_tasklet_complete, \
asd_clear_nexus_timedout); \
if (res) \
goto out_err; \
ASD_DPRINTK("%s: clear nexus posted, waiting...\n", __func__); \
wait_for_completion(&completion); \
res = tcs.dl_opcode; \
if (res == TC_NO_ERROR) \
res = TMF_RESP_FUNC_COMPLETE; \
return res; \
out_err: \
asd_ascb_free(ascb); \
return res
int asd_clear_nexus_ha(struct sas_ha_struct *sas_ha)
{
struct asd_ha_struct *asd_ha = sas_ha->lldd_ha;
CLEAR_NEXUS_PRE;
scb->clear_nexus.nexus = NEXUS_ADAPTER;
CLEAR_NEXUS_POST;
}
int asd_clear_nexus_port(struct asd_sas_port *port)
{
struct asd_ha_struct *asd_ha = port->ha->lldd_ha;
CLEAR_NEXUS_PRE;
scb->clear_nexus.nexus = NEXUS_PORT;
scb->clear_nexus.conn_mask = port->phy_mask;
CLEAR_NEXUS_POST;
}
enum clear_nexus_phase {
NEXUS_PHASE_PRE,
NEXUS_PHASE_POST,
NEXUS_PHASE_RESUME,
};
static int asd_clear_nexus_I_T(struct domain_device *dev,
enum clear_nexus_phase phase)
{
struct asd_ha_struct *asd_ha = dev->port->ha->lldd_ha;
CLEAR_NEXUS_PRE;
scb->clear_nexus.nexus = NEXUS_I_T;
switch (phase) {
case NEXUS_PHASE_PRE:
scb->clear_nexus.flags = EXEC_Q | SUSPEND_TX;
break;
case NEXUS_PHASE_POST:
scb->clear_nexus.flags = SEND_Q | NOTINQ;
break;
case NEXUS_PHASE_RESUME:
scb->clear_nexus.flags = RESUME_TX;
}
scb->clear_nexus.conn_handle = cpu_to_le16((u16)(unsigned long)
dev->lldd_dev);
CLEAR_NEXUS_POST;
}
int asd_I_T_nexus_reset(struct domain_device *dev)
{
int res, tmp_res, i;
struct sas_phy *phy = sas_find_local_phy(dev);
/* Standard mandates link reset for ATA (type 0) and
* hard reset for SSP (type 1) */
int reset_type = (dev->dev_type == SATA_DEV ||
(dev->tproto & SAS_PROTOCOL_STP)) ? 0 : 1;
asd_clear_nexus_I_T(dev, NEXUS_PHASE_PRE);
/* send a hard reset */
ASD_DPRINTK("sending %s reset to %s\n",
reset_type ? "hard" : "soft", dev_name(&phy->dev));
res = sas_phy_reset(phy, reset_type);
if (res == TMF_RESP_FUNC_COMPLETE) {
/* wait for the maximum settle time */
msleep(500);
/* clear all outstanding commands (keep nexus suspended) */
asd_clear_nexus_I_T(dev, NEXUS_PHASE_POST);
}
for (i = 0 ; i < 3; i++) {
tmp_res = asd_clear_nexus_I_T(dev, NEXUS_PHASE_RESUME);
if (tmp_res == TC_RESUME)
return res;
msleep(500);
}
/* This is a bit of a problem: the sequencer is still suspended
* and is refusing to resume. Hope it will resume on a bigger hammer
* or the disk is lost */
dev_printk(KERN_ERR, &phy->dev,
"Failed to resume nexus after reset 0x%x\n", tmp_res);
return TMF_RESP_FUNC_FAILED;
}
static int asd_clear_nexus_I_T_L(struct domain_device *dev, u8 *lun)
{
struct asd_ha_struct *asd_ha = dev->port->ha->lldd_ha;
CLEAR_NEXUS_PRE;
scb->clear_nexus.nexus = NEXUS_I_T_L;
scb->clear_nexus.flags = SEND_Q | EXEC_Q | NOTINQ;
memcpy(scb->clear_nexus.ssp_task.lun, lun, 8);
scb->clear_nexus.conn_handle = cpu_to_le16((u16)(unsigned long)
dev->lldd_dev);
CLEAR_NEXUS_POST;
}
static int asd_clear_nexus_tag(struct sas_task *task)
{
struct asd_ha_struct *asd_ha = task->dev->port->ha->lldd_ha;
struct asd_ascb *tascb = task->lldd_task;
CLEAR_NEXUS_PRE;
scb->clear_nexus.nexus = NEXUS_TAG;
memcpy(scb->clear_nexus.ssp_task.lun, task->ssp_task.LUN, 8);
scb->clear_nexus.ssp_task.tag = tascb->tag;
if (task->dev->tproto)
scb->clear_nexus.conn_handle = cpu_to_le16((u16)(unsigned long)
task->dev->lldd_dev);
CLEAR_NEXUS_POST;
}
static int asd_clear_nexus_index(struct sas_task *task)
{
struct asd_ha_struct *asd_ha = task->dev->port->ha->lldd_ha;
struct asd_ascb *tascb = task->lldd_task;
CLEAR_NEXUS_PRE;
scb->clear_nexus.nexus = NEXUS_TRANS_CX;
if (task->dev->tproto)
scb->clear_nexus.conn_handle = cpu_to_le16((u16)(unsigned long)
task->dev->lldd_dev);
scb->clear_nexus.index = cpu_to_le16(tascb->tc_index);
CLEAR_NEXUS_POST;
}
/* ---------- TMFs ---------- */
static void asd_tmf_timedout(unsigned long data)
{
struct asd_ascb *ascb = (void *) data;
struct tasklet_completion_status *tcs = ascb->uldd_task;
ASD_DPRINTK("tmf timed out\n");
tcs->tmf_state = TMF_RESP_FUNC_FAILED;
complete(ascb->completion);
}
static int asd_get_tmf_resp_tasklet(struct asd_ascb *ascb,
struct done_list_struct *dl)
{
struct asd_ha_struct *asd_ha = ascb->ha;
unsigned long flags;
struct tc_resp_sb_struct {
__le16 index_escb;
u8 len_lsb;
u8 flags;
} __attribute__ ((packed)) *resp_sb = (void *) dl->status_block;
int edb_id = ((resp_sb->flags & 0x70) >> 4)-1;
struct asd_ascb *escb;
struct asd_dma_tok *edb;
struct ssp_frame_hdr *fh;
struct ssp_response_iu *ru;
int res = TMF_RESP_FUNC_FAILED;
ASD_DPRINTK("tmf resp tasklet\n");
spin_lock_irqsave(&asd_ha->seq.tc_index_lock, flags);
escb = asd_tc_index_find(&asd_ha->seq,
(int)le16_to_cpu(resp_sb->index_escb));
spin_unlock_irqrestore(&asd_ha->seq.tc_index_lock, flags);
if (!escb) {
ASD_DPRINTK("Uh-oh! No escb for this dl?!\n");
return res;
}
edb = asd_ha->seq.edb_arr[edb_id + escb->edb_index];
ascb->tag = *(__be16 *)(edb->vaddr+4);
fh = edb->vaddr + 16;
ru = edb->vaddr + 16 + sizeof(*fh);
res = ru->status;
if (ru->datapres == 1) /* Response data present */
res = ru->resp_data[3];
#if 0
ascb->tag = fh->tag;
#endif
ascb->tag_valid = 1;
asd_invalidate_edb(escb, edb_id);
return res;
}
static void asd_tmf_tasklet_complete(struct asd_ascb *ascb,
struct done_list_struct *dl)
{
struct tasklet_completion_status *tcs;
if (!del_timer(&ascb->timer))
return;
tcs = ascb->uldd_task;
ASD_DPRINTK("tmf tasklet complete\n");
tcs->dl_opcode = dl->opcode;
if (dl->opcode == TC_SSP_RESP) {
tcs->tmf_state = asd_get_tmf_resp_tasklet(ascb, dl);
tcs->tag_valid = ascb->tag_valid;
tcs->tag = ascb->tag;
}
complete(ascb->completion);
asd_ascb_free(ascb);
}
static int asd_clear_nexus(struct sas_task *task)
{
int res = TMF_RESP_FUNC_FAILED;
int leftover;
struct asd_ascb *tascb = task->lldd_task;
DECLARE_COMPLETION_ONSTACK(completion);
unsigned long flags;
tascb->completion = &completion;
ASD_DPRINTK("task not done, clearing nexus\n");
if (tascb->tag_valid)
res = asd_clear_nexus_tag(task);
else
res = asd_clear_nexus_index(task);
leftover = wait_for_completion_timeout(&completion,
AIC94XX_SCB_TIMEOUT);
tascb->completion = NULL;
ASD_DPRINTK("came back from clear nexus\n");
spin_lock_irqsave(&task->task_state_lock, flags);
if (leftover < 1)
res = TMF_RESP_FUNC_FAILED;
if (task->task_state_flags & SAS_TASK_STATE_DONE)
res = TMF_RESP_FUNC_COMPLETE;
spin_unlock_irqrestore(&task->task_state_lock, flags);
return res;
}
/**
* asd_abort_task -- ABORT TASK TMF
* @task: the task to be aborted
*
* Before calling ABORT TASK the task state flags should be ORed with
* SAS_TASK_STATE_ABORTED (unless SAS_TASK_STATE_DONE is set) under
* the task_state_lock IRQ spinlock, then ABORT TASK *must* be called.
*
* Implements the ABORT TASK TMF, I_T_L_Q nexus.
* Returns: SAS TMF responses (see sas_task.h),
* -ENOMEM,
* -SAS_QUEUE_FULL.
*
* When ABORT TASK returns, the caller of ABORT TASK checks first the
* task->task_state_flags, and then the return value of ABORT TASK.
*
* If the task has task state bit SAS_TASK_STATE_DONE set, then the
* task was completed successfully prior to it being aborted. The
* caller of ABORT TASK has responsibility to call task->task_done()
* xor free the task, depending on their framework. The return code
* is TMF_RESP_FUNC_FAILED in this case.
*
* Else the SAS_TASK_STATE_DONE bit is not set,
* If the return code is TMF_RESP_FUNC_COMPLETE, then
* the task was aborted successfully. The caller of
* ABORT TASK has responsibility to call task->task_done()
* to finish the task, xor free the task depending on their
* framework.
* else
* the ABORT TASK returned some kind of error. The task
* was _not_ cancelled. Nothing can be assumed.
* The caller of ABORT TASK may wish to retry.
*/
int asd_abort_task(struct sas_task *task)
{
struct asd_ascb *tascb = task->lldd_task;
struct asd_ha_struct *asd_ha = tascb->ha;
int res = 1;
unsigned long flags;
struct asd_ascb *ascb = NULL;
struct scb *scb;
int leftover;
DECLARE_TCS(tcs);
DECLARE_COMPLETION_ONSTACK(completion);
DECLARE_COMPLETION_ONSTACK(tascb_completion);
tascb->completion = &tascb_completion;
spin_lock_irqsave(&task->task_state_lock, flags);
if (task->task_state_flags & SAS_TASK_STATE_DONE) {
spin_unlock_irqrestore(&task->task_state_lock, flags);
res = TMF_RESP_FUNC_COMPLETE;
ASD_DPRINTK("%s: task 0x%p done\n", __func__, task);
goto out_done;
}
spin_unlock_irqrestore(&task->task_state_lock, flags);
ascb = asd_ascb_alloc_list(asd_ha, &res, GFP_KERNEL);
if (!ascb)
return -ENOMEM;
ascb->uldd_task = &tcs;
ascb->completion = &completion;
scb = ascb->scb;
scb->header.opcode = SCB_ABORT_TASK;
switch (task->task_proto) {
case SAS_PROTOCOL_SATA:
case SAS_PROTOCOL_STP:
scb->abort_task.proto_conn_rate = (1 << 5); /* STP */
break;
case SAS_PROTOCOL_SSP:
scb->abort_task.proto_conn_rate = (1 << 4); /* SSP */
scb->abort_task.proto_conn_rate |= task->dev->linkrate;
break;
case SAS_PROTOCOL_SMP:
break;
default:
break;
}
if (task->task_proto == SAS_PROTOCOL_SSP) {
scb->abort_task.ssp_frame.frame_type = SSP_TASK;
memcpy(scb->abort_task.ssp_frame.hashed_dest_addr,
task->dev->hashed_sas_addr, HASHED_SAS_ADDR_SIZE);
memcpy(scb->abort_task.ssp_frame.hashed_src_addr,
task->dev->port->ha->hashed_sas_addr,
HASHED_SAS_ADDR_SIZE);
scb->abort_task.ssp_frame.tptt = cpu_to_be16(0xFFFF);
memcpy(scb->abort_task.ssp_task.lun, task->ssp_task.LUN, 8);
scb->abort_task.ssp_task.tmf = TMF_ABORT_TASK;
scb->abort_task.ssp_task.tag = cpu_to_be16(0xFFFF);
}
scb->abort_task.sister_scb = cpu_to_le16(0xFFFF);
scb->abort_task.conn_handle = cpu_to_le16(
(u16)(unsigned long)task->dev->lldd_dev);
scb->abort_task.retry_count = 1;
scb->abort_task.index = cpu_to_le16((u16)tascb->tc_index);
scb->abort_task.itnl_to = cpu_to_le16(ITNL_TIMEOUT_CONST);
res = asd_enqueue_internal(ascb, asd_tmf_tasklet_complete,
asd_tmf_timedout);
if (res)
goto out_free;
wait_for_completion(&completion);
ASD_DPRINTK("tmf came back\n");
tascb->tag = tcs.tag;
tascb->tag_valid = tcs.tag_valid;
spin_lock_irqsave(&task->task_state_lock, flags);
if (task->task_state_flags & SAS_TASK_STATE_DONE) {
spin_unlock_irqrestore(&task->task_state_lock, flags);
res = TMF_RESP_FUNC_COMPLETE;
ASD_DPRINTK("%s: task 0x%p done\n", __func__, task);
goto out_done;
}
spin_unlock_irqrestore(&task->task_state_lock, flags);
if (tcs.dl_opcode == TC_SSP_RESP) {
/* The task to be aborted has been sent to the device.
* We got a Response IU for the ABORT TASK TMF. */
if (tcs.tmf_state == TMF_RESP_FUNC_COMPLETE)
res = asd_clear_nexus(task);
else
res = tcs.tmf_state;
} else if (tcs.dl_opcode == TC_NO_ERROR &&
tcs.tmf_state == TMF_RESP_FUNC_FAILED) {
/* timeout */
res = TMF_RESP_FUNC_FAILED;
} else {
/* In the following we assume that the managing layer
* will _never_ make a mistake, when issuing ABORT
* TASK.
*/
switch (tcs.dl_opcode) {
default:
res = asd_clear_nexus(task);
/* fallthrough */
case TC_NO_ERROR:
break;
/* The task hasn't been sent to the device xor
* we never got a (sane) Response IU for the
* ABORT TASK TMF.
*/
case TF_NAK_RECV:
res = TMF_RESP_INVALID_FRAME;
break;
case TF_TMF_TASK_DONE: /* done but not reported yet */
res = TMF_RESP_FUNC_FAILED;
leftover =
wait_for_completion_timeout(&tascb_completion,
AIC94XX_SCB_TIMEOUT);
spin_lock_irqsave(&task->task_state_lock, flags);
if (leftover < 1)
res = TMF_RESP_FUNC_FAILED;
if (task->task_state_flags & SAS_TASK_STATE_DONE)
res = TMF_RESP_FUNC_COMPLETE;
spin_unlock_irqrestore(&task->task_state_lock, flags);
break;
case TF_TMF_NO_TAG:
case TF_TMF_TAG_FREE: /* the tag is in the free list */
case TF_TMF_NO_CONN_HANDLE: /* no such device */
res = TMF_RESP_FUNC_COMPLETE;
break;
case TF_TMF_NO_CTX: /* not in seq, or proto != SSP */
res = TMF_RESP_FUNC_ESUPP;
break;
}
}
out_done:
tascb->completion = NULL;
if (res == TMF_RESP_FUNC_COMPLETE) {
task->lldd_task = NULL;
mb();
asd_ascb_free(tascb);
}
ASD_DPRINTK("task 0x%p aborted, res: 0x%x\n", task, res);
return res;
out_free:
asd_ascb_free(ascb);
ASD_DPRINTK("task 0x%p aborted, res: 0x%x\n", task, res);
return res;
}
/**
* asd_initiate_ssp_tmf -- send a TMF to an I_T_L or I_T_L_Q nexus
* @dev: pointer to struct domain_device of interest
* @lun: pointer to u8[8] which is the LUN
* @tmf: the TMF to be performed (see sas_task.h or the SAS spec)
* @index: the transaction context of the task to be queried if QT TMF
*
* This function is used to send ABORT TASK SET, CLEAR ACA,
* CLEAR TASK SET, LU RESET and QUERY TASK TMFs.
*
* No SCBs should be queued to the I_T_L nexus when this SCB is
* pending.
*
* Returns: TMF response code (see sas_task.h or the SAS spec)
*/
static int asd_initiate_ssp_tmf(struct domain_device *dev, u8 *lun,
int tmf, int index)
{
struct asd_ha_struct *asd_ha = dev->port->ha->lldd_ha;
struct asd_ascb *ascb;
int res = 1;
struct scb *scb;
DECLARE_COMPLETION_ONSTACK(completion);
DECLARE_TCS(tcs);
if (!(dev->tproto & SAS_PROTOCOL_SSP))
return TMF_RESP_FUNC_ESUPP;
ascb = asd_ascb_alloc_list(asd_ha, &res, GFP_KERNEL);
if (!ascb)
return -ENOMEM;
ascb->completion = &completion;
ascb->uldd_task = &tcs;
scb = ascb->scb;
if (tmf == TMF_QUERY_TASK)
scb->header.opcode = QUERY_SSP_TASK;
else
scb->header.opcode = INITIATE_SSP_TMF;
scb->ssp_tmf.proto_conn_rate = (1 << 4); /* SSP */
scb->ssp_tmf.proto_conn_rate |= dev->linkrate;
/* SSP frame header */
scb->ssp_tmf.ssp_frame.frame_type = SSP_TASK;
memcpy(scb->ssp_tmf.ssp_frame.hashed_dest_addr,
dev->hashed_sas_addr, HASHED_SAS_ADDR_SIZE);
memcpy(scb->ssp_tmf.ssp_frame.hashed_src_addr,
dev->port->ha->hashed_sas_addr, HASHED_SAS_ADDR_SIZE);
scb->ssp_tmf.ssp_frame.tptt = cpu_to_be16(0xFFFF);
/* SSP Task IU */
memcpy(scb->ssp_tmf.ssp_task.lun, lun, 8);
scb->ssp_tmf.ssp_task.tmf = tmf;
scb->ssp_tmf.sister_scb = cpu_to_le16(0xFFFF);
scb->ssp_tmf.conn_handle= cpu_to_le16((u16)(unsigned long)
dev->lldd_dev);
scb->ssp_tmf.retry_count = 1;
scb->ssp_tmf.itnl_to = cpu_to_le16(ITNL_TIMEOUT_CONST);
if (tmf == TMF_QUERY_TASK)
scb->ssp_tmf.index = cpu_to_le16(index);
res = asd_enqueue_internal(ascb, asd_tmf_tasklet_complete,
asd_tmf_timedout);
if (res)
goto out_err;
wait_for_completion(&completion);
switch (tcs.dl_opcode) {
case TC_NO_ERROR:
res = TMF_RESP_FUNC_COMPLETE;
break;
case TF_NAK_RECV:
res = TMF_RESP_INVALID_FRAME;
break;
case TF_TMF_TASK_DONE:
res = TMF_RESP_FUNC_FAILED;
break;
case TF_TMF_NO_TAG:
case TF_TMF_TAG_FREE: /* the tag is in the free list */
case TF_TMF_NO_CONN_HANDLE: /* no such device */
res = TMF_RESP_FUNC_COMPLETE;
break;
case TF_TMF_NO_CTX: /* not in seq, or proto != SSP */
res = TMF_RESP_FUNC_ESUPP;
break;
default:
/* Allow TMF response codes to propagate upwards */
res = tcs.dl_opcode;
break;
}
return res;
out_err:
asd_ascb_free(ascb);
return res;
}
int asd_abort_task_set(struct domain_device *dev, u8 *lun)
{
int res = asd_initiate_ssp_tmf(dev, lun, TMF_ABORT_TASK_SET, 0);
if (res == TMF_RESP_FUNC_COMPLETE)
asd_clear_nexus_I_T_L(dev, lun);
return res;
}
int asd_clear_aca(struct domain_device *dev, u8 *lun)
{
int res = asd_initiate_ssp_tmf(dev, lun, TMF_CLEAR_ACA, 0);
if (res == TMF_RESP_FUNC_COMPLETE)
asd_clear_nexus_I_T_L(dev, lun);
return res;
}
int asd_clear_task_set(struct domain_device *dev, u8 *lun)
{
int res = asd_initiate_ssp_tmf(dev, lun, TMF_CLEAR_TASK_SET, 0);
if (res == TMF_RESP_FUNC_COMPLETE)
asd_clear_nexus_I_T_L(dev, lun);
return res;
}
int asd_lu_reset(struct domain_device *dev, u8 *lun)
{
int res = asd_initiate_ssp_tmf(dev, lun, TMF_LU_RESET, 0);
if (res == TMF_RESP_FUNC_COMPLETE)
asd_clear_nexus_I_T_L(dev, lun);
return res;
}
/**
* asd_query_task -- send a QUERY TASK TMF to an I_T_L_Q nexus
* task: pointer to sas_task struct of interest
*
* Returns: TMF_RESP_FUNC_COMPLETE if the task is not in the task set,
* or TMF_RESP_FUNC_SUCC if the task is in the task set.
*
* Normally the management layer sets the task to aborted state,
* and then calls query task and then abort task.
*/
int asd_query_task(struct sas_task *task)
{
struct asd_ascb *ascb = task->lldd_task;
int index;
if (ascb) {
index = ascb->tc_index;
return asd_initiate_ssp_tmf(task->dev, task->ssp_task.LUN,
TMF_QUERY_TASK, index);
}
return TMF_RESP_FUNC_COMPLETE;
}
| gpl-2.0 |
sherpya/android-kernel-e310 | arch/arm/mach-fsm/dal_remotetest.c | 718 | 11225 | /* Copyright (c) 2008-2009, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*/
/*
* DAL remote test device test suite.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/debugfs.h>
#include "dal_remotetest.h"
#define BYTEBUF_LEN 64
#define rpc_error(num) \
do { \
errmask |= (1 << num); \
printk(KERN_INFO "%s: remote_unittest_%d failed (%d)\n", \
__func__, num, ret); \
} while (0)
#define verify_error(num, field) \
do { \
errmask |= (1 << num); \
printk(KERN_INFO "%s: remote_unittest_%d failed (%s)\n", \
__func__, num, field); \
} while (0)
static struct dentry *debugfs_dir_entry;
static struct dentry *debugfs_modem_entry;
static struct dentry *debugfs_dsp_entry;
static uint8_t in_bytebuf[BYTEBUF_LEN];
static uint8_t out_bytebuf[BYTEBUF_LEN];
static uint8_t out_bytebuf2[BYTEBUF_LEN];
static struct remote_test_data in_data;
static struct remote_test_data out_data;
static int block_until_cb = 1;
static void init_data(struct remote_test_data *data)
{
int i;
data->regular_event = REMOTE_UNITTEST_INPUT_HANDLE;
data->payload_event = REMOTE_UNITTEST_INPUT_HANDLE;
for (i = 0; i < 32; i++)
data->test[i] = i;
}
static int verify_data(struct remote_test_data *data)
{
int i;
if (data->regular_event != REMOTE_UNITTEST_INPUT_HANDLE ||
data->payload_event != REMOTE_UNITTEST_INPUT_HANDLE)
return -1;
for (i = 0; i < 32; i++)
if (data->test[i] != i)
return -1;
return 0;
}
static int verify_uint32_buffer(uint32_t *buf)
{
int i;
for (i = 0; i < 32; i++)
if (buf[i] != i)
return -1;
return 0;
}
static void init_bytebuf(uint8_t *bytebuf)
{
int i;
for (i = 0; i < BYTEBUF_LEN; i++)
bytebuf[i] = i & 0xff;
}
static int verify_bytebuf(uint8_t *bytebuf)
{
int i;
for (i = 0; i < BYTEBUF_LEN; i++)
if (bytebuf[i] != (i & 0xff))
return -1;
return 0;
}
static void test_cb(void *context, uint32_t param, void *data, uint32_t len)
{
block_until_cb = 0;
}
static int remotetest_exec(int dest, u64 *val)
{
void *dev_handle;
void *event_handles[3];
void *cb_handle;
int ret;
u64 errmask = 0;
uint32_t ouint;
uint32_t oalen;
/* test daldevice_attach */
ret = daldevice_attach(REMOTE_UNITTEST_DEVICEID, NULL,
dest, &dev_handle);
if (ret) {
printk(KERN_INFO "%s: failed to attach (%d)\n", __func__, ret);
*val = 0xffffffff;
return 0;
}
/* test remote_unittest_0 */
ret = remote_unittest_0(dev_handle, REMOTE_UNITTEST_INARG_1);
if (ret)
rpc_error(0);
/* test remote_unittest_1 */
ret = remote_unittest_1(dev_handle, REMOTE_UNITTEST_INARG_1,
REMOTE_UNITTEST_INARG_2);
if (ret)
rpc_error(1);
/* test remote_unittest_2 */
ouint = 0;
ret = remote_unittest_2(dev_handle, REMOTE_UNITTEST_INARG_1, &ouint);
if (ret)
rpc_error(2);
else if (ouint != REMOTE_UNITTEST_OUTARG_1)
verify_error(2, "ouint");
/* test remote_unittest_3 */
ret = remote_unittest_3(dev_handle, REMOTE_UNITTEST_INARG_1,
REMOTE_UNITTEST_INARG_2,
REMOTE_UNITTEST_INARG_3);
if (ret)
rpc_error(3);
/* test remote_unittest_4 */
ouint = 0;
ret = remote_unittest_4(dev_handle, REMOTE_UNITTEST_INARG_1,
REMOTE_UNITTEST_INARG_2, &ouint);
if (ret)
rpc_error(4);
else if (ouint != REMOTE_UNITTEST_OUTARG_1)
verify_error(4, "ouint");
/* test remote_unittest_5 */
init_data(&in_data);
ret = remote_unittest_5(dev_handle, &in_data, sizeof(in_data));
if (ret)
rpc_error(5);
/* test remote_unittest_6 */
init_data(&in_data);
ret = remote_unittest_6(dev_handle, REMOTE_UNITTEST_INARG_1,
&in_data.test, sizeof(in_data.test));
if (ret)
rpc_error(6);
/* test remote_unittest_7 */
init_data(&in_data);
memset(&out_data, 0, sizeof(out_data));
ret = remote_unittest_7(dev_handle, &in_data, sizeof(in_data),
&out_data.test, sizeof(out_data.test),
&oalen);
if (ret)
rpc_error(7);
else if (oalen != sizeof(out_data.test))
verify_error(7, "oalen");
else if (verify_uint32_buffer(out_data.test))
verify_error(7, "obuf");
/* test remote_unittest_8 */
init_bytebuf(in_bytebuf);
memset(&out_data, 0, sizeof(out_data));
ret = remote_unittest_8(dev_handle, in_bytebuf, sizeof(in_bytebuf),
&out_data, sizeof(out_data));
if (ret)
rpc_error(8);
else if (verify_data(&out_data))
verify_error(8, "obuf");
/* test remote_unittest_9 */
memset(&out_bytebuf, 0, sizeof(out_bytebuf));
ret = remote_unittest_9(dev_handle, out_bytebuf, sizeof(out_bytebuf));
if (ret)
rpc_error(9);
else if (verify_bytebuf(out_bytebuf))
verify_error(9, "obuf");
/* test remote_unittest_10 */
init_bytebuf(in_bytebuf);
memset(&out_bytebuf, 0, sizeof(out_bytebuf));
ret = remote_unittest_10(dev_handle, REMOTE_UNITTEST_INARG_1,
in_bytebuf, sizeof(in_bytebuf),
out_bytebuf, sizeof(out_bytebuf), &oalen);
if (ret)
rpc_error(10);
else if (oalen != sizeof(out_bytebuf))
verify_error(10, "oalen");
else if (verify_bytebuf(out_bytebuf))
verify_error(10, "obuf");
/* test remote_unittest_11 */
memset(&out_bytebuf, 0, sizeof(out_bytebuf));
ret = remote_unittest_11(dev_handle, REMOTE_UNITTEST_INARG_1,
out_bytebuf, sizeof(out_bytebuf));
if (ret)
rpc_error(11);
else if (verify_bytebuf(out_bytebuf))
verify_error(11, "obuf");
/* test remote_unittest_12 */
memset(&out_bytebuf, 0, sizeof(out_bytebuf));
ret = remote_unittest_12(dev_handle, REMOTE_UNITTEST_INARG_1,
out_bytebuf, sizeof(out_bytebuf), &oalen);
if (ret)
rpc_error(12);
else if (oalen != sizeof(out_bytebuf))
verify_error(12, "oalen");
else if (verify_bytebuf(out_bytebuf))
verify_error(12, "obuf");
/* test remote_unittest_13 */
init_data(&in_data);
memset(&out_data, 0, sizeof(out_data));
ret = remote_unittest_13(dev_handle, in_data.test, sizeof(in_data.test),
&in_data, sizeof(in_data),
&out_data, sizeof(out_data));
if (ret)
rpc_error(13);
else if (verify_data(&out_data))
verify_error(13, "obuf");
/* test remote_unittest_14 */
init_data(&in_data);
memset(out_bytebuf, 0, sizeof(out_bytebuf));
memset(out_bytebuf2, 0, sizeof(out_bytebuf2));
ret = remote_unittest_14(dev_handle,
in_data.test, sizeof(in_data.test),
out_bytebuf, sizeof(out_bytebuf),
out_bytebuf2, sizeof(out_bytebuf2), &oalen);
if (ret)
rpc_error(14);
else if (verify_bytebuf(out_bytebuf))
verify_error(14, "obuf");
else if (oalen != sizeof(out_bytebuf2))
verify_error(14, "oalen");
else if (verify_bytebuf(out_bytebuf2))
verify_error(14, "obuf2");
/* test remote_unittest_15 */
init_data(&in_data);
memset(out_bytebuf, 0, sizeof(out_bytebuf));
memset(&out_data, 0, sizeof(out_data));
ret = remote_unittest_15(dev_handle,
in_data.test, sizeof(in_data.test),
&in_data, sizeof(in_data),
&out_data, sizeof(out_data), &oalen,
out_bytebuf, sizeof(out_bytebuf));
if (ret)
rpc_error(15);
else if (oalen != sizeof(out_data))
verify_error(15, "oalen");
else if (verify_bytebuf(out_bytebuf))
verify_error(15, "obuf");
else if (verify_data(&out_data))
verify_error(15, "obuf2");
/* test setting up asynch events */
event_handles[0] = dalrpc_alloc_event(dev_handle);
event_handles[1] = dalrpc_alloc_event(dev_handle);
event_handles[2] = dalrpc_alloc_event(dev_handle);
cb_handle = dalrpc_alloc_cb(dev_handle, test_cb, &out_data);
in_data.regular_event = (uint32_t)event_handles[2];
in_data.payload_event = (uint32_t)cb_handle;
ret = remote_unittest_eventcfg(dev_handle, &in_data, sizeof(in_data));
if (ret) {
errmask |= (1 << 16);
printk(KERN_INFO "%s: failed to configure asynch (%d)\n",
__func__, ret);
}
/* test event */
ret = remote_unittest_eventtrig(dev_handle,
REMOTE_UNITTEST_REGULAR_EVENT);
if (ret) {
errmask |= (1 << 17);
printk(KERN_INFO "%s: failed to trigger event (%d)\n",
__func__, ret);
}
ret = dalrpc_event_wait(event_handles[2], 1000);
if (ret) {
errmask |= (1 << 18);
printk(KERN_INFO "%s: failed to receive event (%d)\n",
__func__, ret);
}
/* test event again */
ret = remote_unittest_eventtrig(dev_handle,
REMOTE_UNITTEST_REGULAR_EVENT);
if (ret) {
errmask |= (1 << 19);
printk(KERN_INFO "%s: failed to trigger event (%d)\n",
__func__, ret);
}
ret = dalrpc_event_wait_multiple(3, event_handles, 1000);
if (ret != 2) {
errmask |= (1 << 20);
printk(KERN_INFO "%s: failed to receive event (%d)\n",
__func__, ret);
}
/* test callback */
ret = remote_unittest_eventtrig(dev_handle,
REMOTE_UNITTEST_CALLBACK_EVENT);
if (ret) {
errmask |= (1 << 21);
printk(KERN_INFO "%s: failed to trigger callback (%d)\n",
__func__, ret);
} else
while (block_until_cb)
;
dalrpc_dealloc_cb(dev_handle, cb_handle);
dalrpc_dealloc_event(dev_handle, event_handles[0]);
dalrpc_dealloc_event(dev_handle, event_handles[1]);
dalrpc_dealloc_event(dev_handle, event_handles[2]);
/* test daldevice_detach */
ret = daldevice_detach(dev_handle);
if (ret) {
errmask |= (1 << 22);
printk(KERN_INFO "%s: failed to detach (%d)\n", __func__, ret);
}
printk(KERN_INFO "%s: remote_unittest complete\n", __func__);
*val = errmask;
return 0;
}
static int remotetest_modem_exec(void *data, u64 *val)
{
return remotetest_exec(DALRPC_DEST_MODEM, val);
}
static int remotetest_dsp_exec(void *data, u64 *val)
{
return remotetest_exec(DALRPC_DEST_QDSP, val);
}
DEFINE_SIMPLE_ATTRIBUTE(dal_modemtest_fops, remotetest_modem_exec,
NULL, "%llu\n");
DEFINE_SIMPLE_ATTRIBUTE(dal_dsptest_fops, remotetest_dsp_exec,
NULL, "%llu\n");
static int __init remotetest_init(void)
{
debugfs_dir_entry = debugfs_create_dir("dal", 0);
if (IS_ERR(debugfs_dir_entry))
return PTR_ERR(debugfs_dir_entry);
debugfs_modem_entry = debugfs_create_file("modem_test", 0444,
debugfs_dir_entry,
NULL, &dal_modemtest_fops);
if (IS_ERR(debugfs_modem_entry)) {
debugfs_remove(debugfs_dir_entry);
return PTR_ERR(debugfs_modem_entry);
}
debugfs_dsp_entry = debugfs_create_file("dsp_test", 0444,
debugfs_dir_entry,
NULL, &dal_dsptest_fops);
if (IS_ERR(debugfs_dsp_entry)) {
debugfs_remove(debugfs_modem_entry);
debugfs_remove(debugfs_dir_entry);
return PTR_ERR(debugfs_dsp_entry);
}
return 0;
}
static void __exit remotetest_exit(void)
{
debugfs_remove(debugfs_modem_entry);
debugfs_remove(debugfs_dsp_entry);
debugfs_remove(debugfs_dir_entry);
}
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Test for DAL RPC");
MODULE_VERSION("1.0");
module_init(remotetest_init);
module_exit(remotetest_exit);
| gpl-2.0 |
sherpya/android-kernel-e310 | drivers/i2c/busses/i2c-parport.c | 974 | 8576 | /* ------------------------------------------------------------------------ *
* i2c-parport.c I2C bus over parallel port *
* ------------------------------------------------------------------------ *
Copyright (C) 2003-2010 Jean Delvare <khali@linux-fr.org>
Based on older i2c-philips-par.c driver
Copyright (C) 1995-2000 Simon G. Vogl
With some changes from:
Frodo Looijaard <frodol@dds.nl>
Kyösti Mälkki <kmalkki@cc.hut.fi>
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/delay.h>
#include <linux/parport.h>
#include <linux/i2c.h>
#include <linux/i2c-algo-bit.h>
#include <linux/i2c-smbus.h>
#include <linux/slab.h>
#include "i2c-parport.h"
/* ----- Device list ------------------------------------------------------ */
struct i2c_par {
struct pardevice *pdev;
struct i2c_adapter adapter;
struct i2c_algo_bit_data algo_data;
struct i2c_smbus_alert_setup alert_data;
struct i2c_client *ara;
struct i2c_par *next;
};
static struct i2c_par *adapter_list;
/* ----- Low-level parallel port access ----------------------------------- */
static void port_write_data(struct parport *p, unsigned char d)
{
parport_write_data(p, d);
}
static void port_write_control(struct parport *p, unsigned char d)
{
parport_write_control(p, d);
}
static unsigned char port_read_data(struct parport *p)
{
return parport_read_data(p);
}
static unsigned char port_read_status(struct parport *p)
{
return parport_read_status(p);
}
static unsigned char port_read_control(struct parport *p)
{
return parport_read_control(p);
}
static void (*port_write[])(struct parport *, unsigned char) = {
port_write_data,
NULL,
port_write_control,
};
static unsigned char (*port_read[])(struct parport *) = {
port_read_data,
port_read_status,
port_read_control,
};
/* ----- Unified line operation functions --------------------------------- */
static inline void line_set(struct parport *data, int state,
const struct lineop *op)
{
u8 oldval = port_read[op->port](data);
/* Touch only the bit(s) needed */
if ((op->inverted && !state) || (!op->inverted && state))
port_write[op->port](data, oldval | op->val);
else
port_write[op->port](data, oldval & ~op->val);
}
static inline int line_get(struct parport *data,
const struct lineop *op)
{
u8 oldval = port_read[op->port](data);
return ((op->inverted && (oldval & op->val) != op->val)
|| (!op->inverted && (oldval & op->val) == op->val));
}
/* ----- I2C algorithm call-back functions and structures ----------------- */
static void parport_setscl(void *data, int state)
{
line_set((struct parport *) data, state, &adapter_parm[type].setscl);
}
static void parport_setsda(void *data, int state)
{
line_set((struct parport *) data, state, &adapter_parm[type].setsda);
}
static int parport_getscl(void *data)
{
return line_get((struct parport *) data, &adapter_parm[type].getscl);
}
static int parport_getsda(void *data)
{
return line_get((struct parport *) data, &adapter_parm[type].getsda);
}
/* Encapsulate the functions above in the correct structure.
Note that this is only a template, from which the real structures are
copied. The attaching code will set getscl to NULL for adapters that
cannot read SCL back, and will also make the data field point to
the parallel port structure. */
static const struct i2c_algo_bit_data parport_algo_data = {
.setsda = parport_setsda,
.setscl = parport_setscl,
.getsda = parport_getsda,
.getscl = parport_getscl,
.udelay = 10, /* ~50 kbps */
.timeout = HZ,
};
/* ----- I2c and parallel port call-back functions and structures --------- */
void i2c_parport_irq(void *data)
{
struct i2c_par *adapter = data;
struct i2c_client *ara = adapter->ara;
if (ara) {
dev_dbg(&ara->dev, "SMBus alert received\n");
i2c_handle_smbus_alert(ara);
} else
dev_dbg(&adapter->adapter.dev,
"SMBus alert received but no ARA client!\n");
}
static void i2c_parport_attach (struct parport *port)
{
struct i2c_par *adapter;
adapter = kzalloc(sizeof(struct i2c_par), GFP_KERNEL);
if (adapter == NULL) {
printk(KERN_ERR "i2c-parport: Failed to kzalloc\n");
return;
}
pr_debug("i2c-parport: attaching to %s\n", port->name);
parport_disable_irq(port);
adapter->pdev = parport_register_device(port, "i2c-parport",
NULL, NULL, i2c_parport_irq, PARPORT_FLAG_EXCL, adapter);
if (!adapter->pdev) {
printk(KERN_ERR "i2c-parport: Unable to register with parport\n");
goto ERROR0;
}
/* Fill the rest of the structure */
adapter->adapter.owner = THIS_MODULE;
adapter->adapter.class = I2C_CLASS_HWMON;
strlcpy(adapter->adapter.name, "Parallel port adapter",
sizeof(adapter->adapter.name));
adapter->algo_data = parport_algo_data;
/* Slow down if we can't sense SCL */
if (!adapter_parm[type].getscl.val) {
adapter->algo_data.getscl = NULL;
adapter->algo_data.udelay = 50; /* ~10 kbps */
}
adapter->algo_data.data = port;
adapter->adapter.algo_data = &adapter->algo_data;
adapter->adapter.dev.parent = port->physport->dev;
if (parport_claim_or_block(adapter->pdev) < 0) {
printk(KERN_ERR "i2c-parport: Could not claim parallel port\n");
goto ERROR1;
}
/* Reset hardware to a sane state (SCL and SDA high) */
parport_setsda(port, 1);
parport_setscl(port, 1);
/* Other init if needed (power on...) */
if (adapter_parm[type].init.val) {
line_set(port, 1, &adapter_parm[type].init);
/* Give powered devices some time to settle */
msleep(100);
}
if (i2c_bit_add_bus(&adapter->adapter) < 0) {
printk(KERN_ERR "i2c-parport: Unable to register with I2C\n");
goto ERROR1;
}
/* Setup SMBus alert if supported */
if (adapter_parm[type].smbus_alert) {
adapter->alert_data.alert_edge_triggered = 1;
adapter->ara = i2c_setup_smbus_alert(&adapter->adapter,
&adapter->alert_data);
if (adapter->ara)
parport_enable_irq(port);
else
printk(KERN_WARNING "i2c-parport: Failed to register "
"ARA client\n");
}
/* Add the new adapter to the list */
adapter->next = adapter_list;
adapter_list = adapter;
return;
ERROR1:
parport_release(adapter->pdev);
parport_unregister_device(adapter->pdev);
ERROR0:
kfree(adapter);
}
static void i2c_parport_detach (struct parport *port)
{
struct i2c_par *adapter, *prev;
/* Walk the list */
for (prev = NULL, adapter = adapter_list; adapter;
prev = adapter, adapter = adapter->next) {
if (adapter->pdev->port == port) {
if (adapter->ara) {
parport_disable_irq(port);
i2c_unregister_device(adapter->ara);
}
i2c_del_adapter(&adapter->adapter);
/* Un-init if needed (power off...) */
if (adapter_parm[type].init.val)
line_set(port, 0, &adapter_parm[type].init);
parport_release(adapter->pdev);
parport_unregister_device(adapter->pdev);
if (prev)
prev->next = adapter->next;
else
adapter_list = adapter->next;
kfree(adapter);
return;
}
}
}
static struct parport_driver i2c_parport_driver = {
.name = "i2c-parport",
.attach = i2c_parport_attach,
.detach = i2c_parport_detach,
};
/* ----- Module loading, unloading and information ------------------------ */
static int __init i2c_parport_init(void)
{
if (type < 0) {
printk(KERN_WARNING "i2c-parport: adapter type unspecified\n");
return -ENODEV;
}
if (type >= ARRAY_SIZE(adapter_parm)) {
printk(KERN_WARNING "i2c-parport: invalid type (%d)\n", type);
return -ENODEV;
}
return parport_register_driver(&i2c_parport_driver);
}
static void __exit i2c_parport_exit(void)
{
parport_unregister_driver(&i2c_parport_driver);
}
MODULE_AUTHOR("Jean Delvare <khali@linux-fr.org>");
MODULE_DESCRIPTION("I2C bus over parallel port");
MODULE_LICENSE("GPL");
module_init(i2c_parport_init);
module_exit(i2c_parport_exit);
| gpl-2.0 |
mysteryemotionz/v20j-geeb | drivers/hwmon/asus_atk0110.c | 3278 | 33814 | /*
* Copyright (C) 2007-2009 Luca Tettamanti <kronos.it@gmail.com>
*
* This file is released under the GPLv2
* See COPYING in the top level directory of the kernel tree.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/debugfs.h>
#include <linux/kernel.h>
#include <linux/hwmon.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/dmi.h>
#include <acpi/acpi.h>
#include <acpi/acpixf.h>
#include <acpi/acpi_drivers.h>
#include <acpi/acpi_bus.h>
#define ATK_HID "ATK0110"
static bool new_if;
module_param(new_if, bool, 0);
MODULE_PARM_DESC(new_if, "Override detection heuristic and force the use of the new ATK0110 interface");
static const struct dmi_system_id __initconst atk_force_new_if[] = {
{
/* Old interface has broken MCH temp monitoring */
.ident = "Asus Sabertooth X58",
.matches = {
DMI_MATCH(DMI_BOARD_NAME, "SABERTOOTH X58")
}
},
{ }
};
/*
* Minimum time between readings, enforced in order to avoid
* hogging the CPU.
*/
#define CACHE_TIME HZ
#define BOARD_ID "MBIF"
#define METHOD_ENUMERATE "GGRP"
#define METHOD_READ "GITM"
#define METHOD_WRITE "SITM"
#define METHOD_OLD_READ_TMP "RTMP"
#define METHOD_OLD_READ_VLT "RVLT"
#define METHOD_OLD_READ_FAN "RFAN"
#define METHOD_OLD_ENUM_TMP "TSIF"
#define METHOD_OLD_ENUM_VLT "VSIF"
#define METHOD_OLD_ENUM_FAN "FSIF"
#define ATK_MUX_HWMON 0x00000006ULL
#define ATK_MUX_MGMT 0x00000011ULL
#define ATK_CLASS_MASK 0xff000000ULL
#define ATK_CLASS_FREQ_CTL 0x03000000ULL
#define ATK_CLASS_FAN_CTL 0x04000000ULL
#define ATK_CLASS_HWMON 0x06000000ULL
#define ATK_CLASS_MGMT 0x11000000ULL
#define ATK_TYPE_MASK 0x00ff0000ULL
#define HWMON_TYPE_VOLT 0x00020000ULL
#define HWMON_TYPE_TEMP 0x00030000ULL
#define HWMON_TYPE_FAN 0x00040000ULL
#define ATK_ELEMENT_ID_MASK 0x0000ffffULL
#define ATK_EC_ID 0x11060004ULL
enum atk_pack_member {
HWMON_PACK_FLAGS,
HWMON_PACK_NAME,
HWMON_PACK_LIMIT1,
HWMON_PACK_LIMIT2,
HWMON_PACK_ENABLE
};
/* New package format */
#define _HWMON_NEW_PACK_SIZE 7
#define _HWMON_NEW_PACK_FLAGS 0
#define _HWMON_NEW_PACK_NAME 1
#define _HWMON_NEW_PACK_UNK1 2
#define _HWMON_NEW_PACK_UNK2 3
#define _HWMON_NEW_PACK_LIMIT1 4
#define _HWMON_NEW_PACK_LIMIT2 5
#define _HWMON_NEW_PACK_ENABLE 6
/* Old package format */
#define _HWMON_OLD_PACK_SIZE 5
#define _HWMON_OLD_PACK_FLAGS 0
#define _HWMON_OLD_PACK_NAME 1
#define _HWMON_OLD_PACK_LIMIT1 2
#define _HWMON_OLD_PACK_LIMIT2 3
#define _HWMON_OLD_PACK_ENABLE 4
struct atk_data {
struct device *hwmon_dev;
acpi_handle atk_handle;
struct acpi_device *acpi_dev;
bool old_interface;
/* old interface */
acpi_handle rtmp_handle;
acpi_handle rvlt_handle;
acpi_handle rfan_handle;
/* new inteface */
acpi_handle enumerate_handle;
acpi_handle read_handle;
acpi_handle write_handle;
bool disable_ec;
int voltage_count;
int temperature_count;
int fan_count;
struct list_head sensor_list;
struct {
struct dentry *root;
u32 id;
} debugfs;
};
typedef ssize_t (*sysfs_show_func)(struct device *dev,
struct device_attribute *attr, char *buf);
static const struct acpi_device_id atk_ids[] = {
{ATK_HID, 0},
{"", 0},
};
MODULE_DEVICE_TABLE(acpi, atk_ids);
#define ATTR_NAME_SIZE 16 /* Worst case is "tempN_input" */
struct atk_sensor_data {
struct list_head list;
struct atk_data *data;
struct device_attribute label_attr;
struct device_attribute input_attr;
struct device_attribute limit1_attr;
struct device_attribute limit2_attr;
char label_attr_name[ATTR_NAME_SIZE];
char input_attr_name[ATTR_NAME_SIZE];
char limit1_attr_name[ATTR_NAME_SIZE];
char limit2_attr_name[ATTR_NAME_SIZE];
u64 id;
u64 type;
u64 limit1;
u64 limit2;
u64 cached_value;
unsigned long last_updated; /* in jiffies */
bool is_valid;
char const *acpi_name;
};
/*
* Return buffer format:
* [0-3] "value" is valid flag
* [4-7] value
* [8- ] unknown stuff on newer mobos
*/
struct atk_acpi_ret_buffer {
u32 flags;
u32 value;
u8 data[];
};
/* Input buffer used for GITM and SITM methods */
struct atk_acpi_input_buf {
u32 id;
u32 param1;
u32 param2;
};
static int atk_add(struct acpi_device *device);
static int atk_remove(struct acpi_device *device, int type);
static void atk_print_sensor(struct atk_data *data, union acpi_object *obj);
static int atk_read_value(struct atk_sensor_data *sensor, u64 *value);
static void atk_free_sensors(struct atk_data *data);
static struct acpi_driver atk_driver = {
.name = ATK_HID,
.class = "hwmon",
.ids = atk_ids,
.ops = {
.add = atk_add,
.remove = atk_remove,
},
};
#define input_to_atk_sensor(attr) \
container_of(attr, struct atk_sensor_data, input_attr)
#define label_to_atk_sensor(attr) \
container_of(attr, struct atk_sensor_data, label_attr)
#define limit1_to_atk_sensor(attr) \
container_of(attr, struct atk_sensor_data, limit1_attr)
#define limit2_to_atk_sensor(attr) \
container_of(attr, struct atk_sensor_data, limit2_attr)
static ssize_t atk_input_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct atk_sensor_data *s = input_to_atk_sensor(attr);
u64 value;
int err;
err = atk_read_value(s, &value);
if (err)
return err;
if (s->type == HWMON_TYPE_TEMP)
/* ACPI returns decidegree */
value *= 100;
return sprintf(buf, "%llu\n", value);
}
static ssize_t atk_label_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct atk_sensor_data *s = label_to_atk_sensor(attr);
return sprintf(buf, "%s\n", s->acpi_name);
}
static ssize_t atk_limit1_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct atk_sensor_data *s = limit1_to_atk_sensor(attr);
u64 value = s->limit1;
if (s->type == HWMON_TYPE_TEMP)
value *= 100;
return sprintf(buf, "%lld\n", value);
}
static ssize_t atk_limit2_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct atk_sensor_data *s = limit2_to_atk_sensor(attr);
u64 value = s->limit2;
if (s->type == HWMON_TYPE_TEMP)
value *= 100;
return sprintf(buf, "%lld\n", value);
}
static ssize_t atk_name_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "atk0110\n");
}
static struct device_attribute atk_name_attr =
__ATTR(name, 0444, atk_name_show, NULL);
static void atk_init_attribute(struct device_attribute *attr, char *name,
sysfs_show_func show)
{
sysfs_attr_init(&attr->attr);
attr->attr.name = name;
attr->attr.mode = 0444;
attr->show = show;
attr->store = NULL;
}
static union acpi_object *atk_get_pack_member(struct atk_data *data,
union acpi_object *pack,
enum atk_pack_member m)
{
bool old_if = data->old_interface;
int offset;
switch (m) {
case HWMON_PACK_FLAGS:
offset = old_if ? _HWMON_OLD_PACK_FLAGS : _HWMON_NEW_PACK_FLAGS;
break;
case HWMON_PACK_NAME:
offset = old_if ? _HWMON_OLD_PACK_NAME : _HWMON_NEW_PACK_NAME;
break;
case HWMON_PACK_LIMIT1:
offset = old_if ? _HWMON_OLD_PACK_LIMIT1 :
_HWMON_NEW_PACK_LIMIT1;
break;
case HWMON_PACK_LIMIT2:
offset = old_if ? _HWMON_OLD_PACK_LIMIT2 :
_HWMON_NEW_PACK_LIMIT2;
break;
case HWMON_PACK_ENABLE:
offset = old_if ? _HWMON_OLD_PACK_ENABLE :
_HWMON_NEW_PACK_ENABLE;
break;
default:
return NULL;
}
return &pack->package.elements[offset];
}
/*
* New package format is:
* - flag (int)
* class - used for de-muxing the request to the correct GITn
* type (volt, temp, fan)
* sensor id |
* sensor id - used for de-muxing the request _inside_ the GITn
* - name (str)
* - unknown (int)
* - unknown (int)
* - limit1 (int)
* - limit2 (int)
* - enable (int)
*
* The old package has the same format but it's missing the two unknown fields.
*/
static int validate_hwmon_pack(struct atk_data *data, union acpi_object *obj)
{
struct device *dev = &data->acpi_dev->dev;
union acpi_object *tmp;
bool old_if = data->old_interface;
int const expected_size = old_if ? _HWMON_OLD_PACK_SIZE :
_HWMON_NEW_PACK_SIZE;
if (obj->type != ACPI_TYPE_PACKAGE) {
dev_warn(dev, "Invalid type: %d\n", obj->type);
return -EINVAL;
}
if (obj->package.count != expected_size) {
dev_warn(dev, "Invalid package size: %d, expected: %d\n",
obj->package.count, expected_size);
return -EINVAL;
}
tmp = atk_get_pack_member(data, obj, HWMON_PACK_FLAGS);
if (tmp->type != ACPI_TYPE_INTEGER) {
dev_warn(dev, "Invalid type (flag): %d\n", tmp->type);
return -EINVAL;
}
tmp = atk_get_pack_member(data, obj, HWMON_PACK_NAME);
if (tmp->type != ACPI_TYPE_STRING) {
dev_warn(dev, "Invalid type (name): %d\n", tmp->type);
return -EINVAL;
}
/* Don't check... we don't know what they're useful for anyway */
#if 0
tmp = &obj->package.elements[HWMON_PACK_UNK1];
if (tmp->type != ACPI_TYPE_INTEGER) {
dev_warn(dev, "Invalid type (unk1): %d\n", tmp->type);
return -EINVAL;
}
tmp = &obj->package.elements[HWMON_PACK_UNK2];
if (tmp->type != ACPI_TYPE_INTEGER) {
dev_warn(dev, "Invalid type (unk2): %d\n", tmp->type);
return -EINVAL;
}
#endif
tmp = atk_get_pack_member(data, obj, HWMON_PACK_LIMIT1);
if (tmp->type != ACPI_TYPE_INTEGER) {
dev_warn(dev, "Invalid type (limit1): %d\n", tmp->type);
return -EINVAL;
}
tmp = atk_get_pack_member(data, obj, HWMON_PACK_LIMIT2);
if (tmp->type != ACPI_TYPE_INTEGER) {
dev_warn(dev, "Invalid type (limit2): %d\n", tmp->type);
return -EINVAL;
}
tmp = atk_get_pack_member(data, obj, HWMON_PACK_ENABLE);
if (tmp->type != ACPI_TYPE_INTEGER) {
dev_warn(dev, "Invalid type (enable): %d\n", tmp->type);
return -EINVAL;
}
atk_print_sensor(data, obj);
return 0;
}
#ifdef DEBUG
static char const *atk_sensor_type(union acpi_object *flags)
{
u64 type = flags->integer.value & ATK_TYPE_MASK;
char const *what;
switch (type) {
case HWMON_TYPE_VOLT:
what = "voltage";
break;
case HWMON_TYPE_TEMP:
what = "temperature";
break;
case HWMON_TYPE_FAN:
what = "fan";
break;
default:
what = "unknown";
break;
}
return what;
}
#endif
static void atk_print_sensor(struct atk_data *data, union acpi_object *obj)
{
#ifdef DEBUG
struct device *dev = &data->acpi_dev->dev;
union acpi_object *flags;
union acpi_object *name;
union acpi_object *limit1;
union acpi_object *limit2;
union acpi_object *enable;
char const *what;
flags = atk_get_pack_member(data, obj, HWMON_PACK_FLAGS);
name = atk_get_pack_member(data, obj, HWMON_PACK_NAME);
limit1 = atk_get_pack_member(data, obj, HWMON_PACK_LIMIT1);
limit2 = atk_get_pack_member(data, obj, HWMON_PACK_LIMIT2);
enable = atk_get_pack_member(data, obj, HWMON_PACK_ENABLE);
what = atk_sensor_type(flags);
dev_dbg(dev, "%s: %#llx %s [%llu-%llu] %s\n", what,
flags->integer.value,
name->string.pointer,
limit1->integer.value, limit2->integer.value,
enable->integer.value ? "enabled" : "disabled");
#endif
}
static int atk_read_value_old(struct atk_sensor_data *sensor, u64 *value)
{
struct atk_data *data = sensor->data;
struct device *dev = &data->acpi_dev->dev;
struct acpi_object_list params;
union acpi_object id;
acpi_status status;
acpi_handle method;
switch (sensor->type) {
case HWMON_TYPE_VOLT:
method = data->rvlt_handle;
break;
case HWMON_TYPE_TEMP:
method = data->rtmp_handle;
break;
case HWMON_TYPE_FAN:
method = data->rfan_handle;
break;
default:
return -EINVAL;
}
id.type = ACPI_TYPE_INTEGER;
id.integer.value = sensor->id;
params.count = 1;
params.pointer = &id;
status = acpi_evaluate_integer(method, NULL, ¶ms, value);
if (status != AE_OK) {
dev_warn(dev, "%s: ACPI exception: %s\n", __func__,
acpi_format_exception(status));
return -EIO;
}
return 0;
}
static union acpi_object *atk_ggrp(struct atk_data *data, u16 mux)
{
struct device *dev = &data->acpi_dev->dev;
struct acpi_buffer buf;
acpi_status ret;
struct acpi_object_list params;
union acpi_object id;
union acpi_object *pack;
id.type = ACPI_TYPE_INTEGER;
id.integer.value = mux;
params.count = 1;
params.pointer = &id;
buf.length = ACPI_ALLOCATE_BUFFER;
ret = acpi_evaluate_object(data->enumerate_handle, NULL, ¶ms, &buf);
if (ret != AE_OK) {
dev_err(dev, "GGRP[%#x] ACPI exception: %s\n", mux,
acpi_format_exception(ret));
return ERR_PTR(-EIO);
}
pack = buf.pointer;
if (pack->type != ACPI_TYPE_PACKAGE) {
/* Execution was successful, but the id was not found */
ACPI_FREE(pack);
return ERR_PTR(-ENOENT);
}
if (pack->package.count < 1) {
dev_err(dev, "GGRP[%#x] package is too small\n", mux);
ACPI_FREE(pack);
return ERR_PTR(-EIO);
}
return pack;
}
static union acpi_object *atk_gitm(struct atk_data *data, u64 id)
{
struct device *dev = &data->acpi_dev->dev;
struct atk_acpi_input_buf buf;
union acpi_object tmp;
struct acpi_object_list params;
struct acpi_buffer ret;
union acpi_object *obj;
acpi_status status;
buf.id = id;
buf.param1 = 0;
buf.param2 = 0;
tmp.type = ACPI_TYPE_BUFFER;
tmp.buffer.pointer = (u8 *)&buf;
tmp.buffer.length = sizeof(buf);
params.count = 1;
params.pointer = (void *)&tmp;
ret.length = ACPI_ALLOCATE_BUFFER;
status = acpi_evaluate_object_typed(data->read_handle, NULL, ¶ms,
&ret, ACPI_TYPE_BUFFER);
if (status != AE_OK) {
dev_warn(dev, "GITM[%#llx] ACPI exception: %s\n", id,
acpi_format_exception(status));
return ERR_PTR(-EIO);
}
obj = ret.pointer;
/* Sanity check */
if (obj->buffer.length < 8) {
dev_warn(dev, "Unexpected ASBF length: %u\n",
obj->buffer.length);
ACPI_FREE(obj);
return ERR_PTR(-EIO);
}
return obj;
}
static union acpi_object *atk_sitm(struct atk_data *data,
struct atk_acpi_input_buf *buf)
{
struct device *dev = &data->acpi_dev->dev;
struct acpi_object_list params;
union acpi_object tmp;
struct acpi_buffer ret;
union acpi_object *obj;
acpi_status status;
tmp.type = ACPI_TYPE_BUFFER;
tmp.buffer.pointer = (u8 *)buf;
tmp.buffer.length = sizeof(*buf);
params.count = 1;
params.pointer = &tmp;
ret.length = ACPI_ALLOCATE_BUFFER;
status = acpi_evaluate_object_typed(data->write_handle, NULL, ¶ms,
&ret, ACPI_TYPE_BUFFER);
if (status != AE_OK) {
dev_warn(dev, "SITM[%#x] ACPI exception: %s\n", buf->id,
acpi_format_exception(status));
return ERR_PTR(-EIO);
}
obj = ret.pointer;
/* Sanity check */
if (obj->buffer.length < 8) {
dev_warn(dev, "Unexpected ASBF length: %u\n",
obj->buffer.length);
ACPI_FREE(obj);
return ERR_PTR(-EIO);
}
return obj;
}
static int atk_read_value_new(struct atk_sensor_data *sensor, u64 *value)
{
struct atk_data *data = sensor->data;
struct device *dev = &data->acpi_dev->dev;
union acpi_object *obj;
struct atk_acpi_ret_buffer *buf;
int err = 0;
obj = atk_gitm(data, sensor->id);
if (IS_ERR(obj))
return PTR_ERR(obj);
buf = (struct atk_acpi_ret_buffer *)obj->buffer.pointer;
if (buf->flags == 0) {
/*
* The reading is not valid, possible causes:
* - sensor failure
* - enumeration was FUBAR (and we didn't notice)
*/
dev_warn(dev, "Read failed, sensor = %#llx\n", sensor->id);
err = -EIO;
goto out;
}
*value = buf->value;
out:
ACPI_FREE(obj);
return err;
}
static int atk_read_value(struct atk_sensor_data *sensor, u64 *value)
{
int err;
if (!sensor->is_valid ||
time_after(jiffies, sensor->last_updated + CACHE_TIME)) {
if (sensor->data->old_interface)
err = atk_read_value_old(sensor, value);
else
err = atk_read_value_new(sensor, value);
sensor->is_valid = true;
sensor->last_updated = jiffies;
sensor->cached_value = *value;
} else {
*value = sensor->cached_value;
err = 0;
}
return err;
}
#ifdef CONFIG_DEBUG_FS
static int atk_debugfs_gitm_get(void *p, u64 *val)
{
struct atk_data *data = p;
union acpi_object *ret;
struct atk_acpi_ret_buffer *buf;
int err = 0;
if (!data->read_handle)
return -ENODEV;
if (!data->debugfs.id)
return -EINVAL;
ret = atk_gitm(data, data->debugfs.id);
if (IS_ERR(ret))
return PTR_ERR(ret);
buf = (struct atk_acpi_ret_buffer *)ret->buffer.pointer;
if (buf->flags)
*val = buf->value;
else
err = -EIO;
ACPI_FREE(ret);
return err;
}
DEFINE_SIMPLE_ATTRIBUTE(atk_debugfs_gitm,
atk_debugfs_gitm_get,
NULL,
"0x%08llx\n")
static int atk_acpi_print(char *buf, size_t sz, union acpi_object *obj)
{
int ret = 0;
switch (obj->type) {
case ACPI_TYPE_INTEGER:
ret = snprintf(buf, sz, "0x%08llx\n", obj->integer.value);
break;
case ACPI_TYPE_STRING:
ret = snprintf(buf, sz, "%s\n", obj->string.pointer);
break;
}
return ret;
}
static void atk_pack_print(char *buf, size_t sz, union acpi_object *pack)
{
int ret;
int i;
for (i = 0; i < pack->package.count; i++) {
union acpi_object *obj = &pack->package.elements[i];
ret = atk_acpi_print(buf, sz, obj);
if (ret >= sz)
break;
buf += ret;
sz -= ret;
}
}
static int atk_debugfs_ggrp_open(struct inode *inode, struct file *file)
{
struct atk_data *data = inode->i_private;
char *buf = NULL;
union acpi_object *ret;
u8 cls;
int i;
if (!data->enumerate_handle)
return -ENODEV;
if (!data->debugfs.id)
return -EINVAL;
cls = (data->debugfs.id & 0xff000000) >> 24;
ret = atk_ggrp(data, cls);
if (IS_ERR(ret))
return PTR_ERR(ret);
for (i = 0; i < ret->package.count; i++) {
union acpi_object *pack = &ret->package.elements[i];
union acpi_object *id;
if (pack->type != ACPI_TYPE_PACKAGE)
continue;
if (!pack->package.count)
continue;
id = &pack->package.elements[0];
if (id->integer.value == data->debugfs.id) {
/* Print the package */
buf = kzalloc(512, GFP_KERNEL);
if (!buf) {
ACPI_FREE(ret);
return -ENOMEM;
}
atk_pack_print(buf, 512, pack);
break;
}
}
ACPI_FREE(ret);
if (!buf)
return -EINVAL;
file->private_data = buf;
return nonseekable_open(inode, file);
}
static ssize_t atk_debugfs_ggrp_read(struct file *file, char __user *buf,
size_t count, loff_t *pos)
{
char *str = file->private_data;
size_t len = strlen(str);
return simple_read_from_buffer(buf, count, pos, str, len);
}
static int atk_debugfs_ggrp_release(struct inode *inode, struct file *file)
{
kfree(file->private_data);
return 0;
}
static const struct file_operations atk_debugfs_ggrp_fops = {
.read = atk_debugfs_ggrp_read,
.open = atk_debugfs_ggrp_open,
.release = atk_debugfs_ggrp_release,
.llseek = no_llseek,
};
static void atk_debugfs_init(struct atk_data *data)
{
struct dentry *d;
struct dentry *f;
data->debugfs.id = 0;
d = debugfs_create_dir("asus_atk0110", NULL);
if (!d || IS_ERR(d))
return;
f = debugfs_create_x32("id", S_IRUSR | S_IWUSR, d, &data->debugfs.id);
if (!f || IS_ERR(f))
goto cleanup;
f = debugfs_create_file("gitm", S_IRUSR, d, data,
&atk_debugfs_gitm);
if (!f || IS_ERR(f))
goto cleanup;
f = debugfs_create_file("ggrp", S_IRUSR, d, data,
&atk_debugfs_ggrp_fops);
if (!f || IS_ERR(f))
goto cleanup;
data->debugfs.root = d;
return;
cleanup:
debugfs_remove_recursive(d);
}
static void atk_debugfs_cleanup(struct atk_data *data)
{
debugfs_remove_recursive(data->debugfs.root);
}
#else /* CONFIG_DEBUG_FS */
static void atk_debugfs_init(struct atk_data *data)
{
}
static void atk_debugfs_cleanup(struct atk_data *data)
{
}
#endif
static int atk_add_sensor(struct atk_data *data, union acpi_object *obj)
{
struct device *dev = &data->acpi_dev->dev;
union acpi_object *flags;
union acpi_object *name;
union acpi_object *limit1;
union acpi_object *limit2;
union acpi_object *enable;
struct atk_sensor_data *sensor;
char const *base_name;
char const *limit1_name;
char const *limit2_name;
u64 type;
int err;
int *num;
int start;
if (obj->type != ACPI_TYPE_PACKAGE) {
/* wft is this? */
dev_warn(dev, "Unknown type for ACPI object: (%d)\n",
obj->type);
return -EINVAL;
}
err = validate_hwmon_pack(data, obj);
if (err)
return err;
/* Ok, we have a valid hwmon package */
type = atk_get_pack_member(data, obj, HWMON_PACK_FLAGS)->integer.value
& ATK_TYPE_MASK;
switch (type) {
case HWMON_TYPE_VOLT:
base_name = "in";
limit1_name = "min";
limit2_name = "max";
num = &data->voltage_count;
start = 0;
break;
case HWMON_TYPE_TEMP:
base_name = "temp";
limit1_name = "max";
limit2_name = "crit";
num = &data->temperature_count;
start = 1;
break;
case HWMON_TYPE_FAN:
base_name = "fan";
limit1_name = "min";
limit2_name = "max";
num = &data->fan_count;
start = 1;
break;
default:
dev_warn(dev, "Unknown sensor type: %#llx\n", type);
return -EINVAL;
}
enable = atk_get_pack_member(data, obj, HWMON_PACK_ENABLE);
if (!enable->integer.value)
/* sensor is disabled */
return 0;
flags = atk_get_pack_member(data, obj, HWMON_PACK_FLAGS);
name = atk_get_pack_member(data, obj, HWMON_PACK_NAME);
limit1 = atk_get_pack_member(data, obj, HWMON_PACK_LIMIT1);
limit2 = atk_get_pack_member(data, obj, HWMON_PACK_LIMIT2);
sensor = kzalloc(sizeof(*sensor), GFP_KERNEL);
if (!sensor)
return -ENOMEM;
sensor->acpi_name = kstrdup(name->string.pointer, GFP_KERNEL);
if (!sensor->acpi_name) {
err = -ENOMEM;
goto out;
}
INIT_LIST_HEAD(&sensor->list);
sensor->type = type;
sensor->data = data;
sensor->id = flags->integer.value;
sensor->limit1 = limit1->integer.value;
if (data->old_interface)
sensor->limit2 = limit2->integer.value;
else
/* The upper limit is expressed as delta from lower limit */
sensor->limit2 = sensor->limit1 + limit2->integer.value;
snprintf(sensor->input_attr_name, ATTR_NAME_SIZE,
"%s%d_input", base_name, start + *num);
atk_init_attribute(&sensor->input_attr,
sensor->input_attr_name,
atk_input_show);
snprintf(sensor->label_attr_name, ATTR_NAME_SIZE,
"%s%d_label", base_name, start + *num);
atk_init_attribute(&sensor->label_attr,
sensor->label_attr_name,
atk_label_show);
snprintf(sensor->limit1_attr_name, ATTR_NAME_SIZE,
"%s%d_%s", base_name, start + *num, limit1_name);
atk_init_attribute(&sensor->limit1_attr,
sensor->limit1_attr_name,
atk_limit1_show);
snprintf(sensor->limit2_attr_name, ATTR_NAME_SIZE,
"%s%d_%s", base_name, start + *num, limit2_name);
atk_init_attribute(&sensor->limit2_attr,
sensor->limit2_attr_name,
atk_limit2_show);
list_add(&sensor->list, &data->sensor_list);
(*num)++;
return 1;
out:
kfree(sensor->acpi_name);
kfree(sensor);
return err;
}
static int atk_enumerate_old_hwmon(struct atk_data *data)
{
struct device *dev = &data->acpi_dev->dev;
struct acpi_buffer buf;
union acpi_object *pack;
acpi_status status;
int i, ret;
int count = 0;
/* Voltages */
buf.length = ACPI_ALLOCATE_BUFFER;
status = acpi_evaluate_object_typed(data->atk_handle,
METHOD_OLD_ENUM_VLT, NULL, &buf, ACPI_TYPE_PACKAGE);
if (status != AE_OK) {
dev_warn(dev, METHOD_OLD_ENUM_VLT ": ACPI exception: %s\n",
acpi_format_exception(status));
return -ENODEV;
}
pack = buf.pointer;
for (i = 1; i < pack->package.count; i++) {
union acpi_object *obj = &pack->package.elements[i];
ret = atk_add_sensor(data, obj);
if (ret > 0)
count++;
}
ACPI_FREE(buf.pointer);
/* Temperatures */
buf.length = ACPI_ALLOCATE_BUFFER;
status = acpi_evaluate_object_typed(data->atk_handle,
METHOD_OLD_ENUM_TMP, NULL, &buf, ACPI_TYPE_PACKAGE);
if (status != AE_OK) {
dev_warn(dev, METHOD_OLD_ENUM_TMP ": ACPI exception: %s\n",
acpi_format_exception(status));
ret = -ENODEV;
goto cleanup;
}
pack = buf.pointer;
for (i = 1; i < pack->package.count; i++) {
union acpi_object *obj = &pack->package.elements[i];
ret = atk_add_sensor(data, obj);
if (ret > 0)
count++;
}
ACPI_FREE(buf.pointer);
/* Fans */
buf.length = ACPI_ALLOCATE_BUFFER;
status = acpi_evaluate_object_typed(data->atk_handle,
METHOD_OLD_ENUM_FAN, NULL, &buf, ACPI_TYPE_PACKAGE);
if (status != AE_OK) {
dev_warn(dev, METHOD_OLD_ENUM_FAN ": ACPI exception: %s\n",
acpi_format_exception(status));
ret = -ENODEV;
goto cleanup;
}
pack = buf.pointer;
for (i = 1; i < pack->package.count; i++) {
union acpi_object *obj = &pack->package.elements[i];
ret = atk_add_sensor(data, obj);
if (ret > 0)
count++;
}
ACPI_FREE(buf.pointer);
return count;
cleanup:
atk_free_sensors(data);
return ret;
}
static int atk_ec_present(struct atk_data *data)
{
struct device *dev = &data->acpi_dev->dev;
union acpi_object *pack;
union acpi_object *ec;
int ret;
int i;
pack = atk_ggrp(data, ATK_MUX_MGMT);
if (IS_ERR(pack)) {
if (PTR_ERR(pack) == -ENOENT) {
/* The MGMT class does not exists - that's ok */
dev_dbg(dev, "Class %#llx not found\n", ATK_MUX_MGMT);
return 0;
}
return PTR_ERR(pack);
}
/* Search the EC */
ec = NULL;
for (i = 0; i < pack->package.count; i++) {
union acpi_object *obj = &pack->package.elements[i];
union acpi_object *id;
if (obj->type != ACPI_TYPE_PACKAGE)
continue;
id = &obj->package.elements[0];
if (id->type != ACPI_TYPE_INTEGER)
continue;
if (id->integer.value == ATK_EC_ID) {
ec = obj;
break;
}
}
ret = (ec != NULL);
if (!ret)
/* The system has no EC */
dev_dbg(dev, "EC not found\n");
ACPI_FREE(pack);
return ret;
}
static int atk_ec_enabled(struct atk_data *data)
{
struct device *dev = &data->acpi_dev->dev;
union acpi_object *obj;
struct atk_acpi_ret_buffer *buf;
int err;
obj = atk_gitm(data, ATK_EC_ID);
if (IS_ERR(obj)) {
dev_err(dev, "Unable to query EC status\n");
return PTR_ERR(obj);
}
buf = (struct atk_acpi_ret_buffer *)obj->buffer.pointer;
if (buf->flags == 0) {
dev_err(dev, "Unable to query EC status\n");
err = -EIO;
} else {
err = (buf->value != 0);
dev_dbg(dev, "EC is %sabled\n",
err ? "en" : "dis");
}
ACPI_FREE(obj);
return err;
}
static int atk_ec_ctl(struct atk_data *data, int enable)
{
struct device *dev = &data->acpi_dev->dev;
union acpi_object *obj;
struct atk_acpi_input_buf sitm;
struct atk_acpi_ret_buffer *ec_ret;
int err = 0;
sitm.id = ATK_EC_ID;
sitm.param1 = enable;
sitm.param2 = 0;
obj = atk_sitm(data, &sitm);
if (IS_ERR(obj)) {
dev_err(dev, "Failed to %sable the EC\n",
enable ? "en" : "dis");
return PTR_ERR(obj);
}
ec_ret = (struct atk_acpi_ret_buffer *)obj->buffer.pointer;
if (ec_ret->flags == 0) {
dev_err(dev, "Failed to %sable the EC\n",
enable ? "en" : "dis");
err = -EIO;
} else {
dev_info(dev, "EC %sabled\n",
enable ? "en" : "dis");
}
ACPI_FREE(obj);
return err;
}
static int atk_enumerate_new_hwmon(struct atk_data *data)
{
struct device *dev = &data->acpi_dev->dev;
union acpi_object *pack;
int err;
int i;
err = atk_ec_present(data);
if (err < 0)
return err;
if (err) {
err = atk_ec_enabled(data);
if (err < 0)
return err;
/* If the EC was disabled we will disable it again on unload */
data->disable_ec = err;
err = atk_ec_ctl(data, 1);
if (err) {
data->disable_ec = false;
return err;
}
}
dev_dbg(dev, "Enumerating hwmon sensors\n");
pack = atk_ggrp(data, ATK_MUX_HWMON);
if (IS_ERR(pack))
return PTR_ERR(pack);
for (i = 0; i < pack->package.count; i++) {
union acpi_object *obj = &pack->package.elements[i];
atk_add_sensor(data, obj);
}
err = data->voltage_count + data->temperature_count + data->fan_count;
ACPI_FREE(pack);
return err;
}
static int atk_create_files(struct atk_data *data)
{
struct atk_sensor_data *s;
int err;
list_for_each_entry(s, &data->sensor_list, list) {
err = device_create_file(data->hwmon_dev, &s->input_attr);
if (err)
return err;
err = device_create_file(data->hwmon_dev, &s->label_attr);
if (err)
return err;
err = device_create_file(data->hwmon_dev, &s->limit1_attr);
if (err)
return err;
err = device_create_file(data->hwmon_dev, &s->limit2_attr);
if (err)
return err;
}
err = device_create_file(data->hwmon_dev, &atk_name_attr);
return err;
}
static void atk_remove_files(struct atk_data *data)
{
struct atk_sensor_data *s;
list_for_each_entry(s, &data->sensor_list, list) {
device_remove_file(data->hwmon_dev, &s->input_attr);
device_remove_file(data->hwmon_dev, &s->label_attr);
device_remove_file(data->hwmon_dev, &s->limit1_attr);
device_remove_file(data->hwmon_dev, &s->limit2_attr);
}
device_remove_file(data->hwmon_dev, &atk_name_attr);
}
static void atk_free_sensors(struct atk_data *data)
{
struct list_head *head = &data->sensor_list;
struct atk_sensor_data *s, *tmp;
list_for_each_entry_safe(s, tmp, head, list) {
kfree(s->acpi_name);
kfree(s);
}
}
static int atk_register_hwmon(struct atk_data *data)
{
struct device *dev = &data->acpi_dev->dev;
int err;
dev_dbg(dev, "registering hwmon device\n");
data->hwmon_dev = hwmon_device_register(dev);
if (IS_ERR(data->hwmon_dev))
return PTR_ERR(data->hwmon_dev);
dev_dbg(dev, "populating sysfs directory\n");
err = atk_create_files(data);
if (err)
goto remove;
return 0;
remove:
/* Cleanup the registered files */
atk_remove_files(data);
hwmon_device_unregister(data->hwmon_dev);
return err;
}
static int atk_probe_if(struct atk_data *data)
{
struct device *dev = &data->acpi_dev->dev;
acpi_handle ret;
acpi_status status;
int err = 0;
/* RTMP: read temperature */
status = acpi_get_handle(data->atk_handle, METHOD_OLD_READ_TMP, &ret);
if (ACPI_SUCCESS(status))
data->rtmp_handle = ret;
else
dev_dbg(dev, "method " METHOD_OLD_READ_TMP " not found: %s\n",
acpi_format_exception(status));
/* RVLT: read voltage */
status = acpi_get_handle(data->atk_handle, METHOD_OLD_READ_VLT, &ret);
if (ACPI_SUCCESS(status))
data->rvlt_handle = ret;
else
dev_dbg(dev, "method " METHOD_OLD_READ_VLT " not found: %s\n",
acpi_format_exception(status));
/* RFAN: read fan status */
status = acpi_get_handle(data->atk_handle, METHOD_OLD_READ_FAN, &ret);
if (ACPI_SUCCESS(status))
data->rfan_handle = ret;
else
dev_dbg(dev, "method " METHOD_OLD_READ_FAN " not found: %s\n",
acpi_format_exception(status));
/* Enumeration */
status = acpi_get_handle(data->atk_handle, METHOD_ENUMERATE, &ret);
if (ACPI_SUCCESS(status))
data->enumerate_handle = ret;
else
dev_dbg(dev, "method " METHOD_ENUMERATE " not found: %s\n",
acpi_format_exception(status));
/* De-multiplexer (read) */
status = acpi_get_handle(data->atk_handle, METHOD_READ, &ret);
if (ACPI_SUCCESS(status))
data->read_handle = ret;
else
dev_dbg(dev, "method " METHOD_READ " not found: %s\n",
acpi_format_exception(status));
/* De-multiplexer (write) */
status = acpi_get_handle(data->atk_handle, METHOD_WRITE, &ret);
if (ACPI_SUCCESS(status))
data->write_handle = ret;
else
dev_dbg(dev, "method " METHOD_WRITE " not found: %s\n",
acpi_format_exception(status));
/*
* Check for hwmon methods: first check "old" style methods; note that
* both may be present: in this case we stick to the old interface;
* analysis of multiple DSDTs indicates that when both interfaces
* are present the new one (GGRP/GITM) is not functional.
*/
if (new_if)
dev_info(dev, "Overriding interface detection\n");
if (data->rtmp_handle &&
data->rvlt_handle && data->rfan_handle && !new_if)
data->old_interface = true;
else if (data->enumerate_handle && data->read_handle &&
data->write_handle)
data->old_interface = false;
else
err = -ENODEV;
return err;
}
static int atk_add(struct acpi_device *device)
{
acpi_status ret;
int err;
struct acpi_buffer buf;
union acpi_object *obj;
struct atk_data *data;
dev_dbg(&device->dev, "adding...\n");
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (!data)
return -ENOMEM;
data->acpi_dev = device;
data->atk_handle = device->handle;
INIT_LIST_HEAD(&data->sensor_list);
data->disable_ec = false;
buf.length = ACPI_ALLOCATE_BUFFER;
ret = acpi_evaluate_object_typed(data->atk_handle, BOARD_ID, NULL,
&buf, ACPI_TYPE_PACKAGE);
if (ret != AE_OK) {
dev_dbg(&device->dev, "atk: method MBIF not found\n");
} else {
obj = buf.pointer;
if (obj->package.count >= 2) {
union acpi_object *id = &obj->package.elements[1];
if (id->type == ACPI_TYPE_STRING)
dev_dbg(&device->dev, "board ID = %s\n",
id->string.pointer);
}
ACPI_FREE(buf.pointer);
}
err = atk_probe_if(data);
if (err) {
dev_err(&device->dev, "No usable hwmon interface detected\n");
goto out;
}
if (data->old_interface) {
dev_dbg(&device->dev, "Using old hwmon interface\n");
err = atk_enumerate_old_hwmon(data);
} else {
dev_dbg(&device->dev, "Using new hwmon interface\n");
err = atk_enumerate_new_hwmon(data);
}
if (err < 0)
goto out;
if (err == 0) {
dev_info(&device->dev,
"No usable sensor detected, bailing out\n");
err = -ENODEV;
goto out;
}
err = atk_register_hwmon(data);
if (err)
goto cleanup;
atk_debugfs_init(data);
device->driver_data = data;
return 0;
cleanup:
atk_free_sensors(data);
out:
if (data->disable_ec)
atk_ec_ctl(data, 0);
kfree(data);
return err;
}
static int atk_remove(struct acpi_device *device, int type)
{
struct atk_data *data = device->driver_data;
dev_dbg(&device->dev, "removing...\n");
device->driver_data = NULL;
atk_debugfs_cleanup(data);
atk_remove_files(data);
atk_free_sensors(data);
hwmon_device_unregister(data->hwmon_dev);
if (data->disable_ec) {
if (atk_ec_ctl(data, 0))
dev_err(&device->dev, "Failed to disable EC\n");
}
kfree(data);
return 0;
}
static int __init atk0110_init(void)
{
int ret;
/* Make sure it's safe to access the device through ACPI */
if (!acpi_resources_are_enforced()) {
pr_err("Resources not safely usable due to acpi_enforce_resources kernel parameter\n");
return -EBUSY;
}
if (dmi_check_system(atk_force_new_if))
new_if = true;
ret = acpi_bus_register_driver(&atk_driver);
if (ret)
pr_info("acpi_bus_register_driver failed: %d\n", ret);
return ret;
}
static void __exit atk0110_exit(void)
{
acpi_bus_unregister_driver(&atk_driver);
}
module_init(atk0110_init);
module_exit(atk0110_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
DevChun/holiday-ics-kernel | arch/arm/plat-s3c24xx/s3c2412-iotiming.c | 4046 | 7783 | /* linux/arch/arm/plat-s3c24xx/s3c2412-iotiming.c
*
* Copyright (c) 2006-2008 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
*
* S3C2412/S3C2443 (PL093 based) IO timing support
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/cpufreq.h>
#include <linux/seq_file.h>
#include <linux/sysdev.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/amba/pl093.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/regs-s3c2412-mem.h>
#include <plat/cpu.h>
#include <plat/cpu-freq-core.h>
#include <plat/clock.h>
#define print_ns(x) ((x) / 10), ((x) % 10)
/**
* s3c2412_print_timing - print timing infromation via printk.
* @pfx: The prefix to print each line with.
* @iot: The IO timing information
*/
static void s3c2412_print_timing(const char *pfx, struct s3c_iotimings *iot)
{
struct s3c2412_iobank_timing *bt;
unsigned int bank;
for (bank = 0; bank < MAX_BANKS; bank++) {
bt = iot->bank[bank].io_2412;
if (!bt)
continue;
printk(KERN_DEBUG "%s: %d: idcy=%d.%d wstrd=%d.%d wstwr=%d,%d"
"wstoen=%d.%d wstwen=%d.%d wstbrd=%d.%d\n", pfx, bank,
print_ns(bt->idcy),
print_ns(bt->wstrd),
print_ns(bt->wstwr),
print_ns(bt->wstoen),
print_ns(bt->wstwen),
print_ns(bt->wstbrd));
}
}
/**
* to_div - turn a cycle length into a divisor setting.
* @cyc_tns: The cycle time in 10ths of nanoseconds.
* @clk_tns: The clock period in 10ths of nanoseconds.
*/
static inline unsigned int to_div(unsigned int cyc_tns, unsigned int clk_tns)
{
return cyc_tns ? DIV_ROUND_UP(cyc_tns, clk_tns) : 0;
}
/**
* calc_timing - calculate timing divisor value and check in range.
* @hwtm: The hardware timing in 10ths of nanoseconds.
* @clk_tns: The clock period in 10ths of nanoseconds.
* @err: Pointer to err variable to update in event of failure.
*/
static unsigned int calc_timing(unsigned int hwtm, unsigned int clk_tns,
unsigned int *err)
{
unsigned int ret = to_div(hwtm, clk_tns);
if (ret > 0xf)
*err = -EINVAL;
return ret;
}
/**
* s3c2412_calc_bank - calculate the bank divisor settings.
* @cfg: The current frequency configuration.
* @bt: The bank timing.
*/
static int s3c2412_calc_bank(struct s3c_cpufreq_config *cfg,
struct s3c2412_iobank_timing *bt)
{
unsigned int hclk = cfg->freq.hclk_tns;
int err = 0;
bt->smbidcyr = calc_timing(bt->idcy, hclk, &err);
bt->smbwstrd = calc_timing(bt->wstrd, hclk, &err);
bt->smbwstwr = calc_timing(bt->wstwr, hclk, &err);
bt->smbwstoen = calc_timing(bt->wstoen, hclk, &err);
bt->smbwstwen = calc_timing(bt->wstwen, hclk, &err);
bt->smbwstbrd = calc_timing(bt->wstbrd, hclk, &err);
return err;
}
/**
* s3c2412_iotiming_debugfs - debugfs show io bank timing information
* @seq: The seq_file to write output to using seq_printf().
* @cfg: The current configuration.
* @iob: The IO bank information to decode.
*/
void s3c2412_iotiming_debugfs(struct seq_file *seq,
struct s3c_cpufreq_config *cfg,
union s3c_iobank *iob)
{
struct s3c2412_iobank_timing *bt = iob->io_2412;
seq_printf(seq,
"\tRead: idcy=%d.%d wstrd=%d.%d wstwr=%d,%d"
"wstoen=%d.%d wstwen=%d.%d wstbrd=%d.%d\n",
print_ns(bt->idcy),
print_ns(bt->wstrd),
print_ns(bt->wstwr),
print_ns(bt->wstoen),
print_ns(bt->wstwen),
print_ns(bt->wstbrd));
}
/**
* s3c2412_iotiming_calc - calculate all the bank divisor settings.
* @cfg: The current frequency configuration.
* @iot: The bank timing information.
*
* Calculate the timing information for all the banks that are
* configured as IO, using s3c2412_calc_bank().
*/
int s3c2412_iotiming_calc(struct s3c_cpufreq_config *cfg,
struct s3c_iotimings *iot)
{
struct s3c2412_iobank_timing *bt;
int bank;
int ret;
for (bank = 0; bank < MAX_BANKS; bank++) {
bt = iot->bank[bank].io_2412;
if (!bt)
continue;
ret = s3c2412_calc_bank(cfg, bt);
if (ret) {
printk(KERN_ERR "%s: cannot calculate bank %d io\n",
__func__, bank);
goto err;
}
}
return 0;
err:
return ret;
}
/**
* s3c2412_iotiming_set - set the timing information
* @cfg: The current frequency configuration.
* @iot: The bank timing information.
*
* Set the IO bank information from the details calculated earlier from
* calling s3c2412_iotiming_calc().
*/
void s3c2412_iotiming_set(struct s3c_cpufreq_config *cfg,
struct s3c_iotimings *iot)
{
struct s3c2412_iobank_timing *bt;
void __iomem *regs;
int bank;
/* set the io timings from the specifier */
for (bank = 0; bank < MAX_BANKS; bank++) {
bt = iot->bank[bank].io_2412;
if (!bt)
continue;
regs = S3C2412_SSMC_BANK(bank);
__raw_writel(bt->smbidcyr, regs + SMBIDCYR);
__raw_writel(bt->smbwstrd, regs + SMBWSTRDR);
__raw_writel(bt->smbwstwr, regs + SMBWSTWRR);
__raw_writel(bt->smbwstoen, regs + SMBWSTOENR);
__raw_writel(bt->smbwstwen, regs + SMBWSTWENR);
__raw_writel(bt->smbwstbrd, regs + SMBWSTBRDR);
}
}
static inline unsigned int s3c2412_decode_timing(unsigned int clock, u32 reg)
{
return (reg & 0xf) * clock;
}
static void s3c2412_iotiming_getbank(struct s3c_cpufreq_config *cfg,
struct s3c2412_iobank_timing *bt,
unsigned int bank)
{
unsigned long clk = cfg->freq.hclk_tns; /* ssmc clock??? */
void __iomem *regs = S3C2412_SSMC_BANK(bank);
bt->idcy = s3c2412_decode_timing(clk, __raw_readl(regs + SMBIDCYR));
bt->wstrd = s3c2412_decode_timing(clk, __raw_readl(regs + SMBWSTRDR));
bt->wstoen = s3c2412_decode_timing(clk, __raw_readl(regs + SMBWSTOENR));
bt->wstwen = s3c2412_decode_timing(clk, __raw_readl(regs + SMBWSTWENR));
bt->wstbrd = s3c2412_decode_timing(clk, __raw_readl(regs + SMBWSTBRDR));
}
/**
* bank_is_io - return true if bank is (possibly) IO.
* @bank: The bank number.
* @bankcfg: The value of S3C2412_EBI_BANKCFG.
*/
static inline bool bank_is_io(unsigned int bank, u32 bankcfg)
{
if (bank < 2)
return true;
return !(bankcfg & (1 << bank));
}
int s3c2412_iotiming_get(struct s3c_cpufreq_config *cfg,
struct s3c_iotimings *timings)
{
struct s3c2412_iobank_timing *bt;
u32 bankcfg = __raw_readl(S3C2412_EBI_BANKCFG);
unsigned int bank;
/* look through all banks to see what is currently set. */
for (bank = 0; bank < MAX_BANKS; bank++) {
if (!bank_is_io(bank, bankcfg))
continue;
bt = kzalloc(sizeof(struct s3c2412_iobank_timing), GFP_KERNEL);
if (!bt) {
printk(KERN_ERR "%s: no memory for bank\n", __func__);
return -ENOMEM;
}
timings->bank[bank].io_2412 = bt;
s3c2412_iotiming_getbank(cfg, bt, bank);
}
s3c2412_print_timing("get", timings);
return 0;
}
/* this is in here as it is so small, it doesn't currently warrant a file
* to itself. We expect that any s3c24xx needing this is going to also
* need the iotiming support.
*/
void s3c2412_cpufreq_setrefresh(struct s3c_cpufreq_config *cfg)
{
struct s3c_cpufreq_board *board = cfg->board;
u32 refresh;
WARN_ON(board == NULL);
/* Reduce both the refresh time (in ns) and the frequency (in MHz)
* down to ensure that we do not overflow 32 bit numbers.
*
* This should work for HCLK up to 133MHz and refresh period up
* to 30usec.
*/
refresh = (cfg->freq.hclk / 100) * (board->refresh / 10);
refresh = DIV_ROUND_UP(refresh, (1000 * 1000)); /* apply scale */
refresh &= ((1 << 16) - 1);
s3c_freq_dbg("%s: refresh value %u\n", __func__, (unsigned int)refresh);
__raw_writel(refresh, S3C2412_REFRESH);
}
| gpl-2.0 |
TeamEOS/kernel_oppo_find7 | security/apparmor/path.c | 4814 | 6414 | /*
* AppArmor security module
*
* This file contains AppArmor function for pathnames
*
* Copyright (C) 1998-2008 Novell/SUSE
* Copyright 2009-2010 Canonical Ltd.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2 of the
* License.
*/
#include <linux/magic.h>
#include <linux/mount.h>
#include <linux/namei.h>
#include <linux/nsproxy.h>
#include <linux/path.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/fs_struct.h>
#include "include/apparmor.h"
#include "include/path.h"
#include "include/policy.h"
/* modified from dcache.c */
static int prepend(char **buffer, int buflen, const char *str, int namelen)
{
buflen -= namelen;
if (buflen < 0)
return -ENAMETOOLONG;
*buffer -= namelen;
memcpy(*buffer, str, namelen);
return 0;
}
#define CHROOT_NSCONNECT (PATH_CHROOT_REL | PATH_CHROOT_NSCONNECT)
/**
* d_namespace_path - lookup a name associated with a given path
* @path: path to lookup (NOT NULL)
* @buf: buffer to store path to (NOT NULL)
* @buflen: length of @buf
* @name: Returns - pointer for start of path name with in @buf (NOT NULL)
* @flags: flags controlling path lookup
*
* Handle path name lookup.
*
* Returns: %0 else error code if path lookup fails
* When no error the path name is returned in @name which points to
* to a position in @buf
*/
static int d_namespace_path(struct path *path, char *buf, int buflen,
char **name, int flags)
{
char *res;
int error = 0;
int connected = 1;
if (path->mnt->mnt_flags & MNT_INTERNAL) {
/* it's not mounted anywhere */
res = dentry_path(path->dentry, buf, buflen);
*name = res;
if (IS_ERR(res)) {
*name = buf;
return PTR_ERR(res);
}
if (path->dentry->d_sb->s_magic == PROC_SUPER_MAGIC &&
strncmp(*name, "/sys/", 5) == 0) {
/* TODO: convert over to using a per namespace
* control instead of hard coded /proc
*/
return prepend(name, *name - buf, "/proc", 5);
}
return 0;
}
/* resolve paths relative to chroot?*/
if (flags & PATH_CHROOT_REL) {
struct path root;
get_fs_root(current->fs, &root);
res = __d_path(path, &root, buf, buflen);
path_put(&root);
} else {
res = d_absolute_path(path, buf, buflen);
if (!our_mnt(path->mnt))
connected = 0;
}
/* handle error conditions - and still allow a partial path to
* be returned.
*/
if (!res || IS_ERR(res)) {
connected = 0;
res = dentry_path_raw(path->dentry, buf, buflen);
if (IS_ERR(res)) {
error = PTR_ERR(res);
*name = buf;
goto out;
};
} else if (!our_mnt(path->mnt))
connected = 0;
*name = res;
/* Handle two cases:
* 1. A deleted dentry && profile is not allowing mediation of deleted
* 2. On some filesystems, newly allocated dentries appear to the
* security_path hooks as a deleted dentry except without an inode
* allocated.
*/
if (d_unlinked(path->dentry) && path->dentry->d_inode &&
!(flags & PATH_MEDIATE_DELETED)) {
error = -ENOENT;
goto out;
}
/* If the path is not connected to the expected root,
* check if it is a sysctl and handle specially else remove any
* leading / that __d_path may have returned.
* Unless
* specifically directed to connect the path,
* OR
* if in a chroot and doing chroot relative paths and the path
* resolves to the namespace root (would be connected outside
* of chroot) and specifically directed to connect paths to
* namespace root.
*/
if (!connected) {
if (!(flags & PATH_CONNECT_PATH) &&
!(((flags & CHROOT_NSCONNECT) == CHROOT_NSCONNECT) &&
our_mnt(path->mnt))) {
/* disconnected path, don't return pathname starting
* with '/'
*/
error = -EACCES;
if (*res == '/')
*name = res + 1;
}
}
out:
return error;
}
/**
* get_name_to_buffer - get the pathname to a buffer ensure dir / is appended
* @path: path to get name for (NOT NULL)
* @flags: flags controlling path lookup
* @buffer: buffer to put name in (NOT NULL)
* @size: size of buffer
* @name: Returns - contains position of path name in @buffer (NOT NULL)
*
* Returns: %0 else error on failure
*/
static int get_name_to_buffer(struct path *path, int flags, char *buffer,
int size, char **name, const char **info)
{
int adjust = (flags & PATH_IS_DIR) ? 1 : 0;
int error = d_namespace_path(path, buffer, size - adjust, name, flags);
if (!error && (flags & PATH_IS_DIR) && (*name)[1] != '\0')
/*
* Append "/" to the pathname. The root directory is a special
* case; it already ends in slash.
*/
strcpy(&buffer[size - 2], "/");
if (info && error) {
if (error == -ENOENT)
*info = "Failed name lookup - deleted entry";
else if (error == -ESTALE)
*info = "Failed name lookup - disconnected path";
else if (error == -ENAMETOOLONG)
*info = "Failed name lookup - name too long";
else
*info = "Failed name lookup";
}
return error;
}
/**
* aa_path_name - compute the pathname of a file
* @path: path the file (NOT NULL)
* @flags: flags controlling path name generation
* @buffer: buffer that aa_get_name() allocated (NOT NULL)
* @name: Returns - the generated path name if !error (NOT NULL)
* @info: Returns - information on why the path lookup failed (MAYBE NULL)
*
* @name is a pointer to the beginning of the pathname (which usually differs
* from the beginning of the buffer), or NULL. If there is an error @name
* may contain a partial or invalid name that can be used for audit purposes,
* but it can not be used for mediation.
*
* We need PATH_IS_DIR to indicate whether the file is a directory or not
* because the file may not yet exist, and so we cannot check the inode's
* file type.
*
* Returns: %0 else error code if could retrieve name
*/
int aa_path_name(struct path *path, int flags, char **buffer, const char **name,
const char **info)
{
char *buf, *str = NULL;
int size = 256;
int error;
*name = NULL;
*buffer = NULL;
for (;;) {
/* freed by caller */
buf = kmalloc(size, GFP_KERNEL);
if (!buf)
return -ENOMEM;
error = get_name_to_buffer(path, flags, buf, size, &str, info);
if (error != -ENAMETOOLONG)
break;
kfree(buf);
size <<= 1;
if (size > aa_g_path_max)
return -ENAMETOOLONG;
*info = NULL;
}
*buffer = buf;
*name = str;
return error;
}
| gpl-2.0 |
CyanogenMod/android_kernel_xiaomi_aries | security/tomoyo/securityfs_if.c | 5070 | 7630 | /*
* security/tomoyo/securityfs_if.c
*
* Copyright (C) 2005-2011 NTT DATA CORPORATION
*/
#include <linux/security.h>
#include "common.h"
/**
* tomoyo_check_task_acl - Check permission for task operation.
*
* @r: Pointer to "struct tomoyo_request_info".
* @ptr: Pointer to "struct tomoyo_acl_info".
*
* Returns true if granted, false otherwise.
*/
static bool tomoyo_check_task_acl(struct tomoyo_request_info *r,
const struct tomoyo_acl_info *ptr)
{
const struct tomoyo_task_acl *acl = container_of(ptr, typeof(*acl),
head);
return !tomoyo_pathcmp(r->param.task.domainname, acl->domainname);
}
/**
* tomoyo_write_self - write() for /sys/kernel/security/tomoyo/self_domain interface.
*
* @file: Pointer to "struct file".
* @buf: Domainname to transit to.
* @count: Size of @buf.
* @ppos: Unused.
*
* Returns @count on success, negative value otherwise.
*
* If domain transition was permitted but the domain transition failed, this
* function returns error rather than terminating current thread with SIGKILL.
*/
static ssize_t tomoyo_write_self(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
char *data;
int error;
if (!count || count >= TOMOYO_EXEC_TMPSIZE - 10)
return -ENOMEM;
data = kzalloc(count + 1, GFP_NOFS);
if (!data)
return -ENOMEM;
if (copy_from_user(data, buf, count)) {
error = -EFAULT;
goto out;
}
tomoyo_normalize_line(data);
if (tomoyo_correct_domain(data)) {
const int idx = tomoyo_read_lock();
struct tomoyo_path_info name;
struct tomoyo_request_info r;
name.name = data;
tomoyo_fill_path_info(&name);
/* Check "task manual_domain_transition" permission. */
tomoyo_init_request_info(&r, NULL, TOMOYO_MAC_FILE_EXECUTE);
r.param_type = TOMOYO_TYPE_MANUAL_TASK_ACL;
r.param.task.domainname = &name;
tomoyo_check_acl(&r, tomoyo_check_task_acl);
if (!r.granted)
error = -EPERM;
else {
struct tomoyo_domain_info *new_domain =
tomoyo_assign_domain(data, true);
if (!new_domain) {
error = -ENOENT;
} else {
struct cred *cred = prepare_creds();
if (!cred) {
error = -ENOMEM;
} else {
struct tomoyo_domain_info *old_domain =
cred->security;
cred->security = new_domain;
atomic_inc(&new_domain->users);
atomic_dec(&old_domain->users);
commit_creds(cred);
error = 0;
}
}
}
tomoyo_read_unlock(idx);
} else
error = -EINVAL;
out:
kfree(data);
return error ? error : count;
}
/**
* tomoyo_read_self - read() for /sys/kernel/security/tomoyo/self_domain interface.
*
* @file: Pointer to "struct file".
* @buf: Domainname which current thread belongs to.
* @count: Size of @buf.
* @ppos: Bytes read by now.
*
* Returns read size on success, negative value otherwise.
*/
static ssize_t tomoyo_read_self(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
const char *domain = tomoyo_domain()->domainname->name;
loff_t len = strlen(domain);
loff_t pos = *ppos;
if (pos >= len || !count)
return 0;
len -= pos;
if (count < len)
len = count;
if (copy_to_user(buf, domain + pos, len))
return -EFAULT;
*ppos += len;
return len;
}
/* Operations for /sys/kernel/security/tomoyo/self_domain interface. */
static const struct file_operations tomoyo_self_operations = {
.write = tomoyo_write_self,
.read = tomoyo_read_self,
};
/**
* tomoyo_open - open() for /sys/kernel/security/tomoyo/ interface.
*
* @inode: Pointer to "struct inode".
* @file: Pointer to "struct file".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_open(struct inode *inode, struct file *file)
{
const int key = ((u8 *) file->f_path.dentry->d_inode->i_private)
- ((u8 *) NULL);
return tomoyo_open_control(key, file);
}
/**
* tomoyo_release - close() for /sys/kernel/security/tomoyo/ interface.
*
* @inode: Pointer to "struct inode".
* @file: Pointer to "struct file".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_release(struct inode *inode, struct file *file)
{
return tomoyo_close_control(file->private_data);
}
/**
* tomoyo_poll - poll() for /sys/kernel/security/tomoyo/ interface.
*
* @file: Pointer to "struct file".
* @wait: Pointer to "poll_table". Maybe NULL.
*
* Returns POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM if ready to read/write,
* POLLOUT | POLLWRNORM otherwise.
*/
static unsigned int tomoyo_poll(struct file *file, poll_table *wait)
{
return tomoyo_poll_control(file, wait);
}
/**
* tomoyo_read - read() for /sys/kernel/security/tomoyo/ interface.
*
* @file: Pointer to "struct file".
* @buf: Pointer to buffer.
* @count: Size of @buf.
* @ppos: Unused.
*
* Returns bytes read on success, negative value otherwise.
*/
static ssize_t tomoyo_read(struct file *file, char __user *buf, size_t count,
loff_t *ppos)
{
return tomoyo_read_control(file->private_data, buf, count);
}
/**
* tomoyo_write - write() for /sys/kernel/security/tomoyo/ interface.
*
* @file: Pointer to "struct file".
* @buf: Pointer to buffer.
* @count: Size of @buf.
* @ppos: Unused.
*
* Returns @count on success, negative value otherwise.
*/
static ssize_t tomoyo_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
return tomoyo_write_control(file->private_data, buf, count);
}
/*
* tomoyo_operations is a "struct file_operations" which is used for handling
* /sys/kernel/security/tomoyo/ interface.
*
* Some files under /sys/kernel/security/tomoyo/ directory accept open(O_RDWR).
* See tomoyo_io_buffer for internals.
*/
static const struct file_operations tomoyo_operations = {
.open = tomoyo_open,
.release = tomoyo_release,
.poll = tomoyo_poll,
.read = tomoyo_read,
.write = tomoyo_write,
.llseek = noop_llseek,
};
/**
* tomoyo_create_entry - Create interface files under /sys/kernel/security/tomoyo/ directory.
*
* @name: The name of the interface file.
* @mode: The permission of the interface file.
* @parent: The parent directory.
* @key: Type of interface.
*
* Returns nothing.
*/
static void __init tomoyo_create_entry(const char *name, const umode_t mode,
struct dentry *parent, const u8 key)
{
securityfs_create_file(name, mode, parent, ((u8 *) NULL) + key,
&tomoyo_operations);
}
/**
* tomoyo_initerface_init - Initialize /sys/kernel/security/tomoyo/ interface.
*
* Returns 0.
*/
static int __init tomoyo_initerface_init(void)
{
struct dentry *tomoyo_dir;
/* Don't create securityfs entries unless registered. */
if (current_cred()->security != &tomoyo_kernel_domain)
return 0;
tomoyo_dir = securityfs_create_dir("tomoyo", NULL);
tomoyo_create_entry("query", 0600, tomoyo_dir,
TOMOYO_QUERY);
tomoyo_create_entry("domain_policy", 0600, tomoyo_dir,
TOMOYO_DOMAINPOLICY);
tomoyo_create_entry("exception_policy", 0600, tomoyo_dir,
TOMOYO_EXCEPTIONPOLICY);
tomoyo_create_entry("audit", 0400, tomoyo_dir,
TOMOYO_AUDIT);
tomoyo_create_entry(".process_status", 0600, tomoyo_dir,
TOMOYO_PROCESS_STATUS);
tomoyo_create_entry("stat", 0644, tomoyo_dir,
TOMOYO_STAT);
tomoyo_create_entry("profile", 0600, tomoyo_dir,
TOMOYO_PROFILE);
tomoyo_create_entry("manager", 0600, tomoyo_dir,
TOMOYO_MANAGER);
tomoyo_create_entry("version", 0400, tomoyo_dir,
TOMOYO_VERSION);
securityfs_create_file("self_domain", 0666, tomoyo_dir, NULL,
&tomoyo_self_operations);
tomoyo_load_builtin_policy();
return 0;
}
fs_initcall(tomoyo_initerface_init);
| gpl-2.0 |
UISS-Dev-Team/android_kernel_huawei_c8813 | drivers/usb/host/ehci-sh.c | 5070 | 5234 | /*
* SuperH EHCI host controller driver
*
* Copyright (C) 2010 Paul Mundt
*
* Based on ohci-sh.c and ehci-atmel.c.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/platform_device.h>
#include <linux/clk.h>
struct ehci_sh_priv {
struct clk *iclk, *fclk;
struct usb_hcd *hcd;
};
static int ehci_sh_reset(struct usb_hcd *hcd)
{
struct ehci_hcd *ehci = hcd_to_ehci(hcd);
int ret;
ehci->caps = hcd->regs;
ehci->regs = hcd->regs + HC_LENGTH(ehci, ehci_readl(ehci,
&ehci->caps->hc_capbase));
dbg_hcs_params(ehci, "reset");
dbg_hcc_params(ehci, "reset");
ehci->hcs_params = ehci_readl(ehci, &ehci->caps->hcs_params);
ret = ehci_halt(ehci);
if (unlikely(ret))
return ret;
ret = ehci_init(hcd);
if (unlikely(ret))
return ret;
ehci->sbrn = 0x20;
ehci_reset(ehci);
ehci_port_power(ehci, 0);
return ret;
}
static const struct hc_driver ehci_sh_hc_driver = {
.description = hcd_name,
.product_desc = "SuperH EHCI",
.hcd_priv_size = sizeof(struct ehci_hcd),
/*
* generic hardware linkage
*/
.irq = ehci_irq,
.flags = HCD_USB2 | HCD_MEMORY,
/*
* basic lifecycle operations
*/
.reset = ehci_sh_reset,
.start = ehci_run,
.stop = ehci_stop,
.shutdown = ehci_shutdown,
/*
* managing i/o requests and associated device resources
*/
.urb_enqueue = ehci_urb_enqueue,
.urb_dequeue = ehci_urb_dequeue,
.endpoint_disable = ehci_endpoint_disable,
.endpoint_reset = ehci_endpoint_reset,
/*
* scheduling support
*/
.get_frame_number = ehci_get_frame,
/*
* root hub support
*/
.hub_status_data = ehci_hub_status_data,
.hub_control = ehci_hub_control,
#ifdef CONFIG_PM
.bus_suspend = ehci_bus_suspend,
.bus_resume = ehci_bus_resume,
#endif
.relinquish_port = ehci_relinquish_port,
.port_handed_over = ehci_port_handed_over,
.clear_tt_buffer_complete = ehci_clear_tt_buffer_complete,
};
static int ehci_hcd_sh_probe(struct platform_device *pdev)
{
const struct hc_driver *driver = &ehci_sh_hc_driver;
struct resource *res;
struct ehci_sh_priv *priv;
struct usb_hcd *hcd;
int irq, ret;
if (usb_disabled())
return -ENODEV;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev,
"Found HC with no register addr. Check %s setup!\n",
dev_name(&pdev->dev));
ret = -ENODEV;
goto fail_create_hcd;
}
irq = platform_get_irq(pdev, 0);
if (irq <= 0) {
dev_err(&pdev->dev,
"Found HC with no IRQ. Check %s setup!\n",
dev_name(&pdev->dev));
ret = -ENODEV;
goto fail_create_hcd;
}
/* initialize hcd */
hcd = usb_create_hcd(&ehci_sh_hc_driver, &pdev->dev,
dev_name(&pdev->dev));
if (!hcd) {
ret = -ENOMEM;
goto fail_create_hcd;
}
hcd->rsrc_start = res->start;
hcd->rsrc_len = resource_size(res);
if (!request_mem_region(hcd->rsrc_start, hcd->rsrc_len,
driver->description)) {
dev_dbg(&pdev->dev, "controller already in use\n");
ret = -EBUSY;
goto fail_request_resource;
}
hcd->regs = ioremap_nocache(hcd->rsrc_start, hcd->rsrc_len);
if (hcd->regs == NULL) {
dev_dbg(&pdev->dev, "error mapping memory\n");
ret = -ENXIO;
goto fail_ioremap;
}
priv = kmalloc(sizeof(struct ehci_sh_priv), GFP_KERNEL);
if (!priv) {
dev_dbg(&pdev->dev, "error allocating priv data\n");
ret = -ENOMEM;
goto fail_alloc;
}
/* These are optional, we don't care if they fail */
priv->fclk = clk_get(&pdev->dev, "usb_fck");
if (IS_ERR(priv->fclk))
priv->fclk = NULL;
priv->iclk = clk_get(&pdev->dev, "usb_ick");
if (IS_ERR(priv->iclk))
priv->iclk = NULL;
clk_enable(priv->fclk);
clk_enable(priv->iclk);
ret = usb_add_hcd(hcd, irq, IRQF_SHARED);
if (ret != 0) {
dev_err(&pdev->dev, "Failed to add hcd");
goto fail_add_hcd;
}
priv->hcd = hcd;
platform_set_drvdata(pdev, priv);
return ret;
fail_add_hcd:
clk_disable(priv->iclk);
clk_disable(priv->fclk);
clk_put(priv->iclk);
clk_put(priv->fclk);
kfree(priv);
fail_alloc:
iounmap(hcd->regs);
fail_ioremap:
release_mem_region(hcd->rsrc_start, hcd->rsrc_len);
fail_request_resource:
usb_put_hcd(hcd);
fail_create_hcd:
dev_err(&pdev->dev, "init %s fail, %d\n", dev_name(&pdev->dev), ret);
return ret;
}
static int __exit ehci_hcd_sh_remove(struct platform_device *pdev)
{
struct ehci_sh_priv *priv = platform_get_drvdata(pdev);
struct usb_hcd *hcd = priv->hcd;
usb_remove_hcd(hcd);
iounmap(hcd->regs);
release_mem_region(hcd->rsrc_start, hcd->rsrc_len);
usb_put_hcd(hcd);
platform_set_drvdata(pdev, NULL);
clk_disable(priv->fclk);
clk_disable(priv->iclk);
clk_put(priv->fclk);
clk_put(priv->iclk);
kfree(priv);
return 0;
}
static void ehci_hcd_sh_shutdown(struct platform_device *pdev)
{
struct ehci_sh_priv *priv = platform_get_drvdata(pdev);
struct usb_hcd *hcd = priv->hcd;
if (hcd->driver->shutdown)
hcd->driver->shutdown(hcd);
}
static struct platform_driver ehci_hcd_sh_driver = {
.probe = ehci_hcd_sh_probe,
.remove = __exit_p(ehci_hcd_sh_remove),
.shutdown = ehci_hcd_sh_shutdown,
.driver = {
.name = "sh_ehci",
.owner = THIS_MODULE,
},
};
MODULE_ALIAS("platform:sh_ehci");
| gpl-2.0 |
Snuzzo/B14CKB1RD_kernel_m8 | drivers/leds/leds-fsg.c | 5070 | 5244 | /*
* LED Driver for the Freecom FSG-3
*
* Copyright (c) 2008 Rod Whitby <rod@whitby.id.au>
*
* Author: Rod Whitby <rod@whitby.id.au>
*
* Based on leds-spitz.c
* Copyright 2005-2006 Openedhand Ltd.
* Author: Richard Purdie <rpurdie@openedhand.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/leds.h>
#include <linux/module.h>
#include <mach/hardware.h>
#include <asm/io.h>
#define FSG_LED_WLAN_BIT 0
#define FSG_LED_WAN_BIT 1
#define FSG_LED_SATA_BIT 2
#define FSG_LED_USB_BIT 4
#define FSG_LED_RING_BIT 5
#define FSG_LED_SYNC_BIT 7
static short __iomem *latch_address;
static unsigned short latch_value;
static void fsg_led_wlan_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
if (value) {
latch_value &= ~(1 << FSG_LED_WLAN_BIT);
*latch_address = latch_value;
} else {
latch_value |= (1 << FSG_LED_WLAN_BIT);
*latch_address = latch_value;
}
}
static void fsg_led_wan_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
if (value) {
latch_value &= ~(1 << FSG_LED_WAN_BIT);
*latch_address = latch_value;
} else {
latch_value |= (1 << FSG_LED_WAN_BIT);
*latch_address = latch_value;
}
}
static void fsg_led_sata_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
if (value) {
latch_value &= ~(1 << FSG_LED_SATA_BIT);
*latch_address = latch_value;
} else {
latch_value |= (1 << FSG_LED_SATA_BIT);
*latch_address = latch_value;
}
}
static void fsg_led_usb_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
if (value) {
latch_value &= ~(1 << FSG_LED_USB_BIT);
*latch_address = latch_value;
} else {
latch_value |= (1 << FSG_LED_USB_BIT);
*latch_address = latch_value;
}
}
static void fsg_led_sync_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
if (value) {
latch_value &= ~(1 << FSG_LED_SYNC_BIT);
*latch_address = latch_value;
} else {
latch_value |= (1 << FSG_LED_SYNC_BIT);
*latch_address = latch_value;
}
}
static void fsg_led_ring_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
if (value) {
latch_value &= ~(1 << FSG_LED_RING_BIT);
*latch_address = latch_value;
} else {
latch_value |= (1 << FSG_LED_RING_BIT);
*latch_address = latch_value;
}
}
static struct led_classdev fsg_wlan_led = {
.name = "fsg:blue:wlan",
.brightness_set = fsg_led_wlan_set,
.flags = LED_CORE_SUSPENDRESUME,
};
static struct led_classdev fsg_wan_led = {
.name = "fsg:blue:wan",
.brightness_set = fsg_led_wan_set,
.flags = LED_CORE_SUSPENDRESUME,
};
static struct led_classdev fsg_sata_led = {
.name = "fsg:blue:sata",
.brightness_set = fsg_led_sata_set,
.flags = LED_CORE_SUSPENDRESUME,
};
static struct led_classdev fsg_usb_led = {
.name = "fsg:blue:usb",
.brightness_set = fsg_led_usb_set,
.flags = LED_CORE_SUSPENDRESUME,
};
static struct led_classdev fsg_sync_led = {
.name = "fsg:blue:sync",
.brightness_set = fsg_led_sync_set,
.flags = LED_CORE_SUSPENDRESUME,
};
static struct led_classdev fsg_ring_led = {
.name = "fsg:blue:ring",
.brightness_set = fsg_led_ring_set,
.flags = LED_CORE_SUSPENDRESUME,
};
static int fsg_led_probe(struct platform_device *pdev)
{
int ret;
/* Map the LED chip select address space */
latch_address = (unsigned short *) ioremap(IXP4XX_EXP_BUS_BASE(2), 512);
if (!latch_address) {
ret = -ENOMEM;
goto failremap;
}
latch_value = 0xffff;
*latch_address = latch_value;
ret = led_classdev_register(&pdev->dev, &fsg_wlan_led);
if (ret < 0)
goto failwlan;
ret = led_classdev_register(&pdev->dev, &fsg_wan_led);
if (ret < 0)
goto failwan;
ret = led_classdev_register(&pdev->dev, &fsg_sata_led);
if (ret < 0)
goto failsata;
ret = led_classdev_register(&pdev->dev, &fsg_usb_led);
if (ret < 0)
goto failusb;
ret = led_classdev_register(&pdev->dev, &fsg_sync_led);
if (ret < 0)
goto failsync;
ret = led_classdev_register(&pdev->dev, &fsg_ring_led);
if (ret < 0)
goto failring;
return ret;
failring:
led_classdev_unregister(&fsg_sync_led);
failsync:
led_classdev_unregister(&fsg_usb_led);
failusb:
led_classdev_unregister(&fsg_sata_led);
failsata:
led_classdev_unregister(&fsg_wan_led);
failwan:
led_classdev_unregister(&fsg_wlan_led);
failwlan:
iounmap(latch_address);
failremap:
return ret;
}
static int fsg_led_remove(struct platform_device *pdev)
{
led_classdev_unregister(&fsg_wlan_led);
led_classdev_unregister(&fsg_wan_led);
led_classdev_unregister(&fsg_sata_led);
led_classdev_unregister(&fsg_usb_led);
led_classdev_unregister(&fsg_sync_led);
led_classdev_unregister(&fsg_ring_led);
iounmap(latch_address);
return 0;
}
static struct platform_driver fsg_led_driver = {
.probe = fsg_led_probe,
.remove = fsg_led_remove,
.driver = {
.name = "fsg-led",
},
};
module_platform_driver(fsg_led_driver);
MODULE_AUTHOR("Rod Whitby <rod@whitby.id.au>");
MODULE_DESCRIPTION("Freecom FSG-3 LED driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
AlmightyMegadeth00/kernel_oneplus_msm8974 | drivers/video/pnx4008/pnxrgbfb.c | 5070 | 4462 | /*
* drivers/video/pnx4008/pnxrgbfb.c
*
* PNX4008's framebuffer support
*
* Author: Grigory Tolstolytkin <gtolstolytkin@ru.mvista.com>
* Based on Philips Semiconductors's code
*
* Copyrght (c) 2005 MontaVista Software, Inc.
* Copyright (c) 2005 Philips Semiconductors
* This file is licensed under the terms of the GNU General Public License
* version 2. This program is licensed "as is" without any warranty of any
* kind, whether express or implied.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/vmalloc.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include "sdum.h"
#include "fbcommon.h"
static u32 colreg[16];
static struct fb_var_screeninfo rgbfb_var __initdata = {
.xres = LCD_X_RES,
.yres = LCD_Y_RES,
.xres_virtual = LCD_X_RES,
.yres_virtual = LCD_Y_RES,
.bits_per_pixel = 32,
.red.offset = 16,
.red.length = 8,
.green.offset = 8,
.green.length = 8,
.blue.offset = 0,
.blue.length = 8,
.left_margin = 0,
.right_margin = 0,
.upper_margin = 0,
.lower_margin = 0,
.vmode = FB_VMODE_NONINTERLACED,
};
static struct fb_fix_screeninfo rgbfb_fix __initdata = {
.id = "RGBFB",
.line_length = LCD_X_RES * LCD_BBP,
.type = FB_TYPE_PACKED_PIXELS,
.visual = FB_VISUAL_TRUECOLOR,
.xpanstep = 0,
.ypanstep = 0,
.ywrapstep = 0,
.accel = FB_ACCEL_NONE,
};
static int channel_owned;
static int no_cursor(struct fb_info *info, struct fb_cursor *cursor)
{
return 0;
}
static int rgbfb_setcolreg(u_int regno, u_int red, u_int green, u_int blue,
u_int transp, struct fb_info *info)
{
if (regno > 15)
return 1;
colreg[regno] = ((red & 0xff00) << 8) | (green & 0xff00) |
((blue & 0xff00) >> 8);
return 0;
}
static int rgbfb_mmap(struct fb_info *info, struct vm_area_struct *vma)
{
return pnx4008_sdum_mmap(info, vma, NULL);
}
static struct fb_ops rgbfb_ops = {
.fb_mmap = rgbfb_mmap,
.fb_setcolreg = rgbfb_setcolreg,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
};
static int rgbfb_remove(struct platform_device *pdev)
{
struct fb_info *info = platform_get_drvdata(pdev);
if (info) {
unregister_framebuffer(info);
fb_dealloc_cmap(&info->cmap);
framebuffer_release(info);
platform_set_drvdata(pdev, NULL);
}
pnx4008_free_dum_channel(channel_owned, pdev->id);
pnx4008_set_dum_exit_notification(pdev->id);
return 0;
}
static int __devinit rgbfb_probe(struct platform_device *pdev)
{
struct fb_info *info;
struct dumchannel_uf chan_uf;
int ret;
char *option;
info = framebuffer_alloc(sizeof(u32) * 16, &pdev->dev);
if (!info) {
ret = -ENOMEM;
goto err;
}
pnx4008_get_fb_addresses(FB_TYPE_RGB, (void **)&info->screen_base,
(dma_addr_t *) &rgbfb_fix.smem_start,
&rgbfb_fix.smem_len);
if ((ret = pnx4008_alloc_dum_channel(pdev->id)) < 0)
goto err0;
else {
channel_owned = ret;
chan_uf.channelnr = channel_owned;
chan_uf.dirty = (u32 *) NULL;
chan_uf.source = (u32 *) rgbfb_fix.smem_start;
chan_uf.x_offset = 0;
chan_uf.y_offset = 0;
chan_uf.width = LCD_X_RES;
chan_uf.height = LCD_Y_RES;
if ((ret = pnx4008_put_dum_channel_uf(chan_uf, pdev->id))< 0)
goto err1;
if ((ret =
pnx4008_set_dum_channel_sync(channel_owned, CONF_SYNC_ON,
pdev->id)) < 0)
goto err1;
if ((ret =
pnx4008_set_dum_channel_dirty_detect(channel_owned,
CONF_DIRTYDETECTION_ON,
pdev->id)) < 0)
goto err1;
}
if (!fb_get_options("pnxrgbfb", &option) && option &&
!strcmp(option, "nocursor"))
rgbfb_ops.fb_cursor = no_cursor;
info->node = -1;
info->flags = FBINFO_FLAG_DEFAULT;
info->fbops = &rgbfb_ops;
info->fix = rgbfb_fix;
info->var = rgbfb_var;
info->screen_size = rgbfb_fix.smem_len;
info->pseudo_palette = info->par;
info->par = NULL;
ret = fb_alloc_cmap(&info->cmap, 256, 0);
if (ret < 0)
goto err1;
ret = register_framebuffer(info);
if (ret < 0)
goto err2;
platform_set_drvdata(pdev, info);
return 0;
err2:
fb_dealloc_cmap(&info->cmap);
err1:
pnx4008_free_dum_channel(channel_owned, pdev->id);
err0:
framebuffer_release(info);
err:
return ret;
}
static struct platform_driver rgbfb_driver = {
.driver = {
.name = "pnx4008-rgbfb",
},
.probe = rgbfb_probe,
.remove = rgbfb_remove,
};
module_platform_driver(rgbfb_driver);
MODULE_LICENSE("GPL");
| gpl-2.0 |
omega-roms/I9505_Omega_Kernel_LL | fs/btrfs/sysfs.c | 8142 | 1228 | /*
* Copyright (C) 2007 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License v2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/module.h>
#include <linux/kobject.h>
#include "ctree.h"
#include "disk-io.h"
#include "transaction.h"
/* /sys/fs/btrfs/ entry */
static struct kset *btrfs_kset;
int btrfs_init_sysfs(void)
{
btrfs_kset = kset_create_and_add("btrfs", NULL, fs_kobj);
if (!btrfs_kset)
return -ENOMEM;
return 0;
}
void btrfs_exit_sysfs(void)
{
kset_unregister(btrfs_kset);
}
| gpl-2.0 |
DeltaResero/GC-Wii-Linux-Kernel-3.12.y | drivers/parisc/ccio-dma.c | 8654 | 48902 | /*
** ccio-dma.c:
** DMA management routines for first generation cache-coherent machines.
** Program U2/Uturn in "Virtual Mode" and use the I/O MMU.
**
** (c) Copyright 2000 Grant Grundler
** (c) Copyright 2000 Ryan Bradetich
** (c) Copyright 2000 Hewlett-Packard Company
**
** 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.
**
**
** "Real Mode" operation refers to U2/Uturn chip operation.
** U2/Uturn were designed to perform coherency checks w/o using
** the I/O MMU - basically what x86 does.
**
** Philipp Rumpf has a "Real Mode" driver for PCX-W machines at:
** CVSROOT=:pserver:anonymous@198.186.203.37:/cvsroot/linux-parisc
** cvs -z3 co linux/arch/parisc/kernel/dma-rm.c
**
** I've rewritten his code to work under TPG's tree. See ccio-rm-dma.c.
**
** Drawbacks of using Real Mode are:
** o outbound DMA is slower - U2 won't prefetch data (GSC+ XQL signal).
** o Inbound DMA less efficient - U2 can't use DMA_FAST attribute.
** o Ability to do scatter/gather in HW is lost.
** o Doesn't work under PCX-U/U+ machines since they didn't follow
** the coherency design originally worked out. Only PCX-W does.
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/pci.h>
#include <linux/reboot.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/scatterlist.h>
#include <linux/iommu-helper.h>
#include <linux/export.h>
#include <asm/byteorder.h>
#include <asm/cache.h> /* for L1_CACHE_BYTES */
#include <asm/uaccess.h>
#include <asm/page.h>
#include <asm/dma.h>
#include <asm/io.h>
#include <asm/hardware.h> /* for register_module() */
#include <asm/parisc-device.h>
/*
** Choose "ccio" since that's what HP-UX calls it.
** Make it easier for folks to migrate from one to the other :^)
*/
#define MODULE_NAME "ccio"
#undef DEBUG_CCIO_RES
#undef DEBUG_CCIO_RUN
#undef DEBUG_CCIO_INIT
#undef DEBUG_CCIO_RUN_SG
#ifdef CONFIG_PROC_FS
/* depends on proc fs support. But costs CPU performance. */
#undef CCIO_COLLECT_STATS
#endif
#include <asm/runway.h> /* for proc_runway_root */
#ifdef DEBUG_CCIO_INIT
#define DBG_INIT(x...) printk(x)
#else
#define DBG_INIT(x...)
#endif
#ifdef DEBUG_CCIO_RUN
#define DBG_RUN(x...) printk(x)
#else
#define DBG_RUN(x...)
#endif
#ifdef DEBUG_CCIO_RES
#define DBG_RES(x...) printk(x)
#else
#define DBG_RES(x...)
#endif
#ifdef DEBUG_CCIO_RUN_SG
#define DBG_RUN_SG(x...) printk(x)
#else
#define DBG_RUN_SG(x...)
#endif
#define CCIO_INLINE inline
#define WRITE_U32(value, addr) __raw_writel(value, addr)
#define READ_U32(addr) __raw_readl(addr)
#define U2_IOA_RUNWAY 0x580
#define U2_BC_GSC 0x501
#define UTURN_IOA_RUNWAY 0x581
#define UTURN_BC_GSC 0x502
#define IOA_NORMAL_MODE 0x00020080 /* IO_CONTROL to turn on CCIO */
#define CMD_TLB_DIRECT_WRITE 35 /* IO_COMMAND for I/O TLB Writes */
#define CMD_TLB_PURGE 33 /* IO_COMMAND to Purge I/O TLB entry */
struct ioa_registers {
/* Runway Supervisory Set */
int32_t unused1[12];
uint32_t io_command; /* Offset 12 */
uint32_t io_status; /* Offset 13 */
uint32_t io_control; /* Offset 14 */
int32_t unused2[1];
/* Runway Auxiliary Register Set */
uint32_t io_err_resp; /* Offset 0 */
uint32_t io_err_info; /* Offset 1 */
uint32_t io_err_req; /* Offset 2 */
uint32_t io_err_resp_hi; /* Offset 3 */
uint32_t io_tlb_entry_m; /* Offset 4 */
uint32_t io_tlb_entry_l; /* Offset 5 */
uint32_t unused3[1];
uint32_t io_pdir_base; /* Offset 7 */
uint32_t io_io_low_hv; /* Offset 8 */
uint32_t io_io_high_hv; /* Offset 9 */
uint32_t unused4[1];
uint32_t io_chain_id_mask; /* Offset 11 */
uint32_t unused5[2];
uint32_t io_io_low; /* Offset 14 */
uint32_t io_io_high; /* Offset 15 */
};
/*
** IOA Registers
** -------------
**
** Runway IO_CONTROL Register (+0x38)
**
** The Runway IO_CONTROL register controls the forwarding of transactions.
**
** | 0 ... 13 | 14 15 | 16 ... 21 | 22 | 23 24 | 25 ... 31 |
** | HV | TLB | reserved | HV | mode | reserved |
**
** o mode field indicates the address translation of transactions
** forwarded from Runway to GSC+:
** Mode Name Value Definition
** Off (default) 0 Opaque to matching addresses.
** Include 1 Transparent for matching addresses.
** Peek 3 Map matching addresses.
**
** + "Off" mode: Runway transactions which match the I/O range
** specified by the IO_IO_LOW/IO_IO_HIGH registers will be ignored.
** + "Include" mode: all addresses within the I/O range specified
** by the IO_IO_LOW and IO_IO_HIGH registers are transparently
** forwarded. This is the I/O Adapter's normal operating mode.
** + "Peek" mode: used during system configuration to initialize the
** GSC+ bus. Runway Write_Shorts in the address range specified by
** IO_IO_LOW and IO_IO_HIGH are forwarded through the I/O Adapter
** *AND* the GSC+ address is remapped to the Broadcast Physical
** Address space by setting the 14 high order address bits of the
** 32 bit GSC+ address to ones.
**
** o TLB field affects transactions which are forwarded from GSC+ to Runway.
** "Real" mode is the poweron default.
**
** TLB Mode Value Description
** Real 0 No TLB translation. Address is directly mapped and the
** virtual address is composed of selected physical bits.
** Error 1 Software fills the TLB manually.
** Normal 2 IOA fetches IO TLB misses from IO PDIR (in host memory).
**
**
** IO_IO_LOW_HV +0x60 (HV dependent)
** IO_IO_HIGH_HV +0x64 (HV dependent)
** IO_IO_LOW +0x78 (Architected register)
** IO_IO_HIGH +0x7c (Architected register)
**
** IO_IO_LOW and IO_IO_HIGH set the lower and upper bounds of the
** I/O Adapter address space, respectively.
**
** 0 ... 7 | 8 ... 15 | 16 ... 31 |
** 11111111 | 11111111 | address |
**
** Each LOW/HIGH pair describes a disjoint address space region.
** (2 per GSC+ port). Each incoming Runway transaction address is compared
** with both sets of LOW/HIGH registers. If the address is in the range
** greater than or equal to IO_IO_LOW and less than IO_IO_HIGH the transaction
** for forwarded to the respective GSC+ bus.
** Specify IO_IO_LOW equal to or greater than IO_IO_HIGH to avoid specifying
** an address space region.
**
** In order for a Runway address to reside within GSC+ extended address space:
** Runway Address [0:7] must identically compare to 8'b11111111
** Runway Address [8:11] must be equal to IO_IO_LOW(_HV)[16:19]
** Runway Address [12:23] must be greater than or equal to
** IO_IO_LOW(_HV)[20:31] and less than IO_IO_HIGH(_HV)[20:31].
** Runway Address [24:39] is not used in the comparison.
**
** When the Runway transaction is forwarded to GSC+, the GSC+ address is
** as follows:
** GSC+ Address[0:3] 4'b1111
** GSC+ Address[4:29] Runway Address[12:37]
** GSC+ Address[30:31] 2'b00
**
** All 4 Low/High registers must be initialized (by PDC) once the lower bus
** is interrogated and address space is defined. The operating system will
** modify the architectural IO_IO_LOW and IO_IO_HIGH registers following
** the PDC initialization. However, the hardware version dependent IO_IO_LOW
** and IO_IO_HIGH registers should not be subsequently altered by the OS.
**
** Writes to both sets of registers will take effect immediately, bypassing
** the queues, which ensures that subsequent Runway transactions are checked
** against the updated bounds values. However reads are queued, introducing
** the possibility of a read being bypassed by a subsequent write to the same
** register. This sequence can be avoided by having software wait for read
** returns before issuing subsequent writes.
*/
struct ioc {
struct ioa_registers __iomem *ioc_regs; /* I/O MMU base address */
u8 *res_map; /* resource map, bit == pdir entry */
u64 *pdir_base; /* physical base address */
u32 pdir_size; /* bytes, function of IOV Space size */
u32 res_hint; /* next available IOVP -
circular search */
u32 res_size; /* size of resource map in bytes */
spinlock_t res_lock;
#ifdef CCIO_COLLECT_STATS
#define CCIO_SEARCH_SAMPLE 0x100
unsigned long avg_search[CCIO_SEARCH_SAMPLE];
unsigned long avg_idx; /* current index into avg_search */
unsigned long used_pages;
unsigned long msingle_calls;
unsigned long msingle_pages;
unsigned long msg_calls;
unsigned long msg_pages;
unsigned long usingle_calls;
unsigned long usingle_pages;
unsigned long usg_calls;
unsigned long usg_pages;
#endif
unsigned short cujo20_bug;
/* STUFF We don't need in performance path */
u32 chainid_shift; /* specify bit location of chain_id */
struct ioc *next; /* Linked list of discovered iocs */
const char *name; /* device name from firmware */
unsigned int hw_path; /* the hardware path this ioc is associatd with */
struct pci_dev *fake_pci_dev; /* the fake pci_dev for non-pci devs */
struct resource mmio_region[2]; /* The "routed" MMIO regions */
};
static struct ioc *ioc_list;
static int ioc_count;
/**************************************************************
*
* I/O Pdir Resource Management
*
* Bits set in the resource map are in use.
* Each bit can represent a number of pages.
* LSbs represent lower addresses (IOVA's).
*
* This was was copied from sba_iommu.c. Don't try to unify
* the two resource managers unless a way to have different
* allocation policies is also adjusted. We'd like to avoid
* I/O TLB thrashing by having resource allocation policy
* match the I/O TLB replacement policy.
*
***************************************************************/
#define IOVP_SIZE PAGE_SIZE
#define IOVP_SHIFT PAGE_SHIFT
#define IOVP_MASK PAGE_MASK
/* Convert from IOVP to IOVA and vice versa. */
#define CCIO_IOVA(iovp,offset) ((iovp) | (offset))
#define CCIO_IOVP(iova) ((iova) & IOVP_MASK)
#define PDIR_INDEX(iovp) ((iovp)>>IOVP_SHIFT)
#define MKIOVP(pdir_idx) ((long)(pdir_idx) << IOVP_SHIFT)
#define MKIOVA(iovp,offset) (dma_addr_t)((long)iovp | (long)offset)
/*
** Don't worry about the 150% average search length on a miss.
** If the search wraps around, and passes the res_hint, it will
** cause the kernel to panic anyhow.
*/
#define CCIO_SEARCH_LOOP(ioc, res_idx, mask, size) \
for(; res_ptr < res_end; ++res_ptr) { \
int ret;\
unsigned int idx;\
idx = (unsigned int)((unsigned long)res_ptr - (unsigned long)ioc->res_map); \
ret = iommu_is_span_boundary(idx << 3, pages_needed, 0, boundary_size);\
if ((0 == (*res_ptr & mask)) && !ret) { \
*res_ptr |= mask; \
res_idx = idx;\
ioc->res_hint = res_idx + (size >> 3); \
goto resource_found; \
} \
}
#define CCIO_FIND_FREE_MAPPING(ioa, res_idx, mask, size) \
u##size *res_ptr = (u##size *)&((ioc)->res_map[ioa->res_hint & ~((size >> 3) - 1)]); \
u##size *res_end = (u##size *)&(ioc)->res_map[ioa->res_size]; \
CCIO_SEARCH_LOOP(ioc, res_idx, mask, size); \
res_ptr = (u##size *)&(ioc)->res_map[0]; \
CCIO_SEARCH_LOOP(ioa, res_idx, mask, size);
/*
** Find available bit in this ioa's resource map.
** Use a "circular" search:
** o Most IOVA's are "temporary" - avg search time should be small.
** o keep a history of what happened for debugging
** o KISS.
**
** Perf optimizations:
** o search for log2(size) bits at a time.
** o search for available resource bits using byte/word/whatever.
** o use different search for "large" (eg > 4 pages) or "very large"
** (eg > 16 pages) mappings.
*/
/**
* ccio_alloc_range - Allocate pages in the ioc's resource map.
* @ioc: The I/O Controller.
* @pages_needed: The requested number of pages to be mapped into the
* I/O Pdir...
*
* This function searches the resource map of the ioc to locate a range
* of available pages for the requested size.
*/
static int
ccio_alloc_range(struct ioc *ioc, struct device *dev, size_t size)
{
unsigned int pages_needed = size >> IOVP_SHIFT;
unsigned int res_idx;
unsigned long boundary_size;
#ifdef CCIO_COLLECT_STATS
unsigned long cr_start = mfctl(16);
#endif
BUG_ON(pages_needed == 0);
BUG_ON((pages_needed * IOVP_SIZE) > DMA_CHUNK_SIZE);
DBG_RES("%s() size: %d pages_needed %d\n",
__func__, size, pages_needed);
/*
** "seek and ye shall find"...praying never hurts either...
** ggg sacrifices another 710 to the computer gods.
*/
boundary_size = ALIGN((unsigned long long)dma_get_seg_boundary(dev) + 1,
1ULL << IOVP_SHIFT) >> IOVP_SHIFT;
if (pages_needed <= 8) {
/*
* LAN traffic will not thrash the TLB IFF the same NIC
* uses 8 adjacent pages to map separate payload data.
* ie the same byte in the resource bit map.
*/
#if 0
/* FIXME: bit search should shift it's way through
* an unsigned long - not byte at a time. As it is now,
* we effectively allocate this byte to this mapping.
*/
unsigned long mask = ~(~0UL >> pages_needed);
CCIO_FIND_FREE_MAPPING(ioc, res_idx, mask, 8);
#else
CCIO_FIND_FREE_MAPPING(ioc, res_idx, 0xff, 8);
#endif
} else if (pages_needed <= 16) {
CCIO_FIND_FREE_MAPPING(ioc, res_idx, 0xffff, 16);
} else if (pages_needed <= 32) {
CCIO_FIND_FREE_MAPPING(ioc, res_idx, ~(unsigned int)0, 32);
#ifdef __LP64__
} else if (pages_needed <= 64) {
CCIO_FIND_FREE_MAPPING(ioc, res_idx, ~0UL, 64);
#endif
} else {
panic("%s: %s() Too many pages to map. pages_needed: %u\n",
__FILE__, __func__, pages_needed);
}
panic("%s: %s() I/O MMU is out of mapping resources.\n", __FILE__,
__func__);
resource_found:
DBG_RES("%s() res_idx %d res_hint: %d\n",
__func__, res_idx, ioc->res_hint);
#ifdef CCIO_COLLECT_STATS
{
unsigned long cr_end = mfctl(16);
unsigned long tmp = cr_end - cr_start;
/* check for roll over */
cr_start = (cr_end < cr_start) ? -(tmp) : (tmp);
}
ioc->avg_search[ioc->avg_idx++] = cr_start;
ioc->avg_idx &= CCIO_SEARCH_SAMPLE - 1;
ioc->used_pages += pages_needed;
#endif
/*
** return the bit address.
*/
return res_idx << 3;
}
#define CCIO_FREE_MAPPINGS(ioc, res_idx, mask, size) \
u##size *res_ptr = (u##size *)&((ioc)->res_map[res_idx]); \
BUG_ON((*res_ptr & mask) != mask); \
*res_ptr &= ~(mask);
/**
* ccio_free_range - Free pages from the ioc's resource map.
* @ioc: The I/O Controller.
* @iova: The I/O Virtual Address.
* @pages_mapped: The requested number of pages to be freed from the
* I/O Pdir.
*
* This function frees the resouces allocated for the iova.
*/
static void
ccio_free_range(struct ioc *ioc, dma_addr_t iova, unsigned long pages_mapped)
{
unsigned long iovp = CCIO_IOVP(iova);
unsigned int res_idx = PDIR_INDEX(iovp) >> 3;
BUG_ON(pages_mapped == 0);
BUG_ON((pages_mapped * IOVP_SIZE) > DMA_CHUNK_SIZE);
BUG_ON(pages_mapped > BITS_PER_LONG);
DBG_RES("%s(): res_idx: %d pages_mapped %d\n",
__func__, res_idx, pages_mapped);
#ifdef CCIO_COLLECT_STATS
ioc->used_pages -= pages_mapped;
#endif
if(pages_mapped <= 8) {
#if 0
/* see matching comments in alloc_range */
unsigned long mask = ~(~0UL >> pages_mapped);
CCIO_FREE_MAPPINGS(ioc, res_idx, mask, 8);
#else
CCIO_FREE_MAPPINGS(ioc, res_idx, 0xffUL, 8);
#endif
} else if(pages_mapped <= 16) {
CCIO_FREE_MAPPINGS(ioc, res_idx, 0xffffUL, 16);
} else if(pages_mapped <= 32) {
CCIO_FREE_MAPPINGS(ioc, res_idx, ~(unsigned int)0, 32);
#ifdef __LP64__
} else if(pages_mapped <= 64) {
CCIO_FREE_MAPPINGS(ioc, res_idx, ~0UL, 64);
#endif
} else {
panic("%s:%s() Too many pages to unmap.\n", __FILE__,
__func__);
}
}
/****************************************************************
**
** CCIO dma_ops support routines
**
*****************************************************************/
typedef unsigned long space_t;
#define KERNEL_SPACE 0
/*
** DMA "Page Type" and Hints
** o if SAFE_DMA isn't set, mapping is for FAST_DMA. SAFE_DMA should be
** set for subcacheline DMA transfers since we don't want to damage the
** other part of a cacheline.
** o SAFE_DMA must be set for "memory" allocated via pci_alloc_consistent().
** This bit tells U2 to do R/M/W for partial cachelines. "Streaming"
** data can avoid this if the mapping covers full cache lines.
** o STOP_MOST is needed for atomicity across cachelines.
** Apparently only "some EISA devices" need this.
** Using CONFIG_ISA is hack. Only the IOA with EISA under it needs
** to use this hint iff the EISA devices needs this feature.
** According to the U2 ERS, STOP_MOST enabled pages hurt performance.
** o PREFETCH should *not* be set for cases like Multiple PCI devices
** behind GSCtoPCI (dino) bus converter. Only one cacheline per GSC
** device can be fetched and multiply DMA streams will thrash the
** prefetch buffer and burn memory bandwidth. See 6.7.3 "Prefetch Rules
** and Invalidation of Prefetch Entries".
**
** FIXME: the default hints need to be per GSC device - not global.
**
** HP-UX dorks: linux device driver programming model is totally different
** than HP-UX's. HP-UX always sets HINT_PREFETCH since it's drivers
** do special things to work on non-coherent platforms...linux has to
** be much more careful with this.
*/
#define IOPDIR_VALID 0x01UL
#define HINT_SAFE_DMA 0x02UL /* used for pci_alloc_consistent() pages */
#ifdef CONFIG_EISA
#define HINT_STOP_MOST 0x04UL /* LSL support */
#else
#define HINT_STOP_MOST 0x00UL /* only needed for "some EISA devices" */
#endif
#define HINT_UDPATE_ENB 0x08UL /* not used/supported by U2 */
#define HINT_PREFETCH 0x10UL /* for outbound pages which are not SAFE */
/*
** Use direction (ie PCI_DMA_TODEVICE) to pick hint.
** ccio_alloc_consistent() depends on this to get SAFE_DMA
** when it passes in BIDIRECTIONAL flag.
*/
static u32 hint_lookup[] = {
[PCI_DMA_BIDIRECTIONAL] = HINT_STOP_MOST | HINT_SAFE_DMA | IOPDIR_VALID,
[PCI_DMA_TODEVICE] = HINT_STOP_MOST | HINT_PREFETCH | IOPDIR_VALID,
[PCI_DMA_FROMDEVICE] = HINT_STOP_MOST | IOPDIR_VALID,
};
/**
* ccio_io_pdir_entry - Initialize an I/O Pdir.
* @pdir_ptr: A pointer into I/O Pdir.
* @sid: The Space Identifier.
* @vba: The virtual address.
* @hints: The DMA Hint.
*
* Given a virtual address (vba, arg2) and space id, (sid, arg1),
* load the I/O PDIR entry pointed to by pdir_ptr (arg0). Each IO Pdir
* entry consists of 8 bytes as shown below (MSB == bit 0):
*
*
* WORD 0:
* +------+----------------+-----------------------------------------------+
* | Phys | Virtual Index | Phys |
* | 0:3 | 0:11 | 4:19 |
* |4 bits| 12 bits | 16 bits |
* +------+----------------+-----------------------------------------------+
* WORD 1:
* +-----------------------+-----------------------------------------------+
* | Phys | Rsvd | Prefetch |Update |Rsvd |Lock |Safe |Valid |
* | 20:39 | | Enable |Enable | |Enable|DMA | |
* | 20 bits | 5 bits | 1 bit |1 bit |2 bits|1 bit |1 bit |1 bit |
* +-----------------------+-----------------------------------------------+
*
* The virtual index field is filled with the results of the LCI
* (Load Coherence Index) instruction. The 8 bits used for the virtual
* index are bits 12:19 of the value returned by LCI.
*/
static void CCIO_INLINE
ccio_io_pdir_entry(u64 *pdir_ptr, space_t sid, unsigned long vba,
unsigned long hints)
{
register unsigned long pa;
register unsigned long ci; /* coherent index */
/* We currently only support kernel addresses */
BUG_ON(sid != KERNEL_SPACE);
mtsp(sid,1);
/*
** WORD 1 - low order word
** "hints" parm includes the VALID bit!
** "dep" clobbers the physical address offset bits as well.
*/
pa = virt_to_phys(vba);
asm volatile("depw %1,31,12,%0" : "+r" (pa) : "r" (hints));
((u32 *)pdir_ptr)[1] = (u32) pa;
/*
** WORD 0 - high order word
*/
#ifdef __LP64__
/*
** get bits 12:15 of physical address
** shift bits 16:31 of physical address
** and deposit them
*/
asm volatile ("extrd,u %1,15,4,%0" : "=r" (ci) : "r" (pa));
asm volatile ("extrd,u %1,31,16,%0" : "+r" (pa) : "r" (pa));
asm volatile ("depd %1,35,4,%0" : "+r" (pa) : "r" (ci));
#else
pa = 0;
#endif
/*
** get CPU coherency index bits
** Grab virtual index [0:11]
** Deposit virt_idx bits into I/O PDIR word
*/
asm volatile ("lci %%r0(%%sr1, %1), %0" : "=r" (ci) : "r" (vba));
asm volatile ("extru %1,19,12,%0" : "+r" (ci) : "r" (ci));
asm volatile ("depw %1,15,12,%0" : "+r" (pa) : "r" (ci));
((u32 *)pdir_ptr)[0] = (u32) pa;
/* FIXME: PCX_W platforms don't need FDC/SYNC. (eg C360)
** PCX-U/U+ do. (eg C200/C240)
** PCX-T'? Don't know. (eg C110 or similar K-class)
**
** See PDC_MODEL/option 0/SW_CAP word for "Non-coherent IO-PDIR bit".
** Hopefully we can patch (NOP) these out at boot time somehow.
**
** "Since PCX-U employs an offset hash that is incompatible with
** the real mode coherence index generation of U2, the PDIR entry
** must be flushed to memory to retain coherence."
*/
asm volatile("fdc %%r0(%0)" : : "r" (pdir_ptr));
asm volatile("sync");
}
/**
* ccio_clear_io_tlb - Remove stale entries from the I/O TLB.
* @ioc: The I/O Controller.
* @iovp: The I/O Virtual Page.
* @byte_cnt: The requested number of bytes to be freed from the I/O Pdir.
*
* Purge invalid I/O PDIR entries from the I/O TLB.
*
* FIXME: Can we change the byte_cnt to pages_mapped?
*/
static CCIO_INLINE void
ccio_clear_io_tlb(struct ioc *ioc, dma_addr_t iovp, size_t byte_cnt)
{
u32 chain_size = 1 << ioc->chainid_shift;
iovp &= IOVP_MASK; /* clear offset bits, just want pagenum */
byte_cnt += chain_size;
while(byte_cnt > chain_size) {
WRITE_U32(CMD_TLB_PURGE | iovp, &ioc->ioc_regs->io_command);
iovp += chain_size;
byte_cnt -= chain_size;
}
}
/**
* ccio_mark_invalid - Mark the I/O Pdir entries invalid.
* @ioc: The I/O Controller.
* @iova: The I/O Virtual Address.
* @byte_cnt: The requested number of bytes to be freed from the I/O Pdir.
*
* Mark the I/O Pdir entries invalid and blow away the corresponding I/O
* TLB entries.
*
* FIXME: at some threshold it might be "cheaper" to just blow
* away the entire I/O TLB instead of individual entries.
*
* FIXME: Uturn has 256 TLB entries. We don't need to purge every
* PDIR entry - just once for each possible TLB entry.
* (We do need to maker I/O PDIR entries invalid regardless).
*
* FIXME: Can we change byte_cnt to pages_mapped?
*/
static CCIO_INLINE void
ccio_mark_invalid(struct ioc *ioc, dma_addr_t iova, size_t byte_cnt)
{
u32 iovp = (u32)CCIO_IOVP(iova);
size_t saved_byte_cnt;
/* round up to nearest page size */
saved_byte_cnt = byte_cnt = ALIGN(byte_cnt, IOVP_SIZE);
while(byte_cnt > 0) {
/* invalidate one page at a time */
unsigned int idx = PDIR_INDEX(iovp);
char *pdir_ptr = (char *) &(ioc->pdir_base[idx]);
BUG_ON(idx >= (ioc->pdir_size / sizeof(u64)));
pdir_ptr[7] = 0; /* clear only VALID bit */
/*
** FIXME: PCX_W platforms don't need FDC/SYNC. (eg C360)
** PCX-U/U+ do. (eg C200/C240)
** See PDC_MODEL/option 0/SW_CAP for "Non-coherent IO-PDIR bit".
**
** Hopefully someone figures out how to patch (NOP) the
** FDC/SYNC out at boot time.
*/
asm volatile("fdc %%r0(%0)" : : "r" (pdir_ptr[7]));
iovp += IOVP_SIZE;
byte_cnt -= IOVP_SIZE;
}
asm volatile("sync");
ccio_clear_io_tlb(ioc, CCIO_IOVP(iova), saved_byte_cnt);
}
/****************************************************************
**
** CCIO dma_ops
**
*****************************************************************/
/**
* ccio_dma_supported - Verify the IOMMU supports the DMA address range.
* @dev: The PCI device.
* @mask: A bit mask describing the DMA address range of the device.
*
* This function implements the pci_dma_supported function.
*/
static int
ccio_dma_supported(struct device *dev, u64 mask)
{
if(dev == NULL) {
printk(KERN_ERR MODULE_NAME ": EISA/ISA/et al not supported\n");
BUG();
return 0;
}
/* only support 32-bit devices (ie PCI/GSC) */
return (int)(mask == 0xffffffffUL);
}
/**
* ccio_map_single - Map an address range into the IOMMU.
* @dev: The PCI device.
* @addr: The start address of the DMA region.
* @size: The length of the DMA region.
* @direction: The direction of the DMA transaction (to/from device).
*
* This function implements the pci_map_single function.
*/
static dma_addr_t
ccio_map_single(struct device *dev, void *addr, size_t size,
enum dma_data_direction direction)
{
int idx;
struct ioc *ioc;
unsigned long flags;
dma_addr_t iovp;
dma_addr_t offset;
u64 *pdir_start;
unsigned long hint = hint_lookup[(int)direction];
BUG_ON(!dev);
ioc = GET_IOC(dev);
BUG_ON(size <= 0);
/* save offset bits */
offset = ((unsigned long) addr) & ~IOVP_MASK;
/* round up to nearest IOVP_SIZE */
size = ALIGN(size + offset, IOVP_SIZE);
spin_lock_irqsave(&ioc->res_lock, flags);
#ifdef CCIO_COLLECT_STATS
ioc->msingle_calls++;
ioc->msingle_pages += size >> IOVP_SHIFT;
#endif
idx = ccio_alloc_range(ioc, dev, size);
iovp = (dma_addr_t)MKIOVP(idx);
pdir_start = &(ioc->pdir_base[idx]);
DBG_RUN("%s() 0x%p -> 0x%lx size: %0x%x\n",
__func__, addr, (long)iovp | offset, size);
/* If not cacheline aligned, force SAFE_DMA on the whole mess */
if((size % L1_CACHE_BYTES) || ((unsigned long)addr % L1_CACHE_BYTES))
hint |= HINT_SAFE_DMA;
while(size > 0) {
ccio_io_pdir_entry(pdir_start, KERNEL_SPACE, (unsigned long)addr, hint);
DBG_RUN(" pdir %p %08x%08x\n",
pdir_start,
(u32) (((u32 *) pdir_start)[0]),
(u32) (((u32 *) pdir_start)[1]));
++pdir_start;
addr += IOVP_SIZE;
size -= IOVP_SIZE;
}
spin_unlock_irqrestore(&ioc->res_lock, flags);
/* form complete address */
return CCIO_IOVA(iovp, offset);
}
/**
* ccio_unmap_single - Unmap an address range from the IOMMU.
* @dev: The PCI device.
* @addr: The start address of the DMA region.
* @size: The length of the DMA region.
* @direction: The direction of the DMA transaction (to/from device).
*
* This function implements the pci_unmap_single function.
*/
static void
ccio_unmap_single(struct device *dev, dma_addr_t iova, size_t size,
enum dma_data_direction direction)
{
struct ioc *ioc;
unsigned long flags;
dma_addr_t offset = iova & ~IOVP_MASK;
BUG_ON(!dev);
ioc = GET_IOC(dev);
DBG_RUN("%s() iovp 0x%lx/%x\n",
__func__, (long)iova, size);
iova ^= offset; /* clear offset bits */
size += offset;
size = ALIGN(size, IOVP_SIZE);
spin_lock_irqsave(&ioc->res_lock, flags);
#ifdef CCIO_COLLECT_STATS
ioc->usingle_calls++;
ioc->usingle_pages += size >> IOVP_SHIFT;
#endif
ccio_mark_invalid(ioc, iova, size);
ccio_free_range(ioc, iova, (size >> IOVP_SHIFT));
spin_unlock_irqrestore(&ioc->res_lock, flags);
}
/**
* ccio_alloc_consistent - Allocate a consistent DMA mapping.
* @dev: The PCI device.
* @size: The length of the DMA region.
* @dma_handle: The DMA address handed back to the device (not the cpu).
*
* This function implements the pci_alloc_consistent function.
*/
static void *
ccio_alloc_consistent(struct device *dev, size_t size, dma_addr_t *dma_handle, gfp_t flag)
{
void *ret;
#if 0
/* GRANT Need to establish hierarchy for non-PCI devs as well
** and then provide matching gsc_map_xxx() functions for them as well.
*/
if(!hwdev) {
/* only support PCI */
*dma_handle = 0;
return 0;
}
#endif
ret = (void *) __get_free_pages(flag, get_order(size));
if (ret) {
memset(ret, 0, size);
*dma_handle = ccio_map_single(dev, ret, size, PCI_DMA_BIDIRECTIONAL);
}
return ret;
}
/**
* ccio_free_consistent - Free a consistent DMA mapping.
* @dev: The PCI device.
* @size: The length of the DMA region.
* @cpu_addr: The cpu address returned from the ccio_alloc_consistent.
* @dma_handle: The device address returned from the ccio_alloc_consistent.
*
* This function implements the pci_free_consistent function.
*/
static void
ccio_free_consistent(struct device *dev, size_t size, void *cpu_addr,
dma_addr_t dma_handle)
{
ccio_unmap_single(dev, dma_handle, size, 0);
free_pages((unsigned long)cpu_addr, get_order(size));
}
/*
** Since 0 is a valid pdir_base index value, can't use that
** to determine if a value is valid or not. Use a flag to indicate
** the SG list entry contains a valid pdir index.
*/
#define PIDE_FLAG 0x80000000UL
#ifdef CCIO_COLLECT_STATS
#define IOMMU_MAP_STATS
#endif
#include "iommu-helpers.h"
/**
* ccio_map_sg - Map the scatter/gather list into the IOMMU.
* @dev: The PCI device.
* @sglist: The scatter/gather list to be mapped in the IOMMU.
* @nents: The number of entries in the scatter/gather list.
* @direction: The direction of the DMA transaction (to/from device).
*
* This function implements the pci_map_sg function.
*/
static int
ccio_map_sg(struct device *dev, struct scatterlist *sglist, int nents,
enum dma_data_direction direction)
{
struct ioc *ioc;
int coalesced, filled = 0;
unsigned long flags;
unsigned long hint = hint_lookup[(int)direction];
unsigned long prev_len = 0, current_len = 0;
int i;
BUG_ON(!dev);
ioc = GET_IOC(dev);
DBG_RUN_SG("%s() START %d entries\n", __func__, nents);
/* Fast path single entry scatterlists. */
if (nents == 1) {
sg_dma_address(sglist) = ccio_map_single(dev,
(void *)sg_virt_addr(sglist), sglist->length,
direction);
sg_dma_len(sglist) = sglist->length;
return 1;
}
for(i = 0; i < nents; i++)
prev_len += sglist[i].length;
spin_lock_irqsave(&ioc->res_lock, flags);
#ifdef CCIO_COLLECT_STATS
ioc->msg_calls++;
#endif
/*
** First coalesce the chunks and allocate I/O pdir space
**
** If this is one DMA stream, we can properly map using the
** correct virtual address associated with each DMA page.
** w/o this association, we wouldn't have coherent DMA!
** Access to the virtual address is what forces a two pass algorithm.
*/
coalesced = iommu_coalesce_chunks(ioc, dev, sglist, nents, ccio_alloc_range);
/*
** Program the I/O Pdir
**
** map the virtual addresses to the I/O Pdir
** o dma_address will contain the pdir index
** o dma_len will contain the number of bytes to map
** o page/offset contain the virtual address.
*/
filled = iommu_fill_pdir(ioc, sglist, nents, hint, ccio_io_pdir_entry);
spin_unlock_irqrestore(&ioc->res_lock, flags);
BUG_ON(coalesced != filled);
DBG_RUN_SG("%s() DONE %d mappings\n", __func__, filled);
for (i = 0; i < filled; i++)
current_len += sg_dma_len(sglist + i);
BUG_ON(current_len != prev_len);
return filled;
}
/**
* ccio_unmap_sg - Unmap the scatter/gather list from the IOMMU.
* @dev: The PCI device.
* @sglist: The scatter/gather list to be unmapped from the IOMMU.
* @nents: The number of entries in the scatter/gather list.
* @direction: The direction of the DMA transaction (to/from device).
*
* This function implements the pci_unmap_sg function.
*/
static void
ccio_unmap_sg(struct device *dev, struct scatterlist *sglist, int nents,
enum dma_data_direction direction)
{
struct ioc *ioc;
BUG_ON(!dev);
ioc = GET_IOC(dev);
DBG_RUN_SG("%s() START %d entries, %08lx,%x\n",
__func__, nents, sg_virt_addr(sglist), sglist->length);
#ifdef CCIO_COLLECT_STATS
ioc->usg_calls++;
#endif
while(sg_dma_len(sglist) && nents--) {
#ifdef CCIO_COLLECT_STATS
ioc->usg_pages += sg_dma_len(sglist) >> PAGE_SHIFT;
#endif
ccio_unmap_single(dev, sg_dma_address(sglist),
sg_dma_len(sglist), direction);
++sglist;
}
DBG_RUN_SG("%s() DONE (nents %d)\n", __func__, nents);
}
static struct hppa_dma_ops ccio_ops = {
.dma_supported = ccio_dma_supported,
.alloc_consistent = ccio_alloc_consistent,
.alloc_noncoherent = ccio_alloc_consistent,
.free_consistent = ccio_free_consistent,
.map_single = ccio_map_single,
.unmap_single = ccio_unmap_single,
.map_sg = ccio_map_sg,
.unmap_sg = ccio_unmap_sg,
.dma_sync_single_for_cpu = NULL, /* NOP for U2/Uturn */
.dma_sync_single_for_device = NULL, /* NOP for U2/Uturn */
.dma_sync_sg_for_cpu = NULL, /* ditto */
.dma_sync_sg_for_device = NULL, /* ditto */
};
#ifdef CONFIG_PROC_FS
static int ccio_proc_info(struct seq_file *m, void *p)
{
int len = 0;
struct ioc *ioc = ioc_list;
while (ioc != NULL) {
unsigned int total_pages = ioc->res_size << 3;
#ifdef CCIO_COLLECT_STATS
unsigned long avg = 0, min, max;
int j;
#endif
len += seq_printf(m, "%s\n", ioc->name);
len += seq_printf(m, "Cujo 2.0 bug : %s\n",
(ioc->cujo20_bug ? "yes" : "no"));
len += seq_printf(m, "IO PDIR size : %d bytes (%d entries)\n",
total_pages * 8, total_pages);
#ifdef CCIO_COLLECT_STATS
len += seq_printf(m, "IO PDIR entries : %ld free %ld used (%d%%)\n",
total_pages - ioc->used_pages, ioc->used_pages,
(int)(ioc->used_pages * 100 / total_pages));
#endif
len += seq_printf(m, "Resource bitmap : %d bytes (%d pages)\n",
ioc->res_size, total_pages);
#ifdef CCIO_COLLECT_STATS
min = max = ioc->avg_search[0];
for(j = 0; j < CCIO_SEARCH_SAMPLE; ++j) {
avg += ioc->avg_search[j];
if(ioc->avg_search[j] > max)
max = ioc->avg_search[j];
if(ioc->avg_search[j] < min)
min = ioc->avg_search[j];
}
avg /= CCIO_SEARCH_SAMPLE;
len += seq_printf(m, " Bitmap search : %ld/%ld/%ld (min/avg/max CPU Cycles)\n",
min, avg, max);
len += seq_printf(m, "pci_map_single(): %8ld calls %8ld pages (avg %d/1000)\n",
ioc->msingle_calls, ioc->msingle_pages,
(int)((ioc->msingle_pages * 1000)/ioc->msingle_calls));
/* KLUGE - unmap_sg calls unmap_single for each mapped page */
min = ioc->usingle_calls - ioc->usg_calls;
max = ioc->usingle_pages - ioc->usg_pages;
len += seq_printf(m, "pci_unmap_single: %8ld calls %8ld pages (avg %d/1000)\n",
min, max, (int)((max * 1000)/min));
len += seq_printf(m, "pci_map_sg() : %8ld calls %8ld pages (avg %d/1000)\n",
ioc->msg_calls, ioc->msg_pages,
(int)((ioc->msg_pages * 1000)/ioc->msg_calls));
len += seq_printf(m, "pci_unmap_sg() : %8ld calls %8ld pages (avg %d/1000)\n\n\n",
ioc->usg_calls, ioc->usg_pages,
(int)((ioc->usg_pages * 1000)/ioc->usg_calls));
#endif /* CCIO_COLLECT_STATS */
ioc = ioc->next;
}
return 0;
}
static int ccio_proc_info_open(struct inode *inode, struct file *file)
{
return single_open(file, &ccio_proc_info, NULL);
}
static const struct file_operations ccio_proc_info_fops = {
.owner = THIS_MODULE,
.open = ccio_proc_info_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int ccio_proc_bitmap_info(struct seq_file *m, void *p)
{
int len = 0;
struct ioc *ioc = ioc_list;
while (ioc != NULL) {
u32 *res_ptr = (u32 *)ioc->res_map;
int j;
for (j = 0; j < (ioc->res_size / sizeof(u32)); j++) {
if ((j & 7) == 0)
len += seq_puts(m, "\n ");
len += seq_printf(m, "%08x", *res_ptr);
res_ptr++;
}
len += seq_puts(m, "\n\n");
ioc = ioc->next;
break; /* XXX - remove me */
}
return 0;
}
static int ccio_proc_bitmap_open(struct inode *inode, struct file *file)
{
return single_open(file, &ccio_proc_bitmap_info, NULL);
}
static const struct file_operations ccio_proc_bitmap_fops = {
.owner = THIS_MODULE,
.open = ccio_proc_bitmap_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif /* CONFIG_PROC_FS */
/**
* ccio_find_ioc - Find the ioc in the ioc_list
* @hw_path: The hardware path of the ioc.
*
* This function searches the ioc_list for an ioc that matches
* the provide hardware path.
*/
static struct ioc * ccio_find_ioc(int hw_path)
{
int i;
struct ioc *ioc;
ioc = ioc_list;
for (i = 0; i < ioc_count; i++) {
if (ioc->hw_path == hw_path)
return ioc;
ioc = ioc->next;
}
return NULL;
}
/**
* ccio_get_iommu - Find the iommu which controls this device
* @dev: The parisc device.
*
* This function searches through the registered IOMMU's and returns
* the appropriate IOMMU for the device based on its hardware path.
*/
void * ccio_get_iommu(const struct parisc_device *dev)
{
dev = find_pa_parent_type(dev, HPHW_IOA);
if (!dev)
return NULL;
return ccio_find_ioc(dev->hw_path);
}
#define CUJO_20_STEP 0x10000000 /* inc upper nibble */
/* Cujo 2.0 has a bug which will silently corrupt data being transferred
* to/from certain pages. To avoid this happening, we mark these pages
* as `used', and ensure that nothing will try to allocate from them.
*/
void ccio_cujo20_fixup(struct parisc_device *cujo, u32 iovp)
{
unsigned int idx;
struct parisc_device *dev = parisc_parent(cujo);
struct ioc *ioc = ccio_get_iommu(dev);
u8 *res_ptr;
ioc->cujo20_bug = 1;
res_ptr = ioc->res_map;
idx = PDIR_INDEX(iovp) >> 3;
while (idx < ioc->res_size) {
res_ptr[idx] |= 0xff;
idx += PDIR_INDEX(CUJO_20_STEP) >> 3;
}
}
#if 0
/* GRANT - is this needed for U2 or not? */
/*
** Get the size of the I/O TLB for this I/O MMU.
**
** If spa_shift is non-zero (ie probably U2),
** then calculate the I/O TLB size using spa_shift.
**
** Otherwise we are supposed to get the IODC entry point ENTRY TLB
** and execute it. However, both U2 and Uturn firmware supplies spa_shift.
** I think only Java (K/D/R-class too?) systems don't do this.
*/
static int
ccio_get_iotlb_size(struct parisc_device *dev)
{
if (dev->spa_shift == 0) {
panic("%s() : Can't determine I/O TLB size.\n", __func__);
}
return (1 << dev->spa_shift);
}
#else
/* Uturn supports 256 TLB entries */
#define CCIO_CHAINID_SHIFT 8
#define CCIO_CHAINID_MASK 0xff
#endif /* 0 */
/* We *can't* support JAVA (T600). Venture there at your own risk. */
static const struct parisc_device_id ccio_tbl[] = {
{ HPHW_IOA, HVERSION_REV_ANY_ID, U2_IOA_RUNWAY, 0xb }, /* U2 */
{ HPHW_IOA, HVERSION_REV_ANY_ID, UTURN_IOA_RUNWAY, 0xb }, /* UTurn */
{ 0, }
};
static int ccio_probe(struct parisc_device *dev);
static struct parisc_driver ccio_driver = {
.name = "ccio",
.id_table = ccio_tbl,
.probe = ccio_probe,
};
/**
* ccio_ioc_init - Initialize the I/O Controller
* @ioc: The I/O Controller.
*
* Initialize the I/O Controller which includes setting up the
* I/O Page Directory, the resource map, and initalizing the
* U2/Uturn chip into virtual mode.
*/
static void
ccio_ioc_init(struct ioc *ioc)
{
int i;
unsigned int iov_order;
u32 iova_space_size;
/*
** Determine IOVA Space size from memory size.
**
** Ideally, PCI drivers would register the maximum number
** of DMA they can have outstanding for each device they
** own. Next best thing would be to guess how much DMA
** can be outstanding based on PCI Class/sub-class. Both
** methods still require some "extra" to support PCI
** Hot-Plug/Removal of PCI cards. (aka PCI OLARD).
*/
iova_space_size = (u32) (totalram_pages / count_parisc_driver(&ccio_driver));
/* limit IOVA space size to 1MB-1GB */
if (iova_space_size < (1 << (20 - PAGE_SHIFT))) {
iova_space_size = 1 << (20 - PAGE_SHIFT);
#ifdef __LP64__
} else if (iova_space_size > (1 << (30 - PAGE_SHIFT))) {
iova_space_size = 1 << (30 - PAGE_SHIFT);
#endif
}
/*
** iova space must be log2() in size.
** thus, pdir/res_map will also be log2().
*/
/* We could use larger page sizes in order to *decrease* the number
** of mappings needed. (ie 8k pages means 1/2 the mappings).
**
** Note: Grant Grunder says "Using 8k I/O pages isn't trivial either
** since the pages must also be physically contiguous - typically
** this is the case under linux."
*/
iov_order = get_order(iova_space_size << PAGE_SHIFT);
/* iova_space_size is now bytes, not pages */
iova_space_size = 1 << (iov_order + PAGE_SHIFT);
ioc->pdir_size = (iova_space_size / IOVP_SIZE) * sizeof(u64);
BUG_ON(ioc->pdir_size > 8 * 1024 * 1024); /* max pdir size <= 8MB */
/* Verify it's a power of two */
BUG_ON((1 << get_order(ioc->pdir_size)) != (ioc->pdir_size >> PAGE_SHIFT));
DBG_INIT("%s() hpa 0x%p mem %luMB IOV %dMB (%d bits)\n",
__func__, ioc->ioc_regs,
(unsigned long) totalram_pages >> (20 - PAGE_SHIFT),
iova_space_size>>20,
iov_order + PAGE_SHIFT);
ioc->pdir_base = (u64 *)__get_free_pages(GFP_KERNEL,
get_order(ioc->pdir_size));
if(NULL == ioc->pdir_base) {
panic("%s() could not allocate I/O Page Table\n", __func__);
}
memset(ioc->pdir_base, 0, ioc->pdir_size);
BUG_ON((((unsigned long)ioc->pdir_base) & PAGE_MASK) != (unsigned long)ioc->pdir_base);
DBG_INIT(" base %p\n", ioc->pdir_base);
/* resource map size dictated by pdir_size */
ioc->res_size = (ioc->pdir_size / sizeof(u64)) >> 3;
DBG_INIT("%s() res_size 0x%x\n", __func__, ioc->res_size);
ioc->res_map = (u8 *)__get_free_pages(GFP_KERNEL,
get_order(ioc->res_size));
if(NULL == ioc->res_map) {
panic("%s() could not allocate resource map\n", __func__);
}
memset(ioc->res_map, 0, ioc->res_size);
/* Initialize the res_hint to 16 */
ioc->res_hint = 16;
/* Initialize the spinlock */
spin_lock_init(&ioc->res_lock);
/*
** Chainid is the upper most bits of an IOVP used to determine
** which TLB entry an IOVP will use.
*/
ioc->chainid_shift = get_order(iova_space_size) + PAGE_SHIFT - CCIO_CHAINID_SHIFT;
DBG_INIT(" chainid_shift 0x%x\n", ioc->chainid_shift);
/*
** Initialize IOA hardware
*/
WRITE_U32(CCIO_CHAINID_MASK << ioc->chainid_shift,
&ioc->ioc_regs->io_chain_id_mask);
WRITE_U32(virt_to_phys(ioc->pdir_base),
&ioc->ioc_regs->io_pdir_base);
/*
** Go to "Virtual Mode"
*/
WRITE_U32(IOA_NORMAL_MODE, &ioc->ioc_regs->io_control);
/*
** Initialize all I/O TLB entries to 0 (Valid bit off).
*/
WRITE_U32(0, &ioc->ioc_regs->io_tlb_entry_m);
WRITE_U32(0, &ioc->ioc_regs->io_tlb_entry_l);
for(i = 1 << CCIO_CHAINID_SHIFT; i ; i--) {
WRITE_U32((CMD_TLB_DIRECT_WRITE | (i << ioc->chainid_shift)),
&ioc->ioc_regs->io_command);
}
}
static void __init
ccio_init_resource(struct resource *res, char *name, void __iomem *ioaddr)
{
int result;
res->parent = NULL;
res->flags = IORESOURCE_MEM;
/*
* bracing ((signed) ...) are required for 64bit kernel because
* we only want to sign extend the lower 16 bits of the register.
* The upper 16-bits of range registers are hardcoded to 0xffff.
*/
res->start = (unsigned long)((signed) READ_U32(ioaddr) << 16);
res->end = (unsigned long)((signed) (READ_U32(ioaddr + 4) << 16) - 1);
res->name = name;
/*
* Check if this MMIO range is disable
*/
if (res->end + 1 == res->start)
return;
/* On some platforms (e.g. K-Class), we have already registered
* resources for devices reported by firmware. Some are children
* of ccio.
* "insert" ccio ranges in the mmio hierarchy (/proc/iomem).
*/
result = insert_resource(&iomem_resource, res);
if (result < 0) {
printk(KERN_ERR "%s() failed to claim CCIO bus address space (%08lx,%08lx)\n",
__func__, (unsigned long)res->start, (unsigned long)res->end);
}
}
static void __init ccio_init_resources(struct ioc *ioc)
{
struct resource *res = ioc->mmio_region;
char *name = kmalloc(14, GFP_KERNEL);
snprintf(name, 14, "GSC Bus [%d/]", ioc->hw_path);
ccio_init_resource(res, name, &ioc->ioc_regs->io_io_low);
ccio_init_resource(res + 1, name, &ioc->ioc_regs->io_io_low_hv);
}
static int new_ioc_area(struct resource *res, unsigned long size,
unsigned long min, unsigned long max, unsigned long align)
{
if (max <= min)
return -EBUSY;
res->start = (max - size + 1) &~ (align - 1);
res->end = res->start + size;
/* We might be trying to expand the MMIO range to include
* a child device that has already registered it's MMIO space.
* Use "insert" instead of request_resource().
*/
if (!insert_resource(&iomem_resource, res))
return 0;
return new_ioc_area(res, size, min, max - size, align);
}
static int expand_ioc_area(struct resource *res, unsigned long size,
unsigned long min, unsigned long max, unsigned long align)
{
unsigned long start, len;
if (!res->parent)
return new_ioc_area(res, size, min, max, align);
start = (res->start - size) &~ (align - 1);
len = res->end - start + 1;
if (start >= min) {
if (!adjust_resource(res, start, len))
return 0;
}
start = res->start;
len = ((size + res->end + align) &~ (align - 1)) - start;
if (start + len <= max) {
if (!adjust_resource(res, start, len))
return 0;
}
return -EBUSY;
}
/*
* Dino calls this function. Beware that we may get called on systems
* which have no IOC (725, B180, C160L, etc) but do have a Dino.
* So it's legal to find no parent IOC.
*
* Some other issues: one of the resources in the ioc may be unassigned.
*/
int ccio_allocate_resource(const struct parisc_device *dev,
struct resource *res, unsigned long size,
unsigned long min, unsigned long max, unsigned long align)
{
struct resource *parent = &iomem_resource;
struct ioc *ioc = ccio_get_iommu(dev);
if (!ioc)
goto out;
parent = ioc->mmio_region;
if (parent->parent &&
!allocate_resource(parent, res, size, min, max, align, NULL, NULL))
return 0;
if ((parent + 1)->parent &&
!allocate_resource(parent + 1, res, size, min, max, align,
NULL, NULL))
return 0;
if (!expand_ioc_area(parent, size, min, max, align)) {
__raw_writel(((parent->start)>>16) | 0xffff0000,
&ioc->ioc_regs->io_io_low);
__raw_writel(((parent->end)>>16) | 0xffff0000,
&ioc->ioc_regs->io_io_high);
} else if (!expand_ioc_area(parent + 1, size, min, max, align)) {
parent++;
__raw_writel(((parent->start)>>16) | 0xffff0000,
&ioc->ioc_regs->io_io_low_hv);
__raw_writel(((parent->end)>>16) | 0xffff0000,
&ioc->ioc_regs->io_io_high_hv);
} else {
return -EBUSY;
}
out:
return allocate_resource(parent, res, size, min, max, align, NULL,NULL);
}
int ccio_request_resource(const struct parisc_device *dev,
struct resource *res)
{
struct resource *parent;
struct ioc *ioc = ccio_get_iommu(dev);
if (!ioc) {
parent = &iomem_resource;
} else if ((ioc->mmio_region->start <= res->start) &&
(res->end <= ioc->mmio_region->end)) {
parent = ioc->mmio_region;
} else if (((ioc->mmio_region + 1)->start <= res->start) &&
(res->end <= (ioc->mmio_region + 1)->end)) {
parent = ioc->mmio_region + 1;
} else {
return -EBUSY;
}
/* "transparent" bus bridges need to register MMIO resources
* firmware assigned them. e.g. children of hppb.c (e.g. K-class)
* registered their resources in the PDC "bus walk" (See
* arch/parisc/kernel/inventory.c).
*/
return insert_resource(parent, res);
}
/**
* ccio_probe - Determine if ccio should claim this device.
* @dev: The device which has been found
*
* Determine if ccio should claim this chip (return 0) or not (return 1).
* If so, initialize the chip and tell other partners in crime they
* have work to do.
*/
static int __init ccio_probe(struct parisc_device *dev)
{
int i;
struct ioc *ioc, **ioc_p = &ioc_list;
ioc = kzalloc(sizeof(struct ioc), GFP_KERNEL);
if (ioc == NULL) {
printk(KERN_ERR MODULE_NAME ": memory allocation failure\n");
return 1;
}
ioc->name = dev->id.hversion == U2_IOA_RUNWAY ? "U2" : "UTurn";
printk(KERN_INFO "Found %s at 0x%lx\n", ioc->name,
(unsigned long)dev->hpa.start);
for (i = 0; i < ioc_count; i++) {
ioc_p = &(*ioc_p)->next;
}
*ioc_p = ioc;
ioc->hw_path = dev->hw_path;
ioc->ioc_regs = ioremap_nocache(dev->hpa.start, 4096);
ccio_ioc_init(ioc);
ccio_init_resources(ioc);
hppa_dma_ops = &ccio_ops;
dev->dev.platform_data = kzalloc(sizeof(struct pci_hba_data), GFP_KERNEL);
/* if this fails, no I/O cards will work, so may as well bug */
BUG_ON(dev->dev.platform_data == NULL);
HBA_DATA(dev->dev.platform_data)->iommu = ioc;
#ifdef CONFIG_PROC_FS
if (ioc_count == 0) {
proc_create(MODULE_NAME, 0, proc_runway_root,
&ccio_proc_info_fops);
proc_create(MODULE_NAME"-bitmap", 0, proc_runway_root,
&ccio_proc_bitmap_fops);
}
#endif
ioc_count++;
parisc_has_iommu();
return 0;
}
/**
* ccio_init - ccio initialization procedure.
*
* Register this driver.
*/
void __init ccio_init(void)
{
register_parisc_driver(&ccio_driver);
}
| gpl-2.0 |
zombi-x/android_kernel_nvidia_shieldtablet | drivers/parisc/ccio-dma.c | 8654 | 48902 | /*
** ccio-dma.c:
** DMA management routines for first generation cache-coherent machines.
** Program U2/Uturn in "Virtual Mode" and use the I/O MMU.
**
** (c) Copyright 2000 Grant Grundler
** (c) Copyright 2000 Ryan Bradetich
** (c) Copyright 2000 Hewlett-Packard Company
**
** 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.
**
**
** "Real Mode" operation refers to U2/Uturn chip operation.
** U2/Uturn were designed to perform coherency checks w/o using
** the I/O MMU - basically what x86 does.
**
** Philipp Rumpf has a "Real Mode" driver for PCX-W machines at:
** CVSROOT=:pserver:anonymous@198.186.203.37:/cvsroot/linux-parisc
** cvs -z3 co linux/arch/parisc/kernel/dma-rm.c
**
** I've rewritten his code to work under TPG's tree. See ccio-rm-dma.c.
**
** Drawbacks of using Real Mode are:
** o outbound DMA is slower - U2 won't prefetch data (GSC+ XQL signal).
** o Inbound DMA less efficient - U2 can't use DMA_FAST attribute.
** o Ability to do scatter/gather in HW is lost.
** o Doesn't work under PCX-U/U+ machines since they didn't follow
** the coherency design originally worked out. Only PCX-W does.
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/pci.h>
#include <linux/reboot.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/scatterlist.h>
#include <linux/iommu-helper.h>
#include <linux/export.h>
#include <asm/byteorder.h>
#include <asm/cache.h> /* for L1_CACHE_BYTES */
#include <asm/uaccess.h>
#include <asm/page.h>
#include <asm/dma.h>
#include <asm/io.h>
#include <asm/hardware.h> /* for register_module() */
#include <asm/parisc-device.h>
/*
** Choose "ccio" since that's what HP-UX calls it.
** Make it easier for folks to migrate from one to the other :^)
*/
#define MODULE_NAME "ccio"
#undef DEBUG_CCIO_RES
#undef DEBUG_CCIO_RUN
#undef DEBUG_CCIO_INIT
#undef DEBUG_CCIO_RUN_SG
#ifdef CONFIG_PROC_FS
/* depends on proc fs support. But costs CPU performance. */
#undef CCIO_COLLECT_STATS
#endif
#include <asm/runway.h> /* for proc_runway_root */
#ifdef DEBUG_CCIO_INIT
#define DBG_INIT(x...) printk(x)
#else
#define DBG_INIT(x...)
#endif
#ifdef DEBUG_CCIO_RUN
#define DBG_RUN(x...) printk(x)
#else
#define DBG_RUN(x...)
#endif
#ifdef DEBUG_CCIO_RES
#define DBG_RES(x...) printk(x)
#else
#define DBG_RES(x...)
#endif
#ifdef DEBUG_CCIO_RUN_SG
#define DBG_RUN_SG(x...) printk(x)
#else
#define DBG_RUN_SG(x...)
#endif
#define CCIO_INLINE inline
#define WRITE_U32(value, addr) __raw_writel(value, addr)
#define READ_U32(addr) __raw_readl(addr)
#define U2_IOA_RUNWAY 0x580
#define U2_BC_GSC 0x501
#define UTURN_IOA_RUNWAY 0x581
#define UTURN_BC_GSC 0x502
#define IOA_NORMAL_MODE 0x00020080 /* IO_CONTROL to turn on CCIO */
#define CMD_TLB_DIRECT_WRITE 35 /* IO_COMMAND for I/O TLB Writes */
#define CMD_TLB_PURGE 33 /* IO_COMMAND to Purge I/O TLB entry */
struct ioa_registers {
/* Runway Supervisory Set */
int32_t unused1[12];
uint32_t io_command; /* Offset 12 */
uint32_t io_status; /* Offset 13 */
uint32_t io_control; /* Offset 14 */
int32_t unused2[1];
/* Runway Auxiliary Register Set */
uint32_t io_err_resp; /* Offset 0 */
uint32_t io_err_info; /* Offset 1 */
uint32_t io_err_req; /* Offset 2 */
uint32_t io_err_resp_hi; /* Offset 3 */
uint32_t io_tlb_entry_m; /* Offset 4 */
uint32_t io_tlb_entry_l; /* Offset 5 */
uint32_t unused3[1];
uint32_t io_pdir_base; /* Offset 7 */
uint32_t io_io_low_hv; /* Offset 8 */
uint32_t io_io_high_hv; /* Offset 9 */
uint32_t unused4[1];
uint32_t io_chain_id_mask; /* Offset 11 */
uint32_t unused5[2];
uint32_t io_io_low; /* Offset 14 */
uint32_t io_io_high; /* Offset 15 */
};
/*
** IOA Registers
** -------------
**
** Runway IO_CONTROL Register (+0x38)
**
** The Runway IO_CONTROL register controls the forwarding of transactions.
**
** | 0 ... 13 | 14 15 | 16 ... 21 | 22 | 23 24 | 25 ... 31 |
** | HV | TLB | reserved | HV | mode | reserved |
**
** o mode field indicates the address translation of transactions
** forwarded from Runway to GSC+:
** Mode Name Value Definition
** Off (default) 0 Opaque to matching addresses.
** Include 1 Transparent for matching addresses.
** Peek 3 Map matching addresses.
**
** + "Off" mode: Runway transactions which match the I/O range
** specified by the IO_IO_LOW/IO_IO_HIGH registers will be ignored.
** + "Include" mode: all addresses within the I/O range specified
** by the IO_IO_LOW and IO_IO_HIGH registers are transparently
** forwarded. This is the I/O Adapter's normal operating mode.
** + "Peek" mode: used during system configuration to initialize the
** GSC+ bus. Runway Write_Shorts in the address range specified by
** IO_IO_LOW and IO_IO_HIGH are forwarded through the I/O Adapter
** *AND* the GSC+ address is remapped to the Broadcast Physical
** Address space by setting the 14 high order address bits of the
** 32 bit GSC+ address to ones.
**
** o TLB field affects transactions which are forwarded from GSC+ to Runway.
** "Real" mode is the poweron default.
**
** TLB Mode Value Description
** Real 0 No TLB translation. Address is directly mapped and the
** virtual address is composed of selected physical bits.
** Error 1 Software fills the TLB manually.
** Normal 2 IOA fetches IO TLB misses from IO PDIR (in host memory).
**
**
** IO_IO_LOW_HV +0x60 (HV dependent)
** IO_IO_HIGH_HV +0x64 (HV dependent)
** IO_IO_LOW +0x78 (Architected register)
** IO_IO_HIGH +0x7c (Architected register)
**
** IO_IO_LOW and IO_IO_HIGH set the lower and upper bounds of the
** I/O Adapter address space, respectively.
**
** 0 ... 7 | 8 ... 15 | 16 ... 31 |
** 11111111 | 11111111 | address |
**
** Each LOW/HIGH pair describes a disjoint address space region.
** (2 per GSC+ port). Each incoming Runway transaction address is compared
** with both sets of LOW/HIGH registers. If the address is in the range
** greater than or equal to IO_IO_LOW and less than IO_IO_HIGH the transaction
** for forwarded to the respective GSC+ bus.
** Specify IO_IO_LOW equal to or greater than IO_IO_HIGH to avoid specifying
** an address space region.
**
** In order for a Runway address to reside within GSC+ extended address space:
** Runway Address [0:7] must identically compare to 8'b11111111
** Runway Address [8:11] must be equal to IO_IO_LOW(_HV)[16:19]
** Runway Address [12:23] must be greater than or equal to
** IO_IO_LOW(_HV)[20:31] and less than IO_IO_HIGH(_HV)[20:31].
** Runway Address [24:39] is not used in the comparison.
**
** When the Runway transaction is forwarded to GSC+, the GSC+ address is
** as follows:
** GSC+ Address[0:3] 4'b1111
** GSC+ Address[4:29] Runway Address[12:37]
** GSC+ Address[30:31] 2'b00
**
** All 4 Low/High registers must be initialized (by PDC) once the lower bus
** is interrogated and address space is defined. The operating system will
** modify the architectural IO_IO_LOW and IO_IO_HIGH registers following
** the PDC initialization. However, the hardware version dependent IO_IO_LOW
** and IO_IO_HIGH registers should not be subsequently altered by the OS.
**
** Writes to both sets of registers will take effect immediately, bypassing
** the queues, which ensures that subsequent Runway transactions are checked
** against the updated bounds values. However reads are queued, introducing
** the possibility of a read being bypassed by a subsequent write to the same
** register. This sequence can be avoided by having software wait for read
** returns before issuing subsequent writes.
*/
struct ioc {
struct ioa_registers __iomem *ioc_regs; /* I/O MMU base address */
u8 *res_map; /* resource map, bit == pdir entry */
u64 *pdir_base; /* physical base address */
u32 pdir_size; /* bytes, function of IOV Space size */
u32 res_hint; /* next available IOVP -
circular search */
u32 res_size; /* size of resource map in bytes */
spinlock_t res_lock;
#ifdef CCIO_COLLECT_STATS
#define CCIO_SEARCH_SAMPLE 0x100
unsigned long avg_search[CCIO_SEARCH_SAMPLE];
unsigned long avg_idx; /* current index into avg_search */
unsigned long used_pages;
unsigned long msingle_calls;
unsigned long msingle_pages;
unsigned long msg_calls;
unsigned long msg_pages;
unsigned long usingle_calls;
unsigned long usingle_pages;
unsigned long usg_calls;
unsigned long usg_pages;
#endif
unsigned short cujo20_bug;
/* STUFF We don't need in performance path */
u32 chainid_shift; /* specify bit location of chain_id */
struct ioc *next; /* Linked list of discovered iocs */
const char *name; /* device name from firmware */
unsigned int hw_path; /* the hardware path this ioc is associatd with */
struct pci_dev *fake_pci_dev; /* the fake pci_dev for non-pci devs */
struct resource mmio_region[2]; /* The "routed" MMIO regions */
};
static struct ioc *ioc_list;
static int ioc_count;
/**************************************************************
*
* I/O Pdir Resource Management
*
* Bits set in the resource map are in use.
* Each bit can represent a number of pages.
* LSbs represent lower addresses (IOVA's).
*
* This was was copied from sba_iommu.c. Don't try to unify
* the two resource managers unless a way to have different
* allocation policies is also adjusted. We'd like to avoid
* I/O TLB thrashing by having resource allocation policy
* match the I/O TLB replacement policy.
*
***************************************************************/
#define IOVP_SIZE PAGE_SIZE
#define IOVP_SHIFT PAGE_SHIFT
#define IOVP_MASK PAGE_MASK
/* Convert from IOVP to IOVA and vice versa. */
#define CCIO_IOVA(iovp,offset) ((iovp) | (offset))
#define CCIO_IOVP(iova) ((iova) & IOVP_MASK)
#define PDIR_INDEX(iovp) ((iovp)>>IOVP_SHIFT)
#define MKIOVP(pdir_idx) ((long)(pdir_idx) << IOVP_SHIFT)
#define MKIOVA(iovp,offset) (dma_addr_t)((long)iovp | (long)offset)
/*
** Don't worry about the 150% average search length on a miss.
** If the search wraps around, and passes the res_hint, it will
** cause the kernel to panic anyhow.
*/
#define CCIO_SEARCH_LOOP(ioc, res_idx, mask, size) \
for(; res_ptr < res_end; ++res_ptr) { \
int ret;\
unsigned int idx;\
idx = (unsigned int)((unsigned long)res_ptr - (unsigned long)ioc->res_map); \
ret = iommu_is_span_boundary(idx << 3, pages_needed, 0, boundary_size);\
if ((0 == (*res_ptr & mask)) && !ret) { \
*res_ptr |= mask; \
res_idx = idx;\
ioc->res_hint = res_idx + (size >> 3); \
goto resource_found; \
} \
}
#define CCIO_FIND_FREE_MAPPING(ioa, res_idx, mask, size) \
u##size *res_ptr = (u##size *)&((ioc)->res_map[ioa->res_hint & ~((size >> 3) - 1)]); \
u##size *res_end = (u##size *)&(ioc)->res_map[ioa->res_size]; \
CCIO_SEARCH_LOOP(ioc, res_idx, mask, size); \
res_ptr = (u##size *)&(ioc)->res_map[0]; \
CCIO_SEARCH_LOOP(ioa, res_idx, mask, size);
/*
** Find available bit in this ioa's resource map.
** Use a "circular" search:
** o Most IOVA's are "temporary" - avg search time should be small.
** o keep a history of what happened for debugging
** o KISS.
**
** Perf optimizations:
** o search for log2(size) bits at a time.
** o search for available resource bits using byte/word/whatever.
** o use different search for "large" (eg > 4 pages) or "very large"
** (eg > 16 pages) mappings.
*/
/**
* ccio_alloc_range - Allocate pages in the ioc's resource map.
* @ioc: The I/O Controller.
* @pages_needed: The requested number of pages to be mapped into the
* I/O Pdir...
*
* This function searches the resource map of the ioc to locate a range
* of available pages for the requested size.
*/
static int
ccio_alloc_range(struct ioc *ioc, struct device *dev, size_t size)
{
unsigned int pages_needed = size >> IOVP_SHIFT;
unsigned int res_idx;
unsigned long boundary_size;
#ifdef CCIO_COLLECT_STATS
unsigned long cr_start = mfctl(16);
#endif
BUG_ON(pages_needed == 0);
BUG_ON((pages_needed * IOVP_SIZE) > DMA_CHUNK_SIZE);
DBG_RES("%s() size: %d pages_needed %d\n",
__func__, size, pages_needed);
/*
** "seek and ye shall find"...praying never hurts either...
** ggg sacrifices another 710 to the computer gods.
*/
boundary_size = ALIGN((unsigned long long)dma_get_seg_boundary(dev) + 1,
1ULL << IOVP_SHIFT) >> IOVP_SHIFT;
if (pages_needed <= 8) {
/*
* LAN traffic will not thrash the TLB IFF the same NIC
* uses 8 adjacent pages to map separate payload data.
* ie the same byte in the resource bit map.
*/
#if 0
/* FIXME: bit search should shift it's way through
* an unsigned long - not byte at a time. As it is now,
* we effectively allocate this byte to this mapping.
*/
unsigned long mask = ~(~0UL >> pages_needed);
CCIO_FIND_FREE_MAPPING(ioc, res_idx, mask, 8);
#else
CCIO_FIND_FREE_MAPPING(ioc, res_idx, 0xff, 8);
#endif
} else if (pages_needed <= 16) {
CCIO_FIND_FREE_MAPPING(ioc, res_idx, 0xffff, 16);
} else if (pages_needed <= 32) {
CCIO_FIND_FREE_MAPPING(ioc, res_idx, ~(unsigned int)0, 32);
#ifdef __LP64__
} else if (pages_needed <= 64) {
CCIO_FIND_FREE_MAPPING(ioc, res_idx, ~0UL, 64);
#endif
} else {
panic("%s: %s() Too many pages to map. pages_needed: %u\n",
__FILE__, __func__, pages_needed);
}
panic("%s: %s() I/O MMU is out of mapping resources.\n", __FILE__,
__func__);
resource_found:
DBG_RES("%s() res_idx %d res_hint: %d\n",
__func__, res_idx, ioc->res_hint);
#ifdef CCIO_COLLECT_STATS
{
unsigned long cr_end = mfctl(16);
unsigned long tmp = cr_end - cr_start;
/* check for roll over */
cr_start = (cr_end < cr_start) ? -(tmp) : (tmp);
}
ioc->avg_search[ioc->avg_idx++] = cr_start;
ioc->avg_idx &= CCIO_SEARCH_SAMPLE - 1;
ioc->used_pages += pages_needed;
#endif
/*
** return the bit address.
*/
return res_idx << 3;
}
#define CCIO_FREE_MAPPINGS(ioc, res_idx, mask, size) \
u##size *res_ptr = (u##size *)&((ioc)->res_map[res_idx]); \
BUG_ON((*res_ptr & mask) != mask); \
*res_ptr &= ~(mask);
/**
* ccio_free_range - Free pages from the ioc's resource map.
* @ioc: The I/O Controller.
* @iova: The I/O Virtual Address.
* @pages_mapped: The requested number of pages to be freed from the
* I/O Pdir.
*
* This function frees the resouces allocated for the iova.
*/
static void
ccio_free_range(struct ioc *ioc, dma_addr_t iova, unsigned long pages_mapped)
{
unsigned long iovp = CCIO_IOVP(iova);
unsigned int res_idx = PDIR_INDEX(iovp) >> 3;
BUG_ON(pages_mapped == 0);
BUG_ON((pages_mapped * IOVP_SIZE) > DMA_CHUNK_SIZE);
BUG_ON(pages_mapped > BITS_PER_LONG);
DBG_RES("%s(): res_idx: %d pages_mapped %d\n",
__func__, res_idx, pages_mapped);
#ifdef CCIO_COLLECT_STATS
ioc->used_pages -= pages_mapped;
#endif
if(pages_mapped <= 8) {
#if 0
/* see matching comments in alloc_range */
unsigned long mask = ~(~0UL >> pages_mapped);
CCIO_FREE_MAPPINGS(ioc, res_idx, mask, 8);
#else
CCIO_FREE_MAPPINGS(ioc, res_idx, 0xffUL, 8);
#endif
} else if(pages_mapped <= 16) {
CCIO_FREE_MAPPINGS(ioc, res_idx, 0xffffUL, 16);
} else if(pages_mapped <= 32) {
CCIO_FREE_MAPPINGS(ioc, res_idx, ~(unsigned int)0, 32);
#ifdef __LP64__
} else if(pages_mapped <= 64) {
CCIO_FREE_MAPPINGS(ioc, res_idx, ~0UL, 64);
#endif
} else {
panic("%s:%s() Too many pages to unmap.\n", __FILE__,
__func__);
}
}
/****************************************************************
**
** CCIO dma_ops support routines
**
*****************************************************************/
typedef unsigned long space_t;
#define KERNEL_SPACE 0
/*
** DMA "Page Type" and Hints
** o if SAFE_DMA isn't set, mapping is for FAST_DMA. SAFE_DMA should be
** set for subcacheline DMA transfers since we don't want to damage the
** other part of a cacheline.
** o SAFE_DMA must be set for "memory" allocated via pci_alloc_consistent().
** This bit tells U2 to do R/M/W for partial cachelines. "Streaming"
** data can avoid this if the mapping covers full cache lines.
** o STOP_MOST is needed for atomicity across cachelines.
** Apparently only "some EISA devices" need this.
** Using CONFIG_ISA is hack. Only the IOA with EISA under it needs
** to use this hint iff the EISA devices needs this feature.
** According to the U2 ERS, STOP_MOST enabled pages hurt performance.
** o PREFETCH should *not* be set for cases like Multiple PCI devices
** behind GSCtoPCI (dino) bus converter. Only one cacheline per GSC
** device can be fetched and multiply DMA streams will thrash the
** prefetch buffer and burn memory bandwidth. See 6.7.3 "Prefetch Rules
** and Invalidation of Prefetch Entries".
**
** FIXME: the default hints need to be per GSC device - not global.
**
** HP-UX dorks: linux device driver programming model is totally different
** than HP-UX's. HP-UX always sets HINT_PREFETCH since it's drivers
** do special things to work on non-coherent platforms...linux has to
** be much more careful with this.
*/
#define IOPDIR_VALID 0x01UL
#define HINT_SAFE_DMA 0x02UL /* used for pci_alloc_consistent() pages */
#ifdef CONFIG_EISA
#define HINT_STOP_MOST 0x04UL /* LSL support */
#else
#define HINT_STOP_MOST 0x00UL /* only needed for "some EISA devices" */
#endif
#define HINT_UDPATE_ENB 0x08UL /* not used/supported by U2 */
#define HINT_PREFETCH 0x10UL /* for outbound pages which are not SAFE */
/*
** Use direction (ie PCI_DMA_TODEVICE) to pick hint.
** ccio_alloc_consistent() depends on this to get SAFE_DMA
** when it passes in BIDIRECTIONAL flag.
*/
static u32 hint_lookup[] = {
[PCI_DMA_BIDIRECTIONAL] = HINT_STOP_MOST | HINT_SAFE_DMA | IOPDIR_VALID,
[PCI_DMA_TODEVICE] = HINT_STOP_MOST | HINT_PREFETCH | IOPDIR_VALID,
[PCI_DMA_FROMDEVICE] = HINT_STOP_MOST | IOPDIR_VALID,
};
/**
* ccio_io_pdir_entry - Initialize an I/O Pdir.
* @pdir_ptr: A pointer into I/O Pdir.
* @sid: The Space Identifier.
* @vba: The virtual address.
* @hints: The DMA Hint.
*
* Given a virtual address (vba, arg2) and space id, (sid, arg1),
* load the I/O PDIR entry pointed to by pdir_ptr (arg0). Each IO Pdir
* entry consists of 8 bytes as shown below (MSB == bit 0):
*
*
* WORD 0:
* +------+----------------+-----------------------------------------------+
* | Phys | Virtual Index | Phys |
* | 0:3 | 0:11 | 4:19 |
* |4 bits| 12 bits | 16 bits |
* +------+----------------+-----------------------------------------------+
* WORD 1:
* +-----------------------+-----------------------------------------------+
* | Phys | Rsvd | Prefetch |Update |Rsvd |Lock |Safe |Valid |
* | 20:39 | | Enable |Enable | |Enable|DMA | |
* | 20 bits | 5 bits | 1 bit |1 bit |2 bits|1 bit |1 bit |1 bit |
* +-----------------------+-----------------------------------------------+
*
* The virtual index field is filled with the results of the LCI
* (Load Coherence Index) instruction. The 8 bits used for the virtual
* index are bits 12:19 of the value returned by LCI.
*/
static void CCIO_INLINE
ccio_io_pdir_entry(u64 *pdir_ptr, space_t sid, unsigned long vba,
unsigned long hints)
{
register unsigned long pa;
register unsigned long ci; /* coherent index */
/* We currently only support kernel addresses */
BUG_ON(sid != KERNEL_SPACE);
mtsp(sid,1);
/*
** WORD 1 - low order word
** "hints" parm includes the VALID bit!
** "dep" clobbers the physical address offset bits as well.
*/
pa = virt_to_phys(vba);
asm volatile("depw %1,31,12,%0" : "+r" (pa) : "r" (hints));
((u32 *)pdir_ptr)[1] = (u32) pa;
/*
** WORD 0 - high order word
*/
#ifdef __LP64__
/*
** get bits 12:15 of physical address
** shift bits 16:31 of physical address
** and deposit them
*/
asm volatile ("extrd,u %1,15,4,%0" : "=r" (ci) : "r" (pa));
asm volatile ("extrd,u %1,31,16,%0" : "+r" (pa) : "r" (pa));
asm volatile ("depd %1,35,4,%0" : "+r" (pa) : "r" (ci));
#else
pa = 0;
#endif
/*
** get CPU coherency index bits
** Grab virtual index [0:11]
** Deposit virt_idx bits into I/O PDIR word
*/
asm volatile ("lci %%r0(%%sr1, %1), %0" : "=r" (ci) : "r" (vba));
asm volatile ("extru %1,19,12,%0" : "+r" (ci) : "r" (ci));
asm volatile ("depw %1,15,12,%0" : "+r" (pa) : "r" (ci));
((u32 *)pdir_ptr)[0] = (u32) pa;
/* FIXME: PCX_W platforms don't need FDC/SYNC. (eg C360)
** PCX-U/U+ do. (eg C200/C240)
** PCX-T'? Don't know. (eg C110 or similar K-class)
**
** See PDC_MODEL/option 0/SW_CAP word for "Non-coherent IO-PDIR bit".
** Hopefully we can patch (NOP) these out at boot time somehow.
**
** "Since PCX-U employs an offset hash that is incompatible with
** the real mode coherence index generation of U2, the PDIR entry
** must be flushed to memory to retain coherence."
*/
asm volatile("fdc %%r0(%0)" : : "r" (pdir_ptr));
asm volatile("sync");
}
/**
* ccio_clear_io_tlb - Remove stale entries from the I/O TLB.
* @ioc: The I/O Controller.
* @iovp: The I/O Virtual Page.
* @byte_cnt: The requested number of bytes to be freed from the I/O Pdir.
*
* Purge invalid I/O PDIR entries from the I/O TLB.
*
* FIXME: Can we change the byte_cnt to pages_mapped?
*/
static CCIO_INLINE void
ccio_clear_io_tlb(struct ioc *ioc, dma_addr_t iovp, size_t byte_cnt)
{
u32 chain_size = 1 << ioc->chainid_shift;
iovp &= IOVP_MASK; /* clear offset bits, just want pagenum */
byte_cnt += chain_size;
while(byte_cnt > chain_size) {
WRITE_U32(CMD_TLB_PURGE | iovp, &ioc->ioc_regs->io_command);
iovp += chain_size;
byte_cnt -= chain_size;
}
}
/**
* ccio_mark_invalid - Mark the I/O Pdir entries invalid.
* @ioc: The I/O Controller.
* @iova: The I/O Virtual Address.
* @byte_cnt: The requested number of bytes to be freed from the I/O Pdir.
*
* Mark the I/O Pdir entries invalid and blow away the corresponding I/O
* TLB entries.
*
* FIXME: at some threshold it might be "cheaper" to just blow
* away the entire I/O TLB instead of individual entries.
*
* FIXME: Uturn has 256 TLB entries. We don't need to purge every
* PDIR entry - just once for each possible TLB entry.
* (We do need to maker I/O PDIR entries invalid regardless).
*
* FIXME: Can we change byte_cnt to pages_mapped?
*/
static CCIO_INLINE void
ccio_mark_invalid(struct ioc *ioc, dma_addr_t iova, size_t byte_cnt)
{
u32 iovp = (u32)CCIO_IOVP(iova);
size_t saved_byte_cnt;
/* round up to nearest page size */
saved_byte_cnt = byte_cnt = ALIGN(byte_cnt, IOVP_SIZE);
while(byte_cnt > 0) {
/* invalidate one page at a time */
unsigned int idx = PDIR_INDEX(iovp);
char *pdir_ptr = (char *) &(ioc->pdir_base[idx]);
BUG_ON(idx >= (ioc->pdir_size / sizeof(u64)));
pdir_ptr[7] = 0; /* clear only VALID bit */
/*
** FIXME: PCX_W platforms don't need FDC/SYNC. (eg C360)
** PCX-U/U+ do. (eg C200/C240)
** See PDC_MODEL/option 0/SW_CAP for "Non-coherent IO-PDIR bit".
**
** Hopefully someone figures out how to patch (NOP) the
** FDC/SYNC out at boot time.
*/
asm volatile("fdc %%r0(%0)" : : "r" (pdir_ptr[7]));
iovp += IOVP_SIZE;
byte_cnt -= IOVP_SIZE;
}
asm volatile("sync");
ccio_clear_io_tlb(ioc, CCIO_IOVP(iova), saved_byte_cnt);
}
/****************************************************************
**
** CCIO dma_ops
**
*****************************************************************/
/**
* ccio_dma_supported - Verify the IOMMU supports the DMA address range.
* @dev: The PCI device.
* @mask: A bit mask describing the DMA address range of the device.
*
* This function implements the pci_dma_supported function.
*/
static int
ccio_dma_supported(struct device *dev, u64 mask)
{
if(dev == NULL) {
printk(KERN_ERR MODULE_NAME ": EISA/ISA/et al not supported\n");
BUG();
return 0;
}
/* only support 32-bit devices (ie PCI/GSC) */
return (int)(mask == 0xffffffffUL);
}
/**
* ccio_map_single - Map an address range into the IOMMU.
* @dev: The PCI device.
* @addr: The start address of the DMA region.
* @size: The length of the DMA region.
* @direction: The direction of the DMA transaction (to/from device).
*
* This function implements the pci_map_single function.
*/
static dma_addr_t
ccio_map_single(struct device *dev, void *addr, size_t size,
enum dma_data_direction direction)
{
int idx;
struct ioc *ioc;
unsigned long flags;
dma_addr_t iovp;
dma_addr_t offset;
u64 *pdir_start;
unsigned long hint = hint_lookup[(int)direction];
BUG_ON(!dev);
ioc = GET_IOC(dev);
BUG_ON(size <= 0);
/* save offset bits */
offset = ((unsigned long) addr) & ~IOVP_MASK;
/* round up to nearest IOVP_SIZE */
size = ALIGN(size + offset, IOVP_SIZE);
spin_lock_irqsave(&ioc->res_lock, flags);
#ifdef CCIO_COLLECT_STATS
ioc->msingle_calls++;
ioc->msingle_pages += size >> IOVP_SHIFT;
#endif
idx = ccio_alloc_range(ioc, dev, size);
iovp = (dma_addr_t)MKIOVP(idx);
pdir_start = &(ioc->pdir_base[idx]);
DBG_RUN("%s() 0x%p -> 0x%lx size: %0x%x\n",
__func__, addr, (long)iovp | offset, size);
/* If not cacheline aligned, force SAFE_DMA on the whole mess */
if((size % L1_CACHE_BYTES) || ((unsigned long)addr % L1_CACHE_BYTES))
hint |= HINT_SAFE_DMA;
while(size > 0) {
ccio_io_pdir_entry(pdir_start, KERNEL_SPACE, (unsigned long)addr, hint);
DBG_RUN(" pdir %p %08x%08x\n",
pdir_start,
(u32) (((u32 *) pdir_start)[0]),
(u32) (((u32 *) pdir_start)[1]));
++pdir_start;
addr += IOVP_SIZE;
size -= IOVP_SIZE;
}
spin_unlock_irqrestore(&ioc->res_lock, flags);
/* form complete address */
return CCIO_IOVA(iovp, offset);
}
/**
* ccio_unmap_single - Unmap an address range from the IOMMU.
* @dev: The PCI device.
* @addr: The start address of the DMA region.
* @size: The length of the DMA region.
* @direction: The direction of the DMA transaction (to/from device).
*
* This function implements the pci_unmap_single function.
*/
static void
ccio_unmap_single(struct device *dev, dma_addr_t iova, size_t size,
enum dma_data_direction direction)
{
struct ioc *ioc;
unsigned long flags;
dma_addr_t offset = iova & ~IOVP_MASK;
BUG_ON(!dev);
ioc = GET_IOC(dev);
DBG_RUN("%s() iovp 0x%lx/%x\n",
__func__, (long)iova, size);
iova ^= offset; /* clear offset bits */
size += offset;
size = ALIGN(size, IOVP_SIZE);
spin_lock_irqsave(&ioc->res_lock, flags);
#ifdef CCIO_COLLECT_STATS
ioc->usingle_calls++;
ioc->usingle_pages += size >> IOVP_SHIFT;
#endif
ccio_mark_invalid(ioc, iova, size);
ccio_free_range(ioc, iova, (size >> IOVP_SHIFT));
spin_unlock_irqrestore(&ioc->res_lock, flags);
}
/**
* ccio_alloc_consistent - Allocate a consistent DMA mapping.
* @dev: The PCI device.
* @size: The length of the DMA region.
* @dma_handle: The DMA address handed back to the device (not the cpu).
*
* This function implements the pci_alloc_consistent function.
*/
static void *
ccio_alloc_consistent(struct device *dev, size_t size, dma_addr_t *dma_handle, gfp_t flag)
{
void *ret;
#if 0
/* GRANT Need to establish hierarchy for non-PCI devs as well
** and then provide matching gsc_map_xxx() functions for them as well.
*/
if(!hwdev) {
/* only support PCI */
*dma_handle = 0;
return 0;
}
#endif
ret = (void *) __get_free_pages(flag, get_order(size));
if (ret) {
memset(ret, 0, size);
*dma_handle = ccio_map_single(dev, ret, size, PCI_DMA_BIDIRECTIONAL);
}
return ret;
}
/**
* ccio_free_consistent - Free a consistent DMA mapping.
* @dev: The PCI device.
* @size: The length of the DMA region.
* @cpu_addr: The cpu address returned from the ccio_alloc_consistent.
* @dma_handle: The device address returned from the ccio_alloc_consistent.
*
* This function implements the pci_free_consistent function.
*/
static void
ccio_free_consistent(struct device *dev, size_t size, void *cpu_addr,
dma_addr_t dma_handle)
{
ccio_unmap_single(dev, dma_handle, size, 0);
free_pages((unsigned long)cpu_addr, get_order(size));
}
/*
** Since 0 is a valid pdir_base index value, can't use that
** to determine if a value is valid or not. Use a flag to indicate
** the SG list entry contains a valid pdir index.
*/
#define PIDE_FLAG 0x80000000UL
#ifdef CCIO_COLLECT_STATS
#define IOMMU_MAP_STATS
#endif
#include "iommu-helpers.h"
/**
* ccio_map_sg - Map the scatter/gather list into the IOMMU.
* @dev: The PCI device.
* @sglist: The scatter/gather list to be mapped in the IOMMU.
* @nents: The number of entries in the scatter/gather list.
* @direction: The direction of the DMA transaction (to/from device).
*
* This function implements the pci_map_sg function.
*/
static int
ccio_map_sg(struct device *dev, struct scatterlist *sglist, int nents,
enum dma_data_direction direction)
{
struct ioc *ioc;
int coalesced, filled = 0;
unsigned long flags;
unsigned long hint = hint_lookup[(int)direction];
unsigned long prev_len = 0, current_len = 0;
int i;
BUG_ON(!dev);
ioc = GET_IOC(dev);
DBG_RUN_SG("%s() START %d entries\n", __func__, nents);
/* Fast path single entry scatterlists. */
if (nents == 1) {
sg_dma_address(sglist) = ccio_map_single(dev,
(void *)sg_virt_addr(sglist), sglist->length,
direction);
sg_dma_len(sglist) = sglist->length;
return 1;
}
for(i = 0; i < nents; i++)
prev_len += sglist[i].length;
spin_lock_irqsave(&ioc->res_lock, flags);
#ifdef CCIO_COLLECT_STATS
ioc->msg_calls++;
#endif
/*
** First coalesce the chunks and allocate I/O pdir space
**
** If this is one DMA stream, we can properly map using the
** correct virtual address associated with each DMA page.
** w/o this association, we wouldn't have coherent DMA!
** Access to the virtual address is what forces a two pass algorithm.
*/
coalesced = iommu_coalesce_chunks(ioc, dev, sglist, nents, ccio_alloc_range);
/*
** Program the I/O Pdir
**
** map the virtual addresses to the I/O Pdir
** o dma_address will contain the pdir index
** o dma_len will contain the number of bytes to map
** o page/offset contain the virtual address.
*/
filled = iommu_fill_pdir(ioc, sglist, nents, hint, ccio_io_pdir_entry);
spin_unlock_irqrestore(&ioc->res_lock, flags);
BUG_ON(coalesced != filled);
DBG_RUN_SG("%s() DONE %d mappings\n", __func__, filled);
for (i = 0; i < filled; i++)
current_len += sg_dma_len(sglist + i);
BUG_ON(current_len != prev_len);
return filled;
}
/**
* ccio_unmap_sg - Unmap the scatter/gather list from the IOMMU.
* @dev: The PCI device.
* @sglist: The scatter/gather list to be unmapped from the IOMMU.
* @nents: The number of entries in the scatter/gather list.
* @direction: The direction of the DMA transaction (to/from device).
*
* This function implements the pci_unmap_sg function.
*/
static void
ccio_unmap_sg(struct device *dev, struct scatterlist *sglist, int nents,
enum dma_data_direction direction)
{
struct ioc *ioc;
BUG_ON(!dev);
ioc = GET_IOC(dev);
DBG_RUN_SG("%s() START %d entries, %08lx,%x\n",
__func__, nents, sg_virt_addr(sglist), sglist->length);
#ifdef CCIO_COLLECT_STATS
ioc->usg_calls++;
#endif
while(sg_dma_len(sglist) && nents--) {
#ifdef CCIO_COLLECT_STATS
ioc->usg_pages += sg_dma_len(sglist) >> PAGE_SHIFT;
#endif
ccio_unmap_single(dev, sg_dma_address(sglist),
sg_dma_len(sglist), direction);
++sglist;
}
DBG_RUN_SG("%s() DONE (nents %d)\n", __func__, nents);
}
static struct hppa_dma_ops ccio_ops = {
.dma_supported = ccio_dma_supported,
.alloc_consistent = ccio_alloc_consistent,
.alloc_noncoherent = ccio_alloc_consistent,
.free_consistent = ccio_free_consistent,
.map_single = ccio_map_single,
.unmap_single = ccio_unmap_single,
.map_sg = ccio_map_sg,
.unmap_sg = ccio_unmap_sg,
.dma_sync_single_for_cpu = NULL, /* NOP for U2/Uturn */
.dma_sync_single_for_device = NULL, /* NOP for U2/Uturn */
.dma_sync_sg_for_cpu = NULL, /* ditto */
.dma_sync_sg_for_device = NULL, /* ditto */
};
#ifdef CONFIG_PROC_FS
static int ccio_proc_info(struct seq_file *m, void *p)
{
int len = 0;
struct ioc *ioc = ioc_list;
while (ioc != NULL) {
unsigned int total_pages = ioc->res_size << 3;
#ifdef CCIO_COLLECT_STATS
unsigned long avg = 0, min, max;
int j;
#endif
len += seq_printf(m, "%s\n", ioc->name);
len += seq_printf(m, "Cujo 2.0 bug : %s\n",
(ioc->cujo20_bug ? "yes" : "no"));
len += seq_printf(m, "IO PDIR size : %d bytes (%d entries)\n",
total_pages * 8, total_pages);
#ifdef CCIO_COLLECT_STATS
len += seq_printf(m, "IO PDIR entries : %ld free %ld used (%d%%)\n",
total_pages - ioc->used_pages, ioc->used_pages,
(int)(ioc->used_pages * 100 / total_pages));
#endif
len += seq_printf(m, "Resource bitmap : %d bytes (%d pages)\n",
ioc->res_size, total_pages);
#ifdef CCIO_COLLECT_STATS
min = max = ioc->avg_search[0];
for(j = 0; j < CCIO_SEARCH_SAMPLE; ++j) {
avg += ioc->avg_search[j];
if(ioc->avg_search[j] > max)
max = ioc->avg_search[j];
if(ioc->avg_search[j] < min)
min = ioc->avg_search[j];
}
avg /= CCIO_SEARCH_SAMPLE;
len += seq_printf(m, " Bitmap search : %ld/%ld/%ld (min/avg/max CPU Cycles)\n",
min, avg, max);
len += seq_printf(m, "pci_map_single(): %8ld calls %8ld pages (avg %d/1000)\n",
ioc->msingle_calls, ioc->msingle_pages,
(int)((ioc->msingle_pages * 1000)/ioc->msingle_calls));
/* KLUGE - unmap_sg calls unmap_single for each mapped page */
min = ioc->usingle_calls - ioc->usg_calls;
max = ioc->usingle_pages - ioc->usg_pages;
len += seq_printf(m, "pci_unmap_single: %8ld calls %8ld pages (avg %d/1000)\n",
min, max, (int)((max * 1000)/min));
len += seq_printf(m, "pci_map_sg() : %8ld calls %8ld pages (avg %d/1000)\n",
ioc->msg_calls, ioc->msg_pages,
(int)((ioc->msg_pages * 1000)/ioc->msg_calls));
len += seq_printf(m, "pci_unmap_sg() : %8ld calls %8ld pages (avg %d/1000)\n\n\n",
ioc->usg_calls, ioc->usg_pages,
(int)((ioc->usg_pages * 1000)/ioc->usg_calls));
#endif /* CCIO_COLLECT_STATS */
ioc = ioc->next;
}
return 0;
}
static int ccio_proc_info_open(struct inode *inode, struct file *file)
{
return single_open(file, &ccio_proc_info, NULL);
}
static const struct file_operations ccio_proc_info_fops = {
.owner = THIS_MODULE,
.open = ccio_proc_info_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int ccio_proc_bitmap_info(struct seq_file *m, void *p)
{
int len = 0;
struct ioc *ioc = ioc_list;
while (ioc != NULL) {
u32 *res_ptr = (u32 *)ioc->res_map;
int j;
for (j = 0; j < (ioc->res_size / sizeof(u32)); j++) {
if ((j & 7) == 0)
len += seq_puts(m, "\n ");
len += seq_printf(m, "%08x", *res_ptr);
res_ptr++;
}
len += seq_puts(m, "\n\n");
ioc = ioc->next;
break; /* XXX - remove me */
}
return 0;
}
static int ccio_proc_bitmap_open(struct inode *inode, struct file *file)
{
return single_open(file, &ccio_proc_bitmap_info, NULL);
}
static const struct file_operations ccio_proc_bitmap_fops = {
.owner = THIS_MODULE,
.open = ccio_proc_bitmap_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif /* CONFIG_PROC_FS */
/**
* ccio_find_ioc - Find the ioc in the ioc_list
* @hw_path: The hardware path of the ioc.
*
* This function searches the ioc_list for an ioc that matches
* the provide hardware path.
*/
static struct ioc * ccio_find_ioc(int hw_path)
{
int i;
struct ioc *ioc;
ioc = ioc_list;
for (i = 0; i < ioc_count; i++) {
if (ioc->hw_path == hw_path)
return ioc;
ioc = ioc->next;
}
return NULL;
}
/**
* ccio_get_iommu - Find the iommu which controls this device
* @dev: The parisc device.
*
* This function searches through the registered IOMMU's and returns
* the appropriate IOMMU for the device based on its hardware path.
*/
void * ccio_get_iommu(const struct parisc_device *dev)
{
dev = find_pa_parent_type(dev, HPHW_IOA);
if (!dev)
return NULL;
return ccio_find_ioc(dev->hw_path);
}
#define CUJO_20_STEP 0x10000000 /* inc upper nibble */
/* Cujo 2.0 has a bug which will silently corrupt data being transferred
* to/from certain pages. To avoid this happening, we mark these pages
* as `used', and ensure that nothing will try to allocate from them.
*/
void ccio_cujo20_fixup(struct parisc_device *cujo, u32 iovp)
{
unsigned int idx;
struct parisc_device *dev = parisc_parent(cujo);
struct ioc *ioc = ccio_get_iommu(dev);
u8 *res_ptr;
ioc->cujo20_bug = 1;
res_ptr = ioc->res_map;
idx = PDIR_INDEX(iovp) >> 3;
while (idx < ioc->res_size) {
res_ptr[idx] |= 0xff;
idx += PDIR_INDEX(CUJO_20_STEP) >> 3;
}
}
#if 0
/* GRANT - is this needed for U2 or not? */
/*
** Get the size of the I/O TLB for this I/O MMU.
**
** If spa_shift is non-zero (ie probably U2),
** then calculate the I/O TLB size using spa_shift.
**
** Otherwise we are supposed to get the IODC entry point ENTRY TLB
** and execute it. However, both U2 and Uturn firmware supplies spa_shift.
** I think only Java (K/D/R-class too?) systems don't do this.
*/
static int
ccio_get_iotlb_size(struct parisc_device *dev)
{
if (dev->spa_shift == 0) {
panic("%s() : Can't determine I/O TLB size.\n", __func__);
}
return (1 << dev->spa_shift);
}
#else
/* Uturn supports 256 TLB entries */
#define CCIO_CHAINID_SHIFT 8
#define CCIO_CHAINID_MASK 0xff
#endif /* 0 */
/* We *can't* support JAVA (T600). Venture there at your own risk. */
static const struct parisc_device_id ccio_tbl[] = {
{ HPHW_IOA, HVERSION_REV_ANY_ID, U2_IOA_RUNWAY, 0xb }, /* U2 */
{ HPHW_IOA, HVERSION_REV_ANY_ID, UTURN_IOA_RUNWAY, 0xb }, /* UTurn */
{ 0, }
};
static int ccio_probe(struct parisc_device *dev);
static struct parisc_driver ccio_driver = {
.name = "ccio",
.id_table = ccio_tbl,
.probe = ccio_probe,
};
/**
* ccio_ioc_init - Initialize the I/O Controller
* @ioc: The I/O Controller.
*
* Initialize the I/O Controller which includes setting up the
* I/O Page Directory, the resource map, and initalizing the
* U2/Uturn chip into virtual mode.
*/
static void
ccio_ioc_init(struct ioc *ioc)
{
int i;
unsigned int iov_order;
u32 iova_space_size;
/*
** Determine IOVA Space size from memory size.
**
** Ideally, PCI drivers would register the maximum number
** of DMA they can have outstanding for each device they
** own. Next best thing would be to guess how much DMA
** can be outstanding based on PCI Class/sub-class. Both
** methods still require some "extra" to support PCI
** Hot-Plug/Removal of PCI cards. (aka PCI OLARD).
*/
iova_space_size = (u32) (totalram_pages / count_parisc_driver(&ccio_driver));
/* limit IOVA space size to 1MB-1GB */
if (iova_space_size < (1 << (20 - PAGE_SHIFT))) {
iova_space_size = 1 << (20 - PAGE_SHIFT);
#ifdef __LP64__
} else if (iova_space_size > (1 << (30 - PAGE_SHIFT))) {
iova_space_size = 1 << (30 - PAGE_SHIFT);
#endif
}
/*
** iova space must be log2() in size.
** thus, pdir/res_map will also be log2().
*/
/* We could use larger page sizes in order to *decrease* the number
** of mappings needed. (ie 8k pages means 1/2 the mappings).
**
** Note: Grant Grunder says "Using 8k I/O pages isn't trivial either
** since the pages must also be physically contiguous - typically
** this is the case under linux."
*/
iov_order = get_order(iova_space_size << PAGE_SHIFT);
/* iova_space_size is now bytes, not pages */
iova_space_size = 1 << (iov_order + PAGE_SHIFT);
ioc->pdir_size = (iova_space_size / IOVP_SIZE) * sizeof(u64);
BUG_ON(ioc->pdir_size > 8 * 1024 * 1024); /* max pdir size <= 8MB */
/* Verify it's a power of two */
BUG_ON((1 << get_order(ioc->pdir_size)) != (ioc->pdir_size >> PAGE_SHIFT));
DBG_INIT("%s() hpa 0x%p mem %luMB IOV %dMB (%d bits)\n",
__func__, ioc->ioc_regs,
(unsigned long) totalram_pages >> (20 - PAGE_SHIFT),
iova_space_size>>20,
iov_order + PAGE_SHIFT);
ioc->pdir_base = (u64 *)__get_free_pages(GFP_KERNEL,
get_order(ioc->pdir_size));
if(NULL == ioc->pdir_base) {
panic("%s() could not allocate I/O Page Table\n", __func__);
}
memset(ioc->pdir_base, 0, ioc->pdir_size);
BUG_ON((((unsigned long)ioc->pdir_base) & PAGE_MASK) != (unsigned long)ioc->pdir_base);
DBG_INIT(" base %p\n", ioc->pdir_base);
/* resource map size dictated by pdir_size */
ioc->res_size = (ioc->pdir_size / sizeof(u64)) >> 3;
DBG_INIT("%s() res_size 0x%x\n", __func__, ioc->res_size);
ioc->res_map = (u8 *)__get_free_pages(GFP_KERNEL,
get_order(ioc->res_size));
if(NULL == ioc->res_map) {
panic("%s() could not allocate resource map\n", __func__);
}
memset(ioc->res_map, 0, ioc->res_size);
/* Initialize the res_hint to 16 */
ioc->res_hint = 16;
/* Initialize the spinlock */
spin_lock_init(&ioc->res_lock);
/*
** Chainid is the upper most bits of an IOVP used to determine
** which TLB entry an IOVP will use.
*/
ioc->chainid_shift = get_order(iova_space_size) + PAGE_SHIFT - CCIO_CHAINID_SHIFT;
DBG_INIT(" chainid_shift 0x%x\n", ioc->chainid_shift);
/*
** Initialize IOA hardware
*/
WRITE_U32(CCIO_CHAINID_MASK << ioc->chainid_shift,
&ioc->ioc_regs->io_chain_id_mask);
WRITE_U32(virt_to_phys(ioc->pdir_base),
&ioc->ioc_regs->io_pdir_base);
/*
** Go to "Virtual Mode"
*/
WRITE_U32(IOA_NORMAL_MODE, &ioc->ioc_regs->io_control);
/*
** Initialize all I/O TLB entries to 0 (Valid bit off).
*/
WRITE_U32(0, &ioc->ioc_regs->io_tlb_entry_m);
WRITE_U32(0, &ioc->ioc_regs->io_tlb_entry_l);
for(i = 1 << CCIO_CHAINID_SHIFT; i ; i--) {
WRITE_U32((CMD_TLB_DIRECT_WRITE | (i << ioc->chainid_shift)),
&ioc->ioc_regs->io_command);
}
}
static void __init
ccio_init_resource(struct resource *res, char *name, void __iomem *ioaddr)
{
int result;
res->parent = NULL;
res->flags = IORESOURCE_MEM;
/*
* bracing ((signed) ...) are required for 64bit kernel because
* we only want to sign extend the lower 16 bits of the register.
* The upper 16-bits of range registers are hardcoded to 0xffff.
*/
res->start = (unsigned long)((signed) READ_U32(ioaddr) << 16);
res->end = (unsigned long)((signed) (READ_U32(ioaddr + 4) << 16) - 1);
res->name = name;
/*
* Check if this MMIO range is disable
*/
if (res->end + 1 == res->start)
return;
/* On some platforms (e.g. K-Class), we have already registered
* resources for devices reported by firmware. Some are children
* of ccio.
* "insert" ccio ranges in the mmio hierarchy (/proc/iomem).
*/
result = insert_resource(&iomem_resource, res);
if (result < 0) {
printk(KERN_ERR "%s() failed to claim CCIO bus address space (%08lx,%08lx)\n",
__func__, (unsigned long)res->start, (unsigned long)res->end);
}
}
static void __init ccio_init_resources(struct ioc *ioc)
{
struct resource *res = ioc->mmio_region;
char *name = kmalloc(14, GFP_KERNEL);
snprintf(name, 14, "GSC Bus [%d/]", ioc->hw_path);
ccio_init_resource(res, name, &ioc->ioc_regs->io_io_low);
ccio_init_resource(res + 1, name, &ioc->ioc_regs->io_io_low_hv);
}
static int new_ioc_area(struct resource *res, unsigned long size,
unsigned long min, unsigned long max, unsigned long align)
{
if (max <= min)
return -EBUSY;
res->start = (max - size + 1) &~ (align - 1);
res->end = res->start + size;
/* We might be trying to expand the MMIO range to include
* a child device that has already registered it's MMIO space.
* Use "insert" instead of request_resource().
*/
if (!insert_resource(&iomem_resource, res))
return 0;
return new_ioc_area(res, size, min, max - size, align);
}
static int expand_ioc_area(struct resource *res, unsigned long size,
unsigned long min, unsigned long max, unsigned long align)
{
unsigned long start, len;
if (!res->parent)
return new_ioc_area(res, size, min, max, align);
start = (res->start - size) &~ (align - 1);
len = res->end - start + 1;
if (start >= min) {
if (!adjust_resource(res, start, len))
return 0;
}
start = res->start;
len = ((size + res->end + align) &~ (align - 1)) - start;
if (start + len <= max) {
if (!adjust_resource(res, start, len))
return 0;
}
return -EBUSY;
}
/*
* Dino calls this function. Beware that we may get called on systems
* which have no IOC (725, B180, C160L, etc) but do have a Dino.
* So it's legal to find no parent IOC.
*
* Some other issues: one of the resources in the ioc may be unassigned.
*/
int ccio_allocate_resource(const struct parisc_device *dev,
struct resource *res, unsigned long size,
unsigned long min, unsigned long max, unsigned long align)
{
struct resource *parent = &iomem_resource;
struct ioc *ioc = ccio_get_iommu(dev);
if (!ioc)
goto out;
parent = ioc->mmio_region;
if (parent->parent &&
!allocate_resource(parent, res, size, min, max, align, NULL, NULL))
return 0;
if ((parent + 1)->parent &&
!allocate_resource(parent + 1, res, size, min, max, align,
NULL, NULL))
return 0;
if (!expand_ioc_area(parent, size, min, max, align)) {
__raw_writel(((parent->start)>>16) | 0xffff0000,
&ioc->ioc_regs->io_io_low);
__raw_writel(((parent->end)>>16) | 0xffff0000,
&ioc->ioc_regs->io_io_high);
} else if (!expand_ioc_area(parent + 1, size, min, max, align)) {
parent++;
__raw_writel(((parent->start)>>16) | 0xffff0000,
&ioc->ioc_regs->io_io_low_hv);
__raw_writel(((parent->end)>>16) | 0xffff0000,
&ioc->ioc_regs->io_io_high_hv);
} else {
return -EBUSY;
}
out:
return allocate_resource(parent, res, size, min, max, align, NULL,NULL);
}
int ccio_request_resource(const struct parisc_device *dev,
struct resource *res)
{
struct resource *parent;
struct ioc *ioc = ccio_get_iommu(dev);
if (!ioc) {
parent = &iomem_resource;
} else if ((ioc->mmio_region->start <= res->start) &&
(res->end <= ioc->mmio_region->end)) {
parent = ioc->mmio_region;
} else if (((ioc->mmio_region + 1)->start <= res->start) &&
(res->end <= (ioc->mmio_region + 1)->end)) {
parent = ioc->mmio_region + 1;
} else {
return -EBUSY;
}
/* "transparent" bus bridges need to register MMIO resources
* firmware assigned them. e.g. children of hppb.c (e.g. K-class)
* registered their resources in the PDC "bus walk" (See
* arch/parisc/kernel/inventory.c).
*/
return insert_resource(parent, res);
}
/**
* ccio_probe - Determine if ccio should claim this device.
* @dev: The device which has been found
*
* Determine if ccio should claim this chip (return 0) or not (return 1).
* If so, initialize the chip and tell other partners in crime they
* have work to do.
*/
static int __init ccio_probe(struct parisc_device *dev)
{
int i;
struct ioc *ioc, **ioc_p = &ioc_list;
ioc = kzalloc(sizeof(struct ioc), GFP_KERNEL);
if (ioc == NULL) {
printk(KERN_ERR MODULE_NAME ": memory allocation failure\n");
return 1;
}
ioc->name = dev->id.hversion == U2_IOA_RUNWAY ? "U2" : "UTurn";
printk(KERN_INFO "Found %s at 0x%lx\n", ioc->name,
(unsigned long)dev->hpa.start);
for (i = 0; i < ioc_count; i++) {
ioc_p = &(*ioc_p)->next;
}
*ioc_p = ioc;
ioc->hw_path = dev->hw_path;
ioc->ioc_regs = ioremap_nocache(dev->hpa.start, 4096);
ccio_ioc_init(ioc);
ccio_init_resources(ioc);
hppa_dma_ops = &ccio_ops;
dev->dev.platform_data = kzalloc(sizeof(struct pci_hba_data), GFP_KERNEL);
/* if this fails, no I/O cards will work, so may as well bug */
BUG_ON(dev->dev.platform_data == NULL);
HBA_DATA(dev->dev.platform_data)->iommu = ioc;
#ifdef CONFIG_PROC_FS
if (ioc_count == 0) {
proc_create(MODULE_NAME, 0, proc_runway_root,
&ccio_proc_info_fops);
proc_create(MODULE_NAME"-bitmap", 0, proc_runway_root,
&ccio_proc_bitmap_fops);
}
#endif
ioc_count++;
parisc_has_iommu();
return 0;
}
/**
* ccio_init - ccio initialization procedure.
*
* Register this driver.
*/
void __init ccio_init(void)
{
register_parisc_driver(&ccio_driver);
}
| gpl-2.0 |
LibiSC/Smt520Test | net/atm/atm_misc.c | 9678 | 2635 | /* net/atm/atm_misc.c - Various functions for use by ATM drivers */
/* Written 1995-2000 by Werner Almesberger, EPFL ICA */
#include <linux/module.h>
#include <linux/atm.h>
#include <linux/atmdev.h>
#include <linux/skbuff.h>
#include <linux/sonet.h>
#include <linux/bitops.h>
#include <linux/errno.h>
#include <linux/atomic.h>
int atm_charge(struct atm_vcc *vcc, int truesize)
{
atm_force_charge(vcc, truesize);
if (atomic_read(&sk_atm(vcc)->sk_rmem_alloc) <= sk_atm(vcc)->sk_rcvbuf)
return 1;
atm_return(vcc, truesize);
atomic_inc(&vcc->stats->rx_drop);
return 0;
}
EXPORT_SYMBOL(atm_charge);
struct sk_buff *atm_alloc_charge(struct atm_vcc *vcc, int pdu_size,
gfp_t gfp_flags)
{
struct sock *sk = sk_atm(vcc);
int guess = SKB_TRUESIZE(pdu_size);
atm_force_charge(vcc, guess);
if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) {
struct sk_buff *skb = alloc_skb(pdu_size, gfp_flags);
if (skb) {
atomic_add(skb->truesize-guess,
&sk->sk_rmem_alloc);
return skb;
}
}
atm_return(vcc, guess);
atomic_inc(&vcc->stats->rx_drop);
return NULL;
}
EXPORT_SYMBOL(atm_alloc_charge);
/*
* atm_pcr_goal returns the positive PCR if it should be rounded up, the
* negative PCR if it should be rounded down, and zero if the maximum available
* bandwidth should be used.
*
* The rules are as follows (* = maximum, - = absent (0), x = value "x",
* (x+ = x or next value above x, x- = x or next value below):
*
* min max pcr result min max pcr result
* - - - * (UBR only) x - - x+
* - - * * x - * *
* - - z z- x - z z-
* - * - * x * - x+
* - * * * x * * *
* - * z z- x * z z-
* - y - y- x y - x+
* - y * y- x y * y-
* - y z z- x y z z-
*
* All non-error cases can be converted with the following simple set of rules:
*
* if pcr == z then z-
* else if min == x && pcr == - then x+
* else if max == y then y-
* else *
*/
int atm_pcr_goal(const struct atm_trafprm *tp)
{
if (tp->pcr && tp->pcr != ATM_MAX_PCR)
return -tp->pcr;
if (tp->min_pcr && !tp->pcr)
return tp->min_pcr;
if (tp->max_pcr != ATM_MAX_PCR)
return -tp->max_pcr;
return 0;
}
EXPORT_SYMBOL(atm_pcr_goal);
void sonet_copy_stats(struct k_sonet_stats *from, struct sonet_stats *to)
{
#define __HANDLE_ITEM(i) to->i = atomic_read(&from->i)
__SONET_ITEMS
#undef __HANDLE_ITEM
}
EXPORT_SYMBOL(sonet_copy_stats);
void sonet_subtract_stats(struct k_sonet_stats *from, struct sonet_stats *to)
{
#define __HANDLE_ITEM(i) atomic_sub(to->i, &from->i)
__SONET_ITEMS
#undef __HANDLE_ITEM
}
EXPORT_SYMBOL(sonet_subtract_stats);
| gpl-2.0 |
coliby/terasic_MTL | security/selinux/ss/status.c | 11982 | 3482 | /*
* mmap based event notifications for SELinux
*
* Author: KaiGai Kohei <kaigai@ak.jp.nec.com>
*
* Copyright (C) 2010 NEC corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/gfp.h>
#include <linux/mm.h>
#include <linux/mutex.h>
#include "avc.h"
#include "services.h"
/*
* The selinux_status_page shall be exposed to userspace applications
* using mmap interface on /selinux/status.
* It enables to notify applications a few events that will cause reset
* of userspace access vector without context switching.
*
* The selinux_kernel_status structure on the head of status page is
* protected from concurrent accesses using seqlock logic, so userspace
* application should reference the status page according to the seqlock
* logic.
*
* Typically, application checks status->sequence at the head of access
* control routine. If it is odd-number, kernel is updating the status,
* so please wait for a moment. If it is changed from the last sequence
* number, it means something happen, so application will reset userspace
* avc, if needed.
* In most cases, application shall confirm the kernel status is not
* changed without any system call invocations.
*/
static struct page *selinux_status_page;
static DEFINE_MUTEX(selinux_status_lock);
/*
* selinux_kernel_status_page
*
* It returns a reference to selinux_status_page. If the status page is
* not allocated yet, it also tries to allocate it at the first time.
*/
struct page *selinux_kernel_status_page(void)
{
struct selinux_kernel_status *status;
struct page *result = NULL;
mutex_lock(&selinux_status_lock);
if (!selinux_status_page) {
selinux_status_page = alloc_page(GFP_KERNEL|__GFP_ZERO);
if (selinux_status_page) {
status = page_address(selinux_status_page);
status->version = SELINUX_KERNEL_STATUS_VERSION;
status->sequence = 0;
status->enforcing = selinux_enforcing;
/*
* NOTE: the next policyload event shall set
* a positive value on the status->policyload,
* although it may not be 1, but never zero.
* So, application can know it was updated.
*/
status->policyload = 0;
status->deny_unknown = !security_get_allow_unknown();
}
}
result = selinux_status_page;
mutex_unlock(&selinux_status_lock);
return result;
}
/*
* selinux_status_update_setenforce
*
* It updates status of the current enforcing/permissive mode.
*/
void selinux_status_update_setenforce(int enforcing)
{
struct selinux_kernel_status *status;
mutex_lock(&selinux_status_lock);
if (selinux_status_page) {
status = page_address(selinux_status_page);
status->sequence++;
smp_wmb();
status->enforcing = enforcing;
smp_wmb();
status->sequence++;
}
mutex_unlock(&selinux_status_lock);
}
/*
* selinux_status_update_policyload
*
* It updates status of the times of policy reloaded, and current
* setting of deny_unknown.
*/
void selinux_status_update_policyload(int seqno)
{
struct selinux_kernel_status *status;
mutex_lock(&selinux_status_lock);
if (selinux_status_page) {
status = page_address(selinux_status_page);
status->sequence++;
smp_wmb();
status->policyload = seqno;
status->deny_unknown = !security_get_allow_unknown();
smp_wmb();
status->sequence++;
}
mutex_unlock(&selinux_status_lock);
}
| gpl-2.0 |
haiphamspkt/haiphamkernel | arch/cris/mm/tlb.c | 13774 | 2703 | /*
* linux/arch/cris/mm/tlb.c
*
* Copyright (C) 2000, 2001 Axis Communications AB
*
* Authors: Bjorn Wesen (bjornw@axis.com)
*
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <asm/tlb.h>
#define D(x)
/* The TLB can host up to 64 different mm contexts at the same time.
* The running context is R_MMU_CONTEXT, and each TLB entry contains a
* page_id that has to match to give a hit. In page_id_map, we keep track
* of which mm we have assigned to which page_id, so that we know when
* to invalidate TLB entries.
*
* The last page_id is never running - it is used as an invalid page_id
* so we can make TLB entries that will never match.
*
* Notice that we need to make the flushes atomic, otherwise an interrupt
* handler that uses vmalloced memory might cause a TLB load in the middle
* of a flush causing.
*/
struct mm_struct *page_id_map[NUM_PAGEID];
static int map_replace_ptr = 1; /* which page_id_map entry to replace next */
/* the following functions are similar to those used in the PPC port */
static inline void
alloc_context(struct mm_struct *mm)
{
struct mm_struct *old_mm;
D(printk("tlb: alloc context %d (%p)\n", map_replace_ptr, mm));
/* did we replace an mm ? */
old_mm = page_id_map[map_replace_ptr];
if(old_mm) {
/* throw out any TLB entries belonging to the mm we replace
* in the map
*/
flush_tlb_mm(old_mm);
old_mm->context.page_id = NO_CONTEXT;
}
/* insert it into the page_id_map */
mm->context.page_id = map_replace_ptr;
page_id_map[map_replace_ptr] = mm;
map_replace_ptr++;
if(map_replace_ptr == INVALID_PAGEID)
map_replace_ptr = 0; /* wrap around */
}
/*
* if needed, get a new MMU context for the mm. otherwise nothing is done.
*/
void
get_mmu_context(struct mm_struct *mm)
{
if(mm->context.page_id == NO_CONTEXT)
alloc_context(mm);
}
/* called by __exit_mm to destroy the used MMU context if any before
* destroying the mm itself. this is only called when the last user of the mm
* drops it.
*
* the only thing we really need to do here is mark the used PID slot
* as empty.
*/
void
destroy_context(struct mm_struct *mm)
{
if(mm->context.page_id != NO_CONTEXT) {
D(printk("destroy_context %d (%p)\n", mm->context.page_id, mm));
flush_tlb_mm(mm); /* TODO this might be redundant ? */
page_id_map[mm->context.page_id] = NULL;
}
}
/* called once during VM initialization, from init.c */
void __init
tlb_init(void)
{
int i;
/* clear the page_id map */
for (i = 1; i < ARRAY_SIZE(page_id_map); i++)
page_id_map[i] = NULL;
/* invalidate the entire TLB */
flush_tlb_all();
/* the init_mm has context 0 from the boot */
page_id_map[0] = &init_mm;
}
| gpl-2.0 |
dmachaty/linux-bananapro | net/sunrpc/xprtrdma/physical_ops.c | 207 | 2448 | /*
* Copyright (c) 2015 Oracle. All rights reserved.
* Copyright (c) 2003-2007 Network Appliance, Inc. All rights reserved.
*/
/* No-op chunk preparation. All client memory is pre-registered.
* Sometimes referred to as ALLPHYSICAL mode.
*
* Physical registration is simple because all client memory is
* pre-registered and never deregistered. This mode is good for
* adapter bring up, but is considered not safe: the server is
* trusted not to abuse its access to client memory not involved
* in RDMA I/O.
*/
#include "xprt_rdma.h"
#if IS_ENABLED(CONFIG_SUNRPC_DEBUG)
# define RPCDBG_FACILITY RPCDBG_TRANS
#endif
static int
physical_op_open(struct rpcrdma_ia *ia, struct rpcrdma_ep *ep,
struct rpcrdma_create_data_internal *cdata)
{
struct ib_mr *mr;
/* Obtain an rkey to use for RPC data payloads.
*/
mr = ib_get_dma_mr(ia->ri_pd,
IB_ACCESS_LOCAL_WRITE |
IB_ACCESS_REMOTE_WRITE |
IB_ACCESS_REMOTE_READ);
if (IS_ERR(mr)) {
pr_err("%s: ib_get_dma_mr for failed with %lX\n",
__func__, PTR_ERR(mr));
return -ENOMEM;
}
ia->ri_dma_mr = mr;
return 0;
}
/* PHYSICAL memory registration conveys one page per chunk segment.
*/
static size_t
physical_op_maxpages(struct rpcrdma_xprt *r_xprt)
{
return min_t(unsigned int, RPCRDMA_MAX_DATA_SEGS,
rpcrdma_max_segments(r_xprt));
}
static int
physical_op_init(struct rpcrdma_xprt *r_xprt)
{
return 0;
}
/* The client's physical memory is already exposed for
* remote access via RDMA READ or RDMA WRITE.
*/
static int
physical_op_map(struct rpcrdma_xprt *r_xprt, struct rpcrdma_mr_seg *seg,
int nsegs, bool writing)
{
struct rpcrdma_ia *ia = &r_xprt->rx_ia;
rpcrdma_map_one(ia->ri_device, seg, rpcrdma_data_dir(writing));
seg->mr_rkey = ia->ri_dma_mr->rkey;
seg->mr_base = seg->mr_dma;
seg->mr_nsegs = 1;
return 1;
}
/* Unmap a memory region, but leave it registered.
*/
static int
physical_op_unmap(struct rpcrdma_xprt *r_xprt, struct rpcrdma_mr_seg *seg)
{
struct rpcrdma_ia *ia = &r_xprt->rx_ia;
rpcrdma_unmap_one(ia->ri_device, seg);
return 1;
}
static void
physical_op_destroy(struct rpcrdma_buffer *buf)
{
}
const struct rpcrdma_memreg_ops rpcrdma_physical_memreg_ops = {
.ro_map = physical_op_map,
.ro_unmap = physical_op_unmap,
.ro_open = physical_op_open,
.ro_maxpages = physical_op_maxpages,
.ro_init = physical_op_init,
.ro_destroy = physical_op_destroy,
.ro_displayname = "physical",
};
| gpl-2.0 |
joaquimorg/android_kernel_huawei_u8510 | arch/arm/mach-msm/smd_nmea.c | 719 | 4558 | /* Copyright (c) 2008-2009, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*/
/*
* SMD NMEA Driver -- Provides GPS NMEA device to SMD port interface.
*
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/wait.h>
#include <linux/sched.h>
#include <linux/miscdevice.h>
#include <linux/workqueue.h>
#include <linux/uaccess.h>
#include <mach/msm_smd.h>
#define MAX_BUF_SIZE 200
static DEFINE_MUTEX(nmea_ch_lock);
static DEFINE_MUTEX(nmea_rx_buf_lock);
static DECLARE_WAIT_QUEUE_HEAD(nmea_wait_queue);
struct nmea_device_t {
struct miscdevice misc;
struct smd_channel *ch;
unsigned char rx_buf[MAX_BUF_SIZE];
unsigned int bytes_read;
};
struct nmea_device_t *nmea_devp;
static void nmea_work_func(struct work_struct *ws)
{
int sz;
for (;;) {
sz = smd_cur_packet_size(nmea_devp->ch);
if (sz == 0)
break;
if (sz > smd_read_avail(nmea_devp->ch))
break;
if (sz > MAX_BUF_SIZE) {
smd_read(nmea_devp->ch, 0, sz);
continue;
}
mutex_lock(&nmea_rx_buf_lock);
if (smd_read(nmea_devp->ch, nmea_devp->rx_buf, sz) != sz) {
mutex_unlock(&nmea_rx_buf_lock);
printk(KERN_ERR "nmea: not enough data?!\n");
continue;
}
nmea_devp->bytes_read = sz;
mutex_unlock(&nmea_rx_buf_lock);
wake_up_interruptible(&nmea_wait_queue);
}
}
struct workqueue_struct *nmea_wq;
static DECLARE_WORK(nmea_work, nmea_work_func);
static void nmea_notify(void *priv, unsigned event)
{
switch (event) {
case SMD_EVENT_DATA: {
int sz;
sz = smd_cur_packet_size(nmea_devp->ch);
if ((sz > 0) && (sz <= smd_read_avail(nmea_devp->ch)))
queue_work(nmea_wq, &nmea_work);
break;
}
case SMD_EVENT_OPEN:
printk(KERN_INFO "nmea: smd opened\n");
break;
case SMD_EVENT_CLOSE:
printk(KERN_INFO "nmea: smd closed\n");
break;
}
}
static ssize_t nmea_read(struct file *fp, char __user *buf,
size_t count, loff_t *pos)
{
int r;
int bytes_read;
r = wait_event_interruptible(nmea_wait_queue,
nmea_devp->bytes_read);
if (r < 0) {
/* qualify error message */
if (r != -ERESTARTSYS) {
/* we get this anytime a signal comes in */
printk(KERN_ERR "ERROR:%s:%i:%s: "
"wait_event_interruptible ret %i\n",
__FILE__,
__LINE__,
__func__,
r
);
}
return r;
}
mutex_lock(&nmea_rx_buf_lock);
bytes_read = nmea_devp->bytes_read;
nmea_devp->bytes_read = 0;
r = copy_to_user(buf, nmea_devp->rx_buf, bytes_read);
mutex_unlock(&nmea_rx_buf_lock);
if (r > 0) {
printk(KERN_ERR "ERROR:%s:%i:%s: "
"copy_to_user could not copy %i bytes.\n",
__FILE__,
__LINE__,
__func__,
r);
return r;
}
return bytes_read;
}
static int nmea_open(struct inode *ip, struct file *fp)
{
int r = 0;
mutex_lock(&nmea_ch_lock);
if (nmea_devp->ch == 0)
r = smd_open("GPSNMEA", &nmea_devp->ch, nmea_devp, nmea_notify);
mutex_unlock(&nmea_ch_lock);
return r;
}
static int nmea_release(struct inode *ip, struct file *fp)
{
int r = 0;
mutex_lock(&nmea_ch_lock);
if (nmea_devp->ch != 0) {
r = smd_close(nmea_devp->ch);
nmea_devp->ch = 0;
}
mutex_unlock(&nmea_ch_lock);
return r;
}
static const struct file_operations nmea_fops = {
.owner = THIS_MODULE,
.read = nmea_read,
.open = nmea_open,
.release = nmea_release,
};
static struct nmea_device_t nmea_device = {
.misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = "nmea",
.fops = &nmea_fops,
}
};
static void __exit nmea_exit(void)
{
destroy_workqueue(nmea_wq);
misc_deregister(&nmea_device.misc);
}
static int __init nmea_init(void)
{
int ret;
nmea_device.bytes_read = 0;
nmea_devp = &nmea_device;
nmea_wq = create_singlethread_workqueue("nmea");
if (nmea_wq == 0)
return -ENOMEM;
ret = misc_register(&nmea_device.misc);
return ret;
}
module_init(nmea_init);
module_exit(nmea_exit);
MODULE_DESCRIPTION("MSM Shared Memory NMEA Driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
ryanli/kernel_huawei_c8650 | arch/arm/mach-u300/mmc.c | 719 | 4676 | /*
*
* arch/arm/mach-u300/mmc.c
*
*
* Copyright (C) 2009 ST-Ericsson AB
* License terms: GNU General Public License (GPL) version 2
*
* Author: Linus Walleij <linus.walleij@stericsson.com>
* Author: Johan Lundin <johan.lundin@stericsson.com>
* Author: Jonas Aaberg <jonas.aberg@stericsson.com>
*/
#include <linux/device.h>
#include <linux/amba/bus.h>
#include <linux/mmc/host.h>
#include <linux/input.h>
#include <linux/workqueue.h>
#include <linux/delay.h>
#include <linux/regulator/consumer.h>
#include <linux/regulator/machine.h>
#include <linux/gpio.h>
#include <linux/amba/mmci.h>
#include <linux/slab.h>
#include "mmc.h"
#include "padmux.h"
struct mmci_card_event {
struct input_dev *mmc_input;
int mmc_inserted;
struct work_struct workq;
struct mmci_platform_data mmc0_plat_data;
};
static unsigned int mmc_status(struct device *dev)
{
struct mmci_card_event *mmci_card = container_of(
dev->platform_data,
struct mmci_card_event, mmc0_plat_data);
return mmci_card->mmc_inserted;
}
static int mmci_callback(void *data)
{
struct mmci_card_event *mmci_card = data;
disable_irq_on_gpio_pin(U300_GPIO_PIN_MMC_CD);
schedule_work(&mmci_card->workq);
return 0;
}
static ssize_t gpio_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct mmci_card_event *mmci_card = container_of(
dev->platform_data,
struct mmci_card_event, mmc0_plat_data);
return sprintf(buf, "%d\n", !mmci_card->mmc_inserted);
}
static DEVICE_ATTR(mmc_inserted, S_IRUGO, gpio_show, NULL);
static void _mmci_callback(struct work_struct *ws)
{
struct mmci_card_event *mmci_card = container_of(
ws,
struct mmci_card_event, workq);
mdelay(20);
mmci_card->mmc_inserted = !!gpio_get_value(U300_GPIO_PIN_MMC_CD);
input_report_switch(mmci_card->mmc_input, KEY_INSERT,
!mmci_card->mmc_inserted);
input_sync(mmci_card->mmc_input);
pr_debug("MMC/SD card was %s\n",
mmci_card->mmc_inserted ? "removed" : "inserted");
enable_irq_on_gpio_pin(U300_GPIO_PIN_MMC_CD, !mmci_card->mmc_inserted);
}
int __devinit mmc_init(struct amba_device *adev)
{
struct mmci_card_event *mmci_card;
struct device *mmcsd_device = &adev->dev;
struct pmx *pmx;
int ret = 0;
mmci_card = kzalloc(sizeof(struct mmci_card_event), GFP_KERNEL);
if (!mmci_card)
return -ENOMEM;
/*
* Do not set ocr_mask or voltage translation function,
* we have a regulator we can control instead.
*/
/* Nominally 2.85V on our platform */
mmci_card->mmc0_plat_data.f_max = 24000000;
mmci_card->mmc0_plat_data.status = mmc_status;
mmci_card->mmc0_plat_data.gpio_wp = -1;
mmci_card->mmc0_plat_data.gpio_cd = -1;
mmci_card->mmc0_plat_data.capabilities = MMC_CAP_MMC_HIGHSPEED |
MMC_CAP_SD_HIGHSPEED | MMC_CAP_4_BIT_DATA | MMC_CAP_8_BIT_DATA;
mmcsd_device->platform_data = (void *) &mmci_card->mmc0_plat_data;
INIT_WORK(&mmci_card->workq, _mmci_callback);
ret = gpio_request(U300_GPIO_PIN_MMC_CD, "MMC card detection");
if (ret) {
printk(KERN_CRIT "Could not allocate MMC card detection " \
"GPIO pin\n");
goto out;
}
ret = gpio_direction_input(U300_GPIO_PIN_MMC_CD);
if (ret) {
printk(KERN_CRIT "Invalid GPIO pin requested\n");
goto out;
}
ret = sysfs_create_file(&mmcsd_device->kobj,
&dev_attr_mmc_inserted.attr);
if (ret)
goto out;
mmci_card->mmc_input = input_allocate_device();
if (!mmci_card->mmc_input) {
printk(KERN_CRIT "Could not allocate MMC input device\n");
return -ENOMEM;
}
mmci_card->mmc_input->name = "MMC insert notification";
mmci_card->mmc_input->id.bustype = BUS_HOST;
mmci_card->mmc_input->id.vendor = 0;
mmci_card->mmc_input->id.product = 0;
mmci_card->mmc_input->id.version = 0x0100;
mmci_card->mmc_input->dev.parent = mmcsd_device;
input_set_capability(mmci_card->mmc_input, EV_SW, KEY_INSERT);
/*
* Since this must always be compiled into the kernel, this input
* is never unregistered or free:ed.
*/
ret = input_register_device(mmci_card->mmc_input);
if (ret) {
input_free_device(mmci_card->mmc_input);
goto out;
}
input_set_drvdata(mmci_card->mmc_input, mmci_card);
/*
* Setup padmuxing for MMC. Since this must always be
* compiled into the kernel, pmx is never released.
*/
pmx = pmx_get(mmcsd_device, U300_APP_PMX_MMC_SETTING);
if (IS_ERR(pmx))
pr_warning("Could not get padmux handle\n");
else {
ret = pmx_activate(mmcsd_device, pmx);
if (IS_ERR_VALUE(ret))
pr_warning("Could not activate padmuxing\n");
}
ret = gpio_register_callback(U300_GPIO_PIN_MMC_CD, mmci_callback,
mmci_card);
schedule_work(&mmci_card->workq);
printk(KERN_INFO "Registered MMC insert/remove notification\n");
out:
return ret;
}
| gpl-2.0 |
SlimRoms/kernel_motorola_msm8226 | block/fiops-iosched.c | 975 | 17831 | /*
* IOPS based IO scheduler. Based on CFQ.
* Copyright (C) 2003 Jens Axboe <axboe@kernel.dk>
* Shaohua Li <shli@kernel.org>
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/blkdev.h>
#include <linux/elevator.h>
#include <linux/jiffies.h>
#include <linux/rbtree.h>
#include <linux/ioprio.h>
#include <linux/blktrace_api.h>
#include "blk.h"
#define VIOS_SCALE_SHIFT 10
#define VIOS_SCALE (1 << VIOS_SCALE_SHIFT)
#define VIOS_READ_SCALE (1)
#define VIOS_WRITE_SCALE (1)
#define VIOS_SYNC_SCALE (2)
#define VIOS_ASYNC_SCALE (5)
#define VIOS_PRIO_SCALE (5)
struct fiops_rb_root {
struct rb_root rb;
struct rb_node *left;
unsigned count;
u64 min_vios;
};
#define FIOPS_RB_ROOT (struct fiops_rb_root) { .rb = RB_ROOT}
enum wl_prio_t {
IDLE_WORKLOAD = 0,
BE_WORKLOAD = 1,
RT_WORKLOAD = 2,
FIOPS_PRIO_NR,
};
struct fiops_data {
struct request_queue *queue;
struct fiops_rb_root service_tree[FIOPS_PRIO_NR];
unsigned int busy_queues;
unsigned int in_flight[2];
struct work_struct unplug_work;
unsigned int read_scale;
unsigned int write_scale;
unsigned int sync_scale;
unsigned int async_scale;
};
struct fiops_ioc {
struct io_cq icq;
unsigned int flags;
struct fiops_data *fiopsd;
struct rb_node rb_node;
u64 vios; /* key in service_tree */
struct fiops_rb_root *service_tree;
unsigned int in_flight;
struct rb_root sort_list;
struct list_head fifo;
pid_t pid;
unsigned short ioprio;
enum wl_prio_t wl_type;
};
#define ioc_service_tree(ioc) (&((ioc)->fiopsd->service_tree[(ioc)->wl_type]))
#define RQ_CIC(rq) icq_to_cic((rq)->elv.icq)
enum ioc_state_flags {
FIOPS_IOC_FLAG_on_rr = 0, /* on round-robin busy list */
FIOPS_IOC_FLAG_prio_changed, /* task priority has changed */
};
#define FIOPS_IOC_FNS(name) \
static inline void fiops_mark_ioc_##name(struct fiops_ioc *ioc) \
{ \
ioc->flags |= (1 << FIOPS_IOC_FLAG_##name); \
} \
static inline void fiops_clear_ioc_##name(struct fiops_ioc *ioc) \
{ \
ioc->flags &= ~(1 << FIOPS_IOC_FLAG_##name); \
} \
static inline int fiops_ioc_##name(const struct fiops_ioc *ioc) \
{ \
return ((ioc)->flags & (1 << FIOPS_IOC_FLAG_##name)) != 0; \
}
FIOPS_IOC_FNS(on_rr);
FIOPS_IOC_FNS(prio_changed);
#undef FIOPS_IOC_FNS
#define fiops_log_ioc(fiopsd, ioc, fmt, args...) \
blk_add_trace_msg((fiopsd)->queue, "ioc%d " fmt, (ioc)->pid, ##args)
#define fiops_log(fiopsd, fmt, args...) \
blk_add_trace_msg((fiopsd)->queue, "fiops " fmt, ##args)
enum wl_prio_t fiops_wl_type(short prio_class)
{
if (prio_class == IOPRIO_CLASS_RT)
return RT_WORKLOAD;
if (prio_class == IOPRIO_CLASS_BE)
return BE_WORKLOAD;
return IDLE_WORKLOAD;
}
static inline struct fiops_ioc *icq_to_cic(struct io_cq *icq)
{
/* cic->icq is the first member, %NULL will convert to %NULL */
return container_of(icq, struct fiops_ioc, icq);
}
static inline struct fiops_ioc *fiops_cic_lookup(struct fiops_data *fiopsd,
struct io_context *ioc)
{
if (ioc)
return icq_to_cic(ioc_lookup_icq(ioc, fiopsd->queue));
return NULL;
}
/*
* The below is leftmost cache rbtree addon
*/
static struct fiops_ioc *fiops_rb_first(struct fiops_rb_root *root)
{
/* Service tree is empty */
if (!root->count)
return NULL;
if (!root->left)
root->left = rb_first(&root->rb);
if (root->left)
return rb_entry(root->left, struct fiops_ioc, rb_node);
return NULL;
}
static void rb_erase_init(struct rb_node *n, struct rb_root *root)
{
rb_erase(n, root);
RB_CLEAR_NODE(n);
}
static void fiops_rb_erase(struct rb_node *n, struct fiops_rb_root *root)
{
if (root->left == n)
root->left = NULL;
rb_erase_init(n, &root->rb);
--root->count;
}
static inline u64 max_vios(u64 min_vios, u64 vios)
{
s64 delta = (s64)(vios - min_vios);
if (delta > 0)
min_vios = vios;
return min_vios;
}
static void fiops_update_min_vios(struct fiops_rb_root *service_tree)
{
struct fiops_ioc *ioc;
ioc = fiops_rb_first(service_tree);
if (!ioc)
return;
service_tree->min_vios = max_vios(service_tree->min_vios, ioc->vios);
}
/*
* The fiopsd->service_trees holds all pending fiops_ioc's that have
* requests waiting to be processed. It is sorted in the order that
* we will service the queues.
*/
static void fiops_service_tree_add(struct fiops_data *fiopsd,
struct fiops_ioc *ioc)
{
struct rb_node **p, *parent;
struct fiops_ioc *__ioc;
struct fiops_rb_root *service_tree = ioc_service_tree(ioc);
u64 vios;
int left;
/* New added IOC */
if (RB_EMPTY_NODE(&ioc->rb_node)) {
if (ioc->in_flight > 0)
vios = ioc->vios;
else
vios = max_vios(service_tree->min_vios, ioc->vios);
} else {
vios = ioc->vios;
/* ioc->service_tree might not equal to service_tree */
fiops_rb_erase(&ioc->rb_node, ioc->service_tree);
ioc->service_tree = NULL;
}
fiops_log_ioc(fiopsd, ioc, "service tree add, vios %lld", vios);
left = 1;
parent = NULL;
ioc->service_tree = service_tree;
p = &service_tree->rb.rb_node;
while (*p) {
struct rb_node **n;
parent = *p;
__ioc = rb_entry(parent, struct fiops_ioc, rb_node);
/*
* sort by key, that represents service time.
*/
if (vios < __ioc->vios)
n = &(*p)->rb_left;
else {
n = &(*p)->rb_right;
left = 0;
}
p = n;
}
if (left)
service_tree->left = &ioc->rb_node;
ioc->vios = vios;
rb_link_node(&ioc->rb_node, parent, p);
rb_insert_color(&ioc->rb_node, &service_tree->rb);
service_tree->count++;
fiops_update_min_vios(service_tree);
}
/*
* Update ioc's position in the service tree.
*/
static void fiops_resort_rr_list(struct fiops_data *fiopsd,
struct fiops_ioc *ioc)
{
/*
* Resorting requires the ioc to be on the RR list already.
*/
if (fiops_ioc_on_rr(ioc))
fiops_service_tree_add(fiopsd, ioc);
}
/*
* add to busy list of queues for service, trying to be fair in ordering
* the pending list according to last request service
*/
static void fiops_add_ioc_rr(struct fiops_data *fiopsd, struct fiops_ioc *ioc)
{
BUG_ON(fiops_ioc_on_rr(ioc));
fiops_mark_ioc_on_rr(ioc);
fiopsd->busy_queues++;
fiops_resort_rr_list(fiopsd, ioc);
}
/*
* Called when the ioc no longer has requests pending, remove it from
* the service tree.
*/
static void fiops_del_ioc_rr(struct fiops_data *fiopsd, struct fiops_ioc *ioc)
{
BUG_ON(!fiops_ioc_on_rr(ioc));
fiops_clear_ioc_on_rr(ioc);
if (!RB_EMPTY_NODE(&ioc->rb_node)) {
fiops_rb_erase(&ioc->rb_node, ioc->service_tree);
ioc->service_tree = NULL;
}
BUG_ON(!fiopsd->busy_queues);
fiopsd->busy_queues--;
}
/*
* rb tree support functions
*/
static void fiops_del_rq_rb(struct request *rq)
{
struct fiops_ioc *ioc = RQ_CIC(rq);
elv_rb_del(&ioc->sort_list, rq);
}
static void fiops_add_rq_rb(struct request *rq)
{
struct fiops_ioc *ioc = RQ_CIC(rq);
struct fiops_data *fiopsd = ioc->fiopsd;
elv_rb_add(&ioc->sort_list, rq);
if (!fiops_ioc_on_rr(ioc))
fiops_add_ioc_rr(fiopsd, ioc);
}
static void fiops_reposition_rq_rb(struct fiops_ioc *ioc, struct request *rq)
{
elv_rb_del(&ioc->sort_list, rq);
fiops_add_rq_rb(rq);
}
static void fiops_remove_request(struct request *rq)
{
list_del_init(&rq->queuelist);
fiops_del_rq_rb(rq);
}
static u64 fiops_scaled_vios(struct fiops_data *fiopsd,
struct fiops_ioc *ioc, struct request *rq)
{
int vios = VIOS_SCALE;
if (rq_data_dir(rq) == WRITE)
vios = vios * fiopsd->write_scale / fiopsd->read_scale;
if (!rq_is_sync(rq))
vios = vios * fiopsd->async_scale / fiopsd->sync_scale;
vios += vios * (ioc->ioprio - IOPRIO_NORM) / VIOS_PRIO_SCALE;
return vios;
}
/* return vios dispatched */
static u64 fiops_dispatch_request(struct fiops_data *fiopsd,
struct fiops_ioc *ioc)
{
struct request *rq;
struct request_queue *q = fiopsd->queue;
rq = rq_entry_fifo(ioc->fifo.next);
fiops_remove_request(rq);
elv_dispatch_add_tail(q, rq);
fiopsd->in_flight[rq_is_sync(rq)]++;
ioc->in_flight++;
return fiops_scaled_vios(fiopsd, ioc, rq);
}
static int fiops_forced_dispatch(struct fiops_data *fiopsd)
{
struct fiops_ioc *ioc;
int dispatched = 0;
int i;
for (i = RT_WORKLOAD; i >= IDLE_WORKLOAD; i--) {
while (!RB_EMPTY_ROOT(&fiopsd->service_tree[i].rb)) {
ioc = fiops_rb_first(&fiopsd->service_tree[i]);
while (!list_empty(&ioc->fifo)) {
fiops_dispatch_request(fiopsd, ioc);
dispatched++;
}
if (fiops_ioc_on_rr(ioc))
fiops_del_ioc_rr(fiopsd, ioc);
}
}
return dispatched;
}
static struct fiops_ioc *fiops_select_ioc(struct fiops_data *fiopsd)
{
struct fiops_ioc *ioc;
struct fiops_rb_root *service_tree = NULL;
int i;
struct request *rq;
for (i = RT_WORKLOAD; i >= IDLE_WORKLOAD; i--) {
if (!RB_EMPTY_ROOT(&fiopsd->service_tree[i].rb)) {
service_tree = &fiopsd->service_tree[i];
break;
}
}
if (!service_tree)
return NULL;
ioc = fiops_rb_first(service_tree);
rq = rq_entry_fifo(ioc->fifo.next);
/*
* we are the only async task and sync requests are in flight, delay a
* moment. If there are other tasks coming, sync tasks have no chance
* to be starved, don't delay
*/
if (!rq_is_sync(rq) && fiopsd->in_flight[1] != 0 &&
service_tree->count == 1) {
fiops_log_ioc(fiopsd, ioc,
"postpone async, in_flight async %d sync %d",
fiopsd->in_flight[0], fiopsd->in_flight[1]);
return NULL;
}
return ioc;
}
static void fiops_charge_vios(struct fiops_data *fiopsd,
struct fiops_ioc *ioc, u64 vios)
{
struct fiops_rb_root *service_tree = ioc->service_tree;
ioc->vios += vios;
fiops_log_ioc(fiopsd, ioc, "charge vios %lld, new vios %lld", vios, ioc->vios);
if (RB_EMPTY_ROOT(&ioc->sort_list))
fiops_del_ioc_rr(fiopsd, ioc);
else
fiops_resort_rr_list(fiopsd, ioc);
fiops_update_min_vios(service_tree);
}
static int fiops_dispatch_requests(struct request_queue *q, int force)
{
struct fiops_data *fiopsd = q->elevator->elevator_data;
struct fiops_ioc *ioc;
u64 vios;
if (unlikely(force))
return fiops_forced_dispatch(fiopsd);
ioc = fiops_select_ioc(fiopsd);
if (!ioc)
return 0;
vios = fiops_dispatch_request(fiopsd, ioc);
fiops_charge_vios(fiopsd, ioc, vios);
return 1;
}
static void fiops_init_prio_data(struct fiops_ioc *cic)
{
struct task_struct *tsk = current;
struct io_context *ioc = cic->icq.ioc;
int ioprio_class;
if (!fiops_ioc_prio_changed(cic))
return;
ioprio_class = IOPRIO_PRIO_CLASS(ioc->ioprio);
switch (ioprio_class) {
default:
printk(KERN_ERR "fiops: bad prio %x\n", ioprio_class);
case IOPRIO_CLASS_NONE:
/*
* no prio set, inherit CPU scheduling settings
*/
cic->ioprio = task_nice_ioprio(tsk);
cic->wl_type = fiops_wl_type(task_nice_ioclass(tsk));
break;
case IOPRIO_CLASS_RT:
cic->ioprio = task_ioprio(ioc);
cic->wl_type = fiops_wl_type(IOPRIO_CLASS_RT);
break;
case IOPRIO_CLASS_BE:
cic->ioprio = task_ioprio(ioc);
cic->wl_type = fiops_wl_type(IOPRIO_CLASS_BE);
break;
case IOPRIO_CLASS_IDLE:
cic->wl_type = fiops_wl_type(IOPRIO_CLASS_IDLE);
cic->ioprio = 7;
break;
}
fiops_clear_ioc_prio_changed(cic);
}
static void fiops_insert_request(struct request_queue *q, struct request *rq)
{
struct fiops_ioc *ioc = RQ_CIC(rq);
fiops_init_prio_data(ioc);
list_add_tail(&rq->queuelist, &ioc->fifo);
fiops_add_rq_rb(rq);
}
/*
* scheduler run of queue, if there are requests pending and no one in the
* driver that will restart queueing
*/
static inline void fiops_schedule_dispatch(struct fiops_data *fiopsd)
{
if (fiopsd->busy_queues)
kblockd_schedule_work(fiopsd->queue, &fiopsd->unplug_work);
}
static void fiops_completed_request(struct request_queue *q, struct request *rq)
{
struct fiops_data *fiopsd = q->elevator->elevator_data;
struct fiops_ioc *ioc = RQ_CIC(rq);
fiopsd->in_flight[rq_is_sync(rq)]--;
ioc->in_flight--;
fiops_log_ioc(fiopsd, ioc, "in_flight %d, busy queues %d",
ioc->in_flight, fiopsd->busy_queues);
if (fiopsd->in_flight[0] + fiopsd->in_flight[1] == 0)
fiops_schedule_dispatch(fiopsd);
}
static struct request *
fiops_find_rq_fmerge(struct fiops_data *fiopsd, struct bio *bio)
{
struct task_struct *tsk = current;
struct fiops_ioc *cic;
cic = fiops_cic_lookup(fiopsd, tsk->io_context);
if (cic) {
sector_t sector = bio->bi_sector + bio_sectors(bio);
return elv_rb_find(&cic->sort_list, sector);
}
return NULL;
}
static int fiops_merge(struct request_queue *q, struct request **req,
struct bio *bio)
{
struct fiops_data *fiopsd = q->elevator->elevator_data;
struct request *__rq;
__rq = fiops_find_rq_fmerge(fiopsd, bio);
if (__rq && elv_rq_merge_ok(__rq, bio)) {
*req = __rq;
return ELEVATOR_FRONT_MERGE;
}
return ELEVATOR_NO_MERGE;
}
static void fiops_merged_request(struct request_queue *q, struct request *req,
int type)
{
if (type == ELEVATOR_FRONT_MERGE) {
struct fiops_ioc *ioc = RQ_CIC(req);
fiops_reposition_rq_rb(ioc, req);
}
}
static void
fiops_merged_requests(struct request_queue *q, struct request *rq,
struct request *next)
{
struct fiops_ioc *ioc = RQ_CIC(rq);
struct fiops_data *fiopsd = q->elevator->elevator_data;
fiops_remove_request(next);
ioc = RQ_CIC(next);
/*
* all requests of this task are merged to other tasks, delete it
* from the service tree.
*/
if (fiops_ioc_on_rr(ioc) && RB_EMPTY_ROOT(&ioc->sort_list))
fiops_del_ioc_rr(fiopsd, ioc);
}
static int fiops_allow_merge(struct request_queue *q, struct request *rq,
struct bio *bio)
{
struct fiops_data *fiopsd = q->elevator->elevator_data;
struct fiops_ioc *cic;
/*
* Lookup the ioc that this bio will be queued with. Allow
* merge only if rq is queued there.
*/
cic = fiops_cic_lookup(fiopsd, current->io_context);
return cic == RQ_CIC(rq);
}
static void fiops_exit_queue(struct elevator_queue *e)
{
struct fiops_data *fiopsd = e->elevator_data;
cancel_work_sync(&fiopsd->unplug_work);
kfree(fiopsd);
}
static void fiops_kick_queue(struct work_struct *work)
{
struct fiops_data *fiopsd =
container_of(work, struct fiops_data, unplug_work);
struct request_queue *q = fiopsd->queue;
spin_lock_irq(q->queue_lock);
__blk_run_queue(q);
spin_unlock_irq(q->queue_lock);
}
static void *fiops_init_queue(struct request_queue *q)
{
struct fiops_data *fiopsd;
int i;
fiopsd = kzalloc_node(sizeof(*fiopsd), GFP_KERNEL, q->node);
if (!fiopsd)
return NULL;
fiopsd->queue = q;
for (i = IDLE_WORKLOAD; i <= RT_WORKLOAD; i++)
fiopsd->service_tree[i] = FIOPS_RB_ROOT;
INIT_WORK(&fiopsd->unplug_work, fiops_kick_queue);
fiopsd->read_scale = VIOS_READ_SCALE;
fiopsd->write_scale = VIOS_WRITE_SCALE;
fiopsd->sync_scale = VIOS_SYNC_SCALE;
fiopsd->async_scale = VIOS_ASYNC_SCALE;
return fiopsd;
}
static void fiops_init_icq(struct io_cq *icq)
{
struct fiops_data *fiopsd = icq->q->elevator->elevator_data;
struct fiops_ioc *ioc = icq_to_cic(icq);
RB_CLEAR_NODE(&ioc->rb_node);
INIT_LIST_HEAD(&ioc->fifo);
ioc->sort_list = RB_ROOT;
ioc->fiopsd = fiopsd;
ioc->pid = current->pid;
fiops_mark_ioc_prio_changed(ioc);
}
/*
* sysfs parts below -->
*/
static ssize_t
fiops_var_show(unsigned int var, char *page)
{
return sprintf(page, "%d\n", var);
}
static ssize_t
fiops_var_store(unsigned int *var, const char *page, size_t count)
{
char *p = (char *) page;
*var = simple_strtoul(p, &p, 10);
return count;
}
#define SHOW_FUNCTION(__FUNC, __VAR) \
static ssize_t __FUNC(struct elevator_queue *e, char *page) \
{ \
struct fiops_data *fiopsd = e->elevator_data; \
return fiops_var_show(__VAR, (page)); \
}
SHOW_FUNCTION(fiops_read_scale_show, fiopsd->read_scale);
SHOW_FUNCTION(fiops_write_scale_show, fiopsd->write_scale);
SHOW_FUNCTION(fiops_sync_scale_show, fiopsd->sync_scale);
SHOW_FUNCTION(fiops_async_scale_show, fiopsd->async_scale);
#undef SHOW_FUNCTION
#define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX) \
static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count) \
{ \
struct fiops_data *fiopsd = e->elevator_data; \
unsigned int __data; \
int ret = fiops_var_store(&__data, (page), count); \
if (__data < (MIN)) \
__data = (MIN); \
else if (__data > (MAX)) \
__data = (MAX); \
*(__PTR) = __data; \
return ret; \
}
STORE_FUNCTION(fiops_read_scale_store, &fiopsd->read_scale, 1, 100);
STORE_FUNCTION(fiops_write_scale_store, &fiopsd->write_scale, 1, 100);
STORE_FUNCTION(fiops_sync_scale_store, &fiopsd->sync_scale, 1, 100);
STORE_FUNCTION(fiops_async_scale_store, &fiopsd->async_scale, 1, 100);
#undef STORE_FUNCTION
#define FIOPS_ATTR(name) \
__ATTR(name, S_IRUGO|S_IWUSR, fiops_##name##_show, fiops_##name##_store)
static struct elv_fs_entry fiops_attrs[] = {
FIOPS_ATTR(read_scale),
FIOPS_ATTR(write_scale),
FIOPS_ATTR(sync_scale),
FIOPS_ATTR(async_scale),
__ATTR_NULL
};
static struct elevator_type iosched_fiops = {
.ops = {
.elevator_merge_fn = fiops_merge,
.elevator_merged_fn = fiops_merged_request,
.elevator_merge_req_fn = fiops_merged_requests,
.elevator_allow_merge_fn = fiops_allow_merge,
.elevator_dispatch_fn = fiops_dispatch_requests,
.elevator_add_req_fn = fiops_insert_request,
.elevator_completed_req_fn = fiops_completed_request,
.elevator_former_req_fn = elv_rb_former_request,
.elevator_latter_req_fn = elv_rb_latter_request,
.elevator_init_icq_fn = fiops_init_icq,
.elevator_init_fn = fiops_init_queue,
.elevator_exit_fn = fiops_exit_queue,
},
.icq_size = sizeof(struct fiops_ioc),
.icq_align = __alignof__(struct fiops_ioc),
.elevator_attrs = fiops_attrs,
.elevator_name = "fiops",
.elevator_owner = THIS_MODULE,
};
static int __init fiops_init(void)
{
return elv_register(&iosched_fiops);
}
static void __exit fiops_exit(void)
{
elv_unregister(&iosched_fiops);
}
module_init(fiops_init);
module_exit(fiops_exit);
MODULE_AUTHOR("Jens Axboe, Shaohua Li <shli@kernel.org>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("IOPS based IO scheduler");
| gpl-2.0 |
markyzq/kernel-drm-rockchip | drivers/net/wireless/b43/radio_2057.c | 1999 | 22391 | /*
Broadcom B43 wireless driver
IEEE 802.11n 2057 radio device data tables
Copyright (c) 2010 Rafał Miłecki <zajec5@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Steet, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "b43.h"
#include "radio_2057.h"
#include "phy_common.h"
static u16 r2057_rev4_init[][2] = {
{ 0x0E, 0x20 }, { 0x31, 0x00 }, { 0x32, 0x00 }, { 0x33, 0x00 },
{ 0x35, 0x26 }, { 0x3C, 0xff }, { 0x3D, 0xff }, { 0x3E, 0xff },
{ 0x3F, 0xff }, { 0x62, 0x33 }, { 0x8A, 0xf0 }, { 0x8B, 0x10 },
{ 0x8C, 0xf0 }, { 0x91, 0x3f }, { 0x92, 0x36 }, { 0xA4, 0x8c },
{ 0xA8, 0x55 }, { 0xAF, 0x01 }, { 0x10F, 0xf0 }, { 0x110, 0x10 },
{ 0x111, 0xf0 }, { 0x116, 0x3f }, { 0x117, 0x36 }, { 0x129, 0x8c },
{ 0x12D, 0x55 }, { 0x134, 0x01 }, { 0x15E, 0x00 }, { 0x15F, 0x00 },
{ 0x160, 0x00 }, { 0x161, 0x00 }, { 0x162, 0x00 }, { 0x163, 0x00 },
{ 0x169, 0x02 }, { 0x16A, 0x00 }, { 0x16B, 0x00 }, { 0x16C, 0x00 },
{ 0x1A4, 0x00 }, { 0x1A5, 0x00 }, { 0x1A6, 0x00 }, { 0x1AA, 0x00 },
{ 0x1AB, 0x00 }, { 0x1AC, 0x00 },
};
static u16 r2057_rev5_init[][2] = {
{ 0x00, 0x00 }, { 0x01, 0x57 }, { 0x02, 0x20 }, { 0x23, 0x6 },
{ 0x31, 0x00 }, { 0x32, 0x00 }, { 0x33, 0x00 }, { 0x51, 0x70 },
{ 0x59, 0x88 }, { 0x5C, 0x20 }, { 0x62, 0x33 }, { 0x63, 0x0f },
{ 0x64, 0x0f }, { 0x81, 0x01 }, { 0x91, 0x3f }, { 0x92, 0x36 },
{ 0xA1, 0x20 }, { 0xD6, 0x70 }, { 0xDE, 0x88 }, { 0xE1, 0x20 },
{ 0xE8, 0x0f }, { 0xE9, 0x0f }, { 0x106, 0x01 }, { 0x116, 0x3f },
{ 0x117, 0x36 }, { 0x126, 0x20 }, { 0x15E, 0x00 }, { 0x15F, 0x00 },
{ 0x160, 0x00 }, { 0x161, 0x00 }, { 0x162, 0x00 }, { 0x163, 0x00 },
{ 0x16A, 0x00 }, { 0x16B, 0x00 }, { 0x16C, 0x00 }, { 0x1A4, 0x00 },
{ 0x1A5, 0x00 }, { 0x1A6, 0x00 }, { 0x1AA, 0x00 }, { 0x1AB, 0x00 },
{ 0x1AC, 0x00 }, { 0x1B7, 0x0c }, { 0x1C1, 0x01 }, { 0x1C2, 0x80 },
};
static u16 r2057_rev5a_init[][2] = {
{ 0x00, 0x15 }, { 0x01, 0x57 }, { 0x02, 0x20 }, { 0x23, 0x6 },
{ 0x31, 0x00 }, { 0x32, 0x00 }, { 0x33, 0x00 }, { 0x51, 0x70 },
{ 0x59, 0x88 }, { 0x5C, 0x20 }, { 0x62, 0x33 }, { 0x63, 0x0f },
{ 0x64, 0x0f }, { 0x81, 0x01 }, { 0x91, 0x3f }, { 0x92, 0x36 },
{ 0xC9, 0x01 }, { 0xD6, 0x70 }, { 0xDE, 0x88 }, { 0xE1, 0x20 },
{ 0xE8, 0x0f }, { 0xE9, 0x0f }, { 0x106, 0x01 }, { 0x116, 0x3f },
{ 0x117, 0x36 }, { 0x126, 0x20 }, { 0x14E, 0x01 }, { 0x15E, 0x00 },
{ 0x15F, 0x00 }, { 0x160, 0x00 }, { 0x161, 0x00 }, { 0x162, 0x00 },
{ 0x163, 0x00 }, { 0x16A, 0x00 }, { 0x16B, 0x00 }, { 0x16C, 0x00 },
{ 0x1A4, 0x00 }, { 0x1A5, 0x00 }, { 0x1A6, 0x00 }, { 0x1AA, 0x00 },
{ 0x1AB, 0x00 }, { 0x1AC, 0x00 }, { 0x1B7, 0x0c }, { 0x1C1, 0x01 },
{ 0x1C2, 0x80 },
};
static u16 r2057_rev7_init[][2] = {
{ 0x00, 0x00 }, { 0x01, 0x57 }, { 0x02, 0x20 }, { 0x31, 0x00 },
{ 0x32, 0x00 }, { 0x33, 0x00 }, { 0x51, 0x70 }, { 0x59, 0x88 },
{ 0x5C, 0x20 }, { 0x62, 0x33 }, { 0x63, 0x0f }, { 0x64, 0x13 },
{ 0x66, 0xee }, { 0x6E, 0x58 }, { 0x75, 0x13 }, { 0x7B, 0x13 },
{ 0x7C, 0x14 }, { 0x7D, 0xee }, { 0x81, 0x01 }, { 0x91, 0x3f },
{ 0x92, 0x36 }, { 0xA1, 0x20 }, { 0xD6, 0x70 }, { 0xDE, 0x88 },
{ 0xE1, 0x20 }, { 0xE8, 0x0f }, { 0xE9, 0x13 }, { 0xEB, 0xee },
{ 0xF3, 0x58 }, { 0xFA, 0x13 }, { 0x100, 0x13 }, { 0x101, 0x14 },
{ 0x102, 0xee }, { 0x106, 0x01 }, { 0x116, 0x3f }, { 0x117, 0x36 },
{ 0x126, 0x20 }, { 0x15E, 0x00 }, { 0x15F, 0x00 }, { 0x160, 0x00 },
{ 0x161, 0x00 }, { 0x162, 0x00 }, { 0x163, 0x00 }, { 0x16A, 0x00 },
{ 0x16B, 0x00 }, { 0x16C, 0x00 }, { 0x1A4, 0x00 }, { 0x1A5, 0x00 },
{ 0x1A6, 0x00 }, { 0x1AA, 0x00 }, { 0x1AB, 0x00 }, { 0x1AC, 0x00 },
{ 0x1B7, 0x05 }, { 0x1C2, 0xa0 },
};
/* TODO: Which devices should use it?
static u16 r2057_rev8_init[][2] = {
{ 0x00, 0x08 }, { 0x01, 0x57 }, { 0x02, 0x20 }, { 0x31, 0x00 },
{ 0x32, 0x00 }, { 0x33, 0x00 }, { 0x51, 0x70 }, { 0x59, 0x88 },
{ 0x5C, 0x20 }, { 0x62, 0x33 }, { 0x63, 0x0f }, { 0x64, 0x0f },
{ 0x6E, 0x58 }, { 0x75, 0x13 }, { 0x7B, 0x13 }, { 0x7C, 0x0f },
{ 0x7D, 0xee }, { 0x81, 0x01 }, { 0x91, 0x3f }, { 0x92, 0x36 },
{ 0xA1, 0x20 }, { 0xC9, 0x01 }, { 0xD6, 0x70 }, { 0xDE, 0x88 },
{ 0xE1, 0x20 }, { 0xE8, 0x0f }, { 0xE9, 0x0f }, { 0xF3, 0x58 },
{ 0xFA, 0x13 }, { 0x100, 0x13 }, { 0x101, 0x0f }, { 0x102, 0xee },
{ 0x106, 0x01 }, { 0x116, 0x3f }, { 0x117, 0x36 }, { 0x126, 0x20 },
{ 0x14E, 0x01 }, { 0x15E, 0x00 }, { 0x15F, 0x00 }, { 0x160, 0x00 },
{ 0x161, 0x00 }, { 0x162, 0x00 }, { 0x163, 0x00 }, { 0x16A, 0x00 },
{ 0x16B, 0x00 }, { 0x16C, 0x00 }, { 0x1A4, 0x00 }, { 0x1A5, 0x00 },
{ 0x1A6, 0x00 }, { 0x1AA, 0x00 }, { 0x1AB, 0x00 }, { 0x1AC, 0x00 },
{ 0x1B7, 0x05 }, { 0x1C2, 0xa0 },
};
*/
/* Extracted from MMIO dump of 6.30.223.141 */
static u16 r2057_rev9_init[][2] = {
{ 0x27, 0x1f }, { 0x28, 0x0a }, { 0x29, 0x2f }, { 0x42, 0x1f },
{ 0x48, 0x3f }, { 0x5c, 0x41 }, { 0x63, 0x14 }, { 0x64, 0x12 },
{ 0x66, 0xff }, { 0x74, 0xa3 }, { 0x7b, 0x14 }, { 0x7c, 0x14 },
{ 0x7d, 0xee }, { 0x86, 0xc0 }, { 0xc4, 0x10 }, { 0xc9, 0x01 },
{ 0xe1, 0x41 }, { 0xe8, 0x14 }, { 0xe9, 0x12 }, { 0xeb, 0xff },
{ 0xf5, 0x0a }, { 0xf8, 0x09 }, { 0xf9, 0xa3 }, { 0x100, 0x14 },
{ 0x101, 0x10 }, { 0x102, 0xee }, { 0x10b, 0xc0 }, { 0x149, 0x10 },
{ 0x14e, 0x01 }, { 0x1b7, 0x05 }, { 0x1c2, 0xa0 },
};
/* Extracted from MMIO dump of 6.30.223.248 */
static u16 r2057_rev14_init[][2] = {
{ 0x011, 0xfc }, { 0x030, 0x24 }, { 0x040, 0x1c }, { 0x082, 0x08 },
{ 0x0b4, 0x44 }, { 0x0c8, 0x01 }, { 0x0c9, 0x01 }, { 0x107, 0x08 },
{ 0x14d, 0x01 }, { 0x14e, 0x01 }, { 0x1af, 0x40 }, { 0x1b0, 0x40 },
{ 0x1cc, 0x01 }, { 0x1cf, 0x10 }, { 0x1d0, 0x0f }, { 0x1d3, 0x10 },
{ 0x1d4, 0x0f },
};
#define RADIOREGS7(r00, r01, r02, r03, r04, r05, r06, r07, r08, r09, \
r10, r11, r12, r13, r14, r15, r16, r17, r18, r19, \
r20, r21, r22, r23, r24, r25, r26, r27) \
.radio_vcocal_countval0 = r00, \
.radio_vcocal_countval1 = r01, \
.radio_rfpll_refmaster_sparextalsize = r02, \
.radio_rfpll_loopfilter_r1 = r03, \
.radio_rfpll_loopfilter_c2 = r04, \
.radio_rfpll_loopfilter_c1 = r05, \
.radio_cp_kpd_idac = r06, \
.radio_rfpll_mmd0 = r07, \
.radio_rfpll_mmd1 = r08, \
.radio_vcobuf_tune = r09, \
.radio_logen_mx2g_tune = r10, \
.radio_logen_mx5g_tune = r11, \
.radio_logen_indbuf2g_tune = r12, \
.radio_logen_indbuf5g_tune = r13, \
.radio_txmix2g_tune_boost_pu_core0 = r14, \
.radio_pad2g_tune_pus_core0 = r15, \
.radio_pga_boost_tune_core0 = r16, \
.radio_txmix5g_boost_tune_core0 = r17, \
.radio_pad5g_tune_misc_pus_core0 = r18, \
.radio_lna2g_tune_core0 = r19, \
.radio_lna5g_tune_core0 = r20, \
.radio_txmix2g_tune_boost_pu_core1 = r21, \
.radio_pad2g_tune_pus_core1 = r22, \
.radio_pga_boost_tune_core1 = r23, \
.radio_txmix5g_boost_tune_core1 = r24, \
.radio_pad5g_tune_misc_pus_core1 = r25, \
.radio_lna2g_tune_core1 = r26, \
.radio_lna5g_tune_core1 = r27
#define RADIOREGS7_2G(r00, r01, r02, r03, r04, r05, r06, r07, r08, r09, \
r10, r11, r12, r13, r14, r15, r16, r17) \
.radio_vcocal_countval0 = r00, \
.radio_vcocal_countval1 = r01, \
.radio_rfpll_refmaster_sparextalsize = r02, \
.radio_rfpll_loopfilter_r1 = r03, \
.radio_rfpll_loopfilter_c2 = r04, \
.radio_rfpll_loopfilter_c1 = r05, \
.radio_cp_kpd_idac = r06, \
.radio_rfpll_mmd0 = r07, \
.radio_rfpll_mmd1 = r08, \
.radio_vcobuf_tune = r09, \
.radio_logen_mx2g_tune = r10, \
.radio_logen_indbuf2g_tune = r11, \
.radio_txmix2g_tune_boost_pu_core0 = r12, \
.radio_pad2g_tune_pus_core0 = r13, \
.radio_lna2g_tune_core0 = r14, \
.radio_txmix2g_tune_boost_pu_core1 = r15, \
.radio_pad2g_tune_pus_core1 = r16, \
.radio_lna2g_tune_core1 = r17
#define PHYREGS(r0, r1, r2, r3, r4, r5) \
.phy_regs.phy_bw1a = r0, \
.phy_regs.phy_bw2 = r1, \
.phy_regs.phy_bw3 = r2, \
.phy_regs.phy_bw4 = r3, \
.phy_regs.phy_bw5 = r4, \
.phy_regs.phy_bw6 = r5
/* Copied from brcmsmac (5.75.11): chan_info_nphyrev8_2057_rev5 */
static const struct b43_nphy_chantabent_rev7_2g b43_nphy_chantab_phy_rev8_radio_rev5[] = {
{
.freq = 2412,
RADIOREGS7_2G(0x48, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x6c,
0x09, 0x0d, 0x08, 0x0e, 0x61, 0x03, 0xff, 0x61,
0x03, 0xff),
PHYREGS(0x03c9, 0x03c5, 0x03c1, 0x043a, 0x043f, 0x0443),
},
{
.freq = 2417,
RADIOREGS7_2G(0x4b, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x71,
0x09, 0x0d, 0x08, 0x0e, 0x61, 0x03, 0xff, 0x61,
0x03, 0xff),
PHYREGS(0x03cb, 0x03c7, 0x03c3, 0x0438, 0x043d, 0x0441),
},
{
.freq = 2422,
RADIOREGS7_2G(0x4e, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x76,
0x09, 0x0d, 0x08, 0x0e, 0x61, 0x03, 0xef, 0x61,
0x03, 0xef),
PHYREGS(0x03cd, 0x03c9, 0x03c5, 0x0436, 0x043a, 0x043f),
},
{
.freq = 2427,
RADIOREGS7_2G(0x52, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x7b,
0x09, 0x0c, 0x08, 0x0e, 0x61, 0x03, 0xdf, 0x61,
0x03, 0xdf),
PHYREGS(0x03cf, 0x03cb, 0x03c7, 0x0434, 0x0438, 0x043d),
},
{
.freq = 2432,
RADIOREGS7_2G(0x55, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x80,
0x09, 0x0c, 0x07, 0x0d, 0x61, 0x03, 0xcf, 0x61,
0x03, 0xcf),
PHYREGS(0x03d1, 0x03cd, 0x03c9, 0x0431, 0x0436, 0x043a),
},
{
.freq = 2437,
RADIOREGS7_2G(0x58, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x85,
0x09, 0x0c, 0x07, 0x0d, 0x61, 0x03, 0xbf, 0x61,
0x03, 0xbf),
PHYREGS(0x03d3, 0x03cf, 0x03cb, 0x042f, 0x0434, 0x0438),
},
{
.freq = 2442,
RADIOREGS7_2G(0x5c, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x8a,
0x09, 0x0b, 0x07, 0x0d, 0x61, 0x03, 0xaf, 0x61,
0x03, 0xaf),
PHYREGS(0x03d5, 0x03d1, 0x03cd, 0x042d, 0x0431, 0x0436),
},
{
.freq = 2447,
RADIOREGS7_2G(0x5f, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x8f,
0x09, 0x0b, 0x07, 0x0d, 0x61, 0x03, 0x9f, 0x61,
0x03, 0x9f),
PHYREGS(0x03d7, 0x03d3, 0x03cf, 0x042b, 0x042f, 0x0434),
},
{
.freq = 2452,
RADIOREGS7_2G(0x62, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x94,
0x09, 0x0b, 0x07, 0x0d, 0x61, 0x03, 0x8f, 0x61,
0x03, 0x8f),
PHYREGS(0x03d9, 0x03d5, 0x03d1, 0x0429, 0x042d, 0x0431),
},
{
.freq = 2457,
RADIOREGS7_2G(0x66, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x99,
0x09, 0x0b, 0x07, 0x0c, 0x61, 0x03, 0x7f, 0x61,
0x03, 0x7f),
PHYREGS(0x03db, 0x03d7, 0x03d3, 0x0427, 0x042b, 0x042f),
},
{
.freq = 2462,
RADIOREGS7_2G(0x69, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x9e,
0x09, 0x0b, 0x07, 0x0c, 0x61, 0x03, 0x6f, 0x61,
0x03, 0x6f),
PHYREGS(0x03dd, 0x03d9, 0x03d5, 0x0424, 0x0429, 0x042d),
},
{
.freq = 2467,
RADIOREGS7_2G(0x6c, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0xa3,
0x09, 0x0b, 0x06, 0x0c, 0x61, 0x03, 0x5f, 0x61,
0x03, 0x5f),
PHYREGS(0x03df, 0x03db, 0x03d7, 0x0422, 0x0427, 0x042b),
},
{
.freq = 2472,
RADIOREGS7_2G(0x70, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0xa8,
0x09, 0x0a, 0x06, 0x0b, 0x61, 0x03, 0x4f, 0x61,
0x03, 0x4f),
PHYREGS(0x03e1, 0x03dd, 0x03d9, 0x0420, 0x0424, 0x0429),
},
{
.freq = 2484,
RADIOREGS7_2G(0x78, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0xb4,
0x09, 0x0a, 0x06, 0x0b, 0x61, 0x03, 0x3f, 0x61,
0x03, 0x3f),
PHYREGS(0x03e6, 0x03e2, 0x03de, 0x041b, 0x041f, 0x0424),
}
};
/* Extracted from MMIO dump of 6.30.223.248 */
static const struct b43_nphy_chantabent_rev7_2g b43_nphy_chantab_phy_rev17_radio_rev14[] = {
{
.freq = 2412,
RADIOREGS7_2G(0x48, 0x16, 0x30, 0x2b, 0x1f, 0x1f, 0x30, 0x6c,
0x09, 0x0d, 0x09, 0x03, 0x21, 0x53, 0xff, 0x21,
0x53, 0xff),
PHYREGS(0x03c9, 0x03c5, 0x03c1, 0x043a, 0x043f, 0x0443),
},
{
.freq = 2417,
RADIOREGS7_2G(0x4b, 0x16, 0x30, 0x2b, 0x1f, 0x1f, 0x30, 0x71,
0x09, 0x0d, 0x08, 0x03, 0x21, 0x53, 0xff, 0x21,
0x53, 0xff),
PHYREGS(0x03cb, 0x03c7, 0x03c3, 0x0438, 0x043d, 0x0441),
},
{
.freq = 2422,
RADIOREGS7_2G(0x4e, 0x16, 0x30, 0x2b, 0x1f, 0x1f, 0x30, 0x76,
0x09, 0x0d, 0x08, 0x03, 0x21, 0x53, 0xff, 0x21,
0x53, 0xff),
PHYREGS(0x03cd, 0x03c9, 0x03c5, 0x0436, 0x043a, 0x043f),
},
{
.freq = 2427,
RADIOREGS7_2G(0x52, 0x16, 0x30, 0x2b, 0x1f, 0x1f, 0x30, 0x7b,
0x09, 0x0c, 0x08, 0x03, 0x21, 0x53, 0xff, 0x21,
0x53, 0xff),
PHYREGS(0x03cf, 0x03cb, 0x03c7, 0x0434, 0x0438, 0x043d),
},
{
.freq = 2432,
RADIOREGS7_2G(0x55, 0x16, 0x30, 0x2b, 0x1f, 0x1f, 0x30, 0x80,
0x09, 0x0c, 0x08, 0x03, 0x21, 0x53, 0xff, 0x21,
0x53, 0xff),
PHYREGS(0x03d1, 0x03cd, 0x03c9, 0x0431, 0x0436, 0x043a),
},
{
.freq = 2437,
RADIOREGS7_2G(0x58, 0x16, 0x30, 0x2b, 0x1f, 0x1f, 0x30, 0x85,
0x09, 0x0c, 0x08, 0x03, 0x21, 0x53, 0xff, 0x21,
0x53, 0xff),
PHYREGS(0x03d3, 0x03cf, 0x03cb, 0x042f, 0x0434, 0x0438),
},
{
.freq = 2442,
RADIOREGS7_2G(0x5c, 0x16, 0x30, 0x2b, 0x1f, 0x1f, 0x30, 0x8a,
0x09, 0x0c, 0x08, 0x03, 0x21, 0x43, 0xff, 0x21,
0x43, 0xff),
PHYREGS(0x03d5, 0x03d1, 0x03cd, 0x042d, 0x0431, 0x0436),
},
{
.freq = 2447,
RADIOREGS7_2G(0x5f, 0x16, 0x30, 0x2b, 0x1f, 0x1f, 0x30, 0x8f,
0x09, 0x0c, 0x08, 0x03, 0x21, 0x43, 0xff, 0x21,
0x43, 0xff),
PHYREGS(0x03d7, 0x03d3, 0x03cf, 0x042b, 0x042f, 0x0434),
},
{
.freq = 2452,
RADIOREGS7_2G(0x62, 0x16, 0x30, 0x2b, 0x1f, 0x1f, 0x30, 0x94,
0x09, 0x0c, 0x08, 0x03, 0x21, 0x43, 0xff, 0x21,
0x43, 0xff),
PHYREGS(0x03d9, 0x03d5, 0x03d1, 0x0429, 0x042d, 0x0431),
},
{
.freq = 2457,
RADIOREGS7_2G(0x66, 0x16, 0x30, 0x2b, 0x1f, 0x1f, 0x30, 0x99,
0x09, 0x0b, 0x07, 0x03, 0x21, 0x43, 0xff, 0x21,
0x43, 0xff),
PHYREGS(0x03db, 0x03d7, 0x03d3, 0x0427, 0x042b, 0x042f),
},
{
.freq = 2462,
RADIOREGS7_2G(0x69, 0x16, 0x30, 0x2b, 0x1f, 0x1f, 0x30, 0x9e,
0x09, 0x0b, 0x07, 0x03, 0x01, 0x43, 0xff, 0x01,
0x43, 0xff),
PHYREGS(0x03dd, 0x03d9, 0x03d5, 0x0424, 0x0429, 0x042d),
},
};
/* Extracted from MMIO dump of 6.30.223.141 */
static const struct b43_nphy_chantabent_rev7 b43_nphy_chantab_phy_rev16_radio_rev9[] = {
{
.freq = 2412,
RADIOREGS7(0x48, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x6c,
0x09, 0x0f, 0x0a, 0x00, 0x0a, 0x00, 0x41, 0x63,
0x00, 0x00, 0x00, 0xf0, 0x00, 0x41, 0x63, 0x00,
0x00, 0x00, 0xf0, 0x00),
PHYREGS(0x03c9, 0x03c5, 0x03c1, 0x043a, 0x043f, 0x0443),
},
{
.freq = 2417,
RADIOREGS7(0x4b, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x71,
0x09, 0x0f, 0x0a, 0x00, 0x0a, 0x00, 0x41, 0x63,
0x00, 0x00, 0x00, 0xf0, 0x00, 0x41, 0x63, 0x00,
0x00, 0x00, 0xf0, 0x00),
PHYREGS(0x03cb, 0x03c7, 0x03c3, 0x0438, 0x043d, 0x0441),
},
{
.freq = 2422,
RADIOREGS7(0x4e, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x76,
0x09, 0x0f, 0x09, 0x00, 0x09, 0x00, 0x41, 0x63,
0x00, 0x00, 0x00, 0xf0, 0x00, 0x41, 0x63, 0x00,
0x00, 0x00, 0xf0, 0x00),
PHYREGS(0x03cd, 0x03c9, 0x03c5, 0x0436, 0x043a, 0x043f),
},
{
.freq = 2427,
RADIOREGS7(0x52, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x7b,
0x09, 0x0f, 0x09, 0x00, 0x09, 0x00, 0x41, 0x63,
0x00, 0x00, 0x00, 0xf0, 0x00, 0x41, 0x63, 0x00,
0x00, 0x00, 0xf0, 0x00),
PHYREGS(0x03cf, 0x03cb, 0x03c7, 0x0434, 0x0438, 0x043d),
},
{
.freq = 2432,
RADIOREGS7(0x55, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x80,
0x09, 0x0f, 0x08, 0x00, 0x08, 0x00, 0x41, 0x63,
0x00, 0x00, 0x00, 0xf0, 0x00, 0x41, 0x63, 0x00,
0x00, 0x00, 0xf0, 0x00),
PHYREGS(0x03d1, 0x03cd, 0x03c9, 0x0431, 0x0436, 0x043a),
},
{
.freq = 2437,
RADIOREGS7(0x58, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x85,
0x09, 0x0f, 0x08, 0x00, 0x08, 0x00, 0x41, 0x63,
0x00, 0x00, 0x00, 0xf0, 0x00, 0x41, 0x63, 0x00,
0x00, 0x00, 0xf0, 0x00),
PHYREGS(0x03d3, 0x03cf, 0x03cb, 0x042f, 0x0434, 0x0438),
},
{
.freq = 2442,
RADIOREGS7(0x5c, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x8a,
0x09, 0x0f, 0x07, 0x00, 0x07, 0x00, 0x41, 0x63,
0x00, 0x00, 0x00, 0xf0, 0x00, 0x41, 0x63, 0x00,
0x00, 0x00, 0xf0, 0x00),
PHYREGS(0x03d5, 0x03d1, 0x03cd, 0x042d, 0x0431, 0x0436),
},
{
.freq = 2447,
RADIOREGS7(0x5f, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x8f,
0x09, 0x0f, 0x07, 0x00, 0x07, 0x00, 0x41, 0x63,
0x00, 0x00, 0x00, 0xf0, 0x00, 0x41, 0x63, 0x00,
0x00, 0x00, 0xf0, 0x00),
PHYREGS(0x03d7, 0x03d3, 0x03cf, 0x042b, 0x042f, 0x0434),
},
{
.freq = 2452,
RADIOREGS7(0x62, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x94,
0x09, 0x0f, 0x07, 0x00, 0x07, 0x00, 0x41, 0x63,
0x00, 0x00, 0x00, 0xf0, 0x00, 0x41, 0x63, 0x00,
0x00, 0x00, 0xf0, 0x00),
PHYREGS(0x03d9, 0x03d5, 0x03d1, 0x0429, 0x042d, 0x0431),
},
{
.freq = 2457,
RADIOREGS7(0x66, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x99,
0x09, 0x0f, 0x06, 0x00, 0x06, 0x00, 0x41, 0x63,
0x00, 0x00, 0x00, 0xf0, 0x00, 0x41, 0x63, 0x00,
0x00, 0x00, 0xf0, 0x00),
PHYREGS(0x03db, 0x03d7, 0x03d3, 0x0427, 0x042b, 0x042f),
},
{
.freq = 2462,
RADIOREGS7(0x69, 0x16, 0x30, 0x1b, 0x0a, 0x0a, 0x30, 0x9e,
0x09, 0x0f, 0x06, 0x00, 0x06, 0x00, 0x41, 0x63,
0x00, 0x00, 0x00, 0xf0, 0x00, 0x41, 0x63, 0x00,
0x00, 0x00, 0xf0, 0x00),
PHYREGS(0x03dd, 0x03d9, 0x03d5, 0x0424, 0x0429, 0x042d),
},
{
.freq = 5180,
RADIOREGS7(0xbe, 0x16, 0x10, 0x1f, 0x08, 0x08, 0x3f, 0x06,
0x02, 0x0e, 0x00, 0x0e, 0x00, 0x9e, 0x00, 0x00,
0x9f, 0x2f, 0xa3, 0x00, 0xfc, 0x00, 0x00, 0x4f,
0x3a, 0x83, 0x00, 0xfc),
PHYREGS(0x081c, 0x0818, 0x0814, 0x01f9, 0x01fa, 0x01fb),
},
{
.freq = 5200,
RADIOREGS7(0xc5, 0x16, 0x10, 0x1f, 0x08, 0x08, 0x3f, 0x08,
0x02, 0x0e, 0x00, 0x0e, 0x00, 0x9e, 0x00, 0x00,
0x7f, 0x2f, 0x83, 0x00, 0xf8, 0x00, 0x00, 0x4c,
0x4a, 0x83, 0x00, 0xf8),
PHYREGS(0x0824, 0x0820, 0x081c, 0x01f7, 0x01f8, 0x01f9),
},
{
.freq = 5220,
RADIOREGS7(0xcc, 0x16, 0x10, 0x1f, 0x08, 0x08, 0x3f, 0x0a,
0x02, 0x0e, 0x00, 0x0e, 0x00, 0x9e, 0x00, 0x00,
0x6d, 0x3d, 0x83, 0x00, 0xf8, 0x00, 0x00, 0x2d,
0x2a, 0x73, 0x00, 0xf8),
PHYREGS(0x082c, 0x0828, 0x0824, 0x01f5, 0x01f6, 0x01f7),
},
{
.freq = 5240,
RADIOREGS7(0xd2, 0x16, 0x10, 0x1f, 0x08, 0x08, 0x3f, 0x0c,
0x02, 0x0d, 0x00, 0x0d, 0x00, 0x8d, 0x00, 0x00,
0x4d, 0x1c, 0x73, 0x00, 0xf8, 0x00, 0x00, 0x4d,
0x2b, 0x73, 0x00, 0xf8),
PHYREGS(0x0834, 0x0830, 0x082c, 0x01f3, 0x01f4, 0x01f5),
},
{
.freq = 5745,
RADIOREGS7(0x7b, 0x17, 0x20, 0x1f, 0x08, 0x08, 0x3f, 0x7d,
0x04, 0x08, 0x00, 0x06, 0x00, 0x15, 0x00, 0x00,
0x08, 0x03, 0x03, 0x00, 0x30, 0x00, 0x00, 0x06,
0x02, 0x03, 0x00, 0x30),
PHYREGS(0x08fe, 0x08fa, 0x08f6, 0x01c8, 0x01c8, 0x01c9),
},
{
.freq = 5765,
RADIOREGS7(0x81, 0x17, 0x20, 0x1f, 0x08, 0x08, 0x3f, 0x81,
0x04, 0x08, 0x00, 0x06, 0x00, 0x15, 0x00, 0x00,
0x06, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x05,
0x02, 0x03, 0x00, 0x00),
PHYREGS(0x0906, 0x0902, 0x08fe, 0x01c6, 0x01c7, 0x01c8),
},
{
.freq = 5785,
RADIOREGS7(0x88, 0x17, 0x20, 0x1f, 0x08, 0x08, 0x3f, 0x85,
0x04, 0x08, 0x00, 0x06, 0x00, 0x15, 0x00, 0x00,
0x08, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x05,
0x21, 0x03, 0x00, 0x00),
PHYREGS(0x090e, 0x090a, 0x0906, 0x01c4, 0x01c5, 0x01c6),
},
{
.freq = 5805,
RADIOREGS7(0x8f, 0x17, 0x20, 0x1f, 0x08, 0x08, 0x3f, 0x89,
0x04, 0x07, 0x00, 0x06, 0x00, 0x04, 0x00, 0x00,
0x06, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x03,
0x00, 0x03, 0x00, 0x00),
PHYREGS(0x0916, 0x0912, 0x090e, 0x01c3, 0x01c4, 0x01c4),
},
{
.freq = 5825,
RADIOREGS7(0x95, 0x17, 0x20, 0x1f, 0x08, 0x08, 0x3f, 0x8d,
0x04, 0x07, 0x00, 0x05, 0x00, 0x03, 0x00, 0x00,
0x05, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x03,
0x00, 0x03, 0x00, 0x00),
PHYREGS(0x091e, 0x091a, 0x0916, 0x01c1, 0x01c2, 0x01c3),
},
};
void r2057_upload_inittabs(struct b43_wldev *dev)
{
struct b43_phy *phy = &dev->phy;
u16 *table = NULL;
u16 size, i;
switch (phy->rev) {
case 7:
table = r2057_rev4_init[0];
size = ARRAY_SIZE(r2057_rev4_init);
break;
case 8:
if (phy->radio_rev == 5) {
table = r2057_rev5_init[0];
size = ARRAY_SIZE(r2057_rev5_init);
} else if (phy->radio_rev == 7) {
table = r2057_rev7_init[0];
size = ARRAY_SIZE(r2057_rev7_init);
}
break;
case 9:
if (phy->radio_rev == 5) {
table = r2057_rev5a_init[0];
size = ARRAY_SIZE(r2057_rev5a_init);
}
break;
case 16:
if (phy->radio_rev == 9) {
table = r2057_rev9_init[0];
size = ARRAY_SIZE(r2057_rev9_init);
}
break;
case 17:
if (phy->radio_rev == 14) {
table = r2057_rev14_init[0];
size = ARRAY_SIZE(r2057_rev14_init);
}
break;
}
B43_WARN_ON(!table);
if (table) {
for (i = 0; i < size; i++, table += 2)
b43_radio_write(dev, table[0], table[1]);
}
}
void r2057_get_chantabent_rev7(struct b43_wldev *dev, u16 freq,
const struct b43_nphy_chantabent_rev7 **tabent_r7,
const struct b43_nphy_chantabent_rev7_2g **tabent_r7_2g)
{
struct b43_phy *phy = &dev->phy;
const struct b43_nphy_chantabent_rev7 *e_r7 = NULL;
const struct b43_nphy_chantabent_rev7_2g *e_r7_2g = NULL;
unsigned int len, i;
*tabent_r7 = NULL;
*tabent_r7_2g = NULL;
switch (phy->rev) {
case 8:
if (phy->radio_rev == 5) {
e_r7_2g = b43_nphy_chantab_phy_rev8_radio_rev5;
len = ARRAY_SIZE(b43_nphy_chantab_phy_rev8_radio_rev5);
}
break;
case 16:
if (phy->radio_rev == 9) {
e_r7 = b43_nphy_chantab_phy_rev16_radio_rev9;
len = ARRAY_SIZE(b43_nphy_chantab_phy_rev16_radio_rev9);
}
break;
case 17:
if (phy->radio_rev == 14) {
e_r7_2g = b43_nphy_chantab_phy_rev17_radio_rev14;
len = ARRAY_SIZE(b43_nphy_chantab_phy_rev17_radio_rev14);
}
break;
default:
break;
}
if (e_r7) {
for (i = 0; i < len; i++, e_r7++) {
if (e_r7->freq == freq) {
*tabent_r7 = e_r7;
return;
}
}
} else if (e_r7_2g) {
for (i = 0; i < len; i++, e_r7_2g++) {
if (e_r7_2g->freq == freq) {
*tabent_r7_2g = e_r7_2g;
return;
}
}
} else {
B43_WARN_ON(1);
}
}
| gpl-2.0 |
geiti94/NEMESIS_KERNEL_N5_NOUGAT | arch/mips/txx9/generic/setup.c | 1999 | 22974 | /*
* Based on linux/arch/mips/txx9/rbtx4938/setup.c,
* and RBTX49xx patch from CELF patch archive.
*
* 2003-2005 (c) MontaVista Software, Inc.
* (C) Copyright TOSHIBA CORPORATION 2000-2001, 2004-2007
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/string.h>
#include <linux/module.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/gpio.h>
#include <linux/platform_device.h>
#include <linux/serial_core.h>
#include <linux/mtd/physmap.h>
#include <linux/leds.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/irq.h>
#include <asm/bootinfo.h>
#include <asm/idle.h>
#include <asm/time.h>
#include <asm/reboot.h>
#include <asm/r4kcache.h>
#include <asm/sections.h>
#include <asm/txx9/generic.h>
#include <asm/txx9/pci.h>
#include <asm/txx9tmr.h>
#include <asm/txx9/ndfmc.h>
#include <asm/txx9/dmac.h>
#ifdef CONFIG_CPU_TX49XX
#include <asm/txx9/tx4938.h>
#endif
/* EBUSC settings of TX4927, etc. */
struct resource txx9_ce_res[8];
static char txx9_ce_res_name[8][4]; /* "CEn" */
/* pcode, internal register */
unsigned int txx9_pcode;
char txx9_pcode_str[8];
static struct resource txx9_reg_res = {
.name = txx9_pcode_str,
.flags = IORESOURCE_MEM,
};
void __init
txx9_reg_res_init(unsigned int pcode, unsigned long base, unsigned long size)
{
int i;
for (i = 0; i < ARRAY_SIZE(txx9_ce_res); i++) {
sprintf(txx9_ce_res_name[i], "CE%d", i);
txx9_ce_res[i].flags = IORESOURCE_MEM;
txx9_ce_res[i].name = txx9_ce_res_name[i];
}
txx9_pcode = pcode;
sprintf(txx9_pcode_str, "TX%x", pcode);
if (base) {
txx9_reg_res.start = base & 0xfffffffffULL;
txx9_reg_res.end = (base & 0xfffffffffULL) + (size - 1);
request_resource(&iomem_resource, &txx9_reg_res);
}
}
/* clocks */
unsigned int txx9_master_clock;
unsigned int txx9_cpu_clock;
unsigned int txx9_gbus_clock;
#ifdef CONFIG_CPU_TX39XX
/* don't enable by default - see errata */
int txx9_ccfg_toeon __initdata;
#else
int txx9_ccfg_toeon __initdata = 1;
#endif
/* Minimum CLK support */
struct clk *clk_get(struct device *dev, const char *id)
{
if (!strcmp(id, "spi-baseclk"))
return (struct clk *)((unsigned long)txx9_gbus_clock / 2 / 2);
if (!strcmp(id, "imbus_clk"))
return (struct clk *)((unsigned long)txx9_gbus_clock / 2);
return ERR_PTR(-ENOENT);
}
EXPORT_SYMBOL(clk_get);
int clk_enable(struct clk *clk)
{
return 0;
}
EXPORT_SYMBOL(clk_enable);
void clk_disable(struct clk *clk)
{
}
EXPORT_SYMBOL(clk_disable);
unsigned long clk_get_rate(struct clk *clk)
{
return (unsigned long)clk;
}
EXPORT_SYMBOL(clk_get_rate);
void clk_put(struct clk *clk)
{
}
EXPORT_SYMBOL(clk_put);
/* GPIO support */
#ifdef CONFIG_GPIOLIB
int gpio_to_irq(unsigned gpio)
{
return -EINVAL;
}
EXPORT_SYMBOL(gpio_to_irq);
int irq_to_gpio(unsigned irq)
{
return -EINVAL;
}
EXPORT_SYMBOL(irq_to_gpio);
#endif
#define BOARD_VEC(board) extern struct txx9_board_vec board;
#include <asm/txx9/boards.h>
#undef BOARD_VEC
struct txx9_board_vec *txx9_board_vec __initdata;
static char txx9_system_type[32];
static struct txx9_board_vec *board_vecs[] __initdata = {
#define BOARD_VEC(board) &board,
#include <asm/txx9/boards.h>
#undef BOARD_VEC
};
static struct txx9_board_vec *__init find_board_byname(const char *name)
{
int i;
/* search board_vecs table */
for (i = 0; i < ARRAY_SIZE(board_vecs); i++) {
if (strstr(board_vecs[i]->system, name))
return board_vecs[i];
}
return NULL;
}
static void __init prom_init_cmdline(void)
{
int argc;
int *argv32;
int i; /* Always ignore the "-c" at argv[0] */
if (fw_arg0 >= CKSEG0 || fw_arg1 < CKSEG0) {
/*
* argc is not a valid number, or argv32 is not a valid
* pointer
*/
argc = 0;
argv32 = NULL;
} else {
argc = (int)fw_arg0;
argv32 = (int *)fw_arg1;
}
arcs_cmdline[0] = '\0';
for (i = 1; i < argc; i++) {
char *str = (char *)(long)argv32[i];
if (i != 1)
strcat(arcs_cmdline, " ");
if (strchr(str, ' ')) {
strcat(arcs_cmdline, "\"");
strcat(arcs_cmdline, str);
strcat(arcs_cmdline, "\"");
} else
strcat(arcs_cmdline, str);
}
}
static int txx9_ic_disable __initdata;
static int txx9_dc_disable __initdata;
#if defined(CONFIG_CPU_TX49XX)
/* flush all cache on very early stage (before 4k_cache_init) */
static void __init early_flush_dcache(void)
{
unsigned int conf = read_c0_config();
unsigned int dc_size = 1 << (12 + ((conf & CONF_DC) >> 6));
unsigned int linesz = 32;
unsigned long addr, end;
end = INDEX_BASE + dc_size / 4;
/* 4way, waybit=0 */
for (addr = INDEX_BASE; addr < end; addr += linesz) {
cache_op(Index_Writeback_Inv_D, addr | 0);
cache_op(Index_Writeback_Inv_D, addr | 1);
cache_op(Index_Writeback_Inv_D, addr | 2);
cache_op(Index_Writeback_Inv_D, addr | 3);
}
}
static void __init txx9_cache_fixup(void)
{
unsigned int conf;
conf = read_c0_config();
/* flush and disable */
if (txx9_ic_disable) {
conf |= TX49_CONF_IC;
write_c0_config(conf);
}
if (txx9_dc_disable) {
early_flush_dcache();
conf |= TX49_CONF_DC;
write_c0_config(conf);
}
/* enable cache */
conf = read_c0_config();
if (!txx9_ic_disable)
conf &= ~TX49_CONF_IC;
if (!txx9_dc_disable)
conf &= ~TX49_CONF_DC;
write_c0_config(conf);
if (conf & TX49_CONF_IC)
pr_info("TX49XX I-Cache disabled.\n");
if (conf & TX49_CONF_DC)
pr_info("TX49XX D-Cache disabled.\n");
}
#elif defined(CONFIG_CPU_TX39XX)
/* flush all cache on very early stage (before tx39_cache_init) */
static void __init early_flush_dcache(void)
{
unsigned int conf = read_c0_config();
unsigned int dc_size = 1 << (10 + ((conf & TX39_CONF_DCS_MASK) >>
TX39_CONF_DCS_SHIFT));
unsigned int linesz = 16;
unsigned long addr, end;
end = INDEX_BASE + dc_size / 2;
/* 2way, waybit=0 */
for (addr = INDEX_BASE; addr < end; addr += linesz) {
cache_op(Index_Writeback_Inv_D, addr | 0);
cache_op(Index_Writeback_Inv_D, addr | 1);
}
}
static void __init txx9_cache_fixup(void)
{
unsigned int conf;
conf = read_c0_config();
/* flush and disable */
if (txx9_ic_disable) {
conf &= ~TX39_CONF_ICE;
write_c0_config(conf);
}
if (txx9_dc_disable) {
early_flush_dcache();
conf &= ~TX39_CONF_DCE;
write_c0_config(conf);
}
/* enable cache */
conf = read_c0_config();
if (!txx9_ic_disable)
conf |= TX39_CONF_ICE;
if (!txx9_dc_disable)
conf |= TX39_CONF_DCE;
write_c0_config(conf);
if (!(conf & TX39_CONF_ICE))
pr_info("TX39XX I-Cache disabled.\n");
if (!(conf & TX39_CONF_DCE))
pr_info("TX39XX D-Cache disabled.\n");
}
#else
static inline void txx9_cache_fixup(void)
{
}
#endif
static void __init preprocess_cmdline(void)
{
static char cmdline[COMMAND_LINE_SIZE] __initdata;
char *s;
strcpy(cmdline, arcs_cmdline);
s = cmdline;
arcs_cmdline[0] = '\0';
while (s && *s) {
char *str = strsep(&s, " ");
if (strncmp(str, "board=", 6) == 0) {
txx9_board_vec = find_board_byname(str + 6);
continue;
} else if (strncmp(str, "masterclk=", 10) == 0) {
unsigned long val;
if (strict_strtoul(str + 10, 10, &val) == 0)
txx9_master_clock = val;
continue;
} else if (strcmp(str, "icdisable") == 0) {
txx9_ic_disable = 1;
continue;
} else if (strcmp(str, "dcdisable") == 0) {
txx9_dc_disable = 1;
continue;
} else if (strcmp(str, "toeoff") == 0) {
txx9_ccfg_toeon = 0;
continue;
} else if (strcmp(str, "toeon") == 0) {
txx9_ccfg_toeon = 1;
continue;
}
if (arcs_cmdline[0])
strcat(arcs_cmdline, " ");
strcat(arcs_cmdline, str);
}
txx9_cache_fixup();
}
static void __init select_board(void)
{
const char *envstr;
/* first, determine by "board=" argument in preprocess_cmdline() */
if (txx9_board_vec)
return;
/* next, determine by "board" envvar */
envstr = prom_getenv("board");
if (envstr) {
txx9_board_vec = find_board_byname(envstr);
if (txx9_board_vec)
return;
}
/* select "default" board */
#ifdef CONFIG_CPU_TX39XX
txx9_board_vec = &jmr3927_vec;
#endif
#ifdef CONFIG_CPU_TX49XX
switch (TX4938_REV_PCODE()) {
#ifdef CONFIG_TOSHIBA_RBTX4927
case 0x4927:
txx9_board_vec = &rbtx4927_vec;
break;
case 0x4937:
txx9_board_vec = &rbtx4937_vec;
break;
#endif
#ifdef CONFIG_TOSHIBA_RBTX4938
case 0x4938:
txx9_board_vec = &rbtx4938_vec;
break;
#endif
#ifdef CONFIG_TOSHIBA_RBTX4939
case 0x4939:
txx9_board_vec = &rbtx4939_vec;
break;
#endif
}
#endif
}
void __init prom_init(void)
{
prom_init_cmdline();
preprocess_cmdline();
select_board();
strcpy(txx9_system_type, txx9_board_vec->system);
txx9_board_vec->prom_init();
}
void __init prom_free_prom_memory(void)
{
unsigned long saddr = PAGE_SIZE;
unsigned long eaddr = __pa_symbol(&_text);
if (saddr < eaddr)
free_init_pages("prom memory", saddr, eaddr);
}
const char *get_system_type(void)
{
return txx9_system_type;
}
const char *__init prom_getenv(const char *name)
{
const s32 *str;
if (fw_arg2 < CKSEG0)
return NULL;
str = (const s32 *)fw_arg2;
/* YAMON style ("name", "value" pairs) */
while (str[0] && str[1]) {
if (!strcmp((const char *)(unsigned long)str[0], name))
return (const char *)(unsigned long)str[1];
str += 2;
}
return NULL;
}
static void __noreturn txx9_machine_halt(void)
{
local_irq_disable();
clear_c0_status(ST0_IM);
while (1) {
if (cpu_wait) {
(*cpu_wait)();
if (cpu_has_counter) {
/*
* Clear counter interrupt while it
* breaks WAIT instruction even if
* masked.
*/
write_c0_compare(0);
}
}
}
}
/* Watchdog support */
void __init txx9_wdt_init(unsigned long base)
{
struct resource res = {
.start = base,
.end = base + 0x100 - 1,
.flags = IORESOURCE_MEM,
};
platform_device_register_simple("txx9wdt", -1, &res, 1);
}
void txx9_wdt_now(unsigned long base)
{
struct txx9_tmr_reg __iomem *tmrptr =
ioremap(base, sizeof(struct txx9_tmr_reg));
/* disable watch dog timer */
__raw_writel(TXx9_TMWTMR_WDIS | TXx9_TMWTMR_TWC, &tmrptr->wtmr);
__raw_writel(0, &tmrptr->tcr);
/* kick watchdog */
__raw_writel(TXx9_TMWTMR_TWIE, &tmrptr->wtmr);
__raw_writel(1, &tmrptr->cpra); /* immediate */
__raw_writel(TXx9_TMTCR_TCE | TXx9_TMTCR_CCDE | TXx9_TMTCR_TMODE_WDOG,
&tmrptr->tcr);
}
/* SPI support */
void __init txx9_spi_init(int busid, unsigned long base, int irq)
{
struct resource res[] = {
{
.start = base,
.end = base + 0x20 - 1,
.flags = IORESOURCE_MEM,
}, {
.start = irq,
.flags = IORESOURCE_IRQ,
},
};
platform_device_register_simple("spi_txx9", busid,
res, ARRAY_SIZE(res));
}
void __init txx9_ethaddr_init(unsigned int id, unsigned char *ethaddr)
{
struct platform_device *pdev =
platform_device_alloc("tc35815-mac", id);
if (!pdev ||
platform_device_add_data(pdev, ethaddr, 6) ||
platform_device_add(pdev))
platform_device_put(pdev);
}
void __init txx9_sio_init(unsigned long baseaddr, int irq,
unsigned int line, unsigned int sclk, int nocts)
{
#ifdef CONFIG_SERIAL_TXX9
struct uart_port req;
memset(&req, 0, sizeof(req));
req.line = line;
req.iotype = UPIO_MEM;
req.membase = ioremap(baseaddr, 0x24);
req.mapbase = baseaddr;
req.irq = irq;
if (!nocts)
req.flags |= UPF_BUGGY_UART /*HAVE_CTS_LINE*/;
if (sclk) {
req.flags |= UPF_MAGIC_MULTIPLIER /*USE_SCLK*/;
req.uartclk = sclk;
} else
req.uartclk = TXX9_IMCLK;
early_serial_txx9_setup(&req);
#endif /* CONFIG_SERIAL_TXX9 */
}
#ifdef CONFIG_EARLY_PRINTK
static void null_prom_putchar(char c)
{
}
void (*txx9_prom_putchar)(char c) = null_prom_putchar;
void prom_putchar(char c)
{
txx9_prom_putchar(c);
}
static void __iomem *early_txx9_sio_port;
static void early_txx9_sio_putchar(char c)
{
#define TXX9_SICISR 0x0c
#define TXX9_SITFIFO 0x1c
#define TXX9_SICISR_TXALS 0x00000002
while (!(__raw_readl(early_txx9_sio_port + TXX9_SICISR) &
TXX9_SICISR_TXALS))
;
__raw_writel(c, early_txx9_sio_port + TXX9_SITFIFO);
}
void __init txx9_sio_putchar_init(unsigned long baseaddr)
{
early_txx9_sio_port = ioremap(baseaddr, 0x24);
txx9_prom_putchar = early_txx9_sio_putchar;
}
#endif /* CONFIG_EARLY_PRINTK */
/* wrappers */
void __init plat_mem_setup(void)
{
ioport_resource.start = 0;
ioport_resource.end = ~0UL; /* no limit */
iomem_resource.start = 0;
iomem_resource.end = ~0UL; /* no limit */
/* fallback restart/halt routines */
_machine_restart = (void (*)(char *))txx9_machine_halt;
_machine_halt = txx9_machine_halt;
pm_power_off = txx9_machine_halt;
#ifdef CONFIG_PCI
pcibios_plat_setup = txx9_pcibios_setup;
#endif
txx9_board_vec->mem_setup();
}
void __init arch_init_irq(void)
{
txx9_board_vec->irq_setup();
}
void __init plat_time_init(void)
{
#ifdef CONFIG_CPU_TX49XX
mips_hpt_frequency = txx9_cpu_clock / 2;
#endif
txx9_board_vec->time_init();
}
static int __init _txx9_arch_init(void)
{
if (txx9_board_vec->arch_init)
txx9_board_vec->arch_init();
return 0;
}
arch_initcall(_txx9_arch_init);
static int __init _txx9_device_init(void)
{
if (txx9_board_vec->device_init)
txx9_board_vec->device_init();
return 0;
}
device_initcall(_txx9_device_init);
int (*txx9_irq_dispatch)(int pending);
asmlinkage void plat_irq_dispatch(void)
{
int pending = read_c0_status() & read_c0_cause() & ST0_IM;
int irq = txx9_irq_dispatch(pending);
if (likely(irq >= 0))
do_IRQ(irq);
else
spurious_interrupt();
}
/* see include/asm-mips/mach-tx39xx/mangle-port.h, for example. */
#ifdef NEEDS_TXX9_SWIZZLE_ADDR_B
static unsigned long __swizzle_addr_none(unsigned long port)
{
return port;
}
unsigned long (*__swizzle_addr_b)(unsigned long port) = __swizzle_addr_none;
EXPORT_SYMBOL(__swizzle_addr_b);
#endif
#ifdef NEEDS_TXX9_IOSWABW
static u16 ioswabw_default(volatile u16 *a, u16 x)
{
return le16_to_cpu(x);
}
static u16 __mem_ioswabw_default(volatile u16 *a, u16 x)
{
return x;
}
u16 (*ioswabw)(volatile u16 *a, u16 x) = ioswabw_default;
EXPORT_SYMBOL(ioswabw);
u16 (*__mem_ioswabw)(volatile u16 *a, u16 x) = __mem_ioswabw_default;
EXPORT_SYMBOL(__mem_ioswabw);
#endif
void __init txx9_physmap_flash_init(int no, unsigned long addr,
unsigned long size,
const struct physmap_flash_data *pdata)
{
#if IS_ENABLED(CONFIG_MTD_PHYSMAP)
struct resource res = {
.start = addr,
.end = addr + size - 1,
.flags = IORESOURCE_MEM,
};
struct platform_device *pdev;
static struct mtd_partition parts[2];
struct physmap_flash_data pdata_part;
/* If this area contained boot area, make separate partition */
if (pdata->nr_parts == 0 && !pdata->parts &&
addr < 0x1fc00000 && addr + size > 0x1fc00000 &&
!parts[0].name) {
parts[0].name = "boot";
parts[0].offset = 0x1fc00000 - addr;
parts[0].size = addr + size - 0x1fc00000;
parts[1].name = "user";
parts[1].offset = 0;
parts[1].size = 0x1fc00000 - addr;
pdata_part = *pdata;
pdata_part.nr_parts = ARRAY_SIZE(parts);
pdata_part.parts = parts;
pdata = &pdata_part;
}
pdev = platform_device_alloc("physmap-flash", no);
if (!pdev ||
platform_device_add_resources(pdev, &res, 1) ||
platform_device_add_data(pdev, pdata, sizeof(*pdata)) ||
platform_device_add(pdev))
platform_device_put(pdev);
#endif
}
void __init txx9_ndfmc_init(unsigned long baseaddr,
const struct txx9ndfmc_platform_data *pdata)
{
#if IS_ENABLED(CONFIG_MTD_NAND_TXX9NDFMC)
struct resource res = {
.start = baseaddr,
.end = baseaddr + 0x1000 - 1,
.flags = IORESOURCE_MEM,
};
struct platform_device *pdev = platform_device_alloc("txx9ndfmc", -1);
if (!pdev ||
platform_device_add_resources(pdev, &res, 1) ||
platform_device_add_data(pdev, pdata, sizeof(*pdata)) ||
platform_device_add(pdev))
platform_device_put(pdev);
#endif
}
#if IS_ENABLED(CONFIG_LEDS_GPIO)
static DEFINE_SPINLOCK(txx9_iocled_lock);
#define TXX9_IOCLED_MAXLEDS 8
struct txx9_iocled_data {
struct gpio_chip chip;
u8 cur_val;
void __iomem *mmioaddr;
struct gpio_led_platform_data pdata;
struct gpio_led leds[TXX9_IOCLED_MAXLEDS];
char names[TXX9_IOCLED_MAXLEDS][32];
};
static int txx9_iocled_get(struct gpio_chip *chip, unsigned int offset)
{
struct txx9_iocled_data *data =
container_of(chip, struct txx9_iocled_data, chip);
return data->cur_val & (1 << offset);
}
static void txx9_iocled_set(struct gpio_chip *chip, unsigned int offset,
int value)
{
struct txx9_iocled_data *data =
container_of(chip, struct txx9_iocled_data, chip);
unsigned long flags;
spin_lock_irqsave(&txx9_iocled_lock, flags);
if (value)
data->cur_val |= 1 << offset;
else
data->cur_val &= ~(1 << offset);
writeb(data->cur_val, data->mmioaddr);
mmiowb();
spin_unlock_irqrestore(&txx9_iocled_lock, flags);
}
static int txx9_iocled_dir_in(struct gpio_chip *chip, unsigned int offset)
{
return 0;
}
static int txx9_iocled_dir_out(struct gpio_chip *chip, unsigned int offset,
int value)
{
txx9_iocled_set(chip, offset, value);
return 0;
}
void __init txx9_iocled_init(unsigned long baseaddr,
int basenum, unsigned int num, int lowactive,
const char *color, char **deftriggers)
{
struct txx9_iocled_data *iocled;
struct platform_device *pdev;
int i;
static char *default_triggers[] __initdata = {
"heartbeat",
"ide-disk",
"nand-disk",
NULL,
};
if (!deftriggers)
deftriggers = default_triggers;
iocled = kzalloc(sizeof(*iocled), GFP_KERNEL);
if (!iocled)
return;
iocled->mmioaddr = ioremap(baseaddr, 1);
if (!iocled->mmioaddr)
goto out_free;
iocled->chip.get = txx9_iocled_get;
iocled->chip.set = txx9_iocled_set;
iocled->chip.direction_input = txx9_iocled_dir_in;
iocled->chip.direction_output = txx9_iocled_dir_out;
iocled->chip.label = "iocled";
iocled->chip.base = basenum;
iocled->chip.ngpio = num;
if (gpiochip_add(&iocled->chip))
goto out_unmap;
if (basenum < 0)
basenum = iocled->chip.base;
pdev = platform_device_alloc("leds-gpio", basenum);
if (!pdev)
goto out_gpio;
iocled->pdata.num_leds = num;
iocled->pdata.leds = iocled->leds;
for (i = 0; i < num; i++) {
struct gpio_led *led = &iocled->leds[i];
snprintf(iocled->names[i], sizeof(iocled->names[i]),
"iocled:%s:%u", color, i);
led->name = iocled->names[i];
led->gpio = basenum + i;
led->active_low = lowactive;
if (deftriggers && *deftriggers)
led->default_trigger = *deftriggers++;
}
pdev->dev.platform_data = &iocled->pdata;
if (platform_device_add(pdev))
goto out_pdev;
return;
out_pdev:
platform_device_put(pdev);
out_gpio:
if (gpiochip_remove(&iocled->chip))
return;
out_unmap:
iounmap(iocled->mmioaddr);
out_free:
kfree(iocled);
}
#else /* CONFIG_LEDS_GPIO */
void __init txx9_iocled_init(unsigned long baseaddr,
int basenum, unsigned int num, int lowactive,
const char *color, char **deftriggers)
{
}
#endif /* CONFIG_LEDS_GPIO */
void __init txx9_dmac_init(int id, unsigned long baseaddr, int irq,
const struct txx9dmac_platform_data *pdata)
{
#if IS_ENABLED(CONFIG_TXX9_DMAC)
struct resource res[] = {
{
.start = baseaddr,
.end = baseaddr + 0x800 - 1,
.flags = IORESOURCE_MEM,
#ifndef CONFIG_MACH_TX49XX
}, {
.start = irq,
.flags = IORESOURCE_IRQ,
#endif
}
};
#ifdef CONFIG_MACH_TX49XX
struct resource chan_res[] = {
{
.flags = IORESOURCE_IRQ,
}
};
#endif
struct platform_device *pdev = platform_device_alloc("txx9dmac", id);
struct txx9dmac_chan_platform_data cpdata;
int i;
if (!pdev ||
platform_device_add_resources(pdev, res, ARRAY_SIZE(res)) ||
platform_device_add_data(pdev, pdata, sizeof(*pdata)) ||
platform_device_add(pdev)) {
platform_device_put(pdev);
return;
}
memset(&cpdata, 0, sizeof(cpdata));
cpdata.dmac_dev = pdev;
for (i = 0; i < TXX9_DMA_MAX_NR_CHANNELS; i++) {
#ifdef CONFIG_MACH_TX49XX
chan_res[0].start = irq + i;
#endif
pdev = platform_device_alloc("txx9dmac-chan",
id * TXX9_DMA_MAX_NR_CHANNELS + i);
if (!pdev ||
#ifdef CONFIG_MACH_TX49XX
platform_device_add_resources(pdev, chan_res,
ARRAY_SIZE(chan_res)) ||
#endif
platform_device_add_data(pdev, &cpdata, sizeof(cpdata)) ||
platform_device_add(pdev))
platform_device_put(pdev);
}
#endif
}
void __init txx9_aclc_init(unsigned long baseaddr, int irq,
unsigned int dmac_id,
unsigned int dma_chan_out,
unsigned int dma_chan_in)
{
#if IS_ENABLED(CONFIG_SND_SOC_TXX9ACLC)
unsigned int dma_base = dmac_id * TXX9_DMA_MAX_NR_CHANNELS;
struct resource res[] = {
{
.start = baseaddr,
.end = baseaddr + 0x100 - 1,
.flags = IORESOURCE_MEM,
}, {
.start = irq,
.flags = IORESOURCE_IRQ,
}, {
.name = "txx9dmac-chan",
.start = dma_base + dma_chan_out,
.flags = IORESOURCE_DMA,
}, {
.name = "txx9dmac-chan",
.start = dma_base + dma_chan_in,
.flags = IORESOURCE_DMA,
}
};
struct platform_device *pdev =
platform_device_alloc("txx9aclc-ac97", -1);
if (!pdev ||
platform_device_add_resources(pdev, res, ARRAY_SIZE(res)) ||
platform_device_add(pdev))
platform_device_put(pdev);
#endif
}
static struct bus_type txx9_sramc_subsys = {
.name = "txx9_sram",
.dev_name = "txx9_sram",
};
struct txx9_sramc_dev {
struct device dev;
struct bin_attribute bindata_attr;
void __iomem *base;
};
static ssize_t txx9_sram_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t pos, size_t size)
{
struct txx9_sramc_dev *dev = bin_attr->private;
size_t ramsize = bin_attr->size;
if (pos >= ramsize)
return 0;
if (pos + size > ramsize)
size = ramsize - pos;
memcpy_fromio(buf, dev->base + pos, size);
return size;
}
static ssize_t txx9_sram_write(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t pos, size_t size)
{
struct txx9_sramc_dev *dev = bin_attr->private;
size_t ramsize = bin_attr->size;
if (pos >= ramsize)
return 0;
if (pos + size > ramsize)
size = ramsize - pos;
memcpy_toio(dev->base + pos, buf, size);
return size;
}
void __init txx9_sramc_init(struct resource *r)
{
struct txx9_sramc_dev *dev;
size_t size;
int err;
err = subsys_system_register(&txx9_sramc_subsys, NULL);
if (err)
return;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return;
size = resource_size(r);
dev->base = ioremap(r->start, size);
if (!dev->base)
goto exit;
dev->dev.bus = &txx9_sramc_subsys;
sysfs_bin_attr_init(&dev->bindata_attr);
dev->bindata_attr.attr.name = "bindata";
dev->bindata_attr.attr.mode = S_IRUSR | S_IWUSR;
dev->bindata_attr.read = txx9_sram_read;
dev->bindata_attr.write = txx9_sram_write;
dev->bindata_attr.size = size;
dev->bindata_attr.private = dev;
err = device_register(&dev->dev);
if (err)
goto exit;
err = sysfs_create_bin_file(&dev->dev.kobj, &dev->bindata_attr);
if (err) {
device_unregister(&dev->dev);
goto exit;
}
return;
exit:
if (dev) {
if (dev->base)
iounmap(dev->base);
kfree(dev);
}
}
| gpl-2.0 |
AndroidOpenDevelopment-Devices/android_kernel_moto_shamu | drivers/net/ethernet/intel/ixgbe/ixgbe_x540.c | 2255 | 26556 | /*******************************************************************************
Intel 10 Gigabit PCI Express Linux driver
Copyright(c) 1999 - 2013 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include "ixgbe.h"
#include "ixgbe_phy.h"
#define IXGBE_X540_MAX_TX_QUEUES 128
#define IXGBE_X540_MAX_RX_QUEUES 128
#define IXGBE_X540_RAR_ENTRIES 128
#define IXGBE_X540_MC_TBL_SIZE 128
#define IXGBE_X540_VFT_TBL_SIZE 128
#define IXGBE_X540_RX_PB_SIZE 384
static s32 ixgbe_update_flash_X540(struct ixgbe_hw *hw);
static s32 ixgbe_poll_flash_update_done_X540(struct ixgbe_hw *hw);
static s32 ixgbe_acquire_swfw_sync_X540(struct ixgbe_hw *hw, u16 mask);
static void ixgbe_release_swfw_sync_X540(struct ixgbe_hw *hw, u16 mask);
static s32 ixgbe_get_swfw_sync_semaphore(struct ixgbe_hw *hw);
static void ixgbe_release_swfw_sync_semaphore(struct ixgbe_hw *hw);
static enum ixgbe_media_type ixgbe_get_media_type_X540(struct ixgbe_hw *hw)
{
return ixgbe_media_type_copper;
}
static s32 ixgbe_get_invariants_X540(struct ixgbe_hw *hw)
{
struct ixgbe_mac_info *mac = &hw->mac;
/* Call PHY identify routine to get the phy type */
ixgbe_identify_phy_generic(hw);
mac->mcft_size = IXGBE_X540_MC_TBL_SIZE;
mac->vft_size = IXGBE_X540_VFT_TBL_SIZE;
mac->num_rar_entries = IXGBE_X540_RAR_ENTRIES;
mac->max_rx_queues = IXGBE_X540_MAX_RX_QUEUES;
mac->max_tx_queues = IXGBE_X540_MAX_TX_QUEUES;
mac->max_msix_vectors = ixgbe_get_pcie_msix_count_generic(hw);
return 0;
}
/**
* ixgbe_setup_mac_link_X540 - Set the auto advertised capabilitires
* @hw: pointer to hardware structure
* @speed: new link speed
* @autoneg_wait_to_complete: true when waiting for completion is needed
**/
static s32 ixgbe_setup_mac_link_X540(struct ixgbe_hw *hw,
ixgbe_link_speed speed,
bool autoneg_wait_to_complete)
{
return hw->phy.ops.setup_link_speed(hw, speed,
autoneg_wait_to_complete);
}
/**
* ixgbe_reset_hw_X540 - Perform hardware reset
* @hw: pointer to hardware structure
*
* Resets the hardware by resetting the transmit and receive units, masks
* and clears all interrupts, perform a PHY reset, and perform a link (MAC)
* reset.
**/
static s32 ixgbe_reset_hw_X540(struct ixgbe_hw *hw)
{
s32 status;
u32 ctrl, i;
/* Call adapter stop to disable tx/rx and clear interrupts */
status = hw->mac.ops.stop_adapter(hw);
if (status != 0)
goto reset_hw_out;
/* flush pending Tx transactions */
ixgbe_clear_tx_pending(hw);
mac_reset_top:
ctrl = IXGBE_CTRL_RST;
ctrl |= IXGBE_READ_REG(hw, IXGBE_CTRL);
IXGBE_WRITE_REG(hw, IXGBE_CTRL, ctrl);
IXGBE_WRITE_FLUSH(hw);
/* Poll for reset bit to self-clear indicating reset is complete */
for (i = 0; i < 10; i++) {
udelay(1);
ctrl = IXGBE_READ_REG(hw, IXGBE_CTRL);
if (!(ctrl & IXGBE_CTRL_RST_MASK))
break;
}
if (ctrl & IXGBE_CTRL_RST_MASK) {
status = IXGBE_ERR_RESET_FAILED;
hw_dbg(hw, "Reset polling failed to complete.\n");
}
msleep(100);
/*
* Double resets are required for recovery from certain error
* conditions. Between resets, it is necessary to stall to allow time
* for any pending HW events to complete.
*/
if (hw->mac.flags & IXGBE_FLAGS_DOUBLE_RESET_REQUIRED) {
hw->mac.flags &= ~IXGBE_FLAGS_DOUBLE_RESET_REQUIRED;
goto mac_reset_top;
}
/* Set the Rx packet buffer size. */
IXGBE_WRITE_REG(hw, IXGBE_RXPBSIZE(0), 384 << IXGBE_RXPBSIZE_SHIFT);
/* Store the permanent mac address */
hw->mac.ops.get_mac_addr(hw, hw->mac.perm_addr);
/*
* Store MAC address from RAR0, clear receive address registers, and
* clear the multicast table. Also reset num_rar_entries to 128,
* since we modify this value when programming the SAN MAC address.
*/
hw->mac.num_rar_entries = IXGBE_X540_MAX_TX_QUEUES;
hw->mac.ops.init_rx_addrs(hw);
/* Store the permanent SAN mac address */
hw->mac.ops.get_san_mac_addr(hw, hw->mac.san_addr);
/* Add the SAN MAC address to the RAR only if it's a valid address */
if (is_valid_ether_addr(hw->mac.san_addr)) {
hw->mac.ops.set_rar(hw, hw->mac.num_rar_entries - 1,
hw->mac.san_addr, 0, IXGBE_RAH_AV);
/* Save the SAN MAC RAR index */
hw->mac.san_mac_rar_index = hw->mac.num_rar_entries - 1;
/* Reserve the last RAR for the SAN MAC address */
hw->mac.num_rar_entries--;
}
/* Store the alternative WWNN/WWPN prefix */
hw->mac.ops.get_wwn_prefix(hw, &hw->mac.wwnn_prefix,
&hw->mac.wwpn_prefix);
reset_hw_out:
return status;
}
/**
* ixgbe_start_hw_X540 - Prepare hardware for Tx/Rx
* @hw: pointer to hardware structure
*
* Starts the hardware using the generic start_hw function
* and the generation start_hw function.
* Then performs revision-specific operations, if any.
**/
static s32 ixgbe_start_hw_X540(struct ixgbe_hw *hw)
{
s32 ret_val = 0;
ret_val = ixgbe_start_hw_generic(hw);
if (ret_val != 0)
goto out;
ret_val = ixgbe_start_hw_gen2(hw);
hw->mac.rx_pb_size = IXGBE_X540_RX_PB_SIZE;
out:
return ret_val;
}
/**
* ixgbe_get_supported_physical_layer_X540 - Returns physical layer type
* @hw: pointer to hardware structure
*
* Determines physical layer capabilities of the current configuration.
**/
static u32 ixgbe_get_supported_physical_layer_X540(struct ixgbe_hw *hw)
{
u32 physical_layer = IXGBE_PHYSICAL_LAYER_UNKNOWN;
u16 ext_ability = 0;
hw->phy.ops.identify(hw);
hw->phy.ops.read_reg(hw, MDIO_PMA_EXTABLE, MDIO_MMD_PMAPMD,
&ext_ability);
if (ext_ability & MDIO_PMA_EXTABLE_10GBT)
physical_layer |= IXGBE_PHYSICAL_LAYER_10GBASE_T;
if (ext_ability & MDIO_PMA_EXTABLE_1000BT)
physical_layer |= IXGBE_PHYSICAL_LAYER_1000BASE_T;
if (ext_ability & MDIO_PMA_EXTABLE_100BTX)
physical_layer |= IXGBE_PHYSICAL_LAYER_100BASE_TX;
return physical_layer;
}
/**
* ixgbe_init_eeprom_params_X540 - Initialize EEPROM params
* @hw: pointer to hardware structure
*
* Initializes the EEPROM parameters ixgbe_eeprom_info within the
* ixgbe_hw struct in order to set up EEPROM access.
**/
static s32 ixgbe_init_eeprom_params_X540(struct ixgbe_hw *hw)
{
struct ixgbe_eeprom_info *eeprom = &hw->eeprom;
u32 eec;
u16 eeprom_size;
if (eeprom->type == ixgbe_eeprom_uninitialized) {
eeprom->semaphore_delay = 10;
eeprom->type = ixgbe_flash;
eec = IXGBE_READ_REG(hw, IXGBE_EEC);
eeprom_size = (u16)((eec & IXGBE_EEC_SIZE) >>
IXGBE_EEC_SIZE_SHIFT);
eeprom->word_size = 1 << (eeprom_size +
IXGBE_EEPROM_WORD_SIZE_SHIFT);
hw_dbg(hw, "Eeprom params: type = %d, size = %d\n",
eeprom->type, eeprom->word_size);
}
return 0;
}
/**
* ixgbe_read_eerd_X540- Read EEPROM word using EERD
* @hw: pointer to hardware structure
* @offset: offset of word in the EEPROM to read
* @data: word read from the EEPROM
*
* Reads a 16 bit word from the EEPROM using the EERD register.
**/
static s32 ixgbe_read_eerd_X540(struct ixgbe_hw *hw, u16 offset, u16 *data)
{
s32 status = 0;
if (hw->mac.ops.acquire_swfw_sync(hw, IXGBE_GSSR_EEP_SM) ==
0)
status = ixgbe_read_eerd_generic(hw, offset, data);
else
status = IXGBE_ERR_SWFW_SYNC;
hw->mac.ops.release_swfw_sync(hw, IXGBE_GSSR_EEP_SM);
return status;
}
/**
* ixgbe_read_eerd_buffer_X540 - Read EEPROM word(s) using EERD
* @hw: pointer to hardware structure
* @offset: offset of word in the EEPROM to read
* @words: number of words
* @data: word(s) read from the EEPROM
*
* Reads a 16 bit word(s) from the EEPROM using the EERD register.
**/
static s32 ixgbe_read_eerd_buffer_X540(struct ixgbe_hw *hw,
u16 offset, u16 words, u16 *data)
{
s32 status = 0;
if (hw->mac.ops.acquire_swfw_sync(hw, IXGBE_GSSR_EEP_SM) ==
0)
status = ixgbe_read_eerd_buffer_generic(hw, offset,
words, data);
else
status = IXGBE_ERR_SWFW_SYNC;
hw->mac.ops.release_swfw_sync(hw, IXGBE_GSSR_EEP_SM);
return status;
}
/**
* ixgbe_write_eewr_X540 - Write EEPROM word using EEWR
* @hw: pointer to hardware structure
* @offset: offset of word in the EEPROM to write
* @data: word write to the EEPROM
*
* Write a 16 bit word to the EEPROM using the EEWR register.
**/
static s32 ixgbe_write_eewr_X540(struct ixgbe_hw *hw, u16 offset, u16 data)
{
s32 status = 0;
if (hw->mac.ops.acquire_swfw_sync(hw, IXGBE_GSSR_EEP_SM) == 0)
status = ixgbe_write_eewr_generic(hw, offset, data);
else
status = IXGBE_ERR_SWFW_SYNC;
hw->mac.ops.release_swfw_sync(hw, IXGBE_GSSR_EEP_SM);
return status;
}
/**
* ixgbe_write_eewr_buffer_X540 - Write EEPROM word(s) using EEWR
* @hw: pointer to hardware structure
* @offset: offset of word in the EEPROM to write
* @words: number of words
* @data: word(s) write to the EEPROM
*
* Write a 16 bit word(s) to the EEPROM using the EEWR register.
**/
static s32 ixgbe_write_eewr_buffer_X540(struct ixgbe_hw *hw,
u16 offset, u16 words, u16 *data)
{
s32 status = 0;
if (hw->mac.ops.acquire_swfw_sync(hw, IXGBE_GSSR_EEP_SM) ==
0)
status = ixgbe_write_eewr_buffer_generic(hw, offset,
words, data);
else
status = IXGBE_ERR_SWFW_SYNC;
hw->mac.ops.release_swfw_sync(hw, IXGBE_GSSR_EEP_SM);
return status;
}
/**
* ixgbe_calc_eeprom_checksum_X540 - Calculates and returns the checksum
*
* This function does not use synchronization for EERD and EEWR. It can
* be used internally by function which utilize ixgbe_acquire_swfw_sync_X540.
*
* @hw: pointer to hardware structure
**/
static u16 ixgbe_calc_eeprom_checksum_X540(struct ixgbe_hw *hw)
{
u16 i;
u16 j;
u16 checksum = 0;
u16 length = 0;
u16 pointer = 0;
u16 word = 0;
/*
* Do not use hw->eeprom.ops.read because we do not want to take
* the synchronization semaphores here. Instead use
* ixgbe_read_eerd_generic
*/
/* Include 0x0-0x3F in the checksum */
for (i = 0; i < IXGBE_EEPROM_CHECKSUM; i++) {
if (ixgbe_read_eerd_generic(hw, i, &word) != 0) {
hw_dbg(hw, "EEPROM read failed\n");
break;
}
checksum += word;
}
/*
* Include all data from pointers 0x3, 0x6-0xE. This excludes the
* FW, PHY module, and PCIe Expansion/Option ROM pointers.
*/
for (i = IXGBE_PCIE_ANALOG_PTR; i < IXGBE_FW_PTR; i++) {
if (i == IXGBE_PHY_PTR || i == IXGBE_OPTION_ROM_PTR)
continue;
if (ixgbe_read_eerd_generic(hw, i, &pointer) != 0) {
hw_dbg(hw, "EEPROM read failed\n");
break;
}
/* Skip pointer section if the pointer is invalid. */
if (pointer == 0xFFFF || pointer == 0 ||
pointer >= hw->eeprom.word_size)
continue;
if (ixgbe_read_eerd_generic(hw, pointer, &length) != 0) {
hw_dbg(hw, "EEPROM read failed\n");
break;
}
/* Skip pointer section if length is invalid. */
if (length == 0xFFFF || length == 0 ||
(pointer + length) >= hw->eeprom.word_size)
continue;
for (j = pointer+1; j <= pointer+length; j++) {
if (ixgbe_read_eerd_generic(hw, j, &word) != 0) {
hw_dbg(hw, "EEPROM read failed\n");
break;
}
checksum += word;
}
}
checksum = (u16)IXGBE_EEPROM_SUM - checksum;
return checksum;
}
/**
* ixgbe_validate_eeprom_checksum_X540 - Validate EEPROM checksum
* @hw: pointer to hardware structure
* @checksum_val: calculated checksum
*
* Performs checksum calculation and validates the EEPROM checksum. If the
* caller does not need checksum_val, the value can be NULL.
**/
static s32 ixgbe_validate_eeprom_checksum_X540(struct ixgbe_hw *hw,
u16 *checksum_val)
{
s32 status;
u16 checksum;
u16 read_checksum = 0;
/*
* Read the first word from the EEPROM. If this times out or fails, do
* not continue or we could be in for a very long wait while every
* EEPROM read fails
*/
status = hw->eeprom.ops.read(hw, 0, &checksum);
if (status != 0) {
hw_dbg(hw, "EEPROM read failed\n");
goto out;
}
if (hw->mac.ops.acquire_swfw_sync(hw, IXGBE_GSSR_EEP_SM) == 0) {
checksum = hw->eeprom.ops.calc_checksum(hw);
/*
* Do not use hw->eeprom.ops.read because we do not want to take
* the synchronization semaphores twice here.
*/
ixgbe_read_eerd_generic(hw, IXGBE_EEPROM_CHECKSUM,
&read_checksum);
/*
* Verify read checksum from EEPROM is the same as
* calculated checksum
*/
if (read_checksum != checksum)
status = IXGBE_ERR_EEPROM_CHECKSUM;
/* If the user cares, return the calculated checksum */
if (checksum_val)
*checksum_val = checksum;
} else {
status = IXGBE_ERR_SWFW_SYNC;
}
hw->mac.ops.release_swfw_sync(hw, IXGBE_GSSR_EEP_SM);
out:
return status;
}
/**
* ixgbe_update_eeprom_checksum_X540 - Updates the EEPROM checksum and flash
* @hw: pointer to hardware structure
*
* After writing EEPROM to shadow RAM using EEWR register, software calculates
* checksum and updates the EEPROM and instructs the hardware to update
* the flash.
**/
static s32 ixgbe_update_eeprom_checksum_X540(struct ixgbe_hw *hw)
{
s32 status;
u16 checksum;
/*
* Read the first word from the EEPROM. If this times out or fails, do
* not continue or we could be in for a very long wait while every
* EEPROM read fails
*/
status = hw->eeprom.ops.read(hw, 0, &checksum);
if (status != 0)
hw_dbg(hw, "EEPROM read failed\n");
if (hw->mac.ops.acquire_swfw_sync(hw, IXGBE_GSSR_EEP_SM) == 0) {
checksum = hw->eeprom.ops.calc_checksum(hw);
/*
* Do not use hw->eeprom.ops.write because we do not want to
* take the synchronization semaphores twice here.
*/
status = ixgbe_write_eewr_generic(hw, IXGBE_EEPROM_CHECKSUM,
checksum);
if (status == 0)
status = ixgbe_update_flash_X540(hw);
else
status = IXGBE_ERR_SWFW_SYNC;
}
hw->mac.ops.release_swfw_sync(hw, IXGBE_GSSR_EEP_SM);
return status;
}
/**
* ixgbe_update_flash_X540 - Instruct HW to copy EEPROM to Flash device
* @hw: pointer to hardware structure
*
* Set FLUP (bit 23) of the EEC register to instruct Hardware to copy
* EEPROM from shadow RAM to the flash device.
**/
static s32 ixgbe_update_flash_X540(struct ixgbe_hw *hw)
{
u32 flup;
s32 status = IXGBE_ERR_EEPROM;
status = ixgbe_poll_flash_update_done_X540(hw);
if (status == IXGBE_ERR_EEPROM) {
hw_dbg(hw, "Flash update time out\n");
goto out;
}
flup = IXGBE_READ_REG(hw, IXGBE_EEC) | IXGBE_EEC_FLUP;
IXGBE_WRITE_REG(hw, IXGBE_EEC, flup);
status = ixgbe_poll_flash_update_done_X540(hw);
if (status == 0)
hw_dbg(hw, "Flash update complete\n");
else
hw_dbg(hw, "Flash update time out\n");
if (hw->revision_id == 0) {
flup = IXGBE_READ_REG(hw, IXGBE_EEC);
if (flup & IXGBE_EEC_SEC1VAL) {
flup |= IXGBE_EEC_FLUP;
IXGBE_WRITE_REG(hw, IXGBE_EEC, flup);
}
status = ixgbe_poll_flash_update_done_X540(hw);
if (status == 0)
hw_dbg(hw, "Flash update complete\n");
else
hw_dbg(hw, "Flash update time out\n");
}
out:
return status;
}
/**
* ixgbe_poll_flash_update_done_X540 - Poll flash update status
* @hw: pointer to hardware structure
*
* Polls the FLUDONE (bit 26) of the EEC Register to determine when the
* flash update is done.
**/
static s32 ixgbe_poll_flash_update_done_X540(struct ixgbe_hw *hw)
{
u32 i;
u32 reg;
s32 status = IXGBE_ERR_EEPROM;
for (i = 0; i < IXGBE_FLUDONE_ATTEMPTS; i++) {
reg = IXGBE_READ_REG(hw, IXGBE_EEC);
if (reg & IXGBE_EEC_FLUDONE) {
status = 0;
break;
}
udelay(5);
}
return status;
}
/**
* ixgbe_acquire_swfw_sync_X540 - Acquire SWFW semaphore
* @hw: pointer to hardware structure
* @mask: Mask to specify which semaphore to acquire
*
* Acquires the SWFW semaphore thought the SW_FW_SYNC register for
* the specified function (CSR, PHY0, PHY1, NVM, Flash)
**/
static s32 ixgbe_acquire_swfw_sync_X540(struct ixgbe_hw *hw, u16 mask)
{
u32 swfw_sync;
u32 swmask = mask;
u32 fwmask = mask << 5;
u32 hwmask = 0;
u32 timeout = 200;
u32 i;
if (swmask == IXGBE_GSSR_EEP_SM)
hwmask = IXGBE_GSSR_FLASH_SM;
for (i = 0; i < timeout; i++) {
/*
* SW NVM semaphore bit is used for access to all
* SW_FW_SYNC bits (not just NVM)
*/
if (ixgbe_get_swfw_sync_semaphore(hw))
return IXGBE_ERR_SWFW_SYNC;
swfw_sync = IXGBE_READ_REG(hw, IXGBE_SWFW_SYNC);
if (!(swfw_sync & (fwmask | swmask | hwmask))) {
swfw_sync |= swmask;
IXGBE_WRITE_REG(hw, IXGBE_SWFW_SYNC, swfw_sync);
ixgbe_release_swfw_sync_semaphore(hw);
break;
} else {
/*
* Firmware currently using resource (fwmask),
* hardware currently using resource (hwmask),
* or other software thread currently using
* resource (swmask)
*/
ixgbe_release_swfw_sync_semaphore(hw);
usleep_range(5000, 10000);
}
}
/*
* If the resource is not released by the FW/HW the SW can assume that
* the FW/HW malfunctions. In that case the SW should sets the
* SW bit(s) of the requested resource(s) while ignoring the
* corresponding FW/HW bits in the SW_FW_SYNC register.
*/
if (i >= timeout) {
swfw_sync = IXGBE_READ_REG(hw, IXGBE_SWFW_SYNC);
if (swfw_sync & (fwmask | hwmask)) {
if (ixgbe_get_swfw_sync_semaphore(hw))
return IXGBE_ERR_SWFW_SYNC;
swfw_sync |= swmask;
IXGBE_WRITE_REG(hw, IXGBE_SWFW_SYNC, swfw_sync);
ixgbe_release_swfw_sync_semaphore(hw);
}
}
usleep_range(5000, 10000);
return 0;
}
/**
* ixgbe_release_swfw_sync_X540 - Release SWFW semaphore
* @hw: pointer to hardware structure
* @mask: Mask to specify which semaphore to release
*
* Releases the SWFW semaphore through the SW_FW_SYNC register
* for the specified function (CSR, PHY0, PHY1, EVM, Flash)
**/
static void ixgbe_release_swfw_sync_X540(struct ixgbe_hw *hw, u16 mask)
{
u32 swfw_sync;
u32 swmask = mask;
ixgbe_get_swfw_sync_semaphore(hw);
swfw_sync = IXGBE_READ_REG(hw, IXGBE_SWFW_SYNC);
swfw_sync &= ~swmask;
IXGBE_WRITE_REG(hw, IXGBE_SWFW_SYNC, swfw_sync);
ixgbe_release_swfw_sync_semaphore(hw);
usleep_range(5000, 10000);
}
/**
* ixgbe_get_nvm_semaphore - Get hardware semaphore
* @hw: pointer to hardware structure
*
* Sets the hardware semaphores so SW/FW can gain control of shared resources
**/
static s32 ixgbe_get_swfw_sync_semaphore(struct ixgbe_hw *hw)
{
s32 status = IXGBE_ERR_EEPROM;
u32 timeout = 2000;
u32 i;
u32 swsm;
/* Get SMBI software semaphore between device drivers first */
for (i = 0; i < timeout; i++) {
/*
* If the SMBI bit is 0 when we read it, then the bit will be
* set and we have the semaphore
*/
swsm = IXGBE_READ_REG(hw, IXGBE_SWSM);
if (!(swsm & IXGBE_SWSM_SMBI)) {
status = 0;
break;
}
udelay(50);
}
/* Now get the semaphore between SW/FW through the REGSMP bit */
if (status) {
for (i = 0; i < timeout; i++) {
swsm = IXGBE_READ_REG(hw, IXGBE_SWFW_SYNC);
if (!(swsm & IXGBE_SWFW_REGSMP))
break;
udelay(50);
}
} else {
hw_dbg(hw, "Software semaphore SMBI between device drivers "
"not granted.\n");
}
return status;
}
/**
* ixgbe_release_nvm_semaphore - Release hardware semaphore
* @hw: pointer to hardware structure
*
* This function clears hardware semaphore bits.
**/
static void ixgbe_release_swfw_sync_semaphore(struct ixgbe_hw *hw)
{
u32 swsm;
/* Release both semaphores by writing 0 to the bits REGSMP and SMBI */
swsm = IXGBE_READ_REG(hw, IXGBE_SWSM);
swsm &= ~IXGBE_SWSM_SMBI;
IXGBE_WRITE_REG(hw, IXGBE_SWSM, swsm);
swsm = IXGBE_READ_REG(hw, IXGBE_SWFW_SYNC);
swsm &= ~IXGBE_SWFW_REGSMP;
IXGBE_WRITE_REG(hw, IXGBE_SWFW_SYNC, swsm);
IXGBE_WRITE_FLUSH(hw);
}
/**
* ixgbe_blink_led_start_X540 - Blink LED based on index.
* @hw: pointer to hardware structure
* @index: led number to blink
*
* Devices that implement the version 2 interface:
* X540
**/
static s32 ixgbe_blink_led_start_X540(struct ixgbe_hw *hw, u32 index)
{
u32 macc_reg;
u32 ledctl_reg;
ixgbe_link_speed speed;
bool link_up;
/*
* Link should be up in order for the blink bit in the LED control
* register to work. Force link and speed in the MAC if link is down.
* This will be reversed when we stop the blinking.
*/
hw->mac.ops.check_link(hw, &speed, &link_up, false);
if (!link_up) {
macc_reg = IXGBE_READ_REG(hw, IXGBE_MACC);
macc_reg |= IXGBE_MACC_FLU | IXGBE_MACC_FSV_10G | IXGBE_MACC_FS;
IXGBE_WRITE_REG(hw, IXGBE_MACC, macc_reg);
}
/* Set the LED to LINK_UP + BLINK. */
ledctl_reg = IXGBE_READ_REG(hw, IXGBE_LEDCTL);
ledctl_reg &= ~IXGBE_LED_MODE_MASK(index);
ledctl_reg |= IXGBE_LED_BLINK(index);
IXGBE_WRITE_REG(hw, IXGBE_LEDCTL, ledctl_reg);
IXGBE_WRITE_FLUSH(hw);
return 0;
}
/**
* ixgbe_blink_led_stop_X540 - Stop blinking LED based on index.
* @hw: pointer to hardware structure
* @index: led number to stop blinking
*
* Devices that implement the version 2 interface:
* X540
**/
static s32 ixgbe_blink_led_stop_X540(struct ixgbe_hw *hw, u32 index)
{
u32 macc_reg;
u32 ledctl_reg;
/* Restore the LED to its default value. */
ledctl_reg = IXGBE_READ_REG(hw, IXGBE_LEDCTL);
ledctl_reg &= ~IXGBE_LED_MODE_MASK(index);
ledctl_reg |= IXGBE_LED_LINK_ACTIVE << IXGBE_LED_MODE_SHIFT(index);
ledctl_reg &= ~IXGBE_LED_BLINK(index);
IXGBE_WRITE_REG(hw, IXGBE_LEDCTL, ledctl_reg);
/* Unforce link and speed in the MAC. */
macc_reg = IXGBE_READ_REG(hw, IXGBE_MACC);
macc_reg &= ~(IXGBE_MACC_FLU | IXGBE_MACC_FSV_10G | IXGBE_MACC_FS);
IXGBE_WRITE_REG(hw, IXGBE_MACC, macc_reg);
IXGBE_WRITE_FLUSH(hw);
return 0;
}
static struct ixgbe_mac_operations mac_ops_X540 = {
.init_hw = &ixgbe_init_hw_generic,
.reset_hw = &ixgbe_reset_hw_X540,
.start_hw = &ixgbe_start_hw_X540,
.clear_hw_cntrs = &ixgbe_clear_hw_cntrs_generic,
.get_media_type = &ixgbe_get_media_type_X540,
.get_supported_physical_layer =
&ixgbe_get_supported_physical_layer_X540,
.enable_rx_dma = &ixgbe_enable_rx_dma_generic,
.get_mac_addr = &ixgbe_get_mac_addr_generic,
.get_san_mac_addr = &ixgbe_get_san_mac_addr_generic,
.get_device_caps = &ixgbe_get_device_caps_generic,
.get_wwn_prefix = &ixgbe_get_wwn_prefix_generic,
.stop_adapter = &ixgbe_stop_adapter_generic,
.get_bus_info = &ixgbe_get_bus_info_generic,
.set_lan_id = &ixgbe_set_lan_id_multi_port_pcie,
.read_analog_reg8 = NULL,
.write_analog_reg8 = NULL,
.setup_link = &ixgbe_setup_mac_link_X540,
.set_rxpba = &ixgbe_set_rxpba_generic,
.check_link = &ixgbe_check_mac_link_generic,
.get_link_capabilities = &ixgbe_get_copper_link_capabilities_generic,
.led_on = &ixgbe_led_on_generic,
.led_off = &ixgbe_led_off_generic,
.blink_led_start = &ixgbe_blink_led_start_X540,
.blink_led_stop = &ixgbe_blink_led_stop_X540,
.set_rar = &ixgbe_set_rar_generic,
.clear_rar = &ixgbe_clear_rar_generic,
.set_vmdq = &ixgbe_set_vmdq_generic,
.set_vmdq_san_mac = &ixgbe_set_vmdq_san_mac_generic,
.clear_vmdq = &ixgbe_clear_vmdq_generic,
.init_rx_addrs = &ixgbe_init_rx_addrs_generic,
.update_mc_addr_list = &ixgbe_update_mc_addr_list_generic,
.enable_mc = &ixgbe_enable_mc_generic,
.disable_mc = &ixgbe_disable_mc_generic,
.clear_vfta = &ixgbe_clear_vfta_generic,
.set_vfta = &ixgbe_set_vfta_generic,
.fc_enable = &ixgbe_fc_enable_generic,
.set_fw_drv_ver = &ixgbe_set_fw_drv_ver_generic,
.init_uta_tables = &ixgbe_init_uta_tables_generic,
.setup_sfp = NULL,
.set_mac_anti_spoofing = &ixgbe_set_mac_anti_spoofing,
.set_vlan_anti_spoofing = &ixgbe_set_vlan_anti_spoofing,
.acquire_swfw_sync = &ixgbe_acquire_swfw_sync_X540,
.release_swfw_sync = &ixgbe_release_swfw_sync_X540,
.disable_rx_buff = &ixgbe_disable_rx_buff_generic,
.enable_rx_buff = &ixgbe_enable_rx_buff_generic,
.get_thermal_sensor_data = NULL,
.init_thermal_sensor_thresh = NULL,
.mng_fw_enabled = NULL,
};
static struct ixgbe_eeprom_operations eeprom_ops_X540 = {
.init_params = &ixgbe_init_eeprom_params_X540,
.read = &ixgbe_read_eerd_X540,
.read_buffer = &ixgbe_read_eerd_buffer_X540,
.write = &ixgbe_write_eewr_X540,
.write_buffer = &ixgbe_write_eewr_buffer_X540,
.calc_checksum = &ixgbe_calc_eeprom_checksum_X540,
.validate_checksum = &ixgbe_validate_eeprom_checksum_X540,
.update_checksum = &ixgbe_update_eeprom_checksum_X540,
};
static struct ixgbe_phy_operations phy_ops_X540 = {
.identify = &ixgbe_identify_phy_generic,
.identify_sfp = &ixgbe_identify_sfp_module_generic,
.init = NULL,
.reset = NULL,
.read_reg = &ixgbe_read_phy_reg_generic,
.write_reg = &ixgbe_write_phy_reg_generic,
.setup_link = &ixgbe_setup_phy_link_generic,
.setup_link_speed = &ixgbe_setup_phy_link_speed_generic,
.read_i2c_byte = &ixgbe_read_i2c_byte_generic,
.write_i2c_byte = &ixgbe_write_i2c_byte_generic,
.read_i2c_sff8472 = &ixgbe_read_i2c_sff8472_generic,
.read_i2c_eeprom = &ixgbe_read_i2c_eeprom_generic,
.write_i2c_eeprom = &ixgbe_write_i2c_eeprom_generic,
.check_overtemp = &ixgbe_tn_check_overtemp,
.get_firmware_version = &ixgbe_get_phy_firmware_version_generic,
};
struct ixgbe_info ixgbe_X540_info = {
.mac = ixgbe_mac_X540,
.get_invariants = &ixgbe_get_invariants_X540,
.mac_ops = &mac_ops_X540,
.eeprom_ops = &eeprom_ops_X540,
.phy_ops = &phy_ops_X540,
.mbx_ops = &mbx_ops_generic,
};
| gpl-2.0 |
sztupy/samsung-kernel-herring | crypto/shash.c | 2511 | 16620 | /*
* Synchronous Cryptographic Hash operations.
*
* Copyright (c) 2008 Herbert Xu <herbert@gondor.apana.org.au>
*
* 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 <crypto/scatterwalk.h>
#include <crypto/internal/hash.h>
#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/seq_file.h>
#include "internal.h"
static const struct crypto_type crypto_shash_type;
static int shash_no_setkey(struct crypto_shash *tfm, const u8 *key,
unsigned int keylen)
{
return -ENOSYS;
}
static int shash_setkey_unaligned(struct crypto_shash *tfm, const u8 *key,
unsigned int keylen)
{
struct shash_alg *shash = crypto_shash_alg(tfm);
unsigned long alignmask = crypto_shash_alignmask(tfm);
unsigned long absize;
u8 *buffer, *alignbuffer;
int err;
absize = keylen + (alignmask & ~(crypto_tfm_ctx_alignment() - 1));
buffer = kmalloc(absize, GFP_KERNEL);
if (!buffer)
return -ENOMEM;
alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1);
memcpy(alignbuffer, key, keylen);
err = shash->setkey(tfm, alignbuffer, keylen);
kzfree(buffer);
return err;
}
int crypto_shash_setkey(struct crypto_shash *tfm, const u8 *key,
unsigned int keylen)
{
struct shash_alg *shash = crypto_shash_alg(tfm);
unsigned long alignmask = crypto_shash_alignmask(tfm);
if ((unsigned long)key & alignmask)
return shash_setkey_unaligned(tfm, key, keylen);
return shash->setkey(tfm, key, keylen);
}
EXPORT_SYMBOL_GPL(crypto_shash_setkey);
static inline unsigned int shash_align_buffer_size(unsigned len,
unsigned long mask)
{
return len + (mask & ~(__alignof__(u8 __attribute__ ((aligned))) - 1));
}
static int shash_update_unaligned(struct shash_desc *desc, const u8 *data,
unsigned int len)
{
struct crypto_shash *tfm = desc->tfm;
struct shash_alg *shash = crypto_shash_alg(tfm);
unsigned long alignmask = crypto_shash_alignmask(tfm);
unsigned int unaligned_len = alignmask + 1 -
((unsigned long)data & alignmask);
u8 ubuf[shash_align_buffer_size(unaligned_len, alignmask)]
__attribute__ ((aligned));
u8 *buf = PTR_ALIGN(&ubuf[0], alignmask + 1);
int err;
if (unaligned_len > len)
unaligned_len = len;
memcpy(buf, data, unaligned_len);
err = shash->update(desc, buf, unaligned_len);
memset(buf, 0, unaligned_len);
return err ?:
shash->update(desc, data + unaligned_len, len - unaligned_len);
}
int crypto_shash_update(struct shash_desc *desc, const u8 *data,
unsigned int len)
{
struct crypto_shash *tfm = desc->tfm;
struct shash_alg *shash = crypto_shash_alg(tfm);
unsigned long alignmask = crypto_shash_alignmask(tfm);
if ((unsigned long)data & alignmask)
return shash_update_unaligned(desc, data, len);
return shash->update(desc, data, len);
}
EXPORT_SYMBOL_GPL(crypto_shash_update);
static int shash_final_unaligned(struct shash_desc *desc, u8 *out)
{
struct crypto_shash *tfm = desc->tfm;
unsigned long alignmask = crypto_shash_alignmask(tfm);
struct shash_alg *shash = crypto_shash_alg(tfm);
unsigned int ds = crypto_shash_digestsize(tfm);
u8 ubuf[shash_align_buffer_size(ds, alignmask)]
__attribute__ ((aligned));
u8 *buf = PTR_ALIGN(&ubuf[0], alignmask + 1);
int err;
err = shash->final(desc, buf);
if (err)
goto out;
memcpy(out, buf, ds);
out:
memset(buf, 0, ds);
return err;
}
int crypto_shash_final(struct shash_desc *desc, u8 *out)
{
struct crypto_shash *tfm = desc->tfm;
struct shash_alg *shash = crypto_shash_alg(tfm);
unsigned long alignmask = crypto_shash_alignmask(tfm);
if ((unsigned long)out & alignmask)
return shash_final_unaligned(desc, out);
return shash->final(desc, out);
}
EXPORT_SYMBOL_GPL(crypto_shash_final);
static int shash_finup_unaligned(struct shash_desc *desc, const u8 *data,
unsigned int len, u8 *out)
{
return crypto_shash_update(desc, data, len) ?:
crypto_shash_final(desc, out);
}
int crypto_shash_finup(struct shash_desc *desc, const u8 *data,
unsigned int len, u8 *out)
{
struct crypto_shash *tfm = desc->tfm;
struct shash_alg *shash = crypto_shash_alg(tfm);
unsigned long alignmask = crypto_shash_alignmask(tfm);
if (((unsigned long)data | (unsigned long)out) & alignmask)
return shash_finup_unaligned(desc, data, len, out);
return shash->finup(desc, data, len, out);
}
EXPORT_SYMBOL_GPL(crypto_shash_finup);
static int shash_digest_unaligned(struct shash_desc *desc, const u8 *data,
unsigned int len, u8 *out)
{
return crypto_shash_init(desc) ?:
crypto_shash_finup(desc, data, len, out);
}
int crypto_shash_digest(struct shash_desc *desc, const u8 *data,
unsigned int len, u8 *out)
{
struct crypto_shash *tfm = desc->tfm;
struct shash_alg *shash = crypto_shash_alg(tfm);
unsigned long alignmask = crypto_shash_alignmask(tfm);
if (((unsigned long)data | (unsigned long)out) & alignmask)
return shash_digest_unaligned(desc, data, len, out);
return shash->digest(desc, data, len, out);
}
EXPORT_SYMBOL_GPL(crypto_shash_digest);
static int shash_default_export(struct shash_desc *desc, void *out)
{
memcpy(out, shash_desc_ctx(desc), crypto_shash_descsize(desc->tfm));
return 0;
}
static int shash_default_import(struct shash_desc *desc, const void *in)
{
memcpy(shash_desc_ctx(desc), in, crypto_shash_descsize(desc->tfm));
return 0;
}
static int shash_async_setkey(struct crypto_ahash *tfm, const u8 *key,
unsigned int keylen)
{
struct crypto_shash **ctx = crypto_ahash_ctx(tfm);
return crypto_shash_setkey(*ctx, key, keylen);
}
static int shash_async_init(struct ahash_request *req)
{
struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req));
struct shash_desc *desc = ahash_request_ctx(req);
desc->tfm = *ctx;
desc->flags = req->base.flags;
return crypto_shash_init(desc);
}
int shash_ahash_update(struct ahash_request *req, struct shash_desc *desc)
{
struct crypto_hash_walk walk;
int nbytes;
for (nbytes = crypto_hash_walk_first(req, &walk); nbytes > 0;
nbytes = crypto_hash_walk_done(&walk, nbytes))
nbytes = crypto_shash_update(desc, walk.data, nbytes);
return nbytes;
}
EXPORT_SYMBOL_GPL(shash_ahash_update);
static int shash_async_update(struct ahash_request *req)
{
return shash_ahash_update(req, ahash_request_ctx(req));
}
static int shash_async_final(struct ahash_request *req)
{
return crypto_shash_final(ahash_request_ctx(req), req->result);
}
int shash_ahash_finup(struct ahash_request *req, struct shash_desc *desc)
{
struct crypto_hash_walk walk;
int nbytes;
nbytes = crypto_hash_walk_first(req, &walk);
if (!nbytes)
return crypto_shash_final(desc, req->result);
do {
nbytes = crypto_hash_walk_last(&walk) ?
crypto_shash_finup(desc, walk.data, nbytes,
req->result) :
crypto_shash_update(desc, walk.data, nbytes);
nbytes = crypto_hash_walk_done(&walk, nbytes);
} while (nbytes > 0);
return nbytes;
}
EXPORT_SYMBOL_GPL(shash_ahash_finup);
static int shash_async_finup(struct ahash_request *req)
{
struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req));
struct shash_desc *desc = ahash_request_ctx(req);
desc->tfm = *ctx;
desc->flags = req->base.flags;
return shash_ahash_finup(req, desc);
}
int shash_ahash_digest(struct ahash_request *req, struct shash_desc *desc)
{
struct scatterlist *sg = req->src;
unsigned int offset = sg->offset;
unsigned int nbytes = req->nbytes;
int err;
if (nbytes < min(sg->length, ((unsigned int)(PAGE_SIZE)) - offset)) {
void *data;
data = crypto_kmap(sg_page(sg), 0);
err = crypto_shash_digest(desc, data + offset, nbytes,
req->result);
crypto_kunmap(data, 0);
crypto_yield(desc->flags);
} else
err = crypto_shash_init(desc) ?:
shash_ahash_finup(req, desc);
return err;
}
EXPORT_SYMBOL_GPL(shash_ahash_digest);
static int shash_async_digest(struct ahash_request *req)
{
struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req));
struct shash_desc *desc = ahash_request_ctx(req);
desc->tfm = *ctx;
desc->flags = req->base.flags;
return shash_ahash_digest(req, desc);
}
static int shash_async_export(struct ahash_request *req, void *out)
{
return crypto_shash_export(ahash_request_ctx(req), out);
}
static int shash_async_import(struct ahash_request *req, const void *in)
{
struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req));
struct shash_desc *desc = ahash_request_ctx(req);
desc->tfm = *ctx;
desc->flags = req->base.flags;
return crypto_shash_import(desc, in);
}
static void crypto_exit_shash_ops_async(struct crypto_tfm *tfm)
{
struct crypto_shash **ctx = crypto_tfm_ctx(tfm);
crypto_free_shash(*ctx);
}
int crypto_init_shash_ops_async(struct crypto_tfm *tfm)
{
struct crypto_alg *calg = tfm->__crt_alg;
struct shash_alg *alg = __crypto_shash_alg(calg);
struct crypto_ahash *crt = __crypto_ahash_cast(tfm);
struct crypto_shash **ctx = crypto_tfm_ctx(tfm);
struct crypto_shash *shash;
if (!crypto_mod_get(calg))
return -EAGAIN;
shash = crypto_create_tfm(calg, &crypto_shash_type);
if (IS_ERR(shash)) {
crypto_mod_put(calg);
return PTR_ERR(shash);
}
*ctx = shash;
tfm->exit = crypto_exit_shash_ops_async;
crt->init = shash_async_init;
crt->update = shash_async_update;
crt->final = shash_async_final;
crt->finup = shash_async_finup;
crt->digest = shash_async_digest;
if (alg->setkey)
crt->setkey = shash_async_setkey;
if (alg->export)
crt->export = shash_async_export;
if (alg->import)
crt->import = shash_async_import;
crt->reqsize = sizeof(struct shash_desc) + crypto_shash_descsize(shash);
return 0;
}
static int shash_compat_setkey(struct crypto_hash *tfm, const u8 *key,
unsigned int keylen)
{
struct shash_desc **descp = crypto_hash_ctx(tfm);
struct shash_desc *desc = *descp;
return crypto_shash_setkey(desc->tfm, key, keylen);
}
static int shash_compat_init(struct hash_desc *hdesc)
{
struct shash_desc **descp = crypto_hash_ctx(hdesc->tfm);
struct shash_desc *desc = *descp;
desc->flags = hdesc->flags;
return crypto_shash_init(desc);
}
static int shash_compat_update(struct hash_desc *hdesc, struct scatterlist *sg,
unsigned int len)
{
struct shash_desc **descp = crypto_hash_ctx(hdesc->tfm);
struct shash_desc *desc = *descp;
struct crypto_hash_walk walk;
int nbytes;
for (nbytes = crypto_hash_walk_first_compat(hdesc, &walk, sg, len);
nbytes > 0; nbytes = crypto_hash_walk_done(&walk, nbytes))
nbytes = crypto_shash_update(desc, walk.data, nbytes);
return nbytes;
}
static int shash_compat_final(struct hash_desc *hdesc, u8 *out)
{
struct shash_desc **descp = crypto_hash_ctx(hdesc->tfm);
return crypto_shash_final(*descp, out);
}
static int shash_compat_digest(struct hash_desc *hdesc, struct scatterlist *sg,
unsigned int nbytes, u8 *out)
{
unsigned int offset = sg->offset;
int err;
if (nbytes < min(sg->length, ((unsigned int)(PAGE_SIZE)) - offset)) {
struct shash_desc **descp = crypto_hash_ctx(hdesc->tfm);
struct shash_desc *desc = *descp;
void *data;
desc->flags = hdesc->flags;
data = crypto_kmap(sg_page(sg), 0);
err = crypto_shash_digest(desc, data + offset, nbytes, out);
crypto_kunmap(data, 0);
crypto_yield(desc->flags);
goto out;
}
err = shash_compat_init(hdesc);
if (err)
goto out;
err = shash_compat_update(hdesc, sg, nbytes);
if (err)
goto out;
err = shash_compat_final(hdesc, out);
out:
return err;
}
static void crypto_exit_shash_ops_compat(struct crypto_tfm *tfm)
{
struct shash_desc **descp = crypto_tfm_ctx(tfm);
struct shash_desc *desc = *descp;
crypto_free_shash(desc->tfm);
kzfree(desc);
}
static int crypto_init_shash_ops_compat(struct crypto_tfm *tfm)
{
struct hash_tfm *crt = &tfm->crt_hash;
struct crypto_alg *calg = tfm->__crt_alg;
struct shash_alg *alg = __crypto_shash_alg(calg);
struct shash_desc **descp = crypto_tfm_ctx(tfm);
struct crypto_shash *shash;
struct shash_desc *desc;
if (!crypto_mod_get(calg))
return -EAGAIN;
shash = crypto_create_tfm(calg, &crypto_shash_type);
if (IS_ERR(shash)) {
crypto_mod_put(calg);
return PTR_ERR(shash);
}
desc = kmalloc(sizeof(*desc) + crypto_shash_descsize(shash),
GFP_KERNEL);
if (!desc) {
crypto_free_shash(shash);
return -ENOMEM;
}
*descp = desc;
desc->tfm = shash;
tfm->exit = crypto_exit_shash_ops_compat;
crt->init = shash_compat_init;
crt->update = shash_compat_update;
crt->final = shash_compat_final;
crt->digest = shash_compat_digest;
crt->setkey = shash_compat_setkey;
crt->digestsize = alg->digestsize;
return 0;
}
static int crypto_init_shash_ops(struct crypto_tfm *tfm, u32 type, u32 mask)
{
switch (mask & CRYPTO_ALG_TYPE_MASK) {
case CRYPTO_ALG_TYPE_HASH_MASK:
return crypto_init_shash_ops_compat(tfm);
}
return -EINVAL;
}
static unsigned int crypto_shash_ctxsize(struct crypto_alg *alg, u32 type,
u32 mask)
{
switch (mask & CRYPTO_ALG_TYPE_MASK) {
case CRYPTO_ALG_TYPE_HASH_MASK:
return sizeof(struct shash_desc *);
}
return 0;
}
static int crypto_shash_init_tfm(struct crypto_tfm *tfm)
{
struct crypto_shash *hash = __crypto_shash_cast(tfm);
hash->descsize = crypto_shash_alg(hash)->descsize;
return 0;
}
static unsigned int crypto_shash_extsize(struct crypto_alg *alg)
{
return alg->cra_ctxsize;
}
static void crypto_shash_show(struct seq_file *m, struct crypto_alg *alg)
__attribute__ ((unused));
static void crypto_shash_show(struct seq_file *m, struct crypto_alg *alg)
{
struct shash_alg *salg = __crypto_shash_alg(alg);
seq_printf(m, "type : shash\n");
seq_printf(m, "blocksize : %u\n", alg->cra_blocksize);
seq_printf(m, "digestsize : %u\n", salg->digestsize);
}
static const struct crypto_type crypto_shash_type = {
.ctxsize = crypto_shash_ctxsize,
.extsize = crypto_shash_extsize,
.init = crypto_init_shash_ops,
.init_tfm = crypto_shash_init_tfm,
#ifdef CONFIG_PROC_FS
.show = crypto_shash_show,
#endif
.maskclear = ~CRYPTO_ALG_TYPE_MASK,
.maskset = CRYPTO_ALG_TYPE_MASK,
.type = CRYPTO_ALG_TYPE_SHASH,
.tfmsize = offsetof(struct crypto_shash, base),
};
struct crypto_shash *crypto_alloc_shash(const char *alg_name, u32 type,
u32 mask)
{
return crypto_alloc_tfm(alg_name, &crypto_shash_type, type, mask);
}
EXPORT_SYMBOL_GPL(crypto_alloc_shash);
static int shash_prepare_alg(struct shash_alg *alg)
{
struct crypto_alg *base = &alg->base;
if (alg->digestsize > PAGE_SIZE / 8 ||
alg->descsize > PAGE_SIZE / 8 ||
alg->statesize > PAGE_SIZE / 8)
return -EINVAL;
base->cra_type = &crypto_shash_type;
base->cra_flags &= ~CRYPTO_ALG_TYPE_MASK;
base->cra_flags |= CRYPTO_ALG_TYPE_SHASH;
if (!alg->finup)
alg->finup = shash_finup_unaligned;
if (!alg->digest)
alg->digest = shash_digest_unaligned;
if (!alg->export) {
alg->export = shash_default_export;
alg->import = shash_default_import;
alg->statesize = alg->descsize;
}
if (!alg->setkey)
alg->setkey = shash_no_setkey;
return 0;
}
int crypto_register_shash(struct shash_alg *alg)
{
struct crypto_alg *base = &alg->base;
int err;
err = shash_prepare_alg(alg);
if (err)
return err;
return crypto_register_alg(base);
}
EXPORT_SYMBOL_GPL(crypto_register_shash);
int crypto_unregister_shash(struct shash_alg *alg)
{
return crypto_unregister_alg(&alg->base);
}
EXPORT_SYMBOL_GPL(crypto_unregister_shash);
int shash_register_instance(struct crypto_template *tmpl,
struct shash_instance *inst)
{
int err;
err = shash_prepare_alg(&inst->alg);
if (err)
return err;
return crypto_register_instance(tmpl, shash_crypto_instance(inst));
}
EXPORT_SYMBOL_GPL(shash_register_instance);
void shash_free_instance(struct crypto_instance *inst)
{
crypto_drop_spawn(crypto_instance_ctx(inst));
kfree(shash_instance(inst));
}
EXPORT_SYMBOL_GPL(shash_free_instance);
int crypto_init_shash_spawn(struct crypto_shash_spawn *spawn,
struct shash_alg *alg,
struct crypto_instance *inst)
{
return crypto_init_spawn2(&spawn->base, &alg->base, inst,
&crypto_shash_type);
}
EXPORT_SYMBOL_GPL(crypto_init_shash_spawn);
struct shash_alg *shash_attr_alg(struct rtattr *rta, u32 type, u32 mask)
{
struct crypto_alg *alg;
alg = crypto_attr_alg2(rta, &crypto_shash_type, type, mask);
return IS_ERR(alg) ? ERR_CAST(alg) :
container_of(alg, struct shash_alg, base);
}
EXPORT_SYMBOL_GPL(shash_attr_alg);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Synchronous cryptographic hash type");
| gpl-2.0 |
ea4862/boeffla41_e210k | drivers/s390/net/qeth_l3_sys.c | 2767 | 27615 | /*
* drivers/s390/net/qeth_l3_sys.c
*
* Copyright IBM Corp. 2007
* Author(s): Utz Bacher <utz.bacher@de.ibm.com>,
* Frank Pavlic <fpavlic@de.ibm.com>,
* Thomas Spatzier <tspat@de.ibm.com>,
* Frank Blaschka <frank.blaschka@de.ibm.com>
*/
#include <linux/slab.h>
#include "qeth_l3.h"
#define QETH_DEVICE_ATTR(_id, _name, _mode, _show, _store) \
struct device_attribute dev_attr_##_id = __ATTR(_name, _mode, _show, _store)
static ssize_t qeth_l3_dev_route_show(struct qeth_card *card,
struct qeth_routing_info *route, char *buf)
{
switch (route->type) {
case PRIMARY_ROUTER:
return sprintf(buf, "%s\n", "primary router");
case SECONDARY_ROUTER:
return sprintf(buf, "%s\n", "secondary router");
case MULTICAST_ROUTER:
if (card->info.broadcast_capable == QETH_BROADCAST_WITHOUT_ECHO)
return sprintf(buf, "%s\n", "multicast router+");
else
return sprintf(buf, "%s\n", "multicast router");
case PRIMARY_CONNECTOR:
if (card->info.broadcast_capable == QETH_BROADCAST_WITHOUT_ECHO)
return sprintf(buf, "%s\n", "primary connector+");
else
return sprintf(buf, "%s\n", "primary connector");
case SECONDARY_CONNECTOR:
if (card->info.broadcast_capable == QETH_BROADCAST_WITHOUT_ECHO)
return sprintf(buf, "%s\n", "secondary connector+");
else
return sprintf(buf, "%s\n", "secondary connector");
default:
return sprintf(buf, "%s\n", "no");
}
}
static ssize_t qeth_l3_dev_route4_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_route_show(card, &card->options.route4, buf);
}
static ssize_t qeth_l3_dev_route_store(struct qeth_card *card,
struct qeth_routing_info *route, enum qeth_prot_versions prot,
const char *buf, size_t count)
{
enum qeth_routing_types old_route_type = route->type;
char *tmp;
int rc = 0;
tmp = strsep((char **) &buf, "\n");
mutex_lock(&card->conf_mutex);
if (!strcmp(tmp, "no_router")) {
route->type = NO_ROUTER;
} else if (!strcmp(tmp, "primary_connector")) {
route->type = PRIMARY_CONNECTOR;
} else if (!strcmp(tmp, "secondary_connector")) {
route->type = SECONDARY_CONNECTOR;
} else if (!strcmp(tmp, "primary_router")) {
route->type = PRIMARY_ROUTER;
} else if (!strcmp(tmp, "secondary_router")) {
route->type = SECONDARY_ROUTER;
} else if (!strcmp(tmp, "multicast_router")) {
route->type = MULTICAST_ROUTER;
} else {
rc = -EINVAL;
goto out;
}
if (((card->state == CARD_STATE_SOFTSETUP) ||
(card->state == CARD_STATE_UP)) &&
(old_route_type != route->type)) {
if (prot == QETH_PROT_IPV4)
rc = qeth_l3_setrouting_v4(card);
else if (prot == QETH_PROT_IPV6)
rc = qeth_l3_setrouting_v6(card);
}
out:
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static ssize_t qeth_l3_dev_route4_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_route_store(card, &card->options.route4,
QETH_PROT_IPV4, buf, count);
}
static DEVICE_ATTR(route4, 0644, qeth_l3_dev_route4_show,
qeth_l3_dev_route4_store);
static ssize_t qeth_l3_dev_route6_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_route_show(card, &card->options.route6, buf);
}
static ssize_t qeth_l3_dev_route6_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_route_store(card, &card->options.route6,
QETH_PROT_IPV6, buf, count);
}
static DEVICE_ATTR(route6, 0644, qeth_l3_dev_route6_show,
qeth_l3_dev_route6_store);
static ssize_t qeth_l3_dev_fake_broadcast_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return sprintf(buf, "%i\n", card->options.fake_broadcast? 1:0);
}
static ssize_t qeth_l3_dev_fake_broadcast_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
char *tmp;
int i, rc = 0;
if (!card)
return -EINVAL;
mutex_lock(&card->conf_mutex);
if ((card->state != CARD_STATE_DOWN) &&
(card->state != CARD_STATE_RECOVER)) {
rc = -EPERM;
goto out;
}
i = simple_strtoul(buf, &tmp, 16);
if ((i == 0) || (i == 1))
card->options.fake_broadcast = i;
else
rc = -EINVAL;
out:
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static DEVICE_ATTR(fake_broadcast, 0644, qeth_l3_dev_fake_broadcast_show,
qeth_l3_dev_fake_broadcast_store);
static ssize_t qeth_l3_dev_broadcast_mode_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
if (!((card->info.link_type == QETH_LINK_TYPE_HSTR) ||
(card->info.link_type == QETH_LINK_TYPE_LANE_TR)))
return sprintf(buf, "n/a\n");
return sprintf(buf, "%s\n", (card->options.broadcast_mode ==
QETH_TR_BROADCAST_ALLRINGS)?
"all rings":"local");
}
static ssize_t qeth_l3_dev_broadcast_mode_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
char *tmp;
int rc = 0;
if (!card)
return -EINVAL;
mutex_lock(&card->conf_mutex);
if ((card->state != CARD_STATE_DOWN) &&
(card->state != CARD_STATE_RECOVER)) {
rc = -EPERM;
goto out;
}
if (!((card->info.link_type == QETH_LINK_TYPE_HSTR) ||
(card->info.link_type == QETH_LINK_TYPE_LANE_TR))) {
rc = -EINVAL;
goto out;
}
tmp = strsep((char **) &buf, "\n");
if (!strcmp(tmp, "local"))
card->options.broadcast_mode = QETH_TR_BROADCAST_LOCAL;
else if (!strcmp(tmp, "all_rings"))
card->options.broadcast_mode = QETH_TR_BROADCAST_ALLRINGS;
else
rc = -EINVAL;
out:
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static DEVICE_ATTR(broadcast_mode, 0644, qeth_l3_dev_broadcast_mode_show,
qeth_l3_dev_broadcast_mode_store);
static ssize_t qeth_l3_dev_canonical_macaddr_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
if (!((card->info.link_type == QETH_LINK_TYPE_HSTR) ||
(card->info.link_type == QETH_LINK_TYPE_LANE_TR)))
return sprintf(buf, "n/a\n");
return sprintf(buf, "%i\n", (card->options.macaddr_mode ==
QETH_TR_MACADDR_CANONICAL)? 1:0);
}
static ssize_t qeth_l3_dev_canonical_macaddr_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
char *tmp;
int i, rc = 0;
if (!card)
return -EINVAL;
mutex_lock(&card->conf_mutex);
if ((card->state != CARD_STATE_DOWN) &&
(card->state != CARD_STATE_RECOVER)) {
rc = -EPERM;
goto out;
}
if (!((card->info.link_type == QETH_LINK_TYPE_HSTR) ||
(card->info.link_type == QETH_LINK_TYPE_LANE_TR))) {
rc = -EINVAL;
goto out;
}
i = simple_strtoul(buf, &tmp, 16);
if ((i == 0) || (i == 1))
card->options.macaddr_mode = i?
QETH_TR_MACADDR_CANONICAL :
QETH_TR_MACADDR_NONCANONICAL;
else
rc = -EINVAL;
out:
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static DEVICE_ATTR(canonical_macaddr, 0644, qeth_l3_dev_canonical_macaddr_show,
qeth_l3_dev_canonical_macaddr_store);
static ssize_t qeth_l3_dev_sniffer_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return sprintf(buf, "%i\n", card->options.sniffer ? 1 : 0);
}
static ssize_t qeth_l3_dev_sniffer_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
int rc = 0;
unsigned long i;
if (!card)
return -EINVAL;
if (card->info.type != QETH_CARD_TYPE_IQD)
return -EPERM;
mutex_lock(&card->conf_mutex);
if ((card->state != CARD_STATE_DOWN) &&
(card->state != CARD_STATE_RECOVER)) {
rc = -EPERM;
goto out;
}
rc = strict_strtoul(buf, 16, &i);
if (rc) {
rc = -EINVAL;
goto out;
}
switch (i) {
case 0:
card->options.sniffer = i;
break;
case 1:
qdio_get_ssqd_desc(CARD_DDEV(card), &card->ssqd);
if (card->ssqd.qdioac2 & QETH_SNIFF_AVAIL) {
card->options.sniffer = i;
if (card->qdio.init_pool.buf_count !=
QETH_IN_BUF_COUNT_MAX)
qeth_realloc_buffer_pool(card,
QETH_IN_BUF_COUNT_MAX);
break;
} else
rc = -EPERM;
default: /* fall through */
rc = -EINVAL;
}
out:
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static DEVICE_ATTR(sniffer, 0644, qeth_l3_dev_sniffer_show,
qeth_l3_dev_sniffer_store);
static struct attribute *qeth_l3_device_attrs[] = {
&dev_attr_route4.attr,
&dev_attr_route6.attr,
&dev_attr_fake_broadcast.attr,
&dev_attr_broadcast_mode.attr,
&dev_attr_canonical_macaddr.attr,
&dev_attr_sniffer.attr,
NULL,
};
static struct attribute_group qeth_l3_device_attr_group = {
.attrs = qeth_l3_device_attrs,
};
static ssize_t qeth_l3_dev_ipato_enable_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return sprintf(buf, "%i\n", card->ipato.enabled? 1:0);
}
static ssize_t qeth_l3_dev_ipato_enable_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
struct qeth_ipaddr *tmpipa, *t;
char *tmp;
int rc = 0;
if (!card)
return -EINVAL;
mutex_lock(&card->conf_mutex);
if ((card->state != CARD_STATE_DOWN) &&
(card->state != CARD_STATE_RECOVER)) {
rc = -EPERM;
goto out;
}
tmp = strsep((char **) &buf, "\n");
if (!strcmp(tmp, "toggle")) {
card->ipato.enabled = (card->ipato.enabled)? 0 : 1;
} else if (!strcmp(tmp, "1")) {
card->ipato.enabled = 1;
list_for_each_entry_safe(tmpipa, t, card->ip_tbd_list, entry) {
if ((tmpipa->type == QETH_IP_TYPE_NORMAL) &&
qeth_l3_is_addr_covered_by_ipato(card, tmpipa))
tmpipa->set_flags |=
QETH_IPA_SETIP_TAKEOVER_FLAG;
}
} else if (!strcmp(tmp, "0")) {
card->ipato.enabled = 0;
list_for_each_entry_safe(tmpipa, t, card->ip_tbd_list, entry) {
if (tmpipa->set_flags &
QETH_IPA_SETIP_TAKEOVER_FLAG)
tmpipa->set_flags &=
~QETH_IPA_SETIP_TAKEOVER_FLAG;
}
} else
rc = -EINVAL;
out:
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static QETH_DEVICE_ATTR(ipato_enable, enable, 0644,
qeth_l3_dev_ipato_enable_show,
qeth_l3_dev_ipato_enable_store);
static ssize_t qeth_l3_dev_ipato_invert4_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return sprintf(buf, "%i\n", card->ipato.invert4? 1:0);
}
static ssize_t qeth_l3_dev_ipato_invert4_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
char *tmp;
int rc = 0;
if (!card)
return -EINVAL;
mutex_lock(&card->conf_mutex);
tmp = strsep((char **) &buf, "\n");
if (!strcmp(tmp, "toggle")) {
card->ipato.invert4 = (card->ipato.invert4)? 0 : 1;
} else if (!strcmp(tmp, "1")) {
card->ipato.invert4 = 1;
} else if (!strcmp(tmp, "0")) {
card->ipato.invert4 = 0;
} else
rc = -EINVAL;
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static QETH_DEVICE_ATTR(ipato_invert4, invert4, 0644,
qeth_l3_dev_ipato_invert4_show,
qeth_l3_dev_ipato_invert4_store);
static ssize_t qeth_l3_dev_ipato_add_show(char *buf, struct qeth_card *card,
enum qeth_prot_versions proto)
{
struct qeth_ipato_entry *ipatoe;
unsigned long flags;
char addr_str[40];
int entry_len; /* length of 1 entry string, differs between v4 and v6 */
int i = 0;
entry_len = (proto == QETH_PROT_IPV4)? 12 : 40;
/* add strlen for "/<mask>\n" */
entry_len += (proto == QETH_PROT_IPV4)? 5 : 6;
spin_lock_irqsave(&card->ip_lock, flags);
list_for_each_entry(ipatoe, &card->ipato.entries, entry) {
if (ipatoe->proto != proto)
continue;
/* String must not be longer than PAGE_SIZE. So we check if
* string length gets near PAGE_SIZE. Then we can savely display
* the next IPv6 address (worst case, compared to IPv4) */
if ((PAGE_SIZE - i) <= entry_len)
break;
qeth_l3_ipaddr_to_string(proto, ipatoe->addr, addr_str);
i += snprintf(buf + i, PAGE_SIZE - i,
"%s/%i\n", addr_str, ipatoe->mask_bits);
}
spin_unlock_irqrestore(&card->ip_lock, flags);
i += snprintf(buf + i, PAGE_SIZE - i, "\n");
return i;
}
static ssize_t qeth_l3_dev_ipato_add4_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_ipato_add_show(buf, card, QETH_PROT_IPV4);
}
static int qeth_l3_parse_ipatoe(const char *buf, enum qeth_prot_versions proto,
u8 *addr, int *mask_bits)
{
const char *start, *end;
char *tmp;
char buffer[40] = {0, };
start = buf;
/* get address string */
end = strchr(start, '/');
if (!end || (end - start >= 40)) {
return -EINVAL;
}
strncpy(buffer, start, end - start);
if (qeth_l3_string_to_ipaddr(buffer, proto, addr)) {
return -EINVAL;
}
start = end + 1;
*mask_bits = simple_strtoul(start, &tmp, 10);
if (!strlen(start) ||
(tmp == start) ||
(*mask_bits > ((proto == QETH_PROT_IPV4) ? 32 : 128))) {
return -EINVAL;
}
return 0;
}
static ssize_t qeth_l3_dev_ipato_add_store(const char *buf, size_t count,
struct qeth_card *card, enum qeth_prot_versions proto)
{
struct qeth_ipato_entry *ipatoe;
u8 addr[16];
int mask_bits;
int rc = 0;
mutex_lock(&card->conf_mutex);
rc = qeth_l3_parse_ipatoe(buf, proto, addr, &mask_bits);
if (rc)
goto out;
ipatoe = kzalloc(sizeof(struct qeth_ipato_entry), GFP_KERNEL);
if (!ipatoe) {
rc = -ENOMEM;
goto out;
}
ipatoe->proto = proto;
memcpy(ipatoe->addr, addr, (proto == QETH_PROT_IPV4)? 4:16);
ipatoe->mask_bits = mask_bits;
rc = qeth_l3_add_ipato_entry(card, ipatoe);
if (rc)
kfree(ipatoe);
out:
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static ssize_t qeth_l3_dev_ipato_add4_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_ipato_add_store(buf, count, card, QETH_PROT_IPV4);
}
static QETH_DEVICE_ATTR(ipato_add4, add4, 0644,
qeth_l3_dev_ipato_add4_show,
qeth_l3_dev_ipato_add4_store);
static ssize_t qeth_l3_dev_ipato_del_store(const char *buf, size_t count,
struct qeth_card *card, enum qeth_prot_versions proto)
{
u8 addr[16];
int mask_bits;
int rc = 0;
mutex_lock(&card->conf_mutex);
rc = qeth_l3_parse_ipatoe(buf, proto, addr, &mask_bits);
if (!rc)
qeth_l3_del_ipato_entry(card, proto, addr, mask_bits);
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static ssize_t qeth_l3_dev_ipato_del4_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_ipato_del_store(buf, count, card, QETH_PROT_IPV4);
}
static QETH_DEVICE_ATTR(ipato_del4, del4, 0200, NULL,
qeth_l3_dev_ipato_del4_store);
static ssize_t qeth_l3_dev_ipato_invert6_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return sprintf(buf, "%i\n", card->ipato.invert6? 1:0);
}
static ssize_t qeth_l3_dev_ipato_invert6_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
char *tmp;
int rc = 0;
if (!card)
return -EINVAL;
mutex_lock(&card->conf_mutex);
tmp = strsep((char **) &buf, "\n");
if (!strcmp(tmp, "toggle")) {
card->ipato.invert6 = (card->ipato.invert6)? 0 : 1;
} else if (!strcmp(tmp, "1")) {
card->ipato.invert6 = 1;
} else if (!strcmp(tmp, "0")) {
card->ipato.invert6 = 0;
} else
rc = -EINVAL;
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static QETH_DEVICE_ATTR(ipato_invert6, invert6, 0644,
qeth_l3_dev_ipato_invert6_show,
qeth_l3_dev_ipato_invert6_store);
static ssize_t qeth_l3_dev_ipato_add6_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_ipato_add_show(buf, card, QETH_PROT_IPV6);
}
static ssize_t qeth_l3_dev_ipato_add6_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_ipato_add_store(buf, count, card, QETH_PROT_IPV6);
}
static QETH_DEVICE_ATTR(ipato_add6, add6, 0644,
qeth_l3_dev_ipato_add6_show,
qeth_l3_dev_ipato_add6_store);
static ssize_t qeth_l3_dev_ipato_del6_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_ipato_del_store(buf, count, card, QETH_PROT_IPV6);
}
static QETH_DEVICE_ATTR(ipato_del6, del6, 0200, NULL,
qeth_l3_dev_ipato_del6_store);
static struct attribute *qeth_ipato_device_attrs[] = {
&dev_attr_ipato_enable.attr,
&dev_attr_ipato_invert4.attr,
&dev_attr_ipato_add4.attr,
&dev_attr_ipato_del4.attr,
&dev_attr_ipato_invert6.attr,
&dev_attr_ipato_add6.attr,
&dev_attr_ipato_del6.attr,
NULL,
};
static struct attribute_group qeth_device_ipato_group = {
.name = "ipa_takeover",
.attrs = qeth_ipato_device_attrs,
};
static ssize_t qeth_l3_dev_vipa_add_show(char *buf, struct qeth_card *card,
enum qeth_prot_versions proto)
{
struct qeth_ipaddr *ipaddr;
char addr_str[40];
int entry_len; /* length of 1 entry string, differs between v4 and v6 */
unsigned long flags;
int i = 0;
entry_len = (proto == QETH_PROT_IPV4)? 12 : 40;
entry_len += 2; /* \n + terminator */
spin_lock_irqsave(&card->ip_lock, flags);
list_for_each_entry(ipaddr, &card->ip_list, entry) {
if (ipaddr->proto != proto)
continue;
if (ipaddr->type != QETH_IP_TYPE_VIPA)
continue;
/* String must not be longer than PAGE_SIZE. So we check if
* string length gets near PAGE_SIZE. Then we can savely display
* the next IPv6 address (worst case, compared to IPv4) */
if ((PAGE_SIZE - i) <= entry_len)
break;
qeth_l3_ipaddr_to_string(proto, (const u8 *)&ipaddr->u,
addr_str);
i += snprintf(buf + i, PAGE_SIZE - i, "%s\n", addr_str);
}
spin_unlock_irqrestore(&card->ip_lock, flags);
i += snprintf(buf + i, PAGE_SIZE - i, "\n");
return i;
}
static ssize_t qeth_l3_dev_vipa_add4_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_vipa_add_show(buf, card, QETH_PROT_IPV4);
}
static int qeth_l3_parse_vipae(const char *buf, enum qeth_prot_versions proto,
u8 *addr)
{
if (qeth_l3_string_to_ipaddr(buf, proto, addr)) {
return -EINVAL;
}
return 0;
}
static ssize_t qeth_l3_dev_vipa_add_store(const char *buf, size_t count,
struct qeth_card *card, enum qeth_prot_versions proto)
{
u8 addr[16] = {0, };
int rc;
mutex_lock(&card->conf_mutex);
rc = qeth_l3_parse_vipae(buf, proto, addr);
if (!rc)
rc = qeth_l3_add_vipa(card, proto, addr);
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static ssize_t qeth_l3_dev_vipa_add4_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_vipa_add_store(buf, count, card, QETH_PROT_IPV4);
}
static QETH_DEVICE_ATTR(vipa_add4, add4, 0644,
qeth_l3_dev_vipa_add4_show,
qeth_l3_dev_vipa_add4_store);
static ssize_t qeth_l3_dev_vipa_del_store(const char *buf, size_t count,
struct qeth_card *card, enum qeth_prot_versions proto)
{
u8 addr[16];
int rc;
mutex_lock(&card->conf_mutex);
rc = qeth_l3_parse_vipae(buf, proto, addr);
if (!rc)
qeth_l3_del_vipa(card, proto, addr);
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static ssize_t qeth_l3_dev_vipa_del4_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_vipa_del_store(buf, count, card, QETH_PROT_IPV4);
}
static QETH_DEVICE_ATTR(vipa_del4, del4, 0200, NULL,
qeth_l3_dev_vipa_del4_store);
static ssize_t qeth_l3_dev_vipa_add6_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_vipa_add_show(buf, card, QETH_PROT_IPV6);
}
static ssize_t qeth_l3_dev_vipa_add6_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_vipa_add_store(buf, count, card, QETH_PROT_IPV6);
}
static QETH_DEVICE_ATTR(vipa_add6, add6, 0644,
qeth_l3_dev_vipa_add6_show,
qeth_l3_dev_vipa_add6_store);
static ssize_t qeth_l3_dev_vipa_del6_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_vipa_del_store(buf, count, card, QETH_PROT_IPV6);
}
static QETH_DEVICE_ATTR(vipa_del6, del6, 0200, NULL,
qeth_l3_dev_vipa_del6_store);
static struct attribute *qeth_vipa_device_attrs[] = {
&dev_attr_vipa_add4.attr,
&dev_attr_vipa_del4.attr,
&dev_attr_vipa_add6.attr,
&dev_attr_vipa_del6.attr,
NULL,
};
static struct attribute_group qeth_device_vipa_group = {
.name = "vipa",
.attrs = qeth_vipa_device_attrs,
};
static ssize_t qeth_l3_dev_rxip_add_show(char *buf, struct qeth_card *card,
enum qeth_prot_versions proto)
{
struct qeth_ipaddr *ipaddr;
char addr_str[40];
int entry_len; /* length of 1 entry string, differs between v4 and v6 */
unsigned long flags;
int i = 0;
entry_len = (proto == QETH_PROT_IPV4)? 12 : 40;
entry_len += 2; /* \n + terminator */
spin_lock_irqsave(&card->ip_lock, flags);
list_for_each_entry(ipaddr, &card->ip_list, entry) {
if (ipaddr->proto != proto)
continue;
if (ipaddr->type != QETH_IP_TYPE_RXIP)
continue;
/* String must not be longer than PAGE_SIZE. So we check if
* string length gets near PAGE_SIZE. Then we can savely display
* the next IPv6 address (worst case, compared to IPv4) */
if ((PAGE_SIZE - i) <= entry_len)
break;
qeth_l3_ipaddr_to_string(proto, (const u8 *)&ipaddr->u,
addr_str);
i += snprintf(buf + i, PAGE_SIZE - i, "%s\n", addr_str);
}
spin_unlock_irqrestore(&card->ip_lock, flags);
i += snprintf(buf + i, PAGE_SIZE - i, "\n");
return i;
}
static ssize_t qeth_l3_dev_rxip_add4_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_rxip_add_show(buf, card, QETH_PROT_IPV4);
}
static int qeth_l3_parse_rxipe(const char *buf, enum qeth_prot_versions proto,
u8 *addr)
{
if (qeth_l3_string_to_ipaddr(buf, proto, addr)) {
return -EINVAL;
}
return 0;
}
static ssize_t qeth_l3_dev_rxip_add_store(const char *buf, size_t count,
struct qeth_card *card, enum qeth_prot_versions proto)
{
u8 addr[16] = {0, };
int rc;
mutex_lock(&card->conf_mutex);
rc = qeth_l3_parse_rxipe(buf, proto, addr);
if (!rc)
rc = qeth_l3_add_rxip(card, proto, addr);
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static ssize_t qeth_l3_dev_rxip_add4_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_rxip_add_store(buf, count, card, QETH_PROT_IPV4);
}
static QETH_DEVICE_ATTR(rxip_add4, add4, 0644,
qeth_l3_dev_rxip_add4_show,
qeth_l3_dev_rxip_add4_store);
static ssize_t qeth_l3_dev_rxip_del_store(const char *buf, size_t count,
struct qeth_card *card, enum qeth_prot_versions proto)
{
u8 addr[16];
int rc;
mutex_lock(&card->conf_mutex);
rc = qeth_l3_parse_rxipe(buf, proto, addr);
if (!rc)
qeth_l3_del_rxip(card, proto, addr);
mutex_unlock(&card->conf_mutex);
return rc ? rc : count;
}
static ssize_t qeth_l3_dev_rxip_del4_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_rxip_del_store(buf, count, card, QETH_PROT_IPV4);
}
static QETH_DEVICE_ATTR(rxip_del4, del4, 0200, NULL,
qeth_l3_dev_rxip_del4_store);
static ssize_t qeth_l3_dev_rxip_add6_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_rxip_add_show(buf, card, QETH_PROT_IPV6);
}
static ssize_t qeth_l3_dev_rxip_add6_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_rxip_add_store(buf, count, card, QETH_PROT_IPV6);
}
static QETH_DEVICE_ATTR(rxip_add6, add6, 0644,
qeth_l3_dev_rxip_add6_show,
qeth_l3_dev_rxip_add6_store);
static ssize_t qeth_l3_dev_rxip_del6_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct qeth_card *card = dev_get_drvdata(dev);
if (!card)
return -EINVAL;
return qeth_l3_dev_rxip_del_store(buf, count, card, QETH_PROT_IPV6);
}
static QETH_DEVICE_ATTR(rxip_del6, del6, 0200, NULL,
qeth_l3_dev_rxip_del6_store);
static struct attribute *qeth_rxip_device_attrs[] = {
&dev_attr_rxip_add4.attr,
&dev_attr_rxip_del4.attr,
&dev_attr_rxip_add6.attr,
&dev_attr_rxip_del6.attr,
NULL,
};
static struct attribute_group qeth_device_rxip_group = {
.name = "rxip",
.attrs = qeth_rxip_device_attrs,
};
int qeth_l3_create_device_attributes(struct device *dev)
{
int ret;
ret = sysfs_create_group(&dev->kobj, &qeth_l3_device_attr_group);
if (ret)
return ret;
ret = sysfs_create_group(&dev->kobj, &qeth_device_ipato_group);
if (ret) {
sysfs_remove_group(&dev->kobj, &qeth_l3_device_attr_group);
return ret;
}
ret = sysfs_create_group(&dev->kobj, &qeth_device_vipa_group);
if (ret) {
sysfs_remove_group(&dev->kobj, &qeth_l3_device_attr_group);
sysfs_remove_group(&dev->kobj, &qeth_device_ipato_group);
return ret;
}
ret = sysfs_create_group(&dev->kobj, &qeth_device_rxip_group);
if (ret) {
sysfs_remove_group(&dev->kobj, &qeth_l3_device_attr_group);
sysfs_remove_group(&dev->kobj, &qeth_device_ipato_group);
sysfs_remove_group(&dev->kobj, &qeth_device_vipa_group);
return ret;
}
return 0;
}
void qeth_l3_remove_device_attributes(struct device *dev)
{
sysfs_remove_group(&dev->kobj, &qeth_l3_device_attr_group);
sysfs_remove_group(&dev->kobj, &qeth_device_ipato_group);
sysfs_remove_group(&dev->kobj, &qeth_device_vipa_group);
sysfs_remove_group(&dev->kobj, &qeth_device_rxip_group);
}
| gpl-2.0 |
rmcc/gp_one_kernel | arch/um/drivers/slip_user.c | 4303 | 5115 | /*
* Copyright (C) 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/termios.h>
#include <sys/wait.h>
#include "kern_constants.h"
#include "net_user.h"
#include "os.h"
#include "slip.h"
#include "um_malloc.h"
#include "user.h"
static int slip_user_init(void *data, void *dev)
{
struct slip_data *pri = data;
pri->dev = dev;
return 0;
}
static int set_up_tty(int fd)
{
int i;
struct termios tios;
if (tcgetattr(fd, &tios) < 0) {
printk(UM_KERN_ERR "could not get initial terminal "
"attributes\n");
return -1;
}
tios.c_cflag = CS8 | CREAD | HUPCL | CLOCAL;
tios.c_iflag = IGNBRK | IGNPAR;
tios.c_oflag = 0;
tios.c_lflag = 0;
for (i = 0; i < NCCS; i++)
tios.c_cc[i] = 0;
tios.c_cc[VMIN] = 1;
tios.c_cc[VTIME] = 0;
cfsetospeed(&tios, B38400);
cfsetispeed(&tios, B38400);
if (tcsetattr(fd, TCSAFLUSH, &tios) < 0) {
printk(UM_KERN_ERR "failed to set terminal attributes\n");
return -1;
}
return 0;
}
struct slip_pre_exec_data {
int stdin;
int stdout;
int close_me;
};
static void slip_pre_exec(void *arg)
{
struct slip_pre_exec_data *data = arg;
if (data->stdin >= 0)
dup2(data->stdin, 0);
dup2(data->stdout, 1);
if (data->close_me >= 0)
close(data->close_me);
}
static int slip_tramp(char **argv, int fd)
{
struct slip_pre_exec_data pe_data;
char *output;
int pid, fds[2], err, output_len;
err = os_pipe(fds, 1, 0);
if (err < 0) {
printk(UM_KERN_ERR "slip_tramp : pipe failed, err = %d\n",
-err);
goto out;
}
err = 0;
pe_data.stdin = fd;
pe_data.stdout = fds[1];
pe_data.close_me = fds[0];
err = run_helper(slip_pre_exec, &pe_data, argv);
if (err < 0)
goto out_close;
pid = err;
output_len = UM_KERN_PAGE_SIZE;
output = uml_kmalloc(output_len, UM_GFP_KERNEL);
if (output == NULL) {
printk(UM_KERN_ERR "slip_tramp : failed to allocate output "
"buffer\n");
os_kill_process(pid, 1);
err = -ENOMEM;
goto out_free;
}
close(fds[1]);
read_output(fds[0], output, output_len);
printk("%s", output);
err = helper_wait(pid);
close(fds[0]);
out_free:
kfree(output);
return err;
out_close:
close(fds[0]);
close(fds[1]);
out:
return err;
}
static int slip_open(void *data)
{
struct slip_data *pri = data;
char version_buf[sizeof("nnnnn\0")];
char gate_buf[sizeof("nnn.nnn.nnn.nnn\0")];
char *argv[] = { "uml_net", version_buf, "slip", "up", gate_buf,
NULL };
int sfd, mfd, err;
err = get_pty();
if (err < 0) {
printk(UM_KERN_ERR "slip-open : Failed to open pty, err = %d\n",
-err);
goto out;
}
mfd = err;
err = open(ptsname(mfd), O_RDWR, 0);
if (err < 0) {
printk(UM_KERN_ERR "Couldn't open tty for slip line, "
"err = %d\n", -err);
goto out_close;
}
sfd = err;
if (set_up_tty(sfd))
goto out_close2;
pri->slave = sfd;
pri->slip.pos = 0;
pri->slip.esc = 0;
if (pri->gate_addr != NULL) {
sprintf(version_buf, "%d", UML_NET_VERSION);
strcpy(gate_buf, pri->gate_addr);
err = slip_tramp(argv, sfd);
if (err < 0) {
printk(UM_KERN_ERR "slip_tramp failed - err = %d\n",
-err);
goto out_close2;
}
err = os_get_ifname(pri->slave, pri->name);
if (err < 0) {
printk(UM_KERN_ERR "get_ifname failed, err = %d\n",
-err);
goto out_close2;
}
iter_addresses(pri->dev, open_addr, pri->name);
}
else {
err = os_set_slip(sfd);
if (err < 0) {
printk(UM_KERN_ERR "Failed to set slip discipline "
"encapsulation - err = %d\n", -err);
goto out_close2;
}
}
return mfd;
out_close2:
close(sfd);
out_close:
close(mfd);
out:
return err;
}
static void slip_close(int fd, void *data)
{
struct slip_data *pri = data;
char version_buf[sizeof("nnnnn\0")];
char *argv[] = { "uml_net", version_buf, "slip", "down", pri->name,
NULL };
int err;
if (pri->gate_addr != NULL)
iter_addresses(pri->dev, close_addr, pri->name);
sprintf(version_buf, "%d", UML_NET_VERSION);
err = slip_tramp(argv, pri->slave);
if (err != 0)
printk(UM_KERN_ERR "slip_tramp failed - errno = %d\n", -err);
close(fd);
close(pri->slave);
pri->slave = -1;
}
int slip_user_read(int fd, void *buf, int len, struct slip_data *pri)
{
return slip_proto_read(fd, buf, len, &pri->slip);
}
int slip_user_write(int fd, void *buf, int len, struct slip_data *pri)
{
return slip_proto_write(fd, buf, len, &pri->slip);
}
static void slip_add_addr(unsigned char *addr, unsigned char *netmask,
void *data)
{
struct slip_data *pri = data;
if (pri->slave < 0)
return;
open_addr(addr, netmask, pri->name);
}
static void slip_del_addr(unsigned char *addr, unsigned char *netmask,
void *data)
{
struct slip_data *pri = data;
if (pri->slave < 0)
return;
close_addr(addr, netmask, pri->name);
}
const struct net_user_info slip_user_info = {
.init = slip_user_init,
.open = slip_open,
.close = slip_close,
.remove = NULL,
.add_address = slip_add_addr,
.delete_address = slip_del_addr,
.mtu = BUF_SIZE,
.max_packet = BUF_SIZE,
};
| gpl-2.0 |
zdm110/android_kernel_samsung_msm8226 | drivers/video/backlight/apple_bl.c | 4815 | 6196 | /*
* Backlight Driver for Intel-based Apples
*
* Copyright (c) Red Hat <mjg@redhat.com>
* Based on code from Pommed:
* Copyright (C) 2006 Nicolas Boichat <nicolas @boichat.ch>
* Copyright (C) 2006 Felipe Alfaro Solana <felipe_alfaro @linuxmail.org>
* Copyright (C) 2007 Julien BLACHE <jb@jblache.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This driver triggers SMIs which cause the firmware to change the
* backlight brightness. This is icky in many ways, but it's impractical to
* get at the firmware code in order to figure out what it's actually doing.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/backlight.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/pci.h>
#include <linux/acpi.h>
#include <linux/atomic.h>
static struct backlight_device *apple_backlight_device;
struct hw_data {
/* I/O resource to allocate. */
unsigned long iostart;
unsigned long iolen;
/* Backlight operations structure. */
const struct backlight_ops backlight_ops;
void (*set_brightness)(int);
};
static const struct hw_data *hw_data;
#define DRIVER "apple_backlight: "
/* Module parameters. */
static int debug;
module_param_named(debug, debug, int, 0644);
MODULE_PARM_DESC(debug, "Set to one to enable debugging messages.");
/*
* Implementation for machines with Intel chipset.
*/
static void intel_chipset_set_brightness(int intensity)
{
outb(0x04 | (intensity << 4), 0xb3);
outb(0xbf, 0xb2);
}
static int intel_chipset_send_intensity(struct backlight_device *bd)
{
int intensity = bd->props.brightness;
if (debug)
printk(KERN_DEBUG DRIVER "setting brightness to %d\n",
intensity);
intel_chipset_set_brightness(intensity);
return 0;
}
static int intel_chipset_get_intensity(struct backlight_device *bd)
{
int intensity;
outb(0x03, 0xb3);
outb(0xbf, 0xb2);
intensity = inb(0xb3) >> 4;
if (debug)
printk(KERN_DEBUG DRIVER "read brightness of %d\n",
intensity);
return intensity;
}
static const struct hw_data intel_chipset_data = {
.iostart = 0xb2,
.iolen = 2,
.backlight_ops = {
.options = BL_CORE_SUSPENDRESUME,
.get_brightness = intel_chipset_get_intensity,
.update_status = intel_chipset_send_intensity,
},
.set_brightness = intel_chipset_set_brightness,
};
/*
* Implementation for machines with Nvidia chipset.
*/
static void nvidia_chipset_set_brightness(int intensity)
{
outb(0x04 | (intensity << 4), 0x52f);
outb(0xbf, 0x52e);
}
static int nvidia_chipset_send_intensity(struct backlight_device *bd)
{
int intensity = bd->props.brightness;
if (debug)
printk(KERN_DEBUG DRIVER "setting brightness to %d\n",
intensity);
nvidia_chipset_set_brightness(intensity);
return 0;
}
static int nvidia_chipset_get_intensity(struct backlight_device *bd)
{
int intensity;
outb(0x03, 0x52f);
outb(0xbf, 0x52e);
intensity = inb(0x52f) >> 4;
if (debug)
printk(KERN_DEBUG DRIVER "read brightness of %d\n",
intensity);
return intensity;
}
static const struct hw_data nvidia_chipset_data = {
.iostart = 0x52e,
.iolen = 2,
.backlight_ops = {
.options = BL_CORE_SUSPENDRESUME,
.get_brightness = nvidia_chipset_get_intensity,
.update_status = nvidia_chipset_send_intensity
},
.set_brightness = nvidia_chipset_set_brightness,
};
static int __devinit apple_bl_add(struct acpi_device *dev)
{
struct backlight_properties props;
struct pci_dev *host;
int intensity;
host = pci_get_bus_and_slot(0, 0);
if (!host) {
printk(KERN_ERR DRIVER "unable to find PCI host\n");
return -ENODEV;
}
if (host->vendor == PCI_VENDOR_ID_INTEL)
hw_data = &intel_chipset_data;
else if (host->vendor == PCI_VENDOR_ID_NVIDIA)
hw_data = &nvidia_chipset_data;
pci_dev_put(host);
if (!hw_data) {
printk(KERN_ERR DRIVER "unknown hardware\n");
return -ENODEV;
}
/* Check that the hardware responds - this may not work under EFI */
intensity = hw_data->backlight_ops.get_brightness(NULL);
if (!intensity) {
hw_data->set_brightness(1);
if (!hw_data->backlight_ops.get_brightness(NULL))
return -ENODEV;
hw_data->set_brightness(0);
}
if (!request_region(hw_data->iostart, hw_data->iolen,
"Apple backlight"))
return -ENXIO;
memset(&props, 0, sizeof(struct backlight_properties));
props.type = BACKLIGHT_PLATFORM;
props.max_brightness = 15;
apple_backlight_device = backlight_device_register("apple_backlight",
NULL, NULL, &hw_data->backlight_ops, &props);
if (IS_ERR(apple_backlight_device)) {
release_region(hw_data->iostart, hw_data->iolen);
return PTR_ERR(apple_backlight_device);
}
apple_backlight_device->props.brightness =
hw_data->backlight_ops.get_brightness(apple_backlight_device);
backlight_update_status(apple_backlight_device);
return 0;
}
static int __devexit apple_bl_remove(struct acpi_device *dev, int type)
{
backlight_device_unregister(apple_backlight_device);
release_region(hw_data->iostart, hw_data->iolen);
hw_data = NULL;
return 0;
}
static const struct acpi_device_id apple_bl_ids[] = {
{"APP0002", 0},
{"", 0},
};
static struct acpi_driver apple_bl_driver = {
.name = "Apple backlight",
.ids = apple_bl_ids,
.ops = {
.add = apple_bl_add,
.remove = apple_bl_remove,
},
};
static atomic_t apple_bl_registered = ATOMIC_INIT(0);
int apple_bl_register(void)
{
if (atomic_xchg(&apple_bl_registered, 1) == 0)
return acpi_bus_register_driver(&apple_bl_driver);
return 0;
}
EXPORT_SYMBOL_GPL(apple_bl_register);
void apple_bl_unregister(void)
{
if (atomic_xchg(&apple_bl_registered, 0) == 1)
acpi_bus_unregister_driver(&apple_bl_driver);
}
EXPORT_SYMBOL_GPL(apple_bl_unregister);
static int __init apple_bl_init(void)
{
return apple_bl_register();
}
static void __exit apple_bl_exit(void)
{
apple_bl_unregister();
}
module_init(apple_bl_init);
module_exit(apple_bl_exit);
MODULE_AUTHOR("Matthew Garrett <mjg@redhat.com>");
MODULE_DESCRIPTION("Apple Backlight Driver");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(acpi, apple_bl_ids);
MODULE_ALIAS("mbp_nvidia_bl");
| gpl-2.0 |
lyfest/android_kernel_samsung_sltechn | drivers/staging/rts5139/rts51x_card.c | 5071 | 23861 | /* Driver for Realtek RTS51xx USB card reader
*
* Copyright(c) 2009 Realtek Semiconductor 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, 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/>.
*
* Author:
* wwang (wei_wang@realsil.com.cn)
* No. 450, Shenhu Road, Suzhou Industry Park, Suzhou, China
* Maintainer:
* Edwin Rong (edwin_rong@realsil.com.cn)
* No. 450, Shenhu Road, Suzhou Industry Park, Suzhou, China
*/
#include <linux/blkdev.h>
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/workqueue.h>
#include <scsi/scsi.h>
#include <scsi/scsi_eh.h>
#include <scsi/scsi_device.h>
#include "debug.h"
#include "rts51x.h"
#include "rts51x_chip.h"
#include "rts51x_card.h"
#include "rts51x_transport.h"
#include "rts51x_sys.h"
#include "xd.h"
#include "sd.h"
#include "ms.h"
void do_remaining_work(struct rts51x_chip *chip)
{
struct sd_info *sd_card = &(chip->sd_card);
struct xd_info *xd_card = &(chip->xd_card);
struct ms_info *ms_card = &(chip->ms_card);
if (chip->card_ready & SD_CARD) {
if (sd_card->seq_mode) {
RTS51X_SET_STAT(chip, STAT_RUN);
sd_card->counter++;
} else {
sd_card->counter = 0;
}
}
if (chip->card_ready & XD_CARD) {
if (xd_card->delay_write.delay_write_flag) {
RTS51X_SET_STAT(chip, STAT_RUN);
xd_card->counter++;
} else {
xd_card->counter = 0;
}
}
if (chip->card_ready & MS_CARD) {
if (CHK_MSPRO(ms_card)) {
if (ms_card->seq_mode) {
RTS51X_SET_STAT(chip, STAT_RUN);
ms_card->counter++;
} else {
ms_card->counter = 0;
}
} else {
if (ms_card->delay_write.delay_write_flag) {
RTS51X_SET_STAT(chip, STAT_RUN);
ms_card->counter++;
} else {
ms_card->counter = 0;
}
}
}
if (sd_card->counter > POLLING_WAIT_CNT)
sd_cleanup_work(chip);
if (xd_card->counter > POLLING_WAIT_CNT)
xd_cleanup_work(chip);
if (ms_card->counter > POLLING_WAIT_CNT)
ms_cleanup_work(chip);
}
void do_reset_xd_card(struct rts51x_chip *chip)
{
int retval;
if (chip->card2lun[XD_CARD] >= MAX_ALLOWED_LUN_CNT)
return;
retval = reset_xd_card(chip);
if (retval == STATUS_SUCCESS) {
chip->card_ready |= XD_CARD;
chip->card_fail &= ~XD_CARD;
chip->rw_card[chip->card2lun[XD_CARD]] = xd_rw;
} else {
chip->card_ready &= ~XD_CARD;
chip->card_fail |= XD_CARD;
chip->capacity[chip->card2lun[XD_CARD]] = 0;
chip->rw_card[chip->card2lun[XD_CARD]] = NULL;
rts51x_init_cmd(chip);
rts51x_add_cmd(chip, WRITE_REG_CMD, CARD_OE, XD_OUTPUT_EN, 0);
rts51x_add_cmd(chip, WRITE_REG_CMD, CARD_PWR_CTL, POWER_MASK,
POWER_OFF);
rts51x_add_cmd(chip, WRITE_REG_CMD, CARD_CLK_EN, XD_CLK_EN, 0);
rts51x_send_cmd(chip, MODE_C, 100);
}
}
void do_reset_sd_card(struct rts51x_chip *chip)
{
int retval;
if (chip->card2lun[SD_CARD] >= MAX_ALLOWED_LUN_CNT)
return;
retval = reset_sd_card(chip);
if (retval == STATUS_SUCCESS) {
chip->card_ready |= SD_CARD;
chip->card_fail &= ~SD_CARD;
chip->rw_card[chip->card2lun[SD_CARD]] = sd_rw;
} else {
chip->card_ready &= ~SD_CARD;
chip->card_fail |= SD_CARD;
chip->capacity[chip->card2lun[SD_CARD]] = 0;
chip->rw_card[chip->card2lun[SD_CARD]] = NULL;
rts51x_init_cmd(chip);
rts51x_add_cmd(chip, WRITE_REG_CMD, CARD_OE, SD_OUTPUT_EN, 0);
rts51x_add_cmd(chip, WRITE_REG_CMD, CARD_PWR_CTL, POWER_MASK,
POWER_OFF);
rts51x_add_cmd(chip, WRITE_REG_CMD, CARD_CLK_EN, SD_CLK_EN, 0);
rts51x_send_cmd(chip, MODE_C, 100);
}
}
void do_reset_ms_card(struct rts51x_chip *chip)
{
int retval;
if (chip->card2lun[MS_CARD] >= MAX_ALLOWED_LUN_CNT)
return;
retval = reset_ms_card(chip);
if (retval == STATUS_SUCCESS) {
chip->card_ready |= MS_CARD;
chip->card_fail &= ~MS_CARD;
chip->rw_card[chip->card2lun[MS_CARD]] = ms_rw;
} else {
chip->card_ready &= ~MS_CARD;
chip->card_fail |= MS_CARD;
chip->capacity[chip->card2lun[MS_CARD]] = 0;
chip->rw_card[chip->card2lun[MS_CARD]] = NULL;
rts51x_init_cmd(chip);
rts51x_add_cmd(chip, WRITE_REG_CMD, CARD_OE, MS_OUTPUT_EN, 0);
rts51x_add_cmd(chip, WRITE_REG_CMD, CARD_PWR_CTL, POWER_MASK,
POWER_OFF);
rts51x_add_cmd(chip, WRITE_REG_CMD, CARD_CLK_EN, MS_CLK_EN, 0);
rts51x_send_cmd(chip, MODE_C, 100);
}
}
void card_cd_debounce(struct rts51x_chip *chip, u8 *need_reset,
u8 *need_release)
{
int retval;
u8 release_map = 0, reset_map = 0;
u8 value;
retval = rts51x_get_card_status(chip, &(chip->card_status));
#ifdef SUPPORT_OCP
chip->ocp_stat = (chip->card_status >> 4) & 0x03;
#endif
if (retval != STATUS_SUCCESS)
goto Exit_Debounce;
if (chip->card_exist) {
rts51x_clear_start_time(chip);
retval = rts51x_read_register(chip, CARD_INT_PEND, &value);
if (retval != STATUS_SUCCESS) {
rts51x_ep0_write_register(chip, MC_FIFO_CTL, FIFO_FLUSH,
FIFO_FLUSH);
rts51x_ep0_write_register(chip, SFSM_ED, 0xf8, 0xf8);
value = 0;
}
if (chip->card_exist & XD_CARD) {
if (!(chip->card_status & XD_CD))
release_map |= XD_CARD;
} else if (chip->card_exist & SD_CARD) {
/* if (!(chip->card_status & SD_CD)) { */
if (!(chip->card_status & SD_CD) || (value & SD_INT))
release_map |= SD_CARD;
} else if (chip->card_exist & MS_CARD) {
/* if (!(chip->card_status & MS_CD)) { */
if (!(chip->card_status & MS_CD) || (value & MS_INT))
release_map |= MS_CARD;
}
} else {
if (chip->card_status & XD_CD) {
rts51x_clear_start_time(chip);
reset_map |= XD_CARD;
} else if (chip->card_status & SD_CD) {
rts51x_clear_start_time(chip);
reset_map |= SD_CARD;
} else if (chip->card_status & MS_CD) {
rts51x_clear_start_time(chip);
reset_map |= MS_CARD;
} else {
if (rts51x_check_start_time(chip))
rts51x_set_start_time(chip);
}
}
if (CHECK_PKG(chip, QFN24) && reset_map) {
if (chip->card_exist & XD_CARD) {
reset_map = 0;
goto Exit_Debounce;
}
}
if (reset_map) {
int xd_cnt = 0, sd_cnt = 0, ms_cnt = 0;
int i;
for (i = 0; i < (chip->option.debounce_num); i++) {
retval =
rts51x_get_card_status(chip, &(chip->card_status));
if (retval != STATUS_SUCCESS) {
reset_map = release_map = 0;
goto Exit_Debounce;
}
if (chip->card_status & XD_CD)
xd_cnt++;
else
xd_cnt = 0;
if (chip->card_status & SD_CD)
sd_cnt++;
else
sd_cnt = 0;
if (chip->card_status & MS_CD)
ms_cnt++;
else
ms_cnt = 0;
wait_timeout(30);
}
reset_map = 0;
if (!(chip->card_exist & XD_CARD)
&& (xd_cnt > (chip->option.debounce_num - 1))) {
reset_map |= XD_CARD;
}
if (!(chip->card_exist & SD_CARD)
&& (sd_cnt > (chip->option.debounce_num - 1))) {
reset_map |= SD_CARD;
}
if (!(chip->card_exist & MS_CARD)
&& (ms_cnt > (chip->option.debounce_num - 1))) {
reset_map |= MS_CARD;
}
}
rts51x_write_register(chip, CARD_INT_PEND, XD_INT | MS_INT | SD_INT,
XD_INT | MS_INT | SD_INT);
Exit_Debounce:
if (need_reset)
*need_reset = reset_map;
if (need_release)
*need_release = release_map;
}
void rts51x_init_cards(struct rts51x_chip *chip)
{
u8 need_reset = 0, need_release = 0;
card_cd_debounce(chip, &need_reset, &need_release);
if (need_release) {
RTS51X_DEBUGP("need_release = 0x%x\n", need_release);
rts51x_prepare_run(chip);
RTS51X_SET_STAT(chip, STAT_RUN);
#ifdef SUPPORT_OCP
if (chip->ocp_stat & (MS_OCP_NOW | MS_OCP_EVER)) {
rts51x_write_register(chip, OCPCTL, MS_OCP_CLEAR,
MS_OCP_CLEAR);
chip->ocp_stat = 0;
RTS51X_DEBUGP("Clear OCP status.\n");
}
#endif
if (need_release & XD_CARD) {
chip->card_exist &= ~XD_CARD;
chip->card_ejected = 0;
if (chip->card_ready & XD_CARD) {
release_xd_card(chip);
chip->rw_card[chip->card2lun[XD_CARD]] = NULL;
clear_bit(chip->card2lun[XD_CARD],
&(chip->lun_mc));
}
}
if (need_release & SD_CARD) {
chip->card_exist &= ~SD_CARD;
chip->card_ejected = 0;
if (chip->card_ready & SD_CARD) {
release_sd_card(chip);
chip->rw_card[chip->card2lun[SD_CARD]] = NULL;
clear_bit(chip->card2lun[SD_CARD],
&(chip->lun_mc));
}
}
if (need_release & MS_CARD) {
chip->card_exist &= ~MS_CARD;
chip->card_ejected = 0;
if (chip->card_ready & MS_CARD) {
release_ms_card(chip);
chip->rw_card[chip->card2lun[MS_CARD]] = NULL;
clear_bit(chip->card2lun[MS_CARD],
&(chip->lun_mc));
}
}
}
if (need_reset && !chip->card_ready) {
RTS51X_DEBUGP("need_reset = 0x%x\n", need_reset);
rts51x_prepare_run(chip);
RTS51X_SET_STAT(chip, STAT_RUN);
if (need_reset & XD_CARD) {
chip->card_exist |= XD_CARD;
do_reset_xd_card(chip);
} else if (need_reset & SD_CARD) {
chip->card_exist |= SD_CARD;
do_reset_sd_card(chip);
} else if (need_reset & MS_CARD) {
chip->card_exist |= MS_CARD;
do_reset_ms_card(chip);
}
}
}
void rts51x_release_cards(struct rts51x_chip *chip)
{
if (chip->card_ready & SD_CARD) {
sd_cleanup_work(chip);
release_sd_card(chip);
chip->card_ready &= ~SD_CARD;
}
if (chip->card_ready & XD_CARD) {
xd_cleanup_work(chip);
release_xd_card(chip);
chip->card_ready &= ~XD_CARD;
}
if (chip->card_ready & MS_CARD) {
ms_cleanup_work(chip);
release_ms_card(chip);
chip->card_ready &= ~MS_CARD;
}
}
static inline u8 double_depth(u8 depth)
{
return ((depth > 1) ? (depth - 1) : depth);
}
int switch_ssc_clock(struct rts51x_chip *chip, int clk)
{
struct sd_info *sd_card = &(chip->sd_card);
struct ms_info *ms_card = &(chip->ms_card);
int retval;
u8 N = (u8) (clk - 2), min_N, max_N;
u8 mcu_cnt, div, max_div, ssc_depth;
int sd_vpclk_phase_reset = 0;
if (chip->cur_clk == clk)
return STATUS_SUCCESS;
min_N = 60;
max_N = 120;
max_div = CLK_DIV_4;
RTS51X_DEBUGP("Switch SSC clock to %dMHz\n", clk);
if ((clk <= 2) || (N > max_N))
TRACE_RET(chip, STATUS_FAIL);
mcu_cnt = (u8) (60 / clk + 3);
if (mcu_cnt > 15)
mcu_cnt = 15;
/* To make sure that the SSC clock div_n is
* equal or greater than min_N */
div = CLK_DIV_1;
while ((N < min_N) && (div < max_div)) {
N = (N + 2) * 2 - 2;
div++;
}
RTS51X_DEBUGP("N = %d, div = %d\n", N, div);
if (chip->option.ssc_en) {
if (chip->cur_card == SD_CARD) {
if (CHK_SD_SDR104(sd_card)) {
ssc_depth = chip->option.ssc_depth_sd_sdr104;
} else if (CHK_SD_SDR50(sd_card)) {
ssc_depth = chip->option.ssc_depth_sd_sdr50;
} else if (CHK_SD_DDR50(sd_card)) {
ssc_depth =
double_depth(chip->option.
ssc_depth_sd_ddr50);
} else if (CHK_SD_HS(sd_card)) {
ssc_depth =
double_depth(chip->option.ssc_depth_sd_hs);
} else if (CHK_MMC_52M(sd_card)
|| CHK_MMC_DDR52(sd_card)) {
ssc_depth =
double_depth(chip->option.
ssc_depth_mmc_52m);
} else {
ssc_depth =
double_depth(chip->option.
ssc_depth_low_speed);
}
} else if (chip->cur_card == MS_CARD) {
if (CHK_MSPRO(ms_card)) {
if (CHK_HG8BIT(ms_card)) {
ssc_depth =
double_depth(chip->option.
ssc_depth_ms_hg);
} else {
ssc_depth =
double_depth(chip->option.
ssc_depth_ms_4bit);
}
} else {
if (CHK_MS4BIT(ms_card)) {
ssc_depth =
double_depth(chip->option.
ssc_depth_ms_4bit);
} else {
ssc_depth =
double_depth(chip->option.
ssc_depth_low_speed);
}
}
} else {
ssc_depth =
double_depth(chip->option.ssc_depth_low_speed);
}
if (ssc_depth) {
if (div == CLK_DIV_2) {
/* If clock divided by 2, ssc depth must
* be multiplied by 2 */
if (ssc_depth > 1)
ssc_depth -= 1;
else
ssc_depth = SSC_DEPTH_2M;
} else if (div == CLK_DIV_4) {
/* If clock divided by 4, ssc depth must
* be multiplied by 4 */
if (ssc_depth > 2)
ssc_depth -= 2;
else
ssc_depth = SSC_DEPTH_2M;
}
}
} else {
/* Disable SSC */
ssc_depth = 0;
}
RTS51X_DEBUGP("ssc_depth = %d\n", ssc_depth);
rts51x_init_cmd(chip);
rts51x_add_cmd(chip, WRITE_REG_CMD, CLK_DIV, CLK_CHANGE, CLK_CHANGE);
rts51x_add_cmd(chip, WRITE_REG_CMD, CLK_DIV, 0x3F,
(div << 4) | mcu_cnt);
rts51x_add_cmd(chip, WRITE_REG_CMD, SSC_CTL1, SSC_RSTB, 0);
rts51x_add_cmd(chip, WRITE_REG_CMD, SSC_CTL2, SSC_DEPTH_MASK,
ssc_depth);
rts51x_add_cmd(chip, WRITE_REG_CMD, SSC_DIV_N_0, 0xFF, N);
if (sd_vpclk_phase_reset) {
rts51x_add_cmd(chip, WRITE_REG_CMD, SD_VPCLK0_CTL,
PHASE_NOT_RESET, 0);
rts51x_add_cmd(chip, WRITE_REG_CMD, SD_VPCLK0_CTL,
PHASE_NOT_RESET, PHASE_NOT_RESET);
}
retval = rts51x_send_cmd(chip, MODE_C, 2000);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, retval);
if (chip->option.ssc_en && ssc_depth)
rts51x_write_register(chip, SSC_CTL1, 0xff, 0xD0);
else
rts51x_write_register(chip, SSC_CTL1, 0xff, 0x50);
udelay(100);
RTS51X_WRITE_REG(chip, CLK_DIV, CLK_CHANGE, 0);
chip->cur_clk = clk;
return STATUS_SUCCESS;
}
int switch_normal_clock(struct rts51x_chip *chip, int clk)
{
int retval;
u8 sel, div, mcu_cnt;
int sd_vpclk_phase_reset = 0;
if (chip->cur_clk == clk)
return STATUS_SUCCESS;
if (chip->cur_card == SD_CARD) {
struct sd_info *sd_card = &(chip->sd_card);
if (CHK_SD30_SPEED(sd_card) || CHK_MMC_DDR52(sd_card))
sd_vpclk_phase_reset = 1;
}
switch (clk) {
case CLK_20:
RTS51X_DEBUGP("Switch clock to 20MHz\n");
sel = SSC_80;
div = CLK_DIV_4;
mcu_cnt = 5;
break;
case CLK_30:
RTS51X_DEBUGP("Switch clock to 30MHz\n");
sel = SSC_60;
div = CLK_DIV_2;
mcu_cnt = 4;
break;
case CLK_40:
RTS51X_DEBUGP("Switch clock to 40MHz\n");
sel = SSC_80;
div = CLK_DIV_2;
mcu_cnt = 3;
break;
case CLK_50:
RTS51X_DEBUGP("Switch clock to 50MHz\n");
sel = SSC_100;
div = CLK_DIV_2;
mcu_cnt = 3;
break;
case CLK_60:
RTS51X_DEBUGP("Switch clock to 60MHz\n");
sel = SSC_60;
div = CLK_DIV_1;
mcu_cnt = 3;
break;
case CLK_80:
RTS51X_DEBUGP("Switch clock to 80MHz\n");
sel = SSC_80;
div = CLK_DIV_1;
mcu_cnt = 2;
break;
case CLK_100:
RTS51X_DEBUGP("Switch clock to 100MHz\n");
sel = SSC_100;
div = CLK_DIV_1;
mcu_cnt = 2;
break;
/* case CLK_120:
RTS51X_DEBUGP("Switch clock to 120MHz\n");
sel = SSC_120;
div = CLK_DIV_1;
mcu_cnt = 2;
break;
case CLK_150:
RTS51X_DEBUGP("Switch clock to 150MHz\n");
sel = SSC_150;
div = CLK_DIV_1;
mcu_cnt = 2;
break; */
default:
RTS51X_DEBUGP("Try to switch to an illegal clock (%d)\n",
clk);
TRACE_RET(chip, STATUS_FAIL);
}
if (!sd_vpclk_phase_reset) {
rts51x_init_cmd(chip);
rts51x_add_cmd(chip, WRITE_REG_CMD, CLK_DIV, CLK_CHANGE,
CLK_CHANGE);
rts51x_add_cmd(chip, WRITE_REG_CMD, CLK_DIV, 0x3F,
(div << 4) | mcu_cnt);
rts51x_add_cmd(chip, WRITE_REG_CMD, SSC_CLK_FPGA_SEL, 0xFF,
sel);
rts51x_add_cmd(chip, WRITE_REG_CMD, CLK_DIV, CLK_CHANGE, 0);
retval = rts51x_send_cmd(chip, MODE_C, 100);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, retval);
} else {
rts51x_init_cmd(chip);
rts51x_add_cmd(chip, WRITE_REG_CMD, CLK_DIV, CLK_CHANGE,
CLK_CHANGE);
rts51x_add_cmd(chip, WRITE_REG_CMD, SD_VPCLK0_CTL,
PHASE_NOT_RESET, 0);
rts51x_add_cmd(chip, WRITE_REG_CMD, SD_VPCLK1_CTL,
PHASE_NOT_RESET, 0);
rts51x_add_cmd(chip, WRITE_REG_CMD, CLK_DIV, 0x3F,
(div << 4) | mcu_cnt);
rts51x_add_cmd(chip, WRITE_REG_CMD, SSC_CLK_FPGA_SEL, 0xFF,
sel);
retval = rts51x_send_cmd(chip, MODE_C, 100);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, retval);
udelay(200);
rts51x_init_cmd(chip);
rts51x_add_cmd(chip, WRITE_REG_CMD, SD_VPCLK0_CTL,
PHASE_NOT_RESET, PHASE_NOT_RESET);
rts51x_add_cmd(chip, WRITE_REG_CMD, SD_VPCLK1_CTL,
PHASE_NOT_RESET, PHASE_NOT_RESET);
retval = rts51x_send_cmd(chip, MODE_C, 100);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, retval);
udelay(200);
RTS51X_WRITE_REG(chip, CLK_DIV, CLK_CHANGE, 0);
}
chip->cur_clk = clk;
return STATUS_SUCCESS;
}
int card_rw(struct scsi_cmnd *srb, struct rts51x_chip *chip, u32 sec_addr,
u16 sec_cnt)
{
int retval;
unsigned int lun = SCSI_LUN(srb);
int i;
if (chip->rw_card[lun] == NULL)
return STATUS_FAIL;
RTS51X_DEBUGP("%s card, sector addr: 0x%x, sector cnt: %d\n",
(srb->sc_data_direction ==
DMA_TO_DEVICE) ? "Write" : "Read", sec_addr, sec_cnt);
chip->rw_need_retry = 0;
for (i = 0; i < 3; i++) {
retval = chip->rw_card[lun] (srb, chip, sec_addr, sec_cnt);
if (retval != STATUS_SUCCESS) {
CATCH_TRIGGER(chip);
if (chip->option.reset_or_rw_fail_set_pad_drive) {
rts51x_write_register(chip, CARD_DRIVE_SEL,
SD20_DRIVE_MASK,
DRIVE_8mA);
}
}
if (!chip->rw_need_retry)
break;
RTS51X_DEBUGP("Retry RW, (i = %d\n)", i);
}
return retval;
}
u8 get_lun_card(struct rts51x_chip *chip, unsigned int lun)
{
if ((chip->card_ready & chip->lun2card[lun]) == XD_CARD)
return (u8) XD_CARD;
else if ((chip->card_ready & chip->lun2card[lun]) == SD_CARD)
return (u8) SD_CARD;
else if ((chip->card_ready & chip->lun2card[lun]) == MS_CARD)
return (u8) MS_CARD;
return 0;
}
int card_share_mode(struct rts51x_chip *chip, int card)
{
u8 value;
if (card == SD_CARD)
value = CARD_SHARE_SD;
else if (card == MS_CARD)
value = CARD_SHARE_MS;
else if (card == XD_CARD)
value = CARD_SHARE_XD;
else
TRACE_RET(chip, STATUS_FAIL);
RTS51X_WRITE_REG(chip, CARD_SHARE_MODE, CARD_SHARE_MASK, value);
return STATUS_SUCCESS;
}
int rts51x_select_card(struct rts51x_chip *chip, int card)
{
int retval;
if (chip->cur_card != card) {
u8 mod;
if (card == SD_CARD)
mod = SD_MOD_SEL;
else if (card == MS_CARD)
mod = MS_MOD_SEL;
else if (card == XD_CARD)
mod = XD_MOD_SEL;
else
TRACE_RET(chip, STATUS_FAIL);
RTS51X_WRITE_REG(chip, CARD_SELECT, 0x07, mod);
chip->cur_card = card;
retval = card_share_mode(chip, card);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, retval);
}
return STATUS_SUCCESS;
}
void eject_card(struct rts51x_chip *chip, unsigned int lun)
{
RTS51X_DEBUGP("eject card\n");
RTS51X_SET_STAT(chip, STAT_RUN);
do_remaining_work(chip);
if ((chip->card_ready & chip->lun2card[lun]) == SD_CARD) {
release_sd_card(chip);
chip->card_ejected |= SD_CARD;
chip->card_ready &= ~SD_CARD;
chip->capacity[lun] = 0;
} else if ((chip->card_ready & chip->lun2card[lun]) == XD_CARD) {
release_xd_card(chip);
chip->card_ejected |= XD_CARD;
chip->card_ready &= ~XD_CARD;
chip->capacity[lun] = 0;
} else if ((chip->card_ready & chip->lun2card[lun]) == MS_CARD) {
release_ms_card(chip);
chip->card_ejected |= MS_CARD;
chip->card_ready &= ~MS_CARD;
chip->capacity[lun] = 0;
}
rts51x_write_register(chip, CARD_INT_PEND, XD_INT | MS_INT | SD_INT,
XD_INT | MS_INT | SD_INT);
}
void trans_dma_enable(enum dma_data_direction dir, struct rts51x_chip *chip,
u32 byte_cnt, u8 pack_size)
{
if (pack_size > DMA_1024)
pack_size = DMA_512;
rts51x_add_cmd(chip, WRITE_REG_CMD, CARD_DATA_SOURCE, 0x01,
RING_BUFFER);
rts51x_add_cmd(chip, WRITE_REG_CMD, MC_DMA_TC3, 0xFF,
(u8) (byte_cnt >> 24));
rts51x_add_cmd(chip, WRITE_REG_CMD, MC_DMA_TC2, 0xFF,
(u8) (byte_cnt >> 16));
rts51x_add_cmd(chip, WRITE_REG_CMD, MC_DMA_TC1, 0xFF,
(u8) (byte_cnt >> 8));
rts51x_add_cmd(chip, WRITE_REG_CMD, MC_DMA_TC0, 0xFF, (u8) byte_cnt);
if (dir == DMA_FROM_DEVICE) {
rts51x_add_cmd(chip, WRITE_REG_CMD, MC_DMA_CTL,
0x03 | DMA_PACK_SIZE_MASK,
DMA_DIR_FROM_CARD | DMA_EN | pack_size);
} else {
rts51x_add_cmd(chip, WRITE_REG_CMD, MC_DMA_CTL,
0x03 | DMA_PACK_SIZE_MASK,
DMA_DIR_TO_CARD | DMA_EN | pack_size);
}
}
int enable_card_clock(struct rts51x_chip *chip, u8 card)
{
u8 clk_en = 0;
if (card & XD_CARD)
clk_en |= XD_CLK_EN;
if (card & SD_CARD)
clk_en |= SD_CLK_EN;
if (card & MS_CARD)
clk_en |= MS_CLK_EN;
RTS51X_WRITE_REG(chip, CARD_CLK_EN, clk_en, clk_en);
return STATUS_SUCCESS;
}
int disable_card_clock(struct rts51x_chip *chip, u8 card)
{
u8 clk_en = 0;
if (card & XD_CARD)
clk_en |= XD_CLK_EN;
if (card & SD_CARD)
clk_en |= SD_CLK_EN;
if (card & MS_CARD)
clk_en |= MS_CLK_EN;
RTS51X_WRITE_REG(chip, CARD_CLK_EN, clk_en, 0);
return STATUS_SUCCESS;
}
int card_power_on(struct rts51x_chip *chip, u8 card)
{
u8 mask, val1, val2;
mask = POWER_MASK;
val1 = PARTIAL_POWER_ON;
val2 = POWER_ON;
#ifdef SD_XD_IO_FOLLOW_PWR
if ((card == SD_CARD) || (card == XD_CARD)) {
RTS51X_WRITE_REG(chip, CARD_PWR_CTL, mask | LDO3318_PWR_MASK,
val1 | LDO_SUSPEND);
/* RTS51X_WRITE_REG(chip, CARD_PWR_CTL,
LDO3318_PWR_MASK, LDO_SUSPEND); */
}
/* else if(card==XD_CARD)
{
RTS51X_WRITE_REG(chip, CARD_PWR_CTL,
mask|LDO3318_PWR_MASK, val1|LDO_SUSPEND);
//RTS51X_WRITE_REG(chip, CARD_PWR_CTL,
// LDO3318_PWR_MASK, LDO_SUSPEND);
} */
else {
#endif
RTS51X_WRITE_REG(chip, CARD_PWR_CTL, mask, val1);
#ifdef SD_XD_IO_FOLLOW_PWR
}
#endif
udelay(chip->option.pwr_delay);
RTS51X_WRITE_REG(chip, CARD_PWR_CTL, mask, val2);
#ifdef SD_XD_IO_FOLLOW_PWR
if (card == SD_CARD) {
rts51x_write_register(chip, CARD_PWR_CTL, LDO3318_PWR_MASK,
LDO_ON);
}
#endif
return STATUS_SUCCESS;
}
int card_power_off(struct rts51x_chip *chip, u8 card)
{
u8 mask, val;
mask = POWER_MASK;
val = POWER_OFF;
RTS51X_WRITE_REG(chip, CARD_PWR_CTL, mask, val);
return STATUS_SUCCESS;
}
int monitor_card_cd(struct rts51x_chip *chip, u8 card)
{
int retval;
u8 card_cd[32] = { 0 };
card_cd[SD_CARD] = SD_CD;
card_cd[XD_CARD] = XD_CD;
card_cd[MS_CARD] = MS_CD;
retval = rts51x_get_card_status(chip, &(chip->card_status));
if (retval != STATUS_SUCCESS)
return CD_NOT_EXIST;
if (chip->card_status & card_cd[card])
return CD_EXIST;
return CD_NOT_EXIST;
}
int toggle_gpio(struct rts51x_chip *chip, u8 gpio)
{
int retval;
u8 temp_reg;
u8 gpio_output[4] = {
0x01,
};
u8 gpio_oe[4] = {
0x02,
};
if (chip->rts5179) {
retval = rts51x_ep0_read_register(chip, CARD_GPIO, &temp_reg);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, STATUS_FAIL);
temp_reg ^= gpio_oe[gpio];
temp_reg &= 0xfe; /* bit 0 always set 0 */
retval =
rts51x_ep0_write_register(chip, CARD_GPIO, 0x03, temp_reg);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, STATUS_FAIL);
} else {
retval = rts51x_ep0_read_register(chip, CARD_GPIO, &temp_reg);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, STATUS_FAIL);
temp_reg ^= gpio_output[gpio];
retval =
rts51x_ep0_write_register(chip, CARD_GPIO, 0xFF,
temp_reg | gpio_oe[gpio]);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, STATUS_FAIL);
}
return STATUS_SUCCESS;
}
int turn_on_led(struct rts51x_chip *chip, u8 gpio)
{
int retval;
u8 gpio_oe[4] = {
0x02,
};
u8 gpio_mask[4] = {
0x03,
};
retval =
rts51x_ep0_write_register(chip, CARD_GPIO, gpio_mask[gpio],
gpio_oe[gpio]);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, STATUS_FAIL);
return STATUS_SUCCESS;
}
int turn_off_led(struct rts51x_chip *chip, u8 gpio)
{
int retval;
u8 gpio_output[4] = {
0x01,
};
u8 gpio_oe[4] = {
0x02,
};
u8 gpio_mask[4] = {
0x03,
};
retval =
rts51x_ep0_write_register(chip, CARD_GPIO, gpio_mask[gpio],
gpio_oe[gpio] | gpio_output[gpio]);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, STATUS_FAIL);
return STATUS_SUCCESS;
}
| gpl-2.0 |
sakuraba001/android_kernel_samsung_klteactive | drivers/acpi/dock.c | 5071 | 28515 | /*
* dock.c - ACPI dock station driver
*
* Copyright (C) 2006 Kristen Carlson Accardi <kristen.c.accardi@intel.com>
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/notifier.h>
#include <linux/platform_device.h>
#include <linux/jiffies.h>
#include <linux/stddef.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#define PREFIX "ACPI: "
#define ACPI_DOCK_DRIVER_DESCRIPTION "ACPI Dock Station Driver"
ACPI_MODULE_NAME("dock");
MODULE_AUTHOR("Kristen Carlson Accardi");
MODULE_DESCRIPTION(ACPI_DOCK_DRIVER_DESCRIPTION);
MODULE_LICENSE("GPL");
static bool immediate_undock = 1;
module_param(immediate_undock, bool, 0644);
MODULE_PARM_DESC(immediate_undock, "1 (default) will cause the driver to "
"undock immediately when the undock button is pressed, 0 will cause"
" the driver to wait for userspace to write the undock sysfs file "
" before undocking");
static struct atomic_notifier_head dock_notifier_list;
static const struct acpi_device_id dock_device_ids[] = {
{"LNXDOCK", 0},
{"", 0},
};
MODULE_DEVICE_TABLE(acpi, dock_device_ids);
struct dock_station {
acpi_handle handle;
unsigned long last_dock_time;
u32 flags;
spinlock_t dd_lock;
struct mutex hp_lock;
struct list_head dependent_devices;
struct list_head hotplug_devices;
struct list_head sibling;
struct platform_device *dock_device;
};
static LIST_HEAD(dock_stations);
static int dock_station_count;
struct dock_dependent_device {
struct list_head list;
struct list_head hotplug_list;
acpi_handle handle;
const struct acpi_dock_ops *ops;
void *context;
};
#define DOCK_DOCKING 0x00000001
#define DOCK_UNDOCKING 0x00000002
#define DOCK_IS_DOCK 0x00000010
#define DOCK_IS_ATA 0x00000020
#define DOCK_IS_BAT 0x00000040
#define DOCK_EVENT 3
#define UNDOCK_EVENT 2
/*****************************************************************************
* Dock Dependent device functions *
*****************************************************************************/
/**
* add_dock_dependent_device - associate a device with the dock station
* @ds: The dock station
* @handle: handle of the dependent device
*
* Add the dependent device to the dock's dependent device list.
*/
static int
add_dock_dependent_device(struct dock_station *ds, acpi_handle handle)
{
struct dock_dependent_device *dd;
dd = kzalloc(sizeof(*dd), GFP_KERNEL);
if (!dd)
return -ENOMEM;
dd->handle = handle;
INIT_LIST_HEAD(&dd->list);
INIT_LIST_HEAD(&dd->hotplug_list);
spin_lock(&ds->dd_lock);
list_add_tail(&dd->list, &ds->dependent_devices);
spin_unlock(&ds->dd_lock);
return 0;
}
/**
* dock_add_hotplug_device - associate a hotplug handler with the dock station
* @ds: The dock station
* @dd: The dependent device struct
*
* Add the dependent device to the dock's hotplug device list
*/
static void
dock_add_hotplug_device(struct dock_station *ds,
struct dock_dependent_device *dd)
{
mutex_lock(&ds->hp_lock);
list_add_tail(&dd->hotplug_list, &ds->hotplug_devices);
mutex_unlock(&ds->hp_lock);
}
/**
* dock_del_hotplug_device - remove a hotplug handler from the dock station
* @ds: The dock station
* @dd: the dependent device struct
*
* Delete the dependent device from the dock's hotplug device list
*/
static void
dock_del_hotplug_device(struct dock_station *ds,
struct dock_dependent_device *dd)
{
mutex_lock(&ds->hp_lock);
list_del(&dd->hotplug_list);
mutex_unlock(&ds->hp_lock);
}
/**
* find_dock_dependent_device - get a device dependent on this dock
* @ds: the dock station
* @handle: the acpi_handle of the device we want
*
* iterate over the dependent device list for this dock. If the
* dependent device matches the handle, return.
*/
static struct dock_dependent_device *
find_dock_dependent_device(struct dock_station *ds, acpi_handle handle)
{
struct dock_dependent_device *dd;
spin_lock(&ds->dd_lock);
list_for_each_entry(dd, &ds->dependent_devices, list) {
if (handle == dd->handle) {
spin_unlock(&ds->dd_lock);
return dd;
}
}
spin_unlock(&ds->dd_lock);
return NULL;
}
/*****************************************************************************
* Dock functions *
*****************************************************************************/
/**
* is_dock - see if a device is a dock station
* @handle: acpi handle of the device
*
* If an acpi object has a _DCK method, then it is by definition a dock
* station, so return true.
*/
static int is_dock(acpi_handle handle)
{
acpi_status status;
acpi_handle tmp;
status = acpi_get_handle(handle, "_DCK", &tmp);
if (ACPI_FAILURE(status))
return 0;
return 1;
}
static int is_ejectable(acpi_handle handle)
{
acpi_status status;
acpi_handle tmp;
status = acpi_get_handle(handle, "_EJ0", &tmp);
if (ACPI_FAILURE(status))
return 0;
return 1;
}
static int is_ata(acpi_handle handle)
{
acpi_handle tmp;
if ((ACPI_SUCCESS(acpi_get_handle(handle, "_GTF", &tmp))) ||
(ACPI_SUCCESS(acpi_get_handle(handle, "_GTM", &tmp))) ||
(ACPI_SUCCESS(acpi_get_handle(handle, "_STM", &tmp))) ||
(ACPI_SUCCESS(acpi_get_handle(handle, "_SDD", &tmp))))
return 1;
return 0;
}
static int is_battery(acpi_handle handle)
{
struct acpi_device_info *info;
int ret = 1;
if (!ACPI_SUCCESS(acpi_get_object_info(handle, &info)))
return 0;
if (!(info->valid & ACPI_VALID_HID))
ret = 0;
else
ret = !strcmp("PNP0C0A", info->hardware_id.string);
kfree(info);
return ret;
}
static int is_ejectable_bay(acpi_handle handle)
{
acpi_handle phandle;
if (!is_ejectable(handle))
return 0;
if (is_battery(handle) || is_ata(handle))
return 1;
if (!acpi_get_parent(handle, &phandle) && is_ata(phandle))
return 1;
return 0;
}
/**
* is_dock_device - see if a device is on a dock station
* @handle: acpi handle of the device
*
* If this device is either the dock station itself,
* or is a device dependent on the dock station, then it
* is a dock device
*/
int is_dock_device(acpi_handle handle)
{
struct dock_station *dock_station;
if (!dock_station_count)
return 0;
if (is_dock(handle))
return 1;
list_for_each_entry(dock_station, &dock_stations, sibling)
if (find_dock_dependent_device(dock_station, handle))
return 1;
return 0;
}
EXPORT_SYMBOL_GPL(is_dock_device);
/**
* dock_present - see if the dock station is present.
* @ds: the dock station
*
* execute the _STA method. note that present does not
* imply that we are docked.
*/
static int dock_present(struct dock_station *ds)
{
unsigned long long sta;
acpi_status status;
if (ds) {
status = acpi_evaluate_integer(ds->handle, "_STA", NULL, &sta);
if (ACPI_SUCCESS(status) && sta)
return 1;
}
return 0;
}
/**
* dock_create_acpi_device - add new devices to acpi
* @handle - handle of the device to add
*
* This function will create a new acpi_device for the given
* handle if one does not exist already. This should cause
* acpi to scan for drivers for the given devices, and call
* matching driver's add routine.
*
* Returns a pointer to the acpi_device corresponding to the handle.
*/
static struct acpi_device * dock_create_acpi_device(acpi_handle handle)
{
struct acpi_device *device;
struct acpi_device *parent_device;
acpi_handle parent;
int ret;
if (acpi_bus_get_device(handle, &device)) {
/*
* no device created for this object,
* so we should create one.
*/
acpi_get_parent(handle, &parent);
if (acpi_bus_get_device(parent, &parent_device))
parent_device = NULL;
ret = acpi_bus_add(&device, parent_device, handle,
ACPI_BUS_TYPE_DEVICE);
if (ret) {
pr_debug("error adding bus, %x\n", -ret);
return NULL;
}
}
return device;
}
/**
* dock_remove_acpi_device - remove the acpi_device struct from acpi
* @handle - the handle of the device to remove
*
* Tell acpi to remove the acpi_device. This should cause any loaded
* driver to have it's remove routine called.
*/
static void dock_remove_acpi_device(acpi_handle handle)
{
struct acpi_device *device;
int ret;
if (!acpi_bus_get_device(handle, &device)) {
ret = acpi_bus_trim(device, 1);
if (ret)
pr_debug("error removing bus, %x\n", -ret);
}
}
/**
* hotplug_dock_devices - insert or remove devices on the dock station
* @ds: the dock station
* @event: either bus check or eject request
*
* Some devices on the dock station need to have drivers called
* to perform hotplug operations after a dock event has occurred.
* Traverse the list of dock devices that have registered a
* hotplug handler, and call the handler.
*/
static void hotplug_dock_devices(struct dock_station *ds, u32 event)
{
struct dock_dependent_device *dd;
mutex_lock(&ds->hp_lock);
/*
* First call driver specific hotplug functions
*/
list_for_each_entry(dd, &ds->hotplug_devices, hotplug_list)
if (dd->ops && dd->ops->handler)
dd->ops->handler(dd->handle, event, dd->context);
/*
* Now make sure that an acpi_device is created for each
* dependent device, or removed if this is an eject request.
* This will cause acpi_drivers to be stopped/started if they
* exist
*/
list_for_each_entry(dd, &ds->dependent_devices, list) {
if (event == ACPI_NOTIFY_EJECT_REQUEST)
dock_remove_acpi_device(dd->handle);
else
dock_create_acpi_device(dd->handle);
}
mutex_unlock(&ds->hp_lock);
}
static void dock_event(struct dock_station *ds, u32 event, int num)
{
struct device *dev = &ds->dock_device->dev;
char event_string[13];
char *envp[] = { event_string, NULL };
struct dock_dependent_device *dd;
if (num == UNDOCK_EVENT)
sprintf(event_string, "EVENT=undock");
else
sprintf(event_string, "EVENT=dock");
/*
* Indicate that the status of the dock station has
* changed.
*/
if (num == DOCK_EVENT)
kobject_uevent_env(&dev->kobj, KOBJ_CHANGE, envp);
list_for_each_entry(dd, &ds->hotplug_devices, hotplug_list)
if (dd->ops && dd->ops->uevent)
dd->ops->uevent(dd->handle, event, dd->context);
if (num != DOCK_EVENT)
kobject_uevent_env(&dev->kobj, KOBJ_CHANGE, envp);
}
/**
* eject_dock - respond to a dock eject request
* @ds: the dock station
*
* This is called after _DCK is called, to execute the dock station's
* _EJ0 method.
*/
static void eject_dock(struct dock_station *ds)
{
struct acpi_object_list arg_list;
union acpi_object arg;
acpi_status status;
acpi_handle tmp;
/* all dock devices should have _EJ0, but check anyway */
status = acpi_get_handle(ds->handle, "_EJ0", &tmp);
if (ACPI_FAILURE(status)) {
pr_debug("No _EJ0 support for dock device\n");
return;
}
arg_list.count = 1;
arg_list.pointer = &arg;
arg.type = ACPI_TYPE_INTEGER;
arg.integer.value = 1;
status = acpi_evaluate_object(ds->handle, "_EJ0", &arg_list, NULL);
if (ACPI_FAILURE(status))
pr_debug("Failed to evaluate _EJ0!\n");
}
/**
* handle_dock - handle a dock event
* @ds: the dock station
* @dock: to dock, or undock - that is the question
*
* Execute the _DCK method in response to an acpi event
*/
static void handle_dock(struct dock_station *ds, int dock)
{
acpi_status status;
struct acpi_object_list arg_list;
union acpi_object arg;
struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
struct acpi_buffer name_buffer = { ACPI_ALLOCATE_BUFFER, NULL };
acpi_get_name(ds->handle, ACPI_FULL_PATHNAME, &name_buffer);
printk(KERN_INFO PREFIX "%s - %s\n",
(char *)name_buffer.pointer, dock ? "docking" : "undocking");
/* _DCK method has one argument */
arg_list.count = 1;
arg_list.pointer = &arg;
arg.type = ACPI_TYPE_INTEGER;
arg.integer.value = dock;
status = acpi_evaluate_object(ds->handle, "_DCK", &arg_list, &buffer);
if (ACPI_FAILURE(status) && status != AE_NOT_FOUND)
ACPI_EXCEPTION((AE_INFO, status, "%s - failed to execute"
" _DCK\n", (char *)name_buffer.pointer));
kfree(buffer.pointer);
kfree(name_buffer.pointer);
}
static inline void dock(struct dock_station *ds)
{
handle_dock(ds, 1);
}
static inline void undock(struct dock_station *ds)
{
handle_dock(ds, 0);
}
static inline void begin_dock(struct dock_station *ds)
{
ds->flags |= DOCK_DOCKING;
}
static inline void complete_dock(struct dock_station *ds)
{
ds->flags &= ~(DOCK_DOCKING);
ds->last_dock_time = jiffies;
}
static inline void begin_undock(struct dock_station *ds)
{
ds->flags |= DOCK_UNDOCKING;
}
static inline void complete_undock(struct dock_station *ds)
{
ds->flags &= ~(DOCK_UNDOCKING);
}
static void dock_lock(struct dock_station *ds, int lock)
{
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 = !!lock;
status = acpi_evaluate_object(ds->handle, "_LCK", &arg_list, NULL);
if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
if (lock)
printk(KERN_WARNING PREFIX "Locking device failed\n");
else
printk(KERN_WARNING PREFIX "Unlocking device failed\n");
}
}
/**
* dock_in_progress - see if we are in the middle of handling a dock event
* @ds: the dock station
*
* Sometimes while docking, false dock events can be sent to the driver
* because good connections aren't made or some other reason. Ignore these
* if we are in the middle of doing something.
*/
static int dock_in_progress(struct dock_station *ds)
{
if ((ds->flags & DOCK_DOCKING) ||
time_before(jiffies, (ds->last_dock_time + HZ)))
return 1;
return 0;
}
/**
* register_dock_notifier - add yourself to the dock notifier list
* @nb: the callers notifier block
*
* If a driver wishes to be notified about dock events, they can
* use this function to put a notifier block on the dock notifier list.
* this notifier call chain will be called after a dock event, but
* before hotplugging any new devices.
*/
int register_dock_notifier(struct notifier_block *nb)
{
if (!dock_station_count)
return -ENODEV;
return atomic_notifier_chain_register(&dock_notifier_list, nb);
}
EXPORT_SYMBOL_GPL(register_dock_notifier);
/**
* unregister_dock_notifier - remove yourself from the dock notifier list
* @nb: the callers notifier block
*/
void unregister_dock_notifier(struct notifier_block *nb)
{
if (!dock_station_count)
return;
atomic_notifier_chain_unregister(&dock_notifier_list, nb);
}
EXPORT_SYMBOL_GPL(unregister_dock_notifier);
/**
* register_hotplug_dock_device - register a hotplug function
* @handle: the handle of the device
* @ops: handlers to call after docking
* @context: device specific data
*
* If a driver would like to perform a hotplug operation after a dock
* event, they can register an acpi_notifiy_handler to be called by
* the dock driver after _DCK is executed.
*/
int
register_hotplug_dock_device(acpi_handle handle, const struct acpi_dock_ops *ops,
void *context)
{
struct dock_dependent_device *dd;
struct dock_station *dock_station;
int ret = -EINVAL;
if (!dock_station_count)
return -ENODEV;
/*
* make sure this handle is for a device dependent on the dock,
* this would include the dock station itself
*/
list_for_each_entry(dock_station, &dock_stations, sibling) {
/*
* An ATA bay can be in a dock and itself can be ejected
* separately, so there are two 'dock stations' which need the
* ops
*/
dd = find_dock_dependent_device(dock_station, handle);
if (dd) {
dd->ops = ops;
dd->context = context;
dock_add_hotplug_device(dock_station, dd);
ret = 0;
}
}
return ret;
}
EXPORT_SYMBOL_GPL(register_hotplug_dock_device);
/**
* unregister_hotplug_dock_device - remove yourself from the hotplug list
* @handle: the acpi handle of the device
*/
void unregister_hotplug_dock_device(acpi_handle handle)
{
struct dock_dependent_device *dd;
struct dock_station *dock_station;
if (!dock_station_count)
return;
list_for_each_entry(dock_station, &dock_stations, sibling) {
dd = find_dock_dependent_device(dock_station, handle);
if (dd)
dock_del_hotplug_device(dock_station, dd);
}
}
EXPORT_SYMBOL_GPL(unregister_hotplug_dock_device);
/**
* handle_eject_request - handle an undock request checking for error conditions
*
* Check to make sure the dock device is still present, then undock and
* hotremove all the devices that may need removing.
*/
static int handle_eject_request(struct dock_station *ds, u32 event)
{
if (dock_in_progress(ds))
return -EBUSY;
/*
* here we need to generate the undock
* event prior to actually doing the undock
* so that the device struct still exists.
* Also, even send the dock event if the
* device is not present anymore
*/
dock_event(ds, event, UNDOCK_EVENT);
hotplug_dock_devices(ds, ACPI_NOTIFY_EJECT_REQUEST);
undock(ds);
dock_lock(ds, 0);
eject_dock(ds);
if (dock_present(ds)) {
printk(KERN_ERR PREFIX "Unable to undock!\n");
return -EBUSY;
}
complete_undock(ds);
return 0;
}
/**
* dock_notify - act upon an acpi dock notification
* @handle: the dock station handle
* @event: the acpi event
* @data: our driver data struct
*
* If we are notified to dock, then check to see if the dock is
* present and then dock. Notify all drivers of the dock event,
* and then hotplug and devices that may need hotplugging.
*/
static void dock_notify(acpi_handle handle, u32 event, void *data)
{
struct dock_station *ds = data;
struct acpi_device *tmp;
int surprise_removal = 0;
/*
* According to acpi spec 3.0a, if a DEVICE_CHECK notification
* is sent and _DCK is present, it is assumed to mean an undock
* request.
*/
if ((ds->flags & DOCK_IS_DOCK) && event == ACPI_NOTIFY_DEVICE_CHECK)
event = ACPI_NOTIFY_EJECT_REQUEST;
/*
* dock station: BUS_CHECK - docked or surprise removal
* DEVICE_CHECK - undocked
* other device: BUS_CHECK/DEVICE_CHECK - added or surprise removal
*
* To simplify event handling, dock dependent device handler always
* get ACPI_NOTIFY_BUS_CHECK/ACPI_NOTIFY_DEVICE_CHECK for add and
* ACPI_NOTIFY_EJECT_REQUEST for removal
*/
switch (event) {
case ACPI_NOTIFY_BUS_CHECK:
case ACPI_NOTIFY_DEVICE_CHECK:
if (!dock_in_progress(ds) && acpi_bus_get_device(ds->handle,
&tmp)) {
begin_dock(ds);
dock(ds);
if (!dock_present(ds)) {
printk(KERN_ERR PREFIX "Unable to dock!\n");
complete_dock(ds);
break;
}
atomic_notifier_call_chain(&dock_notifier_list,
event, NULL);
hotplug_dock_devices(ds, event);
complete_dock(ds);
dock_event(ds, event, DOCK_EVENT);
dock_lock(ds, 1);
acpi_update_all_gpes();
break;
}
if (dock_present(ds) || dock_in_progress(ds))
break;
/* This is a surprise removal */
surprise_removal = 1;
event = ACPI_NOTIFY_EJECT_REQUEST;
/* Fall back */
case ACPI_NOTIFY_EJECT_REQUEST:
begin_undock(ds);
if ((immediate_undock && !(ds->flags & DOCK_IS_ATA))
|| surprise_removal)
handle_eject_request(ds, event);
else
dock_event(ds, event, UNDOCK_EVENT);
break;
default:
printk(KERN_ERR PREFIX "Unknown dock event %d\n", event);
}
}
struct dock_data {
acpi_handle handle;
unsigned long event;
struct dock_station *ds;
};
static void acpi_dock_deferred_cb(void *context)
{
struct dock_data *data = context;
dock_notify(data->handle, data->event, data->ds);
kfree(data);
}
static int acpi_dock_notifier_call(struct notifier_block *this,
unsigned long event, void *data)
{
struct dock_station *dock_station;
acpi_handle handle = data;
if (event != ACPI_NOTIFY_BUS_CHECK && event != ACPI_NOTIFY_DEVICE_CHECK
&& event != ACPI_NOTIFY_EJECT_REQUEST)
return 0;
list_for_each_entry(dock_station, &dock_stations, sibling) {
if (dock_station->handle == handle) {
struct dock_data *dd;
dd = kmalloc(sizeof(*dd), GFP_KERNEL);
if (!dd)
return 0;
dd->handle = handle;
dd->event = event;
dd->ds = dock_station;
acpi_os_hotplug_execute(acpi_dock_deferred_cb, dd);
return 0 ;
}
}
return 0;
}
static struct notifier_block dock_acpi_notifier = {
.notifier_call = acpi_dock_notifier_call,
};
/**
* find_dock_devices - find devices on the dock station
* @handle: the handle of the device we are examining
* @lvl: unused
* @context: the dock station private data
* @rv: unused
*
* This function is called by acpi_walk_namespace. It will
* check to see if an object has an _EJD method. If it does, then it
* will see if it is dependent on the dock station.
*/
static acpi_status
find_dock_devices(acpi_handle handle, u32 lvl, void *context, void **rv)
{
acpi_status status;
acpi_handle tmp, parent;
struct dock_station *ds = context;
status = acpi_bus_get_ejd(handle, &tmp);
if (ACPI_FAILURE(status)) {
/* try the parent device as well */
status = acpi_get_parent(handle, &parent);
if (ACPI_FAILURE(status))
goto fdd_out;
/* see if parent is dependent on dock */
status = acpi_bus_get_ejd(parent, &tmp);
if (ACPI_FAILURE(status))
goto fdd_out;
}
if (tmp == ds->handle)
add_dock_dependent_device(ds, handle);
fdd_out:
return AE_OK;
}
/*
* show_docked - read method for "docked" file in sysfs
*/
static ssize_t show_docked(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct acpi_device *tmp;
struct dock_station *dock_station = dev->platform_data;
if (ACPI_SUCCESS(acpi_bus_get_device(dock_station->handle, &tmp)))
return snprintf(buf, PAGE_SIZE, "1\n");
return snprintf(buf, PAGE_SIZE, "0\n");
}
static DEVICE_ATTR(docked, S_IRUGO, show_docked, NULL);
/*
* show_flags - read method for flags file in sysfs
*/
static ssize_t show_flags(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct dock_station *dock_station = dev->platform_data;
return snprintf(buf, PAGE_SIZE, "%d\n", dock_station->flags);
}
static DEVICE_ATTR(flags, S_IRUGO, show_flags, NULL);
/*
* write_undock - write method for "undock" file in sysfs
*/
static ssize_t write_undock(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
int ret;
struct dock_station *dock_station = dev->platform_data;
if (!count)
return -EINVAL;
begin_undock(dock_station);
ret = handle_eject_request(dock_station, ACPI_NOTIFY_EJECT_REQUEST);
return ret ? ret: count;
}
static DEVICE_ATTR(undock, S_IWUSR, NULL, write_undock);
/*
* show_dock_uid - read method for "uid" file in sysfs
*/
static ssize_t show_dock_uid(struct device *dev,
struct device_attribute *attr, char *buf)
{
unsigned long long lbuf;
struct dock_station *dock_station = dev->platform_data;
acpi_status status = acpi_evaluate_integer(dock_station->handle,
"_UID", NULL, &lbuf);
if (ACPI_FAILURE(status))
return 0;
return snprintf(buf, PAGE_SIZE, "%llx\n", lbuf);
}
static DEVICE_ATTR(uid, S_IRUGO, show_dock_uid, NULL);
static ssize_t show_dock_type(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct dock_station *dock_station = dev->platform_data;
char *type;
if (dock_station->flags & DOCK_IS_DOCK)
type = "dock_station";
else if (dock_station->flags & DOCK_IS_ATA)
type = "ata_bay";
else if (dock_station->flags & DOCK_IS_BAT)
type = "battery_bay";
else
type = "unknown";
return snprintf(buf, PAGE_SIZE, "%s\n", type);
}
static DEVICE_ATTR(type, S_IRUGO, show_dock_type, NULL);
static struct attribute *dock_attributes[] = {
&dev_attr_docked.attr,
&dev_attr_flags.attr,
&dev_attr_undock.attr,
&dev_attr_uid.attr,
&dev_attr_type.attr,
NULL
};
static struct attribute_group dock_attribute_group = {
.attrs = dock_attributes
};
/**
* dock_add - add a new dock station
* @handle: the dock station handle
*
* allocated and initialize a new dock station device. Find all devices
* that are on the dock station, and register for dock event notifications.
*/
static int __init dock_add(acpi_handle handle)
{
int ret, id;
struct dock_station ds, *dock_station;
struct platform_device *dd;
id = dock_station_count;
memset(&ds, 0, sizeof(ds));
dd = platform_device_register_data(NULL, "dock", id, &ds, sizeof(ds));
if (IS_ERR(dd))
return PTR_ERR(dd);
dock_station = dd->dev.platform_data;
dock_station->handle = handle;
dock_station->dock_device = dd;
dock_station->last_dock_time = jiffies - HZ;
mutex_init(&dock_station->hp_lock);
spin_lock_init(&dock_station->dd_lock);
INIT_LIST_HEAD(&dock_station->sibling);
INIT_LIST_HEAD(&dock_station->hotplug_devices);
ATOMIC_INIT_NOTIFIER_HEAD(&dock_notifier_list);
INIT_LIST_HEAD(&dock_station->dependent_devices);
/* we want the dock device to send uevents */
dev_set_uevent_suppress(&dd->dev, 0);
if (is_dock(handle))
dock_station->flags |= DOCK_IS_DOCK;
if (is_ata(handle))
dock_station->flags |= DOCK_IS_ATA;
if (is_battery(handle))
dock_station->flags |= DOCK_IS_BAT;
ret = sysfs_create_group(&dd->dev.kobj, &dock_attribute_group);
if (ret)
goto err_unregister;
/* Find dependent devices */
acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
ACPI_UINT32_MAX, find_dock_devices, NULL,
dock_station, NULL);
/* add the dock station as a device dependent on itself */
ret = add_dock_dependent_device(dock_station, handle);
if (ret)
goto err_rmgroup;
dock_station_count++;
list_add(&dock_station->sibling, &dock_stations);
return 0;
err_rmgroup:
sysfs_remove_group(&dd->dev.kobj, &dock_attribute_group);
err_unregister:
platform_device_unregister(dd);
printk(KERN_ERR "%s encountered error %d\n", __func__, ret);
return ret;
}
/**
* dock_remove - free up resources related to the dock station
*/
static int dock_remove(struct dock_station *ds)
{
struct dock_dependent_device *dd, *tmp;
struct platform_device *dock_device = ds->dock_device;
if (!dock_station_count)
return 0;
/* remove dependent devices */
list_for_each_entry_safe(dd, tmp, &ds->dependent_devices, list)
kfree(dd);
list_del(&ds->sibling);
/* cleanup sysfs */
sysfs_remove_group(&dock_device->dev.kobj, &dock_attribute_group);
platform_device_unregister(dock_device);
return 0;
}
/**
* find_dock - look for a dock station
* @handle: acpi handle of a device
* @lvl: unused
* @context: counter of dock stations found
* @rv: unused
*
* This is called by acpi_walk_namespace to look for dock stations.
*/
static __init acpi_status
find_dock(acpi_handle handle, u32 lvl, void *context, void **rv)
{
if (is_dock(handle))
dock_add(handle);
return AE_OK;
}
static __init acpi_status
find_bay(acpi_handle handle, u32 lvl, void *context, void **rv)
{
/* If bay is a dock, it's already handled */
if (is_ejectable_bay(handle) && !is_dock(handle))
dock_add(handle);
return AE_OK;
}
static int __init dock_init(void)
{
if (acpi_disabled)
return 0;
/* look for a dock station */
acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
ACPI_UINT32_MAX, find_dock, NULL, NULL, NULL);
/* look for bay */
acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
ACPI_UINT32_MAX, find_bay, NULL, NULL, NULL);
if (!dock_station_count) {
printk(KERN_INFO PREFIX "No dock devices found.\n");
return 0;
}
register_acpi_bus_notifier(&dock_acpi_notifier);
printk(KERN_INFO PREFIX "%s: %d docks/bays found\n",
ACPI_DOCK_DRIVER_DESCRIPTION, dock_station_count);
return 0;
}
static void __exit dock_exit(void)
{
struct dock_station *tmp, *dock_station;
unregister_acpi_bus_notifier(&dock_acpi_notifier);
list_for_each_entry_safe(dock_station, tmp, &dock_stations, sibling)
dock_remove(dock_station);
}
/*
* Must be called before drivers of devices in dock, otherwise we can't know
* which devices are in a dock
*/
subsys_initcall(dock_init);
module_exit(dock_exit);
| gpl-2.0 |
Abhinav1997/android_kernel_lge_msm8226 | drivers/staging/rts5139/ms_mg.c | 5071 | 16845 | /* Driver for Realtek RTS51xx USB card reader
*
* Copyright(c) 2009 Realtek Semiconductor 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, 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/>.
*
* Author:
* wwang (wei_wang@realsil.com.cn)
* No. 450, Shenhu Road, Suzhou Industry Park, Suzhou, China
* Maintainer:
* Edwin Rong (edwin_rong@realsil.com.cn)
* No. 450, Shenhu Road, Suzhou Industry Park, Suzhou, China
*/
#include <linux/blkdev.h>
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include "debug.h"
#include "trace.h"
#include "rts51x.h"
#include "rts51x_transport.h"
#include "rts51x_scsi.h"
#include "rts51x_card.h"
#include "ms.h"
#ifdef SUPPORT_MAGIC_GATE
int mg_check_int_error(struct rts51x_chip *chip)
{
u8 value;
rts51x_read_register(chip, MS_TRANS_CFG, &value);
if (value & (INT_ERR | INT_CMDNK))
TRACE_RET(chip, STATUS_FAIL);
return STATUS_SUCCESS;
}
static int mg_send_ex_cmd(struct rts51x_chip *chip, u8 cmd, u8 entry_num)
{
int retval, i;
u8 data[8];
data[0] = cmd;
data[1] = 0;
data[2] = 0;
data[3] = 0;
data[4] = 0;
data[5] = 0;
data[6] = entry_num;
data[7] = 0;
for (i = 0; i < MS_MAX_RETRY_COUNT; i++) {
retval =
ms_write_bytes(chip, PRO_EX_SET_CMD, 7, WAIT_INT, data, 8);
if (retval == STATUS_SUCCESS)
break;
}
if (i == MS_MAX_RETRY_COUNT)
TRACE_RET(chip, STATUS_FAIL);
retval = mg_check_int_error(chip);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, STATUS_FAIL);
return STATUS_SUCCESS;
}
int mg_set_tpc_para_sub(struct rts51x_chip *chip, int type, u8 mg_entry_num)
{
int retval;
u8 buf[6];
RTS51X_DEBUGP("--%s--\n", __func__);
if (type == 0)
retval = ms_set_rw_reg_addr(chip, 0, 0, Pro_TPCParm, 1);
else
retval = ms_set_rw_reg_addr(chip, 0, 0, Pro_DataCount1, 6);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, retval);
buf[0] = 0;
buf[1] = 0;
if (type == 1) {
buf[2] = 0;
buf[3] = 0;
buf[4] = 0;
buf[5] = mg_entry_num;
}
retval =
ms_write_bytes(chip, PRO_WRITE_REG, (type == 0) ? 1 : 6,
NO_WAIT_INT, buf, 6);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, retval);
return STATUS_SUCCESS;
}
/**
* Get MagciGate ID and set Leaf ID to medium.
* After receiving this SCSI command, adapter shall fulfill 2 tasks
* below in order:
* 1. send GET_ID TPC command to get MagicGate ID and hold it till
* Response&challenge CMD.
* 2. send SET_ID TPC command to medium with Leaf ID released by host
* in this SCSI CMD.
*/
int mg_set_leaf_id(struct scsi_cmnd *srb, struct rts51x_chip *chip)
{
int retval;
int i;
unsigned int lun = SCSI_LUN(srb);
u8 buf1[32], buf2[12];
RTS51X_DEBUGP("--%s--\n", __func__);
if (scsi_bufflen(srb) < 12) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_INVALID_CMD_FIELD);
TRACE_RET(chip, STATUS_FAIL);
}
ms_cleanup_work(chip);
retval = ms_switch_clock(chip);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, retval);
retval = mg_send_ex_cmd(chip, MG_SET_LID, 0);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_KEY_FAIL_NOT_ESTAB);
TRACE_RET(chip, retval);
}
memset(buf1, 0, 32);
rts51x_get_xfer_buf(buf2, min(12, (int)scsi_bufflen(srb)), srb);
for (i = 0; i < 8; i++)
buf1[8 + i] = buf2[4 + i];
retval =
ms_write_bytes(chip, PRO_WRITE_SHORT_DATA, 32, WAIT_INT, buf1, 32);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_KEY_FAIL_NOT_ESTAB);
TRACE_RET(chip, retval);
}
retval = mg_check_int_error(chip);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_KEY_FAIL_NOT_ESTAB);
TRACE_RET(chip, retval);
}
return STATUS_SUCCESS;
}
/**
* Send Local EKB to host.
* After receiving this SCSI command, adapter shall read the divided
* data(1536 bytes totally) from medium by using READ_LONG_DATA TPC
* for 3 times, and report data to host with data-length is 1052 bytes.
*/
int mg_get_local_EKB(struct scsi_cmnd *srb, struct rts51x_chip *chip)
{
int retval = STATUS_FAIL;
int bufflen;
unsigned int lun = SCSI_LUN(srb);
u8 *buf = NULL;
RTS51X_DEBUGP("--%s--\n", __func__);
ms_cleanup_work(chip);
retval = ms_switch_clock(chip);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, retval);
buf = kmalloc(1540, GFP_KERNEL);
if (!buf)
TRACE_RET(chip, STATUS_NOMEM);
buf[0] = 0x04;
buf[1] = 0x1A;
buf[2] = 0x00;
buf[3] = 0x00;
retval = mg_send_ex_cmd(chip, MG_GET_LEKB, 0);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_KEY_FAIL_NOT_AUTHEN);
TRACE_GOTO(chip, GetEKBFinish);
}
retval = ms_transfer_data(chip, MS_TM_AUTO_READ, PRO_READ_LONG_DATA,
3, WAIT_INT, 0, 0, buf + 4, 1536);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_KEY_FAIL_NOT_AUTHEN);
rts51x_write_register(chip, CARD_STOP, MS_STOP | MS_CLR_ERR,
MS_STOP | MS_CLR_ERR);
TRACE_GOTO(chip, GetEKBFinish);
}
retval = mg_check_int_error(chip);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_KEY_FAIL_NOT_AUTHEN);
TRACE_GOTO(chip, GetEKBFinish);
}
bufflen = min(1052, (int)scsi_bufflen(srb));
rts51x_set_xfer_buf(buf, bufflen, srb);
GetEKBFinish:
kfree(buf);
return retval;
}
/**
* Send challenge(host) to medium.
* After receiving this SCSI command, adapter shall sequentially issues
* TPC commands to the medium for writing 8-bytes data as challenge
* by host within a short data packet.
*/
int mg_chg(struct scsi_cmnd *srb, struct rts51x_chip *chip)
{
struct ms_info *ms_card = &(chip->ms_card);
int retval;
int bufflen;
int i;
unsigned int lun = SCSI_LUN(srb);
u8 buf[32], tmp;
RTS51X_DEBUGP("--%s--\n", __func__);
ms_cleanup_work(chip);
retval = ms_switch_clock(chip);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, retval);
retval = mg_send_ex_cmd(chip, MG_GET_ID, 0);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_INCOMPATIBLE_MEDIUM);
TRACE_RET(chip, retval);
}
retval =
ms_read_bytes(chip, PRO_READ_SHORT_DATA, 32, WAIT_INT, buf, 32);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_INCOMPATIBLE_MEDIUM);
TRACE_RET(chip, retval);
}
retval = mg_check_int_error(chip);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_INCOMPATIBLE_MEDIUM);
TRACE_RET(chip, retval);
}
memcpy(ms_card->magic_gate_id, buf, 16);
for (i = 0; i < 2500; i++) {
RTS51X_READ_REG(chip, MS_TRANS_CFG, &tmp);
if (tmp &
(MS_INT_CED | MS_INT_CMDNK | MS_INT_BREQ | MS_INT_ERR))
break;
wait_timeout(1);
}
if (i == 2500) {
set_sense_type(chip, lun, SENSE_TYPE_MG_INCOMPATIBLE_MEDIUM);
TRACE_RET(chip, STATUS_FAIL);
}
retval = mg_send_ex_cmd(chip, MG_SET_RD, 0);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_INCOMPATIBLE_MEDIUM);
TRACE_RET(chip, retval);
}
bufflen = min(12, (int)scsi_bufflen(srb));
rts51x_get_xfer_buf(buf, bufflen, srb);
for (i = 0; i < 8; i++)
buf[i] = buf[4 + i];
for (i = 0; i < 24; i++)
buf[8 + i] = 0;
retval =
ms_write_bytes(chip, PRO_WRITE_SHORT_DATA, 32, WAIT_INT, buf, 32);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_INCOMPATIBLE_MEDIUM);
TRACE_RET(chip, retval);
}
retval = mg_check_int_error(chip);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_INCOMPATIBLE_MEDIUM);
TRACE_RET(chip, retval);
}
ms_card->mg_auth = 0;
return STATUS_SUCCESS;
}
/**
* Send Response and Challenge data to host.
* After receiving this SCSI command, adapter shall communicates with
* the medium, get parameters(HRd, Rms, MagicGateID) by using READ_SHORT_DATA
* TPC and send the data to host according to certain format required by
* MG-R specification.
* The paremeter MagicGateID is the one that adapter has obtained from
* the medium by TPC commands in Set Leaf ID command phase previously.
*/
int mg_get_rsp_chg(struct scsi_cmnd *srb, struct rts51x_chip *chip)
{
struct ms_info *ms_card = &(chip->ms_card);
int retval, i;
int bufflen;
unsigned int lun = SCSI_LUN(srb);
u8 buf1[32], buf2[36], tmp;
RTS51X_DEBUGP("--%s--\n", __func__);
ms_cleanup_work(chip);
retval = ms_switch_clock(chip);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, retval);
retval = mg_send_ex_cmd(chip, MG_MAKE_RMS, 0);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_KEY_FAIL_NOT_AUTHEN);
TRACE_RET(chip, retval);
}
retval =
ms_read_bytes(chip, PRO_READ_SHORT_DATA, 32, WAIT_INT, buf1, 32);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_KEY_FAIL_NOT_AUTHEN);
TRACE_RET(chip, retval);
}
retval = mg_check_int_error(chip);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_KEY_FAIL_NOT_AUTHEN);
TRACE_RET(chip, retval);
}
buf2[0] = 0x00;
buf2[1] = 0x22;
buf2[2] = 0x00;
buf2[3] = 0x00;
memcpy(buf2 + 4, ms_card->magic_gate_id, 16);
memcpy(buf2 + 20, buf1, 16);
bufflen = min(36, (int)scsi_bufflen(srb));
rts51x_set_xfer_buf(buf2, bufflen, srb);
for (i = 0; i < 2500; i++) {
RTS51X_READ_REG(chip, MS_TRANS_CFG, &tmp);
if (tmp & (MS_INT_CED | MS_INT_CMDNK |
MS_INT_BREQ | MS_INT_ERR))
break;
wait_timeout(1);
}
if (i == 2500) {
set_sense_type(chip, lun, SENSE_TYPE_MG_KEY_FAIL_NOT_AUTHEN);
TRACE_RET(chip, STATUS_FAIL);
}
return STATUS_SUCCESS;
}
/**
* Send response(host) to medium.
* After receiving this SCSI command, adapter shall sequentially
* issues TPC commands to the medium for writing 8-bytes data as
* challenge by host within a short data packet.
*/
int mg_rsp(struct scsi_cmnd *srb, struct rts51x_chip *chip)
{
struct ms_info *ms_card = &(chip->ms_card);
int retval;
int i;
int bufflen;
unsigned int lun = SCSI_LUN(srb);
u8 buf[32];
RTS51X_DEBUGP("--%s--\n", __func__);
ms_cleanup_work(chip);
retval = ms_switch_clock(chip);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, retval);
retval = mg_send_ex_cmd(chip, MG_MAKE_KSE, 0);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_KEY_FAIL_NOT_AUTHEN);
TRACE_RET(chip, retval);
}
bufflen = min(12, (int)scsi_bufflen(srb));
rts51x_get_xfer_buf(buf, bufflen, srb);
for (i = 0; i < 8; i++)
buf[i] = buf[4 + i];
for (i = 0; i < 24; i++)
buf[8 + i] = 0;
retval =
ms_write_bytes(chip, PRO_WRITE_SHORT_DATA, 32, WAIT_INT, buf, 32);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_KEY_FAIL_NOT_AUTHEN);
TRACE_RET(chip, retval);
}
retval = mg_check_int_error(chip);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_KEY_FAIL_NOT_AUTHEN);
TRACE_RET(chip, retval);
}
ms_card->mg_auth = 1;
return STATUS_SUCCESS;
}
/** * Send ICV data to host.
* After receiving this SCSI command, adapter shall read the divided
* data(1024 bytes totally) from medium by using READ_LONG_DATA TPC
* for 2 times, and report data to host with data-length is 1028 bytes.
*
* Since the extra 4 bytes data is just only a prefix to original data
* that read from medium, so that the 4-byte data pushed into Ring buffer
* precedes data tramsinssion from medium to Ring buffer by DMA mechanisim
* in order to get maximum performance and minimum code size simultaneously.
*/
int mg_get_ICV(struct scsi_cmnd *srb, struct rts51x_chip *chip)
{
struct ms_info *ms_card = &(chip->ms_card);
int retval;
int bufflen;
unsigned int lun = SCSI_LUN(srb);
u8 *buf = NULL;
RTS51X_DEBUGP("--%s--\n", __func__);
ms_cleanup_work(chip);
retval = ms_switch_clock(chip);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, retval);
buf = kmalloc(1028, GFP_KERNEL);
if (!buf)
TRACE_RET(chip, STATUS_NOMEM);
buf[0] = 0x04;
buf[1] = 0x02;
buf[2] = 0x00;
buf[3] = 0x00;
retval = mg_send_ex_cmd(chip, MG_GET_IBD, ms_card->mg_entry_num);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
TRACE_GOTO(chip, GetICVFinish);
}
retval = ms_transfer_data(chip, MS_TM_AUTO_READ, PRO_READ_LONG_DATA,
2, WAIT_INT, 0, 0, buf + 4, 1024);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
rts51x_write_register(chip, CARD_STOP, MS_STOP | MS_CLR_ERR,
MS_STOP | MS_CLR_ERR);
TRACE_GOTO(chip, GetICVFinish);
}
retval = mg_check_int_error(chip);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MEDIA_UNRECOVER_READ_ERR);
TRACE_GOTO(chip, GetICVFinish);
}
bufflen = min(1028, (int)scsi_bufflen(srb));
rts51x_set_xfer_buf(buf, bufflen, srb);
GetICVFinish:
kfree(buf);
return retval;
}
/**
* Send ICV data to medium.
* After receiving this SCSI command, adapter shall receive 1028 bytes
* and write the later 1024 bytes to medium by WRITE_LONG_DATA TPC
* consecutively.
*
* Since the first 4-bytes data is just only a prefix to original data
* that sent by host, and it should be skipped by shifting DMA pointer
* before writing 1024 bytes to medium.
*/
int mg_set_ICV(struct scsi_cmnd *srb, struct rts51x_chip *chip)
{
struct ms_info *ms_card = &(chip->ms_card);
int retval;
int bufflen;
#ifdef MG_SET_ICV_SLOW
int i;
#endif
unsigned int lun = SCSI_LUN(srb);
u8 *buf = NULL;
RTS51X_DEBUGP("--%s--\n", __func__);
ms_cleanup_work(chip);
retval = ms_switch_clock(chip);
if (retval != STATUS_SUCCESS)
TRACE_RET(chip, retval);
buf = kmalloc(1028, GFP_KERNEL);
if (!buf)
TRACE_RET(chip, STATUS_NOMEM);
bufflen = min(1028, (int)scsi_bufflen(srb));
rts51x_get_xfer_buf(buf, bufflen, srb);
retval = mg_send_ex_cmd(chip, MG_SET_IBD, ms_card->mg_entry_num);
if (retval != STATUS_SUCCESS) {
if (ms_card->mg_auth == 0) {
if ((buf[5] & 0xC0) != 0)
set_sense_type(chip, lun,
SENSE_TYPE_MG_KEY_FAIL_NOT_ESTAB);
else
set_sense_type(chip, lun,
SENSE_TYPE_MG_WRITE_ERR);
} else {
set_sense_type(chip, lun, SENSE_TYPE_MG_WRITE_ERR);
}
TRACE_GOTO(chip, SetICVFinish);
}
#ifdef MG_SET_ICV_SLOW
for (i = 0; i < 2; i++) {
udelay(50);
rts51x_init_cmd(chip);
rts51x_add_cmd(chip, WRITE_REG_CMD, MS_TPC, 0xFF,
PRO_WRITE_LONG_DATA);
rts51x_add_cmd(chip, WRITE_REG_CMD, MS_TRANS_CFG, 0xFF,
WAIT_INT);
trans_dma_enable(DMA_TO_DEVICE, chip, 512, DMA_512);
rts51x_add_cmd(chip, WRITE_REG_CMD, MS_TRANSFER, 0xFF,
MS_TRANSFER_START | MS_TM_NORMAL_WRITE);
rts51x_add_cmd(chip, CHECK_REG_CMD, MS_TRANSFER,
MS_TRANSFER_END, MS_TRANSFER_END);
retval = rts51x_send_cmd(chip, MODE_CDOR, 100);
if (retval != STATUS_SUCCESS) {
set_sense_type(chip, lun, SENSE_TYPE_MG_WRITE_ERR);
TRACE_GOTO(chip, SetICVFinish);
}
retval = rts51x_transfer_data_rcc(chip, SND_BULK_PIPE(chip),
buf + 4 + i * 512, 512, 0,
NULL, 3000, STAGE_DO);
if (retval != STATUS_SUCCESS) {
rts51x_clear_ms_error(chip);
if (ms_card->mg_auth == 0) {
if ((buf[5] & 0xC0) != 0)
set_sense_type(chip, lun,
SENSE_TYPE_MG_KEY_FAIL_NOT_ESTAB);
else
set_sense_type(chip, lun,
SENSE_TYPE_MG_WRITE_ERR);
} else {
set_sense_type(chip, lun,
SENSE_TYPE_MG_WRITE_ERR);
}
retval = STATUS_FAIL;
TRACE_GOTO(chip, SetICVFinish);
}
retval = rts51x_get_rsp(chip, 1, 3000);
if (CHECK_MS_TRANS_FAIL(chip, retval)
|| mg_check_int_error(chip)) {
rts51x_clear_ms_error(chip);
if (ms_card->mg_auth == 0) {
if ((buf[5] & 0xC0) != 0)
set_sense_type(chip, lun,
SENSE_TYPE_MG_KEY_FAIL_NOT_ESTAB);
else
set_sense_type(chip, lun,
SENSE_TYPE_MG_WRITE_ERR);
} else {
set_sense_type(chip, lun,
SENSE_TYPE_MG_WRITE_ERR);
}
retval = STATUS_FAIL;
TRACE_GOTO(chip, SetICVFinish);
}
}
#else
retval = ms_transfer_data(chip, MS_TM_AUTO_WRITE, PRO_WRITE_LONG_DATA,
2, WAIT_INT, 0, 0, buf + 4, 1024);
if (retval != STATUS_SUCCESS) {
rts51x_clear_ms_error(chip);
if (ms_card->mg_auth == 0) {
if ((buf[5] & 0xC0) != 0)
set_sense_type(chip, lun,
SENSE_TYPE_MG_KEY_FAIL_NOT_ESTAB);
else
set_sense_type(chip, lun,
SENSE_TYPE_MG_WRITE_ERR);
} else {
set_sense_type(chip, lun, SENSE_TYPE_MG_WRITE_ERR);
}
TRACE_GOTO(chip, SetICVFinish);
}
#endif
SetICVFinish:
kfree(buf);
return retval;
}
#endif /* SUPPORT_MAGIC_GATE */
| gpl-2.0 |
suzuke/pdk7105-stm-kernel | fs/exofs/dir.c | 5071 | 17182 | /*
* Copyright (C) 2005, 2006
* Avishay Traeger (avishay@gmail.com)
* Copyright (C) 2008, 2009
* Boaz Harrosh <bharrosh@panasas.com>
*
* Copyrights for code taken from ext2:
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
* from
* linux/fs/minix/inode.c
* Copyright (C) 1991, 1992 Linus Torvalds
*
* This file is part of exofs.
*
* exofs 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. Since it is based on ext2, and the only
* valid version of GPL for the Linux kernel is version 2, the only valid
* version of GPL for exofs is version 2.
*
* exofs 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 exofs; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "exofs.h"
static inline unsigned exofs_chunk_size(struct inode *inode)
{
return inode->i_sb->s_blocksize;
}
static inline void exofs_put_page(struct page *page)
{
kunmap(page);
page_cache_release(page);
}
/* Accesses dir's inode->i_size must be called under inode lock */
static inline unsigned long dir_pages(struct inode *inode)
{
return (inode->i_size + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
}
static unsigned exofs_last_byte(struct inode *inode, unsigned long page_nr)
{
loff_t last_byte = inode->i_size;
last_byte -= page_nr << PAGE_CACHE_SHIFT;
if (last_byte > PAGE_CACHE_SIZE)
last_byte = PAGE_CACHE_SIZE;
return last_byte;
}
static int exofs_commit_chunk(struct page *page, loff_t pos, unsigned len)
{
struct address_space *mapping = page->mapping;
struct inode *dir = mapping->host;
int err = 0;
dir->i_version++;
if (!PageUptodate(page))
SetPageUptodate(page);
if (pos+len > dir->i_size) {
i_size_write(dir, pos+len);
mark_inode_dirty(dir);
}
set_page_dirty(page);
if (IS_DIRSYNC(dir))
err = write_one_page(page, 1);
else
unlock_page(page);
return err;
}
static void exofs_check_page(struct page *page)
{
struct inode *dir = page->mapping->host;
unsigned chunk_size = exofs_chunk_size(dir);
char *kaddr = page_address(page);
unsigned offs, rec_len;
unsigned limit = PAGE_CACHE_SIZE;
struct exofs_dir_entry *p;
char *error;
/* if the page is the last one in the directory */
if ((dir->i_size >> PAGE_CACHE_SHIFT) == page->index) {
limit = dir->i_size & ~PAGE_CACHE_MASK;
if (limit & (chunk_size - 1))
goto Ebadsize;
if (!limit)
goto out;
}
for (offs = 0; offs <= limit - EXOFS_DIR_REC_LEN(1); offs += rec_len) {
p = (struct exofs_dir_entry *)(kaddr + offs);
rec_len = le16_to_cpu(p->rec_len);
if (rec_len < EXOFS_DIR_REC_LEN(1))
goto Eshort;
if (rec_len & 3)
goto Ealign;
if (rec_len < EXOFS_DIR_REC_LEN(p->name_len))
goto Enamelen;
if (((offs + rec_len - 1) ^ offs) & ~(chunk_size-1))
goto Espan;
}
if (offs != limit)
goto Eend;
out:
SetPageChecked(page);
return;
Ebadsize:
EXOFS_ERR("ERROR [exofs_check_page]: "
"size of directory(0x%lx) is not a multiple of chunk size\n",
dir->i_ino
);
goto fail;
Eshort:
error = "rec_len is smaller than minimal";
goto bad_entry;
Ealign:
error = "unaligned directory entry";
goto bad_entry;
Enamelen:
error = "rec_len is too small for name_len";
goto bad_entry;
Espan:
error = "directory entry across blocks";
goto bad_entry;
bad_entry:
EXOFS_ERR(
"ERROR [exofs_check_page]: bad entry in directory(0x%lx): %s - "
"offset=%lu, inode=0x%llu, rec_len=%d, name_len=%d\n",
dir->i_ino, error, (page->index<<PAGE_CACHE_SHIFT)+offs,
_LLU(le64_to_cpu(p->inode_no)),
rec_len, p->name_len);
goto fail;
Eend:
p = (struct exofs_dir_entry *)(kaddr + offs);
EXOFS_ERR("ERROR [exofs_check_page]: "
"entry in directory(0x%lx) spans the page boundary"
"offset=%lu, inode=0x%llx\n",
dir->i_ino, (page->index<<PAGE_CACHE_SHIFT)+offs,
_LLU(le64_to_cpu(p->inode_no)));
fail:
SetPageChecked(page);
SetPageError(page);
}
static struct page *exofs_get_page(struct inode *dir, unsigned long n)
{
struct address_space *mapping = dir->i_mapping;
struct page *page = read_mapping_page(mapping, n, NULL);
if (!IS_ERR(page)) {
kmap(page);
if (!PageChecked(page))
exofs_check_page(page);
if (PageError(page))
goto fail;
}
return page;
fail:
exofs_put_page(page);
return ERR_PTR(-EIO);
}
static inline int exofs_match(int len, const unsigned char *name,
struct exofs_dir_entry *de)
{
if (len != de->name_len)
return 0;
if (!de->inode_no)
return 0;
return !memcmp(name, de->name, len);
}
static inline
struct exofs_dir_entry *exofs_next_entry(struct exofs_dir_entry *p)
{
return (struct exofs_dir_entry *)((char *)p + le16_to_cpu(p->rec_len));
}
static inline unsigned
exofs_validate_entry(char *base, unsigned offset, unsigned mask)
{
struct exofs_dir_entry *de = (struct exofs_dir_entry *)(base + offset);
struct exofs_dir_entry *p =
(struct exofs_dir_entry *)(base + (offset&mask));
while ((char *)p < (char *)de) {
if (p->rec_len == 0)
break;
p = exofs_next_entry(p);
}
return (char *)p - base;
}
static unsigned char exofs_filetype_table[EXOFS_FT_MAX] = {
[EXOFS_FT_UNKNOWN] = DT_UNKNOWN,
[EXOFS_FT_REG_FILE] = DT_REG,
[EXOFS_FT_DIR] = DT_DIR,
[EXOFS_FT_CHRDEV] = DT_CHR,
[EXOFS_FT_BLKDEV] = DT_BLK,
[EXOFS_FT_FIFO] = DT_FIFO,
[EXOFS_FT_SOCK] = DT_SOCK,
[EXOFS_FT_SYMLINK] = DT_LNK,
};
#define S_SHIFT 12
static unsigned char exofs_type_by_mode[S_IFMT >> S_SHIFT] = {
[S_IFREG >> S_SHIFT] = EXOFS_FT_REG_FILE,
[S_IFDIR >> S_SHIFT] = EXOFS_FT_DIR,
[S_IFCHR >> S_SHIFT] = EXOFS_FT_CHRDEV,
[S_IFBLK >> S_SHIFT] = EXOFS_FT_BLKDEV,
[S_IFIFO >> S_SHIFT] = EXOFS_FT_FIFO,
[S_IFSOCK >> S_SHIFT] = EXOFS_FT_SOCK,
[S_IFLNK >> S_SHIFT] = EXOFS_FT_SYMLINK,
};
static inline
void exofs_set_de_type(struct exofs_dir_entry *de, struct inode *inode)
{
umode_t mode = inode->i_mode;
de->file_type = exofs_type_by_mode[(mode & S_IFMT) >> S_SHIFT];
}
static int
exofs_readdir(struct file *filp, void *dirent, filldir_t filldir)
{
loff_t pos = filp->f_pos;
struct inode *inode = filp->f_path.dentry->d_inode;
unsigned int offset = pos & ~PAGE_CACHE_MASK;
unsigned long n = pos >> PAGE_CACHE_SHIFT;
unsigned long npages = dir_pages(inode);
unsigned chunk_mask = ~(exofs_chunk_size(inode)-1);
unsigned char *types = NULL;
int need_revalidate = (filp->f_version != inode->i_version);
if (pos > inode->i_size - EXOFS_DIR_REC_LEN(1))
return 0;
types = exofs_filetype_table;
for ( ; n < npages; n++, offset = 0) {
char *kaddr, *limit;
struct exofs_dir_entry *de;
struct page *page = exofs_get_page(inode, n);
if (IS_ERR(page)) {
EXOFS_ERR("ERROR: bad page in directory(0x%lx)\n",
inode->i_ino);
filp->f_pos += PAGE_CACHE_SIZE - offset;
return PTR_ERR(page);
}
kaddr = page_address(page);
if (unlikely(need_revalidate)) {
if (offset) {
offset = exofs_validate_entry(kaddr, offset,
chunk_mask);
filp->f_pos = (n<<PAGE_CACHE_SHIFT) + offset;
}
filp->f_version = inode->i_version;
need_revalidate = 0;
}
de = (struct exofs_dir_entry *)(kaddr + offset);
limit = kaddr + exofs_last_byte(inode, n) -
EXOFS_DIR_REC_LEN(1);
for (; (char *)de <= limit; de = exofs_next_entry(de)) {
if (de->rec_len == 0) {
EXOFS_ERR("ERROR: "
"zero-length entry in directory(0x%lx)\n",
inode->i_ino);
exofs_put_page(page);
return -EIO;
}
if (de->inode_no) {
int over;
unsigned char d_type = DT_UNKNOWN;
if (types && de->file_type < EXOFS_FT_MAX)
d_type = types[de->file_type];
offset = (char *)de - kaddr;
over = filldir(dirent, de->name, de->name_len,
(n<<PAGE_CACHE_SHIFT) | offset,
le64_to_cpu(de->inode_no),
d_type);
if (over) {
exofs_put_page(page);
return 0;
}
}
filp->f_pos += le16_to_cpu(de->rec_len);
}
exofs_put_page(page);
}
return 0;
}
struct exofs_dir_entry *exofs_find_entry(struct inode *dir,
struct dentry *dentry, struct page **res_page)
{
const unsigned char *name = dentry->d_name.name;
int namelen = dentry->d_name.len;
unsigned reclen = EXOFS_DIR_REC_LEN(namelen);
unsigned long start, n;
unsigned long npages = dir_pages(dir);
struct page *page = NULL;
struct exofs_i_info *oi = exofs_i(dir);
struct exofs_dir_entry *de;
if (npages == 0)
goto out;
*res_page = NULL;
start = oi->i_dir_start_lookup;
if (start >= npages)
start = 0;
n = start;
do {
char *kaddr;
page = exofs_get_page(dir, n);
if (!IS_ERR(page)) {
kaddr = page_address(page);
de = (struct exofs_dir_entry *) kaddr;
kaddr += exofs_last_byte(dir, n) - reclen;
while ((char *) de <= kaddr) {
if (de->rec_len == 0) {
EXOFS_ERR("ERROR: zero-length entry in "
"directory(0x%lx)\n",
dir->i_ino);
exofs_put_page(page);
goto out;
}
if (exofs_match(namelen, name, de))
goto found;
de = exofs_next_entry(de);
}
exofs_put_page(page);
}
if (++n >= npages)
n = 0;
} while (n != start);
out:
return NULL;
found:
*res_page = page;
oi->i_dir_start_lookup = n;
return de;
}
struct exofs_dir_entry *exofs_dotdot(struct inode *dir, struct page **p)
{
struct page *page = exofs_get_page(dir, 0);
struct exofs_dir_entry *de = NULL;
if (!IS_ERR(page)) {
de = exofs_next_entry(
(struct exofs_dir_entry *)page_address(page));
*p = page;
}
return de;
}
ino_t exofs_parent_ino(struct dentry *child)
{
struct page *page;
struct exofs_dir_entry *de;
ino_t ino;
de = exofs_dotdot(child->d_inode, &page);
if (!de)
return 0;
ino = le64_to_cpu(de->inode_no);
exofs_put_page(page);
return ino;
}
ino_t exofs_inode_by_name(struct inode *dir, struct dentry *dentry)
{
ino_t res = 0;
struct exofs_dir_entry *de;
struct page *page;
de = exofs_find_entry(dir, dentry, &page);
if (de) {
res = le64_to_cpu(de->inode_no);
exofs_put_page(page);
}
return res;
}
int exofs_set_link(struct inode *dir, struct exofs_dir_entry *de,
struct page *page, struct inode *inode)
{
loff_t pos = page_offset(page) +
(char *) de - (char *) page_address(page);
unsigned len = le16_to_cpu(de->rec_len);
int err;
lock_page(page);
err = exofs_write_begin(NULL, page->mapping, pos, len,
AOP_FLAG_UNINTERRUPTIBLE, &page, NULL);
if (err)
EXOFS_ERR("exofs_set_link: exofs_write_begin FAILED => %d\n",
err);
de->inode_no = cpu_to_le64(inode->i_ino);
exofs_set_de_type(de, inode);
if (likely(!err))
err = exofs_commit_chunk(page, pos, len);
exofs_put_page(page);
dir->i_mtime = dir->i_ctime = CURRENT_TIME;
mark_inode_dirty(dir);
return err;
}
int exofs_add_link(struct dentry *dentry, struct inode *inode)
{
struct inode *dir = dentry->d_parent->d_inode;
const unsigned char *name = dentry->d_name.name;
int namelen = dentry->d_name.len;
unsigned chunk_size = exofs_chunk_size(dir);
unsigned reclen = EXOFS_DIR_REC_LEN(namelen);
unsigned short rec_len, name_len;
struct page *page = NULL;
struct exofs_sb_info *sbi = inode->i_sb->s_fs_info;
struct exofs_dir_entry *de;
unsigned long npages = dir_pages(dir);
unsigned long n;
char *kaddr;
loff_t pos;
int err;
for (n = 0; n <= npages; n++) {
char *dir_end;
page = exofs_get_page(dir, n);
err = PTR_ERR(page);
if (IS_ERR(page))
goto out;
lock_page(page);
kaddr = page_address(page);
dir_end = kaddr + exofs_last_byte(dir, n);
de = (struct exofs_dir_entry *)kaddr;
kaddr += PAGE_CACHE_SIZE - reclen;
while ((char *)de <= kaddr) {
if ((char *)de == dir_end) {
name_len = 0;
rec_len = chunk_size;
de->rec_len = cpu_to_le16(chunk_size);
de->inode_no = 0;
goto got_it;
}
if (de->rec_len == 0) {
EXOFS_ERR("ERROR: exofs_add_link: "
"zero-length entry in directory(0x%lx)\n",
inode->i_ino);
err = -EIO;
goto out_unlock;
}
err = -EEXIST;
if (exofs_match(namelen, name, de))
goto out_unlock;
name_len = EXOFS_DIR_REC_LEN(de->name_len);
rec_len = le16_to_cpu(de->rec_len);
if (!de->inode_no && rec_len >= reclen)
goto got_it;
if (rec_len >= name_len + reclen)
goto got_it;
de = (struct exofs_dir_entry *) ((char *) de + rec_len);
}
unlock_page(page);
exofs_put_page(page);
}
EXOFS_ERR("exofs_add_link: BAD dentry=%p or inode=0x%lx\n",
dentry, inode->i_ino);
return -EINVAL;
got_it:
pos = page_offset(page) +
(char *)de - (char *)page_address(page);
err = exofs_write_begin(NULL, page->mapping, pos, rec_len, 0,
&page, NULL);
if (err)
goto out_unlock;
if (de->inode_no) {
struct exofs_dir_entry *de1 =
(struct exofs_dir_entry *)((char *)de + name_len);
de1->rec_len = cpu_to_le16(rec_len - name_len);
de->rec_len = cpu_to_le16(name_len);
de = de1;
}
de->name_len = namelen;
memcpy(de->name, name, namelen);
de->inode_no = cpu_to_le64(inode->i_ino);
exofs_set_de_type(de, inode);
err = exofs_commit_chunk(page, pos, rec_len);
dir->i_mtime = dir->i_ctime = CURRENT_TIME;
mark_inode_dirty(dir);
sbi->s_numfiles++;
out_put:
exofs_put_page(page);
out:
return err;
out_unlock:
unlock_page(page);
goto out_put;
}
int exofs_delete_entry(struct exofs_dir_entry *dir, struct page *page)
{
struct address_space *mapping = page->mapping;
struct inode *inode = mapping->host;
struct exofs_sb_info *sbi = inode->i_sb->s_fs_info;
char *kaddr = page_address(page);
unsigned from = ((char *)dir - kaddr) & ~(exofs_chunk_size(inode)-1);
unsigned to = ((char *)dir - kaddr) + le16_to_cpu(dir->rec_len);
loff_t pos;
struct exofs_dir_entry *pde = NULL;
struct exofs_dir_entry *de = (struct exofs_dir_entry *) (kaddr + from);
int err;
while (de < dir) {
if (de->rec_len == 0) {
EXOFS_ERR("ERROR: exofs_delete_entry:"
"zero-length entry in directory(0x%lx)\n",
inode->i_ino);
err = -EIO;
goto out;
}
pde = de;
de = exofs_next_entry(de);
}
if (pde)
from = (char *)pde - (char *)page_address(page);
pos = page_offset(page) + from;
lock_page(page);
err = exofs_write_begin(NULL, page->mapping, pos, to - from, 0,
&page, NULL);
if (err)
EXOFS_ERR("exofs_delete_entry: exofs_write_begin FAILED => %d\n",
err);
if (pde)
pde->rec_len = cpu_to_le16(to - from);
dir->inode_no = 0;
if (likely(!err))
err = exofs_commit_chunk(page, pos, to - from);
inode->i_ctime = inode->i_mtime = CURRENT_TIME;
mark_inode_dirty(inode);
sbi->s_numfiles--;
out:
exofs_put_page(page);
return err;
}
/* kept aligned on 4 bytes */
#define THIS_DIR ".\0\0"
#define PARENT_DIR "..\0"
int exofs_make_empty(struct inode *inode, struct inode *parent)
{
struct address_space *mapping = inode->i_mapping;
struct page *page = grab_cache_page(mapping, 0);
unsigned chunk_size = exofs_chunk_size(inode);
struct exofs_dir_entry *de;
int err;
void *kaddr;
if (!page)
return -ENOMEM;
err = exofs_write_begin(NULL, page->mapping, 0, chunk_size, 0,
&page, NULL);
if (err) {
unlock_page(page);
goto fail;
}
kaddr = kmap_atomic(page);
de = (struct exofs_dir_entry *)kaddr;
de->name_len = 1;
de->rec_len = cpu_to_le16(EXOFS_DIR_REC_LEN(1));
memcpy(de->name, THIS_DIR, sizeof(THIS_DIR));
de->inode_no = cpu_to_le64(inode->i_ino);
exofs_set_de_type(de, inode);
de = (struct exofs_dir_entry *)(kaddr + EXOFS_DIR_REC_LEN(1));
de->name_len = 2;
de->rec_len = cpu_to_le16(chunk_size - EXOFS_DIR_REC_LEN(1));
de->inode_no = cpu_to_le64(parent->i_ino);
memcpy(de->name, PARENT_DIR, sizeof(PARENT_DIR));
exofs_set_de_type(de, inode);
kunmap_atomic(kaddr);
err = exofs_commit_chunk(page, 0, chunk_size);
fail:
page_cache_release(page);
return err;
}
int exofs_empty_dir(struct inode *inode)
{
struct page *page = NULL;
unsigned long i, npages = dir_pages(inode);
for (i = 0; i < npages; i++) {
char *kaddr;
struct exofs_dir_entry *de;
page = exofs_get_page(inode, i);
if (IS_ERR(page))
continue;
kaddr = page_address(page);
de = (struct exofs_dir_entry *)kaddr;
kaddr += exofs_last_byte(inode, i) - EXOFS_DIR_REC_LEN(1);
while ((char *)de <= kaddr) {
if (de->rec_len == 0) {
EXOFS_ERR("ERROR: exofs_empty_dir: "
"zero-length directory entry"
"kaddr=%p, de=%p\n", kaddr, de);
goto not_empty;
}
if (de->inode_no != 0) {
/* check for . and .. */
if (de->name[0] != '.')
goto not_empty;
if (de->name_len > 2)
goto not_empty;
if (de->name_len < 2) {
if (le64_to_cpu(de->inode_no) !=
inode->i_ino)
goto not_empty;
} else if (de->name[1] != '.')
goto not_empty;
}
de = exofs_next_entry(de);
}
exofs_put_page(page);
}
return 1;
not_empty:
exofs_put_page(page);
return 0;
}
const struct file_operations exofs_dir_operations = {
.llseek = generic_file_llseek,
.read = generic_read_dir,
.readdir = exofs_readdir,
};
| gpl-2.0 |
Icenowy/linux-kernel-u8800-aosc-oses | drivers/video/console/mdacon.c | 11471 | 14127 | /*
* linux/drivers/video/mdacon.c -- Low level MDA based console driver
*
* (c) 1998 Andrew Apted <ajapted@netspace.net.au>
*
* including portions (c) 1995-1998 Patrick Caulfield.
*
* slight improvements (c) 2000 Edward Betts <edward@debian.org>
*
* This file is based on the VGA console driver (vgacon.c):
*
* Created 28 Sep 1997 by Geert Uytterhoeven
*
* Rewritten by Martin Mares <mj@ucw.cz>, July 1998
*
* and on the old console.c, vga.c and vesa_blank.c drivers:
*
* Copyright (C) 1991, 1992 Linus Torvalds
* 1995 Jay Estabrook
*
* 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.
*
* Changelog:
* Paul G. (03/2001) Fix mdacon= boot prompt to use __setup().
*/
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/console.h>
#include <linux/string.h>
#include <linux/kd.h>
#include <linux/vt_kern.h>
#include <linux/vt_buffer.h>
#include <linux/selection.h>
#include <linux/spinlock.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <asm/io.h>
#include <asm/vga.h>
static DEFINE_SPINLOCK(mda_lock);
/* description of the hardware layout */
static unsigned long mda_vram_base; /* Base of video memory */
static unsigned long mda_vram_len; /* Size of video memory */
static unsigned int mda_num_columns; /* Number of text columns */
static unsigned int mda_num_lines; /* Number of text lines */
static unsigned int mda_index_port; /* Register select port */
static unsigned int mda_value_port; /* Register value port */
static unsigned int mda_mode_port; /* Mode control port */
static unsigned int mda_status_port; /* Status and Config port */
static unsigned int mda_gfx_port; /* Graphics control port */
/* current hardware state */
static int mda_cursor_loc=-1;
static int mda_cursor_size_from=-1;
static int mda_cursor_size_to=-1;
static enum { TYPE_MDA, TYPE_HERC, TYPE_HERCPLUS, TYPE_HERCCOLOR } mda_type;
static char *mda_type_name;
/* console information */
static int mda_first_vc = 13;
static int mda_last_vc = 16;
static struct vc_data *mda_display_fg = NULL;
module_param(mda_first_vc, int, 0);
MODULE_PARM_DESC(mda_first_vc, "First virtual console. Default: 13");
module_param(mda_last_vc, int, 0);
MODULE_PARM_DESC(mda_last_vc, "Last virtual console. Default: 16");
/* MDA register values
*/
#define MDA_CURSOR_BLINKING 0x00
#define MDA_CURSOR_OFF 0x20
#define MDA_CURSOR_SLOWBLINK 0x60
#define MDA_MODE_GRAPHICS 0x02
#define MDA_MODE_VIDEO_EN 0x08
#define MDA_MODE_BLINK_EN 0x20
#define MDA_MODE_GFX_PAGE1 0x80
#define MDA_STATUS_HSYNC 0x01
#define MDA_STATUS_VSYNC 0x80
#define MDA_STATUS_VIDEO 0x08
#define MDA_CONFIG_COL132 0x08
#define MDA_GFX_MODE_EN 0x01
#define MDA_GFX_PAGE_EN 0x02
/*
* MDA could easily be classified as "pre-dinosaur hardware".
*/
static void write_mda_b(unsigned int val, unsigned char reg)
{
unsigned long flags;
spin_lock_irqsave(&mda_lock, flags);
outb_p(reg, mda_index_port);
outb_p(val, mda_value_port);
spin_unlock_irqrestore(&mda_lock, flags);
}
static void write_mda_w(unsigned int val, unsigned char reg)
{
unsigned long flags;
spin_lock_irqsave(&mda_lock, flags);
outb_p(reg, mda_index_port); outb_p(val >> 8, mda_value_port);
outb_p(reg+1, mda_index_port); outb_p(val & 0xff, mda_value_port);
spin_unlock_irqrestore(&mda_lock, flags);
}
#ifdef TEST_MDA_B
static int test_mda_b(unsigned char val, unsigned char reg)
{
unsigned long flags;
spin_lock_irqsave(&mda_lock, flags);
outb_p(reg, mda_index_port);
outb (val, mda_value_port);
udelay(20); val = (inb_p(mda_value_port) == val);
spin_unlock_irqrestore(&mda_lock, flags);
return val;
}
#endif
static inline void mda_set_cursor(unsigned int location)
{
if (mda_cursor_loc == location)
return;
write_mda_w(location >> 1, 0x0e);
mda_cursor_loc = location;
}
static inline void mda_set_cursor_size(int from, int to)
{
if (mda_cursor_size_from==from && mda_cursor_size_to==to)
return;
if (from > to) {
write_mda_b(MDA_CURSOR_OFF, 0x0a); /* disable cursor */
} else {
write_mda_b(from, 0x0a); /* cursor start */
write_mda_b(to, 0x0b); /* cursor end */
}
mda_cursor_size_from = from;
mda_cursor_size_to = to;
}
#ifndef MODULE
static int __init mdacon_setup(char *str)
{
/* command line format: mdacon=<first>,<last> */
int ints[3];
str = get_options(str, ARRAY_SIZE(ints), ints);
if (ints[0] < 2)
return 0;
if (ints[1] < 1 || ints[1] > MAX_NR_CONSOLES ||
ints[2] < 1 || ints[2] > MAX_NR_CONSOLES)
return 0;
mda_first_vc = ints[1];
mda_last_vc = ints[2];
return 1;
}
__setup("mdacon=", mdacon_setup);
#endif
static int mda_detect(void)
{
int count=0;
u16 *p, p_save;
u16 *q, q_save;
/* do a memory check */
p = (u16 *) mda_vram_base;
q = (u16 *) (mda_vram_base + 0x01000);
p_save = scr_readw(p); q_save = scr_readw(q);
scr_writew(0xAA55, p); if (scr_readw(p) == 0xAA55) count++;
scr_writew(0x55AA, p); if (scr_readw(p) == 0x55AA) count++;
scr_writew(p_save, p);
if (count != 2) {
return 0;
}
/* check if we have 4K or 8K */
scr_writew(0xA55A, q); scr_writew(0x0000, p);
if (scr_readw(q) == 0xA55A) count++;
scr_writew(0x5AA5, q); scr_writew(0x0000, p);
if (scr_readw(q) == 0x5AA5) count++;
scr_writew(p_save, p); scr_writew(q_save, q);
if (count == 4) {
mda_vram_len = 0x02000;
}
/* Ok, there is definitely a card registering at the correct
* memory location, so now we do an I/O port test.
*/
#ifdef TEST_MDA_B
/* Edward: These two mess `tests' mess up my cursor on bootup */
/* cursor low register */
if (! test_mda_b(0x66, 0x0f)) {
return 0;
}
/* cursor low register */
if (! test_mda_b(0x99, 0x0f)) {
return 0;
}
#endif
/* See if the card is a Hercules, by checking whether the vsync
* bit of the status register is changing. This test lasts for
* approximately 1/10th of a second.
*/
p_save = q_save = inb_p(mda_status_port) & MDA_STATUS_VSYNC;
for (count=0; count < 50000 && p_save == q_save; count++) {
q_save = inb(mda_status_port) & MDA_STATUS_VSYNC;
udelay(2);
}
if (p_save != q_save) {
switch (inb_p(mda_status_port) & 0x70) {
case 0x10:
mda_type = TYPE_HERCPLUS;
mda_type_name = "HerculesPlus";
break;
case 0x50:
mda_type = TYPE_HERCCOLOR;
mda_type_name = "HerculesColor";
break;
default:
mda_type = TYPE_HERC;
mda_type_name = "Hercules";
break;
}
}
return 1;
}
static void mda_initialize(void)
{
write_mda_b(97, 0x00); /* horizontal total */
write_mda_b(80, 0x01); /* horizontal displayed */
write_mda_b(82, 0x02); /* horizontal sync pos */
write_mda_b(15, 0x03); /* horizontal sync width */
write_mda_b(25, 0x04); /* vertical total */
write_mda_b(6, 0x05); /* vertical total adjust */
write_mda_b(25, 0x06); /* vertical displayed */
write_mda_b(25, 0x07); /* vertical sync pos */
write_mda_b(2, 0x08); /* interlace mode */
write_mda_b(13, 0x09); /* maximum scanline */
write_mda_b(12, 0x0a); /* cursor start */
write_mda_b(13, 0x0b); /* cursor end */
write_mda_w(0x0000, 0x0c); /* start address */
write_mda_w(0x0000, 0x0e); /* cursor location */
outb_p(MDA_MODE_VIDEO_EN | MDA_MODE_BLINK_EN, mda_mode_port);
outb_p(0x00, mda_status_port);
outb_p(0x00, mda_gfx_port);
}
static const char *mdacon_startup(void)
{
mda_num_columns = 80;
mda_num_lines = 25;
mda_vram_len = 0x01000;
mda_vram_base = VGA_MAP_MEM(0xb0000, mda_vram_len);
mda_index_port = 0x3b4;
mda_value_port = 0x3b5;
mda_mode_port = 0x3b8;
mda_status_port = 0x3ba;
mda_gfx_port = 0x3bf;
mda_type = TYPE_MDA;
mda_type_name = "MDA";
if (! mda_detect()) {
printk("mdacon: MDA card not detected.\n");
return NULL;
}
if (mda_type != TYPE_MDA) {
mda_initialize();
}
/* cursor looks ugly during boot-up, so turn it off */
mda_set_cursor(mda_vram_len - 1);
printk("mdacon: %s with %ldK of memory detected.\n",
mda_type_name, mda_vram_len/1024);
return "MDA-2";
}
static void mdacon_init(struct vc_data *c, int init)
{
c->vc_complement_mask = 0x0800; /* reverse video */
c->vc_display_fg = &mda_display_fg;
if (init) {
c->vc_cols = mda_num_columns;
c->vc_rows = mda_num_lines;
} else
vc_resize(c, mda_num_columns, mda_num_lines);
/* make the first MDA console visible */
if (mda_display_fg == NULL)
mda_display_fg = c;
}
static void mdacon_deinit(struct vc_data *c)
{
/* con_set_default_unimap(c->vc_num); */
if (mda_display_fg == c)
mda_display_fg = NULL;
}
static inline u16 mda_convert_attr(u16 ch)
{
u16 attr = 0x0700;
/* Underline and reverse-video are mutually exclusive on MDA.
* Since reverse-video is used for cursors and selected areas,
* it takes precedence.
*/
if (ch & 0x0800) attr = 0x7000; /* reverse */
else if (ch & 0x0400) attr = 0x0100; /* underline */
return ((ch & 0x0200) << 2) | /* intensity */
(ch & 0x8000) | /* blink */
(ch & 0x00ff) | attr;
}
static u8 mdacon_build_attr(struct vc_data *c, u8 color, u8 intensity,
u8 blink, u8 underline, u8 reverse, u8 italic)
{
/* The attribute is just a bit vector:
*
* Bit 0..1 : intensity (0..2)
* Bit 2 : underline
* Bit 3 : reverse
* Bit 7 : blink
*/
return (intensity & 3) |
((underline & 1) << 2) |
((reverse & 1) << 3) |
(!!italic << 4) |
((blink & 1) << 7);
}
static void mdacon_invert_region(struct vc_data *c, u16 *p, int count)
{
for (; count > 0; count--) {
scr_writew(scr_readw(p) ^ 0x0800, p);
p++;
}
}
#define MDA_ADDR(x,y) ((u16 *) mda_vram_base + (y)*mda_num_columns + (x))
static void mdacon_putc(struct vc_data *c, int ch, int y, int x)
{
scr_writew(mda_convert_attr(ch), MDA_ADDR(x, y));
}
static void mdacon_putcs(struct vc_data *c, const unsigned short *s,
int count, int y, int x)
{
u16 *dest = MDA_ADDR(x, y);
for (; count > 0; count--) {
scr_writew(mda_convert_attr(scr_readw(s++)), dest++);
}
}
static void mdacon_clear(struct vc_data *c, int y, int x,
int height, int width)
{
u16 *dest = MDA_ADDR(x, y);
u16 eattr = mda_convert_attr(c->vc_video_erase_char);
if (width <= 0 || height <= 0)
return;
if (x==0 && width==mda_num_columns) {
scr_memsetw(dest, eattr, height*width*2);
} else {
for (; height > 0; height--, dest+=mda_num_columns)
scr_memsetw(dest, eattr, width*2);
}
}
static void mdacon_bmove(struct vc_data *c, int sy, int sx,
int dy, int dx, int height, int width)
{
u16 *src, *dest;
if (width <= 0 || height <= 0)
return;
if (sx==0 && dx==0 && width==mda_num_columns) {
scr_memmovew(MDA_ADDR(0,dy), MDA_ADDR(0,sy), height*width*2);
} else if (dy < sy || (dy == sy && dx < sx)) {
src = MDA_ADDR(sx, sy);
dest = MDA_ADDR(dx, dy);
for (; height > 0; height--) {
scr_memmovew(dest, src, width*2);
src += mda_num_columns;
dest += mda_num_columns;
}
} else {
src = MDA_ADDR(sx, sy+height-1);
dest = MDA_ADDR(dx, dy+height-1);
for (; height > 0; height--) {
scr_memmovew(dest, src, width*2);
src -= mda_num_columns;
dest -= mda_num_columns;
}
}
}
static int mdacon_switch(struct vc_data *c)
{
return 1; /* redrawing needed */
}
static int mdacon_set_palette(struct vc_data *c, unsigned char *table)
{
return -EINVAL;
}
static int mdacon_blank(struct vc_data *c, int blank, int mode_switch)
{
if (mda_type == TYPE_MDA) {
if (blank)
scr_memsetw((void *)mda_vram_base,
mda_convert_attr(c->vc_video_erase_char),
c->vc_screenbuf_size);
/* Tell console.c that it has to restore the screen itself */
return 1;
} else {
if (blank)
outb_p(0x00, mda_mode_port); /* disable video */
else
outb_p(MDA_MODE_VIDEO_EN | MDA_MODE_BLINK_EN,
mda_mode_port);
return 0;
}
}
static int mdacon_scrolldelta(struct vc_data *c, int lines)
{
return 0;
}
static void mdacon_cursor(struct vc_data *c, int mode)
{
if (mode == CM_ERASE) {
mda_set_cursor(mda_vram_len - 1);
return;
}
mda_set_cursor(c->vc_y*mda_num_columns*2 + c->vc_x*2);
switch (c->vc_cursor_type & 0x0f) {
case CUR_LOWER_THIRD: mda_set_cursor_size(10, 13); break;
case CUR_LOWER_HALF: mda_set_cursor_size(7, 13); break;
case CUR_TWO_THIRDS: mda_set_cursor_size(4, 13); break;
case CUR_BLOCK: mda_set_cursor_size(1, 13); break;
case CUR_NONE: mda_set_cursor_size(14, 13); break;
default: mda_set_cursor_size(12, 13); break;
}
}
static int mdacon_scroll(struct vc_data *c, int t, int b, int dir, int lines)
{
u16 eattr = mda_convert_attr(c->vc_video_erase_char);
if (!lines)
return 0;
if (lines > c->vc_rows) /* maximum realistic size */
lines = c->vc_rows;
switch (dir) {
case SM_UP:
scr_memmovew(MDA_ADDR(0,t), MDA_ADDR(0,t+lines),
(b-t-lines)*mda_num_columns*2);
scr_memsetw(MDA_ADDR(0,b-lines), eattr,
lines*mda_num_columns*2);
break;
case SM_DOWN:
scr_memmovew(MDA_ADDR(0,t+lines), MDA_ADDR(0,t),
(b-t-lines)*mda_num_columns*2);
scr_memsetw(MDA_ADDR(0,t), eattr, lines*mda_num_columns*2);
break;
}
return 0;
}
/*
* The console `switch' structure for the MDA based console
*/
static const struct consw mda_con = {
.owner = THIS_MODULE,
.con_startup = mdacon_startup,
.con_init = mdacon_init,
.con_deinit = mdacon_deinit,
.con_clear = mdacon_clear,
.con_putc = mdacon_putc,
.con_putcs = mdacon_putcs,
.con_cursor = mdacon_cursor,
.con_scroll = mdacon_scroll,
.con_bmove = mdacon_bmove,
.con_switch = mdacon_switch,
.con_blank = mdacon_blank,
.con_set_palette = mdacon_set_palette,
.con_scrolldelta = mdacon_scrolldelta,
.con_build_attr = mdacon_build_attr,
.con_invert_region = mdacon_invert_region,
};
int __init mda_console_init(void)
{
if (mda_first_vc > mda_last_vc)
return 1;
return take_over_console(&mda_con, mda_first_vc-1, mda_last_vc-1, 0);
}
static void __exit mda_console_exit(void)
{
give_up_console(&mda_con);
}
module_init(mda_console_init);
module_exit(mda_console_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
thicklizard/Komodo | arch/arm/mach-msm/smem_log.c | 464 | 48987 | /* Copyright (c) 2008-2011, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
/*
* Shared memory logging implementation.
*/
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/jiffies.h>
#include <linux/remote_spinlock.h>
#include <linux/debugfs.h>
#include <linux/io.h>
#include <linux/string.h>
#include <linux/sched.h>
#include <linux/wait.h>
#include <linux/delay.h>
#include <mach/msm_iomap.h>
#include <mach/smem_log.h>
#include "smd_private.h"
#include "smd_rpc_sym.h"
#include "modem_notifier.h"
#define DEBUG
#undef DEBUG
#ifdef DEBUG
#define D_DUMP_BUFFER(prestr, cnt, buf) \
do { \
int i; \
printk(KERN_ERR "%s", prestr); \
for (i = 0; i < cnt; i++) \
printk(KERN_ERR "%.2x", buf[i]); \
printk(KERN_ERR "\n"); \
} while (0)
#else
#define D_DUMP_BUFFER(prestr, cnt, buf)
#endif
#ifdef DEBUG
#define D(x...) printk(x)
#else
#define D(x...) do {} while (0)
#endif
#if defined(CONFIG_ARCH_MSM7X30) || defined(CONFIG_ARCH_MSM8X60) \
|| defined(CONFIG_ARCH_FSM9XXX)
#define TIMESTAMP_ADDR (MSM_TMR_BASE + 0x08)
#else
#define TIMESTAMP_ADDR (MSM_TMR_BASE + 0x04)
#endif
struct smem_log_item {
uint32_t identifier;
uint32_t timetick;
uint32_t data1;
uint32_t data2;
uint32_t data3;
};
#define SMEM_LOG_NUM_ENTRIES 2000
#define SMEM_LOG_EVENTS_SIZE (sizeof(struct smem_log_item) * \
SMEM_LOG_NUM_ENTRIES)
#define SMEM_LOG_NUM_STATIC_ENTRIES 150
#define SMEM_STATIC_LOG_EVENTS_SIZE (sizeof(struct smem_log_item) * \
SMEM_LOG_NUM_STATIC_ENTRIES)
#define SMEM_LOG_NUM_POWER_ENTRIES 2000
#define SMEM_POWER_LOG_EVENTS_SIZE (sizeof(struct smem_log_item) * \
SMEM_LOG_NUM_POWER_ENTRIES)
#define SMEM_SPINLOCK_SMEM_LOG "S:2"
#define SMEM_SPINLOCK_STATIC_LOG "S:5"
/* POWER shares with SMEM_SPINLOCK_SMEM_LOG */
static remote_spinlock_t remote_spinlock;
static remote_spinlock_t remote_spinlock_static;
static uint32_t smem_log_enable;
static int smem_log_initialized;
module_param_named(log_enable, smem_log_enable, int,
S_IRUGO | S_IWUSR | S_IWGRP);
struct smem_log_inst {
int which_log;
struct smem_log_item __iomem *events;
uint32_t __iomem *idx;
uint32_t num;
uint32_t read_idx;
uint32_t last_read_avail;
wait_queue_head_t read_wait;
remote_spinlock_t *remote_spinlock;
};
enum smem_logs {
GEN = 0,
STA,
POW,
NUM
};
static struct smem_log_inst inst[NUM];
#if defined(CONFIG_DEBUG_FS)
#define HSIZE 13
struct sym {
uint32_t val;
char *str;
struct hlist_node node;
};
struct sym id_syms[] = {
{ SMEM_LOG_PROC_ID_MODEM, "MODM" },
{ SMEM_LOG_PROC_ID_Q6, "QDSP" },
{ SMEM_LOG_PROC_ID_APPS, "APPS" },
};
struct sym base_syms[] = {
{ SMEM_LOG_ONCRPC_EVENT_BASE, "ONCRPC" },
{ SMEM_LOG_SMEM_EVENT_BASE, "SMEM" },
{ SMEM_LOG_TMC_EVENT_BASE, "TMC" },
{ SMEM_LOG_TIMETICK_EVENT_BASE, "TIMETICK" },
{ SMEM_LOG_DEM_EVENT_BASE, "DEM" },
{ SMEM_LOG_ERROR_EVENT_BASE, "ERROR" },
{ SMEM_LOG_DCVS_EVENT_BASE, "DCVS" },
{ SMEM_LOG_SLEEP_EVENT_BASE, "SLEEP" },
{ SMEM_LOG_RPC_ROUTER_EVENT_BASE, "ROUTER" },
};
struct sym event_syms[] = {
#if defined(CONFIG_MSM_N_WAY_SMSM)
{ DEM_SMSM_ISR, "SMSM_ISR" },
{ DEM_STATE_CHANGE, "STATE_CHANGE" },
{ DEM_STATE_MACHINE_ENTER, "STATE_MACHINE_ENTER" },
{ DEM_ENTER_SLEEP, "ENTER_SLEEP" },
{ DEM_END_SLEEP, "END_SLEEP" },
{ DEM_SETUP_SLEEP, "SETUP_SLEEP" },
{ DEM_SETUP_POWER_COLLAPSE, "SETUP_POWER_COLLAPSE" },
{ DEM_SETUP_SUSPEND, "SETUP_SUSPEND" },
{ DEM_EARLY_EXIT, "EARLY_EXIT" },
{ DEM_WAKEUP_REASON, "WAKEUP_REASON" },
{ DEM_DETECT_WAKEUP, "DETECT_WAKEUP" },
{ DEM_DETECT_RESET, "DETECT_RESET" },
{ DEM_DETECT_SLEEPEXIT, "DETECT_SLEEPEXIT" },
{ DEM_DETECT_RUN, "DETECT_RUN" },
{ DEM_APPS_SWFI, "APPS_SWFI" },
{ DEM_SEND_WAKEUP, "SEND_WAKEUP" },
{ DEM_ASSERT_OKTS, "ASSERT_OKTS" },
{ DEM_NEGATE_OKTS, "NEGATE_OKTS" },
{ DEM_PROC_COMM_CMD, "PROC_COMM_CMD" },
{ DEM_REMOVE_PROC_PWR, "REMOVE_PROC_PWR" },
{ DEM_RESTORE_PROC_PWR, "RESTORE_PROC_PWR" },
{ DEM_SMI_CLK_DISABLED, "SMI_CLK_DISABLED" },
{ DEM_SMI_CLK_ENABLED, "SMI_CLK_ENABLED" },
{ DEM_MAO_INTS, "MAO_INTS" },
{ DEM_APPS_WAKEUP_INT, "APPS_WAKEUP_INT" },
{ DEM_PROC_WAKEUP, "PROC_WAKEUP" },
{ DEM_PROC_POWERUP, "PROC_POWERUP" },
{ DEM_TIMER_EXPIRED, "TIMER_EXPIRED" },
{ DEM_SEND_BATTERY_INFO, "SEND_BATTERY_INFO" },
{ DEM_REMOTE_PWR_CB, "REMOTE_PWR_CB" },
{ DEM_TIME_SYNC_START, "TIME_SYNC_START" },
{ DEM_TIME_SYNC_SEND_VALUE, "TIME_SYNC_SEND_VALUE" },
{ DEM_TIME_SYNC_DONE, "TIME_SYNC_DONE" },
{ DEM_TIME_SYNC_REQUEST, "TIME_SYNC_REQUEST" },
{ DEM_TIME_SYNC_POLL, "TIME_SYNC_POLL" },
{ DEM_TIME_SYNC_INIT, "TIME_SYNC_INIT" },
{ DEM_INIT, "INIT" },
#else
{ DEM_NO_SLEEP, "NO_SLEEP" },
{ DEM_INSUF_TIME, "INSUF_TIME" },
{ DEMAPPS_ENTER_SLEEP, "APPS_ENTER_SLEEP" },
{ DEMAPPS_DETECT_WAKEUP, "APPS_DETECT_WAKEUP" },
{ DEMAPPS_END_APPS_TCXO, "APPS_END_APPS_TCXO" },
{ DEMAPPS_ENTER_SLEEPEXIT, "APPS_ENTER_SLEEPEXIT" },
{ DEMAPPS_END_APPS_SLEEP, "APPS_END_APPS_SLEEP" },
{ DEMAPPS_SETUP_APPS_PWRCLPS, "APPS_SETUP_APPS_PWRCLPS" },
{ DEMAPPS_PWRCLPS_EARLY_EXIT, "APPS_PWRCLPS_EARLY_EXIT" },
{ DEMMOD_SEND_WAKEUP, "MOD_SEND_WAKEUP" },
{ DEMMOD_NO_APPS_VOTE, "MOD_NO_APPS_VOTE" },
{ DEMMOD_NO_TCXO_SLEEP, "MOD_NO_TCXO_SLEEP" },
{ DEMMOD_BT_CLOCK, "MOD_BT_CLOCK" },
{ DEMMOD_UART_CLOCK, "MOD_UART_CLOCK" },
{ DEMMOD_OKTS, "MOD_OKTS" },
{ DEM_SLEEP_INFO, "SLEEP_INFO" },
{ DEMMOD_TCXO_END, "MOD_TCXO_END" },
{ DEMMOD_END_SLEEP_SIG, "MOD_END_SLEEP_SIG" },
{ DEMMOD_SETUP_APPSSLEEP, "MOD_SETUP_APPSSLEEP" },
{ DEMMOD_ENTER_TCXO, "MOD_ENTER_TCXO" },
{ DEMMOD_WAKE_APPS, "MOD_WAKE_APPS" },
{ DEMMOD_POWER_COLLAPSE_APPS, "MOD_POWER_COLLAPSE_APPS" },
{ DEMMOD_RESTORE_APPS_PWR, "MOD_RESTORE_APPS_PWR" },
{ DEMAPPS_ASSERT_OKTS, "APPS_ASSERT_OKTS" },
{ DEMAPPS_RESTART_START_TIMER, "APPS_RESTART_START_TIMER" },
{ DEMAPPS_ENTER_RUN, "APPS_ENTER_RUN" },
{ DEMMOD_MAO_INTS, "MOD_MAO_INTS" },
{ DEMMOD_POWERUP_APPS_CALLED, "MOD_POWERUP_APPS_CALLED" },
{ DEMMOD_PC_TIMER_EXPIRED, "MOD_PC_TIMER_EXPIRED" },
{ DEM_DETECT_SLEEPEXIT, "_DETECT_SLEEPEXIT" },
{ DEM_DETECT_RUN, "DETECT_RUN" },
{ DEM_SET_APPS_TIMER, "SET_APPS_TIMER" },
{ DEM_NEGATE_OKTS, "NEGATE_OKTS" },
{ DEMMOD_APPS_WAKEUP_INT, "MOD_APPS_WAKEUP_INT" },
{ DEMMOD_APPS_SWFI, "MOD_APPS_SWFI" },
{ DEM_SEND_BATTERY_INFO, "SEND_BATTERY_INFO" },
{ DEM_SMI_CLK_DISABLED, "SMI_CLK_DISABLED" },
{ DEM_SMI_CLK_ENABLED, "SMI_CLK_ENABLED" },
{ DEMAPPS_SETUP_APPS_SUSPEND, "APPS_SETUP_APPS_SUSPEND" },
{ DEM_RPC_EARLY_EXIT, "RPC_EARLY_EXIT" },
{ DEMAPPS_WAKEUP_REASON, "APPS_WAKEUP_REASON" },
{ DEM_INIT, "INIT" },
#endif
{ DEMMOD_UMTS_BASE, "MOD_UMTS_BASE" },
{ DEMMOD_GL1_GO_TO_SLEEP, "GL1_GO_TO_SLEEP" },
{ DEMMOD_GL1_SLEEP_START, "GL1_SLEEP_START" },
{ DEMMOD_GL1_AFTER_GSM_CLK_ON, "GL1_AFTER_GSM_CLK_ON" },
{ DEMMOD_GL1_BEFORE_RF_ON, "GL1_BEFORE_RF_ON" },
{ DEMMOD_GL1_AFTER_RF_ON, "GL1_AFTER_RF_ON" },
{ DEMMOD_GL1_FRAME_TICK, "GL1_FRAME_TICK" },
{ DEMMOD_GL1_WCDMA_START, "GL1_WCDMA_START" },
{ DEMMOD_GL1_WCDMA_ENDING, "GL1_WCDMA_ENDING" },
{ DEMMOD_UMTS_NOT_OKTS, "UMTS_NOT_OKTS" },
{ DEMMOD_UMTS_START_TCXO_SHUTDOWN, "UMTS_START_TCXO_SHUTDOWN" },
{ DEMMOD_UMTS_END_TCXO_SHUTDOWN, "UMTS_END_TCXO_SHUTDOWN" },
{ DEMMOD_UMTS_START_ARM_HALT, "UMTS_START_ARM_HALT" },
{ DEMMOD_UMTS_END_ARM_HALT, "UMTS_END_ARM_HALT" },
{ DEMMOD_UMTS_NEXT_WAKEUP_SCLK, "UMTS_NEXT_WAKEUP_SCLK" },
{ TIME_REMOTE_LOG_EVENT_START, "START" },
{ TIME_REMOTE_LOG_EVENT_GOTO_WAIT,
"GOTO_WAIT" },
{ TIME_REMOTE_LOG_EVENT_GOTO_INIT,
"GOTO_INIT" },
{ ERR_ERROR_FATAL, "ERR_ERROR_FATAL" },
{ ERR_ERROR_FATAL_TASK, "ERR_ERROR_FATAL_TASK" },
{ DCVSAPPS_LOG_IDLE, "DCVSAPPS_LOG_IDLE" },
{ DCVSAPPS_LOG_ERR, "DCVSAPPS_LOG_ERR" },
{ DCVSAPPS_LOG_CHG, "DCVSAPPS_LOG_CHG" },
{ DCVSAPPS_LOG_REG, "DCVSAPPS_LOG_REG" },
{ DCVSAPPS_LOG_DEREG, "DCVSAPPS_LOG_DEREG" },
{ SMEM_LOG_EVENT_CB, "CB" },
{ SMEM_LOG_EVENT_START, "START" },
{ SMEM_LOG_EVENT_INIT, "INIT" },
{ SMEM_LOG_EVENT_RUNNING, "RUNNING" },
{ SMEM_LOG_EVENT_STOP, "STOP" },
{ SMEM_LOG_EVENT_RESTART, "RESTART" },
{ SMEM_LOG_EVENT_SS, "SS" },
{ SMEM_LOG_EVENT_READ, "READ" },
{ SMEM_LOG_EVENT_WRITE, "WRITE" },
{ SMEM_LOG_EVENT_SIGS1, "SIGS1" },
{ SMEM_LOG_EVENT_SIGS2, "SIGS2" },
{ SMEM_LOG_EVENT_WRITE_DM, "WRITE_DM" },
{ SMEM_LOG_EVENT_READ_DM, "READ_DM" },
{ SMEM_LOG_EVENT_SKIP_DM, "SKIP_DM" },
{ SMEM_LOG_EVENT_STOP_DM, "STOP_DM" },
{ SMEM_LOG_EVENT_ISR, "ISR" },
{ SMEM_LOG_EVENT_TASK, "TASK" },
{ SMEM_LOG_EVENT_RS, "RS" },
{ ONCRPC_LOG_EVENT_SMD_WAIT, "SMD_WAIT" },
{ ONCRPC_LOG_EVENT_RPC_WAIT, "RPC_WAIT" },
{ ONCRPC_LOG_EVENT_RPC_BOTH_WAIT, "RPC_BOTH_WAIT" },
{ ONCRPC_LOG_EVENT_RPC_INIT, "RPC_INIT" },
{ ONCRPC_LOG_EVENT_RUNNING, "RUNNING" },
{ ONCRPC_LOG_EVENT_APIS_INITED, "APIS_INITED" },
{ ONCRPC_LOG_EVENT_AMSS_RESET, "AMSS_RESET" },
{ ONCRPC_LOG_EVENT_SMD_RESET, "SMD_RESET" },
{ ONCRPC_LOG_EVENT_ONCRPC_RESET, "ONCRPC_RESET" },
{ ONCRPC_LOG_EVENT_CB, "CB" },
{ ONCRPC_LOG_EVENT_STD_CALL, "STD_CALL" },
{ ONCRPC_LOG_EVENT_STD_REPLY, "STD_REPLY" },
{ ONCRPC_LOG_EVENT_STD_CALL_ASYNC, "STD_CALL_ASYNC" },
{ NO_SLEEP_OLD, "NO_SLEEP_OLD" },
{ INSUF_TIME, "INSUF_TIME" },
{ MOD_UART_CLOCK, "MOD_UART_CLOCK" },
{ SLEEP_INFO, "SLEEP_INFO" },
{ MOD_TCXO_END, "MOD_TCXO_END" },
{ MOD_ENTER_TCXO, "MOD_ENTER_TCXO" },
{ NO_SLEEP_NEW, "NO_SLEEP_NEW" },
{ RPC_ROUTER_LOG_EVENT_UNKNOWN, "UNKNOWN" },
{ RPC_ROUTER_LOG_EVENT_MSG_READ, "MSG_READ" },
{ RPC_ROUTER_LOG_EVENT_MSG_WRITTEN, "MSG_WRITTEN" },
{ RPC_ROUTER_LOG_EVENT_MSG_CFM_REQ, "MSG_CFM_REQ" },
{ RPC_ROUTER_LOG_EVENT_MSG_CFM_SNT, "MSG_CFM_SNT" },
{ RPC_ROUTER_LOG_EVENT_MID_READ, "MID_READ" },
{ RPC_ROUTER_LOG_EVENT_MID_WRITTEN, "MID_WRITTEN" },
{ RPC_ROUTER_LOG_EVENT_MID_CFM_REQ, "MID_CFM_REQ" },
};
struct sym wakeup_syms[] = {
{ 0x00000040, "OTHER" },
{ 0x00000020, "RESET" },
{ 0x00000010, "ALARM" },
{ 0x00000008, "TIMER" },
{ 0x00000004, "GPIO" },
{ 0x00000002, "INT" },
{ 0x00000001, "RPC" },
{ 0x00000000, "NONE" },
};
struct sym wakeup_int_syms[] = {
{ 0, "MDDI_EXT" },
{ 1, "MDDI_PRI" },
{ 2, "MDDI_CLIENT"},
{ 3, "USB_OTG" },
{ 4, "I2CC" },
{ 5, "SDC1_0" },
{ 6, "SDC1_1" },
{ 7, "SDC2_0" },
{ 8, "SDC2_1" },
{ 9, "ADSP_A9A11" },
{ 10, "UART1" },
{ 11, "UART2" },
{ 12, "UART3" },
{ 13, "DP_RX_DATA" },
{ 14, "DP_RX_DATA2" },
{ 15, "DP_RX_DATA3" },
{ 16, "DM_UART" },
{ 17, "DM_DP_RX_DATA" },
{ 18, "KEYSENSE" },
{ 19, "HSSD" },
{ 20, "NAND_WR_ER_DONE" },
{ 21, "NAND_OP_DONE" },
{ 22, "TCHSCRN1" },
{ 23, "TCHSCRN2" },
{ 24, "TCHSCRN_SSBI" },
{ 25, "USB_HS" },
{ 26, "UART2_DM_RX" },
{ 27, "UART2_DM" },
{ 28, "SDC4_1" },
{ 29, "SDC4_0" },
{ 30, "SDC3_1" },
{ 31, "SDC3_0" },
};
struct sym smsm_syms[] = {
{ 0x80000000, "UN" },
{ 0x7F000000, "ERR" },
{ 0x00800000, "SMLP" },
{ 0x00400000, "ADWN" },
{ 0x00200000, "PWRS" },
{ 0x00100000, "DWLD" },
{ 0x00080000, "SRBT" },
{ 0x00040000, "SDWN" },
{ 0x00020000, "ARBT" },
{ 0x00010000, "REL" },
{ 0x00008000, "SLE" },
{ 0x00004000, "SLP" },
{ 0x00002000, "WFPI" },
{ 0x00001000, "EEX" },
{ 0x00000800, "TIN" },
{ 0x00000400, "TWT" },
{ 0x00000200, "PWRC" },
{ 0x00000100, "RUN" },
{ 0x00000080, "SA" },
{ 0x00000040, "RES" },
{ 0x00000020, "RIN" },
{ 0x00000010, "RWT" },
{ 0x00000008, "SIN" },
{ 0x00000004, "SWT" },
{ 0x00000002, "OE" },
{ 0x00000001, "I" },
};
/* never reorder */
struct sym voter_d2_syms[] = {
{ 0x00000001, NULL },
{ 0x00000002, NULL },
{ 0x00000004, NULL },
{ 0x00000008, NULL },
{ 0x00000010, NULL },
{ 0x00000020, NULL },
{ 0x00000040, NULL },
{ 0x00000080, NULL },
{ 0x00000100, NULL },
{ 0x00000200, NULL },
{ 0x00000400, NULL },
{ 0x00000800, NULL },
{ 0x00001000, NULL },
{ 0x00002000, NULL },
{ 0x00004000, NULL },
{ 0x00008000, NULL },
{ 0x00010000, NULL },
{ 0x00020000, NULL },
{ 0x00040000, NULL },
{ 0x00080000, NULL },
{ 0x00100000, NULL },
{ 0x00200000, NULL },
{ 0x00400000, NULL },
{ 0x00800000, NULL },
{ 0x01000000, NULL },
{ 0x02000000, NULL },
{ 0x04000000, NULL },
{ 0x08000000, NULL },
{ 0x10000000, NULL },
{ 0x20000000, NULL },
{ 0x40000000, NULL },
{ 0x80000000, NULL },
};
/* never reorder */
struct sym voter_d3_syms[] = {
{ 0x00000001, NULL },
{ 0x00000002, NULL },
{ 0x00000004, NULL },
{ 0x00000008, NULL },
{ 0x00000010, NULL },
{ 0x00000020, NULL },
{ 0x00000040, NULL },
{ 0x00000080, NULL },
{ 0x00000100, NULL },
{ 0x00000200, NULL },
{ 0x00000400, NULL },
{ 0x00000800, NULL },
{ 0x00001000, NULL },
{ 0x00002000, NULL },
{ 0x00004000, NULL },
{ 0x00008000, NULL },
{ 0x00010000, NULL },
{ 0x00020000, NULL },
{ 0x00040000, NULL },
{ 0x00080000, NULL },
{ 0x00100000, NULL },
{ 0x00200000, NULL },
{ 0x00400000, NULL },
{ 0x00800000, NULL },
{ 0x01000000, NULL },
{ 0x02000000, NULL },
{ 0x04000000, NULL },
{ 0x08000000, NULL },
{ 0x10000000, NULL },
{ 0x20000000, NULL },
{ 0x40000000, NULL },
{ 0x80000000, NULL },
};
struct sym dem_state_master_syms[] = {
{ 0, "INIT" },
{ 1, "RUN" },
{ 2, "SLEEP_WAIT" },
{ 3, "SLEEP_CONFIRMED" },
{ 4, "SLEEP_EXIT" },
{ 5, "RSA" },
{ 6, "EARLY_EXIT" },
{ 7, "RSA_DELAYED" },
{ 8, "RSA_CHECK_INTS" },
{ 9, "RSA_CONFIRMED" },
{ 10, "RSA_WAKING" },
{ 11, "RSA_RESTORE" },
{ 12, "RESET" },
};
struct sym dem_state_slave_syms[] = {
{ 0, "INIT" },
{ 1, "RUN" },
{ 2, "SLEEP_WAIT" },
{ 3, "SLEEP_EXIT" },
{ 4, "SLEEP_RUN_PENDING" },
{ 5, "POWER_COLLAPSE" },
{ 6, "CHECK_INTERRUPTS" },
{ 7, "SWFI" },
{ 8, "WFPI" },
{ 9, "EARLY_EXIT" },
{ 10, "RESET_RECOVER" },
{ 11, "RESET_ACKNOWLEDGE" },
{ 12, "ERROR" },
};
struct sym smsm_entry_type_syms[] = {
{ 0, "SMSM_APPS_STATE" },
{ 1, "SMSM_MODEM_STATE" },
{ 2, "SMSM_Q6_STATE" },
{ 3, "SMSM_APPS_DEM" },
{ 4, "SMSM_MODEM_DEM" },
{ 5, "SMSM_Q6_DEM" },
{ 6, "SMSM_POWER_MASTER_DEM" },
{ 7, "SMSM_TIME_MASTER_DEM" },
};
struct sym smsm_state_syms[] = {
{ 0x00000001, "INIT" },
{ 0x00000002, "OSENTERED" },
{ 0x00000004, "SMDWAIT" },
{ 0x00000008, "SMDINIT" },
{ 0x00000010, "RPCWAIT" },
{ 0x00000020, "RPCINIT" },
{ 0x00000040, "RESET" },
{ 0x00000080, "RSA" },
{ 0x00000100, "RUN" },
{ 0x00000200, "PWRC" },
{ 0x00000400, "TIMEWAIT" },
{ 0x00000800, "TIMEINIT" },
{ 0x00001000, "PWRC_EARLY_EXIT" },
{ 0x00002000, "WFPI" },
{ 0x00004000, "SLEEP" },
{ 0x00008000, "SLEEPEXIT" },
{ 0x00010000, "OEMSBL_RELEASE" },
{ 0x00020000, "APPS_REBOOT" },
{ 0x00040000, "SYSTEM_POWER_DOWN" },
{ 0x00080000, "SYSTEM_REBOOT" },
{ 0x00100000, "SYSTEM_DOWNLOAD" },
{ 0x00200000, "PWRC_SUSPEND" },
{ 0x00400000, "APPS_SHUTDOWN" },
{ 0x00800000, "SMD_LOOPBACK" },
{ 0x01000000, "RUN_QUIET" },
{ 0x02000000, "MODEM_WAIT" },
{ 0x04000000, "MODEM_BREAK" },
{ 0x08000000, "MODEM_CONTINUE" },
{ 0x80000000, "UNKNOWN" },
};
#define ID_SYM 0
#define BASE_SYM 1
#define EVENT_SYM 2
#define WAKEUP_SYM 3
#define WAKEUP_INT_SYM 4
#define SMSM_SYM 5
#define VOTER_D2_SYM 6
#define VOTER_D3_SYM 7
#define DEM_STATE_MASTER_SYM 8
#define DEM_STATE_SLAVE_SYM 9
#define SMSM_ENTRY_TYPE_SYM 10
#define SMSM_STATE_SYM 11
static struct sym_tbl {
struct sym *data;
int size;
struct hlist_head hlist[HSIZE];
} tbl[] = {
{ id_syms, ARRAY_SIZE(id_syms) },
{ base_syms, ARRAY_SIZE(base_syms) },
{ event_syms, ARRAY_SIZE(event_syms) },
{ wakeup_syms, ARRAY_SIZE(wakeup_syms) },
{ wakeup_int_syms, ARRAY_SIZE(wakeup_int_syms) },
{ smsm_syms, ARRAY_SIZE(smsm_syms) },
{ voter_d2_syms, ARRAY_SIZE(voter_d2_syms) },
{ voter_d3_syms, ARRAY_SIZE(voter_d3_syms) },
{ dem_state_master_syms, ARRAY_SIZE(dem_state_master_syms) },
{ dem_state_slave_syms, ARRAY_SIZE(dem_state_slave_syms) },
{ smsm_entry_type_syms, ARRAY_SIZE(smsm_entry_type_syms) },
{ smsm_state_syms, ARRAY_SIZE(smsm_state_syms) },
};
static void find_voters(void)
{
void *x, *next;
unsigned size;
int i = 0, j = 0;
x = smem_get_entry(SMEM_SLEEP_STATIC, &size);
next = x;
while (next && (next < (x + size)) &&
((i + j) < (ARRAY_SIZE(voter_d3_syms) +
ARRAY_SIZE(voter_d2_syms)))) {
if (i < ARRAY_SIZE(voter_d3_syms)) {
voter_d3_syms[i].str = (char *) next;
i++;
} else if (i >= ARRAY_SIZE(voter_d3_syms) &&
j < ARRAY_SIZE(voter_d2_syms)) {
voter_d2_syms[j].str = (char *) next;
j++;
}
next += 9;
}
}
#define hash(val) (val % HSIZE)
static void init_syms(void)
{
int i;
int j;
for (i = 0; i < ARRAY_SIZE(tbl); ++i)
for (j = 0; j < HSIZE; ++j)
INIT_HLIST_HEAD(&tbl[i].hlist[j]);
for (i = 0; i < ARRAY_SIZE(tbl); ++i)
for (j = 0; j < tbl[i].size; ++j) {
INIT_HLIST_NODE(&tbl[i].data[j].node);
hlist_add_head(&tbl[i].data[j].node,
&tbl[i].hlist[hash(tbl[i].data[j].val)]);
}
}
static char *find_sym(uint32_t id, uint32_t val)
{
struct hlist_node *n;
struct sym *s;
hlist_for_each(n, &tbl[id].hlist[hash(val)]) {
s = hlist_entry(n, struct sym, node);
if (s->val == val)
return s->str;
}
return 0;
}
#else
static void init_syms(void) {}
#endif
static inline unsigned int read_timestamp(void)
{
unsigned int tick = 0;
/* no barriers necessary as the read value is a dependency for the
* comparison operation so the processor shouldn't be able to
* reorder things
*/
do {
tick = __raw_readl(TIMESTAMP_ADDR);
} while (tick != __raw_readl(TIMESTAMP_ADDR));
return tick;
}
static void smem_log_event_from_user(struct smem_log_inst *inst,
const char __user *buf, int size, int num)
{
uint32_t idx;
uint32_t next_idx;
unsigned long flags;
uint32_t identifier = 0;
uint32_t timetick = 0;
int first = 1;
int ret;
remote_spin_lock_irqsave(inst->remote_spinlock, flags);
while (num--) {
idx = *inst->idx;
if (idx < inst->num) {
ret = copy_from_user(&inst->events[idx],
buf, size);
if (ret) {
printk("ERROR %s:%i tried to write "
"%i got ret %i",
__func__, __LINE__,
size, size - ret);
goto out;
}
if (first) {
identifier =
inst->events[idx].
identifier;
timetick = read_timestamp();
first = 0;
} else {
identifier |= SMEM_LOG_CONT;
}
inst->events[idx].identifier =
identifier;
inst->events[idx].timetick =
timetick;
}
next_idx = idx + 1;
if (next_idx >= inst->num)
next_idx = 0;
*inst->idx = next_idx;
buf += sizeof(struct smem_log_item);
}
out:
wmb();
remote_spin_unlock_irqrestore(inst->remote_spinlock, flags);
}
static void _smem_log_event(
struct smem_log_item __iomem *events,
uint32_t __iomem *_idx,
remote_spinlock_t *lock,
int num,
uint32_t id, uint32_t data1, uint32_t data2,
uint32_t data3)
{
struct smem_log_item item;
uint32_t idx;
uint32_t next_idx;
unsigned long flags;
item.timetick = read_timestamp();
item.identifier = id;
item.data1 = data1;
item.data2 = data2;
item.data3 = data3;
remote_spin_lock_irqsave(lock, flags);
idx = *_idx;
if (idx < num) {
memcpy(&events[idx],
&item, sizeof(item));
}
next_idx = idx + 1;
if (next_idx >= num)
next_idx = 0;
*_idx = next_idx;
wmb();
remote_spin_unlock_irqrestore(lock, flags);
}
static void _smem_log_event6(
struct smem_log_item __iomem *events,
uint32_t __iomem *_idx,
remote_spinlock_t *lock,
int num,
uint32_t id, uint32_t data1, uint32_t data2,
uint32_t data3, uint32_t data4, uint32_t data5,
uint32_t data6)
{
struct smem_log_item item[2];
uint32_t idx;
uint32_t next_idx;
unsigned long flags;
item[0].timetick = read_timestamp();
item[0].identifier = id;
item[0].data1 = data1;
item[0].data2 = data2;
item[0].data3 = data3;
item[1].identifier = item[0].identifier;
item[1].timetick = item[0].timetick;
item[1].data1 = data4;
item[1].data2 = data5;
item[1].data3 = data6;
remote_spin_lock_irqsave(lock, flags);
idx = *_idx;
/* FIXME: Wrap around */
if (idx < (num-1)) {
memcpy(&events[idx],
&item, sizeof(item));
}
next_idx = idx + 2;
if (next_idx >= num)
next_idx = 0;
*_idx = next_idx;
wmb();
remote_spin_unlock_irqrestore(lock, flags);
}
void smem_log_event(uint32_t id, uint32_t data1, uint32_t data2,
uint32_t data3)
{
if (smem_log_enable)
_smem_log_event(inst[GEN].events, inst[GEN].idx,
inst[GEN].remote_spinlock,
SMEM_LOG_NUM_ENTRIES, id,
data1, data2, data3);
}
void smem_log_event6(uint32_t id, uint32_t data1, uint32_t data2,
uint32_t data3, uint32_t data4, uint32_t data5,
uint32_t data6)
{
if (smem_log_enable)
_smem_log_event6(inst[GEN].events, inst[GEN].idx,
inst[GEN].remote_spinlock,
SMEM_LOG_NUM_ENTRIES, id,
data1, data2, data3, data4, data5, data6);
}
void smem_log_event_to_static(uint32_t id, uint32_t data1, uint32_t data2,
uint32_t data3)
{
if (smem_log_enable)
_smem_log_event(inst[STA].events, inst[STA].idx,
inst[STA].remote_spinlock,
SMEM_LOG_NUM_STATIC_ENTRIES, id,
data1, data2, data3);
}
void smem_log_event6_to_static(uint32_t id, uint32_t data1, uint32_t data2,
uint32_t data3, uint32_t data4, uint32_t data5,
uint32_t data6)
{
if (smem_log_enable)
_smem_log_event6(inst[STA].events, inst[STA].idx,
inst[STA].remote_spinlock,
SMEM_LOG_NUM_STATIC_ENTRIES, id,
data1, data2, data3, data4, data5, data6);
}
static int _smem_log_init(void)
{
int ret;
inst[GEN].which_log = GEN;
inst[GEN].events =
(struct smem_log_item *)smem_alloc(SMEM_SMEM_LOG_EVENTS,
SMEM_LOG_EVENTS_SIZE);
inst[GEN].idx = (uint32_t *)smem_alloc(SMEM_SMEM_LOG_IDX,
sizeof(uint32_t));
if (!inst[GEN].events || !inst[GEN].idx)
pr_info("%s: no log or log_idx allocated\n", __func__);
inst[GEN].num = SMEM_LOG_NUM_ENTRIES;
inst[GEN].read_idx = 0;
inst[GEN].last_read_avail = SMEM_LOG_NUM_ENTRIES;
init_waitqueue_head(&inst[GEN].read_wait);
inst[GEN].remote_spinlock = &remote_spinlock;
inst[STA].which_log = STA;
inst[STA].events =
(struct smem_log_item *)
smem_alloc(SMEM_SMEM_STATIC_LOG_EVENTS,
SMEM_STATIC_LOG_EVENTS_SIZE);
inst[STA].idx = (uint32_t *)smem_alloc(SMEM_SMEM_STATIC_LOG_IDX,
sizeof(uint32_t));
if (!inst[STA].events || !inst[STA].idx)
pr_info("%s: no static log or log_idx allocated\n", __func__);
inst[STA].num = SMEM_LOG_NUM_STATIC_ENTRIES;
inst[STA].read_idx = 0;
inst[STA].last_read_avail = SMEM_LOG_NUM_ENTRIES;
init_waitqueue_head(&inst[STA].read_wait);
inst[STA].remote_spinlock = &remote_spinlock_static;
inst[POW].which_log = POW;
inst[POW].events =
(struct smem_log_item *)
smem_alloc(SMEM_SMEM_LOG_POWER_EVENTS,
SMEM_POWER_LOG_EVENTS_SIZE);
inst[POW].idx = (uint32_t *)smem_alloc(SMEM_SMEM_LOG_POWER_IDX,
sizeof(uint32_t));
if (!inst[POW].events || !inst[POW].idx)
pr_info("%s: no power log or log_idx allocated\n", __func__);
inst[POW].num = SMEM_LOG_NUM_POWER_ENTRIES;
inst[POW].read_idx = 0;
inst[POW].last_read_avail = SMEM_LOG_NUM_ENTRIES;
init_waitqueue_head(&inst[POW].read_wait);
inst[POW].remote_spinlock = &remote_spinlock;
ret = remote_spin_lock_init(&remote_spinlock,
SMEM_SPINLOCK_SMEM_LOG);
if (ret) {
mb();
return ret;
}
ret = remote_spin_lock_init(&remote_spinlock_static,
SMEM_SPINLOCK_STATIC_LOG);
if (ret) {
mb();
return ret;
}
init_syms();
mb();
return 0;
}
static ssize_t smem_log_read_bin(struct file *fp, char __user *buf,
size_t count, loff_t *pos)
{
int idx;
int orig_idx;
unsigned long flags;
int ret;
int tot_bytes = 0;
struct smem_log_inst *local_inst;
local_inst = fp->private_data;
remote_spin_lock_irqsave(local_inst->remote_spinlock, flags);
orig_idx = *local_inst->idx;
idx = orig_idx;
while (1) {
idx--;
if (idx < 0)
idx = local_inst->num - 1;
if (idx == orig_idx) {
ret = tot_bytes;
break;
}
if ((tot_bytes + sizeof(struct smem_log_item)) > count) {
ret = tot_bytes;
break;
}
ret = copy_to_user(buf, &local_inst->events[idx],
sizeof(struct smem_log_item));
if (ret) {
ret = -EIO;
break;
}
tot_bytes += sizeof(struct smem_log_item);
buf += sizeof(struct smem_log_item);
}
remote_spin_unlock_irqrestore(local_inst->remote_spinlock, flags);
return ret;
}
static ssize_t smem_log_read(struct file *fp, char __user *buf,
size_t count, loff_t *pos)
{
char loc_buf[128];
int i;
int idx;
int orig_idx;
unsigned long flags;
int ret;
int tot_bytes = 0;
struct smem_log_inst *inst;
inst = fp->private_data;
remote_spin_lock_irqsave(inst->remote_spinlock, flags);
orig_idx = *inst->idx;
idx = orig_idx;
while (1) {
idx--;
if (idx < 0)
idx = inst->num - 1;
if (idx == orig_idx) {
ret = tot_bytes;
break;
}
i = scnprintf(loc_buf, 128,
"0x%x 0x%x 0x%x 0x%x 0x%x\n",
inst->events[idx].identifier,
inst->events[idx].timetick,
inst->events[idx].data1,
inst->events[idx].data2,
inst->events[idx].data3);
if (i == 0) {
ret = -EIO;
break;
}
if ((tot_bytes + i) > count) {
ret = tot_bytes;
break;
}
tot_bytes += i;
ret = copy_to_user(buf, loc_buf, i);
if (ret) {
ret = -EIO;
break;
}
buf += i;
}
remote_spin_unlock_irqrestore(inst->remote_spinlock, flags);
return ret;
}
static ssize_t smem_log_write_bin(struct file *fp, const char __user *buf,
size_t count, loff_t *pos)
{
if (count < sizeof(struct smem_log_item))
return -EINVAL;
if (smem_log_enable)
smem_log_event_from_user(fp->private_data, buf,
sizeof(struct smem_log_item),
count / sizeof(struct smem_log_item));
return count;
}
static ssize_t smem_log_write(struct file *fp, const char __user *buf,
size_t count, loff_t *pos)
{
int ret;
const char delimiters[] = " ,;";
char locbuf[256] = {0};
uint32_t val[10] = {0};
int vals = 0;
char *token;
char *running;
struct smem_log_inst *inst;
unsigned long res;
inst = fp->private_data;
count = count > 255 ? 255 : count;
if (!smem_log_enable)
return count;
locbuf[count] = '\0';
ret = copy_from_user(locbuf, buf, count);
if (ret != 0) {
printk(KERN_ERR "ERROR: %s could not copy %i bytes\n",
__func__, ret);
return -EINVAL;
}
D(KERN_ERR "%s: ", __func__);
D_DUMP_BUFFER("We got", len, locbuf);
running = locbuf;
token = strsep(&running, delimiters);
while (token && vals < ARRAY_SIZE(val)) {
if (*token != '\0') {
D(KERN_ERR "%s: ", __func__);
D_DUMP_BUFFER("", strlen(token), token);
ret = strict_strtoul(token, 0, &res);
if (ret) {
printk(KERN_ERR "ERROR: %s:%i got bad char "
"at strict_strtoul\n",
__func__, __LINE__-4);
return -EINVAL;
}
val[vals++] = res;
}
token = strsep(&running, delimiters);
}
if (vals > 5) {
if (inst->which_log == GEN)
smem_log_event6(val[0], val[2], val[3], val[4],
val[7], val[8], val[9]);
else if (inst->which_log == STA)
smem_log_event6_to_static(val[0],
val[2], val[3], val[4],
val[7], val[8], val[9]);
else
return -1;
} else {
if (inst->which_log == GEN)
smem_log_event(val[0], val[2], val[3], val[4]);
else if (inst->which_log == STA)
smem_log_event_to_static(val[0],
val[2], val[3], val[4]);
else
return -1;
}
return count;
}
static int smem_log_open(struct inode *ip, struct file *fp)
{
fp->private_data = &inst[GEN];
return 0;
}
static int smem_log_release(struct inode *ip, struct file *fp)
{
return 0;
}
static long smem_log_ioctl(struct file *fp, unsigned int cmd,
unsigned long arg);
static const struct file_operations smem_log_fops = {
.owner = THIS_MODULE,
.read = smem_log_read,
.write = smem_log_write,
.open = smem_log_open,
.release = smem_log_release,
.unlocked_ioctl = smem_log_ioctl,
};
static const struct file_operations smem_log_bin_fops = {
.owner = THIS_MODULE,
.read = smem_log_read_bin,
.write = smem_log_write_bin,
.open = smem_log_open,
.release = smem_log_release,
.unlocked_ioctl = smem_log_ioctl,
};
static long smem_log_ioctl(struct file *fp,
unsigned int cmd, unsigned long arg)
{
switch (cmd) {
default:
return -ENOTTY;
case SMIOC_SETMODE:
if (arg == SMIOC_TEXT) {
D("%s set text mode\n", __func__);
fp->f_op = &smem_log_fops;
} else if (arg == SMIOC_BINARY) {
D("%s set bin mode\n", __func__);
fp->f_op = &smem_log_bin_fops;
} else {
return -EINVAL;
}
break;
case SMIOC_SETLOG:
if (arg == SMIOC_LOG) {
if (inst[GEN].events)
fp->private_data = &inst[GEN];
else
return -ENODEV;
} else if (arg == SMIOC_STATIC_LOG) {
if (inst[STA].events)
fp->private_data = &inst[STA];
else
return -ENODEV;
} else {
return -EINVAL;
}
break;
}
return 0;
}
static struct miscdevice smem_log_dev = {
.minor = MISC_DYNAMIC_MINOR,
.name = "smem_log",
.fops = &smem_log_fops,
};
#if defined(CONFIG_DEBUG_FS)
#define SMEM_LOG_ITEM_PRINT_SIZE 160
#define EVENTS_PRINT_SIZE \
(SMEM_LOG_ITEM_PRINT_SIZE * SMEM_LOG_NUM_ENTRIES)
static uint32_t smem_log_timeout_ms;
module_param_named(timeout_ms, smem_log_timeout_ms,
int, S_IRUGO | S_IWUSR | S_IWGRP);
static int smem_log_debug_mask;
module_param_named(debug_mask, smem_log_debug_mask, int,
S_IRUGO | S_IWUSR | S_IWGRP);
#define DBG(x...) do {\
if (smem_log_debug_mask) \
printk(KERN_DEBUG x);\
} while (0)
static int update_read_avail(struct smem_log_inst *inst)
{
int curr_read_avail;
unsigned long flags = 0;
remote_spin_lock_irqsave(inst->remote_spinlock, flags);
curr_read_avail = (*inst->idx - inst->read_idx);
if (curr_read_avail < 0)
curr_read_avail = inst->num - inst->read_idx + *inst->idx;
DBG("%s: read = %d write = %d curr = %d last = %d\n", __func__,
inst->read_idx, *inst->idx, curr_read_avail, inst->last_read_avail);
if (curr_read_avail < inst->last_read_avail) {
if (inst->last_read_avail != inst->num)
pr_info("smem_log: skipping %d log entries\n",
inst->last_read_avail);
inst->read_idx = *inst->idx + 1;
inst->last_read_avail = inst->num - 1;
} else
inst->last_read_avail = curr_read_avail;
remote_spin_unlock_irqrestore(inst->remote_spinlock, flags);
DBG("%s: read = %d write = %d curr = %d last = %d\n", __func__,
inst->read_idx, *inst->idx, curr_read_avail, inst->last_read_avail);
return inst->last_read_avail;
}
static int _debug_dump(int log, char *buf, int max, uint32_t cont)
{
unsigned int idx;
int write_idx, read_avail = 0;
unsigned long flags;
int i = 0;
if (!inst[log].events)
return 0;
if (cont && update_read_avail(&inst[log]) == 0)
return 0;
remote_spin_lock_irqsave(inst[log].remote_spinlock, flags);
if (cont) {
idx = inst[log].read_idx;
write_idx = (inst[log].read_idx + inst[log].last_read_avail);
if (write_idx >= inst[log].num)
write_idx -= inst[log].num;
} else {
write_idx = *inst[log].idx;
idx = (write_idx + 1);
}
DBG("%s: read %d write %d idx %d num %d\n", __func__,
inst[log].read_idx, write_idx, idx, inst[log].num - 1);
while ((max - i) > 50) {
if ((inst[log].num - 1) < idx)
idx = 0;
if (idx == write_idx)
break;
if (inst[log].events[idx].identifier) {
i += scnprintf(buf + i, max - i,
"%08x %08x %08x %08x %08x\n",
inst[log].events[idx].identifier,
inst[log].events[idx].timetick,
inst[log].events[idx].data1,
inst[log].events[idx].data2,
inst[log].events[idx].data3);
}
idx++;
}
if (cont) {
inst[log].read_idx = idx;
read_avail = (write_idx - inst[log].read_idx);
if (read_avail < 0)
read_avail = inst->num - inst->read_idx + write_idx;
inst[log].last_read_avail = read_avail;
}
remote_spin_unlock_irqrestore(inst[log].remote_spinlock, flags);
DBG("%s: read %d write %d idx %d num %d\n", __func__,
inst[log].read_idx, write_idx, idx, inst[log].num);
return i;
}
static int _debug_dump_voters(char *buf, int max)
{
int k, i = 0;
find_voters();
i += scnprintf(buf + i, max - i, "Voters:\n");
for (k = 0; k < ARRAY_SIZE(voter_d3_syms); ++k)
if (voter_d3_syms[k].str)
i += scnprintf(buf + i, max - i, "%s ",
voter_d3_syms[k].str);
for (k = 0; k < ARRAY_SIZE(voter_d2_syms); ++k)
if (voter_d2_syms[k].str)
i += scnprintf(buf + i, max - i, "%s ",
voter_d2_syms[k].str);
i += scnprintf(buf + i, max - i, "\n");
return i;
}
static int _debug_dump_sym(int log, char *buf, int max, uint32_t cont)
{
unsigned int idx;
int write_idx, read_avail = 0;
unsigned long flags;
int i = 0;
char *proc;
char *sub;
char *id;
const char *sym = NULL;
uint32_t data[3];
uint32_t proc_val = 0;
uint32_t sub_val = 0;
uint32_t id_val = 0;
uint32_t id_only_val = 0;
uint32_t data1 = 0;
uint32_t data2 = 0;
uint32_t data3 = 0;
if (!inst[log].events)
return 0;
find_voters();
if (cont && update_read_avail(&inst[log]) == 0)
return 0;
remote_spin_lock_irqsave(inst[log].remote_spinlock, flags);
if (cont) {
idx = inst[log].read_idx;
write_idx = (inst[log].read_idx + inst[log].last_read_avail);
if (write_idx >= inst[log].num)
write_idx -= inst[log].num;
} else {
write_idx = *inst[log].idx;
idx = (write_idx + 1);
}
DBG("%s: read %d write %d idx %d num %d\n", __func__,
inst[log].read_idx, write_idx, idx, inst[log].num - 1);
for (; (max - i) > SMEM_LOG_ITEM_PRINT_SIZE; idx++) {
if (idx > (inst[log].num - 1))
idx = 0;
if (idx == write_idx)
break;
if (idx < inst[log].num) {
if (!inst[log].events[idx].identifier)
continue;
proc_val = PROC & inst[log].events[idx].identifier;
sub_val = SUB & inst[log].events[idx].identifier;
id_val = (SUB | ID) & inst[log].events[idx].identifier;
id_only_val = ID & inst[log].events[idx].identifier;
data1 = inst[log].events[idx].data1;
data2 = inst[log].events[idx].data2;
data3 = inst[log].events[idx].data3;
if (!(proc_val & SMEM_LOG_CONT)) {
i += scnprintf(buf + i, max - i, "\n");
proc = find_sym(ID_SYM, proc_val);
if (proc)
i += scnprintf(buf + i, max - i,
"%4s: ", proc);
else
i += scnprintf(buf + i, max - i,
"%04x: ",
PROC &
inst[log].events[idx].
identifier);
i += scnprintf(buf + i, max - i, "%10u ",
inst[log].events[idx].timetick);
sub = find_sym(BASE_SYM, sub_val);
if (sub)
i += scnprintf(buf + i, max - i,
"%9s: ", sub);
else
i += scnprintf(buf + i, max - i,
"%08x: ", sub_val);
id = find_sym(EVENT_SYM, id_val);
if (id)
i += scnprintf(buf + i, max - i,
"%11s: ", id);
else
i += scnprintf(buf + i, max - i,
"%08x: ", id_only_val);
}
if ((proc_val & SMEM_LOG_CONT) &&
(id_val == ONCRPC_LOG_EVENT_STD_CALL ||
id_val == ONCRPC_LOG_EVENT_STD_REPLY)) {
data[0] = data1;
data[1] = data2;
data[2] = data3;
i += scnprintf(buf + i, max - i,
" %.16s", (char *) data);
} else if (proc_val & SMEM_LOG_CONT) {
i += scnprintf(buf + i, max - i,
" %08x %08x %08x",
data1, data2, data3);
} else if (id_val == ONCRPC_LOG_EVENT_STD_CALL) {
sym = smd_rpc_get_sym(data2);
if (sym)
i += scnprintf(buf + i, max - i,
"xid:%4i %8s proc:%3i",
data1, sym, data3);
else
i += scnprintf(buf + i, max - i,
"xid:%4i %08x proc:%3i",
data1, data2, data3);
#if defined(CONFIG_MSM_N_WAY_SMSM)
} else if (id_val == DEM_STATE_CHANGE) {
if (data1 == 1) {
i += scnprintf(buf + i, max - i,
"MASTER: ");
sym = find_sym(DEM_STATE_MASTER_SYM,
data2);
} else if (data1 == 0) {
i += scnprintf(buf + i, max - i,
" SLAVE: ");
sym = find_sym(DEM_STATE_SLAVE_SYM,
data2);
} else {
i += scnprintf(buf + i, max - i,
"%x: ", data1);
sym = NULL;
}
if (sym)
i += scnprintf(buf + i, max - i,
"from:%s ", sym);
else
i += scnprintf(buf + i, max - i,
"from:0x%x ", data2);
if (data1 == 1)
sym = find_sym(DEM_STATE_MASTER_SYM,
data3);
else if (data1 == 0)
sym = find_sym(DEM_STATE_SLAVE_SYM,
data3);
else
sym = NULL;
if (sym)
i += scnprintf(buf + i, max - i,
"to:%s ", sym);
else
i += scnprintf(buf + i, max - i,
"to:0x%x ", data3);
} else if (id_val == DEM_STATE_MACHINE_ENTER) {
i += scnprintf(buf + i, max - i,
"swfi:%i timer:%i manexit:%i",
data1, data2, data3);
} else if (id_val == DEM_TIME_SYNC_REQUEST ||
id_val == DEM_TIME_SYNC_POLL ||
id_val == DEM_TIME_SYNC_INIT) {
sym = find_sym(SMSM_ENTRY_TYPE_SYM,
data1);
if (sym)
i += scnprintf(buf + i, max - i,
"hostid:%s", sym);
else
i += scnprintf(buf + i, max - i,
"hostid:%x", data1);
} else if (id_val == DEM_TIME_SYNC_START ||
id_val == DEM_TIME_SYNC_SEND_VALUE) {
unsigned mask = 0x1;
unsigned tmp = 0;
if (id_val == DEM_TIME_SYNC_START)
i += scnprintf(buf + i, max - i,
"req:");
else
i += scnprintf(buf + i, max - i,
"pol:");
while (mask) {
if (mask & data1) {
sym = find_sym(
SMSM_ENTRY_TYPE_SYM,
tmp);
if (sym)
i += scnprintf(buf + i,
max - i,
"%s ",
sym);
else
i += scnprintf(buf + i,
max - i,
"%i ",
tmp);
}
mask <<= 1;
tmp++;
}
if (id_val == DEM_TIME_SYNC_SEND_VALUE)
i += scnprintf(buf + i, max - i,
"tick:%x", data2);
} else if (id_val == DEM_SMSM_ISR) {
unsigned vals[] = {data2, data3};
unsigned j;
unsigned mask;
unsigned tmp;
unsigned once;
sym = find_sym(SMSM_ENTRY_TYPE_SYM,
data1);
if (sym)
i += scnprintf(buf + i, max - i,
"%s ", sym);
else
i += scnprintf(buf + i, max - i,
"%x ", data1);
for (j = 0; j < ARRAY_SIZE(vals); ++j) {
i += scnprintf(buf + i, max - i, "[");
mask = 0x80000000;
once = 0;
while (mask) {
tmp = vals[j] & mask;
mask >>= 1;
if (!tmp)
continue;
sym = find_sym(SMSM_STATE_SYM,
tmp);
if (once)
i += scnprintf(buf + i,
max - i,
" ");
if (sym)
i += scnprintf(buf + i,
max - i,
"%s",
sym);
else
i += scnprintf(buf + i,
max - i,
"0x%x",
tmp);
once = 1;
}
i += scnprintf(buf + i, max - i, "] ");
}
#else
} else if (id_val == DEMAPPS_WAKEUP_REASON) {
unsigned mask = 0x80000000;
unsigned tmp = 0;
while (mask) {
tmp = data1 & mask;
mask >>= 1;
if (!tmp)
continue;
sym = find_sym(WAKEUP_SYM, tmp);
if (sym)
i += scnprintf(buf + i,
max - i,
"%s ",
sym);
else
i += scnprintf(buf + i,
max - i,
"%08x ",
tmp);
}
i += scnprintf(buf + i, max - i,
"%08x %08x", data2, data3);
} else if (id_val == DEMMOD_APPS_WAKEUP_INT) {
sym = find_sym(WAKEUP_INT_SYM, data1);
if (sym)
i += scnprintf(buf + i, max - i,
"%s %08x %08x",
sym, data2, data3);
else
i += scnprintf(buf + i, max - i,
"%08x %08x %08x",
data1, data2, data3);
} else if (id_val == DEM_NO_SLEEP ||
id_val == NO_SLEEP_NEW) {
unsigned vals[] = {data3, data2};
unsigned j;
unsigned mask;
unsigned tmp;
unsigned once;
i += scnprintf(buf + i, max - i, "%08x ",
data1);
i += scnprintf(buf + i, max - i, "[");
once = 0;
for (j = 0; j < ARRAY_SIZE(vals); ++j) {
mask = 0x00000001;
while (mask) {
tmp = vals[j] & mask;
mask <<= 1;
if (!tmp)
continue;
if (j == 0)
sym = find_sym(
VOTER_D3_SYM,
tmp);
else
sym = find_sym(
VOTER_D2_SYM,
tmp);
if (once)
i += scnprintf(buf + i,
max - i,
" ");
if (sym)
i += scnprintf(buf + i,
max - i,
"%s",
sym);
else
i += scnprintf(buf + i,
max - i,
"%08x",
tmp);
once = 1;
}
}
i += scnprintf(buf + i, max - i, "] ");
#endif
} else if (id_val == SMEM_LOG_EVENT_CB) {
unsigned vals[] = {data2, data3};
unsigned j;
unsigned mask;
unsigned tmp;
unsigned once;
i += scnprintf(buf + i, max - i, "%08x ",
data1);
for (j = 0; j < ARRAY_SIZE(vals); ++j) {
i += scnprintf(buf + i, max - i, "[");
mask = 0x80000000;
once = 0;
while (mask) {
tmp = vals[j] & mask;
mask >>= 1;
if (!tmp)
continue;
sym = find_sym(SMSM_SYM, tmp);
if (once)
i += scnprintf(buf + i,
max - i,
" ");
if (sym)
i += scnprintf(buf + i,
max - i,
"%s",
sym);
else
i += scnprintf(buf + i,
max - i,
"%08x",
tmp);
once = 1;
}
i += scnprintf(buf + i, max - i, "] ");
}
} else {
i += scnprintf(buf + i, max - i,
"%08x %08x %08x",
data1, data2, data3);
}
}
}
if (cont) {
inst[log].read_idx = idx;
read_avail = (write_idx - inst[log].read_idx);
if (read_avail < 0)
read_avail = inst->num - inst->read_idx + write_idx;
inst[log].last_read_avail = read_avail;
}
remote_spin_unlock_irqrestore(inst[log].remote_spinlock, flags);
DBG("%s: read %d write %d idx %d num %d\n", __func__,
inst[log].read_idx, write_idx, idx, inst[log].num);
return i;
}
static int debug_dump(char *buf, int max, uint32_t cont)
{
int r;
while (cont) {
update_read_avail(&inst[GEN]);
r = wait_event_interruptible_timeout(inst[GEN].read_wait,
inst[GEN].last_read_avail,
smem_log_timeout_ms *
HZ / 1000);
DBG("%s: read available %d\n", __func__,
inst[GEN].last_read_avail);
if (r < 0)
return 0;
else if (inst[GEN].last_read_avail)
break;
}
return _debug_dump(GEN, buf, max, cont);
}
static int debug_dump_sym(char *buf, int max, uint32_t cont)
{
int r;
while (cont) {
update_read_avail(&inst[GEN]);
r = wait_event_interruptible_timeout(inst[GEN].read_wait,
inst[GEN].last_read_avail,
smem_log_timeout_ms *
HZ / 1000);
DBG("%s: readavailable %d\n", __func__,
inst[GEN].last_read_avail);
if (r < 0)
return 0;
else if (inst[GEN].last_read_avail)
break;
}
return _debug_dump_sym(GEN, buf, max, cont);
}
static int debug_dump_static(char *buf, int max, uint32_t cont)
{
int r;
while (cont) {
update_read_avail(&inst[STA]);
r = wait_event_interruptible_timeout(inst[STA].read_wait,
inst[STA].last_read_avail,
smem_log_timeout_ms *
HZ / 1000);
DBG("%s: readavailable %d\n", __func__,
inst[STA].last_read_avail);
if (r < 0)
return 0;
else if (inst[STA].last_read_avail)
break;
}
return _debug_dump(STA, buf, max, cont);
}
static int debug_dump_static_sym(char *buf, int max, uint32_t cont)
{
int r;
while (cont) {
update_read_avail(&inst[STA]);
r = wait_event_interruptible_timeout(inst[STA].read_wait,
inst[STA].last_read_avail,
smem_log_timeout_ms *
HZ / 1000);
DBG("%s: readavailable %d\n", __func__,
inst[STA].last_read_avail);
if (r < 0)
return 0;
else if (inst[STA].last_read_avail)
break;
}
return _debug_dump_sym(STA, buf, max, cont);
}
static int debug_dump_power(char *buf, int max, uint32_t cont)
{
int r;
while (cont) {
update_read_avail(&inst[POW]);
r = wait_event_interruptible_timeout(inst[POW].read_wait,
inst[POW].last_read_avail,
smem_log_timeout_ms *
HZ / 1000);
DBG("%s: readavailable %d\n", __func__,
inst[POW].last_read_avail);
if (r < 0)
return 0;
else if (inst[POW].last_read_avail)
break;
}
return _debug_dump(POW, buf, max, cont);
}
static int debug_dump_power_sym(char *buf, int max, uint32_t cont)
{
int r;
while (cont) {
update_read_avail(&inst[POW]);
r = wait_event_interruptible_timeout(inst[POW].read_wait,
inst[POW].last_read_avail,
smem_log_timeout_ms *
HZ / 1000);
DBG("%s: readavailable %d\n", __func__,
inst[POW].last_read_avail);
if (r < 0)
return 0;
else if (inst[POW].last_read_avail)
break;
}
return _debug_dump_sym(POW, buf, max, cont);
}
static int debug_dump_voters(char *buf, int max, uint32_t cont)
{
return _debug_dump_voters(buf, max);
}
static char debug_buffer[EVENTS_PRINT_SIZE];
static ssize_t debug_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
int r;
static int bsize;
int (*fill)(char *, int, uint32_t) = file->private_data;
if (!(*ppos))
bsize = fill(debug_buffer, EVENTS_PRINT_SIZE, 0);
DBG("%s: count %d ppos %d\n", __func__, count, (unsigned int)*ppos);
r = simple_read_from_buffer(buf, count, ppos, debug_buffer,
bsize);
return r;
}
static ssize_t debug_read_cont(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
int (*fill)(char *, int, uint32_t) = file->private_data;
char *buffer = kmalloc(count, GFP_KERNEL);
int bsize;
if (!buffer)
return -ENOMEM;
bsize = fill(buffer, count, 1);
DBG("%s: count %d bsize %d\n", __func__, count, bsize);
if (copy_to_user(buf, buffer, bsize)) {
kfree(buffer);
return -EFAULT;
}
kfree(buffer);
return bsize;
}
static int debug_open(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
return 0;
}
static const struct file_operations debug_ops = {
.read = debug_read,
.open = debug_open,
};
static const struct file_operations debug_ops_cont = {
.read = debug_read_cont,
.open = debug_open,
};
static void debug_create(const char *name, mode_t mode,
struct dentry *dent,
int (*fill)(char *buf, int max, uint32_t cont),
const struct file_operations *fops)
{
debugfs_create_file(name, mode, dent, fill, fops);
}
static void smem_log_debugfs_init(void)
{
struct dentry *dent;
dent = debugfs_create_dir("smem_log", 0);
if (IS_ERR(dent))
return;
debug_create("dump", 0444, dent, debug_dump, &debug_ops);
debug_create("dump_sym", 0444, dent, debug_dump_sym, &debug_ops);
debug_create("dump_static", 0444, dent, debug_dump_static, &debug_ops);
debug_create("dump_static_sym", 0444, dent,
debug_dump_static_sym, &debug_ops);
debug_create("dump_power", 0444, dent, debug_dump_power, &debug_ops);
debug_create("dump_power_sym", 0444, dent,
debug_dump_power_sym, &debug_ops);
debug_create("dump_voters", 0444, dent,
debug_dump_voters, &debug_ops);
debug_create("dump_cont", 0444, dent, debug_dump, &debug_ops_cont);
debug_create("dump_sym_cont", 0444, dent,
debug_dump_sym, &debug_ops_cont);
debug_create("dump_static_cont", 0444, dent,
debug_dump_static, &debug_ops_cont);
debug_create("dump_static_sym_cont", 0444, dent,
debug_dump_static_sym, &debug_ops_cont);
debug_create("dump_power_cont", 0444, dent,
debug_dump_power, &debug_ops_cont);
debug_create("dump_power_sym_cont", 0444, dent,
debug_dump_power_sym, &debug_ops_cont);
smem_log_timeout_ms = 500;
smem_log_debug_mask = 0;
}
#else
static void smem_log_debugfs_init(void) {}
#endif
static int smem_log_initialize(void)
{
int ret;
ret = _smem_log_init();
if (ret < 0) {
pr_err("%s: init failed %d\n", __func__, ret);
return ret;
}
ret = misc_register(&smem_log_dev);
if (ret < 0) {
pr_err("%s: device register failed %d\n", __func__, ret);
return ret;
}
smem_log_enable = 1;
smem_log_initialized = 1;
smem_log_debugfs_init();
return ret;
}
static int modem_notifier(struct notifier_block *this,
unsigned long code,
void *_cmd)
{
switch (code) {
case MODEM_NOTIFIER_SMSM_INIT:
if (!smem_log_initialized)
smem_log_initialize();
break;
default:
break;
}
return NOTIFY_DONE;
}
static struct notifier_block nb = {
.notifier_call = modem_notifier,
};
static int __init smem_log_init(void)
{
return modem_register_notifier(&nb);
}
module_init(smem_log_init);
MODULE_DESCRIPTION("smem log");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
BruceBushby/linux-4.1 | drivers/ata/libata-sff.c | 720 | 85867 | /*
* libata-sff.c - helper library for PCI IDE BMDMA
*
* Maintained by: Tejun Heo <tj@kernel.org>
* Please ALWAYS copy linux-ide@vger.kernel.org
* on emails.
*
* Copyright 2003-2006 Red Hat, Inc. All rights reserved.
* Copyright 2003-2006 Jeff Garzik
*
*
* 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 from http://www.t13.org/ and
* http://www.sata-io.org/
*
*/
#include <linux/kernel.h>
#include <linux/gfp.h>
#include <linux/pci.h>
#include <linux/module.h>
#include <linux/libata.h>
#include <linux/highmem.h>
#include "libata.h"
static struct workqueue_struct *ata_sff_wq;
const struct ata_port_operations ata_sff_port_ops = {
.inherits = &ata_base_port_ops,
.qc_prep = ata_noop_qc_prep,
.qc_issue = ata_sff_qc_issue,
.qc_fill_rtf = ata_sff_qc_fill_rtf,
.freeze = ata_sff_freeze,
.thaw = ata_sff_thaw,
.prereset = ata_sff_prereset,
.softreset = ata_sff_softreset,
.hardreset = sata_sff_hardreset,
.postreset = ata_sff_postreset,
.error_handler = ata_sff_error_handler,
.sff_dev_select = ata_sff_dev_select,
.sff_check_status = ata_sff_check_status,
.sff_tf_load = ata_sff_tf_load,
.sff_tf_read = ata_sff_tf_read,
.sff_exec_command = ata_sff_exec_command,
.sff_data_xfer = ata_sff_data_xfer,
.sff_drain_fifo = ata_sff_drain_fifo,
.lost_interrupt = ata_sff_lost_interrupt,
};
EXPORT_SYMBOL_GPL(ata_sff_port_ops);
/**
* ata_sff_check_status - Read device status reg & clear interrupt
* @ap: port where the device is
*
* Reads ATA taskfile status register for currently-selected device
* and return its value. This also clears pending interrupts
* from this device
*
* LOCKING:
* Inherited from caller.
*/
u8 ata_sff_check_status(struct ata_port *ap)
{
return ioread8(ap->ioaddr.status_addr);
}
EXPORT_SYMBOL_GPL(ata_sff_check_status);
/**
* ata_sff_altstatus - Read device alternate status reg
* @ap: port where the device is
*
* Reads ATA taskfile alternate status register for
* currently-selected device and return its value.
*
* Note: may NOT be used as the check_altstatus() entry in
* ata_port_operations.
*
* LOCKING:
* Inherited from caller.
*/
static u8 ata_sff_altstatus(struct ata_port *ap)
{
if (ap->ops->sff_check_altstatus)
return ap->ops->sff_check_altstatus(ap);
return ioread8(ap->ioaddr.altstatus_addr);
}
/**
* ata_sff_irq_status - Check if the device is busy
* @ap: port where the device is
*
* Determine if the port is currently busy. Uses altstatus
* if available in order to avoid clearing shared IRQ status
* when finding an IRQ source. Non ctl capable devices don't
* share interrupt lines fortunately for us.
*
* LOCKING:
* Inherited from caller.
*/
static u8 ata_sff_irq_status(struct ata_port *ap)
{
u8 status;
if (ap->ops->sff_check_altstatus || ap->ioaddr.altstatus_addr) {
status = ata_sff_altstatus(ap);
/* Not us: We are busy */
if (status & ATA_BUSY)
return status;
}
/* Clear INTRQ latch */
status = ap->ops->sff_check_status(ap);
return status;
}
/**
* ata_sff_sync - Flush writes
* @ap: Port to wait for.
*
* CAUTION:
* If we have an mmio device with no ctl and no altstatus
* method this will fail. No such devices are known to exist.
*
* LOCKING:
* Inherited from caller.
*/
static void ata_sff_sync(struct ata_port *ap)
{
if (ap->ops->sff_check_altstatus)
ap->ops->sff_check_altstatus(ap);
else if (ap->ioaddr.altstatus_addr)
ioread8(ap->ioaddr.altstatus_addr);
}
/**
* ata_sff_pause - Flush writes and wait 400nS
* @ap: Port to pause for.
*
* CAUTION:
* If we have an mmio device with no ctl and no altstatus
* method this will fail. No such devices are known to exist.
*
* LOCKING:
* Inherited from caller.
*/
void ata_sff_pause(struct ata_port *ap)
{
ata_sff_sync(ap);
ndelay(400);
}
EXPORT_SYMBOL_GPL(ata_sff_pause);
/**
* ata_sff_dma_pause - Pause before commencing DMA
* @ap: Port to pause for.
*
* Perform I/O fencing and ensure sufficient cycle delays occur
* for the HDMA1:0 transition
*/
void ata_sff_dma_pause(struct ata_port *ap)
{
if (ap->ops->sff_check_altstatus || ap->ioaddr.altstatus_addr) {
/* An altstatus read will cause the needed delay without
messing up the IRQ status */
ata_sff_altstatus(ap);
return;
}
/* There are no DMA controllers without ctl. BUG here to ensure
we never violate the HDMA1:0 transition timing and risk
corruption. */
BUG();
}
EXPORT_SYMBOL_GPL(ata_sff_dma_pause);
/**
* ata_sff_busy_sleep - sleep until BSY clears, or timeout
* @ap: port containing status register to be polled
* @tmout_pat: impatience timeout in msecs
* @tmout: overall timeout in msecs
*
* Sleep until ATA Status register bit BSY clears,
* or a timeout occurs.
*
* LOCKING:
* Kernel thread context (may sleep).
*
* RETURNS:
* 0 on success, -errno otherwise.
*/
int ata_sff_busy_sleep(struct ata_port *ap,
unsigned long tmout_pat, unsigned long tmout)
{
unsigned long timer_start, timeout;
u8 status;
status = ata_sff_busy_wait(ap, ATA_BUSY, 300);
timer_start = jiffies;
timeout = ata_deadline(timer_start, tmout_pat);
while (status != 0xff && (status & ATA_BUSY) &&
time_before(jiffies, timeout)) {
ata_msleep(ap, 50);
status = ata_sff_busy_wait(ap, ATA_BUSY, 3);
}
if (status != 0xff && (status & ATA_BUSY))
ata_port_warn(ap,
"port is slow to respond, please be patient (Status 0x%x)\n",
status);
timeout = ata_deadline(timer_start, tmout);
while (status != 0xff && (status & ATA_BUSY) &&
time_before(jiffies, timeout)) {
ata_msleep(ap, 50);
status = ap->ops->sff_check_status(ap);
}
if (status == 0xff)
return -ENODEV;
if (status & ATA_BUSY) {
ata_port_err(ap,
"port failed to respond (%lu secs, Status 0x%x)\n",
DIV_ROUND_UP(tmout, 1000), status);
return -EBUSY;
}
return 0;
}
EXPORT_SYMBOL_GPL(ata_sff_busy_sleep);
static int ata_sff_check_ready(struct ata_link *link)
{
u8 status = link->ap->ops->sff_check_status(link->ap);
return ata_check_ready(status);
}
/**
* ata_sff_wait_ready - sleep until BSY clears, or timeout
* @link: SFF link to wait ready status for
* @deadline: deadline jiffies for the operation
*
* Sleep until ATA Status register bit BSY clears, or timeout
* occurs.
*
* LOCKING:
* Kernel thread context (may sleep).
*
* RETURNS:
* 0 on success, -errno otherwise.
*/
int ata_sff_wait_ready(struct ata_link *link, unsigned long deadline)
{
return ata_wait_ready(link, deadline, ata_sff_check_ready);
}
EXPORT_SYMBOL_GPL(ata_sff_wait_ready);
/**
* ata_sff_set_devctl - Write device control reg
* @ap: port where the device is
* @ctl: value to write
*
* Writes ATA taskfile device control register.
*
* Note: may NOT be used as the sff_set_devctl() entry in
* ata_port_operations.
*
* LOCKING:
* Inherited from caller.
*/
static void ata_sff_set_devctl(struct ata_port *ap, u8 ctl)
{
if (ap->ops->sff_set_devctl)
ap->ops->sff_set_devctl(ap, ctl);
else
iowrite8(ctl, ap->ioaddr.ctl_addr);
}
/**
* ata_sff_dev_select - Select device 0/1 on ATA bus
* @ap: ATA channel to manipulate
* @device: ATA device (numbered from zero) to select
*
* Use the method defined in the ATA specification to
* make either device 0, or device 1, active on the
* ATA channel. Works with both PIO and MMIO.
*
* May be used as the dev_select() entry in ata_port_operations.
*
* LOCKING:
* caller.
*/
void ata_sff_dev_select(struct ata_port *ap, unsigned int device)
{
u8 tmp;
if (device == 0)
tmp = ATA_DEVICE_OBS;
else
tmp = ATA_DEVICE_OBS | ATA_DEV1;
iowrite8(tmp, ap->ioaddr.device_addr);
ata_sff_pause(ap); /* needed; also flushes, for mmio */
}
EXPORT_SYMBOL_GPL(ata_sff_dev_select);
/**
* ata_dev_select - Select device 0/1 on ATA bus
* @ap: ATA channel to manipulate
* @device: ATA device (numbered from zero) to select
* @wait: non-zero to wait for Status register BSY bit to clear
* @can_sleep: non-zero if context allows sleeping
*
* Use the method defined in the ATA specification to
* make either device 0, or device 1, active on the
* ATA channel.
*
* This is a high-level version of ata_sff_dev_select(), which
* additionally provides the services of inserting the proper
* pauses and status polling, where needed.
*
* LOCKING:
* caller.
*/
static void ata_dev_select(struct ata_port *ap, unsigned int device,
unsigned int wait, unsigned int can_sleep)
{
if (ata_msg_probe(ap))
ata_port_info(ap, "ata_dev_select: ENTER, device %u, wait %u\n",
device, wait);
if (wait)
ata_wait_idle(ap);
ap->ops->sff_dev_select(ap, device);
if (wait) {
if (can_sleep && ap->link.device[device].class == ATA_DEV_ATAPI)
ata_msleep(ap, 150);
ata_wait_idle(ap);
}
}
/**
* ata_sff_irq_on - Enable interrupts on a port.
* @ap: Port on which interrupts are enabled.
*
* Enable interrupts on a legacy IDE device using MMIO or PIO,
* wait for idle, clear any pending interrupts.
*
* Note: may NOT be used as the sff_irq_on() entry in
* ata_port_operations.
*
* LOCKING:
* Inherited from caller.
*/
void ata_sff_irq_on(struct ata_port *ap)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
if (ap->ops->sff_irq_on) {
ap->ops->sff_irq_on(ap);
return;
}
ap->ctl &= ~ATA_NIEN;
ap->last_ctl = ap->ctl;
if (ap->ops->sff_set_devctl || ioaddr->ctl_addr)
ata_sff_set_devctl(ap, ap->ctl);
ata_wait_idle(ap);
if (ap->ops->sff_irq_clear)
ap->ops->sff_irq_clear(ap);
}
EXPORT_SYMBOL_GPL(ata_sff_irq_on);
/**
* ata_sff_tf_load - send taskfile registers to host controller
* @ap: Port to which output is sent
* @tf: ATA taskfile register set
*
* Outputs ATA taskfile to standard ATA host controller.
*
* LOCKING:
* Inherited from caller.
*/
void ata_sff_tf_load(struct ata_port *ap, const struct ata_taskfile *tf)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
unsigned int is_addr = tf->flags & ATA_TFLAG_ISADDR;
if (tf->ctl != ap->last_ctl) {
if (ioaddr->ctl_addr)
iowrite8(tf->ctl, ioaddr->ctl_addr);
ap->last_ctl = tf->ctl;
ata_wait_idle(ap);
}
if (is_addr && (tf->flags & ATA_TFLAG_LBA48)) {
WARN_ON_ONCE(!ioaddr->ctl_addr);
iowrite8(tf->hob_feature, ioaddr->feature_addr);
iowrite8(tf->hob_nsect, ioaddr->nsect_addr);
iowrite8(tf->hob_lbal, ioaddr->lbal_addr);
iowrite8(tf->hob_lbam, ioaddr->lbam_addr);
iowrite8(tf->hob_lbah, ioaddr->lbah_addr);
VPRINTK("hob: feat 0x%X nsect 0x%X, lba 0x%X 0x%X 0x%X\n",
tf->hob_feature,
tf->hob_nsect,
tf->hob_lbal,
tf->hob_lbam,
tf->hob_lbah);
}
if (is_addr) {
iowrite8(tf->feature, ioaddr->feature_addr);
iowrite8(tf->nsect, ioaddr->nsect_addr);
iowrite8(tf->lbal, ioaddr->lbal_addr);
iowrite8(tf->lbam, ioaddr->lbam_addr);
iowrite8(tf->lbah, ioaddr->lbah_addr);
VPRINTK("feat 0x%X nsect 0x%X lba 0x%X 0x%X 0x%X\n",
tf->feature,
tf->nsect,
tf->lbal,
tf->lbam,
tf->lbah);
}
if (tf->flags & ATA_TFLAG_DEVICE) {
iowrite8(tf->device, ioaddr->device_addr);
VPRINTK("device 0x%X\n", tf->device);
}
ata_wait_idle(ap);
}
EXPORT_SYMBOL_GPL(ata_sff_tf_load);
/**
* ata_sff_tf_read - input device's ATA taskfile shadow registers
* @ap: Port from which input is read
* @tf: ATA taskfile register set for storing input
*
* Reads ATA taskfile registers for currently-selected device
* into @tf. Assumes the device has a fully SFF compliant task file
* layout and behaviour. If you device does not (eg has a different
* status method) then you will need to provide a replacement tf_read
*
* LOCKING:
* Inherited from caller.
*/
void ata_sff_tf_read(struct ata_port *ap, struct ata_taskfile *tf)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
tf->command = ata_sff_check_status(ap);
tf->feature = ioread8(ioaddr->error_addr);
tf->nsect = ioread8(ioaddr->nsect_addr);
tf->lbal = ioread8(ioaddr->lbal_addr);
tf->lbam = ioread8(ioaddr->lbam_addr);
tf->lbah = ioread8(ioaddr->lbah_addr);
tf->device = ioread8(ioaddr->device_addr);
if (tf->flags & ATA_TFLAG_LBA48) {
if (likely(ioaddr->ctl_addr)) {
iowrite8(tf->ctl | ATA_HOB, ioaddr->ctl_addr);
tf->hob_feature = ioread8(ioaddr->error_addr);
tf->hob_nsect = ioread8(ioaddr->nsect_addr);
tf->hob_lbal = ioread8(ioaddr->lbal_addr);
tf->hob_lbam = ioread8(ioaddr->lbam_addr);
tf->hob_lbah = ioread8(ioaddr->lbah_addr);
iowrite8(tf->ctl, ioaddr->ctl_addr);
ap->last_ctl = tf->ctl;
} else
WARN_ON_ONCE(1);
}
}
EXPORT_SYMBOL_GPL(ata_sff_tf_read);
/**
* ata_sff_exec_command - issue ATA command to host controller
* @ap: port to which command is being issued
* @tf: ATA taskfile register set
*
* Issues ATA command, with proper synchronization with interrupt
* handler / other threads.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
void ata_sff_exec_command(struct ata_port *ap, const struct ata_taskfile *tf)
{
DPRINTK("ata%u: cmd 0x%X\n", ap->print_id, tf->command);
iowrite8(tf->command, ap->ioaddr.command_addr);
ata_sff_pause(ap);
}
EXPORT_SYMBOL_GPL(ata_sff_exec_command);
/**
* ata_tf_to_host - issue ATA taskfile to host controller
* @ap: port to which command is being issued
* @tf: ATA taskfile register set
*
* Issues ATA taskfile register set to ATA host controller,
* with proper synchronization with interrupt handler and
* other threads.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
static inline void ata_tf_to_host(struct ata_port *ap,
const struct ata_taskfile *tf)
{
ap->ops->sff_tf_load(ap, tf);
ap->ops->sff_exec_command(ap, tf);
}
/**
* ata_sff_data_xfer - Transfer data by PIO
* @dev: device to target
* @buf: data buffer
* @buflen: buffer length
* @rw: read/write
*
* Transfer data from/to the device data register by PIO.
*
* LOCKING:
* Inherited from caller.
*
* RETURNS:
* Bytes consumed.
*/
unsigned int ata_sff_data_xfer(struct ata_device *dev, unsigned char *buf,
unsigned int buflen, int rw)
{
struct ata_port *ap = dev->link->ap;
void __iomem *data_addr = ap->ioaddr.data_addr;
unsigned int words = buflen >> 1;
/* Transfer multiple of 2 bytes */
if (rw == READ)
ioread16_rep(data_addr, buf, words);
else
iowrite16_rep(data_addr, buf, words);
/* Transfer trailing byte, if any. */
if (unlikely(buflen & 0x01)) {
unsigned char pad[2] = { };
/* Point buf to the tail of buffer */
buf += buflen - 1;
/*
* Use io*16_rep() accessors here as well to avoid pointlessly
* swapping bytes to and from on the big endian machines...
*/
if (rw == READ) {
ioread16_rep(data_addr, pad, 1);
*buf = pad[0];
} else {
pad[0] = *buf;
iowrite16_rep(data_addr, pad, 1);
}
words++;
}
return words << 1;
}
EXPORT_SYMBOL_GPL(ata_sff_data_xfer);
/**
* ata_sff_data_xfer32 - Transfer data by PIO
* @dev: device to target
* @buf: data buffer
* @buflen: buffer length
* @rw: read/write
*
* Transfer data from/to the device data register by PIO using 32bit
* I/O operations.
*
* LOCKING:
* Inherited from caller.
*
* RETURNS:
* Bytes consumed.
*/
unsigned int ata_sff_data_xfer32(struct ata_device *dev, unsigned char *buf,
unsigned int buflen, int rw)
{
struct ata_port *ap = dev->link->ap;
void __iomem *data_addr = ap->ioaddr.data_addr;
unsigned int words = buflen >> 2;
int slop = buflen & 3;
if (!(ap->pflags & ATA_PFLAG_PIO32))
return ata_sff_data_xfer(dev, buf, buflen, rw);
/* Transfer multiple of 4 bytes */
if (rw == READ)
ioread32_rep(data_addr, buf, words);
else
iowrite32_rep(data_addr, buf, words);
/* Transfer trailing bytes, if any */
if (unlikely(slop)) {
unsigned char pad[4] = { };
/* Point buf to the tail of buffer */
buf += buflen - slop;
/*
* Use io*_rep() accessors here as well to avoid pointlessly
* swapping bytes to and from on the big endian machines...
*/
if (rw == READ) {
if (slop < 3)
ioread16_rep(data_addr, pad, 1);
else
ioread32_rep(data_addr, pad, 1);
memcpy(buf, pad, slop);
} else {
memcpy(pad, buf, slop);
if (slop < 3)
iowrite16_rep(data_addr, pad, 1);
else
iowrite32_rep(data_addr, pad, 1);
}
}
return (buflen + 1) & ~1;
}
EXPORT_SYMBOL_GPL(ata_sff_data_xfer32);
/**
* ata_sff_data_xfer_noirq - Transfer data by PIO
* @dev: device to target
* @buf: data buffer
* @buflen: buffer length
* @rw: read/write
*
* Transfer data from/to the device data register by PIO. Do the
* transfer with interrupts disabled.
*
* LOCKING:
* Inherited from caller.
*
* RETURNS:
* Bytes consumed.
*/
unsigned int ata_sff_data_xfer_noirq(struct ata_device *dev, unsigned char *buf,
unsigned int buflen, int rw)
{
unsigned long flags;
unsigned int consumed;
local_irq_save(flags);
consumed = ata_sff_data_xfer32(dev, buf, buflen, rw);
local_irq_restore(flags);
return consumed;
}
EXPORT_SYMBOL_GPL(ata_sff_data_xfer_noirq);
/**
* ata_pio_sector - Transfer a sector of data.
* @qc: Command on going
*
* Transfer qc->sect_size bytes of data from/to the ATA device.
*
* LOCKING:
* Inherited from caller.
*/
static void ata_pio_sector(struct ata_queued_cmd *qc)
{
int do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
struct ata_port *ap = qc->ap;
struct page *page;
unsigned int offset;
unsigned char *buf;
if (qc->curbytes == qc->nbytes - qc->sect_size)
ap->hsm_task_state = HSM_ST_LAST;
page = sg_page(qc->cursg);
offset = qc->cursg->offset + qc->cursg_ofs;
/* get the current page and offset */
page = nth_page(page, (offset >> PAGE_SHIFT));
offset %= PAGE_SIZE;
DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
if (PageHighMem(page)) {
unsigned long flags;
/* FIXME: use a bounce buffer */
local_irq_save(flags);
buf = kmap_atomic(page);
/* do the actual data transfer */
ap->ops->sff_data_xfer(qc->dev, buf + offset, qc->sect_size,
do_write);
kunmap_atomic(buf);
local_irq_restore(flags);
} else {
buf = page_address(page);
ap->ops->sff_data_xfer(qc->dev, buf + offset, qc->sect_size,
do_write);
}
if (!do_write && !PageSlab(page))
flush_dcache_page(page);
qc->curbytes += qc->sect_size;
qc->cursg_ofs += qc->sect_size;
if (qc->cursg_ofs == qc->cursg->length) {
qc->cursg = sg_next(qc->cursg);
qc->cursg_ofs = 0;
}
}
/**
* ata_pio_sectors - Transfer one or many sectors.
* @qc: Command on going
*
* Transfer one or many sectors of data from/to the
* ATA device for the DRQ request.
*
* LOCKING:
* Inherited from caller.
*/
static void ata_pio_sectors(struct ata_queued_cmd *qc)
{
if (is_multi_taskfile(&qc->tf)) {
/* READ/WRITE MULTIPLE */
unsigned int nsect;
WARN_ON_ONCE(qc->dev->multi_count == 0);
nsect = min((qc->nbytes - qc->curbytes) / qc->sect_size,
qc->dev->multi_count);
while (nsect--)
ata_pio_sector(qc);
} else
ata_pio_sector(qc);
ata_sff_sync(qc->ap); /* flush */
}
/**
* atapi_send_cdb - Write CDB bytes to hardware
* @ap: Port to which ATAPI device is attached.
* @qc: Taskfile currently active
*
* When device has indicated its readiness to accept
* a CDB, this function is called. Send the CDB.
*
* LOCKING:
* caller.
*/
static void atapi_send_cdb(struct ata_port *ap, struct ata_queued_cmd *qc)
{
/* send SCSI cdb */
DPRINTK("send cdb\n");
WARN_ON_ONCE(qc->dev->cdb_len < 12);
ap->ops->sff_data_xfer(qc->dev, qc->cdb, qc->dev->cdb_len, 1);
ata_sff_sync(ap);
/* FIXME: If the CDB is for DMA do we need to do the transition delay
or is bmdma_start guaranteed to do it ? */
switch (qc->tf.protocol) {
case ATAPI_PROT_PIO:
ap->hsm_task_state = HSM_ST;
break;
case ATAPI_PROT_NODATA:
ap->hsm_task_state = HSM_ST_LAST;
break;
#ifdef CONFIG_ATA_BMDMA
case ATAPI_PROT_DMA:
ap->hsm_task_state = HSM_ST_LAST;
/* initiate bmdma */
ap->ops->bmdma_start(qc);
break;
#endif /* CONFIG_ATA_BMDMA */
default:
BUG();
}
}
/**
* __atapi_pio_bytes - Transfer data from/to the ATAPI device.
* @qc: Command on going
* @bytes: number of bytes
*
* Transfer Transfer data from/to the ATAPI device.
*
* LOCKING:
* Inherited from caller.
*
*/
static int __atapi_pio_bytes(struct ata_queued_cmd *qc, unsigned int bytes)
{
int rw = (qc->tf.flags & ATA_TFLAG_WRITE) ? WRITE : READ;
struct ata_port *ap = qc->ap;
struct ata_device *dev = qc->dev;
struct ata_eh_info *ehi = &dev->link->eh_info;
struct scatterlist *sg;
struct page *page;
unsigned char *buf;
unsigned int offset, count, consumed;
next_sg:
sg = qc->cursg;
if (unlikely(!sg)) {
ata_ehi_push_desc(ehi, "unexpected or too much trailing data "
"buf=%u cur=%u bytes=%u",
qc->nbytes, qc->curbytes, bytes);
return -1;
}
page = sg_page(sg);
offset = sg->offset + qc->cursg_ofs;
/* get the current page and offset */
page = nth_page(page, (offset >> PAGE_SHIFT));
offset %= PAGE_SIZE;
/* don't overrun current sg */
count = min(sg->length - qc->cursg_ofs, bytes);
/* don't cross page boundaries */
count = min(count, (unsigned int)PAGE_SIZE - offset);
DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
if (PageHighMem(page)) {
unsigned long flags;
/* FIXME: use bounce buffer */
local_irq_save(flags);
buf = kmap_atomic(page);
/* do the actual data transfer */
consumed = ap->ops->sff_data_xfer(dev, buf + offset,
count, rw);
kunmap_atomic(buf);
local_irq_restore(flags);
} else {
buf = page_address(page);
consumed = ap->ops->sff_data_xfer(dev, buf + offset,
count, rw);
}
bytes -= min(bytes, consumed);
qc->curbytes += count;
qc->cursg_ofs += count;
if (qc->cursg_ofs == sg->length) {
qc->cursg = sg_next(qc->cursg);
qc->cursg_ofs = 0;
}
/*
* There used to be a WARN_ON_ONCE(qc->cursg && count != consumed);
* Unfortunately __atapi_pio_bytes doesn't know enough to do the WARN
* check correctly as it doesn't know if it is the last request being
* made. Somebody should implement a proper sanity check.
*/
if (bytes)
goto next_sg;
return 0;
}
/**
* atapi_pio_bytes - Transfer data from/to the ATAPI device.
* @qc: Command on going
*
* Transfer Transfer data from/to the ATAPI device.
*
* LOCKING:
* Inherited from caller.
*/
static void atapi_pio_bytes(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_device *dev = qc->dev;
struct ata_eh_info *ehi = &dev->link->eh_info;
unsigned int ireason, bc_lo, bc_hi, bytes;
int i_write, do_write = (qc->tf.flags & ATA_TFLAG_WRITE) ? 1 : 0;
/* Abuse qc->result_tf for temp storage of intermediate TF
* here to save some kernel stack usage.
* For normal completion, qc->result_tf is not relevant. For
* error, qc->result_tf is later overwritten by ata_qc_complete().
* So, the correctness of qc->result_tf is not affected.
*/
ap->ops->sff_tf_read(ap, &qc->result_tf);
ireason = qc->result_tf.nsect;
bc_lo = qc->result_tf.lbam;
bc_hi = qc->result_tf.lbah;
bytes = (bc_hi << 8) | bc_lo;
/* shall be cleared to zero, indicating xfer of data */
if (unlikely(ireason & ATAPI_COD))
goto atapi_check;
/* make sure transfer direction matches expected */
i_write = ((ireason & ATAPI_IO) == 0) ? 1 : 0;
if (unlikely(do_write != i_write))
goto atapi_check;
if (unlikely(!bytes))
goto atapi_check;
VPRINTK("ata%u: xfering %d bytes\n", ap->print_id, bytes);
if (unlikely(__atapi_pio_bytes(qc, bytes)))
goto err_out;
ata_sff_sync(ap); /* flush */
return;
atapi_check:
ata_ehi_push_desc(ehi, "ATAPI check failed (ireason=0x%x bytes=%u)",
ireason, bytes);
err_out:
qc->err_mask |= AC_ERR_HSM;
ap->hsm_task_state = HSM_ST_ERR;
}
/**
* ata_hsm_ok_in_wq - Check if the qc can be handled in the workqueue.
* @ap: the target ata_port
* @qc: qc on going
*
* RETURNS:
* 1 if ok in workqueue, 0 otherwise.
*/
static inline int ata_hsm_ok_in_wq(struct ata_port *ap,
struct ata_queued_cmd *qc)
{
if (qc->tf.flags & ATA_TFLAG_POLLING)
return 1;
if (ap->hsm_task_state == HSM_ST_FIRST) {
if (qc->tf.protocol == ATA_PROT_PIO &&
(qc->tf.flags & ATA_TFLAG_WRITE))
return 1;
if (ata_is_atapi(qc->tf.protocol) &&
!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
return 1;
}
return 0;
}
/**
* ata_hsm_qc_complete - finish a qc running on standard HSM
* @qc: Command to complete
* @in_wq: 1 if called from workqueue, 0 otherwise
*
* Finish @qc which is running on standard HSM.
*
* LOCKING:
* If @in_wq is zero, spin_lock_irqsave(host lock).
* Otherwise, none on entry and grabs host lock.
*/
static void ata_hsm_qc_complete(struct ata_queued_cmd *qc, int in_wq)
{
struct ata_port *ap = qc->ap;
unsigned long flags;
if (ap->ops->error_handler) {
if (in_wq) {
spin_lock_irqsave(ap->lock, flags);
/* EH might have kicked in while host lock is
* released.
*/
qc = ata_qc_from_tag(ap, qc->tag);
if (qc) {
if (likely(!(qc->err_mask & AC_ERR_HSM))) {
ata_sff_irq_on(ap);
ata_qc_complete(qc);
} else
ata_port_freeze(ap);
}
spin_unlock_irqrestore(ap->lock, flags);
} else {
if (likely(!(qc->err_mask & AC_ERR_HSM)))
ata_qc_complete(qc);
else
ata_port_freeze(ap);
}
} else {
if (in_wq) {
spin_lock_irqsave(ap->lock, flags);
ata_sff_irq_on(ap);
ata_qc_complete(qc);
spin_unlock_irqrestore(ap->lock, flags);
} else
ata_qc_complete(qc);
}
}
/**
* ata_sff_hsm_move - move the HSM to the next state.
* @ap: the target ata_port
* @qc: qc on going
* @status: current device status
* @in_wq: 1 if called from workqueue, 0 otherwise
*
* RETURNS:
* 1 when poll next status needed, 0 otherwise.
*/
int ata_sff_hsm_move(struct ata_port *ap, struct ata_queued_cmd *qc,
u8 status, int in_wq)
{
struct ata_link *link = qc->dev->link;
struct ata_eh_info *ehi = &link->eh_info;
unsigned long flags = 0;
int poll_next;
WARN_ON_ONCE((qc->flags & ATA_QCFLAG_ACTIVE) == 0);
/* Make sure ata_sff_qc_issue() does not throw things
* like DMA polling into the workqueue. Notice that
* in_wq is not equivalent to (qc->tf.flags & ATA_TFLAG_POLLING).
*/
WARN_ON_ONCE(in_wq != ata_hsm_ok_in_wq(ap, qc));
fsm_start:
DPRINTK("ata%u: protocol %d task_state %d (dev_stat 0x%X)\n",
ap->print_id, qc->tf.protocol, ap->hsm_task_state, status);
switch (ap->hsm_task_state) {
case HSM_ST_FIRST:
/* Send first data block or PACKET CDB */
/* If polling, we will stay in the work queue after
* sending the data. Otherwise, interrupt handler
* takes over after sending the data.
*/
poll_next = (qc->tf.flags & ATA_TFLAG_POLLING);
/* check device status */
if (unlikely((status & ATA_DRQ) == 0)) {
/* handle BSY=0, DRQ=0 as error */
if (likely(status & (ATA_ERR | ATA_DF)))
/* device stops HSM for abort/error */
qc->err_mask |= AC_ERR_DEV;
else {
/* HSM violation. Let EH handle this */
ata_ehi_push_desc(ehi,
"ST_FIRST: !(DRQ|ERR|DF)");
qc->err_mask |= AC_ERR_HSM;
}
ap->hsm_task_state = HSM_ST_ERR;
goto fsm_start;
}
/* Device should not ask for data transfer (DRQ=1)
* when it finds something wrong.
* We ignore DRQ here and stop the HSM by
* changing hsm_task_state to HSM_ST_ERR and
* let the EH abort the command or reset the device.
*/
if (unlikely(status & (ATA_ERR | ATA_DF))) {
/* Some ATAPI tape drives forget to clear the ERR bit
* when doing the next command (mostly request sense).
* We ignore ERR here to workaround and proceed sending
* the CDB.
*/
if (!(qc->dev->horkage & ATA_HORKAGE_STUCK_ERR)) {
ata_ehi_push_desc(ehi, "ST_FIRST: "
"DRQ=1 with device error, "
"dev_stat 0x%X", status);
qc->err_mask |= AC_ERR_HSM;
ap->hsm_task_state = HSM_ST_ERR;
goto fsm_start;
}
}
/* Send the CDB (atapi) or the first data block (ata pio out).
* During the state transition, interrupt handler shouldn't
* be invoked before the data transfer is complete and
* hsm_task_state is changed. Hence, the following locking.
*/
if (in_wq)
spin_lock_irqsave(ap->lock, flags);
if (qc->tf.protocol == ATA_PROT_PIO) {
/* PIO data out protocol.
* send first data block.
*/
/* ata_pio_sectors() might change the state
* to HSM_ST_LAST. so, the state is changed here
* before ata_pio_sectors().
*/
ap->hsm_task_state = HSM_ST;
ata_pio_sectors(qc);
} else
/* send CDB */
atapi_send_cdb(ap, qc);
if (in_wq)
spin_unlock_irqrestore(ap->lock, flags);
/* if polling, ata_sff_pio_task() handles the rest.
* otherwise, interrupt handler takes over from here.
*/
break;
case HSM_ST:
/* complete command or read/write the data register */
if (qc->tf.protocol == ATAPI_PROT_PIO) {
/* ATAPI PIO protocol */
if ((status & ATA_DRQ) == 0) {
/* No more data to transfer or device error.
* Device error will be tagged in HSM_ST_LAST.
*/
ap->hsm_task_state = HSM_ST_LAST;
goto fsm_start;
}
/* Device should not ask for data transfer (DRQ=1)
* when it finds something wrong.
* We ignore DRQ here and stop the HSM by
* changing hsm_task_state to HSM_ST_ERR and
* let the EH abort the command or reset the device.
*/
if (unlikely(status & (ATA_ERR | ATA_DF))) {
ata_ehi_push_desc(ehi, "ST-ATAPI: "
"DRQ=1 with device error, "
"dev_stat 0x%X", status);
qc->err_mask |= AC_ERR_HSM;
ap->hsm_task_state = HSM_ST_ERR;
goto fsm_start;
}
atapi_pio_bytes(qc);
if (unlikely(ap->hsm_task_state == HSM_ST_ERR))
/* bad ireason reported by device */
goto fsm_start;
} else {
/* ATA PIO protocol */
if (unlikely((status & ATA_DRQ) == 0)) {
/* handle BSY=0, DRQ=0 as error */
if (likely(status & (ATA_ERR | ATA_DF))) {
/* device stops HSM for abort/error */
qc->err_mask |= AC_ERR_DEV;
/* If diagnostic failed and this is
* IDENTIFY, it's likely a phantom
* device. Mark hint.
*/
if (qc->dev->horkage &
ATA_HORKAGE_DIAGNOSTIC)
qc->err_mask |=
AC_ERR_NODEV_HINT;
} else {
/* HSM violation. Let EH handle this.
* Phantom devices also trigger this
* condition. Mark hint.
*/
ata_ehi_push_desc(ehi, "ST-ATA: "
"DRQ=0 without device error, "
"dev_stat 0x%X", status);
qc->err_mask |= AC_ERR_HSM |
AC_ERR_NODEV_HINT;
}
ap->hsm_task_state = HSM_ST_ERR;
goto fsm_start;
}
/* For PIO reads, some devices may ask for
* data transfer (DRQ=1) alone with ERR=1.
* We respect DRQ here and transfer one
* block of junk data before changing the
* hsm_task_state to HSM_ST_ERR.
*
* For PIO writes, ERR=1 DRQ=1 doesn't make
* sense since the data block has been
* transferred to the device.
*/
if (unlikely(status & (ATA_ERR | ATA_DF))) {
/* data might be corrputed */
qc->err_mask |= AC_ERR_DEV;
if (!(qc->tf.flags & ATA_TFLAG_WRITE)) {
ata_pio_sectors(qc);
status = ata_wait_idle(ap);
}
if (status & (ATA_BUSY | ATA_DRQ)) {
ata_ehi_push_desc(ehi, "ST-ATA: "
"BUSY|DRQ persists on ERR|DF, "
"dev_stat 0x%X", status);
qc->err_mask |= AC_ERR_HSM;
}
/* There are oddball controllers with
* status register stuck at 0x7f and
* lbal/m/h at zero which makes it
* pass all other presence detection
* mechanisms we have. Set NODEV_HINT
* for it. Kernel bz#7241.
*/
if (status == 0x7f)
qc->err_mask |= AC_ERR_NODEV_HINT;
/* ata_pio_sectors() might change the
* state to HSM_ST_LAST. so, the state
* is changed after ata_pio_sectors().
*/
ap->hsm_task_state = HSM_ST_ERR;
goto fsm_start;
}
ata_pio_sectors(qc);
if (ap->hsm_task_state == HSM_ST_LAST &&
(!(qc->tf.flags & ATA_TFLAG_WRITE))) {
/* all data read */
status = ata_wait_idle(ap);
goto fsm_start;
}
}
poll_next = 1;
break;
case HSM_ST_LAST:
if (unlikely(!ata_ok(status))) {
qc->err_mask |= __ac_err_mask(status);
ap->hsm_task_state = HSM_ST_ERR;
goto fsm_start;
}
/* no more data to transfer */
DPRINTK("ata%u: dev %u command complete, drv_stat 0x%x\n",
ap->print_id, qc->dev->devno, status);
WARN_ON_ONCE(qc->err_mask & (AC_ERR_DEV | AC_ERR_HSM));
ap->hsm_task_state = HSM_ST_IDLE;
/* complete taskfile transaction */
ata_hsm_qc_complete(qc, in_wq);
poll_next = 0;
break;
case HSM_ST_ERR:
ap->hsm_task_state = HSM_ST_IDLE;
/* complete taskfile transaction */
ata_hsm_qc_complete(qc, in_wq);
poll_next = 0;
break;
default:
poll_next = 0;
BUG();
}
return poll_next;
}
EXPORT_SYMBOL_GPL(ata_sff_hsm_move);
void ata_sff_queue_work(struct work_struct *work)
{
queue_work(ata_sff_wq, work);
}
EXPORT_SYMBOL_GPL(ata_sff_queue_work);
void ata_sff_queue_delayed_work(struct delayed_work *dwork, unsigned long delay)
{
queue_delayed_work(ata_sff_wq, dwork, delay);
}
EXPORT_SYMBOL_GPL(ata_sff_queue_delayed_work);
void ata_sff_queue_pio_task(struct ata_link *link, unsigned long delay)
{
struct ata_port *ap = link->ap;
WARN_ON((ap->sff_pio_task_link != NULL) &&
(ap->sff_pio_task_link != link));
ap->sff_pio_task_link = link;
/* may fail if ata_sff_flush_pio_task() in progress */
ata_sff_queue_delayed_work(&ap->sff_pio_task, msecs_to_jiffies(delay));
}
EXPORT_SYMBOL_GPL(ata_sff_queue_pio_task);
void ata_sff_flush_pio_task(struct ata_port *ap)
{
DPRINTK("ENTER\n");
cancel_delayed_work_sync(&ap->sff_pio_task);
/*
* We wanna reset the HSM state to IDLE. If we do so without
* grabbing the port lock, critical sections protected by it which
* expect the HSM state to stay stable may get surprised. For
* example, we may set IDLE in between the time
* __ata_sff_port_intr() checks for HSM_ST_IDLE and before it calls
* ata_sff_hsm_move() causing ata_sff_hsm_move() to BUG().
*/
spin_lock_irq(ap->lock);
ap->hsm_task_state = HSM_ST_IDLE;
spin_unlock_irq(ap->lock);
ap->sff_pio_task_link = NULL;
if (ata_msg_ctl(ap))
ata_port_dbg(ap, "%s: EXIT\n", __func__);
}
static void ata_sff_pio_task(struct work_struct *work)
{
struct ata_port *ap =
container_of(work, struct ata_port, sff_pio_task.work);
struct ata_link *link = ap->sff_pio_task_link;
struct ata_queued_cmd *qc;
u8 status;
int poll_next;
BUG_ON(ap->sff_pio_task_link == NULL);
/* qc can be NULL if timeout occurred */
qc = ata_qc_from_tag(ap, link->active_tag);
if (!qc) {
ap->sff_pio_task_link = NULL;
return;
}
fsm_start:
WARN_ON_ONCE(ap->hsm_task_state == HSM_ST_IDLE);
/*
* This is purely heuristic. This is a fast path.
* Sometimes when we enter, BSY will be cleared in
* a chk-status or two. If not, the drive is probably seeking
* or something. Snooze for a couple msecs, then
* chk-status again. If still busy, queue delayed work.
*/
status = ata_sff_busy_wait(ap, ATA_BUSY, 5);
if (status & ATA_BUSY) {
ata_msleep(ap, 2);
status = ata_sff_busy_wait(ap, ATA_BUSY, 10);
if (status & ATA_BUSY) {
ata_sff_queue_pio_task(link, ATA_SHORT_PAUSE);
return;
}
}
/*
* hsm_move() may trigger another command to be processed.
* clean the link beforehand.
*/
ap->sff_pio_task_link = NULL;
/* move the HSM */
poll_next = ata_sff_hsm_move(ap, qc, status, 1);
/* another command or interrupt handler
* may be running at this point.
*/
if (poll_next)
goto fsm_start;
}
/**
* ata_sff_qc_issue - issue taskfile to a SFF controller
* @qc: command to issue to device
*
* This function issues a PIO or NODATA command to a SFF
* controller.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* Zero on success, AC_ERR_* mask on failure
*/
unsigned int ata_sff_qc_issue(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_link *link = qc->dev->link;
/* Use polling pio if the LLD doesn't handle
* interrupt driven pio and atapi CDB interrupt.
*/
if (ap->flags & ATA_FLAG_PIO_POLLING)
qc->tf.flags |= ATA_TFLAG_POLLING;
/* select the device */
ata_dev_select(ap, qc->dev->devno, 1, 0);
/* start the command */
switch (qc->tf.protocol) {
case ATA_PROT_NODATA:
if (qc->tf.flags & ATA_TFLAG_POLLING)
ata_qc_set_polling(qc);
ata_tf_to_host(ap, &qc->tf);
ap->hsm_task_state = HSM_ST_LAST;
if (qc->tf.flags & ATA_TFLAG_POLLING)
ata_sff_queue_pio_task(link, 0);
break;
case ATA_PROT_PIO:
if (qc->tf.flags & ATA_TFLAG_POLLING)
ata_qc_set_polling(qc);
ata_tf_to_host(ap, &qc->tf);
if (qc->tf.flags & ATA_TFLAG_WRITE) {
/* PIO data out protocol */
ap->hsm_task_state = HSM_ST_FIRST;
ata_sff_queue_pio_task(link, 0);
/* always send first data block using the
* ata_sff_pio_task() codepath.
*/
} else {
/* PIO data in protocol */
ap->hsm_task_state = HSM_ST;
if (qc->tf.flags & ATA_TFLAG_POLLING)
ata_sff_queue_pio_task(link, 0);
/* if polling, ata_sff_pio_task() handles the
* rest. otherwise, interrupt handler takes
* over from here.
*/
}
break;
case ATAPI_PROT_PIO:
case ATAPI_PROT_NODATA:
if (qc->tf.flags & ATA_TFLAG_POLLING)
ata_qc_set_polling(qc);
ata_tf_to_host(ap, &qc->tf);
ap->hsm_task_state = HSM_ST_FIRST;
/* send cdb by polling if no cdb interrupt */
if ((!(qc->dev->flags & ATA_DFLAG_CDB_INTR)) ||
(qc->tf.flags & ATA_TFLAG_POLLING))
ata_sff_queue_pio_task(link, 0);
break;
default:
WARN_ON_ONCE(1);
return AC_ERR_SYSTEM;
}
return 0;
}
EXPORT_SYMBOL_GPL(ata_sff_qc_issue);
/**
* ata_sff_qc_fill_rtf - fill result TF using ->sff_tf_read
* @qc: qc to fill result TF for
*
* @qc is finished and result TF needs to be filled. Fill it
* using ->sff_tf_read.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* true indicating that result TF is successfully filled.
*/
bool ata_sff_qc_fill_rtf(struct ata_queued_cmd *qc)
{
qc->ap->ops->sff_tf_read(qc->ap, &qc->result_tf);
return true;
}
EXPORT_SYMBOL_GPL(ata_sff_qc_fill_rtf);
static unsigned int ata_sff_idle_irq(struct ata_port *ap)
{
ap->stats.idle_irq++;
#ifdef ATA_IRQ_TRAP
if ((ap->stats.idle_irq % 1000) == 0) {
ap->ops->sff_check_status(ap);
if (ap->ops->sff_irq_clear)
ap->ops->sff_irq_clear(ap);
ata_port_warn(ap, "irq trap\n");
return 1;
}
#endif
return 0; /* irq not handled */
}
static unsigned int __ata_sff_port_intr(struct ata_port *ap,
struct ata_queued_cmd *qc,
bool hsmv_on_idle)
{
u8 status;
VPRINTK("ata%u: protocol %d task_state %d\n",
ap->print_id, qc->tf.protocol, ap->hsm_task_state);
/* Check whether we are expecting interrupt in this state */
switch (ap->hsm_task_state) {
case HSM_ST_FIRST:
/* Some pre-ATAPI-4 devices assert INTRQ
* at this state when ready to receive CDB.
*/
/* Check the ATA_DFLAG_CDB_INTR flag is enough here.
* The flag was turned on only for atapi devices. No
* need to check ata_is_atapi(qc->tf.protocol) again.
*/
if (!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
return ata_sff_idle_irq(ap);
break;
case HSM_ST_IDLE:
return ata_sff_idle_irq(ap);
default:
break;
}
/* check main status, clearing INTRQ if needed */
status = ata_sff_irq_status(ap);
if (status & ATA_BUSY) {
if (hsmv_on_idle) {
/* BMDMA engine is already stopped, we're screwed */
qc->err_mask |= AC_ERR_HSM;
ap->hsm_task_state = HSM_ST_ERR;
} else
return ata_sff_idle_irq(ap);
}
/* clear irq events */
if (ap->ops->sff_irq_clear)
ap->ops->sff_irq_clear(ap);
ata_sff_hsm_move(ap, qc, status, 0);
return 1; /* irq handled */
}
/**
* ata_sff_port_intr - Handle SFF port interrupt
* @ap: Port on which interrupt arrived (possibly...)
* @qc: Taskfile currently active in engine
*
* Handle port interrupt for given queued command.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* One if interrupt was handled, zero if not (shared irq).
*/
unsigned int ata_sff_port_intr(struct ata_port *ap, struct ata_queued_cmd *qc)
{
return __ata_sff_port_intr(ap, qc, false);
}
EXPORT_SYMBOL_GPL(ata_sff_port_intr);
static inline irqreturn_t __ata_sff_interrupt(int irq, void *dev_instance,
unsigned int (*port_intr)(struct ata_port *, struct ata_queued_cmd *))
{
struct ata_host *host = dev_instance;
bool retried = false;
unsigned int i;
unsigned int handled, idle, polling;
unsigned long flags;
/* TODO: make _irqsave conditional on x86 PCI IDE legacy mode */
spin_lock_irqsave(&host->lock, flags);
retry:
handled = idle = polling = 0;
for (i = 0; i < host->n_ports; i++) {
struct ata_port *ap = host->ports[i];
struct ata_queued_cmd *qc;
qc = ata_qc_from_tag(ap, ap->link.active_tag);
if (qc) {
if (!(qc->tf.flags & ATA_TFLAG_POLLING))
handled |= port_intr(ap, qc);
else
polling |= 1 << i;
} else
idle |= 1 << i;
}
/*
* If no port was expecting IRQ but the controller is actually
* asserting IRQ line, nobody cared will ensue. Check IRQ
* pending status if available and clear spurious IRQ.
*/
if (!handled && !retried) {
bool retry = false;
for (i = 0; i < host->n_ports; i++) {
struct ata_port *ap = host->ports[i];
if (polling & (1 << i))
continue;
if (!ap->ops->sff_irq_check ||
!ap->ops->sff_irq_check(ap))
continue;
if (idle & (1 << i)) {
ap->ops->sff_check_status(ap);
if (ap->ops->sff_irq_clear)
ap->ops->sff_irq_clear(ap);
} else {
/* clear INTRQ and check if BUSY cleared */
if (!(ap->ops->sff_check_status(ap) & ATA_BUSY))
retry |= true;
/*
* With command in flight, we can't do
* sff_irq_clear() w/o racing with completion.
*/
}
}
if (retry) {
retried = true;
goto retry;
}
}
spin_unlock_irqrestore(&host->lock, flags);
return IRQ_RETVAL(handled);
}
/**
* ata_sff_interrupt - Default SFF ATA host interrupt handler
* @irq: irq line (unused)
* @dev_instance: pointer to our ata_host information structure
*
* Default interrupt handler for PCI IDE devices. Calls
* ata_sff_port_intr() for each port that is not disabled.
*
* LOCKING:
* Obtains host lock during operation.
*
* RETURNS:
* IRQ_NONE or IRQ_HANDLED.
*/
irqreturn_t ata_sff_interrupt(int irq, void *dev_instance)
{
return __ata_sff_interrupt(irq, dev_instance, ata_sff_port_intr);
}
EXPORT_SYMBOL_GPL(ata_sff_interrupt);
/**
* ata_sff_lost_interrupt - Check for an apparent lost interrupt
* @ap: port that appears to have timed out
*
* Called from the libata error handlers when the core code suspects
* an interrupt has been lost. If it has complete anything we can and
* then return. Interface must support altstatus for this faster
* recovery to occur.
*
* Locking:
* Caller holds host lock
*/
void ata_sff_lost_interrupt(struct ata_port *ap)
{
u8 status;
struct ata_queued_cmd *qc;
/* Only one outstanding command per SFF channel */
qc = ata_qc_from_tag(ap, ap->link.active_tag);
/* We cannot lose an interrupt on a non-existent or polled command */
if (!qc || qc->tf.flags & ATA_TFLAG_POLLING)
return;
/* See if the controller thinks it is still busy - if so the command
isn't a lost IRQ but is still in progress */
status = ata_sff_altstatus(ap);
if (status & ATA_BUSY)
return;
/* There was a command running, we are no longer busy and we have
no interrupt. */
ata_port_warn(ap, "lost interrupt (Status 0x%x)\n",
status);
/* Run the host interrupt logic as if the interrupt had not been
lost */
ata_sff_port_intr(ap, qc);
}
EXPORT_SYMBOL_GPL(ata_sff_lost_interrupt);
/**
* ata_sff_freeze - Freeze SFF controller port
* @ap: port to freeze
*
* Freeze SFF controller port.
*
* LOCKING:
* Inherited from caller.
*/
void ata_sff_freeze(struct ata_port *ap)
{
ap->ctl |= ATA_NIEN;
ap->last_ctl = ap->ctl;
if (ap->ops->sff_set_devctl || ap->ioaddr.ctl_addr)
ata_sff_set_devctl(ap, ap->ctl);
/* Under certain circumstances, some controllers raise IRQ on
* ATA_NIEN manipulation. Also, many controllers fail to mask
* previously pending IRQ on ATA_NIEN assertion. Clear it.
*/
ap->ops->sff_check_status(ap);
if (ap->ops->sff_irq_clear)
ap->ops->sff_irq_clear(ap);
}
EXPORT_SYMBOL_GPL(ata_sff_freeze);
/**
* ata_sff_thaw - Thaw SFF controller port
* @ap: port to thaw
*
* Thaw SFF controller port.
*
* LOCKING:
* Inherited from caller.
*/
void ata_sff_thaw(struct ata_port *ap)
{
/* clear & re-enable interrupts */
ap->ops->sff_check_status(ap);
if (ap->ops->sff_irq_clear)
ap->ops->sff_irq_clear(ap);
ata_sff_irq_on(ap);
}
EXPORT_SYMBOL_GPL(ata_sff_thaw);
/**
* ata_sff_prereset - prepare SFF link for reset
* @link: SFF link to be reset
* @deadline: deadline jiffies for the operation
*
* SFF link @link is about to be reset. Initialize it. It first
* calls ata_std_prereset() and wait for !BSY if the port is
* being softreset.
*
* LOCKING:
* Kernel thread context (may sleep)
*
* RETURNS:
* 0 on success, -errno otherwise.
*/
int ata_sff_prereset(struct ata_link *link, unsigned long deadline)
{
struct ata_eh_context *ehc = &link->eh_context;
int rc;
rc = ata_std_prereset(link, deadline);
if (rc)
return rc;
/* if we're about to do hardreset, nothing more to do */
if (ehc->i.action & ATA_EH_HARDRESET)
return 0;
/* wait for !BSY if we don't know that no device is attached */
if (!ata_link_offline(link)) {
rc = ata_sff_wait_ready(link, deadline);
if (rc && rc != -ENODEV) {
ata_link_warn(link,
"device not ready (errno=%d), forcing hardreset\n",
rc);
ehc->i.action |= ATA_EH_HARDRESET;
}
}
return 0;
}
EXPORT_SYMBOL_GPL(ata_sff_prereset);
/**
* ata_devchk - PATA device presence detection
* @ap: ATA channel to examine
* @device: Device to examine (starting at zero)
*
* This technique was originally described in
* Hale Landis's ATADRVR (www.ata-atapi.com), and
* later found its way into the ATA/ATAPI spec.
*
* Write a pattern to the ATA shadow registers,
* and if a device is present, it will respond by
* correctly storing and echoing back the
* ATA shadow register contents.
*
* LOCKING:
* caller.
*/
static unsigned int ata_devchk(struct ata_port *ap, unsigned int device)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
u8 nsect, lbal;
ap->ops->sff_dev_select(ap, device);
iowrite8(0x55, ioaddr->nsect_addr);
iowrite8(0xaa, ioaddr->lbal_addr);
iowrite8(0xaa, ioaddr->nsect_addr);
iowrite8(0x55, ioaddr->lbal_addr);
iowrite8(0x55, ioaddr->nsect_addr);
iowrite8(0xaa, ioaddr->lbal_addr);
nsect = ioread8(ioaddr->nsect_addr);
lbal = ioread8(ioaddr->lbal_addr);
if ((nsect == 0x55) && (lbal == 0xaa))
return 1; /* we found a device */
return 0; /* nothing found */
}
/**
* ata_sff_dev_classify - Parse returned ATA device signature
* @dev: ATA device to classify (starting at zero)
* @present: device seems present
* @r_err: Value of error register on completion
*
* After an event -- SRST, E.D.D., or SATA COMRESET -- occurs,
* an ATA/ATAPI-defined set of values is placed in the ATA
* shadow registers, indicating the results of device detection
* and diagnostics.
*
* Select the ATA device, and read the values from the ATA shadow
* registers. Then parse according to the Error register value,
* and the spec-defined values examined by ata_dev_classify().
*
* LOCKING:
* caller.
*
* RETURNS:
* Device type - %ATA_DEV_ATA, %ATA_DEV_ATAPI or %ATA_DEV_NONE.
*/
unsigned int ata_sff_dev_classify(struct ata_device *dev, int present,
u8 *r_err)
{
struct ata_port *ap = dev->link->ap;
struct ata_taskfile tf;
unsigned int class;
u8 err;
ap->ops->sff_dev_select(ap, dev->devno);
memset(&tf, 0, sizeof(tf));
ap->ops->sff_tf_read(ap, &tf);
err = tf.feature;
if (r_err)
*r_err = err;
/* see if device passed diags: continue and warn later */
if (err == 0)
/* diagnostic fail : do nothing _YET_ */
dev->horkage |= ATA_HORKAGE_DIAGNOSTIC;
else if (err == 1)
/* do nothing */ ;
else if ((dev->devno == 0) && (err == 0x81))
/* do nothing */ ;
else
return ATA_DEV_NONE;
/* determine if device is ATA or ATAPI */
class = ata_dev_classify(&tf);
if (class == ATA_DEV_UNKNOWN) {
/* If the device failed diagnostic, it's likely to
* have reported incorrect device signature too.
* Assume ATA device if the device seems present but
* device signature is invalid with diagnostic
* failure.
*/
if (present && (dev->horkage & ATA_HORKAGE_DIAGNOSTIC))
class = ATA_DEV_ATA;
else
class = ATA_DEV_NONE;
} else if ((class == ATA_DEV_ATA) &&
(ap->ops->sff_check_status(ap) == 0))
class = ATA_DEV_NONE;
return class;
}
EXPORT_SYMBOL_GPL(ata_sff_dev_classify);
/**
* ata_sff_wait_after_reset - wait for devices to become ready after reset
* @link: SFF link which is just reset
* @devmask: mask of present devices
* @deadline: deadline jiffies for the operation
*
* Wait devices attached to SFF @link to become ready after
* reset. It contains preceding 150ms wait to avoid accessing TF
* status register too early.
*
* LOCKING:
* Kernel thread context (may sleep).
*
* RETURNS:
* 0 on success, -ENODEV if some or all of devices in @devmask
* don't seem to exist. -errno on other errors.
*/
int ata_sff_wait_after_reset(struct ata_link *link, unsigned int devmask,
unsigned long deadline)
{
struct ata_port *ap = link->ap;
struct ata_ioports *ioaddr = &ap->ioaddr;
unsigned int dev0 = devmask & (1 << 0);
unsigned int dev1 = devmask & (1 << 1);
int rc, ret = 0;
ata_msleep(ap, ATA_WAIT_AFTER_RESET);
/* always check readiness of the master device */
rc = ata_sff_wait_ready(link, deadline);
/* -ENODEV means the odd clown forgot the D7 pulldown resistor
* and TF status is 0xff, bail out on it too.
*/
if (rc)
return rc;
/* if device 1 was found in ata_devchk, wait for register
* access briefly, then wait for BSY to clear.
*/
if (dev1) {
int i;
ap->ops->sff_dev_select(ap, 1);
/* Wait for register access. Some ATAPI devices fail
* to set nsect/lbal after reset, so don't waste too
* much time on it. We're gonna wait for !BSY anyway.
*/
for (i = 0; i < 2; i++) {
u8 nsect, lbal;
nsect = ioread8(ioaddr->nsect_addr);
lbal = ioread8(ioaddr->lbal_addr);
if ((nsect == 1) && (lbal == 1))
break;
ata_msleep(ap, 50); /* give drive a breather */
}
rc = ata_sff_wait_ready(link, deadline);
if (rc) {
if (rc != -ENODEV)
return rc;
ret = rc;
}
}
/* is all this really necessary? */
ap->ops->sff_dev_select(ap, 0);
if (dev1)
ap->ops->sff_dev_select(ap, 1);
if (dev0)
ap->ops->sff_dev_select(ap, 0);
return ret;
}
EXPORT_SYMBOL_GPL(ata_sff_wait_after_reset);
static int ata_bus_softreset(struct ata_port *ap, unsigned int devmask,
unsigned long deadline)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
DPRINTK("ata%u: bus reset via SRST\n", ap->print_id);
if (ap->ioaddr.ctl_addr) {
/* software reset. causes dev0 to be selected */
iowrite8(ap->ctl, ioaddr->ctl_addr);
udelay(20); /* FIXME: flush */
iowrite8(ap->ctl | ATA_SRST, ioaddr->ctl_addr);
udelay(20); /* FIXME: flush */
iowrite8(ap->ctl, ioaddr->ctl_addr);
ap->last_ctl = ap->ctl;
}
/* wait the port to become ready */
return ata_sff_wait_after_reset(&ap->link, devmask, deadline);
}
/**
* ata_sff_softreset - reset host port via ATA SRST
* @link: ATA link to reset
* @classes: resulting classes of attached devices
* @deadline: deadline jiffies for the operation
*
* Reset host port using ATA SRST.
*
* LOCKING:
* Kernel thread context (may sleep)
*
* RETURNS:
* 0 on success, -errno otherwise.
*/
int ata_sff_softreset(struct ata_link *link, unsigned int *classes,
unsigned long deadline)
{
struct ata_port *ap = link->ap;
unsigned int slave_possible = ap->flags & ATA_FLAG_SLAVE_POSS;
unsigned int devmask = 0;
int rc;
u8 err;
DPRINTK("ENTER\n");
/* determine if device 0/1 are present */
if (ata_devchk(ap, 0))
devmask |= (1 << 0);
if (slave_possible && ata_devchk(ap, 1))
devmask |= (1 << 1);
/* select device 0 again */
ap->ops->sff_dev_select(ap, 0);
/* issue bus reset */
DPRINTK("about to softreset, devmask=%x\n", devmask);
rc = ata_bus_softreset(ap, devmask, deadline);
/* if link is occupied, -ENODEV too is an error */
if (rc && (rc != -ENODEV || sata_scr_valid(link))) {
ata_link_err(link, "SRST failed (errno=%d)\n", rc);
return rc;
}
/* determine by signature whether we have ATA or ATAPI devices */
classes[0] = ata_sff_dev_classify(&link->device[0],
devmask & (1 << 0), &err);
if (slave_possible && err != 0x81)
classes[1] = ata_sff_dev_classify(&link->device[1],
devmask & (1 << 1), &err);
DPRINTK("EXIT, classes[0]=%u [1]=%u\n", classes[0], classes[1]);
return 0;
}
EXPORT_SYMBOL_GPL(ata_sff_softreset);
/**
* sata_sff_hardreset - reset host port via SATA phy reset
* @link: link to reset
* @class: resulting class of attached device
* @deadline: deadline jiffies for the operation
*
* SATA phy-reset host port using DET bits of SControl register,
* wait for !BSY and classify the attached device.
*
* LOCKING:
* Kernel thread context (may sleep)
*
* RETURNS:
* 0 on success, -errno otherwise.
*/
int sata_sff_hardreset(struct ata_link *link, unsigned int *class,
unsigned long deadline)
{
struct ata_eh_context *ehc = &link->eh_context;
const unsigned long *timing = sata_ehc_deb_timing(ehc);
bool online;
int rc;
rc = sata_link_hardreset(link, timing, deadline, &online,
ata_sff_check_ready);
if (online)
*class = ata_sff_dev_classify(link->device, 1, NULL);
DPRINTK("EXIT, class=%u\n", *class);
return rc;
}
EXPORT_SYMBOL_GPL(sata_sff_hardreset);
/**
* ata_sff_postreset - SFF postreset callback
* @link: the target SFF ata_link
* @classes: classes of attached devices
*
* This function is invoked after a successful reset. It first
* calls ata_std_postreset() and performs SFF specific postreset
* processing.
*
* LOCKING:
* Kernel thread context (may sleep)
*/
void ata_sff_postreset(struct ata_link *link, unsigned int *classes)
{
struct ata_port *ap = link->ap;
ata_std_postreset(link, classes);
/* is double-select really necessary? */
if (classes[0] != ATA_DEV_NONE)
ap->ops->sff_dev_select(ap, 1);
if (classes[1] != ATA_DEV_NONE)
ap->ops->sff_dev_select(ap, 0);
/* bail out if no device is present */
if (classes[0] == ATA_DEV_NONE && classes[1] == ATA_DEV_NONE) {
DPRINTK("EXIT, no device\n");
return;
}
/* set up device control */
if (ap->ops->sff_set_devctl || ap->ioaddr.ctl_addr) {
ata_sff_set_devctl(ap, ap->ctl);
ap->last_ctl = ap->ctl;
}
}
EXPORT_SYMBOL_GPL(ata_sff_postreset);
/**
* ata_sff_drain_fifo - Stock FIFO drain logic for SFF controllers
* @qc: command
*
* Drain the FIFO and device of any stuck data following a command
* failing to complete. In some cases this is necessary before a
* reset will recover the device.
*
*/
void ata_sff_drain_fifo(struct ata_queued_cmd *qc)
{
int count;
struct ata_port *ap;
/* We only need to flush incoming data when a command was running */
if (qc == NULL || qc->dma_dir == DMA_TO_DEVICE)
return;
ap = qc->ap;
/* Drain up to 64K of data before we give up this recovery method */
for (count = 0; (ap->ops->sff_check_status(ap) & ATA_DRQ)
&& count < 65536; count += 2)
ioread16(ap->ioaddr.data_addr);
/* Can become DEBUG later */
if (count)
ata_port_dbg(ap, "drained %d bytes to clear DRQ\n", count);
}
EXPORT_SYMBOL_GPL(ata_sff_drain_fifo);
/**
* ata_sff_error_handler - Stock error handler for SFF controller
* @ap: port to handle error for
*
* Stock error handler for SFF controller. It can handle both
* PATA and SATA controllers. Many controllers should be able to
* use this EH as-is or with some added handling before and
* after.
*
* LOCKING:
* Kernel thread context (may sleep)
*/
void ata_sff_error_handler(struct ata_port *ap)
{
ata_reset_fn_t softreset = ap->ops->softreset;
ata_reset_fn_t hardreset = ap->ops->hardreset;
struct ata_queued_cmd *qc;
unsigned long flags;
qc = __ata_qc_from_tag(ap, ap->link.active_tag);
if (qc && !(qc->flags & ATA_QCFLAG_FAILED))
qc = NULL;
spin_lock_irqsave(ap->lock, flags);
/*
* We *MUST* do FIFO draining before we issue a reset as
* several devices helpfully clear their internal state and
* will lock solid if we touch the data port post reset. Pass
* qc in case anyone wants to do different PIO/DMA recovery or
* has per command fixups
*/
if (ap->ops->sff_drain_fifo)
ap->ops->sff_drain_fifo(qc);
spin_unlock_irqrestore(ap->lock, flags);
/* ignore built-in hardresets if SCR access is not available */
if ((hardreset == sata_std_hardreset ||
hardreset == sata_sff_hardreset) && !sata_scr_valid(&ap->link))
hardreset = NULL;
ata_do_eh(ap, ap->ops->prereset, softreset, hardreset,
ap->ops->postreset);
}
EXPORT_SYMBOL_GPL(ata_sff_error_handler);
/**
* ata_sff_std_ports - initialize ioaddr with standard port offsets.
* @ioaddr: IO address structure to be initialized
*
* Utility function which initializes data_addr, error_addr,
* feature_addr, nsect_addr, lbal_addr, lbam_addr, lbah_addr,
* device_addr, status_addr, and command_addr to standard offsets
* relative to cmd_addr.
*
* Does not set ctl_addr, altstatus_addr, bmdma_addr, or scr_addr.
*/
void ata_sff_std_ports(struct ata_ioports *ioaddr)
{
ioaddr->data_addr = ioaddr->cmd_addr + ATA_REG_DATA;
ioaddr->error_addr = ioaddr->cmd_addr + ATA_REG_ERR;
ioaddr->feature_addr = ioaddr->cmd_addr + ATA_REG_FEATURE;
ioaddr->nsect_addr = ioaddr->cmd_addr + ATA_REG_NSECT;
ioaddr->lbal_addr = ioaddr->cmd_addr + ATA_REG_LBAL;
ioaddr->lbam_addr = ioaddr->cmd_addr + ATA_REG_LBAM;
ioaddr->lbah_addr = ioaddr->cmd_addr + ATA_REG_LBAH;
ioaddr->device_addr = ioaddr->cmd_addr + ATA_REG_DEVICE;
ioaddr->status_addr = ioaddr->cmd_addr + ATA_REG_STATUS;
ioaddr->command_addr = ioaddr->cmd_addr + ATA_REG_CMD;
}
EXPORT_SYMBOL_GPL(ata_sff_std_ports);
#ifdef CONFIG_PCI
static int ata_resources_present(struct pci_dev *pdev, int port)
{
int i;
/* Check the PCI resources for this channel are enabled */
port = port * 2;
for (i = 0; i < 2; i++) {
if (pci_resource_start(pdev, port + i) == 0 ||
pci_resource_len(pdev, port + i) == 0)
return 0;
}
return 1;
}
/**
* ata_pci_sff_init_host - acquire native PCI ATA resources and init host
* @host: target ATA host
*
* Acquire native PCI ATA resources for @host and initialize the
* first two ports of @host accordingly. Ports marked dummy are
* skipped and allocation failure makes the port dummy.
*
* Note that native PCI resources are valid even for legacy hosts
* as we fix up pdev resources array early in boot, so this
* function can be used for both native and legacy SFF hosts.
*
* LOCKING:
* Inherited from calling layer (may sleep).
*
* RETURNS:
* 0 if at least one port is initialized, -ENODEV if no port is
* available.
*/
int 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;
/* request, iomap BARs and init port addresses accordingly */
for (i = 0; i < 2; i++) {
struct ata_port *ap = host->ports[i];
int base = i * 2;
void __iomem * const *iomap;
if (ata_port_is_dummy(ap))
continue;
/* Discard disabled ports. Some controllers show
* their unused channels this way. Disabled ports are
* made dummy.
*/
if (!ata_resources_present(pdev, i)) {
ap->ops = &ata_dummy_port_ops;
continue;
}
rc = pcim_iomap_regions(pdev, 0x3 << base,
dev_driver_string(gdev));
if (rc) {
dev_warn(gdev,
"failed to request/iomap BARs for port %d (errno=%d)\n",
i, rc);
if (rc == -EBUSY)
pcim_pin_device(pdev);
ap->ops = &ata_dummy_port_ops;
continue;
}
host->iomap = iomap = pcim_iomap_table(pdev);
ap->ioaddr.cmd_addr = iomap[base];
ap->ioaddr.altstatus_addr =
ap->ioaddr.ctl_addr = (void __iomem *)
((unsigned long)iomap[base + 1] | ATA_PCI_CTL_OFS);
ata_sff_std_ports(&ap->ioaddr);
ata_port_desc(ap, "cmd 0x%llx ctl 0x%llx",
(unsigned long long)pci_resource_start(pdev, base),
(unsigned long long)pci_resource_start(pdev, base + 1));
mask |= 1 << i;
}
if (!mask) {
dev_err(gdev, "no available native port\n");
return -ENODEV;
}
return 0;
}
EXPORT_SYMBOL_GPL(ata_pci_sff_init_host);
/**
* ata_pci_sff_prepare_host - helper to prepare PCI PIO-only SFF ATA host
* @pdev: target PCI device
* @ppi: array of port_info, must be enough for two ports
* @r_host: out argument for the initialized ATA host
*
* Helper to allocate PIO-only SFF ATA host for @pdev, acquire
* all PCI resources and initialize it accordingly in one go.
*
* LOCKING:
* Inherited from calling layer (may sleep).
*
* RETURNS:
* 0 on success, -errno otherwise.
*/
int ata_pci_sff_prepare_host(struct pci_dev *pdev,
const struct ata_port_info * const *ppi,
struct ata_host **r_host)
{
struct ata_host *host;
int rc;
if (!devres_open_group(&pdev->dev, NULL, GFP_KERNEL))
return -ENOMEM;
host = ata_host_alloc_pinfo(&pdev->dev, ppi, 2);
if (!host) {
dev_err(&pdev->dev, "failed to allocate ATA host\n");
rc = -ENOMEM;
goto err_out;
}
rc = ata_pci_sff_init_host(host);
if (rc)
goto err_out;
devres_remove_group(&pdev->dev, NULL);
*r_host = host;
return 0;
err_out:
devres_release_group(&pdev->dev, NULL);
return rc;
}
EXPORT_SYMBOL_GPL(ata_pci_sff_prepare_host);
/**
* ata_pci_sff_activate_host - start SFF host, request IRQ and register it
* @host: target SFF ATA host
* @irq_handler: irq_handler used when requesting IRQ(s)
* @sht: scsi_host_template to use when registering the host
*
* This is the counterpart of ata_host_activate() for SFF ATA
* hosts. This separate helper is necessary because SFF hosts
* use two separate interrupts in legacy mode.
*
* LOCKING:
* Inherited from calling layer (may sleep).
*
* RETURNS:
* 0 on success, -errno otherwise.
*/
int ata_pci_sff_activate_host(struct ata_host *host,
irq_handler_t irq_handler,
struct scsi_host_template *sht)
{
struct device *dev = host->dev;
struct pci_dev *pdev = to_pci_dev(dev);
const char *drv_name = dev_driver_string(host->dev);
int legacy_mode = 0, rc;
rc = ata_host_start(host);
if (rc)
return rc;
if ((pdev->class >> 8) == PCI_CLASS_STORAGE_IDE) {
u8 tmp8, mask;
/* TODO: What if one channel is in native mode ... */
pci_read_config_byte(pdev, PCI_CLASS_PROG, &tmp8);
mask = (1 << 2) | (1 << 0);
if ((tmp8 & mask) != mask)
legacy_mode = 1;
}
if (!devres_open_group(dev, NULL, GFP_KERNEL))
return -ENOMEM;
if (!legacy_mode && pdev->irq) {
int i;
rc = devm_request_irq(dev, pdev->irq, irq_handler,
IRQF_SHARED, drv_name, host);
if (rc)
goto out;
for (i = 0; i < 2; i++) {
if (ata_port_is_dummy(host->ports[i]))
continue;
ata_port_desc(host->ports[i], "irq %d", pdev->irq);
}
} else if (legacy_mode) {
if (!ata_port_is_dummy(host->ports[0])) {
rc = devm_request_irq(dev, ATA_PRIMARY_IRQ(pdev),
irq_handler, IRQF_SHARED,
drv_name, host);
if (rc)
goto out;
ata_port_desc(host->ports[0], "irq %d",
ATA_PRIMARY_IRQ(pdev));
}
if (!ata_port_is_dummy(host->ports[1])) {
rc = devm_request_irq(dev, ATA_SECONDARY_IRQ(pdev),
irq_handler, IRQF_SHARED,
drv_name, host);
if (rc)
goto out;
ata_port_desc(host->ports[1], "irq %d",
ATA_SECONDARY_IRQ(pdev));
}
}
rc = ata_host_register(host, sht);
out:
if (rc == 0)
devres_remove_group(dev, NULL);
else
devres_release_group(dev, NULL);
return rc;
}
EXPORT_SYMBOL_GPL(ata_pci_sff_activate_host);
static const struct ata_port_info *ata_sff_find_valid_pi(
const struct ata_port_info * const *ppi)
{
int i;
/* look up the first valid port_info */
for (i = 0; i < 2 && ppi[i]; i++)
if (ppi[i]->port_ops != &ata_dummy_port_ops)
return ppi[i];
return NULL;
}
static int ata_pci_init_one(struct pci_dev *pdev,
const struct ata_port_info * const *ppi,
struct scsi_host_template *sht, void *host_priv,
int hflags, bool bmdma)
{
struct device *dev = &pdev->dev;
const struct ata_port_info *pi;
struct ata_host *host = NULL;
int rc;
DPRINTK("ENTER\n");
pi = ata_sff_find_valid_pi(ppi);
if (!pi) {
dev_err(&pdev->dev, "no valid port_info specified\n");
return -EINVAL;
}
if (!devres_open_group(dev, NULL, GFP_KERNEL))
return -ENOMEM;
rc = pcim_enable_device(pdev);
if (rc)
goto out;
#ifdef CONFIG_ATA_BMDMA
if (bmdma)
/* prepare and activate BMDMA host */
rc = ata_pci_bmdma_prepare_host(pdev, ppi, &host);
else
#endif
/* prepare and activate SFF host */
rc = ata_pci_sff_prepare_host(pdev, ppi, &host);
if (rc)
goto out;
host->private_data = host_priv;
host->flags |= hflags;
#ifdef CONFIG_ATA_BMDMA
if (bmdma) {
pci_set_master(pdev);
rc = ata_pci_sff_activate_host(host, ata_bmdma_interrupt, sht);
} else
#endif
rc = ata_pci_sff_activate_host(host, ata_sff_interrupt, sht);
out:
if (rc == 0)
devres_remove_group(&pdev->dev, NULL);
else
devres_release_group(&pdev->dev, NULL);
return rc;
}
/**
* ata_pci_sff_init_one - Initialize/register PIO-only PCI IDE controller
* @pdev: Controller to be initialized
* @ppi: array of port_info, must be enough for two ports
* @sht: scsi_host_template to use when registering the host
* @host_priv: host private_data
* @hflag: host flags
*
* This is a helper function which can be called from a driver's
* xxx_init_one() probe function if the hardware uses traditional
* IDE taskfile registers and is PIO only.
*
* ASSUMPTION:
* Nobody makes a single channel controller that appears solely as
* the secondary legacy port on PCI.
*
* LOCKING:
* Inherited from PCI layer (may sleep).
*
* RETURNS:
* Zero on success, negative on errno-based value on error.
*/
int ata_pci_sff_init_one(struct pci_dev *pdev,
const struct ata_port_info * const *ppi,
struct scsi_host_template *sht, void *host_priv, int hflag)
{
return ata_pci_init_one(pdev, ppi, sht, host_priv, hflag, 0);
}
EXPORT_SYMBOL_GPL(ata_pci_sff_init_one);
#endif /* CONFIG_PCI */
/*
* BMDMA support
*/
#ifdef CONFIG_ATA_BMDMA
const struct ata_port_operations ata_bmdma_port_ops = {
.inherits = &ata_sff_port_ops,
.error_handler = ata_bmdma_error_handler,
.post_internal_cmd = ata_bmdma_post_internal_cmd,
.qc_prep = ata_bmdma_qc_prep,
.qc_issue = ata_bmdma_qc_issue,
.sff_irq_clear = ata_bmdma_irq_clear,
.bmdma_setup = ata_bmdma_setup,
.bmdma_start = ata_bmdma_start,
.bmdma_stop = ata_bmdma_stop,
.bmdma_status = ata_bmdma_status,
.port_start = ata_bmdma_port_start,
};
EXPORT_SYMBOL_GPL(ata_bmdma_port_ops);
const struct ata_port_operations ata_bmdma32_port_ops = {
.inherits = &ata_bmdma_port_ops,
.sff_data_xfer = ata_sff_data_xfer32,
.port_start = ata_bmdma_port_start32,
};
EXPORT_SYMBOL_GPL(ata_bmdma32_port_ops);
/**
* ata_bmdma_fill_sg - Fill PCI IDE PRD table
* @qc: Metadata associated with taskfile to be transferred
*
* Fill PCI IDE PRD (scatter-gather) table with segments
* associated with the current disk command.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
*/
static void ata_bmdma_fill_sg(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_bmdma_prd *prd = ap->bmdma_prd;
struct scatterlist *sg;
unsigned int si, pi;
pi = 0;
for_each_sg(qc->sg, sg, qc->n_elem, si) {
u32 addr, offset;
u32 sg_len, len;
/* determine if physical DMA addr spans 64K boundary.
* Note h/w doesn't support 64-bit, so we unconditionally
* truncate dma_addr_t to u32.
*/
addr = (u32) sg_dma_address(sg);
sg_len = sg_dma_len(sg);
while (sg_len) {
offset = addr & 0xffff;
len = sg_len;
if ((offset + sg_len) > 0x10000)
len = 0x10000 - offset;
prd[pi].addr = cpu_to_le32(addr);
prd[pi].flags_len = cpu_to_le32(len & 0xffff);
VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", pi, addr, len);
pi++;
sg_len -= len;
addr += len;
}
}
prd[pi - 1].flags_len |= cpu_to_le32(ATA_PRD_EOT);
}
/**
* ata_bmdma_fill_sg_dumb - Fill PCI IDE PRD table
* @qc: Metadata associated with taskfile to be transferred
*
* Fill PCI IDE PRD (scatter-gather) table with segments
* associated with the current disk command. Perform the fill
* so that we avoid writing any length 64K records for
* controllers that don't follow the spec.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
*/
static void ata_bmdma_fill_sg_dumb(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_bmdma_prd *prd = ap->bmdma_prd;
struct scatterlist *sg;
unsigned int si, pi;
pi = 0;
for_each_sg(qc->sg, sg, qc->n_elem, si) {
u32 addr, offset;
u32 sg_len, len, blen;
/* determine if physical DMA addr spans 64K boundary.
* Note h/w doesn't support 64-bit, so we unconditionally
* truncate dma_addr_t to u32.
*/
addr = (u32) sg_dma_address(sg);
sg_len = sg_dma_len(sg);
while (sg_len) {
offset = addr & 0xffff;
len = sg_len;
if ((offset + sg_len) > 0x10000)
len = 0x10000 - offset;
blen = len & 0xffff;
prd[pi].addr = cpu_to_le32(addr);
if (blen == 0) {
/* Some PATA chipsets like the CS5530 can't
cope with 0x0000 meaning 64K as the spec
says */
prd[pi].flags_len = cpu_to_le32(0x8000);
blen = 0x8000;
prd[++pi].addr = cpu_to_le32(addr + 0x8000);
}
prd[pi].flags_len = cpu_to_le32(blen);
VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", pi, addr, len);
pi++;
sg_len -= len;
addr += len;
}
}
prd[pi - 1].flags_len |= cpu_to_le32(ATA_PRD_EOT);
}
/**
* ata_bmdma_qc_prep - Prepare taskfile for submission
* @qc: Metadata associated with taskfile to be prepared
*
* Prepare ATA taskfile for submission.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
void ata_bmdma_qc_prep(struct ata_queued_cmd *qc)
{
if (!(qc->flags & ATA_QCFLAG_DMAMAP))
return;
ata_bmdma_fill_sg(qc);
}
EXPORT_SYMBOL_GPL(ata_bmdma_qc_prep);
/**
* ata_bmdma_dumb_qc_prep - Prepare taskfile for submission
* @qc: Metadata associated with taskfile to be prepared
*
* Prepare ATA taskfile for submission.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
void ata_bmdma_dumb_qc_prep(struct ata_queued_cmd *qc)
{
if (!(qc->flags & ATA_QCFLAG_DMAMAP))
return;
ata_bmdma_fill_sg_dumb(qc);
}
EXPORT_SYMBOL_GPL(ata_bmdma_dumb_qc_prep);
/**
* ata_bmdma_qc_issue - issue taskfile to a BMDMA controller
* @qc: command to issue to device
*
* This function issues a PIO, NODATA or DMA command to a
* SFF/BMDMA controller. PIO and NODATA are handled by
* ata_sff_qc_issue().
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* Zero on success, AC_ERR_* mask on failure
*/
unsigned int ata_bmdma_qc_issue(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_link *link = qc->dev->link;
/* defer PIO handling to sff_qc_issue */
if (!ata_is_dma(qc->tf.protocol))
return ata_sff_qc_issue(qc);
/* select the device */
ata_dev_select(ap, qc->dev->devno, 1, 0);
/* start the command */
switch (qc->tf.protocol) {
case ATA_PROT_DMA:
WARN_ON_ONCE(qc->tf.flags & ATA_TFLAG_POLLING);
ap->ops->sff_tf_load(ap, &qc->tf); /* load tf registers */
ap->ops->bmdma_setup(qc); /* set up bmdma */
ap->ops->bmdma_start(qc); /* initiate bmdma */
ap->hsm_task_state = HSM_ST_LAST;
break;
case ATAPI_PROT_DMA:
WARN_ON_ONCE(qc->tf.flags & ATA_TFLAG_POLLING);
ap->ops->sff_tf_load(ap, &qc->tf); /* load tf registers */
ap->ops->bmdma_setup(qc); /* set up bmdma */
ap->hsm_task_state = HSM_ST_FIRST;
/* send cdb by polling if no cdb interrupt */
if (!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
ata_sff_queue_pio_task(link, 0);
break;
default:
WARN_ON(1);
return AC_ERR_SYSTEM;
}
return 0;
}
EXPORT_SYMBOL_GPL(ata_bmdma_qc_issue);
/**
* ata_bmdma_port_intr - Handle BMDMA port interrupt
* @ap: Port on which interrupt arrived (possibly...)
* @qc: Taskfile currently active in engine
*
* Handle port interrupt for given queued command.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* One if interrupt was handled, zero if not (shared irq).
*/
unsigned int ata_bmdma_port_intr(struct ata_port *ap, struct ata_queued_cmd *qc)
{
struct ata_eh_info *ehi = &ap->link.eh_info;
u8 host_stat = 0;
bool bmdma_stopped = false;
unsigned int handled;
if (ap->hsm_task_state == HSM_ST_LAST && ata_is_dma(qc->tf.protocol)) {
/* check status of DMA engine */
host_stat = ap->ops->bmdma_status(ap);
VPRINTK("ata%u: host_stat 0x%X\n", ap->print_id, host_stat);
/* if it's not our irq... */
if (!(host_stat & ATA_DMA_INTR))
return ata_sff_idle_irq(ap);
/* before we do anything else, clear DMA-Start bit */
ap->ops->bmdma_stop(qc);
bmdma_stopped = true;
if (unlikely(host_stat & ATA_DMA_ERR)) {
/* error when transferring data to/from memory */
qc->err_mask |= AC_ERR_HOST_BUS;
ap->hsm_task_state = HSM_ST_ERR;
}
}
handled = __ata_sff_port_intr(ap, qc, bmdma_stopped);
if (unlikely(qc->err_mask) && ata_is_dma(qc->tf.protocol))
ata_ehi_push_desc(ehi, "BMDMA stat 0x%x", host_stat);
return handled;
}
EXPORT_SYMBOL_GPL(ata_bmdma_port_intr);
/**
* ata_bmdma_interrupt - Default BMDMA ATA host interrupt handler
* @irq: irq line (unused)
* @dev_instance: pointer to our ata_host information structure
*
* Default interrupt handler for PCI IDE devices. Calls
* ata_bmdma_port_intr() for each port that is not disabled.
*
* LOCKING:
* Obtains host lock during operation.
*
* RETURNS:
* IRQ_NONE or IRQ_HANDLED.
*/
irqreturn_t ata_bmdma_interrupt(int irq, void *dev_instance)
{
return __ata_sff_interrupt(irq, dev_instance, ata_bmdma_port_intr);
}
EXPORT_SYMBOL_GPL(ata_bmdma_interrupt);
/**
* ata_bmdma_error_handler - Stock error handler for BMDMA controller
* @ap: port to handle error for
*
* Stock error handler for BMDMA controller. It can handle both
* PATA and SATA controllers. Most BMDMA controllers should be
* able to use this EH as-is or with some added handling before
* and after.
*
* LOCKING:
* Kernel thread context (may sleep)
*/
void ata_bmdma_error_handler(struct ata_port *ap)
{
struct ata_queued_cmd *qc;
unsigned long flags;
bool thaw = false;
qc = __ata_qc_from_tag(ap, ap->link.active_tag);
if (qc && !(qc->flags & ATA_QCFLAG_FAILED))
qc = NULL;
/* reset PIO HSM and stop DMA engine */
spin_lock_irqsave(ap->lock, flags);
if (qc && ata_is_dma(qc->tf.protocol)) {
u8 host_stat;
host_stat = ap->ops->bmdma_status(ap);
/* BMDMA controllers indicate host bus error by
* setting DMA_ERR bit and timing out. As it wasn't
* really a timeout event, adjust error mask and
* cancel frozen state.
*/
if (qc->err_mask == AC_ERR_TIMEOUT && (host_stat & ATA_DMA_ERR)) {
qc->err_mask = AC_ERR_HOST_BUS;
thaw = true;
}
ap->ops->bmdma_stop(qc);
/* if we're gonna thaw, make sure IRQ is clear */
if (thaw) {
ap->ops->sff_check_status(ap);
if (ap->ops->sff_irq_clear)
ap->ops->sff_irq_clear(ap);
}
}
spin_unlock_irqrestore(ap->lock, flags);
if (thaw)
ata_eh_thaw_port(ap);
ata_sff_error_handler(ap);
}
EXPORT_SYMBOL_GPL(ata_bmdma_error_handler);
/**
* ata_bmdma_post_internal_cmd - Stock post_internal_cmd for BMDMA
* @qc: internal command to clean up
*
* LOCKING:
* Kernel thread context (may sleep)
*/
void ata_bmdma_post_internal_cmd(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
unsigned long flags;
if (ata_is_dma(qc->tf.protocol)) {
spin_lock_irqsave(ap->lock, flags);
ap->ops->bmdma_stop(qc);
spin_unlock_irqrestore(ap->lock, flags);
}
}
EXPORT_SYMBOL_GPL(ata_bmdma_post_internal_cmd);
/**
* ata_bmdma_irq_clear - Clear PCI IDE BMDMA interrupt.
* @ap: Port associated with this ATA transaction.
*
* Clear interrupt and error flags in DMA status register.
*
* May be used as the irq_clear() entry in ata_port_operations.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
void ata_bmdma_irq_clear(struct ata_port *ap)
{
void __iomem *mmio = ap->ioaddr.bmdma_addr;
if (!mmio)
return;
iowrite8(ioread8(mmio + ATA_DMA_STATUS), mmio + ATA_DMA_STATUS);
}
EXPORT_SYMBOL_GPL(ata_bmdma_irq_clear);
/**
* ata_bmdma_setup - Set up PCI IDE BMDMA transaction
* @qc: Info associated with this ATA transaction.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
void ata_bmdma_setup(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
unsigned int rw = (qc->tf.flags & ATA_TFLAG_WRITE);
u8 dmactl;
/* load PRD table addr. */
mb(); /* make sure PRD table writes are visible to controller */
iowrite32(ap->bmdma_prd_dma, ap->ioaddr.bmdma_addr + ATA_DMA_TABLE_OFS);
/* specify data direction, triple-check start bit is clear */
dmactl = ioread8(ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
dmactl &= ~(ATA_DMA_WR | ATA_DMA_START);
if (!rw)
dmactl |= ATA_DMA_WR;
iowrite8(dmactl, ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
/* issue r/w command */
ap->ops->sff_exec_command(ap, &qc->tf);
}
EXPORT_SYMBOL_GPL(ata_bmdma_setup);
/**
* ata_bmdma_start - Start a PCI IDE BMDMA transaction
* @qc: Info associated with this ATA transaction.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
void ata_bmdma_start(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
u8 dmactl;
/* start host DMA transaction */
dmactl = ioread8(ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
iowrite8(dmactl | ATA_DMA_START, ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
/* Strictly, one may wish to issue an ioread8() here, to
* flush the mmio write. However, control also passes
* to the hardware at this point, and it will interrupt
* us when we are to resume control. So, in effect,
* we don't care when the mmio write flushes.
* Further, a read of the DMA status register _immediately_
* following the write may not be what certain flaky hardware
* is expected, so I think it is best to not add a readb()
* without first all the MMIO ATA cards/mobos.
* Or maybe I'm just being paranoid.
*
* FIXME: The posting of this write means I/O starts are
* unnecessarily delayed for MMIO
*/
}
EXPORT_SYMBOL_GPL(ata_bmdma_start);
/**
* ata_bmdma_stop - Stop PCI IDE BMDMA transfer
* @qc: Command we are ending DMA for
*
* Clears the ATA_DMA_START flag in the dma control register
*
* May be used as the bmdma_stop() entry in ata_port_operations.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
void ata_bmdma_stop(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
void __iomem *mmio = ap->ioaddr.bmdma_addr;
/* clear start/stop bit */
iowrite8(ioread8(mmio + ATA_DMA_CMD) & ~ATA_DMA_START,
mmio + ATA_DMA_CMD);
/* one-PIO-cycle guaranteed wait, per spec, for HDMA1:0 transition */
ata_sff_dma_pause(ap);
}
EXPORT_SYMBOL_GPL(ata_bmdma_stop);
/**
* ata_bmdma_status - Read PCI IDE BMDMA status
* @ap: Port associated with this ATA transaction.
*
* Read and return BMDMA status register.
*
* May be used as the bmdma_status() entry in ata_port_operations.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
u8 ata_bmdma_status(struct ata_port *ap)
{
return ioread8(ap->ioaddr.bmdma_addr + ATA_DMA_STATUS);
}
EXPORT_SYMBOL_GPL(ata_bmdma_status);
/**
* ata_bmdma_port_start - Set port up for bmdma.
* @ap: Port to initialize
*
* Called just after data structures for each port are
* initialized. Allocates space for PRD table.
*
* May be used as the port_start() entry in ata_port_operations.
*
* LOCKING:
* Inherited from caller.
*/
int ata_bmdma_port_start(struct ata_port *ap)
{
if (ap->mwdma_mask || ap->udma_mask) {
ap->bmdma_prd =
dmam_alloc_coherent(ap->host->dev, ATA_PRD_TBL_SZ,
&ap->bmdma_prd_dma, GFP_KERNEL);
if (!ap->bmdma_prd)
return -ENOMEM;
}
return 0;
}
EXPORT_SYMBOL_GPL(ata_bmdma_port_start);
/**
* ata_bmdma_port_start32 - Set port up for dma.
* @ap: Port to initialize
*
* Called just after data structures for each port are
* initialized. Enables 32bit PIO and allocates space for PRD
* table.
*
* May be used as the port_start() entry in ata_port_operations for
* devices that are capable of 32bit PIO.
*
* LOCKING:
* Inherited from caller.
*/
int ata_bmdma_port_start32(struct ata_port *ap)
{
ap->pflags |= ATA_PFLAG_PIO32 | ATA_PFLAG_PIO32CHANGE;
return ata_bmdma_port_start(ap);
}
EXPORT_SYMBOL_GPL(ata_bmdma_port_start32);
#ifdef CONFIG_PCI
/**
* ata_pci_bmdma_clear_simplex - attempt to kick device out of simplex
* @pdev: PCI device
*
* Some PCI ATA devices report simplex mode but in fact can be told to
* enter non simplex mode. This implements the necessary logic to
* perform the task on such devices. Calling it on other devices will
* have -undefined- behaviour.
*/
int ata_pci_bmdma_clear_simplex(struct pci_dev *pdev)
{
unsigned long bmdma = pci_resource_start(pdev, 4);
u8 simplex;
if (bmdma == 0)
return -ENOENT;
simplex = inb(bmdma + 0x02);
outb(simplex & 0x60, bmdma + 0x02);
simplex = inb(bmdma + 0x02);
if (simplex & 0x80)
return -EOPNOTSUPP;
return 0;
}
EXPORT_SYMBOL_GPL(ata_pci_bmdma_clear_simplex);
static void ata_bmdma_nodma(struct ata_host *host, const char *reason)
{
int i;
dev_err(host->dev, "BMDMA: %s, falling back to PIO\n", reason);
for (i = 0; i < 2; i++) {
host->ports[i]->mwdma_mask = 0;
host->ports[i]->udma_mask = 0;
}
}
/**
* ata_pci_bmdma_init - acquire PCI BMDMA resources and init ATA host
* @host: target ATA host
*
* Acquire PCI BMDMA resources and initialize @host accordingly.
*
* LOCKING:
* Inherited from calling layer (may sleep).
*/
void ata_pci_bmdma_init(struct ata_host *host)
{
struct device *gdev = host->dev;
struct pci_dev *pdev = to_pci_dev(gdev);
int i, rc;
/* No BAR4 allocation: No DMA */
if (pci_resource_start(pdev, 4) == 0) {
ata_bmdma_nodma(host, "BAR4 is zero");
return;
}
/*
* Some controllers require BMDMA region to be initialized
* even if DMA is not in use to clear IRQ status via
* ->sff_irq_clear method. Try to initialize bmdma_addr
* regardless of dma masks.
*/
rc = dma_set_mask(&pdev->dev, ATA_DMA_MASK);
if (rc)
ata_bmdma_nodma(host, "failed to set dma mask");
if (!rc) {
rc = dma_set_coherent_mask(&pdev->dev, ATA_DMA_MASK);
if (rc)
ata_bmdma_nodma(host,
"failed to set consistent dma mask");
}
/* request and iomap DMA region */
rc = pcim_iomap_regions(pdev, 1 << 4, dev_driver_string(gdev));
if (rc) {
ata_bmdma_nodma(host, "failed to request/iomap BAR4");
return;
}
host->iomap = pcim_iomap_table(pdev);
for (i = 0; i < 2; i++) {
struct ata_port *ap = host->ports[i];
void __iomem *bmdma = host->iomap[4] + 8 * i;
if (ata_port_is_dummy(ap))
continue;
ap->ioaddr.bmdma_addr = bmdma;
if ((!(ap->flags & ATA_FLAG_IGN_SIMPLEX)) &&
(ioread8(bmdma + 2) & 0x80))
host->flags |= ATA_HOST_SIMPLEX;
ata_port_desc(ap, "bmdma 0x%llx",
(unsigned long long)pci_resource_start(pdev, 4) + 8 * i);
}
}
EXPORT_SYMBOL_GPL(ata_pci_bmdma_init);
/**
* ata_pci_bmdma_prepare_host - helper to prepare PCI BMDMA ATA host
* @pdev: target PCI device
* @ppi: array of port_info, must be enough for two ports
* @r_host: out argument for the initialized ATA host
*
* Helper to allocate BMDMA ATA host for @pdev, acquire all PCI
* resources and initialize it accordingly in one go.
*
* LOCKING:
* Inherited from calling layer (may sleep).
*
* RETURNS:
* 0 on success, -errno otherwise.
*/
int ata_pci_bmdma_prepare_host(struct pci_dev *pdev,
const struct ata_port_info * const * ppi,
struct ata_host **r_host)
{
int rc;
rc = ata_pci_sff_prepare_host(pdev, ppi, r_host);
if (rc)
return rc;
ata_pci_bmdma_init(*r_host);
return 0;
}
EXPORT_SYMBOL_GPL(ata_pci_bmdma_prepare_host);
/**
* ata_pci_bmdma_init_one - Initialize/register BMDMA PCI IDE controller
* @pdev: Controller to be initialized
* @ppi: array of port_info, must be enough for two ports
* @sht: scsi_host_template to use when registering the host
* @host_priv: host private_data
* @hflags: host flags
*
* This function is similar to ata_pci_sff_init_one() but also
* takes care of BMDMA initialization.
*
* LOCKING:
* Inherited from PCI layer (may sleep).
*
* RETURNS:
* Zero on success, negative on errno-based value on error.
*/
int ata_pci_bmdma_init_one(struct pci_dev *pdev,
const struct ata_port_info * const * ppi,
struct scsi_host_template *sht, void *host_priv,
int hflags)
{
return ata_pci_init_one(pdev, ppi, sht, host_priv, hflags, 1);
}
EXPORT_SYMBOL_GPL(ata_pci_bmdma_init_one);
#endif /* CONFIG_PCI */
#endif /* CONFIG_ATA_BMDMA */
/**
* ata_sff_port_init - Initialize SFF/BMDMA ATA port
* @ap: Port to initialize
*
* Called on port allocation to initialize SFF/BMDMA specific
* fields.
*
* LOCKING:
* None.
*/
void ata_sff_port_init(struct ata_port *ap)
{
INIT_DELAYED_WORK(&ap->sff_pio_task, ata_sff_pio_task);
ap->ctl = ATA_DEVCTL_OBS;
ap->last_ctl = 0xFF;
}
int __init ata_sff_init(void)
{
ata_sff_wq = alloc_workqueue("ata_sff", WQ_MEM_RECLAIM, WQ_MAX_ACTIVE);
if (!ata_sff_wq)
return -ENOMEM;
return 0;
}
void ata_sff_exit(void)
{
destroy_workqueue(ata_sff_wq);
}
| gpl-2.0 |
djvoleur/S6-UniBase | drivers/gpio/gpio-pl061.c | 1744 | 10182 | /*
* Copyright (C) 2008, 2009 Provigent 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.
*
* Driver for the ARM PrimeCell(tm) General Purpose Input/Output (PL061)
*
* Data sheet: ARM DDI 0190B, September 2000
*/
#include <linux/spinlock.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/irq.h>
#include <linux/irqdomain.h>
#include <linux/irqchip/chained_irq.h>
#include <linux/bitops.h>
#include <linux/workqueue.h>
#include <linux/gpio.h>
#include <linux/device.h>
#include <linux/amba/bus.h>
#include <linux/amba/pl061.h>
#include <linux/slab.h>
#include <linux/pinctrl/consumer.h>
#include <linux/pm.h>
#define GPIODIR 0x400
#define GPIOIS 0x404
#define GPIOIBE 0x408
#define GPIOIEV 0x40C
#define GPIOIE 0x410
#define GPIORIS 0x414
#define GPIOMIS 0x418
#define GPIOIC 0x41C
#define PL061_GPIO_NR 8
#ifdef CONFIG_PM
struct pl061_context_save_regs {
u8 gpio_data;
u8 gpio_dir;
u8 gpio_is;
u8 gpio_ibe;
u8 gpio_iev;
u8 gpio_ie;
};
#endif
struct pl061_gpio {
spinlock_t lock;
void __iomem *base;
struct irq_domain *domain;
struct gpio_chip gc;
#ifdef CONFIG_PM
struct pl061_context_save_regs csave_regs;
#endif
};
static int pl061_gpio_request(struct gpio_chip *chip, unsigned offset)
{
/*
* Map back to global GPIO space and request muxing, the direction
* parameter does not matter for this controller.
*/
int gpio = chip->base + offset;
return pinctrl_request_gpio(gpio);
}
static void pl061_gpio_free(struct gpio_chip *chip, unsigned offset)
{
int gpio = chip->base + offset;
pinctrl_free_gpio(gpio);
}
static int pl061_direction_input(struct gpio_chip *gc, unsigned offset)
{
struct pl061_gpio *chip = container_of(gc, struct pl061_gpio, gc);
unsigned long flags;
unsigned char gpiodir;
if (offset >= gc->ngpio)
return -EINVAL;
spin_lock_irqsave(&chip->lock, flags);
gpiodir = readb(chip->base + GPIODIR);
gpiodir &= ~(1 << offset);
writeb(gpiodir, chip->base + GPIODIR);
spin_unlock_irqrestore(&chip->lock, flags);
return 0;
}
static int pl061_direction_output(struct gpio_chip *gc, unsigned offset,
int value)
{
struct pl061_gpio *chip = container_of(gc, struct pl061_gpio, gc);
unsigned long flags;
unsigned char gpiodir;
if (offset >= gc->ngpio)
return -EINVAL;
spin_lock_irqsave(&chip->lock, flags);
writeb(!!value << offset, chip->base + (1 << (offset + 2)));
gpiodir = readb(chip->base + GPIODIR);
gpiodir |= 1 << offset;
writeb(gpiodir, chip->base + GPIODIR);
/*
* gpio value is set again, because pl061 doesn't allow to set value of
* a gpio pin before configuring it in OUT mode.
*/
writeb(!!value << offset, chip->base + (1 << (offset + 2)));
spin_unlock_irqrestore(&chip->lock, flags);
return 0;
}
static int pl061_get_value(struct gpio_chip *gc, unsigned offset)
{
struct pl061_gpio *chip = container_of(gc, struct pl061_gpio, gc);
return !!readb(chip->base + (1 << (offset + 2)));
}
static void pl061_set_value(struct gpio_chip *gc, unsigned offset, int value)
{
struct pl061_gpio *chip = container_of(gc, struct pl061_gpio, gc);
writeb(!!value << offset, chip->base + (1 << (offset + 2)));
}
static int pl061_to_irq(struct gpio_chip *gc, unsigned offset)
{
struct pl061_gpio *chip = container_of(gc, struct pl061_gpio, gc);
return irq_create_mapping(chip->domain, offset);
}
static int pl061_irq_type(struct irq_data *d, unsigned trigger)
{
struct pl061_gpio *chip = irq_data_get_irq_chip_data(d);
int offset = irqd_to_hwirq(d);
unsigned long flags;
u8 gpiois, gpioibe, gpioiev;
if (offset < 0 || offset >= PL061_GPIO_NR)
return -EINVAL;
spin_lock_irqsave(&chip->lock, flags);
gpioiev = readb(chip->base + GPIOIEV);
gpiois = readb(chip->base + GPIOIS);
if (trigger & (IRQ_TYPE_LEVEL_HIGH | IRQ_TYPE_LEVEL_LOW)) {
gpiois |= 1 << offset;
if (trigger & IRQ_TYPE_LEVEL_HIGH)
gpioiev |= 1 << offset;
else
gpioiev &= ~(1 << offset);
} else
gpiois &= ~(1 << offset);
writeb(gpiois, chip->base + GPIOIS);
gpioibe = readb(chip->base + GPIOIBE);
if ((trigger & IRQ_TYPE_EDGE_BOTH) == IRQ_TYPE_EDGE_BOTH)
gpioibe |= 1 << offset;
else {
gpioibe &= ~(1 << offset);
if (trigger & IRQ_TYPE_EDGE_RISING)
gpioiev |= 1 << offset;
else if (trigger & IRQ_TYPE_EDGE_FALLING)
gpioiev &= ~(1 << offset);
}
writeb(gpioibe, chip->base + GPIOIBE);
writeb(gpioiev, chip->base + GPIOIEV);
spin_unlock_irqrestore(&chip->lock, flags);
return 0;
}
static void pl061_irq_handler(unsigned irq, struct irq_desc *desc)
{
unsigned long pending;
int offset;
struct pl061_gpio *chip = irq_desc_get_handler_data(desc);
struct irq_chip *irqchip = irq_desc_get_chip(desc);
chained_irq_enter(irqchip, desc);
pending = readb(chip->base + GPIOMIS);
writeb(pending, chip->base + GPIOIC);
if (pending) {
for_each_set_bit(offset, &pending, PL061_GPIO_NR)
generic_handle_irq(pl061_to_irq(&chip->gc, offset));
}
chained_irq_exit(irqchip, desc);
}
static void pl061_irq_mask(struct irq_data *d)
{
struct pl061_gpio *chip = irq_data_get_irq_chip_data(d);
u8 mask = 1 << (irqd_to_hwirq(d) % PL061_GPIO_NR);
u8 gpioie;
spin_lock(&chip->lock);
gpioie = readb(chip->base + GPIOIE) & ~mask;
writeb(gpioie, chip->base + GPIOIE);
spin_unlock(&chip->lock);
}
static void pl061_irq_unmask(struct irq_data *d)
{
struct pl061_gpio *chip = irq_data_get_irq_chip_data(d);
u8 mask = 1 << (irqd_to_hwirq(d) % PL061_GPIO_NR);
u8 gpioie;
spin_lock(&chip->lock);
gpioie = readb(chip->base + GPIOIE) | mask;
writeb(gpioie, chip->base + GPIOIE);
spin_unlock(&chip->lock);
}
static struct irq_chip pl061_irqchip = {
.name = "pl061 gpio",
.irq_mask = pl061_irq_mask,
.irq_unmask = pl061_irq_unmask,
.irq_set_type = pl061_irq_type,
};
static int pl061_irq_map(struct irq_domain *d, unsigned int virq,
irq_hw_number_t hw)
{
struct pl061_gpio *chip = d->host_data;
irq_set_chip_and_handler_name(virq, &pl061_irqchip, handle_simple_irq,
"pl061");
irq_set_chip_data(virq, chip);
irq_set_irq_type(virq, IRQ_TYPE_NONE);
return 0;
}
static const struct irq_domain_ops pl061_domain_ops = {
.map = pl061_irq_map,
.xlate = irq_domain_xlate_twocell,
};
static int pl061_probe(struct amba_device *adev, const struct amba_id *id)
{
struct device *dev = &adev->dev;
struct pl061_platform_data *pdata = dev->platform_data;
struct pl061_gpio *chip;
int ret, irq, i, irq_base;
chip = devm_kzalloc(dev, sizeof(*chip), GFP_KERNEL);
if (chip == NULL)
return -ENOMEM;
if (pdata) {
chip->gc.base = pdata->gpio_base;
irq_base = pdata->irq_base;
if (irq_base <= 0)
return -ENODEV;
} else {
chip->gc.base = -1;
irq_base = 0;
}
if (!devm_request_mem_region(dev, adev->res.start,
resource_size(&adev->res), "pl061"))
return -EBUSY;
chip->base = devm_ioremap(dev, adev->res.start,
resource_size(&adev->res));
if (!chip->base)
return -ENOMEM;
spin_lock_init(&chip->lock);
chip->gc.request = pl061_gpio_request;
chip->gc.free = pl061_gpio_free;
chip->gc.direction_input = pl061_direction_input;
chip->gc.direction_output = pl061_direction_output;
chip->gc.get = pl061_get_value;
chip->gc.set = pl061_set_value;
chip->gc.to_irq = pl061_to_irq;
chip->gc.ngpio = PL061_GPIO_NR;
chip->gc.label = dev_name(dev);
chip->gc.dev = dev;
chip->gc.owner = THIS_MODULE;
ret = gpiochip_add(&chip->gc);
if (ret)
return ret;
/*
* irq_chip support
*/
writeb(0, chip->base + GPIOIE); /* disable irqs */
irq = adev->irq[0];
if (irq < 0)
return -ENODEV;
irq_set_chained_handler(irq, pl061_irq_handler);
irq_set_handler_data(irq, chip);
chip->domain = irq_domain_add_simple(adev->dev.of_node, PL061_GPIO_NR,
irq_base, &pl061_domain_ops, chip);
if (!chip->domain)
return -ENODEV;
for (i = 0; i < PL061_GPIO_NR; i++) {
if (pdata) {
if (pdata->directions & (1 << i))
pl061_direction_output(&chip->gc, i,
pdata->values & (1 << i));
else
pl061_direction_input(&chip->gc, i);
}
}
amba_set_drvdata(adev, chip);
return 0;
}
#ifdef CONFIG_PM
static int pl061_suspend(struct device *dev)
{
struct pl061_gpio *chip = dev_get_drvdata(dev);
int offset;
chip->csave_regs.gpio_data = 0;
chip->csave_regs.gpio_dir = readb(chip->base + GPIODIR);
chip->csave_regs.gpio_is = readb(chip->base + GPIOIS);
chip->csave_regs.gpio_ibe = readb(chip->base + GPIOIBE);
chip->csave_regs.gpio_iev = readb(chip->base + GPIOIEV);
chip->csave_regs.gpio_ie = readb(chip->base + GPIOIE);
for (offset = 0; offset < PL061_GPIO_NR; offset++) {
if (chip->csave_regs.gpio_dir & (1 << offset))
chip->csave_regs.gpio_data |=
pl061_get_value(&chip->gc, offset) << offset;
}
return 0;
}
static int pl061_resume(struct device *dev)
{
struct pl061_gpio *chip = dev_get_drvdata(dev);
int offset;
for (offset = 0; offset < PL061_GPIO_NR; offset++) {
if (chip->csave_regs.gpio_dir & (1 << offset))
pl061_direction_output(&chip->gc, offset,
chip->csave_regs.gpio_data &
(1 << offset));
else
pl061_direction_input(&chip->gc, offset);
}
writeb(chip->csave_regs.gpio_is, chip->base + GPIOIS);
writeb(chip->csave_regs.gpio_ibe, chip->base + GPIOIBE);
writeb(chip->csave_regs.gpio_iev, chip->base + GPIOIEV);
writeb(chip->csave_regs.gpio_ie, chip->base + GPIOIE);
return 0;
}
static const struct dev_pm_ops pl061_dev_pm_ops = {
.suspend = pl061_suspend,
.resume = pl061_resume,
.freeze = pl061_suspend,
.restore = pl061_resume,
};
#endif
static struct amba_id pl061_ids[] = {
{
.id = 0x00041061,
.mask = 0x000fffff,
},
{ 0, 0 },
};
MODULE_DEVICE_TABLE(amba, pl061_ids);
static struct amba_driver pl061_gpio_driver = {
.drv = {
.name = "pl061_gpio",
#ifdef CONFIG_PM
.pm = &pl061_dev_pm_ops,
#endif
},
.id_table = pl061_ids,
.probe = pl061_probe,
};
static int __init pl061_gpio_init(void)
{
return amba_driver_register(&pl061_gpio_driver);
}
module_init(pl061_gpio_init);
MODULE_AUTHOR("Baruch Siach <baruch@tkos.co.il>");
MODULE_DESCRIPTION("PL061 GPIO driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
OpenLD/linux-wetek-3.10.y | drivers/mtd/nand/gpmi-nand/gpmi-lib.c | 2256 | 41757 | /*
* Freescale GPMI NAND Flash Driver
*
* Copyright (C) 2008-2011 Freescale Semiconductor, Inc.
* Copyright (C) 2008 Embedded Alley Solutions, 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <linux/delay.h>
#include <linux/clk.h>
#include "gpmi-nand.h"
#include "gpmi-regs.h"
#include "bch-regs.h"
static struct timing_threshod timing_default_threshold = {
.max_data_setup_cycles = (BM_GPMI_TIMING0_DATA_SETUP >>
BP_GPMI_TIMING0_DATA_SETUP),
.internal_data_setup_in_ns = 0,
.max_sample_delay_factor = (BM_GPMI_CTRL1_RDN_DELAY >>
BP_GPMI_CTRL1_RDN_DELAY),
.max_dll_clock_period_in_ns = 32,
.max_dll_delay_in_ns = 16,
};
#define MXS_SET_ADDR 0x4
#define MXS_CLR_ADDR 0x8
/*
* Clear the bit and poll it cleared. This is usually called with
* a reset address and mask being either SFTRST(bit 31) or CLKGATE
* (bit 30).
*/
static int clear_poll_bit(void __iomem *addr, u32 mask)
{
int timeout = 0x400;
/* clear the bit */
writel(mask, addr + MXS_CLR_ADDR);
/*
* SFTRST needs 3 GPMI clocks to settle, the reference manual
* recommends to wait 1us.
*/
udelay(1);
/* poll the bit becoming clear */
while ((readl(addr) & mask) && --timeout)
/* nothing */;
return !timeout;
}
#define MODULE_CLKGATE (1 << 30)
#define MODULE_SFTRST (1 << 31)
/*
* The current mxs_reset_block() will do two things:
* [1] enable the module.
* [2] reset the module.
*
* In most of the cases, it's ok.
* But in MX23, there is a hardware bug in the BCH block (see erratum #2847).
* If you try to soft reset the BCH block, it becomes unusable until
* the next hard reset. This case occurs in the NAND boot mode. When the board
* boots by NAND, the ROM of the chip will initialize the BCH blocks itself.
* So If the driver tries to reset the BCH again, the BCH will not work anymore.
* You will see a DMA timeout in this case. The bug has been fixed
* in the following chips, such as MX28.
*
* To avoid this bug, just add a new parameter `just_enable` for
* the mxs_reset_block(), and rewrite it here.
*/
static int gpmi_reset_block(void __iomem *reset_addr, bool just_enable)
{
int ret;
int timeout = 0x400;
/* clear and poll SFTRST */
ret = clear_poll_bit(reset_addr, MODULE_SFTRST);
if (unlikely(ret))
goto error;
/* clear CLKGATE */
writel(MODULE_CLKGATE, reset_addr + MXS_CLR_ADDR);
if (!just_enable) {
/* set SFTRST to reset the block */
writel(MODULE_SFTRST, reset_addr + MXS_SET_ADDR);
udelay(1);
/* poll CLKGATE becoming set */
while ((!(readl(reset_addr) & MODULE_CLKGATE)) && --timeout)
/* nothing */;
if (unlikely(!timeout))
goto error;
}
/* clear and poll SFTRST */
ret = clear_poll_bit(reset_addr, MODULE_SFTRST);
if (unlikely(ret))
goto error;
/* clear and poll CLKGATE */
ret = clear_poll_bit(reset_addr, MODULE_CLKGATE);
if (unlikely(ret))
goto error;
return 0;
error:
pr_err("%s(%p): module reset timeout\n", __func__, reset_addr);
return -ETIMEDOUT;
}
static int __gpmi_enable_clk(struct gpmi_nand_data *this, bool v)
{
struct clk *clk;
int ret;
int i;
for (i = 0; i < GPMI_CLK_MAX; i++) {
clk = this->resources.clock[i];
if (!clk)
break;
if (v) {
ret = clk_prepare_enable(clk);
if (ret)
goto err_clk;
} else {
clk_disable_unprepare(clk);
}
}
return 0;
err_clk:
for (; i > 0; i--)
clk_disable_unprepare(this->resources.clock[i - 1]);
return ret;
}
#define gpmi_enable_clk(x) __gpmi_enable_clk(x, true)
#define gpmi_disable_clk(x) __gpmi_enable_clk(x, false)
int gpmi_init(struct gpmi_nand_data *this)
{
struct resources *r = &this->resources;
int ret;
ret = gpmi_enable_clk(this);
if (ret)
goto err_out;
ret = gpmi_reset_block(r->gpmi_regs, false);
if (ret)
goto err_out;
/*
* Reset BCH here, too. We got failures otherwise :(
* See later BCH reset for explanation of MX23 handling
*/
ret = gpmi_reset_block(r->bch_regs, GPMI_IS_MX23(this));
if (ret)
goto err_out;
/* Choose NAND mode. */
writel(BM_GPMI_CTRL1_GPMI_MODE, r->gpmi_regs + HW_GPMI_CTRL1_CLR);
/* Set the IRQ polarity. */
writel(BM_GPMI_CTRL1_ATA_IRQRDY_POLARITY,
r->gpmi_regs + HW_GPMI_CTRL1_SET);
/* Disable Write-Protection. */
writel(BM_GPMI_CTRL1_DEV_RESET, r->gpmi_regs + HW_GPMI_CTRL1_SET);
/* Select BCH ECC. */
writel(BM_GPMI_CTRL1_BCH_MODE, r->gpmi_regs + HW_GPMI_CTRL1_SET);
gpmi_disable_clk(this);
return 0;
err_out:
return ret;
}
/* This function is very useful. It is called only when the bug occur. */
void gpmi_dump_info(struct gpmi_nand_data *this)
{
struct resources *r = &this->resources;
struct bch_geometry *geo = &this->bch_geometry;
u32 reg;
int i;
pr_err("Show GPMI registers :\n");
for (i = 0; i <= HW_GPMI_DEBUG / 0x10 + 1; i++) {
reg = readl(r->gpmi_regs + i * 0x10);
pr_err("offset 0x%.3x : 0x%.8x\n", i * 0x10, reg);
}
/* start to print out the BCH info */
pr_err("Show BCH registers :\n");
for (i = 0; i <= HW_BCH_VERSION / 0x10 + 1; i++) {
reg = readl(r->bch_regs + i * 0x10);
pr_err("offset 0x%.3x : 0x%.8x\n", i * 0x10, reg);
}
pr_err("BCH Geometry :\n");
pr_err("GF length : %u\n", geo->gf_len);
pr_err("ECC Strength : %u\n", geo->ecc_strength);
pr_err("Page Size in Bytes : %u\n", geo->page_size);
pr_err("Metadata Size in Bytes : %u\n", geo->metadata_size);
pr_err("ECC Chunk Size in Bytes: %u\n", geo->ecc_chunk_size);
pr_err("ECC Chunk Count : %u\n", geo->ecc_chunk_count);
pr_err("Payload Size in Bytes : %u\n", geo->payload_size);
pr_err("Auxiliary Size in Bytes: %u\n", geo->auxiliary_size);
pr_err("Auxiliary Status Offset: %u\n", geo->auxiliary_status_offset);
pr_err("Block Mark Byte Offset : %u\n", geo->block_mark_byte_offset);
pr_err("Block Mark Bit Offset : %u\n", geo->block_mark_bit_offset);
}
/* Configures the geometry for BCH. */
int bch_set_geometry(struct gpmi_nand_data *this)
{
struct resources *r = &this->resources;
struct bch_geometry *bch_geo = &this->bch_geometry;
unsigned int block_count;
unsigned int block_size;
unsigned int metadata_size;
unsigned int ecc_strength;
unsigned int page_size;
unsigned int gf_len;
int ret;
if (common_nfc_set_geometry(this))
return !0;
block_count = bch_geo->ecc_chunk_count - 1;
block_size = bch_geo->ecc_chunk_size;
metadata_size = bch_geo->metadata_size;
ecc_strength = bch_geo->ecc_strength >> 1;
page_size = bch_geo->page_size;
gf_len = bch_geo->gf_len;
ret = gpmi_enable_clk(this);
if (ret)
goto err_out;
/*
* Due to erratum #2847 of the MX23, the BCH cannot be soft reset on this
* chip, otherwise it will lock up. So we skip resetting BCH on the MX23.
* On the other hand, the MX28 needs the reset, because one case has been
* seen where the BCH produced ECC errors constantly after 10000
* consecutive reboots. The latter case has not been seen on the MX23 yet,
* still we don't know if it could happen there as well.
*/
ret = gpmi_reset_block(r->bch_regs, GPMI_IS_MX23(this));
if (ret)
goto err_out;
/* Configure layout 0. */
writel(BF_BCH_FLASH0LAYOUT0_NBLOCKS(block_count)
| BF_BCH_FLASH0LAYOUT0_META_SIZE(metadata_size)
| BF_BCH_FLASH0LAYOUT0_ECC0(ecc_strength, this)
| BF_BCH_FLASH0LAYOUT0_GF(gf_len, this)
| BF_BCH_FLASH0LAYOUT0_DATA0_SIZE(block_size, this),
r->bch_regs + HW_BCH_FLASH0LAYOUT0);
writel(BF_BCH_FLASH0LAYOUT1_PAGE_SIZE(page_size)
| BF_BCH_FLASH0LAYOUT1_ECCN(ecc_strength, this)
| BF_BCH_FLASH0LAYOUT1_GF(gf_len, this)
| BF_BCH_FLASH0LAYOUT1_DATAN_SIZE(block_size, this),
r->bch_regs + HW_BCH_FLASH0LAYOUT1);
/* Set *all* chip selects to use layout 0. */
writel(0, r->bch_regs + HW_BCH_LAYOUTSELECT);
/* Enable interrupts. */
writel(BM_BCH_CTRL_COMPLETE_IRQ_EN,
r->bch_regs + HW_BCH_CTRL_SET);
gpmi_disable_clk(this);
return 0;
err_out:
return ret;
}
/* Converts time in nanoseconds to cycles. */
static unsigned int ns_to_cycles(unsigned int time,
unsigned int period, unsigned int min)
{
unsigned int k;
k = (time + period - 1) / period;
return max(k, min);
}
#define DEF_MIN_PROP_DELAY 5
#define DEF_MAX_PROP_DELAY 9
/* Apply timing to current hardware conditions. */
static int gpmi_nfc_compute_hardware_timing(struct gpmi_nand_data *this,
struct gpmi_nfc_hardware_timing *hw)
{
struct timing_threshod *nfc = &timing_default_threshold;
struct resources *r = &this->resources;
struct nand_chip *nand = &this->nand;
struct nand_timing target = this->timing;
bool improved_timing_is_available;
unsigned long clock_frequency_in_hz;
unsigned int clock_period_in_ns;
bool dll_use_half_periods;
unsigned int dll_delay_shift;
unsigned int max_sample_delay_in_ns;
unsigned int address_setup_in_cycles;
unsigned int data_setup_in_ns;
unsigned int data_setup_in_cycles;
unsigned int data_hold_in_cycles;
int ideal_sample_delay_in_ns;
unsigned int sample_delay_factor;
int tEYE;
unsigned int min_prop_delay_in_ns = DEF_MIN_PROP_DELAY;
unsigned int max_prop_delay_in_ns = DEF_MAX_PROP_DELAY;
/*
* If there are multiple chips, we need to relax the timings to allow
* for signal distortion due to higher capacitance.
*/
if (nand->numchips > 2) {
target.data_setup_in_ns += 10;
target.data_hold_in_ns += 10;
target.address_setup_in_ns += 10;
} else if (nand->numchips > 1) {
target.data_setup_in_ns += 5;
target.data_hold_in_ns += 5;
target.address_setup_in_ns += 5;
}
/* Check if improved timing information is available. */
improved_timing_is_available =
(target.tREA_in_ns >= 0) &&
(target.tRLOH_in_ns >= 0) &&
(target.tRHOH_in_ns >= 0) ;
/* Inspect the clock. */
nfc->clock_frequency_in_hz = clk_get_rate(r->clock[0]);
clock_frequency_in_hz = nfc->clock_frequency_in_hz;
clock_period_in_ns = NSEC_PER_SEC / clock_frequency_in_hz;
/*
* The NFC quantizes setup and hold parameters in terms of clock cycles.
* Here, we quantize the setup and hold timing parameters to the
* next-highest clock period to make sure we apply at least the
* specified times.
*
* For data setup and data hold, the hardware interprets a value of zero
* as the largest possible delay. This is not what's intended by a zero
* in the input parameter, so we impose a minimum of one cycle.
*/
data_setup_in_cycles = ns_to_cycles(target.data_setup_in_ns,
clock_period_in_ns, 1);
data_hold_in_cycles = ns_to_cycles(target.data_hold_in_ns,
clock_period_in_ns, 1);
address_setup_in_cycles = ns_to_cycles(target.address_setup_in_ns,
clock_period_in_ns, 0);
/*
* The clock's period affects the sample delay in a number of ways:
*
* (1) The NFC HAL tells us the maximum clock period the sample delay
* DLL can tolerate. If the clock period is greater than half that
* maximum, we must configure the DLL to be driven by half periods.
*
* (2) We need to convert from an ideal sample delay, in ns, to a
* "sample delay factor," which the NFC uses. This factor depends on
* whether we're driving the DLL with full or half periods.
* Paraphrasing the reference manual:
*
* AD = SDF x 0.125 x RP
*
* where:
*
* AD is the applied delay, in ns.
* SDF is the sample delay factor, which is dimensionless.
* RP is the reference period, in ns, which is a full clock period
* if the DLL is being driven by full periods, or half that if
* the DLL is being driven by half periods.
*
* Let's re-arrange this in a way that's more useful to us:
*
* 8
* SDF = AD x ----
* RP
*
* The reference period is either the clock period or half that, so this
* is:
*
* 8 AD x DDF
* SDF = AD x ----- = --------
* f x P P
*
* where:
*
* f is 1 or 1/2, depending on how we're driving the DLL.
* P is the clock period.
* DDF is the DLL Delay Factor, a dimensionless value that
* incorporates all the constants in the conversion.
*
* DDF will be either 8 or 16, both of which are powers of two. We can
* reduce the cost of this conversion by using bit shifts instead of
* multiplication or division. Thus:
*
* AD << DDS
* SDF = ---------
* P
*
* or
*
* AD = (SDF >> DDS) x P
*
* where:
*
* DDS is the DLL Delay Shift, the logarithm to base 2 of the DDF.
*/
if (clock_period_in_ns > (nfc->max_dll_clock_period_in_ns >> 1)) {
dll_use_half_periods = true;
dll_delay_shift = 3 + 1;
} else {
dll_use_half_periods = false;
dll_delay_shift = 3;
}
/*
* Compute the maximum sample delay the NFC allows, under current
* conditions. If the clock is running too slowly, no sample delay is
* possible.
*/
if (clock_period_in_ns > nfc->max_dll_clock_period_in_ns)
max_sample_delay_in_ns = 0;
else {
/*
* Compute the delay implied by the largest sample delay factor
* the NFC allows.
*/
max_sample_delay_in_ns =
(nfc->max_sample_delay_factor * clock_period_in_ns) >>
dll_delay_shift;
/*
* Check if the implied sample delay larger than the NFC
* actually allows.
*/
if (max_sample_delay_in_ns > nfc->max_dll_delay_in_ns)
max_sample_delay_in_ns = nfc->max_dll_delay_in_ns;
}
/*
* Check if improved timing information is available. If not, we have to
* use a less-sophisticated algorithm.
*/
if (!improved_timing_is_available) {
/*
* Fold the read setup time required by the NFC into the ideal
* sample delay.
*/
ideal_sample_delay_in_ns = target.gpmi_sample_delay_in_ns +
nfc->internal_data_setup_in_ns;
/*
* The ideal sample delay may be greater than the maximum
* allowed by the NFC. If so, we can trade off sample delay time
* for more data setup time.
*
* In each iteration of the following loop, we add a cycle to
* the data setup time and subtract a corresponding amount from
* the sample delay until we've satisified the constraints or
* can't do any better.
*/
while ((ideal_sample_delay_in_ns > max_sample_delay_in_ns) &&
(data_setup_in_cycles < nfc->max_data_setup_cycles)) {
data_setup_in_cycles++;
ideal_sample_delay_in_ns -= clock_period_in_ns;
if (ideal_sample_delay_in_ns < 0)
ideal_sample_delay_in_ns = 0;
}
/*
* Compute the sample delay factor that corresponds most closely
* to the ideal sample delay. If the result is too large for the
* NFC, use the maximum value.
*
* Notice that we use the ns_to_cycles function to compute the
* sample delay factor. We do this because the form of the
* computation is the same as that for calculating cycles.
*/
sample_delay_factor =
ns_to_cycles(
ideal_sample_delay_in_ns << dll_delay_shift,
clock_period_in_ns, 0);
if (sample_delay_factor > nfc->max_sample_delay_factor)
sample_delay_factor = nfc->max_sample_delay_factor;
/* Skip to the part where we return our results. */
goto return_results;
}
/*
* If control arrives here, we have more detailed timing information,
* so we can use a better algorithm.
*/
/*
* Fold the read setup time required by the NFC into the maximum
* propagation delay.
*/
max_prop_delay_in_ns += nfc->internal_data_setup_in_ns;
/*
* Earlier, we computed the number of clock cycles required to satisfy
* the data setup time. Now, we need to know the actual nanoseconds.
*/
data_setup_in_ns = clock_period_in_ns * data_setup_in_cycles;
/*
* Compute tEYE, the width of the data eye when reading from the NAND
* Flash. The eye width is fundamentally determined by the data setup
* time, perturbed by propagation delays and some characteristics of the
* NAND Flash device.
*
* start of the eye = max_prop_delay + tREA
* end of the eye = min_prop_delay + tRHOH + data_setup
*/
tEYE = (int)min_prop_delay_in_ns + (int)target.tRHOH_in_ns +
(int)data_setup_in_ns;
tEYE -= (int)max_prop_delay_in_ns + (int)target.tREA_in_ns;
/*
* The eye must be open. If it's not, we can try to open it by
* increasing its main forcer, the data setup time.
*
* In each iteration of the following loop, we increase the data setup
* time by a single clock cycle. We do this until either the eye is
* open or we run into NFC limits.
*/
while ((tEYE <= 0) &&
(data_setup_in_cycles < nfc->max_data_setup_cycles)) {
/* Give a cycle to data setup. */
data_setup_in_cycles++;
/* Synchronize the data setup time with the cycles. */
data_setup_in_ns += clock_period_in_ns;
/* Adjust tEYE accordingly. */
tEYE += clock_period_in_ns;
}
/*
* When control arrives here, the eye is open. The ideal time to sample
* the data is in the center of the eye:
*
* end of the eye + start of the eye
* --------------------------------- - data_setup
* 2
*
* After some algebra, this simplifies to the code immediately below.
*/
ideal_sample_delay_in_ns =
((int)max_prop_delay_in_ns +
(int)target.tREA_in_ns +
(int)min_prop_delay_in_ns +
(int)target.tRHOH_in_ns -
(int)data_setup_in_ns) >> 1;
/*
* The following figure illustrates some aspects of a NAND Flash read:
*
*
* __ _____________________________________
* RDN \_________________/
*
* <---- tEYE ----->
* /-----------------\
* Read Data ----------------------------< >---------
* \-----------------/
* ^ ^ ^ ^
* | | | |
* |<--Data Setup -->|<--Delay Time -->| |
* | | | |
* | | |
* | |<-- Quantized Delay Time -->|
* | | |
*
*
* We have some issues we must now address:
*
* (1) The *ideal* sample delay time must not be negative. If it is, we
* jam it to zero.
*
* (2) The *ideal* sample delay time must not be greater than that
* allowed by the NFC. If it is, we can increase the data setup
* time, which will reduce the delay between the end of the data
* setup and the center of the eye. It will also make the eye
* larger, which might help with the next issue...
*
* (3) The *quantized* sample delay time must not fall either before the
* eye opens or after it closes (the latter is the problem
* illustrated in the above figure).
*/
/* Jam a negative ideal sample delay to zero. */
if (ideal_sample_delay_in_ns < 0)
ideal_sample_delay_in_ns = 0;
/*
* Extend the data setup as needed to reduce the ideal sample delay
* below the maximum permitted by the NFC.
*/
while ((ideal_sample_delay_in_ns > max_sample_delay_in_ns) &&
(data_setup_in_cycles < nfc->max_data_setup_cycles)) {
/* Give a cycle to data setup. */
data_setup_in_cycles++;
/* Synchronize the data setup time with the cycles. */
data_setup_in_ns += clock_period_in_ns;
/* Adjust tEYE accordingly. */
tEYE += clock_period_in_ns;
/*
* Decrease the ideal sample delay by one half cycle, to keep it
* in the middle of the eye.
*/
ideal_sample_delay_in_ns -= (clock_period_in_ns >> 1);
/* Jam a negative ideal sample delay to zero. */
if (ideal_sample_delay_in_ns < 0)
ideal_sample_delay_in_ns = 0;
}
/*
* Compute the sample delay factor that corresponds to the ideal sample
* delay. If the result is too large, then use the maximum allowed
* value.
*
* Notice that we use the ns_to_cycles function to compute the sample
* delay factor. We do this because the form of the computation is the
* same as that for calculating cycles.
*/
sample_delay_factor =
ns_to_cycles(ideal_sample_delay_in_ns << dll_delay_shift,
clock_period_in_ns, 0);
if (sample_delay_factor > nfc->max_sample_delay_factor)
sample_delay_factor = nfc->max_sample_delay_factor;
/*
* These macros conveniently encapsulate a computation we'll use to
* continuously evaluate whether or not the data sample delay is inside
* the eye.
*/
#define IDEAL_DELAY ((int) ideal_sample_delay_in_ns)
#define QUANTIZED_DELAY \
((int) ((sample_delay_factor * clock_period_in_ns) >> \
dll_delay_shift))
#define DELAY_ERROR (abs(QUANTIZED_DELAY - IDEAL_DELAY))
#define SAMPLE_IS_NOT_WITHIN_THE_EYE (DELAY_ERROR > (tEYE >> 1))
/*
* While the quantized sample time falls outside the eye, reduce the
* sample delay or extend the data setup to move the sampling point back
* toward the eye. Do not allow the number of data setup cycles to
* exceed the maximum allowed by the NFC.
*/
while (SAMPLE_IS_NOT_WITHIN_THE_EYE &&
(data_setup_in_cycles < nfc->max_data_setup_cycles)) {
/*
* If control arrives here, the quantized sample delay falls
* outside the eye. Check if it's before the eye opens, or after
* the eye closes.
*/
if (QUANTIZED_DELAY > IDEAL_DELAY) {
/*
* If control arrives here, the quantized sample delay
* falls after the eye closes. Decrease the quantized
* delay time and then go back to re-evaluate.
*/
if (sample_delay_factor != 0)
sample_delay_factor--;
continue;
}
/*
* If control arrives here, the quantized sample delay falls
* before the eye opens. Shift the sample point by increasing
* data setup time. This will also make the eye larger.
*/
/* Give a cycle to data setup. */
data_setup_in_cycles++;
/* Synchronize the data setup time with the cycles. */
data_setup_in_ns += clock_period_in_ns;
/* Adjust tEYE accordingly. */
tEYE += clock_period_in_ns;
/*
* Decrease the ideal sample delay by one half cycle, to keep it
* in the middle of the eye.
*/
ideal_sample_delay_in_ns -= (clock_period_in_ns >> 1);
/* ...and one less period for the delay time. */
ideal_sample_delay_in_ns -= clock_period_in_ns;
/* Jam a negative ideal sample delay to zero. */
if (ideal_sample_delay_in_ns < 0)
ideal_sample_delay_in_ns = 0;
/*
* We have a new ideal sample delay, so re-compute the quantized
* delay.
*/
sample_delay_factor =
ns_to_cycles(
ideal_sample_delay_in_ns << dll_delay_shift,
clock_period_in_ns, 0);
if (sample_delay_factor > nfc->max_sample_delay_factor)
sample_delay_factor = nfc->max_sample_delay_factor;
}
/* Control arrives here when we're ready to return our results. */
return_results:
hw->data_setup_in_cycles = data_setup_in_cycles;
hw->data_hold_in_cycles = data_hold_in_cycles;
hw->address_setup_in_cycles = address_setup_in_cycles;
hw->use_half_periods = dll_use_half_periods;
hw->sample_delay_factor = sample_delay_factor;
hw->device_busy_timeout = GPMI_DEFAULT_BUSY_TIMEOUT;
hw->wrn_dly_sel = BV_GPMI_CTRL1_WRN_DLY_SEL_4_TO_8NS;
/* Return success. */
return 0;
}
/*
* <1> Firstly, we should know what's the GPMI-clock means.
* The GPMI-clock is the internal clock in the gpmi nand controller.
* If you set 100MHz to gpmi nand controller, the GPMI-clock's period
* is 10ns. Mark the GPMI-clock's period as GPMI-clock-period.
*
* <2> Secondly, we should know what's the frequency on the nand chip pins.
* The frequency on the nand chip pins is derived from the GPMI-clock.
* We can get it from the following equation:
*
* F = G / (DS + DH)
*
* F : the frequency on the nand chip pins.
* G : the GPMI clock, such as 100MHz.
* DS : GPMI_HW_GPMI_TIMING0:DATA_SETUP
* DH : GPMI_HW_GPMI_TIMING0:DATA_HOLD
*
* <3> Thirdly, when the frequency on the nand chip pins is above 33MHz,
* the nand EDO(extended Data Out) timing could be applied.
* The GPMI implements a feedback read strobe to sample the read data.
* The feedback read strobe can be delayed to support the nand EDO timing
* where the read strobe may deasserts before the read data is valid, and
* read data is valid for some time after read strobe.
*
* The following figure illustrates some aspects of a NAND Flash read:
*
* |<---tREA---->|
* | |
* | | |
* |<--tRP-->| |
* | | |
* __ ___|__________________________________
* RDN \________/ |
* |
* /---------\
* Read Data --------------< >---------
* \---------/
* | |
* |<-D->|
* FeedbackRDN ________ ____________
* \___________/
*
* D stands for delay, set in the HW_GPMI_CTRL1:RDN_DELAY.
*
*
* <4> Now, we begin to describe how to compute the right RDN_DELAY.
*
* 4.1) From the aspect of the nand chip pins:
* Delay = (tREA + C - tRP) {1}
*
* tREA : the maximum read access time. From the ONFI nand standards,
* we know that tREA is 16ns in mode 5, tREA is 20ns is mode 4.
* Please check it in : www.onfi.org
* C : a constant for adjust the delay. default is 4.
* tRP : the read pulse width.
* Specified by the HW_GPMI_TIMING0:DATA_SETUP:
* tRP = (GPMI-clock-period) * DATA_SETUP
*
* 4.2) From the aspect of the GPMI nand controller:
* Delay = RDN_DELAY * 0.125 * RP {2}
*
* RP : the DLL reference period.
* if (GPMI-clock-period > DLL_THRETHOLD)
* RP = GPMI-clock-period / 2;
* else
* RP = GPMI-clock-period;
*
* Set the HW_GPMI_CTRL1:HALF_PERIOD if GPMI-clock-period
* is greater DLL_THRETHOLD. In other SOCs, the DLL_THRETHOLD
* is 16ns, but in mx6q, we use 12ns.
*
* 4.3) since {1} equals {2}, we get:
*
* (tREA + 4 - tRP) * 8
* RDN_DELAY = --------------------- {3}
* RP
*
* 4.4) We only support the fastest asynchronous mode of ONFI nand.
* For some ONFI nand, the mode 4 is the fastest mode;
* while for some ONFI nand, the mode 5 is the fastest mode.
* So we only support the mode 4 and mode 5. It is no need to
* support other modes.
*/
static void gpmi_compute_edo_timing(struct gpmi_nand_data *this,
struct gpmi_nfc_hardware_timing *hw)
{
struct resources *r = &this->resources;
unsigned long rate = clk_get_rate(r->clock[0]);
int mode = this->timing_mode;
int dll_threshold = 16; /* in ns */
unsigned long delay;
unsigned long clk_period;
int t_rea;
int c = 4;
int t_rp;
int rp;
/*
* [1] for GPMI_HW_GPMI_TIMING0:
* The async mode requires 40MHz for mode 4, 50MHz for mode 5.
* The GPMI can support 100MHz at most. So if we want to
* get the 40MHz or 50MHz, we have to set DS=1, DH=1.
* Set the ADDRESS_SETUP to 0 in mode 4.
*/
hw->data_setup_in_cycles = 1;
hw->data_hold_in_cycles = 1;
hw->address_setup_in_cycles = ((mode == 5) ? 1 : 0);
/* [2] for GPMI_HW_GPMI_TIMING1 */
hw->device_busy_timeout = 0x9000;
/* [3] for GPMI_HW_GPMI_CTRL1 */
hw->wrn_dly_sel = BV_GPMI_CTRL1_WRN_DLY_SEL_NO_DELAY;
if (GPMI_IS_MX6Q(this))
dll_threshold = 12;
/*
* Enlarge 10 times for the numerator and denominator in {3}.
* This make us to get more accurate result.
*/
clk_period = NSEC_PER_SEC / (rate / 10);
dll_threshold *= 10;
t_rea = ((mode == 5) ? 16 : 20) * 10;
c *= 10;
t_rp = clk_period * 1; /* DATA_SETUP is 1 */
if (clk_period > dll_threshold) {
hw->use_half_periods = 1;
rp = clk_period / 2;
} else {
hw->use_half_periods = 0;
rp = clk_period;
}
/*
* Multiply the numerator with 10, we could do a round off:
* 7.8 round up to 8; 7.4 round down to 7.
*/
delay = (((t_rea + c - t_rp) * 8) * 10) / rp;
delay = (delay + 5) / 10;
hw->sample_delay_factor = delay;
}
static int enable_edo_mode(struct gpmi_nand_data *this, int mode)
{
struct resources *r = &this->resources;
struct nand_chip *nand = &this->nand;
struct mtd_info *mtd = &this->mtd;
uint8_t feature[ONFI_SUBFEATURE_PARAM_LEN] = {};
unsigned long rate;
int ret;
nand->select_chip(mtd, 0);
/* [1] send SET FEATURE commond to NAND */
feature[0] = mode;
ret = nand->onfi_set_features(mtd, nand,
ONFI_FEATURE_ADDR_TIMING_MODE, feature);
if (ret)
goto err_out;
/* [2] send GET FEATURE command to double-check the timing mode */
memset(feature, 0, ONFI_SUBFEATURE_PARAM_LEN);
ret = nand->onfi_get_features(mtd, nand,
ONFI_FEATURE_ADDR_TIMING_MODE, feature);
if (ret || feature[0] != mode)
goto err_out;
nand->select_chip(mtd, -1);
/* [3] set the main IO clock, 100MHz for mode 5, 80MHz for mode 4. */
rate = (mode == 5) ? 100000000 : 80000000;
clk_set_rate(r->clock[0], rate);
/* Let the gpmi_begin() re-compute the timing again. */
this->flags &= ~GPMI_TIMING_INIT_OK;
this->flags |= GPMI_ASYNC_EDO_ENABLED;
this->timing_mode = mode;
dev_info(this->dev, "enable the asynchronous EDO mode %d\n", mode);
return 0;
err_out:
nand->select_chip(mtd, -1);
dev_err(this->dev, "mode:%d ,failed in set feature.\n", mode);
return -EINVAL;
}
int gpmi_extra_init(struct gpmi_nand_data *this)
{
struct nand_chip *chip = &this->nand;
/* Enable the asynchronous EDO feature. */
if (GPMI_IS_MX6Q(this) && chip->onfi_version) {
int mode = onfi_get_async_timing_mode(chip);
/* We only support the timing mode 4 and mode 5. */
if (mode & ONFI_TIMING_MODE_5)
mode = 5;
else if (mode & ONFI_TIMING_MODE_4)
mode = 4;
else
return 0;
return enable_edo_mode(this, mode);
}
return 0;
}
/* Begin the I/O */
void gpmi_begin(struct gpmi_nand_data *this)
{
struct resources *r = &this->resources;
void __iomem *gpmi_regs = r->gpmi_regs;
unsigned int clock_period_in_ns;
uint32_t reg;
unsigned int dll_wait_time_in_us;
struct gpmi_nfc_hardware_timing hw;
int ret;
/* Enable the clock. */
ret = gpmi_enable_clk(this);
if (ret) {
pr_err("We failed in enable the clk\n");
goto err_out;
}
/* Only initialize the timing once */
if (this->flags & GPMI_TIMING_INIT_OK)
return;
this->flags |= GPMI_TIMING_INIT_OK;
if (this->flags & GPMI_ASYNC_EDO_ENABLED)
gpmi_compute_edo_timing(this, &hw);
else
gpmi_nfc_compute_hardware_timing(this, &hw);
/* [1] Set HW_GPMI_TIMING0 */
reg = BF_GPMI_TIMING0_ADDRESS_SETUP(hw.address_setup_in_cycles) |
BF_GPMI_TIMING0_DATA_HOLD(hw.data_hold_in_cycles) |
BF_GPMI_TIMING0_DATA_SETUP(hw.data_setup_in_cycles) ;
writel(reg, gpmi_regs + HW_GPMI_TIMING0);
/* [2] Set HW_GPMI_TIMING1 */
writel(BF_GPMI_TIMING1_BUSY_TIMEOUT(hw.device_busy_timeout),
gpmi_regs + HW_GPMI_TIMING1);
/* [3] The following code is to set the HW_GPMI_CTRL1. */
/* Set the WRN_DLY_SEL */
writel(BM_GPMI_CTRL1_WRN_DLY_SEL, gpmi_regs + HW_GPMI_CTRL1_CLR);
writel(BF_GPMI_CTRL1_WRN_DLY_SEL(hw.wrn_dly_sel),
gpmi_regs + HW_GPMI_CTRL1_SET);
/* DLL_ENABLE must be set to 0 when setting RDN_DELAY or HALF_PERIOD. */
writel(BM_GPMI_CTRL1_DLL_ENABLE, gpmi_regs + HW_GPMI_CTRL1_CLR);
/* Clear out the DLL control fields. */
reg = BM_GPMI_CTRL1_RDN_DELAY | BM_GPMI_CTRL1_HALF_PERIOD;
writel(reg, gpmi_regs + HW_GPMI_CTRL1_CLR);
/* If no sample delay is called for, return immediately. */
if (!hw.sample_delay_factor)
return;
/* Set RDN_DELAY or HALF_PERIOD. */
reg = ((hw.use_half_periods) ? BM_GPMI_CTRL1_HALF_PERIOD : 0)
| BF_GPMI_CTRL1_RDN_DELAY(hw.sample_delay_factor);
writel(reg, gpmi_regs + HW_GPMI_CTRL1_SET);
/* At last, we enable the DLL. */
writel(BM_GPMI_CTRL1_DLL_ENABLE, gpmi_regs + HW_GPMI_CTRL1_SET);
/*
* After we enable the GPMI DLL, we have to wait 64 clock cycles before
* we can use the GPMI. Calculate the amount of time we need to wait,
* in microseconds.
*/
clock_period_in_ns = NSEC_PER_SEC / clk_get_rate(r->clock[0]);
dll_wait_time_in_us = (clock_period_in_ns * 64) / 1000;
if (!dll_wait_time_in_us)
dll_wait_time_in_us = 1;
/* Wait for the DLL to settle. */
udelay(dll_wait_time_in_us);
err_out:
return;
}
void gpmi_end(struct gpmi_nand_data *this)
{
gpmi_disable_clk(this);
}
/* Clears a BCH interrupt. */
void gpmi_clear_bch(struct gpmi_nand_data *this)
{
struct resources *r = &this->resources;
writel(BM_BCH_CTRL_COMPLETE_IRQ, r->bch_regs + HW_BCH_CTRL_CLR);
}
/* Returns the Ready/Busy status of the given chip. */
int gpmi_is_ready(struct gpmi_nand_data *this, unsigned chip)
{
struct resources *r = &this->resources;
uint32_t mask = 0;
uint32_t reg = 0;
if (GPMI_IS_MX23(this)) {
mask = MX23_BM_GPMI_DEBUG_READY0 << chip;
reg = readl(r->gpmi_regs + HW_GPMI_DEBUG);
} else if (GPMI_IS_MX28(this) || GPMI_IS_MX6Q(this)) {
/* MX28 shares the same R/B register as MX6Q. */
mask = MX28_BF_GPMI_STAT_READY_BUSY(1 << chip);
reg = readl(r->gpmi_regs + HW_GPMI_STAT);
} else
pr_err("unknow arch.\n");
return reg & mask;
}
static inline void set_dma_type(struct gpmi_nand_data *this,
enum dma_ops_type type)
{
this->last_dma_type = this->dma_type;
this->dma_type = type;
}
int gpmi_send_command(struct gpmi_nand_data *this)
{
struct dma_chan *channel = get_dma_chan(this);
struct dma_async_tx_descriptor *desc;
struct scatterlist *sgl;
int chip = this->current_chip;
u32 pio[3];
/* [1] send out the PIO words */
pio[0] = BF_GPMI_CTRL0_COMMAND_MODE(BV_GPMI_CTRL0_COMMAND_MODE__WRITE)
| BM_GPMI_CTRL0_WORD_LENGTH
| BF_GPMI_CTRL0_CS(chip, this)
| BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
| BF_GPMI_CTRL0_ADDRESS(BV_GPMI_CTRL0_ADDRESS__NAND_CLE)
| BM_GPMI_CTRL0_ADDRESS_INCREMENT
| BF_GPMI_CTRL0_XFER_COUNT(this->command_length);
pio[1] = pio[2] = 0;
desc = dmaengine_prep_slave_sg(channel,
(struct scatterlist *)pio,
ARRAY_SIZE(pio), DMA_TRANS_NONE, 0);
if (!desc) {
pr_err("step 1 error\n");
return -1;
}
/* [2] send out the COMMAND + ADDRESS string stored in @buffer */
sgl = &this->cmd_sgl;
sg_init_one(sgl, this->cmd_buffer, this->command_length);
dma_map_sg(this->dev, sgl, 1, DMA_TO_DEVICE);
desc = dmaengine_prep_slave_sg(channel,
sgl, 1, DMA_MEM_TO_DEV,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!desc) {
pr_err("step 2 error\n");
return -1;
}
/* [3] submit the DMA */
set_dma_type(this, DMA_FOR_COMMAND);
return start_dma_without_bch_irq(this, desc);
}
int gpmi_send_data(struct gpmi_nand_data *this)
{
struct dma_async_tx_descriptor *desc;
struct dma_chan *channel = get_dma_chan(this);
int chip = this->current_chip;
uint32_t command_mode;
uint32_t address;
u32 pio[2];
/* [1] PIO */
command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WRITE;
address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA;
pio[0] = BF_GPMI_CTRL0_COMMAND_MODE(command_mode)
| BM_GPMI_CTRL0_WORD_LENGTH
| BF_GPMI_CTRL0_CS(chip, this)
| BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
| BF_GPMI_CTRL0_ADDRESS(address)
| BF_GPMI_CTRL0_XFER_COUNT(this->upper_len);
pio[1] = 0;
desc = dmaengine_prep_slave_sg(channel, (struct scatterlist *)pio,
ARRAY_SIZE(pio), DMA_TRANS_NONE, 0);
if (!desc) {
pr_err("step 1 error\n");
return -1;
}
/* [2] send DMA request */
prepare_data_dma(this, DMA_TO_DEVICE);
desc = dmaengine_prep_slave_sg(channel, &this->data_sgl,
1, DMA_MEM_TO_DEV,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!desc) {
pr_err("step 2 error\n");
return -1;
}
/* [3] submit the DMA */
set_dma_type(this, DMA_FOR_WRITE_DATA);
return start_dma_without_bch_irq(this, desc);
}
int gpmi_read_data(struct gpmi_nand_data *this)
{
struct dma_async_tx_descriptor *desc;
struct dma_chan *channel = get_dma_chan(this);
int chip = this->current_chip;
u32 pio[2];
/* [1] : send PIO */
pio[0] = BF_GPMI_CTRL0_COMMAND_MODE(BV_GPMI_CTRL0_COMMAND_MODE__READ)
| BM_GPMI_CTRL0_WORD_LENGTH
| BF_GPMI_CTRL0_CS(chip, this)
| BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
| BF_GPMI_CTRL0_ADDRESS(BV_GPMI_CTRL0_ADDRESS__NAND_DATA)
| BF_GPMI_CTRL0_XFER_COUNT(this->upper_len);
pio[1] = 0;
desc = dmaengine_prep_slave_sg(channel,
(struct scatterlist *)pio,
ARRAY_SIZE(pio), DMA_TRANS_NONE, 0);
if (!desc) {
pr_err("step 1 error\n");
return -1;
}
/* [2] : send DMA request */
prepare_data_dma(this, DMA_FROM_DEVICE);
desc = dmaengine_prep_slave_sg(channel, &this->data_sgl,
1, DMA_DEV_TO_MEM,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!desc) {
pr_err("step 2 error\n");
return -1;
}
/* [3] : submit the DMA */
set_dma_type(this, DMA_FOR_READ_DATA);
return start_dma_without_bch_irq(this, desc);
}
int gpmi_send_page(struct gpmi_nand_data *this,
dma_addr_t payload, dma_addr_t auxiliary)
{
struct bch_geometry *geo = &this->bch_geometry;
uint32_t command_mode;
uint32_t address;
uint32_t ecc_command;
uint32_t buffer_mask;
struct dma_async_tx_descriptor *desc;
struct dma_chan *channel = get_dma_chan(this);
int chip = this->current_chip;
u32 pio[6];
/* A DMA descriptor that does an ECC page read. */
command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WRITE;
address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA;
ecc_command = BV_GPMI_ECCCTRL_ECC_CMD__BCH_ENCODE;
buffer_mask = BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_PAGE |
BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_AUXONLY;
pio[0] = BF_GPMI_CTRL0_COMMAND_MODE(command_mode)
| BM_GPMI_CTRL0_WORD_LENGTH
| BF_GPMI_CTRL0_CS(chip, this)
| BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
| BF_GPMI_CTRL0_ADDRESS(address)
| BF_GPMI_CTRL0_XFER_COUNT(0);
pio[1] = 0;
pio[2] = BM_GPMI_ECCCTRL_ENABLE_ECC
| BF_GPMI_ECCCTRL_ECC_CMD(ecc_command)
| BF_GPMI_ECCCTRL_BUFFER_MASK(buffer_mask);
pio[3] = geo->page_size;
pio[4] = payload;
pio[5] = auxiliary;
desc = dmaengine_prep_slave_sg(channel,
(struct scatterlist *)pio,
ARRAY_SIZE(pio), DMA_TRANS_NONE,
DMA_CTRL_ACK);
if (!desc) {
pr_err("step 2 error\n");
return -1;
}
set_dma_type(this, DMA_FOR_WRITE_ECC_PAGE);
return start_dma_with_bch_irq(this, desc);
}
int gpmi_read_page(struct gpmi_nand_data *this,
dma_addr_t payload, dma_addr_t auxiliary)
{
struct bch_geometry *geo = &this->bch_geometry;
uint32_t command_mode;
uint32_t address;
uint32_t ecc_command;
uint32_t buffer_mask;
struct dma_async_tx_descriptor *desc;
struct dma_chan *channel = get_dma_chan(this);
int chip = this->current_chip;
u32 pio[6];
/* [1] Wait for the chip to report ready. */
command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WAIT_FOR_READY;
address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA;
pio[0] = BF_GPMI_CTRL0_COMMAND_MODE(command_mode)
| BM_GPMI_CTRL0_WORD_LENGTH
| BF_GPMI_CTRL0_CS(chip, this)
| BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
| BF_GPMI_CTRL0_ADDRESS(address)
| BF_GPMI_CTRL0_XFER_COUNT(0);
pio[1] = 0;
desc = dmaengine_prep_slave_sg(channel,
(struct scatterlist *)pio, 2,
DMA_TRANS_NONE, 0);
if (!desc) {
pr_err("step 1 error\n");
return -1;
}
/* [2] Enable the BCH block and read. */
command_mode = BV_GPMI_CTRL0_COMMAND_MODE__READ;
address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA;
ecc_command = BV_GPMI_ECCCTRL_ECC_CMD__BCH_DECODE;
buffer_mask = BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_PAGE
| BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_AUXONLY;
pio[0] = BF_GPMI_CTRL0_COMMAND_MODE(command_mode)
| BM_GPMI_CTRL0_WORD_LENGTH
| BF_GPMI_CTRL0_CS(chip, this)
| BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
| BF_GPMI_CTRL0_ADDRESS(address)
| BF_GPMI_CTRL0_XFER_COUNT(geo->page_size);
pio[1] = 0;
pio[2] = BM_GPMI_ECCCTRL_ENABLE_ECC
| BF_GPMI_ECCCTRL_ECC_CMD(ecc_command)
| BF_GPMI_ECCCTRL_BUFFER_MASK(buffer_mask);
pio[3] = geo->page_size;
pio[4] = payload;
pio[5] = auxiliary;
desc = dmaengine_prep_slave_sg(channel,
(struct scatterlist *)pio,
ARRAY_SIZE(pio), DMA_TRANS_NONE,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!desc) {
pr_err("step 2 error\n");
return -1;
}
/* [3] Disable the BCH block */
command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WAIT_FOR_READY;
address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA;
pio[0] = BF_GPMI_CTRL0_COMMAND_MODE(command_mode)
| BM_GPMI_CTRL0_WORD_LENGTH
| BF_GPMI_CTRL0_CS(chip, this)
| BF_GPMI_CTRL0_LOCK_CS(LOCK_CS_ENABLE, this)
| BF_GPMI_CTRL0_ADDRESS(address)
| BF_GPMI_CTRL0_XFER_COUNT(geo->page_size);
pio[1] = 0;
pio[2] = 0; /* clear GPMI_HW_GPMI_ECCCTRL, disable the BCH. */
desc = dmaengine_prep_slave_sg(channel,
(struct scatterlist *)pio, 3,
DMA_TRANS_NONE,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!desc) {
pr_err("step 3 error\n");
return -1;
}
/* [4] submit the DMA */
set_dma_type(this, DMA_FOR_READ_ECC_PAGE);
return start_dma_with_bch_irq(this, desc);
}
| gpl-2.0 |
moddingg33k/deprecated_android_kernel_synopsis | drivers/net/wireless/bcmdhd/aiutils.c | 2256 | 17842 | /*
* Misc utility routines for accessing chip-specific features
* of the SiliconBackplane-based Broadcom chips.
*
* 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: aiutils.c 321247 2012-03-14 21:14:33Z $
*/
#include <bcm_cfg.h>
#include <typedefs.h>
#include <bcmdefs.h>
#include <osl.h>
#include <bcmutils.h>
#include <siutils.h>
#include <hndsoc.h>
#include <sbchipc.h>
#include <pcicfg.h>
#include "siutils_priv.h"
#define BCM47162_DMP() (0)
#define BCM5357_DMP() (0)
#define remap_coreid(sih, coreid) (coreid)
#define remap_corerev(sih, corerev) (corerev)
static uint32
get_erom_ent(si_t *sih, uint32 **eromptr, uint32 mask, uint32 match)
{
uint32 ent;
uint inv = 0, nom = 0;
while (TRUE) {
ent = R_REG(si_osh(sih), *eromptr);
(*eromptr)++;
if (mask == 0)
break;
if ((ent & ER_VALID) == 0) {
inv++;
continue;
}
if (ent == (ER_END | ER_VALID))
break;
if ((ent & mask) == match)
break;
nom++;
}
SI_VMSG(("%s: Returning ent 0x%08x\n", __FUNCTION__, ent));
if (inv + nom) {
SI_VMSG((" after %d invalid and %d non-matching entries\n", inv, nom));
}
return ent;
}
static uint32
get_asd(si_t *sih, uint32 **eromptr, uint sp, uint ad, uint st, uint32 *addrl, uint32 *addrh,
uint32 *sizel, uint32 *sizeh)
{
uint32 asd, sz, szd;
asd = get_erom_ent(sih, eromptr, ER_VALID, ER_VALID);
if (((asd & ER_TAG1) != ER_ADD) ||
(((asd & AD_SP_MASK) >> AD_SP_SHIFT) != sp) ||
((asd & AD_ST_MASK) != st)) {
(*eromptr)--;
return 0;
}
*addrl = asd & AD_ADDR_MASK;
if (asd & AD_AG32)
*addrh = get_erom_ent(sih, eromptr, 0, 0);
else
*addrh = 0;
*sizeh = 0;
sz = asd & AD_SZ_MASK;
if (sz == AD_SZ_SZD) {
szd = get_erom_ent(sih, eromptr, 0, 0);
*sizel = szd & SD_SZ_MASK;
if (szd & SD_SG32)
*sizeh = get_erom_ent(sih, eromptr, 0, 0);
} else
*sizel = AD_SZ_BASE << (sz >> AD_SZ_SHIFT);
SI_VMSG((" SP %d, ad %d: st = %d, 0x%08x_0x%08x @ 0x%08x_0x%08x\n",
sp, ad, st, *sizeh, *sizel, *addrh, *addrl));
return asd;
}
static void
ai_hwfixup(si_info_t *sii)
{
}
void
ai_scan(si_t *sih, void *regs, uint devid)
{
si_info_t *sii = SI_INFO(sih);
chipcregs_t *cc = (chipcregs_t *)regs;
uint32 erombase, *eromptr, *eromlim;
erombase = R_REG(sii->osh, &cc->eromptr);
switch (BUSTYPE(sih->bustype)) {
case SI_BUS:
eromptr = (uint32 *)REG_MAP(erombase, SI_CORE_SIZE);
break;
case PCI_BUS:
sii->curwrap = (void *)((uintptr)regs + SI_CORE_SIZE);
OSL_PCI_WRITE_CONFIG(sii->osh, PCI_BAR0_WIN, 4, erombase);
eromptr = regs;
break;
case SPI_BUS:
case SDIO_BUS:
eromptr = (uint32 *)(uintptr)erombase;
break;
case PCMCIA_BUS:
default:
SI_ERROR(("Don't know how to do AXI enumertion on bus %d\n", sih->bustype));
ASSERT(0);
return;
}
eromlim = eromptr + (ER_REMAPCONTROL / sizeof(uint32));
SI_VMSG(("ai_scan: regs = 0x%p, erombase = 0x%08x, eromptr = 0x%p, eromlim = 0x%p\n",
regs, erombase, eromptr, eromlim));
while (eromptr < eromlim) {
uint32 cia, cib, cid, mfg, crev, nmw, nsw, nmp, nsp;
uint32 mpd, asd, addrl, addrh, sizel, sizeh;
uint i, j, idx;
bool br;
br = FALSE;
cia = get_erom_ent(sih, &eromptr, ER_TAG, ER_CI);
if (cia == (ER_END | ER_VALID)) {
SI_VMSG(("Found END of erom after %d cores\n", sii->numcores));
ai_hwfixup(sii);
return;
}
cib = get_erom_ent(sih, &eromptr, 0, 0);
if ((cib & ER_TAG) != ER_CI) {
SI_ERROR(("CIA not followed by CIB\n"));
goto error;
}
cid = (cia & CIA_CID_MASK) >> CIA_CID_SHIFT;
mfg = (cia & CIA_MFG_MASK) >> CIA_MFG_SHIFT;
crev = (cib & CIB_REV_MASK) >> CIB_REV_SHIFT;
nmw = (cib & CIB_NMW_MASK) >> CIB_NMW_SHIFT;
nsw = (cib & CIB_NSW_MASK) >> CIB_NSW_SHIFT;
nmp = (cib & CIB_NMP_MASK) >> CIB_NMP_SHIFT;
nsp = (cib & CIB_NSP_MASK) >> CIB_NSP_SHIFT;
#ifdef BCMDBG_SI
SI_VMSG(("Found component 0x%04x/0x%04x rev %d at erom addr 0x%p, with nmw = %d, "
"nsw = %d, nmp = %d & nsp = %d\n",
mfg, cid, crev, eromptr - 1, nmw, nsw, nmp, nsp));
#else
BCM_REFERENCE(crev);
#endif
if (((mfg == MFGID_ARM) && (cid == DEF_AI_COMP)) || (nsp == 0))
continue;
if ((nmw + nsw == 0)) {
if (cid == OOB_ROUTER_CORE_ID) {
asd = get_asd(sih, &eromptr, 0, 0, AD_ST_SLAVE,
&addrl, &addrh, &sizel, &sizeh);
if (asd != 0) {
sii->oob_router = addrl;
}
}
if (cid != GMAC_COMMON_4706_CORE_ID)
continue;
}
idx = sii->numcores;
sii->cia[idx] = cia;
sii->cib[idx] = cib;
sii->coreid[idx] = remap_coreid(sih, cid);
for (i = 0; i < nmp; i++) {
mpd = get_erom_ent(sih, &eromptr, ER_VALID, ER_VALID);
if ((mpd & ER_TAG) != ER_MP) {
SI_ERROR(("Not enough MP entries for component 0x%x\n", cid));
goto error;
}
SI_VMSG((" Master port %d, mp: %d id: %d\n", i,
(mpd & MPD_MP_MASK) >> MPD_MP_SHIFT,
(mpd & MPD_MUI_MASK) >> MPD_MUI_SHIFT));
}
asd = get_asd(sih, &eromptr, 0, 0, AD_ST_SLAVE, &addrl, &addrh, &sizel, &sizeh);
if (asd == 0) {
asd = get_asd(sih, &eromptr, 0, 0, AD_ST_BRIDGE, &addrl, &addrh,
&sizel, &sizeh);
if (asd != 0)
br = TRUE;
else
if ((addrh != 0) || (sizeh != 0) || (sizel != SI_CORE_SIZE)) {
SI_ERROR(("First Slave ASD for core 0x%04x malformed "
"(0x%08x)\n", cid, asd));
goto error;
}
}
sii->coresba[idx] = addrl;
sii->coresba_size[idx] = sizel;
j = 1;
do {
asd = get_asd(sih, &eromptr, 0, j, AD_ST_SLAVE, &addrl, &addrh,
&sizel, &sizeh);
if ((asd != 0) && (j == 1) && (sizel == SI_CORE_SIZE)) {
sii->coresba2[idx] = addrl;
sii->coresba2_size[idx] = sizel;
}
j++;
} while (asd != 0);
for (i = 1; i < nsp; i++) {
j = 0;
do {
asd = get_asd(sih, &eromptr, i, j, AD_ST_SLAVE, &addrl, &addrh,
&sizel, &sizeh);
if (asd == 0)
break;
j++;
} while (1);
if (j == 0) {
SI_ERROR((" SP %d has no address descriptors\n", i));
goto error;
}
}
for (i = 0; i < nmw; i++) {
asd = get_asd(sih, &eromptr, i, 0, AD_ST_MWRAP, &addrl, &addrh,
&sizel, &sizeh);
if (asd == 0) {
SI_ERROR(("Missing descriptor for MW %d\n", i));
goto error;
}
if ((sizeh != 0) || (sizel != SI_CORE_SIZE)) {
SI_ERROR(("Master wrapper %d is not 4KB\n", i));
goto error;
}
if (i == 0)
sii->wrapba[idx] = addrl;
}
for (i = 0; i < nsw; i++) {
uint fwp = (nsp == 1) ? 0 : 1;
asd = get_asd(sih, &eromptr, fwp + i, 0, AD_ST_SWRAP, &addrl, &addrh,
&sizel, &sizeh);
if (asd == 0) {
SI_ERROR(("Missing descriptor for SW %d\n", i));
goto error;
}
if ((sizeh != 0) || (sizel != SI_CORE_SIZE)) {
SI_ERROR(("Slave wrapper %d is not 4KB\n", i));
goto error;
}
if ((nmw == 0) && (i == 0))
sii->wrapba[idx] = addrl;
}
if (br)
continue;
sii->numcores++;
}
SI_ERROR(("Reached end of erom without finding END"));
error:
sii->numcores = 0;
return;
}
void *
ai_setcoreidx(si_t *sih, uint coreidx)
{
si_info_t *sii = SI_INFO(sih);
uint32 addr, wrap;
void *regs;
if (coreidx >= MIN(sii->numcores, SI_MAXCORES))
return (NULL);
addr = sii->coresba[coreidx];
wrap = sii->wrapba[coreidx];
ASSERT((sii->intrsenabled_fn == NULL) || !(*(sii)->intrsenabled_fn)((sii)->intr_arg));
switch (BUSTYPE(sih->bustype)) {
case SI_BUS:
if (!sii->regs[coreidx]) {
sii->regs[coreidx] = REG_MAP(addr, SI_CORE_SIZE);
ASSERT(GOODREGS(sii->regs[coreidx]));
}
sii->curmap = regs = sii->regs[coreidx];
if (!sii->wrappers[coreidx]) {
sii->wrappers[coreidx] = REG_MAP(wrap, SI_CORE_SIZE);
ASSERT(GOODREGS(sii->wrappers[coreidx]));
}
sii->curwrap = sii->wrappers[coreidx];
break;
case SPI_BUS:
case SDIO_BUS:
sii->curmap = regs = (void *)((uintptr)addr);
sii->curwrap = (void *)((uintptr)wrap);
break;
case PCMCIA_BUS:
default:
ASSERT(0);
regs = NULL;
break;
}
sii->curmap = regs;
sii->curidx = coreidx;
return regs;
}
void
ai_coreaddrspaceX(si_t *sih, uint asidx, uint32 *addr, uint32 *size)
{
si_info_t *sii = SI_INFO(sih);
chipcregs_t *cc = NULL;
uint32 erombase, *eromptr, *eromlim;
uint i, j, cidx;
uint32 cia, cib, nmp, nsp;
uint32 asd, addrl, addrh, sizel, sizeh;
for (i = 0; i < sii->numcores; i++) {
if (sii->coreid[i] == CC_CORE_ID) {
cc = (chipcregs_t *)sii->regs[i];
break;
}
}
if (cc == NULL)
goto error;
erombase = R_REG(sii->osh, &cc->eromptr);
eromptr = (uint32 *)REG_MAP(erombase, SI_CORE_SIZE);
eromlim = eromptr + (ER_REMAPCONTROL / sizeof(uint32));
cidx = sii->curidx;
cia = sii->cia[cidx];
cib = sii->cib[cidx];
nmp = (cib & CIB_NMP_MASK) >> CIB_NMP_SHIFT;
nsp = (cib & CIB_NSP_MASK) >> CIB_NSP_SHIFT;
while (eromptr < eromlim) {
if ((get_erom_ent(sih, &eromptr, ER_TAG, ER_CI) == cia) &&
(get_erom_ent(sih, &eromptr, 0, 0) == cib)) {
break;
}
}
for (i = 0; i < nmp; i++)
get_erom_ent(sih, &eromptr, ER_VALID, ER_VALID);
asd = get_asd(sih, &eromptr, 0, 0, AD_ST_SLAVE, &addrl, &addrh, &sizel, &sizeh);
if (asd == 0) {
asd = get_asd(sih, &eromptr, 0, 0, AD_ST_BRIDGE, &addrl, &addrh,
&sizel, &sizeh);
}
j = 1;
do {
asd = get_asd(sih, &eromptr, 0, j, AD_ST_SLAVE, &addrl, &addrh,
&sizel, &sizeh);
j++;
} while (asd != 0);
for (i = 1; i < nsp; i++) {
j = 0;
do {
asd = get_asd(sih, &eromptr, i, j, AD_ST_SLAVE, &addrl, &addrh,
&sizel, &sizeh);
if (asd == 0)
break;
if (!asidx--) {
*addr = addrl;
*size = sizel;
return;
}
j++;
} while (1);
if (j == 0) {
SI_ERROR((" SP %d has no address descriptors\n", i));
break;
}
}
error:
*size = 0;
return;
}
int
ai_numaddrspaces(si_t *sih)
{
return 2;
}
uint32
ai_addrspace(si_t *sih, uint asidx)
{
si_info_t *sii;
uint cidx;
sii = SI_INFO(sih);
cidx = sii->curidx;
if (asidx == 0)
return sii->coresba[cidx];
else if (asidx == 1)
return sii->coresba2[cidx];
else {
SI_ERROR(("%s: Need to parse the erom again to find addr space %d\n",
__FUNCTION__, asidx));
return 0;
}
}
uint32
ai_addrspacesize(si_t *sih, uint asidx)
{
si_info_t *sii;
uint cidx;
sii = SI_INFO(sih);
cidx = sii->curidx;
if (asidx == 0)
return sii->coresba_size[cidx];
else if (asidx == 1)
return sii->coresba2_size[cidx];
else {
SI_ERROR(("%s: Need to parse the erom again to find addr space %d\n",
__FUNCTION__, asidx));
return 0;
}
}
uint
ai_flag(si_t *sih)
{
si_info_t *sii;
aidmp_t *ai;
sii = SI_INFO(sih);
if (BCM47162_DMP()) {
SI_ERROR(("%s: Attempting to read MIPS DMP registers on 47162a0", __FUNCTION__));
return sii->curidx;
}
if (BCM5357_DMP()) {
SI_ERROR(("%s: Attempting to read USB20H DMP registers on 5357b0\n", __FUNCTION__));
return sii->curidx;
}
ai = sii->curwrap;
return (R_REG(sii->osh, &ai->oobselouta30) & 0x1f);
}
void
ai_setint(si_t *sih, int siflag)
{
}
uint
ai_wrap_reg(si_t *sih, uint32 offset, uint32 mask, uint32 val)
{
si_info_t *sii = SI_INFO(sih);
uint32 *map = (uint32 *) sii->curwrap;
if (mask || val) {
uint32 w = R_REG(sii->osh, map+(offset/4));
w &= ~mask;
w |= val;
W_REG(sii->osh, map+(offset/4), val);
}
return (R_REG(sii->osh, map+(offset/4)));
}
uint
ai_corevendor(si_t *sih)
{
si_info_t *sii;
uint32 cia;
sii = SI_INFO(sih);
cia = sii->cia[sii->curidx];
return ((cia & CIA_MFG_MASK) >> CIA_MFG_SHIFT);
}
uint
ai_corerev(si_t *sih)
{
si_info_t *sii;
uint32 cib;
sii = SI_INFO(sih);
cib = sii->cib[sii->curidx];
return remap_corerev(sih, (cib & CIB_REV_MASK) >> CIB_REV_SHIFT);
}
bool
ai_iscoreup(si_t *sih)
{
si_info_t *sii;
aidmp_t *ai;
sii = SI_INFO(sih);
ai = sii->curwrap;
return (((R_REG(sii->osh, &ai->ioctrl) & (SICF_FGC | SICF_CLOCK_EN)) == SICF_CLOCK_EN) &&
((R_REG(sii->osh, &ai->resetctrl) & AIRC_RESET) == 0));
}
uint
ai_corereg(si_t *sih, uint coreidx, uint regoff, uint mask, uint val)
{
uint origidx = 0;
uint32 *r = NULL;
uint w;
uint intr_val = 0;
bool fast = FALSE;
si_info_t *sii;
sii = SI_INFO(sih);
ASSERT(GOODIDX(coreidx));
ASSERT(regoff < SI_CORE_SIZE);
ASSERT((val & ~mask) == 0);
if (coreidx >= SI_MAXCORES)
return 0;
if (BUSTYPE(sih->bustype) == SI_BUS) {
fast = TRUE;
if (!sii->regs[coreidx]) {
sii->regs[coreidx] = REG_MAP(sii->coresba[coreidx],
SI_CORE_SIZE);
ASSERT(GOODREGS(sii->regs[coreidx]));
}
r = (uint32 *)((uchar *)sii->regs[coreidx] + regoff);
} else if (BUSTYPE(sih->bustype) == PCI_BUS) {
if ((sii->coreid[coreidx] == CC_CORE_ID) && SI_FAST(sii)) {
fast = TRUE;
r = (uint32 *)((char *)sii->curmap + PCI_16KB0_CCREGS_OFFSET + regoff);
} else if (sii->pub.buscoreidx == coreidx) {
fast = TRUE;
if (SI_FAST(sii))
r = (uint32 *)((char *)sii->curmap +
PCI_16KB0_PCIREGS_OFFSET + regoff);
else
r = (uint32 *)((char *)sii->curmap +
((regoff >= SBCONFIGOFF) ?
PCI_BAR0_PCISBR_OFFSET : PCI_BAR0_PCIREGS_OFFSET) +
regoff);
}
}
if (!fast) {
INTR_OFF(sii, intr_val);
origidx = si_coreidx(&sii->pub);
r = (uint32*) ((uchar*) ai_setcoreidx(&sii->pub, coreidx) + regoff);
}
ASSERT(r != NULL);
if (mask || val) {
w = (R_REG(sii->osh, r) & ~mask) | val;
W_REG(sii->osh, r, w);
}
w = R_REG(sii->osh, r);
if (!fast) {
if (origidx != coreidx)
ai_setcoreidx(&sii->pub, origidx);
INTR_RESTORE(sii, intr_val);
}
return (w);
}
void
ai_core_disable(si_t *sih, uint32 bits)
{
si_info_t *sii;
volatile uint32 dummy;
uint32 status;
aidmp_t *ai;
sii = SI_INFO(sih);
ASSERT(GOODREGS(sii->curwrap));
ai = sii->curwrap;
if (R_REG(sii->osh, &ai->resetctrl) & AIRC_RESET)
return;
SPINWAIT(((status = R_REG(sii->osh, &ai->resetstatus)) != 0), 300);
if (status != 0) {
SPINWAIT(((status = R_REG(sii->osh, &ai->resetstatus)) != 0), 10000);
}
W_REG(sii->osh, &ai->ioctrl, bits);
dummy = R_REG(sii->osh, &ai->ioctrl);
BCM_REFERENCE(dummy);
OSL_DELAY(10);
W_REG(sii->osh, &ai->resetctrl, AIRC_RESET);
dummy = R_REG(sii->osh, &ai->resetctrl);
BCM_REFERENCE(dummy);
OSL_DELAY(1);
}
void
ai_core_reset(si_t *sih, uint32 bits, uint32 resetbits)
{
si_info_t *sii;
aidmp_t *ai;
volatile uint32 dummy;
sii = SI_INFO(sih);
ASSERT(GOODREGS(sii->curwrap));
ai = sii->curwrap;
ai_core_disable(sih, (bits | resetbits));
W_REG(sii->osh, &ai->ioctrl, (bits | SICF_FGC | SICF_CLOCK_EN));
dummy = R_REG(sii->osh, &ai->ioctrl);
BCM_REFERENCE(dummy);
W_REG(sii->osh, &ai->resetctrl, 0);
dummy = R_REG(sii->osh, &ai->resetctrl);
BCM_REFERENCE(dummy);
OSL_DELAY(1);
W_REG(sii->osh, &ai->ioctrl, (bits | SICF_CLOCK_EN));
dummy = R_REG(sii->osh, &ai->ioctrl);
BCM_REFERENCE(dummy);
OSL_DELAY(1);
}
void
ai_core_cflags_wo(si_t *sih, uint32 mask, uint32 val)
{
si_info_t *sii;
aidmp_t *ai;
uint32 w;
sii = SI_INFO(sih);
if (BCM47162_DMP()) {
SI_ERROR(("%s: Accessing MIPS DMP register (ioctrl) on 47162a0",
__FUNCTION__));
return;
}
if (BCM5357_DMP()) {
SI_ERROR(("%s: Accessing USB20H DMP register (ioctrl) on 5357\n",
__FUNCTION__));
return;
}
ASSERT(GOODREGS(sii->curwrap));
ai = sii->curwrap;
ASSERT((val & ~mask) == 0);
if (mask || val) {
w = ((R_REG(sii->osh, &ai->ioctrl) & ~mask) | val);
W_REG(sii->osh, &ai->ioctrl, w);
}
}
uint32
ai_core_cflags(si_t *sih, uint32 mask, uint32 val)
{
si_info_t *sii;
aidmp_t *ai;
uint32 w;
sii = SI_INFO(sih);
if (BCM47162_DMP()) {
SI_ERROR(("%s: Accessing MIPS DMP register (ioctrl) on 47162a0",
__FUNCTION__));
return 0;
}
if (BCM5357_DMP()) {
SI_ERROR(("%s: Accessing USB20H DMP register (ioctrl) on 5357\n",
__FUNCTION__));
return 0;
}
ASSERT(GOODREGS(sii->curwrap));
ai = sii->curwrap;
ASSERT((val & ~mask) == 0);
if (mask || val) {
w = ((R_REG(sii->osh, &ai->ioctrl) & ~mask) | val);
W_REG(sii->osh, &ai->ioctrl, w);
}
return R_REG(sii->osh, &ai->ioctrl);
}
uint32
ai_core_sflags(si_t *sih, uint32 mask, uint32 val)
{
si_info_t *sii;
aidmp_t *ai;
uint32 w;
sii = SI_INFO(sih);
if (BCM47162_DMP()) {
SI_ERROR(("%s: Accessing MIPS DMP register (iostatus) on 47162a0",
__FUNCTION__));
return 0;
}
if (BCM5357_DMP()) {
SI_ERROR(("%s: Accessing USB20H DMP register (iostatus) on 5357\n",
__FUNCTION__));
return 0;
}
ASSERT(GOODREGS(sii->curwrap));
ai = sii->curwrap;
ASSERT((val & ~mask) == 0);
ASSERT((mask & ~SISF_CORE_BITS) == 0);
if (mask || val) {
w = ((R_REG(sii->osh, &ai->iostatus) & ~mask) | val);
W_REG(sii->osh, &ai->iostatus, w);
}
return R_REG(sii->osh, &ai->iostatus);
}
| gpl-2.0 |
TeamWin/android_kernel_samsung_j7elte | drivers/media/usb/dvb-usb/az6027.c | 2256 | 27738 | /* DVB USB compliant Linux driver for the AZUREWAVE DVB-S/S2 USB2.0 (AZ6027)
* receiver.
*
* Copyright (C) 2009 Adams.Xu <adams.xu@azwave.com.cn>
*
* 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.
*
* see Documentation/dvb/README.dvb-usb for more information
*/
#include "az6027.h"
#include "stb0899_drv.h"
#include "stb0899_reg.h"
#include "stb0899_cfg.h"
#include "stb6100.h"
#include "stb6100_cfg.h"
#include "dvb_ca_en50221.h"
int dvb_usb_az6027_debug;
module_param_named(debug, dvb_usb_az6027_debug, int, 0644);
MODULE_PARM_DESC(debug, "set debugging level (1=info,xfer=2,rc=4 (or-able))." DVB_USB_DEBUG_STATUS);
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
struct az6027_device_state {
struct dvb_ca_en50221 ca;
struct mutex ca_mutex;
u8 power_state;
};
static const struct stb0899_s1_reg az6027_stb0899_s1_init_1[] = {
/* 0x0000000b, SYSREG */
{ STB0899_DEV_ID , 0x30 },
{ STB0899_DISCNTRL1 , 0x32 },
{ STB0899_DISCNTRL2 , 0x80 },
{ STB0899_DISRX_ST0 , 0x04 },
{ STB0899_DISRX_ST1 , 0x00 },
{ STB0899_DISPARITY , 0x00 },
{ STB0899_DISSTATUS , 0x20 },
{ STB0899_DISF22 , 0x99 },
{ STB0899_DISF22RX , 0xa8 },
/* SYSREG ? */
{ STB0899_ACRPRESC , 0x11 },
{ STB0899_ACRDIV1 , 0x0a },
{ STB0899_ACRDIV2 , 0x05 },
{ STB0899_DACR1 , 0x00 },
{ STB0899_DACR2 , 0x00 },
{ STB0899_OUTCFG , 0x00 },
{ STB0899_MODECFG , 0x00 },
{ STB0899_IRQSTATUS_3 , 0xfe },
{ STB0899_IRQSTATUS_2 , 0x03 },
{ STB0899_IRQSTATUS_1 , 0x7c },
{ STB0899_IRQSTATUS_0 , 0xf4 },
{ STB0899_IRQMSK_3 , 0xf3 },
{ STB0899_IRQMSK_2 , 0xfc },
{ STB0899_IRQMSK_1 , 0xff },
{ STB0899_IRQMSK_0 , 0xff },
{ STB0899_IRQCFG , 0x00 },
{ STB0899_I2CCFG , 0x88 },
{ STB0899_I2CRPT , 0x58 },
{ STB0899_IOPVALUE5 , 0x00 },
{ STB0899_IOPVALUE4 , 0x33 },
{ STB0899_IOPVALUE3 , 0x6d },
{ STB0899_IOPVALUE2 , 0x90 },
{ STB0899_IOPVALUE1 , 0x60 },
{ STB0899_IOPVALUE0 , 0x00 },
{ STB0899_GPIO00CFG , 0x82 },
{ STB0899_GPIO01CFG , 0x82 },
{ STB0899_GPIO02CFG , 0x82 },
{ STB0899_GPIO03CFG , 0x82 },
{ STB0899_GPIO04CFG , 0x82 },
{ STB0899_GPIO05CFG , 0x82 },
{ STB0899_GPIO06CFG , 0x82 },
{ STB0899_GPIO07CFG , 0x82 },
{ STB0899_GPIO08CFG , 0x82 },
{ STB0899_GPIO09CFG , 0x82 },
{ STB0899_GPIO10CFG , 0x82 },
{ STB0899_GPIO11CFG , 0x82 },
{ STB0899_GPIO12CFG , 0x82 },
{ STB0899_GPIO13CFG , 0x82 },
{ STB0899_GPIO14CFG , 0x82 },
{ STB0899_GPIO15CFG , 0x82 },
{ STB0899_GPIO16CFG , 0x82 },
{ STB0899_GPIO17CFG , 0x82 },
{ STB0899_GPIO18CFG , 0x82 },
{ STB0899_GPIO19CFG , 0x82 },
{ STB0899_GPIO20CFG , 0x82 },
{ STB0899_SDATCFG , 0xb8 },
{ STB0899_SCLTCFG , 0xba },
{ STB0899_AGCRFCFG , 0x1c }, /* 0x11 */
{ STB0899_GPIO22 , 0x82 }, /* AGCBB2CFG */
{ STB0899_GPIO21 , 0x91 }, /* AGCBB1CFG */
{ STB0899_DIRCLKCFG , 0x82 },
{ STB0899_CLKOUT27CFG , 0x7e },
{ STB0899_STDBYCFG , 0x82 },
{ STB0899_CS0CFG , 0x82 },
{ STB0899_CS1CFG , 0x82 },
{ STB0899_DISEQCOCFG , 0x20 },
{ STB0899_GPIO32CFG , 0x82 },
{ STB0899_GPIO33CFG , 0x82 },
{ STB0899_GPIO34CFG , 0x82 },
{ STB0899_GPIO35CFG , 0x82 },
{ STB0899_GPIO36CFG , 0x82 },
{ STB0899_GPIO37CFG , 0x82 },
{ STB0899_GPIO38CFG , 0x82 },
{ STB0899_GPIO39CFG , 0x82 },
{ STB0899_NCOARSE , 0x17 }, /* 0x15 = 27 Mhz Clock, F/3 = 198MHz, F/6 = 99MHz */
{ STB0899_SYNTCTRL , 0x02 }, /* 0x00 = CLK from CLKI, 0x02 = CLK from XTALI */
{ STB0899_FILTCTRL , 0x00 },
{ STB0899_SYSCTRL , 0x01 },
{ STB0899_STOPCLK1 , 0x20 },
{ STB0899_STOPCLK2 , 0x00 },
{ STB0899_INTBUFSTATUS , 0x00 },
{ STB0899_INTBUFCTRL , 0x0a },
{ 0xffff , 0xff },
};
static const struct stb0899_s1_reg az6027_stb0899_s1_init_3[] = {
{ STB0899_DEMOD , 0x00 },
{ STB0899_RCOMPC , 0xc9 },
{ STB0899_AGC1CN , 0x01 },
{ STB0899_AGC1REF , 0x10 },
{ STB0899_RTC , 0x23 },
{ STB0899_TMGCFG , 0x4e },
{ STB0899_AGC2REF , 0x34 },
{ STB0899_TLSR , 0x84 },
{ STB0899_CFD , 0xf7 },
{ STB0899_ACLC , 0x87 },
{ STB0899_BCLC , 0x94 },
{ STB0899_EQON , 0x41 },
{ STB0899_LDT , 0xf1 },
{ STB0899_LDT2 , 0xe3 },
{ STB0899_EQUALREF , 0xb4 },
{ STB0899_TMGRAMP , 0x10 },
{ STB0899_TMGTHD , 0x30 },
{ STB0899_IDCCOMP , 0xfd },
{ STB0899_QDCCOMP , 0xff },
{ STB0899_POWERI , 0x0c },
{ STB0899_POWERQ , 0x0f },
{ STB0899_RCOMP , 0x6c },
{ STB0899_AGCIQIN , 0x80 },
{ STB0899_AGC2I1 , 0x06 },
{ STB0899_AGC2I2 , 0x00 },
{ STB0899_TLIR , 0x30 },
{ STB0899_RTF , 0x7f },
{ STB0899_DSTATUS , 0x00 },
{ STB0899_LDI , 0xbc },
{ STB0899_CFRM , 0xea },
{ STB0899_CFRL , 0x31 },
{ STB0899_NIRM , 0x2b },
{ STB0899_NIRL , 0x80 },
{ STB0899_ISYMB , 0x1d },
{ STB0899_QSYMB , 0xa6 },
{ STB0899_SFRH , 0x2f },
{ STB0899_SFRM , 0x68 },
{ STB0899_SFRL , 0x40 },
{ STB0899_SFRUPH , 0x2f },
{ STB0899_SFRUPM , 0x68 },
{ STB0899_SFRUPL , 0x40 },
{ STB0899_EQUAI1 , 0x02 },
{ STB0899_EQUAQ1 , 0xff },
{ STB0899_EQUAI2 , 0x04 },
{ STB0899_EQUAQ2 , 0x05 },
{ STB0899_EQUAI3 , 0x02 },
{ STB0899_EQUAQ3 , 0xfd },
{ STB0899_EQUAI4 , 0x03 },
{ STB0899_EQUAQ4 , 0x07 },
{ STB0899_EQUAI5 , 0x08 },
{ STB0899_EQUAQ5 , 0xf5 },
{ STB0899_DSTATUS2 , 0x00 },
{ STB0899_VSTATUS , 0x00 },
{ STB0899_VERROR , 0x86 },
{ STB0899_IQSWAP , 0x2a },
{ STB0899_ECNT1M , 0x00 },
{ STB0899_ECNT1L , 0x00 },
{ STB0899_ECNT2M , 0x00 },
{ STB0899_ECNT2L , 0x00 },
{ STB0899_ECNT3M , 0x0a },
{ STB0899_ECNT3L , 0xad },
{ STB0899_FECAUTO1 , 0x06 },
{ STB0899_FECM , 0x01 },
{ STB0899_VTH12 , 0xb0 },
{ STB0899_VTH23 , 0x7a },
{ STB0899_VTH34 , 0x58 },
{ STB0899_VTH56 , 0x38 },
{ STB0899_VTH67 , 0x34 },
{ STB0899_VTH78 , 0x24 },
{ STB0899_PRVIT , 0xff },
{ STB0899_VITSYNC , 0x19 },
{ STB0899_RSULC , 0xb1 }, /* DVB = 0xb1, DSS = 0xa1 */
{ STB0899_TSULC , 0x42 },
{ STB0899_RSLLC , 0x41 },
{ STB0899_TSLPL , 0x12 },
{ STB0899_TSCFGH , 0x0c },
{ STB0899_TSCFGM , 0x00 },
{ STB0899_TSCFGL , 0x00 },
{ STB0899_TSOUT , 0x69 }, /* 0x0d for CAM */
{ STB0899_RSSYNCDEL , 0x00 },
{ STB0899_TSINHDELH , 0x02 },
{ STB0899_TSINHDELM , 0x00 },
{ STB0899_TSINHDELL , 0x00 },
{ STB0899_TSLLSTKM , 0x1b },
{ STB0899_TSLLSTKL , 0xb3 },
{ STB0899_TSULSTKM , 0x00 },
{ STB0899_TSULSTKL , 0x00 },
{ STB0899_PCKLENUL , 0xbc },
{ STB0899_PCKLENLL , 0xcc },
{ STB0899_RSPCKLEN , 0xbd },
{ STB0899_TSSTATUS , 0x90 },
{ STB0899_ERRCTRL1 , 0xb6 },
{ STB0899_ERRCTRL2 , 0x95 },
{ STB0899_ERRCTRL3 , 0x8d },
{ STB0899_DMONMSK1 , 0x27 },
{ STB0899_DMONMSK0 , 0x03 },
{ STB0899_DEMAPVIT , 0x5c },
{ STB0899_PLPARM , 0x19 },
{ STB0899_PDELCTRL , 0x48 },
{ STB0899_PDELCTRL2 , 0x00 },
{ STB0899_BBHCTRL1 , 0x00 },
{ STB0899_BBHCTRL2 , 0x00 },
{ STB0899_HYSTTHRESH , 0x77 },
{ STB0899_MATCSTM , 0x00 },
{ STB0899_MATCSTL , 0x00 },
{ STB0899_UPLCSTM , 0x00 },
{ STB0899_UPLCSTL , 0x00 },
{ STB0899_DFLCSTM , 0x00 },
{ STB0899_DFLCSTL , 0x00 },
{ STB0899_SYNCCST , 0x00 },
{ STB0899_SYNCDCSTM , 0x00 },
{ STB0899_SYNCDCSTL , 0x00 },
{ STB0899_ISI_ENTRY , 0x00 },
{ STB0899_ISI_BIT_EN , 0x00 },
{ STB0899_MATSTRM , 0xf0 },
{ STB0899_MATSTRL , 0x02 },
{ STB0899_UPLSTRM , 0x45 },
{ STB0899_UPLSTRL , 0x60 },
{ STB0899_DFLSTRM , 0xe3 },
{ STB0899_DFLSTRL , 0x00 },
{ STB0899_SYNCSTR , 0x47 },
{ STB0899_SYNCDSTRM , 0x05 },
{ STB0899_SYNCDSTRL , 0x18 },
{ STB0899_CFGPDELSTATUS1 , 0x19 },
{ STB0899_CFGPDELSTATUS2 , 0x2b },
{ STB0899_BBFERRORM , 0x00 },
{ STB0899_BBFERRORL , 0x01 },
{ STB0899_UPKTERRORM , 0x00 },
{ STB0899_UPKTERRORL , 0x00 },
{ 0xffff , 0xff },
};
struct stb0899_config az6027_stb0899_config = {
.init_dev = az6027_stb0899_s1_init_1,
.init_s2_demod = stb0899_s2_init_2,
.init_s1_demod = az6027_stb0899_s1_init_3,
.init_s2_fec = stb0899_s2_init_4,
.init_tst = stb0899_s1_init_5,
.demod_address = 0xd0, /* 0x68, 0xd0 >> 1 */
.xtal_freq = 27000000,
.inversion = IQ_SWAP_ON, /* 1 */
.lo_clk = 76500000,
.hi_clk = 99000000,
.esno_ave = STB0899_DVBS2_ESNO_AVE,
.esno_quant = STB0899_DVBS2_ESNO_QUANT,
.avframes_coarse = STB0899_DVBS2_AVFRAMES_COARSE,
.avframes_fine = STB0899_DVBS2_AVFRAMES_FINE,
.miss_threshold = STB0899_DVBS2_MISS_THRESHOLD,
.uwp_threshold_acq = STB0899_DVBS2_UWP_THRESHOLD_ACQ,
.uwp_threshold_track = STB0899_DVBS2_UWP_THRESHOLD_TRACK,
.uwp_threshold_sof = STB0899_DVBS2_UWP_THRESHOLD_SOF,
.sof_search_timeout = STB0899_DVBS2_SOF_SEARCH_TIMEOUT,
.btr_nco_bits = STB0899_DVBS2_BTR_NCO_BITS,
.btr_gain_shift_offset = STB0899_DVBS2_BTR_GAIN_SHIFT_OFFSET,
.crl_nco_bits = STB0899_DVBS2_CRL_NCO_BITS,
.ldpc_max_iter = STB0899_DVBS2_LDPC_MAX_ITER,
.tuner_get_frequency = stb6100_get_frequency,
.tuner_set_frequency = stb6100_set_frequency,
.tuner_set_bandwidth = stb6100_set_bandwidth,
.tuner_get_bandwidth = stb6100_get_bandwidth,
.tuner_set_rfsiggain = NULL,
};
struct stb6100_config az6027_stb6100_config = {
.tuner_address = 0xc0,
.refclock = 27000000,
};
/* check for mutex FIXME */
static int az6027_usb_in_op(struct dvb_usb_device *d, u8 req,
u16 value, u16 index, u8 *b, int blen)
{
int ret = -1;
if (mutex_lock_interruptible(&d->usb_mutex))
return -EAGAIN;
ret = usb_control_msg(d->udev,
usb_rcvctrlpipe(d->udev, 0),
req,
USB_TYPE_VENDOR | USB_DIR_IN,
value,
index,
b,
blen,
2000);
if (ret < 0) {
warn("usb in operation failed. (%d)", ret);
ret = -EIO;
} else
ret = 0;
deb_xfer("in: req. %02x, val: %04x, ind: %04x, buffer: ", req, value, index);
debug_dump(b, blen, deb_xfer);
mutex_unlock(&d->usb_mutex);
return ret;
}
static int az6027_usb_out_op(struct dvb_usb_device *d,
u8 req,
u16 value,
u16 index,
u8 *b,
int blen)
{
int ret;
deb_xfer("out: req. %02x, val: %04x, ind: %04x, buffer: ", req, value, index);
debug_dump(b, blen, deb_xfer);
if (mutex_lock_interruptible(&d->usb_mutex))
return -EAGAIN;
ret = usb_control_msg(d->udev,
usb_sndctrlpipe(d->udev, 0),
req,
USB_TYPE_VENDOR | USB_DIR_OUT,
value,
index,
b,
blen,
2000);
if (ret != blen) {
warn("usb out operation failed. (%d)", ret);
mutex_unlock(&d->usb_mutex);
return -EIO;
} else{
mutex_unlock(&d->usb_mutex);
return 0;
}
}
static int az6027_streaming_ctrl(struct dvb_usb_adapter *adap, int onoff)
{
int ret;
u8 req;
u16 value;
u16 index;
int blen;
deb_info("%s %d", __func__, onoff);
req = 0xBC;
value = onoff;
index = 0;
blen = 0;
ret = az6027_usb_out_op(adap->dev, req, value, index, NULL, blen);
if (ret != 0)
warn("usb out operation failed. (%d)", ret);
return ret;
}
/* keys for the enclosed remote control */
static struct rc_map_table rc_map_az6027_table[] = {
{ 0x01, KEY_1 },
{ 0x02, KEY_2 },
};
/* remote control stuff (does not work with my box) */
static int az6027_rc_query(struct dvb_usb_device *d, u32 *event, int *state)
{
return 0;
}
/*
int az6027_power_ctrl(struct dvb_usb_device *d, int onoff)
{
u8 v = onoff;
return az6027_usb_out_op(d,0xBC,v,3,NULL,1);
}
*/
static int az6027_ci_read_attribute_mem(struct dvb_ca_en50221 *ca,
int slot,
int address)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct az6027_device_state *state = (struct az6027_device_state *)d->priv;
int ret;
u8 req;
u16 value;
u16 index;
int blen;
u8 *b;
if (slot != 0)
return -EINVAL;
b = kmalloc(12, GFP_KERNEL);
if (!b)
return -ENOMEM;
mutex_lock(&state->ca_mutex);
req = 0xC1;
value = address;
index = 0;
blen = 1;
ret = az6027_usb_in_op(d, req, value, index, b, blen);
if (ret < 0) {
warn("usb in operation failed. (%d)", ret);
ret = -EINVAL;
} else {
ret = b[0];
}
mutex_unlock(&state->ca_mutex);
kfree(b);
return ret;
}
static int az6027_ci_write_attribute_mem(struct dvb_ca_en50221 *ca,
int slot,
int address,
u8 value)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct az6027_device_state *state = (struct az6027_device_state *)d->priv;
int ret;
u8 req;
u16 value1;
u16 index;
int blen;
deb_info("%s %d", __func__, slot);
if (slot != 0)
return -EINVAL;
mutex_lock(&state->ca_mutex);
req = 0xC2;
value1 = address;
index = value;
blen = 0;
ret = az6027_usb_out_op(d, req, value1, index, NULL, blen);
if (ret != 0)
warn("usb out operation failed. (%d)", ret);
mutex_unlock(&state->ca_mutex);
return ret;
}
static int az6027_ci_read_cam_control(struct dvb_ca_en50221 *ca,
int slot,
u8 address)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct az6027_device_state *state = (struct az6027_device_state *)d->priv;
int ret;
u8 req;
u16 value;
u16 index;
int blen;
u8 *b;
if (slot != 0)
return -EINVAL;
b = kmalloc(12, GFP_KERNEL);
if (!b)
return -ENOMEM;
mutex_lock(&state->ca_mutex);
req = 0xC3;
value = address;
index = 0;
blen = 2;
ret = az6027_usb_in_op(d, req, value, index, b, blen);
if (ret < 0) {
warn("usb in operation failed. (%d)", ret);
ret = -EINVAL;
} else {
if (b[0] == 0)
warn("Read CI IO error");
ret = b[1];
deb_info("read cam data = %x from 0x%x", b[1], value);
}
mutex_unlock(&state->ca_mutex);
kfree(b);
return ret;
}
static int az6027_ci_write_cam_control(struct dvb_ca_en50221 *ca,
int slot,
u8 address,
u8 value)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct az6027_device_state *state = (struct az6027_device_state *)d->priv;
int ret;
u8 req;
u16 value1;
u16 index;
int blen;
if (slot != 0)
return -EINVAL;
mutex_lock(&state->ca_mutex);
req = 0xC4;
value1 = address;
index = value;
blen = 0;
ret = az6027_usb_out_op(d, req, value1, index, NULL, blen);
if (ret != 0) {
warn("usb out operation failed. (%d)", ret);
goto failed;
}
failed:
mutex_unlock(&state->ca_mutex);
return ret;
}
static int CI_CamReady(struct dvb_ca_en50221 *ca, int slot)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
int ret;
u8 req;
u16 value;
u16 index;
int blen;
u8 *b;
b = kmalloc(12, GFP_KERNEL);
if (!b)
return -ENOMEM;
req = 0xC8;
value = 0;
index = 0;
blen = 1;
ret = az6027_usb_in_op(d, req, value, index, b, blen);
if (ret < 0) {
warn("usb in operation failed. (%d)", ret);
ret = -EIO;
} else{
ret = b[0];
}
kfree(b);
return ret;
}
static int az6027_ci_slot_reset(struct dvb_ca_en50221 *ca, int slot)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct az6027_device_state *state = (struct az6027_device_state *)d->priv;
int ret, i;
u8 req;
u16 value;
u16 index;
int blen;
mutex_lock(&state->ca_mutex);
req = 0xC6;
value = 1;
index = 0;
blen = 0;
ret = az6027_usb_out_op(d, req, value, index, NULL, blen);
if (ret != 0) {
warn("usb out operation failed. (%d)", ret);
goto failed;
}
msleep(500);
req = 0xC6;
value = 0;
index = 0;
blen = 0;
ret = az6027_usb_out_op(d, req, value, index, NULL, blen);
if (ret != 0) {
warn("usb out operation failed. (%d)", ret);
goto failed;
}
for (i = 0; i < 15; i++) {
msleep(100);
if (CI_CamReady(ca, slot)) {
deb_info("CAM Ready");
break;
}
}
msleep(5000);
failed:
mutex_unlock(&state->ca_mutex);
return ret;
}
static int az6027_ci_slot_shutdown(struct dvb_ca_en50221 *ca, int slot)
{
return 0;
}
static int az6027_ci_slot_ts_enable(struct dvb_ca_en50221 *ca, int slot)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct az6027_device_state *state = (struct az6027_device_state *)d->priv;
int ret;
u8 req;
u16 value;
u16 index;
int blen;
deb_info("%s", __func__);
mutex_lock(&state->ca_mutex);
req = 0xC7;
value = 1;
index = 0;
blen = 0;
ret = az6027_usb_out_op(d, req, value, index, NULL, blen);
if (ret != 0) {
warn("usb out operation failed. (%d)", ret);
goto failed;
}
failed:
mutex_unlock(&state->ca_mutex);
return ret;
}
static int az6027_ci_poll_slot_status(struct dvb_ca_en50221 *ca, int slot, int open)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct az6027_device_state *state = (struct az6027_device_state *)d->priv;
int ret;
u8 req;
u16 value;
u16 index;
int blen;
u8 *b;
b = kmalloc(12, GFP_KERNEL);
if (!b)
return -ENOMEM;
mutex_lock(&state->ca_mutex);
req = 0xC5;
value = 0;
index = 0;
blen = 1;
ret = az6027_usb_in_op(d, req, value, index, b, blen);
if (ret < 0) {
warn("usb in operation failed. (%d)", ret);
ret = -EIO;
} else
ret = 0;
if (!ret && b[0] == 1) {
ret = DVB_CA_EN50221_POLL_CAM_PRESENT |
DVB_CA_EN50221_POLL_CAM_READY;
}
mutex_unlock(&state->ca_mutex);
kfree(b);
return ret;
}
static void az6027_ci_uninit(struct dvb_usb_device *d)
{
struct az6027_device_state *state;
deb_info("%s", __func__);
if (NULL == d)
return;
state = (struct az6027_device_state *)d->priv;
if (NULL == state)
return;
if (NULL == state->ca.data)
return;
dvb_ca_en50221_release(&state->ca);
memset(&state->ca, 0, sizeof(state->ca));
}
static int az6027_ci_init(struct dvb_usb_adapter *a)
{
struct dvb_usb_device *d = a->dev;
struct az6027_device_state *state = (struct az6027_device_state *)d->priv;
int ret;
deb_info("%s", __func__);
mutex_init(&state->ca_mutex);
state->ca.owner = THIS_MODULE;
state->ca.read_attribute_mem = az6027_ci_read_attribute_mem;
state->ca.write_attribute_mem = az6027_ci_write_attribute_mem;
state->ca.read_cam_control = az6027_ci_read_cam_control;
state->ca.write_cam_control = az6027_ci_write_cam_control;
state->ca.slot_reset = az6027_ci_slot_reset;
state->ca.slot_shutdown = az6027_ci_slot_shutdown;
state->ca.slot_ts_enable = az6027_ci_slot_ts_enable;
state->ca.poll_slot_status = az6027_ci_poll_slot_status;
state->ca.data = d;
ret = dvb_ca_en50221_init(&a->dvb_adap,
&state->ca,
0, /* flags */
1);/* n_slots */
if (ret != 0) {
err("Cannot initialize CI: Error %d.", ret);
memset(&state->ca, 0, sizeof(state->ca));
return ret;
}
deb_info("CI initialized.");
return 0;
}
/*
static int az6027_read_mac_addr(struct dvb_usb_device *d, u8 mac[6])
{
az6027_usb_in_op(d, 0xb7, 6, 0, &mac[0], 6);
return 0;
}
*/
static int az6027_set_voltage(struct dvb_frontend *fe, fe_sec_voltage_t voltage)
{
u8 buf;
struct dvb_usb_adapter *adap = fe->dvb->priv;
struct i2c_msg i2c_msg = {
.addr = 0x99,
.flags = 0,
.buf = &buf,
.len = 1
};
/*
* 2 --18v
* 1 --13v
* 0 --off
*/
switch (voltage) {
case SEC_VOLTAGE_13:
buf = 1;
i2c_transfer(&adap->dev->i2c_adap, &i2c_msg, 1);
break;
case SEC_VOLTAGE_18:
buf = 2;
i2c_transfer(&adap->dev->i2c_adap, &i2c_msg, 1);
break;
case SEC_VOLTAGE_OFF:
buf = 0;
i2c_transfer(&adap->dev->i2c_adap, &i2c_msg, 1);
break;
default:
return -EINVAL;
}
return 0;
}
static int az6027_frontend_poweron(struct dvb_usb_adapter *adap)
{
int ret;
u8 req;
u16 value;
u16 index;
int blen;
req = 0xBC;
value = 1; /* power on */
index = 3;
blen = 0;
ret = az6027_usb_out_op(adap->dev, req, value, index, NULL, blen);
if (ret != 0)
return -EIO;
return 0;
}
static int az6027_frontend_reset(struct dvb_usb_adapter *adap)
{
int ret;
u8 req;
u16 value;
u16 index;
int blen;
/* reset demodulator */
req = 0xC0;
value = 1; /* high */
index = 3;
blen = 0;
ret = az6027_usb_out_op(adap->dev, req, value, index, NULL, blen);
if (ret != 0)
return -EIO;
req = 0xC0;
value = 0; /* low */
index = 3;
blen = 0;
msleep_interruptible(200);
ret = az6027_usb_out_op(adap->dev, req, value, index, NULL, blen);
if (ret != 0)
return -EIO;
msleep_interruptible(200);
req = 0xC0;
value = 1; /*high */
index = 3;
blen = 0;
ret = az6027_usb_out_op(adap->dev, req, value, index, NULL, blen);
if (ret != 0)
return -EIO;
msleep_interruptible(200);
return 0;
}
static int az6027_frontend_tsbypass(struct dvb_usb_adapter *adap, int onoff)
{
int ret;
u8 req;
u16 value;
u16 index;
int blen;
/* TS passthrough */
req = 0xC7;
value = onoff;
index = 0;
blen = 0;
ret = az6027_usb_out_op(adap->dev, req, value, index, NULL, blen);
if (ret != 0)
return -EIO;
return 0;
}
static int az6027_frontend_attach(struct dvb_usb_adapter *adap)
{
az6027_frontend_poweron(adap);
az6027_frontend_reset(adap);
deb_info("adap = %p, dev = %p\n", adap, adap->dev);
adap->fe_adap[0].fe = stb0899_attach(&az6027_stb0899_config, &adap->dev->i2c_adap);
if (adap->fe_adap[0].fe) {
deb_info("found STB0899 DVB-S/DVB-S2 frontend @0x%02x", az6027_stb0899_config.demod_address);
if (stb6100_attach(adap->fe_adap[0].fe, &az6027_stb6100_config, &adap->dev->i2c_adap)) {
deb_info("found STB6100 DVB-S/DVB-S2 frontend @0x%02x", az6027_stb6100_config.tuner_address);
adap->fe_adap[0].fe->ops.set_voltage = az6027_set_voltage;
az6027_ci_init(adap);
} else {
adap->fe_adap[0].fe = NULL;
}
} else
warn("no front-end attached\n");
az6027_frontend_tsbypass(adap, 0);
return 0;
}
static struct dvb_usb_device_properties az6027_properties;
static void az6027_usb_disconnect(struct usb_interface *intf)
{
struct dvb_usb_device *d = usb_get_intfdata(intf);
az6027_ci_uninit(d);
dvb_usb_device_exit(intf);
}
static int az6027_usb_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
return dvb_usb_device_init(intf,
&az6027_properties,
THIS_MODULE,
NULL,
adapter_nr);
}
/* I2C */
static int az6027_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num)
{
struct dvb_usb_device *d = i2c_get_adapdata(adap);
int i = 0, j = 0, len = 0;
u16 index;
u16 value;
int length;
u8 req;
u8 *data;
data = kmalloc(256, GFP_KERNEL);
if (!data)
return -ENOMEM;
if (mutex_lock_interruptible(&d->i2c_mutex) < 0) {
kfree(data);
return -EAGAIN;
}
if (num > 2)
warn("more than 2 i2c messages at a time is not handled yet. TODO.");
for (i = 0; i < num; i++) {
if (msg[i].addr == 0x99) {
req = 0xBE;
index = 0;
value = msg[i].buf[0] & 0x00ff;
length = 1;
az6027_usb_out_op(d, req, value, index, data, length);
}
if (msg[i].addr == 0xd0) {
/* write/read request */
if (i + 1 < num && (msg[i + 1].flags & I2C_M_RD)) {
req = 0xB9;
index = (((msg[i].buf[0] << 8) & 0xff00) | (msg[i].buf[1] & 0x00ff));
value = msg[i].addr + (msg[i].len << 8);
length = msg[i + 1].len + 6;
az6027_usb_in_op(d, req, value, index, data, length);
len = msg[i + 1].len;
for (j = 0; j < len; j++)
msg[i + 1].buf[j] = data[j + 5];
i++;
} else {
/* demod 16bit addr */
req = 0xBD;
index = (((msg[i].buf[0] << 8) & 0xff00) | (msg[i].buf[1] & 0x00ff));
value = msg[i].addr + (2 << 8);
length = msg[i].len - 2;
len = msg[i].len - 2;
for (j = 0; j < len; j++)
data[j] = msg[i].buf[j + 2];
az6027_usb_out_op(d, req, value, index, data, length);
}
}
if (msg[i].addr == 0xc0) {
if (msg[i].flags & I2C_M_RD) {
req = 0xB9;
index = 0x0;
value = msg[i].addr;
length = msg[i].len + 6;
az6027_usb_in_op(d, req, value, index, data, length);
len = msg[i].len;
for (j = 0; j < len; j++)
msg[i].buf[j] = data[j + 5];
} else {
req = 0xBD;
index = msg[i].buf[0] & 0x00FF;
value = msg[i].addr + (1 << 8);
length = msg[i].len - 1;
len = msg[i].len - 1;
for (j = 0; j < len; j++)
data[j] = msg[i].buf[j + 1];
az6027_usb_out_op(d, req, value, index, data, length);
}
}
}
mutex_unlock(&d->i2c_mutex);
kfree(data);
return i;
}
static u32 az6027_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C;
}
static struct i2c_algorithm az6027_i2c_algo = {
.master_xfer = az6027_i2c_xfer,
.functionality = az6027_i2c_func,
};
static int az6027_identify_state(struct usb_device *udev,
struct dvb_usb_device_properties *props,
struct dvb_usb_device_description **desc,
int *cold)
{
u8 *b;
s16 ret;
b = kmalloc(16, GFP_KERNEL);
if (!b)
return -ENOMEM;
ret = usb_control_msg(udev,
usb_rcvctrlpipe(udev, 0),
0xb7,
USB_TYPE_VENDOR | USB_DIR_IN,
6,
0,
b,
6,
USB_CTRL_GET_TIMEOUT);
*cold = ret <= 0;
kfree(b);
deb_info("cold: %d\n", *cold);
return 0;
}
static struct usb_device_id az6027_usb_table[] = {
{ USB_DEVICE(USB_VID_AZUREWAVE, USB_PID_AZUREWAVE_AZ6027) },
{ USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_DVBS2CI_V1) },
{ USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_DVBS2CI_V2) },
{ USB_DEVICE(USB_VID_TECHNISAT, USB_PID_TECHNISAT_USB2_HDCI_V1) },
{ USB_DEVICE(USB_VID_TECHNISAT, USB_PID_TECHNISAT_USB2_HDCI_V2) },
{ USB_DEVICE(USB_VID_ELGATO, USB_PID_ELGATO_EYETV_SAT) },
{ },
};
MODULE_DEVICE_TABLE(usb, az6027_usb_table);
static struct dvb_usb_device_properties az6027_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = CYPRESS_FX2,
.firmware = "dvb-usb-az6027-03.fw",
.no_reconnect = 1,
.size_of_priv = sizeof(struct az6027_device_state),
.identify_state = az6027_identify_state,
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {{
.streaming_ctrl = az6027_streaming_ctrl,
.frontend_attach = az6027_frontend_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 10,
.endpoint = 0x02,
.u = {
.bulk = {
.buffersize = 4096,
}
}
},
}},
}
},
/*
.power_ctrl = az6027_power_ctrl,
.read_mac_address = az6027_read_mac_addr,
*/
.rc.legacy = {
.rc_map_table = rc_map_az6027_table,
.rc_map_size = ARRAY_SIZE(rc_map_az6027_table),
.rc_interval = 400,
.rc_query = az6027_rc_query,
},
.i2c_algo = &az6027_i2c_algo,
.num_device_descs = 6,
.devices = {
{
.name = "AZUREWAVE DVB-S/S2 USB2.0 (AZ6027)",
.cold_ids = { &az6027_usb_table[0], NULL },
.warm_ids = { NULL },
}, {
.name = "TERRATEC S7",
.cold_ids = { &az6027_usb_table[1], NULL },
.warm_ids = { NULL },
}, {
.name = "TERRATEC S7 MKII",
.cold_ids = { &az6027_usb_table[2], NULL },
.warm_ids = { NULL },
}, {
.name = "Technisat SkyStar USB 2 HD CI",
.cold_ids = { &az6027_usb_table[3], NULL },
.warm_ids = { NULL },
}, {
.name = "Technisat SkyStar USB 2 HD CI",
.cold_ids = { &az6027_usb_table[4], NULL },
.warm_ids = { NULL },
}, {
.name = "Elgato EyeTV Sat",
.cold_ids = { &az6027_usb_table[5], NULL },
.warm_ids = { NULL },
},
{ NULL },
}
};
/* usb specific object needed to register this driver with the usb subsystem */
static struct usb_driver az6027_usb_driver = {
.name = "dvb_usb_az6027",
.probe = az6027_usb_probe,
.disconnect = az6027_usb_disconnect,
.id_table = az6027_usb_table,
};
module_usb_driver(az6027_usb_driver);
MODULE_AUTHOR("Adams Xu <Adams.xu@azwave.com.cn>");
MODULE_DESCRIPTION("Driver for AZUREWAVE DVB-S/S2 USB2.0 (AZ6027)");
MODULE_VERSION("1.0");
MODULE_LICENSE("GPL");
| gpl-2.0 |
El-Nath/shamu | drivers/i2c/i2c-stub.c | 2512 | 5646 | /*
i2c-stub.c - I2C/SMBus chip emulator
Copyright (c) 2004 Mark M. Hoffman <mhoffman@lightlink.com>
Copyright (C) 2007, 2012 Jean Delvare <khali@linux-fr.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#define DEBUG 1
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/i2c.h>
#define MAX_CHIPS 10
#define STUB_FUNC (I2C_FUNC_SMBUS_QUICK | I2C_FUNC_SMBUS_BYTE | \
I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WORD_DATA | \
I2C_FUNC_SMBUS_I2C_BLOCK)
static unsigned short chip_addr[MAX_CHIPS];
module_param_array(chip_addr, ushort, NULL, S_IRUGO);
MODULE_PARM_DESC(chip_addr,
"Chip addresses (up to 10, between 0x03 and 0x77)");
static unsigned long functionality = STUB_FUNC;
module_param(functionality, ulong, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(functionality, "Override functionality bitfield");
struct stub_chip {
u8 pointer;
u16 words[256]; /* Byte operations use the LSB as per SMBus
specification */
};
static struct stub_chip *stub_chips;
/* Return negative errno on error. */
static s32 stub_xfer(struct i2c_adapter *adap, u16 addr, unsigned short flags,
char read_write, u8 command, int size, union i2c_smbus_data *data)
{
s32 ret;
int i, len;
struct stub_chip *chip = NULL;
/* Search for the right chip */
for (i = 0; i < MAX_CHIPS && chip_addr[i]; i++) {
if (addr == chip_addr[i]) {
chip = stub_chips + i;
break;
}
}
if (!chip)
return -ENODEV;
switch (size) {
case I2C_SMBUS_QUICK:
dev_dbg(&adap->dev, "smbus quick - addr 0x%02x\n", addr);
ret = 0;
break;
case I2C_SMBUS_BYTE:
if (read_write == I2C_SMBUS_WRITE) {
chip->pointer = command;
dev_dbg(&adap->dev,
"smbus byte - addr 0x%02x, wrote 0x%02x.\n",
addr, command);
} else {
data->byte = chip->words[chip->pointer++] & 0xff;
dev_dbg(&adap->dev,
"smbus byte - addr 0x%02x, read 0x%02x.\n",
addr, data->byte);
}
ret = 0;
break;
case I2C_SMBUS_BYTE_DATA:
if (read_write == I2C_SMBUS_WRITE) {
chip->words[command] &= 0xff00;
chip->words[command] |= data->byte;
dev_dbg(&adap->dev,
"smbus byte data - addr 0x%02x, wrote 0x%02x at 0x%02x.\n",
addr, data->byte, command);
} else {
data->byte = chip->words[command] & 0xff;
dev_dbg(&adap->dev,
"smbus byte data - addr 0x%02x, read 0x%02x at 0x%02x.\n",
addr, data->byte, command);
}
chip->pointer = command + 1;
ret = 0;
break;
case I2C_SMBUS_WORD_DATA:
if (read_write == I2C_SMBUS_WRITE) {
chip->words[command] = data->word;
dev_dbg(&adap->dev,
"smbus word data - addr 0x%02x, wrote 0x%04x at 0x%02x.\n",
addr, data->word, command);
} else {
data->word = chip->words[command];
dev_dbg(&adap->dev,
"smbus word data - addr 0x%02x, read 0x%04x at 0x%02x.\n",
addr, data->word, command);
}
ret = 0;
break;
case I2C_SMBUS_I2C_BLOCK_DATA:
len = data->block[0];
if (read_write == I2C_SMBUS_WRITE) {
for (i = 0; i < len; i++) {
chip->words[command + i] &= 0xff00;
chip->words[command + i] |= data->block[1 + i];
}
dev_dbg(&adap->dev,
"i2c block data - addr 0x%02x, wrote %d bytes at 0x%02x.\n",
addr, len, command);
} else {
for (i = 0; i < len; i++) {
data->block[1 + i] =
chip->words[command + i] & 0xff;
}
dev_dbg(&adap->dev,
"i2c block data - addr 0x%02x, read %d bytes at 0x%02x.\n",
addr, len, command);
}
ret = 0;
break;
default:
dev_dbg(&adap->dev, "Unsupported I2C/SMBus command\n");
ret = -EOPNOTSUPP;
break;
} /* switch (size) */
return ret;
}
static u32 stub_func(struct i2c_adapter *adapter)
{
return STUB_FUNC & functionality;
}
static const struct i2c_algorithm smbus_algorithm = {
.functionality = stub_func,
.smbus_xfer = stub_xfer,
};
static struct i2c_adapter stub_adapter = {
.owner = THIS_MODULE,
.class = I2C_CLASS_HWMON | I2C_CLASS_SPD,
.algo = &smbus_algorithm,
.name = "SMBus stub driver",
};
static int __init i2c_stub_init(void)
{
int i, ret;
if (!chip_addr[0]) {
pr_err("i2c-stub: Please specify a chip address\n");
return -ENODEV;
}
for (i = 0; i < MAX_CHIPS && chip_addr[i]; i++) {
if (chip_addr[i] < 0x03 || chip_addr[i] > 0x77) {
pr_err("i2c-stub: Invalid chip address 0x%02x\n",
chip_addr[i]);
return -EINVAL;
}
pr_info("i2c-stub: Virtual chip at 0x%02x\n", chip_addr[i]);
}
/* Allocate memory for all chips at once */
stub_chips = kzalloc(i * sizeof(struct stub_chip), GFP_KERNEL);
if (!stub_chips) {
pr_err("i2c-stub: Out of memory\n");
return -ENOMEM;
}
ret = i2c_add_adapter(&stub_adapter);
if (ret)
kfree(stub_chips);
return ret;
}
static void __exit i2c_stub_exit(void)
{
i2c_del_adapter(&stub_adapter);
kfree(stub_chips);
}
MODULE_AUTHOR("Mark M. Hoffman <mhoffman@lightlink.com>");
MODULE_DESCRIPTION("I2C stub driver");
MODULE_LICENSE("GPL");
module_init(i2c_stub_init);
module_exit(i2c_stub_exit);
| gpl-2.0 |
psndna88/AGNI-pureSTOCK | sound/soc/codecs/wm8510.c | 3024 | 19102 | /*
* wm8510.c -- WM8510 ALSA Soc Audio driver
*
* Copyright 2006 Wolfson Microelectronics PLC.
*
* Author: Liam Girdwood <lrg@slimlogic.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/i2c.h>
#include <linux/platform_device.h>
#include <linux/spi/spi.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include "wm8510.h"
/*
* wm8510 register cache
* We can't read the WM8510 register space when we are
* using 2 wire for device control, so we cache them instead.
*/
static const u16 wm8510_reg[WM8510_CACHEREGNUM] = {
0x0000, 0x0000, 0x0000, 0x0000,
0x0050, 0x0000, 0x0140, 0x0000,
0x0000, 0x0000, 0x0000, 0x00ff,
0x0000, 0x0000, 0x0100, 0x00ff,
0x0000, 0x0000, 0x012c, 0x002c,
0x002c, 0x002c, 0x002c, 0x0000,
0x0032, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000,
0x0038, 0x000b, 0x0032, 0x0000,
0x0008, 0x000c, 0x0093, 0x00e9,
0x0000, 0x0000, 0x0000, 0x0000,
0x0003, 0x0010, 0x0000, 0x0000,
0x0000, 0x0002, 0x0001, 0x0000,
0x0000, 0x0000, 0x0039, 0x0000,
0x0001,
};
#define WM8510_POWER1_BIASEN 0x08
#define WM8510_POWER1_BUFIOEN 0x10
#define wm8510_reset(c) snd_soc_write(c, WM8510_RESET, 0)
/* codec private data */
struct wm8510_priv {
enum snd_soc_control_type control_type;
};
static const char *wm8510_companding[] = { "Off", "NC", "u-law", "A-law" };
static const char *wm8510_deemp[] = { "None", "32kHz", "44.1kHz", "48kHz" };
static const char *wm8510_alc[] = { "ALC", "Limiter" };
static const struct soc_enum wm8510_enum[] = {
SOC_ENUM_SINGLE(WM8510_COMP, 1, 4, wm8510_companding), /* adc */
SOC_ENUM_SINGLE(WM8510_COMP, 3, 4, wm8510_companding), /* dac */
SOC_ENUM_SINGLE(WM8510_DAC, 4, 4, wm8510_deemp),
SOC_ENUM_SINGLE(WM8510_ALC3, 8, 2, wm8510_alc),
};
static const struct snd_kcontrol_new wm8510_snd_controls[] = {
SOC_SINGLE("Digital Loopback Switch", WM8510_COMP, 0, 1, 0),
SOC_ENUM("DAC Companding", wm8510_enum[1]),
SOC_ENUM("ADC Companding", wm8510_enum[0]),
SOC_ENUM("Playback De-emphasis", wm8510_enum[2]),
SOC_SINGLE("DAC Inversion Switch", WM8510_DAC, 0, 1, 0),
SOC_SINGLE("Master Playback Volume", WM8510_DACVOL, 0, 127, 0),
SOC_SINGLE("High Pass Filter Switch", WM8510_ADC, 8, 1, 0),
SOC_SINGLE("High Pass Cut Off", WM8510_ADC, 4, 7, 0),
SOC_SINGLE("ADC Inversion Switch", WM8510_COMP, 0, 1, 0),
SOC_SINGLE("Capture Volume", WM8510_ADCVOL, 0, 127, 0),
SOC_SINGLE("DAC Playback Limiter Switch", WM8510_DACLIM1, 8, 1, 0),
SOC_SINGLE("DAC Playback Limiter Decay", WM8510_DACLIM1, 4, 15, 0),
SOC_SINGLE("DAC Playback Limiter Attack", WM8510_DACLIM1, 0, 15, 0),
SOC_SINGLE("DAC Playback Limiter Threshold", WM8510_DACLIM2, 4, 7, 0),
SOC_SINGLE("DAC Playback Limiter Boost", WM8510_DACLIM2, 0, 15, 0),
SOC_SINGLE("ALC Enable Switch", WM8510_ALC1, 8, 1, 0),
SOC_SINGLE("ALC Capture Max Gain", WM8510_ALC1, 3, 7, 0),
SOC_SINGLE("ALC Capture Min Gain", WM8510_ALC1, 0, 7, 0),
SOC_SINGLE("ALC Capture ZC Switch", WM8510_ALC2, 8, 1, 0),
SOC_SINGLE("ALC Capture Hold", WM8510_ALC2, 4, 7, 0),
SOC_SINGLE("ALC Capture Target", WM8510_ALC2, 0, 15, 0),
SOC_ENUM("ALC Capture Mode", wm8510_enum[3]),
SOC_SINGLE("ALC Capture Decay", WM8510_ALC3, 4, 15, 0),
SOC_SINGLE("ALC Capture Attack", WM8510_ALC3, 0, 15, 0),
SOC_SINGLE("ALC Capture Noise Gate Switch", WM8510_NGATE, 3, 1, 0),
SOC_SINGLE("ALC Capture Noise Gate Threshold", WM8510_NGATE, 0, 7, 0),
SOC_SINGLE("Capture PGA ZC Switch", WM8510_INPPGA, 7, 1, 0),
SOC_SINGLE("Capture PGA Volume", WM8510_INPPGA, 0, 63, 0),
SOC_SINGLE("Speaker Playback ZC Switch", WM8510_SPKVOL, 7, 1, 0),
SOC_SINGLE("Speaker Playback Switch", WM8510_SPKVOL, 6, 1, 1),
SOC_SINGLE("Speaker Playback Volume", WM8510_SPKVOL, 0, 63, 0),
SOC_SINGLE("Speaker Boost", WM8510_OUTPUT, 2, 1, 0),
SOC_SINGLE("Capture Boost(+20dB)", WM8510_ADCBOOST, 8, 1, 0),
SOC_SINGLE("Mono Playback Switch", WM8510_MONOMIX, 6, 1, 1),
};
/* Speaker Output Mixer */
static const struct snd_kcontrol_new wm8510_speaker_mixer_controls[] = {
SOC_DAPM_SINGLE("Line Bypass Switch", WM8510_SPKMIX, 1, 1, 0),
SOC_DAPM_SINGLE("Aux Playback Switch", WM8510_SPKMIX, 5, 1, 0),
SOC_DAPM_SINGLE("PCM Playback Switch", WM8510_SPKMIX, 0, 1, 0),
};
/* Mono Output Mixer */
static const struct snd_kcontrol_new wm8510_mono_mixer_controls[] = {
SOC_DAPM_SINGLE("Line Bypass Switch", WM8510_MONOMIX, 1, 1, 0),
SOC_DAPM_SINGLE("Aux Playback Switch", WM8510_MONOMIX, 2, 1, 0),
SOC_DAPM_SINGLE("PCM Playback Switch", WM8510_MONOMIX, 0, 1, 0),
};
static const struct snd_kcontrol_new wm8510_boost_controls[] = {
SOC_DAPM_SINGLE("Mic PGA Switch", WM8510_INPPGA, 6, 1, 1),
SOC_DAPM_SINGLE("Aux Volume", WM8510_ADCBOOST, 0, 7, 0),
SOC_DAPM_SINGLE("Mic Volume", WM8510_ADCBOOST, 4, 7, 0),
};
static const struct snd_kcontrol_new wm8510_micpga_controls[] = {
SOC_DAPM_SINGLE("MICP Switch", WM8510_INPUT, 0, 1, 0),
SOC_DAPM_SINGLE("MICN Switch", WM8510_INPUT, 1, 1, 0),
SOC_DAPM_SINGLE("AUX Switch", WM8510_INPUT, 2, 1, 0),
};
static const struct snd_soc_dapm_widget wm8510_dapm_widgets[] = {
SND_SOC_DAPM_MIXER("Speaker Mixer", WM8510_POWER3, 2, 0,
&wm8510_speaker_mixer_controls[0],
ARRAY_SIZE(wm8510_speaker_mixer_controls)),
SND_SOC_DAPM_MIXER("Mono Mixer", WM8510_POWER3, 3, 0,
&wm8510_mono_mixer_controls[0],
ARRAY_SIZE(wm8510_mono_mixer_controls)),
SND_SOC_DAPM_DAC("DAC", "HiFi Playback", WM8510_POWER3, 0, 0),
SND_SOC_DAPM_ADC("ADC", "HiFi Capture", WM8510_POWER2, 0, 0),
SND_SOC_DAPM_PGA("Aux Input", WM8510_POWER1, 6, 0, NULL, 0),
SND_SOC_DAPM_PGA("SpkN Out", WM8510_POWER3, 5, 0, NULL, 0),
SND_SOC_DAPM_PGA("SpkP Out", WM8510_POWER3, 6, 0, NULL, 0),
SND_SOC_DAPM_PGA("Mono Out", WM8510_POWER3, 7, 0, NULL, 0),
SND_SOC_DAPM_MIXER("Mic PGA", WM8510_POWER2, 2, 0,
&wm8510_micpga_controls[0],
ARRAY_SIZE(wm8510_micpga_controls)),
SND_SOC_DAPM_MIXER("Boost Mixer", WM8510_POWER2, 4, 0,
&wm8510_boost_controls[0],
ARRAY_SIZE(wm8510_boost_controls)),
SND_SOC_DAPM_MICBIAS("Mic Bias", WM8510_POWER1, 4, 0),
SND_SOC_DAPM_INPUT("MICN"),
SND_SOC_DAPM_INPUT("MICP"),
SND_SOC_DAPM_INPUT("AUX"),
SND_SOC_DAPM_OUTPUT("MONOOUT"),
SND_SOC_DAPM_OUTPUT("SPKOUTP"),
SND_SOC_DAPM_OUTPUT("SPKOUTN"),
};
static const struct snd_soc_dapm_route audio_map[] = {
/* Mono output mixer */
{"Mono Mixer", "PCM Playback Switch", "DAC"},
{"Mono Mixer", "Aux Playback Switch", "Aux Input"},
{"Mono Mixer", "Line Bypass Switch", "Boost Mixer"},
/* Speaker output mixer */
{"Speaker Mixer", "PCM Playback Switch", "DAC"},
{"Speaker Mixer", "Aux Playback Switch", "Aux Input"},
{"Speaker Mixer", "Line Bypass Switch", "Boost Mixer"},
/* Outputs */
{"Mono Out", NULL, "Mono Mixer"},
{"MONOOUT", NULL, "Mono Out"},
{"SpkN Out", NULL, "Speaker Mixer"},
{"SpkP Out", NULL, "Speaker Mixer"},
{"SPKOUTN", NULL, "SpkN Out"},
{"SPKOUTP", NULL, "SpkP Out"},
/* Microphone PGA */
{"Mic PGA", "MICN Switch", "MICN"},
{"Mic PGA", "MICP Switch", "MICP"},
{ "Mic PGA", "AUX Switch", "Aux Input" },
/* Boost Mixer */
{"Boost Mixer", "Mic PGA Switch", "Mic PGA"},
{"Boost Mixer", "Mic Volume", "MICP"},
{"Boost Mixer", "Aux Volume", "Aux Input"},
{"ADC", NULL, "Boost Mixer"},
};
static int wm8510_add_widgets(struct snd_soc_codec *codec)
{
struct snd_soc_dapm_context *dapm = &codec->dapm;
snd_soc_dapm_new_controls(dapm, wm8510_dapm_widgets,
ARRAY_SIZE(wm8510_dapm_widgets));
snd_soc_dapm_add_routes(dapm, audio_map, ARRAY_SIZE(audio_map));
return 0;
}
struct pll_ {
unsigned int pre_div:4; /* prescale - 1 */
unsigned int n:4;
unsigned int k;
};
static struct pll_ pll_div;
/* The size in bits of the pll divide multiplied by 10
* to allow rounding later */
#define FIXED_PLL_SIZE ((1 << 24) * 10)
static void pll_factors(unsigned int target, unsigned int source)
{
unsigned long long Kpart;
unsigned int K, Ndiv, Nmod;
Ndiv = target / source;
if (Ndiv < 6) {
source >>= 1;
pll_div.pre_div = 1;
Ndiv = target / source;
} else
pll_div.pre_div = 0;
if ((Ndiv < 6) || (Ndiv > 12))
printk(KERN_WARNING
"WM8510 N value %u outwith recommended range!d\n",
Ndiv);
pll_div.n = Ndiv;
Nmod = target % source;
Kpart = FIXED_PLL_SIZE * (long long)Nmod;
do_div(Kpart, source);
K = Kpart & 0xFFFFFFFF;
/* Check if we need to round */
if ((K % 10) >= 5)
K += 5;
/* Move down to proper range now rounding is done */
K /= 10;
pll_div.k = K;
}
static int wm8510_set_dai_pll(struct snd_soc_dai *codec_dai, int pll_id,
int source, unsigned int freq_in, unsigned int freq_out)
{
struct snd_soc_codec *codec = codec_dai->codec;
u16 reg;
if (freq_in == 0 || freq_out == 0) {
/* Clock CODEC directly from MCLK */
reg = snd_soc_read(codec, WM8510_CLOCK);
snd_soc_write(codec, WM8510_CLOCK, reg & 0x0ff);
/* Turn off PLL */
reg = snd_soc_read(codec, WM8510_POWER1);
snd_soc_write(codec, WM8510_POWER1, reg & 0x1df);
return 0;
}
pll_factors(freq_out*4, freq_in);
snd_soc_write(codec, WM8510_PLLN, (pll_div.pre_div << 4) | pll_div.n);
snd_soc_write(codec, WM8510_PLLK1, pll_div.k >> 18);
snd_soc_write(codec, WM8510_PLLK2, (pll_div.k >> 9) & 0x1ff);
snd_soc_write(codec, WM8510_PLLK3, pll_div.k & 0x1ff);
reg = snd_soc_read(codec, WM8510_POWER1);
snd_soc_write(codec, WM8510_POWER1, reg | 0x020);
/* Run CODEC from PLL instead of MCLK */
reg = snd_soc_read(codec, WM8510_CLOCK);
snd_soc_write(codec, WM8510_CLOCK, reg | 0x100);
return 0;
}
/*
* Configure WM8510 clock dividers.
*/
static int wm8510_set_dai_clkdiv(struct snd_soc_dai *codec_dai,
int div_id, int div)
{
struct snd_soc_codec *codec = codec_dai->codec;
u16 reg;
switch (div_id) {
case WM8510_OPCLKDIV:
reg = snd_soc_read(codec, WM8510_GPIO) & 0x1cf;
snd_soc_write(codec, WM8510_GPIO, reg | div);
break;
case WM8510_MCLKDIV:
reg = snd_soc_read(codec, WM8510_CLOCK) & 0x11f;
snd_soc_write(codec, WM8510_CLOCK, reg | div);
break;
case WM8510_ADCCLK:
reg = snd_soc_read(codec, WM8510_ADC) & 0x1f7;
snd_soc_write(codec, WM8510_ADC, reg | div);
break;
case WM8510_DACCLK:
reg = snd_soc_read(codec, WM8510_DAC) & 0x1f7;
snd_soc_write(codec, WM8510_DAC, reg | div);
break;
case WM8510_BCLKDIV:
reg = snd_soc_read(codec, WM8510_CLOCK) & 0x1e3;
snd_soc_write(codec, WM8510_CLOCK, reg | div);
break;
default:
return -EINVAL;
}
return 0;
}
static int wm8510_set_dai_fmt(struct snd_soc_dai *codec_dai,
unsigned int fmt)
{
struct snd_soc_codec *codec = codec_dai->codec;
u16 iface = 0;
u16 clk = snd_soc_read(codec, WM8510_CLOCK) & 0x1fe;
/* set master/slave audio interface */
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
clk |= 0x0001;
break;
case SND_SOC_DAIFMT_CBS_CFS:
break;
default:
return -EINVAL;
}
/* interface format */
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
iface |= 0x0010;
break;
case SND_SOC_DAIFMT_RIGHT_J:
break;
case SND_SOC_DAIFMT_LEFT_J:
iface |= 0x0008;
break;
case SND_SOC_DAIFMT_DSP_A:
iface |= 0x00018;
break;
default:
return -EINVAL;
}
/* clock inversion */
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
case SND_SOC_DAIFMT_IB_IF:
iface |= 0x0180;
break;
case SND_SOC_DAIFMT_IB_NF:
iface |= 0x0100;
break;
case SND_SOC_DAIFMT_NB_IF:
iface |= 0x0080;
break;
default:
return -EINVAL;
}
snd_soc_write(codec, WM8510_IFACE, iface);
snd_soc_write(codec, WM8510_CLOCK, clk);
return 0;
}
static int wm8510_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_codec *codec = rtd->codec;
u16 iface = snd_soc_read(codec, WM8510_IFACE) & 0x19f;
u16 adn = snd_soc_read(codec, WM8510_ADD) & 0x1f1;
/* bit size */
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
break;
case SNDRV_PCM_FORMAT_S20_3LE:
iface |= 0x0020;
break;
case SNDRV_PCM_FORMAT_S24_LE:
iface |= 0x0040;
break;
case SNDRV_PCM_FORMAT_S32_LE:
iface |= 0x0060;
break;
}
/* filter coefficient */
switch (params_rate(params)) {
case 8000:
adn |= 0x5 << 1;
break;
case 11025:
adn |= 0x4 << 1;
break;
case 16000:
adn |= 0x3 << 1;
break;
case 22050:
adn |= 0x2 << 1;
break;
case 32000:
adn |= 0x1 << 1;
break;
case 44100:
case 48000:
break;
}
snd_soc_write(codec, WM8510_IFACE, iface);
snd_soc_write(codec, WM8510_ADD, adn);
return 0;
}
static int wm8510_mute(struct snd_soc_dai *dai, int mute)
{
struct snd_soc_codec *codec = dai->codec;
u16 mute_reg = snd_soc_read(codec, WM8510_DAC) & 0xffbf;
if (mute)
snd_soc_write(codec, WM8510_DAC, mute_reg | 0x40);
else
snd_soc_write(codec, WM8510_DAC, mute_reg);
return 0;
}
/* liam need to make this lower power with dapm */
static int wm8510_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
u16 power1 = snd_soc_read(codec, WM8510_POWER1) & ~0x3;
switch (level) {
case SND_SOC_BIAS_ON:
case SND_SOC_BIAS_PREPARE:
power1 |= 0x1; /* VMID 50k */
snd_soc_write(codec, WM8510_POWER1, power1);
break;
case SND_SOC_BIAS_STANDBY:
power1 |= WM8510_POWER1_BIASEN | WM8510_POWER1_BUFIOEN;
if (codec->dapm.bias_level == SND_SOC_BIAS_OFF) {
/* Initial cap charge at VMID 5k */
snd_soc_write(codec, WM8510_POWER1, power1 | 0x3);
mdelay(100);
}
power1 |= 0x2; /* VMID 500k */
snd_soc_write(codec, WM8510_POWER1, power1);
break;
case SND_SOC_BIAS_OFF:
snd_soc_write(codec, WM8510_POWER1, 0);
snd_soc_write(codec, WM8510_POWER2, 0);
snd_soc_write(codec, WM8510_POWER3, 0);
break;
}
codec->dapm.bias_level = level;
return 0;
}
#define WM8510_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_11025 |\
SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_22050 |\
SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000)
#define WM8510_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE |\
SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S32_LE)
static struct snd_soc_dai_ops wm8510_dai_ops = {
.hw_params = wm8510_pcm_hw_params,
.digital_mute = wm8510_mute,
.set_fmt = wm8510_set_dai_fmt,
.set_clkdiv = wm8510_set_dai_clkdiv,
.set_pll = wm8510_set_dai_pll,
};
static struct snd_soc_dai_driver wm8510_dai = {
.name = "wm8510-hifi",
.playback = {
.stream_name = "Playback",
.channels_min = 2,
.channels_max = 2,
.rates = WM8510_RATES,
.formats = WM8510_FORMATS,},
.capture = {
.stream_name = "Capture",
.channels_min = 2,
.channels_max = 2,
.rates = WM8510_RATES,
.formats = WM8510_FORMATS,},
.ops = &wm8510_dai_ops,
.symmetric_rates = 1,
};
static int wm8510_suspend(struct snd_soc_codec *codec, pm_message_t state)
{
wm8510_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static int wm8510_resume(struct snd_soc_codec *codec)
{
int i;
u8 data[2];
u16 *cache = codec->reg_cache;
/* Sync reg_cache with the hardware */
for (i = 0; i < ARRAY_SIZE(wm8510_reg); i++) {
data[0] = (i << 1) | ((cache[i] >> 8) & 0x0001);
data[1] = cache[i] & 0x00ff;
codec->hw_write(codec->control_data, data, 2);
}
wm8510_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return 0;
}
static int wm8510_probe(struct snd_soc_codec *codec)
{
struct wm8510_priv *wm8510 = snd_soc_codec_get_drvdata(codec);
int ret;
ret = snd_soc_codec_set_cache_io(codec, 7, 9, wm8510->control_type);
if (ret < 0) {
printk(KERN_ERR "wm8510: failed to set cache I/O: %d\n", ret);
return ret;
}
wm8510_reset(codec);
/* power on device */
wm8510_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
snd_soc_add_controls(codec, wm8510_snd_controls,
ARRAY_SIZE(wm8510_snd_controls));
wm8510_add_widgets(codec);
return ret;
}
/* power down chip */
static int wm8510_remove(struct snd_soc_codec *codec)
{
struct wm8510_priv *wm8510 = snd_soc_codec_get_drvdata(codec);
wm8510_set_bias_level(codec, SND_SOC_BIAS_OFF);
kfree(wm8510);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_wm8510 = {
.probe = wm8510_probe,
.remove = wm8510_remove,
.suspend = wm8510_suspend,
.resume = wm8510_resume,
.set_bias_level = wm8510_set_bias_level,
.reg_cache_size = ARRAY_SIZE(wm8510_reg),
.reg_word_size = sizeof(u16),
.reg_cache_default =wm8510_reg,
};
#if defined(CONFIG_SPI_MASTER)
static int __devinit wm8510_spi_probe(struct spi_device *spi)
{
struct wm8510_priv *wm8510;
int ret;
wm8510 = kzalloc(sizeof(struct wm8510_priv), GFP_KERNEL);
if (wm8510 == NULL)
return -ENOMEM;
wm8510->control_type = SND_SOC_SPI;
spi_set_drvdata(spi, wm8510);
ret = snd_soc_register_codec(&spi->dev,
&soc_codec_dev_wm8510, &wm8510_dai, 1);
if (ret < 0)
kfree(wm8510);
return ret;
}
static int __devexit wm8510_spi_remove(struct spi_device *spi)
{
snd_soc_unregister_codec(&spi->dev);
return 0;
}
static struct spi_driver wm8510_spi_driver = {
.driver = {
.name = "wm8510",
.owner = THIS_MODULE,
},
.probe = wm8510_spi_probe,
.remove = __devexit_p(wm8510_spi_remove),
};
#endif /* CONFIG_SPI_MASTER */
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
static __devinit int wm8510_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct wm8510_priv *wm8510;
int ret;
wm8510 = kzalloc(sizeof(struct wm8510_priv), GFP_KERNEL);
if (wm8510 == NULL)
return -ENOMEM;
i2c_set_clientdata(i2c, wm8510);
wm8510->control_type = SND_SOC_I2C;
ret = snd_soc_register_codec(&i2c->dev,
&soc_codec_dev_wm8510, &wm8510_dai, 1);
if (ret < 0)
kfree(wm8510);
return ret;
}
static __devexit int wm8510_i2c_remove(struct i2c_client *client)
{
snd_soc_unregister_codec(&client->dev);
return 0;
}
static const struct i2c_device_id wm8510_i2c_id[] = {
{ "wm8510", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, wm8510_i2c_id);
static struct i2c_driver wm8510_i2c_driver = {
.driver = {
.name = "wm8510-codec",
.owner = THIS_MODULE,
},
.probe = wm8510_i2c_probe,
.remove = __devexit_p(wm8510_i2c_remove),
.id_table = wm8510_i2c_id,
};
#endif
static int __init wm8510_modinit(void)
{
int ret = 0;
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
ret = i2c_add_driver(&wm8510_i2c_driver);
if (ret != 0) {
printk(KERN_ERR "Failed to register WM8510 I2C driver: %d\n",
ret);
}
#endif
#if defined(CONFIG_SPI_MASTER)
ret = spi_register_driver(&wm8510_spi_driver);
if (ret != 0) {
printk(KERN_ERR "Failed to register WM8510 SPI driver: %d\n",
ret);
}
#endif
return ret;
}
module_init(wm8510_modinit);
static void __exit wm8510_exit(void)
{
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
i2c_del_driver(&wm8510_i2c_driver);
#endif
#if defined(CONFIG_SPI_MASTER)
spi_unregister_driver(&wm8510_spi_driver);
#endif
}
module_exit(wm8510_exit);
MODULE_DESCRIPTION("ASoC WM8510 driver");
MODULE_AUTHOR("Liam Girdwood");
MODULE_LICENSE("GPL");
| gpl-2.0 |
DennisBold/CodeAurora-MSM-Kernel | drivers/hwmon/emc2103.c | 4816 | 21123 | /*
* emc2103.c - Support for SMSC EMC2103
* Copyright (c) 2010 SMSC
*
* 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/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
/* Addresses scanned */
static const unsigned short normal_i2c[] = { 0x2E, I2C_CLIENT_END };
static const u8 REG_TEMP[4] = { 0x00, 0x02, 0x04, 0x06 };
static const u8 REG_TEMP_MIN[4] = { 0x3c, 0x38, 0x39, 0x3a };
static const u8 REG_TEMP_MAX[4] = { 0x34, 0x30, 0x31, 0x32 };
#define REG_CONF1 0x20
#define REG_TEMP_MAX_ALARM 0x24
#define REG_TEMP_MIN_ALARM 0x25
#define REG_FAN_CONF1 0x42
#define REG_FAN_TARGET_LO 0x4c
#define REG_FAN_TARGET_HI 0x4d
#define REG_FAN_TACH_HI 0x4e
#define REG_FAN_TACH_LO 0x4f
#define REG_PRODUCT_ID 0xfd
#define REG_MFG_ID 0xfe
/* equation 4 from datasheet: rpm = (3932160 * multipler) / count */
#define FAN_RPM_FACTOR 3932160
/*
* 2103-2 and 2103-4's 3rd temperature sensor can be connected to two diodes
* in anti-parallel mode, and in this configuration both can be read
* independently (so we have 4 temperature inputs). The device can't
* detect if it's connected in this mode, so we have to manually enable
* it. Default is to leave the device in the state it's already in (-1).
* This parameter allows APD mode to be optionally forced on or off
*/
static int apd = -1;
module_param(apd, bint, 0);
MODULE_PARM_DESC(init, "Set to zero to disable anti-parallel diode mode");
struct temperature {
s8 degrees;
u8 fraction; /* 0-7 multiples of 0.125 */
};
struct emc2103_data {
struct device *hwmon_dev;
struct mutex update_lock;
bool valid; /* registers are valid */
bool fan_rpm_control;
int temp_count; /* num of temp sensors */
unsigned long last_updated; /* in jiffies */
struct temperature temp[4]; /* internal + 3 external */
s8 temp_min[4]; /* no fractional part */
s8 temp_max[4]; /* no fractional part */
u8 temp_min_alarm;
u8 temp_max_alarm;
u8 fan_multiplier;
u16 fan_tach;
u16 fan_target;
};
static int read_u8_from_i2c(struct i2c_client *client, u8 i2c_reg, u8 *output)
{
int status = i2c_smbus_read_byte_data(client, i2c_reg);
if (status < 0) {
dev_warn(&client->dev, "reg 0x%02x, err %d\n",
i2c_reg, status);
} else {
*output = status;
}
return status;
}
static void read_temp_from_i2c(struct i2c_client *client, u8 i2c_reg,
struct temperature *temp)
{
u8 degrees, fractional;
if (read_u8_from_i2c(client, i2c_reg, °rees) < 0)
return;
if (read_u8_from_i2c(client, i2c_reg + 1, &fractional) < 0)
return;
temp->degrees = degrees;
temp->fraction = (fractional & 0xe0) >> 5;
}
static void read_fan_from_i2c(struct i2c_client *client, u16 *output,
u8 hi_addr, u8 lo_addr)
{
u8 high_byte, lo_byte;
if (read_u8_from_i2c(client, hi_addr, &high_byte) < 0)
return;
if (read_u8_from_i2c(client, lo_addr, &lo_byte) < 0)
return;
*output = ((u16)high_byte << 5) | (lo_byte >> 3);
}
static void write_fan_target_to_i2c(struct i2c_client *client, u16 new_target)
{
u8 high_byte = (new_target & 0x1fe0) >> 5;
u8 low_byte = (new_target & 0x001f) << 3;
i2c_smbus_write_byte_data(client, REG_FAN_TARGET_LO, low_byte);
i2c_smbus_write_byte_data(client, REG_FAN_TARGET_HI, high_byte);
}
static void read_fan_config_from_i2c(struct i2c_client *client)
{
struct emc2103_data *data = i2c_get_clientdata(client);
u8 conf1;
if (read_u8_from_i2c(client, REG_FAN_CONF1, &conf1) < 0)
return;
data->fan_multiplier = 1 << ((conf1 & 0x60) >> 5);
data->fan_rpm_control = (conf1 & 0x80) != 0;
}
static struct emc2103_data *emc2103_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct emc2103_data *data = i2c_get_clientdata(client);
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ + HZ / 2)
|| !data->valid) {
int i;
for (i = 0; i < data->temp_count; i++) {
read_temp_from_i2c(client, REG_TEMP[i], &data->temp[i]);
read_u8_from_i2c(client, REG_TEMP_MIN[i],
&data->temp_min[i]);
read_u8_from_i2c(client, REG_TEMP_MAX[i],
&data->temp_max[i]);
}
read_u8_from_i2c(client, REG_TEMP_MIN_ALARM,
&data->temp_min_alarm);
read_u8_from_i2c(client, REG_TEMP_MAX_ALARM,
&data->temp_max_alarm);
read_fan_from_i2c(client, &data->fan_tach,
REG_FAN_TACH_HI, REG_FAN_TACH_LO);
read_fan_from_i2c(client, &data->fan_target,
REG_FAN_TARGET_HI, REG_FAN_TARGET_LO);
read_fan_config_from_i2c(client);
data->last_updated = jiffies;
data->valid = true;
}
mutex_unlock(&data->update_lock);
return data;
}
static ssize_t
show_temp(struct device *dev, struct device_attribute *da, char *buf)
{
int nr = to_sensor_dev_attr(da)->index;
struct emc2103_data *data = emc2103_update_device(dev);
int millidegrees = data->temp[nr].degrees * 1000
+ data->temp[nr].fraction * 125;
return sprintf(buf, "%d\n", millidegrees);
}
static ssize_t
show_temp_min(struct device *dev, struct device_attribute *da, char *buf)
{
int nr = to_sensor_dev_attr(da)->index;
struct emc2103_data *data = emc2103_update_device(dev);
int millidegrees = data->temp_min[nr] * 1000;
return sprintf(buf, "%d\n", millidegrees);
}
static ssize_t
show_temp_max(struct device *dev, struct device_attribute *da, char *buf)
{
int nr = to_sensor_dev_attr(da)->index;
struct emc2103_data *data = emc2103_update_device(dev);
int millidegrees = data->temp_max[nr] * 1000;
return sprintf(buf, "%d\n", millidegrees);
}
static ssize_t
show_temp_fault(struct device *dev, struct device_attribute *da, char *buf)
{
int nr = to_sensor_dev_attr(da)->index;
struct emc2103_data *data = emc2103_update_device(dev);
bool fault = (data->temp[nr].degrees == -128);
return sprintf(buf, "%d\n", fault ? 1 : 0);
}
static ssize_t
show_temp_min_alarm(struct device *dev, struct device_attribute *da, char *buf)
{
int nr = to_sensor_dev_attr(da)->index;
struct emc2103_data *data = emc2103_update_device(dev);
bool alarm = data->temp_min_alarm & (1 << nr);
return sprintf(buf, "%d\n", alarm ? 1 : 0);
}
static ssize_t
show_temp_max_alarm(struct device *dev, struct device_attribute *da, char *buf)
{
int nr = to_sensor_dev_attr(da)->index;
struct emc2103_data *data = emc2103_update_device(dev);
bool alarm = data->temp_max_alarm & (1 << nr);
return sprintf(buf, "%d\n", alarm ? 1 : 0);
}
static ssize_t set_temp_min(struct device *dev, struct device_attribute *da,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(da)->index;
struct i2c_client *client = to_i2c_client(dev);
struct emc2103_data *data = i2c_get_clientdata(client);
long val;
int result = kstrtol(buf, 10, &val);
if (result < 0)
return -EINVAL;
val = DIV_ROUND_CLOSEST(val, 1000);
if ((val < -63) || (val > 127))
return -EINVAL;
mutex_lock(&data->update_lock);
data->temp_min[nr] = val;
i2c_smbus_write_byte_data(client, REG_TEMP_MIN[nr], val);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t set_temp_max(struct device *dev, struct device_attribute *da,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(da)->index;
struct i2c_client *client = to_i2c_client(dev);
struct emc2103_data *data = i2c_get_clientdata(client);
long val;
int result = kstrtol(buf, 10, &val);
if (result < 0)
return -EINVAL;
val = DIV_ROUND_CLOSEST(val, 1000);
if ((val < -63) || (val > 127))
return -EINVAL;
mutex_lock(&data->update_lock);
data->temp_max[nr] = val;
i2c_smbus_write_byte_data(client, REG_TEMP_MAX[nr], val);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t
show_fan(struct device *dev, struct device_attribute *da, char *buf)
{
struct emc2103_data *data = emc2103_update_device(dev);
int rpm = 0;
if (data->fan_tach != 0)
rpm = (FAN_RPM_FACTOR * data->fan_multiplier) / data->fan_tach;
return sprintf(buf, "%d\n", rpm);
}
static ssize_t
show_fan_div(struct device *dev, struct device_attribute *da, char *buf)
{
struct emc2103_data *data = emc2103_update_device(dev);
int fan_div = 8 / data->fan_multiplier;
return sprintf(buf, "%d\n", fan_div);
}
/*
* Note: we also update the fan target here, because its value is
* determined in part by the fan clock divider. This follows the principle
* of least surprise; the user doesn't expect the fan target to change just
* because the divider changed.
*/
static ssize_t set_fan_div(struct device *dev, struct device_attribute *da,
const char *buf, size_t count)
{
struct emc2103_data *data = emc2103_update_device(dev);
struct i2c_client *client = to_i2c_client(dev);
int new_range_bits, old_div = 8 / data->fan_multiplier;
long new_div;
int status = kstrtol(buf, 10, &new_div);
if (status < 0)
return -EINVAL;
if (new_div == old_div) /* No change */
return count;
switch (new_div) {
case 1:
new_range_bits = 3;
break;
case 2:
new_range_bits = 2;
break;
case 4:
new_range_bits = 1;
break;
case 8:
new_range_bits = 0;
break;
default:
return -EINVAL;
}
mutex_lock(&data->update_lock);
status = i2c_smbus_read_byte_data(client, REG_FAN_CONF1);
if (status < 0) {
dev_dbg(&client->dev, "reg 0x%02x, err %d\n",
REG_FAN_CONF1, status);
mutex_unlock(&data->update_lock);
return -EIO;
}
status &= 0x9F;
status |= (new_range_bits << 5);
i2c_smbus_write_byte_data(client, REG_FAN_CONF1, status);
data->fan_multiplier = 8 / new_div;
/* update fan target if high byte is not disabled */
if ((data->fan_target & 0x1fe0) != 0x1fe0) {
u16 new_target = (data->fan_target * old_div) / new_div;
data->fan_target = min(new_target, (u16)0x1fff);
write_fan_target_to_i2c(client, data->fan_target);
}
/* invalidate data to force re-read from hardware */
data->valid = false;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t
show_fan_target(struct device *dev, struct device_attribute *da, char *buf)
{
struct emc2103_data *data = emc2103_update_device(dev);
int rpm = 0;
/* high byte of 0xff indicates disabled so return 0 */
if ((data->fan_target != 0) && ((data->fan_target & 0x1fe0) != 0x1fe0))
rpm = (FAN_RPM_FACTOR * data->fan_multiplier)
/ data->fan_target;
return sprintf(buf, "%d\n", rpm);
}
static ssize_t set_fan_target(struct device *dev, struct device_attribute *da,
const char *buf, size_t count)
{
struct emc2103_data *data = emc2103_update_device(dev);
struct i2c_client *client = to_i2c_client(dev);
long rpm_target;
int result = kstrtol(buf, 10, &rpm_target);
if (result < 0)
return -EINVAL;
/* Datasheet states 16384 as maximum RPM target (table 3.2) */
if ((rpm_target < 0) || (rpm_target > 16384))
return -EINVAL;
mutex_lock(&data->update_lock);
if (rpm_target == 0)
data->fan_target = 0x1fff;
else
data->fan_target = SENSORS_LIMIT(
(FAN_RPM_FACTOR * data->fan_multiplier) / rpm_target,
0, 0x1fff);
write_fan_target_to_i2c(client, data->fan_target);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t
show_fan_fault(struct device *dev, struct device_attribute *da, char *buf)
{
struct emc2103_data *data = emc2103_update_device(dev);
bool fault = ((data->fan_tach & 0x1fe0) == 0x1fe0);
return sprintf(buf, "%d\n", fault ? 1 : 0);
}
static ssize_t
show_pwm_enable(struct device *dev, struct device_attribute *da, char *buf)
{
struct emc2103_data *data = emc2103_update_device(dev);
return sprintf(buf, "%d\n", data->fan_rpm_control ? 3 : 0);
}
static ssize_t set_pwm_enable(struct device *dev, struct device_attribute *da,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct emc2103_data *data = i2c_get_clientdata(client);
long new_value;
u8 conf_reg;
int result = kstrtol(buf, 10, &new_value);
if (result < 0)
return -EINVAL;
mutex_lock(&data->update_lock);
switch (new_value) {
case 0:
data->fan_rpm_control = false;
break;
case 3:
data->fan_rpm_control = true;
break;
default:
mutex_unlock(&data->update_lock);
return -EINVAL;
}
read_u8_from_i2c(client, REG_FAN_CONF1, &conf_reg);
if (data->fan_rpm_control)
conf_reg |= 0x80;
else
conf_reg &= ~0x80;
i2c_smbus_write_byte_data(client, REG_FAN_CONF1, conf_reg);
mutex_unlock(&data->update_lock);
return count;
}
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_temp, NULL, 0);
static SENSOR_DEVICE_ATTR(temp1_min, S_IRUGO | S_IWUSR, show_temp_min,
set_temp_min, 0);
static SENSOR_DEVICE_ATTR(temp1_max, S_IRUGO | S_IWUSR, show_temp_max,
set_temp_max, 0);
static SENSOR_DEVICE_ATTR(temp1_fault, S_IRUGO, show_temp_fault, NULL, 0);
static SENSOR_DEVICE_ATTR(temp1_min_alarm, S_IRUGO, show_temp_min_alarm,
NULL, 0);
static SENSOR_DEVICE_ATTR(temp1_max_alarm, S_IRUGO, show_temp_max_alarm,
NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_input, S_IRUGO, show_temp, NULL, 1);
static SENSOR_DEVICE_ATTR(temp2_min, S_IRUGO | S_IWUSR, show_temp_min,
set_temp_min, 1);
static SENSOR_DEVICE_ATTR(temp2_max, S_IRUGO | S_IWUSR, show_temp_max,
set_temp_max, 1);
static SENSOR_DEVICE_ATTR(temp2_fault, S_IRUGO, show_temp_fault, NULL, 1);
static SENSOR_DEVICE_ATTR(temp2_min_alarm, S_IRUGO, show_temp_min_alarm,
NULL, 1);
static SENSOR_DEVICE_ATTR(temp2_max_alarm, S_IRUGO, show_temp_max_alarm,
NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_input, S_IRUGO, show_temp, NULL, 2);
static SENSOR_DEVICE_ATTR(temp3_min, S_IRUGO | S_IWUSR, show_temp_min,
set_temp_min, 2);
static SENSOR_DEVICE_ATTR(temp3_max, S_IRUGO | S_IWUSR, show_temp_max,
set_temp_max, 2);
static SENSOR_DEVICE_ATTR(temp3_fault, S_IRUGO, show_temp_fault, NULL, 2);
static SENSOR_DEVICE_ATTR(temp3_min_alarm, S_IRUGO, show_temp_min_alarm,
NULL, 2);
static SENSOR_DEVICE_ATTR(temp3_max_alarm, S_IRUGO, show_temp_max_alarm,
NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_input, S_IRUGO, show_temp, NULL, 3);
static SENSOR_DEVICE_ATTR(temp4_min, S_IRUGO | S_IWUSR, show_temp_min,
set_temp_min, 3);
static SENSOR_DEVICE_ATTR(temp4_max, S_IRUGO | S_IWUSR, show_temp_max,
set_temp_max, 3);
static SENSOR_DEVICE_ATTR(temp4_fault, S_IRUGO, show_temp_fault, NULL, 3);
static SENSOR_DEVICE_ATTR(temp4_min_alarm, S_IRUGO, show_temp_min_alarm,
NULL, 3);
static SENSOR_DEVICE_ATTR(temp4_max_alarm, S_IRUGO, show_temp_max_alarm,
NULL, 3);
static DEVICE_ATTR(fan1_input, S_IRUGO, show_fan, NULL);
static DEVICE_ATTR(fan1_div, S_IRUGO | S_IWUSR, show_fan_div, set_fan_div);
static DEVICE_ATTR(fan1_target, S_IRUGO | S_IWUSR, show_fan_target,
set_fan_target);
static DEVICE_ATTR(fan1_fault, S_IRUGO, show_fan_fault, NULL);
static DEVICE_ATTR(pwm1_enable, S_IRUGO | S_IWUSR, show_pwm_enable,
set_pwm_enable);
/* sensors present on all models */
static struct attribute *emc2103_attributes[] = {
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp1_min.dev_attr.attr,
&sensor_dev_attr_temp1_max.dev_attr.attr,
&sensor_dev_attr_temp1_fault.dev_attr.attr,
&sensor_dev_attr_temp1_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_max_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_input.dev_attr.attr,
&sensor_dev_attr_temp2_min.dev_attr.attr,
&sensor_dev_attr_temp2_max.dev_attr.attr,
&sensor_dev_attr_temp2_fault.dev_attr.attr,
&sensor_dev_attr_temp2_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_max_alarm.dev_attr.attr,
&dev_attr_fan1_input.attr,
&dev_attr_fan1_div.attr,
&dev_attr_fan1_target.attr,
&dev_attr_fan1_fault.attr,
&dev_attr_pwm1_enable.attr,
NULL
};
/* extra temperature sensors only present on 2103-2 and 2103-4 */
static struct attribute *emc2103_attributes_temp3[] = {
&sensor_dev_attr_temp3_input.dev_attr.attr,
&sensor_dev_attr_temp3_min.dev_attr.attr,
&sensor_dev_attr_temp3_max.dev_attr.attr,
&sensor_dev_attr_temp3_fault.dev_attr.attr,
&sensor_dev_attr_temp3_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp3_max_alarm.dev_attr.attr,
NULL
};
/* extra temperature sensors only present on 2103-2 and 2103-4 in APD mode */
static struct attribute *emc2103_attributes_temp4[] = {
&sensor_dev_attr_temp4_input.dev_attr.attr,
&sensor_dev_attr_temp4_min.dev_attr.attr,
&sensor_dev_attr_temp4_max.dev_attr.attr,
&sensor_dev_attr_temp4_fault.dev_attr.attr,
&sensor_dev_attr_temp4_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp4_max_alarm.dev_attr.attr,
NULL
};
static const struct attribute_group emc2103_group = {
.attrs = emc2103_attributes,
};
static const struct attribute_group emc2103_temp3_group = {
.attrs = emc2103_attributes_temp3,
};
static const struct attribute_group emc2103_temp4_group = {
.attrs = emc2103_attributes_temp4,
};
static int
emc2103_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
struct emc2103_data *data;
int status;
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -EIO;
data = kzalloc(sizeof(struct emc2103_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
i2c_set_clientdata(client, data);
mutex_init(&data->update_lock);
/* 2103-2 and 2103-4 have 3 external diodes, 2103-1 has 1 */
status = i2c_smbus_read_byte_data(client, REG_PRODUCT_ID);
if (status == 0x24) {
/* 2103-1 only has 1 external diode */
data->temp_count = 2;
} else {
/* 2103-2 and 2103-4 have 3 or 4 external diodes */
status = i2c_smbus_read_byte_data(client, REG_CONF1);
if (status < 0) {
dev_dbg(&client->dev, "reg 0x%02x, err %d\n", REG_CONF1,
status);
goto exit_free;
}
/* detect current state of hardware */
data->temp_count = (status & 0x01) ? 4 : 3;
/* force APD state if module parameter is set */
if (apd == 0) {
/* force APD mode off */
data->temp_count = 3;
status &= ~(0x01);
i2c_smbus_write_byte_data(client, REG_CONF1, status);
} else if (apd == 1) {
/* force APD mode on */
data->temp_count = 4;
status |= 0x01;
i2c_smbus_write_byte_data(client, REG_CONF1, status);
}
}
/* Register sysfs hooks */
status = sysfs_create_group(&client->dev.kobj, &emc2103_group);
if (status)
goto exit_free;
if (data->temp_count >= 3) {
status = sysfs_create_group(&client->dev.kobj,
&emc2103_temp3_group);
if (status)
goto exit_remove;
}
if (data->temp_count == 4) {
status = sysfs_create_group(&client->dev.kobj,
&emc2103_temp4_group);
if (status)
goto exit_remove_temp3;
}
data->hwmon_dev = hwmon_device_register(&client->dev);
if (IS_ERR(data->hwmon_dev)) {
status = PTR_ERR(data->hwmon_dev);
goto exit_remove_temp4;
}
dev_info(&client->dev, "%s: sensor '%s'\n",
dev_name(data->hwmon_dev), client->name);
return 0;
exit_remove_temp4:
if (data->temp_count == 4)
sysfs_remove_group(&client->dev.kobj, &emc2103_temp4_group);
exit_remove_temp3:
if (data->temp_count >= 3)
sysfs_remove_group(&client->dev.kobj, &emc2103_temp3_group);
exit_remove:
sysfs_remove_group(&client->dev.kobj, &emc2103_group);
exit_free:
kfree(data);
return status;
}
static int emc2103_remove(struct i2c_client *client)
{
struct emc2103_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
if (data->temp_count == 4)
sysfs_remove_group(&client->dev.kobj, &emc2103_temp4_group);
if (data->temp_count >= 3)
sysfs_remove_group(&client->dev.kobj, &emc2103_temp3_group);
sysfs_remove_group(&client->dev.kobj, &emc2103_group);
kfree(data);
return 0;
}
static const struct i2c_device_id emc2103_ids[] = {
{ "emc2103", 0, },
{ /* LIST END */ }
};
MODULE_DEVICE_TABLE(i2c, emc2103_ids);
/* Return 0 if detection is successful, -ENODEV otherwise */
static int
emc2103_detect(struct i2c_client *new_client, struct i2c_board_info *info)
{
struct i2c_adapter *adapter = new_client->adapter;
int manufacturer, product;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
manufacturer = i2c_smbus_read_byte_data(new_client, REG_MFG_ID);
if (manufacturer != 0x5D)
return -ENODEV;
product = i2c_smbus_read_byte_data(new_client, REG_PRODUCT_ID);
if ((product != 0x24) && (product != 0x26))
return -ENODEV;
strlcpy(info->type, "emc2103", I2C_NAME_SIZE);
return 0;
}
static struct i2c_driver emc2103_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "emc2103",
},
.probe = emc2103_probe,
.remove = emc2103_remove,
.id_table = emc2103_ids,
.detect = emc2103_detect,
.address_list = normal_i2c,
};
module_i2c_driver(emc2103_driver);
MODULE_AUTHOR("Steve Glendinning <steve.glendinning@smsc.com>");
MODULE_DESCRIPTION("SMSC EMC2103 hwmon driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
mrjaydee82/SinLessKerne1-m8-4.4.4 | drivers/hwmon/emc2103.c | 4816 | 21123 | /*
* emc2103.c - Support for SMSC EMC2103
* Copyright (c) 2010 SMSC
*
* 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/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
/* Addresses scanned */
static const unsigned short normal_i2c[] = { 0x2E, I2C_CLIENT_END };
static const u8 REG_TEMP[4] = { 0x00, 0x02, 0x04, 0x06 };
static const u8 REG_TEMP_MIN[4] = { 0x3c, 0x38, 0x39, 0x3a };
static const u8 REG_TEMP_MAX[4] = { 0x34, 0x30, 0x31, 0x32 };
#define REG_CONF1 0x20
#define REG_TEMP_MAX_ALARM 0x24
#define REG_TEMP_MIN_ALARM 0x25
#define REG_FAN_CONF1 0x42
#define REG_FAN_TARGET_LO 0x4c
#define REG_FAN_TARGET_HI 0x4d
#define REG_FAN_TACH_HI 0x4e
#define REG_FAN_TACH_LO 0x4f
#define REG_PRODUCT_ID 0xfd
#define REG_MFG_ID 0xfe
/* equation 4 from datasheet: rpm = (3932160 * multipler) / count */
#define FAN_RPM_FACTOR 3932160
/*
* 2103-2 and 2103-4's 3rd temperature sensor can be connected to two diodes
* in anti-parallel mode, and in this configuration both can be read
* independently (so we have 4 temperature inputs). The device can't
* detect if it's connected in this mode, so we have to manually enable
* it. Default is to leave the device in the state it's already in (-1).
* This parameter allows APD mode to be optionally forced on or off
*/
static int apd = -1;
module_param(apd, bint, 0);
MODULE_PARM_DESC(init, "Set to zero to disable anti-parallel diode mode");
struct temperature {
s8 degrees;
u8 fraction; /* 0-7 multiples of 0.125 */
};
struct emc2103_data {
struct device *hwmon_dev;
struct mutex update_lock;
bool valid; /* registers are valid */
bool fan_rpm_control;
int temp_count; /* num of temp sensors */
unsigned long last_updated; /* in jiffies */
struct temperature temp[4]; /* internal + 3 external */
s8 temp_min[4]; /* no fractional part */
s8 temp_max[4]; /* no fractional part */
u8 temp_min_alarm;
u8 temp_max_alarm;
u8 fan_multiplier;
u16 fan_tach;
u16 fan_target;
};
static int read_u8_from_i2c(struct i2c_client *client, u8 i2c_reg, u8 *output)
{
int status = i2c_smbus_read_byte_data(client, i2c_reg);
if (status < 0) {
dev_warn(&client->dev, "reg 0x%02x, err %d\n",
i2c_reg, status);
} else {
*output = status;
}
return status;
}
static void read_temp_from_i2c(struct i2c_client *client, u8 i2c_reg,
struct temperature *temp)
{
u8 degrees, fractional;
if (read_u8_from_i2c(client, i2c_reg, °rees) < 0)
return;
if (read_u8_from_i2c(client, i2c_reg + 1, &fractional) < 0)
return;
temp->degrees = degrees;
temp->fraction = (fractional & 0xe0) >> 5;
}
static void read_fan_from_i2c(struct i2c_client *client, u16 *output,
u8 hi_addr, u8 lo_addr)
{
u8 high_byte, lo_byte;
if (read_u8_from_i2c(client, hi_addr, &high_byte) < 0)
return;
if (read_u8_from_i2c(client, lo_addr, &lo_byte) < 0)
return;
*output = ((u16)high_byte << 5) | (lo_byte >> 3);
}
static void write_fan_target_to_i2c(struct i2c_client *client, u16 new_target)
{
u8 high_byte = (new_target & 0x1fe0) >> 5;
u8 low_byte = (new_target & 0x001f) << 3;
i2c_smbus_write_byte_data(client, REG_FAN_TARGET_LO, low_byte);
i2c_smbus_write_byte_data(client, REG_FAN_TARGET_HI, high_byte);
}
static void read_fan_config_from_i2c(struct i2c_client *client)
{
struct emc2103_data *data = i2c_get_clientdata(client);
u8 conf1;
if (read_u8_from_i2c(client, REG_FAN_CONF1, &conf1) < 0)
return;
data->fan_multiplier = 1 << ((conf1 & 0x60) >> 5);
data->fan_rpm_control = (conf1 & 0x80) != 0;
}
static struct emc2103_data *emc2103_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct emc2103_data *data = i2c_get_clientdata(client);
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ + HZ / 2)
|| !data->valid) {
int i;
for (i = 0; i < data->temp_count; i++) {
read_temp_from_i2c(client, REG_TEMP[i], &data->temp[i]);
read_u8_from_i2c(client, REG_TEMP_MIN[i],
&data->temp_min[i]);
read_u8_from_i2c(client, REG_TEMP_MAX[i],
&data->temp_max[i]);
}
read_u8_from_i2c(client, REG_TEMP_MIN_ALARM,
&data->temp_min_alarm);
read_u8_from_i2c(client, REG_TEMP_MAX_ALARM,
&data->temp_max_alarm);
read_fan_from_i2c(client, &data->fan_tach,
REG_FAN_TACH_HI, REG_FAN_TACH_LO);
read_fan_from_i2c(client, &data->fan_target,
REG_FAN_TARGET_HI, REG_FAN_TARGET_LO);
read_fan_config_from_i2c(client);
data->last_updated = jiffies;
data->valid = true;
}
mutex_unlock(&data->update_lock);
return data;
}
static ssize_t
show_temp(struct device *dev, struct device_attribute *da, char *buf)
{
int nr = to_sensor_dev_attr(da)->index;
struct emc2103_data *data = emc2103_update_device(dev);
int millidegrees = data->temp[nr].degrees * 1000
+ data->temp[nr].fraction * 125;
return sprintf(buf, "%d\n", millidegrees);
}
static ssize_t
show_temp_min(struct device *dev, struct device_attribute *da, char *buf)
{
int nr = to_sensor_dev_attr(da)->index;
struct emc2103_data *data = emc2103_update_device(dev);
int millidegrees = data->temp_min[nr] * 1000;
return sprintf(buf, "%d\n", millidegrees);
}
static ssize_t
show_temp_max(struct device *dev, struct device_attribute *da, char *buf)
{
int nr = to_sensor_dev_attr(da)->index;
struct emc2103_data *data = emc2103_update_device(dev);
int millidegrees = data->temp_max[nr] * 1000;
return sprintf(buf, "%d\n", millidegrees);
}
static ssize_t
show_temp_fault(struct device *dev, struct device_attribute *da, char *buf)
{
int nr = to_sensor_dev_attr(da)->index;
struct emc2103_data *data = emc2103_update_device(dev);
bool fault = (data->temp[nr].degrees == -128);
return sprintf(buf, "%d\n", fault ? 1 : 0);
}
static ssize_t
show_temp_min_alarm(struct device *dev, struct device_attribute *da, char *buf)
{
int nr = to_sensor_dev_attr(da)->index;
struct emc2103_data *data = emc2103_update_device(dev);
bool alarm = data->temp_min_alarm & (1 << nr);
return sprintf(buf, "%d\n", alarm ? 1 : 0);
}
static ssize_t
show_temp_max_alarm(struct device *dev, struct device_attribute *da, char *buf)
{
int nr = to_sensor_dev_attr(da)->index;
struct emc2103_data *data = emc2103_update_device(dev);
bool alarm = data->temp_max_alarm & (1 << nr);
return sprintf(buf, "%d\n", alarm ? 1 : 0);
}
static ssize_t set_temp_min(struct device *dev, struct device_attribute *da,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(da)->index;
struct i2c_client *client = to_i2c_client(dev);
struct emc2103_data *data = i2c_get_clientdata(client);
long val;
int result = kstrtol(buf, 10, &val);
if (result < 0)
return -EINVAL;
val = DIV_ROUND_CLOSEST(val, 1000);
if ((val < -63) || (val > 127))
return -EINVAL;
mutex_lock(&data->update_lock);
data->temp_min[nr] = val;
i2c_smbus_write_byte_data(client, REG_TEMP_MIN[nr], val);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t set_temp_max(struct device *dev, struct device_attribute *da,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(da)->index;
struct i2c_client *client = to_i2c_client(dev);
struct emc2103_data *data = i2c_get_clientdata(client);
long val;
int result = kstrtol(buf, 10, &val);
if (result < 0)
return -EINVAL;
val = DIV_ROUND_CLOSEST(val, 1000);
if ((val < -63) || (val > 127))
return -EINVAL;
mutex_lock(&data->update_lock);
data->temp_max[nr] = val;
i2c_smbus_write_byte_data(client, REG_TEMP_MAX[nr], val);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t
show_fan(struct device *dev, struct device_attribute *da, char *buf)
{
struct emc2103_data *data = emc2103_update_device(dev);
int rpm = 0;
if (data->fan_tach != 0)
rpm = (FAN_RPM_FACTOR * data->fan_multiplier) / data->fan_tach;
return sprintf(buf, "%d\n", rpm);
}
static ssize_t
show_fan_div(struct device *dev, struct device_attribute *da, char *buf)
{
struct emc2103_data *data = emc2103_update_device(dev);
int fan_div = 8 / data->fan_multiplier;
return sprintf(buf, "%d\n", fan_div);
}
/*
* Note: we also update the fan target here, because its value is
* determined in part by the fan clock divider. This follows the principle
* of least surprise; the user doesn't expect the fan target to change just
* because the divider changed.
*/
static ssize_t set_fan_div(struct device *dev, struct device_attribute *da,
const char *buf, size_t count)
{
struct emc2103_data *data = emc2103_update_device(dev);
struct i2c_client *client = to_i2c_client(dev);
int new_range_bits, old_div = 8 / data->fan_multiplier;
long new_div;
int status = kstrtol(buf, 10, &new_div);
if (status < 0)
return -EINVAL;
if (new_div == old_div) /* No change */
return count;
switch (new_div) {
case 1:
new_range_bits = 3;
break;
case 2:
new_range_bits = 2;
break;
case 4:
new_range_bits = 1;
break;
case 8:
new_range_bits = 0;
break;
default:
return -EINVAL;
}
mutex_lock(&data->update_lock);
status = i2c_smbus_read_byte_data(client, REG_FAN_CONF1);
if (status < 0) {
dev_dbg(&client->dev, "reg 0x%02x, err %d\n",
REG_FAN_CONF1, status);
mutex_unlock(&data->update_lock);
return -EIO;
}
status &= 0x9F;
status |= (new_range_bits << 5);
i2c_smbus_write_byte_data(client, REG_FAN_CONF1, status);
data->fan_multiplier = 8 / new_div;
/* update fan target if high byte is not disabled */
if ((data->fan_target & 0x1fe0) != 0x1fe0) {
u16 new_target = (data->fan_target * old_div) / new_div;
data->fan_target = min(new_target, (u16)0x1fff);
write_fan_target_to_i2c(client, data->fan_target);
}
/* invalidate data to force re-read from hardware */
data->valid = false;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t
show_fan_target(struct device *dev, struct device_attribute *da, char *buf)
{
struct emc2103_data *data = emc2103_update_device(dev);
int rpm = 0;
/* high byte of 0xff indicates disabled so return 0 */
if ((data->fan_target != 0) && ((data->fan_target & 0x1fe0) != 0x1fe0))
rpm = (FAN_RPM_FACTOR * data->fan_multiplier)
/ data->fan_target;
return sprintf(buf, "%d\n", rpm);
}
static ssize_t set_fan_target(struct device *dev, struct device_attribute *da,
const char *buf, size_t count)
{
struct emc2103_data *data = emc2103_update_device(dev);
struct i2c_client *client = to_i2c_client(dev);
long rpm_target;
int result = kstrtol(buf, 10, &rpm_target);
if (result < 0)
return -EINVAL;
/* Datasheet states 16384 as maximum RPM target (table 3.2) */
if ((rpm_target < 0) || (rpm_target > 16384))
return -EINVAL;
mutex_lock(&data->update_lock);
if (rpm_target == 0)
data->fan_target = 0x1fff;
else
data->fan_target = SENSORS_LIMIT(
(FAN_RPM_FACTOR * data->fan_multiplier) / rpm_target,
0, 0x1fff);
write_fan_target_to_i2c(client, data->fan_target);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t
show_fan_fault(struct device *dev, struct device_attribute *da, char *buf)
{
struct emc2103_data *data = emc2103_update_device(dev);
bool fault = ((data->fan_tach & 0x1fe0) == 0x1fe0);
return sprintf(buf, "%d\n", fault ? 1 : 0);
}
static ssize_t
show_pwm_enable(struct device *dev, struct device_attribute *da, char *buf)
{
struct emc2103_data *data = emc2103_update_device(dev);
return sprintf(buf, "%d\n", data->fan_rpm_control ? 3 : 0);
}
static ssize_t set_pwm_enable(struct device *dev, struct device_attribute *da,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct emc2103_data *data = i2c_get_clientdata(client);
long new_value;
u8 conf_reg;
int result = kstrtol(buf, 10, &new_value);
if (result < 0)
return -EINVAL;
mutex_lock(&data->update_lock);
switch (new_value) {
case 0:
data->fan_rpm_control = false;
break;
case 3:
data->fan_rpm_control = true;
break;
default:
mutex_unlock(&data->update_lock);
return -EINVAL;
}
read_u8_from_i2c(client, REG_FAN_CONF1, &conf_reg);
if (data->fan_rpm_control)
conf_reg |= 0x80;
else
conf_reg &= ~0x80;
i2c_smbus_write_byte_data(client, REG_FAN_CONF1, conf_reg);
mutex_unlock(&data->update_lock);
return count;
}
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_temp, NULL, 0);
static SENSOR_DEVICE_ATTR(temp1_min, S_IRUGO | S_IWUSR, show_temp_min,
set_temp_min, 0);
static SENSOR_DEVICE_ATTR(temp1_max, S_IRUGO | S_IWUSR, show_temp_max,
set_temp_max, 0);
static SENSOR_DEVICE_ATTR(temp1_fault, S_IRUGO, show_temp_fault, NULL, 0);
static SENSOR_DEVICE_ATTR(temp1_min_alarm, S_IRUGO, show_temp_min_alarm,
NULL, 0);
static SENSOR_DEVICE_ATTR(temp1_max_alarm, S_IRUGO, show_temp_max_alarm,
NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_input, S_IRUGO, show_temp, NULL, 1);
static SENSOR_DEVICE_ATTR(temp2_min, S_IRUGO | S_IWUSR, show_temp_min,
set_temp_min, 1);
static SENSOR_DEVICE_ATTR(temp2_max, S_IRUGO | S_IWUSR, show_temp_max,
set_temp_max, 1);
static SENSOR_DEVICE_ATTR(temp2_fault, S_IRUGO, show_temp_fault, NULL, 1);
static SENSOR_DEVICE_ATTR(temp2_min_alarm, S_IRUGO, show_temp_min_alarm,
NULL, 1);
static SENSOR_DEVICE_ATTR(temp2_max_alarm, S_IRUGO, show_temp_max_alarm,
NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_input, S_IRUGO, show_temp, NULL, 2);
static SENSOR_DEVICE_ATTR(temp3_min, S_IRUGO | S_IWUSR, show_temp_min,
set_temp_min, 2);
static SENSOR_DEVICE_ATTR(temp3_max, S_IRUGO | S_IWUSR, show_temp_max,
set_temp_max, 2);
static SENSOR_DEVICE_ATTR(temp3_fault, S_IRUGO, show_temp_fault, NULL, 2);
static SENSOR_DEVICE_ATTR(temp3_min_alarm, S_IRUGO, show_temp_min_alarm,
NULL, 2);
static SENSOR_DEVICE_ATTR(temp3_max_alarm, S_IRUGO, show_temp_max_alarm,
NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_input, S_IRUGO, show_temp, NULL, 3);
static SENSOR_DEVICE_ATTR(temp4_min, S_IRUGO | S_IWUSR, show_temp_min,
set_temp_min, 3);
static SENSOR_DEVICE_ATTR(temp4_max, S_IRUGO | S_IWUSR, show_temp_max,
set_temp_max, 3);
static SENSOR_DEVICE_ATTR(temp4_fault, S_IRUGO, show_temp_fault, NULL, 3);
static SENSOR_DEVICE_ATTR(temp4_min_alarm, S_IRUGO, show_temp_min_alarm,
NULL, 3);
static SENSOR_DEVICE_ATTR(temp4_max_alarm, S_IRUGO, show_temp_max_alarm,
NULL, 3);
static DEVICE_ATTR(fan1_input, S_IRUGO, show_fan, NULL);
static DEVICE_ATTR(fan1_div, S_IRUGO | S_IWUSR, show_fan_div, set_fan_div);
static DEVICE_ATTR(fan1_target, S_IRUGO | S_IWUSR, show_fan_target,
set_fan_target);
static DEVICE_ATTR(fan1_fault, S_IRUGO, show_fan_fault, NULL);
static DEVICE_ATTR(pwm1_enable, S_IRUGO | S_IWUSR, show_pwm_enable,
set_pwm_enable);
/* sensors present on all models */
static struct attribute *emc2103_attributes[] = {
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp1_min.dev_attr.attr,
&sensor_dev_attr_temp1_max.dev_attr.attr,
&sensor_dev_attr_temp1_fault.dev_attr.attr,
&sensor_dev_attr_temp1_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_max_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_input.dev_attr.attr,
&sensor_dev_attr_temp2_min.dev_attr.attr,
&sensor_dev_attr_temp2_max.dev_attr.attr,
&sensor_dev_attr_temp2_fault.dev_attr.attr,
&sensor_dev_attr_temp2_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_max_alarm.dev_attr.attr,
&dev_attr_fan1_input.attr,
&dev_attr_fan1_div.attr,
&dev_attr_fan1_target.attr,
&dev_attr_fan1_fault.attr,
&dev_attr_pwm1_enable.attr,
NULL
};
/* extra temperature sensors only present on 2103-2 and 2103-4 */
static struct attribute *emc2103_attributes_temp3[] = {
&sensor_dev_attr_temp3_input.dev_attr.attr,
&sensor_dev_attr_temp3_min.dev_attr.attr,
&sensor_dev_attr_temp3_max.dev_attr.attr,
&sensor_dev_attr_temp3_fault.dev_attr.attr,
&sensor_dev_attr_temp3_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp3_max_alarm.dev_attr.attr,
NULL
};
/* extra temperature sensors only present on 2103-2 and 2103-4 in APD mode */
static struct attribute *emc2103_attributes_temp4[] = {
&sensor_dev_attr_temp4_input.dev_attr.attr,
&sensor_dev_attr_temp4_min.dev_attr.attr,
&sensor_dev_attr_temp4_max.dev_attr.attr,
&sensor_dev_attr_temp4_fault.dev_attr.attr,
&sensor_dev_attr_temp4_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp4_max_alarm.dev_attr.attr,
NULL
};
static const struct attribute_group emc2103_group = {
.attrs = emc2103_attributes,
};
static const struct attribute_group emc2103_temp3_group = {
.attrs = emc2103_attributes_temp3,
};
static const struct attribute_group emc2103_temp4_group = {
.attrs = emc2103_attributes_temp4,
};
static int
emc2103_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
struct emc2103_data *data;
int status;
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -EIO;
data = kzalloc(sizeof(struct emc2103_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
i2c_set_clientdata(client, data);
mutex_init(&data->update_lock);
/* 2103-2 and 2103-4 have 3 external diodes, 2103-1 has 1 */
status = i2c_smbus_read_byte_data(client, REG_PRODUCT_ID);
if (status == 0x24) {
/* 2103-1 only has 1 external diode */
data->temp_count = 2;
} else {
/* 2103-2 and 2103-4 have 3 or 4 external diodes */
status = i2c_smbus_read_byte_data(client, REG_CONF1);
if (status < 0) {
dev_dbg(&client->dev, "reg 0x%02x, err %d\n", REG_CONF1,
status);
goto exit_free;
}
/* detect current state of hardware */
data->temp_count = (status & 0x01) ? 4 : 3;
/* force APD state if module parameter is set */
if (apd == 0) {
/* force APD mode off */
data->temp_count = 3;
status &= ~(0x01);
i2c_smbus_write_byte_data(client, REG_CONF1, status);
} else if (apd == 1) {
/* force APD mode on */
data->temp_count = 4;
status |= 0x01;
i2c_smbus_write_byte_data(client, REG_CONF1, status);
}
}
/* Register sysfs hooks */
status = sysfs_create_group(&client->dev.kobj, &emc2103_group);
if (status)
goto exit_free;
if (data->temp_count >= 3) {
status = sysfs_create_group(&client->dev.kobj,
&emc2103_temp3_group);
if (status)
goto exit_remove;
}
if (data->temp_count == 4) {
status = sysfs_create_group(&client->dev.kobj,
&emc2103_temp4_group);
if (status)
goto exit_remove_temp3;
}
data->hwmon_dev = hwmon_device_register(&client->dev);
if (IS_ERR(data->hwmon_dev)) {
status = PTR_ERR(data->hwmon_dev);
goto exit_remove_temp4;
}
dev_info(&client->dev, "%s: sensor '%s'\n",
dev_name(data->hwmon_dev), client->name);
return 0;
exit_remove_temp4:
if (data->temp_count == 4)
sysfs_remove_group(&client->dev.kobj, &emc2103_temp4_group);
exit_remove_temp3:
if (data->temp_count >= 3)
sysfs_remove_group(&client->dev.kobj, &emc2103_temp3_group);
exit_remove:
sysfs_remove_group(&client->dev.kobj, &emc2103_group);
exit_free:
kfree(data);
return status;
}
static int emc2103_remove(struct i2c_client *client)
{
struct emc2103_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
if (data->temp_count == 4)
sysfs_remove_group(&client->dev.kobj, &emc2103_temp4_group);
if (data->temp_count >= 3)
sysfs_remove_group(&client->dev.kobj, &emc2103_temp3_group);
sysfs_remove_group(&client->dev.kobj, &emc2103_group);
kfree(data);
return 0;
}
static const struct i2c_device_id emc2103_ids[] = {
{ "emc2103", 0, },
{ /* LIST END */ }
};
MODULE_DEVICE_TABLE(i2c, emc2103_ids);
/* Return 0 if detection is successful, -ENODEV otherwise */
static int
emc2103_detect(struct i2c_client *new_client, struct i2c_board_info *info)
{
struct i2c_adapter *adapter = new_client->adapter;
int manufacturer, product;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
manufacturer = i2c_smbus_read_byte_data(new_client, REG_MFG_ID);
if (manufacturer != 0x5D)
return -ENODEV;
product = i2c_smbus_read_byte_data(new_client, REG_PRODUCT_ID);
if ((product != 0x24) && (product != 0x26))
return -ENODEV;
strlcpy(info->type, "emc2103", I2C_NAME_SIZE);
return 0;
}
static struct i2c_driver emc2103_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "emc2103",
},
.probe = emc2103_probe,
.remove = emc2103_remove,
.id_table = emc2103_ids,
.detect = emc2103_detect,
.address_list = normal_i2c,
};
module_i2c_driver(emc2103_driver);
MODULE_AUTHOR("Steve Glendinning <steve.glendinning@smsc.com>");
MODULE_DESCRIPTION("SMSC EMC2103 hwmon driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Ace-III-Dev/android_kernel_samsung_hawaii | drivers/hwmon/jc42.c | 4816 | 16289 | /*
* jc42.c - driver for Jedec JC42.4 compliant temperature sensors
*
* Copyright (c) 2010 Ericsson AB.
*
* Derived from lm77.c by Andras BALI <drewie@freemail.hu>.
*
* JC42.4 compliant temperature sensors are typically used on memory modules.
*
* 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/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
/* Addresses to scan */
static const unsigned short normal_i2c[] = {
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, I2C_CLIENT_END };
/* JC42 registers. All registers are 16 bit. */
#define JC42_REG_CAP 0x00
#define JC42_REG_CONFIG 0x01
#define JC42_REG_TEMP_UPPER 0x02
#define JC42_REG_TEMP_LOWER 0x03
#define JC42_REG_TEMP_CRITICAL 0x04
#define JC42_REG_TEMP 0x05
#define JC42_REG_MANID 0x06
#define JC42_REG_DEVICEID 0x07
/* Status bits in temperature register */
#define JC42_ALARM_CRIT_BIT 15
#define JC42_ALARM_MAX_BIT 14
#define JC42_ALARM_MIN_BIT 13
/* Configuration register defines */
#define JC42_CFG_CRIT_ONLY (1 << 2)
#define JC42_CFG_TCRIT_LOCK (1 << 6)
#define JC42_CFG_EVENT_LOCK (1 << 7)
#define JC42_CFG_SHUTDOWN (1 << 8)
#define JC42_CFG_HYST_SHIFT 9
#define JC42_CFG_HYST_MASK 0x03
/* Capabilities */
#define JC42_CAP_RANGE (1 << 2)
/* Manufacturer IDs */
#define ADT_MANID 0x11d4 /* Analog Devices */
#define ATMEL_MANID 0x001f /* Atmel */
#define MAX_MANID 0x004d /* Maxim */
#define IDT_MANID 0x00b3 /* IDT */
#define MCP_MANID 0x0054 /* Microchip */
#define NXP_MANID 0x1131 /* NXP Semiconductors */
#define ONS_MANID 0x1b09 /* ON Semiconductor */
#define STM_MANID 0x104a /* ST Microelectronics */
/* Supported chips */
/* Analog Devices */
#define ADT7408_DEVID 0x0801
#define ADT7408_DEVID_MASK 0xffff
/* Atmel */
#define AT30TS00_DEVID 0x8201
#define AT30TS00_DEVID_MASK 0xffff
/* IDT */
#define TS3000B3_DEVID 0x2903 /* Also matches TSE2002B3 */
#define TS3000B3_DEVID_MASK 0xffff
#define TS3000GB2_DEVID 0x2912 /* Also matches TSE2002GB2 */
#define TS3000GB2_DEVID_MASK 0xffff
/* Maxim */
#define MAX6604_DEVID 0x3e00
#define MAX6604_DEVID_MASK 0xffff
/* Microchip */
#define MCP9804_DEVID 0x0200
#define MCP9804_DEVID_MASK 0xfffc
#define MCP98242_DEVID 0x2000
#define MCP98242_DEVID_MASK 0xfffc
#define MCP98243_DEVID 0x2100
#define MCP98243_DEVID_MASK 0xfffc
#define MCP9843_DEVID 0x0000 /* Also matches mcp9805 */
#define MCP9843_DEVID_MASK 0xfffe
/* NXP */
#define SE97_DEVID 0xa200
#define SE97_DEVID_MASK 0xfffc
#define SE98_DEVID 0xa100
#define SE98_DEVID_MASK 0xfffc
/* ON Semiconductor */
#define CAT6095_DEVID 0x0800 /* Also matches CAT34TS02 */
#define CAT6095_DEVID_MASK 0xffe0
/* ST Microelectronics */
#define STTS424_DEVID 0x0101
#define STTS424_DEVID_MASK 0xffff
#define STTS424E_DEVID 0x0000
#define STTS424E_DEVID_MASK 0xfffe
#define STTS2002_DEVID 0x0300
#define STTS2002_DEVID_MASK 0xffff
#define STTS3000_DEVID 0x0200
#define STTS3000_DEVID_MASK 0xffff
static u16 jc42_hysteresis[] = { 0, 1500, 3000, 6000 };
struct jc42_chips {
u16 manid;
u16 devid;
u16 devid_mask;
};
static struct jc42_chips jc42_chips[] = {
{ ADT_MANID, ADT7408_DEVID, ADT7408_DEVID_MASK },
{ ATMEL_MANID, AT30TS00_DEVID, AT30TS00_DEVID_MASK },
{ IDT_MANID, TS3000B3_DEVID, TS3000B3_DEVID_MASK },
{ IDT_MANID, TS3000GB2_DEVID, TS3000GB2_DEVID_MASK },
{ MAX_MANID, MAX6604_DEVID, MAX6604_DEVID_MASK },
{ MCP_MANID, MCP9804_DEVID, MCP9804_DEVID_MASK },
{ MCP_MANID, MCP98242_DEVID, MCP98242_DEVID_MASK },
{ MCP_MANID, MCP98243_DEVID, MCP98243_DEVID_MASK },
{ MCP_MANID, MCP9843_DEVID, MCP9843_DEVID_MASK },
{ NXP_MANID, SE97_DEVID, SE97_DEVID_MASK },
{ ONS_MANID, CAT6095_DEVID, CAT6095_DEVID_MASK },
{ NXP_MANID, SE98_DEVID, SE98_DEVID_MASK },
{ STM_MANID, STTS424_DEVID, STTS424_DEVID_MASK },
{ STM_MANID, STTS424E_DEVID, STTS424E_DEVID_MASK },
{ STM_MANID, STTS2002_DEVID, STTS2002_DEVID_MASK },
{ STM_MANID, STTS3000_DEVID, STTS3000_DEVID_MASK },
};
/* Each client has this additional data */
struct jc42_data {
struct device *hwmon_dev;
struct mutex update_lock; /* protect register access */
bool extended; /* true if extended range supported */
bool valid;
unsigned long last_updated; /* In jiffies */
u16 orig_config; /* original configuration */
u16 config; /* current configuration */
u16 temp_input; /* Temperatures */
u16 temp_crit;
u16 temp_min;
u16 temp_max;
};
static int jc42_probe(struct i2c_client *client,
const struct i2c_device_id *id);
static int jc42_detect(struct i2c_client *client, struct i2c_board_info *info);
static int jc42_remove(struct i2c_client *client);
static struct jc42_data *jc42_update_device(struct device *dev);
static const struct i2c_device_id jc42_id[] = {
{ "jc42", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, jc42_id);
#ifdef CONFIG_PM
static int jc42_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct jc42_data *data = i2c_get_clientdata(client);
data->config |= JC42_CFG_SHUTDOWN;
i2c_smbus_write_word_swapped(client, JC42_REG_CONFIG, data->config);
return 0;
}
static int jc42_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct jc42_data *data = i2c_get_clientdata(client);
data->config &= ~JC42_CFG_SHUTDOWN;
i2c_smbus_write_word_swapped(client, JC42_REG_CONFIG, data->config);
return 0;
}
static const struct dev_pm_ops jc42_dev_pm_ops = {
.suspend = jc42_suspend,
.resume = jc42_resume,
};
#define JC42_DEV_PM_OPS (&jc42_dev_pm_ops)
#else
#define JC42_DEV_PM_OPS NULL
#endif /* CONFIG_PM */
/* This is the driver that will be inserted */
static struct i2c_driver jc42_driver = {
.class = I2C_CLASS_SPD,
.driver = {
.name = "jc42",
.pm = JC42_DEV_PM_OPS,
},
.probe = jc42_probe,
.remove = jc42_remove,
.id_table = jc42_id,
.detect = jc42_detect,
.address_list = normal_i2c,
};
#define JC42_TEMP_MIN_EXTENDED (-40000)
#define JC42_TEMP_MIN 0
#define JC42_TEMP_MAX 125000
static u16 jc42_temp_to_reg(int temp, bool extended)
{
int ntemp = SENSORS_LIMIT(temp,
extended ? JC42_TEMP_MIN_EXTENDED :
JC42_TEMP_MIN, JC42_TEMP_MAX);
/* convert from 0.001 to 0.0625 resolution */
return (ntemp * 2 / 125) & 0x1fff;
}
static int jc42_temp_from_reg(s16 reg)
{
reg &= 0x1fff;
/* sign extend register */
if (reg & 0x1000)
reg |= 0xf000;
/* convert from 0.0625 to 0.001 resolution */
return reg * 125 / 2;
}
/* sysfs stuff */
/* read routines for temperature limits */
#define show(value) \
static ssize_t show_##value(struct device *dev, \
struct device_attribute *attr, \
char *buf) \
{ \
struct jc42_data *data = jc42_update_device(dev); \
if (IS_ERR(data)) \
return PTR_ERR(data); \
return sprintf(buf, "%d\n", jc42_temp_from_reg(data->value)); \
}
show(temp_input);
show(temp_crit);
show(temp_min);
show(temp_max);
/* read routines for hysteresis values */
static ssize_t show_temp_crit_hyst(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct jc42_data *data = jc42_update_device(dev);
int temp, hyst;
if (IS_ERR(data))
return PTR_ERR(data);
temp = jc42_temp_from_reg(data->temp_crit);
hyst = jc42_hysteresis[(data->config >> JC42_CFG_HYST_SHIFT)
& JC42_CFG_HYST_MASK];
return sprintf(buf, "%d\n", temp - hyst);
}
static ssize_t show_temp_max_hyst(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct jc42_data *data = jc42_update_device(dev);
int temp, hyst;
if (IS_ERR(data))
return PTR_ERR(data);
temp = jc42_temp_from_reg(data->temp_max);
hyst = jc42_hysteresis[(data->config >> JC42_CFG_HYST_SHIFT)
& JC42_CFG_HYST_MASK];
return sprintf(buf, "%d\n", temp - hyst);
}
/* write routines */
#define set(value, reg) \
static ssize_t set_##value(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t count) \
{ \
struct i2c_client *client = to_i2c_client(dev); \
struct jc42_data *data = i2c_get_clientdata(client); \
int err, ret = count; \
long val; \
if (kstrtol(buf, 10, &val) < 0) \
return -EINVAL; \
mutex_lock(&data->update_lock); \
data->value = jc42_temp_to_reg(val, data->extended); \
err = i2c_smbus_write_word_swapped(client, reg, data->value); \
if (err < 0) \
ret = err; \
mutex_unlock(&data->update_lock); \
return ret; \
}
set(temp_min, JC42_REG_TEMP_LOWER);
set(temp_max, JC42_REG_TEMP_UPPER);
set(temp_crit, JC42_REG_TEMP_CRITICAL);
/*
* JC42.4 compliant chips only support four hysteresis values.
* Pick best choice and go from there.
*/
static ssize_t set_temp_crit_hyst(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct jc42_data *data = i2c_get_clientdata(client);
unsigned long val;
int diff, hyst;
int err;
int ret = count;
if (kstrtoul(buf, 10, &val) < 0)
return -EINVAL;
diff = jc42_temp_from_reg(data->temp_crit) - val;
hyst = 0;
if (diff > 0) {
if (diff < 2250)
hyst = 1; /* 1.5 degrees C */
else if (diff < 4500)
hyst = 2; /* 3.0 degrees C */
else
hyst = 3; /* 6.0 degrees C */
}
mutex_lock(&data->update_lock);
data->config = (data->config
& ~(JC42_CFG_HYST_MASK << JC42_CFG_HYST_SHIFT))
| (hyst << JC42_CFG_HYST_SHIFT);
err = i2c_smbus_write_word_swapped(client, JC42_REG_CONFIG,
data->config);
if (err < 0)
ret = err;
mutex_unlock(&data->update_lock);
return ret;
}
static ssize_t show_alarm(struct device *dev,
struct device_attribute *attr, char *buf)
{
u16 bit = to_sensor_dev_attr(attr)->index;
struct jc42_data *data = jc42_update_device(dev);
u16 val;
if (IS_ERR(data))
return PTR_ERR(data);
val = data->temp_input;
if (bit != JC42_ALARM_CRIT_BIT && (data->config & JC42_CFG_CRIT_ONLY))
val = 0;
return sprintf(buf, "%u\n", (val >> bit) & 1);
}
static DEVICE_ATTR(temp1_input, S_IRUGO,
show_temp_input, NULL);
static DEVICE_ATTR(temp1_crit, S_IRUGO,
show_temp_crit, set_temp_crit);
static DEVICE_ATTR(temp1_min, S_IRUGO,
show_temp_min, set_temp_min);
static DEVICE_ATTR(temp1_max, S_IRUGO,
show_temp_max, set_temp_max);
static DEVICE_ATTR(temp1_crit_hyst, S_IRUGO,
show_temp_crit_hyst, set_temp_crit_hyst);
static DEVICE_ATTR(temp1_max_hyst, S_IRUGO,
show_temp_max_hyst, NULL);
static SENSOR_DEVICE_ATTR(temp1_crit_alarm, S_IRUGO, show_alarm, NULL,
JC42_ALARM_CRIT_BIT);
static SENSOR_DEVICE_ATTR(temp1_min_alarm, S_IRUGO, show_alarm, NULL,
JC42_ALARM_MIN_BIT);
static SENSOR_DEVICE_ATTR(temp1_max_alarm, S_IRUGO, show_alarm, NULL,
JC42_ALARM_MAX_BIT);
static struct attribute *jc42_attributes[] = {
&dev_attr_temp1_input.attr,
&dev_attr_temp1_crit.attr,
&dev_attr_temp1_min.attr,
&dev_attr_temp1_max.attr,
&dev_attr_temp1_crit_hyst.attr,
&dev_attr_temp1_max_hyst.attr,
&sensor_dev_attr_temp1_crit_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_max_alarm.dev_attr.attr,
NULL
};
static umode_t jc42_attribute_mode(struct kobject *kobj,
struct attribute *attr, int index)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct i2c_client *client = to_i2c_client(dev);
struct jc42_data *data = i2c_get_clientdata(client);
unsigned int config = data->config;
bool readonly;
if (attr == &dev_attr_temp1_crit.attr)
readonly = config & JC42_CFG_TCRIT_LOCK;
else if (attr == &dev_attr_temp1_min.attr ||
attr == &dev_attr_temp1_max.attr)
readonly = config & JC42_CFG_EVENT_LOCK;
else if (attr == &dev_attr_temp1_crit_hyst.attr)
readonly = config & (JC42_CFG_EVENT_LOCK | JC42_CFG_TCRIT_LOCK);
else
readonly = true;
return S_IRUGO | (readonly ? 0 : S_IWUSR);
}
static const struct attribute_group jc42_group = {
.attrs = jc42_attributes,
.is_visible = jc42_attribute_mode,
};
/* Return 0 if detection is successful, -ENODEV otherwise */
static int jc42_detect(struct i2c_client *client, struct i2c_board_info *info)
{
struct i2c_adapter *adapter = client->adapter;
int i, config, cap, manid, devid;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA |
I2C_FUNC_SMBUS_WORD_DATA))
return -ENODEV;
cap = i2c_smbus_read_word_swapped(client, JC42_REG_CAP);
config = i2c_smbus_read_word_swapped(client, JC42_REG_CONFIG);
manid = i2c_smbus_read_word_swapped(client, JC42_REG_MANID);
devid = i2c_smbus_read_word_swapped(client, JC42_REG_DEVICEID);
if (cap < 0 || config < 0 || manid < 0 || devid < 0)
return -ENODEV;
if ((cap & 0xff00) || (config & 0xf800))
return -ENODEV;
for (i = 0; i < ARRAY_SIZE(jc42_chips); i++) {
struct jc42_chips *chip = &jc42_chips[i];
if (manid == chip->manid &&
(devid & chip->devid_mask) == chip->devid) {
strlcpy(info->type, "jc42", I2C_NAME_SIZE);
return 0;
}
}
return -ENODEV;
}
static int jc42_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
struct jc42_data *data;
int config, cap, err;
struct device *dev = &client->dev;
data = devm_kzalloc(dev, sizeof(struct jc42_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
i2c_set_clientdata(client, data);
mutex_init(&data->update_lock);
cap = i2c_smbus_read_word_swapped(client, JC42_REG_CAP);
if (cap < 0)
return cap;
data->extended = !!(cap & JC42_CAP_RANGE);
config = i2c_smbus_read_word_swapped(client, JC42_REG_CONFIG);
if (config < 0)
return config;
data->orig_config = config;
if (config & JC42_CFG_SHUTDOWN) {
config &= ~JC42_CFG_SHUTDOWN;
i2c_smbus_write_word_swapped(client, JC42_REG_CONFIG, config);
}
data->config = config;
/* Register sysfs hooks */
err = sysfs_create_group(&dev->kobj, &jc42_group);
if (err)
return err;
data->hwmon_dev = hwmon_device_register(dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
goto exit_remove;
}
return 0;
exit_remove:
sysfs_remove_group(&dev->kobj, &jc42_group);
return err;
}
static int jc42_remove(struct i2c_client *client)
{
struct jc42_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_group(&client->dev.kobj, &jc42_group);
if (data->config != data->orig_config)
i2c_smbus_write_word_swapped(client, JC42_REG_CONFIG,
data->orig_config);
return 0;
}
static struct jc42_data *jc42_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct jc42_data *data = i2c_get_clientdata(client);
struct jc42_data *ret = data;
int val;
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ) || !data->valid) {
val = i2c_smbus_read_word_swapped(client, JC42_REG_TEMP);
if (val < 0) {
ret = ERR_PTR(val);
goto abort;
}
data->temp_input = val;
val = i2c_smbus_read_word_swapped(client,
JC42_REG_TEMP_CRITICAL);
if (val < 0) {
ret = ERR_PTR(val);
goto abort;
}
data->temp_crit = val;
val = i2c_smbus_read_word_swapped(client, JC42_REG_TEMP_LOWER);
if (val < 0) {
ret = ERR_PTR(val);
goto abort;
}
data->temp_min = val;
val = i2c_smbus_read_word_swapped(client, JC42_REG_TEMP_UPPER);
if (val < 0) {
ret = ERR_PTR(val);
goto abort;
}
data->temp_max = val;
data->last_updated = jiffies;
data->valid = true;
}
abort:
mutex_unlock(&data->update_lock);
return ret;
}
module_i2c_driver(jc42_driver);
MODULE_AUTHOR("Guenter Roeck <guenter.roeck@ericsson.com>");
MODULE_DESCRIPTION("JC42 driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
TeamWin/android_kernel_lge_msm8974 | fs/xfs/xfs_fsops.c | 5072 | 19448 | /*
* Copyright (c) 2000-2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* 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_fs.h"
#include "xfs_types.h"
#include "xfs_bit.h"
#include "xfs_inum.h"
#include "xfs_log.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_bmap_btree.h"
#include "xfs_alloc_btree.h"
#include "xfs_ialloc_btree.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_inode_item.h"
#include "xfs_btree.h"
#include "xfs_error.h"
#include "xfs_alloc.h"
#include "xfs_ialloc.h"
#include "xfs_fsops.h"
#include "xfs_itable.h"
#include "xfs_trans_space.h"
#include "xfs_rtalloc.h"
#include "xfs_rw.h"
#include "xfs_filestream.h"
#include "xfs_trace.h"
/*
* File system operations
*/
int
xfs_fs_geometry(
xfs_mount_t *mp,
xfs_fsop_geom_t *geo,
int new_version)
{
memset(geo, 0, sizeof(*geo));
geo->blocksize = mp->m_sb.sb_blocksize;
geo->rtextsize = mp->m_sb.sb_rextsize;
geo->agblocks = mp->m_sb.sb_agblocks;
geo->agcount = mp->m_sb.sb_agcount;
geo->logblocks = mp->m_sb.sb_logblocks;
geo->sectsize = mp->m_sb.sb_sectsize;
geo->inodesize = mp->m_sb.sb_inodesize;
geo->imaxpct = mp->m_sb.sb_imax_pct;
geo->datablocks = mp->m_sb.sb_dblocks;
geo->rtblocks = mp->m_sb.sb_rblocks;
geo->rtextents = mp->m_sb.sb_rextents;
geo->logstart = mp->m_sb.sb_logstart;
ASSERT(sizeof(geo->uuid)==sizeof(mp->m_sb.sb_uuid));
memcpy(geo->uuid, &mp->m_sb.sb_uuid, sizeof(mp->m_sb.sb_uuid));
if (new_version >= 2) {
geo->sunit = mp->m_sb.sb_unit;
geo->swidth = mp->m_sb.sb_width;
}
if (new_version >= 3) {
geo->version = XFS_FSOP_GEOM_VERSION;
geo->flags =
(xfs_sb_version_hasattr(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_ATTR : 0) |
(xfs_sb_version_hasnlink(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_NLINK : 0) |
(xfs_sb_version_hasquota(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_QUOTA : 0) |
(xfs_sb_version_hasalign(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_IALIGN : 0) |
(xfs_sb_version_hasdalign(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_DALIGN : 0) |
(xfs_sb_version_hasshared(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_SHARED : 0) |
(xfs_sb_version_hasextflgbit(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_EXTFLG : 0) |
(xfs_sb_version_hasdirv2(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_DIRV2 : 0) |
(xfs_sb_version_hassector(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_SECTOR : 0) |
(xfs_sb_version_hasasciici(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_DIRV2CI : 0) |
(xfs_sb_version_haslazysbcount(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_LAZYSB : 0) |
(xfs_sb_version_hasattr2(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_ATTR2 : 0);
geo->logsectsize = xfs_sb_version_hassector(&mp->m_sb) ?
mp->m_sb.sb_logsectsize : BBSIZE;
geo->rtsectsize = mp->m_sb.sb_blocksize;
geo->dirblocksize = mp->m_dirblksize;
}
if (new_version >= 4) {
geo->flags |=
(xfs_sb_version_haslogv2(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_LOGV2 : 0);
geo->logsunit = mp->m_sb.sb_logsunit;
}
return 0;
}
static int
xfs_growfs_data_private(
xfs_mount_t *mp, /* mount point for filesystem */
xfs_growfs_data_t *in) /* growfs data input struct */
{
xfs_agf_t *agf;
xfs_agi_t *agi;
xfs_agnumber_t agno;
xfs_extlen_t agsize;
xfs_extlen_t tmpsize;
xfs_alloc_rec_t *arec;
struct xfs_btree_block *block;
xfs_buf_t *bp;
int bucket;
int dpct;
int error;
xfs_agnumber_t nagcount;
xfs_agnumber_t nagimax = 0;
xfs_rfsblock_t nb, nb_mod;
xfs_rfsblock_t new;
xfs_rfsblock_t nfree;
xfs_agnumber_t oagcount;
int pct;
xfs_trans_t *tp;
nb = in->newblocks;
pct = in->imaxpct;
if (nb < mp->m_sb.sb_dblocks || pct < 0 || pct > 100)
return XFS_ERROR(EINVAL);
if ((error = xfs_sb_validate_fsb_count(&mp->m_sb, nb)))
return error;
dpct = pct - mp->m_sb.sb_imax_pct;
bp = xfs_buf_read_uncached(mp, mp->m_ddev_targp,
XFS_FSB_TO_BB(mp, nb) - XFS_FSS_TO_BB(mp, 1),
BBTOB(XFS_FSS_TO_BB(mp, 1)), 0);
if (!bp)
return EIO;
xfs_buf_relse(bp);
new = nb; /* use new as a temporary here */
nb_mod = do_div(new, mp->m_sb.sb_agblocks);
nagcount = new + (nb_mod != 0);
if (nb_mod && nb_mod < XFS_MIN_AG_BLOCKS) {
nagcount--;
nb = (xfs_rfsblock_t)nagcount * mp->m_sb.sb_agblocks;
if (nb < mp->m_sb.sb_dblocks)
return XFS_ERROR(EINVAL);
}
new = nb - mp->m_sb.sb_dblocks;
oagcount = mp->m_sb.sb_agcount;
/* allocate the new per-ag structures */
if (nagcount > oagcount) {
error = xfs_initialize_perag(mp, nagcount, &nagimax);
if (error)
return error;
}
tp = xfs_trans_alloc(mp, XFS_TRANS_GROWFS);
tp->t_flags |= XFS_TRANS_RESERVE;
if ((error = xfs_trans_reserve(tp, XFS_GROWFS_SPACE_RES(mp),
XFS_GROWDATA_LOG_RES(mp), 0, 0, 0))) {
xfs_trans_cancel(tp, 0);
return error;
}
/*
* Write new AG headers to disk. Non-transactional, but written
* synchronously so they are completed prior to the growfs transaction
* being logged.
*/
nfree = 0;
for (agno = nagcount - 1; agno >= oagcount; agno--, new -= agsize) {
/*
* AG freelist header block
*/
bp = xfs_buf_get(mp->m_ddev_targp,
XFS_AG_DADDR(mp, agno, XFS_AGF_DADDR(mp)),
XFS_FSS_TO_BB(mp, 1), XBF_LOCK | XBF_MAPPED);
if (!bp) {
error = ENOMEM;
goto error0;
}
agf = XFS_BUF_TO_AGF(bp);
memset(agf, 0, mp->m_sb.sb_sectsize);
agf->agf_magicnum = cpu_to_be32(XFS_AGF_MAGIC);
agf->agf_versionnum = cpu_to_be32(XFS_AGF_VERSION);
agf->agf_seqno = cpu_to_be32(agno);
if (agno == nagcount - 1)
agsize =
nb -
(agno * (xfs_rfsblock_t)mp->m_sb.sb_agblocks);
else
agsize = mp->m_sb.sb_agblocks;
agf->agf_length = cpu_to_be32(agsize);
agf->agf_roots[XFS_BTNUM_BNOi] = cpu_to_be32(XFS_BNO_BLOCK(mp));
agf->agf_roots[XFS_BTNUM_CNTi] = cpu_to_be32(XFS_CNT_BLOCK(mp));
agf->agf_levels[XFS_BTNUM_BNOi] = cpu_to_be32(1);
agf->agf_levels[XFS_BTNUM_CNTi] = cpu_to_be32(1);
agf->agf_flfirst = 0;
agf->agf_fllast = cpu_to_be32(XFS_AGFL_SIZE(mp) - 1);
agf->agf_flcount = 0;
tmpsize = agsize - XFS_PREALLOC_BLOCKS(mp);
agf->agf_freeblks = cpu_to_be32(tmpsize);
agf->agf_longest = cpu_to_be32(tmpsize);
error = xfs_bwrite(bp);
xfs_buf_relse(bp);
if (error)
goto error0;
/*
* AG inode header block
*/
bp = xfs_buf_get(mp->m_ddev_targp,
XFS_AG_DADDR(mp, agno, XFS_AGI_DADDR(mp)),
XFS_FSS_TO_BB(mp, 1), XBF_LOCK | XBF_MAPPED);
if (!bp) {
error = ENOMEM;
goto error0;
}
agi = XFS_BUF_TO_AGI(bp);
memset(agi, 0, mp->m_sb.sb_sectsize);
agi->agi_magicnum = cpu_to_be32(XFS_AGI_MAGIC);
agi->agi_versionnum = cpu_to_be32(XFS_AGI_VERSION);
agi->agi_seqno = cpu_to_be32(agno);
agi->agi_length = cpu_to_be32(agsize);
agi->agi_count = 0;
agi->agi_root = cpu_to_be32(XFS_IBT_BLOCK(mp));
agi->agi_level = cpu_to_be32(1);
agi->agi_freecount = 0;
agi->agi_newino = cpu_to_be32(NULLAGINO);
agi->agi_dirino = cpu_to_be32(NULLAGINO);
for (bucket = 0; bucket < XFS_AGI_UNLINKED_BUCKETS; bucket++)
agi->agi_unlinked[bucket] = cpu_to_be32(NULLAGINO);
error = xfs_bwrite(bp);
xfs_buf_relse(bp);
if (error)
goto error0;
/*
* BNO btree root block
*/
bp = xfs_buf_get(mp->m_ddev_targp,
XFS_AGB_TO_DADDR(mp, agno, XFS_BNO_BLOCK(mp)),
BTOBB(mp->m_sb.sb_blocksize),
XBF_LOCK | XBF_MAPPED);
if (!bp) {
error = ENOMEM;
goto error0;
}
block = XFS_BUF_TO_BLOCK(bp);
memset(block, 0, mp->m_sb.sb_blocksize);
block->bb_magic = cpu_to_be32(XFS_ABTB_MAGIC);
block->bb_level = 0;
block->bb_numrecs = cpu_to_be16(1);
block->bb_u.s.bb_leftsib = cpu_to_be32(NULLAGBLOCK);
block->bb_u.s.bb_rightsib = cpu_to_be32(NULLAGBLOCK);
arec = XFS_ALLOC_REC_ADDR(mp, block, 1);
arec->ar_startblock = cpu_to_be32(XFS_PREALLOC_BLOCKS(mp));
arec->ar_blockcount = cpu_to_be32(
agsize - be32_to_cpu(arec->ar_startblock));
error = xfs_bwrite(bp);
xfs_buf_relse(bp);
if (error)
goto error0;
/*
* CNT btree root block
*/
bp = xfs_buf_get(mp->m_ddev_targp,
XFS_AGB_TO_DADDR(mp, agno, XFS_CNT_BLOCK(mp)),
BTOBB(mp->m_sb.sb_blocksize),
XBF_LOCK | XBF_MAPPED);
if (!bp) {
error = ENOMEM;
goto error0;
}
block = XFS_BUF_TO_BLOCK(bp);
memset(block, 0, mp->m_sb.sb_blocksize);
block->bb_magic = cpu_to_be32(XFS_ABTC_MAGIC);
block->bb_level = 0;
block->bb_numrecs = cpu_to_be16(1);
block->bb_u.s.bb_leftsib = cpu_to_be32(NULLAGBLOCK);
block->bb_u.s.bb_rightsib = cpu_to_be32(NULLAGBLOCK);
arec = XFS_ALLOC_REC_ADDR(mp, block, 1);
arec->ar_startblock = cpu_to_be32(XFS_PREALLOC_BLOCKS(mp));
arec->ar_blockcount = cpu_to_be32(
agsize - be32_to_cpu(arec->ar_startblock));
nfree += be32_to_cpu(arec->ar_blockcount);
error = xfs_bwrite(bp);
xfs_buf_relse(bp);
if (error)
goto error0;
/*
* INO btree root block
*/
bp = xfs_buf_get(mp->m_ddev_targp,
XFS_AGB_TO_DADDR(mp, agno, XFS_IBT_BLOCK(mp)),
BTOBB(mp->m_sb.sb_blocksize),
XBF_LOCK | XBF_MAPPED);
if (!bp) {
error = ENOMEM;
goto error0;
}
block = XFS_BUF_TO_BLOCK(bp);
memset(block, 0, mp->m_sb.sb_blocksize);
block->bb_magic = cpu_to_be32(XFS_IBT_MAGIC);
block->bb_level = 0;
block->bb_numrecs = 0;
block->bb_u.s.bb_leftsib = cpu_to_be32(NULLAGBLOCK);
block->bb_u.s.bb_rightsib = cpu_to_be32(NULLAGBLOCK);
error = xfs_bwrite(bp);
xfs_buf_relse(bp);
if (error)
goto error0;
}
xfs_trans_agblocks_delta(tp, nfree);
/*
* There are new blocks in the old last a.g.
*/
if (new) {
/*
* Change the agi length.
*/
error = xfs_ialloc_read_agi(mp, tp, agno, &bp);
if (error) {
goto error0;
}
ASSERT(bp);
agi = XFS_BUF_TO_AGI(bp);
be32_add_cpu(&agi->agi_length, new);
ASSERT(nagcount == oagcount ||
be32_to_cpu(agi->agi_length) == mp->m_sb.sb_agblocks);
xfs_ialloc_log_agi(tp, bp, XFS_AGI_LENGTH);
/*
* Change agf length.
*/
error = xfs_alloc_read_agf(mp, tp, agno, 0, &bp);
if (error) {
goto error0;
}
ASSERT(bp);
agf = XFS_BUF_TO_AGF(bp);
be32_add_cpu(&agf->agf_length, new);
ASSERT(be32_to_cpu(agf->agf_length) ==
be32_to_cpu(agi->agi_length));
xfs_alloc_log_agf(tp, bp, XFS_AGF_LENGTH);
/*
* Free the new space.
*/
error = xfs_free_extent(tp, XFS_AGB_TO_FSB(mp, agno,
be32_to_cpu(agf->agf_length) - new), new);
if (error) {
goto error0;
}
}
/*
* Update changed superblock fields transactionally. These are not
* seen by the rest of the world until the transaction commit applies
* them atomically to the superblock.
*/
if (nagcount > oagcount)
xfs_trans_mod_sb(tp, XFS_TRANS_SB_AGCOUNT, nagcount - oagcount);
if (nb > mp->m_sb.sb_dblocks)
xfs_trans_mod_sb(tp, XFS_TRANS_SB_DBLOCKS,
nb - mp->m_sb.sb_dblocks);
if (nfree)
xfs_trans_mod_sb(tp, XFS_TRANS_SB_FDBLOCKS, nfree);
if (dpct)
xfs_trans_mod_sb(tp, XFS_TRANS_SB_IMAXPCT, dpct);
error = xfs_trans_commit(tp, 0);
if (error)
return error;
/* New allocation groups fully initialized, so update mount struct */
if (nagimax)
mp->m_maxagi = nagimax;
if (mp->m_sb.sb_imax_pct) {
__uint64_t icount = mp->m_sb.sb_dblocks * mp->m_sb.sb_imax_pct;
do_div(icount, 100);
mp->m_maxicount = icount << mp->m_sb.sb_inopblog;
} else
mp->m_maxicount = 0;
xfs_set_low_space_thresholds(mp);
/* update secondary superblocks. */
for (agno = 1; agno < nagcount; agno++) {
error = xfs_read_buf(mp, mp->m_ddev_targp,
XFS_AGB_TO_DADDR(mp, agno, XFS_SB_BLOCK(mp)),
XFS_FSS_TO_BB(mp, 1), 0, &bp);
if (error) {
xfs_warn(mp,
"error %d reading secondary superblock for ag %d",
error, agno);
break;
}
xfs_sb_to_disk(XFS_BUF_TO_SBP(bp), &mp->m_sb, XFS_SB_ALL_BITS);
/*
* If we get an error writing out the alternate superblocks,
* just issue a warning and continue. The real work is
* already done and committed.
*/
error = xfs_bwrite(bp);
xfs_buf_relse(bp);
if (error) {
xfs_warn(mp,
"write error %d updating secondary superblock for ag %d",
error, agno);
break; /* no point in continuing */
}
}
return 0;
error0:
xfs_trans_cancel(tp, XFS_TRANS_ABORT);
return error;
}
static int
xfs_growfs_log_private(
xfs_mount_t *mp, /* mount point for filesystem */
xfs_growfs_log_t *in) /* growfs log input struct */
{
xfs_extlen_t nb;
nb = in->newblocks;
if (nb < XFS_MIN_LOG_BLOCKS || nb < XFS_B_TO_FSB(mp, XFS_MIN_LOG_BYTES))
return XFS_ERROR(EINVAL);
if (nb == mp->m_sb.sb_logblocks &&
in->isint == (mp->m_sb.sb_logstart != 0))
return XFS_ERROR(EINVAL);
/*
* Moving the log is hard, need new interfaces to sync
* the log first, hold off all activity while moving it.
* Can have shorter or longer log in the same space,
* or transform internal to external log or vice versa.
*/
return XFS_ERROR(ENOSYS);
}
/*
* protected versions of growfs function acquire and release locks on the mount
* point - exported through ioctls: XFS_IOC_FSGROWFSDATA, XFS_IOC_FSGROWFSLOG,
* XFS_IOC_FSGROWFSRT
*/
int
xfs_growfs_data(
xfs_mount_t *mp,
xfs_growfs_data_t *in)
{
int error;
if (!capable(CAP_SYS_ADMIN))
return XFS_ERROR(EPERM);
if (!mutex_trylock(&mp->m_growlock))
return XFS_ERROR(EWOULDBLOCK);
error = xfs_growfs_data_private(mp, in);
mutex_unlock(&mp->m_growlock);
return error;
}
int
xfs_growfs_log(
xfs_mount_t *mp,
xfs_growfs_log_t *in)
{
int error;
if (!capable(CAP_SYS_ADMIN))
return XFS_ERROR(EPERM);
if (!mutex_trylock(&mp->m_growlock))
return XFS_ERROR(EWOULDBLOCK);
error = xfs_growfs_log_private(mp, in);
mutex_unlock(&mp->m_growlock);
return error;
}
/*
* exported through ioctl XFS_IOC_FSCOUNTS
*/
int
xfs_fs_counts(
xfs_mount_t *mp,
xfs_fsop_counts_t *cnt)
{
xfs_icsb_sync_counters(mp, XFS_ICSB_LAZY_COUNT);
spin_lock(&mp->m_sb_lock);
cnt->freedata = mp->m_sb.sb_fdblocks - XFS_ALLOC_SET_ASIDE(mp);
cnt->freertx = mp->m_sb.sb_frextents;
cnt->freeino = mp->m_sb.sb_ifree;
cnt->allocino = mp->m_sb.sb_icount;
spin_unlock(&mp->m_sb_lock);
return 0;
}
/*
* exported through ioctl XFS_IOC_SET_RESBLKS & XFS_IOC_GET_RESBLKS
*
* xfs_reserve_blocks is called to set m_resblks
* in the in-core mount table. The number of unused reserved blocks
* is kept in m_resblks_avail.
*
* Reserve the requested number of blocks if available. Otherwise return
* as many as possible to satisfy the request. The actual number
* reserved are returned in outval
*
* A null inval pointer indicates that only the current reserved blocks
* available should be returned no settings are changed.
*/
int
xfs_reserve_blocks(
xfs_mount_t *mp,
__uint64_t *inval,
xfs_fsop_resblks_t *outval)
{
__int64_t lcounter, delta, fdblks_delta;
__uint64_t request;
/* If inval is null, report current values and return */
if (inval == (__uint64_t *)NULL) {
if (!outval)
return EINVAL;
outval->resblks = mp->m_resblks;
outval->resblks_avail = mp->m_resblks_avail;
return 0;
}
request = *inval;
/*
* With per-cpu counters, this becomes an interesting
* problem. we needto work out if we are freeing or allocation
* blocks first, then we can do the modification as necessary.
*
* We do this under the m_sb_lock so that if we are near
* ENOSPC, we will hold out any changes while we work out
* what to do. This means that the amount of free space can
* change while we do this, so we need to retry if we end up
* trying to reserve more space than is available.
*
* We also use the xfs_mod_incore_sb() interface so that we
* don't have to care about whether per cpu counter are
* enabled, disabled or even compiled in....
*/
retry:
spin_lock(&mp->m_sb_lock);
xfs_icsb_sync_counters_locked(mp, 0);
/*
* If our previous reservation was larger than the current value,
* then move any unused blocks back to the free pool.
*/
fdblks_delta = 0;
if (mp->m_resblks > request) {
lcounter = mp->m_resblks_avail - request;
if (lcounter > 0) { /* release unused blocks */
fdblks_delta = lcounter;
mp->m_resblks_avail -= lcounter;
}
mp->m_resblks = request;
} else {
__int64_t free;
free = mp->m_sb.sb_fdblocks - XFS_ALLOC_SET_ASIDE(mp);
if (!free)
goto out; /* ENOSPC and fdblks_delta = 0 */
delta = request - mp->m_resblks;
lcounter = free - delta;
if (lcounter < 0) {
/* We can't satisfy the request, just get what we can */
mp->m_resblks += free;
mp->m_resblks_avail += free;
fdblks_delta = -free;
} else {
fdblks_delta = -delta;
mp->m_resblks = request;
mp->m_resblks_avail += delta;
}
}
out:
if (outval) {
outval->resblks = mp->m_resblks;
outval->resblks_avail = mp->m_resblks_avail;
}
spin_unlock(&mp->m_sb_lock);
if (fdblks_delta) {
/*
* If we are putting blocks back here, m_resblks_avail is
* already at its max so this will put it in the free pool.
*
* If we need space, we'll either succeed in getting it
* from the free block count or we'll get an enospc. If
* we get a ENOSPC, it means things changed while we were
* calculating fdblks_delta and so we should try again to
* see if there is anything left to reserve.
*
* Don't set the reserved flag here - we don't want to reserve
* the extra reserve blocks from the reserve.....
*/
int error;
error = xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS,
fdblks_delta, 0);
if (error == ENOSPC)
goto retry;
}
return 0;
}
/*
* Dump a transaction into the log that contains no real change. This is needed
* to be able to make the log dirty or stamp the current tail LSN into the log
* during the covering operation.
*
* We cannot use an inode here for this - that will push dirty state back up
* into the VFS and then periodic inode flushing will prevent log covering from
* making progress. Hence we log a field in the superblock instead and use a
* synchronous transaction to ensure the superblock is immediately unpinned
* and can be written back.
*/
int
xfs_fs_log_dummy(
xfs_mount_t *mp)
{
xfs_trans_t *tp;
int error;
tp = _xfs_trans_alloc(mp, XFS_TRANS_DUMMY1, KM_SLEEP);
error = xfs_trans_reserve(tp, 0, mp->m_sb.sb_sectsize + 128, 0, 0,
XFS_DEFAULT_LOG_COUNT);
if (error) {
xfs_trans_cancel(tp, 0);
return error;
}
/* log the UUID because it is an unchanging field */
xfs_mod_sb(tp, XFS_SB_UUID);
xfs_trans_set_sync(tp);
return xfs_trans_commit(tp, 0);
}
int
xfs_fs_goingdown(
xfs_mount_t *mp,
__uint32_t inflags)
{
switch (inflags) {
case XFS_FSOP_GOING_FLAGS_DEFAULT: {
struct super_block *sb = freeze_bdev(mp->m_super->s_bdev);
if (sb && !IS_ERR(sb)) {
xfs_force_shutdown(mp, SHUTDOWN_FORCE_UMOUNT);
thaw_bdev(sb->s_bdev, sb);
}
break;
}
case XFS_FSOP_GOING_FLAGS_LOGFLUSH:
xfs_force_shutdown(mp, SHUTDOWN_FORCE_UMOUNT);
break;
case XFS_FSOP_GOING_FLAGS_NOLOGFLUSH:
xfs_force_shutdown(mp,
SHUTDOWN_FORCE_UMOUNT | SHUTDOWN_LOG_IO_ERROR);
break;
default:
return XFS_ERROR(EINVAL);
}
return 0;
}
| gpl-2.0 |
friedrich420/S4-TW-AEL-Kernel-v4Plus | drivers/mtd/ar7part.c | 5072 | 4195 | /*
* Copyright © 2007 Eugene Konev <ejka@openwrt.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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
* TI AR7 flash partition table.
* Based on ar7 map by Felix Fietkau <nbd@openwrt.org>
*
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/bootmem.h>
#include <linux/magic.h>
#include <linux/module.h>
#define AR7_PARTS 4
#define ROOT_OFFSET 0xe0000
#define LOADER_MAGIC1 le32_to_cpu(0xfeedfa42)
#define LOADER_MAGIC2 le32_to_cpu(0xfeed1281)
#ifndef SQUASHFS_MAGIC
#define SQUASHFS_MAGIC 0x73717368
#endif
struct ar7_bin_rec {
unsigned int checksum;
unsigned int length;
unsigned int address;
};
static int create_mtd_partitions(struct mtd_info *master,
struct mtd_partition **pparts,
struct mtd_part_parser_data *data)
{
struct ar7_bin_rec header;
unsigned int offset;
size_t len;
unsigned int pre_size = master->erasesize, post_size = 0;
unsigned int root_offset = ROOT_OFFSET;
int retries = 10;
struct mtd_partition *ar7_parts;
ar7_parts = kzalloc(sizeof(*ar7_parts) * AR7_PARTS, GFP_KERNEL);
if (!ar7_parts)
return -ENOMEM;
ar7_parts[0].name = "loader";
ar7_parts[0].offset = 0;
ar7_parts[0].size = master->erasesize;
ar7_parts[0].mask_flags = MTD_WRITEABLE;
ar7_parts[1].name = "config";
ar7_parts[1].offset = 0;
ar7_parts[1].size = master->erasesize;
ar7_parts[1].mask_flags = 0;
do { /* Try 10 blocks starting from master->erasesize */
offset = pre_size;
mtd_read(master, offset, sizeof(header), &len,
(uint8_t *)&header);
if (!strncmp((char *)&header, "TIENV0.8", 8))
ar7_parts[1].offset = pre_size;
if (header.checksum == LOADER_MAGIC1)
break;
if (header.checksum == LOADER_MAGIC2)
break;
pre_size += master->erasesize;
} while (retries--);
pre_size = offset;
if (!ar7_parts[1].offset) {
ar7_parts[1].offset = master->size - master->erasesize;
post_size = master->erasesize;
}
switch (header.checksum) {
case LOADER_MAGIC1:
while (header.length) {
offset += sizeof(header) + header.length;
mtd_read(master, offset, sizeof(header), &len,
(uint8_t *)&header);
}
root_offset = offset + sizeof(header) + 4;
break;
case LOADER_MAGIC2:
while (header.length) {
offset += sizeof(header) + header.length;
mtd_read(master, offset, sizeof(header), &len,
(uint8_t *)&header);
}
root_offset = offset + sizeof(header) + 4 + 0xff;
root_offset &= ~(uint32_t)0xff;
break;
default:
printk(KERN_WARNING "Unknown magic: %08x\n", header.checksum);
break;
}
mtd_read(master, root_offset, sizeof(header), &len, (u8 *)&header);
if (header.checksum != SQUASHFS_MAGIC) {
root_offset += master->erasesize - 1;
root_offset &= ~(master->erasesize - 1);
}
ar7_parts[2].name = "linux";
ar7_parts[2].offset = pre_size;
ar7_parts[2].size = master->size - pre_size - post_size;
ar7_parts[2].mask_flags = 0;
ar7_parts[3].name = "rootfs";
ar7_parts[3].offset = root_offset;
ar7_parts[3].size = master->size - root_offset - post_size;
ar7_parts[3].mask_flags = 0;
*pparts = ar7_parts;
return AR7_PARTS;
}
static struct mtd_part_parser ar7_parser = {
.owner = THIS_MODULE,
.parse_fn = create_mtd_partitions,
.name = "ar7part",
};
static int __init ar7_parser_init(void)
{
return register_mtd_parser(&ar7_parser);
}
module_init(ar7_parser_init);
MODULE_LICENSE("GPL");
MODULE_AUTHOR( "Felix Fietkau <nbd@openwrt.org>, "
"Eugene Konev <ejka@openwrt.org>");
MODULE_DESCRIPTION("MTD partitioning for TI AR7");
| gpl-2.0 |
Sparkey67/android_kernel_lge_g3-1 | drivers/mtd/ar7part.c | 5072 | 4195 | /*
* Copyright © 2007 Eugene Konev <ejka@openwrt.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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
* TI AR7 flash partition table.
* Based on ar7 map by Felix Fietkau <nbd@openwrt.org>
*
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/bootmem.h>
#include <linux/magic.h>
#include <linux/module.h>
#define AR7_PARTS 4
#define ROOT_OFFSET 0xe0000
#define LOADER_MAGIC1 le32_to_cpu(0xfeedfa42)
#define LOADER_MAGIC2 le32_to_cpu(0xfeed1281)
#ifndef SQUASHFS_MAGIC
#define SQUASHFS_MAGIC 0x73717368
#endif
struct ar7_bin_rec {
unsigned int checksum;
unsigned int length;
unsigned int address;
};
static int create_mtd_partitions(struct mtd_info *master,
struct mtd_partition **pparts,
struct mtd_part_parser_data *data)
{
struct ar7_bin_rec header;
unsigned int offset;
size_t len;
unsigned int pre_size = master->erasesize, post_size = 0;
unsigned int root_offset = ROOT_OFFSET;
int retries = 10;
struct mtd_partition *ar7_parts;
ar7_parts = kzalloc(sizeof(*ar7_parts) * AR7_PARTS, GFP_KERNEL);
if (!ar7_parts)
return -ENOMEM;
ar7_parts[0].name = "loader";
ar7_parts[0].offset = 0;
ar7_parts[0].size = master->erasesize;
ar7_parts[0].mask_flags = MTD_WRITEABLE;
ar7_parts[1].name = "config";
ar7_parts[1].offset = 0;
ar7_parts[1].size = master->erasesize;
ar7_parts[1].mask_flags = 0;
do { /* Try 10 blocks starting from master->erasesize */
offset = pre_size;
mtd_read(master, offset, sizeof(header), &len,
(uint8_t *)&header);
if (!strncmp((char *)&header, "TIENV0.8", 8))
ar7_parts[1].offset = pre_size;
if (header.checksum == LOADER_MAGIC1)
break;
if (header.checksum == LOADER_MAGIC2)
break;
pre_size += master->erasesize;
} while (retries--);
pre_size = offset;
if (!ar7_parts[1].offset) {
ar7_parts[1].offset = master->size - master->erasesize;
post_size = master->erasesize;
}
switch (header.checksum) {
case LOADER_MAGIC1:
while (header.length) {
offset += sizeof(header) + header.length;
mtd_read(master, offset, sizeof(header), &len,
(uint8_t *)&header);
}
root_offset = offset + sizeof(header) + 4;
break;
case LOADER_MAGIC2:
while (header.length) {
offset += sizeof(header) + header.length;
mtd_read(master, offset, sizeof(header), &len,
(uint8_t *)&header);
}
root_offset = offset + sizeof(header) + 4 + 0xff;
root_offset &= ~(uint32_t)0xff;
break;
default:
printk(KERN_WARNING "Unknown magic: %08x\n", header.checksum);
break;
}
mtd_read(master, root_offset, sizeof(header), &len, (u8 *)&header);
if (header.checksum != SQUASHFS_MAGIC) {
root_offset += master->erasesize - 1;
root_offset &= ~(master->erasesize - 1);
}
ar7_parts[2].name = "linux";
ar7_parts[2].offset = pre_size;
ar7_parts[2].size = master->size - pre_size - post_size;
ar7_parts[2].mask_flags = 0;
ar7_parts[3].name = "rootfs";
ar7_parts[3].offset = root_offset;
ar7_parts[3].size = master->size - root_offset - post_size;
ar7_parts[3].mask_flags = 0;
*pparts = ar7_parts;
return AR7_PARTS;
}
static struct mtd_part_parser ar7_parser = {
.owner = THIS_MODULE,
.parse_fn = create_mtd_partitions,
.name = "ar7part",
};
static int __init ar7_parser_init(void)
{
return register_mtd_parser(&ar7_parser);
}
module_init(ar7_parser_init);
MODULE_LICENSE("GPL");
MODULE_AUTHOR( "Felix Fietkau <nbd@openwrt.org>, "
"Eugene Konev <ejka@openwrt.org>");
MODULE_DESCRIPTION("MTD partitioning for TI AR7");
| gpl-2.0 |
RazerRom/kernel_lge_hammerhead | drivers/mtd/ar7part.c | 5072 | 4195 | /*
* Copyright © 2007 Eugene Konev <ejka@openwrt.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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
* TI AR7 flash partition table.
* Based on ar7 map by Felix Fietkau <nbd@openwrt.org>
*
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/bootmem.h>
#include <linux/magic.h>
#include <linux/module.h>
#define AR7_PARTS 4
#define ROOT_OFFSET 0xe0000
#define LOADER_MAGIC1 le32_to_cpu(0xfeedfa42)
#define LOADER_MAGIC2 le32_to_cpu(0xfeed1281)
#ifndef SQUASHFS_MAGIC
#define SQUASHFS_MAGIC 0x73717368
#endif
struct ar7_bin_rec {
unsigned int checksum;
unsigned int length;
unsigned int address;
};
static int create_mtd_partitions(struct mtd_info *master,
struct mtd_partition **pparts,
struct mtd_part_parser_data *data)
{
struct ar7_bin_rec header;
unsigned int offset;
size_t len;
unsigned int pre_size = master->erasesize, post_size = 0;
unsigned int root_offset = ROOT_OFFSET;
int retries = 10;
struct mtd_partition *ar7_parts;
ar7_parts = kzalloc(sizeof(*ar7_parts) * AR7_PARTS, GFP_KERNEL);
if (!ar7_parts)
return -ENOMEM;
ar7_parts[0].name = "loader";
ar7_parts[0].offset = 0;
ar7_parts[0].size = master->erasesize;
ar7_parts[0].mask_flags = MTD_WRITEABLE;
ar7_parts[1].name = "config";
ar7_parts[1].offset = 0;
ar7_parts[1].size = master->erasesize;
ar7_parts[1].mask_flags = 0;
do { /* Try 10 blocks starting from master->erasesize */
offset = pre_size;
mtd_read(master, offset, sizeof(header), &len,
(uint8_t *)&header);
if (!strncmp((char *)&header, "TIENV0.8", 8))
ar7_parts[1].offset = pre_size;
if (header.checksum == LOADER_MAGIC1)
break;
if (header.checksum == LOADER_MAGIC2)
break;
pre_size += master->erasesize;
} while (retries--);
pre_size = offset;
if (!ar7_parts[1].offset) {
ar7_parts[1].offset = master->size - master->erasesize;
post_size = master->erasesize;
}
switch (header.checksum) {
case LOADER_MAGIC1:
while (header.length) {
offset += sizeof(header) + header.length;
mtd_read(master, offset, sizeof(header), &len,
(uint8_t *)&header);
}
root_offset = offset + sizeof(header) + 4;
break;
case LOADER_MAGIC2:
while (header.length) {
offset += sizeof(header) + header.length;
mtd_read(master, offset, sizeof(header), &len,
(uint8_t *)&header);
}
root_offset = offset + sizeof(header) + 4 + 0xff;
root_offset &= ~(uint32_t)0xff;
break;
default:
printk(KERN_WARNING "Unknown magic: %08x\n", header.checksum);
break;
}
mtd_read(master, root_offset, sizeof(header), &len, (u8 *)&header);
if (header.checksum != SQUASHFS_MAGIC) {
root_offset += master->erasesize - 1;
root_offset &= ~(master->erasesize - 1);
}
ar7_parts[2].name = "linux";
ar7_parts[2].offset = pre_size;
ar7_parts[2].size = master->size - pre_size - post_size;
ar7_parts[2].mask_flags = 0;
ar7_parts[3].name = "rootfs";
ar7_parts[3].offset = root_offset;
ar7_parts[3].size = master->size - root_offset - post_size;
ar7_parts[3].mask_flags = 0;
*pparts = ar7_parts;
return AR7_PARTS;
}
static struct mtd_part_parser ar7_parser = {
.owner = THIS_MODULE,
.parse_fn = create_mtd_partitions,
.name = "ar7part",
};
static int __init ar7_parser_init(void)
{
return register_mtd_parser(&ar7_parser);
}
module_init(ar7_parser_init);
MODULE_LICENSE("GPL");
MODULE_AUTHOR( "Felix Fietkau <nbd@openwrt.org>, "
"Eugene Konev <ejka@openwrt.org>");
MODULE_DESCRIPTION("MTD partitioning for TI AR7");
| gpl-2.0 |
KylinUI/android_kernel_samsung_exynos5410 | drivers/infiniband/hw/mthca/mthca_provider.c | 5328 | 35936 | /*
* Copyright (c) 2004, 2005 Topspin Communications. All rights reserved.
* Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
* Copyright (c) 2005, 2006 Cisco Systems. All rights reserved.
* Copyright (c) 2005 Mellanox Technologies. All rights reserved.
* Copyright (c) 2004 Voltaire, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <rdma/ib_smi.h>
#include <rdma/ib_umem.h>
#include <rdma/ib_user_verbs.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/stat.h>
#include <linux/mm.h>
#include <linux/export.h>
#include "mthca_dev.h"
#include "mthca_cmd.h"
#include "mthca_user.h"
#include "mthca_memfree.h"
static void init_query_mad(struct ib_smp *mad)
{
mad->base_version = 1;
mad->mgmt_class = IB_MGMT_CLASS_SUBN_LID_ROUTED;
mad->class_version = 1;
mad->method = IB_MGMT_METHOD_GET;
}
static int mthca_query_device(struct ib_device *ibdev,
struct ib_device_attr *props)
{
struct ib_smp *in_mad = NULL;
struct ib_smp *out_mad = NULL;
int err = -ENOMEM;
struct mthca_dev *mdev = to_mdev(ibdev);
in_mad = kzalloc(sizeof *in_mad, GFP_KERNEL);
out_mad = kmalloc(sizeof *out_mad, GFP_KERNEL);
if (!in_mad || !out_mad)
goto out;
memset(props, 0, sizeof *props);
props->fw_ver = mdev->fw_ver;
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_NODE_INFO;
err = mthca_MAD_IFC(mdev, 1, 1,
1, NULL, NULL, in_mad, out_mad);
if (err)
goto out;
props->device_cap_flags = mdev->device_cap_flags;
props->vendor_id = be32_to_cpup((__be32 *) (out_mad->data + 36)) &
0xffffff;
props->vendor_part_id = be16_to_cpup((__be16 *) (out_mad->data + 30));
props->hw_ver = be32_to_cpup((__be32 *) (out_mad->data + 32));
memcpy(&props->sys_image_guid, out_mad->data + 4, 8);
props->max_mr_size = ~0ull;
props->page_size_cap = mdev->limits.page_size_cap;
props->max_qp = mdev->limits.num_qps - mdev->limits.reserved_qps;
props->max_qp_wr = mdev->limits.max_wqes;
props->max_sge = mdev->limits.max_sg;
props->max_cq = mdev->limits.num_cqs - mdev->limits.reserved_cqs;
props->max_cqe = mdev->limits.max_cqes;
props->max_mr = mdev->limits.num_mpts - mdev->limits.reserved_mrws;
props->max_pd = mdev->limits.num_pds - mdev->limits.reserved_pds;
props->max_qp_rd_atom = 1 << mdev->qp_table.rdb_shift;
props->max_qp_init_rd_atom = mdev->limits.max_qp_init_rdma;
props->max_res_rd_atom = props->max_qp_rd_atom * props->max_qp;
props->max_srq = mdev->limits.num_srqs - mdev->limits.reserved_srqs;
props->max_srq_wr = mdev->limits.max_srq_wqes;
props->max_srq_sge = mdev->limits.max_srq_sge;
props->local_ca_ack_delay = mdev->limits.local_ca_ack_delay;
props->atomic_cap = mdev->limits.flags & DEV_LIM_FLAG_ATOMIC ?
IB_ATOMIC_HCA : IB_ATOMIC_NONE;
props->max_pkeys = mdev->limits.pkey_table_len;
props->max_mcast_grp = mdev->limits.num_mgms + mdev->limits.num_amgms;
props->max_mcast_qp_attach = MTHCA_QP_PER_MGM;
props->max_total_mcast_qp_attach = props->max_mcast_qp_attach *
props->max_mcast_grp;
/*
* If Sinai memory key optimization is being used, then only
* the 8-bit key portion will change. For other HCAs, the
* unused index bits will also be used for FMR remapping.
*/
if (mdev->mthca_flags & MTHCA_FLAG_SINAI_OPT)
props->max_map_per_fmr = 255;
else
props->max_map_per_fmr =
(1 << (32 - ilog2(mdev->limits.num_mpts))) - 1;
err = 0;
out:
kfree(in_mad);
kfree(out_mad);
return err;
}
static int mthca_query_port(struct ib_device *ibdev,
u8 port, struct ib_port_attr *props)
{
struct ib_smp *in_mad = NULL;
struct ib_smp *out_mad = NULL;
int err = -ENOMEM;
in_mad = kzalloc(sizeof *in_mad, GFP_KERNEL);
out_mad = kmalloc(sizeof *out_mad, GFP_KERNEL);
if (!in_mad || !out_mad)
goto out;
memset(props, 0, sizeof *props);
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_PORT_INFO;
in_mad->attr_mod = cpu_to_be32(port);
err = mthca_MAD_IFC(to_mdev(ibdev), 1, 1,
port, NULL, NULL, in_mad, out_mad);
if (err)
goto out;
props->lid = be16_to_cpup((__be16 *) (out_mad->data + 16));
props->lmc = out_mad->data[34] & 0x7;
props->sm_lid = be16_to_cpup((__be16 *) (out_mad->data + 18));
props->sm_sl = out_mad->data[36] & 0xf;
props->state = out_mad->data[32] & 0xf;
props->phys_state = out_mad->data[33] >> 4;
props->port_cap_flags = be32_to_cpup((__be32 *) (out_mad->data + 20));
props->gid_tbl_len = to_mdev(ibdev)->limits.gid_table_len;
props->max_msg_sz = 0x80000000;
props->pkey_tbl_len = to_mdev(ibdev)->limits.pkey_table_len;
props->bad_pkey_cntr = be16_to_cpup((__be16 *) (out_mad->data + 46));
props->qkey_viol_cntr = be16_to_cpup((__be16 *) (out_mad->data + 48));
props->active_width = out_mad->data[31] & 0xf;
props->active_speed = out_mad->data[35] >> 4;
props->max_mtu = out_mad->data[41] & 0xf;
props->active_mtu = out_mad->data[36] >> 4;
props->subnet_timeout = out_mad->data[51] & 0x1f;
props->max_vl_num = out_mad->data[37] >> 4;
props->init_type_reply = out_mad->data[41] >> 4;
out:
kfree(in_mad);
kfree(out_mad);
return err;
}
static int mthca_modify_device(struct ib_device *ibdev,
int mask,
struct ib_device_modify *props)
{
if (mask & ~IB_DEVICE_MODIFY_NODE_DESC)
return -EOPNOTSUPP;
if (mask & IB_DEVICE_MODIFY_NODE_DESC) {
if (mutex_lock_interruptible(&to_mdev(ibdev)->cap_mask_mutex))
return -ERESTARTSYS;
memcpy(ibdev->node_desc, props->node_desc, 64);
mutex_unlock(&to_mdev(ibdev)->cap_mask_mutex);
}
return 0;
}
static int mthca_modify_port(struct ib_device *ibdev,
u8 port, int port_modify_mask,
struct ib_port_modify *props)
{
struct mthca_set_ib_param set_ib;
struct ib_port_attr attr;
int err;
if (mutex_lock_interruptible(&to_mdev(ibdev)->cap_mask_mutex))
return -ERESTARTSYS;
err = mthca_query_port(ibdev, port, &attr);
if (err)
goto out;
set_ib.set_si_guid = 0;
set_ib.reset_qkey_viol = !!(port_modify_mask & IB_PORT_RESET_QKEY_CNTR);
set_ib.cap_mask = (attr.port_cap_flags | props->set_port_cap_mask) &
~props->clr_port_cap_mask;
err = mthca_SET_IB(to_mdev(ibdev), &set_ib, port);
if (err)
goto out;
out:
mutex_unlock(&to_mdev(ibdev)->cap_mask_mutex);
return err;
}
static int mthca_query_pkey(struct ib_device *ibdev,
u8 port, u16 index, u16 *pkey)
{
struct ib_smp *in_mad = NULL;
struct ib_smp *out_mad = NULL;
int err = -ENOMEM;
in_mad = kzalloc(sizeof *in_mad, GFP_KERNEL);
out_mad = kmalloc(sizeof *out_mad, GFP_KERNEL);
if (!in_mad || !out_mad)
goto out;
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_PKEY_TABLE;
in_mad->attr_mod = cpu_to_be32(index / 32);
err = mthca_MAD_IFC(to_mdev(ibdev), 1, 1,
port, NULL, NULL, in_mad, out_mad);
if (err)
goto out;
*pkey = be16_to_cpu(((__be16 *) out_mad->data)[index % 32]);
out:
kfree(in_mad);
kfree(out_mad);
return err;
}
static int mthca_query_gid(struct ib_device *ibdev, u8 port,
int index, union ib_gid *gid)
{
struct ib_smp *in_mad = NULL;
struct ib_smp *out_mad = NULL;
int err = -ENOMEM;
in_mad = kzalloc(sizeof *in_mad, GFP_KERNEL);
out_mad = kmalloc(sizeof *out_mad, GFP_KERNEL);
if (!in_mad || !out_mad)
goto out;
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_PORT_INFO;
in_mad->attr_mod = cpu_to_be32(port);
err = mthca_MAD_IFC(to_mdev(ibdev), 1, 1,
port, NULL, NULL, in_mad, out_mad);
if (err)
goto out;
memcpy(gid->raw, out_mad->data + 8, 8);
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_GUID_INFO;
in_mad->attr_mod = cpu_to_be32(index / 8);
err = mthca_MAD_IFC(to_mdev(ibdev), 1, 1,
port, NULL, NULL, in_mad, out_mad);
if (err)
goto out;
memcpy(gid->raw + 8, out_mad->data + (index % 8) * 8, 8);
out:
kfree(in_mad);
kfree(out_mad);
return err;
}
static struct ib_ucontext *mthca_alloc_ucontext(struct ib_device *ibdev,
struct ib_udata *udata)
{
struct mthca_alloc_ucontext_resp uresp;
struct mthca_ucontext *context;
int err;
if (!(to_mdev(ibdev)->active))
return ERR_PTR(-EAGAIN);
memset(&uresp, 0, sizeof uresp);
uresp.qp_tab_size = to_mdev(ibdev)->limits.num_qps;
if (mthca_is_memfree(to_mdev(ibdev)))
uresp.uarc_size = to_mdev(ibdev)->uar_table.uarc_size;
else
uresp.uarc_size = 0;
context = kmalloc(sizeof *context, GFP_KERNEL);
if (!context)
return ERR_PTR(-ENOMEM);
err = mthca_uar_alloc(to_mdev(ibdev), &context->uar);
if (err) {
kfree(context);
return ERR_PTR(err);
}
context->db_tab = mthca_init_user_db_tab(to_mdev(ibdev));
if (IS_ERR(context->db_tab)) {
err = PTR_ERR(context->db_tab);
mthca_uar_free(to_mdev(ibdev), &context->uar);
kfree(context);
return ERR_PTR(err);
}
if (ib_copy_to_udata(udata, &uresp, sizeof uresp)) {
mthca_cleanup_user_db_tab(to_mdev(ibdev), &context->uar, context->db_tab);
mthca_uar_free(to_mdev(ibdev), &context->uar);
kfree(context);
return ERR_PTR(-EFAULT);
}
context->reg_mr_warned = 0;
return &context->ibucontext;
}
static int mthca_dealloc_ucontext(struct ib_ucontext *context)
{
mthca_cleanup_user_db_tab(to_mdev(context->device), &to_mucontext(context)->uar,
to_mucontext(context)->db_tab);
mthca_uar_free(to_mdev(context->device), &to_mucontext(context)->uar);
kfree(to_mucontext(context));
return 0;
}
static int mthca_mmap_uar(struct ib_ucontext *context,
struct vm_area_struct *vma)
{
if (vma->vm_end - vma->vm_start != PAGE_SIZE)
return -EINVAL;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
if (io_remap_pfn_range(vma, vma->vm_start,
to_mucontext(context)->uar.pfn,
PAGE_SIZE, vma->vm_page_prot))
return -EAGAIN;
return 0;
}
static struct ib_pd *mthca_alloc_pd(struct ib_device *ibdev,
struct ib_ucontext *context,
struct ib_udata *udata)
{
struct mthca_pd *pd;
int err;
pd = kmalloc(sizeof *pd, GFP_KERNEL);
if (!pd)
return ERR_PTR(-ENOMEM);
err = mthca_pd_alloc(to_mdev(ibdev), !context, pd);
if (err) {
kfree(pd);
return ERR_PTR(err);
}
if (context) {
if (ib_copy_to_udata(udata, &pd->pd_num, sizeof (__u32))) {
mthca_pd_free(to_mdev(ibdev), pd);
kfree(pd);
return ERR_PTR(-EFAULT);
}
}
return &pd->ibpd;
}
static int mthca_dealloc_pd(struct ib_pd *pd)
{
mthca_pd_free(to_mdev(pd->device), to_mpd(pd));
kfree(pd);
return 0;
}
static struct ib_ah *mthca_ah_create(struct ib_pd *pd,
struct ib_ah_attr *ah_attr)
{
int err;
struct mthca_ah *ah;
ah = kmalloc(sizeof *ah, GFP_ATOMIC);
if (!ah)
return ERR_PTR(-ENOMEM);
err = mthca_create_ah(to_mdev(pd->device), to_mpd(pd), ah_attr, ah);
if (err) {
kfree(ah);
return ERR_PTR(err);
}
return &ah->ibah;
}
static int mthca_ah_destroy(struct ib_ah *ah)
{
mthca_destroy_ah(to_mdev(ah->device), to_mah(ah));
kfree(ah);
return 0;
}
static struct ib_srq *mthca_create_srq(struct ib_pd *pd,
struct ib_srq_init_attr *init_attr,
struct ib_udata *udata)
{
struct mthca_create_srq ucmd;
struct mthca_ucontext *context = NULL;
struct mthca_srq *srq;
int err;
if (init_attr->srq_type != IB_SRQT_BASIC)
return ERR_PTR(-ENOSYS);
srq = kmalloc(sizeof *srq, GFP_KERNEL);
if (!srq)
return ERR_PTR(-ENOMEM);
if (pd->uobject) {
context = to_mucontext(pd->uobject->context);
if (ib_copy_from_udata(&ucmd, udata, sizeof ucmd)) {
err = -EFAULT;
goto err_free;
}
err = mthca_map_user_db(to_mdev(pd->device), &context->uar,
context->db_tab, ucmd.db_index,
ucmd.db_page);
if (err)
goto err_free;
srq->mr.ibmr.lkey = ucmd.lkey;
srq->db_index = ucmd.db_index;
}
err = mthca_alloc_srq(to_mdev(pd->device), to_mpd(pd),
&init_attr->attr, srq);
if (err && pd->uobject)
mthca_unmap_user_db(to_mdev(pd->device), &context->uar,
context->db_tab, ucmd.db_index);
if (err)
goto err_free;
if (context && ib_copy_to_udata(udata, &srq->srqn, sizeof (__u32))) {
mthca_free_srq(to_mdev(pd->device), srq);
err = -EFAULT;
goto err_free;
}
return &srq->ibsrq;
err_free:
kfree(srq);
return ERR_PTR(err);
}
static int mthca_destroy_srq(struct ib_srq *srq)
{
struct mthca_ucontext *context;
if (srq->uobject) {
context = to_mucontext(srq->uobject->context);
mthca_unmap_user_db(to_mdev(srq->device), &context->uar,
context->db_tab, to_msrq(srq)->db_index);
}
mthca_free_srq(to_mdev(srq->device), to_msrq(srq));
kfree(srq);
return 0;
}
static struct ib_qp *mthca_create_qp(struct ib_pd *pd,
struct ib_qp_init_attr *init_attr,
struct ib_udata *udata)
{
struct mthca_create_qp ucmd;
struct mthca_qp *qp;
int err;
if (init_attr->create_flags)
return ERR_PTR(-EINVAL);
switch (init_attr->qp_type) {
case IB_QPT_RC:
case IB_QPT_UC:
case IB_QPT_UD:
{
struct mthca_ucontext *context;
qp = kmalloc(sizeof *qp, GFP_KERNEL);
if (!qp)
return ERR_PTR(-ENOMEM);
if (pd->uobject) {
context = to_mucontext(pd->uobject->context);
if (ib_copy_from_udata(&ucmd, udata, sizeof ucmd)) {
kfree(qp);
return ERR_PTR(-EFAULT);
}
err = mthca_map_user_db(to_mdev(pd->device), &context->uar,
context->db_tab,
ucmd.sq_db_index, ucmd.sq_db_page);
if (err) {
kfree(qp);
return ERR_PTR(err);
}
err = mthca_map_user_db(to_mdev(pd->device), &context->uar,
context->db_tab,
ucmd.rq_db_index, ucmd.rq_db_page);
if (err) {
mthca_unmap_user_db(to_mdev(pd->device),
&context->uar,
context->db_tab,
ucmd.sq_db_index);
kfree(qp);
return ERR_PTR(err);
}
qp->mr.ibmr.lkey = ucmd.lkey;
qp->sq.db_index = ucmd.sq_db_index;
qp->rq.db_index = ucmd.rq_db_index;
}
err = mthca_alloc_qp(to_mdev(pd->device), to_mpd(pd),
to_mcq(init_attr->send_cq),
to_mcq(init_attr->recv_cq),
init_attr->qp_type, init_attr->sq_sig_type,
&init_attr->cap, qp);
if (err && pd->uobject) {
context = to_mucontext(pd->uobject->context);
mthca_unmap_user_db(to_mdev(pd->device),
&context->uar,
context->db_tab,
ucmd.sq_db_index);
mthca_unmap_user_db(to_mdev(pd->device),
&context->uar,
context->db_tab,
ucmd.rq_db_index);
}
qp->ibqp.qp_num = qp->qpn;
break;
}
case IB_QPT_SMI:
case IB_QPT_GSI:
{
/* Don't allow userspace to create special QPs */
if (pd->uobject)
return ERR_PTR(-EINVAL);
qp = kmalloc(sizeof (struct mthca_sqp), GFP_KERNEL);
if (!qp)
return ERR_PTR(-ENOMEM);
qp->ibqp.qp_num = init_attr->qp_type == IB_QPT_SMI ? 0 : 1;
err = mthca_alloc_sqp(to_mdev(pd->device), to_mpd(pd),
to_mcq(init_attr->send_cq),
to_mcq(init_attr->recv_cq),
init_attr->sq_sig_type, &init_attr->cap,
qp->ibqp.qp_num, init_attr->port_num,
to_msqp(qp));
break;
}
default:
/* Don't support raw QPs */
return ERR_PTR(-ENOSYS);
}
if (err) {
kfree(qp);
return ERR_PTR(err);
}
init_attr->cap.max_send_wr = qp->sq.max;
init_attr->cap.max_recv_wr = qp->rq.max;
init_attr->cap.max_send_sge = qp->sq.max_gs;
init_attr->cap.max_recv_sge = qp->rq.max_gs;
init_attr->cap.max_inline_data = qp->max_inline_data;
return &qp->ibqp;
}
static int mthca_destroy_qp(struct ib_qp *qp)
{
if (qp->uobject) {
mthca_unmap_user_db(to_mdev(qp->device),
&to_mucontext(qp->uobject->context)->uar,
to_mucontext(qp->uobject->context)->db_tab,
to_mqp(qp)->sq.db_index);
mthca_unmap_user_db(to_mdev(qp->device),
&to_mucontext(qp->uobject->context)->uar,
to_mucontext(qp->uobject->context)->db_tab,
to_mqp(qp)->rq.db_index);
}
mthca_free_qp(to_mdev(qp->device), to_mqp(qp));
kfree(qp);
return 0;
}
static struct ib_cq *mthca_create_cq(struct ib_device *ibdev, int entries,
int comp_vector,
struct ib_ucontext *context,
struct ib_udata *udata)
{
struct mthca_create_cq ucmd;
struct mthca_cq *cq;
int nent;
int err;
if (entries < 1 || entries > to_mdev(ibdev)->limits.max_cqes)
return ERR_PTR(-EINVAL);
if (context) {
if (ib_copy_from_udata(&ucmd, udata, sizeof ucmd))
return ERR_PTR(-EFAULT);
err = mthca_map_user_db(to_mdev(ibdev), &to_mucontext(context)->uar,
to_mucontext(context)->db_tab,
ucmd.set_db_index, ucmd.set_db_page);
if (err)
return ERR_PTR(err);
err = mthca_map_user_db(to_mdev(ibdev), &to_mucontext(context)->uar,
to_mucontext(context)->db_tab,
ucmd.arm_db_index, ucmd.arm_db_page);
if (err)
goto err_unmap_set;
}
cq = kmalloc(sizeof *cq, GFP_KERNEL);
if (!cq) {
err = -ENOMEM;
goto err_unmap_arm;
}
if (context) {
cq->buf.mr.ibmr.lkey = ucmd.lkey;
cq->set_ci_db_index = ucmd.set_db_index;
cq->arm_db_index = ucmd.arm_db_index;
}
for (nent = 1; nent <= entries; nent <<= 1)
; /* nothing */
err = mthca_init_cq(to_mdev(ibdev), nent,
context ? to_mucontext(context) : NULL,
context ? ucmd.pdn : to_mdev(ibdev)->driver_pd.pd_num,
cq);
if (err)
goto err_free;
if (context && ib_copy_to_udata(udata, &cq->cqn, sizeof (__u32))) {
mthca_free_cq(to_mdev(ibdev), cq);
goto err_free;
}
cq->resize_buf = NULL;
return &cq->ibcq;
err_free:
kfree(cq);
err_unmap_arm:
if (context)
mthca_unmap_user_db(to_mdev(ibdev), &to_mucontext(context)->uar,
to_mucontext(context)->db_tab, ucmd.arm_db_index);
err_unmap_set:
if (context)
mthca_unmap_user_db(to_mdev(ibdev), &to_mucontext(context)->uar,
to_mucontext(context)->db_tab, ucmd.set_db_index);
return ERR_PTR(err);
}
static int mthca_alloc_resize_buf(struct mthca_dev *dev, struct mthca_cq *cq,
int entries)
{
int ret;
spin_lock_irq(&cq->lock);
if (cq->resize_buf) {
ret = -EBUSY;
goto unlock;
}
cq->resize_buf = kmalloc(sizeof *cq->resize_buf, GFP_ATOMIC);
if (!cq->resize_buf) {
ret = -ENOMEM;
goto unlock;
}
cq->resize_buf->state = CQ_RESIZE_ALLOC;
ret = 0;
unlock:
spin_unlock_irq(&cq->lock);
if (ret)
return ret;
ret = mthca_alloc_cq_buf(dev, &cq->resize_buf->buf, entries);
if (ret) {
spin_lock_irq(&cq->lock);
kfree(cq->resize_buf);
cq->resize_buf = NULL;
spin_unlock_irq(&cq->lock);
return ret;
}
cq->resize_buf->cqe = entries - 1;
spin_lock_irq(&cq->lock);
cq->resize_buf->state = CQ_RESIZE_READY;
spin_unlock_irq(&cq->lock);
return 0;
}
static int mthca_resize_cq(struct ib_cq *ibcq, int entries, struct ib_udata *udata)
{
struct mthca_dev *dev = to_mdev(ibcq->device);
struct mthca_cq *cq = to_mcq(ibcq);
struct mthca_resize_cq ucmd;
u32 lkey;
int ret;
if (entries < 1 || entries > dev->limits.max_cqes)
return -EINVAL;
mutex_lock(&cq->mutex);
entries = roundup_pow_of_two(entries + 1);
if (entries == ibcq->cqe + 1) {
ret = 0;
goto out;
}
if (cq->is_kernel) {
ret = mthca_alloc_resize_buf(dev, cq, entries);
if (ret)
goto out;
lkey = cq->resize_buf->buf.mr.ibmr.lkey;
} else {
if (ib_copy_from_udata(&ucmd, udata, sizeof ucmd)) {
ret = -EFAULT;
goto out;
}
lkey = ucmd.lkey;
}
ret = mthca_RESIZE_CQ(dev, cq->cqn, lkey, ilog2(entries));
if (ret) {
if (cq->resize_buf) {
mthca_free_cq_buf(dev, &cq->resize_buf->buf,
cq->resize_buf->cqe);
kfree(cq->resize_buf);
spin_lock_irq(&cq->lock);
cq->resize_buf = NULL;
spin_unlock_irq(&cq->lock);
}
goto out;
}
if (cq->is_kernel) {
struct mthca_cq_buf tbuf;
int tcqe;
spin_lock_irq(&cq->lock);
if (cq->resize_buf->state == CQ_RESIZE_READY) {
mthca_cq_resize_copy_cqes(cq);
tbuf = cq->buf;
tcqe = cq->ibcq.cqe;
cq->buf = cq->resize_buf->buf;
cq->ibcq.cqe = cq->resize_buf->cqe;
} else {
tbuf = cq->resize_buf->buf;
tcqe = cq->resize_buf->cqe;
}
kfree(cq->resize_buf);
cq->resize_buf = NULL;
spin_unlock_irq(&cq->lock);
mthca_free_cq_buf(dev, &tbuf, tcqe);
} else
ibcq->cqe = entries - 1;
out:
mutex_unlock(&cq->mutex);
return ret;
}
static int mthca_destroy_cq(struct ib_cq *cq)
{
if (cq->uobject) {
mthca_unmap_user_db(to_mdev(cq->device),
&to_mucontext(cq->uobject->context)->uar,
to_mucontext(cq->uobject->context)->db_tab,
to_mcq(cq)->arm_db_index);
mthca_unmap_user_db(to_mdev(cq->device),
&to_mucontext(cq->uobject->context)->uar,
to_mucontext(cq->uobject->context)->db_tab,
to_mcq(cq)->set_ci_db_index);
}
mthca_free_cq(to_mdev(cq->device), to_mcq(cq));
kfree(cq);
return 0;
}
static inline u32 convert_access(int acc)
{
return (acc & IB_ACCESS_REMOTE_ATOMIC ? MTHCA_MPT_FLAG_ATOMIC : 0) |
(acc & IB_ACCESS_REMOTE_WRITE ? MTHCA_MPT_FLAG_REMOTE_WRITE : 0) |
(acc & IB_ACCESS_REMOTE_READ ? MTHCA_MPT_FLAG_REMOTE_READ : 0) |
(acc & IB_ACCESS_LOCAL_WRITE ? MTHCA_MPT_FLAG_LOCAL_WRITE : 0) |
MTHCA_MPT_FLAG_LOCAL_READ;
}
static struct ib_mr *mthca_get_dma_mr(struct ib_pd *pd, int acc)
{
struct mthca_mr *mr;
int err;
mr = kmalloc(sizeof *mr, GFP_KERNEL);
if (!mr)
return ERR_PTR(-ENOMEM);
err = mthca_mr_alloc_notrans(to_mdev(pd->device),
to_mpd(pd)->pd_num,
convert_access(acc), mr);
if (err) {
kfree(mr);
return ERR_PTR(err);
}
mr->umem = NULL;
return &mr->ibmr;
}
static struct ib_mr *mthca_reg_phys_mr(struct ib_pd *pd,
struct ib_phys_buf *buffer_list,
int num_phys_buf,
int acc,
u64 *iova_start)
{
struct mthca_mr *mr;
u64 *page_list;
u64 total_size;
unsigned long mask;
int shift;
int npages;
int err;
int i, j, n;
mask = buffer_list[0].addr ^ *iova_start;
total_size = 0;
for (i = 0; i < num_phys_buf; ++i) {
if (i != 0)
mask |= buffer_list[i].addr;
if (i != num_phys_buf - 1)
mask |= buffer_list[i].addr + buffer_list[i].size;
total_size += buffer_list[i].size;
}
if (mask & ~PAGE_MASK)
return ERR_PTR(-EINVAL);
shift = __ffs(mask | 1 << 31);
buffer_list[0].size += buffer_list[0].addr & ((1ULL << shift) - 1);
buffer_list[0].addr &= ~0ull << shift;
mr = kmalloc(sizeof *mr, GFP_KERNEL);
if (!mr)
return ERR_PTR(-ENOMEM);
npages = 0;
for (i = 0; i < num_phys_buf; ++i)
npages += (buffer_list[i].size + (1ULL << shift) - 1) >> shift;
if (!npages)
return &mr->ibmr;
page_list = kmalloc(npages * sizeof *page_list, GFP_KERNEL);
if (!page_list) {
kfree(mr);
return ERR_PTR(-ENOMEM);
}
n = 0;
for (i = 0; i < num_phys_buf; ++i)
for (j = 0;
j < (buffer_list[i].size + (1ULL << shift) - 1) >> shift;
++j)
page_list[n++] = buffer_list[i].addr + ((u64) j << shift);
mthca_dbg(to_mdev(pd->device), "Registering memory at %llx (iova %llx) "
"in PD %x; shift %d, npages %d.\n",
(unsigned long long) buffer_list[0].addr,
(unsigned long long) *iova_start,
to_mpd(pd)->pd_num,
shift, npages);
err = mthca_mr_alloc_phys(to_mdev(pd->device),
to_mpd(pd)->pd_num,
page_list, shift, npages,
*iova_start, total_size,
convert_access(acc), mr);
if (err) {
kfree(page_list);
kfree(mr);
return ERR_PTR(err);
}
kfree(page_list);
mr->umem = NULL;
return &mr->ibmr;
}
static struct ib_mr *mthca_reg_user_mr(struct ib_pd *pd, u64 start, u64 length,
u64 virt, int acc, struct ib_udata *udata)
{
struct mthca_dev *dev = to_mdev(pd->device);
struct ib_umem_chunk *chunk;
struct mthca_mr *mr;
struct mthca_reg_mr ucmd;
u64 *pages;
int shift, n, len;
int i, j, k;
int err = 0;
int write_mtt_size;
if (udata->inlen - sizeof (struct ib_uverbs_cmd_hdr) < sizeof ucmd) {
if (!to_mucontext(pd->uobject->context)->reg_mr_warned) {
mthca_warn(dev, "Process '%s' did not pass in MR attrs.\n",
current->comm);
mthca_warn(dev, " Update libmthca to fix this.\n");
}
++to_mucontext(pd->uobject->context)->reg_mr_warned;
ucmd.mr_attrs = 0;
} else if (ib_copy_from_udata(&ucmd, udata, sizeof ucmd))
return ERR_PTR(-EFAULT);
mr = kmalloc(sizeof *mr, GFP_KERNEL);
if (!mr)
return ERR_PTR(-ENOMEM);
mr->umem = ib_umem_get(pd->uobject->context, start, length, acc,
ucmd.mr_attrs & MTHCA_MR_DMASYNC);
if (IS_ERR(mr->umem)) {
err = PTR_ERR(mr->umem);
goto err;
}
shift = ffs(mr->umem->page_size) - 1;
n = 0;
list_for_each_entry(chunk, &mr->umem->chunk_list, list)
n += chunk->nents;
mr->mtt = mthca_alloc_mtt(dev, n);
if (IS_ERR(mr->mtt)) {
err = PTR_ERR(mr->mtt);
goto err_umem;
}
pages = (u64 *) __get_free_page(GFP_KERNEL);
if (!pages) {
err = -ENOMEM;
goto err_mtt;
}
i = n = 0;
write_mtt_size = min(mthca_write_mtt_size(dev), (int) (PAGE_SIZE / sizeof *pages));
list_for_each_entry(chunk, &mr->umem->chunk_list, list)
for (j = 0; j < chunk->nmap; ++j) {
len = sg_dma_len(&chunk->page_list[j]) >> shift;
for (k = 0; k < len; ++k) {
pages[i++] = sg_dma_address(&chunk->page_list[j]) +
mr->umem->page_size * k;
/*
* Be friendly to write_mtt and pass it chunks
* of appropriate size.
*/
if (i == write_mtt_size) {
err = mthca_write_mtt(dev, mr->mtt, n, pages, i);
if (err)
goto mtt_done;
n += i;
i = 0;
}
}
}
if (i)
err = mthca_write_mtt(dev, mr->mtt, n, pages, i);
mtt_done:
free_page((unsigned long) pages);
if (err)
goto err_mtt;
err = mthca_mr_alloc(dev, to_mpd(pd)->pd_num, shift, virt, length,
convert_access(acc), mr);
if (err)
goto err_mtt;
return &mr->ibmr;
err_mtt:
mthca_free_mtt(dev, mr->mtt);
err_umem:
ib_umem_release(mr->umem);
err:
kfree(mr);
return ERR_PTR(err);
}
static int mthca_dereg_mr(struct ib_mr *mr)
{
struct mthca_mr *mmr = to_mmr(mr);
mthca_free_mr(to_mdev(mr->device), mmr);
if (mmr->umem)
ib_umem_release(mmr->umem);
kfree(mmr);
return 0;
}
static struct ib_fmr *mthca_alloc_fmr(struct ib_pd *pd, int mr_access_flags,
struct ib_fmr_attr *fmr_attr)
{
struct mthca_fmr *fmr;
int err;
fmr = kmalloc(sizeof *fmr, GFP_KERNEL);
if (!fmr)
return ERR_PTR(-ENOMEM);
memcpy(&fmr->attr, fmr_attr, sizeof *fmr_attr);
err = mthca_fmr_alloc(to_mdev(pd->device), to_mpd(pd)->pd_num,
convert_access(mr_access_flags), fmr);
if (err) {
kfree(fmr);
return ERR_PTR(err);
}
return &fmr->ibmr;
}
static int mthca_dealloc_fmr(struct ib_fmr *fmr)
{
struct mthca_fmr *mfmr = to_mfmr(fmr);
int err;
err = mthca_free_fmr(to_mdev(fmr->device), mfmr);
if (err)
return err;
kfree(mfmr);
return 0;
}
static int mthca_unmap_fmr(struct list_head *fmr_list)
{
struct ib_fmr *fmr;
int err;
struct mthca_dev *mdev = NULL;
list_for_each_entry(fmr, fmr_list, list) {
if (mdev && to_mdev(fmr->device) != mdev)
return -EINVAL;
mdev = to_mdev(fmr->device);
}
if (!mdev)
return 0;
if (mthca_is_memfree(mdev)) {
list_for_each_entry(fmr, fmr_list, list)
mthca_arbel_fmr_unmap(mdev, to_mfmr(fmr));
wmb();
} else
list_for_each_entry(fmr, fmr_list, list)
mthca_tavor_fmr_unmap(mdev, to_mfmr(fmr));
err = mthca_SYNC_TPT(mdev);
return err;
}
static ssize_t show_rev(struct device *device, struct device_attribute *attr,
char *buf)
{
struct mthca_dev *dev =
container_of(device, struct mthca_dev, ib_dev.dev);
return sprintf(buf, "%x\n", dev->rev_id);
}
static ssize_t show_fw_ver(struct device *device, struct device_attribute *attr,
char *buf)
{
struct mthca_dev *dev =
container_of(device, struct mthca_dev, ib_dev.dev);
return sprintf(buf, "%d.%d.%d\n", (int) (dev->fw_ver >> 32),
(int) (dev->fw_ver >> 16) & 0xffff,
(int) dev->fw_ver & 0xffff);
}
static ssize_t show_hca(struct device *device, struct device_attribute *attr,
char *buf)
{
struct mthca_dev *dev =
container_of(device, struct mthca_dev, ib_dev.dev);
switch (dev->pdev->device) {
case PCI_DEVICE_ID_MELLANOX_TAVOR:
return sprintf(buf, "MT23108\n");
case PCI_DEVICE_ID_MELLANOX_ARBEL_COMPAT:
return sprintf(buf, "MT25208 (MT23108 compat mode)\n");
case PCI_DEVICE_ID_MELLANOX_ARBEL:
return sprintf(buf, "MT25208\n");
case PCI_DEVICE_ID_MELLANOX_SINAI:
case PCI_DEVICE_ID_MELLANOX_SINAI_OLD:
return sprintf(buf, "MT25204\n");
default:
return sprintf(buf, "unknown\n");
}
}
static ssize_t show_board(struct device *device, struct device_attribute *attr,
char *buf)
{
struct mthca_dev *dev =
container_of(device, struct mthca_dev, ib_dev.dev);
return sprintf(buf, "%.*s\n", MTHCA_BOARD_ID_LEN, dev->board_id);
}
static DEVICE_ATTR(hw_rev, S_IRUGO, show_rev, NULL);
static DEVICE_ATTR(fw_ver, S_IRUGO, show_fw_ver, NULL);
static DEVICE_ATTR(hca_type, S_IRUGO, show_hca, NULL);
static DEVICE_ATTR(board_id, S_IRUGO, show_board, NULL);
static struct device_attribute *mthca_dev_attributes[] = {
&dev_attr_hw_rev,
&dev_attr_fw_ver,
&dev_attr_hca_type,
&dev_attr_board_id
};
static int mthca_init_node_data(struct mthca_dev *dev)
{
struct ib_smp *in_mad = NULL;
struct ib_smp *out_mad = NULL;
int err = -ENOMEM;
in_mad = kzalloc(sizeof *in_mad, GFP_KERNEL);
out_mad = kmalloc(sizeof *out_mad, GFP_KERNEL);
if (!in_mad || !out_mad)
goto out;
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_NODE_DESC;
err = mthca_MAD_IFC(dev, 1, 1,
1, NULL, NULL, in_mad, out_mad);
if (err)
goto out;
memcpy(dev->ib_dev.node_desc, out_mad->data, 64);
in_mad->attr_id = IB_SMP_ATTR_NODE_INFO;
err = mthca_MAD_IFC(dev, 1, 1,
1, NULL, NULL, in_mad, out_mad);
if (err)
goto out;
if (mthca_is_memfree(dev))
dev->rev_id = be32_to_cpup((__be32 *) (out_mad->data + 32));
memcpy(&dev->ib_dev.node_guid, out_mad->data + 12, 8);
out:
kfree(in_mad);
kfree(out_mad);
return err;
}
int mthca_register_device(struct mthca_dev *dev)
{
int ret;
int i;
ret = mthca_init_node_data(dev);
if (ret)
return ret;
strlcpy(dev->ib_dev.name, "mthca%d", IB_DEVICE_NAME_MAX);
dev->ib_dev.owner = THIS_MODULE;
dev->ib_dev.uverbs_abi_ver = MTHCA_UVERBS_ABI_VERSION;
dev->ib_dev.uverbs_cmd_mask =
(1ull << IB_USER_VERBS_CMD_GET_CONTEXT) |
(1ull << IB_USER_VERBS_CMD_QUERY_DEVICE) |
(1ull << IB_USER_VERBS_CMD_QUERY_PORT) |
(1ull << IB_USER_VERBS_CMD_ALLOC_PD) |
(1ull << IB_USER_VERBS_CMD_DEALLOC_PD) |
(1ull << IB_USER_VERBS_CMD_REG_MR) |
(1ull << IB_USER_VERBS_CMD_DEREG_MR) |
(1ull << IB_USER_VERBS_CMD_CREATE_COMP_CHANNEL) |
(1ull << IB_USER_VERBS_CMD_CREATE_CQ) |
(1ull << IB_USER_VERBS_CMD_RESIZE_CQ) |
(1ull << IB_USER_VERBS_CMD_DESTROY_CQ) |
(1ull << IB_USER_VERBS_CMD_CREATE_QP) |
(1ull << IB_USER_VERBS_CMD_QUERY_QP) |
(1ull << IB_USER_VERBS_CMD_MODIFY_QP) |
(1ull << IB_USER_VERBS_CMD_DESTROY_QP) |
(1ull << IB_USER_VERBS_CMD_ATTACH_MCAST) |
(1ull << IB_USER_VERBS_CMD_DETACH_MCAST);
dev->ib_dev.node_type = RDMA_NODE_IB_CA;
dev->ib_dev.phys_port_cnt = dev->limits.num_ports;
dev->ib_dev.num_comp_vectors = 1;
dev->ib_dev.dma_device = &dev->pdev->dev;
dev->ib_dev.query_device = mthca_query_device;
dev->ib_dev.query_port = mthca_query_port;
dev->ib_dev.modify_device = mthca_modify_device;
dev->ib_dev.modify_port = mthca_modify_port;
dev->ib_dev.query_pkey = mthca_query_pkey;
dev->ib_dev.query_gid = mthca_query_gid;
dev->ib_dev.alloc_ucontext = mthca_alloc_ucontext;
dev->ib_dev.dealloc_ucontext = mthca_dealloc_ucontext;
dev->ib_dev.mmap = mthca_mmap_uar;
dev->ib_dev.alloc_pd = mthca_alloc_pd;
dev->ib_dev.dealloc_pd = mthca_dealloc_pd;
dev->ib_dev.create_ah = mthca_ah_create;
dev->ib_dev.query_ah = mthca_ah_query;
dev->ib_dev.destroy_ah = mthca_ah_destroy;
if (dev->mthca_flags & MTHCA_FLAG_SRQ) {
dev->ib_dev.create_srq = mthca_create_srq;
dev->ib_dev.modify_srq = mthca_modify_srq;
dev->ib_dev.query_srq = mthca_query_srq;
dev->ib_dev.destroy_srq = mthca_destroy_srq;
dev->ib_dev.uverbs_cmd_mask |=
(1ull << IB_USER_VERBS_CMD_CREATE_SRQ) |
(1ull << IB_USER_VERBS_CMD_MODIFY_SRQ) |
(1ull << IB_USER_VERBS_CMD_QUERY_SRQ) |
(1ull << IB_USER_VERBS_CMD_DESTROY_SRQ);
if (mthca_is_memfree(dev))
dev->ib_dev.post_srq_recv = mthca_arbel_post_srq_recv;
else
dev->ib_dev.post_srq_recv = mthca_tavor_post_srq_recv;
}
dev->ib_dev.create_qp = mthca_create_qp;
dev->ib_dev.modify_qp = mthca_modify_qp;
dev->ib_dev.query_qp = mthca_query_qp;
dev->ib_dev.destroy_qp = mthca_destroy_qp;
dev->ib_dev.create_cq = mthca_create_cq;
dev->ib_dev.resize_cq = mthca_resize_cq;
dev->ib_dev.destroy_cq = mthca_destroy_cq;
dev->ib_dev.poll_cq = mthca_poll_cq;
dev->ib_dev.get_dma_mr = mthca_get_dma_mr;
dev->ib_dev.reg_phys_mr = mthca_reg_phys_mr;
dev->ib_dev.reg_user_mr = mthca_reg_user_mr;
dev->ib_dev.dereg_mr = mthca_dereg_mr;
if (dev->mthca_flags & MTHCA_FLAG_FMR) {
dev->ib_dev.alloc_fmr = mthca_alloc_fmr;
dev->ib_dev.unmap_fmr = mthca_unmap_fmr;
dev->ib_dev.dealloc_fmr = mthca_dealloc_fmr;
if (mthca_is_memfree(dev))
dev->ib_dev.map_phys_fmr = mthca_arbel_map_phys_fmr;
else
dev->ib_dev.map_phys_fmr = mthca_tavor_map_phys_fmr;
}
dev->ib_dev.attach_mcast = mthca_multicast_attach;
dev->ib_dev.detach_mcast = mthca_multicast_detach;
dev->ib_dev.process_mad = mthca_process_mad;
if (mthca_is_memfree(dev)) {
dev->ib_dev.req_notify_cq = mthca_arbel_arm_cq;
dev->ib_dev.post_send = mthca_arbel_post_send;
dev->ib_dev.post_recv = mthca_arbel_post_receive;
} else {
dev->ib_dev.req_notify_cq = mthca_tavor_arm_cq;
dev->ib_dev.post_send = mthca_tavor_post_send;
dev->ib_dev.post_recv = mthca_tavor_post_receive;
}
mutex_init(&dev->cap_mask_mutex);
ret = ib_register_device(&dev->ib_dev, NULL);
if (ret)
return ret;
for (i = 0; i < ARRAY_SIZE(mthca_dev_attributes); ++i) {
ret = device_create_file(&dev->ib_dev.dev,
mthca_dev_attributes[i]);
if (ret) {
ib_unregister_device(&dev->ib_dev);
return ret;
}
}
mthca_start_catas_poll(dev);
return 0;
}
void mthca_unregister_device(struct mthca_dev *dev)
{
mthca_stop_catas_poll(dev);
ib_unregister_device(&dev->ib_dev);
}
| gpl-2.0 |
cm-b2g/platform_kernel_lge_msm | drivers/tty/serial/8250/8250_fsl.c | 7888 | 1804 | #include <linux/serial_reg.h>
#include <linux/serial_8250.h>
#include "8250.h"
/*
* Freescale 16550 UART "driver", Copyright (C) 2011 Paul Gortmaker.
*
* 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 isn't a full driver; it just provides an alternate IRQ
* handler to deal with an errata. Everything else is just
* using the bog standard 8250 support.
*
* We follow code flow of serial8250_default_handle_irq() but add
* a check for a break and insert a dummy read on the Rx for the
* immediately following IRQ event.
*
* We re-use the already existing "bug handling" lsr_saved_flags
* field to carry the "what we just did" information from the one
* IRQ event to the next one.
*/
int fsl8250_handle_irq(struct uart_port *port)
{
unsigned char lsr, orig_lsr;
unsigned long flags;
unsigned int iir;
struct uart_8250_port *up =
container_of(port, struct uart_8250_port, port);
spin_lock_irqsave(&up->port.lock, flags);
iir = port->serial_in(port, UART_IIR);
if (iir & UART_IIR_NO_INT) {
spin_unlock_irqrestore(&up->port.lock, flags);
return 0;
}
/* This is the WAR; if last event was BRK, then read and return */
if (unlikely(up->lsr_saved_flags & UART_LSR_BI)) {
up->lsr_saved_flags &= ~UART_LSR_BI;
port->serial_in(port, UART_RX);
spin_unlock_irqrestore(&up->port.lock, flags);
return 1;
}
lsr = orig_lsr = up->port.serial_in(&up->port, UART_LSR);
if (lsr & (UART_LSR_DR | UART_LSR_BI))
lsr = serial8250_rx_chars(up, lsr);
serial8250_modem_status(up);
if (lsr & UART_LSR_THRE)
serial8250_tx_chars(up);
up->lsr_saved_flags = orig_lsr;
spin_unlock_irqrestore(&up->port.lock, flags);
return 1;
}
| gpl-2.0 |
kapdop/android_kernel_oneplus_msm8974 | drivers/platform/x86/xo15-ebook.c | 7888 | 4238 | /*
* OLPC XO-1.5 ebook switch driver
* (based on generic ACPI button driver)
*
* Copyright (C) 2009 Paul Fox <pgf@laptop.org>
* Copyright (C) 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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/input.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#define MODULE_NAME "xo15-ebook"
#define XO15_EBOOK_CLASS MODULE_NAME
#define XO15_EBOOK_TYPE_UNKNOWN 0x00
#define XO15_EBOOK_NOTIFY_STATUS 0x80
#define XO15_EBOOK_SUBCLASS "ebook"
#define XO15_EBOOK_HID "XO15EBK"
#define XO15_EBOOK_DEVICE_NAME "EBook Switch"
ACPI_MODULE_NAME(MODULE_NAME);
MODULE_DESCRIPTION("OLPC XO-1.5 ebook switch driver");
MODULE_LICENSE("GPL");
static const struct acpi_device_id ebook_device_ids[] = {
{ XO15_EBOOK_HID, 0 },
{ "", 0 },
};
MODULE_DEVICE_TABLE(acpi, ebook_device_ids);
struct ebook_switch {
struct input_dev *input;
char phys[32]; /* for input device */
};
static int ebook_send_state(struct acpi_device *device)
{
struct ebook_switch *button = acpi_driver_data(device);
unsigned long long state;
acpi_status status;
status = acpi_evaluate_integer(device->handle, "EBK", NULL, &state);
if (ACPI_FAILURE(status))
return -EIO;
/* input layer checks if event is redundant */
input_report_switch(button->input, SW_TABLET_MODE, !state);
input_sync(button->input);
return 0;
}
static void ebook_switch_notify(struct acpi_device *device, u32 event)
{
switch (event) {
case ACPI_FIXED_HARDWARE_EVENT:
case XO15_EBOOK_NOTIFY_STATUS:
ebook_send_state(device);
break;
default:
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Unsupported event [0x%x]\n", event));
break;
}
}
static int ebook_switch_resume(struct acpi_device *device)
{
return ebook_send_state(device);
}
static int ebook_switch_add(struct acpi_device *device)
{
struct ebook_switch *button;
struct input_dev *input;
const char *hid = acpi_device_hid(device);
char *name, *class;
int error;
button = kzalloc(sizeof(struct ebook_switch), GFP_KERNEL);
if (!button)
return -ENOMEM;
device->driver_data = button;
button->input = input = input_allocate_device();
if (!input) {
error = -ENOMEM;
goto err_free_button;
}
name = acpi_device_name(device);
class = acpi_device_class(device);
if (strcmp(hid, XO15_EBOOK_HID)) {
pr_err("Unsupported hid [%s]\n", hid);
error = -ENODEV;
goto err_free_input;
}
strcpy(name, XO15_EBOOK_DEVICE_NAME);
sprintf(class, "%s/%s", XO15_EBOOK_CLASS, XO15_EBOOK_SUBCLASS);
snprintf(button->phys, sizeof(button->phys), "%s/button/input0", hid);
input->name = name;
input->phys = button->phys;
input->id.bustype = BUS_HOST;
input->dev.parent = &device->dev;
input->evbit[0] = BIT_MASK(EV_SW);
set_bit(SW_TABLET_MODE, input->swbit);
error = input_register_device(input);
if (error)
goto err_free_input;
ebook_send_state(device);
if (device->wakeup.flags.valid) {
/* Button's GPE is run-wake GPE */
acpi_enable_gpe(device->wakeup.gpe_device,
device->wakeup.gpe_number);
device_set_wakeup_enable(&device->dev, true);
}
return 0;
err_free_input:
input_free_device(input);
err_free_button:
kfree(button);
return error;
}
static int ebook_switch_remove(struct acpi_device *device, int type)
{
struct ebook_switch *button = acpi_driver_data(device);
input_unregister_device(button->input);
kfree(button);
return 0;
}
static struct acpi_driver xo15_ebook_driver = {
.name = MODULE_NAME,
.class = XO15_EBOOK_CLASS,
.ids = ebook_device_ids,
.ops = {
.add = ebook_switch_add,
.resume = ebook_switch_resume,
.remove = ebook_switch_remove,
.notify = ebook_switch_notify,
},
};
static int __init xo15_ebook_init(void)
{
return acpi_bus_register_driver(&xo15_ebook_driver);
}
static void __exit xo15_ebook_exit(void)
{
acpi_bus_unregister_driver(&xo15_ebook_driver);
}
module_init(xo15_ebook_init);
module_exit(xo15_ebook_exit);
| gpl-2.0 |
androidarmv6/android_kernel_lge_msm7x27-3.0.x | drivers/platform/x86/xo15-ebook.c | 7888 | 4238 | /*
* OLPC XO-1.5 ebook switch driver
* (based on generic ACPI button driver)
*
* Copyright (C) 2009 Paul Fox <pgf@laptop.org>
* Copyright (C) 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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/input.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#define MODULE_NAME "xo15-ebook"
#define XO15_EBOOK_CLASS MODULE_NAME
#define XO15_EBOOK_TYPE_UNKNOWN 0x00
#define XO15_EBOOK_NOTIFY_STATUS 0x80
#define XO15_EBOOK_SUBCLASS "ebook"
#define XO15_EBOOK_HID "XO15EBK"
#define XO15_EBOOK_DEVICE_NAME "EBook Switch"
ACPI_MODULE_NAME(MODULE_NAME);
MODULE_DESCRIPTION("OLPC XO-1.5 ebook switch driver");
MODULE_LICENSE("GPL");
static const struct acpi_device_id ebook_device_ids[] = {
{ XO15_EBOOK_HID, 0 },
{ "", 0 },
};
MODULE_DEVICE_TABLE(acpi, ebook_device_ids);
struct ebook_switch {
struct input_dev *input;
char phys[32]; /* for input device */
};
static int ebook_send_state(struct acpi_device *device)
{
struct ebook_switch *button = acpi_driver_data(device);
unsigned long long state;
acpi_status status;
status = acpi_evaluate_integer(device->handle, "EBK", NULL, &state);
if (ACPI_FAILURE(status))
return -EIO;
/* input layer checks if event is redundant */
input_report_switch(button->input, SW_TABLET_MODE, !state);
input_sync(button->input);
return 0;
}
static void ebook_switch_notify(struct acpi_device *device, u32 event)
{
switch (event) {
case ACPI_FIXED_HARDWARE_EVENT:
case XO15_EBOOK_NOTIFY_STATUS:
ebook_send_state(device);
break;
default:
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Unsupported event [0x%x]\n", event));
break;
}
}
static int ebook_switch_resume(struct acpi_device *device)
{
return ebook_send_state(device);
}
static int ebook_switch_add(struct acpi_device *device)
{
struct ebook_switch *button;
struct input_dev *input;
const char *hid = acpi_device_hid(device);
char *name, *class;
int error;
button = kzalloc(sizeof(struct ebook_switch), GFP_KERNEL);
if (!button)
return -ENOMEM;
device->driver_data = button;
button->input = input = input_allocate_device();
if (!input) {
error = -ENOMEM;
goto err_free_button;
}
name = acpi_device_name(device);
class = acpi_device_class(device);
if (strcmp(hid, XO15_EBOOK_HID)) {
pr_err("Unsupported hid [%s]\n", hid);
error = -ENODEV;
goto err_free_input;
}
strcpy(name, XO15_EBOOK_DEVICE_NAME);
sprintf(class, "%s/%s", XO15_EBOOK_CLASS, XO15_EBOOK_SUBCLASS);
snprintf(button->phys, sizeof(button->phys), "%s/button/input0", hid);
input->name = name;
input->phys = button->phys;
input->id.bustype = BUS_HOST;
input->dev.parent = &device->dev;
input->evbit[0] = BIT_MASK(EV_SW);
set_bit(SW_TABLET_MODE, input->swbit);
error = input_register_device(input);
if (error)
goto err_free_input;
ebook_send_state(device);
if (device->wakeup.flags.valid) {
/* Button's GPE is run-wake GPE */
acpi_enable_gpe(device->wakeup.gpe_device,
device->wakeup.gpe_number);
device_set_wakeup_enable(&device->dev, true);
}
return 0;
err_free_input:
input_free_device(input);
err_free_button:
kfree(button);
return error;
}
static int ebook_switch_remove(struct acpi_device *device, int type)
{
struct ebook_switch *button = acpi_driver_data(device);
input_unregister_device(button->input);
kfree(button);
return 0;
}
static struct acpi_driver xo15_ebook_driver = {
.name = MODULE_NAME,
.class = XO15_EBOOK_CLASS,
.ids = ebook_device_ids,
.ops = {
.add = ebook_switch_add,
.resume = ebook_switch_resume,
.remove = ebook_switch_remove,
.notify = ebook_switch_notify,
},
};
static int __init xo15_ebook_init(void)
{
return acpi_bus_register_driver(&xo15_ebook_driver);
}
static void __exit xo15_ebook_exit(void)
{
acpi_bus_unregister_driver(&xo15_ebook_driver);
}
module_init(xo15_ebook_init);
module_exit(xo15_ebook_exit);
| gpl-2.0 |
Supervenom/linux-mod_sys_call | net/ipv6/xfrm6_mode_beet.c | 8144 | 3318 | /*
* xfrm6_mode_beet.c - BEET mode encapsulation for IPv6.
*
* Copyright (c) 2006 Diego Beltrami <diego.beltrami@gmail.com>
* Miika Komu <miika@iki.fi>
* Herbert Xu <herbert@gondor.apana.org.au>
* Abhinav Pathak <abhinav.pathak@hiit.fi>
* Jeff Ahrenholz <ahrenholz@gmail.com>
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/stringify.h>
#include <net/dsfield.h>
#include <net/dst.h>
#include <net/inet_ecn.h>
#include <net/ipv6.h>
#include <net/xfrm.h>
static void xfrm6_beet_make_header(struct sk_buff *skb)
{
struct ipv6hdr *iph = ipv6_hdr(skb);
iph->version = 6;
memcpy(iph->flow_lbl, XFRM_MODE_SKB_CB(skb)->flow_lbl,
sizeof(iph->flow_lbl));
iph->nexthdr = XFRM_MODE_SKB_CB(skb)->protocol;
ipv6_change_dsfield(iph, 0, XFRM_MODE_SKB_CB(skb)->tos);
iph->hop_limit = XFRM_MODE_SKB_CB(skb)->ttl;
}
/* Add encapsulation header.
*
* The top IP header will be constructed per draft-nikander-esp-beet-mode-06.txt.
*/
static int xfrm6_beet_output(struct xfrm_state *x, struct sk_buff *skb)
{
struct ipv6hdr *top_iph;
struct ip_beet_phdr *ph;
int optlen, hdr_len;
hdr_len = 0;
optlen = XFRM_MODE_SKB_CB(skb)->optlen;
if (unlikely(optlen))
hdr_len += IPV4_BEET_PHMAXLEN - (optlen & 4);
skb_set_network_header(skb, -x->props.header_len - hdr_len);
if (x->sel.family != AF_INET6)
skb->network_header += IPV4_BEET_PHMAXLEN;
skb->mac_header = skb->network_header +
offsetof(struct ipv6hdr, nexthdr);
skb->transport_header = skb->network_header + sizeof(*top_iph);
ph = (struct ip_beet_phdr *)__skb_pull(skb, XFRM_MODE_SKB_CB(skb)->ihl-hdr_len);
xfrm6_beet_make_header(skb);
top_iph = ipv6_hdr(skb);
if (unlikely(optlen)) {
BUG_ON(optlen < 0);
ph->padlen = 4 - (optlen & 4);
ph->hdrlen = optlen / 8;
ph->nexthdr = top_iph->nexthdr;
if (ph->padlen)
memset(ph + 1, IPOPT_NOP, ph->padlen);
top_iph->nexthdr = IPPROTO_BEETPH;
}
top_iph->saddr = *(struct in6_addr *)&x->props.saddr;
top_iph->daddr = *(struct in6_addr *)&x->id.daddr;
return 0;
}
static int xfrm6_beet_input(struct xfrm_state *x, struct sk_buff *skb)
{
struct ipv6hdr *ip6h;
int size = sizeof(struct ipv6hdr);
int err;
err = skb_cow_head(skb, size + skb->mac_len);
if (err)
goto out;
__skb_push(skb, size);
skb_reset_network_header(skb);
skb_mac_header_rebuild(skb);
xfrm6_beet_make_header(skb);
ip6h = ipv6_hdr(skb);
ip6h->payload_len = htons(skb->len - size);
ip6h->daddr = *(struct in6_addr *)&x->sel.daddr.a6;
ip6h->saddr = *(struct in6_addr *)&x->sel.saddr.a6;
err = 0;
out:
return err;
}
static struct xfrm_mode xfrm6_beet_mode = {
.input2 = xfrm6_beet_input,
.input = xfrm_prepare_input,
.output2 = xfrm6_beet_output,
.output = xfrm6_prepare_output,
.owner = THIS_MODULE,
.encap = XFRM_MODE_BEET,
.flags = XFRM_MODE_FLAG_TUNNEL,
};
static int __init xfrm6_beet_init(void)
{
return xfrm_register_mode(&xfrm6_beet_mode, AF_INET6);
}
static void __exit xfrm6_beet_exit(void)
{
int err;
err = xfrm_unregister_mode(&xfrm6_beet_mode, AF_INET6);
BUG_ON(err);
}
module_init(xfrm6_beet_init);
module_exit(xfrm6_beet_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_XFRM_MODE(AF_INET6, XFRM_MODE_BEET);
| gpl-2.0 |
seyko2/openvz_rhel6_kernel_mirror | drivers/parport/ieee1284_ops.c | 14544 | 23800 | /* IEEE-1284 operations for parport.
*
* This file is for generic IEEE 1284 operations. The idea is that
* they are used by the low-level drivers. If they have a special way
* of doing something, they can provide their own routines (and put
* the function pointers in port->ops); if not, they can just use these
* as a fallback.
*
* Note: Make no assumptions about hardware or architecture in this file!
*
* Author: Tim Waugh <tim@cyberelk.demon.co.uk>
* Fixed AUTOFD polarity in ecp_forward_to_reverse(). Fred Barnes, 1999
* Software emulated EPP fixes, Fred Barnes, 04/2001.
*/
#include <linux/module.h>
#include <linux/parport.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <asm/uaccess.h>
#undef DEBUG /* undef me for production */
#ifdef CONFIG_LP_CONSOLE
#undef DEBUG /* Don't want a garbled console */
#endif
#ifdef DEBUG
#define DPRINTK(stuff...) printk (stuff)
#else
#define DPRINTK(stuff...)
#endif
/*** *
* One-way data transfer functions. *
* ***/
/* Compatibility mode. */
size_t parport_ieee1284_write_compat (struct parport *port,
const void *buffer, size_t len,
int flags)
{
int no_irq = 1;
ssize_t count = 0;
const unsigned char *addr = buffer;
unsigned char byte;
struct pardevice *dev = port->physport->cad;
unsigned char ctl = (PARPORT_CONTROL_SELECT
| PARPORT_CONTROL_INIT);
if (port->irq != PARPORT_IRQ_NONE) {
parport_enable_irq (port);
no_irq = 0;
}
port->physport->ieee1284.phase = IEEE1284_PH_FWD_DATA;
parport_write_control (port, ctl);
parport_data_forward (port);
while (count < len) {
unsigned long expire = jiffies + dev->timeout;
long wait = msecs_to_jiffies(10);
unsigned char mask = (PARPORT_STATUS_ERROR
| PARPORT_STATUS_BUSY);
unsigned char val = (PARPORT_STATUS_ERROR
| PARPORT_STATUS_BUSY);
/* Wait until the peripheral's ready */
do {
/* Is the peripheral ready yet? */
if (!parport_wait_peripheral (port, mask, val))
/* Skip the loop */
goto ready;
/* Is the peripheral upset? */
if ((parport_read_status (port) &
(PARPORT_STATUS_PAPEROUT |
PARPORT_STATUS_SELECT |
PARPORT_STATUS_ERROR))
!= (PARPORT_STATUS_SELECT |
PARPORT_STATUS_ERROR))
/* If nFault is asserted (i.e. no
* error) and PAPEROUT and SELECT are
* just red herrings, give the driver
* a chance to check it's happy with
* that before continuing. */
goto stop;
/* Have we run out of time? */
if (!time_before (jiffies, expire))
break;
/* Yield the port for a while. If this is the
first time around the loop, don't let go of
the port. This way, we find out if we have
our interrupt handler called. */
if (count && no_irq) {
parport_release (dev);
schedule_timeout_interruptible(wait);
parport_claim_or_block (dev);
}
else
/* We must have the device claimed here */
parport_wait_event (port, wait);
/* Is there a signal pending? */
if (signal_pending (current))
break;
/* Wait longer next time. */
wait *= 2;
} while (time_before (jiffies, expire));
if (signal_pending (current))
break;
DPRINTK (KERN_DEBUG "%s: Timed out\n", port->name);
break;
ready:
/* Write the character to the data lines. */
byte = *addr++;
parport_write_data (port, byte);
udelay (1);
/* Pulse strobe. */
parport_write_control (port, ctl | PARPORT_CONTROL_STROBE);
udelay (1); /* strobe */
parport_write_control (port, ctl);
udelay (1); /* hold */
/* Assume the peripheral received it. */
count++;
/* Let another process run if it needs to. */
if (time_before (jiffies, expire))
if (!parport_yield_blocking (dev)
&& need_resched())
schedule ();
}
stop:
port->physport->ieee1284.phase = IEEE1284_PH_FWD_IDLE;
return count;
}
/* Nibble mode. */
size_t parport_ieee1284_read_nibble (struct parport *port,
void *buffer, size_t len,
int flags)
{
#ifndef CONFIG_PARPORT_1284
return 0;
#else
unsigned char *buf = buffer;
int i;
unsigned char byte = 0;
len *= 2; /* in nibbles */
for (i=0; i < len; i++) {
unsigned char nibble;
/* Does the error line indicate end of data? */
if (((i & 1) == 0) &&
(parport_read_status(port) & PARPORT_STATUS_ERROR)) {
goto end_of_data;
}
/* Event 7: Set nAutoFd low. */
parport_frob_control (port,
PARPORT_CONTROL_AUTOFD,
PARPORT_CONTROL_AUTOFD);
/* Event 9: nAck goes low. */
port->ieee1284.phase = IEEE1284_PH_REV_DATA;
if (parport_wait_peripheral (port,
PARPORT_STATUS_ACK, 0)) {
/* Timeout -- no more data? */
DPRINTK (KERN_DEBUG
"%s: Nibble timeout at event 9 (%d bytes)\n",
port->name, i/2);
parport_frob_control (port, PARPORT_CONTROL_AUTOFD, 0);
break;
}
/* Read a nibble. */
nibble = parport_read_status (port) >> 3;
nibble &= ~8;
if ((nibble & 0x10) == 0)
nibble |= 8;
nibble &= 0xf;
/* Event 10: Set nAutoFd high. */
parport_frob_control (port, PARPORT_CONTROL_AUTOFD, 0);
/* Event 11: nAck goes high. */
if (parport_wait_peripheral (port,
PARPORT_STATUS_ACK,
PARPORT_STATUS_ACK)) {
/* Timeout -- no more data? */
DPRINTK (KERN_DEBUG
"%s: Nibble timeout at event 11\n",
port->name);
break;
}
if (i & 1) {
/* Second nibble */
byte |= nibble << 4;
*buf++ = byte;
} else
byte = nibble;
}
if (i == len) {
/* Read the last nibble without checking data avail. */
if (parport_read_status (port) & PARPORT_STATUS_ERROR) {
end_of_data:
DPRINTK (KERN_DEBUG
"%s: No more nibble data (%d bytes)\n",
port->name, i/2);
/* Go to reverse idle phase. */
parport_frob_control (port,
PARPORT_CONTROL_AUTOFD,
PARPORT_CONTROL_AUTOFD);
port->physport->ieee1284.phase = IEEE1284_PH_REV_IDLE;
}
else
port->physport->ieee1284.phase = IEEE1284_PH_HBUSY_DAVAIL;
}
return i/2;
#endif /* IEEE1284 support */
}
/* Byte mode. */
size_t parport_ieee1284_read_byte (struct parport *port,
void *buffer, size_t len,
int flags)
{
#ifndef CONFIG_PARPORT_1284
return 0;
#else
unsigned char *buf = buffer;
ssize_t count = 0;
for (count = 0; count < len; count++) {
unsigned char byte;
/* Data available? */
if (parport_read_status (port) & PARPORT_STATUS_ERROR) {
goto end_of_data;
}
/* Event 14: Place data bus in high impedance state. */
parport_data_reverse (port);
/* Event 7: Set nAutoFd low. */
parport_frob_control (port,
PARPORT_CONTROL_AUTOFD,
PARPORT_CONTROL_AUTOFD);
/* Event 9: nAck goes low. */
port->physport->ieee1284.phase = IEEE1284_PH_REV_DATA;
if (parport_wait_peripheral (port,
PARPORT_STATUS_ACK,
0)) {
/* Timeout -- no more data? */
parport_frob_control (port, PARPORT_CONTROL_AUTOFD,
0);
DPRINTK (KERN_DEBUG "%s: Byte timeout at event 9\n",
port->name);
break;
}
byte = parport_read_data (port);
*buf++ = byte;
/* Event 10: Set nAutoFd high */
parport_frob_control (port, PARPORT_CONTROL_AUTOFD, 0);
/* Event 11: nAck goes high. */
if (parport_wait_peripheral (port,
PARPORT_STATUS_ACK,
PARPORT_STATUS_ACK)) {
/* Timeout -- no more data? */
DPRINTK (KERN_DEBUG "%s: Byte timeout at event 11\n",
port->name);
break;
}
/* Event 16: Set nStrobe low. */
parport_frob_control (port,
PARPORT_CONTROL_STROBE,
PARPORT_CONTROL_STROBE);
udelay (5);
/* Event 17: Set nStrobe high. */
parport_frob_control (port, PARPORT_CONTROL_STROBE, 0);
}
if (count == len) {
/* Read the last byte without checking data avail. */
if (parport_read_status (port) & PARPORT_STATUS_ERROR) {
end_of_data:
DPRINTK (KERN_DEBUG
"%s: No more byte data (%Zd bytes)\n",
port->name, count);
/* Go to reverse idle phase. */
parport_frob_control (port,
PARPORT_CONTROL_AUTOFD,
PARPORT_CONTROL_AUTOFD);
port->physport->ieee1284.phase = IEEE1284_PH_REV_IDLE;
}
else
port->physport->ieee1284.phase = IEEE1284_PH_HBUSY_DAVAIL;
}
return count;
#endif /* IEEE1284 support */
}
/*** *
* ECP Functions. *
* ***/
#ifdef CONFIG_PARPORT_1284
static inline
int ecp_forward_to_reverse (struct parport *port)
{
int retval;
/* Event 38: Set nAutoFd low */
parport_frob_control (port,
PARPORT_CONTROL_AUTOFD,
PARPORT_CONTROL_AUTOFD);
parport_data_reverse (port);
udelay (5);
/* Event 39: Set nInit low to initiate bus reversal */
parport_frob_control (port,
PARPORT_CONTROL_INIT,
0);
/* Event 40: PError goes low */
retval = parport_wait_peripheral (port,
PARPORT_STATUS_PAPEROUT, 0);
if (!retval) {
DPRINTK (KERN_DEBUG "%s: ECP direction: reverse\n",
port->name);
port->ieee1284.phase = IEEE1284_PH_REV_IDLE;
} else {
DPRINTK (KERN_DEBUG "%s: ECP direction: failed to reverse\n",
port->name);
port->ieee1284.phase = IEEE1284_PH_ECP_DIR_UNKNOWN;
}
return retval;
}
static inline
int ecp_reverse_to_forward (struct parport *port)
{
int retval;
/* Event 47: Set nInit high */
parport_frob_control (port,
PARPORT_CONTROL_INIT
| PARPORT_CONTROL_AUTOFD,
PARPORT_CONTROL_INIT
| PARPORT_CONTROL_AUTOFD);
/* Event 49: PError goes high */
retval = parport_wait_peripheral (port,
PARPORT_STATUS_PAPEROUT,
PARPORT_STATUS_PAPEROUT);
if (!retval) {
parport_data_forward (port);
DPRINTK (KERN_DEBUG "%s: ECP direction: forward\n",
port->name);
port->ieee1284.phase = IEEE1284_PH_FWD_IDLE;
} else {
DPRINTK (KERN_DEBUG
"%s: ECP direction: failed to switch forward\n",
port->name);
port->ieee1284.phase = IEEE1284_PH_ECP_DIR_UNKNOWN;
}
return retval;
}
#endif /* IEEE1284 support */
/* ECP mode, forward channel, data. */
size_t parport_ieee1284_ecp_write_data (struct parport *port,
const void *buffer, size_t len,
int flags)
{
#ifndef CONFIG_PARPORT_1284
return 0;
#else
const unsigned char *buf = buffer;
size_t written;
int retry;
port = port->physport;
if (port->ieee1284.phase != IEEE1284_PH_FWD_IDLE)
if (ecp_reverse_to_forward (port))
return 0;
port->ieee1284.phase = IEEE1284_PH_FWD_DATA;
/* HostAck high (data, not command) */
parport_frob_control (port,
PARPORT_CONTROL_AUTOFD
| PARPORT_CONTROL_STROBE
| PARPORT_CONTROL_INIT,
PARPORT_CONTROL_INIT);
for (written = 0; written < len; written++, buf++) {
unsigned long expire = jiffies + port->cad->timeout;
unsigned char byte;
byte = *buf;
try_again:
parport_write_data (port, byte);
parport_frob_control (port, PARPORT_CONTROL_STROBE,
PARPORT_CONTROL_STROBE);
udelay (5);
for (retry = 0; retry < 100; retry++) {
if (!parport_wait_peripheral (port,
PARPORT_STATUS_BUSY, 0))
goto success;
if (signal_pending (current)) {
parport_frob_control (port,
PARPORT_CONTROL_STROBE,
0);
break;
}
}
/* Time for Host Transfer Recovery (page 41 of IEEE1284) */
DPRINTK (KERN_DEBUG "%s: ECP transfer stalled!\n", port->name);
parport_frob_control (port, PARPORT_CONTROL_INIT,
PARPORT_CONTROL_INIT);
udelay (50);
if (parport_read_status (port) & PARPORT_STATUS_PAPEROUT) {
/* It's buggered. */
parport_frob_control (port, PARPORT_CONTROL_INIT, 0);
break;
}
parport_frob_control (port, PARPORT_CONTROL_INIT, 0);
udelay (50);
if (!(parport_read_status (port) & PARPORT_STATUS_PAPEROUT))
break;
DPRINTK (KERN_DEBUG "%s: Host transfer recovered\n",
port->name);
if (time_after_eq (jiffies, expire)) break;
goto try_again;
success:
parport_frob_control (port, PARPORT_CONTROL_STROBE, 0);
udelay (5);
if (parport_wait_peripheral (port,
PARPORT_STATUS_BUSY,
PARPORT_STATUS_BUSY))
/* Peripheral hasn't accepted the data. */
break;
}
port->ieee1284.phase = IEEE1284_PH_FWD_IDLE;
return written;
#endif /* IEEE1284 support */
}
/* ECP mode, reverse channel, data. */
size_t parport_ieee1284_ecp_read_data (struct parport *port,
void *buffer, size_t len, int flags)
{
#ifndef CONFIG_PARPORT_1284
return 0;
#else
struct pardevice *dev = port->cad;
unsigned char *buf = buffer;
int rle_count = 0; /* shut gcc up */
unsigned char ctl;
int rle = 0;
ssize_t count = 0;
port = port->physport;
if (port->ieee1284.phase != IEEE1284_PH_REV_IDLE)
if (ecp_forward_to_reverse (port))
return 0;
port->ieee1284.phase = IEEE1284_PH_REV_DATA;
/* Set HostAck low to start accepting data. */
ctl = parport_read_control (port);
ctl &= ~(PARPORT_CONTROL_STROBE | PARPORT_CONTROL_INIT |
PARPORT_CONTROL_AUTOFD);
parport_write_control (port,
ctl | PARPORT_CONTROL_AUTOFD);
while (count < len) {
unsigned long expire = jiffies + dev->timeout;
unsigned char byte;
int command;
/* Event 43: Peripheral sets nAck low. It can take as
long as it wants. */
while (parport_wait_peripheral (port, PARPORT_STATUS_ACK, 0)) {
/* The peripheral hasn't given us data in
35ms. If we have data to give back to the
caller, do it now. */
if (count)
goto out;
/* If we've used up all the time we were allowed,
give up altogether. */
if (!time_before (jiffies, expire))
goto out;
/* Yield the port for a while. */
if (count && dev->port->irq != PARPORT_IRQ_NONE) {
parport_release (dev);
schedule_timeout_interruptible(msecs_to_jiffies(40));
parport_claim_or_block (dev);
}
else
/* We must have the device claimed here. */
parport_wait_event (port, msecs_to_jiffies(40));
/* Is there a signal pending? */
if (signal_pending (current))
goto out;
}
/* Is this a command? */
if (rle)
/* The last byte was a run-length count, so
this can't be as well. */
command = 0;
else
command = (parport_read_status (port) &
PARPORT_STATUS_BUSY) ? 1 : 0;
/* Read the data. */
byte = parport_read_data (port);
/* If this is a channel command, rather than an RLE
command or a normal data byte, don't accept it. */
if (command) {
if (byte & 0x80) {
DPRINTK (KERN_DEBUG "%s: stopping short at "
"channel command (%02x)\n",
port->name, byte);
goto out;
}
else if (port->ieee1284.mode != IEEE1284_MODE_ECPRLE)
DPRINTK (KERN_DEBUG "%s: device illegally "
"using RLE; accepting anyway\n",
port->name);
rle_count = byte + 1;
/* Are we allowed to read that many bytes? */
if (rle_count > (len - count)) {
DPRINTK (KERN_DEBUG "%s: leaving %d RLE bytes "
"for next time\n", port->name,
rle_count);
break;
}
rle = 1;
}
/* Event 44: Set HostAck high, acknowledging handshake. */
parport_write_control (port, ctl);
/* Event 45: The peripheral has 35ms to set nAck high. */
if (parport_wait_peripheral (port, PARPORT_STATUS_ACK,
PARPORT_STATUS_ACK)) {
/* It's gone wrong. Return what data we have
to the caller. */
DPRINTK (KERN_DEBUG "ECP read timed out at 45\n");
if (command)
printk (KERN_WARNING
"%s: command ignored (%02x)\n",
port->name, byte);
break;
}
/* Event 46: Set HostAck low and accept the data. */
parport_write_control (port,
ctl | PARPORT_CONTROL_AUTOFD);
/* If we just read a run-length count, fetch the data. */
if (command)
continue;
/* If this is the byte after a run-length count, decompress. */
if (rle) {
rle = 0;
memset (buf, byte, rle_count);
buf += rle_count;
count += rle_count;
DPRINTK (KERN_DEBUG "%s: decompressed to %d bytes\n",
port->name, rle_count);
} else {
/* Normal data byte. */
*buf = byte;
buf++, count++;
}
}
out:
port->ieee1284.phase = IEEE1284_PH_REV_IDLE;
return count;
#endif /* IEEE1284 support */
}
/* ECP mode, forward channel, commands. */
size_t parport_ieee1284_ecp_write_addr (struct parport *port,
const void *buffer, size_t len,
int flags)
{
#ifndef CONFIG_PARPORT_1284
return 0;
#else
const unsigned char *buf = buffer;
size_t written;
int retry;
port = port->physport;
if (port->ieee1284.phase != IEEE1284_PH_FWD_IDLE)
if (ecp_reverse_to_forward (port))
return 0;
port->ieee1284.phase = IEEE1284_PH_FWD_DATA;
/* HostAck low (command, not data) */
parport_frob_control (port,
PARPORT_CONTROL_AUTOFD
| PARPORT_CONTROL_STROBE
| PARPORT_CONTROL_INIT,
PARPORT_CONTROL_AUTOFD
| PARPORT_CONTROL_INIT);
for (written = 0; written < len; written++, buf++) {
unsigned long expire = jiffies + port->cad->timeout;
unsigned char byte;
byte = *buf;
try_again:
parport_write_data (port, byte);
parport_frob_control (port, PARPORT_CONTROL_STROBE,
PARPORT_CONTROL_STROBE);
udelay (5);
for (retry = 0; retry < 100; retry++) {
if (!parport_wait_peripheral (port,
PARPORT_STATUS_BUSY, 0))
goto success;
if (signal_pending (current)) {
parport_frob_control (port,
PARPORT_CONTROL_STROBE,
0);
break;
}
}
/* Time for Host Transfer Recovery (page 41 of IEEE1284) */
DPRINTK (KERN_DEBUG "%s: ECP transfer stalled!\n", port->name);
parport_frob_control (port, PARPORT_CONTROL_INIT,
PARPORT_CONTROL_INIT);
udelay (50);
if (parport_read_status (port) & PARPORT_STATUS_PAPEROUT) {
/* It's buggered. */
parport_frob_control (port, PARPORT_CONTROL_INIT, 0);
break;
}
parport_frob_control (port, PARPORT_CONTROL_INIT, 0);
udelay (50);
if (!(parport_read_status (port) & PARPORT_STATUS_PAPEROUT))
break;
DPRINTK (KERN_DEBUG "%s: Host transfer recovered\n",
port->name);
if (time_after_eq (jiffies, expire)) break;
goto try_again;
success:
parport_frob_control (port, PARPORT_CONTROL_STROBE, 0);
udelay (5);
if (parport_wait_peripheral (port,
PARPORT_STATUS_BUSY,
PARPORT_STATUS_BUSY))
/* Peripheral hasn't accepted the data. */
break;
}
port->ieee1284.phase = IEEE1284_PH_FWD_IDLE;
return written;
#endif /* IEEE1284 support */
}
/*** *
* EPP functions. *
* ***/
/* EPP mode, forward channel, data. */
size_t parport_ieee1284_epp_write_data (struct parport *port,
const void *buffer, size_t len,
int flags)
{
unsigned char *bp = (unsigned char *) buffer;
size_t ret = 0;
/* set EPP idle state (just to make sure) with strobe low */
parport_frob_control (port,
PARPORT_CONTROL_STROBE |
PARPORT_CONTROL_AUTOFD |
PARPORT_CONTROL_SELECT |
PARPORT_CONTROL_INIT,
PARPORT_CONTROL_STROBE |
PARPORT_CONTROL_INIT);
port->ops->data_forward (port);
for (; len > 0; len--, bp++) {
/* Event 62: Write data and set autofd low */
parport_write_data (port, *bp);
parport_frob_control (port, PARPORT_CONTROL_AUTOFD,
PARPORT_CONTROL_AUTOFD);
/* Event 58: wait for busy (nWait) to go high */
if (parport_poll_peripheral (port, PARPORT_STATUS_BUSY, 0, 10))
break;
/* Event 63: set nAutoFd (nDStrb) high */
parport_frob_control (port, PARPORT_CONTROL_AUTOFD, 0);
/* Event 60: wait for busy (nWait) to go low */
if (parport_poll_peripheral (port, PARPORT_STATUS_BUSY,
PARPORT_STATUS_BUSY, 5))
break;
ret++;
}
/* Event 61: set strobe (nWrite) high */
parport_frob_control (port, PARPORT_CONTROL_STROBE, 0);
return ret;
}
/* EPP mode, reverse channel, data. */
size_t parport_ieee1284_epp_read_data (struct parport *port,
void *buffer, size_t len,
int flags)
{
unsigned char *bp = (unsigned char *) buffer;
unsigned ret = 0;
/* set EPP idle state (just to make sure) with strobe high */
parport_frob_control (port,
PARPORT_CONTROL_STROBE |
PARPORT_CONTROL_AUTOFD |
PARPORT_CONTROL_SELECT |
PARPORT_CONTROL_INIT,
PARPORT_CONTROL_INIT);
port->ops->data_reverse (port);
for (; len > 0; len--, bp++) {
/* Event 67: set nAutoFd (nDStrb) low */
parport_frob_control (port,
PARPORT_CONTROL_AUTOFD,
PARPORT_CONTROL_AUTOFD);
/* Event 58: wait for Busy to go high */
if (parport_wait_peripheral (port, PARPORT_STATUS_BUSY, 0)) {
break;
}
*bp = parport_read_data (port);
/* Event 63: set nAutoFd (nDStrb) high */
parport_frob_control (port, PARPORT_CONTROL_AUTOFD, 0);
/* Event 60: wait for Busy to go low */
if (parport_poll_peripheral (port, PARPORT_STATUS_BUSY,
PARPORT_STATUS_BUSY, 5)) {
break;
}
ret++;
}
port->ops->data_forward (port);
return ret;
}
/* EPP mode, forward channel, addresses. */
size_t parport_ieee1284_epp_write_addr (struct parport *port,
const void *buffer, size_t len,
int flags)
{
unsigned char *bp = (unsigned char *) buffer;
size_t ret = 0;
/* set EPP idle state (just to make sure) with strobe low */
parport_frob_control (port,
PARPORT_CONTROL_STROBE |
PARPORT_CONTROL_AUTOFD |
PARPORT_CONTROL_SELECT |
PARPORT_CONTROL_INIT,
PARPORT_CONTROL_STROBE |
PARPORT_CONTROL_INIT);
port->ops->data_forward (port);
for (; len > 0; len--, bp++) {
/* Event 56: Write data and set nAStrb low. */
parport_write_data (port, *bp);
parport_frob_control (port, PARPORT_CONTROL_SELECT,
PARPORT_CONTROL_SELECT);
/* Event 58: wait for busy (nWait) to go high */
if (parport_poll_peripheral (port, PARPORT_STATUS_BUSY, 0, 10))
break;
/* Event 59: set nAStrb high */
parport_frob_control (port, PARPORT_CONTROL_SELECT, 0);
/* Event 60: wait for busy (nWait) to go low */
if (parport_poll_peripheral (port, PARPORT_STATUS_BUSY,
PARPORT_STATUS_BUSY, 5))
break;
ret++;
}
/* Event 61: set strobe (nWrite) high */
parport_frob_control (port, PARPORT_CONTROL_STROBE, 0);
return ret;
}
/* EPP mode, reverse channel, addresses. */
size_t parport_ieee1284_epp_read_addr (struct parport *port,
void *buffer, size_t len,
int flags)
{
unsigned char *bp = (unsigned char *) buffer;
unsigned ret = 0;
/* Set EPP idle state (just to make sure) with strobe high */
parport_frob_control (port,
PARPORT_CONTROL_STROBE |
PARPORT_CONTROL_AUTOFD |
PARPORT_CONTROL_SELECT |
PARPORT_CONTROL_INIT,
PARPORT_CONTROL_INIT);
port->ops->data_reverse (port);
for (; len > 0; len--, bp++) {
/* Event 64: set nSelectIn (nAStrb) low */
parport_frob_control (port, PARPORT_CONTROL_SELECT,
PARPORT_CONTROL_SELECT);
/* Event 58: wait for Busy to go high */
if (parport_wait_peripheral (port, PARPORT_STATUS_BUSY, 0)) {
break;
}
*bp = parport_read_data (port);
/* Event 59: set nSelectIn (nAStrb) high */
parport_frob_control (port, PARPORT_CONTROL_SELECT,
0);
/* Event 60: wait for Busy to go low */
if (parport_poll_peripheral (port, PARPORT_STATUS_BUSY,
PARPORT_STATUS_BUSY, 5))
break;
ret++;
}
port->ops->data_forward (port);
return ret;
}
EXPORT_SYMBOL(parport_ieee1284_ecp_write_data);
EXPORT_SYMBOL(parport_ieee1284_ecp_read_data);
EXPORT_SYMBOL(parport_ieee1284_ecp_write_addr);
EXPORT_SYMBOL(parport_ieee1284_write_compat);
EXPORT_SYMBOL(parport_ieee1284_read_nibble);
EXPORT_SYMBOL(parport_ieee1284_read_byte);
EXPORT_SYMBOL(parport_ieee1284_epp_write_data);
EXPORT_SYMBOL(parport_ieee1284_epp_read_data);
EXPORT_SYMBOL(parport_ieee1284_epp_write_addr);
EXPORT_SYMBOL(parport_ieee1284_epp_read_addr);
| gpl-2.0 |
jimbojr/linux | arch/x86/kernel/cpu/mshyperv.c | 209 | 5056 | /*
* HyperV Detection code.
*
* Copyright (C) 2010, Novell, Inc.
* Author : K. Y. Srinivasan <ksrinivasan@novell.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
*/
#include <linux/types.h>
#include <linux/time.h>
#include <linux/clocksource.h>
#include <linux/module.h>
#include <linux/hardirq.h>
#include <linux/efi.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/kexec.h>
#include <asm/processor.h>
#include <asm/hypervisor.h>
#include <asm/hyperv.h>
#include <asm/mshyperv.h>
#include <asm/desc.h>
#include <asm/idle.h>
#include <asm/irq_regs.h>
#include <asm/i8259.h>
#include <asm/apic.h>
#include <asm/timer.h>
#include <asm/reboot.h>
struct ms_hyperv_info ms_hyperv;
EXPORT_SYMBOL_GPL(ms_hyperv);
#if IS_ENABLED(CONFIG_HYPERV)
static void (*vmbus_handler)(void);
static void (*hv_kexec_handler)(void);
static void (*hv_crash_handler)(struct pt_regs *regs);
void hyperv_vector_handler(struct pt_regs *regs)
{
struct pt_regs *old_regs = set_irq_regs(regs);
entering_irq();
inc_irq_stat(irq_hv_callback_count);
if (vmbus_handler)
vmbus_handler();
exiting_irq();
set_irq_regs(old_regs);
}
void hv_setup_vmbus_irq(void (*handler)(void))
{
vmbus_handler = handler;
/*
* Setup the IDT for hypervisor callback. Prevent reallocation
* at module reload.
*/
if (!test_bit(HYPERVISOR_CALLBACK_VECTOR, used_vectors))
alloc_intr_gate(HYPERVISOR_CALLBACK_VECTOR,
hyperv_callback_vector);
}
void hv_remove_vmbus_irq(void)
{
/* We have no way to deallocate the interrupt gate */
vmbus_handler = NULL;
}
EXPORT_SYMBOL_GPL(hv_setup_vmbus_irq);
EXPORT_SYMBOL_GPL(hv_remove_vmbus_irq);
void hv_setup_kexec_handler(void (*handler)(void))
{
hv_kexec_handler = handler;
}
EXPORT_SYMBOL_GPL(hv_setup_kexec_handler);
void hv_remove_kexec_handler(void)
{
hv_kexec_handler = NULL;
}
EXPORT_SYMBOL_GPL(hv_remove_kexec_handler);
void hv_setup_crash_handler(void (*handler)(struct pt_regs *regs))
{
hv_crash_handler = handler;
}
EXPORT_SYMBOL_GPL(hv_setup_crash_handler);
void hv_remove_crash_handler(void)
{
hv_crash_handler = NULL;
}
EXPORT_SYMBOL_GPL(hv_remove_crash_handler);
#ifdef CONFIG_KEXEC_CORE
static void hv_machine_shutdown(void)
{
if (kexec_in_progress && hv_kexec_handler)
hv_kexec_handler();
native_machine_shutdown();
}
static void hv_machine_crash_shutdown(struct pt_regs *regs)
{
if (hv_crash_handler)
hv_crash_handler(regs);
native_machine_crash_shutdown(regs);
}
#endif /* CONFIG_KEXEC_CORE */
#endif /* CONFIG_HYPERV */
static uint32_t __init ms_hyperv_platform(void)
{
u32 eax;
u32 hyp_signature[3];
if (!boot_cpu_has(X86_FEATURE_HYPERVISOR))
return 0;
cpuid(HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS,
&eax, &hyp_signature[0], &hyp_signature[1], &hyp_signature[2]);
if (eax >= HYPERV_CPUID_MIN &&
eax <= HYPERV_CPUID_MAX &&
!memcmp("Microsoft Hv", hyp_signature, 12))
return HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
return 0;
}
static cycle_t read_hv_clock(struct clocksource *arg)
{
cycle_t current_tick;
/*
* Read the partition counter to get the current tick count. This count
* is set to 0 when the partition is created and is incremented in
* 100 nanosecond units.
*/
rdmsrl(HV_X64_MSR_TIME_REF_COUNT, current_tick);
return current_tick;
}
static struct clocksource hyperv_cs = {
.name = "hyperv_clocksource",
.rating = 400, /* use this when running on Hyperv*/
.read = read_hv_clock,
.mask = CLOCKSOURCE_MASK(64),
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
static void __init ms_hyperv_init_platform(void)
{
/*
* Extract the features and hints
*/
ms_hyperv.features = cpuid_eax(HYPERV_CPUID_FEATURES);
ms_hyperv.misc_features = cpuid_edx(HYPERV_CPUID_FEATURES);
ms_hyperv.hints = cpuid_eax(HYPERV_CPUID_ENLIGHTMENT_INFO);
printk(KERN_INFO "HyperV: features 0x%x, hints 0x%x\n",
ms_hyperv.features, ms_hyperv.hints);
#ifdef CONFIG_X86_LOCAL_APIC
if (ms_hyperv.features & HV_X64_MSR_APIC_FREQUENCY_AVAILABLE) {
/*
* Get the APIC frequency.
*/
u64 hv_lapic_frequency;
rdmsrl(HV_X64_MSR_APIC_FREQUENCY, hv_lapic_frequency);
hv_lapic_frequency = div_u64(hv_lapic_frequency, HZ);
lapic_timer_frequency = hv_lapic_frequency;
printk(KERN_INFO "HyperV: LAPIC Timer Frequency: %#x\n",
lapic_timer_frequency);
}
#endif
if (ms_hyperv.features & HV_X64_MSR_TIME_REF_COUNT_AVAILABLE)
clocksource_register_hz(&hyperv_cs, NSEC_PER_SEC/100);
#ifdef CONFIG_X86_IO_APIC
no_timer_check = 1;
#endif
#if IS_ENABLED(CONFIG_HYPERV) && defined(CONFIG_KEXEC_CORE)
machine_ops.shutdown = hv_machine_shutdown;
machine_ops.crash_shutdown = hv_machine_crash_shutdown;
#endif
mark_tsc_unstable("running on Hyper-V");
}
const __refconst struct hypervisor_x86 x86_hyper_ms_hyperv = {
.name = "Microsoft HyperV",
.detect = ms_hyperv_platform,
.init_platform = ms_hyperv_init_platform,
};
EXPORT_SYMBOL(x86_hyper_ms_hyperv);
| gpl-2.0 |
bright-pan/rt-thread | components/external/SQLite-3.8.1/SQLiteLib/test/test_thread.c | 209 | 19048 | /*
** 2007 September 9
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains the implementation of some Tcl commands used to
** test that sqlite3 database handles may be concurrently accessed by
** multiple threads. Right now this only works on unix.
*/
#include "sqliteInt.h"
#include <tcl.h>
#if SQLITE_THREADSAFE
#include <errno.h>
#if !defined(_MSC_VER)
#include <unistd.h>
#endif
/*
** One of these is allocated for each thread created by [sqlthread spawn].
*/
typedef struct SqlThread SqlThread;
struct SqlThread {
Tcl_ThreadId parent; /* Thread id of parent thread */
Tcl_Interp *interp; /* Parent interpreter */
char *zScript; /* The script to execute. */
char *zVarname; /* Varname in parent script */
};
/*
** A custom Tcl_Event type used by this module. When the event is
** handled, script zScript is evaluated in interpreter interp. If
** the evaluation throws an exception (returns TCL_ERROR), then the
** error is handled by Tcl_BackgroundError(). If no error occurs,
** the result is simply discarded.
*/
typedef struct EvalEvent EvalEvent;
struct EvalEvent {
Tcl_Event base; /* Base class of type Tcl_Event */
char *zScript; /* The script to execute. */
Tcl_Interp *interp; /* The interpreter to execute it in. */
};
static Tcl_ObjCmdProc sqlthread_proc;
static Tcl_ObjCmdProc clock_seconds_proc;
#if SQLITE_OS_UNIX && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
static Tcl_ObjCmdProc blocking_step_proc;
static Tcl_ObjCmdProc blocking_prepare_v2_proc;
#endif
int Sqlitetest1_Init(Tcl_Interp *);
int Sqlite3_Init(Tcl_Interp *);
/* Functions from main.c */
extern const char *sqlite3ErrName(int);
/* Functions from test1.c */
extern void *sqlite3TestTextToPtr(const char *);
extern int getDbPointer(Tcl_Interp *, const char *, sqlite3 **);
extern int sqlite3TestMakePointerStr(Tcl_Interp *, char *, void *);
extern int sqlite3TestErrCode(Tcl_Interp *, sqlite3 *, int);
/*
** Handler for events of type EvalEvent.
*/
static int tclScriptEvent(Tcl_Event *evPtr, int flags){
int rc;
EvalEvent *p = (EvalEvent *)evPtr;
rc = Tcl_Eval(p->interp, p->zScript);
if( rc!=TCL_OK ){
Tcl_BackgroundError(p->interp);
}
UNUSED_PARAMETER(flags);
return 1;
}
/*
** Register an EvalEvent to evaluate the script pScript in the
** parent interpreter/thread of SqlThread p.
*/
static void postToParent(SqlThread *p, Tcl_Obj *pScript){
EvalEvent *pEvent;
char *zMsg;
int nMsg;
zMsg = Tcl_GetStringFromObj(pScript, &nMsg);
pEvent = (EvalEvent *)ckalloc(sizeof(EvalEvent)+nMsg+1);
pEvent->base.nextPtr = 0;
pEvent->base.proc = tclScriptEvent;
pEvent->zScript = (char *)&pEvent[1];
memcpy(pEvent->zScript, zMsg, nMsg+1);
pEvent->interp = p->interp;
Tcl_ThreadQueueEvent(p->parent, (Tcl_Event *)pEvent, TCL_QUEUE_TAIL);
Tcl_ThreadAlert(p->parent);
}
/*
** The main function for threads created with [sqlthread spawn].
*/
static Tcl_ThreadCreateType tclScriptThread(ClientData pSqlThread){
Tcl_Interp *interp;
Tcl_Obj *pRes;
Tcl_Obj *pList;
int rc;
SqlThread *p = (SqlThread *)pSqlThread;
extern int Sqlitetest_mutex_Init(Tcl_Interp*);
interp = Tcl_CreateInterp();
Tcl_CreateObjCommand(interp, "clock_seconds", clock_seconds_proc, 0, 0);
Tcl_CreateObjCommand(interp, "sqlthread", sqlthread_proc, pSqlThread, 0);
#if SQLITE_OS_UNIX && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
Tcl_CreateObjCommand(interp, "sqlite3_blocking_step", blocking_step_proc,0,0);
Tcl_CreateObjCommand(interp,
"sqlite3_blocking_prepare_v2", blocking_prepare_v2_proc, (void *)1, 0);
Tcl_CreateObjCommand(interp,
"sqlite3_nonblocking_prepare_v2", blocking_prepare_v2_proc, 0, 0);
#endif
Sqlitetest1_Init(interp);
Sqlitetest_mutex_Init(interp);
Sqlite3_Init(interp);
rc = Tcl_Eval(interp, p->zScript);
pRes = Tcl_GetObjResult(interp);
pList = Tcl_NewObj();
Tcl_IncrRefCount(pList);
Tcl_IncrRefCount(pRes);
if( rc!=TCL_OK ){
Tcl_ListObjAppendElement(interp, pList, Tcl_NewStringObj("error", -1));
Tcl_ListObjAppendElement(interp, pList, pRes);
postToParent(p, pList);
Tcl_DecrRefCount(pList);
pList = Tcl_NewObj();
}
Tcl_ListObjAppendElement(interp, pList, Tcl_NewStringObj("set", -1));
Tcl_ListObjAppendElement(interp, pList, Tcl_NewStringObj(p->zVarname, -1));
Tcl_ListObjAppendElement(interp, pList, pRes);
postToParent(p, pList);
ckfree((void *)p);
Tcl_DecrRefCount(pList);
Tcl_DecrRefCount(pRes);
Tcl_DeleteInterp(interp);
while( Tcl_DoOneEvent(TCL_ALL_EVENTS|TCL_DONT_WAIT) );
Tcl_ExitThread(0);
TCL_THREAD_CREATE_RETURN;
}
/*
** sqlthread spawn VARNAME SCRIPT
**
** Spawn a new thread with its own Tcl interpreter and run the
** specified SCRIPT(s) in it. The thread terminates after running
** the script. The result of the script is stored in the variable
** VARNAME.
**
** The caller can wait for the script to terminate using [vwait VARNAME].
*/
static int sqlthread_spawn(
ClientData clientData,
Tcl_Interp *interp,
int objc,
Tcl_Obj *CONST objv[]
){
Tcl_ThreadId x;
SqlThread *pNew;
int rc;
int nVarname; char *zVarname;
int nScript; char *zScript;
/* Parameters for thread creation */
const int nStack = TCL_THREAD_STACK_DEFAULT;
const int flags = TCL_THREAD_NOFLAGS;
assert(objc==4);
UNUSED_PARAMETER(clientData);
UNUSED_PARAMETER(objc);
zVarname = Tcl_GetStringFromObj(objv[2], &nVarname);
zScript = Tcl_GetStringFromObj(objv[3], &nScript);
pNew = (SqlThread *)ckalloc(sizeof(SqlThread)+nVarname+nScript+2);
pNew->zVarname = (char *)&pNew[1];
pNew->zScript = (char *)&pNew->zVarname[nVarname+1];
memcpy(pNew->zVarname, zVarname, nVarname+1);
memcpy(pNew->zScript, zScript, nScript+1);
pNew->parent = Tcl_GetCurrentThread();
pNew->interp = interp;
rc = Tcl_CreateThread(&x, tclScriptThread, (void *)pNew, nStack, flags);
if( rc!=TCL_OK ){
Tcl_AppendResult(interp, "Error in Tcl_CreateThread()", 0);
ckfree((char *)pNew);
return TCL_ERROR;
}
return TCL_OK;
}
/*
** sqlthread parent SCRIPT
**
** This can be called by spawned threads only. It sends the specified
** script back to the parent thread for execution. The result of
** evaluating the SCRIPT is returned. The parent thread must enter
** the event loop for this to work - otherwise the caller will
** block indefinitely.
**
** NOTE: At the moment, this doesn't work. FIXME.
*/
static int sqlthread_parent(
ClientData clientData,
Tcl_Interp *interp,
int objc,
Tcl_Obj *CONST objv[]
){
EvalEvent *pEvent;
char *zMsg;
int nMsg;
SqlThread *p = (SqlThread *)clientData;
assert(objc==3);
UNUSED_PARAMETER(objc);
if( p==0 ){
Tcl_AppendResult(interp, "no parent thread", 0);
return TCL_ERROR;
}
zMsg = Tcl_GetStringFromObj(objv[2], &nMsg);
pEvent = (EvalEvent *)ckalloc(sizeof(EvalEvent)+nMsg+1);
pEvent->base.nextPtr = 0;
pEvent->base.proc = tclScriptEvent;
pEvent->zScript = (char *)&pEvent[1];
memcpy(pEvent->zScript, zMsg, nMsg+1);
pEvent->interp = p->interp;
Tcl_ThreadQueueEvent(p->parent, (Tcl_Event *)pEvent, TCL_QUEUE_TAIL);
Tcl_ThreadAlert(p->parent);
return TCL_OK;
}
static int xBusy(void *pArg, int nBusy){
UNUSED_PARAMETER(pArg);
UNUSED_PARAMETER(nBusy);
sqlite3_sleep(50);
return 1; /* Try again... */
}
/*
** sqlthread open
**
** Open a database handle and return the string representation of
** the pointer value.
*/
static int sqlthread_open(
ClientData clientData,
Tcl_Interp *interp,
int objc,
Tcl_Obj *CONST objv[]
){
int sqlite3TestMakePointerStr(Tcl_Interp *interp, char *zPtr, void *p);
const char *zFilename;
sqlite3 *db;
char zBuf[100];
extern void Md5_Register(sqlite3*);
UNUSED_PARAMETER(clientData);
UNUSED_PARAMETER(objc);
zFilename = Tcl_GetString(objv[2]);
sqlite3_open(zFilename, &db);
#ifdef SQLITE_HAS_CODEC
if( db && objc>=4 ){
const char *zKey;
int nKey;
int rc;
zKey = Tcl_GetStringFromObj(objv[3], &nKey);
rc = sqlite3_key(db, zKey, nKey);
if( rc!=SQLITE_OK ){
char *zErrMsg = sqlite3_mprintf("error %d: %s", rc, sqlite3_errmsg(db));
sqlite3_close(db);
Tcl_AppendResult(interp, zErrMsg, (char*)0);
sqlite3_free(zErrMsg);
return TCL_ERROR;
}
}
#endif
Md5_Register(db);
sqlite3_busy_handler(db, xBusy, 0);
if( sqlite3TestMakePointerStr(interp, zBuf, db) ) return TCL_ERROR;
Tcl_AppendResult(interp, zBuf, 0);
return TCL_OK;
}
/*
** sqlthread open
**
** Return the current thread-id (Tcl_GetCurrentThread()) cast to
** an integer.
*/
static int sqlthread_id(
ClientData clientData,
Tcl_Interp *interp,
int objc,
Tcl_Obj *CONST objv[]
){
Tcl_ThreadId id = Tcl_GetCurrentThread();
Tcl_SetObjResult(interp, Tcl_NewIntObj(SQLITE_PTR_TO_INT(id)));
UNUSED_PARAMETER(clientData);
UNUSED_PARAMETER(objc);
UNUSED_PARAMETER(objv);
return TCL_OK;
}
/*
** Dispatch routine for the sub-commands of [sqlthread].
*/
static int sqlthread_proc(
ClientData clientData,
Tcl_Interp *interp,
int objc,
Tcl_Obj *CONST objv[]
){
struct SubCommand {
char *zName;
Tcl_ObjCmdProc *xProc;
int nArg;
char *zUsage;
} aSub[] = {
{"parent", sqlthread_parent, 1, "SCRIPT"},
{"spawn", sqlthread_spawn, 2, "VARNAME SCRIPT"},
{"open", sqlthread_open, 1, "DBNAME"},
{"id", sqlthread_id, 0, ""},
{0, 0, 0}
};
struct SubCommand *pSub;
int rc;
int iIndex;
if( objc<2 ){
Tcl_WrongNumArgs(interp, 1, objv, "SUB-COMMAND");
return TCL_ERROR;
}
rc = Tcl_GetIndexFromObjStruct(
interp, objv[1], aSub, sizeof(aSub[0]), "sub-command", 0, &iIndex
);
if( rc!=TCL_OK ) return rc;
pSub = &aSub[iIndex];
if( objc<(pSub->nArg+2) ){
Tcl_WrongNumArgs(interp, 2, objv, pSub->zUsage);
return TCL_ERROR;
}
return pSub->xProc(clientData, interp, objc, objv);
}
/*
** The [clock_seconds] command. This is more or less the same as the
** regular tcl [clock seconds], except that it is available in testfixture
** when linked against both Tcl 8.4 and 8.5. Because [clock seconds] is
** implemented as a script in Tcl 8.5, it is not usually available to
** testfixture.
*/
static int clock_seconds_proc(
ClientData clientData,
Tcl_Interp *interp,
int objc,
Tcl_Obj *CONST objv[]
){
Tcl_Time now;
Tcl_GetTime(&now);
Tcl_SetObjResult(interp, Tcl_NewIntObj(now.sec));
UNUSED_PARAMETER(clientData);
UNUSED_PARAMETER(objc);
UNUSED_PARAMETER(objv);
return TCL_OK;
}
/*************************************************************************
** This block contains the implementation of the [sqlite3_blocking_step]
** command available to threads created by [sqlthread spawn] commands. It
** is only available on UNIX for now. This is because pthread condition
** variables are used.
**
** The source code for the C functions sqlite3_blocking_step(),
** blocking_step_notify() and the structure UnlockNotification is
** automatically extracted from this file and used as part of the
** documentation for the sqlite3_unlock_notify() API function. This
** should be considered if these functions are to be extended (i.e. to
** support windows) in the future.
*/
#if SQLITE_OS_UNIX && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
/* BEGIN_SQLITE_BLOCKING_STEP */
/* This example uses the pthreads API */
#include <pthread.h>
/*
** A pointer to an instance of this structure is passed as the user-context
** pointer when registering for an unlock-notify callback.
*/
typedef struct UnlockNotification UnlockNotification;
struct UnlockNotification {
int fired; /* True after unlock event has occurred */
pthread_cond_t cond; /* Condition variable to wait on */
pthread_mutex_t mutex; /* Mutex to protect structure */
};
/*
** This function is an unlock-notify callback registered with SQLite.
*/
static void unlock_notify_cb(void **apArg, int nArg){
int i;
for(i=0; i<nArg; i++){
UnlockNotification *p = (UnlockNotification *)apArg[i];
pthread_mutex_lock(&p->mutex);
p->fired = 1;
pthread_cond_signal(&p->cond);
pthread_mutex_unlock(&p->mutex);
}
}
/*
** This function assumes that an SQLite API call (either sqlite3_prepare_v2()
** or sqlite3_step()) has just returned SQLITE_LOCKED. The argument is the
** associated database connection.
**
** This function calls sqlite3_unlock_notify() to register for an
** unlock-notify callback, then blocks until that callback is delivered
** and returns SQLITE_OK. The caller should then retry the failed operation.
**
** Or, if sqlite3_unlock_notify() indicates that to block would deadlock
** the system, then this function returns SQLITE_LOCKED immediately. In
** this case the caller should not retry the operation and should roll
** back the current transaction (if any).
*/
static int wait_for_unlock_notify(sqlite3 *db){
int rc;
UnlockNotification un;
/* Initialize the UnlockNotification structure. */
un.fired = 0;
pthread_mutex_init(&un.mutex, 0);
pthread_cond_init(&un.cond, 0);
/* Register for an unlock-notify callback. */
rc = sqlite3_unlock_notify(db, unlock_notify_cb, (void *)&un);
assert( rc==SQLITE_LOCKED || rc==SQLITE_OK );
/* The call to sqlite3_unlock_notify() always returns either SQLITE_LOCKED
** or SQLITE_OK.
**
** If SQLITE_LOCKED was returned, then the system is deadlocked. In this
** case this function needs to return SQLITE_LOCKED to the caller so
** that the current transaction can be rolled back. Otherwise, block
** until the unlock-notify callback is invoked, then return SQLITE_OK.
*/
if( rc==SQLITE_OK ){
pthread_mutex_lock(&un.mutex);
if( !un.fired ){
pthread_cond_wait(&un.cond, &un.mutex);
}
pthread_mutex_unlock(&un.mutex);
}
/* Destroy the mutex and condition variables. */
pthread_cond_destroy(&un.cond);
pthread_mutex_destroy(&un.mutex);
return rc;
}
/*
** This function is a wrapper around the SQLite function sqlite3_step().
** It functions in the same way as step(), except that if a required
** shared-cache lock cannot be obtained, this function may block waiting for
** the lock to become available. In this scenario the normal API step()
** function always returns SQLITE_LOCKED.
**
** If this function returns SQLITE_LOCKED, the caller should rollback
** the current transaction (if any) and try again later. Otherwise, the
** system may become deadlocked.
*/
int sqlite3_blocking_step(sqlite3_stmt *pStmt){
int rc;
while( SQLITE_LOCKED==(rc = sqlite3_step(pStmt)) ){
rc = wait_for_unlock_notify(sqlite3_db_handle(pStmt));
if( rc!=SQLITE_OK ) break;
sqlite3_reset(pStmt);
}
return rc;
}
/*
** This function is a wrapper around the SQLite function sqlite3_prepare_v2().
** It functions in the same way as prepare_v2(), except that if a required
** shared-cache lock cannot be obtained, this function may block waiting for
** the lock to become available. In this scenario the normal API prepare_v2()
** function always returns SQLITE_LOCKED.
**
** If this function returns SQLITE_LOCKED, the caller should rollback
** the current transaction (if any) and try again later. Otherwise, the
** system may become deadlocked.
*/
int sqlite3_blocking_prepare_v2(
sqlite3 *db, /* Database handle. */
const char *zSql, /* UTF-8 encoded SQL statement. */
int nSql, /* Length of zSql in bytes. */
sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
const char **pz /* OUT: End of parsed string */
){
int rc;
while( SQLITE_LOCKED==(rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, pz)) ){
rc = wait_for_unlock_notify(db);
if( rc!=SQLITE_OK ) break;
}
return rc;
}
/* END_SQLITE_BLOCKING_STEP */
/*
** Usage: sqlite3_blocking_step STMT
**
** Advance the statement to the next row.
*/
static int blocking_step_proc(
void * clientData,
Tcl_Interp *interp,
int objc,
Tcl_Obj *CONST objv[]
){
sqlite3_stmt *pStmt;
int rc;
if( objc!=2 ){
Tcl_WrongNumArgs(interp, 1, objv, "STMT");
return TCL_ERROR;
}
pStmt = (sqlite3_stmt*)sqlite3TestTextToPtr(Tcl_GetString(objv[1]));
rc = sqlite3_blocking_step(pStmt);
Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), 0);
return TCL_OK;
}
/*
** Usage: sqlite3_blocking_prepare_v2 DB sql bytes ?tailvar?
** Usage: sqlite3_nonblocking_prepare_v2 DB sql bytes ?tailvar?
*/
static int blocking_prepare_v2_proc(
void * clientData,
Tcl_Interp *interp,
int objc,
Tcl_Obj *CONST objv[]
){
sqlite3 *db;
const char *zSql;
int bytes;
const char *zTail = 0;
sqlite3_stmt *pStmt = 0;
char zBuf[50];
int rc;
int isBlocking = !(clientData==0);
if( objc!=5 && objc!=4 ){
Tcl_AppendResult(interp, "wrong # args: should be \"",
Tcl_GetString(objv[0]), " DB sql bytes tailvar", 0);
return TCL_ERROR;
}
if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
zSql = Tcl_GetString(objv[2]);
if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR;
if( isBlocking ){
rc = sqlite3_blocking_prepare_v2(db, zSql, bytes, &pStmt, &zTail);
}else{
rc = sqlite3_prepare_v2(db, zSql, bytes, &pStmt, &zTail);
}
assert(rc==SQLITE_OK || pStmt==0);
if( zTail && objc>=5 ){
if( bytes>=0 ){
bytes = bytes - (zTail-zSql);
}
Tcl_ObjSetVar2(interp, objv[4], 0, Tcl_NewStringObj(zTail, bytes), 0);
}
if( rc!=SQLITE_OK ){
assert( pStmt==0 );
sprintf(zBuf, "%s ", (char *)sqlite3ErrName(rc));
Tcl_AppendResult(interp, zBuf, sqlite3_errmsg(db), 0);
return TCL_ERROR;
}
if( pStmt ){
if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR;
Tcl_AppendResult(interp, zBuf, 0);
}
return TCL_OK;
}
#endif /* SQLITE_OS_UNIX && SQLITE_ENABLE_UNLOCK_NOTIFY */
/*
** End of implementation of [sqlite3_blocking_step].
************************************************************************/
/*
** Register commands with the TCL interpreter.
*/
int SqlitetestThread_Init(Tcl_Interp *interp){
Tcl_CreateObjCommand(interp, "sqlthread", sqlthread_proc, 0, 0);
Tcl_CreateObjCommand(interp, "clock_seconds", clock_seconds_proc, 0, 0);
#if SQLITE_OS_UNIX && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
Tcl_CreateObjCommand(interp, "sqlite3_blocking_step", blocking_step_proc,0,0);
Tcl_CreateObjCommand(interp,
"sqlite3_blocking_prepare_v2", blocking_prepare_v2_proc, (void *)1, 0);
Tcl_CreateObjCommand(interp,
"sqlite3_nonblocking_prepare_v2", blocking_prepare_v2_proc, 0, 0);
#endif
return TCL_OK;
}
#else
int SqlitetestThread_Init(Tcl_Interp *interp){
return TCL_OK;
}
#endif
| gpl-2.0 |
utkanos/android_htc_mecha_kernel_oc | drivers/acpi/acpica/dsmthdat.c | 465 | 21630 | /*******************************************************************************
*
* Module Name: dsmthdat - control method arguments and local variables
*
******************************************************************************/
/*
* Copyright (C) 2000 - 2008, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acdispat.h"
#include "acnamesp.h"
#include "acinterp.h"
#define _COMPONENT ACPI_DISPATCHER
ACPI_MODULE_NAME("dsmthdat")
/* Local prototypes */
static void
acpi_ds_method_data_delete_value(u8 type,
u32 index, struct acpi_walk_state *walk_state);
static acpi_status
acpi_ds_method_data_set_value(u8 type,
u32 index,
union acpi_operand_object *object,
struct acpi_walk_state *walk_state);
#ifdef ACPI_OBSOLETE_FUNCTIONS
acpi_object_type
acpi_ds_method_data_get_type(u16 opcode,
u32 index, struct acpi_walk_state *walk_state);
#endif
/*******************************************************************************
*
* FUNCTION: acpi_ds_method_data_init
*
* PARAMETERS: walk_state - Current walk state object
*
* RETURN: Status
*
* DESCRIPTION: Initialize the data structures that hold the method's arguments
* and locals. The data struct is an array of namespace nodes for
* each - this allows ref_of and de_ref_of to work properly for these
* special data types.
*
* NOTES: walk_state fields are initialized to zero by the
* ACPI_ALLOCATE_ZEROED().
*
* A pseudo-Namespace Node is assigned to each argument and local
* so that ref_of() can return a pointer to the Node.
*
******************************************************************************/
void acpi_ds_method_data_init(struct acpi_walk_state *walk_state)
{
u32 i;
ACPI_FUNCTION_TRACE(ds_method_data_init);
/* Init the method arguments */
for (i = 0; i < ACPI_METHOD_NUM_ARGS; i++) {
ACPI_MOVE_32_TO_32(&walk_state->arguments[i].name,
NAMEOF_ARG_NTE);
walk_state->arguments[i].name.integer |= (i << 24);
walk_state->arguments[i].descriptor_type = ACPI_DESC_TYPE_NAMED;
walk_state->arguments[i].type = ACPI_TYPE_ANY;
walk_state->arguments[i].flags =
ANOBJ_END_OF_PEER_LIST | ANOBJ_METHOD_ARG;
}
/* Init the method locals */
for (i = 0; i < ACPI_METHOD_NUM_LOCALS; i++) {
ACPI_MOVE_32_TO_32(&walk_state->local_variables[i].name,
NAMEOF_LOCAL_NTE);
walk_state->local_variables[i].name.integer |= (i << 24);
walk_state->local_variables[i].descriptor_type =
ACPI_DESC_TYPE_NAMED;
walk_state->local_variables[i].type = ACPI_TYPE_ANY;
walk_state->local_variables[i].flags =
ANOBJ_END_OF_PEER_LIST | ANOBJ_METHOD_LOCAL;
}
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: acpi_ds_method_data_delete_all
*
* PARAMETERS: walk_state - Current walk state object
*
* RETURN: None
*
* DESCRIPTION: Delete method locals and arguments. Arguments are only
* deleted if this method was called from another method.
*
******************************************************************************/
void acpi_ds_method_data_delete_all(struct acpi_walk_state *walk_state)
{
u32 index;
ACPI_FUNCTION_TRACE(ds_method_data_delete_all);
/* Detach the locals */
for (index = 0; index < ACPI_METHOD_NUM_LOCALS; index++) {
if (walk_state->local_variables[index].object) {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC, "Deleting Local%d=%p\n",
index,
walk_state->local_variables[index].
object));
/* Detach object (if present) and remove a reference */
acpi_ns_detach_object(&walk_state->
local_variables[index]);
}
}
/* Detach the arguments */
for (index = 0; index < ACPI_METHOD_NUM_ARGS; index++) {
if (walk_state->arguments[index].object) {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC, "Deleting Arg%d=%p\n",
index,
walk_state->arguments[index].object));
/* Detach object (if present) and remove a reference */
acpi_ns_detach_object(&walk_state->arguments[index]);
}
}
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: acpi_ds_method_data_init_args
*
* PARAMETERS: *Params - Pointer to a parameter list for the method
* max_param_count - The arg count for this method
* walk_state - Current walk state object
*
* RETURN: Status
*
* DESCRIPTION: Initialize arguments for a method. The parameter list is a list
* of ACPI operand objects, either null terminated or whose length
* is defined by max_param_count.
*
******************************************************************************/
acpi_status
acpi_ds_method_data_init_args(union acpi_operand_object **params,
u32 max_param_count,
struct acpi_walk_state *walk_state)
{
acpi_status status;
u32 index = 0;
ACPI_FUNCTION_TRACE_PTR(ds_method_data_init_args, params);
if (!params) {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
"No param list passed to method\n"));
return_ACPI_STATUS(AE_OK);
}
/* Copy passed parameters into the new method stack frame */
while ((index < ACPI_METHOD_NUM_ARGS) &&
(index < max_param_count) && params[index]) {
/*
* A valid parameter.
* Store the argument in the method/walk descriptor.
* Do not copy the arg in order to implement call by reference
*/
status = acpi_ds_method_data_set_value(ACPI_REFCLASS_ARG, index,
params[index],
walk_state);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
index++;
}
ACPI_DEBUG_PRINT((ACPI_DB_EXEC, "%d args passed to method\n", index));
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ds_method_data_get_node
*
* PARAMETERS: Type - Either ACPI_REFCLASS_LOCAL or
* ACPI_REFCLASS_ARG
* Index - Which Local or Arg whose type to get
* walk_state - Current walk state object
* Node - Where the node is returned.
*
* RETURN: Status and node
*
* DESCRIPTION: Get the Node associated with a local or arg.
*
******************************************************************************/
acpi_status
acpi_ds_method_data_get_node(u8 type,
u32 index,
struct acpi_walk_state *walk_state,
struct acpi_namespace_node **node)
{
ACPI_FUNCTION_TRACE(ds_method_data_get_node);
/*
* Method Locals and Arguments are supported
*/
switch (type) {
case ACPI_REFCLASS_LOCAL:
if (index > ACPI_METHOD_MAX_LOCAL) {
ACPI_ERROR((AE_INFO,
"Local index %d is invalid (max %d)",
index, ACPI_METHOD_MAX_LOCAL));
return_ACPI_STATUS(AE_AML_INVALID_INDEX);
}
/* Return a pointer to the pseudo-node */
*node = &walk_state->local_variables[index];
break;
case ACPI_REFCLASS_ARG:
if (index > ACPI_METHOD_MAX_ARG) {
ACPI_ERROR((AE_INFO,
"Arg index %d is invalid (max %d)",
index, ACPI_METHOD_MAX_ARG));
return_ACPI_STATUS(AE_AML_INVALID_INDEX);
}
/* Return a pointer to the pseudo-node */
*node = &walk_state->arguments[index];
break;
default:
ACPI_ERROR((AE_INFO, "Type %d is invalid", type));
return_ACPI_STATUS(AE_TYPE);
}
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ds_method_data_set_value
*
* PARAMETERS: Type - Either ACPI_REFCLASS_LOCAL or
* ACPI_REFCLASS_ARG
* Index - Which Local or Arg to get
* Object - Object to be inserted into the stack entry
* walk_state - Current walk state object
*
* RETURN: Status
*
* DESCRIPTION: Insert an object onto the method stack at entry Opcode:Index.
* Note: There is no "implicit conversion" for locals.
*
******************************************************************************/
static acpi_status
acpi_ds_method_data_set_value(u8 type,
u32 index,
union acpi_operand_object *object,
struct acpi_walk_state *walk_state)
{
acpi_status status;
struct acpi_namespace_node *node;
ACPI_FUNCTION_TRACE(ds_method_data_set_value);
ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
"NewObj %p Type %2.2X, Refs=%d [%s]\n", object,
type, object->common.reference_count,
acpi_ut_get_type_name(object->common.type)));
/* Get the namespace node for the arg/local */
status = acpi_ds_method_data_get_node(type, index, walk_state, &node);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/*
* Increment ref count so object can't be deleted while installed.
* NOTE: We do not copy the object in order to preserve the call by
* reference semantics of ACPI Control Method invocation.
* (See ACPI Specification 2.0_c)
*/
acpi_ut_add_reference(object);
/* Install the object */
node->object = object;
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ds_method_data_get_value
*
* PARAMETERS: Type - Either ACPI_REFCLASS_LOCAL or
* ACPI_REFCLASS_ARG
* Index - Which local_var or argument to get
* walk_state - Current walk state object
* dest_desc - Where Arg or Local value is returned
*
* RETURN: Status
*
* DESCRIPTION: Retrieve value of selected Arg or Local for this method
* Used only in acpi_ex_resolve_to_value().
*
******************************************************************************/
acpi_status
acpi_ds_method_data_get_value(u8 type,
u32 index,
struct acpi_walk_state *walk_state,
union acpi_operand_object **dest_desc)
{
acpi_status status;
struct acpi_namespace_node *node;
union acpi_operand_object *object;
ACPI_FUNCTION_TRACE(ds_method_data_get_value);
/* Validate the object descriptor */
if (!dest_desc) {
ACPI_ERROR((AE_INFO, "Null object descriptor pointer"));
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
/* Get the namespace node for the arg/local */
status = acpi_ds_method_data_get_node(type, index, walk_state, &node);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/* Get the object from the node */
object = node->object;
/* Examine the returned object, it must be valid. */
if (!object) {
/*
* Index points to uninitialized object.
* This means that either 1) The expected argument was
* not passed to the method, or 2) A local variable
* was referenced by the method (via the ASL)
* before it was initialized. Either case is an error.
*/
/* If slack enabled, init the local_x/arg_x to an Integer of value zero */
if (acpi_gbl_enable_interpreter_slack) {
object =
acpi_ut_create_internal_object(ACPI_TYPE_INTEGER);
if (!object) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
object->integer.value = 0;
node->object = object;
}
/* Otherwise, return the error */
else
switch (type) {
case ACPI_REFCLASS_ARG:
ACPI_ERROR((AE_INFO,
"Uninitialized Arg[%d] at node %p",
index, node));
return_ACPI_STATUS(AE_AML_UNINITIALIZED_ARG);
case ACPI_REFCLASS_LOCAL:
/*
* No error message for this case, will be trapped again later to
* detect and ignore cases of Store(local_x,local_x)
*/
return_ACPI_STATUS(AE_AML_UNINITIALIZED_LOCAL);
default:
ACPI_ERROR((AE_INFO,
"Not a Arg/Local opcode: %X",
type));
return_ACPI_STATUS(AE_AML_INTERNAL);
}
}
/*
* The Index points to an initialized and valid object.
* Return an additional reference to the object
*/
*dest_desc = object;
acpi_ut_add_reference(object);
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ds_method_data_delete_value
*
* PARAMETERS: Type - Either ACPI_REFCLASS_LOCAL or
* ACPI_REFCLASS_ARG
* Index - Which local_var or argument to delete
* walk_state - Current walk state object
*
* RETURN: None
*
* DESCRIPTION: Delete the entry at Opcode:Index. Inserts
* a null into the stack slot after the object is deleted.
*
******************************************************************************/
static void
acpi_ds_method_data_delete_value(u8 type,
u32 index, struct acpi_walk_state *walk_state)
{
acpi_status status;
struct acpi_namespace_node *node;
union acpi_operand_object *object;
ACPI_FUNCTION_TRACE(ds_method_data_delete_value);
/* Get the namespace node for the arg/local */
status = acpi_ds_method_data_get_node(type, index, walk_state, &node);
if (ACPI_FAILURE(status)) {
return_VOID;
}
/* Get the associated object */
object = acpi_ns_get_attached_object(node);
/*
* Undefine the Arg or Local by setting its descriptor
* pointer to NULL. Locals/Args can contain both
* ACPI_OPERAND_OBJECTS and ACPI_NAMESPACE_NODEs
*/
node->object = NULL;
if ((object) &&
(ACPI_GET_DESCRIPTOR_TYPE(object) == ACPI_DESC_TYPE_OPERAND)) {
/*
* There is a valid object.
* Decrement the reference count by one to balance the
* increment when the object was stored.
*/
acpi_ut_remove_reference(object);
}
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: acpi_ds_store_object_to_local
*
* PARAMETERS: Type - Either ACPI_REFCLASS_LOCAL or
* ACPI_REFCLASS_ARG
* Index - Which Local or Arg to set
* obj_desc - Value to be stored
* walk_state - Current walk state
*
* RETURN: Status
*
* DESCRIPTION: Store a value in an Arg or Local. The obj_desc is installed
* as the new value for the Arg or Local and the reference count
* for obj_desc is incremented.
*
******************************************************************************/
acpi_status
acpi_ds_store_object_to_local(u8 type,
u32 index,
union acpi_operand_object *obj_desc,
struct acpi_walk_state *walk_state)
{
acpi_status status;
struct acpi_namespace_node *node;
union acpi_operand_object *current_obj_desc;
union acpi_operand_object *new_obj_desc;
ACPI_FUNCTION_TRACE(ds_store_object_to_local);
ACPI_DEBUG_PRINT((ACPI_DB_EXEC, "Type=%2.2X Index=%d Obj=%p\n",
type, index, obj_desc));
/* Parameter validation */
if (!obj_desc) {
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
/* Get the namespace node for the arg/local */
status = acpi_ds_method_data_get_node(type, index, walk_state, &node);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
current_obj_desc = acpi_ns_get_attached_object(node);
if (current_obj_desc == obj_desc) {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC, "Obj=%p already installed!\n",
obj_desc));
return_ACPI_STATUS(status);
}
/*
* If the reference count on the object is more than one, we must
* take a copy of the object before we store. A reference count
* of exactly 1 means that the object was just created during the
* evaluation of an expression, and we can safely use it since it
* is not used anywhere else.
*/
new_obj_desc = obj_desc;
if (obj_desc->common.reference_count > 1) {
status =
acpi_ut_copy_iobject_to_iobject(obj_desc, &new_obj_desc,
walk_state);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
}
/*
* If there is an object already in this slot, we either
* have to delete it, or if this is an argument and there
* is an object reference stored there, we have to do
* an indirect store!
*/
if (current_obj_desc) {
/*
* Check for an indirect store if an argument
* contains an object reference (stored as an Node).
* We don't allow this automatic dereferencing for
* locals, since a store to a local should overwrite
* anything there, including an object reference.
*
* If both Arg0 and Local0 contain ref_of (Local4):
*
* Store (1, Arg0) - Causes indirect store to local4
* Store (1, Local0) - Stores 1 in local0, overwriting
* the reference to local4
* Store (1, de_refof (Local0)) - Causes indirect store to local4
*
* Weird, but true.
*/
if (type == ACPI_REFCLASS_ARG) {
/*
* If we have a valid reference object that came from ref_of(),
* do the indirect store
*/
if ((ACPI_GET_DESCRIPTOR_TYPE(current_obj_desc) ==
ACPI_DESC_TYPE_OPERAND)
&& (current_obj_desc->common.type ==
ACPI_TYPE_LOCAL_REFERENCE)
&& (current_obj_desc->reference.class ==
ACPI_REFCLASS_REFOF)) {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
"Arg (%p) is an ObjRef(Node), storing in node %p\n",
new_obj_desc,
current_obj_desc));
/*
* Store this object to the Node (perform the indirect store)
* NOTE: No implicit conversion is performed, as per the ACPI
* specification rules on storing to Locals/Args.
*/
status =
acpi_ex_store_object_to_node(new_obj_desc,
current_obj_desc->
reference.
object,
walk_state,
ACPI_NO_IMPLICIT_CONVERSION);
/* Remove local reference if we copied the object above */
if (new_obj_desc != obj_desc) {
acpi_ut_remove_reference(new_obj_desc);
}
return_ACPI_STATUS(status);
}
}
/* Delete the existing object before storing the new one */
acpi_ds_method_data_delete_value(type, index, walk_state);
}
/*
* Install the Obj descriptor (*new_obj_desc) into
* the descriptor for the Arg or Local.
* (increments the object reference count by one)
*/
status =
acpi_ds_method_data_set_value(type, index, new_obj_desc,
walk_state);
/* Remove local reference if we copied the object above */
if (new_obj_desc != obj_desc) {
acpi_ut_remove_reference(new_obj_desc);
}
return_ACPI_STATUS(status);
}
#ifdef ACPI_OBSOLETE_FUNCTIONS
/*******************************************************************************
*
* FUNCTION: acpi_ds_method_data_get_type
*
* PARAMETERS: Opcode - Either AML_LOCAL_OP or AML_ARG_OP
* Index - Which Local or Arg whose type to get
* walk_state - Current walk state object
*
* RETURN: Data type of current value of the selected Arg or Local
*
* DESCRIPTION: Get the type of the object stored in the Local or Arg
*
******************************************************************************/
acpi_object_type
acpi_ds_method_data_get_type(u16 opcode,
u32 index, struct acpi_walk_state *walk_state)
{
acpi_status status;
struct acpi_namespace_node *node;
union acpi_operand_object *object;
ACPI_FUNCTION_TRACE(ds_method_data_get_type);
/* Get the namespace node for the arg/local */
status = acpi_ds_method_data_get_node(opcode, index, walk_state, &node);
if (ACPI_FAILURE(status)) {
return_VALUE((ACPI_TYPE_NOT_FOUND));
}
/* Get the object */
object = acpi_ns_get_attached_object(node);
if (!object) {
/* Uninitialized local/arg, return TYPE_ANY */
return_VALUE(ACPI_TYPE_ANY);
}
/* Get the object type */
return_VALUE(object->type);
}
#endif
| gpl-2.0 |
s9yobena/linux | arch/arm/mach-realview/realview_pba8.c | 1233 | 8655 | /*
* linux/arch/arm/mach-realview/realview_pba8.c
*
* Copyright (C) 2008 ARM Limited
* Copyright (C) 2000 Deep Blue Solutions Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/device.h>
#include <linux/amba/bus.h>
#include <linux/amba/pl061.h>
#include <linux/amba/mmci.h>
#include <linux/amba/pl022.h>
#include <linux/io.h>
#include <linux/irqchip/arm-gic.h>
#include <linux/platform_data/clk-realview.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <asm/pgtable.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/time.h>
#include <mach/hardware.h>
#include <mach/board-pba8.h>
#include <mach/irqs.h>
#include "core.h"
static struct map_desc realview_pba8_io_desc[] __initdata = {
{
.virtual = IO_ADDRESS(REALVIEW_SYS_BASE),
.pfn = __phys_to_pfn(REALVIEW_SYS_BASE),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = IO_ADDRESS(REALVIEW_PBA8_GIC_CPU_BASE),
.pfn = __phys_to_pfn(REALVIEW_PBA8_GIC_CPU_BASE),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = IO_ADDRESS(REALVIEW_PBA8_GIC_DIST_BASE),
.pfn = __phys_to_pfn(REALVIEW_PBA8_GIC_DIST_BASE),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = IO_ADDRESS(REALVIEW_SCTL_BASE),
.pfn = __phys_to_pfn(REALVIEW_SCTL_BASE),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = IO_ADDRESS(REALVIEW_PBA8_TIMER0_1_BASE),
.pfn = __phys_to_pfn(REALVIEW_PBA8_TIMER0_1_BASE),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = IO_ADDRESS(REALVIEW_PBA8_TIMER2_3_BASE),
.pfn = __phys_to_pfn(REALVIEW_PBA8_TIMER2_3_BASE),
.length = SZ_4K,
.type = MT_DEVICE,
},
#ifdef CONFIG_PCI
{
.virtual = PCIX_UNIT_BASE,
.pfn = __phys_to_pfn(REALVIEW_PBA8_PCI_BASE),
.length = REALVIEW_PBA8_PCI_BASE_SIZE,
.type = MT_DEVICE
},
#endif
#ifdef CONFIG_DEBUG_LL
{
.virtual = IO_ADDRESS(REALVIEW_PBA8_UART0_BASE),
.pfn = __phys_to_pfn(REALVIEW_PBA8_UART0_BASE),
.length = SZ_4K,
.type = MT_DEVICE,
},
#endif
};
static void __init realview_pba8_map_io(void)
{
iotable_init(realview_pba8_io_desc, ARRAY_SIZE(realview_pba8_io_desc));
}
static struct pl061_platform_data gpio0_plat_data = {
.gpio_base = 0,
};
static struct pl061_platform_data gpio1_plat_data = {
.gpio_base = 8,
};
static struct pl061_platform_data gpio2_plat_data = {
.gpio_base = 16,
};
static struct pl022_ssp_controller ssp0_plat_data = {
.bus_id = 0,
.enable_dma = 0,
.num_chipselect = 1,
};
/*
* RealView PBA8Core AMBA devices
*/
#define GPIO2_IRQ { IRQ_PBA8_GPIO2 }
#define GPIO3_IRQ { IRQ_PBA8_GPIO3 }
#define AACI_IRQ { IRQ_PBA8_AACI }
#define MMCI0_IRQ { IRQ_PBA8_MMCI0A, IRQ_PBA8_MMCI0B }
#define KMI0_IRQ { IRQ_PBA8_KMI0 }
#define KMI1_IRQ { IRQ_PBA8_KMI1 }
#define PBA8_SMC_IRQ { }
#define MPMC_IRQ { }
#define PBA8_CLCD_IRQ { IRQ_PBA8_CLCD }
#define DMAC_IRQ { IRQ_PBA8_DMAC }
#define SCTL_IRQ { }
#define PBA8_WATCHDOG_IRQ { IRQ_PBA8_WATCHDOG }
#define PBA8_GPIO0_IRQ { IRQ_PBA8_GPIO0 }
#define GPIO1_IRQ { IRQ_PBA8_GPIO1 }
#define PBA8_RTC_IRQ { IRQ_PBA8_RTC }
#define SCI_IRQ { IRQ_PBA8_SCI }
#define PBA8_UART0_IRQ { IRQ_PBA8_UART0 }
#define PBA8_UART1_IRQ { IRQ_PBA8_UART1 }
#define PBA8_UART2_IRQ { IRQ_PBA8_UART2 }
#define PBA8_UART3_IRQ { IRQ_PBA8_UART3 }
#define PBA8_SSP_IRQ { IRQ_PBA8_SSP }
/* FPGA Primecells */
APB_DEVICE(aaci, "fpga:aaci", AACI, NULL);
APB_DEVICE(mmc0, "fpga:mmc0", MMCI0, &realview_mmc0_plat_data);
APB_DEVICE(kmi0, "fpga:kmi0", KMI0, NULL);
APB_DEVICE(kmi1, "fpga:kmi1", KMI1, NULL);
APB_DEVICE(uart3, "fpga:uart3", PBA8_UART3, NULL);
/* DevChip Primecells */
AHB_DEVICE(smc, "dev:smc", PBA8_SMC, NULL);
AHB_DEVICE(sctl, "dev:sctl", SCTL, NULL);
APB_DEVICE(wdog, "dev:wdog", PBA8_WATCHDOG, NULL);
APB_DEVICE(gpio0, "dev:gpio0", PBA8_GPIO0, &gpio0_plat_data);
APB_DEVICE(gpio1, "dev:gpio1", GPIO1, &gpio1_plat_data);
APB_DEVICE(gpio2, "dev:gpio2", GPIO2, &gpio2_plat_data);
APB_DEVICE(rtc, "dev:rtc", PBA8_RTC, NULL);
APB_DEVICE(sci0, "dev:sci0", SCI, NULL);
APB_DEVICE(uart0, "dev:uart0", PBA8_UART0, NULL);
APB_DEVICE(uart1, "dev:uart1", PBA8_UART1, NULL);
APB_DEVICE(uart2, "dev:uart2", PBA8_UART2, NULL);
APB_DEVICE(ssp0, "dev:ssp0", PBA8_SSP, &ssp0_plat_data);
/* Primecells on the NEC ISSP chip */
AHB_DEVICE(clcd, "issp:clcd", PBA8_CLCD, &clcd_plat_data);
AHB_DEVICE(dmac, "issp:dmac", DMAC, NULL);
static struct amba_device *amba_devs[] __initdata = {
&dmac_device,
&uart0_device,
&uart1_device,
&uart2_device,
&uart3_device,
&smc_device,
&clcd_device,
&sctl_device,
&wdog_device,
&gpio0_device,
&gpio1_device,
&gpio2_device,
&rtc_device,
&sci0_device,
&ssp0_device,
&aaci_device,
&mmc0_device,
&kmi0_device,
&kmi1_device,
};
/*
* RealView PB-A8 platform devices
*/
static struct resource realview_pba8_flash_resource[] = {
[0] = {
.start = REALVIEW_PBA8_FLASH0_BASE,
.end = REALVIEW_PBA8_FLASH0_BASE + REALVIEW_PBA8_FLASH0_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = REALVIEW_PBA8_FLASH1_BASE,
.end = REALVIEW_PBA8_FLASH1_BASE + REALVIEW_PBA8_FLASH1_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
static struct resource realview_pba8_smsc911x_resources[] = {
[0] = {
.start = REALVIEW_PBA8_ETH_BASE,
.end = REALVIEW_PBA8_ETH_BASE + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_PBA8_ETH,
.end = IRQ_PBA8_ETH,
.flags = IORESOURCE_IRQ,
},
};
static struct resource realview_pba8_isp1761_resources[] = {
[0] = {
.start = REALVIEW_PBA8_USB_BASE,
.end = REALVIEW_PBA8_USB_BASE + SZ_128K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_PBA8_USB,
.end = IRQ_PBA8_USB,
.flags = IORESOURCE_IRQ,
},
};
static struct resource pmu_resource = {
.start = IRQ_PBA8_PMU,
.end = IRQ_PBA8_PMU,
.flags = IORESOURCE_IRQ,
};
static struct platform_device pmu_device = {
.name = "arm-pmu",
.id = -1,
.num_resources = 1,
.resource = &pmu_resource,
};
static void __init gic_init_irq(void)
{
/* ARM PB-A8 on-board GIC */
gic_init(0, IRQ_PBA8_GIC_START,
__io_address(REALVIEW_PBA8_GIC_DIST_BASE),
__io_address(REALVIEW_PBA8_GIC_CPU_BASE));
}
static void __init realview_pba8_timer_init(void)
{
timer0_va_base = __io_address(REALVIEW_PBA8_TIMER0_1_BASE);
timer1_va_base = __io_address(REALVIEW_PBA8_TIMER0_1_BASE) + 0x20;
timer2_va_base = __io_address(REALVIEW_PBA8_TIMER2_3_BASE);
timer3_va_base = __io_address(REALVIEW_PBA8_TIMER2_3_BASE) + 0x20;
realview_clk_init(__io_address(REALVIEW_SYS_BASE), false);
realview_timer_init(IRQ_PBA8_TIMER0_1);
}
static void realview_pba8_restart(char mode, const char *cmd)
{
void __iomem *reset_ctrl = __io_address(REALVIEW_SYS_RESETCTL);
void __iomem *lock_ctrl = __io_address(REALVIEW_SYS_LOCK);
/*
* To reset, we hit the on-board reset register
* in the system FPGA
*/
__raw_writel(REALVIEW_SYS_LOCK_VAL, lock_ctrl);
__raw_writel(0x0000, reset_ctrl);
__raw_writel(0x0004, reset_ctrl);
dsb();
}
static void __init realview_pba8_init(void)
{
int i;
realview_flash_register(realview_pba8_flash_resource,
ARRAY_SIZE(realview_pba8_flash_resource));
realview_eth_register(NULL, realview_pba8_smsc911x_resources);
platform_device_register(&realview_i2c_device);
platform_device_register(&realview_cf_device);
realview_usb_register(realview_pba8_isp1761_resources);
platform_device_register(&pmu_device);
for (i = 0; i < ARRAY_SIZE(amba_devs); i++) {
struct amba_device *d = amba_devs[i];
amba_device_register(d, &iomem_resource);
}
}
MACHINE_START(REALVIEW_PBA8, "ARM-RealView PB-A8")
/* Maintainer: ARM Ltd/Deep Blue Solutions Ltd */
.atag_offset = 0x100,
.fixup = realview_fixup,
.map_io = realview_pba8_map_io,
.init_early = realview_init_early,
.init_irq = gic_init_irq,
.init_time = realview_pba8_timer_init,
.init_machine = realview_pba8_init,
#ifdef CONFIG_ZONE_DMA
.dma_zone_size = SZ_256M,
#endif
.restart = realview_pba8_restart,
MACHINE_END
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.