TTY: fix tty_wait_until_sent on 64-bit machines
[pandora-kernel.git] / drivers / tty / serial / serial_core.c
1 /*
2  *  Driver core for serial ports
3  *
4  *  Based on drivers/char/serial.c, by Linus Torvalds, Theodore Ts'o.
5  *
6  *  Copyright 1999 ARM Limited
7  *  Copyright (C) 2000-2001 Deep Blue Solutions Ltd.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23 #include <linux/module.h>
24 #include <linux/tty.h>
25 #include <linux/slab.h>
26 #include <linux/init.h>
27 #include <linux/console.h>
28 #include <linux/proc_fs.h>
29 #include <linux/seq_file.h>
30 #include <linux/device.h>
31 #include <linux/serial.h> /* for serial_state and serial_icounter_struct */
32 #include <linux/serial_core.h>
33 #include <linux/delay.h>
34 #include <linux/mutex.h>
35
36 #include <asm/irq.h>
37 #include <asm/uaccess.h>
38
39 /*
40  * This is used to lock changes in serial line configuration.
41  */
42 static DEFINE_MUTEX(port_mutex);
43
44 /*
45  * lockdep: port->lock is initialized in two places, but we
46  *          want only one lock-class:
47  */
48 static struct lock_class_key port_lock_key;
49
50 #define HIGH_BITS_OFFSET        ((sizeof(long)-sizeof(int))*8)
51
52 #ifdef CONFIG_SERIAL_CORE_CONSOLE
53 #define uart_console(port)      ((port)->cons && (port)->cons->index == (port)->line)
54 #else
55 #define uart_console(port)      (0)
56 #endif
57
58 static void uart_change_speed(struct tty_struct *tty, struct uart_state *state,
59                                         struct ktermios *old_termios);
60 static void uart_wait_until_sent(struct tty_struct *tty, int timeout);
61 static void uart_change_pm(struct uart_state *state, int pm_state);
62
63 /*
64  * This routine is used by the interrupt handler to schedule processing in
65  * the software interrupt portion of the driver.
66  */
67 void uart_write_wakeup(struct uart_port *port)
68 {
69         struct uart_state *state = port->state;
70         /*
71          * This means you called this function _after_ the port was
72          * closed.  No cookie for you.
73          */
74         BUG_ON(!state);
75         tty_wakeup(state->port.tty);
76 }
77
78 static void uart_stop(struct tty_struct *tty)
79 {
80         struct uart_state *state = tty->driver_data;
81         struct uart_port *port = state->uart_port;
82         unsigned long flags;
83
84         spin_lock_irqsave(&port->lock, flags);
85         port->ops->stop_tx(port);
86         spin_unlock_irqrestore(&port->lock, flags);
87 }
88
89 static void __uart_start(struct tty_struct *tty)
90 {
91         struct uart_state *state = tty->driver_data;
92         struct uart_port *port = state->uart_port;
93
94         if (!uart_circ_empty(&state->xmit) && state->xmit.buf &&
95             !tty->stopped && !tty->hw_stopped)
96                 port->ops->start_tx(port);
97 }
98
99 static void uart_start(struct tty_struct *tty)
100 {
101         struct uart_state *state = tty->driver_data;
102         struct uart_port *port = state->uart_port;
103         unsigned long flags;
104
105         spin_lock_irqsave(&port->lock, flags);
106         __uart_start(tty);
107         spin_unlock_irqrestore(&port->lock, flags);
108 }
109
110 static inline void
111 uart_update_mctrl(struct uart_port *port, unsigned int set, unsigned int clear)
112 {
113         unsigned long flags;
114         unsigned int old;
115
116         spin_lock_irqsave(&port->lock, flags);
117         old = port->mctrl;
118         port->mctrl = (old & ~clear) | set;
119         if (old != port->mctrl)
120                 port->ops->set_mctrl(port, port->mctrl);
121         spin_unlock_irqrestore(&port->lock, flags);
122 }
123
124 #define uart_set_mctrl(port, set)       uart_update_mctrl(port, set, 0)
125 #define uart_clear_mctrl(port, clear)   uart_update_mctrl(port, 0, clear)
126
127 /*
128  * Startup the port.  This will be called once per open.  All calls
129  * will be serialised by the per-port mutex.
130  */
131 static int uart_startup(struct tty_struct *tty, struct uart_state *state, int init_hw)
132 {
133         struct uart_port *uport = state->uart_port;
134         struct tty_port *port = &state->port;
135         unsigned long page;
136         int retval = 0;
137
138         if (port->flags & ASYNC_INITIALIZED)
139                 return 0;
140
141         /*
142          * Set the TTY IO error marker - we will only clear this
143          * once we have successfully opened the port.  Also set
144          * up the tty->alt_speed kludge
145          */
146         set_bit(TTY_IO_ERROR, &tty->flags);
147
148         if (uport->type == PORT_UNKNOWN)
149                 return 0;
150
151         /*
152          * Initialise and allocate the transmit and temporary
153          * buffer.
154          */
155         if (!state->xmit.buf) {
156                 /* This is protected by the per port mutex */
157                 page = get_zeroed_page(GFP_KERNEL);
158                 if (!page)
159                         return -ENOMEM;
160
161                 state->xmit.buf = (unsigned char *) page;
162                 uart_circ_clear(&state->xmit);
163         }
164
165         retval = uport->ops->startup(uport);
166         if (retval == 0) {
167                 if (uart_console(uport) && uport->cons->cflag) {
168                         tty->termios->c_cflag = uport->cons->cflag;
169                         uport->cons->cflag = 0;
170                 }
171                 /*
172                  * Initialise the hardware port settings.
173                  */
174                 uart_change_speed(tty, state, NULL);
175
176                 if (init_hw) {
177                         /*
178                          * Setup the RTS and DTR signals once the
179                          * port is open and ready to respond.
180                          */
181                         if (tty->termios->c_cflag & CBAUD)
182                                 uart_set_mctrl(uport, TIOCM_RTS | TIOCM_DTR);
183                 }
184
185                 if (port->flags & ASYNC_CTS_FLOW) {
186                         spin_lock_irq(&uport->lock);
187                         if (!(uport->ops->get_mctrl(uport) & TIOCM_CTS))
188                                 tty->hw_stopped = 1;
189                         spin_unlock_irq(&uport->lock);
190                 }
191
192                 set_bit(ASYNCB_INITIALIZED, &port->flags);
193
194                 clear_bit(TTY_IO_ERROR, &tty->flags);
195         }
196
197         /*
198          * This is to allow setserial on this port. People may want to set
199          * port/irq/type and then reconfigure the port properly if it failed
200          * now.
201          */
202         if (retval && capable(CAP_SYS_ADMIN))
203                 retval = 0;
204
205         return retval;
206 }
207
208 /*
209  * This routine will shutdown a serial port; interrupts are disabled, and
210  * DTR is dropped if the hangup on close termio flag is on.  Calls to
211  * uart_shutdown are serialised by the per-port semaphore.
212  */
213 static void uart_shutdown(struct tty_struct *tty, struct uart_state *state)
214 {
215         struct uart_port *uport = state->uart_port;
216         struct tty_port *port = &state->port;
217
218         /*
219          * Set the TTY IO error marker
220          */
221         if (tty)
222                 set_bit(TTY_IO_ERROR, &tty->flags);
223
224         if (test_and_clear_bit(ASYNCB_INITIALIZED, &port->flags)) {
225                 /*
226                  * Turn off DTR and RTS early.
227                  */
228                 if (uart_console(uport) && tty)
229                         uport->cons->cflag = tty->termios->c_cflag;
230
231                 if (!tty || (tty->termios->c_cflag & HUPCL))
232                         uart_clear_mctrl(uport, TIOCM_DTR | TIOCM_RTS);
233
234                 /*
235                  * clear delta_msr_wait queue to avoid mem leaks: we may free
236                  * the irq here so the queue might never be woken up.  Note
237                  * that we won't end up waiting on delta_msr_wait again since
238                  * any outstanding file descriptors should be pointing at
239                  * hung_up_tty_fops now.
240                  */
241                 wake_up_interruptible(&port->delta_msr_wait);
242
243                 /*
244                  * Free the IRQ and disable the port.
245                  */
246                 uport->ops->shutdown(uport);
247
248                 /*
249                  * Ensure that the IRQ handler isn't running on another CPU.
250                  */
251                 synchronize_irq(uport->irq);
252         }
253
254         /*
255          * It's possible for shutdown to be called after suspend if we get
256          * a DCD drop (hangup) at just the right time.  Clear suspended bit so
257          * we don't try to resume a port that has been shutdown.
258          */
259         clear_bit(ASYNCB_SUSPENDED, &port->flags);
260
261         /*
262          * Free the transmit buffer page.
263          */
264         if (state->xmit.buf) {
265                 free_page((unsigned long)state->xmit.buf);
266                 state->xmit.buf = NULL;
267         }
268 }
269
270 /**
271  *      uart_update_timeout - update per-port FIFO timeout.
272  *      @port:  uart_port structure describing the port
273  *      @cflag: termios cflag value
274  *      @baud:  speed of the port
275  *
276  *      Set the port FIFO timeout value.  The @cflag value should
277  *      reflect the actual hardware settings.
278  */
279 void
280 uart_update_timeout(struct uart_port *port, unsigned int cflag,
281                     unsigned int baud)
282 {
283         unsigned int bits;
284
285         /* byte size and parity */
286         switch (cflag & CSIZE) {
287         case CS5:
288                 bits = 7;
289                 break;
290         case CS6:
291                 bits = 8;
292                 break;
293         case CS7:
294                 bits = 9;
295                 break;
296         default:
297                 bits = 10;
298                 break; /* CS8 */
299         }
300
301         if (cflag & CSTOPB)
302                 bits++;
303         if (cflag & PARENB)
304                 bits++;
305
306         /*
307          * The total number of bits to be transmitted in the fifo.
308          */
309         bits = bits * port->fifosize;
310
311         /*
312          * Figure the timeout to send the above number of bits.
313          * Add .02 seconds of slop
314          */
315         port->timeout = (HZ * bits) / baud + HZ/50;
316 }
317
318 EXPORT_SYMBOL(uart_update_timeout);
319
320 /**
321  *      uart_get_baud_rate - return baud rate for a particular port
322  *      @port: uart_port structure describing the port in question.
323  *      @termios: desired termios settings.
324  *      @old: old termios (or NULL)
325  *      @min: minimum acceptable baud rate
326  *      @max: maximum acceptable baud rate
327  *
328  *      Decode the termios structure into a numeric baud rate,
329  *      taking account of the magic 38400 baud rate (with spd_*
330  *      flags), and mapping the %B0 rate to 9600 baud.
331  *
332  *      If the new baud rate is invalid, try the old termios setting.
333  *      If it's still invalid, we try 9600 baud.
334  *
335  *      Update the @termios structure to reflect the baud rate
336  *      we're actually going to be using. Don't do this for the case
337  *      where B0 is requested ("hang up").
338  */
339 unsigned int
340 uart_get_baud_rate(struct uart_port *port, struct ktermios *termios,
341                    struct ktermios *old, unsigned int min, unsigned int max)
342 {
343         unsigned int try, baud, altbaud = 38400;
344         int hung_up = 0;
345         upf_t flags = port->flags & UPF_SPD_MASK;
346
347         if (flags == UPF_SPD_HI)
348                 altbaud = 57600;
349         else if (flags == UPF_SPD_VHI)
350                 altbaud = 115200;
351         else if (flags == UPF_SPD_SHI)
352                 altbaud = 230400;
353         else if (flags == UPF_SPD_WARP)
354                 altbaud = 460800;
355
356         for (try = 0; try < 2; try++) {
357                 baud = tty_termios_baud_rate(termios);
358
359                 /*
360                  * The spd_hi, spd_vhi, spd_shi, spd_warp kludge...
361                  * Die! Die! Die!
362                  */
363                 if (try == 0 && baud == 38400)
364                         baud = altbaud;
365
366                 /*
367                  * Special case: B0 rate.
368                  */
369                 if (baud == 0) {
370                         hung_up = 1;
371                         baud = 9600;
372                 }
373
374                 if (baud >= min && baud <= max)
375                         return baud;
376
377                 /*
378                  * Oops, the quotient was zero.  Try again with
379                  * the old baud rate if possible.
380                  */
381                 termios->c_cflag &= ~CBAUD;
382                 if (old) {
383                         baud = tty_termios_baud_rate(old);
384                         if (!hung_up)
385                                 tty_termios_encode_baud_rate(termios,
386                                                                 baud, baud);
387                         old = NULL;
388                         continue;
389                 }
390
391                 /*
392                  * As a last resort, if the range cannot be met then clip to
393                  * the nearest chip supported rate.
394                  */
395                 if (!hung_up) {
396                         if (baud <= min)
397                                 tty_termios_encode_baud_rate(termios,
398                                                         min + 1, min + 1);
399                         else
400                                 tty_termios_encode_baud_rate(termios,
401                                                         max - 1, max - 1);
402                 }
403         }
404         /* Should never happen */
405         WARN_ON(1);
406         return 0;
407 }
408
409 EXPORT_SYMBOL(uart_get_baud_rate);
410
411 /**
412  *      uart_get_divisor - return uart clock divisor
413  *      @port: uart_port structure describing the port.
414  *      @baud: desired baud rate
415  *
416  *      Calculate the uart clock divisor for the port.
417  */
418 unsigned int
419 uart_get_divisor(struct uart_port *port, unsigned int baud)
420 {
421         unsigned int quot;
422
423         /*
424          * Old custom speed handling.
425          */
426         if (baud == 38400 && (port->flags & UPF_SPD_MASK) == UPF_SPD_CUST)
427                 quot = port->custom_divisor;
428         else
429                 quot = (port->uartclk + (8 * baud)) / (16 * baud);
430
431         return quot;
432 }
433
434 EXPORT_SYMBOL(uart_get_divisor);
435
436 /* FIXME: Consistent locking policy */
437 static void uart_change_speed(struct tty_struct *tty, struct uart_state *state,
438                                         struct ktermios *old_termios)
439 {
440         struct tty_port *port = &state->port;
441         struct uart_port *uport = state->uart_port;
442         struct ktermios *termios;
443
444         /*
445          * If we have no tty, termios, or the port does not exist,
446          * then we can't set the parameters for this port.
447          */
448         if (!tty || !tty->termios || uport->type == PORT_UNKNOWN)
449                 return;
450
451         termios = tty->termios;
452
453         /*
454          * Set flags based on termios cflag
455          */
456         if (termios->c_cflag & CRTSCTS)
457                 set_bit(ASYNCB_CTS_FLOW, &port->flags);
458         else
459                 clear_bit(ASYNCB_CTS_FLOW, &port->flags);
460
461         if (termios->c_cflag & CLOCAL)
462                 clear_bit(ASYNCB_CHECK_CD, &port->flags);
463         else
464                 set_bit(ASYNCB_CHECK_CD, &port->flags);
465
466         uport->ops->set_termios(uport, termios, old_termios);
467 }
468
469 static inline int __uart_put_char(struct uart_port *port,
470                                 struct circ_buf *circ, unsigned char c)
471 {
472         unsigned long flags;
473         int ret = 0;
474
475         if (!circ->buf)
476                 return 0;
477
478         spin_lock_irqsave(&port->lock, flags);
479         if (uart_circ_chars_free(circ) != 0) {
480                 circ->buf[circ->head] = c;
481                 circ->head = (circ->head + 1) & (UART_XMIT_SIZE - 1);
482                 ret = 1;
483         }
484         spin_unlock_irqrestore(&port->lock, flags);
485         return ret;
486 }
487
488 static int uart_put_char(struct tty_struct *tty, unsigned char ch)
489 {
490         struct uart_state *state = tty->driver_data;
491
492         return __uart_put_char(state->uart_port, &state->xmit, ch);
493 }
494
495 static void uart_flush_chars(struct tty_struct *tty)
496 {
497         uart_start(tty);
498 }
499
500 static int uart_write(struct tty_struct *tty,
501                                         const unsigned char *buf, int count)
502 {
503         struct uart_state *state = tty->driver_data;
504         struct uart_port *port;
505         struct circ_buf *circ;
506         unsigned long flags;
507         int c, ret = 0;
508
509         /*
510          * This means you called this function _after_ the port was
511          * closed.  No cookie for you.
512          */
513         if (!state) {
514                 WARN_ON(1);
515                 return -EL3HLT;
516         }
517
518         port = state->uart_port;
519         circ = &state->xmit;
520
521         if (!circ->buf)
522                 return 0;
523
524         spin_lock_irqsave(&port->lock, flags);
525         while (1) {
526                 c = CIRC_SPACE_TO_END(circ->head, circ->tail, UART_XMIT_SIZE);
527                 if (count < c)
528                         c = count;
529                 if (c <= 0)
530                         break;
531                 memcpy(circ->buf + circ->head, buf, c);
532                 circ->head = (circ->head + c) & (UART_XMIT_SIZE - 1);
533                 buf += c;
534                 count -= c;
535                 ret += c;
536         }
537         spin_unlock_irqrestore(&port->lock, flags);
538
539         uart_start(tty);
540         return ret;
541 }
542
543 static int uart_write_room(struct tty_struct *tty)
544 {
545         struct uart_state *state = tty->driver_data;
546         unsigned long flags;
547         int ret;
548
549         spin_lock_irqsave(&state->uart_port->lock, flags);
550         ret = uart_circ_chars_free(&state->xmit);
551         spin_unlock_irqrestore(&state->uart_port->lock, flags);
552         return ret;
553 }
554
555 static int uart_chars_in_buffer(struct tty_struct *tty)
556 {
557         struct uart_state *state = tty->driver_data;
558         unsigned long flags;
559         int ret;
560
561         spin_lock_irqsave(&state->uart_port->lock, flags);
562         ret = uart_circ_chars_pending(&state->xmit);
563         spin_unlock_irqrestore(&state->uart_port->lock, flags);
564         return ret;
565 }
566
567 static void uart_flush_buffer(struct tty_struct *tty)
568 {
569         struct uart_state *state = tty->driver_data;
570         struct uart_port *port;
571         unsigned long flags;
572
573         /*
574          * This means you called this function _after_ the port was
575          * closed.  No cookie for you.
576          */
577         if (!state) {
578                 WARN_ON(1);
579                 return;
580         }
581
582         port = state->uart_port;
583         pr_debug("uart_flush_buffer(%d) called\n", tty->index);
584
585         spin_lock_irqsave(&port->lock, flags);
586         uart_circ_clear(&state->xmit);
587         if (port->ops->flush_buffer)
588                 port->ops->flush_buffer(port);
589         spin_unlock_irqrestore(&port->lock, flags);
590         tty_wakeup(tty);
591 }
592
593 /*
594  * This function is used to send a high-priority XON/XOFF character to
595  * the device
596  */
597 static void uart_send_xchar(struct tty_struct *tty, char ch)
598 {
599         struct uart_state *state = tty->driver_data;
600         struct uart_port *port = state->uart_port;
601         unsigned long flags;
602
603         if (port->ops->send_xchar)
604                 port->ops->send_xchar(port, ch);
605         else {
606                 port->x_char = ch;
607                 if (ch) {
608                         spin_lock_irqsave(&port->lock, flags);
609                         port->ops->start_tx(port);
610                         spin_unlock_irqrestore(&port->lock, flags);
611                 }
612         }
613 }
614
615 static void uart_throttle(struct tty_struct *tty)
616 {
617         struct uart_state *state = tty->driver_data;
618
619         if (I_IXOFF(tty))
620                 uart_send_xchar(tty, STOP_CHAR(tty));
621
622         if (tty->termios->c_cflag & CRTSCTS)
623                 uart_clear_mctrl(state->uart_port, TIOCM_RTS);
624 }
625
626 static void uart_unthrottle(struct tty_struct *tty)
627 {
628         struct uart_state *state = tty->driver_data;
629         struct uart_port *port = state->uart_port;
630
631         if (I_IXOFF(tty)) {
632                 if (port->x_char)
633                         port->x_char = 0;
634                 else
635                         uart_send_xchar(tty, START_CHAR(tty));
636         }
637
638         if (tty->termios->c_cflag & CRTSCTS)
639                 uart_set_mctrl(port, TIOCM_RTS);
640 }
641
642 static int uart_get_info(struct uart_state *state,
643                          struct serial_struct __user *retinfo)
644 {
645         struct uart_port *uport = state->uart_port;
646         struct tty_port *port = &state->port;
647         struct serial_struct tmp;
648
649         memset(&tmp, 0, sizeof(tmp));
650
651         /* Ensure the state we copy is consistent and no hardware changes
652            occur as we go */
653         mutex_lock(&port->mutex);
654
655         tmp.type            = uport->type;
656         tmp.line            = uport->line;
657         tmp.port            = uport->iobase;
658         if (HIGH_BITS_OFFSET)
659                 tmp.port_high = (long) uport->iobase >> HIGH_BITS_OFFSET;
660         tmp.irq             = uport->irq;
661         tmp.flags           = uport->flags;
662         tmp.xmit_fifo_size  = uport->fifosize;
663         tmp.baud_base       = uport->uartclk / 16;
664         tmp.close_delay     = port->close_delay / 10;
665         tmp.closing_wait    = port->closing_wait == ASYNC_CLOSING_WAIT_NONE ?
666                                 ASYNC_CLOSING_WAIT_NONE :
667                                 port->closing_wait / 10;
668         tmp.custom_divisor  = uport->custom_divisor;
669         tmp.hub6            = uport->hub6;
670         tmp.io_type         = uport->iotype;
671         tmp.iomem_reg_shift = uport->regshift;
672         tmp.iomem_base      = (void *)(unsigned long)uport->mapbase;
673
674         mutex_unlock(&port->mutex);
675
676         if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
677                 return -EFAULT;
678         return 0;
679 }
680
681 static int uart_set_info(struct tty_struct *tty, struct uart_state *state,
682                          struct serial_struct __user *newinfo)
683 {
684         struct serial_struct new_serial;
685         struct uart_port *uport = state->uart_port;
686         struct tty_port *port = &state->port;
687         unsigned long new_port;
688         unsigned int change_irq, change_port, closing_wait;
689         unsigned int old_custom_divisor, close_delay;
690         upf_t old_flags, new_flags;
691         int retval = 0;
692
693         if (copy_from_user(&new_serial, newinfo, sizeof(new_serial)))
694                 return -EFAULT;
695
696         new_port = new_serial.port;
697         if (HIGH_BITS_OFFSET)
698                 new_port += (unsigned long) new_serial.port_high << HIGH_BITS_OFFSET;
699
700         new_serial.irq = irq_canonicalize(new_serial.irq);
701         close_delay = new_serial.close_delay * 10;
702         closing_wait = new_serial.closing_wait == ASYNC_CLOSING_WAIT_NONE ?
703                         ASYNC_CLOSING_WAIT_NONE : new_serial.closing_wait * 10;
704
705         /*
706          * This semaphore protects port->count.  It is also
707          * very useful to prevent opens.  Also, take the
708          * port configuration semaphore to make sure that a
709          * module insertion/removal doesn't change anything
710          * under us.
711          */
712         mutex_lock(&port->mutex);
713
714         change_irq  = !(uport->flags & UPF_FIXED_PORT)
715                 && new_serial.irq != uport->irq;
716
717         /*
718          * Since changing the 'type' of the port changes its resource
719          * allocations, we should treat type changes the same as
720          * IO port changes.
721          */
722         change_port = !(uport->flags & UPF_FIXED_PORT)
723                 && (new_port != uport->iobase ||
724                     (unsigned long)new_serial.iomem_base != uport->mapbase ||
725                     new_serial.hub6 != uport->hub6 ||
726                     new_serial.io_type != uport->iotype ||
727                     new_serial.iomem_reg_shift != uport->regshift ||
728                     new_serial.type != uport->type);
729
730         old_flags = uport->flags;
731         new_flags = new_serial.flags;
732         old_custom_divisor = uport->custom_divisor;
733
734         if (!capable(CAP_SYS_ADMIN)) {
735                 retval = -EPERM;
736                 if (change_irq || change_port ||
737                     (new_serial.baud_base != uport->uartclk / 16) ||
738                     (close_delay != port->close_delay) ||
739                     (closing_wait != port->closing_wait) ||
740                     (new_serial.xmit_fifo_size &&
741                      new_serial.xmit_fifo_size != uport->fifosize) ||
742                     (((new_flags ^ old_flags) & ~UPF_USR_MASK) != 0))
743                         goto exit;
744                 uport->flags = ((uport->flags & ~UPF_USR_MASK) |
745                                (new_flags & UPF_USR_MASK));
746                 uport->custom_divisor = new_serial.custom_divisor;
747                 goto check_and_exit;
748         }
749
750         /*
751          * Ask the low level driver to verify the settings.
752          */
753         if (uport->ops->verify_port)
754                 retval = uport->ops->verify_port(uport, &new_serial);
755
756         if ((new_serial.irq >= nr_irqs) || (new_serial.irq < 0) ||
757             (new_serial.baud_base < 9600))
758                 retval = -EINVAL;
759
760         if (retval)
761                 goto exit;
762
763         if (change_port || change_irq) {
764                 retval = -EBUSY;
765
766                 /*
767                  * Make sure that we are the sole user of this port.
768                  */
769                 if (tty_port_users(port) > 1)
770                         goto exit;
771
772                 /*
773                  * We need to shutdown the serial port at the old
774                  * port/type/irq combination.
775                  */
776                 uart_shutdown(tty, state);
777         }
778
779         if (change_port) {
780                 unsigned long old_iobase, old_mapbase;
781                 unsigned int old_type, old_iotype, old_hub6, old_shift;
782
783                 old_iobase = uport->iobase;
784                 old_mapbase = uport->mapbase;
785                 old_type = uport->type;
786                 old_hub6 = uport->hub6;
787                 old_iotype = uport->iotype;
788                 old_shift = uport->regshift;
789
790                 /*
791                  * Free and release old regions
792                  */
793                 if (old_type != PORT_UNKNOWN)
794                         uport->ops->release_port(uport);
795
796                 uport->iobase = new_port;
797                 uport->type = new_serial.type;
798                 uport->hub6 = new_serial.hub6;
799                 uport->iotype = new_serial.io_type;
800                 uport->regshift = new_serial.iomem_reg_shift;
801                 uport->mapbase = (unsigned long)new_serial.iomem_base;
802
803                 /*
804                  * Claim and map the new regions
805                  */
806                 if (uport->type != PORT_UNKNOWN) {
807                         retval = uport->ops->request_port(uport);
808                 } else {
809                         /* Always success - Jean II */
810                         retval = 0;
811                 }
812
813                 /*
814                  * If we fail to request resources for the
815                  * new port, try to restore the old settings.
816                  */
817                 if (retval && old_type != PORT_UNKNOWN) {
818                         uport->iobase = old_iobase;
819                         uport->type = old_type;
820                         uport->hub6 = old_hub6;
821                         uport->iotype = old_iotype;
822                         uport->regshift = old_shift;
823                         uport->mapbase = old_mapbase;
824                         retval = uport->ops->request_port(uport);
825                         /*
826                          * If we failed to restore the old settings,
827                          * we fail like this.
828                          */
829                         if (retval)
830                                 uport->type = PORT_UNKNOWN;
831
832                         /*
833                          * We failed anyway.
834                          */
835                         retval = -EBUSY;
836                         /* Added to return the correct error -Ram Gupta */
837                         goto exit;
838                 }
839         }
840
841         if (change_irq)
842                 uport->irq      = new_serial.irq;
843         if (!(uport->flags & UPF_FIXED_PORT))
844                 uport->uartclk  = new_serial.baud_base * 16;
845         uport->flags            = (uport->flags & ~UPF_CHANGE_MASK) |
846                                  (new_flags & UPF_CHANGE_MASK);
847         uport->custom_divisor   = new_serial.custom_divisor;
848         port->close_delay     = close_delay;
849         port->closing_wait    = closing_wait;
850         if (new_serial.xmit_fifo_size)
851                 uport->fifosize = new_serial.xmit_fifo_size;
852         if (port->tty)
853                 port->tty->low_latency =
854                         (uport->flags & UPF_LOW_LATENCY) ? 1 : 0;
855
856  check_and_exit:
857         retval = 0;
858         if (uport->type == PORT_UNKNOWN)
859                 goto exit;
860         if (port->flags & ASYNC_INITIALIZED) {
861                 if (((old_flags ^ uport->flags) & UPF_SPD_MASK) ||
862                     old_custom_divisor != uport->custom_divisor) {
863                         /*
864                          * If they're setting up a custom divisor or speed,
865                          * instead of clearing it, then bitch about it. No
866                          * need to rate-limit; it's CAP_SYS_ADMIN only.
867                          */
868                         if (uport->flags & UPF_SPD_MASK) {
869                                 char buf[64];
870                                 printk(KERN_NOTICE
871                                        "%s sets custom speed on %s. This "
872                                        "is deprecated.\n", current->comm,
873                                        tty_name(port->tty, buf));
874                         }
875                         uart_change_speed(tty, state, NULL);
876                 }
877         } else
878                 retval = uart_startup(tty, state, 1);
879  exit:
880         mutex_unlock(&port->mutex);
881         return retval;
882 }
883
884 /**
885  *      uart_get_lsr_info       -       get line status register info
886  *      @tty: tty associated with the UART
887  *      @state: UART being queried
888  *      @value: returned modem value
889  *
890  *      Note: uart_ioctl protects us against hangups.
891  */
892 static int uart_get_lsr_info(struct tty_struct *tty,
893                         struct uart_state *state, unsigned int __user *value)
894 {
895         struct uart_port *uport = state->uart_port;
896         unsigned int result;
897
898         result = uport->ops->tx_empty(uport);
899
900         /*
901          * If we're about to load something into the transmit
902          * register, we'll pretend the transmitter isn't empty to
903          * avoid a race condition (depending on when the transmit
904          * interrupt happens).
905          */
906         if (uport->x_char ||
907             ((uart_circ_chars_pending(&state->xmit) > 0) &&
908              !tty->stopped && !tty->hw_stopped))
909                 result &= ~TIOCSER_TEMT;
910
911         return put_user(result, value);
912 }
913
914 static int uart_tiocmget(struct tty_struct *tty)
915 {
916         struct uart_state *state = tty->driver_data;
917         struct tty_port *port = &state->port;
918         struct uart_port *uport = state->uart_port;
919         int result = -EIO;
920
921         mutex_lock(&port->mutex);
922         if (!(tty->flags & (1 << TTY_IO_ERROR))) {
923                 result = uport->mctrl;
924                 spin_lock_irq(&uport->lock);
925                 result |= uport->ops->get_mctrl(uport);
926                 spin_unlock_irq(&uport->lock);
927         }
928         mutex_unlock(&port->mutex);
929
930         return result;
931 }
932
933 static int
934 uart_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear)
935 {
936         struct uart_state *state = tty->driver_data;
937         struct uart_port *uport = state->uart_port;
938         struct tty_port *port = &state->port;
939         int ret = -EIO;
940
941         mutex_lock(&port->mutex);
942         if (!(tty->flags & (1 << TTY_IO_ERROR))) {
943                 uart_update_mctrl(uport, set, clear);
944                 ret = 0;
945         }
946         mutex_unlock(&port->mutex);
947         return ret;
948 }
949
950 static int uart_break_ctl(struct tty_struct *tty, int break_state)
951 {
952         struct uart_state *state = tty->driver_data;
953         struct tty_port *port = &state->port;
954         struct uart_port *uport = state->uart_port;
955
956         mutex_lock(&port->mutex);
957
958         if (uport->type != PORT_UNKNOWN)
959                 uport->ops->break_ctl(uport, break_state);
960
961         mutex_unlock(&port->mutex);
962         return 0;
963 }
964
965 static int uart_do_autoconfig(struct tty_struct *tty,struct uart_state *state)
966 {
967         struct uart_port *uport = state->uart_port;
968         struct tty_port *port = &state->port;
969         int flags, ret;
970
971         if (!capable(CAP_SYS_ADMIN))
972                 return -EPERM;
973
974         /*
975          * Take the per-port semaphore.  This prevents count from
976          * changing, and hence any extra opens of the port while
977          * we're auto-configuring.
978          */
979         if (mutex_lock_interruptible(&port->mutex))
980                 return -ERESTARTSYS;
981
982         ret = -EBUSY;
983         if (tty_port_users(port) == 1) {
984                 uart_shutdown(tty, state);
985
986                 /*
987                  * If we already have a port type configured,
988                  * we must release its resources.
989                  */
990                 if (uport->type != PORT_UNKNOWN)
991                         uport->ops->release_port(uport);
992
993                 flags = UART_CONFIG_TYPE;
994                 if (uport->flags & UPF_AUTO_IRQ)
995                         flags |= UART_CONFIG_IRQ;
996
997                 /*
998                  * This will claim the ports resources if
999                  * a port is found.
1000                  */
1001                 uport->ops->config_port(uport, flags);
1002
1003                 ret = uart_startup(tty, state, 1);
1004         }
1005         mutex_unlock(&port->mutex);
1006         return ret;
1007 }
1008
1009 /*
1010  * Wait for any of the 4 modem inputs (DCD,RI,DSR,CTS) to change
1011  * - mask passed in arg for lines of interest
1012  *   (use |'ed TIOCM_RNG/DSR/CD/CTS for masking)
1013  * Caller should use TIOCGICOUNT to see which one it was
1014  *
1015  * FIXME: This wants extracting into a common all driver implementation
1016  * of TIOCMWAIT using tty_port.
1017  */
1018 static int
1019 uart_wait_modem_status(struct uart_state *state, unsigned long arg)
1020 {
1021         struct uart_port *uport = state->uart_port;
1022         struct tty_port *port = &state->port;
1023         DECLARE_WAITQUEUE(wait, current);
1024         struct uart_icount cprev, cnow;
1025         int ret;
1026
1027         /*
1028          * note the counters on entry
1029          */
1030         spin_lock_irq(&uport->lock);
1031         memcpy(&cprev, &uport->icount, sizeof(struct uart_icount));
1032
1033         /*
1034          * Force modem status interrupts on
1035          */
1036         uport->ops->enable_ms(uport);
1037         spin_unlock_irq(&uport->lock);
1038
1039         add_wait_queue(&port->delta_msr_wait, &wait);
1040         for (;;) {
1041                 spin_lock_irq(&uport->lock);
1042                 memcpy(&cnow, &uport->icount, sizeof(struct uart_icount));
1043                 spin_unlock_irq(&uport->lock);
1044
1045                 set_current_state(TASK_INTERRUPTIBLE);
1046
1047                 if (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||
1048                     ((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||
1049                     ((arg & TIOCM_CD)  && (cnow.dcd != cprev.dcd)) ||
1050                     ((arg & TIOCM_CTS) && (cnow.cts != cprev.cts))) {
1051                         ret = 0;
1052                         break;
1053                 }
1054
1055                 schedule();
1056
1057                 /* see if a signal did it */
1058                 if (signal_pending(current)) {
1059                         ret = -ERESTARTSYS;
1060                         break;
1061                 }
1062
1063                 cprev = cnow;
1064         }
1065
1066         current->state = TASK_RUNNING;
1067         remove_wait_queue(&port->delta_msr_wait, &wait);
1068
1069         return ret;
1070 }
1071
1072 /*
1073  * Get counter of input serial line interrupts (DCD,RI,DSR,CTS)
1074  * Return: write counters to the user passed counter struct
1075  * NB: both 1->0 and 0->1 transitions are counted except for
1076  *     RI where only 0->1 is counted.
1077  */
1078 static int uart_get_icount(struct tty_struct *tty,
1079                           struct serial_icounter_struct *icount)
1080 {
1081         struct uart_state *state = tty->driver_data;
1082         struct uart_icount cnow;
1083         struct uart_port *uport = state->uart_port;
1084
1085         spin_lock_irq(&uport->lock);
1086         memcpy(&cnow, &uport->icount, sizeof(struct uart_icount));
1087         spin_unlock_irq(&uport->lock);
1088
1089         icount->cts         = cnow.cts;
1090         icount->dsr         = cnow.dsr;
1091         icount->rng         = cnow.rng;
1092         icount->dcd         = cnow.dcd;
1093         icount->rx          = cnow.rx;
1094         icount->tx          = cnow.tx;
1095         icount->frame       = cnow.frame;
1096         icount->overrun     = cnow.overrun;
1097         icount->parity      = cnow.parity;
1098         icount->brk         = cnow.brk;
1099         icount->buf_overrun = cnow.buf_overrun;
1100
1101         return 0;
1102 }
1103
1104 /*
1105  * Called via sys_ioctl.  We can use spin_lock_irq() here.
1106  */
1107 static int
1108 uart_ioctl(struct tty_struct *tty, unsigned int cmd,
1109            unsigned long arg)
1110 {
1111         struct uart_state *state = tty->driver_data;
1112         struct tty_port *port = &state->port;
1113         void __user *uarg = (void __user *)arg;
1114         int ret = -ENOIOCTLCMD;
1115
1116
1117         /*
1118          * These ioctls don't rely on the hardware to be present.
1119          */
1120         switch (cmd) {
1121         case TIOCGSERIAL:
1122                 ret = uart_get_info(state, uarg);
1123                 break;
1124
1125         case TIOCSSERIAL:
1126                 ret = uart_set_info(tty, state, uarg);
1127                 break;
1128
1129         case TIOCSERCONFIG:
1130                 ret = uart_do_autoconfig(tty, state);
1131                 break;
1132
1133         case TIOCSERGWILD: /* obsolete */
1134         case TIOCSERSWILD: /* obsolete */
1135                 ret = 0;
1136                 break;
1137         }
1138
1139         if (ret != -ENOIOCTLCMD)
1140                 goto out;
1141
1142         if (tty->flags & (1 << TTY_IO_ERROR)) {
1143                 ret = -EIO;
1144                 goto out;
1145         }
1146
1147         /*
1148          * The following should only be used when hardware is present.
1149          */
1150         switch (cmd) {
1151         case TIOCMIWAIT:
1152                 ret = uart_wait_modem_status(state, arg);
1153                 break;
1154         }
1155
1156         if (ret != -ENOIOCTLCMD)
1157                 goto out;
1158
1159         mutex_lock(&port->mutex);
1160
1161         if (tty->flags & (1 << TTY_IO_ERROR)) {
1162                 ret = -EIO;
1163                 goto out_up;
1164         }
1165
1166         /*
1167          * All these rely on hardware being present and need to be
1168          * protected against the tty being hung up.
1169          */
1170         switch (cmd) {
1171         case TIOCSERGETLSR: /* Get line status register */
1172                 ret = uart_get_lsr_info(tty, state, uarg);
1173                 break;
1174
1175         default: {
1176                 struct uart_port *uport = state->uart_port;
1177                 if (uport->ops->ioctl)
1178                         ret = uport->ops->ioctl(uport, cmd, arg);
1179                 break;
1180         }
1181         }
1182 out_up:
1183         mutex_unlock(&port->mutex);
1184 out:
1185         return ret;
1186 }
1187
1188 static void uart_set_ldisc(struct tty_struct *tty)
1189 {
1190         struct uart_state *state = tty->driver_data;
1191         struct uart_port *uport = state->uart_port;
1192
1193         if (uport->ops->set_ldisc)
1194                 uport->ops->set_ldisc(uport, tty->termios->c_line);
1195 }
1196
1197 static void uart_set_termios(struct tty_struct *tty,
1198                                                 struct ktermios *old_termios)
1199 {
1200         struct uart_state *state = tty->driver_data;
1201         unsigned long flags;
1202         unsigned int cflag = tty->termios->c_cflag;
1203
1204
1205         /*
1206          * These are the bits that are used to setup various
1207          * flags in the low level driver. We can ignore the Bfoo
1208          * bits in c_cflag; c_[io]speed will always be set
1209          * appropriately by set_termios() in tty_ioctl.c
1210          */
1211 #define RELEVANT_IFLAG(iflag)   ((iflag) & (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK))
1212         if ((cflag ^ old_termios->c_cflag) == 0 &&
1213             tty->termios->c_ospeed == old_termios->c_ospeed &&
1214             tty->termios->c_ispeed == old_termios->c_ispeed &&
1215             RELEVANT_IFLAG(tty->termios->c_iflag ^ old_termios->c_iflag) == 0) {
1216                 return;
1217         }
1218
1219         uart_change_speed(tty, state, old_termios);
1220
1221         /* Handle transition to B0 status */
1222         if ((old_termios->c_cflag & CBAUD) && !(cflag & CBAUD))
1223                 uart_clear_mctrl(state->uart_port, TIOCM_RTS | TIOCM_DTR);
1224         /* Handle transition away from B0 status */
1225         else if (!(old_termios->c_cflag & CBAUD) && (cflag & CBAUD)) {
1226                 unsigned int mask = TIOCM_DTR;
1227                 if (!(cflag & CRTSCTS) ||
1228                     !test_bit(TTY_THROTTLED, &tty->flags))
1229                         mask |= TIOCM_RTS;
1230                 uart_set_mctrl(state->uart_port, mask);
1231         }
1232
1233         /* Handle turning off CRTSCTS */
1234         if ((old_termios->c_cflag & CRTSCTS) && !(cflag & CRTSCTS)) {
1235                 spin_lock_irqsave(&state->uart_port->lock, flags);
1236                 tty->hw_stopped = 0;
1237                 __uart_start(tty);
1238                 spin_unlock_irqrestore(&state->uart_port->lock, flags);
1239         }
1240         /* Handle turning on CRTSCTS */
1241         else if (!(old_termios->c_cflag & CRTSCTS) && (cflag & CRTSCTS)) {
1242                 spin_lock_irqsave(&state->uart_port->lock, flags);
1243                 if (!(state->uart_port->ops->get_mctrl(state->uart_port) & TIOCM_CTS)) {
1244                         tty->hw_stopped = 1;
1245                         state->uart_port->ops->stop_tx(state->uart_port);
1246                 }
1247                 spin_unlock_irqrestore(&state->uart_port->lock, flags);
1248         }
1249 }
1250
1251 /*
1252  * In 2.4.5, calls to this will be serialized via the BKL in
1253  *  linux/drivers/char/tty_io.c:tty_release()
1254  *  linux/drivers/char/tty_io.c:do_tty_handup()
1255  */
1256 static void uart_close(struct tty_struct *tty, struct file *filp)
1257 {
1258         struct uart_state *state = tty->driver_data;
1259         struct tty_port *port;
1260         struct uart_port *uport;
1261         unsigned long flags;
1262
1263         if (!state)
1264                 return;
1265
1266         uport = state->uart_port;
1267         port = &state->port;
1268
1269         pr_debug("uart_close(%d) called\n", uport->line);
1270
1271         spin_lock_irqsave(&port->lock, flags);
1272
1273         if (tty_hung_up_p(filp)) {
1274                 spin_unlock_irqrestore(&port->lock, flags);
1275                 return;
1276         }
1277
1278         if ((tty->count == 1) && (port->count != 1)) {
1279                 /*
1280                  * Uh, oh.  tty->count is 1, which means that the tty
1281                  * structure will be freed.  port->count should always
1282                  * be one in these conditions.  If it's greater than
1283                  * one, we've got real problems, since it means the
1284                  * serial port won't be shutdown.
1285                  */
1286                 printk(KERN_ERR "uart_close: bad serial port count; tty->count is 1, "
1287                        "port->count is %d\n", port->count);
1288                 port->count = 1;
1289         }
1290         if (--port->count < 0) {
1291                 printk(KERN_ERR "uart_close: bad serial port count for %s: %d\n",
1292                        tty->name, port->count);
1293                 port->count = 0;
1294         }
1295         if (port->count) {
1296                 spin_unlock_irqrestore(&port->lock, flags);
1297                 return;
1298         }
1299
1300         /*
1301          * Now we wait for the transmit buffer to clear; and we notify
1302          * the line discipline to only process XON/XOFF characters by
1303          * setting tty->closing.
1304          */
1305         set_bit(ASYNCB_CLOSING, &port->flags);
1306         tty->closing = 1;
1307         spin_unlock_irqrestore(&port->lock, flags);
1308
1309         if (port->closing_wait != ASYNC_CLOSING_WAIT_NONE)
1310                 tty_wait_until_sent_from_close(tty,
1311                                 msecs_to_jiffies(port->closing_wait));
1312
1313         /*
1314          * At this point, we stop accepting input.  To do this, we
1315          * disable the receive line status interrupts.
1316          */
1317         if (port->flags & ASYNC_INITIALIZED) {
1318                 unsigned long flags;
1319                 spin_lock_irqsave(&uport->lock, flags);
1320                 uport->ops->stop_rx(uport);
1321                 spin_unlock_irqrestore(&uport->lock, flags);
1322                 /*
1323                  * Before we drop DTR, make sure the UART transmitter
1324                  * has completely drained; this is especially
1325                  * important if there is a transmit FIFO!
1326                  */
1327                 uart_wait_until_sent(tty, uport->timeout);
1328         }
1329
1330         mutex_lock(&port->mutex);
1331         uart_shutdown(tty, state);
1332         uart_flush_buffer(tty);
1333
1334         tty_ldisc_flush(tty);
1335
1336         tty_port_tty_set(port, NULL);
1337         spin_lock_irqsave(&port->lock, flags);
1338         tty->closing = 0;
1339
1340         if (port->blocked_open) {
1341                 spin_unlock_irqrestore(&port->lock, flags);
1342                 if (port->close_delay)
1343                         msleep_interruptible(port->close_delay);
1344                 spin_lock_irqsave(&port->lock, flags);
1345         } else if (!uart_console(uport)) {
1346                 spin_unlock_irqrestore(&port->lock, flags);
1347                 uart_change_pm(state, 3);
1348                 spin_lock_irqsave(&port->lock, flags);
1349         }
1350
1351         /*
1352          * Wake up anyone trying to open this port.
1353          */
1354         clear_bit(ASYNCB_NORMAL_ACTIVE, &port->flags);
1355         clear_bit(ASYNCB_CLOSING, &port->flags);
1356         spin_unlock_irqrestore(&port->lock, flags);
1357         wake_up_interruptible(&port->open_wait);
1358         wake_up_interruptible(&port->close_wait);
1359
1360         mutex_unlock(&port->mutex);
1361 }
1362
1363 static void uart_wait_until_sent(struct tty_struct *tty, int timeout)
1364 {
1365         struct uart_state *state = tty->driver_data;
1366         struct uart_port *port = state->uart_port;
1367         unsigned long char_time, expire;
1368
1369         if (port->type == PORT_UNKNOWN || port->fifosize == 0)
1370                 return;
1371
1372         /*
1373          * Set the check interval to be 1/5 of the estimated time to
1374          * send a single character, and make it at least 1.  The check
1375          * interval should also be less than the timeout.
1376          *
1377          * Note: we have to use pretty tight timings here to satisfy
1378          * the NIST-PCTS.
1379          */
1380         char_time = (port->timeout - HZ/50) / port->fifosize;
1381         char_time = char_time / 5;
1382         if (char_time == 0)
1383                 char_time = 1;
1384         if (timeout && timeout < char_time)
1385                 char_time = timeout;
1386
1387         /*
1388          * If the transmitter hasn't cleared in twice the approximate
1389          * amount of time to send the entire FIFO, it probably won't
1390          * ever clear.  This assumes the UART isn't doing flow
1391          * control, which is currently the case.  Hence, if it ever
1392          * takes longer than port->timeout, this is probably due to a
1393          * UART bug of some kind.  So, we clamp the timeout parameter at
1394          * 2*port->timeout.
1395          */
1396         if (timeout == 0 || timeout > 2 * port->timeout)
1397                 timeout = 2 * port->timeout;
1398
1399         expire = jiffies + timeout;
1400
1401         pr_debug("uart_wait_until_sent(%d), jiffies=%lu, expire=%lu...\n",
1402                 port->line, jiffies, expire);
1403
1404         /*
1405          * Check whether the transmitter is empty every 'char_time'.
1406          * 'timeout' / 'expire' give us the maximum amount of time
1407          * we wait.
1408          */
1409         while (!port->ops->tx_empty(port)) {
1410                 msleep_interruptible(jiffies_to_msecs(char_time));
1411                 if (signal_pending(current))
1412                         break;
1413                 if (time_after(jiffies, expire))
1414                         break;
1415         }
1416 }
1417
1418 /*
1419  * This is called with the BKL held in
1420  *  linux/drivers/char/tty_io.c:do_tty_hangup()
1421  * We're called from the eventd thread, so we can sleep for
1422  * a _short_ time only.
1423  */
1424 static void uart_hangup(struct tty_struct *tty)
1425 {
1426         struct uart_state *state = tty->driver_data;
1427         struct tty_port *port = &state->port;
1428         unsigned long flags;
1429
1430         pr_debug("uart_hangup(%d)\n", state->uart_port->line);
1431
1432         mutex_lock(&port->mutex);
1433         if (port->flags & ASYNC_NORMAL_ACTIVE) {
1434                 uart_flush_buffer(tty);
1435                 uart_shutdown(tty, state);
1436                 spin_lock_irqsave(&port->lock, flags);
1437                 port->count = 0;
1438                 clear_bit(ASYNCB_NORMAL_ACTIVE, &port->flags);
1439                 spin_unlock_irqrestore(&port->lock, flags);
1440                 tty_port_tty_set(port, NULL);
1441                 wake_up_interruptible(&port->open_wait);
1442                 wake_up_interruptible(&port->delta_msr_wait);
1443         }
1444         mutex_unlock(&port->mutex);
1445 }
1446
1447 static int uart_carrier_raised(struct tty_port *port)
1448 {
1449         struct uart_state *state = container_of(port, struct uart_state, port);
1450         struct uart_port *uport = state->uart_port;
1451         int mctrl;
1452         spin_lock_irq(&uport->lock);
1453         uport->ops->enable_ms(uport);
1454         mctrl = uport->ops->get_mctrl(uport);
1455         spin_unlock_irq(&uport->lock);
1456         if (mctrl & TIOCM_CAR)
1457                 return 1;
1458         return 0;
1459 }
1460
1461 static void uart_dtr_rts(struct tty_port *port, int onoff)
1462 {
1463         struct uart_state *state = container_of(port, struct uart_state, port);
1464         struct uart_port *uport = state->uart_port;
1465
1466         if (onoff)
1467                 uart_set_mctrl(uport, TIOCM_DTR | TIOCM_RTS);
1468         else
1469                 uart_clear_mctrl(uport, TIOCM_DTR | TIOCM_RTS);
1470 }
1471
1472 static struct uart_state *uart_get(struct uart_driver *drv, int line)
1473 {
1474         struct uart_state *state;
1475         struct tty_port *port;
1476         int ret = 0;
1477
1478         state = drv->state + line;
1479         port = &state->port;
1480         if (mutex_lock_interruptible(&port->mutex)) {
1481                 ret = -ERESTARTSYS;
1482                 goto err;
1483         }
1484
1485         port->count++;
1486         if (!state->uart_port || state->uart_port->flags & UPF_DEAD) {
1487                 ret = -ENXIO;
1488                 goto err_unlock;
1489         }
1490         return state;
1491
1492  err_unlock:
1493         port->count--;
1494         mutex_unlock(&port->mutex);
1495  err:
1496         return ERR_PTR(ret);
1497 }
1498
1499 /*
1500  * calls to uart_open are serialised by the BKL in
1501  *   fs/char_dev.c:chrdev_open()
1502  * Note that if this fails, then uart_close() _will_ be called.
1503  *
1504  * In time, we want to scrap the "opening nonpresent ports"
1505  * behaviour and implement an alternative way for setserial
1506  * to set base addresses/ports/types.  This will allow us to
1507  * get rid of a certain amount of extra tests.
1508  */
1509 static int uart_open(struct tty_struct *tty, struct file *filp)
1510 {
1511         struct uart_driver *drv = (struct uart_driver *)tty->driver->driver_state;
1512         struct uart_state *state;
1513         struct tty_port *port;
1514         int retval, line = tty->index;
1515
1516         pr_debug("uart_open(%d) called\n", line);
1517
1518         /*
1519          * We take the semaphore inside uart_get to guarantee that we won't
1520          * be re-entered while allocating the state structure, or while we
1521          * request any IRQs that the driver may need.  This also has the nice
1522          * side-effect that it delays the action of uart_hangup, so we can
1523          * guarantee that state->port.tty will always contain something
1524          * reasonable.
1525          */
1526         state = uart_get(drv, line);
1527         if (IS_ERR(state)) {
1528                 retval = PTR_ERR(state);
1529                 goto fail;
1530         }
1531         port = &state->port;
1532
1533         /*
1534          * Once we set tty->driver_data here, we are guaranteed that
1535          * uart_close() will decrement the driver module use count.
1536          * Any failures from here onwards should not touch the count.
1537          */
1538         tty->driver_data = state;
1539         state->uart_port->state = state;
1540         tty->low_latency = (state->uart_port->flags & UPF_LOW_LATENCY) ? 1 : 0;
1541         tty->alt_speed = 0;
1542         tty_port_tty_set(port, tty);
1543
1544         /*
1545          * If the port is in the middle of closing, bail out now.
1546          */
1547         if (tty_hung_up_p(filp)) {
1548                 retval = -EAGAIN;
1549                 port->count--;
1550                 mutex_unlock(&port->mutex);
1551                 goto fail;
1552         }
1553
1554         /*
1555          * Make sure the device is in D0 state.
1556          */
1557         if (port->count == 1)
1558                 uart_change_pm(state, 0);
1559
1560         /*
1561          * Start up the serial port.
1562          */
1563         retval = uart_startup(tty, state, 0);
1564
1565         /*
1566          * If we succeeded, wait until the port is ready.
1567          */
1568         mutex_unlock(&port->mutex);
1569         if (retval == 0)
1570                 retval = tty_port_block_til_ready(port, tty, filp);
1571
1572 fail:
1573         return retval;
1574 }
1575
1576 static const char *uart_type(struct uart_port *port)
1577 {
1578         const char *str = NULL;
1579
1580         if (port->ops->type)
1581                 str = port->ops->type(port);
1582
1583         if (!str)
1584                 str = "unknown";
1585
1586         return str;
1587 }
1588
1589 #ifdef CONFIG_PROC_FS
1590
1591 static void uart_line_info(struct seq_file *m, struct uart_driver *drv, int i)
1592 {
1593         struct uart_state *state = drv->state + i;
1594         struct tty_port *port = &state->port;
1595         int pm_state;
1596         struct uart_port *uport = state->uart_port;
1597         char stat_buf[32];
1598         unsigned int status;
1599         int mmio;
1600
1601         if (!uport)
1602                 return;
1603
1604         mmio = uport->iotype >= UPIO_MEM;
1605         seq_printf(m, "%d: uart:%s %s%08llX irq:%d",
1606                         uport->line, uart_type(uport),
1607                         mmio ? "mmio:0x" : "port:",
1608                         mmio ? (unsigned long long)uport->mapbase
1609                              : (unsigned long long)uport->iobase,
1610                         uport->irq);
1611
1612         if (uport->type == PORT_UNKNOWN) {
1613                 seq_putc(m, '\n');
1614                 return;
1615         }
1616
1617         if (capable(CAP_SYS_ADMIN)) {
1618                 mutex_lock(&port->mutex);
1619                 pm_state = state->pm_state;
1620                 if (pm_state)
1621                         uart_change_pm(state, 0);
1622                 spin_lock_irq(&uport->lock);
1623                 status = uport->ops->get_mctrl(uport);
1624                 spin_unlock_irq(&uport->lock);
1625                 if (pm_state)
1626                         uart_change_pm(state, pm_state);
1627                 mutex_unlock(&port->mutex);
1628
1629                 seq_printf(m, " tx:%d rx:%d",
1630                                 uport->icount.tx, uport->icount.rx);
1631                 if (uport->icount.frame)
1632                         seq_printf(m, " fe:%d",
1633                                 uport->icount.frame);
1634                 if (uport->icount.parity)
1635                         seq_printf(m, " pe:%d",
1636                                 uport->icount.parity);
1637                 if (uport->icount.brk)
1638                         seq_printf(m, " brk:%d",
1639                                 uport->icount.brk);
1640                 if (uport->icount.overrun)
1641                         seq_printf(m, " oe:%d",
1642                                 uport->icount.overrun);
1643
1644 #define INFOBIT(bit, str) \
1645         if (uport->mctrl & (bit)) \
1646                 strncat(stat_buf, (str), sizeof(stat_buf) - \
1647                         strlen(stat_buf) - 2)
1648 #define STATBIT(bit, str) \
1649         if (status & (bit)) \
1650                 strncat(stat_buf, (str), sizeof(stat_buf) - \
1651                        strlen(stat_buf) - 2)
1652
1653                 stat_buf[0] = '\0';
1654                 stat_buf[1] = '\0';
1655                 INFOBIT(TIOCM_RTS, "|RTS");
1656                 STATBIT(TIOCM_CTS, "|CTS");
1657                 INFOBIT(TIOCM_DTR, "|DTR");
1658                 STATBIT(TIOCM_DSR, "|DSR");
1659                 STATBIT(TIOCM_CAR, "|CD");
1660                 STATBIT(TIOCM_RNG, "|RI");
1661                 if (stat_buf[0])
1662                         stat_buf[0] = ' ';
1663
1664                 seq_puts(m, stat_buf);
1665         }
1666         seq_putc(m, '\n');
1667 #undef STATBIT
1668 #undef INFOBIT
1669 }
1670
1671 static int uart_proc_show(struct seq_file *m, void *v)
1672 {
1673         struct tty_driver *ttydrv = m->private;
1674         struct uart_driver *drv = ttydrv->driver_state;
1675         int i;
1676
1677         seq_printf(m, "serinfo:1.0 driver%s%s revision:%s\n",
1678                         "", "", "");
1679         for (i = 0; i < drv->nr; i++)
1680                 uart_line_info(m, drv, i);
1681         return 0;
1682 }
1683
1684 static int uart_proc_open(struct inode *inode, struct file *file)
1685 {
1686         return single_open(file, uart_proc_show, PDE(inode)->data);
1687 }
1688
1689 static const struct file_operations uart_proc_fops = {
1690         .owner          = THIS_MODULE,
1691         .open           = uart_proc_open,
1692         .read           = seq_read,
1693         .llseek         = seq_lseek,
1694         .release        = single_release,
1695 };
1696 #endif
1697
1698 #if defined(CONFIG_SERIAL_CORE_CONSOLE) || defined(CONFIG_CONSOLE_POLL)
1699 /*
1700  *      uart_console_write - write a console message to a serial port
1701  *      @port: the port to write the message
1702  *      @s: array of characters
1703  *      @count: number of characters in string to write
1704  *      @write: function to write character to port
1705  */
1706 void uart_console_write(struct uart_port *port, const char *s,
1707                         unsigned int count,
1708                         void (*putchar)(struct uart_port *, int))
1709 {
1710         unsigned int i;
1711
1712         for (i = 0; i < count; i++, s++) {
1713                 if (*s == '\n')
1714                         putchar(port, '\r');
1715                 putchar(port, *s);
1716         }
1717 }
1718 EXPORT_SYMBOL_GPL(uart_console_write);
1719
1720 /*
1721  *      Check whether an invalid uart number has been specified, and
1722  *      if so, search for the first available port that does have
1723  *      console support.
1724  */
1725 struct uart_port * __init
1726 uart_get_console(struct uart_port *ports, int nr, struct console *co)
1727 {
1728         int idx = co->index;
1729
1730         if (idx < 0 || idx >= nr || (ports[idx].iobase == 0 &&
1731                                      ports[idx].membase == NULL))
1732                 for (idx = 0; idx < nr; idx++)
1733                         if (ports[idx].iobase != 0 ||
1734                             ports[idx].membase != NULL)
1735                                 break;
1736
1737         co->index = idx;
1738
1739         return ports + idx;
1740 }
1741
1742 /**
1743  *      uart_parse_options - Parse serial port baud/parity/bits/flow contro.
1744  *      @options: pointer to option string
1745  *      @baud: pointer to an 'int' variable for the baud rate.
1746  *      @parity: pointer to an 'int' variable for the parity.
1747  *      @bits: pointer to an 'int' variable for the number of data bits.
1748  *      @flow: pointer to an 'int' variable for the flow control character.
1749  *
1750  *      uart_parse_options decodes a string containing the serial console
1751  *      options.  The format of the string is <baud><parity><bits><flow>,
1752  *      eg: 115200n8r
1753  */
1754 void
1755 uart_parse_options(char *options, int *baud, int *parity, int *bits, int *flow)
1756 {
1757         char *s = options;
1758
1759         *baud = simple_strtoul(s, NULL, 10);
1760         while (*s >= '0' && *s <= '9')
1761                 s++;
1762         if (*s)
1763                 *parity = *s++;
1764         if (*s)
1765                 *bits = *s++ - '0';
1766         if (*s)
1767                 *flow = *s;
1768 }
1769 EXPORT_SYMBOL_GPL(uart_parse_options);
1770
1771 struct baud_rates {
1772         unsigned int rate;
1773         unsigned int cflag;
1774 };
1775
1776 static const struct baud_rates baud_rates[] = {
1777         { 921600, B921600 },
1778         { 460800, B460800 },
1779         { 230400, B230400 },
1780         { 115200, B115200 },
1781         {  57600, B57600  },
1782         {  38400, B38400  },
1783         {  19200, B19200  },
1784         {   9600, B9600   },
1785         {   4800, B4800   },
1786         {   2400, B2400   },
1787         {   1200, B1200   },
1788         {      0, B38400  }
1789 };
1790
1791 /**
1792  *      uart_set_options - setup the serial console parameters
1793  *      @port: pointer to the serial ports uart_port structure
1794  *      @co: console pointer
1795  *      @baud: baud rate
1796  *      @parity: parity character - 'n' (none), 'o' (odd), 'e' (even)
1797  *      @bits: number of data bits
1798  *      @flow: flow control character - 'r' (rts)
1799  */
1800 int
1801 uart_set_options(struct uart_port *port, struct console *co,
1802                  int baud, int parity, int bits, int flow)
1803 {
1804         struct ktermios termios;
1805         static struct ktermios dummy;
1806         int i;
1807
1808         /*
1809          * Ensure that the serial console lock is initialised
1810          * early.
1811          */
1812         spin_lock_init(&port->lock);
1813         lockdep_set_class(&port->lock, &port_lock_key);
1814
1815         memset(&termios, 0, sizeof(struct ktermios));
1816
1817         termios.c_cflag = CREAD | HUPCL | CLOCAL;
1818
1819         /*
1820          * Construct a cflag setting.
1821          */
1822         for (i = 0; baud_rates[i].rate; i++)
1823                 if (baud_rates[i].rate <= baud)
1824                         break;
1825
1826         termios.c_cflag |= baud_rates[i].cflag;
1827
1828         if (bits == 7)
1829                 termios.c_cflag |= CS7;
1830         else
1831                 termios.c_cflag |= CS8;
1832
1833         switch (parity) {
1834         case 'o': case 'O':
1835                 termios.c_cflag |= PARODD;
1836                 /*fall through*/
1837         case 'e': case 'E':
1838                 termios.c_cflag |= PARENB;
1839                 break;
1840         }
1841
1842         if (flow == 'r')
1843                 termios.c_cflag |= CRTSCTS;
1844
1845         /*
1846          * some uarts on other side don't support no flow control.
1847          * So we set * DTR in host uart to make them happy
1848          */
1849         port->mctrl |= TIOCM_DTR;
1850
1851         port->ops->set_termios(port, &termios, &dummy);
1852         /*
1853          * Allow the setting of the UART parameters with a NULL console
1854          * too:
1855          */
1856         if (co)
1857                 co->cflag = termios.c_cflag;
1858
1859         return 0;
1860 }
1861 EXPORT_SYMBOL_GPL(uart_set_options);
1862 #endif /* CONFIG_SERIAL_CORE_CONSOLE */
1863
1864 static void uart_change_pm(struct uart_state *state, int pm_state)
1865 {
1866         struct uart_port *port = state->uart_port;
1867
1868         if (state->pm_state != pm_state) {
1869                 if (port->ops->pm)
1870                         port->ops->pm(port, pm_state, state->pm_state);
1871                 state->pm_state = pm_state;
1872         }
1873 }
1874
1875 struct uart_match {
1876         struct uart_port *port;
1877         struct uart_driver *driver;
1878 };
1879
1880 static int serial_match_port(struct device *dev, void *data)
1881 {
1882         struct uart_match *match = data;
1883         struct tty_driver *tty_drv = match->driver->tty_driver;
1884         dev_t devt = MKDEV(tty_drv->major, tty_drv->minor_start) +
1885                 match->port->line;
1886
1887         return dev->devt == devt; /* Actually, only one tty per port */
1888 }
1889
1890 int uart_suspend_port(struct uart_driver *drv, struct uart_port *uport)
1891 {
1892         struct uart_state *state = drv->state + uport->line;
1893         struct tty_port *port = &state->port;
1894         struct device *tty_dev;
1895         struct uart_match match = {uport, drv};
1896
1897         mutex_lock(&port->mutex);
1898
1899         tty_dev = device_find_child(uport->dev, &match, serial_match_port);
1900         if (device_may_wakeup(tty_dev)) {
1901                 if (!enable_irq_wake(uport->irq))
1902                         uport->irq_wake = 1;
1903                 put_device(tty_dev);
1904                 mutex_unlock(&port->mutex);
1905                 return 0;
1906         }
1907         put_device(tty_dev);
1908
1909         if (console_suspend_enabled || !uart_console(uport))
1910                 uport->suspended = 1;
1911
1912         if (port->flags & ASYNC_INITIALIZED) {
1913                 const struct uart_ops *ops = uport->ops;
1914                 int tries;
1915
1916                 if (console_suspend_enabled || !uart_console(uport)) {
1917                         set_bit(ASYNCB_SUSPENDED, &port->flags);
1918                         clear_bit(ASYNCB_INITIALIZED, &port->flags);
1919
1920                         spin_lock_irq(&uport->lock);
1921                         ops->stop_tx(uport);
1922                         ops->set_mctrl(uport, 0);
1923                         ops->stop_rx(uport);
1924                         spin_unlock_irq(&uport->lock);
1925                 }
1926
1927                 /*
1928                  * Wait for the transmitter to empty.
1929                  */
1930                 for (tries = 3; !ops->tx_empty(uport) && tries; tries--)
1931                         msleep(10);
1932                 if (!tries)
1933                         printk(KERN_ERR "%s%s%s%d: Unable to drain "
1934                                         "transmitter\n",
1935                                uport->dev ? dev_name(uport->dev) : "",
1936                                uport->dev ? ": " : "",
1937                                drv->dev_name,
1938                                drv->tty_driver->name_base + uport->line);
1939
1940                 if (console_suspend_enabled || !uart_console(uport))
1941                         ops->shutdown(uport);
1942         }
1943
1944         /*
1945          * Disable the console device before suspending.
1946          */
1947         if (console_suspend_enabled && uart_console(uport))
1948                 console_stop(uport->cons);
1949
1950         if (console_suspend_enabled || !uart_console(uport))
1951                 uart_change_pm(state, 3);
1952
1953         mutex_unlock(&port->mutex);
1954
1955         return 0;
1956 }
1957
1958 int uart_resume_port(struct uart_driver *drv, struct uart_port *uport)
1959 {
1960         struct uart_state *state = drv->state + uport->line;
1961         struct tty_port *port = &state->port;
1962         struct device *tty_dev;
1963         struct uart_match match = {uport, drv};
1964         struct ktermios termios;
1965
1966         mutex_lock(&port->mutex);
1967
1968         tty_dev = device_find_child(uport->dev, &match, serial_match_port);
1969         if (!uport->suspended && device_may_wakeup(tty_dev)) {
1970                 if (uport->irq_wake) {
1971                         disable_irq_wake(uport->irq);
1972                         uport->irq_wake = 0;
1973                 }
1974                 put_device(tty_dev);
1975                 mutex_unlock(&port->mutex);
1976                 return 0;
1977         }
1978         put_device(tty_dev);
1979         uport->suspended = 0;
1980
1981         /*
1982          * Re-enable the console device after suspending.
1983          */
1984         if (uart_console(uport)) {
1985                 /*
1986                  * First try to use the console cflag setting.
1987                  */
1988                 memset(&termios, 0, sizeof(struct ktermios));
1989                 termios.c_cflag = uport->cons->cflag;
1990
1991                 /*
1992                  * If that's unset, use the tty termios setting.
1993                  */
1994                 if (port->tty && port->tty->termios && termios.c_cflag == 0)
1995                         termios = *(port->tty->termios);
1996
1997                 if (console_suspend_enabled)
1998                         uart_change_pm(state, 0);
1999                 uport->ops->set_termios(uport, &termios, NULL);
2000                 if (console_suspend_enabled)
2001                         console_start(uport->cons);
2002         }
2003
2004         if (port->flags & ASYNC_SUSPENDED) {
2005                 const struct uart_ops *ops = uport->ops;
2006                 int ret;
2007
2008                 uart_change_pm(state, 0);
2009                 spin_lock_irq(&uport->lock);
2010                 ops->set_mctrl(uport, 0);
2011                 spin_unlock_irq(&uport->lock);
2012                 if (console_suspend_enabled || !uart_console(uport)) {
2013                         /* Protected by port mutex for now */
2014                         struct tty_struct *tty = port->tty;
2015                         ret = ops->startup(uport);
2016                         if (ret == 0) {
2017                                 if (tty)
2018                                         uart_change_speed(tty, state, NULL);
2019                                 spin_lock_irq(&uport->lock);
2020                                 ops->set_mctrl(uport, uport->mctrl);
2021                                 ops->start_tx(uport);
2022                                 spin_unlock_irq(&uport->lock);
2023                                 set_bit(ASYNCB_INITIALIZED, &port->flags);
2024                         } else {
2025                                 /*
2026                                  * Failed to resume - maybe hardware went away?
2027                                  * Clear the "initialized" flag so we won't try
2028                                  * to call the low level drivers shutdown method.
2029                                  */
2030                                 uart_shutdown(tty, state);
2031                         }
2032                 }
2033
2034                 clear_bit(ASYNCB_SUSPENDED, &port->flags);
2035         }
2036
2037         mutex_unlock(&port->mutex);
2038
2039         return 0;
2040 }
2041
2042 static inline void
2043 uart_report_port(struct uart_driver *drv, struct uart_port *port)
2044 {
2045         char address[64];
2046
2047         switch (port->iotype) {
2048         case UPIO_PORT:
2049                 snprintf(address, sizeof(address), "I/O 0x%lx", port->iobase);
2050                 break;
2051         case UPIO_HUB6:
2052                 snprintf(address, sizeof(address),
2053                          "I/O 0x%lx offset 0x%x", port->iobase, port->hub6);
2054                 break;
2055         case UPIO_MEM:
2056         case UPIO_MEM32:
2057         case UPIO_AU:
2058         case UPIO_TSI:
2059                 snprintf(address, sizeof(address),
2060                          "MMIO 0x%llx", (unsigned long long)port->mapbase);
2061                 break;
2062         default:
2063                 strlcpy(address, "*unknown*", sizeof(address));
2064                 break;
2065         }
2066
2067         printk(KERN_INFO "%s%s%s%d at %s (irq = %d) is a %s\n",
2068                port->dev ? dev_name(port->dev) : "",
2069                port->dev ? ": " : "",
2070                drv->dev_name,
2071                drv->tty_driver->name_base + port->line,
2072                address, port->irq, uart_type(port));
2073 }
2074
2075 static void
2076 uart_configure_port(struct uart_driver *drv, struct uart_state *state,
2077                     struct uart_port *port)
2078 {
2079         unsigned int flags;
2080
2081         /*
2082          * If there isn't a port here, don't do anything further.
2083          */
2084         if (!port->iobase && !port->mapbase && !port->membase)
2085                 return;
2086
2087         /*
2088          * Now do the auto configuration stuff.  Note that config_port
2089          * is expected to claim the resources and map the port for us.
2090          */
2091         flags = 0;
2092         if (port->flags & UPF_AUTO_IRQ)
2093                 flags |= UART_CONFIG_IRQ;
2094         if (port->flags & UPF_BOOT_AUTOCONF) {
2095                 if (!(port->flags & UPF_FIXED_TYPE)) {
2096                         port->type = PORT_UNKNOWN;
2097                         flags |= UART_CONFIG_TYPE;
2098                 }
2099                 port->ops->config_port(port, flags);
2100         }
2101
2102         if (port->type != PORT_UNKNOWN) {
2103                 unsigned long flags;
2104
2105                 uart_report_port(drv, port);
2106
2107                 /* Power up port for set_mctrl() */
2108                 uart_change_pm(state, 0);
2109
2110                 /*
2111                  * Ensure that the modem control lines are de-activated.
2112                  * keep the DTR setting that is set in uart_set_options()
2113                  * We probably don't need a spinlock around this, but
2114                  */
2115                 spin_lock_irqsave(&port->lock, flags);
2116                 port->ops->set_mctrl(port, port->mctrl & TIOCM_DTR);
2117                 spin_unlock_irqrestore(&port->lock, flags);
2118
2119                 /*
2120                  * If this driver supports console, and it hasn't been
2121                  * successfully registered yet, try to re-register it.
2122                  * It may be that the port was not available.
2123                  */
2124                 if (port->cons && !(port->cons->flags & CON_ENABLED))
2125                         register_console(port->cons);
2126
2127                 /*
2128                  * Power down all ports by default, except the
2129                  * console if we have one.
2130                  */
2131                 if (!uart_console(port))
2132                         uart_change_pm(state, 3);
2133         }
2134 }
2135
2136 #ifdef CONFIG_CONSOLE_POLL
2137
2138 static int uart_poll_init(struct tty_driver *driver, int line, char *options)
2139 {
2140         struct uart_driver *drv = driver->driver_state;
2141         struct uart_state *state = drv->state + line;
2142         struct uart_port *port;
2143         int baud = 9600;
2144         int bits = 8;
2145         int parity = 'n';
2146         int flow = 'n';
2147
2148         if (!state || !state->uart_port)
2149                 return -1;
2150
2151         port = state->uart_port;
2152         if (!(port->ops->poll_get_char && port->ops->poll_put_char))
2153                 return -1;
2154
2155         if (options) {
2156                 uart_parse_options(options, &baud, &parity, &bits, &flow);
2157                 return uart_set_options(port, NULL, baud, parity, bits, flow);
2158         }
2159
2160         return 0;
2161 }
2162
2163 static int uart_poll_get_char(struct tty_driver *driver, int line)
2164 {
2165         struct uart_driver *drv = driver->driver_state;
2166         struct uart_state *state = drv->state + line;
2167         struct uart_port *port;
2168
2169         if (!state || !state->uart_port)
2170                 return -1;
2171
2172         port = state->uart_port;
2173         return port->ops->poll_get_char(port);
2174 }
2175
2176 static void uart_poll_put_char(struct tty_driver *driver, int line, char ch)
2177 {
2178         struct uart_driver *drv = driver->driver_state;
2179         struct uart_state *state = drv->state + line;
2180         struct uart_port *port;
2181
2182         if (!state || !state->uart_port)
2183                 return;
2184
2185         port = state->uart_port;
2186         port->ops->poll_put_char(port, ch);
2187 }
2188 #endif
2189
2190 static const struct tty_operations uart_ops = {
2191         .open           = uart_open,
2192         .close          = uart_close,
2193         .write          = uart_write,
2194         .put_char       = uart_put_char,
2195         .flush_chars    = uart_flush_chars,
2196         .write_room     = uart_write_room,
2197         .chars_in_buffer= uart_chars_in_buffer,
2198         .flush_buffer   = uart_flush_buffer,
2199         .ioctl          = uart_ioctl,
2200         .throttle       = uart_throttle,
2201         .unthrottle     = uart_unthrottle,
2202         .send_xchar     = uart_send_xchar,
2203         .set_termios    = uart_set_termios,
2204         .set_ldisc      = uart_set_ldisc,
2205         .stop           = uart_stop,
2206         .start          = uart_start,
2207         .hangup         = uart_hangup,
2208         .break_ctl      = uart_break_ctl,
2209         .wait_until_sent= uart_wait_until_sent,
2210 #ifdef CONFIG_PROC_FS
2211         .proc_fops      = &uart_proc_fops,
2212 #endif
2213         .tiocmget       = uart_tiocmget,
2214         .tiocmset       = uart_tiocmset,
2215         .get_icount     = uart_get_icount,
2216 #ifdef CONFIG_CONSOLE_POLL
2217         .poll_init      = uart_poll_init,
2218         .poll_get_char  = uart_poll_get_char,
2219         .poll_put_char  = uart_poll_put_char,
2220 #endif
2221 };
2222
2223 static const struct tty_port_operations uart_port_ops = {
2224         .carrier_raised = uart_carrier_raised,
2225         .dtr_rts        = uart_dtr_rts,
2226 };
2227
2228 /**
2229  *      uart_register_driver - register a driver with the uart core layer
2230  *      @drv: low level driver structure
2231  *
2232  *      Register a uart driver with the core driver.  We in turn register
2233  *      with the tty layer, and initialise the core driver per-port state.
2234  *
2235  *      We have a proc file in /proc/tty/driver which is named after the
2236  *      normal driver.
2237  *
2238  *      drv->port should be NULL, and the per-port structures should be
2239  *      registered using uart_add_one_port after this call has succeeded.
2240  */
2241 int uart_register_driver(struct uart_driver *drv)
2242 {
2243         struct tty_driver *normal;
2244         int i, retval;
2245
2246         BUG_ON(drv->state);
2247
2248         /*
2249          * Maybe we should be using a slab cache for this, especially if
2250          * we have a large number of ports to handle.
2251          */
2252         drv->state = kzalloc(sizeof(struct uart_state) * drv->nr, GFP_KERNEL);
2253         if (!drv->state)
2254                 goto out;
2255
2256         normal = alloc_tty_driver(drv->nr);
2257         if (!normal)
2258                 goto out_kfree;
2259
2260         drv->tty_driver = normal;
2261
2262         normal->owner           = drv->owner;
2263         normal->driver_name     = drv->driver_name;
2264         normal->name            = drv->dev_name;
2265         normal->major           = drv->major;
2266         normal->minor_start     = drv->minor;
2267         normal->type            = TTY_DRIVER_TYPE_SERIAL;
2268         normal->subtype         = SERIAL_TYPE_NORMAL;
2269         normal->init_termios    = tty_std_termios;
2270         normal->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL;
2271         normal->init_termios.c_ispeed = normal->init_termios.c_ospeed = 9600;
2272         normal->flags           = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
2273         normal->driver_state    = drv;
2274         tty_set_operations(normal, &uart_ops);
2275
2276         /*
2277          * Initialise the UART state(s).
2278          */
2279         for (i = 0; i < drv->nr; i++) {
2280                 struct uart_state *state = drv->state + i;
2281                 struct tty_port *port = &state->port;
2282
2283                 tty_port_init(port);
2284                 port->ops = &uart_port_ops;
2285                 port->close_delay     = 500;    /* .5 seconds */
2286                 port->closing_wait    = 30000;  /* 30 seconds */
2287         }
2288
2289         retval = tty_register_driver(normal);
2290         if (retval >= 0)
2291                 return retval;
2292
2293         put_tty_driver(normal);
2294 out_kfree:
2295         kfree(drv->state);
2296 out:
2297         return -ENOMEM;
2298 }
2299
2300 /**
2301  *      uart_unregister_driver - remove a driver from the uart core layer
2302  *      @drv: low level driver structure
2303  *
2304  *      Remove all references to a driver from the core driver.  The low
2305  *      level driver must have removed all its ports via the
2306  *      uart_remove_one_port() if it registered them with uart_add_one_port().
2307  *      (ie, drv->port == NULL)
2308  */
2309 void uart_unregister_driver(struct uart_driver *drv)
2310 {
2311         struct tty_driver *p = drv->tty_driver;
2312         tty_unregister_driver(p);
2313         put_tty_driver(p);
2314         kfree(drv->state);
2315         drv->state = NULL;
2316         drv->tty_driver = NULL;
2317 }
2318
2319 struct tty_driver *uart_console_device(struct console *co, int *index)
2320 {
2321         struct uart_driver *p = co->data;
2322         *index = co->index;
2323         return p->tty_driver;
2324 }
2325
2326 /**
2327  *      uart_add_one_port - attach a driver-defined port structure
2328  *      @drv: pointer to the uart low level driver structure for this port
2329  *      @uport: uart port structure to use for this port.
2330  *
2331  *      This allows the driver to register its own uart_port structure
2332  *      with the core driver.  The main purpose is to allow the low
2333  *      level uart drivers to expand uart_port, rather than having yet
2334  *      more levels of structures.
2335  */
2336 int uart_add_one_port(struct uart_driver *drv, struct uart_port *uport)
2337 {
2338         struct uart_state *state;
2339         struct tty_port *port;
2340         int ret = 0;
2341         struct device *tty_dev;
2342
2343         BUG_ON(in_interrupt());
2344
2345         if (uport->line >= drv->nr)
2346                 return -EINVAL;
2347
2348         state = drv->state + uport->line;
2349         port = &state->port;
2350
2351         mutex_lock(&port_mutex);
2352         mutex_lock(&port->mutex);
2353         if (state->uart_port) {
2354                 ret = -EINVAL;
2355                 goto out;
2356         }
2357
2358         state->uart_port = uport;
2359         state->pm_state = -1;
2360
2361         uport->cons = drv->cons;
2362         uport->state = state;
2363
2364         /*
2365          * If this port is a console, then the spinlock is already
2366          * initialised.
2367          */
2368         if (!(uart_console(uport) && (uport->cons->flags & CON_ENABLED))) {
2369                 spin_lock_init(&uport->lock);
2370                 lockdep_set_class(&uport->lock, &port_lock_key);
2371         }
2372
2373         uart_configure_port(drv, state, uport);
2374
2375         /*
2376          * Register the port whether it's detected or not.  This allows
2377          * setserial to be used to alter this ports parameters.
2378          */
2379         tty_dev = tty_register_device(drv->tty_driver, uport->line, uport->dev);
2380         if (likely(!IS_ERR(tty_dev))) {
2381                 device_init_wakeup(tty_dev, 1);
2382                 device_set_wakeup_enable(tty_dev, 0);
2383         } else
2384                 printk(KERN_ERR "Cannot register tty device on line %d\n",
2385                        uport->line);
2386
2387         /*
2388          * Ensure UPF_DEAD is not set.
2389          */
2390         uport->flags &= ~UPF_DEAD;
2391
2392  out:
2393         mutex_unlock(&port->mutex);
2394         mutex_unlock(&port_mutex);
2395
2396         return ret;
2397 }
2398
2399 /**
2400  *      uart_remove_one_port - detach a driver defined port structure
2401  *      @drv: pointer to the uart low level driver structure for this port
2402  *      @uport: uart port structure for this port
2403  *
2404  *      This unhooks (and hangs up) the specified port structure from the
2405  *      core driver.  No further calls will be made to the low-level code
2406  *      for this port.
2407  */
2408 int uart_remove_one_port(struct uart_driver *drv, struct uart_port *uport)
2409 {
2410         struct uart_state *state = drv->state + uport->line;
2411         struct tty_port *port = &state->port;
2412
2413         BUG_ON(in_interrupt());
2414
2415         if (state->uart_port != uport)
2416                 printk(KERN_ALERT "Removing wrong port: %p != %p\n",
2417                         state->uart_port, uport);
2418
2419         mutex_lock(&port_mutex);
2420
2421         /*
2422          * Mark the port "dead" - this prevents any opens from
2423          * succeeding while we shut down the port.
2424          */
2425         mutex_lock(&port->mutex);
2426         uport->flags |= UPF_DEAD;
2427         mutex_unlock(&port->mutex);
2428
2429         /*
2430          * Remove the devices from the tty layer
2431          */
2432         tty_unregister_device(drv->tty_driver, uport->line);
2433
2434         if (port->tty)
2435                 tty_vhangup(port->tty);
2436
2437         /*
2438          * Free the port IO and memory resources, if any.
2439          */
2440         if (uport->type != PORT_UNKNOWN)
2441                 uport->ops->release_port(uport);
2442
2443         /*
2444          * Indicate that there isn't a port here anymore.
2445          */
2446         uport->type = PORT_UNKNOWN;
2447
2448         state->uart_port = NULL;
2449         mutex_unlock(&port_mutex);
2450
2451         return 0;
2452 }
2453
2454 /*
2455  *      Are the two ports equivalent?
2456  */
2457 int uart_match_port(struct uart_port *port1, struct uart_port *port2)
2458 {
2459         if (port1->iotype != port2->iotype)
2460                 return 0;
2461
2462         switch (port1->iotype) {
2463         case UPIO_PORT:
2464                 return (port1->iobase == port2->iobase);
2465         case UPIO_HUB6:
2466                 return (port1->iobase == port2->iobase) &&
2467                        (port1->hub6   == port2->hub6);
2468         case UPIO_MEM:
2469         case UPIO_MEM32:
2470         case UPIO_AU:
2471         case UPIO_TSI:
2472                 return (port1->mapbase == port2->mapbase);
2473         }
2474         return 0;
2475 }
2476 EXPORT_SYMBOL(uart_match_port);
2477
2478 EXPORT_SYMBOL(uart_write_wakeup);
2479 EXPORT_SYMBOL(uart_register_driver);
2480 EXPORT_SYMBOL(uart_unregister_driver);
2481 EXPORT_SYMBOL(uart_suspend_port);
2482 EXPORT_SYMBOL(uart_resume_port);
2483 EXPORT_SYMBOL(uart_add_one_port);
2484 EXPORT_SYMBOL(uart_remove_one_port);
2485
2486 MODULE_DESCRIPTION("Serial driver core");
2487 MODULE_LICENSE("GPL");