1/*
2 *  linux/drivers/char/amiserial.c
3 *
4 * Serial driver for the amiga builtin port.
5 *
6 * This code was created by taking serial.c version 4.30 from kernel
7 * release 2.3.22, replacing all hardware related stuff with the
8 * corresponding amiga hardware actions, and removing all irrelevant
9 * code. As a consequence, it uses many of the constants and names
10 * associated with the registers and bits of 16550 compatible UARTS -
11 * but only to keep track of status, etc in the state variables. It
12 * was done this was to make it easier to keep the code in line with
13 * (non hardware specific) changes to serial.c.
14 *
15 * The port is registered with the tty driver as minor device 64, and
16 * therefore other ports should should only use 65 upwards.
17 *
18 * Richard Lucock 28/12/99
19 *
20 *  Copyright (C) 1991, 1992  Linus Torvalds
21 *  Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997,
22 * 		1998, 1999  Theodore Ts'o
23 *
24 */
25
26/*
27 * Serial driver configuration section.  Here are the various options:
28 *
29 * SERIAL_PARANOIA_CHECK
30 * 		Check the magic number for the async_structure where
31 * 		ever possible.
32 */
33
34#include <linux/delay.h>
35
36#undef SERIAL_PARANOIA_CHECK
37#define SERIAL_DO_RESTART
38
39/* Set of debugging defines */
40
41#undef SERIAL_DEBUG_INTR
42#undef SERIAL_DEBUG_OPEN
43#undef SERIAL_DEBUG_FLOW
44#undef SERIAL_DEBUG_RS_WAIT_UNTIL_SENT
45
46/* Sanity checks */
47
48#if defined(MODULE) && defined(SERIAL_DEBUG_MCOUNT)
49#define DBG_CNT(s) printk("(%s): [%x] refc=%d, serc=%d, ttyc=%d -> %s\n", \
50 tty->name, (info->flags), serial_driver->refcount,info->count,tty->count,s)
51#else
52#define DBG_CNT(s)
53#endif
54
55/*
56 * End of serial driver configuration section.
57 */
58
59#include <linux/module.h>
60
61#include <linux/types.h>
62#include <linux/serial.h>
63#include <linux/serialP.h>
64#include <linux/serial_reg.h>
65static char *serial_version = "4.30";
66
67#include <linux/errno.h>
68#include <linux/signal.h>
69#include <linux/sched.h>
70#include <linux/kernel.h>
71#include <linux/timer.h>
72#include <linux/interrupt.h>
73#include <linux/tty.h>
74#include <linux/tty_flip.h>
75#include <linux/console.h>
76#include <linux/major.h>
77#include <linux/string.h>
78#include <linux/fcntl.h>
79#include <linux/ptrace.h>
80#include <linux/ioport.h>
81#include <linux/mm.h>
82#include <linux/slab.h>
83#include <linux/init.h>
84#include <linux/bitops.h>
85
86#include <asm/setup.h>
87
88#include <asm/system.h>
89
90#include <asm/irq.h>
91
92#include <asm/amigahw.h>
93#include <asm/amigaints.h>
94
95#define custom amiga_custom
96static char *serial_name = "Amiga-builtin serial driver";
97
98static struct tty_driver *serial_driver;
99
100/* number of characters left in xmit buffer before we ask for more */
101#define WAKEUP_CHARS 256
102
103static struct async_struct *IRQ_ports;
104
105static unsigned char current_ctl_bits;
106
107static void change_speed(struct async_struct *info, struct ktermios *old);
108static void rs_wait_until_sent(struct tty_struct *tty, int timeout);
109
110
111static struct serial_state rs_table[1];
112
113#define NR_PORTS ARRAY_SIZE(rs_table)
114
115#include <asm/uaccess.h>
116
117#define serial_isroot()	(capable(CAP_SYS_ADMIN))
118
119
120static inline int serial_paranoia_check(struct async_struct *info,
121					char *name, const char *routine)
122{
123#ifdef SERIAL_PARANOIA_CHECK
124	static const char *badmagic =
125		"Warning: bad magic number for serial struct (%s) in %s\n";
126	static const char *badinfo =
127		"Warning: null async_struct for (%s) in %s\n";
128
129	if (!info) {
130		printk(badinfo, name, routine);
131		return 1;
132	}
133	if (info->magic != SERIAL_MAGIC) {
134		printk(badmagic, name, routine);
135		return 1;
136	}
137#endif
138	return 0;
139}
140
141/* some serial hardware definitions */
142#define SDR_OVRUN   (1<<15)
143#define SDR_RBF     (1<<14)
144#define SDR_TBE     (1<<13)
145#define SDR_TSRE    (1<<12)
146
147#define SERPER_PARENB    (1<<15)
148
149#define AC_SETCLR   (1<<15)
150#define AC_UARTBRK  (1<<11)
151
152#define SER_DTR     (1<<7)
153#define SER_RTS     (1<<6)
154#define SER_DCD     (1<<5)
155#define SER_CTS     (1<<4)
156#define SER_DSR     (1<<3)
157
158static __inline__ void rtsdtr_ctrl(int bits)
159{
160    ciab.pra = ((bits & (SER_RTS | SER_DTR)) ^ (SER_RTS | SER_DTR)) | (ciab.pra & ~(SER_RTS | SER_DTR));
161}
162
163/*
164 * ------------------------------------------------------------
165 * rs_stop() and rs_start()
166 *
167 * This routines are called before setting or resetting tty->stopped.
168 * They enable or disable transmitter interrupts, as necessary.
169 * ------------------------------------------------------------
170 */
171static void rs_stop(struct tty_struct *tty)
172{
173	struct async_struct *info = (struct async_struct *)tty->driver_data;
174	unsigned long flags;
175
176	if (serial_paranoia_check(info, tty->name, "rs_stop"))
177		return;
178
179	local_irq_save(flags);
180	if (info->IER & UART_IER_THRI) {
181		info->IER &= ~UART_IER_THRI;
182		/* disable Tx interrupt and remove any pending interrupts */
183		custom.intena = IF_TBE;
184		mb();
185		custom.intreq = IF_TBE;
186		mb();
187	}
188	local_irq_restore(flags);
189}
190
191static void rs_start(struct tty_struct *tty)
192{
193	struct async_struct *info = (struct async_struct *)tty->driver_data;
194	unsigned long flags;
195
196	if (serial_paranoia_check(info, tty->name, "rs_start"))
197		return;
198
199	local_irq_save(flags);
200	if (info->xmit.head != info->xmit.tail
201	    && info->xmit.buf
202	    && !(info->IER & UART_IER_THRI)) {
203		info->IER |= UART_IER_THRI;
204		custom.intena = IF_SETCLR | IF_TBE;
205		mb();
206		/* set a pending Tx Interrupt, transmitter should restart now */
207		custom.intreq = IF_SETCLR | IF_TBE;
208		mb();
209	}
210	local_irq_restore(flags);
211}
212
213/*
214 * ----------------------------------------------------------------------
215 *
216 * Here starts the interrupt handling routines.  All of the following
217 * subroutines are declared as inline and are folded into
218 * rs_interrupt().  They were separated out for readability's sake.
219 *
220 * Note: rs_interrupt() is a "fast" interrupt, which means that it
221 * runs with interrupts turned off.  People who may want to modify
222 * rs_interrupt() should try to keep the interrupt handler as fast as
223 * possible.  After you are done making modifications, it is not a bad
224 * idea to do:
225 *
226 * gcc -S -DKERNEL -Wall -Wstrict-prototypes -O6 -fomit-frame-pointer serial.c
227 *
228 * and look at the resulting assemble code in serial.s.
229 *
230 * 				- Ted Ts'o (tytso@mit.edu), 7-Mar-93
231 * -----------------------------------------------------------------------
232 */
233
234/*
235 * This routine is used by the interrupt handler to schedule
236 * processing in the software interrupt portion of the driver.
237 */
238static void rs_sched_event(struct async_struct *info,
239			   int event)
240{
241	info->event |= 1 << event;
242	tasklet_schedule(&info->tlet);
243}
244
245static void receive_chars(struct async_struct *info)
246{
247        int status;
248	int serdatr;
249	struct tty_struct *tty = info->tty;
250	unsigned char ch, flag;
251	struct	async_icount *icount;
252	int oe = 0;
253
254	icount = &info->state->icount;
255
256	status = UART_LSR_DR; /* We obviously have a character! */
257	serdatr = custom.serdatr;
258	mb();
259	custom.intreq = IF_RBF;
260	mb();
261
262	if((serdatr & 0x1ff) == 0)
263	    status |= UART_LSR_BI;
264	if(serdatr & SDR_OVRUN)
265	    status |= UART_LSR_OE;
266
267	ch = serdatr & 0xff;
268	icount->rx++;
269
270#ifdef SERIAL_DEBUG_INTR
271	printk("DR%02x:%02x...", ch, status);
272#endif
273	flag = TTY_NORMAL;
274
275	/*
276	 * We don't handle parity or frame errors - but I have left
277	 * the code in, since I'm not sure that the errors can't be
278	 * detected.
279	 */
280
281	if (status & (UART_LSR_BI | UART_LSR_PE |
282		      UART_LSR_FE | UART_LSR_OE)) {
283	  /*
284	   * For statistics only
285	   */
286	  if (status & UART_LSR_BI) {
287	    status &= ~(UART_LSR_FE | UART_LSR_PE);
288	    icount->brk++;
289	  } else if (status & UART_LSR_PE)
290	    icount->parity++;
291	  else if (status & UART_LSR_FE)
292	    icount->frame++;
293	  if (status & UART_LSR_OE)
294	    icount->overrun++;
295
296	  /*
297	   * Now check to see if character should be
298	   * ignored, and mask off conditions which
299	   * should be ignored.
300	   */
301	  if (status & info->ignore_status_mask)
302	    goto out;
303
304	  status &= info->read_status_mask;
305
306	  if (status & (UART_LSR_BI)) {
307#ifdef SERIAL_DEBUG_INTR
308	    printk("handling break....");
309#endif
310	    flag = TTY_BREAK;
311	    if (info->flags & ASYNC_SAK)
312	      do_SAK(tty);
313	  } else if (status & UART_LSR_PE)
314	    flag = TTY_PARITY;
315	  else if (status & UART_LSR_FE)
316	    flag = TTY_FRAME;
317	  if (status & UART_LSR_OE) {
318	    /*
319	     * Overrun is special, since it's
320	     * reported immediately, and doesn't
321	     * affect the current character
322	     */
323	     oe = 1;
324	  }
325	}
326	tty_insert_flip_char(tty, ch, flag);
327	if (oe == 1)
328		tty_insert_flip_char(tty, 0, TTY_OVERRUN);
329	tty_flip_buffer_push(tty);
330out:
331	return;
332}
333
334static void transmit_chars(struct async_struct *info)
335{
336	custom.intreq = IF_TBE;
337	mb();
338	if (info->x_char) {
339	        custom.serdat = info->x_char | 0x100;
340		mb();
341		info->state->icount.tx++;
342		info->x_char = 0;
343		return;
344	}
345	if (info->xmit.head == info->xmit.tail
346	    || info->tty->stopped
347	    || info->tty->hw_stopped) {
348		info->IER &= ~UART_IER_THRI;
349	        custom.intena = IF_TBE;
350		mb();
351		return;
352	}
353
354	custom.serdat = info->xmit.buf[info->xmit.tail++] | 0x100;
355	mb();
356	info->xmit.tail = info->xmit.tail & (SERIAL_XMIT_SIZE-1);
357	info->state->icount.tx++;
358
359	if (CIRC_CNT(info->xmit.head,
360		     info->xmit.tail,
361		     SERIAL_XMIT_SIZE) < WAKEUP_CHARS)
362		rs_sched_event(info, RS_EVENT_WRITE_WAKEUP);
363
364#ifdef SERIAL_DEBUG_INTR
365	printk("THRE...");
366#endif
367	if (info->xmit.head == info->xmit.tail) {
368	        custom.intena = IF_TBE;
369		mb();
370		info->IER &= ~UART_IER_THRI;
371	}
372}
373
374static void check_modem_status(struct async_struct *info)
375{
376	unsigned char status = ciab.pra & (SER_DCD | SER_CTS | SER_DSR);
377	unsigned char dstatus;
378	struct	async_icount *icount;
379
380	/* Determine bits that have changed */
381	dstatus = status ^ current_ctl_bits;
382	current_ctl_bits = status;
383
384	if (dstatus) {
385		icount = &info->state->icount;
386		/* update input line counters */
387		if (dstatus & SER_DSR)
388			icount->dsr++;
389		if (dstatus & SER_DCD) {
390			icount->dcd++;
391#ifdef CONFIG_HARD_PPS
392			if ((info->flags & ASYNC_HARDPPS_CD) &&
393			    !(status & SER_DCD))
394				hardpps();
395#endif
396		}
397		if (dstatus & SER_CTS)
398			icount->cts++;
399		wake_up_interruptible(&info->delta_msr_wait);
400	}
401
402	if ((info->flags & ASYNC_CHECK_CD) && (dstatus & SER_DCD)) {
403#if (defined(SERIAL_DEBUG_OPEN) || defined(SERIAL_DEBUG_INTR))
404		printk("ttyS%d CD now %s...", info->line,
405		       (!(status & SER_DCD)) ? "on" : "off");
406#endif
407		if (!(status & SER_DCD))
408			wake_up_interruptible(&info->open_wait);
409		else {
410#ifdef SERIAL_DEBUG_OPEN
411			printk("doing serial hangup...");
412#endif
413			if (info->tty)
414				tty_hangup(info->tty);
415		}
416	}
417	if (info->flags & ASYNC_CTS_FLOW) {
418		if (info->tty->hw_stopped) {
419			if (!(status & SER_CTS)) {
420#if (defined(SERIAL_DEBUG_INTR) || defined(SERIAL_DEBUG_FLOW))
421				printk("CTS tx start...");
422#endif
423				info->tty->hw_stopped = 0;
424				info->IER |= UART_IER_THRI;
425				custom.intena = IF_SETCLR | IF_TBE;
426				mb();
427				/* set a pending Tx Interrupt, transmitter should restart now */
428				custom.intreq = IF_SETCLR | IF_TBE;
429				mb();
430				rs_sched_event(info, RS_EVENT_WRITE_WAKEUP);
431				return;
432			}
433		} else {
434			if ((status & SER_CTS)) {
435#if (defined(SERIAL_DEBUG_INTR) || defined(SERIAL_DEBUG_FLOW))
436				printk("CTS tx stop...");
437#endif
438				info->tty->hw_stopped = 1;
439				info->IER &= ~UART_IER_THRI;
440				/* disable Tx interrupt and remove any pending interrupts */
441				custom.intena = IF_TBE;
442				mb();
443				custom.intreq = IF_TBE;
444				mb();
445			}
446		}
447	}
448}
449
450static irqreturn_t ser_vbl_int( int irq, void *data)
451{
452        /* vbl is just a periodic interrupt we tie into to update modem status */
453	struct async_struct * info = IRQ_ports;
454	/*
455	 * TBD - is it better to unregister from this interrupt or to
456	 * ignore it if MSI is clear ?
457	 */
458	if(info->IER & UART_IER_MSI)
459	  check_modem_status(info);
460	return IRQ_HANDLED;
461}
462
463static irqreturn_t ser_rx_int(int irq, void *dev_id)
464{
465	struct async_struct * info;
466
467#ifdef SERIAL_DEBUG_INTR
468	printk("ser_rx_int...");
469#endif
470
471	info = IRQ_ports;
472	if (!info || !info->tty)
473		return IRQ_NONE;
474
475	receive_chars(info);
476	info->last_active = jiffies;
477#ifdef SERIAL_DEBUG_INTR
478	printk("end.\n");
479#endif
480	return IRQ_HANDLED;
481}
482
483static irqreturn_t ser_tx_int(int irq, void *dev_id)
484{
485	struct async_struct * info;
486
487	if (custom.serdatr & SDR_TBE) {
488#ifdef SERIAL_DEBUG_INTR
489	  printk("ser_tx_int...");
490#endif
491
492	  info = IRQ_ports;
493	  if (!info || !info->tty)
494		return IRQ_NONE;
495
496	  transmit_chars(info);
497	  info->last_active = jiffies;
498#ifdef SERIAL_DEBUG_INTR
499	  printk("end.\n");
500#endif
501	}
502	return IRQ_HANDLED;
503}
504
505/*
506 * -------------------------------------------------------------------
507 * Here ends the serial interrupt routines.
508 * -------------------------------------------------------------------
509 */
510
511/*
512 * This routine is used to handle the "bottom half" processing for the
513 * serial driver, known also the "software interrupt" processing.
514 * This processing is done at the kernel interrupt level, after the
515 * rs_interrupt() has returned, BUT WITH INTERRUPTS TURNED ON.  This
516 * is where time-consuming activities which can not be done in the
517 * interrupt driver proper are done; the interrupt driver schedules
518 * them using rs_sched_event(), and they get done here.
519 */
520
521static void do_softint(unsigned long private_)
522{
523	struct async_struct	*info = (struct async_struct *) private_;
524	struct tty_struct	*tty;
525
526	tty = info->tty;
527	if (!tty)
528		return;
529
530	if (test_and_clear_bit(RS_EVENT_WRITE_WAKEUP, &info->event))
531		tty_wakeup(tty);
532}
533
534/*
535 * ---------------------------------------------------------------
536 * Low level utility subroutines for the serial driver:  routines to
537 * figure out the appropriate timeout for an interrupt chain, routines
538 * to initialize and startup a serial port, and routines to shutdown a
539 * serial port.  Useful stuff like that.
540 * ---------------------------------------------------------------
541 */
542
543static int startup(struct async_struct * info)
544{
545	unsigned long flags;
546	int	retval=0;
547	unsigned long page;
548
549	page = get_zeroed_page(GFP_KERNEL);
550	if (!page)
551		return -ENOMEM;
552
553	local_irq_save(flags);
554
555	if (info->flags & ASYNC_INITIALIZED) {
556		free_page(page);
557		goto errout;
558	}
559
560	if (info->xmit.buf)
561		free_page(page);
562	else
563		info->xmit.buf = (unsigned char *) page;
564
565#ifdef SERIAL_DEBUG_OPEN
566	printk("starting up ttys%d ...", info->line);
567#endif
568
569	/* Clear anything in the input buffer */
570
571	custom.intreq = IF_RBF;
572	mb();
573
574	retval = request_irq(IRQ_AMIGA_VERTB, ser_vbl_int, 0, "serial status", info);
575	if (retval) {
576	  if (serial_isroot()) {
577	    if (info->tty)
578	      set_bit(TTY_IO_ERROR,
579		      &info->tty->flags);
580	    retval = 0;
581	  }
582	  goto errout;
583	}
584
585	/* enable both Rx and Tx interrupts */
586	custom.intena = IF_SETCLR | IF_RBF | IF_TBE;
587	mb();
588	info->IER = UART_IER_MSI;
589
590	/* remember current state of the DCD and CTS bits */
591	current_ctl_bits = ciab.pra & (SER_DCD | SER_CTS | SER_DSR);
592
593	IRQ_ports = info;
594
595	info->MCR = 0;
596	if (info->tty->termios->c_cflag & CBAUD)
597	  info->MCR = SER_DTR | SER_RTS;
598	rtsdtr_ctrl(info->MCR);
599
600	if (info->tty)
601		clear_bit(TTY_IO_ERROR, &info->tty->flags);
602	info->xmit.head = info->xmit.tail = 0;
603
604	/*
605	 * Set up the tty->alt_speed kludge
606	 */
607	if (info->tty) {
608		if ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_HI)
609			info->tty->alt_speed = 57600;
610		if ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_VHI)
611			info->tty->alt_speed = 115200;
612		if ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_SHI)
613			info->tty->alt_speed = 230400;
614		if ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_WARP)
615			info->tty->alt_speed = 460800;
616	}
617
618	/*
619	 * and set the speed of the serial port
620	 */
621	change_speed(info, NULL);
622
623	info->flags |= ASYNC_INITIALIZED;
624	local_irq_restore(flags);
625	return 0;
626
627errout:
628	local_irq_restore(flags);
629	return retval;
630}
631
632/*
633 * This routine will shutdown a serial port; interrupts are disabled, and
634 * DTR is dropped if the hangup on close termio flag is on.
635 */
636static void shutdown(struct async_struct * info)
637{
638	unsigned long	flags;
639	struct serial_state *state;
640
641	if (!(info->flags & ASYNC_INITIALIZED))
642		return;
643
644	state = info->state;
645
646#ifdef SERIAL_DEBUG_OPEN
647	printk("Shutting down serial port %d ....\n", info->line);
648#endif
649
650	local_irq_save(flags); /* Disable interrupts */
651
652	/*
653	 * clear delta_msr_wait queue to avoid mem leaks: we may free the irq
654	 * here so the queue might never be waken up
655	 */
656	wake_up_interruptible(&info->delta_msr_wait);
657
658	IRQ_ports = NULL;
659
660	/*
661	 * Free the IRQ, if necessary
662	 */
663	free_irq(IRQ_AMIGA_VERTB, info);
664
665	if (info->xmit.buf) {
666		free_page((unsigned long) info->xmit.buf);
667		info->xmit.buf = NULL;
668	}
669
670	info->IER = 0;
671	custom.intena = IF_RBF | IF_TBE;
672	mb();
673
674	/* disable break condition */
675	custom.adkcon = AC_UARTBRK;
676	mb();
677
678	if (!info->tty || (info->tty->termios->c_cflag & HUPCL))
679		info->MCR &= ~(SER_DTR|SER_RTS);
680	rtsdtr_ctrl(info->MCR);
681
682	if (info->tty)
683		set_bit(TTY_IO_ERROR, &info->tty->flags);
684
685	info->flags &= ~ASYNC_INITIALIZED;
686	local_irq_restore(flags);
687}
688
689
690/*
691 * This routine is called to set the UART divisor registers to match
692 * the specified baud rate for a serial port.
693 */
694static void change_speed(struct async_struct *info,
695			 struct ktermios *old_termios)
696{
697	int	quot = 0, baud_base, baud;
698	unsigned cflag, cval = 0;
699	int	bits;
700	unsigned long	flags;
701
702	if (!info->tty || !info->tty->termios)
703		return;
704	cflag = info->tty->termios->c_cflag;
705
706	/* Byte size is always 8 bits plus parity bit if requested */
707
708	cval = 3; bits = 10;
709	if (cflag & CSTOPB) {
710		cval |= 0x04;
711		bits++;
712	}
713	if (cflag & PARENB) {
714		cval |= UART_LCR_PARITY;
715		bits++;
716	}
717	if (!(cflag & PARODD))
718		cval |= UART_LCR_EPAR;
719#ifdef CMSPAR
720	if (cflag & CMSPAR)
721		cval |= UART_LCR_SPAR;
722#endif
723
724	/* Determine divisor based on baud rate */
725	baud = tty_get_baud_rate(info->tty);
726	if (!baud)
727		baud = 9600;	/* B0 transition handled in rs_set_termios */
728	baud_base = info->state->baud_base;
729	if (baud == 38400 &&
730	    ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_CUST))
731		quot = info->state->custom_divisor;
732	else {
733		if (baud == 134)
734			/* Special case since 134 is really 134.5 */
735			quot = (2*baud_base / 269);
736		else if (baud)
737			quot = baud_base / baud;
738	}
739	/* If the quotient is zero refuse the change */
740	if (!quot && old_termios) {
741		info->tty->termios->c_cflag &= ~CBAUD;
742		info->tty->termios->c_cflag |= (old_termios->c_cflag & CBAUD);
743		baud = tty_get_baud_rate(info->tty);
744		if (!baud)
745			baud = 9600;
746		if (baud == 38400 &&
747		    ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_CUST))
748			quot = info->state->custom_divisor;
749		else {
750			if (baud == 134)
751				/* Special case since 134 is really 134.5 */
752				quot = (2*baud_base / 269);
753			else if (baud)
754				quot = baud_base / baud;
755		}
756	}
757	/* As a last resort, if the quotient is zero, default to 9600 bps */
758	if (!quot)
759		quot = baud_base / 9600;
760	info->quot = quot;
761	info->timeout = ((info->xmit_fifo_size*HZ*bits*quot) / baud_base);
762	info->timeout += HZ/50;		/* Add .02 seconds of slop */
763
764	/* CTS flow control flag and modem status interrupts */
765	info->IER &= ~UART_IER_MSI;
766	if (info->flags & ASYNC_HARDPPS_CD)
767		info->IER |= UART_IER_MSI;
768	if (cflag & CRTSCTS) {
769		info->flags |= ASYNC_CTS_FLOW;
770		info->IER |= UART_IER_MSI;
771	} else
772		info->flags &= ~ASYNC_CTS_FLOW;
773	if (cflag & CLOCAL)
774		info->flags &= ~ASYNC_CHECK_CD;
775	else {
776		info->flags |= ASYNC_CHECK_CD;
777		info->IER |= UART_IER_MSI;
778	}
779	/* TBD:
780	 * Does clearing IER_MSI imply that we should disbale the VBL interrupt ?
781	 */
782
783	/*
784	 * Set up parity check flag
785	 */
786#define RELEVANT_IFLAG(iflag) (iflag & (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK))
787
788	info->read_status_mask = UART_LSR_OE | UART_LSR_DR;
789	if (I_INPCK(info->tty))
790		info->read_status_mask |= UART_LSR_FE | UART_LSR_PE;
791	if (I_BRKINT(info->tty) || I_PARMRK(info->tty))
792		info->read_status_mask |= UART_LSR_BI;
793
794	/*
795	 * Characters to ignore
796	 */
797	info->ignore_status_mask = 0;
798	if (I_IGNPAR(info->tty))
799		info->ignore_status_mask |= UART_LSR_PE | UART_LSR_FE;
800	if (I_IGNBRK(info->tty)) {
801		info->ignore_status_mask |= UART_LSR_BI;
802		/*
803		 * If we're ignore parity and break indicators, ignore
804		 * overruns too.  (For real raw support).
805		 */
806		if (I_IGNPAR(info->tty))
807			info->ignore_status_mask |= UART_LSR_OE;
808	}
809	/*
810	 * !!! ignore all characters if CREAD is not set
811	 */
812	if ((cflag & CREAD) == 0)
813		info->ignore_status_mask |= UART_LSR_DR;
814	local_irq_save(flags);
815
816	{
817	  short serper;
818
819	/* Set up the baud rate */
820	  serper = quot - 1;
821
822	/* Enable or disable parity bit */
823
824	if(cval & UART_LCR_PARITY)
825	  serper |= (SERPER_PARENB);
826
827	custom.serper = serper;
828	mb();
829	}
830
831	info->LCR = cval;				/* Save LCR */
832	local_irq_restore(flags);
833}
834
835static void rs_put_char(struct tty_struct *tty, unsigned char ch)
836{
837	struct async_struct *info;
838	unsigned long flags;
839
840	if (!tty)
841		return;
842
843	info = tty->driver_data;
844
845	if (serial_paranoia_check(info, tty->name, "rs_put_char"))
846		return;
847
848	if (!info->xmit.buf)
849		return;
850
851	local_irq_save(flags);
852	if (CIRC_SPACE(info->xmit.head,
853		       info->xmit.tail,
854		       SERIAL_XMIT_SIZE) == 0) {
855		local_irq_restore(flags);
856		return;
857	}
858
859	info->xmit.buf[info->xmit.head++] = ch;
860	info->xmit.head &= SERIAL_XMIT_SIZE-1;
861	local_irq_restore(flags);
862}
863
864static void rs_flush_chars(struct tty_struct *tty)
865{
866	struct async_struct *info = (struct async_struct *)tty->driver_data;
867	unsigned long flags;
868
869	if (serial_paranoia_check(info, tty->name, "rs_flush_chars"))
870		return;
871
872	if (info->xmit.head == info->xmit.tail
873	    || tty->stopped
874	    || tty->hw_stopped
875	    || !info->xmit.buf)
876		return;
877
878	local_irq_save(flags);
879	info->IER |= UART_IER_THRI;
880	custom.intena = IF_SETCLR | IF_TBE;
881	mb();
882	/* set a pending Tx Interrupt, transmitter should restart now */
883	custom.intreq = IF_SETCLR | IF_TBE;
884	mb();
885	local_irq_restore(flags);
886}
887
888static int rs_write(struct tty_struct * tty, const unsigned char *buf, int count)
889{
890	int	c, ret = 0;
891	struct async_struct *info;
892	unsigned long flags;
893
894	if (!tty)
895		return 0;
896
897	info = tty->driver_data;
898
899	if (serial_paranoia_check(info, tty->name, "rs_write"))
900		return 0;
901
902	if (!info->xmit.buf)
903		return 0;
904
905	local_irq_save(flags);
906	while (1) {
907		c = CIRC_SPACE_TO_END(info->xmit.head,
908				      info->xmit.tail,
909				      SERIAL_XMIT_SIZE);
910		if (count < c)
911			c = count;
912		if (c <= 0) {
913			break;
914		}
915		memcpy(info->xmit.buf + info->xmit.head, buf, c);
916		info->xmit.head = ((info->xmit.head + c) &
917				   (SERIAL_XMIT_SIZE-1));
918		buf += c;
919		count -= c;
920		ret += c;
921	}
922	local_irq_restore(flags);
923
924	if (info->xmit.head != info->xmit.tail
925	    && !tty->stopped
926	    && !tty->hw_stopped
927	    && !(info->IER & UART_IER_THRI)) {
928		info->IER |= UART_IER_THRI;
929		local_irq_disable();
930		custom.intena = IF_SETCLR | IF_TBE;
931		mb();
932		/* set a pending Tx Interrupt, transmitter should restart now */
933		custom.intreq = IF_SETCLR | IF_TBE;
934		mb();
935		local_irq_restore(flags);
936	}
937	return ret;
938}
939
940static int rs_write_room(struct tty_struct *tty)
941{
942	struct async_struct *info = (struct async_struct *)tty->driver_data;
943
944	if (serial_paranoia_check(info, tty->name, "rs_write_room"))
945		return 0;
946	return CIRC_SPACE(info->xmit.head, info->xmit.tail, SERIAL_XMIT_SIZE);
947}
948
949static int rs_chars_in_buffer(struct tty_struct *tty)
950{
951	struct async_struct *info = (struct async_struct *)tty->driver_data;
952
953	if (serial_paranoia_check(info, tty->name, "rs_chars_in_buffer"))
954		return 0;
955	return CIRC_CNT(info->xmit.head, info->xmit.tail, SERIAL_XMIT_SIZE);
956}
957
958static void rs_flush_buffer(struct tty_struct *tty)
959{
960	struct async_struct *info = (struct async_struct *)tty->driver_data;
961	unsigned long flags;
962
963	if (serial_paranoia_check(info, tty->name, "rs_flush_buffer"))
964		return;
965	local_irq_save(flags);
966	info->xmit.head = info->xmit.tail = 0;
967	local_irq_restore(flags);
968	tty_wakeup(tty);
969}
970
971/*
972 * This function is used to send a high-priority XON/XOFF character to
973 * the device
974 */
975static void rs_send_xchar(struct tty_struct *tty, char ch)
976{
977	struct async_struct *info = (struct async_struct *)tty->driver_data;
978        unsigned long flags;
979
980	if (serial_paranoia_check(info, tty->name, "rs_send_char"))
981		return;
982
983	info->x_char = ch;
984	if (ch) {
985		/* Make sure transmit interrupts are on */
986
987	        /* Check this ! */
988	        local_irq_save(flags);
989		if(!(custom.intenar & IF_TBE)) {
990		    custom.intena = IF_SETCLR | IF_TBE;
991		    mb();
992		    /* set a pending Tx Interrupt, transmitter should restart now */
993		    custom.intreq = IF_SETCLR | IF_TBE;
994		    mb();
995		}
996		local_irq_restore(flags);
997
998		info->IER |= UART_IER_THRI;
999	}
1000}
1001
1002/*
1003 * ------------------------------------------------------------
1004 * rs_throttle()
1005 *
1006 * This routine is called by the upper-layer tty layer to signal that
1007 * incoming characters should be throttled.
1008 * ------------------------------------------------------------
1009 */
1010static void rs_throttle(struct tty_struct * tty)
1011{
1012	struct async_struct *info = (struct async_struct *)tty->driver_data;
1013	unsigned long flags;
1014#ifdef SERIAL_DEBUG_THROTTLE
1015	char	buf[64];
1016
1017	printk("throttle %s: %d....\n", tty_name(tty, buf),
1018	       tty->ldisc.chars_in_buffer(tty));
1019#endif
1020
1021	if (serial_paranoia_check(info, tty->name, "rs_throttle"))
1022		return;
1023
1024	if (I_IXOFF(tty))
1025		rs_send_xchar(tty, STOP_CHAR(tty));
1026
1027	if (tty->termios->c_cflag & CRTSCTS)
1028		info->MCR &= ~SER_RTS;
1029
1030	local_irq_save(flags);
1031	rtsdtr_ctrl(info->MCR);
1032	local_irq_restore(flags);
1033}
1034
1035static void rs_unthrottle(struct tty_struct * tty)
1036{
1037	struct async_struct *info = (struct async_struct *)tty->driver_data;
1038	unsigned long flags;
1039#ifdef SERIAL_DEBUG_THROTTLE
1040	char	buf[64];
1041
1042	printk("unthrottle %s: %d....\n", tty_name(tty, buf),
1043	       tty->ldisc.chars_in_buffer(tty));
1044#endif
1045
1046	if (serial_paranoia_check(info, tty->name, "rs_unthrottle"))
1047		return;
1048
1049	if (I_IXOFF(tty)) {
1050		if (info->x_char)
1051			info->x_char = 0;
1052		else
1053			rs_send_xchar(tty, START_CHAR(tty));
1054	}
1055	if (tty->termios->c_cflag & CRTSCTS)
1056		info->MCR |= SER_RTS;
1057	local_irq_save(flags);
1058	rtsdtr_ctrl(info->MCR);
1059	local_irq_restore(flags);
1060}
1061
1062/*
1063 * ------------------------------------------------------------
1064 * rs_ioctl() and friends
1065 * ------------------------------------------------------------
1066 */
1067
1068static int get_serial_info(struct async_struct * info,
1069			   struct serial_struct __user * retinfo)
1070{
1071	struct serial_struct tmp;
1072	struct serial_state *state = info->state;
1073
1074	if (!retinfo)
1075		return -EFAULT;
1076	memset(&tmp, 0, sizeof(tmp));
1077	tmp.type = state->type;
1078	tmp.line = state->line;
1079	tmp.port = state->port;
1080	tmp.irq = state->irq;
1081	tmp.flags = state->flags;
1082	tmp.xmit_fifo_size = state->xmit_fifo_size;
1083	tmp.baud_base = state->baud_base;
1084	tmp.close_delay = state->close_delay;
1085	tmp.closing_wait = state->closing_wait;
1086	tmp.custom_divisor = state->custom_divisor;
1087	if (copy_to_user(retinfo,&tmp,sizeof(*retinfo)))
1088		return -EFAULT;
1089	return 0;
1090}
1091
1092static int set_serial_info(struct async_struct * info,
1093			   struct serial_struct __user * new_info)
1094{
1095	struct serial_struct new_serial;
1096 	struct serial_state old_state, *state;
1097	unsigned int		change_irq,change_port;
1098	int 			retval = 0;
1099
1100	if (copy_from_user(&new_serial,new_info,sizeof(new_serial)))
1101		return -EFAULT;
1102	state = info->state;
1103	old_state = *state;
1104
1105	change_irq = new_serial.irq != state->irq;
1106	change_port = (new_serial.port != state->port);
1107	if(change_irq || change_port || (new_serial.xmit_fifo_size != state->xmit_fifo_size))
1108	  return -EINVAL;
1109
1110	if (!serial_isroot()) {
1111		if ((new_serial.baud_base != state->baud_base) ||
1112		    (new_serial.close_delay != state->close_delay) ||
1113		    (new_serial.xmit_fifo_size != state->xmit_fifo_size) ||
1114		    ((new_serial.flags & ~ASYNC_USR_MASK) !=
1115		     (state->flags & ~ASYNC_USR_MASK)))
1116			return -EPERM;
1117		state->flags = ((state->flags & ~ASYNC_USR_MASK) |
1118			       (new_serial.flags & ASYNC_USR_MASK));
1119		info->flags = ((info->flags & ~ASYNC_USR_MASK) |
1120			       (new_serial.flags & ASYNC_USR_MASK));
1121		state->custom_divisor = new_serial.custom_divisor;
1122		goto check_and_exit;
1123	}
1124
1125	if (new_serial.baud_base < 9600)
1126		return -EINVAL;
1127
1128	/*
1129	 * OK, past this point, all the error checking has been done.
1130	 * At this point, we start making changes.....
1131	 */
1132
1133	state->baud_base = new_serial.baud_base;
1134	state->flags = ((state->flags & ~ASYNC_FLAGS) |
1135			(new_serial.flags & ASYNC_FLAGS));
1136	info->flags = ((state->flags & ~ASYNC_INTERNAL_FLAGS) |
1137		       (info->flags & ASYNC_INTERNAL_FLAGS));
1138	state->custom_divisor = new_serial.custom_divisor;
1139	state->close_delay = new_serial.close_delay * HZ/100;
1140	state->closing_wait = new_serial.closing_wait * HZ/100;
1141	info->tty->low_latency = (info->flags & ASYNC_LOW_LATENCY) ? 1 : 0;
1142
1143check_and_exit:
1144	if (info->flags & ASYNC_INITIALIZED) {
1145		if (((old_state.flags & ASYNC_SPD_MASK) !=
1146		     (state->flags & ASYNC_SPD_MASK)) ||
1147		    (old_state.custom_divisor != state->custom_divisor)) {
1148			if ((state->flags & ASYNC_SPD_MASK) == ASYNC_SPD_HI)
1149				info->tty->alt_speed = 57600;
1150			if ((state->flags & ASYNC_SPD_MASK) == ASYNC_SPD_VHI)
1151				info->tty->alt_speed = 115200;
1152			if ((state->flags & ASYNC_SPD_MASK) == ASYNC_SPD_SHI)
1153				info->tty->alt_speed = 230400;
1154			if ((state->flags & ASYNC_SPD_MASK) == ASYNC_SPD_WARP)
1155				info->tty->alt_speed = 460800;
1156			change_speed(info, NULL);
1157		}
1158	} else
1159		retval = startup(info);
1160	return retval;
1161}
1162
1163
1164/*
1165 * get_lsr_info - get line status register info
1166 *
1167 * Purpose: Let user call ioctl() to get info when the UART physically
1168 * 	    is emptied.  On bus types like RS485, the transmitter must
1169 * 	    release the bus after transmitting. This must be done when
1170 * 	    the transmit shift register is empty, not be done when the
1171 * 	    transmit holding register is empty.  This functionality
1172 * 	    allows an RS485 driver to be written in user space.
1173 */
1174static int get_lsr_info(struct async_struct * info, unsigned int __user *value)
1175{
1176	unsigned char status;
1177	unsigned int result;
1178	unsigned long flags;
1179
1180	local_irq_save(flags);
1181	status = custom.serdatr;
1182	mb();
1183	local_irq_restore(flags);
1184	result = ((status & SDR_TSRE) ? TIOCSER_TEMT : 0);
1185	if (copy_to_user(value, &result, sizeof(int)))
1186		return -EFAULT;
1187	return 0;
1188}
1189
1190
1191static int rs_tiocmget(struct tty_struct *tty, struct file *file)
1192{
1193	struct async_struct * info = (struct async_struct *)tty->driver_data;
1194	unsigned char control, status;
1195	unsigned long flags;
1196
1197	if (serial_paranoia_check(info, tty->name, "rs_ioctl"))
1198		return -ENODEV;
1199	if (tty->flags & (1 << TTY_IO_ERROR))
1200		return -EIO;
1201
1202	control = info->MCR;
1203	local_irq_save(flags);
1204	status = ciab.pra;
1205	local_irq_restore(flags);
1206	return    ((control & SER_RTS) ? TIOCM_RTS : 0)
1207		| ((control & SER_DTR) ? TIOCM_DTR : 0)
1208		| (!(status  & SER_DCD) ? TIOCM_CAR : 0)
1209		| (!(status  & SER_DSR) ? TIOCM_DSR : 0)
1210		| (!(status  & SER_CTS) ? TIOCM_CTS : 0);
1211}
1212
1213static int rs_tiocmset(struct tty_struct *tty, struct file *file,
1214		       unsigned int set, unsigned int clear)
1215{
1216	struct async_struct * info = (struct async_struct *)tty->driver_data;
1217	unsigned long flags;
1218
1219	if (serial_paranoia_check(info, tty->name, "rs_ioctl"))
1220		return -ENODEV;
1221	if (tty->flags & (1 << TTY_IO_ERROR))
1222		return -EIO;
1223
1224	local_irq_save(flags);
1225	if (set & TIOCM_RTS)
1226		info->MCR |= SER_RTS;
1227	if (set & TIOCM_DTR)
1228		info->MCR |= SER_DTR;
1229	if (clear & TIOCM_RTS)
1230		info->MCR &= ~SER_RTS;
1231	if (clear & TIOCM_DTR)
1232		info->MCR &= ~SER_DTR;
1233	rtsdtr_ctrl(info->MCR);
1234	local_irq_restore(flags);
1235	return 0;
1236}
1237
1238/*
1239 * rs_break() --- routine which turns the break handling on or off
1240 */
1241static void rs_break(struct tty_struct *tty, int break_state)
1242{
1243	struct async_struct * info = (struct async_struct *)tty->driver_data;
1244	unsigned long flags;
1245
1246	if (serial_paranoia_check(info, tty->name, "rs_break"))
1247		return;
1248
1249	local_irq_save(flags);
1250	if (break_state == -1)
1251	  custom.adkcon = AC_SETCLR | AC_UARTBRK;
1252	else
1253	  custom.adkcon = AC_UARTBRK;
1254	mb();
1255	local_irq_restore(flags);
1256}
1257
1258
1259static int rs_ioctl(struct tty_struct *tty, struct file * file,
1260		    unsigned int cmd, unsigned long arg)
1261{
1262	struct async_struct * info = (struct async_struct *)tty->driver_data;
1263	struct async_icount cprev, cnow;	/* kernel counter temps */
1264	struct serial_icounter_struct icount;
1265	void __user *argp = (void __user *)arg;
1266	unsigned long flags;
1267
1268	if (serial_paranoia_check(info, tty->name, "rs_ioctl"))
1269		return -ENODEV;
1270
1271	if ((cmd != TIOCGSERIAL) && (cmd != TIOCSSERIAL) &&
1272	    (cmd != TIOCSERCONFIG) && (cmd != TIOCSERGSTRUCT) &&
1273	    (cmd != TIOCMIWAIT) && (cmd != TIOCGICOUNT)) {
1274		if (tty->flags & (1 << TTY_IO_ERROR))
1275		    return -EIO;
1276	}
1277
1278	switch (cmd) {
1279		case TIOCGSERIAL:
1280			return get_serial_info(info, argp);
1281		case TIOCSSERIAL:
1282			return set_serial_info(info, argp);
1283		case TIOCSERCONFIG:
1284			return 0;
1285
1286		case TIOCSERGETLSR: /* Get line status register */
1287			return get_lsr_info(info, argp);
1288
1289		case TIOCSERGSTRUCT:
1290			if (copy_to_user(argp,
1291					 info, sizeof(struct async_struct)))
1292				return -EFAULT;
1293			return 0;
1294
1295		/*
1296		 * Wait for any of the 4 modem inputs (DCD,RI,DSR,CTS) to change
1297		 * - mask passed in arg for lines of interest
1298 		 *   (use |'ed TIOCM_RNG/DSR/CD/CTS for masking)
1299		 * Caller should use TIOCGICOUNT to see which one it was
1300		 */
1301		case TIOCMIWAIT:
1302			local_irq_save(flags);
1303			/* note the counters on entry */
1304			cprev = info->state->icount;
1305			local_irq_restore(flags);
1306			while (1) {
1307				interruptible_sleep_on(&info->delta_msr_wait);
1308				/* see if a signal did it */
1309				if (signal_pending(current))
1310					return -ERESTARTSYS;
1311				local_irq_save(flags);
1312				cnow = info->state->icount; /* atomic copy */
1313				local_irq_restore(flags);
1314				if (cnow.rng == cprev.rng && cnow.dsr == cprev.dsr &&
1315				    cnow.dcd == cprev.dcd && cnow.cts == cprev.cts)
1316					return -EIO; /* no change => error */
1317				if ( ((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||
1318				     ((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||
1319				     ((arg & TIOCM_CD)  && (cnow.dcd != cprev.dcd)) ||
1320				     ((arg & TIOCM_CTS) && (cnow.cts != cprev.cts)) ) {
1321					return 0;
1322				}
1323				cprev = cnow;
1324			}
1325			/* NOTREACHED */
1326
1327		/*
1328		 * Get counter of input serial line interrupts (DCD,RI,DSR,CTS)
1329		 * Return: write counters to the user passed counter struct
1330		 * NB: both 1->0 and 0->1 transitions are counted except for
1331		 *     RI where only 0->1 is counted.
1332		 */
1333		case TIOCGICOUNT:
1334			local_irq_save(flags);
1335			cnow = info->state->icount;
1336			local_irq_restore(flags);
1337			icount.cts = cnow.cts;
1338			icount.dsr = cnow.dsr;
1339			icount.rng = cnow.rng;
1340			icount.dcd = cnow.dcd;
1341			icount.rx = cnow.rx;
1342			icount.tx = cnow.tx;
1343			icount.frame = cnow.frame;
1344			icount.overrun = cnow.overrun;
1345			icount.parity = cnow.parity;
1346			icount.brk = cnow.brk;
1347			icount.buf_overrun = cnow.buf_overrun;
1348
1349			if (copy_to_user(argp, &icount, sizeof(icount)))
1350				return -EFAULT;
1351			return 0;
1352		case TIOCSERGWILD:
1353		case TIOCSERSWILD:
1354			/* "setserial -W" is called in Debian boot */
1355			printk ("TIOCSER?WILD ioctl obsolete, ignored.\n");
1356			return 0;
1357
1358		default:
1359			return -ENOIOCTLCMD;
1360		}
1361	return 0;
1362}
1363
1364static void rs_set_termios(struct tty_struct *tty, struct ktermios *old_termios)
1365{
1366	struct async_struct *info = (struct async_struct *)tty->driver_data;
1367	unsigned long flags;
1368	unsigned int cflag = tty->termios->c_cflag;
1369
1370	if (   (cflag == old_termios->c_cflag)
1371	    && (   RELEVANT_IFLAG(tty->termios->c_iflag)
1372		== RELEVANT_IFLAG(old_termios->c_iflag)))
1373	  return;
1374
1375	change_speed(info, old_termios);
1376
1377	/* Handle transition to B0 status */
1378	if ((old_termios->c_cflag & CBAUD) &&
1379	    !(cflag & CBAUD)) {
1380		info->MCR &= ~(SER_DTR|SER_RTS);
1381		local_irq_save(flags);
1382		rtsdtr_ctrl(info->MCR);
1383		local_irq_restore(flags);
1384	}
1385
1386	/* Handle transition away from B0 status */
1387	if (!(old_termios->c_cflag & CBAUD) &&
1388	    (cflag & CBAUD)) {
1389		info->MCR |= SER_DTR;
1390		if (!(tty->termios->c_cflag & CRTSCTS) ||
1391		    !test_bit(TTY_THROTTLED, &tty->flags)) {
1392			info->MCR |= SER_RTS;
1393		}
1394		local_irq_save(flags);
1395		rtsdtr_ctrl(info->MCR);
1396		local_irq_restore(flags);
1397	}
1398
1399	/* Handle turning off CRTSCTS */
1400	if ((old_termios->c_cflag & CRTSCTS) &&
1401	    !(tty->termios->c_cflag & CRTSCTS)) {
1402		tty->hw_stopped = 0;
1403		rs_start(tty);
1404	}
1405
1406}
1407
1408/*
1409 * ------------------------------------------------------------
1410 * rs_close()
1411 *
1412 * This routine is called when the serial port gets closed.  First, we
1413 * wait for the last remaining data to be sent.  Then, we unlink its
1414 * async structure from the interrupt chain if necessary, and we free
1415 * that IRQ if nothing is left in the chain.
1416 * ------------------------------------------------------------
1417 */
1418static void rs_close(struct tty_struct *tty, struct file * filp)
1419{
1420	struct async_struct * info = (struct async_struct *)tty->driver_data;
1421	struct serial_state *state;
1422	unsigned long flags;
1423
1424	if (!info || serial_paranoia_check(info, tty->name, "rs_close"))
1425		return;
1426
1427	state = info->state;
1428
1429	local_irq_save(flags);
1430
1431	if (tty_hung_up_p(filp)) {
1432		DBG_CNT("before DEC-hung");
1433		local_irq_restore(flags);
1434		return;
1435	}
1436
1437#ifdef SERIAL_DEBUG_OPEN
1438	printk("rs_close ttys%d, count = %d\n", info->line, state->count);
1439#endif
1440	if ((tty->count == 1) && (state->count != 1)) {
1441		/*
1442		 * Uh, oh.  tty->count is 1, which means that the tty
1443		 * structure will be freed.  state->count should always
1444		 * be one in these conditions.  If it's greater than
1445		 * one, we've got real problems, since it means the
1446		 * serial port won't be shutdown.
1447		 */
1448		printk("rs_close: bad serial port count; tty->count is 1, "
1449		       "state->count is %d\n", state->count);
1450		state->count = 1;
1451	}
1452	if (--state->count < 0) {
1453		printk("rs_close: bad serial port count for ttys%d: %d\n",
1454		       info->line, state->count);
1455		state->count = 0;
1456	}
1457	if (state->count) {
1458		DBG_CNT("before DEC-2");
1459		local_irq_restore(flags);
1460		return;
1461	}
1462	info->flags |= ASYNC_CLOSING;
1463	/*
1464	 * Now we wait for the transmit buffer to clear; and we notify
1465	 * the line discipline to only process XON/XOFF characters.
1466	 */
1467	tty->closing = 1;
1468	if (info->closing_wait != ASYNC_CLOSING_WAIT_NONE)
1469		tty_wait_until_sent(tty, info->closing_wait);
1470	/*
1471	 * At this point we stop accepting input.  To do this, we
1472	 * disable the receive line status interrupts, and tell the
1473	 * interrupt driver to stop checking the data ready bit in the
1474	 * line status register.
1475	 */
1476	info->read_status_mask &= ~UART_LSR_DR;
1477	if (info->flags & ASYNC_INITIALIZED) {
1478	        /* disable receive interrupts */
1479	        custom.intena = IF_RBF;
1480		mb();
1481		/* clear any pending receive interrupt */
1482		custom.intreq = IF_RBF;
1483		mb();
1484
1485		/*
1486		 * Before we drop DTR, make sure the UART transmitter
1487		 * has completely drained; this is especially
1488		 * important if there is a transmit FIFO!
1489		 */
1490		rs_wait_until_sent(tty, info->timeout);
1491	}
1492	shutdown(info);
1493	if (tty->driver->flush_buffer)
1494		tty->driver->flush_buffer(tty);
1495
1496	tty_ldisc_flush(tty);
1497	tty->closing = 0;
1498	info->event = 0;
1499	info->tty = NULL;
1500	if (info->blocked_open) {
1501		if (info->close_delay) {
1502			msleep_interruptible(jiffies_to_msecs(info->close_delay));
1503		}
1504		wake_up_interruptible(&info->open_wait);
1505	}
1506	info->flags &= ~(ASYNC_NORMAL_ACTIVE|ASYNC_CLOSING);
1507	wake_up_interruptible(&info->close_wait);
1508	local_irq_restore(flags);
1509}
1510
1511/*
1512 * rs_wait_until_sent() --- wait until the transmitter is empty
1513 */
1514static void rs_wait_until_sent(struct tty_struct *tty, int timeout)
1515{
1516	struct async_struct * info = (struct async_struct *)tty->driver_data;
1517	unsigned long orig_jiffies, char_time;
1518	int lsr;
1519
1520	if (serial_paranoia_check(info, tty->name, "rs_wait_until_sent"))
1521		return;
1522
1523	if (info->xmit_fifo_size == 0)
1524		return; /* Just in case.... */
1525
1526	orig_jiffies = jiffies;
1527	/*
1528	 * Set the check interval to be 1/5 of the estimated time to
1529	 * send a single character, and make it at least 1.  The check
1530	 * interval should also be less than the timeout.
1531	 *
1532	 * Note: we have to use pretty tight timings here to satisfy
1533	 * the NIST-PCTS.
1534	 */
1535	char_time = (info->timeout - HZ/50) / info->xmit_fifo_size;
1536	char_time = char_time / 5;
1537	if (char_time == 0)
1538		char_time = 1;
1539	if (timeout)
1540	  char_time = min_t(unsigned long, char_time, timeout);
1541	/*
1542	 * If the transmitter hasn't cleared in twice the approximate
1543	 * amount of time to send the entire FIFO, it probably won't
1544	 * ever clear.  This assumes the UART isn't doing flow
1545	 * control, which is currently the case.  Hence, if it ever
1546	 * takes longer than info->timeout, this is probably due to a
1547	 * UART bug of some kind.  So, we clamp the timeout parameter at
1548	 * 2*info->timeout.
1549	 */
1550	if (!timeout || timeout > 2*info->timeout)
1551		timeout = 2*info->timeout;
1552#ifdef SERIAL_DEBUG_RS_WAIT_UNTIL_SENT
1553	printk("In rs_wait_until_sent(%d) check=%lu...", timeout, char_time);
1554	printk("jiff=%lu...", jiffies);
1555#endif
1556	while(!((lsr = custom.serdatr) & SDR_TSRE)) {
1557#ifdef SERIAL_DEBUG_RS_WAIT_UNTIL_SENT
1558		printk("serdatr = %d (jiff=%lu)...", lsr, jiffies);
1559#endif
1560		msleep_interruptible(jiffies_to_msecs(char_time));
1561		if (signal_pending(current))
1562			break;
1563		if (timeout && time_after(jiffies, orig_jiffies + timeout))
1564			break;
1565	}
1566	__set_current_state(TASK_RUNNING);
1567#ifdef SERIAL_DEBUG_RS_WAIT_UNTIL_SENT
1568	printk("lsr = %d (jiff=%lu)...done\n", lsr, jiffies);
1569#endif
1570}
1571
1572/*
1573 * rs_hangup() --- called by tty_hangup() when a hangup is signaled.
1574 */
1575static void rs_hangup(struct tty_struct *tty)
1576{
1577	struct async_struct * info = (struct async_struct *)tty->driver_data;
1578	struct serial_state *state = info->state;
1579
1580	if (serial_paranoia_check(info, tty->name, "rs_hangup"))
1581		return;
1582
1583	state = info->state;
1584
1585	rs_flush_buffer(tty);
1586	shutdown(info);
1587	info->event = 0;
1588	state->count = 0;
1589	info->flags &= ~ASYNC_NORMAL_ACTIVE;
1590	info->tty = NULL;
1591	wake_up_interruptible(&info->open_wait);
1592}
1593
1594/*
1595 * ------------------------------------------------------------
1596 * rs_open() and friends
1597 * ------------------------------------------------------------
1598 */
1599static int block_til_ready(struct tty_struct *tty, struct file * filp,
1600			   struct async_struct *info)
1601{
1602#ifdef DECLARE_WAITQUEUE
1603	DECLARE_WAITQUEUE(wait, current);
1604#else
1605	struct wait_queue wait = { current, NULL };
1606#endif
1607	struct serial_state *state = info->state;
1608	int		retval;
1609	int		do_clocal = 0, extra_count = 0;
1610	unsigned long	flags;
1611
1612	/*
1613	 * If the device is in the middle of being closed, then block
1614	 * until it's done, and then try again.
1615	 */
1616	if (tty_hung_up_p(filp) ||
1617	    (info->flags & ASYNC_CLOSING)) {
1618		if (info->flags & ASYNC_CLOSING)
1619			interruptible_sleep_on(&info->close_wait);
1620#ifdef SERIAL_DO_RESTART
1621		return ((info->flags & ASYNC_HUP_NOTIFY) ?
1622			-EAGAIN : -ERESTARTSYS);
1623#else
1624		return -EAGAIN;
1625#endif
1626	}
1627
1628	/*
1629	 * If non-blocking mode is set, or the port is not enabled,
1630	 * then make the check up front and then exit.
1631	 */
1632	if ((filp->f_flags & O_NONBLOCK) ||
1633	    (tty->flags & (1 << TTY_IO_ERROR))) {
1634		info->flags |= ASYNC_NORMAL_ACTIVE;
1635		return 0;
1636	}
1637
1638	if (tty->termios->c_cflag & CLOCAL)
1639		do_clocal = 1;
1640
1641	/*
1642	 * Block waiting for the carrier detect and the line to become
1643	 * free (i.e., not in use by the callout).  While we are in
1644	 * this loop, state->count is dropped by one, so that
1645	 * rs_close() knows when to free things.  We restore it upon
1646	 * exit, either normal or abnormal.
1647	 */
1648	retval = 0;
1649	add_wait_queue(&info->open_wait, &wait);
1650#ifdef SERIAL_DEBUG_OPEN
1651	printk("block_til_ready before block: ttys%d, count = %d\n",
1652	       state->line, state->count);
1653#endif
1654	local_irq_save(flags);
1655	if (!tty_hung_up_p(filp)) {
1656		extra_count = 1;
1657		state->count--;
1658	}
1659	local_irq_restore(flags);
1660	info->blocked_open++;
1661	while (1) {
1662		local_irq_save(flags);
1663		if (tty->termios->c_cflag & CBAUD)
1664		        rtsdtr_ctrl(SER_DTR|SER_RTS);
1665		local_irq_restore(flags);
1666		set_current_state(TASK_INTERRUPTIBLE);
1667		if (tty_hung_up_p(filp) ||
1668		    !(info->flags & ASYNC_INITIALIZED)) {
1669#ifdef SERIAL_DO_RESTART
1670			if (info->flags & ASYNC_HUP_NOTIFY)
1671				retval = -EAGAIN;
1672			else
1673				retval = -ERESTARTSYS;
1674#else
1675			retval = -EAGAIN;
1676#endif
1677			break;
1678		}
1679		if (!(info->flags & ASYNC_CLOSING) &&
1680		    (do_clocal || (!(ciab.pra & SER_DCD)) ))
1681			break;
1682		if (signal_pending(current)) {
1683			retval = -ERESTARTSYS;
1684			break;
1685		}
1686#ifdef SERIAL_DEBUG_OPEN
1687		printk("block_til_ready blocking: ttys%d, count = %d\n",
1688		       info->line, state->count);
1689#endif
1690		schedule();
1691	}
1692	__set_current_state(TASK_RUNNING);
1693	remove_wait_queue(&info->open_wait, &wait);
1694	if (extra_count)
1695		state->count++;
1696	info->blocked_open--;
1697#ifdef SERIAL_DEBUG_OPEN
1698	printk("block_til_ready after blocking: ttys%d, count = %d\n",
1699	       info->line, state->count);
1700#endif
1701	if (retval)
1702		return retval;
1703	info->flags |= ASYNC_NORMAL_ACTIVE;
1704	return 0;
1705}
1706
1707static int get_async_struct(int line, struct async_struct **ret_info)
1708{
1709	struct async_struct *info;
1710	struct serial_state *sstate;
1711
1712	sstate = rs_table + line;
1713	sstate->count++;
1714	if (sstate->info) {
1715		*ret_info = sstate->info;
1716		return 0;
1717	}
1718	info = kmalloc(sizeof(struct async_struct), GFP_KERNEL);
1719	if (!info) {
1720		sstate->count--;
1721		return -ENOMEM;
1722	}
1723	memset(info, 0, sizeof(struct async_struct));
1724#ifdef DECLARE_WAITQUEUE
1725	init_waitqueue_head(&info->open_wait);
1726	init_waitqueue_head(&info->close_wait);
1727	init_waitqueue_head(&info->delta_msr_wait);
1728#endif
1729	info->magic = SERIAL_MAGIC;
1730	info->port = sstate->port;
1731	info->flags = sstate->flags;
1732	info->xmit_fifo_size = sstate->xmit_fifo_size;
1733	info->line = line;
1734	tasklet_init(&info->tlet, do_softint, (unsigned long)info);
1735	info->state = sstate;
1736	if (sstate->info) {
1737		kfree(info);
1738		*ret_info = sstate->info;
1739		return 0;
1740	}
1741	*ret_info = sstate->info = info;
1742	return 0;
1743}
1744
1745/*
1746 * This routine is called whenever a serial port is opened.  It
1747 * enables interrupts for a serial port, linking in its async structure into
1748 * the IRQ chain.   It also performs the serial-specific
1749 * initialization for the tty structure.
1750 */
1751static int rs_open(struct tty_struct *tty, struct file * filp)
1752{
1753	struct async_struct	*info;
1754	int 			retval, line;
1755
1756	line = tty->index;
1757	if ((line < 0) || (line >= NR_PORTS)) {
1758		return -ENODEV;
1759	}
1760	retval = get_async_struct(line, &info);
1761	if (retval) {
1762		return retval;
1763	}
1764	tty->driver_data = info;
1765	info->tty = tty;
1766	if (serial_paranoia_check(info, tty->name, "rs_open"))
1767		return -ENODEV;
1768
1769#ifdef SERIAL_DEBUG_OPEN
1770	printk("rs_open %s, count = %d\n", tty->name, info->state->count);
1771#endif
1772	info->tty->low_latency = (info->flags & ASYNC_LOW_LATENCY) ? 1 : 0;
1773
1774	/*
1775	 * If the port is the middle of closing, bail out now
1776	 */
1777	if (tty_hung_up_p(filp) ||
1778	    (info->flags & ASYNC_CLOSING)) {
1779		if (info->flags & ASYNC_CLOSING)
1780			interruptible_sleep_on(&info->close_wait);
1781#ifdef SERIAL_DO_RESTART
1782		return ((info->flags & ASYNC_HUP_NOTIFY) ?
1783			-EAGAIN : -ERESTARTSYS);
1784#else
1785		return -EAGAIN;
1786#endif
1787	}
1788
1789	/*
1790	 * Start up serial port
1791	 */
1792	retval = startup(info);
1793	if (retval) {
1794		return retval;
1795	}
1796
1797	retval = block_til_ready(tty, filp, info);
1798	if (retval) {
1799#ifdef SERIAL_DEBUG_OPEN
1800		printk("rs_open returning after block_til_ready with %d\n",
1801		       retval);
1802#endif
1803		return retval;
1804	}
1805
1806#ifdef SERIAL_DEBUG_OPEN
1807	printk("rs_open %s successful...", tty->name);
1808#endif
1809	return 0;
1810}
1811
1812/*
1813 * /proc fs routines....
1814 */
1815
1816static inline int line_info(char *buf, struct serial_state *state)
1817{
1818	struct async_struct *info = state->info, scr_info;
1819	char	stat_buf[30], control, status;
1820	int	ret;
1821	unsigned long flags;
1822
1823	ret = sprintf(buf, "%d: uart:amiga_builtin",state->line);
1824
1825	/*
1826	 * Figure out the current RS-232 lines
1827	 */
1828	if (!info) {
1829		info = &scr_info;	/* This is just for serial_{in,out} */
1830
1831		info->magic = SERIAL_MAGIC;
1832		info->flags = state->flags;
1833		info->quot = 0;
1834		info->tty = NULL;
1835	}
1836	local_irq_save(flags);
1837	status = ciab.pra;
1838	control = info ? info->MCR : status;
1839	local_irq_restore(flags);
1840
1841	stat_buf[0] = 0;
1842	stat_buf[1] = 0;
1843	if(!(control & SER_RTS))
1844		strcat(stat_buf, "|RTS");
1845	if(!(status & SER_CTS))
1846		strcat(stat_buf, "|CTS");
1847	if(!(control & SER_DTR))
1848		strcat(stat_buf, "|DTR");
1849	if(!(status & SER_DSR))
1850		strcat(stat_buf, "|DSR");
1851	if(!(status & SER_DCD))
1852		strcat(stat_buf, "|CD");
1853
1854	if (info->quot) {
1855		ret += sprintf(buf+ret, " baud:%d",
1856			       state->baud_base / info->quot);
1857	}
1858
1859	ret += sprintf(buf+ret, " tx:%d rx:%d",
1860		      state->icount.tx, state->icount.rx);
1861
1862	if (state->icount.frame)
1863		ret += sprintf(buf+ret, " fe:%d", state->icount.frame);
1864
1865	if (state->icount.parity)
1866		ret += sprintf(buf+ret, " pe:%d", state->icount.parity);
1867
1868	if (state->icount.brk)
1869		ret += sprintf(buf+ret, " brk:%d", state->icount.brk);
1870
1871	if (state->icount.overrun)
1872		ret += sprintf(buf+ret, " oe:%d", state->icount.overrun);
1873
1874	/*
1875	 * Last thing is the RS-232 status lines
1876	 */
1877	ret += sprintf(buf+ret, " %s\n", stat_buf+1);
1878	return ret;
1879}
1880
1881static int rs_read_proc(char *page, char **start, off_t off, int count,
1882			int *eof, void *data)
1883{
1884	int len = 0, l;
1885	off_t	begin = 0;
1886
1887	len += sprintf(page, "serinfo:1.0 driver:%s\n", serial_version);
1888	l = line_info(page + len, &rs_table[0]);
1889	len += l;
1890	if (len+begin > off+count)
1891	  goto done;
1892	if (len+begin < off) {
1893	  begin += len;
1894	  len = 0;
1895	}
1896	*eof = 1;
1897done:
1898	if (off >= len+begin)
1899		return 0;
1900	*start = page + (off-begin);
1901	return ((count < begin+len-off) ? count : begin+len-off);
1902}
1903
1904/*
1905 * ---------------------------------------------------------------------
1906 * rs_init() and friends
1907 *
1908 * rs_init() is called at boot-time to initialize the serial driver.
1909 * ---------------------------------------------------------------------
1910 */
1911
1912/*
1913 * This routine prints out the appropriate serial driver version
1914 * number, and identifies which options were configured into this
1915 * driver.
1916 */
1917static void show_serial_version(void)
1918{
1919 	printk(KERN_INFO "%s version %s\n", serial_name, serial_version);
1920}
1921
1922
1923static const struct tty_operations serial_ops = {
1924	.open = rs_open,
1925	.close = rs_close,
1926	.write = rs_write,
1927	.put_char = rs_put_char,
1928	.flush_chars = rs_flush_chars,
1929	.write_room = rs_write_room,
1930	.chars_in_buffer = rs_chars_in_buffer,
1931	.flush_buffer = rs_flush_buffer,
1932	.ioctl = rs_ioctl,
1933	.throttle = rs_throttle,
1934	.unthrottle = rs_unthrottle,
1935	.set_termios = rs_set_termios,
1936	.stop = rs_stop,
1937	.start = rs_start,
1938	.hangup = rs_hangup,
1939	.break_ctl = rs_break,
1940	.send_xchar = rs_send_xchar,
1941	.wait_until_sent = rs_wait_until_sent,
1942	.read_proc = rs_read_proc,
1943	.tiocmget = rs_tiocmget,
1944	.tiocmset = rs_tiocmset,
1945};
1946
1947/*
1948 * The serial driver boot-time initialization code!
1949 */
1950static int __init rs_init(void)
1951{
1952	unsigned long flags;
1953	struct serial_state * state;
1954
1955	if (!MACH_IS_AMIGA || !AMIGAHW_PRESENT(AMI_SERIAL))
1956		return -ENODEV;
1957
1958	serial_driver = alloc_tty_driver(1);
1959	if (!serial_driver)
1960		return -ENOMEM;
1961
1962	/*
1963	 *  We request SERDAT and SERPER only, because the serial registers are
1964	 *  too spreaded over the custom register space
1965	 */
1966	if (!request_mem_region(CUSTOM_PHYSADDR+0x30, 4, "amiserial [Paula]"))
1967		return -EBUSY;
1968
1969	IRQ_ports = NULL;
1970
1971	show_serial_version();
1972
1973	/* Initialize the tty_driver structure */
1974
1975	serial_driver->owner = THIS_MODULE;
1976	serial_driver->driver_name = "amiserial";
1977	serial_driver->name = "ttyS";
1978	serial_driver->major = TTY_MAJOR;
1979	serial_driver->minor_start = 64;
1980	serial_driver->type = TTY_DRIVER_TYPE_SERIAL;
1981	serial_driver->subtype = SERIAL_TYPE_NORMAL;
1982	serial_driver->init_termios = tty_std_termios;
1983	serial_driver->init_termios.c_cflag =
1984		B9600 | CS8 | CREAD | HUPCL | CLOCAL;
1985	serial_driver->flags = TTY_DRIVER_REAL_RAW;
1986	tty_set_operations(serial_driver, &serial_ops);
1987
1988	if (tty_register_driver(serial_driver))
1989		panic("Couldn't register serial driver\n");
1990
1991	state = rs_table;
1992	state->magic = SSTATE_MAGIC;
1993	state->port = (int)&custom.serdatr; /* Just to give it a value */
1994	state->line = 0;
1995	state->custom_divisor = 0;
1996	state->close_delay = 5*HZ/10;
1997	state->closing_wait = 30*HZ;
1998	state->icount.cts = state->icount.dsr =
1999	  state->icount.rng = state->icount.dcd = 0;
2000	state->icount.rx = state->icount.tx = 0;
2001	state->icount.frame = state->icount.parity = 0;
2002	state->icount.overrun = state->icount.brk = 0;
2003
2004	printk(KERN_INFO "ttyS%d is the amiga builtin serial port\n",
2005		       state->line);
2006
2007	/* Hardware set up */
2008
2009	state->baud_base = amiga_colorclock;
2010	state->xmit_fifo_size = 1;
2011
2012	local_irq_save(flags);
2013
2014	/* set ISRs, and then disable the rx interrupts */
2015	request_irq(IRQ_AMIGA_TBE, ser_tx_int, 0, "serial TX", state);
2016	request_irq(IRQ_AMIGA_RBF, ser_rx_int, IRQF_DISABLED, "serial RX", state);
2017
2018	/* turn off Rx and Tx interrupts */
2019	custom.intena = IF_RBF | IF_TBE;
2020	mb();
2021
2022	/* clear any pending interrupt */
2023	custom.intreq = IF_RBF | IF_TBE;
2024	mb();
2025
2026	local_irq_restore(flags);
2027
2028	/*
2029	 * set the appropriate directions for the modem control flags,
2030	 * and clear RTS and DTR
2031	 */
2032	ciab.ddra |= (SER_DTR | SER_RTS);   /* outputs */
2033	ciab.ddra &= ~(SER_DCD | SER_CTS | SER_DSR);  /* inputs */
2034
2035	return 0;
2036}
2037
2038static __exit void rs_exit(void)
2039{
2040	int error;
2041	struct async_struct *info = rs_table[0].info;
2042
2043	/* printk("Unloading %s: version %s\n", serial_name, serial_version); */
2044	tasklet_kill(&info->tlet);
2045	if ((error = tty_unregister_driver(serial_driver)))
2046		printk("SERIAL: failed to unregister serial driver (%d)\n",
2047		       error);
2048	put_tty_driver(serial_driver);
2049
2050	if (info) {
2051	  rs_table[0].info = NULL;
2052	  kfree(info);
2053	}
2054
2055	release_mem_region(CUSTOM_PHYSADDR+0x30, 4);
2056}
2057
2058module_init(rs_init)
2059module_exit(rs_exit)
2060
2061
2062/*
2063 * ------------------------------------------------------------
2064 * Serial console driver
2065 * ------------------------------------------------------------
2066 */
2067#ifdef CONFIG_SERIAL_CONSOLE
2068
2069static void amiga_serial_putc(char c)
2070{
2071	custom.serdat = (unsigned char)c | 0x100;
2072	while (!(custom.serdatr & 0x2000))
2073		barrier();
2074}
2075
2076/*
2077 *	Print a string to the serial port trying not to disturb
2078 *	any possible real use of the port...
2079 *
2080 *	The console must be locked when we get here.
2081 */
2082static void serial_console_write(struct console *co, const char *s,
2083				unsigned count)
2084{
2085	unsigned short intena = custom.intenar;
2086
2087	custom.intena = IF_TBE;
2088
2089	while (count--) {
2090		if (*s == '\n')
2091			amiga_serial_putc('\r');
2092		amiga_serial_putc(*s++);
2093	}
2094
2095	custom.intena = IF_SETCLR | (intena & IF_TBE);
2096}
2097
2098static struct tty_driver *serial_console_device(struct console *c, int *index)
2099{
2100	*index = 0;
2101	return serial_driver;
2102}
2103
2104static struct console sercons = {
2105	.name =		"ttyS",
2106	.write =	serial_console_write,
2107	.device =	serial_console_device,
2108	.flags =	CON_PRINTBUFFER,
2109	.index =	-1,
2110};
2111
2112/*
2113 *	Register console.
2114 */
2115static int __init amiserial_console_init(void)
2116{
2117	register_console(&sercons);
2118	return 0;
2119}
2120console_initcall(amiserial_console_init);
2121#endif
2122
2123MODULE_LICENSE("GPL");
2124