]> pilppa.org Git - linux-2.6-omap-h63xx.git/blob - drivers/char/pcmcia/synclink_cs.c
[PATCH] pcmcia: remove dev_list from drivers
[linux-2.6-omap-h63xx.git] / drivers / char / pcmcia / synclink_cs.c
1 /*
2  * linux/drivers/char/pcmcia/synclink_cs.c
3  *
4  * $Id: synclink_cs.c,v 4.34 2005/09/08 13:20:54 paulkf Exp $
5  *
6  * Device driver for Microgate SyncLink PC Card
7  * multiprotocol serial adapter.
8  *
9  * written by Paul Fulghum for Microgate Corporation
10  * paulkf@microgate.com
11  *
12  * Microgate and SyncLink are trademarks of Microgate Corporation
13  *
14  * This code is released under the GNU General Public License (GPL)
15  *
16  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
17  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
20  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
24  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
26  * OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #define VERSION(ver,rel,seq) (((ver)<<16) | ((rel)<<8) | (seq))
30 #if defined(__i386__)
31 #  define BREAKPOINT() asm("   int $3");
32 #else
33 #  define BREAKPOINT() { }
34 #endif
35
36 #define MAX_DEVICE_COUNT 4
37
38 #include <linux/config.h>       
39 #include <linux/module.h>
40 #include <linux/errno.h>
41 #include <linux/signal.h>
42 #include <linux/sched.h>
43 #include <linux/timer.h>
44 #include <linux/time.h>
45 #include <linux/interrupt.h>
46 #include <linux/pci.h>
47 #include <linux/tty.h>
48 #include <linux/tty_flip.h>
49 #include <linux/serial.h>
50 #include <linux/major.h>
51 #include <linux/string.h>
52 #include <linux/fcntl.h>
53 #include <linux/ptrace.h>
54 #include <linux/ioport.h>
55 #include <linux/mm.h>
56 #include <linux/slab.h>
57 #include <linux/netdevice.h>
58 #include <linux/vmalloc.h>
59 #include <linux/init.h>
60 #include <asm/serial.h>
61 #include <linux/delay.h>
62 #include <linux/ioctl.h>
63
64 #include <asm/system.h>
65 #include <asm/io.h>
66 #include <asm/irq.h>
67 #include <asm/dma.h>
68 #include <linux/bitops.h>
69 #include <asm/types.h>
70 #include <linux/termios.h>
71 #include <linux/workqueue.h>
72 #include <linux/hdlc.h>
73
74 #include <pcmcia/cs_types.h>
75 #include <pcmcia/cs.h>
76 #include <pcmcia/cistpl.h>
77 #include <pcmcia/cisreg.h>
78 #include <pcmcia/ds.h>
79
80 #ifdef CONFIG_HDLC_MODULE
81 #define CONFIG_HDLC 1
82 #endif
83
84 #define GET_USER(error,value,addr) error = get_user(value,addr)
85 #define COPY_FROM_USER(error,dest,src,size) error = copy_from_user(dest,src,size) ? -EFAULT : 0
86 #define PUT_USER(error,value,addr) error = put_user(value,addr)
87 #define COPY_TO_USER(error,dest,src,size) error = copy_to_user(dest,src,size) ? -EFAULT : 0
88
89 #include <asm/uaccess.h>
90
91 #include "linux/synclink.h"
92
93 static MGSL_PARAMS default_params = {
94         MGSL_MODE_HDLC,                 /* unsigned long mode */
95         0,                              /* unsigned char loopback; */
96         HDLC_FLAG_UNDERRUN_ABORT15,     /* unsigned short flags; */
97         HDLC_ENCODING_NRZI_SPACE,       /* unsigned char encoding; */
98         0,                              /* unsigned long clock_speed; */
99         0xff,                           /* unsigned char addr_filter; */
100         HDLC_CRC_16_CCITT,              /* unsigned short crc_type; */
101         HDLC_PREAMBLE_LENGTH_8BITS,     /* unsigned char preamble_length; */
102         HDLC_PREAMBLE_PATTERN_NONE,     /* unsigned char preamble; */
103         9600,                           /* unsigned long data_rate; */
104         8,                              /* unsigned char data_bits; */
105         1,                              /* unsigned char stop_bits; */
106         ASYNC_PARITY_NONE               /* unsigned char parity; */
107 };
108
109 typedef struct
110 {
111         int count;
112         unsigned char status;
113         char data[1];
114 } RXBUF;
115
116 /* The queue of BH actions to be performed */
117
118 #define BH_RECEIVE  1
119 #define BH_TRANSMIT 2
120 #define BH_STATUS   4
121
122 #define IO_PIN_SHUTDOWN_LIMIT 100
123
124 #define RELEVANT_IFLAG(iflag) (iflag & (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK))
125
126 struct _input_signal_events {
127         int     ri_up;  
128         int     ri_down;
129         int     dsr_up;
130         int     dsr_down;
131         int     dcd_up;
132         int     dcd_down;
133         int     cts_up;
134         int     cts_down;
135 };
136
137
138 /*
139  * Device instance data structure
140  */
141  
142 typedef struct _mgslpc_info {
143         void *if_ptr;   /* General purpose pointer (used by SPPP) */
144         int                     magic;
145         int                     flags;
146         int                     count;          /* count of opens */
147         int                     line;
148         unsigned short          close_delay;
149         unsigned short          closing_wait;   /* time to wait before closing */
150         
151         struct mgsl_icount      icount;
152         
153         struct tty_struct       *tty;
154         int                     timeout;
155         int                     x_char;         /* xon/xoff character */
156         int                     blocked_open;   /* # of blocked opens */
157         unsigned char           read_status_mask;
158         unsigned char           ignore_status_mask;     
159
160         unsigned char *tx_buf;
161         int            tx_put;
162         int            tx_get;
163         int            tx_count;
164
165         /* circular list of fixed length rx buffers */
166
167         unsigned char  *rx_buf;        /* memory allocated for all rx buffers */
168         int            rx_buf_total_size; /* size of memory allocated for rx buffers */
169         int            rx_put;         /* index of next empty rx buffer */
170         int            rx_get;         /* index of next full rx buffer */
171         int            rx_buf_size;    /* size in bytes of single rx buffer */
172         int            rx_buf_count;   /* total number of rx buffers */
173         int            rx_frame_count; /* number of full rx buffers */
174         
175         wait_queue_head_t       open_wait;
176         wait_queue_head_t       close_wait;
177         
178         wait_queue_head_t       status_event_wait_q;
179         wait_queue_head_t       event_wait_q;
180         struct timer_list       tx_timer;       /* HDLC transmit timeout timer */
181         struct _mgslpc_info     *next_device;   /* device list link */
182
183         unsigned short imra_value;
184         unsigned short imrb_value;
185         unsigned char  pim_value;
186
187         spinlock_t lock;
188         struct work_struct task;                /* task structure for scheduling bh */
189
190         u32 max_frame_size;
191
192         u32 pending_bh;
193
194         int bh_running;
195         int bh_requested;
196         
197         int dcd_chkcount; /* check counts to prevent */
198         int cts_chkcount; /* too many IRQs if a signal */
199         int dsr_chkcount; /* is floating */
200         int ri_chkcount;
201
202         int rx_enabled;
203         int rx_overflow;
204
205         int tx_enabled;
206         int tx_active;
207         int tx_aborting;
208         u32 idle_mode;
209
210         int if_mode; /* serial interface selection (RS-232, v.35 etc) */
211
212         char device_name[25];           /* device instance name */
213
214         unsigned int io_base;   /* base I/O address of adapter */
215         unsigned int irq_level;
216         
217         MGSL_PARAMS params;             /* communications parameters */
218
219         unsigned char serial_signals;   /* current serial signal states */
220
221         char irq_occurred;              /* for diagnostics use */
222         char testing_irq;
223         unsigned int init_error;        /* startup error (DIAGS)        */
224
225         char flag_buf[MAX_ASYNC_BUFFER_SIZE];
226         BOOLEAN drop_rts_on_tx_done;
227
228         struct  _input_signal_events    input_signal_events;
229
230         /* PCMCIA support */
231         dev_link_t            link;
232         dev_node_t            node;
233         int                   stop;
234
235         /* SPPP/Cisco HDLC device parts */
236         int netcount;
237         int dosyncppp;
238         spinlock_t netlock;
239
240 #ifdef CONFIG_HDLC
241         struct net_device *netdev;
242 #endif
243
244 } MGSLPC_INFO;
245
246 #define MGSLPC_MAGIC 0x5402
247
248 /*
249  * The size of the serial xmit buffer is 1 page, or 4096 bytes
250  */
251 #define TXBUFSIZE 4096
252
253     
254 #define CHA     0x00   /* channel A offset */
255 #define CHB     0x40   /* channel B offset */
256
257 /*
258  *  FIXME: PPC has PVR defined in asm/reg.h.  For now we just undef it.
259  */
260 #undef PVR
261
262 #define RXFIFO  0
263 #define TXFIFO  0
264 #define STAR    0x20
265 #define CMDR    0x20
266 #define RSTA    0x21
267 #define PRE     0x21
268 #define MODE    0x22
269 #define TIMR    0x23
270 #define XAD1    0x24
271 #define XAD2    0x25
272 #define RAH1    0x26
273 #define RAH2    0x27
274 #define DAFO    0x27
275 #define RAL1    0x28
276 #define RFC     0x28
277 #define RHCR    0x29
278 #define RAL2    0x29
279 #define RBCL    0x2a
280 #define XBCL    0x2a
281 #define RBCH    0x2b
282 #define XBCH    0x2b
283 #define CCR0    0x2c
284 #define CCR1    0x2d
285 #define CCR2    0x2e
286 #define CCR3    0x2f
287 #define VSTR    0x34
288 #define BGR     0x34
289 #define RLCR    0x35
290 #define AML     0x36
291 #define AMH     0x37
292 #define GIS     0x38
293 #define IVA     0x38
294 #define IPC     0x39
295 #define ISR     0x3a
296 #define IMR     0x3a
297 #define PVR     0x3c
298 #define PIS     0x3d
299 #define PIM     0x3d
300 #define PCR     0x3e
301 #define CCR4    0x3f
302     
303 // IMR/ISR
304     
305 #define IRQ_BREAK_ON    BIT15   // rx break detected
306 #define IRQ_DATAOVERRUN BIT14   // receive data overflow
307 #define IRQ_ALLSENT     BIT13   // all sent
308 #define IRQ_UNDERRUN    BIT12   // transmit data underrun
309 #define IRQ_TIMER       BIT11   // timer interrupt
310 #define IRQ_CTS         BIT10   // CTS status change
311 #define IRQ_TXREPEAT    BIT9    // tx message repeat
312 #define IRQ_TXFIFO      BIT8    // transmit pool ready
313 #define IRQ_RXEOM       BIT7    // receive message end
314 #define IRQ_EXITHUNT    BIT6    // receive frame start
315 #define IRQ_RXTIME      BIT6    // rx char timeout
316 #define IRQ_DCD         BIT2    // carrier detect status change
317 #define IRQ_OVERRUN     BIT1    // receive frame overflow
318 #define IRQ_RXFIFO      BIT0    // receive pool full
319     
320 // STAR
321     
322 #define XFW   BIT6              // transmit FIFO write enable
323 #define CEC   BIT2              // command executing
324 #define CTS   BIT1              // CTS state
325     
326 #define PVR_DTR      BIT0
327 #define PVR_DSR      BIT1
328 #define PVR_RI       BIT2
329 #define PVR_AUTOCTS  BIT3
330 #define PVR_RS232    0x20   /* 0010b */
331 #define PVR_V35      0xe0   /* 1110b */
332 #define PVR_RS422    0x40   /* 0100b */
333     
334 /* Register access functions */ 
335     
336 #define write_reg(info, reg, val) outb((val),(info)->io_base + (reg))
337 #define read_reg(info, reg) inb((info)->io_base + (reg))
338
339 #define read_reg16(info, reg) inw((info)->io_base + (reg))  
340 #define write_reg16(info, reg, val) outw((val), (info)->io_base + (reg))
341     
342 #define set_reg_bits(info, reg, mask) \
343     write_reg(info, (reg), \
344                  (unsigned char) (read_reg(info, (reg)) | (mask)))  
345 #define clear_reg_bits(info, reg, mask) \
346     write_reg(info, (reg), \
347                  (unsigned char) (read_reg(info, (reg)) & ~(mask)))  
348 /*
349  * interrupt enable/disable routines
350  */ 
351 static void irq_disable(MGSLPC_INFO *info, unsigned char channel, unsigned short mask) 
352 {
353         if (channel == CHA) {
354                 info->imra_value |= mask;
355                 write_reg16(info, CHA + IMR, info->imra_value);
356         } else {
357                 info->imrb_value |= mask;
358                 write_reg16(info, CHB + IMR, info->imrb_value);
359         }
360 }
361 static void irq_enable(MGSLPC_INFO *info, unsigned char channel, unsigned short mask) 
362 {
363         if (channel == CHA) {
364                 info->imra_value &= ~mask;
365                 write_reg16(info, CHA + IMR, info->imra_value);
366         } else {
367                 info->imrb_value &= ~mask;
368                 write_reg16(info, CHB + IMR, info->imrb_value);
369         }
370 }
371
372 #define port_irq_disable(info, mask) \
373   { info->pim_value |= (mask); write_reg(info, PIM, info->pim_value); }
374
375 #define port_irq_enable(info, mask) \
376   { info->pim_value &= ~(mask); write_reg(info, PIM, info->pim_value); }
377
378 static void rx_start(MGSLPC_INFO *info);
379 static void rx_stop(MGSLPC_INFO *info);
380
381 static void tx_start(MGSLPC_INFO *info);
382 static void tx_stop(MGSLPC_INFO *info);
383 static void tx_set_idle(MGSLPC_INFO *info);
384
385 static void get_signals(MGSLPC_INFO *info);
386 static void set_signals(MGSLPC_INFO *info);
387
388 static void reset_device(MGSLPC_INFO *info);
389
390 static void hdlc_mode(MGSLPC_INFO *info);
391 static void async_mode(MGSLPC_INFO *info);
392
393 static void tx_timeout(unsigned long context);
394
395 static int ioctl_common(MGSLPC_INFO *info, unsigned int cmd, unsigned long arg);
396
397 #ifdef CONFIG_HDLC
398 #define dev_to_port(D) (dev_to_hdlc(D)->priv)
399 static void hdlcdev_tx_done(MGSLPC_INFO *info);
400 static void hdlcdev_rx(MGSLPC_INFO *info, char *buf, int size);
401 static int  hdlcdev_init(MGSLPC_INFO *info);
402 static void hdlcdev_exit(MGSLPC_INFO *info);
403 #endif
404
405 static void trace_block(MGSLPC_INFO *info,const char* data, int count, int xmit);
406
407 static BOOLEAN register_test(MGSLPC_INFO *info);
408 static BOOLEAN irq_test(MGSLPC_INFO *info);
409 static int adapter_test(MGSLPC_INFO *info);
410
411 static int claim_resources(MGSLPC_INFO *info);
412 static void release_resources(MGSLPC_INFO *info);
413 static void mgslpc_add_device(MGSLPC_INFO *info);
414 static void mgslpc_remove_device(MGSLPC_INFO *info);
415
416 static int  rx_get_frame(MGSLPC_INFO *info);
417 static void rx_reset_buffers(MGSLPC_INFO *info);
418 static int  rx_alloc_buffers(MGSLPC_INFO *info);
419 static void rx_free_buffers(MGSLPC_INFO *info);
420
421 static irqreturn_t mgslpc_isr(int irq, void *dev_id, struct pt_regs * regs);
422
423 /*
424  * Bottom half interrupt handlers
425  */
426 static void bh_handler(void* Context);
427 static void bh_transmit(MGSLPC_INFO *info);
428 static void bh_status(MGSLPC_INFO *info);
429
430 /*
431  * ioctl handlers
432  */
433 static int tiocmget(struct tty_struct *tty, struct file *file);
434 static int tiocmset(struct tty_struct *tty, struct file *file,
435                     unsigned int set, unsigned int clear);
436 static int get_stats(MGSLPC_INFO *info, struct mgsl_icount __user *user_icount);
437 static int get_params(MGSLPC_INFO *info, MGSL_PARAMS __user *user_params);
438 static int set_params(MGSLPC_INFO *info, MGSL_PARAMS __user *new_params);
439 static int get_txidle(MGSLPC_INFO *info, int __user *idle_mode);
440 static int set_txidle(MGSLPC_INFO *info, int idle_mode);
441 static int set_txenable(MGSLPC_INFO *info, int enable);
442 static int tx_abort(MGSLPC_INFO *info);
443 static int set_rxenable(MGSLPC_INFO *info, int enable);
444 static int wait_events(MGSLPC_INFO *info, int __user *mask);
445
446 static MGSLPC_INFO *mgslpc_device_list = NULL;
447 static int mgslpc_device_count = 0;
448
449 /*
450  * Set this param to non-zero to load eax with the
451  * .text section address and breakpoint on module load.
452  * This is useful for use with gdb and add-symbol-file command.
453  */
454 static int break_on_load=0;
455
456 /*
457  * Driver major number, defaults to zero to get auto
458  * assigned major number. May be forced as module parameter.
459  */
460 static int ttymajor=0;
461
462 static int debug_level = 0;
463 static int maxframe[MAX_DEVICE_COUNT] = {0,};
464 static int dosyncppp[MAX_DEVICE_COUNT] = {1,1,1,1};
465
466 module_param(break_on_load, bool, 0);
467 module_param(ttymajor, int, 0);
468 module_param(debug_level, int, 0);
469 module_param_array(maxframe, int, NULL, 0);
470 module_param_array(dosyncppp, int, NULL, 0);
471
472 MODULE_LICENSE("GPL");
473
474 static char *driver_name = "SyncLink PC Card driver";
475 static char *driver_version = "$Revision: 4.34 $";
476
477 static struct tty_driver *serial_driver;
478
479 /* number of characters left in xmit buffer before we ask for more */
480 #define WAKEUP_CHARS 256
481
482 static void mgslpc_change_params(MGSLPC_INFO *info);
483 static void mgslpc_wait_until_sent(struct tty_struct *tty, int timeout);
484
485 /* PCMCIA prototypes */
486
487 static void mgslpc_config(dev_link_t *link);
488 static void mgslpc_release(u_long arg);
489 static int  mgslpc_event(event_t event, int priority,
490                          event_callback_args_t *args);
491 static dev_link_t *mgslpc_attach(void);
492 static void mgslpc_detach(struct pcmcia_device *p_dev);
493
494 static dev_info_t dev_info = "synclink_cs";
495
496 /*
497  * 1st function defined in .text section. Calling this function in
498  * init_module() followed by a breakpoint allows a remote debugger
499  * (gdb) to get the .text address for the add-symbol-file command.
500  * This allows remote debugging of dynamically loadable modules.
501  */
502 static void* mgslpc_get_text_ptr(void)
503 {
504         return mgslpc_get_text_ptr;
505 }
506
507 /**
508  * line discipline callback wrappers
509  *
510  * The wrappers maintain line discipline references
511  * while calling into the line discipline.
512  *
513  * ldisc_flush_buffer - flush line discipline receive buffers
514  * ldisc_receive_buf  - pass receive data to line discipline
515  */
516
517 static void ldisc_flush_buffer(struct tty_struct *tty)
518 {
519         struct tty_ldisc *ld = tty_ldisc_ref(tty);
520         if (ld) {
521                 if (ld->flush_buffer)
522                         ld->flush_buffer(tty);
523                 tty_ldisc_deref(ld);
524         }
525 }
526
527 static void ldisc_receive_buf(struct tty_struct *tty,
528                               const __u8 *data, char *flags, int count)
529 {
530         struct tty_ldisc *ld;
531         if (!tty)
532                 return;
533         ld = tty_ldisc_ref(tty);
534         if (ld) {
535                 if (ld->receive_buf)
536                         ld->receive_buf(tty, data, flags, count);
537                 tty_ldisc_deref(ld);
538         }
539 }
540
541 static dev_link_t *mgslpc_attach(void)
542 {
543     MGSLPC_INFO *info;
544     dev_link_t *link;
545     client_reg_t client_reg;
546     int ret;
547     
548     if (debug_level >= DEBUG_LEVEL_INFO)
549             printk("mgslpc_attach\n");
550         
551     info = (MGSLPC_INFO *)kmalloc(sizeof(MGSLPC_INFO), GFP_KERNEL);
552     if (!info) {
553             printk("Error can't allocate device instance data\n");
554             return NULL;
555     }
556
557     memset(info, 0, sizeof(MGSLPC_INFO));
558     info->magic = MGSLPC_MAGIC;
559     INIT_WORK(&info->task, bh_handler, info);
560     info->max_frame_size = 4096;
561     info->close_delay = 5*HZ/10;
562     info->closing_wait = 30*HZ;
563     init_waitqueue_head(&info->open_wait);
564     init_waitqueue_head(&info->close_wait);
565     init_waitqueue_head(&info->status_event_wait_q);
566     init_waitqueue_head(&info->event_wait_q);
567     spin_lock_init(&info->lock);
568     spin_lock_init(&info->netlock);
569     memcpy(&info->params,&default_params,sizeof(MGSL_PARAMS));
570     info->idle_mode = HDLC_TXIDLE_FLAGS;                
571     info->imra_value = 0xffff;
572     info->imrb_value = 0xffff;
573     info->pim_value = 0xff;
574
575     link = &info->link;
576     link->priv = info;
577     
578     /* Initialize the dev_link_t structure */
579
580     /* Interrupt setup */
581     link->irq.Attributes = IRQ_TYPE_EXCLUSIVE;
582     link->irq.IRQInfo1   = IRQ_LEVEL_ID;
583     link->irq.Handler = NULL;
584     
585     link->conf.Attributes = 0;
586     link->conf.Vcc = 50;
587     link->conf.IntType = INT_MEMORY_AND_IO;
588
589     /* Register with Card Services */
590     link->next = NULL;
591
592     client_reg.dev_info = &dev_info;
593     client_reg.Version = 0x0210;
594     client_reg.event_callback_args.client_data = link;
595
596     ret = pcmcia_register_client(&link->handle, &client_reg);
597     if (ret != CS_SUCCESS) {
598             cs_error(link->handle, RegisterClient, ret);
599             mgslpc_detach(link->handle);
600             return NULL;
601     }
602
603     mgslpc_add_device(info);
604
605     return link;
606 }
607
608 /* Card has been inserted.
609  */
610
611 #define CS_CHECK(fn, ret) \
612 do { last_fn = (fn); if ((last_ret = (ret)) != 0) goto cs_failed; } while (0)
613
614 static void mgslpc_config(dev_link_t *link)
615 {
616     client_handle_t handle = link->handle;
617     MGSLPC_INFO *info = link->priv;
618     tuple_t tuple;
619     cisparse_t parse;
620     int last_fn, last_ret;
621     u_char buf[64];
622     config_info_t conf;
623     cistpl_cftable_entry_t dflt = { 0 };
624     cistpl_cftable_entry_t *cfg;
625     
626     if (debug_level >= DEBUG_LEVEL_INFO)
627             printk("mgslpc_config(0x%p)\n", link);
628
629     /* read CONFIG tuple to find its configuration registers */
630     tuple.DesiredTuple = CISTPL_CONFIG;
631     tuple.Attributes = 0;
632     tuple.TupleData = buf;
633     tuple.TupleDataMax = sizeof(buf);
634     tuple.TupleOffset = 0;
635     CS_CHECK(GetFirstTuple, pcmcia_get_first_tuple(handle, &tuple));
636     CS_CHECK(GetTupleData, pcmcia_get_tuple_data(handle, &tuple));
637     CS_CHECK(ParseTuple, pcmcia_parse_tuple(handle, &tuple, &parse));
638     link->conf.ConfigBase = parse.config.base;
639     link->conf.Present = parse.config.rmask[0];
640     
641     /* Configure card */
642     link->state |= DEV_CONFIG;
643
644     /* Look up the current Vcc */
645     CS_CHECK(GetConfigurationInfo, pcmcia_get_configuration_info(handle, &conf));
646     link->conf.Vcc = conf.Vcc;
647
648     /* get CIS configuration entry */
649
650     tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY;
651     CS_CHECK(GetFirstTuple, pcmcia_get_first_tuple(handle, &tuple));
652
653     cfg = &(parse.cftable_entry);
654     CS_CHECK(GetTupleData, pcmcia_get_tuple_data(handle, &tuple));
655     CS_CHECK(ParseTuple, pcmcia_parse_tuple(handle, &tuple, &parse));
656
657     if (cfg->flags & CISTPL_CFTABLE_DEFAULT) dflt = *cfg;
658     if (cfg->index == 0)
659             goto cs_failed;
660
661     link->conf.ConfigIndex = cfg->index;
662     link->conf.Attributes |= CONF_ENABLE_IRQ;
663         
664     /* IO window settings */
665     link->io.NumPorts1 = 0;
666     if ((cfg->io.nwin > 0) || (dflt.io.nwin > 0)) {
667             cistpl_io_t *io = (cfg->io.nwin) ? &cfg->io : &dflt.io;
668             link->io.Attributes1 = IO_DATA_PATH_WIDTH_AUTO;
669             if (!(io->flags & CISTPL_IO_8BIT))
670                     link->io.Attributes1 = IO_DATA_PATH_WIDTH_16;
671             if (!(io->flags & CISTPL_IO_16BIT))
672                     link->io.Attributes1 = IO_DATA_PATH_WIDTH_8;
673             link->io.IOAddrLines = io->flags & CISTPL_IO_LINES_MASK;
674             link->io.BasePort1 = io->win[0].base;
675             link->io.NumPorts1 = io->win[0].len;
676             CS_CHECK(RequestIO, pcmcia_request_io(link->handle, &link->io));
677     }
678
679     link->conf.Attributes = CONF_ENABLE_IRQ;
680     link->conf.Vcc = 50;
681     link->conf.IntType = INT_MEMORY_AND_IO;
682     link->conf.ConfigIndex = 8;
683     link->conf.Present = PRESENT_OPTION;
684     
685     link->irq.Attributes |= IRQ_HANDLE_PRESENT;
686     link->irq.Handler     = mgslpc_isr;
687     link->irq.Instance    = info;
688     CS_CHECK(RequestIRQ, pcmcia_request_irq(link->handle, &link->irq));
689
690     CS_CHECK(RequestConfiguration, pcmcia_request_configuration(link->handle, &link->conf));
691
692     info->io_base = link->io.BasePort1;
693     info->irq_level = link->irq.AssignedIRQ;
694
695     /* add to linked list of devices */
696     sprintf(info->node.dev_name, "mgslpc0");
697     info->node.major = info->node.minor = 0;
698     link->dev = &info->node;
699
700     printk(KERN_INFO "%s: index 0x%02x:",
701            info->node.dev_name, link->conf.ConfigIndex);
702     if (link->conf.Attributes & CONF_ENABLE_IRQ)
703             printk(", irq %d", link->irq.AssignedIRQ);
704     if (link->io.NumPorts1)
705             printk(", io 0x%04x-0x%04x", link->io.BasePort1,
706                    link->io.BasePort1+link->io.NumPorts1-1);
707     printk("\n");
708     
709     link->state &= ~DEV_CONFIG_PENDING;
710     return;
711
712 cs_failed:
713     cs_error(link->handle, last_fn, last_ret);
714     mgslpc_release((u_long)link);
715 }
716
717 /* Card has been removed.
718  * Unregister device and release PCMCIA configuration.
719  * If device is open, postpone until it is closed.
720  */
721 static void mgslpc_release(u_long arg)
722 {
723     dev_link_t *link = (dev_link_t *)arg;
724
725     if (debug_level >= DEBUG_LEVEL_INFO)
726             printk("mgslpc_release(0x%p)\n", link);
727
728     /* Unlink the device chain */
729     link->dev = NULL;
730     link->state &= ~DEV_CONFIG;
731
732     pcmcia_release_configuration(link->handle);
733     if (link->io.NumPorts1)
734             pcmcia_release_io(link->handle, &link->io);
735     if (link->irq.AssignedIRQ)
736             pcmcia_release_irq(link->handle, &link->irq);
737 }
738
739 static void mgslpc_detach(struct pcmcia_device *p_dev)
740 {
741     dev_link_t *link = dev_to_instance(p_dev);
742
743     if (debug_level >= DEBUG_LEVEL_INFO)
744             printk("mgslpc_detach(0x%p)\n", link);
745
746     if (link->state & DEV_CONFIG) {
747             ((MGSLPC_INFO *)link->priv)->stop = 1;
748             mgslpc_release((u_long)link);
749     }
750
751     mgslpc_remove_device((MGSLPC_INFO *)link->priv);
752 }
753
754 static int mgslpc_suspend(struct pcmcia_device *dev)
755 {
756         dev_link_t *link = dev_to_instance(dev);
757         MGSLPC_INFO *info = link->priv;
758
759         link->state |= DEV_SUSPEND;
760         info->stop = 1;
761         if (link->state & DEV_CONFIG)
762                 pcmcia_release_configuration(link->handle);
763
764         return 0;
765 }
766
767 static int mgslpc_resume(struct pcmcia_device *dev)
768 {
769         dev_link_t *link = dev_to_instance(dev);
770         MGSLPC_INFO *info = link->priv;
771
772         link->state &= ~DEV_SUSPEND;
773         if (link->state & DEV_CONFIG)
774                 pcmcia_request_configuration(link->handle, &link->conf);
775         info->stop = 0;
776
777         return 0;
778 }
779
780
781 static int mgslpc_event(event_t event, int priority,
782                         event_callback_args_t *args)
783 {
784     dev_link_t *link = args->client_data;
785     
786     if (debug_level >= DEBUG_LEVEL_INFO)
787             printk("mgslpc_event(0x%06x)\n", event);
788     
789     switch (event) {
790     case CS_EVENT_CARD_INSERTION:
791             link->state |= DEV_PRESENT | DEV_CONFIG_PENDING;
792             mgslpc_config(link);
793             break;
794     }
795     return 0;
796 }
797
798 static inline int mgslpc_paranoia_check(MGSLPC_INFO *info,
799                                         char *name, const char *routine)
800 {
801 #ifdef MGSLPC_PARANOIA_CHECK
802         static const char *badmagic =
803                 "Warning: bad magic number for mgsl struct (%s) in %s\n";
804         static const char *badinfo =
805                 "Warning: null mgslpc_info for (%s) in %s\n";
806
807         if (!info) {
808                 printk(badinfo, name, routine);
809                 return 1;
810         }
811         if (info->magic != MGSLPC_MAGIC) {
812                 printk(badmagic, name, routine);
813                 return 1;
814         }
815 #else
816         if (!info)
817                 return 1;
818 #endif
819         return 0;
820 }
821
822
823 #define CMD_RXFIFO      BIT7    // release current rx FIFO
824 #define CMD_RXRESET     BIT6    // receiver reset
825 #define CMD_RXFIFO_READ BIT5
826 #define CMD_START_TIMER BIT4
827 #define CMD_TXFIFO      BIT3    // release current tx FIFO
828 #define CMD_TXEOM       BIT1    // transmit end message
829 #define CMD_TXRESET     BIT0    // transmit reset
830
831 static BOOLEAN wait_command_complete(MGSLPC_INFO *info, unsigned char channel) 
832 {
833         int i = 0;
834         /* wait for command completion */ 
835         while (read_reg(info, (unsigned char)(channel+STAR)) & BIT2) {
836                 udelay(1);
837                 if (i++ == 1000)
838                         return FALSE;
839         }
840         return TRUE;
841 }
842
843 static void issue_command(MGSLPC_INFO *info, unsigned char channel, unsigned char cmd) 
844 {
845         wait_command_complete(info, channel);
846         write_reg(info, (unsigned char) (channel + CMDR), cmd);
847 }
848
849 static void tx_pause(struct tty_struct *tty)
850 {
851         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
852         unsigned long flags;
853         
854         if (mgslpc_paranoia_check(info, tty->name, "tx_pause"))
855                 return;
856         if (debug_level >= DEBUG_LEVEL_INFO)
857                 printk("tx_pause(%s)\n",info->device_name);     
858                 
859         spin_lock_irqsave(&info->lock,flags);
860         if (info->tx_enabled)
861                 tx_stop(info);
862         spin_unlock_irqrestore(&info->lock,flags);
863 }
864
865 static void tx_release(struct tty_struct *tty)
866 {
867         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
868         unsigned long flags;
869         
870         if (mgslpc_paranoia_check(info, tty->name, "tx_release"))
871                 return;
872         if (debug_level >= DEBUG_LEVEL_INFO)
873                 printk("tx_release(%s)\n",info->device_name);   
874                 
875         spin_lock_irqsave(&info->lock,flags);
876         if (!info->tx_enabled)
877                 tx_start(info);
878         spin_unlock_irqrestore(&info->lock,flags);
879 }
880
881 /* Return next bottom half action to perform.
882  * or 0 if nothing to do.
883  */
884 static int bh_action(MGSLPC_INFO *info)
885 {
886         unsigned long flags;
887         int rc = 0;
888         
889         spin_lock_irqsave(&info->lock,flags);
890
891         if (info->pending_bh & BH_RECEIVE) {
892                 info->pending_bh &= ~BH_RECEIVE;
893                 rc = BH_RECEIVE;
894         } else if (info->pending_bh & BH_TRANSMIT) {
895                 info->pending_bh &= ~BH_TRANSMIT;
896                 rc = BH_TRANSMIT;
897         } else if (info->pending_bh & BH_STATUS) {
898                 info->pending_bh &= ~BH_STATUS;
899                 rc = BH_STATUS;
900         }
901
902         if (!rc) {
903                 /* Mark BH routine as complete */
904                 info->bh_running   = 0;
905                 info->bh_requested = 0;
906         }
907         
908         spin_unlock_irqrestore(&info->lock,flags);
909         
910         return rc;
911 }
912
913 void bh_handler(void* Context)
914 {
915         MGSLPC_INFO *info = (MGSLPC_INFO*)Context;
916         int action;
917
918         if (!info)
919                 return;
920                 
921         if (debug_level >= DEBUG_LEVEL_BH)
922                 printk( "%s(%d):bh_handler(%s) entry\n",
923                         __FILE__,__LINE__,info->device_name);
924         
925         info->bh_running = 1;
926
927         while((action = bh_action(info)) != 0) {
928         
929                 /* Process work item */
930                 if ( debug_level >= DEBUG_LEVEL_BH )
931                         printk( "%s(%d):bh_handler() work item action=%d\n",
932                                 __FILE__,__LINE__,action);
933
934                 switch (action) {
935                 
936                 case BH_RECEIVE:
937                         while(rx_get_frame(info));
938                         break;
939                 case BH_TRANSMIT:
940                         bh_transmit(info);
941                         break;
942                 case BH_STATUS:
943                         bh_status(info);
944                         break;
945                 default:
946                         /* unknown work item ID */
947                         printk("Unknown work item ID=%08X!\n", action);
948                         break;
949                 }
950         }
951
952         if (debug_level >= DEBUG_LEVEL_BH)
953                 printk( "%s(%d):bh_handler(%s) exit\n",
954                         __FILE__,__LINE__,info->device_name);
955 }
956
957 void bh_transmit(MGSLPC_INFO *info)
958 {
959         struct tty_struct *tty = info->tty;
960         if (debug_level >= DEBUG_LEVEL_BH)
961                 printk("bh_transmit() entry on %s\n", info->device_name);
962
963         if (tty) {
964                 tty_wakeup(tty);
965                 wake_up_interruptible(&tty->write_wait);
966         }
967 }
968
969 void bh_status(MGSLPC_INFO *info)
970 {
971         info->ri_chkcount = 0;
972         info->dsr_chkcount = 0;
973         info->dcd_chkcount = 0;
974         info->cts_chkcount = 0;
975 }
976
977 /* eom: non-zero = end of frame */ 
978 static void rx_ready_hdlc(MGSLPC_INFO *info, int eom)
979 {
980         unsigned char data[2];
981         unsigned char fifo_count, read_count, i;
982         RXBUF *buf = (RXBUF*)(info->rx_buf + (info->rx_put * info->rx_buf_size));
983
984         if (debug_level >= DEBUG_LEVEL_ISR)
985                 printk("%s(%d):rx_ready_hdlc(eom=%d)\n",__FILE__,__LINE__,eom);
986         
987         if (!info->rx_enabled)
988                 return;
989
990         if (info->rx_frame_count >= info->rx_buf_count) {
991                 /* no more free buffers */
992                 issue_command(info, CHA, CMD_RXRESET);
993                 info->pending_bh |= BH_RECEIVE;
994                 info->rx_overflow = 1;
995                 info->icount.buf_overrun++;
996                 return;
997         }
998
999         if (eom) {
1000                 /* end of frame, get FIFO count from RBCL register */ 
1001                 if (!(fifo_count = (unsigned char)(read_reg(info, CHA+RBCL) & 0x1f)))
1002                         fifo_count = 32;
1003         } else
1004                 fifo_count = 32;
1005         
1006         do {
1007                 if (fifo_count == 1) {
1008                         read_count = 1;
1009                         data[0] = read_reg(info, CHA + RXFIFO);
1010                 } else {
1011                         read_count = 2;
1012                         *((unsigned short *) data) = read_reg16(info, CHA + RXFIFO);
1013                 }
1014                 fifo_count -= read_count;
1015                 if (!fifo_count && eom)
1016                         buf->status = data[--read_count];
1017
1018                 for (i = 0; i < read_count; i++) {
1019                         if (buf->count >= info->max_frame_size) {
1020                                 /* frame too large, reset receiver and reset current buffer */
1021                                 issue_command(info, CHA, CMD_RXRESET);
1022                                 buf->count = 0;
1023                                 return;
1024                         }
1025                         *(buf->data + buf->count) = data[i];
1026                         buf->count++;
1027                 }
1028         } while (fifo_count);
1029
1030         if (eom) {
1031                 info->pending_bh |= BH_RECEIVE;
1032                 info->rx_frame_count++;
1033                 info->rx_put++;
1034                 if (info->rx_put >= info->rx_buf_count)
1035                         info->rx_put = 0;
1036         }
1037         issue_command(info, CHA, CMD_RXFIFO);
1038 }
1039
1040 static void rx_ready_async(MGSLPC_INFO *info, int tcd)
1041 {
1042         unsigned char data, status;
1043         int fifo_count;
1044         struct tty_struct *tty = info->tty;
1045         struct mgsl_icount *icount = &info->icount;
1046
1047         if (tcd) {
1048                 /* early termination, get FIFO count from RBCL register */ 
1049                 fifo_count = (unsigned char)(read_reg(info, CHA+RBCL) & 0x1f);
1050
1051                 /* Zero fifo count could mean 0 or 32 bytes available.
1052                  * If BIT5 of STAR is set then at least 1 byte is available.
1053                  */
1054                 if (!fifo_count && (read_reg(info,CHA+STAR) & BIT5))
1055                         fifo_count = 32;
1056         } else
1057                 fifo_count = 32;
1058         
1059         /* Flush received async data to receive data buffer. */ 
1060         while (fifo_count) {
1061                 data   = read_reg(info, CHA + RXFIFO);
1062                 status = read_reg(info, CHA + RXFIFO);
1063                 fifo_count -= 2;
1064
1065                 if (tty->flip.count >= TTY_FLIPBUF_SIZE)
1066                         break;
1067                         
1068                 *tty->flip.char_buf_ptr = data;
1069                 icount->rx++;
1070                 
1071                 *tty->flip.flag_buf_ptr = 0;
1072
1073                 // if no frameing/crc error then save data
1074                 // BIT7:parity error
1075                 // BIT6:framing error
1076
1077                 if (status & (BIT7 + BIT6)) {
1078                         if (status & BIT7) 
1079                                 icount->parity++;
1080                         else
1081                                 icount->frame++;
1082
1083                         /* discard char if tty control flags say so */
1084                         if (status & info->ignore_status_mask)
1085                                 continue;
1086                                 
1087                         status &= info->read_status_mask;
1088
1089                         if (status & BIT7)
1090                                 *tty->flip.flag_buf_ptr = TTY_PARITY;
1091                         else if (status & BIT6)
1092                                 *tty->flip.flag_buf_ptr = TTY_FRAME;
1093                 }
1094                 
1095                 tty->flip.flag_buf_ptr++;
1096                 tty->flip.char_buf_ptr++;
1097                 tty->flip.count++;
1098         }
1099         issue_command(info, CHA, CMD_RXFIFO);
1100
1101         if (debug_level >= DEBUG_LEVEL_ISR) {
1102                 printk("%s(%d):rx_ready_async count=%d\n",
1103                         __FILE__,__LINE__,tty->flip.count);
1104                 printk("%s(%d):rx=%d brk=%d parity=%d frame=%d overrun=%d\n",
1105                         __FILE__,__LINE__,icount->rx,icount->brk,
1106                         icount->parity,icount->frame,icount->overrun);
1107         }
1108                         
1109         if (tty->flip.count)
1110                 tty_flip_buffer_push(tty);
1111 }
1112
1113
1114 static void tx_done(MGSLPC_INFO *info)
1115 {
1116         if (!info->tx_active)
1117                 return;
1118                         
1119         info->tx_active = 0;
1120         info->tx_aborting = 0;
1121
1122         if (info->params.mode == MGSL_MODE_ASYNC)
1123                 return;
1124
1125         info->tx_count = info->tx_put = info->tx_get = 0;
1126         del_timer(&info->tx_timer);     
1127         
1128         if (info->drop_rts_on_tx_done) {
1129                 get_signals(info);
1130                 if (info->serial_signals & SerialSignal_RTS) {
1131                         info->serial_signals &= ~SerialSignal_RTS;
1132                         set_signals(info);
1133                 }
1134                 info->drop_rts_on_tx_done = 0;
1135         }
1136
1137 #ifdef CONFIG_HDLC
1138         if (info->netcount)
1139                 hdlcdev_tx_done(info);
1140         else 
1141 #endif
1142         {
1143                 if (info->tty->stopped || info->tty->hw_stopped) {
1144                         tx_stop(info);
1145                         return;
1146                 }
1147                 info->pending_bh |= BH_TRANSMIT;
1148         }
1149 }
1150
1151 static void tx_ready(MGSLPC_INFO *info)
1152 {
1153         unsigned char fifo_count = 32;
1154         int c;
1155
1156         if (debug_level >= DEBUG_LEVEL_ISR)
1157                 printk("%s(%d):tx_ready(%s)\n", __FILE__,__LINE__,info->device_name);
1158
1159         if (info->params.mode == MGSL_MODE_HDLC) {
1160                 if (!info->tx_active)
1161                         return;
1162         } else {
1163                 if (info->tty->stopped || info->tty->hw_stopped) {
1164                         tx_stop(info);
1165                         return;
1166                 }
1167                 if (!info->tx_count)
1168                         info->tx_active = 0;
1169         }
1170
1171         if (!info->tx_count)
1172                 return;
1173
1174         while (info->tx_count && fifo_count) {
1175                 c = min(2, min_t(int, fifo_count, min(info->tx_count, TXBUFSIZE - info->tx_get)));
1176                 
1177                 if (c == 1) {
1178                         write_reg(info, CHA + TXFIFO, *(info->tx_buf + info->tx_get));
1179                 } else {
1180                         write_reg16(info, CHA + TXFIFO,
1181                                           *((unsigned short*)(info->tx_buf + info->tx_get)));
1182                 }
1183                 info->tx_count -= c;
1184                 info->tx_get = (info->tx_get + c) & (TXBUFSIZE - 1);
1185                 fifo_count -= c;
1186         }
1187
1188         if (info->params.mode == MGSL_MODE_ASYNC) {
1189                 if (info->tx_count < WAKEUP_CHARS)
1190                         info->pending_bh |= BH_TRANSMIT;
1191                 issue_command(info, CHA, CMD_TXFIFO);
1192         } else {
1193                 if (info->tx_count)
1194                         issue_command(info, CHA, CMD_TXFIFO);
1195                 else
1196                         issue_command(info, CHA, CMD_TXFIFO + CMD_TXEOM);
1197         }
1198 }
1199
1200 static void cts_change(MGSLPC_INFO *info)
1201 {
1202         get_signals(info);
1203         if ((info->cts_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT)
1204                 irq_disable(info, CHB, IRQ_CTS);
1205         info->icount.cts++;
1206         if (info->serial_signals & SerialSignal_CTS)
1207                 info->input_signal_events.cts_up++;
1208         else
1209                 info->input_signal_events.cts_down++;
1210         wake_up_interruptible(&info->status_event_wait_q);
1211         wake_up_interruptible(&info->event_wait_q);
1212
1213         if (info->flags & ASYNC_CTS_FLOW) {
1214                 if (info->tty->hw_stopped) {
1215                         if (info->serial_signals & SerialSignal_CTS) {
1216                                 if (debug_level >= DEBUG_LEVEL_ISR)
1217                                         printk("CTS tx start...");
1218                                 if (info->tty)
1219                                         info->tty->hw_stopped = 0;
1220                                 tx_start(info);
1221                                 info->pending_bh |= BH_TRANSMIT;
1222                                 return;
1223                         }
1224                 } else {
1225                         if (!(info->serial_signals & SerialSignal_CTS)) {
1226                                 if (debug_level >= DEBUG_LEVEL_ISR)
1227                                         printk("CTS tx stop...");
1228                                 if (info->tty)
1229                                         info->tty->hw_stopped = 1;
1230                                 tx_stop(info);
1231                         }
1232                 }
1233         }
1234         info->pending_bh |= BH_STATUS;
1235 }
1236
1237 static void dcd_change(MGSLPC_INFO *info)
1238 {
1239         get_signals(info);
1240         if ((info->dcd_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT)
1241                 irq_disable(info, CHB, IRQ_DCD);
1242         info->icount.dcd++;
1243         if (info->serial_signals & SerialSignal_DCD) {
1244                 info->input_signal_events.dcd_up++;
1245         }
1246         else
1247                 info->input_signal_events.dcd_down++;
1248 #ifdef CONFIG_HDLC
1249         if (info->netcount)
1250                 hdlc_set_carrier(info->serial_signals & SerialSignal_DCD, info->netdev);
1251 #endif
1252         wake_up_interruptible(&info->status_event_wait_q);
1253         wake_up_interruptible(&info->event_wait_q);
1254
1255         if (info->flags & ASYNC_CHECK_CD) {
1256                 if (debug_level >= DEBUG_LEVEL_ISR)
1257                         printk("%s CD now %s...", info->device_name,
1258                                (info->serial_signals & SerialSignal_DCD) ? "on" : "off");
1259                 if (info->serial_signals & SerialSignal_DCD)
1260                         wake_up_interruptible(&info->open_wait);
1261                 else {
1262                         if (debug_level >= DEBUG_LEVEL_ISR)
1263                                 printk("doing serial hangup...");
1264                         if (info->tty)
1265                                 tty_hangup(info->tty);
1266                 }
1267         }
1268         info->pending_bh |= BH_STATUS;
1269 }
1270
1271 static void dsr_change(MGSLPC_INFO *info)
1272 {
1273         get_signals(info);
1274         if ((info->dsr_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT)
1275                 port_irq_disable(info, PVR_DSR);
1276         info->icount.dsr++;
1277         if (info->serial_signals & SerialSignal_DSR)
1278                 info->input_signal_events.dsr_up++;
1279         else
1280                 info->input_signal_events.dsr_down++;
1281         wake_up_interruptible(&info->status_event_wait_q);
1282         wake_up_interruptible(&info->event_wait_q);
1283         info->pending_bh |= BH_STATUS;
1284 }
1285
1286 static void ri_change(MGSLPC_INFO *info)
1287 {
1288         get_signals(info);
1289         if ((info->ri_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT)
1290                 port_irq_disable(info, PVR_RI);
1291         info->icount.rng++;
1292         if (info->serial_signals & SerialSignal_RI)
1293                 info->input_signal_events.ri_up++;
1294         else
1295                 info->input_signal_events.ri_down++;
1296         wake_up_interruptible(&info->status_event_wait_q);
1297         wake_up_interruptible(&info->event_wait_q);
1298         info->pending_bh |= BH_STATUS;
1299 }
1300
1301 /* Interrupt service routine entry point.
1302  *      
1303  * Arguments:
1304  * 
1305  * irq     interrupt number that caused interrupt
1306  * dev_id  device ID supplied during interrupt registration
1307  * regs    interrupted processor context
1308  */
1309 static irqreturn_t mgslpc_isr(int irq, void *dev_id, struct pt_regs * regs)
1310 {
1311         MGSLPC_INFO * info = (MGSLPC_INFO *)dev_id;
1312         unsigned short isr;
1313         unsigned char gis, pis;
1314         int count=0;
1315
1316         if (debug_level >= DEBUG_LEVEL_ISR)     
1317                 printk("mgslpc_isr(%d) entry.\n", irq);
1318         if (!info)
1319                 return IRQ_NONE;
1320                 
1321         if (!(info->link.state & DEV_CONFIG))
1322                 return IRQ_HANDLED;
1323
1324         spin_lock(&info->lock);
1325
1326         while ((gis = read_reg(info, CHA + GIS))) {
1327                 if (debug_level >= DEBUG_LEVEL_ISR)     
1328                         printk("mgslpc_isr %s gis=%04X\n", info->device_name,gis);
1329
1330                 if ((gis & 0x70) || count > 1000) {
1331                         printk("synclink_cs:hardware failed or ejected\n");
1332                         break;
1333                 }
1334                 count++;
1335
1336                 if (gis & (BIT1 + BIT0)) {
1337                         isr = read_reg16(info, CHB + ISR);
1338                         if (isr & IRQ_DCD)
1339                                 dcd_change(info);
1340                         if (isr & IRQ_CTS)
1341                                 cts_change(info);
1342                 }
1343                 if (gis & (BIT3 + BIT2))
1344                 {
1345                         isr = read_reg16(info, CHA + ISR);
1346                         if (isr & IRQ_TIMER) {
1347                                 info->irq_occurred = 1;
1348                                 irq_disable(info, CHA, IRQ_TIMER);
1349                         }
1350
1351                         /* receive IRQs */ 
1352                         if (isr & IRQ_EXITHUNT) {
1353                                 info->icount.exithunt++;
1354                                 wake_up_interruptible(&info->event_wait_q);
1355                         }
1356                         if (isr & IRQ_BREAK_ON) {
1357                                 info->icount.brk++;
1358                                 if (info->flags & ASYNC_SAK)
1359                                         do_SAK(info->tty);
1360                         }
1361                         if (isr & IRQ_RXTIME) {
1362                                 issue_command(info, CHA, CMD_RXFIFO_READ);
1363                         }
1364                         if (isr & (IRQ_RXEOM + IRQ_RXFIFO)) {
1365                                 if (info->params.mode == MGSL_MODE_HDLC)
1366                                         rx_ready_hdlc(info, isr & IRQ_RXEOM); 
1367                                 else
1368                                         rx_ready_async(info, isr & IRQ_RXEOM);
1369                         }
1370
1371                         /* transmit IRQs */ 
1372                         if (isr & IRQ_UNDERRUN) {
1373                                 if (info->tx_aborting)
1374                                         info->icount.txabort++;
1375                                 else
1376                                         info->icount.txunder++;
1377                                 tx_done(info);
1378                         }
1379                         else if (isr & IRQ_ALLSENT) {
1380                                 info->icount.txok++;
1381                                 tx_done(info);
1382                         }
1383                         else if (isr & IRQ_TXFIFO)
1384                                 tx_ready(info);
1385                 }
1386                 if (gis & BIT7) {
1387                         pis = read_reg(info, CHA + PIS);
1388                         if (pis & BIT1)
1389                                 dsr_change(info);
1390                         if (pis & BIT2)
1391                                 ri_change(info);
1392                 }
1393         }
1394         
1395         /* Request bottom half processing if there's something 
1396          * for it to do and the bh is not already running
1397          */
1398
1399         if (info->pending_bh && !info->bh_running && !info->bh_requested) {
1400                 if ( debug_level >= DEBUG_LEVEL_ISR )   
1401                         printk("%s(%d):%s queueing bh task.\n",
1402                                 __FILE__,__LINE__,info->device_name);
1403                 schedule_work(&info->task);
1404                 info->bh_requested = 1;
1405         }
1406
1407         spin_unlock(&info->lock);
1408         
1409         if (debug_level >= DEBUG_LEVEL_ISR)     
1410                 printk("%s(%d):mgslpc_isr(%d)exit.\n",
1411                        __FILE__,__LINE__,irq);
1412
1413         return IRQ_HANDLED;
1414 }
1415
1416 /* Initialize and start device.
1417  */
1418 static int startup(MGSLPC_INFO * info)
1419 {
1420         int retval = 0;
1421         
1422         if (debug_level >= DEBUG_LEVEL_INFO)
1423                 printk("%s(%d):startup(%s)\n",__FILE__,__LINE__,info->device_name);
1424                 
1425         if (info->flags & ASYNC_INITIALIZED)
1426                 return 0;
1427         
1428         if (!info->tx_buf) {
1429                 /* allocate a page of memory for a transmit buffer */
1430                 info->tx_buf = (unsigned char *)get_zeroed_page(GFP_KERNEL);
1431                 if (!info->tx_buf) {
1432                         printk(KERN_ERR"%s(%d):%s can't allocate transmit buffer\n",
1433                                 __FILE__,__LINE__,info->device_name);
1434                         return -ENOMEM;
1435                 }
1436         }
1437
1438         info->pending_bh = 0;
1439         
1440         memset(&info->icount, 0, sizeof(info->icount));
1441
1442         init_timer(&info->tx_timer);
1443         info->tx_timer.data = (unsigned long)info;
1444         info->tx_timer.function = tx_timeout;
1445
1446         /* Allocate and claim adapter resources */
1447         retval = claim_resources(info);
1448         
1449         /* perform existance check and diagnostics */
1450         if ( !retval )
1451                 retval = adapter_test(info);
1452                 
1453         if ( retval ) {
1454                 if (capable(CAP_SYS_ADMIN) && info->tty)
1455                         set_bit(TTY_IO_ERROR, &info->tty->flags);
1456                 release_resources(info);
1457                 return retval;
1458         }
1459
1460         /* program hardware for current parameters */
1461         mgslpc_change_params(info);
1462         
1463         if (info->tty)
1464                 clear_bit(TTY_IO_ERROR, &info->tty->flags);
1465
1466         info->flags |= ASYNC_INITIALIZED;
1467         
1468         return 0;
1469 }
1470
1471 /* Called by mgslpc_close() and mgslpc_hangup() to shutdown hardware
1472  */
1473 static void shutdown(MGSLPC_INFO * info)
1474 {
1475         unsigned long flags;
1476         
1477         if (!(info->flags & ASYNC_INITIALIZED))
1478                 return;
1479
1480         if (debug_level >= DEBUG_LEVEL_INFO)
1481                 printk("%s(%d):mgslpc_shutdown(%s)\n",
1482                          __FILE__,__LINE__, info->device_name );
1483
1484         /* clear status wait queue because status changes */
1485         /* can't happen after shutting down the hardware */
1486         wake_up_interruptible(&info->status_event_wait_q);
1487         wake_up_interruptible(&info->event_wait_q);
1488
1489         del_timer(&info->tx_timer);     
1490
1491         if (info->tx_buf) {
1492                 free_page((unsigned long) info->tx_buf);
1493                 info->tx_buf = NULL;
1494         }
1495
1496         spin_lock_irqsave(&info->lock,flags);
1497
1498         rx_stop(info);
1499         tx_stop(info);
1500
1501         /* TODO:disable interrupts instead of reset to preserve signal states */
1502         reset_device(info);
1503         
1504         if (!info->tty || info->tty->termios->c_cflag & HUPCL) {
1505                 info->serial_signals &= ~(SerialSignal_DTR + SerialSignal_RTS);
1506                 set_signals(info);
1507         }
1508         
1509         spin_unlock_irqrestore(&info->lock,flags);
1510
1511         release_resources(info);        
1512         
1513         if (info->tty)
1514                 set_bit(TTY_IO_ERROR, &info->tty->flags);
1515
1516         info->flags &= ~ASYNC_INITIALIZED;
1517 }
1518
1519 static void mgslpc_program_hw(MGSLPC_INFO *info)
1520 {
1521         unsigned long flags;
1522
1523         spin_lock_irqsave(&info->lock,flags);
1524         
1525         rx_stop(info);
1526         tx_stop(info);
1527         info->tx_count = info->tx_put = info->tx_get = 0;
1528         
1529         if (info->params.mode == MGSL_MODE_HDLC || info->netcount)
1530                 hdlc_mode(info);
1531         else
1532                 async_mode(info);
1533                 
1534         set_signals(info);
1535         
1536         info->dcd_chkcount = 0;
1537         info->cts_chkcount = 0;
1538         info->ri_chkcount = 0;
1539         info->dsr_chkcount = 0;
1540
1541         irq_enable(info, CHB, IRQ_DCD | IRQ_CTS);
1542         port_irq_enable(info, (unsigned char) PVR_DSR | PVR_RI);
1543         get_signals(info);
1544                 
1545         if (info->netcount || info->tty->termios->c_cflag & CREAD)
1546                 rx_start(info);
1547                 
1548         spin_unlock_irqrestore(&info->lock,flags);
1549 }
1550
1551 /* Reconfigure adapter based on new parameters
1552  */
1553 static void mgslpc_change_params(MGSLPC_INFO *info)
1554 {
1555         unsigned cflag;
1556         int bits_per_char;
1557
1558         if (!info->tty || !info->tty->termios)
1559                 return;
1560                 
1561         if (debug_level >= DEBUG_LEVEL_INFO)
1562                 printk("%s(%d):mgslpc_change_params(%s)\n",
1563                          __FILE__,__LINE__, info->device_name );
1564                          
1565         cflag = info->tty->termios->c_cflag;
1566
1567         /* if B0 rate (hangup) specified then negate DTR and RTS */
1568         /* otherwise assert DTR and RTS */
1569         if (cflag & CBAUD)
1570                 info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR;
1571         else
1572                 info->serial_signals &= ~(SerialSignal_RTS + SerialSignal_DTR);
1573         
1574         /* byte size and parity */
1575         
1576         switch (cflag & CSIZE) {
1577         case CS5: info->params.data_bits = 5; break;
1578         case CS6: info->params.data_bits = 6; break;
1579         case CS7: info->params.data_bits = 7; break;
1580         case CS8: info->params.data_bits = 8; break;
1581         default:  info->params.data_bits = 7; break;
1582         }
1583               
1584         if (cflag & CSTOPB)
1585                 info->params.stop_bits = 2;
1586         else
1587                 info->params.stop_bits = 1;
1588
1589         info->params.parity = ASYNC_PARITY_NONE;
1590         if (cflag & PARENB) {
1591                 if (cflag & PARODD)
1592                         info->params.parity = ASYNC_PARITY_ODD;
1593                 else
1594                         info->params.parity = ASYNC_PARITY_EVEN;
1595 #ifdef CMSPAR
1596                 if (cflag & CMSPAR)
1597                         info->params.parity = ASYNC_PARITY_SPACE;
1598 #endif
1599         }
1600
1601         /* calculate number of jiffies to transmit a full
1602          * FIFO (32 bytes) at specified data rate
1603          */
1604         bits_per_char = info->params.data_bits + 
1605                         info->params.stop_bits + 1;
1606
1607         /* if port data rate is set to 460800 or less then
1608          * allow tty settings to override, otherwise keep the
1609          * current data rate.
1610          */
1611         if (info->params.data_rate <= 460800) {
1612                 info->params.data_rate = tty_get_baud_rate(info->tty);
1613         }
1614         
1615         if ( info->params.data_rate ) {
1616                 info->timeout = (32*HZ*bits_per_char) / 
1617                                 info->params.data_rate;
1618         }
1619         info->timeout += HZ/50;         /* Add .02 seconds of slop */
1620
1621         if (cflag & CRTSCTS)
1622                 info->flags |= ASYNC_CTS_FLOW;
1623         else
1624                 info->flags &= ~ASYNC_CTS_FLOW;
1625                 
1626         if (cflag & CLOCAL)
1627                 info->flags &= ~ASYNC_CHECK_CD;
1628         else
1629                 info->flags |= ASYNC_CHECK_CD;
1630
1631         /* process tty input control flags */
1632         
1633         info->read_status_mask = 0;
1634         if (I_INPCK(info->tty))
1635                 info->read_status_mask |= BIT7 | BIT6;
1636         if (I_IGNPAR(info->tty))
1637                 info->ignore_status_mask |= BIT7 | BIT6;
1638
1639         mgslpc_program_hw(info);
1640 }
1641
1642 /* Add a character to the transmit buffer
1643  */
1644 static void mgslpc_put_char(struct tty_struct *tty, unsigned char ch)
1645 {
1646         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1647         unsigned long flags;
1648
1649         if (debug_level >= DEBUG_LEVEL_INFO) {
1650                 printk( "%s(%d):mgslpc_put_char(%d) on %s\n",
1651                         __FILE__,__LINE__,ch,info->device_name);
1652         }
1653
1654         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_put_char"))
1655                 return;
1656
1657         if (!tty || !info->tx_buf)
1658                 return;
1659
1660         spin_lock_irqsave(&info->lock,flags);
1661         
1662         if (info->params.mode == MGSL_MODE_ASYNC || !info->tx_active) {
1663                 if (info->tx_count < TXBUFSIZE - 1) {
1664                         info->tx_buf[info->tx_put++] = ch;
1665                         info->tx_put &= TXBUFSIZE-1;
1666                         info->tx_count++;
1667                 }
1668         }
1669         
1670         spin_unlock_irqrestore(&info->lock,flags);
1671 }
1672
1673 /* Enable transmitter so remaining characters in the
1674  * transmit buffer are sent.
1675  */
1676 static void mgslpc_flush_chars(struct tty_struct *tty)
1677 {
1678         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1679         unsigned long flags;
1680                                 
1681         if (debug_level >= DEBUG_LEVEL_INFO)
1682                 printk( "%s(%d):mgslpc_flush_chars() entry on %s tx_count=%d\n",
1683                         __FILE__,__LINE__,info->device_name,info->tx_count);
1684         
1685         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_flush_chars"))
1686                 return;
1687
1688         if (info->tx_count <= 0 || tty->stopped ||
1689             tty->hw_stopped || !info->tx_buf)
1690                 return;
1691
1692         if (debug_level >= DEBUG_LEVEL_INFO)
1693                 printk( "%s(%d):mgslpc_flush_chars() entry on %s starting transmitter\n",
1694                         __FILE__,__LINE__,info->device_name);
1695
1696         spin_lock_irqsave(&info->lock,flags);
1697         if (!info->tx_active)
1698                 tx_start(info);
1699         spin_unlock_irqrestore(&info->lock,flags);
1700 }
1701
1702 /* Send a block of data
1703  *      
1704  * Arguments:
1705  * 
1706  * tty        pointer to tty information structure
1707  * buf        pointer to buffer containing send data
1708  * count      size of send data in bytes
1709  *      
1710  * Returns: number of characters written
1711  */
1712 static int mgslpc_write(struct tty_struct * tty,
1713                         const unsigned char *buf, int count)
1714 {
1715         int c, ret = 0;
1716         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1717         unsigned long flags;
1718         
1719         if (debug_level >= DEBUG_LEVEL_INFO)
1720                 printk( "%s(%d):mgslpc_write(%s) count=%d\n",
1721                         __FILE__,__LINE__,info->device_name,count);
1722         
1723         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_write") ||
1724             !tty || !info->tx_buf)
1725                 goto cleanup;
1726
1727         if (info->params.mode == MGSL_MODE_HDLC) {
1728                 if (count > TXBUFSIZE) {
1729                         ret = -EIO;
1730                         goto cleanup;
1731                 }
1732                 if (info->tx_active)
1733                         goto cleanup;
1734                 else if (info->tx_count)
1735                         goto start;
1736         }
1737
1738         for (;;) {
1739                 c = min(count,
1740                         min(TXBUFSIZE - info->tx_count - 1,
1741                             TXBUFSIZE - info->tx_put));
1742                 if (c <= 0)
1743                         break;
1744                         
1745                 memcpy(info->tx_buf + info->tx_put, buf, c);
1746
1747                 spin_lock_irqsave(&info->lock,flags);
1748                 info->tx_put = (info->tx_put + c) & (TXBUFSIZE-1);
1749                 info->tx_count += c;
1750                 spin_unlock_irqrestore(&info->lock,flags);
1751
1752                 buf += c;
1753                 count -= c;
1754                 ret += c;
1755         }
1756 start:
1757         if (info->tx_count && !tty->stopped && !tty->hw_stopped) {
1758                 spin_lock_irqsave(&info->lock,flags);
1759                 if (!info->tx_active)
1760                         tx_start(info);
1761                 spin_unlock_irqrestore(&info->lock,flags);
1762         }
1763 cleanup:        
1764         if (debug_level >= DEBUG_LEVEL_INFO)
1765                 printk( "%s(%d):mgslpc_write(%s) returning=%d\n",
1766                         __FILE__,__LINE__,info->device_name,ret);
1767         return ret;
1768 }
1769
1770 /* Return the count of free bytes in transmit buffer
1771  */
1772 static int mgslpc_write_room(struct tty_struct *tty)
1773 {
1774         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1775         int ret;
1776                                 
1777         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_write_room"))
1778                 return 0;
1779
1780         if (info->params.mode == MGSL_MODE_HDLC) {
1781                 /* HDLC (frame oriented) mode */
1782                 if (info->tx_active)
1783                         return 0;
1784                 else
1785                         return HDLC_MAX_FRAME_SIZE;
1786         } else {
1787                 ret = TXBUFSIZE - info->tx_count - 1;
1788                 if (ret < 0)
1789                         ret = 0;
1790         }
1791         
1792         if (debug_level >= DEBUG_LEVEL_INFO)
1793                 printk("%s(%d):mgslpc_write_room(%s)=%d\n",
1794                          __FILE__,__LINE__, info->device_name, ret);
1795         return ret;
1796 }
1797
1798 /* Return the count of bytes in transmit buffer
1799  */
1800 static int mgslpc_chars_in_buffer(struct tty_struct *tty)
1801 {
1802         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1803         int rc;
1804                  
1805         if (debug_level >= DEBUG_LEVEL_INFO)
1806                 printk("%s(%d):mgslpc_chars_in_buffer(%s)\n",
1807                          __FILE__,__LINE__, info->device_name );
1808                          
1809         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_chars_in_buffer"))
1810                 return 0;
1811                 
1812         if (info->params.mode == MGSL_MODE_HDLC)
1813                 rc = info->tx_active ? info->max_frame_size : 0;
1814         else
1815                 rc = info->tx_count;
1816
1817         if (debug_level >= DEBUG_LEVEL_INFO)
1818                 printk("%s(%d):mgslpc_chars_in_buffer(%s)=%d\n",
1819                          __FILE__,__LINE__, info->device_name, rc);
1820                          
1821         return rc;
1822 }
1823
1824 /* Discard all data in the send buffer
1825  */
1826 static void mgslpc_flush_buffer(struct tty_struct *tty)
1827 {
1828         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1829         unsigned long flags;
1830         
1831         if (debug_level >= DEBUG_LEVEL_INFO)
1832                 printk("%s(%d):mgslpc_flush_buffer(%s) entry\n",
1833                          __FILE__,__LINE__, info->device_name );
1834         
1835         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_flush_buffer"))
1836                 return;
1837                 
1838         spin_lock_irqsave(&info->lock,flags); 
1839         info->tx_count = info->tx_put = info->tx_get = 0;
1840         del_timer(&info->tx_timer);     
1841         spin_unlock_irqrestore(&info->lock,flags);
1842
1843         wake_up_interruptible(&tty->write_wait);
1844         tty_wakeup(tty);
1845 }
1846
1847 /* Send a high-priority XON/XOFF character
1848  */
1849 static void mgslpc_send_xchar(struct tty_struct *tty, char ch)
1850 {
1851         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1852         unsigned long flags;
1853
1854         if (debug_level >= DEBUG_LEVEL_INFO)
1855                 printk("%s(%d):mgslpc_send_xchar(%s,%d)\n",
1856                          __FILE__,__LINE__, info->device_name, ch );
1857                          
1858         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_send_xchar"))
1859                 return;
1860
1861         info->x_char = ch;
1862         if (ch) {
1863                 spin_lock_irqsave(&info->lock,flags);
1864                 if (!info->tx_enabled)
1865                         tx_start(info);
1866                 spin_unlock_irqrestore(&info->lock,flags);
1867         }
1868 }
1869
1870 /* Signal remote device to throttle send data (our receive data)
1871  */
1872 static void mgslpc_throttle(struct tty_struct * tty)
1873 {
1874         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1875         unsigned long flags;
1876         
1877         if (debug_level >= DEBUG_LEVEL_INFO)
1878                 printk("%s(%d):mgslpc_throttle(%s) entry\n",
1879                          __FILE__,__LINE__, info->device_name );
1880
1881         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_throttle"))
1882                 return;
1883         
1884         if (I_IXOFF(tty))
1885                 mgslpc_send_xchar(tty, STOP_CHAR(tty));
1886  
1887         if (tty->termios->c_cflag & CRTSCTS) {
1888                 spin_lock_irqsave(&info->lock,flags);
1889                 info->serial_signals &= ~SerialSignal_RTS;
1890                 set_signals(info);
1891                 spin_unlock_irqrestore(&info->lock,flags);
1892         }
1893 }
1894
1895 /* Signal remote device to stop throttling send data (our receive data)
1896  */
1897 static void mgslpc_unthrottle(struct tty_struct * tty)
1898 {
1899         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1900         unsigned long flags;
1901         
1902         if (debug_level >= DEBUG_LEVEL_INFO)
1903                 printk("%s(%d):mgslpc_unthrottle(%s) entry\n",
1904                          __FILE__,__LINE__, info->device_name );
1905
1906         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_unthrottle"))
1907                 return;
1908         
1909         if (I_IXOFF(tty)) {
1910                 if (info->x_char)
1911                         info->x_char = 0;
1912                 else
1913                         mgslpc_send_xchar(tty, START_CHAR(tty));
1914         }
1915         
1916         if (tty->termios->c_cflag & CRTSCTS) {
1917                 spin_lock_irqsave(&info->lock,flags);
1918                 info->serial_signals |= SerialSignal_RTS;
1919                 set_signals(info);
1920                 spin_unlock_irqrestore(&info->lock,flags);
1921         }
1922 }
1923
1924 /* get the current serial statistics
1925  */
1926 static int get_stats(MGSLPC_INFO * info, struct mgsl_icount __user *user_icount)
1927 {
1928         int err;
1929         if (debug_level >= DEBUG_LEVEL_INFO)
1930                 printk("get_params(%s)\n", info->device_name);
1931         if (!user_icount) {
1932                 memset(&info->icount, 0, sizeof(info->icount));
1933         } else {
1934                 COPY_TO_USER(err, user_icount, &info->icount, sizeof(struct mgsl_icount));
1935                 if (err)
1936                         return -EFAULT;
1937         }
1938         return 0;
1939 }
1940
1941 /* get the current serial parameters
1942  */
1943 static int get_params(MGSLPC_INFO * info, MGSL_PARAMS __user *user_params)
1944 {
1945         int err;
1946         if (debug_level >= DEBUG_LEVEL_INFO)
1947                 printk("get_params(%s)\n", info->device_name);
1948         COPY_TO_USER(err,user_params, &info->params, sizeof(MGSL_PARAMS));
1949         if (err)
1950                 return -EFAULT;
1951         return 0;
1952 }
1953
1954 /* set the serial parameters
1955  *      
1956  * Arguments:
1957  * 
1958  *      info            pointer to device instance data
1959  *      new_params      user buffer containing new serial params
1960  *
1961  * Returns:     0 if success, otherwise error code
1962  */
1963 static int set_params(MGSLPC_INFO * info, MGSL_PARAMS __user *new_params)
1964 {
1965         unsigned long flags;
1966         MGSL_PARAMS tmp_params;
1967         int err;
1968  
1969         if (debug_level >= DEBUG_LEVEL_INFO)
1970                 printk("%s(%d):set_params %s\n", __FILE__,__LINE__,
1971                         info->device_name );
1972         COPY_FROM_USER(err,&tmp_params, new_params, sizeof(MGSL_PARAMS));
1973         if (err) {
1974                 if ( debug_level >= DEBUG_LEVEL_INFO )
1975                         printk( "%s(%d):set_params(%s) user buffer copy failed\n",
1976                                 __FILE__,__LINE__,info->device_name);
1977                 return -EFAULT;
1978         }
1979         
1980         spin_lock_irqsave(&info->lock,flags);
1981         memcpy(&info->params,&tmp_params,sizeof(MGSL_PARAMS));
1982         spin_unlock_irqrestore(&info->lock,flags);
1983         
1984         mgslpc_change_params(info);
1985         
1986         return 0;
1987 }
1988
1989 static int get_txidle(MGSLPC_INFO * info, int __user *idle_mode)
1990 {
1991         int err;
1992         if (debug_level >= DEBUG_LEVEL_INFO)
1993                 printk("get_txidle(%s)=%d\n", info->device_name, info->idle_mode);
1994         COPY_TO_USER(err,idle_mode, &info->idle_mode, sizeof(int));
1995         if (err)
1996                 return -EFAULT;
1997         return 0;
1998 }
1999
2000 static int set_txidle(MGSLPC_INFO * info, int idle_mode)
2001 {
2002         unsigned long flags;
2003         if (debug_level >= DEBUG_LEVEL_INFO)
2004                 printk("set_txidle(%s,%d)\n", info->device_name, idle_mode);
2005         spin_lock_irqsave(&info->lock,flags);
2006         info->idle_mode = idle_mode;
2007         tx_set_idle(info);
2008         spin_unlock_irqrestore(&info->lock,flags);
2009         return 0;
2010 }
2011
2012 static int get_interface(MGSLPC_INFO * info, int __user *if_mode)
2013 {
2014         int err;
2015         if (debug_level >= DEBUG_LEVEL_INFO)
2016                 printk("get_interface(%s)=%d\n", info->device_name, info->if_mode);
2017         COPY_TO_USER(err,if_mode, &info->if_mode, sizeof(int));
2018         if (err)
2019                 return -EFAULT;
2020         return 0;
2021 }
2022
2023 static int set_interface(MGSLPC_INFO * info, int if_mode)
2024 {
2025         unsigned long flags;
2026         unsigned char val;
2027         if (debug_level >= DEBUG_LEVEL_INFO)
2028                 printk("set_interface(%s,%d)\n", info->device_name, if_mode);
2029         spin_lock_irqsave(&info->lock,flags);
2030         info->if_mode = if_mode;
2031
2032         val = read_reg(info, PVR) & 0x0f;
2033         switch (info->if_mode)
2034         {
2035         case MGSL_INTERFACE_RS232: val |= PVR_RS232; break;
2036         case MGSL_INTERFACE_V35:   val |= PVR_V35;   break;
2037         case MGSL_INTERFACE_RS422: val |= PVR_RS422; break;
2038         }
2039         write_reg(info, PVR, val);
2040
2041         spin_unlock_irqrestore(&info->lock,flags);
2042         return 0;
2043 }
2044
2045 static int set_txenable(MGSLPC_INFO * info, int enable)
2046 {
2047         unsigned long flags;
2048  
2049         if (debug_level >= DEBUG_LEVEL_INFO)
2050                 printk("set_txenable(%s,%d)\n", info->device_name, enable);
2051                         
2052         spin_lock_irqsave(&info->lock,flags);
2053         if (enable) {
2054                 if (!info->tx_enabled)
2055                         tx_start(info);
2056         } else {
2057                 if (info->tx_enabled)
2058                         tx_stop(info);
2059         }
2060         spin_unlock_irqrestore(&info->lock,flags);
2061         return 0;
2062 }
2063
2064 static int tx_abort(MGSLPC_INFO * info)
2065 {
2066         unsigned long flags;
2067  
2068         if (debug_level >= DEBUG_LEVEL_INFO)
2069                 printk("tx_abort(%s)\n", info->device_name);
2070                         
2071         spin_lock_irqsave(&info->lock,flags);
2072         if (info->tx_active && info->tx_count &&
2073             info->params.mode == MGSL_MODE_HDLC) {
2074                 /* clear data count so FIFO is not filled on next IRQ.
2075                  * This results in underrun and abort transmission.
2076                  */
2077                 info->tx_count = info->tx_put = info->tx_get = 0;
2078                 info->tx_aborting = TRUE;
2079         }
2080         spin_unlock_irqrestore(&info->lock,flags);
2081         return 0;
2082 }
2083
2084 static int set_rxenable(MGSLPC_INFO * info, int enable)
2085 {
2086         unsigned long flags;
2087  
2088         if (debug_level >= DEBUG_LEVEL_INFO)
2089                 printk("set_rxenable(%s,%d)\n", info->device_name, enable);
2090                         
2091         spin_lock_irqsave(&info->lock,flags);
2092         if (enable) {
2093                 if (!info->rx_enabled)
2094                         rx_start(info);
2095         } else {
2096                 if (info->rx_enabled)
2097                         rx_stop(info);
2098         }
2099         spin_unlock_irqrestore(&info->lock,flags);
2100         return 0;
2101 }
2102
2103 /* wait for specified event to occur
2104  *      
2105  * Arguments:           info    pointer to device instance data
2106  *                      mask    pointer to bitmask of events to wait for
2107  * Return Value:        0       if successful and bit mask updated with
2108  *                              of events triggerred,
2109  *                      otherwise error code
2110  */
2111 static int wait_events(MGSLPC_INFO * info, int __user *mask_ptr)
2112 {
2113         unsigned long flags;
2114         int s;
2115         int rc=0;
2116         struct mgsl_icount cprev, cnow;
2117         int events;
2118         int mask;
2119         struct  _input_signal_events oldsigs, newsigs;
2120         DECLARE_WAITQUEUE(wait, current);
2121
2122         COPY_FROM_USER(rc,&mask, mask_ptr, sizeof(int));
2123         if (rc)
2124                 return  -EFAULT;
2125                  
2126         if (debug_level >= DEBUG_LEVEL_INFO)
2127                 printk("wait_events(%s,%d)\n", info->device_name, mask);
2128
2129         spin_lock_irqsave(&info->lock,flags);
2130
2131         /* return immediately if state matches requested events */
2132         get_signals(info);
2133         s = info->serial_signals;
2134         events = mask &
2135                 ( ((s & SerialSignal_DSR) ? MgslEvent_DsrActive:MgslEvent_DsrInactive) +
2136                   ((s & SerialSignal_DCD) ? MgslEvent_DcdActive:MgslEvent_DcdInactive) +
2137                   ((s & SerialSignal_CTS) ? MgslEvent_CtsActive:MgslEvent_CtsInactive) +
2138                   ((s & SerialSignal_RI)  ? MgslEvent_RiActive :MgslEvent_RiInactive) );
2139         if (events) {
2140                 spin_unlock_irqrestore(&info->lock,flags);
2141                 goto exit;
2142         }
2143
2144         /* save current irq counts */
2145         cprev = info->icount;
2146         oldsigs = info->input_signal_events;
2147         
2148         if ((info->params.mode == MGSL_MODE_HDLC) &&
2149             (mask & MgslEvent_ExitHuntMode))
2150                 irq_enable(info, CHA, IRQ_EXITHUNT);
2151         
2152         set_current_state(TASK_INTERRUPTIBLE);
2153         add_wait_queue(&info->event_wait_q, &wait);
2154         
2155         spin_unlock_irqrestore(&info->lock,flags);
2156         
2157         
2158         for(;;) {
2159                 schedule();
2160                 if (signal_pending(current)) {
2161                         rc = -ERESTARTSYS;
2162                         break;
2163                 }
2164                         
2165                 /* get current irq counts */
2166                 spin_lock_irqsave(&info->lock,flags);
2167                 cnow = info->icount;
2168                 newsigs = info->input_signal_events;
2169                 set_current_state(TASK_INTERRUPTIBLE);
2170                 spin_unlock_irqrestore(&info->lock,flags);
2171
2172                 /* if no change, wait aborted for some reason */
2173                 if (newsigs.dsr_up   == oldsigs.dsr_up   &&
2174                     newsigs.dsr_down == oldsigs.dsr_down &&
2175                     newsigs.dcd_up   == oldsigs.dcd_up   &&
2176                     newsigs.dcd_down == oldsigs.dcd_down &&
2177                     newsigs.cts_up   == oldsigs.cts_up   &&
2178                     newsigs.cts_down == oldsigs.cts_down &&
2179                     newsigs.ri_up    == oldsigs.ri_up    &&
2180                     newsigs.ri_down  == oldsigs.ri_down  &&
2181                     cnow.exithunt    == cprev.exithunt   &&
2182                     cnow.rxidle      == cprev.rxidle) {
2183                         rc = -EIO;
2184                         break;
2185                 }
2186
2187                 events = mask &
2188                         ( (newsigs.dsr_up   != oldsigs.dsr_up   ? MgslEvent_DsrActive:0)   +
2189                           (newsigs.dsr_down != oldsigs.dsr_down ? MgslEvent_DsrInactive:0) +
2190                           (newsigs.dcd_up   != oldsigs.dcd_up   ? MgslEvent_DcdActive:0)   +
2191                           (newsigs.dcd_down != oldsigs.dcd_down ? MgslEvent_DcdInactive:0) +
2192                           (newsigs.cts_up   != oldsigs.cts_up   ? MgslEvent_CtsActive:0)   +
2193                           (newsigs.cts_down != oldsigs.cts_down ? MgslEvent_CtsInactive:0) +
2194                           (newsigs.ri_up    != oldsigs.ri_up    ? MgslEvent_RiActive:0)    +
2195                           (newsigs.ri_down  != oldsigs.ri_down  ? MgslEvent_RiInactive:0)  +
2196                           (cnow.exithunt    != cprev.exithunt   ? MgslEvent_ExitHuntMode:0) +
2197                           (cnow.rxidle      != cprev.rxidle     ? MgslEvent_IdleReceived:0) );
2198                 if (events)
2199                         break;
2200                 
2201                 cprev = cnow;
2202                 oldsigs = newsigs;
2203         }
2204         
2205         remove_wait_queue(&info->event_wait_q, &wait);
2206         set_current_state(TASK_RUNNING);
2207
2208         if (mask & MgslEvent_ExitHuntMode) {
2209                 spin_lock_irqsave(&info->lock,flags);
2210                 if (!waitqueue_active(&info->event_wait_q))
2211                         irq_disable(info, CHA, IRQ_EXITHUNT);
2212                 spin_unlock_irqrestore(&info->lock,flags);
2213         }
2214 exit:
2215         if (rc == 0)
2216                 PUT_USER(rc, events, mask_ptr);
2217         return rc;
2218 }
2219
2220 static int modem_input_wait(MGSLPC_INFO *info,int arg)
2221 {
2222         unsigned long flags;
2223         int rc;
2224         struct mgsl_icount cprev, cnow;
2225         DECLARE_WAITQUEUE(wait, current);
2226
2227         /* save current irq counts */
2228         spin_lock_irqsave(&info->lock,flags);
2229         cprev = info->icount;
2230         add_wait_queue(&info->status_event_wait_q, &wait);
2231         set_current_state(TASK_INTERRUPTIBLE);
2232         spin_unlock_irqrestore(&info->lock,flags);
2233
2234         for(;;) {
2235                 schedule();
2236                 if (signal_pending(current)) {
2237                         rc = -ERESTARTSYS;
2238                         break;
2239                 }
2240
2241                 /* get new irq counts */
2242                 spin_lock_irqsave(&info->lock,flags);
2243                 cnow = info->icount;
2244                 set_current_state(TASK_INTERRUPTIBLE);
2245                 spin_unlock_irqrestore(&info->lock,flags);
2246
2247                 /* if no change, wait aborted for some reason */
2248                 if (cnow.rng == cprev.rng && cnow.dsr == cprev.dsr &&
2249                     cnow.dcd == cprev.dcd && cnow.cts == cprev.cts) {
2250                         rc = -EIO;
2251                         break;
2252                 }
2253
2254                 /* check for change in caller specified modem input */
2255                 if ((arg & TIOCM_RNG && cnow.rng != cprev.rng) ||
2256                     (arg & TIOCM_DSR && cnow.dsr != cprev.dsr) ||
2257                     (arg & TIOCM_CD  && cnow.dcd != cprev.dcd) ||
2258                     (arg & TIOCM_CTS && cnow.cts != cprev.cts)) {
2259                         rc = 0;
2260                         break;
2261                 }
2262
2263                 cprev = cnow;
2264         }
2265         remove_wait_queue(&info->status_event_wait_q, &wait);
2266         set_current_state(TASK_RUNNING);
2267         return rc;
2268 }
2269
2270 /* return the state of the serial control and status signals
2271  */
2272 static int tiocmget(struct tty_struct *tty, struct file *file)
2273 {
2274         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
2275         unsigned int result;
2276         unsigned long flags;
2277
2278         spin_lock_irqsave(&info->lock,flags);
2279         get_signals(info);
2280         spin_unlock_irqrestore(&info->lock,flags);
2281
2282         result = ((info->serial_signals & SerialSignal_RTS) ? TIOCM_RTS:0) +
2283                 ((info->serial_signals & SerialSignal_DTR) ? TIOCM_DTR:0) +
2284                 ((info->serial_signals & SerialSignal_DCD) ? TIOCM_CAR:0) +
2285                 ((info->serial_signals & SerialSignal_RI)  ? TIOCM_RNG:0) +
2286                 ((info->serial_signals & SerialSignal_DSR) ? TIOCM_DSR:0) +
2287                 ((info->serial_signals & SerialSignal_CTS) ? TIOCM_CTS:0);
2288
2289         if (debug_level >= DEBUG_LEVEL_INFO)
2290                 printk("%s(%d):%s tiocmget() value=%08X\n",
2291                          __FILE__,__LINE__, info->device_name, result );
2292         return result;
2293 }
2294
2295 /* set modem control signals (DTR/RTS)
2296  */
2297 static int tiocmset(struct tty_struct *tty, struct file *file,
2298                     unsigned int set, unsigned int clear)
2299 {
2300         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
2301         unsigned long flags;
2302
2303         if (debug_level >= DEBUG_LEVEL_INFO)
2304                 printk("%s(%d):%s tiocmset(%x,%x)\n",
2305                         __FILE__,__LINE__,info->device_name, set, clear);
2306
2307         if (set & TIOCM_RTS)
2308                 info->serial_signals |= SerialSignal_RTS;
2309         if (set & TIOCM_DTR)
2310                 info->serial_signals |= SerialSignal_DTR;
2311         if (clear & TIOCM_RTS)
2312                 info->serial_signals &= ~SerialSignal_RTS;
2313         if (clear & TIOCM_DTR)
2314                 info->serial_signals &= ~SerialSignal_DTR;
2315
2316         spin_lock_irqsave(&info->lock,flags);
2317         set_signals(info);
2318         spin_unlock_irqrestore(&info->lock,flags);
2319
2320         return 0;
2321 }
2322
2323 /* Set or clear transmit break condition
2324  *
2325  * Arguments:           tty             pointer to tty instance data
2326  *                      break_state     -1=set break condition, 0=clear
2327  */
2328 static void mgslpc_break(struct tty_struct *tty, int break_state)
2329 {
2330         MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data;
2331         unsigned long flags;
2332         
2333         if (debug_level >= DEBUG_LEVEL_INFO)
2334                 printk("%s(%d):mgslpc_break(%s,%d)\n",
2335                          __FILE__,__LINE__, info->device_name, break_state);
2336                          
2337         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_break"))
2338                 return;
2339
2340         spin_lock_irqsave(&info->lock,flags);
2341         if (break_state == -1)
2342                 set_reg_bits(info, CHA+DAFO, BIT6);
2343         else 
2344                 clear_reg_bits(info, CHA+DAFO, BIT6);
2345         spin_unlock_irqrestore(&info->lock,flags);
2346 }
2347
2348 /* Service an IOCTL request
2349  *      
2350  * Arguments:
2351  * 
2352  *      tty     pointer to tty instance data
2353  *      file    pointer to associated file object for device
2354  *      cmd     IOCTL command code
2355  *      arg     command argument/context
2356  *      
2357  * Return Value:        0 if success, otherwise error code
2358  */
2359 static int mgslpc_ioctl(struct tty_struct *tty, struct file * file,
2360                         unsigned int cmd, unsigned long arg)
2361 {
2362         MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data;
2363         
2364         if (debug_level >= DEBUG_LEVEL_INFO)
2365                 printk("%s(%d):mgslpc_ioctl %s cmd=%08X\n", __FILE__,__LINE__,
2366                         info->device_name, cmd );
2367         
2368         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_ioctl"))
2369                 return -ENODEV;
2370
2371         if ((cmd != TIOCGSERIAL) && (cmd != TIOCSSERIAL) &&
2372             (cmd != TIOCMIWAIT) && (cmd != TIOCGICOUNT)) {
2373                 if (tty->flags & (1 << TTY_IO_ERROR))
2374                     return -EIO;
2375         }
2376
2377         return ioctl_common(info, cmd, arg);
2378 }
2379
2380 int ioctl_common(MGSLPC_INFO *info, unsigned int cmd, unsigned long arg)
2381 {
2382         int error;
2383         struct mgsl_icount cnow;        /* kernel counter temps */
2384         struct serial_icounter_struct __user *p_cuser;  /* user space */
2385         void __user *argp = (void __user *)arg;
2386         unsigned long flags;
2387         
2388         switch (cmd) {
2389         case MGSL_IOCGPARAMS:
2390                 return get_params(info, argp);
2391         case MGSL_IOCSPARAMS:
2392                 return set_params(info, argp);
2393         case MGSL_IOCGTXIDLE:
2394                 return get_txidle(info, argp);
2395         case MGSL_IOCSTXIDLE:
2396                 return set_txidle(info, (int)arg);
2397         case MGSL_IOCGIF:
2398                 return get_interface(info, argp);
2399         case MGSL_IOCSIF:
2400                 return set_interface(info,(int)arg);
2401         case MGSL_IOCTXENABLE:
2402                 return set_txenable(info,(int)arg);
2403         case MGSL_IOCRXENABLE:
2404                 return set_rxenable(info,(int)arg);
2405         case MGSL_IOCTXABORT:
2406                 return tx_abort(info);
2407         case MGSL_IOCGSTATS:
2408                 return get_stats(info, argp);
2409         case MGSL_IOCWAITEVENT:
2410                 return wait_events(info, argp);
2411         case TIOCMIWAIT:
2412                 return modem_input_wait(info,(int)arg);
2413         case TIOCGICOUNT:
2414                 spin_lock_irqsave(&info->lock,flags);
2415                 cnow = info->icount;
2416                 spin_unlock_irqrestore(&info->lock,flags);
2417                 p_cuser = argp;
2418                 PUT_USER(error,cnow.cts, &p_cuser->cts);
2419                 if (error) return error;
2420                 PUT_USER(error,cnow.dsr, &p_cuser->dsr);
2421                 if (error) return error;
2422                 PUT_USER(error,cnow.rng, &p_cuser->rng);
2423                 if (error) return error;
2424                 PUT_USER(error,cnow.dcd, &p_cuser->dcd);
2425                 if (error) return error;
2426                 PUT_USER(error,cnow.rx, &p_cuser->rx);
2427                 if (error) return error;
2428                 PUT_USER(error,cnow.tx, &p_cuser->tx);
2429                 if (error) return error;
2430                 PUT_USER(error,cnow.frame, &p_cuser->frame);
2431                 if (error) return error;
2432                 PUT_USER(error,cnow.overrun, &p_cuser->overrun);
2433                 if (error) return error;
2434                 PUT_USER(error,cnow.parity, &p_cuser->parity);
2435                 if (error) return error;
2436                 PUT_USER(error,cnow.brk, &p_cuser->brk);
2437                 if (error) return error;
2438                 PUT_USER(error,cnow.buf_overrun, &p_cuser->buf_overrun);
2439                 if (error) return error;
2440                 return 0;
2441         default:
2442                 return -ENOIOCTLCMD;
2443         }
2444         return 0;
2445 }
2446
2447 /* Set new termios settings
2448  *      
2449  * Arguments:
2450  * 
2451  *      tty             pointer to tty structure
2452  *      termios         pointer to buffer to hold returned old termios
2453  */
2454 static void mgslpc_set_termios(struct tty_struct *tty, struct termios *old_termios)
2455 {
2456         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
2457         unsigned long flags;
2458         
2459         if (debug_level >= DEBUG_LEVEL_INFO)
2460                 printk("%s(%d):mgslpc_set_termios %s\n", __FILE__,__LINE__,
2461                         tty->driver->name );
2462         
2463         /* just return if nothing has changed */
2464         if ((tty->termios->c_cflag == old_termios->c_cflag)
2465             && (RELEVANT_IFLAG(tty->termios->c_iflag) 
2466                 == RELEVANT_IFLAG(old_termios->c_iflag)))
2467           return;
2468
2469         mgslpc_change_params(info);
2470
2471         /* Handle transition to B0 status */
2472         if (old_termios->c_cflag & CBAUD &&
2473             !(tty->termios->c_cflag & CBAUD)) {
2474                 info->serial_signals &= ~(SerialSignal_RTS + SerialSignal_DTR);
2475                 spin_lock_irqsave(&info->lock,flags);
2476                 set_signals(info);
2477                 spin_unlock_irqrestore(&info->lock,flags);
2478         }
2479         
2480         /* Handle transition away from B0 status */
2481         if (!(old_termios->c_cflag & CBAUD) &&
2482             tty->termios->c_cflag & CBAUD) {
2483                 info->serial_signals |= SerialSignal_DTR;
2484                 if (!(tty->termios->c_cflag & CRTSCTS) || 
2485                     !test_bit(TTY_THROTTLED, &tty->flags)) {
2486                         info->serial_signals |= SerialSignal_RTS;
2487                 }
2488                 spin_lock_irqsave(&info->lock,flags);
2489                 set_signals(info);
2490                 spin_unlock_irqrestore(&info->lock,flags);
2491         }
2492         
2493         /* Handle turning off CRTSCTS */
2494         if (old_termios->c_cflag & CRTSCTS &&
2495             !(tty->termios->c_cflag & CRTSCTS)) {
2496                 tty->hw_stopped = 0;
2497                 tx_release(tty);
2498         }
2499 }
2500
2501 static void mgslpc_close(struct tty_struct *tty, struct file * filp)
2502 {
2503         MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data;
2504
2505         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_close"))
2506                 return;
2507         
2508         if (debug_level >= DEBUG_LEVEL_INFO)
2509                 printk("%s(%d):mgslpc_close(%s) entry, count=%d\n",
2510                          __FILE__,__LINE__, info->device_name, info->count);
2511                          
2512         if (!info->count)
2513                 return;
2514
2515         if (tty_hung_up_p(filp))
2516                 goto cleanup;
2517                         
2518         if ((tty->count == 1) && (info->count != 1)) {
2519                 /*
2520                  * tty->count is 1 and the tty structure will be freed.
2521                  * info->count should be one in this case.
2522                  * if it's not, correct it so that the port is shutdown.
2523                  */
2524                 printk("mgslpc_close: bad refcount; tty->count is 1, "
2525                        "info->count is %d\n", info->count);
2526                 info->count = 1;
2527         }
2528         
2529         info->count--;
2530         
2531         /* if at least one open remaining, leave hardware active */
2532         if (info->count)
2533                 goto cleanup;
2534         
2535         info->flags |= ASYNC_CLOSING;
2536         
2537         /* set tty->closing to notify line discipline to 
2538          * only process XON/XOFF characters. Only the N_TTY
2539          * discipline appears to use this (ppp does not).
2540          */
2541         tty->closing = 1;
2542         
2543         /* wait for transmit data to clear all layers */
2544         
2545         if (info->closing_wait != ASYNC_CLOSING_WAIT_NONE) {
2546                 if (debug_level >= DEBUG_LEVEL_INFO)
2547                         printk("%s(%d):mgslpc_close(%s) calling tty_wait_until_sent\n",
2548                                  __FILE__,__LINE__, info->device_name );
2549                 tty_wait_until_sent(tty, info->closing_wait);
2550         }
2551                 
2552         if (info->flags & ASYNC_INITIALIZED)
2553                 mgslpc_wait_until_sent(tty, info->timeout);
2554
2555         if (tty->driver->flush_buffer)
2556                 tty->driver->flush_buffer(tty);
2557
2558         ldisc_flush_buffer(tty);
2559                 
2560         shutdown(info);
2561         
2562         tty->closing = 0;
2563         info->tty = NULL;
2564         
2565         if (info->blocked_open) {
2566                 if (info->close_delay) {
2567                         msleep_interruptible(jiffies_to_msecs(info->close_delay));
2568                 }
2569                 wake_up_interruptible(&info->open_wait);
2570         }
2571         
2572         info->flags &= ~(ASYNC_NORMAL_ACTIVE|ASYNC_CLOSING);
2573                          
2574         wake_up_interruptible(&info->close_wait);
2575         
2576 cleanup:                        
2577         if (debug_level >= DEBUG_LEVEL_INFO)
2578                 printk("%s(%d):mgslpc_close(%s) exit, count=%d\n", __FILE__,__LINE__,
2579                         tty->driver->name, info->count);
2580 }
2581
2582 /* Wait until the transmitter is empty.
2583  */
2584 static void mgslpc_wait_until_sent(struct tty_struct *tty, int timeout)
2585 {
2586         MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data;
2587         unsigned long orig_jiffies, char_time;
2588
2589         if (!info )
2590                 return;
2591
2592         if (debug_level >= DEBUG_LEVEL_INFO)
2593                 printk("%s(%d):mgslpc_wait_until_sent(%s) entry\n",
2594                          __FILE__,__LINE__, info->device_name );
2595       
2596         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_wait_until_sent"))
2597                 return;
2598
2599         if (!(info->flags & ASYNC_INITIALIZED))
2600                 goto exit;
2601          
2602         orig_jiffies = jiffies;
2603       
2604         /* Set check interval to 1/5 of estimated time to
2605          * send a character, and make it at least 1. The check
2606          * interval should also be less than the timeout.
2607          * Note: use tight timings here to satisfy the NIST-PCTS.
2608          */ 
2609        
2610         if ( info->params.data_rate ) {
2611                 char_time = info->timeout/(32 * 5);
2612                 if (!char_time)
2613                         char_time++;
2614         } else
2615                 char_time = 1;
2616                 
2617         if (timeout)
2618                 char_time = min_t(unsigned long, char_time, timeout);
2619                 
2620         if (info->params.mode == MGSL_MODE_HDLC) {
2621                 while (info->tx_active) {
2622                         msleep_interruptible(jiffies_to_msecs(char_time));
2623                         if (signal_pending(current))
2624                                 break;
2625                         if (timeout && time_after(jiffies, orig_jiffies + timeout))
2626                                 break;
2627                 }
2628         } else {
2629                 while ((info->tx_count || info->tx_active) &&
2630                         info->tx_enabled) {
2631                         msleep_interruptible(jiffies_to_msecs(char_time));
2632                         if (signal_pending(current))
2633                                 break;
2634                         if (timeout && time_after(jiffies, orig_jiffies + timeout))
2635                                 break;
2636                 }
2637         }
2638       
2639 exit:
2640         if (debug_level >= DEBUG_LEVEL_INFO)
2641                 printk("%s(%d):mgslpc_wait_until_sent(%s) exit\n",
2642                          __FILE__,__LINE__, info->device_name );
2643 }
2644
2645 /* Called by tty_hangup() when a hangup is signaled.
2646  * This is the same as closing all open files for the port.
2647  */
2648 static void mgslpc_hangup(struct tty_struct *tty)
2649 {
2650         MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data;
2651         
2652         if (debug_level >= DEBUG_LEVEL_INFO)
2653                 printk("%s(%d):mgslpc_hangup(%s)\n",
2654                          __FILE__,__LINE__, info->device_name );
2655                          
2656         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_hangup"))
2657                 return;
2658
2659         mgslpc_flush_buffer(tty);
2660         shutdown(info);
2661         
2662         info->count = 0;        
2663         info->flags &= ~ASYNC_NORMAL_ACTIVE;
2664         info->tty = NULL;
2665
2666         wake_up_interruptible(&info->open_wait);
2667 }
2668
2669 /* Block the current process until the specified port
2670  * is ready to be opened.
2671  */
2672 static int block_til_ready(struct tty_struct *tty, struct file *filp,
2673                            MGSLPC_INFO *info)
2674 {
2675         DECLARE_WAITQUEUE(wait, current);
2676         int             retval;
2677         int             do_clocal = 0, extra_count = 0;
2678         unsigned long   flags;
2679         
2680         if (debug_level >= DEBUG_LEVEL_INFO)
2681                 printk("%s(%d):block_til_ready on %s\n",
2682                          __FILE__,__LINE__, tty->driver->name );
2683
2684         if (filp->f_flags & O_NONBLOCK || tty->flags & (1 << TTY_IO_ERROR)){
2685                 /* nonblock mode is set or port is not enabled */
2686                 /* just verify that callout device is not active */
2687                 info->flags |= ASYNC_NORMAL_ACTIVE;
2688                 return 0;
2689         }
2690
2691         if (tty->termios->c_cflag & CLOCAL)
2692                 do_clocal = 1;
2693
2694         /* Wait for carrier detect and the line to become
2695          * free (i.e., not in use by the callout).  While we are in
2696          * this loop, info->count is dropped by one, so that
2697          * mgslpc_close() knows when to free things.  We restore it upon
2698          * exit, either normal or abnormal.
2699          */
2700          
2701         retval = 0;
2702         add_wait_queue(&info->open_wait, &wait);
2703         
2704         if (debug_level >= DEBUG_LEVEL_INFO)
2705                 printk("%s(%d):block_til_ready before block on %s count=%d\n",
2706                          __FILE__,__LINE__, tty->driver->name, info->count );
2707
2708         spin_lock_irqsave(&info->lock, flags);
2709         if (!tty_hung_up_p(filp)) {
2710                 extra_count = 1;
2711                 info->count--;
2712         }
2713         spin_unlock_irqrestore(&info->lock, flags);
2714         info->blocked_open++;
2715         
2716         while (1) {
2717                 if ((tty->termios->c_cflag & CBAUD)) {
2718                         spin_lock_irqsave(&info->lock,flags);
2719                         info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR;
2720                         set_signals(info);
2721                         spin_unlock_irqrestore(&info->lock,flags);
2722                 }
2723                 
2724                 set_current_state(TASK_INTERRUPTIBLE);
2725                 
2726                 if (tty_hung_up_p(filp) || !(info->flags & ASYNC_INITIALIZED)){
2727                         retval = (info->flags & ASYNC_HUP_NOTIFY) ?
2728                                         -EAGAIN : -ERESTARTSYS;
2729                         break;
2730                 }
2731                 
2732                 spin_lock_irqsave(&info->lock,flags);
2733                 get_signals(info);
2734                 spin_unlock_irqrestore(&info->lock,flags);
2735                 
2736                 if (!(info->flags & ASYNC_CLOSING) &&
2737                     (do_clocal || (info->serial_signals & SerialSignal_DCD)) ) {
2738                         break;
2739                 }
2740                         
2741                 if (signal_pending(current)) {
2742                         retval = -ERESTARTSYS;
2743                         break;
2744                 }
2745                 
2746                 if (debug_level >= DEBUG_LEVEL_INFO)
2747                         printk("%s(%d):block_til_ready blocking on %s count=%d\n",
2748                                  __FILE__,__LINE__, tty->driver->name, info->count );
2749                                  
2750                 schedule();
2751         }
2752         
2753         set_current_state(TASK_RUNNING);
2754         remove_wait_queue(&info->open_wait, &wait);
2755         
2756         if (extra_count)
2757                 info->count++;
2758         info->blocked_open--;
2759         
2760         if (debug_level >= DEBUG_LEVEL_INFO)
2761                 printk("%s(%d):block_til_ready after blocking on %s count=%d\n",
2762                          __FILE__,__LINE__, tty->driver->name, info->count );
2763                          
2764         if (!retval)
2765                 info->flags |= ASYNC_NORMAL_ACTIVE;
2766                 
2767         return retval;
2768 }
2769
2770 static int mgslpc_open(struct tty_struct *tty, struct file * filp)
2771 {
2772         MGSLPC_INFO     *info;
2773         int                     retval, line;
2774         unsigned long flags;
2775
2776         /* verify range of specified line number */     
2777         line = tty->index;
2778         if ((line < 0) || (line >= mgslpc_device_count)) {
2779                 printk("%s(%d):mgslpc_open with invalid line #%d.\n",
2780                         __FILE__,__LINE__,line);
2781                 return -ENODEV;
2782         }
2783
2784         /* find the info structure for the specified line */
2785         info = mgslpc_device_list;
2786         while(info && info->line != line)
2787                 info = info->next_device;
2788         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_open"))
2789                 return -ENODEV;
2790         
2791         tty->driver_data = info;
2792         info->tty = tty;
2793                 
2794         if (debug_level >= DEBUG_LEVEL_INFO)
2795                 printk("%s(%d):mgslpc_open(%s), old ref count = %d\n",
2796                          __FILE__,__LINE__,tty->driver->name, info->count);
2797
2798         /* If port is closing, signal caller to try again */
2799         if (tty_hung_up_p(filp) || info->flags & ASYNC_CLOSING){
2800                 if (info->flags & ASYNC_CLOSING)
2801                         interruptible_sleep_on(&info->close_wait);
2802                 retval = ((info->flags & ASYNC_HUP_NOTIFY) ?
2803                         -EAGAIN : -ERESTARTSYS);
2804                 goto cleanup;
2805         }
2806         
2807         info->tty->low_latency = (info->flags & ASYNC_LOW_LATENCY) ? 1 : 0;
2808
2809         spin_lock_irqsave(&info->netlock, flags);
2810         if (info->netcount) {
2811                 retval = -EBUSY;
2812                 spin_unlock_irqrestore(&info->netlock, flags);
2813                 goto cleanup;
2814         }
2815         info->count++;
2816         spin_unlock_irqrestore(&info->netlock, flags);
2817
2818         if (info->count == 1) {
2819                 /* 1st open on this device, init hardware */
2820                 retval = startup(info);
2821                 if (retval < 0)
2822                         goto cleanup;
2823         }
2824
2825         retval = block_til_ready(tty, filp, info);
2826         if (retval) {
2827                 if (debug_level >= DEBUG_LEVEL_INFO)
2828                         printk("%s(%d):block_til_ready(%s) returned %d\n",
2829                                  __FILE__,__LINE__, info->device_name, retval);
2830                 goto cleanup;
2831         }
2832
2833         if (debug_level >= DEBUG_LEVEL_INFO)
2834                 printk("%s(%d):mgslpc_open(%s) success\n",
2835                          __FILE__,__LINE__, info->device_name);
2836         retval = 0;
2837         
2838 cleanup:                        
2839         if (retval) {
2840                 if (tty->count == 1)
2841                         info->tty = NULL; /* tty layer will release tty struct */
2842                 if(info->count)
2843                         info->count--;
2844         }
2845         
2846         return retval;
2847 }
2848
2849 /*
2850  * /proc fs routines....
2851  */
2852
2853 static inline int line_info(char *buf, MGSLPC_INFO *info)
2854 {
2855         char    stat_buf[30];
2856         int     ret;
2857         unsigned long flags;
2858
2859         ret = sprintf(buf, "%s:io:%04X irq:%d",
2860                       info->device_name, info->io_base, info->irq_level);
2861
2862         /* output current serial signal states */
2863         spin_lock_irqsave(&info->lock,flags);
2864         get_signals(info);
2865         spin_unlock_irqrestore(&info->lock,flags);
2866         
2867         stat_buf[0] = 0;
2868         stat_buf[1] = 0;
2869         if (info->serial_signals & SerialSignal_RTS)
2870                 strcat(stat_buf, "|RTS");
2871         if (info->serial_signals & SerialSignal_CTS)
2872                 strcat(stat_buf, "|CTS");
2873         if (info->serial_signals & SerialSignal_DTR)
2874                 strcat(stat_buf, "|DTR");
2875         if (info->serial_signals & SerialSignal_DSR)
2876                 strcat(stat_buf, "|DSR");
2877         if (info->serial_signals & SerialSignal_DCD)
2878                 strcat(stat_buf, "|CD");
2879         if (info->serial_signals & SerialSignal_RI)
2880                 strcat(stat_buf, "|RI");
2881
2882         if (info->params.mode == MGSL_MODE_HDLC) {
2883                 ret += sprintf(buf+ret, " HDLC txok:%d rxok:%d",
2884                               info->icount.txok, info->icount.rxok);
2885                 if (info->icount.txunder)
2886                         ret += sprintf(buf+ret, " txunder:%d", info->icount.txunder);
2887                 if (info->icount.txabort)
2888                         ret += sprintf(buf+ret, " txabort:%d", info->icount.txabort);
2889                 if (info->icount.rxshort)
2890                         ret += sprintf(buf+ret, " rxshort:%d", info->icount.rxshort);   
2891                 if (info->icount.rxlong)
2892                         ret += sprintf(buf+ret, " rxlong:%d", info->icount.rxlong);
2893                 if (info->icount.rxover)
2894                         ret += sprintf(buf+ret, " rxover:%d", info->icount.rxover);
2895                 if (info->icount.rxcrc)
2896                         ret += sprintf(buf+ret, " rxcrc:%d", info->icount.rxcrc);
2897         } else {
2898                 ret += sprintf(buf+ret, " ASYNC tx:%d rx:%d",
2899                               info->icount.tx, info->icount.rx);
2900                 if (info->icount.frame)
2901                         ret += sprintf(buf+ret, " fe:%d", info->icount.frame);
2902                 if (info->icount.parity)
2903                         ret += sprintf(buf+ret, " pe:%d", info->icount.parity);
2904                 if (info->icount.brk)
2905                         ret += sprintf(buf+ret, " brk:%d", info->icount.brk);   
2906                 if (info->icount.overrun)
2907                         ret += sprintf(buf+ret, " oe:%d", info->icount.overrun);
2908         }
2909         
2910         /* Append serial signal status to end */
2911         ret += sprintf(buf+ret, " %s\n", stat_buf+1);
2912         
2913         ret += sprintf(buf+ret, "txactive=%d bh_req=%d bh_run=%d pending_bh=%x\n",
2914                        info->tx_active,info->bh_requested,info->bh_running,
2915                        info->pending_bh);
2916         
2917         return ret;
2918 }
2919
2920 /* Called to print information about devices
2921  */
2922 static int mgslpc_read_proc(char *page, char **start, off_t off, int count,
2923                  int *eof, void *data)
2924 {
2925         int len = 0, l;
2926         off_t   begin = 0;
2927         MGSLPC_INFO *info;
2928         
2929         len += sprintf(page, "synclink driver:%s\n", driver_version);
2930         
2931         info = mgslpc_device_list;
2932         while( info ) {
2933                 l = line_info(page + len, info);
2934                 len += l;
2935                 if (len+begin > off+count)
2936                         goto done;
2937                 if (len+begin < off) {
2938                         begin += len;
2939                         len = 0;
2940                 }
2941                 info = info->next_device;
2942         }
2943
2944         *eof = 1;
2945 done:
2946         if (off >= len+begin)
2947                 return 0;
2948         *start = page + (off-begin);
2949         return ((count < begin+len-off) ? count : begin+len-off);
2950 }
2951
2952 int rx_alloc_buffers(MGSLPC_INFO *info)
2953 {
2954         /* each buffer has header and data */
2955         info->rx_buf_size = sizeof(RXBUF) + info->max_frame_size;
2956
2957         /* calculate total allocation size for 8 buffers */
2958         info->rx_buf_total_size = info->rx_buf_size * 8;
2959
2960         /* limit total allocated memory */
2961         if (info->rx_buf_total_size > 0x10000)
2962                 info->rx_buf_total_size = 0x10000;
2963
2964         /* calculate number of buffers */
2965         info->rx_buf_count = info->rx_buf_total_size / info->rx_buf_size;
2966
2967         info->rx_buf = kmalloc(info->rx_buf_total_size, GFP_KERNEL);
2968         if (info->rx_buf == NULL)
2969                 return -ENOMEM;
2970
2971         rx_reset_buffers(info);
2972         return 0;
2973 }
2974
2975 void rx_free_buffers(MGSLPC_INFO *info)
2976 {
2977         kfree(info->rx_buf);
2978         info->rx_buf = NULL;
2979 }
2980
2981 int claim_resources(MGSLPC_INFO *info)
2982 {
2983         if (rx_alloc_buffers(info) < 0 ) {
2984                 printk( "Cant allocate rx buffer %s\n", info->device_name);
2985                 release_resources(info);
2986                 return -ENODEV;
2987         }       
2988         return 0;
2989 }
2990
2991 void release_resources(MGSLPC_INFO *info)
2992 {
2993         if (debug_level >= DEBUG_LEVEL_INFO)
2994                 printk("release_resources(%s)\n", info->device_name);
2995         rx_free_buffers(info);
2996 }
2997
2998 /* Add the specified device instance data structure to the
2999  * global linked list of devices and increment the device count.
3000  *      
3001  * Arguments:           info    pointer to device instance data
3002  */
3003 void mgslpc_add_device(MGSLPC_INFO *info)
3004 {
3005         info->next_device = NULL;
3006         info->line = mgslpc_device_count;
3007         sprintf(info->device_name,"ttySLP%d",info->line);
3008         
3009         if (info->line < MAX_DEVICE_COUNT) {
3010                 if (maxframe[info->line])
3011                         info->max_frame_size = maxframe[info->line];
3012                 info->dosyncppp = dosyncppp[info->line];
3013         }
3014
3015         mgslpc_device_count++;
3016         
3017         if (!mgslpc_device_list)
3018                 mgslpc_device_list = info;
3019         else {  
3020                 MGSLPC_INFO *current_dev = mgslpc_device_list;
3021                 while( current_dev->next_device )
3022                         current_dev = current_dev->next_device;
3023                 current_dev->next_device = info;
3024         }
3025         
3026         if (info->max_frame_size < 4096)
3027                 info->max_frame_size = 4096;
3028         else if (info->max_frame_size > 65535)
3029                 info->max_frame_size = 65535;
3030         
3031         printk( "SyncLink PC Card %s:IO=%04X IRQ=%d\n",
3032                 info->device_name, info->io_base, info->irq_level);
3033
3034 #ifdef CONFIG_HDLC
3035         hdlcdev_init(info);
3036 #endif
3037 }
3038
3039 void mgslpc_remove_device(MGSLPC_INFO *remove_info)
3040 {
3041         MGSLPC_INFO *info = mgslpc_device_list;
3042         MGSLPC_INFO *last = NULL;
3043
3044         while(info) {
3045                 if (info == remove_info) {
3046                         if (last)
3047                                 last->next_device = info->next_device;
3048                         else
3049                                 mgslpc_device_list = info->next_device;
3050 #ifdef CONFIG_HDLC
3051                         hdlcdev_exit(info);
3052 #endif
3053                         release_resources(info);
3054                         kfree(info);
3055                         mgslpc_device_count--;
3056                         return;
3057                 }
3058                 last = info;
3059                 info = info->next_device;
3060         }
3061 }
3062
3063 static struct pcmcia_device_id mgslpc_ids[] = {
3064         PCMCIA_DEVICE_MANF_CARD(0x02c5, 0x0050),
3065         PCMCIA_DEVICE_NULL
3066 };
3067 MODULE_DEVICE_TABLE(pcmcia, mgslpc_ids);
3068
3069 static struct pcmcia_driver mgslpc_driver = {
3070         .owner          = THIS_MODULE,
3071         .drv            = {
3072                 .name   = "synclink_cs",
3073         },
3074         .attach         = mgslpc_attach,
3075         .event          = mgslpc_event,
3076         .remove         = mgslpc_detach,
3077         .id_table       = mgslpc_ids,
3078         .suspend        = mgslpc_suspend,
3079         .resume         = mgslpc_resume,
3080 };
3081
3082 static struct tty_operations mgslpc_ops = {
3083         .open = mgslpc_open,
3084         .close = mgslpc_close,
3085         .write = mgslpc_write,
3086         .put_char = mgslpc_put_char,
3087         .flush_chars = mgslpc_flush_chars,
3088         .write_room = mgslpc_write_room,
3089         .chars_in_buffer = mgslpc_chars_in_buffer,
3090         .flush_buffer = mgslpc_flush_buffer,
3091         .ioctl = mgslpc_ioctl,
3092         .throttle = mgslpc_throttle,
3093         .unthrottle = mgslpc_unthrottle,
3094         .send_xchar = mgslpc_send_xchar,
3095         .break_ctl = mgslpc_break,
3096         .wait_until_sent = mgslpc_wait_until_sent,
3097         .read_proc = mgslpc_read_proc,
3098         .set_termios = mgslpc_set_termios,
3099         .stop = tx_pause,
3100         .start = tx_release,
3101         .hangup = mgslpc_hangup,
3102         .tiocmget = tiocmget,
3103         .tiocmset = tiocmset,
3104 };
3105
3106 static void synclink_cs_cleanup(void)
3107 {
3108         int rc;
3109
3110         printk("Unloading %s: version %s\n", driver_name, driver_version);
3111
3112         while(mgslpc_device_list)
3113                 mgslpc_remove_device(mgslpc_device_list);
3114
3115         if (serial_driver) {
3116                 if ((rc = tty_unregister_driver(serial_driver)))
3117                         printk("%s(%d) failed to unregister tty driver err=%d\n",
3118                                __FILE__,__LINE__,rc);
3119                 put_tty_driver(serial_driver);
3120         }
3121
3122         pcmcia_unregister_driver(&mgslpc_driver);
3123 }
3124
3125 static int __init synclink_cs_init(void)
3126 {
3127     int rc;
3128
3129     if (break_on_load) {
3130             mgslpc_get_text_ptr();
3131             BREAKPOINT();
3132     }
3133
3134     printk("%s %s\n", driver_name, driver_version);
3135
3136     if ((rc = pcmcia_register_driver(&mgslpc_driver)) < 0)
3137             return rc;
3138
3139     serial_driver = alloc_tty_driver(MAX_DEVICE_COUNT);
3140     if (!serial_driver) {
3141             rc = -ENOMEM;
3142             goto error;
3143     }
3144
3145     /* Initialize the tty_driver structure */
3146         
3147     serial_driver->owner = THIS_MODULE;
3148     serial_driver->driver_name = "synclink_cs";
3149     serial_driver->name = "ttySLP";
3150     serial_driver->major = ttymajor;
3151     serial_driver->minor_start = 64;
3152     serial_driver->type = TTY_DRIVER_TYPE_SERIAL;
3153     serial_driver->subtype = SERIAL_TYPE_NORMAL;
3154     serial_driver->init_termios = tty_std_termios;
3155     serial_driver->init_termios.c_cflag =
3156             B9600 | CS8 | CREAD | HUPCL | CLOCAL;
3157     serial_driver->flags = TTY_DRIVER_REAL_RAW;
3158     tty_set_operations(serial_driver, &mgslpc_ops);
3159
3160     if ((rc = tty_register_driver(serial_driver)) < 0) {
3161             printk("%s(%d):Couldn't register serial driver\n",
3162                    __FILE__,__LINE__);
3163             put_tty_driver(serial_driver);
3164             serial_driver = NULL;
3165             goto error;
3166     }
3167                         
3168     printk("%s %s, tty major#%d\n",
3169            driver_name, driver_version,
3170            serial_driver->major);
3171         
3172     return 0;
3173
3174 error:
3175     synclink_cs_cleanup();
3176     return rc;
3177 }
3178
3179 static void __exit synclink_cs_exit(void) 
3180 {
3181         synclink_cs_cleanup();
3182 }
3183
3184 module_init(synclink_cs_init);
3185 module_exit(synclink_cs_exit);
3186
3187 static void mgslpc_set_rate(MGSLPC_INFO *info, unsigned char channel, unsigned int rate)
3188 {
3189         unsigned int M, N;
3190         unsigned char val;
3191
3192         /* note:standard BRG mode is broken in V3.2 chip 
3193          * so enhanced mode is always used 
3194          */
3195
3196         if (rate) {
3197                 N = 3686400 / rate;
3198                 if (!N)
3199                         N = 1;
3200                 N >>= 1;
3201                 for (M = 1; N > 64 && M < 16; M++)
3202                         N >>= 1;
3203                 N--;
3204
3205                 /* BGR[5..0] = N
3206                  * BGR[9..6] = M
3207                  * BGR[7..0] contained in BGR register
3208                  * BGR[9..8] contained in CCR2[7..6]
3209                  * divisor = (N+1)*2^M
3210                  *
3211                  * Note: M *must* not be zero (causes asymetric duty cycle)
3212                  */ 
3213                 write_reg(info, (unsigned char) (channel + BGR),
3214                                   (unsigned char) ((M << 6) + N));
3215                 val = read_reg(info, (unsigned char) (channel + CCR2)) & 0x3f;
3216                 val |= ((M << 4) & 0xc0);
3217                 write_reg(info, (unsigned char) (channel + CCR2), val);
3218         }
3219 }
3220
3221 /* Enabled the AUX clock output at the specified frequency.
3222  */
3223 static void enable_auxclk(MGSLPC_INFO *info)
3224 {
3225         unsigned char val;
3226         
3227         /* MODE
3228          *
3229          * 07..06  MDS[1..0] 10 = transparent HDLC mode
3230          * 05      ADM Address Mode, 0 = no addr recognition
3231          * 04      TMD Timer Mode, 0 = external
3232          * 03      RAC Receiver Active, 0 = inactive
3233          * 02      RTS 0=RTS active during xmit, 1=RTS always active
3234          * 01      TRS Timer Resolution, 1=512
3235          * 00      TLP Test Loop, 0 = no loop
3236          *
3237          * 1000 0010
3238          */ 
3239         val = 0x82;
3240         
3241         /* channel B RTS is used to enable AUXCLK driver on SP505 */ 
3242         if (info->params.mode == MGSL_MODE_HDLC && info->params.clock_speed)
3243                 val |= BIT2;
3244         write_reg(info, CHB + MODE, val);
3245         
3246         /* CCR0
3247          *
3248          * 07      PU Power Up, 1=active, 0=power down
3249          * 06      MCE Master Clock Enable, 1=enabled
3250          * 05      Reserved, 0
3251          * 04..02  SC[2..0] Encoding
3252          * 01..00  SM[1..0] Serial Mode, 00=HDLC
3253          *
3254          * 11000000
3255          */ 
3256         write_reg(info, CHB + CCR0, 0xc0);
3257         
3258         /* CCR1
3259          *
3260          * 07      SFLG Shared Flag, 0 = disable shared flags
3261          * 06      GALP Go Active On Loop, 0 = not used
3262          * 05      GLP Go On Loop, 0 = not used
3263          * 04      ODS Output Driver Select, 1=TxD is push-pull output
3264          * 03      ITF Interframe Time Fill, 0=mark, 1=flag
3265          * 02..00  CM[2..0] Clock Mode
3266          *
3267          * 0001 0111
3268          */ 
3269         write_reg(info, CHB + CCR1, 0x17);
3270         
3271         /* CCR2 (Channel B)
3272          *
3273          * 07..06  BGR[9..8] Baud rate bits 9..8
3274          * 05      BDF Baud rate divisor factor, 0=1, 1=BGR value
3275          * 04      SSEL Clock source select, 1=submode b
3276          * 03      TOE 0=TxCLK is input, 1=TxCLK is output
3277          * 02      RWX Read/Write Exchange 0=disabled
3278          * 01      C32, CRC select, 0=CRC-16, 1=CRC-32
3279          * 00      DIV, data inversion 0=disabled, 1=enabled
3280          *
3281          * 0011 1000
3282          */ 
3283         if (info->params.mode == MGSL_MODE_HDLC && info->params.clock_speed)
3284                 write_reg(info, CHB + CCR2, 0x38);
3285         else
3286                 write_reg(info, CHB + CCR2, 0x30);
3287         
3288         /* CCR4
3289          *
3290          * 07      MCK4 Master Clock Divide by 4, 1=enabled
3291          * 06      EBRG Enhanced Baud Rate Generator Mode, 1=enabled
3292          * 05      TST1 Test Pin, 0=normal operation
3293          * 04      ICD Ivert Carrier Detect, 1=enabled (active low)
3294          * 03..02  Reserved, must be 0
3295          * 01..00  RFT[1..0] RxFIFO Threshold 00=32 bytes
3296          *
3297          * 0101 0000
3298          */ 
3299         write_reg(info, CHB + CCR4, 0x50);
3300         
3301         /* if auxclk not enabled, set internal BRG so
3302          * CTS transitions can be detected (requires TxC)
3303          */ 
3304         if (info->params.mode == MGSL_MODE_HDLC && info->params.clock_speed)
3305                 mgslpc_set_rate(info, CHB, info->params.clock_speed);
3306         else
3307                 mgslpc_set_rate(info, CHB, 921600);
3308 }
3309
3310 static void loopback_enable(MGSLPC_INFO *info) 
3311 {
3312         unsigned char val;
3313         
3314         /* CCR1:02..00  CM[2..0] Clock Mode = 111 (clock mode 7) */ 
3315         val = read_reg(info, CHA + CCR1) | (BIT2 + BIT1 + BIT0);
3316         write_reg(info, CHA + CCR1, val);
3317         
3318         /* CCR2:04 SSEL Clock source select, 1=submode b */ 
3319         val = read_reg(info, CHA + CCR2) | (BIT4 + BIT5);
3320         write_reg(info, CHA + CCR2, val);
3321         
3322         /* set LinkSpeed if available, otherwise default to 2Mbps */ 
3323         if (info->params.clock_speed)
3324                 mgslpc_set_rate(info, CHA, info->params.clock_speed);
3325         else
3326                 mgslpc_set_rate(info, CHA, 1843200);
3327         
3328         /* MODE:00 TLP Test Loop, 1=loopback enabled */ 
3329         val = read_reg(info, CHA + MODE) | BIT0;
3330         write_reg(info, CHA + MODE, val);
3331 }
3332
3333 void hdlc_mode(MGSLPC_INFO *info)
3334 {
3335         unsigned char val;
3336         unsigned char clkmode, clksubmode;
3337
3338         /* disable all interrupts */ 
3339         irq_disable(info, CHA, 0xffff);
3340         irq_disable(info, CHB, 0xffff);
3341         port_irq_disable(info, 0xff);
3342         
3343         /* assume clock mode 0a, rcv=RxC xmt=TxC */ 
3344         clkmode = clksubmode = 0;
3345         if (info->params.flags & HDLC_FLAG_RXC_DPLL
3346             && info->params.flags & HDLC_FLAG_TXC_DPLL) {
3347                 /* clock mode 7a, rcv = DPLL, xmt = DPLL */ 
3348                 clkmode = 7;
3349         } else if (info->params.flags & HDLC_FLAG_RXC_BRG
3350                  && info->params.flags & HDLC_FLAG_TXC_BRG) {
3351                 /* clock mode 7b, rcv = BRG, xmt = BRG */ 
3352                 clkmode = 7;
3353                 clksubmode = 1;
3354         } else if (info->params.flags & HDLC_FLAG_RXC_DPLL) {
3355                 if (info->params.flags & HDLC_FLAG_TXC_BRG) {
3356                         /* clock mode 6b, rcv = DPLL, xmt = BRG/16 */ 
3357                         clkmode = 6;
3358                         clksubmode = 1;
3359                 } else {
3360                         /* clock mode 6a, rcv = DPLL, xmt = TxC */ 
3361                         clkmode = 6;
3362                 }
3363         } else if (info->params.flags & HDLC_FLAG_TXC_BRG) {
3364                 /* clock mode 0b, rcv = RxC, xmt = BRG */ 
3365                 clksubmode = 1;
3366         }
3367         
3368         /* MODE
3369          *
3370          * 07..06  MDS[1..0] 10 = transparent HDLC mode
3371          * 05      ADM Address Mode, 0 = no addr recognition
3372          * 04      TMD Timer Mode, 0 = external
3373          * 03      RAC Receiver Active, 0 = inactive
3374          * 02      RTS 0=RTS active during xmit, 1=RTS always active
3375          * 01      TRS Timer Resolution, 1=512
3376          * 00      TLP Test Loop, 0 = no loop
3377          *
3378          * 1000 0010
3379          */ 
3380         val = 0x82;
3381         if (info->params.loopback)
3382                 val |= BIT0;
3383         
3384         /* preserve RTS state */ 
3385         if (info->serial_signals & SerialSignal_RTS)
3386                 val |= BIT2;
3387         write_reg(info, CHA + MODE, val);
3388         
3389         /* CCR0
3390          *
3391          * 07      PU Power Up, 1=active, 0=power down
3392          * 06      MCE Master Clock Enable, 1=enabled
3393          * 05      Reserved, 0
3394          * 04..02  SC[2..0] Encoding
3395          * 01..00  SM[1..0] Serial Mode, 00=HDLC
3396          *
3397          * 11000000
3398          */ 
3399         val = 0xc0;
3400         switch (info->params.encoding)
3401         {
3402         case HDLC_ENCODING_NRZI:
3403                 val |= BIT3;
3404                 break;
3405         case HDLC_ENCODING_BIPHASE_SPACE:
3406                 val |= BIT4;
3407                 break;          // FM0
3408         case HDLC_ENCODING_BIPHASE_MARK:
3409                 val |= BIT4 + BIT2;
3410                 break;          // FM1
3411         case HDLC_ENCODING_BIPHASE_LEVEL:
3412                 val |= BIT4 + BIT3;
3413                 break;          // Manchester
3414         }
3415         write_reg(info, CHA + CCR0, val);
3416         
3417         /* CCR1
3418          *
3419          * 07      SFLG Shared Flag, 0 = disable shared flags
3420          * 06      GALP Go Active On Loop, 0 = not used
3421          * 05      GLP Go On Loop, 0 = not used
3422          * 04      ODS Output Driver Select, 1=TxD is push-pull output
3423          * 03      ITF Interframe Time Fill, 0=mark, 1=flag
3424          * 02..00  CM[2..0] Clock Mode
3425          *
3426          * 0001 0000
3427          */ 
3428         val = 0x10 + clkmode;
3429         write_reg(info, CHA + CCR1, val);
3430         
3431         /* CCR2
3432          *
3433          * 07..06  BGR[9..8] Baud rate bits 9..8
3434          * 05      BDF Baud rate divisor factor, 0=1, 1=BGR value
3435          * 04      SSEL Clock source select, 1=submode b
3436          * 03      TOE 0=TxCLK is input, 0=TxCLK is input
3437          * 02      RWX Read/Write Exchange 0=disabled
3438          * 01      C32, CRC select, 0=CRC-16, 1=CRC-32
3439          * 00      DIV, data inversion 0=disabled, 1=enabled
3440          *
3441          * 0000 0000
3442          */ 
3443         val = 0x00;
3444         if (clkmode == 2 || clkmode == 3 || clkmode == 6
3445             || clkmode == 7 || (clkmode == 0 && clksubmode == 1))
3446                 val |= BIT5;
3447         if (clksubmode)
3448                 val |= BIT4;
3449         if (info->params.crc_type == HDLC_CRC_32_CCITT)
3450                 val |= BIT1;
3451         if (info->params.encoding == HDLC_ENCODING_NRZB)
3452                 val |= BIT0;
3453         write_reg(info, CHA + CCR2, val);
3454         
3455         /* CCR3
3456          *
3457          * 07..06  PRE[1..0] Preamble count 00=1, 01=2, 10=4, 11=8
3458          * 05      EPT Enable preamble transmission, 1=enabled
3459          * 04      RADD Receive address pushed to FIFO, 0=disabled
3460          * 03      CRL CRC Reset Level, 0=FFFF
3461          * 02      RCRC Rx CRC 0=On 1=Off
3462          * 01      TCRC Tx CRC 0=On 1=Off
3463          * 00      PSD DPLL Phase Shift Disable
3464          *
3465          * 0000 0000
3466          */ 
3467         val = 0x00;
3468         if (info->params.crc_type == HDLC_CRC_NONE)
3469                 val |= BIT2 + BIT1;
3470         if (info->params.preamble != HDLC_PREAMBLE_PATTERN_NONE)
3471                 val |= BIT5;
3472         switch (info->params.preamble_length)
3473         {
3474         case HDLC_PREAMBLE_LENGTH_16BITS:
3475                 val |= BIT6;
3476                 break;
3477         case HDLC_PREAMBLE_LENGTH_32BITS:
3478                 val |= BIT6;
3479                 break;
3480         case HDLC_PREAMBLE_LENGTH_64BITS:
3481                 val |= BIT7 + BIT6;
3482                 break;
3483         }
3484         write_reg(info, CHA + CCR3, val);
3485         
3486         /* PRE - Preamble pattern */ 
3487         val = 0;
3488         switch (info->params.preamble)
3489         {
3490         case HDLC_PREAMBLE_PATTERN_FLAGS: val = 0x7e; break;
3491         case HDLC_PREAMBLE_PATTERN_10:    val = 0xaa; break;
3492         case HDLC_PREAMBLE_PATTERN_01:    val = 0x55; break;
3493         case HDLC_PREAMBLE_PATTERN_ONES:  val = 0xff; break;
3494         }
3495         write_reg(info, CHA + PRE, val);
3496         
3497         /* CCR4
3498          *
3499          * 07      MCK4 Master Clock Divide by 4, 1=enabled
3500          * 06      EBRG Enhanced Baud Rate Generator Mode, 1=enabled
3501          * 05      TST1 Test Pin, 0=normal operation
3502          * 04      ICD Ivert Carrier Detect, 1=enabled (active low)
3503          * 03..02  Reserved, must be 0
3504          * 01..00  RFT[1..0] RxFIFO Threshold 00=32 bytes
3505          *
3506          * 0101 0000
3507          */ 
3508         val = 0x50;
3509         write_reg(info, CHA + CCR4, val);
3510         if (info->params.flags & HDLC_FLAG_RXC_DPLL)
3511                 mgslpc_set_rate(info, CHA, info->params.clock_speed * 16);
3512         else
3513                 mgslpc_set_rate(info, CHA, info->params.clock_speed);
3514         
3515         /* RLCR Receive length check register
3516          *
3517          * 7     1=enable receive length check
3518          * 6..0  Max frame length = (RL + 1) * 32
3519          */ 
3520         write_reg(info, CHA + RLCR, 0);
3521         
3522         /* XBCH Transmit Byte Count High
3523          *
3524          * 07      DMA mode, 0 = interrupt driven
3525          * 06      NRM, 0=ABM (ignored)
3526          * 05      CAS Carrier Auto Start
3527          * 04      XC Transmit Continuously (ignored)
3528          * 03..00  XBC[10..8] Transmit byte count bits 10..8
3529          *
3530          * 0000 0000
3531          */ 
3532         val = 0x00;
3533         if (info->params.flags & HDLC_FLAG_AUTO_DCD)
3534                 val |= BIT5;
3535         write_reg(info, CHA + XBCH, val);
3536         enable_auxclk(info);
3537         if (info->params.loopback || info->testing_irq)
3538                 loopback_enable(info);
3539         if (info->params.flags & HDLC_FLAG_AUTO_CTS)
3540         {
3541                 irq_enable(info, CHB, IRQ_CTS);
3542                 /* PVR[3] 1=AUTO CTS active */ 
3543                 set_reg_bits(info, CHA + PVR, BIT3);
3544         } else
3545                 clear_reg_bits(info, CHA + PVR, BIT3);
3546
3547         irq_enable(info, CHA,
3548                          IRQ_RXEOM + IRQ_RXFIFO + IRQ_ALLSENT +
3549                          IRQ_UNDERRUN + IRQ_TXFIFO);
3550         issue_command(info, CHA, CMD_TXRESET + CMD_RXRESET);
3551         wait_command_complete(info, CHA);
3552         read_reg16(info, CHA + ISR);    /* clear pending IRQs */
3553         
3554         /* Master clock mode enabled above to allow reset commands
3555          * to complete even if no data clocks are present.
3556          *
3557          * Disable master clock mode for normal communications because
3558          * V3.2 of the ESCC2 has a bug that prevents the transmit all sent
3559          * IRQ when in master clock mode.
3560          *
3561          * Leave master clock mode enabled for IRQ test because the
3562          * timer IRQ used by the test can only happen in master clock mode.
3563          */ 
3564         if (!info->testing_irq)
3565                 clear_reg_bits(info, CHA + CCR0, BIT6);
3566
3567         tx_set_idle(info);
3568
3569         tx_stop(info);
3570         rx_stop(info);
3571 }
3572
3573 void rx_stop(MGSLPC_INFO *info)
3574 {
3575         if (debug_level >= DEBUG_LEVEL_ISR)
3576                 printk("%s(%d):rx_stop(%s)\n",
3577                          __FILE__,__LINE__, info->device_name );
3578                          
3579         /* MODE:03 RAC Receiver Active, 0=inactive */ 
3580         clear_reg_bits(info, CHA + MODE, BIT3);
3581
3582         info->rx_enabled = 0;
3583         info->rx_overflow = 0;
3584 }
3585
3586 void rx_start(MGSLPC_INFO *info)
3587 {
3588         if (debug_level >= DEBUG_LEVEL_ISR)
3589                 printk("%s(%d):rx_start(%s)\n",
3590                          __FILE__,__LINE__, info->device_name );
3591
3592         rx_reset_buffers(info);
3593         info->rx_enabled = 0;
3594         info->rx_overflow = 0;
3595
3596         /* MODE:03 RAC Receiver Active, 1=active */ 
3597         set_reg_bits(info, CHA + MODE, BIT3);
3598
3599         info->rx_enabled = 1;
3600 }
3601
3602 void tx_start(MGSLPC_INFO *info)
3603 {
3604         if (debug_level >= DEBUG_LEVEL_ISR)
3605                 printk("%s(%d):tx_start(%s)\n",
3606                          __FILE__,__LINE__, info->device_name );
3607                          
3608         if (info->tx_count) {
3609                 /* If auto RTS enabled and RTS is inactive, then assert */
3610                 /* RTS and set a flag indicating that the driver should */
3611                 /* negate RTS when the transmission completes. */
3612                 info->drop_rts_on_tx_done = 0;
3613
3614                 if (info->params.flags & HDLC_FLAG_AUTO_RTS) {
3615                         get_signals(info);
3616                         if (!(info->serial_signals & SerialSignal_RTS)) {
3617                                 info->serial_signals |= SerialSignal_RTS;
3618                                 set_signals(info);
3619                                 info->drop_rts_on_tx_done = 1;
3620                         }
3621                 }
3622
3623                 if (info->params.mode == MGSL_MODE_ASYNC) {
3624                         if (!info->tx_active) {
3625                                 info->tx_active = 1;
3626                                 tx_ready(info);
3627                         }
3628                 } else {
3629                         info->tx_active = 1;
3630                         tx_ready(info);
3631                         info->tx_timer.expires = jiffies + msecs_to_jiffies(5000);
3632                         add_timer(&info->tx_timer);     
3633                 }
3634         }
3635
3636         if (!info->tx_enabled)
3637                 info->tx_enabled = 1;
3638 }
3639
3640 void tx_stop(MGSLPC_INFO *info)
3641 {
3642         if (debug_level >= DEBUG_LEVEL_ISR)
3643                 printk("%s(%d):tx_stop(%s)\n",
3644                          __FILE__,__LINE__, info->device_name );
3645                          
3646         del_timer(&info->tx_timer);     
3647
3648         info->tx_enabled = 0;
3649         info->tx_active  = 0;
3650 }
3651
3652 /* Reset the adapter to a known state and prepare it for further use.
3653  */
3654 void reset_device(MGSLPC_INFO *info)
3655 {
3656         /* power up both channels (set BIT7) */ 
3657         write_reg(info, CHA + CCR0, 0x80);
3658         write_reg(info, CHB + CCR0, 0x80);
3659         write_reg(info, CHA + MODE, 0);
3660         write_reg(info, CHB + MODE, 0);
3661         
3662         /* disable all interrupts */ 
3663         irq_disable(info, CHA, 0xffff);
3664         irq_disable(info, CHB, 0xffff);
3665         port_irq_disable(info, 0xff);
3666         
3667         /* PCR Port Configuration Register
3668          *
3669          * 07..04  DEC[3..0] Serial I/F select outputs
3670          * 03      output, 1=AUTO CTS control enabled
3671          * 02      RI Ring Indicator input 0=active
3672          * 01      DSR input 0=active
3673          * 00      DTR output 0=active
3674          *
3675          * 0000 0110
3676          */ 
3677         write_reg(info, PCR, 0x06);
3678         
3679         /* PVR Port Value Register
3680          *
3681          * 07..04  DEC[3..0] Serial I/F select (0000=disabled)
3682          * 03      AUTO CTS output 1=enabled
3683          * 02      RI Ring Indicator input
3684          * 01      DSR input
3685          * 00      DTR output (1=inactive)
3686          *
3687          * 0000 0001
3688          */
3689 //      write_reg(info, PVR, PVR_DTR);
3690         
3691         /* IPC Interrupt Port Configuration
3692          *
3693          * 07      VIS 1=Masked interrupts visible
3694          * 06..05  Reserved, 0
3695          * 04..03  SLA Slave address, 00 ignored
3696          * 02      CASM Cascading Mode, 1=daisy chain
3697          * 01..00  IC[1..0] Interrupt Config, 01=push-pull output, active low
3698          *
3699          * 0000 0101
3700          */ 
3701         write_reg(info, IPC, 0x05);
3702 }
3703
3704 void async_mode(MGSLPC_INFO *info)
3705 {
3706         unsigned char val;
3707
3708         /* disable all interrupts */ 
3709         irq_disable(info, CHA, 0xffff);
3710         irq_disable(info, CHB, 0xffff);
3711         port_irq_disable(info, 0xff);
3712         
3713         /* MODE
3714          *
3715          * 07      Reserved, 0
3716          * 06      FRTS RTS State, 0=active
3717          * 05      FCTS Flow Control on CTS
3718          * 04      FLON Flow Control Enable
3719          * 03      RAC Receiver Active, 0 = inactive
3720          * 02      RTS 0=Auto RTS, 1=manual RTS
3721          * 01      TRS Timer Resolution, 1=512
3722          * 00      TLP Test Loop, 0 = no loop
3723          *
3724          * 0000 0110
3725          */ 
3726         val = 0x06;
3727         if (info->params.loopback)
3728                 val |= BIT0;
3729         
3730         /* preserve RTS state */ 
3731         if (!(info->serial_signals & SerialSignal_RTS))
3732                 val |= BIT6;
3733         write_reg(info, CHA + MODE, val);
3734         
3735         /* CCR0
3736          *
3737          * 07      PU Power Up, 1=active, 0=power down
3738          * 06      MCE Master Clock Enable, 1=enabled
3739          * 05      Reserved, 0
3740          * 04..02  SC[2..0] Encoding, 000=NRZ
3741          * 01..00  SM[1..0] Serial Mode, 11=Async
3742          *
3743          * 1000 0011
3744          */ 
3745         write_reg(info, CHA + CCR0, 0x83);
3746         
3747         /* CCR1
3748          *
3749          * 07..05  Reserved, 0
3750          * 04      ODS Output Driver Select, 1=TxD is push-pull output
3751          * 03      BCR Bit Clock Rate, 1=16x
3752          * 02..00  CM[2..0] Clock Mode, 111=BRG
3753          *
3754          * 0001 1111
3755          */ 
3756         write_reg(info, CHA + CCR1, 0x1f);
3757         
3758         /* CCR2 (channel A)
3759          *
3760          * 07..06  BGR[9..8] Baud rate bits 9..8
3761          * 05      BDF Baud rate divisor factor, 0=1, 1=BGR value
3762          * 04      SSEL Clock source select, 1=submode b
3763          * 03      TOE 0=TxCLK is input, 0=TxCLK is input
3764          * 02      RWX Read/Write Exchange 0=disabled
3765          * 01      Reserved, 0
3766          * 00      DIV, data inversion 0=disabled, 1=enabled
3767          *
3768          * 0001 0000
3769          */ 
3770         write_reg(info, CHA + CCR2, 0x10);
3771         
3772         /* CCR3
3773          *
3774          * 07..01  Reserved, 0
3775          * 00      PSD DPLL Phase Shift Disable
3776          *
3777          * 0000 0000
3778          */ 
3779         write_reg(info, CHA + CCR3, 0);
3780         
3781         /* CCR4
3782          *
3783          * 07      MCK4 Master Clock Divide by 4, 1=enabled
3784          * 06      EBRG Enhanced Baud Rate Generator Mode, 1=enabled
3785          * 05      TST1 Test Pin, 0=normal operation
3786          * 04      ICD Ivert Carrier Detect, 1=enabled (active low)
3787          * 03..00  Reserved, must be 0
3788          *
3789          * 0101 0000
3790          */ 
3791         write_reg(info, CHA + CCR4, 0x50);
3792         mgslpc_set_rate(info, CHA, info->params.data_rate * 16);
3793         
3794         /* DAFO Data Format
3795          *
3796          * 07      Reserved, 0
3797          * 06      XBRK transmit break, 0=normal operation
3798          * 05      Stop bits (0=1, 1=2)
3799          * 04..03  PAR[1..0] Parity (01=odd, 10=even)
3800          * 02      PAREN Parity Enable
3801          * 01..00  CHL[1..0] Character Length (00=8, 01=7)
3802          *
3803          */ 
3804         val = 0x00;
3805         if (info->params.data_bits != 8)
3806                 val |= BIT0;    /* 7 bits */
3807         if (info->params.stop_bits != 1)
3808                 val |= BIT5;
3809         if (info->params.parity != ASYNC_PARITY_NONE)
3810         {
3811                 val |= BIT2;    /* Parity enable */
3812                 if (info->params.parity == ASYNC_PARITY_ODD)
3813                         val |= BIT3;
3814                 else
3815                         val |= BIT4;
3816         }
3817         write_reg(info, CHA + DAFO, val);
3818         
3819         /* RFC Rx FIFO Control
3820          *
3821          * 07      Reserved, 0
3822          * 06      DPS, 1=parity bit not stored in data byte
3823          * 05      DXS, 0=all data stored in FIFO (including XON/XOFF)
3824          * 04      RFDF Rx FIFO Data Format, 1=status byte stored in FIFO
3825          * 03..02  RFTH[1..0], rx threshold, 11=16 status + 16 data byte
3826          * 01      Reserved, 0
3827          * 00      TCDE Terminate Char Detect Enable, 0=disabled
3828          *
3829          * 0101 1100
3830          */ 
3831         write_reg(info, CHA + RFC, 0x5c);
3832         
3833         /* RLCR Receive length check register
3834          *
3835          * Max frame length = (RL + 1) * 32
3836          */ 
3837         write_reg(info, CHA + RLCR, 0);
3838         
3839         /* XBCH Transmit Byte Count High
3840          *
3841          * 07      DMA mode, 0 = interrupt driven
3842          * 06      NRM, 0=ABM (ignored)
3843          * 05      CAS Carrier Auto Start
3844          * 04      XC Transmit Continuously (ignored)
3845          * 03..00  XBC[10..8] Transmit byte count bits 10..8
3846          *
3847          * 0000 0000
3848          */ 
3849         val = 0x00;
3850         if (info->params.flags & HDLC_FLAG_AUTO_DCD)
3851                 val |= BIT5;
3852         write_reg(info, CHA + XBCH, val);
3853         if (info->params.flags & HDLC_FLAG_AUTO_CTS)
3854                 irq_enable(info, CHA, IRQ_CTS);
3855         
3856         /* MODE:03 RAC Receiver Active, 1=active */ 
3857         set_reg_bits(info, CHA + MODE, BIT3);
3858         enable_auxclk(info);
3859         if (info->params.flags & HDLC_FLAG_AUTO_CTS) {
3860                 irq_enable(info, CHB, IRQ_CTS);
3861                 /* PVR[3] 1=AUTO CTS active */ 
3862                 set_reg_bits(info, CHA + PVR, BIT3);
3863         } else
3864                 clear_reg_bits(info, CHA + PVR, BIT3);
3865         irq_enable(info, CHA,
3866                           IRQ_RXEOM + IRQ_RXFIFO + IRQ_BREAK_ON + IRQ_RXTIME +
3867                           IRQ_ALLSENT + IRQ_TXFIFO);
3868         issue_command(info, CHA, CMD_TXRESET + CMD_RXRESET);
3869         wait_command_complete(info, CHA);
3870         read_reg16(info, CHA + ISR);    /* clear pending IRQs */
3871 }
3872
3873 /* Set the HDLC idle mode for the transmitter.
3874  */
3875 void tx_set_idle(MGSLPC_INFO *info)
3876 {
3877         /* Note: ESCC2 only supports flags and one idle modes */ 
3878         if (info->idle_mode == HDLC_TXIDLE_FLAGS)
3879                 set_reg_bits(info, CHA + CCR1, BIT3);
3880         else
3881                 clear_reg_bits(info, CHA + CCR1, BIT3);
3882 }
3883
3884 /* get state of the V24 status (input) signals.
3885  */
3886 void get_signals(MGSLPC_INFO *info)
3887 {
3888         unsigned char status = 0;
3889         
3890         /* preserve DTR and RTS */ 
3891         info->serial_signals &= SerialSignal_DTR + SerialSignal_RTS;
3892
3893         if (read_reg(info, CHB + VSTR) & BIT7)
3894                 info->serial_signals |= SerialSignal_DCD;
3895         if (read_reg(info, CHB + STAR) & BIT1)
3896                 info->serial_signals |= SerialSignal_CTS;
3897
3898         status = read_reg(info, CHA + PVR);
3899         if (!(status & PVR_RI))
3900                 info->serial_signals |= SerialSignal_RI;
3901         if (!(status & PVR_DSR))
3902                 info->serial_signals |= SerialSignal_DSR;
3903 }
3904
3905 /* Set the state of DTR and RTS based on contents of
3906  * serial_signals member of device extension.
3907  */
3908 void set_signals(MGSLPC_INFO *info)
3909 {
3910         unsigned char val;
3911
3912         val = read_reg(info, CHA + MODE);
3913         if (info->params.mode == MGSL_MODE_ASYNC) {
3914                 if (info->serial_signals & SerialSignal_RTS)
3915                         val &= ~BIT6;
3916                 else
3917                         val |= BIT6;
3918         } else {
3919                 if (info->serial_signals & SerialSignal_RTS)
3920                         val |= BIT2;
3921                 else
3922                         val &= ~BIT2;
3923         }
3924         write_reg(info, CHA + MODE, val);
3925
3926         if (info->serial_signals & SerialSignal_DTR)
3927                 clear_reg_bits(info, CHA + PVR, PVR_DTR);
3928         else
3929                 set_reg_bits(info, CHA + PVR, PVR_DTR);
3930 }
3931
3932 void rx_reset_buffers(MGSLPC_INFO *info)
3933 {
3934         RXBUF *buf;
3935         int i;
3936
3937         info->rx_put = 0;
3938         info->rx_get = 0;
3939         info->rx_frame_count = 0;
3940         for (i=0 ; i < info->rx_buf_count ; i++) {
3941                 buf = (RXBUF*)(info->rx_buf + (i * info->rx_buf_size));
3942                 buf->status = buf->count = 0;
3943         }
3944 }
3945
3946 /* Attempt to return a received HDLC frame
3947  * Only frames received without errors are returned.
3948  *
3949  * Returns 1 if frame returned, otherwise 0
3950  */
3951 int rx_get_frame(MGSLPC_INFO *info)
3952 {
3953         unsigned short status;
3954         RXBUF *buf;
3955         unsigned int framesize = 0;
3956         unsigned long flags;
3957         struct tty_struct *tty = info->tty;
3958         int return_frame = 0;
3959         
3960         if (info->rx_frame_count == 0)
3961                 return 0;
3962
3963         buf = (RXBUF*)(info->rx_buf + (info->rx_get * info->rx_buf_size));
3964
3965         status = buf->status;
3966
3967         /* 07  VFR  1=valid frame
3968          * 06  RDO  1=data overrun
3969          * 05  CRC  1=OK, 0=error
3970          * 04  RAB  1=frame aborted
3971          */
3972         if ((status & 0xf0) != 0xA0) {
3973                 if (!(status & BIT7) || (status & BIT4))
3974                         info->icount.rxabort++;
3975                 else if (status & BIT6)
3976                         info->icount.rxover++;
3977                 else if (!(status & BIT5)) {
3978                         info->icount.rxcrc++;
3979                         if (info->params.crc_type & HDLC_CRC_RETURN_EX)
3980                                 return_frame = 1;
3981                 }
3982                 framesize = 0;
3983 #ifdef CONFIG_HDLC
3984                 {
3985                         struct net_device_stats *stats = hdlc_stats(info->netdev);
3986                         stats->rx_errors++;
3987                         stats->rx_frame_errors++;
3988                 }
3989 #endif
3990         } else
3991                 return_frame = 1;
3992
3993         if (return_frame)
3994                 framesize = buf->count;
3995
3996         if (debug_level >= DEBUG_LEVEL_BH)
3997                 printk("%s(%d):rx_get_frame(%s) status=%04X size=%d\n",
3998                         __FILE__,__LINE__,info->device_name,status,framesize);
3999                         
4000         if (debug_level >= DEBUG_LEVEL_DATA)
4001                 trace_block(info, buf->data, framesize, 0);     
4002                 
4003         if (framesize) {
4004                 if ((info->params.crc_type & HDLC_CRC_RETURN_EX &&
4005                       framesize+1 > info->max_frame_size) ||
4006                     framesize > info->max_frame_size)
4007                         info->icount.rxlong++;
4008                 else {
4009                         if (status & BIT5)
4010                                 info->icount.rxok++;
4011
4012                         if (info->params.crc_type & HDLC_CRC_RETURN_EX) {
4013                                 *(buf->data + framesize) = status & BIT5 ? RX_OK:RX_CRC_ERROR;
4014                                 ++framesize;
4015                         }
4016
4017 #ifdef CONFIG_HDLC
4018                         if (info->netcount)
4019                                 hdlcdev_rx(info, buf->data, framesize);
4020                         else
4021 #endif
4022                                 ldisc_receive_buf(tty, buf->data, info->flag_buf, framesize);
4023                 }
4024         }
4025
4026         spin_lock_irqsave(&info->lock,flags);
4027         buf->status = buf->count = 0;
4028         info->rx_frame_count--;
4029         info->rx_get++;
4030         if (info->rx_get >= info->rx_buf_count)
4031                 info->rx_get = 0;
4032         spin_unlock_irqrestore(&info->lock,flags);
4033
4034         return 1;
4035 }
4036
4037 BOOLEAN register_test(MGSLPC_INFO *info)
4038 {
4039         static unsigned char patterns[] = 
4040             { 0x00, 0xff, 0xaa, 0x55, 0x69, 0x96, 0x0f };
4041         static unsigned int count = sizeof(patterns) / sizeof(patterns[0]);
4042         unsigned int i;
4043         BOOLEAN rc = TRUE;
4044         unsigned long flags;
4045
4046         spin_lock_irqsave(&info->lock,flags);
4047         reset_device(info);
4048
4049         for (i = 0; i < count; i++) {
4050                 write_reg(info, XAD1, patterns[i]);
4051                 write_reg(info, XAD2, patterns[(i + 1) % count]);
4052                 if ((read_reg(info, XAD1) != patterns[i]) || 
4053                     (read_reg(info, XAD2) != patterns[(i + 1) % count])) {
4054                         rc = FALSE;
4055                         break;
4056                 }
4057         }
4058
4059         spin_unlock_irqrestore(&info->lock,flags);
4060         return rc;
4061 }
4062
4063 BOOLEAN irq_test(MGSLPC_INFO *info)
4064 {
4065         unsigned long end_time;
4066         unsigned long flags;
4067
4068         spin_lock_irqsave(&info->lock,flags);
4069         reset_device(info);
4070
4071         info->testing_irq = TRUE;
4072         hdlc_mode(info);
4073
4074         info->irq_occurred = FALSE;
4075
4076         /* init hdlc mode */
4077
4078         irq_enable(info, CHA, IRQ_TIMER);
4079         write_reg(info, CHA + TIMR, 0); /* 512 cycles */
4080         issue_command(info, CHA, CMD_START_TIMER);
4081
4082         spin_unlock_irqrestore(&info->lock,flags);
4083
4084         end_time=100;
4085         while(end_time-- && !info->irq_occurred) {
4086                 msleep_interruptible(10);
4087         }
4088         
4089         info->testing_irq = FALSE;
4090
4091         spin_lock_irqsave(&info->lock,flags);
4092         reset_device(info);
4093         spin_unlock_irqrestore(&info->lock,flags);
4094         
4095         return info->irq_occurred ? TRUE : FALSE;
4096 }
4097
4098 int adapter_test(MGSLPC_INFO *info)
4099 {
4100         if (!register_test(info)) {
4101                 info->init_error = DiagStatus_AddressFailure;
4102                 printk( "%s(%d):Register test failure for device %s Addr=%04X\n",
4103                         __FILE__,__LINE__,info->device_name, (unsigned short)(info->io_base) );
4104                 return -ENODEV;
4105         }
4106
4107         if (!irq_test(info)) {
4108                 info->init_error = DiagStatus_IrqFailure;
4109                 printk( "%s(%d):Interrupt test failure for device %s IRQ=%d\n",
4110                         __FILE__,__LINE__,info->device_name, (unsigned short)(info->irq_level) );
4111                 return -ENODEV;
4112         }
4113
4114         if (debug_level >= DEBUG_LEVEL_INFO)
4115                 printk("%s(%d):device %s passed diagnostics\n",
4116                         __FILE__,__LINE__,info->device_name);
4117         return 0;
4118 }
4119
4120 void trace_block(MGSLPC_INFO *info,const char* data, int count, int xmit)
4121 {
4122         int i;
4123         int linecount;
4124         if (xmit)
4125                 printk("%s tx data:\n",info->device_name);
4126         else
4127                 printk("%s rx data:\n",info->device_name);
4128                 
4129         while(count) {
4130                 if (count > 16)
4131                         linecount = 16;
4132                 else
4133                         linecount = count;
4134                         
4135                 for(i=0;i<linecount;i++)
4136                         printk("%02X ",(unsigned char)data[i]);
4137                 for(;i<17;i++)
4138                         printk("   ");
4139                 for(i=0;i<linecount;i++) {
4140                         if (data[i]>=040 && data[i]<=0176)
4141                                 printk("%c",data[i]);
4142                         else
4143                                 printk(".");
4144                 }
4145                 printk("\n");
4146                 
4147                 data  += linecount;
4148                 count -= linecount;
4149         }
4150 }
4151
4152 /* HDLC frame time out
4153  * update stats and do tx completion processing
4154  */
4155 void tx_timeout(unsigned long context)
4156 {
4157         MGSLPC_INFO *info = (MGSLPC_INFO*)context;
4158         unsigned long flags;
4159         
4160         if ( debug_level >= DEBUG_LEVEL_INFO )
4161                 printk( "%s(%d):tx_timeout(%s)\n",
4162                         __FILE__,__LINE__,info->device_name);
4163         if(info->tx_active &&
4164            info->params.mode == MGSL_MODE_HDLC) {
4165                 info->icount.txtimeout++;
4166         }
4167         spin_lock_irqsave(&info->lock,flags);
4168         info->tx_active = 0;
4169         info->tx_count = info->tx_put = info->tx_get = 0;
4170
4171         spin_unlock_irqrestore(&info->lock,flags);
4172         
4173 #ifdef CONFIG_HDLC
4174         if (info->netcount)
4175                 hdlcdev_tx_done(info);
4176         else
4177 #endif
4178                 bh_transmit(info);
4179 }
4180
4181 #ifdef CONFIG_HDLC
4182
4183 /**
4184  * called by generic HDLC layer when protocol selected (PPP, frame relay, etc.)
4185  * set encoding and frame check sequence (FCS) options
4186  *
4187  * dev       pointer to network device structure
4188  * encoding  serial encoding setting
4189  * parity    FCS setting
4190  *
4191  * returns 0 if success, otherwise error code
4192  */
4193 static int hdlcdev_attach(struct net_device *dev, unsigned short encoding,
4194                           unsigned short parity)
4195 {
4196         MGSLPC_INFO *info = dev_to_port(dev);
4197         unsigned char  new_encoding;
4198         unsigned short new_crctype;
4199
4200         /* return error if TTY interface open */
4201         if (info->count)
4202                 return -EBUSY;
4203
4204         switch (encoding)
4205         {
4206         case ENCODING_NRZ:        new_encoding = HDLC_ENCODING_NRZ; break;
4207         case ENCODING_NRZI:       new_encoding = HDLC_ENCODING_NRZI_SPACE; break;
4208         case ENCODING_FM_MARK:    new_encoding = HDLC_ENCODING_BIPHASE_MARK; break;
4209         case ENCODING_FM_SPACE:   new_encoding = HDLC_ENCODING_BIPHASE_SPACE; break;
4210         case ENCODING_MANCHESTER: new_encoding = HDLC_ENCODING_BIPHASE_LEVEL; break;
4211         default: return -EINVAL;
4212         }
4213
4214         switch (parity)
4215         {
4216         case PARITY_NONE:            new_crctype = HDLC_CRC_NONE; break;
4217         case PARITY_CRC16_PR1_CCITT: new_crctype = HDLC_CRC_16_CCITT; break;
4218         case PARITY_CRC32_PR1_CCITT: new_crctype = HDLC_CRC_32_CCITT; break;
4219         default: return -EINVAL;
4220         }
4221
4222         info->params.encoding = new_encoding;
4223         info->params.crc_type = new_crctype;;
4224
4225         /* if network interface up, reprogram hardware */
4226         if (info->netcount)
4227                 mgslpc_program_hw(info);
4228
4229         return 0;
4230 }
4231
4232 /**
4233  * called by generic HDLC layer to send frame
4234  *
4235  * skb  socket buffer containing HDLC frame
4236  * dev  pointer to network device structure
4237  *
4238  * returns 0 if success, otherwise error code
4239  */
4240 static int hdlcdev_xmit(struct sk_buff *skb, struct net_device *dev)
4241 {
4242         MGSLPC_INFO *info = dev_to_port(dev);
4243         struct net_device_stats *stats = hdlc_stats(dev);
4244         unsigned long flags;
4245
4246         if (debug_level >= DEBUG_LEVEL_INFO)
4247                 printk(KERN_INFO "%s:hdlc_xmit(%s)\n",__FILE__,dev->name);
4248
4249         /* stop sending until this frame completes */
4250         netif_stop_queue(dev);
4251
4252         /* copy data to device buffers */
4253         memcpy(info->tx_buf, skb->data, skb->len);
4254         info->tx_get = 0;
4255         info->tx_put = info->tx_count = skb->len;
4256
4257         /* update network statistics */
4258         stats->tx_packets++;
4259         stats->tx_bytes += skb->len;
4260
4261         /* done with socket buffer, so free it */
4262         dev_kfree_skb(skb);
4263
4264         /* save start time for transmit timeout detection */
4265         dev->trans_start = jiffies;
4266
4267         /* start hardware transmitter if necessary */
4268         spin_lock_irqsave(&info->lock,flags);
4269         if (!info->tx_active)
4270                 tx_start(info);
4271         spin_unlock_irqrestore(&info->lock,flags);
4272
4273         return 0;
4274 }
4275
4276 /**
4277  * called by network layer when interface enabled
4278  * claim resources and initialize hardware
4279  *
4280  * dev  pointer to network device structure
4281  *
4282  * returns 0 if success, otherwise error code
4283  */
4284 static int hdlcdev_open(struct net_device *dev)
4285 {
4286         MGSLPC_INFO *info = dev_to_port(dev);
4287         int rc;
4288         unsigned long flags;
4289
4290         if (debug_level >= DEBUG_LEVEL_INFO)
4291                 printk("%s:hdlcdev_open(%s)\n",__FILE__,dev->name);
4292
4293         /* generic HDLC layer open processing */
4294         if ((rc = hdlc_open(dev)))
4295                 return rc;
4296
4297         /* arbitrate between network and tty opens */
4298         spin_lock_irqsave(&info->netlock, flags);
4299         if (info->count != 0 || info->netcount != 0) {
4300                 printk(KERN_WARNING "%s: hdlc_open returning busy\n", dev->name);
4301                 spin_unlock_irqrestore(&info->netlock, flags);
4302                 return -EBUSY;
4303         }
4304         info->netcount=1;
4305         spin_unlock_irqrestore(&info->netlock, flags);
4306
4307         /* claim resources and init adapter */
4308         if ((rc = startup(info)) != 0) {
4309                 spin_lock_irqsave(&info->netlock, flags);
4310                 info->netcount=0;
4311                 spin_unlock_irqrestore(&info->netlock, flags);
4312                 return rc;
4313         }
4314
4315         /* assert DTR and RTS, apply hardware settings */
4316         info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR;
4317         mgslpc_program_hw(info);
4318
4319         /* enable network layer transmit */
4320         dev->trans_start = jiffies;
4321         netif_start_queue(dev);
4322
4323         /* inform generic HDLC layer of current DCD status */
4324         spin_lock_irqsave(&info->lock, flags);
4325         get_signals(info);
4326         spin_unlock_irqrestore(&info->lock, flags);
4327         hdlc_set_carrier(info->serial_signals & SerialSignal_DCD, dev);
4328
4329         return 0;
4330 }
4331
4332 /**
4333  * called by network layer when interface is disabled
4334  * shutdown hardware and release resources
4335  *
4336  * dev  pointer to network device structure
4337  *
4338  * returns 0 if success, otherwise error code
4339  */
4340 static int hdlcdev_close(struct net_device *dev)
4341 {
4342         MGSLPC_INFO *info = dev_to_port(dev);
4343         unsigned long flags;
4344
4345         if (debug_level >= DEBUG_LEVEL_INFO)
4346                 printk("%s:hdlcdev_close(%s)\n",__FILE__,dev->name);
4347
4348         netif_stop_queue(dev);
4349
4350         /* shutdown adapter and release resources */
4351         shutdown(info);
4352
4353         hdlc_close(dev);
4354
4355         spin_lock_irqsave(&info->netlock, flags);
4356         info->netcount=0;
4357         spin_unlock_irqrestore(&info->netlock, flags);
4358
4359         return 0;
4360 }
4361
4362 /**
4363  * called by network layer to process IOCTL call to network device
4364  *
4365  * dev  pointer to network device structure
4366  * ifr  pointer to network interface request structure
4367  * cmd  IOCTL command code
4368  *
4369  * returns 0 if success, otherwise error code
4370  */
4371 static int hdlcdev_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
4372 {
4373         const size_t size = sizeof(sync_serial_settings);
4374         sync_serial_settings new_line;
4375         sync_serial_settings __user *line = ifr->ifr_settings.ifs_ifsu.sync;
4376         MGSLPC_INFO *info = dev_to_port(dev);
4377         unsigned int flags;
4378
4379         if (debug_level >= DEBUG_LEVEL_INFO)
4380                 printk("%s:hdlcdev_ioctl(%s)\n",__FILE__,dev->name);
4381
4382         /* return error if TTY interface open */
4383         if (info->count)
4384                 return -EBUSY;
4385
4386         if (cmd != SIOCWANDEV)
4387                 return hdlc_ioctl(dev, ifr, cmd);
4388
4389         switch(ifr->ifr_settings.type) {
4390         case IF_GET_IFACE: /* return current sync_serial_settings */
4391
4392                 ifr->ifr_settings.type = IF_IFACE_SYNC_SERIAL;
4393                 if (ifr->ifr_settings.size < size) {
4394                         ifr->ifr_settings.size = size; /* data size wanted */
4395                         return -ENOBUFS;
4396                 }
4397
4398                 flags = info->params.flags & (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL |
4399                                               HDLC_FLAG_RXC_BRG    | HDLC_FLAG_RXC_TXCPIN |
4400                                               HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL |
4401                                               HDLC_FLAG_TXC_BRG    | HDLC_FLAG_TXC_RXCPIN);
4402
4403                 switch (flags){
4404                 case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_TXCPIN): new_line.clock_type = CLOCK_EXT; break;
4405                 case (HDLC_FLAG_RXC_BRG    | HDLC_FLAG_TXC_BRG):    new_line.clock_type = CLOCK_INT; break;
4406                 case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_BRG):    new_line.clock_type = CLOCK_TXINT; break;
4407                 case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_RXCPIN): new_line.clock_type = CLOCK_TXFROMRX; break;
4408                 default: new_line.clock_type = CLOCK_DEFAULT;
4409                 }
4410
4411                 new_line.clock_rate = info->params.clock_speed;
4412                 new_line.loopback   = info->params.loopback ? 1:0;
4413
4414                 if (copy_to_user(line, &new_line, size))
4415                         return -EFAULT;
4416                 return 0;
4417
4418         case IF_IFACE_SYNC_SERIAL: /* set sync_serial_settings */
4419
4420                 if(!capable(CAP_NET_ADMIN))
4421                         return -EPERM;
4422                 if (copy_from_user(&new_line, line, size))
4423                         return -EFAULT;
4424
4425                 switch (new_line.clock_type)
4426                 {
4427                 case CLOCK_EXT:      flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_TXCPIN; break;
4428                 case CLOCK_TXFROMRX: flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_RXCPIN; break;
4429                 case CLOCK_INT:      flags = HDLC_FLAG_RXC_BRG    | HDLC_FLAG_TXC_BRG;    break;
4430                 case CLOCK_TXINT:    flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_BRG;    break;
4431                 case CLOCK_DEFAULT:  flags = info->params.flags &
4432                                              (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL |
4433                                               HDLC_FLAG_RXC_BRG    | HDLC_FLAG_RXC_TXCPIN |
4434                                               HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL |
4435                                               HDLC_FLAG_TXC_BRG    | HDLC_FLAG_TXC_RXCPIN); break;
4436                 default: return -EINVAL;
4437                 }
4438
4439                 if (new_line.loopback != 0 && new_line.loopback != 1)
4440                         return -EINVAL;
4441
4442                 info->params.flags &= ~(HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL |
4443                                         HDLC_FLAG_RXC_BRG    | HDLC_FLAG_RXC_TXCPIN |
4444                                         HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL |
4445                                         HDLC_FLAG_TXC_BRG    | HDLC_FLAG_TXC_RXCPIN);
4446                 info->params.flags |= flags;
4447
4448                 info->params.loopback = new_line.loopback;
4449
4450                 if (flags & (HDLC_FLAG_RXC_BRG | HDLC_FLAG_TXC_BRG))
4451                         info->params.clock_speed = new_line.clock_rate;
4452                 else
4453                         info->params.clock_speed = 0;
4454
4455                 /* if network interface up, reprogram hardware */
4456                 if (info->netcount)
4457                         mgslpc_program_hw(info);
4458                 return 0;
4459
4460         default:
4461                 return hdlc_ioctl(dev, ifr, cmd);
4462         }
4463 }
4464
4465 /**
4466  * called by network layer when transmit timeout is detected
4467  *
4468  * dev  pointer to network device structure
4469  */
4470 static void hdlcdev_tx_timeout(struct net_device *dev)
4471 {
4472         MGSLPC_INFO *info = dev_to_port(dev);
4473         struct net_device_stats *stats = hdlc_stats(dev);
4474         unsigned long flags;
4475
4476         if (debug_level >= DEBUG_LEVEL_INFO)
4477                 printk("hdlcdev_tx_timeout(%s)\n",dev->name);
4478
4479         stats->tx_errors++;
4480         stats->tx_aborted_errors++;
4481
4482         spin_lock_irqsave(&info->lock,flags);
4483         tx_stop(info);
4484         spin_unlock_irqrestore(&info->lock,flags);
4485
4486         netif_wake_queue(dev);
4487 }
4488
4489 /**
4490  * called by device driver when transmit completes
4491  * reenable network layer transmit if stopped
4492  *
4493  * info  pointer to device instance information
4494  */
4495 static void hdlcdev_tx_done(MGSLPC_INFO *info)
4496 {
4497         if (netif_queue_stopped(info->netdev))
4498                 netif_wake_queue(info->netdev);
4499 }
4500
4501 /**
4502  * called by device driver when frame received
4503  * pass frame to network layer
4504  *
4505  * info  pointer to device instance information
4506  * buf   pointer to buffer contianing frame data
4507  * size  count of data bytes in buf
4508  */
4509 static void hdlcdev_rx(MGSLPC_INFO *info, char *buf, int size)
4510 {
4511         struct sk_buff *skb = dev_alloc_skb(size);
4512         struct net_device *dev = info->netdev;
4513         struct net_device_stats *stats = hdlc_stats(dev);
4514
4515         if (debug_level >= DEBUG_LEVEL_INFO)
4516                 printk("hdlcdev_rx(%s)\n",dev->name);
4517
4518         if (skb == NULL) {
4519                 printk(KERN_NOTICE "%s: can't alloc skb, dropping packet\n", dev->name);
4520                 stats->rx_dropped++;
4521                 return;
4522         }
4523
4524         memcpy(skb_put(skb, size),buf,size);
4525
4526         skb->protocol = hdlc_type_trans(skb, info->netdev);
4527
4528         stats->rx_packets++;
4529         stats->rx_bytes += size;
4530
4531         netif_rx(skb);
4532
4533         info->netdev->last_rx = jiffies;
4534 }
4535
4536 /**
4537  * called by device driver when adding device instance
4538  * do generic HDLC initialization
4539  *
4540  * info  pointer to device instance information
4541  *
4542  * returns 0 if success, otherwise error code
4543  */
4544 static int hdlcdev_init(MGSLPC_INFO *info)
4545 {
4546         int rc;
4547         struct net_device *dev;
4548         hdlc_device *hdlc;
4549
4550         /* allocate and initialize network and HDLC layer objects */
4551
4552         if (!(dev = alloc_hdlcdev(info))) {
4553                 printk(KERN_ERR "%s:hdlc device allocation failure\n",__FILE__);
4554                 return -ENOMEM;
4555         }
4556
4557         /* for network layer reporting purposes only */
4558         dev->base_addr = info->io_base;
4559         dev->irq       = info->irq_level;
4560
4561         /* network layer callbacks and settings */
4562         dev->do_ioctl       = hdlcdev_ioctl;
4563         dev->open           = hdlcdev_open;
4564         dev->stop           = hdlcdev_close;
4565         dev->tx_timeout     = hdlcdev_tx_timeout;
4566         dev->watchdog_timeo = 10*HZ;
4567         dev->tx_queue_len   = 50;
4568
4569         /* generic HDLC layer callbacks and settings */
4570         hdlc         = dev_to_hdlc(dev);
4571         hdlc->attach = hdlcdev_attach;
4572         hdlc->xmit   = hdlcdev_xmit;
4573
4574         /* register objects with HDLC layer */
4575         if ((rc = register_hdlc_device(dev))) {
4576                 printk(KERN_WARNING "%s:unable to register hdlc device\n",__FILE__);
4577                 free_netdev(dev);
4578                 return rc;
4579         }
4580
4581         info->netdev = dev;
4582         return 0;
4583 }
4584
4585 /**
4586  * called by device driver when removing device instance
4587  * do generic HDLC cleanup
4588  *
4589  * info  pointer to device instance information
4590  */
4591 static void hdlcdev_exit(MGSLPC_INFO *info)
4592 {
4593         unregister_hdlc_device(info->netdev);
4594         free_netdev(info->netdev);
4595         info->netdev = NULL;
4596 }
4597
4598 #endif /* CONFIG_HDLC */
4599