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