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