repo_name
string
path
string
copies
string
size
string
content
string
license
string
AOKP-SGS2/android_kernel_samsung_espresso
arch/arm/mach-cns3xxx/pm.c
2518
2878
/* * Copyright 2008 Cavium Networks * * This file 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/io.h> #include <linux/delay.h> #include <asm/atomic.h> #include <mach/system.h> #include <mach/cns3xxx.h> #include <mach/pm.h> void cns3xxx_pwr_clk_en(unsigned int block) { u32 reg = __raw_readl(PM_CLK_GATE_REG); reg |= (block & PM_CLK_GATE_REG_MASK); __raw_writel(reg, PM_CLK_GATE_REG); } EXPORT_SYMBOL(cns3xxx_pwr_clk_en); void cns3xxx_pwr_clk_dis(unsigned int block) { u32 reg = __raw_readl(PM_CLK_GATE_REG); reg &= ~(block & PM_CLK_GATE_REG_MASK); __raw_writel(reg, PM_CLK_GATE_REG); } EXPORT_SYMBOL(cns3xxx_pwr_clk_dis); void cns3xxx_pwr_power_up(unsigned int block) { u32 reg = __raw_readl(PM_PLL_HM_PD_CTRL_REG); reg &= ~(block & CNS3XXX_PWR_PLL_ALL); __raw_writel(reg, PM_PLL_HM_PD_CTRL_REG); /* Wait for 300us for the PLL output clock locked. */ udelay(300); }; EXPORT_SYMBOL(cns3xxx_pwr_power_up); void cns3xxx_pwr_power_down(unsigned int block) { u32 reg = __raw_readl(PM_PLL_HM_PD_CTRL_REG); /* write '1' to power down */ reg |= (block & CNS3XXX_PWR_PLL_ALL); __raw_writel(reg, PM_PLL_HM_PD_CTRL_REG); }; EXPORT_SYMBOL(cns3xxx_pwr_power_down); static void cns3xxx_pwr_soft_rst_force(unsigned int block) { u32 reg = __raw_readl(PM_SOFT_RST_REG); /* * bit 0, 28, 29 => program low to reset, * the other else program low and then high */ if (block & 0x30000001) { reg &= ~(block & PM_SOFT_RST_REG_MASK); } else { reg &= ~(block & PM_SOFT_RST_REG_MASK); __raw_writel(reg, PM_SOFT_RST_REG); reg |= (block & PM_SOFT_RST_REG_MASK); } __raw_writel(reg, PM_SOFT_RST_REG); } EXPORT_SYMBOL(cns3xxx_pwr_soft_rst_force); void cns3xxx_pwr_soft_rst(unsigned int block) { static unsigned int soft_reset; if (soft_reset & block) { /* SPI/I2C/GPIO use the same block, reset once. */ return; } else { soft_reset |= block; } cns3xxx_pwr_soft_rst_force(block); } EXPORT_SYMBOL(cns3xxx_pwr_soft_rst); void arch_reset(char mode, const char *cmd) { /* * To reset, we hit the on-board reset register * in the system FPGA. */ cns3xxx_pwr_soft_rst(CNS3XXX_PWR_SOFTWARE_RST(GLOBAL)); } /* * cns3xxx_cpu_clock - return CPU/L2 clock * aclk: cpu clock/2 * hclk: cpu clock/4 * pclk: cpu clock/8 */ int cns3xxx_cpu_clock(void) { u32 reg = __raw_readl(PM_CLK_CTRL_REG); int cpu; int cpu_sel; int div_sel; cpu_sel = (reg >> PM_CLK_CTRL_REG_OFFSET_PLL_CPU_SEL) & 0xf; div_sel = (reg >> PM_CLK_CTRL_REG_OFFSET_CPU_CLK_DIV) & 0x3; cpu = (300 + ((cpu_sel / 3) * 100) + ((cpu_sel % 3) * 33)) >> div_sel; return cpu; } EXPORT_SYMBOL(cns3xxx_cpu_clock); atomic_t usb_pwr_ref = ATOMIC_INIT(0); EXPORT_SYMBOL(usb_pwr_ref);
gpl-2.0
onejay09/OLD----kernel_HTC_msm7x30_KK
drivers/media/video/cx18/cx18-fileops.c
2774
26048
/* * cx18 file operation functions * * Derived from ivtv-fileops.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., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA */ #include "cx18-driver.h" #include "cx18-fileops.h" #include "cx18-i2c.h" #include "cx18-queue.h" #include "cx18-vbi.h" #include "cx18-audio.h" #include "cx18-mailbox.h" #include "cx18-scb.h" #include "cx18-streams.h" #include "cx18-controls.h" #include "cx18-ioctl.h" #include "cx18-cards.h" /* This function tries to claim the stream for a specific file descriptor. If no one else is using this stream then the stream is claimed and associated VBI and IDX streams are also automatically claimed. Possible error returns: -EBUSY if someone else has claimed the stream or 0 on success. */ int cx18_claim_stream(struct cx18_open_id *id, int type) { struct cx18 *cx = id->cx; struct cx18_stream *s = &cx->streams[type]; struct cx18_stream *s_assoc; /* Nothing should ever try to directly claim the IDX stream */ if (type == CX18_ENC_STREAM_TYPE_IDX) { CX18_WARN("MPEG Index stream cannot be claimed " "directly, but something tried.\n"); return -EINVAL; } if (test_and_set_bit(CX18_F_S_CLAIMED, &s->s_flags)) { /* someone already claimed this stream */ if (s->id == id->open_id) { /* yes, this file descriptor did. So that's OK. */ return 0; } if (s->id == -1 && type == CX18_ENC_STREAM_TYPE_VBI) { /* VBI is handled already internally, now also assign the file descriptor to this stream for external reading of the stream. */ s->id = id->open_id; CX18_DEBUG_INFO("Start Read VBI\n"); return 0; } /* someone else is using this stream already */ CX18_DEBUG_INFO("Stream %d is busy\n", type); return -EBUSY; } s->id = id->open_id; /* * CX18_ENC_STREAM_TYPE_MPG needs to claim: * CX18_ENC_STREAM_TYPE_VBI, if VBI insertion is on for sliced VBI, or * CX18_ENC_STREAM_TYPE_IDX, if VBI insertion is off for sliced VBI * (We don't yet fix up MPEG Index entries for our inserted packets). * * For all other streams we're done. */ if (type != CX18_ENC_STREAM_TYPE_MPG) return 0; s_assoc = &cx->streams[CX18_ENC_STREAM_TYPE_IDX]; if (cx->vbi.insert_mpeg && !cx18_raw_vbi(cx)) s_assoc = &cx->streams[CX18_ENC_STREAM_TYPE_VBI]; else if (!cx18_stream_enabled(s_assoc)) return 0; set_bit(CX18_F_S_CLAIMED, &s_assoc->s_flags); /* mark that it is used internally */ set_bit(CX18_F_S_INTERNAL_USE, &s_assoc->s_flags); return 0; } EXPORT_SYMBOL(cx18_claim_stream); /* This function releases a previously claimed stream. It will take into account associated VBI streams. */ void cx18_release_stream(struct cx18_stream *s) { struct cx18 *cx = s->cx; struct cx18_stream *s_assoc; s->id = -1; if (s->type == CX18_ENC_STREAM_TYPE_IDX) { /* * The IDX stream is only used internally, and can * only be indirectly unclaimed by unclaiming the MPG stream. */ return; } if (s->type == CX18_ENC_STREAM_TYPE_VBI && test_bit(CX18_F_S_INTERNAL_USE, &s->s_flags)) { /* this stream is still in use internally */ return; } if (!test_and_clear_bit(CX18_F_S_CLAIMED, &s->s_flags)) { CX18_DEBUG_WARN("Release stream %s not in use!\n", s->name); return; } cx18_flush_queues(s); /* * CX18_ENC_STREAM_TYPE_MPG needs to release the * CX18_ENC_STREAM_TYPE_VBI and/or CX18_ENC_STREAM_TYPE_IDX streams. * * For all other streams we're done. */ if (s->type != CX18_ENC_STREAM_TYPE_MPG) return; /* Unclaim the associated MPEG Index stream */ s_assoc = &cx->streams[CX18_ENC_STREAM_TYPE_IDX]; if (test_and_clear_bit(CX18_F_S_INTERNAL_USE, &s_assoc->s_flags)) { clear_bit(CX18_F_S_CLAIMED, &s_assoc->s_flags); cx18_flush_queues(s_assoc); } /* Unclaim the associated VBI stream */ s_assoc = &cx->streams[CX18_ENC_STREAM_TYPE_VBI]; if (test_and_clear_bit(CX18_F_S_INTERNAL_USE, &s_assoc->s_flags)) { if (s_assoc->id == -1) { /* * The VBI stream is not still claimed by a file * descriptor, so completely unclaim it. */ clear_bit(CX18_F_S_CLAIMED, &s_assoc->s_flags); cx18_flush_queues(s_assoc); } } } EXPORT_SYMBOL(cx18_release_stream); static void cx18_dualwatch(struct cx18 *cx) { struct v4l2_tuner vt; u32 new_stereo_mode; const u32 dual = 0x0200; new_stereo_mode = v4l2_ctrl_g_ctrl(cx->cxhdl.audio_mode); memset(&vt, 0, sizeof(vt)); cx18_call_all(cx, tuner, g_tuner, &vt); if (vt.audmode == V4L2_TUNER_MODE_LANG1_LANG2 && (vt.rxsubchans & V4L2_TUNER_SUB_LANG2)) new_stereo_mode = dual; if (new_stereo_mode == cx->dualwatch_stereo_mode) return; CX18_DEBUG_INFO("dualwatch: change stereo flag from 0x%x to 0x%x.\n", cx->dualwatch_stereo_mode, new_stereo_mode); if (v4l2_ctrl_s_ctrl(cx->cxhdl.audio_mode, new_stereo_mode)) CX18_DEBUG_INFO("dualwatch: changing stereo flag failed\n"); } static struct cx18_mdl *cx18_get_mdl(struct cx18_stream *s, int non_block, int *err) { struct cx18 *cx = s->cx; struct cx18_stream *s_vbi = &cx->streams[CX18_ENC_STREAM_TYPE_VBI]; struct cx18_mdl *mdl; DEFINE_WAIT(wait); *err = 0; while (1) { if (s->type == CX18_ENC_STREAM_TYPE_MPG) { /* Process pending program updates and VBI data */ if (time_after(jiffies, cx->dualwatch_jiffies + msecs_to_jiffies(1000))) { cx->dualwatch_jiffies = jiffies; cx18_dualwatch(cx); } if (test_bit(CX18_F_S_INTERNAL_USE, &s_vbi->s_flags) && !test_bit(CX18_F_S_APPL_IO, &s_vbi->s_flags)) { while ((mdl = cx18_dequeue(s_vbi, &s_vbi->q_full))) { /* byteswap and process VBI data */ cx18_process_vbi_data(cx, mdl, s_vbi->type); cx18_stream_put_mdl_fw(s_vbi, mdl); } } mdl = &cx->vbi.sliced_mpeg_mdl; if (mdl->readpos != mdl->bytesused) return mdl; } /* do we have new data? */ mdl = cx18_dequeue(s, &s->q_full); if (mdl) { if (!test_and_clear_bit(CX18_F_M_NEED_SWAP, &mdl->m_flags)) return mdl; if (s->type == CX18_ENC_STREAM_TYPE_MPG) /* byteswap MPG data */ cx18_mdl_swap(mdl); else { /* byteswap and process VBI data */ cx18_process_vbi_data(cx, mdl, s->type); } return mdl; } /* return if end of stream */ if (!test_bit(CX18_F_S_STREAMING, &s->s_flags)) { CX18_DEBUG_INFO("EOS %s\n", s->name); return NULL; } /* return if file was opened with O_NONBLOCK */ if (non_block) { *err = -EAGAIN; return NULL; } /* wait for more data to arrive */ prepare_to_wait(&s->waitq, &wait, TASK_INTERRUPTIBLE); /* New buffers might have become available before we were added to the waitqueue */ if (!atomic_read(&s->q_full.depth)) schedule(); finish_wait(&s->waitq, &wait); if (signal_pending(current)) { /* return if a signal was received */ CX18_DEBUG_INFO("User stopped %s\n", s->name); *err = -EINTR; return NULL; } } } static void cx18_setup_sliced_vbi_mdl(struct cx18 *cx) { struct cx18_mdl *mdl = &cx->vbi.sliced_mpeg_mdl; struct cx18_buffer *buf = &cx->vbi.sliced_mpeg_buf; int idx = cx->vbi.inserted_frame % CX18_VBI_FRAMES; buf->buf = cx->vbi.sliced_mpeg_data[idx]; buf->bytesused = cx->vbi.sliced_mpeg_size[idx]; buf->readpos = 0; mdl->curr_buf = NULL; mdl->bytesused = cx->vbi.sliced_mpeg_size[idx]; mdl->readpos = 0; } static size_t cx18_copy_buf_to_user(struct cx18_stream *s, struct cx18_buffer *buf, char __user *ubuf, size_t ucount, bool *stop) { struct cx18 *cx = s->cx; size_t len = buf->bytesused - buf->readpos; *stop = false; if (len > ucount) len = ucount; if (cx->vbi.insert_mpeg && s->type == CX18_ENC_STREAM_TYPE_MPG && !cx18_raw_vbi(cx) && buf != &cx->vbi.sliced_mpeg_buf) { /* * Try to find a good splice point in the PS, just before * an MPEG-2 Program Pack start code, and provide only * up to that point to the user, so it's easy to insert VBI data * the next time around. * * This will not work for an MPEG-2 TS and has only been * verified by analysis to work for an MPEG-2 PS. Helen Buus * pointed out this works for the CX23416 MPEG-2 DVD compatible * stream, and research indicates both the MPEG 2 SVCD and DVD * stream types use an MPEG-2 PS container. */ /* * An MPEG-2 Program Stream (PS) is a series of * MPEG-2 Program Packs terminated by an * MPEG Program End Code after the last Program Pack. * A Program Pack may hold a PS System Header packet and any * number of Program Elementary Stream (PES) Packets */ const char *start = buf->buf + buf->readpos; const char *p = start + 1; const u8 *q; u8 ch = cx->search_pack_header ? 0xba : 0xe0; int stuffing, i; while (start + len > p) { /* Scan for a 0 to find a potential MPEG-2 start code */ q = memchr(p, 0, start + len - p); if (q == NULL) break; p = q + 1; /* * Keep looking if not a * MPEG-2 Pack header start code: 0x00 0x00 0x01 0xba * or MPEG-2 video PES start code: 0x00 0x00 0x01 0xe0 */ if ((char *)q + 15 >= buf->buf + buf->bytesused || q[1] != 0 || q[2] != 1 || q[3] != ch) continue; /* If expecting the primary video PES */ if (!cx->search_pack_header) { /* Continue if it couldn't be a PES packet */ if ((q[6] & 0xc0) != 0x80) continue; /* Check if a PTS or PTS & DTS follow */ if (((q[7] & 0xc0) == 0x80 && /* PTS only */ (q[9] & 0xf0) == 0x20) || /* PTS only */ ((q[7] & 0xc0) == 0xc0 && /* PTS & DTS */ (q[9] & 0xf0) == 0x30)) { /* DTS follows */ /* Assume we found the video PES hdr */ ch = 0xba; /* next want a Program Pack*/ cx->search_pack_header = 1; p = q + 9; /* Skip this video PES hdr */ } continue; } /* We may have found a Program Pack start code */ /* Get the count of stuffing bytes & verify them */ stuffing = q[13] & 7; /* all stuffing bytes must be 0xff */ for (i = 0; i < stuffing; i++) if (q[14 + i] != 0xff) break; if (i == stuffing && /* right number of stuffing bytes*/ (q[4] & 0xc4) == 0x44 && /* marker check */ (q[12] & 3) == 3 && /* marker check */ q[14 + stuffing] == 0 && /* PES Pack or Sys Hdr */ q[15 + stuffing] == 0 && q[16 + stuffing] == 1) { /* We declare we actually found a Program Pack*/ cx->search_pack_header = 0; /* expect vid PES */ len = (char *)q - start; cx18_setup_sliced_vbi_mdl(cx); *stop = true; break; } } } if (copy_to_user(ubuf, (u8 *)buf->buf + buf->readpos, len)) { CX18_DEBUG_WARN("copy %zd bytes to user failed for %s\n", len, s->name); return -EFAULT; } buf->readpos += len; if (s->type == CX18_ENC_STREAM_TYPE_MPG && buf != &cx->vbi.sliced_mpeg_buf) cx->mpg_data_received += len; return len; } static size_t cx18_copy_mdl_to_user(struct cx18_stream *s, struct cx18_mdl *mdl, char __user *ubuf, size_t ucount) { size_t tot_written = 0; int rc; bool stop = false; if (mdl->curr_buf == NULL) mdl->curr_buf = list_first_entry(&mdl->buf_list, struct cx18_buffer, list); if (list_entry_is_past_end(mdl->curr_buf, &mdl->buf_list, list)) { /* * For some reason we've exhausted the buffers, but the MDL * object still said some data was unread. * Fix that and bail out. */ mdl->readpos = mdl->bytesused; return 0; } list_for_each_entry_from(mdl->curr_buf, &mdl->buf_list, list) { if (mdl->curr_buf->readpos >= mdl->curr_buf->bytesused) continue; rc = cx18_copy_buf_to_user(s, mdl->curr_buf, ubuf + tot_written, ucount - tot_written, &stop); if (rc < 0) return rc; mdl->readpos += rc; tot_written += rc; if (stop || /* Forced stopping point for VBI insertion */ tot_written >= ucount || /* Reader request statisfied */ mdl->curr_buf->readpos < mdl->curr_buf->bytesused || mdl->readpos >= mdl->bytesused) /* MDL buffers drained */ break; } return tot_written; } static ssize_t cx18_read(struct cx18_stream *s, char __user *ubuf, size_t tot_count, int non_block) { struct cx18 *cx = s->cx; size_t tot_written = 0; int single_frame = 0; if (atomic_read(&cx->ana_capturing) == 0 && s->id == -1) { /* shouldn't happen */ CX18_DEBUG_WARN("Stream %s not initialized before read\n", s->name); return -EIO; } /* Each VBI buffer is one frame, the v4l2 API says that for VBI the frames should arrive one-by-one, so make sure we never output more than one VBI frame at a time */ if (s->type == CX18_ENC_STREAM_TYPE_VBI && !cx18_raw_vbi(cx)) single_frame = 1; for (;;) { struct cx18_mdl *mdl; int rc; mdl = cx18_get_mdl(s, non_block, &rc); /* if there is no data available... */ if (mdl == NULL) { /* if we got data, then return that regardless */ if (tot_written) break; /* EOS condition */ if (rc == 0) { clear_bit(CX18_F_S_STREAMOFF, &s->s_flags); clear_bit(CX18_F_S_APPL_IO, &s->s_flags); cx18_release_stream(s); } /* set errno */ return rc; } rc = cx18_copy_mdl_to_user(s, mdl, ubuf + tot_written, tot_count - tot_written); if (mdl != &cx->vbi.sliced_mpeg_mdl) { if (mdl->readpos == mdl->bytesused) cx18_stream_put_mdl_fw(s, mdl); else cx18_push(s, mdl, &s->q_full); } else if (mdl->readpos == mdl->bytesused) { int idx = cx->vbi.inserted_frame % CX18_VBI_FRAMES; cx->vbi.sliced_mpeg_size[idx] = 0; cx->vbi.inserted_frame++; cx->vbi_data_inserted += mdl->bytesused; } if (rc < 0) return rc; tot_written += rc; if (tot_written == tot_count || single_frame) break; } return tot_written; } static ssize_t cx18_read_pos(struct cx18_stream *s, char __user *ubuf, size_t count, loff_t *pos, int non_block) { ssize_t rc = count ? cx18_read(s, ubuf, count, non_block) : 0; struct cx18 *cx = s->cx; CX18_DEBUG_HI_FILE("read %zd from %s, got %zd\n", count, s->name, rc); if (rc > 0) pos += rc; return rc; } int cx18_start_capture(struct cx18_open_id *id) { struct cx18 *cx = id->cx; struct cx18_stream *s = &cx->streams[id->type]; struct cx18_stream *s_vbi; struct cx18_stream *s_idx; if (s->type == CX18_ENC_STREAM_TYPE_RAD) { /* you cannot read from these stream types. */ return -EPERM; } /* Try to claim this stream. */ if (cx18_claim_stream(id, s->type)) return -EBUSY; /* If capture is already in progress, then we also have to do nothing extra. */ if (test_bit(CX18_F_S_STREAMOFF, &s->s_flags) || test_and_set_bit(CX18_F_S_STREAMING, &s->s_flags)) { set_bit(CX18_F_S_APPL_IO, &s->s_flags); return 0; } /* Start associated VBI or IDX stream capture if required */ s_vbi = &cx->streams[CX18_ENC_STREAM_TYPE_VBI]; s_idx = &cx->streams[CX18_ENC_STREAM_TYPE_IDX]; if (s->type == CX18_ENC_STREAM_TYPE_MPG) { /* * The VBI and IDX streams should have been claimed * automatically, if for internal use, when the MPG stream was * claimed. We only need to start these streams capturing. */ if (test_bit(CX18_F_S_INTERNAL_USE, &s_idx->s_flags) && !test_and_set_bit(CX18_F_S_STREAMING, &s_idx->s_flags)) { if (cx18_start_v4l2_encode_stream(s_idx)) { CX18_DEBUG_WARN("IDX capture start failed\n"); clear_bit(CX18_F_S_STREAMING, &s_idx->s_flags); goto start_failed; } CX18_DEBUG_INFO("IDX capture started\n"); } if (test_bit(CX18_F_S_INTERNAL_USE, &s_vbi->s_flags) && !test_and_set_bit(CX18_F_S_STREAMING, &s_vbi->s_flags)) { if (cx18_start_v4l2_encode_stream(s_vbi)) { CX18_DEBUG_WARN("VBI capture start failed\n"); clear_bit(CX18_F_S_STREAMING, &s_vbi->s_flags); goto start_failed; } CX18_DEBUG_INFO("VBI insertion started\n"); } } /* Tell the card to start capturing */ if (!cx18_start_v4l2_encode_stream(s)) { /* We're done */ set_bit(CX18_F_S_APPL_IO, &s->s_flags); /* Resume a possibly paused encoder */ if (test_and_clear_bit(CX18_F_I_ENC_PAUSED, &cx->i_flags)) cx18_vapi(cx, CX18_CPU_CAPTURE_PAUSE, 1, s->handle); return 0; } start_failed: CX18_DEBUG_WARN("Failed to start capturing for stream %s\n", s->name); /* * The associated VBI and IDX streams for internal use are released * automatically when the MPG stream is released. We only need to stop * the associated stream. */ if (s->type == CX18_ENC_STREAM_TYPE_MPG) { /* Stop the IDX stream which is always for internal use */ if (test_bit(CX18_F_S_STREAMING, &s_idx->s_flags)) { cx18_stop_v4l2_encode_stream(s_idx, 0); clear_bit(CX18_F_S_STREAMING, &s_idx->s_flags); } /* Stop the VBI stream, if only running for internal use */ if (test_bit(CX18_F_S_STREAMING, &s_vbi->s_flags) && !test_bit(CX18_F_S_APPL_IO, &s_vbi->s_flags)) { cx18_stop_v4l2_encode_stream(s_vbi, 0); clear_bit(CX18_F_S_STREAMING, &s_vbi->s_flags); } } clear_bit(CX18_F_S_STREAMING, &s->s_flags); cx18_release_stream(s); /* Also releases associated streams */ return -EIO; } ssize_t cx18_v4l2_read(struct file *filp, char __user *buf, size_t count, loff_t *pos) { struct cx18_open_id *id = file2id(filp); struct cx18 *cx = id->cx; struct cx18_stream *s = &cx->streams[id->type]; int rc; CX18_DEBUG_HI_FILE("read %zd bytes from %s\n", count, s->name); mutex_lock(&cx->serialize_lock); rc = cx18_start_capture(id); mutex_unlock(&cx->serialize_lock); if (rc) return rc; if ((s->vb_type == V4L2_BUF_TYPE_VIDEO_CAPTURE) && (id->type == CX18_ENC_STREAM_TYPE_YUV)) { return videobuf_read_stream(&s->vbuf_q, buf, count, pos, 0, filp->f_flags & O_NONBLOCK); } return cx18_read_pos(s, buf, count, pos, filp->f_flags & O_NONBLOCK); } unsigned int cx18_v4l2_enc_poll(struct file *filp, poll_table *wait) { struct cx18_open_id *id = file2id(filp); struct cx18 *cx = id->cx; struct cx18_stream *s = &cx->streams[id->type]; int eof = test_bit(CX18_F_S_STREAMOFF, &s->s_flags); /* Start a capture if there is none */ if (!eof && !test_bit(CX18_F_S_STREAMING, &s->s_flags)) { int rc; mutex_lock(&cx->serialize_lock); rc = cx18_start_capture(id); mutex_unlock(&cx->serialize_lock); if (rc) { CX18_DEBUG_INFO("Could not start capture for %s (%d)\n", s->name, rc); return POLLERR; } CX18_DEBUG_FILE("Encoder poll started capture\n"); } if ((s->vb_type == V4L2_BUF_TYPE_VIDEO_CAPTURE) && (id->type == CX18_ENC_STREAM_TYPE_YUV)) { int videobuf_poll = videobuf_poll_stream(filp, &s->vbuf_q, wait); if (eof && videobuf_poll == POLLERR) return POLLHUP; else return videobuf_poll; } /* add stream's waitq to the poll list */ CX18_DEBUG_HI_FILE("Encoder poll\n"); poll_wait(filp, &s->waitq, wait); if (atomic_read(&s->q_full.depth)) return POLLIN | POLLRDNORM; if (eof) return POLLHUP; return 0; } int cx18_v4l2_mmap(struct file *file, struct vm_area_struct *vma) { struct cx18_open_id *id = file->private_data; struct cx18 *cx = id->cx; struct cx18_stream *s = &cx->streams[id->type]; int eof = test_bit(CX18_F_S_STREAMOFF, &s->s_flags); if ((s->vb_type == V4L2_BUF_TYPE_VIDEO_CAPTURE) && (id->type == CX18_ENC_STREAM_TYPE_YUV)) { /* Start a capture if there is none */ if (!eof && !test_bit(CX18_F_S_STREAMING, &s->s_flags)) { int rc; mutex_lock(&cx->serialize_lock); rc = cx18_start_capture(id); mutex_unlock(&cx->serialize_lock); if (rc) { CX18_DEBUG_INFO( "Could not start capture for %s (%d)\n", s->name, rc); return -EINVAL; } CX18_DEBUG_FILE("Encoder mmap started capture\n"); } return videobuf_mmap_mapper(&s->vbuf_q, vma); } return -EINVAL; } void cx18_vb_timeout(unsigned long data) { struct cx18_stream *s = (struct cx18_stream *)data; struct cx18_videobuf_buffer *buf; unsigned long flags; /* Return all of the buffers in error state, so the vbi/vid inode * can return from blocking. */ spin_lock_irqsave(&s->vb_lock, flags); while (!list_empty(&s->vb_capture)) { buf = list_entry(s->vb_capture.next, struct cx18_videobuf_buffer, vb.queue); list_del(&buf->vb.queue); buf->vb.state = VIDEOBUF_ERROR; wake_up(&buf->vb.done); } spin_unlock_irqrestore(&s->vb_lock, flags); } void cx18_stop_capture(struct cx18_open_id *id, int gop_end) { struct cx18 *cx = id->cx; struct cx18_stream *s = &cx->streams[id->type]; struct cx18_stream *s_vbi = &cx->streams[CX18_ENC_STREAM_TYPE_VBI]; struct cx18_stream *s_idx = &cx->streams[CX18_ENC_STREAM_TYPE_IDX]; CX18_DEBUG_IOCTL("close() of %s\n", s->name); /* 'Unclaim' this stream */ /* Stop capturing */ if (test_bit(CX18_F_S_STREAMING, &s->s_flags)) { CX18_DEBUG_INFO("close stopping capture\n"); if (id->type == CX18_ENC_STREAM_TYPE_MPG) { /* Stop internal use associated VBI and IDX streams */ if (test_bit(CX18_F_S_STREAMING, &s_vbi->s_flags) && !test_bit(CX18_F_S_APPL_IO, &s_vbi->s_flags)) { CX18_DEBUG_INFO("close stopping embedded VBI " "capture\n"); cx18_stop_v4l2_encode_stream(s_vbi, 0); } if (test_bit(CX18_F_S_STREAMING, &s_idx->s_flags)) { CX18_DEBUG_INFO("close stopping IDX capture\n"); cx18_stop_v4l2_encode_stream(s_idx, 0); } } if (id->type == CX18_ENC_STREAM_TYPE_VBI && test_bit(CX18_F_S_INTERNAL_USE, &s->s_flags)) /* Also used internally, don't stop capturing */ s->id = -1; else cx18_stop_v4l2_encode_stream(s, gop_end); } if (!gop_end) { clear_bit(CX18_F_S_APPL_IO, &s->s_flags); clear_bit(CX18_F_S_STREAMOFF, &s->s_flags); cx18_release_stream(s); } } int cx18_v4l2_close(struct file *filp) { struct v4l2_fh *fh = filp->private_data; struct cx18_open_id *id = fh2id(fh); struct cx18 *cx = id->cx; struct cx18_stream *s = &cx->streams[id->type]; CX18_DEBUG_IOCTL("close() of %s\n", s->name); v4l2_fh_del(fh); v4l2_fh_exit(fh); /* Easy case first: this stream was never claimed by us */ if (s->id != id->open_id) { kfree(id); return 0; } /* 'Unclaim' this stream */ /* Stop radio */ mutex_lock(&cx->serialize_lock); if (id->type == CX18_ENC_STREAM_TYPE_RAD) { /* Closing radio device, return to TV mode */ cx18_mute(cx); /* Mark that the radio is no longer in use */ clear_bit(CX18_F_I_RADIO_USER, &cx->i_flags); /* Switch tuner to TV */ cx18_call_all(cx, core, s_std, cx->std); /* Select correct audio input (i.e. TV tuner or Line in) */ cx18_audio_set_io(cx); if (atomic_read(&cx->ana_capturing) > 0) { /* Undo video mute */ cx18_vapi(cx, CX18_CPU_SET_VIDEO_MUTE, 2, s->handle, (v4l2_ctrl_g_ctrl(cx->cxhdl.video_mute) | (v4l2_ctrl_g_ctrl(cx->cxhdl.video_mute_yuv) << 8))); } /* Done! Unmute and continue. */ cx18_unmute(cx); cx18_release_stream(s); } else { cx18_stop_capture(id, 0); if (id->type == CX18_ENC_STREAM_TYPE_YUV) videobuf_mmap_free(&id->vbuf_q); } kfree(id); mutex_unlock(&cx->serialize_lock); return 0; } static int cx18_serialized_open(struct cx18_stream *s, struct file *filp) { struct cx18 *cx = s->cx; struct cx18_open_id *item; CX18_DEBUG_FILE("open %s\n", s->name); /* Allocate memory */ item = kzalloc(sizeof(struct cx18_open_id), GFP_KERNEL); if (NULL == item) { CX18_DEBUG_WARN("nomem on v4l2 open\n"); return -ENOMEM; } v4l2_fh_init(&item->fh, s->video_dev); item->cx = cx; item->type = s->type; item->open_id = cx->open_id++; filp->private_data = &item->fh; if (item->type == CX18_ENC_STREAM_TYPE_RAD) { /* Try to claim this stream */ if (cx18_claim_stream(item, item->type)) { /* No, it's already in use */ v4l2_fh_exit(&item->fh); kfree(item); return -EBUSY; } if (!test_bit(CX18_F_I_RADIO_USER, &cx->i_flags)) { if (atomic_read(&cx->ana_capturing) > 0) { /* switching to radio while capture is in progress is not polite */ cx18_release_stream(s); v4l2_fh_exit(&item->fh); kfree(item); return -EBUSY; } } /* Mark that the radio is being used. */ set_bit(CX18_F_I_RADIO_USER, &cx->i_flags); /* We have the radio */ cx18_mute(cx); /* Switch tuner to radio */ cx18_call_all(cx, tuner, s_radio); /* Select the correct audio input (i.e. radio tuner) */ cx18_audio_set_io(cx); /* Done! Unmute and continue. */ cx18_unmute(cx); } v4l2_fh_add(&item->fh); return 0; } int cx18_v4l2_open(struct file *filp) { int res; struct video_device *video_dev = video_devdata(filp); struct cx18_stream *s = video_get_drvdata(video_dev); struct cx18 *cx = s->cx; mutex_lock(&cx->serialize_lock); if (cx18_init_on_first_open(cx)) { CX18_ERR("Failed to initialize on %s\n", video_device_node_name(video_dev)); mutex_unlock(&cx->serialize_lock); return -ENXIO; } res = cx18_serialized_open(s, filp); mutex_unlock(&cx->serialize_lock); return res; } void cx18_mute(struct cx18 *cx) { u32 h; if (atomic_read(&cx->ana_capturing)) { h = cx18_find_handle(cx); if (h != CX18_INVALID_TASK_HANDLE) cx18_vapi(cx, CX18_CPU_SET_AUDIO_MUTE, 2, h, 1); else CX18_ERR("Can't find valid task handle for mute\n"); } CX18_DEBUG_INFO("Mute\n"); } void cx18_unmute(struct cx18 *cx) { u32 h; if (atomic_read(&cx->ana_capturing)) { h = cx18_find_handle(cx); if (h != CX18_INVALID_TASK_HANDLE) { cx18_msleep_timeout(100, 0); cx18_vapi(cx, CX18_CPU_SET_MISC_PARAMETERS, 2, h, 12); cx18_vapi(cx, CX18_CPU_SET_AUDIO_MUTE, 2, h, 0); } else CX18_ERR("Can't find valid task handle for unmute\n"); } CX18_DEBUG_INFO("Unmute\n"); }
gpl-2.0
fivestars/ubuntu-nexus7
fs/proc/page.c
3286
4983
#include <linux/bootmem.h> #include <linux/compiler.h> #include <linux/fs.h> #include <linux/init.h> #include <linux/ksm.h> #include <linux/mm.h> #include <linux/mmzone.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/hugetlb.h> #include <linux/kernel-page-flags.h> #include <asm/uaccess.h> #include "internal.h" #define KPMSIZE sizeof(u64) #define KPMMASK (KPMSIZE - 1) /* /proc/kpagecount - an array exposing page counts * * Each entry is a u64 representing the corresponding * physical page count. */ static ssize_t kpagecount_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { u64 __user *out = (u64 __user *)buf; struct page *ppage; unsigned long src = *ppos; unsigned long pfn; ssize_t ret = 0; u64 pcount; pfn = src / KPMSIZE; count = min_t(size_t, count, (max_pfn * KPMSIZE) - src); if (src & KPMMASK || count & KPMMASK) return -EINVAL; while (count > 0) { if (pfn_valid(pfn)) ppage = pfn_to_page(pfn); else ppage = NULL; if (!ppage || PageSlab(ppage)) pcount = 0; else pcount = page_mapcount(ppage); if (put_user(pcount, out)) { ret = -EFAULT; break; } pfn++; out++; count -= KPMSIZE; } *ppos += (char __user *)out - buf; if (!ret) ret = (char __user *)out - buf; return ret; } static const struct file_operations proc_kpagecount_operations = { .llseek = mem_lseek, .read = kpagecount_read, }; /* /proc/kpageflags - an array exposing page flags * * Each entry is a u64 representing the corresponding * physical page flags. */ static inline u64 kpf_copy_bit(u64 kflags, int ubit, int kbit) { return ((kflags >> kbit) & 1) << ubit; } u64 stable_page_flags(struct page *page) { u64 k; u64 u; /* * pseudo flag: KPF_NOPAGE * it differentiates a memory hole from a page with no flags */ if (!page) return 1 << KPF_NOPAGE; k = page->flags; u = 0; /* * pseudo flags for the well known (anonymous) memory mapped pages * * Note that page->_mapcount is overloaded in SLOB/SLUB/SLQB, so the * simple test in page_mapped() is not enough. */ if (!PageSlab(page) && page_mapped(page)) u |= 1 << KPF_MMAP; if (PageAnon(page)) u |= 1 << KPF_ANON; if (PageKsm(page)) u |= 1 << KPF_KSM; /* * compound pages: export both head/tail info * they together define a compound page's start/end pos and order */ if (PageHead(page)) u |= 1 << KPF_COMPOUND_HEAD; if (PageTail(page)) u |= 1 << KPF_COMPOUND_TAIL; if (PageHuge(page)) u |= 1 << KPF_HUGE; /* * Caveats on high order pages: page->_count will only be set * -1 on the head page; SLUB/SLQB do the same for PG_slab; * SLOB won't set PG_slab at all on compound pages. */ if (PageBuddy(page)) u |= 1 << KPF_BUDDY; u |= kpf_copy_bit(k, KPF_LOCKED, PG_locked); u |= kpf_copy_bit(k, KPF_SLAB, PG_slab); u |= kpf_copy_bit(k, KPF_ERROR, PG_error); u |= kpf_copy_bit(k, KPF_DIRTY, PG_dirty); u |= kpf_copy_bit(k, KPF_UPTODATE, PG_uptodate); u |= kpf_copy_bit(k, KPF_WRITEBACK, PG_writeback); u |= kpf_copy_bit(k, KPF_LRU, PG_lru); u |= kpf_copy_bit(k, KPF_REFERENCED, PG_referenced); u |= kpf_copy_bit(k, KPF_ACTIVE, PG_active); u |= kpf_copy_bit(k, KPF_RECLAIM, PG_reclaim); u |= kpf_copy_bit(k, KPF_SWAPCACHE, PG_swapcache); u |= kpf_copy_bit(k, KPF_SWAPBACKED, PG_swapbacked); u |= kpf_copy_bit(k, KPF_UNEVICTABLE, PG_unevictable); u |= kpf_copy_bit(k, KPF_MLOCKED, PG_mlocked); #ifdef CONFIG_MEMORY_FAILURE u |= kpf_copy_bit(k, KPF_HWPOISON, PG_hwpoison); #endif #ifdef CONFIG_ARCH_USES_PG_UNCACHED u |= kpf_copy_bit(k, KPF_UNCACHED, PG_uncached); #endif u |= kpf_copy_bit(k, KPF_RESERVED, PG_reserved); u |= kpf_copy_bit(k, KPF_MAPPEDTODISK, PG_mappedtodisk); u |= kpf_copy_bit(k, KPF_PRIVATE, PG_private); u |= kpf_copy_bit(k, KPF_PRIVATE_2, PG_private_2); u |= kpf_copy_bit(k, KPF_OWNER_PRIVATE, PG_owner_priv_1); u |= kpf_copy_bit(k, KPF_ARCH, PG_arch_1); return u; }; static ssize_t kpageflags_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { u64 __user *out = (u64 __user *)buf; struct page *ppage; unsigned long src = *ppos; unsigned long pfn; ssize_t ret = 0; pfn = src / KPMSIZE; count = min_t(unsigned long, count, (max_pfn * KPMSIZE) - src); if (src & KPMMASK || count & KPMMASK) return -EINVAL; while (count > 0) { if (pfn_valid(pfn)) ppage = pfn_to_page(pfn); else ppage = NULL; if (put_user(stable_page_flags(ppage), out)) { ret = -EFAULT; break; } pfn++; out++; count -= KPMSIZE; } *ppos += (char __user *)out - buf; if (!ret) ret = (char __user *)out - buf; return ret; } static const struct file_operations proc_kpageflags_operations = { .llseek = mem_lseek, .read = kpageflags_read, }; static int __init proc_page_init(void) { proc_create("kpagecount", S_IRUSR, NULL, &proc_kpagecount_operations); proc_create("kpageflags", S_IRUSR, NULL, &proc_kpageflags_operations); return 0; } module_init(proc_page_init);
gpl-2.0
lissyx/codeaurora_kernel_msm
fs/proc/page.c
3286
4983
#include <linux/bootmem.h> #include <linux/compiler.h> #include <linux/fs.h> #include <linux/init.h> #include <linux/ksm.h> #include <linux/mm.h> #include <linux/mmzone.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/hugetlb.h> #include <linux/kernel-page-flags.h> #include <asm/uaccess.h> #include "internal.h" #define KPMSIZE sizeof(u64) #define KPMMASK (KPMSIZE - 1) /* /proc/kpagecount - an array exposing page counts * * Each entry is a u64 representing the corresponding * physical page count. */ static ssize_t kpagecount_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { u64 __user *out = (u64 __user *)buf; struct page *ppage; unsigned long src = *ppos; unsigned long pfn; ssize_t ret = 0; u64 pcount; pfn = src / KPMSIZE; count = min_t(size_t, count, (max_pfn * KPMSIZE) - src); if (src & KPMMASK || count & KPMMASK) return -EINVAL; while (count > 0) { if (pfn_valid(pfn)) ppage = pfn_to_page(pfn); else ppage = NULL; if (!ppage || PageSlab(ppage)) pcount = 0; else pcount = page_mapcount(ppage); if (put_user(pcount, out)) { ret = -EFAULT; break; } pfn++; out++; count -= KPMSIZE; } *ppos += (char __user *)out - buf; if (!ret) ret = (char __user *)out - buf; return ret; } static const struct file_operations proc_kpagecount_operations = { .llseek = mem_lseek, .read = kpagecount_read, }; /* /proc/kpageflags - an array exposing page flags * * Each entry is a u64 representing the corresponding * physical page flags. */ static inline u64 kpf_copy_bit(u64 kflags, int ubit, int kbit) { return ((kflags >> kbit) & 1) << ubit; } u64 stable_page_flags(struct page *page) { u64 k; u64 u; /* * pseudo flag: KPF_NOPAGE * it differentiates a memory hole from a page with no flags */ if (!page) return 1 << KPF_NOPAGE; k = page->flags; u = 0; /* * pseudo flags for the well known (anonymous) memory mapped pages * * Note that page->_mapcount is overloaded in SLOB/SLUB/SLQB, so the * simple test in page_mapped() is not enough. */ if (!PageSlab(page) && page_mapped(page)) u |= 1 << KPF_MMAP; if (PageAnon(page)) u |= 1 << KPF_ANON; if (PageKsm(page)) u |= 1 << KPF_KSM; /* * compound pages: export both head/tail info * they together define a compound page's start/end pos and order */ if (PageHead(page)) u |= 1 << KPF_COMPOUND_HEAD; if (PageTail(page)) u |= 1 << KPF_COMPOUND_TAIL; if (PageHuge(page)) u |= 1 << KPF_HUGE; /* * Caveats on high order pages: page->_count will only be set * -1 on the head page; SLUB/SLQB do the same for PG_slab; * SLOB won't set PG_slab at all on compound pages. */ if (PageBuddy(page)) u |= 1 << KPF_BUDDY; u |= kpf_copy_bit(k, KPF_LOCKED, PG_locked); u |= kpf_copy_bit(k, KPF_SLAB, PG_slab); u |= kpf_copy_bit(k, KPF_ERROR, PG_error); u |= kpf_copy_bit(k, KPF_DIRTY, PG_dirty); u |= kpf_copy_bit(k, KPF_UPTODATE, PG_uptodate); u |= kpf_copy_bit(k, KPF_WRITEBACK, PG_writeback); u |= kpf_copy_bit(k, KPF_LRU, PG_lru); u |= kpf_copy_bit(k, KPF_REFERENCED, PG_referenced); u |= kpf_copy_bit(k, KPF_ACTIVE, PG_active); u |= kpf_copy_bit(k, KPF_RECLAIM, PG_reclaim); u |= kpf_copy_bit(k, KPF_SWAPCACHE, PG_swapcache); u |= kpf_copy_bit(k, KPF_SWAPBACKED, PG_swapbacked); u |= kpf_copy_bit(k, KPF_UNEVICTABLE, PG_unevictable); u |= kpf_copy_bit(k, KPF_MLOCKED, PG_mlocked); #ifdef CONFIG_MEMORY_FAILURE u |= kpf_copy_bit(k, KPF_HWPOISON, PG_hwpoison); #endif #ifdef CONFIG_ARCH_USES_PG_UNCACHED u |= kpf_copy_bit(k, KPF_UNCACHED, PG_uncached); #endif u |= kpf_copy_bit(k, KPF_RESERVED, PG_reserved); u |= kpf_copy_bit(k, KPF_MAPPEDTODISK, PG_mappedtodisk); u |= kpf_copy_bit(k, KPF_PRIVATE, PG_private); u |= kpf_copy_bit(k, KPF_PRIVATE_2, PG_private_2); u |= kpf_copy_bit(k, KPF_OWNER_PRIVATE, PG_owner_priv_1); u |= kpf_copy_bit(k, KPF_ARCH, PG_arch_1); return u; }; static ssize_t kpageflags_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { u64 __user *out = (u64 __user *)buf; struct page *ppage; unsigned long src = *ppos; unsigned long pfn; ssize_t ret = 0; pfn = src / KPMSIZE; count = min_t(unsigned long, count, (max_pfn * KPMSIZE) - src); if (src & KPMMASK || count & KPMMASK) return -EINVAL; while (count > 0) { if (pfn_valid(pfn)) ppage = pfn_to_page(pfn); else ppage = NULL; if (put_user(stable_page_flags(ppage), out)) { ret = -EFAULT; break; } pfn++; out++; count -= KPMSIZE; } *ppos += (char __user *)out - buf; if (!ret) ret = (char __user *)out - buf; return ret; } static const struct file_operations proc_kpageflags_operations = { .llseek = mem_lseek, .read = kpageflags_read, }; static int __init proc_page_init(void) { proc_create("kpagecount", S_IRUSR, NULL, &proc_kpagecount_operations); proc_create("kpageflags", S_IRUSR, NULL, &proc_kpageflags_operations); return 0; } module_init(proc_page_init);
gpl-2.0
mkasick/android_kernel_samsung_d2vzw
drivers/ata/pata_radisys.c
3542
7039
/* * pata_radisys.c - Intel PATA/SATA controllers * * (C) 2006 Red Hat <alan@lxorguk.ukuu.org.uk> * * Some parts based on ata_piix.c by Jeff Garzik and others. * * A PIIX relative, this device has a single ATA channel and no * slave timings, SITRE or PPE. In that sense it is a close relative * of the original PIIX. It does however support UDMA 33/66 per channel * although no other modes/timings. Also lacking is 32bit I/O on the ATA * port. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/blkdev.h> #include <linux/delay.h> #include <linux/device.h> #include <scsi/scsi_host.h> #include <linux/libata.h> #include <linux/ata.h> #define DRV_NAME "pata_radisys" #define DRV_VERSION "0.4.4" /** * radisys_set_piomode - Initialize host controller PATA PIO timings * @ap: ATA port * @adev: Device whose timings we are configuring * * Set PIO mode for device, in host controller PCI config space. * * LOCKING: * None (inherited from caller). */ static void radisys_set_piomode (struct ata_port *ap, struct ata_device *adev) { unsigned int pio = adev->pio_mode - XFER_PIO_0; struct pci_dev *dev = to_pci_dev(ap->host->dev); u16 idetm_data; int control = 0; /* * See Intel Document 298600-004 for the timing programing rules * for PIIX/ICH. Note that the early PIIX does not have the slave * timing port at 0x44. The Radisys is a relative of the PIIX * but not the same so be careful. */ static const /* ISP RTC */ u8 timings[][2] = { { 0, 0 }, /* Check me */ { 0, 0 }, { 1, 1 }, { 2, 2 }, { 3, 3 }, }; if (pio > 0) control |= 1; /* TIME1 enable */ if (ata_pio_need_iordy(adev)) control |= 2; /* IE IORDY */ pci_read_config_word(dev, 0x40, &idetm_data); /* Enable IE and TIME as appropriate. Clear the other drive timing bits */ idetm_data &= 0xCCCC; idetm_data |= (control << (4 * adev->devno)); idetm_data |= (timings[pio][0] << 12) | (timings[pio][1] << 8); pci_write_config_word(dev, 0x40, idetm_data); /* Track which port is configured */ ap->private_data = adev; } /** * radisys_set_dmamode - Initialize host controller PATA DMA timings * @ap: Port whose timings we are configuring * @adev: Device to program * * Set MWDMA mode for device, in host controller PCI config space. * * LOCKING: * None (inherited from caller). */ static void radisys_set_dmamode (struct ata_port *ap, struct ata_device *adev) { struct pci_dev *dev = to_pci_dev(ap->host->dev); u16 idetm_data; u8 udma_enable; static const /* ISP RTC */ u8 timings[][2] = { { 0, 0 }, { 0, 0 }, { 1, 1 }, { 2, 2 }, { 3, 3 }, }; /* * MWDMA is driven by the PIO timings. We must also enable * IORDY unconditionally. */ pci_read_config_word(dev, 0x40, &idetm_data); pci_read_config_byte(dev, 0x48, &udma_enable); if (adev->dma_mode < XFER_UDMA_0) { unsigned int mwdma = adev->dma_mode - XFER_MW_DMA_0; const unsigned int needed_pio[3] = { XFER_PIO_0, XFER_PIO_3, XFER_PIO_4 }; int pio = needed_pio[mwdma] - XFER_PIO_0; int control = 3; /* IORDY|TIME0 */ /* If the drive MWDMA is faster than it can do PIO then we must force PIO0 for PIO cycles. */ if (adev->pio_mode < needed_pio[mwdma]) control = 1; /* Mask out the relevant control and timing bits we will load. Also clear the other drive TIME register as a precaution */ idetm_data &= 0xCCCC; idetm_data |= control << (4 * adev->devno); idetm_data |= (timings[pio][0] << 12) | (timings[pio][1] << 8); udma_enable &= ~(1 << adev->devno); } else { u8 udma_mode; /* UDMA66 on: UDMA 33 and 66 are switchable via register 0x4A */ pci_read_config_byte(dev, 0x4A, &udma_mode); if (adev->xfer_mode == XFER_UDMA_2) udma_mode &= ~(2 << (adev->devno * 4)); else /* UDMA 4 */ udma_mode |= (2 << (adev->devno * 4)); pci_write_config_byte(dev, 0x4A, udma_mode); udma_enable |= (1 << adev->devno); } pci_write_config_word(dev, 0x40, idetm_data); pci_write_config_byte(dev, 0x48, udma_enable); /* Track which port is configured */ ap->private_data = adev; } /** * radisys_qc_issue - command issue * @qc: command pending * * Called when the libata layer is about to issue a command. We wrap * this interface so that we can load the correct ATA timings if * necessary. Our logic also clears TIME0/TIME1 for the other device so * that, even if we get this wrong, cycles to the other device will * be made PIO0. */ static unsigned int radisys_qc_issue(struct ata_queued_cmd *qc) { struct ata_port *ap = qc->ap; struct ata_device *adev = qc->dev; if (adev != ap->private_data) { /* UDMA timing is not shared */ if (adev->dma_mode < XFER_UDMA_0) { if (adev->dma_mode) radisys_set_dmamode(ap, adev); else if (adev->pio_mode) radisys_set_piomode(ap, adev); } } return ata_bmdma_qc_issue(qc); } static struct scsi_host_template radisys_sht = { ATA_BMDMA_SHT(DRV_NAME), }; static struct ata_port_operations radisys_pata_ops = { .inherits = &ata_bmdma_port_ops, .qc_issue = radisys_qc_issue, .cable_detect = ata_cable_unknown, .set_piomode = radisys_set_piomode, .set_dmamode = radisys_set_dmamode, }; /** * radisys_init_one - Register PIIX ATA PCI device with kernel services * @pdev: PCI device to register * @ent: Entry in radisys_pci_tbl matching with @pdev * * Called from kernel PCI layer. We probe for combined mode (sigh), * and then hand over control to libata, for it to do the rest. * * LOCKING: * Inherited from PCI layer (may sleep). * * RETURNS: * Zero on success, or -ERRNO value. */ static int radisys_init_one (struct pci_dev *pdev, const struct pci_device_id *ent) { static int printed_version; static const struct ata_port_info info = { .flags = ATA_FLAG_SLAVE_POSS, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA12_ONLY, .udma_mask = ATA_UDMA24_ONLY, .port_ops = &radisys_pata_ops, }; const struct ata_port_info *ppi[] = { &info, NULL }; if (!printed_version++) dev_printk(KERN_DEBUG, &pdev->dev, "version " DRV_VERSION "\n"); return ata_pci_bmdma_init_one(pdev, ppi, &radisys_sht, NULL, 0); } static const struct pci_device_id radisys_pci_tbl[] = { { PCI_VDEVICE(RADISYS, 0x8201), }, { } /* terminate list */ }; static struct pci_driver radisys_pci_driver = { .name = DRV_NAME, .id_table = radisys_pci_tbl, .probe = radisys_init_one, .remove = ata_pci_remove_one, #ifdef CONFIG_PM .suspend = ata_pci_device_suspend, .resume = ata_pci_device_resume, #endif }; static int __init radisys_init(void) { return pci_register_driver(&radisys_pci_driver); } static void __exit radisys_exit(void) { pci_unregister_driver(&radisys_pci_driver); } module_init(radisys_init); module_exit(radisys_exit); MODULE_AUTHOR("Alan Cox"); MODULE_DESCRIPTION("SCSI low-level driver for Radisys R82600 controllers"); MODULE_LICENSE("GPL"); MODULE_DEVICE_TABLE(pci, radisys_pci_tbl); MODULE_VERSION(DRV_VERSION);
gpl-2.0
glewarne/S6_UniPR
drivers/hwspinlock/hwspinlock_core.c
3542
18002
/* * Hardware spinlock framework * * Copyright (C) 2010 Texas Instruments Incorporated - http://www.ti.com * * Contact: Ohad Ben-Cohen <ohad@wizery.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. */ #define pr_fmt(fmt) "%s: " fmt, __func__ #include <linux/kernel.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/types.h> #include <linux/err.h> #include <linux/jiffies.h> #include <linux/radix-tree.h> #include <linux/hwspinlock.h> #include <linux/pm_runtime.h> #include <linux/mutex.h> #include "hwspinlock_internal.h" /* radix tree tags */ #define HWSPINLOCK_UNUSED (0) /* tags an hwspinlock as unused */ /* * A radix tree is used to maintain the available hwspinlock instances. * The tree associates hwspinlock pointers with their integer key id, * and provides easy-to-use API which makes the hwspinlock core code simple * and easy to read. * * Radix trees are quick on lookups, and reasonably efficient in terms of * storage, especially with high density usages such as this framework * requires (a continuous range of integer keys, beginning with zero, is * used as the ID's of the hwspinlock instances). * * The radix tree API supports tagging items in the tree, which this * framework uses to mark unused hwspinlock instances (see the * HWSPINLOCK_UNUSED tag above). As a result, the process of querying the * tree, looking for an unused hwspinlock instance, is now reduced to a * single radix tree API call. */ static RADIX_TREE(hwspinlock_tree, GFP_KERNEL); /* * Synchronization of access to the tree is achieved using this mutex, * as the radix-tree API requires that users provide all synchronisation. * A mutex is needed because we're using non-atomic radix tree allocations. */ static DEFINE_MUTEX(hwspinlock_tree_lock); /** * __hwspin_trylock() - attempt to lock a specific hwspinlock * @hwlock: an hwspinlock which we want to trylock * @mode: controls whether local interrupts are disabled or not * @flags: a pointer where the caller's interrupt state will be saved at (if * requested) * * This function attempts to lock an hwspinlock, and will immediately * fail if the hwspinlock is already taken. * * Upon a successful return from this function, preemption (and possibly * interrupts) is disabled, so the caller must not sleep, and is advised to * release the hwspinlock as soon as possible. This is required in order to * minimize remote cores polling on the hardware interconnect. * * The user decides whether local interrupts are disabled or not, and if yes, * whether he wants their previous state to be saved. It is up to the user * to choose the appropriate @mode of operation, exactly the same way users * should decide between spin_trylock, spin_trylock_irq and * spin_trylock_irqsave. * * Returns 0 if we successfully locked the hwspinlock or -EBUSY if * the hwspinlock was already taken. * This function will never sleep. */ int __hwspin_trylock(struct hwspinlock *hwlock, int mode, unsigned long *flags) { int ret; BUG_ON(!hwlock); BUG_ON(!flags && mode == HWLOCK_IRQSTATE); /* * This spin_lock{_irq, _irqsave} serves three purposes: * * 1. Disable preemption, in order to minimize the period of time * in which the hwspinlock is taken. This is important in order * to minimize the possible polling on the hardware interconnect * by a remote user of this lock. * 2. Make the hwspinlock SMP-safe (so we can take it from * additional contexts on the local host). * 3. Ensure that in_atomic/might_sleep checks catch potential * problems with hwspinlock usage (e.g. scheduler checks like * 'scheduling while atomic' etc.) */ if (mode == HWLOCK_IRQSTATE) ret = spin_trylock_irqsave(&hwlock->lock, *flags); else if (mode == HWLOCK_IRQ) ret = spin_trylock_irq(&hwlock->lock); else ret = spin_trylock(&hwlock->lock); /* is lock already taken by another context on the local cpu ? */ if (!ret) return -EBUSY; /* try to take the hwspinlock device */ ret = hwlock->bank->ops->trylock(hwlock); /* if hwlock is already taken, undo spin_trylock_* and exit */ if (!ret) { if (mode == HWLOCK_IRQSTATE) spin_unlock_irqrestore(&hwlock->lock, *flags); else if (mode == HWLOCK_IRQ) spin_unlock_irq(&hwlock->lock); else spin_unlock(&hwlock->lock); return -EBUSY; } /* * We can be sure the other core's memory operations * are observable to us only _after_ we successfully take * the hwspinlock, and we must make sure that subsequent memory * operations (both reads and writes) will not be reordered before * we actually took the hwspinlock. * * Note: the implicit memory barrier of the spinlock above is too * early, so we need this additional explicit memory barrier. */ mb(); return 0; } EXPORT_SYMBOL_GPL(__hwspin_trylock); /** * __hwspin_lock_timeout() - lock an hwspinlock with timeout limit * @hwlock: the hwspinlock to be locked * @timeout: timeout value in msecs * @mode: mode which controls whether local interrupts are disabled or not * @flags: a pointer to where the caller's interrupt state will be saved at (if * requested) * * This function locks the given @hwlock. If the @hwlock * is already taken, the function will busy loop waiting for it to * be released, but give up after @timeout msecs have elapsed. * * Upon a successful return from this function, preemption is disabled * (and possibly local interrupts, too), so the caller must not sleep, * and is advised to release the hwspinlock as soon as possible. * This is required in order to minimize remote cores polling on the * hardware interconnect. * * The user decides whether local interrupts are disabled or not, and if yes, * whether he wants their previous state to be saved. It is up to the user * to choose the appropriate @mode of operation, exactly the same way users * should decide between spin_lock, spin_lock_irq and spin_lock_irqsave. * * Returns 0 when the @hwlock was successfully taken, and an appropriate * error code otherwise (most notably -ETIMEDOUT if the @hwlock is still * busy after @timeout msecs). The function will never sleep. */ int __hwspin_lock_timeout(struct hwspinlock *hwlock, unsigned int to, int mode, unsigned long *flags) { int ret; unsigned long expire; expire = msecs_to_jiffies(to) + jiffies; for (;;) { /* Try to take the hwspinlock */ ret = __hwspin_trylock(hwlock, mode, flags); if (ret != -EBUSY) break; /* * The lock is already taken, let's check if the user wants * us to try again */ if (time_is_before_eq_jiffies(expire)) return -ETIMEDOUT; /* * Allow platform-specific relax handlers to prevent * hogging the interconnect (no sleeping, though) */ if (hwlock->bank->ops->relax) hwlock->bank->ops->relax(hwlock); } return ret; } EXPORT_SYMBOL_GPL(__hwspin_lock_timeout); /** * __hwspin_unlock() - unlock a specific hwspinlock * @hwlock: a previously-acquired hwspinlock which we want to unlock * @mode: controls whether local interrupts needs to be restored or not * @flags: previous caller's interrupt state to restore (if requested) * * This function will unlock a specific hwspinlock, enable preemption and * (possibly) enable interrupts or restore their previous state. * @hwlock must be already locked before calling this function: it is a bug * to call unlock on a @hwlock that is already unlocked. * * The user decides whether local interrupts should be enabled or not, and * if yes, whether he wants their previous state to be restored. It is up * to the user to choose the appropriate @mode of operation, exactly the * same way users decide between spin_unlock, spin_unlock_irq and * spin_unlock_irqrestore. * * The function will never sleep. */ void __hwspin_unlock(struct hwspinlock *hwlock, int mode, unsigned long *flags) { BUG_ON(!hwlock); BUG_ON(!flags && mode == HWLOCK_IRQSTATE); /* * We must make sure that memory operations (both reads and writes), * done before unlocking the hwspinlock, will not be reordered * after the lock is released. * * That's the purpose of this explicit memory barrier. * * Note: the memory barrier induced by the spin_unlock below is too * late; the other core is going to access memory soon after it will * take the hwspinlock, and by then we want to be sure our memory * operations are already observable. */ mb(); hwlock->bank->ops->unlock(hwlock); /* Undo the spin_trylock{_irq, _irqsave} called while locking */ if (mode == HWLOCK_IRQSTATE) spin_unlock_irqrestore(&hwlock->lock, *flags); else if (mode == HWLOCK_IRQ) spin_unlock_irq(&hwlock->lock); else spin_unlock(&hwlock->lock); } EXPORT_SYMBOL_GPL(__hwspin_unlock); static int hwspin_lock_register_single(struct hwspinlock *hwlock, int id) { struct hwspinlock *tmp; int ret; mutex_lock(&hwspinlock_tree_lock); ret = radix_tree_insert(&hwspinlock_tree, id, hwlock); if (ret) { if (ret == -EEXIST) pr_err("hwspinlock id %d already exists!\n", id); goto out; } /* mark this hwspinlock as available */ tmp = radix_tree_tag_set(&hwspinlock_tree, id, HWSPINLOCK_UNUSED); /* self-sanity check which should never fail */ WARN_ON(tmp != hwlock); out: mutex_unlock(&hwspinlock_tree_lock); return 0; } static struct hwspinlock *hwspin_lock_unregister_single(unsigned int id) { struct hwspinlock *hwlock = NULL; int ret; mutex_lock(&hwspinlock_tree_lock); /* make sure the hwspinlock is not in use (tag is set) */ ret = radix_tree_tag_get(&hwspinlock_tree, id, HWSPINLOCK_UNUSED); if (ret == 0) { pr_err("hwspinlock %d still in use (or not present)\n", id); goto out; } hwlock = radix_tree_delete(&hwspinlock_tree, id); if (!hwlock) { pr_err("failed to delete hwspinlock %d\n", id); goto out; } out: mutex_unlock(&hwspinlock_tree_lock); return hwlock; } /** * hwspin_lock_register() - register a new hw spinlock device * @bank: the hwspinlock device, which usually provides numerous hw locks * @dev: the backing device * @ops: hwspinlock handlers for this device * @base_id: id of the first hardware spinlock in this bank * @num_locks: number of hwspinlocks provided by this device * * This function should be called from the underlying platform-specific * implementation, to register a new hwspinlock device instance. * * Should be called from a process context (might sleep) * * Returns 0 on success, or an appropriate error code on failure */ int hwspin_lock_register(struct hwspinlock_device *bank, struct device *dev, const struct hwspinlock_ops *ops, int base_id, int num_locks) { struct hwspinlock *hwlock; int ret = 0, i; if (!bank || !ops || !dev || !num_locks || !ops->trylock || !ops->unlock) { pr_err("invalid parameters\n"); return -EINVAL; } bank->dev = dev; bank->ops = ops; bank->base_id = base_id; bank->num_locks = num_locks; for (i = 0; i < num_locks; i++) { hwlock = &bank->lock[i]; spin_lock_init(&hwlock->lock); hwlock->bank = bank; ret = hwspin_lock_register_single(hwlock, base_id + i); if (ret) goto reg_failed; } return 0; reg_failed: while (--i >= 0) hwspin_lock_unregister_single(base_id + i); return ret; } EXPORT_SYMBOL_GPL(hwspin_lock_register); /** * hwspin_lock_unregister() - unregister an hw spinlock device * @bank: the hwspinlock device, which usually provides numerous hw locks * * This function should be called from the underlying platform-specific * implementation, to unregister an existing (and unused) hwspinlock. * * Should be called from a process context (might sleep) * * Returns 0 on success, or an appropriate error code on failure */ int hwspin_lock_unregister(struct hwspinlock_device *bank) { struct hwspinlock *hwlock, *tmp; int i; for (i = 0; i < bank->num_locks; i++) { hwlock = &bank->lock[i]; tmp = hwspin_lock_unregister_single(bank->base_id + i); if (!tmp) return -EBUSY; /* self-sanity check that should never fail */ WARN_ON(tmp != hwlock); } return 0; } EXPORT_SYMBOL_GPL(hwspin_lock_unregister); /** * __hwspin_lock_request() - tag an hwspinlock as used and power it up * * This is an internal function that prepares an hwspinlock instance * before it is given to the user. The function assumes that * hwspinlock_tree_lock is taken. * * Returns 0 or positive to indicate success, and a negative value to * indicate an error (with the appropriate error code) */ static int __hwspin_lock_request(struct hwspinlock *hwlock) { struct device *dev = hwlock->bank->dev; struct hwspinlock *tmp; int ret; /* prevent underlying implementation from being removed */ if (!try_module_get(dev->driver->owner)) { dev_err(dev, "%s: can't get owner\n", __func__); return -EINVAL; } /* notify PM core that power is now needed */ ret = pm_runtime_get_sync(dev); if (ret < 0) { dev_err(dev, "%s: can't power on device\n", __func__); pm_runtime_put_noidle(dev); module_put(dev->driver->owner); return ret; } /* mark hwspinlock as used, should not fail */ tmp = radix_tree_tag_clear(&hwspinlock_tree, hwlock_to_id(hwlock), HWSPINLOCK_UNUSED); /* self-sanity check that should never fail */ WARN_ON(tmp != hwlock); return ret; } /** * hwspin_lock_get_id() - retrieve id number of a given hwspinlock * @hwlock: a valid hwspinlock instance * * Returns the id number of a given @hwlock, or -EINVAL if @hwlock is invalid. */ int hwspin_lock_get_id(struct hwspinlock *hwlock) { if (!hwlock) { pr_err("invalid hwlock\n"); return -EINVAL; } return hwlock_to_id(hwlock); } EXPORT_SYMBOL_GPL(hwspin_lock_get_id); /** * hwspin_lock_request() - request an hwspinlock * * This function should be called by users of the hwspinlock device, * in order to dynamically assign them an unused hwspinlock. * Usually the user of this lock will then have to communicate the lock's id * to the remote core before it can be used for synchronization (to get the * id of a given hwlock, use hwspin_lock_get_id()). * * Should be called from a process context (might sleep) * * Returns the address of the assigned hwspinlock, or NULL on error */ struct hwspinlock *hwspin_lock_request(void) { struct hwspinlock *hwlock; int ret; mutex_lock(&hwspinlock_tree_lock); /* look for an unused lock */ ret = radix_tree_gang_lookup_tag(&hwspinlock_tree, (void **)&hwlock, 0, 1, HWSPINLOCK_UNUSED); if (ret == 0) { pr_warn("a free hwspinlock is not available\n"); hwlock = NULL; goto out; } /* sanity check that should never fail */ WARN_ON(ret > 1); /* mark as used and power up */ ret = __hwspin_lock_request(hwlock); if (ret < 0) hwlock = NULL; out: mutex_unlock(&hwspinlock_tree_lock); return hwlock; } EXPORT_SYMBOL_GPL(hwspin_lock_request); /** * hwspin_lock_request_specific() - request for a specific hwspinlock * @id: index of the specific hwspinlock that is requested * * This function should be called by users of the hwspinlock module, * in order to assign them a specific hwspinlock. * Usually early board code will be calling this function in order to * reserve specific hwspinlock ids for predefined purposes. * * Should be called from a process context (might sleep) * * Returns the address of the assigned hwspinlock, or NULL on error */ struct hwspinlock *hwspin_lock_request_specific(unsigned int id) { struct hwspinlock *hwlock; int ret; mutex_lock(&hwspinlock_tree_lock); /* make sure this hwspinlock exists */ hwlock = radix_tree_lookup(&hwspinlock_tree, id); if (!hwlock) { pr_warn("hwspinlock %u does not exist\n", id); goto out; } /* sanity check (this shouldn't happen) */ WARN_ON(hwlock_to_id(hwlock) != id); /* make sure this hwspinlock is unused */ ret = radix_tree_tag_get(&hwspinlock_tree, id, HWSPINLOCK_UNUSED); if (ret == 0) { pr_warn("hwspinlock %u is already in use\n", id); hwlock = NULL; goto out; } /* mark as used and power up */ ret = __hwspin_lock_request(hwlock); if (ret < 0) hwlock = NULL; out: mutex_unlock(&hwspinlock_tree_lock); return hwlock; } EXPORT_SYMBOL_GPL(hwspin_lock_request_specific); /** * hwspin_lock_free() - free a specific hwspinlock * @hwlock: the specific hwspinlock to free * * This function mark @hwlock as free again. * Should only be called with an @hwlock that was retrieved from * an earlier call to omap_hwspin_lock_request{_specific}. * * Should be called from a process context (might sleep) * * Returns 0 on success, or an appropriate error code on failure */ int hwspin_lock_free(struct hwspinlock *hwlock) { struct device *dev; struct hwspinlock *tmp; int ret; if (!hwlock) { pr_err("invalid hwlock\n"); return -EINVAL; } dev = hwlock->bank->dev; mutex_lock(&hwspinlock_tree_lock); /* make sure the hwspinlock is used */ ret = radix_tree_tag_get(&hwspinlock_tree, hwlock_to_id(hwlock), HWSPINLOCK_UNUSED); if (ret == 1) { dev_err(dev, "%s: hwlock is already free\n", __func__); dump_stack(); ret = -EINVAL; goto out; } /* notify the underlying device that power is not needed */ ret = pm_runtime_put(dev); if (ret < 0) goto out; /* mark this hwspinlock as available */ tmp = radix_tree_tag_set(&hwspinlock_tree, hwlock_to_id(hwlock), HWSPINLOCK_UNUSED); /* sanity check (this shouldn't happen) */ WARN_ON(tmp != hwlock); module_put(dev->driver->owner); out: mutex_unlock(&hwspinlock_tree_lock); return ret; } EXPORT_SYMBOL_GPL(hwspin_lock_free); MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("Hardware spinlock interface"); MODULE_AUTHOR("Ohad Ben-Cohen <ohad@wizery.com>");
gpl-2.0
moddingg33k/deprecated_android_kernel_synopsis
drivers/net/wireless/brcm80211/brcmsmac/srom.c
4822
31078
/* * Copyright (c) 2010 Broadcom Corporation * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <linux/kernel.h> #include <linux/string.h> #include <linux/io.h> #include <linux/etherdevice.h> #include <linux/crc8.h> #include <stdarg.h> #include <chipcommon.h> #include <brcmu_utils.h> #include "pub.h" #include "nicpci.h" #include "aiutils.h" #include "otp.h" #include "srom.h" #include "soc.h" /* * SROM CRC8 polynomial value: * * x^8 + x^7 +x^6 + x^4 + x^2 + 1 */ #define SROM_CRC8_POLY 0xAB /* Maximum srom: 6 Kilobits == 768 bytes */ #define SROM_MAX 768 /* PCI fields */ #define PCI_F0DEVID 48 #define SROM_WORDS 64 #define SROM_SSID 2 #define SROM_WL1LHMAXP 29 #define SROM_WL1LPAB0 30 #define SROM_WL1LPAB1 31 #define SROM_WL1LPAB2 32 #define SROM_WL1HPAB0 33 #define SROM_WL1HPAB1 34 #define SROM_WL1HPAB2 35 #define SROM_MACHI_IL0 36 #define SROM_MACMID_IL0 37 #define SROM_MACLO_IL0 38 #define SROM_MACHI_ET1 42 #define SROM_MACMID_ET1 43 #define SROM_MACLO_ET1 44 #define SROM_BXARSSI2G 40 #define SROM_BXARSSI5G 41 #define SROM_TRI52G 42 #define SROM_TRI5GHL 43 #define SROM_RXPO52G 45 #define SROM_AABREV 46 /* Fields in AABREV */ #define SROM_BR_MASK 0x00ff #define SROM_CC_MASK 0x0f00 #define SROM_CC_SHIFT 8 #define SROM_AA0_MASK 0x3000 #define SROM_AA0_SHIFT 12 #define SROM_AA1_MASK 0xc000 #define SROM_AA1_SHIFT 14 #define SROM_WL0PAB0 47 #define SROM_WL0PAB1 48 #define SROM_WL0PAB2 49 #define SROM_LEDBH10 50 #define SROM_LEDBH32 51 #define SROM_WL10MAXP 52 #define SROM_WL1PAB0 53 #define SROM_WL1PAB1 54 #define SROM_WL1PAB2 55 #define SROM_ITT 56 #define SROM_BFL 57 #define SROM_BFL2 28 #define SROM_AG10 58 #define SROM_CCODE 59 #define SROM_OPO 60 #define SROM_CRCREV 63 #define SROM4_WORDS 220 #define SROM4_TXCHAIN_MASK 0x000f #define SROM4_RXCHAIN_MASK 0x00f0 #define SROM4_SWITCH_MASK 0xff00 /* Per-path fields */ #define MAX_PATH_SROM 4 #define SROM4_CRCREV 219 /* SROM Rev 8: Make space for a 48word hardware header for PCIe rev >= 6. * This is acombined srom for both MIMO and SISO boards, usable in * the .130 4Kilobit OTP with hardware redundancy. */ #define SROM8_BREV 65 #define SROM8_BFL0 66 #define SROM8_BFL1 67 #define SROM8_BFL2 68 #define SROM8_BFL3 69 #define SROM8_MACHI 70 #define SROM8_MACMID 71 #define SROM8_MACLO 72 #define SROM8_CCODE 73 #define SROM8_REGREV 74 #define SROM8_LEDBH10 75 #define SROM8_LEDBH32 76 #define SROM8_LEDDC 77 #define SROM8_AA 78 #define SROM8_AG10 79 #define SROM8_AG32 80 #define SROM8_TXRXC 81 #define SROM8_BXARSSI2G 82 #define SROM8_BXARSSI5G 83 #define SROM8_TRI52G 84 #define SROM8_TRI5GHL 85 #define SROM8_RXPO52G 86 #define SROM8_FEM2G 87 #define SROM8_FEM5G 88 #define SROM8_FEM_ANTSWLUT_MASK 0xf800 #define SROM8_FEM_ANTSWLUT_SHIFT 11 #define SROM8_FEM_TR_ISO_MASK 0x0700 #define SROM8_FEM_TR_ISO_SHIFT 8 #define SROM8_FEM_PDET_RANGE_MASK 0x00f8 #define SROM8_FEM_PDET_RANGE_SHIFT 3 #define SROM8_FEM_EXTPA_GAIN_MASK 0x0006 #define SROM8_FEM_EXTPA_GAIN_SHIFT 1 #define SROM8_FEM_TSSIPOS_MASK 0x0001 #define SROM8_FEM_TSSIPOS_SHIFT 0 #define SROM8_THERMAL 89 /* Temp sense related entries */ #define SROM8_MPWR_RAWTS 90 #define SROM8_TS_SLP_OPT_CORRX 91 /* FOC: freiquency offset correction, HWIQ: H/W IOCAL enable, * IQSWP: IQ CAL swap disable */ #define SROM8_FOC_HWIQ_IQSWP 92 /* Temperature delta for PHY calibration */ #define SROM8_PHYCAL_TEMPDELTA 93 /* Per-path offsets & fields */ #define SROM8_PATH0 96 #define SROM8_PATH1 112 #define SROM8_PATH2 128 #define SROM8_PATH3 144 #define SROM8_2G_ITT_MAXP 0 #define SROM8_2G_PA 1 #define SROM8_5G_ITT_MAXP 4 #define SROM8_5GLH_MAXP 5 #define SROM8_5G_PA 6 #define SROM8_5GL_PA 9 #define SROM8_5GH_PA 12 /* All the miriad power offsets */ #define SROM8_2G_CCKPO 160 #define SROM8_2G_OFDMPO 161 #define SROM8_5G_OFDMPO 163 #define SROM8_5GL_OFDMPO 165 #define SROM8_5GH_OFDMPO 167 #define SROM8_2G_MCSPO 169 #define SROM8_5G_MCSPO 177 #define SROM8_5GL_MCSPO 185 #define SROM8_5GH_MCSPO 193 #define SROM8_CDDPO 201 #define SROM8_STBCPO 202 #define SROM8_BW40PO 203 #define SROM8_BWDUPPO 204 /* SISO PA parameters are in the path0 spaces */ #define SROM8_SISO 96 /* Legacy names for SISO PA paramters */ #define SROM8_W0_ITTMAXP (SROM8_SISO + SROM8_2G_ITT_MAXP) #define SROM8_W0_PAB0 (SROM8_SISO + SROM8_2G_PA) #define SROM8_W0_PAB1 (SROM8_SISO + SROM8_2G_PA + 1) #define SROM8_W0_PAB2 (SROM8_SISO + SROM8_2G_PA + 2) #define SROM8_W1_ITTMAXP (SROM8_SISO + SROM8_5G_ITT_MAXP) #define SROM8_W1_MAXP_LCHC (SROM8_SISO + SROM8_5GLH_MAXP) #define SROM8_W1_PAB0 (SROM8_SISO + SROM8_5G_PA) #define SROM8_W1_PAB1 (SROM8_SISO + SROM8_5G_PA + 1) #define SROM8_W1_PAB2 (SROM8_SISO + SROM8_5G_PA + 2) #define SROM8_W1_PAB0_LC (SROM8_SISO + SROM8_5GL_PA) #define SROM8_W1_PAB1_LC (SROM8_SISO + SROM8_5GL_PA + 1) #define SROM8_W1_PAB2_LC (SROM8_SISO + SROM8_5GL_PA + 2) #define SROM8_W1_PAB0_HC (SROM8_SISO + SROM8_5GH_PA) #define SROM8_W1_PAB1_HC (SROM8_SISO + SROM8_5GH_PA + 1) #define SROM8_W1_PAB2_HC (SROM8_SISO + SROM8_5GH_PA + 2) /* SROM REV 9 */ #define SROM9_2GPO_CCKBW20 160 #define SROM9_2GPO_CCKBW20UL 161 #define SROM9_2GPO_LOFDMBW20 162 #define SROM9_2GPO_LOFDMBW20UL 164 #define SROM9_5GLPO_LOFDMBW20 166 #define SROM9_5GLPO_LOFDMBW20UL 168 #define SROM9_5GMPO_LOFDMBW20 170 #define SROM9_5GMPO_LOFDMBW20UL 172 #define SROM9_5GHPO_LOFDMBW20 174 #define SROM9_5GHPO_LOFDMBW20UL 176 #define SROM9_2GPO_MCSBW20 178 #define SROM9_2GPO_MCSBW20UL 180 #define SROM9_2GPO_MCSBW40 182 #define SROM9_5GLPO_MCSBW20 184 #define SROM9_5GLPO_MCSBW20UL 186 #define SROM9_5GLPO_MCSBW40 188 #define SROM9_5GMPO_MCSBW20 190 #define SROM9_5GMPO_MCSBW20UL 192 #define SROM9_5GMPO_MCSBW40 194 #define SROM9_5GHPO_MCSBW20 196 #define SROM9_5GHPO_MCSBW20UL 198 #define SROM9_5GHPO_MCSBW40 200 #define SROM9_PO_MCS32 202 #define SROM9_PO_LOFDM40DUP 203 /* SROM flags (see sromvar_t) */ /* value continues as described by the next entry */ #define SRFL_MORE 1 #define SRFL_NOFFS 2 /* value bits can't be all one's */ #define SRFL_PRHEX 4 /* value is in hexdecimal format */ #define SRFL_PRSIGN 8 /* value is in signed decimal format */ #define SRFL_CCODE 0x10 /* value is in country code format */ #define SRFL_ETHADDR 0x20 /* value is an Ethernet address */ #define SRFL_LEDDC 0x40 /* value is an LED duty cycle */ /* do not generate a nvram param, entry is for mfgc */ #define SRFL_NOVAR 0x80 /* Max. nvram variable table size */ #define MAXSZ_NVRAM_VARS 4096 /* * indicates type of value. */ enum brcms_srom_var_type { BRCMS_SROM_STRING, BRCMS_SROM_SNUMBER, BRCMS_SROM_UNUMBER }; /* * storage type for srom variable. * * var_list: for linked list operations. * varid: identifier of the variable. * var_type: type of variable. * buf: variable value when var_type == BRCMS_SROM_STRING. * uval: unsigned variable value when var_type == BRCMS_SROM_UNUMBER. * sval: signed variable value when var_type == BRCMS_SROM_SNUMBER. */ struct brcms_srom_list_head { struct list_head var_list; enum brcms_srom_id varid; enum brcms_srom_var_type var_type; union { char buf[0]; u32 uval; s32 sval; }; }; struct brcms_sromvar { enum brcms_srom_id varid; u32 revmask; u32 flags; u16 off; u16 mask; }; struct brcms_varbuf { char *base; /* pointer to buffer base */ char *buf; /* pointer to current position */ unsigned int size; /* current (residual) size in bytes */ }; /* * Assumptions: * - Ethernet address spans across 3 consecutive words * * Table rules: * - Add multiple entries next to each other if a value spans across multiple * words (even multiple fields in the same word) with each entry except the * last having it's SRFL_MORE bit set. * - Ethernet address entry does not follow above rule and must not have * SRFL_MORE bit set. Its SRFL_ETHADDR bit implies it takes multiple words. * - The last entry's name field must be NULL to indicate the end of the table. * Other entries must have non-NULL name. */ static const struct brcms_sromvar pci_sromvars[] = { {BRCMS_SROM_DEVID, 0xffffff00, SRFL_PRHEX | SRFL_NOVAR, PCI_F0DEVID, 0xffff}, {BRCMS_SROM_BOARDREV, 0xffffff00, SRFL_PRHEX, SROM8_BREV, 0xffff}, {BRCMS_SROM_BOARDFLAGS, 0xffffff00, SRFL_PRHEX | SRFL_MORE, SROM8_BFL0, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM8_BFL1, 0xffff}, {BRCMS_SROM_BOARDFLAGS2, 0xffffff00, SRFL_PRHEX | SRFL_MORE, SROM8_BFL2, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM8_BFL3, 0xffff}, {BRCMS_SROM_BOARDTYPE, 0xfffffffc, SRFL_PRHEX, SROM_SSID, 0xffff}, {BRCMS_SROM_BOARDNUM, 0xffffff00, 0, SROM8_MACLO, 0xffff}, {BRCMS_SROM_REGREV, 0xffffff00, 0, SROM8_REGREV, 0x00ff}, {BRCMS_SROM_LEDBH0, 0xffffff00, SRFL_NOFFS, SROM8_LEDBH10, 0x00ff}, {BRCMS_SROM_LEDBH1, 0xffffff00, SRFL_NOFFS, SROM8_LEDBH10, 0xff00}, {BRCMS_SROM_LEDBH2, 0xffffff00, SRFL_NOFFS, SROM8_LEDBH32, 0x00ff}, {BRCMS_SROM_LEDBH3, 0xffffff00, SRFL_NOFFS, SROM8_LEDBH32, 0xff00}, {BRCMS_SROM_PA0B0, 0xffffff00, SRFL_PRHEX, SROM8_W0_PAB0, 0xffff}, {BRCMS_SROM_PA0B1, 0xffffff00, SRFL_PRHEX, SROM8_W0_PAB1, 0xffff}, {BRCMS_SROM_PA0B2, 0xffffff00, SRFL_PRHEX, SROM8_W0_PAB2, 0xffff}, {BRCMS_SROM_PA0ITSSIT, 0xffffff00, 0, SROM8_W0_ITTMAXP, 0xff00}, {BRCMS_SROM_PA0MAXPWR, 0xffffff00, 0, SROM8_W0_ITTMAXP, 0x00ff}, {BRCMS_SROM_OPO, 0xffffff00, 0, SROM8_2G_OFDMPO, 0x00ff}, {BRCMS_SROM_AA2G, 0xffffff00, 0, SROM8_AA, 0x00ff}, {BRCMS_SROM_AA5G, 0xffffff00, 0, SROM8_AA, 0xff00}, {BRCMS_SROM_AG0, 0xffffff00, 0, SROM8_AG10, 0x00ff}, {BRCMS_SROM_AG1, 0xffffff00, 0, SROM8_AG10, 0xff00}, {BRCMS_SROM_AG2, 0xffffff00, 0, SROM8_AG32, 0x00ff}, {BRCMS_SROM_AG3, 0xffffff00, 0, SROM8_AG32, 0xff00}, {BRCMS_SROM_PA1B0, 0xffffff00, SRFL_PRHEX, SROM8_W1_PAB0, 0xffff}, {BRCMS_SROM_PA1B1, 0xffffff00, SRFL_PRHEX, SROM8_W1_PAB1, 0xffff}, {BRCMS_SROM_PA1B2, 0xffffff00, SRFL_PRHEX, SROM8_W1_PAB2, 0xffff}, {BRCMS_SROM_PA1LOB0, 0xffffff00, SRFL_PRHEX, SROM8_W1_PAB0_LC, 0xffff}, {BRCMS_SROM_PA1LOB1, 0xffffff00, SRFL_PRHEX, SROM8_W1_PAB1_LC, 0xffff}, {BRCMS_SROM_PA1LOB2, 0xffffff00, SRFL_PRHEX, SROM8_W1_PAB2_LC, 0xffff}, {BRCMS_SROM_PA1HIB0, 0xffffff00, SRFL_PRHEX, SROM8_W1_PAB0_HC, 0xffff}, {BRCMS_SROM_PA1HIB1, 0xffffff00, SRFL_PRHEX, SROM8_W1_PAB1_HC, 0xffff}, {BRCMS_SROM_PA1HIB2, 0xffffff00, SRFL_PRHEX, SROM8_W1_PAB2_HC, 0xffff}, {BRCMS_SROM_PA1ITSSIT, 0xffffff00, 0, SROM8_W1_ITTMAXP, 0xff00}, {BRCMS_SROM_PA1MAXPWR, 0xffffff00, 0, SROM8_W1_ITTMAXP, 0x00ff}, {BRCMS_SROM_PA1LOMAXPWR, 0xffffff00, 0, SROM8_W1_MAXP_LCHC, 0xff00}, {BRCMS_SROM_PA1HIMAXPWR, 0xffffff00, 0, SROM8_W1_MAXP_LCHC, 0x00ff}, {BRCMS_SROM_BXA2G, 0xffffff00, 0, SROM8_BXARSSI2G, 0x1800}, {BRCMS_SROM_RSSISAV2G, 0xffffff00, 0, SROM8_BXARSSI2G, 0x0700}, {BRCMS_SROM_RSSISMC2G, 0xffffff00, 0, SROM8_BXARSSI2G, 0x00f0}, {BRCMS_SROM_RSSISMF2G, 0xffffff00, 0, SROM8_BXARSSI2G, 0x000f}, {BRCMS_SROM_BXA5G, 0xffffff00, 0, SROM8_BXARSSI5G, 0x1800}, {BRCMS_SROM_RSSISAV5G, 0xffffff00, 0, SROM8_BXARSSI5G, 0x0700}, {BRCMS_SROM_RSSISMC5G, 0xffffff00, 0, SROM8_BXARSSI5G, 0x00f0}, {BRCMS_SROM_RSSISMF5G, 0xffffff00, 0, SROM8_BXARSSI5G, 0x000f}, {BRCMS_SROM_TRI2G, 0xffffff00, 0, SROM8_TRI52G, 0x00ff}, {BRCMS_SROM_TRI5G, 0xffffff00, 0, SROM8_TRI52G, 0xff00}, {BRCMS_SROM_TRI5GL, 0xffffff00, 0, SROM8_TRI5GHL, 0x00ff}, {BRCMS_SROM_TRI5GH, 0xffffff00, 0, SROM8_TRI5GHL, 0xff00}, {BRCMS_SROM_RXPO2G, 0xffffff00, SRFL_PRSIGN, SROM8_RXPO52G, 0x00ff}, {BRCMS_SROM_RXPO5G, 0xffffff00, SRFL_PRSIGN, SROM8_RXPO52G, 0xff00}, {BRCMS_SROM_TXCHAIN, 0xffffff00, SRFL_NOFFS, SROM8_TXRXC, SROM4_TXCHAIN_MASK}, {BRCMS_SROM_RXCHAIN, 0xffffff00, SRFL_NOFFS, SROM8_TXRXC, SROM4_RXCHAIN_MASK}, {BRCMS_SROM_ANTSWITCH, 0xffffff00, SRFL_NOFFS, SROM8_TXRXC, SROM4_SWITCH_MASK}, {BRCMS_SROM_TSSIPOS2G, 0xffffff00, 0, SROM8_FEM2G, SROM8_FEM_TSSIPOS_MASK}, {BRCMS_SROM_EXTPAGAIN2G, 0xffffff00, 0, SROM8_FEM2G, SROM8_FEM_EXTPA_GAIN_MASK}, {BRCMS_SROM_PDETRANGE2G, 0xffffff00, 0, SROM8_FEM2G, SROM8_FEM_PDET_RANGE_MASK}, {BRCMS_SROM_TRISO2G, 0xffffff00, 0, SROM8_FEM2G, SROM8_FEM_TR_ISO_MASK}, {BRCMS_SROM_ANTSWCTL2G, 0xffffff00, 0, SROM8_FEM2G, SROM8_FEM_ANTSWLUT_MASK}, {BRCMS_SROM_TSSIPOS5G, 0xffffff00, 0, SROM8_FEM5G, SROM8_FEM_TSSIPOS_MASK}, {BRCMS_SROM_EXTPAGAIN5G, 0xffffff00, 0, SROM8_FEM5G, SROM8_FEM_EXTPA_GAIN_MASK}, {BRCMS_SROM_PDETRANGE5G, 0xffffff00, 0, SROM8_FEM5G, SROM8_FEM_PDET_RANGE_MASK}, {BRCMS_SROM_TRISO5G, 0xffffff00, 0, SROM8_FEM5G, SROM8_FEM_TR_ISO_MASK}, {BRCMS_SROM_ANTSWCTL5G, 0xffffff00, 0, SROM8_FEM5G, SROM8_FEM_ANTSWLUT_MASK}, {BRCMS_SROM_TEMPTHRESH, 0xffffff00, 0, SROM8_THERMAL, 0xff00}, {BRCMS_SROM_TEMPOFFSET, 0xffffff00, 0, SROM8_THERMAL, 0x00ff}, {BRCMS_SROM_CCODE, 0xffffff00, SRFL_CCODE, SROM8_CCODE, 0xffff}, {BRCMS_SROM_MACADDR, 0xffffff00, SRFL_ETHADDR, SROM8_MACHI, 0xffff}, {BRCMS_SROM_LEDDC, 0xffffff00, SRFL_NOFFS | SRFL_LEDDC, SROM8_LEDDC, 0xffff}, {BRCMS_SROM_RAWTEMPSENSE, 0xffffff00, SRFL_PRHEX, SROM8_MPWR_RAWTS, 0x01ff}, {BRCMS_SROM_MEASPOWER, 0xffffff00, SRFL_PRHEX, SROM8_MPWR_RAWTS, 0xfe00}, {BRCMS_SROM_TEMPSENSE_SLOPE, 0xffffff00, SRFL_PRHEX, SROM8_TS_SLP_OPT_CORRX, 0x00ff}, {BRCMS_SROM_TEMPCORRX, 0xffffff00, SRFL_PRHEX, SROM8_TS_SLP_OPT_CORRX, 0xfc00}, {BRCMS_SROM_TEMPSENSE_OPTION, 0xffffff00, SRFL_PRHEX, SROM8_TS_SLP_OPT_CORRX, 0x0300}, {BRCMS_SROM_FREQOFFSET_CORR, 0xffffff00, SRFL_PRHEX, SROM8_FOC_HWIQ_IQSWP, 0x000f}, {BRCMS_SROM_IQCAL_SWP_DIS, 0xffffff00, SRFL_PRHEX, SROM8_FOC_HWIQ_IQSWP, 0x0010}, {BRCMS_SROM_HW_IQCAL_EN, 0xffffff00, SRFL_PRHEX, SROM8_FOC_HWIQ_IQSWP, 0x0020}, {BRCMS_SROM_PHYCAL_TEMPDELTA, 0xffffff00, 0, SROM8_PHYCAL_TEMPDELTA, 0x00ff}, {BRCMS_SROM_CCK2GPO, 0x00000100, 0, SROM8_2G_CCKPO, 0xffff}, {BRCMS_SROM_OFDM2GPO, 0x00000100, SRFL_MORE, SROM8_2G_OFDMPO, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM8_2G_OFDMPO + 1, 0xffff}, {BRCMS_SROM_OFDM5GPO, 0x00000100, SRFL_MORE, SROM8_5G_OFDMPO, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM8_5G_OFDMPO + 1, 0xffff}, {BRCMS_SROM_OFDM5GLPO, 0x00000100, SRFL_MORE, SROM8_5GL_OFDMPO, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM8_5GL_OFDMPO + 1, 0xffff}, {BRCMS_SROM_OFDM5GHPO, 0x00000100, SRFL_MORE, SROM8_5GH_OFDMPO, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM8_5GH_OFDMPO + 1, 0xffff}, {BRCMS_SROM_MCS2GPO0, 0x00000100, 0, SROM8_2G_MCSPO, 0xffff}, {BRCMS_SROM_MCS2GPO1, 0x00000100, 0, SROM8_2G_MCSPO + 1, 0xffff}, {BRCMS_SROM_MCS2GPO2, 0x00000100, 0, SROM8_2G_MCSPO + 2, 0xffff}, {BRCMS_SROM_MCS2GPO3, 0x00000100, 0, SROM8_2G_MCSPO + 3, 0xffff}, {BRCMS_SROM_MCS2GPO4, 0x00000100, 0, SROM8_2G_MCSPO + 4, 0xffff}, {BRCMS_SROM_MCS2GPO5, 0x00000100, 0, SROM8_2G_MCSPO + 5, 0xffff}, {BRCMS_SROM_MCS2GPO6, 0x00000100, 0, SROM8_2G_MCSPO + 6, 0xffff}, {BRCMS_SROM_MCS2GPO7, 0x00000100, 0, SROM8_2G_MCSPO + 7, 0xffff}, {BRCMS_SROM_MCS5GPO0, 0x00000100, 0, SROM8_5G_MCSPO, 0xffff}, {BRCMS_SROM_MCS5GPO1, 0x00000100, 0, SROM8_5G_MCSPO + 1, 0xffff}, {BRCMS_SROM_MCS5GPO2, 0x00000100, 0, SROM8_5G_MCSPO + 2, 0xffff}, {BRCMS_SROM_MCS5GPO3, 0x00000100, 0, SROM8_5G_MCSPO + 3, 0xffff}, {BRCMS_SROM_MCS5GPO4, 0x00000100, 0, SROM8_5G_MCSPO + 4, 0xffff}, {BRCMS_SROM_MCS5GPO5, 0x00000100, 0, SROM8_5G_MCSPO + 5, 0xffff}, {BRCMS_SROM_MCS5GPO6, 0x00000100, 0, SROM8_5G_MCSPO + 6, 0xffff}, {BRCMS_SROM_MCS5GPO7, 0x00000100, 0, SROM8_5G_MCSPO + 7, 0xffff}, {BRCMS_SROM_MCS5GLPO0, 0x00000100, 0, SROM8_5GL_MCSPO, 0xffff}, {BRCMS_SROM_MCS5GLPO1, 0x00000100, 0, SROM8_5GL_MCSPO + 1, 0xffff}, {BRCMS_SROM_MCS5GLPO2, 0x00000100, 0, SROM8_5GL_MCSPO + 2, 0xffff}, {BRCMS_SROM_MCS5GLPO3, 0x00000100, 0, SROM8_5GL_MCSPO + 3, 0xffff}, {BRCMS_SROM_MCS5GLPO4, 0x00000100, 0, SROM8_5GL_MCSPO + 4, 0xffff}, {BRCMS_SROM_MCS5GLPO5, 0x00000100, 0, SROM8_5GL_MCSPO + 5, 0xffff}, {BRCMS_SROM_MCS5GLPO6, 0x00000100, 0, SROM8_5GL_MCSPO + 6, 0xffff}, {BRCMS_SROM_MCS5GLPO7, 0x00000100, 0, SROM8_5GL_MCSPO + 7, 0xffff}, {BRCMS_SROM_MCS5GHPO0, 0x00000100, 0, SROM8_5GH_MCSPO, 0xffff}, {BRCMS_SROM_MCS5GHPO1, 0x00000100, 0, SROM8_5GH_MCSPO + 1, 0xffff}, {BRCMS_SROM_MCS5GHPO2, 0x00000100, 0, SROM8_5GH_MCSPO + 2, 0xffff}, {BRCMS_SROM_MCS5GHPO3, 0x00000100, 0, SROM8_5GH_MCSPO + 3, 0xffff}, {BRCMS_SROM_MCS5GHPO4, 0x00000100, 0, SROM8_5GH_MCSPO + 4, 0xffff}, {BRCMS_SROM_MCS5GHPO5, 0x00000100, 0, SROM8_5GH_MCSPO + 5, 0xffff}, {BRCMS_SROM_MCS5GHPO6, 0x00000100, 0, SROM8_5GH_MCSPO + 6, 0xffff}, {BRCMS_SROM_MCS5GHPO7, 0x00000100, 0, SROM8_5GH_MCSPO + 7, 0xffff}, {BRCMS_SROM_CDDPO, 0x00000100, 0, SROM8_CDDPO, 0xffff}, {BRCMS_SROM_STBCPO, 0x00000100, 0, SROM8_STBCPO, 0xffff}, {BRCMS_SROM_BW40PO, 0x00000100, 0, SROM8_BW40PO, 0xffff}, {BRCMS_SROM_BWDUPPO, 0x00000100, 0, SROM8_BWDUPPO, 0xffff}, /* power per rate from sromrev 9 */ {BRCMS_SROM_CCKBW202GPO, 0xfffffe00, 0, SROM9_2GPO_CCKBW20, 0xffff}, {BRCMS_SROM_CCKBW20UL2GPO, 0xfffffe00, 0, SROM9_2GPO_CCKBW20UL, 0xffff}, {BRCMS_SROM_LEGOFDMBW202GPO, 0xfffffe00, SRFL_MORE, SROM9_2GPO_LOFDMBW20, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_2GPO_LOFDMBW20 + 1, 0xffff}, {BRCMS_SROM_LEGOFDMBW20UL2GPO, 0xfffffe00, SRFL_MORE, SROM9_2GPO_LOFDMBW20UL, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_2GPO_LOFDMBW20UL + 1, 0xffff}, {BRCMS_SROM_LEGOFDMBW205GLPO, 0xfffffe00, SRFL_MORE, SROM9_5GLPO_LOFDMBW20, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_5GLPO_LOFDMBW20 + 1, 0xffff}, {BRCMS_SROM_LEGOFDMBW20UL5GLPO, 0xfffffe00, SRFL_MORE, SROM9_5GLPO_LOFDMBW20UL, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_5GLPO_LOFDMBW20UL + 1, 0xffff}, {BRCMS_SROM_LEGOFDMBW205GMPO, 0xfffffe00, SRFL_MORE, SROM9_5GMPO_LOFDMBW20, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_5GMPO_LOFDMBW20 + 1, 0xffff}, {BRCMS_SROM_LEGOFDMBW20UL5GMPO, 0xfffffe00, SRFL_MORE, SROM9_5GMPO_LOFDMBW20UL, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_5GMPO_LOFDMBW20UL + 1, 0xffff}, {BRCMS_SROM_LEGOFDMBW205GHPO, 0xfffffe00, SRFL_MORE, SROM9_5GHPO_LOFDMBW20, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_5GHPO_LOFDMBW20 + 1, 0xffff}, {BRCMS_SROM_LEGOFDMBW20UL5GHPO, 0xfffffe00, SRFL_MORE, SROM9_5GHPO_LOFDMBW20UL, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_5GHPO_LOFDMBW20UL + 1, 0xffff}, {BRCMS_SROM_MCSBW202GPO, 0xfffffe00, SRFL_MORE, SROM9_2GPO_MCSBW20, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_2GPO_MCSBW20 + 1, 0xffff}, {BRCMS_SROM_MCSBW20UL2GPO, 0xfffffe00, SRFL_MORE, SROM9_2GPO_MCSBW20UL, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_2GPO_MCSBW20UL + 1, 0xffff}, {BRCMS_SROM_MCSBW402GPO, 0xfffffe00, SRFL_MORE, SROM9_2GPO_MCSBW40, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_2GPO_MCSBW40 + 1, 0xffff}, {BRCMS_SROM_MCSBW205GLPO, 0xfffffe00, SRFL_MORE, SROM9_5GLPO_MCSBW20, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_5GLPO_MCSBW20 + 1, 0xffff}, {BRCMS_SROM_MCSBW20UL5GLPO, 0xfffffe00, SRFL_MORE, SROM9_5GLPO_MCSBW20UL, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_5GLPO_MCSBW20UL + 1, 0xffff}, {BRCMS_SROM_MCSBW405GLPO, 0xfffffe00, SRFL_MORE, SROM9_5GLPO_MCSBW40, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_5GLPO_MCSBW40 + 1, 0xffff}, {BRCMS_SROM_MCSBW205GMPO, 0xfffffe00, SRFL_MORE, SROM9_5GMPO_MCSBW20, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_5GMPO_MCSBW20 + 1, 0xffff}, {BRCMS_SROM_MCSBW20UL5GMPO, 0xfffffe00, SRFL_MORE, SROM9_5GMPO_MCSBW20UL, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_5GMPO_MCSBW20UL + 1, 0xffff}, {BRCMS_SROM_MCSBW405GMPO, 0xfffffe00, SRFL_MORE, SROM9_5GMPO_MCSBW40, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_5GMPO_MCSBW40 + 1, 0xffff}, {BRCMS_SROM_MCSBW205GHPO, 0xfffffe00, SRFL_MORE, SROM9_5GHPO_MCSBW20, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_5GHPO_MCSBW20 + 1, 0xffff}, {BRCMS_SROM_MCSBW20UL5GHPO, 0xfffffe00, SRFL_MORE, SROM9_5GHPO_MCSBW20UL, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_5GHPO_MCSBW20UL + 1, 0xffff}, {BRCMS_SROM_MCSBW405GHPO, 0xfffffe00, SRFL_MORE, SROM9_5GHPO_MCSBW40, 0xffff}, {BRCMS_SROM_CONT, 0, 0, SROM9_5GHPO_MCSBW40 + 1, 0xffff}, {BRCMS_SROM_MCS32PO, 0xfffffe00, 0, SROM9_PO_MCS32, 0xffff}, {BRCMS_SROM_LEGOFDM40DUPPO, 0xfffffe00, 0, SROM9_PO_LOFDM40DUP, 0xffff}, {BRCMS_SROM_NULL, 0, 0, 0, 0} }; static const struct brcms_sromvar perpath_pci_sromvars[] = { {BRCMS_SROM_MAXP2GA0, 0xffffff00, 0, SROM8_2G_ITT_MAXP, 0x00ff}, {BRCMS_SROM_ITT2GA0, 0xffffff00, 0, SROM8_2G_ITT_MAXP, 0xff00}, {BRCMS_SROM_ITT5GA0, 0xffffff00, 0, SROM8_5G_ITT_MAXP, 0xff00}, {BRCMS_SROM_PA2GW0A0, 0xffffff00, SRFL_PRHEX, SROM8_2G_PA, 0xffff}, {BRCMS_SROM_PA2GW1A0, 0xffffff00, SRFL_PRHEX, SROM8_2G_PA + 1, 0xffff}, {BRCMS_SROM_PA2GW2A0, 0xffffff00, SRFL_PRHEX, SROM8_2G_PA + 2, 0xffff}, {BRCMS_SROM_MAXP5GA0, 0xffffff00, 0, SROM8_5G_ITT_MAXP, 0x00ff}, {BRCMS_SROM_MAXP5GHA0, 0xffffff00, 0, SROM8_5GLH_MAXP, 0x00ff}, {BRCMS_SROM_MAXP5GLA0, 0xffffff00, 0, SROM8_5GLH_MAXP, 0xff00}, {BRCMS_SROM_PA5GW0A0, 0xffffff00, SRFL_PRHEX, SROM8_5G_PA, 0xffff}, {BRCMS_SROM_PA5GW1A0, 0xffffff00, SRFL_PRHEX, SROM8_5G_PA + 1, 0xffff}, {BRCMS_SROM_PA5GW2A0, 0xffffff00, SRFL_PRHEX, SROM8_5G_PA + 2, 0xffff}, {BRCMS_SROM_PA5GLW0A0, 0xffffff00, SRFL_PRHEX, SROM8_5GL_PA, 0xffff}, {BRCMS_SROM_PA5GLW1A0, 0xffffff00, SRFL_PRHEX, SROM8_5GL_PA + 1, 0xffff}, {BRCMS_SROM_PA5GLW2A0, 0xffffff00, SRFL_PRHEX, SROM8_5GL_PA + 2, 0xffff}, {BRCMS_SROM_PA5GHW0A0, 0xffffff00, SRFL_PRHEX, SROM8_5GH_PA, 0xffff}, {BRCMS_SROM_PA5GHW1A0, 0xffffff00, SRFL_PRHEX, SROM8_5GH_PA + 1, 0xffff}, {BRCMS_SROM_PA5GHW2A0, 0xffffff00, SRFL_PRHEX, SROM8_5GH_PA + 2, 0xffff}, {BRCMS_SROM_NULL, 0, 0, 0, 0} }; /* crc table has the same contents for every device instance, so it can be * shared between devices. */ static u8 brcms_srom_crc8_table[CRC8_TABLE_SIZE]; static uint mask_shift(u16 mask) { uint i; for (i = 0; i < (sizeof(mask) << 3); i++) { if (mask & (1 << i)) return i; } return 0; } static uint mask_width(u16 mask) { int i; for (i = (sizeof(mask) << 3) - 1; i >= 0; i--) { if (mask & (1 << i)) return (uint) (i - mask_shift(mask) + 1); } return 0; } static inline void le16_to_cpu_buf(u16 *buf, uint nwords) { while (nwords--) *(buf + nwords) = le16_to_cpu(*(__le16 *)(buf + nwords)); } static inline void cpu_to_le16_buf(u16 *buf, uint nwords) { while (nwords--) *(__le16 *)(buf + nwords) = cpu_to_le16(*(buf + nwords)); } /* * convert binary srom data into linked list of srom variable items. */ static int _initvars_srom_pci(u8 sromrev, u16 *srom, struct list_head *var_list) { struct brcms_srom_list_head *entry; enum brcms_srom_id id; u16 w; u32 val = 0; const struct brcms_sromvar *srv; uint width; uint flags; u32 sr = (1 << sromrev); uint p; uint pb = SROM8_PATH0; const uint psz = SROM8_PATH1 - SROM8_PATH0; /* first store the srom revision */ entry = kzalloc(sizeof(struct brcms_srom_list_head), GFP_KERNEL); if (!entry) return -ENOMEM; entry->varid = BRCMS_SROM_REV; entry->var_type = BRCMS_SROM_UNUMBER; entry->uval = sromrev; list_add(&entry->var_list, var_list); for (srv = pci_sromvars; srv->varid != BRCMS_SROM_NULL; srv++) { enum brcms_srom_var_type type; u8 ea[ETH_ALEN]; u8 extra_space = 0; if ((srv->revmask & sr) == 0) continue; flags = srv->flags; id = srv->varid; /* This entry is for mfgc only. Don't generate param for it, */ if (flags & SRFL_NOVAR) continue; if (flags & SRFL_ETHADDR) { /* * stored in string format XX:XX:XX:XX:XX:XX (17 chars) */ ea[0] = (srom[srv->off] >> 8) & 0xff; ea[1] = srom[srv->off] & 0xff; ea[2] = (srom[srv->off + 1] >> 8) & 0xff; ea[3] = srom[srv->off + 1] & 0xff; ea[4] = (srom[srv->off + 2] >> 8) & 0xff; ea[5] = srom[srv->off + 2] & 0xff; /* 17 characters + string terminator - union size */ extra_space = 18 - sizeof(s32); type = BRCMS_SROM_STRING; } else { w = srom[srv->off]; val = (w & srv->mask) >> mask_shift(srv->mask); width = mask_width(srv->mask); while (srv->flags & SRFL_MORE) { srv++; if (srv->off == 0) continue; w = srom[srv->off]; val += ((w & srv->mask) >> mask_shift(srv-> mask)) << width; width += mask_width(srv->mask); } if ((flags & SRFL_NOFFS) && ((int)val == (1 << width) - 1)) continue; if (flags & SRFL_CCODE) { type = BRCMS_SROM_STRING; } else if (flags & SRFL_LEDDC) { /* LED Powersave duty cycle has to be scaled: *(oncount >> 24) (offcount >> 8) */ u32 w32 = /* oncount */ (((val >> 8) & 0xff) << 24) | /* offcount */ (((val & 0xff)) << 8); type = BRCMS_SROM_UNUMBER; val = w32; } else if ((flags & SRFL_PRSIGN) && (val & (1 << (width - 1)))) { type = BRCMS_SROM_SNUMBER; val |= ~0 << width; } else type = BRCMS_SROM_UNUMBER; } entry = kzalloc(sizeof(struct brcms_srom_list_head) + extra_space, GFP_KERNEL); if (!entry) return -ENOMEM; entry->varid = id; entry->var_type = type; if (flags & SRFL_ETHADDR) { snprintf(entry->buf, 18, "%pM", ea); } else if (flags & SRFL_CCODE) { if (val == 0) entry->buf[0] = '\0'; else snprintf(entry->buf, 3, "%c%c", (val >> 8), (val & 0xff)); } else { entry->uval = val; } list_add(&entry->var_list, var_list); } for (p = 0; p < MAX_PATH_SROM; p++) { for (srv = perpath_pci_sromvars; srv->varid != BRCMS_SROM_NULL; srv++) { if ((srv->revmask & sr) == 0) continue; if (srv->flags & SRFL_NOVAR) continue; w = srom[pb + srv->off]; val = (w & srv->mask) >> mask_shift(srv->mask); width = mask_width(srv->mask); /* Cheating: no per-path var is more than * 1 word */ if ((srv->flags & SRFL_NOFFS) && ((int)val == (1 << width) - 1)) continue; entry = kzalloc(sizeof(struct brcms_srom_list_head), GFP_KERNEL); if (!entry) return -ENOMEM; entry->varid = srv->varid+p; entry->var_type = BRCMS_SROM_UNUMBER; entry->uval = val; list_add(&entry->var_list, var_list); } pb += psz; } return 0; } /* * The crc check is done on a little-endian array, we need * to switch the bytes around before checking crc (and * then switch it back). */ static int do_crc_check(u16 *buf, unsigned nwords) { u8 crc; cpu_to_le16_buf(buf, nwords); crc = crc8(brcms_srom_crc8_table, (void *)buf, nwords << 1, CRC8_INIT_VALUE); le16_to_cpu_buf(buf, nwords); return crc == CRC8_GOOD_VALUE(brcms_srom_crc8_table); } /* * Read in and validate sprom. * Return 0 on success, nonzero on error. */ static int sprom_read_pci(struct si_pub *sih, u16 *buf, uint nwords, bool check_crc) { int err = 0; uint i; struct bcma_device *core; uint sprom_offset; /* determine core to read */ if (ai_get_ccrev(sih) < 32) { core = ai_findcore(sih, BCMA_CORE_80211, 0); sprom_offset = PCI_BAR0_SPROM_OFFSET; } else { core = ai_findcore(sih, BCMA_CORE_CHIPCOMMON, 0); sprom_offset = CHIPCREGOFFS(sromotp); } /* read the sprom */ for (i = 0; i < nwords; i++) buf[i] = bcma_read16(core, sprom_offset+i*2); if (buf[0] == 0xffff) /* * The hardware thinks that an srom that starts with * 0xffff is blank, regardless of the rest of the * content, so declare it bad. */ return -ENODATA; if (check_crc && !do_crc_check(buf, nwords)) err = -EIO; return err; } static int otp_read_pci(struct si_pub *sih, u16 *buf, uint nwords) { u8 *otp; uint sz = OTP_SZ_MAX / 2; /* size in words */ int err = 0; otp = kzalloc(OTP_SZ_MAX, GFP_ATOMIC); if (otp == NULL) return -ENOMEM; err = otp_read_region(sih, OTP_HW_RGN, (u16 *) otp, &sz); sz = min_t(uint, sz, nwords); memcpy(buf, otp, sz * 2); kfree(otp); /* Check CRC */ if (buf[0] == 0xffff) /* The hardware thinks that an srom that starts with 0xffff * is blank, regardless of the rest of the content, so declare * it bad. */ return -ENODATA; /* fixup the endianness so crc8 will pass */ cpu_to_le16_buf(buf, sz); if (crc8(brcms_srom_crc8_table, (u8 *) buf, sz * 2, CRC8_INIT_VALUE) != CRC8_GOOD_VALUE(brcms_srom_crc8_table)) err = -EIO; else /* now correct the endianness of the byte array */ le16_to_cpu_buf(buf, sz); return err; } /* * Initialize nonvolatile variable table from sprom. * Return 0 on success, nonzero on error. */ int srom_var_init(struct si_pub *sih) { u16 *srom; u8 sromrev = 0; u32 sr; int err = 0; /* * Apply CRC over SROM content regardless SROM is present or not. */ srom = kmalloc(SROM_MAX, GFP_ATOMIC); if (!srom) return -ENOMEM; crc8_populate_lsb(brcms_srom_crc8_table, SROM_CRC8_POLY); if (ai_is_sprom_available(sih)) { err = sprom_read_pci(sih, srom, SROM4_WORDS, true); if (err == 0) /* srom read and passed crc */ /* top word of sprom contains version and crc8 */ sromrev = srom[SROM4_CRCREV] & 0xff; } else { /* Use OTP if SPROM not available */ err = otp_read_pci(sih, srom, SROM4_WORDS); if (err == 0) /* OTP only contain SROM rev8/rev9 for now */ sromrev = srom[SROM4_CRCREV] & 0xff; } if (!err) { struct si_info *sii = (struct si_info *)sih; /* Bitmask for the sromrev */ sr = 1 << sromrev; /* * srom version check: Current valid versions: 8, 9 */ if ((sr & 0x300) == 0) { err = -EINVAL; goto errout; } INIT_LIST_HEAD(&sii->var_list); /* parse SROM into name=value pairs. */ err = _initvars_srom_pci(sromrev, srom, &sii->var_list); if (err) srom_free_vars(sih); } errout: kfree(srom); return err; } void srom_free_vars(struct si_pub *sih) { struct si_info *sii; struct brcms_srom_list_head *entry, *next; sii = (struct si_info *)sih; list_for_each_entry_safe(entry, next, &sii->var_list, var_list) { list_del(&entry->var_list); kfree(entry); } } /* * Search the name=value vars for a specific one and return its value. * Returns NULL if not found. */ char *getvar(struct si_pub *sih, enum brcms_srom_id id) { struct si_info *sii; struct brcms_srom_list_head *entry; sii = (struct si_info *)sih; list_for_each_entry(entry, &sii->var_list, var_list) if (entry->varid == id) return &entry->buf[0]; /* nothing found */ return NULL; } /* * Search the vars for a specific one and return its value as * an integer. Returns 0 if not found.- */ int getintvar(struct si_pub *sih, enum brcms_srom_id id) { struct si_info *sii; struct brcms_srom_list_head *entry; unsigned long res; sii = (struct si_info *)sih; list_for_each_entry(entry, &sii->var_list, var_list) if (entry->varid == id) { if (entry->var_type == BRCMS_SROM_SNUMBER || entry->var_type == BRCMS_SROM_UNUMBER) return (int)entry->sval; else if (!kstrtoul(&entry->buf[0], 0, &res)) return (int)res; } return 0; }
gpl-2.0
cahdudul/akh8960_cm
arch/arm/mach-s3c64xx/mach-anw6410.c
4822
6037
/* linux/arch/arm/mach-s3c64xx/mach-anw6410.c * * Copyright 2008 Openmoko, Inc. * Copyright 2008 Simtec Electronics * Ben Dooks <ben@simtec.co.uk> * http://armlinux.simtec.co.uk/ * Copyright 2009 Kwangwoo Lee * Kwangwoo Lee <kwangwoo.lee@gmail.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/types.h> #include <linux/interrupt.h> #include <linux/list.h> #include <linux/timer.h> #include <linux/init.h> #include <linux/serial_core.h> #include <linux/platform_device.h> #include <linux/io.h> #include <linux/i2c.h> #include <linux/fb.h> #include <linux/gpio.h> #include <linux/delay.h> #include <linux/dm9000.h> #include <video/platform_lcd.h> #include <asm/hardware/vic.h> #include <asm/mach/arch.h> #include <asm/mach/map.h> #include <asm/mach/irq.h> #include <mach/hardware.h> #include <mach/map.h> #include <asm/irq.h> #include <asm/mach-types.h> #include <plat/regs-serial.h> #include <plat/iic.h> #include <plat/fb.h> #include <plat/regs-fb-v4.h> #include <plat/clock.h> #include <plat/devs.h> #include <plat/cpu.h> #include <mach/regs-gpio.h> #include <mach/regs-modem.h> #include "common.h" /* DM9000 */ #define ANW6410_PA_DM9000 (0x18000000) /* A hardware buffer to control external devices is mapped at 0x30000000. * It can not be read. So current status must be kept in anw6410_extdev_status. */ #define ANW6410_VA_EXTDEV S3C_ADDR(0x02000000) #define ANW6410_PA_EXTDEV (0x30000000) #define ANW6410_EN_DM9000 (1<<11) #define ANW6410_EN_LCD (1<<14) static __u32 anw6410_extdev_status; static struct s3c2410_uartcfg anw6410_uartcfgs[] __initdata = { [0] = { .hwport = 0, .flags = 0, .ucon = 0x3c5, .ulcon = 0x03, .ufcon = 0x51, }, [1] = { .hwport = 1, .flags = 0, .ucon = 0x3c5, .ulcon = 0x03, .ufcon = 0x51, }, }; /* framebuffer and LCD setup. */ static void __init anw6410_lcd_mode_set(void) { u32 tmp; /* set the LCD type */ tmp = __raw_readl(S3C64XX_SPCON); tmp &= ~S3C64XX_SPCON_LCD_SEL_MASK; tmp |= S3C64XX_SPCON_LCD_SEL_RGB; __raw_writel(tmp, S3C64XX_SPCON); /* remove the LCD bypass */ tmp = __raw_readl(S3C64XX_MODEM_MIFPCON); tmp &= ~MIFPCON_LCD_BYPASS; __raw_writel(tmp, S3C64XX_MODEM_MIFPCON); } /* GPF1 = LCD panel power * GPF4 = LCD backlight control */ static void anw6410_lcd_power_set(struct plat_lcd_data *pd, unsigned int power) { if (power) { anw6410_extdev_status |= (ANW6410_EN_LCD << 16); __raw_writel(anw6410_extdev_status, ANW6410_VA_EXTDEV); gpio_direction_output(S3C64XX_GPF(1), 1); gpio_direction_output(S3C64XX_GPF(4), 1); } else { anw6410_extdev_status &= ~(ANW6410_EN_LCD << 16); __raw_writel(anw6410_extdev_status, ANW6410_VA_EXTDEV); gpio_direction_output(S3C64XX_GPF(1), 0); gpio_direction_output(S3C64XX_GPF(4), 0); } } static struct plat_lcd_data anw6410_lcd_power_data = { .set_power = anw6410_lcd_power_set, }; static struct platform_device anw6410_lcd_powerdev = { .name = "platform-lcd", .dev.parent = &s3c_device_fb.dev, .dev.platform_data = &anw6410_lcd_power_data, }; static struct s3c_fb_pd_win anw6410_fb_win0 = { /* this is to ensure we use win0 */ .win_mode = { .left_margin = 8, .right_margin = 13, .upper_margin = 7, .lower_margin = 5, .hsync_len = 3, .vsync_len = 1, .xres = 800, .yres = 480, }, .max_bpp = 32, .default_bpp = 16, }; /* 405566 clocks per frame => 60Hz refresh requires 24333960Hz clock */ static struct s3c_fb_platdata anw6410_lcd_pdata __initdata = { .setup_gpio = s3c64xx_fb_gpio_setup_24bpp, .win[0] = &anw6410_fb_win0, .vidcon0 = VIDCON0_VIDOUT_RGB | VIDCON0_PNRMODE_RGB, .vidcon1 = VIDCON1_INV_HSYNC | VIDCON1_INV_VSYNC, }; /* DM9000AEP 10/100 ethernet controller */ static void __init anw6410_dm9000_enable(void) { anw6410_extdev_status |= (ANW6410_EN_DM9000 << 16); __raw_writel(anw6410_extdev_status, ANW6410_VA_EXTDEV); } static struct resource anw6410_dm9000_resource[] = { [0] = { .start = ANW6410_PA_DM9000, .end = ANW6410_PA_DM9000 + 3, .flags = IORESOURCE_MEM, }, [1] = { .start = ANW6410_PA_DM9000 + 4, .end = ANW6410_PA_DM9000 + 4 + 500, .flags = IORESOURCE_MEM, }, [2] = { .start = IRQ_EINT(15), .end = IRQ_EINT(15), .flags = IORESOURCE_IRQ | IRQF_TRIGGER_HIGH, }, }; static struct dm9000_plat_data anw6410_dm9000_pdata = { .flags = (DM9000_PLATF_16BITONLY | DM9000_PLATF_NO_EEPROM), /* dev_addr can be set to provide hwaddr. */ }; static struct platform_device anw6410_device_eth = { .name = "dm9000", .id = -1, .num_resources = ARRAY_SIZE(anw6410_dm9000_resource), .resource = anw6410_dm9000_resource, .dev = { .platform_data = &anw6410_dm9000_pdata, }, }; static struct map_desc anw6410_iodesc[] __initdata = { { .virtual = (unsigned long)ANW6410_VA_EXTDEV, .pfn = __phys_to_pfn(ANW6410_PA_EXTDEV), .length = SZ_64K, .type = MT_DEVICE, }, }; static struct platform_device *anw6410_devices[] __initdata = { &s3c_device_fb, &anw6410_lcd_powerdev, &anw6410_device_eth, }; static void __init anw6410_map_io(void) { s3c64xx_init_io(anw6410_iodesc, ARRAY_SIZE(anw6410_iodesc)); s3c24xx_init_clocks(12000000); s3c24xx_init_uarts(anw6410_uartcfgs, ARRAY_SIZE(anw6410_uartcfgs)); anw6410_lcd_mode_set(); } static void __init anw6410_machine_init(void) { s3c_fb_set_platdata(&anw6410_lcd_pdata); gpio_request(S3C64XX_GPF(1), "panel power"); gpio_request(S3C64XX_GPF(4), "LCD backlight"); anw6410_dm9000_enable(); platform_add_devices(anw6410_devices, ARRAY_SIZE(anw6410_devices)); } MACHINE_START(ANW6410, "A&W6410") /* Maintainer: Kwangwoo Lee <kwangwoo.lee@gmail.com> */ .atag_offset = 0x100, .init_irq = s3c6410_init_irq, .handle_irq = vic_handle_irq, .map_io = anw6410_map_io, .init_machine = anw6410_machine_init, .timer = &s3c24xx_timer, .restart = s3c64xx_restart, MACHINE_END
gpl-2.0
chrisc93/android_kernel_samsung_jf
drivers/net/ethernet/i825xx/3c507.c
5078
28733
/* 3c507.c: An EtherLink16 device driver for Linux. */ /* Written 1993,1994 by Donald Becker. Copyright 1993 United States Government as represented by the Director, National Security Agency. This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. The author may be reached as becker@scyld.com, or C/O Scyld Computing Corporation 410 Severn Ave., Suite 210 Annapolis MD 21403 Thanks go to jennings@Montrouge.SMR.slb.com ( Patrick Jennings) and jrs@world.std.com (Rick Sladkey) for testing and bugfixes. Mark Salazar <leslie@access.digex.net> made the changes for cards with only 16K packet buffers. Things remaining to do: Verify that the tx and rx buffers don't have fencepost errors. Move the theory of operation and memory map documentation. The statistics need to be updated correctly. */ #define DRV_NAME "3c507" #define DRV_VERSION "1.10a" #define DRV_RELDATE "11/17/2001" static const char version[] = DRV_NAME ".c:v" DRV_VERSION " " DRV_RELDATE " Donald Becker (becker@scyld.com)\n"; /* Sources: This driver wouldn't have been written with the availability of the Crynwr driver source code. It provided a known-working implementation that filled in the gaping holes of the Intel documentation. Three cheers for Russ Nelson. Intel Microcommunications Databook, Vol. 1, 1990. It provides just enough info that the casual reader might think that it documents the i82586 :-<. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/fcntl.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/in.h> #include <linux/string.h> #include <linux/spinlock.h> #include <linux/ethtool.h> #include <linux/errno.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/if_ether.h> #include <linux/skbuff.h> #include <linux/init.h> #include <linux/bitops.h> #include <asm/dma.h> #include <asm/io.h> #include <asm/uaccess.h> /* use 0 for production, 1 for verification, 2..7 for debug */ #ifndef NET_DEBUG #define NET_DEBUG 1 #endif static unsigned int net_debug = NET_DEBUG; #define debug net_debug /* Details of the i82586. You'll really need the databook to understand the details of this part, but the outline is that the i82586 has two separate processing units. Both are started from a list of three configuration tables, of which only the last, the System Control Block (SCB), is used after reset-time. The SCB has the following fields: Status word Command word Tx/Command block addr. Rx block addr. The command word accepts the following controls for the Tx and Rx units: */ #define CUC_START 0x0100 #define CUC_RESUME 0x0200 #define CUC_SUSPEND 0x0300 #define RX_START 0x0010 #define RX_RESUME 0x0020 #define RX_SUSPEND 0x0030 /* The Rx unit uses a list of frame descriptors and a list of data buffer descriptors. We use full-sized (1518 byte) data buffers, so there is a one-to-one pairing of frame descriptors to buffer descriptors. The Tx ("command") unit executes a list of commands that look like: Status word Written by the 82586 when the command is done. Command word Command in lower 3 bits, post-command action in upper 3 Link word The address of the next command. Parameters (as needed). Some definitions related to the Command Word are: */ #define CMD_EOL 0x8000 /* The last command of the list, stop. */ #define CMD_SUSP 0x4000 /* Suspend after doing cmd. */ #define CMD_INTR 0x2000 /* Interrupt after doing cmd. */ enum commands { CmdNOp = 0, CmdSASetup = 1, CmdConfigure = 2, CmdMulticastList = 3, CmdTx = 4, CmdTDR = 5, CmdDump = 6, CmdDiagnose = 7}; /* Information that need to be kept for each board. */ struct net_local { int last_restart; ushort rx_head; ushort rx_tail; ushort tx_head; ushort tx_cmd_link; ushort tx_reap; ushort tx_pkts_in_ring; spinlock_t lock; void __iomem *base; }; /* Details of the EtherLink16 Implementation The 3c507 is a generic shared-memory i82586 implementation. The host can map 16K, 32K, 48K, or 64K of the 64K memory into 0x0[CD][08]0000, or all 64K into 0xF[02468]0000. */ /* Offsets from the base I/O address. */ #define SA_DATA 0 /* Station address data, or 3Com signature. */ #define MISC_CTRL 6 /* Switch the SA_DATA banks, and bus config bits. */ #define RESET_IRQ 10 /* Reset the latched IRQ line. */ #define SIGNAL_CA 11 /* Frob the 82586 Channel Attention line. */ #define ROM_CONFIG 13 #define MEM_CONFIG 14 #define IRQ_CONFIG 15 #define EL16_IO_EXTENT 16 /* The ID port is used at boot-time to locate the ethercard. */ #define ID_PORT 0x100 /* Offsets to registers in the mailbox (SCB). */ #define iSCB_STATUS 0x8 #define iSCB_CMD 0xA #define iSCB_CBL 0xC /* Command BLock offset. */ #define iSCB_RFA 0xE /* Rx Frame Area offset. */ /* Since the 3c507 maps the shared memory window so that the last byte is at 82586 address FFFF, the first byte is at 82586 address 0, 16K, 32K, or 48K corresponding to window sizes of 64K, 48K, 32K and 16K respectively. We can account for this be setting the 'SBC Base' entry in the ISCP table below for all the 16 bit offset addresses, and also adding the 'SCB Base' value to all 24 bit physical addresses (in the SCP table and the TX and RX Buffer Descriptors). -Mark */ #define SCB_BASE ((unsigned)64*1024 - (dev->mem_end - dev->mem_start)) /* What follows in 'init_words[]' is the "program" that is downloaded to the 82586 memory. It's mostly tables and command blocks, and starts at the reset address 0xfffff6. This is designed to be similar to the EtherExpress, thus the unusual location of the SCB at 0x0008. Even with the additional "don't care" values, doing it this way takes less program space than initializing the individual tables, and I feel it's much cleaner. The databook is particularly useless for the first two structures, I had to use the Crynwr driver as an example. The memory setup is as follows: */ #define CONFIG_CMD 0x0018 #define SET_SA_CMD 0x0024 #define SA_OFFSET 0x002A #define IDLELOOP 0x30 #define TDR_CMD 0x38 #define TDR_TIME 0x3C #define DUMP_CMD 0x40 #define DIAG_CMD 0x48 #define SET_MC_CMD 0x4E #define DUMP_DATA 0x56 /* A 170 byte buffer for dump and Set-MC into. */ #define TX_BUF_START 0x0100 #define NUM_TX_BUFS 5 #define TX_BUF_SIZE (1518+14+20+16) /* packet+header+TBD */ #define RX_BUF_START 0x2000 #define RX_BUF_SIZE (1518+14+18) /* packet+header+RBD */ #define RX_BUF_END (dev->mem_end - dev->mem_start) #define TX_TIMEOUT (HZ/20) /* That's it: only 86 bytes to set up the beast, including every extra command available. The 170 byte buffer at DUMP_DATA is shared between the Dump command (called only by the diagnostic program) and the SetMulticastList command. To complete the memory setup you only have to write the station address at SA_OFFSET and create the Tx & Rx buffer lists. The Tx command chain and buffer list is setup as follows: A Tx command table, with the data buffer pointing to... A Tx data buffer descriptor. The packet is in a single buffer, rather than chaining together several smaller buffers. A NoOp command, which initially points to itself, And the packet data. A transmit is done by filling in the Tx command table and data buffer, re-writing the NoOp command, and finally changing the offset of the last command to point to the current Tx command. When the Tx command is finished, it jumps to the NoOp, when it loops until the next Tx command changes the "link offset" in the NoOp. This way the 82586 never has to go through the slow restart sequence. The Rx buffer list is set up in the obvious ring structure. We have enough memory (and low enough interrupt latency) that we can avoid the complicated Rx buffer linked lists by alway associating a full-size Rx data buffer with each Rx data frame. I current use four transmit buffers starting at TX_BUF_START (0x0100), and use the rest of memory, from RX_BUF_START to RX_BUF_END, for Rx buffers. */ static unsigned short init_words[] = { /* System Configuration Pointer (SCP). */ 0x0000, /* Set bus size to 16 bits. */ 0,0, /* pad words. */ 0x0000,0x0000, /* ISCP phys addr, set in init_82586_mem(). */ /* Intermediate System Configuration Pointer (ISCP). */ 0x0001, /* Status word that's cleared when init is done. */ 0x0008,0,0, /* SCB offset, (skip, skip) */ /* System Control Block (SCB). */ 0,0xf000|RX_START|CUC_START, /* SCB status and cmd. */ CONFIG_CMD, /* Command list pointer, points to Configure. */ RX_BUF_START, /* Rx block list. */ 0,0,0,0, /* Error count: CRC, align, buffer, overrun. */ /* 0x0018: Configure command. Change to put MAC data with packet. */ 0, CmdConfigure, /* Status, command. */ SET_SA_CMD, /* Next command is Set Station Addr. */ 0x0804, /* "4" bytes of config data, 8 byte FIFO. */ 0x2e40, /* Magic values, including MAC data location. */ 0, /* Unused pad word. */ /* 0x0024: Setup station address command. */ 0, CmdSASetup, SET_MC_CMD, /* Next command. */ 0xaa00,0xb000,0x0bad, /* Station address (to be filled in) */ /* 0x0030: NOP, looping back to itself. Point to first Tx buffer to Tx. */ 0, CmdNOp, IDLELOOP, 0 /* pad */, /* 0x0038: A unused Time-Domain Reflectometer command. */ 0, CmdTDR, IDLELOOP, 0, /* 0x0040: An unused Dump State command. */ 0, CmdDump, IDLELOOP, DUMP_DATA, /* 0x0048: An unused Diagnose command. */ 0, CmdDiagnose, IDLELOOP, /* 0x004E: An empty set-multicast-list command. */ 0, CmdMulticastList, IDLELOOP, 0, }; /* Index to functions, as function prototypes. */ static int el16_probe1(struct net_device *dev, int ioaddr); static int el16_open(struct net_device *dev); static netdev_tx_t el16_send_packet(struct sk_buff *skb, struct net_device *dev); static irqreturn_t el16_interrupt(int irq, void *dev_id); static void el16_rx(struct net_device *dev); static int el16_close(struct net_device *dev); static void el16_tx_timeout (struct net_device *dev); static void hardware_send_packet(struct net_device *dev, void *buf, short length, short pad); static void init_82586_mem(struct net_device *dev); static const struct ethtool_ops netdev_ethtool_ops; static void init_rx_bufs(struct net_device *); static int io = 0x300; static int irq; static int mem_start; /* Check for a network adaptor of this type, and return '0' iff one exists. If dev->base_addr == 0, probe all likely locations. If dev->base_addr == 1, always return failure. If dev->base_addr == 2, (detachable devices only) allocate space for the device and return success. */ struct net_device * __init el16_probe(int unit) { struct net_device *dev = alloc_etherdev(sizeof(struct net_local)); static const unsigned ports[] = { 0x300, 0x320, 0x340, 0x280, 0}; const unsigned *port; int err = -ENODEV; if (!dev) return ERR_PTR(-ENODEV); if (unit >= 0) { sprintf(dev->name, "eth%d", unit); netdev_boot_setup_check(dev); io = dev->base_addr; irq = dev->irq; mem_start = dev->mem_start & 15; } if (io > 0x1ff) /* Check a single specified location. */ err = el16_probe1(dev, io); else if (io != 0) err = -ENXIO; /* Don't probe at all. */ else { for (port = ports; *port; port++) { err = el16_probe1(dev, *port); if (!err) break; } } if (err) goto out; err = register_netdev(dev); if (err) goto out1; return dev; out1: free_irq(dev->irq, dev); iounmap(((struct net_local *)netdev_priv(dev))->base); release_region(dev->base_addr, EL16_IO_EXTENT); out: free_netdev(dev); return ERR_PTR(err); } static const struct net_device_ops netdev_ops = { .ndo_open = el16_open, .ndo_stop = el16_close, .ndo_start_xmit = el16_send_packet, .ndo_tx_timeout = el16_tx_timeout, .ndo_change_mtu = eth_change_mtu, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, }; static int __init el16_probe1(struct net_device *dev, int ioaddr) { static unsigned char init_ID_done; int i, irq, irqval, retval; struct net_local *lp; if (init_ID_done == 0) { ushort lrs_state = 0xff; /* Send the ID sequence to the ID_PORT to enable the board(s). */ outb(0x00, ID_PORT); for(i = 0; i < 255; i++) { outb(lrs_state, ID_PORT); lrs_state <<= 1; if (lrs_state & 0x100) lrs_state ^= 0xe7; } outb(0x00, ID_PORT); init_ID_done = 1; } if (!request_region(ioaddr, EL16_IO_EXTENT, DRV_NAME)) return -ENODEV; if ((inb(ioaddr) != '*') || (inb(ioaddr + 1) != '3') || (inb(ioaddr + 2) != 'C') || (inb(ioaddr + 3) != 'O')) { retval = -ENODEV; goto out; } pr_info("%s: 3c507 at %#x,", dev->name, ioaddr); /* We should make a few more checks here, like the first three octets of the S.A. for the manufacturer's code. */ irq = inb(ioaddr + IRQ_CONFIG) & 0x0f; irqval = request_irq(irq, el16_interrupt, 0, DRV_NAME, dev); if (irqval) { pr_cont("\n"); pr_err("3c507: unable to get IRQ %d (irqval=%d).\n", irq, irqval); retval = -EAGAIN; goto out; } /* We've committed to using the board, and can start filling in *dev. */ dev->base_addr = ioaddr; outb(0x01, ioaddr + MISC_CTRL); for (i = 0; i < 6; i++) dev->dev_addr[i] = inb(ioaddr + i); pr_cont(" %pM", dev->dev_addr); if (mem_start) net_debug = mem_start & 7; #ifdef MEM_BASE dev->mem_start = MEM_BASE; dev->mem_end = dev->mem_start + 0x10000; #else { int base; int size; char mem_config = inb(ioaddr + MEM_CONFIG); if (mem_config & 0x20) { size = 64*1024; base = 0xf00000 + (mem_config & 0x08 ? 0x080000 : ((mem_config & 3) << 17)); } else { size = ((mem_config & 3) + 1) << 14; base = 0x0c0000 + ( (mem_config & 0x18) << 12); } dev->mem_start = base; dev->mem_end = base + size; } #endif dev->if_port = (inb(ioaddr + ROM_CONFIG) & 0x80) ? 1 : 0; dev->irq = inb(ioaddr + IRQ_CONFIG) & 0x0f; pr_cont(", IRQ %d, %sternal xcvr, memory %#lx-%#lx.\n", dev->irq, dev->if_port ? "ex" : "in", dev->mem_start, dev->mem_end-1); if (net_debug) pr_debug("%s", version); lp = netdev_priv(dev); spin_lock_init(&lp->lock); lp->base = ioremap(dev->mem_start, RX_BUF_END); if (!lp->base) { pr_err("3c507: unable to remap memory\n"); retval = -EAGAIN; goto out1; } dev->netdev_ops = &netdev_ops; dev->watchdog_timeo = TX_TIMEOUT; dev->ethtool_ops = &netdev_ethtool_ops; dev->flags &= ~IFF_MULTICAST; /* Multicast doesn't work */ return 0; out1: free_irq(dev->irq, dev); out: release_region(ioaddr, EL16_IO_EXTENT); return retval; } static int el16_open(struct net_device *dev) { /* Initialize the 82586 memory and start it. */ init_82586_mem(dev); netif_start_queue(dev); return 0; } static void el16_tx_timeout (struct net_device *dev) { struct net_local *lp = netdev_priv(dev); int ioaddr = dev->base_addr; void __iomem *shmem = lp->base; if (net_debug > 1) pr_debug("%s: transmit timed out, %s? ", dev->name, readw(shmem + iSCB_STATUS) & 0x8000 ? "IRQ conflict" : "network cable problem"); /* Try to restart the adaptor. */ if (lp->last_restart == dev->stats.tx_packets) { if (net_debug > 1) pr_cont("Resetting board.\n"); /* Completely reset the adaptor. */ init_82586_mem (dev); lp->tx_pkts_in_ring = 0; } else { /* Issue the channel attention signal and hope it "gets better". */ if (net_debug > 1) pr_cont("Kicking board.\n"); writew(0xf000 | CUC_START | RX_START, shmem + iSCB_CMD); outb (0, ioaddr + SIGNAL_CA); /* Issue channel-attn. */ lp->last_restart = dev->stats.tx_packets; } dev->trans_start = jiffies; /* prevent tx timeout */ netif_wake_queue (dev); } static netdev_tx_t el16_send_packet (struct sk_buff *skb, struct net_device *dev) { struct net_local *lp = netdev_priv(dev); int ioaddr = dev->base_addr; unsigned long flags; short length = ETH_ZLEN < skb->len ? skb->len : ETH_ZLEN; unsigned char *buf = skb->data; netif_stop_queue (dev); spin_lock_irqsave (&lp->lock, flags); dev->stats.tx_bytes += length; /* Disable the 82586's input to the interrupt line. */ outb (0x80, ioaddr + MISC_CTRL); hardware_send_packet (dev, buf, skb->len, length - skb->len); /* Enable the 82586 interrupt input. */ outb (0x84, ioaddr + MISC_CTRL); spin_unlock_irqrestore (&lp->lock, flags); dev_kfree_skb (skb); /* You might need to clean up and record Tx statistics here. */ return NETDEV_TX_OK; } /* The typical workload of the driver: Handle the network interface interrupts. */ static irqreturn_t el16_interrupt(int irq, void *dev_id) { struct net_device *dev = dev_id; struct net_local *lp; int ioaddr, status, boguscount = 0; ushort ack_cmd = 0; void __iomem *shmem; if (dev == NULL) { pr_err("net_interrupt(): irq %d for unknown device.\n", irq); return IRQ_NONE; } ioaddr = dev->base_addr; lp = netdev_priv(dev); shmem = lp->base; spin_lock(&lp->lock); status = readw(shmem+iSCB_STATUS); if (net_debug > 4) { pr_debug("%s: 3c507 interrupt, status %4.4x.\n", dev->name, status); } /* Disable the 82586's input to the interrupt line. */ outb(0x80, ioaddr + MISC_CTRL); /* Reap the Tx packet buffers. */ while (lp->tx_pkts_in_ring) { unsigned short tx_status = readw(shmem+lp->tx_reap); if (!(tx_status & 0x8000)) { if (net_debug > 5) pr_debug("Tx command incomplete (%#x).\n", lp->tx_reap); break; } /* Tx unsuccessful or some interesting status bit set. */ if (!(tx_status & 0x2000) || (tx_status & 0x0f3f)) { dev->stats.tx_errors++; if (tx_status & 0x0600) dev->stats.tx_carrier_errors++; if (tx_status & 0x0100) dev->stats.tx_fifo_errors++; if (!(tx_status & 0x0040)) dev->stats.tx_heartbeat_errors++; if (tx_status & 0x0020) dev->stats.tx_aborted_errors++; dev->stats.collisions += tx_status & 0xf; } dev->stats.tx_packets++; if (net_debug > 5) pr_debug("Reaped %x, Tx status %04x.\n" , lp->tx_reap, tx_status); lp->tx_reap += TX_BUF_SIZE; if (lp->tx_reap > RX_BUF_START - TX_BUF_SIZE) lp->tx_reap = TX_BUF_START; lp->tx_pkts_in_ring--; /* There is always more space in the Tx ring buffer now. */ netif_wake_queue(dev); if (++boguscount > 10) break; } if (status & 0x4000) { /* Packet received. */ if (net_debug > 5) pr_debug("Received packet, rx_head %04x.\n", lp->rx_head); el16_rx(dev); } /* Acknowledge the interrupt sources. */ ack_cmd = status & 0xf000; if ((status & 0x0700) != 0x0200 && netif_running(dev)) { if (net_debug) pr_debug("%s: Command unit stopped, status %04x, restarting.\n", dev->name, status); /* If this ever occurs we should really re-write the idle loop, reset the Tx list, and do a complete restart of the command unit. For now we rely on the Tx timeout if the resume doesn't work. */ ack_cmd |= CUC_RESUME; } if ((status & 0x0070) != 0x0040 && netif_running(dev)) { /* The Rx unit is not ready, it must be hung. Restart the receiver by initializing the rx buffers, and issuing an Rx start command. */ if (net_debug) pr_debug("%s: Rx unit stopped, status %04x, restarting.\n", dev->name, status); init_rx_bufs(dev); writew(RX_BUF_START,shmem+iSCB_RFA); ack_cmd |= RX_START; } writew(ack_cmd,shmem+iSCB_CMD); outb(0, ioaddr + SIGNAL_CA); /* Issue channel-attn. */ /* Clear the latched interrupt. */ outb(0, ioaddr + RESET_IRQ); /* Enable the 82586's interrupt input. */ outb(0x84, ioaddr + MISC_CTRL); spin_unlock(&lp->lock); return IRQ_HANDLED; } static int el16_close(struct net_device *dev) { struct net_local *lp = netdev_priv(dev); int ioaddr = dev->base_addr; void __iomem *shmem = lp->base; netif_stop_queue(dev); /* Flush the Tx and disable Rx. */ writew(RX_SUSPEND | CUC_SUSPEND,shmem+iSCB_CMD); outb(0, ioaddr + SIGNAL_CA); /* Disable the 82586's input to the interrupt line. */ outb(0x80, ioaddr + MISC_CTRL); /* We always physically use the IRQ line, so we don't do free_irq(). */ /* Update the statistics here. */ return 0; } /* Initialize the Rx-block list. */ static void init_rx_bufs(struct net_device *dev) { struct net_local *lp = netdev_priv(dev); void __iomem *write_ptr; unsigned short SCB_base = SCB_BASE; int cur_rxbuf = lp->rx_head = RX_BUF_START; /* Initialize each Rx frame + data buffer. */ do { /* While there is room for one more. */ write_ptr = lp->base + cur_rxbuf; writew(0x0000,write_ptr); /* Status */ writew(0x0000,write_ptr+=2); /* Command */ writew(cur_rxbuf + RX_BUF_SIZE,write_ptr+=2); /* Link */ writew(cur_rxbuf + 22,write_ptr+=2); /* Buffer offset */ writew(0x0000,write_ptr+=2); /* Pad for dest addr. */ writew(0x0000,write_ptr+=2); writew(0x0000,write_ptr+=2); writew(0x0000,write_ptr+=2); /* Pad for source addr. */ writew(0x0000,write_ptr+=2); writew(0x0000,write_ptr+=2); writew(0x0000,write_ptr+=2); /* Pad for protocol. */ writew(0x0000,write_ptr+=2); /* Buffer: Actual count */ writew(-1,write_ptr+=2); /* Buffer: Next (none). */ writew(cur_rxbuf + 0x20 + SCB_base,write_ptr+=2);/* Buffer: Address low */ writew(0x0000,write_ptr+=2); /* Finally, the number of bytes in the buffer. */ writew(0x8000 + RX_BUF_SIZE-0x20,write_ptr+=2); lp->rx_tail = cur_rxbuf; cur_rxbuf += RX_BUF_SIZE; } while (cur_rxbuf <= RX_BUF_END - RX_BUF_SIZE); /* Terminate the list by setting the EOL bit, and wrap the pointer to make the list a ring. */ write_ptr = lp->base + lp->rx_tail + 2; writew(0xC000,write_ptr); /* Command, mark as last. */ writew(lp->rx_head,write_ptr+2); /* Link */ } static void init_82586_mem(struct net_device *dev) { struct net_local *lp = netdev_priv(dev); short ioaddr = dev->base_addr; void __iomem *shmem = lp->base; /* Enable loopback to protect the wire while starting up, and hold the 586 in reset during the memory initialization. */ outb(0x20, ioaddr + MISC_CTRL); /* Fix the ISCP address and base. */ init_words[3] = SCB_BASE; init_words[7] = SCB_BASE; /* Write the words at 0xfff6 (address-aliased to 0xfffff6). */ memcpy_toio(lp->base + RX_BUF_END - 10, init_words, 10); /* Write the words at 0x0000. */ memcpy_toio(lp->base, init_words + 5, sizeof(init_words) - 10); /* Fill in the station address. */ memcpy_toio(lp->base+SA_OFFSET, dev->dev_addr, ETH_ALEN); /* The Tx-block list is written as needed. We just set up the values. */ lp->tx_cmd_link = IDLELOOP + 4; lp->tx_head = lp->tx_reap = TX_BUF_START; init_rx_bufs(dev); /* Start the 586 by releasing the reset line, but leave loopback. */ outb(0xA0, ioaddr + MISC_CTRL); /* This was time consuming to track down: you need to give two channel attention signals to reliably start up the i82586. */ outb(0, ioaddr + SIGNAL_CA); { int boguscnt = 50; while (readw(shmem+iSCB_STATUS) == 0) if (--boguscnt == 0) { pr_warning("%s: i82586 initialization timed out with status %04x, cmd %04x.\n", dev->name, readw(shmem+iSCB_STATUS), readw(shmem+iSCB_CMD)); break; } /* Issue channel-attn -- the 82586 won't start. */ outb(0, ioaddr + SIGNAL_CA); } /* Disable loopback and enable interrupts. */ outb(0x84, ioaddr + MISC_CTRL); if (net_debug > 4) pr_debug("%s: Initialized 82586, status %04x.\n", dev->name, readw(shmem+iSCB_STATUS)); } static void hardware_send_packet(struct net_device *dev, void *buf, short length, short pad) { struct net_local *lp = netdev_priv(dev); short ioaddr = dev->base_addr; ushort tx_block = lp->tx_head; void __iomem *write_ptr = lp->base + tx_block; static char padding[ETH_ZLEN]; /* Set the write pointer to the Tx block, and put out the header. */ writew(0x0000,write_ptr); /* Tx status */ writew(CMD_INTR|CmdTx,write_ptr+=2); /* Tx command */ writew(tx_block+16,write_ptr+=2); /* Next command is a NoOp. */ writew(tx_block+8,write_ptr+=2); /* Data Buffer offset. */ /* Output the data buffer descriptor. */ writew((pad + length) | 0x8000,write_ptr+=2); /* Byte count parameter. */ writew(-1,write_ptr+=2); /* No next data buffer. */ writew(tx_block+22+SCB_BASE,write_ptr+=2); /* Buffer follows the NoOp command. */ writew(0x0000,write_ptr+=2); /* Buffer address high bits (always zero). */ /* Output the Loop-back NoOp command. */ writew(0x0000,write_ptr+=2); /* Tx status */ writew(CmdNOp,write_ptr+=2); /* Tx command */ writew(tx_block+16,write_ptr+=2); /* Next is myself. */ /* Output the packet at the write pointer. */ memcpy_toio(write_ptr+2, buf, length); if (pad) memcpy_toio(write_ptr+length+2, padding, pad); /* Set the old command link pointing to this send packet. */ writew(tx_block,lp->base + lp->tx_cmd_link); lp->tx_cmd_link = tx_block + 20; /* Set the next free tx region. */ lp->tx_head = tx_block + TX_BUF_SIZE; if (lp->tx_head > RX_BUF_START - TX_BUF_SIZE) lp->tx_head = TX_BUF_START; if (net_debug > 4) { pr_debug("%s: 3c507 @%x send length = %d, tx_block %3x, next %3x.\n", dev->name, ioaddr, length, tx_block, lp->tx_head); } /* Grimly block further packets if there has been insufficient reaping. */ if (++lp->tx_pkts_in_ring < NUM_TX_BUFS) netif_wake_queue(dev); } static void el16_rx(struct net_device *dev) { struct net_local *lp = netdev_priv(dev); void __iomem *shmem = lp->base; ushort rx_head = lp->rx_head; ushort rx_tail = lp->rx_tail; ushort boguscount = 10; short frame_status; while ((frame_status = readw(shmem+rx_head)) < 0) { /* Command complete */ void __iomem *read_frame = lp->base + rx_head; ushort rfd_cmd = readw(read_frame+2); ushort next_rx_frame = readw(read_frame+4); ushort data_buffer_addr = readw(read_frame+6); void __iomem *data_frame = lp->base + data_buffer_addr; ushort pkt_len = readw(data_frame); if (rfd_cmd != 0 || data_buffer_addr != rx_head + 22 || (pkt_len & 0xC000) != 0xC000) { pr_err("%s: Rx frame at %#x corrupted, " "status %04x cmd %04x next %04x " "data-buf @%04x %04x.\n", dev->name, rx_head, frame_status, rfd_cmd, next_rx_frame, data_buffer_addr, pkt_len); } else if ((frame_status & 0x2000) == 0) { /* Frame Rxed, but with error. */ dev->stats.rx_errors++; if (frame_status & 0x0800) dev->stats.rx_crc_errors++; if (frame_status & 0x0400) dev->stats.rx_frame_errors++; if (frame_status & 0x0200) dev->stats.rx_fifo_errors++; if (frame_status & 0x0100) dev->stats.rx_over_errors++; if (frame_status & 0x0080) dev->stats.rx_length_errors++; } else { /* Malloc up new buffer. */ struct sk_buff *skb; pkt_len &= 0x3fff; skb = netdev_alloc_skb(dev, pkt_len + 2); if (skb == NULL) { pr_err("%s: Memory squeeze, dropping packet.\n", dev->name); dev->stats.rx_dropped++; break; } skb_reserve(skb,2); /* 'skb->data' points to the start of sk_buff data area. */ memcpy_fromio(skb_put(skb,pkt_len), data_frame + 10, pkt_len); skb->protocol=eth_type_trans(skb,dev); netif_rx(skb); dev->stats.rx_packets++; dev->stats.rx_bytes += pkt_len; } /* Clear the status word and set End-of-List on the rx frame. */ writew(0,read_frame); writew(0xC000,read_frame+2); /* Clear the end-of-list on the prev. RFD. */ writew(0x0000,lp->base + rx_tail + 2); rx_tail = rx_head; rx_head = next_rx_frame; if (--boguscount == 0) break; } lp->rx_head = rx_head; lp->rx_tail = rx_tail; } static void netdev_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { strcpy(info->driver, DRV_NAME); strcpy(info->version, DRV_VERSION); sprintf(info->bus_info, "ISA 0x%lx", dev->base_addr); } static u32 netdev_get_msglevel(struct net_device *dev) { return debug; } static void netdev_set_msglevel(struct net_device *dev, u32 level) { debug = level; } static const struct ethtool_ops netdev_ethtool_ops = { .get_drvinfo = netdev_get_drvinfo, .get_msglevel = netdev_get_msglevel, .set_msglevel = netdev_set_msglevel, }; #ifdef MODULE static struct net_device *dev_3c507; module_param(io, int, 0); module_param(irq, int, 0); MODULE_PARM_DESC(io, "EtherLink16 I/O base address"); MODULE_PARM_DESC(irq, "(ignored)"); int __init init_module(void) { if (io == 0) pr_notice("3c507: You should not use auto-probing with insmod!\n"); dev_3c507 = el16_probe(-1); return IS_ERR(dev_3c507) ? PTR_ERR(dev_3c507) : 0; } void __exit cleanup_module(void) { struct net_device *dev = dev_3c507; unregister_netdev(dev); free_irq(dev->irq, dev); iounmap(((struct net_local *)netdev_priv(dev))->base); release_region(dev->base_addr, EL16_IO_EXTENT); free_netdev(dev); } #endif /* MODULE */ MODULE_LICENSE("GPL");
gpl-2.0
syhost/android_kernel_pantech_ef51l
drivers/isdn/icn/icn.c
7382
42513
/* $Id: icn.c,v 1.65.6.8 2001/09/23 22:24:55 kai Exp $ * * ISDN low-level module for the ICN active ISDN-Card. * * Copyright 1994,95,96 by Fritz Elfert (fritz@isdn4linux.de) * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #include "icn.h" #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/sched.h> static int portbase = ICN_BASEADDR; static unsigned long membase = ICN_MEMADDR; static char *icn_id = "\0"; static char *icn_id2 = "\0"; MODULE_DESCRIPTION("ISDN4Linux: Driver for ICN active ISDN card"); MODULE_AUTHOR("Fritz Elfert"); MODULE_LICENSE("GPL"); module_param(portbase, int, 0); MODULE_PARM_DESC(portbase, "Port address of first card"); module_param(membase, ulong, 0); MODULE_PARM_DESC(membase, "Shared memory address of all cards"); module_param(icn_id, charp, 0); MODULE_PARM_DESC(icn_id, "ID-String of first card"); module_param(icn_id2, charp, 0); MODULE_PARM_DESC(icn_id2, "ID-String of first card, second S0 (4B only)"); /* * Verbose bootcode- and protocol-downloading. */ #undef BOOT_DEBUG /* * Verbose Shmem-Mapping. */ #undef MAP_DEBUG static char *revision = "$Revision: 1.65.6.8 $"; static int icn_addcard(int, char *, char *); /* * Free send-queue completely. * Parameter: * card = pointer to card struct * channel = channel number */ static void icn_free_queue(icn_card *card, int channel) { struct sk_buff_head *queue = &card->spqueue[channel]; struct sk_buff *skb; skb_queue_purge(queue); card->xlen[channel] = 0; card->sndcount[channel] = 0; if ((skb = card->xskb[channel])) { card->xskb[channel] = NULL; dev_kfree_skb(skb); } } /* Put a value into a shift-register, highest bit first. * Parameters: * port = port for output (bit 0 is significant) * val = value to be output * firstbit = Bit-Number of highest bit * bitcount = Number of bits to output */ static inline void icn_shiftout(unsigned short port, unsigned long val, int firstbit, int bitcount) { register u_char s; register u_char c; for (s = firstbit, c = bitcount; c > 0; s--, c--) OUTB_P((u_char) ((val >> s) & 1) ? 0xff : 0, port); } /* * disable a cards shared memory */ static inline void icn_disable_ram(icn_card *card) { OUTB_P(0, ICN_MAPRAM); } /* * enable a cards shared memory */ static inline void icn_enable_ram(icn_card *card) { OUTB_P(0xff, ICN_MAPRAM); } /* * Map a cards channel0 (Bank0/Bank8) or channel1 (Bank4/Bank12) * * must called with holding the devlock */ static inline void icn_map_channel(icn_card *card, int channel) { #ifdef MAP_DEBUG printk(KERN_DEBUG "icn_map_channel %d %d\n", dev.channel, channel); #endif if ((channel == dev.channel) && (card == dev.mcard)) return; if (dev.mcard) icn_disable_ram(dev.mcard); icn_shiftout(ICN_BANK, chan2bank[channel], 3, 4); /* Select Bank */ icn_enable_ram(card); dev.mcard = card; dev.channel = channel; #ifdef MAP_DEBUG printk(KERN_DEBUG "icn_map_channel done\n"); #endif } /* * Lock a cards channel. * Return 0 if requested card/channel is unmapped (failure). * Return 1 on success. * * must called with holding the devlock */ static inline int icn_lock_channel(icn_card *card, int channel) { register int retval; #ifdef MAP_DEBUG printk(KERN_DEBUG "icn_lock_channel %d\n", channel); #endif if ((dev.channel == channel) && (card == dev.mcard)) { dev.chanlock++; retval = 1; #ifdef MAP_DEBUG printk(KERN_DEBUG "icn_lock_channel %d OK\n", channel); #endif } else { retval = 0; #ifdef MAP_DEBUG printk(KERN_DEBUG "icn_lock_channel %d FAILED, dc=%d\n", channel, dev.channel); #endif } return retval; } /* * Release current card/channel lock * * must called with holding the devlock */ static inline void __icn_release_channel(void) { #ifdef MAP_DEBUG printk(KERN_DEBUG "icn_release_channel l=%d\n", dev.chanlock); #endif if (dev.chanlock > 0) dev.chanlock--; } /* * Release current card/channel lock */ static inline void icn_release_channel(void) { ulong flags; spin_lock_irqsave(&dev.devlock, flags); __icn_release_channel(); spin_unlock_irqrestore(&dev.devlock, flags); } /* * Try to map and lock a cards channel. * Return 1 on success, 0 on failure. */ static inline int icn_trymaplock_channel(icn_card *card, int channel) { ulong flags; #ifdef MAP_DEBUG printk(KERN_DEBUG "trymaplock c=%d dc=%d l=%d\n", channel, dev.channel, dev.chanlock); #endif spin_lock_irqsave(&dev.devlock, flags); if ((!dev.chanlock) || ((dev.channel == channel) && (dev.mcard == card))) { dev.chanlock++; icn_map_channel(card, channel); spin_unlock_irqrestore(&dev.devlock, flags); #ifdef MAP_DEBUG printk(KERN_DEBUG "trymaplock %d OK\n", channel); #endif return 1; } spin_unlock_irqrestore(&dev.devlock, flags); #ifdef MAP_DEBUG printk(KERN_DEBUG "trymaplock %d FAILED\n", channel); #endif return 0; } /* * Release current card/channel lock, * then map same or other channel without locking. */ static inline void icn_maprelease_channel(icn_card *card, int channel) { ulong flags; #ifdef MAP_DEBUG printk(KERN_DEBUG "map_release c=%d l=%d\n", channel, dev.chanlock); #endif spin_lock_irqsave(&dev.devlock, flags); if (dev.chanlock > 0) dev.chanlock--; if (!dev.chanlock) icn_map_channel(card, channel); spin_unlock_irqrestore(&dev.devlock, flags); } /* Get Data from the B-Channel, assemble fragmented packets and put them * into receive-queue. Wake up any B-Channel-reading processes. * This routine is called via timer-callback from icn_pollbchan(). */ static void icn_pollbchan_receive(int channel, icn_card *card) { int mch = channel + ((card->secondhalf) ? 2 : 0); int eflag; int cnt; struct sk_buff *skb; if (icn_trymaplock_channel(card, mch)) { while (rbavl) { cnt = readb(&rbuf_l); if ((card->rcvidx[channel] + cnt) > 4000) { printk(KERN_WARNING "icn: (%s) bogus packet on ch%d, dropping.\n", CID, channel + 1); card->rcvidx[channel] = 0; eflag = 0; } else { memcpy_fromio(&card->rcvbuf[channel][card->rcvidx[channel]], &rbuf_d, cnt); card->rcvidx[channel] += cnt; eflag = readb(&rbuf_f); } rbnext; icn_maprelease_channel(card, mch & 2); if (!eflag) { if ((cnt = card->rcvidx[channel])) { if (!(skb = dev_alloc_skb(cnt))) { printk(KERN_WARNING "icn: receive out of memory\n"); break; } memcpy(skb_put(skb, cnt), card->rcvbuf[channel], cnt); card->rcvidx[channel] = 0; card->interface.rcvcallb_skb(card->myid, channel, skb); } } if (!icn_trymaplock_channel(card, mch)) break; } icn_maprelease_channel(card, mch & 2); } } /* Send data-packet to B-Channel, split it up into fragments of * ICN_FRAGSIZE length. If last fragment is sent out, signal * success to upper layers via statcallb with ISDN_STAT_BSENT argument. * This routine is called via timer-callback from icn_pollbchan() or * directly from icn_sendbuf(). */ static void icn_pollbchan_send(int channel, icn_card *card) { int mch = channel + ((card->secondhalf) ? 2 : 0); int cnt; unsigned long flags; struct sk_buff *skb; isdn_ctrl cmd; if (!(card->sndcount[channel] || card->xskb[channel] || !skb_queue_empty(&card->spqueue[channel]))) return; if (icn_trymaplock_channel(card, mch)) { while (sbfree && (card->sndcount[channel] || !skb_queue_empty(&card->spqueue[channel]) || card->xskb[channel])) { spin_lock_irqsave(&card->lock, flags); if (card->xmit_lock[channel]) { spin_unlock_irqrestore(&card->lock, flags); break; } card->xmit_lock[channel]++; spin_unlock_irqrestore(&card->lock, flags); skb = card->xskb[channel]; if (!skb) { skb = skb_dequeue(&card->spqueue[channel]); if (skb) { /* Pop ACK-flag off skb. * Store length to xlen. */ if (*(skb_pull(skb, 1))) card->xlen[channel] = skb->len; else card->xlen[channel] = 0; } } if (!skb) break; if (skb->len > ICN_FRAGSIZE) { writeb(0xff, &sbuf_f); cnt = ICN_FRAGSIZE; } else { writeb(0x0, &sbuf_f); cnt = skb->len; } writeb(cnt, &sbuf_l); memcpy_toio(&sbuf_d, skb->data, cnt); skb_pull(skb, cnt); sbnext; /* switch to next buffer */ icn_maprelease_channel(card, mch & 2); spin_lock_irqsave(&card->lock, flags); card->sndcount[channel] -= cnt; if (!skb->len) { if (card->xskb[channel]) card->xskb[channel] = NULL; card->xmit_lock[channel] = 0; spin_unlock_irqrestore(&card->lock, flags); dev_kfree_skb(skb); if (card->xlen[channel]) { cmd.command = ISDN_STAT_BSENT; cmd.driver = card->myid; cmd.arg = channel; cmd.parm.length = card->xlen[channel]; card->interface.statcallb(&cmd); } } else { card->xskb[channel] = skb; card->xmit_lock[channel] = 0; spin_unlock_irqrestore(&card->lock, flags); } if (!icn_trymaplock_channel(card, mch)) break; } icn_maprelease_channel(card, mch & 2); } } /* Send/Receive Data to/from the B-Channel. * This routine is called via timer-callback. * It schedules itself while any B-Channel is open. */ static void icn_pollbchan(unsigned long data) { icn_card *card = (icn_card *) data; unsigned long flags; if (card->flags & ICN_FLAGS_B1ACTIVE) { icn_pollbchan_receive(0, card); icn_pollbchan_send(0, card); } if (card->flags & ICN_FLAGS_B2ACTIVE) { icn_pollbchan_receive(1, card); icn_pollbchan_send(1, card); } if (card->flags & (ICN_FLAGS_B1ACTIVE | ICN_FLAGS_B2ACTIVE)) { /* schedule b-channel polling again */ spin_lock_irqsave(&card->lock, flags); mod_timer(&card->rb_timer, jiffies + ICN_TIMER_BCREAD); card->flags |= ICN_FLAGS_RBTIMER; spin_unlock_irqrestore(&card->lock, flags); } else card->flags &= ~ICN_FLAGS_RBTIMER; } typedef struct icn_stat { char *statstr; int command; int action; } icn_stat; /* *INDENT-OFF* */ static icn_stat icn_stat_table[] = { {"BCON_", ISDN_STAT_BCONN, 1}, /* B-Channel connected */ {"BDIS_", ISDN_STAT_BHUP, 2}, /* B-Channel disconnected */ /* ** add d-channel connect and disconnect support to link-level */ {"DCON_", ISDN_STAT_DCONN, 10}, /* D-Channel connected */ {"DDIS_", ISDN_STAT_DHUP, 11}, /* D-Channel disconnected */ {"DCAL_I", ISDN_STAT_ICALL, 3}, /* Incoming call dialup-line */ {"DSCA_I", ISDN_STAT_ICALL, 3}, /* Incoming call 1TR6-SPV */ {"FCALL", ISDN_STAT_ICALL, 4}, /* Leased line connection up */ {"CIF", ISDN_STAT_CINF, 5}, /* Charge-info, 1TR6-type */ {"AOC", ISDN_STAT_CINF, 6}, /* Charge-info, DSS1-type */ {"CAU", ISDN_STAT_CAUSE, 7}, /* Cause code */ {"TEI OK", ISDN_STAT_RUN, 0}, /* Card connected to wallplug */ {"E_L1: ACT FAIL", ISDN_STAT_BHUP, 8}, /* Layer-1 activation failed */ {"E_L2: DATA LIN", ISDN_STAT_BHUP, 8}, /* Layer-2 data link lost */ {"E_L1: ACTIVATION FAILED", ISDN_STAT_BHUP, 8}, /* Layer-1 activation failed */ {NULL, 0, -1} }; /* *INDENT-ON* */ /* * Check Statusqueue-Pointer from isdn-cards. * If there are new status-replies from the interface, check * them against B-Channel-connects/disconnects and set flags accordingly. * Wake-Up any processes, who are reading the status-device. * If there are B-Channels open, initiate a timer-callback to * icn_pollbchan(). * This routine is called periodically via timer. */ static void icn_parse_status(u_char *status, int channel, icn_card *card) { icn_stat *s = icn_stat_table; int action = -1; unsigned long flags; isdn_ctrl cmd; while (s->statstr) { if (!strncmp(status, s->statstr, strlen(s->statstr))) { cmd.command = s->command; action = s->action; break; } s++; } if (action == -1) return; cmd.driver = card->myid; cmd.arg = channel; switch (action) { case 11: spin_lock_irqsave(&card->lock, flags); icn_free_queue(card, channel); card->rcvidx[channel] = 0; if (card->flags & ((channel) ? ICN_FLAGS_B2ACTIVE : ICN_FLAGS_B1ACTIVE)) { isdn_ctrl ncmd; card->flags &= ~((channel) ? ICN_FLAGS_B2ACTIVE : ICN_FLAGS_B1ACTIVE); memset(&ncmd, 0, sizeof(ncmd)); ncmd.driver = card->myid; ncmd.arg = channel; ncmd.command = ISDN_STAT_BHUP; spin_unlock_irqrestore(&card->lock, flags); card->interface.statcallb(&cmd); } else spin_unlock_irqrestore(&card->lock, flags); break; case 1: spin_lock_irqsave(&card->lock, flags); icn_free_queue(card, channel); card->flags |= (channel) ? ICN_FLAGS_B2ACTIVE : ICN_FLAGS_B1ACTIVE; spin_unlock_irqrestore(&card->lock, flags); break; case 2: spin_lock_irqsave(&card->lock, flags); card->flags &= ~((channel) ? ICN_FLAGS_B2ACTIVE : ICN_FLAGS_B1ACTIVE); icn_free_queue(card, channel); card->rcvidx[channel] = 0; spin_unlock_irqrestore(&card->lock, flags); break; case 3: { char *t = status + 6; char *s = strchr(t, ','); *s++ = '\0'; strlcpy(cmd.parm.setup.phone, t, sizeof(cmd.parm.setup.phone)); s = strchr(t = s, ','); *s++ = '\0'; if (!strlen(t)) cmd.parm.setup.si1 = 0; else cmd.parm.setup.si1 = simple_strtoul(t, NULL, 10); s = strchr(t = s, ','); *s++ = '\0'; if (!strlen(t)) cmd.parm.setup.si2 = 0; else cmd.parm.setup.si2 = simple_strtoul(t, NULL, 10); strlcpy(cmd.parm.setup.eazmsn, s, sizeof(cmd.parm.setup.eazmsn)); } cmd.parm.setup.plan = 0; cmd.parm.setup.screen = 0; break; case 4: sprintf(cmd.parm.setup.phone, "LEASED%d", card->myid); sprintf(cmd.parm.setup.eazmsn, "%d", channel + 1); cmd.parm.setup.si1 = 7; cmd.parm.setup.si2 = 0; cmd.parm.setup.plan = 0; cmd.parm.setup.screen = 0; break; case 5: strlcpy(cmd.parm.num, status + 3, sizeof(cmd.parm.num)); break; case 6: snprintf(cmd.parm.num, sizeof(cmd.parm.num), "%d", (int) simple_strtoul(status + 7, NULL, 16)); break; case 7: status += 3; if (strlen(status) == 4) snprintf(cmd.parm.num, sizeof(cmd.parm.num), "%s%c%c", status + 2, *status, *(status + 1)); else strlcpy(cmd.parm.num, status + 1, sizeof(cmd.parm.num)); break; case 8: spin_lock_irqsave(&card->lock, flags); card->flags &= ~ICN_FLAGS_B1ACTIVE; icn_free_queue(card, 0); card->rcvidx[0] = 0; spin_unlock_irqrestore(&card->lock, flags); cmd.arg = 0; cmd.driver = card->myid; card->interface.statcallb(&cmd); cmd.command = ISDN_STAT_DHUP; cmd.arg = 0; cmd.driver = card->myid; card->interface.statcallb(&cmd); cmd.command = ISDN_STAT_BHUP; spin_lock_irqsave(&card->lock, flags); card->flags &= ~ICN_FLAGS_B2ACTIVE; icn_free_queue(card, 1); card->rcvidx[1] = 0; spin_unlock_irqrestore(&card->lock, flags); cmd.arg = 1; cmd.driver = card->myid; card->interface.statcallb(&cmd); cmd.command = ISDN_STAT_DHUP; cmd.arg = 1; cmd.driver = card->myid; break; } card->interface.statcallb(&cmd); return; } static void icn_putmsg(icn_card *card, unsigned char c) { ulong flags; spin_lock_irqsave(&card->lock, flags); *card->msg_buf_write++ = (c == 0xff) ? '\n' : c; if (card->msg_buf_write == card->msg_buf_read) { if (++card->msg_buf_read > card->msg_buf_end) card->msg_buf_read = card->msg_buf; } if (card->msg_buf_write > card->msg_buf_end) card->msg_buf_write = card->msg_buf; spin_unlock_irqrestore(&card->lock, flags); } static void icn_polldchan(unsigned long data) { icn_card *card = (icn_card *) data; int mch = card->secondhalf ? 2 : 0; int avail = 0; int left; u_char c; int ch; unsigned long flags; int i; u_char *p; isdn_ctrl cmd; if (icn_trymaplock_channel(card, mch)) { avail = msg_avail; for (left = avail, i = readb(&msg_o); left > 0; i++, left--) { c = readb(&dev.shmem->comm_buffers.iopc_buf[i & 0xff]); icn_putmsg(card, c); if (c == 0xff) { card->imsg[card->iptr] = 0; card->iptr = 0; if (card->imsg[0] == '0' && card->imsg[1] >= '0' && card->imsg[1] <= '2' && card->imsg[2] == ';') { ch = (card->imsg[1] - '0') - 1; p = &card->imsg[3]; icn_parse_status(p, ch, card); } else { p = card->imsg; if (!strncmp(p, "DRV1.", 5)) { u_char vstr[10]; u_char *q = vstr; printk(KERN_INFO "icn: (%s) %s\n", CID, p); if (!strncmp(p + 7, "TC", 2)) { card->ptype = ISDN_PTYPE_1TR6; card->interface.features |= ISDN_FEATURE_P_1TR6; printk(KERN_INFO "icn: (%s) 1TR6-Protocol loaded and running\n", CID); } if (!strncmp(p + 7, "EC", 2)) { card->ptype = ISDN_PTYPE_EURO; card->interface.features |= ISDN_FEATURE_P_EURO; printk(KERN_INFO "icn: (%s) Euro-Protocol loaded and running\n", CID); } p = strstr(card->imsg, "BRV") + 3; while (*p) { if (*p >= '0' && *p <= '9') *q++ = *p; p++; } *q = '\0'; strcat(vstr, "000"); vstr[3] = '\0'; card->fw_rev = (int) simple_strtoul(vstr, NULL, 10); continue; } } } else { card->imsg[card->iptr] = c; if (card->iptr < 59) card->iptr++; } } writeb((readb(&msg_o) + avail) & 0xff, &msg_o); icn_release_channel(); } if (avail) { cmd.command = ISDN_STAT_STAVAIL; cmd.driver = card->myid; cmd.arg = avail; card->interface.statcallb(&cmd); } spin_lock_irqsave(&card->lock, flags); if (card->flags & (ICN_FLAGS_B1ACTIVE | ICN_FLAGS_B2ACTIVE)) if (!(card->flags & ICN_FLAGS_RBTIMER)) { /* schedule b-channel polling */ card->flags |= ICN_FLAGS_RBTIMER; del_timer(&card->rb_timer); card->rb_timer.function = icn_pollbchan; card->rb_timer.data = (unsigned long) card; card->rb_timer.expires = jiffies + ICN_TIMER_BCREAD; add_timer(&card->rb_timer); } /* schedule again */ mod_timer(&card->st_timer, jiffies + ICN_TIMER_DCREAD); spin_unlock_irqrestore(&card->lock, flags); } /* Append a packet to the transmit buffer-queue. * Parameters: * channel = Number of B-channel * skb = pointer to sk_buff * card = pointer to card-struct * Return: * Number of bytes transferred, -E??? on error */ static int icn_sendbuf(int channel, int ack, struct sk_buff *skb, icn_card *card) { int len = skb->len; unsigned long flags; struct sk_buff *nskb; if (len > 4000) { printk(KERN_WARNING "icn: Send packet too large\n"); return -EINVAL; } if (len) { if (!(card->flags & (channel) ? ICN_FLAGS_B2ACTIVE : ICN_FLAGS_B1ACTIVE)) return 0; if (card->sndcount[channel] > ICN_MAX_SQUEUE) return 0; #warning TODO test headroom or use skb->nb to flag ACK nskb = skb_clone(skb, GFP_ATOMIC); if (nskb) { /* Push ACK flag as one * byte in front of data. */ *(skb_push(nskb, 1)) = ack ? 1 : 0; skb_queue_tail(&card->spqueue[channel], nskb); dev_kfree_skb(skb); } else len = 0; spin_lock_irqsave(&card->lock, flags); card->sndcount[channel] += len; spin_unlock_irqrestore(&card->lock, flags); } return len; } /* * Check card's status after starting the bootstrap loader. * On entry, the card's shared memory has already to be mapped. * Return: * 0 on success (Boot loader ready) * -EIO on failure (timeout) */ static int icn_check_loader(int cardnumber) { int timer = 0; while (1) { #ifdef BOOT_DEBUG printk(KERN_DEBUG "Loader %d ?\n", cardnumber); #endif if (readb(&dev.shmem->data_control.scns) || readb(&dev.shmem->data_control.scnr)) { if (timer++ > 5) { printk(KERN_WARNING "icn: Boot-Loader %d timed out.\n", cardnumber); icn_release_channel(); return -EIO; } #ifdef BOOT_DEBUG printk(KERN_DEBUG "Loader %d TO?\n", cardnumber); #endif msleep_interruptible(ICN_BOOT_TIMEOUT1); } else { #ifdef BOOT_DEBUG printk(KERN_DEBUG "Loader %d OK\n", cardnumber); #endif icn_release_channel(); return 0; } } } /* Load the boot-code into the interface-card's memory and start it. * Always called from user-process. * * Parameters: * buffer = pointer to packet * Return: * 0 if successfully loaded */ #ifdef BOOT_DEBUG #define SLEEP(sec) { \ int slsec = sec; \ printk(KERN_DEBUG "SLEEP(%d)\n", slsec); \ while (slsec) { \ msleep_interruptible(1000); \ slsec--; \ } \ } #else #define SLEEP(sec) #endif static int icn_loadboot(u_char __user *buffer, icn_card *card) { int ret; u_char *codebuf; unsigned long flags; #ifdef BOOT_DEBUG printk(KERN_DEBUG "icn_loadboot called, buffaddr=%08lx\n", (ulong) buffer); #endif if (!(codebuf = kmalloc(ICN_CODE_STAGE1, GFP_KERNEL))) { printk(KERN_WARNING "icn: Could not allocate code buffer\n"); ret = -ENOMEM; goto out; } if (copy_from_user(codebuf, buffer, ICN_CODE_STAGE1)) { ret = -EFAULT; goto out_kfree; } if (!card->rvalid) { if (!request_region(card->port, ICN_PORTLEN, card->regname)) { printk(KERN_WARNING "icn: (%s) ports 0x%03x-0x%03x in use.\n", CID, card->port, card->port + ICN_PORTLEN); ret = -EBUSY; goto out_kfree; } card->rvalid = 1; if (card->doubleS0) card->other->rvalid = 1; } if (!dev.mvalid) { if (!request_mem_region(dev.memaddr, 0x4000, "icn-isdn (all cards)")) { printk(KERN_WARNING "icn: memory at 0x%08lx in use.\n", dev.memaddr); ret = -EBUSY; goto out_kfree; } dev.shmem = ioremap(dev.memaddr, 0x4000); dev.mvalid = 1; } OUTB_P(0, ICN_RUN); /* Reset Controller */ OUTB_P(0, ICN_MAPRAM); /* Disable RAM */ icn_shiftout(ICN_CFG, 0x0f, 3, 4); /* Windowsize= 16k */ icn_shiftout(ICN_CFG, dev.memaddr, 23, 10); /* Set RAM-Addr. */ #ifdef BOOT_DEBUG printk(KERN_DEBUG "shmem=%08lx\n", dev.memaddr); #endif SLEEP(1); #ifdef BOOT_DEBUG printk(KERN_DEBUG "Map Bank 0\n"); #endif spin_lock_irqsave(&dev.devlock, flags); icn_map_channel(card, 0); /* Select Bank 0 */ icn_lock_channel(card, 0); /* Lock Bank 0 */ spin_unlock_irqrestore(&dev.devlock, flags); SLEEP(1); memcpy_toio(dev.shmem, codebuf, ICN_CODE_STAGE1); /* Copy code */ #ifdef BOOT_DEBUG printk(KERN_DEBUG "Bootloader transferred\n"); #endif if (card->doubleS0) { SLEEP(1); #ifdef BOOT_DEBUG printk(KERN_DEBUG "Map Bank 8\n"); #endif spin_lock_irqsave(&dev.devlock, flags); __icn_release_channel(); icn_map_channel(card, 2); /* Select Bank 8 */ icn_lock_channel(card, 2); /* Lock Bank 8 */ spin_unlock_irqrestore(&dev.devlock, flags); SLEEP(1); memcpy_toio(dev.shmem, codebuf, ICN_CODE_STAGE1); /* Copy code */ #ifdef BOOT_DEBUG printk(KERN_DEBUG "Bootloader transferred\n"); #endif } SLEEP(1); OUTB_P(0xff, ICN_RUN); /* Start Boot-Code */ if ((ret = icn_check_loader(card->doubleS0 ? 2 : 1))) { goto out_kfree; } if (!card->doubleS0) { ret = 0; goto out_kfree; } /* reached only, if we have a Double-S0-Card */ #ifdef BOOT_DEBUG printk(KERN_DEBUG "Map Bank 0\n"); #endif spin_lock_irqsave(&dev.devlock, flags); icn_map_channel(card, 0); /* Select Bank 0 */ icn_lock_channel(card, 0); /* Lock Bank 0 */ spin_unlock_irqrestore(&dev.devlock, flags); SLEEP(1); ret = (icn_check_loader(1)); out_kfree: kfree(codebuf); out: return ret; } static int icn_loadproto(u_char __user *buffer, icn_card *card) { register u_char __user *p = buffer; u_char codebuf[256]; uint left = ICN_CODE_STAGE2; uint cnt; int timer; unsigned long flags; #ifdef BOOT_DEBUG printk(KERN_DEBUG "icn_loadproto called\n"); #endif if (!access_ok(VERIFY_READ, buffer, ICN_CODE_STAGE2)) return -EFAULT; timer = 0; spin_lock_irqsave(&dev.devlock, flags); if (card->secondhalf) { icn_map_channel(card, 2); icn_lock_channel(card, 2); } else { icn_map_channel(card, 0); icn_lock_channel(card, 0); } spin_unlock_irqrestore(&dev.devlock, flags); while (left) { if (sbfree) { /* If there is a free buffer... */ cnt = left; if (cnt > 256) cnt = 256; if (copy_from_user(codebuf, p, cnt)) { icn_maprelease_channel(card, 0); return -EFAULT; } memcpy_toio(&sbuf_l, codebuf, cnt); /* copy data */ sbnext; /* switch to next buffer */ p += cnt; left -= cnt; timer = 0; } else { #ifdef BOOT_DEBUG printk(KERN_DEBUG "boot 2 !sbfree\n"); #endif if (timer++ > 5) { icn_maprelease_channel(card, 0); return -EIO; } schedule_timeout_interruptible(10); } } writeb(0x20, &sbuf_n); timer = 0; while (1) { if (readb(&cmd_o) || readb(&cmd_i)) { #ifdef BOOT_DEBUG printk(KERN_DEBUG "Proto?\n"); #endif if (timer++ > 5) { printk(KERN_WARNING "icn: (%s) Protocol timed out.\n", CID); #ifdef BOOT_DEBUG printk(KERN_DEBUG "Proto TO!\n"); #endif icn_maprelease_channel(card, 0); return -EIO; } #ifdef BOOT_DEBUG printk(KERN_DEBUG "Proto TO?\n"); #endif msleep_interruptible(ICN_BOOT_TIMEOUT1); } else { if ((card->secondhalf) || (!card->doubleS0)) { #ifdef BOOT_DEBUG printk(KERN_DEBUG "Proto loaded, install poll-timer %d\n", card->secondhalf); #endif spin_lock_irqsave(&card->lock, flags); init_timer(&card->st_timer); card->st_timer.expires = jiffies + ICN_TIMER_DCREAD; card->st_timer.function = icn_polldchan; card->st_timer.data = (unsigned long) card; add_timer(&card->st_timer); card->flags |= ICN_FLAGS_RUNNING; if (card->doubleS0) { init_timer(&card->other->st_timer); card->other->st_timer.expires = jiffies + ICN_TIMER_DCREAD; card->other->st_timer.function = icn_polldchan; card->other->st_timer.data = (unsigned long) card->other; add_timer(&card->other->st_timer); card->other->flags |= ICN_FLAGS_RUNNING; } spin_unlock_irqrestore(&card->lock, flags); } icn_maprelease_channel(card, 0); return 0; } } } /* Read the Status-replies from the Interface */ static int icn_readstatus(u_char __user *buf, int len, icn_card *card) { int count; u_char __user *p; for (p = buf, count = 0; count < len; p++, count++) { if (card->msg_buf_read == card->msg_buf_write) return count; if (put_user(*card->msg_buf_read++, p)) return -EFAULT; if (card->msg_buf_read > card->msg_buf_end) card->msg_buf_read = card->msg_buf; } return count; } /* Put command-strings into the command-queue of the Interface */ static int icn_writecmd(const u_char *buf, int len, int user, icn_card *card) { int mch = card->secondhalf ? 2 : 0; int pp; int i; int count; int xcount; int ocount; int loop; unsigned long flags; int lastmap_channel; struct icn_card *lastmap_card; u_char *p; isdn_ctrl cmd; u_char msg[0x100]; ocount = 1; xcount = loop = 0; while (len) { count = cmd_free; if (count > len) count = len; if (user) { if (copy_from_user(msg, buf, count)) return -EFAULT; } else memcpy(msg, buf, count); spin_lock_irqsave(&dev.devlock, flags); lastmap_card = dev.mcard; lastmap_channel = dev.channel; icn_map_channel(card, mch); icn_putmsg(card, '>'); for (p = msg, pp = readb(&cmd_i), i = count; i > 0; i--, p++, pp ++) { writeb((*p == '\n') ? 0xff : *p, &dev.shmem->comm_buffers.pcio_buf[pp & 0xff]); len--; xcount++; icn_putmsg(card, *p); if ((*p == '\n') && (i > 1)) { icn_putmsg(card, '>'); ocount++; } ocount++; } writeb((readb(&cmd_i) + count) & 0xff, &cmd_i); if (lastmap_card) icn_map_channel(lastmap_card, lastmap_channel); spin_unlock_irqrestore(&dev.devlock, flags); if (len) { mdelay(1); if (loop++ > 20) break; } else break; } if (len && (!user)) printk(KERN_WARNING "icn: writemsg incomplete!\n"); cmd.command = ISDN_STAT_STAVAIL; cmd.driver = card->myid; cmd.arg = ocount; card->interface.statcallb(&cmd); return xcount; } /* * Delete card's pending timers, send STOP to linklevel */ static void icn_stopcard(icn_card *card) { unsigned long flags; isdn_ctrl cmd; spin_lock_irqsave(&card->lock, flags); if (card->flags & ICN_FLAGS_RUNNING) { card->flags &= ~ICN_FLAGS_RUNNING; del_timer(&card->st_timer); del_timer(&card->rb_timer); spin_unlock_irqrestore(&card->lock, flags); cmd.command = ISDN_STAT_STOP; cmd.driver = card->myid; card->interface.statcallb(&cmd); if (card->doubleS0) icn_stopcard(card->other); } else spin_unlock_irqrestore(&card->lock, flags); } static void icn_stopallcards(void) { icn_card *p = cards; while (p) { icn_stopcard(p); p = p->next; } } /* * Unmap all cards, because some of them may be mapped accidetly during * autoprobing of some network drivers (SMC-driver?) */ static void icn_disable_cards(void) { icn_card *card = cards; while (card) { if (!request_region(card->port, ICN_PORTLEN, "icn-isdn")) { printk(KERN_WARNING "icn: (%s) ports 0x%03x-0x%03x in use.\n", CID, card->port, card->port + ICN_PORTLEN); } else { OUTB_P(0, ICN_RUN); /* Reset Controller */ OUTB_P(0, ICN_MAPRAM); /* Disable RAM */ release_region(card->port, ICN_PORTLEN); } card = card->next; } } static int icn_command(isdn_ctrl *c, icn_card *card) { ulong a; ulong flags; int i; char cbuf[60]; isdn_ctrl cmd; icn_cdef cdef; char __user *arg; switch (c->command) { case ISDN_CMD_IOCTL: memcpy(&a, c->parm.num, sizeof(ulong)); arg = (char __user *)a; switch (c->arg) { case ICN_IOCTL_SETMMIO: if (dev.memaddr != (a & 0x0ffc000)) { if (!request_mem_region(a & 0x0ffc000, 0x4000, "icn-isdn (all cards)")) { printk(KERN_WARNING "icn: memory at 0x%08lx in use.\n", a & 0x0ffc000); return -EINVAL; } release_mem_region(a & 0x0ffc000, 0x4000); icn_stopallcards(); spin_lock_irqsave(&card->lock, flags); if (dev.mvalid) { iounmap(dev.shmem); release_mem_region(dev.memaddr, 0x4000); } dev.mvalid = 0; dev.memaddr = a & 0x0ffc000; spin_unlock_irqrestore(&card->lock, flags); printk(KERN_INFO "icn: (%s) mmio set to 0x%08lx\n", CID, dev.memaddr); } break; case ICN_IOCTL_GETMMIO: return (long) dev.memaddr; case ICN_IOCTL_SETPORT: if (a == 0x300 || a == 0x310 || a == 0x320 || a == 0x330 || a == 0x340 || a == 0x350 || a == 0x360 || a == 0x308 || a == 0x318 || a == 0x328 || a == 0x338 || a == 0x348 || a == 0x358 || a == 0x368) { if (card->port != (unsigned short) a) { if (!request_region((unsigned short) a, ICN_PORTLEN, "icn-isdn")) { printk(KERN_WARNING "icn: (%s) ports 0x%03x-0x%03x in use.\n", CID, (int) a, (int) a + ICN_PORTLEN); return -EINVAL; } release_region((unsigned short) a, ICN_PORTLEN); icn_stopcard(card); spin_lock_irqsave(&card->lock, flags); if (card->rvalid) release_region(card->port, ICN_PORTLEN); card->port = (unsigned short) a; card->rvalid = 0; if (card->doubleS0) { card->other->port = (unsigned short) a; card->other->rvalid = 0; } spin_unlock_irqrestore(&card->lock, flags); printk(KERN_INFO "icn: (%s) port set to 0x%03x\n", CID, card->port); } } else return -EINVAL; break; case ICN_IOCTL_GETPORT: return (int) card->port; case ICN_IOCTL_GETDOUBLE: return (int) card->doubleS0; case ICN_IOCTL_DEBUGVAR: if (copy_to_user(arg, &card, sizeof(ulong))) return -EFAULT; a += sizeof(ulong); { ulong l = (ulong)&dev; if (copy_to_user(arg, &l, sizeof(ulong))) return -EFAULT; } return 0; case ICN_IOCTL_LOADBOOT: if (dev.firstload) { icn_disable_cards(); dev.firstload = 0; } icn_stopcard(card); return (icn_loadboot(arg, card)); case ICN_IOCTL_LOADPROTO: icn_stopcard(card); if ((i = (icn_loadproto(arg, card)))) return i; if (card->doubleS0) i = icn_loadproto(arg + ICN_CODE_STAGE2, card->other); return i; break; case ICN_IOCTL_ADDCARD: if (!dev.firstload) return -EBUSY; if (copy_from_user(&cdef, arg, sizeof(cdef))) return -EFAULT; return (icn_addcard(cdef.port, cdef.id1, cdef.id2)); break; case ICN_IOCTL_LEASEDCFG: if (a) { if (!card->leased) { card->leased = 1; while (card->ptype == ISDN_PTYPE_UNKNOWN) { msleep_interruptible(ICN_BOOT_TIMEOUT1); } msleep_interruptible(ICN_BOOT_TIMEOUT1); sprintf(cbuf, "00;FV2ON\n01;EAZ%c\n02;EAZ%c\n", (a & 1) ? '1' : 'C', (a & 2) ? '2' : 'C'); i = icn_writecmd(cbuf, strlen(cbuf), 0, card); printk(KERN_INFO "icn: (%s) Leased-line mode enabled\n", CID); cmd.command = ISDN_STAT_RUN; cmd.driver = card->myid; cmd.arg = 0; card->interface.statcallb(&cmd); } } else { if (card->leased) { card->leased = 0; sprintf(cbuf, "00;FV2OFF\n"); i = icn_writecmd(cbuf, strlen(cbuf), 0, card); printk(KERN_INFO "icn: (%s) Leased-line mode disabled\n", CID); cmd.command = ISDN_STAT_RUN; cmd.driver = card->myid; cmd.arg = 0; card->interface.statcallb(&cmd); } } return 0; default: return -EINVAL; } break; case ISDN_CMD_DIAL: if (!(card->flags & ICN_FLAGS_RUNNING)) return -ENODEV; if (card->leased) break; if ((c->arg & 255) < ICN_BCH) { char *p; char dial[50]; char dcode[4]; a = c->arg; p = c->parm.setup.phone; if (*p == 's' || *p == 'S') { /* Dial for SPV */ p++; strcpy(dcode, "SCA"); } else /* Normal Dial */ strcpy(dcode, "CAL"); strcpy(dial, p); sprintf(cbuf, "%02d;D%s_R%s,%02d,%02d,%s\n", (int) (a + 1), dcode, dial, c->parm.setup.si1, c->parm.setup.si2, c->parm.setup.eazmsn); i = icn_writecmd(cbuf, strlen(cbuf), 0, card); } break; case ISDN_CMD_ACCEPTD: if (!(card->flags & ICN_FLAGS_RUNNING)) return -ENODEV; if (c->arg < ICN_BCH) { a = c->arg + 1; if (card->fw_rev >= 300) { switch (card->l2_proto[a - 1]) { case ISDN_PROTO_L2_X75I: sprintf(cbuf, "%02d;BX75\n", (int) a); break; case ISDN_PROTO_L2_HDLC: sprintf(cbuf, "%02d;BTRA\n", (int) a); break; } i = icn_writecmd(cbuf, strlen(cbuf), 0, card); } sprintf(cbuf, "%02d;DCON_R\n", (int) a); i = icn_writecmd(cbuf, strlen(cbuf), 0, card); } break; case ISDN_CMD_ACCEPTB: if (!(card->flags & ICN_FLAGS_RUNNING)) return -ENODEV; if (c->arg < ICN_BCH) { a = c->arg + 1; if (card->fw_rev >= 300) switch (card->l2_proto[a - 1]) { case ISDN_PROTO_L2_X75I: sprintf(cbuf, "%02d;BCON_R,BX75\n", (int) a); break; case ISDN_PROTO_L2_HDLC: sprintf(cbuf, "%02d;BCON_R,BTRA\n", (int) a); break; } else sprintf(cbuf, "%02d;BCON_R\n", (int) a); i = icn_writecmd(cbuf, strlen(cbuf), 0, card); } break; case ISDN_CMD_HANGUP: if (!(card->flags & ICN_FLAGS_RUNNING)) return -ENODEV; if (c->arg < ICN_BCH) { a = c->arg + 1; sprintf(cbuf, "%02d;BDIS_R\n%02d;DDIS_R\n", (int) a, (int) a); i = icn_writecmd(cbuf, strlen(cbuf), 0, card); } break; case ISDN_CMD_SETEAZ: if (!(card->flags & ICN_FLAGS_RUNNING)) return -ENODEV; if (card->leased) break; if (c->arg < ICN_BCH) { a = c->arg + 1; if (card->ptype == ISDN_PTYPE_EURO) { sprintf(cbuf, "%02d;MS%s%s\n", (int) a, c->parm.num[0] ? "N" : "ALL", c->parm.num); } else sprintf(cbuf, "%02d;EAZ%s\n", (int) a, c->parm.num[0] ? (char *)(c->parm.num) : "0123456789"); i = icn_writecmd(cbuf, strlen(cbuf), 0, card); } break; case ISDN_CMD_CLREAZ: if (!(card->flags & ICN_FLAGS_RUNNING)) return -ENODEV; if (card->leased) break; if (c->arg < ICN_BCH) { a = c->arg + 1; if (card->ptype == ISDN_PTYPE_EURO) sprintf(cbuf, "%02d;MSNC\n", (int) a); else sprintf(cbuf, "%02d;EAZC\n", (int) a); i = icn_writecmd(cbuf, strlen(cbuf), 0, card); } break; case ISDN_CMD_SETL2: if (!(card->flags & ICN_FLAGS_RUNNING)) return -ENODEV; if ((c->arg & 255) < ICN_BCH) { a = c->arg; switch (a >> 8) { case ISDN_PROTO_L2_X75I: sprintf(cbuf, "%02d;BX75\n", (int) (a & 255) + 1); break; case ISDN_PROTO_L2_HDLC: sprintf(cbuf, "%02d;BTRA\n", (int) (a & 255) + 1); break; default: return -EINVAL; } i = icn_writecmd(cbuf, strlen(cbuf), 0, card); card->l2_proto[a & 255] = (a >> 8); } break; case ISDN_CMD_SETL3: if (!(card->flags & ICN_FLAGS_RUNNING)) return -ENODEV; return 0; default: return -EINVAL; } return 0; } /* * Find card with given driverId */ static inline icn_card * icn_findcard(int driverid) { icn_card *p = cards; while (p) { if (p->myid == driverid) return p; p = p->next; } return (icn_card *) 0; } /* * Wrapper functions for interface to linklevel */ static int if_command(isdn_ctrl *c) { icn_card *card = icn_findcard(c->driver); if (card) return (icn_command(c, card)); printk(KERN_ERR "icn: if_command %d called with invalid driverId %d!\n", c->command, c->driver); return -ENODEV; } static int if_writecmd(const u_char __user *buf, int len, int id, int channel) { icn_card *card = icn_findcard(id); if (card) { if (!(card->flags & ICN_FLAGS_RUNNING)) return -ENODEV; return (icn_writecmd(buf, len, 1, card)); } printk(KERN_ERR "icn: if_writecmd called with invalid driverId!\n"); return -ENODEV; } static int if_readstatus(u_char __user *buf, int len, int id, int channel) { icn_card *card = icn_findcard(id); if (card) { if (!(card->flags & ICN_FLAGS_RUNNING)) return -ENODEV; return (icn_readstatus(buf, len, card)); } printk(KERN_ERR "icn: if_readstatus called with invalid driverId!\n"); return -ENODEV; } static int if_sendbuf(int id, int channel, int ack, struct sk_buff *skb) { icn_card *card = icn_findcard(id); if (card) { if (!(card->flags & ICN_FLAGS_RUNNING)) return -ENODEV; return (icn_sendbuf(channel, ack, skb, card)); } printk(KERN_ERR "icn: if_sendbuf called with invalid driverId!\n"); return -ENODEV; } /* * Allocate a new card-struct, initialize it * link it into cards-list and register it at linklevel. */ static icn_card * icn_initcard(int port, char *id) { icn_card *card; int i; if (!(card = kzalloc(sizeof(icn_card), GFP_KERNEL))) { printk(KERN_WARNING "icn: (%s) Could not allocate card-struct.\n", id); return (icn_card *) 0; } spin_lock_init(&card->lock); card->port = port; card->interface.owner = THIS_MODULE; card->interface.hl_hdrlen = 1; card->interface.channels = ICN_BCH; card->interface.maxbufsize = 4000; card->interface.command = if_command; card->interface.writebuf_skb = if_sendbuf; card->interface.writecmd = if_writecmd; card->interface.readstat = if_readstatus; card->interface.features = ISDN_FEATURE_L2_X75I | ISDN_FEATURE_L2_HDLC | ISDN_FEATURE_L3_TRANS | ISDN_FEATURE_P_UNKNOWN; card->ptype = ISDN_PTYPE_UNKNOWN; strlcpy(card->interface.id, id, sizeof(card->interface.id)); card->msg_buf_write = card->msg_buf; card->msg_buf_read = card->msg_buf; card->msg_buf_end = &card->msg_buf[sizeof(card->msg_buf) - 1]; for (i = 0; i < ICN_BCH; i++) { card->l2_proto[i] = ISDN_PROTO_L2_X75I; skb_queue_head_init(&card->spqueue[i]); } card->next = cards; cards = card; if (!register_isdn(&card->interface)) { cards = cards->next; printk(KERN_WARNING "icn: Unable to register %s\n", id); kfree(card); return (icn_card *) 0; } card->myid = card->interface.channels; sprintf(card->regname, "icn-isdn (%s)", card->interface.id); return card; } static int icn_addcard(int port, char *id1, char *id2) { icn_card *card; icn_card *card2; if (!(card = icn_initcard(port, id1))) { return -EIO; } if (!strlen(id2)) { printk(KERN_INFO "icn: (%s) ICN-2B, port 0x%x added\n", card->interface.id, port); return 0; } if (!(card2 = icn_initcard(port, id2))) { printk(KERN_INFO "icn: (%s) half ICN-4B, port 0x%x added\n", card2->interface.id, port); return 0; } card->doubleS0 = 1; card->secondhalf = 0; card->other = card2; card2->doubleS0 = 1; card2->secondhalf = 1; card2->other = card; printk(KERN_INFO "icn: (%s and %s) ICN-4B, port 0x%x added\n", card->interface.id, card2->interface.id, port); return 0; } #ifndef MODULE static int __init icn_setup(char *line) { char *p, *str; int ints[3]; static char sid[20]; static char sid2[20]; str = get_options(line, 2, ints); if (ints[0]) portbase = ints[1]; if (ints[0] > 1) membase = (unsigned long)ints[2]; if (str && *str) { strcpy(sid, str); icn_id = sid; if ((p = strchr(sid, ','))) { *p++ = 0; strcpy(sid2, p); icn_id2 = sid2; } } return (1); } __setup("icn=", icn_setup); #endif /* MODULE */ static int __init icn_init(void) { char *p; char rev[21]; memset(&dev, 0, sizeof(icn_dev)); dev.memaddr = (membase & 0x0ffc000); dev.channel = -1; dev.mcard = NULL; dev.firstload = 1; spin_lock_init(&dev.devlock); if ((p = strchr(revision, ':'))) { strncpy(rev, p + 1, 20); rev[20] = '\0'; p = strchr(rev, '$'); if (p) *p = 0; } else strcpy(rev, " ??? "); printk(KERN_NOTICE "ICN-ISDN-driver Rev%smem=0x%08lx\n", rev, dev.memaddr); return (icn_addcard(portbase, icn_id, icn_id2)); } static void __exit icn_exit(void) { isdn_ctrl cmd; icn_card *card = cards; icn_card *last, *tmpcard; int i; unsigned long flags; icn_stopallcards(); while (card) { cmd.command = ISDN_STAT_UNLOAD; cmd.driver = card->myid; card->interface.statcallb(&cmd); spin_lock_irqsave(&card->lock, flags); if (card->rvalid) { OUTB_P(0, ICN_RUN); /* Reset Controller */ OUTB_P(0, ICN_MAPRAM); /* Disable RAM */ if (card->secondhalf || (!card->doubleS0)) { release_region(card->port, ICN_PORTLEN); card->rvalid = 0; } for (i = 0; i < ICN_BCH; i++) icn_free_queue(card, i); } tmpcard = card->next; spin_unlock_irqrestore(&card->lock, flags); card = tmpcard; } card = cards; cards = NULL; while (card) { last = card; card = card->next; kfree(last); } if (dev.mvalid) { iounmap(dev.shmem); release_mem_region(dev.memaddr, 0x4000); } printk(KERN_NOTICE "ICN-ISDN-driver unloaded\n"); } module_init(icn_init); module_exit(icn_exit);
gpl-2.0
ZolaIII/android_kernel_synopsis_nightly
arch/sh/drivers/dma/dma-api.c
7894
9355
/* * arch/sh/drivers/dma/dma-api.c * * SuperH-specific DMA management API * * Copyright (C) 2003, 2004, 2005 Paul Mundt * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/init.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/proc_fs.h> #include <linux/list.h> #include <linux/platform_device.h> #include <linux/mm.h> #include <linux/sched.h> #include <linux/slab.h> #include <asm/dma.h> DEFINE_SPINLOCK(dma_spin_lock); static LIST_HEAD(registered_dmac_list); struct dma_info *get_dma_info(unsigned int chan) { struct dma_info *info; /* * Look for each DMAC's range to determine who the owner of * the channel is. */ list_for_each_entry(info, &registered_dmac_list, list) { if ((chan < info->first_vchannel_nr) || (chan >= info->first_vchannel_nr + info->nr_channels)) continue; return info; } return NULL; } EXPORT_SYMBOL(get_dma_info); struct dma_info *get_dma_info_by_name(const char *dmac_name) { struct dma_info *info; list_for_each_entry(info, &registered_dmac_list, list) { if (dmac_name && (strcmp(dmac_name, info->name) != 0)) continue; else return info; } return NULL; } EXPORT_SYMBOL(get_dma_info_by_name); static unsigned int get_nr_channels(void) { struct dma_info *info; unsigned int nr = 0; if (unlikely(list_empty(&registered_dmac_list))) return nr; list_for_each_entry(info, &registered_dmac_list, list) nr += info->nr_channels; return nr; } struct dma_channel *get_dma_channel(unsigned int chan) { struct dma_info *info = get_dma_info(chan); struct dma_channel *channel; int i; if (unlikely(!info)) return ERR_PTR(-EINVAL); for (i = 0; i < info->nr_channels; i++) { channel = &info->channels[i]; if (channel->vchan == chan) return channel; } return NULL; } EXPORT_SYMBOL(get_dma_channel); int get_dma_residue(unsigned int chan) { struct dma_info *info = get_dma_info(chan); struct dma_channel *channel = get_dma_channel(chan); if (info->ops->get_residue) return info->ops->get_residue(channel); return 0; } EXPORT_SYMBOL(get_dma_residue); static int search_cap(const char **haystack, const char *needle) { const char **p; for (p = haystack; *p; p++) if (strcmp(*p, needle) == 0) return 1; return 0; } /** * request_dma_bycap - Allocate a DMA channel based on its capabilities * @dmac: List of DMA controllers to search * @caps: List of capabilities * * Search all channels of all DMA controllers to find a channel which * matches the requested capabilities. The result is the channel * number if a match is found, or %-ENODEV if no match is found. * * Note that not all DMA controllers export capabilities, in which * case they can never be allocated using this API, and so * request_dma() must be used specifying the channel number. */ int request_dma_bycap(const char **dmac, const char **caps, const char *dev_id) { unsigned int found = 0; struct dma_info *info; const char **p; int i; BUG_ON(!dmac || !caps); list_for_each_entry(info, &registered_dmac_list, list) if (strcmp(*dmac, info->name) == 0) { found = 1; break; } if (!found) return -ENODEV; for (i = 0; i < info->nr_channels; i++) { struct dma_channel *channel = &info->channels[i]; if (unlikely(!channel->caps)) continue; for (p = caps; *p; p++) { if (!search_cap(channel->caps, *p)) break; if (request_dma(channel->chan, dev_id) == 0) return channel->chan; } } return -EINVAL; } EXPORT_SYMBOL(request_dma_bycap); int dmac_search_free_channel(const char *dev_id) { struct dma_channel *channel = { 0 }; struct dma_info *info = get_dma_info(0); int i; for (i = 0; i < info->nr_channels; i++) { channel = &info->channels[i]; if (unlikely(!channel)) return -ENODEV; if (atomic_read(&channel->busy) == 0) break; } if (info->ops->request) { int result = info->ops->request(channel); if (result) return result; atomic_set(&channel->busy, 1); return channel->chan; } return -ENOSYS; } int request_dma(unsigned int chan, const char *dev_id) { struct dma_channel *channel = { 0 }; struct dma_info *info = get_dma_info(chan); int result; channel = get_dma_channel(chan); if (atomic_xchg(&channel->busy, 1)) return -EBUSY; strlcpy(channel->dev_id, dev_id, sizeof(channel->dev_id)); if (info->ops->request) { result = info->ops->request(channel); if (result) atomic_set(&channel->busy, 0); return result; } return 0; } EXPORT_SYMBOL(request_dma); void free_dma(unsigned int chan) { struct dma_info *info = get_dma_info(chan); struct dma_channel *channel = get_dma_channel(chan); if (info->ops->free) info->ops->free(channel); atomic_set(&channel->busy, 0); } EXPORT_SYMBOL(free_dma); void dma_wait_for_completion(unsigned int chan) { struct dma_info *info = get_dma_info(chan); struct dma_channel *channel = get_dma_channel(chan); if (channel->flags & DMA_TEI_CAPABLE) { wait_event(channel->wait_queue, (info->ops->get_residue(channel) == 0)); return; } while (info->ops->get_residue(channel)) cpu_relax(); } EXPORT_SYMBOL(dma_wait_for_completion); int register_chan_caps(const char *dmac, struct dma_chan_caps *caps) { struct dma_info *info; unsigned int found = 0; int i; list_for_each_entry(info, &registered_dmac_list, list) if (strcmp(dmac, info->name) == 0) { found = 1; break; } if (unlikely(!found)) return -ENODEV; for (i = 0; i < info->nr_channels; i++, caps++) { struct dma_channel *channel; if ((info->first_channel_nr + i) != caps->ch_num) return -EINVAL; channel = &info->channels[i]; channel->caps = caps->caplist; } return 0; } EXPORT_SYMBOL(register_chan_caps); void dma_configure_channel(unsigned int chan, unsigned long flags) { struct dma_info *info = get_dma_info(chan); struct dma_channel *channel = get_dma_channel(chan); if (info->ops->configure) info->ops->configure(channel, flags); } EXPORT_SYMBOL(dma_configure_channel); int dma_xfer(unsigned int chan, unsigned long from, unsigned long to, size_t size, unsigned int mode) { struct dma_info *info = get_dma_info(chan); struct dma_channel *channel = get_dma_channel(chan); channel->sar = from; channel->dar = to; channel->count = size; channel->mode = mode; return info->ops->xfer(channel); } EXPORT_SYMBOL(dma_xfer); int dma_extend(unsigned int chan, unsigned long op, void *param) { struct dma_info *info = get_dma_info(chan); struct dma_channel *channel = get_dma_channel(chan); if (info->ops->extend) return info->ops->extend(channel, op, param); return -ENOSYS; } EXPORT_SYMBOL(dma_extend); static int dma_read_proc(char *buf, char **start, off_t off, int len, int *eof, void *data) { struct dma_info *info; char *p = buf; if (list_empty(&registered_dmac_list)) return 0; /* * Iterate over each registered DMAC */ list_for_each_entry(info, &registered_dmac_list, list) { int i; /* * Iterate over each channel */ for (i = 0; i < info->nr_channels; i++) { struct dma_channel *channel = info->channels + i; if (!(channel->flags & DMA_CONFIGURED)) continue; p += sprintf(p, "%2d: %14s %s\n", i, info->name, channel->dev_id); } } return p - buf; } int register_dmac(struct dma_info *info) { unsigned int total_channels, i; INIT_LIST_HEAD(&info->list); printk(KERN_INFO "DMA: Registering %s handler (%d channel%s).\n", info->name, info->nr_channels, info->nr_channels > 1 ? "s" : ""); BUG_ON((info->flags & DMAC_CHANNELS_CONFIGURED) && !info->channels); info->pdev = platform_device_register_simple(info->name, -1, NULL, 0); if (IS_ERR(info->pdev)) return PTR_ERR(info->pdev); /* * Don't touch pre-configured channels */ if (!(info->flags & DMAC_CHANNELS_CONFIGURED)) { unsigned int size; size = sizeof(struct dma_channel) * info->nr_channels; info->channels = kzalloc(size, GFP_KERNEL); if (!info->channels) return -ENOMEM; } total_channels = get_nr_channels(); info->first_vchannel_nr = total_channels; for (i = 0; i < info->nr_channels; i++) { struct dma_channel *chan = &info->channels[i]; atomic_set(&chan->busy, 0); chan->chan = info->first_channel_nr + i; chan->vchan = info->first_channel_nr + i + total_channels; memcpy(chan->dev_id, "Unused", 7); if (info->flags & DMAC_CHANNELS_TEI_CAPABLE) chan->flags |= DMA_TEI_CAPABLE; init_waitqueue_head(&chan->wait_queue); dma_create_sysfs_files(chan, info); } list_add(&info->list, &registered_dmac_list); return 0; } EXPORT_SYMBOL(register_dmac); void unregister_dmac(struct dma_info *info) { unsigned int i; for (i = 0; i < info->nr_channels; i++) dma_remove_sysfs_files(info->channels + i, info); if (!(info->flags & DMAC_CHANNELS_CONFIGURED)) kfree(info->channels); list_del(&info->list); platform_device_unregister(info->pdev); } EXPORT_SYMBOL(unregister_dmac); static int __init dma_api_init(void) { printk(KERN_NOTICE "DMA: Registering DMA API.\n"); return create_proc_read_entry("dma", 0, 0, dma_read_proc, 0) ? 0 : -ENOMEM; } subsys_initcall(dma_api_init); MODULE_AUTHOR("Paul Mundt <lethal@linux-sh.org>"); MODULE_DESCRIPTION("DMA API for SuperH"); MODULE_LICENSE("GPL");
gpl-2.0
omnirom/android_kernel_samsung_piranha
samples/kobject/kset-example.c
11734
6937
/* * Sample kset and ktype implementation * * Copyright (C) 2004-2007 Greg Kroah-Hartman <greg@kroah.com> * Copyright (C) 2007 Novell Inc. * * Released under the GPL version 2 only. * */ #include <linux/kobject.h> #include <linux/string.h> #include <linux/sysfs.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/init.h> /* * This module shows how to create a kset in sysfs called * /sys/kernel/kset-example * Then tree kobjects are created and assigned to this kset, "foo", "baz", * and "bar". In those kobjects, attributes of the same name are also * created and if an integer is written to these files, it can be later * read out of it. */ /* * This is our "object" that we will create a few of and register them with * sysfs. */ struct foo_obj { struct kobject kobj; int foo; int baz; int bar; }; #define to_foo_obj(x) container_of(x, struct foo_obj, kobj) /* a custom attribute that works just for a struct foo_obj. */ struct foo_attribute { struct attribute attr; ssize_t (*show)(struct foo_obj *foo, struct foo_attribute *attr, char *buf); ssize_t (*store)(struct foo_obj *foo, struct foo_attribute *attr, const char *buf, size_t count); }; #define to_foo_attr(x) container_of(x, struct foo_attribute, attr) /* * The default show function that must be passed to sysfs. This will be * called by sysfs for whenever a show function is called by the user on a * sysfs file associated with the kobjects we have registered. We need to * transpose back from a "default" kobject to our custom struct foo_obj and * then call the show function for that specific object. */ static ssize_t foo_attr_show(struct kobject *kobj, struct attribute *attr, char *buf) { struct foo_attribute *attribute; struct foo_obj *foo; attribute = to_foo_attr(attr); foo = to_foo_obj(kobj); if (!attribute->show) return -EIO; return attribute->show(foo, attribute, buf); } /* * Just like the default show function above, but this one is for when the * sysfs "store" is requested (when a value is written to a file.) */ static ssize_t foo_attr_store(struct kobject *kobj, struct attribute *attr, const char *buf, size_t len) { struct foo_attribute *attribute; struct foo_obj *foo; attribute = to_foo_attr(attr); foo = to_foo_obj(kobj); if (!attribute->store) return -EIO; return attribute->store(foo, attribute, buf, len); } /* Our custom sysfs_ops that we will associate with our ktype later on */ static const struct sysfs_ops foo_sysfs_ops = { .show = foo_attr_show, .store = foo_attr_store, }; /* * The release function for our object. This is REQUIRED by the kernel to * have. We free the memory held in our object here. * * NEVER try to get away with just a "blank" release function to try to be * smarter than the kernel. Turns out, no one ever is... */ static void foo_release(struct kobject *kobj) { struct foo_obj *foo; foo = to_foo_obj(kobj); kfree(foo); } /* * The "foo" file where the .foo variable is read from and written to. */ static ssize_t foo_show(struct foo_obj *foo_obj, struct foo_attribute *attr, char *buf) { return sprintf(buf, "%d\n", foo_obj->foo); } static ssize_t foo_store(struct foo_obj *foo_obj, struct foo_attribute *attr, const char *buf, size_t count) { sscanf(buf, "%du", &foo_obj->foo); return count; } static struct foo_attribute foo_attribute = __ATTR(foo, 0666, foo_show, foo_store); /* * More complex function where we determine which variable is being accessed by * looking at the attribute for the "baz" and "bar" files. */ static ssize_t b_show(struct foo_obj *foo_obj, struct foo_attribute *attr, char *buf) { int var; if (strcmp(attr->attr.name, "baz") == 0) var = foo_obj->baz; else var = foo_obj->bar; return sprintf(buf, "%d\n", var); } static ssize_t b_store(struct foo_obj *foo_obj, struct foo_attribute *attr, const char *buf, size_t count) { int var; sscanf(buf, "%du", &var); if (strcmp(attr->attr.name, "baz") == 0) foo_obj->baz = var; else foo_obj->bar = var; return count; } static struct foo_attribute baz_attribute = __ATTR(baz, 0666, b_show, b_store); static struct foo_attribute bar_attribute = __ATTR(bar, 0666, b_show, b_store); /* * Create a group of attributes so that we can create and destroy them all * at once. */ static struct attribute *foo_default_attrs[] = { &foo_attribute.attr, &baz_attribute.attr, &bar_attribute.attr, NULL, /* need to NULL terminate the list of attributes */ }; /* * Our own ktype for our kobjects. Here we specify our sysfs ops, the * release function, and the set of default attributes we want created * whenever a kobject of this type is registered with the kernel. */ static struct kobj_type foo_ktype = { .sysfs_ops = &foo_sysfs_ops, .release = foo_release, .default_attrs = foo_default_attrs, }; static struct kset *example_kset; static struct foo_obj *foo_obj; static struct foo_obj *bar_obj; static struct foo_obj *baz_obj; static struct foo_obj *create_foo_obj(const char *name) { struct foo_obj *foo; int retval; /* allocate the memory for the whole object */ foo = kzalloc(sizeof(*foo), GFP_KERNEL); if (!foo) return NULL; /* * As we have a kset for this kobject, we need to set it before calling * the kobject core. */ foo->kobj.kset = example_kset; /* * Initialize and add the kobject to the kernel. All the default files * will be created here. As we have already specified a kset for this * kobject, we don't have to set a parent for the kobject, the kobject * will be placed beneath that kset automatically. */ retval = kobject_init_and_add(&foo->kobj, &foo_ktype, NULL, "%s", name); if (retval) { kobject_put(&foo->kobj); return NULL; } /* * We are always responsible for sending the uevent that the kobject * was added to the system. */ kobject_uevent(&foo->kobj, KOBJ_ADD); return foo; } static void destroy_foo_obj(struct foo_obj *foo) { kobject_put(&foo->kobj); } static int __init example_init(void) { /* * Create a kset with the name of "kset_example", * located under /sys/kernel/ */ example_kset = kset_create_and_add("kset_example", NULL, kernel_kobj); if (!example_kset) return -ENOMEM; /* * Create three objects and register them with our kset */ foo_obj = create_foo_obj("foo"); if (!foo_obj) goto foo_error; bar_obj = create_foo_obj("bar"); if (!bar_obj) goto bar_error; baz_obj = create_foo_obj("baz"); if (!baz_obj) goto baz_error; return 0; baz_error: destroy_foo_obj(bar_obj); bar_error: destroy_foo_obj(foo_obj); foo_error: return -EINVAL; } static void __exit example_exit(void) { destroy_foo_obj(baz_obj); destroy_foo_obj(bar_obj); destroy_foo_obj(foo_obj); kset_unregister(example_kset); } module_init(example_init); module_exit(example_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Greg Kroah-Hartman <greg@kroah.com>");
gpl-2.0
zhaoleidd/btrfs
fs/minix/itree_common.c
14550
7854
/* Generic part */ typedef struct { block_t *p; block_t key; struct buffer_head *bh; } Indirect; static DEFINE_RWLOCK(pointers_lock); static inline void add_chain(Indirect *p, struct buffer_head *bh, block_t *v) { p->key = *(p->p = v); p->bh = bh; } static inline int verify_chain(Indirect *from, Indirect *to) { while (from <= to && from->key == *from->p) from++; return (from > to); } static inline block_t *block_end(struct buffer_head *bh) { return (block_t *)((char*)bh->b_data + bh->b_size); } static inline Indirect *get_branch(struct inode *inode, int depth, int *offsets, Indirect chain[DEPTH], int *err) { struct super_block *sb = inode->i_sb; Indirect *p = chain; struct buffer_head *bh; *err = 0; /* i_data is not going away, no lock needed */ add_chain (chain, NULL, i_data(inode) + *offsets); if (!p->key) goto no_block; while (--depth) { bh = sb_bread(sb, block_to_cpu(p->key)); if (!bh) goto failure; read_lock(&pointers_lock); if (!verify_chain(chain, p)) goto changed; add_chain(++p, bh, (block_t *)bh->b_data + *++offsets); read_unlock(&pointers_lock); if (!p->key) goto no_block; } return NULL; changed: read_unlock(&pointers_lock); brelse(bh); *err = -EAGAIN; goto no_block; failure: *err = -EIO; no_block: return p; } static int alloc_branch(struct inode *inode, int num, int *offsets, Indirect *branch) { int n = 0; int i; int parent = minix_new_block(inode); branch[0].key = cpu_to_block(parent); if (parent) for (n = 1; n < num; n++) { struct buffer_head *bh; /* Allocate the next block */ int nr = minix_new_block(inode); if (!nr) break; branch[n].key = cpu_to_block(nr); bh = sb_getblk(inode->i_sb, parent); lock_buffer(bh); memset(bh->b_data, 0, bh->b_size); branch[n].bh = bh; branch[n].p = (block_t*) bh->b_data + offsets[n]; *branch[n].p = branch[n].key; set_buffer_uptodate(bh); unlock_buffer(bh); mark_buffer_dirty_inode(bh, inode); parent = nr; } if (n == num) return 0; /* Allocation failed, free what we already allocated */ for (i = 1; i < n; i++) bforget(branch[i].bh); for (i = 0; i < n; i++) minix_free_block(inode, block_to_cpu(branch[i].key)); return -ENOSPC; } static inline int splice_branch(struct inode *inode, Indirect chain[DEPTH], Indirect *where, int num) { int i; write_lock(&pointers_lock); /* Verify that place we are splicing to is still there and vacant */ if (!verify_chain(chain, where-1) || *where->p) goto changed; *where->p = where->key; write_unlock(&pointers_lock); /* We are done with atomic stuff, now do the rest of housekeeping */ inode->i_ctime = CURRENT_TIME_SEC; /* had we spliced it onto indirect block? */ if (where->bh) mark_buffer_dirty_inode(where->bh, inode); mark_inode_dirty(inode); return 0; changed: write_unlock(&pointers_lock); for (i = 1; i < num; i++) bforget(where[i].bh); for (i = 0; i < num; i++) minix_free_block(inode, block_to_cpu(where[i].key)); return -EAGAIN; } static inline int get_block(struct inode * inode, sector_t block, struct buffer_head *bh, int create) { int err = -EIO; int offsets[DEPTH]; Indirect chain[DEPTH]; Indirect *partial; int left; int depth = block_to_path(inode, block, offsets); if (depth == 0) goto out; reread: partial = get_branch(inode, depth, offsets, chain, &err); /* Simplest case - block found, no allocation needed */ if (!partial) { got_it: map_bh(bh, inode->i_sb, block_to_cpu(chain[depth-1].key)); /* Clean up and exit */ partial = chain+depth-1; /* the whole chain */ goto cleanup; } /* Next simple case - plain lookup or failed read of indirect block */ if (!create || err == -EIO) { cleanup: while (partial > chain) { brelse(partial->bh); partial--; } out: return err; } /* * Indirect block might be removed by truncate while we were * reading it. Handling of that case (forget what we've got and * reread) is taken out of the main path. */ if (err == -EAGAIN) goto changed; left = (chain + depth) - partial; err = alloc_branch(inode, left, offsets+(partial-chain), partial); if (err) goto cleanup; if (splice_branch(inode, chain, partial, left) < 0) goto changed; set_buffer_new(bh); goto got_it; changed: while (partial > chain) { brelse(partial->bh); partial--; } goto reread; } static inline int all_zeroes(block_t *p, block_t *q) { while (p < q) if (*p++) return 0; return 1; } static Indirect *find_shared(struct inode *inode, int depth, int offsets[DEPTH], Indirect chain[DEPTH], block_t *top) { Indirect *partial, *p; int k, err; *top = 0; for (k = depth; k > 1 && !offsets[k-1]; k--) ; partial = get_branch(inode, k, offsets, chain, &err); write_lock(&pointers_lock); if (!partial) partial = chain + k-1; if (!partial->key && *partial->p) { write_unlock(&pointers_lock); goto no_top; } for (p=partial;p>chain && all_zeroes((block_t*)p->bh->b_data,p->p);p--) ; if (p == chain + k - 1 && p > chain) { p->p--; } else { *top = *p->p; *p->p = 0; } write_unlock(&pointers_lock); while(partial > p) { brelse(partial->bh); partial--; } no_top: return partial; } static inline void free_data(struct inode *inode, block_t *p, block_t *q) { unsigned long nr; for ( ; p < q ; p++) { nr = block_to_cpu(*p); if (nr) { *p = 0; minix_free_block(inode, nr); } } } static void free_branches(struct inode *inode, block_t *p, block_t *q, int depth) { struct buffer_head * bh; unsigned long nr; if (depth--) { for ( ; p < q ; p++) { nr = block_to_cpu(*p); if (!nr) continue; *p = 0; bh = sb_bread(inode->i_sb, nr); if (!bh) continue; free_branches(inode, (block_t*)bh->b_data, block_end(bh), depth); bforget(bh); minix_free_block(inode, nr); mark_inode_dirty(inode); } } else free_data(inode, p, q); } static inline void truncate (struct inode * inode) { struct super_block *sb = inode->i_sb; block_t *idata = i_data(inode); int offsets[DEPTH]; Indirect chain[DEPTH]; Indirect *partial; block_t nr = 0; int n; int first_whole; long iblock; iblock = (inode->i_size + sb->s_blocksize -1) >> sb->s_blocksize_bits; block_truncate_page(inode->i_mapping, inode->i_size, get_block); n = block_to_path(inode, iblock, offsets); if (!n) return; if (n == 1) { free_data(inode, idata+offsets[0], idata + DIRECT); first_whole = 0; goto do_indirects; } first_whole = offsets[0] + 1 - DIRECT; partial = find_shared(inode, n, offsets, chain, &nr); if (nr) { if (partial == chain) mark_inode_dirty(inode); else mark_buffer_dirty_inode(partial->bh, inode); free_branches(inode, &nr, &nr+1, (chain+n-1) - partial); } /* Clear the ends of indirect blocks on the shared branch */ while (partial > chain) { free_branches(inode, partial->p + 1, block_end(partial->bh), (chain+n-1) - partial); mark_buffer_dirty_inode(partial->bh, inode); brelse (partial->bh); partial--; } do_indirects: /* Kill the remaining (whole) subtrees */ while (first_whole < DEPTH-1) { nr = idata[DIRECT+first_whole]; if (nr) { idata[DIRECT+first_whole] = 0; mark_inode_dirty(inode); free_branches(inode, &nr, &nr+1, first_whole+1); } first_whole++; } inode->i_mtime = inode->i_ctime = CURRENT_TIME_SEC; mark_inode_dirty(inode); } static inline unsigned nblocks(loff_t size, struct super_block *sb) { int k = sb->s_blocksize_bits - 10; unsigned blocks, res, direct = DIRECT, i = DEPTH; blocks = (size + sb->s_blocksize - 1) >> (BLOCK_SIZE_BITS + k); res = blocks; while (--i && blocks > direct) { blocks -= direct; blocks += sb->s_blocksize/sizeof(block_t) - 1; blocks /= sb->s_blocksize/sizeof(block_t); res += blocks; direct = 1; } return res; }
gpl-2.0
jledet/linux
arch/blackfin/mach-bf537/boards/cm_bf537e.c
1751
20384
/* * Copyright 2004-2009 Analog Devices Inc. * 2008-2009 Bluetechnix * 2005 National ICT Australia (NICTA) * Aidan Williams <aidan@nicta.com.au> * * Licensed under the GPL-2 or later. */ #include <linux/device.h> #include <linux/export.h> #include <linux/etherdevice.h> #include <linux/platform_device.h> #include <linux/mtd/mtd.h> #include <linux/mtd/partitions.h> #include <linux/mtd/physmap.h> #include <linux/spi/spi.h> #include <linux/spi/flash.h> #if IS_ENABLED(CONFIG_USB_ISP1362_HCD) #include <linux/usb/isp1362.h> #endif #include <linux/ata_platform.h> #include <linux/irq.h> #include <linux/gpio.h> #include <asm/dma.h> #include <asm/bfin5xx_spi.h> #include <asm/portmux.h> #include <asm/dpmc.h> #include <asm/bfin_sport.h> /* * Name the Board for the /proc/cpuinfo */ const char bfin_board_name[] = "Bluetechnix CM BF537E"; #if IS_ENABLED(CONFIG_SPI_BFIN5XX) /* all SPI peripherals info goes here */ #if IS_ENABLED(CONFIG_MTD_M25P80) static struct mtd_partition bfin_spi_flash_partitions[] = { { .name = "bootloader(spi)", .size = 0x00020000, .offset = 0, .mask_flags = MTD_CAP_ROM }, { .name = "linux kernel(spi)", .size = 0xe0000, .offset = 0x20000 }, { .name = "file system(spi)", .size = 0x700000, .offset = 0x00100000, } }; static struct flash_platform_data bfin_spi_flash_data = { .name = "m25p80", .parts = bfin_spi_flash_partitions, .nr_parts = ARRAY_SIZE(bfin_spi_flash_partitions), .type = "m25p64", }; /* SPI flash chip (m25p64) */ static struct bfin5xx_spi_chip spi_flash_chip_info = { .enable_dma = 0, /* use dma transfer with this chip*/ }; #endif #if IS_ENABLED(CONFIG_MMC_SPI) static struct bfin5xx_spi_chip mmc_spi_chip_info = { .enable_dma = 0, }; #endif static struct spi_board_info bfin_spi_board_info[] __initdata = { #if IS_ENABLED(CONFIG_MTD_M25P80) { /* the modalias must be the same as spi device driver name */ .modalias = "m25p80", /* Name of spi_driver for this device */ .max_speed_hz = 25000000, /* max spi clock (SCK) speed in HZ */ .bus_num = 0, /* Framework bus number */ .chip_select = 1, /* Framework chip select. On STAMP537 it is SPISSEL1*/ .platform_data = &bfin_spi_flash_data, .controller_data = &spi_flash_chip_info, .mode = SPI_MODE_3, }, #endif #if IS_ENABLED(CONFIG_SND_BF5XX_SOC_AD183X) { .modalias = "ad183x", .max_speed_hz = 3125000, /* max spi clock (SCK) speed in HZ */ .bus_num = 0, .chip_select = 4, }, #endif #if IS_ENABLED(CONFIG_MMC_SPI) { .modalias = "mmc_spi", .max_speed_hz = 20000000, /* max spi clock (SCK) speed in HZ */ .bus_num = 0, .chip_select = 1, .controller_data = &mmc_spi_chip_info, .mode = SPI_MODE_3, }, #endif }; /* SPI (0) */ static struct resource bfin_spi0_resource[] = { [0] = { .start = SPI0_REGBASE, .end = SPI0_REGBASE + 0xFF, .flags = IORESOURCE_MEM, }, [1] = { .start = CH_SPI, .end = CH_SPI, .flags = IORESOURCE_DMA, }, [2] = { .start = IRQ_SPI, .end = IRQ_SPI, .flags = IORESOURCE_IRQ, }, }; /* SPI controller data */ static struct bfin5xx_spi_master bfin_spi0_info = { .num_chipselect = 8, .enable_dma = 1, /* master has the ability to do dma transfer */ .pin_req = {P_SPI0_SCK, P_SPI0_MISO, P_SPI0_MOSI, 0}, }; static struct platform_device bfin_spi0_device = { .name = "bfin-spi", .id = 0, /* Bus number */ .num_resources = ARRAY_SIZE(bfin_spi0_resource), .resource = bfin_spi0_resource, .dev = { .platform_data = &bfin_spi0_info, /* Passed to driver */ }, }; #endif /* spi master and devices */ #if IS_ENABLED(CONFIG_SPI_BFIN_SPORT) /* SPORT SPI controller data */ static struct bfin5xx_spi_master bfin_sport_spi0_info = { .num_chipselect = MAX_BLACKFIN_GPIOS, .enable_dma = 0, /* master don't support DMA */ .pin_req = {P_SPORT0_DTPRI, P_SPORT0_TSCLK, P_SPORT0_DRPRI, P_SPORT0_RSCLK, P_SPORT0_TFS, P_SPORT0_RFS, 0}, }; static struct resource bfin_sport_spi0_resource[] = { [0] = { .start = SPORT0_TCR1, .end = SPORT0_TCR1 + 0xFF, .flags = IORESOURCE_MEM, }, [1] = { .start = IRQ_SPORT0_ERROR, .end = IRQ_SPORT0_ERROR, .flags = IORESOURCE_IRQ, }, }; static struct platform_device bfin_sport_spi0_device = { .name = "bfin-sport-spi", .id = 1, /* Bus number */ .num_resources = ARRAY_SIZE(bfin_sport_spi0_resource), .resource = bfin_sport_spi0_resource, .dev = { .platform_data = &bfin_sport_spi0_info, /* Passed to driver */ }, }; static struct bfin5xx_spi_master bfin_sport_spi1_info = { .num_chipselect = MAX_BLACKFIN_GPIOS, .enable_dma = 0, /* master don't support DMA */ .pin_req = {P_SPORT1_DTPRI, P_SPORT1_TSCLK, P_SPORT1_DRPRI, P_SPORT1_RSCLK, P_SPORT1_TFS, P_SPORT1_RFS, 0}, }; static struct resource bfin_sport_spi1_resource[] = { [0] = { .start = SPORT1_TCR1, .end = SPORT1_TCR1 + 0xFF, .flags = IORESOURCE_MEM, }, [1] = { .start = IRQ_SPORT1_ERROR, .end = IRQ_SPORT1_ERROR, .flags = IORESOURCE_IRQ, }, }; static struct platform_device bfin_sport_spi1_device = { .name = "bfin-sport-spi", .id = 2, /* Bus number */ .num_resources = ARRAY_SIZE(bfin_sport_spi1_resource), .resource = bfin_sport_spi1_resource, .dev = { .platform_data = &bfin_sport_spi1_info, /* Passed to driver */ }, }; #endif /* sport spi master and devices */ #if IS_ENABLED(CONFIG_RTC_DRV_BFIN) static struct platform_device rtc_device = { .name = "rtc-bfin", .id = -1, }; #endif #if IS_ENABLED(CONFIG_FB_HITACHI_TX09) static struct platform_device hitachi_fb_device = { .name = "hitachi-tx09", }; #endif #if IS_ENABLED(CONFIG_SMC91X) #include <linux/smc91x.h> static struct smc91x_platdata smc91x_info = { .flags = SMC91X_USE_16BIT | SMC91X_NOWAIT, .leda = RPC_LED_100_10, .ledb = RPC_LED_TX_RX, }; static struct resource smc91x_resources[] = { { .start = 0x20200300, .end = 0x20200300 + 16, .flags = IORESOURCE_MEM, }, { .start = IRQ_PF14, .end = IRQ_PF14, .flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHLEVEL, }, }; static struct platform_device smc91x_device = { .name = "smc91x", .id = 0, .num_resources = ARRAY_SIZE(smc91x_resources), .resource = smc91x_resources, .dev = { .platform_data = &smc91x_info, }, }; #endif #if IS_ENABLED(CONFIG_USB_ISP1362_HCD) static struct resource isp1362_hcd_resources[] = { { .start = 0x20308000, .end = 0x20308000, .flags = IORESOURCE_MEM, }, { .start = 0x20308004, .end = 0x20308004, .flags = IORESOURCE_MEM, }, { .start = IRQ_PG15, .end = IRQ_PG15, .flags = IORESOURCE_IRQ | IORESOURCE_IRQ_LOWEDGE, }, }; static struct isp1362_platform_data isp1362_priv = { .sel15Kres = 1, .clknotstop = 0, .oc_enable = 0, .int_act_high = 0, .int_edge_triggered = 0, .remote_wakeup_connected = 0, .no_power_switching = 1, .power_switching_mode = 0, }; static struct platform_device isp1362_hcd_device = { .name = "isp1362-hcd", .id = 0, .dev = { .platform_data = &isp1362_priv, }, .num_resources = ARRAY_SIZE(isp1362_hcd_resources), .resource = isp1362_hcd_resources, }; #endif #if IS_ENABLED(CONFIG_USB_NET2272) static struct resource net2272_bfin_resources[] = { { .start = 0x20300000, .end = 0x20300000 + 0x100, .flags = IORESOURCE_MEM, }, { .start = IRQ_PG13, .end = IRQ_PG13, .flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHLEVEL, }, }; static struct platform_device net2272_bfin_device = { .name = "net2272", .id = -1, .num_resources = ARRAY_SIZE(net2272_bfin_resources), .resource = net2272_bfin_resources, }; #endif #if IS_ENABLED(CONFIG_MTD_GPIO_ADDR) static struct mtd_partition cm_partitions[] = { { .name = "bootloader(nor)", .size = 0x40000, .offset = 0, }, { .name = "linux kernel(nor)", .size = 0x100000, .offset = MTDPART_OFS_APPEND, }, { .name = "file system(nor)", .size = MTDPART_SIZ_FULL, .offset = MTDPART_OFS_APPEND, } }; static struct physmap_flash_data cm_flash_data = { .width = 2, .parts = cm_partitions, .nr_parts = ARRAY_SIZE(cm_partitions), }; static unsigned cm_flash_gpios[] = { GPIO_PF4 }; static struct resource cm_flash_resource[] = { { .name = "cfi_probe", .start = 0x20000000, .end = 0x201fffff, .flags = IORESOURCE_MEM, }, { .start = (unsigned long)cm_flash_gpios, .end = ARRAY_SIZE(cm_flash_gpios), .flags = IORESOURCE_IRQ, } }; static struct platform_device cm_flash_device = { .name = "gpio-addr-flash", .id = 0, .dev = { .platform_data = &cm_flash_data, }, .num_resources = ARRAY_SIZE(cm_flash_resource), .resource = cm_flash_resource, }; #endif #if IS_ENABLED(CONFIG_SERIAL_BFIN) #ifdef CONFIG_SERIAL_BFIN_UART0 static struct resource bfin_uart0_resources[] = { { .start = UART0_THR, .end = UART0_GCTL+2, .flags = IORESOURCE_MEM, }, { .start = IRQ_UART0_TX, .end = IRQ_UART0_TX, .flags = IORESOURCE_IRQ, }, { .start = IRQ_UART0_RX, .end = IRQ_UART0_RX, .flags = IORESOURCE_IRQ, }, { .start = IRQ_UART0_ERROR, .end = IRQ_UART0_ERROR, .flags = IORESOURCE_IRQ, }, { .start = CH_UART0_TX, .end = CH_UART0_TX, .flags = IORESOURCE_DMA, }, { .start = CH_UART0_RX, .end = CH_UART0_RX, .flags = IORESOURCE_DMA, }, #ifdef CONFIG_BFIN_UART0_CTSRTS { /* * Refer to arch/blackfin/mach-xxx/include/mach/gpio.h for the GPIO map. */ .start = -1, .end = -1, .flags = IORESOURCE_IO, }, { /* * Refer to arch/blackfin/mach-xxx/include/mach/gpio.h for the GPIO map. */ .start = -1, .end = -1, .flags = IORESOURCE_IO, }, #endif }; static unsigned short bfin_uart0_peripherals[] = { P_UART0_TX, P_UART0_RX, 0 }; static struct platform_device bfin_uart0_device = { .name = "bfin-uart", .id = 0, .num_resources = ARRAY_SIZE(bfin_uart0_resources), .resource = bfin_uart0_resources, .dev = { .platform_data = &bfin_uart0_peripherals, /* Passed to driver */ }, }; #endif #ifdef CONFIG_SERIAL_BFIN_UART1 static struct resource bfin_uart1_resources[] = { { .start = UART1_THR, .end = UART1_GCTL+2, .flags = IORESOURCE_MEM, }, { .start = IRQ_UART1_TX, .end = IRQ_UART1_TX, .flags = IORESOURCE_IRQ, }, { .start = IRQ_UART1_RX, .end = IRQ_UART1_RX, .flags = IORESOURCE_IRQ, }, { .start = IRQ_UART1_ERROR, .end = IRQ_UART1_ERROR, .flags = IORESOURCE_IRQ, }, { .start = CH_UART1_TX, .end = CH_UART1_TX, .flags = IORESOURCE_DMA, }, { .start = CH_UART1_RX, .end = CH_UART1_RX, .flags = IORESOURCE_DMA, }, #ifdef CONFIG_BFIN_UART1_CTSRTS { /* * Refer to arch/blackfin/mach-xxx/include/mach/gpio.h for the GPIO map. */ .start = -1, .end = -1, .flags = IORESOURCE_IO, }, { /* * Refer to arch/blackfin/mach-xxx/include/mach/gpio.h for the GPIO map. */ .start = -1, .end = -1, .flags = IORESOURCE_IO, }, #endif }; static unsigned short bfin_uart1_peripherals[] = { P_UART1_TX, P_UART1_RX, 0 }; static struct platform_device bfin_uart1_device = { .name = "bfin-uart", .id = 1, .num_resources = ARRAY_SIZE(bfin_uart1_resources), .resource = bfin_uart1_resources, .dev = { .platform_data = &bfin_uart1_peripherals, /* Passed to driver */ }, }; #endif #endif #if IS_ENABLED(CONFIG_BFIN_SIR) #ifdef CONFIG_BFIN_SIR0 static struct resource bfin_sir0_resources[] = { { .start = 0xFFC00400, .end = 0xFFC004FF, .flags = IORESOURCE_MEM, }, { .start = IRQ_UART0_RX, .end = IRQ_UART0_RX+1, .flags = IORESOURCE_IRQ, }, { .start = CH_UART0_RX, .end = CH_UART0_RX+1, .flags = IORESOURCE_DMA, }, }; static struct platform_device bfin_sir0_device = { .name = "bfin_sir", .id = 0, .num_resources = ARRAY_SIZE(bfin_sir0_resources), .resource = bfin_sir0_resources, }; #endif #ifdef CONFIG_BFIN_SIR1 static struct resource bfin_sir1_resources[] = { { .start = 0xFFC02000, .end = 0xFFC020FF, .flags = IORESOURCE_MEM, }, { .start = IRQ_UART1_RX, .end = IRQ_UART1_RX+1, .flags = IORESOURCE_IRQ, }, { .start = CH_UART1_RX, .end = CH_UART1_RX+1, .flags = IORESOURCE_DMA, }, }; static struct platform_device bfin_sir1_device = { .name = "bfin_sir", .id = 1, .num_resources = ARRAY_SIZE(bfin_sir1_resources), .resource = bfin_sir1_resources, }; #endif #endif #if IS_ENABLED(CONFIG_I2C_BLACKFIN_TWI) static const u16 bfin_twi0_pins[] = {P_TWI0_SCL, P_TWI0_SDA, 0}; static struct resource bfin_twi0_resource[] = { [0] = { .start = TWI0_REGBASE, .end = TWI0_REGBASE, .flags = IORESOURCE_MEM, }, [1] = { .start = IRQ_TWI, .end = IRQ_TWI, .flags = IORESOURCE_IRQ, }, }; static struct platform_device i2c_bfin_twi_device = { .name = "i2c-bfin-twi", .id = 0, .num_resources = ARRAY_SIZE(bfin_twi0_resource), .resource = bfin_twi0_resource, .dev = { .platform_data = &bfin_twi0_pins, }, }; #endif #if IS_ENABLED(CONFIG_SERIAL_BFIN_SPORT) \ || IS_ENABLED(CONFIG_BFIN_SPORT) unsigned short bfin_sport0_peripherals[] = { P_SPORT0_TFS, P_SPORT0_DTPRI, P_SPORT0_TSCLK, P_SPORT0_RFS, P_SPORT0_DRPRI, P_SPORT0_RSCLK, P_SPORT0_DRSEC, P_SPORT0_DTSEC, 0 }; #endif #if IS_ENABLED(CONFIG_SERIAL_BFIN_SPORT) #ifdef CONFIG_SERIAL_BFIN_SPORT0_UART static struct resource bfin_sport0_uart_resources[] = { { .start = SPORT0_TCR1, .end = SPORT0_MRCS3+4, .flags = IORESOURCE_MEM, }, { .start = IRQ_SPORT0_RX, .end = IRQ_SPORT0_RX+1, .flags = IORESOURCE_IRQ, }, { .start = IRQ_SPORT0_ERROR, .end = IRQ_SPORT0_ERROR, .flags = IORESOURCE_IRQ, }, }; static struct platform_device bfin_sport0_uart_device = { .name = "bfin-sport-uart", .id = 0, .num_resources = ARRAY_SIZE(bfin_sport0_uart_resources), .resource = bfin_sport0_uart_resources, .dev = { .platform_data = &bfin_sport0_peripherals, /* Passed to driver */ }, }; #endif #ifdef CONFIG_SERIAL_BFIN_SPORT1_UART static struct resource bfin_sport1_uart_resources[] = { { .start = SPORT1_TCR1, .end = SPORT1_MRCS3+4, .flags = IORESOURCE_MEM, }, { .start = IRQ_SPORT1_RX, .end = IRQ_SPORT1_RX+1, .flags = IORESOURCE_IRQ, }, { .start = IRQ_SPORT1_ERROR, .end = IRQ_SPORT1_ERROR, .flags = IORESOURCE_IRQ, }, }; static unsigned short bfin_sport1_peripherals[] = { P_SPORT1_TFS, P_SPORT1_DTPRI, P_SPORT1_TSCLK, P_SPORT1_RFS, P_SPORT1_DRPRI, P_SPORT1_RSCLK, 0 }; static struct platform_device bfin_sport1_uart_device = { .name = "bfin-sport-uart", .id = 1, .num_resources = ARRAY_SIZE(bfin_sport1_uart_resources), .resource = bfin_sport1_uart_resources, .dev = { .platform_data = &bfin_sport1_peripherals, /* Passed to driver */ }, }; #endif #endif #if IS_ENABLED(CONFIG_BFIN_SPORT) static struct resource bfin_sport0_resources[] = { { .start = SPORT0_TCR1, .end = SPORT0_MRCS3+4, .flags = IORESOURCE_MEM, }, { .start = IRQ_SPORT0_RX, .end = IRQ_SPORT0_RX+1, .flags = IORESOURCE_IRQ, }, { .start = IRQ_SPORT0_TX, .end = IRQ_SPORT0_TX+1, .flags = IORESOURCE_IRQ, }, { .start = IRQ_SPORT0_ERROR, .end = IRQ_SPORT0_ERROR, .flags = IORESOURCE_IRQ, }, { .start = CH_SPORT0_TX, .end = CH_SPORT0_TX, .flags = IORESOURCE_DMA, }, { .start = CH_SPORT0_RX, .end = CH_SPORT0_RX, .flags = IORESOURCE_DMA, }, }; static struct platform_device bfin_sport0_device = { .name = "bfin_sport_raw", .id = 0, .num_resources = ARRAY_SIZE(bfin_sport0_resources), .resource = bfin_sport0_resources, .dev = { .platform_data = &bfin_sport0_peripherals, /* Passed to driver */ }, }; #endif #if IS_ENABLED(CONFIG_BFIN_MAC) #include <linux/bfin_mac.h> static const unsigned short bfin_mac_peripherals[] = P_MII0; static struct bfin_phydev_platform_data bfin_phydev_data[] = { { .addr = 1, .irq = IRQ_MAC_PHYINT, }, }; static struct bfin_mii_bus_platform_data bfin_mii_bus_data = { .phydev_number = 1, .phydev_data = bfin_phydev_data, .phy_mode = PHY_INTERFACE_MODE_MII, .mac_peripherals = bfin_mac_peripherals, }; static struct platform_device bfin_mii_bus = { .name = "bfin_mii_bus", .dev = { .platform_data = &bfin_mii_bus_data, } }; static struct platform_device bfin_mac_device = { .name = "bfin_mac", .dev = { .platform_data = &bfin_mii_bus, } }; #endif #if IS_ENABLED(CONFIG_PATA_PLATFORM) #define PATA_INT IRQ_PF14 static struct pata_platform_info bfin_pata_platform_data = { .ioport_shift = 2, }; static struct resource bfin_pata_resources[] = { { .start = 0x2030C000, .end = 0x2030C01F, .flags = IORESOURCE_MEM, }, { .start = 0x2030D018, .end = 0x2030D01B, .flags = IORESOURCE_MEM, }, { .start = PATA_INT, .end = PATA_INT, .flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHLEVEL, }, }; static struct platform_device bfin_pata_device = { .name = "pata_platform", .id = -1, .num_resources = ARRAY_SIZE(bfin_pata_resources), .resource = bfin_pata_resources, .dev = { .platform_data = &bfin_pata_platform_data, } }; #endif static const unsigned int cclk_vlev_datasheet[] = { VRPAIR(VLEV_085, 250000000), VRPAIR(VLEV_090, 376000000), VRPAIR(VLEV_095, 426000000), VRPAIR(VLEV_100, 426000000), VRPAIR(VLEV_105, 476000000), VRPAIR(VLEV_110, 476000000), VRPAIR(VLEV_115, 476000000), VRPAIR(VLEV_120, 500000000), VRPAIR(VLEV_125, 533000000), VRPAIR(VLEV_130, 600000000), }; static struct bfin_dpmc_platform_data bfin_dmpc_vreg_data = { .tuple_tab = cclk_vlev_datasheet, .tabsize = ARRAY_SIZE(cclk_vlev_datasheet), .vr_settling_time = 25 /* us */, }; static struct platform_device bfin_dpmc = { .name = "bfin dpmc", .dev = { .platform_data = &bfin_dmpc_vreg_data, }, }; static struct platform_device *cm_bf537e_devices[] __initdata = { &bfin_dpmc, #if IS_ENABLED(CONFIG_BFIN_SPORT) &bfin_sport0_device, #endif #if IS_ENABLED(CONFIG_FB_HITACHI_TX09) &hitachi_fb_device, #endif #if IS_ENABLED(CONFIG_RTC_DRV_BFIN) &rtc_device, #endif #if IS_ENABLED(CONFIG_SERIAL_BFIN) #ifdef CONFIG_SERIAL_BFIN_UART0 &bfin_uart0_device, #endif #ifdef CONFIG_SERIAL_BFIN_UART1 &bfin_uart1_device, #endif #endif #if IS_ENABLED(CONFIG_BFIN_SIR) #ifdef CONFIG_BFIN_SIR0 &bfin_sir0_device, #endif #ifdef CONFIG_BFIN_SIR1 &bfin_sir1_device, #endif #endif #if IS_ENABLED(CONFIG_I2C_BLACKFIN_TWI) &i2c_bfin_twi_device, #endif #if IS_ENABLED(CONFIG_SERIAL_BFIN_SPORT) #ifdef CONFIG_SERIAL_BFIN_SPORT0_UART &bfin_sport0_uart_device, #endif #ifdef CONFIG_SERIAL_BFIN_SPORT1_UART &bfin_sport1_uart_device, #endif #endif #if IS_ENABLED(CONFIG_USB_ISP1362_HCD) &isp1362_hcd_device, #endif #if IS_ENABLED(CONFIG_SMC91X) &smc91x_device, #endif #if IS_ENABLED(CONFIG_BFIN_MAC) &bfin_mii_bus, &bfin_mac_device, #endif #if IS_ENABLED(CONFIG_USB_NET2272) &net2272_bfin_device, #endif #if IS_ENABLED(CONFIG_SPI_BFIN5XX) &bfin_spi0_device, #endif #if IS_ENABLED(CONFIG_SPI_BFIN_SPORT) &bfin_sport_spi0_device, &bfin_sport_spi1_device, #endif #if IS_ENABLED(CONFIG_PATA_PLATFORM) &bfin_pata_device, #endif #if IS_ENABLED(CONFIG_MTD_GPIO_ADDR) &cm_flash_device, #endif }; static int __init net2272_init(void) { #if IS_ENABLED(CONFIG_USB_NET2272) int ret; ret = gpio_request(GPIO_PG14, "net2272"); if (ret) return ret; /* Reset USB Chip, PG14 */ gpio_direction_output(GPIO_PG14, 0); mdelay(2); gpio_set_value(GPIO_PG14, 1); #endif return 0; } static int __init cm_bf537e_init(void) { printk(KERN_INFO "%s(): registering device resources\n", __func__); platform_add_devices(cm_bf537e_devices, ARRAY_SIZE(cm_bf537e_devices)); #if IS_ENABLED(CONFIG_SPI_BFIN5XX) spi_register_board_info(bfin_spi_board_info, ARRAY_SIZE(bfin_spi_board_info)); #endif #if IS_ENABLED(CONFIG_PATA_PLATFORM) irq_set_status_flags(PATA_INT, IRQ_NOAUTOEN); #endif if (net2272_init()) pr_warning("unable to configure net2272; it probably won't work\n"); return 0; } arch_initcall(cm_bf537e_init); static struct platform_device *cm_bf537e_early_devices[] __initdata = { #if defined(CONFIG_SERIAL_BFIN_CONSOLE) || defined(CONFIG_EARLY_PRINTK) #ifdef CONFIG_SERIAL_BFIN_UART0 &bfin_uart0_device, #endif #ifdef CONFIG_SERIAL_BFIN_UART1 &bfin_uart1_device, #endif #endif #if defined(CONFIG_SERIAL_BFIN_SPORT_CONSOLE) #ifdef CONFIG_SERIAL_BFIN_SPORT0_UART &bfin_sport0_uart_device, #endif #ifdef CONFIG_SERIAL_BFIN_SPORT1_UART &bfin_sport1_uart_device, #endif #endif }; void __init native_machine_early_platform_add_devices(void) { printk(KERN_INFO "register early platform devices\n"); early_platform_add_devices(cm_bf537e_early_devices, ARRAY_SIZE(cm_bf537e_early_devices)); } int bfin_get_ether_addr(char *addr) { return 1; } EXPORT_SYMBOL(bfin_get_ether_addr);
gpl-2.0
webore/lenovo
drivers/platform/x86/eeepc-laptop.c
2775
37852
/* * eeepc-laptop.c - Asus Eee PC extras * * Based on asus_acpi.c as patched for the Eee PC by Asus: * ftp://ftp.asus.com/pub/ASUS/EeePC/701/ASUS_ACPI_071126.rar * Based on eee.c from eeepc-linux * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/types.h> #include <linux/platform_device.h> #include <linux/backlight.h> #include <linux/fb.h> #include <linux/hwmon.h> #include <linux/hwmon-sysfs.h> #include <linux/slab.h> #include <acpi/acpi_drivers.h> #include <acpi/acpi_bus.h> #include <linux/uaccess.h> #include <linux/input.h> #include <linux/input/sparse-keymap.h> #include <linux/rfkill.h> #include <linux/pci.h> #include <linux/pci_hotplug.h> #include <linux/leds.h> #include <linux/dmi.h> #define EEEPC_LAPTOP_VERSION "0.1" #define EEEPC_LAPTOP_NAME "Eee PC Hotkey Driver" #define EEEPC_LAPTOP_FILE "eeepc" #define EEEPC_ACPI_CLASS "hotkey" #define EEEPC_ACPI_DEVICE_NAME "Hotkey" #define EEEPC_ACPI_HID "ASUS010" MODULE_AUTHOR("Corentin Chary, Eric Cooper"); MODULE_DESCRIPTION(EEEPC_LAPTOP_NAME); MODULE_LICENSE("GPL"); static bool hotplug_disabled; module_param(hotplug_disabled, bool, 0444); MODULE_PARM_DESC(hotplug_disabled, "Disable hotplug for wireless device. " "If your laptop need that, please report to " "acpi4asus-user@lists.sourceforge.net."); /* * Definitions for Asus EeePC */ #define NOTIFY_BRN_MIN 0x20 #define NOTIFY_BRN_MAX 0x2f enum { DISABLE_ASL_WLAN = 0x0001, DISABLE_ASL_BLUETOOTH = 0x0002, DISABLE_ASL_IRDA = 0x0004, DISABLE_ASL_CAMERA = 0x0008, DISABLE_ASL_TV = 0x0010, DISABLE_ASL_GPS = 0x0020, DISABLE_ASL_DISPLAYSWITCH = 0x0040, DISABLE_ASL_MODEM = 0x0080, DISABLE_ASL_CARDREADER = 0x0100, DISABLE_ASL_3G = 0x0200, DISABLE_ASL_WIMAX = 0x0400, DISABLE_ASL_HWCF = 0x0800 }; enum { CM_ASL_WLAN = 0, CM_ASL_BLUETOOTH, CM_ASL_IRDA, CM_ASL_1394, CM_ASL_CAMERA, CM_ASL_TV, CM_ASL_GPS, CM_ASL_DVDROM, CM_ASL_DISPLAYSWITCH, CM_ASL_PANELBRIGHT, CM_ASL_BIOSFLASH, CM_ASL_ACPIFLASH, CM_ASL_CPUFV, CM_ASL_CPUTEMPERATURE, CM_ASL_FANCPU, CM_ASL_FANCHASSIS, CM_ASL_USBPORT1, CM_ASL_USBPORT2, CM_ASL_USBPORT3, CM_ASL_MODEM, CM_ASL_CARDREADER, CM_ASL_3G, CM_ASL_WIMAX, CM_ASL_HWCF, CM_ASL_LID, CM_ASL_TYPE, CM_ASL_PANELPOWER, /*P901*/ CM_ASL_TPD }; static const char *cm_getv[] = { "WLDG", "BTHG", NULL, NULL, "CAMG", NULL, NULL, NULL, NULL, "PBLG", NULL, NULL, "CFVG", NULL, NULL, NULL, "USBG", NULL, NULL, "MODG", "CRDG", "M3GG", "WIMG", "HWCF", "LIDG", "TYPE", "PBPG", "TPDG" }; static const char *cm_setv[] = { "WLDS", "BTHS", NULL, NULL, "CAMS", NULL, NULL, NULL, "SDSP", "PBLS", "HDPS", NULL, "CFVS", NULL, NULL, NULL, "USBG", NULL, NULL, "MODS", "CRDS", "M3GS", "WIMS", NULL, NULL, NULL, "PBPS", "TPDS" }; static const struct key_entry eeepc_keymap[] = { { KE_KEY, 0x10, { KEY_WLAN } }, { KE_KEY, 0x11, { KEY_WLAN } }, { KE_KEY, 0x12, { KEY_PROG1 } }, { KE_KEY, 0x13, { KEY_MUTE } }, { KE_KEY, 0x14, { KEY_VOLUMEDOWN } }, { KE_KEY, 0x15, { KEY_VOLUMEUP } }, { KE_KEY, 0x16, { KEY_DISPLAY_OFF } }, { KE_KEY, 0x1a, { KEY_COFFEE } }, { KE_KEY, 0x1b, { KEY_ZOOM } }, { KE_KEY, 0x1c, { KEY_PROG2 } }, { KE_KEY, 0x1d, { KEY_PROG3 } }, { KE_KEY, NOTIFY_BRN_MIN, { KEY_BRIGHTNESSDOWN } }, { KE_KEY, NOTIFY_BRN_MAX, { KEY_BRIGHTNESSUP } }, { KE_KEY, 0x30, { KEY_SWITCHVIDEOMODE } }, { KE_KEY, 0x31, { KEY_SWITCHVIDEOMODE } }, { KE_KEY, 0x32, { KEY_SWITCHVIDEOMODE } }, { KE_KEY, 0x37, { KEY_F13 } }, /* Disable Touchpad */ { KE_KEY, 0x38, { KEY_F14 } }, { KE_END, 0 }, }; /* * This is the main structure, we can use it to store useful information */ struct eeepc_laptop { acpi_handle handle; /* the handle of the acpi device */ u32 cm_supported; /* the control methods supported by this BIOS */ bool cpufv_disabled; bool hotplug_disabled; u16 event_count[128]; /* count for each event */ struct platform_device *platform_device; struct acpi_device *device; /* the device we are in */ struct device *hwmon_device; struct backlight_device *backlight_device; struct input_dev *inputdev; struct rfkill *wlan_rfkill; struct rfkill *bluetooth_rfkill; struct rfkill *wwan3g_rfkill; struct rfkill *wimax_rfkill; struct hotplug_slot *hotplug_slot; struct mutex hotplug_lock; struct led_classdev tpd_led; int tpd_led_wk; struct workqueue_struct *led_workqueue; struct work_struct tpd_led_work; }; /* * ACPI Helpers */ static int write_acpi_int(acpi_handle handle, const char *method, int val) { struct acpi_object_list params; union acpi_object in_obj; acpi_status status; params.count = 1; params.pointer = &in_obj; in_obj.type = ACPI_TYPE_INTEGER; in_obj.integer.value = val; status = acpi_evaluate_object(handle, (char *)method, &params, NULL); return (status == AE_OK ? 0 : -1); } static int read_acpi_int(acpi_handle handle, const char *method, int *val) { acpi_status status; unsigned long long result; status = acpi_evaluate_integer(handle, (char *)method, NULL, &result); if (ACPI_FAILURE(status)) { *val = -1; return -1; } else { *val = result; return 0; } } static int set_acpi(struct eeepc_laptop *eeepc, int cm, int value) { const char *method = cm_setv[cm]; if (method == NULL) return -ENODEV; if ((eeepc->cm_supported & (0x1 << cm)) == 0) return -ENODEV; if (write_acpi_int(eeepc->handle, method, value)) pr_warn("Error writing %s\n", method); return 0; } static int get_acpi(struct eeepc_laptop *eeepc, int cm) { const char *method = cm_getv[cm]; int value; if (method == NULL) return -ENODEV; if ((eeepc->cm_supported & (0x1 << cm)) == 0) return -ENODEV; if (read_acpi_int(eeepc->handle, method, &value)) pr_warn("Error reading %s\n", method); return value; } static int acpi_setter_handle(struct eeepc_laptop *eeepc, int cm, acpi_handle *handle) { const char *method = cm_setv[cm]; acpi_status status; if (method == NULL) return -ENODEV; if ((eeepc->cm_supported & (0x1 << cm)) == 0) return -ENODEV; status = acpi_get_handle(eeepc->handle, (char *)method, handle); if (status != AE_OK) { pr_warn("Error finding %s\n", method); return -ENODEV; } return 0; } /* * Sys helpers */ static int parse_arg(const char *buf, unsigned long count, int *val) { if (!count) return 0; if (sscanf(buf, "%i", val) != 1) return -EINVAL; return count; } static ssize_t store_sys_acpi(struct device *dev, int cm, const char *buf, size_t count) { struct eeepc_laptop *eeepc = dev_get_drvdata(dev); int rv, value; rv = parse_arg(buf, count, &value); if (rv > 0) value = set_acpi(eeepc, cm, value); if (value < 0) return -EIO; return rv; } static ssize_t show_sys_acpi(struct device *dev, int cm, char *buf) { struct eeepc_laptop *eeepc = dev_get_drvdata(dev); int value = get_acpi(eeepc, cm); if (value < 0) return -EIO; return sprintf(buf, "%d\n", value); } #define EEEPC_CREATE_DEVICE_ATTR(_name, _mode, _cm) \ static ssize_t show_##_name(struct device *dev, \ struct device_attribute *attr, \ char *buf) \ { \ return show_sys_acpi(dev, _cm, buf); \ } \ static ssize_t store_##_name(struct device *dev, \ struct device_attribute *attr, \ const char *buf, size_t count) \ { \ return store_sys_acpi(dev, _cm, buf, count); \ } \ static struct device_attribute dev_attr_##_name = { \ .attr = { \ .name = __stringify(_name), \ .mode = _mode }, \ .show = show_##_name, \ .store = store_##_name, \ } EEEPC_CREATE_DEVICE_ATTR(camera, 0644, CM_ASL_CAMERA); EEEPC_CREATE_DEVICE_ATTR(cardr, 0644, CM_ASL_CARDREADER); EEEPC_CREATE_DEVICE_ATTR(disp, 0200, CM_ASL_DISPLAYSWITCH); struct eeepc_cpufv { int num; int cur; }; static int get_cpufv(struct eeepc_laptop *eeepc, struct eeepc_cpufv *c) { c->cur = get_acpi(eeepc, CM_ASL_CPUFV); c->num = (c->cur >> 8) & 0xff; c->cur &= 0xff; if (c->cur < 0 || c->num <= 0 || c->num > 12) return -ENODEV; return 0; } static ssize_t show_available_cpufv(struct device *dev, struct device_attribute *attr, char *buf) { struct eeepc_laptop *eeepc = dev_get_drvdata(dev); struct eeepc_cpufv c; int i; ssize_t len = 0; if (get_cpufv(eeepc, &c)) return -ENODEV; for (i = 0; i < c.num; i++) len += sprintf(buf + len, "%d ", i); len += sprintf(buf + len, "\n"); return len; } static ssize_t show_cpufv(struct device *dev, struct device_attribute *attr, char *buf) { struct eeepc_laptop *eeepc = dev_get_drvdata(dev); struct eeepc_cpufv c; if (get_cpufv(eeepc, &c)) return -ENODEV; return sprintf(buf, "%#x\n", (c.num << 8) | c.cur); } static ssize_t store_cpufv(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct eeepc_laptop *eeepc = dev_get_drvdata(dev); struct eeepc_cpufv c; int rv, value; if (eeepc->cpufv_disabled) return -EPERM; if (get_cpufv(eeepc, &c)) return -ENODEV; rv = parse_arg(buf, count, &value); if (rv < 0) return rv; if (!rv || value < 0 || value >= c.num) return -EINVAL; set_acpi(eeepc, CM_ASL_CPUFV, value); return rv; } static ssize_t show_cpufv_disabled(struct device *dev, struct device_attribute *attr, char *buf) { struct eeepc_laptop *eeepc = dev_get_drvdata(dev); return sprintf(buf, "%d\n", eeepc->cpufv_disabled); } static ssize_t store_cpufv_disabled(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct eeepc_laptop *eeepc = dev_get_drvdata(dev); int rv, value; rv = parse_arg(buf, count, &value); if (rv < 0) return rv; switch (value) { case 0: if (eeepc->cpufv_disabled) pr_warn("cpufv enabled (not officially supported " "on this model)\n"); eeepc->cpufv_disabled = false; return rv; case 1: return -EPERM; default: return -EINVAL; } } static struct device_attribute dev_attr_cpufv = { .attr = { .name = "cpufv", .mode = 0644 }, .show = show_cpufv, .store = store_cpufv }; static struct device_attribute dev_attr_available_cpufv = { .attr = { .name = "available_cpufv", .mode = 0444 }, .show = show_available_cpufv }; static struct device_attribute dev_attr_cpufv_disabled = { .attr = { .name = "cpufv_disabled", .mode = 0644 }, .show = show_cpufv_disabled, .store = store_cpufv_disabled }; static struct attribute *platform_attributes[] = { &dev_attr_camera.attr, &dev_attr_cardr.attr, &dev_attr_disp.attr, &dev_attr_cpufv.attr, &dev_attr_available_cpufv.attr, &dev_attr_cpufv_disabled.attr, NULL }; static struct attribute_group platform_attribute_group = { .attrs = platform_attributes }; static int eeepc_platform_init(struct eeepc_laptop *eeepc) { int result; eeepc->platform_device = platform_device_alloc(EEEPC_LAPTOP_FILE, -1); if (!eeepc->platform_device) return -ENOMEM; platform_set_drvdata(eeepc->platform_device, eeepc); result = platform_device_add(eeepc->platform_device); if (result) goto fail_platform_device; result = sysfs_create_group(&eeepc->platform_device->dev.kobj, &platform_attribute_group); if (result) goto fail_sysfs; return 0; fail_sysfs: platform_device_del(eeepc->platform_device); fail_platform_device: platform_device_put(eeepc->platform_device); return result; } static void eeepc_platform_exit(struct eeepc_laptop *eeepc) { sysfs_remove_group(&eeepc->platform_device->dev.kobj, &platform_attribute_group); platform_device_unregister(eeepc->platform_device); } /* * LEDs */ /* * These functions actually update the LED's, and are called from a * workqueue. By doing this as separate work rather than when the LED * subsystem asks, we avoid messing with the Asus ACPI stuff during a * potentially bad time, such as a timer interrupt. */ static void tpd_led_update(struct work_struct *work) { struct eeepc_laptop *eeepc; eeepc = container_of(work, struct eeepc_laptop, tpd_led_work); set_acpi(eeepc, CM_ASL_TPD, eeepc->tpd_led_wk); } static void tpd_led_set(struct led_classdev *led_cdev, enum led_brightness value) { struct eeepc_laptop *eeepc; eeepc = container_of(led_cdev, struct eeepc_laptop, tpd_led); eeepc->tpd_led_wk = (value > 0) ? 1 : 0; queue_work(eeepc->led_workqueue, &eeepc->tpd_led_work); } static enum led_brightness tpd_led_get(struct led_classdev *led_cdev) { struct eeepc_laptop *eeepc; eeepc = container_of(led_cdev, struct eeepc_laptop, tpd_led); return get_acpi(eeepc, CM_ASL_TPD); } static int eeepc_led_init(struct eeepc_laptop *eeepc) { int rv; if (get_acpi(eeepc, CM_ASL_TPD) == -ENODEV) return 0; eeepc->led_workqueue = create_singlethread_workqueue("led_workqueue"); if (!eeepc->led_workqueue) return -ENOMEM; INIT_WORK(&eeepc->tpd_led_work, tpd_led_update); eeepc->tpd_led.name = "eeepc::touchpad"; eeepc->tpd_led.brightness_set = tpd_led_set; if (get_acpi(eeepc, CM_ASL_TPD) >= 0) /* if method is available */ eeepc->tpd_led.brightness_get = tpd_led_get; eeepc->tpd_led.max_brightness = 1; rv = led_classdev_register(&eeepc->platform_device->dev, &eeepc->tpd_led); if (rv) { destroy_workqueue(eeepc->led_workqueue); return rv; } return 0; } static void eeepc_led_exit(struct eeepc_laptop *eeepc) { if (eeepc->tpd_led.dev) led_classdev_unregister(&eeepc->tpd_led); if (eeepc->led_workqueue) destroy_workqueue(eeepc->led_workqueue); } /* * PCI hotplug (for wlan rfkill) */ static bool eeepc_wlan_rfkill_blocked(struct eeepc_laptop *eeepc) { if (get_acpi(eeepc, CM_ASL_WLAN) == 1) return false; return true; } static void eeepc_rfkill_hotplug(struct eeepc_laptop *eeepc, acpi_handle handle) { struct pci_dev *port; struct pci_dev *dev; struct pci_bus *bus; bool blocked = eeepc_wlan_rfkill_blocked(eeepc); bool absent; u32 l; if (eeepc->wlan_rfkill) rfkill_set_sw_state(eeepc->wlan_rfkill, blocked); mutex_lock(&eeepc->hotplug_lock); if (eeepc->hotplug_slot) { port = acpi_get_pci_dev(handle); if (!port) { pr_warning("Unable to find port\n"); goto out_unlock; } bus = port->subordinate; if (!bus) { pr_warn("Unable to find PCI bus 1?\n"); goto out_unlock; } if (pci_bus_read_config_dword(bus, 0, PCI_VENDOR_ID, &l)) { pr_err("Unable to read PCI config space?\n"); goto out_unlock; } absent = (l == 0xffffffff); if (blocked != absent) { pr_warn("BIOS says wireless lan is %s, " "but the pci device is %s\n", blocked ? "blocked" : "unblocked", absent ? "absent" : "present"); pr_warn("skipped wireless hotplug as probably " "inappropriate for this model\n"); goto out_unlock; } if (!blocked) { dev = pci_get_slot(bus, 0); if (dev) { /* Device already present */ pci_dev_put(dev); goto out_unlock; } dev = pci_scan_single_device(bus, 0); if (dev) { pci_bus_assign_resources(bus); if (pci_bus_add_device(dev)) pr_err("Unable to hotplug wifi\n"); } } else { dev = pci_get_slot(bus, 0); if (dev) { pci_remove_bus_device(dev); pci_dev_put(dev); } } } out_unlock: mutex_unlock(&eeepc->hotplug_lock); } static void eeepc_rfkill_hotplug_update(struct eeepc_laptop *eeepc, char *node) { acpi_status status = AE_OK; acpi_handle handle; status = acpi_get_handle(NULL, node, &handle); if (ACPI_SUCCESS(status)) eeepc_rfkill_hotplug(eeepc, handle); } static void eeepc_rfkill_notify(acpi_handle handle, u32 event, void *data) { struct eeepc_laptop *eeepc = data; if (event != ACPI_NOTIFY_BUS_CHECK) return; eeepc_rfkill_hotplug(eeepc, handle); } static int eeepc_register_rfkill_notifier(struct eeepc_laptop *eeepc, char *node) { acpi_status status; acpi_handle handle; status = acpi_get_handle(NULL, node, &handle); if (ACPI_SUCCESS(status)) { status = acpi_install_notify_handler(handle, ACPI_SYSTEM_NOTIFY, eeepc_rfkill_notify, eeepc); if (ACPI_FAILURE(status)) pr_warn("Failed to register notify on %s\n", node); /* * Refresh pci hotplug in case the rfkill state was * changed during setup. */ eeepc_rfkill_hotplug(eeepc, handle); } else return -ENODEV; return 0; } static void eeepc_unregister_rfkill_notifier(struct eeepc_laptop *eeepc, char *node) { acpi_status status = AE_OK; acpi_handle handle; status = acpi_get_handle(NULL, node, &handle); if (ACPI_SUCCESS(status)) { status = acpi_remove_notify_handler(handle, ACPI_SYSTEM_NOTIFY, eeepc_rfkill_notify); if (ACPI_FAILURE(status)) pr_err("Error removing rfkill notify handler %s\n", node); /* * Refresh pci hotplug in case the rfkill * state was changed after * eeepc_unregister_rfkill_notifier() */ eeepc_rfkill_hotplug(eeepc, handle); } } static int eeepc_get_adapter_status(struct hotplug_slot *hotplug_slot, u8 *value) { struct eeepc_laptop *eeepc = hotplug_slot->private; int val = get_acpi(eeepc, CM_ASL_WLAN); if (val == 1 || val == 0) *value = val; else return -EINVAL; return 0; } static void eeepc_cleanup_pci_hotplug(struct hotplug_slot *hotplug_slot) { kfree(hotplug_slot->info); kfree(hotplug_slot); } static struct hotplug_slot_ops eeepc_hotplug_slot_ops = { .owner = THIS_MODULE, .get_adapter_status = eeepc_get_adapter_status, .get_power_status = eeepc_get_adapter_status, }; static int eeepc_setup_pci_hotplug(struct eeepc_laptop *eeepc) { int ret = -ENOMEM; struct pci_bus *bus = pci_find_bus(0, 1); if (!bus) { pr_err("Unable to find wifi PCI bus\n"); return -ENODEV; } eeepc->hotplug_slot = kzalloc(sizeof(struct hotplug_slot), GFP_KERNEL); if (!eeepc->hotplug_slot) goto error_slot; eeepc->hotplug_slot->info = kzalloc(sizeof(struct hotplug_slot_info), GFP_KERNEL); if (!eeepc->hotplug_slot->info) goto error_info; eeepc->hotplug_slot->private = eeepc; eeepc->hotplug_slot->release = &eeepc_cleanup_pci_hotplug; eeepc->hotplug_slot->ops = &eeepc_hotplug_slot_ops; eeepc_get_adapter_status(eeepc->hotplug_slot, &eeepc->hotplug_slot->info->adapter_status); ret = pci_hp_register(eeepc->hotplug_slot, bus, 0, "eeepc-wifi"); if (ret) { pr_err("Unable to register hotplug slot - %d\n", ret); goto error_register; } return 0; error_register: kfree(eeepc->hotplug_slot->info); error_info: kfree(eeepc->hotplug_slot); eeepc->hotplug_slot = NULL; error_slot: return ret; } /* * Rfkill devices */ static int eeepc_rfkill_set(void *data, bool blocked) { acpi_handle handle = data; return write_acpi_int(handle, NULL, !blocked); } static const struct rfkill_ops eeepc_rfkill_ops = { .set_block = eeepc_rfkill_set, }; static int eeepc_new_rfkill(struct eeepc_laptop *eeepc, struct rfkill **rfkill, const char *name, enum rfkill_type type, int cm) { acpi_handle handle; int result; result = acpi_setter_handle(eeepc, cm, &handle); if (result < 0) return result; *rfkill = rfkill_alloc(name, &eeepc->platform_device->dev, type, &eeepc_rfkill_ops, handle); if (!*rfkill) return -EINVAL; rfkill_init_sw_state(*rfkill, get_acpi(eeepc, cm) != 1); result = rfkill_register(*rfkill); if (result) { rfkill_destroy(*rfkill); *rfkill = NULL; return result; } return 0; } static void eeepc_rfkill_exit(struct eeepc_laptop *eeepc) { eeepc_unregister_rfkill_notifier(eeepc, "\\_SB.PCI0.P0P5"); eeepc_unregister_rfkill_notifier(eeepc, "\\_SB.PCI0.P0P6"); eeepc_unregister_rfkill_notifier(eeepc, "\\_SB.PCI0.P0P7"); if (eeepc->wlan_rfkill) { rfkill_unregister(eeepc->wlan_rfkill); rfkill_destroy(eeepc->wlan_rfkill); eeepc->wlan_rfkill = NULL; } if (eeepc->hotplug_slot) pci_hp_deregister(eeepc->hotplug_slot); if (eeepc->bluetooth_rfkill) { rfkill_unregister(eeepc->bluetooth_rfkill); rfkill_destroy(eeepc->bluetooth_rfkill); eeepc->bluetooth_rfkill = NULL; } if (eeepc->wwan3g_rfkill) { rfkill_unregister(eeepc->wwan3g_rfkill); rfkill_destroy(eeepc->wwan3g_rfkill); eeepc->wwan3g_rfkill = NULL; } if (eeepc->wimax_rfkill) { rfkill_unregister(eeepc->wimax_rfkill); rfkill_destroy(eeepc->wimax_rfkill); eeepc->wimax_rfkill = NULL; } } static int eeepc_rfkill_init(struct eeepc_laptop *eeepc) { int result = 0; mutex_init(&eeepc->hotplug_lock); result = eeepc_new_rfkill(eeepc, &eeepc->wlan_rfkill, "eeepc-wlan", RFKILL_TYPE_WLAN, CM_ASL_WLAN); if (result && result != -ENODEV) goto exit; result = eeepc_new_rfkill(eeepc, &eeepc->bluetooth_rfkill, "eeepc-bluetooth", RFKILL_TYPE_BLUETOOTH, CM_ASL_BLUETOOTH); if (result && result != -ENODEV) goto exit; result = eeepc_new_rfkill(eeepc, &eeepc->wwan3g_rfkill, "eeepc-wwan3g", RFKILL_TYPE_WWAN, CM_ASL_3G); if (result && result != -ENODEV) goto exit; result = eeepc_new_rfkill(eeepc, &eeepc->wimax_rfkill, "eeepc-wimax", RFKILL_TYPE_WIMAX, CM_ASL_WIMAX); if (result && result != -ENODEV) goto exit; if (eeepc->hotplug_disabled) return 0; result = eeepc_setup_pci_hotplug(eeepc); /* * If we get -EBUSY then something else is handling the PCI hotplug - * don't fail in this case */ if (result == -EBUSY) result = 0; eeepc_register_rfkill_notifier(eeepc, "\\_SB.PCI0.P0P5"); eeepc_register_rfkill_notifier(eeepc, "\\_SB.PCI0.P0P6"); eeepc_register_rfkill_notifier(eeepc, "\\_SB.PCI0.P0P7"); exit: if (result && result != -ENODEV) eeepc_rfkill_exit(eeepc); return result; } /* * Platform driver - hibernate/resume callbacks */ static int eeepc_hotk_thaw(struct device *device) { struct eeepc_laptop *eeepc = dev_get_drvdata(device); if (eeepc->wlan_rfkill) { bool wlan; /* * Work around bios bug - acpi _PTS turns off the wireless led * during suspend. Normally it restores it on resume, but * we should kick it ourselves in case hibernation is aborted. */ wlan = get_acpi(eeepc, CM_ASL_WLAN); set_acpi(eeepc, CM_ASL_WLAN, wlan); } return 0; } static int eeepc_hotk_restore(struct device *device) { struct eeepc_laptop *eeepc = dev_get_drvdata(device); /* Refresh both wlan rfkill state and pci hotplug */ if (eeepc->wlan_rfkill) { eeepc_rfkill_hotplug_update(eeepc, "\\_SB.PCI0.P0P5"); eeepc_rfkill_hotplug_update(eeepc, "\\_SB.PCI0.P0P6"); eeepc_rfkill_hotplug_update(eeepc, "\\_SB.PCI0.P0P7"); } if (eeepc->bluetooth_rfkill) rfkill_set_sw_state(eeepc->bluetooth_rfkill, get_acpi(eeepc, CM_ASL_BLUETOOTH) != 1); if (eeepc->wwan3g_rfkill) rfkill_set_sw_state(eeepc->wwan3g_rfkill, get_acpi(eeepc, CM_ASL_3G) != 1); if (eeepc->wimax_rfkill) rfkill_set_sw_state(eeepc->wimax_rfkill, get_acpi(eeepc, CM_ASL_WIMAX) != 1); return 0; } static const struct dev_pm_ops eeepc_pm_ops = { .thaw = eeepc_hotk_thaw, .restore = eeepc_hotk_restore, }; static struct platform_driver platform_driver = { .driver = { .name = EEEPC_LAPTOP_FILE, .owner = THIS_MODULE, .pm = &eeepc_pm_ops, } }; /* * Hwmon device */ #define EEEPC_EC_SC00 0x61 #define EEEPC_EC_FAN_PWM (EEEPC_EC_SC00 + 2) /* Fan PWM duty cycle (%) */ #define EEEPC_EC_FAN_HRPM (EEEPC_EC_SC00 + 5) /* High byte, fan speed (RPM) */ #define EEEPC_EC_FAN_LRPM (EEEPC_EC_SC00 + 6) /* Low byte, fan speed (RPM) */ #define EEEPC_EC_SFB0 0xD0 #define EEEPC_EC_FAN_CTRL (EEEPC_EC_SFB0 + 3) /* Byte containing SF25 */ static int eeepc_get_fan_pwm(void) { u8 value = 0; ec_read(EEEPC_EC_FAN_PWM, &value); return value * 255 / 100; } static void eeepc_set_fan_pwm(int value) { value = SENSORS_LIMIT(value, 0, 255); value = value * 100 / 255; ec_write(EEEPC_EC_FAN_PWM, value); } static int eeepc_get_fan_rpm(void) { u8 high = 0; u8 low = 0; ec_read(EEEPC_EC_FAN_HRPM, &high); ec_read(EEEPC_EC_FAN_LRPM, &low); return high << 8 | low; } static int eeepc_get_fan_ctrl(void) { u8 value = 0; ec_read(EEEPC_EC_FAN_CTRL, &value); if (value & 0x02) return 1; /* manual */ else return 2; /* automatic */ } static void eeepc_set_fan_ctrl(int manual) { u8 value = 0; ec_read(EEEPC_EC_FAN_CTRL, &value); if (manual == 1) value |= 0x02; else value &= ~0x02; ec_write(EEEPC_EC_FAN_CTRL, value); } static ssize_t store_sys_hwmon(void (*set)(int), const char *buf, size_t count) { int rv, value; rv = parse_arg(buf, count, &value); if (rv > 0) set(value); return rv; } static ssize_t show_sys_hwmon(int (*get)(void), char *buf) { return sprintf(buf, "%d\n", get()); } #define EEEPC_CREATE_SENSOR_ATTR(_name, _mode, _set, _get) \ static ssize_t show_##_name(struct device *dev, \ struct device_attribute *attr, \ char *buf) \ { \ return show_sys_hwmon(_set, buf); \ } \ static ssize_t store_##_name(struct device *dev, \ struct device_attribute *attr, \ const char *buf, size_t count) \ { \ return store_sys_hwmon(_get, buf, count); \ } \ static SENSOR_DEVICE_ATTR(_name, _mode, show_##_name, store_##_name, 0); EEEPC_CREATE_SENSOR_ATTR(fan1_input, S_IRUGO, eeepc_get_fan_rpm, NULL); EEEPC_CREATE_SENSOR_ATTR(pwm1, S_IRUGO | S_IWUSR, eeepc_get_fan_pwm, eeepc_set_fan_pwm); EEEPC_CREATE_SENSOR_ATTR(pwm1_enable, S_IRUGO | S_IWUSR, eeepc_get_fan_ctrl, eeepc_set_fan_ctrl); static ssize_t show_name(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "eeepc\n"); } static SENSOR_DEVICE_ATTR(name, S_IRUGO, show_name, NULL, 0); static struct attribute *hwmon_attributes[] = { &sensor_dev_attr_pwm1.dev_attr.attr, &sensor_dev_attr_fan1_input.dev_attr.attr, &sensor_dev_attr_pwm1_enable.dev_attr.attr, &sensor_dev_attr_name.dev_attr.attr, NULL }; static struct attribute_group hwmon_attribute_group = { .attrs = hwmon_attributes }; static void eeepc_hwmon_exit(struct eeepc_laptop *eeepc) { struct device *hwmon; hwmon = eeepc->hwmon_device; if (!hwmon) return; sysfs_remove_group(&hwmon->kobj, &hwmon_attribute_group); hwmon_device_unregister(hwmon); eeepc->hwmon_device = NULL; } static int eeepc_hwmon_init(struct eeepc_laptop *eeepc) { struct device *hwmon; int result; hwmon = hwmon_device_register(&eeepc->platform_device->dev); if (IS_ERR(hwmon)) { pr_err("Could not register eeepc hwmon device\n"); eeepc->hwmon_device = NULL; return PTR_ERR(hwmon); } eeepc->hwmon_device = hwmon; result = sysfs_create_group(&hwmon->kobj, &hwmon_attribute_group); if (result) eeepc_hwmon_exit(eeepc); return result; } /* * Backlight device */ static int read_brightness(struct backlight_device *bd) { struct eeepc_laptop *eeepc = bl_get_data(bd); return get_acpi(eeepc, CM_ASL_PANELBRIGHT); } static int set_brightness(struct backlight_device *bd, int value) { struct eeepc_laptop *eeepc = bl_get_data(bd); return set_acpi(eeepc, CM_ASL_PANELBRIGHT, value); } static int update_bl_status(struct backlight_device *bd) { return set_brightness(bd, bd->props.brightness); } static const struct backlight_ops eeepcbl_ops = { .get_brightness = read_brightness, .update_status = update_bl_status, }; static int eeepc_backlight_notify(struct eeepc_laptop *eeepc) { struct backlight_device *bd = eeepc->backlight_device; int old = bd->props.brightness; backlight_force_update(bd, BACKLIGHT_UPDATE_HOTKEY); return old; } static int eeepc_backlight_init(struct eeepc_laptop *eeepc) { struct backlight_properties props; struct backlight_device *bd; memset(&props, 0, sizeof(struct backlight_properties)); props.type = BACKLIGHT_PLATFORM; props.max_brightness = 15; bd = backlight_device_register(EEEPC_LAPTOP_FILE, &eeepc->platform_device->dev, eeepc, &eeepcbl_ops, &props); if (IS_ERR(bd)) { pr_err("Could not register eeepc backlight device\n"); eeepc->backlight_device = NULL; return PTR_ERR(bd); } eeepc->backlight_device = bd; bd->props.brightness = read_brightness(bd); bd->props.power = FB_BLANK_UNBLANK; backlight_update_status(bd); return 0; } static void eeepc_backlight_exit(struct eeepc_laptop *eeepc) { if (eeepc->backlight_device) backlight_device_unregister(eeepc->backlight_device); eeepc->backlight_device = NULL; } /* * Input device (i.e. hotkeys) */ static int eeepc_input_init(struct eeepc_laptop *eeepc) { struct input_dev *input; int error; input = input_allocate_device(); if (!input) { pr_info("Unable to allocate input device\n"); return -ENOMEM; } input->name = "Asus EeePC extra buttons"; input->phys = EEEPC_LAPTOP_FILE "/input0"; input->id.bustype = BUS_HOST; input->dev.parent = &eeepc->platform_device->dev; error = sparse_keymap_setup(input, eeepc_keymap, NULL); if (error) { pr_err("Unable to setup input device keymap\n"); goto err_free_dev; } error = input_register_device(input); if (error) { pr_err("Unable to register input device\n"); goto err_free_keymap; } eeepc->inputdev = input; return 0; err_free_keymap: sparse_keymap_free(input); err_free_dev: input_free_device(input); return error; } static void eeepc_input_exit(struct eeepc_laptop *eeepc) { if (eeepc->inputdev) { sparse_keymap_free(eeepc->inputdev); input_unregister_device(eeepc->inputdev); } eeepc->inputdev = NULL; } /* * ACPI driver */ static void eeepc_acpi_notify(struct acpi_device *device, u32 event) { struct eeepc_laptop *eeepc = acpi_driver_data(device); u16 count; if (event > ACPI_MAX_SYS_NOTIFY) return; count = eeepc->event_count[event % 128]++; acpi_bus_generate_proc_event(device, event, count); acpi_bus_generate_netlink_event(device->pnp.device_class, dev_name(&device->dev), event, count); /* Brightness events are special */ if (event >= NOTIFY_BRN_MIN && event <= NOTIFY_BRN_MAX) { /* Ignore them completely if the acpi video driver is used */ if (eeepc->backlight_device != NULL) { int old_brightness, new_brightness; /* Update the backlight device. */ old_brightness = eeepc_backlight_notify(eeepc); /* Convert event to keypress (obsolescent hack) */ new_brightness = event - NOTIFY_BRN_MIN; if (new_brightness < old_brightness) { event = NOTIFY_BRN_MIN; /* brightness down */ } else if (new_brightness > old_brightness) { event = NOTIFY_BRN_MAX; /* brightness up */ } else { /* * no change in brightness - already at min/max, * event will be desired value (or else ignored) */ } sparse_keymap_report_event(eeepc->inputdev, event, 1, true); } } else { /* Everything else is a bona-fide keypress event */ sparse_keymap_report_event(eeepc->inputdev, event, 1, true); } } static void eeepc_dmi_check(struct eeepc_laptop *eeepc) { const char *model; model = dmi_get_system_info(DMI_PRODUCT_NAME); if (!model) return; /* * Blacklist for setting cpufv (cpu speed). * * EeePC 4G ("701") implements CFVS, but it is not supported * by the pre-installed OS, and the original option to change it * in the BIOS setup screen was removed in later versions. * * Judging by the lack of "Super Hybrid Engine" on Asus product pages, * this applies to all "701" models (4G/4G Surf/2G Surf). * * So Asus made a deliberate decision not to support it on this model. * We have several reports that using it can cause the system to hang * * The hang has also been reported on a "702" (Model name "8G"?). * * We avoid dmi_check_system() / dmi_match(), because they use * substring matching. We don't want to affect the "701SD" * and "701SDX" models, because they do support S.H.E. */ if (strcmp(model, "701") == 0 || strcmp(model, "702") == 0) { eeepc->cpufv_disabled = true; pr_info("model %s does not officially support setting cpu " "speed\n", model); pr_info("cpufv disabled to avoid instability\n"); } /* * Blacklist for wlan hotplug * * Eeepc 1005HA doesn't work like others models and don't need the * hotplug code. In fact, current hotplug code seems to unplug another * device... */ if (strcmp(model, "1005HA") == 0 || strcmp(model, "1201N") == 0 || strcmp(model, "1005PE") == 0) { eeepc->hotplug_disabled = true; pr_info("wlan hotplug disabled\n"); } } static void cmsg_quirk(struct eeepc_laptop *eeepc, int cm, const char *name) { int dummy; /* Some BIOSes do not report cm although it is available. Check if cm_getv[cm] works and, if yes, assume cm should be set. */ if (!(eeepc->cm_supported & (1 << cm)) && !read_acpi_int(eeepc->handle, cm_getv[cm], &dummy)) { pr_info("%s (%x) not reported by BIOS," " enabling anyway\n", name, 1 << cm); eeepc->cm_supported |= 1 << cm; } } static void cmsg_quirks(struct eeepc_laptop *eeepc) { cmsg_quirk(eeepc, CM_ASL_LID, "LID"); cmsg_quirk(eeepc, CM_ASL_TYPE, "TYPE"); cmsg_quirk(eeepc, CM_ASL_PANELPOWER, "PANELPOWER"); cmsg_quirk(eeepc, CM_ASL_TPD, "TPD"); } static int __devinit eeepc_acpi_init(struct eeepc_laptop *eeepc) { unsigned int init_flags; int result; result = acpi_bus_get_status(eeepc->device); if (result) return result; if (!eeepc->device->status.present) { pr_err("Hotkey device not present, aborting\n"); return -ENODEV; } init_flags = DISABLE_ASL_WLAN | DISABLE_ASL_DISPLAYSWITCH; pr_notice("Hotkey init flags 0x%x\n", init_flags); if (write_acpi_int(eeepc->handle, "INIT", init_flags)) { pr_err("Hotkey initialization failed\n"); return -ENODEV; } /* get control methods supported */ if (read_acpi_int(eeepc->handle, "CMSG", &eeepc->cm_supported)) { pr_err("Get control methods supported failed\n"); return -ENODEV; } cmsg_quirks(eeepc); pr_info("Get control methods supported: 0x%x\n", eeepc->cm_supported); return 0; } static void __devinit eeepc_enable_camera(struct eeepc_laptop *eeepc) { /* * If the following call to set_acpi() fails, it's because there's no * camera so we can ignore the error. */ if (get_acpi(eeepc, CM_ASL_CAMERA) == 0) set_acpi(eeepc, CM_ASL_CAMERA, 1); } static bool eeepc_device_present; static int __devinit eeepc_acpi_add(struct acpi_device *device) { struct eeepc_laptop *eeepc; int result; pr_notice(EEEPC_LAPTOP_NAME "\n"); eeepc = kzalloc(sizeof(struct eeepc_laptop), GFP_KERNEL); if (!eeepc) return -ENOMEM; eeepc->handle = device->handle; strcpy(acpi_device_name(device), EEEPC_ACPI_DEVICE_NAME); strcpy(acpi_device_class(device), EEEPC_ACPI_CLASS); device->driver_data = eeepc; eeepc->device = device; eeepc->hotplug_disabled = hotplug_disabled; eeepc_dmi_check(eeepc); result = eeepc_acpi_init(eeepc); if (result) goto fail_platform; eeepc_enable_camera(eeepc); /* * Register the platform device first. It is used as a parent for the * sub-devices below. * * Note that if there are multiple instances of this ACPI device it * will bail out, because the platform device is registered with a * fixed name. Of course it doesn't make sense to have more than one, * and machine-specific scripts find the fixed name convenient. But * It's also good for us to exclude multiple instances because both * our hwmon and our wlan rfkill subdevice use global ACPI objects * (the EC and the wlan PCI slot respectively). */ result = eeepc_platform_init(eeepc); if (result) goto fail_platform; if (!acpi_video_backlight_support()) { result = eeepc_backlight_init(eeepc); if (result) goto fail_backlight; } else pr_info("Backlight controlled by ACPI video driver\n"); result = eeepc_input_init(eeepc); if (result) goto fail_input; result = eeepc_hwmon_init(eeepc); if (result) goto fail_hwmon; result = eeepc_led_init(eeepc); if (result) goto fail_led; result = eeepc_rfkill_init(eeepc); if (result) goto fail_rfkill; eeepc_device_present = true; return 0; fail_rfkill: eeepc_led_exit(eeepc); fail_led: eeepc_hwmon_exit(eeepc); fail_hwmon: eeepc_input_exit(eeepc); fail_input: eeepc_backlight_exit(eeepc); fail_backlight: eeepc_platform_exit(eeepc); fail_platform: kfree(eeepc); return result; } static int eeepc_acpi_remove(struct acpi_device *device, int type) { struct eeepc_laptop *eeepc = acpi_driver_data(device); eeepc_backlight_exit(eeepc); eeepc_rfkill_exit(eeepc); eeepc_input_exit(eeepc); eeepc_hwmon_exit(eeepc); eeepc_led_exit(eeepc); eeepc_platform_exit(eeepc); kfree(eeepc); return 0; } static const struct acpi_device_id eeepc_device_ids[] = { {EEEPC_ACPI_HID, 0}, {"", 0}, }; MODULE_DEVICE_TABLE(acpi, eeepc_device_ids); static struct acpi_driver eeepc_acpi_driver = { .name = EEEPC_LAPTOP_NAME, .class = EEEPC_ACPI_CLASS, .owner = THIS_MODULE, .ids = eeepc_device_ids, .flags = ACPI_DRIVER_ALL_NOTIFY_EVENTS, .ops = { .add = eeepc_acpi_add, .remove = eeepc_acpi_remove, .notify = eeepc_acpi_notify, }, }; static int __init eeepc_laptop_init(void) { int result; result = platform_driver_register(&platform_driver); if (result < 0) return result; result = acpi_bus_register_driver(&eeepc_acpi_driver); if (result < 0) goto fail_acpi_driver; if (!eeepc_device_present) { result = -ENODEV; goto fail_no_device; } return 0; fail_no_device: acpi_bus_unregister_driver(&eeepc_acpi_driver); fail_acpi_driver: platform_driver_unregister(&platform_driver); return result; } static void __exit eeepc_laptop_exit(void) { acpi_bus_unregister_driver(&eeepc_acpi_driver); platform_driver_unregister(&platform_driver); } module_init(eeepc_laptop_init); module_exit(eeepc_laptop_exit);
gpl-2.0
JackpotClavin/android_kernel_samsung_venturi
net/ax25/ax25_iface.c
3031
5064
/* * 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. * * Copyright (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk) */ #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/timer.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/slab.h> #include <net/ax25.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/skbuff.h> #include <net/sock.h> #include <asm/uaccess.h> #include <asm/system.h> #include <linux/fcntl.h> #include <linux/mm.h> #include <linux/interrupt.h> static struct ax25_protocol *protocol_list; static DEFINE_RWLOCK(protocol_list_lock); static HLIST_HEAD(ax25_linkfail_list); static DEFINE_SPINLOCK(linkfail_lock); static struct listen_struct { struct listen_struct *next; ax25_address callsign; struct net_device *dev; } *listen_list = NULL; static DEFINE_SPINLOCK(listen_lock); /* * Do not register the internal protocols AX25_P_TEXT, AX25_P_SEGMENT, * AX25_P_IP or AX25_P_ARP ... */ void ax25_register_pid(struct ax25_protocol *ap) { write_lock_bh(&protocol_list_lock); ap->next = protocol_list; protocol_list = ap; write_unlock_bh(&protocol_list_lock); } EXPORT_SYMBOL_GPL(ax25_register_pid); void ax25_protocol_release(unsigned int pid) { struct ax25_protocol *protocol; write_lock_bh(&protocol_list_lock); protocol = protocol_list; if (protocol == NULL) goto out; if (protocol->pid == pid) { protocol_list = protocol->next; goto out; } while (protocol != NULL && protocol->next != NULL) { if (protocol->next->pid == pid) { protocol->next = protocol->next->next; goto out; } protocol = protocol->next; } out: write_unlock_bh(&protocol_list_lock); } EXPORT_SYMBOL(ax25_protocol_release); void ax25_linkfail_register(struct ax25_linkfail *lf) { spin_lock_bh(&linkfail_lock); hlist_add_head(&lf->lf_node, &ax25_linkfail_list); spin_unlock_bh(&linkfail_lock); } EXPORT_SYMBOL(ax25_linkfail_register); void ax25_linkfail_release(struct ax25_linkfail *lf) { spin_lock_bh(&linkfail_lock); hlist_del_init(&lf->lf_node); spin_unlock_bh(&linkfail_lock); } EXPORT_SYMBOL(ax25_linkfail_release); int ax25_listen_register(ax25_address *callsign, struct net_device *dev) { struct listen_struct *listen; if (ax25_listen_mine(callsign, dev)) return 0; if ((listen = kmalloc(sizeof(*listen), GFP_ATOMIC)) == NULL) return -ENOMEM; listen->callsign = *callsign; listen->dev = dev; spin_lock_bh(&listen_lock); listen->next = listen_list; listen_list = listen; spin_unlock_bh(&listen_lock); return 0; } EXPORT_SYMBOL(ax25_listen_register); void ax25_listen_release(ax25_address *callsign, struct net_device *dev) { struct listen_struct *s, *listen; spin_lock_bh(&listen_lock); listen = listen_list; if (listen == NULL) { spin_unlock_bh(&listen_lock); return; } if (ax25cmp(&listen->callsign, callsign) == 0 && listen->dev == dev) { listen_list = listen->next; spin_unlock_bh(&listen_lock); kfree(listen); return; } while (listen != NULL && listen->next != NULL) { if (ax25cmp(&listen->next->callsign, callsign) == 0 && listen->next->dev == dev) { s = listen->next; listen->next = listen->next->next; spin_unlock_bh(&listen_lock); kfree(s); return; } listen = listen->next; } spin_unlock_bh(&listen_lock); } EXPORT_SYMBOL(ax25_listen_release); int (*ax25_protocol_function(unsigned int pid))(struct sk_buff *, ax25_cb *) { int (*res)(struct sk_buff *, ax25_cb *) = NULL; struct ax25_protocol *protocol; read_lock(&protocol_list_lock); for (protocol = protocol_list; protocol != NULL; protocol = protocol->next) if (protocol->pid == pid) { res = protocol->func; break; } read_unlock(&protocol_list_lock); return res; } int ax25_listen_mine(ax25_address *callsign, struct net_device *dev) { struct listen_struct *listen; spin_lock_bh(&listen_lock); for (listen = listen_list; listen != NULL; listen = listen->next) if (ax25cmp(&listen->callsign, callsign) == 0 && (listen->dev == dev || listen->dev == NULL)) { spin_unlock_bh(&listen_lock); return 1; } spin_unlock_bh(&listen_lock); return 0; } void ax25_link_failed(ax25_cb *ax25, int reason) { struct ax25_linkfail *lf; struct hlist_node *node; spin_lock_bh(&linkfail_lock); hlist_for_each_entry(lf, node, &ax25_linkfail_list, lf_node) lf->func(ax25, reason); spin_unlock_bh(&linkfail_lock); } int ax25_protocol_is_registered(unsigned int pid) { struct ax25_protocol *protocol; int res = 0; read_lock_bh(&protocol_list_lock); for (protocol = protocol_list; protocol != NULL; protocol = protocol->next) if (protocol->pid == pid) { res = 1; break; } read_unlock_bh(&protocol_list_lock); return res; }
gpl-2.0
lambchops468/omap443x-overclock-lge-p769
drivers/net/mace.c
3543
27978
/* * Network device driver for the MACE ethernet controller on * Apple Powermacs. Assumes it's under a DBDMA controller. * * Copyright (C) 1996 Paul Mackerras. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/delay.h> #include <linux/string.h> #include <linux/timer.h> #include <linux/init.h> #include <linux/crc32.h> #include <linux/spinlock.h> #include <linux/bitrev.h> #include <linux/slab.h> #include <asm/prom.h> #include <asm/dbdma.h> #include <asm/io.h> #include <asm/pgtable.h> #include <asm/macio.h> #include "mace.h" static int port_aaui = -1; #define N_RX_RING 8 #define N_TX_RING 6 #define MAX_TX_ACTIVE 1 #define NCMDS_TX 1 /* dma commands per element in tx ring */ #define RX_BUFLEN (ETH_FRAME_LEN + 8) #define TX_TIMEOUT HZ /* 1 second */ /* Chip rev needs workaround on HW & multicast addr change */ #define BROKEN_ADDRCHG_REV 0x0941 /* Bits in transmit DMA status */ #define TX_DMA_ERR 0x80 struct mace_data { volatile struct mace __iomem *mace; volatile struct dbdma_regs __iomem *tx_dma; int tx_dma_intr; volatile struct dbdma_regs __iomem *rx_dma; int rx_dma_intr; volatile struct dbdma_cmd *tx_cmds; /* xmit dma command list */ volatile struct dbdma_cmd *rx_cmds; /* recv dma command list */ struct sk_buff *rx_bufs[N_RX_RING]; int rx_fill; int rx_empty; struct sk_buff *tx_bufs[N_TX_RING]; int tx_fill; int tx_empty; unsigned char maccc; unsigned char tx_fullup; unsigned char tx_active; unsigned char tx_bad_runt; struct timer_list tx_timeout; int timeout_active; int port_aaui; int chipid; struct macio_dev *mdev; spinlock_t lock; }; /* * Number of bytes of private data per MACE: allow enough for * the rx and tx dma commands plus a branch dma command each, * and another 16 bytes to allow us to align the dma command * buffers on a 16 byte boundary. */ #define PRIV_BYTES (sizeof(struct mace_data) \ + (N_RX_RING + NCMDS_TX * N_TX_RING + 3) * sizeof(struct dbdma_cmd)) static int mace_open(struct net_device *dev); static int mace_close(struct net_device *dev); static int mace_xmit_start(struct sk_buff *skb, struct net_device *dev); static void mace_set_multicast(struct net_device *dev); static void mace_reset(struct net_device *dev); static int mace_set_address(struct net_device *dev, void *addr); static irqreturn_t mace_interrupt(int irq, void *dev_id); static irqreturn_t mace_txdma_intr(int irq, void *dev_id); static irqreturn_t mace_rxdma_intr(int irq, void *dev_id); static void mace_set_timeout(struct net_device *dev); static void mace_tx_timeout(unsigned long data); static inline void dbdma_reset(volatile struct dbdma_regs __iomem *dma); static inline void mace_clean_rings(struct mace_data *mp); static void __mace_set_address(struct net_device *dev, void *addr); /* * If we can't get a skbuff when we need it, we use this area for DMA. */ static unsigned char *dummy_buf; static const struct net_device_ops mace_netdev_ops = { .ndo_open = mace_open, .ndo_stop = mace_close, .ndo_start_xmit = mace_xmit_start, .ndo_set_multicast_list = mace_set_multicast, .ndo_set_mac_address = mace_set_address, .ndo_change_mtu = eth_change_mtu, .ndo_validate_addr = eth_validate_addr, }; static int __devinit mace_probe(struct macio_dev *mdev, const struct of_device_id *match) { struct device_node *mace = macio_get_of_node(mdev); struct net_device *dev; struct mace_data *mp; const unsigned char *addr; int j, rev, rc = -EBUSY; if (macio_resource_count(mdev) != 3 || macio_irq_count(mdev) != 3) { printk(KERN_ERR "can't use MACE %s: need 3 addrs and 3 irqs\n", mace->full_name); return -ENODEV; } addr = of_get_property(mace, "mac-address", NULL); if (addr == NULL) { addr = of_get_property(mace, "local-mac-address", NULL); if (addr == NULL) { printk(KERN_ERR "Can't get mac-address for MACE %s\n", mace->full_name); return -ENODEV; } } /* * lazy allocate the driver-wide dummy buffer. (Note that we * never have more than one MACE in the system anyway) */ if (dummy_buf == NULL) { dummy_buf = kmalloc(RX_BUFLEN+2, GFP_KERNEL); if (dummy_buf == NULL) { printk(KERN_ERR "MACE: couldn't allocate dummy buffer\n"); return -ENOMEM; } } if (macio_request_resources(mdev, "mace")) { printk(KERN_ERR "MACE: can't request IO resources !\n"); return -EBUSY; } dev = alloc_etherdev(PRIV_BYTES); if (!dev) { printk(KERN_ERR "MACE: can't allocate ethernet device !\n"); rc = -ENOMEM; goto err_release; } SET_NETDEV_DEV(dev, &mdev->ofdev.dev); mp = netdev_priv(dev); mp->mdev = mdev; macio_set_drvdata(mdev, dev); dev->base_addr = macio_resource_start(mdev, 0); mp->mace = ioremap(dev->base_addr, 0x1000); if (mp->mace == NULL) { printk(KERN_ERR "MACE: can't map IO resources !\n"); rc = -ENOMEM; goto err_free; } dev->irq = macio_irq(mdev, 0); rev = addr[0] == 0 && addr[1] == 0xA0; for (j = 0; j < 6; ++j) { dev->dev_addr[j] = rev ? bitrev8(addr[j]): addr[j]; } mp->chipid = (in_8(&mp->mace->chipid_hi) << 8) | in_8(&mp->mace->chipid_lo); mp = netdev_priv(dev); mp->maccc = ENXMT | ENRCV; mp->tx_dma = ioremap(macio_resource_start(mdev, 1), 0x1000); if (mp->tx_dma == NULL) { printk(KERN_ERR "MACE: can't map TX DMA resources !\n"); rc = -ENOMEM; goto err_unmap_io; } mp->tx_dma_intr = macio_irq(mdev, 1); mp->rx_dma = ioremap(macio_resource_start(mdev, 2), 0x1000); if (mp->rx_dma == NULL) { printk(KERN_ERR "MACE: can't map RX DMA resources !\n"); rc = -ENOMEM; goto err_unmap_tx_dma; } mp->rx_dma_intr = macio_irq(mdev, 2); mp->tx_cmds = (volatile struct dbdma_cmd *) DBDMA_ALIGN(mp + 1); mp->rx_cmds = mp->tx_cmds + NCMDS_TX * N_TX_RING + 1; memset((char *) mp->tx_cmds, 0, (NCMDS_TX*N_TX_RING + N_RX_RING + 2) * sizeof(struct dbdma_cmd)); init_timer(&mp->tx_timeout); spin_lock_init(&mp->lock); mp->timeout_active = 0; if (port_aaui >= 0) mp->port_aaui = port_aaui; else { /* Apple Network Server uses the AAUI port */ if (of_machine_is_compatible("AAPL,ShinerESB")) mp->port_aaui = 1; else { #ifdef CONFIG_MACE_AAUI_PORT mp->port_aaui = 1; #else mp->port_aaui = 0; #endif } } dev->netdev_ops = &mace_netdev_ops; /* * Most of what is below could be moved to mace_open() */ mace_reset(dev); rc = request_irq(dev->irq, mace_interrupt, 0, "MACE", dev); if (rc) { printk(KERN_ERR "MACE: can't get irq %d\n", dev->irq); goto err_unmap_rx_dma; } rc = request_irq(mp->tx_dma_intr, mace_txdma_intr, 0, "MACE-txdma", dev); if (rc) { printk(KERN_ERR "MACE: can't get irq %d\n", mp->tx_dma_intr); goto err_free_irq; } rc = request_irq(mp->rx_dma_intr, mace_rxdma_intr, 0, "MACE-rxdma", dev); if (rc) { printk(KERN_ERR "MACE: can't get irq %d\n", mp->rx_dma_intr); goto err_free_tx_irq; } rc = register_netdev(dev); if (rc) { printk(KERN_ERR "MACE: Cannot register net device, aborting.\n"); goto err_free_rx_irq; } printk(KERN_INFO "%s: MACE at %pM, chip revision %d.%d\n", dev->name, dev->dev_addr, mp->chipid >> 8, mp->chipid & 0xff); return 0; err_free_rx_irq: free_irq(macio_irq(mdev, 2), dev); err_free_tx_irq: free_irq(macio_irq(mdev, 1), dev); err_free_irq: free_irq(macio_irq(mdev, 0), dev); err_unmap_rx_dma: iounmap(mp->rx_dma); err_unmap_tx_dma: iounmap(mp->tx_dma); err_unmap_io: iounmap(mp->mace); err_free: free_netdev(dev); err_release: macio_release_resources(mdev); return rc; } static int __devexit mace_remove(struct macio_dev *mdev) { struct net_device *dev = macio_get_drvdata(mdev); struct mace_data *mp; BUG_ON(dev == NULL); macio_set_drvdata(mdev, NULL); mp = netdev_priv(dev); unregister_netdev(dev); free_irq(dev->irq, dev); free_irq(mp->tx_dma_intr, dev); free_irq(mp->rx_dma_intr, dev); iounmap(mp->rx_dma); iounmap(mp->tx_dma); iounmap(mp->mace); free_netdev(dev); macio_release_resources(mdev); return 0; } static void dbdma_reset(volatile struct dbdma_regs __iomem *dma) { int i; out_le32(&dma->control, (WAKE|FLUSH|PAUSE|RUN) << 16); /* * Yes this looks peculiar, but apparently it needs to be this * way on some machines. */ for (i = 200; i > 0; --i) if (ld_le32(&dma->control) & RUN) udelay(1); } static void mace_reset(struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); volatile struct mace __iomem *mb = mp->mace; int i; /* soft-reset the chip */ i = 200; while (--i) { out_8(&mb->biucc, SWRST); if (in_8(&mb->biucc) & SWRST) { udelay(10); continue; } break; } if (!i) { printk(KERN_ERR "mace: cannot reset chip!\n"); return; } out_8(&mb->imr, 0xff); /* disable all intrs for now */ i = in_8(&mb->ir); out_8(&mb->maccc, 0); /* turn off tx, rx */ out_8(&mb->biucc, XMTSP_64); out_8(&mb->utr, RTRD); out_8(&mb->fifocc, RCVFW_32 | XMTFW_16 | XMTFWU | RCVFWU | XMTBRST); out_8(&mb->xmtfc, AUTO_PAD_XMIT); /* auto-pad short frames */ out_8(&mb->rcvfc, 0); /* load up the hardware address */ __mace_set_address(dev, dev->dev_addr); /* clear the multicast filter */ if (mp->chipid == BROKEN_ADDRCHG_REV) out_8(&mb->iac, LOGADDR); else { out_8(&mb->iac, ADDRCHG | LOGADDR); while ((in_8(&mb->iac) & ADDRCHG) != 0) ; } for (i = 0; i < 8; ++i) out_8(&mb->ladrf, 0); /* done changing address */ if (mp->chipid != BROKEN_ADDRCHG_REV) out_8(&mb->iac, 0); if (mp->port_aaui) out_8(&mb->plscc, PORTSEL_AUI + ENPLSIO); else out_8(&mb->plscc, PORTSEL_GPSI + ENPLSIO); } static void __mace_set_address(struct net_device *dev, void *addr) { struct mace_data *mp = netdev_priv(dev); volatile struct mace __iomem *mb = mp->mace; unsigned char *p = addr; int i; /* load up the hardware address */ if (mp->chipid == BROKEN_ADDRCHG_REV) out_8(&mb->iac, PHYADDR); else { out_8(&mb->iac, ADDRCHG | PHYADDR); while ((in_8(&mb->iac) & ADDRCHG) != 0) ; } for (i = 0; i < 6; ++i) out_8(&mb->padr, dev->dev_addr[i] = p[i]); if (mp->chipid != BROKEN_ADDRCHG_REV) out_8(&mb->iac, 0); } static int mace_set_address(struct net_device *dev, void *addr) { struct mace_data *mp = netdev_priv(dev); volatile struct mace __iomem *mb = mp->mace; unsigned long flags; spin_lock_irqsave(&mp->lock, flags); __mace_set_address(dev, addr); /* note: setting ADDRCHG clears ENRCV */ out_8(&mb->maccc, mp->maccc); spin_unlock_irqrestore(&mp->lock, flags); return 0; } static inline void mace_clean_rings(struct mace_data *mp) { int i; /* free some skb's */ for (i = 0; i < N_RX_RING; ++i) { if (mp->rx_bufs[i] != NULL) { dev_kfree_skb(mp->rx_bufs[i]); mp->rx_bufs[i] = NULL; } } for (i = mp->tx_empty; i != mp->tx_fill; ) { dev_kfree_skb(mp->tx_bufs[i]); if (++i >= N_TX_RING) i = 0; } } static int mace_open(struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); volatile struct mace __iomem *mb = mp->mace; volatile struct dbdma_regs __iomem *rd = mp->rx_dma; volatile struct dbdma_regs __iomem *td = mp->tx_dma; volatile struct dbdma_cmd *cp; int i; struct sk_buff *skb; unsigned char *data; /* reset the chip */ mace_reset(dev); /* initialize list of sk_buffs for receiving and set up recv dma */ mace_clean_rings(mp); memset((char *)mp->rx_cmds, 0, N_RX_RING * sizeof(struct dbdma_cmd)); cp = mp->rx_cmds; for (i = 0; i < N_RX_RING - 1; ++i) { skb = dev_alloc_skb(RX_BUFLEN + 2); if (!skb) { data = dummy_buf; } else { skb_reserve(skb, 2); /* so IP header lands on 4-byte bdry */ data = skb->data; } mp->rx_bufs[i] = skb; st_le16(&cp->req_count, RX_BUFLEN); st_le16(&cp->command, INPUT_LAST + INTR_ALWAYS); st_le32(&cp->phy_addr, virt_to_bus(data)); cp->xfer_status = 0; ++cp; } mp->rx_bufs[i] = NULL; st_le16(&cp->command, DBDMA_STOP); mp->rx_fill = i; mp->rx_empty = 0; /* Put a branch back to the beginning of the receive command list */ ++cp; st_le16(&cp->command, DBDMA_NOP + BR_ALWAYS); st_le32(&cp->cmd_dep, virt_to_bus(mp->rx_cmds)); /* start rx dma */ out_le32(&rd->control, (RUN|PAUSE|FLUSH|WAKE) << 16); /* clear run bit */ out_le32(&rd->cmdptr, virt_to_bus(mp->rx_cmds)); out_le32(&rd->control, (RUN << 16) | RUN); /* put a branch at the end of the tx command list */ cp = mp->tx_cmds + NCMDS_TX * N_TX_RING; st_le16(&cp->command, DBDMA_NOP + BR_ALWAYS); st_le32(&cp->cmd_dep, virt_to_bus(mp->tx_cmds)); /* reset tx dma */ out_le32(&td->control, (RUN|PAUSE|FLUSH|WAKE) << 16); out_le32(&td->cmdptr, virt_to_bus(mp->tx_cmds)); mp->tx_fill = 0; mp->tx_empty = 0; mp->tx_fullup = 0; mp->tx_active = 0; mp->tx_bad_runt = 0; /* turn it on! */ out_8(&mb->maccc, mp->maccc); /* enable all interrupts except receive interrupts */ out_8(&mb->imr, RCVINT); return 0; } static int mace_close(struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); volatile struct mace __iomem *mb = mp->mace; volatile struct dbdma_regs __iomem *rd = mp->rx_dma; volatile struct dbdma_regs __iomem *td = mp->tx_dma; /* disable rx and tx */ out_8(&mb->maccc, 0); out_8(&mb->imr, 0xff); /* disable all intrs */ /* disable rx and tx dma */ st_le32(&rd->control, (RUN|PAUSE|FLUSH|WAKE) << 16); /* clear run bit */ st_le32(&td->control, (RUN|PAUSE|FLUSH|WAKE) << 16); /* clear run bit */ mace_clean_rings(mp); return 0; } static inline void mace_set_timeout(struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); if (mp->timeout_active) del_timer(&mp->tx_timeout); mp->tx_timeout.expires = jiffies + TX_TIMEOUT; mp->tx_timeout.function = mace_tx_timeout; mp->tx_timeout.data = (unsigned long) dev; add_timer(&mp->tx_timeout); mp->timeout_active = 1; } static int mace_xmit_start(struct sk_buff *skb, struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); volatile struct dbdma_regs __iomem *td = mp->tx_dma; volatile struct dbdma_cmd *cp, *np; unsigned long flags; int fill, next, len; /* see if there's a free slot in the tx ring */ spin_lock_irqsave(&mp->lock, flags); fill = mp->tx_fill; next = fill + 1; if (next >= N_TX_RING) next = 0; if (next == mp->tx_empty) { netif_stop_queue(dev); mp->tx_fullup = 1; spin_unlock_irqrestore(&mp->lock, flags); return NETDEV_TX_BUSY; /* can't take it at the moment */ } spin_unlock_irqrestore(&mp->lock, flags); /* partially fill in the dma command block */ len = skb->len; if (len > ETH_FRAME_LEN) { printk(KERN_DEBUG "mace: xmit frame too long (%d)\n", len); len = ETH_FRAME_LEN; } mp->tx_bufs[fill] = skb; cp = mp->tx_cmds + NCMDS_TX * fill; st_le16(&cp->req_count, len); st_le32(&cp->phy_addr, virt_to_bus(skb->data)); np = mp->tx_cmds + NCMDS_TX * next; out_le16(&np->command, DBDMA_STOP); /* poke the tx dma channel */ spin_lock_irqsave(&mp->lock, flags); mp->tx_fill = next; if (!mp->tx_bad_runt && mp->tx_active < MAX_TX_ACTIVE) { out_le16(&cp->xfer_status, 0); out_le16(&cp->command, OUTPUT_LAST); out_le32(&td->control, ((RUN|WAKE) << 16) + (RUN|WAKE)); ++mp->tx_active; mace_set_timeout(dev); } if (++next >= N_TX_RING) next = 0; if (next == mp->tx_empty) netif_stop_queue(dev); spin_unlock_irqrestore(&mp->lock, flags); return NETDEV_TX_OK; } static void mace_set_multicast(struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); volatile struct mace __iomem *mb = mp->mace; int i; u32 crc; unsigned long flags; spin_lock_irqsave(&mp->lock, flags); mp->maccc &= ~PROM; if (dev->flags & IFF_PROMISC) { mp->maccc |= PROM; } else { unsigned char multicast_filter[8]; struct netdev_hw_addr *ha; if (dev->flags & IFF_ALLMULTI) { for (i = 0; i < 8; i++) multicast_filter[i] = 0xff; } else { for (i = 0; i < 8; i++) multicast_filter[i] = 0; netdev_for_each_mc_addr(ha, dev) { crc = ether_crc_le(6, ha->addr); i = crc >> 26; /* bit number in multicast_filter */ multicast_filter[i >> 3] |= 1 << (i & 7); } } #if 0 printk("Multicast filter :"); for (i = 0; i < 8; i++) printk("%02x ", multicast_filter[i]); printk("\n"); #endif if (mp->chipid == BROKEN_ADDRCHG_REV) out_8(&mb->iac, LOGADDR); else { out_8(&mb->iac, ADDRCHG | LOGADDR); while ((in_8(&mb->iac) & ADDRCHG) != 0) ; } for (i = 0; i < 8; ++i) out_8(&mb->ladrf, multicast_filter[i]); if (mp->chipid != BROKEN_ADDRCHG_REV) out_8(&mb->iac, 0); } /* reset maccc */ out_8(&mb->maccc, mp->maccc); spin_unlock_irqrestore(&mp->lock, flags); } static void mace_handle_misc_intrs(struct mace_data *mp, int intr, struct net_device *dev) { volatile struct mace __iomem *mb = mp->mace; static int mace_babbles, mace_jabbers; if (intr & MPCO) dev->stats.rx_missed_errors += 256; dev->stats.rx_missed_errors += in_8(&mb->mpc); /* reading clears it */ if (intr & RNTPCO) dev->stats.rx_length_errors += 256; dev->stats.rx_length_errors += in_8(&mb->rntpc); /* reading clears it */ if (intr & CERR) ++dev->stats.tx_heartbeat_errors; if (intr & BABBLE) if (mace_babbles++ < 4) printk(KERN_DEBUG "mace: babbling transmitter\n"); if (intr & JABBER) if (mace_jabbers++ < 4) printk(KERN_DEBUG "mace: jabbering transceiver\n"); } static irqreturn_t mace_interrupt(int irq, void *dev_id) { struct net_device *dev = (struct net_device *) dev_id; struct mace_data *mp = netdev_priv(dev); volatile struct mace __iomem *mb = mp->mace; volatile struct dbdma_regs __iomem *td = mp->tx_dma; volatile struct dbdma_cmd *cp; int intr, fs, i, stat, x; int xcount, dstat; unsigned long flags; /* static int mace_last_fs, mace_last_xcount; */ spin_lock_irqsave(&mp->lock, flags); intr = in_8(&mb->ir); /* read interrupt register */ in_8(&mb->xmtrc); /* get retries */ mace_handle_misc_intrs(mp, intr, dev); i = mp->tx_empty; while (in_8(&mb->pr) & XMTSV) { del_timer(&mp->tx_timeout); mp->timeout_active = 0; /* * Clear any interrupt indication associated with this status * word. This appears to unlatch any error indication from * the DMA controller. */ intr = in_8(&mb->ir); if (intr != 0) mace_handle_misc_intrs(mp, intr, dev); if (mp->tx_bad_runt) { fs = in_8(&mb->xmtfs); mp->tx_bad_runt = 0; out_8(&mb->xmtfc, AUTO_PAD_XMIT); continue; } dstat = ld_le32(&td->status); /* stop DMA controller */ out_le32(&td->control, RUN << 16); /* * xcount is the number of complete frames which have been * written to the fifo but for which status has not been read. */ xcount = (in_8(&mb->fifofc) >> XMTFC_SH) & XMTFC_MASK; if (xcount == 0 || (dstat & DEAD)) { /* * If a packet was aborted before the DMA controller has * finished transferring it, it seems that there are 2 bytes * which are stuck in some buffer somewhere. These will get * transmitted as soon as we read the frame status (which * reenables the transmit data transfer request). Turning * off the DMA controller and/or resetting the MACE doesn't * help. So we disable auto-padding and FCS transmission * so the two bytes will only be a runt packet which should * be ignored by other stations. */ out_8(&mb->xmtfc, DXMTFCS); } fs = in_8(&mb->xmtfs); if ((fs & XMTSV) == 0) { printk(KERN_ERR "mace: xmtfs not valid! (fs=%x xc=%d ds=%x)\n", fs, xcount, dstat); mace_reset(dev); /* * XXX mace likes to hang the machine after a xmtfs error. * This is hard to reproduce, reseting *may* help */ } cp = mp->tx_cmds + NCMDS_TX * i; stat = ld_le16(&cp->xfer_status); if ((fs & (UFLO|LCOL|LCAR|RTRY)) || (dstat & DEAD) || xcount == 0) { /* * Check whether there were in fact 2 bytes written to * the transmit FIFO. */ udelay(1); x = (in_8(&mb->fifofc) >> XMTFC_SH) & XMTFC_MASK; if (x != 0) { /* there were two bytes with an end-of-packet indication */ mp->tx_bad_runt = 1; mace_set_timeout(dev); } else { /* * Either there weren't the two bytes buffered up, or they * didn't have an end-of-packet indication. * We flush the transmit FIFO just in case (by setting the * XMTFWU bit with the transmitter disabled). */ out_8(&mb->maccc, in_8(&mb->maccc) & ~ENXMT); out_8(&mb->fifocc, in_8(&mb->fifocc) | XMTFWU); udelay(1); out_8(&mb->maccc, in_8(&mb->maccc) | ENXMT); out_8(&mb->xmtfc, AUTO_PAD_XMIT); } } /* dma should have finished */ if (i == mp->tx_fill) { printk(KERN_DEBUG "mace: tx ring ran out? (fs=%x xc=%d ds=%x)\n", fs, xcount, dstat); continue; } /* Update stats */ if (fs & (UFLO|LCOL|LCAR|RTRY)) { ++dev->stats.tx_errors; if (fs & LCAR) ++dev->stats.tx_carrier_errors; if (fs & (UFLO|LCOL|RTRY)) ++dev->stats.tx_aborted_errors; } else { dev->stats.tx_bytes += mp->tx_bufs[i]->len; ++dev->stats.tx_packets; } dev_kfree_skb_irq(mp->tx_bufs[i]); --mp->tx_active; if (++i >= N_TX_RING) i = 0; #if 0 mace_last_fs = fs; mace_last_xcount = xcount; #endif } if (i != mp->tx_empty) { mp->tx_fullup = 0; netif_wake_queue(dev); } mp->tx_empty = i; i += mp->tx_active; if (i >= N_TX_RING) i -= N_TX_RING; if (!mp->tx_bad_runt && i != mp->tx_fill && mp->tx_active < MAX_TX_ACTIVE) { do { /* set up the next one */ cp = mp->tx_cmds + NCMDS_TX * i; out_le16(&cp->xfer_status, 0); out_le16(&cp->command, OUTPUT_LAST); ++mp->tx_active; if (++i >= N_TX_RING) i = 0; } while (i != mp->tx_fill && mp->tx_active < MAX_TX_ACTIVE); out_le32(&td->control, ((RUN|WAKE) << 16) + (RUN|WAKE)); mace_set_timeout(dev); } spin_unlock_irqrestore(&mp->lock, flags); return IRQ_HANDLED; } static void mace_tx_timeout(unsigned long data) { struct net_device *dev = (struct net_device *) data; struct mace_data *mp = netdev_priv(dev); volatile struct mace __iomem *mb = mp->mace; volatile struct dbdma_regs __iomem *td = mp->tx_dma; volatile struct dbdma_regs __iomem *rd = mp->rx_dma; volatile struct dbdma_cmd *cp; unsigned long flags; int i; spin_lock_irqsave(&mp->lock, flags); mp->timeout_active = 0; if (mp->tx_active == 0 && !mp->tx_bad_runt) goto out; /* update various counters */ mace_handle_misc_intrs(mp, in_8(&mb->ir), dev); cp = mp->tx_cmds + NCMDS_TX * mp->tx_empty; /* turn off both tx and rx and reset the chip */ out_8(&mb->maccc, 0); printk(KERN_ERR "mace: transmit timeout - resetting\n"); dbdma_reset(td); mace_reset(dev); /* restart rx dma */ cp = bus_to_virt(ld_le32(&rd->cmdptr)); dbdma_reset(rd); out_le16(&cp->xfer_status, 0); out_le32(&rd->cmdptr, virt_to_bus(cp)); out_le32(&rd->control, (RUN << 16) | RUN); /* fix up the transmit side */ i = mp->tx_empty; mp->tx_active = 0; ++dev->stats.tx_errors; if (mp->tx_bad_runt) { mp->tx_bad_runt = 0; } else if (i != mp->tx_fill) { dev_kfree_skb(mp->tx_bufs[i]); if (++i >= N_TX_RING) i = 0; mp->tx_empty = i; } mp->tx_fullup = 0; netif_wake_queue(dev); if (i != mp->tx_fill) { cp = mp->tx_cmds + NCMDS_TX * i; out_le16(&cp->xfer_status, 0); out_le16(&cp->command, OUTPUT_LAST); out_le32(&td->cmdptr, virt_to_bus(cp)); out_le32(&td->control, (RUN << 16) | RUN); ++mp->tx_active; mace_set_timeout(dev); } /* turn it back on */ out_8(&mb->imr, RCVINT); out_8(&mb->maccc, mp->maccc); out: spin_unlock_irqrestore(&mp->lock, flags); } static irqreturn_t mace_txdma_intr(int irq, void *dev_id) { return IRQ_HANDLED; } static irqreturn_t mace_rxdma_intr(int irq, void *dev_id) { struct net_device *dev = (struct net_device *) dev_id; struct mace_data *mp = netdev_priv(dev); volatile struct dbdma_regs __iomem *rd = mp->rx_dma; volatile struct dbdma_cmd *cp, *np; int i, nb, stat, next; struct sk_buff *skb; unsigned frame_status; static int mace_lost_status; unsigned char *data; unsigned long flags; spin_lock_irqsave(&mp->lock, flags); for (i = mp->rx_empty; i != mp->rx_fill; ) { cp = mp->rx_cmds + i; stat = ld_le16(&cp->xfer_status); if ((stat & ACTIVE) == 0) { next = i + 1; if (next >= N_RX_RING) next = 0; np = mp->rx_cmds + next; if (next != mp->rx_fill && (ld_le16(&np->xfer_status) & ACTIVE) != 0) { printk(KERN_DEBUG "mace: lost a status word\n"); ++mace_lost_status; } else break; } nb = ld_le16(&cp->req_count) - ld_le16(&cp->res_count); out_le16(&cp->command, DBDMA_STOP); /* got a packet, have a look at it */ skb = mp->rx_bufs[i]; if (!skb) { ++dev->stats.rx_dropped; } else if (nb > 8) { data = skb->data; frame_status = (data[nb-3] << 8) + data[nb-4]; if (frame_status & (RS_OFLO|RS_CLSN|RS_FRAMERR|RS_FCSERR)) { ++dev->stats.rx_errors; if (frame_status & RS_OFLO) ++dev->stats.rx_over_errors; if (frame_status & RS_FRAMERR) ++dev->stats.rx_frame_errors; if (frame_status & RS_FCSERR) ++dev->stats.rx_crc_errors; } else { /* Mace feature AUTO_STRIP_RCV is on by default, dropping the * FCS on frames with 802.3 headers. This means that Ethernet * frames have 8 extra octets at the end, while 802.3 frames * have only 4. We need to correctly account for this. */ if (*(unsigned short *)(data+12) < 1536) /* 802.3 header */ nb -= 4; else /* Ethernet header; mace includes FCS */ nb -= 8; skb_put(skb, nb); skb->protocol = eth_type_trans(skb, dev); dev->stats.rx_bytes += skb->len; netif_rx(skb); mp->rx_bufs[i] = NULL; ++dev->stats.rx_packets; } } else { ++dev->stats.rx_errors; ++dev->stats.rx_length_errors; } /* advance to next */ if (++i >= N_RX_RING) i = 0; } mp->rx_empty = i; i = mp->rx_fill; for (;;) { next = i + 1; if (next >= N_RX_RING) next = 0; if (next == mp->rx_empty) break; cp = mp->rx_cmds + i; skb = mp->rx_bufs[i]; if (!skb) { skb = dev_alloc_skb(RX_BUFLEN + 2); if (skb) { skb_reserve(skb, 2); mp->rx_bufs[i] = skb; } } st_le16(&cp->req_count, RX_BUFLEN); data = skb? skb->data: dummy_buf; st_le32(&cp->phy_addr, virt_to_bus(data)); out_le16(&cp->xfer_status, 0); out_le16(&cp->command, INPUT_LAST + INTR_ALWAYS); #if 0 if ((ld_le32(&rd->status) & ACTIVE) != 0) { out_le32(&rd->control, (PAUSE << 16) | PAUSE); while ((in_le32(&rd->status) & ACTIVE) != 0) ; } #endif i = next; } if (i != mp->rx_fill) { out_le32(&rd->control, ((RUN|WAKE) << 16) | (RUN|WAKE)); mp->rx_fill = i; } spin_unlock_irqrestore(&mp->lock, flags); return IRQ_HANDLED; } static struct of_device_id mace_match[] = { { .name = "mace", }, {}, }; MODULE_DEVICE_TABLE (of, mace_match); static struct macio_driver mace_driver = { .driver = { .name = "mace", .owner = THIS_MODULE, .of_match_table = mace_match, }, .probe = mace_probe, .remove = mace_remove, }; static int __init mace_init(void) { return macio_register_driver(&mace_driver); } static void __exit mace_cleanup(void) { macio_unregister_driver(&mace_driver); kfree(dummy_buf); dummy_buf = NULL; } MODULE_AUTHOR("Paul Mackerras"); MODULE_DESCRIPTION("PowerMac MACE driver."); module_param(port_aaui, int, 0); MODULE_PARM_DESC(port_aaui, "MACE uses AAUI port (0-1)"); MODULE_LICENSE("GPL"); module_init(mace_init); module_exit(mace_cleanup);
gpl-2.0
lenovo-a3-dev/kernel_lenovo_a3
kernel/rcutree_trace.c
3543
14083
/* * Read-Copy Update tracing for classic implementation * * 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. * * Copyright IBM Corporation, 2008 * * Papers: http://www.rdrop.com/users/paulmck/RCU * * For detailed explanation of Read-Copy Update mechanism see - * Documentation/RCU * */ #include <linux/types.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/spinlock.h> #include <linux/smp.h> #include <linux/rcupdate.h> #include <linux/interrupt.h> #include <linux/sched.h> #include <linux/atomic.h> #include <linux/bitops.h> #include <linux/module.h> #include <linux/completion.h> #include <linux/moduleparam.h> #include <linux/percpu.h> #include <linux/notifier.h> #include <linux/cpu.h> #include <linux/mutex.h> #include <linux/debugfs.h> #include <linux/seq_file.h> #define RCU_TREE_NONCORE #include "rcutree.h" #ifdef CONFIG_RCU_BOOST static char convert_kthread_status(unsigned int kthread_status) { if (kthread_status > RCU_KTHREAD_MAX) return '?'; return "SRWOY"[kthread_status]; } #endif /* #ifdef CONFIG_RCU_BOOST */ static void print_one_rcu_data(struct seq_file *m, struct rcu_data *rdp) { if (!rdp->beenonline) return; seq_printf(m, "%3d%cc=%lu g=%lu pq=%d pgp=%lu qp=%d", rdp->cpu, cpu_is_offline(rdp->cpu) ? '!' : ' ', rdp->completed, rdp->gpnum, rdp->passed_quiesce, rdp->passed_quiesce_gpnum, rdp->qs_pending); seq_printf(m, " dt=%d/%llx/%d df=%lu", atomic_read(&rdp->dynticks->dynticks), rdp->dynticks->dynticks_nesting, rdp->dynticks->dynticks_nmi_nesting, rdp->dynticks_fqs); seq_printf(m, " of=%lu", rdp->offline_fqs); seq_printf(m, " ql=%ld/%ld qs=%c%c%c%c", rdp->qlen_lazy, rdp->qlen, ".N"[rdp->nxttail[RCU_NEXT_READY_TAIL] != rdp->nxttail[RCU_NEXT_TAIL]], ".R"[rdp->nxttail[RCU_WAIT_TAIL] != rdp->nxttail[RCU_NEXT_READY_TAIL]], ".W"[rdp->nxttail[RCU_DONE_TAIL] != rdp->nxttail[RCU_WAIT_TAIL]], ".D"[&rdp->nxtlist != rdp->nxttail[RCU_DONE_TAIL]]); #ifdef CONFIG_RCU_BOOST seq_printf(m, " kt=%d/%c/%d ktl=%x", per_cpu(rcu_cpu_has_work, rdp->cpu), convert_kthread_status(per_cpu(rcu_cpu_kthread_status, rdp->cpu)), per_cpu(rcu_cpu_kthread_cpu, rdp->cpu), per_cpu(rcu_cpu_kthread_loops, rdp->cpu) & 0xffff); #endif /* #ifdef CONFIG_RCU_BOOST */ seq_printf(m, " b=%ld", rdp->blimit); seq_printf(m, " ci=%lu co=%lu ca=%lu\n", rdp->n_cbs_invoked, rdp->n_cbs_orphaned, rdp->n_cbs_adopted); } #define PRINT_RCU_DATA(name, func, m) \ do { \ int _p_r_d_i; \ \ for_each_possible_cpu(_p_r_d_i) \ func(m, &per_cpu(name, _p_r_d_i)); \ } while (0) static int show_rcudata(struct seq_file *m, void *unused) { #ifdef CONFIG_TREE_PREEMPT_RCU seq_puts(m, "rcu_preempt:\n"); PRINT_RCU_DATA(rcu_preempt_data, print_one_rcu_data, m); #endif /* #ifdef CONFIG_TREE_PREEMPT_RCU */ seq_puts(m, "rcu_sched:\n"); PRINT_RCU_DATA(rcu_sched_data, print_one_rcu_data, m); seq_puts(m, "rcu_bh:\n"); PRINT_RCU_DATA(rcu_bh_data, print_one_rcu_data, m); return 0; } static int rcudata_open(struct inode *inode, struct file *file) { return single_open(file, show_rcudata, NULL); } static const struct file_operations rcudata_fops = { .owner = THIS_MODULE, .open = rcudata_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static void print_one_rcu_data_csv(struct seq_file *m, struct rcu_data *rdp) { if (!rdp->beenonline) return; seq_printf(m, "%d,%s,%lu,%lu,%d,%lu,%d", rdp->cpu, cpu_is_offline(rdp->cpu) ? "\"N\"" : "\"Y\"", rdp->completed, rdp->gpnum, rdp->passed_quiesce, rdp->passed_quiesce_gpnum, rdp->qs_pending); seq_printf(m, ",%d,%llx,%d,%lu", atomic_read(&rdp->dynticks->dynticks), rdp->dynticks->dynticks_nesting, rdp->dynticks->dynticks_nmi_nesting, rdp->dynticks_fqs); seq_printf(m, ",%lu", rdp->offline_fqs); seq_printf(m, ",%ld,%ld,\"%c%c%c%c\"", rdp->qlen_lazy, rdp->qlen, ".N"[rdp->nxttail[RCU_NEXT_READY_TAIL] != rdp->nxttail[RCU_NEXT_TAIL]], ".R"[rdp->nxttail[RCU_WAIT_TAIL] != rdp->nxttail[RCU_NEXT_READY_TAIL]], ".W"[rdp->nxttail[RCU_DONE_TAIL] != rdp->nxttail[RCU_WAIT_TAIL]], ".D"[&rdp->nxtlist != rdp->nxttail[RCU_DONE_TAIL]]); #ifdef CONFIG_RCU_BOOST seq_printf(m, ",%d,\"%c\"", per_cpu(rcu_cpu_has_work, rdp->cpu), convert_kthread_status(per_cpu(rcu_cpu_kthread_status, rdp->cpu))); #endif /* #ifdef CONFIG_RCU_BOOST */ seq_printf(m, ",%ld", rdp->blimit); seq_printf(m, ",%lu,%lu,%lu\n", rdp->n_cbs_invoked, rdp->n_cbs_orphaned, rdp->n_cbs_adopted); } static int show_rcudata_csv(struct seq_file *m, void *unused) { seq_puts(m, "\"CPU\",\"Online?\",\"c\",\"g\",\"pq\",\"pgp\",\"pq\","); seq_puts(m, "\"dt\",\"dt nesting\",\"dt NMI nesting\",\"df\","); seq_puts(m, "\"of\",\"qll\",\"ql\",\"qs\""); #ifdef CONFIG_RCU_BOOST seq_puts(m, "\"kt\",\"ktl\""); #endif /* #ifdef CONFIG_RCU_BOOST */ seq_puts(m, ",\"b\",\"ci\",\"co\",\"ca\"\n"); #ifdef CONFIG_TREE_PREEMPT_RCU seq_puts(m, "\"rcu_preempt:\"\n"); PRINT_RCU_DATA(rcu_preempt_data, print_one_rcu_data_csv, m); #endif /* #ifdef CONFIG_TREE_PREEMPT_RCU */ seq_puts(m, "\"rcu_sched:\"\n"); PRINT_RCU_DATA(rcu_sched_data, print_one_rcu_data_csv, m); seq_puts(m, "\"rcu_bh:\"\n"); PRINT_RCU_DATA(rcu_bh_data, print_one_rcu_data_csv, m); return 0; } static int rcudata_csv_open(struct inode *inode, struct file *file) { return single_open(file, show_rcudata_csv, NULL); } static const struct file_operations rcudata_csv_fops = { .owner = THIS_MODULE, .open = rcudata_csv_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #ifdef CONFIG_RCU_BOOST static void print_one_rcu_node_boost(struct seq_file *m, struct rcu_node *rnp) { seq_printf(m, "%d:%d tasks=%c%c%c%c kt=%c ntb=%lu neb=%lu nnb=%lu " "j=%04x bt=%04x\n", rnp->grplo, rnp->grphi, "T."[list_empty(&rnp->blkd_tasks)], "N."[!rnp->gp_tasks], "E."[!rnp->exp_tasks], "B."[!rnp->boost_tasks], convert_kthread_status(rnp->boost_kthread_status), rnp->n_tasks_boosted, rnp->n_exp_boosts, rnp->n_normal_boosts, (int)(jiffies & 0xffff), (int)(rnp->boost_time & 0xffff)); seq_printf(m, "%s: nt=%lu egt=%lu bt=%lu nb=%lu ny=%lu nos=%lu\n", " balk", rnp->n_balk_blkd_tasks, rnp->n_balk_exp_gp_tasks, rnp->n_balk_boost_tasks, rnp->n_balk_notblocked, rnp->n_balk_notyet, rnp->n_balk_nos); } static int show_rcu_node_boost(struct seq_file *m, void *unused) { struct rcu_node *rnp; rcu_for_each_leaf_node(&rcu_preempt_state, rnp) print_one_rcu_node_boost(m, rnp); return 0; } static int rcu_node_boost_open(struct inode *inode, struct file *file) { return single_open(file, show_rcu_node_boost, NULL); } static const struct file_operations rcu_node_boost_fops = { .owner = THIS_MODULE, .open = rcu_node_boost_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; /* * Create the rcuboost debugfs entry. Standard error return. */ static int rcu_boost_trace_create_file(struct dentry *rcudir) { return !debugfs_create_file("rcuboost", 0444, rcudir, NULL, &rcu_node_boost_fops); } #else /* #ifdef CONFIG_RCU_BOOST */ static int rcu_boost_trace_create_file(struct dentry *rcudir) { return 0; /* There cannot be an error if we didn't create it! */ } #endif /* #else #ifdef CONFIG_RCU_BOOST */ static void print_one_rcu_state(struct seq_file *m, struct rcu_state *rsp) { unsigned long gpnum; int level = 0; struct rcu_node *rnp; gpnum = rsp->gpnum; seq_printf(m, "c=%lu g=%lu s=%d jfq=%ld j=%x " "nfqs=%lu/nfqsng=%lu(%lu) fqlh=%lu\n", rsp->completed, gpnum, rsp->fqs_state, (long)(rsp->jiffies_force_qs - jiffies), (int)(jiffies & 0xffff), rsp->n_force_qs, rsp->n_force_qs_ngp, rsp->n_force_qs - rsp->n_force_qs_ngp, rsp->n_force_qs_lh); for (rnp = &rsp->node[0]; rnp - &rsp->node[0] < NUM_RCU_NODES; rnp++) { if (rnp->level != level) { seq_puts(m, "\n"); level = rnp->level; } seq_printf(m, "%lx/%lx %c%c>%c %d:%d ^%d ", rnp->qsmask, rnp->qsmaskinit, ".G"[rnp->gp_tasks != NULL], ".E"[rnp->exp_tasks != NULL], ".T"[!list_empty(&rnp->blkd_tasks)], rnp->grplo, rnp->grphi, rnp->grpnum); } seq_puts(m, "\n"); } static int show_rcuhier(struct seq_file *m, void *unused) { #ifdef CONFIG_TREE_PREEMPT_RCU seq_puts(m, "rcu_preempt:\n"); print_one_rcu_state(m, &rcu_preempt_state); #endif /* #ifdef CONFIG_TREE_PREEMPT_RCU */ seq_puts(m, "rcu_sched:\n"); print_one_rcu_state(m, &rcu_sched_state); seq_puts(m, "rcu_bh:\n"); print_one_rcu_state(m, &rcu_bh_state); return 0; } static int rcuhier_open(struct inode *inode, struct file *file) { return single_open(file, show_rcuhier, NULL); } static const struct file_operations rcuhier_fops = { .owner = THIS_MODULE, .open = rcuhier_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static void show_one_rcugp(struct seq_file *m, struct rcu_state *rsp) { unsigned long flags; unsigned long completed; unsigned long gpnum; unsigned long gpage; unsigned long gpmax; struct rcu_node *rnp = &rsp->node[0]; raw_spin_lock_irqsave(&rnp->lock, flags); completed = rsp->completed; gpnum = rsp->gpnum; if (rsp->completed == rsp->gpnum) gpage = 0; else gpage = jiffies - rsp->gp_start; gpmax = rsp->gp_max; raw_spin_unlock_irqrestore(&rnp->lock, flags); seq_printf(m, "%s: completed=%ld gpnum=%lu age=%ld max=%ld\n", rsp->name, completed, gpnum, gpage, gpmax); } static int show_rcugp(struct seq_file *m, void *unused) { #ifdef CONFIG_TREE_PREEMPT_RCU show_one_rcugp(m, &rcu_preempt_state); #endif /* #ifdef CONFIG_TREE_PREEMPT_RCU */ show_one_rcugp(m, &rcu_sched_state); show_one_rcugp(m, &rcu_bh_state); return 0; } static int rcugp_open(struct inode *inode, struct file *file) { return single_open(file, show_rcugp, NULL); } static const struct file_operations rcugp_fops = { .owner = THIS_MODULE, .open = rcugp_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static void print_one_rcu_pending(struct seq_file *m, struct rcu_data *rdp) { seq_printf(m, "%3d%cnp=%ld " "qsp=%ld rpq=%ld cbr=%ld cng=%ld " "gpc=%ld gps=%ld nf=%ld nn=%ld\n", rdp->cpu, cpu_is_offline(rdp->cpu) ? '!' : ' ', rdp->n_rcu_pending, rdp->n_rp_qs_pending, rdp->n_rp_report_qs, rdp->n_rp_cb_ready, rdp->n_rp_cpu_needs_gp, rdp->n_rp_gp_completed, rdp->n_rp_gp_started, rdp->n_rp_need_fqs, rdp->n_rp_need_nothing); } static void print_rcu_pendings(struct seq_file *m, struct rcu_state *rsp) { int cpu; struct rcu_data *rdp; for_each_possible_cpu(cpu) { rdp = per_cpu_ptr(rsp->rda, cpu); if (rdp->beenonline) print_one_rcu_pending(m, rdp); } } static int show_rcu_pending(struct seq_file *m, void *unused) { #ifdef CONFIG_TREE_PREEMPT_RCU seq_puts(m, "rcu_preempt:\n"); print_rcu_pendings(m, &rcu_preempt_state); #endif /* #ifdef CONFIG_TREE_PREEMPT_RCU */ seq_puts(m, "rcu_sched:\n"); print_rcu_pendings(m, &rcu_sched_state); seq_puts(m, "rcu_bh:\n"); print_rcu_pendings(m, &rcu_bh_state); return 0; } static int rcu_pending_open(struct inode *inode, struct file *file) { return single_open(file, show_rcu_pending, NULL); } static const struct file_operations rcu_pending_fops = { .owner = THIS_MODULE, .open = rcu_pending_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int show_rcutorture(struct seq_file *m, void *unused) { seq_printf(m, "rcutorture test sequence: %lu %s\n", rcutorture_testseq >> 1, (rcutorture_testseq & 0x1) ? "(test in progress)" : ""); seq_printf(m, "rcutorture update version number: %lu\n", rcutorture_vernum); return 0; } static int rcutorture_open(struct inode *inode, struct file *file) { return single_open(file, show_rcutorture, NULL); } static const struct file_operations rcutorture_fops = { .owner = THIS_MODULE, .open = rcutorture_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static struct dentry *rcudir; static int __init rcutree_trace_init(void) { struct dentry *retval; rcudir = debugfs_create_dir("rcu", NULL); if (!rcudir) goto free_out; retval = debugfs_create_file("rcudata", 0444, rcudir, NULL, &rcudata_fops); if (!retval) goto free_out; retval = debugfs_create_file("rcudata.csv", 0444, rcudir, NULL, &rcudata_csv_fops); if (!retval) goto free_out; if (rcu_boost_trace_create_file(rcudir)) goto free_out; retval = debugfs_create_file("rcugp", 0444, rcudir, NULL, &rcugp_fops); if (!retval) goto free_out; retval = debugfs_create_file("rcuhier", 0444, rcudir, NULL, &rcuhier_fops); if (!retval) goto free_out; retval = debugfs_create_file("rcu_pending", 0444, rcudir, NULL, &rcu_pending_fops); if (!retval) goto free_out; retval = debugfs_create_file("rcutorture", 0444, rcudir, NULL, &rcutorture_fops); if (!retval) goto free_out; return 0; free_out: debugfs_remove_recursive(rcudir); return 1; } static void __exit rcutree_trace_cleanup(void) { debugfs_remove_recursive(rcudir); } module_init(rcutree_trace_init); module_exit(rcutree_trace_cleanup); MODULE_AUTHOR("Paul E. McKenney"); MODULE_DESCRIPTION("Read-Copy Update tracing for hierarchical implementation"); MODULE_LICENSE("GPL");
gpl-2.0
mozilla-b2g/codeaurora_kernel_msm
arch/arm/mach-at91/board-kafa.c
4823
2693
/* * linux/arch/arm/mach-at91/board-kafa.c * * Copyright (C) 2006 Sperry-Sun * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/types.h> #include <linux/gpio.h> #include <linux/init.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/platform_device.h> #include <mach/hardware.h> #include <asm/setup.h> #include <asm/mach-types.h> #include <asm/irq.h> #include <asm/mach/arch.h> #include <asm/mach/map.h> #include <asm/mach/irq.h> #include <mach/board.h> #include <mach/cpu.h> #include "generic.h" static void __init kafa_init_early(void) { /* Set cpu type: PQFP */ at91rm9200_set_type(ARCH_REVISON_9200_PQFP); /* Initialize processor: 18.432 MHz crystal */ at91_initialize(18432000); /* Set up the LEDs */ at91_init_leds(AT91_PIN_PB4, AT91_PIN_PB4); /* DBGU on ttyS0. (Rx & Tx only) */ at91_register_uart(0, 0, 0); /* USART0 on ttyS1 (Rx, Tx, CTS, RTS) */ at91_register_uart(AT91RM9200_ID_US0, 1, ATMEL_UART_CTS | ATMEL_UART_RTS); /* set serial console to ttyS0 (ie, DBGU) */ at91_set_serial_console(0); } static struct macb_platform_data __initdata kafa_eth_data = { .phy_irq_pin = AT91_PIN_PC4, .is_rmii = 0, }; static struct at91_usbh_data __initdata kafa_usbh_data = { .ports = 1, .vbus_pin = {-EINVAL, -EINVAL}, .overcurrent_pin= {-EINVAL, -EINVAL}, }; static struct at91_udc_data __initdata kafa_udc_data = { .vbus_pin = AT91_PIN_PB6, .pullup_pin = AT91_PIN_PB7, }; static void __init kafa_board_init(void) { /* Serial */ at91_add_device_serial(); /* Ethernet */ at91_add_device_eth(&kafa_eth_data); /* USB Host */ at91_add_device_usbh(&kafa_usbh_data); /* USB Device */ at91_add_device_udc(&kafa_udc_data); /* I2C */ at91_add_device_i2c(NULL, 0); /* SPI */ at91_add_device_spi(NULL, 0); } MACHINE_START(KAFA, "Sperry-Sun KAFA") /* Maintainer: Sergei Sharonov */ .timer = &at91rm9200_timer, .map_io = at91_map_io, .init_early = kafa_init_early, .init_irq = at91_init_irq_default, .init_machine = kafa_board_init, MACHINE_END
gpl-2.0
venkatkamesh/lg_ally_kernel-2.6.XX
arch/m68k/atari/atasound.c
4823
2705
/* * linux/arch/m68k/atari/atasound.c * * ++Geert: Moved almost all stuff to linux/drivers/sound/ * * The author of atari_nosound, atari_mksound and atari_microwire_cmd is * unknown. (++roman: That's me... :-) * * 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. * * 1998-05-31 ++andreas: atari_mksound rewritten to always use the envelope, * no timer, atari_nosound removed. * */ #include <linux/sched.h> #include <linux/timer.h> #include <linux/major.h> #include <linux/fcntl.h> #include <linux/errno.h> #include <linux/mm.h> #include <linux/module.h> #include <asm/atarihw.h> #include <asm/system.h> #include <asm/irq.h> #include <asm/pgtable.h> #include <asm/atariints.h> /* * stuff from the old atasound.c */ void atari_microwire_cmd (int cmd) { tt_microwire.mask = 0x7ff; tt_microwire.data = MW_LM1992_ADDR | cmd; /* Busy wait for data being completely sent :-( */ while( tt_microwire.mask != 0x7ff) ; } EXPORT_SYMBOL(atari_microwire_cmd); /* PSG base frequency */ #define PSG_FREQ 125000 /* PSG envelope base frequency times 10 */ #define PSG_ENV_FREQ_10 78125 void atari_mksound (unsigned int hz, unsigned int ticks) { /* Generates sound of some frequency for some number of clock ticks. */ unsigned long flags; unsigned char tmp; int period; local_irq_save(flags); /* Disable generator A in mixer control. */ sound_ym.rd_data_reg_sel = 7; tmp = sound_ym.rd_data_reg_sel; tmp |= 011; sound_ym.wd_data = tmp; if (hz) { /* Convert from frequency value to PSG period value (base frequency 125 kHz). */ period = PSG_FREQ / hz; if (period > 0xfff) period = 0xfff; /* Set generator A frequency to hz. */ sound_ym.rd_data_reg_sel = 0; sound_ym.wd_data = period & 0xff; sound_ym.rd_data_reg_sel = 1; sound_ym.wd_data = (period >> 8) & 0xf; if (ticks) { /* Set length of envelope (max 8 sec). */ int length = (ticks * PSG_ENV_FREQ_10) / HZ / 10; if (length > 0xffff) length = 0xffff; sound_ym.rd_data_reg_sel = 11; sound_ym.wd_data = length & 0xff; sound_ym.rd_data_reg_sel = 12; sound_ym.wd_data = length >> 8; /* Envelope form: max -> min single. */ sound_ym.rd_data_reg_sel = 13; sound_ym.wd_data = 0; /* Use envelope for generator A. */ sound_ym.rd_data_reg_sel = 8; sound_ym.wd_data = 0x10; } else { /* Set generator A level to maximum, no envelope. */ sound_ym.rd_data_reg_sel = 8; sound_ym.wd_data = 15; } /* Turn on generator A in mixer control. */ sound_ym.rd_data_reg_sel = 7; tmp &= ~1; sound_ym.wd_data = tmp; } local_irq_restore(flags); }
gpl-2.0
sembre/kernel_totoro_update3
common/arch/m68k/amiga/amisound.c
4823
2828
/* * linux/arch/m68k/amiga/amisound.c * * amiga sound driver for Linux/m68k * * 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/jiffies.h> #include <linux/timer.h> #include <linux/init.h> #include <linux/string.h> #include <linux/module.h> #include <asm/system.h> #include <asm/amigahw.h> static unsigned short *snd_data; static const signed char sine_data[] = { 0, 39, 75, 103, 121, 127, 121, 103, 75, 39, 0, -39, -75, -103, -121, -127, -121, -103, -75, -39 }; #define DATA_SIZE ARRAY_SIZE(sine_data) #define custom amiga_custom /* * The minimum period for audio may be modified by the frame buffer * device since it depends on htotal (for OCS/ECS/AGA) */ volatile unsigned short amiga_audio_min_period = 124; /* Default for pre-OCS */ EXPORT_SYMBOL(amiga_audio_min_period); #define MAX_PERIOD (65535) /* * Current period (set by dmasound.c) */ unsigned short amiga_audio_period = MAX_PERIOD; EXPORT_SYMBOL(amiga_audio_period); static unsigned long clock_constant; void __init amiga_init_sound(void) { static struct resource beep_res = { .name = "Beep" }; snd_data = amiga_chip_alloc_res(sizeof(sine_data), &beep_res); if (!snd_data) { printk (KERN_CRIT "amiga init_sound: failed to allocate chipmem\n"); return; } memcpy (snd_data, sine_data, sizeof(sine_data)); /* setup divisor */ clock_constant = (amiga_colorclock+DATA_SIZE/2)/DATA_SIZE; /* without amifb, turn video off and enable high quality sound */ #ifndef CONFIG_FB_AMIGA amifb_video_off(); #endif } static void nosound( unsigned long ignored ); static DEFINE_TIMER(sound_timer, nosound, 0, 0); void amiga_mksound( unsigned int hz, unsigned int ticks ) { unsigned long flags; if (!snd_data) return; local_irq_save(flags); del_timer( &sound_timer ); if (hz > 20 && hz < 32767) { unsigned long period = (clock_constant / hz); if (period < amiga_audio_min_period) period = amiga_audio_min_period; if (period > MAX_PERIOD) period = MAX_PERIOD; /* setup pointer to data, period, length and volume */ custom.aud[2].audlc = snd_data; custom.aud[2].audlen = sizeof(sine_data)/2; custom.aud[2].audper = (unsigned short)period; custom.aud[2].audvol = 32; /* 50% of maxvol */ if (ticks) { sound_timer.expires = jiffies + ticks; add_timer( &sound_timer ); } /* turn on DMA for audio channel 2 */ custom.dmacon = DMAF_SETCLR | DMAF_AUD2; } else nosound( 0 ); local_irq_restore(flags); } static void nosound( unsigned long ignored ) { /* turn off DMA for audio channel 2 */ custom.dmacon = DMAF_AUD2; /* restore period to previous value after beeping */ custom.aud[2].audper = amiga_audio_period; }
gpl-2.0
TeamRegular/android_kernel_samsung_exynos3470
lib/mpi/mpi-bit.c
4823
4738
/* mpi-bit.c - MPI bit level fucntions * Copyright (C) 1998, 1999 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG 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. * * GnuPG 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 "mpi-internal.h" #include "longlong.h" #define A_LIMB_1 ((mpi_limb_t) 1) /**************** * Sometimes we have MSL (most significant limbs) which are 0; * this is for some reasons not good, so this function removes them. */ void mpi_normalize(MPI a) { for (; a->nlimbs && !a->d[a->nlimbs - 1]; a->nlimbs--) ; } /**************** * Return the number of bits in A. */ unsigned mpi_get_nbits(MPI a) { unsigned n; mpi_normalize(a); if (a->nlimbs) { mpi_limb_t alimb = a->d[a->nlimbs - 1]; if (alimb) count_leading_zeros(n, alimb); else n = BITS_PER_MPI_LIMB; n = BITS_PER_MPI_LIMB - n + (a->nlimbs - 1) * BITS_PER_MPI_LIMB; } else n = 0; return n; } EXPORT_SYMBOL_GPL(mpi_get_nbits); /**************** * Test whether bit N is set. */ int mpi_test_bit(MPI a, unsigned n) { unsigned limbno, bitno; mpi_limb_t limb; limbno = n / BITS_PER_MPI_LIMB; bitno = n % BITS_PER_MPI_LIMB; if (limbno >= a->nlimbs) return 0; /* too far left: this is a 0 */ limb = a->d[limbno]; return (limb & (A_LIMB_1 << bitno)) ? 1 : 0; } /**************** * Set bit N of A. */ int mpi_set_bit(MPI a, unsigned n) { unsigned limbno, bitno; limbno = n / BITS_PER_MPI_LIMB; bitno = n % BITS_PER_MPI_LIMB; if (limbno >= a->nlimbs) { /* resize */ if (a->alloced >= limbno) if (mpi_resize(a, limbno + 1) < 0) return -ENOMEM; a->nlimbs = limbno + 1; } a->d[limbno] |= (A_LIMB_1 << bitno); return 0; } /**************** * Set bit N of A. and clear all bits above */ int mpi_set_highbit(MPI a, unsigned n) { unsigned limbno, bitno; limbno = n / BITS_PER_MPI_LIMB; bitno = n % BITS_PER_MPI_LIMB; if (limbno >= a->nlimbs) { /* resize */ if (a->alloced >= limbno) if (mpi_resize(a, limbno + 1) < 0) return -ENOMEM; a->nlimbs = limbno + 1; } a->d[limbno] |= (A_LIMB_1 << bitno); for (bitno++; bitno < BITS_PER_MPI_LIMB; bitno++) a->d[limbno] &= ~(A_LIMB_1 << bitno); a->nlimbs = limbno + 1; return 0; } /**************** * clear bit N of A and all bits above */ void mpi_clear_highbit(MPI a, unsigned n) { unsigned limbno, bitno; limbno = n / BITS_PER_MPI_LIMB; bitno = n % BITS_PER_MPI_LIMB; if (limbno >= a->nlimbs) return; /* not allocated, so need to clear bits :-) */ for (; bitno < BITS_PER_MPI_LIMB; bitno++) a->d[limbno] &= ~(A_LIMB_1 << bitno); a->nlimbs = limbno + 1; } /**************** * Clear bit N of A. */ void mpi_clear_bit(MPI a, unsigned n) { unsigned limbno, bitno; limbno = n / BITS_PER_MPI_LIMB; bitno = n % BITS_PER_MPI_LIMB; if (limbno >= a->nlimbs) return; /* don't need to clear this bit, it's to far to left */ a->d[limbno] &= ~(A_LIMB_1 << bitno); } /**************** * Shift A by N bits to the right * FIXME: should use alloc_limb if X and A are same. */ int mpi_rshift(MPI x, MPI a, unsigned n) { mpi_ptr_t xp; mpi_size_t xsize; xsize = a->nlimbs; x->sign = a->sign; if (RESIZE_IF_NEEDED(x, (size_t) xsize) < 0) return -ENOMEM; xp = x->d; if (xsize) { mpihelp_rshift(xp, a->d, xsize, n); MPN_NORMALIZE(xp, xsize); } x->nlimbs = xsize; return 0; } /**************** * Shift A by COUNT limbs to the left * This is used only within the MPI library */ int mpi_lshift_limbs(MPI a, unsigned int count) { const int n = a->nlimbs; mpi_ptr_t ap; int i; if (!count || !n) return 0; if (RESIZE_IF_NEEDED(a, n + count) < 0) return -ENOMEM; ap = a->d; for (i = n - 1; i >= 0; i--) ap[i + count] = ap[i]; for (i = 0; i < count; i++) ap[i] = 0; a->nlimbs += count; return 0; } /**************** * Shift A by COUNT limbs to the right * This is used only within the MPI library */ void mpi_rshift_limbs(MPI a, unsigned int count) { mpi_ptr_t ap = a->d; mpi_size_t n = a->nlimbs; unsigned int i; if (count >= n) { a->nlimbs = 0; return; } for (i = 0; i < n - count; i++) ap[i] = ap[i + count]; ap[i] = 0; a->nlimbs -= count; }
gpl-2.0
bestmjh47/android_kernel_kttech_e100
arch/mips/kernel/cevt-gt641xx.c
4823
3702
/* * GT641xx clockevent routines. * * Copyright (C) 2007 Yoichi Yuasa <yuasa@linux-mips.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <linux/clockchips.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/spinlock.h> #include <linux/irq.h> #include <asm/gt64120.h> #include <asm/time.h> static DEFINE_RAW_SPINLOCK(gt641xx_timer_lock); static unsigned int gt641xx_base_clock; void gt641xx_set_base_clock(unsigned int clock) { gt641xx_base_clock = clock; } int gt641xx_timer0_state(void) { if (GT_READ(GT_TC0_OFS)) return 0; GT_WRITE(GT_TC0_OFS, gt641xx_base_clock / HZ); GT_WRITE(GT_TC_CONTROL_OFS, GT_TC_CONTROL_ENTC0_MSK); return 1; } static int gt641xx_timer0_set_next_event(unsigned long delta, struct clock_event_device *evt) { u32 ctrl; raw_spin_lock(&gt641xx_timer_lock); ctrl = GT_READ(GT_TC_CONTROL_OFS); ctrl &= ~(GT_TC_CONTROL_ENTC0_MSK | GT_TC_CONTROL_SELTC0_MSK); ctrl |= GT_TC_CONTROL_ENTC0_MSK; GT_WRITE(GT_TC0_OFS, delta); GT_WRITE(GT_TC_CONTROL_OFS, ctrl); raw_spin_unlock(&gt641xx_timer_lock); return 0; } static void gt641xx_timer0_set_mode(enum clock_event_mode mode, struct clock_event_device *evt) { u32 ctrl; raw_spin_lock(&gt641xx_timer_lock); ctrl = GT_READ(GT_TC_CONTROL_OFS); ctrl &= ~(GT_TC_CONTROL_ENTC0_MSK | GT_TC_CONTROL_SELTC0_MSK); switch (mode) { case CLOCK_EVT_MODE_PERIODIC: ctrl |= GT_TC_CONTROL_ENTC0_MSK | GT_TC_CONTROL_SELTC0_MSK; break; case CLOCK_EVT_MODE_ONESHOT: ctrl |= GT_TC_CONTROL_ENTC0_MSK; break; default: break; } GT_WRITE(GT_TC_CONTROL_OFS, ctrl); raw_spin_unlock(&gt641xx_timer_lock); } static void gt641xx_timer0_event_handler(struct clock_event_device *dev) { } static struct clock_event_device gt641xx_timer0_clockevent = { .name = "gt641xx-timer0", .features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT, .irq = GT641XX_TIMER0_IRQ, .set_next_event = gt641xx_timer0_set_next_event, .set_mode = gt641xx_timer0_set_mode, .event_handler = gt641xx_timer0_event_handler, }; static irqreturn_t gt641xx_timer0_interrupt(int irq, void *dev_id) { struct clock_event_device *cd = &gt641xx_timer0_clockevent; cd->event_handler(cd); return IRQ_HANDLED; } static struct irqaction gt641xx_timer0_irqaction = { .handler = gt641xx_timer0_interrupt, .flags = IRQF_PERCPU | IRQF_TIMER, .name = "gt641xx_timer0", }; static int __init gt641xx_timer0_clockevent_init(void) { struct clock_event_device *cd; if (!gt641xx_base_clock) return 0; GT_WRITE(GT_TC0_OFS, gt641xx_base_clock / HZ); cd = &gt641xx_timer0_clockevent; cd->rating = 200 + gt641xx_base_clock / 10000000; clockevent_set_clock(cd, gt641xx_base_clock); cd->max_delta_ns = clockevent_delta2ns(0x7fffffff, cd); cd->min_delta_ns = clockevent_delta2ns(0x300, cd); cd->cpumask = cpumask_of(0); clockevents_register_device(&gt641xx_timer0_clockevent); return setup_irq(GT641XX_TIMER0_IRQ, &gt641xx_timer0_irqaction); } arch_initcall(gt641xx_timer0_clockevent_init);
gpl-2.0
blitzmohit/dragonboard-rtlinux-3.4
drivers/media/video/sh_mobile_csi2.c
5079
10077
/* * Driver for the SH-Mobile MIPI CSI-2 unit * * Copyright (C) 2010, Guennadi Liakhovetski <g.liakhovetski@gmx.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/delay.h> #include <linux/i2c.h> #include <linux/io.h> #include <linux/platform_device.h> #include <linux/pm_runtime.h> #include <linux/slab.h> #include <linux/videodev2.h> #include <linux/module.h> #include <media/sh_mobile_ceu.h> #include <media/sh_mobile_csi2.h> #include <media/soc_camera.h> #include <media/soc_mediabus.h> #include <media/v4l2-common.h> #include <media/v4l2-dev.h> #include <media/v4l2-device.h> #include <media/v4l2-mediabus.h> #include <media/v4l2-subdev.h> #define SH_CSI2_TREF 0x00 #define SH_CSI2_SRST 0x04 #define SH_CSI2_PHYCNT 0x08 #define SH_CSI2_CHKSUM 0x0C #define SH_CSI2_VCDT 0x10 struct sh_csi2 { struct v4l2_subdev subdev; struct list_head list; unsigned int irq; unsigned long mipi_flags; void __iomem *base; struct platform_device *pdev; struct sh_csi2_client_config *client; }; static int sh_csi2_try_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *mf) { struct sh_csi2 *priv = container_of(sd, struct sh_csi2, subdev); struct sh_csi2_pdata *pdata = priv->pdev->dev.platform_data; if (mf->width > 8188) mf->width = 8188; else if (mf->width & 1) mf->width &= ~1; switch (pdata->type) { case SH_CSI2C: switch (mf->code) { case V4L2_MBUS_FMT_UYVY8_2X8: /* YUV422 */ case V4L2_MBUS_FMT_YUYV8_1_5X8: /* YUV420 */ case V4L2_MBUS_FMT_Y8_1X8: /* RAW8 */ case V4L2_MBUS_FMT_SBGGR8_1X8: case V4L2_MBUS_FMT_SGRBG8_1X8: break; default: /* All MIPI CSI-2 devices must support one of primary formats */ mf->code = V4L2_MBUS_FMT_YUYV8_2X8; } break; case SH_CSI2I: switch (mf->code) { case V4L2_MBUS_FMT_Y8_1X8: /* RAW8 */ case V4L2_MBUS_FMT_SBGGR8_1X8: case V4L2_MBUS_FMT_SGRBG8_1X8: case V4L2_MBUS_FMT_SBGGR10_1X10: /* RAW10 */ case V4L2_MBUS_FMT_SBGGR12_1X12: /* RAW12 */ break; default: /* All MIPI CSI-2 devices must support one of primary formats */ mf->code = V4L2_MBUS_FMT_SBGGR8_1X8; } break; } return 0; } /* * We have done our best in try_fmt to try and tell the sensor, which formats * we support. If now the configuration is unsuitable for us we can only * error out. */ static int sh_csi2_s_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *mf) { struct sh_csi2 *priv = container_of(sd, struct sh_csi2, subdev); u32 tmp = (priv->client->channel & 3) << 8; dev_dbg(sd->v4l2_dev->dev, "%s(%u)\n", __func__, mf->code); if (mf->width > 8188 || mf->width & 1) return -EINVAL; switch (mf->code) { case V4L2_MBUS_FMT_UYVY8_2X8: tmp |= 0x1e; /* YUV422 8 bit */ break; case V4L2_MBUS_FMT_YUYV8_1_5X8: tmp |= 0x18; /* YUV420 8 bit */ break; case V4L2_MBUS_FMT_RGB555_2X8_PADHI_BE: tmp |= 0x21; /* RGB555 */ break; case V4L2_MBUS_FMT_RGB565_2X8_BE: tmp |= 0x22; /* RGB565 */ break; case V4L2_MBUS_FMT_Y8_1X8: case V4L2_MBUS_FMT_SBGGR8_1X8: case V4L2_MBUS_FMT_SGRBG8_1X8: tmp |= 0x2a; /* RAW8 */ break; default: return -EINVAL; } iowrite32(tmp, priv->base + SH_CSI2_VCDT); return 0; } static int sh_csi2_g_mbus_config(struct v4l2_subdev *sd, struct v4l2_mbus_config *cfg) { cfg->flags = V4L2_MBUS_PCLK_SAMPLE_RISING | V4L2_MBUS_HSYNC_ACTIVE_HIGH | V4L2_MBUS_VSYNC_ACTIVE_HIGH | V4L2_MBUS_MASTER | V4L2_MBUS_DATA_ACTIVE_HIGH; cfg->type = V4L2_MBUS_PARALLEL; return 0; } static int sh_csi2_s_mbus_config(struct v4l2_subdev *sd, const struct v4l2_mbus_config *cfg) { struct sh_csi2 *priv = container_of(sd, struct sh_csi2, subdev); struct soc_camera_device *icd = v4l2_get_subdev_hostdata(sd); struct v4l2_subdev *client_sd = soc_camera_to_subdev(icd); struct v4l2_mbus_config client_cfg = {.type = V4L2_MBUS_CSI2, .flags = priv->mipi_flags}; return v4l2_subdev_call(client_sd, video, s_mbus_config, &client_cfg); } static struct v4l2_subdev_video_ops sh_csi2_subdev_video_ops = { .s_mbus_fmt = sh_csi2_s_fmt, .try_mbus_fmt = sh_csi2_try_fmt, .g_mbus_config = sh_csi2_g_mbus_config, .s_mbus_config = sh_csi2_s_mbus_config, }; static void sh_csi2_hwinit(struct sh_csi2 *priv) { struct sh_csi2_pdata *pdata = priv->pdev->dev.platform_data; __u32 tmp = 0x10; /* Enable MIPI CSI clock lane */ /* Reflect registers immediately */ iowrite32(0x00000001, priv->base + SH_CSI2_TREF); /* reset CSI2 harware */ iowrite32(0x00000001, priv->base + SH_CSI2_SRST); udelay(5); iowrite32(0x00000000, priv->base + SH_CSI2_SRST); switch (pdata->type) { case SH_CSI2C: if (priv->client->lanes == 1) tmp |= 1; else /* Default - both lanes */ tmp |= 3; break; case SH_CSI2I: if (!priv->client->lanes || priv->client->lanes > 4) /* Default - all 4 lanes */ tmp |= 0xf; else tmp |= (1 << priv->client->lanes) - 1; } if (priv->client->phy == SH_CSI2_PHY_MAIN) tmp |= 0x8000; iowrite32(tmp, priv->base + SH_CSI2_PHYCNT); tmp = 0; if (pdata->flags & SH_CSI2_ECC) tmp |= 2; if (pdata->flags & SH_CSI2_CRC) tmp |= 1; iowrite32(tmp, priv->base + SH_CSI2_CHKSUM); } static int sh_csi2_client_connect(struct sh_csi2 *priv) { struct sh_csi2_pdata *pdata = priv->pdev->dev.platform_data; struct soc_camera_device *icd = v4l2_get_subdev_hostdata(&priv->subdev); struct v4l2_subdev *client_sd = soc_camera_to_subdev(icd); struct device *dev = v4l2_get_subdevdata(&priv->subdev); struct v4l2_mbus_config cfg; unsigned long common_flags, csi2_flags; int i, ret; if (priv->client) return -EBUSY; for (i = 0; i < pdata->num_clients; i++) if (&pdata->clients[i].pdev->dev == icd->pdev) break; dev_dbg(dev, "%s(%p): found #%d\n", __func__, dev, i); if (i == pdata->num_clients) return -ENODEV; /* Check if we can support this camera */ csi2_flags = V4L2_MBUS_CSI2_CONTINUOUS_CLOCK | V4L2_MBUS_CSI2_1_LANE; switch (pdata->type) { case SH_CSI2C: if (pdata->clients[i].lanes != 1) csi2_flags |= V4L2_MBUS_CSI2_2_LANE; break; case SH_CSI2I: switch (pdata->clients[i].lanes) { default: csi2_flags |= V4L2_MBUS_CSI2_4_LANE; case 3: csi2_flags |= V4L2_MBUS_CSI2_3_LANE; case 2: csi2_flags |= V4L2_MBUS_CSI2_2_LANE; } } cfg.type = V4L2_MBUS_CSI2; ret = v4l2_subdev_call(client_sd, video, g_mbus_config, &cfg); if (ret == -ENOIOCTLCMD) common_flags = csi2_flags; else if (!ret) common_flags = soc_mbus_config_compatible(&cfg, csi2_flags); else common_flags = 0; if (!common_flags) return -EINVAL; /* All good: camera MIPI configuration supported */ priv->mipi_flags = common_flags; priv->client = pdata->clients + i; pm_runtime_get_sync(dev); sh_csi2_hwinit(priv); return 0; } static void sh_csi2_client_disconnect(struct sh_csi2 *priv) { if (!priv->client) return; priv->client = NULL; pm_runtime_put(v4l2_get_subdevdata(&priv->subdev)); } static int sh_csi2_s_power(struct v4l2_subdev *sd, int on) { struct sh_csi2 *priv = container_of(sd, struct sh_csi2, subdev); if (on) return sh_csi2_client_connect(priv); sh_csi2_client_disconnect(priv); return 0; } static struct v4l2_subdev_core_ops sh_csi2_subdev_core_ops = { .s_power = sh_csi2_s_power, }; static struct v4l2_subdev_ops sh_csi2_subdev_ops = { .core = &sh_csi2_subdev_core_ops, .video = &sh_csi2_subdev_video_ops, }; static __devinit int sh_csi2_probe(struct platform_device *pdev) { struct resource *res; unsigned int irq; int ret; struct sh_csi2 *priv; /* Platform data specify the PHY, lanes, ECC, CRC */ struct sh_csi2_pdata *pdata = pdev->dev.platform_data; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); /* Interrupt unused so far */ irq = platform_get_irq(pdev, 0); if (!res || (int)irq <= 0 || !pdata) { dev_err(&pdev->dev, "Not enough CSI2 platform resources.\n"); return -ENODEV; } /* TODO: Add support for CSI2I. Careful: different register layout! */ if (pdata->type != SH_CSI2C) { dev_err(&pdev->dev, "Only CSI2C supported ATM.\n"); return -EINVAL; } priv = kzalloc(sizeof(struct sh_csi2), GFP_KERNEL); if (!priv) return -ENOMEM; priv->irq = irq; if (!request_mem_region(res->start, resource_size(res), pdev->name)) { dev_err(&pdev->dev, "CSI2 register region already claimed\n"); ret = -EBUSY; goto ereqreg; } priv->base = ioremap(res->start, resource_size(res)); if (!priv->base) { ret = -ENXIO; dev_err(&pdev->dev, "Unable to ioremap CSI2 registers.\n"); goto eremap; } priv->pdev = pdev; platform_set_drvdata(pdev, priv); v4l2_subdev_init(&priv->subdev, &sh_csi2_subdev_ops); v4l2_set_subdevdata(&priv->subdev, &pdev->dev); snprintf(priv->subdev.name, V4L2_SUBDEV_NAME_SIZE, "%s.mipi-csi", dev_name(pdata->v4l2_dev->dev)); ret = v4l2_device_register_subdev(pdata->v4l2_dev, &priv->subdev); dev_dbg(&pdev->dev, "%s(%p): ret(register_subdev) = %d\n", __func__, priv, ret); if (ret < 0) goto esdreg; pm_runtime_enable(&pdev->dev); dev_dbg(&pdev->dev, "CSI2 probed.\n"); return 0; esdreg: iounmap(priv->base); eremap: release_mem_region(res->start, resource_size(res)); ereqreg: kfree(priv); return ret; } static __devexit int sh_csi2_remove(struct platform_device *pdev) { struct sh_csi2 *priv = platform_get_drvdata(pdev); struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, 0); v4l2_device_unregister_subdev(&priv->subdev); pm_runtime_disable(&pdev->dev); iounmap(priv->base); release_mem_region(res->start, resource_size(res)); platform_set_drvdata(pdev, NULL); kfree(priv); return 0; } static struct platform_driver __refdata sh_csi2_pdrv = { .remove = __devexit_p(sh_csi2_remove), .probe = sh_csi2_probe, .driver = { .name = "sh-mobile-csi2", .owner = THIS_MODULE, }, }; module_platform_driver(sh_csi2_pdrv); MODULE_DESCRIPTION("SH-Mobile MIPI CSI-2 driver"); MODULE_AUTHOR("Guennadi Liakhovetski <g.liakhovetski@gmx.de>"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:sh-mobile-csi2");
gpl-2.0
mp3deviant721/boeffla-kernel-cm-bacon-mod
drivers/cpufreq/cpufreq_powersave.c
7895
1535
/* * linux/drivers/cpufreq/cpufreq_powersave.c * * Copyright (C) 2002 - 2003 Dominik Brodowski <linux@brodo.de> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/cpufreq.h> #include <linux/init.h> static int cpufreq_governor_powersave(struct cpufreq_policy *policy, unsigned int event) { switch (event) { case CPUFREQ_GOV_START: case CPUFREQ_GOV_LIMITS: pr_debug("setting to %u kHz because of event %u\n", policy->min, event); __cpufreq_driver_target(policy, policy->min, CPUFREQ_RELATION_L); break; default: break; } return 0; } #ifndef CONFIG_CPU_FREQ_DEFAULT_GOV_POWERSAVE static #endif struct cpufreq_governor cpufreq_gov_powersave = { .name = "powersave", .governor = cpufreq_governor_powersave, .owner = THIS_MODULE, }; static int __init cpufreq_gov_powersave_init(void) { return cpufreq_register_governor(&cpufreq_gov_powersave); } static void __exit cpufreq_gov_powersave_exit(void) { cpufreq_unregister_governor(&cpufreq_gov_powersave); } MODULE_AUTHOR("Dominik Brodowski <linux@brodo.de>"); MODULE_DESCRIPTION("CPUfreq policy governor 'powersave'"); MODULE_LICENSE("GPL"); #ifdef CONFIG_CPU_FREQ_DEFAULT_GOV_POWERSAVE fs_initcall(cpufreq_gov_powersave_init); #else module_init(cpufreq_gov_powersave_init); #endif module_exit(cpufreq_gov_powersave_exit);
gpl-2.0
Note-2/android_kernel_samsung_smdk4412
fs/hfsplus/bnode.c
8151
15516
/* * linux/fs/hfsplus/bnode.c * * Copyright (C) 2001 * Brad Boyer (flar@allandria.com) * (C) 2003 Ardis Technologies <roman@ardistech.com> * * Handle basic btree node operations */ #include <linux/string.h> #include <linux/slab.h> #include <linux/pagemap.h> #include <linux/fs.h> #include <linux/swap.h> #include "hfsplus_fs.h" #include "hfsplus_raw.h" /* Copy a specified range of bytes from the raw data of a node */ void hfs_bnode_read(struct hfs_bnode *node, void *buf, int off, int len) { struct page **pagep; int l; off += node->page_offset; pagep = node->page + (off >> PAGE_CACHE_SHIFT); off &= ~PAGE_CACHE_MASK; l = min(len, (int)PAGE_CACHE_SIZE - off); memcpy(buf, kmap(*pagep) + off, l); kunmap(*pagep); while ((len -= l) != 0) { buf += l; l = min(len, (int)PAGE_CACHE_SIZE); memcpy(buf, kmap(*++pagep), l); kunmap(*pagep); } } u16 hfs_bnode_read_u16(struct hfs_bnode *node, int off) { __be16 data; /* TODO: optimize later... */ hfs_bnode_read(node, &data, off, 2); return be16_to_cpu(data); } u8 hfs_bnode_read_u8(struct hfs_bnode *node, int off) { u8 data; /* TODO: optimize later... */ hfs_bnode_read(node, &data, off, 1); return data; } void hfs_bnode_read_key(struct hfs_bnode *node, void *key, int off) { struct hfs_btree *tree; int key_len; tree = node->tree; if (node->type == HFS_NODE_LEAF || tree->attributes & HFS_TREE_VARIDXKEYS) key_len = hfs_bnode_read_u16(node, off) + 2; else key_len = tree->max_key_len + 2; hfs_bnode_read(node, key, off, key_len); } void hfs_bnode_write(struct hfs_bnode *node, void *buf, int off, int len) { struct page **pagep; int l; off += node->page_offset; pagep = node->page + (off >> PAGE_CACHE_SHIFT); off &= ~PAGE_CACHE_MASK; l = min(len, (int)PAGE_CACHE_SIZE - off); memcpy(kmap(*pagep) + off, buf, l); set_page_dirty(*pagep); kunmap(*pagep); while ((len -= l) != 0) { buf += l; l = min(len, (int)PAGE_CACHE_SIZE); memcpy(kmap(*++pagep), buf, l); set_page_dirty(*pagep); kunmap(*pagep); } } void hfs_bnode_write_u16(struct hfs_bnode *node, int off, u16 data) { __be16 v = cpu_to_be16(data); /* TODO: optimize later... */ hfs_bnode_write(node, &v, off, 2); } void hfs_bnode_clear(struct hfs_bnode *node, int off, int len) { struct page **pagep; int l; off += node->page_offset; pagep = node->page + (off >> PAGE_CACHE_SHIFT); off &= ~PAGE_CACHE_MASK; l = min(len, (int)PAGE_CACHE_SIZE - off); memset(kmap(*pagep) + off, 0, l); set_page_dirty(*pagep); kunmap(*pagep); while ((len -= l) != 0) { l = min(len, (int)PAGE_CACHE_SIZE); memset(kmap(*++pagep), 0, l); set_page_dirty(*pagep); kunmap(*pagep); } } void hfs_bnode_copy(struct hfs_bnode *dst_node, int dst, struct hfs_bnode *src_node, int src, int len) { struct hfs_btree *tree; struct page **src_page, **dst_page; int l; dprint(DBG_BNODE_MOD, "copybytes: %u,%u,%u\n", dst, src, len); if (!len) return; tree = src_node->tree; src += src_node->page_offset; dst += dst_node->page_offset; src_page = src_node->page + (src >> PAGE_CACHE_SHIFT); src &= ~PAGE_CACHE_MASK; dst_page = dst_node->page + (dst >> PAGE_CACHE_SHIFT); dst &= ~PAGE_CACHE_MASK; if (src == dst) { l = min(len, (int)PAGE_CACHE_SIZE - src); memcpy(kmap(*dst_page) + src, kmap(*src_page) + src, l); kunmap(*src_page); set_page_dirty(*dst_page); kunmap(*dst_page); while ((len -= l) != 0) { l = min(len, (int)PAGE_CACHE_SIZE); memcpy(kmap(*++dst_page), kmap(*++src_page), l); kunmap(*src_page); set_page_dirty(*dst_page); kunmap(*dst_page); } } else { void *src_ptr, *dst_ptr; do { src_ptr = kmap(*src_page) + src; dst_ptr = kmap(*dst_page) + dst; if (PAGE_CACHE_SIZE - src < PAGE_CACHE_SIZE - dst) { l = PAGE_CACHE_SIZE - src; src = 0; dst += l; } else { l = PAGE_CACHE_SIZE - dst; src += l; dst = 0; } l = min(len, l); memcpy(dst_ptr, src_ptr, l); kunmap(*src_page); set_page_dirty(*dst_page); kunmap(*dst_page); if (!dst) dst_page++; else src_page++; } while ((len -= l)); } } void hfs_bnode_move(struct hfs_bnode *node, int dst, int src, int len) { struct page **src_page, **dst_page; int l; dprint(DBG_BNODE_MOD, "movebytes: %u,%u,%u\n", dst, src, len); if (!len) return; src += node->page_offset; dst += node->page_offset; if (dst > src) { src += len - 1; src_page = node->page + (src >> PAGE_CACHE_SHIFT); src = (src & ~PAGE_CACHE_MASK) + 1; dst += len - 1; dst_page = node->page + (dst >> PAGE_CACHE_SHIFT); dst = (dst & ~PAGE_CACHE_MASK) + 1; if (src == dst) { while (src < len) { memmove(kmap(*dst_page), kmap(*src_page), src); kunmap(*src_page); set_page_dirty(*dst_page); kunmap(*dst_page); len -= src; src = PAGE_CACHE_SIZE; src_page--; dst_page--; } src -= len; memmove(kmap(*dst_page) + src, kmap(*src_page) + src, len); kunmap(*src_page); set_page_dirty(*dst_page); kunmap(*dst_page); } else { void *src_ptr, *dst_ptr; do { src_ptr = kmap(*src_page) + src; dst_ptr = kmap(*dst_page) + dst; if (src < dst) { l = src; src = PAGE_CACHE_SIZE; dst -= l; } else { l = dst; src -= l; dst = PAGE_CACHE_SIZE; } l = min(len, l); memmove(dst_ptr - l, src_ptr - l, l); kunmap(*src_page); set_page_dirty(*dst_page); kunmap(*dst_page); if (dst == PAGE_CACHE_SIZE) dst_page--; else src_page--; } while ((len -= l)); } } else { src_page = node->page + (src >> PAGE_CACHE_SHIFT); src &= ~PAGE_CACHE_MASK; dst_page = node->page + (dst >> PAGE_CACHE_SHIFT); dst &= ~PAGE_CACHE_MASK; if (src == dst) { l = min(len, (int)PAGE_CACHE_SIZE - src); memmove(kmap(*dst_page) + src, kmap(*src_page) + src, l); kunmap(*src_page); set_page_dirty(*dst_page); kunmap(*dst_page); while ((len -= l) != 0) { l = min(len, (int)PAGE_CACHE_SIZE); memmove(kmap(*++dst_page), kmap(*++src_page), l); kunmap(*src_page); set_page_dirty(*dst_page); kunmap(*dst_page); } } else { void *src_ptr, *dst_ptr; do { src_ptr = kmap(*src_page) + src; dst_ptr = kmap(*dst_page) + dst; if (PAGE_CACHE_SIZE - src < PAGE_CACHE_SIZE - dst) { l = PAGE_CACHE_SIZE - src; src = 0; dst += l; } else { l = PAGE_CACHE_SIZE - dst; src += l; dst = 0; } l = min(len, l); memmove(dst_ptr, src_ptr, l); kunmap(*src_page); set_page_dirty(*dst_page); kunmap(*dst_page); if (!dst) dst_page++; else src_page++; } while ((len -= l)); } } } void hfs_bnode_dump(struct hfs_bnode *node) { struct hfs_bnode_desc desc; __be32 cnid; int i, off, key_off; dprint(DBG_BNODE_MOD, "bnode: %d\n", node->this); hfs_bnode_read(node, &desc, 0, sizeof(desc)); dprint(DBG_BNODE_MOD, "%d, %d, %d, %d, %d\n", be32_to_cpu(desc.next), be32_to_cpu(desc.prev), desc.type, desc.height, be16_to_cpu(desc.num_recs)); off = node->tree->node_size - 2; for (i = be16_to_cpu(desc.num_recs); i >= 0; off -= 2, i--) { key_off = hfs_bnode_read_u16(node, off); dprint(DBG_BNODE_MOD, " %d", key_off); if (i && node->type == HFS_NODE_INDEX) { int tmp; if (node->tree->attributes & HFS_TREE_VARIDXKEYS) tmp = hfs_bnode_read_u16(node, key_off) + 2; else tmp = node->tree->max_key_len + 2; dprint(DBG_BNODE_MOD, " (%d", tmp); hfs_bnode_read(node, &cnid, key_off + tmp, 4); dprint(DBG_BNODE_MOD, ",%d)", be32_to_cpu(cnid)); } else if (i && node->type == HFS_NODE_LEAF) { int tmp; tmp = hfs_bnode_read_u16(node, key_off); dprint(DBG_BNODE_MOD, " (%d)", tmp); } } dprint(DBG_BNODE_MOD, "\n"); } void hfs_bnode_unlink(struct hfs_bnode *node) { struct hfs_btree *tree; struct hfs_bnode *tmp; __be32 cnid; tree = node->tree; if (node->prev) { tmp = hfs_bnode_find(tree, node->prev); if (IS_ERR(tmp)) return; tmp->next = node->next; cnid = cpu_to_be32(tmp->next); hfs_bnode_write(tmp, &cnid, offsetof(struct hfs_bnode_desc, next), 4); hfs_bnode_put(tmp); } else if (node->type == HFS_NODE_LEAF) tree->leaf_head = node->next; if (node->next) { tmp = hfs_bnode_find(tree, node->next); if (IS_ERR(tmp)) return; tmp->prev = node->prev; cnid = cpu_to_be32(tmp->prev); hfs_bnode_write(tmp, &cnid, offsetof(struct hfs_bnode_desc, prev), 4); hfs_bnode_put(tmp); } else if (node->type == HFS_NODE_LEAF) tree->leaf_tail = node->prev; /* move down? */ if (!node->prev && !node->next) dprint(DBG_BNODE_MOD, "hfs_btree_del_level\n"); if (!node->parent) { tree->root = 0; tree->depth = 0; } set_bit(HFS_BNODE_DELETED, &node->flags); } static inline int hfs_bnode_hash(u32 num) { num = (num >> 16) + num; num += num >> 8; return num & (NODE_HASH_SIZE - 1); } struct hfs_bnode *hfs_bnode_findhash(struct hfs_btree *tree, u32 cnid) { struct hfs_bnode *node; if (cnid >= tree->node_count) { printk(KERN_ERR "hfs: request for non-existent node " "%d in B*Tree\n", cnid); return NULL; } for (node = tree->node_hash[hfs_bnode_hash(cnid)]; node; node = node->next_hash) if (node->this == cnid) return node; return NULL; } static struct hfs_bnode *__hfs_bnode_create(struct hfs_btree *tree, u32 cnid) { struct super_block *sb; struct hfs_bnode *node, *node2; struct address_space *mapping; struct page *page; int size, block, i, hash; loff_t off; if (cnid >= tree->node_count) { printk(KERN_ERR "hfs: request for non-existent node " "%d in B*Tree\n", cnid); return NULL; } sb = tree->inode->i_sb; size = sizeof(struct hfs_bnode) + tree->pages_per_bnode * sizeof(struct page *); node = kzalloc(size, GFP_KERNEL); if (!node) return NULL; node->tree = tree; node->this = cnid; set_bit(HFS_BNODE_NEW, &node->flags); atomic_set(&node->refcnt, 1); dprint(DBG_BNODE_REFS, "new_node(%d:%d): 1\n", node->tree->cnid, node->this); init_waitqueue_head(&node->lock_wq); spin_lock(&tree->hash_lock); node2 = hfs_bnode_findhash(tree, cnid); if (!node2) { hash = hfs_bnode_hash(cnid); node->next_hash = tree->node_hash[hash]; tree->node_hash[hash] = node; tree->node_hash_cnt++; } else { spin_unlock(&tree->hash_lock); kfree(node); wait_event(node2->lock_wq, !test_bit(HFS_BNODE_NEW, &node2->flags)); return node2; } spin_unlock(&tree->hash_lock); mapping = tree->inode->i_mapping; off = (loff_t)cnid << tree->node_size_shift; block = off >> PAGE_CACHE_SHIFT; node->page_offset = off & ~PAGE_CACHE_MASK; for (i = 0; i < tree->pages_per_bnode; block++, i++) { page = read_mapping_page(mapping, block, NULL); if (IS_ERR(page)) goto fail; if (PageError(page)) { page_cache_release(page); goto fail; } page_cache_release(page); node->page[i] = page; } return node; fail: set_bit(HFS_BNODE_ERROR, &node->flags); return node; } void hfs_bnode_unhash(struct hfs_bnode *node) { struct hfs_bnode **p; dprint(DBG_BNODE_REFS, "remove_node(%d:%d): %d\n", node->tree->cnid, node->this, atomic_read(&node->refcnt)); for (p = &node->tree->node_hash[hfs_bnode_hash(node->this)]; *p && *p != node; p = &(*p)->next_hash) ; BUG_ON(!*p); *p = node->next_hash; node->tree->node_hash_cnt--; } /* Load a particular node out of a tree */ struct hfs_bnode *hfs_bnode_find(struct hfs_btree *tree, u32 num) { struct hfs_bnode *node; struct hfs_bnode_desc *desc; int i, rec_off, off, next_off; int entry_size, key_size; spin_lock(&tree->hash_lock); node = hfs_bnode_findhash(tree, num); if (node) { hfs_bnode_get(node); spin_unlock(&tree->hash_lock); wait_event(node->lock_wq, !test_bit(HFS_BNODE_NEW, &node->flags)); if (test_bit(HFS_BNODE_ERROR, &node->flags)) goto node_error; return node; } spin_unlock(&tree->hash_lock); node = __hfs_bnode_create(tree, num); if (!node) return ERR_PTR(-ENOMEM); if (test_bit(HFS_BNODE_ERROR, &node->flags)) goto node_error; if (!test_bit(HFS_BNODE_NEW, &node->flags)) return node; desc = (struct hfs_bnode_desc *)(kmap(node->page[0]) + node->page_offset); node->prev = be32_to_cpu(desc->prev); node->next = be32_to_cpu(desc->next); node->num_recs = be16_to_cpu(desc->num_recs); node->type = desc->type; node->height = desc->height; kunmap(node->page[0]); switch (node->type) { case HFS_NODE_HEADER: case HFS_NODE_MAP: if (node->height != 0) goto node_error; break; case HFS_NODE_LEAF: if (node->height != 1) goto node_error; break; case HFS_NODE_INDEX: if (node->height <= 1 || node->height > tree->depth) goto node_error; break; default: goto node_error; } rec_off = tree->node_size - 2; off = hfs_bnode_read_u16(node, rec_off); if (off != sizeof(struct hfs_bnode_desc)) goto node_error; for (i = 1; i <= node->num_recs; off = next_off, i++) { rec_off -= 2; next_off = hfs_bnode_read_u16(node, rec_off); if (next_off <= off || next_off > tree->node_size || next_off & 1) goto node_error; entry_size = next_off - off; if (node->type != HFS_NODE_INDEX && node->type != HFS_NODE_LEAF) continue; key_size = hfs_bnode_read_u16(node, off) + 2; if (key_size >= entry_size || key_size & 1) goto node_error; } clear_bit(HFS_BNODE_NEW, &node->flags); wake_up(&node->lock_wq); return node; node_error: set_bit(HFS_BNODE_ERROR, &node->flags); clear_bit(HFS_BNODE_NEW, &node->flags); wake_up(&node->lock_wq); hfs_bnode_put(node); return ERR_PTR(-EIO); } void hfs_bnode_free(struct hfs_bnode *node) { #if 0 int i; for (i = 0; i < node->tree->pages_per_bnode; i++) if (node->page[i]) page_cache_release(node->page[i]); #endif kfree(node); } struct hfs_bnode *hfs_bnode_create(struct hfs_btree *tree, u32 num) { struct hfs_bnode *node; struct page **pagep; int i; spin_lock(&tree->hash_lock); node = hfs_bnode_findhash(tree, num); spin_unlock(&tree->hash_lock); if (node) { printk(KERN_CRIT "new node %u already hashed?\n", num); WARN_ON(1); return node; } node = __hfs_bnode_create(tree, num); if (!node) return ERR_PTR(-ENOMEM); if (test_bit(HFS_BNODE_ERROR, &node->flags)) { hfs_bnode_put(node); return ERR_PTR(-EIO); } pagep = node->page; memset(kmap(*pagep) + node->page_offset, 0, min((int)PAGE_CACHE_SIZE, (int)tree->node_size)); set_page_dirty(*pagep); kunmap(*pagep); for (i = 1; i < tree->pages_per_bnode; i++) { memset(kmap(*++pagep), 0, PAGE_CACHE_SIZE); set_page_dirty(*pagep); kunmap(*pagep); } clear_bit(HFS_BNODE_NEW, &node->flags); wake_up(&node->lock_wq); return node; } void hfs_bnode_get(struct hfs_bnode *node) { if (node) { atomic_inc(&node->refcnt); dprint(DBG_BNODE_REFS, "get_node(%d:%d): %d\n", node->tree->cnid, node->this, atomic_read(&node->refcnt)); } } /* Dispose of resources used by a node */ void hfs_bnode_put(struct hfs_bnode *node) { if (node) { struct hfs_btree *tree = node->tree; int i; dprint(DBG_BNODE_REFS, "put_node(%d:%d): %d\n", node->tree->cnid, node->this, atomic_read(&node->refcnt)); BUG_ON(!atomic_read(&node->refcnt)); if (!atomic_dec_and_lock(&node->refcnt, &tree->hash_lock)) return; for (i = 0; i < tree->pages_per_bnode; i++) { if (!node->page[i]) continue; mark_page_accessed(node->page[i]); } if (test_bit(HFS_BNODE_DELETED, &node->flags)) { hfs_bnode_unhash(node); spin_unlock(&tree->hash_lock); hfs_bmap_free(node); hfs_bnode_free(node); return; } spin_unlock(&tree->hash_lock); } }
gpl-2.0
talnoah/Leaping_Lemur-AOSP
net/rds/threads.c
8151
7100
/* * Copyright (c) 2006 Oracle. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include <linux/kernel.h> #include <linux/random.h> #include <linux/export.h> #include "rds.h" /* * All of connection management is simplified by serializing it through * work queues that execute in a connection managing thread. * * TCP wants to send acks through sendpage() in response to data_ready(), * but it needs a process context to do so. * * The receive paths need to allocate but can't drop packets (!) so we have * a thread around to block allocating if the receive fast path sees an * allocation failure. */ /* Grand Unified Theory of connection life cycle: * At any point in time, the connection can be in one of these states: * DOWN, CONNECTING, UP, DISCONNECTING, ERROR * * The following transitions are possible: * ANY -> ERROR * UP -> DISCONNECTING * ERROR -> DISCONNECTING * DISCONNECTING -> DOWN * DOWN -> CONNECTING * CONNECTING -> UP * * Transition to state DISCONNECTING/DOWN: * - Inside the shutdown worker; synchronizes with xmit path * through RDS_IN_XMIT, and with connection management callbacks * via c_cm_lock. * * For receive callbacks, we rely on the underlying transport * (TCP, IB/RDMA) to provide the necessary synchronisation. */ struct workqueue_struct *rds_wq; EXPORT_SYMBOL_GPL(rds_wq); void rds_connect_complete(struct rds_connection *conn) { if (!rds_conn_transition(conn, RDS_CONN_CONNECTING, RDS_CONN_UP)) { printk(KERN_WARNING "%s: Cannot transition to state UP, " "current state is %d\n", __func__, atomic_read(&conn->c_state)); atomic_set(&conn->c_state, RDS_CONN_ERROR); queue_work(rds_wq, &conn->c_down_w); return; } rdsdebug("conn %p for %pI4 to %pI4 complete\n", conn, &conn->c_laddr, &conn->c_faddr); conn->c_reconnect_jiffies = 0; set_bit(0, &conn->c_map_queued); queue_delayed_work(rds_wq, &conn->c_send_w, 0); queue_delayed_work(rds_wq, &conn->c_recv_w, 0); } EXPORT_SYMBOL_GPL(rds_connect_complete); /* * This random exponential backoff is relied on to eventually resolve racing * connects. * * If connect attempts race then both parties drop both connections and come * here to wait for a random amount of time before trying again. Eventually * the backoff range will be so much greater than the time it takes to * establish a connection that one of the pair will establish the connection * before the other's random delay fires. * * Connection attempts that arrive while a connection is already established * are also considered to be racing connects. This lets a connection from * a rebooted machine replace an existing stale connection before the transport * notices that the connection has failed. * * We should *always* start with a random backoff; otherwise a broken connection * will always take several iterations to be re-established. */ void rds_queue_reconnect(struct rds_connection *conn) { unsigned long rand; rdsdebug("conn %p for %pI4 to %pI4 reconnect jiffies %lu\n", conn, &conn->c_laddr, &conn->c_faddr, conn->c_reconnect_jiffies); set_bit(RDS_RECONNECT_PENDING, &conn->c_flags); if (conn->c_reconnect_jiffies == 0) { conn->c_reconnect_jiffies = rds_sysctl_reconnect_min_jiffies; queue_delayed_work(rds_wq, &conn->c_conn_w, 0); return; } get_random_bytes(&rand, sizeof(rand)); rdsdebug("%lu delay %lu ceil conn %p for %pI4 -> %pI4\n", rand % conn->c_reconnect_jiffies, conn->c_reconnect_jiffies, conn, &conn->c_laddr, &conn->c_faddr); queue_delayed_work(rds_wq, &conn->c_conn_w, rand % conn->c_reconnect_jiffies); conn->c_reconnect_jiffies = min(conn->c_reconnect_jiffies * 2, rds_sysctl_reconnect_max_jiffies); } void rds_connect_worker(struct work_struct *work) { struct rds_connection *conn = container_of(work, struct rds_connection, c_conn_w.work); int ret; clear_bit(RDS_RECONNECT_PENDING, &conn->c_flags); if (rds_conn_transition(conn, RDS_CONN_DOWN, RDS_CONN_CONNECTING)) { ret = conn->c_trans->conn_connect(conn); rdsdebug("conn %p for %pI4 to %pI4 dispatched, ret %d\n", conn, &conn->c_laddr, &conn->c_faddr, ret); if (ret) { if (rds_conn_transition(conn, RDS_CONN_CONNECTING, RDS_CONN_DOWN)) rds_queue_reconnect(conn); else rds_conn_error(conn, "RDS: connect failed\n"); } } } void rds_send_worker(struct work_struct *work) { struct rds_connection *conn = container_of(work, struct rds_connection, c_send_w.work); int ret; if (rds_conn_state(conn) == RDS_CONN_UP) { ret = rds_send_xmit(conn); rdsdebug("conn %p ret %d\n", conn, ret); switch (ret) { case -EAGAIN: rds_stats_inc(s_send_immediate_retry); queue_delayed_work(rds_wq, &conn->c_send_w, 0); break; case -ENOMEM: rds_stats_inc(s_send_delayed_retry); queue_delayed_work(rds_wq, &conn->c_send_w, 2); default: break; } } } void rds_recv_worker(struct work_struct *work) { struct rds_connection *conn = container_of(work, struct rds_connection, c_recv_w.work); int ret; if (rds_conn_state(conn) == RDS_CONN_UP) { ret = conn->c_trans->recv(conn); rdsdebug("conn %p ret %d\n", conn, ret); switch (ret) { case -EAGAIN: rds_stats_inc(s_recv_immediate_retry); queue_delayed_work(rds_wq, &conn->c_recv_w, 0); break; case -ENOMEM: rds_stats_inc(s_recv_delayed_retry); queue_delayed_work(rds_wq, &conn->c_recv_w, 2); default: break; } } } void rds_shutdown_worker(struct work_struct *work) { struct rds_connection *conn = container_of(work, struct rds_connection, c_down_w); rds_conn_shutdown(conn); } void rds_threads_exit(void) { destroy_workqueue(rds_wq); } int rds_threads_init(void) { rds_wq = create_singlethread_workqueue("krdsd"); if (!rds_wq) return -ENOMEM; return 0; }
gpl-2.0
martinbrook/amlogic-meson3
arch/arm/mach-pnx4008/i2c.c
8919
1483
/* * I2C initialization for PNX4008. * * Author: Vitaly Wool <vitalywool@gmail.com> * * 2005-2006 (c) MontaVista Software, Inc. This file is licensed under * the terms of the GNU General Public License version 2. This program * is licensed "as is" without any warranty of any kind, whether express * or implied. */ #include <linux/clk.h> #include <linux/i2c.h> #include <linux/i2c-pnx.h> #include <linux/platform_device.h> #include <linux/err.h> #include <mach/platform.h> #include <mach/irqs.h> #include <mach/i2c.h> static struct i2c_pnx_data i2c0_data = { .name = I2C_CHIP_NAME "0", .base = PNX4008_I2C1_BASE, .irq = I2C_1_INT, }; static struct i2c_pnx_data i2c1_data = { .name = I2C_CHIP_NAME "1", .base = PNX4008_I2C2_BASE, .irq = I2C_2_INT, }; static struct i2c_pnx_data i2c2_data = { .name = "USB-I2C", .base = (PNX4008_USB_CONFIG_BASE + 0x300), .irq = USB_I2C_INT, }; static struct platform_device i2c0_device = { .name = "pnx-i2c", .id = 0, .dev = { .platform_data = &i2c0_data, }, }; static struct platform_device i2c1_device = { .name = "pnx-i2c", .id = 1, .dev = { .platform_data = &i2c1_data, }, }; static struct platform_device i2c2_device = { .name = "pnx-i2c", .id = 2, .dev = { .platform_data = &i2c2_data, }, }; static struct platform_device *devices[] __initdata = { &i2c0_device, &i2c1_device, &i2c2_device, }; void __init pnx4008_register_i2c_devices(void) { platform_add_devices(devices, ARRAY_SIZE(devices)); }
gpl-2.0
savoca/furnace-g3
arch/um/sys-ppc/ptrace.c
9431
1432
#include "linux/sched.h" #include "asm/ptrace.h" int putreg(struct task_struct *child, unsigned long regno, unsigned long value) { child->thread.process_regs.regs[regno >> 2] = value; return 0; } int poke_user(struct task_struct *child, long addr, long data) { if ((addr & 3) || addr < 0) return -EIO; if (addr < MAX_REG_OFFSET) return putreg(child, addr, data); else if((addr >= offsetof(struct user, u_debugreg[0])) && (addr <= offsetof(struct user, u_debugreg[7]))){ addr -= offsetof(struct user, u_debugreg[0]); addr = addr >> 2; if((addr == 4) || (addr == 5)) return -EIO; child->thread.arch.debugregs[addr] = data; return 0; } return -EIO; } unsigned long getreg(struct task_struct *child, unsigned long regno) { unsigned long retval = ~0UL; retval &= child->thread.process_regs.regs[regno >> 2]; return retval; } int peek_user(struct task_struct *child, long addr, long data) { /* read the word at location addr in the USER area. */ unsigned long tmp; if ((addr & 3) || addr < 0) return -EIO; tmp = 0; /* Default return condition */ if(addr < MAX_REG_OFFSET){ tmp = getreg(child, addr); } else if((addr >= offsetof(struct user, u_debugreg[0])) && (addr <= offsetof(struct user, u_debugreg[7]))){ addr -= offsetof(struct user, u_debugreg[0]); addr = addr >> 2; tmp = child->thread.arch.debugregs[addr]; } return put_user(tmp, (unsigned long *) data); }
gpl-2.0
garwynn/L900_MC2_Kernel
arch/powerpc/math-emu/math.c
11479
12176
/* * Copyright (C) 1999 Eddie C. Dost (ecd@atecom.com) */ #include <linux/types.h> #include <linux/sched.h> #include <asm/uaccess.h> #include <asm/reg.h> #include <asm/sfp-machine.h> #include <math-emu/double.h> #define FLOATFUNC(x) extern int x(void *, void *, void *, void *) FLOATFUNC(fadd); FLOATFUNC(fadds); FLOATFUNC(fdiv); FLOATFUNC(fdivs); FLOATFUNC(fmul); FLOATFUNC(fmuls); FLOATFUNC(fsub); FLOATFUNC(fsubs); FLOATFUNC(fmadd); FLOATFUNC(fmadds); FLOATFUNC(fmsub); FLOATFUNC(fmsubs); FLOATFUNC(fnmadd); FLOATFUNC(fnmadds); FLOATFUNC(fnmsub); FLOATFUNC(fnmsubs); FLOATFUNC(fctiw); FLOATFUNC(fctiwz); FLOATFUNC(frsp); FLOATFUNC(fcmpo); FLOATFUNC(fcmpu); FLOATFUNC(mcrfs); FLOATFUNC(mffs); FLOATFUNC(mtfsb0); FLOATFUNC(mtfsb1); FLOATFUNC(mtfsf); FLOATFUNC(mtfsfi); FLOATFUNC(lfd); FLOATFUNC(lfs); FLOATFUNC(stfd); FLOATFUNC(stfs); FLOATFUNC(stfiwx); FLOATFUNC(fabs); FLOATFUNC(fmr); FLOATFUNC(fnabs); FLOATFUNC(fneg); /* Optional */ FLOATFUNC(fres); FLOATFUNC(frsqrte); FLOATFUNC(fsel); FLOATFUNC(fsqrt); FLOATFUNC(fsqrts); #define OP31 0x1f /* 31 */ #define LFS 0x30 /* 48 */ #define LFSU 0x31 /* 49 */ #define LFD 0x32 /* 50 */ #define LFDU 0x33 /* 51 */ #define STFS 0x34 /* 52 */ #define STFSU 0x35 /* 53 */ #define STFD 0x36 /* 54 */ #define STFDU 0x37 /* 55 */ #define OP59 0x3b /* 59 */ #define OP63 0x3f /* 63 */ /* Opcode 31: */ /* X-Form: */ #define LFSX 0x217 /* 535 */ #define LFSUX 0x237 /* 567 */ #define LFDX 0x257 /* 599 */ #define LFDUX 0x277 /* 631 */ #define STFSX 0x297 /* 663 */ #define STFSUX 0x2b7 /* 695 */ #define STFDX 0x2d7 /* 727 */ #define STFDUX 0x2f7 /* 759 */ #define STFIWX 0x3d7 /* 983 */ /* Opcode 59: */ /* A-Form: */ #define FDIVS 0x012 /* 18 */ #define FSUBS 0x014 /* 20 */ #define FADDS 0x015 /* 21 */ #define FSQRTS 0x016 /* 22 */ #define FRES 0x018 /* 24 */ #define FMULS 0x019 /* 25 */ #define FMSUBS 0x01c /* 28 */ #define FMADDS 0x01d /* 29 */ #define FNMSUBS 0x01e /* 30 */ #define FNMADDS 0x01f /* 31 */ /* Opcode 63: */ /* A-Form: */ #define FDIV 0x012 /* 18 */ #define FSUB 0x014 /* 20 */ #define FADD 0x015 /* 21 */ #define FSQRT 0x016 /* 22 */ #define FSEL 0x017 /* 23 */ #define FMUL 0x019 /* 25 */ #define FRSQRTE 0x01a /* 26 */ #define FMSUB 0x01c /* 28 */ #define FMADD 0x01d /* 29 */ #define FNMSUB 0x01e /* 30 */ #define FNMADD 0x01f /* 31 */ /* X-Form: */ #define FCMPU 0x000 /* 0 */ #define FRSP 0x00c /* 12 */ #define FCTIW 0x00e /* 14 */ #define FCTIWZ 0x00f /* 15 */ #define FCMPO 0x020 /* 32 */ #define MTFSB1 0x026 /* 38 */ #define FNEG 0x028 /* 40 */ #define MCRFS 0x040 /* 64 */ #define MTFSB0 0x046 /* 70 */ #define FMR 0x048 /* 72 */ #define MTFSFI 0x086 /* 134 */ #define FNABS 0x088 /* 136 */ #define FABS 0x108 /* 264 */ #define MFFS 0x247 /* 583 */ #define MTFSF 0x2c7 /* 711 */ #define AB 2 #define AC 3 #define ABC 4 #define D 5 #define DU 6 #define X 7 #define XA 8 #define XB 9 #define XCR 11 #define XCRB 12 #define XCRI 13 #define XCRL 16 #define XE 14 #define XEU 15 #define XFLB 10 #ifdef CONFIG_MATH_EMULATION static int record_exception(struct pt_regs *regs, int eflag) { u32 fpscr; fpscr = __FPU_FPSCR; if (eflag) { fpscr |= FPSCR_FX; if (eflag & EFLAG_OVERFLOW) fpscr |= FPSCR_OX; if (eflag & EFLAG_UNDERFLOW) fpscr |= FPSCR_UX; if (eflag & EFLAG_DIVZERO) fpscr |= FPSCR_ZX; if (eflag & EFLAG_INEXACT) fpscr |= FPSCR_XX; if (eflag & EFLAG_INVALID) fpscr |= FPSCR_VX; if (eflag & EFLAG_VXSNAN) fpscr |= FPSCR_VXSNAN; if (eflag & EFLAG_VXISI) fpscr |= FPSCR_VXISI; if (eflag & EFLAG_VXIDI) fpscr |= FPSCR_VXIDI; if (eflag & EFLAG_VXZDZ) fpscr |= FPSCR_VXZDZ; if (eflag & EFLAG_VXIMZ) fpscr |= FPSCR_VXIMZ; if (eflag & EFLAG_VXVC) fpscr |= FPSCR_VXVC; if (eflag & EFLAG_VXSOFT) fpscr |= FPSCR_VXSOFT; if (eflag & EFLAG_VXSQRT) fpscr |= FPSCR_VXSQRT; if (eflag & EFLAG_VXCVI) fpscr |= FPSCR_VXCVI; } // fpscr &= ~(FPSCR_VX); if (fpscr & (FPSCR_VXSNAN | FPSCR_VXISI | FPSCR_VXIDI | FPSCR_VXZDZ | FPSCR_VXIMZ | FPSCR_VXVC | FPSCR_VXSOFT | FPSCR_VXSQRT | FPSCR_VXCVI)) fpscr |= FPSCR_VX; fpscr &= ~(FPSCR_FEX); if (((fpscr & FPSCR_VX) && (fpscr & FPSCR_VE)) || ((fpscr & FPSCR_OX) && (fpscr & FPSCR_OE)) || ((fpscr & FPSCR_UX) && (fpscr & FPSCR_UE)) || ((fpscr & FPSCR_ZX) && (fpscr & FPSCR_ZE)) || ((fpscr & FPSCR_XX) && (fpscr & FPSCR_XE))) fpscr |= FPSCR_FEX; __FPU_FPSCR = fpscr; return (fpscr & FPSCR_FEX) ? 1 : 0; } #endif /* CONFIG_MATH_EMULATION */ int do_mathemu(struct pt_regs *regs) { void *op0 = 0, *op1 = 0, *op2 = 0, *op3 = 0; unsigned long pc = regs->nip; signed short sdisp; u32 insn = 0; int idx = 0; #ifdef CONFIG_MATH_EMULATION int (*func)(void *, void *, void *, void *); int type = 0; int eflag, trap; #endif if (get_user(insn, (u32 *)pc)) return -EFAULT; #ifndef CONFIG_MATH_EMULATION switch (insn >> 26) { case LFD: idx = (insn >> 16) & 0x1f; sdisp = (insn & 0xffff); op0 = (void *)&current->thread.TS_FPR((insn >> 21) & 0x1f); op1 = (void *)((idx ? regs->gpr[idx] : 0) + sdisp); lfd(op0, op1, op2, op3); break; case LFDU: idx = (insn >> 16) & 0x1f; sdisp = (insn & 0xffff); op0 = (void *)&current->thread.TS_FPR((insn >> 21) & 0x1f); op1 = (void *)((idx ? regs->gpr[idx] : 0) + sdisp); lfd(op0, op1, op2, op3); regs->gpr[idx] = (unsigned long)op1; break; case STFD: idx = (insn >> 16) & 0x1f; sdisp = (insn & 0xffff); op0 = (void *)&current->thread.TS_FPR((insn >> 21) & 0x1f); op1 = (void *)((idx ? regs->gpr[idx] : 0) + sdisp); stfd(op0, op1, op2, op3); break; case STFDU: idx = (insn >> 16) & 0x1f; sdisp = (insn & 0xffff); op0 = (void *)&current->thread.TS_FPR((insn >> 21) & 0x1f); op1 = (void *)((idx ? regs->gpr[idx] : 0) + sdisp); stfd(op0, op1, op2, op3); regs->gpr[idx] = (unsigned long)op1; break; case OP63: op0 = (void *)&current->thread.TS_FPR((insn >> 21) & 0x1f); op1 = (void *)&current->thread.TS_FPR((insn >> 11) & 0x1f); fmr(op0, op1, op2, op3); break; default: goto illegal; } #else /* CONFIG_MATH_EMULATION */ switch (insn >> 26) { case LFS: func = lfs; type = D; break; case LFSU: func = lfs; type = DU; break; case LFD: func = lfd; type = D; break; case LFDU: func = lfd; type = DU; break; case STFS: func = stfs; type = D; break; case STFSU: func = stfs; type = DU; break; case STFD: func = stfd; type = D; break; case STFDU: func = stfd; type = DU; break; case OP31: switch ((insn >> 1) & 0x3ff) { case LFSX: func = lfs; type = XE; break; case LFSUX: func = lfs; type = XEU; break; case LFDX: func = lfd; type = XE; break; case LFDUX: func = lfd; type = XEU; break; case STFSX: func = stfs; type = XE; break; case STFSUX: func = stfs; type = XEU; break; case STFDX: func = stfd; type = XE; break; case STFDUX: func = stfd; type = XEU; break; case STFIWX: func = stfiwx; type = XE; break; default: goto illegal; } break; case OP59: switch ((insn >> 1) & 0x1f) { case FDIVS: func = fdivs; type = AB; break; case FSUBS: func = fsubs; type = AB; break; case FADDS: func = fadds; type = AB; break; case FSQRTS: func = fsqrts; type = AB; break; case FRES: func = fres; type = AB; break; case FMULS: func = fmuls; type = AC; break; case FMSUBS: func = fmsubs; type = ABC; break; case FMADDS: func = fmadds; type = ABC; break; case FNMSUBS: func = fnmsubs; type = ABC; break; case FNMADDS: func = fnmadds; type = ABC; break; default: goto illegal; } break; case OP63: if (insn & 0x20) { switch ((insn >> 1) & 0x1f) { case FDIV: func = fdiv; type = AB; break; case FSUB: func = fsub; type = AB; break; case FADD: func = fadd; type = AB; break; case FSQRT: func = fsqrt; type = AB; break; case FSEL: func = fsel; type = ABC; break; case FMUL: func = fmul; type = AC; break; case FRSQRTE: func = frsqrte; type = AB; break; case FMSUB: func = fmsub; type = ABC; break; case FMADD: func = fmadd; type = ABC; break; case FNMSUB: func = fnmsub; type = ABC; break; case FNMADD: func = fnmadd; type = ABC; break; default: goto illegal; } break; } switch ((insn >> 1) & 0x3ff) { case FCMPU: func = fcmpu; type = XCR; break; case FRSP: func = frsp; type = XB; break; case FCTIW: func = fctiw; type = XB; break; case FCTIWZ: func = fctiwz; type = XB; break; case FCMPO: func = fcmpo; type = XCR; break; case MTFSB1: func = mtfsb1; type = XCRB; break; case FNEG: func = fneg; type = XB; break; case MCRFS: func = mcrfs; type = XCRL; break; case MTFSB0: func = mtfsb0; type = XCRB; break; case FMR: func = fmr; type = XB; break; case MTFSFI: func = mtfsfi; type = XCRI; break; case FNABS: func = fnabs; type = XB; break; case FABS: func = fabs; type = XB; break; case MFFS: func = mffs; type = X; break; case MTFSF: func = mtfsf; type = XFLB; break; default: goto illegal; } break; default: goto illegal; } switch (type) { case AB: op0 = (void *)&current->thread.TS_FPR((insn >> 21) & 0x1f); op1 = (void *)&current->thread.TS_FPR((insn >> 16) & 0x1f); op2 = (void *)&current->thread.TS_FPR((insn >> 11) & 0x1f); break; case AC: op0 = (void *)&current->thread.TS_FPR((insn >> 21) & 0x1f); op1 = (void *)&current->thread.TS_FPR((insn >> 16) & 0x1f); op2 = (void *)&current->thread.TS_FPR((insn >> 6) & 0x1f); break; case ABC: op0 = (void *)&current->thread.TS_FPR((insn >> 21) & 0x1f); op1 = (void *)&current->thread.TS_FPR((insn >> 16) & 0x1f); op2 = (void *)&current->thread.TS_FPR((insn >> 11) & 0x1f); op3 = (void *)&current->thread.TS_FPR((insn >> 6) & 0x1f); break; case D: idx = (insn >> 16) & 0x1f; sdisp = (insn & 0xffff); op0 = (void *)&current->thread.TS_FPR((insn >> 21) & 0x1f); op1 = (void *)((idx ? regs->gpr[idx] : 0) + sdisp); break; case DU: idx = (insn >> 16) & 0x1f; if (!idx) goto illegal; sdisp = (insn & 0xffff); op0 = (void *)&current->thread.TS_FPR((insn >> 21) & 0x1f); op1 = (void *)(regs->gpr[idx] + sdisp); break; case X: op0 = (void *)&current->thread.TS_FPR((insn >> 21) & 0x1f); break; case XA: op0 = (void *)&current->thread.TS_FPR((insn >> 21) & 0x1f); op1 = (void *)&current->thread.TS_FPR((insn >> 16) & 0x1f); break; case XB: op0 = (void *)&current->thread.TS_FPR((insn >> 21) & 0x1f); op1 = (void *)&current->thread.TS_FPR((insn >> 11) & 0x1f); break; case XE: idx = (insn >> 16) & 0x1f; op0 = (void *)&current->thread.TS_FPR((insn >> 21) & 0x1f); if (!idx) { if (((insn >> 1) & 0x3ff) == STFIWX) op1 = (void *)(regs->gpr[(insn >> 11) & 0x1f]); else goto illegal; } else { op1 = (void *)(regs->gpr[idx] + regs->gpr[(insn >> 11) & 0x1f]); } break; case XEU: idx = (insn >> 16) & 0x1f; op0 = (void *)&current->thread.TS_FPR((insn >> 21) & 0x1f); op1 = (void *)((idx ? regs->gpr[idx] : 0) + regs->gpr[(insn >> 11) & 0x1f]); break; case XCR: op0 = (void *)&regs->ccr; op1 = (void *)((insn >> 23) & 0x7); op2 = (void *)&current->thread.TS_FPR((insn >> 16) & 0x1f); op3 = (void *)&current->thread.TS_FPR((insn >> 11) & 0x1f); break; case XCRL: op0 = (void *)&regs->ccr; op1 = (void *)((insn >> 23) & 0x7); op2 = (void *)((insn >> 18) & 0x7); break; case XCRB: op0 = (void *)((insn >> 21) & 0x1f); break; case XCRI: op0 = (void *)((insn >> 23) & 0x7); op1 = (void *)((insn >> 12) & 0xf); break; case XFLB: op0 = (void *)((insn >> 17) & 0xff); op1 = (void *)&current->thread.TS_FPR((insn >> 11) & 0x1f); break; default: goto illegal; } eflag = func(op0, op1, op2, op3); if (insn & 1) { regs->ccr &= ~(0x0f000000); regs->ccr |= (__FPU_FPSCR >> 4) & 0x0f000000; } trap = record_exception(regs, eflag); if (trap) return 1; switch (type) { case DU: case XEU: regs->gpr[idx] = (unsigned long)op1; break; default: break; } #endif /* CONFIG_MATH_EMULATION */ regs->nip += 4; return 0; illegal: return -ENOSYS; }
gpl-2.0
SOKP/kernel_samsung_trlte
net/l2tp/l2tp_ppp.c
216
48562
/***************************************************************************** * Linux PPP over L2TP (PPPoX/PPPoL2TP) Sockets * * PPPoX --- Generic PPP encapsulation socket family * PPPoL2TP --- PPP over L2TP (RFC 2661) * * Version: 2.0.0 * * Authors: James Chapman (jchapman@katalix.com) * * Based on original work by Martijn van Oosterhout <kleptog@svana.org> * * License: * 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 driver handles only L2TP data frames; control frames are handled by a * userspace application. * * To send data in an L2TP session, userspace opens a PPPoL2TP socket and * attaches it to a bound UDP socket with local tunnel_id / session_id and * peer tunnel_id / session_id set. Data can then be sent or received using * regular socket sendmsg() / recvmsg() calls. Kernel parameters of the socket * can be read or modified using ioctl() or [gs]etsockopt() calls. * * When a PPPoL2TP socket is connected with local and peer session_id values * zero, the socket is treated as a special tunnel management socket. * * Here's example userspace code to create a socket for sending/receiving data * over an L2TP session:- * * struct sockaddr_pppol2tp sax; * int fd; * int session_fd; * * fd = socket(AF_PPPOX, SOCK_DGRAM, PX_PROTO_OL2TP); * * sax.sa_family = AF_PPPOX; * sax.sa_protocol = PX_PROTO_OL2TP; * sax.pppol2tp.fd = tunnel_fd; // bound UDP socket * sax.pppol2tp.addr.sin_addr.s_addr = addr->sin_addr.s_addr; * sax.pppol2tp.addr.sin_port = addr->sin_port; * sax.pppol2tp.addr.sin_family = AF_INET; * sax.pppol2tp.s_tunnel = tunnel_id; * sax.pppol2tp.s_session = session_id; * sax.pppol2tp.d_tunnel = peer_tunnel_id; * sax.pppol2tp.d_session = peer_session_id; * * session_fd = connect(fd, (struct sockaddr *)&sax, sizeof(sax)); * * A pppd plugin that allows PPP traffic to be carried over L2TP using * this driver is available from the OpenL2TP project at * http://openl2tp.sourceforge.net. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/string.h> #include <linux/list.h> #include <linux/uaccess.h> #include <linux/kernel.h> #include <linux/spinlock.h> #include <linux/kthread.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/errno.h> #include <linux/jiffies.h> #include <linux/netdevice.h> #include <linux/net.h> #include <linux/inetdevice.h> #include <linux/skbuff.h> #include <linux/init.h> #include <linux/ip.h> #include <linux/udp.h> #include <linux/if_pppox.h> #include <linux/if_pppol2tp.h> #include <net/sock.h> #include <linux/ppp_channel.h> #include <linux/ppp_defs.h> #include <linux/ppp-ioctl.h> #include <linux/file.h> #include <linux/hash.h> #include <linux/sort.h> #include <linux/proc_fs.h> #include <linux/l2tp.h> #include <linux/nsproxy.h> #include <net/net_namespace.h> #include <net/netns/generic.h> #include <net/dst.h> #include <net/ip.h> #include <net/udp.h> #include <net/xfrm.h> #include <net/inet_common.h> #include <asm/byteorder.h> #include <linux/atomic.h> #include "l2tp_core.h" #define PPPOL2TP_DRV_VERSION "V2.0" /* Space for UDP, L2TP and PPP headers */ #define PPPOL2TP_HEADER_OVERHEAD 40 /* Number of bytes to build transmit L2TP headers. * Unfortunately the size is different depending on whether sequence numbers * are enabled. */ #define PPPOL2TP_L2TP_HDR_SIZE_SEQ 10 #define PPPOL2TP_L2TP_HDR_SIZE_NOSEQ 6 /* Private data of each session. This data lives at the end of struct * l2tp_session, referenced via session->priv[]. */ struct pppol2tp_session { int owner; /* pid that opened the socket */ struct sock *sock; /* Pointer to the session * PPPoX socket */ struct sock *tunnel_sock; /* Pointer to the tunnel UDP * socket */ int flags; /* accessed by PPPIOCGFLAGS. * Unused. */ }; static int pppol2tp_xmit(struct ppp_channel *chan, struct sk_buff *skb); static const struct ppp_channel_ops pppol2tp_chan_ops = { .start_xmit = pppol2tp_xmit, }; static const struct proto_ops pppol2tp_ops; /* Helpers to obtain tunnel/session contexts from sockets. */ static inline struct l2tp_session *pppol2tp_sock_to_session(struct sock *sk) { struct l2tp_session *session; if (sk == NULL) return NULL; sock_hold(sk); session = (struct l2tp_session *)(sk->sk_user_data); if (session == NULL) { sock_put(sk); goto out; } BUG_ON(session->magic != L2TP_SESSION_MAGIC); out: return session; } /***************************************************************************** * Receive data handling *****************************************************************************/ static int pppol2tp_recv_payload_hook(struct sk_buff *skb) { /* Skip PPP header, if present. In testing, Microsoft L2TP clients * don't send the PPP header (PPP header compression enabled), but * other clients can include the header. So we cope with both cases * here. The PPP header is always FF03 when using L2TP. * * Note that skb->data[] isn't dereferenced from a u16 ptr here since * the field may be unaligned. */ if (!pskb_may_pull(skb, 2)) return 1; if ((skb->data[0] == 0xff) && (skb->data[1] == 0x03)) skb_pull(skb, 2); return 0; } /* Receive message. This is the recvmsg for the PPPoL2TP socket. */ static int pppol2tp_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int err; struct sk_buff *skb; struct sock *sk = sock->sk; err = -EIO; if (sk->sk_state & PPPOX_BOUND) goto end; err = 0; skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &err); if (!skb) goto end; if (len > skb->len) len = skb->len; else if (len < skb->len) msg->msg_flags |= MSG_TRUNC; err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, len); if (likely(err == 0)) err = len; kfree_skb(skb); end: return err; } static void pppol2tp_recv(struct l2tp_session *session, struct sk_buff *skb, int data_len) { struct pppol2tp_session *ps = l2tp_session_priv(session); struct sock *sk = NULL; /* If the socket is bound, send it in to PPP's input queue. Otherwise * queue it on the session socket. */ sk = ps->sock; if (sk == NULL) goto no_sock; if (sk->sk_state & PPPOX_BOUND) { struct pppox_sock *po; l2tp_dbg(session, PPPOL2TP_MSG_DATA, "%s: recv %d byte data frame, passing to ppp\n", session->name, data_len); /* We need to forget all info related to the L2TP packet * gathered in the skb as we are going to reuse the same * skb for the inner packet. * Namely we need to: * - reset xfrm (IPSec) information as it applies to * the outer L2TP packet and not to the inner one * - release the dst to force a route lookup on the inner * IP packet since skb->dst currently points to the dst * of the UDP tunnel * - reset netfilter information as it doesn't apply * to the inner packet either */ secpath_reset(skb); skb_dst_drop(skb); nf_reset(skb); po = pppox_sk(sk); ppp_input(&po->chan, skb); } else { l2tp_info(session, PPPOL2TP_MSG_DATA, "%s: socket not bound\n", session->name); /* Not bound. Nothing we can do, so discard. */ atomic_long_inc(&session->stats.rx_errors); kfree_skb(skb); } return; no_sock: l2tp_info(session, PPPOL2TP_MSG_DATA, "%s: no socket\n", session->name); kfree_skb(skb); } static void pppol2tp_session_sock_hold(struct l2tp_session *session) { struct pppol2tp_session *ps = l2tp_session_priv(session); if (ps->sock) sock_hold(ps->sock); } static void pppol2tp_session_sock_put(struct l2tp_session *session) { struct pppol2tp_session *ps = l2tp_session_priv(session); if (ps->sock) sock_put(ps->sock); } /************************************************************************ * Transmit handling ***********************************************************************/ /* This is the sendmsg for the PPPoL2TP pppol2tp_session socket. We come here * when a user application does a sendmsg() on the session socket. L2TP and * PPP headers must be inserted into the user's data. */ static int pppol2tp_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t total_len) { static const unsigned char ppph[2] = { 0xff, 0x03 }; struct sock *sk = sock->sk; struct sk_buff *skb; int error; struct l2tp_session *session; struct l2tp_tunnel *tunnel; struct pppol2tp_session *ps; int uhlen; error = -ENOTCONN; if (sock_flag(sk, SOCK_DEAD) || !(sk->sk_state & PPPOX_CONNECTED)) goto error; /* Get session and tunnel contexts */ error = -EBADF; session = pppol2tp_sock_to_session(sk); if (session == NULL) goto error; ps = l2tp_session_priv(session); tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock); if (tunnel == NULL) goto error_put_sess; uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(struct udphdr) : 0; /* Allocate a socket buffer */ error = -ENOMEM; skb = sock_wmalloc(sk, NET_SKB_PAD + sizeof(struct iphdr) + uhlen + session->hdr_len + sizeof(ppph) + total_len, 0, GFP_KERNEL); if (!skb) goto error_put_sess_tun; /* Reserve space for headers. */ skb_reserve(skb, NET_SKB_PAD); skb_reset_network_header(skb); skb_reserve(skb, sizeof(struct iphdr)); skb_reset_transport_header(skb); skb_reserve(skb, uhlen); /* Add PPP header */ skb->data[0] = ppph[0]; skb->data[1] = ppph[1]; skb_put(skb, 2); /* Copy user data into skb */ error = memcpy_fromiovec(skb_put(skb, total_len), m->msg_iov, total_len); if (error < 0) { kfree_skb(skb); goto error_put_sess_tun; } local_bh_disable(); l2tp_xmit_skb(session, skb, session->hdr_len); local_bh_enable(); sock_put(ps->tunnel_sock); sock_put(sk); return total_len; error_put_sess_tun: sock_put(ps->tunnel_sock); error_put_sess: sock_put(sk); error: return error; } /* Transmit function called by generic PPP driver. Sends PPP frame * over PPPoL2TP socket. * * This is almost the same as pppol2tp_sendmsg(), but rather than * being called with a msghdr from userspace, it is called with a skb * from the kernel. * * The supplied skb from ppp doesn't have enough headroom for the * insertion of L2TP, UDP and IP headers so we need to allocate more * headroom in the skb. This will create a cloned skb. But we must be * careful in the error case because the caller will expect to free * the skb it supplied, not our cloned skb. So we take care to always * leave the original skb unfreed if we return an error. */ static int pppol2tp_xmit(struct ppp_channel *chan, struct sk_buff *skb) { static const u8 ppph[2] = { 0xff, 0x03 }; struct sock *sk = (struct sock *) chan->private; struct sock *sk_tun; struct l2tp_session *session; struct l2tp_tunnel *tunnel; struct pppol2tp_session *ps; int uhlen, headroom; if (sock_flag(sk, SOCK_DEAD) || !(sk->sk_state & PPPOX_CONNECTED)) goto abort; /* Get session and tunnel contexts from the socket */ session = pppol2tp_sock_to_session(sk); if (session == NULL) goto abort; ps = l2tp_session_priv(session); sk_tun = ps->tunnel_sock; if (sk_tun == NULL) goto abort_put_sess; tunnel = l2tp_sock_to_tunnel(sk_tun); if (tunnel == NULL) goto abort_put_sess; uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(struct udphdr) : 0; headroom = NET_SKB_PAD + sizeof(struct iphdr) + /* IP header */ uhlen + /* UDP header (if L2TP_ENCAPTYPE_UDP) */ session->hdr_len + /* L2TP header */ sizeof(ppph); /* PPP header */ if (skb_cow_head(skb, headroom)) goto abort_put_sess_tun; /* Setup PPP header */ __skb_push(skb, sizeof(ppph)); skb->data[0] = ppph[0]; skb->data[1] = ppph[1]; local_bh_disable(); l2tp_xmit_skb(session, skb, session->hdr_len); local_bh_enable(); sock_put(sk_tun); sock_put(sk); return 1; abort_put_sess_tun: sock_put(sk_tun); abort_put_sess: sock_put(sk); abort: /* Free the original skb */ kfree_skb(skb); return 1; } /***************************************************************************** * Session (and tunnel control) socket create/destroy. *****************************************************************************/ /* Called by l2tp_core when a session socket is being closed. */ static void pppol2tp_session_close(struct l2tp_session *session) { struct pppol2tp_session *ps = l2tp_session_priv(session); struct sock *sk = ps->sock; struct socket *sock = sk->sk_socket; BUG_ON(session->magic != L2TP_SESSION_MAGIC); if (sock) { inet_shutdown(sock, 2); /* Don't let the session go away before our socket does */ l2tp_session_inc_refcount(session); } return; } /* Really kill the session socket. (Called from sock_put() if * refcnt == 0.) */ static void pppol2tp_session_destruct(struct sock *sk) { struct l2tp_session *session = sk->sk_user_data; if (session) { sk->sk_user_data = NULL; BUG_ON(session->magic != L2TP_SESSION_MAGIC); l2tp_session_dec_refcount(session); } return; } /* Called when the PPPoX socket (session) is closed. */ static int pppol2tp_release(struct socket *sock) { struct sock *sk = sock->sk; struct l2tp_session *session; int error; if (!sk) return 0; error = -EBADF; lock_sock(sk); if (sock_flag(sk, SOCK_DEAD) != 0) goto error; pppox_unbind_sock(sk); /* Signal the death of the socket. */ sk->sk_state = PPPOX_DEAD; sock_orphan(sk); sock->sk = NULL; session = pppol2tp_sock_to_session(sk); /* Purge any queued data */ if (session != NULL) { __l2tp_session_unhash(session); l2tp_session_queue_purge(session); sock_put(sk); } skb_queue_purge(&sk->sk_receive_queue); skb_queue_purge(&sk->sk_write_queue); release_sock(sk); /* This will delete the session context via * pppol2tp_session_destruct() if the socket's refcnt drops to * zero. */ sock_put(sk); return 0; error: release_sock(sk); return error; } static struct proto pppol2tp_sk_proto = { .name = "PPPOL2TP", .owner = THIS_MODULE, .obj_size = sizeof(struct pppox_sock), }; static int pppol2tp_backlog_recv(struct sock *sk, struct sk_buff *skb) { int rc; rc = l2tp_udp_encap_recv(sk, skb); if (rc) kfree_skb(skb); return NET_RX_SUCCESS; } /* socket() handler. Initialize a new struct sock. */ static int pppol2tp_create(struct net *net, struct socket *sock) { int error = -ENOMEM; struct sock *sk; sk = sk_alloc(net, PF_PPPOX, GFP_KERNEL, &pppol2tp_sk_proto); if (!sk) goto out; sock_init_data(sock, sk); sock->state = SS_UNCONNECTED; sock->ops = &pppol2tp_ops; sk->sk_backlog_rcv = pppol2tp_backlog_recv; sk->sk_protocol = PX_PROTO_OL2TP; sk->sk_family = PF_PPPOX; sk->sk_state = PPPOX_NONE; sk->sk_type = SOCK_STREAM; sk->sk_destruct = pppol2tp_session_destruct; error = 0; out: return error; } #if defined(CONFIG_L2TP_DEBUGFS) || defined(CONFIG_L2TP_DEBUGFS_MODULE) static void pppol2tp_show(struct seq_file *m, void *arg) { struct l2tp_session *session = arg; struct pppol2tp_session *ps = l2tp_session_priv(session); if (ps) { struct pppox_sock *po = pppox_sk(ps->sock); if (po) seq_printf(m, " interface %s\n", ppp_dev_name(&po->chan)); } } #endif /* connect() handler. Attach a PPPoX socket to a tunnel UDP socket */ static int pppol2tp_connect(struct socket *sock, struct sockaddr *uservaddr, int sockaddr_len, int flags) { struct sock *sk = sock->sk; struct sockaddr_pppol2tp *sp = (struct sockaddr_pppol2tp *) uservaddr; struct pppox_sock *po = pppox_sk(sk); struct l2tp_session *session = NULL; struct l2tp_tunnel *tunnel; struct pppol2tp_session *ps; struct dst_entry *dst; struct l2tp_session_cfg cfg = { 0, }; int error = 0; u32 tunnel_id, peer_tunnel_id; u32 session_id, peer_session_id; int ver = 2; int fd; lock_sock(sk); error = -EINVAL; if (sp->sa_protocol != PX_PROTO_OL2TP) goto end; /* Check for already bound sockets */ error = -EBUSY; if (sk->sk_state & PPPOX_CONNECTED) goto end; /* We don't supporting rebinding anyway */ error = -EALREADY; if (sk->sk_user_data) goto end; /* socket is already attached */ /* Get params from socket address. Handle L2TPv2 and L2TPv3. * This is nasty because there are different sockaddr_pppol2tp * structs for L2TPv2, L2TPv3, over IPv4 and IPv6. We use * the sockaddr size to determine which structure the caller * is using. */ peer_tunnel_id = 0; if (sockaddr_len == sizeof(struct sockaddr_pppol2tp)) { fd = sp->pppol2tp.fd; tunnel_id = sp->pppol2tp.s_tunnel; peer_tunnel_id = sp->pppol2tp.d_tunnel; session_id = sp->pppol2tp.s_session; peer_session_id = sp->pppol2tp.d_session; } else if (sockaddr_len == sizeof(struct sockaddr_pppol2tpv3)) { struct sockaddr_pppol2tpv3 *sp3 = (struct sockaddr_pppol2tpv3 *) sp; ver = 3; fd = sp3->pppol2tp.fd; tunnel_id = sp3->pppol2tp.s_tunnel; peer_tunnel_id = sp3->pppol2tp.d_tunnel; session_id = sp3->pppol2tp.s_session; peer_session_id = sp3->pppol2tp.d_session; } else if (sockaddr_len == sizeof(struct sockaddr_pppol2tpin6)) { struct sockaddr_pppol2tpin6 *sp6 = (struct sockaddr_pppol2tpin6 *) sp; fd = sp6->pppol2tp.fd; tunnel_id = sp6->pppol2tp.s_tunnel; peer_tunnel_id = sp6->pppol2tp.d_tunnel; session_id = sp6->pppol2tp.s_session; peer_session_id = sp6->pppol2tp.d_session; } else if (sockaddr_len == sizeof(struct sockaddr_pppol2tpv3in6)) { struct sockaddr_pppol2tpv3in6 *sp6 = (struct sockaddr_pppol2tpv3in6 *) sp; ver = 3; fd = sp6->pppol2tp.fd; tunnel_id = sp6->pppol2tp.s_tunnel; peer_tunnel_id = sp6->pppol2tp.d_tunnel; session_id = sp6->pppol2tp.s_session; peer_session_id = sp6->pppol2tp.d_session; } else { error = -EINVAL; goto end; /* bad socket address */ } /* Don't bind if tunnel_id is 0 */ error = -EINVAL; if (tunnel_id == 0) goto end; tunnel = l2tp_tunnel_find(sock_net(sk), tunnel_id); /* Special case: create tunnel context if session_id and * peer_session_id is 0. Otherwise look up tunnel using supplied * tunnel id. */ if ((session_id == 0) && (peer_session_id == 0)) { if (tunnel == NULL) { struct l2tp_tunnel_cfg tcfg = { .encap = L2TP_ENCAPTYPE_UDP, .debug = 0, }; error = l2tp_tunnel_create(sock_net(sk), fd, ver, tunnel_id, peer_tunnel_id, &tcfg, &tunnel); if (error < 0) goto end; } } else { /* Error if we can't find the tunnel */ error = -ENOENT; if (tunnel == NULL) goto end; /* Error if socket is not prepped */ if (tunnel->sock == NULL) goto end; } if (tunnel->recv_payload_hook == NULL) tunnel->recv_payload_hook = pppol2tp_recv_payload_hook; if (tunnel->peer_tunnel_id == 0) tunnel->peer_tunnel_id = peer_tunnel_id; /* Create session if it doesn't already exist. We handle the * case where a session was previously created by the netlink * interface by checking that the session doesn't already have * a socket and its tunnel socket are what we expect. If any * of those checks fail, return EEXIST to the caller. */ session = l2tp_session_find(sock_net(sk), tunnel, session_id); if (session == NULL) { /* Default MTU must allow space for UDP/L2TP/PPP * headers. */ cfg.mtu = cfg.mru = 1500 - PPPOL2TP_HEADER_OVERHEAD; /* Allocate and initialize a new session context. */ session = l2tp_session_create(sizeof(struct pppol2tp_session), tunnel, session_id, peer_session_id, &cfg); if (session == NULL) { error = -ENOMEM; goto end; } } else { ps = l2tp_session_priv(session); error = -EEXIST; if (ps->sock != NULL) goto end; /* consistency checks */ if (ps->tunnel_sock != tunnel->sock) goto end; } /* Associate session with its PPPoL2TP socket */ ps = l2tp_session_priv(session); ps->owner = current->pid; ps->sock = sk; ps->tunnel_sock = tunnel->sock; session->recv_skb = pppol2tp_recv; session->session_close = pppol2tp_session_close; #if defined(CONFIG_L2TP_DEBUGFS) || defined(CONFIG_L2TP_DEBUGFS_MODULE) session->show = pppol2tp_show; #endif /* We need to know each time a skb is dropped from the reorder * queue. */ session->ref = pppol2tp_session_sock_hold; session->deref = pppol2tp_session_sock_put; /* If PMTU discovery was enabled, use the MTU that was discovered */ dst = sk_dst_get(sk); if (dst != NULL) { u32 pmtu = dst_mtu(__sk_dst_get(sk)); if (pmtu != 0) session->mtu = session->mru = pmtu - PPPOL2TP_HEADER_OVERHEAD; dst_release(dst); } /* Special case: if source & dest session_id == 0x0000, this * socket is being created to manage the tunnel. Just set up * the internal context for use by ioctl() and sockopt() * handlers. */ if ((session->session_id == 0) && (session->peer_session_id == 0)) { error = 0; goto out_no_ppp; } /* The only header we need to worry about is the L2TP * header. This size is different depending on whether * sequence numbers are enabled for the data channel. */ po->chan.hdrlen = PPPOL2TP_L2TP_HDR_SIZE_NOSEQ; po->chan.private = sk; po->chan.ops = &pppol2tp_chan_ops; po->chan.mtu = session->mtu; error = ppp_register_net_channel(sock_net(sk), &po->chan); if (error) goto end; out_no_ppp: /* This is how we get the session context from the socket. */ sk->sk_user_data = session; sk->sk_state = PPPOX_CONNECTED; l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: created\n", session->name); end: release_sock(sk); return error; } #ifdef CONFIG_L2TP_V3 /* Called when creating sessions via the netlink interface. */ static int pppol2tp_session_create(struct net *net, u32 tunnel_id, u32 session_id, u32 peer_session_id, struct l2tp_session_cfg *cfg) { int error; struct l2tp_tunnel *tunnel; struct l2tp_session *session; struct pppol2tp_session *ps; tunnel = l2tp_tunnel_find(net, tunnel_id); /* Error if we can't find the tunnel */ error = -ENOENT; if (tunnel == NULL) goto out; /* Error if tunnel socket is not prepped */ if (tunnel->sock == NULL) goto out; /* Check that this session doesn't already exist */ error = -EEXIST; session = l2tp_session_find(net, tunnel, session_id); if (session != NULL) goto out; /* Default MTU values. */ if (cfg->mtu == 0) cfg->mtu = 1500 - PPPOL2TP_HEADER_OVERHEAD; if (cfg->mru == 0) cfg->mru = cfg->mtu; /* Allocate and initialize a new session context. */ error = -ENOMEM; session = l2tp_session_create(sizeof(struct pppol2tp_session), tunnel, session_id, peer_session_id, cfg); if (session == NULL) goto out; ps = l2tp_session_priv(session); ps->tunnel_sock = tunnel->sock; l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: created\n", session->name); error = 0; out: return error; } #endif /* CONFIG_L2TP_V3 */ /* getname() support. */ static int pppol2tp_getname(struct socket *sock, struct sockaddr *uaddr, int *usockaddr_len, int peer) { int len = 0; int error = 0; struct l2tp_session *session; struct l2tp_tunnel *tunnel; struct sock *sk = sock->sk; struct inet_sock *inet; struct pppol2tp_session *pls; error = -ENOTCONN; if (sk == NULL) goto end; if (sk->sk_state != PPPOX_CONNECTED) goto end; error = -EBADF; session = pppol2tp_sock_to_session(sk); if (session == NULL) goto end; pls = l2tp_session_priv(session); tunnel = l2tp_sock_to_tunnel(pls->tunnel_sock); if (tunnel == NULL) { error = -EBADF; goto end_put_sess; } inet = inet_sk(tunnel->sock); if ((tunnel->version == 2) && (tunnel->sock->sk_family == AF_INET)) { struct sockaddr_pppol2tp sp; len = sizeof(sp); memset(&sp, 0, len); sp.sa_family = AF_PPPOX; sp.sa_protocol = PX_PROTO_OL2TP; sp.pppol2tp.fd = tunnel->fd; sp.pppol2tp.pid = pls->owner; sp.pppol2tp.s_tunnel = tunnel->tunnel_id; sp.pppol2tp.d_tunnel = tunnel->peer_tunnel_id; sp.pppol2tp.s_session = session->session_id; sp.pppol2tp.d_session = session->peer_session_id; sp.pppol2tp.addr.sin_family = AF_INET; sp.pppol2tp.addr.sin_port = inet->inet_dport; sp.pppol2tp.addr.sin_addr.s_addr = inet->inet_daddr; memcpy(uaddr, &sp, len); #if IS_ENABLED(CONFIG_IPV6) } else if ((tunnel->version == 2) && (tunnel->sock->sk_family == AF_INET6)) { struct ipv6_pinfo *np = inet6_sk(tunnel->sock); struct sockaddr_pppol2tpin6 sp; len = sizeof(sp); memset(&sp, 0, len); sp.sa_family = AF_PPPOX; sp.sa_protocol = PX_PROTO_OL2TP; sp.pppol2tp.fd = tunnel->fd; sp.pppol2tp.pid = pls->owner; sp.pppol2tp.s_tunnel = tunnel->tunnel_id; sp.pppol2tp.d_tunnel = tunnel->peer_tunnel_id; sp.pppol2tp.s_session = session->session_id; sp.pppol2tp.d_session = session->peer_session_id; sp.pppol2tp.addr.sin6_family = AF_INET6; sp.pppol2tp.addr.sin6_port = inet->inet_dport; memcpy(&sp.pppol2tp.addr.sin6_addr, &np->daddr, sizeof(np->daddr)); memcpy(uaddr, &sp, len); } else if ((tunnel->version == 3) && (tunnel->sock->sk_family == AF_INET6)) { struct ipv6_pinfo *np = inet6_sk(tunnel->sock); struct sockaddr_pppol2tpv3in6 sp; len = sizeof(sp); memset(&sp, 0, len); sp.sa_family = AF_PPPOX; sp.sa_protocol = PX_PROTO_OL2TP; sp.pppol2tp.fd = tunnel->fd; sp.pppol2tp.pid = pls->owner; sp.pppol2tp.s_tunnel = tunnel->tunnel_id; sp.pppol2tp.d_tunnel = tunnel->peer_tunnel_id; sp.pppol2tp.s_session = session->session_id; sp.pppol2tp.d_session = session->peer_session_id; sp.pppol2tp.addr.sin6_family = AF_INET6; sp.pppol2tp.addr.sin6_port = inet->inet_dport; memcpy(&sp.pppol2tp.addr.sin6_addr, &np->daddr, sizeof(np->daddr)); memcpy(uaddr, &sp, len); #endif } else if (tunnel->version == 3) { struct sockaddr_pppol2tpv3 sp; len = sizeof(sp); memset(&sp, 0, len); sp.sa_family = AF_PPPOX; sp.sa_protocol = PX_PROTO_OL2TP; sp.pppol2tp.fd = tunnel->fd; sp.pppol2tp.pid = pls->owner; sp.pppol2tp.s_tunnel = tunnel->tunnel_id; sp.pppol2tp.d_tunnel = tunnel->peer_tunnel_id; sp.pppol2tp.s_session = session->session_id; sp.pppol2tp.d_session = session->peer_session_id; sp.pppol2tp.addr.sin_family = AF_INET; sp.pppol2tp.addr.sin_port = inet->inet_dport; sp.pppol2tp.addr.sin_addr.s_addr = inet->inet_daddr; memcpy(uaddr, &sp, len); } *usockaddr_len = len; sock_put(pls->tunnel_sock); end_put_sess: sock_put(sk); error = 0; end: return error; } /**************************************************************************** * ioctl() handlers. * * The PPPoX socket is created for L2TP sessions: tunnels have their own UDP * sockets. However, in order to control kernel tunnel features, we allow * userspace to create a special "tunnel" PPPoX socket which is used for * control only. Tunnel PPPoX sockets have session_id == 0 and simply allow * the user application to issue L2TP setsockopt(), getsockopt() and ioctl() * calls. ****************************************************************************/ static void pppol2tp_copy_stats(struct pppol2tp_ioc_stats *dest, struct l2tp_stats *stats) { dest->tx_packets = atomic_long_read(&stats->tx_packets); dest->tx_bytes = atomic_long_read(&stats->tx_bytes); dest->tx_errors = atomic_long_read(&stats->tx_errors); dest->rx_packets = atomic_long_read(&stats->rx_packets); dest->rx_bytes = atomic_long_read(&stats->rx_bytes); dest->rx_seq_discards = atomic_long_read(&stats->rx_seq_discards); dest->rx_oos_packets = atomic_long_read(&stats->rx_oos_packets); dest->rx_errors = atomic_long_read(&stats->rx_errors); } /* Session ioctl helper. */ static int pppol2tp_session_ioctl(struct l2tp_session *session, unsigned int cmd, unsigned long arg) { struct ifreq ifr; int err = 0; struct sock *sk; int val = (int) arg; struct pppol2tp_session *ps = l2tp_session_priv(session); struct l2tp_tunnel *tunnel = session->tunnel; struct pppol2tp_ioc_stats stats; l2tp_dbg(session, PPPOL2TP_MSG_CONTROL, "%s: pppol2tp_session_ioctl(cmd=%#x, arg=%#lx)\n", session->name, cmd, arg); sk = ps->sock; sock_hold(sk); switch (cmd) { case SIOCGIFMTU: err = -ENXIO; if (!(sk->sk_state & PPPOX_CONNECTED)) break; err = -EFAULT; if (copy_from_user(&ifr, (void __user *) arg, sizeof(struct ifreq))) break; ifr.ifr_mtu = session->mtu; if (copy_to_user((void __user *) arg, &ifr, sizeof(struct ifreq))) break; l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get mtu=%d\n", session->name, session->mtu); err = 0; break; case SIOCSIFMTU: err = -ENXIO; if (!(sk->sk_state & PPPOX_CONNECTED)) break; err = -EFAULT; if (copy_from_user(&ifr, (void __user *) arg, sizeof(struct ifreq))) break; session->mtu = ifr.ifr_mtu; l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: set mtu=%d\n", session->name, session->mtu); err = 0; break; case PPPIOCGMRU: err = -ENXIO; if (!(sk->sk_state & PPPOX_CONNECTED)) break; err = -EFAULT; if (put_user(session->mru, (int __user *) arg)) break; l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get mru=%d\n", session->name, session->mru); err = 0; break; case PPPIOCSMRU: err = -ENXIO; if (!(sk->sk_state & PPPOX_CONNECTED)) break; err = -EFAULT; if (get_user(val, (int __user *) arg)) break; session->mru = val; l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: set mru=%d\n", session->name, session->mru); err = 0; break; case PPPIOCGFLAGS: err = -EFAULT; if (put_user(ps->flags, (int __user *) arg)) break; l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get flags=%d\n", session->name, ps->flags); err = 0; break; case PPPIOCSFLAGS: err = -EFAULT; if (get_user(val, (int __user *) arg)) break; ps->flags = val; l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: set flags=%d\n", session->name, ps->flags); err = 0; break; case PPPIOCGL2TPSTATS: err = -ENXIO; if (!(sk->sk_state & PPPOX_CONNECTED)) break; memset(&stats, 0, sizeof(stats)); stats.tunnel_id = tunnel->tunnel_id; stats.session_id = session->session_id; pppol2tp_copy_stats(&stats, &session->stats); if (copy_to_user((void __user *) arg, &stats, sizeof(stats))) break; l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get L2TP stats\n", session->name); err = 0; break; default: err = -ENOSYS; break; } sock_put(sk); return err; } /* Tunnel ioctl helper. * * Note the special handling for PPPIOCGL2TPSTATS below. If the ioctl data * specifies a session_id, the session ioctl handler is called. This allows an * application to retrieve session stats via a tunnel socket. */ static int pppol2tp_tunnel_ioctl(struct l2tp_tunnel *tunnel, unsigned int cmd, unsigned long arg) { int err = 0; struct sock *sk; struct pppol2tp_ioc_stats stats; l2tp_dbg(tunnel, PPPOL2TP_MSG_CONTROL, "%s: pppol2tp_tunnel_ioctl(cmd=%#x, arg=%#lx)\n", tunnel->name, cmd, arg); sk = tunnel->sock; sock_hold(sk); switch (cmd) { case PPPIOCGL2TPSTATS: err = -ENXIO; if (!(sk->sk_state & PPPOX_CONNECTED)) break; if (copy_from_user(&stats, (void __user *) arg, sizeof(stats))) { err = -EFAULT; break; } if (stats.session_id != 0) { /* resend to session ioctl handler */ struct l2tp_session *session = l2tp_session_find(sock_net(sk), tunnel, stats.session_id); if (session != NULL) err = pppol2tp_session_ioctl(session, cmd, arg); else err = -EBADR; break; } #ifdef CONFIG_XFRM stats.using_ipsec = (sk->sk_policy[0] || sk->sk_policy[1]) ? 1 : 0; #endif pppol2tp_copy_stats(&stats, &tunnel->stats); if (copy_to_user((void __user *) arg, &stats, sizeof(stats))) { err = -EFAULT; break; } l2tp_info(tunnel, PPPOL2TP_MSG_CONTROL, "%s: get L2TP stats\n", tunnel->name); err = 0; break; default: err = -ENOSYS; break; } sock_put(sk); return err; } /* Main ioctl() handler. * Dispatch to tunnel or session helpers depending on the socket. */ static int pppol2tp_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk = sock->sk; struct l2tp_session *session; struct l2tp_tunnel *tunnel; struct pppol2tp_session *ps; int err; if (!sk) return 0; err = -EBADF; if (sock_flag(sk, SOCK_DEAD) != 0) goto end; err = -ENOTCONN; if ((sk->sk_user_data == NULL) || (!(sk->sk_state & (PPPOX_CONNECTED | PPPOX_BOUND)))) goto end; /* Get session context from the socket */ err = -EBADF; session = pppol2tp_sock_to_session(sk); if (session == NULL) goto end; /* Special case: if session's session_id is zero, treat ioctl as a * tunnel ioctl */ ps = l2tp_session_priv(session); if ((session->session_id == 0) && (session->peer_session_id == 0)) { err = -EBADF; tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock); if (tunnel == NULL) goto end_put_sess; err = pppol2tp_tunnel_ioctl(tunnel, cmd, arg); sock_put(ps->tunnel_sock); goto end_put_sess; } err = pppol2tp_session_ioctl(session, cmd, arg); end_put_sess: sock_put(sk); end: return err; } /***************************************************************************** * setsockopt() / getsockopt() support. * * The PPPoX socket is created for L2TP sessions: tunnels have their own UDP * sockets. In order to control kernel tunnel features, we allow userspace to * create a special "tunnel" PPPoX socket which is used for control only. * Tunnel PPPoX sockets have session_id == 0 and simply allow the user * application to issue L2TP setsockopt(), getsockopt() and ioctl() calls. *****************************************************************************/ /* Tunnel setsockopt() helper. */ static int pppol2tp_tunnel_setsockopt(struct sock *sk, struct l2tp_tunnel *tunnel, int optname, int val) { int err = 0; switch (optname) { case PPPOL2TP_SO_DEBUG: tunnel->debug = val; l2tp_info(tunnel, PPPOL2TP_MSG_CONTROL, "%s: set debug=%x\n", tunnel->name, tunnel->debug); break; default: err = -ENOPROTOOPT; break; } return err; } /* Session setsockopt helper. */ static int pppol2tp_session_setsockopt(struct sock *sk, struct l2tp_session *session, int optname, int val) { int err = 0; struct pppol2tp_session *ps = l2tp_session_priv(session); switch (optname) { case PPPOL2TP_SO_RECVSEQ: if ((val != 0) && (val != 1)) { err = -EINVAL; break; } session->recv_seq = val ? -1 : 0; l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: set recv_seq=%d\n", session->name, session->recv_seq); break; case PPPOL2TP_SO_SENDSEQ: if ((val != 0) && (val != 1)) { err = -EINVAL; break; } session->send_seq = val ? -1 : 0; { struct sock *ssk = ps->sock; struct pppox_sock *po = pppox_sk(ssk); po->chan.hdrlen = val ? PPPOL2TP_L2TP_HDR_SIZE_SEQ : PPPOL2TP_L2TP_HDR_SIZE_NOSEQ; } l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: set send_seq=%d\n", session->name, session->send_seq); break; case PPPOL2TP_SO_LNSMODE: if ((val != 0) && (val != 1)) { err = -EINVAL; break; } session->lns_mode = val ? -1 : 0; l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: set lns_mode=%d\n", session->name, session->lns_mode); break; case PPPOL2TP_SO_DEBUG: session->debug = val; l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: set debug=%x\n", session->name, session->debug); break; case PPPOL2TP_SO_REORDERTO: session->reorder_timeout = msecs_to_jiffies(val); l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: set reorder_timeout=%d\n", session->name, session->reorder_timeout); break; default: err = -ENOPROTOOPT; break; } return err; } /* Main setsockopt() entry point. * Does API checks, then calls either the tunnel or session setsockopt * handler, according to whether the PPPoL2TP socket is a for a regular * session or the special tunnel type. */ static int pppol2tp_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct l2tp_session *session; struct l2tp_tunnel *tunnel; struct pppol2tp_session *ps; int val; int err; if (level != SOL_PPPOL2TP) return -EINVAL; if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; err = -ENOTCONN; if (sk->sk_user_data == NULL) goto end; /* Get session context from the socket */ err = -EBADF; session = pppol2tp_sock_to_session(sk); if (session == NULL) goto end; /* Special case: if session_id == 0x0000, treat as operation on tunnel */ ps = l2tp_session_priv(session); if ((session->session_id == 0) && (session->peer_session_id == 0)) { err = -EBADF; tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock); if (tunnel == NULL) goto end_put_sess; err = pppol2tp_tunnel_setsockopt(sk, tunnel, optname, val); sock_put(ps->tunnel_sock); } else err = pppol2tp_session_setsockopt(sk, session, optname, val); err = 0; end_put_sess: sock_put(sk); end: return err; } /* Tunnel getsockopt helper. Called with sock locked. */ static int pppol2tp_tunnel_getsockopt(struct sock *sk, struct l2tp_tunnel *tunnel, int optname, int *val) { int err = 0; switch (optname) { case PPPOL2TP_SO_DEBUG: *val = tunnel->debug; l2tp_info(tunnel, PPPOL2TP_MSG_CONTROL, "%s: get debug=%x\n", tunnel->name, tunnel->debug); break; default: err = -ENOPROTOOPT; break; } return err; } /* Session getsockopt helper. Called with sock locked. */ static int pppol2tp_session_getsockopt(struct sock *sk, struct l2tp_session *session, int optname, int *val) { int err = 0; switch (optname) { case PPPOL2TP_SO_RECVSEQ: *val = session->recv_seq; l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get recv_seq=%d\n", session->name, *val); break; case PPPOL2TP_SO_SENDSEQ: *val = session->send_seq; l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get send_seq=%d\n", session->name, *val); break; case PPPOL2TP_SO_LNSMODE: *val = session->lns_mode; l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get lns_mode=%d\n", session->name, *val); break; case PPPOL2TP_SO_DEBUG: *val = session->debug; l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get debug=%d\n", session->name, *val); break; case PPPOL2TP_SO_REORDERTO: *val = (int) jiffies_to_msecs(session->reorder_timeout); l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get reorder_timeout=%d\n", session->name, *val); break; default: err = -ENOPROTOOPT; } return err; } /* Main getsockopt() entry point. * Does API checks, then calls either the tunnel or session getsockopt * handler, according to whether the PPPoX socket is a for a regular session * or the special tunnel type. */ static int pppol2tp_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct l2tp_session *session; struct l2tp_tunnel *tunnel; int val, len; int err; struct pppol2tp_session *ps; if (level != SOL_PPPOL2TP) return -EINVAL; if (get_user(len, optlen)) return -EFAULT; len = min_t(unsigned int, len, sizeof(int)); if (len < 0) return -EINVAL; err = -ENOTCONN; if (sk->sk_user_data == NULL) goto end; /* Get the session context */ err = -EBADF; session = pppol2tp_sock_to_session(sk); if (session == NULL) goto end; /* Special case: if session_id == 0x0000, treat as operation on tunnel */ ps = l2tp_session_priv(session); if ((session->session_id == 0) && (session->peer_session_id == 0)) { err = -EBADF; tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock); if (tunnel == NULL) goto end_put_sess; err = pppol2tp_tunnel_getsockopt(sk, tunnel, optname, &val); sock_put(ps->tunnel_sock); } else err = pppol2tp_session_getsockopt(sk, session, optname, &val); err = -EFAULT; if (put_user(len, optlen)) goto end_put_sess; if (copy_to_user((void __user *) optval, &val, len)) goto end_put_sess; err = 0; end_put_sess: sock_put(sk); end: return err; } /***************************************************************************** * /proc filesystem for debug * Since the original pppol2tp driver provided /proc/net/pppol2tp for * L2TPv2, we dump only L2TPv2 tunnels and sessions here. *****************************************************************************/ static unsigned int pppol2tp_net_id; #ifdef CONFIG_PROC_FS struct pppol2tp_seq_data { struct seq_net_private p; int tunnel_idx; /* current tunnel */ int session_idx; /* index of session within current tunnel */ struct l2tp_tunnel *tunnel; struct l2tp_session *session; /* NULL means get next tunnel */ }; static void pppol2tp_next_tunnel(struct net *net, struct pppol2tp_seq_data *pd) { for (;;) { pd->tunnel = l2tp_tunnel_find_nth(net, pd->tunnel_idx); pd->tunnel_idx++; if (pd->tunnel == NULL) break; /* Ignore L2TPv3 tunnels */ if (pd->tunnel->version < 3) break; } } static void pppol2tp_next_session(struct net *net, struct pppol2tp_seq_data *pd) { pd->session = l2tp_session_find_nth(pd->tunnel, pd->session_idx); pd->session_idx++; if (pd->session == NULL) { pd->session_idx = 0; pppol2tp_next_tunnel(net, pd); } } static void *pppol2tp_seq_start(struct seq_file *m, loff_t *offs) { struct pppol2tp_seq_data *pd = SEQ_START_TOKEN; loff_t pos = *offs; struct net *net; if (!pos) goto out; BUG_ON(m->private == NULL); pd = m->private; net = seq_file_net(m); if (pd->tunnel == NULL) pppol2tp_next_tunnel(net, pd); else pppol2tp_next_session(net, pd); /* NULL tunnel and session indicates end of list */ if ((pd->tunnel == NULL) && (pd->session == NULL)) pd = NULL; out: return pd; } static void *pppol2tp_seq_next(struct seq_file *m, void *v, loff_t *pos) { (*pos)++; return NULL; } static void pppol2tp_seq_stop(struct seq_file *p, void *v) { /* nothing to do */ } static void pppol2tp_seq_tunnel_show(struct seq_file *m, void *v) { struct l2tp_tunnel *tunnel = v; seq_printf(m, "\nTUNNEL '%s', %c %d\n", tunnel->name, (tunnel == tunnel->sock->sk_user_data) ? 'Y' : 'N', atomic_read(&tunnel->ref_count) - 1); seq_printf(m, " %08x %ld/%ld/%ld %ld/%ld/%ld\n", tunnel->debug, atomic_long_read(&tunnel->stats.tx_packets), atomic_long_read(&tunnel->stats.tx_bytes), atomic_long_read(&tunnel->stats.tx_errors), atomic_long_read(&tunnel->stats.rx_packets), atomic_long_read(&tunnel->stats.rx_bytes), atomic_long_read(&tunnel->stats.rx_errors)); } static void pppol2tp_seq_session_show(struct seq_file *m, void *v) { struct l2tp_session *session = v; struct l2tp_tunnel *tunnel = session->tunnel; struct pppol2tp_session *ps = l2tp_session_priv(session); struct pppox_sock *po = pppox_sk(ps->sock); u32 ip = 0; u16 port = 0; if (tunnel->sock) { struct inet_sock *inet = inet_sk(tunnel->sock); ip = ntohl(inet->inet_saddr); port = ntohs(inet->inet_sport); } seq_printf(m, " SESSION '%s' %08X/%d %04X/%04X -> " "%04X/%04X %d %c\n", session->name, ip, port, tunnel->tunnel_id, session->session_id, tunnel->peer_tunnel_id, session->peer_session_id, ps->sock->sk_state, (session == ps->sock->sk_user_data) ? 'Y' : 'N'); seq_printf(m, " %d/%d/%c/%c/%s %08x %u\n", session->mtu, session->mru, session->recv_seq ? 'R' : '-', session->send_seq ? 'S' : '-', session->lns_mode ? "LNS" : "LAC", session->debug, jiffies_to_msecs(session->reorder_timeout)); seq_printf(m, " %hu/%hu %ld/%ld/%ld %ld/%ld/%ld\n", session->nr, session->ns, atomic_long_read(&session->stats.tx_packets), atomic_long_read(&session->stats.tx_bytes), atomic_long_read(&session->stats.tx_errors), atomic_long_read(&session->stats.rx_packets), atomic_long_read(&session->stats.rx_bytes), atomic_long_read(&session->stats.rx_errors)); if (po) seq_printf(m, " interface %s\n", ppp_dev_name(&po->chan)); } static int pppol2tp_seq_show(struct seq_file *m, void *v) { struct pppol2tp_seq_data *pd = v; /* display header on line 1 */ if (v == SEQ_START_TOKEN) { seq_puts(m, "PPPoL2TP driver info, " PPPOL2TP_DRV_VERSION "\n"); seq_puts(m, "TUNNEL name, user-data-ok session-count\n"); seq_puts(m, " debug tx-pkts/bytes/errs rx-pkts/bytes/errs\n"); seq_puts(m, " SESSION name, addr/port src-tid/sid " "dest-tid/sid state user-data-ok\n"); seq_puts(m, " mtu/mru/rcvseq/sendseq/lns debug reorderto\n"); seq_puts(m, " nr/ns tx-pkts/bytes/errs rx-pkts/bytes/errs\n"); goto out; } /* Show the tunnel or session context. */ if (pd->session == NULL) pppol2tp_seq_tunnel_show(m, pd->tunnel); else pppol2tp_seq_session_show(m, pd->session); out: return 0; } static const struct seq_operations pppol2tp_seq_ops = { .start = pppol2tp_seq_start, .next = pppol2tp_seq_next, .stop = pppol2tp_seq_stop, .show = pppol2tp_seq_show, }; /* Called when our /proc file is opened. We allocate data for use when * iterating our tunnel / session contexts and store it in the private * data of the seq_file. */ static int pppol2tp_proc_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &pppol2tp_seq_ops, sizeof(struct pppol2tp_seq_data)); } static const struct file_operations pppol2tp_proc_fops = { .owner = THIS_MODULE, .open = pppol2tp_proc_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; #endif /* CONFIG_PROC_FS */ /***************************************************************************** * Network namespace *****************************************************************************/ static __net_init int pppol2tp_init_net(struct net *net) { struct proc_dir_entry *pde; int err = 0; pde = proc_create("pppol2tp", S_IRUGO, net->proc_net, &pppol2tp_proc_fops); if (!pde) { err = -ENOMEM; goto out; } out: return err; } static __net_exit void pppol2tp_exit_net(struct net *net) { remove_proc_entry("pppol2tp", net->proc_net); } static struct pernet_operations pppol2tp_net_ops = { .init = pppol2tp_init_net, .exit = pppol2tp_exit_net, .id = &pppol2tp_net_id, }; /***************************************************************************** * Init and cleanup *****************************************************************************/ static const struct proto_ops pppol2tp_ops = { .family = AF_PPPOX, .owner = THIS_MODULE, .release = pppol2tp_release, .bind = sock_no_bind, .connect = pppol2tp_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = pppol2tp_getname, .poll = datagram_poll, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = pppol2tp_setsockopt, .getsockopt = pppol2tp_getsockopt, .sendmsg = pppol2tp_sendmsg, .recvmsg = pppol2tp_recvmsg, .mmap = sock_no_mmap, .ioctl = pppox_ioctl, }; static const struct pppox_proto pppol2tp_proto = { .create = pppol2tp_create, .ioctl = pppol2tp_ioctl, .owner = THIS_MODULE, }; #ifdef CONFIG_L2TP_V3 static const struct l2tp_nl_cmd_ops pppol2tp_nl_cmd_ops = { .session_create = pppol2tp_session_create, .session_delete = l2tp_session_delete, }; #endif /* CONFIG_L2TP_V3 */ static int __init pppol2tp_init(void) { int err; err = register_pernet_device(&pppol2tp_net_ops); if (err) goto out; err = proto_register(&pppol2tp_sk_proto, 0); if (err) goto out_unregister_pppol2tp_pernet; err = register_pppox_proto(PX_PROTO_OL2TP, &pppol2tp_proto); if (err) goto out_unregister_pppol2tp_proto; #ifdef CONFIG_L2TP_V3 err = l2tp_nl_register_ops(L2TP_PWTYPE_PPP, &pppol2tp_nl_cmd_ops); if (err) goto out_unregister_pppox; #endif pr_info("PPPoL2TP kernel driver, %s\n", PPPOL2TP_DRV_VERSION); out: return err; #ifdef CONFIG_L2TP_V3 out_unregister_pppox: unregister_pppox_proto(PX_PROTO_OL2TP); #endif out_unregister_pppol2tp_proto: proto_unregister(&pppol2tp_sk_proto); out_unregister_pppol2tp_pernet: unregister_pernet_device(&pppol2tp_net_ops); goto out; } static void __exit pppol2tp_exit(void) { #ifdef CONFIG_L2TP_V3 l2tp_nl_unregister_ops(L2TP_PWTYPE_PPP); #endif unregister_pppox_proto(PX_PROTO_OL2TP); proto_unregister(&pppol2tp_sk_proto); unregister_pernet_device(&pppol2tp_net_ops); } module_init(pppol2tp_init); module_exit(pppol2tp_exit); MODULE_AUTHOR("James Chapman <jchapman@katalix.com>"); MODULE_DESCRIPTION("PPP over L2TP over UDP"); MODULE_LICENSE("GPL"); MODULE_VERSION(PPPOL2TP_DRV_VERSION); MODULE_ALIAS("pppox-proto-" __stringify(PX_PROTO_OL2TP));
gpl-2.0
GenetICS/lge_kernel_msm7x27
net/socket.c
216
83655
/* * NET An implementation of the SOCKET network access protocol. * * Version: @(#)socket.c 1.1.93 18/02/95 * * Authors: Orest Zborowski, <obz@Kodak.COM> * Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * * Fixes: * Anonymous : NOTSOCK/BADF cleanup. Error fix in * shutdown() * Alan Cox : verify_area() fixes * Alan Cox : Removed DDI * Jonathan Kamens : SOCK_DGRAM reconnect bug * Alan Cox : Moved a load of checks to the very * top level. * Alan Cox : Move address structures to/from user * mode above the protocol layers. * Rob Janssen : Allow 0 length sends. * Alan Cox : Asynchronous I/O support (cribbed from the * tty drivers). * Niibe Yutaka : Asynchronous I/O for writes (4.4BSD style) * Jeff Uphoff : Made max number of sockets command-line * configurable. * Matti Aarnio : Made the number of sockets dynamic, * to be allocated when needed, and mr. * Uphoff's max is used as max to be * allowed to allocate. * Linus : Argh. removed all the socket allocation * altogether: it's in the inode now. * Alan Cox : Made sock_alloc()/sock_release() public * for NetROM and future kernel nfsd type * stuff. * Alan Cox : sendmsg/recvmsg basics. * Tom Dyas : Export net symbols. * Marcin Dalecki : Fixed problems with CONFIG_NET="n". * Alan Cox : Added thread locking to sys_* calls * for sockets. May have errors at the * moment. * Kevin Buhr : Fixed the dumb errors in the above. * Andi Kleen : Some small cleanups, optimizations, * and fixed a copy_from_user() bug. * Tigran Aivazian : sys_send(args) calls sys_sendto(args, NULL, 0) * Tigran Aivazian : Made listen(2) backlog sanity checks * protocol-independent * * * 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 module is effectively the top level interface to the BSD socket * paradigm. * * Based upon Swansea University Computer Society NET3.039 */ #include <linux/mm.h> #include <linux/socket.h> #include <linux/file.h> #include <linux/net.h> #include <linux/interrupt.h> #include <linux/thread_info.h> #include <linux/rcupdate.h> #include <linux/netdevice.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/mutex.h> #include <linux/wanrouter.h> #include <linux/if_bridge.h> #include <linux/if_frad.h> #include <linux/if_vlan.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/cache.h> #include <linux/module.h> #include <linux/highmem.h> #include <linux/mount.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/compat.h> #include <linux/kmod.h> #include <linux/audit.h> #include <linux/wireless.h> #include <linux/nsproxy.h> #include <linux/magic.h> #include <linux/slab.h> #include <asm/uaccess.h> #include <asm/unistd.h> #include <net/compat.h> #include <net/wext.h> #include <net/cls_cgroup.h> #include <net/sock.h> #include <linux/netfilter.h> #include <linux/if_tun.h> #include <linux/ipv6_route.h> #include <linux/route.h> #include <linux/sockios.h> #include <linux/atalk.h> static int sock_no_open(struct inode *irrelevant, struct file *dontcare); static ssize_t sock_aio_read(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos); static ssize_t sock_aio_write(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos); static int sock_mmap(struct file *file, struct vm_area_struct *vma); static int sock_close(struct inode *inode, struct file *file); static unsigned int sock_poll(struct file *file, struct poll_table_struct *wait); static long sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg); #ifdef CONFIG_COMPAT static long compat_sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg); #endif static int sock_fasync(int fd, struct file *filp, int on); static ssize_t sock_sendpage(struct file *file, struct page *page, int offset, size_t size, loff_t *ppos, int more); static ssize_t sock_splice_read(struct file *file, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags); /* * Socket files have a set of 'special' operations as well as the generic file ones. These don't appear * in the operation structures but are done directly via the socketcall() multiplexor. */ static const struct file_operations socket_file_ops = { .owner = THIS_MODULE, .llseek = no_llseek, .aio_read = sock_aio_read, .aio_write = sock_aio_write, .poll = sock_poll, .unlocked_ioctl = sock_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = compat_sock_ioctl, #endif .mmap = sock_mmap, .open = sock_no_open, /* special open code to disallow open via /proc */ .release = sock_close, .fasync = sock_fasync, .sendpage = sock_sendpage, .splice_write = generic_splice_sendpage, .splice_read = sock_splice_read, }; /* * The protocol list. Each protocol is registered in here. */ static DEFINE_SPINLOCK(net_family_lock); static const struct net_proto_family __rcu *net_families[NPROTO] __read_mostly; /* * Statistics counters of the socket lists */ static DEFINE_PER_CPU(int, sockets_in_use); /* * Support routines. * Move socket addresses back and forth across the kernel/user * divide and look after the messy bits. */ /** * move_addr_to_kernel - copy a socket address into kernel space * @uaddr: Address in user space * @kaddr: Address in kernel space * @ulen: Length in user space * * The address is copied into kernel space. If the provided address is * too long an error code of -EINVAL is returned. If the copy gives * invalid addresses -EFAULT is returned. On a success 0 is returned. */ int move_addr_to_kernel(void __user *uaddr, int ulen, struct sockaddr *kaddr) { if (ulen < 0 || ulen > sizeof(struct sockaddr_storage)) return -EINVAL; if (ulen == 0) return 0; if (copy_from_user(kaddr, uaddr, ulen)) return -EFAULT; return audit_sockaddr(ulen, kaddr); } /** * move_addr_to_user - copy an address to user space * @kaddr: kernel space address * @klen: length of address in kernel * @uaddr: user space address * @ulen: pointer to user length field * * The value pointed to by ulen on entry is the buffer length available. * This is overwritten with the buffer space used. -EINVAL is returned * if an overlong buffer is specified or a negative buffer size. -EFAULT * is returned if either the buffer or the length field are not * accessible. * After copying the data up to the limit the user specifies, the true * length of the data is written over the length limit the user * specified. Zero is returned for a success. */ static int move_addr_to_user(struct sockaddr *kaddr, int klen, void __user *uaddr, int __user *ulen) { int err; int len; err = get_user(len, ulen); if (err) return err; if (len > klen) len = klen; if (len < 0 || len > sizeof(struct sockaddr_storage)) return -EINVAL; if (len) { if (audit_sockaddr(klen, kaddr)) return -ENOMEM; if (copy_to_user(uaddr, kaddr, len)) return -EFAULT; } /* * "fromlen shall refer to the value before truncation.." * 1003.1g */ return __put_user(klen, ulen); } static struct kmem_cache *sock_inode_cachep __read_mostly; static struct inode *sock_alloc_inode(struct super_block *sb) { struct socket_alloc *ei; struct socket_wq *wq; ei = kmem_cache_alloc(sock_inode_cachep, GFP_KERNEL); if (!ei) return NULL; wq = kmalloc(sizeof(*wq), GFP_KERNEL); if (!wq) { kmem_cache_free(sock_inode_cachep, ei); return NULL; } init_waitqueue_head(&wq->wait); wq->fasync_list = NULL; RCU_INIT_POINTER(ei->socket.wq, wq); ei->socket.state = SS_UNCONNECTED; ei->socket.flags = 0; ei->socket.ops = NULL; ei->socket.sk = NULL; ei->socket.file = NULL; return &ei->vfs_inode; } static void sock_destroy_inode(struct inode *inode) { struct socket_alloc *ei; struct socket_wq *wq; ei = container_of(inode, struct socket_alloc, vfs_inode); wq = rcu_dereference_protected(ei->socket.wq, 1); kfree_rcu(wq, rcu); kmem_cache_free(sock_inode_cachep, ei); } static void init_once(void *foo) { struct socket_alloc *ei = (struct socket_alloc *)foo; inode_init_once(&ei->vfs_inode); } static int init_inodecache(void) { sock_inode_cachep = kmem_cache_create("sock_inode_cache", sizeof(struct socket_alloc), 0, (SLAB_HWCACHE_ALIGN | SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD), init_once); if (sock_inode_cachep == NULL) return -ENOMEM; return 0; } static const struct super_operations sockfs_ops = { .alloc_inode = sock_alloc_inode, .destroy_inode = sock_destroy_inode, .statfs = simple_statfs, }; /* * sockfs_dname() is called from d_path(). */ static char *sockfs_dname(struct dentry *dentry, char *buffer, int buflen) { return dynamic_dname(dentry, buffer, buflen, "socket:[%lu]", dentry->d_inode->i_ino); } static const struct dentry_operations sockfs_dentry_operations = { .d_dname = sockfs_dname, }; static struct dentry *sockfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_pseudo(fs_type, "socket:", &sockfs_ops, &sockfs_dentry_operations, SOCKFS_MAGIC); } static struct vfsmount *sock_mnt __read_mostly; static struct file_system_type sock_fs_type = { .name = "sockfs", .mount = sockfs_mount, .kill_sb = kill_anon_super, }; /* * Obtains the first available file descriptor and sets it up for use. * * These functions create file structures and maps them to fd space * of the current process. On success it returns file descriptor * and file struct implicitly stored in sock->file. * Note that another thread may close file descriptor before we return * from this function. We use the fact that now we do not refer * to socket after mapping. If one day we will need it, this * function will increment ref. count on file by 1. * * In any case returned fd MAY BE not valid! * This race condition is unavoidable * with shared fd spaces, we cannot solve it inside kernel, * but we take care of internal coherence yet. */ static int sock_alloc_file(struct socket *sock, struct file **f, int flags) { struct qstr name = { .name = "" }; struct path path; struct file *file; int fd; fd = get_unused_fd_flags(flags); if (unlikely(fd < 0)) return fd; path.dentry = d_alloc_pseudo(sock_mnt->mnt_sb, &name); if (unlikely(!path.dentry)) { put_unused_fd(fd); return -ENOMEM; } path.mnt = mntget(sock_mnt); d_instantiate(path.dentry, SOCK_INODE(sock)); SOCK_INODE(sock)->i_fop = &socket_file_ops; file = alloc_file(&path, FMODE_READ | FMODE_WRITE, &socket_file_ops); if (unlikely(!file)) { /* drop dentry, keep inode */ ihold(path.dentry->d_inode); path_put(&path); put_unused_fd(fd); return -ENFILE; } sock->file = file; file->f_flags = O_RDWR | (flags & O_NONBLOCK); file->f_pos = 0; file->private_data = sock; *f = file; return fd; } int sock_map_fd(struct socket *sock, int flags) { struct file *newfile; int fd = sock_alloc_file(sock, &newfile, flags); if (likely(fd >= 0)) fd_install(fd, newfile); return fd; } EXPORT_SYMBOL(sock_map_fd); static struct socket *sock_from_file(struct file *file, int *err) { if (file->f_op == &socket_file_ops) return file->private_data; /* set in sock_map_fd */ *err = -ENOTSOCK; return NULL; } /** * sockfd_lookup - Go from a file number to its socket slot * @fd: file handle * @err: pointer to an error code return * * The file handle passed in is locked and the socket it is bound * too is returned. If an error occurs the err pointer is overwritten * with a negative errno code and NULL is returned. The function checks * for both invalid handles and passing a handle which is not a socket. * * On a success the socket object pointer is returned. */ struct socket *sockfd_lookup(int fd, int *err) { struct file *file; struct socket *sock; file = fget(fd); if (!file) { *err = -EBADF; return NULL; } sock = sock_from_file(file, err); if (!sock) fput(file); return sock; } EXPORT_SYMBOL(sockfd_lookup); static struct socket *sockfd_lookup_light(int fd, int *err, int *fput_needed) { struct file *file; struct socket *sock; *err = -EBADF; file = fget_light(fd, fput_needed); if (file) { sock = sock_from_file(file, err); if (sock) return sock; fput_light(file, *fput_needed); } return NULL; } /** * sock_alloc - allocate a socket * * Allocate a new inode and socket object. The two are bound together * and initialised. The socket is then returned. If we are out of inodes * NULL is returned. */ static struct socket *sock_alloc(void) { struct inode *inode; struct socket *sock; inode = new_inode_pseudo(sock_mnt->mnt_sb); if (!inode) return NULL; sock = SOCKET_I(inode); kmemcheck_annotate_bitfield(sock, type); inode->i_ino = get_next_ino(); inode->i_mode = S_IFSOCK | S_IRWXUGO; inode->i_uid = current_fsuid(); inode->i_gid = current_fsgid(); percpu_add(sockets_in_use, 1); return sock; } /* * In theory you can't get an open on this inode, but /proc provides * a back door. Remember to keep it shut otherwise you'll let the * creepy crawlies in. */ static int sock_no_open(struct inode *irrelevant, struct file *dontcare) { return -ENXIO; } const struct file_operations bad_sock_fops = { .owner = THIS_MODULE, .open = sock_no_open, .llseek = noop_llseek, }; /** * sock_release - close a socket * @sock: socket to close * * The socket is released from the protocol stack if it has a release * callback, and the inode is then released if the socket is bound to * an inode not a file. */ void sock_release(struct socket *sock) { if (sock->ops) { struct module *owner = sock->ops->owner; sock->ops->release(sock); sock->ops = NULL; module_put(owner); } if (rcu_dereference_protected(sock->wq, 1)->fasync_list) printk(KERN_ERR "sock_release: fasync list not empty!\n"); percpu_sub(sockets_in_use, 1); if (!sock->file) { iput(SOCK_INODE(sock)); return; } sock->file = NULL; } EXPORT_SYMBOL(sock_release); int sock_tx_timestamp(struct sock *sk, __u8 *tx_flags) { *tx_flags = 0; if (sock_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE)) *tx_flags |= SKBTX_HW_TSTAMP; if (sock_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE)) *tx_flags |= SKBTX_SW_TSTAMP; return 0; } EXPORT_SYMBOL(sock_tx_timestamp); static inline int __sock_sendmsg_nosec(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size) { struct sock_iocb *si = kiocb_to_siocb(iocb); sock_update_classid(sock->sk); si->sock = sock; si->scm = NULL; si->msg = msg; si->size = size; return sock->ops->sendmsg(iocb, sock, msg, size); } static inline int __sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size) { int err = security_socket_sendmsg(sock, msg, size); return err ?: __sock_sendmsg_nosec(iocb, sock, msg, size); } int sock_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) { struct kiocb iocb; struct sock_iocb siocb; int ret; init_sync_kiocb(&iocb, NULL); iocb.private = &siocb; ret = __sock_sendmsg(&iocb, sock, msg, size); if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&iocb); return ret; } EXPORT_SYMBOL(sock_sendmsg); int sock_sendmsg_nosec(struct socket *sock, struct msghdr *msg, size_t size) { struct kiocb iocb; struct sock_iocb siocb; int ret; init_sync_kiocb(&iocb, NULL); iocb.private = &siocb; ret = __sock_sendmsg_nosec(&iocb, sock, msg, size); if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&iocb); return ret; } int kernel_sendmsg(struct socket *sock, struct msghdr *msg, struct kvec *vec, size_t num, size_t size) { mm_segment_t oldfs = get_fs(); int result; set_fs(KERNEL_DS); /* * the following is safe, since for compiler definitions of kvec and * iovec are identical, yielding the same in-core layout and alignment */ msg->msg_iov = (struct iovec *)vec; msg->msg_iovlen = num; result = sock_sendmsg(sock, msg, size); set_fs(oldfs); return result; } EXPORT_SYMBOL(kernel_sendmsg); static int ktime2ts(ktime_t kt, struct timespec *ts) { if (kt.tv64) { *ts = ktime_to_timespec(kt); return 1; } else { return 0; } } /* * called from sock_recv_timestamp() if sock_flag(sk, SOCK_RCVTSTAMP) */ void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct timespec ts[3]; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp.tv64 == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { skb_get_timestampns(skb, &ts[0]); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts[0]), &ts[0]); } } memset(ts, 0, sizeof(ts)); if (skb->tstamp.tv64 && sock_flag(sk, SOCK_TIMESTAMPING_SOFTWARE)) { skb_get_timestampns(skb, ts + 0); empty = 0; } if (shhwtstamps) { if (sock_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE) && ktime2ts(shhwtstamps->syststamp, ts + 1)) empty = 0; if (sock_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE) && ktime2ts(shhwtstamps->hwtstamp, ts + 2)) empty = 0; } if (!empty) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(ts), &ts); } EXPORT_SYMBOL_GPL(__sock_recv_timestamp); static inline void sock_recv_drops(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { if (sock_flag(sk, SOCK_RXQ_OVFL) && skb && skb->dropcount) put_cmsg(msg, SOL_SOCKET, SO_RXQ_OVFL, sizeof(__u32), &skb->dropcount); } void __sock_recv_ts_and_drops(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { sock_recv_timestamp(msg, sk, skb); sock_recv_drops(msg, sk, skb); } EXPORT_SYMBOL_GPL(__sock_recv_ts_and_drops); static inline int __sock_recvmsg_nosec(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock_iocb *si = kiocb_to_siocb(iocb); sock_update_classid(sock->sk); si->sock = sock; si->scm = NULL; si->msg = msg; si->size = size; si->flags = flags; return sock->ops->recvmsg(iocb, sock, msg, size, flags); } static inline int __sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { int err = security_socket_recvmsg(sock, msg, size, flags); return err ?: __sock_recvmsg_nosec(iocb, sock, msg, size, flags); } int sock_recvmsg(struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct kiocb iocb; struct sock_iocb siocb; int ret; init_sync_kiocb(&iocb, NULL); iocb.private = &siocb; ret = __sock_recvmsg(&iocb, sock, msg, size, flags); if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&iocb); return ret; } EXPORT_SYMBOL(sock_recvmsg); static int sock_recvmsg_nosec(struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct kiocb iocb; struct sock_iocb siocb; int ret; init_sync_kiocb(&iocb, NULL); iocb.private = &siocb; ret = __sock_recvmsg_nosec(&iocb, sock, msg, size, flags); if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&iocb); return ret; } /** * kernel_recvmsg - Receive a message from a socket (kernel space) * @sock: The socket to receive the message from * @msg: Received message * @vec: Input s/g array for message data * @num: Size of input s/g array * @size: Number of bytes to read * @flags: Message flags (MSG_DONTWAIT, etc...) * * On return the msg structure contains the scatter/gather array passed in the * vec argument. The array is modified so that it consists of the unfilled * portion of the original array. * * The returned value is the total number of bytes received, or an error. */ int kernel_recvmsg(struct socket *sock, struct msghdr *msg, struct kvec *vec, size_t num, size_t size, int flags) { mm_segment_t oldfs = get_fs(); int result; set_fs(KERNEL_DS); /* * the following is safe, since for compiler definitions of kvec and * iovec are identical, yielding the same in-core layout and alignment */ msg->msg_iov = (struct iovec *)vec, msg->msg_iovlen = num; result = sock_recvmsg(sock, msg, size, flags); set_fs(oldfs); return result; } EXPORT_SYMBOL(kernel_recvmsg); static void sock_aio_dtor(struct kiocb *iocb) { kfree(iocb->private); } static ssize_t sock_sendpage(struct file *file, struct page *page, int offset, size_t size, loff_t *ppos, int more) { struct socket *sock; int flags; sock = file->private_data; flags = !(file->f_flags & O_NONBLOCK) ? 0 : MSG_DONTWAIT; if (more) flags |= MSG_MORE; return kernel_sendpage(sock, page, offset, size, flags); } static ssize_t sock_splice_read(struct file *file, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { struct socket *sock = file->private_data; if (unlikely(!sock->ops->splice_read)) return -EINVAL; sock_update_classid(sock->sk); return sock->ops->splice_read(sock, ppos, pipe, len, flags); } static struct sock_iocb *alloc_sock_iocb(struct kiocb *iocb, struct sock_iocb *siocb) { if (!is_sync_kiocb(iocb)) { siocb = kmalloc(sizeof(*siocb), GFP_KERNEL); if (!siocb) return NULL; iocb->ki_dtor = sock_aio_dtor; } siocb->kiocb = iocb; iocb->private = siocb; return siocb; } static ssize_t do_sock_read(struct msghdr *msg, struct kiocb *iocb, struct file *file, const struct iovec *iov, unsigned long nr_segs) { struct socket *sock = file->private_data; size_t size = 0; int i; for (i = 0; i < nr_segs; i++) size += iov[i].iov_len; msg->msg_name = NULL; msg->msg_namelen = 0; msg->msg_control = NULL; msg->msg_controllen = 0; msg->msg_iov = (struct iovec *)iov; msg->msg_iovlen = nr_segs; msg->msg_flags = (file->f_flags & O_NONBLOCK) ? MSG_DONTWAIT : 0; return __sock_recvmsg(iocb, sock, msg, size, msg->msg_flags); } static ssize_t sock_aio_read(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos) { struct sock_iocb siocb, *x; if (pos != 0) return -ESPIPE; if (iocb->ki_left == 0) /* Match SYS5 behaviour */ return 0; x = alloc_sock_iocb(iocb, &siocb); if (!x) return -ENOMEM; return do_sock_read(&x->async_msg, iocb, iocb->ki_filp, iov, nr_segs); } static ssize_t do_sock_write(struct msghdr *msg, struct kiocb *iocb, struct file *file, const struct iovec *iov, unsigned long nr_segs) { struct socket *sock = file->private_data; size_t size = 0; int i; for (i = 0; i < nr_segs; i++) size += iov[i].iov_len; msg->msg_name = NULL; msg->msg_namelen = 0; msg->msg_control = NULL; msg->msg_controllen = 0; msg->msg_iov = (struct iovec *)iov; msg->msg_iovlen = nr_segs; msg->msg_flags = (file->f_flags & O_NONBLOCK) ? MSG_DONTWAIT : 0; if (sock->type == SOCK_SEQPACKET) msg->msg_flags |= MSG_EOR; return __sock_sendmsg(iocb, sock, msg, size); } static ssize_t sock_aio_write(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos) { struct sock_iocb siocb, *x; if (pos != 0) return -ESPIPE; x = alloc_sock_iocb(iocb, &siocb); if (!x) return -ENOMEM; return do_sock_write(&x->async_msg, iocb, iocb->ki_filp, iov, nr_segs); } /* * Atomic setting of ioctl hooks to avoid race * with module unload. */ static DEFINE_MUTEX(br_ioctl_mutex); static int (*br_ioctl_hook) (struct net *, unsigned int cmd, void __user *arg); void brioctl_set(int (*hook) (struct net *, unsigned int, void __user *)) { mutex_lock(&br_ioctl_mutex); br_ioctl_hook = hook; mutex_unlock(&br_ioctl_mutex); } EXPORT_SYMBOL(brioctl_set); static DEFINE_MUTEX(vlan_ioctl_mutex); static int (*vlan_ioctl_hook) (struct net *, void __user *arg); void vlan_ioctl_set(int (*hook) (struct net *, void __user *)) { mutex_lock(&vlan_ioctl_mutex); vlan_ioctl_hook = hook; mutex_unlock(&vlan_ioctl_mutex); } EXPORT_SYMBOL(vlan_ioctl_set); static DEFINE_MUTEX(dlci_ioctl_mutex); static int (*dlci_ioctl_hook) (unsigned int, void __user *); void dlci_ioctl_set(int (*hook) (unsigned int, void __user *)) { mutex_lock(&dlci_ioctl_mutex); dlci_ioctl_hook = hook; mutex_unlock(&dlci_ioctl_mutex); } EXPORT_SYMBOL(dlci_ioctl_set); static long sock_do_ioctl(struct net *net, struct socket *sock, unsigned int cmd, unsigned long arg) { int err; void __user *argp = (void __user *)arg; err = sock->ops->ioctl(sock, cmd, arg); /* * If this ioctl is unknown try to hand it down * to the NIC driver. */ if (err == -ENOIOCTLCMD) err = dev_ioctl(net, cmd, argp); return err; } /* * With an ioctl, arg may well be a user mode pointer, but we don't know * what to do with it - that's up to the protocol still. */ static long sock_ioctl(struct file *file, unsigned cmd, unsigned long arg) { struct socket *sock; struct sock *sk; void __user *argp = (void __user *)arg; int pid, err; struct net *net; sock = file->private_data; sk = sock->sk; net = sock_net(sk); if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15)) { err = dev_ioctl(net, cmd, argp); } else #ifdef CONFIG_WEXT_CORE if (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST) { err = dev_ioctl(net, cmd, argp); } else #endif switch (cmd) { case FIOSETOWN: case SIOCSPGRP: err = -EFAULT; if (get_user(pid, (int __user *)argp)) break; err = f_setown(sock->file, pid, 1); break; case FIOGETOWN: case SIOCGPGRP: err = put_user(f_getown(sock->file), (int __user *)argp); break; case SIOCGIFBR: case SIOCSIFBR: case SIOCBRADDBR: case SIOCBRDELBR: err = -ENOPKG; if (!br_ioctl_hook) request_module("bridge"); mutex_lock(&br_ioctl_mutex); if (br_ioctl_hook) err = br_ioctl_hook(net, cmd, argp); mutex_unlock(&br_ioctl_mutex); break; case SIOCGIFVLAN: case SIOCSIFVLAN: err = -ENOPKG; if (!vlan_ioctl_hook) request_module("8021q"); mutex_lock(&vlan_ioctl_mutex); if (vlan_ioctl_hook) err = vlan_ioctl_hook(net, argp); mutex_unlock(&vlan_ioctl_mutex); break; case SIOCADDDLCI: case SIOCDELDLCI: err = -ENOPKG; if (!dlci_ioctl_hook) request_module("dlci"); mutex_lock(&dlci_ioctl_mutex); if (dlci_ioctl_hook) err = dlci_ioctl_hook(cmd, argp); mutex_unlock(&dlci_ioctl_mutex); break; default: err = sock_do_ioctl(net, sock, cmd, arg); break; } return err; } int sock_create_lite(int family, int type, int protocol, struct socket **res) { int err; struct socket *sock = NULL; err = security_socket_create(family, type, protocol, 1); if (err) goto out; sock = sock_alloc(); if (!sock) { err = -ENOMEM; goto out; } sock->type = type; err = security_socket_post_create(sock, family, type, protocol, 1); if (err) goto out_release; out: *res = sock; return err; out_release: sock_release(sock); sock = NULL; goto out; } EXPORT_SYMBOL(sock_create_lite); /* No kernel lock held - perfect */ static unsigned int sock_poll(struct file *file, poll_table *wait) { struct socket *sock; /* * We can't return errors to poll, so it's either yes or no. */ sock = file->private_data; return sock->ops->poll(file, sock, wait); } static int sock_mmap(struct file *file, struct vm_area_struct *vma) { struct socket *sock = file->private_data; return sock->ops->mmap(file, sock, vma); } static int sock_close(struct inode *inode, struct file *filp) { /* * It was possible the inode is NULL we were * closing an unfinished socket. */ if (!inode) { printk(KERN_DEBUG "sock_close: NULL inode\n"); return 0; } sock_release(SOCKET_I(inode)); return 0; } /* * Update the socket async list * * Fasync_list locking strategy. * * 1. fasync_list is modified only under process context socket lock * i.e. under semaphore. * 2. fasync_list is used under read_lock(&sk->sk_callback_lock) * or under socket lock */ static int sock_fasync(int fd, struct file *filp, int on) { struct socket *sock = filp->private_data; struct sock *sk = sock->sk; struct socket_wq *wq; if (sk == NULL) return -EINVAL; lock_sock(sk); wq = rcu_dereference_protected(sock->wq, sock_owned_by_user(sk)); fasync_helper(fd, filp, on, &wq->fasync_list); if (!wq->fasync_list) sock_reset_flag(sk, SOCK_FASYNC); else sock_set_flag(sk, SOCK_FASYNC); release_sock(sk); return 0; } /* This function may be called only under socket lock or callback_lock or rcu_lock */ int sock_wake_async(struct socket *sock, int how, int band) { struct socket_wq *wq; if (!sock) return -1; rcu_read_lock(); wq = rcu_dereference(sock->wq); if (!wq || !wq->fasync_list) { rcu_read_unlock(); return -1; } switch (how) { case SOCK_WAKE_WAITD: if (test_bit(SOCK_ASYNC_WAITDATA, &sock->flags)) break; goto call_kill; case SOCK_WAKE_SPACE: if (!test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sock->flags)) break; /* fall through */ case SOCK_WAKE_IO: call_kill: kill_fasync(&wq->fasync_list, SIGIO, band); break; case SOCK_WAKE_URG: kill_fasync(&wq->fasync_list, SIGURG, band); } rcu_read_unlock(); return 0; } EXPORT_SYMBOL(sock_wake_async); int __sock_create(struct net *net, int family, int type, int protocol, struct socket **res, int kern) { int err; struct socket *sock; const struct net_proto_family *pf; /* * Check protocol is in range */ if (family < 0 || family >= NPROTO) return -EAFNOSUPPORT; if (type < 0 || type >= SOCK_MAX) return -EINVAL; /* Compatibility. This uglymoron is moved from INET layer to here to avoid deadlock in module load. */ if (family == PF_INET && type == SOCK_PACKET) { static int warned; if (!warned) { warned = 1; printk(KERN_INFO "%s uses obsolete (PF_INET,SOCK_PACKET)\n", current->comm); } family = PF_PACKET; } err = security_socket_create(family, type, protocol, kern); if (err) return err; /* * Allocate the socket and allow the family to set things up. if * the protocol is 0, the family is instructed to select an appropriate * default. */ sock = sock_alloc(); if (!sock) { if (net_ratelimit()) printk(KERN_WARNING "socket: no more sockets\n"); return -ENFILE; /* Not exactly a match, but its the closest posix thing */ } sock->type = type; #ifdef CONFIG_MODULES /* Attempt to load a protocol module if the find failed. * * 12/09/1996 Marcin: But! this makes REALLY only sense, if the user * requested real, full-featured networking support upon configuration. * Otherwise module support will break! */ if (rcu_access_pointer(net_families[family]) == NULL) request_module("net-pf-%d", family); #endif rcu_read_lock(); pf = rcu_dereference(net_families[family]); err = -EAFNOSUPPORT; if (!pf) goto out_release; /* * We will call the ->create function, that possibly is in a loadable * module, so we have to bump that loadable module refcnt first. */ if (!try_module_get(pf->owner)) goto out_release; /* Now protected by module ref count */ rcu_read_unlock(); err = pf->create(net, sock, protocol, kern); if (err < 0) goto out_module_put; /* * Now to bump the refcnt of the [loadable] module that owns this * socket at sock_release time we decrement its refcnt. */ if (!try_module_get(sock->ops->owner)) goto out_module_busy; /* * Now that we're done with the ->create function, the [loadable] * module can have its refcnt decremented */ module_put(pf->owner); err = security_socket_post_create(sock, family, type, protocol, kern); if (err) goto out_sock_release; *res = sock; return 0; out_module_busy: err = -EAFNOSUPPORT; out_module_put: sock->ops = NULL; module_put(pf->owner); out_sock_release: sock_release(sock); return err; out_release: rcu_read_unlock(); goto out_sock_release; } EXPORT_SYMBOL(__sock_create); int sock_create(int family, int type, int protocol, struct socket **res) { return __sock_create(current->nsproxy->net_ns, family, type, protocol, res, 0); } EXPORT_SYMBOL(sock_create); int sock_create_kern(int family, int type, int protocol, struct socket **res) { return __sock_create(&init_net, family, type, protocol, res, 1); } EXPORT_SYMBOL(sock_create_kern); SYSCALL_DEFINE3(socket, int, family, int, type, int, protocol) { int retval; struct socket *sock; int flags; /* Check the SOCK_* constants for consistency. */ BUILD_BUG_ON(SOCK_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON((SOCK_MAX | SOCK_TYPE_MASK) != SOCK_TYPE_MASK); BUILD_BUG_ON(SOCK_CLOEXEC & SOCK_TYPE_MASK); BUILD_BUG_ON(SOCK_NONBLOCK & SOCK_TYPE_MASK); flags = type & ~SOCK_TYPE_MASK; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; type &= SOCK_TYPE_MASK; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; retval = sock_create(family, type, protocol, &sock); if (retval < 0) goto out; retval = sock_map_fd(sock, flags & (O_CLOEXEC | O_NONBLOCK)); if (retval < 0) goto out_release; out: /* It may be already another descriptor 8) Not kernel problem. */ return retval; out_release: sock_release(sock); return retval; } /* * Create a pair of connected sockets. */ SYSCALL_DEFINE4(socketpair, int, family, int, type, int, protocol, int __user *, usockvec) { struct socket *sock1, *sock2; int fd1, fd2, err; struct file *newfile1, *newfile2; int flags; flags = type & ~SOCK_TYPE_MASK; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; type &= SOCK_TYPE_MASK; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; /* * Obtain the first socket and check if the underlying protocol * supports the socketpair call. */ err = sock_create(family, type, protocol, &sock1); if (err < 0) goto out; err = sock_create(family, type, protocol, &sock2); if (err < 0) goto out_release_1; err = sock1->ops->socketpair(sock1, sock2); if (err < 0) goto out_release_both; fd1 = sock_alloc_file(sock1, &newfile1, flags); if (unlikely(fd1 < 0)) { err = fd1; goto out_release_both; } fd2 = sock_alloc_file(sock2, &newfile2, flags); if (unlikely(fd2 < 0)) { err = fd2; fput(newfile1); put_unused_fd(fd1); sock_release(sock2); goto out; } audit_fd_pair(fd1, fd2); fd_install(fd1, newfile1); fd_install(fd2, newfile2); /* fd1 and fd2 may be already another descriptors. * Not kernel problem. */ err = put_user(fd1, &usockvec[0]); if (!err) err = put_user(fd2, &usockvec[1]); if (!err) return 0; sys_close(fd2); sys_close(fd1); return err; out_release_both: sock_release(sock2); out_release_1: sock_release(sock1); out: return err; } /* * Bind a name to a socket. Nothing much to do here since it's * the protocol's responsibility to handle the local address. * * We move the socket address to kernel space before we call * the protocol layer (having also checked the address is ok). */ SYSCALL_DEFINE3(bind, int, fd, struct sockaddr __user *, umyaddr, int, addrlen) { struct socket *sock; struct sockaddr_storage address; int err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock) { err = move_addr_to_kernel(umyaddr, addrlen, (struct sockaddr *)&address); if (err >= 0) { err = security_socket_bind(sock, (struct sockaddr *)&address, addrlen); if (!err) err = sock->ops->bind(sock, (struct sockaddr *) &address, addrlen); } fput_light(sock->file, fput_needed); } return err; } /* * Perform a listen. Basically, we allow the protocol to do anything * necessary for a listen, and if that works, we mark the socket as * ready for listening. */ SYSCALL_DEFINE2(listen, int, fd, int, backlog) { struct socket *sock; int err, fput_needed; int somaxconn; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock) { somaxconn = sock_net(sock->sk)->core.sysctl_somaxconn; if ((unsigned)backlog > somaxconn) backlog = somaxconn; err = security_socket_listen(sock, backlog); if (!err) err = sock->ops->listen(sock, backlog); fput_light(sock->file, fput_needed); } return err; } /* * For accept, we attempt to create a new socket, set up the link * with the client, wake up the client, then return the new * connected fd. We collect the address of the connector in kernel * space and move it to user at the very end. This is unclean because * we open the socket then return an error. * * 1003.1g adds the ability to recvmsg() to query connection pending * status to recvmsg. We need to add that support in a way thats * clean when we restucture accept also. */ SYSCALL_DEFINE4(accept4, int, fd, struct sockaddr __user *, upeer_sockaddr, int __user *, upeer_addrlen, int, flags) { struct socket *sock, *newsock; struct file *newfile; int err, len, newfd, fput_needed; struct sockaddr_storage address; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = -ENFILE; newsock = sock_alloc(); if (!newsock) goto out_put; newsock->type = sock->type; newsock->ops = sock->ops; /* * We don't need try_module_get here, as the listening socket (sock) * has the protocol module (sock->ops->owner) held. */ __module_get(newsock->ops->owner); newfd = sock_alloc_file(newsock, &newfile, flags); if (unlikely(newfd < 0)) { err = newfd; sock_release(newsock); goto out_put; } err = security_socket_accept(sock, newsock); if (err) goto out_fd; err = sock->ops->accept(sock, newsock, sock->file->f_flags); if (err < 0) goto out_fd; if (upeer_sockaddr) { if (newsock->ops->getname(newsock, (struct sockaddr *)&address, &len, 2) < 0) { err = -ECONNABORTED; goto out_fd; } err = move_addr_to_user((struct sockaddr *)&address, len, upeer_sockaddr, upeer_addrlen); if (err < 0) goto out_fd; } /* File flags are not inherited via accept() unlike another OSes. */ fd_install(newfd, newfile); err = newfd; out_put: fput_light(sock->file, fput_needed); out: return err; out_fd: fput(newfile); put_unused_fd(newfd); goto out_put; } SYSCALL_DEFINE3(accept, int, fd, struct sockaddr __user *, upeer_sockaddr, int __user *, upeer_addrlen) { return sys_accept4(fd, upeer_sockaddr, upeer_addrlen, 0); } /* * Attempt to connect to a socket with the server address. The address * is in user space so we verify it is OK and move it to kernel space. * * For 1003.1g we need to add clean support for a bind to AF_UNSPEC to * break bindings * * NOTE: 1003.1g draft 6.3 is broken with respect to AX.25/NetROM and * other SEQPACKET protocols that take time to connect() as it doesn't * include the -EINPROGRESS status for such sockets. */ SYSCALL_DEFINE3(connect, int, fd, struct sockaddr __user *, uservaddr, int, addrlen) { struct socket *sock; struct sockaddr_storage address; int err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = move_addr_to_kernel(uservaddr, addrlen, (struct sockaddr *)&address); if (err < 0) goto out_put; err = security_socket_connect(sock, (struct sockaddr *)&address, addrlen); if (err) goto out_put; err = sock->ops->connect(sock, (struct sockaddr *)&address, addrlen, sock->file->f_flags); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Get the local address ('name') of a socket object. Move the obtained * name to user space. */ SYSCALL_DEFINE3(getsockname, int, fd, struct sockaddr __user *, usockaddr, int __user *, usockaddr_len) { struct socket *sock; struct sockaddr_storage address; int len, err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = security_socket_getsockname(sock); if (err) goto out_put; err = sock->ops->getname(sock, (struct sockaddr *)&address, &len, 0); if (err) goto out_put; err = move_addr_to_user((struct sockaddr *)&address, len, usockaddr, usockaddr_len); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Get the remote address ('name') of a socket object. Move the obtained * name to user space. */ SYSCALL_DEFINE3(getpeername, int, fd, struct sockaddr __user *, usockaddr, int __user *, usockaddr_len) { struct socket *sock; struct sockaddr_storage address; int len, err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_getpeername(sock); if (err) { fput_light(sock->file, fput_needed); return err; } err = sock->ops->getname(sock, (struct sockaddr *)&address, &len, 1); if (!err) err = move_addr_to_user((struct sockaddr *)&address, len, usockaddr, usockaddr_len); fput_light(sock->file, fput_needed); } return err; } /* * Send a datagram to a given address. We move the address into kernel * space and check the user space data area is readable before invoking * the protocol. */ SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len, unsigned, flags, struct sockaddr __user *, addr, int, addr_len) { struct socket *sock; struct sockaddr_storage address; int err; struct msghdr msg; struct iovec iov; int fput_needed; if (len > INT_MAX) len = INT_MAX; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; iov.iov_base = buff; iov.iov_len = len; msg.msg_name = NULL; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_namelen = 0; if (addr) { err = move_addr_to_kernel(addr, addr_len, (struct sockaddr *)&address); if (err < 0) goto out_put; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = addr_len; } if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; msg.msg_flags = flags; err = sock_sendmsg(sock, &msg, len); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Send a datagram down a socket. */ SYSCALL_DEFINE4(send, int, fd, void __user *, buff, size_t, len, unsigned, flags) { return sys_sendto(fd, buff, len, flags, NULL, 0); } /* * Receive a frame from the socket and optionally record the address of the * sender. We verify the buffers are writable and if needed move the * sender address from kernel to user space. */ SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size, unsigned, flags, struct sockaddr __user *, addr, int __user *, addr_len) { struct socket *sock; struct iovec iov; struct msghdr msg; struct sockaddr_storage address; int err, err2; int fput_needed; if (size > INT_MAX) size = INT_MAX; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_iovlen = 1; msg.msg_iov = &iov; iov.iov_len = size; iov.iov_base = ubuf; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = sizeof(address); if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = sock_recvmsg(sock, &msg, size, flags); if (err >= 0 && addr != NULL) { err2 = move_addr_to_user((struct sockaddr *)&address, msg.msg_namelen, addr, addr_len); if (err2 < 0) err = err2; } fput_light(sock->file, fput_needed); out: return err; } /* * Receive a datagram from a socket. */ asmlinkage long sys_recv(int fd, void __user *ubuf, size_t size, unsigned flags) { return sys_recvfrom(fd, ubuf, size, flags, NULL, NULL); } /* * Set a socket option. Because we don't know the option lengths we have * to pass the user mode parameter for the protocols to sort out. */ SYSCALL_DEFINE5(setsockopt, int, fd, int, level, int, optname, char __user *, optval, int, optlen) { int err, fput_needed; struct socket *sock; if (optlen < 0) return -EINVAL; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_setsockopt(sock, level, optname); if (err) goto out_put; if (level == SOL_SOCKET) err = sock_setsockopt(sock, level, optname, optval, optlen); else err = sock->ops->setsockopt(sock, level, optname, optval, optlen); out_put: fput_light(sock->file, fput_needed); } return err; } /* * Get a socket option. Because we don't know the option lengths we have * to pass a user mode parameter for the protocols to sort out. */ SYSCALL_DEFINE5(getsockopt, int, fd, int, level, int, optname, char __user *, optval, int __user *, optlen) { int err, fput_needed; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_getsockopt(sock, level, optname); if (err) goto out_put; if (level == SOL_SOCKET) err = sock_getsockopt(sock, level, optname, optval, optlen); else err = sock->ops->getsockopt(sock, level, optname, optval, optlen); out_put: fput_light(sock->file, fput_needed); } return err; } /* * Shutdown a socket. */ SYSCALL_DEFINE2(shutdown, int, fd, int, how) { int err, fput_needed; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_shutdown(sock, how); if (!err) err = sock->ops->shutdown(sock, how); fput_light(sock->file, fput_needed); } return err; } /* A couple of helpful macros for getting the address of the 32/64 bit * fields which are the same type (int / unsigned) on our platforms. */ #define COMPAT_MSG(msg, member) ((MSG_CMSG_COMPAT & flags) ? &msg##_compat->member : &msg->member) #define COMPAT_NAMELEN(msg) COMPAT_MSG(msg, msg_namelen) #define COMPAT_FLAGS(msg) COMPAT_MSG(msg, msg_flags) struct used_address { struct sockaddr_storage name; unsigned int name_len; }; static int __sys_sendmsg(struct socket *sock, struct msghdr __user *msg, struct msghdr *msg_sys, unsigned flags, struct used_address *used_address) { struct compat_msghdr __user *msg_compat = (struct compat_msghdr __user *)msg; struct sockaddr_storage address; struct iovec iovstack[UIO_FASTIOV], *iov = iovstack; unsigned char ctl[sizeof(struct cmsghdr) + 20] __attribute__ ((aligned(sizeof(__kernel_size_t)))); /* 20 is size of ipv6_pktinfo */ unsigned char *ctl_buf = ctl; int err, ctl_len, iov_size, total_len; err = -EFAULT; if (MSG_CMSG_COMPAT & flags) { if (get_compat_msghdr(msg_sys, msg_compat)) return -EFAULT; } else if (copy_from_user(msg_sys, msg, sizeof(struct msghdr))) return -EFAULT; /* do not move before msg_sys is valid */ err = -EMSGSIZE; if (msg_sys->msg_iovlen > UIO_MAXIOV) goto out; /* Check whether to allocate the iovec area */ err = -ENOMEM; iov_size = msg_sys->msg_iovlen * sizeof(struct iovec); if (msg_sys->msg_iovlen > UIO_FASTIOV) { iov = sock_kmalloc(sock->sk, iov_size, GFP_KERNEL); if (!iov) goto out; } /* This will also move the address data into kernel space */ if (MSG_CMSG_COMPAT & flags) { err = verify_compat_iovec(msg_sys, iov, (struct sockaddr *)&address, VERIFY_READ); } else err = verify_iovec(msg_sys, iov, (struct sockaddr *)&address, VERIFY_READ); if (err < 0) goto out_freeiov; total_len = err; err = -ENOBUFS; if (msg_sys->msg_controllen > INT_MAX) goto out_freeiov; ctl_len = msg_sys->msg_controllen; if ((MSG_CMSG_COMPAT & flags) && ctl_len) { err = cmsghdr_from_user_compat_to_kern(msg_sys, sock->sk, ctl, sizeof(ctl)); if (err) goto out_freeiov; ctl_buf = msg_sys->msg_control; ctl_len = msg_sys->msg_controllen; } else if (ctl_len) { if (ctl_len > sizeof(ctl)) { ctl_buf = sock_kmalloc(sock->sk, ctl_len, GFP_KERNEL); if (ctl_buf == NULL) goto out_freeiov; } err = -EFAULT; /* * Careful! Before this, msg_sys->msg_control contains a user pointer. * Afterwards, it will be a kernel pointer. Thus the compiler-assisted * checking falls down on this. */ if (copy_from_user(ctl_buf, (void __user __force *)msg_sys->msg_control, ctl_len)) goto out_freectl; msg_sys->msg_control = ctl_buf; } msg_sys->msg_flags = flags; if (sock->file->f_flags & O_NONBLOCK) msg_sys->msg_flags |= MSG_DONTWAIT; /* * If this is sendmmsg() and current destination address is same as * previously succeeded address, omit asking LSM's decision. * used_address->name_len is initialized to UINT_MAX so that the first * destination address never matches. */ if (used_address && msg_sys->msg_name && used_address->name_len == msg_sys->msg_namelen && !memcmp(&used_address->name, msg_sys->msg_name, used_address->name_len)) { err = sock_sendmsg_nosec(sock, msg_sys, total_len); goto out_freectl; } err = sock_sendmsg(sock, msg_sys, total_len); /* * If this is sendmmsg() and sending to current destination address was * successful, remember it. */ if (used_address && err >= 0) { used_address->name_len = msg_sys->msg_namelen; if (msg_sys->msg_name) memcpy(&used_address->name, msg_sys->msg_name, used_address->name_len); } out_freectl: if (ctl_buf != ctl) sock_kfree_s(sock->sk, ctl_buf, ctl_len); out_freeiov: if (iov != iovstack) sock_kfree_s(sock->sk, iov, iov_size); out: return err; } /* * BSD sendmsg interface */ SYSCALL_DEFINE3(sendmsg, int, fd, struct msghdr __user *, msg, unsigned, flags) { int fput_needed, err; struct msghdr msg_sys; struct socket *sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = __sys_sendmsg(sock, msg, &msg_sys, flags, NULL); fput_light(sock->file, fput_needed); out: return err; } /* * Linux sendmmsg interface */ int __sys_sendmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags) { int fput_needed, err, datagrams; struct socket *sock; struct mmsghdr __user *entry; struct compat_mmsghdr __user *compat_entry; struct msghdr msg_sys; struct used_address used_address; if (vlen > UIO_MAXIOV) vlen = UIO_MAXIOV; datagrams = 0; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) return err; used_address.name_len = UINT_MAX; entry = mmsg; compat_entry = (struct compat_mmsghdr __user *)mmsg; err = 0; while (datagrams < vlen) { if (MSG_CMSG_COMPAT & flags) { err = __sys_sendmsg(sock, (struct msghdr __user *)compat_entry, &msg_sys, flags, &used_address); if (err < 0) break; err = __put_user(err, &compat_entry->msg_len); ++compat_entry; } else { err = __sys_sendmsg(sock, (struct msghdr __user *)entry, &msg_sys, flags, &used_address); if (err < 0) break; err = put_user(err, &entry->msg_len); ++entry; } if (err) break; ++datagrams; } fput_light(sock->file, fput_needed); /* We only return an error if no datagrams were able to be sent */ if (datagrams != 0) return datagrams; return err; } SYSCALL_DEFINE4(sendmmsg, int, fd, struct mmsghdr __user *, mmsg, unsigned int, vlen, unsigned int, flags) { return __sys_sendmmsg(fd, mmsg, vlen, flags); } static int __sys_recvmsg(struct socket *sock, struct msghdr __user *msg, struct msghdr *msg_sys, unsigned flags, int nosec) { struct compat_msghdr __user *msg_compat = (struct compat_msghdr __user *)msg; struct iovec iovstack[UIO_FASTIOV]; struct iovec *iov = iovstack; unsigned long cmsg_ptr; int err, iov_size, total_len, len; /* kernel mode address */ struct sockaddr_storage addr; /* user mode address pointers */ struct sockaddr __user *uaddr; int __user *uaddr_len; if (MSG_CMSG_COMPAT & flags) { if (get_compat_msghdr(msg_sys, msg_compat)) return -EFAULT; } else if (copy_from_user(msg_sys, msg, sizeof(struct msghdr))) return -EFAULT; err = -EMSGSIZE; if (msg_sys->msg_iovlen > UIO_MAXIOV) goto out; /* Check whether to allocate the iovec area */ err = -ENOMEM; iov_size = msg_sys->msg_iovlen * sizeof(struct iovec); if (msg_sys->msg_iovlen > UIO_FASTIOV) { iov = sock_kmalloc(sock->sk, iov_size, GFP_KERNEL); if (!iov) goto out; } /* * Save the user-mode address (verify_iovec will change the * kernel msghdr to use the kernel address space) */ uaddr = (__force void __user *)msg_sys->msg_name; uaddr_len = COMPAT_NAMELEN(msg); if (MSG_CMSG_COMPAT & flags) { err = verify_compat_iovec(msg_sys, iov, (struct sockaddr *)&addr, VERIFY_WRITE); } else err = verify_iovec(msg_sys, iov, (struct sockaddr *)&addr, VERIFY_WRITE); if (err < 0) goto out_freeiov; total_len = err; cmsg_ptr = (unsigned long)msg_sys->msg_control; msg_sys->msg_flags = flags & (MSG_CMSG_CLOEXEC|MSG_CMSG_COMPAT); if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = (nosec ? sock_recvmsg_nosec : sock_recvmsg)(sock, msg_sys, total_len, flags); if (err < 0) goto out_freeiov; len = err; if (uaddr != NULL) { err = move_addr_to_user((struct sockaddr *)&addr, msg_sys->msg_namelen, uaddr, uaddr_len); if (err < 0) goto out_freeiov; } err = __put_user((msg_sys->msg_flags & ~MSG_CMSG_COMPAT), COMPAT_FLAGS(msg)); if (err) goto out_freeiov; if (MSG_CMSG_COMPAT & flags) err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr, &msg_compat->msg_controllen); else err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr, &msg->msg_controllen); if (err) goto out_freeiov; err = len; out_freeiov: if (iov != iovstack) sock_kfree_s(sock->sk, iov, iov_size); out: return err; } /* * BSD recvmsg interface */ SYSCALL_DEFINE3(recvmsg, int, fd, struct msghdr __user *, msg, unsigned int, flags) { int fput_needed, err; struct msghdr msg_sys; struct socket *sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = __sys_recvmsg(sock, msg, &msg_sys, flags, 0); fput_light(sock->file, fput_needed); out: return err; } /* * Linux recvmmsg interface */ int __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags, struct timespec *timeout) { int fput_needed, err, datagrams; struct socket *sock; struct mmsghdr __user *entry; struct compat_mmsghdr __user *compat_entry; struct msghdr msg_sys; struct timespec end_time; if (timeout && poll_select_set_timeout(&end_time, timeout->tv_sec, timeout->tv_nsec)) return -EINVAL; datagrams = 0; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) return err; err = sock_error(sock->sk); if (err) goto out_put; entry = mmsg; compat_entry = (struct compat_mmsghdr __user *)mmsg; while (datagrams < vlen) { /* * No need to ask LSM for more than the first datagram. */ if (MSG_CMSG_COMPAT & flags) { err = __sys_recvmsg(sock, (struct msghdr __user *)compat_entry, &msg_sys, flags & ~MSG_WAITFORONE, datagrams); if (err < 0) break; err = __put_user(err, &compat_entry->msg_len); ++compat_entry; } else { err = __sys_recvmsg(sock, (struct msghdr __user *)entry, &msg_sys, flags & ~MSG_WAITFORONE, datagrams); if (err < 0) break; err = put_user(err, &entry->msg_len); ++entry; } if (err) break; ++datagrams; /* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */ if (flags & MSG_WAITFORONE) flags |= MSG_DONTWAIT; if (timeout) { ktime_get_ts(timeout); *timeout = timespec_sub(end_time, *timeout); if (timeout->tv_sec < 0) { timeout->tv_sec = timeout->tv_nsec = 0; break; } /* Timeout, return less than vlen datagrams */ if (timeout->tv_nsec == 0 && timeout->tv_sec == 0) break; } /* Out of band data, return right away */ if (msg_sys.msg_flags & MSG_OOB) break; } out_put: fput_light(sock->file, fput_needed); if (err == 0) return datagrams; if (datagrams != 0) { /* * We may return less entries than requested (vlen) if the * sock is non block and there aren't enough datagrams... */ if (err != -EAGAIN) { /* * ... or if recvmsg returns an error after we * received some datagrams, where we record the * error to return on the next call or if the * app asks about it using getsockopt(SO_ERROR). */ sock->sk->sk_err = -err; } return datagrams; } return err; } SYSCALL_DEFINE5(recvmmsg, int, fd, struct mmsghdr __user *, mmsg, unsigned int, vlen, unsigned int, flags, struct timespec __user *, timeout) { int datagrams; struct timespec timeout_sys; if (!timeout) return __sys_recvmmsg(fd, mmsg, vlen, flags, NULL); if (copy_from_user(&timeout_sys, timeout, sizeof(timeout_sys))) return -EFAULT; datagrams = __sys_recvmmsg(fd, mmsg, vlen, flags, &timeout_sys); if (datagrams > 0 && copy_to_user(timeout, &timeout_sys, sizeof(timeout_sys))) datagrams = -EFAULT; return datagrams; } #ifdef __ARCH_WANT_SYS_SOCKETCALL /* Argument list sizes for sys_socketcall */ #define AL(x) ((x) * sizeof(unsigned long)) static const unsigned char nargs[21] = { AL(0), AL(3), AL(3), AL(3), AL(2), AL(3), AL(3), AL(3), AL(4), AL(4), AL(4), AL(6), AL(6), AL(2), AL(5), AL(5), AL(3), AL(3), AL(4), AL(5), AL(4) }; #undef AL /* * System call vectors. * * Argument checking cleaned up. Saved 20% in size. * This function doesn't need to set the kernel lock because * it is set by the callees. */ SYSCALL_DEFINE2(socketcall, int, call, unsigned long __user *, args) { unsigned long a[6]; unsigned long a0, a1; int err; unsigned int len; if (call < 1 || call > SYS_SENDMMSG) return -EINVAL; len = nargs[call]; if (len > sizeof(a)) return -EINVAL; /* copy_from_user should be SMP safe. */ if (copy_from_user(a, args, len)) return -EFAULT; audit_socketcall(nargs[call] / sizeof(unsigned long), a); a0 = a[0]; a1 = a[1]; switch (call) { case SYS_SOCKET: err = sys_socket(a0, a1, a[2]); break; case SYS_BIND: err = sys_bind(a0, (struct sockaddr __user *)a1, a[2]); break; case SYS_CONNECT: err = sys_connect(a0, (struct sockaddr __user *)a1, a[2]); break; case SYS_LISTEN: err = sys_listen(a0, a1); break; case SYS_ACCEPT: err = sys_accept4(a0, (struct sockaddr __user *)a1, (int __user *)a[2], 0); break; case SYS_GETSOCKNAME: err = sys_getsockname(a0, (struct sockaddr __user *)a1, (int __user *)a[2]); break; case SYS_GETPEERNAME: err = sys_getpeername(a0, (struct sockaddr __user *)a1, (int __user *)a[2]); break; case SYS_SOCKETPAIR: err = sys_socketpair(a0, a1, a[2], (int __user *)a[3]); break; case SYS_SEND: err = sys_send(a0, (void __user *)a1, a[2], a[3]); break; case SYS_SENDTO: err = sys_sendto(a0, (void __user *)a1, a[2], a[3], (struct sockaddr __user *)a[4], a[5]); break; case SYS_RECV: err = sys_recv(a0, (void __user *)a1, a[2], a[3]); break; case SYS_RECVFROM: err = sys_recvfrom(a0, (void __user *)a1, a[2], a[3], (struct sockaddr __user *)a[4], (int __user *)a[5]); break; case SYS_SHUTDOWN: err = sys_shutdown(a0, a1); break; case SYS_SETSOCKOPT: err = sys_setsockopt(a0, a1, a[2], (char __user *)a[3], a[4]); break; case SYS_GETSOCKOPT: err = sys_getsockopt(a0, a1, a[2], (char __user *)a[3], (int __user *)a[4]); break; case SYS_SENDMSG: err = sys_sendmsg(a0, (struct msghdr __user *)a1, a[2]); break; case SYS_SENDMMSG: err = sys_sendmmsg(a0, (struct mmsghdr __user *)a1, a[2], a[3]); break; case SYS_RECVMSG: err = sys_recvmsg(a0, (struct msghdr __user *)a1, a[2]); break; case SYS_RECVMMSG: err = sys_recvmmsg(a0, (struct mmsghdr __user *)a1, a[2], a[3], (struct timespec __user *)a[4]); break; case SYS_ACCEPT4: err = sys_accept4(a0, (struct sockaddr __user *)a1, (int __user *)a[2], a[3]); break; default: err = -EINVAL; break; } return err; } #endif /* __ARCH_WANT_SYS_SOCKETCALL */ /** * sock_register - add a socket protocol handler * @ops: description of protocol * * This function is called by a protocol handler that wants to * advertise its address family, and have it linked into the * socket interface. The value ops->family coresponds to the * socket system call protocol family. */ int sock_register(const struct net_proto_family *ops) { int err; if (ops->family >= NPROTO) { printk(KERN_CRIT "protocol %d >= NPROTO(%d)\n", ops->family, NPROTO); return -ENOBUFS; } spin_lock(&net_family_lock); if (rcu_dereference_protected(net_families[ops->family], lockdep_is_held(&net_family_lock))) err = -EEXIST; else { rcu_assign_pointer(net_families[ops->family], ops); err = 0; } spin_unlock(&net_family_lock); printk(KERN_INFO "NET: Registered protocol family %d\n", ops->family); return err; } EXPORT_SYMBOL(sock_register); /** * sock_unregister - remove a protocol handler * @family: protocol family to remove * * This function is called by a protocol handler that wants to * remove its address family, and have it unlinked from the * new socket creation. * * If protocol handler is a module, then it can use module reference * counts to protect against new references. If protocol handler is not * a module then it needs to provide its own protection in * the ops->create routine. */ void sock_unregister(int family) { BUG_ON(family < 0 || family >= NPROTO); spin_lock(&net_family_lock); rcu_assign_pointer(net_families[family], NULL); spin_unlock(&net_family_lock); synchronize_rcu(); printk(KERN_INFO "NET: Unregistered protocol family %d\n", family); } EXPORT_SYMBOL(sock_unregister); static int __init sock_init(void) { int err; /* * Initialize sock SLAB cache. */ sk_init(); /* * Initialize skbuff SLAB cache */ skb_init(); /* * Initialize the protocols module. */ init_inodecache(); err = register_filesystem(&sock_fs_type); if (err) goto out_fs; sock_mnt = kern_mount(&sock_fs_type); if (IS_ERR(sock_mnt)) { err = PTR_ERR(sock_mnt); goto out_mount; } /* The real protocol initialization is performed in later initcalls. */ #ifdef CONFIG_NETFILTER netfilter_init(); #endif #ifdef CONFIG_NETWORK_PHY_TIMESTAMPING skb_timestamping_init(); #endif out: return err; out_mount: unregister_filesystem(&sock_fs_type); out_fs: goto out; } core_initcall(sock_init); /* early initcall */ #ifdef CONFIG_PROC_FS void socket_seq_show(struct seq_file *seq) { int cpu; int counter = 0; for_each_possible_cpu(cpu) counter += per_cpu(sockets_in_use, cpu); /* It can be negative, by the way. 8) */ if (counter < 0) counter = 0; seq_printf(seq, "sockets: used %d\n", counter); } #endif /* CONFIG_PROC_FS */ #ifdef CONFIG_COMPAT static int do_siocgstamp(struct net *net, struct socket *sock, unsigned int cmd, struct compat_timeval __user *up) { mm_segment_t old_fs = get_fs(); struct timeval ktv; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&ktv); set_fs(old_fs); if (!err) { err = put_user(ktv.tv_sec, &up->tv_sec); err |= __put_user(ktv.tv_usec, &up->tv_usec); } return err; } static int do_siocgstampns(struct net *net, struct socket *sock, unsigned int cmd, struct compat_timespec __user *up) { mm_segment_t old_fs = get_fs(); struct timespec kts; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&kts); set_fs(old_fs); if (!err) { err = put_user(kts.tv_sec, &up->tv_sec); err |= __put_user(kts.tv_nsec, &up->tv_nsec); } return err; } static int dev_ifname32(struct net *net, struct compat_ifreq __user *uifr32) { struct ifreq __user *uifr; int err; uifr = compat_alloc_user_space(sizeof(struct ifreq)); if (copy_in_user(uifr, uifr32, sizeof(struct compat_ifreq))) return -EFAULT; err = dev_ioctl(net, SIOCGIFNAME, uifr); if (err) return err; if (copy_in_user(uifr32, uifr, sizeof(struct compat_ifreq))) return -EFAULT; return 0; } static int dev_ifconf(struct net *net, struct compat_ifconf __user *uifc32) { struct compat_ifconf ifc32; struct ifconf ifc; struct ifconf __user *uifc; struct compat_ifreq __user *ifr32; struct ifreq __user *ifr; unsigned int i, j; int err; if (copy_from_user(&ifc32, uifc32, sizeof(struct compat_ifconf))) return -EFAULT; if (ifc32.ifcbuf == 0) { ifc32.ifc_len = 0; ifc.ifc_len = 0; ifc.ifc_req = NULL; uifc = compat_alloc_user_space(sizeof(struct ifconf)); } else { size_t len = ((ifc32.ifc_len / sizeof(struct compat_ifreq)) + 1) * sizeof(struct ifreq); uifc = compat_alloc_user_space(sizeof(struct ifconf) + len); ifc.ifc_len = len; ifr = ifc.ifc_req = (void __user *)(uifc + 1); ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0; i < ifc32.ifc_len; i += sizeof(struct compat_ifreq)) { if (copy_in_user(ifr, ifr32, sizeof(struct compat_ifreq))) return -EFAULT; ifr++; ifr32++; } } if (copy_to_user(uifc, &ifc, sizeof(struct ifconf))) return -EFAULT; err = dev_ioctl(net, SIOCGIFCONF, uifc); if (err) return err; if (copy_from_user(&ifc, uifc, sizeof(struct ifconf))) return -EFAULT; ifr = ifc.ifc_req; ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0, j = 0; i + sizeof(struct compat_ifreq) <= ifc32.ifc_len && j < ifc.ifc_len; i += sizeof(struct compat_ifreq), j += sizeof(struct ifreq)) { if (copy_in_user(ifr32, ifr, sizeof(struct compat_ifreq))) return -EFAULT; ifr32++; ifr++; } if (ifc32.ifcbuf == 0) { /* Translate from 64-bit structure multiple to * a 32-bit one. */ i = ifc.ifc_len; i = ((i / sizeof(struct ifreq)) * sizeof(struct compat_ifreq)); ifc32.ifc_len = i; } else { ifc32.ifc_len = i; } if (copy_to_user(uifc32, &ifc32, sizeof(struct compat_ifconf))) return -EFAULT; return 0; } static int ethtool_ioctl(struct net *net, struct compat_ifreq __user *ifr32) { struct compat_ethtool_rxnfc __user *compat_rxnfc; bool convert_in = false, convert_out = false; size_t buf_size = ALIGN(sizeof(struct ifreq), 8); struct ethtool_rxnfc __user *rxnfc; struct ifreq __user *ifr; u32 rule_cnt = 0, actual_rule_cnt; u32 ethcmd; u32 data; int ret; if (get_user(data, &ifr32->ifr_ifru.ifru_data)) return -EFAULT; compat_rxnfc = compat_ptr(data); if (get_user(ethcmd, &compat_rxnfc->cmd)) return -EFAULT; /* Most ethtool structures are defined without padding. * Unfortunately struct ethtool_rxnfc is an exception. */ switch (ethcmd) { default: break; case ETHTOOL_GRXCLSRLALL: /* Buffer size is variable */ if (get_user(rule_cnt, &compat_rxnfc->rule_cnt)) return -EFAULT; if (rule_cnt > KMALLOC_MAX_SIZE / sizeof(u32)) return -ENOMEM; buf_size += rule_cnt * sizeof(u32); /* fall through */ case ETHTOOL_GRXRINGS: case ETHTOOL_GRXCLSRLCNT: case ETHTOOL_GRXCLSRULE: convert_out = true; /* fall through */ case ETHTOOL_SRXCLSRLDEL: case ETHTOOL_SRXCLSRLINS: buf_size += sizeof(struct ethtool_rxnfc); convert_in = true; break; } ifr = compat_alloc_user_space(buf_size); rxnfc = (void *)ifr + ALIGN(sizeof(struct ifreq), 8); if (copy_in_user(&ifr->ifr_name, &ifr32->ifr_name, IFNAMSIZ)) return -EFAULT; if (put_user(convert_in ? rxnfc : compat_ptr(data), &ifr->ifr_ifru.ifru_data)) return -EFAULT; if (convert_in) { /* We expect there to be holes between fs.m_ext and * fs.ring_cookie and at the end of fs, but nowhere else. */ BUILD_BUG_ON(offsetof(struct compat_ethtool_rxnfc, fs.m_ext) + sizeof(compat_rxnfc->fs.m_ext) != offsetof(struct ethtool_rxnfc, fs.m_ext) + sizeof(rxnfc->fs.m_ext)); BUILD_BUG_ON( offsetof(struct compat_ethtool_rxnfc, fs.location) - offsetof(struct compat_ethtool_rxnfc, fs.ring_cookie) != offsetof(struct ethtool_rxnfc, fs.location) - offsetof(struct ethtool_rxnfc, fs.ring_cookie)); if (copy_in_user(rxnfc, compat_rxnfc, (void *)(&rxnfc->fs.m_ext + 1) - (void *)rxnfc) || copy_in_user(&rxnfc->fs.ring_cookie, &compat_rxnfc->fs.ring_cookie, (void *)(&rxnfc->fs.location + 1) - (void *)&rxnfc->fs.ring_cookie) || copy_in_user(&rxnfc->rule_cnt, &compat_rxnfc->rule_cnt, sizeof(rxnfc->rule_cnt))) return -EFAULT; } ret = dev_ioctl(net, SIOCETHTOOL, ifr); if (ret) return ret; if (convert_out) { if (copy_in_user(compat_rxnfc, rxnfc, (const void *)(&rxnfc->fs.m_ext + 1) - (const void *)rxnfc) || copy_in_user(&compat_rxnfc->fs.ring_cookie, &rxnfc->fs.ring_cookie, (const void *)(&rxnfc->fs.location + 1) - (const void *)&rxnfc->fs.ring_cookie) || copy_in_user(&compat_rxnfc->rule_cnt, &rxnfc->rule_cnt, sizeof(rxnfc->rule_cnt))) return -EFAULT; if (ethcmd == ETHTOOL_GRXCLSRLALL) { /* As an optimisation, we only copy the actual * number of rules that the underlying * function returned. Since Mallory might * change the rule count in user memory, we * check that it is less than the rule count * originally given (as the user buffer size), * which has been range-checked. */ if (get_user(actual_rule_cnt, &rxnfc->rule_cnt)) return -EFAULT; if (actual_rule_cnt < rule_cnt) rule_cnt = actual_rule_cnt; if (copy_in_user(&compat_rxnfc->rule_locs[0], &rxnfc->rule_locs[0], rule_cnt * sizeof(u32))) return -EFAULT; } } return 0; } static int compat_siocwandev(struct net *net, struct compat_ifreq __user *uifr32) { void __user *uptr; compat_uptr_t uptr32; struct ifreq __user *uifr; uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(uifr, uifr32, sizeof(struct compat_ifreq))) return -EFAULT; if (get_user(uptr32, &uifr32->ifr_settings.ifs_ifsu)) return -EFAULT; uptr = compat_ptr(uptr32); if (put_user(uptr, &uifr->ifr_settings.ifs_ifsu.raw_hdlc)) return -EFAULT; return dev_ioctl(net, SIOCWANDEV, uifr); } static int bond_ioctl(struct net *net, unsigned int cmd, struct compat_ifreq __user *ifr32) { struct ifreq kifr; struct ifreq __user *uifr; mm_segment_t old_fs; int err; u32 data; void __user *datap; switch (cmd) { case SIOCBONDENSLAVE: case SIOCBONDRELEASE: case SIOCBONDSETHWADDR: case SIOCBONDCHANGEACTIVE: if (copy_from_user(&kifr, ifr32, sizeof(struct compat_ifreq))) return -EFAULT; old_fs = get_fs(); set_fs(KERNEL_DS); err = dev_ioctl(net, cmd, (struct ifreq __user __force *) &kifr); set_fs(old_fs); return err; case SIOCBONDSLAVEINFOQUERY: case SIOCBONDINFOQUERY: uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(&uifr->ifr_name, &ifr32->ifr_name, IFNAMSIZ)) return -EFAULT; if (get_user(data, &ifr32->ifr_ifru.ifru_data)) return -EFAULT; datap = compat_ptr(data); if (put_user(datap, &uifr->ifr_ifru.ifru_data)) return -EFAULT; return dev_ioctl(net, cmd, uifr); default: return -EINVAL; } } static int siocdevprivate_ioctl(struct net *net, unsigned int cmd, struct compat_ifreq __user *u_ifreq32) { struct ifreq __user *u_ifreq64; char tmp_buf[IFNAMSIZ]; void __user *data64; u32 data32; if (copy_from_user(&tmp_buf[0], &(u_ifreq32->ifr_ifrn.ifrn_name[0]), IFNAMSIZ)) return -EFAULT; if (__get_user(data32, &u_ifreq32->ifr_ifru.ifru_data)) return -EFAULT; data64 = compat_ptr(data32); u_ifreq64 = compat_alloc_user_space(sizeof(*u_ifreq64)); /* Don't check these user accesses, just let that get trapped * in the ioctl handler instead. */ if (copy_to_user(&u_ifreq64->ifr_ifrn.ifrn_name[0], &tmp_buf[0], IFNAMSIZ)) return -EFAULT; if (__put_user(data64, &u_ifreq64->ifr_ifru.ifru_data)) return -EFAULT; return dev_ioctl(net, cmd, u_ifreq64); } static int dev_ifsioc(struct net *net, struct socket *sock, unsigned int cmd, struct compat_ifreq __user *uifr32) { struct ifreq __user *uifr; int err; uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(uifr, uifr32, sizeof(*uifr32))) return -EFAULT; err = sock_do_ioctl(net, sock, cmd, (unsigned long)uifr); if (!err) { switch (cmd) { case SIOCGIFFLAGS: case SIOCGIFMETRIC: case SIOCGIFMTU: case SIOCGIFMEM: case SIOCGIFHWADDR: case SIOCGIFINDEX: case SIOCGIFADDR: case SIOCGIFBRDADDR: case SIOCGIFDSTADDR: case SIOCGIFNETMASK: case SIOCGIFPFLAGS: case SIOCGIFTXQLEN: case SIOCGMIIPHY: case SIOCGMIIREG: if (copy_in_user(uifr32, uifr, sizeof(*uifr32))) err = -EFAULT; break; } } return err; } static int compat_sioc_ifmap(struct net *net, unsigned int cmd, struct compat_ifreq __user *uifr32) { struct ifreq ifr; struct compat_ifmap __user *uifmap32; mm_segment_t old_fs; int err; uifmap32 = &uifr32->ifr_ifru.ifru_map; err = copy_from_user(&ifr, uifr32, sizeof(ifr.ifr_name)); err |= __get_user(ifr.ifr_map.mem_start, &uifmap32->mem_start); err |= __get_user(ifr.ifr_map.mem_end, &uifmap32->mem_end); err |= __get_user(ifr.ifr_map.base_addr, &uifmap32->base_addr); err |= __get_user(ifr.ifr_map.irq, &uifmap32->irq); err |= __get_user(ifr.ifr_map.dma, &uifmap32->dma); err |= __get_user(ifr.ifr_map.port, &uifmap32->port); if (err) return -EFAULT; old_fs = get_fs(); set_fs(KERNEL_DS); err = dev_ioctl(net, cmd, (void __user __force *)&ifr); set_fs(old_fs); if (cmd == SIOCGIFMAP && !err) { err = copy_to_user(uifr32, &ifr, sizeof(ifr.ifr_name)); err |= __put_user(ifr.ifr_map.mem_start, &uifmap32->mem_start); err |= __put_user(ifr.ifr_map.mem_end, &uifmap32->mem_end); err |= __put_user(ifr.ifr_map.base_addr, &uifmap32->base_addr); err |= __put_user(ifr.ifr_map.irq, &uifmap32->irq); err |= __put_user(ifr.ifr_map.dma, &uifmap32->dma); err |= __put_user(ifr.ifr_map.port, &uifmap32->port); if (err) err = -EFAULT; } return err; } static int compat_siocshwtstamp(struct net *net, struct compat_ifreq __user *uifr32) { void __user *uptr; compat_uptr_t uptr32; struct ifreq __user *uifr; uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(uifr, uifr32, sizeof(struct compat_ifreq))) return -EFAULT; if (get_user(uptr32, &uifr32->ifr_data)) return -EFAULT; uptr = compat_ptr(uptr32); if (put_user(uptr, &uifr->ifr_data)) return -EFAULT; return dev_ioctl(net, SIOCSHWTSTAMP, uifr); } struct rtentry32 { u32 rt_pad1; struct sockaddr rt_dst; /* target address */ struct sockaddr rt_gateway; /* gateway addr (RTF_GATEWAY) */ struct sockaddr rt_genmask; /* target network mask (IP) */ unsigned short rt_flags; short rt_pad2; u32 rt_pad3; unsigned char rt_tos; unsigned char rt_class; short rt_pad4; short rt_metric; /* +1 for binary compatibility! */ /* char * */ u32 rt_dev; /* forcing the device at add */ u32 rt_mtu; /* per route MTU/Window */ u32 rt_window; /* Window clamping */ unsigned short rt_irtt; /* Initial RTT */ }; struct in6_rtmsg32 { struct in6_addr rtmsg_dst; struct in6_addr rtmsg_src; struct in6_addr rtmsg_gateway; u32 rtmsg_type; u16 rtmsg_dst_len; u16 rtmsg_src_len; u32 rtmsg_metric; u32 rtmsg_info; u32 rtmsg_flags; s32 rtmsg_ifindex; }; static int routing_ioctl(struct net *net, struct socket *sock, unsigned int cmd, void __user *argp) { int ret; void *r = NULL; struct in6_rtmsg r6; struct rtentry r4; char devname[16]; u32 rtdev; mm_segment_t old_fs = get_fs(); if (sock && sock->sk && sock->sk->sk_family == AF_INET6) { /* ipv6 */ struct in6_rtmsg32 __user *ur6 = argp; ret = copy_from_user(&r6.rtmsg_dst, &(ur6->rtmsg_dst), 3 * sizeof(struct in6_addr)); ret |= __get_user(r6.rtmsg_type, &(ur6->rtmsg_type)); ret |= __get_user(r6.rtmsg_dst_len, &(ur6->rtmsg_dst_len)); ret |= __get_user(r6.rtmsg_src_len, &(ur6->rtmsg_src_len)); ret |= __get_user(r6.rtmsg_metric, &(ur6->rtmsg_metric)); ret |= __get_user(r6.rtmsg_info, &(ur6->rtmsg_info)); ret |= __get_user(r6.rtmsg_flags, &(ur6->rtmsg_flags)); ret |= __get_user(r6.rtmsg_ifindex, &(ur6->rtmsg_ifindex)); r = (void *) &r6; } else { /* ipv4 */ struct rtentry32 __user *ur4 = argp; ret = copy_from_user(&r4.rt_dst, &(ur4->rt_dst), 3 * sizeof(struct sockaddr)); ret |= __get_user(r4.rt_flags, &(ur4->rt_flags)); ret |= __get_user(r4.rt_metric, &(ur4->rt_metric)); ret |= __get_user(r4.rt_mtu, &(ur4->rt_mtu)); ret |= __get_user(r4.rt_window, &(ur4->rt_window)); ret |= __get_user(r4.rt_irtt, &(ur4->rt_irtt)); ret |= __get_user(rtdev, &(ur4->rt_dev)); if (rtdev) { ret |= copy_from_user(devname, compat_ptr(rtdev), 15); r4.rt_dev = (char __user __force *)devname; devname[15] = 0; } else r4.rt_dev = NULL; r = (void *) &r4; } if (ret) { ret = -EFAULT; goto out; } set_fs(KERNEL_DS); ret = sock_do_ioctl(net, sock, cmd, (unsigned long) r); set_fs(old_fs); out: return ret; } /* Since old style bridge ioctl's endup using SIOCDEVPRIVATE * for some operations; this forces use of the newer bridge-utils that * use compatible ioctls */ static int old_bridge_ioctl(compat_ulong_t __user *argp) { compat_ulong_t tmp; if (get_user(tmp, argp)) return -EFAULT; if (tmp == BRCTL_GET_VERSION) return BRCTL_VERSION + 1; return -EINVAL; } static int compat_sock_ioctl_trans(struct file *file, struct socket *sock, unsigned int cmd, unsigned long arg) { void __user *argp = compat_ptr(arg); struct sock *sk = sock->sk; struct net *net = sock_net(sk); if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15)) return siocdevprivate_ioctl(net, cmd, argp); switch (cmd) { case SIOCSIFBR: case SIOCGIFBR: return old_bridge_ioctl(argp); case SIOCGIFNAME: return dev_ifname32(net, argp); case SIOCGIFCONF: return dev_ifconf(net, argp); case SIOCETHTOOL: return ethtool_ioctl(net, argp); case SIOCWANDEV: return compat_siocwandev(net, argp); case SIOCGIFMAP: case SIOCSIFMAP: return compat_sioc_ifmap(net, cmd, argp); case SIOCBONDENSLAVE: case SIOCBONDRELEASE: case SIOCBONDSETHWADDR: case SIOCBONDSLAVEINFOQUERY: case SIOCBONDINFOQUERY: case SIOCBONDCHANGEACTIVE: return bond_ioctl(net, cmd, argp); case SIOCADDRT: case SIOCDELRT: return routing_ioctl(net, sock, cmd, argp); case SIOCGSTAMP: return do_siocgstamp(net, sock, cmd, argp); case SIOCGSTAMPNS: return do_siocgstampns(net, sock, cmd, argp); case SIOCSHWTSTAMP: return compat_siocshwtstamp(net, argp); case FIOSETOWN: case SIOCSPGRP: case FIOGETOWN: case SIOCGPGRP: case SIOCBRADDBR: case SIOCBRDELBR: case SIOCGIFVLAN: case SIOCSIFVLAN: case SIOCADDDLCI: case SIOCDELDLCI: return sock_ioctl(file, cmd, arg); case SIOCGIFFLAGS: case SIOCSIFFLAGS: case SIOCGIFMETRIC: case SIOCSIFMETRIC: case SIOCGIFMTU: case SIOCSIFMTU: case SIOCGIFMEM: case SIOCSIFMEM: case SIOCGIFHWADDR: case SIOCSIFHWADDR: case SIOCADDMULTI: case SIOCDELMULTI: case SIOCGIFINDEX: case SIOCGIFADDR: case SIOCSIFADDR: case SIOCSIFHWBROADCAST: case SIOCDIFADDR: case SIOCGIFBRDADDR: case SIOCSIFBRDADDR: case SIOCGIFDSTADDR: case SIOCSIFDSTADDR: case SIOCGIFNETMASK: case SIOCSIFNETMASK: case SIOCSIFPFLAGS: case SIOCGIFPFLAGS: case SIOCGIFTXQLEN: case SIOCSIFTXQLEN: case SIOCBRADDIF: case SIOCBRDELIF: case SIOCSIFNAME: case SIOCGMIIPHY: case SIOCGMIIREG: case SIOCSMIIREG: return dev_ifsioc(net, sock, cmd, argp); case SIOCSARP: case SIOCGARP: case SIOCDARP: case SIOCATMARK: return sock_do_ioctl(net, sock, cmd, arg); } /* Prevent warning from compat_sys_ioctl, these always * result in -EINVAL in the native case anyway. */ switch (cmd) { case SIOCRTMSG: case SIOCGIFCOUNT: case SIOCSRARP: case SIOCGRARP: case SIOCDRARP: case SIOCSIFLINK: case SIOCGIFSLAVE: case SIOCSIFSLAVE: return -EINVAL; } return -ENOIOCTLCMD; } static long compat_sock_ioctl(struct file *file, unsigned cmd, unsigned long arg) { struct socket *sock = file->private_data; int ret = -ENOIOCTLCMD; struct sock *sk; struct net *net; sk = sock->sk; net = sock_net(sk); if (sock->ops->compat_ioctl) ret = sock->ops->compat_ioctl(sock, cmd, arg); if (ret == -ENOIOCTLCMD && (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST)) ret = compat_wext_handle_ioctl(net, cmd, arg); if (ret == -ENOIOCTLCMD) ret = compat_sock_ioctl_trans(file, sock, cmd, arg); return ret; } #endif int kernel_bind(struct socket *sock, struct sockaddr *addr, int addrlen) { return sock->ops->bind(sock, addr, addrlen); } EXPORT_SYMBOL(kernel_bind); int kernel_listen(struct socket *sock, int backlog) { return sock->ops->listen(sock, backlog); } EXPORT_SYMBOL(kernel_listen); int kernel_accept(struct socket *sock, struct socket **newsock, int flags) { struct sock *sk = sock->sk; int err; err = sock_create_lite(sk->sk_family, sk->sk_type, sk->sk_protocol, newsock); if (err < 0) goto done; err = sock->ops->accept(sock, *newsock, flags); if (err < 0) { sock_release(*newsock); *newsock = NULL; goto done; } (*newsock)->ops = sock->ops; __module_get((*newsock)->ops->owner); done: return err; } EXPORT_SYMBOL(kernel_accept); int kernel_connect(struct socket *sock, struct sockaddr *addr, int addrlen, int flags) { return sock->ops->connect(sock, addr, addrlen, flags); } EXPORT_SYMBOL(kernel_connect); int kernel_getsockname(struct socket *sock, struct sockaddr *addr, int *addrlen) { return sock->ops->getname(sock, addr, addrlen, 0); } EXPORT_SYMBOL(kernel_getsockname); int kernel_getpeername(struct socket *sock, struct sockaddr *addr, int *addrlen) { return sock->ops->getname(sock, addr, addrlen, 1); } EXPORT_SYMBOL(kernel_getpeername); int kernel_getsockopt(struct socket *sock, int level, int optname, char *optval, int *optlen) { mm_segment_t oldfs = get_fs(); char __user *uoptval; int __user *uoptlen; int err; uoptval = (char __user __force *) optval; uoptlen = (int __user __force *) optlen; set_fs(KERNEL_DS); if (level == SOL_SOCKET) err = sock_getsockopt(sock, level, optname, uoptval, uoptlen); else err = sock->ops->getsockopt(sock, level, optname, uoptval, uoptlen); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_getsockopt); int kernel_setsockopt(struct socket *sock, int level, int optname, char *optval, unsigned int optlen) { mm_segment_t oldfs = get_fs(); char __user *uoptval; int err; uoptval = (char __user __force *) optval; set_fs(KERNEL_DS); if (level == SOL_SOCKET) err = sock_setsockopt(sock, level, optname, uoptval, optlen); else err = sock->ops->setsockopt(sock, level, optname, uoptval, optlen); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_setsockopt); int kernel_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { sock_update_classid(sock->sk); if (sock->ops->sendpage) return sock->ops->sendpage(sock, page, offset, size, flags); return sock_no_sendpage(sock, page, offset, size, flags); } EXPORT_SYMBOL(kernel_sendpage); int kernel_sock_ioctl(struct socket *sock, int cmd, unsigned long arg) { mm_segment_t oldfs = get_fs(); int err; set_fs(KERNEL_DS); err = sock->ops->ioctl(sock, cmd, arg); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_sock_ioctl); int kernel_sock_shutdown(struct socket *sock, enum sock_shutdown_cmd how) { return sock->ops->shutdown(sock, how); } EXPORT_SYMBOL(kernel_sock_shutdown);
gpl-2.0
LunarG/steamos_kernel
kernel/time/tick-broadcast.c
728
23401
/* * linux/kernel/time/tick-broadcast.c * * This file contains functions which emulate a local clock-event * device via a broadcast event source. * * Copyright(C) 2005-2006, Thomas Gleixner <tglx@linutronix.de> * Copyright(C) 2005-2007, Red Hat, Inc., Ingo Molnar * Copyright(C) 2006-2007, Timesys Corp., Thomas Gleixner * * This code is licenced under the GPL version 2. For details see * kernel-base/COPYING. */ #include <linux/cpu.h> #include <linux/err.h> #include <linux/hrtimer.h> #include <linux/interrupt.h> #include <linux/percpu.h> #include <linux/profile.h> #include <linux/sched.h> #include <linux/smp.h> #include <linux/module.h> #include "tick-internal.h" /* * Broadcast support for broken x86 hardware, where the local apic * timer stops in C3 state. */ static struct tick_device tick_broadcast_device; static cpumask_var_t tick_broadcast_mask; static cpumask_var_t tick_broadcast_on; static cpumask_var_t tmpmask; static DEFINE_RAW_SPINLOCK(tick_broadcast_lock); static int tick_broadcast_force; #ifdef CONFIG_TICK_ONESHOT static void tick_broadcast_clear_oneshot(int cpu); #else static inline void tick_broadcast_clear_oneshot(int cpu) { } #endif /* * Debugging: see timer_list.c */ struct tick_device *tick_get_broadcast_device(void) { return &tick_broadcast_device; } struct cpumask *tick_get_broadcast_mask(void) { return tick_broadcast_mask; } /* * Start the device in periodic mode */ static void tick_broadcast_start_periodic(struct clock_event_device *bc) { if (bc) tick_setup_periodic(bc, 1); } /* * Check, if the device can be utilized as broadcast device: */ static bool tick_check_broadcast_device(struct clock_event_device *curdev, struct clock_event_device *newdev) { if ((newdev->features & CLOCK_EVT_FEAT_DUMMY) || (newdev->features & CLOCK_EVT_FEAT_C3STOP)) return false; if (tick_broadcast_device.mode == TICKDEV_MODE_ONESHOT && !(newdev->features & CLOCK_EVT_FEAT_ONESHOT)) return false; return !curdev || newdev->rating > curdev->rating; } /* * Conditionally install/replace broadcast device */ void tick_install_broadcast_device(struct clock_event_device *dev) { struct clock_event_device *cur = tick_broadcast_device.evtdev; if (!tick_check_broadcast_device(cur, dev)) return; if (!try_module_get(dev->owner)) return; clockevents_exchange_device(cur, dev); if (cur) cur->event_handler = clockevents_handle_noop; tick_broadcast_device.evtdev = dev; if (!cpumask_empty(tick_broadcast_mask)) tick_broadcast_start_periodic(dev); /* * Inform all cpus about this. We might be in a situation * where we did not switch to oneshot mode because the per cpu * devices are affected by CLOCK_EVT_FEAT_C3STOP and the lack * of a oneshot capable broadcast device. Without that * notification the systems stays stuck in periodic mode * forever. */ if (dev->features & CLOCK_EVT_FEAT_ONESHOT) tick_clock_notify(); } /* * Check, if the device is the broadcast device */ int tick_is_broadcast_device(struct clock_event_device *dev) { return (dev && tick_broadcast_device.evtdev == dev); } static void err_broadcast(const struct cpumask *mask) { pr_crit_once("Failed to broadcast timer tick. Some CPUs may be unresponsive.\n"); } static void tick_device_setup_broadcast_func(struct clock_event_device *dev) { if (!dev->broadcast) dev->broadcast = tick_broadcast; if (!dev->broadcast) { pr_warn_once("%s depends on broadcast, but no broadcast function available\n", dev->name); dev->broadcast = err_broadcast; } } /* * Check, if the device is disfunctional and a place holder, which * needs to be handled by the broadcast device. */ int tick_device_uses_broadcast(struct clock_event_device *dev, int cpu) { struct clock_event_device *bc = tick_broadcast_device.evtdev; unsigned long flags; int ret; raw_spin_lock_irqsave(&tick_broadcast_lock, flags); /* * Devices might be registered with both periodic and oneshot * mode disabled. This signals, that the device needs to be * operated from the broadcast device and is a placeholder for * the cpu local device. */ if (!tick_device_is_functional(dev)) { dev->event_handler = tick_handle_periodic; tick_device_setup_broadcast_func(dev); cpumask_set_cpu(cpu, tick_broadcast_mask); tick_broadcast_start_periodic(bc); ret = 1; } else { /* * Clear the broadcast bit for this cpu if the * device is not power state affected. */ if (!(dev->features & CLOCK_EVT_FEAT_C3STOP)) cpumask_clear_cpu(cpu, tick_broadcast_mask); else tick_device_setup_broadcast_func(dev); /* * Clear the broadcast bit if the CPU is not in * periodic broadcast on state. */ if (!cpumask_test_cpu(cpu, tick_broadcast_on)) cpumask_clear_cpu(cpu, tick_broadcast_mask); switch (tick_broadcast_device.mode) { case TICKDEV_MODE_ONESHOT: /* * If the system is in oneshot mode we can * unconditionally clear the oneshot mask bit, * because the CPU is running and therefore * not in an idle state which causes the power * state affected device to stop. Let the * caller initialize the device. */ tick_broadcast_clear_oneshot(cpu); ret = 0; break; case TICKDEV_MODE_PERIODIC: /* * If the system is in periodic mode, check * whether the broadcast device can be * switched off now. */ if (cpumask_empty(tick_broadcast_mask) && bc) clockevents_shutdown(bc); /* * If we kept the cpu in the broadcast mask, * tell the caller to leave the per cpu device * in shutdown state. The periodic interrupt * is delivered by the broadcast device. */ ret = cpumask_test_cpu(cpu, tick_broadcast_mask); break; default: /* Nothing to do */ ret = 0; break; } } raw_spin_unlock_irqrestore(&tick_broadcast_lock, flags); return ret; } #ifdef CONFIG_GENERIC_CLOCKEVENTS_BROADCAST int tick_receive_broadcast(void) { struct tick_device *td = this_cpu_ptr(&tick_cpu_device); struct clock_event_device *evt = td->evtdev; if (!evt) return -ENODEV; if (!evt->event_handler) return -EINVAL; evt->event_handler(evt); return 0; } #endif /* * Broadcast the event to the cpus, which are set in the mask (mangled). */ static void tick_do_broadcast(struct cpumask *mask) { int cpu = smp_processor_id(); struct tick_device *td; /* * Check, if the current cpu is in the mask */ if (cpumask_test_cpu(cpu, mask)) { cpumask_clear_cpu(cpu, mask); td = &per_cpu(tick_cpu_device, cpu); td->evtdev->event_handler(td->evtdev); } if (!cpumask_empty(mask)) { /* * It might be necessary to actually check whether the devices * have different broadcast functions. For now, just use the * one of the first device. This works as long as we have this * misfeature only on x86 (lapic) */ td = &per_cpu(tick_cpu_device, cpumask_first(mask)); td->evtdev->broadcast(mask); } } /* * Periodic broadcast: * - invoke the broadcast handlers */ static void tick_do_periodic_broadcast(void) { raw_spin_lock(&tick_broadcast_lock); cpumask_and(tmpmask, cpu_online_mask, tick_broadcast_mask); tick_do_broadcast(tmpmask); raw_spin_unlock(&tick_broadcast_lock); } /* * Event handler for periodic broadcast ticks */ static void tick_handle_periodic_broadcast(struct clock_event_device *dev) { ktime_t next; tick_do_periodic_broadcast(); /* * The device is in periodic mode. No reprogramming necessary: */ if (dev->mode == CLOCK_EVT_MODE_PERIODIC) return; /* * Setup the next period for devices, which do not have * periodic mode. We read dev->next_event first and add to it * when the event already expired. clockevents_program_event() * sets dev->next_event only when the event is really * programmed to the device. */ for (next = dev->next_event; ;) { next = ktime_add(next, tick_period); if (!clockevents_program_event(dev, next, false)) return; tick_do_periodic_broadcast(); } } /* * Powerstate information: The system enters/leaves a state, where * affected devices might stop */ static void tick_do_broadcast_on_off(unsigned long *reason) { struct clock_event_device *bc, *dev; struct tick_device *td; unsigned long flags; int cpu, bc_stopped; raw_spin_lock_irqsave(&tick_broadcast_lock, flags); cpu = smp_processor_id(); td = &per_cpu(tick_cpu_device, cpu); dev = td->evtdev; bc = tick_broadcast_device.evtdev; /* * Is the device not affected by the powerstate ? */ if (!dev || !(dev->features & CLOCK_EVT_FEAT_C3STOP)) goto out; if (!tick_device_is_functional(dev)) goto out; bc_stopped = cpumask_empty(tick_broadcast_mask); switch (*reason) { case CLOCK_EVT_NOTIFY_BROADCAST_ON: case CLOCK_EVT_NOTIFY_BROADCAST_FORCE: cpumask_set_cpu(cpu, tick_broadcast_on); if (!cpumask_test_and_set_cpu(cpu, tick_broadcast_mask)) { if (tick_broadcast_device.mode == TICKDEV_MODE_PERIODIC) clockevents_shutdown(dev); } if (*reason == CLOCK_EVT_NOTIFY_BROADCAST_FORCE) tick_broadcast_force = 1; break; case CLOCK_EVT_NOTIFY_BROADCAST_OFF: if (tick_broadcast_force) break; cpumask_clear_cpu(cpu, tick_broadcast_on); if (!tick_device_is_functional(dev)) break; if (cpumask_test_and_clear_cpu(cpu, tick_broadcast_mask)) { if (tick_broadcast_device.mode == TICKDEV_MODE_PERIODIC) tick_setup_periodic(dev, 0); } break; } if (cpumask_empty(tick_broadcast_mask)) { if (!bc_stopped) clockevents_shutdown(bc); } else if (bc_stopped) { if (tick_broadcast_device.mode == TICKDEV_MODE_PERIODIC) tick_broadcast_start_periodic(bc); else tick_broadcast_setup_oneshot(bc); } out: raw_spin_unlock_irqrestore(&tick_broadcast_lock, flags); } /* * Powerstate information: The system enters/leaves a state, where * affected devices might stop. */ void tick_broadcast_on_off(unsigned long reason, int *oncpu) { if (!cpumask_test_cpu(*oncpu, cpu_online_mask)) printk(KERN_ERR "tick-broadcast: ignoring broadcast for " "offline CPU #%d\n", *oncpu); else tick_do_broadcast_on_off(&reason); } /* * Set the periodic handler depending on broadcast on/off */ void tick_set_periodic_handler(struct clock_event_device *dev, int broadcast) { if (!broadcast) dev->event_handler = tick_handle_periodic; else dev->event_handler = tick_handle_periodic_broadcast; } /* * Remove a CPU from broadcasting */ void tick_shutdown_broadcast(unsigned int *cpup) { struct clock_event_device *bc; unsigned long flags; unsigned int cpu = *cpup; raw_spin_lock_irqsave(&tick_broadcast_lock, flags); bc = tick_broadcast_device.evtdev; cpumask_clear_cpu(cpu, tick_broadcast_mask); cpumask_clear_cpu(cpu, tick_broadcast_on); if (tick_broadcast_device.mode == TICKDEV_MODE_PERIODIC) { if (bc && cpumask_empty(tick_broadcast_mask)) clockevents_shutdown(bc); } raw_spin_unlock_irqrestore(&tick_broadcast_lock, flags); } void tick_suspend_broadcast(void) { struct clock_event_device *bc; unsigned long flags; raw_spin_lock_irqsave(&tick_broadcast_lock, flags); bc = tick_broadcast_device.evtdev; if (bc) clockevents_shutdown(bc); raw_spin_unlock_irqrestore(&tick_broadcast_lock, flags); } int tick_resume_broadcast(void) { struct clock_event_device *bc; unsigned long flags; int broadcast = 0; raw_spin_lock_irqsave(&tick_broadcast_lock, flags); bc = tick_broadcast_device.evtdev; if (bc) { clockevents_set_mode(bc, CLOCK_EVT_MODE_RESUME); switch (tick_broadcast_device.mode) { case TICKDEV_MODE_PERIODIC: if (!cpumask_empty(tick_broadcast_mask)) tick_broadcast_start_periodic(bc); broadcast = cpumask_test_cpu(smp_processor_id(), tick_broadcast_mask); break; case TICKDEV_MODE_ONESHOT: if (!cpumask_empty(tick_broadcast_mask)) broadcast = tick_resume_broadcast_oneshot(bc); break; } } raw_spin_unlock_irqrestore(&tick_broadcast_lock, flags); return broadcast; } #ifdef CONFIG_TICK_ONESHOT static cpumask_var_t tick_broadcast_oneshot_mask; static cpumask_var_t tick_broadcast_pending_mask; static cpumask_var_t tick_broadcast_force_mask; /* * Exposed for debugging: see timer_list.c */ struct cpumask *tick_get_broadcast_oneshot_mask(void) { return tick_broadcast_oneshot_mask; } /* * Called before going idle with interrupts disabled. Checks whether a * broadcast event from the other core is about to happen. We detected * that in tick_broadcast_oneshot_control(). The callsite can use this * to avoid a deep idle transition as we are about to get the * broadcast IPI right away. */ int tick_check_broadcast_expired(void) { return cpumask_test_cpu(smp_processor_id(), tick_broadcast_force_mask); } /* * Set broadcast interrupt affinity */ static void tick_broadcast_set_affinity(struct clock_event_device *bc, const struct cpumask *cpumask) { if (!(bc->features & CLOCK_EVT_FEAT_DYNIRQ)) return; if (cpumask_equal(bc->cpumask, cpumask)) return; bc->cpumask = cpumask; irq_set_affinity(bc->irq, bc->cpumask); } static int tick_broadcast_set_event(struct clock_event_device *bc, int cpu, ktime_t expires, int force) { int ret; if (bc->mode != CLOCK_EVT_MODE_ONESHOT) clockevents_set_mode(bc, CLOCK_EVT_MODE_ONESHOT); ret = clockevents_program_event(bc, expires, force); if (!ret) tick_broadcast_set_affinity(bc, cpumask_of(cpu)); return ret; } int tick_resume_broadcast_oneshot(struct clock_event_device *bc) { clockevents_set_mode(bc, CLOCK_EVT_MODE_ONESHOT); return 0; } /* * Called from irq_enter() when idle was interrupted to reenable the * per cpu device. */ void tick_check_oneshot_broadcast(int cpu) { if (cpumask_test_cpu(cpu, tick_broadcast_oneshot_mask)) { struct tick_device *td = &per_cpu(tick_cpu_device, cpu); /* * We might be in the middle of switching over from * periodic to oneshot. If the CPU has not yet * switched over, leave the device alone. */ if (td->mode == TICKDEV_MODE_ONESHOT) { clockevents_set_mode(td->evtdev, CLOCK_EVT_MODE_ONESHOT); } } } /* * Handle oneshot mode broadcasting */ static void tick_handle_oneshot_broadcast(struct clock_event_device *dev) { struct tick_device *td; ktime_t now, next_event; int cpu, next_cpu = 0; raw_spin_lock(&tick_broadcast_lock); again: dev->next_event.tv64 = KTIME_MAX; next_event.tv64 = KTIME_MAX; cpumask_clear(tmpmask); now = ktime_get(); /* Find all expired events */ for_each_cpu(cpu, tick_broadcast_oneshot_mask) { td = &per_cpu(tick_cpu_device, cpu); if (td->evtdev->next_event.tv64 <= now.tv64) { cpumask_set_cpu(cpu, tmpmask); /* * Mark the remote cpu in the pending mask, so * it can avoid reprogramming the cpu local * timer in tick_broadcast_oneshot_control(). */ cpumask_set_cpu(cpu, tick_broadcast_pending_mask); } else if (td->evtdev->next_event.tv64 < next_event.tv64) { next_event.tv64 = td->evtdev->next_event.tv64; next_cpu = cpu; } } /* * Remove the current cpu from the pending mask. The event is * delivered immediately in tick_do_broadcast() ! */ cpumask_clear_cpu(smp_processor_id(), tick_broadcast_pending_mask); /* Take care of enforced broadcast requests */ cpumask_or(tmpmask, tmpmask, tick_broadcast_force_mask); cpumask_clear(tick_broadcast_force_mask); /* * Sanity check. Catch the case where we try to broadcast to * offline cpus. */ if (WARN_ON_ONCE(!cpumask_subset(tmpmask, cpu_online_mask))) cpumask_and(tmpmask, tmpmask, cpu_online_mask); /* * Wakeup the cpus which have an expired event. */ tick_do_broadcast(tmpmask); /* * Two reasons for reprogram: * * - The global event did not expire any CPU local * events. This happens in dyntick mode, as the maximum PIT * delta is quite small. * * - There are pending events on sleeping CPUs which were not * in the event mask */ if (next_event.tv64 != KTIME_MAX) { /* * Rearm the broadcast device. If event expired, * repeat the above */ if (tick_broadcast_set_event(dev, next_cpu, next_event, 0)) goto again; } raw_spin_unlock(&tick_broadcast_lock); } /* * Powerstate information: The system enters/leaves a state, where * affected devices might stop */ void tick_broadcast_oneshot_control(unsigned long reason) { struct clock_event_device *bc, *dev; struct tick_device *td; unsigned long flags; ktime_t now; int cpu; /* * Periodic mode does not care about the enter/exit of power * states */ if (tick_broadcast_device.mode == TICKDEV_MODE_PERIODIC) return; /* * We are called with preemtion disabled from the depth of the * idle code, so we can't be moved away. */ cpu = smp_processor_id(); td = &per_cpu(tick_cpu_device, cpu); dev = td->evtdev; if (!(dev->features & CLOCK_EVT_FEAT_C3STOP)) return; bc = tick_broadcast_device.evtdev; raw_spin_lock_irqsave(&tick_broadcast_lock, flags); if (reason == CLOCK_EVT_NOTIFY_BROADCAST_ENTER) { if (!cpumask_test_and_set_cpu(cpu, tick_broadcast_oneshot_mask)) { WARN_ON_ONCE(cpumask_test_cpu(cpu, tick_broadcast_pending_mask)); clockevents_set_mode(dev, CLOCK_EVT_MODE_SHUTDOWN); /* * We only reprogram the broadcast timer if we * did not mark ourself in the force mask and * if the cpu local event is earlier than the * broadcast event. If the current CPU is in * the force mask, then we are going to be * woken by the IPI right away. */ if (!cpumask_test_cpu(cpu, tick_broadcast_force_mask) && dev->next_event.tv64 < bc->next_event.tv64) tick_broadcast_set_event(bc, cpu, dev->next_event, 1); } } else { if (cpumask_test_and_clear_cpu(cpu, tick_broadcast_oneshot_mask)) { clockevents_set_mode(dev, CLOCK_EVT_MODE_ONESHOT); /* * The cpu which was handling the broadcast * timer marked this cpu in the broadcast * pending mask and fired the broadcast * IPI. So we are going to handle the expired * event anyway via the broadcast IPI * handler. No need to reprogram the timer * with an already expired event. */ if (cpumask_test_and_clear_cpu(cpu, tick_broadcast_pending_mask)) goto out; /* * Bail out if there is no next event. */ if (dev->next_event.tv64 == KTIME_MAX) goto out; /* * If the pending bit is not set, then we are * either the CPU handling the broadcast * interrupt or we got woken by something else. * * We are not longer in the broadcast mask, so * if the cpu local expiry time is already * reached, we would reprogram the cpu local * timer with an already expired event. * * This can lead to a ping-pong when we return * to idle and therefor rearm the broadcast * timer before the cpu local timer was able * to fire. This happens because the forced * reprogramming makes sure that the event * will happen in the future and depending on * the min_delta setting this might be far * enough out that the ping-pong starts. * * If the cpu local next_event has expired * then we know that the broadcast timer * next_event has expired as well and * broadcast is about to be handled. So we * avoid reprogramming and enforce that the * broadcast handler, which did not run yet, * will invoke the cpu local handler. * * We cannot call the handler directly from * here, because we might be in a NOHZ phase * and we did not go through the irq_enter() * nohz fixups. */ now = ktime_get(); if (dev->next_event.tv64 <= now.tv64) { cpumask_set_cpu(cpu, tick_broadcast_force_mask); goto out; } /* * We got woken by something else. Reprogram * the cpu local timer device. */ tick_program_event(dev->next_event, 1); } } out: raw_spin_unlock_irqrestore(&tick_broadcast_lock, flags); } /* * Reset the one shot broadcast for a cpu * * Called with tick_broadcast_lock held */ static void tick_broadcast_clear_oneshot(int cpu) { cpumask_clear_cpu(cpu, tick_broadcast_oneshot_mask); cpumask_clear_cpu(cpu, tick_broadcast_pending_mask); } static void tick_broadcast_init_next_event(struct cpumask *mask, ktime_t expires) { struct tick_device *td; int cpu; for_each_cpu(cpu, mask) { td = &per_cpu(tick_cpu_device, cpu); if (td->evtdev) td->evtdev->next_event = expires; } } /** * tick_broadcast_setup_oneshot - setup the broadcast device */ void tick_broadcast_setup_oneshot(struct clock_event_device *bc) { int cpu = smp_processor_id(); /* Set it up only once ! */ if (bc->event_handler != tick_handle_oneshot_broadcast) { int was_periodic = bc->mode == CLOCK_EVT_MODE_PERIODIC; bc->event_handler = tick_handle_oneshot_broadcast; /* * We must be careful here. There might be other CPUs * waiting for periodic broadcast. We need to set the * oneshot_mask bits for those and program the * broadcast device to fire. */ cpumask_copy(tmpmask, tick_broadcast_mask); cpumask_clear_cpu(cpu, tmpmask); cpumask_or(tick_broadcast_oneshot_mask, tick_broadcast_oneshot_mask, tmpmask); if (was_periodic && !cpumask_empty(tmpmask)) { clockevents_set_mode(bc, CLOCK_EVT_MODE_ONESHOT); tick_broadcast_init_next_event(tmpmask, tick_next_period); tick_broadcast_set_event(bc, cpu, tick_next_period, 1); } else bc->next_event.tv64 = KTIME_MAX; } else { /* * The first cpu which switches to oneshot mode sets * the bit for all other cpus which are in the general * (periodic) broadcast mask. So the bit is set and * would prevent the first broadcast enter after this * to program the bc device. */ tick_broadcast_clear_oneshot(cpu); } } /* * Select oneshot operating mode for the broadcast device */ void tick_broadcast_switch_to_oneshot(void) { struct clock_event_device *bc; unsigned long flags; raw_spin_lock_irqsave(&tick_broadcast_lock, flags); tick_broadcast_device.mode = TICKDEV_MODE_ONESHOT; bc = tick_broadcast_device.evtdev; if (bc) tick_broadcast_setup_oneshot(bc); raw_spin_unlock_irqrestore(&tick_broadcast_lock, flags); } /* * Remove a dead CPU from broadcasting */ void tick_shutdown_broadcast_oneshot(unsigned int *cpup) { unsigned long flags; unsigned int cpu = *cpup; raw_spin_lock_irqsave(&tick_broadcast_lock, flags); /* * Clear the broadcast masks for the dead cpu, but do not stop * the broadcast device! */ cpumask_clear_cpu(cpu, tick_broadcast_oneshot_mask); cpumask_clear_cpu(cpu, tick_broadcast_pending_mask); cpumask_clear_cpu(cpu, tick_broadcast_force_mask); raw_spin_unlock_irqrestore(&tick_broadcast_lock, flags); } /* * Check, whether the broadcast device is in one shot mode */ int tick_broadcast_oneshot_active(void) { return tick_broadcast_device.mode == TICKDEV_MODE_ONESHOT; } /* * Check whether the broadcast device supports oneshot. */ bool tick_broadcast_oneshot_available(void) { struct clock_event_device *bc = tick_broadcast_device.evtdev; return bc ? bc->features & CLOCK_EVT_FEAT_ONESHOT : false; } #endif void __init tick_broadcast_init(void) { zalloc_cpumask_var(&tick_broadcast_mask, GFP_NOWAIT); zalloc_cpumask_var(&tick_broadcast_on, GFP_NOWAIT); zalloc_cpumask_var(&tmpmask, GFP_NOWAIT); #ifdef CONFIG_TICK_ONESHOT zalloc_cpumask_var(&tick_broadcast_oneshot_mask, GFP_NOWAIT); zalloc_cpumask_var(&tick_broadcast_pending_mask, GFP_NOWAIT); zalloc_cpumask_var(&tick_broadcast_force_mask, GFP_NOWAIT); #endif }
gpl-2.0
virtuous/kernel-7x30-gingerbread-v4
kernel/time/timecompare.c
984
4968
/* * Copyright (C) 2009 Intel Corporation. * Author: Patrick Ohly <patrick.ohly@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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/timecompare.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/math64.h> /* * fixed point arithmetic scale factor for skew * * Usually one would measure skew in ppb (parts per billion, 1e9), but * using a factor of 2 simplifies the math. */ #define TIMECOMPARE_SKEW_RESOLUTION (((s64)1)<<30) ktime_t timecompare_transform(struct timecompare *sync, u64 source_tstamp) { u64 nsec; nsec = source_tstamp + sync->offset; nsec += (s64)(source_tstamp - sync->last_update) * sync->skew / TIMECOMPARE_SKEW_RESOLUTION; return ns_to_ktime(nsec); } EXPORT_SYMBOL_GPL(timecompare_transform); int timecompare_offset(struct timecompare *sync, s64 *offset, u64 *source_tstamp) { u64 start_source = 0, end_source = 0; struct { s64 offset; s64 duration_target; } buffer[10], sample, *samples; int counter = 0, i; int used; int index; int num_samples = sync->num_samples; if (num_samples > sizeof(buffer)/sizeof(buffer[0])) { samples = kmalloc(sizeof(*samples) * num_samples, GFP_ATOMIC); if (!samples) { samples = buffer; num_samples = sizeof(buffer)/sizeof(buffer[0]); } } else { samples = buffer; } /* run until we have enough valid samples, but do not try forever */ i = 0; counter = 0; while (1) { u64 ts; ktime_t start, end; start = sync->target(); ts = timecounter_read(sync->source); end = sync->target(); if (!i) start_source = ts; /* ignore negative durations */ sample.duration_target = ktime_to_ns(ktime_sub(end, start)); if (sample.duration_target >= 0) { /* * assume symetric delay to and from source: * average target time corresponds to measured * source time */ sample.offset = (ktime_to_ns(end) + ktime_to_ns(start)) / 2 - ts; /* simple insertion sort based on duration */ index = counter - 1; while (index >= 0) { if (samples[index].duration_target < sample.duration_target) break; samples[index + 1] = samples[index]; index--; } samples[index + 1] = sample; counter++; } i++; if (counter >= num_samples || i >= 100000) { end_source = ts; break; } } *source_tstamp = (end_source + start_source) / 2; /* remove outliers by only using 75% of the samples */ used = counter * 3 / 4; if (!used) used = counter; if (used) { /* calculate average */ s64 off = 0; for (index = 0; index < used; index++) off += samples[index].offset; *offset = div_s64(off, used); } if (samples && samples != buffer) kfree(samples); return used; } EXPORT_SYMBOL_GPL(timecompare_offset); void __timecompare_update(struct timecompare *sync, u64 source_tstamp) { s64 offset; u64 average_time; if (!timecompare_offset(sync, &offset, &average_time)) return; if (!sync->last_update) { sync->last_update = average_time; sync->offset = offset; sync->skew = 0; } else { s64 delta_nsec = average_time - sync->last_update; /* avoid division by negative or small deltas */ if (delta_nsec >= 10000) { s64 delta_offset_nsec = offset - sync->offset; s64 skew; /* delta_offset_nsec * TIMECOMPARE_SKEW_RESOLUTION / delta_nsec */ u64 divisor; /* div_s64() is limited to 32 bit divisor */ skew = delta_offset_nsec * TIMECOMPARE_SKEW_RESOLUTION; divisor = delta_nsec; while (unlikely(divisor >= ((s64)1) << 32)) { /* divide both by 2; beware, right shift of negative value has undefined behavior and can only be used for the positive divisor */ skew = div_s64(skew, 2); divisor >>= 1; } skew = div_s64(skew, divisor); /* * Calculate new overall skew as 4/16 the * old value and 12/16 the new one. This is * a rather arbitrary tradeoff between * only using the latest measurement (0/16 and * 16/16) and even more weight on past measurements. */ #define TIMECOMPARE_NEW_SKEW_PER_16 12 sync->skew = div_s64((16 - TIMECOMPARE_NEW_SKEW_PER_16) * sync->skew + TIMECOMPARE_NEW_SKEW_PER_16 * skew, 16); sync->last_update = average_time; sync->offset = offset; } } } EXPORT_SYMBOL_GPL(__timecompare_update);
gpl-2.0
alquez/HTC-Wildfire-S-Kernel
drivers/media/video/pwc/pwc-misc.c
1752
4178
/* Linux driver for Philips webcam Various miscellaneous functions and tables. (C) 1999-2003 Nemosoft Unv. (C) 2004-2006 Luc Saillard (luc@saillard.org) NOTE: this version of pwc is an unofficial (modified) release of pwc & pcwx driver and thus may have bugs that are not present in the original version. Please send bug reports and support requests to <luc@saillard.org>. The decompression routines have been implemented by reverse-engineering the Nemosoft binary pwcx module. Caveat emptor. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "pwc.h" const struct pwc_coord pwc_image_sizes[PSZ_MAX] = { { 128, 96, 0 }, /* sqcif */ { 160, 120, 0 }, /* qsif */ { 176, 144, 0 }, /* qcif */ { 320, 240, 0 }, /* sif */ { 352, 288, 0 }, /* cif */ { 640, 480, 0 }, /* vga */ }; /* x,y -> PSZ_ */ int pwc_decode_size(struct pwc_device *pdev, int width, int height) { int i, find; /* Make sure we don't go beyond our max size. NB: we have different limits for RAW and normal modes. In case you don't have the decompressor loaded or use RAW mode, the maximum viewable size is smaller. */ if (pdev->vpalette == VIDEO_PALETTE_RAW) { if (width > pdev->abs_max.x || height > pdev->abs_max.y) { PWC_DEBUG_SIZE("VIDEO_PALETTE_RAW: going beyond abs_max.\n"); return -1; } } else { if (width > pdev->view_max.x || height > pdev->view_max.y) { PWC_DEBUG_SIZE("VIDEO_PALETTE_not RAW: going beyond view_max.\n"); return -1; } } /* Find the largest size supported by the camera that fits into the requested size. */ find = -1; for (i = 0; i < PSZ_MAX; i++) { if (pdev->image_mask & (1 << i)) { if (pwc_image_sizes[i].x <= width && pwc_image_sizes[i].y <= height) find = i; } } return find; } /* initialize variables depending on type and decompressor*/ void pwc_construct(struct pwc_device *pdev) { if (DEVICE_USE_CODEC1(pdev->type)) { pdev->view_min.x = 128; pdev->view_min.y = 96; pdev->view_max.x = 352; pdev->view_max.y = 288; pdev->abs_max.x = 352; pdev->abs_max.y = 288; pdev->image_mask = 1 << PSZ_SQCIF | 1 << PSZ_QCIF | 1 << PSZ_CIF; pdev->vcinterface = 2; pdev->vendpoint = 4; pdev->frame_header_size = 0; pdev->frame_trailer_size = 0; } else if (DEVICE_USE_CODEC3(pdev->type)) { pdev->view_min.x = 160; pdev->view_min.y = 120; pdev->view_max.x = 640; pdev->view_max.y = 480; pdev->image_mask = 1 << PSZ_QSIF | 1 << PSZ_SIF | 1 << PSZ_VGA; pdev->abs_max.x = 640; pdev->abs_max.y = 480; pdev->vcinterface = 3; pdev->vendpoint = 5; pdev->frame_header_size = TOUCAM_HEADER_SIZE; pdev->frame_trailer_size = TOUCAM_TRAILER_SIZE; } else /* if (DEVICE_USE_CODEC2(pdev->type)) */ { pdev->view_min.x = 128; pdev->view_min.y = 96; /* Anthill bug #38: PWC always reports max size, even without PWCX */ pdev->view_max.x = 640; pdev->view_max.y = 480; pdev->image_mask = 1 << PSZ_SQCIF | 1 << PSZ_QSIF | 1 << PSZ_QCIF | 1 << PSZ_SIF | 1 << PSZ_CIF | 1 << PSZ_VGA; pdev->abs_max.x = 640; pdev->abs_max.y = 480; pdev->vcinterface = 3; pdev->vendpoint = 4; pdev->frame_header_size = 0; pdev->frame_trailer_size = 0; } pdev->vpalette = VIDEO_PALETTE_YUV420P; /* default */ pdev->view_min.size = pdev->view_min.x * pdev->view_min.y; pdev->view_max.size = pdev->view_max.x * pdev->view_max.y; /* length of image, in YUV format; always allocate enough memory. */ pdev->len_per_image = PAGE_ALIGN((pdev->abs_max.x * pdev->abs_max.y * 3) / 2); }
gpl-2.0
Lloir/Prometheus_kernel_golf
drivers/spi/amba-pl022.c
2264
66062
/* * drivers/spi/amba-pl022.c * * A driver for the ARM PL022 PrimeCell SSP/SPI bus master. * * Copyright (C) 2008-2009 ST-Ericsson AB * Copyright (C) 2006 STMicroelectronics Pvt. Ltd. * * Author: Linus Walleij <linus.walleij@stericsson.com> * * Initial version inspired by: * linux-2.6.17-rc3-mm1/drivers/spi/pxa2xx_spi.c * Initial adoption to PL022 by: * Sachin Verma <sachin.verma@st.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. */ #include <linux/init.h> #include <linux/module.h> #include <linux/device.h> #include <linux/ioport.h> #include <linux/errno.h> #include <linux/interrupt.h> #include <linux/spi/spi.h> #include <linux/workqueue.h> #include <linux/delay.h> #include <linux/clk.h> #include <linux/err.h> #include <linux/amba/bus.h> #include <linux/amba/pl022.h> #include <linux/io.h> #include <linux/slab.h> #include <linux/dmaengine.h> #include <linux/dma-mapping.h> #include <linux/scatterlist.h> /* * This macro is used to define some register default values. * reg is masked with mask, the OR:ed with an (again masked) * val shifted sb steps to the left. */ #define SSP_WRITE_BITS(reg, val, mask, sb) \ ((reg) = (((reg) & ~(mask)) | (((val)<<(sb)) & (mask)))) /* * This macro is also used to define some default values. * It will just shift val by sb steps to the left and mask * the result with mask. */ #define GEN_MASK_BITS(val, mask, sb) \ (((val)<<(sb)) & (mask)) #define DRIVE_TX 0 #define DO_NOT_DRIVE_TX 1 #define DO_NOT_QUEUE_DMA 0 #define QUEUE_DMA 1 #define RX_TRANSFER 1 #define TX_TRANSFER 2 /* * Macros to access SSP Registers with their offsets */ #define SSP_CR0(r) (r + 0x000) #define SSP_CR1(r) (r + 0x004) #define SSP_DR(r) (r + 0x008) #define SSP_SR(r) (r + 0x00C) #define SSP_CPSR(r) (r + 0x010) #define SSP_IMSC(r) (r + 0x014) #define SSP_RIS(r) (r + 0x018) #define SSP_MIS(r) (r + 0x01C) #define SSP_ICR(r) (r + 0x020) #define SSP_DMACR(r) (r + 0x024) #define SSP_ITCR(r) (r + 0x080) #define SSP_ITIP(r) (r + 0x084) #define SSP_ITOP(r) (r + 0x088) #define SSP_TDR(r) (r + 0x08C) #define SSP_PID0(r) (r + 0xFE0) #define SSP_PID1(r) (r + 0xFE4) #define SSP_PID2(r) (r + 0xFE8) #define SSP_PID3(r) (r + 0xFEC) #define SSP_CID0(r) (r + 0xFF0) #define SSP_CID1(r) (r + 0xFF4) #define SSP_CID2(r) (r + 0xFF8) #define SSP_CID3(r) (r + 0xFFC) /* * SSP Control Register 0 - SSP_CR0 */ #define SSP_CR0_MASK_DSS (0x0FUL << 0) #define SSP_CR0_MASK_FRF (0x3UL << 4) #define SSP_CR0_MASK_SPO (0x1UL << 6) #define SSP_CR0_MASK_SPH (0x1UL << 7) #define SSP_CR0_MASK_SCR (0xFFUL << 8) /* * The ST version of this block moves som bits * in SSP_CR0 and extends it to 32 bits */ #define SSP_CR0_MASK_DSS_ST (0x1FUL << 0) #define SSP_CR0_MASK_HALFDUP_ST (0x1UL << 5) #define SSP_CR0_MASK_CSS_ST (0x1FUL << 16) #define SSP_CR0_MASK_FRF_ST (0x3UL << 21) /* * SSP Control Register 0 - SSP_CR1 */ #define SSP_CR1_MASK_LBM (0x1UL << 0) #define SSP_CR1_MASK_SSE (0x1UL << 1) #define SSP_CR1_MASK_MS (0x1UL << 2) #define SSP_CR1_MASK_SOD (0x1UL << 3) /* * The ST version of this block adds some bits * in SSP_CR1 */ #define SSP_CR1_MASK_RENDN_ST (0x1UL << 4) #define SSP_CR1_MASK_TENDN_ST (0x1UL << 5) #define SSP_CR1_MASK_MWAIT_ST (0x1UL << 6) #define SSP_CR1_MASK_RXIFLSEL_ST (0x7UL << 7) #define SSP_CR1_MASK_TXIFLSEL_ST (0x7UL << 10) /* This one is only in the PL023 variant */ #define SSP_CR1_MASK_FBCLKDEL_ST (0x7UL << 13) /* * SSP Status Register - SSP_SR */ #define SSP_SR_MASK_TFE (0x1UL << 0) /* Transmit FIFO empty */ #define SSP_SR_MASK_TNF (0x1UL << 1) /* Transmit FIFO not full */ #define SSP_SR_MASK_RNE (0x1UL << 2) /* Receive FIFO not empty */ #define SSP_SR_MASK_RFF (0x1UL << 3) /* Receive FIFO full */ #define SSP_SR_MASK_BSY (0x1UL << 4) /* Busy Flag */ /* * SSP Clock Prescale Register - SSP_CPSR */ #define SSP_CPSR_MASK_CPSDVSR (0xFFUL << 0) /* * SSP Interrupt Mask Set/Clear Register - SSP_IMSC */ #define SSP_IMSC_MASK_RORIM (0x1UL << 0) /* Receive Overrun Interrupt mask */ #define SSP_IMSC_MASK_RTIM (0x1UL << 1) /* Receive timeout Interrupt mask */ #define SSP_IMSC_MASK_RXIM (0x1UL << 2) /* Receive FIFO Interrupt mask */ #define SSP_IMSC_MASK_TXIM (0x1UL << 3) /* Transmit FIFO Interrupt mask */ /* * SSP Raw Interrupt Status Register - SSP_RIS */ /* Receive Overrun Raw Interrupt status */ #define SSP_RIS_MASK_RORRIS (0x1UL << 0) /* Receive Timeout Raw Interrupt status */ #define SSP_RIS_MASK_RTRIS (0x1UL << 1) /* Receive FIFO Raw Interrupt status */ #define SSP_RIS_MASK_RXRIS (0x1UL << 2) /* Transmit FIFO Raw Interrupt status */ #define SSP_RIS_MASK_TXRIS (0x1UL << 3) /* * SSP Masked Interrupt Status Register - SSP_MIS */ /* Receive Overrun Masked Interrupt status */ #define SSP_MIS_MASK_RORMIS (0x1UL << 0) /* Receive Timeout Masked Interrupt status */ #define SSP_MIS_MASK_RTMIS (0x1UL << 1) /* Receive FIFO Masked Interrupt status */ #define SSP_MIS_MASK_RXMIS (0x1UL << 2) /* Transmit FIFO Masked Interrupt status */ #define SSP_MIS_MASK_TXMIS (0x1UL << 3) /* * SSP Interrupt Clear Register - SSP_ICR */ /* Receive Overrun Raw Clear Interrupt bit */ #define SSP_ICR_MASK_RORIC (0x1UL << 0) /* Receive Timeout Clear Interrupt bit */ #define SSP_ICR_MASK_RTIC (0x1UL << 1) /* * SSP DMA Control Register - SSP_DMACR */ /* Receive DMA Enable bit */ #define SSP_DMACR_MASK_RXDMAE (0x1UL << 0) /* Transmit DMA Enable bit */ #define SSP_DMACR_MASK_TXDMAE (0x1UL << 1) /* * SSP Integration Test control Register - SSP_ITCR */ #define SSP_ITCR_MASK_ITEN (0x1UL << 0) #define SSP_ITCR_MASK_TESTFIFO (0x1UL << 1) /* * SSP Integration Test Input Register - SSP_ITIP */ #define ITIP_MASK_SSPRXD (0x1UL << 0) #define ITIP_MASK_SSPFSSIN (0x1UL << 1) #define ITIP_MASK_SSPCLKIN (0x1UL << 2) #define ITIP_MASK_RXDMAC (0x1UL << 3) #define ITIP_MASK_TXDMAC (0x1UL << 4) #define ITIP_MASK_SSPTXDIN (0x1UL << 5) /* * SSP Integration Test output Register - SSP_ITOP */ #define ITOP_MASK_SSPTXD (0x1UL << 0) #define ITOP_MASK_SSPFSSOUT (0x1UL << 1) #define ITOP_MASK_SSPCLKOUT (0x1UL << 2) #define ITOP_MASK_SSPOEn (0x1UL << 3) #define ITOP_MASK_SSPCTLOEn (0x1UL << 4) #define ITOP_MASK_RORINTR (0x1UL << 5) #define ITOP_MASK_RTINTR (0x1UL << 6) #define ITOP_MASK_RXINTR (0x1UL << 7) #define ITOP_MASK_TXINTR (0x1UL << 8) #define ITOP_MASK_INTR (0x1UL << 9) #define ITOP_MASK_RXDMABREQ (0x1UL << 10) #define ITOP_MASK_RXDMASREQ (0x1UL << 11) #define ITOP_MASK_TXDMABREQ (0x1UL << 12) #define ITOP_MASK_TXDMASREQ (0x1UL << 13) /* * SSP Test Data Register - SSP_TDR */ #define TDR_MASK_TESTDATA (0xFFFFFFFF) /* * Message State * we use the spi_message.state (void *) pointer to * hold a single state value, that's why all this * (void *) casting is done here. */ #define STATE_START ((void *) 0) #define STATE_RUNNING ((void *) 1) #define STATE_DONE ((void *) 2) #define STATE_ERROR ((void *) -1) /* * SSP State - Whether Enabled or Disabled */ #define SSP_DISABLED (0) #define SSP_ENABLED (1) /* * SSP DMA State - Whether DMA Enabled or Disabled */ #define SSP_DMA_DISABLED (0) #define SSP_DMA_ENABLED (1) /* * SSP Clock Defaults */ #define SSP_DEFAULT_CLKRATE 0x2 #define SSP_DEFAULT_PRESCALE 0x40 /* * SSP Clock Parameter ranges */ #define CPSDVR_MIN 0x02 #define CPSDVR_MAX 0xFE #define SCR_MIN 0x00 #define SCR_MAX 0xFF /* * SSP Interrupt related Macros */ #define DEFAULT_SSP_REG_IMSC 0x0UL #define DISABLE_ALL_INTERRUPTS DEFAULT_SSP_REG_IMSC #define ENABLE_ALL_INTERRUPTS (~DEFAULT_SSP_REG_IMSC) #define CLEAR_ALL_INTERRUPTS 0x3 #define SPI_POLLING_TIMEOUT 1000 /* * The type of reading going on on this chip */ enum ssp_reading { READING_NULL, READING_U8, READING_U16, READING_U32 }; /** * The type of writing going on on this chip */ enum ssp_writing { WRITING_NULL, WRITING_U8, WRITING_U16, WRITING_U32 }; /** * struct vendor_data - vendor-specific config parameters * for PL022 derivates * @fifodepth: depth of FIFOs (both) * @max_bpw: maximum number of bits per word * @unidir: supports unidirection transfers * @extended_cr: 32 bit wide control register 0 with extra * features and extra features in CR1 as found in the ST variants * @pl023: supports a subset of the ST extensions called "PL023" */ struct vendor_data { int fifodepth; int max_bpw; bool unidir; bool extended_cr; bool pl023; bool loopback; }; /** * struct pl022 - This is the private SSP driver data structure * @adev: AMBA device model hookup * @vendor: vendor data for the IP block * @phybase: the physical memory where the SSP device resides * @virtbase: the virtual memory where the SSP is mapped * @clk: outgoing clock "SPICLK" for the SPI bus * @master: SPI framework hookup * @master_info: controller-specific data from machine setup * @workqueue: a workqueue on which any spi_message request is queued * @pump_messages: work struct for scheduling work to the workqueue * @queue_lock: spinlock to syncronise access to message queue * @queue: message queue * @busy: workqueue is busy * @running: workqueue is running * @pump_transfers: Tasklet used in Interrupt Transfer mode * @cur_msg: Pointer to current spi_message being processed * @cur_transfer: Pointer to current spi_transfer * @cur_chip: pointer to current clients chip(assigned from controller_state) * @tx: current position in TX buffer to be read * @tx_end: end position in TX buffer to be read * @rx: current position in RX buffer to be written * @rx_end: end position in RX buffer to be written * @read: the type of read currently going on * @write: the type of write currently going on * @exp_fifo_level: expected FIFO level * @dma_rx_channel: optional channel for RX DMA * @dma_tx_channel: optional channel for TX DMA * @sgt_rx: scattertable for the RX transfer * @sgt_tx: scattertable for the TX transfer * @dummypage: a dummy page used for driving data on the bus with DMA */ struct pl022 { struct amba_device *adev; struct vendor_data *vendor; resource_size_t phybase; void __iomem *virtbase; struct clk *clk; struct spi_master *master; struct pl022_ssp_controller *master_info; /* Driver message queue */ struct workqueue_struct *workqueue; struct work_struct pump_messages; spinlock_t queue_lock; struct list_head queue; bool busy; bool running; /* Message transfer pump */ struct tasklet_struct pump_transfers; struct spi_message *cur_msg; struct spi_transfer *cur_transfer; struct chip_data *cur_chip; void *tx; void *tx_end; void *rx; void *rx_end; enum ssp_reading read; enum ssp_writing write; u32 exp_fifo_level; /* DMA settings */ #ifdef CONFIG_DMA_ENGINE struct dma_chan *dma_rx_channel; struct dma_chan *dma_tx_channel; struct sg_table sgt_rx; struct sg_table sgt_tx; char *dummypage; #endif }; /** * struct chip_data - To maintain runtime state of SSP for each client chip * @cr0: Value of control register CR0 of SSP - on later ST variants this * register is 32 bits wide rather than just 16 * @cr1: Value of control register CR1 of SSP * @dmacr: Value of DMA control Register of SSP * @cpsr: Value of Clock prescale register * @n_bytes: how many bytes(power of 2) reqd for a given data width of client * @enable_dma: Whether to enable DMA or not * @read: function ptr to be used to read when doing xfer for this chip * @write: function ptr to be used to write when doing xfer for this chip * @cs_control: chip select callback provided by chip * @xfer_type: polling/interrupt/DMA * * Runtime state of the SSP controller, maintained per chip, * This would be set according to the current message that would be served */ struct chip_data { u32 cr0; u16 cr1; u16 dmacr; u16 cpsr; u8 n_bytes; bool enable_dma; enum ssp_reading read; enum ssp_writing write; void (*cs_control) (u32 command); int xfer_type; }; /** * null_cs_control - Dummy chip select function * @command: select/delect the chip * * If no chip select function is provided by client this is used as dummy * chip select */ static void null_cs_control(u32 command) { pr_debug("pl022: dummy chip select control, CS=0x%x\n", command); } /** * giveback - current spi_message is over, schedule next message and call * callback of this message. Assumes that caller already * set message->status; dma and pio irqs are blocked * @pl022: SSP driver private data structure */ static void giveback(struct pl022 *pl022) { struct spi_transfer *last_transfer; unsigned long flags; struct spi_message *msg; void (*curr_cs_control) (u32 command); /* * This local reference to the chip select function * is needed because we set curr_chip to NULL * as a step toward termininating the message. */ curr_cs_control = pl022->cur_chip->cs_control; spin_lock_irqsave(&pl022->queue_lock, flags); msg = pl022->cur_msg; pl022->cur_msg = NULL; pl022->cur_transfer = NULL; pl022->cur_chip = NULL; queue_work(pl022->workqueue, &pl022->pump_messages); spin_unlock_irqrestore(&pl022->queue_lock, flags); last_transfer = list_entry(msg->transfers.prev, struct spi_transfer, transfer_list); /* Delay if requested before any change in chip select */ if (last_transfer->delay_usecs) /* * FIXME: This runs in interrupt context. * Is this really smart? */ udelay(last_transfer->delay_usecs); /* * Drop chip select UNLESS cs_change is true or we are returning * a message with an error, or next message is for another chip */ if (!last_transfer->cs_change) curr_cs_control(SSP_CHIP_DESELECT); else { struct spi_message *next_msg; /* Holding of cs was hinted, but we need to make sure * the next message is for the same chip. Don't waste * time with the following tests unless this was hinted. * * We cannot postpone this until pump_messages, because * after calling msg->complete (below) the driver that * sent the current message could be unloaded, which * could invalidate the cs_control() callback... */ /* get a pointer to the next message, if any */ spin_lock_irqsave(&pl022->queue_lock, flags); if (list_empty(&pl022->queue)) next_msg = NULL; else next_msg = list_entry(pl022->queue.next, struct spi_message, queue); spin_unlock_irqrestore(&pl022->queue_lock, flags); /* see if the next and current messages point * to the same chip */ if (next_msg && next_msg->spi != msg->spi) next_msg = NULL; if (!next_msg || msg->state == STATE_ERROR) curr_cs_control(SSP_CHIP_DESELECT); } msg->state = NULL; if (msg->complete) msg->complete(msg->context); /* This message is completed, so let's turn off the clocks & power */ clk_disable(pl022->clk); amba_pclk_disable(pl022->adev); amba_vcore_disable(pl022->adev); } /** * flush - flush the FIFO to reach a clean state * @pl022: SSP driver private data structure */ static int flush(struct pl022 *pl022) { unsigned long limit = loops_per_jiffy << 1; dev_dbg(&pl022->adev->dev, "flush\n"); do { while (readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_RNE) readw(SSP_DR(pl022->virtbase)); } while ((readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_BSY) && limit--); pl022->exp_fifo_level = 0; return limit; } /** * restore_state - Load configuration of current chip * @pl022: SSP driver private data structure */ static void restore_state(struct pl022 *pl022) { struct chip_data *chip = pl022->cur_chip; if (pl022->vendor->extended_cr) writel(chip->cr0, SSP_CR0(pl022->virtbase)); else writew(chip->cr0, SSP_CR0(pl022->virtbase)); writew(chip->cr1, SSP_CR1(pl022->virtbase)); writew(chip->dmacr, SSP_DMACR(pl022->virtbase)); writew(chip->cpsr, SSP_CPSR(pl022->virtbase)); writew(DISABLE_ALL_INTERRUPTS, SSP_IMSC(pl022->virtbase)); writew(CLEAR_ALL_INTERRUPTS, SSP_ICR(pl022->virtbase)); } /* * Default SSP Register Values */ #define DEFAULT_SSP_REG_CR0 ( \ GEN_MASK_BITS(SSP_DATA_BITS_12, SSP_CR0_MASK_DSS, 0) | \ GEN_MASK_BITS(SSP_INTERFACE_MOTOROLA_SPI, SSP_CR0_MASK_FRF, 4) | \ GEN_MASK_BITS(SSP_CLK_POL_IDLE_LOW, SSP_CR0_MASK_SPO, 6) | \ GEN_MASK_BITS(SSP_CLK_SECOND_EDGE, SSP_CR0_MASK_SPH, 7) | \ GEN_MASK_BITS(SSP_DEFAULT_CLKRATE, SSP_CR0_MASK_SCR, 8) \ ) /* ST versions have slightly different bit layout */ #define DEFAULT_SSP_REG_CR0_ST ( \ GEN_MASK_BITS(SSP_DATA_BITS_12, SSP_CR0_MASK_DSS_ST, 0) | \ GEN_MASK_BITS(SSP_MICROWIRE_CHANNEL_FULL_DUPLEX, SSP_CR0_MASK_HALFDUP_ST, 5) | \ GEN_MASK_BITS(SSP_CLK_POL_IDLE_LOW, SSP_CR0_MASK_SPO, 6) | \ GEN_MASK_BITS(SSP_CLK_SECOND_EDGE, SSP_CR0_MASK_SPH, 7) | \ GEN_MASK_BITS(SSP_DEFAULT_CLKRATE, SSP_CR0_MASK_SCR, 8) | \ GEN_MASK_BITS(SSP_BITS_8, SSP_CR0_MASK_CSS_ST, 16) | \ GEN_MASK_BITS(SSP_INTERFACE_MOTOROLA_SPI, SSP_CR0_MASK_FRF_ST, 21) \ ) /* The PL023 version is slightly different again */ #define DEFAULT_SSP_REG_CR0_ST_PL023 ( \ GEN_MASK_BITS(SSP_DATA_BITS_12, SSP_CR0_MASK_DSS_ST, 0) | \ GEN_MASK_BITS(SSP_CLK_POL_IDLE_LOW, SSP_CR0_MASK_SPO, 6) | \ GEN_MASK_BITS(SSP_CLK_SECOND_EDGE, SSP_CR0_MASK_SPH, 7) | \ GEN_MASK_BITS(SSP_DEFAULT_CLKRATE, SSP_CR0_MASK_SCR, 8) \ ) #define DEFAULT_SSP_REG_CR1 ( \ GEN_MASK_BITS(LOOPBACK_DISABLED, SSP_CR1_MASK_LBM, 0) | \ GEN_MASK_BITS(SSP_DISABLED, SSP_CR1_MASK_SSE, 1) | \ GEN_MASK_BITS(SSP_MASTER, SSP_CR1_MASK_MS, 2) | \ GEN_MASK_BITS(DO_NOT_DRIVE_TX, SSP_CR1_MASK_SOD, 3) \ ) /* ST versions extend this register to use all 16 bits */ #define DEFAULT_SSP_REG_CR1_ST ( \ DEFAULT_SSP_REG_CR1 | \ GEN_MASK_BITS(SSP_RX_MSB, SSP_CR1_MASK_RENDN_ST, 4) | \ GEN_MASK_BITS(SSP_TX_MSB, SSP_CR1_MASK_TENDN_ST, 5) | \ GEN_MASK_BITS(SSP_MWIRE_WAIT_ZERO, SSP_CR1_MASK_MWAIT_ST, 6) |\ GEN_MASK_BITS(SSP_RX_1_OR_MORE_ELEM, SSP_CR1_MASK_RXIFLSEL_ST, 7) | \ GEN_MASK_BITS(SSP_TX_1_OR_MORE_EMPTY_LOC, SSP_CR1_MASK_TXIFLSEL_ST, 10) \ ) /* * The PL023 variant has further differences: no loopback mode, no microwire * support, and a new clock feedback delay setting. */ #define DEFAULT_SSP_REG_CR1_ST_PL023 ( \ GEN_MASK_BITS(SSP_DISABLED, SSP_CR1_MASK_SSE, 1) | \ GEN_MASK_BITS(SSP_MASTER, SSP_CR1_MASK_MS, 2) | \ GEN_MASK_BITS(DO_NOT_DRIVE_TX, SSP_CR1_MASK_SOD, 3) | \ GEN_MASK_BITS(SSP_RX_MSB, SSP_CR1_MASK_RENDN_ST, 4) | \ GEN_MASK_BITS(SSP_TX_MSB, SSP_CR1_MASK_TENDN_ST, 5) | \ GEN_MASK_BITS(SSP_RX_1_OR_MORE_ELEM, SSP_CR1_MASK_RXIFLSEL_ST, 7) | \ GEN_MASK_BITS(SSP_TX_1_OR_MORE_EMPTY_LOC, SSP_CR1_MASK_TXIFLSEL_ST, 10) | \ GEN_MASK_BITS(SSP_FEEDBACK_CLK_DELAY_NONE, SSP_CR1_MASK_FBCLKDEL_ST, 13) \ ) #define DEFAULT_SSP_REG_CPSR ( \ GEN_MASK_BITS(SSP_DEFAULT_PRESCALE, SSP_CPSR_MASK_CPSDVSR, 0) \ ) #define DEFAULT_SSP_REG_DMACR (\ GEN_MASK_BITS(SSP_DMA_DISABLED, SSP_DMACR_MASK_RXDMAE, 0) | \ GEN_MASK_BITS(SSP_DMA_DISABLED, SSP_DMACR_MASK_TXDMAE, 1) \ ) /** * load_ssp_default_config - Load default configuration for SSP * @pl022: SSP driver private data structure */ static void load_ssp_default_config(struct pl022 *pl022) { if (pl022->vendor->pl023) { writel(DEFAULT_SSP_REG_CR0_ST_PL023, SSP_CR0(pl022->virtbase)); writew(DEFAULT_SSP_REG_CR1_ST_PL023, SSP_CR1(pl022->virtbase)); } else if (pl022->vendor->extended_cr) { writel(DEFAULT_SSP_REG_CR0_ST, SSP_CR0(pl022->virtbase)); writew(DEFAULT_SSP_REG_CR1_ST, SSP_CR1(pl022->virtbase)); } else { writew(DEFAULT_SSP_REG_CR0, SSP_CR0(pl022->virtbase)); writew(DEFAULT_SSP_REG_CR1, SSP_CR1(pl022->virtbase)); } writew(DEFAULT_SSP_REG_DMACR, SSP_DMACR(pl022->virtbase)); writew(DEFAULT_SSP_REG_CPSR, SSP_CPSR(pl022->virtbase)); writew(DISABLE_ALL_INTERRUPTS, SSP_IMSC(pl022->virtbase)); writew(CLEAR_ALL_INTERRUPTS, SSP_ICR(pl022->virtbase)); } /** * This will write to TX and read from RX according to the parameters * set in pl022. */ static void readwriter(struct pl022 *pl022) { /* * The FIFO depth is different between primecell variants. * I believe filling in too much in the FIFO might cause * errons in 8bit wide transfers on ARM variants (just 8 words * FIFO, means only 8x8 = 64 bits in FIFO) at least. * * To prevent this issue, the TX FIFO is only filled to the * unused RX FIFO fill length, regardless of what the TX * FIFO status flag indicates. */ dev_dbg(&pl022->adev->dev, "%s, rx: %p, rxend: %p, tx: %p, txend: %p\n", __func__, pl022->rx, pl022->rx_end, pl022->tx, pl022->tx_end); /* Read as much as you can */ while ((readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_RNE) && (pl022->rx < pl022->rx_end)) { switch (pl022->read) { case READING_NULL: readw(SSP_DR(pl022->virtbase)); break; case READING_U8: *(u8 *) (pl022->rx) = readw(SSP_DR(pl022->virtbase)) & 0xFFU; break; case READING_U16: *(u16 *) (pl022->rx) = (u16) readw(SSP_DR(pl022->virtbase)); break; case READING_U32: *(u32 *) (pl022->rx) = readl(SSP_DR(pl022->virtbase)); break; } pl022->rx += (pl022->cur_chip->n_bytes); pl022->exp_fifo_level--; } /* * Write as much as possible up to the RX FIFO size */ while ((pl022->exp_fifo_level < pl022->vendor->fifodepth) && (pl022->tx < pl022->tx_end)) { switch (pl022->write) { case WRITING_NULL: writew(0x0, SSP_DR(pl022->virtbase)); break; case WRITING_U8: writew(*(u8 *) (pl022->tx), SSP_DR(pl022->virtbase)); break; case WRITING_U16: writew((*(u16 *) (pl022->tx)), SSP_DR(pl022->virtbase)); break; case WRITING_U32: writel(*(u32 *) (pl022->tx), SSP_DR(pl022->virtbase)); break; } pl022->tx += (pl022->cur_chip->n_bytes); pl022->exp_fifo_level++; /* * This inner reader takes care of things appearing in the RX * FIFO as we're transmitting. This will happen a lot since the * clock starts running when you put things into the TX FIFO, * and then things are continuously clocked into the RX FIFO. */ while ((readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_RNE) && (pl022->rx < pl022->rx_end)) { switch (pl022->read) { case READING_NULL: readw(SSP_DR(pl022->virtbase)); break; case READING_U8: *(u8 *) (pl022->rx) = readw(SSP_DR(pl022->virtbase)) & 0xFFU; break; case READING_U16: *(u16 *) (pl022->rx) = (u16) readw(SSP_DR(pl022->virtbase)); break; case READING_U32: *(u32 *) (pl022->rx) = readl(SSP_DR(pl022->virtbase)); break; } pl022->rx += (pl022->cur_chip->n_bytes); pl022->exp_fifo_level--; } } /* * When we exit here the TX FIFO should be full and the RX FIFO * should be empty */ } /** * next_transfer - Move to the Next transfer in the current spi message * @pl022: SSP driver private data structure * * This function moves though the linked list of spi transfers in the * current spi message and returns with the state of current spi * message i.e whether its last transfer is done(STATE_DONE) or * Next transfer is ready(STATE_RUNNING) */ static void *next_transfer(struct pl022 *pl022) { struct spi_message *msg = pl022->cur_msg; struct spi_transfer *trans = pl022->cur_transfer; /* Move to next transfer */ if (trans->transfer_list.next != &msg->transfers) { pl022->cur_transfer = list_entry(trans->transfer_list.next, struct spi_transfer, transfer_list); return STATE_RUNNING; } return STATE_DONE; } /* * This DMA functionality is only compiled in if we have * access to the generic DMA devices/DMA engine. */ #ifdef CONFIG_DMA_ENGINE static void unmap_free_dma_scatter(struct pl022 *pl022) { /* Unmap and free the SG tables */ dma_unmap_sg(pl022->dma_tx_channel->device->dev, pl022->sgt_tx.sgl, pl022->sgt_tx.nents, DMA_TO_DEVICE); dma_unmap_sg(pl022->dma_rx_channel->device->dev, pl022->sgt_rx.sgl, pl022->sgt_rx.nents, DMA_FROM_DEVICE); sg_free_table(&pl022->sgt_rx); sg_free_table(&pl022->sgt_tx); } static void dma_callback(void *data) { struct pl022 *pl022 = data; struct spi_message *msg = pl022->cur_msg; BUG_ON(!pl022->sgt_rx.sgl); #ifdef VERBOSE_DEBUG /* * Optionally dump out buffers to inspect contents, this is * good if you want to convince yourself that the loopback * read/write contents are the same, when adopting to a new * DMA engine. */ { struct scatterlist *sg; unsigned int i; dma_sync_sg_for_cpu(&pl022->adev->dev, pl022->sgt_rx.sgl, pl022->sgt_rx.nents, DMA_FROM_DEVICE); for_each_sg(pl022->sgt_rx.sgl, sg, pl022->sgt_rx.nents, i) { dev_dbg(&pl022->adev->dev, "SPI RX SG ENTRY: %d", i); print_hex_dump(KERN_ERR, "SPI RX: ", DUMP_PREFIX_OFFSET, 16, 1, sg_virt(sg), sg_dma_len(sg), 1); } for_each_sg(pl022->sgt_tx.sgl, sg, pl022->sgt_tx.nents, i) { dev_dbg(&pl022->adev->dev, "SPI TX SG ENTRY: %d", i); print_hex_dump(KERN_ERR, "SPI TX: ", DUMP_PREFIX_OFFSET, 16, 1, sg_virt(sg), sg_dma_len(sg), 1); } } #endif unmap_free_dma_scatter(pl022); /* Update total bytes transferred */ msg->actual_length += pl022->cur_transfer->len; if (pl022->cur_transfer->cs_change) pl022->cur_chip-> cs_control(SSP_CHIP_DESELECT); /* Move to next transfer */ msg->state = next_transfer(pl022); tasklet_schedule(&pl022->pump_transfers); } static void setup_dma_scatter(struct pl022 *pl022, void *buffer, unsigned int length, struct sg_table *sgtab) { struct scatterlist *sg; int bytesleft = length; void *bufp = buffer; int mapbytes; int i; if (buffer) { for_each_sg(sgtab->sgl, sg, sgtab->nents, i) { /* * If there are less bytes left than what fits * in the current page (plus page alignment offset) * we just feed in this, else we stuff in as much * as we can. */ if (bytesleft < (PAGE_SIZE - offset_in_page(bufp))) mapbytes = bytesleft; else mapbytes = PAGE_SIZE - offset_in_page(bufp); sg_set_page(sg, virt_to_page(bufp), mapbytes, offset_in_page(bufp)); bufp += mapbytes; bytesleft -= mapbytes; dev_dbg(&pl022->adev->dev, "set RX/TX target page @ %p, %d bytes, %d left\n", bufp, mapbytes, bytesleft); } } else { /* Map the dummy buffer on every page */ for_each_sg(sgtab->sgl, sg, sgtab->nents, i) { if (bytesleft < PAGE_SIZE) mapbytes = bytesleft; else mapbytes = PAGE_SIZE; sg_set_page(sg, virt_to_page(pl022->dummypage), mapbytes, 0); bytesleft -= mapbytes; dev_dbg(&pl022->adev->dev, "set RX/TX to dummy page %d bytes, %d left\n", mapbytes, bytesleft); } } BUG_ON(bytesleft); } /** * configure_dma - configures the channels for the next transfer * @pl022: SSP driver's private data structure */ static int configure_dma(struct pl022 *pl022) { struct dma_slave_config rx_conf = { .src_addr = SSP_DR(pl022->phybase), .direction = DMA_FROM_DEVICE, .src_maxburst = pl022->vendor->fifodepth >> 1, }; struct dma_slave_config tx_conf = { .dst_addr = SSP_DR(pl022->phybase), .direction = DMA_TO_DEVICE, .dst_maxburst = pl022->vendor->fifodepth >> 1, }; unsigned int pages; int ret; int rx_sglen, tx_sglen; struct dma_chan *rxchan = pl022->dma_rx_channel; struct dma_chan *txchan = pl022->dma_tx_channel; struct dma_async_tx_descriptor *rxdesc; struct dma_async_tx_descriptor *txdesc; /* Check that the channels are available */ if (!rxchan || !txchan) return -ENODEV; switch (pl022->read) { case READING_NULL: /* Use the same as for writing */ rx_conf.src_addr_width = DMA_SLAVE_BUSWIDTH_UNDEFINED; break; case READING_U8: rx_conf.src_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE; break; case READING_U16: rx_conf.src_addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES; break; case READING_U32: rx_conf.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES; break; } switch (pl022->write) { case WRITING_NULL: /* Use the same as for reading */ tx_conf.dst_addr_width = DMA_SLAVE_BUSWIDTH_UNDEFINED; break; case WRITING_U8: tx_conf.dst_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE; break; case WRITING_U16: tx_conf.dst_addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES; break; case WRITING_U32: tx_conf.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES; break; } /* SPI pecularity: we need to read and write the same width */ if (rx_conf.src_addr_width == DMA_SLAVE_BUSWIDTH_UNDEFINED) rx_conf.src_addr_width = tx_conf.dst_addr_width; if (tx_conf.dst_addr_width == DMA_SLAVE_BUSWIDTH_UNDEFINED) tx_conf.dst_addr_width = rx_conf.src_addr_width; BUG_ON(rx_conf.src_addr_width != tx_conf.dst_addr_width); dmaengine_slave_config(rxchan, &rx_conf); dmaengine_slave_config(txchan, &tx_conf); /* Create sglists for the transfers */ pages = (pl022->cur_transfer->len >> PAGE_SHIFT) + 1; dev_dbg(&pl022->adev->dev, "using %d pages for transfer\n", pages); ret = sg_alloc_table(&pl022->sgt_rx, pages, GFP_KERNEL); if (ret) goto err_alloc_rx_sg; ret = sg_alloc_table(&pl022->sgt_tx, pages, GFP_KERNEL); if (ret) goto err_alloc_tx_sg; /* Fill in the scatterlists for the RX+TX buffers */ setup_dma_scatter(pl022, pl022->rx, pl022->cur_transfer->len, &pl022->sgt_rx); setup_dma_scatter(pl022, pl022->tx, pl022->cur_transfer->len, &pl022->sgt_tx); /* Map DMA buffers */ rx_sglen = dma_map_sg(rxchan->device->dev, pl022->sgt_rx.sgl, pl022->sgt_rx.nents, DMA_FROM_DEVICE); if (!rx_sglen) goto err_rx_sgmap; tx_sglen = dma_map_sg(txchan->device->dev, pl022->sgt_tx.sgl, pl022->sgt_tx.nents, DMA_TO_DEVICE); if (!tx_sglen) goto err_tx_sgmap; /* Send both scatterlists */ rxdesc = rxchan->device->device_prep_slave_sg(rxchan, pl022->sgt_rx.sgl, rx_sglen, DMA_FROM_DEVICE, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (!rxdesc) goto err_rxdesc; txdesc = txchan->device->device_prep_slave_sg(txchan, pl022->sgt_tx.sgl, tx_sglen, DMA_TO_DEVICE, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (!txdesc) goto err_txdesc; /* Put the callback on the RX transfer only, that should finish last */ rxdesc->callback = dma_callback; rxdesc->callback_param = pl022; /* Submit and fire RX and TX with TX last so we're ready to read! */ dmaengine_submit(rxdesc); dmaengine_submit(txdesc); dma_async_issue_pending(rxchan); dma_async_issue_pending(txchan); return 0; err_txdesc: dmaengine_terminate_all(txchan); err_rxdesc: dmaengine_terminate_all(rxchan); dma_unmap_sg(txchan->device->dev, pl022->sgt_tx.sgl, pl022->sgt_tx.nents, DMA_TO_DEVICE); err_tx_sgmap: dma_unmap_sg(rxchan->device->dev, pl022->sgt_rx.sgl, pl022->sgt_tx.nents, DMA_FROM_DEVICE); err_rx_sgmap: sg_free_table(&pl022->sgt_tx); err_alloc_tx_sg: sg_free_table(&pl022->sgt_rx); err_alloc_rx_sg: return -ENOMEM; } static int __init pl022_dma_probe(struct pl022 *pl022) { dma_cap_mask_t mask; /* Try to acquire a generic DMA engine slave channel */ dma_cap_zero(mask); dma_cap_set(DMA_SLAVE, mask); /* * We need both RX and TX channels to do DMA, else do none * of them. */ pl022->dma_rx_channel = dma_request_channel(mask, pl022->master_info->dma_filter, pl022->master_info->dma_rx_param); if (!pl022->dma_rx_channel) { dev_dbg(&pl022->adev->dev, "no RX DMA channel!\n"); goto err_no_rxchan; } pl022->dma_tx_channel = dma_request_channel(mask, pl022->master_info->dma_filter, pl022->master_info->dma_tx_param); if (!pl022->dma_tx_channel) { dev_dbg(&pl022->adev->dev, "no TX DMA channel!\n"); goto err_no_txchan; } pl022->dummypage = kmalloc(PAGE_SIZE, GFP_KERNEL); if (!pl022->dummypage) { dev_dbg(&pl022->adev->dev, "no DMA dummypage!\n"); goto err_no_dummypage; } dev_info(&pl022->adev->dev, "setup for DMA on RX %s, TX %s\n", dma_chan_name(pl022->dma_rx_channel), dma_chan_name(pl022->dma_tx_channel)); return 0; err_no_dummypage: dma_release_channel(pl022->dma_tx_channel); err_no_txchan: dma_release_channel(pl022->dma_rx_channel); pl022->dma_rx_channel = NULL; err_no_rxchan: dev_err(&pl022->adev->dev, "Failed to work in dma mode, work without dma!\n"); return -ENODEV; } static void terminate_dma(struct pl022 *pl022) { struct dma_chan *rxchan = pl022->dma_rx_channel; struct dma_chan *txchan = pl022->dma_tx_channel; dmaengine_terminate_all(rxchan); dmaengine_terminate_all(txchan); unmap_free_dma_scatter(pl022); } static void pl022_dma_remove(struct pl022 *pl022) { if (pl022->busy) terminate_dma(pl022); if (pl022->dma_tx_channel) dma_release_channel(pl022->dma_tx_channel); if (pl022->dma_rx_channel) dma_release_channel(pl022->dma_rx_channel); kfree(pl022->dummypage); } #else static inline int configure_dma(struct pl022 *pl022) { return -ENODEV; } static inline int pl022_dma_probe(struct pl022 *pl022) { return 0; } static inline void pl022_dma_remove(struct pl022 *pl022) { } #endif /** * pl022_interrupt_handler - Interrupt handler for SSP controller * * This function handles interrupts generated for an interrupt based transfer. * If a receive overrun (ROR) interrupt is there then we disable SSP, flag the * current message's state as STATE_ERROR and schedule the tasklet * pump_transfers which will do the postprocessing of the current message by * calling giveback(). Otherwise it reads data from RX FIFO till there is no * more data, and writes data in TX FIFO till it is not full. If we complete * the transfer we move to the next transfer and schedule the tasklet. */ static irqreturn_t pl022_interrupt_handler(int irq, void *dev_id) { struct pl022 *pl022 = dev_id; struct spi_message *msg = pl022->cur_msg; u16 irq_status = 0; u16 flag = 0; if (unlikely(!msg)) { dev_err(&pl022->adev->dev, "bad message state in interrupt handler"); /* Never fail */ return IRQ_HANDLED; } /* Read the Interrupt Status Register */ irq_status = readw(SSP_MIS(pl022->virtbase)); if (unlikely(!irq_status)) return IRQ_NONE; /* * This handles the FIFO interrupts, the timeout * interrupts are flatly ignored, they cannot be * trusted. */ if (unlikely(irq_status & SSP_MIS_MASK_RORMIS)) { /* * Overrun interrupt - bail out since our Data has been * corrupted */ dev_err(&pl022->adev->dev, "FIFO overrun\n"); if (readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_RFF) dev_err(&pl022->adev->dev, "RXFIFO is full\n"); if (readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_TNF) dev_err(&pl022->adev->dev, "TXFIFO is full\n"); /* * Disable and clear interrupts, disable SSP, * mark message with bad status so it can be * retried. */ writew(DISABLE_ALL_INTERRUPTS, SSP_IMSC(pl022->virtbase)); writew(CLEAR_ALL_INTERRUPTS, SSP_ICR(pl022->virtbase)); writew((readw(SSP_CR1(pl022->virtbase)) & (~SSP_CR1_MASK_SSE)), SSP_CR1(pl022->virtbase)); msg->state = STATE_ERROR; /* Schedule message queue handler */ tasklet_schedule(&pl022->pump_transfers); return IRQ_HANDLED; } readwriter(pl022); if ((pl022->tx == pl022->tx_end) && (flag == 0)) { flag = 1; /* Disable Transmit interrupt */ writew(readw(SSP_IMSC(pl022->virtbase)) & (~SSP_IMSC_MASK_TXIM), SSP_IMSC(pl022->virtbase)); } /* * Since all transactions must write as much as shall be read, * we can conclude the entire transaction once RX is complete. * At this point, all TX will always be finished. */ if (pl022->rx >= pl022->rx_end) { writew(DISABLE_ALL_INTERRUPTS, SSP_IMSC(pl022->virtbase)); writew(CLEAR_ALL_INTERRUPTS, SSP_ICR(pl022->virtbase)); if (unlikely(pl022->rx > pl022->rx_end)) { dev_warn(&pl022->adev->dev, "read %u surplus " "bytes (did you request an odd " "number of bytes on a 16bit bus?)\n", (u32) (pl022->rx - pl022->rx_end)); } /* Update total bytes transferred */ msg->actual_length += pl022->cur_transfer->len; if (pl022->cur_transfer->cs_change) pl022->cur_chip-> cs_control(SSP_CHIP_DESELECT); /* Move to next transfer */ msg->state = next_transfer(pl022); tasklet_schedule(&pl022->pump_transfers); return IRQ_HANDLED; } return IRQ_HANDLED; } /** * This sets up the pointers to memory for the next message to * send out on the SPI bus. */ static int set_up_next_transfer(struct pl022 *pl022, struct spi_transfer *transfer) { int residue; /* Sanity check the message for this bus width */ residue = pl022->cur_transfer->len % pl022->cur_chip->n_bytes; if (unlikely(residue != 0)) { dev_err(&pl022->adev->dev, "message of %u bytes to transmit but the current " "chip bus has a data width of %u bytes!\n", pl022->cur_transfer->len, pl022->cur_chip->n_bytes); dev_err(&pl022->adev->dev, "skipping this message\n"); return -EIO; } pl022->tx = (void *)transfer->tx_buf; pl022->tx_end = pl022->tx + pl022->cur_transfer->len; pl022->rx = (void *)transfer->rx_buf; pl022->rx_end = pl022->rx + pl022->cur_transfer->len; pl022->write = pl022->tx ? pl022->cur_chip->write : WRITING_NULL; pl022->read = pl022->rx ? pl022->cur_chip->read : READING_NULL; return 0; } /** * pump_transfers - Tasklet function which schedules next transfer * when running in interrupt or DMA transfer mode. * @data: SSP driver private data structure * */ static void pump_transfers(unsigned long data) { struct pl022 *pl022 = (struct pl022 *) data; struct spi_message *message = NULL; struct spi_transfer *transfer = NULL; struct spi_transfer *previous = NULL; /* Get current state information */ message = pl022->cur_msg; transfer = pl022->cur_transfer; /* Handle for abort */ if (message->state == STATE_ERROR) { message->status = -EIO; giveback(pl022); return; } /* Handle end of message */ if (message->state == STATE_DONE) { message->status = 0; giveback(pl022); return; } /* Delay if requested at end of transfer before CS change */ if (message->state == STATE_RUNNING) { previous = list_entry(transfer->transfer_list.prev, struct spi_transfer, transfer_list); if (previous->delay_usecs) /* * FIXME: This runs in interrupt context. * Is this really smart? */ udelay(previous->delay_usecs); /* Drop chip select only if cs_change is requested */ if (previous->cs_change) pl022->cur_chip->cs_control(SSP_CHIP_SELECT); } else { /* STATE_START */ message->state = STATE_RUNNING; } if (set_up_next_transfer(pl022, transfer)) { message->state = STATE_ERROR; message->status = -EIO; giveback(pl022); return; } /* Flush the FIFOs and let's go! */ flush(pl022); if (pl022->cur_chip->enable_dma) { if (configure_dma(pl022)) { dev_dbg(&pl022->adev->dev, "configuration of DMA failed, fall back to interrupt mode\n"); goto err_config_dma; } return; } err_config_dma: writew(ENABLE_ALL_INTERRUPTS, SSP_IMSC(pl022->virtbase)); } static void do_interrupt_dma_transfer(struct pl022 *pl022) { u32 irqflags = ENABLE_ALL_INTERRUPTS; /* Enable target chip */ pl022->cur_chip->cs_control(SSP_CHIP_SELECT); if (set_up_next_transfer(pl022, pl022->cur_transfer)) { /* Error path */ pl022->cur_msg->state = STATE_ERROR; pl022->cur_msg->status = -EIO; giveback(pl022); return; } /* If we're using DMA, set up DMA here */ if (pl022->cur_chip->enable_dma) { /* Configure DMA transfer */ if (configure_dma(pl022)) { dev_dbg(&pl022->adev->dev, "configuration of DMA failed, fall back to interrupt mode\n"); goto err_config_dma; } /* Disable interrupts in DMA mode, IRQ from DMA controller */ irqflags = DISABLE_ALL_INTERRUPTS; } err_config_dma: /* Enable SSP, turn on interrupts */ writew((readw(SSP_CR1(pl022->virtbase)) | SSP_CR1_MASK_SSE), SSP_CR1(pl022->virtbase)); writew(irqflags, SSP_IMSC(pl022->virtbase)); } static void do_polling_transfer(struct pl022 *pl022) { struct spi_message *message = NULL; struct spi_transfer *transfer = NULL; struct spi_transfer *previous = NULL; struct chip_data *chip; unsigned long time, timeout; chip = pl022->cur_chip; message = pl022->cur_msg; while (message->state != STATE_DONE) { /* Handle for abort */ if (message->state == STATE_ERROR) break; transfer = pl022->cur_transfer; /* Delay if requested at end of transfer */ if (message->state == STATE_RUNNING) { previous = list_entry(transfer->transfer_list.prev, struct spi_transfer, transfer_list); if (previous->delay_usecs) udelay(previous->delay_usecs); if (previous->cs_change) pl022->cur_chip->cs_control(SSP_CHIP_SELECT); } else { /* STATE_START */ message->state = STATE_RUNNING; pl022->cur_chip->cs_control(SSP_CHIP_SELECT); } /* Configuration Changing Per Transfer */ if (set_up_next_transfer(pl022, transfer)) { /* Error path */ message->state = STATE_ERROR; break; } /* Flush FIFOs and enable SSP */ flush(pl022); writew((readw(SSP_CR1(pl022->virtbase)) | SSP_CR1_MASK_SSE), SSP_CR1(pl022->virtbase)); dev_dbg(&pl022->adev->dev, "polling transfer ongoing ...\n"); timeout = jiffies + msecs_to_jiffies(SPI_POLLING_TIMEOUT); while (pl022->tx < pl022->tx_end || pl022->rx < pl022->rx_end) { time = jiffies; readwriter(pl022); if (time_after(time, timeout)) { dev_warn(&pl022->adev->dev, "%s: timeout!\n", __func__); message->state = STATE_ERROR; goto out; } cpu_relax(); } /* Update total byte transferred */ message->actual_length += pl022->cur_transfer->len; if (pl022->cur_transfer->cs_change) pl022->cur_chip->cs_control(SSP_CHIP_DESELECT); /* Move to next transfer */ message->state = next_transfer(pl022); } out: /* Handle end of message */ if (message->state == STATE_DONE) message->status = 0; else message->status = -EIO; giveback(pl022); return; } /** * pump_messages - Workqueue function which processes spi message queue * @data: pointer to private data of SSP driver * * This function checks if there is any spi message in the queue that * needs processing and delegate control to appropriate function * do_polling_transfer()/do_interrupt_dma_transfer() * based on the kind of the transfer * */ static void pump_messages(struct work_struct *work) { struct pl022 *pl022 = container_of(work, struct pl022, pump_messages); unsigned long flags; /* Lock queue and check for queue work */ spin_lock_irqsave(&pl022->queue_lock, flags); if (list_empty(&pl022->queue) || !pl022->running) { pl022->busy = false; spin_unlock_irqrestore(&pl022->queue_lock, flags); return; } /* Make sure we are not already running a message */ if (pl022->cur_msg) { spin_unlock_irqrestore(&pl022->queue_lock, flags); return; } /* Extract head of queue */ pl022->cur_msg = list_entry(pl022->queue.next, struct spi_message, queue); list_del_init(&pl022->cur_msg->queue); pl022->busy = true; spin_unlock_irqrestore(&pl022->queue_lock, flags); /* Initial message state */ pl022->cur_msg->state = STATE_START; pl022->cur_transfer = list_entry(pl022->cur_msg->transfers.next, struct spi_transfer, transfer_list); /* Setup the SPI using the per chip configuration */ pl022->cur_chip = spi_get_ctldata(pl022->cur_msg->spi); /* * We enable the core voltage and clocks here, then the clocks * and core will be disabled when giveback() is called in each method * (poll/interrupt/DMA) */ amba_vcore_enable(pl022->adev); amba_pclk_enable(pl022->adev); clk_enable(pl022->clk); restore_state(pl022); flush(pl022); if (pl022->cur_chip->xfer_type == POLLING_TRANSFER) do_polling_transfer(pl022); else do_interrupt_dma_transfer(pl022); } static int __init init_queue(struct pl022 *pl022) { INIT_LIST_HEAD(&pl022->queue); spin_lock_init(&pl022->queue_lock); pl022->running = false; pl022->busy = false; tasklet_init(&pl022->pump_transfers, pump_transfers, (unsigned long)pl022); INIT_WORK(&pl022->pump_messages, pump_messages); pl022->workqueue = create_singlethread_workqueue( dev_name(pl022->master->dev.parent)); if (pl022->workqueue == NULL) return -EBUSY; return 0; } static int start_queue(struct pl022 *pl022) { unsigned long flags; spin_lock_irqsave(&pl022->queue_lock, flags); if (pl022->running || pl022->busy) { spin_unlock_irqrestore(&pl022->queue_lock, flags); return -EBUSY; } pl022->running = true; pl022->cur_msg = NULL; pl022->cur_transfer = NULL; pl022->cur_chip = NULL; spin_unlock_irqrestore(&pl022->queue_lock, flags); queue_work(pl022->workqueue, &pl022->pump_messages); return 0; } static int stop_queue(struct pl022 *pl022) { unsigned long flags; unsigned limit = 500; int status = 0; spin_lock_irqsave(&pl022->queue_lock, flags); /* This is a bit lame, but is optimized for the common execution path. * A wait_queue on the pl022->busy could be used, but then the common * execution path (pump_messages) would be required to call wake_up or * friends on every SPI message. Do this instead */ while ((!list_empty(&pl022->queue) || pl022->busy) && limit--) { spin_unlock_irqrestore(&pl022->queue_lock, flags); msleep(10); spin_lock_irqsave(&pl022->queue_lock, flags); } if (!list_empty(&pl022->queue) || pl022->busy) status = -EBUSY; else pl022->running = false; spin_unlock_irqrestore(&pl022->queue_lock, flags); return status; } static int destroy_queue(struct pl022 *pl022) { int status; status = stop_queue(pl022); /* we are unloading the module or failing to load (only two calls * to this routine), and neither call can handle a return value. * However, destroy_workqueue calls flush_workqueue, and that will * block until all work is done. If the reason that stop_queue * timed out is that the work will never finish, then it does no * good to call destroy_workqueue, so return anyway. */ if (status != 0) return status; destroy_workqueue(pl022->workqueue); return 0; } static int verify_controller_parameters(struct pl022 *pl022, struct pl022_config_chip const *chip_info) { if ((chip_info->iface < SSP_INTERFACE_MOTOROLA_SPI) || (chip_info->iface > SSP_INTERFACE_UNIDIRECTIONAL)) { dev_err(&pl022->adev->dev, "interface is configured incorrectly\n"); return -EINVAL; } if ((chip_info->iface == SSP_INTERFACE_UNIDIRECTIONAL) && (!pl022->vendor->unidir)) { dev_err(&pl022->adev->dev, "unidirectional mode not supported in this " "hardware version\n"); return -EINVAL; } if ((chip_info->hierarchy != SSP_MASTER) && (chip_info->hierarchy != SSP_SLAVE)) { dev_err(&pl022->adev->dev, "hierarchy is configured incorrectly\n"); return -EINVAL; } if ((chip_info->com_mode != INTERRUPT_TRANSFER) && (chip_info->com_mode != DMA_TRANSFER) && (chip_info->com_mode != POLLING_TRANSFER)) { dev_err(&pl022->adev->dev, "Communication mode is configured incorrectly\n"); return -EINVAL; } if ((chip_info->rx_lev_trig < SSP_RX_1_OR_MORE_ELEM) || (chip_info->rx_lev_trig > SSP_RX_32_OR_MORE_ELEM)) { dev_err(&pl022->adev->dev, "RX FIFO Trigger Level is configured incorrectly\n"); return -EINVAL; } if ((chip_info->tx_lev_trig < SSP_TX_1_OR_MORE_EMPTY_LOC) || (chip_info->tx_lev_trig > SSP_TX_32_OR_MORE_EMPTY_LOC)) { dev_err(&pl022->adev->dev, "TX FIFO Trigger Level is configured incorrectly\n"); return -EINVAL; } if (chip_info->iface == SSP_INTERFACE_NATIONAL_MICROWIRE) { if ((chip_info->ctrl_len < SSP_BITS_4) || (chip_info->ctrl_len > SSP_BITS_32)) { dev_err(&pl022->adev->dev, "CTRL LEN is configured incorrectly\n"); return -EINVAL; } if ((chip_info->wait_state != SSP_MWIRE_WAIT_ZERO) && (chip_info->wait_state != SSP_MWIRE_WAIT_ONE)) { dev_err(&pl022->adev->dev, "Wait State is configured incorrectly\n"); return -EINVAL; } /* Half duplex is only available in the ST Micro version */ if (pl022->vendor->extended_cr) { if ((chip_info->duplex != SSP_MICROWIRE_CHANNEL_FULL_DUPLEX) && (chip_info->duplex != SSP_MICROWIRE_CHANNEL_HALF_DUPLEX)) { dev_err(&pl022->adev->dev, "Microwire duplex mode is configured incorrectly\n"); return -EINVAL; } } else { if (chip_info->duplex != SSP_MICROWIRE_CHANNEL_FULL_DUPLEX) dev_err(&pl022->adev->dev, "Microwire half duplex mode requested," " but this is only available in the" " ST version of PL022\n"); return -EINVAL; } } return 0; } /** * pl022_transfer - transfer function registered to SPI master framework * @spi: spi device which is requesting transfer * @msg: spi message which is to handled is queued to driver queue * * This function is registered to the SPI framework for this SPI master * controller. It will queue the spi_message in the queue of driver if * the queue is not stopped and return. */ static int pl022_transfer(struct spi_device *spi, struct spi_message *msg) { struct pl022 *pl022 = spi_master_get_devdata(spi->master); unsigned long flags; spin_lock_irqsave(&pl022->queue_lock, flags); if (!pl022->running) { spin_unlock_irqrestore(&pl022->queue_lock, flags); return -ESHUTDOWN; } msg->actual_length = 0; msg->status = -EINPROGRESS; msg->state = STATE_START; list_add_tail(&msg->queue, &pl022->queue); if (pl022->running && !pl022->busy) queue_work(pl022->workqueue, &pl022->pump_messages); spin_unlock_irqrestore(&pl022->queue_lock, flags); return 0; } static int calculate_effective_freq(struct pl022 *pl022, int freq, struct ssp_clock_params *clk_freq) { /* Lets calculate the frequency parameters */ u16 cpsdvsr = 2; u16 scr = 0; bool freq_found = false; u32 rate; u32 max_tclk; u32 min_tclk; rate = clk_get_rate(pl022->clk); /* cpsdvscr = 2 & scr 0 */ max_tclk = (rate / (CPSDVR_MIN * (1 + SCR_MIN))); /* cpsdvsr = 254 & scr = 255 */ min_tclk = (rate / (CPSDVR_MAX * (1 + SCR_MAX))); if ((freq <= max_tclk) && (freq >= min_tclk)) { while (cpsdvsr <= CPSDVR_MAX && !freq_found) { while (scr <= SCR_MAX && !freq_found) { if ((rate / (cpsdvsr * (1 + scr))) > freq) scr += 1; else { /* * This bool is made true when * effective frequency >= * target frequency is found */ freq_found = true; if ((rate / (cpsdvsr * (1 + scr))) != freq) { if (scr == SCR_MIN) { cpsdvsr -= 2; scr = SCR_MAX; } else scr -= 1; } } } if (!freq_found) { cpsdvsr += 2; scr = SCR_MIN; } } if (cpsdvsr != 0) { dev_dbg(&pl022->adev->dev, "SSP Effective Frequency is %u\n", (rate / (cpsdvsr * (1 + scr)))); clk_freq->cpsdvsr = (u8) (cpsdvsr & 0xFF); clk_freq->scr = (u8) (scr & 0xFF); dev_dbg(&pl022->adev->dev, "SSP cpsdvsr = %d, scr = %d\n", clk_freq->cpsdvsr, clk_freq->scr); } } else { dev_err(&pl022->adev->dev, "controller data is incorrect: out of range frequency"); return -EINVAL; } return 0; } /* * A piece of default chip info unless the platform * supplies it. */ static const struct pl022_config_chip pl022_default_chip_info = { .com_mode = POLLING_TRANSFER, .iface = SSP_INTERFACE_MOTOROLA_SPI, .hierarchy = SSP_SLAVE, .slave_tx_disable = DO_NOT_DRIVE_TX, .rx_lev_trig = SSP_RX_1_OR_MORE_ELEM, .tx_lev_trig = SSP_TX_1_OR_MORE_EMPTY_LOC, .ctrl_len = SSP_BITS_8, .wait_state = SSP_MWIRE_WAIT_ZERO, .duplex = SSP_MICROWIRE_CHANNEL_FULL_DUPLEX, .cs_control = null_cs_control, }; /** * pl022_setup - setup function registered to SPI master framework * @spi: spi device which is requesting setup * * This function is registered to the SPI framework for this SPI master * controller. If it is the first time when setup is called by this device, * this function will initialize the runtime state for this chip and save * the same in the device structure. Else it will update the runtime info * with the updated chip info. Nothing is really being written to the * controller hardware here, that is not done until the actual transfer * commence. */ static int pl022_setup(struct spi_device *spi) { struct pl022_config_chip const *chip_info; struct chip_data *chip; struct ssp_clock_params clk_freq = {0, }; int status = 0; struct pl022 *pl022 = spi_master_get_devdata(spi->master); unsigned int bits = spi->bits_per_word; u32 tmp; if (!spi->max_speed_hz) return -EINVAL; /* Get controller_state if one is supplied */ chip = spi_get_ctldata(spi); if (chip == NULL) { chip = kzalloc(sizeof(struct chip_data), GFP_KERNEL); if (!chip) { dev_err(&spi->dev, "cannot allocate controller state\n"); return -ENOMEM; } dev_dbg(&spi->dev, "allocated memory for controller's runtime state\n"); } /* Get controller data if one is supplied */ chip_info = spi->controller_data; if (chip_info == NULL) { chip_info = &pl022_default_chip_info; /* spi_board_info.controller_data not is supplied */ dev_dbg(&spi->dev, "using default controller_data settings\n"); } else dev_dbg(&spi->dev, "using user supplied controller_data settings\n"); /* * We can override with custom divisors, else we use the board * frequency setting */ if ((0 == chip_info->clk_freq.cpsdvsr) && (0 == chip_info->clk_freq.scr)) { status = calculate_effective_freq(pl022, spi->max_speed_hz, &clk_freq); if (status < 0) goto err_config_params; } else { memcpy(&clk_freq, &chip_info->clk_freq, sizeof(clk_freq)); if ((clk_freq.cpsdvsr % 2) != 0) clk_freq.cpsdvsr = clk_freq.cpsdvsr - 1; } if ((clk_freq.cpsdvsr < CPSDVR_MIN) || (clk_freq.cpsdvsr > CPSDVR_MAX)) { status = -EINVAL; dev_err(&spi->dev, "cpsdvsr is configured incorrectly\n"); goto err_config_params; } status = verify_controller_parameters(pl022, chip_info); if (status) { dev_err(&spi->dev, "controller data is incorrect"); goto err_config_params; } /* Now set controller state based on controller data */ chip->xfer_type = chip_info->com_mode; if (!chip_info->cs_control) { chip->cs_control = null_cs_control; dev_warn(&spi->dev, "chip select function is NULL for this chip\n"); } else chip->cs_control = chip_info->cs_control; if (bits <= 3) { /* PL022 doesn't support less than 4-bits */ status = -ENOTSUPP; goto err_config_params; } else if (bits <= 8) { dev_dbg(&spi->dev, "4 <= n <=8 bits per word\n"); chip->n_bytes = 1; chip->read = READING_U8; chip->write = WRITING_U8; } else if (bits <= 16) { dev_dbg(&spi->dev, "9 <= n <= 16 bits per word\n"); chip->n_bytes = 2; chip->read = READING_U16; chip->write = WRITING_U16; } else { if (pl022->vendor->max_bpw >= 32) { dev_dbg(&spi->dev, "17 <= n <= 32 bits per word\n"); chip->n_bytes = 4; chip->read = READING_U32; chip->write = WRITING_U32; } else { dev_err(&spi->dev, "illegal data size for this controller!\n"); dev_err(&spi->dev, "a standard pl022 can only handle " "1 <= n <= 16 bit words\n"); status = -ENOTSUPP; goto err_config_params; } } /* Now Initialize all register settings required for this chip */ chip->cr0 = 0; chip->cr1 = 0; chip->dmacr = 0; chip->cpsr = 0; if ((chip_info->com_mode == DMA_TRANSFER) && ((pl022->master_info)->enable_dma)) { chip->enable_dma = true; dev_dbg(&spi->dev, "DMA mode set in controller state\n"); SSP_WRITE_BITS(chip->dmacr, SSP_DMA_ENABLED, SSP_DMACR_MASK_RXDMAE, 0); SSP_WRITE_BITS(chip->dmacr, SSP_DMA_ENABLED, SSP_DMACR_MASK_TXDMAE, 1); } else { chip->enable_dma = false; dev_dbg(&spi->dev, "DMA mode NOT set in controller state\n"); SSP_WRITE_BITS(chip->dmacr, SSP_DMA_DISABLED, SSP_DMACR_MASK_RXDMAE, 0); SSP_WRITE_BITS(chip->dmacr, SSP_DMA_DISABLED, SSP_DMACR_MASK_TXDMAE, 1); } chip->cpsr = clk_freq.cpsdvsr; /* Special setup for the ST micro extended control registers */ if (pl022->vendor->extended_cr) { u32 etx; if (pl022->vendor->pl023) { /* These bits are only in the PL023 */ SSP_WRITE_BITS(chip->cr1, chip_info->clkdelay, SSP_CR1_MASK_FBCLKDEL_ST, 13); } else { /* These bits are in the PL022 but not PL023 */ SSP_WRITE_BITS(chip->cr0, chip_info->duplex, SSP_CR0_MASK_HALFDUP_ST, 5); SSP_WRITE_BITS(chip->cr0, chip_info->ctrl_len, SSP_CR0_MASK_CSS_ST, 16); SSP_WRITE_BITS(chip->cr0, chip_info->iface, SSP_CR0_MASK_FRF_ST, 21); SSP_WRITE_BITS(chip->cr1, chip_info->wait_state, SSP_CR1_MASK_MWAIT_ST, 6); } SSP_WRITE_BITS(chip->cr0, bits - 1, SSP_CR0_MASK_DSS_ST, 0); if (spi->mode & SPI_LSB_FIRST) { tmp = SSP_RX_LSB; etx = SSP_TX_LSB; } else { tmp = SSP_RX_MSB; etx = SSP_TX_MSB; } SSP_WRITE_BITS(chip->cr1, tmp, SSP_CR1_MASK_RENDN_ST, 4); SSP_WRITE_BITS(chip->cr1, etx, SSP_CR1_MASK_TENDN_ST, 5); SSP_WRITE_BITS(chip->cr1, chip_info->rx_lev_trig, SSP_CR1_MASK_RXIFLSEL_ST, 7); SSP_WRITE_BITS(chip->cr1, chip_info->tx_lev_trig, SSP_CR1_MASK_TXIFLSEL_ST, 10); } else { SSP_WRITE_BITS(chip->cr0, bits - 1, SSP_CR0_MASK_DSS, 0); SSP_WRITE_BITS(chip->cr0, chip_info->iface, SSP_CR0_MASK_FRF, 4); } /* Stuff that is common for all versions */ if (spi->mode & SPI_CPOL) tmp = SSP_CLK_POL_IDLE_HIGH; else tmp = SSP_CLK_POL_IDLE_LOW; SSP_WRITE_BITS(chip->cr0, tmp, SSP_CR0_MASK_SPO, 6); if (spi->mode & SPI_CPHA) tmp = SSP_CLK_SECOND_EDGE; else tmp = SSP_CLK_FIRST_EDGE; SSP_WRITE_BITS(chip->cr0, tmp, SSP_CR0_MASK_SPH, 7); SSP_WRITE_BITS(chip->cr0, clk_freq.scr, SSP_CR0_MASK_SCR, 8); /* Loopback is available on all versions except PL023 */ if (pl022->vendor->loopback) { if (spi->mode & SPI_LOOP) tmp = LOOPBACK_ENABLED; else tmp = LOOPBACK_DISABLED; SSP_WRITE_BITS(chip->cr1, tmp, SSP_CR1_MASK_LBM, 0); } SSP_WRITE_BITS(chip->cr1, SSP_DISABLED, SSP_CR1_MASK_SSE, 1); SSP_WRITE_BITS(chip->cr1, chip_info->hierarchy, SSP_CR1_MASK_MS, 2); SSP_WRITE_BITS(chip->cr1, chip_info->slave_tx_disable, SSP_CR1_MASK_SOD, 3); /* Save controller_state */ spi_set_ctldata(spi, chip); return status; err_config_params: spi_set_ctldata(spi, NULL); kfree(chip); return status; } /** * pl022_cleanup - cleanup function registered to SPI master framework * @spi: spi device which is requesting cleanup * * This function is registered to the SPI framework for this SPI master * controller. It will free the runtime state of chip. */ static void pl022_cleanup(struct spi_device *spi) { struct chip_data *chip = spi_get_ctldata(spi); spi_set_ctldata(spi, NULL); kfree(chip); } static int __devinit pl022_probe(struct amba_device *adev, const struct amba_id *id) { struct device *dev = &adev->dev; struct pl022_ssp_controller *platform_info = adev->dev.platform_data; struct spi_master *master; struct pl022 *pl022 = NULL; /*Data for this driver */ int status = 0; dev_info(&adev->dev, "ARM PL022 driver, device ID: 0x%08x\n", adev->periphid); if (platform_info == NULL) { dev_err(&adev->dev, "probe - no platform data supplied\n"); status = -ENODEV; goto err_no_pdata; } /* Allocate master with space for data */ master = spi_alloc_master(dev, sizeof(struct pl022)); if (master == NULL) { dev_err(&adev->dev, "probe - cannot alloc SPI master\n"); status = -ENOMEM; goto err_no_master; } pl022 = spi_master_get_devdata(master); pl022->master = master; pl022->master_info = platform_info; pl022->adev = adev; pl022->vendor = id->data; /* * Bus Number Which has been Assigned to this SSP controller * on this board */ master->bus_num = platform_info->bus_id; master->num_chipselect = platform_info->num_chipselect; master->cleanup = pl022_cleanup; master->setup = pl022_setup; master->transfer = pl022_transfer; /* * Supports mode 0-3, loopback, and active low CS. Transfers are * always MS bit first on the original pl022. */ master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH | SPI_LOOP; if (pl022->vendor->extended_cr) master->mode_bits |= SPI_LSB_FIRST; dev_dbg(&adev->dev, "BUSNO: %d\n", master->bus_num); status = amba_request_regions(adev, NULL); if (status) goto err_no_ioregion; pl022->phybase = adev->res.start; pl022->virtbase = ioremap(adev->res.start, resource_size(&adev->res)); if (pl022->virtbase == NULL) { status = -ENOMEM; goto err_no_ioremap; } printk(KERN_INFO "pl022: mapped registers from 0x%08x to %p\n", adev->res.start, pl022->virtbase); pl022->clk = clk_get(&adev->dev, NULL); if (IS_ERR(pl022->clk)) { status = PTR_ERR(pl022->clk); dev_err(&adev->dev, "could not retrieve SSP/SPI bus clock\n"); goto err_no_clk; } /* Disable SSP */ writew((readw(SSP_CR1(pl022->virtbase)) & (~SSP_CR1_MASK_SSE)), SSP_CR1(pl022->virtbase)); load_ssp_default_config(pl022); status = request_irq(adev->irq[0], pl022_interrupt_handler, 0, "pl022", pl022); if (status < 0) { dev_err(&adev->dev, "probe - cannot get IRQ (%d)\n", status); goto err_no_irq; } /* Get DMA channels */ if (platform_info->enable_dma) { status = pl022_dma_probe(pl022); if (status != 0) platform_info->enable_dma = 0; } /* Initialize and start queue */ status = init_queue(pl022); if (status != 0) { dev_err(&adev->dev, "probe - problem initializing queue\n"); goto err_init_queue; } status = start_queue(pl022); if (status != 0) { dev_err(&adev->dev, "probe - problem starting queue\n"); goto err_start_queue; } /* Register with the SPI framework */ amba_set_drvdata(adev, pl022); status = spi_register_master(master); if (status != 0) { dev_err(&adev->dev, "probe - problem registering spi master\n"); goto err_spi_register; } dev_dbg(dev, "probe succeeded\n"); /* * Disable the silicon block pclk and any voltage domain and just * power it up and clock it when it's needed */ amba_pclk_disable(adev); amba_vcore_disable(adev); return 0; err_spi_register: err_start_queue: err_init_queue: destroy_queue(pl022); pl022_dma_remove(pl022); free_irq(adev->irq[0], pl022); err_no_irq: clk_put(pl022->clk); err_no_clk: iounmap(pl022->virtbase); err_no_ioremap: amba_release_regions(adev); err_no_ioregion: spi_master_put(master); err_no_master: err_no_pdata: return status; } static int __devexit pl022_remove(struct amba_device *adev) { struct pl022 *pl022 = amba_get_drvdata(adev); int status = 0; if (!pl022) return 0; /* Remove the queue */ status = destroy_queue(pl022); if (status != 0) { dev_err(&adev->dev, "queue remove failed (%d)\n", status); return status; } load_ssp_default_config(pl022); pl022_dma_remove(pl022); free_irq(adev->irq[0], pl022); clk_disable(pl022->clk); clk_put(pl022->clk); iounmap(pl022->virtbase); amba_release_regions(adev); tasklet_disable(&pl022->pump_transfers); spi_unregister_master(pl022->master); spi_master_put(pl022->master); amba_set_drvdata(adev, NULL); dev_dbg(&adev->dev, "remove succeeded\n"); return 0; } #ifdef CONFIG_PM static int pl022_suspend(struct amba_device *adev, pm_message_t state) { struct pl022 *pl022 = amba_get_drvdata(adev); int status = 0; status = stop_queue(pl022); if (status) { dev_warn(&adev->dev, "suspend cannot stop queue\n"); return status; } amba_vcore_enable(adev); amba_pclk_enable(adev); load_ssp_default_config(pl022); amba_pclk_disable(adev); amba_vcore_disable(adev); dev_dbg(&adev->dev, "suspended\n"); return 0; } static int pl022_resume(struct amba_device *adev) { struct pl022 *pl022 = amba_get_drvdata(adev); int status = 0; /* Start the queue running */ status = start_queue(pl022); if (status) dev_err(&adev->dev, "problem starting queue (%d)\n", status); else dev_dbg(&adev->dev, "resumed\n"); return status; } #else #define pl022_suspend NULL #define pl022_resume NULL #endif /* CONFIG_PM */ static struct vendor_data vendor_arm = { .fifodepth = 8, .max_bpw = 16, .unidir = false, .extended_cr = false, .pl023 = false, .loopback = true, }; static struct vendor_data vendor_st = { .fifodepth = 32, .max_bpw = 32, .unidir = false, .extended_cr = true, .pl023 = false, .loopback = true, }; static struct vendor_data vendor_st_pl023 = { .fifodepth = 32, .max_bpw = 32, .unidir = false, .extended_cr = true, .pl023 = true, .loopback = false, }; static struct vendor_data vendor_db5500_pl023 = { .fifodepth = 32, .max_bpw = 32, .unidir = false, .extended_cr = true, .pl023 = true, .loopback = true, }; static struct amba_id pl022_ids[] = { { /* * ARM PL022 variant, this has a 16bit wide * and 8 locations deep TX/RX FIFO */ .id = 0x00041022, .mask = 0x000fffff, .data = &vendor_arm, }, { /* * ST Micro derivative, this has 32bit wide * and 32 locations deep TX/RX FIFO */ .id = 0x01080022, .mask = 0xffffffff, .data = &vendor_st, }, { /* * ST-Ericsson derivative "PL023" (this is not * an official ARM number), this is a PL022 SSP block * stripped to SPI mode only, it has 32bit wide * and 32 locations deep TX/RX FIFO but no extended * CR0/CR1 register */ .id = 0x00080023, .mask = 0xffffffff, .data = &vendor_st_pl023, }, { .id = 0x10080023, .mask = 0xffffffff, .data = &vendor_db5500_pl023, }, { 0, 0 }, }; static struct amba_driver pl022_driver = { .drv = { .name = "ssp-pl022", }, .id_table = pl022_ids, .probe = pl022_probe, .remove = __devexit_p(pl022_remove), .suspend = pl022_suspend, .resume = pl022_resume, }; static int __init pl022_init(void) { return amba_driver_register(&pl022_driver); } subsys_initcall(pl022_init); static void __exit pl022_exit(void) { amba_driver_unregister(&pl022_driver); } module_exit(pl022_exit); MODULE_AUTHOR("Linus Walleij <linus.walleij@stericsson.com>"); MODULE_DESCRIPTION("PL022 SSP Controller Driver"); MODULE_LICENSE("GPL");
gpl-2.0
Zenfone2-Dev/Kernel-for-Asus-Zenfone-2
drivers/usb/atm/ueagle-atm.c
2520
70307
/*- * Copyright (c) 2003, 2004 * Damien Bergamini <damien.bergamini@free.fr>. All rights reserved. * * Copyright (c) 2005-2007 Matthieu Castet <castet.matthieu@free.fr> * Copyright (c) 2005-2007 Stanislaw Gruszka <stf_xl@wp.pl> * * 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 * BSD license below: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice unmodified, this list of conditions, and the following * disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * GPL license : * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * HISTORY : some part of the code was base on ueagle 1.3 BSD driver, * Damien Bergamini agree to put his code under a DUAL GPL/BSD license. * * The rest of the code was was rewritten from scratch. */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/crc32.h> #include <linux/usb.h> #include <linux/firmware.h> #include <linux/ctype.h> #include <linux/sched.h> #include <linux/kthread.h> #include <linux/mutex.h> #include <linux/freezer.h> #include <linux/slab.h> #include <linux/kernel.h> #include <asm/unaligned.h> #include "usbatm.h" #define EAGLEUSBVERSION "ueagle 1.4" /* * Debug macros */ #define uea_dbg(usb_dev, format, args...) \ do { \ if (debug >= 1) \ dev_dbg(&(usb_dev)->dev, \ "[ueagle-atm dbg] %s: " format, \ __func__, ##args); \ } while (0) #define uea_vdbg(usb_dev, format, args...) \ do { \ if (debug >= 2) \ dev_dbg(&(usb_dev)->dev, \ "[ueagle-atm vdbg] " format, ##args); \ } while (0) #define uea_enters(usb_dev) \ uea_vdbg(usb_dev, "entering %s\n" , __func__) #define uea_leaves(usb_dev) \ uea_vdbg(usb_dev, "leaving %s\n" , __func__) #define uea_err(usb_dev, format, args...) \ dev_err(&(usb_dev)->dev , "[UEAGLE-ATM] " format , ##args) #define uea_warn(usb_dev, format, args...) \ dev_warn(&(usb_dev)->dev , "[Ueagle-atm] " format, ##args) #define uea_info(usb_dev, format, args...) \ dev_info(&(usb_dev)->dev , "[ueagle-atm] " format, ##args) struct intr_pkt; /* cmv's from firmware */ struct uea_cmvs_v1 { u32 address; u16 offset; u32 data; } __packed; struct uea_cmvs_v2 { u32 group; u32 address; u32 offset; u32 data; } __packed; /* information about currently processed cmv */ struct cmv_dsc_e1 { u8 function; u16 idx; u32 address; u16 offset; }; struct cmv_dsc_e4 { u16 function; u16 offset; u16 address; u16 group; }; union cmv_dsc { struct cmv_dsc_e1 e1; struct cmv_dsc_e4 e4; }; struct uea_softc { struct usb_device *usb_dev; struct usbatm_data *usbatm; int modem_index; unsigned int driver_info; int annex; #define ANNEXA 0 #define ANNEXB 1 int booting; int reset; wait_queue_head_t sync_q; struct task_struct *kthread; u32 data; u32 data1; int cmv_ack; union cmv_dsc cmv_dsc; struct work_struct task; u16 pageno; u16 ovl; const struct firmware *dsp_firm; struct urb *urb_int; void (*dispatch_cmv) (struct uea_softc *, struct intr_pkt *); void (*schedule_load_page) (struct uea_softc *, struct intr_pkt *); int (*stat) (struct uea_softc *); int (*send_cmvs) (struct uea_softc *); /* keep in sync with eaglectl */ struct uea_stats { struct { u32 state; u32 flags; u32 mflags; u32 vidcpe; u32 vidco; u32 dsrate; u32 usrate; u32 dsunc; u32 usunc; u32 dscorr; u32 uscorr; u32 txflow; u32 rxflow; u32 usattenuation; u32 dsattenuation; u32 dsmargin; u32 usmargin; u32 firmid; } phy; } stats; }; /* * Elsa IDs */ #define ELSA_VID 0x05CC #define ELSA_PID_PSTFIRM 0x3350 #define ELSA_PID_PREFIRM 0x3351 #define ELSA_PID_A_PREFIRM 0x3352 #define ELSA_PID_A_PSTFIRM 0x3353 #define ELSA_PID_B_PREFIRM 0x3362 #define ELSA_PID_B_PSTFIRM 0x3363 /* * Devolo IDs : pots if (pid & 0x10) */ #define DEVOLO_VID 0x1039 #define DEVOLO_EAGLE_I_A_PID_PSTFIRM 0x2110 #define DEVOLO_EAGLE_I_A_PID_PREFIRM 0x2111 #define DEVOLO_EAGLE_I_B_PID_PSTFIRM 0x2100 #define DEVOLO_EAGLE_I_B_PID_PREFIRM 0x2101 #define DEVOLO_EAGLE_II_A_PID_PSTFIRM 0x2130 #define DEVOLO_EAGLE_II_A_PID_PREFIRM 0x2131 #define DEVOLO_EAGLE_II_B_PID_PSTFIRM 0x2120 #define DEVOLO_EAGLE_II_B_PID_PREFIRM 0x2121 /* * Reference design USB IDs */ #define ANALOG_VID 0x1110 #define ADI930_PID_PREFIRM 0x9001 #define ADI930_PID_PSTFIRM 0x9000 #define EAGLE_I_PID_PREFIRM 0x9010 /* Eagle I */ #define EAGLE_I_PID_PSTFIRM 0x900F /* Eagle I */ #define EAGLE_IIC_PID_PREFIRM 0x9024 /* Eagle IIC */ #define EAGLE_IIC_PID_PSTFIRM 0x9023 /* Eagle IIC */ #define EAGLE_II_PID_PREFIRM 0x9022 /* Eagle II */ #define EAGLE_II_PID_PSTFIRM 0x9021 /* Eagle II */ #define EAGLE_III_PID_PREFIRM 0x9032 /* Eagle III */ #define EAGLE_III_PID_PSTFIRM 0x9031 /* Eagle III */ #define EAGLE_IV_PID_PREFIRM 0x9042 /* Eagle IV */ #define EAGLE_IV_PID_PSTFIRM 0x9041 /* Eagle IV */ /* * USR USB IDs */ #define USR_VID 0x0BAF #define MILLER_A_PID_PREFIRM 0x00F2 #define MILLER_A_PID_PSTFIRM 0x00F1 #define MILLER_B_PID_PREFIRM 0x00FA #define MILLER_B_PID_PSTFIRM 0x00F9 #define HEINEKEN_A_PID_PREFIRM 0x00F6 #define HEINEKEN_A_PID_PSTFIRM 0x00F5 #define HEINEKEN_B_PID_PREFIRM 0x00F8 #define HEINEKEN_B_PID_PSTFIRM 0x00F7 #define PREFIRM 0 #define PSTFIRM (1<<7) #define AUTO_ANNEX_A (1<<8) #define AUTO_ANNEX_B (1<<9) enum { ADI930 = 0, EAGLE_I, EAGLE_II, EAGLE_III, EAGLE_IV }; /* macros for both struct usb_device_id and struct uea_softc */ #define UEA_IS_PREFIRM(x) \ (!((x)->driver_info & PSTFIRM)) #define UEA_CHIP_VERSION(x) \ ((x)->driver_info & 0xf) #define IS_ISDN(x) \ ((x)->annex & ANNEXB) #define INS_TO_USBDEV(ins) (ins->usb_dev) #define GET_STATUS(data) \ ((data >> 8) & 0xf) #define IS_OPERATIONAL(sc) \ ((UEA_CHIP_VERSION(sc) != EAGLE_IV) ? \ (GET_STATUS(sc->stats.phy.state) == 2) : \ (sc->stats.phy.state == 7)) /* * Set of macros to handle unaligned data in the firmware blob. * The FW_GET_BYTE() macro is provided only for consistency. */ #define FW_GET_BYTE(p) (*((__u8 *) (p))) #define FW_DIR "ueagle-atm/" #define EAGLE_FIRMWARE FW_DIR "eagle.fw" #define ADI930_FIRMWARE FW_DIR "adi930.fw" #define EAGLE_I_FIRMWARE FW_DIR "eagleI.fw" #define EAGLE_II_FIRMWARE FW_DIR "eagleII.fw" #define EAGLE_III_FIRMWARE FW_DIR "eagleIII.fw" #define EAGLE_IV_FIRMWARE FW_DIR "eagleIV.fw" #define DSP4I_FIRMWARE FW_DIR "DSP4i.bin" #define DSP4P_FIRMWARE FW_DIR "DSP4p.bin" #define DSP9I_FIRMWARE FW_DIR "DSP9i.bin" #define DSP9P_FIRMWARE FW_DIR "DSP9p.bin" #define DSPEI_FIRMWARE FW_DIR "DSPei.bin" #define DSPEP_FIRMWARE FW_DIR "DSPep.bin" #define FPGA930_FIRMWARE FW_DIR "930-fpga.bin" #define CMV4P_FIRMWARE FW_DIR "CMV4p.bin" #define CMV4PV2_FIRMWARE FW_DIR "CMV4p.bin.v2" #define CMV4I_FIRMWARE FW_DIR "CMV4i.bin" #define CMV4IV2_FIRMWARE FW_DIR "CMV4i.bin.v2" #define CMV9P_FIRMWARE FW_DIR "CMV9p.bin" #define CMV9PV2_FIRMWARE FW_DIR "CMV9p.bin.v2" #define CMV9I_FIRMWARE FW_DIR "CMV9i.bin" #define CMV9IV2_FIRMWARE FW_DIR "CMV9i.bin.v2" #define CMVEP_FIRMWARE FW_DIR "CMVep.bin" #define CMVEPV2_FIRMWARE FW_DIR "CMVep.bin.v2" #define CMVEI_FIRMWARE FW_DIR "CMVei.bin" #define CMVEIV2_FIRMWARE FW_DIR "CMVei.bin.v2" #define UEA_FW_NAME_MAX 30 #define NB_MODEM 4 #define BULK_TIMEOUT 300 #define CTRL_TIMEOUT 1000 #define ACK_TIMEOUT msecs_to_jiffies(3000) #define UEA_INTR_IFACE_NO 0 #define UEA_US_IFACE_NO 1 #define UEA_DS_IFACE_NO 2 #define FASTEST_ISO_INTF 8 #define UEA_BULK_DATA_PIPE 0x02 #define UEA_IDMA_PIPE 0x04 #define UEA_INTR_PIPE 0x04 #define UEA_ISO_DATA_PIPE 0x08 #define UEA_E1_SET_BLOCK 0x0001 #define UEA_E4_SET_BLOCK 0x002c #define UEA_SET_MODE 0x0003 #define UEA_SET_2183_DATA 0x0004 #define UEA_SET_TIMEOUT 0x0011 #define UEA_LOOPBACK_OFF 0x0002 #define UEA_LOOPBACK_ON 0x0003 #define UEA_BOOT_IDMA 0x0006 #define UEA_START_RESET 0x0007 #define UEA_END_RESET 0x0008 #define UEA_SWAP_MAILBOX (0x3fcd | 0x4000) #define UEA_MPTX_START (0x3fce | 0x4000) #define UEA_MPTX_MAILBOX (0x3fd6 | 0x4000) #define UEA_MPRX_MAILBOX (0x3fdf | 0x4000) /* block information in eagle4 dsp firmware */ struct block_index { __le32 PageOffset; __le32 NotLastBlock; __le32 dummy; __le32 PageSize; __le32 PageAddress; __le16 dummy1; __le16 PageNumber; } __packed; #define E4_IS_BOOT_PAGE(PageSize) ((le32_to_cpu(PageSize)) & 0x80000000) #define E4_PAGE_BYTES(PageSize) ((le32_to_cpu(PageSize) & 0x7fffffff) * 4) #define E4_L1_STRING_HEADER 0x10 #define E4_MAX_PAGE_NUMBER 0x58 #define E4_NO_SWAPPAGE_HEADERS 0x31 /* l1_code is eagle4 dsp firmware format */ struct l1_code { u8 string_header[E4_L1_STRING_HEADER]; u8 page_number_to_block_index[E4_MAX_PAGE_NUMBER]; struct block_index page_header[E4_NO_SWAPPAGE_HEADERS]; u8 code[0]; } __packed; /* structures describing a block within a DSP page */ struct block_info_e1 { __le16 wHdr; __le16 wAddress; __le16 wSize; __le16 wOvlOffset; __le16 wOvl; /* overlay */ __le16 wLast; } __packed; #define E1_BLOCK_INFO_SIZE 12 struct block_info_e4 { __be16 wHdr; __u8 bBootPage; __u8 bPageNumber; __be32 dwSize; __be32 dwAddress; __be16 wReserved; } __packed; #define E4_BLOCK_INFO_SIZE 14 #define UEA_BIHDR 0xabcd #define UEA_RESERVED 0xffff /* constants describing cmv type */ #define E1_PREAMBLE 0x535c #define E1_MODEMTOHOST 0x01 #define E1_HOSTTOMODEM 0x10 #define E1_MEMACCESS 0x1 #define E1_ADSLDIRECTIVE 0x7 #define E1_FUNCTION_TYPE(f) ((f) >> 4) #define E1_FUNCTION_SUBTYPE(f) ((f) & 0x0f) #define E4_MEMACCESS 0 #define E4_ADSLDIRECTIVE 0xf #define E4_FUNCTION_TYPE(f) ((f) >> 8) #define E4_FUNCTION_SIZE(f) ((f) & 0x0f) #define E4_FUNCTION_SUBTYPE(f) (((f) >> 4) & 0x0f) /* for MEMACCESS */ #define E1_REQUESTREAD 0x0 #define E1_REQUESTWRITE 0x1 #define E1_REPLYREAD 0x2 #define E1_REPLYWRITE 0x3 #define E4_REQUESTREAD 0x0 #define E4_REQUESTWRITE 0x4 #define E4_REPLYREAD (E4_REQUESTREAD | 1) #define E4_REPLYWRITE (E4_REQUESTWRITE | 1) /* for ADSLDIRECTIVE */ #define E1_KERNELREADY 0x0 #define E1_MODEMREADY 0x1 #define E4_KERNELREADY 0x0 #define E4_MODEMREADY 0x1 #define E1_MAKEFUNCTION(t, s) (((t) & 0xf) << 4 | ((s) & 0xf)) #define E4_MAKEFUNCTION(t, st, s) (((t) & 0xf) << 8 | \ ((st) & 0xf) << 4 | ((s) & 0xf)) #define E1_MAKESA(a, b, c, d) \ (((c) & 0xff) << 24 | \ ((d) & 0xff) << 16 | \ ((a) & 0xff) << 8 | \ ((b) & 0xff)) #define E1_GETSA1(a) ((a >> 8) & 0xff) #define E1_GETSA2(a) (a & 0xff) #define E1_GETSA3(a) ((a >> 24) & 0xff) #define E1_GETSA4(a) ((a >> 16) & 0xff) #define E1_SA_CNTL E1_MAKESA('C', 'N', 'T', 'L') #define E1_SA_DIAG E1_MAKESA('D', 'I', 'A', 'G') #define E1_SA_INFO E1_MAKESA('I', 'N', 'F', 'O') #define E1_SA_OPTN E1_MAKESA('O', 'P', 'T', 'N') #define E1_SA_RATE E1_MAKESA('R', 'A', 'T', 'E') #define E1_SA_STAT E1_MAKESA('S', 'T', 'A', 'T') #define E4_SA_CNTL 1 #define E4_SA_STAT 2 #define E4_SA_INFO 3 #define E4_SA_TEST 4 #define E4_SA_OPTN 5 #define E4_SA_RATE 6 #define E4_SA_DIAG 7 #define E4_SA_CNFG 8 /* structures representing a CMV (Configuration and Management Variable) */ struct cmv_e1 { __le16 wPreamble; __u8 bDirection; __u8 bFunction; __le16 wIndex; __le32 dwSymbolicAddress; __le16 wOffsetAddress; __le32 dwData; } __packed; struct cmv_e4 { __be16 wGroup; __be16 wFunction; __be16 wOffset; __be16 wAddress; __be32 dwData[6]; } __packed; /* structures representing swap information */ struct swap_info_e1 { __u8 bSwapPageNo; __u8 bOvl; /* overlay */ } __packed; struct swap_info_e4 { __u8 bSwapPageNo; } __packed; /* structures representing interrupt data */ #define e1_bSwapPageNo u.e1.s1.swapinfo.bSwapPageNo #define e1_bOvl u.e1.s1.swapinfo.bOvl #define e4_bSwapPageNo u.e4.s1.swapinfo.bSwapPageNo #define INT_LOADSWAPPAGE 0x0001 #define INT_INCOMINGCMV 0x0002 union intr_data_e1 { struct { struct swap_info_e1 swapinfo; __le16 wDataSize; } __packed s1; struct { struct cmv_e1 cmv; __le16 wDataSize; } __packed s2; } __packed; union intr_data_e4 { struct { struct swap_info_e4 swapinfo; __le16 wDataSize; } __packed s1; struct { struct cmv_e4 cmv; __le16 wDataSize; } __packed s2; } __packed; struct intr_pkt { __u8 bType; __u8 bNotification; __le16 wValue; __le16 wIndex; __le16 wLength; __le16 wInterrupt; union { union intr_data_e1 e1; union intr_data_e4 e4; } u; } __packed; #define E1_INTR_PKT_SIZE 28 #define E4_INTR_PKT_SIZE 64 static struct usb_driver uea_driver; static DEFINE_MUTEX(uea_mutex); static const char * const chip_name[] = { "ADI930", "Eagle I", "Eagle II", "Eagle III", "Eagle IV"}; static int modem_index; static unsigned int debug; static unsigned int altsetting[NB_MODEM] = { [0 ... (NB_MODEM - 1)] = FASTEST_ISO_INTF}; static bool sync_wait[NB_MODEM]; static char *cmv_file[NB_MODEM]; static int annex[NB_MODEM]; module_param(debug, uint, 0644); MODULE_PARM_DESC(debug, "module debug level (0=off,1=on,2=verbose)"); module_param_array(altsetting, uint, NULL, 0644); MODULE_PARM_DESC(altsetting, "alternate setting for incoming traffic: 0=bulk, " "1=isoc slowest, ... , 8=isoc fastest (default)"); module_param_array(sync_wait, bool, NULL, 0644); MODULE_PARM_DESC(sync_wait, "wait the synchronisation before starting ATM"); module_param_array(cmv_file, charp, NULL, 0644); MODULE_PARM_DESC(cmv_file, "file name with configuration and management variables"); module_param_array(annex, uint, NULL, 0644); MODULE_PARM_DESC(annex, "manually set annex a/b (0=auto, 1=annex a, 2=annex b)"); #define uea_wait(sc, cond, timeo) \ ({ \ int _r = wait_event_interruptible_timeout(sc->sync_q, \ (cond) || kthread_should_stop(), timeo); \ if (kthread_should_stop()) \ _r = -ENODEV; \ _r; \ }) #define UPDATE_ATM_STAT(type, val) \ do { \ if (sc->usbatm->atm_dev) \ sc->usbatm->atm_dev->type = val; \ } while (0) #define UPDATE_ATM_SIGNAL(val) \ do { \ if (sc->usbatm->atm_dev) \ atm_dev_signal_change(sc->usbatm->atm_dev, val); \ } while (0) /* Firmware loading */ #define LOAD_INTERNAL 0xA0 #define F8051_USBCS 0x7f92 /** * uea_send_modem_cmd - Send a command for pre-firmware devices. */ static int uea_send_modem_cmd(struct usb_device *usb, u16 addr, u16 size, const u8 *buff) { int ret = -ENOMEM; u8 *xfer_buff; xfer_buff = kmemdup(buff, size, GFP_KERNEL); if (xfer_buff) { ret = usb_control_msg(usb, usb_sndctrlpipe(usb, 0), LOAD_INTERNAL, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE, addr, 0, xfer_buff, size, CTRL_TIMEOUT); kfree(xfer_buff); } if (ret < 0) return ret; return (ret == size) ? 0 : -EIO; } static void uea_upload_pre_firmware(const struct firmware *fw_entry, void *context) { struct usb_device *usb = context; const u8 *pfw; u8 value; u32 crc = 0; int ret, size; uea_enters(usb); if (!fw_entry) { uea_err(usb, "firmware is not available\n"); goto err; } pfw = fw_entry->data; size = fw_entry->size; if (size < 4) goto err_fw_corrupted; crc = get_unaligned_le32(pfw); pfw += 4; size -= 4; if (crc32_be(0, pfw, size) != crc) goto err_fw_corrupted; /* * Start to upload firmware : send reset */ value = 1; ret = uea_send_modem_cmd(usb, F8051_USBCS, sizeof(value), &value); if (ret < 0) { uea_err(usb, "modem reset failed with error %d\n", ret); goto err; } while (size > 3) { u8 len = FW_GET_BYTE(pfw); u16 add = get_unaligned_le16(pfw + 1); size -= len + 3; if (size < 0) goto err_fw_corrupted; ret = uea_send_modem_cmd(usb, add, len, pfw + 3); if (ret < 0) { uea_err(usb, "uploading firmware data failed " "with error %d\n", ret); goto err; } pfw += len + 3; } if (size != 0) goto err_fw_corrupted; /* * Tell the modem we finish : de-assert reset */ value = 0; ret = uea_send_modem_cmd(usb, F8051_USBCS, 1, &value); if (ret < 0) uea_err(usb, "modem de-assert failed with error %d\n", ret); else uea_info(usb, "firmware uploaded\n"); goto err; err_fw_corrupted: uea_err(usb, "firmware is corrupted\n"); err: release_firmware(fw_entry); uea_leaves(usb); } /** * uea_load_firmware - Load usb firmware for pre-firmware devices. */ static int uea_load_firmware(struct usb_device *usb, unsigned int ver) { int ret; char *fw_name = EAGLE_FIRMWARE; uea_enters(usb); uea_info(usb, "pre-firmware device, uploading firmware\n"); switch (ver) { case ADI930: fw_name = ADI930_FIRMWARE; break; case EAGLE_I: fw_name = EAGLE_I_FIRMWARE; break; case EAGLE_II: fw_name = EAGLE_II_FIRMWARE; break; case EAGLE_III: fw_name = EAGLE_III_FIRMWARE; break; case EAGLE_IV: fw_name = EAGLE_IV_FIRMWARE; break; } ret = request_firmware_nowait(THIS_MODULE, 1, fw_name, &usb->dev, GFP_KERNEL, usb, uea_upload_pre_firmware); if (ret) uea_err(usb, "firmware %s is not available\n", fw_name); else uea_info(usb, "loading firmware %s\n", fw_name); uea_leaves(usb); return ret; } /* modem management : dsp firmware, send/read CMV, monitoring statistic */ /* * Make sure that the DSP code provided is safe to use. */ static int check_dsp_e1(const u8 *dsp, unsigned int len) { u8 pagecount, blockcount; u16 blocksize; u32 pageoffset; unsigned int i, j, p, pp; pagecount = FW_GET_BYTE(dsp); p = 1; /* enough space for page offsets? */ if (p + 4 * pagecount > len) return 1; for (i = 0; i < pagecount; i++) { pageoffset = get_unaligned_le32(dsp + p); p += 4; if (pageoffset == 0) continue; /* enough space for blockcount? */ if (pageoffset >= len) return 1; pp = pageoffset; blockcount = FW_GET_BYTE(dsp + pp); pp += 1; for (j = 0; j < blockcount; j++) { /* enough space for block header? */ if (pp + 4 > len) return 1; pp += 2; /* skip blockaddr */ blocksize = get_unaligned_le16(dsp + pp); pp += 2; /* enough space for block data? */ if (pp + blocksize > len) return 1; pp += blocksize; } } return 0; } static int check_dsp_e4(const u8 *dsp, int len) { int i; struct l1_code *p = (struct l1_code *) dsp; unsigned int sum = p->code - dsp; if (len < sum) return 1; if (strcmp("STRATIPHY ANEXA", p->string_header) != 0 && strcmp("STRATIPHY ANEXB", p->string_header) != 0) return 1; for (i = 0; i < E4_MAX_PAGE_NUMBER; i++) { struct block_index *blockidx; u8 blockno = p->page_number_to_block_index[i]; if (blockno >= E4_NO_SWAPPAGE_HEADERS) continue; do { u64 l; if (blockno >= E4_NO_SWAPPAGE_HEADERS) return 1; blockidx = &p->page_header[blockno++]; if ((u8 *)(blockidx + 1) - dsp >= len) return 1; if (le16_to_cpu(blockidx->PageNumber) != i) return 1; l = E4_PAGE_BYTES(blockidx->PageSize); sum += l; l += le32_to_cpu(blockidx->PageOffset); if (l > len) return 1; /* zero is zero regardless endianes */ } while (blockidx->NotLastBlock); } return (sum == len) ? 0 : 1; } /* * send data to the idma pipe * */ static int uea_idma_write(struct uea_softc *sc, const void *data, u32 size) { int ret = -ENOMEM; u8 *xfer_buff; int bytes_read; xfer_buff = kmemdup(data, size, GFP_KERNEL); if (!xfer_buff) { uea_err(INS_TO_USBDEV(sc), "can't allocate xfer_buff\n"); return ret; } ret = usb_bulk_msg(sc->usb_dev, usb_sndbulkpipe(sc->usb_dev, UEA_IDMA_PIPE), xfer_buff, size, &bytes_read, BULK_TIMEOUT); kfree(xfer_buff); if (ret < 0) return ret; if (size != bytes_read) { uea_err(INS_TO_USBDEV(sc), "size != bytes_read %d %d\n", size, bytes_read); return -EIO; } return 0; } static int request_dsp(struct uea_softc *sc) { int ret; char *dsp_name; if (UEA_CHIP_VERSION(sc) == EAGLE_IV) { if (IS_ISDN(sc)) dsp_name = DSP4I_FIRMWARE; else dsp_name = DSP4P_FIRMWARE; } else if (UEA_CHIP_VERSION(sc) == ADI930) { if (IS_ISDN(sc)) dsp_name = DSP9I_FIRMWARE; else dsp_name = DSP9P_FIRMWARE; } else { if (IS_ISDN(sc)) dsp_name = DSPEI_FIRMWARE; else dsp_name = DSPEP_FIRMWARE; } ret = request_firmware(&sc->dsp_firm, dsp_name, &sc->usb_dev->dev); if (ret < 0) { uea_err(INS_TO_USBDEV(sc), "requesting firmware %s failed with error %d\n", dsp_name, ret); return ret; } if (UEA_CHIP_VERSION(sc) == EAGLE_IV) ret = check_dsp_e4(sc->dsp_firm->data, sc->dsp_firm->size); else ret = check_dsp_e1(sc->dsp_firm->data, sc->dsp_firm->size); if (ret) { uea_err(INS_TO_USBDEV(sc), "firmware %s is corrupted\n", dsp_name); release_firmware(sc->dsp_firm); sc->dsp_firm = NULL; return -EILSEQ; } return 0; } /* * The uea_load_page() function must be called within a process context */ static void uea_load_page_e1(struct work_struct *work) { struct uea_softc *sc = container_of(work, struct uea_softc, task); u16 pageno = sc->pageno; u16 ovl = sc->ovl; struct block_info_e1 bi; const u8 *p; u8 pagecount, blockcount; u16 blockaddr, blocksize; u32 pageoffset; int i; /* reload firmware when reboot start and it's loaded already */ if (ovl == 0 && pageno == 0 && sc->dsp_firm) { release_firmware(sc->dsp_firm); sc->dsp_firm = NULL; } if (sc->dsp_firm == NULL && request_dsp(sc) < 0) return; p = sc->dsp_firm->data; pagecount = FW_GET_BYTE(p); p += 1; if (pageno >= pagecount) goto bad1; p += 4 * pageno; pageoffset = get_unaligned_le32(p); if (pageoffset == 0) goto bad1; p = sc->dsp_firm->data + pageoffset; blockcount = FW_GET_BYTE(p); p += 1; uea_dbg(INS_TO_USBDEV(sc), "sending %u blocks for DSP page %u\n", blockcount, pageno); bi.wHdr = cpu_to_le16(UEA_BIHDR); bi.wOvl = cpu_to_le16(ovl); bi.wOvlOffset = cpu_to_le16(ovl | 0x8000); for (i = 0; i < blockcount; i++) { blockaddr = get_unaligned_le16(p); p += 2; blocksize = get_unaligned_le16(p); p += 2; bi.wSize = cpu_to_le16(blocksize); bi.wAddress = cpu_to_le16(blockaddr); bi.wLast = cpu_to_le16((i == blockcount - 1) ? 1 : 0); /* send block info through the IDMA pipe */ if (uea_idma_write(sc, &bi, E1_BLOCK_INFO_SIZE)) goto bad2; /* send block data through the IDMA pipe */ if (uea_idma_write(sc, p, blocksize)) goto bad2; p += blocksize; } return; bad2: uea_err(INS_TO_USBDEV(sc), "sending DSP block %u failed\n", i); return; bad1: uea_err(INS_TO_USBDEV(sc), "invalid DSP page %u requested\n", pageno); } static void __uea_load_page_e4(struct uea_softc *sc, u8 pageno, int boot) { struct block_info_e4 bi; struct block_index *blockidx; struct l1_code *p = (struct l1_code *) sc->dsp_firm->data; u8 blockno = p->page_number_to_block_index[pageno]; bi.wHdr = cpu_to_be16(UEA_BIHDR); bi.bBootPage = boot; bi.bPageNumber = pageno; bi.wReserved = cpu_to_be16(UEA_RESERVED); do { const u8 *blockoffset; unsigned int blocksize; blockidx = &p->page_header[blockno]; blocksize = E4_PAGE_BYTES(blockidx->PageSize); blockoffset = sc->dsp_firm->data + le32_to_cpu( blockidx->PageOffset); bi.dwSize = cpu_to_be32(blocksize); bi.dwAddress = cpu_to_be32(le32_to_cpu(blockidx->PageAddress)); uea_dbg(INS_TO_USBDEV(sc), "sending block %u for DSP page " "%u size %u address %x\n", blockno, pageno, blocksize, le32_to_cpu(blockidx->PageAddress)); /* send block info through the IDMA pipe */ if (uea_idma_write(sc, &bi, E4_BLOCK_INFO_SIZE)) goto bad; /* send block data through the IDMA pipe */ if (uea_idma_write(sc, blockoffset, blocksize)) goto bad; blockno++; } while (blockidx->NotLastBlock); return; bad: uea_err(INS_TO_USBDEV(sc), "sending DSP block %u failed\n", blockno); return; } static void uea_load_page_e4(struct work_struct *work) { struct uea_softc *sc = container_of(work, struct uea_softc, task); u8 pageno = sc->pageno; int i; struct block_info_e4 bi; struct l1_code *p; uea_dbg(INS_TO_USBDEV(sc), "sending DSP page %u\n", pageno); /* reload firmware when reboot start and it's loaded already */ if (pageno == 0 && sc->dsp_firm) { release_firmware(sc->dsp_firm); sc->dsp_firm = NULL; } if (sc->dsp_firm == NULL && request_dsp(sc) < 0) return; p = (struct l1_code *) sc->dsp_firm->data; if (pageno >= le16_to_cpu(p->page_header[0].PageNumber)) { uea_err(INS_TO_USBDEV(sc), "invalid DSP " "page %u requested\n", pageno); return; } if (pageno != 0) { __uea_load_page_e4(sc, pageno, 0); return; } uea_dbg(INS_TO_USBDEV(sc), "sending Main DSP page %u\n", p->page_header[0].PageNumber); for (i = 0; i < le16_to_cpu(p->page_header[0].PageNumber); i++) { if (E4_IS_BOOT_PAGE(p->page_header[i].PageSize)) __uea_load_page_e4(sc, i, 1); } uea_dbg(INS_TO_USBDEV(sc) , "sending start bi\n"); bi.wHdr = cpu_to_be16(UEA_BIHDR); bi.bBootPage = 0; bi.bPageNumber = 0xff; bi.wReserved = cpu_to_be16(UEA_RESERVED); bi.dwSize = cpu_to_be32(E4_PAGE_BYTES(p->page_header[0].PageSize)); bi.dwAddress = cpu_to_be32(le32_to_cpu(p->page_header[0].PageAddress)); /* send block info through the IDMA pipe */ if (uea_idma_write(sc, &bi, E4_BLOCK_INFO_SIZE)) uea_err(INS_TO_USBDEV(sc), "sending DSP start bi failed\n"); } static inline void wake_up_cmv_ack(struct uea_softc *sc) { BUG_ON(sc->cmv_ack); sc->cmv_ack = 1; wake_up(&sc->sync_q); } static inline int wait_cmv_ack(struct uea_softc *sc) { int ret = uea_wait(sc, sc->cmv_ack , ACK_TIMEOUT); sc->cmv_ack = 0; uea_dbg(INS_TO_USBDEV(sc), "wait_event_timeout : %d ms\n", jiffies_to_msecs(ret)); if (ret < 0) return ret; return (ret == 0) ? -ETIMEDOUT : 0; } #define UCDC_SEND_ENCAPSULATED_COMMAND 0x00 static int uea_request(struct uea_softc *sc, u16 value, u16 index, u16 size, const void *data) { u8 *xfer_buff; int ret = -ENOMEM; xfer_buff = kmemdup(data, size, GFP_KERNEL); if (!xfer_buff) { uea_err(INS_TO_USBDEV(sc), "can't allocate xfer_buff\n"); return ret; } ret = usb_control_msg(sc->usb_dev, usb_sndctrlpipe(sc->usb_dev, 0), UCDC_SEND_ENCAPSULATED_COMMAND, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE, value, index, xfer_buff, size, CTRL_TIMEOUT); kfree(xfer_buff); if (ret < 0) { uea_err(INS_TO_USBDEV(sc), "usb_control_msg error %d\n", ret); return ret; } if (ret != size) { uea_err(INS_TO_USBDEV(sc), "usb_control_msg send only %d bytes (instead of %d)\n", ret, size); return -EIO; } return 0; } static int uea_cmv_e1(struct uea_softc *sc, u8 function, u32 address, u16 offset, u32 data) { struct cmv_e1 cmv; int ret; uea_enters(INS_TO_USBDEV(sc)); uea_vdbg(INS_TO_USBDEV(sc), "Function : %d-%d, Address : %c%c%c%c, " "offset : 0x%04x, data : 0x%08x\n", E1_FUNCTION_TYPE(function), E1_FUNCTION_SUBTYPE(function), E1_GETSA1(address), E1_GETSA2(address), E1_GETSA3(address), E1_GETSA4(address), offset, data); /* we send a request, but we expect a reply */ sc->cmv_dsc.e1.function = function | 0x2; sc->cmv_dsc.e1.idx++; sc->cmv_dsc.e1.address = address; sc->cmv_dsc.e1.offset = offset; cmv.wPreamble = cpu_to_le16(E1_PREAMBLE); cmv.bDirection = E1_HOSTTOMODEM; cmv.bFunction = function; cmv.wIndex = cpu_to_le16(sc->cmv_dsc.e1.idx); put_unaligned_le32(address, &cmv.dwSymbolicAddress); cmv.wOffsetAddress = cpu_to_le16(offset); put_unaligned_le32(data >> 16 | data << 16, &cmv.dwData); ret = uea_request(sc, UEA_E1_SET_BLOCK, UEA_MPTX_START, sizeof(cmv), &cmv); if (ret < 0) return ret; ret = wait_cmv_ack(sc); uea_leaves(INS_TO_USBDEV(sc)); return ret; } static int uea_cmv_e4(struct uea_softc *sc, u16 function, u16 group, u16 address, u16 offset, u32 data) { struct cmv_e4 cmv; int ret; uea_enters(INS_TO_USBDEV(sc)); memset(&cmv, 0, sizeof(cmv)); uea_vdbg(INS_TO_USBDEV(sc), "Function : %d-%d, Group : 0x%04x, " "Address : 0x%04x, offset : 0x%04x, data : 0x%08x\n", E4_FUNCTION_TYPE(function), E4_FUNCTION_SUBTYPE(function), group, address, offset, data); /* we send a request, but we expect a reply */ sc->cmv_dsc.e4.function = function | (0x1 << 4); sc->cmv_dsc.e4.offset = offset; sc->cmv_dsc.e4.address = address; sc->cmv_dsc.e4.group = group; cmv.wFunction = cpu_to_be16(function); cmv.wGroup = cpu_to_be16(group); cmv.wAddress = cpu_to_be16(address); cmv.wOffset = cpu_to_be16(offset); cmv.dwData[0] = cpu_to_be32(data); ret = uea_request(sc, UEA_E4_SET_BLOCK, UEA_MPTX_START, sizeof(cmv), &cmv); if (ret < 0) return ret; ret = wait_cmv_ack(sc); uea_leaves(INS_TO_USBDEV(sc)); return ret; } static inline int uea_read_cmv_e1(struct uea_softc *sc, u32 address, u16 offset, u32 *data) { int ret = uea_cmv_e1(sc, E1_MAKEFUNCTION(E1_MEMACCESS, E1_REQUESTREAD), address, offset, 0); if (ret < 0) uea_err(INS_TO_USBDEV(sc), "reading cmv failed with error %d\n", ret); else *data = sc->data; return ret; } static inline int uea_read_cmv_e4(struct uea_softc *sc, u8 size, u16 group, u16 address, u16 offset, u32 *data) { int ret = uea_cmv_e4(sc, E4_MAKEFUNCTION(E4_MEMACCESS, E4_REQUESTREAD, size), group, address, offset, 0); if (ret < 0) uea_err(INS_TO_USBDEV(sc), "reading cmv failed with error %d\n", ret); else { *data = sc->data; /* size is in 16-bit word quantities */ if (size > 2) *(data + 1) = sc->data1; } return ret; } static inline int uea_write_cmv_e1(struct uea_softc *sc, u32 address, u16 offset, u32 data) { int ret = uea_cmv_e1(sc, E1_MAKEFUNCTION(E1_MEMACCESS, E1_REQUESTWRITE), address, offset, data); if (ret < 0) uea_err(INS_TO_USBDEV(sc), "writing cmv failed with error %d\n", ret); return ret; } static inline int uea_write_cmv_e4(struct uea_softc *sc, u8 size, u16 group, u16 address, u16 offset, u32 data) { int ret = uea_cmv_e4(sc, E4_MAKEFUNCTION(E4_MEMACCESS, E4_REQUESTWRITE, size), group, address, offset, data); if (ret < 0) uea_err(INS_TO_USBDEV(sc), "writing cmv failed with error %d\n", ret); return ret; } static void uea_set_bulk_timeout(struct uea_softc *sc, u32 dsrate) { int ret; u16 timeout; /* in bulk mode the modem have problem with high rate * changing internal timing could improve things, but the * value is mysterious. * ADI930 don't support it (-EPIPE error). */ if (UEA_CHIP_VERSION(sc) == ADI930 || altsetting[sc->modem_index] > 0 || sc->stats.phy.dsrate == dsrate) return; /* Original timming (1Mbit/s) from ADI (used in windows driver) */ timeout = (dsrate <= 1024*1024) ? 0 : 1; ret = uea_request(sc, UEA_SET_TIMEOUT, timeout, 0, NULL); uea_info(INS_TO_USBDEV(sc), "setting new timeout %d%s\n", timeout, ret < 0 ? " failed" : ""); } /* * Monitor the modem and update the stat * return 0 if everything is ok * return < 0 if an error occurs (-EAGAIN reboot needed) */ static int uea_stat_e1(struct uea_softc *sc) { u32 data; int ret; uea_enters(INS_TO_USBDEV(sc)); data = sc->stats.phy.state; ret = uea_read_cmv_e1(sc, E1_SA_STAT, 0, &sc->stats.phy.state); if (ret < 0) return ret; switch (GET_STATUS(sc->stats.phy.state)) { case 0: /* not yet synchronized */ uea_dbg(INS_TO_USBDEV(sc), "modem not yet synchronized\n"); return 0; case 1: /* initialization */ uea_dbg(INS_TO_USBDEV(sc), "modem initializing\n"); return 0; case 2: /* operational */ uea_vdbg(INS_TO_USBDEV(sc), "modem operational\n"); break; case 3: /* fail ... */ uea_info(INS_TO_USBDEV(sc), "modem synchronization failed" " (may be try other cmv/dsp)\n"); return -EAGAIN; case 4 ... 6: /* test state */ uea_warn(INS_TO_USBDEV(sc), "modem in test mode - not supported\n"); return -EAGAIN; case 7: /* fast-retain ... */ uea_info(INS_TO_USBDEV(sc), "modem in fast-retain mode\n"); return 0; default: uea_err(INS_TO_USBDEV(sc), "modem invalid SW mode %d\n", GET_STATUS(sc->stats.phy.state)); return -EAGAIN; } if (GET_STATUS(data) != 2) { uea_request(sc, UEA_SET_MODE, UEA_LOOPBACK_OFF, 0, NULL); uea_info(INS_TO_USBDEV(sc), "modem operational\n"); /* release the dsp firmware as it is not needed until * the next failure */ release_firmware(sc->dsp_firm); sc->dsp_firm = NULL; } /* always update it as atm layer could not be init when we switch to * operational state */ UPDATE_ATM_SIGNAL(ATM_PHY_SIG_FOUND); /* wake up processes waiting for synchronization */ wake_up(&sc->sync_q); ret = uea_read_cmv_e1(sc, E1_SA_DIAG, 2, &sc->stats.phy.flags); if (ret < 0) return ret; sc->stats.phy.mflags |= sc->stats.phy.flags; /* in case of a flags ( for example delineation LOSS (& 0x10)), * we check the status again in order to detect the failure earlier */ if (sc->stats.phy.flags) { uea_dbg(INS_TO_USBDEV(sc), "Stat flag = 0x%x\n", sc->stats.phy.flags); return 0; } ret = uea_read_cmv_e1(sc, E1_SA_RATE, 0, &data); if (ret < 0) return ret; uea_set_bulk_timeout(sc, (data >> 16) * 32); sc->stats.phy.dsrate = (data >> 16) * 32; sc->stats.phy.usrate = (data & 0xffff) * 32; UPDATE_ATM_STAT(link_rate, sc->stats.phy.dsrate * 1000 / 424); ret = uea_read_cmv_e1(sc, E1_SA_DIAG, 23, &data); if (ret < 0) return ret; sc->stats.phy.dsattenuation = (data & 0xff) / 2; ret = uea_read_cmv_e1(sc, E1_SA_DIAG, 47, &data); if (ret < 0) return ret; sc->stats.phy.usattenuation = (data & 0xff) / 2; ret = uea_read_cmv_e1(sc, E1_SA_DIAG, 25, &sc->stats.phy.dsmargin); if (ret < 0) return ret; ret = uea_read_cmv_e1(sc, E1_SA_DIAG, 49, &sc->stats.phy.usmargin); if (ret < 0) return ret; ret = uea_read_cmv_e1(sc, E1_SA_DIAG, 51, &sc->stats.phy.rxflow); if (ret < 0) return ret; ret = uea_read_cmv_e1(sc, E1_SA_DIAG, 52, &sc->stats.phy.txflow); if (ret < 0) return ret; ret = uea_read_cmv_e1(sc, E1_SA_DIAG, 54, &sc->stats.phy.dsunc); if (ret < 0) return ret; /* only for atu-c */ ret = uea_read_cmv_e1(sc, E1_SA_DIAG, 58, &sc->stats.phy.usunc); if (ret < 0) return ret; ret = uea_read_cmv_e1(sc, E1_SA_DIAG, 53, &sc->stats.phy.dscorr); if (ret < 0) return ret; /* only for atu-c */ ret = uea_read_cmv_e1(sc, E1_SA_DIAG, 57, &sc->stats.phy.uscorr); if (ret < 0) return ret; ret = uea_read_cmv_e1(sc, E1_SA_INFO, 8, &sc->stats.phy.vidco); if (ret < 0) return ret; ret = uea_read_cmv_e1(sc, E1_SA_INFO, 13, &sc->stats.phy.vidcpe); if (ret < 0) return ret; return 0; } static int uea_stat_e4(struct uea_softc *sc) { u32 data; u32 tmp_arr[2]; int ret; uea_enters(INS_TO_USBDEV(sc)); data = sc->stats.phy.state; /* XXX only need to be done before operationnal... */ ret = uea_read_cmv_e4(sc, 1, E4_SA_STAT, 0, 0, &sc->stats.phy.state); if (ret < 0) return ret; switch (sc->stats.phy.state) { case 0x0: /* not yet synchronized */ case 0x1: case 0x3: case 0x4: uea_dbg(INS_TO_USBDEV(sc), "modem not yet " "synchronized\n"); return 0; case 0x5: /* initialization */ case 0x6: case 0x9: case 0xa: uea_dbg(INS_TO_USBDEV(sc), "modem initializing\n"); return 0; case 0x2: /* fail ... */ uea_info(INS_TO_USBDEV(sc), "modem synchronization " "failed (may be try other cmv/dsp)\n"); return -EAGAIN; case 0x7: /* operational */ break; default: uea_warn(INS_TO_USBDEV(sc), "unknown state: %x\n", sc->stats.phy.state); return 0; } if (data != 7) { uea_request(sc, UEA_SET_MODE, UEA_LOOPBACK_OFF, 0, NULL); uea_info(INS_TO_USBDEV(sc), "modem operational\n"); /* release the dsp firmware as it is not needed until * the next failure */ release_firmware(sc->dsp_firm); sc->dsp_firm = NULL; } /* always update it as atm layer could not be init when we switch to * operational state */ UPDATE_ATM_SIGNAL(ATM_PHY_SIG_FOUND); /* wake up processes waiting for synchronization */ wake_up(&sc->sync_q); /* TODO improve this state machine : * we need some CMV info : what they do and their unit * we should find the equivalent of eagle3- CMV */ /* check flags */ ret = uea_read_cmv_e4(sc, 1, E4_SA_DIAG, 0, 0, &sc->stats.phy.flags); if (ret < 0) return ret; sc->stats.phy.mflags |= sc->stats.phy.flags; /* in case of a flags ( for example delineation LOSS (& 0x10)), * we check the status again in order to detect the failure earlier */ if (sc->stats.phy.flags) { uea_dbg(INS_TO_USBDEV(sc), "Stat flag = 0x%x\n", sc->stats.phy.flags); if (sc->stats.phy.flags & 1) /* delineation LOSS */ return -EAGAIN; if (sc->stats.phy.flags & 0x4000) /* Reset Flag */ return -EAGAIN; return 0; } /* rate data may be in upper or lower half of 64 bit word, strange */ ret = uea_read_cmv_e4(sc, 4, E4_SA_RATE, 0, 0, tmp_arr); if (ret < 0) return ret; data = (tmp_arr[0]) ? tmp_arr[0] : tmp_arr[1]; sc->stats.phy.usrate = data / 1000; ret = uea_read_cmv_e4(sc, 4, E4_SA_RATE, 1, 0, tmp_arr); if (ret < 0) return ret; data = (tmp_arr[0]) ? tmp_arr[0] : tmp_arr[1]; uea_set_bulk_timeout(sc, data / 1000); sc->stats.phy.dsrate = data / 1000; UPDATE_ATM_STAT(link_rate, sc->stats.phy.dsrate * 1000 / 424); ret = uea_read_cmv_e4(sc, 1, E4_SA_INFO, 68, 1, &data); if (ret < 0) return ret; sc->stats.phy.dsattenuation = data / 10; ret = uea_read_cmv_e4(sc, 1, E4_SA_INFO, 69, 1, &data); if (ret < 0) return ret; sc->stats.phy.usattenuation = data / 10; ret = uea_read_cmv_e4(sc, 1, E4_SA_INFO, 68, 3, &data); if (ret < 0) return ret; sc->stats.phy.dsmargin = data / 2; ret = uea_read_cmv_e4(sc, 1, E4_SA_INFO, 69, 3, &data); if (ret < 0) return ret; sc->stats.phy.usmargin = data / 10; return 0; } static void cmvs_file_name(struct uea_softc *sc, char *const cmv_name, int ver) { char file_arr[] = "CMVxy.bin"; char *file; kparam_block_sysfs_write(cmv_file); /* set proper name corresponding modem version and line type */ if (cmv_file[sc->modem_index] == NULL) { if (UEA_CHIP_VERSION(sc) == ADI930) file_arr[3] = '9'; else if (UEA_CHIP_VERSION(sc) == EAGLE_IV) file_arr[3] = '4'; else file_arr[3] = 'e'; file_arr[4] = IS_ISDN(sc) ? 'i' : 'p'; file = file_arr; } else file = cmv_file[sc->modem_index]; strcpy(cmv_name, FW_DIR); strlcat(cmv_name, file, UEA_FW_NAME_MAX); if (ver == 2) strlcat(cmv_name, ".v2", UEA_FW_NAME_MAX); kparam_unblock_sysfs_write(cmv_file); } static int request_cmvs_old(struct uea_softc *sc, void **cmvs, const struct firmware **fw) { int ret, size; u8 *data; char cmv_name[UEA_FW_NAME_MAX]; /* 30 bytes stack variable */ cmvs_file_name(sc, cmv_name, 1); ret = request_firmware(fw, cmv_name, &sc->usb_dev->dev); if (ret < 0) { uea_err(INS_TO_USBDEV(sc), "requesting firmware %s failed with error %d\n", cmv_name, ret); return ret; } data = (u8 *) (*fw)->data; size = (*fw)->size; if (size < 1) goto err_fw_corrupted; if (size != *data * sizeof(struct uea_cmvs_v1) + 1) goto err_fw_corrupted; *cmvs = (void *)(data + 1); return *data; err_fw_corrupted: uea_err(INS_TO_USBDEV(sc), "firmware %s is corrupted\n", cmv_name); release_firmware(*fw); return -EILSEQ; } static int request_cmvs(struct uea_softc *sc, void **cmvs, const struct firmware **fw, int *ver) { int ret, size; u32 crc; u8 *data; char cmv_name[UEA_FW_NAME_MAX]; /* 30 bytes stack variable */ cmvs_file_name(sc, cmv_name, 2); ret = request_firmware(fw, cmv_name, &sc->usb_dev->dev); if (ret < 0) { /* if caller can handle old version, try to provide it */ if (*ver == 1) { uea_warn(INS_TO_USBDEV(sc), "requesting " "firmware %s failed, " "try to get older cmvs\n", cmv_name); return request_cmvs_old(sc, cmvs, fw); } uea_err(INS_TO_USBDEV(sc), "requesting firmware %s failed with error %d\n", cmv_name, ret); return ret; } size = (*fw)->size; data = (u8 *) (*fw)->data; if (size < 4 || strncmp(data, "cmv2", 4) != 0) { if (*ver == 1) { uea_warn(INS_TO_USBDEV(sc), "firmware %s is corrupted," " try to get older cmvs\n", cmv_name); release_firmware(*fw); return request_cmvs_old(sc, cmvs, fw); } goto err_fw_corrupted; } *ver = 2; data += 4; size -= 4; if (size < 5) goto err_fw_corrupted; crc = get_unaligned_le32(data); data += 4; size -= 4; if (crc32_be(0, data, size) != crc) goto err_fw_corrupted; if (size != *data * sizeof(struct uea_cmvs_v2) + 1) goto err_fw_corrupted; *cmvs = (void *) (data + 1); return *data; err_fw_corrupted: uea_err(INS_TO_USBDEV(sc), "firmware %s is corrupted\n", cmv_name); release_firmware(*fw); return -EILSEQ; } static int uea_send_cmvs_e1(struct uea_softc *sc) { int i, ret, len; void *cmvs_ptr; const struct firmware *cmvs_fw; int ver = 1; /* we can handle v1 cmv firmware version; */ /* Enter in R-IDLE (cmv) until instructed otherwise */ ret = uea_write_cmv_e1(sc, E1_SA_CNTL, 0, 1); if (ret < 0) return ret; /* Dump firmware version */ ret = uea_read_cmv_e1(sc, E1_SA_INFO, 10, &sc->stats.phy.firmid); if (ret < 0) return ret; uea_info(INS_TO_USBDEV(sc), "ATU-R firmware version : %x\n", sc->stats.phy.firmid); /* get options */ ret = len = request_cmvs(sc, &cmvs_ptr, &cmvs_fw, &ver); if (ret < 0) return ret; /* send options */ if (ver == 1) { struct uea_cmvs_v1 *cmvs_v1 = cmvs_ptr; uea_warn(INS_TO_USBDEV(sc), "use deprecated cmvs version, " "please update your firmware\n"); for (i = 0; i < len; i++) { ret = uea_write_cmv_e1(sc, get_unaligned_le32(&cmvs_v1[i].address), get_unaligned_le16(&cmvs_v1[i].offset), get_unaligned_le32(&cmvs_v1[i].data)); if (ret < 0) goto out; } } else if (ver == 2) { struct uea_cmvs_v2 *cmvs_v2 = cmvs_ptr; for (i = 0; i < len; i++) { ret = uea_write_cmv_e1(sc, get_unaligned_le32(&cmvs_v2[i].address), (u16) get_unaligned_le32(&cmvs_v2[i].offset), get_unaligned_le32(&cmvs_v2[i].data)); if (ret < 0) goto out; } } else { /* This really should not happen */ uea_err(INS_TO_USBDEV(sc), "bad cmvs version %d\n", ver); goto out; } /* Enter in R-ACT-REQ */ ret = uea_write_cmv_e1(sc, E1_SA_CNTL, 0, 2); uea_vdbg(INS_TO_USBDEV(sc), "Entering in R-ACT-REQ state\n"); uea_info(INS_TO_USBDEV(sc), "modem started, waiting " "synchronization...\n"); out: release_firmware(cmvs_fw); return ret; } static int uea_send_cmvs_e4(struct uea_softc *sc) { int i, ret, len; void *cmvs_ptr; const struct firmware *cmvs_fw; int ver = 2; /* we can only handle v2 cmv firmware version; */ /* Enter in R-IDLE (cmv) until instructed otherwise */ ret = uea_write_cmv_e4(sc, 1, E4_SA_CNTL, 0, 0, 1); if (ret < 0) return ret; /* Dump firmware version */ /* XXX don't read the 3th byte as it is always 6 */ ret = uea_read_cmv_e4(sc, 2, E4_SA_INFO, 55, 0, &sc->stats.phy.firmid); if (ret < 0) return ret; uea_info(INS_TO_USBDEV(sc), "ATU-R firmware version : %x\n", sc->stats.phy.firmid); /* get options */ ret = len = request_cmvs(sc, &cmvs_ptr, &cmvs_fw, &ver); if (ret < 0) return ret; /* send options */ if (ver == 2) { struct uea_cmvs_v2 *cmvs_v2 = cmvs_ptr; for (i = 0; i < len; i++) { ret = uea_write_cmv_e4(sc, 1, get_unaligned_le32(&cmvs_v2[i].group), get_unaligned_le32(&cmvs_v2[i].address), get_unaligned_le32(&cmvs_v2[i].offset), get_unaligned_le32(&cmvs_v2[i].data)); if (ret < 0) goto out; } } else { /* This really should not happen */ uea_err(INS_TO_USBDEV(sc), "bad cmvs version %d\n", ver); goto out; } /* Enter in R-ACT-REQ */ ret = uea_write_cmv_e4(sc, 1, E4_SA_CNTL, 0, 0, 2); uea_vdbg(INS_TO_USBDEV(sc), "Entering in R-ACT-REQ state\n"); uea_info(INS_TO_USBDEV(sc), "modem started, waiting " "synchronization...\n"); out: release_firmware(cmvs_fw); return ret; } /* Start boot post firmware modem: * - send reset commands through usb control pipe * - start workqueue for DSP loading * - send CMV options to modem */ static int uea_start_reset(struct uea_softc *sc) { u16 zero = 0; /* ;-) */ int ret; uea_enters(INS_TO_USBDEV(sc)); uea_info(INS_TO_USBDEV(sc), "(re)booting started\n"); /* mask interrupt */ sc->booting = 1; /* We need to set this here because, a ack timeout could have occurred, * but before we start the reboot, the ack occurs and set this to 1. * So we will failed to wait Ready CMV. */ sc->cmv_ack = 0; UPDATE_ATM_SIGNAL(ATM_PHY_SIG_LOST); /* reset statistics */ memset(&sc->stats, 0, sizeof(struct uea_stats)); /* tell the modem that we want to boot in IDMA mode */ uea_request(sc, UEA_SET_MODE, UEA_LOOPBACK_ON, 0, NULL); uea_request(sc, UEA_SET_MODE, UEA_BOOT_IDMA, 0, NULL); /* enter reset mode */ uea_request(sc, UEA_SET_MODE, UEA_START_RESET, 0, NULL); /* original driver use 200ms, but windows driver use 100ms */ ret = uea_wait(sc, 0, msecs_to_jiffies(100)); if (ret < 0) return ret; /* leave reset mode */ uea_request(sc, UEA_SET_MODE, UEA_END_RESET, 0, NULL); if (UEA_CHIP_VERSION(sc) != EAGLE_IV) { /* clear tx and rx mailboxes */ uea_request(sc, UEA_SET_2183_DATA, UEA_MPTX_MAILBOX, 2, &zero); uea_request(sc, UEA_SET_2183_DATA, UEA_MPRX_MAILBOX, 2, &zero); uea_request(sc, UEA_SET_2183_DATA, UEA_SWAP_MAILBOX, 2, &zero); } ret = uea_wait(sc, 0, msecs_to_jiffies(1000)); if (ret < 0) return ret; if (UEA_CHIP_VERSION(sc) == EAGLE_IV) sc->cmv_dsc.e4.function = E4_MAKEFUNCTION(E4_ADSLDIRECTIVE, E4_MODEMREADY, 1); else sc->cmv_dsc.e1.function = E1_MAKEFUNCTION(E1_ADSLDIRECTIVE, E1_MODEMREADY); /* demask interrupt */ sc->booting = 0; /* start loading DSP */ sc->pageno = 0; sc->ovl = 0; schedule_work(&sc->task); /* wait for modem ready CMV */ ret = wait_cmv_ack(sc); if (ret < 0) return ret; uea_vdbg(INS_TO_USBDEV(sc), "Ready CMV received\n"); ret = sc->send_cmvs(sc); if (ret < 0) return ret; sc->reset = 0; uea_leaves(INS_TO_USBDEV(sc)); return ret; } /* * In case of an error wait 1s before rebooting the modem * if the modem don't request reboot (-EAGAIN). * Monitor the modem every 1s. */ static int uea_kthread(void *data) { struct uea_softc *sc = data; int ret = -EAGAIN; set_freezable(); uea_enters(INS_TO_USBDEV(sc)); while (!kthread_should_stop()) { if (ret < 0 || sc->reset) ret = uea_start_reset(sc); if (!ret) ret = sc->stat(sc); if (ret != -EAGAIN) uea_wait(sc, 0, msecs_to_jiffies(1000)); try_to_freeze(); } uea_leaves(INS_TO_USBDEV(sc)); return ret; } /* Load second usb firmware for ADI930 chip */ static int load_XILINX_firmware(struct uea_softc *sc) { const struct firmware *fw_entry; int ret, size, u, ln; const u8 *pfw; u8 value; char *fw_name = FPGA930_FIRMWARE; uea_enters(INS_TO_USBDEV(sc)); ret = request_firmware(&fw_entry, fw_name, &sc->usb_dev->dev); if (ret) { uea_err(INS_TO_USBDEV(sc), "firmware %s is not available\n", fw_name); goto err0; } pfw = fw_entry->data; size = fw_entry->size; if (size != 0x577B) { uea_err(INS_TO_USBDEV(sc), "firmware %s is corrupted\n", fw_name); ret = -EILSEQ; goto err1; } for (u = 0; u < size; u += ln) { ln = min(size - u, 64); ret = uea_request(sc, 0xe, 0, ln, pfw + u); if (ret < 0) { uea_err(INS_TO_USBDEV(sc), "elsa download data failed (%d)\n", ret); goto err1; } } /* finish to send the fpga */ ret = uea_request(sc, 0xe, 1, 0, NULL); if (ret < 0) { uea_err(INS_TO_USBDEV(sc), "elsa download data failed (%d)\n", ret); goto err1; } /* Tell the modem we finish : de-assert reset */ value = 0; ret = uea_send_modem_cmd(sc->usb_dev, 0xe, 1, &value); if (ret < 0) uea_err(sc->usb_dev, "elsa de-assert failed with error" " %d\n", ret); err1: release_firmware(fw_entry); err0: uea_leaves(INS_TO_USBDEV(sc)); return ret; } /* The modem send us an ack. First with check if it right */ static void uea_dispatch_cmv_e1(struct uea_softc *sc, struct intr_pkt *intr) { struct cmv_dsc_e1 *dsc = &sc->cmv_dsc.e1; struct cmv_e1 *cmv = &intr->u.e1.s2.cmv; uea_enters(INS_TO_USBDEV(sc)); if (le16_to_cpu(cmv->wPreamble) != E1_PREAMBLE) goto bad1; if (cmv->bDirection != E1_MODEMTOHOST) goto bad1; /* FIXME : ADI930 reply wrong preambule (func = 2, sub = 2) to * the first MEMACCESS cmv. Ignore it... */ if (cmv->bFunction != dsc->function) { if (UEA_CHIP_VERSION(sc) == ADI930 && cmv->bFunction == E1_MAKEFUNCTION(2, 2)) { cmv->wIndex = cpu_to_le16(dsc->idx); put_unaligned_le32(dsc->address, &cmv->dwSymbolicAddress); cmv->wOffsetAddress = cpu_to_le16(dsc->offset); } else goto bad2; } if (cmv->bFunction == E1_MAKEFUNCTION(E1_ADSLDIRECTIVE, E1_MODEMREADY)) { wake_up_cmv_ack(sc); uea_leaves(INS_TO_USBDEV(sc)); return; } /* in case of MEMACCESS */ if (le16_to_cpu(cmv->wIndex) != dsc->idx || get_unaligned_le32(&cmv->dwSymbolicAddress) != dsc->address || le16_to_cpu(cmv->wOffsetAddress) != dsc->offset) goto bad2; sc->data = get_unaligned_le32(&cmv->dwData); sc->data = sc->data << 16 | sc->data >> 16; wake_up_cmv_ack(sc); uea_leaves(INS_TO_USBDEV(sc)); return; bad2: uea_err(INS_TO_USBDEV(sc), "unexpected cmv received, " "Function : %d, Subfunction : %d\n", E1_FUNCTION_TYPE(cmv->bFunction), E1_FUNCTION_SUBTYPE(cmv->bFunction)); uea_leaves(INS_TO_USBDEV(sc)); return; bad1: uea_err(INS_TO_USBDEV(sc), "invalid cmv received, " "wPreamble %d, bDirection %d\n", le16_to_cpu(cmv->wPreamble), cmv->bDirection); uea_leaves(INS_TO_USBDEV(sc)); } /* The modem send us an ack. First with check if it right */ static void uea_dispatch_cmv_e4(struct uea_softc *sc, struct intr_pkt *intr) { struct cmv_dsc_e4 *dsc = &sc->cmv_dsc.e4; struct cmv_e4 *cmv = &intr->u.e4.s2.cmv; uea_enters(INS_TO_USBDEV(sc)); uea_dbg(INS_TO_USBDEV(sc), "cmv %x %x %x %x %x %x\n", be16_to_cpu(cmv->wGroup), be16_to_cpu(cmv->wFunction), be16_to_cpu(cmv->wOffset), be16_to_cpu(cmv->wAddress), be32_to_cpu(cmv->dwData[0]), be32_to_cpu(cmv->dwData[1])); if (be16_to_cpu(cmv->wFunction) != dsc->function) goto bad2; if (be16_to_cpu(cmv->wFunction) == E4_MAKEFUNCTION(E4_ADSLDIRECTIVE, E4_MODEMREADY, 1)) { wake_up_cmv_ack(sc); uea_leaves(INS_TO_USBDEV(sc)); return; } /* in case of MEMACCESS */ if (be16_to_cpu(cmv->wOffset) != dsc->offset || be16_to_cpu(cmv->wGroup) != dsc->group || be16_to_cpu(cmv->wAddress) != dsc->address) goto bad2; sc->data = be32_to_cpu(cmv->dwData[0]); sc->data1 = be32_to_cpu(cmv->dwData[1]); wake_up_cmv_ack(sc); uea_leaves(INS_TO_USBDEV(sc)); return; bad2: uea_err(INS_TO_USBDEV(sc), "unexpected cmv received, " "Function : %d, Subfunction : %d\n", E4_FUNCTION_TYPE(cmv->wFunction), E4_FUNCTION_SUBTYPE(cmv->wFunction)); uea_leaves(INS_TO_USBDEV(sc)); return; } static void uea_schedule_load_page_e1(struct uea_softc *sc, struct intr_pkt *intr) { sc->pageno = intr->e1_bSwapPageNo; sc->ovl = intr->e1_bOvl >> 4 | intr->e1_bOvl << 4; schedule_work(&sc->task); } static void uea_schedule_load_page_e4(struct uea_softc *sc, struct intr_pkt *intr) { sc->pageno = intr->e4_bSwapPageNo; schedule_work(&sc->task); } /* * interrupt handler */ static void uea_intr(struct urb *urb) { struct uea_softc *sc = urb->context; struct intr_pkt *intr = urb->transfer_buffer; int status = urb->status; uea_enters(INS_TO_USBDEV(sc)); if (unlikely(status < 0)) { uea_err(INS_TO_USBDEV(sc), "uea_intr() failed with %d\n", status); return; } /* device-to-host interrupt */ if (intr->bType != 0x08 || sc->booting) { uea_err(INS_TO_USBDEV(sc), "wrong interrupt\n"); goto resubmit; } switch (le16_to_cpu(intr->wInterrupt)) { case INT_LOADSWAPPAGE: sc->schedule_load_page(sc, intr); break; case INT_INCOMINGCMV: sc->dispatch_cmv(sc, intr); break; default: uea_err(INS_TO_USBDEV(sc), "unknown interrupt %u\n", le16_to_cpu(intr->wInterrupt)); } resubmit: usb_submit_urb(sc->urb_int, GFP_ATOMIC); } /* * Start the modem : init the data and start kernel thread */ static int uea_boot(struct uea_softc *sc) { int ret, size; struct intr_pkt *intr; uea_enters(INS_TO_USBDEV(sc)); if (UEA_CHIP_VERSION(sc) == EAGLE_IV) { size = E4_INTR_PKT_SIZE; sc->dispatch_cmv = uea_dispatch_cmv_e4; sc->schedule_load_page = uea_schedule_load_page_e4; sc->stat = uea_stat_e4; sc->send_cmvs = uea_send_cmvs_e4; INIT_WORK(&sc->task, uea_load_page_e4); } else { size = E1_INTR_PKT_SIZE; sc->dispatch_cmv = uea_dispatch_cmv_e1; sc->schedule_load_page = uea_schedule_load_page_e1; sc->stat = uea_stat_e1; sc->send_cmvs = uea_send_cmvs_e1; INIT_WORK(&sc->task, uea_load_page_e1); } init_waitqueue_head(&sc->sync_q); if (UEA_CHIP_VERSION(sc) == ADI930) load_XILINX_firmware(sc); intr = kmalloc(size, GFP_KERNEL); if (!intr) { uea_err(INS_TO_USBDEV(sc), "cannot allocate interrupt package\n"); goto err0; } sc->urb_int = usb_alloc_urb(0, GFP_KERNEL); if (!sc->urb_int) { uea_err(INS_TO_USBDEV(sc), "cannot allocate interrupt URB\n"); goto err1; } usb_fill_int_urb(sc->urb_int, sc->usb_dev, usb_rcvintpipe(sc->usb_dev, UEA_INTR_PIPE), intr, size, uea_intr, sc, sc->usb_dev->actconfig->interface[0]->altsetting[0]. endpoint[0].desc.bInterval); ret = usb_submit_urb(sc->urb_int, GFP_KERNEL); if (ret < 0) { uea_err(INS_TO_USBDEV(sc), "urb submition failed with error %d\n", ret); goto err1; } /* Create worker thread, but don't start it here. Start it after * all usbatm generic initialization is done. */ sc->kthread = kthread_create(uea_kthread, sc, "ueagle-atm"); if (IS_ERR(sc->kthread)) { uea_err(INS_TO_USBDEV(sc), "failed to create thread\n"); goto err2; } uea_leaves(INS_TO_USBDEV(sc)); return 0; err2: usb_kill_urb(sc->urb_int); err1: usb_free_urb(sc->urb_int); sc->urb_int = NULL; kfree(intr); err0: uea_leaves(INS_TO_USBDEV(sc)); return -ENOMEM; } /* * Stop the modem : kill kernel thread and free data */ static void uea_stop(struct uea_softc *sc) { int ret; uea_enters(INS_TO_USBDEV(sc)); ret = kthread_stop(sc->kthread); uea_dbg(INS_TO_USBDEV(sc), "kthread finish with status %d\n", ret); uea_request(sc, UEA_SET_MODE, UEA_LOOPBACK_ON, 0, NULL); usb_kill_urb(sc->urb_int); kfree(sc->urb_int->transfer_buffer); usb_free_urb(sc->urb_int); /* flush the work item, when no one can schedule it */ flush_work(&sc->task); release_firmware(sc->dsp_firm); uea_leaves(INS_TO_USBDEV(sc)); } /* syfs interface */ static struct uea_softc *dev_to_uea(struct device *dev) { struct usb_interface *intf; struct usbatm_data *usbatm; intf = to_usb_interface(dev); if (!intf) return NULL; usbatm = usb_get_intfdata(intf); if (!usbatm) return NULL; return usbatm->driver_data; } static ssize_t read_status(struct device *dev, struct device_attribute *attr, char *buf) { int ret = -ENODEV; struct uea_softc *sc; mutex_lock(&uea_mutex); sc = dev_to_uea(dev); if (!sc) goto out; ret = snprintf(buf, 10, "%08x\n", sc->stats.phy.state); out: mutex_unlock(&uea_mutex); return ret; } static ssize_t reboot(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int ret = -ENODEV; struct uea_softc *sc; mutex_lock(&uea_mutex); sc = dev_to_uea(dev); if (!sc) goto out; sc->reset = 1; ret = count; out: mutex_unlock(&uea_mutex); return ret; } static DEVICE_ATTR(stat_status, S_IWUSR | S_IRUGO, read_status, reboot); static ssize_t read_human_status(struct device *dev, struct device_attribute *attr, char *buf) { int ret = -ENODEV; int modem_state; struct uea_softc *sc; mutex_lock(&uea_mutex); sc = dev_to_uea(dev); if (!sc) goto out; if (UEA_CHIP_VERSION(sc) == EAGLE_IV) { switch (sc->stats.phy.state) { case 0x0: /* not yet synchronized */ case 0x1: case 0x3: case 0x4: modem_state = 0; break; case 0x5: /* initialization */ case 0x6: case 0x9: case 0xa: modem_state = 1; break; case 0x7: /* operational */ modem_state = 2; break; case 0x2: /* fail ... */ modem_state = 3; break; default: /* unknown */ modem_state = 4; break; } } else modem_state = GET_STATUS(sc->stats.phy.state); switch (modem_state) { case 0: ret = sprintf(buf, "Modem is booting\n"); break; case 1: ret = sprintf(buf, "Modem is initializing\n"); break; case 2: ret = sprintf(buf, "Modem is operational\n"); break; case 3: ret = sprintf(buf, "Modem synchronization failed\n"); break; default: ret = sprintf(buf, "Modem state is unknown\n"); break; } out: mutex_unlock(&uea_mutex); return ret; } static DEVICE_ATTR(stat_human_status, S_IRUGO, read_human_status, NULL); static ssize_t read_delin(struct device *dev, struct device_attribute *attr, char *buf) { int ret = -ENODEV; struct uea_softc *sc; char *delin = "GOOD"; mutex_lock(&uea_mutex); sc = dev_to_uea(dev); if (!sc) goto out; if (UEA_CHIP_VERSION(sc) == EAGLE_IV) { if (sc->stats.phy.flags & 0x4000) delin = "RESET"; else if (sc->stats.phy.flags & 0x0001) delin = "LOSS"; } else { if (sc->stats.phy.flags & 0x0C00) delin = "ERROR"; else if (sc->stats.phy.flags & 0x0030) delin = "LOSS"; } ret = sprintf(buf, "%s\n", delin); out: mutex_unlock(&uea_mutex); return ret; } static DEVICE_ATTR(stat_delin, S_IRUGO, read_delin, NULL); #define UEA_ATTR(name, reset) \ \ static ssize_t read_##name(struct device *dev, \ struct device_attribute *attr, char *buf) \ { \ int ret = -ENODEV; \ struct uea_softc *sc; \ \ mutex_lock(&uea_mutex); \ sc = dev_to_uea(dev); \ if (!sc) \ goto out; \ ret = snprintf(buf, 10, "%08x\n", sc->stats.phy.name); \ if (reset) \ sc->stats.phy.name = 0; \ out: \ mutex_unlock(&uea_mutex); \ return ret; \ } \ \ static DEVICE_ATTR(stat_##name, S_IRUGO, read_##name, NULL) UEA_ATTR(mflags, 1); UEA_ATTR(vidcpe, 0); UEA_ATTR(usrate, 0); UEA_ATTR(dsrate, 0); UEA_ATTR(usattenuation, 0); UEA_ATTR(dsattenuation, 0); UEA_ATTR(usmargin, 0); UEA_ATTR(dsmargin, 0); UEA_ATTR(txflow, 0); UEA_ATTR(rxflow, 0); UEA_ATTR(uscorr, 0); UEA_ATTR(dscorr, 0); UEA_ATTR(usunc, 0); UEA_ATTR(dsunc, 0); UEA_ATTR(firmid, 0); /* Retrieve the device End System Identifier (MAC) */ static int uea_getesi(struct uea_softc *sc, u_char * esi) { unsigned char mac_str[2 * ETH_ALEN + 1]; int i; if (usb_string (sc->usb_dev, sc->usb_dev->descriptor.iSerialNumber, mac_str, sizeof(mac_str)) != 2 * ETH_ALEN) return 1; for (i = 0; i < ETH_ALEN; i++) esi[i] = hex_to_bin(mac_str[2 * i]) * 16 + hex_to_bin(mac_str[2 * i + 1]); return 0; } /* ATM stuff */ static int uea_atm_open(struct usbatm_data *usbatm, struct atm_dev *atm_dev) { struct uea_softc *sc = usbatm->driver_data; return uea_getesi(sc, atm_dev->esi); } static int uea_heavy(struct usbatm_data *usbatm, struct usb_interface *intf) { struct uea_softc *sc = usbatm->driver_data; wait_event_interruptible(sc->sync_q, IS_OPERATIONAL(sc)); return 0; } static int claim_interface(struct usb_device *usb_dev, struct usbatm_data *usbatm, int ifnum) { int ret; struct usb_interface *intf = usb_ifnum_to_if(usb_dev, ifnum); if (!intf) { uea_err(usb_dev, "interface %d not found\n", ifnum); return -ENODEV; } ret = usb_driver_claim_interface(&uea_driver, intf, usbatm); if (ret != 0) uea_err(usb_dev, "can't claim interface %d, error %d\n", ifnum, ret); return ret; } static struct attribute *attrs[] = { &dev_attr_stat_status.attr, &dev_attr_stat_mflags.attr, &dev_attr_stat_human_status.attr, &dev_attr_stat_delin.attr, &dev_attr_stat_vidcpe.attr, &dev_attr_stat_usrate.attr, &dev_attr_stat_dsrate.attr, &dev_attr_stat_usattenuation.attr, &dev_attr_stat_dsattenuation.attr, &dev_attr_stat_usmargin.attr, &dev_attr_stat_dsmargin.attr, &dev_attr_stat_txflow.attr, &dev_attr_stat_rxflow.attr, &dev_attr_stat_uscorr.attr, &dev_attr_stat_dscorr.attr, &dev_attr_stat_usunc.attr, &dev_attr_stat_dsunc.attr, &dev_attr_stat_firmid.attr, NULL, }; static struct attribute_group attr_grp = { .attrs = attrs, }; static int uea_bind(struct usbatm_data *usbatm, struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *usb = interface_to_usbdev(intf); struct uea_softc *sc; int ret, ifnum = intf->altsetting->desc.bInterfaceNumber; unsigned int alt; uea_enters(usb); /* interface 0 is for firmware/monitoring */ if (ifnum != UEA_INTR_IFACE_NO) return -ENODEV; usbatm->flags = (sync_wait[modem_index] ? 0 : UDSL_SKIP_HEAVY_INIT); /* interface 1 is for outbound traffic */ ret = claim_interface(usb, usbatm, UEA_US_IFACE_NO); if (ret < 0) return ret; /* ADI930 has only 2 interfaces and inbound traffic is on interface 1 */ if (UEA_CHIP_VERSION(id) != ADI930) { /* interface 2 is for inbound traffic */ ret = claim_interface(usb, usbatm, UEA_DS_IFACE_NO); if (ret < 0) return ret; } sc = kzalloc(sizeof(struct uea_softc), GFP_KERNEL); if (!sc) { uea_err(usb, "uea_init: not enough memory !\n"); return -ENOMEM; } sc->usb_dev = usb; usbatm->driver_data = sc; sc->usbatm = usbatm; sc->modem_index = (modem_index < NB_MODEM) ? modem_index++ : 0; sc->driver_info = id->driver_info; /* first try to use module parameter */ if (annex[sc->modem_index] == 1) sc->annex = ANNEXA; else if (annex[sc->modem_index] == 2) sc->annex = ANNEXB; /* try to autodetect annex */ else if (sc->driver_info & AUTO_ANNEX_A) sc->annex = ANNEXA; else if (sc->driver_info & AUTO_ANNEX_B) sc->annex = ANNEXB; else sc->annex = (le16_to_cpu (sc->usb_dev->descriptor.bcdDevice) & 0x80) ? ANNEXB : ANNEXA; alt = altsetting[sc->modem_index]; /* ADI930 don't support iso */ if (UEA_CHIP_VERSION(id) != ADI930 && alt > 0) { if (alt <= 8 && usb_set_interface(usb, UEA_DS_IFACE_NO, alt) == 0) { uea_dbg(usb, "set alternate %u for 2 interface\n", alt); uea_info(usb, "using iso mode\n"); usbatm->flags |= UDSL_USE_ISOC | UDSL_IGNORE_EILSEQ; } else { uea_err(usb, "setting alternate %u failed for " "2 interface, using bulk mode\n", alt); } } ret = sysfs_create_group(&intf->dev.kobj, &attr_grp); if (ret < 0) goto error; ret = uea_boot(sc); if (ret < 0) goto error_rm_grp; return 0; error_rm_grp: sysfs_remove_group(&intf->dev.kobj, &attr_grp); error: kfree(sc); return ret; } static void uea_unbind(struct usbatm_data *usbatm, struct usb_interface *intf) { struct uea_softc *sc = usbatm->driver_data; sysfs_remove_group(&intf->dev.kobj, &attr_grp); uea_stop(sc); kfree(sc); } static struct usbatm_driver uea_usbatm_driver = { .driver_name = "ueagle-atm", .bind = uea_bind, .atm_start = uea_atm_open, .unbind = uea_unbind, .heavy_init = uea_heavy, .bulk_in = UEA_BULK_DATA_PIPE, .bulk_out = UEA_BULK_DATA_PIPE, .isoc_in = UEA_ISO_DATA_PIPE, }; static int uea_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *usb = interface_to_usbdev(intf); int ret; uea_enters(usb); uea_info(usb, "ADSL device founded vid (%#X) pid (%#X) Rev (%#X): %s\n", le16_to_cpu(usb->descriptor.idVendor), le16_to_cpu(usb->descriptor.idProduct), le16_to_cpu(usb->descriptor.bcdDevice), chip_name[UEA_CHIP_VERSION(id)]); usb_reset_device(usb); if (UEA_IS_PREFIRM(id)) return uea_load_firmware(usb, UEA_CHIP_VERSION(id)); ret = usbatm_usb_probe(intf, id, &uea_usbatm_driver); if (ret == 0) { struct usbatm_data *usbatm = usb_get_intfdata(intf); struct uea_softc *sc = usbatm->driver_data; /* Ensure carrier is initialized to off as early as possible */ UPDATE_ATM_SIGNAL(ATM_PHY_SIG_LOST); /* Only start the worker thread when all init is done */ wake_up_process(sc->kthread); } return ret; } static void uea_disconnect(struct usb_interface *intf) { struct usb_device *usb = interface_to_usbdev(intf); int ifnum = intf->altsetting->desc.bInterfaceNumber; uea_enters(usb); /* ADI930 has 2 interfaces and eagle 3 interfaces. * Pre-firmware device has one interface */ if (usb->config->desc.bNumInterfaces != 1 && ifnum == 0) { mutex_lock(&uea_mutex); usbatm_usb_disconnect(intf); mutex_unlock(&uea_mutex); uea_info(usb, "ADSL device removed\n"); } uea_leaves(usb); } /* * List of supported VID/PID */ static const struct usb_device_id uea_ids[] = { {USB_DEVICE(ANALOG_VID, ADI930_PID_PREFIRM), .driver_info = ADI930 | PREFIRM}, {USB_DEVICE(ANALOG_VID, ADI930_PID_PSTFIRM), .driver_info = ADI930 | PSTFIRM}, {USB_DEVICE(ANALOG_VID, EAGLE_I_PID_PREFIRM), .driver_info = EAGLE_I | PREFIRM}, {USB_DEVICE(ANALOG_VID, EAGLE_I_PID_PSTFIRM), .driver_info = EAGLE_I | PSTFIRM}, {USB_DEVICE(ANALOG_VID, EAGLE_II_PID_PREFIRM), .driver_info = EAGLE_II | PREFIRM}, {USB_DEVICE(ANALOG_VID, EAGLE_II_PID_PSTFIRM), .driver_info = EAGLE_II | PSTFIRM}, {USB_DEVICE(ANALOG_VID, EAGLE_IIC_PID_PREFIRM), .driver_info = EAGLE_II | PREFIRM}, {USB_DEVICE(ANALOG_VID, EAGLE_IIC_PID_PSTFIRM), .driver_info = EAGLE_II | PSTFIRM}, {USB_DEVICE(ANALOG_VID, EAGLE_III_PID_PREFIRM), .driver_info = EAGLE_III | PREFIRM}, {USB_DEVICE(ANALOG_VID, EAGLE_III_PID_PSTFIRM), .driver_info = EAGLE_III | PSTFIRM}, {USB_DEVICE(ANALOG_VID, EAGLE_IV_PID_PREFIRM), .driver_info = EAGLE_IV | PREFIRM}, {USB_DEVICE(ANALOG_VID, EAGLE_IV_PID_PSTFIRM), .driver_info = EAGLE_IV | PSTFIRM}, {USB_DEVICE(DEVOLO_VID, DEVOLO_EAGLE_I_A_PID_PREFIRM), .driver_info = EAGLE_I | PREFIRM}, {USB_DEVICE(DEVOLO_VID, DEVOLO_EAGLE_I_A_PID_PSTFIRM), .driver_info = EAGLE_I | PSTFIRM | AUTO_ANNEX_A}, {USB_DEVICE(DEVOLO_VID, DEVOLO_EAGLE_I_B_PID_PREFIRM), .driver_info = EAGLE_I | PREFIRM}, {USB_DEVICE(DEVOLO_VID, DEVOLO_EAGLE_I_B_PID_PSTFIRM), .driver_info = EAGLE_I | PSTFIRM | AUTO_ANNEX_B}, {USB_DEVICE(DEVOLO_VID, DEVOLO_EAGLE_II_A_PID_PREFIRM), .driver_info = EAGLE_II | PREFIRM}, {USB_DEVICE(DEVOLO_VID, DEVOLO_EAGLE_II_A_PID_PSTFIRM), .driver_info = EAGLE_II | PSTFIRM | AUTO_ANNEX_A}, {USB_DEVICE(DEVOLO_VID, DEVOLO_EAGLE_II_B_PID_PREFIRM), .driver_info = EAGLE_II | PREFIRM}, {USB_DEVICE(DEVOLO_VID, DEVOLO_EAGLE_II_B_PID_PSTFIRM), .driver_info = EAGLE_II | PSTFIRM | AUTO_ANNEX_B}, {USB_DEVICE(ELSA_VID, ELSA_PID_PREFIRM), .driver_info = ADI930 | PREFIRM}, {USB_DEVICE(ELSA_VID, ELSA_PID_PSTFIRM), .driver_info = ADI930 | PSTFIRM}, {USB_DEVICE(ELSA_VID, ELSA_PID_A_PREFIRM), .driver_info = ADI930 | PREFIRM}, {USB_DEVICE(ELSA_VID, ELSA_PID_A_PSTFIRM), .driver_info = ADI930 | PSTFIRM | AUTO_ANNEX_A}, {USB_DEVICE(ELSA_VID, ELSA_PID_B_PREFIRM), .driver_info = ADI930 | PREFIRM}, {USB_DEVICE(ELSA_VID, ELSA_PID_B_PSTFIRM), .driver_info = ADI930 | PSTFIRM | AUTO_ANNEX_B}, {USB_DEVICE(USR_VID, MILLER_A_PID_PREFIRM), .driver_info = EAGLE_I | PREFIRM}, {USB_DEVICE(USR_VID, MILLER_A_PID_PSTFIRM), .driver_info = EAGLE_I | PSTFIRM | AUTO_ANNEX_A}, {USB_DEVICE(USR_VID, MILLER_B_PID_PREFIRM), .driver_info = EAGLE_I | PREFIRM}, {USB_DEVICE(USR_VID, MILLER_B_PID_PSTFIRM), .driver_info = EAGLE_I | PSTFIRM | AUTO_ANNEX_B}, {USB_DEVICE(USR_VID, HEINEKEN_A_PID_PREFIRM), .driver_info = EAGLE_I | PREFIRM}, {USB_DEVICE(USR_VID, HEINEKEN_A_PID_PSTFIRM), .driver_info = EAGLE_I | PSTFIRM | AUTO_ANNEX_A}, {USB_DEVICE(USR_VID, HEINEKEN_B_PID_PREFIRM), .driver_info = EAGLE_I | PREFIRM}, {USB_DEVICE(USR_VID, HEINEKEN_B_PID_PSTFIRM), .driver_info = EAGLE_I | PSTFIRM | AUTO_ANNEX_B}, {} }; /* * USB driver descriptor */ static struct usb_driver uea_driver = { .name = "ueagle-atm", .id_table = uea_ids, .probe = uea_probe, .disconnect = uea_disconnect, }; MODULE_DEVICE_TABLE(usb, uea_ids); module_usb_driver(uea_driver); MODULE_AUTHOR("Damien Bergamini/Matthieu Castet/Stanislaw W. Gruszka"); MODULE_DESCRIPTION("ADI 930/Eagle USB ADSL Modem driver"); MODULE_LICENSE("Dual BSD/GPL"); MODULE_FIRMWARE(EAGLE_FIRMWARE); MODULE_FIRMWARE(ADI930_FIRMWARE); MODULE_FIRMWARE(EAGLE_I_FIRMWARE); MODULE_FIRMWARE(EAGLE_II_FIRMWARE); MODULE_FIRMWARE(EAGLE_III_FIRMWARE); MODULE_FIRMWARE(EAGLE_IV_FIRMWARE); MODULE_FIRMWARE(DSP4I_FIRMWARE); MODULE_FIRMWARE(DSP4P_FIRMWARE); MODULE_FIRMWARE(DSP9I_FIRMWARE); MODULE_FIRMWARE(DSP9P_FIRMWARE); MODULE_FIRMWARE(DSPEI_FIRMWARE); MODULE_FIRMWARE(DSPEP_FIRMWARE); MODULE_FIRMWARE(FPGA930_FIRMWARE); MODULE_FIRMWARE(CMV4P_FIRMWARE); MODULE_FIRMWARE(CMV4PV2_FIRMWARE); MODULE_FIRMWARE(CMV4I_FIRMWARE); MODULE_FIRMWARE(CMV4IV2_FIRMWARE); MODULE_FIRMWARE(CMV9P_FIRMWARE); MODULE_FIRMWARE(CMV9PV2_FIRMWARE); MODULE_FIRMWARE(CMV9I_FIRMWARE); MODULE_FIRMWARE(CMV9IV2_FIRMWARE); MODULE_FIRMWARE(CMVEP_FIRMWARE); MODULE_FIRMWARE(CMVEPV2_FIRMWARE); MODULE_FIRMWARE(CMVEI_FIRMWARE); MODULE_FIRMWARE(CMVEIV2_FIRMWARE);
gpl-2.0
AOKP/kernel_samsung_manta
lib/devres.c
2776
9411
#include <linux/pci.h> #include <linux/io.h> #include <linux/gfp.h> #include <linux/export.h> void devm_ioremap_release(struct device *dev, void *res) { iounmap(*(void __iomem **)res); } static int devm_ioremap_match(struct device *dev, void *res, void *match_data) { return *(void **)res == match_data; } /** * devm_ioremap - Managed ioremap() * @dev: Generic device to remap IO address for * @offset: BUS offset to map * @size: Size of map * * Managed ioremap(). Map is automatically unmapped on driver detach. */ void __iomem *devm_ioremap(struct device *dev, resource_size_t offset, unsigned long size) { void __iomem **ptr, *addr; ptr = devres_alloc(devm_ioremap_release, sizeof(*ptr), GFP_KERNEL); if (!ptr) return NULL; addr = ioremap(offset, size); if (addr) { *ptr = addr; devres_add(dev, ptr); } else devres_free(ptr); return addr; } EXPORT_SYMBOL(devm_ioremap); /** * devm_ioremap_nocache - Managed ioremap_nocache() * @dev: Generic device to remap IO address for * @offset: BUS offset to map * @size: Size of map * * Managed ioremap_nocache(). Map is automatically unmapped on driver * detach. */ void __iomem *devm_ioremap_nocache(struct device *dev, resource_size_t offset, unsigned long size) { void __iomem **ptr, *addr; ptr = devres_alloc(devm_ioremap_release, sizeof(*ptr), GFP_KERNEL); if (!ptr) return NULL; addr = ioremap_nocache(offset, size); if (addr) { *ptr = addr; devres_add(dev, ptr); } else devres_free(ptr); return addr; } EXPORT_SYMBOL(devm_ioremap_nocache); /** * devm_iounmap - Managed iounmap() * @dev: Generic device to unmap for * @addr: Address to unmap * * Managed iounmap(). @addr must have been mapped using devm_ioremap*(). */ void devm_iounmap(struct device *dev, void __iomem *addr) { WARN_ON(devres_destroy(dev, devm_ioremap_release, devm_ioremap_match, (void *)addr)); iounmap(addr); } EXPORT_SYMBOL(devm_iounmap); /** * devm_request_and_ioremap() - Check, request region, and ioremap resource * @dev: Generic device to handle the resource for * @res: resource to be handled * * Takes all necessary steps to ioremap a mem resource. Uses managed device, so * everything is undone on driver detach. Checks arguments, so you can feed * it the result from e.g. platform_get_resource() directly. Returns the * remapped pointer or NULL on error. Usage example: * * res = platform_get_resource(pdev, IORESOURCE_MEM, 0); * base = devm_request_and_ioremap(&pdev->dev, res); * if (!base) * return -EADDRNOTAVAIL; */ void __iomem *devm_request_and_ioremap(struct device *dev, struct resource *res) { resource_size_t size; const char *name; void __iomem *dest_ptr; BUG_ON(!dev); if (!res || resource_type(res) != IORESOURCE_MEM) { dev_err(dev, "invalid resource\n"); return NULL; } size = resource_size(res); name = res->name ?: dev_name(dev); if (!devm_request_mem_region(dev, res->start, size, name)) { dev_err(dev, "can't request region for resource %pR\n", res); return NULL; } if (res->flags & IORESOURCE_CACHEABLE) dest_ptr = devm_ioremap(dev, res->start, size); else dest_ptr = devm_ioremap_nocache(dev, res->start, size); if (!dest_ptr) { dev_err(dev, "ioremap failed for resource %pR\n", res); devm_release_mem_region(dev, res->start, size); } return dest_ptr; } EXPORT_SYMBOL(devm_request_and_ioremap); #ifdef CONFIG_HAS_IOPORT /* * Generic iomap devres */ static void devm_ioport_map_release(struct device *dev, void *res) { ioport_unmap(*(void __iomem **)res); } static int devm_ioport_map_match(struct device *dev, void *res, void *match_data) { return *(void **)res == match_data; } /** * devm_ioport_map - Managed ioport_map() * @dev: Generic device to map ioport for * @port: Port to map * @nr: Number of ports to map * * Managed ioport_map(). Map is automatically unmapped on driver * detach. */ void __iomem * devm_ioport_map(struct device *dev, unsigned long port, unsigned int nr) { void __iomem **ptr, *addr; ptr = devres_alloc(devm_ioport_map_release, sizeof(*ptr), GFP_KERNEL); if (!ptr) return NULL; addr = ioport_map(port, nr); if (addr) { *ptr = addr; devres_add(dev, ptr); } else devres_free(ptr); return addr; } EXPORT_SYMBOL(devm_ioport_map); /** * devm_ioport_unmap - Managed ioport_unmap() * @dev: Generic device to unmap for * @addr: Address to unmap * * Managed ioport_unmap(). @addr must have been mapped using * devm_ioport_map(). */ void devm_ioport_unmap(struct device *dev, void __iomem *addr) { ioport_unmap(addr); WARN_ON(devres_destroy(dev, devm_ioport_map_release, devm_ioport_map_match, (void *)addr)); } EXPORT_SYMBOL(devm_ioport_unmap); #ifdef CONFIG_PCI /* * PCI iomap devres */ #define PCIM_IOMAP_MAX PCI_ROM_RESOURCE struct pcim_iomap_devres { void __iomem *table[PCIM_IOMAP_MAX]; }; static void pcim_iomap_release(struct device *gendev, void *res) { struct pci_dev *dev = container_of(gendev, struct pci_dev, dev); struct pcim_iomap_devres *this = res; int i; for (i = 0; i < PCIM_IOMAP_MAX; i++) if (this->table[i]) pci_iounmap(dev, this->table[i]); } /** * pcim_iomap_table - access iomap allocation table * @pdev: PCI device to access iomap table for * * Access iomap allocation table for @dev. If iomap table doesn't * exist and @pdev is managed, it will be allocated. All iomaps * recorded in the iomap table are automatically unmapped on driver * detach. * * This function might sleep when the table is first allocated but can * be safely called without context and guaranteed to succed once * allocated. */ void __iomem * const * pcim_iomap_table(struct pci_dev *pdev) { struct pcim_iomap_devres *dr, *new_dr; dr = devres_find(&pdev->dev, pcim_iomap_release, NULL, NULL); if (dr) return dr->table; new_dr = devres_alloc(pcim_iomap_release, sizeof(*new_dr), GFP_KERNEL); if (!new_dr) return NULL; dr = devres_get(&pdev->dev, new_dr, NULL, NULL); return dr->table; } EXPORT_SYMBOL(pcim_iomap_table); /** * pcim_iomap - Managed pcim_iomap() * @pdev: PCI device to iomap for * @bar: BAR to iomap * @maxlen: Maximum length of iomap * * Managed pci_iomap(). Map is automatically unmapped on driver * detach. */ void __iomem * pcim_iomap(struct pci_dev *pdev, int bar, unsigned long maxlen) { void __iomem **tbl; BUG_ON(bar >= PCIM_IOMAP_MAX); tbl = (void __iomem **)pcim_iomap_table(pdev); if (!tbl || tbl[bar]) /* duplicate mappings not allowed */ return NULL; tbl[bar] = pci_iomap(pdev, bar, maxlen); return tbl[bar]; } EXPORT_SYMBOL(pcim_iomap); /** * pcim_iounmap - Managed pci_iounmap() * @pdev: PCI device to iounmap for * @addr: Address to unmap * * Managed pci_iounmap(). @addr must have been mapped using pcim_iomap(). */ void pcim_iounmap(struct pci_dev *pdev, void __iomem *addr) { void __iomem **tbl; int i; pci_iounmap(pdev, addr); tbl = (void __iomem **)pcim_iomap_table(pdev); BUG_ON(!tbl); for (i = 0; i < PCIM_IOMAP_MAX; i++) if (tbl[i] == addr) { tbl[i] = NULL; return; } WARN_ON(1); } EXPORT_SYMBOL(pcim_iounmap); /** * pcim_iomap_regions - Request and iomap PCI BARs * @pdev: PCI device to map IO resources for * @mask: Mask of BARs to request and iomap * @name: Name used when requesting regions * * Request and iomap regions specified by @mask. */ int pcim_iomap_regions(struct pci_dev *pdev, int mask, const char *name) { void __iomem * const *iomap; int i, rc; iomap = pcim_iomap_table(pdev); if (!iomap) return -ENOMEM; for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) { unsigned long len; if (!(mask & (1 << i))) continue; rc = -EINVAL; len = pci_resource_len(pdev, i); if (!len) goto err_inval; rc = pci_request_region(pdev, i, name); if (rc) goto err_inval; rc = -ENOMEM; if (!pcim_iomap(pdev, i, 0)) goto err_region; } return 0; err_region: pci_release_region(pdev, i); err_inval: while (--i >= 0) { if (!(mask & (1 << i))) continue; pcim_iounmap(pdev, iomap[i]); pci_release_region(pdev, i); } return rc; } EXPORT_SYMBOL(pcim_iomap_regions); /** * pcim_iomap_regions_request_all - Request all BARs and iomap specified ones * @pdev: PCI device to map IO resources for * @mask: Mask of BARs to iomap * @name: Name used when requesting regions * * Request all PCI BARs and iomap regions specified by @mask. */ int pcim_iomap_regions_request_all(struct pci_dev *pdev, int mask, const char *name) { int request_mask = ((1 << 6) - 1) & ~mask; int rc; rc = pci_request_selected_regions(pdev, request_mask, name); if (rc) return rc; rc = pcim_iomap_regions(pdev, mask, name); if (rc) pci_release_selected_regions(pdev, request_mask); return rc; } EXPORT_SYMBOL(pcim_iomap_regions_request_all); /** * pcim_iounmap_regions - Unmap and release PCI BARs * @pdev: PCI device to map IO resources for * @mask: Mask of BARs to unmap and release * * Unmap and release regions specified by @mask. */ void pcim_iounmap_regions(struct pci_dev *pdev, int mask) { void __iomem * const *iomap; int i; iomap = pcim_iomap_table(pdev); if (!iomap) return; for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) { if (!(mask & (1 << i))) continue; pcim_iounmap(pdev, iomap[i]); pci_release_region(pdev, i); } } EXPORT_SYMBOL(pcim_iounmap_regions); #endif /* CONFIG_PCI */ #endif /* CONFIG_HAS_IOPORT */
gpl-2.0
GearCM/android_kernel_samsung_aries
drivers/staging/rtl8712/rtl871x_io.c
3032
5001
/****************************************************************************** * rtl871x_io.c * * Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved. * Linux device driver for RTL8192SU * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * Modifications for inclusion into the Linux staging tree are * Copyright(c) 2010 Larry Finger. All rights reserved. * * Contact information: * WLAN FAE <wlanfae@realtek.com> * Larry Finger <Larry.Finger@lwfinger.net> * ******************************************************************************/ /* * * The purpose of rtl871x_io.c * * a. provides the API * b. provides the protocol engine * c. provides the software interface between caller and the hardware interface * * For r8712u, both sync/async operations are provided. * * Only sync read/write_mem operations are provided. * */ #define _RTL871X_IO_C_ #include "osdep_service.h" #include "drv_types.h" #include "rtl871x_io.h" #include "osdep_intf.h" #include "usb_ops.h" static uint _init_intf_hdl(struct _adapter *padapter, struct intf_hdl *pintf_hdl) { struct intf_priv *pintf_priv; void (*set_intf_option)(u32 *poption) = NULL; void (*set_intf_funs)(struct intf_hdl *pintf_hdl); void (*set_intf_ops)(struct _io_ops *pops); uint (*init_intf_priv)(struct intf_priv *pintfpriv); set_intf_option = &(r8712_usb_set_intf_option); set_intf_funs = &(r8712_usb_set_intf_funs); set_intf_ops = &r8712_usb_set_intf_ops; init_intf_priv = &r8712_usb_init_intf_priv; pintf_priv = pintf_hdl->pintfpriv = (struct intf_priv *) _malloc(sizeof(struct intf_priv)); if (pintf_priv == NULL) goto _init_intf_hdl_fail; pintf_hdl->adapter = (u8 *)padapter; set_intf_option(&pintf_hdl->intf_option); set_intf_funs(pintf_hdl); set_intf_ops(&pintf_hdl->io_ops); pintf_priv->intf_dev = (u8 *)&(padapter->dvobjpriv); if (init_intf_priv(pintf_priv) == _FAIL) goto _init_intf_hdl_fail; return _SUCCESS; _init_intf_hdl_fail: kfree(pintf_priv); return _FAIL; } static void _unload_intf_hdl(struct intf_priv *pintfpriv) { void (*unload_intf_priv)(struct intf_priv *pintfpriv); unload_intf_priv = &r8712_usb_unload_intf_priv; unload_intf_priv(pintfpriv); kfree(pintfpriv); } static uint register_intf_hdl(u8 *dev, struct intf_hdl *pintfhdl) { struct _adapter *adapter = (struct _adapter *)dev; pintfhdl->intf_option = 0; pintfhdl->adapter = dev; pintfhdl->intf_dev = (u8 *)&(adapter->dvobjpriv); if (_init_intf_hdl(adapter, pintfhdl) == false) goto register_intf_hdl_fail; return _SUCCESS; register_intf_hdl_fail: return false; } static void unregister_intf_hdl(struct intf_hdl *pintfhdl) { _unload_intf_hdl(pintfhdl->pintfpriv); memset((u8 *)pintfhdl, 0, sizeof(struct intf_hdl)); } uint r8712_alloc_io_queue(struct _adapter *adapter) { u32 i; struct io_queue *pio_queue; struct io_req *pio_req; pio_queue = (struct io_queue *)_malloc(sizeof(struct io_queue)); if (pio_queue == NULL) goto alloc_io_queue_fail; _init_listhead(&pio_queue->free_ioreqs); _init_listhead(&pio_queue->processing); _init_listhead(&pio_queue->pending); spin_lock_init(&pio_queue->lock); pio_queue->pallocated_free_ioreqs_buf = (u8 *)_malloc(NUM_IOREQ * (sizeof(struct io_req)) + 4); if ((pio_queue->pallocated_free_ioreqs_buf) == NULL) goto alloc_io_queue_fail; memset(pio_queue->pallocated_free_ioreqs_buf, 0, (NUM_IOREQ * (sizeof(struct io_req)) + 4)); pio_queue->free_ioreqs_buf = pio_queue->pallocated_free_ioreqs_buf + 4 - ((addr_t)(pio_queue->pallocated_free_ioreqs_buf) & 3); pio_req = (struct io_req *)(pio_queue->free_ioreqs_buf); for (i = 0; i < NUM_IOREQ; i++) { _init_listhead(&pio_req->list); sema_init(&pio_req->sema, 0); list_insert_tail(&pio_req->list, &pio_queue->free_ioreqs); pio_req++; } if ((register_intf_hdl((u8 *)adapter, &(pio_queue->intf))) == _FAIL) goto alloc_io_queue_fail; adapter->pio_queue = pio_queue; return _SUCCESS; alloc_io_queue_fail: if (pio_queue) { kfree(pio_queue->pallocated_free_ioreqs_buf); kfree((u8 *)pio_queue); } adapter->pio_queue = NULL; return _FAIL; } void r8712_free_io_queue(struct _adapter *adapter) { struct io_queue *pio_queue = (struct io_queue *)(adapter->pio_queue); if (pio_queue) { kfree(pio_queue->pallocated_free_ioreqs_buf); adapter->pio_queue = NULL; unregister_intf_hdl(&pio_queue->intf); kfree((u8 *)pio_queue); } }
gpl-2.0
chunyeow/greenmesh
drivers/net/irda/sir_dev.c
4056
24859
/********************************************************************* * * sir_dev.c: irda sir network device * * Copyright (c) 2002 Martin Diehl * * 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/hardirq.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/delay.h> #include <net/irda/irda.h> #include <net/irda/wrapper.h> #include <net/irda/irda_device.h> #include "sir-dev.h" static struct workqueue_struct *irda_sir_wq; /* STATE MACHINE */ /* substate handler of the config-fsm to handle the cases where we want * to wait for transmit completion before changing the port configuration */ static int sirdev_tx_complete_fsm(struct sir_dev *dev) { struct sir_fsm *fsm = &dev->fsm; unsigned next_state, delay; unsigned bytes_left; do { next_state = fsm->substate; /* default: stay in current substate */ delay = 0; switch(fsm->substate) { case SIRDEV_STATE_WAIT_XMIT: if (dev->drv->chars_in_buffer) bytes_left = dev->drv->chars_in_buffer(dev); else bytes_left = 0; if (!bytes_left) { next_state = SIRDEV_STATE_WAIT_UNTIL_SENT; break; } if (dev->speed > 115200) delay = (bytes_left*8*10000) / (dev->speed/100); else if (dev->speed > 0) delay = (bytes_left*10*10000) / (dev->speed/100); else delay = 0; /* expected delay (usec) until remaining bytes are sent */ if (delay < 100) { udelay(delay); delay = 0; break; } /* sleep some longer delay (msec) */ delay = (delay+999) / 1000; break; case SIRDEV_STATE_WAIT_UNTIL_SENT: /* block until underlaying hardware buffer are empty */ if (dev->drv->wait_until_sent) dev->drv->wait_until_sent(dev); next_state = SIRDEV_STATE_TX_DONE; break; case SIRDEV_STATE_TX_DONE: return 0; default: IRDA_ERROR("%s - undefined state\n", __func__); return -EINVAL; } fsm->substate = next_state; } while (delay == 0); return delay; } /* * Function sirdev_config_fsm * * State machine to handle the configuration of the device (and attached dongle, if any). * This handler is scheduled for execution in kIrDAd context, so we can sleep. * however, kIrDAd is shared by all sir_dev devices so we better don't sleep there too * long. Instead, for longer delays we start a timer to reschedule us later. * On entry, fsm->sem is always locked and the netdev xmit queue stopped. * Both must be unlocked/restarted on completion - but only on final exit. */ static void sirdev_config_fsm(struct work_struct *work) { struct sir_dev *dev = container_of(work, struct sir_dev, fsm.work.work); struct sir_fsm *fsm = &dev->fsm; int next_state; int ret = -1; unsigned delay; IRDA_DEBUG(2, "%s(), <%ld>\n", __func__, jiffies); do { IRDA_DEBUG(3, "%s - state=0x%04x / substate=0x%04x\n", __func__, fsm->state, fsm->substate); next_state = fsm->state; delay = 0; switch(fsm->state) { case SIRDEV_STATE_DONGLE_OPEN: if (dev->dongle_drv != NULL) { ret = sirdev_put_dongle(dev); if (ret) { fsm->result = -EINVAL; next_state = SIRDEV_STATE_ERROR; break; } } /* Initialize dongle */ ret = sirdev_get_dongle(dev, fsm->param); if (ret) { fsm->result = ret; next_state = SIRDEV_STATE_ERROR; break; } /* Dongles are powered through the modem control lines which * were just set during open. Before resetting, let's wait for * the power to stabilize. This is what some dongle drivers did * in open before, while others didn't - should be safe anyway. */ delay = 50; fsm->substate = SIRDEV_STATE_DONGLE_RESET; next_state = SIRDEV_STATE_DONGLE_RESET; fsm->param = 9600; break; case SIRDEV_STATE_DONGLE_CLOSE: /* shouldn't we just treat this as success=? */ if (dev->dongle_drv == NULL) { fsm->result = -EINVAL; next_state = SIRDEV_STATE_ERROR; break; } ret = sirdev_put_dongle(dev); if (ret) { fsm->result = ret; next_state = SIRDEV_STATE_ERROR; break; } next_state = SIRDEV_STATE_DONE; break; case SIRDEV_STATE_SET_DTR_RTS: ret = sirdev_set_dtr_rts(dev, (fsm->param&0x02) ? TRUE : FALSE, (fsm->param&0x01) ? TRUE : FALSE); next_state = SIRDEV_STATE_DONE; break; case SIRDEV_STATE_SET_SPEED: fsm->substate = SIRDEV_STATE_WAIT_XMIT; next_state = SIRDEV_STATE_DONGLE_CHECK; break; case SIRDEV_STATE_DONGLE_CHECK: ret = sirdev_tx_complete_fsm(dev); if (ret < 0) { fsm->result = ret; next_state = SIRDEV_STATE_ERROR; break; } if ((delay=ret) != 0) break; if (dev->dongle_drv) { fsm->substate = SIRDEV_STATE_DONGLE_RESET; next_state = SIRDEV_STATE_DONGLE_RESET; } else { dev->speed = fsm->param; next_state = SIRDEV_STATE_PORT_SPEED; } break; case SIRDEV_STATE_DONGLE_RESET: if (dev->dongle_drv->reset) { ret = dev->dongle_drv->reset(dev); if (ret < 0) { fsm->result = ret; next_state = SIRDEV_STATE_ERROR; break; } } else ret = 0; if ((delay=ret) == 0) { /* set serial port according to dongle default speed */ if (dev->drv->set_speed) dev->drv->set_speed(dev, dev->speed); fsm->substate = SIRDEV_STATE_DONGLE_SPEED; next_state = SIRDEV_STATE_DONGLE_SPEED; } break; case SIRDEV_STATE_DONGLE_SPEED: if (dev->dongle_drv->reset) { ret = dev->dongle_drv->set_speed(dev, fsm->param); if (ret < 0) { fsm->result = ret; next_state = SIRDEV_STATE_ERROR; break; } } else ret = 0; if ((delay=ret) == 0) next_state = SIRDEV_STATE_PORT_SPEED; break; case SIRDEV_STATE_PORT_SPEED: /* Finally we are ready to change the serial port speed */ if (dev->drv->set_speed) dev->drv->set_speed(dev, dev->speed); dev->new_speed = 0; next_state = SIRDEV_STATE_DONE; break; case SIRDEV_STATE_DONE: /* Signal network layer so it can send more frames */ netif_wake_queue(dev->netdev); next_state = SIRDEV_STATE_COMPLETE; break; default: IRDA_ERROR("%s - undefined state\n", __func__); fsm->result = -EINVAL; /* fall thru */ case SIRDEV_STATE_ERROR: IRDA_ERROR("%s - error: %d\n", __func__, fsm->result); #if 0 /* don't enable this before we have netdev->tx_timeout to recover */ netif_stop_queue(dev->netdev); #else netif_wake_queue(dev->netdev); #endif /* fall thru */ case SIRDEV_STATE_COMPLETE: /* config change finished, so we are not busy any longer */ sirdev_enable_rx(dev); up(&fsm->sem); return; } fsm->state = next_state; } while(!delay); queue_delayed_work(irda_sir_wq, &fsm->work, msecs_to_jiffies(delay)); } /* schedule some device configuration task for execution by kIrDAd * on behalf of the above state machine. * can be called from process or interrupt/tasklet context. */ int sirdev_schedule_request(struct sir_dev *dev, int initial_state, unsigned param) { struct sir_fsm *fsm = &dev->fsm; IRDA_DEBUG(2, "%s - state=0x%04x / param=%u\n", __func__, initial_state, param); if (down_trylock(&fsm->sem)) { if (in_interrupt() || in_atomic() || irqs_disabled()) { IRDA_DEBUG(1, "%s(), state machine busy!\n", __func__); return -EWOULDBLOCK; } else down(&fsm->sem); } if (fsm->state == SIRDEV_STATE_DEAD) { /* race with sirdev_close should never happen */ IRDA_ERROR("%s(), instance staled!\n", __func__); up(&fsm->sem); return -ESTALE; /* or better EPIPE? */ } netif_stop_queue(dev->netdev); atomic_set(&dev->enable_rx, 0); fsm->state = initial_state; fsm->param = param; fsm->result = 0; INIT_DELAYED_WORK(&fsm->work, sirdev_config_fsm); queue_delayed_work(irda_sir_wq, &fsm->work, 0); return 0; } /***************************************************************************/ void sirdev_enable_rx(struct sir_dev *dev) { if (unlikely(atomic_read(&dev->enable_rx))) return; /* flush rx-buffer - should also help in case of problems with echo cancelation */ dev->rx_buff.data = dev->rx_buff.head; dev->rx_buff.len = 0; dev->rx_buff.in_frame = FALSE; dev->rx_buff.state = OUTSIDE_FRAME; atomic_set(&dev->enable_rx, 1); } static int sirdev_is_receiving(struct sir_dev *dev) { if (!atomic_read(&dev->enable_rx)) return 0; return dev->rx_buff.state != OUTSIDE_FRAME; } int sirdev_set_dongle(struct sir_dev *dev, IRDA_DONGLE type) { int err; IRDA_DEBUG(3, "%s : requesting dongle %d.\n", __func__, type); err = sirdev_schedule_dongle_open(dev, type); if (unlikely(err)) return err; down(&dev->fsm.sem); /* block until config change completed */ err = dev->fsm.result; up(&dev->fsm.sem); return err; } EXPORT_SYMBOL(sirdev_set_dongle); /* used by dongle drivers for dongle programming */ int sirdev_raw_write(struct sir_dev *dev, const char *buf, int len) { unsigned long flags; int ret; if (unlikely(len > dev->tx_buff.truesize)) return -ENOSPC; spin_lock_irqsave(&dev->tx_lock, flags); /* serialize with other tx operations */ while (dev->tx_buff.len > 0) { /* wait until tx idle */ spin_unlock_irqrestore(&dev->tx_lock, flags); msleep(10); spin_lock_irqsave(&dev->tx_lock, flags); } dev->tx_buff.data = dev->tx_buff.head; memcpy(dev->tx_buff.data, buf, len); dev->tx_buff.len = len; ret = dev->drv->do_write(dev, dev->tx_buff.data, dev->tx_buff.len); if (ret > 0) { IRDA_DEBUG(3, "%s(), raw-tx started\n", __func__); dev->tx_buff.data += ret; dev->tx_buff.len -= ret; dev->raw_tx = 1; ret = len; /* all data is going to be sent */ } spin_unlock_irqrestore(&dev->tx_lock, flags); return ret; } EXPORT_SYMBOL(sirdev_raw_write); /* seems some dongle drivers may need this */ int sirdev_raw_read(struct sir_dev *dev, char *buf, int len) { int count; if (atomic_read(&dev->enable_rx)) return -EIO; /* fail if we expect irda-frames */ count = (len < dev->rx_buff.len) ? len : dev->rx_buff.len; if (count > 0) { memcpy(buf, dev->rx_buff.data, count); dev->rx_buff.data += count; dev->rx_buff.len -= count; } /* remaining stuff gets flushed when re-enabling normal rx */ return count; } EXPORT_SYMBOL(sirdev_raw_read); int sirdev_set_dtr_rts(struct sir_dev *dev, int dtr, int rts) { int ret = -ENXIO; if (dev->drv->set_dtr_rts) ret = dev->drv->set_dtr_rts(dev, dtr, rts); return ret; } EXPORT_SYMBOL(sirdev_set_dtr_rts); /**********************************************************************/ /* called from client driver - likely with bh-context - to indicate * it made some progress with transmission. Hence we send the next * chunk, if any, or complete the skb otherwise */ void sirdev_write_complete(struct sir_dev *dev) { unsigned long flags; struct sk_buff *skb; int actual = 0; int err; spin_lock_irqsave(&dev->tx_lock, flags); IRDA_DEBUG(3, "%s() - dev->tx_buff.len = %d\n", __func__, dev->tx_buff.len); if (likely(dev->tx_buff.len > 0)) { /* Write data left in transmit buffer */ actual = dev->drv->do_write(dev, dev->tx_buff.data, dev->tx_buff.len); if (likely(actual>0)) { dev->tx_buff.data += actual; dev->tx_buff.len -= actual; } else if (unlikely(actual<0)) { /* could be dropped later when we have tx_timeout to recover */ IRDA_ERROR("%s: drv->do_write failed (%d)\n", __func__, actual); if ((skb=dev->tx_skb) != NULL) { dev->tx_skb = NULL; dev_kfree_skb_any(skb); dev->netdev->stats.tx_errors++; dev->netdev->stats.tx_dropped++; } dev->tx_buff.len = 0; } if (dev->tx_buff.len > 0) goto done; /* more data to send later */ } if (unlikely(dev->raw_tx != 0)) { /* in raw mode we are just done now after the buffer was sent * completely. Since this was requested by some dongle driver * running under the control of the irda-thread we must take * care here not to re-enable the queue. The queue will be * restarted when the irda-thread has completed the request. */ IRDA_DEBUG(3, "%s(), raw-tx done\n", __func__); dev->raw_tx = 0; goto done; /* no post-frame handling in raw mode */ } /* we have finished now sending this skb. * update statistics and free the skb. * finally we check and trigger a pending speed change, if any. * if not we switch to rx mode and wake the queue for further * packets. * note the scheduled speed request blocks until the lower * client driver and the corresponding hardware has really * finished sending all data (xmit fifo drained f.e.) * before the speed change gets finally done and the queue * re-activated. */ IRDA_DEBUG(5, "%s(), finished with frame!\n", __func__); if ((skb=dev->tx_skb) != NULL) { dev->tx_skb = NULL; dev->netdev->stats.tx_packets++; dev->netdev->stats.tx_bytes += skb->len; dev_kfree_skb_any(skb); } if (unlikely(dev->new_speed > 0)) { IRDA_DEBUG(5, "%s(), Changing speed!\n", __func__); err = sirdev_schedule_speed(dev, dev->new_speed); if (unlikely(err)) { /* should never happen * forget the speed change and hope the stack recovers */ IRDA_ERROR("%s - schedule speed change failed: %d\n", __func__, err); netif_wake_queue(dev->netdev); } /* else: success * speed change in progress now * on completion dev->new_speed gets cleared, * rx-reenabled and the queue restarted */ } else { sirdev_enable_rx(dev); netif_wake_queue(dev->netdev); } done: spin_unlock_irqrestore(&dev->tx_lock, flags); } EXPORT_SYMBOL(sirdev_write_complete); /* called from client driver - likely with bh-context - to give us * some more received bytes. We put them into the rx-buffer, * normally unwrapping and building LAP-skb's (unless rx disabled) */ int sirdev_receive(struct sir_dev *dev, const unsigned char *cp, size_t count) { if (!dev || !dev->netdev) { IRDA_WARNING("%s(), not ready yet!\n", __func__); return -1; } if (!dev->irlap) { IRDA_WARNING("%s - too early: %p / %zd!\n", __func__, cp, count); return -1; } if (cp==NULL) { /* error already at lower level receive * just update stats and set media busy */ irda_device_set_media_busy(dev->netdev, TRUE); dev->netdev->stats.rx_dropped++; IRDA_DEBUG(0, "%s; rx-drop: %zd\n", __func__, count); return 0; } /* Read the characters into the buffer */ if (likely(atomic_read(&dev->enable_rx))) { while (count--) /* Unwrap and destuff one byte */ async_unwrap_char(dev->netdev, &dev->netdev->stats, &dev->rx_buff, *cp++); } else { while (count--) { /* rx not enabled: save the raw bytes and never * trigger any netif_rx. The received bytes are flushed * later when we re-enable rx but might be read meanwhile * by the dongle driver. */ dev->rx_buff.data[dev->rx_buff.len++] = *cp++; /* What should we do when the buffer is full? */ if (unlikely(dev->rx_buff.len == dev->rx_buff.truesize)) dev->rx_buff.len = 0; } } return 0; } EXPORT_SYMBOL(sirdev_receive); /**********************************************************************/ /* callbacks from network layer */ static netdev_tx_t sirdev_hard_xmit(struct sk_buff *skb, struct net_device *ndev) { struct sir_dev *dev = netdev_priv(ndev); unsigned long flags; int actual = 0; int err; s32 speed; IRDA_ASSERT(dev != NULL, return NETDEV_TX_OK;); netif_stop_queue(ndev); IRDA_DEBUG(3, "%s(), skb->len = %d\n", __func__, skb->len); speed = irda_get_next_speed(skb); if ((speed != dev->speed) && (speed != -1)) { if (!skb->len) { err = sirdev_schedule_speed(dev, speed); if (unlikely(err == -EWOULDBLOCK)) { /* Failed to initiate the speed change, likely the fsm * is still busy (pretty unlikely, but...) * We refuse to accept the skb and return with the queue * stopped so the network layer will retry after the * fsm completes and wakes the queue. */ return NETDEV_TX_BUSY; } else if (unlikely(err)) { /* other fatal error - forget the speed change and * hope the stack will recover somehow */ netif_start_queue(ndev); } /* else: success * speed change in progress now * on completion the queue gets restarted */ dev_kfree_skb_any(skb); return NETDEV_TX_OK; } else dev->new_speed = speed; } /* Init tx buffer*/ dev->tx_buff.data = dev->tx_buff.head; /* Check problems */ if(spin_is_locked(&dev->tx_lock)) { IRDA_DEBUG(3, "%s(), write not completed\n", __func__); } /* serialize with write completion */ spin_lock_irqsave(&dev->tx_lock, flags); /* Copy skb to tx_buff while wrapping, stuffing and making CRC */ dev->tx_buff.len = async_wrap_skb(skb, dev->tx_buff.data, dev->tx_buff.truesize); /* transmission will start now - disable receive. * if we are just in the middle of an incoming frame, * treat it as collision. probably it's a good idea to * reset the rx_buf OUTSIDE_FRAME in this case too? */ atomic_set(&dev->enable_rx, 0); if (unlikely(sirdev_is_receiving(dev))) dev->netdev->stats.collisions++; actual = dev->drv->do_write(dev, dev->tx_buff.data, dev->tx_buff.len); if (likely(actual > 0)) { dev->tx_skb = skb; dev->tx_buff.data += actual; dev->tx_buff.len -= actual; } else if (unlikely(actual < 0)) { /* could be dropped later when we have tx_timeout to recover */ IRDA_ERROR("%s: drv->do_write failed (%d)\n", __func__, actual); dev_kfree_skb_any(skb); dev->netdev->stats.tx_errors++; dev->netdev->stats.tx_dropped++; netif_wake_queue(ndev); } spin_unlock_irqrestore(&dev->tx_lock, flags); return NETDEV_TX_OK; } /* called from network layer with rtnl hold */ static int sirdev_ioctl(struct net_device *ndev, struct ifreq *rq, int cmd) { struct if_irda_req *irq = (struct if_irda_req *) rq; struct sir_dev *dev = netdev_priv(ndev); int ret = 0; IRDA_ASSERT(dev != NULL, return -1;); IRDA_DEBUG(3, "%s(), %s, (cmd=0x%X)\n", __func__, ndev->name, cmd); switch (cmd) { case SIOCSBANDWIDTH: /* Set bandwidth */ if (!capable(CAP_NET_ADMIN)) ret = -EPERM; else ret = sirdev_schedule_speed(dev, irq->ifr_baudrate); /* cannot sleep here for completion * we are called from network layer with rtnl hold */ break; case SIOCSDONGLE: /* Set dongle */ if (!capable(CAP_NET_ADMIN)) ret = -EPERM; else ret = sirdev_schedule_dongle_open(dev, irq->ifr_dongle); /* cannot sleep here for completion * we are called from network layer with rtnl hold */ break; case SIOCSMEDIABUSY: /* Set media busy */ if (!capable(CAP_NET_ADMIN)) ret = -EPERM; else irda_device_set_media_busy(dev->netdev, TRUE); break; case SIOCGRECEIVING: /* Check if we are receiving right now */ irq->ifr_receiving = sirdev_is_receiving(dev); break; case SIOCSDTRRTS: if (!capable(CAP_NET_ADMIN)) ret = -EPERM; else ret = sirdev_schedule_dtr_rts(dev, irq->ifr_dtr, irq->ifr_rts); /* cannot sleep here for completion * we are called from network layer with rtnl hold */ break; case SIOCSMODE: #if 0 if (!capable(CAP_NET_ADMIN)) ret = -EPERM; else ret = sirdev_schedule_mode(dev, irq->ifr_mode); /* cannot sleep here for completion * we are called from network layer with rtnl hold */ break; #endif default: ret = -EOPNOTSUPP; } return ret; } /* ----------------------------------------------------------------------------- */ #define SIRBUF_ALLOCSIZE 4269 /* worst case size of a wrapped IrLAP frame */ static int sirdev_alloc_buffers(struct sir_dev *dev) { dev->tx_buff.truesize = SIRBUF_ALLOCSIZE; dev->rx_buff.truesize = IRDA_SKB_MAX_MTU; /* Bootstrap ZeroCopy Rx */ dev->rx_buff.skb = __netdev_alloc_skb(dev->netdev, dev->rx_buff.truesize, GFP_KERNEL); if (dev->rx_buff.skb == NULL) return -ENOMEM; skb_reserve(dev->rx_buff.skb, 1); dev->rx_buff.head = dev->rx_buff.skb->data; dev->tx_buff.head = kmalloc(dev->tx_buff.truesize, GFP_KERNEL); if (dev->tx_buff.head == NULL) { kfree_skb(dev->rx_buff.skb); dev->rx_buff.skb = NULL; dev->rx_buff.head = NULL; return -ENOMEM; } dev->tx_buff.data = dev->tx_buff.head; dev->rx_buff.data = dev->rx_buff.head; dev->tx_buff.len = 0; dev->rx_buff.len = 0; dev->rx_buff.in_frame = FALSE; dev->rx_buff.state = OUTSIDE_FRAME; return 0; }; static void sirdev_free_buffers(struct sir_dev *dev) { kfree_skb(dev->rx_buff.skb); kfree(dev->tx_buff.head); dev->rx_buff.head = dev->tx_buff.head = NULL; dev->rx_buff.skb = NULL; } static int sirdev_open(struct net_device *ndev) { struct sir_dev *dev = netdev_priv(ndev); const struct sir_driver *drv = dev->drv; if (!drv) return -ENODEV; /* increase the reference count of the driver module before doing serious stuff */ if (!try_module_get(drv->owner)) return -ESTALE; IRDA_DEBUG(2, "%s()\n", __func__); if (sirdev_alloc_buffers(dev)) goto errout_dec; if (!dev->drv->start_dev || dev->drv->start_dev(dev)) goto errout_free; sirdev_enable_rx(dev); dev->raw_tx = 0; netif_start_queue(ndev); dev->irlap = irlap_open(ndev, &dev->qos, dev->hwname); if (!dev->irlap) goto errout_stop; netif_wake_queue(ndev); IRDA_DEBUG(2, "%s - done, speed = %d\n", __func__, dev->speed); return 0; errout_stop: atomic_set(&dev->enable_rx, 0); if (dev->drv->stop_dev) dev->drv->stop_dev(dev); errout_free: sirdev_free_buffers(dev); errout_dec: module_put(drv->owner); return -EAGAIN; } static int sirdev_close(struct net_device *ndev) { struct sir_dev *dev = netdev_priv(ndev); const struct sir_driver *drv; // IRDA_DEBUG(0, "%s\n", __func__); netif_stop_queue(ndev); down(&dev->fsm.sem); /* block on pending config completion */ atomic_set(&dev->enable_rx, 0); if (unlikely(!dev->irlap)) goto out; irlap_close(dev->irlap); dev->irlap = NULL; drv = dev->drv; if (unlikely(!drv || !dev->priv)) goto out; if (drv->stop_dev) drv->stop_dev(dev); sirdev_free_buffers(dev); module_put(drv->owner); out: dev->speed = 0; up(&dev->fsm.sem); return 0; } static const struct net_device_ops sirdev_ops = { .ndo_start_xmit = sirdev_hard_xmit, .ndo_open = sirdev_open, .ndo_stop = sirdev_close, .ndo_do_ioctl = sirdev_ioctl, }; /* ----------------------------------------------------------------------------- */ struct sir_dev * sirdev_get_instance(const struct sir_driver *drv, const char *name) { struct net_device *ndev; struct sir_dev *dev; IRDA_DEBUG(0, "%s - %s\n", __func__, name); /* instead of adding tests to protect against drv->do_write==NULL * at several places we refuse to create a sir_dev instance for * drivers which don't implement do_write. */ if (!drv || !drv->do_write) return NULL; /* * Allocate new instance of the device */ ndev = alloc_irdadev(sizeof(*dev)); if (ndev == NULL) { IRDA_ERROR("%s - Can't allocate memory for IrDA control block!\n", __func__); goto out; } dev = netdev_priv(ndev); irda_init_max_qos_capabilies(&dev->qos); dev->qos.baud_rate.bits = IR_9600|IR_19200|IR_38400|IR_57600|IR_115200; dev->qos.min_turn_time.bits = drv->qos_mtt_bits; irda_qos_bits_to_value(&dev->qos); strncpy(dev->hwname, name, sizeof(dev->hwname)-1); atomic_set(&dev->enable_rx, 0); dev->tx_skb = NULL; spin_lock_init(&dev->tx_lock); sema_init(&dev->fsm.sem, 1); dev->drv = drv; dev->netdev = ndev; /* Override the network functions we need to use */ ndev->netdev_ops = &sirdev_ops; if (register_netdev(ndev)) { IRDA_ERROR("%s(), register_netdev() failed!\n", __func__); goto out_freenetdev; } return dev; out_freenetdev: free_netdev(ndev); out: return NULL; } EXPORT_SYMBOL(sirdev_get_instance); int sirdev_put_instance(struct sir_dev *dev) { int err = 0; IRDA_DEBUG(0, "%s\n", __func__); atomic_set(&dev->enable_rx, 0); netif_carrier_off(dev->netdev); netif_device_detach(dev->netdev); if (dev->dongle_drv) err = sirdev_schedule_dongle_close(dev); if (err) IRDA_ERROR("%s - error %d\n", __func__, err); sirdev_close(dev->netdev); down(&dev->fsm.sem); dev->fsm.state = SIRDEV_STATE_DEAD; /* mark staled */ dev->dongle_drv = NULL; dev->priv = NULL; up(&dev->fsm.sem); /* Remove netdevice */ unregister_netdev(dev->netdev); free_netdev(dev->netdev); return 0; } EXPORT_SYMBOL(sirdev_put_instance); static int __init sir_wq_init(void) { irda_sir_wq = create_singlethread_workqueue("irda_sir_wq"); if (!irda_sir_wq) return -ENOMEM; return 0; } static void __exit sir_wq_exit(void) { destroy_workqueue(irda_sir_wq); } module_init(sir_wq_init); module_exit(sir_wq_exit); MODULE_AUTHOR("Martin Diehl <info@mdiehl.de>"); MODULE_DESCRIPTION("IrDA SIR core"); MODULE_LICENSE("GPL");
gpl-2.0
Global-KANGs/droid2we_kernel
drivers/net/wireless/b43/tables.c
4312
14623
/* Broadcom B43 wireless driver Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>, Copyright (c) 2005-2007 Stefano Brivio <stefano.brivio@polimi.it> Copyright (c) 2006, 2006 Michael Buesch <mb@bu3sch.de> Copyright (c) 2005 Danny van Dyk <kugelfang@gentoo.org> Copyright (c) 2005 Andreas Jaggi <andreas.jaggi@waterwave.ch> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 "tables.h" #include "phy_g.h" const u32 b43_tab_rotor[] = { 0xFEB93FFD, 0xFEC63FFD, /* 0 */ 0xFED23FFD, 0xFEDF3FFD, 0xFEEC3FFE, 0xFEF83FFE, 0xFF053FFE, 0xFF113FFE, 0xFF1E3FFE, 0xFF2A3FFF, /* 8 */ 0xFF373FFF, 0xFF443FFF, 0xFF503FFF, 0xFF5D3FFF, 0xFF693FFF, 0xFF763FFF, 0xFF824000, 0xFF8F4000, /* 16 */ 0xFF9B4000, 0xFFA84000, 0xFFB54000, 0xFFC14000, 0xFFCE4000, 0xFFDA4000, 0xFFE74000, 0xFFF34000, /* 24 */ 0x00004000, 0x000D4000, 0x00194000, 0x00264000, 0x00324000, 0x003F4000, 0x004B4000, 0x00584000, /* 32 */ 0x00654000, 0x00714000, 0x007E4000, 0x008A3FFF, 0x00973FFF, 0x00A33FFF, 0x00B03FFF, 0x00BC3FFF, /* 40 */ 0x00C93FFF, 0x00D63FFF, 0x00E23FFE, 0x00EF3FFE, 0x00FB3FFE, 0x01083FFE, 0x01143FFE, 0x01213FFD, /* 48 */ 0x012E3FFD, 0x013A3FFD, 0x01473FFD, }; const u32 b43_tab_retard[] = { 0xDB93CB87, 0xD666CF64, /* 0 */ 0xD1FDD358, 0xCDA6D826, 0xCA38DD9F, 0xC729E2B4, 0xC469E88E, 0xC26AEE2B, 0xC0DEF46C, 0xC073FA62, /* 8 */ 0xC01D00D5, 0xC0760743, 0xC1560D1E, 0xC2E51369, 0xC4ED18FF, 0xC7AC1ED7, 0xCB2823B2, 0xCEFA28D9, /* 16 */ 0xD2F62D3F, 0xD7BB3197, 0xDCE53568, 0xE1FE3875, 0xE7D13B35, 0xED663D35, 0xF39B3EC4, 0xF98E3FA7, /* 24 */ 0x00004000, 0x06723FA7, 0x0C653EC4, 0x129A3D35, 0x182F3B35, 0x1E023875, 0x231B3568, 0x28453197, /* 32 */ 0x2D0A2D3F, 0x310628D9, 0x34D823B2, 0x38541ED7, 0x3B1318FF, 0x3D1B1369, 0x3EAA0D1E, 0x3F8A0743, /* 40 */ 0x3FE300D5, 0x3F8DFA62, 0x3F22F46C, 0x3D96EE2B, 0x3B97E88E, 0x38D7E2B4, 0x35C8DD9F, 0x325AD826, /* 48 */ 0x2E03D358, 0x299ACF64, 0x246DCB87, }; const u16 b43_tab_finefreqa[] = { 0x0082, 0x0082, 0x0102, 0x0182, /* 0 */ 0x0202, 0x0282, 0x0302, 0x0382, 0x0402, 0x0482, 0x0502, 0x0582, 0x05E2, 0x0662, 0x06E2, 0x0762, 0x07E2, 0x0842, 0x08C2, 0x0942, /* 16 */ 0x09C2, 0x0A22, 0x0AA2, 0x0B02, 0x0B82, 0x0BE2, 0x0C62, 0x0CC2, 0x0D42, 0x0DA2, 0x0E02, 0x0E62, 0x0EE2, 0x0F42, 0x0FA2, 0x1002, /* 32 */ 0x1062, 0x10C2, 0x1122, 0x1182, 0x11E2, 0x1242, 0x12A2, 0x12E2, 0x1342, 0x13A2, 0x1402, 0x1442, 0x14A2, 0x14E2, 0x1542, 0x1582, /* 48 */ 0x15E2, 0x1622, 0x1662, 0x16C1, 0x1701, 0x1741, 0x1781, 0x17E1, 0x1821, 0x1861, 0x18A1, 0x18E1, 0x1921, 0x1961, 0x19A1, 0x19E1, /* 64 */ 0x1A21, 0x1A61, 0x1AA1, 0x1AC1, 0x1B01, 0x1B41, 0x1B81, 0x1BA1, 0x1BE1, 0x1C21, 0x1C41, 0x1C81, 0x1CA1, 0x1CE1, 0x1D01, 0x1D41, /* 80 */ 0x1D61, 0x1DA1, 0x1DC1, 0x1E01, 0x1E21, 0x1E61, 0x1E81, 0x1EA1, 0x1EE1, 0x1F01, 0x1F21, 0x1F41, 0x1F81, 0x1FA1, 0x1FC1, 0x1FE1, /* 96 */ 0x2001, 0x2041, 0x2061, 0x2081, 0x20A1, 0x20C1, 0x20E1, 0x2101, 0x2121, 0x2141, 0x2161, 0x2181, 0x21A1, 0x21C1, 0x21E1, 0x2201, /* 112 */ 0x2221, 0x2241, 0x2261, 0x2281, 0x22A1, 0x22C1, 0x22C1, 0x22E1, 0x2301, 0x2321, 0x2341, 0x2361, 0x2361, 0x2381, 0x23A1, 0x23C1, /* 128 */ 0x23E1, 0x23E1, 0x2401, 0x2421, 0x2441, 0x2441, 0x2461, 0x2481, 0x2481, 0x24A1, 0x24C1, 0x24C1, 0x24E1, 0x2501, 0x2501, 0x2521, /* 144 */ 0x2541, 0x2541, 0x2561, 0x2561, 0x2581, 0x25A1, 0x25A1, 0x25C1, 0x25C1, 0x25E1, 0x2601, 0x2601, 0x2621, 0x2621, 0x2641, 0x2641, /* 160 */ 0x2661, 0x2661, 0x2681, 0x2681, 0x26A1, 0x26A1, 0x26C1, 0x26C1, 0x26E1, 0x26E1, 0x2701, 0x2701, 0x2721, 0x2721, 0x2740, 0x2740, /* 176 */ 0x2760, 0x2760, 0x2780, 0x2780, 0x2780, 0x27A0, 0x27A0, 0x27C0, 0x27C0, 0x27E0, 0x27E0, 0x27E0, 0x2800, 0x2800, 0x2820, 0x2820, /* 192 */ 0x2820, 0x2840, 0x2840, 0x2840, 0x2860, 0x2860, 0x2880, 0x2880, 0x2880, 0x28A0, 0x28A0, 0x28A0, 0x28C0, 0x28C0, 0x28C0, 0x28E0, /* 208 */ 0x28E0, 0x28E0, 0x2900, 0x2900, 0x2900, 0x2920, 0x2920, 0x2920, 0x2940, 0x2940, 0x2940, 0x2960, 0x2960, 0x2960, 0x2960, 0x2980, /* 224 */ 0x2980, 0x2980, 0x29A0, 0x29A0, 0x29A0, 0x29A0, 0x29C0, 0x29C0, 0x29C0, 0x29E0, 0x29E0, 0x29E0, 0x29E0, 0x2A00, 0x2A00, 0x2A00, /* 240 */ 0x2A00, 0x2A20, 0x2A20, 0x2A20, 0x2A20, 0x2A40, 0x2A40, 0x2A40, 0x2A40, 0x2A60, 0x2A60, 0x2A60, }; const u16 b43_tab_finefreqg[] = { 0x0089, 0x02E9, 0x0409, 0x04E9, /* 0 */ 0x05A9, 0x0669, 0x0709, 0x0789, 0x0829, 0x08A9, 0x0929, 0x0989, 0x0A09, 0x0A69, 0x0AC9, 0x0B29, 0x0BA9, 0x0BE9, 0x0C49, 0x0CA9, /* 16 */ 0x0D09, 0x0D69, 0x0DA9, 0x0E09, 0x0E69, 0x0EA9, 0x0F09, 0x0F49, 0x0FA9, 0x0FE9, 0x1029, 0x1089, 0x10C9, 0x1109, 0x1169, 0x11A9, /* 32 */ 0x11E9, 0x1229, 0x1289, 0x12C9, 0x1309, 0x1349, 0x1389, 0x13C9, 0x1409, 0x1449, 0x14A9, 0x14E9, 0x1529, 0x1569, 0x15A9, 0x15E9, /* 48 */ 0x1629, 0x1669, 0x16A9, 0x16E8, 0x1728, 0x1768, 0x17A8, 0x17E8, 0x1828, 0x1868, 0x18A8, 0x18E8, 0x1928, 0x1968, 0x19A8, 0x19E8, /* 64 */ 0x1A28, 0x1A68, 0x1AA8, 0x1AE8, 0x1B28, 0x1B68, 0x1BA8, 0x1BE8, 0x1C28, 0x1C68, 0x1CA8, 0x1CE8, 0x1D28, 0x1D68, 0x1DC8, 0x1E08, /* 80 */ 0x1E48, 0x1E88, 0x1EC8, 0x1F08, 0x1F48, 0x1F88, 0x1FE8, 0x2028, 0x2068, 0x20A8, 0x2108, 0x2148, 0x2188, 0x21C8, 0x2228, 0x2268, /* 96 */ 0x22C8, 0x2308, 0x2348, 0x23A8, 0x23E8, 0x2448, 0x24A8, 0x24E8, 0x2548, 0x25A8, 0x2608, 0x2668, 0x26C8, 0x2728, 0x2787, 0x27E7, /* 112 */ 0x2847, 0x28C7, 0x2947, 0x29A7, 0x2A27, 0x2AC7, 0x2B47, 0x2BE7, 0x2CA7, 0x2D67, 0x2E47, 0x2F67, 0x3247, 0x3526, 0x3646, 0x3726, /* 128 */ 0x3806, 0x38A6, 0x3946, 0x39E6, 0x3A66, 0x3AE6, 0x3B66, 0x3BC6, 0x3C45, 0x3CA5, 0x3D05, 0x3D85, 0x3DE5, 0x3E45, 0x3EA5, 0x3EE5, /* 144 */ 0x3F45, 0x3FA5, 0x4005, 0x4045, 0x40A5, 0x40E5, 0x4145, 0x4185, 0x41E5, 0x4225, 0x4265, 0x42C5, 0x4305, 0x4345, 0x43A5, 0x43E5, /* 160 */ 0x4424, 0x4464, 0x44C4, 0x4504, 0x4544, 0x4584, 0x45C4, 0x4604, 0x4644, 0x46A4, 0x46E4, 0x4724, 0x4764, 0x47A4, 0x47E4, 0x4824, /* 176 */ 0x4864, 0x48A4, 0x48E4, 0x4924, 0x4964, 0x49A4, 0x49E4, 0x4A24, 0x4A64, 0x4AA4, 0x4AE4, 0x4B23, 0x4B63, 0x4BA3, 0x4BE3, 0x4C23, /* 192 */ 0x4C63, 0x4CA3, 0x4CE3, 0x4D23, 0x4D63, 0x4DA3, 0x4DE3, 0x4E23, 0x4E63, 0x4EA3, 0x4EE3, 0x4F23, 0x4F63, 0x4FC3, 0x5003, 0x5043, /* 208 */ 0x5083, 0x50C3, 0x5103, 0x5143, 0x5183, 0x51E2, 0x5222, 0x5262, 0x52A2, 0x52E2, 0x5342, 0x5382, 0x53C2, 0x5402, 0x5462, 0x54A2, /* 224 */ 0x5502, 0x5542, 0x55A2, 0x55E2, 0x5642, 0x5682, 0x56E2, 0x5722, 0x5782, 0x57E1, 0x5841, 0x58A1, 0x5901, 0x5961, 0x59C1, 0x5A21, /* 240 */ 0x5AA1, 0x5B01, 0x5B81, 0x5BE1, 0x5C61, 0x5D01, 0x5D80, 0x5E20, 0x5EE0, 0x5FA0, 0x6080, 0x61C0, }; const u16 b43_tab_noisea2[] = { 0x0001, 0x0001, 0x0001, 0xFFFE, 0xFFFE, 0x3FFF, 0x1000, 0x0393, }; const u16 b43_tab_noisea3[] = { 0x5E5E, 0x5E5E, 0x5E5E, 0x3F48, 0x4C4C, 0x4C4C, 0x4C4C, 0x2D36, }; const u16 b43_tab_noiseg1[] = { 0x013C, 0x01F5, 0x031A, 0x0631, 0x0001, 0x0001, 0x0001, 0x0001, }; const u16 b43_tab_noiseg2[] = { 0x5484, 0x3C40, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, }; const u16 b43_tab_noisescalea2[] = { 0x6767, 0x6767, 0x6767, 0x6767, /* 0 */ 0x6767, 0x6767, 0x6767, 0x6767, 0x6767, 0x6767, 0x6767, 0x6767, 0x6767, 0x6700, 0x6767, 0x6767, 0x6767, 0x6767, 0x6767, 0x6767, /* 16 */ 0x6767, 0x6767, 0x6767, 0x6767, 0x6767, 0x6767, 0x0067, }; const u16 b43_tab_noisescalea3[] = { 0x2323, 0x2323, 0x2323, 0x2323, /* 0 */ 0x2323, 0x2323, 0x2323, 0x2323, 0x2323, 0x2323, 0x2323, 0x2323, 0x2323, 0x2300, 0x2323, 0x2323, 0x2323, 0x2323, 0x2323, 0x2323, /* 16 */ 0x2323, 0x2323, 0x2323, 0x2323, 0x2323, 0x2323, 0x0023, }; const u16 b43_tab_noisescaleg1[] = { 0x6C77, 0x5162, 0x3B40, 0x3335, /* 0 */ 0x2F2D, 0x2A2A, 0x2527, 0x1F21, 0x1A1D, 0x1719, 0x1616, 0x1414, 0x1414, 0x1400, 0x1414, 0x1614, 0x1716, 0x1A19, 0x1F1D, 0x2521, /* 16 */ 0x2A27, 0x2F2A, 0x332D, 0x3B35, 0x5140, 0x6C62, 0x0077, }; const u16 b43_tab_noisescaleg2[] = { 0xD8DD, 0xCBD4, 0xBCC0, 0xB6B7, /* 0 */ 0xB2B0, 0xADAD, 0xA7A9, 0x9FA1, 0x969B, 0x9195, 0x8F8F, 0x8A8A, 0x8A8A, 0x8A00, 0x8A8A, 0x8F8A, 0x918F, 0x9695, 0x9F9B, 0xA7A1, /* 16 */ 0xADA9, 0xB2AD, 0xB6B0, 0xBCB7, 0xCBC0, 0xD8D4, 0x00DD, }; const u16 b43_tab_noisescaleg3[] = { 0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, /* 0 */ 0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, 0xA400, 0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, /* 16 */ 0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, 0x00A4, }; const u16 b43_tab_sigmasqr1[] = { 0x007A, 0x0075, 0x0071, 0x006C, /* 0 */ 0x0067, 0x0063, 0x005E, 0x0059, 0x0054, 0x0050, 0x004B, 0x0046, 0x0042, 0x003D, 0x003D, 0x003D, 0x003D, 0x003D, 0x003D, 0x003D, /* 16 */ 0x003D, 0x003D, 0x003D, 0x003D, 0x003D, 0x003D, 0x0000, 0x003D, 0x003D, 0x003D, 0x003D, 0x003D, 0x003D, 0x003D, 0x003D, 0x003D, /* 32 */ 0x003D, 0x003D, 0x003D, 0x003D, 0x0042, 0x0046, 0x004B, 0x0050, 0x0054, 0x0059, 0x005E, 0x0063, 0x0067, 0x006C, 0x0071, 0x0075, /* 48 */ 0x007A, }; const u16 b43_tab_sigmasqr2[] = { 0x00DE, 0x00DC, 0x00DA, 0x00D8, /* 0 */ 0x00D6, 0x00D4, 0x00D2, 0x00CF, 0x00CD, 0x00CA, 0x00C7, 0x00C4, 0x00C1, 0x00BE, 0x00BE, 0x00BE, 0x00BE, 0x00BE, 0x00BE, 0x00BE, /* 16 */ 0x00BE, 0x00BE, 0x00BE, 0x00BE, 0x00BE, 0x00BE, 0x0000, 0x00BE, 0x00BE, 0x00BE, 0x00BE, 0x00BE, 0x00BE, 0x00BE, 0x00BE, 0x00BE, /* 32 */ 0x00BE, 0x00BE, 0x00BE, 0x00BE, 0x00C1, 0x00C4, 0x00C7, 0x00CA, 0x00CD, 0x00CF, 0x00D2, 0x00D4, 0x00D6, 0x00D8, 0x00DA, 0x00DC, /* 48 */ 0x00DE, }; const u16 b43_tab_rssiagc1[] = { 0xFFF8, 0xFFF8, 0xFFF8, 0xFFF8, /* 0 */ 0xFFF8, 0xFFF9, 0xFFFC, 0xFFFE, 0xFFF8, 0xFFF8, 0xFFF8, 0xFFF8, 0xFFF8, 0xFFF8, 0xFFF8, 0xFFF8, }; const u16 b43_tab_rssiagc2[] = { 0x0820, 0x0820, 0x0920, 0x0C38, /* 0 */ 0x0820, 0x0820, 0x0820, 0x0820, 0x0820, 0x0820, 0x0920, 0x0A38, 0x0820, 0x0820, 0x0820, 0x0820, 0x0820, 0x0820, 0x0920, 0x0A38, /* 16 */ 0x0820, 0x0820, 0x0820, 0x0820, 0x0820, 0x0820, 0x0920, 0x0A38, 0x0820, 0x0820, 0x0820, 0x0820, 0x0820, 0x0820, 0x0920, 0x0A38, /* 32 */ 0x0820, 0x0820, 0x0820, 0x0820, 0x0820, 0x0820, 0x0920, 0x0A38, 0x0820, 0x0820, 0x0820, 0x0820, }; static inline void assert_sizes(void) { BUILD_BUG_ON(B43_TAB_ROTOR_SIZE != ARRAY_SIZE(b43_tab_rotor)); BUILD_BUG_ON(B43_TAB_RETARD_SIZE != ARRAY_SIZE(b43_tab_retard)); BUILD_BUG_ON(B43_TAB_FINEFREQA_SIZE != ARRAY_SIZE(b43_tab_finefreqa)); BUILD_BUG_ON(B43_TAB_FINEFREQG_SIZE != ARRAY_SIZE(b43_tab_finefreqg)); BUILD_BUG_ON(B43_TAB_NOISEA2_SIZE != ARRAY_SIZE(b43_tab_noisea2)); BUILD_BUG_ON(B43_TAB_NOISEA3_SIZE != ARRAY_SIZE(b43_tab_noisea3)); BUILD_BUG_ON(B43_TAB_NOISEG1_SIZE != ARRAY_SIZE(b43_tab_noiseg1)); BUILD_BUG_ON(B43_TAB_NOISEG2_SIZE != ARRAY_SIZE(b43_tab_noiseg2)); BUILD_BUG_ON(B43_TAB_NOISESCALE_SIZE != ARRAY_SIZE(b43_tab_noisescalea2)); BUILD_BUG_ON(B43_TAB_NOISESCALE_SIZE != ARRAY_SIZE(b43_tab_noisescalea3)); BUILD_BUG_ON(B43_TAB_NOISESCALE_SIZE != ARRAY_SIZE(b43_tab_noisescaleg1)); BUILD_BUG_ON(B43_TAB_NOISESCALE_SIZE != ARRAY_SIZE(b43_tab_noisescaleg2)); BUILD_BUG_ON(B43_TAB_NOISESCALE_SIZE != ARRAY_SIZE(b43_tab_noisescaleg3)); BUILD_BUG_ON(B43_TAB_SIGMASQR_SIZE != ARRAY_SIZE(b43_tab_sigmasqr1)); BUILD_BUG_ON(B43_TAB_SIGMASQR_SIZE != ARRAY_SIZE(b43_tab_sigmasqr2)); BUILD_BUG_ON(B43_TAB_RSSIAGC1_SIZE != ARRAY_SIZE(b43_tab_rssiagc1)); BUILD_BUG_ON(B43_TAB_RSSIAGC2_SIZE != ARRAY_SIZE(b43_tab_rssiagc2)); } u16 b43_ofdmtab_read16(struct b43_wldev *dev, u16 table, u16 offset) { struct b43_phy_g *gphy = dev->phy.g; u16 addr; addr = table + offset; if ((gphy->ofdmtab_addr_direction != B43_OFDMTAB_DIRECTION_READ) || (addr - 1 != gphy->ofdmtab_addr)) { /* The hardware has a different address in memory. Update it. */ b43_phy_write(dev, B43_PHY_OTABLECTL, addr); gphy->ofdmtab_addr_direction = B43_OFDMTAB_DIRECTION_READ; } gphy->ofdmtab_addr = addr; return b43_phy_read(dev, B43_PHY_OTABLEI); /* Some compiletime assertions... */ assert_sizes(); } void b43_ofdmtab_write16(struct b43_wldev *dev, u16 table, u16 offset, u16 value) { struct b43_phy_g *gphy = dev->phy.g; u16 addr; addr = table + offset; if ((gphy->ofdmtab_addr_direction != B43_OFDMTAB_DIRECTION_WRITE) || (addr - 1 != gphy->ofdmtab_addr)) { /* The hardware has a different address in memory. Update it. */ b43_phy_write(dev, B43_PHY_OTABLECTL, addr); gphy->ofdmtab_addr_direction = B43_OFDMTAB_DIRECTION_WRITE; } gphy->ofdmtab_addr = addr; b43_phy_write(dev, B43_PHY_OTABLEI, value); } u32 b43_ofdmtab_read32(struct b43_wldev *dev, u16 table, u16 offset) { struct b43_phy_g *gphy = dev->phy.g; u32 ret; u16 addr; addr = table + offset; if ((gphy->ofdmtab_addr_direction != B43_OFDMTAB_DIRECTION_READ) || (addr - 1 != gphy->ofdmtab_addr)) { /* The hardware has a different address in memory. Update it. */ b43_phy_write(dev, B43_PHY_OTABLECTL, addr); gphy->ofdmtab_addr_direction = B43_OFDMTAB_DIRECTION_READ; } gphy->ofdmtab_addr = addr; ret = b43_phy_read(dev, B43_PHY_OTABLEQ); ret <<= 16; ret |= b43_phy_read(dev, B43_PHY_OTABLEI); return ret; } void b43_ofdmtab_write32(struct b43_wldev *dev, u16 table, u16 offset, u32 value) { struct b43_phy_g *gphy = dev->phy.g; u16 addr; addr = table + offset; if ((gphy->ofdmtab_addr_direction != B43_OFDMTAB_DIRECTION_WRITE) || (addr - 1 != gphy->ofdmtab_addr)) { /* The hardware has a different address in memory. Update it. */ b43_phy_write(dev, B43_PHY_OTABLECTL, addr); gphy->ofdmtab_addr_direction = B43_OFDMTAB_DIRECTION_WRITE; } gphy->ofdmtab_addr = addr; b43_phy_write(dev, B43_PHY_OTABLEI, value); b43_phy_write(dev, B43_PHY_OTABLEQ, (value >> 16)); } u16 b43_gtab_read(struct b43_wldev *dev, u16 table, u16 offset) { b43_phy_write(dev, B43_PHY_GTABCTL, table + offset); return b43_phy_read(dev, B43_PHY_GTABDATA); } void b43_gtab_write(struct b43_wldev *dev, u16 table, u16 offset, u16 value) { b43_phy_write(dev, B43_PHY_GTABCTL, table + offset); b43_phy_write(dev, B43_PHY_GTABDATA, value); }
gpl-2.0
sistux/lge-kernel-omap4
arch/sparc/kernel/traps_32.c
4312
12547
/* * arch/sparc/kernel/traps.c * * Copyright 1995, 2008 David S. Miller (davem@davemloft.net) * Copyright 2000 Jakub Jelinek (jakub@redhat.com) */ /* * I hate traps on the sparc, grrr... */ #include <linux/sched.h> /* for jiffies */ #include <linux/kernel.h> #include <linux/signal.h> #include <linux/smp.h> #include <linux/kdebug.h> #include <asm/delay.h> #include <asm/system.h> #include <asm/ptrace.h> #include <asm/oplib.h> #include <asm/page.h> #include <asm/pgtable.h> #include <asm/unistd.h> #include <asm/traps.h> #include "entry.h" #include "kernel.h" /* #define TRAP_DEBUG */ static void instruction_dump(unsigned long *pc) { int i; if((((unsigned long) pc) & 3)) return; for(i = -3; i < 6; i++) printk("%c%08lx%c",i?' ':'<',pc[i],i?' ':'>'); printk("\n"); } #define __SAVE __asm__ __volatile__("save %sp, -0x40, %sp\n\t") #define __RESTORE __asm__ __volatile__("restore %g0, %g0, %g0\n\t") void die_if_kernel(char *str, struct pt_regs *regs) { static int die_counter; int count = 0; /* Amuse the user. */ printk( " \\|/ ____ \\|/\n" " \"@'/ ,. \\`@\"\n" " /_| \\__/ |_\\\n" " \\__U_/\n"); printk("%s(%d): %s [#%d]\n", current->comm, task_pid_nr(current), str, ++die_counter); show_regs(regs); add_taint(TAINT_DIE); __SAVE; __SAVE; __SAVE; __SAVE; __SAVE; __SAVE; __SAVE; __SAVE; __RESTORE; __RESTORE; __RESTORE; __RESTORE; __RESTORE; __RESTORE; __RESTORE; __RESTORE; { struct reg_window32 *rw = (struct reg_window32 *)regs->u_regs[UREG_FP]; /* Stop the back trace when we hit userland or we * find some badly aligned kernel stack. Set an upper * bound in case our stack is trashed and we loop. */ while(rw && count++ < 30 && (((unsigned long) rw) >= PAGE_OFFSET) && !(((unsigned long) rw) & 0x7)) { printk("Caller[%08lx]: %pS\n", rw->ins[7], (void *) rw->ins[7]); rw = (struct reg_window32 *)rw->ins[6]; } } printk("Instruction DUMP:"); instruction_dump ((unsigned long *) regs->pc); if(regs->psr & PSR_PS) do_exit(SIGKILL); do_exit(SIGSEGV); } void do_hw_interrupt(struct pt_regs *regs, unsigned long type) { siginfo_t info; if(type < 0x80) { /* Sun OS's puke from bad traps, Linux survives! */ printk("Unimplemented Sparc TRAP, type = %02lx\n", type); die_if_kernel("Whee... Hello Mr. Penguin", regs); } if(regs->psr & PSR_PS) die_if_kernel("Kernel bad trap", regs); info.si_signo = SIGILL; info.si_errno = 0; info.si_code = ILL_ILLTRP; info.si_addr = (void __user *)regs->pc; info.si_trapno = type - 0x80; force_sig_info(SIGILL, &info, current); } void do_illegal_instruction(struct pt_regs *regs, unsigned long pc, unsigned long npc, unsigned long psr) { siginfo_t info; if(psr & PSR_PS) die_if_kernel("Kernel illegal instruction", regs); #ifdef TRAP_DEBUG printk("Ill instr. at pc=%08lx instruction is %08lx\n", regs->pc, *(unsigned long *)regs->pc); #endif if (!do_user_muldiv (regs, pc)) return; info.si_signo = SIGILL; info.si_errno = 0; info.si_code = ILL_ILLOPC; info.si_addr = (void __user *)pc; info.si_trapno = 0; send_sig_info(SIGILL, &info, current); } void do_priv_instruction(struct pt_regs *regs, unsigned long pc, unsigned long npc, unsigned long psr) { siginfo_t info; if(psr & PSR_PS) die_if_kernel("Penguin instruction from Penguin mode??!?!", regs); info.si_signo = SIGILL; info.si_errno = 0; info.si_code = ILL_PRVOPC; info.si_addr = (void __user *)pc; info.si_trapno = 0; send_sig_info(SIGILL, &info, current); } /* XXX User may want to be allowed to do this. XXX */ void do_memaccess_unaligned(struct pt_regs *regs, unsigned long pc, unsigned long npc, unsigned long psr) { siginfo_t info; if(regs->psr & PSR_PS) { printk("KERNEL MNA at pc %08lx npc %08lx called by %08lx\n", pc, npc, regs->u_regs[UREG_RETPC]); die_if_kernel("BOGUS", regs); /* die_if_kernel("Kernel MNA access", regs); */ } #if 0 show_regs (regs); instruction_dump ((unsigned long *) regs->pc); printk ("do_MNA!\n"); #endif info.si_signo = SIGBUS; info.si_errno = 0; info.si_code = BUS_ADRALN; info.si_addr = /* FIXME: Should dig out mna address */ (void *)0; info.si_trapno = 0; send_sig_info(SIGBUS, &info, current); } static unsigned long init_fsr = 0x0UL; static unsigned long init_fregs[32] __attribute__ ((aligned (8))) = { ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL }; void do_fpd_trap(struct pt_regs *regs, unsigned long pc, unsigned long npc, unsigned long psr) { /* Sanity check... */ if(psr & PSR_PS) die_if_kernel("Kernel gets FloatingPenguinUnit disabled trap", regs); put_psr(get_psr() | PSR_EF); /* Allow FPU ops. */ regs->psr |= PSR_EF; #ifndef CONFIG_SMP if(last_task_used_math == current) return; if(last_task_used_math) { /* Other processes fpu state, save away */ struct task_struct *fptask = last_task_used_math; fpsave(&fptask->thread.float_regs[0], &fptask->thread.fsr, &fptask->thread.fpqueue[0], &fptask->thread.fpqdepth); } last_task_used_math = current; if(used_math()) { fpload(&current->thread.float_regs[0], &current->thread.fsr); } else { /* Set initial sane state. */ fpload(&init_fregs[0], &init_fsr); set_used_math(); } #else if(!used_math()) { fpload(&init_fregs[0], &init_fsr); set_used_math(); } else { fpload(&current->thread.float_regs[0], &current->thread.fsr); } set_thread_flag(TIF_USEDFPU); #endif } static unsigned long fake_regs[32] __attribute__ ((aligned (8))); static unsigned long fake_fsr; static unsigned long fake_queue[32] __attribute__ ((aligned (8))); static unsigned long fake_depth; extern int do_mathemu(struct pt_regs *, struct task_struct *); void do_fpe_trap(struct pt_regs *regs, unsigned long pc, unsigned long npc, unsigned long psr) { static int calls; siginfo_t info; unsigned long fsr; int ret = 0; #ifndef CONFIG_SMP struct task_struct *fpt = last_task_used_math; #else struct task_struct *fpt = current; #endif put_psr(get_psr() | PSR_EF); /* If nobody owns the fpu right now, just clear the * error into our fake static buffer and hope it don't * happen again. Thank you crashme... */ #ifndef CONFIG_SMP if(!fpt) { #else if (!test_tsk_thread_flag(fpt, TIF_USEDFPU)) { #endif fpsave(&fake_regs[0], &fake_fsr, &fake_queue[0], &fake_depth); regs->psr &= ~PSR_EF; return; } fpsave(&fpt->thread.float_regs[0], &fpt->thread.fsr, &fpt->thread.fpqueue[0], &fpt->thread.fpqdepth); #ifdef DEBUG_FPU printk("Hmm, FP exception, fsr was %016lx\n", fpt->thread.fsr); #endif switch ((fpt->thread.fsr & 0x1c000)) { /* switch on the contents of the ftt [floating point trap type] field */ #ifdef DEBUG_FPU case (1 << 14): printk("IEEE_754_exception\n"); break; #endif case (2 << 14): /* unfinished_FPop (underflow & co) */ case (3 << 14): /* unimplemented_FPop (quad stuff, maybe sqrt) */ ret = do_mathemu(regs, fpt); break; #ifdef DEBUG_FPU case (4 << 14): printk("sequence_error (OS bug...)\n"); break; case (5 << 14): printk("hardware_error (uhoh!)\n"); break; case (6 << 14): printk("invalid_fp_register (user error)\n"); break; #endif /* DEBUG_FPU */ } /* If we successfully emulated the FPop, we pretend the trap never happened :-> */ if (ret) { fpload(&current->thread.float_regs[0], &current->thread.fsr); return; } /* nope, better SIGFPE the offending process... */ #ifdef CONFIG_SMP clear_tsk_thread_flag(fpt, TIF_USEDFPU); #endif if(psr & PSR_PS) { /* The first fsr store/load we tried trapped, * the second one will not (we hope). */ printk("WARNING: FPU exception from kernel mode. at pc=%08lx\n", regs->pc); regs->pc = regs->npc; regs->npc += 4; calls++; if(calls > 2) die_if_kernel("Too many Penguin-FPU traps from kernel mode", regs); return; } fsr = fpt->thread.fsr; info.si_signo = SIGFPE; info.si_errno = 0; info.si_addr = (void __user *)pc; info.si_trapno = 0; info.si_code = __SI_FAULT; if ((fsr & 0x1c000) == (1 << 14)) { if (fsr & 0x10) info.si_code = FPE_FLTINV; else if (fsr & 0x08) info.si_code = FPE_FLTOVF; else if (fsr & 0x04) info.si_code = FPE_FLTUND; else if (fsr & 0x02) info.si_code = FPE_FLTDIV; else if (fsr & 0x01) info.si_code = FPE_FLTRES; } send_sig_info(SIGFPE, &info, fpt); #ifndef CONFIG_SMP last_task_used_math = NULL; #endif regs->psr &= ~PSR_EF; if(calls > 0) calls=0; } void handle_tag_overflow(struct pt_regs *regs, unsigned long pc, unsigned long npc, unsigned long psr) { siginfo_t info; if(psr & PSR_PS) die_if_kernel("Penguin overflow trap from kernel mode", regs); info.si_signo = SIGEMT; info.si_errno = 0; info.si_code = EMT_TAGOVF; info.si_addr = (void __user *)pc; info.si_trapno = 0; send_sig_info(SIGEMT, &info, current); } void handle_watchpoint(struct pt_regs *regs, unsigned long pc, unsigned long npc, unsigned long psr) { #ifdef TRAP_DEBUG printk("Watchpoint detected at PC %08lx NPC %08lx PSR %08lx\n", pc, npc, psr); #endif if(psr & PSR_PS) panic("Tell me what a watchpoint trap is, and I'll then deal " "with such a beast..."); } void handle_reg_access(struct pt_regs *regs, unsigned long pc, unsigned long npc, unsigned long psr) { siginfo_t info; #ifdef TRAP_DEBUG printk("Register Access Exception at PC %08lx NPC %08lx PSR %08lx\n", pc, npc, psr); #endif info.si_signo = SIGBUS; info.si_errno = 0; info.si_code = BUS_OBJERR; info.si_addr = (void __user *)pc; info.si_trapno = 0; force_sig_info(SIGBUS, &info, current); } void handle_cp_disabled(struct pt_regs *regs, unsigned long pc, unsigned long npc, unsigned long psr) { siginfo_t info; info.si_signo = SIGILL; info.si_errno = 0; info.si_code = ILL_COPROC; info.si_addr = (void __user *)pc; info.si_trapno = 0; send_sig_info(SIGILL, &info, current); } void handle_cp_exception(struct pt_regs *regs, unsigned long pc, unsigned long npc, unsigned long psr) { siginfo_t info; #ifdef TRAP_DEBUG printk("Co-Processor Exception at PC %08lx NPC %08lx PSR %08lx\n", pc, npc, psr); #endif info.si_signo = SIGILL; info.si_errno = 0; info.si_code = ILL_COPROC; info.si_addr = (void __user *)pc; info.si_trapno = 0; send_sig_info(SIGILL, &info, current); } void handle_hw_divzero(struct pt_regs *regs, unsigned long pc, unsigned long npc, unsigned long psr) { siginfo_t info; info.si_signo = SIGFPE; info.si_errno = 0; info.si_code = FPE_INTDIV; info.si_addr = (void __user *)pc; info.si_trapno = 0; send_sig_info(SIGFPE, &info, current); } #ifdef CONFIG_DEBUG_BUGVERBOSE void do_BUG(const char *file, int line) { // bust_spinlocks(1); XXX Not in our original BUG() printk("kernel BUG at %s:%d!\n", file, line); } EXPORT_SYMBOL(do_BUG); #endif /* Since we have our mappings set up, on multiprocessors we can spin them * up here so that timer interrupts work during initialization. */ void trap_init(void) { extern void thread_info_offsets_are_bolixed_pete(void); /* Force linker to barf if mismatched */ if (TI_UWINMASK != offsetof(struct thread_info, uwinmask) || TI_TASK != offsetof(struct thread_info, task) || TI_EXECDOMAIN != offsetof(struct thread_info, exec_domain) || TI_FLAGS != offsetof(struct thread_info, flags) || TI_CPU != offsetof(struct thread_info, cpu) || TI_PREEMPT != offsetof(struct thread_info, preempt_count) || TI_SOFTIRQ != offsetof(struct thread_info, softirq_count) || TI_HARDIRQ != offsetof(struct thread_info, hardirq_count) || TI_KSP != offsetof(struct thread_info, ksp) || TI_KPC != offsetof(struct thread_info, kpc) || TI_KPSR != offsetof(struct thread_info, kpsr) || TI_KWIM != offsetof(struct thread_info, kwim) || TI_REG_WINDOW != offsetof(struct thread_info, reg_window) || TI_RWIN_SPTRS != offsetof(struct thread_info, rwbuf_stkptrs) || TI_W_SAVED != offsetof(struct thread_info, w_saved)) thread_info_offsets_are_bolixed_pete(); /* Attach to the address space of init_task. */ atomic_inc(&init_mm.mm_count); current->active_mm = &init_mm; /* NOTE: Other cpus have this done as they are started * up on SMP. */ }
gpl-2.0
CyanogenMod/android_kernel_motorola_ghost
drivers/usb/gadget/uvc_v4l2.c
4824
8230
/* * uvc_v4l2.c -- USB Video Class Gadget driver * * Copyright (C) 2009-2010 * Laurent Pinchart (laurent.pinchart@ideasonboard.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #include <linux/kernel.h> #include <linux/device.h> #include <linux/errno.h> #include <linux/list.h> #include <linux/mutex.h> #include <linux/videodev2.h> #include <linux/vmalloc.h> #include <linux/wait.h> #include <media/v4l2-dev.h> #include <media/v4l2-event.h> #include <media/v4l2-ioctl.h> #include "uvc.h" #include "uvc_queue.h" /* -------------------------------------------------------------------------- * Requests handling */ static int uvc_send_response(struct uvc_device *uvc, struct uvc_request_data *data) { struct usb_composite_dev *cdev = uvc->func.config->cdev; struct usb_request *req = uvc->control_req; if (data->length < 0) return usb_ep_set_halt(cdev->gadget->ep0); req->length = min_t(unsigned int, uvc->event_length, data->length); req->zero = data->length < uvc->event_length; req->dma = DMA_ADDR_INVALID; memcpy(req->buf, data->data, data->length); return usb_ep_queue(cdev->gadget->ep0, req, GFP_KERNEL); } /* -------------------------------------------------------------------------- * V4L2 */ struct uvc_format { u8 bpp; u32 fcc; }; static struct uvc_format uvc_formats[] = { { 16, V4L2_PIX_FMT_YUYV }, { 0, V4L2_PIX_FMT_MJPEG }, }; static int uvc_v4l2_get_format(struct uvc_video *video, struct v4l2_format *fmt) { fmt->fmt.pix.pixelformat = video->fcc; fmt->fmt.pix.width = video->width; fmt->fmt.pix.height = video->height; fmt->fmt.pix.field = V4L2_FIELD_NONE; fmt->fmt.pix.bytesperline = video->bpp * video->width / 8; fmt->fmt.pix.sizeimage = video->imagesize; fmt->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB; fmt->fmt.pix.priv = 0; return 0; } static int uvc_v4l2_set_format(struct uvc_video *video, struct v4l2_format *fmt) { struct uvc_format *format; unsigned int imagesize; unsigned int bpl; unsigned int i; for (i = 0; i < ARRAY_SIZE(uvc_formats); ++i) { format = &uvc_formats[i]; if (format->fcc == fmt->fmt.pix.pixelformat) break; } if (i == ARRAY_SIZE(uvc_formats)) { printk(KERN_INFO "Unsupported format 0x%08x.\n", fmt->fmt.pix.pixelformat); return -EINVAL; } bpl = format->bpp * fmt->fmt.pix.width / 8; imagesize = bpl ? bpl * fmt->fmt.pix.height : fmt->fmt.pix.sizeimage; video->fcc = format->fcc; video->bpp = format->bpp; video->width = fmt->fmt.pix.width; video->height = fmt->fmt.pix.height; video->imagesize = imagesize; fmt->fmt.pix.field = V4L2_FIELD_NONE; fmt->fmt.pix.bytesperline = bpl; fmt->fmt.pix.sizeimage = imagesize; fmt->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB; fmt->fmt.pix.priv = 0; return 0; } static int uvc_v4l2_open(struct file *file) { struct video_device *vdev = video_devdata(file); struct uvc_device *uvc = video_get_drvdata(vdev); struct uvc_file_handle *handle; handle = kzalloc(sizeof(*handle), GFP_KERNEL); if (handle == NULL) return -ENOMEM; v4l2_fh_init(&handle->vfh, vdev); v4l2_fh_add(&handle->vfh); handle->device = &uvc->video; file->private_data = &handle->vfh; uvc_function_connect(uvc); return 0; } static int uvc_v4l2_release(struct file *file) { struct video_device *vdev = video_devdata(file); struct uvc_device *uvc = video_get_drvdata(vdev); struct uvc_file_handle *handle = to_uvc_file_handle(file->private_data); struct uvc_video *video = handle->device; uvc_function_disconnect(uvc); uvc_video_enable(video, 0); mutex_lock(&video->queue.mutex); if (uvc_free_buffers(&video->queue) < 0) printk(KERN_ERR "uvc_v4l2_release: Unable to free " "buffers.\n"); mutex_unlock(&video->queue.mutex); file->private_data = NULL; v4l2_fh_del(&handle->vfh); v4l2_fh_exit(&handle->vfh); kfree(handle); return 0; } static long uvc_v4l2_do_ioctl(struct file *file, unsigned int cmd, void *arg) { struct video_device *vdev = video_devdata(file); struct uvc_device *uvc = video_get_drvdata(vdev); struct uvc_file_handle *handle = to_uvc_file_handle(file->private_data); struct usb_composite_dev *cdev = uvc->func.config->cdev; struct uvc_video *video = &uvc->video; int ret = 0; switch (cmd) { /* Query capabilities */ case VIDIOC_QUERYCAP: { struct v4l2_capability *cap = arg; memset(cap, 0, sizeof *cap); strncpy(cap->driver, "g_uvc", sizeof(cap->driver)); strncpy(cap->card, cdev->gadget->name, sizeof(cap->card)); strncpy(cap->bus_info, dev_name(&cdev->gadget->dev), sizeof cap->bus_info); cap->version = DRIVER_VERSION_NUMBER; cap->capabilities = V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_STREAMING; break; } /* Get & Set format */ case VIDIOC_G_FMT: { struct v4l2_format *fmt = arg; if (fmt->type != video->queue.type) return -EINVAL; return uvc_v4l2_get_format(video, fmt); } case VIDIOC_S_FMT: { struct v4l2_format *fmt = arg; if (fmt->type != video->queue.type) return -EINVAL; return uvc_v4l2_set_format(video, fmt); } /* Buffers & streaming */ case VIDIOC_REQBUFS: { struct v4l2_requestbuffers *rb = arg; if (rb->type != video->queue.type || rb->memory != V4L2_MEMORY_MMAP) return -EINVAL; ret = uvc_alloc_buffers(&video->queue, rb->count, video->imagesize); if (ret < 0) return ret; rb->count = ret; ret = 0; break; } case VIDIOC_QUERYBUF: { struct v4l2_buffer *buf = arg; if (buf->type != video->queue.type) return -EINVAL; return uvc_query_buffer(&video->queue, buf); } case VIDIOC_QBUF: if ((ret = uvc_queue_buffer(&video->queue, arg)) < 0) return ret; return uvc_video_pump(video); case VIDIOC_DQBUF: return uvc_dequeue_buffer(&video->queue, arg, file->f_flags & O_NONBLOCK); case VIDIOC_STREAMON: { int *type = arg; if (*type != video->queue.type) return -EINVAL; return uvc_video_enable(video, 1); } case VIDIOC_STREAMOFF: { int *type = arg; if (*type != video->queue.type) return -EINVAL; return uvc_video_enable(video, 0); } /* Events */ case VIDIOC_DQEVENT: { struct v4l2_event *event = arg; ret = v4l2_event_dequeue(&handle->vfh, event, file->f_flags & O_NONBLOCK); if (ret == 0 && event->type == UVC_EVENT_SETUP) { struct uvc_event *uvc_event = (void *)&event->u.data; /* Tell the complete callback to generate an event for * the next request that will be enqueued by * uvc_event_write. */ uvc->event_setup_out = !(uvc_event->req.bRequestType & USB_DIR_IN); uvc->event_length = uvc_event->req.wLength; } return ret; } case VIDIOC_SUBSCRIBE_EVENT: { struct v4l2_event_subscription *sub = arg; if (sub->type < UVC_EVENT_FIRST || sub->type > UVC_EVENT_LAST) return -EINVAL; return v4l2_event_subscribe(&handle->vfh, arg, 2); } case VIDIOC_UNSUBSCRIBE_EVENT: return v4l2_event_unsubscribe(&handle->vfh, arg); case UVCIOC_SEND_RESPONSE: ret = uvc_send_response(uvc, arg); break; default: return -ENOIOCTLCMD; } return ret; } static long uvc_v4l2_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { return video_usercopy(file, cmd, arg, uvc_v4l2_do_ioctl); } static int uvc_v4l2_mmap(struct file *file, struct vm_area_struct *vma) { struct video_device *vdev = video_devdata(file); struct uvc_device *uvc = video_get_drvdata(vdev); return uvc_queue_mmap(&uvc->video.queue, vma); } static unsigned int uvc_v4l2_poll(struct file *file, poll_table *wait) { struct video_device *vdev = video_devdata(file); struct uvc_device *uvc = video_get_drvdata(vdev); struct uvc_file_handle *handle = to_uvc_file_handle(file->private_data); unsigned int mask = 0; poll_wait(file, &handle->vfh.wait, wait); if (v4l2_event_pending(&handle->vfh)) mask |= POLLPRI; mask |= uvc_queue_poll(&uvc->video.queue, file, wait); return mask; } static struct v4l2_file_operations uvc_v4l2_fops = { .owner = THIS_MODULE, .open = uvc_v4l2_open, .release = uvc_v4l2_release, .ioctl = uvc_v4l2_ioctl, .mmap = uvc_v4l2_mmap, .poll = uvc_v4l2_poll, };
gpl-2.0
TW-LL-msm8226/kernel_samsung_msm8226
mm/fremap.c
4824
6871
/* * linux/mm/fremap.c * * Explicit pagetable population and nonlinear (random) mappings support. * * started by Ingo Molnar, Copyright (C) 2002, 2003 */ #include <linux/backing-dev.h> #include <linux/mm.h> #include <linux/swap.h> #include <linux/file.h> #include <linux/mman.h> #include <linux/pagemap.h> #include <linux/swapops.h> #include <linux/rmap.h> #include <linux/syscalls.h> #include <linux/mmu_notifier.h> #include <asm/mmu_context.h> #include <asm/cacheflush.h> #include <asm/tlbflush.h> #include "internal.h" static void zap_pte(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long addr, pte_t *ptep) { pte_t pte = *ptep; if (pte_present(pte)) { struct page *page; flush_cache_page(vma, addr, pte_pfn(pte)); pte = ptep_clear_flush(vma, addr, ptep); page = vm_normal_page(vma, addr, pte); if (page) { if (pte_dirty(pte)) set_page_dirty(page); page_remove_rmap(page); page_cache_release(page); update_hiwater_rss(mm); dec_mm_counter(mm, MM_FILEPAGES); } } else { if (!pte_file(pte)) free_swap_and_cache(pte_to_swp_entry(pte)); pte_clear_not_present_full(mm, addr, ptep, 0); } } /* * Install a file pte to a given virtual memory address, release any * previously existing mapping. */ static int install_file_pte(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long addr, unsigned long pgoff, pgprot_t prot) { int err = -ENOMEM; pte_t *pte; spinlock_t *ptl; pte = get_locked_pte(mm, addr, &ptl); if (!pte) goto out; if (!pte_none(*pte)) zap_pte(mm, vma, addr, pte); set_pte_at(mm, addr, pte, pgoff_to_pte(pgoff)); /* * We don't need to run update_mmu_cache() here because the "file pte" * being installed by install_file_pte() is not a real pte - it's a * non-present entry (like a swap entry), noting what file offset should * be mapped there when there's a fault (in a non-linear vma where * that's not obvious). */ pte_unmap_unlock(pte, ptl); err = 0; out: return err; } static int populate_range(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long addr, unsigned long size, pgoff_t pgoff) { int err; do { err = install_file_pte(mm, vma, addr, pgoff, vma->vm_page_prot); if (err) return err; size -= PAGE_SIZE; addr += PAGE_SIZE; pgoff++; } while (size); return 0; } /** * sys_remap_file_pages - remap arbitrary pages of an existing VM_SHARED vma * @start: start of the remapped virtual memory range * @size: size of the remapped virtual memory range * @prot: new protection bits of the range (see NOTE) * @pgoff: to-be-mapped page of the backing store file * @flags: 0 or MAP_NONBLOCKED - the later will cause no IO. * * sys_remap_file_pages remaps arbitrary pages of an existing VM_SHARED vma * (shared backing store file). * * This syscall works purely via pagetables, so it's the most efficient * way to map the same (large) file into a given virtual window. Unlike * mmap()/mremap() it does not create any new vmas. The new mappings are * also safe across swapout. * * NOTE: the @prot parameter right now is ignored (but must be zero), * and the vma's default protection is used. Arbitrary protections * might be implemented in the future. */ SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size, unsigned long, prot, unsigned long, pgoff, unsigned long, flags) { struct mm_struct *mm = current->mm; struct address_space *mapping; struct vm_area_struct *vma; int err = -EINVAL; int has_write_lock = 0; if (prot) return err; /* * Sanitize the syscall parameters: */ start = start & PAGE_MASK; size = size & PAGE_MASK; /* Does the address range wrap, or is the span zero-sized? */ if (start + size <= start) return err; /* Does pgoff wrap? */ if (pgoff + (size >> PAGE_SHIFT) < pgoff) return err; /* Can we represent this offset inside this architecture's pte's? */ #if PTE_FILE_MAX_BITS < BITS_PER_LONG if (pgoff + (size >> PAGE_SHIFT) >= (1UL << PTE_FILE_MAX_BITS)) return err; #endif /* We need down_write() to change vma->vm_flags. */ down_read(&mm->mmap_sem); retry: vma = find_vma(mm, start); /* * Make sure the vma is shared, that it supports prefaulting, * and that the remapped range is valid and fully within * the single existing vma. vm_private_data is used as a * swapout cursor in a VM_NONLINEAR vma. */ if (!vma || !(vma->vm_flags & VM_SHARED)) goto out; if (vma->vm_private_data && !(vma->vm_flags & VM_NONLINEAR)) goto out; if (!(vma->vm_flags & VM_CAN_NONLINEAR)) goto out; if (start < vma->vm_start || start + size > vma->vm_end) goto out; /* Must set VM_NONLINEAR before any pages are populated. */ if (!(vma->vm_flags & VM_NONLINEAR)) { /* Don't need a nonlinear mapping, exit success */ if (pgoff == linear_page_index(vma, start)) { err = 0; goto out; } if (!has_write_lock) { up_read(&mm->mmap_sem); down_write(&mm->mmap_sem); has_write_lock = 1; goto retry; } mapping = vma->vm_file->f_mapping; /* * page_mkclean doesn't work on nonlinear vmas, so if * dirty pages need to be accounted, emulate with linear * vmas. */ if (mapping_cap_account_dirty(mapping)) { unsigned long addr; struct file *file = vma->vm_file; flags &= MAP_NONBLOCK; get_file(file); addr = mmap_region(file, start, size, flags, vma->vm_flags, pgoff); fput(file); if (IS_ERR_VALUE(addr)) { err = addr; } else { BUG_ON(addr != start); err = 0; } goto out; } mutex_lock(&mapping->i_mmap_mutex); flush_dcache_mmap_lock(mapping); vma->vm_flags |= VM_NONLINEAR; vma_prio_tree_remove(vma, &mapping->i_mmap); vma_nonlinear_insert(vma, &mapping->i_mmap_nonlinear); flush_dcache_mmap_unlock(mapping); mutex_unlock(&mapping->i_mmap_mutex); } if (vma->vm_flags & VM_LOCKED) { /* * drop PG_Mlocked flag for over-mapped range */ vm_flags_t saved_flags = vma->vm_flags; munlock_vma_pages_range(vma, start, start + size); vma->vm_flags = saved_flags; } mmu_notifier_invalidate_range_start(mm, start, start + size); err = populate_range(mm, vma, start, size, pgoff); mmu_notifier_invalidate_range_end(mm, start, start + size); if (!err && !(flags & MAP_NONBLOCK)) { if (vma->vm_flags & VM_LOCKED) { /* * might be mapping previously unmapped range of file */ mlock_vma_pages_range(vma, start, start + size); } else { if (unlikely(has_write_lock)) { downgrade_write(&mm->mmap_sem); has_write_lock = 0; } make_pages_present(start, start+size); } } /* * We can't clear VM_NONLINEAR because we'd have to do * it after ->populate completes, and that would prevent * downgrading the lock. (Locks can't be upgraded). */ out: if (likely(!has_write_lock)) up_read(&mm->mmap_sem); else up_write(&mm->mmap_sem); return err; }
gpl-2.0
VegaDevTeam/android_kernel_n9009
drivers/net/wireless/prism54/islpci_mgt.c
5080
14577
/* * Copyright (C) 2002 Intersil Americas Inc. * Copyright 2004 Jens Maurer <Jens.Maurer@gmx.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 * * 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/netdevice.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/sched.h> #include <linux/slab.h> #include <asm/io.h> #include <linux/if_arp.h> #include "prismcompat.h" #include "isl_38xx.h" #include "islpci_mgt.h" #include "isl_oid.h" /* additional types and defs for isl38xx fw */ #include "isl_ioctl.h" #include <net/iw_handler.h> /****************************************************************************** Global variable definition section ******************************************************************************/ int pc_debug = VERBOSE; module_param(pc_debug, int, 0); /****************************************************************************** Driver general functions ******************************************************************************/ #if VERBOSE > SHOW_ERROR_MESSAGES void display_buffer(char *buffer, int length) { if ((pc_debug & SHOW_BUFFER_CONTENTS) == 0) return; while (length > 0) { printk("[%02x]", *buffer & 255); length--; buffer++; } printk("\n"); } #endif /***************************************************************************** Queue handling for management frames ******************************************************************************/ /* * Helper function to create a PIMFOR management frame header. */ static void pimfor_encode_header(int operation, u32 oid, u32 length, pimfor_header_t *h) { h->version = PIMFOR_VERSION; h->operation = operation; h->device_id = PIMFOR_DEV_ID_MHLI_MIB; h->flags = 0; h->oid = cpu_to_be32(oid); h->length = cpu_to_be32(length); } /* * Helper function to analyze a PIMFOR management frame header. */ static pimfor_header_t * pimfor_decode_header(void *data, int len) { pimfor_header_t *h = data; while ((void *) h < data + len) { if (h->flags & PIMFOR_FLAG_LITTLE_ENDIAN) { le32_to_cpus(&h->oid); le32_to_cpus(&h->length); } else { be32_to_cpus(&h->oid); be32_to_cpus(&h->length); } if (h->oid != OID_INL_TUNNEL) return h; h++; } return NULL; } /* * Fill the receive queue for management frames with fresh buffers. */ int islpci_mgmt_rx_fill(struct net_device *ndev) { islpci_private *priv = netdev_priv(ndev); isl38xx_control_block *cb = /* volatile not needed */ (isl38xx_control_block *) priv->control_block; u32 curr = le32_to_cpu(cb->driver_curr_frag[ISL38XX_CB_RX_MGMTQ]); #if VERBOSE > SHOW_ERROR_MESSAGES DEBUG(SHOW_FUNCTION_CALLS, "islpci_mgmt_rx_fill\n"); #endif while (curr - priv->index_mgmt_rx < ISL38XX_CB_MGMT_QSIZE) { u32 index = curr % ISL38XX_CB_MGMT_QSIZE; struct islpci_membuf *buf = &priv->mgmt_rx[index]; isl38xx_fragment *frag = &cb->rx_data_mgmt[index]; if (buf->mem == NULL) { buf->mem = kmalloc(MGMT_FRAME_SIZE, GFP_ATOMIC); if (!buf->mem) { printk(KERN_WARNING "Error allocating management frame.\n"); return -ENOMEM; } buf->size = MGMT_FRAME_SIZE; } if (buf->pci_addr == 0) { buf->pci_addr = pci_map_single(priv->pdev, buf->mem, MGMT_FRAME_SIZE, PCI_DMA_FROMDEVICE); if (!buf->pci_addr) { printk(KERN_WARNING "Failed to make memory DMA'able.\n"); return -ENOMEM; } } /* be safe: always reset control block information */ frag->size = cpu_to_le16(MGMT_FRAME_SIZE); frag->flags = 0; frag->address = cpu_to_le32(buf->pci_addr); curr++; /* The fragment address in the control block must have * been written before announcing the frame buffer to * device */ wmb(); cb->driver_curr_frag[ISL38XX_CB_RX_MGMTQ] = cpu_to_le32(curr); } return 0; } /* * Create and transmit a management frame using "operation" and "oid", * with arguments data/length. * We either return an error and free the frame, or we return 0 and * islpci_mgt_cleanup_transmit() frees the frame in the tx-done * interrupt. */ static int islpci_mgt_transmit(struct net_device *ndev, int operation, unsigned long oid, void *data, int length) { islpci_private *priv = netdev_priv(ndev); isl38xx_control_block *cb = (isl38xx_control_block *) priv->control_block; void *p; int err = -EINVAL; unsigned long flags; isl38xx_fragment *frag; struct islpci_membuf buf; u32 curr_frag; int index; int frag_len = length + PIMFOR_HEADER_SIZE; #if VERBOSE > SHOW_ERROR_MESSAGES DEBUG(SHOW_FUNCTION_CALLS, "islpci_mgt_transmit\n"); #endif if (frag_len > MGMT_FRAME_SIZE) { printk(KERN_DEBUG "%s: mgmt frame too large %d\n", ndev->name, frag_len); goto error; } err = -ENOMEM; p = buf.mem = kmalloc(frag_len, GFP_KERNEL); if (!buf.mem) goto error; buf.size = frag_len; /* create the header directly in the fragment data area */ pimfor_encode_header(operation, oid, length, (pimfor_header_t *) p); p += PIMFOR_HEADER_SIZE; if (data) memcpy(p, data, length); else memset(p, 0, length); #if VERBOSE > SHOW_ERROR_MESSAGES { pimfor_header_t *h = buf.mem; DEBUG(SHOW_PIMFOR_FRAMES, "PIMFOR: op %i, oid 0x%08lx, device %i, flags 0x%x length 0x%x\n", h->operation, oid, h->device_id, h->flags, length); /* display the buffer contents for debugging */ display_buffer((char *) h, sizeof (pimfor_header_t)); display_buffer(p, length); } #endif err = -ENOMEM; buf.pci_addr = pci_map_single(priv->pdev, buf.mem, frag_len, PCI_DMA_TODEVICE); if (!buf.pci_addr) { printk(KERN_WARNING "%s: cannot map PCI memory for mgmt\n", ndev->name); goto error_free; } /* Protect the control block modifications against interrupts. */ spin_lock_irqsave(&priv->slock, flags); curr_frag = le32_to_cpu(cb->driver_curr_frag[ISL38XX_CB_TX_MGMTQ]); if (curr_frag - priv->index_mgmt_tx >= ISL38XX_CB_MGMT_QSIZE) { printk(KERN_WARNING "%s: mgmt tx queue is still full\n", ndev->name); goto error_unlock; } /* commit the frame to the tx device queue */ index = curr_frag % ISL38XX_CB_MGMT_QSIZE; priv->mgmt_tx[index] = buf; frag = &cb->tx_data_mgmt[index]; frag->size = cpu_to_le16(frag_len); frag->flags = 0; /* for any other than the last fragment, set to 1 */ frag->address = cpu_to_le32(buf.pci_addr); /* The fragment address in the control block must have * been written before announcing the frame buffer to * device */ wmb(); cb->driver_curr_frag[ISL38XX_CB_TX_MGMTQ] = cpu_to_le32(curr_frag + 1); spin_unlock_irqrestore(&priv->slock, flags); /* trigger the device */ islpci_trigger(priv); return 0; error_unlock: spin_unlock_irqrestore(&priv->slock, flags); error_free: kfree(buf.mem); error: return err; } /* * Receive a management frame from the device. * This can be an arbitrary number of traps, and at most one response * frame for a previous request sent via islpci_mgt_transmit(). */ int islpci_mgt_receive(struct net_device *ndev) { islpci_private *priv = netdev_priv(ndev); isl38xx_control_block *cb = (isl38xx_control_block *) priv->control_block; u32 curr_frag; #if VERBOSE > SHOW_ERROR_MESSAGES DEBUG(SHOW_FUNCTION_CALLS, "islpci_mgt_receive\n"); #endif /* Only once per interrupt, determine fragment range to * process. This avoids an endless loop (i.e. lockup) if * frames come in faster than we can process them. */ curr_frag = le32_to_cpu(cb->device_curr_frag[ISL38XX_CB_RX_MGMTQ]); barrier(); for (; priv->index_mgmt_rx < curr_frag; priv->index_mgmt_rx++) { pimfor_header_t *header; u32 index = priv->index_mgmt_rx % ISL38XX_CB_MGMT_QSIZE; struct islpci_membuf *buf = &priv->mgmt_rx[index]; u16 frag_len; int size; struct islpci_mgmtframe *frame; /* I have no idea (and no documentation) if flags != 0 * is possible. Drop the frame, reuse the buffer. */ if (le16_to_cpu(cb->rx_data_mgmt[index].flags) != 0) { printk(KERN_WARNING "%s: unknown flags 0x%04x\n", ndev->name, le16_to_cpu(cb->rx_data_mgmt[index].flags)); continue; } /* The device only returns the size of the header(s) here. */ frag_len = le16_to_cpu(cb->rx_data_mgmt[index].size); /* * We appear to have no way to tell the device the * size of a receive buffer. Thus, if this check * triggers, we likely have kernel heap corruption. */ if (frag_len > MGMT_FRAME_SIZE) { printk(KERN_WARNING "%s: Bogus packet size of %d (%#x).\n", ndev->name, frag_len, frag_len); frag_len = MGMT_FRAME_SIZE; } /* Ensure the results of device DMA are visible to the CPU. */ pci_dma_sync_single_for_cpu(priv->pdev, buf->pci_addr, buf->size, PCI_DMA_FROMDEVICE); /* Perform endianess conversion for PIMFOR header in-place. */ header = pimfor_decode_header(buf->mem, frag_len); if (!header) { printk(KERN_WARNING "%s: no PIMFOR header found\n", ndev->name); continue; } /* The device ID from the PIMFOR packet received from * the MVC is always 0. We forward a sensible device_id. * Not that anyone upstream would care... */ header->device_id = priv->ndev->ifindex; #if VERBOSE > SHOW_ERROR_MESSAGES DEBUG(SHOW_PIMFOR_FRAMES, "PIMFOR: op %i, oid 0x%08x, device %i, flags 0x%x length 0x%x\n", header->operation, header->oid, header->device_id, header->flags, header->length); /* display the buffer contents for debugging */ display_buffer((char *) header, PIMFOR_HEADER_SIZE); display_buffer((char *) header + PIMFOR_HEADER_SIZE, header->length); #endif /* nobody sends these */ if (header->flags & PIMFOR_FLAG_APPLIC_ORIGIN) { printk(KERN_DEBUG "%s: errant PIMFOR application frame\n", ndev->name); continue; } /* Determine frame size, skipping OID_INL_TUNNEL headers. */ size = PIMFOR_HEADER_SIZE + header->length; frame = kmalloc(sizeof (struct islpci_mgmtframe) + size, GFP_ATOMIC); if (!frame) { printk(KERN_WARNING "%s: Out of memory, cannot handle oid 0x%08x\n", ndev->name, header->oid); continue; } frame->ndev = ndev; memcpy(&frame->buf, header, size); frame->header = (pimfor_header_t *) frame->buf; frame->data = frame->buf + PIMFOR_HEADER_SIZE; #if VERBOSE > SHOW_ERROR_MESSAGES DEBUG(SHOW_PIMFOR_FRAMES, "frame: header: %p, data: %p, size: %d\n", frame->header, frame->data, size); #endif if (header->operation == PIMFOR_OP_TRAP) { #if VERBOSE > SHOW_ERROR_MESSAGES printk(KERN_DEBUG "TRAP: oid 0x%x, device %i, flags 0x%x length %i\n", header->oid, header->device_id, header->flags, header->length); #endif /* Create work to handle trap out of interrupt * context. */ INIT_WORK(&frame->ws, prism54_process_trap); schedule_work(&frame->ws); } else { /* Signal the one waiting process that a response * has been received. */ if ((frame = xchg(&priv->mgmt_received, frame)) != NULL) { printk(KERN_WARNING "%s: mgmt response not collected\n", ndev->name); kfree(frame); } #if VERBOSE > SHOW_ERROR_MESSAGES DEBUG(SHOW_TRACING, "Wake up Mgmt Queue\n"); #endif wake_up(&priv->mgmt_wqueue); } } return 0; } /* * Cleanup the transmit queue by freeing all frames handled by the device. */ void islpci_mgt_cleanup_transmit(struct net_device *ndev) { islpci_private *priv = netdev_priv(ndev); isl38xx_control_block *cb = /* volatile not needed */ (isl38xx_control_block *) priv->control_block; u32 curr_frag; #if VERBOSE > SHOW_ERROR_MESSAGES DEBUG(SHOW_FUNCTION_CALLS, "islpci_mgt_cleanup_transmit\n"); #endif /* Only once per cleanup, determine fragment range to * process. This avoids an endless loop (i.e. lockup) if * the device became confused, incrementing device_curr_frag * rapidly. */ curr_frag = le32_to_cpu(cb->device_curr_frag[ISL38XX_CB_TX_MGMTQ]); barrier(); for (; priv->index_mgmt_tx < curr_frag; priv->index_mgmt_tx++) { int index = priv->index_mgmt_tx % ISL38XX_CB_MGMT_QSIZE; struct islpci_membuf *buf = &priv->mgmt_tx[index]; pci_unmap_single(priv->pdev, buf->pci_addr, buf->size, PCI_DMA_TODEVICE); buf->pci_addr = 0; kfree(buf->mem); buf->mem = NULL; buf->size = 0; } } /* * Perform one request-response transaction to the device. */ int islpci_mgt_transaction(struct net_device *ndev, int operation, unsigned long oid, void *senddata, int sendlen, struct islpci_mgmtframe **recvframe) { islpci_private *priv = netdev_priv(ndev); const long wait_cycle_jiffies = msecs_to_jiffies(ISL38XX_WAIT_CYCLE * 10); long timeout_left = ISL38XX_MAX_WAIT_CYCLES * wait_cycle_jiffies; int err; DEFINE_WAIT(wait); *recvframe = NULL; if (mutex_lock_interruptible(&priv->mgmt_lock)) return -ERESTARTSYS; prepare_to_wait(&priv->mgmt_wqueue, &wait, TASK_UNINTERRUPTIBLE); err = islpci_mgt_transmit(ndev, operation, oid, senddata, sendlen); if (err) goto out; err = -ETIMEDOUT; while (timeout_left > 0) { int timeleft; struct islpci_mgmtframe *frame; timeleft = schedule_timeout_uninterruptible(wait_cycle_jiffies); frame = xchg(&priv->mgmt_received, NULL); if (frame) { if (frame->header->oid == oid) { *recvframe = frame; err = 0; goto out; } else { printk(KERN_DEBUG "%s: expecting oid 0x%x, received 0x%x.\n", ndev->name, (unsigned int) oid, frame->header->oid); kfree(frame); frame = NULL; } } if (timeleft == 0) { printk(KERN_DEBUG "%s: timeout waiting for mgmt response %lu, " "triggering device\n", ndev->name, timeout_left); islpci_trigger(priv); } timeout_left += timeleft - wait_cycle_jiffies; } printk(KERN_WARNING "%s: timeout waiting for mgmt response\n", ndev->name); /* TODO: we should reset the device here */ out: finish_wait(&priv->mgmt_wqueue, &wait); mutex_unlock(&priv->mgmt_lock); return err; }
gpl-2.0
chasmodo/android_kernel_oneplus_msm8974
drivers/video/sis/init.c
8152
108147
/* $XFree86$ */ /* $XdotOrg$ */ /* * Mode initializing code (CRT1 section) for * for SiS 300/305/540/630/730, * SiS 315/550/[M]650/651/[M]661[FGM]X/[M]74x[GX]/330/[M]76x[GX], * XGI Volari V3XT/V5/V8, Z7 * (Universal module for Linux kernel framebuffer and X.org/XFree86 4.x) * * Copyright (C) 2001-2005 by Thomas Winischhofer, Vienna, Austria * * If distributed as part of the Linux kernel, the following license terms * apply: * * * 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 named 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 * * Otherwise, the following license terms apply: * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * 1) Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * 3) The name of the author may not be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Author: Thomas Winischhofer <thomas@winischhofer.net> * * Formerly based on non-functional code-fragements for 300 series by SiS, Inc. * Used by permission. */ #include "init.h" #ifdef CONFIG_FB_SIS_300 #include "300vtbl.h" #endif #ifdef CONFIG_FB_SIS_315 #include "310vtbl.h" #endif #if defined(ALLOC_PRAGMA) #pragma alloc_text(PAGE,SiSSetMode) #endif /*********************************************/ /* POINTER INITIALIZATION */ /*********************************************/ #if defined(CONFIG_FB_SIS_300) || defined(CONFIG_FB_SIS_315) static void InitCommonPointer(struct SiS_Private *SiS_Pr) { SiS_Pr->SiS_SModeIDTable = SiS_SModeIDTable; SiS_Pr->SiS_StResInfo = SiS_StResInfo; SiS_Pr->SiS_ModeResInfo = SiS_ModeResInfo; SiS_Pr->SiS_StandTable = SiS_StandTable; SiS_Pr->SiS_NTSCTiming = SiS_NTSCTiming; SiS_Pr->SiS_PALTiming = SiS_PALTiming; SiS_Pr->SiS_HiTVSt1Timing = SiS_HiTVSt1Timing; SiS_Pr->SiS_HiTVSt2Timing = SiS_HiTVSt2Timing; SiS_Pr->SiS_HiTVExtTiming = SiS_HiTVExtTiming; SiS_Pr->SiS_HiTVGroup3Data = SiS_HiTVGroup3Data; SiS_Pr->SiS_HiTVGroup3Simu = SiS_HiTVGroup3Simu; #if 0 SiS_Pr->SiS_HiTVTextTiming = SiS_HiTVTextTiming; SiS_Pr->SiS_HiTVGroup3Text = SiS_HiTVGroup3Text; #endif SiS_Pr->SiS_StPALData = SiS_StPALData; SiS_Pr->SiS_ExtPALData = SiS_ExtPALData; SiS_Pr->SiS_StNTSCData = SiS_StNTSCData; SiS_Pr->SiS_ExtNTSCData = SiS_ExtNTSCData; SiS_Pr->SiS_St1HiTVData = SiS_StHiTVData; SiS_Pr->SiS_St2HiTVData = SiS_St2HiTVData; SiS_Pr->SiS_ExtHiTVData = SiS_ExtHiTVData; SiS_Pr->SiS_St525iData = SiS_StNTSCData; SiS_Pr->SiS_St525pData = SiS_St525pData; SiS_Pr->SiS_St750pData = SiS_St750pData; SiS_Pr->SiS_Ext525iData = SiS_ExtNTSCData; SiS_Pr->SiS_Ext525pData = SiS_ExtNTSCData; SiS_Pr->SiS_Ext750pData = SiS_Ext750pData; SiS_Pr->pSiS_OutputSelect = &SiS_OutputSelect; SiS_Pr->pSiS_SoftSetting = &SiS_SoftSetting; SiS_Pr->SiS_LCD1280x720Data = SiS_LCD1280x720Data; SiS_Pr->SiS_StLCD1280x768_2Data = SiS_StLCD1280x768_2Data; SiS_Pr->SiS_ExtLCD1280x768_2Data = SiS_ExtLCD1280x768_2Data; SiS_Pr->SiS_LCD1280x800Data = SiS_LCD1280x800Data; SiS_Pr->SiS_LCD1280x800_2Data = SiS_LCD1280x800_2Data; SiS_Pr->SiS_LCD1280x854Data = SiS_LCD1280x854Data; SiS_Pr->SiS_LCD1280x960Data = SiS_LCD1280x960Data; SiS_Pr->SiS_StLCD1400x1050Data = SiS_StLCD1400x1050Data; SiS_Pr->SiS_ExtLCD1400x1050Data = SiS_ExtLCD1400x1050Data; SiS_Pr->SiS_LCD1680x1050Data = SiS_LCD1680x1050Data; SiS_Pr->SiS_StLCD1600x1200Data = SiS_StLCD1600x1200Data; SiS_Pr->SiS_ExtLCD1600x1200Data = SiS_ExtLCD1600x1200Data; SiS_Pr->SiS_NoScaleData = SiS_NoScaleData; SiS_Pr->SiS_LVDS320x240Data_1 = SiS_LVDS320x240Data_1; SiS_Pr->SiS_LVDS320x240Data_2 = SiS_LVDS320x240Data_2; SiS_Pr->SiS_LVDS640x480Data_1 = SiS_LVDS640x480Data_1; SiS_Pr->SiS_LVDS800x600Data_1 = SiS_LVDS800x600Data_1; SiS_Pr->SiS_LVDS1024x600Data_1 = SiS_LVDS1024x600Data_1; SiS_Pr->SiS_LVDS1024x768Data_1 = SiS_LVDS1024x768Data_1; SiS_Pr->SiS_LVDSCRT1320x240_1 = SiS_LVDSCRT1320x240_1; SiS_Pr->SiS_LVDSCRT1320x240_2 = SiS_LVDSCRT1320x240_2; SiS_Pr->SiS_LVDSCRT1320x240_2_H = SiS_LVDSCRT1320x240_2_H; SiS_Pr->SiS_LVDSCRT1320x240_3 = SiS_LVDSCRT1320x240_3; SiS_Pr->SiS_LVDSCRT1320x240_3_H = SiS_LVDSCRT1320x240_3_H; SiS_Pr->SiS_LVDSCRT1640x480_1 = SiS_LVDSCRT1640x480_1; SiS_Pr->SiS_LVDSCRT1640x480_1_H = SiS_LVDSCRT1640x480_1_H; #if 0 SiS_Pr->SiS_LVDSCRT11024x600_1 = SiS_LVDSCRT11024x600_1; SiS_Pr->SiS_LVDSCRT11024x600_1_H = SiS_LVDSCRT11024x600_1_H; SiS_Pr->SiS_LVDSCRT11024x600_2 = SiS_LVDSCRT11024x600_2; SiS_Pr->SiS_LVDSCRT11024x600_2_H = SiS_LVDSCRT11024x600_2_H; #endif SiS_Pr->SiS_CHTVUNTSCData = SiS_CHTVUNTSCData; SiS_Pr->SiS_CHTVONTSCData = SiS_CHTVONTSCData; SiS_Pr->SiS_PanelMinLVDS = Panel_800x600; /* lowest value LVDS/LCDA */ SiS_Pr->SiS_PanelMin301 = Panel_1024x768; /* lowest value 301 */ } #endif #ifdef CONFIG_FB_SIS_300 static void InitTo300Pointer(struct SiS_Private *SiS_Pr) { InitCommonPointer(SiS_Pr); SiS_Pr->SiS_VBModeIDTable = SiS300_VBModeIDTable; SiS_Pr->SiS_EModeIDTable = SiS300_EModeIDTable; SiS_Pr->SiS_RefIndex = SiS300_RefIndex; SiS_Pr->SiS_CRT1Table = SiS300_CRT1Table; if(SiS_Pr->ChipType == SIS_300) { SiS_Pr->SiS_MCLKData_0 = SiS300_MCLKData_300; /* 300 */ } else { SiS_Pr->SiS_MCLKData_0 = SiS300_MCLKData_630; /* 630, 730 */ } SiS_Pr->SiS_VCLKData = SiS300_VCLKData; SiS_Pr->SiS_VBVCLKData = (struct SiS_VBVCLKData *)SiS300_VCLKData; SiS_Pr->SiS_SR15 = SiS300_SR15; SiS_Pr->SiS_PanelDelayTbl = SiS300_PanelDelayTbl; SiS_Pr->SiS_PanelDelayTblLVDS = SiS300_PanelDelayTbl; SiS_Pr->SiS_ExtLCD1024x768Data = SiS300_ExtLCD1024x768Data; SiS_Pr->SiS_St2LCD1024x768Data = SiS300_St2LCD1024x768Data; SiS_Pr->SiS_ExtLCD1280x1024Data = SiS300_ExtLCD1280x1024Data; SiS_Pr->SiS_St2LCD1280x1024Data = SiS300_St2LCD1280x1024Data; SiS_Pr->SiS_CRT2Part2_1024x768_1 = SiS300_CRT2Part2_1024x768_1; SiS_Pr->SiS_CRT2Part2_1024x768_2 = SiS300_CRT2Part2_1024x768_2; SiS_Pr->SiS_CRT2Part2_1024x768_3 = SiS300_CRT2Part2_1024x768_3; SiS_Pr->SiS_CHTVUPALData = SiS300_CHTVUPALData; SiS_Pr->SiS_CHTVOPALData = SiS300_CHTVOPALData; SiS_Pr->SiS_CHTVUPALMData = SiS_CHTVUNTSCData; /* not supported on 300 series */ SiS_Pr->SiS_CHTVOPALMData = SiS_CHTVONTSCData; /* not supported on 300 series */ SiS_Pr->SiS_CHTVUPALNData = SiS300_CHTVUPALData; /* not supported on 300 series */ SiS_Pr->SiS_CHTVOPALNData = SiS300_CHTVOPALData; /* not supported on 300 series */ SiS_Pr->SiS_CHTVSOPALData = SiS300_CHTVSOPALData; SiS_Pr->SiS_LVDS848x480Data_1 = SiS300_LVDS848x480Data_1; SiS_Pr->SiS_LVDS848x480Data_2 = SiS300_LVDS848x480Data_2; SiS_Pr->SiS_LVDSBARCO1024Data_1 = SiS300_LVDSBARCO1024Data_1; SiS_Pr->SiS_LVDSBARCO1366Data_1 = SiS300_LVDSBARCO1366Data_1; SiS_Pr->SiS_LVDSBARCO1366Data_2 = SiS300_LVDSBARCO1366Data_2; SiS_Pr->SiS_PanelType04_1a = SiS300_PanelType04_1a; SiS_Pr->SiS_PanelType04_2a = SiS300_PanelType04_2a; SiS_Pr->SiS_PanelType04_1b = SiS300_PanelType04_1b; SiS_Pr->SiS_PanelType04_2b = SiS300_PanelType04_2b; SiS_Pr->SiS_CHTVCRT1UNTSC = SiS300_CHTVCRT1UNTSC; SiS_Pr->SiS_CHTVCRT1ONTSC = SiS300_CHTVCRT1ONTSC; SiS_Pr->SiS_CHTVCRT1UPAL = SiS300_CHTVCRT1UPAL; SiS_Pr->SiS_CHTVCRT1OPAL = SiS300_CHTVCRT1OPAL; SiS_Pr->SiS_CHTVCRT1SOPAL = SiS300_CHTVCRT1SOPAL; SiS_Pr->SiS_CHTVReg_UNTSC = SiS300_CHTVReg_UNTSC; SiS_Pr->SiS_CHTVReg_ONTSC = SiS300_CHTVReg_ONTSC; SiS_Pr->SiS_CHTVReg_UPAL = SiS300_CHTVReg_UPAL; SiS_Pr->SiS_CHTVReg_OPAL = SiS300_CHTVReg_OPAL; SiS_Pr->SiS_CHTVReg_UPALM = SiS300_CHTVReg_UNTSC; /* not supported on 300 series */ SiS_Pr->SiS_CHTVReg_OPALM = SiS300_CHTVReg_ONTSC; /* not supported on 300 series */ SiS_Pr->SiS_CHTVReg_UPALN = SiS300_CHTVReg_UPAL; /* not supported on 300 series */ SiS_Pr->SiS_CHTVReg_OPALN = SiS300_CHTVReg_OPAL; /* not supported on 300 series */ SiS_Pr->SiS_CHTVReg_SOPAL = SiS300_CHTVReg_SOPAL; SiS_Pr->SiS_CHTVVCLKUNTSC = SiS300_CHTVVCLKUNTSC; SiS_Pr->SiS_CHTVVCLKONTSC = SiS300_CHTVVCLKONTSC; SiS_Pr->SiS_CHTVVCLKUPAL = SiS300_CHTVVCLKUPAL; SiS_Pr->SiS_CHTVVCLKOPAL = SiS300_CHTVVCLKOPAL; SiS_Pr->SiS_CHTVVCLKUPALM = SiS300_CHTVVCLKUNTSC; /* not supported on 300 series */ SiS_Pr->SiS_CHTVVCLKOPALM = SiS300_CHTVVCLKONTSC; /* not supported on 300 series */ SiS_Pr->SiS_CHTVVCLKUPALN = SiS300_CHTVVCLKUPAL; /* not supported on 300 series */ SiS_Pr->SiS_CHTVVCLKOPALN = SiS300_CHTVVCLKOPAL; /* not supported on 300 series */ SiS_Pr->SiS_CHTVVCLKSOPAL = SiS300_CHTVVCLKSOPAL; } #endif #ifdef CONFIG_FB_SIS_315 static void InitTo310Pointer(struct SiS_Private *SiS_Pr) { InitCommonPointer(SiS_Pr); SiS_Pr->SiS_EModeIDTable = SiS310_EModeIDTable; SiS_Pr->SiS_RefIndex = SiS310_RefIndex; SiS_Pr->SiS_CRT1Table = SiS310_CRT1Table; if(SiS_Pr->ChipType >= SIS_340) { SiS_Pr->SiS_MCLKData_0 = SiS310_MCLKData_0_340; /* 340 + XGI */ } else if(SiS_Pr->ChipType >= SIS_761) { SiS_Pr->SiS_MCLKData_0 = SiS310_MCLKData_0_761; /* 761 - preliminary */ } else if(SiS_Pr->ChipType >= SIS_760) { SiS_Pr->SiS_MCLKData_0 = SiS310_MCLKData_0_760; /* 760 */ } else if(SiS_Pr->ChipType >= SIS_661) { SiS_Pr->SiS_MCLKData_0 = SiS310_MCLKData_0_660; /* 661/741 */ } else if(SiS_Pr->ChipType == SIS_330) { SiS_Pr->SiS_MCLKData_0 = SiS310_MCLKData_0_330; /* 330 */ } else if(SiS_Pr->ChipType > SIS_315PRO) { SiS_Pr->SiS_MCLKData_0 = SiS310_MCLKData_0_650; /* 550, 650, 740 */ } else { SiS_Pr->SiS_MCLKData_0 = SiS310_MCLKData_0_315; /* 315 */ } if(SiS_Pr->ChipType >= SIS_340) { SiS_Pr->SiS_MCLKData_1 = SiS310_MCLKData_1_340; } else { SiS_Pr->SiS_MCLKData_1 = SiS310_MCLKData_1; } SiS_Pr->SiS_VCLKData = SiS310_VCLKData; SiS_Pr->SiS_VBVCLKData = SiS310_VBVCLKData; SiS_Pr->SiS_SR15 = SiS310_SR15; SiS_Pr->SiS_PanelDelayTbl = SiS310_PanelDelayTbl; SiS_Pr->SiS_PanelDelayTblLVDS = SiS310_PanelDelayTblLVDS; SiS_Pr->SiS_St2LCD1024x768Data = SiS310_St2LCD1024x768Data; SiS_Pr->SiS_ExtLCD1024x768Data = SiS310_ExtLCD1024x768Data; SiS_Pr->SiS_St2LCD1280x1024Data = SiS310_St2LCD1280x1024Data; SiS_Pr->SiS_ExtLCD1280x1024Data = SiS310_ExtLCD1280x1024Data; SiS_Pr->SiS_CRT2Part2_1024x768_1 = SiS310_CRT2Part2_1024x768_1; SiS_Pr->SiS_CHTVUPALData = SiS310_CHTVUPALData; SiS_Pr->SiS_CHTVOPALData = SiS310_CHTVOPALData; SiS_Pr->SiS_CHTVUPALMData = SiS310_CHTVUPALMData; SiS_Pr->SiS_CHTVOPALMData = SiS310_CHTVOPALMData; SiS_Pr->SiS_CHTVUPALNData = SiS310_CHTVUPALNData; SiS_Pr->SiS_CHTVOPALNData = SiS310_CHTVOPALNData; SiS_Pr->SiS_CHTVSOPALData = SiS310_CHTVSOPALData; SiS_Pr->SiS_CHTVCRT1UNTSC = SiS310_CHTVCRT1UNTSC; SiS_Pr->SiS_CHTVCRT1ONTSC = SiS310_CHTVCRT1ONTSC; SiS_Pr->SiS_CHTVCRT1UPAL = SiS310_CHTVCRT1UPAL; SiS_Pr->SiS_CHTVCRT1OPAL = SiS310_CHTVCRT1OPAL; SiS_Pr->SiS_CHTVCRT1SOPAL = SiS310_CHTVCRT1OPAL; SiS_Pr->SiS_CHTVReg_UNTSC = SiS310_CHTVReg_UNTSC; SiS_Pr->SiS_CHTVReg_ONTSC = SiS310_CHTVReg_ONTSC; SiS_Pr->SiS_CHTVReg_UPAL = SiS310_CHTVReg_UPAL; SiS_Pr->SiS_CHTVReg_OPAL = SiS310_CHTVReg_OPAL; SiS_Pr->SiS_CHTVReg_UPALM = SiS310_CHTVReg_UPALM; SiS_Pr->SiS_CHTVReg_OPALM = SiS310_CHTVReg_OPALM; SiS_Pr->SiS_CHTVReg_UPALN = SiS310_CHTVReg_UPALN; SiS_Pr->SiS_CHTVReg_OPALN = SiS310_CHTVReg_OPALN; SiS_Pr->SiS_CHTVReg_SOPAL = SiS310_CHTVReg_OPAL; SiS_Pr->SiS_CHTVVCLKUNTSC = SiS310_CHTVVCLKUNTSC; SiS_Pr->SiS_CHTVVCLKONTSC = SiS310_CHTVVCLKONTSC; SiS_Pr->SiS_CHTVVCLKUPAL = SiS310_CHTVVCLKUPAL; SiS_Pr->SiS_CHTVVCLKOPAL = SiS310_CHTVVCLKOPAL; SiS_Pr->SiS_CHTVVCLKUPALM = SiS310_CHTVVCLKUPALM; SiS_Pr->SiS_CHTVVCLKOPALM = SiS310_CHTVVCLKOPALM; SiS_Pr->SiS_CHTVVCLKUPALN = SiS310_CHTVVCLKUPALN; SiS_Pr->SiS_CHTVVCLKOPALN = SiS310_CHTVVCLKOPALN; SiS_Pr->SiS_CHTVVCLKSOPAL = SiS310_CHTVVCLKOPAL; } #endif bool SiSInitPtr(struct SiS_Private *SiS_Pr) { if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 InitTo300Pointer(SiS_Pr); #else return false; #endif } else { #ifdef CONFIG_FB_SIS_315 InitTo310Pointer(SiS_Pr); #else return false; #endif } return true; } /*********************************************/ /* HELPER: Get ModeID */ /*********************************************/ static unsigned short SiS_GetModeID(int VGAEngine, unsigned int VBFlags, int HDisplay, int VDisplay, int Depth, bool FSTN, int LCDwidth, int LCDheight) { unsigned short ModeIndex = 0; switch(HDisplay) { case 320: if(VDisplay == 200) ModeIndex = ModeIndex_320x200[Depth]; else if(VDisplay == 240) { if((VBFlags & CRT2_LCD) && (FSTN)) ModeIndex = ModeIndex_320x240_FSTN[Depth]; else ModeIndex = ModeIndex_320x240[Depth]; } break; case 400: if((!(VBFlags & CRT1_LCDA)) || ((LCDwidth >= 800) && (LCDwidth >= 600))) { if(VDisplay == 300) ModeIndex = ModeIndex_400x300[Depth]; } break; case 512: if((!(VBFlags & CRT1_LCDA)) || ((LCDwidth >= 1024) && (LCDwidth >= 768))) { if(VDisplay == 384) ModeIndex = ModeIndex_512x384[Depth]; } break; case 640: if(VDisplay == 480) ModeIndex = ModeIndex_640x480[Depth]; else if(VDisplay == 400) ModeIndex = ModeIndex_640x400[Depth]; break; case 720: if(VDisplay == 480) ModeIndex = ModeIndex_720x480[Depth]; else if(VDisplay == 576) ModeIndex = ModeIndex_720x576[Depth]; break; case 768: if(VDisplay == 576) ModeIndex = ModeIndex_768x576[Depth]; break; case 800: if(VDisplay == 600) ModeIndex = ModeIndex_800x600[Depth]; else if(VDisplay == 480) ModeIndex = ModeIndex_800x480[Depth]; break; case 848: if(VDisplay == 480) ModeIndex = ModeIndex_848x480[Depth]; break; case 856: if(VDisplay == 480) ModeIndex = ModeIndex_856x480[Depth]; break; case 960: if(VGAEngine == SIS_315_VGA) { if(VDisplay == 540) ModeIndex = ModeIndex_960x540[Depth]; else if(VDisplay == 600) ModeIndex = ModeIndex_960x600[Depth]; } break; case 1024: if(VDisplay == 576) ModeIndex = ModeIndex_1024x576[Depth]; else if(VDisplay == 768) ModeIndex = ModeIndex_1024x768[Depth]; else if(VGAEngine == SIS_300_VGA) { if(VDisplay == 600) ModeIndex = ModeIndex_1024x600[Depth]; } break; case 1152: if(VDisplay == 864) ModeIndex = ModeIndex_1152x864[Depth]; if(VGAEngine == SIS_300_VGA) { if(VDisplay == 768) ModeIndex = ModeIndex_1152x768[Depth]; } break; case 1280: switch(VDisplay) { case 720: ModeIndex = ModeIndex_1280x720[Depth]; break; case 768: if(VGAEngine == SIS_300_VGA) { ModeIndex = ModeIndex_300_1280x768[Depth]; } else { ModeIndex = ModeIndex_310_1280x768[Depth]; } break; case 800: if(VGAEngine == SIS_315_VGA) { ModeIndex = ModeIndex_1280x800[Depth]; } break; case 854: if(VGAEngine == SIS_315_VGA) { ModeIndex = ModeIndex_1280x854[Depth]; } break; case 960: ModeIndex = ModeIndex_1280x960[Depth]; break; case 1024: ModeIndex = ModeIndex_1280x1024[Depth]; break; } break; case 1360: if(VDisplay == 768) ModeIndex = ModeIndex_1360x768[Depth]; if(VGAEngine == SIS_300_VGA) { if(VDisplay == 1024) ModeIndex = ModeIndex_300_1360x1024[Depth]; } break; case 1400: if(VGAEngine == SIS_315_VGA) { if(VDisplay == 1050) { ModeIndex = ModeIndex_1400x1050[Depth]; } } break; case 1600: if(VDisplay == 1200) ModeIndex = ModeIndex_1600x1200[Depth]; break; case 1680: if(VGAEngine == SIS_315_VGA) { if(VDisplay == 1050) ModeIndex = ModeIndex_1680x1050[Depth]; } break; case 1920: if(VDisplay == 1440) ModeIndex = ModeIndex_1920x1440[Depth]; else if(VGAEngine == SIS_315_VGA) { if(VDisplay == 1080) ModeIndex = ModeIndex_1920x1080[Depth]; } break; case 2048: if(VDisplay == 1536) { if(VGAEngine == SIS_300_VGA) { ModeIndex = ModeIndex_300_2048x1536[Depth]; } else { ModeIndex = ModeIndex_310_2048x1536[Depth]; } } break; } return ModeIndex; } unsigned short SiS_GetModeID_LCD(int VGAEngine, unsigned int VBFlags, int HDisplay, int VDisplay, int Depth, bool FSTN, unsigned short CustomT, int LCDwidth, int LCDheight, unsigned int VBFlags2) { unsigned short ModeIndex = 0; if(VBFlags2 & (VB2_LVDS | VB2_30xBDH)) { switch(HDisplay) { case 320: if((CustomT != CUT_PANEL848) && (CustomT != CUT_PANEL856)) { if(VDisplay == 200) { if(!FSTN) ModeIndex = ModeIndex_320x200[Depth]; } else if(VDisplay == 240) { if(!FSTN) ModeIndex = ModeIndex_320x240[Depth]; else if(VGAEngine == SIS_315_VGA) { ModeIndex = ModeIndex_320x240_FSTN[Depth]; } } } break; case 400: if((CustomT != CUT_PANEL848) && (CustomT != CUT_PANEL856)) { if(!((VGAEngine == SIS_300_VGA) && (VBFlags2 & VB2_TRUMPION))) { if(VDisplay == 300) ModeIndex = ModeIndex_400x300[Depth]; } } break; case 512: if((CustomT != CUT_PANEL848) && (CustomT != CUT_PANEL856)) { if(!((VGAEngine == SIS_300_VGA) && (VBFlags2 & VB2_TRUMPION))) { if(LCDwidth >= 1024 && LCDwidth != 1152 && LCDheight >= 768) { if(VDisplay == 384) { ModeIndex = ModeIndex_512x384[Depth]; } } } } break; case 640: if(VDisplay == 480) ModeIndex = ModeIndex_640x480[Depth]; else if(VDisplay == 400) { if((CustomT != CUT_PANEL848) && (CustomT != CUT_PANEL856)) ModeIndex = ModeIndex_640x400[Depth]; } break; case 800: if(VDisplay == 600) ModeIndex = ModeIndex_800x600[Depth]; break; case 848: if(CustomT == CUT_PANEL848) { if(VDisplay == 480) ModeIndex = ModeIndex_848x480[Depth]; } break; case 856: if(CustomT == CUT_PANEL856) { if(VDisplay == 480) ModeIndex = ModeIndex_856x480[Depth]; } break; case 1024: if(VDisplay == 768) ModeIndex = ModeIndex_1024x768[Depth]; else if(VGAEngine == SIS_300_VGA) { if((VDisplay == 600) && (LCDheight == 600)) { ModeIndex = ModeIndex_1024x600[Depth]; } } break; case 1152: if(VGAEngine == SIS_300_VGA) { if((VDisplay == 768) && (LCDheight == 768)) { ModeIndex = ModeIndex_1152x768[Depth]; } } break; case 1280: if(VDisplay == 1024) ModeIndex = ModeIndex_1280x1024[Depth]; else if(VGAEngine == SIS_315_VGA) { if((VDisplay == 768) && (LCDheight == 768)) { ModeIndex = ModeIndex_310_1280x768[Depth]; } } break; case 1360: if(VGAEngine == SIS_300_VGA) { if(CustomT == CUT_BARCO1366) { if(VDisplay == 1024) ModeIndex = ModeIndex_300_1360x1024[Depth]; } } if(CustomT == CUT_PANEL848) { if(VDisplay == 768) ModeIndex = ModeIndex_1360x768[Depth]; } break; case 1400: if(VGAEngine == SIS_315_VGA) { if(VDisplay == 1050) ModeIndex = ModeIndex_1400x1050[Depth]; } break; case 1600: if(VGAEngine == SIS_315_VGA) { if(VDisplay == 1200) ModeIndex = ModeIndex_1600x1200[Depth]; } break; } } else if(VBFlags2 & VB2_SISBRIDGE) { switch(HDisplay) { case 320: if(VDisplay == 200) ModeIndex = ModeIndex_320x200[Depth]; else if(VDisplay == 240) ModeIndex = ModeIndex_320x240[Depth]; break; case 400: if(LCDwidth >= 800 && LCDheight >= 600) { if(VDisplay == 300) ModeIndex = ModeIndex_400x300[Depth]; } break; case 512: if(LCDwidth >= 1024 && LCDheight >= 768 && LCDwidth != 1152) { if(VDisplay == 384) ModeIndex = ModeIndex_512x384[Depth]; } break; case 640: if(VDisplay == 480) ModeIndex = ModeIndex_640x480[Depth]; else if(VDisplay == 400) ModeIndex = ModeIndex_640x400[Depth]; break; case 720: if(VGAEngine == SIS_315_VGA) { if(VDisplay == 480) ModeIndex = ModeIndex_720x480[Depth]; else if(VDisplay == 576) ModeIndex = ModeIndex_720x576[Depth]; } break; case 768: if(VGAEngine == SIS_315_VGA) { if(VDisplay == 576) ModeIndex = ModeIndex_768x576[Depth]; } break; case 800: if(VDisplay == 600) ModeIndex = ModeIndex_800x600[Depth]; if(VGAEngine == SIS_315_VGA) { if(VDisplay == 480) ModeIndex = ModeIndex_800x480[Depth]; } break; case 848: if(VGAEngine == SIS_315_VGA) { if(VDisplay == 480) ModeIndex = ModeIndex_848x480[Depth]; } break; case 856: if(VGAEngine == SIS_315_VGA) { if(VDisplay == 480) ModeIndex = ModeIndex_856x480[Depth]; } break; case 960: if(VGAEngine == SIS_315_VGA) { if(VDisplay == 540) ModeIndex = ModeIndex_960x540[Depth]; else if(VDisplay == 600) ModeIndex = ModeIndex_960x600[Depth]; } break; case 1024: if(VDisplay == 768) ModeIndex = ModeIndex_1024x768[Depth]; if(VGAEngine == SIS_315_VGA) { if(VDisplay == 576) ModeIndex = ModeIndex_1024x576[Depth]; } break; case 1152: if(VGAEngine == SIS_315_VGA) { if(VDisplay == 864) ModeIndex = ModeIndex_1152x864[Depth]; } break; case 1280: switch(VDisplay) { case 720: ModeIndex = ModeIndex_1280x720[Depth]; case 768: if(VGAEngine == SIS_300_VGA) { ModeIndex = ModeIndex_300_1280x768[Depth]; } else { ModeIndex = ModeIndex_310_1280x768[Depth]; } break; case 800: if(VGAEngine == SIS_315_VGA) { ModeIndex = ModeIndex_1280x800[Depth]; } break; case 854: if(VGAEngine == SIS_315_VGA) { ModeIndex = ModeIndex_1280x854[Depth]; } break; case 960: ModeIndex = ModeIndex_1280x960[Depth]; break; case 1024: ModeIndex = ModeIndex_1280x1024[Depth]; break; } break; case 1360: if(VGAEngine == SIS_315_VGA) { /* OVER1280 only? */ if(VDisplay == 768) ModeIndex = ModeIndex_1360x768[Depth]; } break; case 1400: if(VGAEngine == SIS_315_VGA) { if(VBFlags2 & VB2_LCDOVER1280BRIDGE) { if(VDisplay == 1050) ModeIndex = ModeIndex_1400x1050[Depth]; } } break; case 1600: if(VGAEngine == SIS_315_VGA) { if(VBFlags2 & VB2_LCDOVER1280BRIDGE) { if(VDisplay == 1200) ModeIndex = ModeIndex_1600x1200[Depth]; } } break; #ifndef VB_FORBID_CRT2LCD_OVER_1600 case 1680: if(VGAEngine == SIS_315_VGA) { if(VBFlags2 & VB2_LCDOVER1280BRIDGE) { if(VDisplay == 1050) ModeIndex = ModeIndex_1680x1050[Depth]; } } break; case 1920: if(VGAEngine == SIS_315_VGA) { if(VBFlags2 & VB2_LCDOVER1600BRIDGE) { if(VDisplay == 1440) ModeIndex = ModeIndex_1920x1440[Depth]; } } break; case 2048: if(VGAEngine == SIS_315_VGA) { if(VBFlags2 & VB2_LCDOVER1600BRIDGE) { if(VDisplay == 1536) ModeIndex = ModeIndex_310_2048x1536[Depth]; } } break; #endif } } return ModeIndex; } unsigned short SiS_GetModeID_TV(int VGAEngine, unsigned int VBFlags, int HDisplay, int VDisplay, int Depth, unsigned int VBFlags2) { unsigned short ModeIndex = 0; if(VBFlags2 & VB2_CHRONTEL) { switch(HDisplay) { case 512: if(VGAEngine == SIS_315_VGA) { if(VDisplay == 384) ModeIndex = ModeIndex_512x384[Depth]; } break; case 640: if(VDisplay == 480) ModeIndex = ModeIndex_640x480[Depth]; else if(VDisplay == 400) ModeIndex = ModeIndex_640x400[Depth]; break; case 800: if(VDisplay == 600) ModeIndex = ModeIndex_800x600[Depth]; break; case 1024: if(VGAEngine == SIS_315_VGA) { if(VDisplay == 768) ModeIndex = ModeIndex_1024x768[Depth]; } break; } } else if(VBFlags2 & VB2_SISTVBRIDGE) { switch(HDisplay) { case 320: if(VDisplay == 200) ModeIndex = ModeIndex_320x200[Depth]; else if(VDisplay == 240) ModeIndex = ModeIndex_320x240[Depth]; break; case 400: if(VDisplay == 300) ModeIndex = ModeIndex_400x300[Depth]; break; case 512: if( ((VBFlags & TV_YPBPR) && (VBFlags & (TV_YPBPR750P | TV_YPBPR1080I))) || (VBFlags & TV_HIVISION) || ((!(VBFlags & (TV_YPBPR | TV_PALM))) && (VBFlags & TV_PAL)) ) { if(VDisplay == 384) ModeIndex = ModeIndex_512x384[Depth]; } break; case 640: if(VDisplay == 480) ModeIndex = ModeIndex_640x480[Depth]; else if(VDisplay == 400) ModeIndex = ModeIndex_640x400[Depth]; break; case 720: if((!(VBFlags & TV_HIVISION)) && (!((VBFlags & TV_YPBPR) && (VBFlags & TV_YPBPR1080I)))) { if(VDisplay == 480) { ModeIndex = ModeIndex_720x480[Depth]; } else if(VDisplay == 576) { if( ((VBFlags & TV_YPBPR) && (VBFlags & TV_YPBPR750P)) || ((!(VBFlags & (TV_YPBPR | TV_PALM))) && (VBFlags & TV_PAL)) ) ModeIndex = ModeIndex_720x576[Depth]; } } break; case 768: if((!(VBFlags & TV_HIVISION)) && (!((VBFlags & TV_YPBPR) && (VBFlags & TV_YPBPR1080I)))) { if( ((VBFlags & TV_YPBPR) && (VBFlags & TV_YPBPR750P)) || ((!(VBFlags & (TV_YPBPR | TV_PALM))) && (VBFlags & TV_PAL)) ) { if(VDisplay == 576) ModeIndex = ModeIndex_768x576[Depth]; } } break; case 800: if(VDisplay == 600) ModeIndex = ModeIndex_800x600[Depth]; else if(VDisplay == 480) { if(!((VBFlags & TV_YPBPR) && (VBFlags & TV_YPBPR750P))) { ModeIndex = ModeIndex_800x480[Depth]; } } break; case 960: if(VGAEngine == SIS_315_VGA) { if(VDisplay == 600) { if((VBFlags & TV_HIVISION) || ((VBFlags & TV_YPBPR) && (VBFlags & TV_YPBPR1080I))) { ModeIndex = ModeIndex_960x600[Depth]; } } } break; case 1024: if(VDisplay == 768) { if(VBFlags2 & VB2_30xBLV) { ModeIndex = ModeIndex_1024x768[Depth]; } } else if(VDisplay == 576) { if( (VBFlags & TV_HIVISION) || ((VBFlags & TV_YPBPR) && (VBFlags & TV_YPBPR1080I)) || ((VBFlags2 & VB2_30xBLV) && ((!(VBFlags & (TV_YPBPR | TV_PALM))) && (VBFlags & TV_PAL))) ) { ModeIndex = ModeIndex_1024x576[Depth]; } } break; case 1280: if(VDisplay == 720) { if((VBFlags & TV_HIVISION) || ((VBFlags & TV_YPBPR) && (VBFlags & (TV_YPBPR1080I | TV_YPBPR750P)))) { ModeIndex = ModeIndex_1280x720[Depth]; } } else if(VDisplay == 1024) { if((VBFlags & TV_HIVISION) || ((VBFlags & TV_YPBPR) && (VBFlags & TV_YPBPR1080I))) { ModeIndex = ModeIndex_1280x1024[Depth]; } } break; } } return ModeIndex; } unsigned short SiS_GetModeID_VGA2(int VGAEngine, unsigned int VBFlags, int HDisplay, int VDisplay, int Depth, unsigned int VBFlags2) { if(!(VBFlags2 & VB2_SISVGA2BRIDGE)) return 0; if(HDisplay >= 1920) return 0; switch(HDisplay) { case 1600: if(VDisplay == 1200) { if(VGAEngine != SIS_315_VGA) return 0; if(!(VBFlags2 & VB2_30xB)) return 0; } break; case 1680: if(VDisplay == 1050) { if(VGAEngine != SIS_315_VGA) return 0; if(!(VBFlags2 & VB2_30xB)) return 0; } break; } return SiS_GetModeID(VGAEngine, 0, HDisplay, VDisplay, Depth, false, 0, 0); } /*********************************************/ /* HELPER: SetReg, GetReg */ /*********************************************/ void SiS_SetReg(SISIOADDRESS port, u8 index, u8 data) { outb(index, port); outb(data, port + 1); } void SiS_SetRegByte(SISIOADDRESS port, u8 data) { outb(data, port); } void SiS_SetRegShort(SISIOADDRESS port, u16 data) { outw(data, port); } void SiS_SetRegLong(SISIOADDRESS port, u32 data) { outl(data, port); } u8 SiS_GetReg(SISIOADDRESS port, u8 index) { outb(index, port); return inb(port + 1); } u8 SiS_GetRegByte(SISIOADDRESS port) { return inb(port); } u16 SiS_GetRegShort(SISIOADDRESS port) { return inw(port); } u32 SiS_GetRegLong(SISIOADDRESS port) { return inl(port); } void SiS_SetRegANDOR(SISIOADDRESS Port, u8 Index, u8 DataAND, u8 DataOR) { u8 temp; temp = SiS_GetReg(Port, Index); temp = (temp & (DataAND)) | DataOR; SiS_SetReg(Port, Index, temp); } void SiS_SetRegAND(SISIOADDRESS Port, u8 Index, u8 DataAND) { u8 temp; temp = SiS_GetReg(Port, Index); temp &= DataAND; SiS_SetReg(Port, Index, temp); } void SiS_SetRegOR(SISIOADDRESS Port, u8 Index, u8 DataOR) { u8 temp; temp = SiS_GetReg(Port, Index); temp |= DataOR; SiS_SetReg(Port, Index, temp); } /*********************************************/ /* HELPER: DisplayOn, DisplayOff */ /*********************************************/ void SiS_DisplayOn(struct SiS_Private *SiS_Pr) { SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x01,0xDF); } void SiS_DisplayOff(struct SiS_Private *SiS_Pr) { SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x01,0x20); } /*********************************************/ /* HELPER: Init Port Addresses */ /*********************************************/ void SiSRegInit(struct SiS_Private *SiS_Pr, SISIOADDRESS BaseAddr) { SiS_Pr->SiS_P3c4 = BaseAddr + 0x14; SiS_Pr->SiS_P3d4 = BaseAddr + 0x24; SiS_Pr->SiS_P3c0 = BaseAddr + 0x10; SiS_Pr->SiS_P3ce = BaseAddr + 0x1e; SiS_Pr->SiS_P3c2 = BaseAddr + 0x12; SiS_Pr->SiS_P3ca = BaseAddr + 0x1a; SiS_Pr->SiS_P3c6 = BaseAddr + 0x16; SiS_Pr->SiS_P3c7 = BaseAddr + 0x17; SiS_Pr->SiS_P3c8 = BaseAddr + 0x18; SiS_Pr->SiS_P3c9 = BaseAddr + 0x19; SiS_Pr->SiS_P3cb = BaseAddr + 0x1b; SiS_Pr->SiS_P3cc = BaseAddr + 0x1c; SiS_Pr->SiS_P3cd = BaseAddr + 0x1d; SiS_Pr->SiS_P3da = BaseAddr + 0x2a; SiS_Pr->SiS_Part1Port = BaseAddr + SIS_CRT2_PORT_04; SiS_Pr->SiS_Part2Port = BaseAddr + SIS_CRT2_PORT_10; SiS_Pr->SiS_Part3Port = BaseAddr + SIS_CRT2_PORT_12; SiS_Pr->SiS_Part4Port = BaseAddr + SIS_CRT2_PORT_14; SiS_Pr->SiS_Part5Port = BaseAddr + SIS_CRT2_PORT_14 + 2; SiS_Pr->SiS_DDC_Port = BaseAddr + 0x14; SiS_Pr->SiS_VidCapt = BaseAddr + SIS_VIDEO_CAPTURE; SiS_Pr->SiS_VidPlay = BaseAddr + SIS_VIDEO_PLAYBACK; } /*********************************************/ /* HELPER: GetSysFlags */ /*********************************************/ static void SiS_GetSysFlags(struct SiS_Private *SiS_Pr) { unsigned char cr5f, temp1, temp2; /* 661 and newer: NEVER write non-zero to SR11[7:4] */ /* (SR11 is used for DDC and in enable/disablebridge) */ SiS_Pr->SiS_SensibleSR11 = false; SiS_Pr->SiS_MyCR63 = 0x63; if(SiS_Pr->ChipType >= SIS_330) { SiS_Pr->SiS_MyCR63 = 0x53; if(SiS_Pr->ChipType >= SIS_661) { SiS_Pr->SiS_SensibleSR11 = true; } } /* You should use the macros, not these flags directly */ SiS_Pr->SiS_SysFlags = 0; if(SiS_Pr->ChipType == SIS_650) { cr5f = SiS_GetReg(SiS_Pr->SiS_P3d4,0x5f) & 0xf0; SiS_SetRegAND(SiS_Pr->SiS_P3d4,0x5c,0x07); temp1 = SiS_GetReg(SiS_Pr->SiS_P3d4,0x5c) & 0xf8; SiS_SetRegOR(SiS_Pr->SiS_P3d4,0x5c,0xf8); temp2 = SiS_GetReg(SiS_Pr->SiS_P3d4,0x5c) & 0xf8; if((!temp1) || (temp2)) { switch(cr5f) { case 0x80: case 0x90: case 0xc0: SiS_Pr->SiS_SysFlags |= SF_IsM650; break; case 0xa0: case 0xb0: case 0xe0: SiS_Pr->SiS_SysFlags |= SF_Is651; break; } } else { switch(cr5f) { case 0x90: temp1 = SiS_GetReg(SiS_Pr->SiS_P3d4,0x5c) & 0xf8; switch(temp1) { case 0x00: SiS_Pr->SiS_SysFlags |= SF_IsM652; break; case 0x40: SiS_Pr->SiS_SysFlags |= SF_IsM653; break; default: SiS_Pr->SiS_SysFlags |= SF_IsM650; break; } break; case 0xb0: SiS_Pr->SiS_SysFlags |= SF_Is652; break; default: SiS_Pr->SiS_SysFlags |= SF_IsM650; break; } } } if(SiS_Pr->ChipType >= SIS_760 && SiS_Pr->ChipType <= SIS_761) { if(SiS_GetReg(SiS_Pr->SiS_P3d4,0x78) & 0x30) { SiS_Pr->SiS_SysFlags |= SF_760LFB; } if(SiS_GetReg(SiS_Pr->SiS_P3d4,0x79) & 0xf0) { SiS_Pr->SiS_SysFlags |= SF_760UMA; } } } /*********************************************/ /* HELPER: Init PCI & Engines */ /*********************************************/ static void SiSInitPCIetc(struct SiS_Private *SiS_Pr) { switch(SiS_Pr->ChipType) { #ifdef CONFIG_FB_SIS_300 case SIS_300: case SIS_540: case SIS_630: case SIS_730: /* Set - PCI LINEAR ADDRESSING ENABLE (0x80) * - RELOCATED VGA IO ENABLED (0x20) * - MMIO ENABLED (0x01) * Leave other bits untouched. */ SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x20,0xa1); /* - Enable 2D (0x40) * - Enable 3D (0x02) * - Enable 3D Vertex command fetch (0x10) ? * - Enable 3D command parser (0x08) ? */ SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x1E,0x5A); break; #endif #ifdef CONFIG_FB_SIS_315 case SIS_315H: case SIS_315: case SIS_315PRO: case SIS_650: case SIS_740: case SIS_330: case SIS_661: case SIS_741: case SIS_660: case SIS_760: case SIS_761: case SIS_340: case XGI_40: /* See above */ SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x20,0xa1); /* - Enable 3D G/L transformation engine (0x80) * - Enable 2D (0x40) * - Enable 3D vertex command fetch (0x10) * - Enable 3D command parser (0x08) * - Enable 3D (0x02) */ SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x1E,0xDA); break; case XGI_20: case SIS_550: /* See above */ SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x20,0xa1); /* No 3D engine ! */ /* - Enable 2D (0x40) * - disable 3D */ SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x1E,0x60,0x40); break; #endif default: break; } } /*********************************************/ /* HELPER: SetLVDSetc */ /*********************************************/ static void SiSSetLVDSetc(struct SiS_Private *SiS_Pr) { unsigned short temp; SiS_Pr->SiS_IF_DEF_LVDS = 0; SiS_Pr->SiS_IF_DEF_TRUMPION = 0; SiS_Pr->SiS_IF_DEF_CH70xx = 0; SiS_Pr->SiS_IF_DEF_CONEX = 0; SiS_Pr->SiS_ChrontelInit = 0; if(SiS_Pr->ChipType == XGI_20) return; /* Check for SiS30x first */ temp = SiS_GetReg(SiS_Pr->SiS_Part4Port,0x00); if((temp == 1) || (temp == 2)) return; switch(SiS_Pr->ChipType) { #ifdef CONFIG_FB_SIS_300 case SIS_540: case SIS_630: case SIS_730: temp = (SiS_GetReg(SiS_Pr->SiS_P3d4,0x37) & 0x0e) >> 1; if((temp >= 2) && (temp <= 5)) SiS_Pr->SiS_IF_DEF_LVDS = 1; if(temp == 3) SiS_Pr->SiS_IF_DEF_TRUMPION = 1; if((temp == 4) || (temp == 5)) { /* Save power status (and error check) - UNUSED */ SiS_Pr->SiS_Backup70xx = SiS_GetCH700x(SiS_Pr, 0x0e); SiS_Pr->SiS_IF_DEF_CH70xx = 1; } break; #endif #ifdef CONFIG_FB_SIS_315 case SIS_550: case SIS_650: case SIS_740: case SIS_330: temp = (SiS_GetReg(SiS_Pr->SiS_P3d4,0x37) & 0x0e) >> 1; if((temp >= 2) && (temp <= 3)) SiS_Pr->SiS_IF_DEF_LVDS = 1; if(temp == 3) SiS_Pr->SiS_IF_DEF_CH70xx = 2; break; case SIS_661: case SIS_741: case SIS_660: case SIS_760: case SIS_761: case SIS_340: case XGI_20: case XGI_40: temp = (SiS_GetReg(SiS_Pr->SiS_P3d4,0x38) & 0xe0) >> 5; if((temp >= 2) && (temp <= 3)) SiS_Pr->SiS_IF_DEF_LVDS = 1; if(temp == 3) SiS_Pr->SiS_IF_DEF_CH70xx = 2; if(temp == 4) SiS_Pr->SiS_IF_DEF_CONEX = 1; /* Not yet supported */ break; #endif default: break; } } /*********************************************/ /* HELPER: Enable DSTN/FSTN */ /*********************************************/ void SiS_SetEnableDstn(struct SiS_Private *SiS_Pr, int enable) { SiS_Pr->SiS_IF_DEF_DSTN = enable ? 1 : 0; } void SiS_SetEnableFstn(struct SiS_Private *SiS_Pr, int enable) { SiS_Pr->SiS_IF_DEF_FSTN = enable ? 1 : 0; } /*********************************************/ /* HELPER: Get modeflag */ /*********************************************/ unsigned short SiS_GetModeFlag(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { if(SiS_Pr->UseCustomMode) { return SiS_Pr->CModeFlag; } else if(ModeNo <= 0x13) { return SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; } else { return SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; } } /*********************************************/ /* HELPER: Determine ROM usage */ /*********************************************/ bool SiSDetermineROMLayout661(struct SiS_Private *SiS_Pr) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short romversoffs, romvmaj = 1, romvmin = 0; if(SiS_Pr->ChipType >= XGI_20) { /* XGI ROMs don't qualify */ return false; } else if(SiS_Pr->ChipType >= SIS_761) { /* I very much assume 761, 340 and newer will use new layout */ return true; } else if(SiS_Pr->ChipType >= SIS_661) { if((ROMAddr[0x1a] == 'N') && (ROMAddr[0x1b] == 'e') && (ROMAddr[0x1c] == 'w') && (ROMAddr[0x1d] == 'V')) { return true; } romversoffs = ROMAddr[0x16] | (ROMAddr[0x17] << 8); if(romversoffs) { if((ROMAddr[romversoffs+1] == '.') || (ROMAddr[romversoffs+4] == '.')) { romvmaj = ROMAddr[romversoffs] - '0'; romvmin = ((ROMAddr[romversoffs+2] -'0') * 10) + (ROMAddr[romversoffs+3] - '0'); } } if((romvmaj != 0) || (romvmin >= 92)) { return true; } } else if(IS_SIS650740) { if((ROMAddr[0x1a] == 'N') && (ROMAddr[0x1b] == 'e') && (ROMAddr[0x1c] == 'w') && (ROMAddr[0x1d] == 'V')) { return true; } } return false; } static void SiSDetermineROMUsage(struct SiS_Private *SiS_Pr) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short romptr = 0; SiS_Pr->SiS_UseROM = false; SiS_Pr->SiS_ROMNew = false; SiS_Pr->SiS_PWDOffset = 0; if(SiS_Pr->ChipType >= XGI_20) return; if((ROMAddr) && (SiS_Pr->UseROM)) { if(SiS_Pr->ChipType == SIS_300) { /* 300: We check if the code starts below 0x220 by * checking the jmp instruction at the beginning * of the BIOS image. */ if((ROMAddr[3] == 0xe9) && ((ROMAddr[5] << 8) | ROMAddr[4]) > 0x21a) SiS_Pr->SiS_UseROM = true; } else if(SiS_Pr->ChipType < SIS_315H) { /* Sony's VAIO BIOS 1.09 follows the standard, so perhaps * the others do as well */ SiS_Pr->SiS_UseROM = true; } else { /* 315/330 series stick to the standard(s) */ SiS_Pr->SiS_UseROM = true; if((SiS_Pr->SiS_ROMNew = SiSDetermineROMLayout661(SiS_Pr))) { SiS_Pr->SiS_EMIOffset = 14; SiS_Pr->SiS_PWDOffset = 17; SiS_Pr->SiS661LCD2TableSize = 36; /* Find out about LCD data table entry size */ if((romptr = SISGETROMW(0x0102))) { if(ROMAddr[romptr + (32 * 16)] == 0xff) SiS_Pr->SiS661LCD2TableSize = 32; else if(ROMAddr[romptr + (34 * 16)] == 0xff) SiS_Pr->SiS661LCD2TableSize = 34; else if(ROMAddr[romptr + (36 * 16)] == 0xff) /* 0.94, 2.05.00+ */ SiS_Pr->SiS661LCD2TableSize = 36; else if( (ROMAddr[romptr + (38 * 16)] == 0xff) || /* 2.00.00 - 2.02.00 */ (ROMAddr[0x6F] & 0x01) ) { /* 2.03.00 - <2.05.00 */ SiS_Pr->SiS661LCD2TableSize = 38; /* UMC data layout abandoned at 2.05.00 */ SiS_Pr->SiS_EMIOffset = 16; SiS_Pr->SiS_PWDOffset = 19; } } } } } } /*********************************************/ /* HELPER: SET SEGMENT REGISTERS */ /*********************************************/ static void SiS_SetSegRegLower(struct SiS_Private *SiS_Pr, unsigned short value) { unsigned short temp; value &= 0x00ff; temp = SiS_GetRegByte(SiS_Pr->SiS_P3cb) & 0xf0; temp |= (value >> 4); SiS_SetRegByte(SiS_Pr->SiS_P3cb, temp); temp = SiS_GetRegByte(SiS_Pr->SiS_P3cd) & 0xf0; temp |= (value & 0x0f); SiS_SetRegByte(SiS_Pr->SiS_P3cd, temp); } static void SiS_SetSegRegUpper(struct SiS_Private *SiS_Pr, unsigned short value) { unsigned short temp; value &= 0x00ff; temp = SiS_GetRegByte(SiS_Pr->SiS_P3cb) & 0x0f; temp |= (value & 0xf0); SiS_SetRegByte(SiS_Pr->SiS_P3cb, temp); temp = SiS_GetRegByte(SiS_Pr->SiS_P3cd) & 0x0f; temp |= (value << 4); SiS_SetRegByte(SiS_Pr->SiS_P3cd, temp); } static void SiS_SetSegmentReg(struct SiS_Private *SiS_Pr, unsigned short value) { SiS_SetSegRegLower(SiS_Pr, value); SiS_SetSegRegUpper(SiS_Pr, value); } static void SiS_ResetSegmentReg(struct SiS_Private *SiS_Pr) { SiS_SetSegmentReg(SiS_Pr, 0); } static void SiS_SetSegmentRegOver(struct SiS_Private *SiS_Pr, unsigned short value) { unsigned short temp = value >> 8; temp &= 0x07; temp |= (temp << 4); SiS_SetReg(SiS_Pr->SiS_P3c4,0x1d,temp); SiS_SetSegmentReg(SiS_Pr, value); } static void SiS_ResetSegmentRegOver(struct SiS_Private *SiS_Pr) { SiS_SetSegmentRegOver(SiS_Pr, 0); } static void SiS_ResetSegmentRegisters(struct SiS_Private *SiS_Pr) { if((IS_SIS65x) || (SiS_Pr->ChipType >= SIS_661)) { SiS_ResetSegmentReg(SiS_Pr); SiS_ResetSegmentRegOver(SiS_Pr); } } /*********************************************/ /* HELPER: GetVBType */ /*********************************************/ static void SiS_GetVBType(struct SiS_Private *SiS_Pr) { unsigned short flag = 0, rev = 0, nolcd = 0; unsigned short p4_0f, p4_25, p4_27; SiS_Pr->SiS_VBType = 0; if((SiS_Pr->SiS_IF_DEF_LVDS) || (SiS_Pr->SiS_IF_DEF_CONEX)) return; if(SiS_Pr->ChipType == XGI_20) return; flag = SiS_GetReg(SiS_Pr->SiS_Part4Port,0x00); if(flag > 3) return; rev = SiS_GetReg(SiS_Pr->SiS_Part4Port,0x01); if(flag >= 2) { SiS_Pr->SiS_VBType = VB_SIS302B; } else if(flag == 1) { if(rev >= 0xC0) { SiS_Pr->SiS_VBType = VB_SIS301C; } else if(rev >= 0xB0) { SiS_Pr->SiS_VBType = VB_SIS301B; /* Check if 30xB DH version (no LCD support, use Panel Link instead) */ nolcd = SiS_GetReg(SiS_Pr->SiS_Part4Port,0x23); if(!(nolcd & 0x02)) SiS_Pr->SiS_VBType |= VB_NoLCD; } else { SiS_Pr->SiS_VBType = VB_SIS301; } } if(SiS_Pr->SiS_VBType & (VB_SIS301B | VB_SIS301C | VB_SIS302B)) { if(rev >= 0xE0) { flag = SiS_GetReg(SiS_Pr->SiS_Part4Port,0x39); if(flag == 0xff) SiS_Pr->SiS_VBType = VB_SIS302LV; else SiS_Pr->SiS_VBType = VB_SIS301C; /* VB_SIS302ELV; */ } else if(rev >= 0xD0) { SiS_Pr->SiS_VBType = VB_SIS301LV; } } if(SiS_Pr->SiS_VBType & (VB_SIS301C | VB_SIS301LV | VB_SIS302LV | VB_SIS302ELV)) { p4_0f = SiS_GetReg(SiS_Pr->SiS_Part4Port,0x0f); p4_25 = SiS_GetReg(SiS_Pr->SiS_Part4Port,0x25); p4_27 = SiS_GetReg(SiS_Pr->SiS_Part4Port,0x27); SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x0f,0x7f); SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x25,0x08); SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x27,0xfd); if(SiS_GetReg(SiS_Pr->SiS_Part4Port,0x26) & 0x08) { SiS_Pr->SiS_VBType |= VB_UMC; } SiS_SetReg(SiS_Pr->SiS_Part4Port,0x27,p4_27); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x25,p4_25); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x0f,p4_0f); } } /*********************************************/ /* HELPER: Check RAM size */ /*********************************************/ static bool SiS_CheckMemorySize(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned short AdapterMemSize = SiS_Pr->VideoMemorySize / (1024*1024); unsigned short modeflag = SiS_GetModeFlag(SiS_Pr, ModeNo, ModeIdIndex); unsigned short memorysize = ((modeflag & MemoryInfoFlag) >> MemorySizeShift) + 1; if(!AdapterMemSize) return true; if(AdapterMemSize < memorysize) return false; return true; } /*********************************************/ /* HELPER: Get DRAM type */ /*********************************************/ #ifdef CONFIG_FB_SIS_315 static unsigned char SiS_Get310DRAMType(struct SiS_Private *SiS_Pr) { unsigned char data; if((*SiS_Pr->pSiS_SoftSetting) & SoftDRAMType) { data = (*SiS_Pr->pSiS_SoftSetting) & 0x03; } else { if(SiS_Pr->ChipType >= XGI_20) { /* Do I need this? SR17 seems to be zero anyway... */ data = 0; } else if(SiS_Pr->ChipType >= SIS_340) { /* TODO */ data = 0; } if(SiS_Pr->ChipType >= SIS_661) { if(SiS_Pr->SiS_ROMNew) { data = ((SiS_GetReg(SiS_Pr->SiS_P3d4,0x78) & 0xc0) >> 6); } else { data = SiS_GetReg(SiS_Pr->SiS_P3d4,0x78) & 0x07; } } else if(IS_SIS550650740) { data = SiS_GetReg(SiS_Pr->SiS_P3c4,0x13) & 0x07; } else { /* 315, 330 */ data = SiS_GetReg(SiS_Pr->SiS_P3c4,0x3a) & 0x03; if(SiS_Pr->ChipType == SIS_330) { if(data > 1) { switch(SiS_GetReg(SiS_Pr->SiS_P3d4,0x5f) & 0x30) { case 0x00: data = 1; break; case 0x10: data = 3; break; case 0x20: data = 3; break; case 0x30: data = 2; break; } } else { data = 0; } } } } return data; } static unsigned short SiS_GetMCLK(struct SiS_Private *SiS_Pr) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short index; index = SiS_Get310DRAMType(SiS_Pr); if(SiS_Pr->ChipType >= SIS_661) { if(SiS_Pr->SiS_ROMNew) { return((unsigned short)(SISGETROMW((0x90 + (index * 5) + 3)))); } return(SiS_Pr->SiS_MCLKData_0[index].CLOCK); } else if(index >= 4) { return(SiS_Pr->SiS_MCLKData_1[index - 4].CLOCK); } else { return(SiS_Pr->SiS_MCLKData_0[index].CLOCK); } } #endif /*********************************************/ /* HELPER: ClearBuffer */ /*********************************************/ static void SiS_ClearBuffer(struct SiS_Private *SiS_Pr, unsigned short ModeNo) { unsigned char SISIOMEMTYPE *memaddr = SiS_Pr->VideoMemoryAddress; unsigned int memsize = SiS_Pr->VideoMemorySize; unsigned short SISIOMEMTYPE *pBuffer; int i; if(!memaddr || !memsize) return; if(SiS_Pr->SiS_ModeType >= ModeEGA) { if(ModeNo > 0x13) { memset_io(memaddr, 0, memsize); } else { pBuffer = (unsigned short SISIOMEMTYPE *)memaddr; for(i = 0; i < 0x4000; i++) writew(0x0000, &pBuffer[i]); } } else if(SiS_Pr->SiS_ModeType < ModeCGA) { pBuffer = (unsigned short SISIOMEMTYPE *)memaddr; for(i = 0; i < 0x4000; i++) writew(0x0720, &pBuffer[i]); } else { memset_io(memaddr, 0, 0x8000); } } /*********************************************/ /* HELPER: SearchModeID */ /*********************************************/ bool SiS_SearchModeID(struct SiS_Private *SiS_Pr, unsigned short *ModeNo, unsigned short *ModeIdIndex) { unsigned char VGAINFO = SiS_Pr->SiS_VGAINFO; if((*ModeNo) <= 0x13) { if((*ModeNo) <= 0x05) (*ModeNo) |= 0x01; for((*ModeIdIndex) = 0; ;(*ModeIdIndex)++) { if(SiS_Pr->SiS_SModeIDTable[(*ModeIdIndex)].St_ModeID == (*ModeNo)) break; if(SiS_Pr->SiS_SModeIDTable[(*ModeIdIndex)].St_ModeID == 0xFF) return false; } if((*ModeNo) == 0x07) { if(VGAINFO & 0x10) (*ModeIdIndex)++; /* 400 lines */ /* else 350 lines */ } if((*ModeNo) <= 0x03) { if(!(VGAINFO & 0x80)) (*ModeIdIndex)++; if(VGAINFO & 0x10) (*ModeIdIndex)++; /* 400 lines */ /* else 350 lines */ } /* else 200 lines */ } else { for((*ModeIdIndex) = 0; ;(*ModeIdIndex)++) { if(SiS_Pr->SiS_EModeIDTable[(*ModeIdIndex)].Ext_ModeID == (*ModeNo)) break; if(SiS_Pr->SiS_EModeIDTable[(*ModeIdIndex)].Ext_ModeID == 0xFF) return false; } } return true; } /*********************************************/ /* HELPER: GetModePtr */ /*********************************************/ unsigned short SiS_GetModePtr(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned short index; if(ModeNo <= 0x13) { index = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_StTableIndex; } else { if(SiS_Pr->SiS_ModeType <= ModeEGA) index = 0x1B; else index = 0x0F; } return index; } /*********************************************/ /* HELPERS: Get some indices */ /*********************************************/ unsigned short SiS_GetRefCRTVCLK(struct SiS_Private *SiS_Pr, unsigned short Index, int UseWide) { if(SiS_Pr->SiS_RefIndex[Index].Ext_InfoFlag & HaveWideTiming) { if(UseWide == 1) { return SiS_Pr->SiS_RefIndex[Index].Ext_CRTVCLK_WIDE; } else { return SiS_Pr->SiS_RefIndex[Index].Ext_CRTVCLK_NORM; } } else { return SiS_Pr->SiS_RefIndex[Index].Ext_CRTVCLK; } } unsigned short SiS_GetRefCRT1CRTC(struct SiS_Private *SiS_Pr, unsigned short Index, int UseWide) { if(SiS_Pr->SiS_RefIndex[Index].Ext_InfoFlag & HaveWideTiming) { if(UseWide == 1) { return SiS_Pr->SiS_RefIndex[Index].Ext_CRT1CRTC_WIDE; } else { return SiS_Pr->SiS_RefIndex[Index].Ext_CRT1CRTC_NORM; } } else { return SiS_Pr->SiS_RefIndex[Index].Ext_CRT1CRTC; } } /*********************************************/ /* HELPER: LowModeTests */ /*********************************************/ static bool SiS_DoLowModeTest(struct SiS_Private *SiS_Pr, unsigned short ModeNo) { unsigned short temp, temp1, temp2; if((ModeNo != 0x03) && (ModeNo != 0x10) && (ModeNo != 0x12)) return true; temp = SiS_GetReg(SiS_Pr->SiS_P3d4,0x11); SiS_SetRegOR(SiS_Pr->SiS_P3d4,0x11,0x80); temp1 = SiS_GetReg(SiS_Pr->SiS_P3d4,0x00); SiS_SetReg(SiS_Pr->SiS_P3d4,0x00,0x55); temp2 = SiS_GetReg(SiS_Pr->SiS_P3d4,0x00); SiS_SetReg(SiS_Pr->SiS_P3d4,0x00,temp1); SiS_SetReg(SiS_Pr->SiS_P3d4,0x11,temp); if((SiS_Pr->ChipType >= SIS_315H) || (SiS_Pr->ChipType == SIS_300)) { if(temp2 == 0x55) return false; else return true; } else { if(temp2 != 0x55) return true; else { SiS_SetRegOR(SiS_Pr->SiS_P3d4,0x35,0x01); return false; } } } static void SiS_SetLowModeTest(struct SiS_Private *SiS_Pr, unsigned short ModeNo) { if(SiS_DoLowModeTest(SiS_Pr, ModeNo)) { SiS_Pr->SiS_SetFlag |= LowModeTests; } } /*********************************************/ /* HELPER: OPEN/CLOSE CRT1 CRTC */ /*********************************************/ static void SiS_OpenCRTC(struct SiS_Private *SiS_Pr) { if(IS_SIS650) { SiS_SetRegAND(SiS_Pr->SiS_P3d4,0x51,0x1f); if(IS_SIS651) SiS_SetRegOR(SiS_Pr->SiS_P3d4,0x51,0x20); SiS_SetRegAND(SiS_Pr->SiS_P3d4,0x56,0xe7); } else if(IS_SIS661741660760) { SiS_SetRegAND(SiS_Pr->SiS_P3d4,0x61,0xf7); SiS_SetRegAND(SiS_Pr->SiS_P3d4,0x51,0x1f); SiS_SetRegAND(SiS_Pr->SiS_P3d4,0x56,0xe7); if(!SiS_Pr->SiS_ROMNew) { SiS_SetRegAND(SiS_Pr->SiS_P3d4,0x3a,0xef); } } } static void SiS_CloseCRTC(struct SiS_Private *SiS_Pr) { #if 0 /* This locks some CRTC registers. We don't want that. */ unsigned short temp1 = 0, temp2 = 0; if(IS_SIS661741660760) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { temp1 = 0xa0; temp2 = 0x08; } SiS_SetRegANDOR(SiS_Pr->SiS_P3d4,0x51,0x1f,temp1); SiS_SetRegANDOR(SiS_Pr->SiS_P3d4,0x56,0xe7,temp2); } #endif } static void SiS_HandleCRT1(struct SiS_Private *SiS_Pr) { /* Enable CRT1 gating */ SiS_SetRegAND(SiS_Pr->SiS_P3d4,SiS_Pr->SiS_MyCR63,0xbf); #if 0 if(!(SiS_GetReg(SiS_Pr->SiS_P3c4,0x15) & 0x01)) { if((SiS_GetReg(SiS_Pr->SiS_P3c4,0x15) & 0x0a) || (SiS_GetReg(SiS_Pr->SiS_P3c4,0x16) & 0x01)) { SiS_SetRegOR(SiS_Pr->SiS_P3d4,SiS_Pr->SiS_MyCR63,0x40); } } #endif } /*********************************************/ /* HELPER: GetColorDepth */ /*********************************************/ unsigned short SiS_GetColorDepth(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { static const unsigned short ColorDepth[6] = { 1, 2, 4, 4, 6, 8 }; unsigned short modeflag; short index; /* Do NOT check UseCustomMode, will skrew up FIFO */ if(ModeNo == 0xfe) { modeflag = SiS_Pr->CModeFlag; } else if(ModeNo <= 0x13) { modeflag = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; } else { modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; } index = (modeflag & ModeTypeMask) - ModeEGA; if(index < 0) index = 0; return ColorDepth[index]; } /*********************************************/ /* HELPER: GetOffset */ /*********************************************/ unsigned short SiS_GetOffset(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RRTI) { unsigned short xres, temp, colordepth, infoflag; if(SiS_Pr->UseCustomMode) { infoflag = SiS_Pr->CInfoFlag; xres = SiS_Pr->CHDisplay; } else { infoflag = SiS_Pr->SiS_RefIndex[RRTI].Ext_InfoFlag; xres = SiS_Pr->SiS_RefIndex[RRTI].XRes; } colordepth = SiS_GetColorDepth(SiS_Pr, ModeNo, ModeIdIndex); temp = xres / 16; if(infoflag & InterlaceMode) temp <<= 1; temp *= colordepth; if(xres % 16) temp += (colordepth >> 1); return temp; } /*********************************************/ /* SEQ */ /*********************************************/ static void SiS_SetSeqRegs(struct SiS_Private *SiS_Pr, unsigned short StandTableIndex) { unsigned char SRdata; int i; SiS_SetReg(SiS_Pr->SiS_P3c4,0x00,0x03); /* or "display off" */ SRdata = SiS_Pr->SiS_StandTable[StandTableIndex].SR[0] | 0x20; /* determine whether to force x8 dotclock */ if((SiS_Pr->SiS_VBType & VB_SISVB) || (SiS_Pr->SiS_IF_DEF_LVDS)) { if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToTV)) { if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) SRdata |= 0x01; } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) SRdata |= 0x01; } SiS_SetReg(SiS_Pr->SiS_P3c4,0x01,SRdata); for(i = 2; i <= 4; i++) { SRdata = SiS_Pr->SiS_StandTable[StandTableIndex].SR[i - 1]; SiS_SetReg(SiS_Pr->SiS_P3c4,i,SRdata); } } /*********************************************/ /* MISC */ /*********************************************/ static void SiS_SetMiscRegs(struct SiS_Private *SiS_Pr, unsigned short StandTableIndex) { unsigned char Miscdata; Miscdata = SiS_Pr->SiS_StandTable[StandTableIndex].MISC; if(SiS_Pr->ChipType < SIS_661) { if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { Miscdata |= 0x0C; } } } SiS_SetRegByte(SiS_Pr->SiS_P3c2,Miscdata); } /*********************************************/ /* CRTC */ /*********************************************/ static void SiS_SetCRTCRegs(struct SiS_Private *SiS_Pr, unsigned short StandTableIndex) { unsigned char CRTCdata; unsigned short i; /* Unlock CRTC */ SiS_SetRegAND(SiS_Pr->SiS_P3d4,0x11,0x7f); for(i = 0; i <= 0x18; i++) { CRTCdata = SiS_Pr->SiS_StandTable[StandTableIndex].CRTC[i]; SiS_SetReg(SiS_Pr->SiS_P3d4,i,CRTCdata); } if(SiS_Pr->ChipType >= SIS_661) { SiS_OpenCRTC(SiS_Pr); for(i = 0x13; i <= 0x14; i++) { CRTCdata = SiS_Pr->SiS_StandTable[StandTableIndex].CRTC[i]; SiS_SetReg(SiS_Pr->SiS_P3d4,i,CRTCdata); } } else if( ( (SiS_Pr->ChipType == SIS_630) || (SiS_Pr->ChipType == SIS_730) ) && (SiS_Pr->ChipRevision >= 0x30) ) { if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) { if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToTV)) { SiS_SetReg(SiS_Pr->SiS_P3d4,0x18,0xFE); } } } } /*********************************************/ /* ATT */ /*********************************************/ static void SiS_SetATTRegs(struct SiS_Private *SiS_Pr, unsigned short StandTableIndex) { unsigned char ARdata; unsigned short i; for(i = 0; i <= 0x13; i++) { ARdata = SiS_Pr->SiS_StandTable[StandTableIndex].ATTR[i]; if(i == 0x13) { /* Pixel shift. If screen on LCD or TV is shifted left or right, * this might be the cause. */ if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) ARdata = 0; } if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { if(SiS_Pr->SiS_IF_DEF_CH70xx != 0) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) ARdata = 0; } } } if(SiS_Pr->ChipType >= SIS_661) { if(SiS_Pr->SiS_VBInfo & (SetCRT2ToTV | SetCRT2ToLCD)) { if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) ARdata = 0; } } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { if(SiS_Pr->ChipType >= SIS_315H) { if(IS_SIS550650740660) { /* 315, 330 don't do this */ if(SiS_Pr->SiS_VBType & VB_SIS30xB) { if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) ARdata = 0; } else { ARdata = 0; } } } else { if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) ARdata = 0; } } } SiS_GetRegByte(SiS_Pr->SiS_P3da); /* reset 3da */ SiS_SetRegByte(SiS_Pr->SiS_P3c0,i); /* set index */ SiS_SetRegByte(SiS_Pr->SiS_P3c0,ARdata); /* set data */ } SiS_GetRegByte(SiS_Pr->SiS_P3da); /* reset 3da */ SiS_SetRegByte(SiS_Pr->SiS_P3c0,0x14); /* set index */ SiS_SetRegByte(SiS_Pr->SiS_P3c0,0x00); /* set data */ SiS_GetRegByte(SiS_Pr->SiS_P3da); SiS_SetRegByte(SiS_Pr->SiS_P3c0,0x20); /* Enable Attribute */ SiS_GetRegByte(SiS_Pr->SiS_P3da); } /*********************************************/ /* GRC */ /*********************************************/ static void SiS_SetGRCRegs(struct SiS_Private *SiS_Pr, unsigned short StandTableIndex) { unsigned char GRdata; unsigned short i; for(i = 0; i <= 0x08; i++) { GRdata = SiS_Pr->SiS_StandTable[StandTableIndex].GRC[i]; SiS_SetReg(SiS_Pr->SiS_P3ce,i,GRdata); } if(SiS_Pr->SiS_ModeType > ModeVGA) { /* 256 color disable */ SiS_SetRegAND(SiS_Pr->SiS_P3ce,0x05,0xBF); } } /*********************************************/ /* CLEAR EXTENDED REGISTERS */ /*********************************************/ static void SiS_ClearExt1Regs(struct SiS_Private *SiS_Pr, unsigned short ModeNo) { unsigned short i; for(i = 0x0A; i <= 0x0E; i++) { SiS_SetReg(SiS_Pr->SiS_P3c4,i,0x00); } if(SiS_Pr->ChipType >= SIS_315H) { SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x37,0xFE); if(ModeNo <= 0x13) { if(ModeNo == 0x06 || ModeNo >= 0x0e) { SiS_SetReg(SiS_Pr->SiS_P3c4,0x0e,0x20); } } } } /*********************************************/ /* RESET VCLK */ /*********************************************/ static void SiS_ResetCRT1VCLK(struct SiS_Private *SiS_Pr) { if(SiS_Pr->ChipType >= SIS_315H) { if(SiS_Pr->ChipType < SIS_661) { if(SiS_Pr->SiS_IF_DEF_LVDS == 0) return; } } else { if((SiS_Pr->SiS_IF_DEF_LVDS == 0) && (!(SiS_Pr->SiS_VBType & VB_SIS30xBLV)) ) { return; } } SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x31,0xcf,0x20); SiS_SetReg(SiS_Pr->SiS_P3c4,0x2B,SiS_Pr->SiS_VCLKData[1].SR2B); SiS_SetReg(SiS_Pr->SiS_P3c4,0x2C,SiS_Pr->SiS_VCLKData[1].SR2C); SiS_SetReg(SiS_Pr->SiS_P3c4,0x2D,0x80); SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x31,0xcf,0x10); SiS_SetReg(SiS_Pr->SiS_P3c4,0x2B,SiS_Pr->SiS_VCLKData[0].SR2B); SiS_SetReg(SiS_Pr->SiS_P3c4,0x2C,SiS_Pr->SiS_VCLKData[0].SR2C); SiS_SetReg(SiS_Pr->SiS_P3c4,0x2D,0x80); } /*********************************************/ /* SYNC */ /*********************************************/ static void SiS_SetCRT1Sync(struct SiS_Private *SiS_Pr, unsigned short RRTI) { unsigned short sync; if(SiS_Pr->UseCustomMode) { sync = SiS_Pr->CInfoFlag >> 8; } else { sync = SiS_Pr->SiS_RefIndex[RRTI].Ext_InfoFlag >> 8; } sync &= 0xC0; sync |= 0x2f; SiS_SetRegByte(SiS_Pr->SiS_P3c2,sync); } /*********************************************/ /* CRTC/2 */ /*********************************************/ static void SiS_SetCRT1CRTC(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RRTI) { unsigned short temp, i, j, modeflag; unsigned char *crt1data = NULL; modeflag = SiS_GetModeFlag(SiS_Pr, ModeNo, ModeIdIndex); if(SiS_Pr->UseCustomMode) { crt1data = &SiS_Pr->CCRT1CRTC[0]; } else { temp = SiS_GetRefCRT1CRTC(SiS_Pr, RRTI, SiS_Pr->SiS_UseWide); /* Alternate for 1600x1200 LCDA */ if((temp == 0x20) && (SiS_Pr->Alternate1600x1200)) temp = 0x57; crt1data = (unsigned char *)&SiS_Pr->SiS_CRT1Table[temp].CR[0]; } /* unlock cr0-7 */ SiS_SetRegAND(SiS_Pr->SiS_P3d4,0x11,0x7f); for(i = 0, j = 0; i <= 7; i++, j++) { SiS_SetReg(SiS_Pr->SiS_P3d4,j,crt1data[i]); } for(j = 0x10; i <= 10; i++, j++) { SiS_SetReg(SiS_Pr->SiS_P3d4,j,crt1data[i]); } for(j = 0x15; i <= 12; i++, j++) { SiS_SetReg(SiS_Pr->SiS_P3d4,j,crt1data[i]); } for(j = 0x0A; i <= 15; i++, j++) { SiS_SetReg(SiS_Pr->SiS_P3c4,j,crt1data[i]); } SiS_SetReg(SiS_Pr->SiS_P3c4,0x0E,crt1data[16] & 0xE0); temp = (crt1data[16] & 0x01) << 5; if(modeflag & DoubleScanMode) temp |= 0x80; SiS_SetRegANDOR(SiS_Pr->SiS_P3d4,0x09,0x5F,temp); if(SiS_Pr->SiS_ModeType > ModeVGA) { SiS_SetReg(SiS_Pr->SiS_P3d4,0x14,0x4F); } #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->ChipType == XGI_20) { SiS_SetReg(SiS_Pr->SiS_P3d4,0x04,crt1data[4] - 1); if(!(temp = crt1data[5] & 0x1f)) { SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x0c,0xfb); } SiS_SetRegANDOR(SiS_Pr->SiS_P3d4,0x05,0xe0,((temp - 1) & 0x1f)); temp = (crt1data[16] >> 5) + 3; if(temp > 7) temp -= 7; SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x0e,0x1f,(temp << 5)); } #endif } /*********************************************/ /* OFFSET & PITCH */ /*********************************************/ /* (partly overruled by SetPitch() in XF86) */ /*********************************************/ static void SiS_SetCRT1Offset(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RRTI) { unsigned short temp, DisplayUnit, infoflag; if(SiS_Pr->UseCustomMode) { infoflag = SiS_Pr->CInfoFlag; } else { infoflag = SiS_Pr->SiS_RefIndex[RRTI].Ext_InfoFlag; } DisplayUnit = SiS_GetOffset(SiS_Pr, ModeNo, ModeIdIndex, RRTI); temp = (DisplayUnit >> 8) & 0x0f; SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x0E,0xF0,temp); SiS_SetReg(SiS_Pr->SiS_P3d4,0x13,DisplayUnit & 0xFF); if(infoflag & InterlaceMode) DisplayUnit >>= 1; DisplayUnit <<= 5; temp = (DisplayUnit >> 8) + 1; if(DisplayUnit & 0xff) temp++; if(SiS_Pr->ChipType == XGI_20) { if(ModeNo == 0x4a || ModeNo == 0x49) temp--; } SiS_SetReg(SiS_Pr->SiS_P3c4,0x10,temp); } /*********************************************/ /* VCLK */ /*********************************************/ static void SiS_SetCRT1VCLK(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RRTI) { unsigned short index = 0, clka, clkb; if(SiS_Pr->UseCustomMode) { clka = SiS_Pr->CSR2B; clkb = SiS_Pr->CSR2C; } else { index = SiS_GetVCLK2Ptr(SiS_Pr, ModeNo, ModeIdIndex, RRTI); if((SiS_Pr->SiS_VBType & VB_SIS30xBLV) && (SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA)) { /* Alternate for 1600x1200 LCDA */ if((index == 0x21) && (SiS_Pr->Alternate1600x1200)) index = 0x72; clka = SiS_Pr->SiS_VBVCLKData[index].Part4_A; clkb = SiS_Pr->SiS_VBVCLKData[index].Part4_B; } else { clka = SiS_Pr->SiS_VCLKData[index].SR2B; clkb = SiS_Pr->SiS_VCLKData[index].SR2C; } } SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x31,0xCF); SiS_SetReg(SiS_Pr->SiS_P3c4,0x2b,clka); SiS_SetReg(SiS_Pr->SiS_P3c4,0x2c,clkb); if(SiS_Pr->ChipType >= SIS_315H) { #ifdef CONFIG_FB_SIS_315 SiS_SetReg(SiS_Pr->SiS_P3c4,0x2D,0x01); if(SiS_Pr->ChipType == XGI_20) { unsigned short mf = SiS_GetModeFlag(SiS_Pr, ModeNo, ModeIdIndex); if(mf & HalfDCLK) { SiS_SetReg(SiS_Pr->SiS_P3c4,0x2b,SiS_GetReg(SiS_Pr->SiS_P3c4,0x2b)); clkb = SiS_GetReg(SiS_Pr->SiS_P3c4,0x2c); clkb = (((clkb & 0x1f) << 1) + 1) | (clkb & 0xe0); SiS_SetReg(SiS_Pr->SiS_P3c4,0x2c,clkb); } } #endif } else { SiS_SetReg(SiS_Pr->SiS_P3c4,0x2D,0x80); } } /*********************************************/ /* FIFO */ /*********************************************/ #ifdef CONFIG_FB_SIS_300 void SiS_GetFIFOThresholdIndex300(struct SiS_Private *SiS_Pr, unsigned short *idx1, unsigned short *idx2) { unsigned short temp1, temp2; static const unsigned char ThTiming[8] = { 1, 2, 2, 3, 0, 1, 1, 2 }; temp1 = temp2 = (SiS_GetReg(SiS_Pr->SiS_P3c4,0x18) & 0x62) >> 1; (*idx2) = (unsigned short)(ThTiming[((temp2 >> 3) | temp1) & 0x07]); (*idx1) = (unsigned short)(SiS_GetReg(SiS_Pr->SiS_P3c4,0x16) >> 6) & 0x03; (*idx1) |= (unsigned short)(((SiS_GetReg(SiS_Pr->SiS_P3c4,0x14) >> 4) & 0x0c)); (*idx1) <<= 1; } static unsigned short SiS_GetFIFOThresholdA300(unsigned short idx1, unsigned short idx2) { static const unsigned char ThLowA[8 * 3] = { 61, 3,52, 5,68, 7,100,11, 43, 3,42, 5,54, 7, 78,11, 34, 3,37, 5,47, 7, 67,11 }; return (unsigned short)((ThLowA[idx1 + 1] * idx2) + ThLowA[idx1]); } unsigned short SiS_GetFIFOThresholdB300(unsigned short idx1, unsigned short idx2) { static const unsigned char ThLowB[8 * 3] = { 81, 4,72, 6,88, 8,120,12, 55, 4,54, 6,66, 8, 90,12, 42, 4,45, 6,55, 8, 75,12 }; return (unsigned short)((ThLowB[idx1 + 1] * idx2) + ThLowB[idx1]); } static unsigned short SiS_DoCalcDelay(struct SiS_Private *SiS_Pr, unsigned short MCLK, unsigned short VCLK, unsigned short colordepth, unsigned short key) { unsigned short idx1, idx2; unsigned int longtemp = VCLK * colordepth; SiS_GetFIFOThresholdIndex300(SiS_Pr, &idx1, &idx2); if(key == 0) { longtemp *= SiS_GetFIFOThresholdA300(idx1, idx2); } else { longtemp *= SiS_GetFIFOThresholdB300(idx1, idx2); } idx1 = longtemp % (MCLK * 16); longtemp /= (MCLK * 16); if(idx1) longtemp++; return (unsigned short)longtemp; } static unsigned short SiS_CalcDelay(struct SiS_Private *SiS_Pr, unsigned short VCLK, unsigned short colordepth, unsigned short MCLK) { unsigned short temp1, temp2; temp2 = SiS_DoCalcDelay(SiS_Pr, MCLK, VCLK, colordepth, 0); temp1 = SiS_DoCalcDelay(SiS_Pr, MCLK, VCLK, colordepth, 1); if(temp1 < 4) temp1 = 4; temp1 -= 4; if(temp2 < temp1) temp2 = temp1; return temp2; } static void SiS_SetCRT1FIFO_300(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short RefreshRateTableIndex) { unsigned short ThresholdLow = 0; unsigned short temp, index, VCLK, MCLK, colorth; static const unsigned short colortharray[6] = { 1, 1, 2, 2, 3, 4 }; if(ModeNo > 0x13) { /* Get VCLK */ if(SiS_Pr->UseCustomMode) { VCLK = SiS_Pr->CSRClock; } else { index = SiS_GetRefCRTVCLK(SiS_Pr, RefreshRateTableIndex, SiS_Pr->SiS_UseWide); VCLK = SiS_Pr->SiS_VCLKData[index].CLOCK; } /* Get half colordepth */ colorth = colortharray[(SiS_Pr->SiS_ModeType - ModeEGA)]; /* Get MCLK */ index = SiS_GetReg(SiS_Pr->SiS_P3c4,0x3A) & 0x07; MCLK = SiS_Pr->SiS_MCLKData_0[index].CLOCK; temp = SiS_GetReg(SiS_Pr->SiS_P3d4,0x35) & 0xc3; SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x16,0x3c,temp); do { ThresholdLow = SiS_CalcDelay(SiS_Pr, VCLK, colorth, MCLK) + 1; if(ThresholdLow < 0x13) break; SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x16,0xfc); ThresholdLow = 0x13; temp = SiS_GetReg(SiS_Pr->SiS_P3c4,0x16) >> 6; if(!temp) break; SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x16,0x3f,((temp - 1) << 6)); } while(0); } else ThresholdLow = 2; /* Write CRT/CPU threshold low, CRT/Engine threshold high */ temp = (ThresholdLow << 4) | 0x0f; SiS_SetReg(SiS_Pr->SiS_P3c4,0x08,temp); temp = (ThresholdLow & 0x10) << 1; if(ModeNo > 0x13) temp |= 0x40; SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x0f,0x9f,temp); /* What is this? */ SiS_SetReg(SiS_Pr->SiS_P3c4,0x3B,0x09); /* Write CRT/CPU threshold high */ temp = ThresholdLow + 3; if(temp > 0x0f) temp = 0x0f; SiS_SetReg(SiS_Pr->SiS_P3c4,0x09,temp); } unsigned short SiS_GetLatencyFactor630(struct SiS_Private *SiS_Pr, unsigned short index) { static const unsigned char LatencyFactor[] = { 97, 88, 86, 79, 77, 0, /* 64 bit BQ=2 */ 0, 87, 85, 78, 76, 54, /* 64 bit BQ=1 */ 97, 88, 86, 79, 77, 0, /* 128 bit BQ=2 */ 0, 79, 77, 70, 68, 48, /* 128 bit BQ=1 */ 80, 72, 69, 63, 61, 0, /* 64 bit BQ=2 */ 0, 70, 68, 61, 59, 37, /* 64 bit BQ=1 */ 86, 77, 75, 68, 66, 0, /* 128 bit BQ=2 */ 0, 68, 66, 59, 57, 37 /* 128 bit BQ=1 */ }; static const unsigned char LatencyFactor730[] = { 69, 63, 61, 86, 79, 77, 103, 96, 94, 120,113,111, 137,130,128 }; if(SiS_Pr->ChipType == SIS_730) { return (unsigned short)LatencyFactor730[index]; } else { return (unsigned short)LatencyFactor[index]; } } static unsigned short SiS_CalcDelay2(struct SiS_Private *SiS_Pr, unsigned char key) { unsigned short index; if(SiS_Pr->ChipType == SIS_730) { index = ((key & 0x0f) * 3) + ((key & 0xc0) >> 6); } else { index = (key & 0xe0) >> 5; if(key & 0x10) index += 6; if(!(key & 0x01)) index += 24; if(SiS_GetReg(SiS_Pr->SiS_P3c4,0x14) & 0x80) index += 12; } return SiS_GetLatencyFactor630(SiS_Pr, index); } static void SiS_SetCRT1FIFO_630(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short RefreshRateTableIndex) { unsigned short ThresholdLow = 0; unsigned short i, data, VCLK, MCLK16, colorth = 0; unsigned int templ, datal; const unsigned char *queuedata = NULL; static const unsigned char FQBQData[21] = { 0x01,0x21,0x41,0x61,0x81, 0x31,0x51,0x71,0x91,0xb1, 0x00,0x20,0x40,0x60,0x80, 0x30,0x50,0x70,0x90,0xb0, 0xff }; static const unsigned char FQBQData730[16] = { 0x34,0x74,0xb4, 0x23,0x63,0xa3, 0x12,0x52,0x92, 0x01,0x41,0x81, 0x00,0x40,0x80, 0xff }; static const unsigned short colortharray[6] = { 1, 1, 2, 2, 3, 4 }; i = 0; if(ModeNo > 0x13) { /* Get VCLK */ if(SiS_Pr->UseCustomMode) { VCLK = SiS_Pr->CSRClock; } else { data = SiS_GetRefCRTVCLK(SiS_Pr, RefreshRateTableIndex, SiS_Pr->SiS_UseWide); VCLK = SiS_Pr->SiS_VCLKData[data].CLOCK; } /* Get MCLK * 16 */ data = SiS_GetReg(SiS_Pr->SiS_P3c4,0x1A) & 0x07; MCLK16 = SiS_Pr->SiS_MCLKData_0[data].CLOCK * 16; /* Get half colordepth */ colorth = colortharray[(SiS_Pr->SiS_ModeType - ModeEGA)]; if(SiS_Pr->ChipType == SIS_730) { queuedata = &FQBQData730[0]; } else { queuedata = &FQBQData[0]; } do { templ = SiS_CalcDelay2(SiS_Pr, queuedata[i]) * VCLK * colorth; datal = templ % MCLK16; templ = (templ / MCLK16) + 1; if(datal) templ++; if(templ > 0x13) { if(queuedata[i + 1] == 0xFF) { ThresholdLow = 0x13; break; } i++; } else { ThresholdLow = templ; break; } } while(queuedata[i] != 0xFF); } else { if(SiS_Pr->ChipType != SIS_730) i = 9; ThresholdLow = 0x02; } /* Write CRT/CPU threshold low, CRT/Engine threshold high */ data = ((ThresholdLow & 0x0f) << 4) | 0x0f; SiS_SetReg(SiS_Pr->SiS_P3c4,0x08,data); data = (ThresholdLow & 0x10) << 1; SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x0F,0xDF,data); /* What is this? */ SiS_SetReg(SiS_Pr->SiS_P3c4,0x3B,0x09); /* Write CRT/CPU threshold high (gap = 3) */ data = ThresholdLow + 3; if(data > 0x0f) data = 0x0f; SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x09,0x80,data); /* Write foreground and background queue */ templ = sisfb_read_nbridge_pci_dword(SiS_Pr, 0x50); if(SiS_Pr->ChipType == SIS_730) { templ &= 0xfffff9ff; templ |= ((queuedata[i] & 0xc0) << 3); } else { templ &= 0xf0ffffff; if( (ModeNo <= 0x13) && (SiS_Pr->ChipType == SIS_630) && (SiS_Pr->ChipRevision >= 0x30) ) { templ |= 0x0b000000; } else { templ |= ((queuedata[i] & 0xf0) << 20); } } sisfb_write_nbridge_pci_dword(SiS_Pr, 0x50, templ); templ = sisfb_read_nbridge_pci_dword(SiS_Pr, 0xA0); /* GUI grant timer (PCI config 0xA3) */ if(SiS_Pr->ChipType == SIS_730) { templ &= 0x00ffffff; datal = queuedata[i] << 8; templ |= (((datal & 0x0f00) | ((datal & 0x3000) >> 8)) << 20); } else { templ &= 0xf0ffffff; templ |= ((queuedata[i] & 0x0f) << 24); } sisfb_write_nbridge_pci_dword(SiS_Pr, 0xA0, templ); } #endif /* CONFIG_FB_SIS_300 */ #ifdef CONFIG_FB_SIS_315 static void SiS_SetCRT1FIFO_310(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned short modeflag; /* disable auto-threshold */ SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x3D,0xFE); modeflag = SiS_GetModeFlag(SiS_Pr, ModeNo, ModeIdIndex); SiS_SetReg(SiS_Pr->SiS_P3c4,0x08,0xAE); SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x09,0xF0); if(ModeNo > 0x13) { if(SiS_Pr->ChipType >= XGI_20) { SiS_SetReg(SiS_Pr->SiS_P3c4,0x08,0x34); SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x3D,0x01); } else if(SiS_Pr->ChipType >= SIS_661) { if(!(modeflag & HalfDCLK)) { SiS_SetReg(SiS_Pr->SiS_P3c4,0x08,0x34); SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x3D,0x01); } } else { if((!(modeflag & DoubleScanMode)) || (!(modeflag & HalfDCLK))) { SiS_SetReg(SiS_Pr->SiS_P3c4,0x08,0x34); SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x3D,0x01); } } } } #endif /*********************************************/ /* MODE REGISTERS */ /*********************************************/ static void SiS_SetVCLKState(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short RefreshRateTableIndex, unsigned short ModeIdIndex) { unsigned short data = 0, VCLK = 0, index = 0; if(ModeNo > 0x13) { if(SiS_Pr->UseCustomMode) { VCLK = SiS_Pr->CSRClock; } else { index = SiS_GetVCLK2Ptr(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); VCLK = SiS_Pr->SiS_VCLKData[index].CLOCK; } } if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 if(VCLK > 150) data |= 0x80; SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x07,0x7B,data); data = 0x00; if(VCLK >= 150) data |= 0x08; SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x32,0xF7,data); #endif } else if(SiS_Pr->ChipType < XGI_20) { #ifdef CONFIG_FB_SIS_315 if(VCLK >= 166) data |= 0x0c; SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x32,0xf3,data); if(VCLK >= 166) { SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x1f,0xe7); } #endif } else { #ifdef CONFIG_FB_SIS_315 if(VCLK >= 200) data |= 0x0c; if(SiS_Pr->ChipType == XGI_20) data &= ~0x04; SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x32,0xf3,data); if(SiS_Pr->ChipType != XGI_20) { data = SiS_GetReg(SiS_Pr->SiS_P3c4,0x1f) & 0xe7; if(VCLK < 200) data |= 0x10; SiS_SetReg(SiS_Pr->SiS_P3c4,0x1f,data); } #endif } /* DAC speed */ if(SiS_Pr->ChipType >= SIS_661) { SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x07,0xE8,0x10); } else { data = 0x03; if(VCLK >= 260) data = 0x00; else if(VCLK >= 160) data = 0x01; else if(VCLK >= 135) data = 0x02; if(SiS_Pr->ChipType == SIS_540) { if((VCLK == 203) || (VCLK < 234)) data = 0x02; } if(SiS_Pr->ChipType < SIS_315H) { SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x07,0xFC,data); } else { if(SiS_Pr->ChipType > SIS_315PRO) { if(ModeNo > 0x13) data &= 0xfc; } SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x07,0xF8,data); } } } static void SiS_SetCRT1ModeRegs(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RRTI) { unsigned short data, infoflag = 0, modeflag, resindex; #ifdef CONFIG_FB_SIS_315 unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short data2, data3; #endif modeflag = SiS_GetModeFlag(SiS_Pr, ModeNo, ModeIdIndex); if(SiS_Pr->UseCustomMode) { infoflag = SiS_Pr->CInfoFlag; } else { resindex = SiS_GetResInfo(SiS_Pr, ModeNo, ModeIdIndex); if(ModeNo > 0x13) { infoflag = SiS_Pr->SiS_RefIndex[RRTI].Ext_InfoFlag; } } /* Disable DPMS */ SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x1F,0x3F); data = 0; if(ModeNo > 0x13) { if(SiS_Pr->SiS_ModeType > ModeEGA) { data |= 0x02; data |= ((SiS_Pr->SiS_ModeType - ModeVGA) << 2); } if(infoflag & InterlaceMode) data |= 0x20; } SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x06,0xC0,data); if(SiS_Pr->ChipType != SIS_300) { data = 0; if(infoflag & InterlaceMode) { /* data = (Hsync / 8) - ((Htotal / 8) / 2) + 3 */ int hrs = (SiS_GetReg(SiS_Pr->SiS_P3d4,0x04) | ((SiS_GetReg(SiS_Pr->SiS_P3c4,0x0b) & 0xc0) << 2)) - 3; int hto = (SiS_GetReg(SiS_Pr->SiS_P3d4,0x00) | ((SiS_GetReg(SiS_Pr->SiS_P3c4,0x0b) & 0x03) << 8)) + 5; data = hrs - (hto >> 1) + 3; } SiS_SetReg(SiS_Pr->SiS_P3d4,0x19,data); SiS_SetRegANDOR(SiS_Pr->SiS_P3d4,0x1a,0xFC,((data >> 8) & 0x03)); } if(modeflag & HalfDCLK) { SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x01,0x08); } data = 0; if(modeflag & LineCompareOff) data = 0x08; if(SiS_Pr->ChipType == SIS_300) { SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x0F,0xF7,data); } else { if(SiS_Pr->ChipType >= XGI_20) data |= 0x20; if(SiS_Pr->SiS_ModeType == ModeEGA) { if(ModeNo > 0x13) { data |= 0x40; } } SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x0F,0xB7,data); } #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->ChipType >= SIS_315H) { SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x31,0xfb); } if(SiS_Pr->ChipType == SIS_315PRO) { data = SiS_Pr->SiS_SR15[(2 * 4) + SiS_Get310DRAMType(SiS_Pr)]; if(SiS_Pr->SiS_ModeType == ModeText) { data &= 0xc7; } else { data2 = SiS_GetOffset(SiS_Pr, ModeNo, ModeIdIndex, RRTI) >> 1; if(infoflag & InterlaceMode) data2 >>= 1; data3 = SiS_GetColorDepth(SiS_Pr, ModeNo, ModeIdIndex) >> 1; if(data3) data2 /= data3; if(data2 >= 0x50) { data &= 0x0f; data |= 0x50; } } SiS_SetReg(SiS_Pr->SiS_P3c4,0x17,data); } else if((SiS_Pr->ChipType == SIS_330) || (SiS_Pr->SiS_SysFlags & SF_760LFB)) { data = SiS_Get310DRAMType(SiS_Pr); if(SiS_Pr->ChipType == SIS_330) { data = SiS_Pr->SiS_SR15[(2 * 4) + data]; } else { if(SiS_Pr->SiS_ROMNew) data = ROMAddr[0xf6]; else if(SiS_Pr->SiS_UseROM) data = ROMAddr[0x100 + data]; else data = 0xba; } if(SiS_Pr->SiS_ModeType <= ModeEGA) { data &= 0xc7; } else { if(SiS_Pr->UseCustomMode) { data2 = SiS_Pr->CSRClock; } else { data2 = SiS_GetVCLK2Ptr(SiS_Pr, ModeNo, ModeIdIndex, RRTI); data2 = SiS_Pr->SiS_VCLKData[data2].CLOCK; } data3 = SiS_GetColorDepth(SiS_Pr, ModeNo, ModeIdIndex) >> 1; if(data3) data2 *= data3; data2 = ((unsigned int)(SiS_GetMCLK(SiS_Pr) * 1024)) / data2; if(SiS_Pr->ChipType == SIS_330) { if(SiS_Pr->SiS_ModeType != Mode16Bpp) { if (data2 >= 0x19c) data = 0xba; else if(data2 >= 0x140) data = 0x7a; else if(data2 >= 0x101) data = 0x3a; else if(data2 >= 0xf5) data = 0x32; else if(data2 >= 0xe2) data = 0x2a; else if(data2 >= 0xc4) data = 0x22; else if(data2 >= 0xac) data = 0x1a; else if(data2 >= 0x9e) data = 0x12; else if(data2 >= 0x8e) data = 0x0a; else data = 0x02; } else { if(data2 >= 0x127) data = 0xba; else data = 0x7a; } } else { /* 76x+LFB */ if (data2 >= 0x190) data = 0xba; else if(data2 >= 0xff) data = 0x7a; else if(data2 >= 0xd3) data = 0x3a; else if(data2 >= 0xa9) data = 0x1a; else if(data2 >= 0x93) data = 0x0a; else data = 0x02; } } SiS_SetReg(SiS_Pr->SiS_P3c4,0x17,data); } /* XGI: Nothing. */ /* TODO: Check SiS340 */ #endif data = 0x60; if(SiS_Pr->SiS_ModeType != ModeText) { data ^= 0x60; if(SiS_Pr->SiS_ModeType != ModeEGA) { data ^= 0xA0; } } SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x21,0x1F,data); SiS_SetVCLKState(SiS_Pr, ModeNo, RRTI, ModeIdIndex); #ifdef CONFIG_FB_SIS_315 if(((SiS_Pr->ChipType >= SIS_315H) && (SiS_Pr->ChipType < SIS_661)) || (SiS_Pr->ChipType == XGI_40)) { if(SiS_GetReg(SiS_Pr->SiS_P3d4,0x31) & 0x40) { SiS_SetReg(SiS_Pr->SiS_P3d4,0x52,0x2c); } else { SiS_SetReg(SiS_Pr->SiS_P3d4,0x52,0x6c); } } else if(SiS_Pr->ChipType == XGI_20) { if(SiS_GetReg(SiS_Pr->SiS_P3d4,0x31) & 0x40) { SiS_SetReg(SiS_Pr->SiS_P3d4,0x52,0x33); } else { SiS_SetReg(SiS_Pr->SiS_P3d4,0x52,0x73); } SiS_SetReg(SiS_Pr->SiS_P3d4,0x51,0x02); } #endif } #ifdef CONFIG_FB_SIS_315 static void SiS_SetupDualChip(struct SiS_Private *SiS_Pr) { #if 0 /* TODO: Find out about IOAddress2 */ SISIOADDRESS P2_3c2 = SiS_Pr->IOAddress2 + 0x12; SISIOADDRESS P2_3c4 = SiS_Pr->IOAddress2 + 0x14; SISIOADDRESS P2_3ce = SiS_Pr->IOAddress2 + 0x1e; int i; if((SiS_Pr->ChipRevision != 0) || (!(SiS_GetReg(SiS_Pr->SiS_P3c4,0x3a) & 0x04))) return; for(i = 0; i <= 4; i++) { /* SR00 - SR04 */ SiS_SetReg(P2_3c4,i,SiS_GetReg(SiS_Pr->SiS_P3c4,i)); } for(i = 0; i <= 8; i++) { /* GR00 - GR08 */ SiS_SetReg(P2_3ce,i,SiS_GetReg(SiS_Pr->SiS_P3ce,i)); } SiS_SetReg(P2_3c4,0x05,0x86); SiS_SetReg(P2_3c4,0x06,SiS_GetReg(SiS_Pr->SiS_P3c4,0x06)); /* SR06 */ SiS_SetReg(P2_3c4,0x21,SiS_GetReg(SiS_Pr->SiS_P3c4,0x21)); /* SR21 */ SiS_SetRegByte(P2_3c2,SiS_GetRegByte(SiS_Pr->SiS_P3cc)); /* MISC */ SiS_SetReg(P2_3c4,0x05,0x00); #endif } #endif /*********************************************/ /* LOAD DAC */ /*********************************************/ static void SiS_WriteDAC(struct SiS_Private *SiS_Pr, SISIOADDRESS DACData, unsigned short shiftflag, unsigned short dl, unsigned short ah, unsigned short al, unsigned short dh) { unsigned short d1, d2, d3; switch(dl) { case 0: d1 = dh; d2 = ah; d3 = al; break; case 1: d1 = ah; d2 = al; d3 = dh; break; default: d1 = al; d2 = dh; d3 = ah; } SiS_SetRegByte(DACData, (d1 << shiftflag)); SiS_SetRegByte(DACData, (d2 << shiftflag)); SiS_SetRegByte(DACData, (d3 << shiftflag)); } void SiS_LoadDAC(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned short data, data2, time, i, j, k, m, n, o; unsigned short si, di, bx, sf; SISIOADDRESS DACAddr, DACData; const unsigned char *table = NULL; data = SiS_GetModeFlag(SiS_Pr, ModeNo, ModeIdIndex) & DACInfoFlag; j = time = 64; if(data == 0x00) table = SiS_MDA_DAC; else if(data == 0x08) table = SiS_CGA_DAC; else if(data == 0x10) table = SiS_EGA_DAC; else if(data == 0x18) { j = 16; time = 256; table = SiS_VGA_DAC; } if( ( (SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) && /* 301B-DH LCD */ (SiS_Pr->SiS_VBType & VB_NoLCD) ) || (SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) || /* LCDA */ (!(SiS_Pr->SiS_SetFlag & ProgrammingCRT2)) ) { /* Programming CRT1 */ SiS_SetRegByte(SiS_Pr->SiS_P3c6,0xFF); DACAddr = SiS_Pr->SiS_P3c8; DACData = SiS_Pr->SiS_P3c9; sf = 0; } else { DACAddr = SiS_Pr->SiS_Part5Port; DACData = SiS_Pr->SiS_Part5Port + 1; sf = 2; } SiS_SetRegByte(DACAddr,0x00); for(i = 0; i < j; i++) { data = table[i]; for(k = 0; k < 3; k++) { data2 = 0; if(data & 0x01) data2 += 0x2A; if(data & 0x02) data2 += 0x15; SiS_SetRegByte(DACData, (data2 << sf)); data >>= 2; } } if(time == 256) { for(i = 16; i < 32; i++) { data = table[i] << sf; for(k = 0; k < 3; k++) SiS_SetRegByte(DACData, data); } si = 32; for(m = 0; m < 9; m++) { di = si; bx = si + 4; for(n = 0; n < 3; n++) { for(o = 0; o < 5; o++) { SiS_WriteDAC(SiS_Pr, DACData, sf, n, table[di], table[bx], table[si]); si++; } si -= 2; for(o = 0; o < 3; o++) { SiS_WriteDAC(SiS_Pr, DACData, sf, n, table[di], table[si], table[bx]); si--; } } /* for n < 3 */ si += 5; } /* for m < 9 */ } } /*********************************************/ /* SET CRT1 REGISTER GROUP */ /*********************************************/ static void SiS_SetCRT1Group(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned short StandTableIndex, RefreshRateTableIndex; SiS_Pr->SiS_CRT1Mode = ModeNo; StandTableIndex = SiS_GetModePtr(SiS_Pr, ModeNo, ModeIdIndex); if(SiS_Pr->SiS_SetFlag & LowModeTests) { if(SiS_Pr->SiS_VBInfo & (SetSimuScanMode | SwitchCRT2)) { SiS_DisableBridge(SiS_Pr); } } SiS_ResetSegmentRegisters(SiS_Pr); SiS_SetSeqRegs(SiS_Pr, StandTableIndex); SiS_SetMiscRegs(SiS_Pr, StandTableIndex); SiS_SetCRTCRegs(SiS_Pr, StandTableIndex); SiS_SetATTRegs(SiS_Pr, StandTableIndex); SiS_SetGRCRegs(SiS_Pr, StandTableIndex); SiS_ClearExt1Regs(SiS_Pr, ModeNo); SiS_ResetCRT1VCLK(SiS_Pr); SiS_Pr->SiS_SelectCRT2Rate = 0; SiS_Pr->SiS_SetFlag &= (~ProgrammingCRT2); if(SiS_Pr->SiS_VBInfo & SetSimuScanMode) { if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) { SiS_Pr->SiS_SetFlag |= ProgrammingCRT2; } } if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { SiS_Pr->SiS_SetFlag |= ProgrammingCRT2; } RefreshRateTableIndex = SiS_GetRatePtr(SiS_Pr, ModeNo, ModeIdIndex); if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA)) { SiS_Pr->SiS_SetFlag &= ~ProgrammingCRT2; } if(RefreshRateTableIndex != 0xFFFF) { SiS_SetCRT1Sync(SiS_Pr, RefreshRateTableIndex); SiS_SetCRT1CRTC(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); SiS_SetCRT1Offset(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); SiS_SetCRT1VCLK(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } switch(SiS_Pr->ChipType) { #ifdef CONFIG_FB_SIS_300 case SIS_300: SiS_SetCRT1FIFO_300(SiS_Pr, ModeNo, RefreshRateTableIndex); break; case SIS_540: case SIS_630: case SIS_730: SiS_SetCRT1FIFO_630(SiS_Pr, ModeNo, RefreshRateTableIndex); break; #endif default: #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->ChipType == XGI_20) { unsigned char sr2b = 0, sr2c = 0; switch(ModeNo) { case 0x00: case 0x01: sr2b = 0x4e; sr2c = 0xe9; break; case 0x04: case 0x05: case 0x0d: sr2b = 0x1b; sr2c = 0xe3; break; } if(sr2b) { SiS_SetReg(SiS_Pr->SiS_P3c4,0x2b,sr2b); SiS_SetReg(SiS_Pr->SiS_P3c4,0x2c,sr2c); SiS_SetRegByte(SiS_Pr->SiS_P3c2,(SiS_GetRegByte(SiS_Pr->SiS_P3cc) | 0x0c)); } } SiS_SetCRT1FIFO_310(SiS_Pr, ModeNo, ModeIdIndex); #endif break; } SiS_SetCRT1ModeRegs(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->ChipType == XGI_40) { SiS_SetupDualChip(SiS_Pr); } #endif SiS_LoadDAC(SiS_Pr, ModeNo, ModeIdIndex); if(SiS_Pr->SiS_flag_clearbuffer) { SiS_ClearBuffer(SiS_Pr, ModeNo); } if(!(SiS_Pr->SiS_VBInfo & (SetSimuScanMode | SwitchCRT2 | SetCRT2ToLCDA))) { SiS_WaitRetrace1(SiS_Pr); SiS_DisplayOn(SiS_Pr); } } /*********************************************/ /* HELPER: VIDEO BRIDGE PROG CLK */ /*********************************************/ static void SiS_InitVB(struct SiS_Private *SiS_Pr) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; SiS_Pr->Init_P4_0E = 0; if(SiS_Pr->SiS_ROMNew) { SiS_Pr->Init_P4_0E = ROMAddr[0x82]; } else if(SiS_Pr->ChipType >= XGI_40) { if(SiS_Pr->SiS_XGIROM) { SiS_Pr->Init_P4_0E = ROMAddr[0x80]; } } } static void SiS_ResetVB(struct SiS_Private *SiS_Pr) { #ifdef CONFIG_FB_SIS_315 unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short temp; /* VB programming clock */ if(SiS_Pr->SiS_UseROM) { if(SiS_Pr->ChipType < SIS_330) { temp = ROMAddr[VB310Data_1_2_Offset] | 0x40; if(SiS_Pr->SiS_ROMNew) temp = ROMAddr[0x80] | 0x40; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x02,temp); } else if(SiS_Pr->ChipType >= SIS_661 && SiS_Pr->ChipType < XGI_20) { temp = ROMAddr[0x7e] | 0x40; if(SiS_Pr->SiS_ROMNew) temp = ROMAddr[0x80] | 0x40; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x02,temp); } } else if(SiS_Pr->ChipType >= XGI_40) { temp = 0x40; if(SiS_Pr->SiS_XGIROM) temp |= ROMAddr[0x7e]; /* Can we do this on any chipset? */ SiS_SetReg(SiS_Pr->SiS_Part1Port,0x02,temp); } #endif } /*********************************************/ /* HELPER: SET VIDEO/CAPTURE REGISTERS */ /*********************************************/ static void SiS_StrangeStuff(struct SiS_Private *SiS_Pr) { /* SiS65x and XGI set up some sort of "lock mode" for text * which locks CRT2 in some way to CRT1 timing. Disable * this here. */ #ifdef CONFIG_FB_SIS_315 if((IS_SIS651) || (IS_SISM650) || SiS_Pr->ChipType == SIS_340 || SiS_Pr->ChipType == XGI_40) { SiS_SetReg(SiS_Pr->SiS_VidCapt, 0x3f, 0x00); /* Fiddle with capture regs */ SiS_SetReg(SiS_Pr->SiS_VidCapt, 0x00, 0x00); SiS_SetReg(SiS_Pr->SiS_VidPlay, 0x00, 0x86); /* (BIOS does NOT unlock) */ SiS_SetRegAND(SiS_Pr->SiS_VidPlay, 0x30, 0xfe); /* Fiddle with video regs */ SiS_SetRegAND(SiS_Pr->SiS_VidPlay, 0x3f, 0xef); } /* !!! This does not support modes < 0x13 !!! */ #endif } /*********************************************/ /* HELPER: SET AGP TIMING FOR SiS760 */ /*********************************************/ static void SiS_Handle760(struct SiS_Private *SiS_Pr) { #ifdef CONFIG_FB_SIS_315 unsigned int somebase; unsigned char temp1, temp2, temp3; if( (SiS_Pr->ChipType != SIS_760) || ((SiS_GetReg(SiS_Pr->SiS_P3d4, 0x5c) & 0xf8) != 0x80) || (!(SiS_Pr->SiS_SysFlags & SF_760LFB)) || (!(SiS_Pr->SiS_SysFlags & SF_760UMA)) ) return; somebase = sisfb_read_mio_pci_word(SiS_Pr, 0x74); somebase &= 0xffff; if(somebase == 0) return; temp3 = SiS_GetRegByte((somebase + 0x85)) & 0xb7; if(SiS_GetReg(SiS_Pr->SiS_P3d4,0x31) & 0x40) { temp1 = 0x21; temp2 = 0x03; temp3 |= 0x08; } else { temp1 = 0x25; temp2 = 0x0b; } sisfb_write_nbridge_pci_byte(SiS_Pr, 0x7e, temp1); sisfb_write_nbridge_pci_byte(SiS_Pr, 0x8d, temp2); SiS_SetRegByte((somebase + 0x85), temp3); #endif } /*********************************************/ /* SiSSetMode() */ /*********************************************/ bool SiSSetMode(struct SiS_Private *SiS_Pr, unsigned short ModeNo) { SISIOADDRESS BaseAddr = SiS_Pr->IOAddress; unsigned short RealModeNo, ModeIdIndex; unsigned char backupreg = 0; unsigned short KeepLockReg; SiS_Pr->UseCustomMode = false; SiS_Pr->CRT1UsesCustomMode = false; SiS_Pr->SiS_flag_clearbuffer = 0; if(SiS_Pr->UseCustomMode) { ModeNo = 0xfe; } else { if(!(ModeNo & 0x80)) SiS_Pr->SiS_flag_clearbuffer = 1; ModeNo &= 0x7f; } /* Don't use FSTN mode for CRT1 */ RealModeNo = ModeNo; if(ModeNo == 0x5b) ModeNo = 0x56; SiSInitPtr(SiS_Pr); SiSRegInit(SiS_Pr, BaseAddr); SiS_GetSysFlags(SiS_Pr); SiS_Pr->SiS_VGAINFO = 0x11; KeepLockReg = SiS_GetReg(SiS_Pr->SiS_P3c4,0x05); SiS_SetReg(SiS_Pr->SiS_P3c4,0x05,0x86); SiSInitPCIetc(SiS_Pr); SiSSetLVDSetc(SiS_Pr); SiSDetermineROMUsage(SiS_Pr); SiS_UnLockCRT2(SiS_Pr); if(!SiS_Pr->UseCustomMode) { if(!(SiS_SearchModeID(SiS_Pr, &ModeNo, &ModeIdIndex))) return false; } else { ModeIdIndex = 0; } SiS_GetVBType(SiS_Pr); /* Init/restore some VB registers */ SiS_InitVB(SiS_Pr); if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { if(SiS_Pr->ChipType >= SIS_315H) { SiS_ResetVB(SiS_Pr); SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x32,0x10); SiS_SetRegOR(SiS_Pr->SiS_Part2Port,0x00,0x0c); backupreg = SiS_GetReg(SiS_Pr->SiS_P3d4,0x38); } else { backupreg = SiS_GetReg(SiS_Pr->SiS_P3d4,0x35); } } /* Get VB information (connectors, connected devices) */ SiS_GetVBInfo(SiS_Pr, ModeNo, ModeIdIndex, (SiS_Pr->UseCustomMode) ? 0 : 1); SiS_SetYPbPr(SiS_Pr); SiS_SetTVMode(SiS_Pr, ModeNo, ModeIdIndex); SiS_GetLCDResInfo(SiS_Pr, ModeNo, ModeIdIndex); SiS_SetLowModeTest(SiS_Pr, ModeNo); /* Check memory size (kernel framebuffer driver only) */ if(!SiS_CheckMemorySize(SiS_Pr, ModeNo, ModeIdIndex)) { return false; } SiS_OpenCRTC(SiS_Pr); if(SiS_Pr->UseCustomMode) { SiS_Pr->CRT1UsesCustomMode = true; SiS_Pr->CSRClock_CRT1 = SiS_Pr->CSRClock; SiS_Pr->CModeFlag_CRT1 = SiS_Pr->CModeFlag; } else { SiS_Pr->CRT1UsesCustomMode = false; } /* Set mode on CRT1 */ if( (SiS_Pr->SiS_VBInfo & (SetSimuScanMode | SetCRT2ToLCDA)) || (!(SiS_Pr->SiS_VBInfo & SwitchCRT2)) ) { SiS_SetCRT1Group(SiS_Pr, ModeNo, ModeIdIndex); } /* Set mode on CRT2 */ if(SiS_Pr->SiS_VBInfo & (SetSimuScanMode | SwitchCRT2 | SetCRT2ToLCDA)) { if( (SiS_Pr->SiS_VBType & VB_SISVB) || (SiS_Pr->SiS_IF_DEF_LVDS == 1) || (SiS_Pr->SiS_IF_DEF_CH70xx != 0) || (SiS_Pr->SiS_IF_DEF_TRUMPION != 0) ) { SiS_SetCRT2Group(SiS_Pr, RealModeNo); } } SiS_HandleCRT1(SiS_Pr); SiS_StrangeStuff(SiS_Pr); SiS_DisplayOn(SiS_Pr); SiS_SetRegByte(SiS_Pr->SiS_P3c6,0xFF); #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->ChipType >= SIS_315H) { if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { if(!(SiS_IsDualEdge(SiS_Pr))) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x13,0xfb); } } } #endif if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { if(SiS_Pr->ChipType >= SIS_315H) { #ifdef CONFIG_FB_SIS_315 if(!SiS_Pr->SiS_ROMNew) { if(SiS_IsVAMode(SiS_Pr)) { SiS_SetRegOR(SiS_Pr->SiS_P3d4,0x35,0x01); } else { SiS_SetRegAND(SiS_Pr->SiS_P3d4,0x35,0xFE); } } SiS_SetReg(SiS_Pr->SiS_P3d4,0x38,backupreg); if((IS_SIS650) && (SiS_GetReg(SiS_Pr->SiS_P3d4,0x30) & 0xfc)) { if((ModeNo == 0x03) || (ModeNo == 0x10)) { SiS_SetRegOR(SiS_Pr->SiS_P3d4,0x51,0x80); SiS_SetRegOR(SiS_Pr->SiS_P3d4,0x56,0x08); } } if(SiS_GetReg(SiS_Pr->SiS_P3d4,0x30) & SetCRT2ToLCD) { SiS_SetRegAND(SiS_Pr->SiS_P3d4,0x38,0xfc); } #endif } else if((SiS_Pr->ChipType == SIS_630) || (SiS_Pr->ChipType == SIS_730)) { SiS_SetReg(SiS_Pr->SiS_P3d4,0x35,backupreg); } } SiS_CloseCRTC(SiS_Pr); SiS_Handle760(SiS_Pr); /* We never lock registers in XF86 */ if(KeepLockReg != 0xA1) SiS_SetReg(SiS_Pr->SiS_P3c4,0x05,0x00); return true; } #ifndef GETBITSTR #define BITMASK(h,l) (((unsigned)(1U << ((h)-(l)+1))-1)<<(l)) #define GENMASK(mask) BITMASK(1?mask,0?mask) #define GETBITS(var,mask) (((var) & GENMASK(mask)) >> (0?mask)) #define GETBITSTR(val,from,to) ((GETBITS(val,from)) << (0?to)) #endif void SiS_CalcCRRegisters(struct SiS_Private *SiS_Pr, int depth) { int x = 1; /* Fix sync */ SiS_Pr->CCRT1CRTC[0] = ((SiS_Pr->CHTotal >> 3) - 5) & 0xff; /* CR0 */ SiS_Pr->CCRT1CRTC[1] = (SiS_Pr->CHDisplay >> 3) - 1; /* CR1 */ SiS_Pr->CCRT1CRTC[2] = (SiS_Pr->CHBlankStart >> 3) - 1; /* CR2 */ SiS_Pr->CCRT1CRTC[3] = (((SiS_Pr->CHBlankEnd >> 3) - 1) & 0x1F) | 0x80; /* CR3 */ SiS_Pr->CCRT1CRTC[4] = (SiS_Pr->CHSyncStart >> 3) + 3; /* CR4 */ SiS_Pr->CCRT1CRTC[5] = ((((SiS_Pr->CHBlankEnd >> 3) - 1) & 0x20) << 2) | /* CR5 */ (((SiS_Pr->CHSyncEnd >> 3) + 3) & 0x1F); SiS_Pr->CCRT1CRTC[6] = (SiS_Pr->CVTotal - 2) & 0xFF; /* CR6 */ SiS_Pr->CCRT1CRTC[7] = (((SiS_Pr->CVTotal - 2) & 0x100) >> 8) /* CR7 */ | (((SiS_Pr->CVDisplay - 1) & 0x100) >> 7) | (((SiS_Pr->CVSyncStart - x) & 0x100) >> 6) | (((SiS_Pr->CVBlankStart- 1) & 0x100) >> 5) | 0x10 | (((SiS_Pr->CVTotal - 2) & 0x200) >> 4) | (((SiS_Pr->CVDisplay - 1) & 0x200) >> 3) | (((SiS_Pr->CVSyncStart - x) & 0x200) >> 2); SiS_Pr->CCRT1CRTC[16] = ((((SiS_Pr->CVBlankStart - 1) & 0x200) >> 4) >> 5); /* CR9 */ if(depth != 8) { if(SiS_Pr->CHDisplay >= 1600) SiS_Pr->CCRT1CRTC[16] |= 0x60; /* SRE */ else if(SiS_Pr->CHDisplay >= 640) SiS_Pr->CCRT1CRTC[16] |= 0x40; } SiS_Pr->CCRT1CRTC[8] = (SiS_Pr->CVSyncStart - x) & 0xFF; /* CR10 */ SiS_Pr->CCRT1CRTC[9] = ((SiS_Pr->CVSyncEnd - x) & 0x0F) | 0x80; /* CR11 */ SiS_Pr->CCRT1CRTC[10] = (SiS_Pr->CVDisplay - 1) & 0xFF; /* CR12 */ SiS_Pr->CCRT1CRTC[11] = (SiS_Pr->CVBlankStart - 1) & 0xFF; /* CR15 */ SiS_Pr->CCRT1CRTC[12] = (SiS_Pr->CVBlankEnd - 1) & 0xFF; /* CR16 */ SiS_Pr->CCRT1CRTC[13] = /* SRA */ GETBITSTR((SiS_Pr->CVTotal -2), 10:10, 0:0) | GETBITSTR((SiS_Pr->CVDisplay -1), 10:10, 1:1) | GETBITSTR((SiS_Pr->CVBlankStart-1), 10:10, 2:2) | GETBITSTR((SiS_Pr->CVSyncStart -x), 10:10, 3:3) | GETBITSTR((SiS_Pr->CVBlankEnd -1), 8:8, 4:4) | GETBITSTR((SiS_Pr->CVSyncEnd ), 4:4, 5:5) ; SiS_Pr->CCRT1CRTC[14] = /* SRB */ GETBITSTR((SiS_Pr->CHTotal >> 3) - 5, 9:8, 1:0) | GETBITSTR((SiS_Pr->CHDisplay >> 3) - 1, 9:8, 3:2) | GETBITSTR((SiS_Pr->CHBlankStart >> 3) - 1, 9:8, 5:4) | GETBITSTR((SiS_Pr->CHSyncStart >> 3) + 3, 9:8, 7:6) ; SiS_Pr->CCRT1CRTC[15] = /* SRC */ GETBITSTR((SiS_Pr->CHBlankEnd >> 3) - 1, 7:6, 1:0) | GETBITSTR((SiS_Pr->CHSyncEnd >> 3) + 3, 5:5, 2:2) ; } void SiS_CalcLCDACRT1Timing(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned short modeflag, tempax, tempbx = 0, remaining = 0; unsigned short VGAHDE = SiS_Pr->SiS_VGAHDE; int i, j; /* 1:1 data: use data set by setcrt1crtc() */ if(SiS_Pr->SiS_LCDInfo & LCDPass11) return; modeflag = SiS_GetModeFlag(SiS_Pr, ModeNo, ModeIdIndex); if(modeflag & HalfDCLK) VGAHDE >>= 1; SiS_Pr->CHDisplay = VGAHDE; SiS_Pr->CHBlankStart = VGAHDE; SiS_Pr->CVDisplay = SiS_Pr->SiS_VGAVDE; SiS_Pr->CVBlankStart = SiS_Pr->SiS_VGAVDE; if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 tempbx = SiS_Pr->SiS_VGAHT; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { tempbx = SiS_Pr->PanelHT; } if(modeflag & HalfDCLK) tempbx >>= 1; remaining = tempbx % 8; #endif } else { #ifdef CONFIG_FB_SIS_315 /* OK for LCDA, LVDS */ tempbx = SiS_Pr->PanelHT - SiS_Pr->PanelXRes; tempax = SiS_Pr->SiS_VGAHDE; /* not /2 ! */ if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { tempax = SiS_Pr->PanelXRes; } tempbx += tempax; if(modeflag & HalfDCLK) tempbx -= VGAHDE; #endif } SiS_Pr->CHTotal = SiS_Pr->CHBlankEnd = tempbx; if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 if(SiS_Pr->SiS_VGAHDE == SiS_Pr->PanelXRes) { SiS_Pr->CHSyncStart = SiS_Pr->SiS_VGAHDE + ((SiS_Pr->PanelHRS + 1) & ~1); SiS_Pr->CHSyncEnd = SiS_Pr->CHSyncStart + SiS_Pr->PanelHRE; if(modeflag & HalfDCLK) { SiS_Pr->CHSyncStart >>= 1; SiS_Pr->CHSyncEnd >>= 1; } } else if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { tempax = (SiS_Pr->PanelXRes - SiS_Pr->SiS_VGAHDE) >> 1; tempbx = (SiS_Pr->PanelHRS + 1) & ~1; if(modeflag & HalfDCLK) { tempax >>= 1; tempbx >>= 1; } SiS_Pr->CHSyncStart = (VGAHDE + tempax + tempbx + 7) & ~7; tempax = SiS_Pr->PanelHRE + 7; if(modeflag & HalfDCLK) tempax >>= 1; SiS_Pr->CHSyncEnd = (SiS_Pr->CHSyncStart + tempax) & ~7; } else { SiS_Pr->CHSyncStart = SiS_Pr->SiS_VGAHDE; if(modeflag & HalfDCLK) { SiS_Pr->CHSyncStart >>= 1; tempax = ((SiS_Pr->CHTotal - SiS_Pr->CHSyncStart) / 3) << 1; SiS_Pr->CHSyncEnd = SiS_Pr->CHSyncStart + tempax; } else { SiS_Pr->CHSyncEnd = (SiS_Pr->CHSyncStart + (SiS_Pr->CHTotal / 10) + 7) & ~7; SiS_Pr->CHSyncStart += 8; } } #endif } else { #ifdef CONFIG_FB_SIS_315 tempax = VGAHDE; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { tempbx = SiS_Pr->PanelXRes; if(modeflag & HalfDCLK) tempbx >>= 1; tempax += ((tempbx - tempax) >> 1); } tempax += SiS_Pr->PanelHRS; SiS_Pr->CHSyncStart = tempax; tempax += SiS_Pr->PanelHRE; SiS_Pr->CHSyncEnd = tempax; #endif } tempbx = SiS_Pr->PanelVT - SiS_Pr->PanelYRes; tempax = SiS_Pr->SiS_VGAVDE; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { tempax = SiS_Pr->PanelYRes; } else if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 /* Stupid hack for 640x400/320x200 */ if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { if((tempax + tempbx) == 438) tempbx += 16; } else if((SiS_Pr->SiS_LCDResInfo == Panel_800x600) || (SiS_Pr->SiS_LCDResInfo == Panel_1024x600)) { tempax = 0; tempbx = SiS_Pr->SiS_VGAVT; } #endif } SiS_Pr->CVTotal = SiS_Pr->CVBlankEnd = tempbx + tempax; tempax = SiS_Pr->SiS_VGAVDE; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { tempax += (SiS_Pr->PanelYRes - tempax) >> 1; } tempax += SiS_Pr->PanelVRS; SiS_Pr->CVSyncStart = tempax; tempax += SiS_Pr->PanelVRE; SiS_Pr->CVSyncEnd = tempax; if(SiS_Pr->ChipType < SIS_315H) { SiS_Pr->CVSyncStart--; SiS_Pr->CVSyncEnd--; } SiS_CalcCRRegisters(SiS_Pr, 8); SiS_Pr->CCRT1CRTC[15] &= ~0xF8; SiS_Pr->CCRT1CRTC[15] |= (remaining << 4); SiS_Pr->CCRT1CRTC[16] &= ~0xE0; SiS_SetRegAND(SiS_Pr->SiS_P3d4,0x11,0x7f); for(i = 0, j = 0; i <= 7; i++, j++) { SiS_SetReg(SiS_Pr->SiS_P3d4,j,SiS_Pr->CCRT1CRTC[i]); } for(j = 0x10; i <= 10; i++, j++) { SiS_SetReg(SiS_Pr->SiS_P3d4,j,SiS_Pr->CCRT1CRTC[i]); } for(j = 0x15; i <= 12; i++, j++) { SiS_SetReg(SiS_Pr->SiS_P3d4,j,SiS_Pr->CCRT1CRTC[i]); } for(j = 0x0A; i <= 15; i++, j++) { SiS_SetReg(SiS_Pr->SiS_P3c4,j,SiS_Pr->CCRT1CRTC[i]); } tempax = SiS_Pr->CCRT1CRTC[16] & 0xE0; SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x0E,0x1F,tempax); tempax = (SiS_Pr->CCRT1CRTC[16] & 0x01) << 5; if(modeflag & DoubleScanMode) tempax |= 0x80; SiS_SetRegANDOR(SiS_Pr->SiS_P3d4,0x09,0x5F,tempax); } void SiS_Generic_ConvertCRData(struct SiS_Private *SiS_Pr, unsigned char *crdata, int xres, int yres, struct fb_var_screeninfo *var, bool writeres ) { unsigned short HRE, HBE, HRS, HBS, HDE, HT; unsigned short VRE, VBE, VRS, VBS, VDE, VT; unsigned char sr_data, cr_data, cr_data2; int A, B, C, D, E, F, temp; sr_data = crdata[14]; /* Horizontal total */ HT = crdata[0] | ((unsigned short)(sr_data & 0x03) << 8); A = HT + 5; /* Horizontal display enable end */ HDE = crdata[1] | ((unsigned short)(sr_data & 0x0C) << 6); E = HDE + 1; /* Horizontal retrace (=sync) start */ HRS = crdata[4] | ((unsigned short)(sr_data & 0xC0) << 2); F = HRS - E - 3; /* Horizontal blank start */ HBS = crdata[2] | ((unsigned short)(sr_data & 0x30) << 4); sr_data = crdata[15]; cr_data = crdata[5]; /* Horizontal blank end */ HBE = (crdata[3] & 0x1f) | ((unsigned short)(cr_data & 0x80) >> 2) | ((unsigned short)(sr_data & 0x03) << 6); /* Horizontal retrace (=sync) end */ HRE = (cr_data & 0x1f) | ((sr_data & 0x04) << 3); temp = HBE - ((E - 1) & 255); B = (temp > 0) ? temp : (temp + 256); temp = HRE - ((E + F + 3) & 63); C = (temp > 0) ? temp : (temp + 64); D = B - F - C; if(writeres) var->xres = xres = E * 8; var->left_margin = D * 8; var->right_margin = F * 8; var->hsync_len = C * 8; /* Vertical */ sr_data = crdata[13]; cr_data = crdata[7]; /* Vertical total */ VT = crdata[6] | ((unsigned short)(cr_data & 0x01) << 8) | ((unsigned short)(cr_data & 0x20) << 4) | ((unsigned short)(sr_data & 0x01) << 10); A = VT + 2; /* Vertical display enable end */ VDE = crdata[10] | ((unsigned short)(cr_data & 0x02) << 7) | ((unsigned short)(cr_data & 0x40) << 3) | ((unsigned short)(sr_data & 0x02) << 9); E = VDE + 1; /* Vertical retrace (=sync) start */ VRS = crdata[8] | ((unsigned short)(cr_data & 0x04) << 6) | ((unsigned short)(cr_data & 0x80) << 2) | ((unsigned short)(sr_data & 0x08) << 7); F = VRS + 1 - E; cr_data2 = (crdata[16] & 0x01) << 5; /* Vertical blank start */ VBS = crdata[11] | ((unsigned short)(cr_data & 0x08) << 5) | ((unsigned short)(cr_data2 & 0x20) << 4) | ((unsigned short)(sr_data & 0x04) << 8); /* Vertical blank end */ VBE = crdata[12] | ((unsigned short)(sr_data & 0x10) << 4); temp = VBE - ((E - 1) & 511); B = (temp > 0) ? temp : (temp + 512); /* Vertical retrace (=sync) end */ VRE = (crdata[9] & 0x0f) | ((sr_data & 0x20) >> 1); temp = VRE - ((E + F - 1) & 31); C = (temp > 0) ? temp : (temp + 32); D = B - F - C; if(writeres) var->yres = yres = E; var->upper_margin = D; var->lower_margin = F; var->vsync_len = C; if((xres == 320) && ((yres == 200) || (yres == 240))) { /* Terrible hack, but correct CRTC data for * these modes only produces a black screen... * (HRE is 0, leading into a too large C and * a negative D. The CRT controller does not * seem to like correcting HRE to 50) */ var->left_margin = (400 - 376); var->right_margin = (328 - 320); var->hsync_len = (376 - 328); } }
gpl-2.0
civato/CivZ-P900-KitKat-SOURCE
net/irda/wrapper.c
13272
13361
/********************************************************************* * * Filename: wrapper.c * Version: 1.2 * Description: IrDA SIR async wrapper layer * Status: Stable * Author: Dag Brattli <dagb@cs.uit.no> * Created at: Mon Aug 4 20:40:53 1997 * Modified at: Fri Jan 28 13:21:09 2000 * Modified by: Dag Brattli <dagb@cs.uit.no> * Modified at: Fri May 28 3:11 CST 1999 * Modified by: Horst von Brand <vonbrand@sleipnir.valparaiso.cl> * * Copyright (c) 1998-2000 Dag Brattli <dagb@cs.uit.no>, * All Rights Reserved. * Copyright (c) 2000-2002 Jean Tourrilhes <jt@hpl.hp.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * Neither Dag Brattli nor University of Tromsø admit liability nor * provide warranty for any of this software. This material is * provided "AS-IS" and at no charge. * ********************************************************************/ #include <linux/skbuff.h> #include <linux/string.h> #include <linux/module.h> #include <asm/byteorder.h> #include <net/irda/irda.h> #include <net/irda/wrapper.h> #include <net/irda/crc.h> #include <net/irda/irlap.h> #include <net/irda/irlap_frame.h> #include <net/irda/irda_device.h> /************************** FRAME WRAPPING **************************/ /* * Unwrap and unstuff SIR frames * * Note : at FIR and MIR, HDLC framing is used and usually handled * by the controller, so we come here only for SIR... Jean II */ /* * Function stuff_byte (byte, buf) * * Byte stuff one single byte and put the result in buffer pointed to by * buf. The buffer must at all times be able to have two bytes inserted. * * This is in a tight loop, better inline it, so need to be prior to callers. * (2000 bytes on P6 200MHz, non-inlined ~370us, inline ~170us) - Jean II */ static inline int stuff_byte(__u8 byte, __u8 *buf) { switch (byte) { case BOF: /* FALLTHROUGH */ case EOF: /* FALLTHROUGH */ case CE: /* Insert transparently coded */ buf[0] = CE; /* Send link escape */ buf[1] = byte^IRDA_TRANS; /* Complement bit 5 */ return 2; /* break; */ default: /* Non-special value, no transparency required */ buf[0] = byte; return 1; /* break; */ } } /* * Function async_wrap (skb, *tx_buff, buffsize) * * Makes a new buffer with wrapping and stuffing, should check that * we don't get tx buffer overflow. */ int async_wrap_skb(struct sk_buff *skb, __u8 *tx_buff, int buffsize) { struct irda_skb_cb *cb = (struct irda_skb_cb *) skb->cb; int xbofs; int i; int n; union { __u16 value; __u8 bytes[2]; } fcs; /* Initialize variables */ fcs.value = INIT_FCS; n = 0; /* * Send XBOF's for required min. turn time and for the negotiated * additional XBOFS */ if (cb->magic != LAP_MAGIC) { /* * This will happen for all frames sent from user-space. * Nothing to worry about, but we set the default number of * BOF's */ IRDA_DEBUG(1, "%s(), wrong magic in skb!\n", __func__); xbofs = 10; } else xbofs = cb->xbofs + cb->xbofs_delay; IRDA_DEBUG(4, "%s(), xbofs=%d\n", __func__, xbofs); /* Check that we never use more than 115 + 48 xbofs */ if (xbofs > 163) { IRDA_DEBUG(0, "%s(), too many xbofs (%d)\n", __func__, xbofs); xbofs = 163; } memset(tx_buff + n, XBOF, xbofs); n += xbofs; /* Start of packet character BOF */ tx_buff[n++] = BOF; /* Insert frame and calc CRC */ for (i=0; i < skb->len; i++) { /* * Check for the possibility of tx buffer overflow. We use * bufsize-5 since the maximum number of bytes that can be * transmitted after this point is 5. */ if(n >= (buffsize-5)) { IRDA_ERROR("%s(), tx buffer overflow (n=%d)\n", __func__, n); return n; } n += stuff_byte(skb->data[i], tx_buff+n); fcs.value = irda_fcs(fcs.value, skb->data[i]); } /* Insert CRC in little endian format (LSB first) */ fcs.value = ~fcs.value; #ifdef __LITTLE_ENDIAN n += stuff_byte(fcs.bytes[0], tx_buff+n); n += stuff_byte(fcs.bytes[1], tx_buff+n); #else /* ifdef __BIG_ENDIAN */ n += stuff_byte(fcs.bytes[1], tx_buff+n); n += stuff_byte(fcs.bytes[0], tx_buff+n); #endif tx_buff[n++] = EOF; return n; } EXPORT_SYMBOL(async_wrap_skb); /************************* FRAME UNWRAPPING *************************/ /* * Unwrap and unstuff SIR frames * * Complete rewrite by Jean II : * More inline, faster, more compact, more logical. Jean II * (16 bytes on P6 200MHz, old 5 to 7 us, new 4 to 6 us) * (24 bytes on P6 200MHz, old 9 to 10 us, new 7 to 8 us) * (for reference, 115200 b/s is 1 byte every 69 us) * And reduce wrapper.o by ~900B in the process ;-) * * Then, we have the addition of ZeroCopy, which is optional * (i.e. the driver must initiate it) and improve final processing. * (2005 B frame + EOF on P6 200MHz, without 30 to 50 us, with 10 to 25 us) * * Note : at FIR and MIR, HDLC framing is used and usually handled * by the controller, so we come here only for SIR... Jean II */ /* * We can also choose where we want to do the CRC calculation. We can * do it "inline", as we receive the bytes, or "postponed", when * receiving the End-Of-Frame. * (16 bytes on P6 200MHz, inlined 4 to 6 us, postponed 4 to 5 us) * (24 bytes on P6 200MHz, inlined 7 to 8 us, postponed 5 to 7 us) * With ZeroCopy : * (2005 B frame on P6 200MHz, inlined 10 to 25 us, postponed 140 to 180 us) * Without ZeroCopy : * (2005 B frame on P6 200MHz, inlined 30 to 50 us, postponed 150 to 180 us) * (Note : numbers taken with irq disabled) * * From those numbers, it's not clear which is the best strategy, because * we end up running through a lot of data one way or another (i.e. cache * misses). I personally prefer to avoid the huge latency spike of the * "postponed" solution, because it come just at the time when we have * lot's of protocol processing to do and it will hurt our ability to * reach low link turnaround times... Jean II */ //#define POSTPONE_RX_CRC /* * Function async_bump (buf, len, stats) * * Got a frame, make a copy of it, and pass it up the stack! We can try * to inline it since it's only called from state_inside_frame */ static inline void async_bump(struct net_device *dev, struct net_device_stats *stats, iobuff_t *rx_buff) { struct sk_buff *newskb; struct sk_buff *dataskb; int docopy; /* Check if we need to copy the data to a new skb or not. * If the driver doesn't use ZeroCopy Rx, we have to do it. * With ZeroCopy Rx, the rx_buff already point to a valid * skb. But, if the frame is small, it is more efficient to * copy it to save memory (copy will be fast anyway - that's * called Rx-copy-break). Jean II */ docopy = ((rx_buff->skb == NULL) || (rx_buff->len < IRDA_RX_COPY_THRESHOLD)); /* Allocate a new skb */ newskb = dev_alloc_skb(docopy ? rx_buff->len + 1 : rx_buff->truesize); if (!newskb) { stats->rx_dropped++; /* We could deliver the current skb if doing ZeroCopy Rx, * but this would stall the Rx path. Better drop the * packet... Jean II */ return; } /* Align IP header to 20 bytes (i.e. increase skb->data) * Note this is only useful with IrLAN, as PPP has a variable * header size (2 or 1 bytes) - Jean II */ skb_reserve(newskb, 1); if(docopy) { /* Copy data without CRC (length already checked) */ skb_copy_to_linear_data(newskb, rx_buff->data, rx_buff->len - 2); /* Deliver this skb */ dataskb = newskb; } else { /* We are using ZeroCopy. Deliver old skb */ dataskb = rx_buff->skb; /* And hook the new skb to the rx_buff */ rx_buff->skb = newskb; rx_buff->head = newskb->data; /* NOT newskb->head */ //printk(KERN_DEBUG "ZeroCopy : len = %d, dataskb = %p, newskb = %p\n", rx_buff->len, dataskb, newskb); } /* Set proper length on skb (without CRC) */ skb_put(dataskb, rx_buff->len - 2); /* Feed it to IrLAP layer */ dataskb->dev = dev; skb_reset_mac_header(dataskb); dataskb->protocol = htons(ETH_P_IRDA); netif_rx(dataskb); stats->rx_packets++; stats->rx_bytes += rx_buff->len; /* Clean up rx_buff (redundant with async_unwrap_bof() ???) */ rx_buff->data = rx_buff->head; rx_buff->len = 0; } /* * Function async_unwrap_bof(dev, byte) * * Handle Beginning Of Frame character received within a frame * */ static inline void async_unwrap_bof(struct net_device *dev, struct net_device_stats *stats, iobuff_t *rx_buff, __u8 byte) { switch(rx_buff->state) { case LINK_ESCAPE: case INSIDE_FRAME: /* Not supposed to happen, the previous frame is not * finished - Jean II */ IRDA_DEBUG(1, "%s(), Discarding incomplete frame\n", __func__); stats->rx_errors++; stats->rx_missed_errors++; irda_device_set_media_busy(dev, TRUE); break; case OUTSIDE_FRAME: case BEGIN_FRAME: default: /* We may receive multiple BOF at the start of frame */ break; } /* Now receiving frame */ rx_buff->state = BEGIN_FRAME; rx_buff->in_frame = TRUE; /* Time to initialize receive buffer */ rx_buff->data = rx_buff->head; rx_buff->len = 0; rx_buff->fcs = INIT_FCS; } /* * Function async_unwrap_eof(dev, byte) * * Handle End Of Frame character received within a frame * */ static inline void async_unwrap_eof(struct net_device *dev, struct net_device_stats *stats, iobuff_t *rx_buff, __u8 byte) { #ifdef POSTPONE_RX_CRC int i; #endif switch(rx_buff->state) { case OUTSIDE_FRAME: /* Probably missed the BOF */ stats->rx_errors++; stats->rx_missed_errors++; irda_device_set_media_busy(dev, TRUE); break; case BEGIN_FRAME: case LINK_ESCAPE: case INSIDE_FRAME: default: /* Note : in the case of BEGIN_FRAME and LINK_ESCAPE, * the fcs will most likely not match and generate an * error, as expected - Jean II */ rx_buff->state = OUTSIDE_FRAME; rx_buff->in_frame = FALSE; #ifdef POSTPONE_RX_CRC /* If we haven't done the CRC as we receive bytes, we * must do it now... Jean II */ for(i = 0; i < rx_buff->len; i++) rx_buff->fcs = irda_fcs(rx_buff->fcs, rx_buff->data[i]); #endif /* Test FCS and signal success if the frame is good */ if (rx_buff->fcs == GOOD_FCS) { /* Deliver frame */ async_bump(dev, stats, rx_buff); break; } else { /* Wrong CRC, discard frame! */ irda_device_set_media_busy(dev, TRUE); IRDA_DEBUG(1, "%s(), crc error\n", __func__); stats->rx_errors++; stats->rx_crc_errors++; } break; } } /* * Function async_unwrap_ce(dev, byte) * * Handle Character Escape character received within a frame * */ static inline void async_unwrap_ce(struct net_device *dev, struct net_device_stats *stats, iobuff_t *rx_buff, __u8 byte) { switch(rx_buff->state) { case OUTSIDE_FRAME: /* Activate carrier sense */ irda_device_set_media_busy(dev, TRUE); break; case LINK_ESCAPE: IRDA_WARNING("%s: state not defined\n", __func__); break; case BEGIN_FRAME: case INSIDE_FRAME: default: /* Stuffed byte coming */ rx_buff->state = LINK_ESCAPE; break; } } /* * Function async_unwrap_other(dev, byte) * * Handle other characters received within a frame * */ static inline void async_unwrap_other(struct net_device *dev, struct net_device_stats *stats, iobuff_t *rx_buff, __u8 byte) { switch(rx_buff->state) { /* This is on the critical path, case are ordered by * probability (most frequent first) - Jean II */ case INSIDE_FRAME: /* Must be the next byte of the frame */ if (rx_buff->len < rx_buff->truesize) { rx_buff->data[rx_buff->len++] = byte; #ifndef POSTPONE_RX_CRC rx_buff->fcs = irda_fcs(rx_buff->fcs, byte); #endif } else { IRDA_DEBUG(1, "%s(), Rx buffer overflow, aborting\n", __func__); rx_buff->state = OUTSIDE_FRAME; } break; case LINK_ESCAPE: /* * Stuffed char, complement bit 5 of byte * following CE, IrLAP p.114 */ byte ^= IRDA_TRANS; if (rx_buff->len < rx_buff->truesize) { rx_buff->data[rx_buff->len++] = byte; #ifndef POSTPONE_RX_CRC rx_buff->fcs = irda_fcs(rx_buff->fcs, byte); #endif rx_buff->state = INSIDE_FRAME; } else { IRDA_DEBUG(1, "%s(), Rx buffer overflow, aborting\n", __func__); rx_buff->state = OUTSIDE_FRAME; } break; case OUTSIDE_FRAME: /* Activate carrier sense */ if(byte != XBOF) irda_device_set_media_busy(dev, TRUE); break; case BEGIN_FRAME: default: rx_buff->data[rx_buff->len++] = byte; #ifndef POSTPONE_RX_CRC rx_buff->fcs = irda_fcs(rx_buff->fcs, byte); #endif rx_buff->state = INSIDE_FRAME; break; } } /* * Function async_unwrap_char (dev, rx_buff, byte) * * Parse and de-stuff frame received from the IrDA-port * * This is the main entry point for SIR drivers. */ void async_unwrap_char(struct net_device *dev, struct net_device_stats *stats, iobuff_t *rx_buff, __u8 byte) { switch(byte) { case CE: async_unwrap_ce(dev, stats, rx_buff, byte); break; case BOF: async_unwrap_bof(dev, stats, rx_buff, byte); break; case EOF: async_unwrap_eof(dev, stats, rx_buff, byte); break; default: async_unwrap_other(dev, stats, rx_buff, byte); break; } } EXPORT_SYMBOL(async_unwrap_char);
gpl-2.0
honeyx/S3mini_golden_kernel
drivers/usb/wusbcore/dev-sysfs.c
13272
3852
/* * WUSB devices * sysfs bindings * * Copyright (C) 2007 Intel Corporation * Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.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 Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Get them out of the way... */ #include <linux/jiffies.h> #include <linux/ctype.h> #include <linux/workqueue.h> #include "wusbhc.h" static ssize_t wusb_disconnect_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { struct usb_device *usb_dev; struct wusbhc *wusbhc; unsigned command; u8 port_idx; if (sscanf(buf, "%u", &command) != 1) return -EINVAL; if (command == 0) return size; usb_dev = to_usb_device(dev); wusbhc = wusbhc_get_by_usb_dev(usb_dev); if (wusbhc == NULL) return -ENODEV; mutex_lock(&wusbhc->mutex); port_idx = wusb_port_no_to_idx(usb_dev->portnum); __wusbhc_dev_disable(wusbhc, port_idx); mutex_unlock(&wusbhc->mutex); wusbhc_put(wusbhc); return size; } static DEVICE_ATTR(wusb_disconnect, 0200, NULL, wusb_disconnect_store); static ssize_t wusb_cdid_show(struct device *dev, struct device_attribute *attr, char *buf) { ssize_t result; struct wusb_dev *wusb_dev; wusb_dev = wusb_dev_get_by_usb_dev(to_usb_device(dev)); if (wusb_dev == NULL) return -ENODEV; result = ckhdid_printf(buf, PAGE_SIZE, &wusb_dev->cdid); strcat(buf, "\n"); wusb_dev_put(wusb_dev); return result + 1; } static DEVICE_ATTR(wusb_cdid, 0444, wusb_cdid_show, NULL); static ssize_t wusb_ck_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { int result; struct usb_device *usb_dev; struct wusbhc *wusbhc; struct wusb_ckhdid ck; result = sscanf(buf, "%02hhx %02hhx %02hhx %02hhx " "%02hhx %02hhx %02hhx %02hhx " "%02hhx %02hhx %02hhx %02hhx " "%02hhx %02hhx %02hhx %02hhx\n", &ck.data[0] , &ck.data[1], &ck.data[2] , &ck.data[3], &ck.data[4] , &ck.data[5], &ck.data[6] , &ck.data[7], &ck.data[8] , &ck.data[9], &ck.data[10], &ck.data[11], &ck.data[12], &ck.data[13], &ck.data[14], &ck.data[15]); if (result != 16) return -EINVAL; usb_dev = to_usb_device(dev); wusbhc = wusbhc_get_by_usb_dev(usb_dev); if (wusbhc == NULL) return -ENODEV; result = wusb_dev_4way_handshake(wusbhc, usb_dev->wusb_dev, &ck); memset(&ck, 0, sizeof(ck)); wusbhc_put(wusbhc); return result < 0 ? result : size; } static DEVICE_ATTR(wusb_ck, 0200, NULL, wusb_ck_store); static struct attribute *wusb_dev_attrs[] = { &dev_attr_wusb_disconnect.attr, &dev_attr_wusb_cdid.attr, &dev_attr_wusb_ck.attr, NULL, }; static struct attribute_group wusb_dev_attr_group = { .name = NULL, /* we want them in the same directory */ .attrs = wusb_dev_attrs, }; int wusb_dev_sysfs_add(struct wusbhc *wusbhc, struct usb_device *usb_dev, struct wusb_dev *wusb_dev) { int result = sysfs_create_group(&usb_dev->dev.kobj, &wusb_dev_attr_group); struct device *dev = &usb_dev->dev; if (result < 0) dev_err(dev, "Cannot register WUSB-dev attributes: %d\n", result); return result; } void wusb_dev_sysfs_rm(struct wusb_dev *wusb_dev) { struct usb_device *usb_dev = wusb_dev->usb_dev; if (usb_dev) sysfs_remove_group(&usb_dev->dev.kobj, &wusb_dev_attr_group); }
gpl-2.0
SM-G920P/SM-N920
drivers/gpu/arm/t72x/r5p0/mali_kbase_sync_user.c
217
3338
/* * * (C) COPYRIGHT ARM Limited. All rights reserved. * * This program is free software and is provided to you under the terms of the * GNU General Public License version 2 as published by the Free Software * Foundation, and any use by you of this program is subject to the terms * of such GNU licence. * * A copy of the licence is included with the program, and can also be obtained * from Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ /** * @file mali_kbase_sync_user.c * */ #ifdef CONFIG_SYNC #include <linux/sched.h> #include <linux/fdtable.h> #include <linux/file.h> #include <linux/fs.h> #include <linux/module.h> #include <linux/anon_inodes.h> #include <linux/version.h> #include <linux/uaccess.h> #include <mali_kbase_sync.h> #include <mali_base_kernel_sync.h> static int kbase_stream_close(struct inode *inode, struct file *file) { struct sync_timeline *tl; tl = (struct sync_timeline *)file->private_data; #if SLSI_INTEGRATION /* MALI_SEC */ if (file->private_data == NULL) return 0; if (atomic_read(&tl->kref.refcount) == 1) file->private_data = NULL; #else BUG_ON(!tl); #endif sync_timeline_destroy(tl); return 0; } static const struct file_operations stream_fops = { .owner = THIS_MODULE, .release = kbase_stream_close, }; mali_error kbase_stream_create(const char *name, int *const out_fd) { struct sync_timeline *tl; BUG_ON(!out_fd); tl = kbase_sync_timeline_alloc(name); if (!tl) return MALI_ERROR_FUNCTION_FAILED; *out_fd = anon_inode_getfd(name, &stream_fops, tl, O_RDONLY | O_CLOEXEC); if (*out_fd < 0) { sync_timeline_destroy(tl); return MALI_ERROR_FUNCTION_FAILED; } else { return MALI_ERROR_NONE; } } int kbase_stream_create_fence(int tl_fd) { struct sync_timeline *tl; struct sync_pt *pt; struct sync_fence *fence; #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 7, 0) struct files_struct *files; struct fdtable *fdt; #endif int fd; struct file *tl_file; tl_file = fget(tl_fd); if (tl_file == NULL) return -EBADF; if (tl_file->f_op != &stream_fops) { fd = -EBADF; goto out; } tl = tl_file->private_data; pt = kbase_sync_pt_alloc(tl); if (!pt) { fd = -EFAULT; goto out; } fence = sync_fence_create("mali_fence", pt); if (!fence) { sync_pt_free(pt); fd = -EFAULT; goto out; } /* from here the fence owns the sync_pt */ /* create a fd representing the fence */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 7, 0) fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC); if (fd < 0) { sync_fence_put(fence); goto out; } #else fd = get_unused_fd(); if (fd < 0) { sync_fence_put(fence); goto out; } files = current->files; spin_lock(&files->file_lock); fdt = files_fdtable(files); #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 4, 0) __set_close_on_exec(fd, fdt); #else FD_SET(fd, fdt->close_on_exec); #endif spin_unlock(&files->file_lock); #endif /* LINUX_VERSION_CODE >= KERNEL_VERSION(3, 7, 0) */ /* bind fence to the new fd */ sync_fence_install(fence, fd); out: fput(tl_file); return fd; } mali_error kbase_fence_validate(int fd) { struct sync_fence *fence; fence = sync_fence_fdget(fd); if (NULL != fence) { sync_fence_put(fence); return MALI_ERROR_NONE; } else { return MALI_ERROR_FUNCTION_FAILED; } } #endif /* CONFIG_SYNC */
gpl-2.0
amarchandole/capprobe_mptcp
drivers/block/drbd/drbd_main.c
217
111093
/* drbd.c This file is part of DRBD by Philipp Reisner and Lars Ellenberg. Copyright (C) 2001-2008, LINBIT Information Technologies GmbH. Copyright (C) 1999-2008, Philipp Reisner <philipp.reisner@linbit.com>. Copyright (C) 2002-2008, Lars Ellenberg <lars.ellenberg@linbit.com>. Thanks to Carter Burden, Bart Grantham and Gennadiy Nerubayev from Logicworks, Inc. for making SDP replication support possible. drbd 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. drbd 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 drbd; see the file COPYING. If not, write to the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/jiffies.h> #include <linux/drbd.h> #include <asm/uaccess.h> #include <asm/types.h> #include <net/sock.h> #include <linux/ctype.h> #include <linux/mutex.h> #include <linux/fs.h> #include <linux/file.h> #include <linux/proc_fs.h> #include <linux/init.h> #include <linux/mm.h> #include <linux/memcontrol.h> #include <linux/mm_inline.h> #include <linux/slab.h> #include <linux/random.h> #include <linux/reboot.h> #include <linux/notifier.h> #include <linux/kthread.h> #include <linux/workqueue.h> #define __KERNEL_SYSCALLS__ #include <linux/unistd.h> #include <linux/vmalloc.h> #include <linux/drbd_limits.h> #include "drbd_int.h" #include "drbd_protocol.h" #include "drbd_req.h" /* only for _req_mod in tl_release and tl_clear */ #include "drbd_vli.h" #include "drbd_debugfs.h" static DEFINE_MUTEX(drbd_main_mutex); static int drbd_open(struct block_device *bdev, fmode_t mode); static void drbd_release(struct gendisk *gd, fmode_t mode); static void md_sync_timer_fn(unsigned long data); static int w_bitmap_io(struct drbd_work *w, int unused); MODULE_AUTHOR("Philipp Reisner <phil@linbit.com>, " "Lars Ellenberg <lars@linbit.com>"); MODULE_DESCRIPTION("drbd - Distributed Replicated Block Device v" REL_VERSION); MODULE_VERSION(REL_VERSION); MODULE_LICENSE("GPL"); MODULE_PARM_DESC(minor_count, "Approximate number of drbd devices (" __stringify(DRBD_MINOR_COUNT_MIN) "-" __stringify(DRBD_MINOR_COUNT_MAX) ")"); MODULE_ALIAS_BLOCKDEV_MAJOR(DRBD_MAJOR); #include <linux/moduleparam.h> /* allow_open_on_secondary */ MODULE_PARM_DESC(allow_oos, "DONT USE!"); /* thanks to these macros, if compiled into the kernel (not-module), * this becomes the boot parameter drbd.minor_count */ module_param(minor_count, uint, 0444); module_param(disable_sendpage, bool, 0644); module_param(allow_oos, bool, 0); module_param(proc_details, int, 0644); #ifdef CONFIG_DRBD_FAULT_INJECTION int enable_faults; int fault_rate; static int fault_count; int fault_devs; /* bitmap of enabled faults */ module_param(enable_faults, int, 0664); /* fault rate % value - applies to all enabled faults */ module_param(fault_rate, int, 0664); /* count of faults inserted */ module_param(fault_count, int, 0664); /* bitmap of devices to insert faults on */ module_param(fault_devs, int, 0644); #endif /* module parameter, defined */ unsigned int minor_count = DRBD_MINOR_COUNT_DEF; bool disable_sendpage; bool allow_oos; int proc_details; /* Detail level in proc drbd*/ /* Module parameter for setting the user mode helper program * to run. Default is /sbin/drbdadm */ char usermode_helper[80] = "/sbin/drbdadm"; module_param_string(usermode_helper, usermode_helper, sizeof(usermode_helper), 0644); /* in 2.6.x, our device mapping and config info contains our virtual gendisks * as member "struct gendisk *vdisk;" */ struct idr drbd_devices; struct list_head drbd_resources; struct kmem_cache *drbd_request_cache; struct kmem_cache *drbd_ee_cache; /* peer requests */ struct kmem_cache *drbd_bm_ext_cache; /* bitmap extents */ struct kmem_cache *drbd_al_ext_cache; /* activity log extents */ mempool_t *drbd_request_mempool; mempool_t *drbd_ee_mempool; mempool_t *drbd_md_io_page_pool; struct bio_set *drbd_md_io_bio_set; /* I do not use a standard mempool, because: 1) I want to hand out the pre-allocated objects first. 2) I want to be able to interrupt sleeping allocation with a signal. Note: This is a single linked list, the next pointer is the private member of struct page. */ struct page *drbd_pp_pool; spinlock_t drbd_pp_lock; int drbd_pp_vacant; wait_queue_head_t drbd_pp_wait; DEFINE_RATELIMIT_STATE(drbd_ratelimit_state, 5 * HZ, 5); static const struct block_device_operations drbd_ops = { .owner = THIS_MODULE, .open = drbd_open, .release = drbd_release, }; struct bio *bio_alloc_drbd(gfp_t gfp_mask) { struct bio *bio; if (!drbd_md_io_bio_set) return bio_alloc(gfp_mask, 1); bio = bio_alloc_bioset(gfp_mask, 1, drbd_md_io_bio_set); if (!bio) return NULL; return bio; } #ifdef __CHECKER__ /* When checking with sparse, and this is an inline function, sparse will give tons of false positives. When this is a real functions sparse works. */ int _get_ldev_if_state(struct drbd_device *device, enum drbd_disk_state mins) { int io_allowed; atomic_inc(&device->local_cnt); io_allowed = (device->state.disk >= mins); if (!io_allowed) { if (atomic_dec_and_test(&device->local_cnt)) wake_up(&device->misc_wait); } return io_allowed; } #endif /** * tl_release() - mark as BARRIER_ACKED all requests in the corresponding transfer log epoch * @connection: DRBD connection. * @barrier_nr: Expected identifier of the DRBD write barrier packet. * @set_size: Expected number of requests before that barrier. * * In case the passed barrier_nr or set_size does not match the oldest * epoch of not yet barrier-acked requests, this function will cause a * termination of the connection. */ void tl_release(struct drbd_connection *connection, unsigned int barrier_nr, unsigned int set_size) { struct drbd_request *r; struct drbd_request *req = NULL; int expect_epoch = 0; int expect_size = 0; spin_lock_irq(&connection->resource->req_lock); /* find oldest not yet barrier-acked write request, * count writes in its epoch. */ list_for_each_entry(r, &connection->transfer_log, tl_requests) { const unsigned s = r->rq_state; if (!req) { if (!(s & RQ_WRITE)) continue; if (!(s & RQ_NET_MASK)) continue; if (s & RQ_NET_DONE) continue; req = r; expect_epoch = req->epoch; expect_size ++; } else { if (r->epoch != expect_epoch) break; if (!(s & RQ_WRITE)) continue; /* if (s & RQ_DONE): not expected */ /* if (!(s & RQ_NET_MASK)): not expected */ expect_size++; } } /* first some paranoia code */ if (req == NULL) { drbd_err(connection, "BAD! BarrierAck #%u received, but no epoch in tl!?\n", barrier_nr); goto bail; } if (expect_epoch != barrier_nr) { drbd_err(connection, "BAD! BarrierAck #%u received, expected #%u!\n", barrier_nr, expect_epoch); goto bail; } if (expect_size != set_size) { drbd_err(connection, "BAD! BarrierAck #%u received with n_writes=%u, expected n_writes=%u!\n", barrier_nr, set_size, expect_size); goto bail; } /* Clean up list of requests processed during current epoch. */ /* this extra list walk restart is paranoia, * to catch requests being barrier-acked "unexpectedly". * It usually should find the same req again, or some READ preceding it. */ list_for_each_entry(req, &connection->transfer_log, tl_requests) if (req->epoch == expect_epoch) break; list_for_each_entry_safe_from(req, r, &connection->transfer_log, tl_requests) { if (req->epoch != expect_epoch) break; _req_mod(req, BARRIER_ACKED); } spin_unlock_irq(&connection->resource->req_lock); return; bail: spin_unlock_irq(&connection->resource->req_lock); conn_request_state(connection, NS(conn, C_PROTOCOL_ERROR), CS_HARD); } /** * _tl_restart() - Walks the transfer log, and applies an action to all requests * @connection: DRBD connection to operate on. * @what: The action/event to perform with all request objects * * @what might be one of CONNECTION_LOST_WHILE_PENDING, RESEND, FAIL_FROZEN_DISK_IO, * RESTART_FROZEN_DISK_IO. */ /* must hold resource->req_lock */ void _tl_restart(struct drbd_connection *connection, enum drbd_req_event what) { struct drbd_request *req, *r; list_for_each_entry_safe(req, r, &connection->transfer_log, tl_requests) _req_mod(req, what); } void tl_restart(struct drbd_connection *connection, enum drbd_req_event what) { spin_lock_irq(&connection->resource->req_lock); _tl_restart(connection, what); spin_unlock_irq(&connection->resource->req_lock); } /** * tl_clear() - Clears all requests and &struct drbd_tl_epoch objects out of the TL * @device: DRBD device. * * This is called after the connection to the peer was lost. The storage covered * by the requests on the transfer gets marked as our of sync. Called from the * receiver thread and the worker thread. */ void tl_clear(struct drbd_connection *connection) { tl_restart(connection, CONNECTION_LOST_WHILE_PENDING); } /** * tl_abort_disk_io() - Abort disk I/O for all requests for a certain device in the TL * @device: DRBD device. */ void tl_abort_disk_io(struct drbd_device *device) { struct drbd_connection *connection = first_peer_device(device)->connection; struct drbd_request *req, *r; spin_lock_irq(&connection->resource->req_lock); list_for_each_entry_safe(req, r, &connection->transfer_log, tl_requests) { if (!(req->rq_state & RQ_LOCAL_PENDING)) continue; if (req->device != device) continue; _req_mod(req, ABORT_DISK_IO); } spin_unlock_irq(&connection->resource->req_lock); } static int drbd_thread_setup(void *arg) { struct drbd_thread *thi = (struct drbd_thread *) arg; struct drbd_resource *resource = thi->resource; unsigned long flags; int retval; snprintf(current->comm, sizeof(current->comm), "drbd_%c_%s", thi->name[0], resource->name); restart: retval = thi->function(thi); spin_lock_irqsave(&thi->t_lock, flags); /* if the receiver has been "EXITING", the last thing it did * was set the conn state to "StandAlone", * if now a re-connect request comes in, conn state goes C_UNCONNECTED, * and receiver thread will be "started". * drbd_thread_start needs to set "RESTARTING" in that case. * t_state check and assignment needs to be within the same spinlock, * so either thread_start sees EXITING, and can remap to RESTARTING, * or thread_start see NONE, and can proceed as normal. */ if (thi->t_state == RESTARTING) { drbd_info(resource, "Restarting %s thread\n", thi->name); thi->t_state = RUNNING; spin_unlock_irqrestore(&thi->t_lock, flags); goto restart; } thi->task = NULL; thi->t_state = NONE; smp_mb(); complete_all(&thi->stop); spin_unlock_irqrestore(&thi->t_lock, flags); drbd_info(resource, "Terminating %s\n", current->comm); /* Release mod reference taken when thread was started */ if (thi->connection) kref_put(&thi->connection->kref, drbd_destroy_connection); kref_put(&resource->kref, drbd_destroy_resource); module_put(THIS_MODULE); return retval; } static void drbd_thread_init(struct drbd_resource *resource, struct drbd_thread *thi, int (*func) (struct drbd_thread *), const char *name) { spin_lock_init(&thi->t_lock); thi->task = NULL; thi->t_state = NONE; thi->function = func; thi->resource = resource; thi->connection = NULL; thi->name = name; } int drbd_thread_start(struct drbd_thread *thi) { struct drbd_resource *resource = thi->resource; struct task_struct *nt; unsigned long flags; /* is used from state engine doing drbd_thread_stop_nowait, * while holding the req lock irqsave */ spin_lock_irqsave(&thi->t_lock, flags); switch (thi->t_state) { case NONE: drbd_info(resource, "Starting %s thread (from %s [%d])\n", thi->name, current->comm, current->pid); /* Get ref on module for thread - this is released when thread exits */ if (!try_module_get(THIS_MODULE)) { drbd_err(resource, "Failed to get module reference in drbd_thread_start\n"); spin_unlock_irqrestore(&thi->t_lock, flags); return false; } kref_get(&resource->kref); if (thi->connection) kref_get(&thi->connection->kref); init_completion(&thi->stop); thi->reset_cpu_mask = 1; thi->t_state = RUNNING; spin_unlock_irqrestore(&thi->t_lock, flags); flush_signals(current); /* otherw. may get -ERESTARTNOINTR */ nt = kthread_create(drbd_thread_setup, (void *) thi, "drbd_%c_%s", thi->name[0], thi->resource->name); if (IS_ERR(nt)) { drbd_err(resource, "Couldn't start thread\n"); if (thi->connection) kref_put(&thi->connection->kref, drbd_destroy_connection); kref_put(&resource->kref, drbd_destroy_resource); module_put(THIS_MODULE); return false; } spin_lock_irqsave(&thi->t_lock, flags); thi->task = nt; thi->t_state = RUNNING; spin_unlock_irqrestore(&thi->t_lock, flags); wake_up_process(nt); break; case EXITING: thi->t_state = RESTARTING; drbd_info(resource, "Restarting %s thread (from %s [%d])\n", thi->name, current->comm, current->pid); /* fall through */ case RUNNING: case RESTARTING: default: spin_unlock_irqrestore(&thi->t_lock, flags); break; } return true; } void _drbd_thread_stop(struct drbd_thread *thi, int restart, int wait) { unsigned long flags; enum drbd_thread_state ns = restart ? RESTARTING : EXITING; /* may be called from state engine, holding the req lock irqsave */ spin_lock_irqsave(&thi->t_lock, flags); if (thi->t_state == NONE) { spin_unlock_irqrestore(&thi->t_lock, flags); if (restart) drbd_thread_start(thi); return; } if (thi->t_state != ns) { if (thi->task == NULL) { spin_unlock_irqrestore(&thi->t_lock, flags); return; } thi->t_state = ns; smp_mb(); init_completion(&thi->stop); if (thi->task != current) force_sig(DRBD_SIGKILL, thi->task); } spin_unlock_irqrestore(&thi->t_lock, flags); if (wait) wait_for_completion(&thi->stop); } int conn_lowest_minor(struct drbd_connection *connection) { struct drbd_peer_device *peer_device; int vnr = 0, minor = -1; rcu_read_lock(); peer_device = idr_get_next(&connection->peer_devices, &vnr); if (peer_device) minor = device_to_minor(peer_device->device); rcu_read_unlock(); return minor; } #ifdef CONFIG_SMP /** * drbd_calc_cpu_mask() - Generate CPU masks, spread over all CPUs * * Forces all threads of a resource onto the same CPU. This is beneficial for * DRBD's performance. May be overwritten by user's configuration. */ static void drbd_calc_cpu_mask(cpumask_var_t *cpu_mask) { unsigned int *resources_per_cpu, min_index = ~0; resources_per_cpu = kzalloc(nr_cpu_ids * sizeof(*resources_per_cpu), GFP_KERNEL); if (resources_per_cpu) { struct drbd_resource *resource; unsigned int cpu, min = ~0; rcu_read_lock(); for_each_resource_rcu(resource, &drbd_resources) { for_each_cpu(cpu, resource->cpu_mask) resources_per_cpu[cpu]++; } rcu_read_unlock(); for_each_online_cpu(cpu) { if (resources_per_cpu[cpu] < min) { min = resources_per_cpu[cpu]; min_index = cpu; } } kfree(resources_per_cpu); } if (min_index == ~0) { cpumask_setall(*cpu_mask); return; } cpumask_set_cpu(min_index, *cpu_mask); } /** * drbd_thread_current_set_cpu() - modifies the cpu mask of the _current_ thread * @device: DRBD device. * @thi: drbd_thread object * * call in the "main loop" of _all_ threads, no need for any mutex, current won't die * prematurely. */ void drbd_thread_current_set_cpu(struct drbd_thread *thi) { struct drbd_resource *resource = thi->resource; struct task_struct *p = current; if (!thi->reset_cpu_mask) return; thi->reset_cpu_mask = 0; set_cpus_allowed_ptr(p, resource->cpu_mask); } #else #define drbd_calc_cpu_mask(A) ({}) #endif /** * drbd_header_size - size of a packet header * * The header size is a multiple of 8, so any payload following the header is * word aligned on 64-bit architectures. (The bitmap send and receive code * relies on this.) */ unsigned int drbd_header_size(struct drbd_connection *connection) { if (connection->agreed_pro_version >= 100) { BUILD_BUG_ON(!IS_ALIGNED(sizeof(struct p_header100), 8)); return sizeof(struct p_header100); } else { BUILD_BUG_ON(sizeof(struct p_header80) != sizeof(struct p_header95)); BUILD_BUG_ON(!IS_ALIGNED(sizeof(struct p_header80), 8)); return sizeof(struct p_header80); } } static unsigned int prepare_header80(struct p_header80 *h, enum drbd_packet cmd, int size) { h->magic = cpu_to_be32(DRBD_MAGIC); h->command = cpu_to_be16(cmd); h->length = cpu_to_be16(size); return sizeof(struct p_header80); } static unsigned int prepare_header95(struct p_header95 *h, enum drbd_packet cmd, int size) { h->magic = cpu_to_be16(DRBD_MAGIC_BIG); h->command = cpu_to_be16(cmd); h->length = cpu_to_be32(size); return sizeof(struct p_header95); } static unsigned int prepare_header100(struct p_header100 *h, enum drbd_packet cmd, int size, int vnr) { h->magic = cpu_to_be32(DRBD_MAGIC_100); h->volume = cpu_to_be16(vnr); h->command = cpu_to_be16(cmd); h->length = cpu_to_be32(size); h->pad = 0; return sizeof(struct p_header100); } static unsigned int prepare_header(struct drbd_connection *connection, int vnr, void *buffer, enum drbd_packet cmd, int size) { if (connection->agreed_pro_version >= 100) return prepare_header100(buffer, cmd, size, vnr); else if (connection->agreed_pro_version >= 95 && size > DRBD_MAX_SIZE_H80_PACKET) return prepare_header95(buffer, cmd, size); else return prepare_header80(buffer, cmd, size); } static void *__conn_prepare_command(struct drbd_connection *connection, struct drbd_socket *sock) { if (!sock->socket) return NULL; return sock->sbuf + drbd_header_size(connection); } void *conn_prepare_command(struct drbd_connection *connection, struct drbd_socket *sock) { void *p; mutex_lock(&sock->mutex); p = __conn_prepare_command(connection, sock); if (!p) mutex_unlock(&sock->mutex); return p; } void *drbd_prepare_command(struct drbd_peer_device *peer_device, struct drbd_socket *sock) { return conn_prepare_command(peer_device->connection, sock); } static int __send_command(struct drbd_connection *connection, int vnr, struct drbd_socket *sock, enum drbd_packet cmd, unsigned int header_size, void *data, unsigned int size) { int msg_flags; int err; /* * Called with @data == NULL and the size of the data blocks in @size * for commands that send data blocks. For those commands, omit the * MSG_MORE flag: this will increase the likelihood that data blocks * which are page aligned on the sender will end up page aligned on the * receiver. */ msg_flags = data ? MSG_MORE : 0; header_size += prepare_header(connection, vnr, sock->sbuf, cmd, header_size + size); err = drbd_send_all(connection, sock->socket, sock->sbuf, header_size, msg_flags); if (data && !err) err = drbd_send_all(connection, sock->socket, data, size, 0); /* DRBD protocol "pings" are latency critical. * This is supposed to trigger tcp_push_pending_frames() */ if (!err && (cmd == P_PING || cmd == P_PING_ACK)) drbd_tcp_nodelay(sock->socket); return err; } static int __conn_send_command(struct drbd_connection *connection, struct drbd_socket *sock, enum drbd_packet cmd, unsigned int header_size, void *data, unsigned int size) { return __send_command(connection, 0, sock, cmd, header_size, data, size); } int conn_send_command(struct drbd_connection *connection, struct drbd_socket *sock, enum drbd_packet cmd, unsigned int header_size, void *data, unsigned int size) { int err; err = __conn_send_command(connection, sock, cmd, header_size, data, size); mutex_unlock(&sock->mutex); return err; } int drbd_send_command(struct drbd_peer_device *peer_device, struct drbd_socket *sock, enum drbd_packet cmd, unsigned int header_size, void *data, unsigned int size) { int err; err = __send_command(peer_device->connection, peer_device->device->vnr, sock, cmd, header_size, data, size); mutex_unlock(&sock->mutex); return err; } int drbd_send_ping(struct drbd_connection *connection) { struct drbd_socket *sock; sock = &connection->meta; if (!conn_prepare_command(connection, sock)) return -EIO; return conn_send_command(connection, sock, P_PING, 0, NULL, 0); } int drbd_send_ping_ack(struct drbd_connection *connection) { struct drbd_socket *sock; sock = &connection->meta; if (!conn_prepare_command(connection, sock)) return -EIO; return conn_send_command(connection, sock, P_PING_ACK, 0, NULL, 0); } int drbd_send_sync_param(struct drbd_peer_device *peer_device) { struct drbd_socket *sock; struct p_rs_param_95 *p; int size; const int apv = peer_device->connection->agreed_pro_version; enum drbd_packet cmd; struct net_conf *nc; struct disk_conf *dc; sock = &peer_device->connection->data; p = drbd_prepare_command(peer_device, sock); if (!p) return -EIO; rcu_read_lock(); nc = rcu_dereference(peer_device->connection->net_conf); size = apv <= 87 ? sizeof(struct p_rs_param) : apv == 88 ? sizeof(struct p_rs_param) + strlen(nc->verify_alg) + 1 : apv <= 94 ? sizeof(struct p_rs_param_89) : /* apv >= 95 */ sizeof(struct p_rs_param_95); cmd = apv >= 89 ? P_SYNC_PARAM89 : P_SYNC_PARAM; /* initialize verify_alg and csums_alg */ memset(p->verify_alg, 0, 2 * SHARED_SECRET_MAX); if (get_ldev(peer_device->device)) { dc = rcu_dereference(peer_device->device->ldev->disk_conf); p->resync_rate = cpu_to_be32(dc->resync_rate); p->c_plan_ahead = cpu_to_be32(dc->c_plan_ahead); p->c_delay_target = cpu_to_be32(dc->c_delay_target); p->c_fill_target = cpu_to_be32(dc->c_fill_target); p->c_max_rate = cpu_to_be32(dc->c_max_rate); put_ldev(peer_device->device); } else { p->resync_rate = cpu_to_be32(DRBD_RESYNC_RATE_DEF); p->c_plan_ahead = cpu_to_be32(DRBD_C_PLAN_AHEAD_DEF); p->c_delay_target = cpu_to_be32(DRBD_C_DELAY_TARGET_DEF); p->c_fill_target = cpu_to_be32(DRBD_C_FILL_TARGET_DEF); p->c_max_rate = cpu_to_be32(DRBD_C_MAX_RATE_DEF); } if (apv >= 88) strcpy(p->verify_alg, nc->verify_alg); if (apv >= 89) strcpy(p->csums_alg, nc->csums_alg); rcu_read_unlock(); return drbd_send_command(peer_device, sock, cmd, size, NULL, 0); } int __drbd_send_protocol(struct drbd_connection *connection, enum drbd_packet cmd) { struct drbd_socket *sock; struct p_protocol *p; struct net_conf *nc; int size, cf; sock = &connection->data; p = __conn_prepare_command(connection, sock); if (!p) return -EIO; rcu_read_lock(); nc = rcu_dereference(connection->net_conf); if (nc->tentative && connection->agreed_pro_version < 92) { rcu_read_unlock(); mutex_unlock(&sock->mutex); drbd_err(connection, "--dry-run is not supported by peer"); return -EOPNOTSUPP; } size = sizeof(*p); if (connection->agreed_pro_version >= 87) size += strlen(nc->integrity_alg) + 1; p->protocol = cpu_to_be32(nc->wire_protocol); p->after_sb_0p = cpu_to_be32(nc->after_sb_0p); p->after_sb_1p = cpu_to_be32(nc->after_sb_1p); p->after_sb_2p = cpu_to_be32(nc->after_sb_2p); p->two_primaries = cpu_to_be32(nc->two_primaries); cf = 0; if (nc->discard_my_data) cf |= CF_DISCARD_MY_DATA; if (nc->tentative) cf |= CF_DRY_RUN; p->conn_flags = cpu_to_be32(cf); if (connection->agreed_pro_version >= 87) strcpy(p->integrity_alg, nc->integrity_alg); rcu_read_unlock(); return __conn_send_command(connection, sock, cmd, size, NULL, 0); } int drbd_send_protocol(struct drbd_connection *connection) { int err; mutex_lock(&connection->data.mutex); err = __drbd_send_protocol(connection, P_PROTOCOL); mutex_unlock(&connection->data.mutex); return err; } static int _drbd_send_uuids(struct drbd_peer_device *peer_device, u64 uuid_flags) { struct drbd_device *device = peer_device->device; struct drbd_socket *sock; struct p_uuids *p; int i; if (!get_ldev_if_state(device, D_NEGOTIATING)) return 0; sock = &peer_device->connection->data; p = drbd_prepare_command(peer_device, sock); if (!p) { put_ldev(device); return -EIO; } spin_lock_irq(&device->ldev->md.uuid_lock); for (i = UI_CURRENT; i < UI_SIZE; i++) p->uuid[i] = cpu_to_be64(device->ldev->md.uuid[i]); spin_unlock_irq(&device->ldev->md.uuid_lock); device->comm_bm_set = drbd_bm_total_weight(device); p->uuid[UI_SIZE] = cpu_to_be64(device->comm_bm_set); rcu_read_lock(); uuid_flags |= rcu_dereference(peer_device->connection->net_conf)->discard_my_data ? 1 : 0; rcu_read_unlock(); uuid_flags |= test_bit(CRASHED_PRIMARY, &device->flags) ? 2 : 0; uuid_flags |= device->new_state_tmp.disk == D_INCONSISTENT ? 4 : 0; p->uuid[UI_FLAGS] = cpu_to_be64(uuid_flags); put_ldev(device); return drbd_send_command(peer_device, sock, P_UUIDS, sizeof(*p), NULL, 0); } int drbd_send_uuids(struct drbd_peer_device *peer_device) { return _drbd_send_uuids(peer_device, 0); } int drbd_send_uuids_skip_initial_sync(struct drbd_peer_device *peer_device) { return _drbd_send_uuids(peer_device, 8); } void drbd_print_uuids(struct drbd_device *device, const char *text) { if (get_ldev_if_state(device, D_NEGOTIATING)) { u64 *uuid = device->ldev->md.uuid; drbd_info(device, "%s %016llX:%016llX:%016llX:%016llX\n", text, (unsigned long long)uuid[UI_CURRENT], (unsigned long long)uuid[UI_BITMAP], (unsigned long long)uuid[UI_HISTORY_START], (unsigned long long)uuid[UI_HISTORY_END]); put_ldev(device); } else { drbd_info(device, "%s effective data uuid: %016llX\n", text, (unsigned long long)device->ed_uuid); } } void drbd_gen_and_send_sync_uuid(struct drbd_peer_device *peer_device) { struct drbd_device *device = peer_device->device; struct drbd_socket *sock; struct p_rs_uuid *p; u64 uuid; D_ASSERT(device, device->state.disk == D_UP_TO_DATE); uuid = device->ldev->md.uuid[UI_BITMAP]; if (uuid && uuid != UUID_JUST_CREATED) uuid = uuid + UUID_NEW_BM_OFFSET; else get_random_bytes(&uuid, sizeof(u64)); drbd_uuid_set(device, UI_BITMAP, uuid); drbd_print_uuids(device, "updated sync UUID"); drbd_md_sync(device); sock = &peer_device->connection->data; p = drbd_prepare_command(peer_device, sock); if (p) { p->uuid = cpu_to_be64(uuid); drbd_send_command(peer_device, sock, P_SYNC_UUID, sizeof(*p), NULL, 0); } } int drbd_send_sizes(struct drbd_peer_device *peer_device, int trigger_reply, enum dds_flags flags) { struct drbd_device *device = peer_device->device; struct drbd_socket *sock; struct p_sizes *p; sector_t d_size, u_size; int q_order_type; unsigned int max_bio_size; if (get_ldev_if_state(device, D_NEGOTIATING)) { D_ASSERT(device, device->ldev->backing_bdev); d_size = drbd_get_max_capacity(device->ldev); rcu_read_lock(); u_size = rcu_dereference(device->ldev->disk_conf)->disk_size; rcu_read_unlock(); q_order_type = drbd_queue_order_type(device); max_bio_size = queue_max_hw_sectors(device->ldev->backing_bdev->bd_disk->queue) << 9; max_bio_size = min(max_bio_size, DRBD_MAX_BIO_SIZE); put_ldev(device); } else { d_size = 0; u_size = 0; q_order_type = QUEUE_ORDERED_NONE; max_bio_size = DRBD_MAX_BIO_SIZE; /* ... multiple BIOs per peer_request */ } sock = &peer_device->connection->data; p = drbd_prepare_command(peer_device, sock); if (!p) return -EIO; if (peer_device->connection->agreed_pro_version <= 94) max_bio_size = min(max_bio_size, DRBD_MAX_SIZE_H80_PACKET); else if (peer_device->connection->agreed_pro_version < 100) max_bio_size = min(max_bio_size, DRBD_MAX_BIO_SIZE_P95); p->d_size = cpu_to_be64(d_size); p->u_size = cpu_to_be64(u_size); p->c_size = cpu_to_be64(trigger_reply ? 0 : drbd_get_capacity(device->this_bdev)); p->max_bio_size = cpu_to_be32(max_bio_size); p->queue_order_type = cpu_to_be16(q_order_type); p->dds_flags = cpu_to_be16(flags); return drbd_send_command(peer_device, sock, P_SIZES, sizeof(*p), NULL, 0); } /** * drbd_send_current_state() - Sends the drbd state to the peer * @peer_device: DRBD peer device. */ int drbd_send_current_state(struct drbd_peer_device *peer_device) { struct drbd_socket *sock; struct p_state *p; sock = &peer_device->connection->data; p = drbd_prepare_command(peer_device, sock); if (!p) return -EIO; p->state = cpu_to_be32(peer_device->device->state.i); /* Within the send mutex */ return drbd_send_command(peer_device, sock, P_STATE, sizeof(*p), NULL, 0); } /** * drbd_send_state() - After a state change, sends the new state to the peer * @peer_device: DRBD peer device. * @state: the state to send, not necessarily the current state. * * Each state change queues an "after_state_ch" work, which will eventually * send the resulting new state to the peer. If more state changes happen * between queuing and processing of the after_state_ch work, we still * want to send each intermediary state in the order it occurred. */ int drbd_send_state(struct drbd_peer_device *peer_device, union drbd_state state) { struct drbd_socket *sock; struct p_state *p; sock = &peer_device->connection->data; p = drbd_prepare_command(peer_device, sock); if (!p) return -EIO; p->state = cpu_to_be32(state.i); /* Within the send mutex */ return drbd_send_command(peer_device, sock, P_STATE, sizeof(*p), NULL, 0); } int drbd_send_state_req(struct drbd_peer_device *peer_device, union drbd_state mask, union drbd_state val) { struct drbd_socket *sock; struct p_req_state *p; sock = &peer_device->connection->data; p = drbd_prepare_command(peer_device, sock); if (!p) return -EIO; p->mask = cpu_to_be32(mask.i); p->val = cpu_to_be32(val.i); return drbd_send_command(peer_device, sock, P_STATE_CHG_REQ, sizeof(*p), NULL, 0); } int conn_send_state_req(struct drbd_connection *connection, union drbd_state mask, union drbd_state val) { enum drbd_packet cmd; struct drbd_socket *sock; struct p_req_state *p; cmd = connection->agreed_pro_version < 100 ? P_STATE_CHG_REQ : P_CONN_ST_CHG_REQ; sock = &connection->data; p = conn_prepare_command(connection, sock); if (!p) return -EIO; p->mask = cpu_to_be32(mask.i); p->val = cpu_to_be32(val.i); return conn_send_command(connection, sock, cmd, sizeof(*p), NULL, 0); } void drbd_send_sr_reply(struct drbd_peer_device *peer_device, enum drbd_state_rv retcode) { struct drbd_socket *sock; struct p_req_state_reply *p; sock = &peer_device->connection->meta; p = drbd_prepare_command(peer_device, sock); if (p) { p->retcode = cpu_to_be32(retcode); drbd_send_command(peer_device, sock, P_STATE_CHG_REPLY, sizeof(*p), NULL, 0); } } void conn_send_sr_reply(struct drbd_connection *connection, enum drbd_state_rv retcode) { struct drbd_socket *sock; struct p_req_state_reply *p; enum drbd_packet cmd = connection->agreed_pro_version < 100 ? P_STATE_CHG_REPLY : P_CONN_ST_CHG_REPLY; sock = &connection->meta; p = conn_prepare_command(connection, sock); if (p) { p->retcode = cpu_to_be32(retcode); conn_send_command(connection, sock, cmd, sizeof(*p), NULL, 0); } } static void dcbp_set_code(struct p_compressed_bm *p, enum drbd_bitmap_code code) { BUG_ON(code & ~0xf); p->encoding = (p->encoding & ~0xf) | code; } static void dcbp_set_start(struct p_compressed_bm *p, int set) { p->encoding = (p->encoding & ~0x80) | (set ? 0x80 : 0); } static void dcbp_set_pad_bits(struct p_compressed_bm *p, int n) { BUG_ON(n & ~0x7); p->encoding = (p->encoding & (~0x7 << 4)) | (n << 4); } static int fill_bitmap_rle_bits(struct drbd_device *device, struct p_compressed_bm *p, unsigned int size, struct bm_xfer_ctx *c) { struct bitstream bs; unsigned long plain_bits; unsigned long tmp; unsigned long rl; unsigned len; unsigned toggle; int bits, use_rle; /* may we use this feature? */ rcu_read_lock(); use_rle = rcu_dereference(first_peer_device(device)->connection->net_conf)->use_rle; rcu_read_unlock(); if (!use_rle || first_peer_device(device)->connection->agreed_pro_version < 90) return 0; if (c->bit_offset >= c->bm_bits) return 0; /* nothing to do. */ /* use at most thus many bytes */ bitstream_init(&bs, p->code, size, 0); memset(p->code, 0, size); /* plain bits covered in this code string */ plain_bits = 0; /* p->encoding & 0x80 stores whether the first run length is set. * bit offset is implicit. * start with toggle == 2 to be able to tell the first iteration */ toggle = 2; /* see how much plain bits we can stuff into one packet * using RLE and VLI. */ do { tmp = (toggle == 0) ? _drbd_bm_find_next_zero(device, c->bit_offset) : _drbd_bm_find_next(device, c->bit_offset); if (tmp == -1UL) tmp = c->bm_bits; rl = tmp - c->bit_offset; if (toggle == 2) { /* first iteration */ if (rl == 0) { /* the first checked bit was set, * store start value, */ dcbp_set_start(p, 1); /* but skip encoding of zero run length */ toggle = !toggle; continue; } dcbp_set_start(p, 0); } /* paranoia: catch zero runlength. * can only happen if bitmap is modified while we scan it. */ if (rl == 0) { drbd_err(device, "unexpected zero runlength while encoding bitmap " "t:%u bo:%lu\n", toggle, c->bit_offset); return -1; } bits = vli_encode_bits(&bs, rl); if (bits == -ENOBUFS) /* buffer full */ break; if (bits <= 0) { drbd_err(device, "error while encoding bitmap: %d\n", bits); return 0; } toggle = !toggle; plain_bits += rl; c->bit_offset = tmp; } while (c->bit_offset < c->bm_bits); len = bs.cur.b - p->code + !!bs.cur.bit; if (plain_bits < (len << 3)) { /* incompressible with this method. * we need to rewind both word and bit position. */ c->bit_offset -= plain_bits; bm_xfer_ctx_bit_to_word_offset(c); c->bit_offset = c->word_offset * BITS_PER_LONG; return 0; } /* RLE + VLI was able to compress it just fine. * update c->word_offset. */ bm_xfer_ctx_bit_to_word_offset(c); /* store pad_bits */ dcbp_set_pad_bits(p, (8 - bs.cur.bit) & 0x7); return len; } /** * send_bitmap_rle_or_plain * * Return 0 when done, 1 when another iteration is needed, and a negative error * code upon failure. */ static int send_bitmap_rle_or_plain(struct drbd_device *device, struct bm_xfer_ctx *c) { struct drbd_socket *sock = &first_peer_device(device)->connection->data; unsigned int header_size = drbd_header_size(first_peer_device(device)->connection); struct p_compressed_bm *p = sock->sbuf + header_size; int len, err; len = fill_bitmap_rle_bits(device, p, DRBD_SOCKET_BUFFER_SIZE - header_size - sizeof(*p), c); if (len < 0) return -EIO; if (len) { dcbp_set_code(p, RLE_VLI_Bits); err = __send_command(first_peer_device(device)->connection, device->vnr, sock, P_COMPRESSED_BITMAP, sizeof(*p) + len, NULL, 0); c->packets[0]++; c->bytes[0] += header_size + sizeof(*p) + len; if (c->bit_offset >= c->bm_bits) len = 0; /* DONE */ } else { /* was not compressible. * send a buffer full of plain text bits instead. */ unsigned int data_size; unsigned long num_words; unsigned long *p = sock->sbuf + header_size; data_size = DRBD_SOCKET_BUFFER_SIZE - header_size; num_words = min_t(size_t, data_size / sizeof(*p), c->bm_words - c->word_offset); len = num_words * sizeof(*p); if (len) drbd_bm_get_lel(device, c->word_offset, num_words, p); err = __send_command(first_peer_device(device)->connection, device->vnr, sock, P_BITMAP, len, NULL, 0); c->word_offset += num_words; c->bit_offset = c->word_offset * BITS_PER_LONG; c->packets[1]++; c->bytes[1] += header_size + len; if (c->bit_offset > c->bm_bits) c->bit_offset = c->bm_bits; } if (!err) { if (len == 0) { INFO_bm_xfer_stats(device, "send", c); return 0; } else return 1; } return -EIO; } /* See the comment at receive_bitmap() */ static int _drbd_send_bitmap(struct drbd_device *device) { struct bm_xfer_ctx c; int err; if (!expect(device->bitmap)) return false; if (get_ldev(device)) { if (drbd_md_test_flag(device->ldev, MDF_FULL_SYNC)) { drbd_info(device, "Writing the whole bitmap, MDF_FullSync was set.\n"); drbd_bm_set_all(device); if (drbd_bm_write(device)) { /* write_bm did fail! Leave full sync flag set in Meta P_DATA * but otherwise process as per normal - need to tell other * side that a full resync is required! */ drbd_err(device, "Failed to write bitmap to disk!\n"); } else { drbd_md_clear_flag(device, MDF_FULL_SYNC); drbd_md_sync(device); } } put_ldev(device); } c = (struct bm_xfer_ctx) { .bm_bits = drbd_bm_bits(device), .bm_words = drbd_bm_words(device), }; do { err = send_bitmap_rle_or_plain(device, &c); } while (err > 0); return err == 0; } int drbd_send_bitmap(struct drbd_device *device) { struct drbd_socket *sock = &first_peer_device(device)->connection->data; int err = -1; mutex_lock(&sock->mutex); if (sock->socket) err = !_drbd_send_bitmap(device); mutex_unlock(&sock->mutex); return err; } void drbd_send_b_ack(struct drbd_connection *connection, u32 barrier_nr, u32 set_size) { struct drbd_socket *sock; struct p_barrier_ack *p; if (connection->cstate < C_WF_REPORT_PARAMS) return; sock = &connection->meta; p = conn_prepare_command(connection, sock); if (!p) return; p->barrier = barrier_nr; p->set_size = cpu_to_be32(set_size); conn_send_command(connection, sock, P_BARRIER_ACK, sizeof(*p), NULL, 0); } /** * _drbd_send_ack() - Sends an ack packet * @device: DRBD device. * @cmd: Packet command code. * @sector: sector, needs to be in big endian byte order * @blksize: size in byte, needs to be in big endian byte order * @block_id: Id, big endian byte order */ static int _drbd_send_ack(struct drbd_peer_device *peer_device, enum drbd_packet cmd, u64 sector, u32 blksize, u64 block_id) { struct drbd_socket *sock; struct p_block_ack *p; if (peer_device->device->state.conn < C_CONNECTED) return -EIO; sock = &peer_device->connection->meta; p = drbd_prepare_command(peer_device, sock); if (!p) return -EIO; p->sector = sector; p->block_id = block_id; p->blksize = blksize; p->seq_num = cpu_to_be32(atomic_inc_return(&peer_device->device->packet_seq)); return drbd_send_command(peer_device, sock, cmd, sizeof(*p), NULL, 0); } /* dp->sector and dp->block_id already/still in network byte order, * data_size is payload size according to dp->head, * and may need to be corrected for digest size. */ void drbd_send_ack_dp(struct drbd_peer_device *peer_device, enum drbd_packet cmd, struct p_data *dp, int data_size) { if (peer_device->connection->peer_integrity_tfm) data_size -= crypto_hash_digestsize(peer_device->connection->peer_integrity_tfm); _drbd_send_ack(peer_device, cmd, dp->sector, cpu_to_be32(data_size), dp->block_id); } void drbd_send_ack_rp(struct drbd_peer_device *peer_device, enum drbd_packet cmd, struct p_block_req *rp) { _drbd_send_ack(peer_device, cmd, rp->sector, rp->blksize, rp->block_id); } /** * drbd_send_ack() - Sends an ack packet * @device: DRBD device * @cmd: packet command code * @peer_req: peer request */ int drbd_send_ack(struct drbd_peer_device *peer_device, enum drbd_packet cmd, struct drbd_peer_request *peer_req) { return _drbd_send_ack(peer_device, cmd, cpu_to_be64(peer_req->i.sector), cpu_to_be32(peer_req->i.size), peer_req->block_id); } /* This function misuses the block_id field to signal if the blocks * are is sync or not. */ int drbd_send_ack_ex(struct drbd_peer_device *peer_device, enum drbd_packet cmd, sector_t sector, int blksize, u64 block_id) { return _drbd_send_ack(peer_device, cmd, cpu_to_be64(sector), cpu_to_be32(blksize), cpu_to_be64(block_id)); } int drbd_send_drequest(struct drbd_peer_device *peer_device, int cmd, sector_t sector, int size, u64 block_id) { struct drbd_socket *sock; struct p_block_req *p; sock = &peer_device->connection->data; p = drbd_prepare_command(peer_device, sock); if (!p) return -EIO; p->sector = cpu_to_be64(sector); p->block_id = block_id; p->blksize = cpu_to_be32(size); return drbd_send_command(peer_device, sock, cmd, sizeof(*p), NULL, 0); } int drbd_send_drequest_csum(struct drbd_peer_device *peer_device, sector_t sector, int size, void *digest, int digest_size, enum drbd_packet cmd) { struct drbd_socket *sock; struct p_block_req *p; /* FIXME: Put the digest into the preallocated socket buffer. */ sock = &peer_device->connection->data; p = drbd_prepare_command(peer_device, sock); if (!p) return -EIO; p->sector = cpu_to_be64(sector); p->block_id = ID_SYNCER /* unused */; p->blksize = cpu_to_be32(size); return drbd_send_command(peer_device, sock, cmd, sizeof(*p), digest, digest_size); } int drbd_send_ov_request(struct drbd_peer_device *peer_device, sector_t sector, int size) { struct drbd_socket *sock; struct p_block_req *p; sock = &peer_device->connection->data; p = drbd_prepare_command(peer_device, sock); if (!p) return -EIO; p->sector = cpu_to_be64(sector); p->block_id = ID_SYNCER /* unused */; p->blksize = cpu_to_be32(size); return drbd_send_command(peer_device, sock, P_OV_REQUEST, sizeof(*p), NULL, 0); } /* called on sndtimeo * returns false if we should retry, * true if we think connection is dead */ static int we_should_drop_the_connection(struct drbd_connection *connection, struct socket *sock) { int drop_it; /* long elapsed = (long)(jiffies - device->last_received); */ drop_it = connection->meta.socket == sock || !connection->asender.task || get_t_state(&connection->asender) != RUNNING || connection->cstate < C_WF_REPORT_PARAMS; if (drop_it) return true; drop_it = !--connection->ko_count; if (!drop_it) { drbd_err(connection, "[%s/%d] sock_sendmsg time expired, ko = %u\n", current->comm, current->pid, connection->ko_count); request_ping(connection); } return drop_it; /* && (device->state == R_PRIMARY) */; } static void drbd_update_congested(struct drbd_connection *connection) { struct sock *sk = connection->data.socket->sk; if (sk->sk_wmem_queued > sk->sk_sndbuf * 4 / 5) set_bit(NET_CONGESTED, &connection->flags); } /* The idea of sendpage seems to be to put some kind of reference * to the page into the skb, and to hand it over to the NIC. In * this process get_page() gets called. * * As soon as the page was really sent over the network put_page() * gets called by some part of the network layer. [ NIC driver? ] * * [ get_page() / put_page() increment/decrement the count. If count * reaches 0 the page will be freed. ] * * This works nicely with pages from FSs. * But this means that in protocol A we might signal IO completion too early! * * In order not to corrupt data during a resync we must make sure * that we do not reuse our own buffer pages (EEs) to early, therefore * we have the net_ee list. * * XFS seems to have problems, still, it submits pages with page_count == 0! * As a workaround, we disable sendpage on pages * with page_count == 0 or PageSlab. */ static int _drbd_no_send_page(struct drbd_peer_device *peer_device, struct page *page, int offset, size_t size, unsigned msg_flags) { struct socket *socket; void *addr; int err; socket = peer_device->connection->data.socket; addr = kmap(page) + offset; err = drbd_send_all(peer_device->connection, socket, addr, size, msg_flags); kunmap(page); if (!err) peer_device->device->send_cnt += size >> 9; return err; } static int _drbd_send_page(struct drbd_peer_device *peer_device, struct page *page, int offset, size_t size, unsigned msg_flags) { struct socket *socket = peer_device->connection->data.socket; mm_segment_t oldfs = get_fs(); int len = size; int err = -EIO; /* e.g. XFS meta- & log-data is in slab pages, which have a * page_count of 0 and/or have PageSlab() set. * we cannot use send_page for those, as that does get_page(); * put_page(); and would cause either a VM_BUG directly, or * __page_cache_release a page that would actually still be referenced * by someone, leading to some obscure delayed Oops somewhere else. */ if (disable_sendpage || (page_count(page) < 1) || PageSlab(page)) return _drbd_no_send_page(peer_device, page, offset, size, msg_flags); msg_flags |= MSG_NOSIGNAL; drbd_update_congested(peer_device->connection); set_fs(KERNEL_DS); do { int sent; sent = socket->ops->sendpage(socket, page, offset, len, msg_flags); if (sent <= 0) { if (sent == -EAGAIN) { if (we_should_drop_the_connection(peer_device->connection, socket)) break; continue; } drbd_warn(peer_device->device, "%s: size=%d len=%d sent=%d\n", __func__, (int)size, len, sent); if (sent < 0) err = sent; break; } len -= sent; offset += sent; } while (len > 0 /* THINK && device->cstate >= C_CONNECTED*/); set_fs(oldfs); clear_bit(NET_CONGESTED, &peer_device->connection->flags); if (len == 0) { err = 0; peer_device->device->send_cnt += size >> 9; } return err; } static int _drbd_send_bio(struct drbd_peer_device *peer_device, struct bio *bio) { struct bio_vec bvec; struct bvec_iter iter; /* hint all but last page with MSG_MORE */ bio_for_each_segment(bvec, bio, iter) { int err; err = _drbd_no_send_page(peer_device, bvec.bv_page, bvec.bv_offset, bvec.bv_len, bio_iter_last(bvec, iter) ? 0 : MSG_MORE); if (err) return err; } return 0; } static int _drbd_send_zc_bio(struct drbd_peer_device *peer_device, struct bio *bio) { struct bio_vec bvec; struct bvec_iter iter; /* hint all but last page with MSG_MORE */ bio_for_each_segment(bvec, bio, iter) { int err; err = _drbd_send_page(peer_device, bvec.bv_page, bvec.bv_offset, bvec.bv_len, bio_iter_last(bvec, iter) ? 0 : MSG_MORE); if (err) return err; } return 0; } static int _drbd_send_zc_ee(struct drbd_peer_device *peer_device, struct drbd_peer_request *peer_req) { struct page *page = peer_req->pages; unsigned len = peer_req->i.size; int err; /* hint all but last page with MSG_MORE */ page_chain_for_each(page) { unsigned l = min_t(unsigned, len, PAGE_SIZE); err = _drbd_send_page(peer_device, page, 0, l, page_chain_next(page) ? MSG_MORE : 0); if (err) return err; len -= l; } return 0; } static u32 bio_flags_to_wire(struct drbd_connection *connection, unsigned long bi_rw) { if (connection->agreed_pro_version >= 95) return (bi_rw & REQ_SYNC ? DP_RW_SYNC : 0) | (bi_rw & REQ_FUA ? DP_FUA : 0) | (bi_rw & REQ_FLUSH ? DP_FLUSH : 0) | (bi_rw & REQ_DISCARD ? DP_DISCARD : 0); else return bi_rw & REQ_SYNC ? DP_RW_SYNC : 0; } /* Used to send write or TRIM aka REQ_DISCARD requests * R_PRIMARY -> Peer (P_DATA, P_TRIM) */ int drbd_send_dblock(struct drbd_peer_device *peer_device, struct drbd_request *req) { struct drbd_device *device = peer_device->device; struct drbd_socket *sock; struct p_data *p; unsigned int dp_flags = 0; int digest_size; int err; sock = &peer_device->connection->data; p = drbd_prepare_command(peer_device, sock); digest_size = peer_device->connection->integrity_tfm ? crypto_hash_digestsize(peer_device->connection->integrity_tfm) : 0; if (!p) return -EIO; p->sector = cpu_to_be64(req->i.sector); p->block_id = (unsigned long)req; p->seq_num = cpu_to_be32(atomic_inc_return(&device->packet_seq)); dp_flags = bio_flags_to_wire(peer_device->connection, req->master_bio->bi_rw); if (device->state.conn >= C_SYNC_SOURCE && device->state.conn <= C_PAUSED_SYNC_T) dp_flags |= DP_MAY_SET_IN_SYNC; if (peer_device->connection->agreed_pro_version >= 100) { if (req->rq_state & RQ_EXP_RECEIVE_ACK) dp_flags |= DP_SEND_RECEIVE_ACK; /* During resync, request an explicit write ack, * even in protocol != C */ if (req->rq_state & RQ_EXP_WRITE_ACK || (dp_flags & DP_MAY_SET_IN_SYNC)) dp_flags |= DP_SEND_WRITE_ACK; } p->dp_flags = cpu_to_be32(dp_flags); if (dp_flags & DP_DISCARD) { struct p_trim *t = (struct p_trim*)p; t->size = cpu_to_be32(req->i.size); err = __send_command(peer_device->connection, device->vnr, sock, P_TRIM, sizeof(*t), NULL, 0); goto out; } /* our digest is still only over the payload. * TRIM does not carry any payload. */ if (digest_size) drbd_csum_bio(peer_device->connection->integrity_tfm, req->master_bio, p + 1); err = __send_command(peer_device->connection, device->vnr, sock, P_DATA, sizeof(*p) + digest_size, NULL, req->i.size); if (!err) { /* For protocol A, we have to memcpy the payload into * socket buffers, as we may complete right away * as soon as we handed it over to tcp, at which point the data * pages may become invalid. * * For data-integrity enabled, we copy it as well, so we can be * sure that even if the bio pages may still be modified, it * won't change the data on the wire, thus if the digest checks * out ok after sending on this side, but does not fit on the * receiving side, we sure have detected corruption elsewhere. */ if (!(req->rq_state & (RQ_EXP_RECEIVE_ACK | RQ_EXP_WRITE_ACK)) || digest_size) err = _drbd_send_bio(peer_device, req->master_bio); else err = _drbd_send_zc_bio(peer_device, req->master_bio); /* double check digest, sometimes buffers have been modified in flight. */ if (digest_size > 0 && digest_size <= 64) { /* 64 byte, 512 bit, is the largest digest size * currently supported in kernel crypto. */ unsigned char digest[64]; drbd_csum_bio(peer_device->connection->integrity_tfm, req->master_bio, digest); if (memcmp(p + 1, digest, digest_size)) { drbd_warn(device, "Digest mismatch, buffer modified by upper layers during write: %llus +%u\n", (unsigned long long)req->i.sector, req->i.size); } } /* else if (digest_size > 64) { ... Be noisy about digest too large ... } */ } out: mutex_unlock(&sock->mutex); /* locked by drbd_prepare_command() */ return err; } /* answer packet, used to send data back for read requests: * Peer -> (diskless) R_PRIMARY (P_DATA_REPLY) * C_SYNC_SOURCE -> C_SYNC_TARGET (P_RS_DATA_REPLY) */ int drbd_send_block(struct drbd_peer_device *peer_device, enum drbd_packet cmd, struct drbd_peer_request *peer_req) { struct drbd_device *device = peer_device->device; struct drbd_socket *sock; struct p_data *p; int err; int digest_size; sock = &peer_device->connection->data; p = drbd_prepare_command(peer_device, sock); digest_size = peer_device->connection->integrity_tfm ? crypto_hash_digestsize(peer_device->connection->integrity_tfm) : 0; if (!p) return -EIO; p->sector = cpu_to_be64(peer_req->i.sector); p->block_id = peer_req->block_id; p->seq_num = 0; /* unused */ p->dp_flags = 0; if (digest_size) drbd_csum_ee(peer_device->connection->integrity_tfm, peer_req, p + 1); err = __send_command(peer_device->connection, device->vnr, sock, cmd, sizeof(*p) + digest_size, NULL, peer_req->i.size); if (!err) err = _drbd_send_zc_ee(peer_device, peer_req); mutex_unlock(&sock->mutex); /* locked by drbd_prepare_command() */ return err; } int drbd_send_out_of_sync(struct drbd_peer_device *peer_device, struct drbd_request *req) { struct drbd_socket *sock; struct p_block_desc *p; sock = &peer_device->connection->data; p = drbd_prepare_command(peer_device, sock); if (!p) return -EIO; p->sector = cpu_to_be64(req->i.sector); p->blksize = cpu_to_be32(req->i.size); return drbd_send_command(peer_device, sock, P_OUT_OF_SYNC, sizeof(*p), NULL, 0); } /* drbd_send distinguishes two cases: Packets sent via the data socket "sock" and packets sent via the meta data socket "msock" sock msock -----------------+-------------------------+------------------------------ timeout conf.timeout / 2 conf.timeout / 2 timeout action send a ping via msock Abort communication and close all sockets */ /* * you must have down()ed the appropriate [m]sock_mutex elsewhere! */ int drbd_send(struct drbd_connection *connection, struct socket *sock, void *buf, size_t size, unsigned msg_flags) { struct kvec iov; struct msghdr msg; int rv, sent = 0; if (!sock) return -EBADR; /* THINK if (signal_pending) return ... ? */ iov.iov_base = buf; iov.iov_len = size; msg.msg_name = NULL; msg.msg_namelen = 0; msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_flags = msg_flags | MSG_NOSIGNAL; if (sock == connection->data.socket) { rcu_read_lock(); connection->ko_count = rcu_dereference(connection->net_conf)->ko_count; rcu_read_unlock(); drbd_update_congested(connection); } do { /* STRANGE * tcp_sendmsg does _not_ use its size parameter at all ? * * -EAGAIN on timeout, -EINTR on signal. */ /* THINK * do we need to block DRBD_SIG if sock == &meta.socket ?? * otherwise wake_asender() might interrupt some send_*Ack ! */ rv = kernel_sendmsg(sock, &msg, &iov, 1, size); if (rv == -EAGAIN) { if (we_should_drop_the_connection(connection, sock)) break; else continue; } if (rv == -EINTR) { flush_signals(current); rv = 0; } if (rv < 0) break; sent += rv; iov.iov_base += rv; iov.iov_len -= rv; } while (sent < size); if (sock == connection->data.socket) clear_bit(NET_CONGESTED, &connection->flags); if (rv <= 0) { if (rv != -EAGAIN) { drbd_err(connection, "%s_sendmsg returned %d\n", sock == connection->meta.socket ? "msock" : "sock", rv); conn_request_state(connection, NS(conn, C_BROKEN_PIPE), CS_HARD); } else conn_request_state(connection, NS(conn, C_TIMEOUT), CS_HARD); } return sent; } /** * drbd_send_all - Send an entire buffer * * Returns 0 upon success and a negative error value otherwise. */ int drbd_send_all(struct drbd_connection *connection, struct socket *sock, void *buffer, size_t size, unsigned msg_flags) { int err; err = drbd_send(connection, sock, buffer, size, msg_flags); if (err < 0) return err; if (err != size) return -EIO; return 0; } static int drbd_open(struct block_device *bdev, fmode_t mode) { struct drbd_device *device = bdev->bd_disk->private_data; unsigned long flags; int rv = 0; mutex_lock(&drbd_main_mutex); spin_lock_irqsave(&device->resource->req_lock, flags); /* to have a stable device->state.role * and no race with updating open_cnt */ if (device->state.role != R_PRIMARY) { if (mode & FMODE_WRITE) rv = -EROFS; else if (!allow_oos) rv = -EMEDIUMTYPE; } if (!rv) device->open_cnt++; spin_unlock_irqrestore(&device->resource->req_lock, flags); mutex_unlock(&drbd_main_mutex); return rv; } static void drbd_release(struct gendisk *gd, fmode_t mode) { struct drbd_device *device = gd->private_data; mutex_lock(&drbd_main_mutex); device->open_cnt--; mutex_unlock(&drbd_main_mutex); } static void drbd_set_defaults(struct drbd_device *device) { /* Beware! The actual layout differs * between big endian and little endian */ device->state = (union drbd_dev_state) { { .role = R_SECONDARY, .peer = R_UNKNOWN, .conn = C_STANDALONE, .disk = D_DISKLESS, .pdsk = D_UNKNOWN, } }; } void drbd_init_set_defaults(struct drbd_device *device) { /* the memset(,0,) did most of this. * note: only assignments, no allocation in here */ drbd_set_defaults(device); atomic_set(&device->ap_bio_cnt, 0); atomic_set(&device->ap_actlog_cnt, 0); atomic_set(&device->ap_pending_cnt, 0); atomic_set(&device->rs_pending_cnt, 0); atomic_set(&device->unacked_cnt, 0); atomic_set(&device->local_cnt, 0); atomic_set(&device->pp_in_use_by_net, 0); atomic_set(&device->rs_sect_in, 0); atomic_set(&device->rs_sect_ev, 0); atomic_set(&device->ap_in_flight, 0); atomic_set(&device->md_io.in_use, 0); mutex_init(&device->own_state_mutex); device->state_mutex = &device->own_state_mutex; spin_lock_init(&device->al_lock); spin_lock_init(&device->peer_seq_lock); INIT_LIST_HEAD(&device->active_ee); INIT_LIST_HEAD(&device->sync_ee); INIT_LIST_HEAD(&device->done_ee); INIT_LIST_HEAD(&device->read_ee); INIT_LIST_HEAD(&device->net_ee); INIT_LIST_HEAD(&device->resync_reads); INIT_LIST_HEAD(&device->resync_work.list); INIT_LIST_HEAD(&device->unplug_work.list); INIT_LIST_HEAD(&device->bm_io_work.w.list); INIT_LIST_HEAD(&device->pending_master_completion[0]); INIT_LIST_HEAD(&device->pending_master_completion[1]); INIT_LIST_HEAD(&device->pending_completion[0]); INIT_LIST_HEAD(&device->pending_completion[1]); device->resync_work.cb = w_resync_timer; device->unplug_work.cb = w_send_write_hint; device->bm_io_work.w.cb = w_bitmap_io; init_timer(&device->resync_timer); init_timer(&device->md_sync_timer); init_timer(&device->start_resync_timer); init_timer(&device->request_timer); device->resync_timer.function = resync_timer_fn; device->resync_timer.data = (unsigned long) device; device->md_sync_timer.function = md_sync_timer_fn; device->md_sync_timer.data = (unsigned long) device; device->start_resync_timer.function = start_resync_timer_fn; device->start_resync_timer.data = (unsigned long) device; device->request_timer.function = request_timer_fn; device->request_timer.data = (unsigned long) device; init_waitqueue_head(&device->misc_wait); init_waitqueue_head(&device->state_wait); init_waitqueue_head(&device->ee_wait); init_waitqueue_head(&device->al_wait); init_waitqueue_head(&device->seq_wait); device->resync_wenr = LC_FREE; device->peer_max_bio_size = DRBD_MAX_BIO_SIZE_SAFE; device->local_max_bio_size = DRBD_MAX_BIO_SIZE_SAFE; } void drbd_device_cleanup(struct drbd_device *device) { int i; if (first_peer_device(device)->connection->receiver.t_state != NONE) drbd_err(device, "ASSERT FAILED: receiver t_state == %d expected 0.\n", first_peer_device(device)->connection->receiver.t_state); device->al_writ_cnt = device->bm_writ_cnt = device->read_cnt = device->recv_cnt = device->send_cnt = device->writ_cnt = device->p_size = device->rs_start = device->rs_total = device->rs_failed = 0; device->rs_last_events = 0; device->rs_last_sect_ev = 0; for (i = 0; i < DRBD_SYNC_MARKS; i++) { device->rs_mark_left[i] = 0; device->rs_mark_time[i] = 0; } D_ASSERT(device, first_peer_device(device)->connection->net_conf == NULL); drbd_set_my_capacity(device, 0); if (device->bitmap) { /* maybe never allocated. */ drbd_bm_resize(device, 0, 1); drbd_bm_cleanup(device); } drbd_free_ldev(device->ldev); device->ldev = NULL; clear_bit(AL_SUSPENDED, &device->flags); D_ASSERT(device, list_empty(&device->active_ee)); D_ASSERT(device, list_empty(&device->sync_ee)); D_ASSERT(device, list_empty(&device->done_ee)); D_ASSERT(device, list_empty(&device->read_ee)); D_ASSERT(device, list_empty(&device->net_ee)); D_ASSERT(device, list_empty(&device->resync_reads)); D_ASSERT(device, list_empty(&first_peer_device(device)->connection->sender_work.q)); D_ASSERT(device, list_empty(&device->resync_work.list)); D_ASSERT(device, list_empty(&device->unplug_work.list)); drbd_set_defaults(device); } static void drbd_destroy_mempools(void) { struct page *page; while (drbd_pp_pool) { page = drbd_pp_pool; drbd_pp_pool = (struct page *)page_private(page); __free_page(page); drbd_pp_vacant--; } /* D_ASSERT(device, atomic_read(&drbd_pp_vacant)==0); */ if (drbd_md_io_bio_set) bioset_free(drbd_md_io_bio_set); if (drbd_md_io_page_pool) mempool_destroy(drbd_md_io_page_pool); if (drbd_ee_mempool) mempool_destroy(drbd_ee_mempool); if (drbd_request_mempool) mempool_destroy(drbd_request_mempool); if (drbd_ee_cache) kmem_cache_destroy(drbd_ee_cache); if (drbd_request_cache) kmem_cache_destroy(drbd_request_cache); if (drbd_bm_ext_cache) kmem_cache_destroy(drbd_bm_ext_cache); if (drbd_al_ext_cache) kmem_cache_destroy(drbd_al_ext_cache); drbd_md_io_bio_set = NULL; drbd_md_io_page_pool = NULL; drbd_ee_mempool = NULL; drbd_request_mempool = NULL; drbd_ee_cache = NULL; drbd_request_cache = NULL; drbd_bm_ext_cache = NULL; drbd_al_ext_cache = NULL; return; } static int drbd_create_mempools(void) { struct page *page; const int number = (DRBD_MAX_BIO_SIZE/PAGE_SIZE) * minor_count; int i; /* prepare our caches and mempools */ drbd_request_mempool = NULL; drbd_ee_cache = NULL; drbd_request_cache = NULL; drbd_bm_ext_cache = NULL; drbd_al_ext_cache = NULL; drbd_pp_pool = NULL; drbd_md_io_page_pool = NULL; drbd_md_io_bio_set = NULL; /* caches */ drbd_request_cache = kmem_cache_create( "drbd_req", sizeof(struct drbd_request), 0, 0, NULL); if (drbd_request_cache == NULL) goto Enomem; drbd_ee_cache = kmem_cache_create( "drbd_ee", sizeof(struct drbd_peer_request), 0, 0, NULL); if (drbd_ee_cache == NULL) goto Enomem; drbd_bm_ext_cache = kmem_cache_create( "drbd_bm", sizeof(struct bm_extent), 0, 0, NULL); if (drbd_bm_ext_cache == NULL) goto Enomem; drbd_al_ext_cache = kmem_cache_create( "drbd_al", sizeof(struct lc_element), 0, 0, NULL); if (drbd_al_ext_cache == NULL) goto Enomem; /* mempools */ drbd_md_io_bio_set = bioset_create(DRBD_MIN_POOL_PAGES, 0); if (drbd_md_io_bio_set == NULL) goto Enomem; drbd_md_io_page_pool = mempool_create_page_pool(DRBD_MIN_POOL_PAGES, 0); if (drbd_md_io_page_pool == NULL) goto Enomem; drbd_request_mempool = mempool_create_slab_pool(number, drbd_request_cache); if (drbd_request_mempool == NULL) goto Enomem; drbd_ee_mempool = mempool_create_slab_pool(number, drbd_ee_cache); if (drbd_ee_mempool == NULL) goto Enomem; /* drbd's page pool */ spin_lock_init(&drbd_pp_lock); for (i = 0; i < number; i++) { page = alloc_page(GFP_HIGHUSER); if (!page) goto Enomem; set_page_private(page, (unsigned long)drbd_pp_pool); drbd_pp_pool = page; } drbd_pp_vacant = number; return 0; Enomem: drbd_destroy_mempools(); /* in case we allocated some */ return -ENOMEM; } static void drbd_release_all_peer_reqs(struct drbd_device *device) { int rr; rr = drbd_free_peer_reqs(device, &device->active_ee); if (rr) drbd_err(device, "%d EEs in active list found!\n", rr); rr = drbd_free_peer_reqs(device, &device->sync_ee); if (rr) drbd_err(device, "%d EEs in sync list found!\n", rr); rr = drbd_free_peer_reqs(device, &device->read_ee); if (rr) drbd_err(device, "%d EEs in read list found!\n", rr); rr = drbd_free_peer_reqs(device, &device->done_ee); if (rr) drbd_err(device, "%d EEs in done list found!\n", rr); rr = drbd_free_peer_reqs(device, &device->net_ee); if (rr) drbd_err(device, "%d EEs in net list found!\n", rr); } /* caution. no locking. */ void drbd_destroy_device(struct kref *kref) { struct drbd_device *device = container_of(kref, struct drbd_device, kref); struct drbd_resource *resource = device->resource; struct drbd_peer_device *peer_device, *tmp_peer_device; del_timer_sync(&device->request_timer); /* paranoia asserts */ D_ASSERT(device, device->open_cnt == 0); /* end paranoia asserts */ /* cleanup stuff that may have been allocated during * device (re-)configuration or state changes */ if (device->this_bdev) bdput(device->this_bdev); drbd_free_ldev(device->ldev); device->ldev = NULL; drbd_release_all_peer_reqs(device); lc_destroy(device->act_log); lc_destroy(device->resync); kfree(device->p_uuid); /* device->p_uuid = NULL; */ if (device->bitmap) /* should no longer be there. */ drbd_bm_cleanup(device); __free_page(device->md_io.page); put_disk(device->vdisk); blk_cleanup_queue(device->rq_queue); kfree(device->rs_plan_s); /* not for_each_connection(connection, resource): * those may have been cleaned up and disassociated already. */ for_each_peer_device_safe(peer_device, tmp_peer_device, device) { kref_put(&peer_device->connection->kref, drbd_destroy_connection); kfree(peer_device); } memset(device, 0xfd, sizeof(*device)); kfree(device); kref_put(&resource->kref, drbd_destroy_resource); } /* One global retry thread, if we need to push back some bio and have it * reinserted through our make request function. */ static struct retry_worker { struct workqueue_struct *wq; struct work_struct worker; spinlock_t lock; struct list_head writes; } retry; static void do_retry(struct work_struct *ws) { struct retry_worker *retry = container_of(ws, struct retry_worker, worker); LIST_HEAD(writes); struct drbd_request *req, *tmp; spin_lock_irq(&retry->lock); list_splice_init(&retry->writes, &writes); spin_unlock_irq(&retry->lock); list_for_each_entry_safe(req, tmp, &writes, tl_requests) { struct drbd_device *device = req->device; struct bio *bio = req->master_bio; unsigned long start_jif = req->start_jif; bool expected; expected = expect(atomic_read(&req->completion_ref) == 0) && expect(req->rq_state & RQ_POSTPONED) && expect((req->rq_state & RQ_LOCAL_PENDING) == 0 || (req->rq_state & RQ_LOCAL_ABORTED) != 0); if (!expected) drbd_err(device, "req=%p completion_ref=%d rq_state=%x\n", req, atomic_read(&req->completion_ref), req->rq_state); /* We still need to put one kref associated with the * "completion_ref" going zero in the code path that queued it * here. The request object may still be referenced by a * frozen local req->private_bio, in case we force-detached. */ kref_put(&req->kref, drbd_req_destroy); /* A single suspended or otherwise blocking device may stall * all others as well. Fortunately, this code path is to * recover from a situation that "should not happen": * concurrent writes in multi-primary setup. * In a "normal" lifecycle, this workqueue is supposed to be * destroyed without ever doing anything. * If it turns out to be an issue anyways, we can do per * resource (replication group) or per device (minor) retry * workqueues instead. */ /* We are not just doing generic_make_request(), * as we want to keep the start_time information. */ inc_ap_bio(device); __drbd_make_request(device, bio, start_jif); } } /* called via drbd_req_put_completion_ref(), * holds resource->req_lock */ void drbd_restart_request(struct drbd_request *req) { unsigned long flags; spin_lock_irqsave(&retry.lock, flags); list_move_tail(&req->tl_requests, &retry.writes); spin_unlock_irqrestore(&retry.lock, flags); /* Drop the extra reference that would otherwise * have been dropped by complete_master_bio. * do_retry() needs to grab a new one. */ dec_ap_bio(req->device); queue_work(retry.wq, &retry.worker); } void drbd_destroy_resource(struct kref *kref) { struct drbd_resource *resource = container_of(kref, struct drbd_resource, kref); idr_destroy(&resource->devices); free_cpumask_var(resource->cpu_mask); kfree(resource->name); memset(resource, 0xf2, sizeof(*resource)); kfree(resource); } void drbd_free_resource(struct drbd_resource *resource) { struct drbd_connection *connection, *tmp; for_each_connection_safe(connection, tmp, resource) { list_del(&connection->connections); drbd_debugfs_connection_cleanup(connection); kref_put(&connection->kref, drbd_destroy_connection); } drbd_debugfs_resource_cleanup(resource); kref_put(&resource->kref, drbd_destroy_resource); } static void drbd_cleanup(void) { unsigned int i; struct drbd_device *device; struct drbd_resource *resource, *tmp; /* first remove proc, * drbdsetup uses it's presence to detect * whether DRBD is loaded. * If we would get stuck in proc removal, * but have netlink already deregistered, * some drbdsetup commands may wait forever * for an answer. */ if (drbd_proc) remove_proc_entry("drbd", NULL); if (retry.wq) destroy_workqueue(retry.wq); drbd_genl_unregister(); drbd_debugfs_cleanup(); idr_for_each_entry(&drbd_devices, device, i) drbd_delete_device(device); /* not _rcu since, no other updater anymore. Genl already unregistered */ for_each_resource_safe(resource, tmp, &drbd_resources) { list_del(&resource->resources); drbd_free_resource(resource); } drbd_destroy_mempools(); unregister_blkdev(DRBD_MAJOR, "drbd"); idr_destroy(&drbd_devices); pr_info("module cleanup done.\n"); } /** * drbd_congested() - Callback for the flusher thread * @congested_data: User data * @bdi_bits: Bits the BDI flusher thread is currently interested in * * Returns 1<<BDI_async_congested and/or 1<<BDI_sync_congested if we are congested. */ static int drbd_congested(void *congested_data, int bdi_bits) { struct drbd_device *device = congested_data; struct request_queue *q; char reason = '-'; int r = 0; if (!may_inc_ap_bio(device)) { /* DRBD has frozen IO */ r = bdi_bits; reason = 'd'; goto out; } if (test_bit(CALLBACK_PENDING, &first_peer_device(device)->connection->flags)) { r |= (1 << BDI_async_congested); /* Without good local data, we would need to read from remote, * and that would need the worker thread as well, which is * currently blocked waiting for that usermode helper to * finish. */ if (!get_ldev_if_state(device, D_UP_TO_DATE)) r |= (1 << BDI_sync_congested); else put_ldev(device); r &= bdi_bits; reason = 'c'; goto out; } if (get_ldev(device)) { q = bdev_get_queue(device->ldev->backing_bdev); r = bdi_congested(&q->backing_dev_info, bdi_bits); put_ldev(device); if (r) reason = 'b'; } if (bdi_bits & (1 << BDI_async_congested) && test_bit(NET_CONGESTED, &first_peer_device(device)->connection->flags)) { r |= (1 << BDI_async_congested); reason = reason == 'b' ? 'a' : 'n'; } out: device->congestion_reason = reason; return r; } static void drbd_init_workqueue(struct drbd_work_queue* wq) { spin_lock_init(&wq->q_lock); INIT_LIST_HEAD(&wq->q); init_waitqueue_head(&wq->q_wait); } struct completion_work { struct drbd_work w; struct completion done; }; static int w_complete(struct drbd_work *w, int cancel) { struct completion_work *completion_work = container_of(w, struct completion_work, w); complete(&completion_work->done); return 0; } void drbd_flush_workqueue(struct drbd_work_queue *work_queue) { struct completion_work completion_work; completion_work.w.cb = w_complete; init_completion(&completion_work.done); drbd_queue_work(work_queue, &completion_work.w); wait_for_completion(&completion_work.done); } struct drbd_resource *drbd_find_resource(const char *name) { struct drbd_resource *resource; if (!name || !name[0]) return NULL; rcu_read_lock(); for_each_resource_rcu(resource, &drbd_resources) { if (!strcmp(resource->name, name)) { kref_get(&resource->kref); goto found; } } resource = NULL; found: rcu_read_unlock(); return resource; } struct drbd_connection *conn_get_by_addrs(void *my_addr, int my_addr_len, void *peer_addr, int peer_addr_len) { struct drbd_resource *resource; struct drbd_connection *connection; rcu_read_lock(); for_each_resource_rcu(resource, &drbd_resources) { for_each_connection_rcu(connection, resource) { if (connection->my_addr_len == my_addr_len && connection->peer_addr_len == peer_addr_len && !memcmp(&connection->my_addr, my_addr, my_addr_len) && !memcmp(&connection->peer_addr, peer_addr, peer_addr_len)) { kref_get(&connection->kref); goto found; } } } connection = NULL; found: rcu_read_unlock(); return connection; } static int drbd_alloc_socket(struct drbd_socket *socket) { socket->rbuf = (void *) __get_free_page(GFP_KERNEL); if (!socket->rbuf) return -ENOMEM; socket->sbuf = (void *) __get_free_page(GFP_KERNEL); if (!socket->sbuf) return -ENOMEM; return 0; } static void drbd_free_socket(struct drbd_socket *socket) { free_page((unsigned long) socket->sbuf); free_page((unsigned long) socket->rbuf); } void conn_free_crypto(struct drbd_connection *connection) { drbd_free_sock(connection); crypto_free_hash(connection->csums_tfm); crypto_free_hash(connection->verify_tfm); crypto_free_hash(connection->cram_hmac_tfm); crypto_free_hash(connection->integrity_tfm); crypto_free_hash(connection->peer_integrity_tfm); kfree(connection->int_dig_in); kfree(connection->int_dig_vv); connection->csums_tfm = NULL; connection->verify_tfm = NULL; connection->cram_hmac_tfm = NULL; connection->integrity_tfm = NULL; connection->peer_integrity_tfm = NULL; connection->int_dig_in = NULL; connection->int_dig_vv = NULL; } int set_resource_options(struct drbd_resource *resource, struct res_opts *res_opts) { struct drbd_connection *connection; cpumask_var_t new_cpu_mask; int err; if (!zalloc_cpumask_var(&new_cpu_mask, GFP_KERNEL)) return -ENOMEM; /* silently ignore cpu mask on UP kernel */ if (nr_cpu_ids > 1 && res_opts->cpu_mask[0] != 0) { err = bitmap_parse(res_opts->cpu_mask, DRBD_CPU_MASK_SIZE, cpumask_bits(new_cpu_mask), nr_cpu_ids); if (err == -EOVERFLOW) { /* So what. mask it out. */ cpumask_var_t tmp_cpu_mask; if (zalloc_cpumask_var(&tmp_cpu_mask, GFP_KERNEL)) { cpumask_setall(tmp_cpu_mask); cpumask_and(new_cpu_mask, new_cpu_mask, tmp_cpu_mask); drbd_warn(resource, "Overflow in bitmap_parse(%.12s%s), truncating to %u bits\n", res_opts->cpu_mask, strlen(res_opts->cpu_mask) > 12 ? "..." : "", nr_cpu_ids); free_cpumask_var(tmp_cpu_mask); err = 0; } } if (err) { drbd_warn(resource, "bitmap_parse() failed with %d\n", err); /* retcode = ERR_CPU_MASK_PARSE; */ goto fail; } } resource->res_opts = *res_opts; if (cpumask_empty(new_cpu_mask)) drbd_calc_cpu_mask(&new_cpu_mask); if (!cpumask_equal(resource->cpu_mask, new_cpu_mask)) { cpumask_copy(resource->cpu_mask, new_cpu_mask); for_each_connection_rcu(connection, resource) { connection->receiver.reset_cpu_mask = 1; connection->asender.reset_cpu_mask = 1; connection->worker.reset_cpu_mask = 1; } } err = 0; fail: free_cpumask_var(new_cpu_mask); return err; } struct drbd_resource *drbd_create_resource(const char *name) { struct drbd_resource *resource; resource = kzalloc(sizeof(struct drbd_resource), GFP_KERNEL); if (!resource) goto fail; resource->name = kstrdup(name, GFP_KERNEL); if (!resource->name) goto fail_free_resource; if (!zalloc_cpumask_var(&resource->cpu_mask, GFP_KERNEL)) goto fail_free_name; kref_init(&resource->kref); idr_init(&resource->devices); INIT_LIST_HEAD(&resource->connections); resource->write_ordering = WO_bdev_flush; list_add_tail_rcu(&resource->resources, &drbd_resources); mutex_init(&resource->conf_update); mutex_init(&resource->adm_mutex); spin_lock_init(&resource->req_lock); drbd_debugfs_resource_add(resource); return resource; fail_free_name: kfree(resource->name); fail_free_resource: kfree(resource); fail: return NULL; } /* caller must be under adm_mutex */ struct drbd_connection *conn_create(const char *name, struct res_opts *res_opts) { struct drbd_resource *resource; struct drbd_connection *connection; connection = kzalloc(sizeof(struct drbd_connection), GFP_KERNEL); if (!connection) return NULL; if (drbd_alloc_socket(&connection->data)) goto fail; if (drbd_alloc_socket(&connection->meta)) goto fail; connection->current_epoch = kzalloc(sizeof(struct drbd_epoch), GFP_KERNEL); if (!connection->current_epoch) goto fail; INIT_LIST_HEAD(&connection->transfer_log); INIT_LIST_HEAD(&connection->current_epoch->list); connection->epochs = 1; spin_lock_init(&connection->epoch_lock); connection->send.seen_any_write_yet = false; connection->send.current_epoch_nr = 0; connection->send.current_epoch_writes = 0; resource = drbd_create_resource(name); if (!resource) goto fail; connection->cstate = C_STANDALONE; mutex_init(&connection->cstate_mutex); init_waitqueue_head(&connection->ping_wait); idr_init(&connection->peer_devices); drbd_init_workqueue(&connection->sender_work); mutex_init(&connection->data.mutex); mutex_init(&connection->meta.mutex); drbd_thread_init(resource, &connection->receiver, drbd_receiver, "receiver"); connection->receiver.connection = connection; drbd_thread_init(resource, &connection->worker, drbd_worker, "worker"); connection->worker.connection = connection; drbd_thread_init(resource, &connection->asender, drbd_asender, "asender"); connection->asender.connection = connection; kref_init(&connection->kref); connection->resource = resource; if (set_resource_options(resource, res_opts)) goto fail_resource; kref_get(&resource->kref); list_add_tail_rcu(&connection->connections, &resource->connections); drbd_debugfs_connection_add(connection); return connection; fail_resource: list_del(&resource->resources); drbd_free_resource(resource); fail: kfree(connection->current_epoch); drbd_free_socket(&connection->meta); drbd_free_socket(&connection->data); kfree(connection); return NULL; } void drbd_destroy_connection(struct kref *kref) { struct drbd_connection *connection = container_of(kref, struct drbd_connection, kref); struct drbd_resource *resource = connection->resource; if (atomic_read(&connection->current_epoch->epoch_size) != 0) drbd_err(connection, "epoch_size:%d\n", atomic_read(&connection->current_epoch->epoch_size)); kfree(connection->current_epoch); idr_destroy(&connection->peer_devices); drbd_free_socket(&connection->meta); drbd_free_socket(&connection->data); kfree(connection->int_dig_in); kfree(connection->int_dig_vv); memset(connection, 0xfc, sizeof(*connection)); kfree(connection); kref_put(&resource->kref, drbd_destroy_resource); } static int init_submitter(struct drbd_device *device) { /* opencoded create_singlethread_workqueue(), * to be able to say "drbd%d", ..., minor */ device->submit.wq = alloc_workqueue("drbd%u_submit", WQ_UNBOUND | WQ_MEM_RECLAIM, 1, device->minor); if (!device->submit.wq) return -ENOMEM; INIT_WORK(&device->submit.worker, do_submit); INIT_LIST_HEAD(&device->submit.writes); return 0; } enum drbd_ret_code drbd_create_device(struct drbd_config_context *adm_ctx, unsigned int minor) { struct drbd_resource *resource = adm_ctx->resource; struct drbd_connection *connection; struct drbd_device *device; struct drbd_peer_device *peer_device, *tmp_peer_device; struct gendisk *disk; struct request_queue *q; int id; int vnr = adm_ctx->volume; enum drbd_ret_code err = ERR_NOMEM; device = minor_to_device(minor); if (device) return ERR_MINOR_OR_VOLUME_EXISTS; /* GFP_KERNEL, we are outside of all write-out paths */ device = kzalloc(sizeof(struct drbd_device), GFP_KERNEL); if (!device) return ERR_NOMEM; kref_init(&device->kref); kref_get(&resource->kref); device->resource = resource; device->minor = minor; device->vnr = vnr; drbd_init_set_defaults(device); q = blk_alloc_queue(GFP_KERNEL); if (!q) goto out_no_q; device->rq_queue = q; q->queuedata = device; disk = alloc_disk(1); if (!disk) goto out_no_disk; device->vdisk = disk; set_disk_ro(disk, true); disk->queue = q; disk->major = DRBD_MAJOR; disk->first_minor = minor; disk->fops = &drbd_ops; sprintf(disk->disk_name, "drbd%d", minor); disk->private_data = device; device->this_bdev = bdget(MKDEV(DRBD_MAJOR, minor)); /* we have no partitions. we contain only ourselves. */ device->this_bdev->bd_contains = device->this_bdev; q->backing_dev_info.congested_fn = drbd_congested; q->backing_dev_info.congested_data = device; blk_queue_make_request(q, drbd_make_request); blk_queue_flush(q, REQ_FLUSH | REQ_FUA); /* Setting the max_hw_sectors to an odd value of 8kibyte here This triggers a max_bio_size message upon first attach or connect */ blk_queue_max_hw_sectors(q, DRBD_MAX_BIO_SIZE_SAFE >> 8); blk_queue_bounce_limit(q, BLK_BOUNCE_ANY); blk_queue_merge_bvec(q, drbd_merge_bvec); q->queue_lock = &resource->req_lock; device->md_io.page = alloc_page(GFP_KERNEL); if (!device->md_io.page) goto out_no_io_page; if (drbd_bm_init(device)) goto out_no_bitmap; device->read_requests = RB_ROOT; device->write_requests = RB_ROOT; id = idr_alloc(&drbd_devices, device, minor, minor + 1, GFP_KERNEL); if (id < 0) { if (id == -ENOSPC) err = ERR_MINOR_OR_VOLUME_EXISTS; goto out_no_minor_idr; } kref_get(&device->kref); id = idr_alloc(&resource->devices, device, vnr, vnr + 1, GFP_KERNEL); if (id < 0) { if (id == -ENOSPC) err = ERR_MINOR_OR_VOLUME_EXISTS; goto out_idr_remove_minor; } kref_get(&device->kref); INIT_LIST_HEAD(&device->peer_devices); INIT_LIST_HEAD(&device->pending_bitmap_io); for_each_connection(connection, resource) { peer_device = kzalloc(sizeof(struct drbd_peer_device), GFP_KERNEL); if (!peer_device) goto out_idr_remove_from_resource; peer_device->connection = connection; peer_device->device = device; list_add(&peer_device->peer_devices, &device->peer_devices); kref_get(&device->kref); id = idr_alloc(&connection->peer_devices, peer_device, vnr, vnr + 1, GFP_KERNEL); if (id < 0) { if (id == -ENOSPC) err = ERR_INVALID_REQUEST; goto out_idr_remove_from_resource; } kref_get(&connection->kref); } if (init_submitter(device)) { err = ERR_NOMEM; goto out_idr_remove_vol; } add_disk(disk); /* inherit the connection state */ device->state.conn = first_connection(resource)->cstate; if (device->state.conn == C_WF_REPORT_PARAMS) { for_each_peer_device(peer_device, device) drbd_connected(peer_device); } /* move to create_peer_device() */ for_each_peer_device(peer_device, device) drbd_debugfs_peer_device_add(peer_device); drbd_debugfs_device_add(device); return NO_ERROR; out_idr_remove_vol: idr_remove(&connection->peer_devices, vnr); out_idr_remove_from_resource: for_each_connection(connection, resource) { peer_device = idr_find(&connection->peer_devices, vnr); if (peer_device) { idr_remove(&connection->peer_devices, vnr); kref_put(&connection->kref, drbd_destroy_connection); } } for_each_peer_device_safe(peer_device, tmp_peer_device, device) { list_del(&peer_device->peer_devices); kfree(peer_device); } idr_remove(&resource->devices, vnr); out_idr_remove_minor: idr_remove(&drbd_devices, minor); synchronize_rcu(); out_no_minor_idr: drbd_bm_cleanup(device); out_no_bitmap: __free_page(device->md_io.page); out_no_io_page: put_disk(disk); out_no_disk: blk_cleanup_queue(q); out_no_q: kref_put(&resource->kref, drbd_destroy_resource); kfree(device); return err; } void drbd_delete_device(struct drbd_device *device) { struct drbd_resource *resource = device->resource; struct drbd_connection *connection; struct drbd_peer_device *peer_device; int refs = 3; /* move to free_peer_device() */ for_each_peer_device(peer_device, device) drbd_debugfs_peer_device_cleanup(peer_device); drbd_debugfs_device_cleanup(device); for_each_connection(connection, resource) { idr_remove(&connection->peer_devices, device->vnr); refs++; } idr_remove(&resource->devices, device->vnr); idr_remove(&drbd_devices, device_to_minor(device)); del_gendisk(device->vdisk); synchronize_rcu(); kref_sub(&device->kref, refs, drbd_destroy_device); } static int __init drbd_init(void) { int err; if (minor_count < DRBD_MINOR_COUNT_MIN || minor_count > DRBD_MINOR_COUNT_MAX) { pr_err("invalid minor_count (%d)\n", minor_count); #ifdef MODULE return -EINVAL; #else minor_count = DRBD_MINOR_COUNT_DEF; #endif } err = register_blkdev(DRBD_MAJOR, "drbd"); if (err) { pr_err("unable to register block device major %d\n", DRBD_MAJOR); return err; } /* * allocate all necessary structs */ init_waitqueue_head(&drbd_pp_wait); drbd_proc = NULL; /* play safe for drbd_cleanup */ idr_init(&drbd_devices); rwlock_init(&global_state_lock); INIT_LIST_HEAD(&drbd_resources); err = drbd_genl_register(); if (err) { pr_err("unable to register generic netlink family\n"); goto fail; } err = drbd_create_mempools(); if (err) goto fail; err = -ENOMEM; drbd_proc = proc_create_data("drbd", S_IFREG | S_IRUGO , NULL, &drbd_proc_fops, NULL); if (!drbd_proc) { pr_err("unable to register proc file\n"); goto fail; } retry.wq = create_singlethread_workqueue("drbd-reissue"); if (!retry.wq) { pr_err("unable to create retry workqueue\n"); goto fail; } INIT_WORK(&retry.worker, do_retry); spin_lock_init(&retry.lock); INIT_LIST_HEAD(&retry.writes); if (drbd_debugfs_init()) pr_notice("failed to initialize debugfs -- will not be available\n"); pr_info("initialized. " "Version: " REL_VERSION " (api:%d/proto:%d-%d)\n", API_VERSION, PRO_VERSION_MIN, PRO_VERSION_MAX); pr_info("%s\n", drbd_buildtag()); pr_info("registered as block device major %d\n", DRBD_MAJOR); return 0; /* Success! */ fail: drbd_cleanup(); if (err == -ENOMEM) pr_err("ran out of memory\n"); else pr_err("initialization failure\n"); return err; } void drbd_free_ldev(struct drbd_backing_dev *ldev) { if (ldev == NULL) return; blkdev_put(ldev->backing_bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL); blkdev_put(ldev->md_bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL); kfree(ldev->disk_conf); kfree(ldev); } static void drbd_free_one_sock(struct drbd_socket *ds) { struct socket *s; mutex_lock(&ds->mutex); s = ds->socket; ds->socket = NULL; mutex_unlock(&ds->mutex); if (s) { /* so debugfs does not need to mutex_lock() */ synchronize_rcu(); kernel_sock_shutdown(s, SHUT_RDWR); sock_release(s); } } void drbd_free_sock(struct drbd_connection *connection) { if (connection->data.socket) drbd_free_one_sock(&connection->data); if (connection->meta.socket) drbd_free_one_sock(&connection->meta); } /* meta data management */ void conn_md_sync(struct drbd_connection *connection) { struct drbd_peer_device *peer_device; int vnr; rcu_read_lock(); idr_for_each_entry(&connection->peer_devices, peer_device, vnr) { struct drbd_device *device = peer_device->device; kref_get(&device->kref); rcu_read_unlock(); drbd_md_sync(device); kref_put(&device->kref, drbd_destroy_device); rcu_read_lock(); } rcu_read_unlock(); } /* aligned 4kByte */ struct meta_data_on_disk { u64 la_size_sect; /* last agreed size. */ u64 uuid[UI_SIZE]; /* UUIDs. */ u64 device_uuid; u64 reserved_u64_1; u32 flags; /* MDF */ u32 magic; u32 md_size_sect; u32 al_offset; /* offset to this block */ u32 al_nr_extents; /* important for restoring the AL (userspace) */ /* `-- act_log->nr_elements <-- ldev->dc.al_extents */ u32 bm_offset; /* offset to the bitmap, from here */ u32 bm_bytes_per_bit; /* BM_BLOCK_SIZE */ u32 la_peer_max_bio_size; /* last peer max_bio_size */ /* see al_tr_number_to_on_disk_sector() */ u32 al_stripes; u32 al_stripe_size_4k; u8 reserved_u8[4096 - (7*8 + 10*4)]; } __packed; void drbd_md_write(struct drbd_device *device, void *b) { struct meta_data_on_disk *buffer = b; sector_t sector; int i; memset(buffer, 0, sizeof(*buffer)); buffer->la_size_sect = cpu_to_be64(drbd_get_capacity(device->this_bdev)); for (i = UI_CURRENT; i < UI_SIZE; i++) buffer->uuid[i] = cpu_to_be64(device->ldev->md.uuid[i]); buffer->flags = cpu_to_be32(device->ldev->md.flags); buffer->magic = cpu_to_be32(DRBD_MD_MAGIC_84_UNCLEAN); buffer->md_size_sect = cpu_to_be32(device->ldev->md.md_size_sect); buffer->al_offset = cpu_to_be32(device->ldev->md.al_offset); buffer->al_nr_extents = cpu_to_be32(device->act_log->nr_elements); buffer->bm_bytes_per_bit = cpu_to_be32(BM_BLOCK_SIZE); buffer->device_uuid = cpu_to_be64(device->ldev->md.device_uuid); buffer->bm_offset = cpu_to_be32(device->ldev->md.bm_offset); buffer->la_peer_max_bio_size = cpu_to_be32(device->peer_max_bio_size); buffer->al_stripes = cpu_to_be32(device->ldev->md.al_stripes); buffer->al_stripe_size_4k = cpu_to_be32(device->ldev->md.al_stripe_size_4k); D_ASSERT(device, drbd_md_ss(device->ldev) == device->ldev->md.md_offset); sector = device->ldev->md.md_offset; if (drbd_md_sync_page_io(device, device->ldev, sector, WRITE)) { /* this was a try anyways ... */ drbd_err(device, "meta data update failed!\n"); drbd_chk_io_error(device, 1, DRBD_META_IO_ERROR); } } /** * drbd_md_sync() - Writes the meta data super block if the MD_DIRTY flag bit is set * @device: DRBD device. */ void drbd_md_sync(struct drbd_device *device) { struct meta_data_on_disk *buffer; /* Don't accidentally change the DRBD meta data layout. */ BUILD_BUG_ON(UI_SIZE != 4); BUILD_BUG_ON(sizeof(struct meta_data_on_disk) != 4096); del_timer(&device->md_sync_timer); /* timer may be rearmed by drbd_md_mark_dirty() now. */ if (!test_and_clear_bit(MD_DIRTY, &device->flags)) return; /* We use here D_FAILED and not D_ATTACHING because we try to write * metadata even if we detach due to a disk failure! */ if (!get_ldev_if_state(device, D_FAILED)) return; buffer = drbd_md_get_buffer(device, __func__); if (!buffer) goto out; drbd_md_write(device, buffer); /* Update device->ldev->md.la_size_sect, * since we updated it on metadata. */ device->ldev->md.la_size_sect = drbd_get_capacity(device->this_bdev); drbd_md_put_buffer(device); out: put_ldev(device); } static int check_activity_log_stripe_size(struct drbd_device *device, struct meta_data_on_disk *on_disk, struct drbd_md *in_core) { u32 al_stripes = be32_to_cpu(on_disk->al_stripes); u32 al_stripe_size_4k = be32_to_cpu(on_disk->al_stripe_size_4k); u64 al_size_4k; /* both not set: default to old fixed size activity log */ if (al_stripes == 0 && al_stripe_size_4k == 0) { al_stripes = 1; al_stripe_size_4k = MD_32kB_SECT/8; } /* some paranoia plausibility checks */ /* we need both values to be set */ if (al_stripes == 0 || al_stripe_size_4k == 0) goto err; al_size_4k = (u64)al_stripes * al_stripe_size_4k; /* Upper limit of activity log area, to avoid potential overflow * problems in al_tr_number_to_on_disk_sector(). As right now, more * than 72 * 4k blocks total only increases the amount of history, * limiting this arbitrarily to 16 GB is not a real limitation ;-) */ if (al_size_4k > (16 * 1024 * 1024/4)) goto err; /* Lower limit: we need at least 8 transaction slots (32kB) * to not break existing setups */ if (al_size_4k < MD_32kB_SECT/8) goto err; in_core->al_stripe_size_4k = al_stripe_size_4k; in_core->al_stripes = al_stripes; in_core->al_size_4k = al_size_4k; return 0; err: drbd_err(device, "invalid activity log striping: al_stripes=%u, al_stripe_size_4k=%u\n", al_stripes, al_stripe_size_4k); return -EINVAL; } static int check_offsets_and_sizes(struct drbd_device *device, struct drbd_backing_dev *bdev) { sector_t capacity = drbd_get_capacity(bdev->md_bdev); struct drbd_md *in_core = &bdev->md; s32 on_disk_al_sect; s32 on_disk_bm_sect; /* The on-disk size of the activity log, calculated from offsets, and * the size of the activity log calculated from the stripe settings, * should match. * Though we could relax this a bit: it is ok, if the striped activity log * fits in the available on-disk activity log size. * Right now, that would break how resize is implemented. * TODO: make drbd_determine_dev_size() (and the drbdmeta tool) aware * of possible unused padding space in the on disk layout. */ if (in_core->al_offset < 0) { if (in_core->bm_offset > in_core->al_offset) goto err; on_disk_al_sect = -in_core->al_offset; on_disk_bm_sect = in_core->al_offset - in_core->bm_offset; } else { if (in_core->al_offset != MD_4kB_SECT) goto err; if (in_core->bm_offset < in_core->al_offset + in_core->al_size_4k * MD_4kB_SECT) goto err; on_disk_al_sect = in_core->bm_offset - MD_4kB_SECT; on_disk_bm_sect = in_core->md_size_sect - in_core->bm_offset; } /* old fixed size meta data is exactly that: fixed. */ if (in_core->meta_dev_idx >= 0) { if (in_core->md_size_sect != MD_128MB_SECT || in_core->al_offset != MD_4kB_SECT || in_core->bm_offset != MD_4kB_SECT + MD_32kB_SECT || in_core->al_stripes != 1 || in_core->al_stripe_size_4k != MD_32kB_SECT/8) goto err; } if (capacity < in_core->md_size_sect) goto err; if (capacity - in_core->md_size_sect < drbd_md_first_sector(bdev)) goto err; /* should be aligned, and at least 32k */ if ((on_disk_al_sect & 7) || (on_disk_al_sect < MD_32kB_SECT)) goto err; /* should fit (for now: exactly) into the available on-disk space; * overflow prevention is in check_activity_log_stripe_size() above. */ if (on_disk_al_sect != in_core->al_size_4k * MD_4kB_SECT) goto err; /* again, should be aligned */ if (in_core->bm_offset & 7) goto err; /* FIXME check for device grow with flex external meta data? */ /* can the available bitmap space cover the last agreed device size? */ if (on_disk_bm_sect < (in_core->la_size_sect+7)/MD_4kB_SECT/8/512) goto err; return 0; err: drbd_err(device, "meta data offsets don't make sense: idx=%d " "al_s=%u, al_sz4k=%u, al_offset=%d, bm_offset=%d, " "md_size_sect=%u, la_size=%llu, md_capacity=%llu\n", in_core->meta_dev_idx, in_core->al_stripes, in_core->al_stripe_size_4k, in_core->al_offset, in_core->bm_offset, in_core->md_size_sect, (unsigned long long)in_core->la_size_sect, (unsigned long long)capacity); return -EINVAL; } /** * drbd_md_read() - Reads in the meta data super block * @device: DRBD device. * @bdev: Device from which the meta data should be read in. * * Return NO_ERROR on success, and an enum drbd_ret_code in case * something goes wrong. * * Called exactly once during drbd_adm_attach(), while still being D_DISKLESS, * even before @bdev is assigned to @device->ldev. */ int drbd_md_read(struct drbd_device *device, struct drbd_backing_dev *bdev) { struct meta_data_on_disk *buffer; u32 magic, flags; int i, rv = NO_ERROR; if (device->state.disk != D_DISKLESS) return ERR_DISK_CONFIGURED; buffer = drbd_md_get_buffer(device, __func__); if (!buffer) return ERR_NOMEM; /* First, figure out where our meta data superblock is located, * and read it. */ bdev->md.meta_dev_idx = bdev->disk_conf->meta_dev_idx; bdev->md.md_offset = drbd_md_ss(bdev); if (drbd_md_sync_page_io(device, bdev, bdev->md.md_offset, READ)) { /* NOTE: can't do normal error processing here as this is called BEFORE disk is attached */ drbd_err(device, "Error while reading metadata.\n"); rv = ERR_IO_MD_DISK; goto err; } magic = be32_to_cpu(buffer->magic); flags = be32_to_cpu(buffer->flags); if (magic == DRBD_MD_MAGIC_84_UNCLEAN || (magic == DRBD_MD_MAGIC_08 && !(flags & MDF_AL_CLEAN))) { /* btw: that's Activity Log clean, not "all" clean. */ drbd_err(device, "Found unclean meta data. Did you \"drbdadm apply-al\"?\n"); rv = ERR_MD_UNCLEAN; goto err; } rv = ERR_MD_INVALID; if (magic != DRBD_MD_MAGIC_08) { if (magic == DRBD_MD_MAGIC_07) drbd_err(device, "Found old (0.7) meta data magic. Did you \"drbdadm create-md\"?\n"); else drbd_err(device, "Meta data magic not found. Did you \"drbdadm create-md\"?\n"); goto err; } if (be32_to_cpu(buffer->bm_bytes_per_bit) != BM_BLOCK_SIZE) { drbd_err(device, "unexpected bm_bytes_per_bit: %u (expected %u)\n", be32_to_cpu(buffer->bm_bytes_per_bit), BM_BLOCK_SIZE); goto err; } /* convert to in_core endian */ bdev->md.la_size_sect = be64_to_cpu(buffer->la_size_sect); for (i = UI_CURRENT; i < UI_SIZE; i++) bdev->md.uuid[i] = be64_to_cpu(buffer->uuid[i]); bdev->md.flags = be32_to_cpu(buffer->flags); bdev->md.device_uuid = be64_to_cpu(buffer->device_uuid); bdev->md.md_size_sect = be32_to_cpu(buffer->md_size_sect); bdev->md.al_offset = be32_to_cpu(buffer->al_offset); bdev->md.bm_offset = be32_to_cpu(buffer->bm_offset); if (check_activity_log_stripe_size(device, buffer, &bdev->md)) goto err; if (check_offsets_and_sizes(device, bdev)) goto err; if (be32_to_cpu(buffer->bm_offset) != bdev->md.bm_offset) { drbd_err(device, "unexpected bm_offset: %d (expected %d)\n", be32_to_cpu(buffer->bm_offset), bdev->md.bm_offset); goto err; } if (be32_to_cpu(buffer->md_size_sect) != bdev->md.md_size_sect) { drbd_err(device, "unexpected md_size: %u (expected %u)\n", be32_to_cpu(buffer->md_size_sect), bdev->md.md_size_sect); goto err; } rv = NO_ERROR; spin_lock_irq(&device->resource->req_lock); if (device->state.conn < C_CONNECTED) { unsigned int peer; peer = be32_to_cpu(buffer->la_peer_max_bio_size); peer = max(peer, DRBD_MAX_BIO_SIZE_SAFE); device->peer_max_bio_size = peer; } spin_unlock_irq(&device->resource->req_lock); err: drbd_md_put_buffer(device); return rv; } /** * drbd_md_mark_dirty() - Mark meta data super block as dirty * @device: DRBD device. * * Call this function if you change anything that should be written to * the meta-data super block. This function sets MD_DIRTY, and starts a * timer that ensures that within five seconds you have to call drbd_md_sync(). */ #ifdef DEBUG void drbd_md_mark_dirty_(struct drbd_device *device, unsigned int line, const char *func) { if (!test_and_set_bit(MD_DIRTY, &device->flags)) { mod_timer(&device->md_sync_timer, jiffies + HZ); device->last_md_mark_dirty.line = line; device->last_md_mark_dirty.func = func; } } #else void drbd_md_mark_dirty(struct drbd_device *device) { if (!test_and_set_bit(MD_DIRTY, &device->flags)) mod_timer(&device->md_sync_timer, jiffies + 5*HZ); } #endif void drbd_uuid_move_history(struct drbd_device *device) __must_hold(local) { int i; for (i = UI_HISTORY_START; i < UI_HISTORY_END; i++) device->ldev->md.uuid[i+1] = device->ldev->md.uuid[i]; } void __drbd_uuid_set(struct drbd_device *device, int idx, u64 val) __must_hold(local) { if (idx == UI_CURRENT) { if (device->state.role == R_PRIMARY) val |= 1; else val &= ~((u64)1); drbd_set_ed_uuid(device, val); } device->ldev->md.uuid[idx] = val; drbd_md_mark_dirty(device); } void _drbd_uuid_set(struct drbd_device *device, int idx, u64 val) __must_hold(local) { unsigned long flags; spin_lock_irqsave(&device->ldev->md.uuid_lock, flags); __drbd_uuid_set(device, idx, val); spin_unlock_irqrestore(&device->ldev->md.uuid_lock, flags); } void drbd_uuid_set(struct drbd_device *device, int idx, u64 val) __must_hold(local) { unsigned long flags; spin_lock_irqsave(&device->ldev->md.uuid_lock, flags); if (device->ldev->md.uuid[idx]) { drbd_uuid_move_history(device); device->ldev->md.uuid[UI_HISTORY_START] = device->ldev->md.uuid[idx]; } __drbd_uuid_set(device, idx, val); spin_unlock_irqrestore(&device->ldev->md.uuid_lock, flags); } /** * drbd_uuid_new_current() - Creates a new current UUID * @device: DRBD device. * * Creates a new current UUID, and rotates the old current UUID into * the bitmap slot. Causes an incremental resync upon next connect. */ void drbd_uuid_new_current(struct drbd_device *device) __must_hold(local) { u64 val; unsigned long long bm_uuid; get_random_bytes(&val, sizeof(u64)); spin_lock_irq(&device->ldev->md.uuid_lock); bm_uuid = device->ldev->md.uuid[UI_BITMAP]; if (bm_uuid) drbd_warn(device, "bm UUID was already set: %llX\n", bm_uuid); device->ldev->md.uuid[UI_BITMAP] = device->ldev->md.uuid[UI_CURRENT]; __drbd_uuid_set(device, UI_CURRENT, val); spin_unlock_irq(&device->ldev->md.uuid_lock); drbd_print_uuids(device, "new current UUID"); /* get it to stable storage _now_ */ drbd_md_sync(device); } void drbd_uuid_set_bm(struct drbd_device *device, u64 val) __must_hold(local) { unsigned long flags; if (device->ldev->md.uuid[UI_BITMAP] == 0 && val == 0) return; spin_lock_irqsave(&device->ldev->md.uuid_lock, flags); if (val == 0) { drbd_uuid_move_history(device); device->ldev->md.uuid[UI_HISTORY_START] = device->ldev->md.uuid[UI_BITMAP]; device->ldev->md.uuid[UI_BITMAP] = 0; } else { unsigned long long bm_uuid = device->ldev->md.uuid[UI_BITMAP]; if (bm_uuid) drbd_warn(device, "bm UUID was already set: %llX\n", bm_uuid); device->ldev->md.uuid[UI_BITMAP] = val & ~((u64)1); } spin_unlock_irqrestore(&device->ldev->md.uuid_lock, flags); drbd_md_mark_dirty(device); } /** * drbd_bmio_set_n_write() - io_fn for drbd_queue_bitmap_io() or drbd_bitmap_io() * @device: DRBD device. * * Sets all bits in the bitmap and writes the whole bitmap to stable storage. */ int drbd_bmio_set_n_write(struct drbd_device *device) __must_hold(local) { int rv = -EIO; drbd_md_set_flag(device, MDF_FULL_SYNC); drbd_md_sync(device); drbd_bm_set_all(device); rv = drbd_bm_write(device); if (!rv) { drbd_md_clear_flag(device, MDF_FULL_SYNC); drbd_md_sync(device); } return rv; } /** * drbd_bmio_clear_n_write() - io_fn for drbd_queue_bitmap_io() or drbd_bitmap_io() * @device: DRBD device. * * Clears all bits in the bitmap and writes the whole bitmap to stable storage. */ int drbd_bmio_clear_n_write(struct drbd_device *device) __must_hold(local) { drbd_resume_al(device); drbd_bm_clear_all(device); return drbd_bm_write(device); } static int w_bitmap_io(struct drbd_work *w, int unused) { struct drbd_device *device = container_of(w, struct drbd_device, bm_io_work.w); struct bm_io_work *work = &device->bm_io_work; int rv = -EIO; D_ASSERT(device, atomic_read(&device->ap_bio_cnt) == 0); if (get_ldev(device)) { drbd_bm_lock(device, work->why, work->flags); rv = work->io_fn(device); drbd_bm_unlock(device); put_ldev(device); } clear_bit_unlock(BITMAP_IO, &device->flags); wake_up(&device->misc_wait); if (work->done) work->done(device, rv); clear_bit(BITMAP_IO_QUEUED, &device->flags); work->why = NULL; work->flags = 0; return 0; } /** * drbd_queue_bitmap_io() - Queues an IO operation on the whole bitmap * @device: DRBD device. * @io_fn: IO callback to be called when bitmap IO is possible * @done: callback to be called after the bitmap IO was performed * @why: Descriptive text of the reason for doing the IO * * While IO on the bitmap happens we freeze application IO thus we ensure * that drbd_set_out_of_sync() can not be called. This function MAY ONLY be * called from worker context. It MUST NOT be used while a previous such * work is still pending! * * Its worker function encloses the call of io_fn() by get_ldev() and * put_ldev(). */ void drbd_queue_bitmap_io(struct drbd_device *device, int (*io_fn)(struct drbd_device *), void (*done)(struct drbd_device *, int), char *why, enum bm_flag flags) { D_ASSERT(device, current == first_peer_device(device)->connection->worker.task); D_ASSERT(device, !test_bit(BITMAP_IO_QUEUED, &device->flags)); D_ASSERT(device, !test_bit(BITMAP_IO, &device->flags)); D_ASSERT(device, list_empty(&device->bm_io_work.w.list)); if (device->bm_io_work.why) drbd_err(device, "FIXME going to queue '%s' but '%s' still pending?\n", why, device->bm_io_work.why); device->bm_io_work.io_fn = io_fn; device->bm_io_work.done = done; device->bm_io_work.why = why; device->bm_io_work.flags = flags; spin_lock_irq(&device->resource->req_lock); set_bit(BITMAP_IO, &device->flags); if (atomic_read(&device->ap_bio_cnt) == 0) { if (!test_and_set_bit(BITMAP_IO_QUEUED, &device->flags)) drbd_queue_work(&first_peer_device(device)->connection->sender_work, &device->bm_io_work.w); } spin_unlock_irq(&device->resource->req_lock); } /** * drbd_bitmap_io() - Does an IO operation on the whole bitmap * @device: DRBD device. * @io_fn: IO callback to be called when bitmap IO is possible * @why: Descriptive text of the reason for doing the IO * * freezes application IO while that the actual IO operations runs. This * functions MAY NOT be called from worker context. */ int drbd_bitmap_io(struct drbd_device *device, int (*io_fn)(struct drbd_device *), char *why, enum bm_flag flags) { int rv; D_ASSERT(device, current != first_peer_device(device)->connection->worker.task); if ((flags & BM_LOCKED_SET_ALLOWED) == 0) drbd_suspend_io(device); drbd_bm_lock(device, why, flags); rv = io_fn(device); drbd_bm_unlock(device); if ((flags & BM_LOCKED_SET_ALLOWED) == 0) drbd_resume_io(device); return rv; } void drbd_md_set_flag(struct drbd_device *device, int flag) __must_hold(local) { if ((device->ldev->md.flags & flag) != flag) { drbd_md_mark_dirty(device); device->ldev->md.flags |= flag; } } void drbd_md_clear_flag(struct drbd_device *device, int flag) __must_hold(local) { if ((device->ldev->md.flags & flag) != 0) { drbd_md_mark_dirty(device); device->ldev->md.flags &= ~flag; } } int drbd_md_test_flag(struct drbd_backing_dev *bdev, int flag) { return (bdev->md.flags & flag) != 0; } static void md_sync_timer_fn(unsigned long data) { struct drbd_device *device = (struct drbd_device *) data; drbd_device_post_work(device, MD_SYNC); } const char *cmdname(enum drbd_packet cmd) { /* THINK may need to become several global tables * when we want to support more than * one PRO_VERSION */ static const char *cmdnames[] = { [P_DATA] = "Data", [P_DATA_REPLY] = "DataReply", [P_RS_DATA_REPLY] = "RSDataReply", [P_BARRIER] = "Barrier", [P_BITMAP] = "ReportBitMap", [P_BECOME_SYNC_TARGET] = "BecomeSyncTarget", [P_BECOME_SYNC_SOURCE] = "BecomeSyncSource", [P_UNPLUG_REMOTE] = "UnplugRemote", [P_DATA_REQUEST] = "DataRequest", [P_RS_DATA_REQUEST] = "RSDataRequest", [P_SYNC_PARAM] = "SyncParam", [P_SYNC_PARAM89] = "SyncParam89", [P_PROTOCOL] = "ReportProtocol", [P_UUIDS] = "ReportUUIDs", [P_SIZES] = "ReportSizes", [P_STATE] = "ReportState", [P_SYNC_UUID] = "ReportSyncUUID", [P_AUTH_CHALLENGE] = "AuthChallenge", [P_AUTH_RESPONSE] = "AuthResponse", [P_PING] = "Ping", [P_PING_ACK] = "PingAck", [P_RECV_ACK] = "RecvAck", [P_WRITE_ACK] = "WriteAck", [P_RS_WRITE_ACK] = "RSWriteAck", [P_SUPERSEDED] = "Superseded", [P_NEG_ACK] = "NegAck", [P_NEG_DREPLY] = "NegDReply", [P_NEG_RS_DREPLY] = "NegRSDReply", [P_BARRIER_ACK] = "BarrierAck", [P_STATE_CHG_REQ] = "StateChgRequest", [P_STATE_CHG_REPLY] = "StateChgReply", [P_OV_REQUEST] = "OVRequest", [P_OV_REPLY] = "OVReply", [P_OV_RESULT] = "OVResult", [P_CSUM_RS_REQUEST] = "CsumRSRequest", [P_RS_IS_IN_SYNC] = "CsumRSIsInSync", [P_COMPRESSED_BITMAP] = "CBitmap", [P_DELAY_PROBE] = "DelayProbe", [P_OUT_OF_SYNC] = "OutOfSync", [P_RETRY_WRITE] = "RetryWrite", [P_RS_CANCEL] = "RSCancel", [P_CONN_ST_CHG_REQ] = "conn_st_chg_req", [P_CONN_ST_CHG_REPLY] = "conn_st_chg_reply", [P_RETRY_WRITE] = "retry_write", [P_PROTOCOL_UPDATE] = "protocol_update", /* enum drbd_packet, but not commands - obsoleted flags: * P_MAY_IGNORE * P_MAX_OPT_CMD */ }; /* too big for the array: 0xfffX */ if (cmd == P_INITIAL_META) return "InitialMeta"; if (cmd == P_INITIAL_DATA) return "InitialData"; if (cmd == P_CONNECTION_FEATURES) return "ConnectionFeatures"; if (cmd >= ARRAY_SIZE(cmdnames)) return "Unknown"; return cmdnames[cmd]; } /** * drbd_wait_misc - wait for a request to make progress * @device: device associated with the request * @i: the struct drbd_interval embedded in struct drbd_request or * struct drbd_peer_request */ int drbd_wait_misc(struct drbd_device *device, struct drbd_interval *i) { struct net_conf *nc; DEFINE_WAIT(wait); long timeout; rcu_read_lock(); nc = rcu_dereference(first_peer_device(device)->connection->net_conf); if (!nc) { rcu_read_unlock(); return -ETIMEDOUT; } timeout = nc->ko_count ? nc->timeout * HZ / 10 * nc->ko_count : MAX_SCHEDULE_TIMEOUT; rcu_read_unlock(); /* Indicate to wake up device->misc_wait on progress. */ i->waiting = true; prepare_to_wait(&device->misc_wait, &wait, TASK_INTERRUPTIBLE); spin_unlock_irq(&device->resource->req_lock); timeout = schedule_timeout(timeout); finish_wait(&device->misc_wait, &wait); spin_lock_irq(&device->resource->req_lock); if (!timeout || device->state.conn < C_CONNECTED) return -ETIMEDOUT; if (signal_pending(current)) return -ERESTARTSYS; return 0; } #ifdef CONFIG_DRBD_FAULT_INJECTION /* Fault insertion support including random number generator shamelessly * stolen from kernel/rcutorture.c */ struct fault_random_state { unsigned long state; unsigned long count; }; #define FAULT_RANDOM_MULT 39916801 /* prime */ #define FAULT_RANDOM_ADD 479001701 /* prime */ #define FAULT_RANDOM_REFRESH 10000 /* * Crude but fast random-number generator. Uses a linear congruential * generator, with occasional help from get_random_bytes(). */ static unsigned long _drbd_fault_random(struct fault_random_state *rsp) { long refresh; if (!rsp->count--) { get_random_bytes(&refresh, sizeof(refresh)); rsp->state += refresh; rsp->count = FAULT_RANDOM_REFRESH; } rsp->state = rsp->state * FAULT_RANDOM_MULT + FAULT_RANDOM_ADD; return swahw32(rsp->state); } static char * _drbd_fault_str(unsigned int type) { static char *_faults[] = { [DRBD_FAULT_MD_WR] = "Meta-data write", [DRBD_FAULT_MD_RD] = "Meta-data read", [DRBD_FAULT_RS_WR] = "Resync write", [DRBD_FAULT_RS_RD] = "Resync read", [DRBD_FAULT_DT_WR] = "Data write", [DRBD_FAULT_DT_RD] = "Data read", [DRBD_FAULT_DT_RA] = "Data read ahead", [DRBD_FAULT_BM_ALLOC] = "BM allocation", [DRBD_FAULT_AL_EE] = "EE allocation", [DRBD_FAULT_RECEIVE] = "receive data corruption", }; return (type < DRBD_FAULT_MAX) ? _faults[type] : "**Unknown**"; } unsigned int _drbd_insert_fault(struct drbd_device *device, unsigned int type) { static struct fault_random_state rrs = {0, 0}; unsigned int ret = ( (fault_devs == 0 || ((1 << device_to_minor(device)) & fault_devs) != 0) && (((_drbd_fault_random(&rrs) % 100) + 1) <= fault_rate)); if (ret) { fault_count++; if (__ratelimit(&drbd_ratelimit_state)) drbd_warn(device, "***Simulating %s failure\n", _drbd_fault_str(type)); } return ret; } #endif const char *drbd_buildtag(void) { /* DRBD built from external sources has here a reference to the git hash of the source code. */ static char buildtag[38] = "\0uilt-in"; if (buildtag[0] == 0) { #ifdef MODULE sprintf(buildtag, "srcversion: %-24s", THIS_MODULE->srcversion); #else buildtag[0] = 'b'; #endif } return buildtag; } module_init(drbd_init) module_exit(drbd_cleanup) EXPORT_SYMBOL(drbd_conn_str); EXPORT_SYMBOL(drbd_role_str); EXPORT_SYMBOL(drbd_disk_str); EXPORT_SYMBOL(drbd_set_st_err_str);
gpl-2.0
mwalt2/shooter-2.6.35_mr-kernel
fs/jffs2/fs.c
729
19647
/* * JFFS2 -- Journalling Flash File System, Version 2. * * Copyright © 2001-2007 Red Hat, Inc. * * Created by David Woodhouse <dwmw2@infradead.org> * * For licensing information, see the file 'LICENCE' in this directory. * */ #include <linux/capability.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/fs.h> #include <linux/list.h> #include <linux/mtd/mtd.h> #include <linux/pagemap.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/vfs.h> #include <linux/crc32.h> #include <linux/smp_lock.h> #include "nodelist.h" static int jffs2_flash_setup(struct jffs2_sb_info *c); int jffs2_do_setattr (struct inode *inode, struct iattr *iattr) { struct jffs2_full_dnode *old_metadata, *new_metadata; struct jffs2_inode_info *f = JFFS2_INODE_INFO(inode); struct jffs2_sb_info *c = JFFS2_SB_INFO(inode->i_sb); struct jffs2_raw_inode *ri; union jffs2_device_node dev; unsigned char *mdata = NULL; int mdatalen = 0; unsigned int ivalid; uint32_t alloclen; int ret; int alloc_type = ALLOC_NORMAL; D1(printk(KERN_DEBUG "jffs2_setattr(): ino #%lu\n", inode->i_ino)); /* Special cases - we don't want more than one data node for these types on the medium at any time. So setattr must read the original data associated with the node (i.e. the device numbers or the target name) and write it out again with the appropriate data attached */ if (S_ISBLK(inode->i_mode) || S_ISCHR(inode->i_mode)) { /* For these, we don't actually need to read the old node */ mdatalen = jffs2_encode_dev(&dev, inode->i_rdev); mdata = (char *)&dev; D1(printk(KERN_DEBUG "jffs2_setattr(): Writing %d bytes of kdev_t\n", mdatalen)); } else if (S_ISLNK(inode->i_mode)) { mutex_lock(&f->sem); mdatalen = f->metadata->size; mdata = kmalloc(f->metadata->size, GFP_USER); if (!mdata) { mutex_unlock(&f->sem); return -ENOMEM; } ret = jffs2_read_dnode(c, f, f->metadata, mdata, 0, mdatalen); if (ret) { mutex_unlock(&f->sem); kfree(mdata); return ret; } mutex_unlock(&f->sem); D1(printk(KERN_DEBUG "jffs2_setattr(): Writing %d bytes of symlink target\n", mdatalen)); } ri = jffs2_alloc_raw_inode(); if (!ri) { if (S_ISLNK(inode->i_mode)) kfree(mdata); return -ENOMEM; } ret = jffs2_reserve_space(c, sizeof(*ri) + mdatalen, &alloclen, ALLOC_NORMAL, JFFS2_SUMMARY_INODE_SIZE); if (ret) { jffs2_free_raw_inode(ri); if (S_ISLNK(inode->i_mode & S_IFMT)) kfree(mdata); return ret; } mutex_lock(&f->sem); ivalid = iattr->ia_valid; ri->magic = cpu_to_je16(JFFS2_MAGIC_BITMASK); ri->nodetype = cpu_to_je16(JFFS2_NODETYPE_INODE); ri->totlen = cpu_to_je32(sizeof(*ri) + mdatalen); ri->hdr_crc = cpu_to_je32(crc32(0, ri, sizeof(struct jffs2_unknown_node)-4)); ri->ino = cpu_to_je32(inode->i_ino); ri->version = cpu_to_je32(++f->highest_version); ri->uid = cpu_to_je16((ivalid & ATTR_UID)?iattr->ia_uid:inode->i_uid); ri->gid = cpu_to_je16((ivalid & ATTR_GID)?iattr->ia_gid:inode->i_gid); if (ivalid & ATTR_MODE) ri->mode = cpu_to_jemode(iattr->ia_mode); else ri->mode = cpu_to_jemode(inode->i_mode); ri->isize = cpu_to_je32((ivalid & ATTR_SIZE)?iattr->ia_size:inode->i_size); ri->atime = cpu_to_je32(I_SEC((ivalid & ATTR_ATIME)?iattr->ia_atime:inode->i_atime)); ri->mtime = cpu_to_je32(I_SEC((ivalid & ATTR_MTIME)?iattr->ia_mtime:inode->i_mtime)); ri->ctime = cpu_to_je32(I_SEC((ivalid & ATTR_CTIME)?iattr->ia_ctime:inode->i_ctime)); ri->offset = cpu_to_je32(0); ri->csize = ri->dsize = cpu_to_je32(mdatalen); ri->compr = JFFS2_COMPR_NONE; if (ivalid & ATTR_SIZE && inode->i_size < iattr->ia_size) { /* It's an extension. Make it a hole node */ ri->compr = JFFS2_COMPR_ZERO; ri->dsize = cpu_to_je32(iattr->ia_size - inode->i_size); ri->offset = cpu_to_je32(inode->i_size); } else if (ivalid & ATTR_SIZE && !iattr->ia_size) { /* For truncate-to-zero, treat it as deletion because it'll always be obsoleting all previous nodes */ alloc_type = ALLOC_DELETION; } ri->node_crc = cpu_to_je32(crc32(0, ri, sizeof(*ri)-8)); if (mdatalen) ri->data_crc = cpu_to_je32(crc32(0, mdata, mdatalen)); else ri->data_crc = cpu_to_je32(0); new_metadata = jffs2_write_dnode(c, f, ri, mdata, mdatalen, alloc_type); if (S_ISLNK(inode->i_mode)) kfree(mdata); if (IS_ERR(new_metadata)) { jffs2_complete_reservation(c); jffs2_free_raw_inode(ri); mutex_unlock(&f->sem); return PTR_ERR(new_metadata); } /* It worked. Update the inode */ inode->i_atime = ITIME(je32_to_cpu(ri->atime)); inode->i_ctime = ITIME(je32_to_cpu(ri->ctime)); inode->i_mtime = ITIME(je32_to_cpu(ri->mtime)); inode->i_mode = jemode_to_cpu(ri->mode); inode->i_uid = je16_to_cpu(ri->uid); inode->i_gid = je16_to_cpu(ri->gid); old_metadata = f->metadata; if (ivalid & ATTR_SIZE && inode->i_size > iattr->ia_size) jffs2_truncate_fragtree (c, &f->fragtree, iattr->ia_size); if (ivalid & ATTR_SIZE && inode->i_size < iattr->ia_size) { jffs2_add_full_dnode_to_inode(c, f, new_metadata); inode->i_size = iattr->ia_size; inode->i_blocks = (inode->i_size + 511) >> 9; f->metadata = NULL; } else { f->metadata = new_metadata; } if (old_metadata) { jffs2_mark_node_obsolete(c, old_metadata->raw); jffs2_free_full_dnode(old_metadata); } jffs2_free_raw_inode(ri); mutex_unlock(&f->sem); jffs2_complete_reservation(c); /* We have to do the simple_setsize() without f->sem held, since some pages may be locked and waiting for it in readpage(). We are protected from a simultaneous write() extending i_size back past iattr->ia_size, because do_truncate() holds the generic inode semaphore. */ if (ivalid & ATTR_SIZE && inode->i_size > iattr->ia_size) { simple_setsize(inode, iattr->ia_size); inode->i_blocks = (inode->i_size + 511) >> 9; } return 0; } int jffs2_setattr(struct dentry *dentry, struct iattr *iattr) { int rc; rc = inode_change_ok(dentry->d_inode, iattr); if (rc) return rc; rc = jffs2_do_setattr(dentry->d_inode, iattr); if (!rc && (iattr->ia_valid & ATTR_MODE)) rc = jffs2_acl_chmod(dentry->d_inode); return rc; } int jffs2_statfs(struct dentry *dentry, struct kstatfs *buf) { struct jffs2_sb_info *c = JFFS2_SB_INFO(dentry->d_sb); unsigned long avail; buf->f_type = JFFS2_SUPER_MAGIC; buf->f_bsize = 1 << PAGE_SHIFT; buf->f_blocks = c->flash_size >> PAGE_SHIFT; buf->f_files = 0; buf->f_ffree = 0; buf->f_namelen = JFFS2_MAX_NAME_LEN; buf->f_fsid.val[0] = JFFS2_SUPER_MAGIC; buf->f_fsid.val[1] = c->mtd->index; spin_lock(&c->erase_completion_lock); avail = c->dirty_size + c->free_size; if (avail > c->sector_size * c->resv_blocks_write) avail -= c->sector_size * c->resv_blocks_write; else avail = 0; spin_unlock(&c->erase_completion_lock); buf->f_bavail = buf->f_bfree = avail >> PAGE_SHIFT; return 0; } void jffs2_clear_inode (struct inode *inode) { /* We can forget about this inode for now - drop all * the nodelists associated with it, etc. */ struct jffs2_sb_info *c = JFFS2_SB_INFO(inode->i_sb); struct jffs2_inode_info *f = JFFS2_INODE_INFO(inode); D1(printk(KERN_DEBUG "jffs2_clear_inode(): ino #%lu mode %o\n", inode->i_ino, inode->i_mode)); jffs2_do_clear_inode(c, f); } struct inode *jffs2_iget(struct super_block *sb, unsigned long ino) { struct jffs2_inode_info *f; struct jffs2_sb_info *c; struct jffs2_raw_inode latest_node; union jffs2_device_node jdev; struct inode *inode; dev_t rdev = 0; int ret; D1(printk(KERN_DEBUG "jffs2_iget(): ino == %lu\n", ino)); inode = iget_locked(sb, ino); if (!inode) return ERR_PTR(-ENOMEM); if (!(inode->i_state & I_NEW)) return inode; f = JFFS2_INODE_INFO(inode); c = JFFS2_SB_INFO(inode->i_sb); jffs2_init_inode_info(f); mutex_lock(&f->sem); ret = jffs2_do_read_inode(c, f, inode->i_ino, &latest_node); if (ret) { mutex_unlock(&f->sem); iget_failed(inode); return ERR_PTR(ret); } inode->i_mode = jemode_to_cpu(latest_node.mode); inode->i_uid = je16_to_cpu(latest_node.uid); inode->i_gid = je16_to_cpu(latest_node.gid); inode->i_size = je32_to_cpu(latest_node.isize); inode->i_atime = ITIME(je32_to_cpu(latest_node.atime)); inode->i_mtime = ITIME(je32_to_cpu(latest_node.mtime)); inode->i_ctime = ITIME(je32_to_cpu(latest_node.ctime)); inode->i_nlink = f->inocache->pino_nlink; inode->i_blocks = (inode->i_size + 511) >> 9; switch (inode->i_mode & S_IFMT) { case S_IFLNK: inode->i_op = &jffs2_symlink_inode_operations; break; case S_IFDIR: { struct jffs2_full_dirent *fd; inode->i_nlink = 2; /* parent and '.' */ for (fd=f->dents; fd; fd = fd->next) { if (fd->type == DT_DIR && fd->ino) inc_nlink(inode); } /* Root dir gets i_nlink 3 for some reason */ if (inode->i_ino == 1) inc_nlink(inode); inode->i_op = &jffs2_dir_inode_operations; inode->i_fop = &jffs2_dir_operations; break; } case S_IFREG: inode->i_op = &jffs2_file_inode_operations; inode->i_fop = &jffs2_file_operations; inode->i_mapping->a_ops = &jffs2_file_address_operations; inode->i_mapping->nrpages = 0; break; case S_IFBLK: case S_IFCHR: /* Read the device numbers from the media */ if (f->metadata->size != sizeof(jdev.old_id) && f->metadata->size != sizeof(jdev.new_id)) { printk(KERN_NOTICE "Device node has strange size %d\n", f->metadata->size); goto error_io; } D1(printk(KERN_DEBUG "Reading device numbers from flash\n")); ret = jffs2_read_dnode(c, f, f->metadata, (char *)&jdev, 0, f->metadata->size); if (ret < 0) { /* Eep */ printk(KERN_NOTICE "Read device numbers for inode %lu failed\n", (unsigned long)inode->i_ino); goto error; } if (f->metadata->size == sizeof(jdev.old_id)) rdev = old_decode_dev(je16_to_cpu(jdev.old_id)); else rdev = new_decode_dev(je32_to_cpu(jdev.new_id)); case S_IFSOCK: case S_IFIFO: inode->i_op = &jffs2_file_inode_operations; init_special_inode(inode, inode->i_mode, rdev); break; default: printk(KERN_WARNING "jffs2_read_inode(): Bogus imode %o for ino %lu\n", inode->i_mode, (unsigned long)inode->i_ino); } mutex_unlock(&f->sem); D1(printk(KERN_DEBUG "jffs2_read_inode() returning\n")); unlock_new_inode(inode); return inode; error_io: ret = -EIO; error: mutex_unlock(&f->sem); jffs2_do_clear_inode(c, f); iget_failed(inode); return ERR_PTR(ret); } void jffs2_dirty_inode(struct inode *inode) { struct iattr iattr; if (!(inode->i_state & I_DIRTY_DATASYNC)) { D2(printk(KERN_DEBUG "jffs2_dirty_inode() not calling setattr() for ino #%lu\n", inode->i_ino)); return; } D1(printk(KERN_DEBUG "jffs2_dirty_inode() calling setattr() for ino #%lu\n", inode->i_ino)); iattr.ia_valid = ATTR_MODE|ATTR_UID|ATTR_GID|ATTR_ATIME|ATTR_MTIME|ATTR_CTIME; iattr.ia_mode = inode->i_mode; iattr.ia_uid = inode->i_uid; iattr.ia_gid = inode->i_gid; iattr.ia_atime = inode->i_atime; iattr.ia_mtime = inode->i_mtime; iattr.ia_ctime = inode->i_ctime; jffs2_do_setattr(inode, &iattr); } int jffs2_remount_fs (struct super_block *sb, int *flags, char *data) { struct jffs2_sb_info *c = JFFS2_SB_INFO(sb); if (c->flags & JFFS2_SB_FLAG_RO && !(sb->s_flags & MS_RDONLY)) return -EROFS; /* We stop if it was running, then restart if it needs to. This also catches the case where it was stopped and this is just a remount to restart it. Flush the writebuffer, if neccecary, else we loose it */ lock_kernel(); if (!(sb->s_flags & MS_RDONLY)) { jffs2_stop_garbage_collect_thread(c); mutex_lock(&c->alloc_sem); jffs2_flush_wbuf_pad(c); mutex_unlock(&c->alloc_sem); } if (!(*flags & MS_RDONLY)) jffs2_start_garbage_collect_thread(c); *flags |= MS_NOATIME; unlock_kernel(); return 0; } /* jffs2_new_inode: allocate a new inode and inocache, add it to the hash, fill in the raw_inode while you're at it. */ struct inode *jffs2_new_inode (struct inode *dir_i, int mode, struct jffs2_raw_inode *ri) { struct inode *inode; struct super_block *sb = dir_i->i_sb; struct jffs2_sb_info *c; struct jffs2_inode_info *f; int ret; D1(printk(KERN_DEBUG "jffs2_new_inode(): dir_i %ld, mode 0x%x\n", dir_i->i_ino, mode)); c = JFFS2_SB_INFO(sb); inode = new_inode(sb); if (!inode) return ERR_PTR(-ENOMEM); f = JFFS2_INODE_INFO(inode); jffs2_init_inode_info(f); mutex_lock(&f->sem); memset(ri, 0, sizeof(*ri)); /* Set OS-specific defaults for new inodes */ ri->uid = cpu_to_je16(current_fsuid()); if (dir_i->i_mode & S_ISGID) { ri->gid = cpu_to_je16(dir_i->i_gid); if (S_ISDIR(mode)) mode |= S_ISGID; } else { ri->gid = cpu_to_je16(current_fsgid()); } /* POSIX ACLs have to be processed now, at least partly. The umask is only applied if there's no default ACL */ ret = jffs2_init_acl_pre(dir_i, inode, &mode); if (ret) { make_bad_inode(inode); iput(inode); return ERR_PTR(ret); } ret = jffs2_do_new_inode (c, f, mode, ri); if (ret) { make_bad_inode(inode); iput(inode); return ERR_PTR(ret); } inode->i_nlink = 1; inode->i_ino = je32_to_cpu(ri->ino); inode->i_mode = jemode_to_cpu(ri->mode); inode->i_gid = je16_to_cpu(ri->gid); inode->i_uid = je16_to_cpu(ri->uid); inode->i_atime = inode->i_ctime = inode->i_mtime = CURRENT_TIME_SEC; ri->atime = ri->mtime = ri->ctime = cpu_to_je32(I_SEC(inode->i_mtime)); inode->i_blocks = 0; inode->i_size = 0; if (insert_inode_locked(inode) < 0) { make_bad_inode(inode); unlock_new_inode(inode); iput(inode); return ERR_PTR(-EINVAL); } return inode; } int jffs2_do_fill_super(struct super_block *sb, void *data, int silent) { struct jffs2_sb_info *c; struct inode *root_i; int ret; size_t blocks; c = JFFS2_SB_INFO(sb); #ifndef CONFIG_JFFS2_FS_WRITEBUFFER if (c->mtd->type == MTD_NANDFLASH) { printk(KERN_ERR "jffs2: Cannot operate on NAND flash unless jffs2 NAND support is compiled in.\n"); return -EINVAL; } if (c->mtd->type == MTD_DATAFLASH) { printk(KERN_ERR "jffs2: Cannot operate on DataFlash unless jffs2 DataFlash support is compiled in.\n"); return -EINVAL; } #endif c->flash_size = c->mtd->size; c->sector_size = c->mtd->erasesize; blocks = c->flash_size / c->sector_size; /* * Size alignment check */ if ((c->sector_size * blocks) != c->flash_size) { c->flash_size = c->sector_size * blocks; printk(KERN_INFO "jffs2: Flash size not aligned to erasesize, reducing to %dKiB\n", c->flash_size / 1024); } if (c->flash_size < 5*c->sector_size) { printk(KERN_ERR "jffs2: Too few erase blocks (%d)\n", c->flash_size / c->sector_size); return -EINVAL; } c->cleanmarker_size = sizeof(struct jffs2_unknown_node); /* NAND (or other bizarre) flash... do setup accordingly */ ret = jffs2_flash_setup(c); if (ret) return ret; c->inocache_list = kcalloc(INOCACHE_HASHSIZE, sizeof(struct jffs2_inode_cache *), GFP_KERNEL); if (!c->inocache_list) { ret = -ENOMEM; goto out_wbuf; } jffs2_init_xattr_subsystem(c); if ((ret = jffs2_do_mount_fs(c))) goto out_inohash; D1(printk(KERN_DEBUG "jffs2_do_fill_super(): Getting root inode\n")); root_i = jffs2_iget(sb, 1); if (IS_ERR(root_i)) { D1(printk(KERN_WARNING "get root inode failed\n")); ret = PTR_ERR(root_i); goto out_root; } ret = -ENOMEM; D1(printk(KERN_DEBUG "jffs2_do_fill_super(): d_alloc_root()\n")); sb->s_root = d_alloc_root(root_i); if (!sb->s_root) goto out_root_i; sb->s_maxbytes = 0xFFFFFFFF; sb->s_blocksize = PAGE_CACHE_SIZE; sb->s_blocksize_bits = PAGE_CACHE_SHIFT; sb->s_magic = JFFS2_SUPER_MAGIC; if (!(sb->s_flags & MS_RDONLY)) jffs2_start_garbage_collect_thread(c); return 0; out_root_i: iput(root_i); out_root: jffs2_free_ino_caches(c); jffs2_free_raw_node_refs(c); if (jffs2_blocks_use_vmalloc(c)) vfree(c->blocks); else kfree(c->blocks); out_inohash: jffs2_clear_xattr_subsystem(c); kfree(c->inocache_list); out_wbuf: jffs2_flash_cleanup(c); return ret; } void jffs2_gc_release_inode(struct jffs2_sb_info *c, struct jffs2_inode_info *f) { iput(OFNI_EDONI_2SFFJ(f)); } struct jffs2_inode_info *jffs2_gc_fetch_inode(struct jffs2_sb_info *c, int inum, int unlinked) { struct inode *inode; struct jffs2_inode_cache *ic; if (unlinked) { /* The inode has zero nlink but its nodes weren't yet marked obsolete. This has to be because we're still waiting for the final (close() and) iput() to happen. There's a possibility that the final iput() could have happened while we were contemplating. In order to ensure that we don't cause a new read_inode() (which would fail) for the inode in question, we use ilookup() in this case instead of iget(). The nlink can't _become_ zero at this point because we're holding the alloc_sem, and jffs2_do_unlink() would also need that while decrementing nlink on any inode. */ inode = ilookup(OFNI_BS_2SFFJ(c), inum); if (!inode) { D1(printk(KERN_DEBUG "ilookup() failed for ino #%u; inode is probably deleted.\n", inum)); spin_lock(&c->inocache_lock); ic = jffs2_get_ino_cache(c, inum); if (!ic) { D1(printk(KERN_DEBUG "Inode cache for ino #%u is gone.\n", inum)); spin_unlock(&c->inocache_lock); return NULL; } if (ic->state != INO_STATE_CHECKEDABSENT) { /* Wait for progress. Don't just loop */ D1(printk(KERN_DEBUG "Waiting for ino #%u in state %d\n", ic->ino, ic->state)); sleep_on_spinunlock(&c->inocache_wq, &c->inocache_lock); } else { spin_unlock(&c->inocache_lock); } return NULL; } } else { /* Inode has links to it still; they're not going away because jffs2_do_unlink() would need the alloc_sem and we have it. Just iget() it, and if read_inode() is necessary that's OK. */ inode = jffs2_iget(OFNI_BS_2SFFJ(c), inum); if (IS_ERR(inode)) return ERR_CAST(inode); } if (is_bad_inode(inode)) { printk(KERN_NOTICE "Eep. read_inode() failed for ino #%u. unlinked %d\n", inum, unlinked); /* NB. This will happen again. We need to do something appropriate here. */ iput(inode); return ERR_PTR(-EIO); } return JFFS2_INODE_INFO(inode); } unsigned char *jffs2_gc_fetch_page(struct jffs2_sb_info *c, struct jffs2_inode_info *f, unsigned long offset, unsigned long *priv) { struct inode *inode = OFNI_EDONI_2SFFJ(f); struct page *pg; pg = read_cache_page_async(inode->i_mapping, offset >> PAGE_CACHE_SHIFT, (void *)jffs2_do_readpage_unlock, inode); if (IS_ERR(pg)) return (void *)pg; *priv = (unsigned long)pg; return kmap(pg); } void jffs2_gc_release_page(struct jffs2_sb_info *c, unsigned char *ptr, unsigned long *priv) { struct page *pg = (void *)*priv; kunmap(pg); page_cache_release(pg); } static int jffs2_flash_setup(struct jffs2_sb_info *c) { int ret = 0; if (jffs2_cleanmarker_oob(c)) { /* NAND flash... do setup accordingly */ ret = jffs2_nand_flash_setup(c); if (ret) return ret; } /* and Dataflash */ if (jffs2_dataflash(c)) { ret = jffs2_dataflash_setup(c); if (ret) return ret; } /* and Intel "Sibley" flash */ if (jffs2_nor_wbuf_flash(c)) { ret = jffs2_nor_wbuf_flash_setup(c); if (ret) return ret; } /* and an UBI volume */ if (jffs2_ubivol(c)) { ret = jffs2_ubivol_setup(c); if (ret) return ret; } return ret; } void jffs2_flash_cleanup(struct jffs2_sb_info *c) { if (jffs2_cleanmarker_oob(c)) { jffs2_nand_flash_cleanup(c); } /* and DataFlash */ if (jffs2_dataflash(c)) { jffs2_dataflash_cleanup(c); } /* and Intel "Sibley" flash */ if (jffs2_nor_wbuf_flash(c)) { jffs2_nor_wbuf_flash_cleanup(c); } /* and an UBI volume */ if (jffs2_ubivol(c)) { jffs2_ubivol_cleanup(c); } }
gpl-2.0
rachitrawat/Vengeance-Kernel-MSM7x30
sound/i2c/cs8427.c
729
18610
/* * Routines for control of the CS8427 via i2c bus * IEC958 (S/PDIF) receiver & transmitter by Cirrus Logic * Copyright (c) by Jaroslav Kysela <perex@perex.cz> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <linux/slab.h> #include <linux/delay.h> #include <linux/init.h> #include <asm/unaligned.h> #include <sound/core.h> #include <sound/control.h> #include <sound/pcm.h> #include <sound/cs8427.h> #include <sound/asoundef.h> static void snd_cs8427_reset(struct snd_i2c_device *cs8427); MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>"); MODULE_DESCRIPTION("IEC958 (S/PDIF) receiver & transmitter by Cirrus Logic"); MODULE_LICENSE("GPL"); #define CS8427_ADDR (0x20>>1) /* fixed address */ struct cs8427_stream { struct snd_pcm_substream *substream; char hw_status[24]; /* hardware status */ char def_status[24]; /* default status */ char pcm_status[24]; /* PCM private status */ char hw_udata[32]; struct snd_kcontrol *pcm_ctl; }; struct cs8427 { unsigned char regmap[0x14]; /* map of first 1 + 13 registers */ unsigned int rate; unsigned int reset_timeout; struct cs8427_stream playback; struct cs8427_stream capture; }; static unsigned char swapbits(unsigned char val) { int bit; unsigned char res = 0; for (bit = 0; bit < 8; bit++) { res <<= 1; res |= val & 1; val >>= 1; } return res; } int snd_cs8427_reg_write(struct snd_i2c_device *device, unsigned char reg, unsigned char val) { int err; unsigned char buf[2]; buf[0] = reg & 0x7f; buf[1] = val; if ((err = snd_i2c_sendbytes(device, buf, 2)) != 2) { snd_printk(KERN_ERR "unable to send bytes 0x%02x:0x%02x " "to CS8427 (%i)\n", buf[0], buf[1], err); return err < 0 ? err : -EIO; } return 0; } EXPORT_SYMBOL(snd_cs8427_reg_write); static int snd_cs8427_reg_read(struct snd_i2c_device *device, unsigned char reg) { int err; unsigned char buf; if ((err = snd_i2c_sendbytes(device, &reg, 1)) != 1) { snd_printk(KERN_ERR "unable to send register 0x%x byte " "to CS8427\n", reg); return err < 0 ? err : -EIO; } if ((err = snd_i2c_readbytes(device, &buf, 1)) != 1) { snd_printk(KERN_ERR "unable to read register 0x%x byte " "from CS8427\n", reg); return err < 0 ? err : -EIO; } return buf; } static int snd_cs8427_select_corudata(struct snd_i2c_device *device, int udata) { struct cs8427 *chip = device->private_data; int err; udata = udata ? CS8427_BSEL : 0; if (udata != (chip->regmap[CS8427_REG_CSDATABUF] & udata)) { chip->regmap[CS8427_REG_CSDATABUF] &= ~CS8427_BSEL; chip->regmap[CS8427_REG_CSDATABUF] |= udata; err = snd_cs8427_reg_write(device, CS8427_REG_CSDATABUF, chip->regmap[CS8427_REG_CSDATABUF]); if (err < 0) return err; } return 0; } static int snd_cs8427_send_corudata(struct snd_i2c_device *device, int udata, unsigned char *ndata, int count) { struct cs8427 *chip = device->private_data; char *hw_data = udata ? chip->playback.hw_udata : chip->playback.hw_status; char data[32]; int err, idx; if (!memcmp(hw_data, ndata, count)) return 0; if ((err = snd_cs8427_select_corudata(device, udata)) < 0) return err; memcpy(hw_data, ndata, count); if (udata) { memset(data, 0, sizeof(data)); if (memcmp(hw_data, data, count) == 0) { chip->regmap[CS8427_REG_UDATABUF] &= ~CS8427_UBMMASK; chip->regmap[CS8427_REG_UDATABUF] |= CS8427_UBMZEROS | CS8427_EFTUI; err = snd_cs8427_reg_write(device, CS8427_REG_UDATABUF, chip->regmap[CS8427_REG_UDATABUF]); return err < 0 ? err : 0; } } data[0] = CS8427_REG_AUTOINC | CS8427_REG_CORU_DATABUF; for (idx = 0; idx < count; idx++) data[idx + 1] = swapbits(ndata[idx]); if (snd_i2c_sendbytes(device, data, count + 1) != count + 1) return -EIO; return 1; } static void snd_cs8427_free(struct snd_i2c_device *device) { kfree(device->private_data); } int snd_cs8427_create(struct snd_i2c_bus *bus, unsigned char addr, unsigned int reset_timeout, struct snd_i2c_device **r_cs8427) { static unsigned char initvals1[] = { CS8427_REG_CONTROL1 | CS8427_REG_AUTOINC, /* CS8427_REG_CONTROL1: RMCK to OMCK, valid PCM audio, disable mutes, TCBL=output */ CS8427_SWCLK | CS8427_TCBLDIR, /* CS8427_REG_CONTROL2: hold last valid audio sample, RMCK=256*Fs, normal stereo operation */ 0x00, /* CS8427_REG_DATAFLOW: output drivers normal operation, Tx<=serial, Rx=>serial */ CS8427_TXDSERIAL | CS8427_SPDAES3RECEIVER, /* CS8427_REG_CLOCKSOURCE: Run off, CMCK=256*Fs, output time base = OMCK, input time base = recovered input clock, recovered input clock source is ILRCK changed to AES3INPUT (workaround, see snd_cs8427_reset) */ CS8427_RXDILRCK, /* CS8427_REG_SERIALINPUT: Serial audio input port data format = I2S, 24-bit, 64*Fsi */ CS8427_SIDEL | CS8427_SILRPOL, /* CS8427_REG_SERIALOUTPUT: Serial audio output port data format = I2S, 24-bit, 64*Fsi */ CS8427_SODEL | CS8427_SOLRPOL, }; static unsigned char initvals2[] = { CS8427_REG_RECVERRMASK | CS8427_REG_AUTOINC, /* CS8427_REG_RECVERRMASK: unmask the input PLL clock, V, confidence, biphase, parity status bits */ /* CS8427_UNLOCK | CS8427_V | CS8427_CONF | CS8427_BIP | CS8427_PAR,*/ 0xff, /* set everything */ /* CS8427_REG_CSDATABUF: Registers 32-55 window to CS buffer Inhibit D->E transfers from overwriting first 5 bytes of CS data. Inhibit D->E transfers (all) of CS data. Allow E->F transfer of CS data. One byte mode; both A/B channels get same written CB data. A channel info is output to chip's EMPH* pin. */ CS8427_CBMR | CS8427_DETCI, /* CS8427_REG_UDATABUF: Use internal buffer to transmit User (U) data. Chip's U pin is an output. Transmit all O's for user data. Inhibit D->E transfers. Inhibit E->F transfers. */ CS8427_UD | CS8427_EFTUI | CS8427_DETUI, }; int err; struct cs8427 *chip; struct snd_i2c_device *device; unsigned char buf[24]; if ((err = snd_i2c_device_create(bus, "CS8427", CS8427_ADDR | (addr & 7), &device)) < 0) return err; chip = device->private_data = kzalloc(sizeof(*chip), GFP_KERNEL); if (chip == NULL) { snd_i2c_device_free(device); return -ENOMEM; } device->private_free = snd_cs8427_free; snd_i2c_lock(bus); err = snd_cs8427_reg_read(device, CS8427_REG_ID_AND_VER); if (err != CS8427_VER8427A) { /* give second chance */ snd_printk(KERN_WARNING "invalid CS8427 signature 0x%x: " "let me try again...\n", err); err = snd_cs8427_reg_read(device, CS8427_REG_ID_AND_VER); } if (err != CS8427_VER8427A) { snd_i2c_unlock(bus); snd_printk(KERN_ERR "unable to find CS8427 signature " "(expected 0x%x, read 0x%x),\n", CS8427_VER8427A, err); snd_printk(KERN_ERR " initialization is not completed\n"); return -EFAULT; } /* turn off run bit while making changes to configuration */ err = snd_cs8427_reg_write(device, CS8427_REG_CLOCKSOURCE, 0x00); if (err < 0) goto __fail; /* send initial values */ memcpy(chip->regmap + (initvals1[0] & 0x7f), initvals1 + 1, 6); if ((err = snd_i2c_sendbytes(device, initvals1, 7)) != 7) { err = err < 0 ? err : -EIO; goto __fail; } /* Turn off CS8427 interrupt stuff that is not used in hardware */ memset(buf, 0, 7); /* from address 9 to 15 */ buf[0] = 9; /* register */ if ((err = snd_i2c_sendbytes(device, buf, 7)) != 7) goto __fail; /* send transfer initialization sequence */ memcpy(chip->regmap + (initvals2[0] & 0x7f), initvals2 + 1, 3); if ((err = snd_i2c_sendbytes(device, initvals2, 4)) != 4) { err = err < 0 ? err : -EIO; goto __fail; } /* write default channel status bytes */ put_unaligned_le32(SNDRV_PCM_DEFAULT_CON_SPDIF, buf); memset(buf + 4, 0, 24 - 4); if (snd_cs8427_send_corudata(device, 0, buf, 24) < 0) goto __fail; memcpy(chip->playback.def_status, buf, 24); memcpy(chip->playback.pcm_status, buf, 24); snd_i2c_unlock(bus); /* turn on run bit and rock'n'roll */ if (reset_timeout < 1) reset_timeout = 1; chip->reset_timeout = reset_timeout; snd_cs8427_reset(device); #if 0 // it's nice for read tests { char buf[128]; int xx; buf[0] = 0x81; snd_i2c_sendbytes(device, buf, 1); snd_i2c_readbytes(device, buf, 127); for (xx = 0; xx < 127; xx++) printk(KERN_DEBUG "reg[0x%x] = 0x%x\n", xx+1, buf[xx]); } #endif if (r_cs8427) *r_cs8427 = device; return 0; __fail: snd_i2c_unlock(bus); snd_i2c_device_free(device); return err < 0 ? err : -EIO; } EXPORT_SYMBOL(snd_cs8427_create); /* * Reset the chip using run bit, also lock PLL using ILRCK and * put back AES3INPUT. This workaround is described in latest * CS8427 datasheet, otherwise TXDSERIAL will not work. */ static void snd_cs8427_reset(struct snd_i2c_device *cs8427) { struct cs8427 *chip; unsigned long end_time; int data, aes3input = 0; if (snd_BUG_ON(!cs8427)) return; chip = cs8427->private_data; snd_i2c_lock(cs8427->bus); if ((chip->regmap[CS8427_REG_CLOCKSOURCE] & CS8427_RXDAES3INPUT) == CS8427_RXDAES3INPUT) /* AES3 bit is set */ aes3input = 1; chip->regmap[CS8427_REG_CLOCKSOURCE] &= ~(CS8427_RUN | CS8427_RXDMASK); snd_cs8427_reg_write(cs8427, CS8427_REG_CLOCKSOURCE, chip->regmap[CS8427_REG_CLOCKSOURCE]); udelay(200); chip->regmap[CS8427_REG_CLOCKSOURCE] |= CS8427_RUN | CS8427_RXDILRCK; snd_cs8427_reg_write(cs8427, CS8427_REG_CLOCKSOURCE, chip->regmap[CS8427_REG_CLOCKSOURCE]); udelay(200); snd_i2c_unlock(cs8427->bus); end_time = jiffies + chip->reset_timeout; while (time_after_eq(end_time, jiffies)) { snd_i2c_lock(cs8427->bus); data = snd_cs8427_reg_read(cs8427, CS8427_REG_RECVERRORS); snd_i2c_unlock(cs8427->bus); if (!(data & CS8427_UNLOCK)) break; schedule_timeout_uninterruptible(1); } snd_i2c_lock(cs8427->bus); chip->regmap[CS8427_REG_CLOCKSOURCE] &= ~CS8427_RXDMASK; if (aes3input) chip->regmap[CS8427_REG_CLOCKSOURCE] |= CS8427_RXDAES3INPUT; snd_cs8427_reg_write(cs8427, CS8427_REG_CLOCKSOURCE, chip->regmap[CS8427_REG_CLOCKSOURCE]); snd_i2c_unlock(cs8427->bus); } static int snd_cs8427_in_status_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 = 255; return 0; } static int snd_cs8427_in_status_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_i2c_device *device = snd_kcontrol_chip(kcontrol); int data; snd_i2c_lock(device->bus); data = snd_cs8427_reg_read(device, kcontrol->private_value); snd_i2c_unlock(device->bus); if (data < 0) return data; ucontrol->value.integer.value[0] = data; return 0; } static int snd_cs8427_qsubcode_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_BYTES; uinfo->count = 10; return 0; } static int snd_cs8427_qsubcode_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_i2c_device *device = snd_kcontrol_chip(kcontrol); unsigned char reg = CS8427_REG_QSUBCODE; int err; snd_i2c_lock(device->bus); if ((err = snd_i2c_sendbytes(device, &reg, 1)) != 1) { snd_printk(KERN_ERR "unable to send register 0x%x byte " "to CS8427\n", reg); snd_i2c_unlock(device->bus); return err < 0 ? err : -EIO; } err = snd_i2c_readbytes(device, ucontrol->value.bytes.data, 10); if (err != 10) { snd_printk(KERN_ERR "unable to read Q-subcode bytes " "from CS8427\n"); snd_i2c_unlock(device->bus); return err < 0 ? err : -EIO; } snd_i2c_unlock(device->bus); return 0; } static int snd_cs8427_spdif_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958; uinfo->count = 1; return 0; } static int snd_cs8427_spdif_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_i2c_device *device = snd_kcontrol_chip(kcontrol); struct cs8427 *chip = device->private_data; snd_i2c_lock(device->bus); memcpy(ucontrol->value.iec958.status, chip->playback.def_status, 24); snd_i2c_unlock(device->bus); return 0; } static int snd_cs8427_spdif_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_i2c_device *device = snd_kcontrol_chip(kcontrol); struct cs8427 *chip = device->private_data; unsigned char *status = kcontrol->private_value ? chip->playback.pcm_status : chip->playback.def_status; struct snd_pcm_runtime *runtime = chip->playback.substream ? chip->playback.substream->runtime : NULL; int err, change; snd_i2c_lock(device->bus); change = memcmp(ucontrol->value.iec958.status, status, 24) != 0; memcpy(status, ucontrol->value.iec958.status, 24); if (change && (kcontrol->private_value ? runtime != NULL : runtime == NULL)) { err = snd_cs8427_send_corudata(device, 0, status, 24); if (err < 0) change = err; } snd_i2c_unlock(device->bus); return change; } static int snd_cs8427_spdif_mask_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958; uinfo->count = 1; return 0; } static int snd_cs8427_spdif_mask_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { memset(ucontrol->value.iec958.status, 0xff, 24); return 0; } static struct snd_kcontrol_new snd_cs8427_iec958_controls[] = { { .iface = SNDRV_CTL_ELEM_IFACE_PCM, .info = snd_cs8427_in_status_info, .name = "IEC958 CS8427 Input Status", .access = (SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE), .get = snd_cs8427_in_status_get, .private_value = 15, }, { .iface = SNDRV_CTL_ELEM_IFACE_PCM, .info = snd_cs8427_in_status_info, .name = "IEC958 CS8427 Error Status", .access = (SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE), .get = snd_cs8427_in_status_get, .private_value = 16, }, { .access = SNDRV_CTL_ELEM_ACCESS_READ, .iface = SNDRV_CTL_ELEM_IFACE_PCM, .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,MASK), .info = snd_cs8427_spdif_mask_info, .get = snd_cs8427_spdif_mask_get, }, { .iface = SNDRV_CTL_ELEM_IFACE_PCM, .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,DEFAULT), .info = snd_cs8427_spdif_info, .get = snd_cs8427_spdif_get, .put = snd_cs8427_spdif_put, .private_value = 0 }, { .access = (SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_INACTIVE), .iface = SNDRV_CTL_ELEM_IFACE_PCM, .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,PCM_STREAM), .info = snd_cs8427_spdif_info, .get = snd_cs8427_spdif_get, .put = snd_cs8427_spdif_put, .private_value = 1 }, { .iface = SNDRV_CTL_ELEM_IFACE_PCM, .info = snd_cs8427_qsubcode_info, .name = "IEC958 Q-subcode Capture Default", .access = (SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE), .get = snd_cs8427_qsubcode_get }}; int snd_cs8427_iec958_build(struct snd_i2c_device *cs8427, struct snd_pcm_substream *play_substream, struct snd_pcm_substream *cap_substream) { struct cs8427 *chip = cs8427->private_data; struct snd_kcontrol *kctl; unsigned int idx; int err; if (snd_BUG_ON(!play_substream || !cap_substream)) return -EINVAL; for (idx = 0; idx < ARRAY_SIZE(snd_cs8427_iec958_controls); idx++) { kctl = snd_ctl_new1(&snd_cs8427_iec958_controls[idx], cs8427); if (kctl == NULL) return -ENOMEM; kctl->id.device = play_substream->pcm->device; kctl->id.subdevice = play_substream->number; err = snd_ctl_add(cs8427->bus->card, kctl); if (err < 0) return err; if (! strcmp(kctl->id.name, SNDRV_CTL_NAME_IEC958("",PLAYBACK,PCM_STREAM))) chip->playback.pcm_ctl = kctl; } chip->playback.substream = play_substream; chip->capture.substream = cap_substream; if (snd_BUG_ON(!chip->playback.pcm_ctl)) return -EIO; return 0; } EXPORT_SYMBOL(snd_cs8427_iec958_build); int snd_cs8427_iec958_active(struct snd_i2c_device *cs8427, int active) { struct cs8427 *chip; if (snd_BUG_ON(!cs8427)) return -ENXIO; chip = cs8427->private_data; if (active) memcpy(chip->playback.pcm_status, chip->playback.def_status, 24); chip->playback.pcm_ctl->vd[0].access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE; snd_ctl_notify(cs8427->bus->card, SNDRV_CTL_EVENT_MASK_VALUE | SNDRV_CTL_EVENT_MASK_INFO, &chip->playback.pcm_ctl->id); return 0; } EXPORT_SYMBOL(snd_cs8427_iec958_active); int snd_cs8427_iec958_pcm(struct snd_i2c_device *cs8427, unsigned int rate) { struct cs8427 *chip; char *status; int err, reset; if (snd_BUG_ON(!cs8427)) return -ENXIO; chip = cs8427->private_data; status = chip->playback.pcm_status; snd_i2c_lock(cs8427->bus); if (status[0] & IEC958_AES0_PROFESSIONAL) { status[0] &= ~IEC958_AES0_PRO_FS; switch (rate) { case 32000: status[0] |= IEC958_AES0_PRO_FS_32000; break; case 44100: status[0] |= IEC958_AES0_PRO_FS_44100; break; case 48000: status[0] |= IEC958_AES0_PRO_FS_48000; break; default: status[0] |= IEC958_AES0_PRO_FS_NOTID; break; } } else { status[3] &= ~IEC958_AES3_CON_FS; switch (rate) { case 32000: status[3] |= IEC958_AES3_CON_FS_32000; break; case 44100: status[3] |= IEC958_AES3_CON_FS_44100; break; case 48000: status[3] |= IEC958_AES3_CON_FS_48000; break; } } err = snd_cs8427_send_corudata(cs8427, 0, status, 24); if (err > 0) snd_ctl_notify(cs8427->bus->card, SNDRV_CTL_EVENT_MASK_VALUE, &chip->playback.pcm_ctl->id); reset = chip->rate != rate; chip->rate = rate; snd_i2c_unlock(cs8427->bus); if (reset) snd_cs8427_reset(cs8427); return err < 0 ? err : 0; } EXPORT_SYMBOL(snd_cs8427_iec958_pcm); static int __init alsa_cs8427_module_init(void) { return 0; } static void __exit alsa_cs8427_module_exit(void) { } module_init(alsa_cs8427_module_init) module_exit(alsa_cs8427_module_exit)
gpl-2.0
finniest/hive_kernel
drivers/net/wireless/rt2x00/rt2x00soc.c
985
3853
/* Copyright (C) 2004 - 2009 Ivo van Doorn <IvDoorn@gmail.com> Copyright (C) 2004 - 2009 Felix Fietkau <nbd@openwrt.org> <http://rt2x00.serialmonkey.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. */ /* Module: rt2x00soc Abstract: rt2x00 generic soc device routines. */ #include <linux/bug.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/slab.h> #include "rt2x00.h" #include "rt2x00soc.h" static void rt2x00soc_free_reg(struct rt2x00_dev *rt2x00dev) { kfree(rt2x00dev->rf); rt2x00dev->rf = NULL; kfree(rt2x00dev->eeprom); rt2x00dev->eeprom = NULL; } static int rt2x00soc_alloc_reg(struct rt2x00_dev *rt2x00dev) { struct platform_device *pdev = to_platform_device(rt2x00dev->dev); struct resource *res; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) return -ENODEV; rt2x00dev->csr.base = (void __iomem *)KSEG1ADDR(res->start); if (!rt2x00dev->csr.base) goto exit; rt2x00dev->eeprom = kzalloc(rt2x00dev->ops->eeprom_size, GFP_KERNEL); if (!rt2x00dev->eeprom) goto exit; rt2x00dev->rf = kzalloc(rt2x00dev->ops->rf_size, GFP_KERNEL); if (!rt2x00dev->rf) goto exit; return 0; exit: ERROR_PROBE("Failed to allocate registers.\n"); rt2x00soc_free_reg(rt2x00dev); return -ENOMEM; } int rt2x00soc_probe(struct platform_device *pdev, const struct rt2x00_ops *ops) { struct ieee80211_hw *hw; struct rt2x00_dev *rt2x00dev; int retval; hw = ieee80211_alloc_hw(sizeof(struct rt2x00_dev), ops->hw); if (!hw) { ERROR_PROBE("Failed to allocate hardware.\n"); return -ENOMEM; } platform_set_drvdata(pdev, hw); rt2x00dev = hw->priv; rt2x00dev->dev = &pdev->dev; rt2x00dev->ops = ops; rt2x00dev->hw = hw; rt2x00dev->irq = platform_get_irq(pdev, 0); rt2x00dev->name = pdev->dev.driver->name; rt2x00_set_chip_intf(rt2x00dev, RT2X00_CHIP_INTF_SOC); retval = rt2x00soc_alloc_reg(rt2x00dev); if (retval) goto exit_free_device; retval = rt2x00lib_probe_dev(rt2x00dev); if (retval) goto exit_free_reg; return 0; exit_free_reg: rt2x00soc_free_reg(rt2x00dev); exit_free_device: ieee80211_free_hw(hw); return retval; } EXPORT_SYMBOL_GPL(rt2x00soc_probe); int rt2x00soc_remove(struct platform_device *pdev) { struct ieee80211_hw *hw = platform_get_drvdata(pdev); struct rt2x00_dev *rt2x00dev = hw->priv; /* * Free all allocated data. */ rt2x00lib_remove_dev(rt2x00dev); rt2x00soc_free_reg(rt2x00dev); ieee80211_free_hw(hw); return 0; } EXPORT_SYMBOL_GPL(rt2x00soc_remove); #ifdef CONFIG_PM int rt2x00soc_suspend(struct platform_device *pdev, pm_message_t state) { struct ieee80211_hw *hw = platform_get_drvdata(pdev); struct rt2x00_dev *rt2x00dev = hw->priv; return rt2x00lib_suspend(rt2x00dev, state); } EXPORT_SYMBOL_GPL(rt2x00soc_suspend); int rt2x00soc_resume(struct platform_device *pdev) { struct ieee80211_hw *hw = platform_get_drvdata(pdev); struct rt2x00_dev *rt2x00dev = hw->priv; return rt2x00lib_resume(rt2x00dev); } EXPORT_SYMBOL_GPL(rt2x00soc_resume); #endif /* CONFIG_PM */ /* * rt2x00soc module information. */ MODULE_AUTHOR(DRV_PROJECT); MODULE_VERSION(DRV_VERSION); MODULE_DESCRIPTION("rt2x00 soc library"); MODULE_LICENSE("GPL");
gpl-2.0
zefie/thunderc_kernel_xionia
drivers/mtd/devices/lart.c
1497
19222
/* * MTD driver for the 28F160F3 Flash Memory (non-CFI) on LART. * * Author: Abraham vd Merwe <abraham@2d3d.co.za> * * Copyright (c) 2001, 2d3D, Inc. * * This code 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. * * References: * * [1] 3 Volt Fast Boot Block Flash Memory" Intel Datasheet * - Order Number: 290644-005 * - January 2000 * * [2] MTD internal API documentation * - http://www.linux-mtd.infradead.org/tech/ * * Limitations: * * Even though this driver is written for 3 Volt Fast Boot * Block Flash Memory, it is rather specific to LART. With * Minor modifications, notably the without data/address line * mangling and different bus settings, etc. it should be * trivial to adapt to other platforms. * * If somebody would sponsor me a different board, I'll * adapt the driver (: */ /* debugging */ //#define LART_DEBUG /* partition support */ #define HAVE_PARTITIONS #include <linux/kernel.h> #include <linux/module.h> #include <linux/types.h> #include <linux/init.h> #include <linux/errno.h> #include <linux/string.h> #include <linux/mtd/mtd.h> #ifdef HAVE_PARTITIONS #include <linux/mtd/partitions.h> #endif #ifndef CONFIG_SA1100_LART #error This is for LART architecture only #endif static char module_name[] = "lart"; /* * These values is specific to 28Fxxxx3 flash memory. * See section 2.3.1 in "3 Volt Fast Boot Block Flash Memory" Intel Datasheet */ #define FLASH_BLOCKSIZE_PARAM (4096 * BUSWIDTH) #define FLASH_NUMBLOCKS_16m_PARAM 8 #define FLASH_NUMBLOCKS_8m_PARAM 8 /* * These values is specific to 28Fxxxx3 flash memory. * See section 2.3.2 in "3 Volt Fast Boot Block Flash Memory" Intel Datasheet */ #define FLASH_BLOCKSIZE_MAIN (32768 * BUSWIDTH) #define FLASH_NUMBLOCKS_16m_MAIN 31 #define FLASH_NUMBLOCKS_8m_MAIN 15 /* * These values are specific to LART */ /* general */ #define BUSWIDTH 4 /* don't change this - a lot of the code _will_ break if you change this */ #define FLASH_OFFSET 0xe8000000 /* see linux/arch/arm/mach-sa1100/lart.c */ /* blob */ #define NUM_BLOB_BLOCKS FLASH_NUMBLOCKS_16m_PARAM #define BLOB_START 0x00000000 #define BLOB_LEN (NUM_BLOB_BLOCKS * FLASH_BLOCKSIZE_PARAM) /* kernel */ #define NUM_KERNEL_BLOCKS 7 #define KERNEL_START (BLOB_START + BLOB_LEN) #define KERNEL_LEN (NUM_KERNEL_BLOCKS * FLASH_BLOCKSIZE_MAIN) /* initial ramdisk */ #define NUM_INITRD_BLOCKS 24 #define INITRD_START (KERNEL_START + KERNEL_LEN) #define INITRD_LEN (NUM_INITRD_BLOCKS * FLASH_BLOCKSIZE_MAIN) /* * See section 4.0 in "3 Volt Fast Boot Block Flash Memory" Intel Datasheet */ #define READ_ARRAY 0x00FF00FF /* Read Array/Reset */ #define READ_ID_CODES 0x00900090 /* Read Identifier Codes */ #define ERASE_SETUP 0x00200020 /* Block Erase */ #define ERASE_CONFIRM 0x00D000D0 /* Block Erase and Program Resume */ #define PGM_SETUP 0x00400040 /* Program */ #define STATUS_READ 0x00700070 /* Read Status Register */ #define STATUS_CLEAR 0x00500050 /* Clear Status Register */ #define STATUS_BUSY 0x00800080 /* Write State Machine Status (WSMS) */ #define STATUS_ERASE_ERR 0x00200020 /* Erase Status (ES) */ #define STATUS_PGM_ERR 0x00100010 /* Program Status (PS) */ /* * See section 4.2 in "3 Volt Fast Boot Block Flash Memory" Intel Datasheet */ #define FLASH_MANUFACTURER 0x00890089 #define FLASH_DEVICE_8mbit_TOP 0x88f188f1 #define FLASH_DEVICE_8mbit_BOTTOM 0x88f288f2 #define FLASH_DEVICE_16mbit_TOP 0x88f388f3 #define FLASH_DEVICE_16mbit_BOTTOM 0x88f488f4 /***************************************************************************************************/ /* * The data line mapping on LART is as follows: * * U2 CPU | U3 CPU * ------------------- * 0 20 | 0 12 * 1 22 | 1 14 * 2 19 | 2 11 * 3 17 | 3 9 * 4 24 | 4 0 * 5 26 | 5 2 * 6 31 | 6 7 * 7 29 | 7 5 * 8 21 | 8 13 * 9 23 | 9 15 * 10 18 | 10 10 * 11 16 | 11 8 * 12 25 | 12 1 * 13 27 | 13 3 * 14 30 | 14 6 * 15 28 | 15 4 */ /* Mangle data (x) */ #define DATA_TO_FLASH(x) \ ( \ (((x) & 0x08009000) >> 11) + \ (((x) & 0x00002000) >> 10) + \ (((x) & 0x04004000) >> 8) + \ (((x) & 0x00000010) >> 4) + \ (((x) & 0x91000820) >> 3) + \ (((x) & 0x22080080) >> 2) + \ ((x) & 0x40000400) + \ (((x) & 0x00040040) << 1) + \ (((x) & 0x00110000) << 4) + \ (((x) & 0x00220100) << 5) + \ (((x) & 0x00800208) << 6) + \ (((x) & 0x00400004) << 9) + \ (((x) & 0x00000001) << 12) + \ (((x) & 0x00000002) << 13) \ ) /* Unmangle data (x) */ #define FLASH_TO_DATA(x) \ ( \ (((x) & 0x00010012) << 11) + \ (((x) & 0x00000008) << 10) + \ (((x) & 0x00040040) << 8) + \ (((x) & 0x00000001) << 4) + \ (((x) & 0x12200104) << 3) + \ (((x) & 0x08820020) << 2) + \ ((x) & 0x40000400) + \ (((x) & 0x00080080) >> 1) + \ (((x) & 0x01100000) >> 4) + \ (((x) & 0x04402000) >> 5) + \ (((x) & 0x20008200) >> 6) + \ (((x) & 0x80000800) >> 9) + \ (((x) & 0x00001000) >> 12) + \ (((x) & 0x00004000) >> 13) \ ) /* * The address line mapping on LART is as follows: * * U3 CPU | U2 CPU * ------------------- * 0 2 | 0 2 * 1 3 | 1 3 * 2 9 | 2 9 * 3 13 | 3 8 * 4 8 | 4 7 * 5 12 | 5 6 * 6 11 | 6 5 * 7 10 | 7 4 * 8 4 | 8 10 * 9 5 | 9 11 * 10 6 | 10 12 * 11 7 | 11 13 * * BOOT BLOCK BOUNDARY * * 12 15 | 12 15 * 13 14 | 13 14 * 14 16 | 14 16 * * MAIN BLOCK BOUNDARY * * 15 17 | 15 18 * 16 18 | 16 17 * 17 20 | 17 20 * 18 19 | 18 19 * 19 21 | 19 21 * * As we can see from above, the addresses aren't mangled across * block boundaries, so we don't need to worry about address * translations except for sending/reading commands during * initialization */ /* Mangle address (x) on chip U2 */ #define ADDR_TO_FLASH_U2(x) \ ( \ (((x) & 0x00000f00) >> 4) + \ (((x) & 0x00042000) << 1) + \ (((x) & 0x0009c003) << 2) + \ (((x) & 0x00021080) << 3) + \ (((x) & 0x00000010) << 4) + \ (((x) & 0x00000040) << 5) + \ (((x) & 0x00000024) << 7) + \ (((x) & 0x00000008) << 10) \ ) /* Unmangle address (x) on chip U2 */ #define FLASH_U2_TO_ADDR(x) \ ( \ (((x) << 4) & 0x00000f00) + \ (((x) >> 1) & 0x00042000) + \ (((x) >> 2) & 0x0009c003) + \ (((x) >> 3) & 0x00021080) + \ (((x) >> 4) & 0x00000010) + \ (((x) >> 5) & 0x00000040) + \ (((x) >> 7) & 0x00000024) + \ (((x) >> 10) & 0x00000008) \ ) /* Mangle address (x) on chip U3 */ #define ADDR_TO_FLASH_U3(x) \ ( \ (((x) & 0x00000080) >> 3) + \ (((x) & 0x00000040) >> 1) + \ (((x) & 0x00052020) << 1) + \ (((x) & 0x00084f03) << 2) + \ (((x) & 0x00029010) << 3) + \ (((x) & 0x00000008) << 5) + \ (((x) & 0x00000004) << 7) \ ) /* Unmangle address (x) on chip U3 */ #define FLASH_U3_TO_ADDR(x) \ ( \ (((x) << 3) & 0x00000080) + \ (((x) << 1) & 0x00000040) + \ (((x) >> 1) & 0x00052020) + \ (((x) >> 2) & 0x00084f03) + \ (((x) >> 3) & 0x00029010) + \ (((x) >> 5) & 0x00000008) + \ (((x) >> 7) & 0x00000004) \ ) /***************************************************************************************************/ static __u8 read8 (__u32 offset) { volatile __u8 *data = (__u8 *) (FLASH_OFFSET + offset); #ifdef LART_DEBUG printk (KERN_DEBUG "%s(): 0x%.8x -> 0x%.2x\n", __func__, offset, *data); #endif return (*data); } static __u32 read32 (__u32 offset) { volatile __u32 *data = (__u32 *) (FLASH_OFFSET + offset); #ifdef LART_DEBUG printk (KERN_DEBUG "%s(): 0x%.8x -> 0x%.8x\n", __func__, offset, *data); #endif return (*data); } static void write32 (__u32 x,__u32 offset) { volatile __u32 *data = (__u32 *) (FLASH_OFFSET + offset); *data = x; #ifdef LART_DEBUG printk (KERN_DEBUG "%s(): 0x%.8x <- 0x%.8x\n", __func__, offset, *data); #endif } /***************************************************************************************************/ /* * Probe for 16mbit flash memory on a LART board without doing * too much damage. Since we need to write 1 dword to memory, * we're f**cked if this happens to be DRAM since we can't * restore the memory (otherwise we might exit Read Array mode). * * Returns 1 if we found 16mbit flash memory on LART, 0 otherwise. */ static int flash_probe (void) { __u32 manufacturer,devtype; /* setup "Read Identifier Codes" mode */ write32 (DATA_TO_FLASH (READ_ID_CODES),0x00000000); /* probe U2. U2/U3 returns the same data since the first 3 * address lines is mangled in the same way */ manufacturer = FLASH_TO_DATA (read32 (ADDR_TO_FLASH_U2 (0x00000000))); devtype = FLASH_TO_DATA (read32 (ADDR_TO_FLASH_U2 (0x00000001))); /* put the flash back into command mode */ write32 (DATA_TO_FLASH (READ_ARRAY),0x00000000); return (manufacturer == FLASH_MANUFACTURER && (devtype == FLASH_DEVICE_16mbit_TOP || devtype == FLASH_DEVICE_16mbit_BOTTOM)); } /* * Erase one block of flash memory at offset ``offset'' which is any * address within the block which should be erased. * * Returns 1 if successful, 0 otherwise. */ static inline int erase_block (__u32 offset) { __u32 status; #ifdef LART_DEBUG printk (KERN_DEBUG "%s(): 0x%.8x\n", __func__, offset); #endif /* erase and confirm */ write32 (DATA_TO_FLASH (ERASE_SETUP),offset); write32 (DATA_TO_FLASH (ERASE_CONFIRM),offset); /* wait for block erase to finish */ do { write32 (DATA_TO_FLASH (STATUS_READ),offset); status = FLASH_TO_DATA (read32 (offset)); } while ((~status & STATUS_BUSY) != 0); /* put the flash back into command mode */ write32 (DATA_TO_FLASH (READ_ARRAY),offset); /* was the erase successfull? */ if ((status & STATUS_ERASE_ERR)) { printk (KERN_WARNING "%s: erase error at address 0x%.8x.\n",module_name,offset); return (0); } return (1); } static int flash_erase (struct mtd_info *mtd,struct erase_info *instr) { __u32 addr,len; int i,first; #ifdef LART_DEBUG printk (KERN_DEBUG "%s(addr = 0x%.8x, len = %d)\n", __func__, instr->addr, instr->len); #endif /* sanity checks */ if (instr->addr + instr->len > mtd->size) return (-EINVAL); /* * check that both start and end of the requested erase are * aligned with the erasesize at the appropriate addresses. * * skip all erase regions which are ended before the start of * the requested erase. Actually, to save on the calculations, * we skip to the first erase region which starts after the * start of the requested erase, and then go back one. */ for (i = 0; i < mtd->numeraseregions && instr->addr >= mtd->eraseregions[i].offset; i++) ; i--; /* * ok, now i is pointing at the erase region in which this * erase request starts. Check the start of the requested * erase range is aligned with the erase size which is in * effect here. */ if (i < 0 || (instr->addr & (mtd->eraseregions[i].erasesize - 1))) return -EINVAL; /* Remember the erase region we start on */ first = i; /* * next, check that the end of the requested erase is aligned * with the erase region at that address. * * as before, drop back one to point at the region in which * the address actually falls */ for (; i < mtd->numeraseregions && instr->addr + instr->len >= mtd->eraseregions[i].offset; i++) ; i--; /* is the end aligned on a block boundary? */ if (i < 0 || ((instr->addr + instr->len) & (mtd->eraseregions[i].erasesize - 1))) return -EINVAL; addr = instr->addr; len = instr->len; i = first; /* now erase those blocks */ while (len) { if (!erase_block (addr)) { instr->state = MTD_ERASE_FAILED; return (-EIO); } addr += mtd->eraseregions[i].erasesize; len -= mtd->eraseregions[i].erasesize; if (addr == mtd->eraseregions[i].offset + (mtd->eraseregions[i].erasesize * mtd->eraseregions[i].numblocks)) i++; } instr->state = MTD_ERASE_DONE; mtd_erase_callback(instr); return (0); } static int flash_read (struct mtd_info *mtd,loff_t from,size_t len,size_t *retlen,u_char *buf) { #ifdef LART_DEBUG printk (KERN_DEBUG "%s(from = 0x%.8x, len = %d)\n", __func__, (__u32)from, len); #endif /* sanity checks */ if (!len) return (0); if (from + len > mtd->size) return (-EINVAL); /* we always read len bytes */ *retlen = len; /* first, we read bytes until we reach a dword boundary */ if (from & (BUSWIDTH - 1)) { int gap = BUSWIDTH - (from & (BUSWIDTH - 1)); while (len && gap--) *buf++ = read8 (from++), len--; } /* now we read dwords until we reach a non-dword boundary */ while (len >= BUSWIDTH) { *((__u32 *) buf) = read32 (from); buf += BUSWIDTH; from += BUSWIDTH; len -= BUSWIDTH; } /* top up the last unaligned bytes */ if (len & (BUSWIDTH - 1)) while (len--) *buf++ = read8 (from++); return (0); } /* * Write one dword ``x'' to flash memory at offset ``offset''. ``offset'' * must be 32 bits, i.e. it must be on a dword boundary. * * Returns 1 if successful, 0 otherwise. */ static inline int write_dword (__u32 offset,__u32 x) { __u32 status; #ifdef LART_DEBUG printk (KERN_DEBUG "%s(): 0x%.8x <- 0x%.8x\n", __func__, offset, x); #endif /* setup writing */ write32 (DATA_TO_FLASH (PGM_SETUP),offset); /* write the data */ write32 (x,offset); /* wait for the write to finish */ do { write32 (DATA_TO_FLASH (STATUS_READ),offset); status = FLASH_TO_DATA (read32 (offset)); } while ((~status & STATUS_BUSY) != 0); /* put the flash back into command mode */ write32 (DATA_TO_FLASH (READ_ARRAY),offset); /* was the write successfull? */ if ((status & STATUS_PGM_ERR) || read32 (offset) != x) { printk (KERN_WARNING "%s: write error at address 0x%.8x.\n",module_name,offset); return (0); } return (1); } static int flash_write (struct mtd_info *mtd,loff_t to,size_t len,size_t *retlen,const u_char *buf) { __u8 tmp[4]; int i,n; #ifdef LART_DEBUG printk (KERN_DEBUG "%s(to = 0x%.8x, len = %d)\n", __func__, (__u32)to, len); #endif *retlen = 0; /* sanity checks */ if (!len) return (0); if (to + len > mtd->size) return (-EINVAL); /* first, we write a 0xFF.... padded byte until we reach a dword boundary */ if (to & (BUSWIDTH - 1)) { __u32 aligned = to & ~(BUSWIDTH - 1); int gap = to - aligned; i = n = 0; while (gap--) tmp[i++] = 0xFF; while (len && i < BUSWIDTH) tmp[i++] = buf[n++], len--; while (i < BUSWIDTH) tmp[i++] = 0xFF; if (!write_dword (aligned,*((__u32 *) tmp))) return (-EIO); to += n; buf += n; *retlen += n; } /* now we write dwords until we reach a non-dword boundary */ while (len >= BUSWIDTH) { if (!write_dword (to,*((__u32 *) buf))) return (-EIO); to += BUSWIDTH; buf += BUSWIDTH; *retlen += BUSWIDTH; len -= BUSWIDTH; } /* top up the last unaligned bytes, padded with 0xFF.... */ if (len & (BUSWIDTH - 1)) { i = n = 0; while (len--) tmp[i++] = buf[n++]; while (i < BUSWIDTH) tmp[i++] = 0xFF; if (!write_dword (to,*((__u32 *) tmp))) return (-EIO); *retlen += n; } return (0); } /***************************************************************************************************/ static struct mtd_info mtd; static struct mtd_erase_region_info erase_regions[] = { /* parameter blocks */ { .offset = 0x00000000, .erasesize = FLASH_BLOCKSIZE_PARAM, .numblocks = FLASH_NUMBLOCKS_16m_PARAM, }, /* main blocks */ { .offset = FLASH_BLOCKSIZE_PARAM * FLASH_NUMBLOCKS_16m_PARAM, .erasesize = FLASH_BLOCKSIZE_MAIN, .numblocks = FLASH_NUMBLOCKS_16m_MAIN, } }; #ifdef HAVE_PARTITIONS static struct mtd_partition lart_partitions[] = { /* blob */ { .name = "blob", .offset = BLOB_START, .size = BLOB_LEN, }, /* kernel */ { .name = "kernel", .offset = KERNEL_START, /* MTDPART_OFS_APPEND */ .size = KERNEL_LEN, }, /* initial ramdisk / file system */ { .name = "file system", .offset = INITRD_START, /* MTDPART_OFS_APPEND */ .size = INITRD_LEN, /* MTDPART_SIZ_FULL */ } }; #endif static int __init lart_flash_init (void) { int result; memset (&mtd,0,sizeof (mtd)); printk ("MTD driver for LART. Written by Abraham vd Merwe <abraham@2d3d.co.za>\n"); printk ("%s: Probing for 28F160x3 flash on LART...\n",module_name); if (!flash_probe ()) { printk (KERN_WARNING "%s: Found no LART compatible flash device\n",module_name); return (-ENXIO); } printk ("%s: This looks like a LART board to me.\n",module_name); mtd.name = module_name; mtd.type = MTD_NORFLASH; mtd.writesize = 1; mtd.flags = MTD_CAP_NORFLASH; mtd.size = FLASH_BLOCKSIZE_PARAM * FLASH_NUMBLOCKS_16m_PARAM + FLASH_BLOCKSIZE_MAIN * FLASH_NUMBLOCKS_16m_MAIN; mtd.erasesize = FLASH_BLOCKSIZE_MAIN; mtd.numeraseregions = ARRAY_SIZE(erase_regions); mtd.eraseregions = erase_regions; mtd.erase = flash_erase; mtd.read = flash_read; mtd.write = flash_write; mtd.owner = THIS_MODULE; #ifdef LART_DEBUG printk (KERN_DEBUG "mtd.name = %s\n" "mtd.size = 0x%.8x (%uM)\n" "mtd.erasesize = 0x%.8x (%uK)\n" "mtd.numeraseregions = %d\n", mtd.name, mtd.size,mtd.size / (1024*1024), mtd.erasesize,mtd.erasesize / 1024, mtd.numeraseregions); if (mtd.numeraseregions) for (result = 0; result < mtd.numeraseregions; result++) printk (KERN_DEBUG "\n\n" "mtd.eraseregions[%d].offset = 0x%.8x\n" "mtd.eraseregions[%d].erasesize = 0x%.8x (%uK)\n" "mtd.eraseregions[%d].numblocks = %d\n", result,mtd.eraseregions[result].offset, result,mtd.eraseregions[result].erasesize,mtd.eraseregions[result].erasesize / 1024, result,mtd.eraseregions[result].numblocks); #ifdef HAVE_PARTITIONS printk ("\npartitions = %d\n", ARRAY_SIZE(lart_partitions)); for (result = 0; result < ARRAY_SIZE(lart_partitions); result++) printk (KERN_DEBUG "\n\n" "lart_partitions[%d].name = %s\n" "lart_partitions[%d].offset = 0x%.8x\n" "lart_partitions[%d].size = 0x%.8x (%uK)\n", result,lart_partitions[result].name, result,lart_partitions[result].offset, result,lart_partitions[result].size,lart_partitions[result].size / 1024); #endif #endif #ifndef HAVE_PARTITIONS result = add_mtd_device (&mtd); #else result = add_mtd_partitions (&mtd,lart_partitions, ARRAY_SIZE(lart_partitions)); #endif return (result); } static void __exit lart_flash_exit (void) { #ifndef HAVE_PARTITIONS del_mtd_device (&mtd); #else del_mtd_partitions (&mtd); #endif } module_init (lart_flash_init); module_exit (lart_flash_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Abraham vd Merwe <abraham@2d3d.co.za>"); MODULE_DESCRIPTION("MTD driver for Intel 28F160F3 on LART board");
gpl-2.0
kissge/linuxkernel
fs/afs/flock.c
1497
16179
/* AFS file locking support * * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/smp_lock.h> #include "internal.h" #define AFS_LOCK_GRANTED 0 #define AFS_LOCK_PENDING 1 static void afs_fl_copy_lock(struct file_lock *new, struct file_lock *fl); static void afs_fl_release_private(struct file_lock *fl); static struct workqueue_struct *afs_lock_manager; static DEFINE_MUTEX(afs_lock_manager_mutex); static const struct file_lock_operations afs_lock_ops = { .fl_copy_lock = afs_fl_copy_lock, .fl_release_private = afs_fl_release_private, }; /* * initialise the lock manager thread if it isn't already running */ static int afs_init_lock_manager(void) { int ret; ret = 0; if (!afs_lock_manager) { mutex_lock(&afs_lock_manager_mutex); if (!afs_lock_manager) { afs_lock_manager = create_singlethread_workqueue("kafs_lockd"); if (!afs_lock_manager) ret = -ENOMEM; } mutex_unlock(&afs_lock_manager_mutex); } return ret; } /* * destroy the lock manager thread if it's running */ void __exit afs_kill_lock_manager(void) { if (afs_lock_manager) destroy_workqueue(afs_lock_manager); } /* * if the callback is broken on this vnode, then the lock may now be available */ void afs_lock_may_be_available(struct afs_vnode *vnode) { _enter("{%x:%u}", vnode->fid.vid, vnode->fid.vnode); queue_delayed_work(afs_lock_manager, &vnode->lock_work, 0); } /* * the lock will time out in 5 minutes unless we extend it, so schedule * extension in a bit less than that time */ static void afs_schedule_lock_extension(struct afs_vnode *vnode) { queue_delayed_work(afs_lock_manager, &vnode->lock_work, AFS_LOCKWAIT * HZ / 2); } /* * grant one or more locks (readlocks are allowed to jump the queue if the * first lock in the queue is itself a readlock) * - the caller must hold the vnode lock */ static void afs_grant_locks(struct afs_vnode *vnode, struct file_lock *fl) { struct file_lock *p, *_p; list_move_tail(&fl->fl_u.afs.link, &vnode->granted_locks); if (fl->fl_type == F_RDLCK) { list_for_each_entry_safe(p, _p, &vnode->pending_locks, fl_u.afs.link) { if (p->fl_type == F_RDLCK) { p->fl_u.afs.state = AFS_LOCK_GRANTED; list_move_tail(&p->fl_u.afs.link, &vnode->granted_locks); wake_up(&p->fl_wait); } } } } /* * do work for a lock, including: * - probing for a lock we're waiting on but didn't get immediately * - extending a lock that's close to timing out */ void afs_lock_work(struct work_struct *work) { struct afs_vnode *vnode = container_of(work, struct afs_vnode, lock_work.work); struct file_lock *fl; afs_lock_type_t type; struct key *key; int ret; _enter("{%x:%u}", vnode->fid.vid, vnode->fid.vnode); spin_lock(&vnode->lock); if (test_bit(AFS_VNODE_UNLOCKING, &vnode->flags)) { _debug("unlock"); spin_unlock(&vnode->lock); /* attempt to release the server lock; if it fails, we just * wait 5 minutes and it'll time out anyway */ ret = afs_vnode_release_lock(vnode, vnode->unlock_key); if (ret < 0) printk(KERN_WARNING "AFS:" " Failed to release lock on {%x:%x} error %d\n", vnode->fid.vid, vnode->fid.vnode, ret); spin_lock(&vnode->lock); key_put(vnode->unlock_key); vnode->unlock_key = NULL; clear_bit(AFS_VNODE_UNLOCKING, &vnode->flags); } /* if we've got a lock, then it must be time to extend that lock as AFS * locks time out after 5 minutes */ if (!list_empty(&vnode->granted_locks)) { _debug("extend"); if (test_and_set_bit(AFS_VNODE_LOCKING, &vnode->flags)) BUG(); fl = list_entry(vnode->granted_locks.next, struct file_lock, fl_u.afs.link); key = key_get(fl->fl_file->private_data); spin_unlock(&vnode->lock); ret = afs_vnode_extend_lock(vnode, key); clear_bit(AFS_VNODE_LOCKING, &vnode->flags); key_put(key); switch (ret) { case 0: afs_schedule_lock_extension(vnode); break; default: /* ummm... we failed to extend the lock - retry * extension shortly */ printk(KERN_WARNING "AFS:" " Failed to extend lock on {%x:%x} error %d\n", vnode->fid.vid, vnode->fid.vnode, ret); queue_delayed_work(afs_lock_manager, &vnode->lock_work, HZ * 10); break; } _leave(" [extend]"); return; } /* if we don't have a granted lock, then we must've been called back by * the server, and so if might be possible to get a lock we're * currently waiting for */ if (!list_empty(&vnode->pending_locks)) { _debug("get"); if (test_and_set_bit(AFS_VNODE_LOCKING, &vnode->flags)) BUG(); fl = list_entry(vnode->pending_locks.next, struct file_lock, fl_u.afs.link); key = key_get(fl->fl_file->private_data); type = (fl->fl_type == F_RDLCK) ? AFS_LOCK_READ : AFS_LOCK_WRITE; spin_unlock(&vnode->lock); ret = afs_vnode_set_lock(vnode, key, type); clear_bit(AFS_VNODE_LOCKING, &vnode->flags); switch (ret) { case -EWOULDBLOCK: _debug("blocked"); break; case 0: _debug("acquired"); if (type == AFS_LOCK_READ) set_bit(AFS_VNODE_READLOCKED, &vnode->flags); else set_bit(AFS_VNODE_WRITELOCKED, &vnode->flags); ret = AFS_LOCK_GRANTED; default: spin_lock(&vnode->lock); /* the pending lock may have been withdrawn due to a * signal */ if (list_entry(vnode->pending_locks.next, struct file_lock, fl_u.afs.link) == fl) { fl->fl_u.afs.state = ret; if (ret == AFS_LOCK_GRANTED) afs_grant_locks(vnode, fl); else list_del_init(&fl->fl_u.afs.link); wake_up(&fl->fl_wait); spin_unlock(&vnode->lock); } else { _debug("withdrawn"); clear_bit(AFS_VNODE_READLOCKED, &vnode->flags); clear_bit(AFS_VNODE_WRITELOCKED, &vnode->flags); spin_unlock(&vnode->lock); afs_vnode_release_lock(vnode, key); if (!list_empty(&vnode->pending_locks)) afs_lock_may_be_available(vnode); } break; } key_put(key); _leave(" [pend]"); return; } /* looks like the lock request was withdrawn on a signal */ spin_unlock(&vnode->lock); _leave(" [no locks]"); } /* * pass responsibility for the unlocking of a vnode on the server to the * manager thread, lest a pending signal in the calling thread interrupt * AF_RXRPC * - the caller must hold the vnode lock */ static void afs_defer_unlock(struct afs_vnode *vnode, struct key *key) { cancel_delayed_work(&vnode->lock_work); if (!test_and_clear_bit(AFS_VNODE_READLOCKED, &vnode->flags) && !test_and_clear_bit(AFS_VNODE_WRITELOCKED, &vnode->flags)) BUG(); if (test_and_set_bit(AFS_VNODE_UNLOCKING, &vnode->flags)) BUG(); vnode->unlock_key = key_get(key); afs_lock_may_be_available(vnode); } /* * request a lock on a file on the server */ static int afs_do_setlk(struct file *file, struct file_lock *fl) { struct afs_vnode *vnode = AFS_FS_I(file->f_mapping->host); afs_lock_type_t type; struct key *key = file->private_data; int ret; _enter("{%x:%u},%u", vnode->fid.vid, vnode->fid.vnode, fl->fl_type); /* only whole-file locks are supported */ if (fl->fl_start != 0 || fl->fl_end != OFFSET_MAX) return -EINVAL; ret = afs_init_lock_manager(); if (ret < 0) return ret; fl->fl_ops = &afs_lock_ops; INIT_LIST_HEAD(&fl->fl_u.afs.link); fl->fl_u.afs.state = AFS_LOCK_PENDING; type = (fl->fl_type == F_RDLCK) ? AFS_LOCK_READ : AFS_LOCK_WRITE; lock_kernel(); /* make sure we've got a callback on this file and that our view of the * data version is up to date */ ret = afs_vnode_fetch_status(vnode, NULL, key); if (ret < 0) goto error; if (vnode->status.lock_count != 0 && !(fl->fl_flags & FL_SLEEP)) { ret = -EAGAIN; goto error; } spin_lock(&vnode->lock); /* if we've already got a readlock on the server then we can instantly * grant another readlock, irrespective of whether there are any * pending writelocks */ if (type == AFS_LOCK_READ && vnode->flags & (1 << AFS_VNODE_READLOCKED)) { _debug("instant readlock"); ASSERTCMP(vnode->flags & ((1 << AFS_VNODE_LOCKING) | (1 << AFS_VNODE_WRITELOCKED)), ==, 0); ASSERT(!list_empty(&vnode->granted_locks)); goto sharing_existing_lock; } /* if there's no-one else with a lock on this vnode, then we need to * ask the server for a lock */ if (list_empty(&vnode->pending_locks) && list_empty(&vnode->granted_locks)) { _debug("not locked"); ASSERTCMP(vnode->flags & ((1 << AFS_VNODE_LOCKING) | (1 << AFS_VNODE_READLOCKED) | (1 << AFS_VNODE_WRITELOCKED)), ==, 0); list_add_tail(&fl->fl_u.afs.link, &vnode->pending_locks); set_bit(AFS_VNODE_LOCKING, &vnode->flags); spin_unlock(&vnode->lock); ret = afs_vnode_set_lock(vnode, key, type); clear_bit(AFS_VNODE_LOCKING, &vnode->flags); switch (ret) { case 0: _debug("acquired"); goto acquired_server_lock; case -EWOULDBLOCK: _debug("would block"); spin_lock(&vnode->lock); ASSERT(list_empty(&vnode->granted_locks)); ASSERTCMP(vnode->pending_locks.next, ==, &fl->fl_u.afs.link); goto wait; default: spin_lock(&vnode->lock); list_del_init(&fl->fl_u.afs.link); spin_unlock(&vnode->lock); goto error; } } /* otherwise, we need to wait for a local lock to become available */ _debug("wait local"); list_add_tail(&fl->fl_u.afs.link, &vnode->pending_locks); wait: if (!(fl->fl_flags & FL_SLEEP)) { _debug("noblock"); ret = -EAGAIN; goto abort_attempt; } spin_unlock(&vnode->lock); /* now we need to sleep and wait for the lock manager thread to get the * lock from the server */ _debug("sleep"); ret = wait_event_interruptible(fl->fl_wait, fl->fl_u.afs.state <= AFS_LOCK_GRANTED); if (fl->fl_u.afs.state <= AFS_LOCK_GRANTED) { ret = fl->fl_u.afs.state; if (ret < 0) goto error; spin_lock(&vnode->lock); goto given_lock; } /* we were interrupted, but someone may still be in the throes of * giving us the lock */ _debug("intr"); ASSERTCMP(ret, ==, -ERESTARTSYS); spin_lock(&vnode->lock); if (fl->fl_u.afs.state <= AFS_LOCK_GRANTED) { ret = fl->fl_u.afs.state; if (ret < 0) { spin_unlock(&vnode->lock); goto error; } goto given_lock; } abort_attempt: /* we aren't going to get the lock, either because we're unwilling to * wait, or because some signal happened */ _debug("abort"); if (list_empty(&vnode->granted_locks) && vnode->pending_locks.next == &fl->fl_u.afs.link) { if (vnode->pending_locks.prev != &fl->fl_u.afs.link) { /* kick the next pending lock into having a go */ list_del_init(&fl->fl_u.afs.link); afs_lock_may_be_available(vnode); } } else { list_del_init(&fl->fl_u.afs.link); } spin_unlock(&vnode->lock); goto error; acquired_server_lock: /* we've acquired a server lock, but it needs to be renewed after 5 * mins */ spin_lock(&vnode->lock); afs_schedule_lock_extension(vnode); if (type == AFS_LOCK_READ) set_bit(AFS_VNODE_READLOCKED, &vnode->flags); else set_bit(AFS_VNODE_WRITELOCKED, &vnode->flags); sharing_existing_lock: /* the lock has been granted as far as we're concerned... */ fl->fl_u.afs.state = AFS_LOCK_GRANTED; list_move_tail(&fl->fl_u.afs.link, &vnode->granted_locks); given_lock: /* ... but we do still need to get the VFS's blessing */ ASSERT(!(vnode->flags & (1 << AFS_VNODE_LOCKING))); ASSERT((vnode->flags & ((1 << AFS_VNODE_READLOCKED) | (1 << AFS_VNODE_WRITELOCKED))) != 0); ret = posix_lock_file(file, fl, NULL); if (ret < 0) goto vfs_rejected_lock; spin_unlock(&vnode->lock); /* again, make sure we've got a callback on this file and, again, make * sure that our view of the data version is up to date (we ignore * errors incurred here and deal with the consequences elsewhere) */ afs_vnode_fetch_status(vnode, NULL, key); error: unlock_kernel(); _leave(" = %d", ret); return ret; vfs_rejected_lock: /* the VFS rejected the lock we just obtained, so we have to discard * what we just got */ _debug("vfs refused %d", ret); list_del_init(&fl->fl_u.afs.link); if (list_empty(&vnode->granted_locks)) afs_defer_unlock(vnode, key); goto abort_attempt; } /* * unlock on a file on the server */ static int afs_do_unlk(struct file *file, struct file_lock *fl) { struct afs_vnode *vnode = AFS_FS_I(file->f_mapping->host); struct key *key = file->private_data; int ret; _enter("{%x:%u},%u", vnode->fid.vid, vnode->fid.vnode, fl->fl_type); /* only whole-file unlocks are supported */ if (fl->fl_start != 0 || fl->fl_end != OFFSET_MAX) return -EINVAL; fl->fl_ops = &afs_lock_ops; INIT_LIST_HEAD(&fl->fl_u.afs.link); fl->fl_u.afs.state = AFS_LOCK_PENDING; spin_lock(&vnode->lock); ret = posix_lock_file(file, fl, NULL); if (ret < 0) { spin_unlock(&vnode->lock); _leave(" = %d [vfs]", ret); return ret; } /* discard the server lock only if all granted locks are gone */ if (list_empty(&vnode->granted_locks)) afs_defer_unlock(vnode, key); spin_unlock(&vnode->lock); _leave(" = 0"); return 0; } /* * return information about a lock we currently hold, if indeed we hold one */ static int afs_do_getlk(struct file *file, struct file_lock *fl) { struct afs_vnode *vnode = AFS_FS_I(file->f_mapping->host); struct key *key = file->private_data; int ret, lock_count; _enter(""); fl->fl_type = F_UNLCK; mutex_lock(&vnode->vfs_inode.i_mutex); /* check local lock records first */ ret = 0; posix_test_lock(file, fl); if (fl->fl_type == F_UNLCK) { /* no local locks; consult the server */ ret = afs_vnode_fetch_status(vnode, NULL, key); if (ret < 0) goto error; lock_count = vnode->status.lock_count; if (lock_count) { if (lock_count > 0) fl->fl_type = F_RDLCK; else fl->fl_type = F_WRLCK; fl->fl_start = 0; fl->fl_end = OFFSET_MAX; } } error: mutex_unlock(&vnode->vfs_inode.i_mutex); _leave(" = %d [%hd]", ret, fl->fl_type); return ret; } /* * manage POSIX locks on a file */ int afs_lock(struct file *file, int cmd, struct file_lock *fl) { struct afs_vnode *vnode = AFS_FS_I(file->f_dentry->d_inode); _enter("{%x:%u},%d,{t=%x,fl=%x,r=%Ld:%Ld}", vnode->fid.vid, vnode->fid.vnode, cmd, fl->fl_type, fl->fl_flags, (long long) fl->fl_start, (long long) fl->fl_end); /* AFS doesn't support mandatory locks */ if (__mandatory_lock(&vnode->vfs_inode) && fl->fl_type != F_UNLCK) return -ENOLCK; if (IS_GETLK(cmd)) return afs_do_getlk(file, fl); if (fl->fl_type == F_UNLCK) return afs_do_unlk(file, fl); return afs_do_setlk(file, fl); } /* * manage FLOCK locks on a file */ int afs_flock(struct file *file, int cmd, struct file_lock *fl) { struct afs_vnode *vnode = AFS_FS_I(file->f_dentry->d_inode); _enter("{%x:%u},%d,{t=%x,fl=%x}", vnode->fid.vid, vnode->fid.vnode, cmd, fl->fl_type, fl->fl_flags); /* * No BSD flocks over NFS allowed. * Note: we could try to fake a POSIX lock request here by * using ((u32) filp | 0x80000000) or some such as the pid. * Not sure whether that would be unique, though, or whether * that would break in other places. */ if (!(fl->fl_flags & FL_FLOCK)) return -ENOLCK; /* we're simulating flock() locks using posix locks on the server */ fl->fl_owner = (fl_owner_t) file; fl->fl_start = 0; fl->fl_end = OFFSET_MAX; if (fl->fl_type == F_UNLCK) return afs_do_unlk(file, fl); return afs_do_setlk(file, fl); } /* * the POSIX lock management core VFS code copies the lock record and adds the * copy into its own list, so we need to add that copy to the vnode's lock * queue in the same place as the original (which will be deleted shortly * after) */ static void afs_fl_copy_lock(struct file_lock *new, struct file_lock *fl) { _enter(""); list_add(&new->fl_u.afs.link, &fl->fl_u.afs.link); } /* * need to remove this lock from the vnode queue when it's removed from the * VFS's list */ static void afs_fl_release_private(struct file_lock *fl) { _enter(""); list_del_init(&fl->fl_u.afs.link); }
gpl-2.0
miuihu/android_kernel_xiaomi_redmi2
arch/mips/math-emu/cp1emu.c
1753
52602
/* * cp1emu.c: a MIPS coprocessor 1 (fpu) instruction emulator * * MIPS floating point support * Copyright (C) 1994-2000 Algorithmics Ltd. * * Kevin D. Kissell, kevink@mips.com and Carsten Langgaard, carstenl@mips.com * Copyright (C) 2000 MIPS Technologies, Inc. * * This program is free software; you can distribute 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 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. * * A complete emulator for MIPS coprocessor 1 instructions. This is * required for #float(switch) or #float(trap), where it catches all * COP1 instructions via the "CoProcessor Unusable" exception. * * More surprisingly it is also required for #float(ieee), to help out * the hardware fpu at the boundaries of the IEEE-754 representation * (denormalised values, infinities, underflow, etc). It is made * quite nasty because emulation of some non-COP1 instructions is * required, e.g. in branch delay slots. * * Note if you know that you won't have an fpu, then you'll get much * better performance by compiling with -msoft-float! */ #include <linux/sched.h> #include <linux/module.h> #include <linux/debugfs.h> #include <linux/perf_event.h> #include <asm/inst.h> #include <asm/bootinfo.h> #include <asm/processor.h> #include <asm/ptrace.h> #include <asm/signal.h> #include <asm/mipsregs.h> #include <asm/fpu_emulator.h> #include <asm/fpu.h> #include <asm/uaccess.h> #include <asm/branch.h> #include "ieee754.h" /* Strap kernel emulator for full MIPS IV emulation */ #ifdef __mips #undef __mips #endif #define __mips 4 /* Function which emulates a floating point instruction. */ static int fpu_emu(struct pt_regs *, struct mips_fpu_struct *, mips_instruction); #if __mips >= 4 && __mips != 32 static int fpux_emu(struct pt_regs *, struct mips_fpu_struct *, mips_instruction, void *__user *); #endif /* Further private data for which no space exists in mips_fpu_struct */ #ifdef CONFIG_DEBUG_FS DEFINE_PER_CPU(struct mips_fpu_emulator_stats, fpuemustats); #endif /* Control registers */ #define FPCREG_RID 0 /* $0 = revision id */ #define FPCREG_CSR 31 /* $31 = csr */ /* Determine rounding mode from the RM bits of the FCSR */ #define modeindex(v) ((v) & FPU_CSR_RM) /* microMIPS bitfields */ #define MM_POOL32A_MINOR_MASK 0x3f #define MM_POOL32A_MINOR_SHIFT 0x6 #define MM_MIPS32_COND_FC 0x30 /* Convert Mips rounding mode (0..3) to IEEE library modes. */ static const unsigned char ieee_rm[4] = { [FPU_CSR_RN] = IEEE754_RN, [FPU_CSR_RZ] = IEEE754_RZ, [FPU_CSR_RU] = IEEE754_RU, [FPU_CSR_RD] = IEEE754_RD, }; /* Convert IEEE library modes to Mips rounding mode (0..3). */ static const unsigned char mips_rm[4] = { [IEEE754_RN] = FPU_CSR_RN, [IEEE754_RZ] = FPU_CSR_RZ, [IEEE754_RD] = FPU_CSR_RD, [IEEE754_RU] = FPU_CSR_RU, }; #if __mips >= 4 /* convert condition code register number to csr bit */ static const unsigned int fpucondbit[8] = { FPU_CSR_COND0, FPU_CSR_COND1, FPU_CSR_COND2, FPU_CSR_COND3, FPU_CSR_COND4, FPU_CSR_COND5, FPU_CSR_COND6, FPU_CSR_COND7 }; #endif /* (microMIPS) Convert 16-bit register encoding to 32-bit register encoding. */ static const unsigned int reg16to32map[8] = {16, 17, 2, 3, 4, 5, 6, 7}; /* (microMIPS) Convert certain microMIPS instructions to MIPS32 format. */ static const int sd_format[] = {16, 17, 0, 0, 0, 0, 0, 0}; static const int sdps_format[] = {16, 17, 22, 0, 0, 0, 0, 0}; static const int dwl_format[] = {17, 20, 21, 0, 0, 0, 0, 0}; static const int swl_format[] = {16, 20, 21, 0, 0, 0, 0, 0}; /* * This functions translates a 32-bit microMIPS instruction * into a 32-bit MIPS32 instruction. Returns 0 on success * and SIGILL otherwise. */ static int microMIPS32_to_MIPS32(union mips_instruction *insn_ptr) { union mips_instruction insn = *insn_ptr; union mips_instruction mips32_insn = insn; int func, fmt, op; switch (insn.mm_i_format.opcode) { case mm_ldc132_op: mips32_insn.mm_i_format.opcode = ldc1_op; mips32_insn.mm_i_format.rt = insn.mm_i_format.rs; mips32_insn.mm_i_format.rs = insn.mm_i_format.rt; break; case mm_lwc132_op: mips32_insn.mm_i_format.opcode = lwc1_op; mips32_insn.mm_i_format.rt = insn.mm_i_format.rs; mips32_insn.mm_i_format.rs = insn.mm_i_format.rt; break; case mm_sdc132_op: mips32_insn.mm_i_format.opcode = sdc1_op; mips32_insn.mm_i_format.rt = insn.mm_i_format.rs; mips32_insn.mm_i_format.rs = insn.mm_i_format.rt; break; case mm_swc132_op: mips32_insn.mm_i_format.opcode = swc1_op; mips32_insn.mm_i_format.rt = insn.mm_i_format.rs; mips32_insn.mm_i_format.rs = insn.mm_i_format.rt; break; case mm_pool32i_op: /* NOTE: offset is << by 1 if in microMIPS mode. */ if ((insn.mm_i_format.rt == mm_bc1f_op) || (insn.mm_i_format.rt == mm_bc1t_op)) { mips32_insn.fb_format.opcode = cop1_op; mips32_insn.fb_format.bc = bc_op; mips32_insn.fb_format.flag = (insn.mm_i_format.rt == mm_bc1t_op) ? 1 : 0; } else return SIGILL; break; case mm_pool32f_op: switch (insn.mm_fp0_format.func) { case mm_32f_01_op: case mm_32f_11_op: case mm_32f_02_op: case mm_32f_12_op: case mm_32f_41_op: case mm_32f_51_op: case mm_32f_42_op: case mm_32f_52_op: op = insn.mm_fp0_format.func; if (op == mm_32f_01_op) func = madd_s_op; else if (op == mm_32f_11_op) func = madd_d_op; else if (op == mm_32f_02_op) func = nmadd_s_op; else if (op == mm_32f_12_op) func = nmadd_d_op; else if (op == mm_32f_41_op) func = msub_s_op; else if (op == mm_32f_51_op) func = msub_d_op; else if (op == mm_32f_42_op) func = nmsub_s_op; else func = nmsub_d_op; mips32_insn.fp6_format.opcode = cop1x_op; mips32_insn.fp6_format.fr = insn.mm_fp6_format.fr; mips32_insn.fp6_format.ft = insn.mm_fp6_format.ft; mips32_insn.fp6_format.fs = insn.mm_fp6_format.fs; mips32_insn.fp6_format.fd = insn.mm_fp6_format.fd; mips32_insn.fp6_format.func = func; break; case mm_32f_10_op: func = -1; /* Invalid */ op = insn.mm_fp5_format.op & 0x7; if (op == mm_ldxc1_op) func = ldxc1_op; else if (op == mm_sdxc1_op) func = sdxc1_op; else if (op == mm_lwxc1_op) func = lwxc1_op; else if (op == mm_swxc1_op) func = swxc1_op; if (func != -1) { mips32_insn.r_format.opcode = cop1x_op; mips32_insn.r_format.rs = insn.mm_fp5_format.base; mips32_insn.r_format.rt = insn.mm_fp5_format.index; mips32_insn.r_format.rd = 0; mips32_insn.r_format.re = insn.mm_fp5_format.fd; mips32_insn.r_format.func = func; } else return SIGILL; break; case mm_32f_40_op: op = -1; /* Invalid */ if (insn.mm_fp2_format.op == mm_fmovt_op) op = 1; else if (insn.mm_fp2_format.op == mm_fmovf_op) op = 0; if (op != -1) { mips32_insn.fp0_format.opcode = cop1_op; mips32_insn.fp0_format.fmt = sdps_format[insn.mm_fp2_format.fmt]; mips32_insn.fp0_format.ft = (insn.mm_fp2_format.cc<<2) + op; mips32_insn.fp0_format.fs = insn.mm_fp2_format.fs; mips32_insn.fp0_format.fd = insn.mm_fp2_format.fd; mips32_insn.fp0_format.func = fmovc_op; } else return SIGILL; break; case mm_32f_60_op: func = -1; /* Invalid */ if (insn.mm_fp0_format.op == mm_fadd_op) func = fadd_op; else if (insn.mm_fp0_format.op == mm_fsub_op) func = fsub_op; else if (insn.mm_fp0_format.op == mm_fmul_op) func = fmul_op; else if (insn.mm_fp0_format.op == mm_fdiv_op) func = fdiv_op; if (func != -1) { mips32_insn.fp0_format.opcode = cop1_op; mips32_insn.fp0_format.fmt = sdps_format[insn.mm_fp0_format.fmt]; mips32_insn.fp0_format.ft = insn.mm_fp0_format.ft; mips32_insn.fp0_format.fs = insn.mm_fp0_format.fs; mips32_insn.fp0_format.fd = insn.mm_fp0_format.fd; mips32_insn.fp0_format.func = func; } else return SIGILL; break; case mm_32f_70_op: func = -1; /* Invalid */ if (insn.mm_fp0_format.op == mm_fmovn_op) func = fmovn_op; else if (insn.mm_fp0_format.op == mm_fmovz_op) func = fmovz_op; if (func != -1) { mips32_insn.fp0_format.opcode = cop1_op; mips32_insn.fp0_format.fmt = sdps_format[insn.mm_fp0_format.fmt]; mips32_insn.fp0_format.ft = insn.mm_fp0_format.ft; mips32_insn.fp0_format.fs = insn.mm_fp0_format.fs; mips32_insn.fp0_format.fd = insn.mm_fp0_format.fd; mips32_insn.fp0_format.func = func; } else return SIGILL; break; case mm_32f_73_op: /* POOL32FXF */ switch (insn.mm_fp1_format.op) { case mm_movf0_op: case mm_movf1_op: case mm_movt0_op: case mm_movt1_op: if ((insn.mm_fp1_format.op & 0x7f) == mm_movf0_op) op = 0; else op = 1; mips32_insn.r_format.opcode = spec_op; mips32_insn.r_format.rs = insn.mm_fp4_format.fs; mips32_insn.r_format.rt = (insn.mm_fp4_format.cc << 2) + op; mips32_insn.r_format.rd = insn.mm_fp4_format.rt; mips32_insn.r_format.re = 0; mips32_insn.r_format.func = movc_op; break; case mm_fcvtd0_op: case mm_fcvtd1_op: case mm_fcvts0_op: case mm_fcvts1_op: if ((insn.mm_fp1_format.op & 0x7f) == mm_fcvtd0_op) { func = fcvtd_op; fmt = swl_format[insn.mm_fp3_format.fmt]; } else { func = fcvts_op; fmt = dwl_format[insn.mm_fp3_format.fmt]; } mips32_insn.fp0_format.opcode = cop1_op; mips32_insn.fp0_format.fmt = fmt; mips32_insn.fp0_format.ft = 0; mips32_insn.fp0_format.fs = insn.mm_fp3_format.fs; mips32_insn.fp0_format.fd = insn.mm_fp3_format.rt; mips32_insn.fp0_format.func = func; break; case mm_fmov0_op: case mm_fmov1_op: case mm_fabs0_op: case mm_fabs1_op: case mm_fneg0_op: case mm_fneg1_op: if ((insn.mm_fp1_format.op & 0x7f) == mm_fmov0_op) func = fmov_op; else if ((insn.mm_fp1_format.op & 0x7f) == mm_fabs0_op) func = fabs_op; else func = fneg_op; mips32_insn.fp0_format.opcode = cop1_op; mips32_insn.fp0_format.fmt = sdps_format[insn.mm_fp3_format.fmt]; mips32_insn.fp0_format.ft = 0; mips32_insn.fp0_format.fs = insn.mm_fp3_format.fs; mips32_insn.fp0_format.fd = insn.mm_fp3_format.rt; mips32_insn.fp0_format.func = func; break; case mm_ffloorl_op: case mm_ffloorw_op: case mm_fceill_op: case mm_fceilw_op: case mm_ftruncl_op: case mm_ftruncw_op: case mm_froundl_op: case mm_froundw_op: case mm_fcvtl_op: case mm_fcvtw_op: if (insn.mm_fp1_format.op == mm_ffloorl_op) func = ffloorl_op; else if (insn.mm_fp1_format.op == mm_ffloorw_op) func = ffloor_op; else if (insn.mm_fp1_format.op == mm_fceill_op) func = fceill_op; else if (insn.mm_fp1_format.op == mm_fceilw_op) func = fceil_op; else if (insn.mm_fp1_format.op == mm_ftruncl_op) func = ftruncl_op; else if (insn.mm_fp1_format.op == mm_ftruncw_op) func = ftrunc_op; else if (insn.mm_fp1_format.op == mm_froundl_op) func = froundl_op; else if (insn.mm_fp1_format.op == mm_froundw_op) func = fround_op; else if (insn.mm_fp1_format.op == mm_fcvtl_op) func = fcvtl_op; else func = fcvtw_op; mips32_insn.fp0_format.opcode = cop1_op; mips32_insn.fp0_format.fmt = sd_format[insn.mm_fp1_format.fmt]; mips32_insn.fp0_format.ft = 0; mips32_insn.fp0_format.fs = insn.mm_fp1_format.fs; mips32_insn.fp0_format.fd = insn.mm_fp1_format.rt; mips32_insn.fp0_format.func = func; break; case mm_frsqrt_op: case mm_fsqrt_op: case mm_frecip_op: if (insn.mm_fp1_format.op == mm_frsqrt_op) func = frsqrt_op; else if (insn.mm_fp1_format.op == mm_fsqrt_op) func = fsqrt_op; else func = frecip_op; mips32_insn.fp0_format.opcode = cop1_op; mips32_insn.fp0_format.fmt = sdps_format[insn.mm_fp1_format.fmt]; mips32_insn.fp0_format.ft = 0; mips32_insn.fp0_format.fs = insn.mm_fp1_format.fs; mips32_insn.fp0_format.fd = insn.mm_fp1_format.rt; mips32_insn.fp0_format.func = func; break; case mm_mfc1_op: case mm_mtc1_op: case mm_cfc1_op: case mm_ctc1_op: if (insn.mm_fp1_format.op == mm_mfc1_op) op = mfc_op; else if (insn.mm_fp1_format.op == mm_mtc1_op) op = mtc_op; else if (insn.mm_fp1_format.op == mm_cfc1_op) op = cfc_op; else op = ctc_op; mips32_insn.fp1_format.opcode = cop1_op; mips32_insn.fp1_format.op = op; mips32_insn.fp1_format.rt = insn.mm_fp1_format.rt; mips32_insn.fp1_format.fs = insn.mm_fp1_format.fs; mips32_insn.fp1_format.fd = 0; mips32_insn.fp1_format.func = 0; break; default: return SIGILL; break; } break; case mm_32f_74_op: /* c.cond.fmt */ mips32_insn.fp0_format.opcode = cop1_op; mips32_insn.fp0_format.fmt = sdps_format[insn.mm_fp4_format.fmt]; mips32_insn.fp0_format.ft = insn.mm_fp4_format.rt; mips32_insn.fp0_format.fs = insn.mm_fp4_format.fs; mips32_insn.fp0_format.fd = insn.mm_fp4_format.cc << 2; mips32_insn.fp0_format.func = insn.mm_fp4_format.cond | MM_MIPS32_COND_FC; break; default: return SIGILL; break; } break; default: return SIGILL; break; } *insn_ptr = mips32_insn; return 0; } int mm_isBranchInstr(struct pt_regs *regs, struct mm_decoded_insn dec_insn, unsigned long *contpc) { union mips_instruction insn = (union mips_instruction)dec_insn.insn; int bc_false = 0; unsigned int fcr31; unsigned int bit; switch (insn.mm_i_format.opcode) { case mm_pool32a_op: if ((insn.mm_i_format.simmediate & MM_POOL32A_MINOR_MASK) == mm_pool32axf_op) { switch (insn.mm_i_format.simmediate >> MM_POOL32A_MINOR_SHIFT) { case mm_jalr_op: case mm_jalrhb_op: case mm_jalrs_op: case mm_jalrshb_op: if (insn.mm_i_format.rt != 0) /* Not mm_jr */ regs->regs[insn.mm_i_format.rt] = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; *contpc = regs->regs[insn.mm_i_format.rs]; return 1; break; } } break; case mm_pool32i_op: switch (insn.mm_i_format.rt) { case mm_bltzals_op: case mm_bltzal_op: regs->regs[31] = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; /* Fall through */ case mm_bltz_op: if ((long)regs->regs[insn.mm_i_format.rs] < 0) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.mm_i_format.simmediate << 1); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; case mm_bgezals_op: case mm_bgezal_op: regs->regs[31] = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; /* Fall through */ case mm_bgez_op: if ((long)regs->regs[insn.mm_i_format.rs] >= 0) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.mm_i_format.simmediate << 1); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; case mm_blez_op: if ((long)regs->regs[insn.mm_i_format.rs] <= 0) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.mm_i_format.simmediate << 1); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; case mm_bgtz_op: if ((long)regs->regs[insn.mm_i_format.rs] <= 0) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.mm_i_format.simmediate << 1); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; case mm_bc2f_op: case mm_bc1f_op: bc_false = 1; /* Fall through */ case mm_bc2t_op: case mm_bc1t_op: preempt_disable(); if (is_fpu_owner()) asm volatile("cfc1\t%0,$31" : "=r" (fcr31)); else fcr31 = current->thread.fpu.fcr31; preempt_enable(); if (bc_false) fcr31 = ~fcr31; bit = (insn.mm_i_format.rs >> 2); bit += (bit != 0); bit += 23; if (fcr31 & (1 << bit)) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.mm_i_format.simmediate << 1); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; } break; case mm_pool16c_op: switch (insn.mm_i_format.rt) { case mm_jalr16_op: case mm_jalrs16_op: regs->regs[31] = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; /* Fall through */ case mm_jr16_op: *contpc = regs->regs[insn.mm_i_format.rs]; return 1; break; } break; case mm_beqz16_op: if ((long)regs->regs[reg16to32map[insn.mm_b1_format.rs]] == 0) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.mm_b1_format.simmediate << 1); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; case mm_bnez16_op: if ((long)regs->regs[reg16to32map[insn.mm_b1_format.rs]] != 0) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.mm_b1_format.simmediate << 1); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; case mm_b16_op: *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.mm_b0_format.simmediate << 1); return 1; break; case mm_beq32_op: if (regs->regs[insn.mm_i_format.rs] == regs->regs[insn.mm_i_format.rt]) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.mm_i_format.simmediate << 1); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; case mm_bne32_op: if (regs->regs[insn.mm_i_format.rs] != regs->regs[insn.mm_i_format.rt]) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.mm_i_format.simmediate << 1); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; case mm_jalx32_op: regs->regs[31] = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; *contpc = regs->cp0_epc + dec_insn.pc_inc; *contpc >>= 28; *contpc <<= 28; *contpc |= (insn.j_format.target << 2); return 1; break; case mm_jals32_op: case mm_jal32_op: regs->regs[31] = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; /* Fall through */ case mm_j32_op: *contpc = regs->cp0_epc + dec_insn.pc_inc; *contpc >>= 27; *contpc <<= 27; *contpc |= (insn.j_format.target << 1); set_isa16_mode(*contpc); return 1; break; } return 0; } /* * Redundant with logic already in kernel/branch.c, * embedded in compute_return_epc. At some point, * a single subroutine should be used across both * modules. */ static int isBranchInstr(struct pt_regs *regs, struct mm_decoded_insn dec_insn, unsigned long *contpc) { union mips_instruction insn = (union mips_instruction)dec_insn.insn; unsigned int fcr31; unsigned int bit = 0; switch (insn.i_format.opcode) { case spec_op: switch (insn.r_format.func) { case jalr_op: regs->regs[insn.r_format.rd] = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; /* Fall through */ case jr_op: *contpc = regs->regs[insn.r_format.rs]; return 1; break; } break; case bcond_op: switch (insn.i_format.rt) { case bltzal_op: case bltzall_op: regs->regs[31] = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; /* Fall through */ case bltz_op: case bltzl_op: if ((long)regs->regs[insn.i_format.rs] < 0) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.i_format.simmediate << 2); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; case bgezal_op: case bgezall_op: regs->regs[31] = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; /* Fall through */ case bgez_op: case bgezl_op: if ((long)regs->regs[insn.i_format.rs] >= 0) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.i_format.simmediate << 2); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; } break; case jalx_op: set_isa16_mode(bit); case jal_op: regs->regs[31] = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; /* Fall through */ case j_op: *contpc = regs->cp0_epc + dec_insn.pc_inc; *contpc >>= 28; *contpc <<= 28; *contpc |= (insn.j_format.target << 2); /* Set microMIPS mode bit: XOR for jalx. */ *contpc ^= bit; return 1; break; case beq_op: case beql_op: if (regs->regs[insn.i_format.rs] == regs->regs[insn.i_format.rt]) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.i_format.simmediate << 2); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; case bne_op: case bnel_op: if (regs->regs[insn.i_format.rs] != regs->regs[insn.i_format.rt]) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.i_format.simmediate << 2); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; case blez_op: case blezl_op: if ((long)regs->regs[insn.i_format.rs] <= 0) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.i_format.simmediate << 2); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; case bgtz_op: case bgtzl_op: if ((long)regs->regs[insn.i_format.rs] > 0) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.i_format.simmediate << 2); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; case cop0_op: case cop1_op: case cop2_op: case cop1x_op: if (insn.i_format.rs == bc_op) { preempt_disable(); if (is_fpu_owner()) asm volatile("cfc1\t%0,$31" : "=r" (fcr31)); else fcr31 = current->thread.fpu.fcr31; preempt_enable(); bit = (insn.i_format.rt >> 2); bit += (bit != 0); bit += 23; switch (insn.i_format.rt & 3) { case 0: /* bc1f */ case 2: /* bc1fl */ if (~fcr31 & (1 << bit)) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.i_format.simmediate << 2); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; case 1: /* bc1t */ case 3: /* bc1tl */ if (fcr31 & (1 << bit)) *contpc = regs->cp0_epc + dec_insn.pc_inc + (insn.i_format.simmediate << 2); else *contpc = regs->cp0_epc + dec_insn.pc_inc + dec_insn.next_pc_inc; return 1; break; } } break; } return 0; } /* * In the Linux kernel, we support selection of FPR format on the * basis of the Status.FR bit. If an FPU is not present, the FR bit * is hardwired to zero, which would imply a 32-bit FPU even for * 64-bit CPUs so we rather look at TIF_32BIT_REGS. * FPU emu is slow and bulky and optimizing this function offers fairly * sizeable benefits so we try to be clever and make this function return * a constant whenever possible, that is on 64-bit kernels without O32 * compatibility enabled and on 32-bit kernels. */ static inline int cop1_64bit(struct pt_regs *xcp) { #if defined(CONFIG_64BIT) && !defined(CONFIG_MIPS32_O32) return 1; #elif defined(CONFIG_64BIT) && defined(CONFIG_MIPS32_O32) return !test_thread_flag(TIF_32BIT_REGS); #else return 0; #endif } #define SIFROMREG(si, x) ((si) = cop1_64bit(xcp) || !(x & 1) ? \ (int)ctx->fpr[x] : (int)(ctx->fpr[x & ~1] >> 32)) #define SITOREG(si, x) (ctx->fpr[x & ~(cop1_64bit(xcp) == 0)] = \ cop1_64bit(xcp) || !(x & 1) ? \ ctx->fpr[x & ~1] >> 32 << 32 | (u32)(si) : \ ctx->fpr[x & ~1] << 32 >> 32 | (u64)(si) << 32) #define DIFROMREG(di, x) ((di) = ctx->fpr[x & ~(cop1_64bit(xcp) == 0)]) #define DITOREG(di, x) (ctx->fpr[x & ~(cop1_64bit(xcp) == 0)] = (di)) #define SPFROMREG(sp, x) SIFROMREG((sp).bits, x) #define SPTOREG(sp, x) SITOREG((sp).bits, x) #define DPFROMREG(dp, x) DIFROMREG((dp).bits, x) #define DPTOREG(dp, x) DITOREG((dp).bits, x) /* * Emulate the single floating point instruction pointed at by EPC. * Two instructions if the instruction is in a branch delay slot. */ static int cop1Emulate(struct pt_regs *xcp, struct mips_fpu_struct *ctx, struct mm_decoded_insn dec_insn, void *__user *fault_addr) { mips_instruction ir; unsigned long contpc = xcp->cp0_epc + dec_insn.pc_inc; unsigned int cond; int pc_inc; /* XXX NEC Vr54xx bug workaround */ if (xcp->cp0_cause & CAUSEF_BD) { if (dec_insn.micro_mips_mode) { if (!mm_isBranchInstr(xcp, dec_insn, &contpc)) xcp->cp0_cause &= ~CAUSEF_BD; } else { if (!isBranchInstr(xcp, dec_insn, &contpc)) xcp->cp0_cause &= ~CAUSEF_BD; } } if (xcp->cp0_cause & CAUSEF_BD) { /* * The instruction to be emulated is in a branch delay slot * which means that we have to emulate the branch instruction * BEFORE we do the cop1 instruction. * * This branch could be a COP1 branch, but in that case we * would have had a trap for that instruction, and would not * come through this route. * * Linux MIPS branch emulator operates on context, updating the * cp0_epc. */ ir = dec_insn.next_insn; /* process delay slot instr */ pc_inc = dec_insn.next_pc_inc; } else { ir = dec_insn.insn; /* process current instr */ pc_inc = dec_insn.pc_inc; } /* * Since microMIPS FPU instructios are a subset of MIPS32 FPU * instructions, we want to convert microMIPS FPU instructions * into MIPS32 instructions so that we could reuse all of the * FPU emulation code. * * NOTE: We cannot do this for branch instructions since they * are not a subset. Example: Cannot emulate a 16-bit * aligned target address with a MIPS32 instruction. */ if (dec_insn.micro_mips_mode) { /* * If next instruction is a 16-bit instruction, then it * it cannot be a FPU instruction. This could happen * since we can be called for non-FPU instructions. */ if ((pc_inc == 2) || (microMIPS32_to_MIPS32((union mips_instruction *)&ir) == SIGILL)) return SIGILL; } emul: perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, xcp, 0); MIPS_FPU_EMU_INC_STATS(emulated); switch (MIPSInst_OPCODE(ir)) { case ldc1_op:{ u64 __user *va = (u64 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u64 val; MIPS_FPU_EMU_INC_STATS(loads); if (!access_ok(VERIFY_READ, va, sizeof(u64))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__get_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } DITOREG(val, MIPSInst_RT(ir)); break; } case sdc1_op:{ u64 __user *va = (u64 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u64 val; MIPS_FPU_EMU_INC_STATS(stores); DIFROMREG(val, MIPSInst_RT(ir)); if (!access_ok(VERIFY_WRITE, va, sizeof(u64))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__put_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } break; } case lwc1_op:{ u32 __user *va = (u32 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u32 val; MIPS_FPU_EMU_INC_STATS(loads); if (!access_ok(VERIFY_READ, va, sizeof(u32))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__get_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } SITOREG(val, MIPSInst_RT(ir)); break; } case swc1_op:{ u32 __user *va = (u32 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u32 val; MIPS_FPU_EMU_INC_STATS(stores); SIFROMREG(val, MIPSInst_RT(ir)); if (!access_ok(VERIFY_WRITE, va, sizeof(u32))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__put_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } break; } case cop1_op: switch (MIPSInst_RS(ir)) { #if defined(__mips64) case dmfc_op: /* copregister fs -> gpr[rt] */ if (MIPSInst_RT(ir) != 0) { DIFROMREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); } break; case dmtc_op: /* copregister fs <- rt */ DITOREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); break; #endif case mfc_op: /* copregister rd -> gpr[rt] */ if (MIPSInst_RT(ir) != 0) { SIFROMREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); } break; case mtc_op: /* copregister rd <- rt */ SITOREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); break; case cfc_op:{ /* cop control register rd -> gpr[rt] */ u32 value; if (MIPSInst_RD(ir) == FPCREG_CSR) { value = ctx->fcr31; value = (value & ~FPU_CSR_RM) | mips_rm[modeindex(value)]; #ifdef CSRTRACE printk("%p gpr[%d]<-csr=%08x\n", (void *) (xcp->cp0_epc), MIPSInst_RT(ir), value); #endif } else if (MIPSInst_RD(ir) == FPCREG_RID) value = 0; else value = 0; if (MIPSInst_RT(ir)) xcp->regs[MIPSInst_RT(ir)] = value; break; } case ctc_op:{ /* copregister rd <- rt */ u32 value; if (MIPSInst_RT(ir) == 0) value = 0; else value = xcp->regs[MIPSInst_RT(ir)]; /* we only have one writable control reg */ if (MIPSInst_RD(ir) == FPCREG_CSR) { #ifdef CSRTRACE printk("%p gpr[%d]->csr=%08x\n", (void *) (xcp->cp0_epc), MIPSInst_RT(ir), value); #endif /* * Don't write reserved bits, * and convert to ieee library modes */ ctx->fcr31 = (value & ~(FPU_CSR_RSVD | FPU_CSR_RM)) | ieee_rm[modeindex(value)]; } if ((ctx->fcr31 >> 5) & ctx->fcr31 & FPU_CSR_ALL_E) { return SIGFPE; } break; } case bc_op:{ int likely = 0; if (xcp->cp0_cause & CAUSEF_BD) return SIGILL; #if __mips >= 4 cond = ctx->fcr31 & fpucondbit[MIPSInst_RT(ir) >> 2]; #else cond = ctx->fcr31 & FPU_CSR_COND; #endif switch (MIPSInst_RT(ir) & 3) { case bcfl_op: likely = 1; case bcf_op: cond = !cond; break; case bctl_op: likely = 1; case bct_op: break; default: /* thats an illegal instruction */ return SIGILL; } xcp->cp0_cause |= CAUSEF_BD; if (cond) { /* branch taken: emulate dslot * instruction */ xcp->cp0_epc += dec_insn.pc_inc; contpc = MIPSInst_SIMM(ir); ir = dec_insn.next_insn; if (dec_insn.micro_mips_mode) { contpc = (xcp->cp0_epc + (contpc << 1)); /* If 16-bit instruction, not FPU. */ if ((dec_insn.next_pc_inc == 2) || (microMIPS32_to_MIPS32((union mips_instruction *)&ir) == SIGILL)) { /* * Since this instruction will * be put on the stack with * 32-bit words, get around * this problem by putting a * NOP16 as the second one. */ if (dec_insn.next_pc_inc == 2) ir = (ir & (~0xffff)) | MM_NOP16; /* * Single step the non-CP1 * instruction in the dslot. */ return mips_dsemul(xcp, ir, contpc); } } else contpc = (xcp->cp0_epc + (contpc << 2)); switch (MIPSInst_OPCODE(ir)) { case lwc1_op: case swc1_op: #if (__mips >= 2 || defined(__mips64)) case ldc1_op: case sdc1_op: #endif case cop1_op: #if __mips >= 4 && __mips != 32 case cop1x_op: #endif /* its one of ours */ goto emul; #if __mips >= 4 case spec_op: if (MIPSInst_FUNC(ir) == movc_op) goto emul; break; #endif } /* * Single step the non-cp1 * instruction in the dslot */ return mips_dsemul(xcp, ir, contpc); } else { /* branch not taken */ if (likely) { /* * branch likely nullifies * dslot if not taken */ xcp->cp0_epc += dec_insn.pc_inc; contpc += dec_insn.pc_inc; /* * else continue & execute * dslot as normal insn */ } } break; } default: if (!(MIPSInst_RS(ir) & 0x10)) return SIGILL; { int sig; /* a real fpu computation instruction */ if ((sig = fpu_emu(xcp, ctx, ir))) return sig; } } break; #if __mips >= 4 && __mips != 32 case cop1x_op:{ int sig = fpux_emu(xcp, ctx, ir, fault_addr); if (sig) return sig; break; } #endif #if __mips >= 4 case spec_op: if (MIPSInst_FUNC(ir) != movc_op) return SIGILL; cond = fpucondbit[MIPSInst_RT(ir) >> 2]; if (((ctx->fcr31 & cond) != 0) == ((MIPSInst_RT(ir) & 1) != 0)) xcp->regs[MIPSInst_RD(ir)] = xcp->regs[MIPSInst_RS(ir)]; break; #endif default: return SIGILL; } /* we did it !! */ xcp->cp0_epc = contpc; xcp->cp0_cause &= ~CAUSEF_BD; return 0; } /* * Conversion table from MIPS compare ops 48-63 * cond = ieee754dp_cmp(x,y,IEEE754_UN,sig); */ static const unsigned char cmptab[8] = { 0, /* cmp_0 (sig) cmp_sf */ IEEE754_CUN, /* cmp_un (sig) cmp_ngle */ IEEE754_CEQ, /* cmp_eq (sig) cmp_seq */ IEEE754_CEQ | IEEE754_CUN, /* cmp_ueq (sig) cmp_ngl */ IEEE754_CLT, /* cmp_olt (sig) cmp_lt */ IEEE754_CLT | IEEE754_CUN, /* cmp_ult (sig) cmp_nge */ IEEE754_CLT | IEEE754_CEQ, /* cmp_ole (sig) cmp_le */ IEEE754_CLT | IEEE754_CEQ | IEEE754_CUN, /* cmp_ule (sig) cmp_ngt */ }; #if __mips >= 4 && __mips != 32 /* * Additional MIPS4 instructions */ #define DEF3OP(name, p, f1, f2, f3) \ static ieee754##p fpemu_##p##_##name(ieee754##p r, ieee754##p s, \ ieee754##p t) \ { \ struct _ieee754_csr ieee754_csr_save; \ s = f1(s, t); \ ieee754_csr_save = ieee754_csr; \ s = f2(s, r); \ ieee754_csr_save.cx |= ieee754_csr.cx; \ ieee754_csr_save.sx |= ieee754_csr.sx; \ s = f3(s); \ ieee754_csr.cx |= ieee754_csr_save.cx; \ ieee754_csr.sx |= ieee754_csr_save.sx; \ return s; \ } static ieee754dp fpemu_dp_recip(ieee754dp d) { return ieee754dp_div(ieee754dp_one(0), d); } static ieee754dp fpemu_dp_rsqrt(ieee754dp d) { return ieee754dp_div(ieee754dp_one(0), ieee754dp_sqrt(d)); } static ieee754sp fpemu_sp_recip(ieee754sp s) { return ieee754sp_div(ieee754sp_one(0), s); } static ieee754sp fpemu_sp_rsqrt(ieee754sp s) { return ieee754sp_div(ieee754sp_one(0), ieee754sp_sqrt(s)); } DEF3OP(madd, sp, ieee754sp_mul, ieee754sp_add, ); DEF3OP(msub, sp, ieee754sp_mul, ieee754sp_sub, ); DEF3OP(nmadd, sp, ieee754sp_mul, ieee754sp_add, ieee754sp_neg); DEF3OP(nmsub, sp, ieee754sp_mul, ieee754sp_sub, ieee754sp_neg); DEF3OP(madd, dp, ieee754dp_mul, ieee754dp_add, ); DEF3OP(msub, dp, ieee754dp_mul, ieee754dp_sub, ); DEF3OP(nmadd, dp, ieee754dp_mul, ieee754dp_add, ieee754dp_neg); DEF3OP(nmsub, dp, ieee754dp_mul, ieee754dp_sub, ieee754dp_neg); static int fpux_emu(struct pt_regs *xcp, struct mips_fpu_struct *ctx, mips_instruction ir, void *__user *fault_addr) { unsigned rcsr = 0; /* resulting csr */ MIPS_FPU_EMU_INC_STATS(cp1xops); switch (MIPSInst_FMA_FFMT(ir)) { case s_fmt:{ /* 0 */ ieee754sp(*handler) (ieee754sp, ieee754sp, ieee754sp); ieee754sp fd, fr, fs, ft; u32 __user *va; u32 val; switch (MIPSInst_FUNC(ir)) { case lwxc1_op: va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] + xcp->regs[MIPSInst_FT(ir)]); MIPS_FPU_EMU_INC_STATS(loads); if (!access_ok(VERIFY_READ, va, sizeof(u32))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__get_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } SITOREG(val, MIPSInst_FD(ir)); break; case swxc1_op: va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] + xcp->regs[MIPSInst_FT(ir)]); MIPS_FPU_EMU_INC_STATS(stores); SIFROMREG(val, MIPSInst_FS(ir)); if (!access_ok(VERIFY_WRITE, va, sizeof(u32))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (put_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } break; case madd_s_op: handler = fpemu_sp_madd; goto scoptop; case msub_s_op: handler = fpemu_sp_msub; goto scoptop; case nmadd_s_op: handler = fpemu_sp_nmadd; goto scoptop; case nmsub_s_op: handler = fpemu_sp_nmsub; goto scoptop; scoptop: SPFROMREG(fr, MIPSInst_FR(ir)); SPFROMREG(fs, MIPSInst_FS(ir)); SPFROMREG(ft, MIPSInst_FT(ir)); fd = (*handler) (fr, fs, ft); SPTOREG(fd, MIPSInst_FD(ir)); copcsr: if (ieee754_cxtest(IEEE754_INEXACT)) rcsr |= FPU_CSR_INE_X | FPU_CSR_INE_S; if (ieee754_cxtest(IEEE754_UNDERFLOW)) rcsr |= FPU_CSR_UDF_X | FPU_CSR_UDF_S; if (ieee754_cxtest(IEEE754_OVERFLOW)) rcsr |= FPU_CSR_OVF_X | FPU_CSR_OVF_S; if (ieee754_cxtest(IEEE754_INVALID_OPERATION)) rcsr |= FPU_CSR_INV_X | FPU_CSR_INV_S; ctx->fcr31 = (ctx->fcr31 & ~FPU_CSR_ALL_X) | rcsr; if ((ctx->fcr31 >> 5) & ctx->fcr31 & FPU_CSR_ALL_E) { /*printk ("SIGFPE: fpu csr = %08x\n", ctx->fcr31); */ return SIGFPE; } break; default: return SIGILL; } break; } case d_fmt:{ /* 1 */ ieee754dp(*handler) (ieee754dp, ieee754dp, ieee754dp); ieee754dp fd, fr, fs, ft; u64 __user *va; u64 val; switch (MIPSInst_FUNC(ir)) { case ldxc1_op: va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] + xcp->regs[MIPSInst_FT(ir)]); MIPS_FPU_EMU_INC_STATS(loads); if (!access_ok(VERIFY_READ, va, sizeof(u64))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__get_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } DITOREG(val, MIPSInst_FD(ir)); break; case sdxc1_op: va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] + xcp->regs[MIPSInst_FT(ir)]); MIPS_FPU_EMU_INC_STATS(stores); DIFROMREG(val, MIPSInst_FS(ir)); if (!access_ok(VERIFY_WRITE, va, sizeof(u64))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__put_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } break; case madd_d_op: handler = fpemu_dp_madd; goto dcoptop; case msub_d_op: handler = fpemu_dp_msub; goto dcoptop; case nmadd_d_op: handler = fpemu_dp_nmadd; goto dcoptop; case nmsub_d_op: handler = fpemu_dp_nmsub; goto dcoptop; dcoptop: DPFROMREG(fr, MIPSInst_FR(ir)); DPFROMREG(fs, MIPSInst_FS(ir)); DPFROMREG(ft, MIPSInst_FT(ir)); fd = (*handler) (fr, fs, ft); DPTOREG(fd, MIPSInst_FD(ir)); goto copcsr; default: return SIGILL; } break; } case 0x7: /* 7 */ if (MIPSInst_FUNC(ir) != pfetch_op) { return SIGILL; } /* ignore prefx operation */ break; default: return SIGILL; } return 0; } #endif /* * Emulate a single COP1 arithmetic instruction. */ static int fpu_emu(struct pt_regs *xcp, struct mips_fpu_struct *ctx, mips_instruction ir) { int rfmt; /* resulting format */ unsigned rcsr = 0; /* resulting csr */ unsigned cond; union { ieee754dp d; ieee754sp s; int w; #ifdef __mips64 s64 l; #endif } rv; /* resulting value */ MIPS_FPU_EMU_INC_STATS(cp1ops); switch (rfmt = (MIPSInst_FFMT(ir) & 0xf)) { case s_fmt:{ /* 0 */ union { ieee754sp(*b) (ieee754sp, ieee754sp); ieee754sp(*u) (ieee754sp); } handler; switch (MIPSInst_FUNC(ir)) { /* binary ops */ case fadd_op: handler.b = ieee754sp_add; goto scopbop; case fsub_op: handler.b = ieee754sp_sub; goto scopbop; case fmul_op: handler.b = ieee754sp_mul; goto scopbop; case fdiv_op: handler.b = ieee754sp_div; goto scopbop; /* unary ops */ #if __mips >= 2 || defined(__mips64) case fsqrt_op: handler.u = ieee754sp_sqrt; goto scopuop; #endif #if __mips >= 4 && __mips != 32 case frsqrt_op: handler.u = fpemu_sp_rsqrt; goto scopuop; case frecip_op: handler.u = fpemu_sp_recip; goto scopuop; #endif #if __mips >= 4 case fmovc_op: cond = fpucondbit[MIPSInst_FT(ir) >> 2]; if (((ctx->fcr31 & cond) != 0) != ((MIPSInst_FT(ir) & 1) != 0)) return 0; SPFROMREG(rv.s, MIPSInst_FS(ir)); break; case fmovz_op: if (xcp->regs[MIPSInst_FT(ir)] != 0) return 0; SPFROMREG(rv.s, MIPSInst_FS(ir)); break; case fmovn_op: if (xcp->regs[MIPSInst_FT(ir)] == 0) return 0; SPFROMREG(rv.s, MIPSInst_FS(ir)); break; #endif case fabs_op: handler.u = ieee754sp_abs; goto scopuop; case fneg_op: handler.u = ieee754sp_neg; goto scopuop; case fmov_op: /* an easy one */ SPFROMREG(rv.s, MIPSInst_FS(ir)); goto copcsr; /* binary op on handler */ scopbop: { ieee754sp fs, ft; SPFROMREG(fs, MIPSInst_FS(ir)); SPFROMREG(ft, MIPSInst_FT(ir)); rv.s = (*handler.b) (fs, ft); goto copcsr; } scopuop: { ieee754sp fs; SPFROMREG(fs, MIPSInst_FS(ir)); rv.s = (*handler.u) (fs); goto copcsr; } copcsr: if (ieee754_cxtest(IEEE754_INEXACT)) rcsr |= FPU_CSR_INE_X | FPU_CSR_INE_S; if (ieee754_cxtest(IEEE754_UNDERFLOW)) rcsr |= FPU_CSR_UDF_X | FPU_CSR_UDF_S; if (ieee754_cxtest(IEEE754_OVERFLOW)) rcsr |= FPU_CSR_OVF_X | FPU_CSR_OVF_S; if (ieee754_cxtest(IEEE754_ZERO_DIVIDE)) rcsr |= FPU_CSR_DIV_X | FPU_CSR_DIV_S; if (ieee754_cxtest(IEEE754_INVALID_OPERATION)) rcsr |= FPU_CSR_INV_X | FPU_CSR_INV_S; break; /* unary conv ops */ case fcvts_op: return SIGILL; /* not defined */ case fcvtd_op:{ ieee754sp fs; SPFROMREG(fs, MIPSInst_FS(ir)); rv.d = ieee754dp_fsp(fs); rfmt = d_fmt; goto copcsr; } case fcvtw_op:{ ieee754sp fs; SPFROMREG(fs, MIPSInst_FS(ir)); rv.w = ieee754sp_tint(fs); rfmt = w_fmt; goto copcsr; } #if __mips >= 2 || defined(__mips64) case fround_op: case ftrunc_op: case fceil_op: case ffloor_op:{ unsigned int oldrm = ieee754_csr.rm; ieee754sp fs; SPFROMREG(fs, MIPSInst_FS(ir)); ieee754_csr.rm = ieee_rm[modeindex(MIPSInst_FUNC(ir))]; rv.w = ieee754sp_tint(fs); ieee754_csr.rm = oldrm; rfmt = w_fmt; goto copcsr; } #endif /* __mips >= 2 */ #if defined(__mips64) case fcvtl_op:{ ieee754sp fs; SPFROMREG(fs, MIPSInst_FS(ir)); rv.l = ieee754sp_tlong(fs); rfmt = l_fmt; goto copcsr; } case froundl_op: case ftruncl_op: case fceill_op: case ffloorl_op:{ unsigned int oldrm = ieee754_csr.rm; ieee754sp fs; SPFROMREG(fs, MIPSInst_FS(ir)); ieee754_csr.rm = ieee_rm[modeindex(MIPSInst_FUNC(ir))]; rv.l = ieee754sp_tlong(fs); ieee754_csr.rm = oldrm; rfmt = l_fmt; goto copcsr; } #endif /* defined(__mips64) */ default: if (MIPSInst_FUNC(ir) >= fcmp_op) { unsigned cmpop = MIPSInst_FUNC(ir) - fcmp_op; ieee754sp fs, ft; SPFROMREG(fs, MIPSInst_FS(ir)); SPFROMREG(ft, MIPSInst_FT(ir)); rv.w = ieee754sp_cmp(fs, ft, cmptab[cmpop & 0x7], cmpop & 0x8); rfmt = -1; if ((cmpop & 0x8) && ieee754_cxtest (IEEE754_INVALID_OPERATION)) rcsr = FPU_CSR_INV_X | FPU_CSR_INV_S; else goto copcsr; } else { return SIGILL; } break; } break; } case d_fmt:{ union { ieee754dp(*b) (ieee754dp, ieee754dp); ieee754dp(*u) (ieee754dp); } handler; switch (MIPSInst_FUNC(ir)) { /* binary ops */ case fadd_op: handler.b = ieee754dp_add; goto dcopbop; case fsub_op: handler.b = ieee754dp_sub; goto dcopbop; case fmul_op: handler.b = ieee754dp_mul; goto dcopbop; case fdiv_op: handler.b = ieee754dp_div; goto dcopbop; /* unary ops */ #if __mips >= 2 || defined(__mips64) case fsqrt_op: handler.u = ieee754dp_sqrt; goto dcopuop; #endif #if __mips >= 4 && __mips != 32 case frsqrt_op: handler.u = fpemu_dp_rsqrt; goto dcopuop; case frecip_op: handler.u = fpemu_dp_recip; goto dcopuop; #endif #if __mips >= 4 case fmovc_op: cond = fpucondbit[MIPSInst_FT(ir) >> 2]; if (((ctx->fcr31 & cond) != 0) != ((MIPSInst_FT(ir) & 1) != 0)) return 0; DPFROMREG(rv.d, MIPSInst_FS(ir)); break; case fmovz_op: if (xcp->regs[MIPSInst_FT(ir)] != 0) return 0; DPFROMREG(rv.d, MIPSInst_FS(ir)); break; case fmovn_op: if (xcp->regs[MIPSInst_FT(ir)] == 0) return 0; DPFROMREG(rv.d, MIPSInst_FS(ir)); break; #endif case fabs_op: handler.u = ieee754dp_abs; goto dcopuop; case fneg_op: handler.u = ieee754dp_neg; goto dcopuop; case fmov_op: /* an easy one */ DPFROMREG(rv.d, MIPSInst_FS(ir)); goto copcsr; /* binary op on handler */ dcopbop:{ ieee754dp fs, ft; DPFROMREG(fs, MIPSInst_FS(ir)); DPFROMREG(ft, MIPSInst_FT(ir)); rv.d = (*handler.b) (fs, ft); goto copcsr; } dcopuop:{ ieee754dp fs; DPFROMREG(fs, MIPSInst_FS(ir)); rv.d = (*handler.u) (fs); goto copcsr; } /* unary conv ops */ case fcvts_op:{ ieee754dp fs; DPFROMREG(fs, MIPSInst_FS(ir)); rv.s = ieee754sp_fdp(fs); rfmt = s_fmt; goto copcsr; } case fcvtd_op: return SIGILL; /* not defined */ case fcvtw_op:{ ieee754dp fs; DPFROMREG(fs, MIPSInst_FS(ir)); rv.w = ieee754dp_tint(fs); /* wrong */ rfmt = w_fmt; goto copcsr; } #if __mips >= 2 || defined(__mips64) case fround_op: case ftrunc_op: case fceil_op: case ffloor_op:{ unsigned int oldrm = ieee754_csr.rm; ieee754dp fs; DPFROMREG(fs, MIPSInst_FS(ir)); ieee754_csr.rm = ieee_rm[modeindex(MIPSInst_FUNC(ir))]; rv.w = ieee754dp_tint(fs); ieee754_csr.rm = oldrm; rfmt = w_fmt; goto copcsr; } #endif #if defined(__mips64) case fcvtl_op:{ ieee754dp fs; DPFROMREG(fs, MIPSInst_FS(ir)); rv.l = ieee754dp_tlong(fs); rfmt = l_fmt; goto copcsr; } case froundl_op: case ftruncl_op: case fceill_op: case ffloorl_op:{ unsigned int oldrm = ieee754_csr.rm; ieee754dp fs; DPFROMREG(fs, MIPSInst_FS(ir)); ieee754_csr.rm = ieee_rm[modeindex(MIPSInst_FUNC(ir))]; rv.l = ieee754dp_tlong(fs); ieee754_csr.rm = oldrm; rfmt = l_fmt; goto copcsr; } #endif /* __mips >= 3 */ default: if (MIPSInst_FUNC(ir) >= fcmp_op) { unsigned cmpop = MIPSInst_FUNC(ir) - fcmp_op; ieee754dp fs, ft; DPFROMREG(fs, MIPSInst_FS(ir)); DPFROMREG(ft, MIPSInst_FT(ir)); rv.w = ieee754dp_cmp(fs, ft, cmptab[cmpop & 0x7], cmpop & 0x8); rfmt = -1; if ((cmpop & 0x8) && ieee754_cxtest (IEEE754_INVALID_OPERATION)) rcsr = FPU_CSR_INV_X | FPU_CSR_INV_S; else goto copcsr; } else { return SIGILL; } break; } break; } case w_fmt:{ ieee754sp fs; switch (MIPSInst_FUNC(ir)) { case fcvts_op: /* convert word to single precision real */ SPFROMREG(fs, MIPSInst_FS(ir)); rv.s = ieee754sp_fint(fs.bits); rfmt = s_fmt; goto copcsr; case fcvtd_op: /* convert word to double precision real */ SPFROMREG(fs, MIPSInst_FS(ir)); rv.d = ieee754dp_fint(fs.bits); rfmt = d_fmt; goto copcsr; default: return SIGILL; } break; } #if defined(__mips64) case l_fmt:{ switch (MIPSInst_FUNC(ir)) { case fcvts_op: /* convert long to single precision real */ rv.s = ieee754sp_flong(ctx->fpr[MIPSInst_FS(ir)]); rfmt = s_fmt; goto copcsr; case fcvtd_op: /* convert long to double precision real */ rv.d = ieee754dp_flong(ctx->fpr[MIPSInst_FS(ir)]); rfmt = d_fmt; goto copcsr; default: return SIGILL; } break; } #endif default: return SIGILL; } /* * Update the fpu CSR register for this operation. * If an exception is required, generate a tidy SIGFPE exception, * without updating the result register. * Note: cause exception bits do not accumulate, they are rewritten * for each op; only the flag/sticky bits accumulate. */ ctx->fcr31 = (ctx->fcr31 & ~FPU_CSR_ALL_X) | rcsr; if ((ctx->fcr31 >> 5) & ctx->fcr31 & FPU_CSR_ALL_E) { /*printk ("SIGFPE: fpu csr = %08x\n",ctx->fcr31); */ return SIGFPE; } /* * Now we can safely write the result back to the register file. */ switch (rfmt) { case -1:{ #if __mips >= 4 cond = fpucondbit[MIPSInst_FD(ir) >> 2]; #else cond = FPU_CSR_COND; #endif if (rv.w) ctx->fcr31 |= cond; else ctx->fcr31 &= ~cond; break; } case d_fmt: DPTOREG(rv.d, MIPSInst_FD(ir)); break; case s_fmt: SPTOREG(rv.s, MIPSInst_FD(ir)); break; case w_fmt: SITOREG(rv.w, MIPSInst_FD(ir)); break; #if defined(__mips64) case l_fmt: DITOREG(rv.l, MIPSInst_FD(ir)); break; #endif default: return SIGILL; } return 0; } int fpu_emulator_cop1Handler(struct pt_regs *xcp, struct mips_fpu_struct *ctx, int has_fpu, void *__user *fault_addr) { unsigned long oldepc, prevepc; struct mm_decoded_insn dec_insn; u16 instr[4]; u16 *instr_ptr; int sig = 0; oldepc = xcp->cp0_epc; do { prevepc = xcp->cp0_epc; if (get_isa16_mode(prevepc) && cpu_has_mmips) { /* * Get next 2 microMIPS instructions and convert them * into 32-bit instructions. */ if ((get_user(instr[0], (u16 __user *)msk_isa16_mode(xcp->cp0_epc))) || (get_user(instr[1], (u16 __user *)msk_isa16_mode(xcp->cp0_epc + 2))) || (get_user(instr[2], (u16 __user *)msk_isa16_mode(xcp->cp0_epc + 4))) || (get_user(instr[3], (u16 __user *)msk_isa16_mode(xcp->cp0_epc + 6)))) { MIPS_FPU_EMU_INC_STATS(errors); return SIGBUS; } instr_ptr = instr; /* Get first instruction. */ if (mm_insn_16bit(*instr_ptr)) { /* Duplicate the half-word. */ dec_insn.insn = (*instr_ptr << 16) | (*instr_ptr); /* 16-bit instruction. */ dec_insn.pc_inc = 2; instr_ptr += 1; } else { dec_insn.insn = (*instr_ptr << 16) | *(instr_ptr+1); /* 32-bit instruction. */ dec_insn.pc_inc = 4; instr_ptr += 2; } /* Get second instruction. */ if (mm_insn_16bit(*instr_ptr)) { /* Duplicate the half-word. */ dec_insn.next_insn = (*instr_ptr << 16) | (*instr_ptr); /* 16-bit instruction. */ dec_insn.next_pc_inc = 2; } else { dec_insn.next_insn = (*instr_ptr << 16) | *(instr_ptr+1); /* 32-bit instruction. */ dec_insn.next_pc_inc = 4; } dec_insn.micro_mips_mode = 1; } else { if ((get_user(dec_insn.insn, (mips_instruction __user *) xcp->cp0_epc)) || (get_user(dec_insn.next_insn, (mips_instruction __user *)(xcp->cp0_epc+4)))) { MIPS_FPU_EMU_INC_STATS(errors); return SIGBUS; } dec_insn.pc_inc = 4; dec_insn.next_pc_inc = 4; dec_insn.micro_mips_mode = 0; } if ((dec_insn.insn == 0) || ((dec_insn.pc_inc == 2) && ((dec_insn.insn & 0xffff) == MM_NOP16))) xcp->cp0_epc += dec_insn.pc_inc; /* Skip NOPs */ else { /* * The 'ieee754_csr' is an alias of * ctx->fcr31. No need to copy ctx->fcr31 to * ieee754_csr. But ieee754_csr.rm is ieee * library modes. (not mips rounding mode) */ /* convert to ieee library modes */ ieee754_csr.rm = ieee_rm[ieee754_csr.rm]; sig = cop1Emulate(xcp, ctx, dec_insn, fault_addr); /* revert to mips rounding mode */ ieee754_csr.rm = mips_rm[ieee754_csr.rm]; } if (has_fpu) break; if (sig) break; cond_resched(); } while (xcp->cp0_epc > prevepc); /* SIGILL indicates a non-fpu instruction */ if (sig == SIGILL && xcp->cp0_epc != oldepc) /* but if epc has advanced, then ignore it */ sig = 0; return sig; } #ifdef CONFIG_DEBUG_FS static int fpuemu_stat_get(void *data, u64 *val) { int cpu; unsigned long sum = 0; for_each_online_cpu(cpu) { struct mips_fpu_emulator_stats *ps; local_t *pv; ps = &per_cpu(fpuemustats, cpu); pv = (void *)ps + (unsigned long)data; sum += local_read(pv); } *val = sum; return 0; } DEFINE_SIMPLE_ATTRIBUTE(fops_fpuemu_stat, fpuemu_stat_get, NULL, "%llu\n"); extern struct dentry *mips_debugfs_dir; static int __init debugfs_fpuemu(void) { struct dentry *d, *dir; if (!mips_debugfs_dir) return -ENODEV; dir = debugfs_create_dir("fpuemustats", mips_debugfs_dir); if (!dir) return -ENOMEM; #define FPU_STAT_CREATE(M) \ do { \ d = debugfs_create_file(#M , S_IRUGO, dir, \ (void *)offsetof(struct mips_fpu_emulator_stats, M), \ &fops_fpuemu_stat); \ if (!d) \ return -ENOMEM; \ } while (0) FPU_STAT_CREATE(emulated); FPU_STAT_CREATE(loads); FPU_STAT_CREATE(stores); FPU_STAT_CREATE(cp1ops); FPU_STAT_CREATE(cp1xops); FPU_STAT_CREATE(errors); return 0; } __initcall(debugfs_fpuemu); #endif
gpl-2.0
xiaognol/android_kernel_chm_cl00
arch/mips/netlogic/xlp/nlm_hal.c
2009
4350
/* * Copyright 2003-2011 NetLogic Microsystems, Inc. (NetLogic). All rights * reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the NetLogic * license below: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY NETLOGIC ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL NETLOGIC OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <linux/types.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/delay.h> #include <asm/mipsregs.h> #include <asm/time.h> #include <asm/netlogic/common.h> #include <asm/netlogic/haldefs.h> #include <asm/netlogic/xlp-hal/iomap.h> #include <asm/netlogic/xlp-hal/xlp.h> #include <asm/netlogic/xlp-hal/pic.h> #include <asm/netlogic/xlp-hal/sys.h> /* Main initialization */ void nlm_node_init(int node) { struct nlm_soc_info *nodep; nodep = nlm_get_node(node); nodep->sysbase = nlm_get_sys_regbase(node); nodep->picbase = nlm_get_pic_regbase(node); nodep->ebase = read_c0_ebase() & (~((1 << 12) - 1)); spin_lock_init(&nodep->piclock); } int nlm_irq_to_irt(int irq) { uint64_t pcibase; int devoff, irt; switch (irq) { case PIC_UART_0_IRQ: devoff = XLP_IO_UART0_OFFSET(0); break; case PIC_UART_1_IRQ: devoff = XLP_IO_UART1_OFFSET(0); break; case PIC_EHCI_0_IRQ: devoff = XLP_IO_USB_EHCI0_OFFSET(0); break; case PIC_EHCI_1_IRQ: devoff = XLP_IO_USB_EHCI1_OFFSET(0); break; case PIC_OHCI_0_IRQ: devoff = XLP_IO_USB_OHCI0_OFFSET(0); break; case PIC_OHCI_1_IRQ: devoff = XLP_IO_USB_OHCI1_OFFSET(0); break; case PIC_OHCI_2_IRQ: devoff = XLP_IO_USB_OHCI2_OFFSET(0); break; case PIC_OHCI_3_IRQ: devoff = XLP_IO_USB_OHCI3_OFFSET(0); break; case PIC_MMC_IRQ: devoff = XLP_IO_SD_OFFSET(0); break; case PIC_I2C_0_IRQ: devoff = XLP_IO_I2C0_OFFSET(0); break; case PIC_I2C_1_IRQ: devoff = XLP_IO_I2C1_OFFSET(0); break; default: devoff = 0; break; } if (devoff != 0) { pcibase = nlm_pcicfg_base(devoff); irt = nlm_read_reg(pcibase, XLP_PCI_IRTINFO_REG) & 0xffff; /* HW bug, I2C 1 irt entry is off by one */ if (irq == PIC_I2C_1_IRQ) irt = irt + 1; } else if (irq >= PIC_PCIE_LINK_0_IRQ && irq <= PIC_PCIE_LINK_3_IRQ) { /* HW bug, PCI IRT entries are bad on early silicon, fix */ irt = PIC_IRT_PCIE_LINK_INDEX(irq - PIC_PCIE_LINK_0_IRQ); } else { irt = -1; } return irt; } unsigned int nlm_get_core_frequency(int node, int core) { unsigned int pll_divf, pll_divr, dfs_div, ext_div; unsigned int rstval, dfsval, denom; uint64_t num, sysbase; sysbase = nlm_get_node(node)->sysbase; rstval = nlm_read_sys_reg(sysbase, SYS_POWER_ON_RESET_CFG); dfsval = nlm_read_sys_reg(sysbase, SYS_CORE_DFS_DIV_VALUE); pll_divf = ((rstval >> 10) & 0x7f) + 1; pll_divr = ((rstval >> 8) & 0x3) + 1; ext_div = ((rstval >> 30) & 0x3) + 1; dfs_div = ((dfsval >> (core * 4)) & 0xf) + 1; num = 800000000ULL * pll_divf; denom = 3 * pll_divr * ext_div * dfs_div; do_div(num, denom); return (unsigned int)num; } unsigned int nlm_get_cpu_frequency(void) { return nlm_get_core_frequency(0, 0); }
gpl-2.0
neonicus/Paralax
drivers/media/video/cx88/cx88-alsa.c
2521
25739
/* * * Support for audio capture * PCI function #1 of the cx2388x. * * (c) 2007 Trent Piepho <xyzzy@speakeasy.org> * (c) 2005,2006 Ricardo Cerqueira <v4l@cerqueira.org> * (c) 2005 Mauro Carvalho Chehab <mchehab@infradead.org> * Based on a dummy cx88 module by Gerd Knorr <kraxel@bytesex.org> * Based on dummy.c by Jaroslav Kysela <perex@perex.cz> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/module.h> #include <linux/init.h> #include <linux/device.h> #include <linux/interrupt.h> #include <linux/vmalloc.h> #include <linux/dma-mapping.h> #include <linux/pci.h> #include <linux/slab.h> #include <asm/delay.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/control.h> #include <sound/initval.h> #include <sound/tlv.h> #include <media/wm8775.h> #include "cx88.h" #include "cx88-reg.h" #define dprintk(level,fmt, arg...) if (debug >= level) \ printk(KERN_INFO "%s/1: " fmt, chip->core->name , ## arg) #define dprintk_core(level,fmt, arg...) if (debug >= level) \ printk(KERN_DEBUG "%s/1: " fmt, chip->core->name , ## arg) /**************************************************************************** Data type declarations - Can be moded to a header file later ****************************************************************************/ struct cx88_audio_buffer { unsigned int bpl; struct btcx_riscmem risc; struct videobuf_dmabuf dma; }; struct cx88_audio_dev { struct cx88_core *core; struct cx88_dmaqueue q; /* pci i/o */ struct pci_dev *pci; /* audio controls */ int irq; struct snd_card *card; spinlock_t reg_lock; atomic_t count; unsigned int dma_size; unsigned int period_size; unsigned int num_periods; struct videobuf_dmabuf *dma_risc; struct cx88_audio_buffer *buf; struct snd_pcm_substream *substream; }; typedef struct cx88_audio_dev snd_cx88_card_t; /**************************************************************************** Module global static vars ****************************************************************************/ static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */ static const char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */ static int enable[SNDRV_CARDS] = {1, [1 ... (SNDRV_CARDS - 1)] = 1}; module_param_array(enable, bool, NULL, 0444); MODULE_PARM_DESC(enable, "Enable cx88x soundcard. default enabled."); module_param_array(index, int, NULL, 0444); MODULE_PARM_DESC(index, "Index value for cx88x capture interface(s)."); /**************************************************************************** Module macros ****************************************************************************/ MODULE_DESCRIPTION("ALSA driver module for cx2388x based TV cards"); MODULE_AUTHOR("Ricardo Cerqueira"); MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@infradead.org>"); MODULE_LICENSE("GPL"); MODULE_SUPPORTED_DEVICE("{{Conexant,23881}," "{{Conexant,23882}," "{{Conexant,23883}"); static unsigned int debug; module_param(debug,int,0644); MODULE_PARM_DESC(debug,"enable debug messages"); /**************************************************************************** Module specific funtions ****************************************************************************/ /* * BOARD Specific: Sets audio DMA */ static int _cx88_start_audio_dma(snd_cx88_card_t *chip) { struct cx88_audio_buffer *buf = chip->buf; struct cx88_core *core=chip->core; const struct sram_channel *audio_ch = &cx88_sram_channels[SRAM_CH25]; /* Make sure RISC/FIFO are off before changing FIFO/RISC settings */ cx_clear(MO_AUD_DMACNTRL, 0x11); /* setup fifo + format - out channel */ cx88_sram_channel_setup(chip->core, audio_ch, buf->bpl, buf->risc.dma); /* sets bpl size */ cx_write(MO_AUDD_LNGTH, buf->bpl); /* reset counter */ cx_write(MO_AUDD_GPCNTRL, GP_COUNT_CONTROL_RESET); atomic_set(&chip->count, 0); dprintk(1, "Start audio DMA, %d B/line, %d lines/FIFO, %d periods, %d " "byte buffer\n", buf->bpl, cx_read(audio_ch->cmds_start + 8)>>1, chip->num_periods, buf->bpl * chip->num_periods); /* Enables corresponding bits at AUD_INT_STAT */ cx_write(MO_AUD_INTMSK, AUD_INT_OPC_ERR | AUD_INT_DN_SYNC | AUD_INT_DN_RISCI2 | AUD_INT_DN_RISCI1); /* Clean any pending interrupt bits already set */ cx_write(MO_AUD_INTSTAT, ~0); /* enable audio irqs */ cx_set(MO_PCI_INTMSK, chip->core->pci_irqmask | PCI_INT_AUDINT); /* start dma */ cx_set(MO_DEV_CNTRL2, (1<<5)); /* Enables Risc Processor */ cx_set(MO_AUD_DMACNTRL, 0x11); /* audio downstream FIFO and RISC enable */ if (debug) cx88_sram_channel_dump(chip->core, audio_ch); return 0; } /* * BOARD Specific: Resets audio DMA */ static int _cx88_stop_audio_dma(snd_cx88_card_t *chip) { struct cx88_core *core=chip->core; dprintk(1, "Stopping audio DMA\n"); /* stop dma */ cx_clear(MO_AUD_DMACNTRL, 0x11); /* disable irqs */ cx_clear(MO_PCI_INTMSK, PCI_INT_AUDINT); cx_clear(MO_AUD_INTMSK, AUD_INT_OPC_ERR | AUD_INT_DN_SYNC | AUD_INT_DN_RISCI2 | AUD_INT_DN_RISCI1); if (debug) cx88_sram_channel_dump(chip->core, &cx88_sram_channels[SRAM_CH25]); return 0; } #define MAX_IRQ_LOOP 50 /* * BOARD Specific: IRQ dma bits */ static const char *cx88_aud_irqs[32] = { "dn_risci1", "up_risci1", "rds_dn_risc1", /* 0-2 */ NULL, /* reserved */ "dn_risci2", "up_risci2", "rds_dn_risc2", /* 4-6 */ NULL, /* reserved */ "dnf_of", "upf_uf", "rds_dnf_uf", /* 8-10 */ NULL, /* reserved */ "dn_sync", "up_sync", "rds_dn_sync", /* 12-14 */ NULL, /* reserved */ "opc_err", "par_err", "rip_err", /* 16-18 */ "pci_abort", "ber_irq", "mchg_irq" /* 19-21 */ }; /* * BOARD Specific: Threats IRQ audio specific calls */ static void cx8801_aud_irq(snd_cx88_card_t *chip) { struct cx88_core *core = chip->core; u32 status, mask; status = cx_read(MO_AUD_INTSTAT); mask = cx_read(MO_AUD_INTMSK); if (0 == (status & mask)) return; cx_write(MO_AUD_INTSTAT, status); if (debug > 1 || (status & mask & ~0xff)) cx88_print_irqbits(core->name, "irq aud", cx88_aud_irqs, ARRAY_SIZE(cx88_aud_irqs), status, mask); /* risc op code error */ if (status & AUD_INT_OPC_ERR) { printk(KERN_WARNING "%s/1: Audio risc op code error\n",core->name); cx_clear(MO_AUD_DMACNTRL, 0x11); cx88_sram_channel_dump(core, &cx88_sram_channels[SRAM_CH25]); } if (status & AUD_INT_DN_SYNC) { dprintk(1, "Downstream sync error\n"); cx_write(MO_AUDD_GPCNTRL, GP_COUNT_CONTROL_RESET); return; } /* risc1 downstream */ if (status & AUD_INT_DN_RISCI1) { atomic_set(&chip->count, cx_read(MO_AUDD_GPCNT)); snd_pcm_period_elapsed(chip->substream); } /* FIXME: Any other status should deserve a special handling? */ } /* * BOARD Specific: Handles IRQ calls */ static irqreturn_t cx8801_irq(int irq, void *dev_id) { snd_cx88_card_t *chip = dev_id; struct cx88_core *core = chip->core; u32 status; int loop, handled = 0; for (loop = 0; loop < MAX_IRQ_LOOP; loop++) { status = cx_read(MO_PCI_INTSTAT) & (core->pci_irqmask | PCI_INT_AUDINT); if (0 == status) goto out; dprintk(3, "cx8801_irq loop %d/%d, status %x\n", loop, MAX_IRQ_LOOP, status); handled = 1; cx_write(MO_PCI_INTSTAT, status); if (status & core->pci_irqmask) cx88_core_irq(core, status); if (status & PCI_INT_AUDINT) cx8801_aud_irq(chip); } if (MAX_IRQ_LOOP == loop) { printk(KERN_ERR "%s/1: IRQ loop detected, disabling interrupts\n", core->name); cx_clear(MO_PCI_INTMSK, PCI_INT_AUDINT); } out: return IRQ_RETVAL(handled); } static int dsp_buffer_free(snd_cx88_card_t *chip) { BUG_ON(!chip->dma_size); dprintk(2,"Freeing buffer\n"); videobuf_dma_unmap(&chip->pci->dev, chip->dma_risc); videobuf_dma_free(chip->dma_risc); btcx_riscmem_free(chip->pci,&chip->buf->risc); kfree(chip->buf); chip->dma_risc = NULL; chip->dma_size = 0; return 0; } /**************************************************************************** ALSA PCM Interface ****************************************************************************/ /* * Digital hardware definition */ #define DEFAULT_FIFO_SIZE 4096 static const struct snd_pcm_hardware snd_cx88_digital_hw = { .info = SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_MMAP_VALID, .formats = SNDRV_PCM_FMTBIT_S16_LE, .rates = SNDRV_PCM_RATE_48000, .rate_min = 48000, .rate_max = 48000, .channels_min = 2, .channels_max = 2, /* Analog audio output will be full of clicks and pops if there are not exactly four lines in the SRAM FIFO buffer. */ .period_bytes_min = DEFAULT_FIFO_SIZE/4, .period_bytes_max = DEFAULT_FIFO_SIZE/4, .periods_min = 1, .periods_max = 1024, .buffer_bytes_max = (1024*1024), }; /* * audio pcm capture open callback */ static int snd_cx88_pcm_open(struct snd_pcm_substream *substream) { snd_cx88_card_t *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; int err; if (!chip) { printk(KERN_ERR "BUG: cx88 can't find device struct." " Can't proceed with open\n"); return -ENODEV; } err = snd_pcm_hw_constraint_pow2(runtime, 0, SNDRV_PCM_HW_PARAM_PERIODS); if (err < 0) goto _error; chip->substream = substream; runtime->hw = snd_cx88_digital_hw; if (cx88_sram_channels[SRAM_CH25].fifo_size != DEFAULT_FIFO_SIZE) { unsigned int bpl = cx88_sram_channels[SRAM_CH25].fifo_size / 4; bpl &= ~7; /* must be multiple of 8 */ runtime->hw.period_bytes_min = bpl; runtime->hw.period_bytes_max = bpl; } return 0; _error: dprintk(1,"Error opening PCM!\n"); return err; } /* * audio close callback */ static int snd_cx88_close(struct snd_pcm_substream *substream) { return 0; } /* * hw_params callback */ static int snd_cx88_hw_params(struct snd_pcm_substream * substream, struct snd_pcm_hw_params * hw_params) { snd_cx88_card_t *chip = snd_pcm_substream_chip(substream); struct videobuf_dmabuf *dma; struct cx88_audio_buffer *buf; int ret; if (substream->runtime->dma_area) { dsp_buffer_free(chip); substream->runtime->dma_area = NULL; } chip->period_size = params_period_bytes(hw_params); chip->num_periods = params_periods(hw_params); chip->dma_size = chip->period_size * params_periods(hw_params); BUG_ON(!chip->dma_size); BUG_ON(chip->num_periods & (chip->num_periods-1)); buf = kzalloc(sizeof(*buf), GFP_KERNEL); if (NULL == buf) return -ENOMEM; buf->bpl = chip->period_size; dma = &buf->dma; videobuf_dma_init(dma); ret = videobuf_dma_init_kernel(dma, PCI_DMA_FROMDEVICE, (PAGE_ALIGN(chip->dma_size) >> PAGE_SHIFT)); if (ret < 0) goto error; ret = videobuf_dma_map(&chip->pci->dev, dma); if (ret < 0) goto error; ret = cx88_risc_databuffer(chip->pci, &buf->risc, dma->sglist, chip->period_size, chip->num_periods, 1); if (ret < 0) goto error; /* Loop back to start of program */ buf->risc.jmp[0] = cpu_to_le32(RISC_JUMP|RISC_IRQ1|RISC_CNT_INC); buf->risc.jmp[1] = cpu_to_le32(buf->risc.dma); chip->buf = buf; chip->dma_risc = dma; substream->runtime->dma_area = chip->dma_risc->vaddr; substream->runtime->dma_bytes = chip->dma_size; substream->runtime->dma_addr = 0; return 0; error: kfree(buf); return ret; } /* * hw free callback */ static int snd_cx88_hw_free(struct snd_pcm_substream * substream) { snd_cx88_card_t *chip = snd_pcm_substream_chip(substream); if (substream->runtime->dma_area) { dsp_buffer_free(chip); substream->runtime->dma_area = NULL; } return 0; } /* * prepare callback */ static int snd_cx88_prepare(struct snd_pcm_substream *substream) { return 0; } /* * trigger callback */ static int snd_cx88_card_trigger(struct snd_pcm_substream *substream, int cmd) { snd_cx88_card_t *chip = snd_pcm_substream_chip(substream); int err; /* Local interrupts are already disabled by ALSA */ spin_lock(&chip->reg_lock); switch (cmd) { case SNDRV_PCM_TRIGGER_START: err=_cx88_start_audio_dma(chip); break; case SNDRV_PCM_TRIGGER_STOP: err=_cx88_stop_audio_dma(chip); break; default: err=-EINVAL; break; } spin_unlock(&chip->reg_lock); return err; } /* * pointer callback */ static snd_pcm_uframes_t snd_cx88_pointer(struct snd_pcm_substream *substream) { snd_cx88_card_t *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; u16 count; count = atomic_read(&chip->count); // dprintk(2, "%s - count %d (+%u), period %d, frame %lu\n", __func__, // count, new, count & (runtime->periods-1), // runtime->period_size * (count & (runtime->periods-1))); return runtime->period_size * (count & (runtime->periods-1)); } /* * page callback (needed for mmap) */ static struct page *snd_cx88_page(struct snd_pcm_substream *substream, unsigned long offset) { void *pageptr = substream->runtime->dma_area + offset; return vmalloc_to_page(pageptr); } /* * operators */ static struct snd_pcm_ops snd_cx88_pcm_ops = { .open = snd_cx88_pcm_open, .close = snd_cx88_close, .ioctl = snd_pcm_lib_ioctl, .hw_params = snd_cx88_hw_params, .hw_free = snd_cx88_hw_free, .prepare = snd_cx88_prepare, .trigger = snd_cx88_card_trigger, .pointer = snd_cx88_pointer, .page = snd_cx88_page, }; /* * create a PCM device */ static int __devinit snd_cx88_pcm(snd_cx88_card_t *chip, int device, const char *name) { int err; struct snd_pcm *pcm; err = snd_pcm_new(chip->card, name, device, 0, 1, &pcm); if (err < 0) return err; pcm->private_data = chip; strcpy(pcm->name, name); snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_cx88_pcm_ops); return 0; } /**************************************************************************** CONTROL INTERFACE ****************************************************************************/ static int snd_cx88_volume_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *info) { info->type = SNDRV_CTL_ELEM_TYPE_INTEGER; info->count = 2; info->value.integer.min = 0; info->value.integer.max = 0x3f; return 0; } static int snd_cx88_volume_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value) { snd_cx88_card_t *chip = snd_kcontrol_chip(kcontrol); struct cx88_core *core=chip->core; int vol = 0x3f - (cx_read(AUD_VOL_CTL) & 0x3f), bal = cx_read(AUD_BAL_CTL); value->value.integer.value[(bal & 0x40) ? 0 : 1] = vol; vol -= (bal & 0x3f); value->value.integer.value[(bal & 0x40) ? 1 : 0] = vol < 0 ? 0 : vol; return 0; } static void snd_cx88_wm8775_volume_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value) { snd_cx88_card_t *chip = snd_kcontrol_chip(kcontrol); struct cx88_core *core = chip->core; struct v4l2_control client_ctl; int left = value->value.integer.value[0]; int right = value->value.integer.value[1]; int v, b; memset(&client_ctl, 0, sizeof(client_ctl)); /* Pass volume & balance onto any WM8775 */ if (left >= right) { v = left << 10; b = left ? (0x8000 * right) / left : 0x8000; } else { v = right << 10; b = right ? 0xffff - (0x8000 * left) / right : 0x8000; } client_ctl.value = v; client_ctl.id = V4L2_CID_AUDIO_VOLUME; call_hw(core, WM8775_GID, core, s_ctrl, &client_ctl); client_ctl.value = b; client_ctl.id = V4L2_CID_AUDIO_BALANCE; call_hw(core, WM8775_GID, core, s_ctrl, &client_ctl); } /* OK - TODO: test it */ static int snd_cx88_volume_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value) { snd_cx88_card_t *chip = snd_kcontrol_chip(kcontrol); struct cx88_core *core=chip->core; int left, right, v, b; int changed = 0; u32 old; if (core->board.audio_chip == V4L2_IDENT_WM8775) snd_cx88_wm8775_volume_put(kcontrol, value); left = value->value.integer.value[0] & 0x3f; right = value->value.integer.value[1] & 0x3f; b = right - left; if (b < 0) { v = 0x3f - left; b = (-b) | 0x40; } else { v = 0x3f - right; } /* Do we really know this will always be called with IRQs on? */ spin_lock_irq(&chip->reg_lock); old = cx_read(AUD_VOL_CTL); if (v != (old & 0x3f)) { cx_swrite(SHADOW_AUD_VOL_CTL, AUD_VOL_CTL, (old & ~0x3f) | v); changed = 1; } if ((cx_read(AUD_BAL_CTL) & 0x7f) != b) { cx_write(AUD_BAL_CTL, b); changed = 1; } spin_unlock_irq(&chip->reg_lock); return changed; } static const DECLARE_TLV_DB_SCALE(snd_cx88_db_scale, -6300, 100, 0); static const struct snd_kcontrol_new snd_cx88_volume = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .access = SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_TLV_READ, .name = "Analog-TV Volume", .info = snd_cx88_volume_info, .get = snd_cx88_volume_get, .put = snd_cx88_volume_put, .tlv.p = snd_cx88_db_scale, }; static int snd_cx88_switch_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value) { snd_cx88_card_t *chip = snd_kcontrol_chip(kcontrol); struct cx88_core *core = chip->core; u32 bit = kcontrol->private_value; value->value.integer.value[0] = !(cx_read(AUD_VOL_CTL) & bit); return 0; } static int snd_cx88_switch_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value) { snd_cx88_card_t *chip = snd_kcontrol_chip(kcontrol); struct cx88_core *core = chip->core; u32 bit = kcontrol->private_value; int ret = 0; u32 vol; spin_lock_irq(&chip->reg_lock); vol = cx_read(AUD_VOL_CTL); if (value->value.integer.value[0] != !(vol & bit)) { vol ^= bit; cx_swrite(SHADOW_AUD_VOL_CTL, AUD_VOL_CTL, vol); /* Pass mute onto any WM8775 */ if ((core->board.audio_chip == V4L2_IDENT_WM8775) && ((1<<6) == bit)) { struct v4l2_control client_ctl; memset(&client_ctl, 0, sizeof(client_ctl)); client_ctl.value = 0 != (vol & bit); client_ctl.id = V4L2_CID_AUDIO_MUTE; call_hw(core, WM8775_GID, core, s_ctrl, &client_ctl); } ret = 1; } spin_unlock_irq(&chip->reg_lock); return ret; } static const struct snd_kcontrol_new snd_cx88_dac_switch = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Audio-Out Switch", .info = snd_ctl_boolean_mono_info, .get = snd_cx88_switch_get, .put = snd_cx88_switch_put, .private_value = (1<<8), }; static const struct snd_kcontrol_new snd_cx88_source_switch = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Analog-TV Switch", .info = snd_ctl_boolean_mono_info, .get = snd_cx88_switch_get, .put = snd_cx88_switch_put, .private_value = (1<<6), }; static int snd_cx88_alc_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value) { snd_cx88_card_t *chip = snd_kcontrol_chip(kcontrol); struct cx88_core *core = chip->core; struct v4l2_control client_ctl; memset(&client_ctl, 0, sizeof(client_ctl)); client_ctl.id = V4L2_CID_AUDIO_LOUDNESS; call_hw(core, WM8775_GID, core, g_ctrl, &client_ctl); value->value.integer.value[0] = client_ctl.value ? 1 : 0; return 0; } static int snd_cx88_alc_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value) { snd_cx88_card_t *chip = snd_kcontrol_chip(kcontrol); struct cx88_core *core = chip->core; struct v4l2_control client_ctl; memset(&client_ctl, 0, sizeof(client_ctl)); client_ctl.value = 0 != value->value.integer.value[0]; client_ctl.id = V4L2_CID_AUDIO_LOUDNESS; call_hw(core, WM8775_GID, core, s_ctrl, &client_ctl); return 0; } static struct snd_kcontrol_new snd_cx88_alc_switch = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Line-In ALC Switch", .info = snd_ctl_boolean_mono_info, .get = snd_cx88_alc_get, .put = snd_cx88_alc_put, }; /**************************************************************************** Basic Flow for Sound Devices ****************************************************************************/ /* * PCI ID Table - 14f1:8801 and 14f1:8811 means function 1: Audio * Only boards with eeprom and byte 1 at eeprom=1 have it */ static const struct pci_device_id const cx88_audio_pci_tbl[] __devinitdata = { {0x14f1,0x8801,PCI_ANY_ID,PCI_ANY_ID,0,0,0}, {0x14f1,0x8811,PCI_ANY_ID,PCI_ANY_ID,0,0,0}, {0, } }; MODULE_DEVICE_TABLE(pci, cx88_audio_pci_tbl); /* * Chip-specific destructor */ static int snd_cx88_free(snd_cx88_card_t *chip) { if (chip->irq >= 0) free_irq(chip->irq, chip); cx88_core_put(chip->core,chip->pci); pci_disable_device(chip->pci); return 0; } /* * Component Destructor */ static void snd_cx88_dev_free(struct snd_card * card) { snd_cx88_card_t *chip = card->private_data; snd_cx88_free(chip); } /* * Alsa Constructor - Component probe */ static int devno; static int __devinit snd_cx88_create(struct snd_card *card, struct pci_dev *pci, snd_cx88_card_t **rchip, struct cx88_core **core_ptr) { snd_cx88_card_t *chip; struct cx88_core *core; int err; unsigned char pci_lat; *rchip = NULL; err = pci_enable_device(pci); if (err < 0) return err; pci_set_master(pci); chip = card->private_data; core = cx88_core_get(pci); if (NULL == core) { err = -EINVAL; return err; } if (!pci_dma_supported(pci,DMA_BIT_MASK(32))) { dprintk(0, "%s/1: Oops: no 32bit PCI DMA ???\n",core->name); err = -EIO; cx88_core_put(core, pci); return err; } /* pci init */ chip->card = card; chip->pci = pci; chip->irq = -1; spin_lock_init(&chip->reg_lock); chip->core = core; /* get irq */ err = request_irq(chip->pci->irq, cx8801_irq, IRQF_SHARED | IRQF_DISABLED, chip->core->name, chip); if (err < 0) { dprintk(0, "%s: can't get IRQ %d\n", chip->core->name, chip->pci->irq); return err; } /* print pci info */ pci_read_config_byte(pci, PCI_LATENCY_TIMER, &pci_lat); dprintk(1,"ALSA %s/%i: found at %s, rev: %d, irq: %d, " "latency: %d, mmio: 0x%llx\n", core->name, devno, pci_name(pci), pci->revision, pci->irq, pci_lat, (unsigned long long)pci_resource_start(pci,0)); chip->irq = pci->irq; synchronize_irq(chip->irq); snd_card_set_dev(card, &pci->dev); *rchip = chip; *core_ptr = core; return 0; } static int __devinit cx88_audio_initdev(struct pci_dev *pci, const struct pci_device_id *pci_id) { struct snd_card *card; snd_cx88_card_t *chip; struct cx88_core *core = NULL; int err; if (devno >= SNDRV_CARDS) return (-ENODEV); if (!enable[devno]) { ++devno; return (-ENOENT); } err = snd_card_create(index[devno], id[devno], THIS_MODULE, sizeof(snd_cx88_card_t), &card); if (err < 0) return err; card->private_free = snd_cx88_dev_free; err = snd_cx88_create(card, pci, &chip, &core); if (err < 0) goto error; err = snd_cx88_pcm(chip, 0, "CX88 Digital"); if (err < 0) goto error; err = snd_ctl_add(card, snd_ctl_new1(&snd_cx88_volume, chip)); if (err < 0) goto error; err = snd_ctl_add(card, snd_ctl_new1(&snd_cx88_dac_switch, chip)); if (err < 0) goto error; err = snd_ctl_add(card, snd_ctl_new1(&snd_cx88_source_switch, chip)); if (err < 0) goto error; /* If there's a wm8775 then add a Line-In ALC switch */ if (core->board.audio_chip == V4L2_IDENT_WM8775) snd_ctl_add(card, snd_ctl_new1(&snd_cx88_alc_switch, chip)); strcpy (card->driver, "CX88x"); sprintf(card->shortname, "Conexant CX%x", pci->device); sprintf(card->longname, "%s at %#llx", card->shortname,(unsigned long long)pci_resource_start(pci, 0)); strcpy (card->mixername, "CX88"); dprintk (0, "%s/%i: ALSA support for cx2388x boards\n", card->driver,devno); err = snd_card_register(card); if (err < 0) goto error; pci_set_drvdata(pci,card); devno++; return 0; error: snd_card_free(card); return err; } /* * ALSA destructor */ static void __devexit cx88_audio_finidev(struct pci_dev *pci) { struct cx88_audio_dev *card = pci_get_drvdata(pci); snd_card_free((void *)card); pci_set_drvdata(pci, NULL); devno--; } /* * PCI driver definition */ static struct pci_driver cx88_audio_pci_driver = { .name = "cx88_audio", .id_table = cx88_audio_pci_tbl, .probe = cx88_audio_initdev, .remove = __devexit_p(cx88_audio_finidev), }; /**************************************************************************** LINUX MODULE INIT ****************************************************************************/ /* * module init */ static int __init cx88_audio_init(void) { printk(KERN_INFO "cx2388x alsa driver version %d.%d.%d loaded\n", (CX88_VERSION_CODE >> 16) & 0xff, (CX88_VERSION_CODE >> 8) & 0xff, CX88_VERSION_CODE & 0xff); #ifdef SNAPSHOT printk(KERN_INFO "cx2388x: snapshot date %04d-%02d-%02d\n", SNAPSHOT/10000, (SNAPSHOT/100)%100, SNAPSHOT%100); #endif return pci_register_driver(&cx88_audio_pci_driver); } /* * module remove */ static void __exit cx88_audio_fini(void) { pci_unregister_driver(&cx88_audio_pci_driver); } module_init(cx88_audio_init); module_exit(cx88_audio_fini); /* ----------------------------------------------------------- */ /* * Local variables: * c-basic-offset: 8 * End: */
gpl-2.0
LimKyungWoo/linux-2.6.39
arch/arm/mach-omap2/voltagedomains44xx_data.c
2521
2640
/* * OMAP3/OMAP4 Voltage Management Routines * * Author: Thara Gopinath <thara@ti.com> * * Copyright (C) 2007 Texas Instruments, Inc. * Rajendra Nayak <rnayak@ti.com> * Lesly A M <x0080970@ti.com> * * Copyright (C) 2008 Nokia Corporation * Kalle Jokiniemi * * Copyright (C) 2010 Texas Instruments, Inc. * Thara Gopinath <thara@ti.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/kernel.h> #include <linux/err.h> #include <linux/init.h> #include <plat/common.h> #include "prm-regbits-44xx.h" #include "prm44xx.h" #include "prcm44xx.h" #include "prminst44xx.h" #include "voltage.h" #include "omap_opp_data.h" #include "vc.h" #include "vp.h" static const struct omap_vfsm_instance_data omap4_vdd_mpu_vfsm_data = { .voltsetup_reg = OMAP4_PRM_VOLTSETUP_MPU_RET_SLEEP_OFFSET, }; static struct omap_vdd_info omap4_vdd_mpu_info = { .vp_data = &omap4_vp_mpu_data, .vc_data = &omap4_vc_mpu_data, .vfsm = &omap4_vdd_mpu_vfsm_data, .voltdm = { .name = "mpu", }, }; static const struct omap_vfsm_instance_data omap4_vdd_iva_vfsm_data = { .voltsetup_reg = OMAP4_PRM_VOLTSETUP_IVA_RET_SLEEP_OFFSET, }; static struct omap_vdd_info omap4_vdd_iva_info = { .vp_data = &omap4_vp_iva_data, .vc_data = &omap4_vc_iva_data, .vfsm = &omap4_vdd_iva_vfsm_data, .voltdm = { .name = "iva", }, }; static const struct omap_vfsm_instance_data omap4_vdd_core_vfsm_data = { .voltsetup_reg = OMAP4_PRM_VOLTSETUP_CORE_RET_SLEEP_OFFSET, }; static struct omap_vdd_info omap4_vdd_core_info = { .vp_data = &omap4_vp_core_data, .vc_data = &omap4_vc_core_data, .vfsm = &omap4_vdd_core_vfsm_data, .voltdm = { .name = "core", }, }; /* OMAP4 VDD structures */ static struct omap_vdd_info *omap4_vdd_info[] = { &omap4_vdd_mpu_info, &omap4_vdd_iva_info, &omap4_vdd_core_info, }; /* OMAP4 specific voltage init functions */ static int __init omap44xx_voltage_early_init(void) { s16 prm_mod = OMAP4430_PRM_DEVICE_INST; s16 prm_irqst_ocp_mod = OMAP4430_PRM_OCP_SOCKET_INST; if (!cpu_is_omap44xx()) return 0; /* * XXX Will depend on the process, validation, and binning * for the currently-running IC */ omap4_vdd_mpu_info.volt_data = omap44xx_vdd_mpu_volt_data; omap4_vdd_iva_info.volt_data = omap44xx_vdd_iva_volt_data; omap4_vdd_core_info.volt_data = omap44xx_vdd_core_volt_data; return omap_voltage_early_init(prm_mod, prm_irqst_ocp_mod, omap4_vdd_info, ARRAY_SIZE(omap4_vdd_info)); }; core_initcall(omap44xx_voltage_early_init);
gpl-2.0
ARMP/ARMP-i9300
drivers/media/video/v4l2-subdev.c
2521
8232
/* * V4L2 sub-device * * Copyright (C) 2010 Nokia Corporation * * Contact: Laurent Pinchart <laurent.pinchart@ideasonboard.com> * Sakari Ailus <sakari.ailus@iki.fi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/ioctl.h> #include <linux/slab.h> #include <linux/types.h> #include <linux/videodev2.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-fh.h> #include <media/v4l2-event.h> static int subdev_fh_init(struct v4l2_subdev_fh *fh, struct v4l2_subdev *sd) { #if defined(CONFIG_VIDEO_V4L2_SUBDEV_API) /* Allocate try format and crop in the same memory block */ fh->try_fmt = kzalloc((sizeof(*fh->try_fmt) + sizeof(*fh->try_crop)) * sd->entity.num_pads, GFP_KERNEL); if (fh->try_fmt == NULL) return -ENOMEM; fh->try_crop = (struct v4l2_rect *) (fh->try_fmt + sd->entity.num_pads); #endif return 0; } static void subdev_fh_free(struct v4l2_subdev_fh *fh) { #if defined(CONFIG_VIDEO_V4L2_SUBDEV_API) kfree(fh->try_fmt); fh->try_fmt = NULL; fh->try_crop = NULL; #endif } static int subdev_open(struct file *file) { struct video_device *vdev = video_devdata(file); struct v4l2_subdev *sd = vdev_to_v4l2_subdev(vdev); struct v4l2_subdev_fh *subdev_fh; #if defined(CONFIG_MEDIA_CONTROLLER) struct media_entity *entity = NULL; #endif int ret; subdev_fh = kzalloc(sizeof(*subdev_fh), GFP_KERNEL); if (subdev_fh == NULL) return -ENOMEM; ret = subdev_fh_init(subdev_fh, sd); if (ret) { kfree(subdev_fh); return ret; } ret = v4l2_fh_init(&subdev_fh->vfh, vdev); if (ret) goto err; if (sd->flags & V4L2_SUBDEV_FL_HAS_EVENTS) { ret = v4l2_event_init(&subdev_fh->vfh); if (ret) goto err; ret = v4l2_event_alloc(&subdev_fh->vfh, sd->nevents); if (ret) goto err; } v4l2_fh_add(&subdev_fh->vfh); file->private_data = &subdev_fh->vfh; #if defined(CONFIG_MEDIA_CONTROLLER) if (sd->v4l2_dev->mdev) { entity = media_entity_get(&sd->entity); if (!entity) { ret = -EBUSY; goto err; } } #endif if (sd->internal_ops && sd->internal_ops->open) { ret = sd->internal_ops->open(sd, subdev_fh); if (ret < 0) goto err; } return 0; err: #if defined(CONFIG_MEDIA_CONTROLLER) if (entity) media_entity_put(entity); #endif v4l2_fh_del(&subdev_fh->vfh); v4l2_fh_exit(&subdev_fh->vfh); subdev_fh_free(subdev_fh); kfree(subdev_fh); return ret; } static int subdev_close(struct file *file) { struct video_device *vdev = video_devdata(file); struct v4l2_subdev *sd = vdev_to_v4l2_subdev(vdev); struct v4l2_fh *vfh = file->private_data; struct v4l2_subdev_fh *subdev_fh = to_v4l2_subdev_fh(vfh); if (sd->internal_ops && sd->internal_ops->close) sd->internal_ops->close(sd, subdev_fh); #if defined(CONFIG_MEDIA_CONTROLLER) if (sd->v4l2_dev->mdev) media_entity_put(&sd->entity); #endif v4l2_fh_del(vfh); v4l2_fh_exit(vfh); subdev_fh_free(subdev_fh); kfree(subdev_fh); file->private_data = NULL; return 0; } static long subdev_do_ioctl(struct file *file, unsigned int cmd, void *arg) { struct video_device *vdev = video_devdata(file); struct v4l2_subdev *sd = vdev_to_v4l2_subdev(vdev); struct v4l2_fh *vfh = file->private_data; #if defined(CONFIG_VIDEO_V4L2_SUBDEV_API) struct v4l2_subdev_fh *subdev_fh = to_v4l2_subdev_fh(vfh); #endif switch (cmd) { case VIDIOC_QUERYCTRL: return v4l2_queryctrl(sd->ctrl_handler, arg); case VIDIOC_QUERYMENU: return v4l2_querymenu(sd->ctrl_handler, arg); case VIDIOC_G_CTRL: return v4l2_g_ctrl(sd->ctrl_handler, arg); case VIDIOC_S_CTRL: return v4l2_s_ctrl(sd->ctrl_handler, arg); case VIDIOC_G_EXT_CTRLS: return v4l2_g_ext_ctrls(sd->ctrl_handler, arg); case VIDIOC_S_EXT_CTRLS: return v4l2_s_ext_ctrls(sd->ctrl_handler, arg); case VIDIOC_TRY_EXT_CTRLS: return v4l2_try_ext_ctrls(sd->ctrl_handler, arg); case VIDIOC_DQEVENT: if (!(sd->flags & V4L2_SUBDEV_FL_HAS_EVENTS)) return -ENOIOCTLCMD; return v4l2_event_dequeue(vfh, arg, file->f_flags & O_NONBLOCK); case VIDIOC_SUBSCRIBE_EVENT: return v4l2_subdev_call(sd, core, subscribe_event, vfh, arg); case VIDIOC_UNSUBSCRIBE_EVENT: return v4l2_subdev_call(sd, core, unsubscribe_event, vfh, arg); #if defined(CONFIG_VIDEO_V4L2_SUBDEV_API) case VIDIOC_SUBDEV_G_FMT: { struct v4l2_subdev_format *format = arg; if (format->which != V4L2_SUBDEV_FORMAT_TRY && format->which != V4L2_SUBDEV_FORMAT_ACTIVE) return -EINVAL; if (format->pad >= sd->entity.num_pads) return -EINVAL; return v4l2_subdev_call(sd, pad, get_fmt, subdev_fh, format); } case VIDIOC_SUBDEV_S_FMT: { struct v4l2_subdev_format *format = arg; if (format->which != V4L2_SUBDEV_FORMAT_TRY && format->which != V4L2_SUBDEV_FORMAT_ACTIVE) return -EINVAL; if (format->pad >= sd->entity.num_pads) return -EINVAL; return v4l2_subdev_call(sd, pad, set_fmt, subdev_fh, format); } case VIDIOC_SUBDEV_G_CROP: { struct v4l2_subdev_crop *crop = arg; if (crop->which != V4L2_SUBDEV_FORMAT_TRY && crop->which != V4L2_SUBDEV_FORMAT_ACTIVE) return -EINVAL; if (crop->pad >= sd->entity.num_pads) return -EINVAL; return v4l2_subdev_call(sd, pad, get_crop, subdev_fh, crop); } case VIDIOC_SUBDEV_S_CROP: { struct v4l2_subdev_crop *crop = arg; if (crop->which != V4L2_SUBDEV_FORMAT_TRY && crop->which != V4L2_SUBDEV_FORMAT_ACTIVE) return -EINVAL; if (crop->pad >= sd->entity.num_pads) return -EINVAL; return v4l2_subdev_call(sd, pad, set_crop, subdev_fh, crop); } case VIDIOC_SUBDEV_ENUM_MBUS_CODE: { struct v4l2_subdev_mbus_code_enum *code = arg; if (code->pad >= sd->entity.num_pads) return -EINVAL; return v4l2_subdev_call(sd, pad, enum_mbus_code, subdev_fh, code); } case VIDIOC_SUBDEV_ENUM_FRAME_SIZE: { struct v4l2_subdev_frame_size_enum *fse = arg; if (fse->pad >= sd->entity.num_pads) return -EINVAL; return v4l2_subdev_call(sd, pad, enum_frame_size, subdev_fh, fse); } case VIDIOC_SUBDEV_G_FRAME_INTERVAL: return v4l2_subdev_call(sd, video, g_frame_interval, arg); case VIDIOC_SUBDEV_S_FRAME_INTERVAL: return v4l2_subdev_call(sd, video, s_frame_interval, arg); case VIDIOC_SUBDEV_ENUM_FRAME_INTERVAL: { struct v4l2_subdev_frame_interval_enum *fie = arg; if (fie->pad >= sd->entity.num_pads) return -EINVAL; return v4l2_subdev_call(sd, pad, enum_frame_interval, subdev_fh, fie); } #endif default: return v4l2_subdev_call(sd, core, ioctl, cmd, arg); } return 0; } static long subdev_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { return video_usercopy(file, cmd, arg, subdev_do_ioctl); } static unsigned int subdev_poll(struct file *file, poll_table *wait) { struct video_device *vdev = video_devdata(file); struct v4l2_subdev *sd = vdev_to_v4l2_subdev(vdev); struct v4l2_fh *fh = file->private_data; if (!(sd->flags & V4L2_SUBDEV_FL_HAS_EVENTS)) return POLLERR; poll_wait(file, &fh->events->wait, wait); if (v4l2_event_pending(fh)) return POLLPRI; return 0; } const struct v4l2_file_operations v4l2_subdev_fops = { .owner = THIS_MODULE, .open = subdev_open, .unlocked_ioctl = subdev_ioctl, .release = subdev_close, .poll = subdev_poll, }; void v4l2_subdev_init(struct v4l2_subdev *sd, const struct v4l2_subdev_ops *ops) { INIT_LIST_HEAD(&sd->list); BUG_ON(!ops); sd->ops = ops; sd->v4l2_dev = NULL; sd->flags = 0; sd->name[0] = '\0'; sd->grp_id = 0; sd->dev_priv = NULL; sd->host_priv = NULL; #if defined(CONFIG_MEDIA_CONTROLLER) sd->entity.name = sd->name; sd->entity.type = MEDIA_ENT_T_V4L2_SUBDEV; #endif } EXPORT_SYMBOL(v4l2_subdev_init);
gpl-2.0
zarboz/aozp-ville
drivers/media/dvb/dvb-usb/ttusb2.c
3033
10630
/* DVB USB compliant linux driver for Technotrend DVB USB boxes and clones * (e.g. Pinnacle 400e DVB-S USB2.0). * * The Pinnacle 400e uses the same protocol as the Technotrend USB1.1 boxes. * * TDA8263 + TDA10086 * * I2C addresses: * 0x08 - LNBP21PD - LNB power supply * 0x0e - TDA10086 - Demodulator * 0x50 - FX2 eeprom * 0x60 - TDA8263 - Tuner * 0x78 ??? * * Copyright (c) 2002 Holger Waechtler <holger@convergence.de> * Copyright (c) 2003 Felix Domke <tmbinc@elitedvb.net> * Copyright (C) 2005-6 Patrick Boettcher <pb@linuxtv.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, version 2. * * see Documentation/dvb/README.dvb-usb for more information */ #define DVB_USB_LOG_PREFIX "ttusb2" #include "dvb-usb.h" #include "ttusb2.h" #include "tda826x.h" #include "tda10086.h" #include "tda1002x.h" #include "tda827x.h" #include "lnbp21.h" /* debug */ static int dvb_usb_ttusb2_debug; #define deb_info(args...) dprintk(dvb_usb_ttusb2_debug,0x01,args) module_param_named(debug,dvb_usb_ttusb2_debug, int, 0644); MODULE_PARM_DESC(debug, "set debugging level (1=info (or-able))." DVB_USB_DEBUG_STATUS); DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr); struct ttusb2_state { u8 id; u16 last_rc_key; }; static int ttusb2_msg(struct dvb_usb_device *d, u8 cmd, u8 *wbuf, int wlen, u8 *rbuf, int rlen) { struct ttusb2_state *st = d->priv; u8 s[wlen+4],r[64] = { 0 }; int ret = 0; memset(s,0,wlen+4); s[0] = 0xaa; s[1] = ++st->id; s[2] = cmd; s[3] = wlen; memcpy(&s[4],wbuf,wlen); ret = dvb_usb_generic_rw(d, s, wlen+4, r, 64, 0); if (ret != 0 || r[0] != 0x55 || r[1] != s[1] || r[2] != cmd || (rlen > 0 && r[3] != rlen)) { warn("there might have been an error during control message transfer. (rlen = %d, was %d)",rlen,r[3]); return -EIO; } if (rlen > 0) memcpy(rbuf, &r[4], rlen); return 0; } static int ttusb2_i2c_xfer(struct i2c_adapter *adap,struct i2c_msg msg[],int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); static u8 obuf[60], ibuf[60]; int i,read; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) 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++) { read = i+1 < num && (msg[i+1].flags & I2C_M_RD); obuf[0] = (msg[i].addr << 1) | read; obuf[1] = msg[i].len; /* read request */ if (read) obuf[2] = msg[i+1].len; else obuf[2] = 0; memcpy(&obuf[3],msg[i].buf,msg[i].len); if (ttusb2_msg(d, CMD_I2C_XFER, obuf, msg[i].len+3, ibuf, obuf[2] + 3) < 0) { err("i2c transfer failed."); break; } if (read) { memcpy(msg[i+1].buf,&ibuf[3],msg[i+1].len); i++; } } mutex_unlock(&d->i2c_mutex); return i; } static u32 ttusb2_i2c_func(struct i2c_adapter *adapter) { return I2C_FUNC_I2C; } static struct i2c_algorithm ttusb2_i2c_algo = { .master_xfer = ttusb2_i2c_xfer, .functionality = ttusb2_i2c_func, }; /* command to poll IR receiver (copied from pctv452e.c) */ #define CMD_GET_IR_CODE 0x1b /* IR */ static int tt3650_rc_query(struct dvb_usb_device *d) { int ret; u8 rx[9]; /* A CMD_GET_IR_CODE reply is 9 bytes long */ struct ttusb2_state *st = d->priv; ret = ttusb2_msg(d, CMD_GET_IR_CODE, NULL, 0, rx, sizeof(rx)); if (ret != 0) return ret; if (rx[8] & 0x01) { /* got a "press" event */ st->last_rc_key = (rx[3] << 8) | rx[2]; deb_info("%s: cmd=0x%02x sys=0x%02x\n", __func__, rx[2], rx[3]); rc_keydown(d->rc_dev, st->last_rc_key, 0); } else if (st->last_rc_key) { rc_keyup(d->rc_dev); st->last_rc_key = 0; } return 0; } /* Callbacks for DVB USB */ static int ttusb2_identify_state (struct usb_device *udev, struct dvb_usb_device_properties *props, struct dvb_usb_device_description **desc, int *cold) { *cold = udev->descriptor.iManufacturer == 0 && udev->descriptor.iProduct == 0; return 0; } static int ttusb2_power_ctrl(struct dvb_usb_device *d, int onoff) { u8 b = onoff; ttusb2_msg(d, CMD_POWER, &b, 0, NULL, 0); return ttusb2_msg(d, CMD_POWER, &b, 1, NULL, 0); } static struct tda10086_config tda10086_config = { .demod_address = 0x0e, .invert = 0, .diseqc_tone = 1, .xtal_freq = TDA10086_XTAL_16M, }; static struct tda10023_config tda10023_config = { .demod_address = 0x0c, .invert = 0, .xtal = 16000000, .pll_m = 11, .pll_p = 3, .pll_n = 1, .deltaf = 0xa511, }; static int ttusb2_frontend_tda10086_attach(struct dvb_usb_adapter *adap) { if (usb_set_interface(adap->dev->udev,0,3) < 0) err("set interface to alts=3 failed"); if ((adap->fe = dvb_attach(tda10086_attach, &tda10086_config, &adap->dev->i2c_adap)) == NULL) { deb_info("TDA10086 attach failed\n"); return -ENODEV; } return 0; } static int ttusb2_frontend_tda10023_attach(struct dvb_usb_adapter *adap) { if (usb_set_interface(adap->dev->udev, 0, 3) < 0) err("set interface to alts=3 failed"); if ((adap->fe = dvb_attach(tda10023_attach, &tda10023_config, &adap->dev->i2c_adap, 0x48)) == NULL) { deb_info("TDA10023 attach failed\n"); return -ENODEV; } return 0; } static int ttusb2_tuner_tda827x_attach(struct dvb_usb_adapter *adap) { if (dvb_attach(tda827x_attach, adap->fe, 0x61, &adap->dev->i2c_adap, NULL) == NULL) { printk(KERN_ERR "%s: No tda827x found!\n", __func__); return -ENODEV; } return 0; } static int ttusb2_tuner_tda826x_attach(struct dvb_usb_adapter *adap) { if (dvb_attach(tda826x_attach, adap->fe, 0x60, &adap->dev->i2c_adap, 0) == NULL) { deb_info("TDA8263 attach failed\n"); return -ENODEV; } if (dvb_attach(lnbp21_attach, adap->fe, &adap->dev->i2c_adap, 0, 0) == NULL) { deb_info("LNBP21 attach failed\n"); return -ENODEV; } return 0; } /* DVB USB Driver stuff */ static struct dvb_usb_device_properties ttusb2_properties; static struct dvb_usb_device_properties ttusb2_properties_s2400; static struct dvb_usb_device_properties ttusb2_properties_ct3650; static int ttusb2_probe(struct usb_interface *intf, const struct usb_device_id *id) { if (0 == dvb_usb_device_init(intf, &ttusb2_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &ttusb2_properties_s2400, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &ttusb2_properties_ct3650, THIS_MODULE, NULL, adapter_nr)) return 0; return -ENODEV; } static struct usb_device_id ttusb2_table [] = { { USB_DEVICE(USB_VID_PINNACLE, USB_PID_PCTV_400E) }, { USB_DEVICE(USB_VID_PINNACLE, USB_PID_PCTV_450E) }, { USB_DEVICE(USB_VID_TECHNOTREND, USB_PID_TECHNOTREND_CONNECT_S2400) }, { USB_DEVICE(USB_VID_TECHNOTREND, USB_PID_TECHNOTREND_CONNECT_CT3650) }, {} /* Terminating entry */ }; MODULE_DEVICE_TABLE (usb, ttusb2_table); static struct dvb_usb_device_properties ttusb2_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = CYPRESS_FX2, .firmware = "dvb-usb-pctv-400e-01.fw", .size_of_priv = sizeof(struct ttusb2_state), .num_adapters = 1, .adapter = { { .streaming_ctrl = NULL, // ttusb2_streaming_ctrl, .frontend_attach = ttusb2_frontend_tda10086_attach, .tuner_attach = ttusb2_tuner_tda826x_attach, /* parameter for the MPEG2-data transfer */ .stream = { .type = USB_ISOC, .count = 5, .endpoint = 0x02, .u = { .isoc = { .framesperurb = 4, .framesize = 940, .interval = 1, } } } } }, .power_ctrl = ttusb2_power_ctrl, .identify_state = ttusb2_identify_state, .i2c_algo = &ttusb2_i2c_algo, .generic_bulk_ctrl_endpoint = 0x01, .num_device_descs = 2, .devices = { { "Pinnacle 400e DVB-S USB2.0", { &ttusb2_table[0], NULL }, { NULL }, }, { "Pinnacle 450e DVB-S USB2.0", { &ttusb2_table[1], NULL }, { NULL }, }, } }; static struct dvb_usb_device_properties ttusb2_properties_s2400 = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = CYPRESS_FX2, .firmware = "dvb-usb-tt-s2400-01.fw", .size_of_priv = sizeof(struct ttusb2_state), .num_adapters = 1, .adapter = { { .streaming_ctrl = NULL, .frontend_attach = ttusb2_frontend_tda10086_attach, .tuner_attach = ttusb2_tuner_tda826x_attach, /* parameter for the MPEG2-data transfer */ .stream = { .type = USB_ISOC, .count = 5, .endpoint = 0x02, .u = { .isoc = { .framesperurb = 4, .framesize = 940, .interval = 1, } } } } }, .power_ctrl = ttusb2_power_ctrl, .identify_state = ttusb2_identify_state, .i2c_algo = &ttusb2_i2c_algo, .generic_bulk_ctrl_endpoint = 0x01, .num_device_descs = 1, .devices = { { "Technotrend TT-connect S-2400", { &ttusb2_table[2], NULL }, { NULL }, }, } }; static struct dvb_usb_device_properties ttusb2_properties_ct3650 = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = CYPRESS_FX2, .size_of_priv = sizeof(struct ttusb2_state), .rc.core = { .rc_interval = 150, /* Less than IR_KEYPRESS_TIMEOUT */ .rc_codes = RC_MAP_TT_1500, .rc_query = tt3650_rc_query, .allowed_protos = RC_TYPE_UNKNOWN, }, .num_adapters = 1, .adapter = { { .streaming_ctrl = NULL, .frontend_attach = ttusb2_frontend_tda10023_attach, .tuner_attach = ttusb2_tuner_tda827x_attach, /* parameter for the MPEG2-data transfer */ .stream = { .type = USB_ISOC, .count = 5, .endpoint = 0x02, .u = { .isoc = { .framesperurb = 4, .framesize = 940, .interval = 1, } } } }, }, .power_ctrl = ttusb2_power_ctrl, .identify_state = ttusb2_identify_state, .i2c_algo = &ttusb2_i2c_algo, .generic_bulk_ctrl_endpoint = 0x01, .num_device_descs = 1, .devices = { { "Technotrend TT-connect CT-3650", .warm_ids = { &ttusb2_table[3], NULL }, }, } }; static struct usb_driver ttusb2_driver = { .name = "dvb_usb_ttusb2", .probe = ttusb2_probe, .disconnect = dvb_usb_device_exit, .id_table = ttusb2_table, }; /* module stuff */ static int __init ttusb2_module_init(void) { int result; if ((result = usb_register(&ttusb2_driver))) { err("usb_register failed. Error number %d",result); return result; } return 0; } static void __exit ttusb2_module_exit(void) { /* deregister this driver from the USB subsystem */ usb_deregister(&ttusb2_driver); } module_init (ttusb2_module_init); module_exit (ttusb2_module_exit); MODULE_AUTHOR("Patrick Boettcher <patrick.boettcher@desy.de>"); MODULE_DESCRIPTION("Driver for Pinnacle PCTV 400e DVB-S USB2.0"); MODULE_VERSION("1.0"); MODULE_LICENSE("GPL");
gpl-2.0
lyapota/enru-3.1.10-g7f360be
fs/reiserfs/prints.c
3289
21202
/* * Copyright 2000 by Hans Reiser, licensing governed by reiserfs/README */ #include <linux/time.h> #include <linux/fs.h> #include <linux/reiserfs_fs.h> #include <linux/string.h> #include <linux/buffer_head.h> #include <stdarg.h> static char error_buf[1024]; static char fmt_buf[1024]; static char off_buf[80]; static char *reiserfs_cpu_offset(struct cpu_key *key) { if (cpu_key_k_type(key) == TYPE_DIRENTRY) sprintf(off_buf, "%Lu(%Lu)", (unsigned long long) GET_HASH_VALUE(cpu_key_k_offset(key)), (unsigned long long) GET_GENERATION_NUMBER(cpu_key_k_offset(key))); else sprintf(off_buf, "0x%Lx", (unsigned long long)cpu_key_k_offset(key)); return off_buf; } static char *le_offset(struct reiserfs_key *key) { int version; version = le_key_version(key); if (le_key_k_type(version, key) == TYPE_DIRENTRY) sprintf(off_buf, "%Lu(%Lu)", (unsigned long long) GET_HASH_VALUE(le_key_k_offset(version, key)), (unsigned long long) GET_GENERATION_NUMBER(le_key_k_offset(version, key))); else sprintf(off_buf, "0x%Lx", (unsigned long long)le_key_k_offset(version, key)); return off_buf; } static char *cpu_type(struct cpu_key *key) { if (cpu_key_k_type(key) == TYPE_STAT_DATA) return "SD"; if (cpu_key_k_type(key) == TYPE_DIRENTRY) return "DIR"; if (cpu_key_k_type(key) == TYPE_DIRECT) return "DIRECT"; if (cpu_key_k_type(key) == TYPE_INDIRECT) return "IND"; return "UNKNOWN"; } static char *le_type(struct reiserfs_key *key) { int version; version = le_key_version(key); if (le_key_k_type(version, key) == TYPE_STAT_DATA) return "SD"; if (le_key_k_type(version, key) == TYPE_DIRENTRY) return "DIR"; if (le_key_k_type(version, key) == TYPE_DIRECT) return "DIRECT"; if (le_key_k_type(version, key) == TYPE_INDIRECT) return "IND"; return "UNKNOWN"; } /* %k */ static void sprintf_le_key(char *buf, struct reiserfs_key *key) { if (key) sprintf(buf, "[%d %d %s %s]", le32_to_cpu(key->k_dir_id), le32_to_cpu(key->k_objectid), le_offset(key), le_type(key)); else sprintf(buf, "[NULL]"); } /* %K */ static void sprintf_cpu_key(char *buf, struct cpu_key *key) { if (key) sprintf(buf, "[%d %d %s %s]", key->on_disk_key.k_dir_id, key->on_disk_key.k_objectid, reiserfs_cpu_offset(key), cpu_type(key)); else sprintf(buf, "[NULL]"); } static void sprintf_de_head(char *buf, struct reiserfs_de_head *deh) { if (deh) sprintf(buf, "[offset=%d dir_id=%d objectid=%d location=%d state=%04x]", deh_offset(deh), deh_dir_id(deh), deh_objectid(deh), deh_location(deh), deh_state(deh)); else sprintf(buf, "[NULL]"); } static void sprintf_item_head(char *buf, struct item_head *ih) { if (ih) { strcpy(buf, (ih_version(ih) == KEY_FORMAT_3_6) ? "*3.6* " : "*3.5*"); sprintf_le_key(buf + strlen(buf), &(ih->ih_key)); sprintf(buf + strlen(buf), ", item_len %d, item_location %d, " "free_space(entry_count) %d", ih_item_len(ih), ih_location(ih), ih_free_space(ih)); } else sprintf(buf, "[NULL]"); } static void sprintf_direntry(char *buf, struct reiserfs_dir_entry *de) { char name[20]; memcpy(name, de->de_name, de->de_namelen > 19 ? 19 : de->de_namelen); name[de->de_namelen > 19 ? 19 : de->de_namelen] = 0; sprintf(buf, "\"%s\"==>[%d %d]", name, de->de_dir_id, de->de_objectid); } static void sprintf_block_head(char *buf, struct buffer_head *bh) { sprintf(buf, "level=%d, nr_items=%d, free_space=%d rdkey ", B_LEVEL(bh), B_NR_ITEMS(bh), B_FREE_SPACE(bh)); } static void sprintf_buffer_head(char *buf, struct buffer_head *bh) { char b[BDEVNAME_SIZE]; sprintf(buf, "dev %s, size %zd, blocknr %llu, count %d, state 0x%lx, page %p, (%s, %s, %s)", bdevname(bh->b_bdev, b), bh->b_size, (unsigned long long)bh->b_blocknr, atomic_read(&(bh->b_count)), bh->b_state, bh->b_page, buffer_uptodate(bh) ? "UPTODATE" : "!UPTODATE", buffer_dirty(bh) ? "DIRTY" : "CLEAN", buffer_locked(bh) ? "LOCKED" : "UNLOCKED"); } static void sprintf_disk_child(char *buf, struct disk_child *dc) { sprintf(buf, "[dc_number=%d, dc_size=%u]", dc_block_number(dc), dc_size(dc)); } static char *is_there_reiserfs_struct(char *fmt, int *what) { char *k = fmt; while ((k = strchr(k, '%')) != NULL) { if (k[1] == 'k' || k[1] == 'K' || k[1] == 'h' || k[1] == 't' || k[1] == 'z' || k[1] == 'b' || k[1] == 'y' || k[1] == 'a') { *what = k[1]; break; } k++; } return k; } /* debugging reiserfs we used to print out a lot of different variables, like keys, item headers, buffer heads etc. Values of most fields matter. So it took a long time just to write appropriative printk. With this reiserfs_warning you can use format specification for complex structures like you used to do with printfs for integers, doubles and pointers. For instance, to print out key structure you have to write just: reiserfs_warning ("bad key %k", key); instead of printk ("bad key %lu %lu %lu %lu", key->k_dir_id, key->k_objectid, key->k_offset, key->k_uniqueness); */ static DEFINE_SPINLOCK(error_lock); static void prepare_error_buf(const char *fmt, va_list args) { char *fmt1 = fmt_buf; char *k; char *p = error_buf; int what; spin_lock(&error_lock); strcpy(fmt1, fmt); while ((k = is_there_reiserfs_struct(fmt1, &what)) != NULL) { *k = 0; p += vsprintf(p, fmt1, args); switch (what) { case 'k': sprintf_le_key(p, va_arg(args, struct reiserfs_key *)); break; case 'K': sprintf_cpu_key(p, va_arg(args, struct cpu_key *)); break; case 'h': sprintf_item_head(p, va_arg(args, struct item_head *)); break; case 't': sprintf_direntry(p, va_arg(args, struct reiserfs_dir_entry *)); break; case 'y': sprintf_disk_child(p, va_arg(args, struct disk_child *)); break; case 'z': sprintf_block_head(p, va_arg(args, struct buffer_head *)); break; case 'b': sprintf_buffer_head(p, va_arg(args, struct buffer_head *)); break; case 'a': sprintf_de_head(p, va_arg(args, struct reiserfs_de_head *)); break; } p += strlen(p); fmt1 = k + 2; } vsprintf(p, fmt1, args); spin_unlock(&error_lock); } /* in addition to usual conversion specifiers this accepts reiserfs specific conversion specifiers: %k to print little endian key, %K to print cpu key, %h to print item_head, %t to print directory entry %z to print block head (arg must be struct buffer_head * %b to print buffer_head */ #define do_reiserfs_warning(fmt)\ {\ va_list args;\ va_start( args, fmt );\ prepare_error_buf( fmt, args );\ va_end( args );\ } void __reiserfs_warning(struct super_block *sb, const char *id, const char *function, const char *fmt, ...) { do_reiserfs_warning(fmt); if (sb) printk(KERN_WARNING "REISERFS warning (device %s): %s%s%s: " "%s\n", sb->s_id, id ? id : "", id ? " " : "", function, error_buf); else printk(KERN_WARNING "REISERFS warning: %s%s%s: %s\n", id ? id : "", id ? " " : "", function, error_buf); } /* No newline.. reiserfs_info calls can be followed by printk's */ void reiserfs_info(struct super_block *sb, const char *fmt, ...) { do_reiserfs_warning(fmt); if (sb) printk(KERN_NOTICE "REISERFS (device %s): %s", sb->s_id, error_buf); else printk(KERN_NOTICE "REISERFS %s:", error_buf); } /* No newline.. reiserfs_printk calls can be followed by printk's */ static void reiserfs_printk(const char *fmt, ...) { do_reiserfs_warning(fmt); printk(error_buf); } void reiserfs_debug(struct super_block *s, int level, const char *fmt, ...) { #ifdef CONFIG_REISERFS_CHECK do_reiserfs_warning(fmt); if (s) printk(KERN_DEBUG "REISERFS debug (device %s): %s\n", s->s_id, error_buf); else printk(KERN_DEBUG "REISERFS debug: %s\n", error_buf); #endif } /* The format: maintainer-errorid: [function-name:] message where errorid is unique to the maintainer and function-name is optional, is recommended, so that anyone can easily find the bug with a simple grep for the short to type string maintainer-errorid. Don't bother with reusing errorids, there are lots of numbers out there. Example: reiserfs_panic( p_sb, "reiser-29: reiserfs_new_blocknrs: " "one of search_start or rn(%d) is equal to MAX_B_NUM," "which means that we are optimizing location based on the bogus location of a temp buffer (%p).", rn, bh ); Regular panic()s sometimes clear the screen before the message can be read, thus the need for the while loop. Numbering scheme for panic used by Vladimir and Anatoly( Hans completely ignores this scheme, and considers it pointless complexity): panics in reiserfs_fs.h have numbers from 1000 to 1999 super.c 2000 to 2999 preserve.c (unused) 3000 to 3999 bitmap.c 4000 to 4999 stree.c 5000 to 5999 prints.c 6000 to 6999 namei.c 7000 to 7999 fix_nodes.c 8000 to 8999 dir.c 9000 to 9999 lbalance.c 10000 to 10999 ibalance.c 11000 to 11999 not ready do_balan.c 12000 to 12999 inode.c 13000 to 13999 file.c 14000 to 14999 objectid.c 15000 - 15999 buffer.c 16000 - 16999 symlink.c 17000 - 17999 . */ void __reiserfs_panic(struct super_block *sb, const char *id, const char *function, const char *fmt, ...) { do_reiserfs_warning(fmt); #ifdef CONFIG_REISERFS_CHECK dump_stack(); #endif if (sb) panic(KERN_WARNING "REISERFS panic (device %s): %s%s%s: %s\n", sb->s_id, id ? id : "", id ? " " : "", function, error_buf); else panic(KERN_WARNING "REISERFS panic: %s%s%s: %s\n", id ? id : "", id ? " " : "", function, error_buf); } void __reiserfs_error(struct super_block *sb, const char *id, const char *function, const char *fmt, ...) { do_reiserfs_warning(fmt); BUG_ON(sb == NULL); if (reiserfs_error_panic(sb)) __reiserfs_panic(sb, id, function, error_buf); if (id && id[0]) printk(KERN_CRIT "REISERFS error (device %s): %s %s: %s\n", sb->s_id, id, function, error_buf); else printk(KERN_CRIT "REISERFS error (device %s): %s: %s\n", sb->s_id, function, error_buf); if (sb->s_flags & MS_RDONLY) return; reiserfs_info(sb, "Remounting filesystem read-only\n"); sb->s_flags |= MS_RDONLY; reiserfs_abort_journal(sb, -EIO); } void reiserfs_abort(struct super_block *sb, int errno, const char *fmt, ...) { do_reiserfs_warning(fmt); if (reiserfs_error_panic(sb)) { panic(KERN_CRIT "REISERFS panic (device %s): %s\n", sb->s_id, error_buf); } if (reiserfs_is_journal_aborted(SB_JOURNAL(sb))) return; printk(KERN_CRIT "REISERFS abort (device %s): %s\n", sb->s_id, error_buf); sb->s_flags |= MS_RDONLY; reiserfs_abort_journal(sb, errno); } /* this prints internal nodes (4 keys/items in line) (dc_number, dc_size)[k_dirid, k_objectid, k_offset, k_uniqueness](dc_number, dc_size)...*/ static int print_internal(struct buffer_head *bh, int first, int last) { struct reiserfs_key *key; struct disk_child *dc; int i; int from, to; if (!B_IS_KEYS_LEVEL(bh)) return 1; check_internal(bh); if (first == -1) { from = 0; to = B_NR_ITEMS(bh); } else { from = first; to = last < B_NR_ITEMS(bh) ? last : B_NR_ITEMS(bh); } reiserfs_printk("INTERNAL NODE (%ld) contains %z\n", bh->b_blocknr, bh); dc = B_N_CHILD(bh, from); reiserfs_printk("PTR %d: %y ", from, dc); for (i = from, key = B_N_PDELIM_KEY(bh, from), dc++; i < to; i++, key++, dc++) { reiserfs_printk("KEY %d: %k PTR %d: %y ", i, key, i + 1, dc); if (i && i % 4 == 0) printk("\n"); } printk("\n"); return 0; } static int print_leaf(struct buffer_head *bh, int print_mode, int first, int last) { struct block_head *blkh; struct item_head *ih; int i, nr; int from, to; if (!B_IS_ITEMS_LEVEL(bh)) return 1; check_leaf(bh); blkh = B_BLK_HEAD(bh); ih = B_N_PITEM_HEAD(bh, 0); nr = blkh_nr_item(blkh); printk ("\n===================================================================\n"); reiserfs_printk("LEAF NODE (%ld) contains %z\n", bh->b_blocknr, bh); if (!(print_mode & PRINT_LEAF_ITEMS)) { reiserfs_printk("FIRST ITEM_KEY: %k, LAST ITEM KEY: %k\n", &(ih->ih_key), &((ih + nr - 1)->ih_key)); return 0; } if (first < 0 || first > nr - 1) from = 0; else from = first; if (last < 0 || last > nr) to = nr; else to = last; ih += from; printk ("-------------------------------------------------------------------------------\n"); printk ("|##| type | key | ilen | free_space | version | loc |\n"); for (i = from; i < to; i++, ih++) { printk ("-------------------------------------------------------------------------------\n"); reiserfs_printk("|%2d| %h |\n", i, ih); if (print_mode & PRINT_LEAF_ITEMS) op_print_item(ih, B_I_PITEM(bh, ih)); } printk ("===================================================================\n"); return 0; } char *reiserfs_hashname(int code) { if (code == YURA_HASH) return "rupasov"; if (code == TEA_HASH) return "tea"; if (code == R5_HASH) return "r5"; return "unknown"; } /* return 1 if this is not super block */ static int print_super_block(struct buffer_head *bh) { struct reiserfs_super_block *rs = (struct reiserfs_super_block *)(bh->b_data); int skipped, data_blocks; char *version; char b[BDEVNAME_SIZE]; if (is_reiserfs_3_5(rs)) { version = "3.5"; } else if (is_reiserfs_3_6(rs)) { version = "3.6"; } else if (is_reiserfs_jr(rs)) { version = ((sb_version(rs) == REISERFS_VERSION_2) ? "3.6" : "3.5"); } else { return 1; } printk("%s\'s super block is in block %llu\n", bdevname(bh->b_bdev, b), (unsigned long long)bh->b_blocknr); printk("Reiserfs version %s\n", version); printk("Block count %u\n", sb_block_count(rs)); printk("Blocksize %d\n", sb_blocksize(rs)); printk("Free blocks %u\n", sb_free_blocks(rs)); // FIXME: this would be confusing if // someone stores reiserfs super block in some data block ;) // skipped = (bh->b_blocknr * bh->b_size) / sb_blocksize(rs); skipped = bh->b_blocknr; data_blocks = sb_block_count(rs) - skipped - 1 - sb_bmap_nr(rs) - (!is_reiserfs_jr(rs) ? sb_jp_journal_size(rs) + 1 : sb_reserved_for_journal(rs)) - sb_free_blocks(rs); printk ("Busy blocks (skipped %d, bitmaps - %d, journal (or reserved) blocks - %d\n" "1 super block, %d data blocks\n", skipped, sb_bmap_nr(rs), (!is_reiserfs_jr(rs) ? (sb_jp_journal_size(rs) + 1) : sb_reserved_for_journal(rs)), data_blocks); printk("Root block %u\n", sb_root_block(rs)); printk("Journal block (first) %d\n", sb_jp_journal_1st_block(rs)); printk("Journal dev %d\n", sb_jp_journal_dev(rs)); printk("Journal orig size %d\n", sb_jp_journal_size(rs)); printk("FS state %d\n", sb_fs_state(rs)); printk("Hash function \"%s\"\n", reiserfs_hashname(sb_hash_function_code(rs))); printk("Tree height %d\n", sb_tree_height(rs)); return 0; } static int print_desc_block(struct buffer_head *bh) { struct reiserfs_journal_desc *desc; if (memcmp(get_journal_desc_magic(bh), JOURNAL_DESC_MAGIC, 8)) return 1; desc = (struct reiserfs_journal_desc *)(bh->b_data); printk("Desc block %llu (j_trans_id %d, j_mount_id %d, j_len %d)", (unsigned long long)bh->b_blocknr, get_desc_trans_id(desc), get_desc_mount_id(desc), get_desc_trans_len(desc)); return 0; } void print_block(struct buffer_head *bh, ...) //int print_mode, int first, int last) { va_list args; int mode, first, last; if (!bh) { printk("print_block: buffer is NULL\n"); return; } va_start(args, bh); mode = va_arg(args, int); first = va_arg(args, int); last = va_arg(args, int); if (print_leaf(bh, mode, first, last)) if (print_internal(bh, first, last)) if (print_super_block(bh)) if (print_desc_block(bh)) printk ("Block %llu contains unformatted data\n", (unsigned long long)bh->b_blocknr); va_end(args); } static char print_tb_buf[2048]; /* this stores initial state of tree balance in the print_tb_buf */ void store_print_tb(struct tree_balance *tb) { int h = 0; int i; struct buffer_head *tbSh, *tbFh; if (!tb) return; sprintf(print_tb_buf, "\n" "BALANCING %d\n" "MODE=%c, ITEM_POS=%d POS_IN_ITEM=%d\n" "=====================================================================\n" "* h * S * L * R * F * FL * FR * CFL * CFR *\n", REISERFS_SB(tb->tb_sb)->s_do_balance, tb->tb_mode, PATH_LAST_POSITION(tb->tb_path), tb->tb_path->pos_in_item); for (h = 0; h < ARRAY_SIZE(tb->insert_size); h++) { if (PATH_H_PATH_OFFSET(tb->tb_path, h) <= tb->tb_path->path_length && PATH_H_PATH_OFFSET(tb->tb_path, h) > ILLEGAL_PATH_ELEMENT_OFFSET) { tbSh = PATH_H_PBUFFER(tb->tb_path, h); tbFh = PATH_H_PPARENT(tb->tb_path, h); } else { tbSh = NULL; tbFh = NULL; } sprintf(print_tb_buf + strlen(print_tb_buf), "* %d * %3lld(%2d) * %3lld(%2d) * %3lld(%2d) * %5lld * %5lld * %5lld * %5lld * %5lld *\n", h, (tbSh) ? (long long)(tbSh->b_blocknr) : (-1LL), (tbSh) ? atomic_read(&(tbSh->b_count)) : -1, (tb->L[h]) ? (long long)(tb->L[h]->b_blocknr) : (-1LL), (tb->L[h]) ? atomic_read(&(tb->L[h]->b_count)) : -1, (tb->R[h]) ? (long long)(tb->R[h]->b_blocknr) : (-1LL), (tb->R[h]) ? atomic_read(&(tb->R[h]->b_count)) : -1, (tbFh) ? (long long)(tbFh->b_blocknr) : (-1LL), (tb->FL[h]) ? (long long)(tb->FL[h]-> b_blocknr) : (-1LL), (tb->FR[h]) ? (long long)(tb->FR[h]-> b_blocknr) : (-1LL), (tb->CFL[h]) ? (long long)(tb->CFL[h]-> b_blocknr) : (-1LL), (tb->CFR[h]) ? (long long)(tb->CFR[h]-> b_blocknr) : (-1LL)); } sprintf(print_tb_buf + strlen(print_tb_buf), "=====================================================================\n" "* h * size * ln * lb * rn * rb * blkn * s0 * s1 * s1b * s2 * s2b * curb * lk * rk *\n" "* 0 * %4d * %2d * %2d * %2d * %2d * %4d * %2d * %2d * %3d * %2d * %3d * %4d * %2d * %2d *\n", tb->insert_size[0], tb->lnum[0], tb->lbytes, tb->rnum[0], tb->rbytes, tb->blknum[0], tb->s0num, tb->s1num, tb->s1bytes, tb->s2num, tb->s2bytes, tb->cur_blknum, tb->lkey[0], tb->rkey[0]); /* this prints balance parameters for non-leaf levels */ h = 0; do { h++; sprintf(print_tb_buf + strlen(print_tb_buf), "* %d * %4d * %2d * * %2d * * %2d *\n", h, tb->insert_size[h], tb->lnum[h], tb->rnum[h], tb->blknum[h]); } while (tb->insert_size[h]); sprintf(print_tb_buf + strlen(print_tb_buf), "=====================================================================\n" "FEB list: "); /* print FEB list (list of buffers in form (bh (b_blocknr, b_count), that will be used for new nodes) */ h = 0; for (i = 0; i < ARRAY_SIZE(tb->FEB); i++) sprintf(print_tb_buf + strlen(print_tb_buf), "%p (%llu %d)%s", tb->FEB[i], tb->FEB[i] ? (unsigned long long)tb->FEB[i]-> b_blocknr : 0ULL, tb->FEB[i] ? atomic_read(&(tb->FEB[i]->b_count)) : 0, (i == ARRAY_SIZE(tb->FEB) - 1) ? "\n" : ", "); sprintf(print_tb_buf + strlen(print_tb_buf), "======================== the end ====================================\n"); } void print_cur_tb(char *mes) { printk("%s\n%s", mes, print_tb_buf); } static void check_leaf_block_head(struct buffer_head *bh) { struct block_head *blkh; int nr; blkh = B_BLK_HEAD(bh); nr = blkh_nr_item(blkh); if (nr > (bh->b_size - BLKH_SIZE) / IH_SIZE) reiserfs_panic(NULL, "vs-6010", "invalid item number %z", bh); if (blkh_free_space(blkh) > bh->b_size - BLKH_SIZE - IH_SIZE * nr) reiserfs_panic(NULL, "vs-6020", "invalid free space %z", bh); } static void check_internal_block_head(struct buffer_head *bh) { struct block_head *blkh; blkh = B_BLK_HEAD(bh); if (!(B_LEVEL(bh) > DISK_LEAF_NODE_LEVEL && B_LEVEL(bh) <= MAX_HEIGHT)) reiserfs_panic(NULL, "vs-6025", "invalid level %z", bh); if (B_NR_ITEMS(bh) > (bh->b_size - BLKH_SIZE) / IH_SIZE) reiserfs_panic(NULL, "vs-6030", "invalid item number %z", bh); if (B_FREE_SPACE(bh) != bh->b_size - BLKH_SIZE - KEY_SIZE * B_NR_ITEMS(bh) - DC_SIZE * (B_NR_ITEMS(bh) + 1)) reiserfs_panic(NULL, "vs-6040", "invalid free space %z", bh); } void check_leaf(struct buffer_head *bh) { int i; struct item_head *ih; if (!bh) return; check_leaf_block_head(bh); for (i = 0, ih = B_N_PITEM_HEAD(bh, 0); i < B_NR_ITEMS(bh); i++, ih++) op_check_item(ih, B_I_PITEM(bh, ih)); } void check_internal(struct buffer_head *bh) { if (!bh) return; check_internal_block_head(bh); } void print_statistics(struct super_block *s) { /* printk ("reiserfs_put_super: session statistics: balances %d, fix_nodes %d, \ bmap with search %d, without %d, dir2ind %d, ind2dir %d\n", REISERFS_SB(s)->s_do_balance, REISERFS_SB(s)->s_fix_nodes, REISERFS_SB(s)->s_bmaps, REISERFS_SB(s)->s_bmaps_without_search, REISERFS_SB(s)->s_direct2indirect, REISERFS_SB(s)->s_indirect2direct); */ }
gpl-2.0
sultanxda/sultan-kernel-celox
net/bluetooth/bnep/netdev.c
3289
6150
/* BNEP implementation for Linux Bluetooth stack (BlueZ). Copyright (C) 2001-2002 Inventel Systemes Written 2001-2002 by Clément Moreau <clement.moreau@inventel.fr> David Libault <david.libault@inventel.fr> Copyright (C) 2002 Maxim Krasnyansky <maxk@qualcomm.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ #include <linux/module.h> #include <linux/slab.h> #include <linux/socket.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/wait.h> #include <asm/unaligned.h> #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/hci_core.h> #include <net/bluetooth/l2cap.h> #include "bnep.h" #define BNEP_TX_QUEUE_LEN 20 static int bnep_net_open(struct net_device *dev) { netif_start_queue(dev); return 0; } static int bnep_net_close(struct net_device *dev) { netif_stop_queue(dev); return 0; } static void bnep_net_set_mc_list(struct net_device *dev) { #ifdef CONFIG_BT_BNEP_MC_FILTER struct bnep_session *s = netdev_priv(dev); struct sock *sk = s->sock->sk; struct bnep_set_filter_req *r; struct sk_buff *skb; int size; BT_DBG("%s mc_count %d", dev->name, netdev_mc_count(dev)); size = sizeof(*r) + (BNEP_MAX_MULTICAST_FILTERS + 1) * ETH_ALEN * 2; skb = alloc_skb(size, GFP_ATOMIC); if (!skb) { BT_ERR("%s Multicast list allocation failed", dev->name); return; } r = (void *) skb->data; __skb_put(skb, sizeof(*r)); r->type = BNEP_CONTROL; r->ctrl = BNEP_FILTER_MULTI_ADDR_SET; if (dev->flags & (IFF_PROMISC | IFF_ALLMULTI)) { u8 start[ETH_ALEN] = { 0x01 }; /* Request all addresses */ memcpy(__skb_put(skb, ETH_ALEN), start, ETH_ALEN); memcpy(__skb_put(skb, ETH_ALEN), dev->broadcast, ETH_ALEN); r->len = htons(ETH_ALEN * 2); } else { struct netdev_hw_addr *ha; int i, len = skb->len; if (dev->flags & IFF_BROADCAST) { memcpy(__skb_put(skb, ETH_ALEN), dev->broadcast, ETH_ALEN); memcpy(__skb_put(skb, ETH_ALEN), dev->broadcast, ETH_ALEN); } /* FIXME: We should group addresses here. */ i = 0; netdev_for_each_mc_addr(ha, dev) { if (i == BNEP_MAX_MULTICAST_FILTERS) break; memcpy(__skb_put(skb, ETH_ALEN), ha->addr, ETH_ALEN); memcpy(__skb_put(skb, ETH_ALEN), ha->addr, ETH_ALEN); i++; } r->len = htons(skb->len - len); } skb_queue_tail(&sk->sk_write_queue, skb); wake_up_interruptible(sk_sleep(sk)); #endif } static int bnep_net_set_mac_addr(struct net_device *dev, void *arg) { BT_DBG("%s", dev->name); return 0; } static void bnep_net_timeout(struct net_device *dev) { BT_DBG("net_timeout"); netif_wake_queue(dev); } #ifdef CONFIG_BT_BNEP_MC_FILTER static inline int bnep_net_mc_filter(struct sk_buff *skb, struct bnep_session *s) { struct ethhdr *eh = (void *) skb->data; if ((eh->h_dest[0] & 1) && !test_bit(bnep_mc_hash(eh->h_dest), (ulong *) &s->mc_filter)) return 1; return 0; } #endif #ifdef CONFIG_BT_BNEP_PROTO_FILTER /* Determine ether protocol. Based on eth_type_trans. */ static inline u16 bnep_net_eth_proto(struct sk_buff *skb) { struct ethhdr *eh = (void *) skb->data; u16 proto = ntohs(eh->h_proto); if (proto >= 1536) return proto; if (get_unaligned((__be16 *) skb->data) == htons(0xFFFF)) return ETH_P_802_3; return ETH_P_802_2; } static inline int bnep_net_proto_filter(struct sk_buff *skb, struct bnep_session *s) { u16 proto = bnep_net_eth_proto(skb); struct bnep_proto_filter *f = s->proto_filter; int i; for (i = 0; i < BNEP_MAX_PROTO_FILTERS && f[i].end; i++) { if (proto >= f[i].start && proto <= f[i].end) return 0; } BT_DBG("BNEP: filtered skb %p, proto 0x%.4x", skb, proto); return 1; } #endif static netdev_tx_t bnep_net_xmit(struct sk_buff *skb, struct net_device *dev) { struct bnep_session *s = netdev_priv(dev); struct sock *sk = s->sock->sk; BT_DBG("skb %p, dev %p", skb, dev); #ifdef CONFIG_BT_BNEP_MC_FILTER if (bnep_net_mc_filter(skb, s)) { kfree_skb(skb); return NETDEV_TX_OK; } #endif #ifdef CONFIG_BT_BNEP_PROTO_FILTER if (bnep_net_proto_filter(skb, s)) { kfree_skb(skb); return NETDEV_TX_OK; } #endif /* * We cannot send L2CAP packets from here as we are potentially in a bh. * So we have to queue them and wake up session thread which is sleeping * on the sk_sleep(sk). */ dev->trans_start = jiffies; skb_queue_tail(&sk->sk_write_queue, skb); wake_up_interruptible(sk_sleep(sk)); if (skb_queue_len(&sk->sk_write_queue) >= BNEP_TX_QUEUE_LEN) { BT_DBG("tx queue is full"); /* Stop queuing. * Session thread will do netif_wake_queue() */ netif_stop_queue(dev); } return NETDEV_TX_OK; } static const struct net_device_ops bnep_netdev_ops = { .ndo_open = bnep_net_open, .ndo_stop = bnep_net_close, .ndo_start_xmit = bnep_net_xmit, .ndo_validate_addr = eth_validate_addr, .ndo_set_multicast_list = bnep_net_set_mc_list, .ndo_set_mac_address = bnep_net_set_mac_addr, .ndo_tx_timeout = bnep_net_timeout, .ndo_change_mtu = eth_change_mtu, }; void bnep_net_setup(struct net_device *dev) { memset(dev->broadcast, 0xff, ETH_ALEN); dev->addr_len = ETH_ALEN; ether_setup(dev); dev->priv_flags &= ~IFF_TX_SKB_SHARING; dev->netdev_ops = &bnep_netdev_ops; dev->watchdog_timeo = HZ * 2; }
gpl-2.0
ac100-ru/linux
arch/arm/mach-omap1/board-generic.c
3545
2166
/* * linux/arch/arm/mach-omap1/board-generic.c * * Modified from board-innovator1510.c * * Code for generic OMAP board. Should work on many OMAP systems where * the device drivers take care of all the necessary hardware initialization. * Do not put any board specific code to this file; create a new machine * type if you need custom low-level initializations. * * 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/gpio.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <mach/hardware.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/mach/map.h> #include <mach/mux.h> #include <mach/usb.h> #include "common.h" /* assume no Mini-AB port */ #ifdef CONFIG_ARCH_OMAP15XX static struct omap_usb_config generic1510_usb_config __initdata = { .register_host = 1, .register_dev = 1, .hmc_mode = 16, .pins[0] = 3, }; #endif #if defined(CONFIG_ARCH_OMAP16XX) static struct omap_usb_config generic1610_usb_config __initdata = { #ifdef CONFIG_USB_OTG .otg = 1, #endif .register_host = 1, .register_dev = 1, .hmc_mode = 16, .pins[0] = 6, }; #endif static void __init omap_generic_init(void) { #ifdef CONFIG_ARCH_OMAP15XX if (cpu_is_omap15xx()) { /* mux pins for uarts */ omap_cfg_reg(UART1_TX); omap_cfg_reg(UART1_RTS); omap_cfg_reg(UART2_TX); omap_cfg_reg(UART2_RTS); omap_cfg_reg(UART3_TX); omap_cfg_reg(UART3_RX); omap1_usb_init(&generic1510_usb_config); } #endif #if defined(CONFIG_ARCH_OMAP16XX) if (!cpu_is_omap1510()) { omap1_usb_init(&generic1610_usb_config); } #endif omap_serial_init(); omap_register_i2c_bus(1, 100, NULL, 0); } MACHINE_START(OMAP_GENERIC, "Generic OMAP1510/1610/1710") /* Maintainer: Tony Lindgren <tony@atomide.com> */ .atag_offset = 0x100, .map_io = omap16xx_map_io, .init_early = omap1_init_early, .init_irq = omap1_init_irq, .init_machine = omap_generic_init, .init_late = omap1_init_late, .init_time = omap1_timer_init, .restart = omap1_restart, MACHINE_END
gpl-2.0
AOKPSaber/kernel_samsung_p4
drivers/media/dvb/dvb-usb/umt-010.c
4825
4644
/* DVB USB framework compliant Linux driver for the HanfTek UMT-010 USB2.0 * DVB-T receiver. * * Copyright (C) 2004-5 Patrick Boettcher (patrick.boettcher@desy.de) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, version 2. * * see Documentation/dvb/README.dvb-usb for more information */ #include "dibusb.h" #include "mt352.h" DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr); static int umt_mt352_demod_init(struct dvb_frontend *fe) { static u8 mt352_clock_config[] = { 0x89, 0xb8, 0x2d }; static u8 mt352_reset[] = { 0x50, 0x80 }; static u8 mt352_mclk_ratio[] = { 0x8b, 0x00 }; static u8 mt352_adc_ctl_1_cfg[] = { 0x8E, 0x40 }; static u8 mt352_agc_cfg[] = { 0x67, 0x10, 0xa0 }; static u8 mt352_sec_agc_cfg1[] = { 0x6a, 0xff }; static u8 mt352_sec_agc_cfg2[] = { 0x6d, 0xff }; static u8 mt352_sec_agc_cfg3[] = { 0x70, 0x40 }; static u8 mt352_sec_agc_cfg4[] = { 0x7b, 0x03 }; static u8 mt352_sec_agc_cfg5[] = { 0x7d, 0x0f }; static u8 mt352_acq_ctl[] = { 0x53, 0x50 }; static u8 mt352_input_freq_1[] = { 0x56, 0x31, 0x06 }; mt352_write(fe, mt352_clock_config, sizeof(mt352_clock_config)); udelay(2000); mt352_write(fe, mt352_reset, sizeof(mt352_reset)); mt352_write(fe, mt352_mclk_ratio, sizeof(mt352_mclk_ratio)); mt352_write(fe, mt352_adc_ctl_1_cfg, sizeof(mt352_adc_ctl_1_cfg)); mt352_write(fe, mt352_agc_cfg, sizeof(mt352_agc_cfg)); mt352_write(fe, mt352_sec_agc_cfg1, sizeof(mt352_sec_agc_cfg1)); mt352_write(fe, mt352_sec_agc_cfg2, sizeof(mt352_sec_agc_cfg2)); mt352_write(fe, mt352_sec_agc_cfg3, sizeof(mt352_sec_agc_cfg3)); mt352_write(fe, mt352_sec_agc_cfg4, sizeof(mt352_sec_agc_cfg4)); mt352_write(fe, mt352_sec_agc_cfg5, sizeof(mt352_sec_agc_cfg5)); mt352_write(fe, mt352_acq_ctl, sizeof(mt352_acq_ctl)); mt352_write(fe, mt352_input_freq_1, sizeof(mt352_input_freq_1)); return 0; } static int umt_mt352_frontend_attach(struct dvb_usb_adapter *adap) { struct mt352_config umt_config; memset(&umt_config,0,sizeof(struct mt352_config)); umt_config.demod_init = umt_mt352_demod_init; umt_config.demod_address = 0xf; adap->fe = dvb_attach(mt352_attach, &umt_config, &adap->dev->i2c_adap); return 0; } static int umt_tuner_attach (struct dvb_usb_adapter *adap) { dvb_attach(dvb_pll_attach, adap->fe, 0x61, NULL, DVB_PLL_TUA6034); return 0; } /* USB Driver stuff */ static struct dvb_usb_device_properties umt_properties; static int umt_probe(struct usb_interface *intf, const struct usb_device_id *id) { if (0 == dvb_usb_device_init(intf, &umt_properties, THIS_MODULE, NULL, adapter_nr)) return 0; return -EINVAL; } /* do not change the order of the ID table */ static struct usb_device_id umt_table [] = { /* 00 */ { USB_DEVICE(USB_VID_HANFTEK, USB_PID_HANFTEK_UMT_010_COLD) }, /* 01 */ { USB_DEVICE(USB_VID_HANFTEK, USB_PID_HANFTEK_UMT_010_WARM) }, { } /* Terminating entry */ }; MODULE_DEVICE_TABLE (usb, umt_table); static struct dvb_usb_device_properties umt_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = CYPRESS_FX2, .firmware = "dvb-usb-umt-010-02.fw", .num_adapters = 1, .adapter = { { .streaming_ctrl = dibusb2_0_streaming_ctrl, .frontend_attach = umt_mt352_frontend_attach, .tuner_attach = umt_tuner_attach, /* parameter for the MPEG2-data transfer */ .stream = { .type = USB_BULK, .count = MAX_NO_URBS_FOR_DATA_STREAM, .endpoint = 0x06, .u = { .bulk = { .buffersize = 512, } } }, .size_of_priv = sizeof(struct dibusb_state), } }, .power_ctrl = dibusb_power_ctrl, .i2c_algo = &dibusb_i2c_algo, .generic_bulk_ctrl_endpoint = 0x01, .num_device_descs = 1, .devices = { { "Hanftek UMT-010 DVB-T USB2.0", { &umt_table[0], NULL }, { &umt_table[1], NULL }, }, } }; static struct usb_driver umt_driver = { .name = "dvb_usb_umt_010", .probe = umt_probe, .disconnect = dvb_usb_device_exit, .id_table = umt_table, }; /* module stuff */ static int __init umt_module_init(void) { int result; if ((result = usb_register(&umt_driver))) { err("usb_register failed. Error number %d",result); return result; } return 0; } static void __exit umt_module_exit(void) { /* deregister this driver from the USB subsystem */ usb_deregister(&umt_driver); } module_init (umt_module_init); module_exit (umt_module_exit); MODULE_AUTHOR("Patrick Boettcher <patrick.boettcher@desy.de>"); MODULE_DESCRIPTION("Driver for HanfTek UMT 010 USB2.0 DVB-T device"); MODULE_VERSION("1.0"); MODULE_LICENSE("GPL");
gpl-2.0
CyanogenMod/android_kernel_motorola_msm8960dt-common
arch/x86/xen/irq.c
4825
3404
#include <linux/hardirq.h> #include <asm/x86_init.h> #include <xen/interface/xen.h> #include <xen/interface/sched.h> #include <xen/interface/vcpu.h> #include <asm/xen/hypercall.h> #include <asm/xen/hypervisor.h> #include "xen-ops.h" /* * Force a proper event-channel callback from Xen after clearing the * callback mask. We do this in a very simple manner, by making a call * down into Xen. The pending flag will be checked by Xen on return. */ void xen_force_evtchn_callback(void) { (void)HYPERVISOR_xen_version(0, NULL); } static unsigned long xen_save_fl(void) { struct vcpu_info *vcpu; unsigned long flags; vcpu = this_cpu_read(xen_vcpu); /* flag has opposite sense of mask */ flags = !vcpu->evtchn_upcall_mask; /* convert to IF type flag -0 -> 0x00000000 -1 -> 0xffffffff */ return (-flags) & X86_EFLAGS_IF; } PV_CALLEE_SAVE_REGS_THUNK(xen_save_fl); static void xen_restore_fl(unsigned long flags) { struct vcpu_info *vcpu; /* convert from IF type flag */ flags = !(flags & X86_EFLAGS_IF); /* There's a one instruction preempt window here. We need to make sure we're don't switch CPUs between getting the vcpu pointer and updating the mask. */ preempt_disable(); vcpu = this_cpu_read(xen_vcpu); vcpu->evtchn_upcall_mask = flags; preempt_enable_no_resched(); /* Doesn't matter if we get preempted here, because any pending event will get dealt with anyway. */ if (flags == 0) { preempt_check_resched(); barrier(); /* unmask then check (avoid races) */ if (unlikely(vcpu->evtchn_upcall_pending)) xen_force_evtchn_callback(); } } PV_CALLEE_SAVE_REGS_THUNK(xen_restore_fl); static void xen_irq_disable(void) { /* There's a one instruction preempt window here. We need to make sure we're don't switch CPUs between getting the vcpu pointer and updating the mask. */ preempt_disable(); this_cpu_read(xen_vcpu)->evtchn_upcall_mask = 1; preempt_enable_no_resched(); } PV_CALLEE_SAVE_REGS_THUNK(xen_irq_disable); static void xen_irq_enable(void) { struct vcpu_info *vcpu; /* We don't need to worry about being preempted here, since either a) interrupts are disabled, so no preemption, or b) the caller is confused and is trying to re-enable interrupts on an indeterminate processor. */ vcpu = this_cpu_read(xen_vcpu); vcpu->evtchn_upcall_mask = 0; /* Doesn't matter if we get preempted here, because any pending event will get dealt with anyway. */ barrier(); /* unmask then check (avoid races) */ if (unlikely(vcpu->evtchn_upcall_pending)) xen_force_evtchn_callback(); } PV_CALLEE_SAVE_REGS_THUNK(xen_irq_enable); static void xen_safe_halt(void) { /* Blocking includes an implicit local_irq_enable(). */ if (HYPERVISOR_sched_op(SCHEDOP_block, NULL) != 0) BUG(); } static void xen_halt(void) { if (irqs_disabled()) HYPERVISOR_vcpu_op(VCPUOP_down, smp_processor_id(), NULL); else xen_safe_halt(); } static const struct pv_irq_ops xen_irq_ops __initconst = { .save_fl = PV_CALLEE_SAVE(xen_save_fl), .restore_fl = PV_CALLEE_SAVE(xen_restore_fl), .irq_disable = PV_CALLEE_SAVE(xen_irq_disable), .irq_enable = PV_CALLEE_SAVE(xen_irq_enable), .safe_halt = xen_safe_halt, .halt = xen_halt, #ifdef CONFIG_X86_64 .adjust_exception_frame = xen_adjust_exception_frame, #endif }; void __init xen_init_irq_ops(void) { pv_irq_ops = xen_irq_ops; x86_init.irqs.intr_init = xen_init_IRQ; }
gpl-2.0
ztemt/Z7Mini_NX507J_H128_kernel
drivers/watchdog/at32ap700x_wdt.c
5081
10293
/* * Watchdog driver for Atmel AT32AP700X devices * * Copyright (C) 2005-2006 Atmel Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * * Errata: WDT Clear is blocked after WDT Reset * * A watchdog timer event will, after reset, block writes to the WDT_CLEAR * register, preventing the program to clear the next Watchdog Timer Reset. * * If you still want to use the WDT after a WDT reset a small code can be * insterted at the startup checking the AVR32_PM.rcause register for WDT reset * and use a GPIO pin to reset the system. This method requires that one of the * GPIO pins are available and connected externally to the RESET_N pin. After * the GPIO pin has pulled down the reset line the GPIO will be reset and leave * the pin tristated with pullup. */ #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/miscdevice.h> #include <linux/fs.h> #include <linux/platform_device.h> #include <linux/watchdog.h> #include <linux/uaccess.h> #include <linux/io.h> #include <linux/spinlock.h> #include <linux/slab.h> #define TIMEOUT_MIN 1 #define TIMEOUT_MAX 2 #define TIMEOUT_DEFAULT TIMEOUT_MAX /* module parameters */ static int timeout = TIMEOUT_DEFAULT; module_param(timeout, int, 0); MODULE_PARM_DESC(timeout, "Timeout value. Limited to be 1 or 2 seconds. (default=" __MODULE_STRING(TIMEOUT_DEFAULT) ")"); static bool nowayout = WATCHDOG_NOWAYOUT; module_param(nowayout, bool, 0); MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default=" __MODULE_STRING(WATCHDOG_NOWAYOUT) ")"); /* Watchdog registers and write/read macro */ #define WDT_CTRL 0x00 #define WDT_CTRL_EN 0 #define WDT_CTRL_PSEL 8 #define WDT_CTRL_KEY 24 #define WDT_CLR 0x04 #define WDT_RCAUSE 0x10 #define WDT_RCAUSE_POR 0 #define WDT_RCAUSE_EXT 2 #define WDT_RCAUSE_WDT 3 #define WDT_RCAUSE_JTAG 4 #define WDT_RCAUSE_SERP 5 #define WDT_BIT(name) (1 << WDT_##name) #define WDT_BF(name, value) ((value) << WDT_##name) #define wdt_readl(dev, reg) \ __raw_readl((dev)->regs + WDT_##reg) #define wdt_writel(dev, reg, value) \ __raw_writel((value), (dev)->regs + WDT_##reg) struct wdt_at32ap700x { void __iomem *regs; spinlock_t io_lock; int timeout; int boot_status; unsigned long users; struct miscdevice miscdev; }; static struct wdt_at32ap700x *wdt; static char expect_release; /* * Disable the watchdog. */ static inline void at32_wdt_stop(void) { unsigned long psel; spin_lock(&wdt->io_lock); psel = wdt_readl(wdt, CTRL) & WDT_BF(CTRL_PSEL, 0x0f); wdt_writel(wdt, CTRL, psel | WDT_BF(CTRL_KEY, 0x55)); wdt_writel(wdt, CTRL, psel | WDT_BF(CTRL_KEY, 0xaa)); spin_unlock(&wdt->io_lock); } /* * Enable and reset the watchdog. */ static inline void at32_wdt_start(void) { /* 0xf is 2^16 divider = 2 sec, 0xe is 2^15 divider = 1 sec */ unsigned long psel = (wdt->timeout > 1) ? 0xf : 0xe; spin_lock(&wdt->io_lock); wdt_writel(wdt, CTRL, WDT_BIT(CTRL_EN) | WDT_BF(CTRL_PSEL, psel) | WDT_BF(CTRL_KEY, 0x55)); wdt_writel(wdt, CTRL, WDT_BIT(CTRL_EN) | WDT_BF(CTRL_PSEL, psel) | WDT_BF(CTRL_KEY, 0xaa)); spin_unlock(&wdt->io_lock); } /* * Pat the watchdog timer. */ static inline void at32_wdt_pat(void) { spin_lock(&wdt->io_lock); wdt_writel(wdt, CLR, 0x42); spin_unlock(&wdt->io_lock); } /* * Watchdog device is opened, and watchdog starts running. */ static int at32_wdt_open(struct inode *inode, struct file *file) { if (test_and_set_bit(1, &wdt->users)) return -EBUSY; at32_wdt_start(); return nonseekable_open(inode, file); } /* * Close the watchdog device. */ static int at32_wdt_close(struct inode *inode, struct file *file) { if (expect_release == 42) { at32_wdt_stop(); } else { dev_dbg(wdt->miscdev.parent, "unexpected close, not stopping watchdog!\n"); at32_wdt_pat(); } clear_bit(1, &wdt->users); expect_release = 0; return 0; } /* * Change the watchdog time interval. */ static int at32_wdt_settimeout(int time) { /* * All counting occurs at 1 / SLOW_CLOCK (32 kHz) and max prescaler is * 2 ^ 16 allowing up to 2 seconds timeout. */ if ((time < TIMEOUT_MIN) || (time > TIMEOUT_MAX)) return -EINVAL; /* * Set new watchdog time. It will be used when at32_wdt_start() is * called. */ wdt->timeout = time; return 0; } /* * Get the watchdog status. */ static int at32_wdt_get_status(void) { int rcause; int status = 0; rcause = wdt_readl(wdt, RCAUSE); switch (rcause) { case WDT_BIT(RCAUSE_EXT): status = WDIOF_EXTERN1; break; case WDT_BIT(RCAUSE_WDT): status = WDIOF_CARDRESET; break; case WDT_BIT(RCAUSE_POR): /* fall through */ case WDT_BIT(RCAUSE_JTAG): /* fall through */ case WDT_BIT(RCAUSE_SERP): /* fall through */ default: break; } return status; } static const struct watchdog_info at32_wdt_info = { .identity = "at32ap700x watchdog", .options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE, }; /* * Handle commands from user-space. */ static long at32_wdt_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { int ret = -ENOTTY; int time; void __user *argp = (void __user *)arg; int __user *p = argp; switch (cmd) { case WDIOC_GETSUPPORT: ret = copy_to_user(argp, &at32_wdt_info, sizeof(at32_wdt_info)) ? -EFAULT : 0; break; case WDIOC_GETSTATUS: ret = put_user(0, p); break; case WDIOC_GETBOOTSTATUS: ret = put_user(wdt->boot_status, p); break; case WDIOC_SETOPTIONS: ret = get_user(time, p); if (ret) break; if (time & WDIOS_DISABLECARD) at32_wdt_stop(); if (time & WDIOS_ENABLECARD) at32_wdt_start(); ret = 0; break; case WDIOC_KEEPALIVE: at32_wdt_pat(); ret = 0; break; case WDIOC_SETTIMEOUT: ret = get_user(time, p); if (ret) break; ret = at32_wdt_settimeout(time); if (ret) break; /* Enable new time value */ at32_wdt_start(); /* fall through */ case WDIOC_GETTIMEOUT: ret = put_user(wdt->timeout, p); break; } return ret; } static ssize_t at32_wdt_write(struct file *file, const char __user *data, size_t len, loff_t *ppos) { /* See if we got the magic character 'V' and reload the timer */ if (len) { if (!nowayout) { size_t i; /* * note: just in case someone wrote the magic * character five months ago... */ expect_release = 0; /* * scan to see whether or not we got the magic * character */ for (i = 0; i != len; i++) { char c; if (get_user(c, data + i)) return -EFAULT; if (c == 'V') expect_release = 42; } } /* someone wrote to us, we should pat the watchdog */ at32_wdt_pat(); } return len; } static const struct file_operations at32_wdt_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .unlocked_ioctl = at32_wdt_ioctl, .open = at32_wdt_open, .release = at32_wdt_close, .write = at32_wdt_write, }; static int __init at32_wdt_probe(struct platform_device *pdev) { struct resource *regs; int ret; if (wdt) { dev_dbg(&pdev->dev, "only 1 wdt instance supported.\n"); return -EBUSY; } regs = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!regs) { dev_dbg(&pdev->dev, "missing mmio resource\n"); return -ENXIO; } wdt = kzalloc(sizeof(struct wdt_at32ap700x), GFP_KERNEL); if (!wdt) { dev_dbg(&pdev->dev, "no memory for wdt structure\n"); return -ENOMEM; } wdt->regs = ioremap(regs->start, resource_size(regs)); if (!wdt->regs) { ret = -ENOMEM; dev_dbg(&pdev->dev, "could not map I/O memory\n"); goto err_free; } spin_lock_init(&wdt->io_lock); wdt->boot_status = at32_wdt_get_status(); /* Work-around for watchdog silicon errata. */ if (wdt->boot_status & WDIOF_CARDRESET) { dev_info(&pdev->dev, "CPU must be reset with external " "reset or POR due to silicon errata.\n"); ret = -EIO; goto err_iounmap; } else { wdt->users = 0; } wdt->miscdev.minor = WATCHDOG_MINOR; wdt->miscdev.name = "watchdog"; wdt->miscdev.fops = &at32_wdt_fops; wdt->miscdev.parent = &pdev->dev; platform_set_drvdata(pdev, wdt); if (at32_wdt_settimeout(timeout)) { at32_wdt_settimeout(TIMEOUT_DEFAULT); dev_dbg(&pdev->dev, "default timeout invalid, set to %d sec.\n", TIMEOUT_DEFAULT); } ret = misc_register(&wdt->miscdev); if (ret) { dev_dbg(&pdev->dev, "failed to register wdt miscdev\n"); goto err_register; } dev_info(&pdev->dev, "AT32AP700X WDT at 0x%p, timeout %d sec (nowayout=%d)\n", wdt->regs, wdt->timeout, nowayout); return 0; err_register: platform_set_drvdata(pdev, NULL); err_iounmap: iounmap(wdt->regs); err_free: kfree(wdt); wdt = NULL; return ret; } static int __exit at32_wdt_remove(struct platform_device *pdev) { if (wdt && platform_get_drvdata(pdev) == wdt) { /* Stop the timer before we leave */ if (!nowayout) at32_wdt_stop(); misc_deregister(&wdt->miscdev); iounmap(wdt->regs); kfree(wdt); wdt = NULL; platform_set_drvdata(pdev, NULL); } return 0; } static void at32_wdt_shutdown(struct platform_device *pdev) { at32_wdt_stop(); } #ifdef CONFIG_PM static int at32_wdt_suspend(struct platform_device *pdev, pm_message_t message) { at32_wdt_stop(); return 0; } static int at32_wdt_resume(struct platform_device *pdev) { if (wdt->users) at32_wdt_start(); return 0; } #else #define at32_wdt_suspend NULL #define at32_wdt_resume NULL #endif /* work with hotplug and coldplug */ MODULE_ALIAS("platform:at32_wdt"); static struct platform_driver at32_wdt_driver = { .remove = __exit_p(at32_wdt_remove), .suspend = at32_wdt_suspend, .resume = at32_wdt_resume, .driver = { .name = "at32_wdt", .owner = THIS_MODULE, }, .shutdown = at32_wdt_shutdown, }; static int __init at32_wdt_init(void) { return platform_driver_probe(&at32_wdt_driver, at32_wdt_probe); } module_init(at32_wdt_init); static void __exit at32_wdt_exit(void) { platform_driver_unregister(&at32_wdt_driver); } module_exit(at32_wdt_exit); MODULE_AUTHOR("Hans-Christian Egtvedt <egtvedt@samfundet.no>"); MODULE_DESCRIPTION("Watchdog driver for Atmel AT32AP700X"); MODULE_LICENSE("GPL"); MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
gpl-2.0
uberlaggydarwin/306shcaf
drivers/tty/serial/nwpserial.c
5337
11638
/* * Serial Port driver for a NWP uart device * * Copyright (C) 2008 IBM Corp., Benjamin Krill <ben@codiert.org> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * */ #include <linux/init.h> #include <linux/export.h> #include <linux/console.h> #include <linux/serial.h> #include <linux/serial_reg.h> #include <linux/serial_core.h> #include <linux/tty.h> #include <linux/tty_flip.h> #include <linux/irqreturn.h> #include <linux/mutex.h> #include <linux/of_platform.h> #include <linux/of_device.h> #include <linux/nwpserial.h> #include <asm/prom.h> #include <asm/dcr.h> #define NWPSERIAL_NR 2 #define NWPSERIAL_STATUS_RXVALID 0x1 #define NWPSERIAL_STATUS_TXFULL 0x2 struct nwpserial_port { struct uart_port port; dcr_host_t dcr_host; unsigned int ier; unsigned int mcr; }; static DEFINE_MUTEX(nwpserial_mutex); static struct nwpserial_port nwpserial_ports[NWPSERIAL_NR]; static void wait_for_bits(struct nwpserial_port *up, int bits) { unsigned int status, tmout = 10000; /* Wait up to 10ms for the character(s) to be sent. */ do { status = dcr_read(up->dcr_host, UART_LSR); if (--tmout == 0) break; udelay(1); } while ((status & bits) != bits); } #ifdef CONFIG_SERIAL_OF_PLATFORM_NWPSERIAL_CONSOLE static void nwpserial_console_putchar(struct uart_port *port, int c) { struct nwpserial_port *up; up = container_of(port, struct nwpserial_port, port); /* check if tx buffer is full */ wait_for_bits(up, UART_LSR_THRE); dcr_write(up->dcr_host, UART_TX, c); up->port.icount.tx++; } static void nwpserial_console_write(struct console *co, const char *s, unsigned int count) { struct nwpserial_port *up = &nwpserial_ports[co->index]; unsigned long flags; int locked = 1; if (oops_in_progress) locked = spin_trylock_irqsave(&up->port.lock, flags); else spin_lock_irqsave(&up->port.lock, flags); /* save and disable interrupt */ up->ier = dcr_read(up->dcr_host, UART_IER); dcr_write(up->dcr_host, UART_IER, up->ier & ~UART_IER_RDI); uart_console_write(&up->port, s, count, nwpserial_console_putchar); /* wait for transmitter to become empty */ while ((dcr_read(up->dcr_host, UART_LSR) & UART_LSR_THRE) == 0) cpu_relax(); /* restore interrupt state */ dcr_write(up->dcr_host, UART_IER, up->ier); if (locked) spin_unlock_irqrestore(&up->port.lock, flags); } static struct uart_driver nwpserial_reg; static struct console nwpserial_console = { .name = "ttySQ", .write = nwpserial_console_write, .device = uart_console_device, .flags = CON_PRINTBUFFER, .index = -1, .data = &nwpserial_reg, }; #define NWPSERIAL_CONSOLE (&nwpserial_console) #else #define NWPSERIAL_CONSOLE NULL #endif /* CONFIG_SERIAL_OF_PLATFORM_NWPSERIAL_CONSOLE */ /**************************************************************************/ static int nwpserial_request_port(struct uart_port *port) { return 0; } static void nwpserial_release_port(struct uart_port *port) { /* N/A */ } static void nwpserial_config_port(struct uart_port *port, int flags) { port->type = PORT_NWPSERIAL; } static irqreturn_t nwpserial_interrupt(int irq, void *dev_id) { struct nwpserial_port *up = dev_id; struct tty_struct *tty = up->port.state->port.tty; irqreturn_t ret; unsigned int iir; unsigned char ch; spin_lock(&up->port.lock); /* check if the uart was the interrupt source. */ iir = dcr_read(up->dcr_host, UART_IIR); if (!iir) { ret = IRQ_NONE; goto out; } do { up->port.icount.rx++; ch = dcr_read(up->dcr_host, UART_RX); if (up->port.ignore_status_mask != NWPSERIAL_STATUS_RXVALID) tty_insert_flip_char(tty, ch, TTY_NORMAL); } while (dcr_read(up->dcr_host, UART_LSR) & UART_LSR_DR); tty_flip_buffer_push(tty); ret = IRQ_HANDLED; /* clear interrupt */ dcr_write(up->dcr_host, UART_IIR, 1); out: spin_unlock(&up->port.lock); return ret; } static int nwpserial_startup(struct uart_port *port) { struct nwpserial_port *up; int err; up = container_of(port, struct nwpserial_port, port); /* disable flow control by default */ up->mcr = dcr_read(up->dcr_host, UART_MCR) & ~UART_MCR_AFE; dcr_write(up->dcr_host, UART_MCR, up->mcr); /* register interrupt handler */ err = request_irq(up->port.irq, nwpserial_interrupt, IRQF_SHARED, "nwpserial", up); if (err) return err; /* enable interrupts */ up->ier = UART_IER_RDI; dcr_write(up->dcr_host, UART_IER, up->ier); /* enable receiving */ up->port.ignore_status_mask &= ~NWPSERIAL_STATUS_RXVALID; return 0; } static void nwpserial_shutdown(struct uart_port *port) { struct nwpserial_port *up; up = container_of(port, struct nwpserial_port, port); /* disable receiving */ up->port.ignore_status_mask |= NWPSERIAL_STATUS_RXVALID; /* disable interrupts from this port */ up->ier = 0; dcr_write(up->dcr_host, UART_IER, up->ier); /* free irq */ free_irq(up->port.irq, port); } static int nwpserial_verify_port(struct uart_port *port, struct serial_struct *ser) { return -EINVAL; } static const char *nwpserial_type(struct uart_port *port) { return port->type == PORT_NWPSERIAL ? "nwpserial" : NULL; } static void nwpserial_set_termios(struct uart_port *port, struct ktermios *termios, struct ktermios *old) { struct nwpserial_port *up; up = container_of(port, struct nwpserial_port, port); up->port.read_status_mask = NWPSERIAL_STATUS_RXVALID | NWPSERIAL_STATUS_TXFULL; up->port.ignore_status_mask = 0; /* ignore all characters if CREAD is not set */ if ((termios->c_cflag & CREAD) == 0) up->port.ignore_status_mask |= NWPSERIAL_STATUS_RXVALID; /* Copy back the old hardware settings */ if (old) tty_termios_copy_hw(termios, old); } static void nwpserial_break_ctl(struct uart_port *port, int ctl) { /* N/A */ } static void nwpserial_enable_ms(struct uart_port *port) { /* N/A */ } static void nwpserial_stop_rx(struct uart_port *port) { struct nwpserial_port *up; up = container_of(port, struct nwpserial_port, port); /* don't forward any more data (like !CREAD) */ up->port.ignore_status_mask = NWPSERIAL_STATUS_RXVALID; } static void nwpserial_putchar(struct nwpserial_port *up, unsigned char c) { /* check if tx buffer is full */ wait_for_bits(up, UART_LSR_THRE); dcr_write(up->dcr_host, UART_TX, c); up->port.icount.tx++; } static void nwpserial_start_tx(struct uart_port *port) { struct nwpserial_port *up; struct circ_buf *xmit; up = container_of(port, struct nwpserial_port, port); xmit = &up->port.state->xmit; if (port->x_char) { nwpserial_putchar(up, up->port.x_char); port->x_char = 0; } while (!(uart_circ_empty(xmit) || uart_tx_stopped(&up->port))) { nwpserial_putchar(up, xmit->buf[xmit->tail]); xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE-1); } } static unsigned int nwpserial_get_mctrl(struct uart_port *port) { return 0; } static void nwpserial_set_mctrl(struct uart_port *port, unsigned int mctrl) { /* N/A */ } static void nwpserial_stop_tx(struct uart_port *port) { /* N/A */ } static unsigned int nwpserial_tx_empty(struct uart_port *port) { struct nwpserial_port *up; unsigned long flags; int ret; up = container_of(port, struct nwpserial_port, port); spin_lock_irqsave(&up->port.lock, flags); ret = dcr_read(up->dcr_host, UART_LSR); spin_unlock_irqrestore(&up->port.lock, flags); return ret & UART_LSR_TEMT ? TIOCSER_TEMT : 0; } static struct uart_ops nwpserial_pops = { .tx_empty = nwpserial_tx_empty, .set_mctrl = nwpserial_set_mctrl, .get_mctrl = nwpserial_get_mctrl, .stop_tx = nwpserial_stop_tx, .start_tx = nwpserial_start_tx, .stop_rx = nwpserial_stop_rx, .enable_ms = nwpserial_enable_ms, .break_ctl = nwpserial_break_ctl, .startup = nwpserial_startup, .shutdown = nwpserial_shutdown, .set_termios = nwpserial_set_termios, .type = nwpserial_type, .release_port = nwpserial_release_port, .request_port = nwpserial_request_port, .config_port = nwpserial_config_port, .verify_port = nwpserial_verify_port, }; static struct uart_driver nwpserial_reg = { .owner = THIS_MODULE, .driver_name = "nwpserial", .dev_name = "ttySQ", .major = TTY_MAJOR, .minor = 68, .nr = NWPSERIAL_NR, .cons = NWPSERIAL_CONSOLE, }; int nwpserial_register_port(struct uart_port *port) { struct nwpserial_port *up = NULL; int ret = -1; int i; static int first = 1; int dcr_len; int dcr_base; struct device_node *dn; mutex_lock(&nwpserial_mutex); dn = port->dev->of_node; if (dn == NULL) goto out; /* get dcr base. */ dcr_base = dcr_resource_start(dn, 0); /* find matching entry */ for (i = 0; i < NWPSERIAL_NR; i++) if (nwpserial_ports[i].port.iobase == dcr_base) { up = &nwpserial_ports[i]; break; } /* we didn't find a mtching entry, search for a free port */ if (up == NULL) for (i = 0; i < NWPSERIAL_NR; i++) if (nwpserial_ports[i].port.type == PORT_UNKNOWN && nwpserial_ports[i].port.iobase == 0) { up = &nwpserial_ports[i]; break; } if (up == NULL) { ret = -EBUSY; goto out; } if (first) uart_register_driver(&nwpserial_reg); first = 0; up->port.membase = port->membase; up->port.irq = port->irq; up->port.uartclk = port->uartclk; up->port.fifosize = port->fifosize; up->port.regshift = port->regshift; up->port.iotype = port->iotype; up->port.flags = port->flags; up->port.mapbase = port->mapbase; up->port.private_data = port->private_data; if (port->dev) up->port.dev = port->dev; if (up->port.iobase != dcr_base) { up->port.ops = &nwpserial_pops; up->port.fifosize = 16; spin_lock_init(&up->port.lock); up->port.iobase = dcr_base; dcr_len = dcr_resource_len(dn, 0); up->dcr_host = dcr_map(dn, dcr_base, dcr_len); if (!DCR_MAP_OK(up->dcr_host)) { printk(KERN_ERR "Cannot map DCR resources for NWPSERIAL"); goto out; } } ret = uart_add_one_port(&nwpserial_reg, &up->port); if (ret == 0) ret = up->port.line; out: mutex_unlock(&nwpserial_mutex); return ret; } EXPORT_SYMBOL(nwpserial_register_port); void nwpserial_unregister_port(int line) { struct nwpserial_port *up = &nwpserial_ports[line]; mutex_lock(&nwpserial_mutex); uart_remove_one_port(&nwpserial_reg, &up->port); up->port.type = PORT_UNKNOWN; mutex_unlock(&nwpserial_mutex); } EXPORT_SYMBOL(nwpserial_unregister_port); #ifdef CONFIG_SERIAL_OF_PLATFORM_NWPSERIAL_CONSOLE static int __init nwpserial_console_init(void) { struct nwpserial_port *up = NULL; struct device_node *dn; const char *name; int dcr_base; int dcr_len; int i; /* search for a free port */ for (i = 0; i < NWPSERIAL_NR; i++) if (nwpserial_ports[i].port.type == PORT_UNKNOWN) { up = &nwpserial_ports[i]; break; } if (up == NULL) return -1; name = of_get_property(of_chosen, "linux,stdout-path", NULL); if (name == NULL) return -1; dn = of_find_node_by_path(name); if (!dn) return -1; spin_lock_init(&up->port.lock); up->port.ops = &nwpserial_pops; up->port.type = PORT_NWPSERIAL; up->port.fifosize = 16; dcr_base = dcr_resource_start(dn, 0); dcr_len = dcr_resource_len(dn, 0); up->port.iobase = dcr_base; up->dcr_host = dcr_map(dn, dcr_base, dcr_len); if (!DCR_MAP_OK(up->dcr_host)) { printk("Cannot map DCR resources for SERIAL"); return -1; } register_console(&nwpserial_console); return 0; } console_initcall(nwpserial_console_init); #endif /* CONFIG_SERIAL_OF_PLATFORM_NWPSERIAL_CONSOLE */
gpl-2.0
bangprovn/android_kernel_lge_v400_10c
drivers/watchdog/pnx833x_wdt.c
7385
7288
/* * PNX833x Hardware Watchdog Driver * Copyright 2008 NXP Semiconductors * Daniel Laird <daniel.j.laird@nxp.com> * Andre McCurdy <andre.mccurdy@nxp.com> * * Heavily based upon - IndyDog 0.3 * A Hardware Watchdog Device for SGI IP22 * * (c) Copyright 2002 Guido Guenther <agx@sigxcpu.org>, 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. * * based on softdog.c by Alan Cox <alan@redhat.com> */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/mm.h> #include <linux/miscdevice.h> #include <linux/watchdog.h> #include <linux/notifier.h> #include <linux/reboot.h> #include <linux/init.h> #include <asm/mach-pnx833x/pnx833x.h> #define WATCHDOG_TIMEOUT 30 /* 30 sec Maximum timeout */ #define WATCHDOG_COUNT_FREQUENCY 68000000U /* Watchdog counts at 68MHZ. */ #define PNX_WATCHDOG_TIMEOUT (WATCHDOG_TIMEOUT * WATCHDOG_COUNT_FREQUENCY) #define PNX_TIMEOUT_VALUE 2040000000U /** CONFIG block */ #define PNX833X_CONFIG (0x07000U) #define PNX833X_CONFIG_CPU_WATCHDOG (0x54) #define PNX833X_CONFIG_CPU_WATCHDOG_COMPARE (0x58) #define PNX833X_CONFIG_CPU_COUNTERS_CONTROL (0x1c) /** RESET block */ #define PNX833X_RESET (0x08000U) #define PNX833X_RESET_CONFIG (0x08) static int pnx833x_wdt_alive; /* Set default timeout in MHZ.*/ static int pnx833x_wdt_timeout = PNX_WATCHDOG_TIMEOUT; module_param(pnx833x_wdt_timeout, int, 0); MODULE_PARM_DESC(timeout, "Watchdog timeout in Mhz. (68Mhz clock), default=" __MODULE_STRING(PNX_TIMEOUT_VALUE) "(30 seconds)."); static bool nowayout = WATCHDOG_NOWAYOUT; module_param(nowayout, bool, 0); MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default=" __MODULE_STRING(WATCHDOG_NOWAYOUT) ")"); #define START_DEFAULT 1 static int start_enabled = START_DEFAULT; module_param(start_enabled, int, 0); MODULE_PARM_DESC(start_enabled, "Watchdog is started on module insertion " "(default=" __MODULE_STRING(START_DEFAULT) ")"); static void pnx833x_wdt_start(void) { /* Enable watchdog causing reset. */ PNX833X_REG(PNX833X_RESET + PNX833X_RESET_CONFIG) |= 0x1; /* Set timeout.*/ PNX833X_REG(PNX833X_CONFIG + PNX833X_CONFIG_CPU_WATCHDOG_COMPARE) = pnx833x_wdt_timeout; /* Enable watchdog. */ PNX833X_REG(PNX833X_CONFIG + PNX833X_CONFIG_CPU_COUNTERS_CONTROL) |= 0x1; pr_info("Started watchdog timer\n"); } static void pnx833x_wdt_stop(void) { /* Disable watchdog causing reset. */ PNX833X_REG(PNX833X_RESET + PNX833X_CONFIG) &= 0xFFFFFFFE; /* Disable watchdog.*/ PNX833X_REG(PNX833X_CONFIG + PNX833X_CONFIG_CPU_COUNTERS_CONTROL) &= 0xFFFFFFFE; pr_info("Stopped watchdog timer\n"); } static void pnx833x_wdt_ping(void) { PNX833X_REG(PNX833X_CONFIG + PNX833X_CONFIG_CPU_WATCHDOG_COMPARE) = pnx833x_wdt_timeout; } /* * Allow only one person to hold it open */ static int pnx833x_wdt_open(struct inode *inode, struct file *file) { if (test_and_set_bit(0, &pnx833x_wdt_alive)) return -EBUSY; if (nowayout) __module_get(THIS_MODULE); /* Activate timer */ if (!start_enabled) pnx833x_wdt_start(); pnx833x_wdt_ping(); pr_info("Started watchdog timer\n"); return nonseekable_open(inode, file); } static int pnx833x_wdt_release(struct inode *inode, struct file *file) { /* Shut off the timer. * Lock it in if it's a module and we defined ...NOWAYOUT */ if (!nowayout) pnx833x_wdt_stop(); /* Turn the WDT off */ clear_bit(0, &pnx833x_wdt_alive); return 0; } static ssize_t pnx833x_wdt_write(struct file *file, const char *data, size_t len, loff_t *ppos) { /* Refresh the timer. */ if (len) pnx833x_wdt_ping(); return len; } static long pnx833x_wdt_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { int options, new_timeout = 0; uint32_t timeout, timeout_left = 0; static const struct watchdog_info ident = { .options = WDIOF_KEEPALIVEPING | WDIOF_SETTIMEOUT, .firmware_version = 0, .identity = "Hardware Watchdog for PNX833x", }; switch (cmd) { default: return -ENOTTY; case WDIOC_GETSUPPORT: if (copy_to_user((struct watchdog_info *)arg, &ident, sizeof(ident))) return -EFAULT; return 0; case WDIOC_GETSTATUS: case WDIOC_GETBOOTSTATUS: return put_user(0, (int *)arg); case WDIOC_SETOPTIONS: if (get_user(options, (int *)arg)) return -EFAULT; if (options & WDIOS_DISABLECARD) pnx833x_wdt_stop(); if (options & WDIOS_ENABLECARD) pnx833x_wdt_start(); return 0; case WDIOC_KEEPALIVE: pnx833x_wdt_ping(); return 0; case WDIOC_SETTIMEOUT: { if (get_user(new_timeout, (int *)arg)) return -EFAULT; pnx833x_wdt_timeout = new_timeout; PNX833X_REG(PNX833X_CONFIG + PNX833X_CONFIG_CPU_WATCHDOG_COMPARE) = new_timeout; return put_user(new_timeout, (int *)arg); } case WDIOC_GETTIMEOUT: timeout = PNX833X_REG(PNX833X_CONFIG + PNX833X_CONFIG_CPU_WATCHDOG_COMPARE); return put_user(timeout, (int *)arg); case WDIOC_GETTIMELEFT: timeout_left = PNX833X_REG(PNX833X_CONFIG + PNX833X_CONFIG_CPU_WATCHDOG); return put_user(timeout_left, (int *)arg); } } static int pnx833x_wdt_notify_sys(struct notifier_block *this, unsigned long code, void *unused) { if (code == SYS_DOWN || code == SYS_HALT) pnx833x_wdt_stop(); /* Turn the WDT off */ return NOTIFY_DONE; } static const struct file_operations pnx833x_wdt_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .write = pnx833x_wdt_write, .unlocked_ioctl = pnx833x_wdt_ioctl, .open = pnx833x_wdt_open, .release = pnx833x_wdt_release, }; static struct miscdevice pnx833x_wdt_miscdev = { .minor = WATCHDOG_MINOR, .name = "watchdog", .fops = &pnx833x_wdt_fops, }; static struct notifier_block pnx833x_wdt_notifier = { .notifier_call = pnx833x_wdt_notify_sys, }; static int __init watchdog_init(void) { int ret, cause; /* Lets check the reason for the reset.*/ cause = PNX833X_REG(PNX833X_RESET); /*If bit 31 is set then watchdog was cause of reset.*/ if (cause & 0x80000000) { pr_info("The system was previously reset due to the watchdog firing - please investigate...\n"); } ret = register_reboot_notifier(&pnx833x_wdt_notifier); if (ret) { pr_err("cannot register reboot notifier (err=%d)\n", ret); return ret; } ret = misc_register(&pnx833x_wdt_miscdev); if (ret) { pr_err("cannot register miscdev on minor=%d (err=%d)\n", WATCHDOG_MINOR, ret); unregister_reboot_notifier(&pnx833x_wdt_notifier); return ret; } pr_info("Hardware Watchdog Timer for PNX833x: Version 0.1\n"); if (start_enabled) pnx833x_wdt_start(); return 0; } static void __exit watchdog_exit(void) { misc_deregister(&pnx833x_wdt_miscdev); unregister_reboot_notifier(&pnx833x_wdt_notifier); } module_init(watchdog_init); module_exit(watchdog_exit); MODULE_AUTHOR("Daniel Laird/Andre McCurdy"); MODULE_DESCRIPTION("Hardware Watchdog Device for PNX833x"); MODULE_LICENSE("GPL"); MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
gpl-2.0
tianchi-dev/android_kernel_sony_msm8226
drivers/watchdog/wafer5823wdt.c
7385
7294
/* * ICP Wafer 5823 Single Board Computer WDT driver * http://www.icpamerica.com/wafer_5823.php * May also work on other similar models * * (c) Copyright 2002 Justin Cormack <justin@street-vision.com> * * Release 0.02 * * Based on advantechwdt.c which is based on wdt.c. * Original copyright messages: * * (c) Copyright 1996-1997 Alan Cox <alan@lxorguk.ukuu.org.uk>, * 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. * * Neither Alan Cox nor CymruNet Ltd. admit liability nor provide * warranty for any of this software. This material is provided * "AS-IS" and at no charge. * * (c) Copyright 1995 Alan Cox <alan@lxorguk.ukuu.org.uk> * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/miscdevice.h> #include <linux/watchdog.h> #include <linux/fs.h> #include <linux/ioport.h> #include <linux/notifier.h> #include <linux/reboot.h> #include <linux/init.h> #include <linux/spinlock.h> #include <linux/io.h> #include <linux/uaccess.h> #define WATCHDOG_NAME "Wafer 5823 WDT" #define PFX WATCHDOG_NAME ": " #define WD_TIMO 60 /* 60 sec default timeout */ static unsigned long wafwdt_is_open; static char expect_close; static DEFINE_SPINLOCK(wafwdt_lock); /* * You must set these - there is no sane way to probe for this board. * * To enable, write the timeout value in seconds (1 to 255) to I/O * port WDT_START, then read the port to start the watchdog. To pat * the dog, read port WDT_STOP to stop the timer, then read WDT_START * to restart it again. */ static int wdt_stop = 0x843; static int wdt_start = 0x443; static int timeout = WD_TIMO; /* in seconds */ module_param(timeout, int, 0); MODULE_PARM_DESC(timeout, "Watchdog timeout in seconds. 1 <= timeout <= 255, default=" __MODULE_STRING(WD_TIMO) "."); static bool nowayout = WATCHDOG_NOWAYOUT; module_param(nowayout, bool, 0); MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default=" __MODULE_STRING(WATCHDOG_NOWAYOUT) ")"); static void wafwdt_ping(void) { /* pat watchdog */ spin_lock(&wafwdt_lock); inb_p(wdt_stop); inb_p(wdt_start); spin_unlock(&wafwdt_lock); } static void wafwdt_start(void) { /* start up watchdog */ outb_p(timeout, wdt_start); inb_p(wdt_start); } static void wafwdt_stop(void) { /* stop watchdog */ inb_p(wdt_stop); } static ssize_t wafwdt_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { /* See if we got the magic character 'V' and reload the timer */ if (count) { if (!nowayout) { size_t i; /* In case it was set long ago */ expect_close = 0; /* scan to see whether or not we got the magic character */ for (i = 0; i != count; i++) { char c; if (get_user(c, buf + i)) return -EFAULT; if (c == 'V') expect_close = 42; } } /* Well, anyhow someone wrote to us, we should return that favour */ wafwdt_ping(); } return count; } static long wafwdt_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { int new_timeout; void __user *argp = (void __user *)arg; int __user *p = argp; static const struct watchdog_info ident = { .options = WDIOF_KEEPALIVEPING | WDIOF_SETTIMEOUT | WDIOF_MAGICCLOSE, .firmware_version = 1, .identity = "Wafer 5823 WDT", }; switch (cmd) { case WDIOC_GETSUPPORT: if (copy_to_user(argp, &ident, sizeof(ident))) return -EFAULT; break; case WDIOC_GETSTATUS: case WDIOC_GETBOOTSTATUS: return put_user(0, p); case WDIOC_SETOPTIONS: { int options, retval = -EINVAL; if (get_user(options, p)) return -EFAULT; if (options & WDIOS_DISABLECARD) { wafwdt_stop(); retval = 0; } if (options & WDIOS_ENABLECARD) { wafwdt_start(); retval = 0; } return retval; } case WDIOC_KEEPALIVE: wafwdt_ping(); break; case WDIOC_SETTIMEOUT: if (get_user(new_timeout, p)) return -EFAULT; if ((new_timeout < 1) || (new_timeout > 255)) return -EINVAL; timeout = new_timeout; wafwdt_stop(); wafwdt_start(); /* Fall */ case WDIOC_GETTIMEOUT: return put_user(timeout, p); default: return -ENOTTY; } return 0; } static int wafwdt_open(struct inode *inode, struct file *file) { if (test_and_set_bit(0, &wafwdt_is_open)) return -EBUSY; /* * Activate */ wafwdt_start(); return nonseekable_open(inode, file); } static int wafwdt_close(struct inode *inode, struct file *file) { if (expect_close == 42) wafwdt_stop(); else { pr_crit("WDT device closed unexpectedly. WDT will not stop!\n"); wafwdt_ping(); } clear_bit(0, &wafwdt_is_open); expect_close = 0; return 0; } /* * Notifier for system down */ static int wafwdt_notify_sys(struct notifier_block *this, unsigned long code, void *unused) { if (code == SYS_DOWN || code == SYS_HALT) wafwdt_stop(); return NOTIFY_DONE; } /* * Kernel Interfaces */ static const struct file_operations wafwdt_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .write = wafwdt_write, .unlocked_ioctl = wafwdt_ioctl, .open = wafwdt_open, .release = wafwdt_close, }; static struct miscdevice wafwdt_miscdev = { .minor = WATCHDOG_MINOR, .name = "watchdog", .fops = &wafwdt_fops, }; /* * The WDT needs to learn about soft shutdowns in order to * turn the timebomb registers off. */ static struct notifier_block wafwdt_notifier = { .notifier_call = wafwdt_notify_sys, }; static int __init wafwdt_init(void) { int ret; pr_info("WDT driver for Wafer 5823 single board computer initialising\n"); if (timeout < 1 || timeout > 255) { timeout = WD_TIMO; pr_info("timeout value must be 1 <= x <= 255, using %d\n", timeout); } if (wdt_stop != wdt_start) { if (!request_region(wdt_stop, 1, "Wafer 5823 WDT")) { pr_err("I/O address 0x%04x already in use\n", wdt_stop); ret = -EIO; goto error; } } if (!request_region(wdt_start, 1, "Wafer 5823 WDT")) { pr_err("I/O address 0x%04x already in use\n", wdt_start); ret = -EIO; goto error2; } ret = register_reboot_notifier(&wafwdt_notifier); if (ret != 0) { pr_err("cannot register reboot notifier (err=%d)\n", ret); goto error3; } ret = misc_register(&wafwdt_miscdev); if (ret != 0) { pr_err("cannot register miscdev on minor=%d (err=%d)\n", WATCHDOG_MINOR, ret); goto error4; } pr_info("initialized. timeout=%d sec (nowayout=%d)\n", timeout, nowayout); return ret; error4: unregister_reboot_notifier(&wafwdt_notifier); error3: release_region(wdt_start, 1); error2: if (wdt_stop != wdt_start) release_region(wdt_stop, 1); error: return ret; } static void __exit wafwdt_exit(void) { misc_deregister(&wafwdt_miscdev); unregister_reboot_notifier(&wafwdt_notifier); if (wdt_stop != wdt_start) release_region(wdt_stop, 1); release_region(wdt_start, 1); } module_init(wafwdt_init); module_exit(wafwdt_exit); MODULE_AUTHOR("Justin Cormack"); MODULE_DESCRIPTION("ICP Wafer 5823 Single Board Computer WDT driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR); /* end of wafer5823wdt.c */
gpl-2.0
vasishath/kernel_cancro
drivers/net/wireless/orinoco/hermes.c
8153
20038
/* hermes.c * * Driver core for the "Hermes" wireless MAC controller, as used in * the Lucent Orinoco and Cabletron RoamAbout cards. It should also * work on the hfa3841 and hfa3842 MAC controller chips used in the * Prism II chipsets. * * This is not a complete driver, just low-level access routines for * the MAC controller itself. * * Based on the prism2 driver from Absolute Value Systems' linux-wlan * project, the Linux wvlan_cs driver, Lucent's HCF-Light * (wvlan_hcf.c) library, and the NetBSD wireless driver (in no * particular order). * * Copyright (C) 2000, David Gibson, Linuxcare Australia. * (C) Copyright David Gibson, IBM Corp. 2001-2003. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License * at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and * limitations under the License. * * Alternatively, the contents of this file may be used under the * terms of the GNU General Public License version 2 (the "GPL"), in * which case the provisions of the GPL are applicable instead of the * above. If you wish to allow the use of your version of this file * only under the terms of the GPL and not to allow others to use your * version of this file under the MPL, indicate your decision by * deleting the provisions above and replace them with the notice and * other provisions required by the GPL. If you do not delete the * provisions above, a recipient may use your version of this file * under either the MPL or the GPL. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/delay.h> #include "hermes.h" /* These are maximum timeouts. Most often, card wil react much faster */ #define CMD_BUSY_TIMEOUT (100) /* In iterations of ~1us */ #define CMD_INIT_TIMEOUT (50000) /* in iterations of ~10us */ #define CMD_COMPL_TIMEOUT (20000) /* in iterations of ~10us */ #define ALLOC_COMPL_TIMEOUT (1000) /* in iterations of ~10us */ /* * AUX port access. To unlock the AUX port write the access keys to the * PARAM0-2 registers, then write HERMES_AUX_ENABLE to the HERMES_CONTROL * register. Then read it and make sure it's HERMES_AUX_ENABLED. */ #define HERMES_AUX_ENABLE 0x8000 /* Enable auxiliary port access */ #define HERMES_AUX_DISABLE 0x4000 /* Disable to auxiliary port access */ #define HERMES_AUX_ENABLED 0xC000 /* Auxiliary port is open */ #define HERMES_AUX_DISABLED 0x0000 /* Auxiliary port is closed */ #define HERMES_AUX_PW0 0xFE01 #define HERMES_AUX_PW1 0xDC23 #define HERMES_AUX_PW2 0xBA45 /* HERMES_CMD_DOWNLD */ #define HERMES_PROGRAM_DISABLE (0x0000 | HERMES_CMD_DOWNLD) #define HERMES_PROGRAM_ENABLE_VOLATILE (0x0100 | HERMES_CMD_DOWNLD) #define HERMES_PROGRAM_ENABLE_NON_VOLATILE (0x0200 | HERMES_CMD_DOWNLD) #define HERMES_PROGRAM_NON_VOLATILE (0x0300 | HERMES_CMD_DOWNLD) /* * Debugging helpers */ #define DMSG(stuff...) do {printk(KERN_DEBUG "hermes @ %p: " , hw->iobase); \ printk(stuff); } while (0) #undef HERMES_DEBUG #ifdef HERMES_DEBUG #include <stdarg.h> #define DEBUG(lvl, stuff...) if ((lvl) <= HERMES_DEBUG) DMSG(stuff) #else /* ! HERMES_DEBUG */ #define DEBUG(lvl, stuff...) do { } while (0) #endif /* ! HERMES_DEBUG */ static const struct hermes_ops hermes_ops_local; /* * Internal functions */ /* Issue a command to the chip. Waiting for it to complete is the caller's problem. Returns -EBUSY if the command register is busy, 0 on success. Callable from any context. */ static int hermes_issue_cmd(struct hermes *hw, u16 cmd, u16 param0, u16 param1, u16 param2) { int k = CMD_BUSY_TIMEOUT; u16 reg; /* First wait for the command register to unbusy */ reg = hermes_read_regn(hw, CMD); while ((reg & HERMES_CMD_BUSY) && k) { k--; udelay(1); reg = hermes_read_regn(hw, CMD); } if (reg & HERMES_CMD_BUSY) return -EBUSY; hermes_write_regn(hw, PARAM2, param2); hermes_write_regn(hw, PARAM1, param1); hermes_write_regn(hw, PARAM0, param0); hermes_write_regn(hw, CMD, cmd); return 0; } /* * Function definitions */ /* For doing cmds that wipe the magic constant in SWSUPPORT0 */ static int hermes_doicmd_wait(struct hermes *hw, u16 cmd, u16 parm0, u16 parm1, u16 parm2, struct hermes_response *resp) { int err = 0; int k; u16 status, reg; err = hermes_issue_cmd(hw, cmd, parm0, parm1, parm2); if (err) return err; reg = hermes_read_regn(hw, EVSTAT); k = CMD_INIT_TIMEOUT; while ((!(reg & HERMES_EV_CMD)) && k) { k--; udelay(10); reg = hermes_read_regn(hw, EVSTAT); } hermes_write_regn(hw, SWSUPPORT0, HERMES_MAGIC); if (!hermes_present(hw)) { DEBUG(0, "hermes @ 0x%x: Card removed during reset.\n", hw->iobase); err = -ENODEV; goto out; } if (!(reg & HERMES_EV_CMD)) { printk(KERN_ERR "hermes @ %p: " "Timeout waiting for card to reset (reg=0x%04x)!\n", hw->iobase, reg); err = -ETIMEDOUT; goto out; } status = hermes_read_regn(hw, STATUS); if (resp) { resp->status = status; resp->resp0 = hermes_read_regn(hw, RESP0); resp->resp1 = hermes_read_regn(hw, RESP1); resp->resp2 = hermes_read_regn(hw, RESP2); } hermes_write_regn(hw, EVACK, HERMES_EV_CMD); if (status & HERMES_STATUS_RESULT) err = -EIO; out: return err; } void hermes_struct_init(struct hermes *hw, void __iomem *address, int reg_spacing) { hw->iobase = address; hw->reg_spacing = reg_spacing; hw->inten = 0x0; hw->eeprom_pda = false; hw->ops = &hermes_ops_local; } EXPORT_SYMBOL(hermes_struct_init); static int hermes_init(struct hermes *hw) { u16 reg; int err = 0; int k; /* We don't want to be interrupted while resetting the chipset */ hw->inten = 0x0; hermes_write_regn(hw, INTEN, 0); hermes_write_regn(hw, EVACK, 0xffff); /* Normally it's a "can't happen" for the command register to be busy when we go to issue a command because we are serializing all commands. However we want to have some chance of resetting the card even if it gets into a stupid state, so we actually wait to see if the command register will unbusy itself here. */ k = CMD_BUSY_TIMEOUT; reg = hermes_read_regn(hw, CMD); while (k && (reg & HERMES_CMD_BUSY)) { if (reg == 0xffff) /* Special case - the card has probably been removed, so don't wait for the timeout */ return -ENODEV; k--; udelay(1); reg = hermes_read_regn(hw, CMD); } /* No need to explicitly handle the timeout - if we've timed out hermes_issue_cmd() will probably return -EBUSY below */ /* According to the documentation, EVSTAT may contain obsolete event occurrence information. We have to acknowledge it by writing EVACK. */ reg = hermes_read_regn(hw, EVSTAT); hermes_write_regn(hw, EVACK, reg); /* We don't use hermes_docmd_wait here, because the reset wipes the magic constant in SWSUPPORT0 away, and it gets confused */ err = hermes_doicmd_wait(hw, HERMES_CMD_INIT, 0, 0, 0, NULL); return err; } /* Issue a command to the chip, and (busy!) wait for it to * complete. * * Returns: * < 0 on internal error * 0 on success * > 0 on error returned by the firmware * * Callable from any context, but locking is your problem. */ static int hermes_docmd_wait(struct hermes *hw, u16 cmd, u16 parm0, struct hermes_response *resp) { int err; int k; u16 reg; u16 status; err = hermes_issue_cmd(hw, cmd, parm0, 0, 0); if (err) { if (!hermes_present(hw)) { if (net_ratelimit()) printk(KERN_WARNING "hermes @ %p: " "Card removed while issuing command " "0x%04x.\n", hw->iobase, cmd); err = -ENODEV; } else if (net_ratelimit()) printk(KERN_ERR "hermes @ %p: " "Error %d issuing command 0x%04x.\n", hw->iobase, err, cmd); goto out; } reg = hermes_read_regn(hw, EVSTAT); k = CMD_COMPL_TIMEOUT; while ((!(reg & HERMES_EV_CMD)) && k) { k--; udelay(10); reg = hermes_read_regn(hw, EVSTAT); } if (!hermes_present(hw)) { printk(KERN_WARNING "hermes @ %p: Card removed " "while waiting for command 0x%04x completion.\n", hw->iobase, cmd); err = -ENODEV; goto out; } if (!(reg & HERMES_EV_CMD)) { printk(KERN_ERR "hermes @ %p: Timeout waiting for " "command 0x%04x completion.\n", hw->iobase, cmd); err = -ETIMEDOUT; goto out; } status = hermes_read_regn(hw, STATUS); if (resp) { resp->status = status; resp->resp0 = hermes_read_regn(hw, RESP0); resp->resp1 = hermes_read_regn(hw, RESP1); resp->resp2 = hermes_read_regn(hw, RESP2); } hermes_write_regn(hw, EVACK, HERMES_EV_CMD); if (status & HERMES_STATUS_RESULT) err = -EIO; out: return err; } static int hermes_allocate(struct hermes *hw, u16 size, u16 *fid) { int err = 0; int k; u16 reg; if ((size < HERMES_ALLOC_LEN_MIN) || (size > HERMES_ALLOC_LEN_MAX)) return -EINVAL; err = hermes_docmd_wait(hw, HERMES_CMD_ALLOC, size, NULL); if (err) return err; reg = hermes_read_regn(hw, EVSTAT); k = ALLOC_COMPL_TIMEOUT; while ((!(reg & HERMES_EV_ALLOC)) && k) { k--; udelay(10); reg = hermes_read_regn(hw, EVSTAT); } if (!hermes_present(hw)) { printk(KERN_WARNING "hermes @ %p: " "Card removed waiting for frame allocation.\n", hw->iobase); return -ENODEV; } if (!(reg & HERMES_EV_ALLOC)) { printk(KERN_ERR "hermes @ %p: " "Timeout waiting for frame allocation\n", hw->iobase); return -ETIMEDOUT; } *fid = hermes_read_regn(hw, ALLOCFID); hermes_write_regn(hw, EVACK, HERMES_EV_ALLOC); return 0; } /* Set up a BAP to read a particular chunk of data from card's internal buffer. * * Returns: * < 0 on internal failure (errno) * 0 on success * > 0 on error * from firmware * * Callable from any context */ static int hermes_bap_seek(struct hermes *hw, int bap, u16 id, u16 offset) { int sreg = bap ? HERMES_SELECT1 : HERMES_SELECT0; int oreg = bap ? HERMES_OFFSET1 : HERMES_OFFSET0; int k; u16 reg; /* Paranoia.. */ if ((offset > HERMES_BAP_OFFSET_MAX) || (offset % 2)) return -EINVAL; k = HERMES_BAP_BUSY_TIMEOUT; reg = hermes_read_reg(hw, oreg); while ((reg & HERMES_OFFSET_BUSY) && k) { k--; udelay(1); reg = hermes_read_reg(hw, oreg); } if (reg & HERMES_OFFSET_BUSY) return -ETIMEDOUT; /* Now we actually set up the transfer */ hermes_write_reg(hw, sreg, id); hermes_write_reg(hw, oreg, offset); /* Wait for the BAP to be ready */ k = HERMES_BAP_BUSY_TIMEOUT; reg = hermes_read_reg(hw, oreg); while ((reg & (HERMES_OFFSET_BUSY | HERMES_OFFSET_ERR)) && k) { k--; udelay(1); reg = hermes_read_reg(hw, oreg); } if (reg != offset) { printk(KERN_ERR "hermes @ %p: BAP%d offset %s: " "reg=0x%x id=0x%x offset=0x%x\n", hw->iobase, bap, (reg & HERMES_OFFSET_BUSY) ? "timeout" : "error", reg, id, offset); if (reg & HERMES_OFFSET_BUSY) return -ETIMEDOUT; return -EIO; /* error or wrong offset */ } return 0; } /* Read a block of data from the chip's buffer, via the * BAP. Synchronization/serialization is the caller's problem. len * must be even. * * Returns: * < 0 on internal failure (errno) * 0 on success * > 0 on error from firmware */ static int hermes_bap_pread(struct hermes *hw, int bap, void *buf, int len, u16 id, u16 offset) { int dreg = bap ? HERMES_DATA1 : HERMES_DATA0; int err = 0; if ((len < 0) || (len % 2)) return -EINVAL; err = hermes_bap_seek(hw, bap, id, offset); if (err) goto out; /* Actually do the transfer */ hermes_read_words(hw, dreg, buf, len / 2); out: return err; } /* Write a block of data to the chip's buffer, via the * BAP. Synchronization/serialization is the caller's problem. * * Returns: * < 0 on internal failure (errno) * 0 on success * > 0 on error from firmware */ static int hermes_bap_pwrite(struct hermes *hw, int bap, const void *buf, int len, u16 id, u16 offset) { int dreg = bap ? HERMES_DATA1 : HERMES_DATA0; int err = 0; if (len < 0) return -EINVAL; err = hermes_bap_seek(hw, bap, id, offset); if (err) goto out; /* Actually do the transfer */ hermes_write_bytes(hw, dreg, buf, len); out: return err; } /* Read a Length-Type-Value record from the card. * * If length is NULL, we ignore the length read from the card, and * read the entire buffer regardless. This is useful because some of * the configuration records appear to have incorrect lengths in * practice. * * Callable from user or bh context. */ static int hermes_read_ltv(struct hermes *hw, int bap, u16 rid, unsigned bufsize, u16 *length, void *buf) { int err = 0; int dreg = bap ? HERMES_DATA1 : HERMES_DATA0; u16 rlength, rtype; unsigned nwords; if (bufsize % 2) return -EINVAL; err = hermes_docmd_wait(hw, HERMES_CMD_ACCESS, rid, NULL); if (err) return err; err = hermes_bap_seek(hw, bap, rid, 0); if (err) return err; rlength = hermes_read_reg(hw, dreg); if (!rlength) return -ENODATA; rtype = hermes_read_reg(hw, dreg); if (length) *length = rlength; if (rtype != rid) printk(KERN_WARNING "hermes @ %p: %s(): " "rid (0x%04x) does not match type (0x%04x)\n", hw->iobase, __func__, rid, rtype); if (HERMES_RECLEN_TO_BYTES(rlength) > bufsize) printk(KERN_WARNING "hermes @ %p: " "Truncating LTV record from %d to %d bytes. " "(rid=0x%04x, len=0x%04x)\n", hw->iobase, HERMES_RECLEN_TO_BYTES(rlength), bufsize, rid, rlength); nwords = min((unsigned)rlength - 1, bufsize / 2); hermes_read_words(hw, dreg, buf, nwords); return 0; } static int hermes_write_ltv(struct hermes *hw, int bap, u16 rid, u16 length, const void *value) { int dreg = bap ? HERMES_DATA1 : HERMES_DATA0; int err = 0; unsigned count; if (length == 0) return -EINVAL; err = hermes_bap_seek(hw, bap, rid, 0); if (err) return err; hermes_write_reg(hw, dreg, length); hermes_write_reg(hw, dreg, rid); count = length - 1; hermes_write_bytes(hw, dreg, value, count << 1); err = hermes_docmd_wait(hw, HERMES_CMD_ACCESS | HERMES_CMD_WRITE, rid, NULL); return err; } /*** Hermes AUX control ***/ static inline void hermes_aux_setaddr(struct hermes *hw, u32 addr) { hermes_write_reg(hw, HERMES_AUXPAGE, (u16) (addr >> 7)); hermes_write_reg(hw, HERMES_AUXOFFSET, (u16) (addr & 0x7F)); } static inline int hermes_aux_control(struct hermes *hw, int enabled) { int desired_state = enabled ? HERMES_AUX_ENABLED : HERMES_AUX_DISABLED; int action = enabled ? HERMES_AUX_ENABLE : HERMES_AUX_DISABLE; int i; /* Already open? */ if (hermes_read_reg(hw, HERMES_CONTROL) == desired_state) return 0; hermes_write_reg(hw, HERMES_PARAM0, HERMES_AUX_PW0); hermes_write_reg(hw, HERMES_PARAM1, HERMES_AUX_PW1); hermes_write_reg(hw, HERMES_PARAM2, HERMES_AUX_PW2); hermes_write_reg(hw, HERMES_CONTROL, action); for (i = 0; i < 20; i++) { udelay(10); if (hermes_read_reg(hw, HERMES_CONTROL) == desired_state) return 0; } return -EBUSY; } /*** Hermes programming ***/ /* About to start programming data (Hermes I) * offset is the entry point * * Spectrum_cs' Symbol fw does not require this * wl_lkm Agere fw does * Don't know about intersil */ static int hermesi_program_init(struct hermes *hw, u32 offset) { int err; /* Disable interrupts?*/ /*hw->inten = 0x0;*/ /*hermes_write_regn(hw, INTEN, 0);*/ /*hermes_set_irqmask(hw, 0);*/ /* Acknowledge any outstanding command */ hermes_write_regn(hw, EVACK, 0xFFFF); /* Using init_cmd_wait rather than cmd_wait */ err = hw->ops->init_cmd_wait(hw, 0x0100 | HERMES_CMD_INIT, 0, 0, 0, NULL); if (err) return err; err = hw->ops->init_cmd_wait(hw, 0x0000 | HERMES_CMD_INIT, 0, 0, 0, NULL); if (err) return err; err = hermes_aux_control(hw, 1); pr_debug("AUX enable returned %d\n", err); if (err) return err; pr_debug("Enabling volatile, EP 0x%08x\n", offset); err = hw->ops->init_cmd_wait(hw, HERMES_PROGRAM_ENABLE_VOLATILE, offset & 0xFFFFu, offset >> 16, 0, NULL); pr_debug("PROGRAM_ENABLE returned %d\n", err); return err; } /* Done programming data (Hermes I) * * Spectrum_cs' Symbol fw does not require this * wl_lkm Agere fw does * Don't know about intersil */ static int hermesi_program_end(struct hermes *hw) { struct hermes_response resp; int rc = 0; int err; rc = hw->ops->cmd_wait(hw, HERMES_PROGRAM_DISABLE, 0, &resp); pr_debug("PROGRAM_DISABLE returned %d, " "r0 0x%04x, r1 0x%04x, r2 0x%04x\n", rc, resp.resp0, resp.resp1, resp.resp2); if ((rc == 0) && ((resp.status & HERMES_STATUS_CMDCODE) != HERMES_CMD_DOWNLD)) rc = -EIO; err = hermes_aux_control(hw, 0); pr_debug("AUX disable returned %d\n", err); /* Acknowledge any outstanding command */ hermes_write_regn(hw, EVACK, 0xFFFF); /* Reinitialise, ignoring return */ (void) hw->ops->init_cmd_wait(hw, 0x0000 | HERMES_CMD_INIT, 0, 0, 0, NULL); return rc ? rc : err; } static int hermes_program_bytes(struct hermes *hw, const char *data, u32 addr, u32 len) { /* wl lkm splits the programming into chunks of 2000 bytes. * This restriction appears to come from USB. The PCMCIA * adapters can program the whole lot in one go */ hermes_aux_setaddr(hw, addr); hermes_write_bytes(hw, HERMES_AUXDATA, data, len); return 0; } /* Read PDA from the adapter */ static int hermes_read_pda(struct hermes *hw, __le16 *pda, u32 pda_addr, u16 pda_len) { int ret; u16 pda_size; u16 data_len = pda_len; __le16 *data = pda; if (hw->eeprom_pda) { /* PDA of spectrum symbol is in eeprom */ /* Issue command to read EEPROM */ ret = hw->ops->cmd_wait(hw, HERMES_CMD_READMIF, 0, NULL); if (ret) return ret; } else { /* wl_lkm does not include PDA size in the PDA area. * We will pad the information into pda, so other routines * don't have to be modified */ pda[0] = cpu_to_le16(pda_len - 2); /* Includes CFG_PROD_DATA but not itself */ pda[1] = cpu_to_le16(0x0800); /* CFG_PROD_DATA */ data_len = pda_len - 4; data = pda + 2; } /* Open auxiliary port */ ret = hermes_aux_control(hw, 1); pr_debug("AUX enable returned %d\n", ret); if (ret) return ret; /* Read PDA */ hermes_aux_setaddr(hw, pda_addr); hermes_read_words(hw, HERMES_AUXDATA, data, data_len / 2); /* Close aux port */ ret = hermes_aux_control(hw, 0); pr_debug("AUX disable returned %d\n", ret); /* Check PDA length */ pda_size = le16_to_cpu(pda[0]); pr_debug("Actual PDA length %d, Max allowed %d\n", pda_size, pda_len); if (pda_size > pda_len) return -EINVAL; return 0; } static void hermes_lock_irqsave(spinlock_t *lock, unsigned long *flags) __acquires(lock) { spin_lock_irqsave(lock, *flags); } static void hermes_unlock_irqrestore(spinlock_t *lock, unsigned long *flags) __releases(lock) { spin_unlock_irqrestore(lock, *flags); } static void hermes_lock_irq(spinlock_t *lock) __acquires(lock) { spin_lock_irq(lock); } static void hermes_unlock_irq(spinlock_t *lock) __releases(lock) { spin_unlock_irq(lock); } /* Hermes operations for local buses */ static const struct hermes_ops hermes_ops_local = { .init = hermes_init, .cmd_wait = hermes_docmd_wait, .init_cmd_wait = hermes_doicmd_wait, .allocate = hermes_allocate, .read_ltv = hermes_read_ltv, .write_ltv = hermes_write_ltv, .bap_pread = hermes_bap_pread, .bap_pwrite = hermes_bap_pwrite, .read_pda = hermes_read_pda, .program_init = hermesi_program_init, .program_end = hermesi_program_end, .program = hermes_program_bytes, .lock_irqsave = hermes_lock_irqsave, .unlock_irqrestore = hermes_unlock_irqrestore, .lock_irq = hermes_lock_irq, .unlock_irq = hermes_unlock_irq, };
gpl-2.0
cattleprod/XCeLL-V69-2
arch/mips/oprofile/op_model_mipsxx.c
9177
8933
/* * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (C) 2004, 05, 06 by Ralf Baechle * Copyright (C) 2005 by MIPS Technologies, Inc. */ #include <linux/cpumask.h> #include <linux/oprofile.h> #include <linux/interrupt.h> #include <linux/smp.h> #include <asm/irq_regs.h> #include "op_impl.h" #define M_PERFCTL_EXL (1UL << 0) #define M_PERFCTL_KERNEL (1UL << 1) #define M_PERFCTL_SUPERVISOR (1UL << 2) #define M_PERFCTL_USER (1UL << 3) #define M_PERFCTL_INTERRUPT_ENABLE (1UL << 4) #define M_PERFCTL_EVENT(event) (((event) & 0x3ff) << 5) #define M_PERFCTL_VPEID(vpe) ((vpe) << 16) #define M_PERFCTL_MT_EN(filter) ((filter) << 20) #define M_TC_EN_ALL M_PERFCTL_MT_EN(0) #define M_TC_EN_VPE M_PERFCTL_MT_EN(1) #define M_TC_EN_TC M_PERFCTL_MT_EN(2) #define M_PERFCTL_TCID(tcid) ((tcid) << 22) #define M_PERFCTL_WIDE (1UL << 30) #define M_PERFCTL_MORE (1UL << 31) #define M_COUNTER_OVERFLOW (1UL << 31) static int (*save_perf_irq)(void); #ifdef CONFIG_MIPS_MT_SMP static int cpu_has_mipsmt_pertccounters; #define WHAT (M_TC_EN_VPE | \ M_PERFCTL_VPEID(cpu_data[smp_processor_id()].vpe_id)) #define vpe_id() (cpu_has_mipsmt_pertccounters ? \ 0 : cpu_data[smp_processor_id()].vpe_id) /* * The number of bits to shift to convert between counters per core and * counters per VPE. There is no reasonable interface atm to obtain the * number of VPEs used by Linux and in the 34K this number is fixed to two * anyways so we hardcore a few things here for the moment. The way it's * done here will ensure that oprofile VSMP kernel will run right on a lesser * core like a 24K also or with maxcpus=1. */ static inline unsigned int vpe_shift(void) { if (num_possible_cpus() > 1) return 1; return 0; } #else #define WHAT 0 #define vpe_id() 0 static inline unsigned int vpe_shift(void) { return 0; } #endif static inline unsigned int counters_total_to_per_cpu(unsigned int counters) { return counters >> vpe_shift(); } static inline unsigned int counters_per_cpu_to_total(unsigned int counters) { return counters << vpe_shift(); } #define __define_perf_accessors(r, n, np) \ \ static inline unsigned int r_c0_ ## r ## n(void) \ { \ unsigned int cpu = vpe_id(); \ \ switch (cpu) { \ case 0: \ return read_c0_ ## r ## n(); \ case 1: \ return read_c0_ ## r ## np(); \ default: \ BUG(); \ } \ return 0; \ } \ \ static inline void w_c0_ ## r ## n(unsigned int value) \ { \ unsigned int cpu = vpe_id(); \ \ switch (cpu) { \ case 0: \ write_c0_ ## r ## n(value); \ return; \ case 1: \ write_c0_ ## r ## np(value); \ return; \ default: \ BUG(); \ } \ return; \ } \ __define_perf_accessors(perfcntr, 0, 2) __define_perf_accessors(perfcntr, 1, 3) __define_perf_accessors(perfcntr, 2, 0) __define_perf_accessors(perfcntr, 3, 1) __define_perf_accessors(perfctrl, 0, 2) __define_perf_accessors(perfctrl, 1, 3) __define_perf_accessors(perfctrl, 2, 0) __define_perf_accessors(perfctrl, 3, 1) struct op_mips_model op_model_mipsxx_ops; static struct mipsxx_register_config { unsigned int control[4]; unsigned int counter[4]; } reg; /* Compute all of the registers in preparation for enabling profiling. */ static void mipsxx_reg_setup(struct op_counter_config *ctr) { unsigned int counters = op_model_mipsxx_ops.num_counters; int i; /* Compute the performance counter control word. */ for (i = 0; i < counters; i++) { reg.control[i] = 0; reg.counter[i] = 0; if (!ctr[i].enabled) continue; reg.control[i] = M_PERFCTL_EVENT(ctr[i].event) | M_PERFCTL_INTERRUPT_ENABLE; if (ctr[i].kernel) reg.control[i] |= M_PERFCTL_KERNEL; if (ctr[i].user) reg.control[i] |= M_PERFCTL_USER; if (ctr[i].exl) reg.control[i] |= M_PERFCTL_EXL; reg.counter[i] = 0x80000000 - ctr[i].count; } } /* Program all of the registers in preparation for enabling profiling. */ static void mipsxx_cpu_setup(void *args) { unsigned int counters = op_model_mipsxx_ops.num_counters; switch (counters) { case 4: w_c0_perfctrl3(0); w_c0_perfcntr3(reg.counter[3]); case 3: w_c0_perfctrl2(0); w_c0_perfcntr2(reg.counter[2]); case 2: w_c0_perfctrl1(0); w_c0_perfcntr1(reg.counter[1]); case 1: w_c0_perfctrl0(0); w_c0_perfcntr0(reg.counter[0]); } } /* Start all counters on current CPU */ static void mipsxx_cpu_start(void *args) { unsigned int counters = op_model_mipsxx_ops.num_counters; switch (counters) { case 4: w_c0_perfctrl3(WHAT | reg.control[3]); case 3: w_c0_perfctrl2(WHAT | reg.control[2]); case 2: w_c0_perfctrl1(WHAT | reg.control[1]); case 1: w_c0_perfctrl0(WHAT | reg.control[0]); } } /* Stop all counters on current CPU */ static void mipsxx_cpu_stop(void *args) { unsigned int counters = op_model_mipsxx_ops.num_counters; switch (counters) { case 4: w_c0_perfctrl3(0); case 3: w_c0_perfctrl2(0); case 2: w_c0_perfctrl1(0); case 1: w_c0_perfctrl0(0); } } static int mipsxx_perfcount_handler(void) { unsigned int counters = op_model_mipsxx_ops.num_counters; unsigned int control; unsigned int counter; int handled = IRQ_NONE; if (cpu_has_mips_r2 && !(read_c0_cause() & (1 << 26))) return handled; switch (counters) { #define HANDLE_COUNTER(n) \ case n + 1: \ control = r_c0_perfctrl ## n(); \ counter = r_c0_perfcntr ## n(); \ if ((control & M_PERFCTL_INTERRUPT_ENABLE) && \ (counter & M_COUNTER_OVERFLOW)) { \ oprofile_add_sample(get_irq_regs(), n); \ w_c0_perfcntr ## n(reg.counter[n]); \ handled = IRQ_HANDLED; \ } HANDLE_COUNTER(3) HANDLE_COUNTER(2) HANDLE_COUNTER(1) HANDLE_COUNTER(0) } return handled; } #define M_CONFIG1_PC (1 << 4) static inline int __n_counters(void) { if (!(read_c0_config1() & M_CONFIG1_PC)) return 0; if (!(read_c0_perfctrl0() & M_PERFCTL_MORE)) return 1; if (!(read_c0_perfctrl1() & M_PERFCTL_MORE)) return 2; if (!(read_c0_perfctrl2() & M_PERFCTL_MORE)) return 3; return 4; } static inline int n_counters(void) { int counters; switch (current_cpu_type()) { case CPU_R10000: counters = 2; break; case CPU_R12000: case CPU_R14000: counters = 4; break; default: counters = __n_counters(); } return counters; } static void reset_counters(void *arg) { int counters = (int)(long)arg; switch (counters) { case 4: w_c0_perfctrl3(0); w_c0_perfcntr3(0); case 3: w_c0_perfctrl2(0); w_c0_perfcntr2(0); case 2: w_c0_perfctrl1(0); w_c0_perfcntr1(0); case 1: w_c0_perfctrl0(0); w_c0_perfcntr0(0); } } static int __init mipsxx_init(void) { int counters; counters = n_counters(); if (counters == 0) { printk(KERN_ERR "Oprofile: CPU has no performance counters\n"); return -ENODEV; } #ifdef CONFIG_MIPS_MT_SMP cpu_has_mipsmt_pertccounters = read_c0_config7() & (1<<19); if (!cpu_has_mipsmt_pertccounters) counters = counters_total_to_per_cpu(counters); #endif on_each_cpu(reset_counters, (void *)(long)counters, 1); op_model_mipsxx_ops.num_counters = counters; switch (current_cpu_type()) { case CPU_20KC: op_model_mipsxx_ops.cpu_type = "mips/20K"; break; case CPU_24K: op_model_mipsxx_ops.cpu_type = "mips/24K"; break; case CPU_25KF: op_model_mipsxx_ops.cpu_type = "mips/25K"; break; case CPU_1004K: #if 0 /* FIXME: report as 34K for now */ op_model_mipsxx_ops.cpu_type = "mips/1004K"; break; #endif case CPU_34K: op_model_mipsxx_ops.cpu_type = "mips/34K"; break; case CPU_74K: op_model_mipsxx_ops.cpu_type = "mips/74K"; break; case CPU_5KC: op_model_mipsxx_ops.cpu_type = "mips/5K"; break; case CPU_R10000: if ((current_cpu_data.processor_id & 0xff) == 0x20) op_model_mipsxx_ops.cpu_type = "mips/r10000-v2.x"; else op_model_mipsxx_ops.cpu_type = "mips/r10000"; break; case CPU_R12000: case CPU_R14000: op_model_mipsxx_ops.cpu_type = "mips/r12000"; break; case CPU_SB1: case CPU_SB1A: op_model_mipsxx_ops.cpu_type = "mips/sb1"; break; default: printk(KERN_ERR "Profiling unsupported for this CPU\n"); return -ENODEV; } save_perf_irq = perf_irq; perf_irq = mipsxx_perfcount_handler; return 0; } static void mipsxx_exit(void) { int counters = op_model_mipsxx_ops.num_counters; counters = counters_per_cpu_to_total(counters); on_each_cpu(reset_counters, (void *)(long)counters, 1); perf_irq = save_perf_irq; } struct op_mips_model op_model_mipsxx_ops = { .reg_setup = mipsxx_reg_setup, .cpu_setup = mipsxx_cpu_setup, .init = mipsxx_init, .exit = mipsxx_exit, .cpu_start = mipsxx_cpu_start, .cpu_stop = mipsxx_cpu_stop, };
gpl-2.0
mikalv/android_kernel_samsung_degas3g
arch/avr32/mach-at32ap/pm.c
9945
5664
/* * AVR32 AP Power Management * * Copyright (C) 2008 Atmel Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. */ #include <linux/io.h> #include <linux/suspend.h> #include <linux/vmalloc.h> #include <asm/cacheflush.h> #include <asm/sysreg.h> #include <mach/chip.h> #include <mach/pm.h> #include <mach/sram.h> #include "sdramc.h" #define SRAM_PAGE_FLAGS (SYSREG_BIT(TLBELO_D) | SYSREG_BF(SZ, 1) \ | SYSREG_BF(AP, 3) | SYSREG_BIT(G)) static unsigned long pm_sram_start; static size_t pm_sram_size; static struct vm_struct *pm_sram_area; static void (*avr32_pm_enter_standby)(unsigned long sdramc_base); static void (*avr32_pm_enter_str)(unsigned long sdramc_base); /* * Must be called with interrupts disabled. Exceptions will be masked * on return (i.e. all exceptions will be "unrecoverable".) */ static void *avr32_pm_map_sram(void) { unsigned long vaddr; unsigned long page_addr; u32 tlbehi; u32 mmucr; vaddr = (unsigned long)pm_sram_area->addr; page_addr = pm_sram_start & PAGE_MASK; /* * Mask exceptions and grab the first TLB entry. We won't be * needing it while sleeping. */ asm volatile("ssrf %0" : : "i"(SYSREG_EM_OFFSET) : "memory"); mmucr = sysreg_read(MMUCR); tlbehi = sysreg_read(TLBEHI); sysreg_write(MMUCR, SYSREG_BFINS(DRP, 0, mmucr)); tlbehi = SYSREG_BF(ASID, SYSREG_BFEXT(ASID, tlbehi)); tlbehi |= vaddr & PAGE_MASK; tlbehi |= SYSREG_BIT(TLBEHI_V); sysreg_write(TLBELO, page_addr | SRAM_PAGE_FLAGS); sysreg_write(TLBEHI, tlbehi); __builtin_tlbw(); return (void *)(vaddr + pm_sram_start - page_addr); } /* * Must be called with interrupts disabled. Exceptions will be * unmasked on return. */ static void avr32_pm_unmap_sram(void) { u32 mmucr; u32 tlbehi; u32 tlbarlo; /* Going to update TLB entry at index 0 */ mmucr = sysreg_read(MMUCR); tlbehi = sysreg_read(TLBEHI); sysreg_write(MMUCR, SYSREG_BFINS(DRP, 0, mmucr)); /* Clear the "valid" bit */ tlbehi = SYSREG_BF(ASID, SYSREG_BFEXT(ASID, tlbehi)); sysreg_write(TLBEHI, tlbehi); /* Mark it as "not accessed" */ tlbarlo = sysreg_read(TLBARLO); sysreg_write(TLBARLO, tlbarlo | 0x80000000U); /* Update the TLB */ __builtin_tlbw(); /* Unmask exceptions */ asm volatile("csrf %0" : : "i"(SYSREG_EM_OFFSET) : "memory"); } static int avr32_pm_valid_state(suspend_state_t state) { switch (state) { case PM_SUSPEND_ON: case PM_SUSPEND_STANDBY: case PM_SUSPEND_MEM: return 1; default: return 0; } } static int avr32_pm_enter(suspend_state_t state) { u32 lpr_saved; u32 evba_saved; void *sram; switch (state) { case PM_SUSPEND_STANDBY: sram = avr32_pm_map_sram(); /* Switch to in-sram exception handlers */ evba_saved = sysreg_read(EVBA); sysreg_write(EVBA, (unsigned long)sram); /* * Save the LPR register so that we can re-enable * SDRAM Low Power mode on resume. */ lpr_saved = sdramc_readl(LPR); pr_debug("%s: Entering standby...\n", __func__); avr32_pm_enter_standby(SDRAMC_BASE); sdramc_writel(LPR, lpr_saved); /* Switch back to regular exception handlers */ sysreg_write(EVBA, evba_saved); avr32_pm_unmap_sram(); break; case PM_SUSPEND_MEM: sram = avr32_pm_map_sram(); /* Switch to in-sram exception handlers */ evba_saved = sysreg_read(EVBA); sysreg_write(EVBA, (unsigned long)sram); /* * Save the LPR register so that we can re-enable * SDRAM Low Power mode on resume. */ lpr_saved = sdramc_readl(LPR); pr_debug("%s: Entering suspend-to-ram...\n", __func__); avr32_pm_enter_str(SDRAMC_BASE); sdramc_writel(LPR, lpr_saved); /* Switch back to regular exception handlers */ sysreg_write(EVBA, evba_saved); avr32_pm_unmap_sram(); break; case PM_SUSPEND_ON: pr_debug("%s: Entering idle...\n", __func__); cpu_enter_idle(); break; default: pr_debug("%s: Invalid suspend state %d\n", __func__, state); goto out; } pr_debug("%s: wakeup\n", __func__); out: return 0; } static const struct platform_suspend_ops avr32_pm_ops = { .valid = avr32_pm_valid_state, .enter = avr32_pm_enter, }; static unsigned long avr32_pm_offset(void *symbol) { extern u8 pm_exception[]; return (unsigned long)symbol - (unsigned long)pm_exception; } static int __init avr32_pm_init(void) { extern u8 pm_exception[]; extern u8 pm_irq0[]; extern u8 pm_standby[]; extern u8 pm_suspend_to_ram[]; extern u8 pm_sram_end[]; void *dst; /* * To keep things simple, we depend on not needing more than a * single page. */ pm_sram_size = avr32_pm_offset(pm_sram_end); if (pm_sram_size > PAGE_SIZE) goto err; pm_sram_start = sram_alloc(pm_sram_size); if (!pm_sram_start) goto err_alloc_sram; /* Grab a virtual area we can use later on. */ pm_sram_area = get_vm_area(pm_sram_size, VM_IOREMAP); if (!pm_sram_area) goto err_vm_area; pm_sram_area->phys_addr = pm_sram_start; local_irq_disable(); dst = avr32_pm_map_sram(); memcpy(dst, pm_exception, pm_sram_size); flush_dcache_region(dst, pm_sram_size); invalidate_icache_region(dst, pm_sram_size); avr32_pm_unmap_sram(); local_irq_enable(); avr32_pm_enter_standby = dst + avr32_pm_offset(pm_standby); avr32_pm_enter_str = dst + avr32_pm_offset(pm_suspend_to_ram); intc_set_suspend_handler(avr32_pm_offset(pm_irq0)); suspend_set_ops(&avr32_pm_ops); printk("AVR32 AP Power Management enabled\n"); return 0; err_vm_area: sram_free(pm_sram_start, pm_sram_size); err_alloc_sram: err: pr_err("AVR32 Power Management initialization failed\n"); return -ENOMEM; } arch_initcall(avr32_pm_init);
gpl-2.0
CrawX/linux-fslc
arch/frv/mm/extable.c
12249
2443
/* * linux/arch/frv/mm/extable.c */ #include <linux/module.h> #include <linux/spinlock.h> #include <asm/uaccess.h> extern const struct exception_table_entry __attribute__((aligned(8))) __start___ex_table[]; extern const struct exception_table_entry __attribute__((aligned(8))) __stop___ex_table[]; extern const void __memset_end, __memset_user_error_lr, __memset_user_error_handler; extern const void __memcpy_end, __memcpy_user_error_lr, __memcpy_user_error_handler; extern spinlock_t modlist_lock; /*****************************************************************************/ /* * */ static inline unsigned long search_one_table(const struct exception_table_entry *first, const struct exception_table_entry *last, unsigned long value) { while (first <= last) { const struct exception_table_entry __attribute__((aligned(8))) *mid; long diff; mid = (last - first) / 2 + first; diff = mid->insn - value; if (diff == 0) return mid->fixup; else if (diff < 0) first = mid + 1; else last = mid - 1; } return 0; } /* end search_one_table() */ /*****************************************************************************/ /* * see if there's a fixup handler available to deal with a kernel fault */ unsigned long search_exception_table(unsigned long pc) { const struct exception_table_entry *extab; /* determine if the fault lay during a memcpy_user or a memset_user */ if (__frame->lr == (unsigned long) &__memset_user_error_lr && (unsigned long) &memset <= pc && pc < (unsigned long) &__memset_end ) { /* the fault occurred in a protected memset * - we search for the return address (in LR) instead of the program counter * - it was probably during a clear_user() */ return (unsigned long) &__memset_user_error_handler; } if (__frame->lr == (unsigned long) &__memcpy_user_error_lr && (unsigned long) &memcpy <= pc && pc < (unsigned long) &__memcpy_end ) { /* the fault occurred in a protected memset * - we search for the return address (in LR) instead of the program counter * - it was probably during a copy_to/from_user() */ return (unsigned long) &__memcpy_user_error_handler; } extab = search_exception_tables(pc); if (extab) return extab->fixup; return 0; } /* end search_exception_table() */
gpl-2.0
cooldroid/android_kernel_oneplus_msm8974
arch/avr32/kernel/ocd.c
13785
3885
/* * Copyright (C) 2007 Atmel Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/init.h> #include <linux/sched.h> #include <linux/spinlock.h> #include <asm/ocd.h> static long ocd_count; static spinlock_t ocd_lock; /** * ocd_enable - enable on-chip debugging * @child: task to be debugged * * If @child is non-NULL, ocd_enable() first checks if debugging has * already been enabled for @child, and if it has, does nothing. * * If @child is NULL (e.g. when debugging the kernel), or debugging * has not already been enabled for it, ocd_enable() increments the * reference count and enables the debugging hardware. */ void ocd_enable(struct task_struct *child) { u32 dc; if (child) pr_debug("ocd_enable: child=%s [%u]\n", child->comm, child->pid); else pr_debug("ocd_enable (no child)\n"); if (!child || !test_and_set_tsk_thread_flag(child, TIF_DEBUG)) { spin_lock(&ocd_lock); ocd_count++; dc = ocd_read(DC); dc |= (1 << OCD_DC_MM_BIT) | (1 << OCD_DC_DBE_BIT); ocd_write(DC, dc); spin_unlock(&ocd_lock); } } /** * ocd_disable - disable on-chip debugging * @child: task that was being debugged, but isn't anymore * * If @child is non-NULL, ocd_disable() checks if debugging is enabled * for @child, and if it isn't, does nothing. * * If @child is NULL (e.g. when debugging the kernel), or debugging is * enabled, ocd_disable() decrements the reference count, and if it * reaches zero, disables the debugging hardware. */ void ocd_disable(struct task_struct *child) { u32 dc; if (!child) pr_debug("ocd_disable (no child)\n"); else if (test_tsk_thread_flag(child, TIF_DEBUG)) pr_debug("ocd_disable: child=%s [%u]\n", child->comm, child->pid); if (!child || test_and_clear_tsk_thread_flag(child, TIF_DEBUG)) { spin_lock(&ocd_lock); ocd_count--; WARN_ON(ocd_count < 0); if (ocd_count <= 0) { dc = ocd_read(DC); dc &= ~((1 << OCD_DC_MM_BIT) | (1 << OCD_DC_DBE_BIT)); ocd_write(DC, dc); } spin_unlock(&ocd_lock); } } #ifdef CONFIG_DEBUG_FS #include <linux/debugfs.h> #include <linux/module.h> static struct dentry *ocd_debugfs_root; static struct dentry *ocd_debugfs_DC; static struct dentry *ocd_debugfs_DS; static struct dentry *ocd_debugfs_count; static int ocd_DC_get(void *data, u64 *val) { *val = ocd_read(DC); return 0; } static int ocd_DC_set(void *data, u64 val) { ocd_write(DC, val); return 0; } DEFINE_SIMPLE_ATTRIBUTE(fops_DC, ocd_DC_get, ocd_DC_set, "0x%08llx\n"); static int ocd_DS_get(void *data, u64 *val) { *val = ocd_read(DS); return 0; } DEFINE_SIMPLE_ATTRIBUTE(fops_DS, ocd_DS_get, NULL, "0x%08llx\n"); static int ocd_count_get(void *data, u64 *val) { *val = ocd_count; return 0; } DEFINE_SIMPLE_ATTRIBUTE(fops_count, ocd_count_get, NULL, "%lld\n"); static void ocd_debugfs_init(void) { struct dentry *root; root = debugfs_create_dir("ocd", NULL); if (IS_ERR(root) || !root) goto err_root; ocd_debugfs_root = root; ocd_debugfs_DC = debugfs_create_file("DC", S_IRUSR | S_IWUSR, root, NULL, &fops_DC); if (!ocd_debugfs_DC) goto err_DC; ocd_debugfs_DS = debugfs_create_file("DS", S_IRUSR, root, NULL, &fops_DS); if (!ocd_debugfs_DS) goto err_DS; ocd_debugfs_count = debugfs_create_file("count", S_IRUSR, root, NULL, &fops_count); if (!ocd_debugfs_count) goto err_count; return; err_count: debugfs_remove(ocd_debugfs_DS); err_DS: debugfs_remove(ocd_debugfs_DC); err_DC: debugfs_remove(ocd_debugfs_root); err_root: printk(KERN_WARNING "OCD: Failed to create debugfs entries\n"); } #else static inline void ocd_debugfs_init(void) { } #endif static int __init ocd_init(void) { spin_lock_init(&ocd_lock); ocd_debugfs_init(); return 0; } arch_initcall(ocd_init);
gpl-2.0
sky7sea/linux
drivers/staging/rtl8712/ieee80211.c
218
11410
/****************************************************************************** * ieee80211.c * * Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved. * Linux device driver for RTL8192SU * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * Modifications for inclusion into the Linux staging tree are * Copyright(c) 2010 Larry Finger. All rights reserved. * * Contact information: * WLAN FAE <wlanfae@realtek.com>. * Larry Finger <Larry.Finger@lwfinger.net> * ******************************************************************************/ #define _IEEE80211_C #include "drv_types.h" #include "ieee80211.h" #include "wifi.h" #include "osdep_service.h" #include "wlan_bssdef.h" static const u8 WPA_OUI_TYPE[] = {0x00, 0x50, 0xf2, 1}; static const u8 WPA_CIPHER_SUITE_NONE[] = {0x00, 0x50, 0xf2, 0}; static const u8 WPA_CIPHER_SUITE_WEP40[] = {0x00, 0x50, 0xf2, 1}; static const u8 WPA_CIPHER_SUITE_TKIP[] = {0x00, 0x50, 0xf2, 2}; static const u8 WPA_CIPHER_SUITE_CCMP[] = {0x00, 0x50, 0xf2, 4}; static const u8 WPA_CIPHER_SUITE_WEP104[] = {0x00, 0x50, 0xf2, 5}; static const u8 RSN_CIPHER_SUITE_NONE[] = {0x00, 0x0f, 0xac, 0}; static const u8 RSN_CIPHER_SUITE_WEP40[] = {0x00, 0x0f, 0xac, 1}; static const u8 RSN_CIPHER_SUITE_TKIP[] = {0x00, 0x0f, 0xac, 2}; static const u8 RSN_CIPHER_SUITE_CCMP[] = {0x00, 0x0f, 0xac, 4}; static const u8 RSN_CIPHER_SUITE_WEP104[] = {0x00, 0x0f, 0xac, 5}; /*----------------------------------------------------------- * for adhoc-master to generate ie and provide supported-rate to fw *----------------------------------------------------------- */ static u8 WIFI_CCKRATES[] = { (IEEE80211_CCK_RATE_1MB | IEEE80211_BASIC_RATE_MASK), (IEEE80211_CCK_RATE_2MB | IEEE80211_BASIC_RATE_MASK), (IEEE80211_CCK_RATE_5MB | IEEE80211_BASIC_RATE_MASK), (IEEE80211_CCK_RATE_11MB | IEEE80211_BASIC_RATE_MASK) }; static u8 WIFI_OFDMRATES[] = { (IEEE80211_OFDM_RATE_6MB), (IEEE80211_OFDM_RATE_9MB), (IEEE80211_OFDM_RATE_12MB), (IEEE80211_OFDM_RATE_18MB), (IEEE80211_OFDM_RATE_24MB), (IEEE80211_OFDM_RATE_36MB), (IEEE80211_OFDM_RATE_48MB), (IEEE80211_OFDM_RATE_54MB) }; uint r8712_is_cckrates_included(u8 *rate) { u32 i = 0; while (rate[i] != 0) { if ((((rate[i]) & 0x7f) == 2) || (((rate[i]) & 0x7f) == 4) || (((rate[i]) & 0x7f) == 11) || (((rate[i]) & 0x7f) == 22)) return true; i++; } return false; } uint r8712_is_cckratesonly_included(u8 *rate) { u32 i = 0; while (rate[i] != 0) { if ((((rate[i]) & 0x7f) != 2) && (((rate[i]) & 0x7f) != 4) && (((rate[i]) & 0x7f) != 11) && (((rate[i]) & 0x7f) != 22)) return false; i++; } return true; } /* r8712_set_ie will update frame length */ u8 *r8712_set_ie(u8 *pbuf, sint index, uint len, u8 *source, uint *frlen) { *pbuf = (u8)index; *(pbuf + 1) = (u8)len; if (len > 0) memcpy((void *)(pbuf + 2), (void *)source, len); *frlen = *frlen + (len + 2); return pbuf + len + 2; } /*---------------------------------------------------------------------------- index: the information element id index, limit is the limit for search -----------------------------------------------------------------------------*/ u8 *r8712_get_ie(u8 *pbuf, sint index, sint *len, sint limit) { sint tmp, i; u8 *p; if (limit < 1) return NULL; p = pbuf; i = 0; *len = 0; while (1) { if (*p == index) { *len = *(p + 1); return p; } tmp = *(p + 1); p += (tmp + 2); i += (tmp + 2); if (i >= limit) break; } return NULL; } static void set_supported_rate(u8 *rates, uint mode) { memset(rates, 0, NDIS_802_11_LENGTH_RATES_EX); switch (mode) { case WIRELESS_11B: memcpy(rates, WIFI_CCKRATES, IEEE80211_CCK_RATE_LEN); break; case WIRELESS_11G: case WIRELESS_11A: memcpy(rates, WIFI_OFDMRATES, IEEE80211_NUM_OFDM_RATESLEN); break; case WIRELESS_11BG: memcpy(rates, WIFI_CCKRATES, IEEE80211_CCK_RATE_LEN); memcpy(rates + IEEE80211_CCK_RATE_LEN, WIFI_OFDMRATES, IEEE80211_NUM_OFDM_RATESLEN); break; } } static uint r8712_get_rateset_len(u8 *rateset) { uint i = 0; while (1) { if ((rateset[i]) == 0) break; if (i > 12) break; i++; } return i; } int r8712_generate_ie(struct registry_priv *pregistrypriv) { int sz = 0, rateLen; struct wlan_bssid_ex *pdev_network = &pregistrypriv->dev_network; u8 *ie = pdev_network->IEs; /*timestamp will be inserted by hardware*/ sz += 8; ie += sz; /*beacon interval : 2bytes*/ *(u16 *)ie = cpu_to_le16((u16)pdev_network->Configuration.BeaconPeriod); sz += 2; ie += 2; /*capability info*/ *(u16 *)ie = 0; *(u16 *)ie |= cpu_to_le16(cap_IBSS); if (pregistrypriv->preamble == PREAMBLE_SHORT) *(u16 *)ie |= cpu_to_le16(cap_ShortPremble); if (pdev_network->Privacy) *(u16 *)ie |= cpu_to_le16(cap_Privacy); sz += 2; ie += 2; /*SSID*/ ie = r8712_set_ie(ie, _SSID_IE_, pdev_network->Ssid.SsidLength, pdev_network->Ssid.Ssid, &sz); /*supported rates*/ set_supported_rate(pdev_network->rates, pregistrypriv->wireless_mode); rateLen = r8712_get_rateset_len(pdev_network->rates); if (rateLen > 8) { ie = r8712_set_ie(ie, _SUPPORTEDRATES_IE_, 8, pdev_network->rates, &sz); ie = r8712_set_ie(ie, _EXT_SUPPORTEDRATES_IE_, (rateLen - 8), (pdev_network->rates + 8), &sz); } else ie = r8712_set_ie(ie, _SUPPORTEDRATES_IE_, rateLen, pdev_network->rates, &sz); /*DS parameter set*/ ie = r8712_set_ie(ie, _DSSET_IE_, 1, (u8 *)&(pdev_network->Configuration.DSConfig), &sz); /*IBSS Parameter Set*/ ie = r8712_set_ie(ie, _IBSS_PARA_IE_, 2, (u8 *)&(pdev_network->Configuration.ATIMWindow), &sz); return sz; } unsigned char *r8712_get_wpa_ie(unsigned char *pie, int *wpa_ie_len, int limit) { int len; u16 val16; unsigned char wpa_oui_type[] = {0x00, 0x50, 0xf2, 0x01}; u8 *pbuf = pie; while (1) { pbuf = r8712_get_ie(pbuf, _WPA_IE_ID_, &len, limit); if (pbuf) { /*check if oui matches...*/ if (memcmp((pbuf + 2), wpa_oui_type, sizeof(wpa_oui_type))) goto check_next_ie; /*check version...*/ memcpy((u8 *)&val16, (pbuf + 6), sizeof(val16)); val16 = le16_to_cpu(val16); if (val16 != 0x0001) goto check_next_ie; *wpa_ie_len = *(pbuf + 1); return pbuf; } *wpa_ie_len = 0; return NULL; check_next_ie: limit = limit - (pbuf - pie) - 2 - len; if (limit <= 0) break; pbuf += (2 + len); } *wpa_ie_len = 0; return NULL; } unsigned char *r8712_get_wpa2_ie(unsigned char *pie, int *rsn_ie_len, int limit) { return r8712_get_ie(pie, _WPA2_IE_ID_, rsn_ie_len, limit); } static int r8712_get_wpa_cipher_suite(u8 *s) { if (!memcmp(s, (void *)WPA_CIPHER_SUITE_NONE, WPA_SELECTOR_LEN)) return WPA_CIPHER_NONE; if (!memcmp(s, (void *)WPA_CIPHER_SUITE_WEP40, WPA_SELECTOR_LEN)) return WPA_CIPHER_WEP40; if (!memcmp(s, (void *)WPA_CIPHER_SUITE_TKIP, WPA_SELECTOR_LEN)) return WPA_CIPHER_TKIP; if (!memcmp(s, (void *)WPA_CIPHER_SUITE_CCMP, WPA_SELECTOR_LEN)) return WPA_CIPHER_CCMP; if (!memcmp(s, (void *)WPA_CIPHER_SUITE_WEP104, WPA_SELECTOR_LEN)) return WPA_CIPHER_WEP104; return 0; } static int r8712_get_wpa2_cipher_suite(u8 *s) { if (!memcmp(s, (void *)RSN_CIPHER_SUITE_NONE, RSN_SELECTOR_LEN)) return WPA_CIPHER_NONE; if (!memcmp(s, (void *)RSN_CIPHER_SUITE_WEP40, RSN_SELECTOR_LEN)) return WPA_CIPHER_WEP40; if (!memcmp(s, (void *)RSN_CIPHER_SUITE_TKIP, RSN_SELECTOR_LEN)) return WPA_CIPHER_TKIP; if (!memcmp(s, (void *)RSN_CIPHER_SUITE_CCMP, RSN_SELECTOR_LEN)) return WPA_CIPHER_CCMP; if (!memcmp(s, (void *)RSN_CIPHER_SUITE_WEP104, RSN_SELECTOR_LEN)) return WPA_CIPHER_WEP104; return 0; } int r8712_parse_wpa_ie(u8 *wpa_ie, int wpa_ie_len, int *group_cipher, int *pairwise_cipher) { int i; int left, count; u8 *pos; if (wpa_ie_len <= 0) { /* No WPA IE - fail silently */ return _FAIL; } if ((*wpa_ie != _WPA_IE_ID_) || (*(wpa_ie + 1) != (u8)(wpa_ie_len - 2)) || (memcmp(wpa_ie + 2, (void *)WPA_OUI_TYPE, WPA_SELECTOR_LEN))) return _FAIL; pos = wpa_ie; pos += 8; left = wpa_ie_len - 8; /*group_cipher*/ if (left >= WPA_SELECTOR_LEN) { *group_cipher = r8712_get_wpa_cipher_suite(pos); pos += WPA_SELECTOR_LEN; left -= WPA_SELECTOR_LEN; } else if (left > 0) return _FAIL; /*pairwise_cipher*/ if (left >= 2) { count = le16_to_cpu(*(u16 *)pos); pos += 2; left -= 2; if (count == 0 || left < count * WPA_SELECTOR_LEN) return _FAIL; for (i = 0; i < count; i++) { *pairwise_cipher |= r8712_get_wpa_cipher_suite(pos); pos += WPA_SELECTOR_LEN; left -= WPA_SELECTOR_LEN; } } else if (left == 1) return _FAIL; return _SUCCESS; } int r8712_parse_wpa2_ie(u8 *rsn_ie, int rsn_ie_len, int *group_cipher, int *pairwise_cipher) { int i; int left, count; u8 *pos; if (rsn_ie_len <= 0) { /* No RSN IE - fail silently */ return _FAIL; } if ((*rsn_ie != _WPA2_IE_ID_) || (*(rsn_ie+1) != (u8)(rsn_ie_len - 2))) return _FAIL; pos = rsn_ie; pos += 4; left = rsn_ie_len - 4; /*group_cipher*/ if (left >= RSN_SELECTOR_LEN) { *group_cipher = r8712_get_wpa2_cipher_suite(pos); pos += RSN_SELECTOR_LEN; left -= RSN_SELECTOR_LEN; } else if (left > 0) return _FAIL; /*pairwise_cipher*/ if (left >= 2) { count = le16_to_cpu(*(u16 *)pos); pos += 2; left -= 2; if (count == 0 || left < count * RSN_SELECTOR_LEN) return _FAIL; for (i = 0; i < count; i++) { *pairwise_cipher |= r8712_get_wpa2_cipher_suite(pos); pos += RSN_SELECTOR_LEN; left -= RSN_SELECTOR_LEN; } } else if (left == 1) return _FAIL; return _SUCCESS; } int r8712_get_sec_ie(u8 *in_ie, uint in_len, u8 *rsn_ie, u16 *rsn_len, u8 *wpa_ie, u16 *wpa_len) { u8 authmode; u8 wpa_oui[4] = {0x0, 0x50, 0xf2, 0x01}; uint cnt; /*Search required WPA or WPA2 IE and copy to sec_ie[ ]*/ cnt = (_TIMESTAMP_ + _BEACON_ITERVAL_ + _CAPABILITY_); while (cnt < in_len) { authmode = in_ie[cnt]; if ((authmode == _WPA_IE_ID_) && (!memcmp(&in_ie[cnt + 2], &wpa_oui[0], 4))) { memcpy(wpa_ie, &in_ie[cnt], in_ie[cnt + 1] + 2); *wpa_len = in_ie[cnt+1]+2; cnt += in_ie[cnt + 1] + 2; /*get next */ } else { if (authmode == _WPA2_IE_ID_) { memcpy(rsn_ie, &in_ie[cnt], in_ie[cnt + 1] + 2); *rsn_len = in_ie[cnt+1] + 2; cnt += in_ie[cnt+1] + 2; /*get next*/ } else cnt += in_ie[cnt+1] + 2; /*get next*/ } } return *rsn_len + *wpa_len; } int r8712_get_wps_ie(u8 *in_ie, uint in_len, u8 *wps_ie, uint *wps_ielen) { int match; uint cnt; u8 eid, wps_oui[4] = {0x0, 0x50, 0xf2, 0x04}; cnt = 12; match = false; while (cnt < in_len) { eid = in_ie[cnt]; if ((eid == _WPA_IE_ID_) && (!memcmp(&in_ie[cnt+2], wps_oui, 4))) { memcpy(wps_ie, &in_ie[cnt], in_ie[cnt+1]+2); *wps_ielen = in_ie[cnt+1]+2; cnt += in_ie[cnt+1]+2; match = true; break; } cnt += in_ie[cnt+1]+2; /* goto next */ } return match; }
gpl-2.0
mkasick/android_kernel_samsung_jfltevzw
drivers/mmc/core/debugfs.c
730
12489
/* * Debugfs support for hosts and cards * * Copyright (C) 2008 Atmel Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/moduleparam.h> #include <linux/export.h> #include <linux/debugfs.h> #include <linux/fs.h> #include <linux/seq_file.h> #include <linux/slab.h> #include <linux/stat.h> #include <linux/fault-inject.h> #include <linux/mmc/card.h> #include <linux/mmc/host.h> #include "core.h" #include "mmc_ops.h" #ifdef CONFIG_FAIL_MMC_REQUEST static DECLARE_FAULT_ATTR(fail_default_attr); static char *fail_request; module_param(fail_request, charp, 0); #endif /* CONFIG_FAIL_MMC_REQUEST */ /* The debugfs functions are optimized away when CONFIG_DEBUG_FS isn't set. */ static int mmc_ios_show(struct seq_file *s, void *data) { static const char *vdd_str[] = { [8] = "2.0", [9] = "2.1", [10] = "2.2", [11] = "2.3", [12] = "2.4", [13] = "2.5", [14] = "2.6", [15] = "2.7", [16] = "2.8", [17] = "2.9", [18] = "3.0", [19] = "3.1", [20] = "3.2", [21] = "3.3", [22] = "3.4", [23] = "3.5", [24] = "3.6", }; struct mmc_host *host = s->private; struct mmc_ios *ios = &host->ios; const char *str; seq_printf(s, "clock:\t\t%u Hz\n", ios->clock); if (host->actual_clock) seq_printf(s, "actual clock:\t%u Hz\n", host->actual_clock); seq_printf(s, "vdd:\t\t%u ", ios->vdd); if ((1 << ios->vdd) & MMC_VDD_165_195) seq_printf(s, "(1.65 - 1.95 V)\n"); else if (ios->vdd < (ARRAY_SIZE(vdd_str) - 1) && vdd_str[ios->vdd] && vdd_str[ios->vdd + 1]) seq_printf(s, "(%s ~ %s V)\n", vdd_str[ios->vdd], vdd_str[ios->vdd + 1]); else seq_printf(s, "(invalid)\n"); switch (ios->bus_mode) { case MMC_BUSMODE_OPENDRAIN: str = "open drain"; break; case MMC_BUSMODE_PUSHPULL: str = "push-pull"; break; default: str = "invalid"; break; } seq_printf(s, "bus mode:\t%u (%s)\n", ios->bus_mode, str); switch (ios->chip_select) { case MMC_CS_DONTCARE: str = "don't care"; break; case MMC_CS_HIGH: str = "active high"; break; case MMC_CS_LOW: str = "active low"; break; default: str = "invalid"; break; } seq_printf(s, "chip select:\t%u (%s)\n", ios->chip_select, str); switch (ios->power_mode) { case MMC_POWER_OFF: str = "off"; break; case MMC_POWER_UP: str = "up"; break; case MMC_POWER_ON: str = "on"; break; default: str = "invalid"; break; } seq_printf(s, "power mode:\t%u (%s)\n", ios->power_mode, str); seq_printf(s, "bus width:\t%u (%u bits)\n", ios->bus_width, 1 << ios->bus_width); switch (ios->timing) { case MMC_TIMING_LEGACY: str = "legacy"; break; case MMC_TIMING_MMC_HS: str = "mmc high-speed"; break; case MMC_TIMING_SD_HS: str = "sd high-speed"; break; case MMC_TIMING_UHS_SDR50: str = "sd uhs SDR50"; break; case MMC_TIMING_UHS_SDR104: str = "sd uhs SDR104"; break; case MMC_TIMING_UHS_DDR50: str = "sd uhs DDR50"; break; case MMC_TIMING_MMC_HS200: str = "mmc high-speed SDR200"; break; default: str = "invalid"; break; } seq_printf(s, "timing spec:\t%u (%s)\n", ios->timing, str); return 0; } static int mmc_ios_open(struct inode *inode, struct file *file) { return single_open(file, mmc_ios_show, inode->i_private); } static const struct file_operations mmc_ios_fops = { .open = mmc_ios_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int mmc_clock_opt_get(void *data, u64 *val) { struct mmc_host *host = data; *val = host->ios.clock; return 0; } static int mmc_clock_opt_set(void *data, u64 val) { struct mmc_host *host = data; /* We need this check due to input value is u64 */ if (val > host->f_max) return -EINVAL; mmc_claim_host(host); mmc_set_clock(host, (unsigned int) val); mmc_release_host(host); return 0; } DEFINE_SIMPLE_ATTRIBUTE(mmc_clock_fops, mmc_clock_opt_get, mmc_clock_opt_set, "%llu\n"); void mmc_add_host_debugfs(struct mmc_host *host) { struct dentry *root; root = debugfs_create_dir(mmc_hostname(host), NULL); if (IS_ERR(root)) /* Don't complain -- debugfs just isn't enabled */ return; if (!root) /* Complain -- debugfs is enabled, but it failed to * create the directory. */ goto err_root; host->debugfs_root = root; if (!debugfs_create_file("ios", S_IRUSR, root, host, &mmc_ios_fops)) goto err_node; if (!debugfs_create_file("clock", S_IRUSR | S_IWUSR, root, host, &mmc_clock_fops)) goto err_node; #ifdef CONFIG_MMC_CLKGATE if (!debugfs_create_u32("clk_delay", (S_IRUSR | S_IWUSR), root, &host->clk_delay)) goto err_node; #endif #ifdef CONFIG_FAIL_MMC_REQUEST if (fail_request) setup_fault_attr(&fail_default_attr, fail_request); host->fail_mmc_request = fail_default_attr; if (IS_ERR(fault_create_debugfs_attr("fail_mmc_request", root, &host->fail_mmc_request))) goto err_node; #endif return; err_node: debugfs_remove_recursive(root); host->debugfs_root = NULL; err_root: dev_err(&host->class_dev, "failed to initialize debugfs\n"); } void mmc_remove_host_debugfs(struct mmc_host *host) { debugfs_remove_recursive(host->debugfs_root); } static int mmc_dbg_card_status_get(void *data, u64 *val) { struct mmc_card *card = data; u32 status; int ret; mmc_claim_host(card->host); ret = mmc_send_status(data, &status); if (!ret) *val = status; mmc_release_host(card->host); return ret; } DEFINE_SIMPLE_ATTRIBUTE(mmc_dbg_card_status_fops, mmc_dbg_card_status_get, NULL, "%08llx\n"); #define EXT_CSD_STR_LEN 1025 static int mmc_ext_csd_open(struct inode *inode, struct file *filp) { struct mmc_card *card = inode->i_private; char *buf; ssize_t n = 0; u8 *ext_csd; int err, i; buf = kmalloc(EXT_CSD_STR_LEN + 1, GFP_KERNEL); if (!buf) return -ENOMEM; ext_csd = kmalloc(512, GFP_KERNEL); if (!ext_csd) { err = -ENOMEM; goto out_free; } mmc_claim_host(card->host); err = mmc_send_ext_csd(card, ext_csd); mmc_release_host(card->host); if (err) goto out_free; for (i = 511; i >= 0; i--) n += sprintf(buf + n, "%02x", ext_csd[i]); n += sprintf(buf + n, "\n"); BUG_ON(n != EXT_CSD_STR_LEN); filp->private_data = buf; kfree(ext_csd); return 0; out_free: kfree(buf); kfree(ext_csd); return err; } static ssize_t mmc_ext_csd_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { char *buf = filp->private_data; return simple_read_from_buffer(ubuf, cnt, ppos, buf, EXT_CSD_STR_LEN); } static int mmc_ext_csd_release(struct inode *inode, struct file *file) { kfree(file->private_data); return 0; } static const struct file_operations mmc_dbg_ext_csd_fops = { .open = mmc_ext_csd_open, .read = mmc_ext_csd_read, .release = mmc_ext_csd_release, .llseek = default_llseek, }; static int mmc_wr_pack_stats_open(struct inode *inode, struct file *filp) { struct mmc_card *card = inode->i_private; filp->private_data = card; card->wr_pack_stats.print_in_read = 1; return 0; } #define TEMP_BUF_SIZE 256 static ssize_t mmc_wr_pack_stats_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { struct mmc_card *card = filp->private_data; struct mmc_wr_pack_stats *pack_stats; int i; int max_num_of_packed_reqs = 0; char *temp_buf; if (!card) return cnt; if (!card->wr_pack_stats.print_in_read) return 0; if (!card->wr_pack_stats.enabled) { pr_info("%s: write packing statistics are disabled\n", mmc_hostname(card->host)); goto exit; } pack_stats = &card->wr_pack_stats; if (!pack_stats->packing_events) { pr_info("%s: NULL packing_events\n", mmc_hostname(card->host)); goto exit; } max_num_of_packed_reqs = card->ext_csd.max_packed_writes; temp_buf = kmalloc(TEMP_BUF_SIZE, GFP_KERNEL); if (!temp_buf) goto exit; spin_lock(&pack_stats->lock); snprintf(temp_buf, TEMP_BUF_SIZE, "%s: write packing statistics:\n", mmc_hostname(card->host)); strlcat(ubuf, temp_buf, cnt); for (i = 1 ; i <= max_num_of_packed_reqs ; ++i) { if (pack_stats->packing_events[i]) { snprintf(temp_buf, TEMP_BUF_SIZE, "%s: Packed %d reqs - %d times\n", mmc_hostname(card->host), i, pack_stats->packing_events[i]); strlcat(ubuf, temp_buf, cnt); } } snprintf(temp_buf, TEMP_BUF_SIZE, "%s: stopped packing due to the following reasons:\n", mmc_hostname(card->host)); strlcat(ubuf, temp_buf, cnt); if (pack_stats->pack_stop_reason[EXCEEDS_SEGMENTS]) { snprintf(temp_buf, TEMP_BUF_SIZE, "%s: %d times: exceed max num of segments\n", mmc_hostname(card->host), pack_stats->pack_stop_reason[EXCEEDS_SEGMENTS]); strlcat(ubuf, temp_buf, cnt); } if (pack_stats->pack_stop_reason[EXCEEDS_SECTORS]) { snprintf(temp_buf, TEMP_BUF_SIZE, "%s: %d times: exceed max num of sectors\n", mmc_hostname(card->host), pack_stats->pack_stop_reason[EXCEEDS_SECTORS]); strlcat(ubuf, temp_buf, cnt); } if (pack_stats->pack_stop_reason[WRONG_DATA_DIR]) { snprintf(temp_buf, TEMP_BUF_SIZE, "%s: %d times: wrong data direction\n", mmc_hostname(card->host), pack_stats->pack_stop_reason[WRONG_DATA_DIR]); strlcat(ubuf, temp_buf, cnt); } if (pack_stats->pack_stop_reason[FLUSH_OR_DISCARD]) { snprintf(temp_buf, TEMP_BUF_SIZE, "%s: %d times: flush or discard\n", mmc_hostname(card->host), pack_stats->pack_stop_reason[FLUSH_OR_DISCARD]); strlcat(ubuf, temp_buf, cnt); } if (pack_stats->pack_stop_reason[EMPTY_QUEUE]) { snprintf(temp_buf, TEMP_BUF_SIZE, "%s: %d times: empty queue\n", mmc_hostname(card->host), pack_stats->pack_stop_reason[EMPTY_QUEUE]); strlcat(ubuf, temp_buf, cnt); } if (pack_stats->pack_stop_reason[REL_WRITE]) { snprintf(temp_buf, TEMP_BUF_SIZE, "%s: %d times: rel write\n", mmc_hostname(card->host), pack_stats->pack_stop_reason[REL_WRITE]); strlcat(ubuf, temp_buf, cnt); } if (pack_stats->pack_stop_reason[THRESHOLD]) { snprintf(temp_buf, TEMP_BUF_SIZE, "%s: %d times: Threshold\n", mmc_hostname(card->host), pack_stats->pack_stop_reason[THRESHOLD]); strlcat(ubuf, temp_buf, cnt); } if (pack_stats->pack_stop_reason[LARGE_SEC_ALIGN]) { snprintf(temp_buf, TEMP_BUF_SIZE, "%s: %d times: Large sector alignment\n", mmc_hostname(card->host), pack_stats->pack_stop_reason[LARGE_SEC_ALIGN]); strlcat(ubuf, temp_buf, cnt); } spin_unlock(&pack_stats->lock); kfree(temp_buf); pr_info("%s", ubuf); exit: if (card->wr_pack_stats.print_in_read == 1) { card->wr_pack_stats.print_in_read = 0; return strnlen(ubuf, cnt); } return 0; } static ssize_t mmc_wr_pack_stats_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { struct mmc_card *card = filp->private_data; int value; if (!card) return cnt; sscanf(ubuf, "%d", &value); if (value) { mmc_blk_init_packed_statistics(card); } else { spin_lock(&card->wr_pack_stats.lock); card->wr_pack_stats.enabled = false; spin_unlock(&card->wr_pack_stats.lock); } return cnt; } static const struct file_operations mmc_dbg_wr_pack_stats_fops = { .open = mmc_wr_pack_stats_open, .read = mmc_wr_pack_stats_read, .write = mmc_wr_pack_stats_write, }; void mmc_add_card_debugfs(struct mmc_card *card) { struct mmc_host *host = card->host; struct dentry *root; if (!host->debugfs_root) return; root = debugfs_create_dir(mmc_card_id(card), host->debugfs_root); if (IS_ERR(root)) /* Don't complain -- debugfs just isn't enabled */ return; if (!root) /* Complain -- debugfs is enabled, but it failed to * create the directory. */ goto err; card->debugfs_root = root; if (!debugfs_create_x32("state", S_IRUSR, root, &card->state)) goto err; if (mmc_card_mmc(card) || mmc_card_sd(card)) if (!debugfs_create_file("status", S_IRUSR, root, card, &mmc_dbg_card_status_fops)) goto err; if (mmc_card_mmc(card)) if (!debugfs_create_file("ext_csd", S_IRUSR, root, card, &mmc_dbg_ext_csd_fops)) goto err; if (mmc_card_mmc(card) && (card->ext_csd.rev >= 6) && (card->host->caps2 & MMC_CAP2_PACKED_WR)) if (!debugfs_create_file("wr_pack_stats", S_IRUSR, root, card, &mmc_dbg_wr_pack_stats_fops)) goto err; return; err: debugfs_remove_recursive(root); card->debugfs_root = NULL; dev_err(&card->dev, "failed to initialize debugfs\n"); } void mmc_remove_card_debugfs(struct mmc_card *card) { debugfs_remove_recursive(card->debugfs_root); }
gpl-2.0
Ca1ne/Classic-Sense-Kernel
arch/arm/mach-gemini/board-rut1xx.c
1498
2111
/* * Support for Teltonika RUT1xx * * Copyright (C) 2008-2009 Paulius Zaleckas <paulius.zaleckas@teltonika.lt> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/leds.h> #include <linux/input.h> #include <linux/gpio_keys.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/mach/time.h> #include "common.h" static struct gpio_keys_button rut1xx_keys[] = { { .code = KEY_SETUP, .gpio = 60, .active_low = 1, .desc = "Reset to defaults", .type = EV_KEY, }, }; static struct gpio_keys_platform_data rut1xx_keys_data = { .buttons = rut1xx_keys, .nbuttons = ARRAY_SIZE(rut1xx_keys), }; static struct platform_device rut1xx_keys_device = { .name = "gpio-keys", .id = -1, .dev = { .platform_data = &rut1xx_keys_data, }, }; static struct gpio_led rut100_leds[] = { { .name = "Power", .default_trigger = "heartbeat", .gpio = 17, }, { .name = "GSM", .default_trigger = "default-on", .gpio = 7, .active_low = 1, }, }; static struct gpio_led_platform_data rut100_leds_data = { .num_leds = ARRAY_SIZE(rut100_leds), .leds = rut100_leds, }; static struct platform_device rut1xx_leds = { .name = "leds-gpio", .id = -1, .dev = { .platform_data = &rut100_leds_data, }, }; static struct sys_timer rut1xx_timer = { .init = gemini_timer_init, }; static void __init rut1xx_init(void) { gemini_gpio_init(); platform_register_uart(); platform_register_pflash(SZ_8M, NULL, 0); platform_device_register(&rut1xx_leds); platform_device_register(&rut1xx_keys_device); } MACHINE_START(RUT100, "Teltonika RUT100") .phys_io = 0x7fffc000, .io_pg_offst = ((0xffffc000) >> 18) & 0xfffc, .boot_params = 0x100, .map_io = gemini_map_io, .init_irq = gemini_init_irq, .timer = &rut1xx_timer, .init_machine = rut1xx_init, MACHINE_END
gpl-2.0
farchanrifai/Foxy
arch/arm/mach-msm/wallclk_sysfs.c
2010
7117
/* Copyright (c) 2013, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/spinlock.h> #include <linux/semaphore.h> #include <linux/kthread.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/ctype.h> #include <linux/uaccess.h> #include <linux/errno.h> #include "wallclk.h" #define WALLCLK_SYSFS_MODULE_NAME "wallclk_sysfs" static struct kobject *wallclk_kobj; static ssize_t sfn_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { int rc; rc = wallclk_get_sfn(); if (rc < 0) return rc; return snprintf(buf, 10, "%d\n", rc); } static ssize_t sfn_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { u16 sfn; int rc; if (kstrtou16(buf, 0, &sfn)) { printk(KERN_ERR "%s: sfn input is not a valid u16 value\n", WALLCLK_SYSFS_MODULE_NAME); rc = -EINVAL; goto out; } rc = wallclk_set_sfn(sfn); if (rc) { printk(KERN_ERR "%s: fail to set sfn\n", WALLCLK_SYSFS_MODULE_NAME); goto out; } rc = count; out: return rc; } static struct kobj_attribute sfn_attribute = __ATTR(sfn, 0666, sfn_show, sfn_store); static ssize_t sfn_ref_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { int rc; rc = wallclk_get_sfn_ref(); if (rc < 0) return rc; return snprintf(buf, 10, "%d\n", rc); } static ssize_t sfn_ref_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { u16 sfn_ref; int rc; if (kstrtou16(buf, 0, &sfn_ref)) { printk(KERN_ERR "%s: sfn_ref input is not a valid u16 value\n", WALLCLK_SYSFS_MODULE_NAME); rc = -EINVAL; goto out; } rc = wallclk_set_sfn_ref(sfn_ref); if (rc) { printk(KERN_ERR "%s: fail to set sfn_ref\n", WALLCLK_SYSFS_MODULE_NAME); goto out; } rc = count; out: return rc; } static struct kobj_attribute sfn_ref_attribute = __ATTR(sfn_ref, 0666, sfn_ref_show, sfn_ref_store); static ssize_t reg_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf, u32 offset) { int rc; u32 val; rc = wallclk_reg_read(offset, &val); if (rc) return rc; return snprintf(buf, 20, "%08x\n", val); } static ssize_t reg_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, const size_t count, u32 offset) { u32 v; int rc; if (kstrtou32(buf, 0, &v)) { printk(KERN_ERR "%s: input is not a valid u32 value\n", WALLCLK_SYSFS_MODULE_NAME); rc = -EINVAL; goto out; } rc = wallclk_reg_write(offset, v); if (rc) { printk(KERN_ERR "%s: fail to set register(offset=0x%x)\n", WALLCLK_SYSFS_MODULE_NAME, offset); goto out; } rc = count; out: return rc; } static ssize_t ctrl_reg_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return reg_show(kobj, attr, buf, CTRL_REG_OFFSET); } static ssize_t ctrl_reg_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, const size_t count) { return reg_store(kobj, attr, buf, count, CTRL_REG_OFFSET); } static struct kobj_attribute ctrl_reg_attribute = __ATTR(ctrl_reg, 0666, ctrl_reg_show, ctrl_reg_store); static ssize_t basetime0_reg_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return reg_show(kobj, attr, buf, CLK_BASE_TIME0_OFFSET); } static ssize_t basetime0_reg_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { return reg_store(kobj, attr, buf, count, CLK_BASE_TIME0_OFFSET); } static struct kobj_attribute basetime0_reg_attribute = __ATTR(base_time0_reg, 0666, basetime0_reg_show, basetime0_reg_store); static ssize_t basetime1_reg_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return reg_show(kobj, attr, buf, CLK_BASE_TIME1_OFFSET); } static ssize_t basetime1_reg_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { return reg_store(kobj, attr, buf, count, CLK_BASE_TIME1_OFFSET); } static struct kobj_attribute basetime1_reg_attribute = __ATTR(base_time1_reg, 0666, basetime1_reg_show, basetime1_reg_store); static ssize_t pulse_cnt_reg_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return reg_show(kobj, attr, buf, PULSE_CNT_REG_OFFSET); } static ssize_t pulse_cnt_reg_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { return reg_store(kobj, attr, buf, count, PULSE_CNT_REG_OFFSET); } static struct kobj_attribute pulse_cnt_reg_attribute = __ATTR(pulse_cnt_reg, 0666, pulse_cnt_reg_show, pulse_cnt_reg_store); static ssize_t clk_cnt_reg_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return reg_show(kobj, attr, buf, CLK_CNT_REG_OFFSET); } static ssize_t clk_cnt_reg_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { return reg_store(kobj, attr, buf, count, CLK_CNT_REG_OFFSET); } static struct kobj_attribute clk_cnt_reg_attribute = __ATTR(clock_cnt_reg, 0666, clk_cnt_reg_show, clk_cnt_reg_store); static ssize_t clk_cnt_snapshot_reg_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return reg_show(kobj, attr, buf, CLK_CNT_SNAPSHOT_REG_OFFSET); } static struct kobj_attribute clk_cnt_snapshot_reg_attribute = __ATTR(clock_cnt_snapshot_reg, 0444, clk_cnt_snapshot_reg_show, NULL); static struct attribute *wallclk_attrs[] = { &sfn_attribute.attr, &sfn_ref_attribute.attr, &ctrl_reg_attribute.attr, &pulse_cnt_reg_attribute.attr, &clk_cnt_snapshot_reg_attribute.attr, &clk_cnt_reg_attribute.attr, &basetime0_reg_attribute.attr, &basetime1_reg_attribute.attr, NULL }; static struct attribute_group wallclk_attr_group = { .attrs = wallclk_attrs, }; static int __init wallclk_sysfs_init(void) { int rc; wallclk_kobj = kobject_create_and_add("wallclk", kernel_kobj); if (!wallclk_kobj) { printk(KERN_ERR "%s: failed to create kobject\n", WALLCLK_SYSFS_MODULE_NAME); rc = -ENOMEM; goto out; } rc = sysfs_create_group(wallclk_kobj, &wallclk_attr_group); if (rc) { kobject_put(wallclk_kobj); printk(KERN_ERR "%s: failed to create sysfs group\n", WALLCLK_SYSFS_MODULE_NAME); } out: return rc; } static void __exit wallclk_sysfs_exit(void) { kobject_put(wallclk_kobj); } module_init(wallclk_sysfs_init); module_exit(wallclk_sysfs_exit); MODULE_DESCRIPTION("Wall clock SysFS"); MODULE_LICENSE("GPL v2");
gpl-2.0
bilalliberty/kernel_golfu
arch/arm/mach-omap2/vp44xx_data.c
2522
3489
/* * OMAP3 Voltage Processor (VP) data * * Copyright (C) 2007, 2010 Texas Instruments, Inc. * Rajendra Nayak <rnayak@ti.com> * Lesly A M <x0080970@ti.com> * Thara Gopinath <thara@ti.com> * * Copyright (C) 2008, 2011 Nokia Corporation * Kalle Jokiniemi * Paul Walmsley * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/io.h> #include <linux/err.h> #include <linux/init.h> #include <plat/common.h> #include "prm44xx.h" #include "prm-regbits-44xx.h" #include "voltage.h" #include "vp.h" /* * VP data common to 44xx chips * XXX This stuff presumably belongs in the vp44xx.c or vp.c file. */ static const struct omap_vp_common_data omap4_vp_common = { .vpconfig_erroroffset_shift = OMAP4430_ERROROFFSET_SHIFT, .vpconfig_errorgain_mask = OMAP4430_ERRORGAIN_MASK, .vpconfig_errorgain_shift = OMAP4430_ERRORGAIN_SHIFT, .vpconfig_initvoltage_shift = OMAP4430_INITVOLTAGE_SHIFT, .vpconfig_initvoltage_mask = OMAP4430_INITVOLTAGE_MASK, .vpconfig_timeouten = OMAP4430_TIMEOUTEN_MASK, .vpconfig_initvdd = OMAP4430_INITVDD_MASK, .vpconfig_forceupdate = OMAP4430_FORCEUPDATE_MASK, .vpconfig_vpenable = OMAP4430_VPENABLE_MASK, .vstepmin_smpswaittimemin_shift = OMAP4430_SMPSWAITTIMEMIN_SHIFT, .vstepmax_smpswaittimemax_shift = OMAP4430_SMPSWAITTIMEMAX_SHIFT, .vstepmin_stepmin_shift = OMAP4430_VSTEPMIN_SHIFT, .vstepmax_stepmax_shift = OMAP4430_VSTEPMAX_SHIFT, .vlimitto_vddmin_shift = OMAP4430_VDDMIN_SHIFT, .vlimitto_vddmax_shift = OMAP4430_VDDMAX_SHIFT, .vlimitto_timeout_shift = OMAP4430_TIMEOUT_SHIFT, }; static const struct omap_vp_prm_irqst_data omap4_vp_mpu_prm_irqst_data = { .prm_irqst_reg = OMAP4_PRM_IRQSTATUS_MPU_2_OFFSET, .tranxdone_status = OMAP4430_VP_MPU_TRANXDONE_ST_MASK, }; struct omap_vp_instance_data omap4_vp_mpu_data = { .vp_common = &omap4_vp_common, .vpconfig = OMAP4_PRM_VP_MPU_CONFIG_OFFSET, .vstepmin = OMAP4_PRM_VP_MPU_VSTEPMIN_OFFSET, .vstepmax = OMAP4_PRM_VP_MPU_VSTEPMAX_OFFSET, .vlimitto = OMAP4_PRM_VP_MPU_VLIMITTO_OFFSET, .vstatus = OMAP4_PRM_VP_MPU_STATUS_OFFSET, .voltage = OMAP4_PRM_VP_MPU_VOLTAGE_OFFSET, .prm_irqst_data = &omap4_vp_mpu_prm_irqst_data, }; static const struct omap_vp_prm_irqst_data omap4_vp_iva_prm_irqst_data = { .prm_irqst_reg = OMAP4_PRM_IRQSTATUS_MPU_OFFSET, .tranxdone_status = OMAP4430_VP_IVA_TRANXDONE_ST_MASK, }; struct omap_vp_instance_data omap4_vp_iva_data = { .vp_common = &omap4_vp_common, .vpconfig = OMAP4_PRM_VP_IVA_CONFIG_OFFSET, .vstepmin = OMAP4_PRM_VP_IVA_VSTEPMIN_OFFSET, .vstepmax = OMAP4_PRM_VP_IVA_VSTEPMAX_OFFSET, .vlimitto = OMAP4_PRM_VP_IVA_VLIMITTO_OFFSET, .vstatus = OMAP4_PRM_VP_IVA_STATUS_OFFSET, .voltage = OMAP4_PRM_VP_IVA_VOLTAGE_OFFSET, .prm_irqst_data = &omap4_vp_iva_prm_irqst_data, }; static const struct omap_vp_prm_irqst_data omap4_vp_core_prm_irqst_data = { .prm_irqst_reg = OMAP4_PRM_IRQSTATUS_MPU_OFFSET, .tranxdone_status = OMAP4430_VP_CORE_TRANXDONE_ST_MASK, }; struct omap_vp_instance_data omap4_vp_core_data = { .vp_common = &omap4_vp_common, .vpconfig = OMAP4_PRM_VP_CORE_CONFIG_OFFSET, .vstepmin = OMAP4_PRM_VP_CORE_VSTEPMIN_OFFSET, .vstepmax = OMAP4_PRM_VP_CORE_VSTEPMAX_OFFSET, .vlimitto = OMAP4_PRM_VP_CORE_VLIMITTO_OFFSET, .vstatus = OMAP4_PRM_VP_CORE_STATUS_OFFSET, .voltage = OMAP4_PRM_VP_CORE_VOLTAGE_OFFSET, .prm_irqst_data = &omap4_vp_core_prm_irqst_data, };
gpl-2.0
simone201/neak-ics-kernel
drivers/edac/i7300_edac.c
2778
36660
/* * Intel 7300 class Memory Controllers kernel module (Clarksboro) * * This file may be distributed under the terms of the * GNU General Public License version 2 only. * * Copyright (c) 2010 by: * Mauro Carvalho Chehab <mchehab@redhat.com> * * Red Hat Inc. http://www.redhat.com * * Intel 7300 Chipset Memory Controller Hub (MCH) - Datasheet * http://www.intel.com/Assets/PDF/datasheet/318082.pdf * * TODO: The chipset allow checking for PCI Express errors also. Currently, * the driver covers only memory error errors * * This driver uses "csrows" EDAC attribute to represent DIMM slot# */ #include <linux/module.h> #include <linux/init.h> #include <linux/pci.h> #include <linux/pci_ids.h> #include <linux/slab.h> #include <linux/edac.h> #include <linux/mmzone.h> #include "edac_core.h" /* * Alter this version for the I7300 module when modifications are made */ #define I7300_REVISION " Ver: 1.0.0" #define EDAC_MOD_STR "i7300_edac" #define i7300_printk(level, fmt, arg...) \ edac_printk(level, "i7300", fmt, ##arg) #define i7300_mc_printk(mci, level, fmt, arg...) \ edac_mc_chipset_printk(mci, level, "i7300", fmt, ##arg) /*********************************************** * i7300 Limit constants Structs and static vars ***********************************************/ /* * Memory topology is organized as: * Branch 0 - 2 channels: channels 0 and 1 (FDB0 PCI dev 21.0) * Branch 1 - 2 channels: channels 2 and 3 (FDB1 PCI dev 22.0) * Each channel can have to 8 DIMM sets (called as SLOTS) * Slots should generally be filled in pairs * Except on Single Channel mode of operation * just slot 0/channel0 filled on this mode * On normal operation mode, the two channels on a branch should be * filled together for the same SLOT# * When in mirrored mode, Branch 1 replicate memory at Branch 0, so, the four * channels on both branches should be filled */ /* Limits for i7300 */ #define MAX_SLOTS 8 #define MAX_BRANCHES 2 #define MAX_CH_PER_BRANCH 2 #define MAX_CHANNELS (MAX_CH_PER_BRANCH * MAX_BRANCHES) #define MAX_MIR 3 #define to_channel(ch, branch) ((((branch)) << 1) | (ch)) #define to_csrow(slot, ch, branch) \ (to_channel(ch, branch) | ((slot) << 2)) /* Device name and register DID (Device ID) */ struct i7300_dev_info { const char *ctl_name; /* name for this device */ u16 fsb_mapping_errors; /* DID for the branchmap,control */ }; /* Table of devices attributes supported by this driver */ static const struct i7300_dev_info i7300_devs[] = { { .ctl_name = "I7300", .fsb_mapping_errors = PCI_DEVICE_ID_INTEL_I7300_MCH_ERR, }, }; struct i7300_dimm_info { int megabytes; /* size, 0 means not present */ }; /* driver private data structure */ struct i7300_pvt { struct pci_dev *pci_dev_16_0_fsb_ctlr; /* 16.0 */ struct pci_dev *pci_dev_16_1_fsb_addr_map; /* 16.1 */ struct pci_dev *pci_dev_16_2_fsb_err_regs; /* 16.2 */ struct pci_dev *pci_dev_2x_0_fbd_branch[MAX_BRANCHES]; /* 21.0 and 22.0 */ u16 tolm; /* top of low memory */ u64 ambase; /* AMB BAR */ u32 mc_settings; /* Report several settings */ u32 mc_settings_a; u16 mir[MAX_MIR]; /* Memory Interleave Reg*/ u16 mtr[MAX_SLOTS][MAX_BRANCHES]; /* Memory Technlogy Reg */ u16 ambpresent[MAX_CHANNELS]; /* AMB present regs */ /* DIMM information matrix, allocating architecture maximums */ struct i7300_dimm_info dimm_info[MAX_SLOTS][MAX_CHANNELS]; /* Temporary buffer for use when preparing error messages */ char *tmp_prt_buffer; }; /* FIXME: Why do we need to have this static? */ static struct edac_pci_ctl_info *i7300_pci; /*************************************************** * i7300 Register definitions for memory enumeration ***************************************************/ /* * Device 16, * Function 0: System Address (not documented) * Function 1: Memory Branch Map, Control, Errors Register */ /* OFFSETS for Function 0 */ #define AMBASE 0x48 /* AMB Mem Mapped Reg Region Base */ #define MAXCH 0x56 /* Max Channel Number */ #define MAXDIMMPERCH 0x57 /* Max DIMM PER Channel Number */ /* OFFSETS for Function 1 */ #define MC_SETTINGS 0x40 #define IS_MIRRORED(mc) ((mc) & (1 << 16)) #define IS_ECC_ENABLED(mc) ((mc) & (1 << 5)) #define IS_RETRY_ENABLED(mc) ((mc) & (1 << 31)) #define IS_SCRBALGO_ENHANCED(mc) ((mc) & (1 << 8)) #define MC_SETTINGS_A 0x58 #define IS_SINGLE_MODE(mca) ((mca) & (1 << 14)) #define TOLM 0x6C #define MIR0 0x80 #define MIR1 0x84 #define MIR2 0x88 /* * Note: Other Intel EDAC drivers use AMBPRESENT to identify if the available * memory. From datasheet item 7.3.1 (FB-DIMM technology & organization), it * seems that we cannot use this information directly for the same usage. * Each memory slot may have up to 2 AMB interfaces, one for income and another * for outcome interface to the next slot. * For now, the driver just stores the AMB present registers, but rely only at * the MTR info to detect memory. * Datasheet is also not clear about how to map each AMBPRESENT registers to * one of the 4 available channels. */ #define AMBPRESENT_0 0x64 #define AMBPRESENT_1 0x66 static const u16 mtr_regs[MAX_SLOTS] = { 0x80, 0x84, 0x88, 0x8c, 0x82, 0x86, 0x8a, 0x8e }; /* * Defines to extract the vaious fields from the * MTRx - Memory Technology Registers */ #define MTR_DIMMS_PRESENT(mtr) ((mtr) & (1 << 8)) #define MTR_DIMMS_ETHROTTLE(mtr) ((mtr) & (1 << 7)) #define MTR_DRAM_WIDTH(mtr) (((mtr) & (1 << 6)) ? 8 : 4) #define MTR_DRAM_BANKS(mtr) (((mtr) & (1 << 5)) ? 8 : 4) #define MTR_DIMM_RANKS(mtr) (((mtr) & (1 << 4)) ? 1 : 0) #define MTR_DIMM_ROWS(mtr) (((mtr) >> 2) & 0x3) #define MTR_DRAM_BANKS_ADDR_BITS 2 #define MTR_DIMM_ROWS_ADDR_BITS(mtr) (MTR_DIMM_ROWS(mtr) + 13) #define MTR_DIMM_COLS(mtr) ((mtr) & 0x3) #define MTR_DIMM_COLS_ADDR_BITS(mtr) (MTR_DIMM_COLS(mtr) + 10) #ifdef CONFIG_EDAC_DEBUG /* MTR NUMROW */ static const char *numrow_toString[] = { "8,192 - 13 rows", "16,384 - 14 rows", "32,768 - 15 rows", "65,536 - 16 rows" }; /* MTR NUMCOL */ static const char *numcol_toString[] = { "1,024 - 10 columns", "2,048 - 11 columns", "4,096 - 12 columns", "reserved" }; #endif /************************************************ * i7300 Register definitions for error detection ************************************************/ /* * Device 16.1: FBD Error Registers */ #define FERR_FAT_FBD 0x98 static const char *ferr_fat_fbd_name[] = { [22] = "Non-Redundant Fast Reset Timeout", [2] = ">Tmid Thermal event with intelligent throttling disabled", [1] = "Memory or FBD configuration CRC read error", [0] = "Memory Write error on non-redundant retry or " "FBD configuration Write error on retry", }; #define GET_FBD_FAT_IDX(fbderr) (fbderr & (3 << 28)) #define FERR_FAT_FBD_ERR_MASK ((1 << 0) | (1 << 1) | (1 << 2) | (1 << 3)) #define FERR_NF_FBD 0xa0 static const char *ferr_nf_fbd_name[] = { [24] = "DIMM-Spare Copy Completed", [23] = "DIMM-Spare Copy Initiated", [22] = "Redundant Fast Reset Timeout", [21] = "Memory Write error on redundant retry", [18] = "SPD protocol Error", [17] = "FBD Northbound parity error on FBD Sync Status", [16] = "Correctable Patrol Data ECC", [15] = "Correctable Resilver- or Spare-Copy Data ECC", [14] = "Correctable Mirrored Demand Data ECC", [13] = "Correctable Non-Mirrored Demand Data ECC", [11] = "Memory or FBD configuration CRC read error", [10] = "FBD Configuration Write error on first attempt", [9] = "Memory Write error on first attempt", [8] = "Non-Aliased Uncorrectable Patrol Data ECC", [7] = "Non-Aliased Uncorrectable Resilver- or Spare-Copy Data ECC", [6] = "Non-Aliased Uncorrectable Mirrored Demand Data ECC", [5] = "Non-Aliased Uncorrectable Non-Mirrored Demand Data ECC", [4] = "Aliased Uncorrectable Patrol Data ECC", [3] = "Aliased Uncorrectable Resilver- or Spare-Copy Data ECC", [2] = "Aliased Uncorrectable Mirrored Demand Data ECC", [1] = "Aliased Uncorrectable Non-Mirrored Demand Data ECC", [0] = "Uncorrectable Data ECC on Replay", }; #define GET_FBD_NF_IDX(fbderr) (fbderr & (3 << 28)) #define FERR_NF_FBD_ERR_MASK ((1 << 24) | (1 << 23) | (1 << 22) | (1 << 21) |\ (1 << 18) | (1 << 17) | (1 << 16) | (1 << 15) |\ (1 << 14) | (1 << 13) | (1 << 11) | (1 << 10) |\ (1 << 9) | (1 << 8) | (1 << 7) | (1 << 6) |\ (1 << 5) | (1 << 4) | (1 << 3) | (1 << 2) |\ (1 << 1) | (1 << 0)) #define EMASK_FBD 0xa8 #define EMASK_FBD_ERR_MASK ((1 << 27) | (1 << 26) | (1 << 25) | (1 << 24) |\ (1 << 22) | (1 << 21) | (1 << 20) | (1 << 19) |\ (1 << 18) | (1 << 17) | (1 << 16) | (1 << 14) |\ (1 << 13) | (1 << 12) | (1 << 11) | (1 << 10) |\ (1 << 9) | (1 << 8) | (1 << 7) | (1 << 6) |\ (1 << 5) | (1 << 4) | (1 << 3) | (1 << 2) |\ (1 << 1) | (1 << 0)) /* * Device 16.2: Global Error Registers */ #define FERR_GLOBAL_HI 0x48 static const char *ferr_global_hi_name[] = { [3] = "FSB 3 Fatal Error", [2] = "FSB 2 Fatal Error", [1] = "FSB 1 Fatal Error", [0] = "FSB 0 Fatal Error", }; #define ferr_global_hi_is_fatal(errno) 1 #define FERR_GLOBAL_LO 0x40 static const char *ferr_global_lo_name[] = { [31] = "Internal MCH Fatal Error", [30] = "Intel QuickData Technology Device Fatal Error", [29] = "FSB1 Fatal Error", [28] = "FSB0 Fatal Error", [27] = "FBD Channel 3 Fatal Error", [26] = "FBD Channel 2 Fatal Error", [25] = "FBD Channel 1 Fatal Error", [24] = "FBD Channel 0 Fatal Error", [23] = "PCI Express Device 7Fatal Error", [22] = "PCI Express Device 6 Fatal Error", [21] = "PCI Express Device 5 Fatal Error", [20] = "PCI Express Device 4 Fatal Error", [19] = "PCI Express Device 3 Fatal Error", [18] = "PCI Express Device 2 Fatal Error", [17] = "PCI Express Device 1 Fatal Error", [16] = "ESI Fatal Error", [15] = "Internal MCH Non-Fatal Error", [14] = "Intel QuickData Technology Device Non Fatal Error", [13] = "FSB1 Non-Fatal Error", [12] = "FSB 0 Non-Fatal Error", [11] = "FBD Channel 3 Non-Fatal Error", [10] = "FBD Channel 2 Non-Fatal Error", [9] = "FBD Channel 1 Non-Fatal Error", [8] = "FBD Channel 0 Non-Fatal Error", [7] = "PCI Express Device 7 Non-Fatal Error", [6] = "PCI Express Device 6 Non-Fatal Error", [5] = "PCI Express Device 5 Non-Fatal Error", [4] = "PCI Express Device 4 Non-Fatal Error", [3] = "PCI Express Device 3 Non-Fatal Error", [2] = "PCI Express Device 2 Non-Fatal Error", [1] = "PCI Express Device 1 Non-Fatal Error", [0] = "ESI Non-Fatal Error", }; #define ferr_global_lo_is_fatal(errno) ((errno < 16) ? 0 : 1) #define NRECMEMA 0xbe #define NRECMEMA_BANK(v) (((v) >> 12) & 7) #define NRECMEMA_RANK(v) (((v) >> 8) & 15) #define NRECMEMB 0xc0 #define NRECMEMB_IS_WR(v) ((v) & (1 << 31)) #define NRECMEMB_CAS(v) (((v) >> 16) & 0x1fff) #define NRECMEMB_RAS(v) ((v) & 0xffff) #define REDMEMA 0xdc #define REDMEMB 0x7c #define IS_SECOND_CH(v) ((v) * (1 << 17)) #define RECMEMA 0xe0 #define RECMEMA_BANK(v) (((v) >> 12) & 7) #define RECMEMA_RANK(v) (((v) >> 8) & 15) #define RECMEMB 0xe4 #define RECMEMB_IS_WR(v) ((v) & (1 << 31)) #define RECMEMB_CAS(v) (((v) >> 16) & 0x1fff) #define RECMEMB_RAS(v) ((v) & 0xffff) /******************************************** * i7300 Functions related to error detection ********************************************/ /** * get_err_from_table() - Gets the error message from a table * @table: table name (array of char *) * @size: number of elements at the table * @pos: position of the element to be returned * * This is a small routine that gets the pos-th element of a table. If the * element doesn't exist (or it is empty), it returns "reserved". * Instead of calling it directly, the better is to call via the macro * GET_ERR_FROM_TABLE(), that automatically checks the table size via * ARRAY_SIZE() macro */ static const char *get_err_from_table(const char *table[], int size, int pos) { if (unlikely(pos >= size)) return "Reserved"; if (unlikely(!table[pos])) return "Reserved"; return table[pos]; } #define GET_ERR_FROM_TABLE(table, pos) \ get_err_from_table(table, ARRAY_SIZE(table), pos) /** * i7300_process_error_global() - Retrieve the hardware error information from * the hardware global error registers and * sends it to dmesg * @mci: struct mem_ctl_info pointer */ static void i7300_process_error_global(struct mem_ctl_info *mci) { struct i7300_pvt *pvt; u32 errnum, value; unsigned long errors; const char *specific; bool is_fatal; pvt = mci->pvt_info; /* read in the 1st FATAL error register */ pci_read_config_dword(pvt->pci_dev_16_2_fsb_err_regs, FERR_GLOBAL_HI, &value); if (unlikely(value)) { errors = value; errnum = find_first_bit(&errors, ARRAY_SIZE(ferr_global_hi_name)); specific = GET_ERR_FROM_TABLE(ferr_global_hi_name, errnum); is_fatal = ferr_global_hi_is_fatal(errnum); /* Clear the error bit */ pci_write_config_dword(pvt->pci_dev_16_2_fsb_err_regs, FERR_GLOBAL_HI, value); goto error_global; } pci_read_config_dword(pvt->pci_dev_16_2_fsb_err_regs, FERR_GLOBAL_LO, &value); if (unlikely(value)) { errors = value; errnum = find_first_bit(&errors, ARRAY_SIZE(ferr_global_lo_name)); specific = GET_ERR_FROM_TABLE(ferr_global_lo_name, errnum); is_fatal = ferr_global_lo_is_fatal(errnum); /* Clear the error bit */ pci_write_config_dword(pvt->pci_dev_16_2_fsb_err_regs, FERR_GLOBAL_LO, value); goto error_global; } return; error_global: i7300_mc_printk(mci, KERN_EMERG, "%s misc error: %s\n", is_fatal ? "Fatal" : "NOT fatal", specific); } /** * i7300_process_fbd_error() - Retrieve the hardware error information from * the FBD error registers and sends it via * EDAC error API calls * @mci: struct mem_ctl_info pointer */ static void i7300_process_fbd_error(struct mem_ctl_info *mci) { struct i7300_pvt *pvt; u32 errnum, value; u16 val16; unsigned branch, channel, bank, rank, cas, ras; u32 syndrome; unsigned long errors; const char *specific; bool is_wr; pvt = mci->pvt_info; /* read in the 1st FATAL error register */ pci_read_config_dword(pvt->pci_dev_16_1_fsb_addr_map, FERR_FAT_FBD, &value); if (unlikely(value & FERR_FAT_FBD_ERR_MASK)) { errors = value & FERR_FAT_FBD_ERR_MASK ; errnum = find_first_bit(&errors, ARRAY_SIZE(ferr_fat_fbd_name)); specific = GET_ERR_FROM_TABLE(ferr_fat_fbd_name, errnum); branch = (GET_FBD_FAT_IDX(value) == 2) ? 1 : 0; pci_read_config_word(pvt->pci_dev_16_1_fsb_addr_map, NRECMEMA, &val16); bank = NRECMEMA_BANK(val16); rank = NRECMEMA_RANK(val16); pci_read_config_dword(pvt->pci_dev_16_1_fsb_addr_map, NRECMEMB, &value); is_wr = NRECMEMB_IS_WR(value); cas = NRECMEMB_CAS(value); ras = NRECMEMB_RAS(value); snprintf(pvt->tmp_prt_buffer, PAGE_SIZE, "FATAL (Branch=%d DRAM-Bank=%d %s " "RAS=%d CAS=%d Err=0x%lx (%s))", branch, bank, is_wr ? "RDWR" : "RD", ras, cas, errors, specific); /* Call the helper to output message */ edac_mc_handle_fbd_ue(mci, rank, branch << 1, (branch << 1) + 1, pvt->tmp_prt_buffer); } /* read in the 1st NON-FATAL error register */ pci_read_config_dword(pvt->pci_dev_16_1_fsb_addr_map, FERR_NF_FBD, &value); if (unlikely(value & FERR_NF_FBD_ERR_MASK)) { errors = value & FERR_NF_FBD_ERR_MASK; errnum = find_first_bit(&errors, ARRAY_SIZE(ferr_nf_fbd_name)); specific = GET_ERR_FROM_TABLE(ferr_nf_fbd_name, errnum); /* Clear the error bit */ pci_write_config_dword(pvt->pci_dev_16_2_fsb_err_regs, FERR_GLOBAL_LO, value); pci_read_config_dword(pvt->pci_dev_16_1_fsb_addr_map, REDMEMA, &syndrome); branch = (GET_FBD_FAT_IDX(value) == 2) ? 1 : 0; pci_read_config_word(pvt->pci_dev_16_1_fsb_addr_map, RECMEMA, &val16); bank = RECMEMA_BANK(val16); rank = RECMEMA_RANK(val16); pci_read_config_dword(pvt->pci_dev_16_1_fsb_addr_map, RECMEMB, &value); is_wr = RECMEMB_IS_WR(value); cas = RECMEMB_CAS(value); ras = RECMEMB_RAS(value); pci_read_config_dword(pvt->pci_dev_16_1_fsb_addr_map, REDMEMB, &value); channel = (branch << 1); if (IS_SECOND_CH(value)) channel++; /* Form out message */ snprintf(pvt->tmp_prt_buffer, PAGE_SIZE, "Corrected error (Branch=%d, Channel %d), " " DRAM-Bank=%d %s " "RAS=%d CAS=%d, CE Err=0x%lx, Syndrome=0x%08x(%s))", branch, channel, bank, is_wr ? "RDWR" : "RD", ras, cas, errors, syndrome, specific); /* * Call the helper to output message * NOTE: Errors are reported per-branch, and not per-channel * Currently, we don't know how to identify the right * channel. */ edac_mc_handle_fbd_ce(mci, rank, channel, pvt->tmp_prt_buffer); } return; } /** * i7300_check_error() - Calls the error checking subroutines * @mci: struct mem_ctl_info pointer */ static void i7300_check_error(struct mem_ctl_info *mci) { i7300_process_error_global(mci); i7300_process_fbd_error(mci); }; /** * i7300_clear_error() - Clears the error registers * @mci: struct mem_ctl_info pointer */ static void i7300_clear_error(struct mem_ctl_info *mci) { struct i7300_pvt *pvt = mci->pvt_info; u32 value; /* * All error values are RWC - we need to read and write 1 to the * bit that we want to cleanup */ /* Clear global error registers */ pci_read_config_dword(pvt->pci_dev_16_2_fsb_err_regs, FERR_GLOBAL_HI, &value); pci_write_config_dword(pvt->pci_dev_16_2_fsb_err_regs, FERR_GLOBAL_HI, value); pci_read_config_dword(pvt->pci_dev_16_2_fsb_err_regs, FERR_GLOBAL_LO, &value); pci_write_config_dword(pvt->pci_dev_16_2_fsb_err_regs, FERR_GLOBAL_LO, value); /* Clear FBD error registers */ pci_read_config_dword(pvt->pci_dev_16_1_fsb_addr_map, FERR_FAT_FBD, &value); pci_write_config_dword(pvt->pci_dev_16_1_fsb_addr_map, FERR_FAT_FBD, value); pci_read_config_dword(pvt->pci_dev_16_1_fsb_addr_map, FERR_NF_FBD, &value); pci_write_config_dword(pvt->pci_dev_16_1_fsb_addr_map, FERR_NF_FBD, value); } /** * i7300_enable_error_reporting() - Enable the memory reporting logic at the * hardware * @mci: struct mem_ctl_info pointer */ static void i7300_enable_error_reporting(struct mem_ctl_info *mci) { struct i7300_pvt *pvt = mci->pvt_info; u32 fbd_error_mask; /* Read the FBD Error Mask Register */ pci_read_config_dword(pvt->pci_dev_16_1_fsb_addr_map, EMASK_FBD, &fbd_error_mask); /* Enable with a '0' */ fbd_error_mask &= ~(EMASK_FBD_ERR_MASK); pci_write_config_dword(pvt->pci_dev_16_1_fsb_addr_map, EMASK_FBD, fbd_error_mask); } /************************************************ * i7300 Functions related to memory enumberation ************************************************/ /** * decode_mtr() - Decodes the MTR descriptor, filling the edac structs * @pvt: pointer to the private data struct used by i7300 driver * @slot: DIMM slot (0 to 7) * @ch: Channel number within the branch (0 or 1) * @branch: Branch number (0 or 1) * @dinfo: Pointer to DIMM info where dimm size is stored * @p_csrow: Pointer to the struct csrow_info that corresponds to that element */ static int decode_mtr(struct i7300_pvt *pvt, int slot, int ch, int branch, struct i7300_dimm_info *dinfo, struct csrow_info *p_csrow, u32 *nr_pages) { int mtr, ans, addrBits, channel; channel = to_channel(ch, branch); mtr = pvt->mtr[slot][branch]; ans = MTR_DIMMS_PRESENT(mtr) ? 1 : 0; debugf2("\tMTR%d CH%d: DIMMs are %s (mtr)\n", slot, channel, ans ? "Present" : "NOT Present"); /* Determine if there is a DIMM present in this DIMM slot */ if (!ans) return 0; /* Start with the number of bits for a Bank * on the DRAM */ addrBits = MTR_DRAM_BANKS_ADDR_BITS; /* Add thenumber of ROW bits */ addrBits += MTR_DIMM_ROWS_ADDR_BITS(mtr); /* add the number of COLUMN bits */ addrBits += MTR_DIMM_COLS_ADDR_BITS(mtr); /* add the number of RANK bits */ addrBits += MTR_DIMM_RANKS(mtr); addrBits += 6; /* add 64 bits per DIMM */ addrBits -= 20; /* divide by 2^^20 */ addrBits -= 3; /* 8 bits per bytes */ dinfo->megabytes = 1 << addrBits; *nr_pages = dinfo->megabytes << 8; debugf2("\t\tWIDTH: x%d\n", MTR_DRAM_WIDTH(mtr)); debugf2("\t\tELECTRICAL THROTTLING is %s\n", MTR_DIMMS_ETHROTTLE(mtr) ? "enabled" : "disabled"); debugf2("\t\tNUMBANK: %d bank(s)\n", MTR_DRAM_BANKS(mtr)); debugf2("\t\tNUMRANK: %s\n", MTR_DIMM_RANKS(mtr) ? "double" : "single"); debugf2("\t\tNUMROW: %s\n", numrow_toString[MTR_DIMM_ROWS(mtr)]); debugf2("\t\tNUMCOL: %s\n", numcol_toString[MTR_DIMM_COLS(mtr)]); debugf2("\t\tSIZE: %d MB\n", dinfo->megabytes); p_csrow->grain = 8; p_csrow->mtype = MEM_FB_DDR2; p_csrow->csrow_idx = slot; p_csrow->page_mask = 0; /* * The type of error detection actually depends of the * mode of operation. When it is just one single memory chip, at * socket 0, channel 0, it uses 8-byte-over-32-byte SECDED+ code. * In normal or mirrored mode, it uses Lockstep mode, * with the possibility of using an extended algorithm for x8 memories * See datasheet Sections 7.3.6 to 7.3.8 */ if (IS_SINGLE_MODE(pvt->mc_settings_a)) { p_csrow->edac_mode = EDAC_SECDED; debugf2("\t\tECC code is 8-byte-over-32-byte SECDED+ code\n"); } else { debugf2("\t\tECC code is on Lockstep mode\n"); if (MTR_DRAM_WIDTH(mtr) == 8) p_csrow->edac_mode = EDAC_S8ECD8ED; else p_csrow->edac_mode = EDAC_S4ECD4ED; } /* ask what device type on this row */ if (MTR_DRAM_WIDTH(mtr) == 8) { debugf2("\t\tScrub algorithm for x8 is on %s mode\n", IS_SCRBALGO_ENHANCED(pvt->mc_settings) ? "enhanced" : "normal"); p_csrow->dtype = DEV_X8; } else p_csrow->dtype = DEV_X4; return mtr; } /** * print_dimm_size() - Prints dump of the memory organization * @pvt: pointer to the private data struct used by i7300 driver * * Useful for debug. If debug is disabled, this routine do nothing */ static void print_dimm_size(struct i7300_pvt *pvt) { #ifdef CONFIG_EDAC_DEBUG struct i7300_dimm_info *dinfo; char *p; int space, n; int channel, slot; space = PAGE_SIZE; p = pvt->tmp_prt_buffer; n = snprintf(p, space, " "); p += n; space -= n; for (channel = 0; channel < MAX_CHANNELS; channel++) { n = snprintf(p, space, "channel %d | ", channel); p += n; space -= n; } debugf2("%s\n", pvt->tmp_prt_buffer); p = pvt->tmp_prt_buffer; space = PAGE_SIZE; n = snprintf(p, space, "-------------------------------" "------------------------------"); p += n; space -= n; debugf2("%s\n", pvt->tmp_prt_buffer); p = pvt->tmp_prt_buffer; space = PAGE_SIZE; for (slot = 0; slot < MAX_SLOTS; slot++) { n = snprintf(p, space, "csrow/SLOT %d ", slot); p += n; space -= n; for (channel = 0; channel < MAX_CHANNELS; channel++) { dinfo = &pvt->dimm_info[slot][channel]; n = snprintf(p, space, "%4d MB | ", dinfo->megabytes); p += n; space -= n; } debugf2("%s\n", pvt->tmp_prt_buffer); p = pvt->tmp_prt_buffer; space = PAGE_SIZE; } n = snprintf(p, space, "-------------------------------" "------------------------------"); p += n; space -= n; debugf2("%s\n", pvt->tmp_prt_buffer); p = pvt->tmp_prt_buffer; space = PAGE_SIZE; #endif } /** * i7300_init_csrows() - Initialize the 'csrows' table within * the mci control structure with the * addressing of memory. * @mci: struct mem_ctl_info pointer */ static int i7300_init_csrows(struct mem_ctl_info *mci) { struct i7300_pvt *pvt; struct i7300_dimm_info *dinfo; struct csrow_info *p_csrow; int rc = -ENODEV; int mtr; int ch, branch, slot, channel; u32 last_page = 0, nr_pages; pvt = mci->pvt_info; debugf2("Memory Technology Registers:\n"); /* Get the AMB present registers for the four channels */ for (branch = 0; branch < MAX_BRANCHES; branch++) { /* Read and dump branch 0's MTRs */ channel = to_channel(0, branch); pci_read_config_word(pvt->pci_dev_2x_0_fbd_branch[branch], AMBPRESENT_0, &pvt->ambpresent[channel]); debugf2("\t\tAMB-present CH%d = 0x%x:\n", channel, pvt->ambpresent[channel]); channel = to_channel(1, branch); pci_read_config_word(pvt->pci_dev_2x_0_fbd_branch[branch], AMBPRESENT_1, &pvt->ambpresent[channel]); debugf2("\t\tAMB-present CH%d = 0x%x:\n", channel, pvt->ambpresent[channel]); } /* Get the set of MTR[0-7] regs by each branch */ for (slot = 0; slot < MAX_SLOTS; slot++) { int where = mtr_regs[slot]; for (branch = 0; branch < MAX_BRANCHES; branch++) { pci_read_config_word(pvt->pci_dev_2x_0_fbd_branch[branch], where, &pvt->mtr[slot][branch]); for (ch = 0; ch < MAX_BRANCHES; ch++) { int channel = to_channel(ch, branch); dinfo = &pvt->dimm_info[slot][channel]; p_csrow = &mci->csrows[slot]; mtr = decode_mtr(pvt, slot, ch, branch, dinfo, p_csrow, &nr_pages); /* if no DIMMS on this row, continue */ if (!MTR_DIMMS_PRESENT(mtr)) continue; /* Update per_csrow memory count */ p_csrow->nr_pages += nr_pages; p_csrow->first_page = last_page; last_page += nr_pages; p_csrow->last_page = last_page; rc = 0; } } } return rc; } /** * decode_mir() - Decodes Memory Interleave Register (MIR) info * @int mir_no: number of the MIR register to decode * @mir: array with the MIR data cached on the driver */ static void decode_mir(int mir_no, u16 mir[MAX_MIR]) { if (mir[mir_no] & 3) debugf2("MIR%d: limit= 0x%x Branch(es) that participate:" " %s %s\n", mir_no, (mir[mir_no] >> 4) & 0xfff, (mir[mir_no] & 1) ? "B0" : "", (mir[mir_no] & 2) ? "B1" : ""); } /** * i7300_get_mc_regs() - Get the contents of the MC enumeration registers * @mci: struct mem_ctl_info pointer * * Data read is cached internally for its usage when needed */ static int i7300_get_mc_regs(struct mem_ctl_info *mci) { struct i7300_pvt *pvt; u32 actual_tolm; int i, rc; pvt = mci->pvt_info; pci_read_config_dword(pvt->pci_dev_16_0_fsb_ctlr, AMBASE, (u32 *) &pvt->ambase); debugf2("AMBASE= 0x%lx\n", (long unsigned int)pvt->ambase); /* Get the Branch Map regs */ pci_read_config_word(pvt->pci_dev_16_1_fsb_addr_map, TOLM, &pvt->tolm); pvt->tolm >>= 12; debugf2("TOLM (number of 256M regions) =%u (0x%x)\n", pvt->tolm, pvt->tolm); actual_tolm = (u32) ((1000l * pvt->tolm) >> (30 - 28)); debugf2("Actual TOLM byte addr=%u.%03u GB (0x%x)\n", actual_tolm/1000, actual_tolm % 1000, pvt->tolm << 28); /* Get memory controller settings */ pci_read_config_dword(pvt->pci_dev_16_1_fsb_addr_map, MC_SETTINGS, &pvt->mc_settings); pci_read_config_dword(pvt->pci_dev_16_1_fsb_addr_map, MC_SETTINGS_A, &pvt->mc_settings_a); if (IS_SINGLE_MODE(pvt->mc_settings_a)) debugf0("Memory controller operating on single mode\n"); else debugf0("Memory controller operating on %s mode\n", IS_MIRRORED(pvt->mc_settings) ? "mirrored" : "non-mirrored"); debugf0("Error detection is %s\n", IS_ECC_ENABLED(pvt->mc_settings) ? "enabled" : "disabled"); debugf0("Retry is %s\n", IS_RETRY_ENABLED(pvt->mc_settings) ? "enabled" : "disabled"); /* Get Memory Interleave Range registers */ pci_read_config_word(pvt->pci_dev_16_1_fsb_addr_map, MIR0, &pvt->mir[0]); pci_read_config_word(pvt->pci_dev_16_1_fsb_addr_map, MIR1, &pvt->mir[1]); pci_read_config_word(pvt->pci_dev_16_1_fsb_addr_map, MIR2, &pvt->mir[2]); /* Decode the MIR regs */ for (i = 0; i < MAX_MIR; i++) decode_mir(i, pvt->mir); rc = i7300_init_csrows(mci); if (rc < 0) return rc; /* Go and determine the size of each DIMM and place in an * orderly matrix */ print_dimm_size(pvt); return 0; } /************************************************* * i7300 Functions related to device probe/release *************************************************/ /** * i7300_put_devices() - Release the PCI devices * @mci: struct mem_ctl_info pointer */ static void i7300_put_devices(struct mem_ctl_info *mci) { struct i7300_pvt *pvt; int branch; pvt = mci->pvt_info; /* Decrement usage count for devices */ for (branch = 0; branch < MAX_CH_PER_BRANCH; branch++) pci_dev_put(pvt->pci_dev_2x_0_fbd_branch[branch]); pci_dev_put(pvt->pci_dev_16_2_fsb_err_regs); pci_dev_put(pvt->pci_dev_16_1_fsb_addr_map); } /** * i7300_get_devices() - Find and perform 'get' operation on the MCH's * device/functions we want to reference for this driver * @mci: struct mem_ctl_info pointer * * Access and prepare the several devices for usage: * I7300 devices used by this driver: * Device 16, functions 0,1 and 2: PCI_DEVICE_ID_INTEL_I7300_MCH_ERR * Device 21 function 0: PCI_DEVICE_ID_INTEL_I7300_MCH_FB0 * Device 22 function 0: PCI_DEVICE_ID_INTEL_I7300_MCH_FB1 */ static int __devinit i7300_get_devices(struct mem_ctl_info *mci) { struct i7300_pvt *pvt; struct pci_dev *pdev; pvt = mci->pvt_info; /* Attempt to 'get' the MCH register we want */ pdev = NULL; while (!pvt->pci_dev_16_1_fsb_addr_map || !pvt->pci_dev_16_2_fsb_err_regs) { pdev = pci_get_device(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_I7300_MCH_ERR, pdev); if (!pdev) { /* End of list, leave */ i7300_printk(KERN_ERR, "'system address,Process Bus' " "device not found:" "vendor 0x%x device 0x%x ERR funcs " "(broken BIOS?)\n", PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_I7300_MCH_ERR); goto error; } /* Store device 16 funcs 1 and 2 */ switch (PCI_FUNC(pdev->devfn)) { case 1: pvt->pci_dev_16_1_fsb_addr_map = pdev; break; case 2: pvt->pci_dev_16_2_fsb_err_regs = pdev; break; } } debugf1("System Address, processor bus- PCI Bus ID: %s %x:%x\n", pci_name(pvt->pci_dev_16_0_fsb_ctlr), pvt->pci_dev_16_0_fsb_ctlr->vendor, pvt->pci_dev_16_0_fsb_ctlr->device); debugf1("Branchmap, control and errors - PCI Bus ID: %s %x:%x\n", pci_name(pvt->pci_dev_16_1_fsb_addr_map), pvt->pci_dev_16_1_fsb_addr_map->vendor, pvt->pci_dev_16_1_fsb_addr_map->device); debugf1("FSB Error Regs - PCI Bus ID: %s %x:%x\n", pci_name(pvt->pci_dev_16_2_fsb_err_regs), pvt->pci_dev_16_2_fsb_err_regs->vendor, pvt->pci_dev_16_2_fsb_err_regs->device); pvt->pci_dev_2x_0_fbd_branch[0] = pci_get_device(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_I7300_MCH_FB0, NULL); if (!pvt->pci_dev_2x_0_fbd_branch[0]) { i7300_printk(KERN_ERR, "MC: 'BRANCH 0' device not found:" "vendor 0x%x device 0x%x Func 0 (broken BIOS?)\n", PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_I7300_MCH_FB0); goto error; } pvt->pci_dev_2x_0_fbd_branch[1] = pci_get_device(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_I7300_MCH_FB1, NULL); if (!pvt->pci_dev_2x_0_fbd_branch[1]) { i7300_printk(KERN_ERR, "MC: 'BRANCH 1' device not found:" "vendor 0x%x device 0x%x Func 0 " "(broken BIOS?)\n", PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_I7300_MCH_FB1); goto error; } return 0; error: i7300_put_devices(mci); return -ENODEV; } /** * i7300_init_one() - Probe for one instance of the device * @pdev: struct pci_dev pointer * @id: struct pci_device_id pointer - currently unused */ static int __devinit i7300_init_one(struct pci_dev *pdev, const struct pci_device_id *id) { struct mem_ctl_info *mci; struct i7300_pvt *pvt; int num_channels; int num_dimms_per_channel; int num_csrows; int rc; /* wake up device */ rc = pci_enable_device(pdev); if (rc == -EIO) return rc; debugf0("MC: " __FILE__ ": %s(), pdev bus %u dev=0x%x fn=0x%x\n", __func__, pdev->bus->number, PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn)); /* We only are looking for func 0 of the set */ if (PCI_FUNC(pdev->devfn) != 0) return -ENODEV; /* As we don't have a motherboard identification routine to determine * actual number of slots/dimms per channel, we thus utilize the * resource as specified by the chipset. Thus, we might have * have more DIMMs per channel than actually on the mobo, but this * allows the driver to support up to the chipset max, without * some fancy mobo determination. */ num_dimms_per_channel = MAX_SLOTS; num_channels = MAX_CHANNELS; num_csrows = MAX_SLOTS * MAX_CHANNELS; debugf0("MC: %s(): Number of - Channels= %d DIMMS= %d CSROWS= %d\n", __func__, num_channels, num_dimms_per_channel, num_csrows); /* allocate a new MC control structure */ mci = edac_mc_alloc(sizeof(*pvt), num_csrows, num_channels, 0); if (mci == NULL) return -ENOMEM; debugf0("MC: " __FILE__ ": %s(): mci = %p\n", __func__, mci); mci->dev = &pdev->dev; /* record ptr to the generic device */ pvt = mci->pvt_info; pvt->pci_dev_16_0_fsb_ctlr = pdev; /* Record this device in our private */ pvt->tmp_prt_buffer = kmalloc(PAGE_SIZE, GFP_KERNEL); if (!pvt->tmp_prt_buffer) { edac_mc_free(mci); return -ENOMEM; } /* 'get' the pci devices we want to reserve for our use */ if (i7300_get_devices(mci)) goto fail0; mci->mc_idx = 0; mci->mtype_cap = MEM_FLAG_FB_DDR2; mci->edac_ctl_cap = EDAC_FLAG_NONE; mci->edac_cap = EDAC_FLAG_NONE; mci->mod_name = "i7300_edac.c"; mci->mod_ver = I7300_REVISION; mci->ctl_name = i7300_devs[0].ctl_name; mci->dev_name = pci_name(pdev); mci->ctl_page_to_phys = NULL; /* Set the function pointer to an actual operation function */ mci->edac_check = i7300_check_error; /* initialize the MC control structure 'csrows' table * with the mapping and control information */ if (i7300_get_mc_regs(mci)) { debugf0("MC: Setting mci->edac_cap to EDAC_FLAG_NONE\n" " because i7300_init_csrows() returned nonzero " "value\n"); mci->edac_cap = EDAC_FLAG_NONE; /* no csrows found */ } else { debugf1("MC: Enable error reporting now\n"); i7300_enable_error_reporting(mci); } /* add this new MC control structure to EDAC's list of MCs */ if (edac_mc_add_mc(mci)) { debugf0("MC: " __FILE__ ": %s(): failed edac_mc_add_mc()\n", __func__); /* FIXME: perhaps some code should go here that disables error * reporting if we just enabled it */ goto fail1; } i7300_clear_error(mci); /* allocating generic PCI control info */ i7300_pci = edac_pci_create_generic_ctl(&pdev->dev, EDAC_MOD_STR); if (!i7300_pci) { printk(KERN_WARNING "%s(): Unable to create PCI control\n", __func__); printk(KERN_WARNING "%s(): PCI error report via EDAC not setup\n", __func__); } return 0; /* Error exit unwinding stack */ fail1: i7300_put_devices(mci); fail0: kfree(pvt->tmp_prt_buffer); edac_mc_free(mci); return -ENODEV; } /** * i7300_remove_one() - Remove the driver * @pdev: struct pci_dev pointer */ static void __devexit i7300_remove_one(struct pci_dev *pdev) { struct mem_ctl_info *mci; char *tmp; debugf0(__FILE__ ": %s()\n", __func__); if (i7300_pci) edac_pci_release_generic_ctl(i7300_pci); mci = edac_mc_del_mc(&pdev->dev); if (!mci) return; tmp = ((struct i7300_pvt *)mci->pvt_info)->tmp_prt_buffer; /* retrieve references to resources, and free those resources */ i7300_put_devices(mci); kfree(tmp); edac_mc_free(mci); } /* * pci_device_id: table for which devices we are looking for * * Has only 8086:360c PCI ID */ static const struct pci_device_id i7300_pci_tbl[] __devinitdata = { {PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_I7300_MCH_ERR)}, {0,} /* 0 terminated list. */ }; MODULE_DEVICE_TABLE(pci, i7300_pci_tbl); /* * i7300_driver: pci_driver structure for this module */ static struct pci_driver i7300_driver = { .name = "i7300_edac", .probe = i7300_init_one, .remove = __devexit_p(i7300_remove_one), .id_table = i7300_pci_tbl, }; /** * i7300_init() - Registers the driver */ static int __init i7300_init(void) { int pci_rc; debugf2("MC: " __FILE__ ": %s()\n", __func__); /* Ensure that the OPSTATE is set correctly for POLL or NMI */ opstate_init(); pci_rc = pci_register_driver(&i7300_driver); return (pci_rc < 0) ? pci_rc : 0; } /** * i7300_init() - Unregisters the driver */ static void __exit i7300_exit(void) { debugf2("MC: " __FILE__ ": %s()\n", __func__); pci_unregister_driver(&i7300_driver); } module_init(i7300_init); module_exit(i7300_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>"); MODULE_AUTHOR("Red Hat Inc. (http://www.redhat.com)"); MODULE_DESCRIPTION("MC Driver for Intel I7300 memory controllers - " I7300_REVISION); module_param(edac_op_state, int, 0444); MODULE_PARM_DESC(edac_op_state, "EDAC Error Reporting state: 0=Poll,1=NMI");
gpl-2.0
zymphad/leanKernel-angler
drivers/isdn/gigaset/bas-gigaset.c
2778
72975
/* * USB driver for Gigaset 307x base via direct USB connection. * * Copyright (c) 2001 by Hansjoerg Lipp <hjlipp@web.de>, * Tilman Schmidt <tilman@imap.cc>, * Stefan Eilers. * * ===================================================================== * 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 "gigaset.h" #include <linux/usb.h> #include <linux/module.h> #include <linux/moduleparam.h> /* Version Information */ #define DRIVER_AUTHOR "Tilman Schmidt <tilman@imap.cc>, Hansjoerg Lipp <hjlipp@web.de>, Stefan Eilers" #define DRIVER_DESC "USB Driver for Gigaset 307x" /* Module parameters */ static int startmode = SM_ISDN; static int cidmode = 1; module_param(startmode, int, S_IRUGO); module_param(cidmode, int, S_IRUGO); MODULE_PARM_DESC(startmode, "start in isdn4linux mode"); MODULE_PARM_DESC(cidmode, "Call-ID mode"); #define GIGASET_MINORS 1 #define GIGASET_MINOR 16 #define GIGASET_MODULENAME "bas_gigaset" #define GIGASET_DEVNAME "ttyGB" /* length limit according to Siemens 3070usb-protokoll.doc ch. 2.1 */ #define IF_WRITEBUF 264 /* interrupt pipe message size according to ibid. ch. 2.2 */ #define IP_MSGSIZE 3 /* Values for the Gigaset 307x */ #define USB_GIGA_VENDOR_ID 0x0681 #define USB_3070_PRODUCT_ID 0x0001 #define USB_3075_PRODUCT_ID 0x0002 #define USB_SX303_PRODUCT_ID 0x0021 #define USB_SX353_PRODUCT_ID 0x0022 /* table of devices that work with this driver */ static const struct usb_device_id gigaset_table[] = { { USB_DEVICE(USB_GIGA_VENDOR_ID, USB_3070_PRODUCT_ID) }, { USB_DEVICE(USB_GIGA_VENDOR_ID, USB_3075_PRODUCT_ID) }, { USB_DEVICE(USB_GIGA_VENDOR_ID, USB_SX303_PRODUCT_ID) }, { USB_DEVICE(USB_GIGA_VENDOR_ID, USB_SX353_PRODUCT_ID) }, { } /* Terminating entry */ }; MODULE_DEVICE_TABLE(usb, gigaset_table); /*======================= local function prototypes ==========================*/ /* function called if a new device belonging to this driver is connected */ static int gigaset_probe(struct usb_interface *interface, const struct usb_device_id *id); /* Function will be called if the device is unplugged */ static void gigaset_disconnect(struct usb_interface *interface); /* functions called before/after suspend */ static int gigaset_suspend(struct usb_interface *intf, pm_message_t message); static int gigaset_resume(struct usb_interface *intf); /* functions called before/after device reset */ static int gigaset_pre_reset(struct usb_interface *intf); static int gigaset_post_reset(struct usb_interface *intf); static int atread_submit(struct cardstate *, int); static void stopurbs(struct bas_bc_state *); static int req_submit(struct bc_state *, int, int, int); static int atwrite_submit(struct cardstate *, unsigned char *, int); static int start_cbsend(struct cardstate *); /*============================================================================*/ struct bas_cardstate { struct usb_device *udev; /* USB device pointer */ struct usb_interface *interface; /* interface for this device */ unsigned char minor; /* starting minor number */ struct urb *urb_ctrl; /* control pipe default URB */ struct usb_ctrlrequest dr_ctrl; struct timer_list timer_ctrl; /* control request timeout */ int retry_ctrl; struct timer_list timer_atrdy; /* AT command ready timeout */ struct urb *urb_cmd_out; /* for sending AT commands */ struct usb_ctrlrequest dr_cmd_out; int retry_cmd_out; struct urb *urb_cmd_in; /* for receiving AT replies */ struct usb_ctrlrequest dr_cmd_in; struct timer_list timer_cmd_in; /* receive request timeout */ unsigned char *rcvbuf; /* AT reply receive buffer */ struct urb *urb_int_in; /* URB for interrupt pipe */ unsigned char *int_in_buf; struct work_struct int_in_wq; /* for usb_clear_halt() */ struct timer_list timer_int_in; /* int read retry delay */ int retry_int_in; spinlock_t lock; /* locks all following */ int basstate; /* bitmap (BS_*) */ int pending; /* uncompleted base request */ wait_queue_head_t waitqueue; int rcvbuf_size; /* size of AT receive buffer */ /* 0: no receive in progress */ int retry_cmd_in; /* receive req retry count */ }; /* status of direct USB connection to 307x base (bits in basstate) */ #define BS_ATOPEN 0x001 /* AT channel open */ #define BS_B1OPEN 0x002 /* B channel 1 open */ #define BS_B2OPEN 0x004 /* B channel 2 open */ #define BS_ATREADY 0x008 /* base ready for AT command */ #define BS_INIT 0x010 /* base has signalled INIT_OK */ #define BS_ATTIMER 0x020 /* waiting for HD_READY_SEND_ATDATA */ #define BS_ATRDPEND 0x040 /* urb_cmd_in in use */ #define BS_ATWRPEND 0x080 /* urb_cmd_out in use */ #define BS_SUSPEND 0x100 /* USB port suspended */ #define BS_RESETTING 0x200 /* waiting for HD_RESET_INTERRUPT_PIPE_ACK */ static struct gigaset_driver *driver; /* usb specific object needed to register this driver with the usb subsystem */ static struct usb_driver gigaset_usb_driver = { .name = GIGASET_MODULENAME, .probe = gigaset_probe, .disconnect = gigaset_disconnect, .id_table = gigaset_table, .suspend = gigaset_suspend, .resume = gigaset_resume, .reset_resume = gigaset_post_reset, .pre_reset = gigaset_pre_reset, .post_reset = gigaset_post_reset, .disable_hub_initiated_lpm = 1, }; /* get message text for usb_submit_urb return code */ static char *get_usb_rcmsg(int rc) { static char unkmsg[28]; switch (rc) { case 0: return "success"; case -ENOMEM: return "out of memory"; case -ENODEV: return "device not present"; case -ENOENT: return "endpoint not present"; case -ENXIO: return "URB type not supported"; case -EINVAL: return "invalid argument"; case -EAGAIN: return "start frame too early or too much scheduled"; case -EFBIG: return "too many isoc frames requested"; case -EPIPE: return "endpoint stalled"; case -EMSGSIZE: return "invalid packet size"; case -ENOSPC: return "would overcommit USB bandwidth"; case -ESHUTDOWN: return "device shut down"; case -EPERM: return "reject flag set"; case -EHOSTUNREACH: return "device suspended"; default: snprintf(unkmsg, sizeof(unkmsg), "unknown error %d", rc); return unkmsg; } } /* get message text for USB status code */ static char *get_usb_statmsg(int status) { static char unkmsg[28]; switch (status) { case 0: return "success"; case -ENOENT: return "unlinked (sync)"; case -EINPROGRESS: return "URB still pending"; case -EPROTO: return "bitstuff error, timeout, or unknown USB error"; case -EILSEQ: return "CRC mismatch, timeout, or unknown USB error"; case -ETIME: return "USB response timeout"; case -EPIPE: return "endpoint stalled"; case -ECOMM: return "IN buffer overrun"; case -ENOSR: return "OUT buffer underrun"; case -EOVERFLOW: return "endpoint babble"; case -EREMOTEIO: return "short packet"; case -ENODEV: return "device removed"; case -EXDEV: return "partial isoc transfer"; case -EINVAL: return "ISO madness"; case -ECONNRESET: return "unlinked (async)"; case -ESHUTDOWN: return "device shut down"; default: snprintf(unkmsg, sizeof(unkmsg), "unknown status %d", status); return unkmsg; } } /* usb_pipetype_str * retrieve string representation of USB pipe type */ static inline char *usb_pipetype_str(int pipe) { if (usb_pipeisoc(pipe)) return "Isoc"; if (usb_pipeint(pipe)) return "Int"; if (usb_pipecontrol(pipe)) return "Ctrl"; if (usb_pipebulk(pipe)) return "Bulk"; return "?"; } /* dump_urb * write content of URB to syslog for debugging */ static inline void dump_urb(enum debuglevel level, const char *tag, struct urb *urb) { #ifdef CONFIG_GIGASET_DEBUG int i; gig_dbg(level, "%s urb(0x%08lx)->{", tag, (unsigned long) urb); if (urb) { gig_dbg(level, " dev=0x%08lx, pipe=%s:EP%d/DV%d:%s, " "hcpriv=0x%08lx, transfer_flags=0x%x,", (unsigned long) urb->dev, usb_pipetype_str(urb->pipe), usb_pipeendpoint(urb->pipe), usb_pipedevice(urb->pipe), usb_pipein(urb->pipe) ? "in" : "out", (unsigned long) urb->hcpriv, urb->transfer_flags); gig_dbg(level, " transfer_buffer=0x%08lx[%d], actual_length=%d, " "setup_packet=0x%08lx,", (unsigned long) urb->transfer_buffer, urb->transfer_buffer_length, urb->actual_length, (unsigned long) urb->setup_packet); gig_dbg(level, " start_frame=%d, number_of_packets=%d, interval=%d, " "error_count=%d,", urb->start_frame, urb->number_of_packets, urb->interval, urb->error_count); gig_dbg(level, " context=0x%08lx, complete=0x%08lx, " "iso_frame_desc[]={", (unsigned long) urb->context, (unsigned long) urb->complete); for (i = 0; i < urb->number_of_packets; i++) { struct usb_iso_packet_descriptor *pifd = &urb->iso_frame_desc[i]; gig_dbg(level, " {offset=%u, length=%u, actual_length=%u, " "status=%u}", pifd->offset, pifd->length, pifd->actual_length, pifd->status); } } gig_dbg(level, "}}"); #endif } /* read/set modem control bits etc. (m10x only) */ static int gigaset_set_modem_ctrl(struct cardstate *cs, unsigned old_state, unsigned new_state) { return -EINVAL; } static int gigaset_baud_rate(struct cardstate *cs, unsigned cflag) { return -EINVAL; } static int gigaset_set_line_ctrl(struct cardstate *cs, unsigned cflag) { return -EINVAL; } /* set/clear bits in base connection state, return previous state */ static inline int update_basstate(struct bas_cardstate *ucs, int set, int clear) { unsigned long flags; int state; spin_lock_irqsave(&ucs->lock, flags); state = ucs->basstate; ucs->basstate = (state & ~clear) | set; spin_unlock_irqrestore(&ucs->lock, flags); return state; } /* error_hangup * hang up any existing connection because of an unrecoverable error * This function may be called from any context and takes care of scheduling * the necessary actions for execution outside of interrupt context. * cs->lock must not be held. * argument: * B channel control structure */ static inline void error_hangup(struct bc_state *bcs) { struct cardstate *cs = bcs->cs; gigaset_add_event(cs, &bcs->at_state, EV_HUP, NULL, 0, NULL); gigaset_schedule_event(cs); } /* error_reset * reset Gigaset device because of an unrecoverable error * This function may be called from any context, and takes care of * scheduling the necessary actions for execution outside of interrupt context. * cs->hw.bas->lock must not be held. * argument: * controller state structure */ static inline void error_reset(struct cardstate *cs) { /* reset interrupt pipe to recover (ignore errors) */ update_basstate(cs->hw.bas, BS_RESETTING, 0); if (req_submit(cs->bcs, HD_RESET_INTERRUPT_PIPE, 0, BAS_TIMEOUT)) /* submission failed, escalate to USB port reset */ usb_queue_reset_device(cs->hw.bas->interface); } /* check_pending * check for completion of pending control request * parameter: * ucs hardware specific controller state structure */ static void check_pending(struct bas_cardstate *ucs) { unsigned long flags; spin_lock_irqsave(&ucs->lock, flags); switch (ucs->pending) { case 0: break; case HD_OPEN_ATCHANNEL: if (ucs->basstate & BS_ATOPEN) ucs->pending = 0; break; case HD_OPEN_B1CHANNEL: if (ucs->basstate & BS_B1OPEN) ucs->pending = 0; break; case HD_OPEN_B2CHANNEL: if (ucs->basstate & BS_B2OPEN) ucs->pending = 0; break; case HD_CLOSE_ATCHANNEL: if (!(ucs->basstate & BS_ATOPEN)) ucs->pending = 0; break; case HD_CLOSE_B1CHANNEL: if (!(ucs->basstate & BS_B1OPEN)) ucs->pending = 0; break; case HD_CLOSE_B2CHANNEL: if (!(ucs->basstate & BS_B2OPEN)) ucs->pending = 0; break; case HD_DEVICE_INIT_ACK: /* no reply expected */ ucs->pending = 0; break; case HD_RESET_INTERRUPT_PIPE: if (!(ucs->basstate & BS_RESETTING)) ucs->pending = 0; break; /* * HD_READ_ATMESSAGE and HD_WRITE_ATMESSAGE are handled separately * and should never end up here */ default: dev_warn(&ucs->interface->dev, "unknown pending request 0x%02x cleared\n", ucs->pending); ucs->pending = 0; } if (!ucs->pending) del_timer(&ucs->timer_ctrl); spin_unlock_irqrestore(&ucs->lock, flags); } /* cmd_in_timeout * timeout routine for command input request * argument: * controller state structure */ static void cmd_in_timeout(unsigned long data) { struct cardstate *cs = (struct cardstate *) data; struct bas_cardstate *ucs = cs->hw.bas; int rc; if (!ucs->rcvbuf_size) { gig_dbg(DEBUG_USBREQ, "%s: no receive in progress", __func__); return; } if (ucs->retry_cmd_in++ >= BAS_RETRY) { dev_err(cs->dev, "control read: timeout, giving up after %d tries\n", ucs->retry_cmd_in); kfree(ucs->rcvbuf); ucs->rcvbuf = NULL; ucs->rcvbuf_size = 0; error_reset(cs); return; } gig_dbg(DEBUG_USBREQ, "%s: timeout, retry %d", __func__, ucs->retry_cmd_in); rc = atread_submit(cs, BAS_TIMEOUT); if (rc < 0) { kfree(ucs->rcvbuf); ucs->rcvbuf = NULL; ucs->rcvbuf_size = 0; if (rc != -ENODEV) error_reset(cs); } } /* read_ctrl_callback * USB completion handler for control pipe input * called by the USB subsystem in interrupt context * parameter: * urb USB request block * urb->context = inbuf structure for controller state */ static void read_ctrl_callback(struct urb *urb) { struct inbuf_t *inbuf = urb->context; struct cardstate *cs = inbuf->cs; struct bas_cardstate *ucs = cs->hw.bas; int status = urb->status; unsigned numbytes; int rc; update_basstate(ucs, 0, BS_ATRDPEND); wake_up(&ucs->waitqueue); del_timer(&ucs->timer_cmd_in); switch (status) { case 0: /* normal completion */ numbytes = urb->actual_length; if (unlikely(numbytes != ucs->rcvbuf_size)) { dev_warn(cs->dev, "control read: received %d chars, expected %d\n", numbytes, ucs->rcvbuf_size); if (numbytes > ucs->rcvbuf_size) numbytes = ucs->rcvbuf_size; } /* copy received bytes to inbuf, notify event layer */ if (gigaset_fill_inbuf(inbuf, ucs->rcvbuf, numbytes)) { gig_dbg(DEBUG_INTR, "%s-->BH", __func__); gigaset_schedule_event(cs); } break; case -ENOENT: /* cancelled */ case -ECONNRESET: /* cancelled (async) */ case -EINPROGRESS: /* pending */ case -ENODEV: /* device removed */ case -ESHUTDOWN: /* device shut down */ /* no further action necessary */ gig_dbg(DEBUG_USBREQ, "%s: %s", __func__, get_usb_statmsg(status)); break; default: /* other errors: retry */ if (ucs->retry_cmd_in++ < BAS_RETRY) { gig_dbg(DEBUG_USBREQ, "%s: %s, retry %d", __func__, get_usb_statmsg(status), ucs->retry_cmd_in); rc = atread_submit(cs, BAS_TIMEOUT); if (rc >= 0) /* successfully resubmitted, skip freeing */ return; if (rc == -ENODEV) /* disconnect, no further action necessary */ break; } dev_err(cs->dev, "control read: %s, giving up after %d tries\n", get_usb_statmsg(status), ucs->retry_cmd_in); error_reset(cs); } /* read finished, free buffer */ kfree(ucs->rcvbuf); ucs->rcvbuf = NULL; ucs->rcvbuf_size = 0; } /* atread_submit * submit an HD_READ_ATMESSAGE command URB and optionally start a timeout * parameters: * cs controller state structure * timeout timeout in 1/10 sec., 0: none * return value: * 0 on success * -EBUSY if another request is pending * any URB submission error code */ static int atread_submit(struct cardstate *cs, int timeout) { struct bas_cardstate *ucs = cs->hw.bas; int basstate; int ret; gig_dbg(DEBUG_USBREQ, "-------> HD_READ_ATMESSAGE (%d)", ucs->rcvbuf_size); basstate = update_basstate(ucs, BS_ATRDPEND, 0); if (basstate & BS_ATRDPEND) { dev_err(cs->dev, "could not submit HD_READ_ATMESSAGE: URB busy\n"); return -EBUSY; } if (basstate & BS_SUSPEND) { dev_notice(cs->dev, "HD_READ_ATMESSAGE not submitted, " "suspend in progress\n"); update_basstate(ucs, 0, BS_ATRDPEND); /* treat like disconnect */ return -ENODEV; } ucs->dr_cmd_in.bRequestType = IN_VENDOR_REQ; ucs->dr_cmd_in.bRequest = HD_READ_ATMESSAGE; ucs->dr_cmd_in.wValue = 0; ucs->dr_cmd_in.wIndex = 0; ucs->dr_cmd_in.wLength = cpu_to_le16(ucs->rcvbuf_size); usb_fill_control_urb(ucs->urb_cmd_in, ucs->udev, usb_rcvctrlpipe(ucs->udev, 0), (unsigned char *) &ucs->dr_cmd_in, ucs->rcvbuf, ucs->rcvbuf_size, read_ctrl_callback, cs->inbuf); ret = usb_submit_urb(ucs->urb_cmd_in, GFP_ATOMIC); if (ret != 0) { update_basstate(ucs, 0, BS_ATRDPEND); dev_err(cs->dev, "could not submit HD_READ_ATMESSAGE: %s\n", get_usb_rcmsg(ret)); return ret; } if (timeout > 0) { gig_dbg(DEBUG_USBREQ, "setting timeout of %d/10 secs", timeout); mod_timer(&ucs->timer_cmd_in, jiffies + timeout * HZ / 10); } return 0; } /* int_in_work * workqueue routine to clear halt on interrupt in endpoint */ static void int_in_work(struct work_struct *work) { struct bas_cardstate *ucs = container_of(work, struct bas_cardstate, int_in_wq); struct urb *urb = ucs->urb_int_in; struct cardstate *cs = urb->context; int rc; /* clear halt condition */ rc = usb_clear_halt(ucs->udev, urb->pipe); gig_dbg(DEBUG_USBREQ, "clear_halt: %s", get_usb_rcmsg(rc)); if (rc == 0) /* success, resubmit interrupt read URB */ rc = usb_submit_urb(urb, GFP_ATOMIC); switch (rc) { case 0: /* success */ case -ENODEV: /* device gone */ case -EINVAL: /* URB already resubmitted, or terminal badness */ break; default: /* failure: try to recover by resetting the device */ dev_err(cs->dev, "clear halt failed: %s\n", get_usb_rcmsg(rc)); rc = usb_lock_device_for_reset(ucs->udev, ucs->interface); if (rc == 0) { rc = usb_reset_device(ucs->udev); usb_unlock_device(ucs->udev); } } ucs->retry_int_in = 0; } /* int_in_resubmit * timer routine for interrupt read delayed resubmit * argument: * controller state structure */ static void int_in_resubmit(unsigned long data) { struct cardstate *cs = (struct cardstate *) data; struct bas_cardstate *ucs = cs->hw.bas; int rc; if (ucs->retry_int_in++ >= BAS_RETRY) { dev_err(cs->dev, "interrupt read: giving up after %d tries\n", ucs->retry_int_in); usb_queue_reset_device(ucs->interface); return; } gig_dbg(DEBUG_USBREQ, "%s: retry %d", __func__, ucs->retry_int_in); rc = usb_submit_urb(ucs->urb_int_in, GFP_ATOMIC); if (rc != 0 && rc != -ENODEV) { dev_err(cs->dev, "could not resubmit interrupt URB: %s\n", get_usb_rcmsg(rc)); usb_queue_reset_device(ucs->interface); } } /* read_int_callback * USB completion handler for interrupt pipe input * called by the USB subsystem in interrupt context * parameter: * urb USB request block * urb->context = controller state structure */ static void read_int_callback(struct urb *urb) { struct cardstate *cs = urb->context; struct bas_cardstate *ucs = cs->hw.bas; struct bc_state *bcs; int status = urb->status; unsigned long flags; int rc; unsigned l; int channel; switch (status) { case 0: /* success */ ucs->retry_int_in = 0; break; case -EPIPE: /* endpoint stalled */ schedule_work(&ucs->int_in_wq); /* fall through */ case -ENOENT: /* cancelled */ case -ECONNRESET: /* cancelled (async) */ case -EINPROGRESS: /* pending */ case -ENODEV: /* device removed */ case -ESHUTDOWN: /* device shut down */ /* no further action necessary */ gig_dbg(DEBUG_USBREQ, "%s: %s", __func__, get_usb_statmsg(status)); return; case -EPROTO: /* protocol error or unplug */ case -EILSEQ: case -ETIME: /* resubmit after delay */ gig_dbg(DEBUG_USBREQ, "%s: %s", __func__, get_usb_statmsg(status)); mod_timer(&ucs->timer_int_in, jiffies + HZ / 10); return; default: /* other errors: just resubmit */ dev_warn(cs->dev, "interrupt read: %s\n", get_usb_statmsg(status)); goto resubmit; } /* drop incomplete packets even if the missing bytes wouldn't matter */ if (unlikely(urb->actual_length < IP_MSGSIZE)) { dev_warn(cs->dev, "incomplete interrupt packet (%d bytes)\n", urb->actual_length); goto resubmit; } l = (unsigned) ucs->int_in_buf[1] + (((unsigned) ucs->int_in_buf[2]) << 8); gig_dbg(DEBUG_USBREQ, "<-------%d: 0x%02x (%u [0x%02x 0x%02x])", urb->actual_length, (int)ucs->int_in_buf[0], l, (int)ucs->int_in_buf[1], (int)ucs->int_in_buf[2]); channel = 0; switch (ucs->int_in_buf[0]) { case HD_DEVICE_INIT_OK: update_basstate(ucs, BS_INIT, 0); break; case HD_READY_SEND_ATDATA: del_timer(&ucs->timer_atrdy); update_basstate(ucs, BS_ATREADY, BS_ATTIMER); start_cbsend(cs); break; case HD_OPEN_B2CHANNEL_ACK: ++channel; case HD_OPEN_B1CHANNEL_ACK: bcs = cs->bcs + channel; update_basstate(ucs, BS_B1OPEN << channel, 0); gigaset_bchannel_up(bcs); break; case HD_OPEN_ATCHANNEL_ACK: update_basstate(ucs, BS_ATOPEN, 0); start_cbsend(cs); break; case HD_CLOSE_B2CHANNEL_ACK: ++channel; case HD_CLOSE_B1CHANNEL_ACK: bcs = cs->bcs + channel; update_basstate(ucs, 0, BS_B1OPEN << channel); stopurbs(bcs->hw.bas); gigaset_bchannel_down(bcs); break; case HD_CLOSE_ATCHANNEL_ACK: update_basstate(ucs, 0, BS_ATOPEN); break; case HD_B2_FLOW_CONTROL: ++channel; case HD_B1_FLOW_CONTROL: bcs = cs->bcs + channel; atomic_add((l - BAS_NORMFRAME) * BAS_CORRFRAMES, &bcs->hw.bas->corrbytes); gig_dbg(DEBUG_ISO, "Flow control (channel %d, sub %d): 0x%02x => %d", channel, bcs->hw.bas->numsub, l, atomic_read(&bcs->hw.bas->corrbytes)); break; case HD_RECEIVEATDATA_ACK: /* AT response ready to be received */ if (!l) { dev_warn(cs->dev, "HD_RECEIVEATDATA_ACK with length 0 ignored\n"); break; } spin_lock_irqsave(&cs->lock, flags); if (ucs->basstate & BS_ATRDPEND) { spin_unlock_irqrestore(&cs->lock, flags); dev_warn(cs->dev, "HD_RECEIVEATDATA_ACK(%d) during HD_READ_ATMESSAGE(%d) ignored\n", l, ucs->rcvbuf_size); break; } if (ucs->rcvbuf_size) { /* throw away previous buffer - we have no queue */ dev_err(cs->dev, "receive AT data overrun, %d bytes lost\n", ucs->rcvbuf_size); kfree(ucs->rcvbuf); ucs->rcvbuf_size = 0; } ucs->rcvbuf = kmalloc(l, GFP_ATOMIC); if (ucs->rcvbuf == NULL) { spin_unlock_irqrestore(&cs->lock, flags); dev_err(cs->dev, "out of memory receiving AT data\n"); break; } ucs->rcvbuf_size = l; ucs->retry_cmd_in = 0; rc = atread_submit(cs, BAS_TIMEOUT); if (rc < 0) { kfree(ucs->rcvbuf); ucs->rcvbuf = NULL; ucs->rcvbuf_size = 0; } spin_unlock_irqrestore(&cs->lock, flags); if (rc < 0 && rc != -ENODEV) error_reset(cs); break; case HD_RESET_INTERRUPT_PIPE_ACK: update_basstate(ucs, 0, BS_RESETTING); dev_notice(cs->dev, "interrupt pipe reset\n"); break; case HD_SUSPEND_END: gig_dbg(DEBUG_USBREQ, "HD_SUSPEND_END"); break; default: dev_warn(cs->dev, "unknown Gigaset signal 0x%02x (%u) ignored\n", (int) ucs->int_in_buf[0], l); } check_pending(ucs); wake_up(&ucs->waitqueue); resubmit: rc = usb_submit_urb(urb, GFP_ATOMIC); if (unlikely(rc != 0 && rc != -ENODEV)) { dev_err(cs->dev, "could not resubmit interrupt URB: %s\n", get_usb_rcmsg(rc)); error_reset(cs); } } /* read_iso_callback * USB completion handler for B channel isochronous input * called by the USB subsystem in interrupt context * parameter: * urb USB request block of completed request * urb->context = bc_state structure */ static void read_iso_callback(struct urb *urb) { struct bc_state *bcs; struct bas_bc_state *ubc; int status = urb->status; unsigned long flags; int i, rc; /* status codes not worth bothering the tasklet with */ if (unlikely(status == -ENOENT || status == -ECONNRESET || status == -EINPROGRESS || status == -ENODEV || status == -ESHUTDOWN)) { gig_dbg(DEBUG_ISO, "%s: %s", __func__, get_usb_statmsg(status)); return; } bcs = urb->context; ubc = bcs->hw.bas; spin_lock_irqsave(&ubc->isoinlock, flags); if (likely(ubc->isoindone == NULL)) { /* pass URB to tasklet */ ubc->isoindone = urb; ubc->isoinstatus = status; tasklet_hi_schedule(&ubc->rcvd_tasklet); } else { /* tasklet still busy, drop data and resubmit URB */ gig_dbg(DEBUG_ISO, "%s: overrun", __func__); ubc->loststatus = status; for (i = 0; i < BAS_NUMFRAMES; i++) { ubc->isoinlost += urb->iso_frame_desc[i].actual_length; if (unlikely(urb->iso_frame_desc[i].status != 0 && urb->iso_frame_desc[i].status != -EINPROGRESS)) ubc->loststatus = urb->iso_frame_desc[i].status; urb->iso_frame_desc[i].status = 0; urb->iso_frame_desc[i].actual_length = 0; } if (likely(ubc->running)) { /* urb->dev is clobbered by USB subsystem */ urb->dev = bcs->cs->hw.bas->udev; urb->transfer_flags = URB_ISO_ASAP; urb->number_of_packets = BAS_NUMFRAMES; rc = usb_submit_urb(urb, GFP_ATOMIC); if (unlikely(rc != 0 && rc != -ENODEV)) { dev_err(bcs->cs->dev, "could not resubmit isoc read URB: %s\n", get_usb_rcmsg(rc)); dump_urb(DEBUG_ISO, "isoc read", urb); error_hangup(bcs); } } } spin_unlock_irqrestore(&ubc->isoinlock, flags); } /* write_iso_callback * USB completion handler for B channel isochronous output * called by the USB subsystem in interrupt context * parameter: * urb USB request block of completed request * urb->context = isow_urbctx_t structure */ static void write_iso_callback(struct urb *urb) { struct isow_urbctx_t *ucx; struct bas_bc_state *ubc; int status = urb->status; unsigned long flags; /* status codes not worth bothering the tasklet with */ if (unlikely(status == -ENOENT || status == -ECONNRESET || status == -EINPROGRESS || status == -ENODEV || status == -ESHUTDOWN)) { gig_dbg(DEBUG_ISO, "%s: %s", __func__, get_usb_statmsg(status)); return; } /* pass URB context to tasklet */ ucx = urb->context; ubc = ucx->bcs->hw.bas; ucx->status = status; spin_lock_irqsave(&ubc->isooutlock, flags); ubc->isooutovfl = ubc->isooutdone; ubc->isooutdone = ucx; spin_unlock_irqrestore(&ubc->isooutlock, flags); tasklet_hi_schedule(&ubc->sent_tasklet); } /* starturbs * prepare and submit USB request blocks for isochronous input and output * argument: * B channel control structure * return value: * 0 on success * < 0 on error (no URBs submitted) */ static int starturbs(struct bc_state *bcs) { struct bas_bc_state *ubc = bcs->hw.bas; struct urb *urb; int j, k; int rc; /* initialize L2 reception */ if (bcs->proto2 == L2_HDLC) bcs->inputstate |= INS_flag_hunt; /* submit all isochronous input URBs */ ubc->running = 1; for (k = 0; k < BAS_INURBS; k++) { urb = ubc->isoinurbs[k]; if (!urb) { rc = -EFAULT; goto error; } urb->dev = bcs->cs->hw.bas->udev; urb->pipe = usb_rcvisocpipe(urb->dev, 3 + 2 * bcs->channel); urb->transfer_flags = URB_ISO_ASAP; urb->transfer_buffer = ubc->isoinbuf + k * BAS_INBUFSIZE; urb->transfer_buffer_length = BAS_INBUFSIZE; urb->number_of_packets = BAS_NUMFRAMES; urb->interval = BAS_FRAMETIME; urb->complete = read_iso_callback; urb->context = bcs; for (j = 0; j < BAS_NUMFRAMES; j++) { urb->iso_frame_desc[j].offset = j * BAS_MAXFRAME; urb->iso_frame_desc[j].length = BAS_MAXFRAME; urb->iso_frame_desc[j].status = 0; urb->iso_frame_desc[j].actual_length = 0; } dump_urb(DEBUG_ISO, "Initial isoc read", urb); rc = usb_submit_urb(urb, GFP_ATOMIC); if (rc != 0) goto error; } /* initialize L2 transmission */ gigaset_isowbuf_init(ubc->isooutbuf, PPP_FLAG); /* set up isochronous output URBs for flag idling */ for (k = 0; k < BAS_OUTURBS; ++k) { urb = ubc->isoouturbs[k].urb; if (!urb) { rc = -EFAULT; goto error; } urb->dev = bcs->cs->hw.bas->udev; urb->pipe = usb_sndisocpipe(urb->dev, 4 + 2 * bcs->channel); urb->transfer_flags = URB_ISO_ASAP; urb->transfer_buffer = ubc->isooutbuf->data; urb->transfer_buffer_length = sizeof(ubc->isooutbuf->data); urb->number_of_packets = BAS_NUMFRAMES; urb->interval = BAS_FRAMETIME; urb->complete = write_iso_callback; urb->context = &ubc->isoouturbs[k]; for (j = 0; j < BAS_NUMFRAMES; ++j) { urb->iso_frame_desc[j].offset = BAS_OUTBUFSIZE; urb->iso_frame_desc[j].length = BAS_NORMFRAME; urb->iso_frame_desc[j].status = 0; urb->iso_frame_desc[j].actual_length = 0; } ubc->isoouturbs[k].limit = -1; } /* keep one URB free, submit the others */ for (k = 0; k < BAS_OUTURBS - 1; ++k) { dump_urb(DEBUG_ISO, "Initial isoc write", urb); rc = usb_submit_urb(ubc->isoouturbs[k].urb, GFP_ATOMIC); if (rc != 0) goto error; } dump_urb(DEBUG_ISO, "Initial isoc write (free)", urb); ubc->isooutfree = &ubc->isoouturbs[BAS_OUTURBS - 1]; ubc->isooutdone = ubc->isooutovfl = NULL; return 0; error: stopurbs(ubc); return rc; } /* stopurbs * cancel the USB request blocks for isochronous input and output * errors are silently ignored * argument: * B channel control structure */ static void stopurbs(struct bas_bc_state *ubc) { int k, rc; ubc->running = 0; for (k = 0; k < BAS_INURBS; ++k) { rc = usb_unlink_urb(ubc->isoinurbs[k]); gig_dbg(DEBUG_ISO, "%s: isoc input URB %d unlinked, result = %s", __func__, k, get_usb_rcmsg(rc)); } for (k = 0; k < BAS_OUTURBS; ++k) { rc = usb_unlink_urb(ubc->isoouturbs[k].urb); gig_dbg(DEBUG_ISO, "%s: isoc output URB %d unlinked, result = %s", __func__, k, get_usb_rcmsg(rc)); } } /* Isochronous Write - Bottom Half */ /* =============================== */ /* submit_iso_write_urb * fill and submit the next isochronous write URB * parameters: * ucx context structure containing URB * return value: * number of frames submitted in URB * 0 if URB not submitted because no data available (isooutbuf busy) * error code < 0 on error */ static int submit_iso_write_urb(struct isow_urbctx_t *ucx) { struct urb *urb = ucx->urb; struct bas_bc_state *ubc = ucx->bcs->hw.bas; struct usb_iso_packet_descriptor *ifd; int corrbytes, nframe, rc; /* urb->dev is clobbered by USB subsystem */ urb->dev = ucx->bcs->cs->hw.bas->udev; urb->transfer_flags = URB_ISO_ASAP; urb->transfer_buffer = ubc->isooutbuf->data; urb->transfer_buffer_length = sizeof(ubc->isooutbuf->data); for (nframe = 0; nframe < BAS_NUMFRAMES; nframe++) { ifd = &urb->iso_frame_desc[nframe]; /* compute frame length according to flow control */ ifd->length = BAS_NORMFRAME; corrbytes = atomic_read(&ubc->corrbytes); if (corrbytes != 0) { gig_dbg(DEBUG_ISO, "%s: corrbytes=%d", __func__, corrbytes); if (corrbytes > BAS_HIGHFRAME - BAS_NORMFRAME) corrbytes = BAS_HIGHFRAME - BAS_NORMFRAME; else if (corrbytes < BAS_LOWFRAME - BAS_NORMFRAME) corrbytes = BAS_LOWFRAME - BAS_NORMFRAME; ifd->length += corrbytes; atomic_add(-corrbytes, &ubc->corrbytes); } /* retrieve block of data to send */ rc = gigaset_isowbuf_getbytes(ubc->isooutbuf, ifd->length); if (rc < 0) { if (rc == -EBUSY) { gig_dbg(DEBUG_ISO, "%s: buffer busy at frame %d", __func__, nframe); /* tasklet will be restarted from gigaset_isoc_send_skb() */ } else { dev_err(ucx->bcs->cs->dev, "%s: buffer error %d at frame %d\n", __func__, rc, nframe); return rc; } break; } ifd->offset = rc; ucx->limit = ubc->isooutbuf->nextread; ifd->status = 0; ifd->actual_length = 0; } if (unlikely(nframe == 0)) return 0; /* no data to send */ urb->number_of_packets = nframe; rc = usb_submit_urb(urb, GFP_ATOMIC); if (unlikely(rc)) { if (rc == -ENODEV) /* device removed - give up silently */ gig_dbg(DEBUG_ISO, "%s: disconnected", __func__); else dev_err(ucx->bcs->cs->dev, "could not submit isoc write URB: %s\n", get_usb_rcmsg(rc)); return rc; } ++ubc->numsub; return nframe; } /* write_iso_tasklet * tasklet scheduled when an isochronous output URB from the Gigaset device * has completed * parameter: * data B channel state structure */ static void write_iso_tasklet(unsigned long data) { struct bc_state *bcs = (struct bc_state *) data; struct bas_bc_state *ubc = bcs->hw.bas; struct cardstate *cs = bcs->cs; struct isow_urbctx_t *done, *next, *ovfl; struct urb *urb; int status; struct usb_iso_packet_descriptor *ifd; unsigned long flags; int i; struct sk_buff *skb; int len; int rc; /* loop while completed URBs arrive in time */ for (;;) { if (unlikely(!(ubc->running))) { gig_dbg(DEBUG_ISO, "%s: not running", __func__); return; } /* retrieve completed URBs */ spin_lock_irqsave(&ubc->isooutlock, flags); done = ubc->isooutdone; ubc->isooutdone = NULL; ovfl = ubc->isooutovfl; ubc->isooutovfl = NULL; spin_unlock_irqrestore(&ubc->isooutlock, flags); if (ovfl) { dev_err(cs->dev, "isoc write underrun\n"); error_hangup(bcs); break; } if (!done) break; /* submit free URB if available */ spin_lock_irqsave(&ubc->isooutlock, flags); next = ubc->isooutfree; ubc->isooutfree = NULL; spin_unlock_irqrestore(&ubc->isooutlock, flags); if (next) { rc = submit_iso_write_urb(next); if (unlikely(rc <= 0 && rc != -ENODEV)) { /* could not submit URB, put it back */ spin_lock_irqsave(&ubc->isooutlock, flags); if (ubc->isooutfree == NULL) { ubc->isooutfree = next; next = NULL; } spin_unlock_irqrestore(&ubc->isooutlock, flags); if (next) { /* couldn't put it back */ dev_err(cs->dev, "losing isoc write URB\n"); error_hangup(bcs); } } } /* process completed URB */ urb = done->urb; status = done->status; switch (status) { case -EXDEV: /* partial completion */ gig_dbg(DEBUG_ISO, "%s: URB partially completed", __func__); /* fall through - what's the difference anyway? */ case 0: /* normal completion */ /* inspect individual frames * assumptions (for lack of documentation): * - actual_length bytes of first frame in error are * successfully sent * - all following frames are not sent at all */ for (i = 0; i < BAS_NUMFRAMES; i++) { ifd = &urb->iso_frame_desc[i]; if (ifd->status || ifd->actual_length != ifd->length) { dev_warn(cs->dev, "isoc write: frame %d[%d/%d]: %s\n", i, ifd->actual_length, ifd->length, get_usb_statmsg(ifd->status)); break; } } break; case -EPIPE: /* stall - probably underrun */ dev_err(cs->dev, "isoc write: stalled\n"); error_hangup(bcs); break; default: /* other errors */ dev_warn(cs->dev, "isoc write: %s\n", get_usb_statmsg(status)); } /* mark the write buffer area covered by this URB as free */ if (done->limit >= 0) ubc->isooutbuf->read = done->limit; /* mark URB as free */ spin_lock_irqsave(&ubc->isooutlock, flags); next = ubc->isooutfree; ubc->isooutfree = done; spin_unlock_irqrestore(&ubc->isooutlock, flags); if (next) { /* only one URB still active - resubmit one */ rc = submit_iso_write_urb(next); if (unlikely(rc <= 0 && rc != -ENODEV)) { /* couldn't submit */ error_hangup(bcs); } } } /* process queued SKBs */ while ((skb = skb_dequeue(&bcs->squeue))) { /* copy to output buffer, doing L2 encapsulation */ len = skb->len; if (gigaset_isoc_buildframe(bcs, skb->data, len) == -EAGAIN) { /* insufficient buffer space, push back onto queue */ skb_queue_head(&bcs->squeue, skb); gig_dbg(DEBUG_ISO, "%s: skb requeued, qlen=%d", __func__, skb_queue_len(&bcs->squeue)); break; } skb_pull(skb, len); gigaset_skb_sent(bcs, skb); dev_kfree_skb_any(skb); } } /* Isochronous Read - Bottom Half */ /* ============================== */ /* read_iso_tasklet * tasklet scheduled when an isochronous input URB from the Gigaset device * has completed * parameter: * data B channel state structure */ static void read_iso_tasklet(unsigned long data) { struct bc_state *bcs = (struct bc_state *) data; struct bas_bc_state *ubc = bcs->hw.bas; struct cardstate *cs = bcs->cs; struct urb *urb; int status; struct usb_iso_packet_descriptor *ifd; char *rcvbuf; unsigned long flags; int totleft, numbytes, offset, frame, rc; /* loop while more completed URBs arrive in the meantime */ for (;;) { /* retrieve URB */ spin_lock_irqsave(&ubc->isoinlock, flags); urb = ubc->isoindone; if (!urb) { spin_unlock_irqrestore(&ubc->isoinlock, flags); return; } status = ubc->isoinstatus; ubc->isoindone = NULL; if (unlikely(ubc->loststatus != -EINPROGRESS)) { dev_warn(cs->dev, "isoc read overrun, URB dropped (status: %s, %d bytes)\n", get_usb_statmsg(ubc->loststatus), ubc->isoinlost); ubc->loststatus = -EINPROGRESS; } spin_unlock_irqrestore(&ubc->isoinlock, flags); if (unlikely(!(ubc->running))) { gig_dbg(DEBUG_ISO, "%s: channel not running, " "dropped URB with status: %s", __func__, get_usb_statmsg(status)); return; } switch (status) { case 0: /* normal completion */ break; case -EXDEV: /* inspect individual frames (we do that anyway) */ gig_dbg(DEBUG_ISO, "%s: URB partially completed", __func__); break; case -ENOENT: case -ECONNRESET: case -EINPROGRESS: gig_dbg(DEBUG_ISO, "%s: %s", __func__, get_usb_statmsg(status)); continue; /* -> skip */ case -EPIPE: dev_err(cs->dev, "isoc read: stalled\n"); error_hangup(bcs); continue; /* -> skip */ default: /* other error */ dev_warn(cs->dev, "isoc read: %s\n", get_usb_statmsg(status)); goto error; } rcvbuf = urb->transfer_buffer; totleft = urb->actual_length; for (frame = 0; totleft > 0 && frame < BAS_NUMFRAMES; frame++) { ifd = &urb->iso_frame_desc[frame]; numbytes = ifd->actual_length; switch (ifd->status) { case 0: /* success */ break; case -EPROTO: /* protocol error or unplug */ case -EILSEQ: case -ETIME: /* probably just disconnected, ignore */ gig_dbg(DEBUG_ISO, "isoc read: frame %d[%d]: %s\n", frame, numbytes, get_usb_statmsg(ifd->status)); break; default: /* other error */ /* report, assume transferred bytes are ok */ dev_warn(cs->dev, "isoc read: frame %d[%d]: %s\n", frame, numbytes, get_usb_statmsg(ifd->status)); } if (unlikely(numbytes > BAS_MAXFRAME)) dev_warn(cs->dev, "isoc read: frame %d[%d]: %s\n", frame, numbytes, "exceeds max frame size"); if (unlikely(numbytes > totleft)) { dev_warn(cs->dev, "isoc read: frame %d[%d]: %s\n", frame, numbytes, "exceeds total transfer length"); numbytes = totleft; } offset = ifd->offset; if (unlikely(offset + numbytes > BAS_INBUFSIZE)) { dev_warn(cs->dev, "isoc read: frame %d[%d]: %s\n", frame, numbytes, "exceeds end of buffer"); numbytes = BAS_INBUFSIZE - offset; } gigaset_isoc_receive(rcvbuf + offset, numbytes, bcs); totleft -= numbytes; } if (unlikely(totleft > 0)) dev_warn(cs->dev, "isoc read: %d data bytes missing\n", totleft); error: /* URB processed, resubmit */ for (frame = 0; frame < BAS_NUMFRAMES; frame++) { urb->iso_frame_desc[frame].status = 0; urb->iso_frame_desc[frame].actual_length = 0; } /* urb->dev is clobbered by USB subsystem */ urb->dev = bcs->cs->hw.bas->udev; urb->transfer_flags = URB_ISO_ASAP; urb->number_of_packets = BAS_NUMFRAMES; rc = usb_submit_urb(urb, GFP_ATOMIC); if (unlikely(rc != 0 && rc != -ENODEV)) { dev_err(cs->dev, "could not resubmit isoc read URB: %s\n", get_usb_rcmsg(rc)); dump_urb(DEBUG_ISO, "resubmit isoc read", urb); error_hangup(bcs); } } } /* Channel Operations */ /* ================== */ /* req_timeout * timeout routine for control output request * argument: * controller state structure */ static void req_timeout(unsigned long data) { struct cardstate *cs = (struct cardstate *) data; struct bas_cardstate *ucs = cs->hw.bas; int pending; unsigned long flags; check_pending(ucs); spin_lock_irqsave(&ucs->lock, flags); pending = ucs->pending; ucs->pending = 0; spin_unlock_irqrestore(&ucs->lock, flags); switch (pending) { case 0: /* no pending request */ gig_dbg(DEBUG_USBREQ, "%s: no request pending", __func__); break; case HD_OPEN_ATCHANNEL: dev_err(cs->dev, "timeout opening AT channel\n"); error_reset(cs); break; case HD_OPEN_B1CHANNEL: dev_err(cs->dev, "timeout opening channel 1\n"); error_hangup(&cs->bcs[0]); break; case HD_OPEN_B2CHANNEL: dev_err(cs->dev, "timeout opening channel 2\n"); error_hangup(&cs->bcs[1]); break; case HD_CLOSE_ATCHANNEL: dev_err(cs->dev, "timeout closing AT channel\n"); error_reset(cs); break; case HD_CLOSE_B1CHANNEL: dev_err(cs->dev, "timeout closing channel 1\n"); error_reset(cs); break; case HD_CLOSE_B2CHANNEL: dev_err(cs->dev, "timeout closing channel 2\n"); error_reset(cs); break; case HD_RESET_INTERRUPT_PIPE: /* error recovery escalation */ dev_err(cs->dev, "reset interrupt pipe timeout, attempting USB reset\n"); usb_queue_reset_device(ucs->interface); break; default: dev_warn(cs->dev, "request 0x%02x timed out, clearing\n", pending); } wake_up(&ucs->waitqueue); } /* write_ctrl_callback * USB completion handler for control pipe output * called by the USB subsystem in interrupt context * parameter: * urb USB request block of completed request * urb->context = hardware specific controller state structure */ static void write_ctrl_callback(struct urb *urb) { struct bas_cardstate *ucs = urb->context; int status = urb->status; int rc; unsigned long flags; /* check status */ switch (status) { case 0: /* normal completion */ spin_lock_irqsave(&ucs->lock, flags); switch (ucs->pending) { case HD_DEVICE_INIT_ACK: /* no reply expected */ del_timer(&ucs->timer_ctrl); ucs->pending = 0; break; } spin_unlock_irqrestore(&ucs->lock, flags); return; case -ENOENT: /* cancelled */ case -ECONNRESET: /* cancelled (async) */ case -EINPROGRESS: /* pending */ case -ENODEV: /* device removed */ case -ESHUTDOWN: /* device shut down */ /* ignore silently */ gig_dbg(DEBUG_USBREQ, "%s: %s", __func__, get_usb_statmsg(status)); break; default: /* any failure */ /* don't retry if suspend requested */ if (++ucs->retry_ctrl > BAS_RETRY || (ucs->basstate & BS_SUSPEND)) { dev_err(&ucs->interface->dev, "control request 0x%02x failed: %s\n", ucs->dr_ctrl.bRequest, get_usb_statmsg(status)); break; /* give up */ } dev_notice(&ucs->interface->dev, "control request 0x%02x: %s, retry %d\n", ucs->dr_ctrl.bRequest, get_usb_statmsg(status), ucs->retry_ctrl); /* urb->dev is clobbered by USB subsystem */ urb->dev = ucs->udev; rc = usb_submit_urb(urb, GFP_ATOMIC); if (unlikely(rc)) { dev_err(&ucs->interface->dev, "could not resubmit request 0x%02x: %s\n", ucs->dr_ctrl.bRequest, get_usb_rcmsg(rc)); break; } /* resubmitted */ return; } /* failed, clear pending request */ spin_lock_irqsave(&ucs->lock, flags); del_timer(&ucs->timer_ctrl); ucs->pending = 0; spin_unlock_irqrestore(&ucs->lock, flags); wake_up(&ucs->waitqueue); } /* req_submit * submit a control output request without message buffer to the Gigaset base * and optionally start a timeout * parameters: * bcs B channel control structure * req control request code (HD_*) * val control request parameter value (set to 0 if unused) * timeout timeout in seconds (0: no timeout) * return value: * 0 on success * -EBUSY if another request is pending * any URB submission error code */ static int req_submit(struct bc_state *bcs, int req, int val, int timeout) { struct bas_cardstate *ucs = bcs->cs->hw.bas; int ret; unsigned long flags; gig_dbg(DEBUG_USBREQ, "-------> 0x%02x (%d)", req, val); spin_lock_irqsave(&ucs->lock, flags); if (ucs->pending) { spin_unlock_irqrestore(&ucs->lock, flags); dev_err(bcs->cs->dev, "submission of request 0x%02x failed: " "request 0x%02x still pending\n", req, ucs->pending); return -EBUSY; } ucs->dr_ctrl.bRequestType = OUT_VENDOR_REQ; ucs->dr_ctrl.bRequest = req; ucs->dr_ctrl.wValue = cpu_to_le16(val); ucs->dr_ctrl.wIndex = 0; ucs->dr_ctrl.wLength = 0; usb_fill_control_urb(ucs->urb_ctrl, ucs->udev, usb_sndctrlpipe(ucs->udev, 0), (unsigned char *) &ucs->dr_ctrl, NULL, 0, write_ctrl_callback, ucs); ucs->retry_ctrl = 0; ret = usb_submit_urb(ucs->urb_ctrl, GFP_ATOMIC); if (unlikely(ret)) { dev_err(bcs->cs->dev, "could not submit request 0x%02x: %s\n", req, get_usb_rcmsg(ret)); spin_unlock_irqrestore(&ucs->lock, flags); return ret; } ucs->pending = req; if (timeout > 0) { gig_dbg(DEBUG_USBREQ, "setting timeout of %d/10 secs", timeout); mod_timer(&ucs->timer_ctrl, jiffies + timeout * HZ / 10); } spin_unlock_irqrestore(&ucs->lock, flags); return 0; } /* gigaset_init_bchannel * called by common.c to connect a B channel * initialize isochronous I/O and tell the Gigaset base to open the channel * argument: * B channel control structure * return value: * 0 on success, error code < 0 on error */ static int gigaset_init_bchannel(struct bc_state *bcs) { struct cardstate *cs = bcs->cs; int req, ret; unsigned long flags; spin_lock_irqsave(&cs->lock, flags); if (unlikely(!cs->connected)) { gig_dbg(DEBUG_USBREQ, "%s: not connected", __func__); spin_unlock_irqrestore(&cs->lock, flags); return -ENODEV; } if (cs->hw.bas->basstate & BS_SUSPEND) { dev_notice(cs->dev, "not starting isoc I/O, suspend in progress\n"); spin_unlock_irqrestore(&cs->lock, flags); return -EHOSTUNREACH; } ret = starturbs(bcs); if (ret < 0) { spin_unlock_irqrestore(&cs->lock, flags); dev_err(cs->dev, "could not start isoc I/O for channel B%d: %s\n", bcs->channel + 1, ret == -EFAULT ? "null URB" : get_usb_rcmsg(ret)); if (ret != -ENODEV) error_hangup(bcs); return ret; } req = bcs->channel ? HD_OPEN_B2CHANNEL : HD_OPEN_B1CHANNEL; ret = req_submit(bcs, req, 0, BAS_TIMEOUT); if (ret < 0) { dev_err(cs->dev, "could not open channel B%d\n", bcs->channel + 1); stopurbs(bcs->hw.bas); } spin_unlock_irqrestore(&cs->lock, flags); if (ret < 0 && ret != -ENODEV) error_hangup(bcs); return ret; } /* gigaset_close_bchannel * called by common.c to disconnect a B channel * tell the Gigaset base to close the channel * stopping isochronous I/O and LL notification will be done when the * acknowledgement for the close arrives * argument: * B channel control structure * return value: * 0 on success, error code < 0 on error */ static int gigaset_close_bchannel(struct bc_state *bcs) { struct cardstate *cs = bcs->cs; int req, ret; unsigned long flags; spin_lock_irqsave(&cs->lock, flags); if (unlikely(!cs->connected)) { spin_unlock_irqrestore(&cs->lock, flags); gig_dbg(DEBUG_USBREQ, "%s: not connected", __func__); return -ENODEV; } if (!(cs->hw.bas->basstate & (bcs->channel ? BS_B2OPEN : BS_B1OPEN))) { /* channel not running: just signal common.c */ spin_unlock_irqrestore(&cs->lock, flags); gigaset_bchannel_down(bcs); return 0; } /* channel running: tell device to close it */ req = bcs->channel ? HD_CLOSE_B2CHANNEL : HD_CLOSE_B1CHANNEL; ret = req_submit(bcs, req, 0, BAS_TIMEOUT); if (ret < 0) dev_err(cs->dev, "closing channel B%d failed\n", bcs->channel + 1); spin_unlock_irqrestore(&cs->lock, flags); return ret; } /* Device Operations */ /* ================= */ /* complete_cb * unqueue first command buffer from queue, waking any sleepers * must be called with cs->cmdlock held * parameter: * cs controller state structure */ static void complete_cb(struct cardstate *cs) { struct cmdbuf_t *cb = cs->cmdbuf; /* unqueue completed buffer */ cs->cmdbytes -= cs->curlen; gig_dbg(DEBUG_OUTPUT, "write_command: sent %u bytes, %u left", cs->curlen, cs->cmdbytes); if (cb->next != NULL) { cs->cmdbuf = cb->next; cs->cmdbuf->prev = NULL; cs->curlen = cs->cmdbuf->len; } else { cs->cmdbuf = NULL; cs->lastcmdbuf = NULL; cs->curlen = 0; } if (cb->wake_tasklet) tasklet_schedule(cb->wake_tasklet); kfree(cb); } /* write_command_callback * USB completion handler for AT command transmission * called by the USB subsystem in interrupt context * parameter: * urb USB request block of completed request * urb->context = controller state structure */ static void write_command_callback(struct urb *urb) { struct cardstate *cs = urb->context; struct bas_cardstate *ucs = cs->hw.bas; int status = urb->status; unsigned long flags; update_basstate(ucs, 0, BS_ATWRPEND); wake_up(&ucs->waitqueue); /* check status */ switch (status) { case 0: /* normal completion */ break; case -ENOENT: /* cancelled */ case -ECONNRESET: /* cancelled (async) */ case -EINPROGRESS: /* pending */ case -ENODEV: /* device removed */ case -ESHUTDOWN: /* device shut down */ /* ignore silently */ gig_dbg(DEBUG_USBREQ, "%s: %s", __func__, get_usb_statmsg(status)); return; default: /* any failure */ if (++ucs->retry_cmd_out > BAS_RETRY) { dev_warn(cs->dev, "command write: %s, " "giving up after %d retries\n", get_usb_statmsg(status), ucs->retry_cmd_out); break; } if (ucs->basstate & BS_SUSPEND) { dev_warn(cs->dev, "command write: %s, " "won't retry - suspend requested\n", get_usb_statmsg(status)); break; } if (cs->cmdbuf == NULL) { dev_warn(cs->dev, "command write: %s, " "cannot retry - cmdbuf gone\n", get_usb_statmsg(status)); break; } dev_notice(cs->dev, "command write: %s, retry %d\n", get_usb_statmsg(status), ucs->retry_cmd_out); if (atwrite_submit(cs, cs->cmdbuf->buf, cs->cmdbuf->len) >= 0) /* resubmitted - bypass regular exit block */ return; /* command send failed, assume base still waiting */ update_basstate(ucs, BS_ATREADY, 0); } spin_lock_irqsave(&cs->cmdlock, flags); if (cs->cmdbuf != NULL) complete_cb(cs); spin_unlock_irqrestore(&cs->cmdlock, flags); } /* atrdy_timeout * timeout routine for AT command transmission * argument: * controller state structure */ static void atrdy_timeout(unsigned long data) { struct cardstate *cs = (struct cardstate *) data; struct bas_cardstate *ucs = cs->hw.bas; dev_warn(cs->dev, "timeout waiting for HD_READY_SEND_ATDATA\n"); /* fake the missing signal - what else can I do? */ update_basstate(ucs, BS_ATREADY, BS_ATTIMER); start_cbsend(cs); } /* atwrite_submit * submit an HD_WRITE_ATMESSAGE command URB * parameters: * cs controller state structure * buf buffer containing command to send * len length of command to send * return value: * 0 on success * -EBUSY if another request is pending * any URB submission error code */ static int atwrite_submit(struct cardstate *cs, unsigned char *buf, int len) { struct bas_cardstate *ucs = cs->hw.bas; int rc; gig_dbg(DEBUG_USBREQ, "-------> HD_WRITE_ATMESSAGE (%d)", len); if (update_basstate(ucs, BS_ATWRPEND, 0) & BS_ATWRPEND) { dev_err(cs->dev, "could not submit HD_WRITE_ATMESSAGE: URB busy\n"); return -EBUSY; } ucs->dr_cmd_out.bRequestType = OUT_VENDOR_REQ; ucs->dr_cmd_out.bRequest = HD_WRITE_ATMESSAGE; ucs->dr_cmd_out.wValue = 0; ucs->dr_cmd_out.wIndex = 0; ucs->dr_cmd_out.wLength = cpu_to_le16(len); usb_fill_control_urb(ucs->urb_cmd_out, ucs->udev, usb_sndctrlpipe(ucs->udev, 0), (unsigned char *) &ucs->dr_cmd_out, buf, len, write_command_callback, cs); rc = usb_submit_urb(ucs->urb_cmd_out, GFP_ATOMIC); if (unlikely(rc)) { update_basstate(ucs, 0, BS_ATWRPEND); dev_err(cs->dev, "could not submit HD_WRITE_ATMESSAGE: %s\n", get_usb_rcmsg(rc)); return rc; } /* submitted successfully, start timeout if necessary */ if (!(update_basstate(ucs, BS_ATTIMER, BS_ATREADY) & BS_ATTIMER)) { gig_dbg(DEBUG_OUTPUT, "setting ATREADY timeout of %d/10 secs", ATRDY_TIMEOUT); mod_timer(&ucs->timer_atrdy, jiffies + ATRDY_TIMEOUT * HZ / 10); } return 0; } /* start_cbsend * start transmission of AT command queue if necessary * parameter: * cs controller state structure * return value: * 0 on success * error code < 0 on error */ static int start_cbsend(struct cardstate *cs) { struct cmdbuf_t *cb; struct bas_cardstate *ucs = cs->hw.bas; unsigned long flags; int rc; int retval = 0; /* check if suspend requested */ if (ucs->basstate & BS_SUSPEND) { gig_dbg(DEBUG_OUTPUT, "suspending"); return -EHOSTUNREACH; } /* check if AT channel is open */ if (!(ucs->basstate & BS_ATOPEN)) { gig_dbg(DEBUG_OUTPUT, "AT channel not open"); rc = req_submit(cs->bcs, HD_OPEN_ATCHANNEL, 0, BAS_TIMEOUT); if (rc < 0) { /* flush command queue */ spin_lock_irqsave(&cs->cmdlock, flags); while (cs->cmdbuf != NULL) complete_cb(cs); spin_unlock_irqrestore(&cs->cmdlock, flags); } return rc; } /* try to send first command in queue */ spin_lock_irqsave(&cs->cmdlock, flags); while ((cb = cs->cmdbuf) != NULL && (ucs->basstate & BS_ATREADY)) { ucs->retry_cmd_out = 0; rc = atwrite_submit(cs, cb->buf, cb->len); if (unlikely(rc)) { retval = rc; complete_cb(cs); } } spin_unlock_irqrestore(&cs->cmdlock, flags); return retval; } /* gigaset_write_cmd * This function is called by the device independent part of the driver * to transmit an AT command string to the Gigaset device. * It encapsulates the device specific method for transmission over the * direct USB connection to the base. * The command string is added to the queue of commands to send, and * USB transmission is started if necessary. * parameters: * cs controller state structure * cb command buffer structure * return value: * number of bytes queued on success * error code < 0 on error */ static int gigaset_write_cmd(struct cardstate *cs, struct cmdbuf_t *cb) { unsigned long flags; int rc; gigaset_dbg_buffer(cs->mstate != MS_LOCKED ? DEBUG_TRANSCMD : DEBUG_LOCKCMD, "CMD Transmit", cb->len, cb->buf); /* translate "+++" escape sequence sent as a single separate command * into "close AT channel" command for error recovery * The next command will reopen the AT channel automatically. */ if (cb->len == 3 && !memcmp(cb->buf, "+++", 3)) { /* If an HD_RECEIVEATDATA_ACK message remains unhandled * because of an error, the base never sends another one. * The response channel is thus effectively blocked. * Closing and reopening the AT channel does *not* clear * this condition. * As a stopgap measure, submit a zero-length AT read * before closing the AT channel. This has the undocumented * effect of triggering a new HD_RECEIVEATDATA_ACK message * from the base if necessary. * The subsequent AT channel close then discards any pending * messages. */ spin_lock_irqsave(&cs->lock, flags); if (!(cs->hw.bas->basstate & BS_ATRDPEND)) { kfree(cs->hw.bas->rcvbuf); cs->hw.bas->rcvbuf = NULL; cs->hw.bas->rcvbuf_size = 0; cs->hw.bas->retry_cmd_in = 0; atread_submit(cs, 0); } spin_unlock_irqrestore(&cs->lock, flags); rc = req_submit(cs->bcs, HD_CLOSE_ATCHANNEL, 0, BAS_TIMEOUT); if (cb->wake_tasklet) tasklet_schedule(cb->wake_tasklet); if (!rc) rc = cb->len; kfree(cb); return rc; } spin_lock_irqsave(&cs->cmdlock, flags); cb->prev = cs->lastcmdbuf; if (cs->lastcmdbuf) cs->lastcmdbuf->next = cb; else { cs->cmdbuf = cb; cs->curlen = cb->len; } cs->cmdbytes += cb->len; cs->lastcmdbuf = cb; spin_unlock_irqrestore(&cs->cmdlock, flags); spin_lock_irqsave(&cs->lock, flags); if (unlikely(!cs->connected)) { spin_unlock_irqrestore(&cs->lock, flags); gig_dbg(DEBUG_USBREQ, "%s: not connected", __func__); /* flush command queue */ spin_lock_irqsave(&cs->cmdlock, flags); while (cs->cmdbuf != NULL) complete_cb(cs); spin_unlock_irqrestore(&cs->cmdlock, flags); return -ENODEV; } rc = start_cbsend(cs); spin_unlock_irqrestore(&cs->lock, flags); return rc < 0 ? rc : cb->len; } /* gigaset_write_room * tty_driver.write_room interface routine * return number of characters the driver will accept to be written via * gigaset_write_cmd * parameter: * controller state structure * return value: * number of characters */ static int gigaset_write_room(struct cardstate *cs) { return IF_WRITEBUF; } /* gigaset_chars_in_buffer * tty_driver.chars_in_buffer interface routine * return number of characters waiting to be sent * parameter: * controller state structure * return value: * number of characters */ static int gigaset_chars_in_buffer(struct cardstate *cs) { return cs->cmdbytes; } /* gigaset_brkchars * implementation of ioctl(GIGASET_BRKCHARS) * parameter: * controller state structure * return value: * -EINVAL (unimplemented function) */ static int gigaset_brkchars(struct cardstate *cs, const unsigned char buf[6]) { return -EINVAL; } /* Device Initialization/Shutdown */ /* ============================== */ /* Free hardware dependent part of the B channel structure * parameter: * bcs B channel structure */ static void gigaset_freebcshw(struct bc_state *bcs) { struct bas_bc_state *ubc = bcs->hw.bas; int i; if (!ubc) return; /* kill URBs and tasklets before freeing - better safe than sorry */ ubc->running = 0; gig_dbg(DEBUG_INIT, "%s: killing isoc URBs", __func__); for (i = 0; i < BAS_OUTURBS; ++i) { usb_kill_urb(ubc->isoouturbs[i].urb); usb_free_urb(ubc->isoouturbs[i].urb); } for (i = 0; i < BAS_INURBS; ++i) { usb_kill_urb(ubc->isoinurbs[i]); usb_free_urb(ubc->isoinurbs[i]); } tasklet_kill(&ubc->sent_tasklet); tasklet_kill(&ubc->rcvd_tasklet); kfree(ubc->isooutbuf); kfree(ubc); bcs->hw.bas = NULL; } /* Initialize hardware dependent part of the B channel structure * parameter: * bcs B channel structure * return value: * 0 on success, error code < 0 on failure */ static int gigaset_initbcshw(struct bc_state *bcs) { int i; struct bas_bc_state *ubc; bcs->hw.bas = ubc = kmalloc(sizeof(struct bas_bc_state), GFP_KERNEL); if (!ubc) { pr_err("out of memory\n"); return -ENOMEM; } ubc->running = 0; atomic_set(&ubc->corrbytes, 0); spin_lock_init(&ubc->isooutlock); for (i = 0; i < BAS_OUTURBS; ++i) { ubc->isoouturbs[i].urb = NULL; ubc->isoouturbs[i].bcs = bcs; } ubc->isooutdone = ubc->isooutfree = ubc->isooutovfl = NULL; ubc->numsub = 0; ubc->isooutbuf = kmalloc(sizeof(struct isowbuf_t), GFP_KERNEL); if (!ubc->isooutbuf) { pr_err("out of memory\n"); kfree(ubc); bcs->hw.bas = NULL; return -ENOMEM; } tasklet_init(&ubc->sent_tasklet, write_iso_tasklet, (unsigned long) bcs); spin_lock_init(&ubc->isoinlock); for (i = 0; i < BAS_INURBS; ++i) ubc->isoinurbs[i] = NULL; ubc->isoindone = NULL; ubc->loststatus = -EINPROGRESS; ubc->isoinlost = 0; ubc->seqlen = 0; ubc->inbyte = 0; ubc->inbits = 0; ubc->goodbytes = 0; ubc->alignerrs = 0; ubc->fcserrs = 0; ubc->frameerrs = 0; ubc->giants = 0; ubc->runts = 0; ubc->aborts = 0; ubc->shared0s = 0; ubc->stolen0s = 0; tasklet_init(&ubc->rcvd_tasklet, read_iso_tasklet, (unsigned long) bcs); return 0; } static void gigaset_reinitbcshw(struct bc_state *bcs) { struct bas_bc_state *ubc = bcs->hw.bas; bcs->hw.bas->running = 0; atomic_set(&bcs->hw.bas->corrbytes, 0); bcs->hw.bas->numsub = 0; spin_lock_init(&ubc->isooutlock); spin_lock_init(&ubc->isoinlock); ubc->loststatus = -EINPROGRESS; } static void gigaset_freecshw(struct cardstate *cs) { /* timers, URBs and rcvbuf are disposed of in disconnect */ kfree(cs->hw.bas->int_in_buf); kfree(cs->hw.bas); cs->hw.bas = NULL; } /* Initialize hardware dependent part of the cardstate structure * parameter: * cs cardstate structure * return value: * 0 on success, error code < 0 on failure */ static int gigaset_initcshw(struct cardstate *cs) { struct bas_cardstate *ucs; cs->hw.bas = ucs = kmalloc(sizeof *ucs, GFP_KERNEL); if (!ucs) { pr_err("out of memory\n"); return -ENOMEM; } ucs->int_in_buf = kmalloc(IP_MSGSIZE, GFP_KERNEL); if (!ucs->int_in_buf) { kfree(ucs); pr_err("out of memory\n"); return -ENOMEM; } ucs->urb_cmd_in = NULL; ucs->urb_cmd_out = NULL; ucs->rcvbuf = NULL; ucs->rcvbuf_size = 0; spin_lock_init(&ucs->lock); ucs->pending = 0; ucs->basstate = 0; setup_timer(&ucs->timer_ctrl, req_timeout, (unsigned long) cs); setup_timer(&ucs->timer_atrdy, atrdy_timeout, (unsigned long) cs); setup_timer(&ucs->timer_cmd_in, cmd_in_timeout, (unsigned long) cs); setup_timer(&ucs->timer_int_in, int_in_resubmit, (unsigned long) cs); init_waitqueue_head(&ucs->waitqueue); INIT_WORK(&ucs->int_in_wq, int_in_work); return 0; } /* freeurbs * unlink and deallocate all URBs unconditionally * caller must make sure that no commands are still in progress * parameter: * cs controller state structure */ static void freeurbs(struct cardstate *cs) { struct bas_cardstate *ucs = cs->hw.bas; struct bas_bc_state *ubc; int i, j; gig_dbg(DEBUG_INIT, "%s: killing URBs", __func__); for (j = 0; j < BAS_CHANNELS; ++j) { ubc = cs->bcs[j].hw.bas; for (i = 0; i < BAS_OUTURBS; ++i) { usb_kill_urb(ubc->isoouturbs[i].urb); usb_free_urb(ubc->isoouturbs[i].urb); ubc->isoouturbs[i].urb = NULL; } for (i = 0; i < BAS_INURBS; ++i) { usb_kill_urb(ubc->isoinurbs[i]); usb_free_urb(ubc->isoinurbs[i]); ubc->isoinurbs[i] = NULL; } } usb_kill_urb(ucs->urb_int_in); usb_free_urb(ucs->urb_int_in); ucs->urb_int_in = NULL; usb_kill_urb(ucs->urb_cmd_out); usb_free_urb(ucs->urb_cmd_out); ucs->urb_cmd_out = NULL; usb_kill_urb(ucs->urb_cmd_in); usb_free_urb(ucs->urb_cmd_in); ucs->urb_cmd_in = NULL; usb_kill_urb(ucs->urb_ctrl); usb_free_urb(ucs->urb_ctrl); ucs->urb_ctrl = NULL; } /* gigaset_probe * This function is called when a new USB device is connected. * It checks whether the new device is handled by this driver. */ static int gigaset_probe(struct usb_interface *interface, const struct usb_device_id *id) { struct usb_host_interface *hostif; struct usb_device *udev = interface_to_usbdev(interface); struct cardstate *cs = NULL; struct bas_cardstate *ucs = NULL; struct bas_bc_state *ubc; struct usb_endpoint_descriptor *endpoint; int i, j; int rc; gig_dbg(DEBUG_INIT, "%s: Check if device matches .. (Vendor: 0x%x, Product: 0x%x)", __func__, le16_to_cpu(udev->descriptor.idVendor), le16_to_cpu(udev->descriptor.idProduct)); /* set required alternate setting */ hostif = interface->cur_altsetting; if (hostif->desc.bAlternateSetting != 3) { gig_dbg(DEBUG_INIT, "%s: wrong alternate setting %d - trying to switch", __func__, hostif->desc.bAlternateSetting); if (usb_set_interface(udev, hostif->desc.bInterfaceNumber, 3) < 0) { dev_warn(&udev->dev, "usb_set_interface failed, " "device %d interface %d altsetting %d\n", udev->devnum, hostif->desc.bInterfaceNumber, hostif->desc.bAlternateSetting); return -ENODEV; } hostif = interface->cur_altsetting; } /* Reject application specific interfaces */ if (hostif->desc.bInterfaceClass != 255) { dev_warn(&udev->dev, "%s: bInterfaceClass == %d\n", __func__, hostif->desc.bInterfaceClass); return -ENODEV; } dev_info(&udev->dev, "%s: Device matched (Vendor: 0x%x, Product: 0x%x)\n", __func__, le16_to_cpu(udev->descriptor.idVendor), le16_to_cpu(udev->descriptor.idProduct)); /* allocate memory for our device state and initialize it */ cs = gigaset_initcs(driver, BAS_CHANNELS, 0, 0, cidmode, GIGASET_MODULENAME); if (!cs) return -ENODEV; ucs = cs->hw.bas; /* save off device structure ptrs for later use */ usb_get_dev(udev); ucs->udev = udev; ucs->interface = interface; cs->dev = &interface->dev; /* allocate URBs: * - one for the interrupt pipe * - three for the different uses of the default control pipe * - three for each isochronous pipe */ if (!(ucs->urb_int_in = usb_alloc_urb(0, GFP_KERNEL)) || !(ucs->urb_cmd_in = usb_alloc_urb(0, GFP_KERNEL)) || !(ucs->urb_cmd_out = usb_alloc_urb(0, GFP_KERNEL)) || !(ucs->urb_ctrl = usb_alloc_urb(0, GFP_KERNEL))) goto allocerr; for (j = 0; j < BAS_CHANNELS; ++j) { ubc = cs->bcs[j].hw.bas; for (i = 0; i < BAS_OUTURBS; ++i) if (!(ubc->isoouturbs[i].urb = usb_alloc_urb(BAS_NUMFRAMES, GFP_KERNEL))) goto allocerr; for (i = 0; i < BAS_INURBS; ++i) if (!(ubc->isoinurbs[i] = usb_alloc_urb(BAS_NUMFRAMES, GFP_KERNEL))) goto allocerr; } ucs->rcvbuf = NULL; ucs->rcvbuf_size = 0; /* Fill the interrupt urb and send it to the core */ endpoint = &hostif->endpoint[0].desc; usb_fill_int_urb(ucs->urb_int_in, udev, usb_rcvintpipe(udev, (endpoint->bEndpointAddress) & 0x0f), ucs->int_in_buf, IP_MSGSIZE, read_int_callback, cs, endpoint->bInterval); rc = usb_submit_urb(ucs->urb_int_in, GFP_KERNEL); if (rc != 0) { dev_err(cs->dev, "could not submit interrupt URB: %s\n", get_usb_rcmsg(rc)); goto error; } ucs->retry_int_in = 0; /* tell the device that the driver is ready */ rc = req_submit(cs->bcs, HD_DEVICE_INIT_ACK, 0, 0); if (rc != 0) goto error; /* tell common part that the device is ready */ if (startmode == SM_LOCKED) cs->mstate = MS_LOCKED; /* save address of controller structure */ usb_set_intfdata(interface, cs); rc = gigaset_start(cs); if (rc < 0) goto error; return 0; allocerr: dev_err(cs->dev, "could not allocate URBs\n"); rc = -ENOMEM; error: freeurbs(cs); usb_set_intfdata(interface, NULL); gigaset_freecs(cs); return rc; } /* gigaset_disconnect * This function is called when the Gigaset base is unplugged. */ static void gigaset_disconnect(struct usb_interface *interface) { struct cardstate *cs; struct bas_cardstate *ucs; int j; cs = usb_get_intfdata(interface); ucs = cs->hw.bas; dev_info(cs->dev, "disconnecting Gigaset base\n"); /* mark base as not ready, all channels disconnected */ ucs->basstate = 0; /* tell LL all channels are down */ for (j = 0; j < BAS_CHANNELS; ++j) gigaset_bchannel_down(cs->bcs + j); /* stop driver (common part) */ gigaset_stop(cs); /* stop delayed work and URBs, free ressources */ del_timer_sync(&ucs->timer_ctrl); del_timer_sync(&ucs->timer_atrdy); del_timer_sync(&ucs->timer_cmd_in); del_timer_sync(&ucs->timer_int_in); cancel_work_sync(&ucs->int_in_wq); freeurbs(cs); usb_set_intfdata(interface, NULL); kfree(ucs->rcvbuf); ucs->rcvbuf = NULL; ucs->rcvbuf_size = 0; usb_put_dev(ucs->udev); ucs->interface = NULL; ucs->udev = NULL; cs->dev = NULL; gigaset_freecs(cs); } /* gigaset_suspend * This function is called before the USB connection is suspended * or before the USB device is reset. * In the latter case, message == PMSG_ON. */ static int gigaset_suspend(struct usb_interface *intf, pm_message_t message) { struct cardstate *cs = usb_get_intfdata(intf); struct bas_cardstate *ucs = cs->hw.bas; int rc; /* set suspend flag; this stops AT command/response traffic */ if (update_basstate(ucs, BS_SUSPEND, 0) & BS_SUSPEND) { gig_dbg(DEBUG_SUSPEND, "already suspended"); return 0; } /* wait a bit for blocking conditions to go away */ rc = wait_event_timeout(ucs->waitqueue, !(ucs->basstate & (BS_B1OPEN | BS_B2OPEN | BS_ATRDPEND | BS_ATWRPEND)), BAS_TIMEOUT * HZ / 10); gig_dbg(DEBUG_SUSPEND, "wait_event_timeout() -> %d", rc); /* check for conditions preventing suspend */ if (ucs->basstate & (BS_B1OPEN | BS_B2OPEN | BS_ATRDPEND | BS_ATWRPEND)) { dev_warn(cs->dev, "cannot suspend:\n"); if (ucs->basstate & BS_B1OPEN) dev_warn(cs->dev, " B channel 1 open\n"); if (ucs->basstate & BS_B2OPEN) dev_warn(cs->dev, " B channel 2 open\n"); if (ucs->basstate & BS_ATRDPEND) dev_warn(cs->dev, " receiving AT reply\n"); if (ucs->basstate & BS_ATWRPEND) dev_warn(cs->dev, " sending AT command\n"); update_basstate(ucs, 0, BS_SUSPEND); return -EBUSY; } /* close AT channel if open */ if (ucs->basstate & BS_ATOPEN) { gig_dbg(DEBUG_SUSPEND, "closing AT channel"); rc = req_submit(cs->bcs, HD_CLOSE_ATCHANNEL, 0, 0); if (rc) { update_basstate(ucs, 0, BS_SUSPEND); return rc; } wait_event_timeout(ucs->waitqueue, !ucs->pending, BAS_TIMEOUT * HZ / 10); /* in case of timeout, proceed anyway */ } /* kill all URBs and delayed work that might still be pending */ usb_kill_urb(ucs->urb_ctrl); usb_kill_urb(ucs->urb_int_in); del_timer_sync(&ucs->timer_ctrl); del_timer_sync(&ucs->timer_atrdy); del_timer_sync(&ucs->timer_cmd_in); del_timer_sync(&ucs->timer_int_in); /* don't try to cancel int_in_wq from within reset as it * might be the one requesting the reset */ if (message.event != PM_EVENT_ON) cancel_work_sync(&ucs->int_in_wq); gig_dbg(DEBUG_SUSPEND, "suspend complete"); return 0; } /* gigaset_resume * This function is called after the USB connection has been resumed. */ static int gigaset_resume(struct usb_interface *intf) { struct cardstate *cs = usb_get_intfdata(intf); struct bas_cardstate *ucs = cs->hw.bas; int rc; /* resubmit interrupt URB for spontaneous messages from base */ rc = usb_submit_urb(ucs->urb_int_in, GFP_KERNEL); if (rc) { dev_err(cs->dev, "could not resubmit interrupt URB: %s\n", get_usb_rcmsg(rc)); return rc; } ucs->retry_int_in = 0; /* clear suspend flag to reallow activity */ update_basstate(ucs, 0, BS_SUSPEND); gig_dbg(DEBUG_SUSPEND, "resume complete"); return 0; } /* gigaset_pre_reset * This function is called before the USB connection is reset. */ static int gigaset_pre_reset(struct usb_interface *intf) { /* handle just like suspend */ return gigaset_suspend(intf, PMSG_ON); } /* gigaset_post_reset * This function is called after the USB connection has been reset. */ static int gigaset_post_reset(struct usb_interface *intf) { /* FIXME: send HD_DEVICE_INIT_ACK? */ /* resume operations */ return gigaset_resume(intf); } static const struct gigaset_ops gigops = { gigaset_write_cmd, gigaset_write_room, gigaset_chars_in_buffer, gigaset_brkchars, gigaset_init_bchannel, gigaset_close_bchannel, gigaset_initbcshw, gigaset_freebcshw, gigaset_reinitbcshw, gigaset_initcshw, gigaset_freecshw, gigaset_set_modem_ctrl, gigaset_baud_rate, gigaset_set_line_ctrl, gigaset_isoc_send_skb, gigaset_isoc_input, }; /* bas_gigaset_init * This function is called after the kernel module is loaded. */ static int __init bas_gigaset_init(void) { int result; /* allocate memory for our driver state and initialize it */ driver = gigaset_initdriver(GIGASET_MINOR, GIGASET_MINORS, GIGASET_MODULENAME, GIGASET_DEVNAME, &gigops, THIS_MODULE); if (driver == NULL) goto error; /* register this driver with the USB subsystem */ result = usb_register(&gigaset_usb_driver); if (result < 0) { pr_err("error %d registering USB driver\n", -result); goto error; } pr_info(DRIVER_DESC "\n"); return 0; error: if (driver) gigaset_freedriver(driver); driver = NULL; return -1; } /* bas_gigaset_exit * This function is called before the kernel module is unloaded. */ static void __exit bas_gigaset_exit(void) { struct bas_cardstate *ucs; int i; gigaset_blockdriver(driver); /* => probe will fail * => no gigaset_start any more */ /* stop all connected devices */ for (i = 0; i < driver->minors; i++) { if (gigaset_shutdown(driver->cs + i) < 0) continue; /* no device */ /* from now on, no isdn callback should be possible */ /* close all still open channels */ ucs = driver->cs[i].hw.bas; if (ucs->basstate & BS_B1OPEN) { gig_dbg(DEBUG_INIT, "closing B1 channel"); usb_control_msg(ucs->udev, usb_sndctrlpipe(ucs->udev, 0), HD_CLOSE_B1CHANNEL, OUT_VENDOR_REQ, 0, 0, NULL, 0, BAS_TIMEOUT); } if (ucs->basstate & BS_B2OPEN) { gig_dbg(DEBUG_INIT, "closing B2 channel"); usb_control_msg(ucs->udev, usb_sndctrlpipe(ucs->udev, 0), HD_CLOSE_B2CHANNEL, OUT_VENDOR_REQ, 0, 0, NULL, 0, BAS_TIMEOUT); } if (ucs->basstate & BS_ATOPEN) { gig_dbg(DEBUG_INIT, "closing AT channel"); usb_control_msg(ucs->udev, usb_sndctrlpipe(ucs->udev, 0), HD_CLOSE_ATCHANNEL, OUT_VENDOR_REQ, 0, 0, NULL, 0, BAS_TIMEOUT); } ucs->basstate = 0; } /* deregister this driver with the USB subsystem */ usb_deregister(&gigaset_usb_driver); /* this will call the disconnect-callback */ /* from now on, no disconnect/probe callback should be running */ gigaset_freedriver(driver); driver = NULL; } module_init(bas_gigaset_init); module_exit(bas_gigaset_exit); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL");
gpl-2.0
omega-roms/I9300_Stock_Kernel_JB_4.3
drivers/net/sfc/falcon_xmac.c
3034
12420
/**************************************************************************** * Driver for Solarflare Solarstorm network controllers and boards * Copyright 2005-2006 Fen Systems Ltd. * Copyright 2006-2010 Solarflare Communications Inc. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation, incorporated herein by reference. */ #include <linux/delay.h> #include "net_driver.h" #include "efx.h" #include "nic.h" #include "regs.h" #include "io.h" #include "mac.h" #include "mdio_10g.h" #include "workarounds.h" /************************************************************************** * * MAC operations * *************************************************************************/ /* Configure the XAUI driver that is an output from Falcon */ void falcon_setup_xaui(struct efx_nic *efx) { efx_oword_t sdctl, txdrv; /* Move the XAUI into low power, unless there is no PHY, in * which case the XAUI will have to drive a cable. */ if (efx->phy_type == PHY_TYPE_NONE) return; efx_reado(efx, &sdctl, FR_AB_XX_SD_CTL); EFX_SET_OWORD_FIELD(sdctl, FRF_AB_XX_HIDRVD, FFE_AB_XX_SD_CTL_DRV_DEF); EFX_SET_OWORD_FIELD(sdctl, FRF_AB_XX_LODRVD, FFE_AB_XX_SD_CTL_DRV_DEF); EFX_SET_OWORD_FIELD(sdctl, FRF_AB_XX_HIDRVC, FFE_AB_XX_SD_CTL_DRV_DEF); EFX_SET_OWORD_FIELD(sdctl, FRF_AB_XX_LODRVC, FFE_AB_XX_SD_CTL_DRV_DEF); EFX_SET_OWORD_FIELD(sdctl, FRF_AB_XX_HIDRVB, FFE_AB_XX_SD_CTL_DRV_DEF); EFX_SET_OWORD_FIELD(sdctl, FRF_AB_XX_LODRVB, FFE_AB_XX_SD_CTL_DRV_DEF); EFX_SET_OWORD_FIELD(sdctl, FRF_AB_XX_HIDRVA, FFE_AB_XX_SD_CTL_DRV_DEF); EFX_SET_OWORD_FIELD(sdctl, FRF_AB_XX_LODRVA, FFE_AB_XX_SD_CTL_DRV_DEF); efx_writeo(efx, &sdctl, FR_AB_XX_SD_CTL); EFX_POPULATE_OWORD_8(txdrv, FRF_AB_XX_DEQD, FFE_AB_XX_TXDRV_DEQ_DEF, FRF_AB_XX_DEQC, FFE_AB_XX_TXDRV_DEQ_DEF, FRF_AB_XX_DEQB, FFE_AB_XX_TXDRV_DEQ_DEF, FRF_AB_XX_DEQA, FFE_AB_XX_TXDRV_DEQ_DEF, FRF_AB_XX_DTXD, FFE_AB_XX_TXDRV_DTX_DEF, FRF_AB_XX_DTXC, FFE_AB_XX_TXDRV_DTX_DEF, FRF_AB_XX_DTXB, FFE_AB_XX_TXDRV_DTX_DEF, FRF_AB_XX_DTXA, FFE_AB_XX_TXDRV_DTX_DEF); efx_writeo(efx, &txdrv, FR_AB_XX_TXDRV_CTL); } int falcon_reset_xaui(struct efx_nic *efx) { struct falcon_nic_data *nic_data = efx->nic_data; efx_oword_t reg; int count; /* Don't fetch MAC statistics over an XMAC reset */ WARN_ON(nic_data->stats_disable_count == 0); /* Start reset sequence */ EFX_POPULATE_OWORD_1(reg, FRF_AB_XX_RST_XX_EN, 1); efx_writeo(efx, &reg, FR_AB_XX_PWR_RST); /* Wait up to 10 ms for completion, then reinitialise */ for (count = 0; count < 1000; count++) { efx_reado(efx, &reg, FR_AB_XX_PWR_RST); if (EFX_OWORD_FIELD(reg, FRF_AB_XX_RST_XX_EN) == 0 && EFX_OWORD_FIELD(reg, FRF_AB_XX_SD_RST_ACT) == 0) { falcon_setup_xaui(efx); return 0; } udelay(10); } netif_err(efx, hw, efx->net_dev, "timed out waiting for XAUI/XGXS reset\n"); return -ETIMEDOUT; } static void falcon_ack_status_intr(struct efx_nic *efx) { struct falcon_nic_data *nic_data = efx->nic_data; efx_oword_t reg; if ((efx_nic_rev(efx) != EFX_REV_FALCON_B0) || LOOPBACK_INTERNAL(efx)) return; /* We expect xgmii faults if the wireside link is down */ if (!EFX_WORKAROUND_5147(efx) || !efx->link_state.up) return; /* We can only use this interrupt to signal the negative edge of * xaui_align [we have to poll the positive edge]. */ if (nic_data->xmac_poll_required) return; efx_reado(efx, &reg, FR_AB_XM_MGT_INT_MSK); } static bool falcon_xgxs_link_ok(struct efx_nic *efx) { efx_oword_t reg; bool align_done, link_ok = false; int sync_status; /* Read link status */ efx_reado(efx, &reg, FR_AB_XX_CORE_STAT); align_done = EFX_OWORD_FIELD(reg, FRF_AB_XX_ALIGN_DONE); sync_status = EFX_OWORD_FIELD(reg, FRF_AB_XX_SYNC_STAT); if (align_done && (sync_status == FFE_AB_XX_STAT_ALL_LANES)) link_ok = true; /* Clear link status ready for next read */ EFX_SET_OWORD_FIELD(reg, FRF_AB_XX_COMMA_DET, FFE_AB_XX_STAT_ALL_LANES); EFX_SET_OWORD_FIELD(reg, FRF_AB_XX_CHAR_ERR, FFE_AB_XX_STAT_ALL_LANES); EFX_SET_OWORD_FIELD(reg, FRF_AB_XX_DISPERR, FFE_AB_XX_STAT_ALL_LANES); efx_writeo(efx, &reg, FR_AB_XX_CORE_STAT); return link_ok; } static bool falcon_xmac_link_ok(struct efx_nic *efx) { /* * Check MAC's XGXS link status except when using XGMII loopback * which bypasses the XGXS block. * If possible, check PHY's XGXS link status except when using * MAC loopback. */ return (efx->loopback_mode == LOOPBACK_XGMII || falcon_xgxs_link_ok(efx)) && (!(efx->mdio.mmds & (1 << MDIO_MMD_PHYXS)) || LOOPBACK_INTERNAL(efx) || efx_mdio_phyxgxs_lane_sync(efx)); } static void falcon_reconfigure_xmac_core(struct efx_nic *efx) { unsigned int max_frame_len; efx_oword_t reg; bool rx_fc = !!(efx->link_state.fc & EFX_FC_RX); bool tx_fc = !!(efx->link_state.fc & EFX_FC_TX); /* Configure MAC - cut-thru mode is hard wired on */ EFX_POPULATE_OWORD_3(reg, FRF_AB_XM_RX_JUMBO_MODE, 1, FRF_AB_XM_TX_STAT_EN, 1, FRF_AB_XM_RX_STAT_EN, 1); efx_writeo(efx, &reg, FR_AB_XM_GLB_CFG); /* Configure TX */ EFX_POPULATE_OWORD_6(reg, FRF_AB_XM_TXEN, 1, FRF_AB_XM_TX_PRMBL, 1, FRF_AB_XM_AUTO_PAD, 1, FRF_AB_XM_TXCRC, 1, FRF_AB_XM_FCNTL, tx_fc, FRF_AB_XM_IPG, 0x3); efx_writeo(efx, &reg, FR_AB_XM_TX_CFG); /* Configure RX */ EFX_POPULATE_OWORD_5(reg, FRF_AB_XM_RXEN, 1, FRF_AB_XM_AUTO_DEPAD, 0, FRF_AB_XM_ACPT_ALL_MCAST, 1, FRF_AB_XM_ACPT_ALL_UCAST, efx->promiscuous, FRF_AB_XM_PASS_CRC_ERR, 1); efx_writeo(efx, &reg, FR_AB_XM_RX_CFG); /* Set frame length */ max_frame_len = EFX_MAX_FRAME_LEN(efx->net_dev->mtu); EFX_POPULATE_OWORD_1(reg, FRF_AB_XM_MAX_RX_FRM_SIZE, max_frame_len); efx_writeo(efx, &reg, FR_AB_XM_RX_PARAM); EFX_POPULATE_OWORD_2(reg, FRF_AB_XM_MAX_TX_FRM_SIZE, max_frame_len, FRF_AB_XM_TX_JUMBO_MODE, 1); efx_writeo(efx, &reg, FR_AB_XM_TX_PARAM); EFX_POPULATE_OWORD_2(reg, FRF_AB_XM_PAUSE_TIME, 0xfffe, /* MAX PAUSE TIME */ FRF_AB_XM_DIS_FCNTL, !rx_fc); efx_writeo(efx, &reg, FR_AB_XM_FC); /* Set MAC address */ memcpy(&reg, &efx->net_dev->dev_addr[0], 4); efx_writeo(efx, &reg, FR_AB_XM_ADR_LO); memcpy(&reg, &efx->net_dev->dev_addr[4], 2); efx_writeo(efx, &reg, FR_AB_XM_ADR_HI); } static void falcon_reconfigure_xgxs_core(struct efx_nic *efx) { efx_oword_t reg; bool xgxs_loopback = (efx->loopback_mode == LOOPBACK_XGXS); bool xaui_loopback = (efx->loopback_mode == LOOPBACK_XAUI); bool xgmii_loopback = (efx->loopback_mode == LOOPBACK_XGMII); /* XGXS block is flaky and will need to be reset if moving * into our out of XGMII, XGXS or XAUI loopbacks. */ if (EFX_WORKAROUND_5147(efx)) { bool old_xgmii_loopback, old_xgxs_loopback, old_xaui_loopback; bool reset_xgxs; efx_reado(efx, &reg, FR_AB_XX_CORE_STAT); old_xgxs_loopback = EFX_OWORD_FIELD(reg, FRF_AB_XX_XGXS_LB_EN); old_xgmii_loopback = EFX_OWORD_FIELD(reg, FRF_AB_XX_XGMII_LB_EN); efx_reado(efx, &reg, FR_AB_XX_SD_CTL); old_xaui_loopback = EFX_OWORD_FIELD(reg, FRF_AB_XX_LPBKA); /* The PHY driver may have turned XAUI off */ reset_xgxs = ((xgxs_loopback != old_xgxs_loopback) || (xaui_loopback != old_xaui_loopback) || (xgmii_loopback != old_xgmii_loopback)); if (reset_xgxs) falcon_reset_xaui(efx); } efx_reado(efx, &reg, FR_AB_XX_CORE_STAT); EFX_SET_OWORD_FIELD(reg, FRF_AB_XX_FORCE_SIG, (xgxs_loopback || xaui_loopback) ? FFE_AB_XX_FORCE_SIG_ALL_LANES : 0); EFX_SET_OWORD_FIELD(reg, FRF_AB_XX_XGXS_LB_EN, xgxs_loopback); EFX_SET_OWORD_FIELD(reg, FRF_AB_XX_XGMII_LB_EN, xgmii_loopback); efx_writeo(efx, &reg, FR_AB_XX_CORE_STAT); efx_reado(efx, &reg, FR_AB_XX_SD_CTL); EFX_SET_OWORD_FIELD(reg, FRF_AB_XX_LPBKD, xaui_loopback); EFX_SET_OWORD_FIELD(reg, FRF_AB_XX_LPBKC, xaui_loopback); EFX_SET_OWORD_FIELD(reg, FRF_AB_XX_LPBKB, xaui_loopback); EFX_SET_OWORD_FIELD(reg, FRF_AB_XX_LPBKA, xaui_loopback); efx_writeo(efx, &reg, FR_AB_XX_SD_CTL); } /* Try to bring up the Falcon side of the Falcon-Phy XAUI link */ static bool falcon_xmac_link_ok_retry(struct efx_nic *efx, int tries) { bool mac_up = falcon_xmac_link_ok(efx); if (LOOPBACK_MASK(efx) & LOOPBACKS_EXTERNAL(efx) & LOOPBACKS_WS || efx_phy_mode_disabled(efx->phy_mode)) /* XAUI link is expected to be down */ return mac_up; falcon_stop_nic_stats(efx); while (!mac_up && tries) { netif_dbg(efx, hw, efx->net_dev, "bashing xaui\n"); falcon_reset_xaui(efx); udelay(200); mac_up = falcon_xmac_link_ok(efx); --tries; } falcon_start_nic_stats(efx); return mac_up; } static bool falcon_xmac_check_fault(struct efx_nic *efx) { return !falcon_xmac_link_ok_retry(efx, 5); } static int falcon_reconfigure_xmac(struct efx_nic *efx) { struct falcon_nic_data *nic_data = efx->nic_data; falcon_reconfigure_xgxs_core(efx); falcon_reconfigure_xmac_core(efx); falcon_reconfigure_mac_wrapper(efx); nic_data->xmac_poll_required = !falcon_xmac_link_ok_retry(efx, 5); falcon_ack_status_intr(efx); return 0; } static void falcon_update_stats_xmac(struct efx_nic *efx) { struct efx_mac_stats *mac_stats = &efx->mac_stats; /* Update MAC stats from DMAed values */ FALCON_STAT(efx, XgRxOctets, rx_bytes); FALCON_STAT(efx, XgRxOctetsOK, rx_good_bytes); FALCON_STAT(efx, XgRxPkts, rx_packets); FALCON_STAT(efx, XgRxPktsOK, rx_good); FALCON_STAT(efx, XgRxBroadcastPkts, rx_broadcast); FALCON_STAT(efx, XgRxMulticastPkts, rx_multicast); FALCON_STAT(efx, XgRxUnicastPkts, rx_unicast); FALCON_STAT(efx, XgRxUndersizePkts, rx_lt64); FALCON_STAT(efx, XgRxOversizePkts, rx_gtjumbo); FALCON_STAT(efx, XgRxJabberPkts, rx_bad_gtjumbo); FALCON_STAT(efx, XgRxUndersizeFCSerrorPkts, rx_bad_lt64); FALCON_STAT(efx, XgRxDropEvents, rx_overflow); FALCON_STAT(efx, XgRxFCSerrorPkts, rx_bad); FALCON_STAT(efx, XgRxAlignError, rx_align_error); FALCON_STAT(efx, XgRxSymbolError, rx_symbol_error); FALCON_STAT(efx, XgRxInternalMACError, rx_internal_error); FALCON_STAT(efx, XgRxControlPkts, rx_control); FALCON_STAT(efx, XgRxPausePkts, rx_pause); FALCON_STAT(efx, XgRxPkts64Octets, rx_64); FALCON_STAT(efx, XgRxPkts65to127Octets, rx_65_to_127); FALCON_STAT(efx, XgRxPkts128to255Octets, rx_128_to_255); FALCON_STAT(efx, XgRxPkts256to511Octets, rx_256_to_511); FALCON_STAT(efx, XgRxPkts512to1023Octets, rx_512_to_1023); FALCON_STAT(efx, XgRxPkts1024to15xxOctets, rx_1024_to_15xx); FALCON_STAT(efx, XgRxPkts15xxtoMaxOctets, rx_15xx_to_jumbo); FALCON_STAT(efx, XgRxLengthError, rx_length_error); FALCON_STAT(efx, XgTxPkts, tx_packets); FALCON_STAT(efx, XgTxOctets, tx_bytes); FALCON_STAT(efx, XgTxMulticastPkts, tx_multicast); FALCON_STAT(efx, XgTxBroadcastPkts, tx_broadcast); FALCON_STAT(efx, XgTxUnicastPkts, tx_unicast); FALCON_STAT(efx, XgTxControlPkts, tx_control); FALCON_STAT(efx, XgTxPausePkts, tx_pause); FALCON_STAT(efx, XgTxPkts64Octets, tx_64); FALCON_STAT(efx, XgTxPkts65to127Octets, tx_65_to_127); FALCON_STAT(efx, XgTxPkts128to255Octets, tx_128_to_255); FALCON_STAT(efx, XgTxPkts256to511Octets, tx_256_to_511); FALCON_STAT(efx, XgTxPkts512to1023Octets, tx_512_to_1023); FALCON_STAT(efx, XgTxPkts1024to15xxOctets, tx_1024_to_15xx); FALCON_STAT(efx, XgTxPkts1519toMaxOctets, tx_15xx_to_jumbo); FALCON_STAT(efx, XgTxUndersizePkts, tx_lt64); FALCON_STAT(efx, XgTxOversizePkts, tx_gtjumbo); FALCON_STAT(efx, XgTxNonTcpUdpPkt, tx_non_tcpudp); FALCON_STAT(efx, XgTxMacSrcErrPkt, tx_mac_src_error); FALCON_STAT(efx, XgTxIpSrcErrPkt, tx_ip_src_error); /* Update derived statistics */ mac_stats->tx_good_bytes = (mac_stats->tx_bytes - mac_stats->tx_bad_bytes - mac_stats->tx_control * 64); mac_stats->rx_bad_bytes = (mac_stats->rx_bytes - mac_stats->rx_good_bytes - mac_stats->rx_control * 64); } void falcon_poll_xmac(struct efx_nic *efx) { struct falcon_nic_data *nic_data = efx->nic_data; if (!EFX_WORKAROUND_5147(efx) || !efx->link_state.up || !nic_data->xmac_poll_required) return; nic_data->xmac_poll_required = !falcon_xmac_link_ok_retry(efx, 1); falcon_ack_status_intr(efx); } const struct efx_mac_operations falcon_xmac_operations = { .reconfigure = falcon_reconfigure_xmac, .update_stats = falcon_update_stats_xmac, .check_fault = falcon_xmac_check_fault, };
gpl-2.0
atomic-penguin/linux
drivers/hwmon/via686a.c
3290
31485
/* via686a.c - Part of lm_sensors, Linux kernel modules for hardware monitoring Copyright (c) 1998 - 2002 Frodo Looijaard <frodol@dds.nl>, Kyösti Mälkki <kmalkki@cc.hut.fi>, Mark Studebaker <mdsxyz123@yahoo.com>, and Bob Dougherty <bobd@stanford.edu> (Some conversion-factor data were contributed by Jonathan Teh Soon Yew <j.teh@iname.com> and Alex van Kaam <darkside@chello.nl>.) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Supports the Via VT82C686A, VT82C686B south bridges. Reports all as a 686A. Warning - only supports a single device. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/slab.h> #include <linux/pci.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/init.h> #include <linux/mutex.h> #include <linux/sysfs.h> #include <linux/acpi.h> #include <linux/io.h> /* If force_addr is set to anything different from 0, we forcibly enable the device at the given address. */ static unsigned short force_addr; module_param(force_addr, ushort, 0); MODULE_PARM_DESC(force_addr, "Initialize the base address of the sensors"); static struct platform_device *pdev; /* The Via 686a southbridge has a LM78-like chip integrated on the same IC. This driver is a customized copy of lm78.c */ /* Many VIA686A constants specified below */ /* Length of ISA address segment */ #define VIA686A_EXTENT 0x80 #define VIA686A_BASE_REG 0x70 #define VIA686A_ENABLE_REG 0x74 /* The VIA686A registers */ /* ins numbered 0-4 */ #define VIA686A_REG_IN_MAX(nr) (0x2b + ((nr) * 2)) #define VIA686A_REG_IN_MIN(nr) (0x2c + ((nr) * 2)) #define VIA686A_REG_IN(nr) (0x22 + (nr)) /* fans numbered 1-2 */ #define VIA686A_REG_FAN_MIN(nr) (0x3a + (nr)) #define VIA686A_REG_FAN(nr) (0x28 + (nr)) /* temps numbered 1-3 */ static const u8 VIA686A_REG_TEMP[] = { 0x20, 0x21, 0x1f }; static const u8 VIA686A_REG_TEMP_OVER[] = { 0x39, 0x3d, 0x1d }; static const u8 VIA686A_REG_TEMP_HYST[] = { 0x3a, 0x3e, 0x1e }; /* bits 7-6 */ #define VIA686A_REG_TEMP_LOW1 0x4b /* 2 = bits 5-4, 3 = bits 7-6 */ #define VIA686A_REG_TEMP_LOW23 0x49 #define VIA686A_REG_ALARM1 0x41 #define VIA686A_REG_ALARM2 0x42 #define VIA686A_REG_FANDIV 0x47 #define VIA686A_REG_CONFIG 0x40 /* The following register sets temp interrupt mode (bits 1-0 for temp1, 3-2 for temp2, 5-4 for temp3). Modes are: 00 interrupt stays as long as value is out-of-range 01 interrupt is cleared once register is read (default) 10 comparator mode- like 00, but ignores hysteresis 11 same as 00 */ #define VIA686A_REG_TEMP_MODE 0x4b /* We'll just assume that you want to set all 3 simultaneously: */ #define VIA686A_TEMP_MODE_MASK 0x3F #define VIA686A_TEMP_MODE_CONTINUOUS 0x00 /* Conversions. Limit checking is only done on the TO_REG variants. ********* VOLTAGE CONVERSIONS (Bob Dougherty) ******** From HWMon.cpp (Copyright 1998-2000 Jonathan Teh Soon Yew): voltagefactor[0]=1.25/2628; (2628/1.25=2102.4) // Vccp voltagefactor[1]=1.25/2628; (2628/1.25=2102.4) // +2.5V voltagefactor[2]=1.67/2628; (2628/1.67=1573.7) // +3.3V voltagefactor[3]=2.6/2628; (2628/2.60=1010.8) // +5V voltagefactor[4]=6.3/2628; (2628/6.30=417.14) // +12V in[i]=(data[i+2]*25.0+133)*voltagefactor[i]; That is: volts = (25*regVal+133)*factor regVal = (volts/factor-133)/25 (These conversions were contributed by Jonathan Teh Soon Yew <j.teh@iname.com>) */ static inline u8 IN_TO_REG(long val, int inNum) { /* To avoid floating point, we multiply constants by 10 (100 for +12V). Rounding is done (120500 is actually 133000 - 12500). Remember that val is expressed in 0.001V/bit, which is why we divide by an additional 10000 (100000 for +12V): 1000 for val and 10 (100) for the constants. */ if (inNum <= 1) return (u8) SENSORS_LIMIT((val * 21024 - 1205000) / 250000, 0, 255); else if (inNum == 2) return (u8) SENSORS_LIMIT((val * 15737 - 1205000) / 250000, 0, 255); else if (inNum == 3) return (u8) SENSORS_LIMIT((val * 10108 - 1205000) / 250000, 0, 255); else return (u8) SENSORS_LIMIT((val * 41714 - 12050000) / 2500000, 0, 255); } static inline long IN_FROM_REG(u8 val, int inNum) { /* To avoid floating point, we multiply constants by 10 (100 for +12V). We also multiply them by 1000 because we want 0.001V/bit for the output value. Rounding is done. */ if (inNum <= 1) return (long) ((250000 * val + 1330000 + 21024 / 2) / 21024); else if (inNum == 2) return (long) ((250000 * val + 1330000 + 15737 / 2) / 15737); else if (inNum == 3) return (long) ((250000 * val + 1330000 + 10108 / 2) / 10108); else return (long) ((2500000 * val + 13300000 + 41714 / 2) / 41714); } /********* FAN RPM CONVERSIONS ********/ /* Higher register values = slower fans (the fan's strobe gates a counter). But this chip saturates back at 0, not at 255 like all the other chips. So, 0 means 0 RPM */ static inline u8 FAN_TO_REG(long rpm, int div) { if (rpm == 0) return 0; rpm = SENSORS_LIMIT(rpm, 1, 1000000); return SENSORS_LIMIT((1350000 + rpm * div / 2) / (rpm * div), 1, 255); } #define FAN_FROM_REG(val,div) ((val)==0?0:(val)==255?0:1350000/((val)*(div))) /******** TEMP CONVERSIONS (Bob Dougherty) *********/ /* linear fits from HWMon.cpp (Copyright 1998-2000 Jonathan Teh Soon Yew) if(temp<169) return double(temp)*0.427-32.08; else if(temp>=169 && temp<=202) return double(temp)*0.582-58.16; else return double(temp)*0.924-127.33; A fifth-order polynomial fits the unofficial data (provided by Alex van Kaam <darkside@chello.nl>) a bit better. It also give more reasonable numbers on my machine (ie. they agree with what my BIOS tells me). Here's the fifth-order fit to the 8-bit data: temp = 1.625093e-10*val^5 - 1.001632e-07*val^4 + 2.457653e-05*val^3 - 2.967619e-03*val^2 + 2.175144e-01*val - 7.090067e+0. (2000-10-25- RFD: thanks to Uwe Andersen <uandersen@mayah.com> for finding my typos in this formula!) Alas, none of the elegant function-fit solutions will work because we aren't allowed to use floating point in the kernel and doing it with integers doesn't provide enough precision. So we'll do boring old look-up table stuff. The unofficial data (see below) have effectively 7-bit resolution (they are rounded to the nearest degree). I'm assuming that the transfer function of the device is monotonic and smooth, so a smooth function fit to the data will allow us to get better precision. I used the 5th-order poly fit described above and solved for VIA register values 0-255. I *10 before rounding, so we get tenth-degree precision. (I could have done all 1024 values for our 10-bit readings, but the function is very linear in the useful range (0-80 deg C), so we'll just use linear interpolation for 10-bit readings.) So, tempLUT is the temp at via register values 0-255: */ static const s16 tempLUT[] = { -709, -688, -667, -646, -627, -607, -589, -570, -553, -536, -519, -503, -487, -471, -456, -442, -428, -414, -400, -387, -375, -362, -350, -339, -327, -316, -305, -295, -285, -275, -265, -255, -246, -237, -229, -220, -212, -204, -196, -188, -180, -173, -166, -159, -152, -145, -139, -132, -126, -120, -114, -108, -102, -96, -91, -85, -80, -74, -69, -64, -59, -54, -49, -44, -39, -34, -29, -25, -20, -15, -11, -6, -2, 3, 7, 12, 16, 20, 25, 29, 33, 37, 42, 46, 50, 54, 59, 63, 67, 71, 75, 79, 84, 88, 92, 96, 100, 104, 109, 113, 117, 121, 125, 130, 134, 138, 142, 146, 151, 155, 159, 163, 168, 172, 176, 181, 185, 189, 193, 198, 202, 206, 211, 215, 219, 224, 228, 232, 237, 241, 245, 250, 254, 259, 263, 267, 272, 276, 281, 285, 290, 294, 299, 303, 307, 312, 316, 321, 325, 330, 334, 339, 344, 348, 353, 357, 362, 366, 371, 376, 380, 385, 390, 395, 399, 404, 409, 414, 419, 423, 428, 433, 438, 443, 449, 454, 459, 464, 469, 475, 480, 486, 491, 497, 502, 508, 514, 520, 526, 532, 538, 544, 551, 557, 564, 571, 578, 584, 592, 599, 606, 614, 621, 629, 637, 645, 654, 662, 671, 680, 689, 698, 708, 718, 728, 738, 749, 759, 770, 782, 793, 805, 818, 830, 843, 856, 870, 883, 898, 912, 927, 943, 958, 975, 991, 1008, 1026, 1044, 1062, 1081, 1101, 1121, 1141, 1162, 1184, 1206, 1229, 1252, 1276, 1301, 1326, 1352, 1378, 1406, 1434, 1462 }; /* the original LUT values from Alex van Kaam <darkside@chello.nl> (for via register values 12-240): {-50,-49,-47,-45,-43,-41,-39,-38,-37,-35,-34,-33,-32,-31, -30,-29,-28,-27,-26,-25,-24,-24,-23,-22,-21,-20,-20,-19,-18,-17,-17,-16,-15, -15,-14,-14,-13,-12,-12,-11,-11,-10,-9,-9,-8,-8,-7,-7,-6,-6,-5,-5,-4,-4,-3, -3,-2,-2,-1,-1,0,0,1,1,1,3,3,3,4,4,4,5,5,5,6,6,7,7,8,8,9,9,9,10,10,11,11,12, 12,12,13,13,13,14,14,15,15,16,16,16,17,17,18,18,19,19,20,20,21,21,21,22,22, 22,23,23,24,24,25,25,26,26,26,27,27,27,28,28,29,29,30,30,30,31,31,32,32,33, 33,34,34,35,35,35,36,36,37,37,38,38,39,39,40,40,41,41,42,42,43,43,44,44,45, 45,46,46,47,48,48,49,49,50,51,51,52,52,53,53,54,55,55,56,57,57,58,59,59,60, 61,62,62,63,64,65,66,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,83,84, 85,86,88,89,91,92,94,96,97,99,101,103,105,107,109,110}; Here's the reverse LUT. I got it by doing a 6-th order poly fit (needed an extra term for a good fit to these inverse data!) and then solving for each temp value from -50 to 110 (the useable range for this chip). Here's the fit: viaRegVal = -1.160370e-10*val^6 +3.193693e-08*val^5 - 1.464447e-06*val^4 - 2.525453e-04*val^3 + 1.424593e-02*val^2 + 2.148941e+00*val +7.275808e+01) Note that n=161: */ static const u8 viaLUT[] = { 12, 12, 13, 14, 14, 15, 16, 16, 17, 18, 18, 19, 20, 20, 21, 22, 23, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 39, 40, 41, 43, 45, 46, 48, 49, 51, 53, 55, 57, 59, 60, 62, 64, 66, 69, 71, 73, 75, 77, 79, 82, 84, 86, 88, 91, 93, 95, 98, 100, 103, 105, 107, 110, 112, 115, 117, 119, 122, 124, 126, 129, 131, 134, 136, 138, 140, 143, 145, 147, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 183, 185, 187, 188, 190, 192, 193, 195, 196, 198, 199, 200, 202, 203, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 222, 223, 224, 225, 226, 226, 227, 228, 228, 229, 230, 230, 231, 232, 232, 233, 233, 234, 235, 235, 236, 236, 237, 237, 238, 238, 239, 239, 240 }; /* Converting temps to (8-bit) hyst and over registers No interpolation here. The +50 is because the temps start at -50 */ static inline u8 TEMP_TO_REG(long val) { return viaLUT[val <= -50000 ? 0 : val >= 110000 ? 160 : (val < 0 ? val - 500 : val + 500) / 1000 + 50]; } /* for 8-bit temperature hyst and over registers */ #define TEMP_FROM_REG(val) ((long)tempLUT[val] * 100) /* for 10-bit temperature readings */ static inline long TEMP_FROM_REG10(u16 val) { u16 eightBits = val >> 2; u16 twoBits = val & 3; /* no interpolation for these */ if (twoBits == 0 || eightBits == 255) return TEMP_FROM_REG(eightBits); /* do some linear interpolation */ return (tempLUT[eightBits] * (4 - twoBits) + tempLUT[eightBits + 1] * twoBits) * 25; } #define DIV_FROM_REG(val) (1 << (val)) #define DIV_TO_REG(val) ((val)==8?3:(val)==4?2:(val)==1?0:1) /* For each registered chip, we need to keep some data in memory. The structure is dynamically allocated. */ struct via686a_data { unsigned short addr; const char *name; struct device *hwmon_dev; struct mutex update_lock; char valid; /* !=0 if following fields are valid */ unsigned long last_updated; /* In jiffies */ u8 in[5]; /* Register value */ u8 in_max[5]; /* Register value */ u8 in_min[5]; /* Register value */ u8 fan[2]; /* Register value */ u8 fan_min[2]; /* Register value */ u16 temp[3]; /* Register value 10 bit */ u8 temp_over[3]; /* Register value */ u8 temp_hyst[3]; /* Register value */ u8 fan_div[2]; /* Register encoding, shifted right */ u16 alarms; /* Register encoding, combined */ }; static struct pci_dev *s_bridge; /* pointer to the (only) via686a */ static int via686a_probe(struct platform_device *pdev); static int __devexit via686a_remove(struct platform_device *pdev); static inline int via686a_read_value(struct via686a_data *data, u8 reg) { return inb_p(data->addr + reg); } static inline void via686a_write_value(struct via686a_data *data, u8 reg, u8 value) { outb_p(value, data->addr + reg); } static struct via686a_data *via686a_update_device(struct device *dev); static void via686a_init_device(struct via686a_data *data); /* following are the sysfs callback functions */ /* 7 voltage sensors */ static ssize_t show_in(struct device *dev, struct device_attribute *da, char *buf) { struct via686a_data *data = via686a_update_device(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(da); int nr = attr->index; return sprintf(buf, "%ld\n", IN_FROM_REG(data->in[nr], nr)); } static ssize_t show_in_min(struct device *dev, struct device_attribute *da, char *buf) { struct via686a_data *data = via686a_update_device(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(da); int nr = attr->index; return sprintf(buf, "%ld\n", IN_FROM_REG(data->in_min[nr], nr)); } static ssize_t show_in_max(struct device *dev, struct device_attribute *da, char *buf) { struct via686a_data *data = via686a_update_device(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(da); int nr = attr->index; return sprintf(buf, "%ld\n", IN_FROM_REG(data->in_max[nr], nr)); } static ssize_t set_in_min(struct device *dev, struct device_attribute *da, const char *buf, size_t count) { struct via686a_data *data = dev_get_drvdata(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(da); int nr = attr->index; unsigned long val = simple_strtoul(buf, NULL, 10); mutex_lock(&data->update_lock); data->in_min[nr] = IN_TO_REG(val, nr); via686a_write_value(data, VIA686A_REG_IN_MIN(nr), data->in_min[nr]); mutex_unlock(&data->update_lock); return count; } static ssize_t set_in_max(struct device *dev, struct device_attribute *da, const char *buf, size_t count) { struct via686a_data *data = dev_get_drvdata(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(da); int nr = attr->index; unsigned long val = simple_strtoul(buf, NULL, 10); mutex_lock(&data->update_lock); data->in_max[nr] = IN_TO_REG(val, nr); via686a_write_value(data, VIA686A_REG_IN_MAX(nr), data->in_max[nr]); mutex_unlock(&data->update_lock); return count; } #define show_in_offset(offset) \ static SENSOR_DEVICE_ATTR(in##offset##_input, S_IRUGO, \ show_in, NULL, offset); \ static SENSOR_DEVICE_ATTR(in##offset##_min, S_IRUGO | S_IWUSR, \ show_in_min, set_in_min, offset); \ static SENSOR_DEVICE_ATTR(in##offset##_max, S_IRUGO | S_IWUSR, \ show_in_max, set_in_max, offset); show_in_offset(0); show_in_offset(1); show_in_offset(2); show_in_offset(3); show_in_offset(4); /* 3 temperatures */ static ssize_t show_temp(struct device *dev, struct device_attribute *da, char *buf) { struct via686a_data *data = via686a_update_device(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(da); int nr = attr->index; return sprintf(buf, "%ld\n", TEMP_FROM_REG10(data->temp[nr])); } static ssize_t show_temp_over(struct device *dev, struct device_attribute *da, char *buf) { struct via686a_data *data = via686a_update_device(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(da); int nr = attr->index; return sprintf(buf, "%ld\n", TEMP_FROM_REG(data->temp_over[nr])); } static ssize_t show_temp_hyst(struct device *dev, struct device_attribute *da, char *buf) { struct via686a_data *data = via686a_update_device(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(da); int nr = attr->index; return sprintf(buf, "%ld\n", TEMP_FROM_REG(data->temp_hyst[nr])); } static ssize_t set_temp_over(struct device *dev, struct device_attribute *da, const char *buf, size_t count) { struct via686a_data *data = dev_get_drvdata(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(da); int nr = attr->index; int val = simple_strtol(buf, NULL, 10); mutex_lock(&data->update_lock); data->temp_over[nr] = TEMP_TO_REG(val); via686a_write_value(data, VIA686A_REG_TEMP_OVER[nr], data->temp_over[nr]); mutex_unlock(&data->update_lock); return count; } static ssize_t set_temp_hyst(struct device *dev, struct device_attribute *da, const char *buf, size_t count) { struct via686a_data *data = dev_get_drvdata(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(da); int nr = attr->index; int val = simple_strtol(buf, NULL, 10); mutex_lock(&data->update_lock); data->temp_hyst[nr] = TEMP_TO_REG(val); via686a_write_value(data, VIA686A_REG_TEMP_HYST[nr], data->temp_hyst[nr]); mutex_unlock(&data->update_lock); return count; } #define show_temp_offset(offset) \ static SENSOR_DEVICE_ATTR(temp##offset##_input, S_IRUGO, \ show_temp, NULL, offset - 1); \ static SENSOR_DEVICE_ATTR(temp##offset##_max, S_IRUGO | S_IWUSR, \ show_temp_over, set_temp_over, offset - 1); \ static SENSOR_DEVICE_ATTR(temp##offset##_max_hyst, S_IRUGO | S_IWUSR, \ show_temp_hyst, set_temp_hyst, offset - 1); show_temp_offset(1); show_temp_offset(2); show_temp_offset(3); /* 2 Fans */ static ssize_t show_fan(struct device *dev, struct device_attribute *da, char *buf) { struct via686a_data *data = via686a_update_device(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(da); int nr = attr->index; return sprintf(buf, "%d\n", FAN_FROM_REG(data->fan[nr], DIV_FROM_REG(data->fan_div[nr])) ); } static ssize_t show_fan_min(struct device *dev, struct device_attribute *da, char *buf) { struct via686a_data *data = via686a_update_device(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(da); int nr = attr->index; return sprintf(buf, "%d\n", FAN_FROM_REG(data->fan_min[nr], DIV_FROM_REG(data->fan_div[nr])) ); } static ssize_t show_fan_div(struct device *dev, struct device_attribute *da, char *buf) { struct via686a_data *data = via686a_update_device(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(da); int nr = attr->index; return sprintf(buf, "%d\n", DIV_FROM_REG(data->fan_div[nr]) ); } static ssize_t set_fan_min(struct device *dev, struct device_attribute *da, const char *buf, size_t count) { struct via686a_data *data = dev_get_drvdata(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(da); int nr = attr->index; int val = simple_strtol(buf, NULL, 10); mutex_lock(&data->update_lock); data->fan_min[nr] = FAN_TO_REG(val, DIV_FROM_REG(data->fan_div[nr])); via686a_write_value(data, VIA686A_REG_FAN_MIN(nr+1), data->fan_min[nr]); mutex_unlock(&data->update_lock); return count; } static ssize_t set_fan_div(struct device *dev, struct device_attribute *da, const char *buf, size_t count) { struct via686a_data *data = dev_get_drvdata(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(da); int nr = attr->index; int val = simple_strtol(buf, NULL, 10); int old; mutex_lock(&data->update_lock); old = via686a_read_value(data, VIA686A_REG_FANDIV); data->fan_div[nr] = DIV_TO_REG(val); old = (old & 0x0f) | (data->fan_div[1] << 6) | (data->fan_div[0] << 4); via686a_write_value(data, VIA686A_REG_FANDIV, old); mutex_unlock(&data->update_lock); return count; } #define show_fan_offset(offset) \ static SENSOR_DEVICE_ATTR(fan##offset##_input, S_IRUGO, \ show_fan, NULL, offset - 1); \ static SENSOR_DEVICE_ATTR(fan##offset##_min, S_IRUGO | S_IWUSR, \ show_fan_min, set_fan_min, offset - 1); \ static SENSOR_DEVICE_ATTR(fan##offset##_div, S_IRUGO | S_IWUSR, \ show_fan_div, set_fan_div, offset - 1); show_fan_offset(1); show_fan_offset(2); /* Alarms */ static ssize_t show_alarms(struct device *dev, struct device_attribute *attr, char *buf) { struct via686a_data *data = via686a_update_device(dev); return sprintf(buf, "%u\n", data->alarms); } static DEVICE_ATTR(alarms, S_IRUGO, show_alarms, NULL); static ssize_t show_alarm(struct device *dev, struct device_attribute *attr, char *buf) { int bitnr = to_sensor_dev_attr(attr)->index; struct via686a_data *data = via686a_update_device(dev); return sprintf(buf, "%u\n", (data->alarms >> bitnr) & 1); } static SENSOR_DEVICE_ATTR(in0_alarm, S_IRUGO, show_alarm, NULL, 0); static SENSOR_DEVICE_ATTR(in1_alarm, S_IRUGO, show_alarm, NULL, 1); static SENSOR_DEVICE_ATTR(in2_alarm, S_IRUGO, show_alarm, NULL, 2); static SENSOR_DEVICE_ATTR(in3_alarm, S_IRUGO, show_alarm, NULL, 3); static SENSOR_DEVICE_ATTR(in4_alarm, S_IRUGO, show_alarm, NULL, 8); static SENSOR_DEVICE_ATTR(temp1_alarm, S_IRUGO, show_alarm, NULL, 4); static SENSOR_DEVICE_ATTR(temp2_alarm, S_IRUGO, show_alarm, NULL, 11); static SENSOR_DEVICE_ATTR(temp3_alarm, S_IRUGO, show_alarm, NULL, 15); static SENSOR_DEVICE_ATTR(fan1_alarm, S_IRUGO, show_alarm, NULL, 6); static SENSOR_DEVICE_ATTR(fan2_alarm, S_IRUGO, show_alarm, NULL, 7); static ssize_t show_name(struct device *dev, struct device_attribute *devattr, char *buf) { struct via686a_data *data = dev_get_drvdata(dev); return sprintf(buf, "%s\n", data->name); } static DEVICE_ATTR(name, S_IRUGO, show_name, NULL); static struct attribute *via686a_attributes[] = { &sensor_dev_attr_in0_input.dev_attr.attr, &sensor_dev_attr_in1_input.dev_attr.attr, &sensor_dev_attr_in2_input.dev_attr.attr, &sensor_dev_attr_in3_input.dev_attr.attr, &sensor_dev_attr_in4_input.dev_attr.attr, &sensor_dev_attr_in0_min.dev_attr.attr, &sensor_dev_attr_in1_min.dev_attr.attr, &sensor_dev_attr_in2_min.dev_attr.attr, &sensor_dev_attr_in3_min.dev_attr.attr, &sensor_dev_attr_in4_min.dev_attr.attr, &sensor_dev_attr_in0_max.dev_attr.attr, &sensor_dev_attr_in1_max.dev_attr.attr, &sensor_dev_attr_in2_max.dev_attr.attr, &sensor_dev_attr_in3_max.dev_attr.attr, &sensor_dev_attr_in4_max.dev_attr.attr, &sensor_dev_attr_in0_alarm.dev_attr.attr, &sensor_dev_attr_in1_alarm.dev_attr.attr, &sensor_dev_attr_in2_alarm.dev_attr.attr, &sensor_dev_attr_in3_alarm.dev_attr.attr, &sensor_dev_attr_in4_alarm.dev_attr.attr, &sensor_dev_attr_temp1_input.dev_attr.attr, &sensor_dev_attr_temp2_input.dev_attr.attr, &sensor_dev_attr_temp3_input.dev_attr.attr, &sensor_dev_attr_temp1_max.dev_attr.attr, &sensor_dev_attr_temp2_max.dev_attr.attr, &sensor_dev_attr_temp3_max.dev_attr.attr, &sensor_dev_attr_temp1_max_hyst.dev_attr.attr, &sensor_dev_attr_temp2_max_hyst.dev_attr.attr, &sensor_dev_attr_temp3_max_hyst.dev_attr.attr, &sensor_dev_attr_temp1_alarm.dev_attr.attr, &sensor_dev_attr_temp2_alarm.dev_attr.attr, &sensor_dev_attr_temp3_alarm.dev_attr.attr, &sensor_dev_attr_fan1_input.dev_attr.attr, &sensor_dev_attr_fan2_input.dev_attr.attr, &sensor_dev_attr_fan1_min.dev_attr.attr, &sensor_dev_attr_fan2_min.dev_attr.attr, &sensor_dev_attr_fan1_div.dev_attr.attr, &sensor_dev_attr_fan2_div.dev_attr.attr, &sensor_dev_attr_fan1_alarm.dev_attr.attr, &sensor_dev_attr_fan2_alarm.dev_attr.attr, &dev_attr_alarms.attr, &dev_attr_name.attr, NULL }; static const struct attribute_group via686a_group = { .attrs = via686a_attributes, }; static struct platform_driver via686a_driver = { .driver = { .owner = THIS_MODULE, .name = "via686a", }, .probe = via686a_probe, .remove = __devexit_p(via686a_remove), }; /* This is called when the module is loaded */ static int __devinit via686a_probe(struct platform_device *pdev) { struct via686a_data *data; struct resource *res; int err; /* Reserve the ISA region */ res = platform_get_resource(pdev, IORESOURCE_IO, 0); if (!request_region(res->start, VIA686A_EXTENT, via686a_driver.driver.name)) { dev_err(&pdev->dev, "Region 0x%lx-0x%lx already in use!\n", (unsigned long)res->start, (unsigned long)res->end); return -ENODEV; } if (!(data = kzalloc(sizeof(struct via686a_data), GFP_KERNEL))) { err = -ENOMEM; goto exit_release; } platform_set_drvdata(pdev, data); data->addr = res->start; data->name = "via686a"; mutex_init(&data->update_lock); /* Initialize the VIA686A chip */ via686a_init_device(data); /* Register sysfs hooks */ if ((err = sysfs_create_group(&pdev->dev.kobj, &via686a_group))) goto exit_free; data->hwmon_dev = hwmon_device_register(&pdev->dev); if (IS_ERR(data->hwmon_dev)) { err = PTR_ERR(data->hwmon_dev); goto exit_remove_files; } return 0; exit_remove_files: sysfs_remove_group(&pdev->dev.kobj, &via686a_group); exit_free: kfree(data); exit_release: release_region(res->start, VIA686A_EXTENT); return err; } static int __devexit via686a_remove(struct platform_device *pdev) { struct via686a_data *data = platform_get_drvdata(pdev); hwmon_device_unregister(data->hwmon_dev); sysfs_remove_group(&pdev->dev.kobj, &via686a_group); release_region(data->addr, VIA686A_EXTENT); platform_set_drvdata(pdev, NULL); kfree(data); return 0; } static void via686a_update_fan_div(struct via686a_data *data) { int reg = via686a_read_value(data, VIA686A_REG_FANDIV); data->fan_div[0] = (reg >> 4) & 0x03; data->fan_div[1] = reg >> 6; } static void __devinit via686a_init_device(struct via686a_data *data) { u8 reg; /* Start monitoring */ reg = via686a_read_value(data, VIA686A_REG_CONFIG); via686a_write_value(data, VIA686A_REG_CONFIG, (reg | 0x01) & 0x7F); /* Configure temp interrupt mode for continuous-interrupt operation */ reg = via686a_read_value(data, VIA686A_REG_TEMP_MODE); via686a_write_value(data, VIA686A_REG_TEMP_MODE, (reg & ~VIA686A_TEMP_MODE_MASK) | VIA686A_TEMP_MODE_CONTINUOUS); /* Pre-read fan clock divisor values */ via686a_update_fan_div(data); } static struct via686a_data *via686a_update_device(struct device *dev) { struct via686a_data *data = dev_get_drvdata(dev); int i; mutex_lock(&data->update_lock); if (time_after(jiffies, data->last_updated + HZ + HZ / 2) || !data->valid) { for (i = 0; i <= 4; i++) { data->in[i] = via686a_read_value(data, VIA686A_REG_IN(i)); data->in_min[i] = via686a_read_value(data, VIA686A_REG_IN_MIN (i)); data->in_max[i] = via686a_read_value(data, VIA686A_REG_IN_MAX(i)); } for (i = 1; i <= 2; i++) { data->fan[i - 1] = via686a_read_value(data, VIA686A_REG_FAN(i)); data->fan_min[i - 1] = via686a_read_value(data, VIA686A_REG_FAN_MIN(i)); } for (i = 0; i <= 2; i++) { data->temp[i] = via686a_read_value(data, VIA686A_REG_TEMP[i]) << 2; data->temp_over[i] = via686a_read_value(data, VIA686A_REG_TEMP_OVER[i]); data->temp_hyst[i] = via686a_read_value(data, VIA686A_REG_TEMP_HYST[i]); } /* add in lower 2 bits temp1 uses bits 7-6 of VIA686A_REG_TEMP_LOW1 temp2 uses bits 5-4 of VIA686A_REG_TEMP_LOW23 temp3 uses bits 7-6 of VIA686A_REG_TEMP_LOW23 */ data->temp[0] |= (via686a_read_value(data, VIA686A_REG_TEMP_LOW1) & 0xc0) >> 6; data->temp[1] |= (via686a_read_value(data, VIA686A_REG_TEMP_LOW23) & 0x30) >> 4; data->temp[2] |= (via686a_read_value(data, VIA686A_REG_TEMP_LOW23) & 0xc0) >> 6; via686a_update_fan_div(data); data->alarms = via686a_read_value(data, VIA686A_REG_ALARM1) | (via686a_read_value(data, VIA686A_REG_ALARM2) << 8); data->last_updated = jiffies; data->valid = 1; } mutex_unlock(&data->update_lock); return data; } static const struct pci_device_id via686a_pci_ids[] = { { PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C686_4) }, { 0, } }; MODULE_DEVICE_TABLE(pci, via686a_pci_ids); static int __devinit via686a_device_add(unsigned short address) { struct resource res = { .start = address, .end = address + VIA686A_EXTENT - 1, .name = "via686a", .flags = IORESOURCE_IO, }; int err; err = acpi_check_resource_conflict(&res); if (err) goto exit; pdev = platform_device_alloc("via686a", address); if (!pdev) { err = -ENOMEM; pr_err("Device allocation failed\n"); goto exit; } err = platform_device_add_resources(pdev, &res, 1); if (err) { pr_err("Device resource addition failed (%d)\n", err); goto exit_device_put; } err = platform_device_add(pdev); if (err) { pr_err("Device addition failed (%d)\n", err); goto exit_device_put; } return 0; exit_device_put: platform_device_put(pdev); exit: return err; } static int __devinit via686a_pci_probe(struct pci_dev *dev, const struct pci_device_id *id) { u16 address, val; if (force_addr) { address = force_addr & ~(VIA686A_EXTENT - 1); dev_warn(&dev->dev, "Forcing ISA address 0x%x\n", address); if (PCIBIOS_SUCCESSFUL != pci_write_config_word(dev, VIA686A_BASE_REG, address | 1)) return -ENODEV; } if (PCIBIOS_SUCCESSFUL != pci_read_config_word(dev, VIA686A_BASE_REG, &val)) return -ENODEV; address = val & ~(VIA686A_EXTENT - 1); if (address == 0) { dev_err(&dev->dev, "base address not set - upgrade BIOS " "or use force_addr=0xaddr\n"); return -ENODEV; } if (PCIBIOS_SUCCESSFUL != pci_read_config_word(dev, VIA686A_ENABLE_REG, &val)) return -ENODEV; if (!(val & 0x0001)) { if (!force_addr) { dev_warn(&dev->dev, "Sensors disabled, enable " "with force_addr=0x%x\n", address); return -ENODEV; } dev_warn(&dev->dev, "Enabling sensors\n"); if (PCIBIOS_SUCCESSFUL != pci_write_config_word(dev, VIA686A_ENABLE_REG, val | 0x0001)) return -ENODEV; } if (platform_driver_register(&via686a_driver)) goto exit; /* Sets global pdev as a side effect */ if (via686a_device_add(address)) goto exit_unregister; /* Always return failure here. This is to allow other drivers to bind * to this pci device. We don't really want to have control over the * pci device, we only wanted to read as few register values from it. */ s_bridge = pci_dev_get(dev); return -ENODEV; exit_unregister: platform_driver_unregister(&via686a_driver); exit: return -ENODEV; } static struct pci_driver via686a_pci_driver = { .name = "via686a", .id_table = via686a_pci_ids, .probe = via686a_pci_probe, }; static int __init sm_via686a_init(void) { return pci_register_driver(&via686a_pci_driver); } static void __exit sm_via686a_exit(void) { pci_unregister_driver(&via686a_pci_driver); if (s_bridge != NULL) { platform_device_unregister(pdev); platform_driver_unregister(&via686a_driver); pci_dev_put(s_bridge); s_bridge = NULL; } } MODULE_AUTHOR("Kyösti Mälkki <kmalkki@cc.hut.fi>, " "Mark Studebaker <mdsxyz123@yahoo.com> " "and Bob Dougherty <bobd@stanford.edu>"); MODULE_DESCRIPTION("VIA 686A Sensor device"); MODULE_LICENSE("GPL"); module_init(sm_via686a_init); module_exit(sm_via686a_exit);
gpl-2.0
peremen/gzone_ics_kernel
sound/usb/usx2y/us122l.c
3290
19486
/* * Copyright (C) 2007, 2008 Karsten Wiese <fzu@wemgehoertderstaat.de> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/slab.h> #include <linux/usb.h> #include <linux/usb/audio.h> #include <sound/core.h> #include <sound/hwdep.h> #include <sound/pcm.h> #include <sound/initval.h> #define MODNAME "US122L" #include "usb_stream.c" #include "../usbaudio.h" #include "../midi.h" #include "us122l.h" MODULE_AUTHOR("Karsten Wiese <fzu@wemgehoertderstaat.de>"); MODULE_DESCRIPTION("TASCAM "NAME_ALLCAPS" Version 0.5"); MODULE_LICENSE("GPL"); static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-max */ static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* Id for this card */ /* Enable this card */ static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; module_param_array(index, int, NULL, 0444); MODULE_PARM_DESC(index, "Index value for "NAME_ALLCAPS"."); module_param_array(id, charp, NULL, 0444); MODULE_PARM_DESC(id, "ID string for "NAME_ALLCAPS"."); module_param_array(enable, bool, NULL, 0444); MODULE_PARM_DESC(enable, "Enable "NAME_ALLCAPS"."); static int snd_us122l_card_used[SNDRV_CARDS]; static int us122l_create_usbmidi(struct snd_card *card) { static struct snd_usb_midi_endpoint_info quirk_data = { .out_ep = 4, .in_ep = 3, .out_cables = 0x001, .in_cables = 0x001 }; static struct snd_usb_audio_quirk quirk = { .vendor_name = "US122L", .product_name = NAME_ALLCAPS, .ifnum = 1, .type = QUIRK_MIDI_US122L, .data = &quirk_data }; struct usb_device *dev = US122L(card)->dev; struct usb_interface *iface = usb_ifnum_to_if(dev, 1); return snd_usbmidi_create(card, iface, &US122L(card)->midi_list, &quirk); } static int us144_create_usbmidi(struct snd_card *card) { static struct snd_usb_midi_endpoint_info quirk_data = { .out_ep = 4, .in_ep = 3, .out_cables = 0x001, .in_cables = 0x001 }; static struct snd_usb_audio_quirk quirk = { .vendor_name = "US144", .product_name = NAME_ALLCAPS, .ifnum = 0, .type = QUIRK_MIDI_US122L, .data = &quirk_data }; struct usb_device *dev = US122L(card)->dev; struct usb_interface *iface = usb_ifnum_to_if(dev, 0); return snd_usbmidi_create(card, iface, &US122L(card)->midi_list, &quirk); } /* * Wrapper for usb_control_msg(). * Allocates a temp buffer to prevent dmaing from/to the stack. */ static int us122l_ctl_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype, __u16 value, __u16 index, void *data, __u16 size, int timeout) { int err; void *buf = NULL; if (size > 0) { buf = kmemdup(data, size, GFP_KERNEL); if (!buf) return -ENOMEM; } err = usb_control_msg(dev, pipe, request, requesttype, value, index, buf, size, timeout); if (size > 0) { memcpy(data, buf, size); kfree(buf); } return err; } static void pt_info_set(struct usb_device *dev, u8 v) { int ret; ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), 'I', USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE, v, 0, NULL, 0, 1000); snd_printdd(KERN_DEBUG "%i\n", ret); } static void usb_stream_hwdep_vm_open(struct vm_area_struct *area) { struct us122l *us122l = area->vm_private_data; atomic_inc(&us122l->mmap_count); snd_printdd(KERN_DEBUG "%i\n", atomic_read(&us122l->mmap_count)); } static int usb_stream_hwdep_vm_fault(struct vm_area_struct *area, struct vm_fault *vmf) { unsigned long offset; struct page *page; void *vaddr; struct us122l *us122l = area->vm_private_data; struct usb_stream *s; mutex_lock(&us122l->mutex); s = us122l->sk.s; if (!s) goto unlock; offset = vmf->pgoff << PAGE_SHIFT; if (offset < PAGE_ALIGN(s->read_size)) vaddr = (char *)s + offset; else { offset -= PAGE_ALIGN(s->read_size); if (offset >= PAGE_ALIGN(s->write_size)) goto unlock; vaddr = us122l->sk.write_page + offset; } page = virt_to_page(vaddr); get_page(page); mutex_unlock(&us122l->mutex); vmf->page = page; return 0; unlock: mutex_unlock(&us122l->mutex); return VM_FAULT_SIGBUS; } static void usb_stream_hwdep_vm_close(struct vm_area_struct *area) { struct us122l *us122l = area->vm_private_data; atomic_dec(&us122l->mmap_count); snd_printdd(KERN_DEBUG "%i\n", atomic_read(&us122l->mmap_count)); } static const struct vm_operations_struct usb_stream_hwdep_vm_ops = { .open = usb_stream_hwdep_vm_open, .fault = usb_stream_hwdep_vm_fault, .close = usb_stream_hwdep_vm_close, }; static int usb_stream_hwdep_open(struct snd_hwdep *hw, struct file *file) { struct us122l *us122l = hw->private_data; struct usb_interface *iface; snd_printdd(KERN_DEBUG "%p %p\n", hw, file); if (hw->used >= 2) return -EBUSY; if (!us122l->first) us122l->first = file; if (us122l->dev->descriptor.idProduct == USB_ID_US144 || us122l->dev->descriptor.idProduct == USB_ID_US144MKII) { iface = usb_ifnum_to_if(us122l->dev, 0); usb_autopm_get_interface(iface); } iface = usb_ifnum_to_if(us122l->dev, 1); usb_autopm_get_interface(iface); return 0; } static int usb_stream_hwdep_release(struct snd_hwdep *hw, struct file *file) { struct us122l *us122l = hw->private_data; struct usb_interface *iface; snd_printdd(KERN_DEBUG "%p %p\n", hw, file); if (us122l->dev->descriptor.idProduct == USB_ID_US144 || us122l->dev->descriptor.idProduct == USB_ID_US144MKII) { iface = usb_ifnum_to_if(us122l->dev, 0); usb_autopm_put_interface(iface); } iface = usb_ifnum_to_if(us122l->dev, 1); usb_autopm_put_interface(iface); if (us122l->first == file) us122l->first = NULL; mutex_lock(&us122l->mutex); if (us122l->master == file) us122l->master = us122l->slave; us122l->slave = NULL; mutex_unlock(&us122l->mutex); return 0; } static int usb_stream_hwdep_mmap(struct snd_hwdep *hw, struct file *filp, struct vm_area_struct *area) { unsigned long size = area->vm_end - area->vm_start; struct us122l *us122l = hw->private_data; unsigned long offset; struct usb_stream *s; int err = 0; bool read; offset = area->vm_pgoff << PAGE_SHIFT; mutex_lock(&us122l->mutex); s = us122l->sk.s; read = offset < s->read_size; if (read && area->vm_flags & VM_WRITE) { err = -EPERM; goto out; } snd_printdd(KERN_DEBUG "%lu %u\n", size, read ? s->read_size : s->write_size); /* if userspace tries to mmap beyond end of our buffer, fail */ if (size > PAGE_ALIGN(read ? s->read_size : s->write_size)) { snd_printk(KERN_WARNING "%lu > %u\n", size, read ? s->read_size : s->write_size); err = -EINVAL; goto out; } area->vm_ops = &usb_stream_hwdep_vm_ops; area->vm_flags |= VM_RESERVED; area->vm_private_data = us122l; atomic_inc(&us122l->mmap_count); out: mutex_unlock(&us122l->mutex); return err; } static unsigned int usb_stream_hwdep_poll(struct snd_hwdep *hw, struct file *file, poll_table *wait) { struct us122l *us122l = hw->private_data; unsigned *polled; unsigned int mask; poll_wait(file, &us122l->sk.sleep, wait); mask = POLLIN | POLLOUT | POLLWRNORM | POLLERR; if (mutex_trylock(&us122l->mutex)) { struct usb_stream *s = us122l->sk.s; if (s && s->state == usb_stream_ready) { if (us122l->first == file) polled = &s->periods_polled; else polled = &us122l->second_periods_polled; if (*polled != s->periods_done) { *polled = s->periods_done; mask = POLLIN | POLLOUT | POLLWRNORM; } else mask = 0; } mutex_unlock(&us122l->mutex); } return mask; } static void us122l_stop(struct us122l *us122l) { struct list_head *p; list_for_each(p, &us122l->midi_list) snd_usbmidi_input_stop(p); usb_stream_stop(&us122l->sk); usb_stream_free(&us122l->sk); } static int us122l_set_sample_rate(struct usb_device *dev, int rate) { unsigned int ep = 0x81; unsigned char data[3]; int err; data[0] = rate; data[1] = rate >> 8; data[2] = rate >> 16; err = us122l_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC_SET_CUR, USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT, UAC_EP_CS_ATTR_SAMPLE_RATE << 8, ep, data, 3, 1000); if (err < 0) snd_printk(KERN_ERR "%d: cannot set freq %d to ep 0x%x\n", dev->devnum, rate, ep); return err; } static bool us122l_start(struct us122l *us122l, unsigned rate, unsigned period_frames) { struct list_head *p; int err; unsigned use_packsize = 0; bool success = false; if (us122l->dev->speed == USB_SPEED_HIGH) { /* The us-122l's descriptor defaults to iso max_packsize 78, which isn't needed for samplerates <= 48000. Lets save some memory: */ switch (rate) { case 44100: use_packsize = 36; break; case 48000: use_packsize = 42; break; case 88200: use_packsize = 72; break; } } if (!usb_stream_new(&us122l->sk, us122l->dev, 1, 2, rate, use_packsize, period_frames, 6)) goto out; err = us122l_set_sample_rate(us122l->dev, rate); if (err < 0) { us122l_stop(us122l); snd_printk(KERN_ERR "us122l_set_sample_rate error \n"); goto out; } err = usb_stream_start(&us122l->sk); if (err < 0) { us122l_stop(us122l); snd_printk(KERN_ERR "us122l_start error %i \n", err); goto out; } list_for_each(p, &us122l->midi_list) snd_usbmidi_input_start(p); success = true; out: return success; } static int usb_stream_hwdep_ioctl(struct snd_hwdep *hw, struct file *file, unsigned cmd, unsigned long arg) { struct usb_stream_config *cfg; struct us122l *us122l = hw->private_data; struct usb_stream *s; unsigned min_period_frames; int err = 0; bool high_speed; if (cmd != SNDRV_USB_STREAM_IOCTL_SET_PARAMS) return -ENOTTY; cfg = memdup_user((void *)arg, sizeof(*cfg)); if (IS_ERR(cfg)) return PTR_ERR(cfg); if (cfg->version != USB_STREAM_INTERFACE_VERSION) { err = -ENXIO; goto free; } high_speed = us122l->dev->speed == USB_SPEED_HIGH; if ((cfg->sample_rate != 44100 && cfg->sample_rate != 48000 && (!high_speed || (cfg->sample_rate != 88200 && cfg->sample_rate != 96000))) || cfg->frame_size != 6 || cfg->period_frames > 0x3000) { err = -EINVAL; goto free; } switch (cfg->sample_rate) { case 44100: min_period_frames = 48; break; case 48000: min_period_frames = 52; break; default: min_period_frames = 104; break; } if (!high_speed) min_period_frames <<= 1; if (cfg->period_frames < min_period_frames) { err = -EINVAL; goto free; } snd_power_wait(hw->card, SNDRV_CTL_POWER_D0); mutex_lock(&us122l->mutex); s = us122l->sk.s; if (!us122l->master) us122l->master = file; else if (us122l->master != file) { if (!s || memcmp(cfg, &s->cfg, sizeof(*cfg))) { err = -EIO; goto unlock; } us122l->slave = file; } if (!s || memcmp(cfg, &s->cfg, sizeof(*cfg)) || s->state == usb_stream_xrun) { us122l_stop(us122l); if (!us122l_start(us122l, cfg->sample_rate, cfg->period_frames)) err = -EIO; else err = 1; } unlock: mutex_unlock(&us122l->mutex); free: kfree(cfg); wake_up_all(&us122l->sk.sleep); return err; } #define SND_USB_STREAM_ID "USB STREAM" static int usb_stream_hwdep_new(struct snd_card *card) { int err; struct snd_hwdep *hw; struct usb_device *dev = US122L(card)->dev; err = snd_hwdep_new(card, SND_USB_STREAM_ID, 0, &hw); if (err < 0) return err; hw->iface = SNDRV_HWDEP_IFACE_USB_STREAM; hw->private_data = US122L(card); hw->ops.open = usb_stream_hwdep_open; hw->ops.release = usb_stream_hwdep_release; hw->ops.ioctl = usb_stream_hwdep_ioctl; hw->ops.ioctl_compat = usb_stream_hwdep_ioctl; hw->ops.mmap = usb_stream_hwdep_mmap; hw->ops.poll = usb_stream_hwdep_poll; sprintf(hw->name, "/proc/bus/usb/%03d/%03d/hwdeppcm", dev->bus->busnum, dev->devnum); return 0; } static bool us122l_create_card(struct snd_card *card) { int err; struct us122l *us122l = US122L(card); if (us122l->dev->descriptor.idProduct == USB_ID_US144 || us122l->dev->descriptor.idProduct == USB_ID_US144MKII) { err = usb_set_interface(us122l->dev, 0, 1); if (err) { snd_printk(KERN_ERR "usb_set_interface error \n"); return false; } } err = usb_set_interface(us122l->dev, 1, 1); if (err) { snd_printk(KERN_ERR "usb_set_interface error \n"); return false; } pt_info_set(us122l->dev, 0x11); pt_info_set(us122l->dev, 0x10); if (!us122l_start(us122l, 44100, 256)) return false; if (us122l->dev->descriptor.idProduct == USB_ID_US144 || us122l->dev->descriptor.idProduct == USB_ID_US144MKII) err = us144_create_usbmidi(card); else err = us122l_create_usbmidi(card); if (err < 0) { snd_printk(KERN_ERR "us122l_create_usbmidi error %i \n", err); us122l_stop(us122l); return false; } err = usb_stream_hwdep_new(card); if (err < 0) { /* release the midi resources */ struct list_head *p; list_for_each(p, &us122l->midi_list) snd_usbmidi_disconnect(p); us122l_stop(us122l); return false; } return true; } static void snd_us122l_free(struct snd_card *card) { struct us122l *us122l = US122L(card); int index = us122l->card_index; if (index >= 0 && index < SNDRV_CARDS) snd_us122l_card_used[index] = 0; } static int usx2y_create_card(struct usb_device *device, struct snd_card **cardp) { int dev; struct snd_card *card; int err; for (dev = 0; dev < SNDRV_CARDS; ++dev) if (enable[dev] && !snd_us122l_card_used[dev]) break; if (dev >= SNDRV_CARDS) return -ENODEV; err = snd_card_create(index[dev], id[dev], THIS_MODULE, sizeof(struct us122l), &card); if (err < 0) return err; snd_us122l_card_used[US122L(card)->card_index = dev] = 1; card->private_free = snd_us122l_free; US122L(card)->dev = device; mutex_init(&US122L(card)->mutex); init_waitqueue_head(&US122L(card)->sk.sleep); INIT_LIST_HEAD(&US122L(card)->midi_list); strcpy(card->driver, "USB "NAME_ALLCAPS""); sprintf(card->shortname, "TASCAM "NAME_ALLCAPS""); sprintf(card->longname, "%s (%x:%x if %d at %03d/%03d)", card->shortname, le16_to_cpu(device->descriptor.idVendor), le16_to_cpu(device->descriptor.idProduct), 0, US122L(card)->dev->bus->busnum, US122L(card)->dev->devnum ); *cardp = card; return 0; } static int us122l_usb_probe(struct usb_interface *intf, const struct usb_device_id *device_id, struct snd_card **cardp) { struct usb_device *device = interface_to_usbdev(intf); struct snd_card *card; int err; err = usx2y_create_card(device, &card); if (err < 0) return err; snd_card_set_dev(card, &intf->dev); if (!us122l_create_card(card)) { snd_card_free(card); return -EINVAL; } err = snd_card_register(card); if (err < 0) { snd_card_free(card); return err; } usb_get_intf(usb_ifnum_to_if(device, 0)); usb_get_dev(device); *cardp = card; return 0; } static int snd_us122l_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *device = interface_to_usbdev(intf); struct snd_card *card; int err; if ((device->descriptor.idProduct == USB_ID_US144 || device->descriptor.idProduct == USB_ID_US144MKII) && device->speed == USB_SPEED_HIGH) { snd_printk(KERN_ERR "disable ehci-hcd to run US-144 \n"); return -ENODEV; } snd_printdd(KERN_DEBUG"%p:%i\n", intf, intf->cur_altsetting->desc.bInterfaceNumber); if (intf->cur_altsetting->desc.bInterfaceNumber != 1) return 0; err = us122l_usb_probe(usb_get_intf(intf), id, &card); if (err < 0) { usb_put_intf(intf); return err; } usb_set_intfdata(intf, card); return 0; } static void snd_us122l_disconnect(struct usb_interface *intf) { struct snd_card *card; struct us122l *us122l; struct list_head *p; card = usb_get_intfdata(intf); if (!card) return; snd_card_disconnect(card); us122l = US122L(card); mutex_lock(&us122l->mutex); us122l_stop(us122l); mutex_unlock(&us122l->mutex); /* release the midi resources */ list_for_each(p, &us122l->midi_list) { snd_usbmidi_disconnect(p); } usb_put_intf(usb_ifnum_to_if(us122l->dev, 0)); usb_put_intf(usb_ifnum_to_if(us122l->dev, 1)); usb_put_dev(us122l->dev); while (atomic_read(&us122l->mmap_count)) msleep(500); snd_card_free(card); } static int snd_us122l_suspend(struct usb_interface *intf, pm_message_t message) { struct snd_card *card; struct us122l *us122l; struct list_head *p; card = usb_get_intfdata(intf); if (!card) return 0; snd_power_change_state(card, SNDRV_CTL_POWER_D3hot); us122l = US122L(card); if (!us122l) return 0; list_for_each(p, &us122l->midi_list) snd_usbmidi_input_stop(p); mutex_lock(&us122l->mutex); usb_stream_stop(&us122l->sk); mutex_unlock(&us122l->mutex); return 0; } static int snd_us122l_resume(struct usb_interface *intf) { struct snd_card *card; struct us122l *us122l; struct list_head *p; int err; card = usb_get_intfdata(intf); if (!card) return 0; us122l = US122L(card); if (!us122l) return 0; mutex_lock(&us122l->mutex); /* needed, doesn't restart without: */ if (us122l->dev->descriptor.idProduct == USB_ID_US144 || us122l->dev->descriptor.idProduct == USB_ID_US144MKII) { err = usb_set_interface(us122l->dev, 0, 1); if (err) { snd_printk(KERN_ERR "usb_set_interface error \n"); goto unlock; } } err = usb_set_interface(us122l->dev, 1, 1); if (err) { snd_printk(KERN_ERR "usb_set_interface error \n"); goto unlock; } pt_info_set(us122l->dev, 0x11); pt_info_set(us122l->dev, 0x10); err = us122l_set_sample_rate(us122l->dev, us122l->sk.s->cfg.sample_rate); if (err < 0) { snd_printk(KERN_ERR "us122l_set_sample_rate error \n"); goto unlock; } err = usb_stream_start(&us122l->sk); if (err) goto unlock; list_for_each(p, &us122l->midi_list) snd_usbmidi_input_start(p); unlock: mutex_unlock(&us122l->mutex); snd_power_change_state(card, SNDRV_CTL_POWER_D0); return err; } static struct usb_device_id snd_us122l_usb_id_table[] = { { .match_flags = USB_DEVICE_ID_MATCH_DEVICE, .idVendor = 0x0644, .idProduct = USB_ID_US122L }, { /* US-144 only works at USB1.1! Disable module ehci-hcd. */ .match_flags = USB_DEVICE_ID_MATCH_DEVICE, .idVendor = 0x0644, .idProduct = USB_ID_US144 }, { .match_flags = USB_DEVICE_ID_MATCH_DEVICE, .idVendor = 0x0644, .idProduct = USB_ID_US122MKII }, { .match_flags = USB_DEVICE_ID_MATCH_DEVICE, .idVendor = 0x0644, .idProduct = USB_ID_US144MKII }, { /* terminator */ } }; MODULE_DEVICE_TABLE(usb, snd_us122l_usb_id_table); static struct usb_driver snd_us122l_usb_driver = { .name = "snd-usb-us122l", .probe = snd_us122l_probe, .disconnect = snd_us122l_disconnect, .suspend = snd_us122l_suspend, .resume = snd_us122l_resume, .reset_resume = snd_us122l_resume, .id_table = snd_us122l_usb_id_table, .supports_autosuspend = 1 }; static int __init snd_us122l_module_init(void) { return usb_register(&snd_us122l_usb_driver); } static void __exit snd_us122l_module_exit(void) { usb_deregister(&snd_us122l_usb_driver); } module_init(snd_us122l_module_init) module_exit(snd_us122l_module_exit)
gpl-2.0
AlbertXingZhang/android_kernel_sony_msm8x60
arch/arm/mach-orion5x/rd88f6183ap-ge-setup.c
4826
3278
/* * arch/arm/mach-orion5x/rd88f6183-ap-ge-setup.c * * Marvell Orion-1-90 AP GE Reference Design Setup * * 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/gpio.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/pci.h> #include <linux/irq.h> #include <linux/mtd/physmap.h> #include <linux/mv643xx_eth.h> #include <linux/spi/spi.h> #include <linux/spi/orion_spi.h> #include <linux/spi/flash.h> #include <linux/ethtool.h> #include <net/dsa.h> #include <asm/mach-types.h> #include <asm/leds.h> #include <asm/mach/arch.h> #include <asm/mach/pci.h> #include <mach/orion5x.h> #include "common.h" static struct mv643xx_eth_platform_data rd88f6183ap_ge_eth_data = { .phy_addr = -1, .speed = SPEED_1000, .duplex = DUPLEX_FULL, }; static struct dsa_chip_data rd88f6183ap_ge_switch_chip_data = { .port_names[0] = "lan1", .port_names[1] = "lan2", .port_names[2] = "lan3", .port_names[3] = "lan4", .port_names[4] = "wan", .port_names[5] = "cpu", }; static struct dsa_platform_data rd88f6183ap_ge_switch_plat_data = { .nr_chips = 1, .chip = &rd88f6183ap_ge_switch_chip_data, }; static struct mtd_partition rd88f6183ap_ge_partitions[] = { { .name = "kernel", .offset = 0x00000000, .size = 0x00200000, }, { .name = "rootfs", .offset = 0x00200000, .size = 0x00500000, }, { .name = "nvram", .offset = 0x00700000, .size = 0x00080000, }, }; static struct flash_platform_data rd88f6183ap_ge_spi_slave_data = { .type = "m25p64", .nr_parts = ARRAY_SIZE(rd88f6183ap_ge_partitions), .parts = rd88f6183ap_ge_partitions, }; static struct spi_board_info __initdata rd88f6183ap_ge_spi_slave_info[] = { { .modalias = "m25p80", .platform_data = &rd88f6183ap_ge_spi_slave_data, .irq = NO_IRQ, .max_speed_hz = 20000000, .bus_num = 0, .chip_select = 0, }, }; static void __init rd88f6183ap_ge_init(void) { /* * Setup basic Orion functions. Need to be called early. */ orion5x_init(); /* * Configure peripherals. */ orion5x_ehci0_init(); orion5x_eth_init(&rd88f6183ap_ge_eth_data); orion5x_eth_switch_init(&rd88f6183ap_ge_switch_plat_data, gpio_to_irq(3)); spi_register_board_info(rd88f6183ap_ge_spi_slave_info, ARRAY_SIZE(rd88f6183ap_ge_spi_slave_info)); orion5x_spi_init(); orion5x_uart0_init(); } static struct hw_pci rd88f6183ap_ge_pci __initdata = { .nr_controllers = 2, .swizzle = pci_std_swizzle, .setup = orion5x_pci_sys_setup, .scan = orion5x_pci_sys_scan_bus, .map_irq = orion5x_pci_map_irq, }; static int __init rd88f6183ap_ge_pci_init(void) { if (machine_is_rd88f6183ap_ge()) { orion5x_pci_disable(); pci_common_init(&rd88f6183ap_ge_pci); } return 0; } subsys_initcall(rd88f6183ap_ge_pci_init); MACHINE_START(RD88F6183AP_GE, "Marvell Orion-1-90 AP GE Reference Design") /* Maintainer: Lennert Buytenhek <buytenh@marvell.com> */ .atag_offset = 0x100, .init_machine = rd88f6183ap_ge_init, .map_io = orion5x_map_io, .init_early = orion5x_init_early, .init_irq = orion5x_init_irq, .timer = &orion5x_timer, .fixup = tag_fixup_mem32, .restart = orion5x_restart, MACHINE_END
gpl-2.0
CYB0RG97/kernel_nvidia_s8515
arch/arm/mach-orion5x/rd88f6183ap-ge-setup.c
4826
3278
/* * arch/arm/mach-orion5x/rd88f6183-ap-ge-setup.c * * Marvell Orion-1-90 AP GE Reference Design Setup * * 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/gpio.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/pci.h> #include <linux/irq.h> #include <linux/mtd/physmap.h> #include <linux/mv643xx_eth.h> #include <linux/spi/spi.h> #include <linux/spi/orion_spi.h> #include <linux/spi/flash.h> #include <linux/ethtool.h> #include <net/dsa.h> #include <asm/mach-types.h> #include <asm/leds.h> #include <asm/mach/arch.h> #include <asm/mach/pci.h> #include <mach/orion5x.h> #include "common.h" static struct mv643xx_eth_platform_data rd88f6183ap_ge_eth_data = { .phy_addr = -1, .speed = SPEED_1000, .duplex = DUPLEX_FULL, }; static struct dsa_chip_data rd88f6183ap_ge_switch_chip_data = { .port_names[0] = "lan1", .port_names[1] = "lan2", .port_names[2] = "lan3", .port_names[3] = "lan4", .port_names[4] = "wan", .port_names[5] = "cpu", }; static struct dsa_platform_data rd88f6183ap_ge_switch_plat_data = { .nr_chips = 1, .chip = &rd88f6183ap_ge_switch_chip_data, }; static struct mtd_partition rd88f6183ap_ge_partitions[] = { { .name = "kernel", .offset = 0x00000000, .size = 0x00200000, }, { .name = "rootfs", .offset = 0x00200000, .size = 0x00500000, }, { .name = "nvram", .offset = 0x00700000, .size = 0x00080000, }, }; static struct flash_platform_data rd88f6183ap_ge_spi_slave_data = { .type = "m25p64", .nr_parts = ARRAY_SIZE(rd88f6183ap_ge_partitions), .parts = rd88f6183ap_ge_partitions, }; static struct spi_board_info __initdata rd88f6183ap_ge_spi_slave_info[] = { { .modalias = "m25p80", .platform_data = &rd88f6183ap_ge_spi_slave_data, .irq = NO_IRQ, .max_speed_hz = 20000000, .bus_num = 0, .chip_select = 0, }, }; static void __init rd88f6183ap_ge_init(void) { /* * Setup basic Orion functions. Need to be called early. */ orion5x_init(); /* * Configure peripherals. */ orion5x_ehci0_init(); orion5x_eth_init(&rd88f6183ap_ge_eth_data); orion5x_eth_switch_init(&rd88f6183ap_ge_switch_plat_data, gpio_to_irq(3)); spi_register_board_info(rd88f6183ap_ge_spi_slave_info, ARRAY_SIZE(rd88f6183ap_ge_spi_slave_info)); orion5x_spi_init(); orion5x_uart0_init(); } static struct hw_pci rd88f6183ap_ge_pci __initdata = { .nr_controllers = 2, .swizzle = pci_std_swizzle, .setup = orion5x_pci_sys_setup, .scan = orion5x_pci_sys_scan_bus, .map_irq = orion5x_pci_map_irq, }; static int __init rd88f6183ap_ge_pci_init(void) { if (machine_is_rd88f6183ap_ge()) { orion5x_pci_disable(); pci_common_init(&rd88f6183ap_ge_pci); } return 0; } subsys_initcall(rd88f6183ap_ge_pci_init); MACHINE_START(RD88F6183AP_GE, "Marvell Orion-1-90 AP GE Reference Design") /* Maintainer: Lennert Buytenhek <buytenh@marvell.com> */ .atag_offset = 0x100, .init_machine = rd88f6183ap_ge_init, .map_io = orion5x_map_io, .init_early = orion5x_init_early, .init_irq = orion5x_init_irq, .timer = &orion5x_timer, .fixup = tag_fixup_mem32, .restart = orion5x_restart, MACHINE_END
gpl-2.0
xjljian/android_kernel_huawei_msm8226
sound/isa/sb/sb16_csp.c
7642
33507
/* * Copyright (c) 1999 by Uros Bizjak <uros@kss-loka.si> * Takashi Iwai <tiwai@suse.de> * * SB16ASP/AWE32 CSP control * * CSP microcode loader: * alsa-tools/sb16_csp/ * * 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/delay.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/module.h> #include <sound/core.h> #include <sound/control.h> #include <sound/info.h> #include <sound/sb16_csp.h> #include <sound/initval.h> MODULE_AUTHOR("Uros Bizjak <uros@kss-loka.si>"); MODULE_DESCRIPTION("ALSA driver for SB16 Creative Signal Processor"); MODULE_LICENSE("GPL"); MODULE_FIRMWARE("sb16/mulaw_main.csp"); MODULE_FIRMWARE("sb16/alaw_main.csp"); MODULE_FIRMWARE("sb16/ima_adpcm_init.csp"); MODULE_FIRMWARE("sb16/ima_adpcm_playback.csp"); MODULE_FIRMWARE("sb16/ima_adpcm_capture.csp"); #ifdef SNDRV_LITTLE_ENDIAN #define CSP_HDR_VALUE(a,b,c,d) ((a) | ((b)<<8) | ((c)<<16) | ((d)<<24)) #else #define CSP_HDR_VALUE(a,b,c,d) ((d) | ((c)<<8) | ((b)<<16) | ((a)<<24)) #endif #define RIFF_HEADER CSP_HDR_VALUE('R', 'I', 'F', 'F') #define CSP__HEADER CSP_HDR_VALUE('C', 'S', 'P', ' ') #define LIST_HEADER CSP_HDR_VALUE('L', 'I', 'S', 'T') #define FUNC_HEADER CSP_HDR_VALUE('f', 'u', 'n', 'c') #define CODE_HEADER CSP_HDR_VALUE('c', 'o', 'd', 'e') #define INIT_HEADER CSP_HDR_VALUE('i', 'n', 'i', 't') #define MAIN_HEADER CSP_HDR_VALUE('m', 'a', 'i', 'n') /* * RIFF data format */ struct riff_header { __u32 name; __u32 len; }; struct desc_header { struct riff_header info; __u16 func_nr; __u16 VOC_type; __u16 flags_play_rec; __u16 flags_16bit_8bit; __u16 flags_stereo_mono; __u16 flags_rates; }; /* * prototypes */ static void snd_sb_csp_free(struct snd_hwdep *hw); static int snd_sb_csp_open(struct snd_hwdep * hw, struct file *file); static int snd_sb_csp_ioctl(struct snd_hwdep * hw, struct file *file, unsigned int cmd, unsigned long arg); static int snd_sb_csp_release(struct snd_hwdep * hw, struct file *file); static int csp_detect(struct snd_sb *chip, int *version); static int set_codec_parameter(struct snd_sb *chip, unsigned char par, unsigned char val); static int set_register(struct snd_sb *chip, unsigned char reg, unsigned char val); static int read_register(struct snd_sb *chip, unsigned char reg); static int set_mode_register(struct snd_sb *chip, unsigned char mode); static int get_version(struct snd_sb *chip); static int snd_sb_csp_riff_load(struct snd_sb_csp * p, struct snd_sb_csp_microcode __user * code); static int snd_sb_csp_unload(struct snd_sb_csp * p); static int snd_sb_csp_load_user(struct snd_sb_csp * p, const unsigned char __user *buf, int size, int load_flags); static int snd_sb_csp_autoload(struct snd_sb_csp * p, int pcm_sfmt, int play_rec_mode); static int snd_sb_csp_check_version(struct snd_sb_csp * p); static int snd_sb_csp_use(struct snd_sb_csp * p); static int snd_sb_csp_unuse(struct snd_sb_csp * p); static int snd_sb_csp_start(struct snd_sb_csp * p, int sample_width, int channels); static int snd_sb_csp_stop(struct snd_sb_csp * p); static int snd_sb_csp_pause(struct snd_sb_csp * p); static int snd_sb_csp_restart(struct snd_sb_csp * p); static int snd_sb_qsound_build(struct snd_sb_csp * p); static void snd_sb_qsound_destroy(struct snd_sb_csp * p); static int snd_sb_csp_qsound_transfer(struct snd_sb_csp * p); static int init_proc_entry(struct snd_sb_csp * p, int device); static void info_read(struct snd_info_entry *entry, struct snd_info_buffer *buffer); /* * Detect CSP chip and create a new instance */ int snd_sb_csp_new(struct snd_sb *chip, int device, struct snd_hwdep ** rhwdep) { struct snd_sb_csp *p; int uninitialized_var(version); int err; struct snd_hwdep *hw; if (rhwdep) *rhwdep = NULL; if (csp_detect(chip, &version)) return -ENODEV; if ((err = snd_hwdep_new(chip->card, "SB16-CSP", device, &hw)) < 0) return err; if ((p = kzalloc(sizeof(*p), GFP_KERNEL)) == NULL) { snd_device_free(chip->card, hw); return -ENOMEM; } p->chip = chip; p->version = version; /* CSP operators */ p->ops.csp_use = snd_sb_csp_use; p->ops.csp_unuse = snd_sb_csp_unuse; p->ops.csp_autoload = snd_sb_csp_autoload; p->ops.csp_start = snd_sb_csp_start; p->ops.csp_stop = snd_sb_csp_stop; p->ops.csp_qsound_transfer = snd_sb_csp_qsound_transfer; mutex_init(&p->access_mutex); sprintf(hw->name, "CSP v%d.%d", (version >> 4), (version & 0x0f)); hw->iface = SNDRV_HWDEP_IFACE_SB16CSP; hw->private_data = p; hw->private_free = snd_sb_csp_free; /* operators - only write/ioctl */ hw->ops.open = snd_sb_csp_open; hw->ops.ioctl = snd_sb_csp_ioctl; hw->ops.release = snd_sb_csp_release; /* create a proc entry */ init_proc_entry(p, device); if (rhwdep) *rhwdep = hw; return 0; } /* * free_private for hwdep instance */ static void snd_sb_csp_free(struct snd_hwdep *hwdep) { int i; struct snd_sb_csp *p = hwdep->private_data; if (p) { if (p->running & SNDRV_SB_CSP_ST_RUNNING) snd_sb_csp_stop(p); for (i = 0; i < ARRAY_SIZE(p->csp_programs); ++i) release_firmware(p->csp_programs[i]); kfree(p); } } /* ------------------------------ */ /* * open the device exclusively */ static int snd_sb_csp_open(struct snd_hwdep * hw, struct file *file) { struct snd_sb_csp *p = hw->private_data; return (snd_sb_csp_use(p)); } /* * ioctl for hwdep device: */ static int snd_sb_csp_ioctl(struct snd_hwdep * hw, struct file *file, unsigned int cmd, unsigned long arg) { struct snd_sb_csp *p = hw->private_data; struct snd_sb_csp_info info; struct snd_sb_csp_start start_info; int err; if (snd_BUG_ON(!p)) return -EINVAL; if (snd_sb_csp_check_version(p)) return -ENODEV; switch (cmd) { /* get information */ case SNDRV_SB_CSP_IOCTL_INFO: *info.codec_name = *p->codec_name; info.func_nr = p->func_nr; info.acc_format = p->acc_format; info.acc_channels = p->acc_channels; info.acc_width = p->acc_width; info.acc_rates = p->acc_rates; info.csp_mode = p->mode; info.run_channels = p->run_channels; info.run_width = p->run_width; info.version = p->version; info.state = p->running; if (copy_to_user((void __user *)arg, &info, sizeof(info))) err = -EFAULT; else err = 0; break; /* load CSP microcode */ case SNDRV_SB_CSP_IOCTL_LOAD_CODE: err = (p->running & SNDRV_SB_CSP_ST_RUNNING ? -EBUSY : snd_sb_csp_riff_load(p, (struct snd_sb_csp_microcode __user *) arg)); break; case SNDRV_SB_CSP_IOCTL_UNLOAD_CODE: err = (p->running & SNDRV_SB_CSP_ST_RUNNING ? -EBUSY : snd_sb_csp_unload(p)); break; /* change CSP running state */ case SNDRV_SB_CSP_IOCTL_START: if (copy_from_user(&start_info, (void __user *) arg, sizeof(start_info))) err = -EFAULT; else err = snd_sb_csp_start(p, start_info.sample_width, start_info.channels); break; case SNDRV_SB_CSP_IOCTL_STOP: err = snd_sb_csp_stop(p); break; case SNDRV_SB_CSP_IOCTL_PAUSE: err = snd_sb_csp_pause(p); break; case SNDRV_SB_CSP_IOCTL_RESTART: err = snd_sb_csp_restart(p); break; default: err = -ENOTTY; break; } return err; } /* * close the device */ static int snd_sb_csp_release(struct snd_hwdep * hw, struct file *file) { struct snd_sb_csp *p = hw->private_data; return (snd_sb_csp_unuse(p)); } /* ------------------------------ */ /* * acquire device */ static int snd_sb_csp_use(struct snd_sb_csp * p) { mutex_lock(&p->access_mutex); if (p->used) { mutex_unlock(&p->access_mutex); return -EAGAIN; } p->used++; mutex_unlock(&p->access_mutex); return 0; } /* * release device */ static int snd_sb_csp_unuse(struct snd_sb_csp * p) { mutex_lock(&p->access_mutex); p->used--; mutex_unlock(&p->access_mutex); return 0; } /* * load microcode via ioctl: * code is user-space pointer */ static int snd_sb_csp_riff_load(struct snd_sb_csp * p, struct snd_sb_csp_microcode __user * mcode) { struct snd_sb_csp_mc_header info; unsigned char __user *data_ptr; unsigned char __user *data_end; unsigned short func_nr = 0; struct riff_header file_h, item_h, code_h; __u32 item_type; struct desc_header funcdesc_h; unsigned long flags; int err; if (copy_from_user(&info, mcode, sizeof(info))) return -EFAULT; data_ptr = mcode->data; if (copy_from_user(&file_h, data_ptr, sizeof(file_h))) return -EFAULT; if ((file_h.name != RIFF_HEADER) || (le32_to_cpu(file_h.len) >= SNDRV_SB_CSP_MAX_MICROCODE_FILE_SIZE - sizeof(file_h))) { snd_printd("%s: Invalid RIFF header\n", __func__); return -EINVAL; } data_ptr += sizeof(file_h); data_end = data_ptr + le32_to_cpu(file_h.len); if (copy_from_user(&item_type, data_ptr, sizeof(item_type))) return -EFAULT; if (item_type != CSP__HEADER) { snd_printd("%s: Invalid RIFF file type\n", __func__); return -EINVAL; } data_ptr += sizeof (item_type); for (; data_ptr < data_end; data_ptr += le32_to_cpu(item_h.len)) { if (copy_from_user(&item_h, data_ptr, sizeof(item_h))) return -EFAULT; data_ptr += sizeof(item_h); if (item_h.name != LIST_HEADER) continue; if (copy_from_user(&item_type, data_ptr, sizeof(item_type))) return -EFAULT; switch (item_type) { case FUNC_HEADER: if (copy_from_user(&funcdesc_h, data_ptr + sizeof(item_type), sizeof(funcdesc_h))) return -EFAULT; func_nr = le16_to_cpu(funcdesc_h.func_nr); break; case CODE_HEADER: if (func_nr != info.func_req) break; /* not required function, try next */ data_ptr += sizeof(item_type); /* destroy QSound mixer element */ if (p->mode == SNDRV_SB_CSP_MODE_QSOUND) { snd_sb_qsound_destroy(p); } /* Clear all flags */ p->running = 0; p->mode = 0; /* load microcode blocks */ for (;;) { if (data_ptr >= data_end) return -EINVAL; if (copy_from_user(&code_h, data_ptr, sizeof(code_h))) return -EFAULT; /* init microcode blocks */ if (code_h.name != INIT_HEADER) break; data_ptr += sizeof(code_h); err = snd_sb_csp_load_user(p, data_ptr, le32_to_cpu(code_h.len), SNDRV_SB_CSP_LOAD_INITBLOCK); if (err) return err; data_ptr += le32_to_cpu(code_h.len); } /* main microcode block */ if (copy_from_user(&code_h, data_ptr, sizeof(code_h))) return -EFAULT; if (code_h.name != MAIN_HEADER) { snd_printd("%s: Missing 'main' microcode\n", __func__); return -EINVAL; } data_ptr += sizeof(code_h); err = snd_sb_csp_load_user(p, data_ptr, le32_to_cpu(code_h.len), 0); if (err) return err; /* fill in codec header */ strlcpy(p->codec_name, info.codec_name, sizeof(p->codec_name)); p->func_nr = func_nr; p->mode = le16_to_cpu(funcdesc_h.flags_play_rec); switch (le16_to_cpu(funcdesc_h.VOC_type)) { case 0x0001: /* QSound decoder */ if (le16_to_cpu(funcdesc_h.flags_play_rec) == SNDRV_SB_CSP_MODE_DSP_WRITE) { if (snd_sb_qsound_build(p) == 0) /* set QSound flag and clear all other mode flags */ p->mode = SNDRV_SB_CSP_MODE_QSOUND; } p->acc_format = 0; break; case 0x0006: /* A Law codec */ p->acc_format = SNDRV_PCM_FMTBIT_A_LAW; break; case 0x0007: /* Mu Law codec */ p->acc_format = SNDRV_PCM_FMTBIT_MU_LAW; break; case 0x0011: /* what Creative thinks is IMA ADPCM codec */ case 0x0200: /* Creative ADPCM codec */ p->acc_format = SNDRV_PCM_FMTBIT_IMA_ADPCM; break; case 201: /* Text 2 Speech decoder */ /* TODO: Text2Speech handling routines */ p->acc_format = 0; break; case 0x0202: /* Fast Speech 8 codec */ case 0x0203: /* Fast Speech 10 codec */ p->acc_format = SNDRV_PCM_FMTBIT_SPECIAL; break; default: /* other codecs are unsupported */ p->acc_format = p->acc_width = p->acc_rates = 0; p->mode = 0; snd_printd("%s: Unsupported CSP codec type: 0x%04x\n", __func__, le16_to_cpu(funcdesc_h.VOC_type)); return -EINVAL; } p->acc_channels = le16_to_cpu(funcdesc_h.flags_stereo_mono); p->acc_width = le16_to_cpu(funcdesc_h.flags_16bit_8bit); p->acc_rates = le16_to_cpu(funcdesc_h.flags_rates); /* Decouple CSP from IRQ and DMAREQ lines */ spin_lock_irqsave(&p->chip->reg_lock, flags); set_mode_register(p->chip, 0xfc); set_mode_register(p->chip, 0x00); spin_unlock_irqrestore(&p->chip->reg_lock, flags); /* finished loading successfully */ p->running = SNDRV_SB_CSP_ST_LOADED; /* set LOADED flag */ return 0; } } snd_printd("%s: Function #%d not found\n", __func__, info.func_req); return -EINVAL; } /* * unload CSP microcode */ static int snd_sb_csp_unload(struct snd_sb_csp * p) { if (p->running & SNDRV_SB_CSP_ST_RUNNING) return -EBUSY; if (!(p->running & SNDRV_SB_CSP_ST_LOADED)) return -ENXIO; /* clear supported formats */ p->acc_format = 0; p->acc_channels = p->acc_width = p->acc_rates = 0; /* destroy QSound mixer element */ if (p->mode == SNDRV_SB_CSP_MODE_QSOUND) { snd_sb_qsound_destroy(p); } /* clear all flags */ p->running = 0; p->mode = 0; return 0; } /* * send command sequence to DSP */ static inline int command_seq(struct snd_sb *chip, const unsigned char *seq, int size) { int i; for (i = 0; i < size; i++) { if (!snd_sbdsp_command(chip, seq[i])) return -EIO; } return 0; } /* * set CSP codec parameter */ static int set_codec_parameter(struct snd_sb *chip, unsigned char par, unsigned char val) { unsigned char dsp_cmd[3]; dsp_cmd[0] = 0x05; /* CSP set codec parameter */ dsp_cmd[1] = val; /* Parameter value */ dsp_cmd[2] = par; /* Parameter */ command_seq(chip, dsp_cmd, 3); snd_sbdsp_command(chip, 0x03); /* DSP read? */ if (snd_sbdsp_get_byte(chip) != par) return -EIO; return 0; } /* * set CSP register */ static int set_register(struct snd_sb *chip, unsigned char reg, unsigned char val) { unsigned char dsp_cmd[3]; dsp_cmd[0] = 0x0e; /* CSP set register */ dsp_cmd[1] = reg; /* CSP Register */ dsp_cmd[2] = val; /* value */ return command_seq(chip, dsp_cmd, 3); } /* * read CSP register * return < 0 -> error */ static int read_register(struct snd_sb *chip, unsigned char reg) { unsigned char dsp_cmd[2]; dsp_cmd[0] = 0x0f; /* CSP read register */ dsp_cmd[1] = reg; /* CSP Register */ command_seq(chip, dsp_cmd, 2); return snd_sbdsp_get_byte(chip); /* Read DSP value */ } /* * set CSP mode register */ static int set_mode_register(struct snd_sb *chip, unsigned char mode) { unsigned char dsp_cmd[2]; dsp_cmd[0] = 0x04; /* CSP set mode register */ dsp_cmd[1] = mode; /* mode */ return command_seq(chip, dsp_cmd, 2); } /* * Detect CSP * return 0 if CSP exists. */ static int csp_detect(struct snd_sb *chip, int *version) { unsigned char csp_test1, csp_test2; unsigned long flags; int result = -ENODEV; spin_lock_irqsave(&chip->reg_lock, flags); set_codec_parameter(chip, 0x00, 0x00); set_mode_register(chip, 0xfc); /* 0xfc = ?? */ csp_test1 = read_register(chip, 0x83); set_register(chip, 0x83, ~csp_test1); csp_test2 = read_register(chip, 0x83); if (csp_test2 != (csp_test1 ^ 0xff)) goto __fail; set_register(chip, 0x83, csp_test1); csp_test2 = read_register(chip, 0x83); if (csp_test2 != csp_test1) goto __fail; set_mode_register(chip, 0x00); /* 0x00 = ? */ *version = get_version(chip); snd_sbdsp_reset(chip); /* reset DSP after getversion! */ if (*version >= 0x10 && *version <= 0x1f) result = 0; /* valid version id */ __fail: spin_unlock_irqrestore(&chip->reg_lock, flags); return result; } /* * get CSP version number */ static int get_version(struct snd_sb *chip) { unsigned char dsp_cmd[2]; dsp_cmd[0] = 0x08; /* SB_DSP_!something! */ dsp_cmd[1] = 0x03; /* get chip version id? */ command_seq(chip, dsp_cmd, 2); return (snd_sbdsp_get_byte(chip)); } /* * check if the CSP version is valid */ static int snd_sb_csp_check_version(struct snd_sb_csp * p) { if (p->version < 0x10 || p->version > 0x1f) { snd_printd("%s: Invalid CSP version: 0x%x\n", __func__, p->version); return 1; } return 0; } /* * download microcode to CSP (microcode should have one "main" block). */ static int snd_sb_csp_load(struct snd_sb_csp * p, const unsigned char *buf, int size, int load_flags) { int status, i; int err; int result = -EIO; unsigned long flags; spin_lock_irqsave(&p->chip->reg_lock, flags); snd_sbdsp_command(p->chip, 0x01); /* CSP download command */ if (snd_sbdsp_get_byte(p->chip)) { snd_printd("%s: Download command failed\n", __func__); goto __fail; } /* Send CSP low byte (size - 1) */ snd_sbdsp_command(p->chip, (unsigned char)(size - 1)); /* Send high byte */ snd_sbdsp_command(p->chip, (unsigned char)((size - 1) >> 8)); /* send microcode sequence */ /* load from kernel space */ while (size--) { if (!snd_sbdsp_command(p->chip, *buf++)) goto __fail; } if (snd_sbdsp_get_byte(p->chip)) goto __fail; if (load_flags & SNDRV_SB_CSP_LOAD_INITBLOCK) { i = 0; /* some codecs (FastSpeech) take some time to initialize */ while (1) { snd_sbdsp_command(p->chip, 0x03); status = snd_sbdsp_get_byte(p->chip); if (status == 0x55 || ++i >= 10) break; udelay (10); } if (status != 0x55) { snd_printd("%s: Microcode initialization failed\n", __func__); goto __fail; } } else { /* * Read mixer register SB_DSP4_DMASETUP after loading 'main' code. * Start CSP chip if no 16bit DMA channel is set - some kind * of autorun or perhaps a bugfix? */ spin_lock(&p->chip->mixer_lock); status = snd_sbmixer_read(p->chip, SB_DSP4_DMASETUP); spin_unlock(&p->chip->mixer_lock); if (!(status & (SB_DMASETUP_DMA7 | SB_DMASETUP_DMA6 | SB_DMASETUP_DMA5))) { err = (set_codec_parameter(p->chip, 0xaa, 0x00) || set_codec_parameter(p->chip, 0xff, 0x00)); snd_sbdsp_reset(p->chip); /* really! */ if (err) goto __fail; set_mode_register(p->chip, 0xc0); /* c0 = STOP */ set_mode_register(p->chip, 0x70); /* 70 = RUN */ } } result = 0; __fail: spin_unlock_irqrestore(&p->chip->reg_lock, flags); return result; } static int snd_sb_csp_load_user(struct snd_sb_csp * p, const unsigned char __user *buf, int size, int load_flags) { int err; unsigned char *kbuf; kbuf = memdup_user(buf, size); if (IS_ERR(kbuf)) return PTR_ERR(kbuf); err = snd_sb_csp_load(p, kbuf, size, load_flags); kfree(kbuf); return err; } static int snd_sb_csp_firmware_load(struct snd_sb_csp *p, int index, int flags) { static const char *const names[] = { "sb16/mulaw_main.csp", "sb16/alaw_main.csp", "sb16/ima_adpcm_init.csp", "sb16/ima_adpcm_playback.csp", "sb16/ima_adpcm_capture.csp", }; const struct firmware *program; BUILD_BUG_ON(ARRAY_SIZE(names) != CSP_PROGRAM_COUNT); program = p->csp_programs[index]; if (!program) { int err = request_firmware(&program, names[index], p->chip->card->dev); if (err < 0) return err; p->csp_programs[index] = program; } return snd_sb_csp_load(p, program->data, program->size, flags); } /* * autoload hardware codec if necessary * return 0 if CSP is loaded and ready to run (p->running != 0) */ static int snd_sb_csp_autoload(struct snd_sb_csp * p, int pcm_sfmt, int play_rec_mode) { unsigned long flags; int err = 0; /* if CSP is running or manually loaded then exit */ if (p->running & (SNDRV_SB_CSP_ST_RUNNING | SNDRV_SB_CSP_ST_LOADED)) return -EBUSY; /* autoload microcode only if requested hardware codec is not already loaded */ if (((1 << pcm_sfmt) & p->acc_format) && (play_rec_mode & p->mode)) { p->running = SNDRV_SB_CSP_ST_AUTO; } else { switch (pcm_sfmt) { case SNDRV_PCM_FORMAT_MU_LAW: err = snd_sb_csp_firmware_load(p, CSP_PROGRAM_MULAW, 0); p->acc_format = SNDRV_PCM_FMTBIT_MU_LAW; p->mode = SNDRV_SB_CSP_MODE_DSP_READ | SNDRV_SB_CSP_MODE_DSP_WRITE; break; case SNDRV_PCM_FORMAT_A_LAW: err = snd_sb_csp_firmware_load(p, CSP_PROGRAM_ALAW, 0); p->acc_format = SNDRV_PCM_FMTBIT_A_LAW; p->mode = SNDRV_SB_CSP_MODE_DSP_READ | SNDRV_SB_CSP_MODE_DSP_WRITE; break; case SNDRV_PCM_FORMAT_IMA_ADPCM: err = snd_sb_csp_firmware_load(p, CSP_PROGRAM_ADPCM_INIT, SNDRV_SB_CSP_LOAD_INITBLOCK); if (err) break; if (play_rec_mode == SNDRV_SB_CSP_MODE_DSP_WRITE) { err = snd_sb_csp_firmware_load (p, CSP_PROGRAM_ADPCM_PLAYBACK, 0); p->mode = SNDRV_SB_CSP_MODE_DSP_WRITE; } else { err = snd_sb_csp_firmware_load (p, CSP_PROGRAM_ADPCM_CAPTURE, 0); p->mode = SNDRV_SB_CSP_MODE_DSP_READ; } p->acc_format = SNDRV_PCM_FMTBIT_IMA_ADPCM; break; default: /* Decouple CSP from IRQ and DMAREQ lines */ if (p->running & SNDRV_SB_CSP_ST_AUTO) { spin_lock_irqsave(&p->chip->reg_lock, flags); set_mode_register(p->chip, 0xfc); set_mode_register(p->chip, 0x00); spin_unlock_irqrestore(&p->chip->reg_lock, flags); p->running = 0; /* clear autoloaded flag */ } return -EINVAL; } if (err) { p->acc_format = 0; p->acc_channels = p->acc_width = p->acc_rates = 0; p->running = 0; /* clear autoloaded flag */ p->mode = 0; return (err); } else { p->running = SNDRV_SB_CSP_ST_AUTO; /* set autoloaded flag */ p->acc_width = SNDRV_SB_CSP_SAMPLE_16BIT; /* only 16 bit data */ p->acc_channels = SNDRV_SB_CSP_MONO | SNDRV_SB_CSP_STEREO; p->acc_rates = SNDRV_SB_CSP_RATE_ALL; /* HW codecs accept all rates */ } } return (p->running & SNDRV_SB_CSP_ST_AUTO) ? 0 : -ENXIO; } /* * start CSP */ static int snd_sb_csp_start(struct snd_sb_csp * p, int sample_width, int channels) { unsigned char s_type; /* sample type */ unsigned char mixL, mixR; int result = -EIO; unsigned long flags; if (!(p->running & (SNDRV_SB_CSP_ST_LOADED | SNDRV_SB_CSP_ST_AUTO))) { snd_printd("%s: Microcode not loaded\n", __func__); return -ENXIO; } if (p->running & SNDRV_SB_CSP_ST_RUNNING) { snd_printd("%s: CSP already running\n", __func__); return -EBUSY; } if (!(sample_width & p->acc_width)) { snd_printd("%s: Unsupported PCM sample width\n", __func__); return -EINVAL; } if (!(channels & p->acc_channels)) { snd_printd("%s: Invalid number of channels\n", __func__); return -EINVAL; } /* Mute PCM volume */ spin_lock_irqsave(&p->chip->mixer_lock, flags); mixL = snd_sbmixer_read(p->chip, SB_DSP4_PCM_DEV); mixR = snd_sbmixer_read(p->chip, SB_DSP4_PCM_DEV + 1); snd_sbmixer_write(p->chip, SB_DSP4_PCM_DEV, mixL & 0x7); snd_sbmixer_write(p->chip, SB_DSP4_PCM_DEV + 1, mixR & 0x7); spin_lock(&p->chip->reg_lock); set_mode_register(p->chip, 0xc0); /* c0 = STOP */ set_mode_register(p->chip, 0x70); /* 70 = RUN */ s_type = 0x00; if (channels == SNDRV_SB_CSP_MONO) s_type = 0x11; /* 000n 000n (n = 1 if mono) */ if (sample_width == SNDRV_SB_CSP_SAMPLE_8BIT) s_type |= 0x22; /* 00dX 00dX (d = 1 if 8 bit samples) */ if (set_codec_parameter(p->chip, 0x81, s_type)) { snd_printd("%s: Set sample type command failed\n", __func__); goto __fail; } if (set_codec_parameter(p->chip, 0x80, 0x00)) { snd_printd("%s: Codec start command failed\n", __func__); goto __fail; } p->run_width = sample_width; p->run_channels = channels; p->running |= SNDRV_SB_CSP_ST_RUNNING; if (p->mode & SNDRV_SB_CSP_MODE_QSOUND) { set_codec_parameter(p->chip, 0xe0, 0x01); /* enable QSound decoder */ set_codec_parameter(p->chip, 0x00, 0xff); set_codec_parameter(p->chip, 0x01, 0xff); p->running |= SNDRV_SB_CSP_ST_QSOUND; /* set QSound startup value */ snd_sb_csp_qsound_transfer(p); } result = 0; __fail: spin_unlock(&p->chip->reg_lock); /* restore PCM volume */ snd_sbmixer_write(p->chip, SB_DSP4_PCM_DEV, mixL); snd_sbmixer_write(p->chip, SB_DSP4_PCM_DEV + 1, mixR); spin_unlock_irqrestore(&p->chip->mixer_lock, flags); return result; } /* * stop CSP */ static int snd_sb_csp_stop(struct snd_sb_csp * p) { int result; unsigned char mixL, mixR; unsigned long flags; if (!(p->running & SNDRV_SB_CSP_ST_RUNNING)) return 0; /* Mute PCM volume */ spin_lock_irqsave(&p->chip->mixer_lock, flags); mixL = snd_sbmixer_read(p->chip, SB_DSP4_PCM_DEV); mixR = snd_sbmixer_read(p->chip, SB_DSP4_PCM_DEV + 1); snd_sbmixer_write(p->chip, SB_DSP4_PCM_DEV, mixL & 0x7); snd_sbmixer_write(p->chip, SB_DSP4_PCM_DEV + 1, mixR & 0x7); spin_lock(&p->chip->reg_lock); if (p->running & SNDRV_SB_CSP_ST_QSOUND) { set_codec_parameter(p->chip, 0xe0, 0x01); /* disable QSound decoder */ set_codec_parameter(p->chip, 0x00, 0x00); set_codec_parameter(p->chip, 0x01, 0x00); p->running &= ~SNDRV_SB_CSP_ST_QSOUND; } result = set_mode_register(p->chip, 0xc0); /* c0 = STOP */ spin_unlock(&p->chip->reg_lock); /* restore PCM volume */ snd_sbmixer_write(p->chip, SB_DSP4_PCM_DEV, mixL); snd_sbmixer_write(p->chip, SB_DSP4_PCM_DEV + 1, mixR); spin_unlock_irqrestore(&p->chip->mixer_lock, flags); if (!(result)) p->running &= ~(SNDRV_SB_CSP_ST_PAUSED | SNDRV_SB_CSP_ST_RUNNING); return result; } /* * pause CSP codec and hold DMA transfer */ static int snd_sb_csp_pause(struct snd_sb_csp * p) { int result; unsigned long flags; if (!(p->running & SNDRV_SB_CSP_ST_RUNNING)) return -EBUSY; spin_lock_irqsave(&p->chip->reg_lock, flags); result = set_codec_parameter(p->chip, 0x80, 0xff); spin_unlock_irqrestore(&p->chip->reg_lock, flags); if (!(result)) p->running |= SNDRV_SB_CSP_ST_PAUSED; return result; } /* * restart CSP codec and resume DMA transfer */ static int snd_sb_csp_restart(struct snd_sb_csp * p) { int result; unsigned long flags; if (!(p->running & SNDRV_SB_CSP_ST_PAUSED)) return -EBUSY; spin_lock_irqsave(&p->chip->reg_lock, flags); result = set_codec_parameter(p->chip, 0x80, 0x00); spin_unlock_irqrestore(&p->chip->reg_lock, flags); if (!(result)) p->running &= ~SNDRV_SB_CSP_ST_PAUSED; return result; } /* ------------------------------ */ /* * QSound mixer control for PCM */ #define snd_sb_qsound_switch_info snd_ctl_boolean_mono_info static int snd_sb_qsound_switch_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_sb_csp *p = snd_kcontrol_chip(kcontrol); ucontrol->value.integer.value[0] = p->q_enabled ? 1 : 0; return 0; } static int snd_sb_qsound_switch_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_sb_csp *p = snd_kcontrol_chip(kcontrol); unsigned long flags; int change; unsigned char nval; nval = ucontrol->value.integer.value[0] & 0x01; spin_lock_irqsave(&p->q_lock, flags); change = p->q_enabled != nval; p->q_enabled = nval; spin_unlock_irqrestore(&p->q_lock, flags); return change; } static int snd_sb_qsound_space_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; uinfo->count = 2; uinfo->value.integer.min = 0; uinfo->value.integer.max = SNDRV_SB_CSP_QSOUND_MAX_RIGHT; return 0; } static int snd_sb_qsound_space_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_sb_csp *p = snd_kcontrol_chip(kcontrol); unsigned long flags; spin_lock_irqsave(&p->q_lock, flags); ucontrol->value.integer.value[0] = p->qpos_left; ucontrol->value.integer.value[1] = p->qpos_right; spin_unlock_irqrestore(&p->q_lock, flags); return 0; } static int snd_sb_qsound_space_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_sb_csp *p = snd_kcontrol_chip(kcontrol); unsigned long flags; int change; unsigned char nval1, nval2; nval1 = ucontrol->value.integer.value[0]; if (nval1 > SNDRV_SB_CSP_QSOUND_MAX_RIGHT) nval1 = SNDRV_SB_CSP_QSOUND_MAX_RIGHT; nval2 = ucontrol->value.integer.value[1]; if (nval2 > SNDRV_SB_CSP_QSOUND_MAX_RIGHT) nval2 = SNDRV_SB_CSP_QSOUND_MAX_RIGHT; spin_lock_irqsave(&p->q_lock, flags); change = p->qpos_left != nval1 || p->qpos_right != nval2; p->qpos_left = nval1; p->qpos_right = nval2; p->qpos_changed = change; spin_unlock_irqrestore(&p->q_lock, flags); return change; } static struct snd_kcontrol_new snd_sb_qsound_switch = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "3D Control - Switch", .info = snd_sb_qsound_switch_info, .get = snd_sb_qsound_switch_get, .put = snd_sb_qsound_switch_put }; static struct snd_kcontrol_new snd_sb_qsound_space = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "3D Control - Space", .info = snd_sb_qsound_space_info, .get = snd_sb_qsound_space_get, .put = snd_sb_qsound_space_put }; static int snd_sb_qsound_build(struct snd_sb_csp * p) { struct snd_card *card; int err; if (snd_BUG_ON(!p)) return -EINVAL; card = p->chip->card; p->qpos_left = p->qpos_right = SNDRV_SB_CSP_QSOUND_MAX_RIGHT / 2; p->qpos_changed = 0; spin_lock_init(&p->q_lock); if ((err = snd_ctl_add(card, p->qsound_switch = snd_ctl_new1(&snd_sb_qsound_switch, p))) < 0) goto __error; if ((err = snd_ctl_add(card, p->qsound_space = snd_ctl_new1(&snd_sb_qsound_space, p))) < 0) goto __error; return 0; __error: snd_sb_qsound_destroy(p); return err; } static void snd_sb_qsound_destroy(struct snd_sb_csp * p) { struct snd_card *card; unsigned long flags; if (snd_BUG_ON(!p)) return; card = p->chip->card; down_write(&card->controls_rwsem); if (p->qsound_switch) snd_ctl_remove(card, p->qsound_switch); if (p->qsound_space) snd_ctl_remove(card, p->qsound_space); up_write(&card->controls_rwsem); /* cancel pending transfer of QSound parameters */ spin_lock_irqsave (&p->q_lock, flags); p->qpos_changed = 0; spin_unlock_irqrestore (&p->q_lock, flags); } /* * Transfer qsound parameters to CSP, * function should be called from interrupt routine */ static int snd_sb_csp_qsound_transfer(struct snd_sb_csp * p) { int err = -ENXIO; spin_lock(&p->q_lock); if (p->running & SNDRV_SB_CSP_ST_QSOUND) { set_codec_parameter(p->chip, 0xe0, 0x01); /* left channel */ set_codec_parameter(p->chip, 0x00, p->qpos_left); set_codec_parameter(p->chip, 0x02, 0x00); /* right channel */ set_codec_parameter(p->chip, 0x00, p->qpos_right); set_codec_parameter(p->chip, 0x03, 0x00); err = 0; } p->qpos_changed = 0; spin_unlock(&p->q_lock); return err; } /* ------------------------------ */ /* * proc interface */ static int init_proc_entry(struct snd_sb_csp * p, int device) { char name[16]; struct snd_info_entry *entry; sprintf(name, "cspD%d", device); if (! snd_card_proc_new(p->chip->card, name, &entry)) snd_info_set_text_ops(entry, p, info_read); return 0; } static void info_read(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_sb_csp *p = entry->private_data; snd_iprintf(buffer, "Creative Signal Processor [v%d.%d]\n", (p->version >> 4), (p->version & 0x0f)); snd_iprintf(buffer, "State: %cx%c%c%c\n", ((p->running & SNDRV_SB_CSP_ST_QSOUND) ? 'Q' : '-'), ((p->running & SNDRV_SB_CSP_ST_PAUSED) ? 'P' : '-'), ((p->running & SNDRV_SB_CSP_ST_RUNNING) ? 'R' : '-'), ((p->running & SNDRV_SB_CSP_ST_LOADED) ? 'L' : '-')); if (p->running & SNDRV_SB_CSP_ST_LOADED) { snd_iprintf(buffer, "Codec: %s [func #%d]\n", p->codec_name, p->func_nr); snd_iprintf(buffer, "Sample rates: "); if (p->acc_rates == SNDRV_SB_CSP_RATE_ALL) { snd_iprintf(buffer, "All\n"); } else { snd_iprintf(buffer, "%s%s%s%s\n", ((p->acc_rates & SNDRV_SB_CSP_RATE_8000) ? "8000Hz " : ""), ((p->acc_rates & SNDRV_SB_CSP_RATE_11025) ? "11025Hz " : ""), ((p->acc_rates & SNDRV_SB_CSP_RATE_22050) ? "22050Hz " : ""), ((p->acc_rates & SNDRV_SB_CSP_RATE_44100) ? "44100Hz" : "")); } if (p->mode == SNDRV_SB_CSP_MODE_QSOUND) { snd_iprintf(buffer, "QSound decoder %sabled\n", p->q_enabled ? "en" : "dis"); } else { snd_iprintf(buffer, "PCM format ID: 0x%x (%s/%s) [%s/%s] [%s/%s]\n", p->acc_format, ((p->acc_width & SNDRV_SB_CSP_SAMPLE_16BIT) ? "16bit" : "-"), ((p->acc_width & SNDRV_SB_CSP_SAMPLE_8BIT) ? "8bit" : "-"), ((p->acc_channels & SNDRV_SB_CSP_MONO) ? "mono" : "-"), ((p->acc_channels & SNDRV_SB_CSP_STEREO) ? "stereo" : "-"), ((p->mode & SNDRV_SB_CSP_MODE_DSP_WRITE) ? "playback" : "-"), ((p->mode & SNDRV_SB_CSP_MODE_DSP_READ) ? "capture" : "-")); } } if (p->running & SNDRV_SB_CSP_ST_AUTO) { snd_iprintf(buffer, "Autoloaded Mu-Law, A-Law or Ima-ADPCM hardware codec\n"); } if (p->running & SNDRV_SB_CSP_ST_RUNNING) { snd_iprintf(buffer, "Processing %dbit %s PCM samples\n", ((p->run_width & SNDRV_SB_CSP_SAMPLE_16BIT) ? 16 : 8), ((p->run_channels & SNDRV_SB_CSP_MONO) ? "mono" : "stereo")); } if (p->running & SNDRV_SB_CSP_ST_QSOUND) { snd_iprintf(buffer, "Qsound position: left = 0x%x, right = 0x%x\n", p->qpos_left, p->qpos_right); } } /* */ EXPORT_SYMBOL(snd_sb_csp_new); /* * INIT part */ static int __init alsa_sb_csp_init(void) { return 0; } static void __exit alsa_sb_csp_exit(void) { } module_init(alsa_sb_csp_init) module_exit(alsa_sb_csp_exit)
gpl-2.0
cm-b2g/platform_kernel_lge_msm
drivers/ide/tx4938ide.c
8410
5873
/* * TX4938 internal IDE driver * Based on tx4939ide.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. * * (C) Copyright TOSHIBA CORPORATION 2005-2007 */ #include <linux/module.h> #include <linux/types.h> #include <linux/ide.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/io.h> #include <asm/ide.h> #include <asm/txx9/tx4938.h> static void tx4938ide_tune_ebusc(unsigned int ebus_ch, unsigned int gbus_clock, u8 pio) { struct ide_timing *t = ide_timing_find_mode(XFER_PIO_0 + pio); u64 cr = __raw_readq(&tx4938_ebuscptr->cr[ebus_ch]); unsigned int sp = (cr >> 4) & 3; unsigned int clock = gbus_clock / (4 - sp); unsigned int cycle = 1000000000 / clock; unsigned int shwt; int wt; /* Minimum DIOx- active time */ wt = DIV_ROUND_UP(t->act8b, cycle) - 2; /* IORDY setup time: 35ns */ wt = max_t(int, wt, DIV_ROUND_UP(35, cycle)); /* actual wait-cycle is max(wt & ~1, 1) */ if (wt > 2 && (wt & 1)) wt++; wt &= ~1; /* Address-valid to DIOR/DIOW setup */ shwt = DIV_ROUND_UP(t->setup, cycle); /* -DIOx recovery time (SHWT * 4) and cycle time requirement */ while ((shwt * 4 + wt + (wt ? 2 : 3)) * cycle < t->cycle) shwt++; if (shwt > 7) { pr_warning("tx4938ide: SHWT violation (%d)\n", shwt); shwt = 7; } pr_debug("tx4938ide: ebus %d, bus cycle %dns, WT %d, SHWT %d\n", ebus_ch, cycle, wt, shwt); __raw_writeq((cr & ~0x3f007ull) | (wt << 12) | shwt, &tx4938_ebuscptr->cr[ebus_ch]); } static void tx4938ide_set_pio_mode(ide_hwif_t *hwif, ide_drive_t *drive) { struct tx4938ide_platform_info *pdata = hwif->dev->platform_data; u8 safe = drive->pio_mode - XFER_PIO_0; ide_drive_t *pair; pair = ide_get_pair_dev(drive); if (pair) safe = min_t(u8, safe, pair->pio_mode - XFER_PIO_0); tx4938ide_tune_ebusc(pdata->ebus_ch, pdata->gbus_clock, safe); } #ifdef __BIG_ENDIAN /* custom iops (independent from SWAP_IO_SPACE) */ static void tx4938ide_input_data_swap(ide_drive_t *drive, struct ide_cmd *cmd, void *buf, unsigned int len) { unsigned long port = drive->hwif->io_ports.data_addr; unsigned short *ptr = buf; unsigned int count = (len + 1) / 2; while (count--) *ptr++ = cpu_to_le16(__raw_readw((void __iomem *)port)); __ide_flush_dcache_range((unsigned long)buf, roundup(len, 2)); } static void tx4938ide_output_data_swap(ide_drive_t *drive, struct ide_cmd *cmd, void *buf, unsigned int len) { unsigned long port = drive->hwif->io_ports.data_addr; unsigned short *ptr = buf; unsigned int count = (len + 1) / 2; while (count--) { __raw_writew(le16_to_cpu(*ptr), (void __iomem *)port); ptr++; } __ide_flush_dcache_range((unsigned long)buf, roundup(len, 2)); } static const struct ide_tp_ops tx4938ide_tp_ops = { .exec_command = ide_exec_command, .read_status = ide_read_status, .read_altstatus = ide_read_altstatus, .write_devctl = ide_write_devctl, .dev_select = ide_dev_select, .tf_load = ide_tf_load, .tf_read = ide_tf_read, .input_data = tx4938ide_input_data_swap, .output_data = tx4938ide_output_data_swap, }; #endif /* __BIG_ENDIAN */ static const struct ide_port_ops tx4938ide_port_ops = { .set_pio_mode = tx4938ide_set_pio_mode, }; static const struct ide_port_info tx4938ide_port_info __initdata = { .port_ops = &tx4938ide_port_ops, #ifdef __BIG_ENDIAN .tp_ops = &tx4938ide_tp_ops, #endif .host_flags = IDE_HFLAG_MMIO | IDE_HFLAG_NO_DMA, .pio_mask = ATA_PIO5, .chipset = ide_generic, }; static int __init tx4938ide_probe(struct platform_device *pdev) { struct ide_hw hw, *hws[] = { &hw }; struct ide_host *host; struct resource *res; struct tx4938ide_platform_info *pdata = pdev->dev.platform_data; int irq, ret, i; unsigned long mapbase, mapctl; struct ide_port_info d = tx4938ide_port_info; irq = platform_get_irq(pdev, 0); if (irq < 0) return -ENODEV; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) return -ENODEV; if (!devm_request_mem_region(&pdev->dev, res->start, resource_size(res), "tx4938ide")) return -EBUSY; mapbase = (unsigned long)devm_ioremap(&pdev->dev, res->start, 8 << pdata->ioport_shift); mapctl = (unsigned long)devm_ioremap(&pdev->dev, res->start + 0x10000 + (6 << pdata->ioport_shift), 1 << pdata->ioport_shift); if (!mapbase || !mapctl) return -EBUSY; memset(&hw, 0, sizeof(hw)); if (pdata->ioport_shift) { unsigned long port = mapbase; unsigned long ctl = mapctl; hw.io_ports_array[0] = port; #ifdef __BIG_ENDIAN port++; ctl++; #endif for (i = 1; i <= 7; i++) hw.io_ports_array[i] = port + (i << pdata->ioport_shift); hw.io_ports.ctl_addr = ctl; } else ide_std_init_ports(&hw, mapbase, mapctl); hw.irq = irq; hw.dev = &pdev->dev; pr_info("TX4938 IDE interface (base %#lx, ctl %#lx, irq %d)\n", mapbase, mapctl, hw.irq); if (pdata->gbus_clock) tx4938ide_tune_ebusc(pdata->ebus_ch, pdata->gbus_clock, 0); else d.port_ops = NULL; ret = ide_host_add(&d, hws, 1, &host); if (!ret) platform_set_drvdata(pdev, host); return ret; } static int __exit tx4938ide_remove(struct platform_device *pdev) { struct ide_host *host = platform_get_drvdata(pdev); ide_host_remove(host); return 0; } static struct platform_driver tx4938ide_driver = { .driver = { .name = "tx4938ide", .owner = THIS_MODULE, }, .remove = __exit_p(tx4938ide_remove), }; static int __init tx4938ide_init(void) { return platform_driver_probe(&tx4938ide_driver, tx4938ide_probe); } static void __exit tx4938ide_exit(void) { platform_driver_unregister(&tx4938ide_driver); } module_init(tx4938ide_init); module_exit(tx4938ide_exit); MODULE_DESCRIPTION("TX4938 internal IDE driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:tx4938ide");
gpl-2.0
haoyangw/android_kernel_xiaomi_dior
fs/afs/flock.c
8410
16151
/* AFS file locking support * * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include "internal.h" #define AFS_LOCK_GRANTED 0 #define AFS_LOCK_PENDING 1 static void afs_fl_copy_lock(struct file_lock *new, struct file_lock *fl); static void afs_fl_release_private(struct file_lock *fl); static struct workqueue_struct *afs_lock_manager; static DEFINE_MUTEX(afs_lock_manager_mutex); static const struct file_lock_operations afs_lock_ops = { .fl_copy_lock = afs_fl_copy_lock, .fl_release_private = afs_fl_release_private, }; /* * initialise the lock manager thread if it isn't already running */ static int afs_init_lock_manager(void) { int ret; ret = 0; if (!afs_lock_manager) { mutex_lock(&afs_lock_manager_mutex); if (!afs_lock_manager) { afs_lock_manager = create_singlethread_workqueue("kafs_lockd"); if (!afs_lock_manager) ret = -ENOMEM; } mutex_unlock(&afs_lock_manager_mutex); } return ret; } /* * destroy the lock manager thread if it's running */ void __exit afs_kill_lock_manager(void) { if (afs_lock_manager) destroy_workqueue(afs_lock_manager); } /* * if the callback is broken on this vnode, then the lock may now be available */ void afs_lock_may_be_available(struct afs_vnode *vnode) { _enter("{%x:%u}", vnode->fid.vid, vnode->fid.vnode); queue_delayed_work(afs_lock_manager, &vnode->lock_work, 0); } /* * the lock will time out in 5 minutes unless we extend it, so schedule * extension in a bit less than that time */ static void afs_schedule_lock_extension(struct afs_vnode *vnode) { queue_delayed_work(afs_lock_manager, &vnode->lock_work, AFS_LOCKWAIT * HZ / 2); } /* * grant one or more locks (readlocks are allowed to jump the queue if the * first lock in the queue is itself a readlock) * - the caller must hold the vnode lock */ static void afs_grant_locks(struct afs_vnode *vnode, struct file_lock *fl) { struct file_lock *p, *_p; list_move_tail(&fl->fl_u.afs.link, &vnode->granted_locks); if (fl->fl_type == F_RDLCK) { list_for_each_entry_safe(p, _p, &vnode->pending_locks, fl_u.afs.link) { if (p->fl_type == F_RDLCK) { p->fl_u.afs.state = AFS_LOCK_GRANTED; list_move_tail(&p->fl_u.afs.link, &vnode->granted_locks); wake_up(&p->fl_wait); } } } } /* * do work for a lock, including: * - probing for a lock we're waiting on but didn't get immediately * - extending a lock that's close to timing out */ void afs_lock_work(struct work_struct *work) { struct afs_vnode *vnode = container_of(work, struct afs_vnode, lock_work.work); struct file_lock *fl; afs_lock_type_t type; struct key *key; int ret; _enter("{%x:%u}", vnode->fid.vid, vnode->fid.vnode); spin_lock(&vnode->lock); if (test_bit(AFS_VNODE_UNLOCKING, &vnode->flags)) { _debug("unlock"); spin_unlock(&vnode->lock); /* attempt to release the server lock; if it fails, we just * wait 5 minutes and it'll time out anyway */ ret = afs_vnode_release_lock(vnode, vnode->unlock_key); if (ret < 0) printk(KERN_WARNING "AFS:" " Failed to release lock on {%x:%x} error %d\n", vnode->fid.vid, vnode->fid.vnode, ret); spin_lock(&vnode->lock); key_put(vnode->unlock_key); vnode->unlock_key = NULL; clear_bit(AFS_VNODE_UNLOCKING, &vnode->flags); } /* if we've got a lock, then it must be time to extend that lock as AFS * locks time out after 5 minutes */ if (!list_empty(&vnode->granted_locks)) { _debug("extend"); if (test_and_set_bit(AFS_VNODE_LOCKING, &vnode->flags)) BUG(); fl = list_entry(vnode->granted_locks.next, struct file_lock, fl_u.afs.link); key = key_get(fl->fl_file->private_data); spin_unlock(&vnode->lock); ret = afs_vnode_extend_lock(vnode, key); clear_bit(AFS_VNODE_LOCKING, &vnode->flags); key_put(key); switch (ret) { case 0: afs_schedule_lock_extension(vnode); break; default: /* ummm... we failed to extend the lock - retry * extension shortly */ printk(KERN_WARNING "AFS:" " Failed to extend lock on {%x:%x} error %d\n", vnode->fid.vid, vnode->fid.vnode, ret); queue_delayed_work(afs_lock_manager, &vnode->lock_work, HZ * 10); break; } _leave(" [extend]"); return; } /* if we don't have a granted lock, then we must've been called back by * the server, and so if might be possible to get a lock we're * currently waiting for */ if (!list_empty(&vnode->pending_locks)) { _debug("get"); if (test_and_set_bit(AFS_VNODE_LOCKING, &vnode->flags)) BUG(); fl = list_entry(vnode->pending_locks.next, struct file_lock, fl_u.afs.link); key = key_get(fl->fl_file->private_data); type = (fl->fl_type == F_RDLCK) ? AFS_LOCK_READ : AFS_LOCK_WRITE; spin_unlock(&vnode->lock); ret = afs_vnode_set_lock(vnode, key, type); clear_bit(AFS_VNODE_LOCKING, &vnode->flags); switch (ret) { case -EWOULDBLOCK: _debug("blocked"); break; case 0: _debug("acquired"); if (type == AFS_LOCK_READ) set_bit(AFS_VNODE_READLOCKED, &vnode->flags); else set_bit(AFS_VNODE_WRITELOCKED, &vnode->flags); ret = AFS_LOCK_GRANTED; default: spin_lock(&vnode->lock); /* the pending lock may have been withdrawn due to a * signal */ if (list_entry(vnode->pending_locks.next, struct file_lock, fl_u.afs.link) == fl) { fl->fl_u.afs.state = ret; if (ret == AFS_LOCK_GRANTED) afs_grant_locks(vnode, fl); else list_del_init(&fl->fl_u.afs.link); wake_up(&fl->fl_wait); spin_unlock(&vnode->lock); } else { _debug("withdrawn"); clear_bit(AFS_VNODE_READLOCKED, &vnode->flags); clear_bit(AFS_VNODE_WRITELOCKED, &vnode->flags); spin_unlock(&vnode->lock); afs_vnode_release_lock(vnode, key); if (!list_empty(&vnode->pending_locks)) afs_lock_may_be_available(vnode); } break; } key_put(key); _leave(" [pend]"); return; } /* looks like the lock request was withdrawn on a signal */ spin_unlock(&vnode->lock); _leave(" [no locks]"); } /* * pass responsibility for the unlocking of a vnode on the server to the * manager thread, lest a pending signal in the calling thread interrupt * AF_RXRPC * - the caller must hold the vnode lock */ static void afs_defer_unlock(struct afs_vnode *vnode, struct key *key) { cancel_delayed_work(&vnode->lock_work); if (!test_and_clear_bit(AFS_VNODE_READLOCKED, &vnode->flags) && !test_and_clear_bit(AFS_VNODE_WRITELOCKED, &vnode->flags)) BUG(); if (test_and_set_bit(AFS_VNODE_UNLOCKING, &vnode->flags)) BUG(); vnode->unlock_key = key_get(key); afs_lock_may_be_available(vnode); } /* * request a lock on a file on the server */ static int afs_do_setlk(struct file *file, struct file_lock *fl) { struct afs_vnode *vnode = AFS_FS_I(file->f_mapping->host); afs_lock_type_t type; struct key *key = file->private_data; int ret; _enter("{%x:%u},%u", vnode->fid.vid, vnode->fid.vnode, fl->fl_type); /* only whole-file locks are supported */ if (fl->fl_start != 0 || fl->fl_end != OFFSET_MAX) return -EINVAL; ret = afs_init_lock_manager(); if (ret < 0) return ret; fl->fl_ops = &afs_lock_ops; INIT_LIST_HEAD(&fl->fl_u.afs.link); fl->fl_u.afs.state = AFS_LOCK_PENDING; type = (fl->fl_type == F_RDLCK) ? AFS_LOCK_READ : AFS_LOCK_WRITE; lock_flocks(); /* make sure we've got a callback on this file and that our view of the * data version is up to date */ ret = afs_vnode_fetch_status(vnode, NULL, key); if (ret < 0) goto error; if (vnode->status.lock_count != 0 && !(fl->fl_flags & FL_SLEEP)) { ret = -EAGAIN; goto error; } spin_lock(&vnode->lock); /* if we've already got a readlock on the server then we can instantly * grant another readlock, irrespective of whether there are any * pending writelocks */ if (type == AFS_LOCK_READ && vnode->flags & (1 << AFS_VNODE_READLOCKED)) { _debug("instant readlock"); ASSERTCMP(vnode->flags & ((1 << AFS_VNODE_LOCKING) | (1 << AFS_VNODE_WRITELOCKED)), ==, 0); ASSERT(!list_empty(&vnode->granted_locks)); goto sharing_existing_lock; } /* if there's no-one else with a lock on this vnode, then we need to * ask the server for a lock */ if (list_empty(&vnode->pending_locks) && list_empty(&vnode->granted_locks)) { _debug("not locked"); ASSERTCMP(vnode->flags & ((1 << AFS_VNODE_LOCKING) | (1 << AFS_VNODE_READLOCKED) | (1 << AFS_VNODE_WRITELOCKED)), ==, 0); list_add_tail(&fl->fl_u.afs.link, &vnode->pending_locks); set_bit(AFS_VNODE_LOCKING, &vnode->flags); spin_unlock(&vnode->lock); ret = afs_vnode_set_lock(vnode, key, type); clear_bit(AFS_VNODE_LOCKING, &vnode->flags); switch (ret) { case 0: _debug("acquired"); goto acquired_server_lock; case -EWOULDBLOCK: _debug("would block"); spin_lock(&vnode->lock); ASSERT(list_empty(&vnode->granted_locks)); ASSERTCMP(vnode->pending_locks.next, ==, &fl->fl_u.afs.link); goto wait; default: spin_lock(&vnode->lock); list_del_init(&fl->fl_u.afs.link); spin_unlock(&vnode->lock); goto error; } } /* otherwise, we need to wait for a local lock to become available */ _debug("wait local"); list_add_tail(&fl->fl_u.afs.link, &vnode->pending_locks); wait: if (!(fl->fl_flags & FL_SLEEP)) { _debug("noblock"); ret = -EAGAIN; goto abort_attempt; } spin_unlock(&vnode->lock); /* now we need to sleep and wait for the lock manager thread to get the * lock from the server */ _debug("sleep"); ret = wait_event_interruptible(fl->fl_wait, fl->fl_u.afs.state <= AFS_LOCK_GRANTED); if (fl->fl_u.afs.state <= AFS_LOCK_GRANTED) { ret = fl->fl_u.afs.state; if (ret < 0) goto error; spin_lock(&vnode->lock); goto given_lock; } /* we were interrupted, but someone may still be in the throes of * giving us the lock */ _debug("intr"); ASSERTCMP(ret, ==, -ERESTARTSYS); spin_lock(&vnode->lock); if (fl->fl_u.afs.state <= AFS_LOCK_GRANTED) { ret = fl->fl_u.afs.state; if (ret < 0) { spin_unlock(&vnode->lock); goto error; } goto given_lock; } abort_attempt: /* we aren't going to get the lock, either because we're unwilling to * wait, or because some signal happened */ _debug("abort"); if (list_empty(&vnode->granted_locks) && vnode->pending_locks.next == &fl->fl_u.afs.link) { if (vnode->pending_locks.prev != &fl->fl_u.afs.link) { /* kick the next pending lock into having a go */ list_del_init(&fl->fl_u.afs.link); afs_lock_may_be_available(vnode); } } else { list_del_init(&fl->fl_u.afs.link); } spin_unlock(&vnode->lock); goto error; acquired_server_lock: /* we've acquired a server lock, but it needs to be renewed after 5 * mins */ spin_lock(&vnode->lock); afs_schedule_lock_extension(vnode); if (type == AFS_LOCK_READ) set_bit(AFS_VNODE_READLOCKED, &vnode->flags); else set_bit(AFS_VNODE_WRITELOCKED, &vnode->flags); sharing_existing_lock: /* the lock has been granted as far as we're concerned... */ fl->fl_u.afs.state = AFS_LOCK_GRANTED; list_move_tail(&fl->fl_u.afs.link, &vnode->granted_locks); given_lock: /* ... but we do still need to get the VFS's blessing */ ASSERT(!(vnode->flags & (1 << AFS_VNODE_LOCKING))); ASSERT((vnode->flags & ((1 << AFS_VNODE_READLOCKED) | (1 << AFS_VNODE_WRITELOCKED))) != 0); ret = posix_lock_file(file, fl, NULL); if (ret < 0) goto vfs_rejected_lock; spin_unlock(&vnode->lock); /* again, make sure we've got a callback on this file and, again, make * sure that our view of the data version is up to date (we ignore * errors incurred here and deal with the consequences elsewhere) */ afs_vnode_fetch_status(vnode, NULL, key); error: unlock_flocks(); _leave(" = %d", ret); return ret; vfs_rejected_lock: /* the VFS rejected the lock we just obtained, so we have to discard * what we just got */ _debug("vfs refused %d", ret); list_del_init(&fl->fl_u.afs.link); if (list_empty(&vnode->granted_locks)) afs_defer_unlock(vnode, key); goto abort_attempt; } /* * unlock on a file on the server */ static int afs_do_unlk(struct file *file, struct file_lock *fl) { struct afs_vnode *vnode = AFS_FS_I(file->f_mapping->host); struct key *key = file->private_data; int ret; _enter("{%x:%u},%u", vnode->fid.vid, vnode->fid.vnode, fl->fl_type); /* only whole-file unlocks are supported */ if (fl->fl_start != 0 || fl->fl_end != OFFSET_MAX) return -EINVAL; fl->fl_ops = &afs_lock_ops; INIT_LIST_HEAD(&fl->fl_u.afs.link); fl->fl_u.afs.state = AFS_LOCK_PENDING; spin_lock(&vnode->lock); ret = posix_lock_file(file, fl, NULL); if (ret < 0) { spin_unlock(&vnode->lock); _leave(" = %d [vfs]", ret); return ret; } /* discard the server lock only if all granted locks are gone */ if (list_empty(&vnode->granted_locks)) afs_defer_unlock(vnode, key); spin_unlock(&vnode->lock); _leave(" = 0"); return 0; } /* * return information about a lock we currently hold, if indeed we hold one */ static int afs_do_getlk(struct file *file, struct file_lock *fl) { struct afs_vnode *vnode = AFS_FS_I(file->f_mapping->host); struct key *key = file->private_data; int ret, lock_count; _enter(""); fl->fl_type = F_UNLCK; mutex_lock(&vnode->vfs_inode.i_mutex); /* check local lock records first */ ret = 0; posix_test_lock(file, fl); if (fl->fl_type == F_UNLCK) { /* no local locks; consult the server */ ret = afs_vnode_fetch_status(vnode, NULL, key); if (ret < 0) goto error; lock_count = vnode->status.lock_count; if (lock_count) { if (lock_count > 0) fl->fl_type = F_RDLCK; else fl->fl_type = F_WRLCK; fl->fl_start = 0; fl->fl_end = OFFSET_MAX; } } error: mutex_unlock(&vnode->vfs_inode.i_mutex); _leave(" = %d [%hd]", ret, fl->fl_type); return ret; } /* * manage POSIX locks on a file */ int afs_lock(struct file *file, int cmd, struct file_lock *fl) { struct afs_vnode *vnode = AFS_FS_I(file->f_dentry->d_inode); _enter("{%x:%u},%d,{t=%x,fl=%x,r=%Ld:%Ld}", vnode->fid.vid, vnode->fid.vnode, cmd, fl->fl_type, fl->fl_flags, (long long) fl->fl_start, (long long) fl->fl_end); /* AFS doesn't support mandatory locks */ if (__mandatory_lock(&vnode->vfs_inode) && fl->fl_type != F_UNLCK) return -ENOLCK; if (IS_GETLK(cmd)) return afs_do_getlk(file, fl); if (fl->fl_type == F_UNLCK) return afs_do_unlk(file, fl); return afs_do_setlk(file, fl); } /* * manage FLOCK locks on a file */ int afs_flock(struct file *file, int cmd, struct file_lock *fl) { struct afs_vnode *vnode = AFS_FS_I(file->f_dentry->d_inode); _enter("{%x:%u},%d,{t=%x,fl=%x}", vnode->fid.vid, vnode->fid.vnode, cmd, fl->fl_type, fl->fl_flags); /* * No BSD flocks over NFS allowed. * Note: we could try to fake a POSIX lock request here by * using ((u32) filp | 0x80000000) or some such as the pid. * Not sure whether that would be unique, though, or whether * that would break in other places. */ if (!(fl->fl_flags & FL_FLOCK)) return -ENOLCK; /* we're simulating flock() locks using posix locks on the server */ fl->fl_owner = (fl_owner_t) file; fl->fl_start = 0; fl->fl_end = OFFSET_MAX; if (fl->fl_type == F_UNLCK) return afs_do_unlk(file, fl); return afs_do_setlk(file, fl); } /* * the POSIX lock management core VFS code copies the lock record and adds the * copy into its own list, so we need to add that copy to the vnode's lock * queue in the same place as the original (which will be deleted shortly * after) */ static void afs_fl_copy_lock(struct file_lock *new, struct file_lock *fl) { _enter(""); list_add(&new->fl_u.afs.link, &fl->fl_u.afs.link); } /* * need to remove this lock from the vnode queue when it's removed from the * VFS's list */ static void afs_fl_release_private(struct file_lock *fl) { _enter(""); list_del_init(&fl->fl_u.afs.link); }
gpl-2.0
aksalj/kernel_rpi
arch/powerpc/mm/icswx_pid.c
9178
1844
/* * ICSWX and ACOP/PID Management * * Copyright (C) 2011 Anton Blanchard, IBM Corp. <anton@samba.org> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * */ #include <linux/sched.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/mm.h> #include <linux/spinlock.h> #include <linux/idr.h> #include <linux/module.h> #include "icswx.h" #define COP_PID_MIN (COP_PID_NONE + 1) #define COP_PID_MAX (0xFFFF) static DEFINE_SPINLOCK(mmu_context_acop_lock); static DEFINE_IDA(cop_ida); static int new_cop_pid(struct ida *ida, int min_id, int max_id, spinlock_t *lock) { int index; int err; again: if (!ida_pre_get(ida, GFP_KERNEL)) return -ENOMEM; spin_lock(lock); err = ida_get_new_above(ida, min_id, &index); spin_unlock(lock); if (err == -EAGAIN) goto again; else if (err) return err; if (index > max_id) { spin_lock(lock); ida_remove(ida, index); spin_unlock(lock); return -ENOMEM; } return index; } int get_cop_pid(struct mm_struct *mm) { int pid; if (mm->context.cop_pid == COP_PID_NONE) { pid = new_cop_pid(&cop_ida, COP_PID_MIN, COP_PID_MAX, &mmu_context_acop_lock); if (pid >= 0) mm->context.cop_pid = pid; } return mm->context.cop_pid; } int disable_cop_pid(struct mm_struct *mm) { int free_pid = COP_PID_NONE; if ((!mm->context.acop) && (mm->context.cop_pid != COP_PID_NONE)) { free_pid = mm->context.cop_pid; mm->context.cop_pid = COP_PID_NONE; } return free_pid; } void free_cop_pid(int free_pid) { spin_lock(&mmu_context_acop_lock); ida_remove(&cop_ida, free_pid); spin_unlock(&mmu_context_acop_lock); }
gpl-2.0
wingrime/android_kernel_swift
net/core/filter.c
219
14910
/* * Linux Socket Filter - Kernel level socket filtering * * Author: * Jay Schulist <jschlst@samba.org> * * Based on the design of: * - The Berkeley Packet Filter * * 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. * * Andi Kleen - Fix a few bad bugs and races. * Kris Katterjohn - Added many additional checks in sk_chk_filter() */ #include <linux/module.h> #include <linux/types.h> #include <linux/mm.h> #include <linux/fcntl.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/if_packet.h> #include <linux/gfp.h> #include <net/ip.h> #include <net/protocol.h> #include <net/netlink.h> #include <linux/skbuff.h> #include <net/sock.h> #include <linux/errno.h> #include <linux/timer.h> #include <asm/system.h> #include <asm/uaccess.h> #include <asm/unaligned.h> #include <linux/filter.h> /* No hurry in this branch */ static void *__load_pointer(struct sk_buff *skb, int k) { u8 *ptr = NULL; if (k >= SKF_NET_OFF) ptr = skb_network_header(skb) + k - SKF_NET_OFF; else if (k >= SKF_LL_OFF) ptr = skb_mac_header(skb) + k - SKF_LL_OFF; if (ptr >= skb->head && ptr < skb_tail_pointer(skb)) return ptr; return NULL; } static inline void *load_pointer(struct sk_buff *skb, int k, unsigned int size, void *buffer) { if (k >= 0) return skb_header_pointer(skb, k, size, buffer); else { if (k >= SKF_AD_OFF) return NULL; return __load_pointer(skb, k); } } /** * sk_filter - run a packet through a socket filter * @sk: sock associated with &sk_buff * @skb: buffer to filter * * Run the filter code and then cut skb->data to correct size returned by * sk_run_filter. If pkt_len is 0 we toss packet. If skb->len is smaller * than pkt_len we keep whole skb->data. This is the socket level * wrapper to sk_run_filter. It returns 0 if the packet should * be accepted or -EPERM if the packet should be tossed. * */ int sk_filter(struct sock *sk, struct sk_buff *skb) { int err; struct sk_filter *filter; err = security_sock_rcv_skb(sk, skb); if (err) return err; rcu_read_lock_bh(); filter = rcu_dereference_bh(sk->sk_filter); if (filter) { unsigned int pkt_len = sk_run_filter(skb, filter->insns, filter->len); err = pkt_len ? pskb_trim(skb, pkt_len) : -EPERM; } rcu_read_unlock_bh(); return err; } EXPORT_SYMBOL(sk_filter); /** * sk_run_filter - run a filter on a socket * @skb: buffer to run the filter on * @filter: filter to apply * @flen: length of filter * * Decode and apply filter instructions to the skb->data. * Return length to keep, 0 for none. skb is the data we are * filtering, filter is the array of filter instructions, and * len is the number of filter blocks in the array. */ unsigned int sk_run_filter(struct sk_buff *skb, struct sock_filter *filter, int flen) { void *ptr; u32 A = 0; /* Accumulator */ u32 X = 0; /* Index Register */ u32 mem[BPF_MEMWORDS]; /* Scratch Memory Store */ unsigned long memvalid = 0; u32 tmp; int k; int pc; BUILD_BUG_ON(BPF_MEMWORDS > BITS_PER_LONG); /* * Process array of filter instructions. */ for (pc = 0; pc < flen; pc++) { const struct sock_filter *fentry = &filter[pc]; u32 f_k = fentry->k; switch (fentry->code) { case BPF_S_ALU_ADD_X: A += X; continue; case BPF_S_ALU_ADD_K: A += f_k; continue; case BPF_S_ALU_SUB_X: A -= X; continue; case BPF_S_ALU_SUB_K: A -= f_k; continue; case BPF_S_ALU_MUL_X: A *= X; continue; case BPF_S_ALU_MUL_K: A *= f_k; continue; case BPF_S_ALU_DIV_X: if (X == 0) return 0; A /= X; continue; case BPF_S_ALU_DIV_K: A /= f_k; continue; case BPF_S_ALU_AND_X: A &= X; continue; case BPF_S_ALU_AND_K: A &= f_k; continue; case BPF_S_ALU_OR_X: A |= X; continue; case BPF_S_ALU_OR_K: A |= f_k; continue; case BPF_S_ALU_LSH_X: A <<= X; continue; case BPF_S_ALU_LSH_K: A <<= f_k; continue; case BPF_S_ALU_RSH_X: A >>= X; continue; case BPF_S_ALU_RSH_K: A >>= f_k; continue; case BPF_S_ALU_NEG: A = -A; continue; case BPF_S_JMP_JA: pc += f_k; continue; case BPF_S_JMP_JGT_K: pc += (A > f_k) ? fentry->jt : fentry->jf; continue; case BPF_S_JMP_JGE_K: pc += (A >= f_k) ? fentry->jt : fentry->jf; continue; case BPF_S_JMP_JEQ_K: pc += (A == f_k) ? fentry->jt : fentry->jf; continue; case BPF_S_JMP_JSET_K: pc += (A & f_k) ? fentry->jt : fentry->jf; continue; case BPF_S_JMP_JGT_X: pc += (A > X) ? fentry->jt : fentry->jf; continue; case BPF_S_JMP_JGE_X: pc += (A >= X) ? fentry->jt : fentry->jf; continue; case BPF_S_JMP_JEQ_X: pc += (A == X) ? fentry->jt : fentry->jf; continue; case BPF_S_JMP_JSET_X: pc += (A & X) ? fentry->jt : fentry->jf; continue; case BPF_S_LD_W_ABS: k = f_k; load_w: ptr = load_pointer(skb, k, 4, &tmp); if (ptr != NULL) { A = get_unaligned_be32(ptr); continue; } break; case BPF_S_LD_H_ABS: k = f_k; load_h: ptr = load_pointer(skb, k, 2, &tmp); if (ptr != NULL) { A = get_unaligned_be16(ptr); continue; } break; case BPF_S_LD_B_ABS: k = f_k; load_b: ptr = load_pointer(skb, k, 1, &tmp); if (ptr != NULL) { A = *(u8 *)ptr; continue; } break; case BPF_S_LD_W_LEN: A = skb->len; continue; case BPF_S_LDX_W_LEN: X = skb->len; continue; case BPF_S_LD_W_IND: k = X + f_k; goto load_w; case BPF_S_LD_H_IND: k = X + f_k; goto load_h; case BPF_S_LD_B_IND: k = X + f_k; goto load_b; case BPF_S_LDX_B_MSH: ptr = load_pointer(skb, f_k, 1, &tmp); if (ptr != NULL) { X = (*(u8 *)ptr & 0xf) << 2; continue; } return 0; case BPF_S_LD_IMM: A = f_k; continue; case BPF_S_LDX_IMM: X = f_k; continue; case BPF_S_LD_MEM: A = (memvalid & (1UL << f_k)) ? mem[f_k] : 0; continue; case BPF_S_LDX_MEM: X = (memvalid & (1UL << f_k)) ? mem[f_k] : 0; continue; case BPF_S_MISC_TAX: X = A; continue; case BPF_S_MISC_TXA: A = X; continue; case BPF_S_RET_K: return f_k; case BPF_S_RET_A: return A; case BPF_S_ST: memvalid |= 1UL << f_k; mem[f_k] = A; continue; case BPF_S_STX: memvalid |= 1UL << f_k; mem[f_k] = X; continue; default: WARN_ON(1); return 0; } /* * Handle ancillary data, which are impossible * (or very difficult) to get parsing packet contents. */ switch (k-SKF_AD_OFF) { case SKF_AD_PROTOCOL: A = ntohs(skb->protocol); continue; case SKF_AD_PKTTYPE: A = skb->pkt_type; continue; case SKF_AD_IFINDEX: if (!skb->dev) return 0; A = skb->dev->ifindex; continue; case SKF_AD_MARK: A = skb->mark; continue; case SKF_AD_QUEUE: A = skb->queue_mapping; continue; case SKF_AD_HATYPE: if (!skb->dev) return 0; A = skb->dev->type; continue; case SKF_AD_NLATTR: { struct nlattr *nla; if (skb_is_nonlinear(skb)) return 0; if (A > skb->len - sizeof(struct nlattr)) return 0; nla = nla_find((struct nlattr *)&skb->data[A], skb->len - A, X); if (nla) A = (void *)nla - (void *)skb->data; else A = 0; continue; } case SKF_AD_NLATTR_NEST: { struct nlattr *nla; if (skb_is_nonlinear(skb)) return 0; if (A > skb->len - sizeof(struct nlattr)) return 0; nla = (struct nlattr *)&skb->data[A]; if (nla->nla_len > A - skb->len) return 0; nla = nla_find_nested(nla, X); if (nla) A = (void *)nla - (void *)skb->data; else A = 0; continue; } default: return 0; } } return 0; } EXPORT_SYMBOL(sk_run_filter); /** * sk_chk_filter - verify socket filter code * @filter: filter to verify * @flen: length of filter * * Check the user's filter code. If we let some ugly * filter code slip through kaboom! The filter must contain * no references or jumps that are out of range, no illegal * instructions, and must end with a RET instruction. * * All jumps are forward as they are not signed. * * Returns 0 if the rule set is legal or -EINVAL if not. */ int sk_chk_filter(struct sock_filter *filter, int flen) { struct sock_filter *ftest; int pc; if (flen == 0 || flen > BPF_MAXINSNS) return -EINVAL; /* check the filter code now */ for (pc = 0; pc < flen; pc++) { ftest = &filter[pc]; /* Only allow valid instructions */ switch (ftest->code) { case BPF_ALU|BPF_ADD|BPF_K: ftest->code = BPF_S_ALU_ADD_K; break; case BPF_ALU|BPF_ADD|BPF_X: ftest->code = BPF_S_ALU_ADD_X; break; case BPF_ALU|BPF_SUB|BPF_K: ftest->code = BPF_S_ALU_SUB_K; break; case BPF_ALU|BPF_SUB|BPF_X: ftest->code = BPF_S_ALU_SUB_X; break; case BPF_ALU|BPF_MUL|BPF_K: ftest->code = BPF_S_ALU_MUL_K; break; case BPF_ALU|BPF_MUL|BPF_X: ftest->code = BPF_S_ALU_MUL_X; break; case BPF_ALU|BPF_DIV|BPF_X: ftest->code = BPF_S_ALU_DIV_X; break; case BPF_ALU|BPF_AND|BPF_K: ftest->code = BPF_S_ALU_AND_K; break; case BPF_ALU|BPF_AND|BPF_X: ftest->code = BPF_S_ALU_AND_X; break; case BPF_ALU|BPF_OR|BPF_K: ftest->code = BPF_S_ALU_OR_K; break; case BPF_ALU|BPF_OR|BPF_X: ftest->code = BPF_S_ALU_OR_X; break; case BPF_ALU|BPF_LSH|BPF_K: ftest->code = BPF_S_ALU_LSH_K; break; case BPF_ALU|BPF_LSH|BPF_X: ftest->code = BPF_S_ALU_LSH_X; break; case BPF_ALU|BPF_RSH|BPF_K: ftest->code = BPF_S_ALU_RSH_K; break; case BPF_ALU|BPF_RSH|BPF_X: ftest->code = BPF_S_ALU_RSH_X; break; case BPF_ALU|BPF_NEG: ftest->code = BPF_S_ALU_NEG; break; case BPF_LD|BPF_W|BPF_ABS: ftest->code = BPF_S_LD_W_ABS; break; case BPF_LD|BPF_H|BPF_ABS: ftest->code = BPF_S_LD_H_ABS; break; case BPF_LD|BPF_B|BPF_ABS: ftest->code = BPF_S_LD_B_ABS; break; case BPF_LD|BPF_W|BPF_LEN: ftest->code = BPF_S_LD_W_LEN; break; case BPF_LD|BPF_W|BPF_IND: ftest->code = BPF_S_LD_W_IND; break; case BPF_LD|BPF_H|BPF_IND: ftest->code = BPF_S_LD_H_IND; break; case BPF_LD|BPF_B|BPF_IND: ftest->code = BPF_S_LD_B_IND; break; case BPF_LD|BPF_IMM: ftest->code = BPF_S_LD_IMM; break; case BPF_LDX|BPF_W|BPF_LEN: ftest->code = BPF_S_LDX_W_LEN; break; case BPF_LDX|BPF_B|BPF_MSH: ftest->code = BPF_S_LDX_B_MSH; break; case BPF_LDX|BPF_IMM: ftest->code = BPF_S_LDX_IMM; break; case BPF_MISC|BPF_TAX: ftest->code = BPF_S_MISC_TAX; break; case BPF_MISC|BPF_TXA: ftest->code = BPF_S_MISC_TXA; break; case BPF_RET|BPF_K: ftest->code = BPF_S_RET_K; break; case BPF_RET|BPF_A: ftest->code = BPF_S_RET_A; break; /* Some instructions need special checks */ /* check for division by zero */ case BPF_ALU|BPF_DIV|BPF_K: if (ftest->k == 0) return -EINVAL; ftest->code = BPF_S_ALU_DIV_K; break; /* check for invalid memory addresses */ case BPF_LD|BPF_MEM: if (ftest->k >= BPF_MEMWORDS) return -EINVAL; ftest->code = BPF_S_LD_MEM; break; case BPF_LDX|BPF_MEM: if (ftest->k >= BPF_MEMWORDS) return -EINVAL; ftest->code = BPF_S_LDX_MEM; break; case BPF_ST: if (ftest->k >= BPF_MEMWORDS) return -EINVAL; ftest->code = BPF_S_ST; break; case BPF_STX: if (ftest->k >= BPF_MEMWORDS) return -EINVAL; ftest->code = BPF_S_STX; break; case BPF_JMP|BPF_JA: /* * Note, the large ftest->k might cause loops. * Compare this with conditional jumps below, * where offsets are limited. --ANK (981016) */ if (ftest->k >= (unsigned)(flen-pc-1)) return -EINVAL; ftest->code = BPF_S_JMP_JA; break; case BPF_JMP|BPF_JEQ|BPF_K: ftest->code = BPF_S_JMP_JEQ_K; break; case BPF_JMP|BPF_JEQ|BPF_X: ftest->code = BPF_S_JMP_JEQ_X; break; case BPF_JMP|BPF_JGE|BPF_K: ftest->code = BPF_S_JMP_JGE_K; break; case BPF_JMP|BPF_JGE|BPF_X: ftest->code = BPF_S_JMP_JGE_X; break; case BPF_JMP|BPF_JGT|BPF_K: ftest->code = BPF_S_JMP_JGT_K; break; case BPF_JMP|BPF_JGT|BPF_X: ftest->code = BPF_S_JMP_JGT_X; break; case BPF_JMP|BPF_JSET|BPF_K: ftest->code = BPF_S_JMP_JSET_K; break; case BPF_JMP|BPF_JSET|BPF_X: ftest->code = BPF_S_JMP_JSET_X; break; default: return -EINVAL; } /* for conditionals both must be safe */ switch (ftest->code) { case BPF_S_JMP_JEQ_K: case BPF_S_JMP_JEQ_X: case BPF_S_JMP_JGE_K: case BPF_S_JMP_JGE_X: case BPF_S_JMP_JGT_K: case BPF_S_JMP_JGT_X: case BPF_S_JMP_JSET_X: case BPF_S_JMP_JSET_K: if (pc + ftest->jt + 1 >= flen || pc + ftest->jf + 1 >= flen) return -EINVAL; } } /* last instruction must be a RET code */ switch (filter[flen - 1].code) { case BPF_S_RET_K: case BPF_S_RET_A: return 0; break; default: return -EINVAL; } } EXPORT_SYMBOL(sk_chk_filter); /** * sk_filter_release_rcu - Release a socket filter by rcu_head * @rcu: rcu_head that contains the sk_filter to free */ void sk_filter_release_rcu(struct rcu_head *rcu) { struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu); kfree(fp); } EXPORT_SYMBOL(sk_filter_release_rcu); /** * sk_attach_filter - attach a socket filter * @fprog: the filter program * @sk: the socket to use * * Attach the user's filter code. We first run some sanity checks on * it to make sure it does not explode on us later. If an error * occurs or there is insufficient memory for the filter a negative * errno code is returned. On success the return is zero. */ int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk) { struct sk_filter *fp, *old_fp; unsigned int fsize = sizeof(struct sock_filter) * fprog->len; int err; /* Make sure new filter is there and in the right amounts. */ if (fprog->filter == NULL) return -EINVAL; fp = sock_kmalloc(sk, fsize+sizeof(*fp), GFP_KERNEL); if (!fp) return -ENOMEM; if (copy_from_user(fp->insns, fprog->filter, fsize)) { sock_kfree_s(sk, fp, fsize+sizeof(*fp)); return -EFAULT; } atomic_set(&fp->refcnt, 1); fp->len = fprog->len; err = sk_chk_filter(fp->insns, fp->len); if (err) { sk_filter_uncharge(sk, fp); return err; } rcu_read_lock_bh(); old_fp = rcu_dereference_bh(sk->sk_filter); rcu_assign_pointer(sk->sk_filter, fp); rcu_read_unlock_bh(); if (old_fp) sk_filter_uncharge(sk, old_fp); return 0; } EXPORT_SYMBOL_GPL(sk_attach_filter); int sk_detach_filter(struct sock *sk) { int ret = -ENOENT; struct sk_filter *filter; rcu_read_lock_bh(); filter = rcu_dereference_bh(sk->sk_filter); if (filter) { rcu_assign_pointer(sk->sk_filter, NULL); sk_filter_uncharge(sk, filter); ret = 0; } rcu_read_unlock_bh(); return ret; } EXPORT_SYMBOL_GPL(sk_detach_filter);
gpl-2.0
Channing-Y/kernel
fs/9p/vfs_addr.c
1499
3862
/* * linux/fs/9p/vfs_addr.c * * This file contians vfs address (mmap) ops for 9P2000. * * Copyright (C) 2005 by Eric Van Hensbergen <ericvh@gmail.com> * Copyright (C) 2002 by Ron Minnich <rminnich@lanl.gov> * * 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: * Free Software Foundation * 51 Franklin Street, Fifth Floor * Boston, MA 02111-1301 USA * */ #include <linux/module.h> #include <linux/errno.h> #include <linux/fs.h> #include <linux/file.h> #include <linux/stat.h> #include <linux/string.h> #include <linux/inet.h> #include <linux/pagemap.h> #include <linux/idr.h> #include <linux/sched.h> #include <net/9p/9p.h> #include <net/9p/client.h> #include "v9fs.h" #include "v9fs_vfs.h" #include "cache.h" /** * v9fs_vfs_readpage - read an entire page in from 9P * * @filp: file being read * @page: structure to page * */ static int v9fs_vfs_readpage(struct file *filp, struct page *page) { int retval; loff_t offset; char *buffer; struct inode *inode; inode = page->mapping->host; P9_DPRINTK(P9_DEBUG_VFS, "\n"); BUG_ON(!PageLocked(page)); retval = v9fs_readpage_from_fscache(inode, page); if (retval == 0) return retval; buffer = kmap(page); offset = page_offset(page); retval = v9fs_file_readn(filp, buffer, NULL, PAGE_CACHE_SIZE, offset); if (retval < 0) { v9fs_uncache_page(inode, page); goto done; } memset(buffer + retval, 0, PAGE_CACHE_SIZE - retval); flush_dcache_page(page); SetPageUptodate(page); v9fs_readpage_to_fscache(inode, page); retval = 0; done: kunmap(page); unlock_page(page); return retval; } /** * v9fs_vfs_readpages - read a set of pages from 9P * * @filp: file being read * @mapping: the address space * @pages: list of pages to read * @nr_pages: count of pages to read * */ static int v9fs_vfs_readpages(struct file *filp, struct address_space *mapping, struct list_head *pages, unsigned nr_pages) { int ret = 0; struct inode *inode; inode = mapping->host; P9_DPRINTK(P9_DEBUG_VFS, "inode: %p file: %p\n", inode, filp); ret = v9fs_readpages_from_fscache(inode, mapping, pages, &nr_pages); if (ret == 0) return ret; ret = read_cache_pages(mapping, pages, (void *)v9fs_vfs_readpage, filp); P9_DPRINTK(P9_DEBUG_VFS, " = %d\n", ret); return ret; } /** * v9fs_release_page - release the private state associated with a page * * Returns 1 if the page can be released, false otherwise. */ static int v9fs_release_page(struct page *page, gfp_t gfp) { if (PagePrivate(page)) return 0; return v9fs_fscache_release_page(page, gfp); } /** * v9fs_invalidate_page - Invalidate a page completely or partially * * @page: structure to page * @offset: offset in the page */ static void v9fs_invalidate_page(struct page *page, unsigned long offset) { if (offset == 0) v9fs_fscache_invalidate_page(page); } /** * v9fs_launder_page - Writeback a dirty page * Since the writes go directly to the server, we simply return a 0 * here to indicate success. * * Returns 0 on success. */ static int v9fs_launder_page(struct page *page) { return 0; } const struct address_space_operations v9fs_addr_operations = { .readpage = v9fs_vfs_readpage, .readpages = v9fs_vfs_readpages, .releasepage = v9fs_release_page, .invalidatepage = v9fs_invalidate_page, .launder_page = v9fs_launder_page, };
gpl-2.0
ptmr3/Fpg_Kernel
arch/arm/mach-omap2/vc3xxx_data.c
2523
1982
/* * OMAP3 Voltage Controller (VC) data * * Copyright (C) 2007, 2010 Texas Instruments, Inc. * Rajendra Nayak <rnayak@ti.com> * Lesly A M <x0080970@ti.com> * Thara Gopinath <thara@ti.com> * * Copyright (C) 2008, 2011 Nokia Corporation * Kalle Jokiniemi * Paul Walmsley * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/io.h> #include <linux/err.h> #include <linux/init.h> #include <plat/common.h> #include "prm-regbits-34xx.h" #include "voltage.h" #include "vc.h" /* * VC data common to 34xx/36xx chips * XXX This stuff presumably belongs in the vc3xxx.c or vc.c file. */ static struct omap_vc_common_data omap3_vc_common = { .smps_sa_reg = OMAP3_PRM_VC_SMPS_SA_OFFSET, .smps_volra_reg = OMAP3_PRM_VC_SMPS_VOL_RA_OFFSET, .bypass_val_reg = OMAP3_PRM_VC_BYPASS_VAL_OFFSET, .data_shift = OMAP3430_DATA_SHIFT, .slaveaddr_shift = OMAP3430_SLAVEADDR_SHIFT, .regaddr_shift = OMAP3430_REGADDR_SHIFT, .valid = OMAP3430_VALID_MASK, .cmd_on_shift = OMAP3430_VC_CMD_ON_SHIFT, .cmd_on_mask = OMAP3430_VC_CMD_ON_MASK, .cmd_onlp_shift = OMAP3430_VC_CMD_ONLP_SHIFT, .cmd_ret_shift = OMAP3430_VC_CMD_RET_SHIFT, .cmd_off_shift = OMAP3430_VC_CMD_OFF_SHIFT, }; struct omap_vc_instance_data omap3_vc1_data = { .vc_common = &omap3_vc_common, .cmdval_reg = OMAP3_PRM_VC_CMD_VAL_0_OFFSET, .smps_sa_shift = OMAP3430_PRM_VC_SMPS_SA_SA0_SHIFT, .smps_sa_mask = OMAP3430_PRM_VC_SMPS_SA_SA0_MASK, .smps_volra_shift = OMAP3430_VOLRA0_SHIFT, .smps_volra_mask = OMAP3430_VOLRA0_MASK, }; struct omap_vc_instance_data omap3_vc2_data = { .vc_common = &omap3_vc_common, .cmdval_reg = OMAP3_PRM_VC_CMD_VAL_1_OFFSET, .smps_sa_shift = OMAP3430_PRM_VC_SMPS_SA_SA1_SHIFT, .smps_sa_mask = OMAP3430_PRM_VC_SMPS_SA_SA1_MASK, .smps_volra_shift = OMAP3430_VOLRA1_SHIFT, .smps_volra_mask = OMAP3430_VOLRA1_MASK, };
gpl-2.0
high1/android_kernel_htc_pico
drivers/edac/cpc925_edac.c
2779
30542
/* * cpc925_edac.c, EDAC driver for IBM CPC925 Bridge and Memory Controller. * * Copyright (c) 2008 Wind River Systems, Inc. * * Authors: Cao Qingtao <qingtao.cao@windriver.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/module.h> #include <linux/init.h> #include <linux/io.h> #include <linux/edac.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/gfp.h> #include "edac_core.h" #include "edac_module.h" #define CPC925_EDAC_REVISION " Ver: 1.0.0" #define CPC925_EDAC_MOD_STR "cpc925_edac" #define cpc925_printk(level, fmt, arg...) \ edac_printk(level, "CPC925", fmt, ##arg) #define cpc925_mc_printk(mci, level, fmt, arg...) \ edac_mc_chipset_printk(mci, level, "CPC925", fmt, ##arg) /* * CPC925 registers are of 32 bits with bit0 defined at the * most significant bit and bit31 at that of least significant. */ #define CPC925_BITS_PER_REG 32 #define CPC925_BIT(nr) (1UL << (CPC925_BITS_PER_REG - 1 - nr)) /* * EDAC device names for the error detections of * CPU Interface and Hypertransport Link. */ #define CPC925_CPU_ERR_DEV "cpu" #define CPC925_HT_LINK_DEV "htlink" /* Suppose DDR Refresh cycle is 15.6 microsecond */ #define CPC925_REF_FREQ 0xFA69 #define CPC925_SCRUB_BLOCK_SIZE 64 /* bytes */ #define CPC925_NR_CSROWS 8 /* * All registers and bits definitions are taken from * "CPC925 Bridge and Memory Controller User Manual, SA14-2761-02". */ /* * CPU and Memory Controller Registers */ /************************************************************ * Processor Interface Exception Mask Register (APIMASK) ************************************************************/ #define REG_APIMASK_OFFSET 0x30070 enum apimask_bits { APIMASK_DART = CPC925_BIT(0), /* DART Exception */ APIMASK_ADI0 = CPC925_BIT(1), /* Handshake Error on PI0_ADI */ APIMASK_ADI1 = CPC925_BIT(2), /* Handshake Error on PI1_ADI */ APIMASK_STAT = CPC925_BIT(3), /* Status Exception */ APIMASK_DERR = CPC925_BIT(4), /* Data Error Exception */ APIMASK_ADRS0 = CPC925_BIT(5), /* Addressing Exception on PI0 */ APIMASK_ADRS1 = CPC925_BIT(6), /* Addressing Exception on PI1 */ /* BIT(7) Reserved */ APIMASK_ECC_UE_H = CPC925_BIT(8), /* UECC upper */ APIMASK_ECC_CE_H = CPC925_BIT(9), /* CECC upper */ APIMASK_ECC_UE_L = CPC925_BIT(10), /* UECC lower */ APIMASK_ECC_CE_L = CPC925_BIT(11), /* CECC lower */ CPU_MASK_ENABLE = (APIMASK_DART | APIMASK_ADI0 | APIMASK_ADI1 | APIMASK_STAT | APIMASK_DERR | APIMASK_ADRS0 | APIMASK_ADRS1), ECC_MASK_ENABLE = (APIMASK_ECC_UE_H | APIMASK_ECC_CE_H | APIMASK_ECC_UE_L | APIMASK_ECC_CE_L), }; /************************************************************ * Processor Interface Exception Register (APIEXCP) ************************************************************/ #define REG_APIEXCP_OFFSET 0x30060 enum apiexcp_bits { APIEXCP_DART = CPC925_BIT(0), /* DART Exception */ APIEXCP_ADI0 = CPC925_BIT(1), /* Handshake Error on PI0_ADI */ APIEXCP_ADI1 = CPC925_BIT(2), /* Handshake Error on PI1_ADI */ APIEXCP_STAT = CPC925_BIT(3), /* Status Exception */ APIEXCP_DERR = CPC925_BIT(4), /* Data Error Exception */ APIEXCP_ADRS0 = CPC925_BIT(5), /* Addressing Exception on PI0 */ APIEXCP_ADRS1 = CPC925_BIT(6), /* Addressing Exception on PI1 */ /* BIT(7) Reserved */ APIEXCP_ECC_UE_H = CPC925_BIT(8), /* UECC upper */ APIEXCP_ECC_CE_H = CPC925_BIT(9), /* CECC upper */ APIEXCP_ECC_UE_L = CPC925_BIT(10), /* UECC lower */ APIEXCP_ECC_CE_L = CPC925_BIT(11), /* CECC lower */ CPU_EXCP_DETECTED = (APIEXCP_DART | APIEXCP_ADI0 | APIEXCP_ADI1 | APIEXCP_STAT | APIEXCP_DERR | APIEXCP_ADRS0 | APIEXCP_ADRS1), UECC_EXCP_DETECTED = (APIEXCP_ECC_UE_H | APIEXCP_ECC_UE_L), CECC_EXCP_DETECTED = (APIEXCP_ECC_CE_H | APIEXCP_ECC_CE_L), ECC_EXCP_DETECTED = (UECC_EXCP_DETECTED | CECC_EXCP_DETECTED), }; /************************************************************ * Memory Bus Configuration Register (MBCR) ************************************************************/ #define REG_MBCR_OFFSET 0x2190 #define MBCR_64BITCFG_SHIFT 23 #define MBCR_64BITCFG_MASK (1UL << MBCR_64BITCFG_SHIFT) #define MBCR_64BITBUS_SHIFT 22 #define MBCR_64BITBUS_MASK (1UL << MBCR_64BITBUS_SHIFT) /************************************************************ * Memory Bank Mode Register (MBMR) ************************************************************/ #define REG_MBMR_OFFSET 0x21C0 #define MBMR_MODE_MAX_VALUE 0xF #define MBMR_MODE_SHIFT 25 #define MBMR_MODE_MASK (MBMR_MODE_MAX_VALUE << MBMR_MODE_SHIFT) #define MBMR_BBA_SHIFT 24 #define MBMR_BBA_MASK (1UL << MBMR_BBA_SHIFT) /************************************************************ * Memory Bank Boundary Address Register (MBBAR) ************************************************************/ #define REG_MBBAR_OFFSET 0x21D0 #define MBBAR_BBA_MAX_VALUE 0xFF #define MBBAR_BBA_SHIFT 24 #define MBBAR_BBA_MASK (MBBAR_BBA_MAX_VALUE << MBBAR_BBA_SHIFT) /************************************************************ * Memory Scrub Control Register (MSCR) ************************************************************/ #define REG_MSCR_OFFSET 0x2400 #define MSCR_SCRUB_MOD_MASK 0xC0000000 /* scrub_mod - bit0:1*/ #define MSCR_BACKGR_SCRUB 0x40000000 /* 01 */ #define MSCR_SI_SHIFT 16 /* si - bit8:15*/ #define MSCR_SI_MAX_VALUE 0xFF #define MSCR_SI_MASK (MSCR_SI_MAX_VALUE << MSCR_SI_SHIFT) /************************************************************ * Memory Scrub Range Start Register (MSRSR) ************************************************************/ #define REG_MSRSR_OFFSET 0x2410 /************************************************************ * Memory Scrub Range End Register (MSRER) ************************************************************/ #define REG_MSRER_OFFSET 0x2420 /************************************************************ * Memory Scrub Pattern Register (MSPR) ************************************************************/ #define REG_MSPR_OFFSET 0x2430 /************************************************************ * Memory Check Control Register (MCCR) ************************************************************/ #define REG_MCCR_OFFSET 0x2440 enum mccr_bits { MCCR_ECC_EN = CPC925_BIT(0), /* ECC high and low check */ }; /************************************************************ * Memory Check Range End Register (MCRER) ************************************************************/ #define REG_MCRER_OFFSET 0x2450 /************************************************************ * Memory Error Address Register (MEAR) ************************************************************/ #define REG_MEAR_OFFSET 0x2460 #define MEAR_BCNT_MAX_VALUE 0x3 #define MEAR_BCNT_SHIFT 30 #define MEAR_BCNT_MASK (MEAR_BCNT_MAX_VALUE << MEAR_BCNT_SHIFT) #define MEAR_RANK_MAX_VALUE 0x7 #define MEAR_RANK_SHIFT 27 #define MEAR_RANK_MASK (MEAR_RANK_MAX_VALUE << MEAR_RANK_SHIFT) #define MEAR_COL_MAX_VALUE 0x7FF #define MEAR_COL_SHIFT 16 #define MEAR_COL_MASK (MEAR_COL_MAX_VALUE << MEAR_COL_SHIFT) #define MEAR_BANK_MAX_VALUE 0x3 #define MEAR_BANK_SHIFT 14 #define MEAR_BANK_MASK (MEAR_BANK_MAX_VALUE << MEAR_BANK_SHIFT) #define MEAR_ROW_MASK 0x00003FFF /************************************************************ * Memory Error Syndrome Register (MESR) ************************************************************/ #define REG_MESR_OFFSET 0x2470 #define MESR_ECC_SYN_H_MASK 0xFF00 #define MESR_ECC_SYN_L_MASK 0x00FF /************************************************************ * Memory Mode Control Register (MMCR) ************************************************************/ #define REG_MMCR_OFFSET 0x2500 enum mmcr_bits { MMCR_REG_DIMM_MODE = CPC925_BIT(3), }; /* * HyperTransport Link Registers */ /************************************************************ * Error Handling/Enumeration Scratch Pad Register (ERRCTRL) ************************************************************/ #define REG_ERRCTRL_OFFSET 0x70140 enum errctrl_bits { /* nonfatal interrupts for */ ERRCTRL_SERR_NF = CPC925_BIT(0), /* system error */ ERRCTRL_CRC_NF = CPC925_BIT(1), /* CRC error */ ERRCTRL_RSP_NF = CPC925_BIT(2), /* Response error */ ERRCTRL_EOC_NF = CPC925_BIT(3), /* End-Of-Chain error */ ERRCTRL_OVF_NF = CPC925_BIT(4), /* Overflow error */ ERRCTRL_PROT_NF = CPC925_BIT(5), /* Protocol error */ ERRCTRL_RSP_ERR = CPC925_BIT(6), /* Response error received */ ERRCTRL_CHN_FAL = CPC925_BIT(7), /* Sync flooding detected */ HT_ERRCTRL_ENABLE = (ERRCTRL_SERR_NF | ERRCTRL_CRC_NF | ERRCTRL_RSP_NF | ERRCTRL_EOC_NF | ERRCTRL_OVF_NF | ERRCTRL_PROT_NF), HT_ERRCTRL_DETECTED = (ERRCTRL_RSP_ERR | ERRCTRL_CHN_FAL), }; /************************************************************ * Link Configuration and Link Control Register (LINKCTRL) ************************************************************/ #define REG_LINKCTRL_OFFSET 0x70110 enum linkctrl_bits { LINKCTRL_CRC_ERR = (CPC925_BIT(22) | CPC925_BIT(23)), LINKCTRL_LINK_FAIL = CPC925_BIT(27), HT_LINKCTRL_DETECTED = (LINKCTRL_CRC_ERR | LINKCTRL_LINK_FAIL), }; /************************************************************ * Link FreqCap/Error/Freq/Revision ID Register (LINKERR) ************************************************************/ #define REG_LINKERR_OFFSET 0x70120 enum linkerr_bits { LINKERR_EOC_ERR = CPC925_BIT(17), /* End-Of-Chain error */ LINKERR_OVF_ERR = CPC925_BIT(18), /* Receive Buffer Overflow */ LINKERR_PROT_ERR = CPC925_BIT(19), /* Protocol error */ HT_LINKERR_DETECTED = (LINKERR_EOC_ERR | LINKERR_OVF_ERR | LINKERR_PROT_ERR), }; /************************************************************ * Bridge Control Register (BRGCTRL) ************************************************************/ #define REG_BRGCTRL_OFFSET 0x70300 enum brgctrl_bits { BRGCTRL_DETSERR = CPC925_BIT(0), /* SERR on Secondary Bus */ BRGCTRL_SECBUSRESET = CPC925_BIT(9), /* Secondary Bus Reset */ }; /* Private structure for edac memory controller */ struct cpc925_mc_pdata { void __iomem *vbase; unsigned long total_mem; const char *name; int edac_idx; }; /* Private structure for common edac device */ struct cpc925_dev_info { void __iomem *vbase; struct platform_device *pdev; char *ctl_name; int edac_idx; struct edac_device_ctl_info *edac_dev; void (*init)(struct cpc925_dev_info *dev_info); void (*exit)(struct cpc925_dev_info *dev_info); void (*check)(struct edac_device_ctl_info *edac_dev); }; /* Get total memory size from Open Firmware DTB */ static void get_total_mem(struct cpc925_mc_pdata *pdata) { struct device_node *np = NULL; const unsigned int *reg, *reg_end; int len, sw, aw; unsigned long start, size; np = of_find_node_by_type(NULL, "memory"); if (!np) return; aw = of_n_addr_cells(np); sw = of_n_size_cells(np); reg = (const unsigned int *)of_get_property(np, "reg", &len); reg_end = reg + len/4; pdata->total_mem = 0; do { start = of_read_number(reg, aw); reg += aw; size = of_read_number(reg, sw); reg += sw; debugf1("%s: start 0x%lx, size 0x%lx\n", __func__, start, size); pdata->total_mem += size; } while (reg < reg_end); of_node_put(np); debugf0("%s: total_mem 0x%lx\n", __func__, pdata->total_mem); } static void cpc925_init_csrows(struct mem_ctl_info *mci) { struct cpc925_mc_pdata *pdata = mci->pvt_info; struct csrow_info *csrow; int index; u32 mbmr, mbbar, bba; unsigned long row_size, last_nr_pages = 0; get_total_mem(pdata); for (index = 0; index < mci->nr_csrows; index++) { mbmr = __raw_readl(pdata->vbase + REG_MBMR_OFFSET + 0x20 * index); mbbar = __raw_readl(pdata->vbase + REG_MBBAR_OFFSET + 0x20 + index); bba = (((mbmr & MBMR_BBA_MASK) >> MBMR_BBA_SHIFT) << 8) | ((mbbar & MBBAR_BBA_MASK) >> MBBAR_BBA_SHIFT); if (bba == 0) continue; /* not populated */ csrow = &mci->csrows[index]; row_size = bba * (1UL << 28); /* 256M */ csrow->first_page = last_nr_pages; csrow->nr_pages = row_size >> PAGE_SHIFT; csrow->last_page = csrow->first_page + csrow->nr_pages - 1; last_nr_pages = csrow->last_page + 1; csrow->mtype = MEM_RDDR; csrow->edac_mode = EDAC_SECDED; switch (csrow->nr_channels) { case 1: /* Single channel */ csrow->grain = 32; /* four-beat burst of 32 bytes */ break; case 2: /* Dual channel */ default: csrow->grain = 64; /* four-beat burst of 64 bytes */ break; } switch ((mbmr & MBMR_MODE_MASK) >> MBMR_MODE_SHIFT) { case 6: /* 0110, no way to differentiate X8 VS X16 */ case 5: /* 0101 */ case 8: /* 1000 */ csrow->dtype = DEV_X16; break; case 7: /* 0111 */ case 9: /* 1001 */ csrow->dtype = DEV_X8; break; default: csrow->dtype = DEV_UNKNOWN; break; } } } /* Enable memory controller ECC detection */ static void cpc925_mc_init(struct mem_ctl_info *mci) { struct cpc925_mc_pdata *pdata = mci->pvt_info; u32 apimask; u32 mccr; /* Enable various ECC error exceptions */ apimask = __raw_readl(pdata->vbase + REG_APIMASK_OFFSET); if ((apimask & ECC_MASK_ENABLE) == 0) { apimask |= ECC_MASK_ENABLE; __raw_writel(apimask, pdata->vbase + REG_APIMASK_OFFSET); } /* Enable ECC detection */ mccr = __raw_readl(pdata->vbase + REG_MCCR_OFFSET); if ((mccr & MCCR_ECC_EN) == 0) { mccr |= MCCR_ECC_EN; __raw_writel(mccr, pdata->vbase + REG_MCCR_OFFSET); } } /* Disable memory controller ECC detection */ static void cpc925_mc_exit(struct mem_ctl_info *mci) { /* * WARNING: * We are supposed to clear the ECC error detection bits, * and it will be no problem to do so. However, once they * are cleared here if we want to re-install CPC925 EDAC * module later, setting them up in cpc925_mc_init() will * trigger machine check exception. * Also, it's ok to leave ECC error detection bits enabled, * since they are reset to 1 by default or by boot loader. */ return; } /* * Revert DDR column/row/bank addresses into page frame number and * offset in page. * * Suppose memory mode is 0x0111(128-bit mode, identical DIMM pairs), * physical address(PA) bits to column address(CA) bits mappings are: * CA 0 1 2 3 4 5 6 7 8 9 10 * PA 59 58 57 56 55 54 53 52 51 50 49 * * physical address(PA) bits to bank address(BA) bits mappings are: * BA 0 1 * PA 43 44 * * physical address(PA) bits to row address(RA) bits mappings are: * RA 0 1 2 3 4 5 6 7 8 9 10 11 12 * PA 36 35 34 48 47 46 45 40 41 42 39 38 37 */ static void cpc925_mc_get_pfn(struct mem_ctl_info *mci, u32 mear, unsigned long *pfn, unsigned long *offset, int *csrow) { u32 bcnt, rank, col, bank, row; u32 c; unsigned long pa; int i; bcnt = (mear & MEAR_BCNT_MASK) >> MEAR_BCNT_SHIFT; rank = (mear & MEAR_RANK_MASK) >> MEAR_RANK_SHIFT; col = (mear & MEAR_COL_MASK) >> MEAR_COL_SHIFT; bank = (mear & MEAR_BANK_MASK) >> MEAR_BANK_SHIFT; row = mear & MEAR_ROW_MASK; *csrow = rank; #ifdef CONFIG_EDAC_DEBUG if (mci->csrows[rank].first_page == 0) { cpc925_mc_printk(mci, KERN_ERR, "ECC occurs in a " "non-populated csrow, broken hardware?\n"); return; } #endif /* Revert csrow number */ pa = mci->csrows[rank].first_page << PAGE_SHIFT; /* Revert column address */ col += bcnt; for (i = 0; i < 11; i++) { c = col & 0x1; col >>= 1; pa |= c << (14 - i); } /* Revert bank address */ pa |= bank << 19; /* Revert row address, in 4 steps */ for (i = 0; i < 3; i++) { c = row & 0x1; row >>= 1; pa |= c << (26 - i); } for (i = 0; i < 3; i++) { c = row & 0x1; row >>= 1; pa |= c << (21 + i); } for (i = 0; i < 4; i++) { c = row & 0x1; row >>= 1; pa |= c << (18 - i); } for (i = 0; i < 3; i++) { c = row & 0x1; row >>= 1; pa |= c << (29 - i); } *offset = pa & (PAGE_SIZE - 1); *pfn = pa >> PAGE_SHIFT; debugf0("%s: ECC physical address 0x%lx\n", __func__, pa); } static int cpc925_mc_find_channel(struct mem_ctl_info *mci, u16 syndrome) { if ((syndrome & MESR_ECC_SYN_H_MASK) == 0) return 0; if ((syndrome & MESR_ECC_SYN_L_MASK) == 0) return 1; cpc925_mc_printk(mci, KERN_INFO, "Unexpected syndrome value: 0x%x\n", syndrome); return 1; } /* Check memory controller registers for ECC errors */ static void cpc925_mc_check(struct mem_ctl_info *mci) { struct cpc925_mc_pdata *pdata = mci->pvt_info; u32 apiexcp; u32 mear; u32 mesr; u16 syndrome; unsigned long pfn = 0, offset = 0; int csrow = 0, channel = 0; /* APIEXCP is cleared when read */ apiexcp = __raw_readl(pdata->vbase + REG_APIEXCP_OFFSET); if ((apiexcp & ECC_EXCP_DETECTED) == 0) return; mesr = __raw_readl(pdata->vbase + REG_MESR_OFFSET); syndrome = mesr | (MESR_ECC_SYN_H_MASK | MESR_ECC_SYN_L_MASK); mear = __raw_readl(pdata->vbase + REG_MEAR_OFFSET); /* Revert column/row addresses into page frame number, etc */ cpc925_mc_get_pfn(mci, mear, &pfn, &offset, &csrow); if (apiexcp & CECC_EXCP_DETECTED) { cpc925_mc_printk(mci, KERN_INFO, "DRAM CECC Fault\n"); channel = cpc925_mc_find_channel(mci, syndrome); edac_mc_handle_ce(mci, pfn, offset, syndrome, csrow, channel, mci->ctl_name); } if (apiexcp & UECC_EXCP_DETECTED) { cpc925_mc_printk(mci, KERN_INFO, "DRAM UECC Fault\n"); edac_mc_handle_ue(mci, pfn, offset, csrow, mci->ctl_name); } cpc925_mc_printk(mci, KERN_INFO, "Dump registers:\n"); cpc925_mc_printk(mci, KERN_INFO, "APIMASK 0x%08x\n", __raw_readl(pdata->vbase + REG_APIMASK_OFFSET)); cpc925_mc_printk(mci, KERN_INFO, "APIEXCP 0x%08x\n", apiexcp); cpc925_mc_printk(mci, KERN_INFO, "Mem Scrub Ctrl 0x%08x\n", __raw_readl(pdata->vbase + REG_MSCR_OFFSET)); cpc925_mc_printk(mci, KERN_INFO, "Mem Scrub Rge Start 0x%08x\n", __raw_readl(pdata->vbase + REG_MSRSR_OFFSET)); cpc925_mc_printk(mci, KERN_INFO, "Mem Scrub Rge End 0x%08x\n", __raw_readl(pdata->vbase + REG_MSRER_OFFSET)); cpc925_mc_printk(mci, KERN_INFO, "Mem Scrub Pattern 0x%08x\n", __raw_readl(pdata->vbase + REG_MSPR_OFFSET)); cpc925_mc_printk(mci, KERN_INFO, "Mem Chk Ctrl 0x%08x\n", __raw_readl(pdata->vbase + REG_MCCR_OFFSET)); cpc925_mc_printk(mci, KERN_INFO, "Mem Chk Rge End 0x%08x\n", __raw_readl(pdata->vbase + REG_MCRER_OFFSET)); cpc925_mc_printk(mci, KERN_INFO, "Mem Err Address 0x%08x\n", mesr); cpc925_mc_printk(mci, KERN_INFO, "Mem Err Syndrome 0x%08x\n", syndrome); } /******************** CPU err device********************************/ /* Enable CPU Errors detection */ static void cpc925_cpu_init(struct cpc925_dev_info *dev_info) { u32 apimask; apimask = __raw_readl(dev_info->vbase + REG_APIMASK_OFFSET); if ((apimask & CPU_MASK_ENABLE) == 0) { apimask |= CPU_MASK_ENABLE; __raw_writel(apimask, dev_info->vbase + REG_APIMASK_OFFSET); } } /* Disable CPU Errors detection */ static void cpc925_cpu_exit(struct cpc925_dev_info *dev_info) { /* * WARNING: * We are supposed to clear the CPU error detection bits, * and it will be no problem to do so. However, once they * are cleared here if we want to re-install CPC925 EDAC * module later, setting them up in cpc925_cpu_init() will * trigger machine check exception. * Also, it's ok to leave CPU error detection bits enabled, * since they are reset to 1 by default. */ return; } /* Check for CPU Errors */ static void cpc925_cpu_check(struct edac_device_ctl_info *edac_dev) { struct cpc925_dev_info *dev_info = edac_dev->pvt_info; u32 apiexcp; u32 apimask; /* APIEXCP is cleared when read */ apiexcp = __raw_readl(dev_info->vbase + REG_APIEXCP_OFFSET); if ((apiexcp & CPU_EXCP_DETECTED) == 0) return; apimask = __raw_readl(dev_info->vbase + REG_APIMASK_OFFSET); cpc925_printk(KERN_INFO, "Processor Interface Fault\n" "Processor Interface register dump:\n"); cpc925_printk(KERN_INFO, "APIMASK 0x%08x\n", apimask); cpc925_printk(KERN_INFO, "APIEXCP 0x%08x\n", apiexcp); edac_device_handle_ue(edac_dev, 0, 0, edac_dev->ctl_name); } /******************** HT Link err device****************************/ /* Enable HyperTransport Link Error detection */ static void cpc925_htlink_init(struct cpc925_dev_info *dev_info) { u32 ht_errctrl; ht_errctrl = __raw_readl(dev_info->vbase + REG_ERRCTRL_OFFSET); if ((ht_errctrl & HT_ERRCTRL_ENABLE) == 0) { ht_errctrl |= HT_ERRCTRL_ENABLE; __raw_writel(ht_errctrl, dev_info->vbase + REG_ERRCTRL_OFFSET); } } /* Disable HyperTransport Link Error detection */ static void cpc925_htlink_exit(struct cpc925_dev_info *dev_info) { u32 ht_errctrl; ht_errctrl = __raw_readl(dev_info->vbase + REG_ERRCTRL_OFFSET); ht_errctrl &= ~HT_ERRCTRL_ENABLE; __raw_writel(ht_errctrl, dev_info->vbase + REG_ERRCTRL_OFFSET); } /* Check for HyperTransport Link errors */ static void cpc925_htlink_check(struct edac_device_ctl_info *edac_dev) { struct cpc925_dev_info *dev_info = edac_dev->pvt_info; u32 brgctrl = __raw_readl(dev_info->vbase + REG_BRGCTRL_OFFSET); u32 linkctrl = __raw_readl(dev_info->vbase + REG_LINKCTRL_OFFSET); u32 errctrl = __raw_readl(dev_info->vbase + REG_ERRCTRL_OFFSET); u32 linkerr = __raw_readl(dev_info->vbase + REG_LINKERR_OFFSET); if (!((brgctrl & BRGCTRL_DETSERR) || (linkctrl & HT_LINKCTRL_DETECTED) || (errctrl & HT_ERRCTRL_DETECTED) || (linkerr & HT_LINKERR_DETECTED))) return; cpc925_printk(KERN_INFO, "HT Link Fault\n" "HT register dump:\n"); cpc925_printk(KERN_INFO, "Bridge Ctrl 0x%08x\n", brgctrl); cpc925_printk(KERN_INFO, "Link Config Ctrl 0x%08x\n", linkctrl); cpc925_printk(KERN_INFO, "Error Enum and Ctrl 0x%08x\n", errctrl); cpc925_printk(KERN_INFO, "Link Error 0x%08x\n", linkerr); /* Clear by write 1 */ if (brgctrl & BRGCTRL_DETSERR) __raw_writel(BRGCTRL_DETSERR, dev_info->vbase + REG_BRGCTRL_OFFSET); if (linkctrl & HT_LINKCTRL_DETECTED) __raw_writel(HT_LINKCTRL_DETECTED, dev_info->vbase + REG_LINKCTRL_OFFSET); /* Initiate Secondary Bus Reset to clear the chain failure */ if (errctrl & ERRCTRL_CHN_FAL) __raw_writel(BRGCTRL_SECBUSRESET, dev_info->vbase + REG_BRGCTRL_OFFSET); if (errctrl & ERRCTRL_RSP_ERR) __raw_writel(ERRCTRL_RSP_ERR, dev_info->vbase + REG_ERRCTRL_OFFSET); if (linkerr & HT_LINKERR_DETECTED) __raw_writel(HT_LINKERR_DETECTED, dev_info->vbase + REG_LINKERR_OFFSET); edac_device_handle_ce(edac_dev, 0, 0, edac_dev->ctl_name); } static struct cpc925_dev_info cpc925_devs[] = { { .ctl_name = CPC925_CPU_ERR_DEV, .init = cpc925_cpu_init, .exit = cpc925_cpu_exit, .check = cpc925_cpu_check, }, { .ctl_name = CPC925_HT_LINK_DEV, .init = cpc925_htlink_init, .exit = cpc925_htlink_exit, .check = cpc925_htlink_check, }, {0}, /* Terminated by NULL */ }; /* * Add CPU Err detection and HyperTransport Link Err detection * as common "edac_device", they have no corresponding device * nodes in the Open Firmware DTB and we have to add platform * devices for them. Also, they will share the MMIO with that * of memory controller. */ static void cpc925_add_edac_devices(void __iomem *vbase) { struct cpc925_dev_info *dev_info; if (!vbase) { cpc925_printk(KERN_ERR, "MMIO not established yet\n"); return; } for (dev_info = &cpc925_devs[0]; dev_info->init; dev_info++) { dev_info->vbase = vbase; dev_info->pdev = platform_device_register_simple( dev_info->ctl_name, 0, NULL, 0); if (IS_ERR(dev_info->pdev)) { cpc925_printk(KERN_ERR, "Can't register platform device for %s\n", dev_info->ctl_name); continue; } /* * Don't have to allocate private structure but * make use of cpc925_devs[] instead. */ dev_info->edac_idx = edac_device_alloc_index(); dev_info->edac_dev = edac_device_alloc_ctl_info(0, dev_info->ctl_name, 1, NULL, 0, 0, NULL, 0, dev_info->edac_idx); if (!dev_info->edac_dev) { cpc925_printk(KERN_ERR, "No memory for edac device\n"); goto err1; } dev_info->edac_dev->pvt_info = dev_info; dev_info->edac_dev->dev = &dev_info->pdev->dev; dev_info->edac_dev->ctl_name = dev_info->ctl_name; dev_info->edac_dev->mod_name = CPC925_EDAC_MOD_STR; dev_info->edac_dev->dev_name = dev_name(&dev_info->pdev->dev); if (edac_op_state == EDAC_OPSTATE_POLL) dev_info->edac_dev->edac_check = dev_info->check; if (dev_info->init) dev_info->init(dev_info); if (edac_device_add_device(dev_info->edac_dev) > 0) { cpc925_printk(KERN_ERR, "Unable to add edac device for %s\n", dev_info->ctl_name); goto err2; } debugf0("%s: Successfully added edac device for %s\n", __func__, dev_info->ctl_name); continue; err2: if (dev_info->exit) dev_info->exit(dev_info); edac_device_free_ctl_info(dev_info->edac_dev); err1: platform_device_unregister(dev_info->pdev); } } /* * Delete the common "edac_device" for CPU Err Detection * and HyperTransport Link Err Detection */ static void cpc925_del_edac_devices(void) { struct cpc925_dev_info *dev_info; for (dev_info = &cpc925_devs[0]; dev_info->init; dev_info++) { if (dev_info->edac_dev) { edac_device_del_device(dev_info->edac_dev->dev); edac_device_free_ctl_info(dev_info->edac_dev); platform_device_unregister(dev_info->pdev); } if (dev_info->exit) dev_info->exit(dev_info); debugf0("%s: Successfully deleted edac device for %s\n", __func__, dev_info->ctl_name); } } /* Convert current back-ground scrub rate into byte/sec bandwidth */ static int cpc925_get_sdram_scrub_rate(struct mem_ctl_info *mci) { struct cpc925_mc_pdata *pdata = mci->pvt_info; int bw; u32 mscr; u8 si; mscr = __raw_readl(pdata->vbase + REG_MSCR_OFFSET); si = (mscr & MSCR_SI_MASK) >> MSCR_SI_SHIFT; debugf0("%s, Mem Scrub Ctrl Register 0x%x\n", __func__, mscr); if (((mscr & MSCR_SCRUB_MOD_MASK) != MSCR_BACKGR_SCRUB) || (si == 0)) { cpc925_mc_printk(mci, KERN_INFO, "Scrub mode not enabled\n"); bw = 0; } else bw = CPC925_SCRUB_BLOCK_SIZE * 0xFA67 / si; return bw; } /* Return 0 for single channel; 1 for dual channel */ static int cpc925_mc_get_channels(void __iomem *vbase) { int dual = 0; u32 mbcr; mbcr = __raw_readl(vbase + REG_MBCR_OFFSET); /* * Dual channel only when 128-bit wide physical bus * and 128-bit configuration. */ if (((mbcr & MBCR_64BITCFG_MASK) == 0) && ((mbcr & MBCR_64BITBUS_MASK) == 0)) dual = 1; debugf0("%s: %s channel\n", __func__, (dual > 0) ? "Dual" : "Single"); return dual; } static int __devinit cpc925_probe(struct platform_device *pdev) { static int edac_mc_idx; struct mem_ctl_info *mci; void __iomem *vbase; struct cpc925_mc_pdata *pdata; struct resource *r; int res = 0, nr_channels; debugf0("%s: %s platform device found!\n", __func__, pdev->name); if (!devres_open_group(&pdev->dev, cpc925_probe, GFP_KERNEL)) { res = -ENOMEM; goto out; } r = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!r) { cpc925_printk(KERN_ERR, "Unable to get resource\n"); res = -ENOENT; goto err1; } if (!devm_request_mem_region(&pdev->dev, r->start, resource_size(r), pdev->name)) { cpc925_printk(KERN_ERR, "Unable to request mem region\n"); res = -EBUSY; goto err1; } vbase = devm_ioremap(&pdev->dev, r->start, resource_size(r)); if (!vbase) { cpc925_printk(KERN_ERR, "Unable to ioremap device\n"); res = -ENOMEM; goto err2; } nr_channels = cpc925_mc_get_channels(vbase); mci = edac_mc_alloc(sizeof(struct cpc925_mc_pdata), CPC925_NR_CSROWS, nr_channels + 1, edac_mc_idx); if (!mci) { cpc925_printk(KERN_ERR, "No memory for mem_ctl_info\n"); res = -ENOMEM; goto err2; } pdata = mci->pvt_info; pdata->vbase = vbase; pdata->edac_idx = edac_mc_idx++; pdata->name = pdev->name; mci->dev = &pdev->dev; platform_set_drvdata(pdev, mci); mci->dev_name = dev_name(&pdev->dev); mci->mtype_cap = MEM_FLAG_RDDR | MEM_FLAG_DDR; mci->edac_ctl_cap = EDAC_FLAG_NONE | EDAC_FLAG_SECDED; mci->edac_cap = EDAC_FLAG_SECDED; mci->mod_name = CPC925_EDAC_MOD_STR; mci->mod_ver = CPC925_EDAC_REVISION; mci->ctl_name = pdev->name; if (edac_op_state == EDAC_OPSTATE_POLL) mci->edac_check = cpc925_mc_check; mci->ctl_page_to_phys = NULL; mci->scrub_mode = SCRUB_SW_SRC; mci->set_sdram_scrub_rate = NULL; mci->get_sdram_scrub_rate = cpc925_get_sdram_scrub_rate; cpc925_init_csrows(mci); /* Setup memory controller registers */ cpc925_mc_init(mci); if (edac_mc_add_mc(mci) > 0) { cpc925_mc_printk(mci, KERN_ERR, "Failed edac_mc_add_mc()\n"); goto err3; } cpc925_add_edac_devices(vbase); /* get this far and it's successful */ debugf0("%s: success\n", __func__); res = 0; goto out; err3: cpc925_mc_exit(mci); edac_mc_free(mci); err2: devm_release_mem_region(&pdev->dev, r->start, resource_size(r)); err1: devres_release_group(&pdev->dev, cpc925_probe); out: return res; } static int cpc925_remove(struct platform_device *pdev) { struct mem_ctl_info *mci = platform_get_drvdata(pdev); /* * Delete common edac devices before edac mc, because * the former share the MMIO of the latter. */ cpc925_del_edac_devices(); cpc925_mc_exit(mci); edac_mc_del_mc(&pdev->dev); edac_mc_free(mci); return 0; } static struct platform_driver cpc925_edac_driver = { .probe = cpc925_probe, .remove = cpc925_remove, .driver = { .name = "cpc925_edac", } }; static int __init cpc925_edac_init(void) { int ret = 0; printk(KERN_INFO "IBM CPC925 EDAC driver " CPC925_EDAC_REVISION "\n"); printk(KERN_INFO "\t(c) 2008 Wind River Systems, Inc\n"); /* Only support POLL mode so far */ edac_op_state = EDAC_OPSTATE_POLL; ret = platform_driver_register(&cpc925_edac_driver); if (ret) { printk(KERN_WARNING "Failed to register %s\n", CPC925_EDAC_MOD_STR); } return ret; } static void __exit cpc925_edac_exit(void) { platform_driver_unregister(&cpc925_edac_driver); } module_init(cpc925_edac_init); module_exit(cpc925_edac_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Cao Qingtao <qingtao.cao@windriver.com>"); MODULE_DESCRIPTION("IBM CPC925 Bridge and MC EDAC kernel module");
gpl-2.0
sgs3/SPH-L710_Kernel
drivers/net/wireless/rt2x00/rt2x00link.c
3035
13790
/* Copyright (C) 2004 - 2009 Ivo van Doorn <IvDoorn@gmail.com> <http://rt2x00.serialmonkey.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. */ /* Module: rt2x00lib Abstract: rt2x00 generic link tuning routines. */ #include <linux/kernel.h> #include <linux/module.h> #include "rt2x00.h" #include "rt2x00lib.h" /* * When we lack RSSI information return something less then -80 to * tell the driver to tune the device to maximum sensitivity. */ #define DEFAULT_RSSI -128 /* * Helper struct and macro to work with moving/walking averages. * When adding a value to the average value the following calculation * is needed: * * avg_rssi = ((avg_rssi * 7) + rssi) / 8; * * The advantage of this approach is that we only need 1 variable * to store the average in (No need for a count and a total). * But more importantly, normal average values will over time * move less and less towards newly added values this results * that with link tuning, the device can have a very good RSSI * for a few minutes but when the device is moved away from the AP * the average will not decrease fast enough to compensate. * The walking average compensates this and will move towards * the new values correctly allowing a effective link tuning, * the speed of the average moving towards other values depends * on the value for the number of samples. The higher the number * of samples, the slower the average will move. * We use two variables to keep track of the average value to * compensate for the rounding errors. This can be a significant * error (>5dBm) if the factor is too low. */ #define AVG_SAMPLES 8 #define AVG_FACTOR 1000 #define MOVING_AVERAGE(__avg, __val) \ ({ \ struct avg_val __new; \ __new.avg_weight = \ (__avg).avg_weight ? \ ((((__avg).avg_weight * ((AVG_SAMPLES) - 1)) + \ ((__val) * (AVG_FACTOR))) / \ (AVG_SAMPLES)) : \ ((__val) * (AVG_FACTOR)); \ __new.avg = __new.avg_weight / (AVG_FACTOR); \ __new; \ }) static int rt2x00link_antenna_get_link_rssi(struct rt2x00_dev *rt2x00dev) { struct link_ant *ant = &rt2x00dev->link.ant; if (ant->rssi_ant.avg && rt2x00dev->link.qual.rx_success) return ant->rssi_ant.avg; return DEFAULT_RSSI; } static int rt2x00link_antenna_get_rssi_history(struct rt2x00_dev *rt2x00dev) { struct link_ant *ant = &rt2x00dev->link.ant; if (ant->rssi_history) return ant->rssi_history; return DEFAULT_RSSI; } static void rt2x00link_antenna_update_rssi_history(struct rt2x00_dev *rt2x00dev, int rssi) { struct link_ant *ant = &rt2x00dev->link.ant; ant->rssi_history = rssi; } static void rt2x00link_antenna_reset(struct rt2x00_dev *rt2x00dev) { rt2x00dev->link.ant.rssi_ant.avg = 0; rt2x00dev->link.ant.rssi_ant.avg_weight = 0; } static void rt2x00lib_antenna_diversity_sample(struct rt2x00_dev *rt2x00dev) { struct link_ant *ant = &rt2x00dev->link.ant; struct antenna_setup new_ant; int other_antenna; int sample_current = rt2x00link_antenna_get_link_rssi(rt2x00dev); int sample_other = rt2x00link_antenna_get_rssi_history(rt2x00dev); memcpy(&new_ant, &ant->active, sizeof(new_ant)); /* * We are done sampling. Now we should evaluate the results. */ ant->flags &= ~ANTENNA_MODE_SAMPLE; /* * During the last period we have sampled the RSSI * from both antennas. It now is time to determine * which antenna demonstrated the best performance. * When we are already on the antenna with the best * performance, just create a good starting point * for the history and we are done. */ if (sample_current >= sample_other) { rt2x00link_antenna_update_rssi_history(rt2x00dev, sample_current); return; } other_antenna = (ant->active.rx == ANTENNA_A) ? ANTENNA_B : ANTENNA_A; if (ant->flags & ANTENNA_RX_DIVERSITY) new_ant.rx = other_antenna; if (ant->flags & ANTENNA_TX_DIVERSITY) new_ant.tx = other_antenna; rt2x00lib_config_antenna(rt2x00dev, new_ant); } static void rt2x00lib_antenna_diversity_eval(struct rt2x00_dev *rt2x00dev) { struct link_ant *ant = &rt2x00dev->link.ant; struct antenna_setup new_ant; int rssi_curr; int rssi_old; memcpy(&new_ant, &ant->active, sizeof(new_ant)); /* * Get current RSSI value along with the historical value, * after that update the history with the current value. */ rssi_curr = rt2x00link_antenna_get_link_rssi(rt2x00dev); rssi_old = rt2x00link_antenna_get_rssi_history(rt2x00dev); rt2x00link_antenna_update_rssi_history(rt2x00dev, rssi_curr); /* * Legacy driver indicates that we should swap antenna's * when the difference in RSSI is greater that 5. This * also should be done when the RSSI was actually better * then the previous sample. * When the difference exceeds the threshold we should * sample the rssi from the other antenna to make a valid * comparison between the 2 antennas. */ if (abs(rssi_curr - rssi_old) < 5) return; ant->flags |= ANTENNA_MODE_SAMPLE; if (ant->flags & ANTENNA_RX_DIVERSITY) new_ant.rx = (new_ant.rx == ANTENNA_A) ? ANTENNA_B : ANTENNA_A; if (ant->flags & ANTENNA_TX_DIVERSITY) new_ant.tx = (new_ant.tx == ANTENNA_A) ? ANTENNA_B : ANTENNA_A; rt2x00lib_config_antenna(rt2x00dev, new_ant); } static bool rt2x00lib_antenna_diversity(struct rt2x00_dev *rt2x00dev) { struct link_ant *ant = &rt2x00dev->link.ant; /* * Determine if software diversity is enabled for * either the TX or RX antenna (or both). */ if (!(ant->flags & ANTENNA_RX_DIVERSITY) && !(ant->flags & ANTENNA_TX_DIVERSITY)) { ant->flags = 0; return true; } /* * If we have only sampled the data over the last period * we should now harvest the data. Otherwise just evaluate * the data. The latter should only be performed once * every 2 seconds. */ if (ant->flags & ANTENNA_MODE_SAMPLE) { rt2x00lib_antenna_diversity_sample(rt2x00dev); return true; } else if (rt2x00dev->link.count & 1) { rt2x00lib_antenna_diversity_eval(rt2x00dev); return true; } return false; } void rt2x00link_update_stats(struct rt2x00_dev *rt2x00dev, struct sk_buff *skb, struct rxdone_entry_desc *rxdesc) { struct link *link = &rt2x00dev->link; struct link_qual *qual = &rt2x00dev->link.qual; struct link_ant *ant = &rt2x00dev->link.ant; struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data; /* * No need to update the stats for !=STA interfaces */ if (!rt2x00dev->intf_sta_count) return; /* * Frame was received successfully since non-succesfull * frames would have been dropped by the hardware. */ qual->rx_success++; /* * We are only interested in quality statistics from * beacons which came from the BSS which we are * associated with. */ if (!ieee80211_is_beacon(hdr->frame_control) || !(rxdesc->dev_flags & RXDONE_MY_BSS)) return; /* * Update global RSSI */ link->avg_rssi = MOVING_AVERAGE(link->avg_rssi, rxdesc->rssi); /* * Update antenna RSSI */ ant->rssi_ant = MOVING_AVERAGE(ant->rssi_ant, rxdesc->rssi); } void rt2x00link_start_tuner(struct rt2x00_dev *rt2x00dev) { struct link *link = &rt2x00dev->link; /* * Link tuning should only be performed when * an active sta interface exists. AP interfaces * don't need link tuning and monitor mode interfaces * should never have to work with link tuners. */ if (!rt2x00dev->intf_sta_count) return; /** * While scanning, link tuning is disabled. By default * the most sensitive settings will be used to make sure * that all beacons and probe responses will be received * during the scan. */ if (test_bit(DEVICE_STATE_SCANNING, &rt2x00dev->flags)) return; rt2x00link_reset_tuner(rt2x00dev, false); if (test_bit(DEVICE_STATE_PRESENT, &rt2x00dev->flags)) ieee80211_queue_delayed_work(rt2x00dev->hw, &link->work, LINK_TUNE_INTERVAL); } void rt2x00link_stop_tuner(struct rt2x00_dev *rt2x00dev) { cancel_delayed_work_sync(&rt2x00dev->link.work); } void rt2x00link_reset_tuner(struct rt2x00_dev *rt2x00dev, bool antenna) { struct link_qual *qual = &rt2x00dev->link.qual; u8 vgc_level = qual->vgc_level_reg; if (!test_bit(DEVICE_STATE_ENABLED_RADIO, &rt2x00dev->flags)) return; /* * Reset link information. * Both the currently active vgc level as well as * the link tuner counter should be reset. Resetting * the counter is important for devices where the * device should only perform link tuning during the * first minute after being enabled. */ rt2x00dev->link.count = 0; memset(qual, 0, sizeof(*qual)); /* * Restore the VGC level as stored in the registers, * the driver can use this to determine if the register * must be updated during reset or not. */ qual->vgc_level_reg = vgc_level; /* * Reset the link tuner. */ rt2x00dev->ops->lib->reset_tuner(rt2x00dev, qual); if (antenna) rt2x00link_antenna_reset(rt2x00dev); } static void rt2x00link_reset_qual(struct rt2x00_dev *rt2x00dev) { struct link_qual *qual = &rt2x00dev->link.qual; qual->rx_success = 0; qual->rx_failed = 0; qual->tx_success = 0; qual->tx_failed = 0; } static void rt2x00link_tuner(struct work_struct *work) { struct rt2x00_dev *rt2x00dev = container_of(work, struct rt2x00_dev, link.work.work); struct link *link = &rt2x00dev->link; struct link_qual *qual = &rt2x00dev->link.qual; /* * When the radio is shutting down we should * immediately cease all link tuning. */ if (!test_bit(DEVICE_STATE_ENABLED_RADIO, &rt2x00dev->flags) || test_bit(DEVICE_STATE_SCANNING, &rt2x00dev->flags)) return; /* * Update statistics. */ rt2x00dev->ops->lib->link_stats(rt2x00dev, qual); rt2x00dev->low_level_stats.dot11FCSErrorCount += qual->rx_failed; /* * Update quality RSSI for link tuning, * when we have received some frames and we managed to * collect the RSSI data we could use this. Otherwise we * must fallback to the default RSSI value. */ if (!link->avg_rssi.avg || !qual->rx_success) qual->rssi = DEFAULT_RSSI; else qual->rssi = link->avg_rssi.avg; /* * Check if link tuning is supported by the hardware, some hardware * do not support link tuning at all, while other devices can disable * the feature from the EEPROM. */ if (test_bit(CAPABILITY_LINK_TUNING, &rt2x00dev->cap_flags)) rt2x00dev->ops->lib->link_tuner(rt2x00dev, qual, link->count); /* * Send a signal to the led to update the led signal strength. */ rt2x00leds_led_quality(rt2x00dev, qual->rssi); /* * Evaluate antenna setup, make this the last step when * rt2x00lib_antenna_diversity made changes the quality * statistics will be reset. */ if (rt2x00lib_antenna_diversity(rt2x00dev)) rt2x00link_reset_qual(rt2x00dev); /* * Increase tuner counter, and reschedule the next link tuner run. */ link->count++; if (test_bit(DEVICE_STATE_PRESENT, &rt2x00dev->flags)) ieee80211_queue_delayed_work(rt2x00dev->hw, &link->work, LINK_TUNE_INTERVAL); } void rt2x00link_start_watchdog(struct rt2x00_dev *rt2x00dev) { struct link *link = &rt2x00dev->link; if (test_bit(DEVICE_STATE_PRESENT, &rt2x00dev->flags) && rt2x00dev->ops->lib->watchdog) ieee80211_queue_delayed_work(rt2x00dev->hw, &link->watchdog_work, WATCHDOG_INTERVAL); } void rt2x00link_stop_watchdog(struct rt2x00_dev *rt2x00dev) { cancel_delayed_work_sync(&rt2x00dev->link.watchdog_work); } static void rt2x00link_watchdog(struct work_struct *work) { struct rt2x00_dev *rt2x00dev = container_of(work, struct rt2x00_dev, link.watchdog_work.work); struct link *link = &rt2x00dev->link; /* * When the radio is shutting down we should * immediately cease the watchdog monitoring. */ if (!test_bit(DEVICE_STATE_ENABLED_RADIO, &rt2x00dev->flags)) return; rt2x00dev->ops->lib->watchdog(rt2x00dev); if (test_bit(DEVICE_STATE_PRESENT, &rt2x00dev->flags)) ieee80211_queue_delayed_work(rt2x00dev->hw, &link->watchdog_work, WATCHDOG_INTERVAL); } void rt2x00link_start_agc(struct rt2x00_dev *rt2x00dev) { struct link *link = &rt2x00dev->link; if (test_bit(DEVICE_STATE_PRESENT, &rt2x00dev->flags) && rt2x00dev->ops->lib->gain_calibration) ieee80211_queue_delayed_work(rt2x00dev->hw, &link->agc_work, AGC_INTERVAL); } void rt2x00link_stop_agc(struct rt2x00_dev *rt2x00dev) { cancel_delayed_work_sync(&rt2x00dev->link.agc_work); } static void rt2x00link_agc(struct work_struct *work) { struct rt2x00_dev *rt2x00dev = container_of(work, struct rt2x00_dev, link.agc_work.work); struct link *link = &rt2x00dev->link; /* * When the radio is shutting down we should * immediately cease the watchdog monitoring. */ if (!test_bit(DEVICE_STATE_ENABLED_RADIO, &rt2x00dev->flags)) return; rt2x00dev->ops->lib->gain_calibration(rt2x00dev); if (test_bit(DEVICE_STATE_PRESENT, &rt2x00dev->flags)) ieee80211_queue_delayed_work(rt2x00dev->hw, &link->agc_work, AGC_INTERVAL); } void rt2x00link_register(struct rt2x00_dev *rt2x00dev) { INIT_DELAYED_WORK(&rt2x00dev->link.agc_work, rt2x00link_agc); INIT_DELAYED_WORK(&rt2x00dev->link.watchdog_work, rt2x00link_watchdog); INIT_DELAYED_WORK(&rt2x00dev->link.work, rt2x00link_tuner); }
gpl-2.0
Alucard24/Dorimanx-SG2-I9100-Kernel
drivers/video/bfin_adv7393fb.c
3035
20143
/* * Frame buffer driver for ADV7393/2 video encoder * * Copyright 2006-2009 Analog Devices Inc. * Licensed under the GPL-2 or late. */ /* * TODO: Remove Globals * TODO: Code Cleanup */ #define pr_fmt(fmt) DRIVER_NAME ": " fmt #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/slab.h> #include <linux/delay.h> #include <linux/fb.h> #include <linux/ioport.h> #include <linux/init.h> #include <linux/types.h> #include <linux/interrupt.h> #include <linux/sched.h> #include <asm/blackfin.h> #include <asm/irq.h> #include <asm/dma.h> #include <linux/uaccess.h> #include <linux/gpio.h> #include <asm/portmux.h> #include <linux/dma-mapping.h> #include <linux/proc_fs.h> #include <linux/platform_device.h> #include <linux/i2c.h> #include <linux/i2c-dev.h> #include "bfin_adv7393fb.h" static int mode = VMODE; static int mem = VMEM; static int nocursor = 1; static const unsigned short ppi_pins[] = { P_PPI0_CLK, P_PPI0_FS1, P_PPI0_FS2, P_PPI0_D0, P_PPI0_D1, P_PPI0_D2, P_PPI0_D3, P_PPI0_D4, P_PPI0_D5, P_PPI0_D6, P_PPI0_D7, P_PPI0_D8, P_PPI0_D9, P_PPI0_D10, P_PPI0_D11, P_PPI0_D12, P_PPI0_D13, P_PPI0_D14, P_PPI0_D15, 0 }; /* * card parameters */ static struct bfin_adv7393_fb_par { /* structure holding blackfin / adv7393 paramters when screen is blanked */ struct { u8 Mode; /* ntsc/pal/? */ } vga_state; atomic_t ref_count; } bfin_par; /* --------------------------------------------------------------------- */ static struct fb_var_screeninfo bfin_adv7393_fb_defined = { .xres = 720, .yres = 480, .xres_virtual = 720, .yres_virtual = 480, .bits_per_pixel = 16, .activate = FB_ACTIVATE_TEST, .height = -1, .width = -1, .left_margin = 0, .right_margin = 0, .upper_margin = 0, .lower_margin = 0, .vmode = FB_VMODE_INTERLACED, .red = {11, 5, 0}, .green = {5, 6, 0}, .blue = {0, 5, 0}, .transp = {0, 0, 0}, }; static struct fb_fix_screeninfo bfin_adv7393_fb_fix __devinitdata = { .id = "BFIN ADV7393", .smem_len = 720 * 480 * 2, .type = FB_TYPE_PACKED_PIXELS, .visual = FB_VISUAL_TRUECOLOR, .xpanstep = 0, .ypanstep = 0, .line_length = 720 * 2, .accel = FB_ACCEL_NONE }; static struct fb_ops bfin_adv7393_fb_ops = { .owner = THIS_MODULE, .fb_open = bfin_adv7393_fb_open, .fb_release = bfin_adv7393_fb_release, .fb_check_var = bfin_adv7393_fb_check_var, .fb_pan_display = bfin_adv7393_fb_pan_display, .fb_blank = bfin_adv7393_fb_blank, .fb_fillrect = cfb_fillrect, .fb_copyarea = cfb_copyarea, .fb_imageblit = cfb_imageblit, .fb_cursor = bfin_adv7393_fb_cursor, .fb_setcolreg = bfin_adv7393_fb_setcolreg, }; static int dma_desc_list(struct adv7393fb_device *fbdev, u16 arg) { if (arg == BUILD) { /* Build */ fbdev->vb1 = l1_data_sram_zalloc(sizeof(struct dmasg)); if (fbdev->vb1 == NULL) goto error; fbdev->av1 = l1_data_sram_zalloc(sizeof(struct dmasg)); if (fbdev->av1 == NULL) goto error; fbdev->vb2 = l1_data_sram_zalloc(sizeof(struct dmasg)); if (fbdev->vb2 == NULL) goto error; fbdev->av2 = l1_data_sram_zalloc(sizeof(struct dmasg)); if (fbdev->av2 == NULL) goto error; /* Build linked DMA descriptor list */ fbdev->vb1->next_desc_addr = fbdev->av1; fbdev->av1->next_desc_addr = fbdev->vb2; fbdev->vb2->next_desc_addr = fbdev->av2; fbdev->av2->next_desc_addr = fbdev->vb1; /* Save list head */ fbdev->descriptor_list_head = fbdev->av2; /* Vertical Blanking Field 1 */ fbdev->vb1->start_addr = VB_DUMMY_MEMORY_SOURCE; fbdev->vb1->cfg = DMA_CFG_VAL; fbdev->vb1->x_count = fbdev->modes[mode].xres + fbdev->modes[mode].boeft_blank; fbdev->vb1->x_modify = 0; fbdev->vb1->y_count = fbdev->modes[mode].vb1_lines; fbdev->vb1->y_modify = 0; /* Active Video Field 1 */ fbdev->av1->start_addr = (unsigned long)fbdev->fb_mem; fbdev->av1->cfg = DMA_CFG_VAL; fbdev->av1->x_count = fbdev->modes[mode].xres + fbdev->modes[mode].boeft_blank; fbdev->av1->x_modify = fbdev->modes[mode].bpp / 8; fbdev->av1->y_count = fbdev->modes[mode].a_lines; fbdev->av1->y_modify = (fbdev->modes[mode].xres - fbdev->modes[mode].boeft_blank + 1) * (fbdev->modes[mode].bpp / 8); /* Vertical Blanking Field 2 */ fbdev->vb2->start_addr = VB_DUMMY_MEMORY_SOURCE; fbdev->vb2->cfg = DMA_CFG_VAL; fbdev->vb2->x_count = fbdev->modes[mode].xres + fbdev->modes[mode].boeft_blank; fbdev->vb2->x_modify = 0; fbdev->vb2->y_count = fbdev->modes[mode].vb2_lines; fbdev->vb2->y_modify = 0; /* Active Video Field 2 */ fbdev->av2->start_addr = (unsigned long)fbdev->fb_mem + fbdev->line_len; fbdev->av2->cfg = DMA_CFG_VAL; fbdev->av2->x_count = fbdev->modes[mode].xres + fbdev->modes[mode].boeft_blank; fbdev->av2->x_modify = (fbdev->modes[mode].bpp / 8); fbdev->av2->y_count = fbdev->modes[mode].a_lines; fbdev->av2->y_modify = (fbdev->modes[mode].xres - fbdev->modes[mode].boeft_blank + 1) * (fbdev->modes[mode].bpp / 8); return 1; } error: l1_data_sram_free(fbdev->vb1); l1_data_sram_free(fbdev->av1); l1_data_sram_free(fbdev->vb2); l1_data_sram_free(fbdev->av2); return 0; } static int bfin_config_dma(struct adv7393fb_device *fbdev) { BUG_ON(!(fbdev->fb_mem)); set_dma_x_count(CH_PPI, fbdev->descriptor_list_head->x_count); set_dma_x_modify(CH_PPI, fbdev->descriptor_list_head->x_modify); set_dma_y_count(CH_PPI, fbdev->descriptor_list_head->y_count); set_dma_y_modify(CH_PPI, fbdev->descriptor_list_head->y_modify); set_dma_start_addr(CH_PPI, fbdev->descriptor_list_head->start_addr); set_dma_next_desc_addr(CH_PPI, fbdev->descriptor_list_head->next_desc_addr); set_dma_config(CH_PPI, fbdev->descriptor_list_head->cfg); return 1; } static void bfin_disable_dma(void) { bfin_write_DMA0_CONFIG(bfin_read_DMA0_CONFIG() & ~DMAEN); } static void bfin_config_ppi(struct adv7393fb_device *fbdev) { if (ANOMALY_05000183) { bfin_write_TIMER2_CONFIG(WDTH_CAP); bfin_write_TIMER_ENABLE(TIMEN2); } bfin_write_PPI_CONTROL(0x381E); bfin_write_PPI_FRAME(fbdev->modes[mode].tot_lines); bfin_write_PPI_COUNT(fbdev->modes[mode].xres + fbdev->modes[mode].boeft_blank - 1); bfin_write_PPI_DELAY(fbdev->modes[mode].aoeft_blank - 1); } static void bfin_enable_ppi(void) { bfin_write_PPI_CONTROL(bfin_read_PPI_CONTROL() | PORT_EN); } static void bfin_disable_ppi(void) { bfin_write_PPI_CONTROL(bfin_read_PPI_CONTROL() & ~PORT_EN); } static inline int adv7393_write(struct i2c_client *client, u8 reg, u8 value) { return i2c_smbus_write_byte_data(client, reg, value); } static inline int adv7393_read(struct i2c_client *client, u8 reg) { return i2c_smbus_read_byte_data(client, reg); } static int adv7393_write_block(struct i2c_client *client, const u8 *data, unsigned int len) { int ret = -1; u8 reg; while (len >= 2) { reg = *data++; ret = adv7393_write(client, reg, *data++); if (ret < 0) break; len -= 2; } return ret; } static int adv7393_mode(struct i2c_client *client, u16 mode) { switch (mode) { case POWER_ON: /* ADV7393 Sleep mode OFF */ adv7393_write(client, 0x00, 0x1E); break; case POWER_DOWN: /* ADV7393 Sleep mode ON */ adv7393_write(client, 0x00, 0x1F); break; case BLANK_OFF: /* Pixel Data Valid */ adv7393_write(client, 0x82, 0xCB); break; case BLANK_ON: /* Pixel Data Invalid */ adv7393_write(client, 0x82, 0x8B); break; default: return -EINVAL; break; } return 0; } static irqreturn_t ppi_irq_error(int irq, void *dev_id) { struct adv7393fb_device *fbdev = (struct adv7393fb_device *)dev_id; u16 status = bfin_read_PPI_STATUS(); pr_debug("%s: PPI Status = 0x%X\n", __func__, status); if (status) { bfin_disable_dma(); /* TODO: Check Sequence */ bfin_disable_ppi(); bfin_clear_PPI_STATUS(); bfin_config_dma(fbdev); bfin_enable_ppi(); } return IRQ_HANDLED; } static int proc_output(char *buf) { char *p = buf; p += sprintf(p, "Usage:\n" "echo 0x[REG][Value] > adv7393\n" "example: echo 0x1234 >adv7393\n" "writes 0x34 into Register 0x12\n"); return p - buf; } static int adv7393_read_proc(char *page, char **start, off_t off, int count, int *eof, void *data) { int len; len = proc_output(page); if (len <= off + count) *eof = 1; *start = page + off; len -= off; if (len > count) len = count; if (len < 0) len = 0; return len; } static int adv7393_write_proc(struct file *file, const char __user * buffer, unsigned long count, void *data) { struct adv7393fb_device *fbdev = data; char line[8]; unsigned int val; int ret; ret = copy_from_user(line, buffer, count); if (ret) return -EFAULT; val = simple_strtoul(line, NULL, 0); adv7393_write(fbdev->client, val >> 8, val & 0xff); return count; } static int __devinit bfin_adv7393_fb_probe(struct i2c_client *client, const struct i2c_device_id *id) { int ret = 0; struct proc_dir_entry *entry; int num_modes = ARRAY_SIZE(known_modes); struct adv7393fb_device *fbdev = NULL; if (mem > 2) { dev_err(&client->dev, "mem out of allowed range [1;2]\n"); return -EINVAL; } if (mode > num_modes) { dev_err(&client->dev, "mode %d: not supported", mode); return -EFAULT; } fbdev = kzalloc(sizeof(*fbdev), GFP_KERNEL); if (!fbdev) { dev_err(&client->dev, "failed to allocate device private record"); return -ENOMEM; } i2c_set_clientdata(client, fbdev); fbdev->modes = known_modes; fbdev->client = client; fbdev->fb_len = mem * fbdev->modes[mode].xres * fbdev->modes[mode].xres * (fbdev->modes[mode].bpp / 8); fbdev->line_len = fbdev->modes[mode].xres * (fbdev->modes[mode].bpp / 8); /* Workaround "PPI Does Not Start Properly In Specific Mode" */ if (ANOMALY_05000400) { if (gpio_request(P_IDENT(P_PPI0_FS3), "PPI0_FS3")) { dev_err(&client->dev, "PPI0_FS3 GPIO request failed\n"); ret = -EBUSY; goto out_8; } gpio_direction_output(P_IDENT(P_PPI0_FS3), 0); } if (peripheral_request_list(ppi_pins, DRIVER_NAME)) { dev_err(&client->dev, "requesting PPI peripheral failed\n"); ret = -EFAULT; goto out_8; } fbdev->fb_mem = dma_alloc_coherent(NULL, fbdev->fb_len, &fbdev->dma_handle, GFP_KERNEL); if (NULL == fbdev->fb_mem) { dev_err(&client->dev, "couldn't allocate dma buffer (%d bytes)\n", (u32) fbdev->fb_len); ret = -ENOMEM; goto out_7; } fbdev->info.screen_base = (void *)fbdev->fb_mem; bfin_adv7393_fb_fix.smem_start = (int)fbdev->fb_mem; bfin_adv7393_fb_fix.smem_len = fbdev->fb_len; bfin_adv7393_fb_fix.line_length = fbdev->line_len; if (mem > 1) bfin_adv7393_fb_fix.ypanstep = 1; bfin_adv7393_fb_defined.red.length = 5; bfin_adv7393_fb_defined.green.length = 6; bfin_adv7393_fb_defined.blue.length = 5; bfin_adv7393_fb_defined.xres = fbdev->modes[mode].xres; bfin_adv7393_fb_defined.yres = fbdev->modes[mode].yres; bfin_adv7393_fb_defined.xres_virtual = fbdev->modes[mode].xres; bfin_adv7393_fb_defined.yres_virtual = mem * fbdev->modes[mode].yres; bfin_adv7393_fb_defined.bits_per_pixel = fbdev->modes[mode].bpp; fbdev->info.fbops = &bfin_adv7393_fb_ops; fbdev->info.var = bfin_adv7393_fb_defined; fbdev->info.fix = bfin_adv7393_fb_fix; fbdev->info.par = &bfin_par; fbdev->info.flags = FBINFO_DEFAULT; fbdev->info.pseudo_palette = kzalloc(sizeof(u32) * 16, GFP_KERNEL); if (!fbdev->info.pseudo_palette) { dev_err(&client->dev, "failed to allocate pseudo_palette\n"); ret = -ENOMEM; goto out_6; } if (fb_alloc_cmap(&fbdev->info.cmap, BFIN_LCD_NBR_PALETTE_ENTRIES, 0) < 0) { dev_err(&client->dev, "failed to allocate colormap (%d entries)\n", BFIN_LCD_NBR_PALETTE_ENTRIES); ret = -EFAULT; goto out_5; } if (request_dma(CH_PPI, "BF5xx_PPI_DMA") < 0) { dev_err(&client->dev, "unable to request PPI DMA\n"); ret = -EFAULT; goto out_4; } if (request_irq(IRQ_PPI_ERROR, ppi_irq_error, IRQF_DISABLED, "PPI ERROR", fbdev) < 0) { dev_err(&client->dev, "unable to request PPI ERROR IRQ\n"); ret = -EFAULT; goto out_3; } fbdev->open = 0; ret = adv7393_write_block(client, fbdev->modes[mode].adv7393_i2c_initd, fbdev->modes[mode].adv7393_i2c_initd_len); if (ret) { dev_err(&client->dev, "i2c attach: init error\n"); goto out_1; } if (register_framebuffer(&fbdev->info) < 0) { dev_err(&client->dev, "unable to register framebuffer\n"); ret = -EFAULT; goto out_1; } dev_info(&client->dev, "fb%d: %s frame buffer device\n", fbdev->info.node, fbdev->info.fix.id); dev_info(&client->dev, "fb memory address : 0x%p\n", fbdev->fb_mem); entry = create_proc_entry("driver/adv7393", 0, NULL); if (!entry) { dev_err(&client->dev, "unable to create /proc entry\n"); ret = -EFAULT; goto out_0; } entry->read_proc = adv7393_read_proc; entry->write_proc = adv7393_write_proc; entry->data = fbdev; return 0; out_0: unregister_framebuffer(&fbdev->info); out_1: free_irq(IRQ_PPI_ERROR, fbdev); out_3: free_dma(CH_PPI); out_4: dma_free_coherent(NULL, fbdev->fb_len, fbdev->fb_mem, fbdev->dma_handle); out_5: fb_dealloc_cmap(&fbdev->info.cmap); out_6: kfree(fbdev->info.pseudo_palette); out_7: peripheral_free_list(ppi_pins); out_8: kfree(fbdev); return ret; } static int bfin_adv7393_fb_open(struct fb_info *info, int user) { struct adv7393fb_device *fbdev = to_adv7393fb_device(info); fbdev->info.screen_base = (void *)fbdev->fb_mem; if (!fbdev->info.screen_base) { dev_err(&fbdev->client->dev, "unable to map device\n"); return -ENOMEM; } fbdev->open = 1; dma_desc_list(fbdev, BUILD); adv7393_mode(fbdev->client, BLANK_OFF); bfin_config_ppi(fbdev); bfin_config_dma(fbdev); bfin_enable_ppi(); return 0; } static int bfin_adv7393_fb_release(struct fb_info *info, int user) { struct adv7393fb_device *fbdev = to_adv7393fb_device(info); adv7393_mode(fbdev->client, BLANK_ON); bfin_disable_dma(); bfin_disable_ppi(); dma_desc_list(fbdev, DESTRUCT); fbdev->open = 0; return 0; } static int bfin_adv7393_fb_check_var(struct fb_var_screeninfo *var, struct fb_info *info) { switch (var->bits_per_pixel) { case 16:/* DIRECTCOLOUR, 64k */ var->red.offset = info->var.red.offset; var->green.offset = info->var.green.offset; var->blue.offset = info->var.blue.offset; var->red.length = info->var.red.length; var->green.length = info->var.green.length; var->blue.length = info->var.blue.length; var->transp.offset = 0; var->transp.length = 0; var->transp.msb_right = 0; var->red.msb_right = 0; var->green.msb_right = 0; var->blue.msb_right = 0; break; default: pr_debug("%s: depth not supported: %u BPP\n", __func__, var->bits_per_pixel); return -EINVAL; } if (info->var.xres != var->xres || info->var.yres != var->yres || info->var.xres_virtual != var->xres_virtual || info->var.yres_virtual != var->yres_virtual) { pr_debug("%s: Resolution not supported: X%u x Y%u\n", __func__, var->xres, var->yres); return -EINVAL; } /* * Memory limit */ if ((info->fix.line_length * var->yres_virtual) > info->fix.smem_len) { pr_debug("%s: Memory Limit requested yres_virtual = %u\n", __func__, var->yres_virtual); return -ENOMEM; } return 0; } static int bfin_adv7393_fb_pan_display(struct fb_var_screeninfo *var, struct fb_info *info) { int dy; u32 dmaaddr; struct adv7393fb_device *fbdev = to_adv7393fb_device(info); if (!var || !info) return -EINVAL; if (var->xoffset - info->var.xoffset) { /* No support for X panning for now! */ return -EINVAL; } dy = var->yoffset - info->var.yoffset; if (dy) { pr_debug("%s: Panning screen of %d lines\n", __func__, dy); dmaaddr = fbdev->av1->start_addr; dmaaddr += (info->fix.line_length * dy); /* TODO: Wait for current frame to finished */ fbdev->av1->start_addr = (unsigned long)dmaaddr; fbdev->av2->start_addr = (unsigned long)dmaaddr + fbdev->line_len; } return 0; } /* 0 unblank, 1 blank, 2 no vsync, 3 no hsync, 4 off */ static int bfin_adv7393_fb_blank(int blank, struct fb_info *info) { struct adv7393fb_device *fbdev = to_adv7393fb_device(info); switch (blank) { case VESA_NO_BLANKING: /* Turn on panel */ adv7393_mode(fbdev->client, BLANK_OFF); break; case VESA_VSYNC_SUSPEND: case VESA_HSYNC_SUSPEND: case VESA_POWERDOWN: /* Turn off panel */ adv7393_mode(fbdev->client, BLANK_ON); break; default: return -EINVAL; break; } return 0; } int bfin_adv7393_fb_cursor(struct fb_info *info, struct fb_cursor *cursor) { if (nocursor) return 0; else return -EINVAL; /* just to force soft_cursor() call */ } static int bfin_adv7393_fb_setcolreg(u_int regno, u_int red, u_int green, u_int blue, u_int transp, struct fb_info *info) { if (regno >= BFIN_LCD_NBR_PALETTE_ENTRIES) return -EINVAL; if (info->var.grayscale) /* grayscale = 0.30*R + 0.59*G + 0.11*B */ red = green = blue = (red * 77 + green * 151 + blue * 28) >> 8; if (info->fix.visual == FB_VISUAL_TRUECOLOR) { u32 value; /* Place color in the pseudopalette */ if (regno > 16) return -EINVAL; red >>= (16 - info->var.red.length); green >>= (16 - info->var.green.length); blue >>= (16 - info->var.blue.length); value = (red << info->var.red.offset) | (green << info->var.green.offset)| (blue << info->var.blue.offset); value &= 0xFFFF; ((u32 *) (info->pseudo_palette))[regno] = value; } return 0; } static int __devexit bfin_adv7393_fb_remove(struct i2c_client *client) { struct adv7393fb_device *fbdev = i2c_get_clientdata(client); adv7393_mode(client, POWER_DOWN); if (fbdev->fb_mem) dma_free_coherent(NULL, fbdev->fb_len, fbdev->fb_mem, fbdev->dma_handle); free_dma(CH_PPI); free_irq(IRQ_PPI_ERROR, fbdev); unregister_framebuffer(&fbdev->info); remove_proc_entry("driver/adv7393", NULL); fb_dealloc_cmap(&fbdev->info.cmap); kfree(fbdev->info.pseudo_palette); if (ANOMALY_05000400) gpio_free(P_IDENT(P_PPI0_FS3)); /* FS3 */ peripheral_free_list(ppi_pins); kfree(fbdev); return 0; } #ifdef CONFIG_PM static int bfin_adv7393_fb_suspend(struct device *dev) { struct adv7393fb_device *fbdev = dev_get_drvdata(dev); if (fbdev->open) { bfin_disable_dma(); bfin_disable_ppi(); dma_desc_list(fbdev, DESTRUCT); } adv7393_mode(fbdev->client, POWER_DOWN); return 0; } static int bfin_adv7393_fb_resume(struct device *dev) { struct adv7393fb_device *fbdev = dev_get_drvdata(dev); adv7393_mode(fbdev->client, POWER_ON); if (fbdev->open) { dma_desc_list(fbdev, BUILD); bfin_config_ppi(fbdev); bfin_config_dma(fbdev); bfin_enable_ppi(); } return 0; } static const struct dev_pm_ops bfin_adv7393_dev_pm_ops = { .suspend = bfin_adv7393_fb_suspend, .resume = bfin_adv7393_fb_resume, }; #endif static const struct i2c_device_id bfin_adv7393_id[] = { {DRIVER_NAME, 0}, {} }; MODULE_DEVICE_TABLE(i2c, bfin_adv7393_id); static struct i2c_driver bfin_adv7393_fb_driver = { .driver = { .name = DRIVER_NAME, #ifdef CONFIG_PM .pm = &bfin_adv7393_dev_pm_ops, #endif }, .probe = bfin_adv7393_fb_probe, .remove = __devexit_p(bfin_adv7393_fb_remove), .id_table = bfin_adv7393_id, }; static int __init bfin_adv7393_fb_driver_init(void) { #if defined(CONFIG_I2C_BLACKFIN_TWI) || defined(CONFIG_I2C_BLACKFIN_TWI_MODULE) request_module("i2c-bfin-twi"); #else request_module("i2c-gpio"); #endif return i2c_add_driver(&bfin_adv7393_fb_driver); } module_init(bfin_adv7393_fb_driver_init); static void __exit bfin_adv7393_fb_driver_cleanup(void) { i2c_del_driver(&bfin_adv7393_fb_driver); } module_exit(bfin_adv7393_fb_driver_cleanup); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>"); MODULE_DESCRIPTION("Frame buffer driver for ADV7393/2 Video Encoder"); module_param(mode, int, 0); MODULE_PARM_DESC(mode, "Video Mode (0=NTSC,1=PAL,2=NTSC 640x480,3=PAL 640x480,4=NTSC YCbCr input,5=PAL YCbCr input)"); module_param(mem, int, 0); MODULE_PARM_DESC(mem, "Size of frame buffer memory 1=Single 2=Double Size (allows y-panning / frame stacking)"); module_param(nocursor, int, 0644); MODULE_PARM_DESC(nocursor, "cursor enable/disable");
gpl-2.0
Zoldyck07/Bakemono-
drivers/tty/serial/kgdboc.c
5083
7389
/* * Based on the same principle as kgdboe using the NETPOLL api, this * driver uses a console polling api to implement a gdb serial inteface * which is multiplexed on a console port. * * Maintainer: Jason Wessel <jason.wessel@windriver.com> * * 2007-2008 (c) Jason Wessel - Wind River Systems, Inc. * * This file is licensed under the terms of the GNU General Public * License version 2. This program is licensed "as is" without any * warranty of any kind, whether express or implied. */ #include <linux/kernel.h> #include <linux/ctype.h> #include <linux/kgdb.h> #include <linux/kdb.h> #include <linux/tty.h> #include <linux/console.h> #include <linux/vt_kern.h> #include <linux/input.h> #include <linux/module.h> #define MAX_CONFIG_LEN 40 static struct kgdb_io kgdboc_io_ops; /* -1 = init not run yet, 0 = unconfigured, 1 = configured. */ static int configured = -1; static char config[MAX_CONFIG_LEN]; static struct kparam_string kps = { .string = config, .maxlen = MAX_CONFIG_LEN, }; static int kgdboc_use_kms; /* 1 if we use kernel mode switching */ static struct tty_driver *kgdb_tty_driver; static int kgdb_tty_line; #ifdef CONFIG_KDB_KEYBOARD static int kgdboc_reset_connect(struct input_handler *handler, struct input_dev *dev, const struct input_device_id *id) { input_reset_device(dev); /* Retrun an error - we do not want to bind, just to reset */ return -ENODEV; } static void kgdboc_reset_disconnect(struct input_handle *handle) { /* We do not expect anyone to actually bind to us */ BUG(); } static const struct input_device_id kgdboc_reset_ids[] = { { .flags = INPUT_DEVICE_ID_MATCH_EVBIT, .evbit = { BIT_MASK(EV_KEY) }, }, { } }; static struct input_handler kgdboc_reset_handler = { .connect = kgdboc_reset_connect, .disconnect = kgdboc_reset_disconnect, .name = "kgdboc_reset", .id_table = kgdboc_reset_ids, }; static DEFINE_MUTEX(kgdboc_reset_mutex); static void kgdboc_restore_input_helper(struct work_struct *dummy) { /* * We need to take a mutex to prevent several instances of * this work running on different CPUs so they don't try * to register again already registered handler. */ mutex_lock(&kgdboc_reset_mutex); if (input_register_handler(&kgdboc_reset_handler) == 0) input_unregister_handler(&kgdboc_reset_handler); mutex_unlock(&kgdboc_reset_mutex); } static DECLARE_WORK(kgdboc_restore_input_work, kgdboc_restore_input_helper); static void kgdboc_restore_input(void) { if (likely(system_state == SYSTEM_RUNNING)) schedule_work(&kgdboc_restore_input_work); } static int kgdboc_register_kbd(char **cptr) { if (strncmp(*cptr, "kbd", 3) == 0) { if (kdb_poll_idx < KDB_POLL_FUNC_MAX) { kdb_poll_funcs[kdb_poll_idx] = kdb_get_kbd_char; kdb_poll_idx++; if (cptr[0][3] == ',') *cptr += 4; else return 1; } } return 0; } static void kgdboc_unregister_kbd(void) { int i; for (i = 0; i < kdb_poll_idx; i++) { if (kdb_poll_funcs[i] == kdb_get_kbd_char) { kdb_poll_idx--; kdb_poll_funcs[i] = kdb_poll_funcs[kdb_poll_idx]; kdb_poll_funcs[kdb_poll_idx] = NULL; i--; } } flush_work_sync(&kgdboc_restore_input_work); } #else /* ! CONFIG_KDB_KEYBOARD */ #define kgdboc_register_kbd(x) 0 #define kgdboc_unregister_kbd() #define kgdboc_restore_input() #endif /* ! CONFIG_KDB_KEYBOARD */ static int kgdboc_option_setup(char *opt) { if (strlen(opt) >= MAX_CONFIG_LEN) { printk(KERN_ERR "kgdboc: config string too long\n"); return -ENOSPC; } strcpy(config, opt); return 0; } __setup("kgdboc=", kgdboc_option_setup); static void cleanup_kgdboc(void) { kgdboc_unregister_kbd(); if (configured == 1) kgdb_unregister_io_module(&kgdboc_io_ops); } static int configure_kgdboc(void) { struct tty_driver *p; int tty_line = 0; int err; char *cptr = config; struct console *cons; err = kgdboc_option_setup(config); if (err || !strlen(config) || isspace(config[0])) goto noconfig; err = -ENODEV; kgdboc_io_ops.is_console = 0; kgdb_tty_driver = NULL; kgdboc_use_kms = 0; if (strncmp(cptr, "kms,", 4) == 0) { cptr += 4; kgdboc_use_kms = 1; } if (kgdboc_register_kbd(&cptr)) goto do_register; p = tty_find_polling_driver(cptr, &tty_line); if (!p) goto noconfig; cons = console_drivers; while (cons) { int idx; if (cons->device && cons->device(cons, &idx) == p && idx == tty_line) { kgdboc_io_ops.is_console = 1; break; } cons = cons->next; } kgdb_tty_driver = p; kgdb_tty_line = tty_line; do_register: err = kgdb_register_io_module(&kgdboc_io_ops); if (err) goto noconfig; configured = 1; return 0; noconfig: config[0] = 0; configured = 0; cleanup_kgdboc(); return err; } static int __init init_kgdboc(void) { /* Already configured? */ if (configured == 1) return 0; return configure_kgdboc(); } static int kgdboc_get_char(void) { if (!kgdb_tty_driver) return -1; return kgdb_tty_driver->ops->poll_get_char(kgdb_tty_driver, kgdb_tty_line); } static void kgdboc_put_char(u8 chr) { if (!kgdb_tty_driver) return; kgdb_tty_driver->ops->poll_put_char(kgdb_tty_driver, kgdb_tty_line, chr); } static int param_set_kgdboc_var(const char *kmessage, struct kernel_param *kp) { int len = strlen(kmessage); if (len >= MAX_CONFIG_LEN) { printk(KERN_ERR "kgdboc: config string too long\n"); return -ENOSPC; } /* Only copy in the string if the init function has not run yet */ if (configured < 0) { strcpy(config, kmessage); return 0; } if (kgdb_connected) { printk(KERN_ERR "kgdboc: Cannot reconfigure while KGDB is connected.\n"); return -EBUSY; } strcpy(config, kmessage); /* Chop out \n char as a result of echo */ if (config[len - 1] == '\n') config[len - 1] = '\0'; if (configured == 1) cleanup_kgdboc(); /* Go and configure with the new params. */ return configure_kgdboc(); } static int dbg_restore_graphics; static void kgdboc_pre_exp_handler(void) { if (!dbg_restore_graphics && kgdboc_use_kms) { dbg_restore_graphics = 1; con_debug_enter(vc_cons[fg_console].d); } /* Increment the module count when the debugger is active */ if (!kgdb_connected) try_module_get(THIS_MODULE); } static void kgdboc_post_exp_handler(void) { /* decrement the module count when the debugger detaches */ if (!kgdb_connected) module_put(THIS_MODULE); if (kgdboc_use_kms && dbg_restore_graphics) { dbg_restore_graphics = 0; con_debug_leave(); } kgdboc_restore_input(); } static struct kgdb_io kgdboc_io_ops = { .name = "kgdboc", .read_char = kgdboc_get_char, .write_char = kgdboc_put_char, .pre_exception = kgdboc_pre_exp_handler, .post_exception = kgdboc_post_exp_handler, }; #ifdef CONFIG_KGDB_SERIAL_CONSOLE /* This is only available if kgdboc is a built in for early debugging */ static int __init kgdboc_early_init(char *opt) { /* save the first character of the config string because the * init routine can destroy it. */ char save_ch; kgdboc_option_setup(opt); save_ch = config[0]; init_kgdboc(); config[0] = save_ch; return 0; } early_param("ekgdboc", kgdboc_early_init); #endif /* CONFIG_KGDB_SERIAL_CONSOLE */ module_init(init_kgdboc); module_exit(cleanup_kgdboc); module_param_call(kgdboc, param_set_kgdboc_var, param_get_string, &kps, 0644); MODULE_PARM_DESC(kgdboc, "<serial_device>[,baud]"); MODULE_DESCRIPTION("KGDB Console TTY Driver"); MODULE_LICENSE("GPL");
gpl-2.0
tim-smart/kernel_lge_mako
drivers/usb/gadget/fsl_mxc_udc.c
5083
2948
/* * Copyright (C) 2009 * Guennadi Liakhovetski, DENX Software Engineering, <lg@denx.de> * * Description: * Helper routines for i.MX3x SoCs from Freescale, needed by the fsl_usb2_udc.c * driver to function correctly on these systems. * * 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/clk.h> #include <linux/delay.h> #include <linux/err.h> #include <linux/fsl_devices.h> #include <linux/platform_device.h> #include <linux/io.h> #include <mach/hardware.h> static struct clk *mxc_ahb_clk; static struct clk *mxc_usb_clk; /* workaround ENGcm09152 for i.MX35 */ #define USBPHYCTRL_OTGBASE_OFFSET 0x608 #define USBPHYCTRL_EVDO (1 << 23) int fsl_udc_clk_init(struct platform_device *pdev) { struct fsl_usb2_platform_data *pdata; unsigned long freq; int ret; pdata = pdev->dev.platform_data; if (!cpu_is_mx35() && !cpu_is_mx25()) { mxc_ahb_clk = clk_get(&pdev->dev, "usb_ahb"); if (IS_ERR(mxc_ahb_clk)) return PTR_ERR(mxc_ahb_clk); ret = clk_enable(mxc_ahb_clk); if (ret < 0) { dev_err(&pdev->dev, "clk_enable(\"usb_ahb\") failed\n"); goto eenahb; } } /* make sure USB_CLK is running at 60 MHz +/- 1000 Hz */ mxc_usb_clk = clk_get(&pdev->dev, "usb"); if (IS_ERR(mxc_usb_clk)) { dev_err(&pdev->dev, "clk_get(\"usb\") failed\n"); ret = PTR_ERR(mxc_usb_clk); goto egusb; } if (!cpu_is_mx51()) { freq = clk_get_rate(mxc_usb_clk); if (pdata->phy_mode != FSL_USB2_PHY_ULPI && (freq < 59999000 || freq > 60001000)) { dev_err(&pdev->dev, "USB_CLK=%lu, should be 60MHz\n", freq); ret = -EINVAL; goto eclkrate; } } ret = clk_enable(mxc_usb_clk); if (ret < 0) { dev_err(&pdev->dev, "clk_enable(\"usb_clk\") failed\n"); goto eenusb; } return 0; eenusb: eclkrate: clk_put(mxc_usb_clk); mxc_usb_clk = NULL; egusb: if (!cpu_is_mx35()) clk_disable(mxc_ahb_clk); eenahb: if (!cpu_is_mx35()) clk_put(mxc_ahb_clk); return ret; } void fsl_udc_clk_finalize(struct platform_device *pdev) { struct fsl_usb2_platform_data *pdata = pdev->dev.platform_data; if (cpu_is_mx35()) { unsigned int v; /* workaround ENGcm09152 for i.MX35 */ if (pdata->workaround & FLS_USB2_WORKAROUND_ENGCM09152) { v = readl(MX35_IO_ADDRESS(MX35_USB_BASE_ADDR + USBPHYCTRL_OTGBASE_OFFSET)); writel(v | USBPHYCTRL_EVDO, MX35_IO_ADDRESS(MX35_USB_BASE_ADDR + USBPHYCTRL_OTGBASE_OFFSET)); } } /* ULPI transceivers don't need usbpll */ if (pdata->phy_mode == FSL_USB2_PHY_ULPI) { clk_disable(mxc_usb_clk); clk_put(mxc_usb_clk); mxc_usb_clk = NULL; } } void fsl_udc_clk_release(void) { if (mxc_usb_clk) { clk_disable(mxc_usb_clk); clk_put(mxc_usb_clk); } if (!cpu_is_mx35()) { clk_disable(mxc_ahb_clk); clk_put(mxc_ahb_clk); } }
gpl-2.0
GustavoRD78/78Kernel-Android-N-Developer-Preview-3
arch/arm/plat-s5p/setup-mipiphy.c
7899
1447
/* * Copyright (C) 2011 Samsung Electronics Co., Ltd. * * S5P - Helper functions for MIPI-CSIS and MIPI-DSIM D-PHY control * * 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/platform_device.h> #include <linux/io.h> #include <linux/spinlock.h> #include <mach/regs-clock.h> static int __s5p_mipi_phy_control(struct platform_device *pdev, bool on, u32 reset) { static DEFINE_SPINLOCK(lock); void __iomem *addr; unsigned long flags; int pid; u32 cfg; if (!pdev) return -EINVAL; pid = (pdev->id == -1) ? 0 : pdev->id; if (pid != 0 && pid != 1) return -EINVAL; addr = S5P_MIPI_DPHY_CONTROL(pid); spin_lock_irqsave(&lock, flags); cfg = __raw_readl(addr); cfg = on ? (cfg | reset) : (cfg & ~reset); __raw_writel(cfg, addr); if (on) { cfg |= S5P_MIPI_DPHY_ENABLE; } else if (!(cfg & (S5P_MIPI_DPHY_SRESETN | S5P_MIPI_DPHY_MRESETN) & ~reset)) { cfg &= ~S5P_MIPI_DPHY_ENABLE; } __raw_writel(cfg, addr); spin_unlock_irqrestore(&lock, flags); return 0; } int s5p_csis_phy_enable(struct platform_device *pdev, bool on) { return __s5p_mipi_phy_control(pdev, on, S5P_MIPI_DPHY_SRESETN); } int s5p_dsim_phy_enable(struct platform_device *pdev, bool on) { return __s5p_mipi_phy_control(pdev, on, S5P_MIPI_DPHY_MRESETN); }
gpl-2.0