diff options
Diffstat (limited to 'drivers/char/pcmcia')
-rw-r--r-- | drivers/char/pcmcia/Kconfig | 56 | ||||
-rw-r--r-- | drivers/char/pcmcia/Makefile | 11 | ||||
-rw-r--r-- | drivers/char/pcmcia/cm4000_cs.c | 1969 | ||||
-rw-r--r-- | drivers/char/pcmcia/cm4040_cs.c | 732 | ||||
-rw-r--r-- | drivers/char/pcmcia/cm4040_cs.h | 47 | ||||
-rw-r--r-- | drivers/char/pcmcia/ipwireless/Makefile | 10 | ||||
-rw-r--r-- | drivers/char/pcmcia/ipwireless/hardware.c | 1764 | ||||
-rw-r--r-- | drivers/char/pcmcia/ipwireless/hardware.h | 62 | ||||
-rw-r--r-- | drivers/char/pcmcia/ipwireless/main.c | 500 | ||||
-rw-r--r-- | drivers/char/pcmcia/ipwireless/main.h | 75 | ||||
-rw-r--r-- | drivers/char/pcmcia/ipwireless/network.c | 506 | ||||
-rw-r--r-- | drivers/char/pcmcia/ipwireless/network.h | 53 | ||||
-rw-r--r-- | drivers/char/pcmcia/ipwireless/setup_protocol.h | 108 | ||||
-rw-r--r-- | drivers/char/pcmcia/ipwireless/tty.c | 688 | ||||
-rw-r--r-- | drivers/char/pcmcia/ipwireless/tty.h | 48 | ||||
-rw-r--r-- | drivers/char/pcmcia/synclink_cs.c | 4498 |
16 files changed, 11127 insertions, 0 deletions
diff --git a/drivers/char/pcmcia/Kconfig b/drivers/char/pcmcia/Kconfig new file mode 100644 index 0000000..ffa0efc --- /dev/null +++ b/drivers/char/pcmcia/Kconfig @@ -0,0 +1,56 @@ +# +# PCMCIA character device configuration +# + +menu "PCMCIA character devices" + depends on HOTPLUG && PCMCIA!=n + +config SYNCLINK_CS + tristate "SyncLink PC Card support" + depends on PCMCIA + help + Enable support for the SyncLink PC Card serial adapter, running + asynchronous and HDLC communications up to 512Kbps. The port is + selectable for RS-232, V.35, RS-449, RS-530, and X.21 + + This driver may be built as a module ( = code which can be + inserted in and removed from the running kernel whenever you want). + The module will be called synclinkmp. If you want to do that, say M + here. + +config CARDMAN_4000 + tristate "Omnikey Cardman 4000 support" + depends on PCMCIA + select BITREVERSE + help + Enable support for the Omnikey Cardman 4000 PCMCIA Smartcard + reader. + + This kernel driver requires additional userspace support, either + by the vendor-provided PC/SC ifd_handler (http://www.omnikey.com/), + or via the cm4000 backend of OpenCT (http://www.opensc.com/). + +config CARDMAN_4040 + tristate "Omnikey CardMan 4040 support" + depends on PCMCIA + help + Enable support for the Omnikey CardMan 4040 PCMCIA Smartcard + reader. + + This card is basically a USB CCID device connected to a FIFO + in I/O space. To use the kernel driver, you will need either the + PC/SC ifdhandler provided from the Omnikey homepage + (http://www.omnikey.com/), or a current development version of OpenCT + (http://www.opensc.org/). + +config IPWIRELESS + tristate "IPWireless 3G UMTS PCMCIA card support" + depends on PCMCIA && NETDEVICES + select PPP + help + This is a driver for 3G UMTS PCMCIA card from IPWireless company. In + some countries (for example Czech Republic, T-Mobile ISP) this card + is shipped for service called UMTS 4G. + +endmenu + diff --git a/drivers/char/pcmcia/Makefile b/drivers/char/pcmcia/Makefile new file mode 100644 index 0000000..be8f287 --- /dev/null +++ b/drivers/char/pcmcia/Makefile @@ -0,0 +1,11 @@ +# +# drivers/char/pcmcia/Makefile +# +# Makefile for the Linux PCMCIA char device drivers. +# + +obj-y += ipwireless/ + +obj-$(CONFIG_SYNCLINK_CS) += synclink_cs.o +obj-$(CONFIG_CARDMAN_4000) += cm4000_cs.o +obj-$(CONFIG_CARDMAN_4040) += cm4040_cs.o diff --git a/drivers/char/pcmcia/cm4000_cs.c b/drivers/char/pcmcia/cm4000_cs.c new file mode 100644 index 0000000..dbb9125 --- /dev/null +++ b/drivers/char/pcmcia/cm4000_cs.c @@ -0,0 +1,1969 @@ + /* + * A driver for the PCMCIA Smartcard Reader "Omnikey CardMan Mobile 4000" + * + * cm4000_cs.c support.linux@omnikey.com + * + * Tue Oct 23 11:32:43 GMT 2001 herp - cleaned up header files + * Sun Jan 20 10:11:15 MET 2002 herp - added modversion header files + * Thu Nov 14 16:34:11 GMT 2002 mh - added PPS functionality + * Tue Nov 19 16:36:27 GMT 2002 mh - added SUSPEND/RESUME functionailty + * Wed Jul 28 12:55:01 CEST 2004 mh - kernel 2.6 adjustments + * + * current version: 2.4.0gm4 + * + * (C) 2000,2001,2002,2003,2004 Omnikey AG + * + * (C) 2005-2006 Harald Welte <laforge@gnumonks.org> + * - Adhere to Kernel CodingStyle + * - Port to 2.6.13 "new" style PCMCIA + * - Check for copy_{from,to}_user return values + * - Use nonseekable_open() + * - add class interface for udev device creation + * + * All rights reserved. Licensed under dual BSD/GPL license. + */ + +/* #define PCMCIA_DEBUG 6 */ + +#include <linux/kernel.h> +#include <linux/module.h> +#include <linux/slab.h> +#include <linux/init.h> +#include <linux/fs.h> +#include <linux/delay.h> +#include <linux/bitrev.h> +#include <linux/smp_lock.h> +#include <linux/uaccess.h> +#include <linux/io.h> + +#include <pcmcia/cs_types.h> +#include <pcmcia/cs.h> +#include <pcmcia/cistpl.h> +#include <pcmcia/cisreg.h> +#include <pcmcia/ciscode.h> +#include <pcmcia/ds.h> + +#include <linux/cm4000_cs.h> + +/* #define ATR_CSUM */ + +#ifdef PCMCIA_DEBUG +#define reader_to_dev(x) (&handle_to_dev(x->p_dev)) +static int pc_debug = PCMCIA_DEBUG; +module_param(pc_debug, int, 0600); +#define DEBUGP(n, rdr, x, args...) do { \ + if (pc_debug >= (n)) \ + dev_printk(KERN_DEBUG, reader_to_dev(rdr), "%s:" x, \ + __func__ , ## args); \ + } while (0) +#else +#define DEBUGP(n, rdr, x, args...) +#endif +static char *version = "cm4000_cs.c v2.4.0gm6 - All bugs added by Harald Welte"; + +#define T_1SEC (HZ) +#define T_10MSEC msecs_to_jiffies(10) +#define T_20MSEC msecs_to_jiffies(20) +#define T_40MSEC msecs_to_jiffies(40) +#define T_50MSEC msecs_to_jiffies(50) +#define T_100MSEC msecs_to_jiffies(100) +#define T_500MSEC msecs_to_jiffies(500) + +static void cm4000_release(struct pcmcia_device *link); + +static int major; /* major number we get from the kernel */ + +/* note: the first state has to have number 0 always */ + +#define M_FETCH_ATR 0 +#define M_TIMEOUT_WAIT 1 +#define M_READ_ATR_LEN 2 +#define M_READ_ATR 3 +#define M_ATR_PRESENT 4 +#define M_BAD_CARD 5 +#define M_CARDOFF 6 + +#define LOCK_IO 0 +#define LOCK_MONITOR 1 + +#define IS_AUTOPPS_ACT 6 +#define IS_PROCBYTE_PRESENT 7 +#define IS_INVREV 8 +#define IS_ANY_T0 9 +#define IS_ANY_T1 10 +#define IS_ATR_PRESENT 11 +#define IS_ATR_VALID 12 +#define IS_CMM_ABSENT 13 +#define IS_BAD_LENGTH 14 +#define IS_BAD_CSUM 15 +#define IS_BAD_CARD 16 + +#define REG_FLAGS0(x) (x + 0) +#define REG_FLAGS1(x) (x + 1) +#define REG_NUM_BYTES(x) (x + 2) +#define REG_BUF_ADDR(x) (x + 3) +#define REG_BUF_DATA(x) (x + 4) +#define REG_NUM_SEND(x) (x + 5) +#define REG_BAUDRATE(x) (x + 6) +#define REG_STOPBITS(x) (x + 7) + +struct cm4000_dev { + struct pcmcia_device *p_dev; + dev_node_t node; /* OS node (major,minor) */ + + unsigned char atr[MAX_ATR]; + unsigned char rbuf[512]; + unsigned char sbuf[512]; + + wait_queue_head_t devq; /* when removing cardman must not be + zeroed! */ + + wait_queue_head_t ioq; /* if IO is locked, wait on this Q */ + wait_queue_head_t atrq; /* wait for ATR valid */ + wait_queue_head_t readq; /* used by write to wake blk.read */ + + /* warning: do not move this fields. + * initialising to zero depends on it - see ZERO_DEV below. */ + unsigned char atr_csum; + unsigned char atr_len_retry; + unsigned short atr_len; + unsigned short rlen; /* bytes avail. after write */ + unsigned short rpos; /* latest read pos. write zeroes */ + unsigned char procbyte; /* T=0 procedure byte */ + unsigned char mstate; /* state of card monitor */ + unsigned char cwarn; /* slow down warning */ + unsigned char flags0; /* cardman IO-flags 0 */ + unsigned char flags1; /* cardman IO-flags 1 */ + unsigned int mdelay; /* variable monitor speeds, in jiffies */ + + unsigned int baudv; /* baud value for speed */ + unsigned char ta1; + unsigned char proto; /* T=0, T=1, ... */ + unsigned long flags; /* lock+flags (MONITOR,IO,ATR) * for concurrent + access */ + + unsigned char pts[4]; + + struct timer_list timer; /* used to keep monitor running */ + int monitor_running; +}; + +#define ZERO_DEV(dev) \ + memset(&dev->atr_csum,0, \ + sizeof(struct cm4000_dev) - \ + offsetof(struct cm4000_dev, atr_csum)) + +static struct pcmcia_device *dev_table[CM4000_MAX_DEV]; +static struct class *cmm_class; + +/* This table doesn't use spaces after the comma between fields and thus + * violates CodingStyle. However, I don't really think wrapping it around will + * make it any clearer to read -HW */ +static unsigned char fi_di_table[10][14] = { +/*FI 00 01 02 03 04 05 06 07 08 09 10 11 12 13 */ +/*DI */ +/* 0 */ {0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11}, +/* 1 */ {0x01,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x91,0x11,0x11,0x11,0x11}, +/* 2 */ {0x02,0x12,0x22,0x32,0x11,0x11,0x11,0x11,0x11,0x92,0xA2,0xB2,0x11,0x11}, +/* 3 */ {0x03,0x13,0x23,0x33,0x43,0x53,0x63,0x11,0x11,0x93,0xA3,0xB3,0xC3,0xD3}, +/* 4 */ {0x04,0x14,0x24,0x34,0x44,0x54,0x64,0x11,0x11,0x94,0xA4,0xB4,0xC4,0xD4}, +/* 5 */ {0x00,0x15,0x25,0x35,0x45,0x55,0x65,0x11,0x11,0x95,0xA5,0xB5,0xC5,0xD5}, +/* 6 */ {0x06,0x16,0x26,0x36,0x46,0x56,0x66,0x11,0x11,0x96,0xA6,0xB6,0xC6,0xD6}, +/* 7 */ {0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11}, +/* 8 */ {0x08,0x11,0x28,0x38,0x48,0x58,0x68,0x11,0x11,0x98,0xA8,0xB8,0xC8,0xD8}, +/* 9 */ {0x09,0x19,0x29,0x39,0x49,0x59,0x69,0x11,0x11,0x99,0xA9,0xB9,0xC9,0xD9} +}; + +#ifndef PCMCIA_DEBUG +#define xoutb outb +#define xinb inb +#else +static inline void xoutb(unsigned char val, unsigned short port) +{ + if (pc_debug >= 7) + printk(KERN_DEBUG "outb(val=%.2x,port=%.4x)\n", val, port); + outb(val, port); +} +static inline unsigned char xinb(unsigned short port) +{ + unsigned char val; + + val = inb(port); + if (pc_debug >= 7) + printk(KERN_DEBUG "%.2x=inb(%.4x)\n", val, port); + + return val; +} +#endif + +static inline unsigned char invert_revert(unsigned char ch) +{ + return bitrev8(~ch); +} + +static void str_invert_revert(unsigned char *b, int len) +{ + int i; + + for (i = 0; i < len; i++) + b[i] = invert_revert(b[i]); +} + +#define ATRLENCK(dev,pos) \ + if (pos>=dev->atr_len || pos>=MAX_ATR) \ + goto return_0; + +static unsigned int calc_baudv(unsigned char fidi) +{ + unsigned int wcrcf, wbrcf, fi_rfu, di_rfu; + + fi_rfu = 372; + di_rfu = 1; + + /* FI */ + switch ((fidi >> 4) & 0x0F) { + case 0x00: + wcrcf = 372; + break; + case 0x01: + wcrcf = 372; + break; + case 0x02: + wcrcf = 558; + break; + case 0x03: + wcrcf = 744; + break; + case 0x04: + wcrcf = 1116; + break; + case 0x05: + wcrcf = 1488; + break; + case 0x06: + wcrcf = 1860; + break; + case 0x07: + wcrcf = fi_rfu; + break; + case 0x08: + wcrcf = fi_rfu; + break; + case 0x09: + wcrcf = 512; + break; + case 0x0A: + wcrcf = 768; + break; + case 0x0B: + wcrcf = 1024; + break; + case 0x0C: + wcrcf = 1536; + break; + case 0x0D: + wcrcf = 2048; + break; + default: + wcrcf = fi_rfu; + break; + } + + /* DI */ + switch (fidi & 0x0F) { + case 0x00: + wbrcf = di_rfu; + break; + case 0x01: + wbrcf = 1; + break; + case 0x02: + wbrcf = 2; + break; + case 0x03: + wbrcf = 4; + break; + case 0x04: + wbrcf = 8; + break; + case 0x05: + wbrcf = 16; + break; + case 0x06: + wbrcf = 32; + break; + case 0x07: + wbrcf = di_rfu; + break; + case 0x08: + wbrcf = 12; + break; + case 0x09: + wbrcf = 20; + break; + default: + wbrcf = di_rfu; + break; + } + + return (wcrcf / wbrcf); +} + +static unsigned short io_read_num_rec_bytes(unsigned int iobase, + unsigned short *s) +{ + unsigned short tmp; + + tmp = *s = 0; + do { + *s = tmp; + tmp = inb(REG_NUM_BYTES(iobase)) | + (inb(REG_FLAGS0(iobase)) & 4 ? 0x100 : 0); + } while (tmp != *s); + + return *s; +} + +static int parse_atr(struct cm4000_dev *dev) +{ + unsigned char any_t1, any_t0; + unsigned char ch, ifno; + int ix, done; + + DEBUGP(3, dev, "-> parse_atr: dev->atr_len = %i\n", dev->atr_len); + + if (dev->atr_len < 3) { + DEBUGP(5, dev, "parse_atr: atr_len < 3\n"); + return 0; + } + + if (dev->atr[0] == 0x3f) + set_bit(IS_INVREV, &dev->flags); + else + clear_bit(IS_INVREV, &dev->flags); + ix = 1; + ifno = 1; + ch = dev->atr[1]; + dev->proto = 0; /* XXX PROTO */ + any_t1 = any_t0 = done = 0; + dev->ta1 = 0x11; /* defaults to 9600 baud */ + do { + if (ifno == 1 && (ch & 0x10)) { + /* read first interface byte and TA1 is present */ + dev->ta1 = dev->atr[2]; + DEBUGP(5, dev, "Card says FiDi is 0x%.2x\n", dev->ta1); + ifno++; + } else if ((ifno == 2) && (ch & 0x10)) { /* TA(2) */ + dev->ta1 = 0x11; + ifno++; + } + + DEBUGP(5, dev, "Yi=%.2x\n", ch & 0xf0); + ix += ((ch & 0x10) >> 4) /* no of int.face chars */ + +((ch & 0x20) >> 5) + + ((ch & 0x40) >> 6) + + ((ch & 0x80) >> 7); + /* ATRLENCK(dev,ix); */ + if (ch & 0x80) { /* TDi */ + ch = dev->atr[ix]; + if ((ch & 0x0f)) { + any_t1 = 1; + DEBUGP(5, dev, "card is capable of T=1\n"); + } else { + any_t0 = 1; + DEBUGP(5, dev, "card is capable of T=0\n"); + } + } else + done = 1; + } while (!done); + + DEBUGP(5, dev, "ix=%d noHist=%d any_t1=%d\n", + ix, dev->atr[1] & 15, any_t1); + if (ix + 1 + (dev->atr[1] & 0x0f) + any_t1 != dev->atr_len) { + DEBUGP(5, dev, "length error\n"); + return 0; + } + if (any_t0) + set_bit(IS_ANY_T0, &dev->flags); + + if (any_t1) { /* compute csum */ + dev->atr_csum = 0; +#ifdef ATR_CSUM + for (i = 1; i < dev->atr_len; i++) + dev->atr_csum ^= dev->atr[i]; + if (dev->atr_csum) { + set_bit(IS_BAD_CSUM, &dev->flags); + DEBUGP(5, dev, "bad checksum\n"); + goto return_0; + } +#endif + if (any_t0 == 0) + dev->proto = 1; /* XXX PROTO */ + set_bit(IS_ANY_T1, &dev->flags); + } + + return 1; +} + +struct card_fixup { + char atr[12]; + u_int8_t atr_len; + u_int8_t stopbits; +}; + +static struct card_fixup card_fixups[] = { + { /* ACOS */ + .atr = { 0x3b, 0xb3, 0x11, 0x00, 0x00, 0x41, 0x01 }, + .atr_len = 7, + .stopbits = 0x03, + }, + { /* Motorola */ + .atr = {0x3b, 0x76, 0x13, 0x00, 0x00, 0x80, 0x62, 0x07, + 0x41, 0x81, 0x81 }, + .atr_len = 11, + .stopbits = 0x04, + }, +}; + +static void set_cardparameter(struct cm4000_dev *dev) +{ + int i; + unsigned int iobase = dev->p_dev->io.BasePort1; + u_int8_t stopbits = 0x02; /* ISO default */ + + DEBUGP(3, dev, "-> set_cardparameter\n"); + + dev->flags1 = dev->flags1 | (((dev->baudv - 1) & 0x0100) >> 8); + xoutb(dev->flags1, REG_FLAGS1(iobase)); + DEBUGP(5, dev, "flags1 = 0x%02x\n", dev->flags1); + + /* set baudrate */ + xoutb((unsigned char)((dev->baudv - 1) & 0xFF), REG_BAUDRATE(iobase)); + + DEBUGP(5, dev, "baudv = %i -> write 0x%02x\n", dev->baudv, + ((dev->baudv - 1) & 0xFF)); + + /* set stopbits */ + for (i = 0; i < ARRAY_SIZE(card_fixups); i++) { + if (!memcmp(dev->atr, card_fixups[i].atr, + card_fixups[i].atr_len)) + stopbits = card_fixups[i].stopbits; + } + xoutb(stopbits, REG_STOPBITS(iobase)); + + DEBUGP(3, dev, "<- set_cardparameter\n"); +} + +static int set_protocol(struct cm4000_dev *dev, struct ptsreq *ptsreq) +{ + + unsigned long tmp, i; + unsigned short num_bytes_read; + unsigned char pts_reply[4]; + ssize_t rc; + unsigned int iobase = dev->p_dev->io.BasePort1; + + rc = 0; + + DEBUGP(3, dev, "-> set_protocol\n"); + DEBUGP(5, dev, "ptsreq->Protocol = 0x%.8x, ptsreq->Flags=0x%.8x, " + "ptsreq->pts1=0x%.2x, ptsreq->pts2=0x%.2x, " + "ptsreq->pts3=0x%.2x\n", (unsigned int)ptsreq->protocol, + (unsigned int)ptsreq->flags, ptsreq->pts1, ptsreq->pts2, + ptsreq->pts3); + + /* Fill PTS structure */ + dev->pts[0] = 0xff; + dev->pts[1] = 0x00; + tmp = ptsreq->protocol; + while ((tmp = (tmp >> 1)) > 0) + dev->pts[1]++; + dev->proto = dev->pts[1]; /* Set new protocol */ + dev->pts[1] = (0x01 << 4) | (dev->pts[1]); + + /* Correct Fi/Di according to CM4000 Fi/Di table */ + DEBUGP(5, dev, "Ta(1) from ATR is 0x%.2x\n", dev->ta1); + /* set Fi/Di according to ATR TA(1) */ + dev->pts[2] = fi_di_table[dev->ta1 & 0x0F][(dev->ta1 >> 4) & 0x0F]; + + /* Calculate PCK character */ + dev->pts[3] = dev->pts[0] ^ dev->pts[1] ^ dev->pts[2]; + + DEBUGP(5, dev, "pts0=%.2x, pts1=%.2x, pts2=%.2x, pts3=%.2x\n", + dev->pts[0], dev->pts[1], dev->pts[2], dev->pts[3]); + + /* check card convention */ + if (test_bit(IS_INVREV, &dev->flags)) + str_invert_revert(dev->pts, 4); + + /* reset SM */ + xoutb(0x80, REG_FLAGS0(iobase)); + + /* Enable access to the message buffer */ + DEBUGP(5, dev, "Enable access to the messages buffer\n"); + dev->flags1 = 0x20 /* T_Active */ + | (test_bit(IS_INVREV, &dev->flags) ? 0x02 : 0x00) /* inv parity */ + | ((dev->baudv >> 8) & 0x01); /* MSB-baud */ + xoutb(dev->flags1, REG_FLAGS1(iobase)); + + DEBUGP(5, dev, "Enable message buffer -> flags1 = 0x%.2x\n", + dev->flags1); + + /* write challenge to the buffer */ + DEBUGP(5, dev, "Write challenge to buffer: "); + for (i = 0; i < 4; i++) { + xoutb(i, REG_BUF_ADDR(iobase)); + xoutb(dev->pts[i], REG_BUF_DATA(iobase)); /* buf data */ +#ifdef PCMCIA_DEBUG + if (pc_debug >= 5) + printk("0x%.2x ", dev->pts[i]); + } + if (pc_debug >= 5) + printk("\n"); +#else + } +#endif + + /* set number of bytes to write */ + DEBUGP(5, dev, "Set number of bytes to write\n"); + xoutb(0x04, REG_NUM_SEND(iobase)); + + /* Trigger CARDMAN CONTROLLER */ + xoutb(0x50, REG_FLAGS0(iobase)); + + /* Monitor progress */ + /* wait for xmit done */ + DEBUGP(5, dev, "Waiting for NumRecBytes getting valid\n"); + + for (i = 0; i < 100; i++) { + if (inb(REG_FLAGS0(iobase)) & 0x08) { + DEBUGP(5, dev, "NumRecBytes is valid\n"); + break; + } + mdelay(10); + } + if (i == 100) { + DEBUGP(5, dev, "Timeout waiting for NumRecBytes getting " + "valid\n"); + rc = -EIO; + goto exit_setprotocol; + } + + DEBUGP(5, dev, "Reading NumRecBytes\n"); + for (i = 0; i < 100; i++) { + io_read_num_rec_bytes(iobase, &num_bytes_read); + if (num_bytes_read >= 4) { + DEBUGP(2, dev, "NumRecBytes = %i\n", num_bytes_read); + break; + } + mdelay(10); + } + + /* check whether it is a short PTS reply? */ + if (num_bytes_read == 3) + i = 0; + + if (i == 100) { + DEBUGP(5, dev, "Timeout reading num_bytes_read\n"); + rc = -EIO; + goto exit_setprotocol; + } + + DEBUGP(5, dev, "Reset the CARDMAN CONTROLLER\n"); + xoutb(0x80, REG_FLAGS0(iobase)); + + /* Read PPS reply */ + DEBUGP(5, dev, "Read PPS reply\n"); + for (i = 0; i < num_bytes_read; i++) { + xoutb(i, REG_BUF_ADDR(iobase)); + pts_reply[i] = inb(REG_BUF_DATA(iobase)); + } + +#ifdef PCMCIA_DEBUG + DEBUGP(2, dev, "PTSreply: "); + for (i = 0; i < num_bytes_read; i++) { + if (pc_debug >= 5) + printk("0x%.2x ", pts_reply[i]); + } + printk("\n"); +#endif /* PCMCIA_DEBUG */ + + DEBUGP(5, dev, "Clear Tactive in Flags1\n"); + xoutb(0x20, REG_FLAGS1(iobase)); + + /* Compare ptsreq and ptsreply */ + if ((dev->pts[0] == pts_reply[0]) && + (dev->pts[1] == pts_reply[1]) && + (dev->pts[2] == pts_reply[2]) && (dev->pts[3] == pts_reply[3])) { + /* setcardparameter according to PPS */ + dev->baudv = calc_baudv(dev->pts[2]); + set_cardparameter(dev); + } else if ((dev->pts[0] == pts_reply[0]) && + ((dev->pts[1] & 0xef) == pts_reply[1]) && + ((pts_reply[0] ^ pts_reply[1]) == pts_reply[2])) { + /* short PTS reply, set card parameter to default values */ + dev->baudv = calc_baudv(0x11); + set_cardparameter(dev); + } else + rc = -EIO; + +exit_setprotocol: + DEBUGP(3, dev, "<- set_protocol\n"); + return rc; +} + +static int io_detect_cm4000(unsigned int iobase, struct cm4000_dev *dev) +{ + + /* note: statemachine is assumed to be reset */ + if (inb(REG_FLAGS0(iobase)) & 8) { + clear_bit(IS_ATR_VALID, &dev->flags); + set_bit(IS_CMM_ABSENT, &dev->flags); + return 0; /* detect CMM = 1 -> failure */ + } + /* xoutb(0x40, REG_FLAGS1(iobase)); detectCMM */ + xoutb(dev->flags1 | 0x40, REG_FLAGS1(iobase)); + if ((inb(REG_FLAGS0(iobase)) & 8) == 0) { + clear_bit(IS_ATR_VALID, &dev->flags); + set_bit(IS_CMM_ABSENT, &dev->flags); + return 0; /* detect CMM=0 -> failure */ + } + /* clear detectCMM again by restoring original flags1 */ + xoutb(dev->flags1, REG_FLAGS1(iobase)); + return 1; +} + +static void terminate_monitor(struct cm4000_dev *dev) +{ + + /* tell the monitor to stop and wait until + * it terminates. + */ + DEBUGP(3, dev, "-> terminate_monitor\n"); + wait_event_interruptible(dev->devq, + test_and_set_bit(LOCK_MONITOR, + (void *)&dev->flags)); + + /* now, LOCK_MONITOR has been set. + * allow a last cycle in the monitor. + * the monitor will indicate that it has + * finished by clearing this bit. + */ + DEBUGP(5, dev, "Now allow last cycle of monitor!\n"); + while (test_bit(LOCK_MONITOR, (void *)&dev->flags)) + msleep(25); + + DEBUGP(5, dev, "Delete timer\n"); + del_timer_sync(&dev->timer); +#ifdef PCMCIA_DEBUG + dev->monitor_running = 0; +#endif + + DEBUGP(3, dev, "<- terminate_monitor\n"); +} + +/* + * monitor the card every 50msec. as a side-effect, retrieve the + * atr once a card is inserted. another side-effect of retrieving the + * atr is that the card will be powered on, so there is no need to + * power on the card explictely from the application: the driver + * is already doing that for you. + */ + +static void monitor_card(unsigned long p) +{ + struct cm4000_dev *dev = (struct cm4000_dev *) p; + unsigned int iobase = dev->p_dev->io.BasePort1; + unsigned short s; + struct ptsreq ptsreq; + int i, atrc; + + DEBUGP(7, dev, "-> monitor_card\n"); + + /* if someone has set the lock for us: we're done! */ + if (test_and_set_bit(LOCK_MONITOR, &dev->flags)) { + DEBUGP(4, dev, "About to stop monitor\n"); + /* no */ + dev->rlen = + dev->rpos = + dev->atr_csum = dev->atr_len_retry = dev->cwarn = 0; + dev->mstate = M_FETCH_ATR; + clear_bit(LOCK_MONITOR, &dev->flags); + /* close et al. are sleeping on devq, so wake it */ + wake_up_interruptible(&dev->devq); + DEBUGP(2, dev, "<- monitor_card (we are done now)\n"); + return; + } + + /* try to lock io: if it is already locked, just add another timer */ + if (test_and_set_bit(LOCK_IO, (void *)&dev->flags)) { + DEBUGP(4, dev, "Couldn't get IO lock\n"); + goto return_with_timer; + } + + /* is a card/a reader inserted at all ? */ + dev->flags0 = xinb(REG_FLAGS0(iobase)); + DEBUGP(7, dev, "dev->flags0 = 0x%2x\n", dev->flags0); + DEBUGP(7, dev, "smartcard present: %s\n", + dev->flags0 & 1 ? "yes" : "no"); + DEBUGP(7, dev, "cardman present: %s\n", + dev->flags0 == 0xff ? "no" : "yes"); + + if ((dev->flags0 & 1) == 0 /* no smartcard inserted */ + || dev->flags0 == 0xff) { /* no cardman inserted */ + /* no */ + dev->rlen = + dev->rpos = + dev->atr_csum = dev->atr_len_retry = dev->cwarn = 0; + dev->mstate = M_FETCH_ATR; + + dev->flags &= 0x000000ff; /* only keep IO and MONITOR locks */ + + if (dev->flags0 == 0xff) { + DEBUGP(4, dev, "set IS_CMM_ABSENT bit\n"); + set_bit(IS_CMM_ABSENT, &dev->flags); + } else if (test_bit(IS_CMM_ABSENT, &dev->flags)) { + DEBUGP(4, dev, "clear IS_CMM_ABSENT bit " + "(card is removed)\n"); + clear_bit(IS_CMM_ABSENT, &dev->flags); + } + + goto release_io; + } else if ((dev->flags0 & 1) && test_bit(IS_CMM_ABSENT, &dev->flags)) { + /* cardman and card present but cardman was absent before + * (after suspend with inserted card) */ + DEBUGP(4, dev, "clear IS_CMM_ABSENT bit (card is inserted)\n"); + clear_bit(IS_CMM_ABSENT, &dev->flags); + } + + if (test_bit(IS_ATR_VALID, &dev->flags) == 1) { + DEBUGP(7, dev, "believe ATR is already valid (do nothing)\n"); + goto release_io; + } + + switch (dev->mstate) { + unsigned char flags0; + case M_CARDOFF: + DEBUGP(4, dev, "M_CARDOFF\n"); + flags0 = inb(REG_FLAGS0(iobase)); + if (flags0 & 0x02) { + /* wait until Flags0 indicate power is off */ + dev->mdelay = T_10MSEC; + } else { + /* Flags0 indicate power off and no card inserted now; + * Reset CARDMAN CONTROLLER */ + xoutb(0x80, REG_FLAGS0(iobase)); + + /* prepare for fetching ATR again: after card off ATR + * is read again automatically */ + dev->rlen = + dev->rpos = + dev->atr_csum = + dev->atr_len_retry = dev->cwarn = 0; + dev->mstate = M_FETCH_ATR; + + /* minimal gap between CARDOFF and read ATR is 50msec */ + dev->mdelay = T_50MSEC; + } + break; + case M_FETCH_ATR: + DEBUGP(4, dev, "M_FETCH_ATR\n"); + xoutb(0x80, REG_FLAGS0(iobase)); + DEBUGP(4, dev, "Reset BAUDV to 9600\n"); + dev->baudv = 0x173; /* 9600 */ + xoutb(0x02, REG_STOPBITS(iobase)); /* stopbits=2 */ + xoutb(0x73, REG_BAUDRATE(iobase)); /* baud value */ + xoutb(0x21, REG_FLAGS1(iobase)); /* T_Active=1, baud + value */ + /* warm start vs. power on: */ + xoutb(dev->flags0 & 2 ? 0x46 : 0x44, REG_FLAGS0(iobase)); + dev->mdelay = T_40MSEC; + dev->mstate = M_TIMEOUT_WAIT; + break; + case M_TIMEOUT_WAIT: + DEBUGP(4, dev, "M_TIMEOUT_WAIT\n"); + /* numRecBytes */ + io_read_num_rec_bytes(iobase, &dev->atr_len); + dev->mdelay = T_10MSEC; + dev->mstate = M_READ_ATR_LEN; + break; + case M_READ_ATR_LEN: + DEBUGP(4, dev, "M_READ_ATR_LEN\n"); + /* infinite loop possible, since there is no timeout */ + +#define MAX_ATR_LEN_RETRY 100 + + if (dev->atr_len == io_read_num_rec_bytes(iobase, &s)) { + if (dev->atr_len_retry++ >= MAX_ATR_LEN_RETRY) { /* + XX msec */ + dev->mdelay = T_10MSEC; + dev->mstate = M_READ_ATR; + } + } else { + dev->atr_len = s; + dev->atr_len_retry = 0; /* set new timeout */ + } + + DEBUGP(4, dev, "Current ATR_LEN = %i\n", dev->atr_len); + break; + case M_READ_ATR: + DEBUGP(4, dev, "M_READ_ATR\n"); + xoutb(0x80, REG_FLAGS0(iobase)); /* reset SM */ + for (i = 0; i < dev->atr_len; i++) { + xoutb(i, REG_BUF_ADDR(iobase)); + dev->atr[i] = inb(REG_BUF_DATA(iobase)); + } + /* Deactivate T_Active flags */ + DEBUGP(4, dev, "Deactivate T_Active flags\n"); + dev->flags1 = 0x01; + xoutb(dev->flags1, REG_FLAGS1(iobase)); + + /* atr is present (which doesnt mean it's valid) */ + set_bit(IS_ATR_PRESENT, &dev->flags); + if (dev->atr[0] == 0x03) + str_invert_revert(dev->atr, dev->atr_len); + atrc = parse_atr(dev); + if (atrc == 0) { /* atr invalid */ + dev->mdelay = 0; + dev->mstate = M_BAD_CARD; + } else { + dev->mdelay = T_50MSEC; + dev->mstate = M_ATR_PRESENT; + set_bit(IS_ATR_VALID, &dev->flags); + } + + if (test_bit(IS_ATR_VALID, &dev->flags) == 1) { + DEBUGP(4, dev, "monitor_card: ATR valid\n"); + /* if ta1 == 0x11, no PPS necessary (default values) */ + /* do not do PPS with multi protocol cards */ + if ((test_bit(IS_AUTOPPS_ACT, &dev->flags) == 0) && + (dev->ta1 != 0x11) && + !(test_bit(IS_ANY_T0, &dev->flags) && + test_bit(IS_ANY_T1, &dev->flags))) { + DEBUGP(4, dev, "Perform AUTOPPS\n"); + set_bit(IS_AUTOPPS_ACT, &dev->flags); + ptsreq.protocol = ptsreq.protocol = + (0x01 << dev->proto); + ptsreq.flags = 0x01; + ptsreq.pts1 = 0x00; + ptsreq.pts2 = 0x00; + ptsreq.pts3 = 0x00; + if (set_protocol(dev, &ptsreq) == 0) { + DEBUGP(4, dev, "AUTOPPS ret SUCC\n"); + clear_bit(IS_AUTOPPS_ACT, &dev->flags); + wake_up_interruptible(&dev->atrq); + } else { + DEBUGP(4, dev, "AUTOPPS failed: " + "repower using defaults\n"); + /* prepare for repowering */ + clear_bit(IS_ATR_PRESENT, &dev->flags); + clear_bit(IS_ATR_VALID, &dev->flags); + dev->rlen = + dev->rpos = + dev->atr_csum = + dev->atr_len_retry = dev->cwarn = 0; + dev->mstate = M_FETCH_ATR; + + dev->mdelay = T_50MSEC; + } + } else { + /* for cards which use slightly different + * params (extra guard time) */ + set_cardparameter(dev); + if (test_bit(IS_AUTOPPS_ACT, &dev->flags) == 1) + DEBUGP(4, dev, "AUTOPPS already active " + "2nd try:use default values\n"); + if (dev->ta1 == 0x11) + DEBUGP(4, dev, "No AUTOPPS necessary " + "TA(1)==0x11\n"); + if (test_bit(IS_ANY_T0, &dev->flags) + && test_bit(IS_ANY_T1, &dev->flags)) + DEBUGP(4, dev, "Do NOT perform AUTOPPS " + "with multiprotocol cards\n"); + clear_bit(IS_AUTOPPS_ACT, &dev->flags); + wake_up_interruptible(&dev->atrq); + } + } else { + DEBUGP(4, dev, "ATR invalid\n"); + wake_up_interruptible(&dev->atrq); + } + break; + case M_BAD_CARD: + DEBUGP(4, dev, "M_BAD_CARD\n"); + /* slow down warning, but prompt immediately after insertion */ + if (dev->cwarn == 0 || dev->cwarn == 10) { + set_bit(IS_BAD_CARD, &dev->flags); + printk(KERN_WARNING MODULE_NAME ": device %s: ", + dev->node.dev_name); + if (test_bit(IS_BAD_CSUM, &dev->flags)) { + DEBUGP(4, dev, "ATR checksum (0x%.2x, should " + "be zero) failed\n", dev->atr_csum); + } +#ifdef PCMCIA_DEBUG + else if (test_bit(IS_BAD_LENGTH, &dev->flags)) { + DEBUGP(4, dev, "ATR length error\n"); + } else { + DEBUGP(4, dev, "card damaged or wrong way " + "inserted\n"); + } +#endif + dev->cwarn = 0; + wake_up_interruptible(&dev->atrq); /* wake open */ + } + dev->cwarn++; + dev->mdelay = T_100MSEC; + dev->mstate = M_FETCH_ATR; + break; + default: + DEBUGP(7, dev, "Unknown action\n"); + break; /* nothing */ + } + +release_io: + DEBUGP(7, dev, "release_io\n"); + clear_bit(LOCK_IO, &dev->flags); + wake_up_interruptible(&dev->ioq); /* whoever needs IO */ + +return_with_timer: + DEBUGP(7, dev, "<- monitor_card (returns with timer)\n"); + mod_timer(&dev->timer, jiffies + dev->mdelay); + clear_bit(LOCK_MONITOR, &dev->flags); +} + +/* Interface to userland (file_operations) */ + +static ssize_t cmm_read(struct file *filp, __user char *buf, size_t count, + loff_t *ppos) +{ + struct cm4000_dev *dev = filp->private_data; + unsigned int iobase = dev->p_dev->io.BasePort1; + ssize_t rc; + int i, j, k; + + DEBUGP(2, dev, "-> cmm_read(%s,%d)\n", current->comm, current->pid); + + if (count == 0) /* according to manpage */ + return 0; + + if (!pcmcia_dev_present(dev->p_dev) || /* device removed */ + test_bit(IS_CMM_ABSENT, &dev->flags)) + return -ENODEV; + + if (test_bit(IS_BAD_CSUM, &dev->flags)) + return -EIO; + + /* also see the note about this in cmm_write */ + if (wait_event_interruptible + (dev->atrq, + ((filp->f_flags & O_NONBLOCK) + || (test_bit(IS_ATR_PRESENT, (void *)&dev->flags) != 0)))) { + if (filp->f_flags & O_NONBLOCK) + return -EAGAIN; + return -ERESTARTSYS; + } + + if (test_bit(IS_ATR_VALID, &dev->flags) == 0) + return -EIO; + + /* this one implements blocking IO */ + if (wait_event_interruptible + (dev->readq, + ((filp->f_flags & O_NONBLOCK) || (dev->rpos < dev->rlen)))) { + if (filp->f_flags & O_NONBLOCK) + return -EAGAIN; + return -ERESTARTSYS; + } + + /* lock io */ + if (wait_event_interruptible + (dev->ioq, + ((filp->f_flags & O_NONBLOCK) + || (test_and_set_bit(LOCK_IO, (void *)&dev->flags) == 0)))) { + if (filp->f_flags & O_NONBLOCK) + return -EAGAIN; + return -ERESTARTSYS; + } + + rc = 0; + dev->flags0 = inb(REG_FLAGS0(iobase)); + if ((dev->flags0 & 1) == 0 /* no smartcard inserted */ + || dev->flags0 == 0xff) { /* no cardman inserted */ + clear_bit(IS_ATR_VALID, &dev->flags); + if (dev->flags0 & 1) { + set_bit(IS_CMM_ABSENT, &dev->flags); + rc = -ENODEV; + } + rc = -EIO; + goto release_io; + } + + DEBUGP(4, dev, "begin read answer\n"); + j = min(count, (size_t)(dev->rlen - dev->rpos)); + k = dev->rpos; + if (k + j > 255) + j = 256 - k; + DEBUGP(4, dev, "read1 j=%d\n", j); + for (i = 0; i < j; i++) { + xoutb(k++, REG_BUF_ADDR(iobase)); + dev->rbuf[i] = xinb(REG_BUF_DATA(iobase)); + } + j = min(count, (size_t)(dev->rlen - dev->rpos)); + if (k + j > 255) { + DEBUGP(4, dev, "read2 j=%d\n", j); + dev->flags1 |= 0x10; /* MSB buf addr set */ + xoutb(dev->flags1, REG_FLAGS1(iobase)); + for (; i < j; i++) { + xoutb(k++, REG_BUF_ADDR(iobase)); + dev->rbuf[i] = xinb(REG_BUF_DATA(iobase)); + } + } + + if (dev->proto == 0 && count > dev->rlen - dev->rpos) { + DEBUGP(4, dev, "T=0 and count > buffer\n"); + dev->rbuf[i] = dev->rbuf[i - 1]; + dev->rbuf[i - 1] = dev->procbyte; + j++; + } + count = j; + + dev->rpos = dev->rlen + 1; + + /* Clear T1Active */ + DEBUGP(4, dev, "Clear T1Active\n"); + dev->flags1 &= 0xdf; + xoutb(dev->flags1, REG_FLAGS1(iobase)); + + xoutb(0, REG_FLAGS1(iobase)); /* clear detectCMM */ + /* last check before exit */ + if (!io_detect_cm4000(iobase, dev)) + count = -ENODEV; + + if (test_bit(IS_INVREV, &dev->flags) && count > 0) + str_invert_revert(dev->rbuf, count); + + if (copy_to_user(buf, dev->rbuf, count)) + return -EFAULT; + +release_io: + clear_bit(LOCK_IO, &dev->flags); + wake_up_interruptible(&dev->ioq); + + DEBUGP(2, dev, "<- cmm_read returns: rc = %Zi\n", + (rc < 0 ? rc : count)); + return rc < 0 ? rc : count; +} + +static ssize_t cmm_write(struct file *filp, const char __user *buf, + size_t count, loff_t *ppos) +{ + struct cm4000_dev *dev = (struct cm4000_dev *) filp->private_data; + unsigned int iobase = dev->p_dev->io.BasePort1; + unsigned short s; + unsigned char tmp; + unsigned char infolen; + unsigned char sendT0; + unsigned short nsend; + unsigned short nr; + ssize_t rc; + int i; + + DEBUGP(2, dev, "-> cmm_write(%s,%d)\n", current->comm, current->pid); + + if (count == 0) /* according to manpage */ + return 0; + + if (dev->proto == 0 && count < 4) { + /* T0 must have at least 4 bytes */ + DEBUGP(4, dev, "T0 short write\n"); + return -EIO; + } + + nr = count & 0x1ff; /* max bytes to write */ + + sendT0 = dev->proto ? 0 : nr > 5 ? 0x08 : 0; + + if (!pcmcia_dev_present(dev->p_dev) || /* device removed */ + test_bit(IS_CMM_ABSENT, &dev->flags)) + return -ENODEV; + + if (test_bit(IS_BAD_CSUM, &dev->flags)) { + DEBUGP(4, dev, "bad csum\n"); + return -EIO; + } + + /* + * wait for atr to become valid. + * note: it is important to lock this code. if we dont, the monitor + * could be run between test_bit and the call to sleep on the + * atr-queue. if *then* the monitor detects atr valid, it will wake up + * any process on the atr-queue, *but* since we have been interrupted, + * we do not yet sleep on this queue. this would result in a missed + * wake_up and the calling process would sleep forever (until + * interrupted). also, do *not* restore_flags before sleep_on, because + * this could result in the same situation! + */ + if (wait_event_interruptible + (dev->atrq, + ((filp->f_flags & O_NONBLOCK) + || (test_bit(IS_ATR_PRESENT, (void *)&dev->flags) != 0)))) { + if (filp->f_flags & O_NONBLOCK) + return -EAGAIN; + return -ERESTARTSYS; + } + + if (test_bit(IS_ATR_VALID, &dev->flags) == 0) { /* invalid atr */ + DEBUGP(4, dev, "invalid ATR\n"); + return -EIO; + } + + /* lock io */ + if (wait_event_interruptible + (dev->ioq, + ((filp->f_flags & O_NONBLOCK) + || (test_and_set_bit(LOCK_IO, (void *)&dev->flags) == 0)))) { + if (filp->f_flags & O_NONBLOCK) + return -EAGAIN; + return -ERESTARTSYS; + } + + if (copy_from_user(dev->sbuf, buf, ((count > 512) ? 512 : count))) + return -EFAULT; + + rc = 0; + dev->flags0 = inb(REG_FLAGS0(iobase)); + if ((dev->flags0 & 1) == 0 /* no smartcard inserted */ + || dev->flags0 == 0xff) { /* no cardman inserted */ + clear_bit(IS_ATR_VALID, &dev->flags); + if (dev->flags0 & 1) { + set_bit(IS_CMM_ABSENT, &dev->flags); + rc = -ENODEV; + } else { + DEBUGP(4, dev, "IO error\n"); + rc = -EIO; + } + goto release_io; + } + + xoutb(0x80, REG_FLAGS0(iobase)); /* reset SM */ + + if (!io_detect_cm4000(iobase, dev)) { + rc = -ENODEV; + goto release_io; + } + + /* reflect T=0 send/read mode in flags1 */ + dev->flags1 |= (sendT0); + + set_cardparameter(dev); + + /* dummy read, reset flag procedure received */ + tmp = inb(REG_FLAGS1(iobase)); + + dev->flags1 = 0x20 /* T_Active */ + | (sendT0) + | (test_bit(IS_INVREV, &dev->flags) ? 2 : 0)/* inverse parity */ + | (((dev->baudv - 1) & 0x0100) >> 8); /* MSB-Baud */ + DEBUGP(1, dev, "set dev->flags1 = 0x%.2x\n", dev->flags1); + xoutb(dev->flags1, REG_FLAGS1(iobase)); + + /* xmit data */ + DEBUGP(4, dev, "Xmit data\n"); + for (i = 0; i < nr; i++) { + if (i >= 256) { + dev->flags1 = 0x20 /* T_Active */ + | (sendT0) /* SendT0 */ + /* inverse parity: */ + | (test_bit(IS_INVREV, &dev->flags) ? 2 : 0) + | (((dev->baudv - 1) & 0x0100) >> 8) /* MSB-Baud */ + | 0x10; /* set address high */ + DEBUGP(4, dev, "dev->flags = 0x%.2x - set address " + "high\n", dev->flags1); + xoutb(dev->flags1, REG_FLAGS1(iobase)); + } + if (test_bit(IS_INVREV, &dev->flags)) { + DEBUGP(4, dev, "Apply inverse convention for 0x%.2x " + "-> 0x%.2x\n", (unsigned char)dev->sbuf[i], + invert_revert(dev->sbuf[i])); + xoutb(i, REG_BUF_ADDR(iobase)); + xoutb(invert_revert(dev->sbuf[i]), + REG_BUF_DATA(iobase)); + } else { + xoutb(i, REG_BUF_ADDR(iobase)); + xoutb(dev->sbuf[i], REG_BUF_DATA(iobase)); + } + } + DEBUGP(4, dev, "Xmit done\n"); + + if (dev->proto == 0) { + /* T=0 proto: 0 byte reply */ + if (nr == 4) { + DEBUGP(4, dev, "T=0 assumes 0 byte reply\n"); + xoutb(i, REG_BUF_ADDR(iobase)); + if (test_bit(IS_INVREV, &dev->flags)) + xoutb(0xff, REG_BUF_DATA(iobase)); + else + xoutb(0x00, REG_BUF_DATA(iobase)); + } + + /* numSendBytes */ + if (sendT0) + nsend = nr; + else { + if (nr == 4) + nsend = 5; + else { + nsend = 5 + (unsigned char)dev->sbuf[4]; + if (dev->sbuf[4] == 0) + nsend += 0x100; + } + } + } else + nsend = nr; + + /* T0: output procedure byte */ + if (test_bit(IS_INVREV, &dev->flags)) { + DEBUGP(4, dev, "T=0 set Procedure byte (inverse-reverse) " + "0x%.2x\n", invert_revert(dev->sbuf[1])); + xoutb(invert_revert(dev->sbuf[1]), REG_NUM_BYTES(iobase)); + } else { + DEBUGP(4, dev, "T=0 set Procedure byte 0x%.2x\n", dev->sbuf[1]); + xoutb(dev->sbuf[1], REG_NUM_BYTES(iobase)); + } + + DEBUGP(1, dev, "set NumSendBytes = 0x%.2x\n", + (unsigned char)(nsend & 0xff)); + xoutb((unsigned char)(nsend & 0xff), REG_NUM_SEND(iobase)); + + DEBUGP(1, dev, "Trigger CARDMAN CONTROLLER (0x%.2x)\n", + 0x40 /* SM_Active */ + | (dev->flags0 & 2 ? 0 : 4) /* power on if needed */ + |(dev->proto ? 0x10 : 0x08) /* T=1/T=0 */ + |(nsend & 0x100) >> 8 /* MSB numSendBytes */ ); + xoutb(0x40 /* SM_Active */ + | (dev->flags0 & 2 ? 0 : 4) /* power on if needed */ + |(dev->proto ? 0x10 : 0x08) /* T=1/T=0 */ + |(nsend & 0x100) >> 8, /* MSB numSendBytes */ + REG_FLAGS0(iobase)); + + /* wait for xmit done */ + if (dev->proto == 1) { + DEBUGP(4, dev, "Wait for xmit done\n"); + for (i = 0; i < 1000; i++) { + if (inb(REG_FLAGS0(iobase)) & 0x08) + break; + msleep_interruptible(10); + } + if (i == 1000) { + DEBUGP(4, dev, "timeout waiting for xmit done\n"); + rc = -EIO; + goto release_io; + } + } + + /* T=1: wait for infoLen */ + + infolen = 0; + if (dev->proto) { + /* wait until infoLen is valid */ + for (i = 0; i < 6000; i++) { /* max waiting time of 1 min */ + io_read_num_rec_bytes(iobase, &s); + if (s >= 3) { + infolen = inb(REG_FLAGS1(iobase)); + DEBUGP(4, dev, "infolen=%d\n", infolen); + break; + } + msleep_interruptible(10); + } + if (i == 6000) { + DEBUGP(4, dev, "timeout waiting for infoLen\n"); + rc = -EIO; + goto release_io; + } + } else + clear_bit(IS_PROCBYTE_PRESENT, &dev->flags); + + /* numRecBytes | bit9 of numRecytes */ + io_read_num_rec_bytes(iobase, &dev->rlen); + for (i = 0; i < 600; i++) { /* max waiting time of 2 sec */ + if (dev->proto) { + if (dev->rlen >= infolen + 4) + break; + } + msleep_interruptible(10); + /* numRecBytes | bit9 of numRecytes */ + io_read_num_rec_bytes(iobase, &s); + if (s > dev->rlen) { + DEBUGP(1, dev, "NumRecBytes inc (reset timeout)\n"); + i = 0; /* reset timeout */ + dev->rlen = s; + } + /* T=0: we are done when numRecBytes doesn't + * increment any more and NoProcedureByte + * is set and numRecBytes == bytes sent + 6 + * (header bytes + data + 1 for sw2) + * except when the card replies an error + * which means, no data will be sent back. + */ + else if (dev->proto == 0) { + if ((inb(REG_BUF_ADDR(iobase)) & 0x80)) { + /* no procedure byte received since last read */ + DEBUGP(1, dev, "NoProcedure byte set\n"); + /* i=0; */ + } else { + /* procedure byte received since last read */ + DEBUGP(1, dev, "NoProcedure byte unset " + "(reset timeout)\n"); + dev->procbyte = inb(REG_FLAGS1(iobase)); + DEBUGP(1, dev, "Read procedure byte 0x%.2x\n", + dev->procbyte); + i = 0; /* resettimeout */ + } + if (inb(REG_FLAGS0(iobase)) & 0x08) { + DEBUGP(1, dev, "T0Done flag (read reply)\n"); + break; + } + } + if (dev->proto) + infolen = inb(REG_FLAGS1(iobase)); + } + if (i == 600) { + DEBUGP(1, dev, "timeout waiting for numRecBytes\n"); + rc = -EIO; + goto release_io; + } else { + if (dev->proto == 0) { + DEBUGP(1, dev, "Wait for T0Done bit to be set\n"); + for (i = 0; i < 1000; i++) { + if (inb(REG_FLAGS0(iobase)) & 0x08) + break; + msleep_interruptible(10); + } + if (i == 1000) { + DEBUGP(1, dev, "timeout waiting for T0Done\n"); + rc = -EIO; + goto release_io; + } + + dev->procbyte = inb(REG_FLAGS1(iobase)); + DEBUGP(4, dev, "Read procedure byte 0x%.2x\n", + dev->procbyte); + + io_read_num_rec_bytes(iobase, &dev->rlen); + DEBUGP(4, dev, "Read NumRecBytes = %i\n", dev->rlen); + + } + } + /* T=1: read offset=zero, T=0: read offset=after challenge */ + dev->rpos = dev->proto ? 0 : nr == 4 ? 5 : nr > dev->rlen ? 5 : nr; + DEBUGP(4, dev, "dev->rlen = %i, dev->rpos = %i, nr = %i\n", + dev->rlen, dev->rpos, nr); + +release_io: + DEBUGP(4, dev, "Reset SM\n"); + xoutb(0x80, REG_FLAGS0(iobase)); /* reset SM */ + + if (rc < 0) { + DEBUGP(4, dev, "Write failed but clear T_Active\n"); + dev->flags1 &= 0xdf; + xoutb(dev->flags1, REG_FLAGS1(iobase)); + } + + clear_bit(LOCK_IO, &dev->flags); + wake_up_interruptible(&dev->ioq); + wake_up_interruptible(&dev->readq); /* tell read we have data */ + + /* ITSEC E2: clear write buffer */ + memset((char *)dev->sbuf, 0, 512); + + /* return error or actually written bytes */ + DEBUGP(2, dev, "<- cmm_write\n"); + return rc < 0 ? rc : nr; +} + +static void start_monitor(struct cm4000_dev *dev) +{ + DEBUGP(3, dev, "-> start_monitor\n"); + if (!dev->monitor_running) { + DEBUGP(5, dev, "create, init and add timer\n"); + setup_timer(&dev->timer, monitor_card, (unsigned long)dev); + dev->monitor_running = 1; + mod_timer(&dev->timer, jiffies); + } else + DEBUGP(5, dev, "monitor already running\n"); + DEBUGP(3, dev, "<- start_monitor\n"); +} + +static void stop_monitor(struct cm4000_dev *dev) +{ + DEBUGP(3, dev, "-> stop_monitor\n"); + if (dev->monitor_running) { + DEBUGP(5, dev, "stopping monitor\n"); + terminate_monitor(dev); + /* reset monitor SM */ + clear_bit(IS_ATR_VALID, &dev->flags); + clear_bit(IS_ATR_PRESENT, &dev->flags); + } else + DEBUGP(5, dev, "monitor already stopped\n"); + DEBUGP(3, dev, "<- stop_monitor\n"); +} + +static long cmm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) +{ + struct cm4000_dev *dev = filp->private_data; + unsigned int iobase = dev->p_dev->io.BasePort1; + struct inode *inode = filp->f_path.dentry->d_inode; + struct pcmcia_device *link; + int size; + int rc; + void __user *argp = (void __user *)arg; +#ifdef PCMCIA_DEBUG + char *ioctl_names[CM_IOC_MAXNR + 1] = { + [_IOC_NR(CM_IOCGSTATUS)] "CM_IOCGSTATUS", + [_IOC_NR(CM_IOCGATR)] "CM_IOCGATR", + [_IOC_NR(CM_IOCARDOFF)] "CM_IOCARDOFF", + [_IOC_NR(CM_IOCSPTS)] "CM_IOCSPTS", + [_IOC_NR(CM_IOSDBGLVL)] "CM4000_DBGLVL", + }; +#endif + DEBUGP(3, dev, "cmm_ioctl(device=%d.%d) %s\n", imajor(inode), + iminor(inode), ioctl_names[_IOC_NR(cmd)]); + + lock_kernel(); + rc = -ENODEV; + link = dev_table[iminor(inode)]; + if (!pcmcia_dev_present(link)) { + DEBUGP(4, dev, "DEV_OK false\n"); + goto out; + } + + if (test_bit(IS_CMM_ABSENT, &dev->flags)) { + DEBUGP(4, dev, "CMM_ABSENT flag set\n"); + goto out; + } + rc = -EINVAL; + + if (_IOC_TYPE(cmd) != CM_IOC_MAGIC) { + DEBUGP(4, dev, "ioctype mismatch\n"); + goto out; + } + if (_IOC_NR(cmd) > CM_IOC_MAXNR) { + DEBUGP(4, dev, "iocnr mismatch\n"); + goto out; + } + size = _IOC_SIZE(cmd); + rc = -EFAULT; + DEBUGP(4, dev, "iocdir=%.4x iocr=%.4x iocw=%.4x iocsize=%d cmd=%.4x\n", + _IOC_DIR(cmd), _IOC_READ, _IOC_WRITE, size, cmd); + + if (_IOC_DIR(cmd) & _IOC_READ) { + if (!access_ok(VERIFY_WRITE, argp, size)) + goto out; + } + if (_IOC_DIR(cmd) & _IOC_WRITE) { + if (!access_ok(VERIFY_READ, argp, size)) + goto out; + } + rc = 0; + + switch (cmd) { + case CM_IOCGSTATUS: + DEBUGP(4, dev, " ... in CM_IOCGSTATUS\n"); + { + int status; + + /* clear other bits, but leave inserted & powered as + * they are */ + status = dev->flags0 & 3; + if (test_bit(IS_ATR_PRESENT, &dev->flags)) + status |= CM_ATR_PRESENT; + if (test_bit(IS_ATR_VALID, &dev->flags)) + status |= CM_ATR_VALID; + if (test_bit(IS_CMM_ABSENT, &dev->flags)) + status |= CM_NO_READER; + if (test_bit(IS_BAD_CARD, &dev->flags)) + status |= CM_BAD_CARD; + if (copy_to_user(argp, &status, sizeof(int))) + rc = -EFAULT; + } + break; + case CM_IOCGATR: + DEBUGP(4, dev, "... in CM_IOCGATR\n"); + { + struct atreq __user *atreq = argp; + int tmp; + /* allow nonblocking io and being interrupted */ + if (wait_event_interruptible + (dev->atrq, + ((filp->f_flags & O_NONBLOCK) + || (test_bit(IS_ATR_PRESENT, (void *)&dev->flags) + != 0)))) { + if (filp->f_flags & O_NONBLOCK) + rc = -EAGAIN; + else + rc = -ERESTARTSYS; + break; + } + + rc = -EFAULT; + if (test_bit(IS_ATR_VALID, &dev->flags) == 0) { + tmp = -1; + if (copy_to_user(&(atreq->atr_len), &tmp, + sizeof(int))) + break; + } else { + if (copy_to_user(atreq->atr, dev->atr, + dev->atr_len)) + break; + + tmp = dev->atr_len; + if (copy_to_user(&(atreq->atr_len), &tmp, sizeof(int))) + break; + } + rc = 0; + break; + } + case CM_IOCARDOFF: + +#ifdef PCMCIA_DEBUG + DEBUGP(4, dev, "... in CM_IOCARDOFF\n"); + if (dev->flags0 & 0x01) { + DEBUGP(4, dev, " Card inserted\n"); + } else { + DEBUGP(2, dev, " No card inserted\n"); + } + if (dev->flags0 & 0x02) { + DEBUGP(4, dev, " Card powered\n"); + } else { + DEBUGP(2, dev, " Card not powered\n"); + } +#endif + + /* is a card inserted and powered? */ + if ((dev->flags0 & 0x01) && (dev->flags0 & 0x02)) { + + /* get IO lock */ + if (wait_event_interruptible + (dev->ioq, + ((filp->f_flags & O_NONBLOCK) + || (test_and_set_bit(LOCK_IO, (void *)&dev->flags) + == 0)))) { + if (filp->f_flags & O_NONBLOCK) + rc = -EAGAIN; + else + rc = -ERESTARTSYS; + break; + } + /* Set Flags0 = 0x42 */ + DEBUGP(4, dev, "Set Flags0=0x42 \n"); + xoutb(0x42, REG_FLAGS0(iobase)); + clear_bit(IS_ATR_PRESENT, &dev->flags); + clear_bit(IS_ATR_VALID, &dev->flags); + dev->mstate = M_CARDOFF; + clear_bit(LOCK_IO, &dev->flags); + if (wait_event_interruptible + (dev->atrq, + ((filp->f_flags & O_NONBLOCK) + || (test_bit(IS_ATR_VALID, (void *)&dev->flags) != + 0)))) { + if (filp->f_flags & O_NONBLOCK) + rc = -EAGAIN; + else + rc = -ERESTARTSYS; + break; + } + } + /* release lock */ + clear_bit(LOCK_IO, &dev->flags); + wake_up_interruptible(&dev->ioq); + + return 0; + case CM_IOCSPTS: + { + struct ptsreq krnptsreq; + + if (copy_from_user(&krnptsreq, argp, + sizeof(struct ptsreq))) { + rc = -EFAULT; + break; + } + + rc = 0; + DEBUGP(4, dev, "... in CM_IOCSPTS\n"); + /* wait for ATR to get valid */ + if (wait_event_interruptible + (dev->atrq, + ((filp->f_flags & O_NONBLOCK) + || (test_bit(IS_ATR_PRESENT, (void *)&dev->flags) + != 0)))) { + if (filp->f_flags & O_NONBLOCK) + rc = -EAGAIN; + else + rc = -ERESTARTSYS; + break; + } + /* get IO lock */ + if (wait_event_interruptible + (dev->ioq, + ((filp->f_flags & O_NONBLOCK) + || (test_and_set_bit(LOCK_IO, (void *)&dev->flags) + == 0)))) { + if (filp->f_flags & O_NONBLOCK) + rc = -EAGAIN; + else + rc = -ERESTARTSYS; + break; + } + + if ((rc = set_protocol(dev, &krnptsreq)) != 0) { + /* auto power_on again */ + dev->mstate = M_FETCH_ATR; + clear_bit(IS_ATR_VALID, &dev->flags); + } + /* release lock */ + clear_bit(LOCK_IO, &dev->flags); + wake_up_interruptible(&dev->ioq); + + } + break; +#ifdef PCMCIA_DEBUG + case CM_IOSDBGLVL: /* set debug log level */ + { + int old_pc_debug = 0; + + old_pc_debug = pc_debug; + if (copy_from_user(&pc_debug, argp, sizeof(int))) + rc = -EFAULT; + else if (old_pc_debug != pc_debug) + DEBUGP(0, dev, "Changed debug log level " + "to %i\n", pc_debug); + } + break; +#endif + default: + DEBUGP(4, dev, "... in default (unknown IOCTL code)\n"); + rc = -ENOTTY; + } +out: + unlock_kernel(); + return rc; +} + +static int cmm_open(struct inode *inode, struct file *filp) +{ + struct cm4000_dev *dev; + struct pcmcia_device *link; + int minor = iminor(inode); + int ret; + + if (minor >= CM4000_MAX_DEV) + return -ENODEV; + + lock_kernel(); + link = dev_table[minor]; + if (link == NULL || !pcmcia_dev_present(link)) { + ret = -ENODEV; + goto out; + } + + if (link->open) { + ret = -EBUSY; + goto out; + } + + dev = link->priv; + filp->private_data = dev; + + DEBUGP(2, dev, "-> cmm_open(device=%d.%d process=%s,%d)\n", + imajor(inode), minor, current->comm, current->pid); + + /* init device variables, they may be "polluted" after close + * or, the device may never have been closed (i.e. open failed) + */ + + ZERO_DEV(dev); + + /* opening will always block since the + * monitor will be started by open, which + * means we have to wait for ATR becoming + * vaild = block until valid (or card + * inserted) + */ + if (filp->f_flags & O_NONBLOCK) { + ret = -EAGAIN; + goto out; + } + + dev->mdelay = T_50MSEC; + + /* start monitoring the cardstatus */ + start_monitor(dev); + + link->open = 1; /* only one open per device */ + + DEBUGP(2, dev, "<- cmm_open\n"); + ret = nonseekable_open(inode, filp); +out: + unlock_kernel(); + return ret; +} + +static int cmm_close(struct inode *inode, struct file *filp) +{ + struct cm4000_dev *dev; + struct pcmcia_device *link; + int minor = iminor(inode); + + if (minor >= CM4000_MAX_DEV) + return -ENODEV; + + link = dev_table[minor]; + if (link == NULL) + return -ENODEV; + + dev = link->priv; + + DEBUGP(2, dev, "-> cmm_close(maj/min=%d.%d)\n", + imajor(inode), minor); + + stop_monitor(dev); + + ZERO_DEV(dev); + + link->open = 0; /* only one open per device */ + wake_up(&dev->devq); /* socket removed? */ + + DEBUGP(2, dev, "cmm_close\n"); + return 0; +} + +static void cmm_cm4000_release(struct pcmcia_device * link) +{ + struct cm4000_dev *dev = link->priv; + + /* dont terminate the monitor, rather rely on + * close doing that for us. + */ + DEBUGP(3, dev, "-> cmm_cm4000_release\n"); + while (link->open) { + printk(KERN_INFO MODULE_NAME ": delaying release until " + "process has terminated\n"); + /* note: don't interrupt us: + * close the applications which own + * the devices _first_ ! + */ + wait_event(dev->devq, (link->open == 0)); + } + /* dev->devq=NULL; this cannot be zeroed earlier */ + DEBUGP(3, dev, "<- cmm_cm4000_release\n"); + return; +} + +/*==== Interface to PCMCIA Layer =======================================*/ + +static int cm4000_config_check(struct pcmcia_device *p_dev, + cistpl_cftable_entry_t *cfg, + cistpl_cftable_entry_t *dflt, + unsigned int vcc, + void *priv_data) +{ + if (!cfg->io.nwin) + return -ENODEV; + + /* Get the IOaddr */ + p_dev->io.BasePort1 = cfg->io.win[0].base; + p_dev->io.NumPorts1 = cfg->io.win[0].len; + p_dev->io.Attributes1 = IO_DATA_PATH_WIDTH_AUTO; + if (!(cfg->io.flags & CISTPL_IO_8BIT)) + p_dev->io.Attributes1 = IO_DATA_PATH_WIDTH_16; + if (!(cfg->io.flags & CISTPL_IO_16BIT)) + p_dev->io.Attributes1 = IO_DATA_PATH_WIDTH_8; + p_dev->io.IOAddrLines = cfg->io.flags & CISTPL_IO_LINES_MASK; + + return pcmcia_request_io(p_dev, &p_dev->io); +} + +static int cm4000_config(struct pcmcia_device * link, int devno) +{ + struct cm4000_dev *dev; + + /* read the config-tuples */ + if (pcmcia_loop_config(link, cm4000_config_check, NULL)) + goto cs_release; + + link->conf.IntType = 00000002; + + if (pcmcia_request_configuration(link, &link->conf)) + goto cs_release; + + dev = link->priv; + sprintf(dev->node.dev_name, DEVICE_NAME "%d", devno); + dev->node.major = major; + dev->node.minor = devno; + dev->node.next = NULL; + link->dev_node = &dev->node; + + return 0; + +cs_release: + cm4000_release(link); + return -ENODEV; +} + +static int cm4000_suspend(struct pcmcia_device *link) +{ + struct cm4000_dev *dev; + + dev = link->priv; + stop_monitor(dev); + + return 0; +} + +static int cm4000_resume(struct pcmcia_device *link) +{ + struct cm4000_dev *dev; + + dev = link->priv; + if (link->open) + start_monitor(dev); + + return 0; +} + +static void cm4000_release(struct pcmcia_device *link) +{ + cmm_cm4000_release(link); /* delay release until device closed */ + pcmcia_disable_device(link); +} + +static int cm4000_probe(struct pcmcia_device *link) +{ + struct cm4000_dev *dev; + int i, ret; + + for (i = 0; i < CM4000_MAX_DEV; i++) + if (dev_table[i] == NULL) + break; + + if (i == CM4000_MAX_DEV) { + printk(KERN_NOTICE MODULE_NAME ": all devices in use\n"); + return -ENODEV; + } + + /* create a new cm4000_cs device */ + dev = kzalloc(sizeof(struct cm4000_dev), GFP_KERNEL); + if (dev == NULL) + return -ENOMEM; + + dev->p_dev = link; + link->priv = dev; + link->conf.IntType = INT_MEMORY_AND_IO; + dev_table[i] = link; + + init_waitqueue_head(&dev->devq); + init_waitqueue_head(&dev->ioq); + init_waitqueue_head(&dev->atrq); + init_waitqueue_head(&dev->readq); + + ret = cm4000_config(link, i); + if (ret) { + dev_table[i] = NULL; + kfree(dev); + return ret; + } + + device_create(cmm_class, NULL, MKDEV(major, i), NULL, "cmm%d", i); + + return 0; +} + +static void cm4000_detach(struct pcmcia_device *link) +{ + struct cm4000_dev *dev = link->priv; + int devno; + + /* find device */ + for (devno = 0; devno < CM4000_MAX_DEV; devno++) + if (dev_table[devno] == link) + break; + if (devno == CM4000_MAX_DEV) + return; + + stop_monitor(dev); + + cm4000_release(link); + + dev_table[devno] = NULL; + kfree(dev); + + device_destroy(cmm_class, MKDEV(major, devno)); + + return; +} + +static const struct file_operations cm4000_fops = { + .owner = THIS_MODULE, + .read = cmm_read, + .write = cmm_write, + .unlocked_ioctl = cmm_ioctl, + .open = cmm_open, + .release= cmm_close, +}; + +static struct pcmcia_device_id cm4000_ids[] = { + PCMCIA_DEVICE_MANF_CARD(0x0223, 0x0002), + PCMCIA_DEVICE_PROD_ID12("CardMan", "4000", 0x2FB368CA, 0xA2BD8C39), + PCMCIA_DEVICE_NULL, +}; +MODULE_DEVICE_TABLE(pcmcia, cm4000_ids); + +static struct pcmcia_driver cm4000_driver = { + .owner = THIS_MODULE, + .drv = { + .name = "cm4000_cs", + }, + .probe = cm4000_probe, + .remove = cm4000_detach, + .suspend = cm4000_suspend, + .resume = cm4000_resume, + .id_table = cm4000_ids, +}; + +static int __init cmm_init(void) +{ + int rc; + + printk(KERN_INFO "%s\n", version); + + cmm_class = class_create(THIS_MODULE, "cardman_4000"); + if (IS_ERR(cmm_class)) + return PTR_ERR(cmm_class); + + major = register_chrdev(0, DEVICE_NAME, &cm4000_fops); + if (major < 0) { + printk(KERN_WARNING MODULE_NAME + ": could not get major number\n"); + class_destroy(cmm_class); + return major; + } + + rc = pcmcia_register_driver(&cm4000_driver); + if (rc < 0) { + unregister_chrdev(major, DEVICE_NAME); + class_destroy(cmm_class); + return rc; + } + + return 0; +} + +static void __exit cmm_exit(void) +{ + printk(KERN_INFO MODULE_NAME ": unloading\n"); + pcmcia_unregister_driver(&cm4000_driver); + unregister_chrdev(major, DEVICE_NAME); + class_destroy(cmm_class); +}; + +module_init(cmm_init); +module_exit(cmm_exit); +MODULE_LICENSE("Dual BSD/GPL"); diff --git a/drivers/char/pcmcia/cm4040_cs.c b/drivers/char/pcmcia/cm4040_cs.c new file mode 100644 index 0000000..4f0723b --- /dev/null +++ b/drivers/char/pcmcia/cm4040_cs.c @@ -0,0 +1,732 @@ +/* + * A driver for the Omnikey PCMCIA smartcard reader CardMan 4040 + * + * (c) 2000-2004 Omnikey AG (http://www.omnikey.com/) + * + * (C) 2005-2006 Harald Welte <laforge@gnumonks.org> + * - add support for poll() + * - driver cleanup + * - add waitqueues + * - adhere to linux kernel coding style and policies + * - support 2.6.13 "new style" pcmcia interface + * - add class interface for udev device creation + * + * The device basically is a USB CCID compliant device that has been + * attached to an I/O-Mapped FIFO. + * + * All rights reserved, Dual BSD/GPL Licensed. + */ + +/* #define PCMCIA_DEBUG 6 */ + +#include <linux/kernel.h> +#include <linux/module.h> +#include <linux/slab.h> +#include <linux/init.h> +#include <linux/fs.h> +#include <linux/delay.h> +#include <linux/poll.h> +#include <linux/smp_lock.h> +#include <linux/wait.h> +#include <asm/uaccess.h> +#include <asm/io.h> + +#include <pcmcia/cs_types.h> +#include <pcmcia/cs.h> +#include <pcmcia/cistpl.h> +#include <pcmcia/cisreg.h> +#include <pcmcia/ciscode.h> +#include <pcmcia/ds.h> + +#include "cm4040_cs.h" + + +#ifdef PCMCIA_DEBUG +#define reader_to_dev(x) (&handle_to_dev(x->p_dev)) +static int pc_debug = PCMCIA_DEBUG; +module_param(pc_debug, int, 0600); +#define DEBUGP(n, rdr, x, args...) do { \ + if (pc_debug >= (n)) \ + dev_printk(KERN_DEBUG, reader_to_dev(rdr), "%s:" x, \ + __func__ , ##args); \ + } while (0) +#else +#define DEBUGP(n, rdr, x, args...) +#endif + +static char *version = +"OMNIKEY CardMan 4040 v1.1.0gm5 - All bugs added by Harald Welte"; + +#define CCID_DRIVER_BULK_DEFAULT_TIMEOUT (150*HZ) +#define CCID_DRIVER_ASYNC_POWERUP_TIMEOUT (35*HZ) +#define CCID_DRIVER_MINIMUM_TIMEOUT (3*HZ) +#define READ_WRITE_BUFFER_SIZE 512 +#define POLL_LOOP_COUNT 1000 + +/* how often to poll for fifo status change */ +#define POLL_PERIOD msecs_to_jiffies(10) + +static void reader_release(struct pcmcia_device *link); + +static int major; +static struct class *cmx_class; + +#define BS_READABLE 0x01 +#define BS_WRITABLE 0x02 + +struct reader_dev { + struct pcmcia_device *p_dev; + dev_node_t node; + wait_queue_head_t devq; + wait_queue_head_t poll_wait; + wait_queue_head_t read_wait; + wait_queue_head_t write_wait; + unsigned long buffer_status; + unsigned long timeout; + unsigned char s_buf[READ_WRITE_BUFFER_SIZE]; + unsigned char r_buf[READ_WRITE_BUFFER_SIZE]; + struct timer_list poll_timer; +}; + +static struct pcmcia_device *dev_table[CM_MAX_DEV]; + +#ifndef PCMCIA_DEBUG +#define xoutb outb +#define xinb inb +#else +static inline void xoutb(unsigned char val, unsigned short port) +{ + if (pc_debug >= 7) + printk(KERN_DEBUG "outb(val=%.2x,port=%.4x)\n", val, port); + outb(val, port); +} + +static inline unsigned char xinb(unsigned short port) +{ + unsigned char val; + + val = inb(port); + if (pc_debug >= 7) + printk(KERN_DEBUG "%.2x=inb(%.4x)\n", val, port); + return val; +} +#endif + +/* poll the device fifo status register. not to be confused with + * the poll syscall. */ +static void cm4040_do_poll(unsigned long dummy) +{ + struct reader_dev *dev = (struct reader_dev *) dummy; + unsigned int obs = xinb(dev->p_dev->io.BasePort1 + + REG_OFFSET_BUFFER_STATUS); + + if ((obs & BSR_BULK_IN_FULL)) { + set_bit(BS_READABLE, &dev->buffer_status); + DEBUGP(4, dev, "waking up read_wait\n"); + wake_up_interruptible(&dev->read_wait); + } else + clear_bit(BS_READABLE, &dev->buffer_status); + + if (!(obs & BSR_BULK_OUT_FULL)) { + set_bit(BS_WRITABLE, &dev->buffer_status); + DEBUGP(4, dev, "waking up write_wait\n"); + wake_up_interruptible(&dev->write_wait); + } else + clear_bit(BS_WRITABLE, &dev->buffer_status); + + if (dev->buffer_status) + wake_up_interruptible(&dev->poll_wait); + + mod_timer(&dev->poll_timer, jiffies + POLL_PERIOD); +} + +static void cm4040_stop_poll(struct reader_dev *dev) +{ + del_timer_sync(&dev->poll_timer); +} + +static int wait_for_bulk_out_ready(struct reader_dev *dev) +{ + int i, rc; + int iobase = dev->p_dev->io.BasePort1; + + for (i = 0; i < POLL_LOOP_COUNT; i++) { + if ((xinb(iobase + REG_OFFSET_BUFFER_STATUS) + & BSR_BULK_OUT_FULL) == 0) { + DEBUGP(4, dev, "BulkOut empty (i=%d)\n", i); + return 1; + } + } + + DEBUGP(4, dev, "wait_event_interruptible_timeout(timeout=%ld\n", + dev->timeout); + rc = wait_event_interruptible_timeout(dev->write_wait, + test_and_clear_bit(BS_WRITABLE, + &dev->buffer_status), + dev->timeout); + + if (rc > 0) + DEBUGP(4, dev, "woke up: BulkOut empty\n"); + else if (rc == 0) + DEBUGP(4, dev, "woke up: BulkOut full, returning 0 :(\n"); + else if (rc < 0) + DEBUGP(4, dev, "woke up: signal arrived\n"); + + return rc; +} + +/* Write to Sync Control Register */ +static int write_sync_reg(unsigned char val, struct reader_dev *dev) +{ + int iobase = dev->p_dev->io.BasePort1; + int rc; + + rc = wait_for_bulk_out_ready(dev); + if (rc <= 0) + return rc; + + xoutb(val, iobase + REG_OFFSET_SYNC_CONTROL); + rc = wait_for_bulk_out_ready(dev); + if (rc <= 0) + return rc; + + return 1; +} + +static int wait_for_bulk_in_ready(struct reader_dev *dev) +{ + int i, rc; + int iobase = dev->p_dev->io.BasePort1; + + for (i = 0; i < POLL_LOOP_COUNT; i++) { + if ((xinb(iobase + REG_OFFSET_BUFFER_STATUS) + & BSR_BULK_IN_FULL) == BSR_BULK_IN_FULL) { + DEBUGP(3, dev, "BulkIn full (i=%d)\n", i); + return 1; + } + } + + DEBUGP(4, dev, "wait_event_interruptible_timeout(timeout=%ld\n", + dev->timeout); + rc = wait_event_interruptible_timeout(dev->read_wait, + test_and_clear_bit(BS_READABLE, + &dev->buffer_status), + dev->timeout); + if (rc > 0) + DEBUGP(4, dev, "woke up: BulkIn full\n"); + else if (rc == 0) + DEBUGP(4, dev, "woke up: BulkIn not full, returning 0 :(\n"); + else if (rc < 0) + DEBUGP(4, dev, "woke up: signal arrived\n"); + + return rc; +} + +static ssize_t cm4040_read(struct file *filp, char __user *buf, + size_t count, loff_t *ppos) +{ + struct reader_dev *dev = filp->private_data; + int iobase = dev->p_dev->io.BasePort1; + size_t bytes_to_read; + unsigned long i; + size_t min_bytes_to_read; + int rc; + unsigned char uc; + + DEBUGP(2, dev, "-> cm4040_read(%s,%d)\n", current->comm, current->pid); + + if (count == 0) + return 0; + + if (count < 10) + return -EFAULT; + + if (filp->f_flags & O_NONBLOCK) { + DEBUGP(4, dev, "filep->f_flags O_NONBLOCK set\n"); + DEBUGP(2, dev, "<- cm4040_read (failure)\n"); + return -EAGAIN; + } + + if (!pcmcia_dev_present(dev->p_dev)) + return -ENODEV; + + for (i = 0; i < 5; i++) { + rc = wait_for_bulk_in_ready(dev); + if (rc <= 0) { + DEBUGP(5, dev, "wait_for_bulk_in_ready rc=%.2x\n", rc); + DEBUGP(2, dev, "<- cm4040_read (failed)\n"); + if (rc == -ERESTARTSYS) + return rc; + return -EIO; + } + dev->r_buf[i] = xinb(iobase + REG_OFFSET_BULK_IN); +#ifdef PCMCIA_DEBUG + if (pc_debug >= 6) + printk(KERN_DEBUG "%lu:%2x ", i, dev->r_buf[i]); + } + printk("\n"); +#else + } +#endif + + bytes_to_read = 5 + le32_to_cpu(*(__le32 *)&dev->r_buf[1]); + + DEBUGP(6, dev, "BytesToRead=%lu\n", bytes_to_read); + + min_bytes_to_read = min(count, bytes_to_read + 5); + min_bytes_to_read = min_t(size_t, min_bytes_to_read, READ_WRITE_BUFFER_SIZE); + + DEBUGP(6, dev, "Min=%lu\n", min_bytes_to_read); + + for (i = 0; i < (min_bytes_to_read-5); i++) { + rc = wait_for_bulk_in_ready(dev); + if (rc <= 0) { + DEBUGP(5, dev, "wait_for_bulk_in_ready rc=%.2x\n", rc); + DEBUGP(2, dev, "<- cm4040_read (failed)\n"); + if (rc == -ERESTARTSYS) + return rc; + return -EIO; + } + dev->r_buf[i+5] = xinb(iobase + REG_OFFSET_BULK_IN); +#ifdef PCMCIA_DEBUG + if (pc_debug >= 6) + printk(KERN_DEBUG "%lu:%2x ", i, dev->r_buf[i]); + } + printk("\n"); +#else + } +#endif + + *ppos = min_bytes_to_read; + if (copy_to_user(buf, dev->r_buf, min_bytes_to_read)) + return -EFAULT; + + rc = wait_for_bulk_in_ready(dev); + if (rc <= 0) { + DEBUGP(5, dev, "wait_for_bulk_in_ready rc=%.2x\n", rc); + DEBUGP(2, dev, "<- cm4040_read (failed)\n"); + if (rc == -ERESTARTSYS) + return rc; + return -EIO; + } + + rc = write_sync_reg(SCR_READER_TO_HOST_DONE, dev); + if (rc <= 0) { + DEBUGP(5, dev, "write_sync_reg c=%.2x\n", rc); + DEBUGP(2, dev, "<- cm4040_read (failed)\n"); + if (rc == -ERESTARTSYS) + return rc; + else + return -EIO; + } + + uc = xinb(iobase + REG_OFFSET_BULK_IN); + + DEBUGP(2, dev, "<- cm4040_read (successfully)\n"); + return min_bytes_to_read; +} + +static ssize_t cm4040_write(struct file *filp, const char __user *buf, + size_t count, loff_t *ppos) +{ + struct reader_dev *dev = filp->private_data; + int iobase = dev->p_dev->io.BasePort1; + ssize_t rc; + int i; + unsigned int bytes_to_write; + + DEBUGP(2, dev, "-> cm4040_write(%s,%d)\n", current->comm, current->pid); + + if (count == 0) { + DEBUGP(2, dev, "<- cm4040_write empty read (successfully)\n"); + return 0; + } + + if ((count < 5) || (count > READ_WRITE_BUFFER_SIZE)) { + DEBUGP(2, dev, "<- cm4040_write buffersize=%Zd < 5\n", count); + return -EIO; + } + + if (filp->f_flags & O_NONBLOCK) { + DEBUGP(4, dev, "filep->f_flags O_NONBLOCK set\n"); + DEBUGP(4, dev, "<- cm4040_write (failure)\n"); + return -EAGAIN; + } + + if (!pcmcia_dev_present(dev->p_dev)) + return -ENODEV; + + bytes_to_write = count; + if (copy_from_user(dev->s_buf, buf, bytes_to_write)) + return -EFAULT; + + switch (dev->s_buf[0]) { + case CMD_PC_TO_RDR_XFRBLOCK: + case CMD_PC_TO_RDR_SECURE: + case CMD_PC_TO_RDR_TEST_SECURE: + case CMD_PC_TO_RDR_OK_SECURE: + dev->timeout = CCID_DRIVER_BULK_DEFAULT_TIMEOUT; + break; + + case CMD_PC_TO_RDR_ICCPOWERON: + dev->timeout = CCID_DRIVER_ASYNC_POWERUP_TIMEOUT; + break; + + case CMD_PC_TO_RDR_GETSLOTSTATUS: + case CMD_PC_TO_RDR_ICCPOWEROFF: + case CMD_PC_TO_RDR_GETPARAMETERS: + case CMD_PC_TO_RDR_RESETPARAMETERS: + case CMD_PC_TO_RDR_SETPARAMETERS: + case CMD_PC_TO_RDR_ESCAPE: + case CMD_PC_TO_RDR_ICCCLOCK: + default: + dev->timeout = CCID_DRIVER_MINIMUM_TIMEOUT; + break; + } + + rc = write_sync_reg(SCR_HOST_TO_READER_START, dev); + if (rc <= 0) { + DEBUGP(5, dev, "write_sync_reg c=%.2Zx\n", rc); + DEBUGP(2, dev, "<- cm4040_write (failed)\n"); + if (rc == -ERESTARTSYS) + return rc; + else + return -EIO; + } + + DEBUGP(4, dev, "start \n"); + + for (i = 0; i < bytes_to_write; i++) { + rc = wait_for_bulk_out_ready(dev); + if (rc <= 0) { + DEBUGP(5, dev, "wait_for_bulk_out_ready rc=%.2Zx\n", + rc); + DEBUGP(2, dev, "<- cm4040_write (failed)\n"); + if (rc == -ERESTARTSYS) + return rc; + else + return -EIO; + } + + xoutb(dev->s_buf[i],iobase + REG_OFFSET_BULK_OUT); + } + DEBUGP(4, dev, "end\n"); + + rc = write_sync_reg(SCR_HOST_TO_READER_DONE, dev); + + if (rc <= 0) { + DEBUGP(5, dev, "write_sync_reg c=%.2Zx\n", rc); + DEBUGP(2, dev, "<- cm4040_write (failed)\n"); + if (rc == -ERESTARTSYS) + return rc; + else + return -EIO; + } + + DEBUGP(2, dev, "<- cm4040_write (successfully)\n"); + return count; +} + +static unsigned int cm4040_poll(struct file *filp, poll_table *wait) +{ + struct reader_dev *dev = filp->private_data; + unsigned int mask = 0; + + poll_wait(filp, &dev->poll_wait, wait); + + if (test_and_clear_bit(BS_READABLE, &dev->buffer_status)) + mask |= POLLIN | POLLRDNORM; + if (test_and_clear_bit(BS_WRITABLE, &dev->buffer_status)) + mask |= POLLOUT | POLLWRNORM; + + DEBUGP(2, dev, "<- cm4040_poll(%u)\n", mask); + + return mask; +} + +static int cm4040_open(struct inode *inode, struct file *filp) +{ + struct reader_dev *dev; + struct pcmcia_device *link; + int minor = iminor(inode); + int ret; + + if (minor >= CM_MAX_DEV) + return -ENODEV; + + lock_kernel(); + link = dev_table[minor]; + if (link == NULL || !pcmcia_dev_present(link)) { + ret = -ENODEV; + goto out; + } + + if (link->open) { + ret = -EBUSY; + goto out; + } + + dev = link->priv; + filp->private_data = dev; + + if (filp->f_flags & O_NONBLOCK) { + DEBUGP(4, dev, "filep->f_flags O_NONBLOCK set\n"); + ret = -EAGAIN; + goto out; + } + + link->open = 1; + + dev->poll_timer.data = (unsigned long) dev; + mod_timer(&dev->poll_timer, jiffies + POLL_PERIOD); + + DEBUGP(2, dev, "<- cm4040_open (successfully)\n"); + ret = nonseekable_open(inode, filp); +out: + unlock_kernel(); + return ret; +} + +static int cm4040_close(struct inode *inode, struct file *filp) +{ + struct reader_dev *dev = filp->private_data; + struct pcmcia_device *link; + int minor = iminor(inode); + + DEBUGP(2, dev, "-> cm4040_close(maj/min=%d.%d)\n", imajor(inode), + iminor(inode)); + + if (minor >= CM_MAX_DEV) + return -ENODEV; + + link = dev_table[minor]; + if (link == NULL) + return -ENODEV; + + cm4040_stop_poll(dev); + + link->open = 0; + wake_up(&dev->devq); + + DEBUGP(2, dev, "<- cm4040_close\n"); + return 0; +} + +static void cm4040_reader_release(struct pcmcia_device *link) +{ + struct reader_dev *dev = link->priv; + + DEBUGP(3, dev, "-> cm4040_reader_release\n"); + while (link->open) { + DEBUGP(3, dev, KERN_INFO MODULE_NAME ": delaying release " + "until process has terminated\n"); + wait_event(dev->devq, (link->open == 0)); + } + DEBUGP(3, dev, "<- cm4040_reader_release\n"); + return; +} + +static int cm4040_config_check(struct pcmcia_device *p_dev, + cistpl_cftable_entry_t *cfg, + cistpl_cftable_entry_t *dflt, + unsigned int vcc, + void *priv_data) +{ + int rc; + if (!cfg->io.nwin) + return -ENODEV; + + /* Get the IOaddr */ + p_dev->io.BasePort1 = cfg->io.win[0].base; + p_dev->io.NumPorts1 = cfg->io.win[0].len; + p_dev->io.Attributes1 = IO_DATA_PATH_WIDTH_AUTO; + if (!(cfg->io.flags & CISTPL_IO_8BIT)) + p_dev->io.Attributes1 = IO_DATA_PATH_WIDTH_16; + if (!(cfg->io.flags & CISTPL_IO_16BIT)) + p_dev->io.Attributes1 = IO_DATA_PATH_WIDTH_8; + p_dev->io.IOAddrLines = cfg->io.flags & CISTPL_IO_LINES_MASK; + + rc = pcmcia_request_io(p_dev, &p_dev->io); + dev_printk(KERN_INFO, &handle_to_dev(p_dev), + "pcmcia_request_io returned 0x%x\n", rc); + return rc; +} + + +static int reader_config(struct pcmcia_device *link, int devno) +{ + struct reader_dev *dev; + int fail_rc; + + link->io.BasePort2 = 0; + link->io.NumPorts2 = 0; + link->io.Attributes2 = 0; + + if (pcmcia_loop_config(link, cm4040_config_check, NULL)) + goto cs_release; + + link->conf.IntType = 00000002; + + fail_rc = pcmcia_request_configuration(link, &link->conf); + if (fail_rc != 0) { + dev_printk(KERN_INFO, &handle_to_dev(link), + "pcmcia_request_configuration failed 0x%x\n", + fail_rc); + goto cs_release; + } + + dev = link->priv; + sprintf(dev->node.dev_name, DEVICE_NAME "%d", devno); + dev->node.major = major; + dev->node.minor = devno; + dev->node.next = &dev->node; + + DEBUGP(2, dev, "device " DEVICE_NAME "%d at 0x%.4x-0x%.4x\n", devno, + link->io.BasePort1, link->io.BasePort1+link->io.NumPorts1); + DEBUGP(2, dev, "<- reader_config (succ)\n"); + + return 0; + +cs_release: + reader_release(link); + return -ENODEV; +} + +static void reader_release(struct pcmcia_device *link) +{ + cm4040_reader_release(link); + pcmcia_disable_device(link); +} + +static int reader_probe(struct pcmcia_device *link) +{ + struct reader_dev *dev; + int i, ret; + + for (i = 0; i < CM_MAX_DEV; i++) { + if (dev_table[i] == NULL) + break; + } + + if (i == CM_MAX_DEV) + return -ENODEV; + + dev = kzalloc(sizeof(struct reader_dev), GFP_KERNEL); + if (dev == NULL) + return -ENOMEM; + + dev->timeout = CCID_DRIVER_MINIMUM_TIMEOUT; + dev->buffer_status = 0; + + link->priv = dev; + dev->p_dev = link; + + link->conf.IntType = INT_MEMORY_AND_IO; + dev_table[i] = link; + + init_waitqueue_head(&dev->devq); + init_waitqueue_head(&dev->poll_wait); + init_waitqueue_head(&dev->read_wait); + init_waitqueue_head(&dev->write_wait); + setup_timer(&dev->poll_timer, cm4040_do_poll, 0); + + ret = reader_config(link, i); + if (ret) { + dev_table[i] = NULL; + kfree(dev); + return ret; + } + + device_create(cmx_class, NULL, MKDEV(major, i), NULL, "cmx%d", i); + + return 0; +} + +static void reader_detach(struct pcmcia_device *link) +{ + struct reader_dev *dev = link->priv; + int devno; + + /* find device */ + for (devno = 0; devno < CM_MAX_DEV; devno++) { + if (dev_table[devno] == link) + break; + } + if (devno == CM_MAX_DEV) + return; + + reader_release(link); + + dev_table[devno] = NULL; + kfree(dev); + + device_destroy(cmx_class, MKDEV(major, devno)); + + return; +} + +static const struct file_operations reader_fops = { + .owner = THIS_MODULE, + .read = cm4040_read, + .write = cm4040_write, + .open = cm4040_open, + .release = cm4040_close, + .poll = cm4040_poll, +}; + +static struct pcmcia_device_id cm4040_ids[] = { + PCMCIA_DEVICE_MANF_CARD(0x0223, 0x0200), + PCMCIA_DEVICE_PROD_ID12("OMNIKEY", "CardMan 4040", + 0xE32CDD8C, 0x8F23318B), + PCMCIA_DEVICE_NULL, +}; +MODULE_DEVICE_TABLE(pcmcia, cm4040_ids); + +static struct pcmcia_driver reader_driver = { + .owner = THIS_MODULE, + .drv = { + .name = "cm4040_cs", + }, + .probe = reader_probe, + .remove = reader_detach, + .id_table = cm4040_ids, +}; + +static int __init cm4040_init(void) +{ + int rc; + + printk(KERN_INFO "%s\n", version); + cmx_class = class_create(THIS_MODULE, "cardman_4040"); + if (IS_ERR(cmx_class)) + return PTR_ERR(cmx_class); + + major = register_chrdev(0, DEVICE_NAME, &reader_fops); + if (major < 0) { + printk(KERN_WARNING MODULE_NAME + ": could not get major number\n"); + class_destroy(cmx_class); + return major; + } + + rc = pcmcia_register_driver(&reader_driver); + if (rc < 0) { + unregister_chrdev(major, DEVICE_NAME); + class_destroy(cmx_class); + return rc; + } + + return 0; +} + +static void __exit cm4040_exit(void) +{ + printk(KERN_INFO MODULE_NAME ": unloading\n"); + pcmcia_unregister_driver(&reader_driver); + unregister_chrdev(major, DEVICE_NAME); + class_destroy(cmx_class); +} + +module_init(cm4040_init); +module_exit(cm4040_exit); +MODULE_LICENSE("Dual BSD/GPL"); diff --git a/drivers/char/pcmcia/cm4040_cs.h b/drivers/char/pcmcia/cm4040_cs.h new file mode 100644 index 0000000..9a8b805 --- /dev/null +++ b/drivers/char/pcmcia/cm4040_cs.h @@ -0,0 +1,47 @@ +#ifndef _CM4040_H_ +#define _CM4040_H_ + +#define CM_MAX_DEV 4 + +#define DEVICE_NAME "cmx" +#define MODULE_NAME "cm4040_cs" + +#define REG_OFFSET_BULK_OUT 0 +#define REG_OFFSET_BULK_IN 0 +#define REG_OFFSET_BUFFER_STATUS 1 +#define REG_OFFSET_SYNC_CONTROL 2 + +#define BSR_BULK_IN_FULL 0x02 +#define BSR_BULK_OUT_FULL 0x01 + +#define SCR_HOST_TO_READER_START 0x80 +#define SCR_ABORT 0x40 +#define SCR_EN_NOTIFY 0x20 +#define SCR_ACK_NOTIFY 0x10 +#define SCR_READER_TO_HOST_DONE 0x08 +#define SCR_HOST_TO_READER_DONE 0x04 +#define SCR_PULSE_INTERRUPT 0x02 +#define SCR_POWER_DOWN 0x01 + + +#define CMD_PC_TO_RDR_ICCPOWERON 0x62 +#define CMD_PC_TO_RDR_GETSLOTSTATUS 0x65 +#define CMD_PC_TO_RDR_ICCPOWEROFF 0x63 +#define CMD_PC_TO_RDR_SECURE 0x69 +#define CMD_PC_TO_RDR_GETPARAMETERS 0x6C +#define CMD_PC_TO_RDR_RESETPARAMETERS 0x6D +#define CMD_PC_TO_RDR_SETPARAMETERS 0x61 +#define CMD_PC_TO_RDR_XFRBLOCK 0x6F +#define CMD_PC_TO_RDR_ESCAPE 0x6B +#define CMD_PC_TO_RDR_ICCCLOCK 0x6E +#define CMD_PC_TO_RDR_TEST_SECURE 0x74 +#define CMD_PC_TO_RDR_OK_SECURE 0x89 + + +#define CMD_RDR_TO_PC_SLOTSTATUS 0x81 +#define CMD_RDR_TO_PC_DATABLOCK 0x80 +#define CMD_RDR_TO_PC_PARAMETERS 0x82 +#define CMD_RDR_TO_PC_ESCAPE 0x83 +#define CMD_RDR_TO_PC_OK_SECURE 0x89 + +#endif /* _CM4040_H_ */ diff --git a/drivers/char/pcmcia/ipwireless/Makefile b/drivers/char/pcmcia/ipwireless/Makefile new file mode 100644 index 0000000..b71eb59 --- /dev/null +++ b/drivers/char/pcmcia/ipwireless/Makefile @@ -0,0 +1,10 @@ +# +# drivers/char/pcmcia/ipwireless/Makefile +# +# Makefile for the IPWireless driver +# + +obj-$(CONFIG_IPWIRELESS) += ipwireless.o + +ipwireless-objs := hardware.o main.o network.o tty.o + diff --git a/drivers/char/pcmcia/ipwireless/hardware.c b/drivers/char/pcmcia/ipwireless/hardware.c new file mode 100644 index 0000000..4c1820c --- /dev/null +++ b/drivers/char/pcmcia/ipwireless/hardware.c @@ -0,0 +1,1764 @@ +/* + * IPWireless 3G PCMCIA Network Driver + * + * Original code + * by Stephen Blackheath <stephen@blacksapphire.com>, + * Ben Martel <benm@symmetric.co.nz> + * + * Copyrighted as follows: + * Copyright (C) 2004 by Symmetric Systems Ltd (NZ) + * + * Various driver changes and rewrites, port to new kernels + * Copyright (C) 2006-2007 Jiri Kosina + * + * Misc code cleanups and updates + * Copyright (C) 2007 David Sterba + */ + +#include <linux/interrupt.h> +#include <linux/io.h> +#include <linux/irq.h> +#include <linux/kernel.h> +#include <linux/list.h> +#include <linux/slab.h> + +#include "hardware.h" +#include "setup_protocol.h" +#include "network.h" +#include "main.h" + +static void ipw_send_setup_packet(struct ipw_hardware *hw); +static void handle_received_SETUP_packet(struct ipw_hardware *ipw, + unsigned int address, + const unsigned char *data, int len, + int is_last); +static void ipwireless_setup_timer(unsigned long data); +static void handle_received_CTRL_packet(struct ipw_hardware *hw, + unsigned int channel_idx, const unsigned char *data, int len); + +/*#define TIMING_DIAGNOSTICS*/ + +#ifdef TIMING_DIAGNOSTICS + +static struct timing_stats { + unsigned long last_report_time; + unsigned long read_time; + unsigned long write_time; + unsigned long read_bytes; + unsigned long write_bytes; + unsigned long start_time; +}; + +static void start_timing(void) +{ + timing_stats.start_time = jiffies; +} + +static void end_read_timing(unsigned length) +{ + timing_stats.read_time += (jiffies - start_time); + timing_stats.read_bytes += length + 2; + report_timing(); +} + +static void end_write_timing(unsigned length) +{ + timing_stats.write_time += (jiffies - start_time); + timing_stats.write_bytes += length + 2; + report_timing(); +} + +static void report_timing(void) +{ + unsigned long since = jiffies - timing_stats.last_report_time; + + /* If it's been more than one second... */ + if (since >= HZ) { + int first = (timing_stats.last_report_time == 0); + + timing_stats.last_report_time = jiffies; + if (!first) + printk(KERN_INFO IPWIRELESS_PCCARD_NAME + ": %u us elapsed - read %lu bytes in %u us, wrote %lu bytes in %u us\n", + jiffies_to_usecs(since), + timing_stats.read_bytes, + jiffies_to_usecs(timing_stats.read_time), + timing_stats.write_bytes, + jiffies_to_usecs(timing_stats.write_time)); + + timing_stats.read_time = 0; + timing_stats.write_time = 0; + timing_stats.read_bytes = 0; + timing_stats.write_bytes = 0; + } +} +#else +static void start_timing(void) { } +static void end_read_timing(unsigned length) { } +static void end_write_timing(unsigned length) { } +#endif + +/* Imported IPW definitions */ + +#define LL_MTU_V1 318 +#define LL_MTU_V2 250 +#define LL_MTU_MAX (LL_MTU_V1 > LL_MTU_V2 ? LL_MTU_V1 : LL_MTU_V2) + +#define PRIO_DATA 2 +#define PRIO_CTRL 1 +#define PRIO_SETUP 0 + +/* Addresses */ +#define ADDR_SETUP_PROT 0 + +/* Protocol ids */ +enum { + /* Identifier for the Com Data protocol */ + TL_PROTOCOLID_COM_DATA = 0, + + /* Identifier for the Com Control protocol */ + TL_PROTOCOLID_COM_CTRL = 1, + + /* Identifier for the Setup protocol */ + TL_PROTOCOLID_SETUP = 2 +}; + +/* Number of bytes in NL packet header (cannot do + * sizeof(nl_packet_header) since it's a bitfield) */ +#define NL_FIRST_PACKET_HEADER_SIZE 3 + +/* Number of bytes in NL packet header (cannot do + * sizeof(nl_packet_header) since it's a bitfield) */ +#define NL_FOLLOWING_PACKET_HEADER_SIZE 1 + +struct nl_first_packet_header { + unsigned char protocol:3; + unsigned char address:3; + unsigned char packet_rank:2; + unsigned char length_lsb; + unsigned char length_msb; +}; + +struct nl_packet_header { + unsigned char protocol:3; + unsigned char address:3; + unsigned char packet_rank:2; +}; + +/* Value of 'packet_rank' above */ +#define NL_INTERMEDIATE_PACKET 0x0 +#define NL_LAST_PACKET 0x1 +#define NL_FIRST_PACKET 0x2 + +union nl_packet { + /* Network packet header of the first packet (a special case) */ + struct nl_first_packet_header hdr_first; + /* Network packet header of the following packets (if any) */ + struct nl_packet_header hdr; + /* Complete network packet (header + data) */ + unsigned char rawpkt[LL_MTU_MAX]; +} __attribute__ ((__packed__)); + +#define HW_VERSION_UNKNOWN -1 +#define HW_VERSION_1 1 +#define HW_VERSION_2 2 + +/* IPW I/O ports */ +#define IOIER 0x00 /* Interrupt Enable Register */ +#define IOIR 0x02 /* Interrupt Source/ACK register */ +#define IODCR 0x04 /* Data Control Register */ +#define IODRR 0x06 /* Data Read Register */ +#define IODWR 0x08 /* Data Write Register */ +#define IOESR 0x0A /* Embedded Driver Status Register */ +#define IORXR 0x0C /* Rx Fifo Register (Host to Embedded) */ +#define IOTXR 0x0E /* Tx Fifo Register (Embedded to Host) */ + +/* I/O ports and bit definitions for version 1 of the hardware */ + +/* IER bits*/ +#define IER_RXENABLED 0x1 +#define IER_TXENABLED 0x2 + +/* ISR bits */ +#define IR_RXINTR 0x1 +#define IR_TXINTR 0x2 + +/* DCR bits */ +#define DCR_RXDONE 0x1 +#define DCR_TXDONE 0x2 +#define DCR_RXRESET 0x4 +#define DCR_TXRESET 0x8 + +/* I/O ports and bit definitions for version 2 of the hardware */ + +struct MEMCCR { + unsigned short reg_config_option; /* PCCOR: Configuration Option Register */ + unsigned short reg_config_and_status; /* PCCSR: Configuration and Status Register */ + unsigned short reg_pin_replacement; /* PCPRR: Pin Replacemant Register */ + unsigned short reg_socket_and_copy; /* PCSCR: Socket and Copy Register */ + unsigned short reg_ext_status; /* PCESR: Extendend Status Register */ + unsigned short reg_io_base; /* PCIOB: I/O Base Register */ +}; + +struct MEMINFREG { + unsigned short memreg_tx_old; /* TX Register (R/W) */ + unsigned short pad1; + unsigned short memreg_rx_done; /* RXDone Register (R/W) */ + unsigned short pad2; + unsigned short memreg_rx; /* RX Register (R/W) */ + unsigned short pad3; + unsigned short memreg_pc_interrupt_ack; /* PC intr Ack Register (W) */ + unsigned short pad4; + unsigned long memreg_card_present;/* Mask for Host to check (R) for + * CARD_PRESENT_VALUE */ + unsigned short memreg_tx_new; /* TX2 (new) Register (R/W) */ +}; + +#define CARD_PRESENT_VALUE (0xBEEFCAFEUL) + +#define MEMTX_TX 0x0001 +#define MEMRX_RX 0x0001 +#define MEMRX_RX_DONE 0x0001 +#define MEMRX_PCINTACKK 0x0001 + +#define NL_NUM_OF_PRIORITIES 3 +#define NL_NUM_OF_PROTOCOLS 3 +#define NL_NUM_OF_ADDRESSES NO_OF_IPW_CHANNELS + +struct ipw_hardware { + unsigned int base_port; + short hw_version; + unsigned short ll_mtu; + spinlock_t lock; + + int initializing; + int init_loops; + struct timer_list setup_timer; + + /* Flag if hw is ready to send next packet */ + int tx_ready; + /* Count of pending packets to be sent */ + int tx_queued; + struct list_head tx_queue[NL_NUM_OF_PRIORITIES]; + + int rx_bytes_queued; + struct list_head rx_queue; + /* Pool of rx_packet structures that are not currently used. */ + struct list_head rx_pool; + int rx_pool_size; + /* True if reception of data is blocked while userspace processes it. */ + int blocking_rx; + /* True if there is RX data ready on the hardware. */ + int rx_ready; + unsigned short last_memtx_serial; + /* + * Newer versions of the V2 card firmware send serial numbers in the + * MemTX register. 'serial_number_detected' is set true when we detect + * a non-zero serial number (indicating the new firmware). Thereafter, + * the driver can safely ignore the Timer Recovery re-sends to avoid + * out-of-sync problems. + */ + int serial_number_detected; + struct work_struct work_rx; + + /* True if we are to send the set-up data to the hardware. */ + int to_setup; + + /* Card has been removed */ + int removed; + /* Saved irq value when we disable the interrupt. */ + int irq; + /* True if this driver is shutting down. */ + int shutting_down; + /* Modem control lines */ + unsigned int control_lines[NL_NUM_OF_ADDRESSES]; + struct ipw_rx_packet *packet_assembler[NL_NUM_OF_ADDRESSES]; + + struct tasklet_struct tasklet; + + /* The handle for the network layer, for the sending of events to it. */ + struct ipw_network *network; + struct MEMINFREG __iomem *memory_info_regs; + struct MEMCCR __iomem *memregs_CCR; + void (*reboot_callback) (void *data); + void *reboot_callback_data; + + unsigned short __iomem *memreg_tx; +}; + +/* + * Packet info structure for tx packets. + * Note: not all the fields defined here are required for all protocols + */ +struct ipw_tx_packet { + struct list_head queue; + /* channel idx + 1 */ + unsigned char dest_addr; + /* SETUP, CTRL or DATA */ + unsigned char protocol; + /* Length of data block, which starts at the end of this structure */ + unsigned short length; + /* Sending state */ + /* Offset of where we've sent up to so far */ + unsigned long offset; + /* Count of packet fragments, starting at 0 */ + int fragment_count; + + /* Called after packet is sent and before is freed */ + void (*packet_callback) (void *cb_data, unsigned int packet_length); + void *callback_data; +}; + +/* Signals from DTE */ +#define COMCTRL_RTS 0 +#define COMCTRL_DTR 1 + +/* Signals from DCE */ +#define COMCTRL_CTS 2 +#define COMCTRL_DCD 3 +#define COMCTRL_DSR 4 +#define COMCTRL_RI 5 + +struct ipw_control_packet_body { + /* DTE signal or DCE signal */ + unsigned char sig_no; + /* 0: set signal, 1: clear signal */ + unsigned char value; +} __attribute__ ((__packed__)); + +struct ipw_control_packet { + struct ipw_tx_packet header; + struct ipw_control_packet_body body; +}; + +struct ipw_rx_packet { + struct list_head queue; + unsigned int capacity; + unsigned int length; + unsigned int protocol; + unsigned int channel_idx; +}; + +static char *data_type(const unsigned char *buf, unsigned length) +{ + struct nl_packet_header *hdr = (struct nl_packet_header *) buf; + + if (length == 0) + return " "; + + if (hdr->packet_rank & NL_FIRST_PACKET) { + switch (hdr->protocol) { + case TL_PROTOCOLID_COM_DATA: return "DATA "; + case TL_PROTOCOLID_COM_CTRL: return "CTRL "; + case TL_PROTOCOLID_SETUP: return "SETUP"; + default: return "???? "; + } + } else + return " "; +} + +#define DUMP_MAX_BYTES 64 + +static void dump_data_bytes(const char *type, const unsigned char *data, + unsigned length) +{ + char prefix[56]; + + sprintf(prefix, IPWIRELESS_PCCARD_NAME ": %s %s ", + type, data_type(data, length)); + print_hex_dump_bytes(prefix, 0, (void *)data, + length < DUMP_MAX_BYTES ? length : DUMP_MAX_BYTES); +} + +static void swap_packet_bitfield_to_le(unsigned char *data) +{ +#ifdef __BIG_ENDIAN_BITFIELD + unsigned char tmp = *data, ret = 0; + + /* + * transform bits from aa.bbb.ccc to ccc.bbb.aa + */ + ret |= tmp & 0xc0 >> 6; + ret |= tmp & 0x38 >> 1; + ret |= tmp & 0x07 << 5; + *data = ret & 0xff; +#endif +} + +static void swap_packet_bitfield_from_le(unsigned char *data) +{ +#ifdef __BIG_ENDIAN_BITFIELD + unsigned char tmp = *data, ret = 0; + + /* + * transform bits from ccc.bbb.aa to aa.bbb.ccc + */ + ret |= tmp & 0xe0 >> 5; + ret |= tmp & 0x1c << 1; + ret |= tmp & 0x03 << 6; + *data = ret & 0xff; +#endif +} + +static void do_send_fragment(struct ipw_hardware *hw, unsigned char *data, + unsigned length) +{ + unsigned i; + unsigned long flags; + + start_timing(); + BUG_ON(length > hw->ll_mtu); + + if (ipwireless_debug) + dump_data_bytes("send", data, length); + + spin_lock_irqsave(&hw->lock, flags); + + hw->tx_ready = 0; + swap_packet_bitfield_to_le(data); + + if (hw->hw_version == HW_VERSION_1) { + outw((unsigned short) length, hw->base_port + IODWR); + + for (i = 0; i < length; i += 2) { + unsigned short d = data[i]; + __le16 raw_data; + + if (i + 1 < length) + d |= data[i + 1] << 8; + raw_data = cpu_to_le16(d); + outw(raw_data, hw->base_port + IODWR); + } + + outw(DCR_TXDONE, hw->base_port + IODCR); + } else if (hw->hw_version == HW_VERSION_2) { + outw((unsigned short) length, hw->base_port); + + for (i = 0; i < length; i += 2) { + unsigned short d = data[i]; + __le16 raw_data; + + if (i + 1 < length) + d |= data[i + 1] << 8; + raw_data = cpu_to_le16(d); + outw(raw_data, hw->base_port); + } + while ((i & 3) != 2) { + outw((unsigned short) 0xDEAD, hw->base_port); + i += 2; + } + writew(MEMRX_RX, &hw->memory_info_regs->memreg_rx); + } + + spin_unlock_irqrestore(&hw->lock, flags); + + end_write_timing(length); +} + +static void do_send_packet(struct ipw_hardware *hw, struct ipw_tx_packet *packet) +{ + unsigned short fragment_data_len; + unsigned short data_left = packet->length - packet->offset; + unsigned short header_size; + union nl_packet pkt; + + header_size = + (packet->fragment_count == 0) + ? NL_FIRST_PACKET_HEADER_SIZE + : NL_FOLLOWING_PACKET_HEADER_SIZE; + fragment_data_len = hw->ll_mtu - header_size; + if (data_left < fragment_data_len) + fragment_data_len = data_left; + + /* + * hdr_first is now in machine bitfield order, which will be swapped + * to le just before it goes to hw + */ + pkt.hdr_first.protocol = packet->protocol; + pkt.hdr_first.address = packet->dest_addr; + pkt.hdr_first.packet_rank = 0; + + /* First packet? */ + if (packet->fragment_count == 0) { + pkt.hdr_first.packet_rank |= NL_FIRST_PACKET; + pkt.hdr_first.length_lsb = (unsigned char) packet->length; + pkt.hdr_first.length_msb = + (unsigned char) (packet->length >> 8); + } + + memcpy(pkt.rawpkt + header_size, + ((unsigned char *) packet) + sizeof(struct ipw_tx_packet) + + packet->offset, fragment_data_len); + packet->offset += fragment_data_len; + packet->fragment_count++; + + /* Last packet? (May also be first packet.) */ + if (packet->offset == packet->length) + pkt.hdr_first.packet_rank |= NL_LAST_PACKET; + do_send_fragment(hw, pkt.rawpkt, header_size + fragment_data_len); + + /* If this packet has unsent data, then re-queue it. */ + if (packet->offset < packet->length) { + /* + * Re-queue it at the head of the highest priority queue so + * it goes before all other packets + */ + unsigned long flags; + + spin_lock_irqsave(&hw->lock, flags); + list_add(&packet->queue, &hw->tx_queue[0]); + hw->tx_queued++; + spin_unlock_irqrestore(&hw->lock, flags); + } else { + if (packet->packet_callback) + packet->packet_callback(packet->callback_data, + packet->length); + kfree(packet); + } +} + +static void ipw_setup_hardware(struct ipw_hardware *hw) +{ + unsigned long flags; + + spin_lock_irqsave(&hw->lock, flags); + if (hw->hw_version == HW_VERSION_1) { + /* Reset RX FIFO */ + outw(DCR_RXRESET, hw->base_port + IODCR); + /* SB: Reset TX FIFO */ + outw(DCR_TXRESET, hw->base_port + IODCR); + + /* Enable TX and RX interrupts. */ + outw(IER_TXENABLED | IER_RXENABLED, hw->base_port + IOIER); + } else { + /* + * Set INTRACK bit (bit 0), which means we must explicitly + * acknowledge interrupts by clearing bit 2 of reg_config_and_status. + */ + unsigned short csr = readw(&hw->memregs_CCR->reg_config_and_status); + + csr |= 1; + writew(csr, &hw->memregs_CCR->reg_config_and_status); + } + spin_unlock_irqrestore(&hw->lock, flags); +} + +/* + * If 'packet' is NULL, then this function allocates a new packet, setting its + * length to 0 and ensuring it has the specified minimum amount of free space. + * + * If 'packet' is not NULL, then this function enlarges it if it doesn't + * have the specified minimum amount of free space. + * + */ +static struct ipw_rx_packet *pool_allocate(struct ipw_hardware *hw, + struct ipw_rx_packet *packet, + int minimum_free_space) +{ + + if (!packet) { + unsigned long flags; + + spin_lock_irqsave(&hw->lock, flags); + if (!list_empty(&hw->rx_pool)) { + packet = list_first_entry(&hw->rx_pool, + struct ipw_rx_packet, queue); + hw->rx_pool_size--; + spin_unlock_irqrestore(&hw->lock, flags); + list_del(&packet->queue); + } else { + const int min_capacity = + ipwireless_ppp_mru(hw->network) + 2; + int new_capacity; + + spin_unlock_irqrestore(&hw->lock, flags); + new_capacity = + (minimum_free_space > min_capacity + ? minimum_free_space + : min_capacity); + packet = kmalloc(sizeof(struct ipw_rx_packet) + + new_capacity, GFP_ATOMIC); + if (!packet) + return NULL; + packet->capacity = new_capacity; + } + packet->length = 0; + } + + if (packet->length + minimum_free_space > packet->capacity) { + struct ipw_rx_packet *old_packet = packet; + + packet = kmalloc(sizeof(struct ipw_rx_packet) + + old_packet->length + minimum_free_space, + GFP_ATOMIC); + if (!packet) { + kfree(old_packet); + return NULL; + } + memcpy(packet, old_packet, + sizeof(struct ipw_rx_packet) + + old_packet->length); + packet->capacity = old_packet->length + minimum_free_space; + kfree(old_packet); + } + + return packet; +} + +static void pool_free(struct ipw_hardware *hw, struct ipw_rx_packet *packet) +{ + if (hw->rx_pool_size > 6) + kfree(packet); + else { + hw->rx_pool_size++; + list_add(&packet->queue, &hw->rx_pool); + } +} + +static void queue_received_packet(struct ipw_hardware *hw, + unsigned int protocol, + unsigned int address, + const unsigned char *data, int length, + int is_last) +{ + unsigned int channel_idx = address - 1; + struct ipw_rx_packet *packet = NULL; + unsigned long flags; + + /* Discard packet if channel index is out of range. */ + if (channel_idx >= NL_NUM_OF_ADDRESSES) { + printk(KERN_INFO IPWIRELESS_PCCARD_NAME + ": data packet has bad address %u\n", address); + return; + } + + /* + * ->packet_assembler is safe to touch unlocked, this is the only place + */ + if (protocol == TL_PROTOCOLID_COM_DATA) { + struct ipw_rx_packet **assem = + &hw->packet_assembler[channel_idx]; + + /* + * Create a new packet, or assembler already contains one + * enlarge it by 'length' bytes. + */ + (*assem) = pool_allocate(hw, *assem, length); + if (!(*assem)) { + printk(KERN_ERR IPWIRELESS_PCCARD_NAME + ": no memory for incomming data packet, dropped!\n"); + return; + } + (*assem)->protocol = protocol; + (*assem)->channel_idx = channel_idx; + + /* Append this packet data onto existing data. */ + memcpy((unsigned char *)(*assem) + + sizeof(struct ipw_rx_packet) + + (*assem)->length, data, length); + (*assem)->length += length; + if (is_last) { + packet = *assem; + *assem = NULL; + /* Count queued DATA bytes only */ + spin_lock_irqsave(&hw->lock, flags); + hw->rx_bytes_queued += packet->length; + spin_unlock_irqrestore(&hw->lock, flags); + } + } else { + /* If it's a CTRL packet, don't assemble, just queue it. */ + packet = pool_allocate(hw, NULL, length); + if (!packet) { + printk(KERN_ERR IPWIRELESS_PCCARD_NAME + ": no memory for incomming ctrl packet, dropped!\n"); + return; + } + packet->protocol = protocol; + packet->channel_idx = channel_idx; + memcpy((unsigned char *)packet + sizeof(struct ipw_rx_packet), + data, length); + packet->length = length; + } + + /* + * If this is the last packet, then send the assembled packet on to the + * network layer. + */ + if (packet) { + spin_lock_irqsave(&hw->lock, flags); + list_add_tail(&packet->queue, &hw->rx_queue); + /* Block reception of incoming packets if queue is full. */ + hw->blocking_rx = + (hw->rx_bytes_queued >= IPWIRELESS_RX_QUEUE_SIZE); + + spin_unlock_irqrestore(&hw->lock, flags); + schedule_work(&hw->work_rx); + } +} + +/* + * Workqueue callback + */ +static void ipw_receive_data_work(struct work_struct *work_rx) +{ + struct ipw_hardware *hw = + container_of(work_rx, struct ipw_hardware, work_rx); + unsigned long flags; + + spin_lock_irqsave(&hw->lock, flags); + while (!list_empty(&hw->rx_queue)) { + struct ipw_rx_packet *packet = + list_first_entry(&hw->rx_queue, + struct ipw_rx_packet, queue); + + if (hw->shutting_down) + break; + list_del(&packet->queue); + + /* + * Note: ipwireless_network_packet_received must be called in a + * process context (i.e. via schedule_work) because the tty + * output code can sleep in the tty_flip_buffer_push call. + */ + if (packet->protocol == TL_PROTOCOLID_COM_DATA) { + if (hw->network != NULL) { + /* If the network hasn't been disconnected. */ + spin_unlock_irqrestore(&hw->lock, flags); + /* + * This must run unlocked due to tty processing + * and mutex locking + */ + ipwireless_network_packet_received( + hw->network, + packet->channel_idx, + (unsigned char *)packet + + sizeof(struct ipw_rx_packet), + packet->length); + spin_lock_irqsave(&hw->lock, flags); + } + /* Count queued DATA bytes only */ + hw->rx_bytes_queued -= packet->length; + } else { + /* + * This is safe to be called locked, callchain does + * not block + */ + handle_received_CTRL_packet(hw, packet->channel_idx, + (unsigned char *)packet + + sizeof(struct ipw_rx_packet), + packet->length); + } + pool_free(hw, packet); + /* + * Unblock reception of incoming packets if queue is no longer + * full. + */ + hw->blocking_rx = + hw->rx_bytes_queued >= IPWIRELESS_RX_QUEUE_SIZE; + if (hw->shutting_down) + break; + } + spin_unlock_irqrestore(&hw->lock, flags); +} + +static void handle_received_CTRL_packet(struct ipw_hardware *hw, + unsigned int channel_idx, + const unsigned char *data, int len) +{ + const struct ipw_control_packet_body *body = + (const struct ipw_control_packet_body *) data; + unsigned int changed_mask; + + if (len != sizeof(struct ipw_control_packet_body)) { + printk(KERN_INFO IPWIRELESS_PCCARD_NAME + ": control packet was %d bytes - wrong size!\n", + len); + return; + } + + switch (body->sig_no) { + case COMCTRL_CTS: + changed_mask = IPW_CONTROL_LINE_CTS; + break; + case COMCTRL_DCD: + changed_mask = IPW_CONTROL_LINE_DCD; + break; + case COMCTRL_DSR: + changed_mask = IPW_CONTROL_LINE_DSR; + break; + case COMCTRL_RI: + changed_mask = IPW_CONTROL_LINE_RI; + break; + default: + changed_mask = 0; + } + + if (changed_mask != 0) { + if (body->value) + hw->control_lines[channel_idx] |= changed_mask; + else + hw->control_lines[channel_idx] &= ~changed_mask; + if (hw->network) + ipwireless_network_notify_control_line_change( + hw->network, + channel_idx, + hw->control_lines[channel_idx], + changed_mask); + } +} + +static void handle_received_packet(struct ipw_hardware *hw, + const union nl_packet *packet, + unsigned short len) +{ + unsigned int protocol = packet->hdr.protocol; + unsigned int address = packet->hdr.address; + unsigned int header_length; + const unsigned char *data; + unsigned int data_len; + int is_last = packet->hdr.packet_rank & NL_LAST_PACKET; + + if (packet->hdr.packet_rank & NL_FIRST_PACKET) + header_length = NL_FIRST_PACKET_HEADER_SIZE; + else + header_length = NL_FOLLOWING_PACKET_HEADER_SIZE; + + data = packet->rawpkt + header_length; + data_len = len - header_length; + switch (protocol) { + case TL_PROTOCOLID_COM_DATA: + case TL_PROTOCOLID_COM_CTRL: + queue_received_packet(hw, protocol, address, data, data_len, + is_last); + break; + case TL_PROTOCOLID_SETUP: + handle_received_SETUP_packet(hw, address, data, data_len, + is_last); + break; + } +} + +static void acknowledge_data_read(struct ipw_hardware *hw) +{ + if (hw->hw_version == HW_VERSION_1) + outw(DCR_RXDONE, hw->base_port + IODCR); + else + writew(MEMRX_PCINTACKK, + &hw->memory_info_regs->memreg_pc_interrupt_ack); +} + +/* + * Retrieve a packet from the IPW hardware. + */ +static void do_receive_packet(struct ipw_hardware *hw) +{ + unsigned len; + unsigned i; + unsigned char pkt[LL_MTU_MAX]; + + start_timing(); + + if (hw->hw_version == HW_VERSION_1) { + len = inw(hw->base_port + IODRR); + if (len > hw->ll_mtu) { + printk(KERN_INFO IPWIRELESS_PCCARD_NAME + ": received a packet of %u bytes - longer than the MTU!\n", len); + outw(DCR_RXDONE | DCR_RXRESET, hw->base_port + IODCR); + return; + } + + for (i = 0; i < len; i += 2) { + __le16 raw_data = inw(hw->base_port + IODRR); + unsigned short data = le16_to_cpu(raw_data); + + pkt[i] = (unsigned char) data; + pkt[i + 1] = (unsigned char) (data >> 8); + } + } else { + len = inw(hw->base_port); + if (len > hw->ll_mtu) { + printk(KERN_INFO IPWIRELESS_PCCARD_NAME + ": received a packet of %u bytes - longer than the MTU!\n", len); + writew(MEMRX_PCINTACKK, + &hw->memory_info_regs->memreg_pc_interrupt_ack); + return; + } + + for (i = 0; i < len; i += 2) { + __le16 raw_data = inw(hw->base_port); + unsigned short data = le16_to_cpu(raw_data); + + pkt[i] = (unsigned char) data; + pkt[i + 1] = (unsigned char) (data >> 8); + } + + while ((i & 3) != 2) { + inw(hw->base_port); + i += 2; + } + } + + acknowledge_data_read(hw); + + swap_packet_bitfield_from_le(pkt); + + if (ipwireless_debug) + dump_data_bytes("recv", pkt, len); + + handle_received_packet(hw, (union nl_packet *) pkt, len); + + end_read_timing(len); +} + +static int get_current_packet_priority(struct ipw_hardware *hw) +{ + /* + * If we're initializing, don't send anything of higher priority than + * PRIO_SETUP. The network layer therefore need not care about + * hardware initialization - any of its stuff will simply be queued + * until setup is complete. + */ + return (hw->to_setup || hw->initializing + ? PRIO_SETUP + 1 : NL_NUM_OF_PRIORITIES); +} + +/* + * return 1 if something has been received from hw + */ +static int get_packets_from_hw(struct ipw_hardware *hw) +{ + int received = 0; + unsigned long flags; + + spin_lock_irqsave(&hw->lock, flags); + while (hw->rx_ready && !hw->blocking_rx) { + received = 1; + hw->rx_ready--; + spin_unlock_irqrestore(&hw->lock, flags); + + do_receive_packet(hw); + + spin_lock_irqsave(&hw->lock, flags); + } + spin_unlock_irqrestore(&hw->lock, flags); + + return received; +} + +/* + * Send pending packet up to given priority, prioritize SETUP data until + * hardware is fully setup. + * + * return 1 if more packets can be sent + */ +static int send_pending_packet(struct ipw_hardware *hw, int priority_limit) +{ + int more_to_send = 0; + unsigned long flags; + + spin_lock_irqsave(&hw->lock, flags); + if (hw->tx_queued && hw->tx_ready) { + int priority; + struct ipw_tx_packet *packet = NULL; + + /* Pick a packet */ + for (priority = 0; priority < priority_limit; priority++) { + if (!list_empty(&hw->tx_queue[priority])) { + packet = list_first_entry( + &hw->tx_queue[priority], + struct ipw_tx_packet, + queue); + + hw->tx_queued--; + list_del(&packet->queue); + + break; + } + } + if (!packet) { + hw->tx_queued = 0; + spin_unlock_irqrestore(&hw->lock, flags); + return 0; + } + + spin_unlock_irqrestore(&hw->lock, flags); + + /* Send */ + do_send_packet(hw, packet); + + /* Check if more to send */ + spin_lock_irqsave(&hw->lock, flags); + for (priority = 0; priority < priority_limit; priority++) + if (!list_empty(&hw->tx_queue[priority])) { + more_to_send = 1; + break; + } + + if (!more_to_send) + hw->tx_queued = 0; + } + spin_unlock_irqrestore(&hw->lock, flags); + + return more_to_send; +} + +/* + * Send and receive all queued packets. + */ +static void ipwireless_do_tasklet(unsigned long hw_) +{ + struct ipw_hardware *hw = (struct ipw_hardware *) hw_; + unsigned long flags; + + spin_lock_irqsave(&hw->lock, flags); + if (hw->shutting_down) { + spin_unlock_irqrestore(&hw->lock, flags); + return; + } + + if (hw->to_setup == 1) { + /* + * Initial setup data sent to hardware + */ + hw->to_setup = 2; + spin_unlock_irqrestore(&hw->lock, flags); + + ipw_setup_hardware(hw); + ipw_send_setup_packet(hw); + + send_pending_packet(hw, PRIO_SETUP + 1); + get_packets_from_hw(hw); + } else { + int priority_limit = get_current_packet_priority(hw); + int again; + + spin_unlock_irqrestore(&hw->lock, flags); + + do { + again = send_pending_packet(hw, priority_limit); + again |= get_packets_from_hw(hw); + } while (again); + } +} + +/* + * return true if the card is physically present. + */ +static int is_card_present(struct ipw_hardware *hw) +{ + if (hw->hw_version == HW_VERSION_1) + return inw(hw->base_port + IOIR) != 0xFFFF; + else + return readl(&hw->memory_info_regs->memreg_card_present) == + CARD_PRESENT_VALUE; +} + +static irqreturn_t ipwireless_handle_v1_interrupt(int irq, + struct ipw_hardware *hw) +{ + unsigned short irqn; + + irqn = inw(hw->base_port + IOIR); + + /* Check if card is present */ + if (irqn == 0xFFFF) + return IRQ_NONE; + else if (irqn != 0) { + unsigned short ack = 0; + unsigned long flags; + + /* Transmit complete. */ + if (irqn & IR_TXINTR) { + ack |= IR_TXINTR; + spin_lock_irqsave(&hw->lock, flags); + hw->tx_ready = 1; + spin_unlock_irqrestore(&hw->lock, flags); + } + /* Received data */ + if (irqn & IR_RXINTR) { + ack |= IR_RXINTR; + spin_lock_irqsave(&hw->lock, flags); + hw->rx_ready++; + spin_unlock_irqrestore(&hw->lock, flags); + } + if (ack != 0) { + outw(ack, hw->base_port + IOIR); + tasklet_schedule(&hw->tasklet); + } + return IRQ_HANDLED; + } + return IRQ_NONE; +} + +static void acknowledge_pcmcia_interrupt(struct ipw_hardware *hw) +{ + unsigned short csr = readw(&hw->memregs_CCR->reg_config_and_status); + + csr &= 0xfffd; + writew(csr, &hw->memregs_CCR->reg_config_and_status); +} + +static irqreturn_t ipwireless_handle_v2_v3_interrupt(int irq, + struct ipw_hardware *hw) +{ + int tx = 0; + int rx = 0; + int rx_repeat = 0; + int try_mem_tx_old; + unsigned long flags; + + do { + + unsigned short memtx = readw(hw->memreg_tx); + unsigned short memtx_serial; + unsigned short memrxdone = + readw(&hw->memory_info_regs->memreg_rx_done); + + try_mem_tx_old = 0; + + /* check whether the interrupt was generated by ipwireless card */ + if (!(memtx & MEMTX_TX) && !(memrxdone & MEMRX_RX_DONE)) { + + /* check if the card uses memreg_tx_old register */ + if (hw->memreg_tx == &hw->memory_info_regs->memreg_tx_new) { + memtx = readw(&hw->memory_info_regs->memreg_tx_old); + if (memtx & MEMTX_TX) { + printk(KERN_INFO IPWIRELESS_PCCARD_NAME + ": Using memreg_tx_old\n"); + hw->memreg_tx = + &hw->memory_info_regs->memreg_tx_old; + } else { + return IRQ_NONE; + } + } else + return IRQ_NONE; + } + + /* + * See if the card is physically present. Note that while it is + * powering up, it appears not to be present. + */ + if (!is_card_present(hw)) { + acknowledge_pcmcia_interrupt(hw); + return IRQ_HANDLED; + } + + memtx_serial = memtx & (unsigned short) 0xff00; + if (memtx & MEMTX_TX) { + writew(memtx_serial, hw->memreg_tx); + + if (hw->serial_number_detected) { + if (memtx_serial != hw->last_memtx_serial) { + hw->last_memtx_serial = memtx_serial; + spin_lock_irqsave(&hw->lock, flags); + hw->rx_ready++; + spin_unlock_irqrestore(&hw->lock, flags); + rx = 1; + } else + /* Ignore 'Timer Recovery' duplicates. */ + rx_repeat = 1; + } else { + /* + * If a non-zero serial number is seen, then enable + * serial number checking. + */ + if (memtx_serial != 0) { + hw->serial_number_detected = 1; + printk(KERN_DEBUG IPWIRELESS_PCCARD_NAME + ": memreg_tx serial num detected\n"); + + spin_lock_irqsave(&hw->lock, flags); + hw->rx_ready++; + spin_unlock_irqrestore(&hw->lock, flags); + } + rx = 1; + } + } + if (memrxdone & MEMRX_RX_DONE) { + writew(0, &hw->memory_info_regs->memreg_rx_done); + spin_lock_irqsave(&hw->lock, flags); + hw->tx_ready = 1; + spin_unlock_irqrestore(&hw->lock, flags); + tx = 1; + } + if (tx) + writew(MEMRX_PCINTACKK, + &hw->memory_info_regs->memreg_pc_interrupt_ack); + + acknowledge_pcmcia_interrupt(hw); + + if (tx || rx) + tasklet_schedule(&hw->tasklet); + else if (!rx_repeat) { + if (hw->memreg_tx == &hw->memory_info_regs->memreg_tx_new) { + if (hw->serial_number_detected) + printk(KERN_WARNING IPWIRELESS_PCCARD_NAME + ": spurious interrupt - new_tx mode\n"); + else { + printk(KERN_WARNING IPWIRELESS_PCCARD_NAME + ": no valid memreg_tx value - switching to the old memreg_tx\n"); + hw->memreg_tx = + &hw->memory_info_regs->memreg_tx_old; + try_mem_tx_old = 1; + } + } else + printk(KERN_WARNING IPWIRELESS_PCCARD_NAME + ": spurious interrupt - old_tx mode\n"); + } + + } while (try_mem_tx_old == 1); + + return IRQ_HANDLED; +} + +irqreturn_t ipwireless_interrupt(int irq, void *dev_id) +{ + struct ipw_hardware *hw = dev_id; + + if (hw->hw_version == HW_VERSION_1) + return ipwireless_handle_v1_interrupt(irq, hw); + else + return ipwireless_handle_v2_v3_interrupt(irq, hw); +} + +static void flush_packets_to_hw(struct ipw_hardware *hw) +{ + int priority_limit; + unsigned long flags; + + spin_lock_irqsave(&hw->lock, flags); + priority_limit = get_current_packet_priority(hw); + spin_unlock_irqrestore(&hw->lock, flags); + + while (send_pending_packet(hw, priority_limit)); +} + +static void send_packet(struct ipw_hardware *hw, int priority, + struct ipw_tx_packet *packet) +{ + unsigned long flags; + + spin_lock_irqsave(&hw->lock, flags); + list_add_tail(&packet->queue, &hw->tx_queue[priority]); + hw->tx_queued++; + spin_unlock_irqrestore(&hw->lock, flags); + + flush_packets_to_hw(hw); +} + +/* Create data packet, non-atomic allocation */ +static void *alloc_data_packet(int data_size, + unsigned char dest_addr, + unsigned char protocol) +{ + struct ipw_tx_packet *packet = kzalloc( + sizeof(struct ipw_tx_packet) + data_size, + GFP_ATOMIC); + + if (!packet) + return NULL; + + INIT_LIST_HEAD(&packet->queue); + packet->dest_addr = dest_addr; + packet->protocol = protocol; + packet->length = data_size; + + return packet; +} + +static void *alloc_ctrl_packet(int header_size, + unsigned char dest_addr, + unsigned char protocol, + unsigned char sig_no) +{ + /* + * sig_no is located right after ipw_tx_packet struct in every + * CTRL or SETUP packets, we can use ipw_control_packet as a + * common struct + */ + struct ipw_control_packet *packet = kzalloc(header_size, GFP_ATOMIC); + + if (!packet) + return NULL; + + INIT_LIST_HEAD(&packet->header.queue); + packet->header.dest_addr = dest_addr; + packet->header.protocol = protocol; + packet->header.length = header_size - sizeof(struct ipw_tx_packet); + packet->body.sig_no = sig_no; + + return packet; +} + +int ipwireless_send_packet(struct ipw_hardware *hw, unsigned int channel_idx, + const unsigned char *data, unsigned int length, + void (*callback) (void *cb, unsigned int length), + void *callback_data) +{ + struct ipw_tx_packet *packet; + + packet = alloc_data_packet(length, (channel_idx + 1), + TL_PROTOCOLID_COM_DATA); + if (!packet) + return -ENOMEM; + packet->packet_callback = callback; + packet->callback_data = callback_data; + memcpy((unsigned char *) packet + sizeof(struct ipw_tx_packet), data, + length); + + send_packet(hw, PRIO_DATA, packet); + return 0; +} + +static int set_control_line(struct ipw_hardware *hw, int prio, + unsigned int channel_idx, int line, int state) +{ + struct ipw_control_packet *packet; + int protocolid = TL_PROTOCOLID_COM_CTRL; + + if (prio == PRIO_SETUP) + protocolid = TL_PROTOCOLID_SETUP; + + packet = alloc_ctrl_packet(sizeof(struct ipw_control_packet), + (channel_idx + 1), protocolid, line); + if (!packet) + return -ENOMEM; + packet->header.length = sizeof(struct ipw_control_packet_body); + packet->body.value = (state == 0 ? 0 : 1); + send_packet(hw, prio, &packet->header); + return 0; +} + + +static int set_DTR(struct ipw_hardware *hw, int priority, + unsigned int channel_idx, int state) +{ + if (state != 0) + hw->control_lines[channel_idx] |= IPW_CONTROL_LINE_DTR; + else + hw->control_lines[channel_idx] &= ~IPW_CONTROL_LINE_DTR; + + return set_control_line(hw, priority, channel_idx, COMCTRL_DTR, state); +} + +static int set_RTS(struct ipw_hardware *hw, int priority, + unsigned int channel_idx, int state) +{ + if (state != 0) + hw->control_lines[channel_idx] |= IPW_CONTROL_LINE_RTS; + else + hw->control_lines[channel_idx] &= ~IPW_CONTROL_LINE_RTS; + + return set_control_line(hw, priority, channel_idx, COMCTRL_RTS, state); +} + +int ipwireless_set_DTR(struct ipw_hardware *hw, unsigned int channel_idx, + int state) +{ + return set_DTR(hw, PRIO_CTRL, channel_idx, state); +} + +int ipwireless_set_RTS(struct ipw_hardware *hw, unsigned int channel_idx, + int state) +{ + return set_RTS(hw, PRIO_CTRL, channel_idx, state); +} + +struct ipw_setup_get_version_query_packet { + struct ipw_tx_packet header; + struct tl_setup_get_version_qry body; +}; + +struct ipw_setup_config_packet { + struct ipw_tx_packet header; + struct tl_setup_config_msg body; +}; + +struct ipw_setup_config_done_packet { + struct ipw_tx_packet header; + struct tl_setup_config_done_msg body; +}; + +struct ipw_setup_open_packet { + struct ipw_tx_packet header; + struct tl_setup_open_msg body; +}; + +struct ipw_setup_info_packet { + struct ipw_tx_packet header; + struct tl_setup_info_msg body; +}; + +struct ipw_setup_reboot_msg_ack { + struct ipw_tx_packet header; + struct TlSetupRebootMsgAck body; +}; + +/* This handles the actual initialization of the card */ +static void __handle_setup_get_version_rsp(struct ipw_hardware *hw) +{ + struct ipw_setup_config_packet *config_packet; + struct ipw_setup_config_done_packet *config_done_packet; + struct ipw_setup_open_packet *open_packet; + struct ipw_setup_info_packet *info_packet; + int port; + unsigned int channel_idx; + + /* generate config packet */ + for (port = 1; port <= NL_NUM_OF_ADDRESSES; port++) { + config_packet = alloc_ctrl_packet( + sizeof(struct ipw_setup_config_packet), + ADDR_SETUP_PROT, + TL_PROTOCOLID_SETUP, + TL_SETUP_SIGNO_CONFIG_MSG); + if (!config_packet) + goto exit_nomem; + config_packet->header.length = sizeof(struct tl_setup_config_msg); + config_packet->body.port_no = port; + config_packet->body.prio_data = PRIO_DATA; + config_packet->body.prio_ctrl = PRIO_CTRL; + send_packet(hw, PRIO_SETUP, &config_packet->header); + } + config_done_packet = alloc_ctrl_packet( + sizeof(struct ipw_setup_config_done_packet), + ADDR_SETUP_PROT, + TL_PROTOCOLID_SETUP, + TL_SETUP_SIGNO_CONFIG_DONE_MSG); + if (!config_done_packet) + goto exit_nomem; + config_done_packet->header.length = sizeof(struct tl_setup_config_done_msg); + send_packet(hw, PRIO_SETUP, &config_done_packet->header); + + /* generate open packet */ + for (port = 1; port <= NL_NUM_OF_ADDRESSES; port++) { + open_packet = alloc_ctrl_packet( + sizeof(struct ipw_setup_open_packet), + ADDR_SETUP_PROT, + TL_PROTOCOLID_SETUP, + TL_SETUP_SIGNO_OPEN_MSG); + if (!open_packet) + goto exit_nomem; + open_packet->header.length = sizeof(struct tl_setup_open_msg); + open_packet->body.port_no = port; + send_packet(hw, PRIO_SETUP, &open_packet->header); + } + for (channel_idx = 0; + channel_idx < NL_NUM_OF_ADDRESSES; channel_idx++) { + int ret; + + ret = set_DTR(hw, PRIO_SETUP, channel_idx, + (hw->control_lines[channel_idx] & + IPW_CONTROL_LINE_DTR) != 0); + if (ret) { + printk(KERN_ERR IPWIRELESS_PCCARD_NAME + ": error setting DTR (%d)\n", ret); + return; + } + + set_RTS(hw, PRIO_SETUP, channel_idx, + (hw->control_lines [channel_idx] & + IPW_CONTROL_LINE_RTS) != 0); + if (ret) { + printk(KERN_ERR IPWIRELESS_PCCARD_NAME + ": error setting RTS (%d)\n", ret); + return; + } + } + /* + * For NDIS we assume that we are using sync PPP frames, for COM async. + * This driver uses NDIS mode too. We don't bother with translation + * from async -> sync PPP. + */ + info_packet = alloc_ctrl_packet(sizeof(struct ipw_setup_info_packet), + ADDR_SETUP_PROT, + TL_PROTOCOLID_SETUP, + TL_SETUP_SIGNO_INFO_MSG); + if (!info_packet) + goto exit_nomem; + info_packet->header.length = sizeof(struct tl_setup_info_msg); + info_packet->body.driver_type = NDISWAN_DRIVER; + info_packet->body.major_version = NDISWAN_DRIVER_MAJOR_VERSION; + info_packet->body.minor_version = NDISWAN_DRIVER_MINOR_VERSION; + send_packet(hw, PRIO_SETUP, &info_packet->header); + + /* Initialization is now complete, so we clear the 'to_setup' flag */ + hw->to_setup = 0; + + return; + +exit_nomem: + printk(KERN_ERR IPWIRELESS_PCCARD_NAME + ": not enough memory to alloc control packet\n"); + hw->to_setup = -1; +} + +static void handle_setup_get_version_rsp(struct ipw_hardware *hw, + unsigned char vers_no) +{ + del_timer(&hw->setup_timer); + hw->initializing = 0; + printk(KERN_INFO IPWIRELESS_PCCARD_NAME ": card is ready.\n"); + + if (vers_no == TL_SETUP_VERSION) + __handle_setup_get_version_rsp(hw); + else + printk(KERN_ERR IPWIRELESS_PCCARD_NAME + ": invalid hardware version no %u\n", + (unsigned int) vers_no); +} + +static void ipw_send_setup_packet(struct ipw_hardware *hw) +{ + struct ipw_setup_get_version_query_packet *ver_packet; + + ver_packet = alloc_ctrl_packet( + sizeof(struct ipw_setup_get_version_query_packet), + ADDR_SETUP_PROT, TL_PROTOCOLID_SETUP, + TL_SETUP_SIGNO_GET_VERSION_QRY); + ver_packet->header.length = sizeof(struct tl_setup_get_version_qry); + + /* + * Response is handled in handle_received_SETUP_packet + */ + send_packet(hw, PRIO_SETUP, &ver_packet->header); +} + +static void handle_received_SETUP_packet(struct ipw_hardware *hw, + unsigned int address, + const unsigned char *data, int len, + int is_last) +{ + const union ipw_setup_rx_msg *rx_msg = (const union ipw_setup_rx_msg *) data; + + if (address != ADDR_SETUP_PROT) { + printk(KERN_INFO IPWIRELESS_PCCARD_NAME + ": setup packet has bad address %d\n", address); + return; + } + + switch (rx_msg->sig_no) { + case TL_SETUP_SIGNO_GET_VERSION_RSP: + if (hw->to_setup) + handle_setup_get_version_rsp(hw, + rx_msg->version_rsp_msg.version); + break; + + case TL_SETUP_SIGNO_OPEN_MSG: + if (ipwireless_debug) { + unsigned int channel_idx = rx_msg->open_msg.port_no - 1; + + printk(KERN_INFO IPWIRELESS_PCCARD_NAME + ": OPEN_MSG [channel %u] reply received\n", + channel_idx); + } + break; + + case TL_SETUP_SIGNO_INFO_MSG_ACK: + if (ipwireless_debug) + printk(KERN_DEBUG IPWIRELESS_PCCARD_NAME + ": card successfully configured as NDISWAN\n"); + break; + + case TL_SETUP_SIGNO_REBOOT_MSG: + if (hw->to_setup) + printk(KERN_DEBUG IPWIRELESS_PCCARD_NAME + ": Setup not completed - ignoring reboot msg\n"); + else { + struct ipw_setup_reboot_msg_ack *packet; + + printk(KERN_DEBUG IPWIRELESS_PCCARD_NAME + ": Acknowledging REBOOT message\n"); + packet = alloc_ctrl_packet( + sizeof(struct ipw_setup_reboot_msg_ack), + ADDR_SETUP_PROT, TL_PROTOCOLID_SETUP, + TL_SETUP_SIGNO_REBOOT_MSG_ACK); + packet->header.length = + sizeof(struct TlSetupRebootMsgAck); + send_packet(hw, PRIO_SETUP, &packet->header); + if (hw->reboot_callback) + hw->reboot_callback(hw->reboot_callback_data); + } + break; + + default: + printk(KERN_INFO IPWIRELESS_PCCARD_NAME + ": unknown setup message %u received\n", + (unsigned int) rx_msg->sig_no); + } +} + +static void do_close_hardware(struct ipw_hardware *hw) +{ + unsigned int irqn; + + if (hw->hw_version == HW_VERSION_1) { + /* Disable TX and RX interrupts. */ + outw(0, hw->base_port + IOIER); + + /* Acknowledge any outstanding interrupt requests */ + irqn = inw(hw->base_port + IOIR); + if (irqn & IR_TXINTR) + outw(IR_TXINTR, hw->base_port + IOIR); + if (irqn & IR_RXINTR) + outw(IR_RXINTR, hw->base_port + IOIR); + + synchronize_irq(hw->irq); + } +} + +struct ipw_hardware *ipwireless_hardware_create(void) +{ + int i; + struct ipw_hardware *hw = + kzalloc(sizeof(struct ipw_hardware), GFP_KERNEL); + + if (!hw) + return NULL; + + hw->irq = -1; + hw->initializing = 1; + hw->tx_ready = 1; + hw->rx_bytes_queued = 0; + hw->rx_pool_size = 0; + hw->last_memtx_serial = (unsigned short) 0xffff; + for (i = 0; i < NL_NUM_OF_PRIORITIES; i++) + INIT_LIST_HEAD(&hw->tx_queue[i]); + + INIT_LIST_HEAD(&hw->rx_queue); + INIT_LIST_HEAD(&hw->rx_pool); + spin_lock_init(&hw->lock); + tasklet_init(&hw->tasklet, ipwireless_do_tasklet, (unsigned long) hw); + INIT_WORK(&hw->work_rx, ipw_receive_data_work); + setup_timer(&hw->setup_timer, ipwireless_setup_timer, + (unsigned long) hw); + + return hw; +} + +void ipwireless_init_hardware_v1(struct ipw_hardware *hw, + unsigned int base_port, + void __iomem *attr_memory, + void __iomem *common_memory, + int is_v2_card, + void (*reboot_callback) (void *data), + void *reboot_callback_data) +{ + if (hw->removed) { + hw->removed = 0; + enable_irq(hw->irq); + } + hw->base_port = base_port; + hw->hw_version = (is_v2_card ? HW_VERSION_2 : HW_VERSION_1); + hw->ll_mtu = (hw->hw_version == HW_VERSION_1 ? LL_MTU_V1 : LL_MTU_V2); + hw->memregs_CCR = (struct MEMCCR __iomem *) + ((unsigned short __iomem *) attr_memory + 0x200); + hw->memory_info_regs = (struct MEMINFREG __iomem *) common_memory; + hw->memreg_tx = &hw->memory_info_regs->memreg_tx_new; + hw->reboot_callback = reboot_callback; + hw->reboot_callback_data = reboot_callback_data; +} + +void ipwireless_init_hardware_v2_v3(struct ipw_hardware *hw) +{ + hw->initializing = 1; + hw->init_loops = 0; + printk(KERN_INFO IPWIRELESS_PCCARD_NAME + ": waiting for card to start up...\n"); + ipwireless_setup_timer((unsigned long) hw); +} + +static void ipwireless_setup_timer(unsigned long data) +{ + struct ipw_hardware *hw = (struct ipw_hardware *) data; + + hw->init_loops++; + + if (hw->init_loops == TL_SETUP_MAX_VERSION_QRY && + hw->hw_version == HW_VERSION_2 && + hw->memreg_tx == &hw->memory_info_regs->memreg_tx_new) { + printk(KERN_INFO IPWIRELESS_PCCARD_NAME + ": failed to startup using TX2, trying TX\n"); + + hw->memreg_tx = &hw->memory_info_regs->memreg_tx_old; + hw->init_loops = 0; + } + /* Give up after a certain number of retries */ + if (hw->init_loops == TL_SETUP_MAX_VERSION_QRY) { + printk(KERN_INFO IPWIRELESS_PCCARD_NAME + ": card failed to start up!\n"); + hw->initializing = 0; + } else { + /* Do not attempt to write to the board if it is not present. */ + if (is_card_present(hw)) { + unsigned long flags; + + spin_lock_irqsave(&hw->lock, flags); + hw->to_setup = 1; + hw->tx_ready = 1; + spin_unlock_irqrestore(&hw->lock, flags); + tasklet_schedule(&hw->tasklet); + } + + mod_timer(&hw->setup_timer, + jiffies + msecs_to_jiffies(TL_SETUP_VERSION_QRY_TMO)); + } +} + +/* + * Stop any interrupts from executing so that, once this function returns, + * other layers of the driver can be sure they won't get any more callbacks. + * Thus must be called on a proper process context. + */ +void ipwireless_stop_interrupts(struct ipw_hardware *hw) +{ + if (!hw->shutting_down) { + /* Tell everyone we are going down. */ + hw->shutting_down = 1; + del_timer(&hw->setup_timer); + + /* Prevent the hardware from sending any more interrupts */ + do_close_hardware(hw); + } +} + +void ipwireless_hardware_free(struct ipw_hardware *hw) +{ + int i; + struct ipw_rx_packet *rp, *rq; + struct ipw_tx_packet *tp, *tq; + + ipwireless_stop_interrupts(hw); + + flush_scheduled_work(); + + for (i = 0; i < NL_NUM_OF_ADDRESSES; i++) + if (hw->packet_assembler[i] != NULL) + kfree(hw->packet_assembler[i]); + + for (i = 0; i < NL_NUM_OF_PRIORITIES; i++) + list_for_each_entry_safe(tp, tq, &hw->tx_queue[i], queue) { + list_del(&tp->queue); + kfree(tp); + } + + list_for_each_entry_safe(rp, rq, &hw->rx_queue, queue) { + list_del(&rp->queue); + kfree(rp); + } + + list_for_each_entry_safe(rp, rq, &hw->rx_pool, queue) { + list_del(&rp->queue); + kfree(rp); + } + kfree(hw); +} + +/* + * Associate the specified network with this hardware, so it will receive events + * from it. + */ +void ipwireless_associate_network(struct ipw_hardware *hw, + struct ipw_network *network) +{ + hw->network = network; +} diff --git a/drivers/char/pcmcia/ipwireless/hardware.h b/drivers/char/pcmcia/ipwireless/hardware.h new file mode 100644 index 0000000..90a8590 --- /dev/null +++ b/drivers/char/pcmcia/ipwireless/hardware.h @@ -0,0 +1,62 @@ +/* + * IPWireless 3G PCMCIA Network Driver + * + * Original code + * by Stephen Blackheath <stephen@blacksapphire.com>, + * Ben Martel <benm@symmetric.co.nz> + * + * Copyrighted as follows: + * Copyright (C) 2004 by Symmetric Systems Ltd (NZ) + * + * Various driver changes and rewrites, port to new kernels + * Copyright (C) 2006-2007 Jiri Kosina + * + * Misc code cleanups and updates + * Copyright (C) 2007 David Sterba + */ + +#ifndef _IPWIRELESS_CS_HARDWARE_H_ +#define _IPWIRELESS_CS_HARDWARE_H_ + +#include <linux/types.h> +#include <linux/sched.h> +#include <linux/interrupt.h> + +#define IPW_CONTROL_LINE_CTS 0x0001 +#define IPW_CONTROL_LINE_DCD 0x0002 +#define IPW_CONTROL_LINE_DSR 0x0004 +#define IPW_CONTROL_LINE_RI 0x0008 +#define IPW_CONTROL_LINE_DTR 0x0010 +#define IPW_CONTROL_LINE_RTS 0x0020 + +struct ipw_hardware; +struct ipw_network; + +struct ipw_hardware *ipwireless_hardware_create(void); +void ipwireless_hardware_free(struct ipw_hardware *hw); +irqreturn_t ipwireless_interrupt(int irq, void *dev_id); +int ipwireless_set_DTR(struct ipw_hardware *hw, unsigned int channel_idx, + int state); +int ipwireless_set_RTS(struct ipw_hardware *hw, unsigned int channel_idx, + int state); +int ipwireless_send_packet(struct ipw_hardware *hw, + unsigned int channel_idx, + const unsigned char *data, + unsigned int length, + void (*packet_sent_callback) (void *cb, + unsigned int length), + void *sent_cb_data); +void ipwireless_associate_network(struct ipw_hardware *hw, + struct ipw_network *net); +void ipwireless_stop_interrupts(struct ipw_hardware *hw); +void ipwireless_init_hardware_v1(struct ipw_hardware *hw, + unsigned int base_port, + void __iomem *attr_memory, + void __iomem *common_memory, + int is_v2_card, + void (*reboot_cb) (void *data), + void *reboot_cb_data); +void ipwireless_init_hardware_v2_v3(struct ipw_hardware *hw); +void ipwireless_sleep(unsigned int tenths); + +#endif diff --git a/drivers/char/pcmcia/ipwireless/main.c b/drivers/char/pcmcia/ipwireless/main.c new file mode 100644 index 0000000..5216fce --- /dev/null +++ b/drivers/char/pcmcia/ipwireless/main.c @@ -0,0 +1,500 @@ +/* + * IPWireless 3G PCMCIA Network Driver + * + * Original code + * by Stephen Blackheath <stephen@blacksapphire.com>, + * Ben Martel <benm@symmetric.co.nz> + * + * Copyrighted as follows: + * Copyright (C) 2004 by Symmetric Systems Ltd (NZ) + * + * Various driver changes and rewrites, port to new kernels + * Copyright (C) 2006-2007 Jiri Kosina + * + * Misc code cleanups and updates + * Copyright (C) 2007 David Sterba + */ + +#include "hardware.h" +#include "network.h" +#include "main.h" +#include "tty.h" + +#include <linux/delay.h> +#include <linux/init.h> +#include <linux/io.h> +#include <linux/kernel.h> +#include <linux/module.h> +#include <linux/sched.h> +#include <linux/slab.h> + +#include <pcmcia/cisreg.h> +#include <pcmcia/device_id.h> +#include <pcmcia/ss.h> +#include <pcmcia/ds.h> +#include <pcmcia/cs.h> + +static struct pcmcia_device_id ipw_ids[] = { + PCMCIA_DEVICE_MANF_CARD(0x02f2, 0x0100), + PCMCIA_DEVICE_MANF_CARD(0x02f2, 0x0200), + PCMCIA_DEVICE_NULL +}; +MODULE_DEVICE_TABLE(pcmcia, ipw_ids); + +static void ipwireless_detach(struct pcmcia_device *link); + +/* + * Module params + */ +/* Debug mode: more verbose, print sent/recv bytes */ +int ipwireless_debug; +int ipwireless_loopback; +int ipwireless_out_queue = 10; + +module_param_named(debug, ipwireless_debug, int, 0); +module_param_named(loopback, ipwireless_loopback, int, 0); +module_param_named(out_queue, ipwireless_out_queue, int, 0); +MODULE_PARM_DESC(debug, "switch on debug messages [0]"); +MODULE_PARM_DESC(loopback, + "debug: enable ras_raw channel [0]"); +MODULE_PARM_DESC(out_queue, "debug: set size of outgoing PPP queue [10]"); + +/* Executes in process context. */ +static void signalled_reboot_work(struct work_struct *work_reboot) +{ + struct ipw_dev *ipw = container_of(work_reboot, struct ipw_dev, + work_reboot); + struct pcmcia_device *link = ipw->link; + int ret = pcmcia_reset_card(link->socket); + + if (ret != 0) + cs_error(link, ResetCard, ret); +} + +static void signalled_reboot_callback(void *callback_data) +{ + struct ipw_dev *ipw = (struct ipw_dev *) callback_data; + + /* Delegate to process context. */ + schedule_work(&ipw->work_reboot); +} + +static int config_ipwireless(struct ipw_dev *ipw) +{ + struct pcmcia_device *link = ipw->link; + int ret; + tuple_t tuple; + unsigned short buf[64]; + cisparse_t parse; + unsigned short cor_value; + memreq_t memreq_attr_memory; + memreq_t memreq_common_memory; + + ipw->is_v2_card = 0; + + tuple.Attributes = 0; + tuple.TupleData = (cisdata_t *) buf; + tuple.TupleDataMax = sizeof(buf); + tuple.TupleOffset = 0; + + tuple.DesiredTuple = RETURN_FIRST_TUPLE; + + ret = pcmcia_get_first_tuple(link, &tuple); + + while (ret == 0) { + ret = pcmcia_get_tuple_data(link, &tuple); + + if (ret != 0) { + cs_error(link, GetTupleData, ret); + goto exit0; + } + ret = pcmcia_get_next_tuple(link, &tuple); + } + + tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY; + + ret = pcmcia_get_first_tuple(link, &tuple); + + if (ret != 0) { + cs_error(link, GetFirstTuple, ret); + goto exit0; + } + + ret = pcmcia_get_tuple_data(link, &tuple); + + if (ret != 0) { + cs_error(link, GetTupleData, ret); + goto exit0; + } + + ret = pcmcia_parse_tuple(&tuple, &parse); + + if (ret != 0) { + cs_error(link, ParseTuple, ret); + goto exit0; + } + + link->io.Attributes1 = IO_DATA_PATH_WIDTH_AUTO; + link->io.BasePort1 = parse.cftable_entry.io.win[0].base; + link->io.NumPorts1 = parse.cftable_entry.io.win[0].len; + link->io.IOAddrLines = 16; + + link->irq.IRQInfo1 = parse.cftable_entry.irq.IRQInfo1; + + /* 0x40 causes it to generate level mode interrupts. */ + /* 0x04 enables IREQ pin. */ + cor_value = parse.cftable_entry.index | 0x44; + link->conf.ConfigIndex = cor_value; + + /* IRQ and I/O settings */ + tuple.DesiredTuple = CISTPL_CONFIG; + + ret = pcmcia_get_first_tuple(link, &tuple); + + if (ret != 0) { + cs_error(link, GetFirstTuple, ret); + goto exit0; + } + + ret = pcmcia_get_tuple_data(link, &tuple); + + if (ret != 0) { + cs_error(link, GetTupleData, ret); + goto exit0; + } + + ret = pcmcia_parse_tuple(&tuple, &parse); + + if (ret != 0) { + cs_error(link, GetTupleData, ret); + goto exit0; + } + link->conf.Attributes = CONF_ENABLE_IRQ; + link->conf.ConfigBase = parse.config.base; + link->conf.Present = parse.config.rmask[0]; + link->conf.IntType = INT_MEMORY_AND_IO; + + link->irq.Attributes = IRQ_TYPE_DYNAMIC_SHARING | IRQ_HANDLE_PRESENT; + link->irq.Handler = ipwireless_interrupt; + link->irq.Instance = ipw->hardware; + + ret = pcmcia_request_io(link, &link->io); + + if (ret != 0) { + cs_error(link, RequestIO, ret); + goto exit0; + } + + request_region(link->io.BasePort1, link->io.NumPorts1, + IPWIRELESS_PCCARD_NAME); + + /* memory settings */ + + tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY; + + ret = pcmcia_get_first_tuple(link, &tuple); + + if (ret != 0) { + cs_error(link, GetFirstTuple, ret); + goto exit1; + } + + ret = pcmcia_get_tuple_data(link, &tuple); + + if (ret != 0) { + cs_error(link, GetTupleData, ret); + goto exit1; + } + + ret = pcmcia_parse_tuple(&tuple, &parse); + + if (ret != 0) { + cs_error(link, ParseTuple, ret); + goto exit1; + } + + if (parse.cftable_entry.mem.nwin > 0) { + ipw->request_common_memory.Attributes = + WIN_DATA_WIDTH_16 | WIN_MEMORY_TYPE_CM | WIN_ENABLE; + ipw->request_common_memory.Base = + parse.cftable_entry.mem.win[0].host_addr; + ipw->request_common_memory.Size = parse.cftable_entry.mem.win[0].len; + if (ipw->request_common_memory.Size < 0x1000) + ipw->request_common_memory.Size = 0x1000; + ipw->request_common_memory.AccessSpeed = 0; + + ret = pcmcia_request_window(&link, &ipw->request_common_memory, + &ipw->handle_common_memory); + + if (ret != 0) { + cs_error(link, RequestWindow, ret); + goto exit1; + } + + memreq_common_memory.CardOffset = + parse.cftable_entry.mem.win[0].card_addr; + memreq_common_memory.Page = 0; + + ret = pcmcia_map_mem_page(ipw->handle_common_memory, + &memreq_common_memory); + + if (ret != 0) { + cs_error(link, MapMemPage, ret); + goto exit1; + } + + ipw->is_v2_card = + parse.cftable_entry.mem.win[0].len == 0x100; + + ipw->common_memory = ioremap(ipw->request_common_memory.Base, + ipw->request_common_memory.Size); + request_mem_region(ipw->request_common_memory.Base, + ipw->request_common_memory.Size, IPWIRELESS_PCCARD_NAME); + + ipw->request_attr_memory.Attributes = + WIN_DATA_WIDTH_16 | WIN_MEMORY_TYPE_AM | WIN_ENABLE; + ipw->request_attr_memory.Base = 0; + ipw->request_attr_memory.Size = 0; /* this used to be 0x1000 */ + ipw->request_attr_memory.AccessSpeed = 0; + + ret = pcmcia_request_window(&link, &ipw->request_attr_memory, + &ipw->handle_attr_memory); + + if (ret != 0) { + cs_error(link, RequestWindow, ret); + goto exit2; + } + + memreq_attr_memory.CardOffset = 0; + memreq_attr_memory.Page = 0; + + ret = pcmcia_map_mem_page(ipw->handle_attr_memory, + &memreq_attr_memory); + + if (ret != 0) { + cs_error(link, MapMemPage, ret); + goto exit2; + } + + ipw->attr_memory = ioremap(ipw->request_attr_memory.Base, + ipw->request_attr_memory.Size); + request_mem_region(ipw->request_attr_memory.Base, ipw->request_attr_memory.Size, + IPWIRELESS_PCCARD_NAME); + } + + INIT_WORK(&ipw->work_reboot, signalled_reboot_work); + + ipwireless_init_hardware_v1(ipw->hardware, link->io.BasePort1, + ipw->attr_memory, ipw->common_memory, + ipw->is_v2_card, signalled_reboot_callback, + ipw); + + ret = pcmcia_request_irq(link, &link->irq); + + if (ret != 0) { + cs_error(link, RequestIRQ, ret); + goto exit3; + } + + printk(KERN_INFO IPWIRELESS_PCCARD_NAME ": Card type %s\n", + ipw->is_v2_card ? "V2/V3" : "V1"); + printk(KERN_INFO IPWIRELESS_PCCARD_NAME + ": I/O ports 0x%04x-0x%04x, irq %d\n", + (unsigned int) link->io.BasePort1, + (unsigned int) (link->io.BasePort1 + + link->io.NumPorts1 - 1), + (unsigned int) link->irq.AssignedIRQ); + if (ipw->attr_memory && ipw->common_memory) + printk(KERN_INFO IPWIRELESS_PCCARD_NAME + ": attr memory 0x%08lx-0x%08lx, common memory 0x%08lx-0x%08lx\n", + ipw->request_attr_memory.Base, + ipw->request_attr_memory.Base + + ipw->request_attr_memory.Size - 1, + ipw->request_common_memory.Base, + ipw->request_common_memory.Base + + ipw->request_common_memory.Size - 1); + + ipw->network = ipwireless_network_create(ipw->hardware); + if (!ipw->network) + goto exit3; + + ipw->tty = ipwireless_tty_create(ipw->hardware, ipw->network, + ipw->nodes); + if (!ipw->tty) + goto exit3; + + ipwireless_init_hardware_v2_v3(ipw->hardware); + + /* + * Do the RequestConfiguration last, because it enables interrupts. + * Then we don't get any interrupts before we're ready for them. + */ + ret = pcmcia_request_configuration(link, &link->conf); + + if (ret != 0) { + cs_error(link, RequestConfiguration, ret); + goto exit4; + } + + link->dev_node = &ipw->nodes[0]; + + return 0; + +exit4: + pcmcia_disable_device(link); +exit3: + if (ipw->attr_memory) { + release_mem_region(ipw->request_attr_memory.Base, + ipw->request_attr_memory.Size); + iounmap(ipw->attr_memory); + pcmcia_release_window(ipw->handle_attr_memory); + pcmcia_disable_device(link); + } +exit2: + if (ipw->common_memory) { + release_mem_region(ipw->request_common_memory.Base, + ipw->request_common_memory.Size); + iounmap(ipw->common_memory); + pcmcia_release_window(ipw->handle_common_memory); + } +exit1: + pcmcia_disable_device(link); +exit0: + return -1; +} + +static void release_ipwireless(struct ipw_dev *ipw) +{ + pcmcia_disable_device(ipw->link); + + if (ipw->common_memory) { + release_mem_region(ipw->request_common_memory.Base, + ipw->request_common_memory.Size); + iounmap(ipw->common_memory); + } + if (ipw->attr_memory) { + release_mem_region(ipw->request_attr_memory.Base, + ipw->request_attr_memory.Size); + iounmap(ipw->attr_memory); + } + if (ipw->common_memory) + pcmcia_release_window(ipw->handle_common_memory); + if (ipw->attr_memory) + pcmcia_release_window(ipw->handle_attr_memory); + + /* Break the link with Card Services */ + pcmcia_disable_device(ipw->link); +} + +/* + * ipwireless_attach() creates an "instance" of the driver, allocating + * local data structures for one device (one interface). The device + * is registered with Card Services. + * + * The pcmcia_device structure is initialized, but we don't actually + * configure the card at this point -- we wait until we receive a + * card insertion event. + */ +static int ipwireless_attach(struct pcmcia_device *link) +{ + struct ipw_dev *ipw; + int ret; + + ipw = kzalloc(sizeof(struct ipw_dev), GFP_KERNEL); + if (!ipw) + return -ENOMEM; + + ipw->link = link; + link->priv = ipw; + link->irq.Instance = ipw; + + /* Link this device into our device list. */ + link->dev_node = &ipw->nodes[0]; + + ipw->hardware = ipwireless_hardware_create(); + if (!ipw->hardware) { + kfree(ipw); + return -ENOMEM; + } + /* RegisterClient will call config_ipwireless */ + + ret = config_ipwireless(ipw); + + if (ret != 0) { + cs_error(link, RegisterClient, ret); + ipwireless_detach(link); + return ret; + } + + return 0; +} + +/* + * This deletes a driver "instance". The device is de-registered with + * Card Services. If it has been released, all local data structures + * are freed. Otherwise, the structures will be freed when the device + * is released. + */ +static void ipwireless_detach(struct pcmcia_device *link) +{ + struct ipw_dev *ipw = link->priv; + + release_ipwireless(ipw); + + if (ipw->tty != NULL) + ipwireless_tty_free(ipw->tty); + if (ipw->network != NULL) + ipwireless_network_free(ipw->network); + if (ipw->hardware != NULL) + ipwireless_hardware_free(ipw->hardware); + kfree(ipw); +} + +static struct pcmcia_driver me = { + .owner = THIS_MODULE, + .probe = ipwireless_attach, + .remove = ipwireless_detach, + .drv = { .name = IPWIRELESS_PCCARD_NAME }, + .id_table = ipw_ids +}; + +/* + * Module insertion : initialisation of the module. + * Register the card with cardmgr... + */ +static int __init init_ipwireless(void) +{ + int ret; + + printk(KERN_INFO IPWIRELESS_PCCARD_NAME " " + IPWIRELESS_PCMCIA_VERSION " by " IPWIRELESS_PCMCIA_AUTHOR "\n"); + + ret = ipwireless_tty_init(); + if (ret != 0) + return ret; + + ret = pcmcia_register_driver(&me); + if (ret != 0) + ipwireless_tty_release(); + + return ret; +} + +/* + * Module removal + */ +static void __exit exit_ipwireless(void) +{ + printk(KERN_INFO IPWIRELESS_PCCARD_NAME " " + IPWIRELESS_PCMCIA_VERSION " removed\n"); + + pcmcia_unregister_driver(&me); + ipwireless_tty_release(); +} + +module_init(init_ipwireless); +module_exit(exit_ipwireless); + +MODULE_AUTHOR(IPWIRELESS_PCMCIA_AUTHOR); +MODULE_DESCRIPTION(IPWIRELESS_PCCARD_NAME " " IPWIRELESS_PCMCIA_VERSION); +MODULE_LICENSE("GPL"); diff --git a/drivers/char/pcmcia/ipwireless/main.h b/drivers/char/pcmcia/ipwireless/main.h new file mode 100644 index 0000000..0e0363a --- /dev/null +++ b/drivers/char/pcmcia/ipwireless/main.h @@ -0,0 +1,75 @@ +/* + * IPWireless 3G PCMCIA Network Driver + * + * Original code + * by Stephen Blackheath <stephen@blacksapphire.com>, + * Ben Martel <benm@symmetric.co.nz> + * + * Copyrighted as follows: + * Copyright (C) 2004 by Symmetric Systems Ltd (NZ) + * + * Various driver changes and rewrites, port to new kernels + * Copyright (C) 2006-2007 Jiri Kosina + * + * Misc code cleanups and updates + * Copyright (C) 2007 David Sterba + */ + +#ifndef _IPWIRELESS_CS_H_ +#define _IPWIRELESS_CS_H_ + +#include <linux/sched.h> +#include <linux/types.h> + +#include <pcmcia/cs_types.h> +#include <pcmcia/cs.h> +#include <pcmcia/cistpl.h> +#include <pcmcia/ds.h> + +#include "hardware.h" + +#define IPWIRELESS_PCCARD_NAME "ipwireless" +#define IPWIRELESS_PCMCIA_VERSION "1.1" +#define IPWIRELESS_PCMCIA_AUTHOR \ + "Stephen Blackheath, Ben Martel, Jiri Kosina and David Sterba" + +#define IPWIRELESS_TX_QUEUE_SIZE 262144 +#define IPWIRELESS_RX_QUEUE_SIZE 262144 + +#define IPWIRELESS_STATE_DEBUG + +struct ipw_hardware; +struct ipw_network; +struct ipw_tty; + +struct ipw_dev { + struct pcmcia_device *link; + int is_v2_card; + + window_handle_t handle_attr_memory; + void __iomem *attr_memory; + win_req_t request_attr_memory; + + window_handle_t handle_common_memory; + void __iomem *common_memory; + win_req_t request_common_memory; + + dev_node_t nodes[2]; + /* Reference to attribute memory, containing CIS data */ + void *attribute_memory; + + /* Hardware context */ + struct ipw_hardware *hardware; + /* Network layer context */ + struct ipw_network *network; + /* TTY device context */ + struct ipw_tty *tty; + struct work_struct work_reboot; +}; + +/* Module parametres */ +extern int ipwireless_debug; +extern int ipwireless_loopback; +extern int ipwireless_out_queue; + +#endif diff --git a/drivers/char/pcmcia/ipwireless/network.c b/drivers/char/pcmcia/ipwireless/network.c new file mode 100644 index 0000000..590762a --- /dev/null +++ b/drivers/char/pcmcia/ipwireless/network.c @@ -0,0 +1,506 @@ +/* + * IPWireless 3G PCMCIA Network Driver + * + * Original code + * by Stephen Blackheath <stephen@blacksapphire.com>, + * Ben Martel <benm@symmetric.co.nz> + * + * Copyrighted as follows: + * Copyright (C) 2004 by Symmetric Systems Ltd (NZ) + * + * Various driver changes and rewrites, port to new kernels + * Copyright (C) 2006-2007 Jiri Kosina + * + * Misc code cleanups and updates + * Copyright (C) 2007 David Sterba + */ + +#include <linux/interrupt.h> +#include <linux/kernel.h> +#include <linux/mutex.h> +#include <linux/netdevice.h> +#include <linux/ppp_channel.h> +#include <linux/ppp_defs.h> +#include <linux/if_ppp.h> +#include <linux/skbuff.h> + +#include "network.h" +#include "hardware.h" +#include "main.h" +#include "tty.h" + +#define MAX_ASSOCIATED_TTYS 2 + +#define SC_RCV_BITS (SC_RCV_B7_1|SC_RCV_B7_0|SC_RCV_ODDP|SC_RCV_EVNP) + +struct ipw_network { + /* Hardware context, used for calls to hardware layer. */ + struct ipw_hardware *hardware; + /* Context for kernel 'generic_ppp' functionality */ + struct ppp_channel *ppp_channel; + /* tty context connected with IPW console */ + struct ipw_tty *associated_ttys[NO_OF_IPW_CHANNELS][MAX_ASSOCIATED_TTYS]; + /* True if ppp needs waking up once we're ready to xmit */ + int ppp_blocked; + /* Number of packets queued up in hardware module. */ + int outgoing_packets_queued; + /* Spinlock to avoid interrupts during shutdown */ + spinlock_t lock; + struct mutex close_lock; + + /* PPP ioctl data, not actually used anywere */ + unsigned int flags; + unsigned int rbits; + u32 xaccm[8]; + u32 raccm; + int mru; + + int shutting_down; + unsigned int ras_control_lines; + + struct work_struct work_go_online; + struct work_struct work_go_offline; +}; + +static void notify_packet_sent(void *callback_data, unsigned int packet_length) +{ + struct ipw_network *network = callback_data; + unsigned long flags; + + spin_lock_irqsave(&network->lock, flags); + network->outgoing_packets_queued--; + if (network->ppp_channel != NULL) { + if (network->ppp_blocked) { + network->ppp_blocked = 0; + spin_unlock_irqrestore(&network->lock, flags); + ppp_output_wakeup(network->ppp_channel); + if (ipwireless_debug) + printk(KERN_DEBUG IPWIRELESS_PCCARD_NAME + ": ppp unblocked\n"); + } else + spin_unlock_irqrestore(&network->lock, flags); + } else + spin_unlock_irqrestore(&network->lock, flags); +} + +/* + * Called by the ppp system when it has a packet to send to the hardware. + */ +static int ipwireless_ppp_start_xmit(struct ppp_channel *ppp_channel, + struct sk_buff *skb) +{ + struct ipw_network *network = ppp_channel->private; + unsigned long flags; + + spin_lock_irqsave(&network->lock, flags); + if (network->outgoing_packets_queued < ipwireless_out_queue) { + unsigned char *buf; + static unsigned char header[] = { + PPP_ALLSTATIONS, /* 0xff */ + PPP_UI, /* 0x03 */ + }; + int ret; + + network->outgoing_packets_queued++; + spin_unlock_irqrestore(&network->lock, flags); + + /* + * If we have the requested amount of headroom in the skb we + * were handed, then we can add the header efficiently. + */ + if (skb_headroom(skb) >= 2) { + memcpy(skb_push(skb, 2), header, 2); + ret = ipwireless_send_packet(network->hardware, + IPW_CHANNEL_RAS, skb->data, + skb->len, + notify_packet_sent, + network); + if (ret == -1) { + skb_pull(skb, 2); + return 0; + } + } else { + /* Otherwise (rarely) we do it inefficiently. */ + buf = kmalloc(skb->len + 2, GFP_ATOMIC); + if (!buf) + return 0; + memcpy(buf + 2, skb->data, skb->len); + memcpy(buf, header, 2); + ret = ipwireless_send_packet(network->hardware, + IPW_CHANNEL_RAS, buf, + skb->len + 2, + notify_packet_sent, + network); + kfree(buf); + if (ret == -1) + return 0; + } + kfree_skb(skb); + return 1; + } else { + /* + * Otherwise reject the packet, and flag that the ppp system + * needs to be unblocked once we are ready to send. + */ + network->ppp_blocked = 1; + spin_unlock_irqrestore(&network->lock, flags); + if (ipwireless_debug) + printk(KERN_DEBUG IPWIRELESS_PCCARD_NAME ": ppp blocked\n"); + return 0; + } +} + +/* Handle an ioctl call that has come in via ppp. (copy of ppp_async_ioctl() */ +static int ipwireless_ppp_ioctl(struct ppp_channel *ppp_channel, + unsigned int cmd, unsigned long arg) +{ + struct ipw_network *network = ppp_channel->private; + int err, val; + u32 accm[8]; + int __user *user_arg = (int __user *) arg; + + err = -EFAULT; + switch (cmd) { + case PPPIOCGFLAGS: + val = network->flags | network->rbits; + if (put_user(val, user_arg)) + break; + err = 0; + break; + + case PPPIOCSFLAGS: + if (get_user(val, user_arg)) + break; + network->flags = val & ~SC_RCV_BITS; + network->rbits = val & SC_RCV_BITS; + err = 0; + break; + + case PPPIOCGASYNCMAP: + if (put_user(network->xaccm[0], user_arg)) + break; + err = 0; + break; + + case PPPIOCSASYNCMAP: + if (get_user(network->xaccm[0], user_arg)) + break; + err = 0; + break; + + case PPPIOCGRASYNCMAP: + if (put_user(network->raccm, user_arg)) + break; + err = 0; + break; + + case PPPIOCSRASYNCMAP: + if (get_user(network->raccm, user_arg)) + break; + err = 0; + break; + + case PPPIOCGXASYNCMAP: + if (copy_to_user((void __user *) arg, network->xaccm, + sizeof(network->xaccm))) + break; + err = 0; + break; + + case PPPIOCSXASYNCMAP: + if (copy_from_user(accm, (void __user *) arg, sizeof(accm))) + break; + accm[2] &= ~0x40000000U; /* can't escape 0x5e */ + accm[3] |= 0x60000000U; /* must escape 0x7d, 0x7e */ + memcpy(network->xaccm, accm, sizeof(network->xaccm)); + err = 0; + break; + + case PPPIOCGMRU: + if (put_user(network->mru, user_arg)) + break; + err = 0; + break; + + case PPPIOCSMRU: + if (get_user(val, user_arg)) + break; + if (val < PPP_MRU) + val = PPP_MRU; + network->mru = val; + err = 0; + break; + + default: + err = -ENOTTY; + } + + return err; +} + +static struct ppp_channel_ops ipwireless_ppp_channel_ops = { + .start_xmit = ipwireless_ppp_start_xmit, + .ioctl = ipwireless_ppp_ioctl +}; + +static void do_go_online(struct work_struct *work_go_online) +{ + struct ipw_network *network = + container_of(work_go_online, struct ipw_network, + work_go_online); + unsigned long flags; + + spin_lock_irqsave(&network->lock, flags); + if (!network->ppp_channel) { + struct ppp_channel *channel; + + spin_unlock_irqrestore(&network->lock, flags); + channel = kzalloc(sizeof(struct ppp_channel), GFP_KERNEL); + if (!channel) { + printk(KERN_ERR IPWIRELESS_PCCARD_NAME + ": unable to allocate PPP channel\n"); + return; + } + channel->private = network; + channel->mtu = 16384; /* Wild guess */ + channel->hdrlen = 2; + channel->ops = &ipwireless_ppp_channel_ops; + + network->flags = 0; + network->rbits = 0; + network->mru = PPP_MRU; + memset(network->xaccm, 0, sizeof(network->xaccm)); + network->xaccm[0] = ~0U; + network->xaccm[3] = 0x60000000U; + network->raccm = ~0U; + ppp_register_channel(channel); + spin_lock_irqsave(&network->lock, flags); + network->ppp_channel = channel; + } + spin_unlock_irqrestore(&network->lock, flags); +} + +static void do_go_offline(struct work_struct *work_go_offline) +{ + struct ipw_network *network = + container_of(work_go_offline, struct ipw_network, + work_go_offline); + unsigned long flags; + + mutex_lock(&network->close_lock); + spin_lock_irqsave(&network->lock, flags); + if (network->ppp_channel != NULL) { + struct ppp_channel *channel = network->ppp_channel; + + network->ppp_channel = NULL; + spin_unlock_irqrestore(&network->lock, flags); + mutex_unlock(&network->close_lock); + ppp_unregister_channel(channel); + } else { + spin_unlock_irqrestore(&network->lock, flags); + mutex_unlock(&network->close_lock); + } +} + +void ipwireless_network_notify_control_line_change(struct ipw_network *network, + unsigned int channel_idx, + unsigned int control_lines, + unsigned int changed_mask) +{ + int i; + + if (channel_idx == IPW_CHANNEL_RAS) + network->ras_control_lines = control_lines; + + for (i = 0; i < MAX_ASSOCIATED_TTYS; i++) { + struct ipw_tty *tty = + network->associated_ttys[channel_idx][i]; + + /* + * If it's associated with a tty (other than the RAS channel + * when we're online), then send the data to that tty. The RAS + * channel's data is handled above - it always goes through + * ppp_generic. + */ + if (tty) + ipwireless_tty_notify_control_line_change(tty, + channel_idx, + control_lines, + changed_mask); + } +} + +/* + * Some versions of firmware stuff packets with 0xff 0x03 (PPP: ALLSTATIONS, UI) + * bytes, which are required on sent packet, but not always present on received + * packets + */ +static struct sk_buff *ipw_packet_received_skb(unsigned char *data, + unsigned int length) +{ + struct sk_buff *skb; + + if (length > 2 && data[0] == PPP_ALLSTATIONS && data[1] == PPP_UI) { + length -= 2; + data += 2; + } + + skb = dev_alloc_skb(length + 4); + skb_reserve(skb, 2); + memcpy(skb_put(skb, length), data, length); + + return skb; +} + +void ipwireless_network_packet_received(struct ipw_network *network, + unsigned int channel_idx, + unsigned char *data, + unsigned int length) +{ + int i; + unsigned long flags; + + for (i = 0; i < MAX_ASSOCIATED_TTYS; i++) { + struct ipw_tty *tty = network->associated_ttys[channel_idx][i]; + + if (!tty) + continue; + + /* + * If it's associated with a tty (other than the RAS channel + * when we're online), then send the data to that tty. The RAS + * channel's data is handled above - it always goes through + * ppp_generic. + */ + if (channel_idx == IPW_CHANNEL_RAS + && (network->ras_control_lines & + IPW_CONTROL_LINE_DCD) != 0 + && ipwireless_tty_is_modem(tty)) { + /* + * If data came in on the RAS channel and this tty is + * the modem tty, and we are online, then we send it to + * the PPP layer. + */ + mutex_lock(&network->close_lock); + spin_lock_irqsave(&network->lock, flags); + if (network->ppp_channel != NULL) { + struct sk_buff *skb; + + spin_unlock_irqrestore(&network->lock, + flags); + + /* Send the data to the ppp_generic module. */ + skb = ipw_packet_received_skb(data, length); + ppp_input(network->ppp_channel, skb); + } else + spin_unlock_irqrestore(&network->lock, + flags); + mutex_unlock(&network->close_lock); + } + /* Otherwise we send it out the tty. */ + else + ipwireless_tty_received(tty, data, length); + } +} + +struct ipw_network *ipwireless_network_create(struct ipw_hardware *hw) +{ + struct ipw_network *network = + kzalloc(sizeof(struct ipw_network), GFP_ATOMIC); + + if (!network) + return NULL; + + spin_lock_init(&network->lock); + mutex_init(&network->close_lock); + + network->hardware = hw; + + INIT_WORK(&network->work_go_online, do_go_online); + INIT_WORK(&network->work_go_offline, do_go_offline); + + ipwireless_associate_network(hw, network); + + return network; +} + +void ipwireless_network_free(struct ipw_network *network) +{ + network->shutting_down = 1; + + ipwireless_ppp_close(network); + flush_scheduled_work(); + + ipwireless_stop_interrupts(network->hardware); + ipwireless_associate_network(network->hardware, NULL); + + kfree(network); +} + +void ipwireless_associate_network_tty(struct ipw_network *network, + unsigned int channel_idx, + struct ipw_tty *tty) +{ + int i; + + for (i = 0; i < MAX_ASSOCIATED_TTYS; i++) + if (network->associated_ttys[channel_idx][i] == NULL) { + network->associated_ttys[channel_idx][i] = tty; + break; + } +} + +void ipwireless_disassociate_network_ttys(struct ipw_network *network, + unsigned int channel_idx) +{ + int i; + + for (i = 0; i < MAX_ASSOCIATED_TTYS; i++) + network->associated_ttys[channel_idx][i] = NULL; +} + +void ipwireless_ppp_open(struct ipw_network *network) +{ + if (ipwireless_debug) + printk(KERN_DEBUG IPWIRELESS_PCCARD_NAME ": online\n"); + schedule_work(&network->work_go_online); +} + +void ipwireless_ppp_close(struct ipw_network *network) +{ + /* Disconnect from the wireless network. */ + if (ipwireless_debug) + printk(KERN_DEBUG IPWIRELESS_PCCARD_NAME ": offline\n"); + schedule_work(&network->work_go_offline); +} + +int ipwireless_ppp_channel_index(struct ipw_network *network) +{ + int ret = -1; + unsigned long flags; + + spin_lock_irqsave(&network->lock, flags); + if (network->ppp_channel != NULL) + ret = ppp_channel_index(network->ppp_channel); + spin_unlock_irqrestore(&network->lock, flags); + + return ret; +} + +int ipwireless_ppp_unit_number(struct ipw_network *network) +{ + int ret = -1; + unsigned long flags; + + spin_lock_irqsave(&network->lock, flags); + if (network->ppp_channel != NULL) + ret = ppp_unit_number(network->ppp_channel); + spin_unlock_irqrestore(&network->lock, flags); + + return ret; +} + +int ipwireless_ppp_mru(const struct ipw_network *network) +{ + return network->mru; +} diff --git a/drivers/char/pcmcia/ipwireless/network.h b/drivers/char/pcmcia/ipwireless/network.h new file mode 100644 index 0000000..561f765 --- /dev/null +++ b/drivers/char/pcmcia/ipwireless/network.h @@ -0,0 +1,53 @@ +/* + * IPWireless 3G PCMCIA Network Driver + * + * Original code + * by Stephen Blackheath <stephen@blacksapphire.com>, + * Ben Martel <benm@symmetric.co.nz> + * + * Copyrighted as follows: + * Copyright (C) 2004 by Symmetric Systems Ltd (NZ) + * + * Various driver changes and rewrites, port to new kernels + * Copyright (C) 2006-2007 Jiri Kosina + * + * Misc code cleanups and updates + * Copyright (C) 2007 David Sterba + */ + +#ifndef _IPWIRELESS_CS_NETWORK_H_ +#define _IPWIRELESS_CS_NETWORK_H_ + +#include <linux/types.h> + +struct ipw_network; +struct ipw_tty; +struct ipw_hardware; + +/* Definitions of the different channels on the PCMCIA UE */ +#define IPW_CHANNEL_RAS 0 +#define IPW_CHANNEL_DIALLER 1 +#define IPW_CHANNEL_CONSOLE 2 +#define NO_OF_IPW_CHANNELS 5 + +void ipwireless_network_notify_control_line_change(struct ipw_network *net, + unsigned int channel_idx, unsigned int control_lines, + unsigned int control_mask); +void ipwireless_network_packet_received(struct ipw_network *net, + unsigned int channel_idx, unsigned char *data, + unsigned int length); +struct ipw_network *ipwireless_network_create(struct ipw_hardware *hw); +void ipwireless_network_free(struct ipw_network *net); +void ipwireless_associate_network_tty(struct ipw_network *net, + unsigned int channel_idx, struct ipw_tty *tty); +void ipwireless_disassociate_network_ttys(struct ipw_network *net, + unsigned int channel_idx); + +void ipwireless_ppp_open(struct ipw_network *net); + +void ipwireless_ppp_close(struct ipw_network *net); +int ipwireless_ppp_channel_index(struct ipw_network *net); +int ipwireless_ppp_unit_number(struct ipw_network *net); +int ipwireless_ppp_mru(const struct ipw_network *net); + +#endif diff --git a/drivers/char/pcmcia/ipwireless/setup_protocol.h b/drivers/char/pcmcia/ipwireless/setup_protocol.h new file mode 100644 index 0000000..9d6bcc7 --- /dev/null +++ b/drivers/char/pcmcia/ipwireless/setup_protocol.h @@ -0,0 +1,108 @@ +/* + * IPWireless 3G PCMCIA Network Driver + * + * Original code + * by Stephen Blackheath <stephen@blacksapphire.com>, + * Ben Martel <benm@symmetric.co.nz> + * + * Copyrighted as follows: + * Copyright (C) 2004 by Symmetric Systems Ltd (NZ) + * + * Various driver changes and rewrites, port to new kernels + * Copyright (C) 2006-2007 Jiri Kosina + * + * Misc code cleanups and updates + * Copyright (C) 2007 David Sterba + */ + +#ifndef _IPWIRELESS_CS_SETUP_PROTOCOL_H_ +#define _IPWIRELESS_CS_SETUP_PROTOCOL_H_ + +/* Version of the setup protocol and transport protocols */ +#define TL_SETUP_VERSION 1 + +#define TL_SETUP_VERSION_QRY_TMO 1000 +#define TL_SETUP_MAX_VERSION_QRY 30 + +/* Message numbers 0-9 are obsoleted and must not be reused! */ +#define TL_SETUP_SIGNO_GET_VERSION_QRY 10 +#define TL_SETUP_SIGNO_GET_VERSION_RSP 11 +#define TL_SETUP_SIGNO_CONFIG_MSG 12 +#define TL_SETUP_SIGNO_CONFIG_DONE_MSG 13 +#define TL_SETUP_SIGNO_OPEN_MSG 14 +#define TL_SETUP_SIGNO_CLOSE_MSG 15 + +#define TL_SETUP_SIGNO_INFO_MSG 20 +#define TL_SETUP_SIGNO_INFO_MSG_ACK 21 + +#define TL_SETUP_SIGNO_REBOOT_MSG 22 +#define TL_SETUP_SIGNO_REBOOT_MSG_ACK 23 + +/* Synchronous start-messages */ +struct tl_setup_get_version_qry { + unsigned char sig_no; /* TL_SETUP_SIGNO_GET_VERSION_QRY */ +} __attribute__ ((__packed__)); + +struct tl_setup_get_version_rsp { + unsigned char sig_no; /* TL_SETUP_SIGNO_GET_VERSION_RSP */ + unsigned char version; /* TL_SETUP_VERSION */ +} __attribute__ ((__packed__)); + +struct tl_setup_config_msg { + unsigned char sig_no; /* TL_SETUP_SIGNO_CONFIG_MSG */ + unsigned char port_no; + unsigned char prio_data; + unsigned char prio_ctrl; +} __attribute__ ((__packed__)); + +struct tl_setup_config_done_msg { + unsigned char sig_no; /* TL_SETUP_SIGNO_CONFIG_DONE_MSG */ +} __attribute__ ((__packed__)); + +/* Asyncronous messages */ +struct tl_setup_open_msg { + unsigned char sig_no; /* TL_SETUP_SIGNO_OPEN_MSG */ + unsigned char port_no; +} __attribute__ ((__packed__)); + +struct tl_setup_close_msg { + unsigned char sig_no; /* TL_SETUP_SIGNO_CLOSE_MSG */ + unsigned char port_no; +} __attribute__ ((__packed__)); + +/* Driver type - for use in tl_setup_info_msg.driver_type */ +#define COMM_DRIVER 0 +#define NDISWAN_DRIVER 1 +#define NDISWAN_DRIVER_MAJOR_VERSION 2 +#define NDISWAN_DRIVER_MINOR_VERSION 0 + +/* + * It should not matter when this message comes over as we just store the + * results and send the ACK. + */ +struct tl_setup_info_msg { + unsigned char sig_no; /* TL_SETUP_SIGNO_INFO_MSG */ + unsigned char driver_type; + unsigned char major_version; + unsigned char minor_version; +} __attribute__ ((__packed__)); + +struct tl_setup_info_msgAck { + unsigned char sig_no; /* TL_SETUP_SIGNO_INFO_MSG_ACK */ +} __attribute__ ((__packed__)); + +struct TlSetupRebootMsgAck { + unsigned char sig_no; /* TL_SETUP_SIGNO_REBOOT_MSG_ACK */ +} __attribute__ ((__packed__)); + +/* Define a union of all the msgs that the driver can receive from the card.*/ +union ipw_setup_rx_msg { + unsigned char sig_no; + struct tl_setup_get_version_rsp version_rsp_msg; + struct tl_setup_open_msg open_msg; + struct tl_setup_close_msg close_msg; + struct tl_setup_info_msg InfoMsg; + struct tl_setup_info_msgAck info_msg_ack; +} __attribute__ ((__packed__)); + +#endif /* _IPWIRELESS_CS_SETUP_PROTOCOL_H_ */ diff --git a/drivers/char/pcmcia/ipwireless/tty.c b/drivers/char/pcmcia/ipwireless/tty.c new file mode 100644 index 0000000..569f2f7 --- /dev/null +++ b/drivers/char/pcmcia/ipwireless/tty.c @@ -0,0 +1,688 @@ +/* + * IPWireless 3G PCMCIA Network Driver + * + * Original code + * by Stephen Blackheath <stephen@blacksapphire.com>, + * Ben Martel <benm@symmetric.co.nz> + * + * Copyrighted as follows: + * Copyright (C) 2004 by Symmetric Systems Ltd (NZ) + * + * Various driver changes and rewrites, port to new kernels + * Copyright (C) 2006-2007 Jiri Kosina + * + * Misc code cleanups and updates + * Copyright (C) 2007 David Sterba + */ + +#include <linux/init.h> +#include <linux/kernel.h> +#include <linux/module.h> +#include <linux/mutex.h> +#include <linux/ppp_defs.h> +#include <linux/if.h> +#include <linux/if_ppp.h> +#include <linux/sched.h> +#include <linux/serial.h> +#include <linux/slab.h> +#include <linux/tty.h> +#include <linux/tty_driver.h> +#include <linux/tty_flip.h> +#include <linux/uaccess.h> + +#include "tty.h" +#include "network.h" +#include "hardware.h" +#include "main.h" + +#define IPWIRELESS_PCMCIA_START (0) +#define IPWIRELESS_PCMCIA_MINORS (24) +#define IPWIRELESS_PCMCIA_MINOR_RANGE (8) + +#define TTYTYPE_MODEM (0) +#define TTYTYPE_MONITOR (1) +#define TTYTYPE_RAS_RAW (2) + +struct ipw_tty { + int index; + struct ipw_hardware *hardware; + unsigned int channel_idx; + unsigned int secondary_channel_idx; + int tty_type; + struct ipw_network *network; + struct tty_struct *linux_tty; + int open_count; + unsigned int control_lines; + struct mutex ipw_tty_mutex; + int tx_bytes_queued; + int closing; +}; + +static struct ipw_tty *ttys[IPWIRELESS_PCMCIA_MINORS]; + +static struct tty_driver *ipw_tty_driver; + +static char *tty_type_name(int tty_type) +{ + static char *channel_names[] = { + "modem", + "monitor", + "RAS-raw" + }; + + return channel_names[tty_type]; +} + +static void report_registering(struct ipw_tty *tty) +{ + char *iftype = tty_type_name(tty->tty_type); + + printk(KERN_INFO IPWIRELESS_PCCARD_NAME + ": registering %s device ttyIPWp%d\n", iftype, tty->index); +} + +static void report_deregistering(struct ipw_tty *tty) +{ + char *iftype = tty_type_name(tty->tty_type); + + printk(KERN_INFO IPWIRELESS_PCCARD_NAME + ": deregistering %s device ttyIPWp%d\n", iftype, + tty->index); +} + +static struct ipw_tty *get_tty(int minor) +{ + if (minor < ipw_tty_driver->minor_start + || minor >= ipw_tty_driver->minor_start + + IPWIRELESS_PCMCIA_MINORS) + return NULL; + else { + int minor_offset = minor - ipw_tty_driver->minor_start; + + /* + * The 'ras_raw' channel is only available when 'loopback' mode + * is enabled. + * Number of minor starts with 16 (_RANGE * _RAS_RAW). + */ + if (!ipwireless_loopback && + minor_offset >= + IPWIRELESS_PCMCIA_MINOR_RANGE * TTYTYPE_RAS_RAW) + return NULL; + + return ttys[minor_offset]; + } +} + +static int ipw_open(struct tty_struct *linux_tty, struct file *filp) +{ + int minor = linux_tty->index; + struct ipw_tty *tty = get_tty(minor); + + if (!tty) + return -ENODEV; + + mutex_lock(&tty->ipw_tty_mutex); + + if (tty->closing) { + mutex_unlock(&tty->ipw_tty_mutex); + return -ENODEV; + } + if (tty->open_count == 0) + tty->tx_bytes_queued = 0; + + tty->open_count++; + + tty->linux_tty = linux_tty; + linux_tty->driver_data = tty; + linux_tty->low_latency = 1; + + if (tty->tty_type == TTYTYPE_MODEM) + ipwireless_ppp_open(tty->network); + + mutex_unlock(&tty->ipw_tty_mutex); + + return 0; +} + +static void do_ipw_close(struct ipw_tty *tty) +{ + tty->open_count--; + + if (tty->open_count == 0) { + struct tty_struct *linux_tty = tty->linux_tty; + + if (linux_tty != NULL) { + tty->linux_tty = NULL; + linux_tty->driver_data = NULL; + + if (tty->tty_type == TTYTYPE_MODEM) + ipwireless_ppp_close(tty->network); + } + } +} + +static void ipw_hangup(struct tty_struct *linux_tty) +{ + struct ipw_tty *tty = linux_tty->driver_data; + + if (!tty) + return; + + mutex_lock(&tty->ipw_tty_mutex); + if (tty->open_count == 0) { + mutex_unlock(&tty->ipw_tty_mutex); + return; + } + + do_ipw_close(tty); + + mutex_unlock(&tty->ipw_tty_mutex); +} + +static void ipw_close(struct tty_struct *linux_tty, struct file *filp) +{ + ipw_hangup(linux_tty); +} + +/* Take data received from hardware, and send it out the tty */ +void ipwireless_tty_received(struct ipw_tty *tty, unsigned char *data, + unsigned int length) +{ + struct tty_struct *linux_tty; + int work = 0; + + mutex_lock(&tty->ipw_tty_mutex); + linux_tty = tty->linux_tty; + if (linux_tty == NULL) { + mutex_unlock(&tty->ipw_tty_mutex); + return; + } + + if (!tty->open_count) { + mutex_unlock(&tty->ipw_tty_mutex); + return; + } + mutex_unlock(&tty->ipw_tty_mutex); + + work = tty_insert_flip_string(linux_tty, data, length); + + if (work != length) + printk(KERN_DEBUG IPWIRELESS_PCCARD_NAME + ": %d chars not inserted to flip buffer!\n", + length - work); + + /* + * This may sleep if ->low_latency is set + */ + if (work) + tty_flip_buffer_push(linux_tty); +} + +static void ipw_write_packet_sent_callback(void *callback_data, + unsigned int packet_length) +{ + struct ipw_tty *tty = callback_data; + + /* + * Packet has been sent, so we subtract the number of bytes from our + * tally of outstanding TX bytes. + */ + tty->tx_bytes_queued -= packet_length; +} + +static int ipw_write(struct tty_struct *linux_tty, + const unsigned char *buf, int count) +{ + struct ipw_tty *tty = linux_tty->driver_data; + int room, ret; + + if (!tty) + return -ENODEV; + + mutex_lock(&tty->ipw_tty_mutex); + if (!tty->open_count) { + mutex_unlock(&tty->ipw_tty_mutex); + return -EINVAL; + } + + room = IPWIRELESS_TX_QUEUE_SIZE - tty->tx_bytes_queued; + if (room < 0) + room = 0; + /* Don't allow caller to write any more than we have room for */ + if (count > room) + count = room; + + if (count == 0) { + mutex_unlock(&tty->ipw_tty_mutex); + return 0; + } + + ret = ipwireless_send_packet(tty->hardware, IPW_CHANNEL_RAS, + buf, count, + ipw_write_packet_sent_callback, tty); + if (ret == -1) { + mutex_unlock(&tty->ipw_tty_mutex); + return 0; + } + + tty->tx_bytes_queued += count; + mutex_unlock(&tty->ipw_tty_mutex); + + return count; +} + +static int ipw_write_room(struct tty_struct *linux_tty) +{ + struct ipw_tty *tty = linux_tty->driver_data; + int room; + + /* FIXME: Exactly how is the tty object locked here .. */ + if (!tty) + return -ENODEV; + + if (!tty->open_count) + return -EINVAL; + + room = IPWIRELESS_TX_QUEUE_SIZE - tty->tx_bytes_queued; + if (room < 0) + room = 0; + + return room; +} + +static int ipwireless_get_serial_info(struct ipw_tty *tty, + struct serial_struct __user *retinfo) +{ + struct serial_struct tmp; + + if (!retinfo) + return (-EFAULT); + + memset(&tmp, 0, sizeof(tmp)); + tmp.type = PORT_UNKNOWN; + tmp.line = tty->index; + tmp.port = 0; + tmp.irq = 0; + tmp.flags = 0; + tmp.baud_base = 115200; + tmp.close_delay = 0; + tmp.closing_wait = 0; + tmp.custom_divisor = 0; + tmp.hub6 = 0; + if (copy_to_user(retinfo, &tmp, sizeof(*retinfo))) + return -EFAULT; + + return 0; +} + +static int ipw_chars_in_buffer(struct tty_struct *linux_tty) +{ + struct ipw_tty *tty = linux_tty->driver_data; + + if (!tty) + return -ENODEV; + + if (!tty->open_count) + return -EINVAL; + + return tty->tx_bytes_queued; +} + +static int get_control_lines(struct ipw_tty *tty) +{ + unsigned int my = tty->control_lines; + unsigned int out = 0; + + if (my & IPW_CONTROL_LINE_RTS) + out |= TIOCM_RTS; + if (my & IPW_CONTROL_LINE_DTR) + out |= TIOCM_DTR; + if (my & IPW_CONTROL_LINE_CTS) + out |= TIOCM_CTS; + if (my & IPW_CONTROL_LINE_DSR) + out |= TIOCM_DSR; + if (my & IPW_CONTROL_LINE_DCD) + out |= TIOCM_CD; + + return out; +} + +static int set_control_lines(struct ipw_tty *tty, unsigned int set, + unsigned int clear) +{ + int ret; + + if (set & TIOCM_RTS) { + ret = ipwireless_set_RTS(tty->hardware, tty->channel_idx, 1); + if (ret) + return ret; + if (tty->secondary_channel_idx != -1) { + ret = ipwireless_set_RTS(tty->hardware, + tty->secondary_channel_idx, 1); + if (ret) + return ret; + } + } + if (set & TIOCM_DTR) { + ret = ipwireless_set_DTR(tty->hardware, tty->channel_idx, 1); + if (ret) + return ret; + if (tty->secondary_channel_idx != -1) { + ret = ipwireless_set_DTR(tty->hardware, + tty->secondary_channel_idx, 1); + if (ret) + return ret; + } + } + if (clear & TIOCM_RTS) { + ret = ipwireless_set_RTS(tty->hardware, tty->channel_idx, 0); + if (tty->secondary_channel_idx != -1) { + ret = ipwireless_set_RTS(tty->hardware, + tty->secondary_channel_idx, 0); + if (ret) + return ret; + } + } + if (clear & TIOCM_DTR) { + ret = ipwireless_set_DTR(tty->hardware, tty->channel_idx, 0); + if (tty->secondary_channel_idx != -1) { + ret = ipwireless_set_DTR(tty->hardware, + tty->secondary_channel_idx, 0); + if (ret) + return ret; + } + } + return 0; +} + +static int ipw_tiocmget(struct tty_struct *linux_tty, struct file *file) +{ + struct ipw_tty *tty = linux_tty->driver_data; + /* FIXME: Exactly how is the tty object locked here .. */ + + if (!tty) + return -ENODEV; + + if (!tty->open_count) + return -EINVAL; + + return get_control_lines(tty); +} + +static int +ipw_tiocmset(struct tty_struct *linux_tty, struct file *file, + unsigned int set, unsigned int clear) +{ + struct ipw_tty *tty = linux_tty->driver_data; + /* FIXME: Exactly how is the tty object locked here .. */ + + if (!tty) + return -ENODEV; + + if (!tty->open_count) + return -EINVAL; + + return set_control_lines(tty, set, clear); +} + +static int ipw_ioctl(struct tty_struct *linux_tty, struct file *file, + unsigned int cmd, unsigned long arg) +{ + struct ipw_tty *tty = linux_tty->driver_data; + + if (!tty) + return -ENODEV; + + if (!tty->open_count) + return -EINVAL; + + /* FIXME: Exactly how is the tty object locked here .. */ + + switch (cmd) { + case TIOCGSERIAL: + return ipwireless_get_serial_info(tty, (void __user *) arg); + + case TIOCSSERIAL: + return 0; /* Keeps the PCMCIA scripts happy. */ + } + + if (tty->tty_type == TTYTYPE_MODEM) { + switch (cmd) { + case PPPIOCGCHAN: + { + int chan = ipwireless_ppp_channel_index( + tty->network); + + if (chan < 0) + return -ENODEV; + if (put_user(chan, (int __user *) arg)) + return -EFAULT; + } + return 0; + + case PPPIOCGUNIT: + { + int unit = ipwireless_ppp_unit_number( + tty->network); + + if (unit < 0) + return -ENODEV; + if (put_user(unit, (int __user *) arg)) + return -EFAULT; + } + return 0; + + case FIONREAD: + { + int val = 0; + + if (put_user(val, (int __user *) arg)) + return -EFAULT; + } + return 0; + case TCFLSH: + return tty_perform_flush(linux_tty, arg); + } + } + return tty_mode_ioctl(linux_tty, file, cmd , arg); +} + +static int add_tty(dev_node_t *nodesp, int j, + struct ipw_hardware *hardware, + struct ipw_network *network, int channel_idx, + int secondary_channel_idx, int tty_type) +{ + ttys[j] = kzalloc(sizeof(struct ipw_tty), GFP_KERNEL); + if (!ttys[j]) + return -ENOMEM; + ttys[j]->index = j; + ttys[j]->hardware = hardware; + ttys[j]->channel_idx = channel_idx; + ttys[j]->secondary_channel_idx = secondary_channel_idx; + ttys[j]->network = network; + ttys[j]->tty_type = tty_type; + mutex_init(&ttys[j]->ipw_tty_mutex); + + tty_register_device(ipw_tty_driver, j, NULL); + ipwireless_associate_network_tty(network, channel_idx, ttys[j]); + + if (secondary_channel_idx != -1) + ipwireless_associate_network_tty(network, + secondary_channel_idx, + ttys[j]); + if (nodesp != NULL) { + sprintf(nodesp->dev_name, "ttyIPWp%d", j); + nodesp->major = ipw_tty_driver->major; + nodesp->minor = j + ipw_tty_driver->minor_start; + } + if (get_tty(j + ipw_tty_driver->minor_start) == ttys[j]) + report_registering(ttys[j]); + return 0; +} + +struct ipw_tty *ipwireless_tty_create(struct ipw_hardware *hardware, + struct ipw_network *network, + dev_node_t *nodes) +{ + int i, j; + + for (i = 0; i < IPWIRELESS_PCMCIA_MINOR_RANGE; i++) { + int allfree = 1; + + for (j = i; j < IPWIRELESS_PCMCIA_MINORS; + j += IPWIRELESS_PCMCIA_MINOR_RANGE) + if (ttys[j] != NULL) { + allfree = 0; + break; + } + + if (allfree) { + j = i; + + if (add_tty(&nodes[0], j, hardware, network, + IPW_CHANNEL_DIALLER, IPW_CHANNEL_RAS, + TTYTYPE_MODEM)) + return NULL; + + j += IPWIRELESS_PCMCIA_MINOR_RANGE; + if (add_tty(&nodes[1], j, hardware, network, + IPW_CHANNEL_DIALLER, -1, + TTYTYPE_MONITOR)) + return NULL; + + j += IPWIRELESS_PCMCIA_MINOR_RANGE; + if (add_tty(NULL, j, hardware, network, + IPW_CHANNEL_RAS, -1, + TTYTYPE_RAS_RAW)) + return NULL; + + nodes[0].next = &nodes[1]; + nodes[1].next = NULL; + + return ttys[i]; + } + } + return NULL; +} + +/* + * Must be called before ipwireless_network_free(). + */ +void ipwireless_tty_free(struct ipw_tty *tty) +{ + int j; + struct ipw_network *network = ttys[tty->index]->network; + + for (j = tty->index; j < IPWIRELESS_PCMCIA_MINORS; + j += IPWIRELESS_PCMCIA_MINOR_RANGE) { + struct ipw_tty *ttyj = ttys[j]; + + if (ttyj) { + mutex_lock(&ttyj->ipw_tty_mutex); + if (get_tty(j + ipw_tty_driver->minor_start) == ttyj) + report_deregistering(ttyj); + ttyj->closing = 1; + if (ttyj->linux_tty != NULL) { + mutex_unlock(&ttyj->ipw_tty_mutex); + tty_hangup(ttyj->linux_tty); + /* Wait till the tty_hangup has completed */ + flush_scheduled_work(); + /* FIXME: Exactly how is the tty object locked here + against a parallel ioctl etc */ + mutex_lock(&ttyj->ipw_tty_mutex); + } + while (ttyj->open_count) + do_ipw_close(ttyj); + ipwireless_disassociate_network_ttys(network, + ttyj->channel_idx); + tty_unregister_device(ipw_tty_driver, j); + ttys[j] = NULL; + mutex_unlock(&ttyj->ipw_tty_mutex); + kfree(ttyj); + } + } +} + +static struct tty_operations tty_ops = { + .open = ipw_open, + .close = ipw_close, + .hangup = ipw_hangup, + .write = ipw_write, + .write_room = ipw_write_room, + .ioctl = ipw_ioctl, + .chars_in_buffer = ipw_chars_in_buffer, + .tiocmget = ipw_tiocmget, + .tiocmset = ipw_tiocmset, +}; + +int ipwireless_tty_init(void) +{ + int result; + + ipw_tty_driver = alloc_tty_driver(IPWIRELESS_PCMCIA_MINORS); + if (!ipw_tty_driver) + return -ENOMEM; + + ipw_tty_driver->owner = THIS_MODULE; + ipw_tty_driver->driver_name = IPWIRELESS_PCCARD_NAME; + ipw_tty_driver->name = "ttyIPWp"; + ipw_tty_driver->major = 0; + ipw_tty_driver->minor_start = IPWIRELESS_PCMCIA_START; + ipw_tty_driver->type = TTY_DRIVER_TYPE_SERIAL; + ipw_tty_driver->subtype = SERIAL_TYPE_NORMAL; + ipw_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV; + ipw_tty_driver->init_termios = tty_std_termios; + ipw_tty_driver->init_termios.c_cflag = + B9600 | CS8 | CREAD | HUPCL | CLOCAL; + ipw_tty_driver->init_termios.c_ispeed = 9600; + ipw_tty_driver->init_termios.c_ospeed = 9600; + tty_set_operations(ipw_tty_driver, &tty_ops); + result = tty_register_driver(ipw_tty_driver); + if (result) { + printk(KERN_ERR IPWIRELESS_PCCARD_NAME + ": failed to register tty driver\n"); + put_tty_driver(ipw_tty_driver); + return result; + } + + return 0; +} + +void ipwireless_tty_release(void) +{ + int ret; + + ret = tty_unregister_driver(ipw_tty_driver); + put_tty_driver(ipw_tty_driver); + if (ret != 0) + printk(KERN_ERR IPWIRELESS_PCCARD_NAME + ": tty_unregister_driver failed with code %d\n", ret); +} + +int ipwireless_tty_is_modem(struct ipw_tty *tty) +{ + return tty->tty_type == TTYTYPE_MODEM; +} + +void +ipwireless_tty_notify_control_line_change(struct ipw_tty *tty, + unsigned int channel_idx, + unsigned int control_lines, + unsigned int changed_mask) +{ + unsigned int old_control_lines = tty->control_lines; + + tty->control_lines = (tty->control_lines & ~changed_mask) + | (control_lines & changed_mask); + + /* + * If DCD is de-asserted, we close the tty so pppd can tell that we + * have gone offline. + */ + if ((old_control_lines & IPW_CONTROL_LINE_DCD) + && !(tty->control_lines & IPW_CONTROL_LINE_DCD) + && tty->linux_tty) { + tty_hangup(tty->linux_tty); + } +} + diff --git a/drivers/char/pcmcia/ipwireless/tty.h b/drivers/char/pcmcia/ipwireless/tty.h new file mode 100644 index 0000000..b0deb91 --- /dev/null +++ b/drivers/char/pcmcia/ipwireless/tty.h @@ -0,0 +1,48 @@ +/* + * IPWireless 3G PCMCIA Network Driver + * + * Original code + * by Stephen Blackheath <stephen@blacksapphire.com>, + * Ben Martel <benm@symmetric.co.nz> + * + * Copyrighted as follows: + * Copyright (C) 2004 by Symmetric Systems Ltd (NZ) + * + * Various driver changes and rewrites, port to new kernels + * Copyright (C) 2006-2007 Jiri Kosina + * + * Misc code cleanups and updates + * Copyright (C) 2007 David Sterba + */ + +#ifndef _IPWIRELESS_CS_TTY_H_ +#define _IPWIRELESS_CS_TTY_H_ + +#include <linux/types.h> +#include <linux/sched.h> + +#include <pcmcia/cs_types.h> +#include <pcmcia/cs.h> +#include <pcmcia/cistpl.h> +#include <pcmcia/ds.h> + +struct ipw_tty; +struct ipw_network; +struct ipw_hardware; + +int ipwireless_tty_init(void); +void ipwireless_tty_release(void); + +struct ipw_tty *ipwireless_tty_create(struct ipw_hardware *hw, + struct ipw_network *net, + dev_node_t *nodes); +void ipwireless_tty_free(struct ipw_tty *tty); +void ipwireless_tty_received(struct ipw_tty *tty, unsigned char *data, + unsigned int length); +int ipwireless_tty_is_modem(struct ipw_tty *tty); +void ipwireless_tty_notify_control_line_change(struct ipw_tty *tty, + unsigned int channel_idx, + unsigned int control_lines, + unsigned int changed_mask); + +#endif diff --git a/drivers/char/pcmcia/synclink_cs.c b/drivers/char/pcmcia/synclink_cs.c new file mode 100644 index 0000000..4d64a02 --- /dev/null +++ b/drivers/char/pcmcia/synclink_cs.c @@ -0,0 +1,4498 @@ +/* + * linux/drivers/char/pcmcia/synclink_cs.c + * + * $Id: synclink_cs.c,v 4.34 2005/09/08 13:20:54 paulkf Exp $ + * + * Device driver for Microgate SyncLink PC Card + * multiprotocol serial adapter. + * + * written by Paul Fulghum for Microgate Corporation + * paulkf@microgate.com + * + * Microgate and SyncLink are trademarks of Microgate Corporation + * + * This code is released under the GNU General Public License (GPL) + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#define VERSION(ver,rel,seq) (((ver)<<16) | ((rel)<<8) | (seq)) +#if defined(__i386__) +# define BREAKPOINT() asm(" int $3"); +#else +# define BREAKPOINT() { } +#endif + +#define MAX_DEVICE_COUNT 4 + +#include <linux/module.h> +#include <linux/errno.h> +#include <linux/signal.h> +#include <linux/sched.h> +#include <linux/timer.h> +#include <linux/time.h> +#include <linux/interrupt.h> +#include <linux/tty.h> +#include <linux/tty_flip.h> +#include <linux/serial.h> +#include <linux/major.h> +#include <linux/string.h> +#include <linux/fcntl.h> +#include <linux/ptrace.h> +#include <linux/ioport.h> +#include <linux/mm.h> +#include <linux/slab.h> +#include <linux/netdevice.h> +#include <linux/vmalloc.h> +#include <linux/init.h> +#include <linux/delay.h> +#include <linux/ioctl.h> +#include <linux/synclink.h> + +#include <asm/system.h> +#include <asm/io.h> +#include <asm/irq.h> +#include <asm/dma.h> +#include <linux/bitops.h> +#include <asm/types.h> +#include <linux/termios.h> +#include <linux/workqueue.h> +#include <linux/hdlc.h> + +#include <pcmcia/cs_types.h> +#include <pcmcia/cs.h> +#include <pcmcia/cistpl.h> +#include <pcmcia/cisreg.h> +#include <pcmcia/ds.h> + +#if defined(CONFIG_HDLC) || (defined(CONFIG_HDLC_MODULE) && defined(CONFIG_SYNCLINK_CS_MODULE)) +#define SYNCLINK_GENERIC_HDLC 1 +#else +#define SYNCLINK_GENERIC_HDLC 0 +#endif + +#define GET_USER(error,value,addr) error = get_user(value,addr) +#define COPY_FROM_USER(error,dest,src,size) error = copy_from_user(dest,src,size) ? -EFAULT : 0 +#define PUT_USER(error,value,addr) error = put_user(value,addr) +#define COPY_TO_USER(error,dest,src,size) error = copy_to_user(dest,src,size) ? -EFAULT : 0 + +#include <asm/uaccess.h> + +static MGSL_PARAMS default_params = { + MGSL_MODE_HDLC, /* unsigned long mode */ + 0, /* unsigned char loopback; */ + HDLC_FLAG_UNDERRUN_ABORT15, /* unsigned short flags; */ + HDLC_ENCODING_NRZI_SPACE, /* unsigned char encoding; */ + 0, /* unsigned long clock_speed; */ + 0xff, /* unsigned char addr_filter; */ + HDLC_CRC_16_CCITT, /* unsigned short crc_type; */ + HDLC_PREAMBLE_LENGTH_8BITS, /* unsigned char preamble_length; */ + HDLC_PREAMBLE_PATTERN_NONE, /* unsigned char preamble; */ + 9600, /* unsigned long data_rate; */ + 8, /* unsigned char data_bits; */ + 1, /* unsigned char stop_bits; */ + ASYNC_PARITY_NONE /* unsigned char parity; */ +}; + +typedef struct +{ + int count; + unsigned char status; + char data[1]; +} RXBUF; + +/* The queue of BH actions to be performed */ + +#define BH_RECEIVE 1 +#define BH_TRANSMIT 2 +#define BH_STATUS 4 + +#define IO_PIN_SHUTDOWN_LIMIT 100 + +#define RELEVANT_IFLAG(iflag) (iflag & (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK)) + +struct _input_signal_events { + int ri_up; + int ri_down; + int dsr_up; + int dsr_down; + int dcd_up; + int dcd_down; + int cts_up; + int cts_down; +}; + + +/* + * Device instance data structure + */ + +typedef struct _mgslpc_info { + void *if_ptr; /* General purpose pointer (used by SPPP) */ + int magic; + int flags; + int count; /* count of opens */ + int line; + unsigned short close_delay; + unsigned short closing_wait; /* time to wait before closing */ + + struct mgsl_icount icount; + + struct tty_struct *tty; + int timeout; + int x_char; /* xon/xoff character */ + int blocked_open; /* # of blocked opens */ + unsigned char read_status_mask; + unsigned char ignore_status_mask; + + unsigned char *tx_buf; + int tx_put; + int tx_get; + int tx_count; + + /* circular list of fixed length rx buffers */ + + unsigned char *rx_buf; /* memory allocated for all rx buffers */ + int rx_buf_total_size; /* size of memory allocated for rx buffers */ + int rx_put; /* index of next empty rx buffer */ + int rx_get; /* index of next full rx buffer */ + int rx_buf_size; /* size in bytes of single rx buffer */ + int rx_buf_count; /* total number of rx buffers */ + int rx_frame_count; /* number of full rx buffers */ + + wait_queue_head_t open_wait; + wait_queue_head_t close_wait; + + wait_queue_head_t status_event_wait_q; + wait_queue_head_t event_wait_q; + struct timer_list tx_timer; /* HDLC transmit timeout timer */ + struct _mgslpc_info *next_device; /* device list link */ + + unsigned short imra_value; + unsigned short imrb_value; + unsigned char pim_value; + + spinlock_t lock; + struct work_struct task; /* task structure for scheduling bh */ + + u32 max_frame_size; + + u32 pending_bh; + + bool bh_running; + bool bh_requested; + + int dcd_chkcount; /* check counts to prevent */ + int cts_chkcount; /* too many IRQs if a signal */ + int dsr_chkcount; /* is floating */ + int ri_chkcount; + + bool rx_enabled; + bool rx_overflow; + + bool tx_enabled; + bool tx_active; + bool tx_aborting; + u32 idle_mode; + + int if_mode; /* serial interface selection (RS-232, v.35 etc) */ + + char device_name[25]; /* device instance name */ + + unsigned int io_base; /* base I/O address of adapter */ + unsigned int irq_level; + + MGSL_PARAMS params; /* communications parameters */ + + unsigned char serial_signals; /* current serial signal states */ + + bool irq_occurred; /* for diagnostics use */ + char testing_irq; + unsigned int init_error; /* startup error (DIAGS) */ + + char flag_buf[MAX_ASYNC_BUFFER_SIZE]; + bool drop_rts_on_tx_done; + + struct _input_signal_events input_signal_events; + + /* PCMCIA support */ + struct pcmcia_device *p_dev; + dev_node_t node; + int stop; + + /* SPPP/Cisco HDLC device parts */ + int netcount; + spinlock_t netlock; + +#if SYNCLINK_GENERIC_HDLC + struct net_device *netdev; +#endif + +} MGSLPC_INFO; + +#define MGSLPC_MAGIC 0x5402 + +/* + * The size of the serial xmit buffer is 1 page, or 4096 bytes + */ +#define TXBUFSIZE 4096 + + +#define CHA 0x00 /* channel A offset */ +#define CHB 0x40 /* channel B offset */ + +/* + * FIXME: PPC has PVR defined in asm/reg.h. For now we just undef it. + */ +#undef PVR + +#define RXFIFO 0 +#define TXFIFO 0 +#define STAR 0x20 +#define CMDR 0x20 +#define RSTA 0x21 +#define PRE 0x21 +#define MODE 0x22 +#define TIMR 0x23 +#define XAD1 0x24 +#define XAD2 0x25 +#define RAH1 0x26 +#define RAH2 0x27 +#define DAFO 0x27 +#define RAL1 0x28 +#define RFC 0x28 +#define RHCR 0x29 +#define RAL2 0x29 +#define RBCL 0x2a +#define XBCL 0x2a +#define RBCH 0x2b +#define XBCH 0x2b +#define CCR0 0x2c +#define CCR1 0x2d +#define CCR2 0x2e +#define CCR3 0x2f +#define VSTR 0x34 +#define BGR 0x34 +#define RLCR 0x35 +#define AML 0x36 +#define AMH 0x37 +#define GIS 0x38 +#define IVA 0x38 +#define IPC 0x39 +#define ISR 0x3a +#define IMR 0x3a +#define PVR 0x3c +#define PIS 0x3d +#define PIM 0x3d +#define PCR 0x3e +#define CCR4 0x3f + +// IMR/ISR + +#define IRQ_BREAK_ON BIT15 // rx break detected +#define IRQ_DATAOVERRUN BIT14 // receive data overflow +#define IRQ_ALLSENT BIT13 // all sent +#define IRQ_UNDERRUN BIT12 // transmit data underrun +#define IRQ_TIMER BIT11 // timer interrupt +#define IRQ_CTS BIT10 // CTS status change +#define IRQ_TXREPEAT BIT9 // tx message repeat +#define IRQ_TXFIFO BIT8 // transmit pool ready +#define IRQ_RXEOM BIT7 // receive message end +#define IRQ_EXITHUNT BIT6 // receive frame start +#define IRQ_RXTIME BIT6 // rx char timeout +#define IRQ_DCD BIT2 // carrier detect status change +#define IRQ_OVERRUN BIT1 // receive frame overflow +#define IRQ_RXFIFO BIT0 // receive pool full + +// STAR + +#define XFW BIT6 // transmit FIFO write enable +#define CEC BIT2 // command executing +#define CTS BIT1 // CTS state + +#define PVR_DTR BIT0 +#define PVR_DSR BIT1 +#define PVR_RI BIT2 +#define PVR_AUTOCTS BIT3 +#define PVR_RS232 0x20 /* 0010b */ +#define PVR_V35 0xe0 /* 1110b */ +#define PVR_RS422 0x40 /* 0100b */ + +/* Register access functions */ + +#define write_reg(info, reg, val) outb((val),(info)->io_base + (reg)) +#define read_reg(info, reg) inb((info)->io_base + (reg)) + +#define read_reg16(info, reg) inw((info)->io_base + (reg)) +#define write_reg16(info, reg, val) outw((val), (info)->io_base + (reg)) + +#define set_reg_bits(info, reg, mask) \ + write_reg(info, (reg), \ + (unsigned char) (read_reg(info, (reg)) | (mask))) +#define clear_reg_bits(info, reg, mask) \ + write_reg(info, (reg), \ + (unsigned char) (read_reg(info, (reg)) & ~(mask))) +/* + * interrupt enable/disable routines + */ +static void irq_disable(MGSLPC_INFO *info, unsigned char channel, unsigned short mask) +{ + if (channel == CHA) { + info->imra_value |= mask; + write_reg16(info, CHA + IMR, info->imra_value); + } else { + info->imrb_value |= mask; + write_reg16(info, CHB + IMR, info->imrb_value); + } +} +static void irq_enable(MGSLPC_INFO *info, unsigned char channel, unsigned short mask) +{ + if (channel == CHA) { + info->imra_value &= ~mask; + write_reg16(info, CHA + IMR, info->imra_value); + } else { + info->imrb_value &= ~mask; + write_reg16(info, CHB + IMR, info->imrb_value); + } +} + +#define port_irq_disable(info, mask) \ + { info->pim_value |= (mask); write_reg(info, PIM, info->pim_value); } + +#define port_irq_enable(info, mask) \ + { info->pim_value &= ~(mask); write_reg(info, PIM, info->pim_value); } + +static void rx_start(MGSLPC_INFO *info); +static void rx_stop(MGSLPC_INFO *info); + +static void tx_start(MGSLPC_INFO *info); +static void tx_stop(MGSLPC_INFO *info); +static void tx_set_idle(MGSLPC_INFO *info); + +static void get_signals(MGSLPC_INFO *info); +static void set_signals(MGSLPC_INFO *info); + +static void reset_device(MGSLPC_INFO *info); + +static void hdlc_mode(MGSLPC_INFO *info); +static void async_mode(MGSLPC_INFO *info); + +static void tx_timeout(unsigned long context); + +static int ioctl_common(MGSLPC_INFO *info, unsigned int cmd, unsigned long arg); + +#if SYNCLINK_GENERIC_HDLC +#define dev_to_port(D) (dev_to_hdlc(D)->priv) +static void hdlcdev_tx_done(MGSLPC_INFO *info); +static void hdlcdev_rx(MGSLPC_INFO *info, char *buf, int size); +static int hdlcdev_init(MGSLPC_INFO *info); +static void hdlcdev_exit(MGSLPC_INFO *info); +#endif + +static void trace_block(MGSLPC_INFO *info,const char* data, int count, int xmit); + +static bool register_test(MGSLPC_INFO *info); +static bool irq_test(MGSLPC_INFO *info); +static int adapter_test(MGSLPC_INFO *info); + +static int claim_resources(MGSLPC_INFO *info); +static void release_resources(MGSLPC_INFO *info); +static void mgslpc_add_device(MGSLPC_INFO *info); +static void mgslpc_remove_device(MGSLPC_INFO *info); + +static bool rx_get_frame(MGSLPC_INFO *info); +static void rx_reset_buffers(MGSLPC_INFO *info); +static int rx_alloc_buffers(MGSLPC_INFO *info); +static void rx_free_buffers(MGSLPC_INFO *info); + +static irqreturn_t mgslpc_isr(int irq, void *dev_id); + +/* + * Bottom half interrupt handlers + */ +static void bh_handler(struct work_struct *work); +static void bh_transmit(MGSLPC_INFO *info); +static void bh_status(MGSLPC_INFO *info); + +/* + * ioctl handlers + */ +static int tiocmget(struct tty_struct *tty, struct file *file); +static int tiocmset(struct tty_struct *tty, struct file *file, + unsigned int set, unsigned int clear); +static int get_stats(MGSLPC_INFO *info, struct mgsl_icount __user *user_icount); +static int get_params(MGSLPC_INFO *info, MGSL_PARAMS __user *user_params); +static int set_params(MGSLPC_INFO *info, MGSL_PARAMS __user *new_params); +static int get_txidle(MGSLPC_INFO *info, int __user *idle_mode); +static int set_txidle(MGSLPC_INFO *info, int idle_mode); +static int set_txenable(MGSLPC_INFO *info, int enable); +static int tx_abort(MGSLPC_INFO *info); +static int set_rxenable(MGSLPC_INFO *info, int enable); +static int wait_events(MGSLPC_INFO *info, int __user *mask); + +static MGSLPC_INFO *mgslpc_device_list = NULL; +static int mgslpc_device_count = 0; + +/* + * Set this param to non-zero to load eax with the + * .text section address and breakpoint on module load. + * This is useful for use with gdb and add-symbol-file command. + */ +static int break_on_load=0; + +/* + * Driver major number, defaults to zero to get auto + * assigned major number. May be forced as module parameter. + */ +static int ttymajor=0; + +static int debug_level = 0; +static int maxframe[MAX_DEVICE_COUNT] = {0,}; + +module_param(break_on_load, bool, 0); +module_param(ttymajor, int, 0); +module_param(debug_level, int, 0); +module_param_array(maxframe, int, NULL, 0); + +MODULE_LICENSE("GPL"); + +static char *driver_name = "SyncLink PC Card driver"; +static char *driver_version = "$Revision: 4.34 $"; + +static struct tty_driver *serial_driver; + +/* number of characters left in xmit buffer before we ask for more */ +#define WAKEUP_CHARS 256 + +static void mgslpc_change_params(MGSLPC_INFO *info); +static void mgslpc_wait_until_sent(struct tty_struct *tty, int timeout); + +/* PCMCIA prototypes */ + +static int mgslpc_config(struct pcmcia_device *link); +static void mgslpc_release(u_long arg); +static void mgslpc_detach(struct pcmcia_device *p_dev); + +/* + * 1st function defined in .text section. Calling this function in + * init_module() followed by a breakpoint allows a remote debugger + * (gdb) to get the .text address for the add-symbol-file command. + * This allows remote debugging of dynamically loadable modules. + */ +static void* mgslpc_get_text_ptr(void) +{ + return mgslpc_get_text_ptr; +} + +/** + * line discipline callback wrappers + * + * The wrappers maintain line discipline references + * while calling into the line discipline. + * + * ldisc_receive_buf - pass receive data to line discipline + */ + +static void ldisc_receive_buf(struct tty_struct *tty, + const __u8 *data, char *flags, int count) +{ + struct tty_ldisc *ld; + if (!tty) + return; + ld = tty_ldisc_ref(tty); + if (ld) { + if (ld->ops->receive_buf) + ld->ops->receive_buf(tty, data, flags, count); + tty_ldisc_deref(ld); + } +} + +static int mgslpc_probe(struct pcmcia_device *link) +{ + MGSLPC_INFO *info; + int ret; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("mgslpc_attach\n"); + + info = kzalloc(sizeof(MGSLPC_INFO), GFP_KERNEL); + if (!info) { + printk("Error can't allocate device instance data\n"); + return -ENOMEM; + } + + info->magic = MGSLPC_MAGIC; + INIT_WORK(&info->task, bh_handler); + info->max_frame_size = 4096; + info->close_delay = 5*HZ/10; + info->closing_wait = 30*HZ; + init_waitqueue_head(&info->open_wait); + init_waitqueue_head(&info->close_wait); + init_waitqueue_head(&info->status_event_wait_q); + init_waitqueue_head(&info->event_wait_q); + spin_lock_init(&info->lock); + spin_lock_init(&info->netlock); + memcpy(&info->params,&default_params,sizeof(MGSL_PARAMS)); + info->idle_mode = HDLC_TXIDLE_FLAGS; + info->imra_value = 0xffff; + info->imrb_value = 0xffff; + info->pim_value = 0xff; + + info->p_dev = link; + link->priv = info; + + /* Initialize the struct pcmcia_device structure */ + + /* Interrupt setup */ + link->irq.Attributes = IRQ_TYPE_DYNAMIC_SHARING; + link->irq.IRQInfo1 = IRQ_LEVEL_ID; + link->irq.Handler = NULL; + + link->conf.Attributes = 0; + link->conf.IntType = INT_MEMORY_AND_IO; + + ret = mgslpc_config(link); + if (ret) + return ret; + + mgslpc_add_device(info); + + return 0; +} + +/* Card has been inserted. + */ + +#define CS_CHECK(fn, ret) \ +do { last_fn = (fn); if ((last_ret = (ret)) != 0) goto cs_failed; } while (0) + +static int mgslpc_config(struct pcmcia_device *link) +{ + MGSLPC_INFO *info = link->priv; + tuple_t tuple; + cisparse_t parse; + int last_fn, last_ret; + u_char buf[64]; + cistpl_cftable_entry_t dflt = { 0 }; + cistpl_cftable_entry_t *cfg; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("mgslpc_config(0x%p)\n", link); + + tuple.Attributes = 0; + tuple.TupleData = buf; + tuple.TupleDataMax = sizeof(buf); + tuple.TupleOffset = 0; + + /* get CIS configuration entry */ + + tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY; + CS_CHECK(GetFirstTuple, pcmcia_get_first_tuple(link, &tuple)); + + cfg = &(parse.cftable_entry); + CS_CHECK(GetTupleData, pcmcia_get_tuple_data(link, &tuple)); + CS_CHECK(ParseTuple, pcmcia_parse_tuple(&tuple, &parse)); + + if (cfg->flags & CISTPL_CFTABLE_DEFAULT) dflt = *cfg; + if (cfg->index == 0) + goto cs_failed; + + link->conf.ConfigIndex = cfg->index; + link->conf.Attributes |= CONF_ENABLE_IRQ; + + /* IO window settings */ + link->io.NumPorts1 = 0; + if ((cfg->io.nwin > 0) || (dflt.io.nwin > 0)) { + cistpl_io_t *io = (cfg->io.nwin) ? &cfg->io : &dflt.io; + link->io.Attributes1 = IO_DATA_PATH_WIDTH_AUTO; + if (!(io->flags & CISTPL_IO_8BIT)) + link->io.Attributes1 = IO_DATA_PATH_WIDTH_16; + if (!(io->flags & CISTPL_IO_16BIT)) + link->io.Attributes1 = IO_DATA_PATH_WIDTH_8; + link->io.IOAddrLines = io->flags & CISTPL_IO_LINES_MASK; + link->io.BasePort1 = io->win[0].base; + link->io.NumPorts1 = io->win[0].len; + CS_CHECK(RequestIO, pcmcia_request_io(link, &link->io)); + } + + link->conf.Attributes = CONF_ENABLE_IRQ; + link->conf.IntType = INT_MEMORY_AND_IO; + link->conf.ConfigIndex = 8; + link->conf.Present = PRESENT_OPTION; + + link->irq.Attributes |= IRQ_HANDLE_PRESENT; + link->irq.Handler = mgslpc_isr; + link->irq.Instance = info; + CS_CHECK(RequestIRQ, pcmcia_request_irq(link, &link->irq)); + + CS_CHECK(RequestConfiguration, pcmcia_request_configuration(link, &link->conf)); + + info->io_base = link->io.BasePort1; + info->irq_level = link->irq.AssignedIRQ; + + /* add to linked list of devices */ + sprintf(info->node.dev_name, "mgslpc0"); + info->node.major = info->node.minor = 0; + link->dev_node = &info->node; + + printk(KERN_INFO "%s: index 0x%02x:", + info->node.dev_name, link->conf.ConfigIndex); + if (link->conf.Attributes & CONF_ENABLE_IRQ) + printk(", irq %d", link->irq.AssignedIRQ); + if (link->io.NumPorts1) + printk(", io 0x%04x-0x%04x", link->io.BasePort1, + link->io.BasePort1+link->io.NumPorts1-1); + printk("\n"); + return 0; + +cs_failed: + cs_error(link, last_fn, last_ret); + mgslpc_release((u_long)link); + return -ENODEV; +} + +/* Card has been removed. + * Unregister device and release PCMCIA configuration. + * If device is open, postpone until it is closed. + */ +static void mgslpc_release(u_long arg) +{ + struct pcmcia_device *link = (struct pcmcia_device *)arg; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("mgslpc_release(0x%p)\n", link); + + pcmcia_disable_device(link); +} + +static void mgslpc_detach(struct pcmcia_device *link) +{ + if (debug_level >= DEBUG_LEVEL_INFO) + printk("mgslpc_detach(0x%p)\n", link); + + ((MGSLPC_INFO *)link->priv)->stop = 1; + mgslpc_release((u_long)link); + + mgslpc_remove_device((MGSLPC_INFO *)link->priv); +} + +static int mgslpc_suspend(struct pcmcia_device *link) +{ + MGSLPC_INFO *info = link->priv; + + info->stop = 1; + + return 0; +} + +static int mgslpc_resume(struct pcmcia_device *link) +{ + MGSLPC_INFO *info = link->priv; + + info->stop = 0; + + return 0; +} + + +static inline bool mgslpc_paranoia_check(MGSLPC_INFO *info, + char *name, const char *routine) +{ +#ifdef MGSLPC_PARANOIA_CHECK + static const char *badmagic = + "Warning: bad magic number for mgsl struct (%s) in %s\n"; + static const char *badinfo = + "Warning: null mgslpc_info for (%s) in %s\n"; + + if (!info) { + printk(badinfo, name, routine); + return true; + } + if (info->magic != MGSLPC_MAGIC) { + printk(badmagic, name, routine); + return true; + } +#else + if (!info) + return true; +#endif + return false; +} + + +#define CMD_RXFIFO BIT7 // release current rx FIFO +#define CMD_RXRESET BIT6 // receiver reset +#define CMD_RXFIFO_READ BIT5 +#define CMD_START_TIMER BIT4 +#define CMD_TXFIFO BIT3 // release current tx FIFO +#define CMD_TXEOM BIT1 // transmit end message +#define CMD_TXRESET BIT0 // transmit reset + +static bool wait_command_complete(MGSLPC_INFO *info, unsigned char channel) +{ + int i = 0; + /* wait for command completion */ + while (read_reg(info, (unsigned char)(channel+STAR)) & BIT2) { + udelay(1); + if (i++ == 1000) + return false; + } + return true; +} + +static void issue_command(MGSLPC_INFO *info, unsigned char channel, unsigned char cmd) +{ + wait_command_complete(info, channel); + write_reg(info, (unsigned char) (channel + CMDR), cmd); +} + +static void tx_pause(struct tty_struct *tty) +{ + MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data; + unsigned long flags; + + if (mgslpc_paranoia_check(info, tty->name, "tx_pause")) + return; + if (debug_level >= DEBUG_LEVEL_INFO) + printk("tx_pause(%s)\n",info->device_name); + + spin_lock_irqsave(&info->lock,flags); + if (info->tx_enabled) + tx_stop(info); + spin_unlock_irqrestore(&info->lock,flags); +} + +static void tx_release(struct tty_struct *tty) +{ + MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data; + unsigned long flags; + + if (mgslpc_paranoia_check(info, tty->name, "tx_release")) + return; + if (debug_level >= DEBUG_LEVEL_INFO) + printk("tx_release(%s)\n",info->device_name); + + spin_lock_irqsave(&info->lock,flags); + if (!info->tx_enabled) + tx_start(info); + spin_unlock_irqrestore(&info->lock,flags); +} + +/* Return next bottom half action to perform. + * or 0 if nothing to do. + */ +static int bh_action(MGSLPC_INFO *info) +{ + unsigned long flags; + int rc = 0; + + spin_lock_irqsave(&info->lock,flags); + + if (info->pending_bh & BH_RECEIVE) { + info->pending_bh &= ~BH_RECEIVE; + rc = BH_RECEIVE; + } else if (info->pending_bh & BH_TRANSMIT) { + info->pending_bh &= ~BH_TRANSMIT; + rc = BH_TRANSMIT; + } else if (info->pending_bh & BH_STATUS) { + info->pending_bh &= ~BH_STATUS; + rc = BH_STATUS; + } + + if (!rc) { + /* Mark BH routine as complete */ + info->bh_running = false; + info->bh_requested = false; + } + + spin_unlock_irqrestore(&info->lock,flags); + + return rc; +} + +static void bh_handler(struct work_struct *work) +{ + MGSLPC_INFO *info = container_of(work, MGSLPC_INFO, task); + int action; + + if (!info) + return; + + if (debug_level >= DEBUG_LEVEL_BH) + printk( "%s(%d):bh_handler(%s) entry\n", + __FILE__,__LINE__,info->device_name); + + info->bh_running = true; + + while((action = bh_action(info)) != 0) { + + /* Process work item */ + if ( debug_level >= DEBUG_LEVEL_BH ) + printk( "%s(%d):bh_handler() work item action=%d\n", + __FILE__,__LINE__,action); + + switch (action) { + + case BH_RECEIVE: + while(rx_get_frame(info)); + break; + case BH_TRANSMIT: + bh_transmit(info); + break; + case BH_STATUS: + bh_status(info); + break; + default: + /* unknown work item ID */ + printk("Unknown work item ID=%08X!\n", action); + break; + } + } + + if (debug_level >= DEBUG_LEVEL_BH) + printk( "%s(%d):bh_handler(%s) exit\n", + __FILE__,__LINE__,info->device_name); +} + +static void bh_transmit(MGSLPC_INFO *info) +{ + struct tty_struct *tty = info->tty; + if (debug_level >= DEBUG_LEVEL_BH) + printk("bh_transmit() entry on %s\n", info->device_name); + + if (tty) + tty_wakeup(tty); +} + +static void bh_status(MGSLPC_INFO *info) +{ + info->ri_chkcount = 0; + info->dsr_chkcount = 0; + info->dcd_chkcount = 0; + info->cts_chkcount = 0; +} + +/* eom: non-zero = end of frame */ +static void rx_ready_hdlc(MGSLPC_INFO *info, int eom) +{ + unsigned char data[2]; + unsigned char fifo_count, read_count, i; + RXBUF *buf = (RXBUF*)(info->rx_buf + (info->rx_put * info->rx_buf_size)); + + if (debug_level >= DEBUG_LEVEL_ISR) + printk("%s(%d):rx_ready_hdlc(eom=%d)\n",__FILE__,__LINE__,eom); + + if (!info->rx_enabled) + return; + + if (info->rx_frame_count >= info->rx_buf_count) { + /* no more free buffers */ + issue_command(info, CHA, CMD_RXRESET); + info->pending_bh |= BH_RECEIVE; + info->rx_overflow = true; + info->icount.buf_overrun++; + return; + } + + if (eom) { + /* end of frame, get FIFO count from RBCL register */ + if (!(fifo_count = (unsigned char)(read_reg(info, CHA+RBCL) & 0x1f))) + fifo_count = 32; + } else + fifo_count = 32; + + do { + if (fifo_count == 1) { + read_count = 1; + data[0] = read_reg(info, CHA + RXFIFO); + } else { + read_count = 2; + *((unsigned short *) data) = read_reg16(info, CHA + RXFIFO); + } + fifo_count -= read_count; + if (!fifo_count && eom) + buf->status = data[--read_count]; + + for (i = 0; i < read_count; i++) { + if (buf->count >= info->max_frame_size) { + /* frame too large, reset receiver and reset current buffer */ + issue_command(info, CHA, CMD_RXRESET); + buf->count = 0; + return; + } + *(buf->data + buf->count) = data[i]; + buf->count++; + } + } while (fifo_count); + + if (eom) { + info->pending_bh |= BH_RECEIVE; + info->rx_frame_count++; + info->rx_put++; + if (info->rx_put >= info->rx_buf_count) + info->rx_put = 0; + } + issue_command(info, CHA, CMD_RXFIFO); +} + +static void rx_ready_async(MGSLPC_INFO *info, int tcd) +{ + unsigned char data, status, flag; + int fifo_count; + int work = 0; + struct tty_struct *tty = info->tty; + struct mgsl_icount *icount = &info->icount; + + if (tcd) { + /* early termination, get FIFO count from RBCL register */ + fifo_count = (unsigned char)(read_reg(info, CHA+RBCL) & 0x1f); + + /* Zero fifo count could mean 0 or 32 bytes available. + * If BIT5 of STAR is set then at least 1 byte is available. + */ + if (!fifo_count && (read_reg(info,CHA+STAR) & BIT5)) + fifo_count = 32; + } else + fifo_count = 32; + + tty_buffer_request_room(tty, fifo_count); + /* Flush received async data to receive data buffer. */ + while (fifo_count) { + data = read_reg(info, CHA + RXFIFO); + status = read_reg(info, CHA + RXFIFO); + fifo_count -= 2; + + icount->rx++; + flag = TTY_NORMAL; + + // if no frameing/crc error then save data + // BIT7:parity error + // BIT6:framing error + + if (status & (BIT7 + BIT6)) { + if (status & BIT7) + icount->parity++; + else + icount->frame++; + + /* discard char if tty control flags say so */ + if (status & info->ignore_status_mask) + continue; + + status &= info->read_status_mask; + + if (status & BIT7) + flag = TTY_PARITY; + else if (status & BIT6) + flag = TTY_FRAME; + } + work += tty_insert_flip_char(tty, data, flag); + } + issue_command(info, CHA, CMD_RXFIFO); + + if (debug_level >= DEBUG_LEVEL_ISR) { + printk("%s(%d):rx_ready_async", + __FILE__,__LINE__); + printk("%s(%d):rx=%d brk=%d parity=%d frame=%d overrun=%d\n", + __FILE__,__LINE__,icount->rx,icount->brk, + icount->parity,icount->frame,icount->overrun); + } + + if (work) + tty_flip_buffer_push(tty); +} + + +static void tx_done(MGSLPC_INFO *info) +{ + if (!info->tx_active) + return; + + info->tx_active = false; + info->tx_aborting = false; + + if (info->params.mode == MGSL_MODE_ASYNC) + return; + + info->tx_count = info->tx_put = info->tx_get = 0; + del_timer(&info->tx_timer); + + if (info->drop_rts_on_tx_done) { + get_signals(info); + if (info->serial_signals & SerialSignal_RTS) { + info->serial_signals &= ~SerialSignal_RTS; + set_signals(info); + } + info->drop_rts_on_tx_done = false; + } + +#if SYNCLINK_GENERIC_HDLC + if (info->netcount) + hdlcdev_tx_done(info); + else +#endif + { + if (info->tty->stopped || info->tty->hw_stopped) { + tx_stop(info); + return; + } + info->pending_bh |= BH_TRANSMIT; + } +} + +static void tx_ready(MGSLPC_INFO *info) +{ + unsigned char fifo_count = 32; + int c; + + if (debug_level >= DEBUG_LEVEL_ISR) + printk("%s(%d):tx_ready(%s)\n", __FILE__,__LINE__,info->device_name); + + if (info->params.mode == MGSL_MODE_HDLC) { + if (!info->tx_active) + return; + } else { + if (info->tty->stopped || info->tty->hw_stopped) { + tx_stop(info); + return; + } + if (!info->tx_count) + info->tx_active = false; + } + + if (!info->tx_count) + return; + + while (info->tx_count && fifo_count) { + c = min(2, min_t(int, fifo_count, min(info->tx_count, TXBUFSIZE - info->tx_get))); + + if (c == 1) { + write_reg(info, CHA + TXFIFO, *(info->tx_buf + info->tx_get)); + } else { + write_reg16(info, CHA + TXFIFO, + *((unsigned short*)(info->tx_buf + info->tx_get))); + } + info->tx_count -= c; + info->tx_get = (info->tx_get + c) & (TXBUFSIZE - 1); + fifo_count -= c; + } + + if (info->params.mode == MGSL_MODE_ASYNC) { + if (info->tx_count < WAKEUP_CHARS) + info->pending_bh |= BH_TRANSMIT; + issue_command(info, CHA, CMD_TXFIFO); + } else { + if (info->tx_count) + issue_command(info, CHA, CMD_TXFIFO); + else + issue_command(info, CHA, CMD_TXFIFO + CMD_TXEOM); + } +} + +static void cts_change(MGSLPC_INFO *info) +{ + get_signals(info); + if ((info->cts_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT) + irq_disable(info, CHB, IRQ_CTS); + info->icount.cts++; + if (info->serial_signals & SerialSignal_CTS) + info->input_signal_events.cts_up++; + else + info->input_signal_events.cts_down++; + wake_up_interruptible(&info->status_event_wait_q); + wake_up_interruptible(&info->event_wait_q); + + if (info->flags & ASYNC_CTS_FLOW) { + if (info->tty->hw_stopped) { + if (info->serial_signals & SerialSignal_CTS) { + if (debug_level >= DEBUG_LEVEL_ISR) + printk("CTS tx start..."); + if (info->tty) + info->tty->hw_stopped = 0; + tx_start(info); + info->pending_bh |= BH_TRANSMIT; + return; + } + } else { + if (!(info->serial_signals & SerialSignal_CTS)) { + if (debug_level >= DEBUG_LEVEL_ISR) + printk("CTS tx stop..."); + if (info->tty) + info->tty->hw_stopped = 1; + tx_stop(info); + } + } + } + info->pending_bh |= BH_STATUS; +} + +static void dcd_change(MGSLPC_INFO *info) +{ + get_signals(info); + if ((info->dcd_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT) + irq_disable(info, CHB, IRQ_DCD); + info->icount.dcd++; + if (info->serial_signals & SerialSignal_DCD) { + info->input_signal_events.dcd_up++; + } + else + info->input_signal_events.dcd_down++; +#if SYNCLINK_GENERIC_HDLC + if (info->netcount) { + if (info->serial_signals & SerialSignal_DCD) + netif_carrier_on(info->netdev); + else + netif_carrier_off(info->netdev); + } +#endif + wake_up_interruptible(&info->status_event_wait_q); + wake_up_interruptible(&info->event_wait_q); + + if (info->flags & ASYNC_CHECK_CD) { + if (debug_level >= DEBUG_LEVEL_ISR) + printk("%s CD now %s...", info->device_name, + (info->serial_signals & SerialSignal_DCD) ? "on" : "off"); + if (info->serial_signals & SerialSignal_DCD) + wake_up_interruptible(&info->open_wait); + else { + if (debug_level >= DEBUG_LEVEL_ISR) + printk("doing serial hangup..."); + if (info->tty) + tty_hangup(info->tty); + } + } + info->pending_bh |= BH_STATUS; +} + +static void dsr_change(MGSLPC_INFO *info) +{ + get_signals(info); + if ((info->dsr_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT) + port_irq_disable(info, PVR_DSR); + info->icount.dsr++; + if (info->serial_signals & SerialSignal_DSR) + info->input_signal_events.dsr_up++; + else + info->input_signal_events.dsr_down++; + wake_up_interruptible(&info->status_event_wait_q); + wake_up_interruptible(&info->event_wait_q); + info->pending_bh |= BH_STATUS; +} + +static void ri_change(MGSLPC_INFO *info) +{ + get_signals(info); + if ((info->ri_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT) + port_irq_disable(info, PVR_RI); + info->icount.rng++; + if (info->serial_signals & SerialSignal_RI) + info->input_signal_events.ri_up++; + else + info->input_signal_events.ri_down++; + wake_up_interruptible(&info->status_event_wait_q); + wake_up_interruptible(&info->event_wait_q); + info->pending_bh |= BH_STATUS; +} + +/* Interrupt service routine entry point. + * + * Arguments: + * + * irq interrupt number that caused interrupt + * dev_id device ID supplied during interrupt registration + */ +static irqreturn_t mgslpc_isr(int dummy, void *dev_id) +{ + MGSLPC_INFO *info = dev_id; + unsigned short isr; + unsigned char gis, pis; + int count=0; + + if (debug_level >= DEBUG_LEVEL_ISR) + printk("mgslpc_isr(%d) entry.\n", info->irq_level); + + if (!(info->p_dev->_locked)) + return IRQ_HANDLED; + + spin_lock(&info->lock); + + while ((gis = read_reg(info, CHA + GIS))) { + if (debug_level >= DEBUG_LEVEL_ISR) + printk("mgslpc_isr %s gis=%04X\n", info->device_name,gis); + + if ((gis & 0x70) || count > 1000) { + printk("synclink_cs:hardware failed or ejected\n"); + break; + } + count++; + + if (gis & (BIT1 + BIT0)) { + isr = read_reg16(info, CHB + ISR); + if (isr & IRQ_DCD) + dcd_change(info); + if (isr & IRQ_CTS) + cts_change(info); + } + if (gis & (BIT3 + BIT2)) + { + isr = read_reg16(info, CHA + ISR); + if (isr & IRQ_TIMER) { + info->irq_occurred = true; + irq_disable(info, CHA, IRQ_TIMER); + } + + /* receive IRQs */ + if (isr & IRQ_EXITHUNT) { + info->icount.exithunt++; + wake_up_interruptible(&info->event_wait_q); + } + if (isr & IRQ_BREAK_ON) { + info->icount.brk++; + if (info->flags & ASYNC_SAK) + do_SAK(info->tty); + } + if (isr & IRQ_RXTIME) { + issue_command(info, CHA, CMD_RXFIFO_READ); + } + if (isr & (IRQ_RXEOM + IRQ_RXFIFO)) { + if (info->params.mode == MGSL_MODE_HDLC) + rx_ready_hdlc(info, isr & IRQ_RXEOM); + else + rx_ready_async(info, isr & IRQ_RXEOM); + } + + /* transmit IRQs */ + if (isr & IRQ_UNDERRUN) { + if (info->tx_aborting) + info->icount.txabort++; + else + info->icount.txunder++; + tx_done(info); + } + else if (isr & IRQ_ALLSENT) { + info->icount.txok++; + tx_done(info); + } + else if (isr & IRQ_TXFIFO) + tx_ready(info); + } + if (gis & BIT7) { + pis = read_reg(info, CHA + PIS); + if (pis & BIT1) + dsr_change(info); + if (pis & BIT2) + ri_change(info); + } + } + + /* Request bottom half processing if there's something + * for it to do and the bh is not already running + */ + + if (info->pending_bh && !info->bh_running && !info->bh_requested) { + if ( debug_level >= DEBUG_LEVEL_ISR ) + printk("%s(%d):%s queueing bh task.\n", + __FILE__,__LINE__,info->device_name); + schedule_work(&info->task); + info->bh_requested = true; + } + + spin_unlock(&info->lock); + + if (debug_level >= DEBUG_LEVEL_ISR) + printk("%s(%d):mgslpc_isr(%d)exit.\n", + __FILE__, __LINE__, info->irq_level); + + return IRQ_HANDLED; +} + +/* Initialize and start device. + */ +static int startup(MGSLPC_INFO * info) +{ + int retval = 0; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):startup(%s)\n",__FILE__,__LINE__,info->device_name); + + if (info->flags & ASYNC_INITIALIZED) + return 0; + + if (!info->tx_buf) { + /* allocate a page of memory for a transmit buffer */ + info->tx_buf = (unsigned char *)get_zeroed_page(GFP_KERNEL); + if (!info->tx_buf) { + printk(KERN_ERR"%s(%d):%s can't allocate transmit buffer\n", + __FILE__,__LINE__,info->device_name); + return -ENOMEM; + } + } + + info->pending_bh = 0; + + memset(&info->icount, 0, sizeof(info->icount)); + + setup_timer(&info->tx_timer, tx_timeout, (unsigned long)info); + + /* Allocate and claim adapter resources */ + retval = claim_resources(info); + + /* perform existance check and diagnostics */ + if ( !retval ) + retval = adapter_test(info); + + if ( retval ) { + if (capable(CAP_SYS_ADMIN) && info->tty) + set_bit(TTY_IO_ERROR, &info->tty->flags); + release_resources(info); + return retval; + } + + /* program hardware for current parameters */ + mgslpc_change_params(info); + + if (info->tty) + clear_bit(TTY_IO_ERROR, &info->tty->flags); + + info->flags |= ASYNC_INITIALIZED; + + return 0; +} + +/* Called by mgslpc_close() and mgslpc_hangup() to shutdown hardware + */ +static void shutdown(MGSLPC_INFO * info) +{ + unsigned long flags; + + if (!(info->flags & ASYNC_INITIALIZED)) + return; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_shutdown(%s)\n", + __FILE__,__LINE__, info->device_name ); + + /* clear status wait queue because status changes */ + /* can't happen after shutting down the hardware */ + wake_up_interruptible(&info->status_event_wait_q); + wake_up_interruptible(&info->event_wait_q); + + del_timer_sync(&info->tx_timer); + + if (info->tx_buf) { + free_page((unsigned long) info->tx_buf); + info->tx_buf = NULL; + } + + spin_lock_irqsave(&info->lock,flags); + + rx_stop(info); + tx_stop(info); + + /* TODO:disable interrupts instead of reset to preserve signal states */ + reset_device(info); + + if (!info->tty || info->tty->termios->c_cflag & HUPCL) { + info->serial_signals &= ~(SerialSignal_DTR + SerialSignal_RTS); + set_signals(info); + } + + spin_unlock_irqrestore(&info->lock,flags); + + release_resources(info); + + if (info->tty) + set_bit(TTY_IO_ERROR, &info->tty->flags); + + info->flags &= ~ASYNC_INITIALIZED; +} + +static void mgslpc_program_hw(MGSLPC_INFO *info) +{ + unsigned long flags; + + spin_lock_irqsave(&info->lock,flags); + + rx_stop(info); + tx_stop(info); + info->tx_count = info->tx_put = info->tx_get = 0; + + if (info->params.mode == MGSL_MODE_HDLC || info->netcount) + hdlc_mode(info); + else + async_mode(info); + + set_signals(info); + + info->dcd_chkcount = 0; + info->cts_chkcount = 0; + info->ri_chkcount = 0; + info->dsr_chkcount = 0; + + irq_enable(info, CHB, IRQ_DCD | IRQ_CTS); + port_irq_enable(info, (unsigned char) PVR_DSR | PVR_RI); + get_signals(info); + + if (info->netcount || info->tty->termios->c_cflag & CREAD) + rx_start(info); + + spin_unlock_irqrestore(&info->lock,flags); +} + +/* Reconfigure adapter based on new parameters + */ +static void mgslpc_change_params(MGSLPC_INFO *info) +{ + unsigned cflag; + int bits_per_char; + + if (!info->tty || !info->tty->termios) + return; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_change_params(%s)\n", + __FILE__,__LINE__, info->device_name ); + + cflag = info->tty->termios->c_cflag; + + /* if B0 rate (hangup) specified then negate DTR and RTS */ + /* otherwise assert DTR and RTS */ + if (cflag & CBAUD) + info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR; + else + info->serial_signals &= ~(SerialSignal_RTS + SerialSignal_DTR); + + /* byte size and parity */ + + switch (cflag & CSIZE) { + case CS5: info->params.data_bits = 5; break; + case CS6: info->params.data_bits = 6; break; + case CS7: info->params.data_bits = 7; break; + case CS8: info->params.data_bits = 8; break; + default: info->params.data_bits = 7; break; + } + + if (cflag & CSTOPB) + info->params.stop_bits = 2; + else + info->params.stop_bits = 1; + + info->params.parity = ASYNC_PARITY_NONE; + if (cflag & PARENB) { + if (cflag & PARODD) + info->params.parity = ASYNC_PARITY_ODD; + else + info->params.parity = ASYNC_PARITY_EVEN; +#ifdef CMSPAR + if (cflag & CMSPAR) + info->params.parity = ASYNC_PARITY_SPACE; +#endif + } + + /* calculate number of jiffies to transmit a full + * FIFO (32 bytes) at specified data rate + */ + bits_per_char = info->params.data_bits + + info->params.stop_bits + 1; + + /* if port data rate is set to 460800 or less then + * allow tty settings to override, otherwise keep the + * current data rate. + */ + if (info->params.data_rate <= 460800) { + info->params.data_rate = tty_get_baud_rate(info->tty); + } + + if ( info->params.data_rate ) { + info->timeout = (32*HZ*bits_per_char) / + info->params.data_rate; + } + info->timeout += HZ/50; /* Add .02 seconds of slop */ + + if (cflag & CRTSCTS) + info->flags |= ASYNC_CTS_FLOW; + else + info->flags &= ~ASYNC_CTS_FLOW; + + if (cflag & CLOCAL) + info->flags &= ~ASYNC_CHECK_CD; + else + info->flags |= ASYNC_CHECK_CD; + + /* process tty input control flags */ + + info->read_status_mask = 0; + if (I_INPCK(info->tty)) + info->read_status_mask |= BIT7 | BIT6; + if (I_IGNPAR(info->tty)) + info->ignore_status_mask |= BIT7 | BIT6; + + mgslpc_program_hw(info); +} + +/* Add a character to the transmit buffer + */ +static int mgslpc_put_char(struct tty_struct *tty, unsigned char ch) +{ + MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data; + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) { + printk( "%s(%d):mgslpc_put_char(%d) on %s\n", + __FILE__,__LINE__,ch,info->device_name); + } + + if (mgslpc_paranoia_check(info, tty->name, "mgslpc_put_char")) + return 0; + + if (!info->tx_buf) + return 0; + + spin_lock_irqsave(&info->lock,flags); + + if (info->params.mode == MGSL_MODE_ASYNC || !info->tx_active) { + if (info->tx_count < TXBUFSIZE - 1) { + info->tx_buf[info->tx_put++] = ch; + info->tx_put &= TXBUFSIZE-1; + info->tx_count++; + } + } + + spin_unlock_irqrestore(&info->lock,flags); + return 1; +} + +/* Enable transmitter so remaining characters in the + * transmit buffer are sent. + */ +static void mgslpc_flush_chars(struct tty_struct *tty) +{ + MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data; + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk( "%s(%d):mgslpc_flush_chars() entry on %s tx_count=%d\n", + __FILE__,__LINE__,info->device_name,info->tx_count); + + if (mgslpc_paranoia_check(info, tty->name, "mgslpc_flush_chars")) + return; + + if (info->tx_count <= 0 || tty->stopped || + tty->hw_stopped || !info->tx_buf) + return; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk( "%s(%d):mgslpc_flush_chars() entry on %s starting transmitter\n", + __FILE__,__LINE__,info->device_name); + + spin_lock_irqsave(&info->lock,flags); + if (!info->tx_active) + tx_start(info); + spin_unlock_irqrestore(&info->lock,flags); +} + +/* Send a block of data + * + * Arguments: + * + * tty pointer to tty information structure + * buf pointer to buffer containing send data + * count size of send data in bytes + * + * Returns: number of characters written + */ +static int mgslpc_write(struct tty_struct * tty, + const unsigned char *buf, int count) +{ + int c, ret = 0; + MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data; + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk( "%s(%d):mgslpc_write(%s) count=%d\n", + __FILE__,__LINE__,info->device_name,count); + + if (mgslpc_paranoia_check(info, tty->name, "mgslpc_write") || + !info->tx_buf) + goto cleanup; + + if (info->params.mode == MGSL_MODE_HDLC) { + if (count > TXBUFSIZE) { + ret = -EIO; + goto cleanup; + } + if (info->tx_active) + goto cleanup; + else if (info->tx_count) + goto start; + } + + for (;;) { + c = min(count, + min(TXBUFSIZE - info->tx_count - 1, + TXBUFSIZE - info->tx_put)); + if (c <= 0) + break; + + memcpy(info->tx_buf + info->tx_put, buf, c); + + spin_lock_irqsave(&info->lock,flags); + info->tx_put = (info->tx_put + c) & (TXBUFSIZE-1); + info->tx_count += c; + spin_unlock_irqrestore(&info->lock,flags); + + buf += c; + count -= c; + ret += c; + } +start: + if (info->tx_count && !tty->stopped && !tty->hw_stopped) { + spin_lock_irqsave(&info->lock,flags); + if (!info->tx_active) + tx_start(info); + spin_unlock_irqrestore(&info->lock,flags); + } +cleanup: + if (debug_level >= DEBUG_LEVEL_INFO) + printk( "%s(%d):mgslpc_write(%s) returning=%d\n", + __FILE__,__LINE__,info->device_name,ret); + return ret; +} + +/* Return the count of free bytes in transmit buffer + */ +static int mgslpc_write_room(struct tty_struct *tty) +{ + MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data; + int ret; + + if (mgslpc_paranoia_check(info, tty->name, "mgslpc_write_room")) + return 0; + + if (info->params.mode == MGSL_MODE_HDLC) { + /* HDLC (frame oriented) mode */ + if (info->tx_active) + return 0; + else + return HDLC_MAX_FRAME_SIZE; + } else { + ret = TXBUFSIZE - info->tx_count - 1; + if (ret < 0) + ret = 0; + } + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_write_room(%s)=%d\n", + __FILE__,__LINE__, info->device_name, ret); + return ret; +} + +/* Return the count of bytes in transmit buffer + */ +static int mgslpc_chars_in_buffer(struct tty_struct *tty) +{ + MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data; + int rc; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_chars_in_buffer(%s)\n", + __FILE__,__LINE__, info->device_name ); + + if (mgslpc_paranoia_check(info, tty->name, "mgslpc_chars_in_buffer")) + return 0; + + if (info->params.mode == MGSL_MODE_HDLC) + rc = info->tx_active ? info->max_frame_size : 0; + else + rc = info->tx_count; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_chars_in_buffer(%s)=%d\n", + __FILE__,__LINE__, info->device_name, rc); + + return rc; +} + +/* Discard all data in the send buffer + */ +static void mgslpc_flush_buffer(struct tty_struct *tty) +{ + MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data; + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_flush_buffer(%s) entry\n", + __FILE__,__LINE__, info->device_name ); + + if (mgslpc_paranoia_check(info, tty->name, "mgslpc_flush_buffer")) + return; + + spin_lock_irqsave(&info->lock,flags); + info->tx_count = info->tx_put = info->tx_get = 0; + del_timer(&info->tx_timer); + spin_unlock_irqrestore(&info->lock,flags); + + wake_up_interruptible(&tty->write_wait); + tty_wakeup(tty); +} + +/* Send a high-priority XON/XOFF character + */ +static void mgslpc_send_xchar(struct tty_struct *tty, char ch) +{ + MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data; + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_send_xchar(%s,%d)\n", + __FILE__,__LINE__, info->device_name, ch ); + + if (mgslpc_paranoia_check(info, tty->name, "mgslpc_send_xchar")) + return; + + info->x_char = ch; + if (ch) { + spin_lock_irqsave(&info->lock,flags); + if (!info->tx_enabled) + tx_start(info); + spin_unlock_irqrestore(&info->lock,flags); + } +} + +/* Signal remote device to throttle send data (our receive data) + */ +static void mgslpc_throttle(struct tty_struct * tty) +{ + MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data; + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_throttle(%s) entry\n", + __FILE__,__LINE__, info->device_name ); + + if (mgslpc_paranoia_check(info, tty->name, "mgslpc_throttle")) + return; + + if (I_IXOFF(tty)) + mgslpc_send_xchar(tty, STOP_CHAR(tty)); + + if (tty->termios->c_cflag & CRTSCTS) { + spin_lock_irqsave(&info->lock,flags); + info->serial_signals &= ~SerialSignal_RTS; + set_signals(info); + spin_unlock_irqrestore(&info->lock,flags); + } +} + +/* Signal remote device to stop throttling send data (our receive data) + */ +static void mgslpc_unthrottle(struct tty_struct * tty) +{ + MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data; + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_unthrottle(%s) entry\n", + __FILE__,__LINE__, info->device_name ); + + if (mgslpc_paranoia_check(info, tty->name, "mgslpc_unthrottle")) + return; + + if (I_IXOFF(tty)) { + if (info->x_char) + info->x_char = 0; + else + mgslpc_send_xchar(tty, START_CHAR(tty)); + } + + if (tty->termios->c_cflag & CRTSCTS) { + spin_lock_irqsave(&info->lock,flags); + info->serial_signals |= SerialSignal_RTS; + set_signals(info); + spin_unlock_irqrestore(&info->lock,flags); + } +} + +/* get the current serial statistics + */ +static int get_stats(MGSLPC_INFO * info, struct mgsl_icount __user *user_icount) +{ + int err; + if (debug_level >= DEBUG_LEVEL_INFO) + printk("get_params(%s)\n", info->device_name); + if (!user_icount) { + memset(&info->icount, 0, sizeof(info->icount)); + } else { + COPY_TO_USER(err, user_icount, &info->icount, sizeof(struct mgsl_icount)); + if (err) + return -EFAULT; + } + return 0; +} + +/* get the current serial parameters + */ +static int get_params(MGSLPC_INFO * info, MGSL_PARAMS __user *user_params) +{ + int err; + if (debug_level >= DEBUG_LEVEL_INFO) + printk("get_params(%s)\n", info->device_name); + COPY_TO_USER(err,user_params, &info->params, sizeof(MGSL_PARAMS)); + if (err) + return -EFAULT; + return 0; +} + +/* set the serial parameters + * + * Arguments: + * + * info pointer to device instance data + * new_params user buffer containing new serial params + * + * Returns: 0 if success, otherwise error code + */ +static int set_params(MGSLPC_INFO * info, MGSL_PARAMS __user *new_params) +{ + unsigned long flags; + MGSL_PARAMS tmp_params; + int err; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):set_params %s\n", __FILE__,__LINE__, + info->device_name ); + COPY_FROM_USER(err,&tmp_params, new_params, sizeof(MGSL_PARAMS)); + if (err) { + if ( debug_level >= DEBUG_LEVEL_INFO ) + printk( "%s(%d):set_params(%s) user buffer copy failed\n", + __FILE__,__LINE__,info->device_name); + return -EFAULT; + } + + spin_lock_irqsave(&info->lock,flags); + memcpy(&info->params,&tmp_params,sizeof(MGSL_PARAMS)); + spin_unlock_irqrestore(&info->lock,flags); + + mgslpc_change_params(info); + + return 0; +} + +static int get_txidle(MGSLPC_INFO * info, int __user *idle_mode) +{ + int err; + if (debug_level >= DEBUG_LEVEL_INFO) + printk("get_txidle(%s)=%d\n", info->device_name, info->idle_mode); + COPY_TO_USER(err,idle_mode, &info->idle_mode, sizeof(int)); + if (err) + return -EFAULT; + return 0; +} + +static int set_txidle(MGSLPC_INFO * info, int idle_mode) +{ + unsigned long flags; + if (debug_level >= DEBUG_LEVEL_INFO) + printk("set_txidle(%s,%d)\n", info->device_name, idle_mode); + spin_lock_irqsave(&info->lock,flags); + info->idle_mode = idle_mode; + tx_set_idle(info); + spin_unlock_irqrestore(&info->lock,flags); + return 0; +} + +static int get_interface(MGSLPC_INFO * info, int __user *if_mode) +{ + int err; + if (debug_level >= DEBUG_LEVEL_INFO) + printk("get_interface(%s)=%d\n", info->device_name, info->if_mode); + COPY_TO_USER(err,if_mode, &info->if_mode, sizeof(int)); + if (err) + return -EFAULT; + return 0; +} + +static int set_interface(MGSLPC_INFO * info, int if_mode) +{ + unsigned long flags; + unsigned char val; + if (debug_level >= DEBUG_LEVEL_INFO) + printk("set_interface(%s,%d)\n", info->device_name, if_mode); + spin_lock_irqsave(&info->lock,flags); + info->if_mode = if_mode; + + val = read_reg(info, PVR) & 0x0f; + switch (info->if_mode) + { + case MGSL_INTERFACE_RS232: val |= PVR_RS232; break; + case MGSL_INTERFACE_V35: val |= PVR_V35; break; + case MGSL_INTERFACE_RS422: val |= PVR_RS422; break; + } + write_reg(info, PVR, val); + + spin_unlock_irqrestore(&info->lock,flags); + return 0; +} + +static int set_txenable(MGSLPC_INFO * info, int enable) +{ + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("set_txenable(%s,%d)\n", info->device_name, enable); + + spin_lock_irqsave(&info->lock,flags); + if (enable) { + if (!info->tx_enabled) + tx_start(info); + } else { + if (info->tx_enabled) + tx_stop(info); + } + spin_unlock_irqrestore(&info->lock,flags); + return 0; +} + +static int tx_abort(MGSLPC_INFO * info) +{ + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("tx_abort(%s)\n", info->device_name); + + spin_lock_irqsave(&info->lock,flags); + if (info->tx_active && info->tx_count && + info->params.mode == MGSL_MODE_HDLC) { + /* clear data count so FIFO is not filled on next IRQ. + * This results in underrun and abort transmission. + */ + info->tx_count = info->tx_put = info->tx_get = 0; + info->tx_aborting = true; + } + spin_unlock_irqrestore(&info->lock,flags); + return 0; +} + +static int set_rxenable(MGSLPC_INFO * info, int enable) +{ + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("set_rxenable(%s,%d)\n", info->device_name, enable); + + spin_lock_irqsave(&info->lock,flags); + if (enable) { + if (!info->rx_enabled) + rx_start(info); + } else { + if (info->rx_enabled) + rx_stop(info); + } + spin_unlock_irqrestore(&info->lock,flags); + return 0; +} + +/* wait for specified event to occur + * + * Arguments: info pointer to device instance data + * mask pointer to bitmask of events to wait for + * Return Value: 0 if successful and bit mask updated with + * of events triggerred, + * otherwise error code + */ +static int wait_events(MGSLPC_INFO * info, int __user *mask_ptr) +{ + unsigned long flags; + int s; + int rc=0; + struct mgsl_icount cprev, cnow; + int events; + int mask; + struct _input_signal_events oldsigs, newsigs; + DECLARE_WAITQUEUE(wait, current); + + COPY_FROM_USER(rc,&mask, mask_ptr, sizeof(int)); + if (rc) + return -EFAULT; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("wait_events(%s,%d)\n", info->device_name, mask); + + spin_lock_irqsave(&info->lock,flags); + + /* return immediately if state matches requested events */ + get_signals(info); + s = info->serial_signals; + events = mask & + ( ((s & SerialSignal_DSR) ? MgslEvent_DsrActive:MgslEvent_DsrInactive) + + ((s & SerialSignal_DCD) ? MgslEvent_DcdActive:MgslEvent_DcdInactive) + + ((s & SerialSignal_CTS) ? MgslEvent_CtsActive:MgslEvent_CtsInactive) + + ((s & SerialSignal_RI) ? MgslEvent_RiActive :MgslEvent_RiInactive) ); + if (events) { + spin_unlock_irqrestore(&info->lock,flags); + goto exit; + } + + /* save current irq counts */ + cprev = info->icount; + oldsigs = info->input_signal_events; + + if ((info->params.mode == MGSL_MODE_HDLC) && + (mask & MgslEvent_ExitHuntMode)) + irq_enable(info, CHA, IRQ_EXITHUNT); + + set_current_state(TASK_INTERRUPTIBLE); + add_wait_queue(&info->event_wait_q, &wait); + + spin_unlock_irqrestore(&info->lock,flags); + + + for(;;) { + schedule(); + if (signal_pending(current)) { + rc = -ERESTARTSYS; + break; + } + + /* get current irq counts */ + spin_lock_irqsave(&info->lock,flags); + cnow = info->icount; + newsigs = info->input_signal_events; + set_current_state(TASK_INTERRUPTIBLE); + spin_unlock_irqrestore(&info->lock,flags); + + /* if no change, wait aborted for some reason */ + if (newsigs.dsr_up == oldsigs.dsr_up && + newsigs.dsr_down == oldsigs.dsr_down && + newsigs.dcd_up == oldsigs.dcd_up && + newsigs.dcd_down == oldsigs.dcd_down && + newsigs.cts_up == oldsigs.cts_up && + newsigs.cts_down == oldsigs.cts_down && + newsigs.ri_up == oldsigs.ri_up && + newsigs.ri_down == oldsigs.ri_down && + cnow.exithunt == cprev.exithunt && + cnow.rxidle == cprev.rxidle) { + rc = -EIO; + break; + } + + events = mask & + ( (newsigs.dsr_up != oldsigs.dsr_up ? MgslEvent_DsrActive:0) + + (newsigs.dsr_down != oldsigs.dsr_down ? MgslEvent_DsrInactive:0) + + (newsigs.dcd_up != oldsigs.dcd_up ? MgslEvent_DcdActive:0) + + (newsigs.dcd_down != oldsigs.dcd_down ? MgslEvent_DcdInactive:0) + + (newsigs.cts_up != oldsigs.cts_up ? MgslEvent_CtsActive:0) + + (newsigs.cts_down != oldsigs.cts_down ? MgslEvent_CtsInactive:0) + + (newsigs.ri_up != oldsigs.ri_up ? MgslEvent_RiActive:0) + + (newsigs.ri_down != oldsigs.ri_down ? MgslEvent_RiInactive:0) + + (cnow.exithunt != cprev.exithunt ? MgslEvent_ExitHuntMode:0) + + (cnow.rxidle != cprev.rxidle ? MgslEvent_IdleReceived:0) ); + if (events) + break; + + cprev = cnow; + oldsigs = newsigs; + } + + remove_wait_queue(&info->event_wait_q, &wait); + set_current_state(TASK_RUNNING); + + if (mask & MgslEvent_ExitHuntMode) { + spin_lock_irqsave(&info->lock,flags); + if (!waitqueue_active(&info->event_wait_q)) + irq_disable(info, CHA, IRQ_EXITHUNT); + spin_unlock_irqrestore(&info->lock,flags); + } +exit: + if (rc == 0) + PUT_USER(rc, events, mask_ptr); + return rc; +} + +static int modem_input_wait(MGSLPC_INFO *info,int arg) +{ + unsigned long flags; + int rc; + struct mgsl_icount cprev, cnow; + DECLARE_WAITQUEUE(wait, current); + + /* save current irq counts */ + spin_lock_irqsave(&info->lock,flags); + cprev = info->icount; + add_wait_queue(&info->status_event_wait_q, &wait); + set_current_state(TASK_INTERRUPTIBLE); + spin_unlock_irqrestore(&info->lock,flags); + + for(;;) { + schedule(); + if (signal_pending(current)) { + rc = -ERESTARTSYS; + break; + } + + /* get new irq counts */ + spin_lock_irqsave(&info->lock,flags); + cnow = info->icount; + set_current_state(TASK_INTERRUPTIBLE); + spin_unlock_irqrestore(&info->lock,flags); + + /* if no change, wait aborted for some reason */ + if (cnow.rng == cprev.rng && cnow.dsr == cprev.dsr && + cnow.dcd == cprev.dcd && cnow.cts == cprev.cts) { + rc = -EIO; + break; + } + + /* check for change in caller specified modem input */ + if ((arg & TIOCM_RNG && cnow.rng != cprev.rng) || + (arg & TIOCM_DSR && cnow.dsr != cprev.dsr) || + (arg & TIOCM_CD && cnow.dcd != cprev.dcd) || + (arg & TIOCM_CTS && cnow.cts != cprev.cts)) { + rc = 0; + break; + } + + cprev = cnow; + } + remove_wait_queue(&info->status_event_wait_q, &wait); + set_current_state(TASK_RUNNING); + return rc; +} + +/* return the state of the serial control and status signals + */ +static int tiocmget(struct tty_struct *tty, struct file *file) +{ + MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data; + unsigned int result; + unsigned long flags; + + spin_lock_irqsave(&info->lock,flags); + get_signals(info); + spin_unlock_irqrestore(&info->lock,flags); + + result = ((info->serial_signals & SerialSignal_RTS) ? TIOCM_RTS:0) + + ((info->serial_signals & SerialSignal_DTR) ? TIOCM_DTR:0) + + ((info->serial_signals & SerialSignal_DCD) ? TIOCM_CAR:0) + + ((info->serial_signals & SerialSignal_RI) ? TIOCM_RNG:0) + + ((info->serial_signals & SerialSignal_DSR) ? TIOCM_DSR:0) + + ((info->serial_signals & SerialSignal_CTS) ? TIOCM_CTS:0); + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):%s tiocmget() value=%08X\n", + __FILE__,__LINE__, info->device_name, result ); + return result; +} + +/* set modem control signals (DTR/RTS) + */ +static int tiocmset(struct tty_struct *tty, struct file *file, + unsigned int set, unsigned int clear) +{ + MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data; + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):%s tiocmset(%x,%x)\n", + __FILE__,__LINE__,info->device_name, set, clear); + + if (set & TIOCM_RTS) + info->serial_signals |= SerialSignal_RTS; + if (set & TIOCM_DTR) + info->serial_signals |= SerialSignal_DTR; + if (clear & TIOCM_RTS) + info->serial_signals &= ~SerialSignal_RTS; + if (clear & TIOCM_DTR) + info->serial_signals &= ~SerialSignal_DTR; + + spin_lock_irqsave(&info->lock,flags); + set_signals(info); + spin_unlock_irqrestore(&info->lock,flags); + + return 0; +} + +/* Set or clear transmit break condition + * + * Arguments: tty pointer to tty instance data + * break_state -1=set break condition, 0=clear + */ +static int mgslpc_break(struct tty_struct *tty, int break_state) +{ + MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data; + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_break(%s,%d)\n", + __FILE__,__LINE__, info->device_name, break_state); + + if (mgslpc_paranoia_check(info, tty->name, "mgslpc_break")) + return -EINVAL; + + spin_lock_irqsave(&info->lock,flags); + if (break_state == -1) + set_reg_bits(info, CHA+DAFO, BIT6); + else + clear_reg_bits(info, CHA+DAFO, BIT6); + spin_unlock_irqrestore(&info->lock,flags); + return 0; +} + +/* Service an IOCTL request + * + * Arguments: + * + * tty pointer to tty instance data + * file pointer to associated file object for device + * cmd IOCTL command code + * arg command argument/context + * + * Return Value: 0 if success, otherwise error code + */ +static int mgslpc_ioctl(struct tty_struct *tty, struct file * file, + unsigned int cmd, unsigned long arg) +{ + MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_ioctl %s cmd=%08X\n", __FILE__,__LINE__, + info->device_name, cmd ); + + if (mgslpc_paranoia_check(info, tty->name, "mgslpc_ioctl")) + return -ENODEV; + + if ((cmd != TIOCGSERIAL) && (cmd != TIOCSSERIAL) && + (cmd != TIOCMIWAIT) && (cmd != TIOCGICOUNT)) { + if (tty->flags & (1 << TTY_IO_ERROR)) + return -EIO; + } + + return ioctl_common(info, cmd, arg); +} + +static int ioctl_common(MGSLPC_INFO *info, unsigned int cmd, unsigned long arg) +{ + int error; + struct mgsl_icount cnow; /* kernel counter temps */ + struct serial_icounter_struct __user *p_cuser; /* user space */ + void __user *argp = (void __user *)arg; + unsigned long flags; + + switch (cmd) { + case MGSL_IOCGPARAMS: + return get_params(info, argp); + case MGSL_IOCSPARAMS: + return set_params(info, argp); + case MGSL_IOCGTXIDLE: + return get_txidle(info, argp); + case MGSL_IOCSTXIDLE: + return set_txidle(info, (int)arg); + case MGSL_IOCGIF: + return get_interface(info, argp); + case MGSL_IOCSIF: + return set_interface(info,(int)arg); + case MGSL_IOCTXENABLE: + return set_txenable(info,(int)arg); + case MGSL_IOCRXENABLE: + return set_rxenable(info,(int)arg); + case MGSL_IOCTXABORT: + return tx_abort(info); + case MGSL_IOCGSTATS: + return get_stats(info, argp); + case MGSL_IOCWAITEVENT: + return wait_events(info, argp); + case TIOCMIWAIT: + return modem_input_wait(info,(int)arg); + case TIOCGICOUNT: + spin_lock_irqsave(&info->lock,flags); + cnow = info->icount; + spin_unlock_irqrestore(&info->lock,flags); + p_cuser = argp; + PUT_USER(error,cnow.cts, &p_cuser->cts); + if (error) return error; + PUT_USER(error,cnow.dsr, &p_cuser->dsr); + if (error) return error; + PUT_USER(error,cnow.rng, &p_cuser->rng); + if (error) return error; + PUT_USER(error,cnow.dcd, &p_cuser->dcd); + if (error) return error; + PUT_USER(error,cnow.rx, &p_cuser->rx); + if (error) return error; + PUT_USER(error,cnow.tx, &p_cuser->tx); + if (error) return error; + PUT_USER(error,cnow.frame, &p_cuser->frame); + if (error) return error; + PUT_USER(error,cnow.overrun, &p_cuser->overrun); + if (error) return error; + PUT_USER(error,cnow.parity, &p_cuser->parity); + if (error) return error; + PUT_USER(error,cnow.brk, &p_cuser->brk); + if (error) return error; + PUT_USER(error,cnow.buf_overrun, &p_cuser->buf_overrun); + if (error) return error; + return 0; + default: + return -ENOIOCTLCMD; + } + return 0; +} + +/* Set new termios settings + * + * Arguments: + * + * tty pointer to tty structure + * termios pointer to buffer to hold returned old termios + */ +static void mgslpc_set_termios(struct tty_struct *tty, struct ktermios *old_termios) +{ + MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data; + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_set_termios %s\n", __FILE__,__LINE__, + tty->driver->name ); + + /* just return if nothing has changed */ + if ((tty->termios->c_cflag == old_termios->c_cflag) + && (RELEVANT_IFLAG(tty->termios->c_iflag) + == RELEVANT_IFLAG(old_termios->c_iflag))) + return; + + mgslpc_change_params(info); + + /* Handle transition to B0 status */ + if (old_termios->c_cflag & CBAUD && + !(tty->termios->c_cflag & CBAUD)) { + info->serial_signals &= ~(SerialSignal_RTS + SerialSignal_DTR); + spin_lock_irqsave(&info->lock,flags); + set_signals(info); + spin_unlock_irqrestore(&info->lock,flags); + } + + /* Handle transition away from B0 status */ + if (!(old_termios->c_cflag & CBAUD) && + tty->termios->c_cflag & CBAUD) { + info->serial_signals |= SerialSignal_DTR; + if (!(tty->termios->c_cflag & CRTSCTS) || + !test_bit(TTY_THROTTLED, &tty->flags)) { + info->serial_signals |= SerialSignal_RTS; + } + spin_lock_irqsave(&info->lock,flags); + set_signals(info); + spin_unlock_irqrestore(&info->lock,flags); + } + + /* Handle turning off CRTSCTS */ + if (old_termios->c_cflag & CRTSCTS && + !(tty->termios->c_cflag & CRTSCTS)) { + tty->hw_stopped = 0; + tx_release(tty); + } +} + +static void mgslpc_close(struct tty_struct *tty, struct file * filp) +{ + MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data; + + if (mgslpc_paranoia_check(info, tty->name, "mgslpc_close")) + return; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_close(%s) entry, count=%d\n", + __FILE__,__LINE__, info->device_name, info->count); + + if (!info->count) + return; + + if (tty_hung_up_p(filp)) + goto cleanup; + + if ((tty->count == 1) && (info->count != 1)) { + /* + * tty->count is 1 and the tty structure will be freed. + * info->count should be one in this case. + * if it's not, correct it so that the port is shutdown. + */ + printk("mgslpc_close: bad refcount; tty->count is 1, " + "info->count is %d\n", info->count); + info->count = 1; + } + + info->count--; + + /* if at least one open remaining, leave hardware active */ + if (info->count) + goto cleanup; + + info->flags |= ASYNC_CLOSING; + + /* set tty->closing to notify line discipline to + * only process XON/XOFF characters. Only the N_TTY + * discipline appears to use this (ppp does not). + */ + tty->closing = 1; + + /* wait for transmit data to clear all layers */ + + if (info->closing_wait != ASYNC_CLOSING_WAIT_NONE) { + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_close(%s) calling tty_wait_until_sent\n", + __FILE__,__LINE__, info->device_name ); + tty_wait_until_sent(tty, info->closing_wait); + } + + if (info->flags & ASYNC_INITIALIZED) + mgslpc_wait_until_sent(tty, info->timeout); + + mgslpc_flush_buffer(tty); + + tty_ldisc_flush(tty); + + shutdown(info); + + tty->closing = 0; + info->tty = NULL; + + if (info->blocked_open) { + if (info->close_delay) { + msleep_interruptible(jiffies_to_msecs(info->close_delay)); + } + wake_up_interruptible(&info->open_wait); + } + + info->flags &= ~(ASYNC_NORMAL_ACTIVE|ASYNC_CLOSING); + + wake_up_interruptible(&info->close_wait); + +cleanup: + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_close(%s) exit, count=%d\n", __FILE__,__LINE__, + tty->driver->name, info->count); +} + +/* Wait until the transmitter is empty. + */ +static void mgslpc_wait_until_sent(struct tty_struct *tty, int timeout) +{ + MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data; + unsigned long orig_jiffies, char_time; + + if (!info ) + return; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_wait_until_sent(%s) entry\n", + __FILE__,__LINE__, info->device_name ); + + if (mgslpc_paranoia_check(info, tty->name, "mgslpc_wait_until_sent")) + return; + + if (!(info->flags & ASYNC_INITIALIZED)) + goto exit; + + orig_jiffies = jiffies; + + /* Set check interval to 1/5 of estimated time to + * send a character, and make it at least 1. The check + * interval should also be less than the timeout. + * Note: use tight timings here to satisfy the NIST-PCTS. + */ + + if ( info->params.data_rate ) { + char_time = info->timeout/(32 * 5); + if (!char_time) + char_time++; + } else + char_time = 1; + + if (timeout) + char_time = min_t(unsigned long, char_time, timeout); + + if (info->params.mode == MGSL_MODE_HDLC) { + while (info->tx_active) { + msleep_interruptible(jiffies_to_msecs(char_time)); + if (signal_pending(current)) + break; + if (timeout && time_after(jiffies, orig_jiffies + timeout)) + break; + } + } else { + while ((info->tx_count || info->tx_active) && + info->tx_enabled) { + msleep_interruptible(jiffies_to_msecs(char_time)); + if (signal_pending(current)) + break; + if (timeout && time_after(jiffies, orig_jiffies + timeout)) + break; + } + } + +exit: + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_wait_until_sent(%s) exit\n", + __FILE__,__LINE__, info->device_name ); +} + +/* Called by tty_hangup() when a hangup is signaled. + * This is the same as closing all open files for the port. + */ +static void mgslpc_hangup(struct tty_struct *tty) +{ + MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_hangup(%s)\n", + __FILE__,__LINE__, info->device_name ); + + if (mgslpc_paranoia_check(info, tty->name, "mgslpc_hangup")) + return; + + mgslpc_flush_buffer(tty); + shutdown(info); + + info->count = 0; + info->flags &= ~ASYNC_NORMAL_ACTIVE; + info->tty = NULL; + + wake_up_interruptible(&info->open_wait); +} + +/* Block the current process until the specified port + * is ready to be opened. + */ +static int block_til_ready(struct tty_struct *tty, struct file *filp, + MGSLPC_INFO *info) +{ + DECLARE_WAITQUEUE(wait, current); + int retval; + bool do_clocal = false; + bool extra_count = false; + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):block_til_ready on %s\n", + __FILE__,__LINE__, tty->driver->name ); + + if (filp->f_flags & O_NONBLOCK || tty->flags & (1 << TTY_IO_ERROR)){ + /* nonblock mode is set or port is not enabled */ + /* just verify that callout device is not active */ + info->flags |= ASYNC_NORMAL_ACTIVE; + return 0; + } + + if (tty->termios->c_cflag & CLOCAL) + do_clocal = true; + + /* Wait for carrier detect and the line to become + * free (i.e., not in use by the callout). While we are in + * this loop, info->count is dropped by one, so that + * mgslpc_close() knows when to free things. We restore it upon + * exit, either normal or abnormal. + */ + + retval = 0; + add_wait_queue(&info->open_wait, &wait); + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):block_til_ready before block on %s count=%d\n", + __FILE__,__LINE__, tty->driver->name, info->count ); + + spin_lock_irqsave(&info->lock, flags); + if (!tty_hung_up_p(filp)) { + extra_count = true; + info->count--; + } + spin_unlock_irqrestore(&info->lock, flags); + info->blocked_open++; + + while (1) { + if ((tty->termios->c_cflag & CBAUD)) { + spin_lock_irqsave(&info->lock,flags); + info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR; + set_signals(info); + spin_unlock_irqrestore(&info->lock,flags); + } + + set_current_state(TASK_INTERRUPTIBLE); + + if (tty_hung_up_p(filp) || !(info->flags & ASYNC_INITIALIZED)){ + retval = (info->flags & ASYNC_HUP_NOTIFY) ? + -EAGAIN : -ERESTARTSYS; + break; + } + + spin_lock_irqsave(&info->lock,flags); + get_signals(info); + spin_unlock_irqrestore(&info->lock,flags); + + if (!(info->flags & ASYNC_CLOSING) && + (do_clocal || (info->serial_signals & SerialSignal_DCD)) ) { + break; + } + + if (signal_pending(current)) { + retval = -ERESTARTSYS; + break; + } + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):block_til_ready blocking on %s count=%d\n", + __FILE__,__LINE__, tty->driver->name, info->count ); + + schedule(); + } + + set_current_state(TASK_RUNNING); + remove_wait_queue(&info->open_wait, &wait); + + if (extra_count) + info->count++; + info->blocked_open--; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):block_til_ready after blocking on %s count=%d\n", + __FILE__,__LINE__, tty->driver->name, info->count ); + + if (!retval) + info->flags |= ASYNC_NORMAL_ACTIVE; + + return retval; +} + +static int mgslpc_open(struct tty_struct *tty, struct file * filp) +{ + MGSLPC_INFO *info; + int retval, line; + unsigned long flags; + + /* verify range of specified line number */ + line = tty->index; + if ((line < 0) || (line >= mgslpc_device_count)) { + printk("%s(%d):mgslpc_open with invalid line #%d.\n", + __FILE__,__LINE__,line); + return -ENODEV; + } + + /* find the info structure for the specified line */ + info = mgslpc_device_list; + while(info && info->line != line) + info = info->next_device; + if (mgslpc_paranoia_check(info, tty->name, "mgslpc_open")) + return -ENODEV; + + tty->driver_data = info; + info->tty = tty; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_open(%s), old ref count = %d\n", + __FILE__,__LINE__,tty->driver->name, info->count); + + /* If port is closing, signal caller to try again */ + if (tty_hung_up_p(filp) || info->flags & ASYNC_CLOSING){ + if (info->flags & ASYNC_CLOSING) + interruptible_sleep_on(&info->close_wait); + retval = ((info->flags & ASYNC_HUP_NOTIFY) ? + -EAGAIN : -ERESTARTSYS); + goto cleanup; + } + + info->tty->low_latency = (info->flags & ASYNC_LOW_LATENCY) ? 1 : 0; + + spin_lock_irqsave(&info->netlock, flags); + if (info->netcount) { + retval = -EBUSY; + spin_unlock_irqrestore(&info->netlock, flags); + goto cleanup; + } + info->count++; + spin_unlock_irqrestore(&info->netlock, flags); + + if (info->count == 1) { + /* 1st open on this device, init hardware */ + retval = startup(info); + if (retval < 0) + goto cleanup; + } + + retval = block_til_ready(tty, filp, info); + if (retval) { + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):block_til_ready(%s) returned %d\n", + __FILE__,__LINE__, info->device_name, retval); + goto cleanup; + } + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):mgslpc_open(%s) success\n", + __FILE__,__LINE__, info->device_name); + retval = 0; + +cleanup: + if (retval) { + if (tty->count == 1) + info->tty = NULL; /* tty layer will release tty struct */ + if(info->count) + info->count--; + } + + return retval; +} + +/* + * /proc fs routines.... + */ + +static inline int line_info(char *buf, MGSLPC_INFO *info) +{ + char stat_buf[30]; + int ret; + unsigned long flags; + + ret = sprintf(buf, "%s:io:%04X irq:%d", + info->device_name, info->io_base, info->irq_level); + + /* output current serial signal states */ + spin_lock_irqsave(&info->lock,flags); + get_signals(info); + spin_unlock_irqrestore(&info->lock,flags); + + stat_buf[0] = 0; + stat_buf[1] = 0; + if (info->serial_signals & SerialSignal_RTS) + strcat(stat_buf, "|RTS"); + if (info->serial_signals & SerialSignal_CTS) + strcat(stat_buf, "|CTS"); + if (info->serial_signals & SerialSignal_DTR) + strcat(stat_buf, "|DTR"); + if (info->serial_signals & SerialSignal_DSR) + strcat(stat_buf, "|DSR"); + if (info->serial_signals & SerialSignal_DCD) + strcat(stat_buf, "|CD"); + if (info->serial_signals & SerialSignal_RI) + strcat(stat_buf, "|RI"); + + if (info->params.mode == MGSL_MODE_HDLC) { + ret += sprintf(buf+ret, " HDLC txok:%d rxok:%d", + info->icount.txok, info->icount.rxok); + if (info->icount.txunder) + ret += sprintf(buf+ret, " txunder:%d", info->icount.txunder); + if (info->icount.txabort) + ret += sprintf(buf+ret, " txabort:%d", info->icount.txabort); + if (info->icount.rxshort) + ret += sprintf(buf+ret, " rxshort:%d", info->icount.rxshort); + if (info->icount.rxlong) + ret += sprintf(buf+ret, " rxlong:%d", info->icount.rxlong); + if (info->icount.rxover) + ret += sprintf(buf+ret, " rxover:%d", info->icount.rxover); + if (info->icount.rxcrc) + ret += sprintf(buf+ret, " rxcrc:%d", info->icount.rxcrc); + } else { + ret += sprintf(buf+ret, " ASYNC tx:%d rx:%d", + info->icount.tx, info->icount.rx); + if (info->icount.frame) + ret += sprintf(buf+ret, " fe:%d", info->icount.frame); + if (info->icount.parity) + ret += sprintf(buf+ret, " pe:%d", info->icount.parity); + if (info->icount.brk) + ret += sprintf(buf+ret, " brk:%d", info->icount.brk); + if (info->icount.overrun) + ret += sprintf(buf+ret, " oe:%d", info->icount.overrun); + } + + /* Append serial signal status to end */ + ret += sprintf(buf+ret, " %s\n", stat_buf+1); + + ret += sprintf(buf+ret, "txactive=%d bh_req=%d bh_run=%d pending_bh=%x\n", + info->tx_active,info->bh_requested,info->bh_running, + info->pending_bh); + + return ret; +} + +/* Called to print information about devices + */ +static int mgslpc_read_proc(char *page, char **start, off_t off, int count, + int *eof, void *data) +{ + int len = 0, l; + off_t begin = 0; + MGSLPC_INFO *info; + + len += sprintf(page, "synclink driver:%s\n", driver_version); + + info = mgslpc_device_list; + while( info ) { + l = line_info(page + len, info); + len += l; + if (len+begin > off+count) + goto done; + if (len+begin < off) { + begin += len; + len = 0; + } + info = info->next_device; + } + + *eof = 1; +done: + if (off >= len+begin) + return 0; + *start = page + (off-begin); + return ((count < begin+len-off) ? count : begin+len-off); +} + +static int rx_alloc_buffers(MGSLPC_INFO *info) +{ + /* each buffer has header and data */ + info->rx_buf_size = sizeof(RXBUF) + info->max_frame_size; + + /* calculate total allocation size for 8 buffers */ + info->rx_buf_total_size = info->rx_buf_size * 8; + + /* limit total allocated memory */ + if (info->rx_buf_total_size > 0x10000) + info->rx_buf_total_size = 0x10000; + + /* calculate number of buffers */ + info->rx_buf_count = info->rx_buf_total_size / info->rx_buf_size; + + info->rx_buf = kmalloc(info->rx_buf_total_size, GFP_KERNEL); + if (info->rx_buf == NULL) + return -ENOMEM; + + rx_reset_buffers(info); + return 0; +} + +static void rx_free_buffers(MGSLPC_INFO *info) +{ + kfree(info->rx_buf); + info->rx_buf = NULL; +} + +static int claim_resources(MGSLPC_INFO *info) +{ + if (rx_alloc_buffers(info) < 0 ) { + printk( "Cant allocate rx buffer %s\n", info->device_name); + release_resources(info); + return -ENODEV; + } + return 0; +} + +static void release_resources(MGSLPC_INFO *info) +{ + if (debug_level >= DEBUG_LEVEL_INFO) + printk("release_resources(%s)\n", info->device_name); + rx_free_buffers(info); +} + +/* Add the specified device instance data structure to the + * global linked list of devices and increment the device count. + * + * Arguments: info pointer to device instance data + */ +static void mgslpc_add_device(MGSLPC_INFO *info) +{ + info->next_device = NULL; + info->line = mgslpc_device_count; + sprintf(info->device_name,"ttySLP%d",info->line); + + if (info->line < MAX_DEVICE_COUNT) { + if (maxframe[info->line]) + info->max_frame_size = maxframe[info->line]; + } + + mgslpc_device_count++; + + if (!mgslpc_device_list) + mgslpc_device_list = info; + else { + MGSLPC_INFO *current_dev = mgslpc_device_list; + while( current_dev->next_device ) + current_dev = current_dev->next_device; + current_dev->next_device = info; + } + + if (info->max_frame_size < 4096) + info->max_frame_size = 4096; + else if (info->max_frame_size > 65535) + info->max_frame_size = 65535; + + printk( "SyncLink PC Card %s:IO=%04X IRQ=%d\n", + info->device_name, info->io_base, info->irq_level); + +#if SYNCLINK_GENERIC_HDLC + hdlcdev_init(info); +#endif +} + +static void mgslpc_remove_device(MGSLPC_INFO *remove_info) +{ + MGSLPC_INFO *info = mgslpc_device_list; + MGSLPC_INFO *last = NULL; + + while(info) { + if (info == remove_info) { + if (last) + last->next_device = info->next_device; + else + mgslpc_device_list = info->next_device; +#if SYNCLINK_GENERIC_HDLC + hdlcdev_exit(info); +#endif + release_resources(info); + kfree(info); + mgslpc_device_count--; + return; + } + last = info; + info = info->next_device; + } +} + +static struct pcmcia_device_id mgslpc_ids[] = { + PCMCIA_DEVICE_MANF_CARD(0x02c5, 0x0050), + PCMCIA_DEVICE_NULL +}; +MODULE_DEVICE_TABLE(pcmcia, mgslpc_ids); + +static struct pcmcia_driver mgslpc_driver = { + .owner = THIS_MODULE, + .drv = { + .name = "synclink_cs", + }, + .probe = mgslpc_probe, + .remove = mgslpc_detach, + .id_table = mgslpc_ids, + .suspend = mgslpc_suspend, + .resume = mgslpc_resume, +}; + +static const struct tty_operations mgslpc_ops = { + .open = mgslpc_open, + .close = mgslpc_close, + .write = mgslpc_write, + .put_char = mgslpc_put_char, + .flush_chars = mgslpc_flush_chars, + .write_room = mgslpc_write_room, + .chars_in_buffer = mgslpc_chars_in_buffer, + .flush_buffer = mgslpc_flush_buffer, + .ioctl = mgslpc_ioctl, + .throttle = mgslpc_throttle, + .unthrottle = mgslpc_unthrottle, + .send_xchar = mgslpc_send_xchar, + .break_ctl = mgslpc_break, + .wait_until_sent = mgslpc_wait_until_sent, + .read_proc = mgslpc_read_proc, + .set_termios = mgslpc_set_termios, + .stop = tx_pause, + .start = tx_release, + .hangup = mgslpc_hangup, + .tiocmget = tiocmget, + .tiocmset = tiocmset, +}; + +static void synclink_cs_cleanup(void) +{ + int rc; + + printk("Unloading %s: version %s\n", driver_name, driver_version); + + while(mgslpc_device_list) + mgslpc_remove_device(mgslpc_device_list); + + if (serial_driver) { + if ((rc = tty_unregister_driver(serial_driver))) + printk("%s(%d) failed to unregister tty driver err=%d\n", + __FILE__,__LINE__,rc); + put_tty_driver(serial_driver); + } + + pcmcia_unregister_driver(&mgslpc_driver); +} + +static int __init synclink_cs_init(void) +{ + int rc; + + if (break_on_load) { + mgslpc_get_text_ptr(); + BREAKPOINT(); + } + + printk("%s %s\n", driver_name, driver_version); + + if ((rc = pcmcia_register_driver(&mgslpc_driver)) < 0) + return rc; + + serial_driver = alloc_tty_driver(MAX_DEVICE_COUNT); + if (!serial_driver) { + rc = -ENOMEM; + goto error; + } + + /* Initialize the tty_driver structure */ + + serial_driver->owner = THIS_MODULE; + serial_driver->driver_name = "synclink_cs"; + serial_driver->name = "ttySLP"; + serial_driver->major = ttymajor; + serial_driver->minor_start = 64; + serial_driver->type = TTY_DRIVER_TYPE_SERIAL; + serial_driver->subtype = SERIAL_TYPE_NORMAL; + serial_driver->init_termios = tty_std_termios; + serial_driver->init_termios.c_cflag = + B9600 | CS8 | CREAD | HUPCL | CLOCAL; + serial_driver->flags = TTY_DRIVER_REAL_RAW; + tty_set_operations(serial_driver, &mgslpc_ops); + + if ((rc = tty_register_driver(serial_driver)) < 0) { + printk("%s(%d):Couldn't register serial driver\n", + __FILE__,__LINE__); + put_tty_driver(serial_driver); + serial_driver = NULL; + goto error; + } + + printk("%s %s, tty major#%d\n", + driver_name, driver_version, + serial_driver->major); + + return 0; + +error: + synclink_cs_cleanup(); + return rc; +} + +static void __exit synclink_cs_exit(void) +{ + synclink_cs_cleanup(); +} + +module_init(synclink_cs_init); +module_exit(synclink_cs_exit); + +static void mgslpc_set_rate(MGSLPC_INFO *info, unsigned char channel, unsigned int rate) +{ + unsigned int M, N; + unsigned char val; + + /* note:standard BRG mode is broken in V3.2 chip + * so enhanced mode is always used + */ + + if (rate) { + N = 3686400 / rate; + if (!N) + N = 1; + N >>= 1; + for (M = 1; N > 64 && M < 16; M++) + N >>= 1; + N--; + + /* BGR[5..0] = N + * BGR[9..6] = M + * BGR[7..0] contained in BGR register + * BGR[9..8] contained in CCR2[7..6] + * divisor = (N+1)*2^M + * + * Note: M *must* not be zero (causes asymetric duty cycle) + */ + write_reg(info, (unsigned char) (channel + BGR), + (unsigned char) ((M << 6) + N)); + val = read_reg(info, (unsigned char) (channel + CCR2)) & 0x3f; + val |= ((M << 4) & 0xc0); + write_reg(info, (unsigned char) (channel + CCR2), val); + } +} + +/* Enabled the AUX clock output at the specified frequency. + */ +static void enable_auxclk(MGSLPC_INFO *info) +{ + unsigned char val; + + /* MODE + * + * 07..06 MDS[1..0] 10 = transparent HDLC mode + * 05 ADM Address Mode, 0 = no addr recognition + * 04 TMD Timer Mode, 0 = external + * 03 RAC Receiver Active, 0 = inactive + * 02 RTS 0=RTS active during xmit, 1=RTS always active + * 01 TRS Timer Resolution, 1=512 + * 00 TLP Test Loop, 0 = no loop + * + * 1000 0010 + */ + val = 0x82; + + /* channel B RTS is used to enable AUXCLK driver on SP505 */ + if (info->params.mode == MGSL_MODE_HDLC && info->params.clock_speed) + val |= BIT2; + write_reg(info, CHB + MODE, val); + + /* CCR0 + * + * 07 PU Power Up, 1=active, 0=power down + * 06 MCE Master Clock Enable, 1=enabled + * 05 Reserved, 0 + * 04..02 SC[2..0] Encoding + * 01..00 SM[1..0] Serial Mode, 00=HDLC + * + * 11000000 + */ + write_reg(info, CHB + CCR0, 0xc0); + + /* CCR1 + * + * 07 SFLG Shared Flag, 0 = disable shared flags + * 06 GALP Go Active On Loop, 0 = not used + * 05 GLP Go On Loop, 0 = not used + * 04 ODS Output Driver Select, 1=TxD is push-pull output + * 03 ITF Interframe Time Fill, 0=mark, 1=flag + * 02..00 CM[2..0] Clock Mode + * + * 0001 0111 + */ + write_reg(info, CHB + CCR1, 0x17); + + /* CCR2 (Channel B) + * + * 07..06 BGR[9..8] Baud rate bits 9..8 + * 05 BDF Baud rate divisor factor, 0=1, 1=BGR value + * 04 SSEL Clock source select, 1=submode b + * 03 TOE 0=TxCLK is input, 1=TxCLK is output + * 02 RWX Read/Write Exchange 0=disabled + * 01 C32, CRC select, 0=CRC-16, 1=CRC-32 + * 00 DIV, data inversion 0=disabled, 1=enabled + * + * 0011 1000 + */ + if (info->params.mode == MGSL_MODE_HDLC && info->params.clock_speed) + write_reg(info, CHB + CCR2, 0x38); + else + write_reg(info, CHB + CCR2, 0x30); + + /* CCR4 + * + * 07 MCK4 Master Clock Divide by 4, 1=enabled + * 06 EBRG Enhanced Baud Rate Generator Mode, 1=enabled + * 05 TST1 Test Pin, 0=normal operation + * 04 ICD Ivert Carrier Detect, 1=enabled (active low) + * 03..02 Reserved, must be 0 + * 01..00 RFT[1..0] RxFIFO Threshold 00=32 bytes + * + * 0101 0000 + */ + write_reg(info, CHB + CCR4, 0x50); + + /* if auxclk not enabled, set internal BRG so + * CTS transitions can be detected (requires TxC) + */ + if (info->params.mode == MGSL_MODE_HDLC && info->params.clock_speed) + mgslpc_set_rate(info, CHB, info->params.clock_speed); + else + mgslpc_set_rate(info, CHB, 921600); +} + +static void loopback_enable(MGSLPC_INFO *info) +{ + unsigned char val; + + /* CCR1:02..00 CM[2..0] Clock Mode = 111 (clock mode 7) */ + val = read_reg(info, CHA + CCR1) | (BIT2 + BIT1 + BIT0); + write_reg(info, CHA + CCR1, val); + + /* CCR2:04 SSEL Clock source select, 1=submode b */ + val = read_reg(info, CHA + CCR2) | (BIT4 + BIT5); + write_reg(info, CHA + CCR2, val); + + /* set LinkSpeed if available, otherwise default to 2Mbps */ + if (info->params.clock_speed) + mgslpc_set_rate(info, CHA, info->params.clock_speed); + else + mgslpc_set_rate(info, CHA, 1843200); + + /* MODE:00 TLP Test Loop, 1=loopback enabled */ + val = read_reg(info, CHA + MODE) | BIT0; + write_reg(info, CHA + MODE, val); +} + +static void hdlc_mode(MGSLPC_INFO *info) +{ + unsigned char val; + unsigned char clkmode, clksubmode; + + /* disable all interrupts */ + irq_disable(info, CHA, 0xffff); + irq_disable(info, CHB, 0xffff); + port_irq_disable(info, 0xff); + + /* assume clock mode 0a, rcv=RxC xmt=TxC */ + clkmode = clksubmode = 0; + if (info->params.flags & HDLC_FLAG_RXC_DPLL + && info->params.flags & HDLC_FLAG_TXC_DPLL) { + /* clock mode 7a, rcv = DPLL, xmt = DPLL */ + clkmode = 7; + } else if (info->params.flags & HDLC_FLAG_RXC_BRG + && info->params.flags & HDLC_FLAG_TXC_BRG) { + /* clock mode 7b, rcv = BRG, xmt = BRG */ + clkmode = 7; + clksubmode = 1; + } else if (info->params.flags & HDLC_FLAG_RXC_DPLL) { + if (info->params.flags & HDLC_FLAG_TXC_BRG) { + /* clock mode 6b, rcv = DPLL, xmt = BRG/16 */ + clkmode = 6; + clksubmode = 1; + } else { + /* clock mode 6a, rcv = DPLL, xmt = TxC */ + clkmode = 6; + } + } else if (info->params.flags & HDLC_FLAG_TXC_BRG) { + /* clock mode 0b, rcv = RxC, xmt = BRG */ + clksubmode = 1; + } + + /* MODE + * + * 07..06 MDS[1..0] 10 = transparent HDLC mode + * 05 ADM Address Mode, 0 = no addr recognition + * 04 TMD Timer Mode, 0 = external + * 03 RAC Receiver Active, 0 = inactive + * 02 RTS 0=RTS active during xmit, 1=RTS always active + * 01 TRS Timer Resolution, 1=512 + * 00 TLP Test Loop, 0 = no loop + * + * 1000 0010 + */ + val = 0x82; + if (info->params.loopback) + val |= BIT0; + + /* preserve RTS state */ + if (info->serial_signals & SerialSignal_RTS) + val |= BIT2; + write_reg(info, CHA + MODE, val); + + /* CCR0 + * + * 07 PU Power Up, 1=active, 0=power down + * 06 MCE Master Clock Enable, 1=enabled + * 05 Reserved, 0 + * 04..02 SC[2..0] Encoding + * 01..00 SM[1..0] Serial Mode, 00=HDLC + * + * 11000000 + */ + val = 0xc0; + switch (info->params.encoding) + { + case HDLC_ENCODING_NRZI: + val |= BIT3; + break; + case HDLC_ENCODING_BIPHASE_SPACE: + val |= BIT4; + break; // FM0 + case HDLC_ENCODING_BIPHASE_MARK: + val |= BIT4 + BIT2; + break; // FM1 + case HDLC_ENCODING_BIPHASE_LEVEL: + val |= BIT4 + BIT3; + break; // Manchester + } + write_reg(info, CHA + CCR0, val); + + /* CCR1 + * + * 07 SFLG Shared Flag, 0 = disable shared flags + * 06 GALP Go Active On Loop, 0 = not used + * 05 GLP Go On Loop, 0 = not used + * 04 ODS Output Driver Select, 1=TxD is push-pull output + * 03 ITF Interframe Time Fill, 0=mark, 1=flag + * 02..00 CM[2..0] Clock Mode + * + * 0001 0000 + */ + val = 0x10 + clkmode; + write_reg(info, CHA + CCR1, val); + + /* CCR2 + * + * 07..06 BGR[9..8] Baud rate bits 9..8 + * 05 BDF Baud rate divisor factor, 0=1, 1=BGR value + * 04 SSEL Clock source select, 1=submode b + * 03 TOE 0=TxCLK is input, 0=TxCLK is input + * 02 RWX Read/Write Exchange 0=disabled + * 01 C32, CRC select, 0=CRC-16, 1=CRC-32 + * 00 DIV, data inversion 0=disabled, 1=enabled + * + * 0000 0000 + */ + val = 0x00; + if (clkmode == 2 || clkmode == 3 || clkmode == 6 + || clkmode == 7 || (clkmode == 0 && clksubmode == 1)) + val |= BIT5; + if (clksubmode) + val |= BIT4; + if (info->params.crc_type == HDLC_CRC_32_CCITT) + val |= BIT1; + if (info->params.encoding == HDLC_ENCODING_NRZB) + val |= BIT0; + write_reg(info, CHA + CCR2, val); + + /* CCR3 + * + * 07..06 PRE[1..0] Preamble count 00=1, 01=2, 10=4, 11=8 + * 05 EPT Enable preamble transmission, 1=enabled + * 04 RADD Receive address pushed to FIFO, 0=disabled + * 03 CRL CRC Reset Level, 0=FFFF + * 02 RCRC Rx CRC 0=On 1=Off + * 01 TCRC Tx CRC 0=On 1=Off + * 00 PSD DPLL Phase Shift Disable + * + * 0000 0000 + */ + val = 0x00; + if (info->params.crc_type == HDLC_CRC_NONE) + val |= BIT2 + BIT1; + if (info->params.preamble != HDLC_PREAMBLE_PATTERN_NONE) + val |= BIT5; + switch (info->params.preamble_length) + { + case HDLC_PREAMBLE_LENGTH_16BITS: + val |= BIT6; + break; + case HDLC_PREAMBLE_LENGTH_32BITS: + val |= BIT6; + break; + case HDLC_PREAMBLE_LENGTH_64BITS: + val |= BIT7 + BIT6; + break; + } + write_reg(info, CHA + CCR3, val); + + /* PRE - Preamble pattern */ + val = 0; + switch (info->params.preamble) + { + case HDLC_PREAMBLE_PATTERN_FLAGS: val = 0x7e; break; + case HDLC_PREAMBLE_PATTERN_10: val = 0xaa; break; + case HDLC_PREAMBLE_PATTERN_01: val = 0x55; break; + case HDLC_PREAMBLE_PATTERN_ONES: val = 0xff; break; + } + write_reg(info, CHA + PRE, val); + + /* CCR4 + * + * 07 MCK4 Master Clock Divide by 4, 1=enabled + * 06 EBRG Enhanced Baud Rate Generator Mode, 1=enabled + * 05 TST1 Test Pin, 0=normal operation + * 04 ICD Ivert Carrier Detect, 1=enabled (active low) + * 03..02 Reserved, must be 0 + * 01..00 RFT[1..0] RxFIFO Threshold 00=32 bytes + * + * 0101 0000 + */ + val = 0x50; + write_reg(info, CHA + CCR4, val); + if (info->params.flags & HDLC_FLAG_RXC_DPLL) + mgslpc_set_rate(info, CHA, info->params.clock_speed * 16); + else + mgslpc_set_rate(info, CHA, info->params.clock_speed); + + /* RLCR Receive length check register + * + * 7 1=enable receive length check + * 6..0 Max frame length = (RL + 1) * 32 + */ + write_reg(info, CHA + RLCR, 0); + + /* XBCH Transmit Byte Count High + * + * 07 DMA mode, 0 = interrupt driven + * 06 NRM, 0=ABM (ignored) + * 05 CAS Carrier Auto Start + * 04 XC Transmit Continuously (ignored) + * 03..00 XBC[10..8] Transmit byte count bits 10..8 + * + * 0000 0000 + */ + val = 0x00; + if (info->params.flags & HDLC_FLAG_AUTO_DCD) + val |= BIT5; + write_reg(info, CHA + XBCH, val); + enable_auxclk(info); + if (info->params.loopback || info->testing_irq) + loopback_enable(info); + if (info->params.flags & HDLC_FLAG_AUTO_CTS) + { + irq_enable(info, CHB, IRQ_CTS); + /* PVR[3] 1=AUTO CTS active */ + set_reg_bits(info, CHA + PVR, BIT3); + } else + clear_reg_bits(info, CHA + PVR, BIT3); + + irq_enable(info, CHA, + IRQ_RXEOM + IRQ_RXFIFO + IRQ_ALLSENT + + IRQ_UNDERRUN + IRQ_TXFIFO); + issue_command(info, CHA, CMD_TXRESET + CMD_RXRESET); + wait_command_complete(info, CHA); + read_reg16(info, CHA + ISR); /* clear pending IRQs */ + + /* Master clock mode enabled above to allow reset commands + * to complete even if no data clocks are present. + * + * Disable master clock mode for normal communications because + * V3.2 of the ESCC2 has a bug that prevents the transmit all sent + * IRQ when in master clock mode. + * + * Leave master clock mode enabled for IRQ test because the + * timer IRQ used by the test can only happen in master clock mode. + */ + if (!info->testing_irq) + clear_reg_bits(info, CHA + CCR0, BIT6); + + tx_set_idle(info); + + tx_stop(info); + rx_stop(info); +} + +static void rx_stop(MGSLPC_INFO *info) +{ + if (debug_level >= DEBUG_LEVEL_ISR) + printk("%s(%d):rx_stop(%s)\n", + __FILE__,__LINE__, info->device_name ); + + /* MODE:03 RAC Receiver Active, 0=inactive */ + clear_reg_bits(info, CHA + MODE, BIT3); + + info->rx_enabled = false; + info->rx_overflow = false; +} + +static void rx_start(MGSLPC_INFO *info) +{ + if (debug_level >= DEBUG_LEVEL_ISR) + printk("%s(%d):rx_start(%s)\n", + __FILE__,__LINE__, info->device_name ); + + rx_reset_buffers(info); + info->rx_enabled = false; + info->rx_overflow = false; + + /* MODE:03 RAC Receiver Active, 1=active */ + set_reg_bits(info, CHA + MODE, BIT3); + + info->rx_enabled = true; +} + +static void tx_start(MGSLPC_INFO *info) +{ + if (debug_level >= DEBUG_LEVEL_ISR) + printk("%s(%d):tx_start(%s)\n", + __FILE__,__LINE__, info->device_name ); + + if (info->tx_count) { + /* If auto RTS enabled and RTS is inactive, then assert */ + /* RTS and set a flag indicating that the driver should */ + /* negate RTS when the transmission completes. */ + info->drop_rts_on_tx_done = false; + + if (info->params.flags & HDLC_FLAG_AUTO_RTS) { + get_signals(info); + if (!(info->serial_signals & SerialSignal_RTS)) { + info->serial_signals |= SerialSignal_RTS; + set_signals(info); + info->drop_rts_on_tx_done = true; + } + } + + if (info->params.mode == MGSL_MODE_ASYNC) { + if (!info->tx_active) { + info->tx_active = true; + tx_ready(info); + } + } else { + info->tx_active = true; + tx_ready(info); + mod_timer(&info->tx_timer, jiffies + + msecs_to_jiffies(5000)); + } + } + + if (!info->tx_enabled) + info->tx_enabled = true; +} + +static void tx_stop(MGSLPC_INFO *info) +{ + if (debug_level >= DEBUG_LEVEL_ISR) + printk("%s(%d):tx_stop(%s)\n", + __FILE__,__LINE__, info->device_name ); + + del_timer(&info->tx_timer); + + info->tx_enabled = false; + info->tx_active = false; +} + +/* Reset the adapter to a known state and prepare it for further use. + */ +static void reset_device(MGSLPC_INFO *info) +{ + /* power up both channels (set BIT7) */ + write_reg(info, CHA + CCR0, 0x80); + write_reg(info, CHB + CCR0, 0x80); + write_reg(info, CHA + MODE, 0); + write_reg(info, CHB + MODE, 0); + + /* disable all interrupts */ + irq_disable(info, CHA, 0xffff); + irq_disable(info, CHB, 0xffff); + port_irq_disable(info, 0xff); + + /* PCR Port Configuration Register + * + * 07..04 DEC[3..0] Serial I/F select outputs + * 03 output, 1=AUTO CTS control enabled + * 02 RI Ring Indicator input 0=active + * 01 DSR input 0=active + * 00 DTR output 0=active + * + * 0000 0110 + */ + write_reg(info, PCR, 0x06); + + /* PVR Port Value Register + * + * 07..04 DEC[3..0] Serial I/F select (0000=disabled) + * 03 AUTO CTS output 1=enabled + * 02 RI Ring Indicator input + * 01 DSR input + * 00 DTR output (1=inactive) + * + * 0000 0001 + */ +// write_reg(info, PVR, PVR_DTR); + + /* IPC Interrupt Port Configuration + * + * 07 VIS 1=Masked interrupts visible + * 06..05 Reserved, 0 + * 04..03 SLA Slave address, 00 ignored + * 02 CASM Cascading Mode, 1=daisy chain + * 01..00 IC[1..0] Interrupt Config, 01=push-pull output, active low + * + * 0000 0101 + */ + write_reg(info, IPC, 0x05); +} + +static void async_mode(MGSLPC_INFO *info) +{ + unsigned char val; + + /* disable all interrupts */ + irq_disable(info, CHA, 0xffff); + irq_disable(info, CHB, 0xffff); + port_irq_disable(info, 0xff); + + /* MODE + * + * 07 Reserved, 0 + * 06 FRTS RTS State, 0=active + * 05 FCTS Flow Control on CTS + * 04 FLON Flow Control Enable + * 03 RAC Receiver Active, 0 = inactive + * 02 RTS 0=Auto RTS, 1=manual RTS + * 01 TRS Timer Resolution, 1=512 + * 00 TLP Test Loop, 0 = no loop + * + * 0000 0110 + */ + val = 0x06; + if (info->params.loopback) + val |= BIT0; + + /* preserve RTS state */ + if (!(info->serial_signals & SerialSignal_RTS)) + val |= BIT6; + write_reg(info, CHA + MODE, val); + + /* CCR0 + * + * 07 PU Power Up, 1=active, 0=power down + * 06 MCE Master Clock Enable, 1=enabled + * 05 Reserved, 0 + * 04..02 SC[2..0] Encoding, 000=NRZ + * 01..00 SM[1..0] Serial Mode, 11=Async + * + * 1000 0011 + */ + write_reg(info, CHA + CCR0, 0x83); + + /* CCR1 + * + * 07..05 Reserved, 0 + * 04 ODS Output Driver Select, 1=TxD is push-pull output + * 03 BCR Bit Clock Rate, 1=16x + * 02..00 CM[2..0] Clock Mode, 111=BRG + * + * 0001 1111 + */ + write_reg(info, CHA + CCR1, 0x1f); + + /* CCR2 (channel A) + * + * 07..06 BGR[9..8] Baud rate bits 9..8 + * 05 BDF Baud rate divisor factor, 0=1, 1=BGR value + * 04 SSEL Clock source select, 1=submode b + * 03 TOE 0=TxCLK is input, 0=TxCLK is input + * 02 RWX Read/Write Exchange 0=disabled + * 01 Reserved, 0 + * 00 DIV, data inversion 0=disabled, 1=enabled + * + * 0001 0000 + */ + write_reg(info, CHA + CCR2, 0x10); + + /* CCR3 + * + * 07..01 Reserved, 0 + * 00 PSD DPLL Phase Shift Disable + * + * 0000 0000 + */ + write_reg(info, CHA + CCR3, 0); + + /* CCR4 + * + * 07 MCK4 Master Clock Divide by 4, 1=enabled + * 06 EBRG Enhanced Baud Rate Generator Mode, 1=enabled + * 05 TST1 Test Pin, 0=normal operation + * 04 ICD Ivert Carrier Detect, 1=enabled (active low) + * 03..00 Reserved, must be 0 + * + * 0101 0000 + */ + write_reg(info, CHA + CCR4, 0x50); + mgslpc_set_rate(info, CHA, info->params.data_rate * 16); + + /* DAFO Data Format + * + * 07 Reserved, 0 + * 06 XBRK transmit break, 0=normal operation + * 05 Stop bits (0=1, 1=2) + * 04..03 PAR[1..0] Parity (01=odd, 10=even) + * 02 PAREN Parity Enable + * 01..00 CHL[1..0] Character Length (00=8, 01=7) + * + */ + val = 0x00; + if (info->params.data_bits != 8) + val |= BIT0; /* 7 bits */ + if (info->params.stop_bits != 1) + val |= BIT5; + if (info->params.parity != ASYNC_PARITY_NONE) + { + val |= BIT2; /* Parity enable */ + if (info->params.parity == ASYNC_PARITY_ODD) + val |= BIT3; + else + val |= BIT4; + } + write_reg(info, CHA + DAFO, val); + + /* RFC Rx FIFO Control + * + * 07 Reserved, 0 + * 06 DPS, 1=parity bit not stored in data byte + * 05 DXS, 0=all data stored in FIFO (including XON/XOFF) + * 04 RFDF Rx FIFO Data Format, 1=status byte stored in FIFO + * 03..02 RFTH[1..0], rx threshold, 11=16 status + 16 data byte + * 01 Reserved, 0 + * 00 TCDE Terminate Char Detect Enable, 0=disabled + * + * 0101 1100 + */ + write_reg(info, CHA + RFC, 0x5c); + + /* RLCR Receive length check register + * + * Max frame length = (RL + 1) * 32 + */ + write_reg(info, CHA + RLCR, 0); + + /* XBCH Transmit Byte Count High + * + * 07 DMA mode, 0 = interrupt driven + * 06 NRM, 0=ABM (ignored) + * 05 CAS Carrier Auto Start + * 04 XC Transmit Continuously (ignored) + * 03..00 XBC[10..8] Transmit byte count bits 10..8 + * + * 0000 0000 + */ + val = 0x00; + if (info->params.flags & HDLC_FLAG_AUTO_DCD) + val |= BIT5; + write_reg(info, CHA + XBCH, val); + if (info->params.flags & HDLC_FLAG_AUTO_CTS) + irq_enable(info, CHA, IRQ_CTS); + + /* MODE:03 RAC Receiver Active, 1=active */ + set_reg_bits(info, CHA + MODE, BIT3); + enable_auxclk(info); + if (info->params.flags & HDLC_FLAG_AUTO_CTS) { + irq_enable(info, CHB, IRQ_CTS); + /* PVR[3] 1=AUTO CTS active */ + set_reg_bits(info, CHA + PVR, BIT3); + } else + clear_reg_bits(info, CHA + PVR, BIT3); + irq_enable(info, CHA, + IRQ_RXEOM + IRQ_RXFIFO + IRQ_BREAK_ON + IRQ_RXTIME + + IRQ_ALLSENT + IRQ_TXFIFO); + issue_command(info, CHA, CMD_TXRESET + CMD_RXRESET); + wait_command_complete(info, CHA); + read_reg16(info, CHA + ISR); /* clear pending IRQs */ +} + +/* Set the HDLC idle mode for the transmitter. + */ +static void tx_set_idle(MGSLPC_INFO *info) +{ + /* Note: ESCC2 only supports flags and one idle modes */ + if (info->idle_mode == HDLC_TXIDLE_FLAGS) + set_reg_bits(info, CHA + CCR1, BIT3); + else + clear_reg_bits(info, CHA + CCR1, BIT3); +} + +/* get state of the V24 status (input) signals. + */ +static void get_signals(MGSLPC_INFO *info) +{ + unsigned char status = 0; + + /* preserve DTR and RTS */ + info->serial_signals &= SerialSignal_DTR + SerialSignal_RTS; + + if (read_reg(info, CHB + VSTR) & BIT7) + info->serial_signals |= SerialSignal_DCD; + if (read_reg(info, CHB + STAR) & BIT1) + info->serial_signals |= SerialSignal_CTS; + + status = read_reg(info, CHA + PVR); + if (!(status & PVR_RI)) + info->serial_signals |= SerialSignal_RI; + if (!(status & PVR_DSR)) + info->serial_signals |= SerialSignal_DSR; +} + +/* Set the state of DTR and RTS based on contents of + * serial_signals member of device extension. + */ +static void set_signals(MGSLPC_INFO *info) +{ + unsigned char val; + + val = read_reg(info, CHA + MODE); + if (info->params.mode == MGSL_MODE_ASYNC) { + if (info->serial_signals & SerialSignal_RTS) + val &= ~BIT6; + else + val |= BIT6; + } else { + if (info->serial_signals & SerialSignal_RTS) + val |= BIT2; + else + val &= ~BIT2; + } + write_reg(info, CHA + MODE, val); + + if (info->serial_signals & SerialSignal_DTR) + clear_reg_bits(info, CHA + PVR, PVR_DTR); + else + set_reg_bits(info, CHA + PVR, PVR_DTR); +} + +static void rx_reset_buffers(MGSLPC_INFO *info) +{ + RXBUF *buf; + int i; + + info->rx_put = 0; + info->rx_get = 0; + info->rx_frame_count = 0; + for (i=0 ; i < info->rx_buf_count ; i++) { + buf = (RXBUF*)(info->rx_buf + (i * info->rx_buf_size)); + buf->status = buf->count = 0; + } +} + +/* Attempt to return a received HDLC frame + * Only frames received without errors are returned. + * + * Returns true if frame returned, otherwise false + */ +static bool rx_get_frame(MGSLPC_INFO *info) +{ + unsigned short status; + RXBUF *buf; + unsigned int framesize = 0; + unsigned long flags; + struct tty_struct *tty = info->tty; + bool return_frame = false; + + if (info->rx_frame_count == 0) + return false; + + buf = (RXBUF*)(info->rx_buf + (info->rx_get * info->rx_buf_size)); + + status = buf->status; + + /* 07 VFR 1=valid frame + * 06 RDO 1=data overrun + * 05 CRC 1=OK, 0=error + * 04 RAB 1=frame aborted + */ + if ((status & 0xf0) != 0xA0) { + if (!(status & BIT7) || (status & BIT4)) + info->icount.rxabort++; + else if (status & BIT6) + info->icount.rxover++; + else if (!(status & BIT5)) { + info->icount.rxcrc++; + if (info->params.crc_type & HDLC_CRC_RETURN_EX) + return_frame = true; + } + framesize = 0; +#if SYNCLINK_GENERIC_HDLC + { + info->netdev->stats.rx_errors++; + info->netdev->stats.rx_frame_errors++; + } +#endif + } else + return_frame = true; + + if (return_frame) + framesize = buf->count; + + if (debug_level >= DEBUG_LEVEL_BH) + printk("%s(%d):rx_get_frame(%s) status=%04X size=%d\n", + __FILE__,__LINE__,info->device_name,status,framesize); + + if (debug_level >= DEBUG_LEVEL_DATA) + trace_block(info, buf->data, framesize, 0); + + if (framesize) { + if ((info->params.crc_type & HDLC_CRC_RETURN_EX && + framesize+1 > info->max_frame_size) || + framesize > info->max_frame_size) + info->icount.rxlong++; + else { + if (status & BIT5) + info->icount.rxok++; + + if (info->params.crc_type & HDLC_CRC_RETURN_EX) { + *(buf->data + framesize) = status & BIT5 ? RX_OK:RX_CRC_ERROR; + ++framesize; + } + +#if SYNCLINK_GENERIC_HDLC + if (info->netcount) + hdlcdev_rx(info, buf->data, framesize); + else +#endif + ldisc_receive_buf(tty, buf->data, info->flag_buf, framesize); + } + } + + spin_lock_irqsave(&info->lock,flags); + buf->status = buf->count = 0; + info->rx_frame_count--; + info->rx_get++; + if (info->rx_get >= info->rx_buf_count) + info->rx_get = 0; + spin_unlock_irqrestore(&info->lock,flags); + + return true; +} + +static bool register_test(MGSLPC_INFO *info) +{ + static unsigned char patterns[] = + { 0x00, 0xff, 0xaa, 0x55, 0x69, 0x96, 0x0f }; + static unsigned int count = ARRAY_SIZE(patterns); + unsigned int i; + bool rc = true; + unsigned long flags; + + spin_lock_irqsave(&info->lock,flags); + reset_device(info); + + for (i = 0; i < count; i++) { + write_reg(info, XAD1, patterns[i]); + write_reg(info, XAD2, patterns[(i + 1) % count]); + if ((read_reg(info, XAD1) != patterns[i]) || + (read_reg(info, XAD2) != patterns[(i + 1) % count])) { + rc = false; + break; + } + } + + spin_unlock_irqrestore(&info->lock,flags); + return rc; +} + +static bool irq_test(MGSLPC_INFO *info) +{ + unsigned long end_time; + unsigned long flags; + + spin_lock_irqsave(&info->lock,flags); + reset_device(info); + + info->testing_irq = true; + hdlc_mode(info); + + info->irq_occurred = false; + + /* init hdlc mode */ + + irq_enable(info, CHA, IRQ_TIMER); + write_reg(info, CHA + TIMR, 0); /* 512 cycles */ + issue_command(info, CHA, CMD_START_TIMER); + + spin_unlock_irqrestore(&info->lock,flags); + + end_time=100; + while(end_time-- && !info->irq_occurred) { + msleep_interruptible(10); + } + + info->testing_irq = false; + + spin_lock_irqsave(&info->lock,flags); + reset_device(info); + spin_unlock_irqrestore(&info->lock,flags); + + return info->irq_occurred; +} + +static int adapter_test(MGSLPC_INFO *info) +{ + if (!register_test(info)) { + info->init_error = DiagStatus_AddressFailure; + printk( "%s(%d):Register test failure for device %s Addr=%04X\n", + __FILE__,__LINE__,info->device_name, (unsigned short)(info->io_base) ); + return -ENODEV; + } + + if (!irq_test(info)) { + info->init_error = DiagStatus_IrqFailure; + printk( "%s(%d):Interrupt test failure for device %s IRQ=%d\n", + __FILE__,__LINE__,info->device_name, (unsigned short)(info->irq_level) ); + return -ENODEV; + } + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s(%d):device %s passed diagnostics\n", + __FILE__,__LINE__,info->device_name); + return 0; +} + +static void trace_block(MGSLPC_INFO *info,const char* data, int count, int xmit) +{ + int i; + int linecount; + if (xmit) + printk("%s tx data:\n",info->device_name); + else + printk("%s rx data:\n",info->device_name); + + while(count) { + if (count > 16) + linecount = 16; + else + linecount = count; + + for(i=0;i<linecount;i++) + printk("%02X ",(unsigned char)data[i]); + for(;i<17;i++) + printk(" "); + for(i=0;i<linecount;i++) { + if (data[i]>=040 && data[i]<=0176) + printk("%c",data[i]); + else + printk("."); + } + printk("\n"); + + data += linecount; + count -= linecount; + } +} + +/* HDLC frame time out + * update stats and do tx completion processing + */ +static void tx_timeout(unsigned long context) +{ + MGSLPC_INFO *info = (MGSLPC_INFO*)context; + unsigned long flags; + + if ( debug_level >= DEBUG_LEVEL_INFO ) + printk( "%s(%d):tx_timeout(%s)\n", + __FILE__,__LINE__,info->device_name); + if(info->tx_active && + info->params.mode == MGSL_MODE_HDLC) { + info->icount.txtimeout++; + } + spin_lock_irqsave(&info->lock,flags); + info->tx_active = false; + info->tx_count = info->tx_put = info->tx_get = 0; + + spin_unlock_irqrestore(&info->lock,flags); + +#if SYNCLINK_GENERIC_HDLC + if (info->netcount) + hdlcdev_tx_done(info); + else +#endif + bh_transmit(info); +} + +#if SYNCLINK_GENERIC_HDLC + +/** + * called by generic HDLC layer when protocol selected (PPP, frame relay, etc.) + * set encoding and frame check sequence (FCS) options + * + * dev pointer to network device structure + * encoding serial encoding setting + * parity FCS setting + * + * returns 0 if success, otherwise error code + */ +static int hdlcdev_attach(struct net_device *dev, unsigned short encoding, + unsigned short parity) +{ + MGSLPC_INFO *info = dev_to_port(dev); + unsigned char new_encoding; + unsigned short new_crctype; + + /* return error if TTY interface open */ + if (info->count) + return -EBUSY; + + switch (encoding) + { + case ENCODING_NRZ: new_encoding = HDLC_ENCODING_NRZ; break; + case ENCODING_NRZI: new_encoding = HDLC_ENCODING_NRZI_SPACE; break; + case ENCODING_FM_MARK: new_encoding = HDLC_ENCODING_BIPHASE_MARK; break; + case ENCODING_FM_SPACE: new_encoding = HDLC_ENCODING_BIPHASE_SPACE; break; + case ENCODING_MANCHESTER: new_encoding = HDLC_ENCODING_BIPHASE_LEVEL; break; + default: return -EINVAL; + } + + switch (parity) + { + case PARITY_NONE: new_crctype = HDLC_CRC_NONE; break; + case PARITY_CRC16_PR1_CCITT: new_crctype = HDLC_CRC_16_CCITT; break; + case PARITY_CRC32_PR1_CCITT: new_crctype = HDLC_CRC_32_CCITT; break; + default: return -EINVAL; + } + + info->params.encoding = new_encoding; + info->params.crc_type = new_crctype; + + /* if network interface up, reprogram hardware */ + if (info->netcount) + mgslpc_program_hw(info); + + return 0; +} + +/** + * called by generic HDLC layer to send frame + * + * skb socket buffer containing HDLC frame + * dev pointer to network device structure + * + * returns 0 if success, otherwise error code + */ +static int hdlcdev_xmit(struct sk_buff *skb, struct net_device *dev) +{ + MGSLPC_INFO *info = dev_to_port(dev); + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk(KERN_INFO "%s:hdlc_xmit(%s)\n",__FILE__,dev->name); + + /* stop sending until this frame completes */ + netif_stop_queue(dev); + + /* copy data to device buffers */ + skb_copy_from_linear_data(skb, info->tx_buf, skb->len); + info->tx_get = 0; + info->tx_put = info->tx_count = skb->len; + + /* update network statistics */ + dev->stats.tx_packets++; + dev->stats.tx_bytes += skb->len; + + /* done with socket buffer, so free it */ + dev_kfree_skb(skb); + + /* save start time for transmit timeout detection */ + dev->trans_start = jiffies; + + /* start hardware transmitter if necessary */ + spin_lock_irqsave(&info->lock,flags); + if (!info->tx_active) + tx_start(info); + spin_unlock_irqrestore(&info->lock,flags); + + return 0; +} + +/** + * called by network layer when interface enabled + * claim resources and initialize hardware + * + * dev pointer to network device structure + * + * returns 0 if success, otherwise error code + */ +static int hdlcdev_open(struct net_device *dev) +{ + MGSLPC_INFO *info = dev_to_port(dev); + int rc; + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s:hdlcdev_open(%s)\n",__FILE__,dev->name); + + /* generic HDLC layer open processing */ + if ((rc = hdlc_open(dev))) + return rc; + + /* arbitrate between network and tty opens */ + spin_lock_irqsave(&info->netlock, flags); + if (info->count != 0 || info->netcount != 0) { + printk(KERN_WARNING "%s: hdlc_open returning busy\n", dev->name); + spin_unlock_irqrestore(&info->netlock, flags); + return -EBUSY; + } + info->netcount=1; + spin_unlock_irqrestore(&info->netlock, flags); + + /* claim resources and init adapter */ + if ((rc = startup(info)) != 0) { + spin_lock_irqsave(&info->netlock, flags); + info->netcount=0; + spin_unlock_irqrestore(&info->netlock, flags); + return rc; + } + + /* assert DTR and RTS, apply hardware settings */ + info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR; + mgslpc_program_hw(info); + + /* enable network layer transmit */ + dev->trans_start = jiffies; + netif_start_queue(dev); + + /* inform generic HDLC layer of current DCD status */ + spin_lock_irqsave(&info->lock, flags); + get_signals(info); + spin_unlock_irqrestore(&info->lock, flags); + if (info->serial_signals & SerialSignal_DCD) + netif_carrier_on(dev); + else + netif_carrier_off(dev); + return 0; +} + +/** + * called by network layer when interface is disabled + * shutdown hardware and release resources + * + * dev pointer to network device structure + * + * returns 0 if success, otherwise error code + */ +static int hdlcdev_close(struct net_device *dev) +{ + MGSLPC_INFO *info = dev_to_port(dev); + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s:hdlcdev_close(%s)\n",__FILE__,dev->name); + + netif_stop_queue(dev); + + /* shutdown adapter and release resources */ + shutdown(info); + + hdlc_close(dev); + + spin_lock_irqsave(&info->netlock, flags); + info->netcount=0; + spin_unlock_irqrestore(&info->netlock, flags); + + return 0; +} + +/** + * called by network layer to process IOCTL call to network device + * + * dev pointer to network device structure + * ifr pointer to network interface request structure + * cmd IOCTL command code + * + * returns 0 if success, otherwise error code + */ +static int hdlcdev_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) +{ + const size_t size = sizeof(sync_serial_settings); + sync_serial_settings new_line; + sync_serial_settings __user *line = ifr->ifr_settings.ifs_ifsu.sync; + MGSLPC_INFO *info = dev_to_port(dev); + unsigned int flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("%s:hdlcdev_ioctl(%s)\n",__FILE__,dev->name); + + /* return error if TTY interface open */ + if (info->count) + return -EBUSY; + + if (cmd != SIOCWANDEV) + return hdlc_ioctl(dev, ifr, cmd); + + switch(ifr->ifr_settings.type) { + case IF_GET_IFACE: /* return current sync_serial_settings */ + + ifr->ifr_settings.type = IF_IFACE_SYNC_SERIAL; + if (ifr->ifr_settings.size < size) { + ifr->ifr_settings.size = size; /* data size wanted */ + return -ENOBUFS; + } + + flags = info->params.flags & (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL | + HDLC_FLAG_RXC_BRG | HDLC_FLAG_RXC_TXCPIN | + HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL | + HDLC_FLAG_TXC_BRG | HDLC_FLAG_TXC_RXCPIN); + + switch (flags){ + case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_TXCPIN): new_line.clock_type = CLOCK_EXT; break; + case (HDLC_FLAG_RXC_BRG | HDLC_FLAG_TXC_BRG): new_line.clock_type = CLOCK_INT; break; + case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_BRG): new_line.clock_type = CLOCK_TXINT; break; + case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_RXCPIN): new_line.clock_type = CLOCK_TXFROMRX; break; + default: new_line.clock_type = CLOCK_DEFAULT; + } + + new_line.clock_rate = info->params.clock_speed; + new_line.loopback = info->params.loopback ? 1:0; + + if (copy_to_user(line, &new_line, size)) + return -EFAULT; + return 0; + + case IF_IFACE_SYNC_SERIAL: /* set sync_serial_settings */ + + if(!capable(CAP_NET_ADMIN)) + return -EPERM; + if (copy_from_user(&new_line, line, size)) + return -EFAULT; + + switch (new_line.clock_type) + { + case CLOCK_EXT: flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_TXCPIN; break; + case CLOCK_TXFROMRX: flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_RXCPIN; break; + case CLOCK_INT: flags = HDLC_FLAG_RXC_BRG | HDLC_FLAG_TXC_BRG; break; + case CLOCK_TXINT: flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_BRG; break; + case CLOCK_DEFAULT: flags = info->params.flags & + (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL | + HDLC_FLAG_RXC_BRG | HDLC_FLAG_RXC_TXCPIN | + HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL | + HDLC_FLAG_TXC_BRG | HDLC_FLAG_TXC_RXCPIN); break; + default: return -EINVAL; + } + + if (new_line.loopback != 0 && new_line.loopback != 1) + return -EINVAL; + + info->params.flags &= ~(HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL | + HDLC_FLAG_RXC_BRG | HDLC_FLAG_RXC_TXCPIN | + HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL | + HDLC_FLAG_TXC_BRG | HDLC_FLAG_TXC_RXCPIN); + info->params.flags |= flags; + + info->params.loopback = new_line.loopback; + + if (flags & (HDLC_FLAG_RXC_BRG | HDLC_FLAG_TXC_BRG)) + info->params.clock_speed = new_line.clock_rate; + else + info->params.clock_speed = 0; + + /* if network interface up, reprogram hardware */ + if (info->netcount) + mgslpc_program_hw(info); + return 0; + + default: + return hdlc_ioctl(dev, ifr, cmd); + } +} + +/** + * called by network layer when transmit timeout is detected + * + * dev pointer to network device structure + */ +static void hdlcdev_tx_timeout(struct net_device *dev) +{ + MGSLPC_INFO *info = dev_to_port(dev); + unsigned long flags; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("hdlcdev_tx_timeout(%s)\n",dev->name); + + dev->stats.tx_errors++; + dev->stats.tx_aborted_errors++; + + spin_lock_irqsave(&info->lock,flags); + tx_stop(info); + spin_unlock_irqrestore(&info->lock,flags); + + netif_wake_queue(dev); +} + +/** + * called by device driver when transmit completes + * reenable network layer transmit if stopped + * + * info pointer to device instance information + */ +static void hdlcdev_tx_done(MGSLPC_INFO *info) +{ + if (netif_queue_stopped(info->netdev)) + netif_wake_queue(info->netdev); +} + +/** + * called by device driver when frame received + * pass frame to network layer + * + * info pointer to device instance information + * buf pointer to buffer contianing frame data + * size count of data bytes in buf + */ +static void hdlcdev_rx(MGSLPC_INFO *info, char *buf, int size) +{ + struct sk_buff *skb = dev_alloc_skb(size); + struct net_device *dev = info->netdev; + + if (debug_level >= DEBUG_LEVEL_INFO) + printk("hdlcdev_rx(%s)\n",dev->name); + + if (skb == NULL) { + printk(KERN_NOTICE "%s: can't alloc skb, dropping packet\n", dev->name); + dev->stats.rx_dropped++; + return; + } + + memcpy(skb_put(skb, size), buf, size); + + skb->protocol = hdlc_type_trans(skb, dev); + + dev->stats.rx_packets++; + dev->stats.rx_bytes += size; + + netif_rx(skb); + + dev->last_rx = jiffies; +} + +/** + * called by device driver when adding device instance + * do generic HDLC initialization + * + * info pointer to device instance information + * + * returns 0 if success, otherwise error code + */ +static int hdlcdev_init(MGSLPC_INFO *info) +{ + int rc; + struct net_device *dev; + hdlc_device *hdlc; + + /* allocate and initialize network and HDLC layer objects */ + + if (!(dev = alloc_hdlcdev(info))) { + printk(KERN_ERR "%s:hdlc device allocation failure\n",__FILE__); + return -ENOMEM; + } + + /* for network layer reporting purposes only */ + dev->base_addr = info->io_base; + dev->irq = info->irq_level; + + /* network layer callbacks and settings */ + dev->do_ioctl = hdlcdev_ioctl; + dev->open = hdlcdev_open; + dev->stop = hdlcdev_close; + dev->tx_timeout = hdlcdev_tx_timeout; + dev->watchdog_timeo = 10*HZ; + dev->tx_queue_len = 50; + + /* generic HDLC layer callbacks and settings */ + hdlc = dev_to_hdlc(dev); + hdlc->attach = hdlcdev_attach; + hdlc->xmit = hdlcdev_xmit; + + /* register objects with HDLC layer */ + if ((rc = register_hdlc_device(dev))) { + printk(KERN_WARNING "%s:unable to register hdlc device\n",__FILE__); + free_netdev(dev); + return rc; + } + + info->netdev = dev; + return 0; +} + +/** + * called by device driver when removing device instance + * do generic HDLC cleanup + * + * info pointer to device instance information + */ +static void hdlcdev_exit(MGSLPC_INFO *info) +{ + unregister_hdlc_device(info->netdev); + free_netdev(info->netdev); + info->netdev = NULL; +} + +#endif /* CONFIG_HDLC */ + |