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