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