GNU Linux-libre 4.9.309-gnu1
[releases.git] / drivers / tty / serial / serial_core.c
1 /*
2  *  Driver core for serial ports
3  *
4  *  Based on drivers/char/serial.c, by Linus Torvalds, Theodore Ts'o.
5  *
6  *  Copyright 1999 ARM Limited
7  *  Copyright (C) 2000-2001 Deep Blue Solutions Ltd.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23 #include <linux/module.h>
24 #include <linux/tty.h>
25 #include <linux/tty_flip.h>
26 #include <linux/slab.h>
27 #include <linux/init.h>
28 #include <linux/console.h>
29 #include <linux/of.h>
30 #include <linux/proc_fs.h>
31 #include <linux/seq_file.h>
32 #include <linux/device.h>
33 #include <linux/serial.h> /* for serial_state and serial_icounter_struct */
34 #include <linux/serial_core.h>
35 #include <linux/delay.h>
36 #include <linux/mutex.h>
37
38 #include <asm/irq.h>
39 #include <asm/uaccess.h>
40
41 /*
42  * This is used to lock changes in serial line configuration.
43  */
44 static DEFINE_MUTEX(port_mutex);
45
46 /*
47  * lockdep: port->lock is initialized in two places, but we
48  *          want only one lock-class:
49  */
50 static struct lock_class_key port_lock_key;
51
52 #define HIGH_BITS_OFFSET        ((sizeof(long)-sizeof(int))*8)
53
54 static void uart_change_speed(struct tty_struct *tty, struct uart_state *state,
55                                         struct ktermios *old_termios);
56 static void uart_wait_until_sent(struct tty_struct *tty, int timeout);
57 static void uart_change_pm(struct uart_state *state,
58                            enum uart_pm_state pm_state);
59
60 static void uart_port_shutdown(struct tty_port *port);
61
62 static int uart_dcd_enabled(struct uart_port *uport)
63 {
64         return !!(uport->status & UPSTAT_DCD_ENABLE);
65 }
66
67 static inline struct uart_port *uart_port_ref(struct uart_state *state)
68 {
69         if (atomic_add_unless(&state->refcount, 1, 0))
70                 return state->uart_port;
71         return NULL;
72 }
73
74 static inline void uart_port_deref(struct uart_port *uport)
75 {
76         if (uport && atomic_dec_and_test(&uport->state->refcount))
77                 wake_up(&uport->state->remove_wait);
78 }
79
80 #define uart_port_lock(state, flags)                                    \
81         ({                                                              \
82                 struct uart_port *__uport = uart_port_ref(state);       \
83                 if (__uport)                                            \
84                         spin_lock_irqsave(&__uport->lock, flags);       \
85                 __uport;                                                \
86         })
87
88 #define uart_port_unlock(uport, flags)                                  \
89         ({                                                              \
90                 struct uart_port *__uport = uport;                      \
91                 if (__uport)                                            \
92                         spin_unlock_irqrestore(&__uport->lock, flags);  \
93                 uart_port_deref(__uport);                               \
94         })
95
96 static inline struct uart_port *uart_port_check(struct uart_state *state)
97 {
98         lockdep_assert_held(&state->port.mutex);
99         return state->uart_port;
100 }
101
102 /*
103  * This routine is used by the interrupt handler to schedule processing in
104  * the software interrupt portion of the driver.
105  */
106 void uart_write_wakeup(struct uart_port *port)
107 {
108         struct uart_state *state = port->state;
109         /*
110          * This means you called this function _after_ the port was
111          * closed.  No cookie for you.
112          */
113         BUG_ON(!state);
114         tty_port_tty_wakeup(&state->port);
115 }
116
117 static void uart_stop(struct tty_struct *tty)
118 {
119         struct uart_state *state = tty->driver_data;
120         struct uart_port *port;
121         unsigned long flags;
122
123         port = uart_port_lock(state, flags);
124         if (port)
125                 port->ops->stop_tx(port);
126         uart_port_unlock(port, flags);
127 }
128
129 static void __uart_start(struct tty_struct *tty)
130 {
131         struct uart_state *state = tty->driver_data;
132         struct uart_port *port = state->uart_port;
133
134         if (port && !uart_tx_stopped(port))
135                 port->ops->start_tx(port);
136 }
137
138 static void uart_start(struct tty_struct *tty)
139 {
140         struct uart_state *state = tty->driver_data;
141         struct uart_port *port;
142         unsigned long flags;
143
144         port = uart_port_lock(state, flags);
145         __uart_start(tty);
146         uart_port_unlock(port, flags);
147 }
148
149 static void
150 uart_update_mctrl(struct uart_port *port, unsigned int set, unsigned int clear)
151 {
152         unsigned long flags;
153         unsigned int old;
154
155         spin_lock_irqsave(&port->lock, flags);
156         old = port->mctrl;
157         port->mctrl = (old & ~clear) | set;
158         if (old != port->mctrl)
159                 port->ops->set_mctrl(port, port->mctrl);
160         spin_unlock_irqrestore(&port->lock, flags);
161 }
162
163 #define uart_set_mctrl(port, set)       uart_update_mctrl(port, set, 0)
164 #define uart_clear_mctrl(port, clear)   uart_update_mctrl(port, 0, clear)
165
166 /*
167  * Startup the port.  This will be called once per open.  All calls
168  * will be serialised by the per-port mutex.
169  */
170 static int uart_port_startup(struct tty_struct *tty, struct uart_state *state,
171                 int init_hw)
172 {
173         struct uart_port *uport = uart_port_check(state);
174         unsigned long page;
175         unsigned long flags = 0;
176         int retval = 0;
177
178         if (uport->type == PORT_UNKNOWN)
179                 return 1;
180
181         /*
182          * Make sure the device is in D0 state.
183          */
184         uart_change_pm(state, UART_PM_STATE_ON);
185
186         /*
187          * Initialise and allocate the transmit and temporary
188          * buffer.
189          */
190         page = get_zeroed_page(GFP_KERNEL);
191         if (!page)
192                 return -ENOMEM;
193
194         uart_port_lock(state, flags);
195         if (!state->xmit.buf) {
196                 state->xmit.buf = (unsigned char *) page;
197                 uart_circ_clear(&state->xmit);
198                 uart_port_unlock(uport, flags);
199         } else {
200                 uart_port_unlock(uport, flags);
201                 /*
202                  * Do not free() the page under the port lock, see
203                  * uart_shutdown().
204                  */
205                 free_page(page);
206         }
207
208         retval = uport->ops->startup(uport);
209         if (retval == 0) {
210                 if (uart_console(uport) && uport->cons->cflag) {
211                         tty->termios.c_cflag = uport->cons->cflag;
212                         tty->termios.c_ispeed = uport->cons->ispeed;
213                         tty->termios.c_ospeed = uport->cons->ospeed;
214                         uport->cons->cflag = 0;
215                         uport->cons->ispeed = 0;
216                         uport->cons->ospeed = 0;
217                 }
218                 /*
219                  * Initialise the hardware port settings.
220                  */
221                 uart_change_speed(tty, state, NULL);
222
223                 /*
224                  * Setup the RTS and DTR signals once the
225                  * port is open and ready to respond.
226                  */
227                 if (init_hw && C_BAUD(tty))
228                         uart_set_mctrl(uport, TIOCM_RTS | TIOCM_DTR);
229         }
230
231         /*
232          * This is to allow setserial on this port. People may want to set
233          * port/irq/type and then reconfigure the port properly if it failed
234          * now.
235          */
236         if (retval && capable(CAP_SYS_ADMIN))
237                 return 1;
238
239         return retval;
240 }
241
242 static int uart_startup(struct tty_struct *tty, struct uart_state *state,
243                 int init_hw)
244 {
245         struct tty_port *port = &state->port;
246         int retval;
247
248         if (tty_port_initialized(port))
249                 return 0;
250
251         retval = uart_port_startup(tty, state, init_hw);
252         if (retval)
253                 set_bit(TTY_IO_ERROR, &tty->flags);
254
255         return retval;
256 }
257
258 /*
259  * This routine will shutdown a serial port; interrupts are disabled, and
260  * DTR is dropped if the hangup on close termio flag is on.  Calls to
261  * uart_shutdown are serialised by the per-port semaphore.
262  *
263  * uport == NULL if uart_port has already been removed
264  */
265 static void uart_shutdown(struct tty_struct *tty, struct uart_state *state)
266 {
267         struct uart_port *uport = uart_port_check(state);
268         struct tty_port *port = &state->port;
269         unsigned long flags = 0;
270         char *xmit_buf = NULL;
271
272         /*
273          * Set the TTY IO error marker
274          */
275         if (tty)
276                 set_bit(TTY_IO_ERROR, &tty->flags);
277
278         if (tty_port_initialized(port)) {
279                 tty_port_set_initialized(port, 0);
280
281                 /*
282                  * Turn off DTR and RTS early.
283                  */
284                 if (uport && uart_console(uport) && tty) {
285                         uport->cons->cflag = tty->termios.c_cflag;
286                         uport->cons->ispeed = tty->termios.c_ispeed;
287                         uport->cons->ospeed = tty->termios.c_ospeed;
288                 }
289
290                 if (!tty || C_HUPCL(tty))
291                         uart_clear_mctrl(uport, TIOCM_DTR | TIOCM_RTS);
292
293                 uart_port_shutdown(port);
294         }
295
296         /*
297          * It's possible for shutdown to be called after suspend if we get
298          * a DCD drop (hangup) at just the right time.  Clear suspended bit so
299          * we don't try to resume a port that has been shutdown.
300          */
301         tty_port_set_suspended(port, 0);
302
303         /*
304          * Do not free() the transmit buffer page under the port lock since
305          * this can create various circular locking scenarios. For instance,
306          * console driver may need to allocate/free a debug object, which
307          * can endup in printk() recursion.
308          */
309         uart_port_lock(state, flags);
310         xmit_buf = state->xmit.buf;
311         state->xmit.buf = NULL;
312         uart_port_unlock(uport, flags);
313
314         if (xmit_buf)
315                 free_page((unsigned long)xmit_buf);
316 }
317
318 /**
319  *      uart_update_timeout - update per-port FIFO timeout.
320  *      @port:  uart_port structure describing the port
321  *      @cflag: termios cflag value
322  *      @baud:  speed of the port
323  *
324  *      Set the port FIFO timeout value.  The @cflag value should
325  *      reflect the actual hardware settings.
326  */
327 void
328 uart_update_timeout(struct uart_port *port, unsigned int cflag,
329                     unsigned int baud)
330 {
331         unsigned int bits;
332
333         /* byte size and parity */
334         switch (cflag & CSIZE) {
335         case CS5:
336                 bits = 7;
337                 break;
338         case CS6:
339                 bits = 8;
340                 break;
341         case CS7:
342                 bits = 9;
343                 break;
344         default:
345                 bits = 10;
346                 break; /* CS8 */
347         }
348
349         if (cflag & CSTOPB)
350                 bits++;
351         if (cflag & PARENB)
352                 bits++;
353
354         /*
355          * The total number of bits to be transmitted in the fifo.
356          */
357         bits = bits * port->fifosize;
358
359         /*
360          * Figure the timeout to send the above number of bits.
361          * Add .02 seconds of slop
362          */
363         port->timeout = (HZ * bits) / baud + HZ/50;
364 }
365
366 EXPORT_SYMBOL(uart_update_timeout);
367
368 /**
369  *      uart_get_baud_rate - return baud rate for a particular port
370  *      @port: uart_port structure describing the port in question.
371  *      @termios: desired termios settings.
372  *      @old: old termios (or NULL)
373  *      @min: minimum acceptable baud rate
374  *      @max: maximum acceptable baud rate
375  *
376  *      Decode the termios structure into a numeric baud rate,
377  *      taking account of the magic 38400 baud rate (with spd_*
378  *      flags), and mapping the %B0 rate to 9600 baud.
379  *
380  *      If the new baud rate is invalid, try the old termios setting.
381  *      If it's still invalid, we try 9600 baud.
382  *
383  *      Update the @termios structure to reflect the baud rate
384  *      we're actually going to be using. Don't do this for the case
385  *      where B0 is requested ("hang up").
386  */
387 unsigned int
388 uart_get_baud_rate(struct uart_port *port, struct ktermios *termios,
389                    struct ktermios *old, unsigned int min, unsigned int max)
390 {
391         unsigned int try;
392         unsigned int baud;
393         unsigned int altbaud;
394         int hung_up = 0;
395         upf_t flags = port->flags & UPF_SPD_MASK;
396
397         switch (flags) {
398         case UPF_SPD_HI:
399                 altbaud = 57600;
400                 break;
401         case UPF_SPD_VHI:
402                 altbaud = 115200;
403                 break;
404         case UPF_SPD_SHI:
405                 altbaud = 230400;
406                 break;
407         case UPF_SPD_WARP:
408                 altbaud = 460800;
409                 break;
410         default:
411                 altbaud = 38400;
412                 break;
413         }
414
415         for (try = 0; try < 2; try++) {
416                 baud = tty_termios_baud_rate(termios);
417
418                 /*
419                  * The spd_hi, spd_vhi, spd_shi, spd_warp kludge...
420                  * Die! Die! Die!
421                  */
422                 if (try == 0 && baud == 38400)
423                         baud = altbaud;
424
425                 /*
426                  * Special case: B0 rate.
427                  */
428                 if (baud == 0) {
429                         hung_up = 1;
430                         baud = 9600;
431                 }
432
433                 if (baud >= min && baud <= max)
434                         return baud;
435
436                 /*
437                  * Oops, the quotient was zero.  Try again with
438                  * the old baud rate if possible.
439                  */
440                 termios->c_cflag &= ~CBAUD;
441                 if (old) {
442                         baud = tty_termios_baud_rate(old);
443                         if (!hung_up)
444                                 tty_termios_encode_baud_rate(termios,
445                                                                 baud, baud);
446                         old = NULL;
447                         continue;
448                 }
449
450                 /*
451                  * As a last resort, if the range cannot be met then clip to
452                  * the nearest chip supported rate.
453                  */
454                 if (!hung_up) {
455                         if (baud <= min)
456                                 tty_termios_encode_baud_rate(termios,
457                                                         min + 1, min + 1);
458                         else
459                                 tty_termios_encode_baud_rate(termios,
460                                                         max - 1, max - 1);
461                 }
462         }
463         /* Should never happen */
464         WARN_ON(1);
465         return 0;
466 }
467
468 EXPORT_SYMBOL(uart_get_baud_rate);
469
470 /**
471  *      uart_get_divisor - return uart clock divisor
472  *      @port: uart_port structure describing the port.
473  *      @baud: desired baud rate
474  *
475  *      Calculate the uart clock divisor for the port.
476  */
477 unsigned int
478 uart_get_divisor(struct uart_port *port, unsigned int baud)
479 {
480         unsigned int quot;
481
482         /*
483          * Old custom speed handling.
484          */
485         if (baud == 38400 && (port->flags & UPF_SPD_MASK) == UPF_SPD_CUST)
486                 quot = port->custom_divisor;
487         else
488                 quot = DIV_ROUND_CLOSEST(port->uartclk, 16 * baud);
489
490         return quot;
491 }
492
493 EXPORT_SYMBOL(uart_get_divisor);
494
495 /* Caller holds port mutex */
496 static void uart_change_speed(struct tty_struct *tty, struct uart_state *state,
497                                         struct ktermios *old_termios)
498 {
499         struct uart_port *uport = uart_port_check(state);
500         struct ktermios *termios;
501         int hw_stopped;
502
503         /*
504          * If we have no tty, termios, or the port does not exist,
505          * then we can't set the parameters for this port.
506          */
507         if (!tty || uport->type == PORT_UNKNOWN)
508                 return;
509
510         termios = &tty->termios;
511         uport->ops->set_termios(uport, termios, old_termios);
512
513         /*
514          * Set modem status enables based on termios cflag
515          */
516         spin_lock_irq(&uport->lock);
517         if (termios->c_cflag & CRTSCTS)
518                 uport->status |= UPSTAT_CTS_ENABLE;
519         else
520                 uport->status &= ~UPSTAT_CTS_ENABLE;
521
522         if (termios->c_cflag & CLOCAL)
523                 uport->status &= ~UPSTAT_DCD_ENABLE;
524         else
525                 uport->status |= UPSTAT_DCD_ENABLE;
526
527         /* reset sw-assisted CTS flow control based on (possibly) new mode */
528         hw_stopped = uport->hw_stopped;
529         uport->hw_stopped = uart_softcts_mode(uport) &&
530                                 !(uport->ops->get_mctrl(uport) & TIOCM_CTS);
531         if (uport->hw_stopped) {
532                 if (!hw_stopped)
533                         uport->ops->stop_tx(uport);
534         } else {
535                 if (hw_stopped)
536                         __uart_start(tty);
537         }
538         spin_unlock_irq(&uport->lock);
539 }
540
541 static int uart_put_char(struct tty_struct *tty, unsigned char c)
542 {
543         struct uart_state *state = tty->driver_data;
544         struct uart_port *port;
545         struct circ_buf *circ;
546         unsigned long flags;
547         int ret = 0;
548
549         circ = &state->xmit;
550         port = uart_port_lock(state, flags);
551         if (!circ->buf) {
552                 uart_port_unlock(port, flags);
553                 return 0;
554         }
555
556         if (port && uart_circ_chars_free(circ) != 0) {
557                 circ->buf[circ->head] = c;
558                 circ->head = (circ->head + 1) & (UART_XMIT_SIZE - 1);
559                 ret = 1;
560         }
561         uart_port_unlock(port, flags);
562         return ret;
563 }
564
565 static void uart_flush_chars(struct tty_struct *tty)
566 {
567         uart_start(tty);
568 }
569
570 static int uart_write(struct tty_struct *tty,
571                                         const unsigned char *buf, int count)
572 {
573         struct uart_state *state = tty->driver_data;
574         struct uart_port *port;
575         struct circ_buf *circ;
576         unsigned long flags;
577         int c, ret = 0;
578
579         /*
580          * This means you called this function _after_ the port was
581          * closed.  No cookie for you.
582          */
583         if (!state) {
584                 WARN_ON(1);
585                 return -EL3HLT;
586         }
587
588         port = uart_port_lock(state, flags);
589         circ = &state->xmit;
590         if (!circ->buf) {
591                 uart_port_unlock(port, flags);
592                 return 0;
593         }
594
595         while (port) {
596                 c = CIRC_SPACE_TO_END(circ->head, circ->tail, UART_XMIT_SIZE);
597                 if (count < c)
598                         c = count;
599                 if (c <= 0)
600                         break;
601                 memcpy(circ->buf + circ->head, buf, c);
602                 circ->head = (circ->head + c) & (UART_XMIT_SIZE - 1);
603                 buf += c;
604                 count -= c;
605                 ret += c;
606         }
607
608         __uart_start(tty);
609         uart_port_unlock(port, flags);
610         return ret;
611 }
612
613 static int uart_write_room(struct tty_struct *tty)
614 {
615         struct uart_state *state = tty->driver_data;
616         struct uart_port *port;
617         unsigned long flags;
618         int ret;
619
620         port = uart_port_lock(state, flags);
621         ret = uart_circ_chars_free(&state->xmit);
622         uart_port_unlock(port, flags);
623         return ret;
624 }
625
626 static int uart_chars_in_buffer(struct tty_struct *tty)
627 {
628         struct uart_state *state = tty->driver_data;
629         struct uart_port *port;
630         unsigned long flags;
631         int ret;
632
633         port = uart_port_lock(state, flags);
634         ret = uart_circ_chars_pending(&state->xmit);
635         uart_port_unlock(port, flags);
636         return ret;
637 }
638
639 static void uart_flush_buffer(struct tty_struct *tty)
640 {
641         struct uart_state *state = tty->driver_data;
642         struct uart_port *port;
643         unsigned long flags;
644
645         /*
646          * This means you called this function _after_ the port was
647          * closed.  No cookie for you.
648          */
649         if (!state) {
650                 WARN_ON(1);
651                 return;
652         }
653
654         pr_debug("uart_flush_buffer(%d) called\n", tty->index);
655
656         port = uart_port_lock(state, flags);
657         if (!port)
658                 return;
659         uart_circ_clear(&state->xmit);
660         if (port->ops->flush_buffer)
661                 port->ops->flush_buffer(port);
662         uart_port_unlock(port, flags);
663         tty_port_tty_wakeup(&state->port);
664 }
665
666 /*
667  * This function is used to send a high-priority XON/XOFF character to
668  * the device
669  */
670 static void uart_send_xchar(struct tty_struct *tty, char ch)
671 {
672         struct uart_state *state = tty->driver_data;
673         struct uart_port *port;
674         unsigned long flags;
675
676         port = uart_port_ref(state);
677         if (!port)
678                 return;
679
680         if (port->ops->send_xchar)
681                 port->ops->send_xchar(port, ch);
682         else {
683                 spin_lock_irqsave(&port->lock, flags);
684                 port->x_char = ch;
685                 if (ch)
686                         port->ops->start_tx(port);
687                 spin_unlock_irqrestore(&port->lock, flags);
688         }
689         uart_port_deref(port);
690 }
691
692 static void uart_throttle(struct tty_struct *tty)
693 {
694         struct uart_state *state = tty->driver_data;
695         struct uart_port *port;
696         upstat_t mask = 0;
697
698         port = uart_port_ref(state);
699         if (!port)
700                 return;
701
702         if (I_IXOFF(tty))
703                 mask |= UPSTAT_AUTOXOFF;
704         if (C_CRTSCTS(tty))
705                 mask |= UPSTAT_AUTORTS;
706
707         if (port->status & mask) {
708                 port->ops->throttle(port);
709                 mask &= ~port->status;
710         }
711
712         if (mask & UPSTAT_AUTORTS)
713                 uart_clear_mctrl(port, TIOCM_RTS);
714
715         if (mask & UPSTAT_AUTOXOFF)
716                 uart_send_xchar(tty, STOP_CHAR(tty));
717
718         uart_port_deref(port);
719 }
720
721 static void uart_unthrottle(struct tty_struct *tty)
722 {
723         struct uart_state *state = tty->driver_data;
724         struct uart_port *port;
725         upstat_t mask = 0;
726
727         if (!state)
728                 return;
729
730         port = uart_port_ref(state);
731         if (!port)
732                 return;
733
734         if (I_IXOFF(tty))
735                 mask |= UPSTAT_AUTOXOFF;
736         if (C_CRTSCTS(tty))
737                 mask |= UPSTAT_AUTORTS;
738
739         if (port->status & mask) {
740                 port->ops->unthrottle(port);
741                 mask &= ~port->status;
742         }
743
744         if (mask & UPSTAT_AUTORTS)
745                 uart_set_mctrl(port, TIOCM_RTS);
746
747         if (mask & UPSTAT_AUTOXOFF)
748                 uart_send_xchar(tty, START_CHAR(tty));
749
750         uart_port_deref(port);
751 }
752
753 static int uart_get_info(struct tty_port *port, struct serial_struct *retinfo)
754 {
755         struct uart_state *state = container_of(port, struct uart_state, port);
756         struct uart_port *uport;
757         int ret = -ENODEV;
758
759         memset(retinfo, 0, sizeof(*retinfo));
760
761         /*
762          * Ensure the state we copy is consistent and no hardware changes
763          * occur as we go
764          */
765         mutex_lock(&port->mutex);
766         uport = uart_port_check(state);
767         if (!uport)
768                 goto out;
769
770         retinfo->type       = uport->type;
771         retinfo->line       = uport->line;
772         retinfo->port       = uport->iobase;
773         if (HIGH_BITS_OFFSET)
774                 retinfo->port_high = (long) uport->iobase >> HIGH_BITS_OFFSET;
775         retinfo->irq                = uport->irq;
776         retinfo->flags      = uport->flags;
777         retinfo->xmit_fifo_size  = uport->fifosize;
778         retinfo->baud_base          = uport->uartclk / 16;
779         retinfo->close_delay        = jiffies_to_msecs(port->close_delay) / 10;
780         retinfo->closing_wait    = port->closing_wait == ASYNC_CLOSING_WAIT_NONE ?
781                                 ASYNC_CLOSING_WAIT_NONE :
782                                 jiffies_to_msecs(port->closing_wait) / 10;
783         retinfo->custom_divisor  = uport->custom_divisor;
784         retinfo->hub6       = uport->hub6;
785         retinfo->io_type         = uport->iotype;
786         retinfo->iomem_reg_shift = uport->regshift;
787         retinfo->iomem_base      = (void *)(unsigned long)uport->mapbase;
788
789         ret = 0;
790 out:
791         mutex_unlock(&port->mutex);
792         return ret;
793 }
794
795 static int uart_get_info_user(struct tty_port *port,
796                          struct serial_struct __user *retinfo)
797 {
798         struct serial_struct tmp;
799
800         if (uart_get_info(port, &tmp) < 0)
801                 return -EIO;
802
803         if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
804                 return -EFAULT;
805         return 0;
806 }
807
808 static int uart_set_info(struct tty_struct *tty, struct tty_port *port,
809                          struct uart_state *state,
810                          struct serial_struct *new_info)
811 {
812         struct uart_port *uport = uart_port_check(state);
813         unsigned long new_port;
814         unsigned int change_irq, change_port, closing_wait;
815         unsigned int old_custom_divisor, close_delay;
816         upf_t old_flags, new_flags;
817         int retval = 0;
818
819         if (!uport)
820                 return -EIO;
821
822         new_port = new_info->port;
823         if (HIGH_BITS_OFFSET)
824                 new_port += (unsigned long) new_info->port_high << HIGH_BITS_OFFSET;
825
826         new_info->irq = irq_canonicalize(new_info->irq);
827         close_delay = msecs_to_jiffies(new_info->close_delay * 10);
828         closing_wait = new_info->closing_wait == ASYNC_CLOSING_WAIT_NONE ?
829                         ASYNC_CLOSING_WAIT_NONE :
830                         msecs_to_jiffies(new_info->closing_wait * 10);
831
832
833         change_irq  = !(uport->flags & UPF_FIXED_PORT)
834                 && new_info->irq != uport->irq;
835
836         /*
837          * Since changing the 'type' of the port changes its resource
838          * allocations, we should treat type changes the same as
839          * IO port changes.
840          */
841         change_port = !(uport->flags & UPF_FIXED_PORT)
842                 && (new_port != uport->iobase ||
843                     (unsigned long)new_info->iomem_base != uport->mapbase ||
844                     new_info->hub6 != uport->hub6 ||
845                     new_info->io_type != uport->iotype ||
846                     new_info->iomem_reg_shift != uport->regshift ||
847                     new_info->type != uport->type);
848
849         old_flags = uport->flags;
850         new_flags = new_info->flags;
851         old_custom_divisor = uport->custom_divisor;
852
853         if (!capable(CAP_SYS_ADMIN)) {
854                 retval = -EPERM;
855                 if (change_irq || change_port ||
856                     (new_info->baud_base != uport->uartclk / 16) ||
857                     (close_delay != port->close_delay) ||
858                     (closing_wait != port->closing_wait) ||
859                     (new_info->xmit_fifo_size &&
860                      new_info->xmit_fifo_size != uport->fifosize) ||
861                     (((new_flags ^ old_flags) & ~UPF_USR_MASK) != 0))
862                         goto exit;
863                 uport->flags = ((uport->flags & ~UPF_USR_MASK) |
864                                (new_flags & UPF_USR_MASK));
865                 uport->custom_divisor = new_info->custom_divisor;
866                 goto check_and_exit;
867         }
868
869         /*
870          * Ask the low level driver to verify the settings.
871          */
872         if (uport->ops->verify_port)
873                 retval = uport->ops->verify_port(uport, new_info);
874
875         if ((new_info->irq >= nr_irqs) || (new_info->irq < 0) ||
876             (new_info->baud_base < 9600))
877                 retval = -EINVAL;
878
879         if (retval)
880                 goto exit;
881
882         if (change_port || change_irq) {
883                 retval = -EBUSY;
884
885                 /*
886                  * Make sure that we are the sole user of this port.
887                  */
888                 if (tty_port_users(port) > 1)
889                         goto exit;
890
891                 /*
892                  * We need to shutdown the serial port at the old
893                  * port/type/irq combination.
894                  */
895                 uart_shutdown(tty, state);
896         }
897
898         if (change_port) {
899                 unsigned long old_iobase, old_mapbase;
900                 unsigned int old_type, old_iotype, old_hub6, old_shift;
901
902                 old_iobase = uport->iobase;
903                 old_mapbase = uport->mapbase;
904                 old_type = uport->type;
905                 old_hub6 = uport->hub6;
906                 old_iotype = uport->iotype;
907                 old_shift = uport->regshift;
908
909                 /*
910                  * Free and release old regions
911                  */
912                 if (old_type != PORT_UNKNOWN && uport->ops->release_port)
913                         uport->ops->release_port(uport);
914
915                 uport->iobase = new_port;
916                 uport->type = new_info->type;
917                 uport->hub6 = new_info->hub6;
918                 uport->iotype = new_info->io_type;
919                 uport->regshift = new_info->iomem_reg_shift;
920                 uport->mapbase = (unsigned long)new_info->iomem_base;
921
922                 /*
923                  * Claim and map the new regions
924                  */
925                 if (uport->type != PORT_UNKNOWN && uport->ops->request_port) {
926                         retval = uport->ops->request_port(uport);
927                 } else {
928                         /* Always success - Jean II */
929                         retval = 0;
930                 }
931
932                 /*
933                  * If we fail to request resources for the
934                  * new port, try to restore the old settings.
935                  */
936                 if (retval) {
937                         uport->iobase = old_iobase;
938                         uport->type = old_type;
939                         uport->hub6 = old_hub6;
940                         uport->iotype = old_iotype;
941                         uport->regshift = old_shift;
942                         uport->mapbase = old_mapbase;
943
944                         if (old_type != PORT_UNKNOWN) {
945                                 retval = uport->ops->request_port(uport);
946                                 /*
947                                  * If we failed to restore the old settings,
948                                  * we fail like this.
949                                  */
950                                 if (retval)
951                                         uport->type = PORT_UNKNOWN;
952
953                                 /*
954                                  * We failed anyway.
955                                  */
956                                 retval = -EBUSY;
957                         }
958
959                         /* Added to return the correct error -Ram Gupta */
960                         goto exit;
961                 }
962         }
963
964         if (change_irq)
965                 uport->irq      = new_info->irq;
966         if (!(uport->flags & UPF_FIXED_PORT))
967                 uport->uartclk  = new_info->baud_base * 16;
968         uport->flags            = (uport->flags & ~UPF_CHANGE_MASK) |
969                                  (new_flags & UPF_CHANGE_MASK);
970         uport->custom_divisor   = new_info->custom_divisor;
971         port->close_delay     = close_delay;
972         port->closing_wait    = closing_wait;
973         if (new_info->xmit_fifo_size)
974                 uport->fifosize = new_info->xmit_fifo_size;
975         port->low_latency = (uport->flags & UPF_LOW_LATENCY) ? 1 : 0;
976
977  check_and_exit:
978         retval = 0;
979         if (uport->type == PORT_UNKNOWN)
980                 goto exit;
981         if (tty_port_initialized(port)) {
982                 if (((old_flags ^ uport->flags) & UPF_SPD_MASK) ||
983                     old_custom_divisor != uport->custom_divisor) {
984                         /*
985                          * If they're setting up a custom divisor or speed,
986                          * instead of clearing it, then bitch about it. No
987                          * need to rate-limit; it's CAP_SYS_ADMIN only.
988                          */
989                         if (uport->flags & UPF_SPD_MASK) {
990                                 dev_notice(uport->dev,
991                                        "%s sets custom speed on %s. This is deprecated.\n",
992                                       current->comm,
993                                       tty_name(port->tty));
994                         }
995                         uart_change_speed(tty, state, NULL);
996                 }
997         } else {
998                 retval = uart_startup(tty, state, 1);
999                 if (retval == 0)
1000                         tty_port_set_initialized(port, true);
1001                 if (retval > 0)
1002                         retval = 0;
1003         }
1004  exit:
1005         return retval;
1006 }
1007
1008 static int uart_set_info_user(struct tty_struct *tty, struct uart_state *state,
1009                          struct serial_struct __user *newinfo)
1010 {
1011         struct serial_struct new_serial;
1012         struct tty_port *port = &state->port;
1013         int retval;
1014
1015         if (copy_from_user(&new_serial, newinfo, sizeof(new_serial)))
1016                 return -EFAULT;
1017
1018         /*
1019          * This semaphore protects port->count.  It is also
1020          * very useful to prevent opens.  Also, take the
1021          * port configuration semaphore to make sure that a
1022          * module insertion/removal doesn't change anything
1023          * under us.
1024          */
1025         mutex_lock(&port->mutex);
1026         retval = uart_set_info(tty, port, state, &new_serial);
1027         mutex_unlock(&port->mutex);
1028         return retval;
1029 }
1030
1031 /**
1032  *      uart_get_lsr_info       -       get line status register info
1033  *      @tty: tty associated with the UART
1034  *      @state: UART being queried
1035  *      @value: returned modem value
1036  */
1037 static int uart_get_lsr_info(struct tty_struct *tty,
1038                         struct uart_state *state, unsigned int __user *value)
1039 {
1040         struct uart_port *uport = uart_port_check(state);
1041         unsigned int result;
1042
1043         result = uport->ops->tx_empty(uport);
1044
1045         /*
1046          * If we're about to load something into the transmit
1047          * register, we'll pretend the transmitter isn't empty to
1048          * avoid a race condition (depending on when the transmit
1049          * interrupt happens).
1050          */
1051         if (uport->x_char ||
1052             ((uart_circ_chars_pending(&state->xmit) > 0) &&
1053              !uart_tx_stopped(uport)))
1054                 result &= ~TIOCSER_TEMT;
1055
1056         return put_user(result, value);
1057 }
1058
1059 static int uart_tiocmget(struct tty_struct *tty)
1060 {
1061         struct uart_state *state = tty->driver_data;
1062         struct tty_port *port = &state->port;
1063         struct uart_port *uport;
1064         int result = -EIO;
1065
1066         mutex_lock(&port->mutex);
1067         uport = uart_port_check(state);
1068         if (!uport)
1069                 goto out;
1070
1071         if (!tty_io_error(tty)) {
1072                 result = uport->mctrl;
1073                 spin_lock_irq(&uport->lock);
1074                 result |= uport->ops->get_mctrl(uport);
1075                 spin_unlock_irq(&uport->lock);
1076         }
1077 out:
1078         mutex_unlock(&port->mutex);
1079         return result;
1080 }
1081
1082 static int
1083 uart_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear)
1084 {
1085         struct uart_state *state = tty->driver_data;
1086         struct tty_port *port = &state->port;
1087         struct uart_port *uport;
1088         int ret = -EIO;
1089
1090         mutex_lock(&port->mutex);
1091         uport = uart_port_check(state);
1092         if (!uport)
1093                 goto out;
1094
1095         if (!tty_io_error(tty)) {
1096                 uart_update_mctrl(uport, set, clear);
1097                 ret = 0;
1098         }
1099 out:
1100         mutex_unlock(&port->mutex);
1101         return ret;
1102 }
1103
1104 static int uart_break_ctl(struct tty_struct *tty, int break_state)
1105 {
1106         struct uart_state *state = tty->driver_data;
1107         struct tty_port *port = &state->port;
1108         struct uart_port *uport;
1109         int ret = -EIO;
1110
1111         mutex_lock(&port->mutex);
1112         uport = uart_port_check(state);
1113         if (!uport)
1114                 goto out;
1115
1116         if (uport->type != PORT_UNKNOWN && uport->ops->break_ctl)
1117                 uport->ops->break_ctl(uport, break_state);
1118         ret = 0;
1119 out:
1120         mutex_unlock(&port->mutex);
1121         return ret;
1122 }
1123
1124 static int uart_do_autoconfig(struct tty_struct *tty,struct uart_state *state)
1125 {
1126         struct tty_port *port = &state->port;
1127         struct uart_port *uport;
1128         int flags, ret;
1129
1130         if (!capable(CAP_SYS_ADMIN))
1131                 return -EPERM;
1132
1133         /*
1134          * Take the per-port semaphore.  This prevents count from
1135          * changing, and hence any extra opens of the port while
1136          * we're auto-configuring.
1137          */
1138         if (mutex_lock_interruptible(&port->mutex))
1139                 return -ERESTARTSYS;
1140
1141         uport = uart_port_check(state);
1142         if (!uport) {
1143                 ret = -EIO;
1144                 goto out;
1145         }
1146
1147         ret = -EBUSY;
1148         if (tty_port_users(port) == 1) {
1149                 uart_shutdown(tty, state);
1150
1151                 /*
1152                  * If we already have a port type configured,
1153                  * we must release its resources.
1154                  */
1155                 if (uport->type != PORT_UNKNOWN && uport->ops->release_port)
1156                         uport->ops->release_port(uport);
1157
1158                 flags = UART_CONFIG_TYPE;
1159                 if (uport->flags & UPF_AUTO_IRQ)
1160                         flags |= UART_CONFIG_IRQ;
1161
1162                 /*
1163                  * This will claim the ports resources if
1164                  * a port is found.
1165                  */
1166                 uport->ops->config_port(uport, flags);
1167
1168                 ret = uart_startup(tty, state, 1);
1169                 if (ret == 0)
1170                         tty_port_set_initialized(port, true);
1171                 if (ret > 0)
1172                         ret = 0;
1173         }
1174 out:
1175         mutex_unlock(&port->mutex);
1176         return ret;
1177 }
1178
1179 static void uart_enable_ms(struct uart_port *uport)
1180 {
1181         /*
1182          * Force modem status interrupts on
1183          */
1184         if (uport->ops->enable_ms)
1185                 uport->ops->enable_ms(uport);
1186 }
1187
1188 /*
1189  * Wait for any of the 4 modem inputs (DCD,RI,DSR,CTS) to change
1190  * - mask passed in arg for lines of interest
1191  *   (use |'ed TIOCM_RNG/DSR/CD/CTS for masking)
1192  * Caller should use TIOCGICOUNT to see which one it was
1193  *
1194  * FIXME: This wants extracting into a common all driver implementation
1195  * of TIOCMWAIT using tty_port.
1196  */
1197 static int uart_wait_modem_status(struct uart_state *state, unsigned long arg)
1198 {
1199         struct uart_port *uport;
1200         struct tty_port *port = &state->port;
1201         DECLARE_WAITQUEUE(wait, current);
1202         struct uart_icount cprev, cnow;
1203         int ret;
1204
1205         /*
1206          * note the counters on entry
1207          */
1208         uport = uart_port_ref(state);
1209         if (!uport)
1210                 return -EIO;
1211         spin_lock_irq(&uport->lock);
1212         memcpy(&cprev, &uport->icount, sizeof(struct uart_icount));
1213         uart_enable_ms(uport);
1214         spin_unlock_irq(&uport->lock);
1215
1216         add_wait_queue(&port->delta_msr_wait, &wait);
1217         for (;;) {
1218                 spin_lock_irq(&uport->lock);
1219                 memcpy(&cnow, &uport->icount, sizeof(struct uart_icount));
1220                 spin_unlock_irq(&uport->lock);
1221
1222                 set_current_state(TASK_INTERRUPTIBLE);
1223
1224                 if (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||
1225                     ((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||
1226                     ((arg & TIOCM_CD)  && (cnow.dcd != cprev.dcd)) ||
1227                     ((arg & TIOCM_CTS) && (cnow.cts != cprev.cts))) {
1228                         ret = 0;
1229                         break;
1230                 }
1231
1232                 schedule();
1233
1234                 /* see if a signal did it */
1235                 if (signal_pending(current)) {
1236                         ret = -ERESTARTSYS;
1237                         break;
1238                 }
1239
1240                 cprev = cnow;
1241         }
1242         __set_current_state(TASK_RUNNING);
1243         remove_wait_queue(&port->delta_msr_wait, &wait);
1244         uart_port_deref(uport);
1245
1246         return ret;
1247 }
1248
1249 /*
1250  * Get counter of input serial line interrupts (DCD,RI,DSR,CTS)
1251  * Return: write counters to the user passed counter struct
1252  * NB: both 1->0 and 0->1 transitions are counted except for
1253  *     RI where only 0->1 is counted.
1254  */
1255 static int uart_get_icount(struct tty_struct *tty,
1256                           struct serial_icounter_struct *icount)
1257 {
1258         struct uart_state *state = tty->driver_data;
1259         struct uart_icount cnow;
1260         struct uart_port *uport;
1261
1262         uport = uart_port_ref(state);
1263         if (!uport)
1264                 return -EIO;
1265         spin_lock_irq(&uport->lock);
1266         memcpy(&cnow, &uport->icount, sizeof(struct uart_icount));
1267         spin_unlock_irq(&uport->lock);
1268         uart_port_deref(uport);
1269
1270         icount->cts         = cnow.cts;
1271         icount->dsr         = cnow.dsr;
1272         icount->rng         = cnow.rng;
1273         icount->dcd         = cnow.dcd;
1274         icount->rx          = cnow.rx;
1275         icount->tx          = cnow.tx;
1276         icount->frame       = cnow.frame;
1277         icount->overrun     = cnow.overrun;
1278         icount->parity      = cnow.parity;
1279         icount->brk         = cnow.brk;
1280         icount->buf_overrun = cnow.buf_overrun;
1281
1282         return 0;
1283 }
1284
1285 static int uart_get_rs485_config(struct uart_port *port,
1286                          struct serial_rs485 __user *rs485)
1287 {
1288         unsigned long flags;
1289         struct serial_rs485 aux;
1290
1291         spin_lock_irqsave(&port->lock, flags);
1292         aux = port->rs485;
1293         spin_unlock_irqrestore(&port->lock, flags);
1294
1295         if (copy_to_user(rs485, &aux, sizeof(aux)))
1296                 return -EFAULT;
1297
1298         return 0;
1299 }
1300
1301 static int uart_set_rs485_config(struct uart_port *port,
1302                          struct serial_rs485 __user *rs485_user)
1303 {
1304         struct serial_rs485 rs485;
1305         int ret;
1306         unsigned long flags;
1307
1308         if (!port->rs485_config)
1309                 return -ENOIOCTLCMD;
1310
1311         if (copy_from_user(&rs485, rs485_user, sizeof(*rs485_user)))
1312                 return -EFAULT;
1313
1314         spin_lock_irqsave(&port->lock, flags);
1315         ret = port->rs485_config(port, &rs485);
1316         spin_unlock_irqrestore(&port->lock, flags);
1317         if (ret)
1318                 return ret;
1319
1320         if (copy_to_user(rs485_user, &port->rs485, sizeof(port->rs485)))
1321                 return -EFAULT;
1322
1323         return 0;
1324 }
1325
1326 /*
1327  * Called via sys_ioctl.  We can use spin_lock_irq() here.
1328  */
1329 static int
1330 uart_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg)
1331 {
1332         struct uart_state *state = tty->driver_data;
1333         struct tty_port *port = &state->port;
1334         struct uart_port *uport;
1335         void __user *uarg = (void __user *)arg;
1336         int ret = -ENOIOCTLCMD;
1337
1338
1339         /*
1340          * These ioctls don't rely on the hardware to be present.
1341          */
1342         switch (cmd) {
1343         case TIOCGSERIAL:
1344                 ret = uart_get_info_user(port, uarg);
1345                 break;
1346
1347         case TIOCSSERIAL:
1348                 down_write(&tty->termios_rwsem);
1349                 ret = uart_set_info_user(tty, state, uarg);
1350                 up_write(&tty->termios_rwsem);
1351                 break;
1352
1353         case TIOCSERCONFIG:
1354                 down_write(&tty->termios_rwsem);
1355                 ret = uart_do_autoconfig(tty, state);
1356                 up_write(&tty->termios_rwsem);
1357                 break;
1358
1359         case TIOCSERGWILD: /* obsolete */
1360         case TIOCSERSWILD: /* obsolete */
1361                 ret = 0;
1362                 break;
1363         }
1364
1365         if (ret != -ENOIOCTLCMD)
1366                 goto out;
1367
1368         if (tty_io_error(tty)) {
1369                 ret = -EIO;
1370                 goto out;
1371         }
1372
1373         /*
1374          * The following should only be used when hardware is present.
1375          */
1376         switch (cmd) {
1377         case TIOCMIWAIT:
1378                 ret = uart_wait_modem_status(state, arg);
1379                 break;
1380         }
1381
1382         if (ret != -ENOIOCTLCMD)
1383                 goto out;
1384
1385         mutex_lock(&port->mutex);
1386         uport = uart_port_check(state);
1387
1388         if (!uport || tty_io_error(tty)) {
1389                 ret = -EIO;
1390                 goto out_up;
1391         }
1392
1393         /*
1394          * All these rely on hardware being present and need to be
1395          * protected against the tty being hung up.
1396          */
1397
1398         switch (cmd) {
1399         case TIOCSERGETLSR: /* Get line status register */
1400                 ret = uart_get_lsr_info(tty, state, uarg);
1401                 break;
1402
1403         case TIOCGRS485:
1404                 ret = uart_get_rs485_config(uport, uarg);
1405                 break;
1406
1407         case TIOCSRS485:
1408                 ret = uart_set_rs485_config(uport, uarg);
1409                 break;
1410         default:
1411                 if (uport->ops->ioctl)
1412                         ret = uport->ops->ioctl(uport, cmd, arg);
1413                 break;
1414         }
1415 out_up:
1416         mutex_unlock(&port->mutex);
1417 out:
1418         return ret;
1419 }
1420
1421 static void uart_set_ldisc(struct tty_struct *tty)
1422 {
1423         struct uart_state *state = tty->driver_data;
1424         struct uart_port *uport;
1425         struct tty_port *port = &state->port;
1426
1427         if (!tty_port_initialized(port))
1428                 return;
1429
1430         mutex_lock(&state->port.mutex);
1431         uport = uart_port_check(state);
1432         if (uport && uport->ops->set_ldisc)
1433                 uport->ops->set_ldisc(uport, &tty->termios);
1434         mutex_unlock(&state->port.mutex);
1435 }
1436
1437 static void uart_set_termios(struct tty_struct *tty,
1438                                                 struct ktermios *old_termios)
1439 {
1440         struct uart_state *state = tty->driver_data;
1441         struct uart_port *uport;
1442         unsigned int cflag = tty->termios.c_cflag;
1443         unsigned int iflag_mask = IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK;
1444         bool sw_changed = false;
1445
1446         mutex_lock(&state->port.mutex);
1447         uport = uart_port_check(state);
1448         if (!uport)
1449                 goto out;
1450
1451         /*
1452          * Drivers doing software flow control also need to know
1453          * about changes to these input settings.
1454          */
1455         if (uport->flags & UPF_SOFT_FLOW) {
1456                 iflag_mask |= IXANY|IXON|IXOFF;
1457                 sw_changed =
1458                    tty->termios.c_cc[VSTART] != old_termios->c_cc[VSTART] ||
1459                    tty->termios.c_cc[VSTOP] != old_termios->c_cc[VSTOP];
1460         }
1461
1462         /*
1463          * These are the bits that are used to setup various
1464          * flags in the low level driver. We can ignore the Bfoo
1465          * bits in c_cflag; c_[io]speed will always be set
1466          * appropriately by set_termios() in tty_ioctl.c
1467          */
1468         if ((cflag ^ old_termios->c_cflag) == 0 &&
1469             tty->termios.c_ospeed == old_termios->c_ospeed &&
1470             tty->termios.c_ispeed == old_termios->c_ispeed &&
1471             ((tty->termios.c_iflag ^ old_termios->c_iflag) & iflag_mask) == 0 &&
1472             !sw_changed) {
1473                 goto out;
1474         }
1475
1476         uart_change_speed(tty, state, old_termios);
1477         /* reload cflag from termios; port driver may have overriden flags */
1478         cflag = tty->termios.c_cflag;
1479
1480         /* Handle transition to B0 status */
1481         if ((old_termios->c_cflag & CBAUD) && !(cflag & CBAUD))
1482                 uart_clear_mctrl(uport, TIOCM_RTS | TIOCM_DTR);
1483         /* Handle transition away from B0 status */
1484         else if (!(old_termios->c_cflag & CBAUD) && (cflag & CBAUD)) {
1485                 unsigned int mask = TIOCM_DTR;
1486                 if (!(cflag & CRTSCTS) || !tty_throttled(tty))
1487                         mask |= TIOCM_RTS;
1488                 uart_set_mctrl(uport, mask);
1489         }
1490 out:
1491         mutex_unlock(&state->port.mutex);
1492 }
1493
1494 /*
1495  * Calls to uart_close() are serialised via the tty_lock in
1496  *   drivers/tty/tty_io.c:tty_release()
1497  *   drivers/tty/tty_io.c:do_tty_hangup()
1498  */
1499 static void uart_close(struct tty_struct *tty, struct file *filp)
1500 {
1501         struct uart_state *state = tty->driver_data;
1502         struct tty_port *port;
1503
1504         if (!state) {
1505                 struct uart_driver *drv = tty->driver->driver_state;
1506
1507                 state = drv->state + tty->index;
1508                 port = &state->port;
1509                 spin_lock_irq(&port->lock);
1510                 --port->count;
1511                 spin_unlock_irq(&port->lock);
1512                 return;
1513         }
1514
1515         port = &state->port;
1516         pr_debug("uart_close(%d) called\n", tty->index);
1517
1518         tty_port_close(tty->port, tty, filp);
1519 }
1520
1521 static void uart_tty_port_shutdown(struct tty_port *port)
1522 {
1523         struct uart_state *state = container_of(port, struct uart_state, port);
1524         struct uart_port *uport = uart_port_check(state);
1525         char *buf;
1526
1527         /*
1528          * At this point, we stop accepting input.  To do this, we
1529          * disable the receive line status interrupts.
1530          */
1531         if (WARN(!uport, "detached port still initialized!\n"))
1532                 return;
1533
1534         spin_lock_irq(&uport->lock);
1535         uport->ops->stop_rx(uport);
1536         spin_unlock_irq(&uport->lock);
1537
1538         uart_port_shutdown(port);
1539
1540         /*
1541          * It's possible for shutdown to be called after suspend if we get
1542          * a DCD drop (hangup) at just the right time.  Clear suspended bit so
1543          * we don't try to resume a port that has been shutdown.
1544          */
1545         tty_port_set_suspended(port, 0);
1546
1547         /*
1548          * Free the transmit buffer.
1549          */
1550         spin_lock_irq(&uport->lock);
1551         buf = state->xmit.buf;
1552         state->xmit.buf = NULL;
1553         spin_unlock_irq(&uport->lock);
1554
1555         if (buf)
1556                 free_page((unsigned long)buf);
1557
1558         uart_change_pm(state, UART_PM_STATE_OFF);
1559 }
1560
1561 static void uart_wait_until_sent(struct tty_struct *tty, int timeout)
1562 {
1563         struct uart_state *state = tty->driver_data;
1564         struct uart_port *port;
1565         unsigned long char_time, expire;
1566
1567         port = uart_port_ref(state);
1568         if (!port || port->type == PORT_UNKNOWN || port->fifosize == 0) {
1569                 uart_port_deref(port);
1570                 return;
1571         }
1572
1573         /*
1574          * Set the check interval to be 1/5 of the estimated time to
1575          * send a single character, and make it at least 1.  The check
1576          * interval should also be less than the timeout.
1577          *
1578          * Note: we have to use pretty tight timings here to satisfy
1579          * the NIST-PCTS.
1580          */
1581         char_time = (port->timeout - HZ/50) / port->fifosize;
1582         char_time = char_time / 5;
1583         if (char_time == 0)
1584                 char_time = 1;
1585         if (timeout && timeout < char_time)
1586                 char_time = timeout;
1587
1588         /*
1589          * If the transmitter hasn't cleared in twice the approximate
1590          * amount of time to send the entire FIFO, it probably won't
1591          * ever clear.  This assumes the UART isn't doing flow
1592          * control, which is currently the case.  Hence, if it ever
1593          * takes longer than port->timeout, this is probably due to a
1594          * UART bug of some kind.  So, we clamp the timeout parameter at
1595          * 2*port->timeout.
1596          */
1597         if (timeout == 0 || timeout > 2 * port->timeout)
1598                 timeout = 2 * port->timeout;
1599
1600         expire = jiffies + timeout;
1601
1602         pr_debug("uart_wait_until_sent(%d), jiffies=%lu, expire=%lu...\n",
1603                 port->line, jiffies, expire);
1604
1605         /*
1606          * Check whether the transmitter is empty every 'char_time'.
1607          * 'timeout' / 'expire' give us the maximum amount of time
1608          * we wait.
1609          */
1610         while (!port->ops->tx_empty(port)) {
1611                 msleep_interruptible(jiffies_to_msecs(char_time));
1612                 if (signal_pending(current))
1613                         break;
1614                 if (time_after(jiffies, expire))
1615                         break;
1616         }
1617         uart_port_deref(port);
1618 }
1619
1620 /*
1621  * Calls to uart_hangup() are serialised by the tty_lock in
1622  *   drivers/tty/tty_io.c:do_tty_hangup()
1623  * This runs from a workqueue and can sleep for a _short_ time only.
1624  */
1625 static void uart_hangup(struct tty_struct *tty)
1626 {
1627         struct uart_state *state = tty->driver_data;
1628         struct tty_port *port = &state->port;
1629         struct uart_port *uport;
1630         unsigned long flags;
1631
1632         pr_debug("uart_hangup(%d)\n", tty->index);
1633
1634         mutex_lock(&port->mutex);
1635         uport = uart_port_check(state);
1636         WARN(!uport, "hangup of detached port!\n");
1637
1638         if (tty_port_active(port)) {
1639                 uart_flush_buffer(tty);
1640                 uart_shutdown(tty, state);
1641                 spin_lock_irqsave(&port->lock, flags);
1642                 port->count = 0;
1643                 spin_unlock_irqrestore(&port->lock, flags);
1644                 tty_port_set_active(port, 0);
1645                 tty_port_tty_set(port, NULL);
1646                 if (uport && !uart_console(uport))
1647                         uart_change_pm(state, UART_PM_STATE_OFF);
1648                 wake_up_interruptible(&port->open_wait);
1649                 wake_up_interruptible(&port->delta_msr_wait);
1650         }
1651         mutex_unlock(&port->mutex);
1652 }
1653
1654 /* uport == NULL if uart_port has already been removed */
1655 static void uart_port_shutdown(struct tty_port *port)
1656 {
1657         struct uart_state *state = container_of(port, struct uart_state, port);
1658         struct uart_port *uport = uart_port_check(state);
1659
1660         /*
1661          * clear delta_msr_wait queue to avoid mem leaks: we may free
1662          * the irq here so the queue might never be woken up.  Note
1663          * that we won't end up waiting on delta_msr_wait again since
1664          * any outstanding file descriptors should be pointing at
1665          * hung_up_tty_fops now.
1666          */
1667         wake_up_interruptible(&port->delta_msr_wait);
1668
1669         /*
1670          * Free the IRQ and disable the port.
1671          */
1672         if (uport)
1673                 uport->ops->shutdown(uport);
1674
1675         /*
1676          * Ensure that the IRQ handler isn't running on another CPU.
1677          */
1678         if (uport)
1679                 synchronize_irq(uport->irq);
1680 }
1681
1682 static int uart_carrier_raised(struct tty_port *port)
1683 {
1684         struct uart_state *state = container_of(port, struct uart_state, port);
1685         struct uart_port *uport;
1686         int mctrl;
1687
1688         uport = uart_port_ref(state);
1689         /*
1690          * Should never observe uport == NULL since checks for hangup should
1691          * abort the tty_port_block_til_ready() loop before checking for carrier
1692          * raised -- but report carrier raised if it does anyway so open will
1693          * continue and not sleep
1694          */
1695         if (WARN_ON(!uport))
1696                 return 1;
1697         spin_lock_irq(&uport->lock);
1698         uart_enable_ms(uport);
1699         mctrl = uport->ops->get_mctrl(uport);
1700         spin_unlock_irq(&uport->lock);
1701         uart_port_deref(uport);
1702         if (mctrl & TIOCM_CAR)
1703                 return 1;
1704         return 0;
1705 }
1706
1707 static void uart_dtr_rts(struct tty_port *port, int onoff)
1708 {
1709         struct uart_state *state = container_of(port, struct uart_state, port);
1710         struct uart_port *uport;
1711
1712         uport = uart_port_ref(state);
1713         if (!uport)
1714                 return;
1715
1716         if (onoff)
1717                 uart_set_mctrl(uport, TIOCM_DTR | TIOCM_RTS);
1718         else
1719                 uart_clear_mctrl(uport, TIOCM_DTR | TIOCM_RTS);
1720
1721         uart_port_deref(uport);
1722 }
1723
1724 /*
1725  * Calls to uart_open are serialised by the tty_lock in
1726  *   drivers/tty/tty_io.c:tty_open()
1727  * Note that if this fails, then uart_close() _will_ be called.
1728  *
1729  * In time, we want to scrap the "opening nonpresent ports"
1730  * behaviour and implement an alternative way for setserial
1731  * to set base addresses/ports/types.  This will allow us to
1732  * get rid of a certain amount of extra tests.
1733  */
1734 static int uart_open(struct tty_struct *tty, struct file *filp)
1735 {
1736         struct uart_state *state = tty->driver_data;
1737         int retval;
1738
1739         retval = tty_port_open(&state->port, tty, filp);
1740         if (retval > 0)
1741                 retval = 0;
1742
1743         return retval;
1744 }
1745
1746 static int uart_port_activate(struct tty_port *port, struct tty_struct *tty)
1747 {
1748         struct uart_state *state = container_of(port, struct uart_state, port);
1749         struct uart_port *uport;
1750         int ret;
1751
1752         uport = uart_port_check(state);
1753         if (!uport || uport->flags & UPF_DEAD)
1754                 return -ENXIO;
1755
1756         port->low_latency = (uport->flags & UPF_LOW_LATENCY) ? 1 : 0;
1757
1758         /*
1759          * Start up the serial port.
1760          */
1761         ret = uart_startup(tty, state, 0);
1762         if (ret > 0)
1763                 tty_port_set_active(port, 1);
1764
1765         return ret;
1766 }
1767
1768 static const char *uart_type(struct uart_port *port)
1769 {
1770         const char *str = NULL;
1771
1772         if (port->ops->type)
1773                 str = port->ops->type(port);
1774
1775         if (!str)
1776                 str = "unknown";
1777
1778         return str;
1779 }
1780
1781 #ifdef CONFIG_PROC_FS
1782
1783 static void uart_line_info(struct seq_file *m, struct uart_driver *drv, int i)
1784 {
1785         struct uart_state *state = drv->state + i;
1786         struct tty_port *port = &state->port;
1787         enum uart_pm_state pm_state;
1788         struct uart_port *uport;
1789         char stat_buf[32];
1790         unsigned int status;
1791         int mmio;
1792
1793         mutex_lock(&port->mutex);
1794         uport = uart_port_check(state);
1795         if (!uport)
1796                 goto out;
1797
1798         mmio = uport->iotype >= UPIO_MEM;
1799         seq_printf(m, "%d: uart:%s %s%08llX irq:%d",
1800                         uport->line, uart_type(uport),
1801                         mmio ? "mmio:0x" : "port:",
1802                         mmio ? (unsigned long long)uport->mapbase
1803                              : (unsigned long long)uport->iobase,
1804                         uport->irq);
1805
1806         if (uport->type == PORT_UNKNOWN) {
1807                 seq_putc(m, '\n');
1808                 goto out;
1809         }
1810
1811         if (capable(CAP_SYS_ADMIN)) {
1812                 pm_state = state->pm_state;
1813                 if (pm_state != UART_PM_STATE_ON)
1814                         uart_change_pm(state, UART_PM_STATE_ON);
1815                 spin_lock_irq(&uport->lock);
1816                 status = uport->ops->get_mctrl(uport);
1817                 spin_unlock_irq(&uport->lock);
1818                 if (pm_state != UART_PM_STATE_ON)
1819                         uart_change_pm(state, pm_state);
1820
1821                 seq_printf(m, " tx:%d rx:%d",
1822                                 uport->icount.tx, uport->icount.rx);
1823                 if (uport->icount.frame)
1824                         seq_printf(m, " fe:%d", uport->icount.frame);
1825                 if (uport->icount.parity)
1826                         seq_printf(m, " pe:%d", uport->icount.parity);
1827                 if (uport->icount.brk)
1828                         seq_printf(m, " brk:%d", uport->icount.brk);
1829                 if (uport->icount.overrun)
1830                         seq_printf(m, " oe:%d", uport->icount.overrun);
1831
1832 #define INFOBIT(bit, str) \
1833         if (uport->mctrl & (bit)) \
1834                 strncat(stat_buf, (str), sizeof(stat_buf) - \
1835                         strlen(stat_buf) - 2)
1836 #define STATBIT(bit, str) \
1837         if (status & (bit)) \
1838                 strncat(stat_buf, (str), sizeof(stat_buf) - \
1839                        strlen(stat_buf) - 2)
1840
1841                 stat_buf[0] = '\0';
1842                 stat_buf[1] = '\0';
1843                 INFOBIT(TIOCM_RTS, "|RTS");
1844                 STATBIT(TIOCM_CTS, "|CTS");
1845                 INFOBIT(TIOCM_DTR, "|DTR");
1846                 STATBIT(TIOCM_DSR, "|DSR");
1847                 STATBIT(TIOCM_CAR, "|CD");
1848                 STATBIT(TIOCM_RNG, "|RI");
1849                 if (stat_buf[0])
1850                         stat_buf[0] = ' ';
1851
1852                 seq_puts(m, stat_buf);
1853         }
1854         seq_putc(m, '\n');
1855 #undef STATBIT
1856 #undef INFOBIT
1857 out:
1858         mutex_unlock(&port->mutex);
1859 }
1860
1861 static int uart_proc_show(struct seq_file *m, void *v)
1862 {
1863         struct tty_driver *ttydrv = m->private;
1864         struct uart_driver *drv = ttydrv->driver_state;
1865         int i;
1866
1867         seq_printf(m, "serinfo:1.0 driver%s%s revision:%s\n", "", "", "");
1868         for (i = 0; i < drv->nr; i++)
1869                 uart_line_info(m, drv, i);
1870         return 0;
1871 }
1872
1873 static int uart_proc_open(struct inode *inode, struct file *file)
1874 {
1875         return single_open(file, uart_proc_show, PDE_DATA(inode));
1876 }
1877
1878 static const struct file_operations uart_proc_fops = {
1879         .owner          = THIS_MODULE,
1880         .open           = uart_proc_open,
1881         .read           = seq_read,
1882         .llseek         = seq_lseek,
1883         .release        = single_release,
1884 };
1885 #endif
1886
1887 #if defined(CONFIG_SERIAL_CORE_CONSOLE) || defined(CONFIG_CONSOLE_POLL)
1888 /**
1889  *      uart_console_write - write a console message to a serial port
1890  *      @port: the port to write the message
1891  *      @s: array of characters
1892  *      @count: number of characters in string to write
1893  *      @putchar: function to write character to port
1894  */
1895 void uart_console_write(struct uart_port *port, const char *s,
1896                         unsigned int count,
1897                         void (*putchar)(struct uart_port *, int))
1898 {
1899         unsigned int i;
1900
1901         for (i = 0; i < count; i++, s++) {
1902                 if (*s == '\n')
1903                         putchar(port, '\r');
1904                 putchar(port, *s);
1905         }
1906 }
1907 EXPORT_SYMBOL_GPL(uart_console_write);
1908
1909 /*
1910  *      Check whether an invalid uart number has been specified, and
1911  *      if so, search for the first available port that does have
1912  *      console support.
1913  */
1914 struct uart_port * __init
1915 uart_get_console(struct uart_port *ports, int nr, struct console *co)
1916 {
1917         int idx = co->index;
1918
1919         if (idx < 0 || idx >= nr || (ports[idx].iobase == 0 &&
1920                                      ports[idx].membase == NULL))
1921                 for (idx = 0; idx < nr; idx++)
1922                         if (ports[idx].iobase != 0 ||
1923                             ports[idx].membase != NULL)
1924                                 break;
1925
1926         co->index = idx;
1927
1928         return ports + idx;
1929 }
1930
1931 /**
1932  *      uart_parse_earlycon - Parse earlycon options
1933  *      @p:       ptr to 2nd field (ie., just beyond '<name>,')
1934  *      @iotype:  ptr for decoded iotype (out)
1935  *      @addr:    ptr for decoded mapbase/iobase (out)
1936  *      @options: ptr for <options> field; NULL if not present (out)
1937  *
1938  *      Decodes earlycon kernel command line parameters of the form
1939  *         earlycon=<name>,io|mmio|mmio16|mmio32|mmio32be|mmio32native,<addr>,<options>
1940  *         console=<name>,io|mmio|mmio16|mmio32|mmio32be|mmio32native,<addr>,<options>
1941  *
1942  *      The optional form
1943  *         earlycon=<name>,0x<addr>,<options>
1944  *         console=<name>,0x<addr>,<options>
1945  *      is also accepted; the returned @iotype will be UPIO_MEM.
1946  *
1947  *      Returns 0 on success or -EINVAL on failure
1948  */
1949 int uart_parse_earlycon(char *p, unsigned char *iotype, resource_size_t *addr,
1950                         char **options)
1951 {
1952         if (strncmp(p, "mmio,", 5) == 0) {
1953                 *iotype = UPIO_MEM;
1954                 p += 5;
1955         } else if (strncmp(p, "mmio16,", 7) == 0) {
1956                 *iotype = UPIO_MEM16;
1957                 p += 7;
1958         } else if (strncmp(p, "mmio32,", 7) == 0) {
1959                 *iotype = UPIO_MEM32;
1960                 p += 7;
1961         } else if (strncmp(p, "mmio32be,", 9) == 0) {
1962                 *iotype = UPIO_MEM32BE;
1963                 p += 9;
1964         } else if (strncmp(p, "mmio32native,", 13) == 0) {
1965                 *iotype = IS_ENABLED(CONFIG_CPU_BIG_ENDIAN) ?
1966                         UPIO_MEM32BE : UPIO_MEM32;
1967                 p += 13;
1968         } else if (strncmp(p, "io,", 3) == 0) {
1969                 *iotype = UPIO_PORT;
1970                 p += 3;
1971         } else if (strncmp(p, "0x", 2) == 0) {
1972                 *iotype = UPIO_MEM;
1973         } else {
1974                 return -EINVAL;
1975         }
1976
1977         /*
1978          * Before you replace it with kstrtoull(), think about options separator
1979          * (',') it will not tolerate
1980          */
1981         *addr = simple_strtoull(p, NULL, 0);
1982         p = strchr(p, ',');
1983         if (p)
1984                 p++;
1985
1986         *options = p;
1987         return 0;
1988 }
1989 EXPORT_SYMBOL_GPL(uart_parse_earlycon);
1990
1991 /**
1992  *      uart_parse_options - Parse serial port baud/parity/bits/flow control.
1993  *      @options: pointer to option string
1994  *      @baud: pointer to an 'int' variable for the baud rate.
1995  *      @parity: pointer to an 'int' variable for the parity.
1996  *      @bits: pointer to an 'int' variable for the number of data bits.
1997  *      @flow: pointer to an 'int' variable for the flow control character.
1998  *
1999  *      uart_parse_options decodes a string containing the serial console
2000  *      options.  The format of the string is <baud><parity><bits><flow>,
2001  *      eg: 115200n8r
2002  */
2003 void
2004 uart_parse_options(char *options, int *baud, int *parity, int *bits, int *flow)
2005 {
2006         char *s = options;
2007
2008         *baud = simple_strtoul(s, NULL, 10);
2009         while (*s >= '0' && *s <= '9')
2010                 s++;
2011         if (*s)
2012                 *parity = *s++;
2013         if (*s)
2014                 *bits = *s++ - '0';
2015         if (*s)
2016                 *flow = *s;
2017 }
2018 EXPORT_SYMBOL_GPL(uart_parse_options);
2019
2020 /**
2021  *      uart_set_options - setup the serial console parameters
2022  *      @port: pointer to the serial ports uart_port structure
2023  *      @co: console pointer
2024  *      @baud: baud rate
2025  *      @parity: parity character - 'n' (none), 'o' (odd), 'e' (even)
2026  *      @bits: number of data bits
2027  *      @flow: flow control character - 'r' (rts)
2028  */
2029 int
2030 uart_set_options(struct uart_port *port, struct console *co,
2031                  int baud, int parity, int bits, int flow)
2032 {
2033         struct ktermios termios;
2034         static struct ktermios dummy;
2035
2036         /*
2037          * Ensure that the serial console lock is initialised
2038          * early.
2039          * If this port is a console, then the spinlock is already
2040          * initialised.
2041          */
2042         if (!(uart_console(port) && (port->cons->flags & CON_ENABLED))) {
2043                 spin_lock_init(&port->lock);
2044                 lockdep_set_class(&port->lock, &port_lock_key);
2045         }
2046
2047         memset(&termios, 0, sizeof(struct ktermios));
2048
2049         termios.c_cflag |= CREAD | HUPCL | CLOCAL;
2050         tty_termios_encode_baud_rate(&termios, baud, baud);
2051
2052         if (bits == 7)
2053                 termios.c_cflag |= CS7;
2054         else
2055                 termios.c_cflag |= CS8;
2056
2057         switch (parity) {
2058         case 'o': case 'O':
2059                 termios.c_cflag |= PARODD;
2060                 /*fall through*/
2061         case 'e': case 'E':
2062                 termios.c_cflag |= PARENB;
2063                 break;
2064         }
2065
2066         if (flow == 'r')
2067                 termios.c_cflag |= CRTSCTS;
2068
2069         /*
2070          * some uarts on other side don't support no flow control.
2071          * So we set * DTR in host uart to make them happy
2072          */
2073         port->mctrl |= TIOCM_DTR;
2074
2075         port->ops->set_termios(port, &termios, &dummy);
2076         /*
2077          * Allow the setting of the UART parameters with a NULL console
2078          * too:
2079          */
2080         if (co) {
2081                 co->cflag = termios.c_cflag;
2082                 co->ispeed = termios.c_ispeed;
2083                 co->ospeed = termios.c_ospeed;
2084         }
2085
2086         return 0;
2087 }
2088 EXPORT_SYMBOL_GPL(uart_set_options);
2089 #endif /* CONFIG_SERIAL_CORE_CONSOLE */
2090
2091 /**
2092  * uart_change_pm - set power state of the port
2093  *
2094  * @state: port descriptor
2095  * @pm_state: new state
2096  *
2097  * Locking: port->mutex has to be held
2098  */
2099 static void uart_change_pm(struct uart_state *state,
2100                            enum uart_pm_state pm_state)
2101 {
2102         struct uart_port *port = uart_port_check(state);
2103
2104         if (state->pm_state != pm_state) {
2105                 if (port && port->ops->pm)
2106                         port->ops->pm(port, pm_state, state->pm_state);
2107                 state->pm_state = pm_state;
2108         }
2109 }
2110
2111 struct uart_match {
2112         struct uart_port *port;
2113         struct uart_driver *driver;
2114 };
2115
2116 static int serial_match_port(struct device *dev, void *data)
2117 {
2118         struct uart_match *match = data;
2119         struct tty_driver *tty_drv = match->driver->tty_driver;
2120         dev_t devt = MKDEV(tty_drv->major, tty_drv->minor_start) +
2121                 match->port->line;
2122
2123         return dev->devt == devt; /* Actually, only one tty per port */
2124 }
2125
2126 int uart_suspend_port(struct uart_driver *drv, struct uart_port *uport)
2127 {
2128         struct uart_state *state = drv->state + uport->line;
2129         struct tty_port *port = &state->port;
2130         struct device *tty_dev;
2131         struct uart_match match = {uport, drv};
2132
2133         mutex_lock(&port->mutex);
2134
2135         tty_dev = device_find_child(uport->dev, &match, serial_match_port);
2136         if (device_may_wakeup(tty_dev)) {
2137                 if (!enable_irq_wake(uport->irq))
2138                         uport->irq_wake = 1;
2139                 put_device(tty_dev);
2140                 mutex_unlock(&port->mutex);
2141                 return 0;
2142         }
2143         put_device(tty_dev);
2144
2145         /* Nothing to do if the console is not suspending */
2146         if (!console_suspend_enabled && uart_console(uport))
2147                 goto unlock;
2148
2149         uport->suspended = 1;
2150
2151         if (tty_port_initialized(port)) {
2152                 const struct uart_ops *ops = uport->ops;
2153                 int tries;
2154
2155                 tty_port_set_suspended(port, 1);
2156                 tty_port_set_initialized(port, 0);
2157
2158                 spin_lock_irq(&uport->lock);
2159                 ops->stop_tx(uport);
2160                 ops->set_mctrl(uport, 0);
2161                 ops->stop_rx(uport);
2162                 spin_unlock_irq(&uport->lock);
2163
2164                 /*
2165                  * Wait for the transmitter to empty.
2166                  */
2167                 for (tries = 3; !ops->tx_empty(uport) && tries; tries--)
2168                         msleep(10);
2169                 if (!tries)
2170                         dev_err(uport->dev, "%s%d: Unable to drain transmitter\n",
2171                                 drv->dev_name,
2172                                 drv->tty_driver->name_base + uport->line);
2173
2174                 ops->shutdown(uport);
2175         }
2176
2177         /*
2178          * Disable the console device before suspending.
2179          */
2180         if (uart_console(uport))
2181                 console_stop(uport->cons);
2182
2183         uart_change_pm(state, UART_PM_STATE_OFF);
2184 unlock:
2185         mutex_unlock(&port->mutex);
2186
2187         return 0;
2188 }
2189
2190 int uart_resume_port(struct uart_driver *drv, struct uart_port *uport)
2191 {
2192         struct uart_state *state = drv->state + uport->line;
2193         struct tty_port *port = &state->port;
2194         struct device *tty_dev;
2195         struct uart_match match = {uport, drv};
2196         struct ktermios termios;
2197
2198         mutex_lock(&port->mutex);
2199
2200         tty_dev = device_find_child(uport->dev, &match, serial_match_port);
2201         if (!uport->suspended && device_may_wakeup(tty_dev)) {
2202                 if (uport->irq_wake) {
2203                         disable_irq_wake(uport->irq);
2204                         uport->irq_wake = 0;
2205                 }
2206                 put_device(tty_dev);
2207                 mutex_unlock(&port->mutex);
2208                 return 0;
2209         }
2210         put_device(tty_dev);
2211         uport->suspended = 0;
2212
2213         /*
2214          * Re-enable the console device after suspending.
2215          */
2216         if (uart_console(uport)) {
2217                 /*
2218                  * First try to use the console cflag setting.
2219                  */
2220                 memset(&termios, 0, sizeof(struct ktermios));
2221                 termios.c_cflag = uport->cons->cflag;
2222                 termios.c_ispeed = uport->cons->ispeed;
2223                 termios.c_ospeed = uport->cons->ospeed;
2224
2225                 /*
2226                  * If that's unset, use the tty termios setting.
2227                  */
2228                 if (port->tty && termios.c_cflag == 0)
2229                         termios = port->tty->termios;
2230
2231                 if (console_suspend_enabled)
2232                         uart_change_pm(state, UART_PM_STATE_ON);
2233                 uport->ops->set_termios(uport, &termios, NULL);
2234                 if (console_suspend_enabled)
2235                         console_start(uport->cons);
2236         }
2237
2238         if (tty_port_suspended(port)) {
2239                 const struct uart_ops *ops = uport->ops;
2240                 int ret;
2241
2242                 uart_change_pm(state, UART_PM_STATE_ON);
2243                 spin_lock_irq(&uport->lock);
2244                 ops->set_mctrl(uport, 0);
2245                 spin_unlock_irq(&uport->lock);
2246                 if (console_suspend_enabled || !uart_console(uport)) {
2247                         /* Protected by port mutex for now */
2248                         struct tty_struct *tty = port->tty;
2249                         ret = ops->startup(uport);
2250                         if (ret == 0) {
2251                                 if (tty)
2252                                         uart_change_speed(tty, state, NULL);
2253                                 spin_lock_irq(&uport->lock);
2254                                 ops->set_mctrl(uport, uport->mctrl);
2255                                 ops->start_tx(uport);
2256                                 spin_unlock_irq(&uport->lock);
2257                                 tty_port_set_initialized(port, 1);
2258                         } else {
2259                                 /*
2260                                  * Failed to resume - maybe hardware went away?
2261                                  * Clear the "initialized" flag so we won't try
2262                                  * to call the low level drivers shutdown method.
2263                                  */
2264                                 uart_shutdown(tty, state);
2265                         }
2266                 }
2267
2268                 tty_port_set_suspended(port, 0);
2269         }
2270
2271         mutex_unlock(&port->mutex);
2272
2273         return 0;
2274 }
2275
2276 static inline void
2277 uart_report_port(struct uart_driver *drv, struct uart_port *port)
2278 {
2279         char address[64];
2280
2281         switch (port->iotype) {
2282         case UPIO_PORT:
2283                 snprintf(address, sizeof(address), "I/O 0x%lx", port->iobase);
2284                 break;
2285         case UPIO_HUB6:
2286                 snprintf(address, sizeof(address),
2287                          "I/O 0x%lx offset 0x%x", port->iobase, port->hub6);
2288                 break;
2289         case UPIO_MEM:
2290         case UPIO_MEM16:
2291         case UPIO_MEM32:
2292         case UPIO_MEM32BE:
2293         case UPIO_AU:
2294         case UPIO_TSI:
2295                 snprintf(address, sizeof(address),
2296                          "MMIO 0x%llx", (unsigned long long)port->mapbase);
2297                 break;
2298         default:
2299                 strlcpy(address, "*unknown*", sizeof(address));
2300                 break;
2301         }
2302
2303         printk(KERN_INFO "%s%s%s%d at %s (irq = %d, base_baud = %d) is a %s\n",
2304                port->dev ? dev_name(port->dev) : "",
2305                port->dev ? ": " : "",
2306                drv->dev_name,
2307                drv->tty_driver->name_base + port->line,
2308                address, port->irq, port->uartclk / 16, uart_type(port));
2309 }
2310
2311 static void
2312 uart_configure_port(struct uart_driver *drv, struct uart_state *state,
2313                     struct uart_port *port)
2314 {
2315         unsigned int flags;
2316
2317         /*
2318          * If there isn't a port here, don't do anything further.
2319          */
2320         if (!port->iobase && !port->mapbase && !port->membase)
2321                 return;
2322
2323         /*
2324          * Now do the auto configuration stuff.  Note that config_port
2325          * is expected to claim the resources and map the port for us.
2326          */
2327         flags = 0;
2328         if (port->flags & UPF_AUTO_IRQ)
2329                 flags |= UART_CONFIG_IRQ;
2330         if (port->flags & UPF_BOOT_AUTOCONF) {
2331                 if (!(port->flags & UPF_FIXED_TYPE)) {
2332                         port->type = PORT_UNKNOWN;
2333                         flags |= UART_CONFIG_TYPE;
2334                 }
2335                 port->ops->config_port(port, flags);
2336         }
2337
2338         if (port->type != PORT_UNKNOWN) {
2339                 unsigned long flags;
2340
2341                 uart_report_port(drv, port);
2342
2343                 /* Power up port for set_mctrl() */
2344                 uart_change_pm(state, UART_PM_STATE_ON);
2345
2346                 /*
2347                  * Ensure that the modem control lines are de-activated.
2348                  * keep the DTR setting that is set in uart_set_options()
2349                  * We probably don't need a spinlock around this, but
2350                  */
2351                 spin_lock_irqsave(&port->lock, flags);
2352                 port->mctrl &= TIOCM_DTR;
2353                 port->ops->set_mctrl(port, port->mctrl);
2354                 spin_unlock_irqrestore(&port->lock, flags);
2355
2356                 /*
2357                  * If this driver supports console, and it hasn't been
2358                  * successfully registered yet, try to re-register it.
2359                  * It may be that the port was not available.
2360                  */
2361                 if (port->cons && !(port->cons->flags & CON_ENABLED))
2362                         register_console(port->cons);
2363
2364                 /*
2365                  * Power down all ports by default, except the
2366                  * console if we have one.
2367                  */
2368                 if (!uart_console(port))
2369                         uart_change_pm(state, UART_PM_STATE_OFF);
2370         }
2371 }
2372
2373 #ifdef CONFIG_CONSOLE_POLL
2374
2375 static int uart_poll_init(struct tty_driver *driver, int line, char *options)
2376 {
2377         struct uart_driver *drv = driver->driver_state;
2378         struct uart_state *state = drv->state + line;
2379         struct tty_port *tport;
2380         struct uart_port *port;
2381         int baud = 9600;
2382         int bits = 8;
2383         int parity = 'n';
2384         int flow = 'n';
2385         int ret = 0;
2386
2387         if (!state)
2388                 return -1;
2389
2390         tport = &state->port;
2391         mutex_lock(&tport->mutex);
2392
2393         port = uart_port_check(state);
2394         if (!port || !(port->ops->poll_get_char && port->ops->poll_put_char)) {
2395                 ret = -1;
2396                 goto out;
2397         }
2398
2399         if (port->ops->poll_init) {
2400                 /*
2401                  * We don't set initialized as we only initialized the hw,
2402                  * e.g. state->xmit is still uninitialized.
2403                  */
2404                 if (!tty_port_initialized(tport))
2405                         ret = port->ops->poll_init(port);
2406         }
2407
2408         if (!ret && options) {
2409                 uart_parse_options(options, &baud, &parity, &bits, &flow);
2410                 ret = uart_set_options(port, NULL, baud, parity, bits, flow);
2411         }
2412 out:
2413         mutex_unlock(&tport->mutex);
2414         return ret;
2415 }
2416
2417 static int uart_poll_get_char(struct tty_driver *driver, int line)
2418 {
2419         struct uart_driver *drv = driver->driver_state;
2420         struct uart_state *state = drv->state + line;
2421         struct uart_port *port;
2422         int ret = -1;
2423
2424         if (state) {
2425                 port = uart_port_ref(state);
2426                 if (port)
2427                         ret = port->ops->poll_get_char(port);
2428                 uart_port_deref(port);
2429         }
2430         return ret;
2431 }
2432
2433 static void uart_poll_put_char(struct tty_driver *driver, int line, char ch)
2434 {
2435         struct uart_driver *drv = driver->driver_state;
2436         struct uart_state *state = drv->state + line;
2437         struct uart_port *port;
2438
2439         port = uart_port_ref(state);
2440         if (!port)
2441                 return;
2442
2443         if (ch == '\n')
2444                 port->ops->poll_put_char(port, '\r');
2445         port->ops->poll_put_char(port, ch);
2446         uart_port_deref(port);
2447 }
2448 #endif
2449
2450 static int uart_install(struct tty_driver *driver, struct tty_struct *tty)
2451 {
2452         struct uart_driver *drv = driver->driver_state;
2453         struct uart_state *state = drv->state + tty->index;
2454
2455         tty->driver_data = state;
2456
2457         return tty_standard_install(driver, tty);
2458 }
2459
2460 static const struct tty_operations uart_ops = {
2461         .install        = uart_install,
2462         .open           = uart_open,
2463         .close          = uart_close,
2464         .write          = uart_write,
2465         .put_char       = uart_put_char,
2466         .flush_chars    = uart_flush_chars,
2467         .write_room     = uart_write_room,
2468         .chars_in_buffer= uart_chars_in_buffer,
2469         .flush_buffer   = uart_flush_buffer,
2470         .ioctl          = uart_ioctl,
2471         .throttle       = uart_throttle,
2472         .unthrottle     = uart_unthrottle,
2473         .send_xchar     = uart_send_xchar,
2474         .set_termios    = uart_set_termios,
2475         .set_ldisc      = uart_set_ldisc,
2476         .stop           = uart_stop,
2477         .start          = uart_start,
2478         .hangup         = uart_hangup,
2479         .break_ctl      = uart_break_ctl,
2480         .wait_until_sent= uart_wait_until_sent,
2481 #ifdef CONFIG_PROC_FS
2482         .proc_fops      = &uart_proc_fops,
2483 #endif
2484         .tiocmget       = uart_tiocmget,
2485         .tiocmset       = uart_tiocmset,
2486         .get_icount     = uart_get_icount,
2487 #ifdef CONFIG_CONSOLE_POLL
2488         .poll_init      = uart_poll_init,
2489         .poll_get_char  = uart_poll_get_char,
2490         .poll_put_char  = uart_poll_put_char,
2491 #endif
2492 };
2493
2494 static const struct tty_port_operations uart_port_ops = {
2495         .carrier_raised = uart_carrier_raised,
2496         .dtr_rts        = uart_dtr_rts,
2497         .activate       = uart_port_activate,
2498         .shutdown       = uart_tty_port_shutdown,
2499 };
2500
2501 /**
2502  *      uart_register_driver - register a driver with the uart core layer
2503  *      @drv: low level driver structure
2504  *
2505  *      Register a uart driver with the core driver.  We in turn register
2506  *      with the tty layer, and initialise the core driver per-port state.
2507  *
2508  *      We have a proc file in /proc/tty/driver which is named after the
2509  *      normal driver.
2510  *
2511  *      drv->port should be NULL, and the per-port structures should be
2512  *      registered using uart_add_one_port after this call has succeeded.
2513  */
2514 int uart_register_driver(struct uart_driver *drv)
2515 {
2516         struct tty_driver *normal;
2517         int i, retval;
2518
2519         BUG_ON(drv->state);
2520
2521         /*
2522          * Maybe we should be using a slab cache for this, especially if
2523          * we have a large number of ports to handle.
2524          */
2525         drv->state = kzalloc(sizeof(struct uart_state) * drv->nr, GFP_KERNEL);
2526         if (!drv->state)
2527                 goto out;
2528
2529         normal = alloc_tty_driver(drv->nr);
2530         if (!normal)
2531                 goto out_kfree;
2532
2533         drv->tty_driver = normal;
2534
2535         normal->driver_name     = drv->driver_name;
2536         normal->name            = drv->dev_name;
2537         normal->major           = drv->major;
2538         normal->minor_start     = drv->minor;
2539         normal->type            = TTY_DRIVER_TYPE_SERIAL;
2540         normal->subtype         = SERIAL_TYPE_NORMAL;
2541         normal->init_termios    = tty_std_termios;
2542         normal->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL;
2543         normal->init_termios.c_ispeed = normal->init_termios.c_ospeed = 9600;
2544         normal->flags           = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
2545         normal->driver_state    = drv;
2546         tty_set_operations(normal, &uart_ops);
2547
2548         /*
2549          * Initialise the UART state(s).
2550          */
2551         for (i = 0; i < drv->nr; i++) {
2552                 struct uart_state *state = drv->state + i;
2553                 struct tty_port *port = &state->port;
2554
2555                 tty_port_init(port);
2556                 port->ops = &uart_port_ops;
2557         }
2558
2559         retval = tty_register_driver(normal);
2560         if (retval >= 0)
2561                 return retval;
2562
2563         for (i = 0; i < drv->nr; i++)
2564                 tty_port_destroy(&drv->state[i].port);
2565         put_tty_driver(normal);
2566 out_kfree:
2567         kfree(drv->state);
2568 out:
2569         return -ENOMEM;
2570 }
2571
2572 /**
2573  *      uart_unregister_driver - remove a driver from the uart core layer
2574  *      @drv: low level driver structure
2575  *
2576  *      Remove all references to a driver from the core driver.  The low
2577  *      level driver must have removed all its ports via the
2578  *      uart_remove_one_port() if it registered them with uart_add_one_port().
2579  *      (ie, drv->port == NULL)
2580  */
2581 void uart_unregister_driver(struct uart_driver *drv)
2582 {
2583         struct tty_driver *p = drv->tty_driver;
2584         unsigned int i;
2585
2586         tty_unregister_driver(p);
2587         put_tty_driver(p);
2588         for (i = 0; i < drv->nr; i++)
2589                 tty_port_destroy(&drv->state[i].port);
2590         kfree(drv->state);
2591         drv->state = NULL;
2592         drv->tty_driver = NULL;
2593 }
2594
2595 struct tty_driver *uart_console_device(struct console *co, int *index)
2596 {
2597         struct uart_driver *p = co->data;
2598         *index = co->index;
2599         return p->tty_driver;
2600 }
2601
2602 static ssize_t uart_get_attr_uartclk(struct device *dev,
2603         struct device_attribute *attr, char *buf)
2604 {
2605         struct serial_struct tmp;
2606         struct tty_port *port = dev_get_drvdata(dev);
2607
2608         uart_get_info(port, &tmp);
2609         return snprintf(buf, PAGE_SIZE, "%d\n", tmp.baud_base * 16);
2610 }
2611
2612 static ssize_t uart_get_attr_type(struct device *dev,
2613         struct device_attribute *attr, char *buf)
2614 {
2615         struct serial_struct tmp;
2616         struct tty_port *port = dev_get_drvdata(dev);
2617
2618         uart_get_info(port, &tmp);
2619         return snprintf(buf, PAGE_SIZE, "%d\n", tmp.type);
2620 }
2621 static ssize_t uart_get_attr_line(struct device *dev,
2622         struct device_attribute *attr, char *buf)
2623 {
2624         struct serial_struct tmp;
2625         struct tty_port *port = dev_get_drvdata(dev);
2626
2627         uart_get_info(port, &tmp);
2628         return snprintf(buf, PAGE_SIZE, "%d\n", tmp.line);
2629 }
2630
2631 static ssize_t uart_get_attr_port(struct device *dev,
2632         struct device_attribute *attr, char *buf)
2633 {
2634         struct serial_struct tmp;
2635         struct tty_port *port = dev_get_drvdata(dev);
2636         unsigned long ioaddr;
2637
2638         uart_get_info(port, &tmp);
2639         ioaddr = tmp.port;
2640         if (HIGH_BITS_OFFSET)
2641                 ioaddr |= (unsigned long)tmp.port_high << HIGH_BITS_OFFSET;
2642         return snprintf(buf, PAGE_SIZE, "0x%lX\n", ioaddr);
2643 }
2644
2645 static ssize_t uart_get_attr_irq(struct device *dev,
2646         struct device_attribute *attr, char *buf)
2647 {
2648         struct serial_struct tmp;
2649         struct tty_port *port = dev_get_drvdata(dev);
2650
2651         uart_get_info(port, &tmp);
2652         return snprintf(buf, PAGE_SIZE, "%d\n", tmp.irq);
2653 }
2654
2655 static ssize_t uart_get_attr_flags(struct device *dev,
2656         struct device_attribute *attr, char *buf)
2657 {
2658         struct serial_struct tmp;
2659         struct tty_port *port = dev_get_drvdata(dev);
2660
2661         uart_get_info(port, &tmp);
2662         return snprintf(buf, PAGE_SIZE, "0x%X\n", tmp.flags);
2663 }
2664
2665 static ssize_t uart_get_attr_xmit_fifo_size(struct device *dev,
2666         struct device_attribute *attr, char *buf)
2667 {
2668         struct serial_struct tmp;
2669         struct tty_port *port = dev_get_drvdata(dev);
2670
2671         uart_get_info(port, &tmp);
2672         return snprintf(buf, PAGE_SIZE, "%d\n", tmp.xmit_fifo_size);
2673 }
2674
2675
2676 static ssize_t uart_get_attr_close_delay(struct device *dev,
2677         struct device_attribute *attr, char *buf)
2678 {
2679         struct serial_struct tmp;
2680         struct tty_port *port = dev_get_drvdata(dev);
2681
2682         uart_get_info(port, &tmp);
2683         return snprintf(buf, PAGE_SIZE, "%d\n", tmp.close_delay);
2684 }
2685
2686
2687 static ssize_t uart_get_attr_closing_wait(struct device *dev,
2688         struct device_attribute *attr, char *buf)
2689 {
2690         struct serial_struct tmp;
2691         struct tty_port *port = dev_get_drvdata(dev);
2692
2693         uart_get_info(port, &tmp);
2694         return snprintf(buf, PAGE_SIZE, "%d\n", tmp.closing_wait);
2695 }
2696
2697 static ssize_t uart_get_attr_custom_divisor(struct device *dev,
2698         struct device_attribute *attr, char *buf)
2699 {
2700         struct serial_struct tmp;
2701         struct tty_port *port = dev_get_drvdata(dev);
2702
2703         uart_get_info(port, &tmp);
2704         return snprintf(buf, PAGE_SIZE, "%d\n", tmp.custom_divisor);
2705 }
2706
2707 static ssize_t uart_get_attr_io_type(struct device *dev,
2708         struct device_attribute *attr, char *buf)
2709 {
2710         struct serial_struct tmp;
2711         struct tty_port *port = dev_get_drvdata(dev);
2712
2713         uart_get_info(port, &tmp);
2714         return snprintf(buf, PAGE_SIZE, "%d\n", tmp.io_type);
2715 }
2716
2717 static ssize_t uart_get_attr_iomem_base(struct device *dev,
2718         struct device_attribute *attr, char *buf)
2719 {
2720         struct serial_struct tmp;
2721         struct tty_port *port = dev_get_drvdata(dev);
2722
2723         uart_get_info(port, &tmp);
2724         return snprintf(buf, PAGE_SIZE, "0x%lX\n", (unsigned long)tmp.iomem_base);
2725 }
2726
2727 static ssize_t uart_get_attr_iomem_reg_shift(struct device *dev,
2728         struct device_attribute *attr, char *buf)
2729 {
2730         struct serial_struct tmp;
2731         struct tty_port *port = dev_get_drvdata(dev);
2732
2733         uart_get_info(port, &tmp);
2734         return snprintf(buf, PAGE_SIZE, "%d\n", tmp.iomem_reg_shift);
2735 }
2736
2737 static DEVICE_ATTR(type, S_IRUSR | S_IRGRP, uart_get_attr_type, NULL);
2738 static DEVICE_ATTR(line, S_IRUSR | S_IRGRP, uart_get_attr_line, NULL);
2739 static DEVICE_ATTR(port, S_IRUSR | S_IRGRP, uart_get_attr_port, NULL);
2740 static DEVICE_ATTR(irq, S_IRUSR | S_IRGRP, uart_get_attr_irq, NULL);
2741 static DEVICE_ATTR(flags, S_IRUSR | S_IRGRP, uart_get_attr_flags, NULL);
2742 static DEVICE_ATTR(xmit_fifo_size, S_IRUSR | S_IRGRP, uart_get_attr_xmit_fifo_size, NULL);
2743 static DEVICE_ATTR(uartclk, S_IRUSR | S_IRGRP, uart_get_attr_uartclk, NULL);
2744 static DEVICE_ATTR(close_delay, S_IRUSR | S_IRGRP, uart_get_attr_close_delay, NULL);
2745 static DEVICE_ATTR(closing_wait, S_IRUSR | S_IRGRP, uart_get_attr_closing_wait, NULL);
2746 static DEVICE_ATTR(custom_divisor, S_IRUSR | S_IRGRP, uart_get_attr_custom_divisor, NULL);
2747 static DEVICE_ATTR(io_type, S_IRUSR | S_IRGRP, uart_get_attr_io_type, NULL);
2748 static DEVICE_ATTR(iomem_base, S_IRUSR | S_IRGRP, uart_get_attr_iomem_base, NULL);
2749 static DEVICE_ATTR(iomem_reg_shift, S_IRUSR | S_IRGRP, uart_get_attr_iomem_reg_shift, NULL);
2750
2751 static struct attribute *tty_dev_attrs[] = {
2752         &dev_attr_type.attr,
2753         &dev_attr_line.attr,
2754         &dev_attr_port.attr,
2755         &dev_attr_irq.attr,
2756         &dev_attr_flags.attr,
2757         &dev_attr_xmit_fifo_size.attr,
2758         &dev_attr_uartclk.attr,
2759         &dev_attr_close_delay.attr,
2760         &dev_attr_closing_wait.attr,
2761         &dev_attr_custom_divisor.attr,
2762         &dev_attr_io_type.attr,
2763         &dev_attr_iomem_base.attr,
2764         &dev_attr_iomem_reg_shift.attr,
2765         NULL,
2766         };
2767
2768 static const struct attribute_group tty_dev_attr_group = {
2769         .attrs = tty_dev_attrs,
2770         };
2771
2772 /**
2773  *      uart_add_one_port - attach a driver-defined port structure
2774  *      @drv: pointer to the uart low level driver structure for this port
2775  *      @uport: uart port structure to use for this port.
2776  *
2777  *      This allows the driver to register its own uart_port structure
2778  *      with the core driver.  The main purpose is to allow the low
2779  *      level uart drivers to expand uart_port, rather than having yet
2780  *      more levels of structures.
2781  */
2782 int uart_add_one_port(struct uart_driver *drv, struct uart_port *uport)
2783 {
2784         struct uart_state *state;
2785         struct tty_port *port;
2786         int ret = 0;
2787         struct device *tty_dev;
2788         int num_groups;
2789
2790         BUG_ON(in_interrupt());
2791
2792         if (uport->line >= drv->nr)
2793                 return -EINVAL;
2794
2795         state = drv->state + uport->line;
2796         port = &state->port;
2797
2798         mutex_lock(&port_mutex);
2799         mutex_lock(&port->mutex);
2800         if (state->uart_port) {
2801                 ret = -EINVAL;
2802                 goto out;
2803         }
2804
2805         /* Link the port to the driver state table and vice versa */
2806         atomic_set(&state->refcount, 1);
2807         init_waitqueue_head(&state->remove_wait);
2808         state->uart_port = uport;
2809         uport->state = state;
2810
2811         state->pm_state = UART_PM_STATE_UNDEFINED;
2812         uport->cons = drv->cons;
2813         uport->minor = drv->tty_driver->minor_start + uport->line;
2814
2815         /*
2816          * If this port is a console, then the spinlock is already
2817          * initialised.
2818          */
2819         if (!(uart_console(uport) && (uport->cons->flags & CON_ENABLED))) {
2820                 spin_lock_init(&uport->lock);
2821                 lockdep_set_class(&uport->lock, &port_lock_key);
2822         }
2823         if (uport->cons && uport->dev)
2824                 of_console_check(uport->dev->of_node, uport->cons->name, uport->line);
2825
2826         tty_port_link_device(port, drv->tty_driver, uport->line);
2827         uart_configure_port(drv, state, uport);
2828
2829         port->console = uart_console(uport);
2830
2831         num_groups = 2;
2832         if (uport->attr_group)
2833                 num_groups++;
2834
2835         uport->tty_groups = kcalloc(num_groups, sizeof(*uport->tty_groups),
2836                                     GFP_KERNEL);
2837         if (!uport->tty_groups) {
2838                 ret = -ENOMEM;
2839                 goto out;
2840         }
2841         uport->tty_groups[0] = &tty_dev_attr_group;
2842         if (uport->attr_group)
2843                 uport->tty_groups[1] = uport->attr_group;
2844
2845         /*
2846          * Register the port whether it's detected or not.  This allows
2847          * setserial to be used to alter this port's parameters.
2848          */
2849         tty_dev = tty_port_register_device_attr(port, drv->tty_driver,
2850                         uport->line, uport->dev, port, uport->tty_groups);
2851         if (likely(!IS_ERR(tty_dev))) {
2852                 device_set_wakeup_capable(tty_dev, 1);
2853         } else {
2854                 dev_err(uport->dev, "Cannot register tty device on line %d\n",
2855                        uport->line);
2856         }
2857
2858         /*
2859          * Ensure UPF_DEAD is not set.
2860          */
2861         uport->flags &= ~UPF_DEAD;
2862
2863  out:
2864         mutex_unlock(&port->mutex);
2865         mutex_unlock(&port_mutex);
2866
2867         return ret;
2868 }
2869
2870 /**
2871  *      uart_remove_one_port - detach a driver defined port structure
2872  *      @drv: pointer to the uart low level driver structure for this port
2873  *      @uport: uart port structure for this port
2874  *
2875  *      This unhooks (and hangs up) the specified port structure from the
2876  *      core driver.  No further calls will be made to the low-level code
2877  *      for this port.
2878  */
2879 int uart_remove_one_port(struct uart_driver *drv, struct uart_port *uport)
2880 {
2881         struct uart_state *state = drv->state + uport->line;
2882         struct tty_port *port = &state->port;
2883         struct uart_port *uart_port;
2884         struct tty_struct *tty;
2885         int ret = 0;
2886
2887         BUG_ON(in_interrupt());
2888
2889         mutex_lock(&port_mutex);
2890
2891         /*
2892          * Mark the port "dead" - this prevents any opens from
2893          * succeeding while we shut down the port.
2894          */
2895         mutex_lock(&port->mutex);
2896         uart_port = uart_port_check(state);
2897         if (uart_port != uport)
2898                 dev_alert(uport->dev, "Removing wrong port: %p != %p\n",
2899                           uart_port, uport);
2900
2901         if (!uart_port) {
2902                 mutex_unlock(&port->mutex);
2903                 ret = -EINVAL;
2904                 goto out;
2905         }
2906         uport->flags |= UPF_DEAD;
2907         mutex_unlock(&port->mutex);
2908
2909         /*
2910          * Remove the devices from the tty layer
2911          */
2912         tty_unregister_device(drv->tty_driver, uport->line);
2913
2914         tty = tty_port_tty_get(port);
2915         if (tty) {
2916                 tty_vhangup(port->tty);
2917                 tty_kref_put(tty);
2918         }
2919
2920         /*
2921          * If the port is used as a console, unregister it
2922          */
2923         if (uart_console(uport))
2924                 unregister_console(uport->cons);
2925
2926         /*
2927          * Free the port IO and memory resources, if any.
2928          */
2929         if (uport->type != PORT_UNKNOWN && uport->ops->release_port)
2930                 uport->ops->release_port(uport);
2931         kfree(uport->tty_groups);
2932
2933         /*
2934          * Indicate that there isn't a port here anymore.
2935          */
2936         uport->type = PORT_UNKNOWN;
2937
2938         mutex_lock(&port->mutex);
2939         WARN_ON(atomic_dec_return(&state->refcount) < 0);
2940         wait_event(state->remove_wait, !atomic_read(&state->refcount));
2941         state->uart_port = NULL;
2942         mutex_unlock(&port->mutex);
2943 out:
2944         mutex_unlock(&port_mutex);
2945
2946         return ret;
2947 }
2948
2949 /*
2950  *      Are the two ports equivalent?
2951  */
2952 int uart_match_port(struct uart_port *port1, struct uart_port *port2)
2953 {
2954         if (port1->iotype != port2->iotype)
2955                 return 0;
2956
2957         switch (port1->iotype) {
2958         case UPIO_PORT:
2959                 return (port1->iobase == port2->iobase);
2960         case UPIO_HUB6:
2961                 return (port1->iobase == port2->iobase) &&
2962                        (port1->hub6   == port2->hub6);
2963         case UPIO_MEM:
2964         case UPIO_MEM16:
2965         case UPIO_MEM32:
2966         case UPIO_MEM32BE:
2967         case UPIO_AU:
2968         case UPIO_TSI:
2969                 return (port1->mapbase == port2->mapbase);
2970         }
2971         return 0;
2972 }
2973 EXPORT_SYMBOL(uart_match_port);
2974
2975 /**
2976  *      uart_handle_dcd_change - handle a change of carrier detect state
2977  *      @uport: uart_port structure for the open port
2978  *      @status: new carrier detect status, nonzero if active
2979  *
2980  *      Caller must hold uport->lock
2981  */
2982 void uart_handle_dcd_change(struct uart_port *uport, unsigned int status)
2983 {
2984         struct tty_port *port = &uport->state->port;
2985         struct tty_struct *tty = port->tty;
2986         struct tty_ldisc *ld;
2987
2988         lockdep_assert_held_once(&uport->lock);
2989
2990         if (tty) {
2991                 ld = tty_ldisc_ref(tty);
2992                 if (ld) {
2993                         if (ld->ops->dcd_change)
2994                                 ld->ops->dcd_change(tty, status);
2995                         tty_ldisc_deref(ld);
2996                 }
2997         }
2998
2999         uport->icount.dcd++;
3000
3001         if (uart_dcd_enabled(uport)) {
3002                 if (status)
3003                         wake_up_interruptible(&port->open_wait);
3004                 else if (tty)
3005                         tty_hangup(tty);
3006         }
3007 }
3008 EXPORT_SYMBOL_GPL(uart_handle_dcd_change);
3009
3010 /**
3011  *      uart_handle_cts_change - handle a change of clear-to-send state
3012  *      @uport: uart_port structure for the open port
3013  *      @status: new clear to send status, nonzero if active
3014  *
3015  *      Caller must hold uport->lock
3016  */
3017 void uart_handle_cts_change(struct uart_port *uport, unsigned int status)
3018 {
3019         lockdep_assert_held_once(&uport->lock);
3020
3021         uport->icount.cts++;
3022
3023         if (uart_softcts_mode(uport)) {
3024                 if (uport->hw_stopped) {
3025                         if (status) {
3026                                 uport->hw_stopped = 0;
3027                                 uport->ops->start_tx(uport);
3028                                 uart_write_wakeup(uport);
3029                         }
3030                 } else {
3031                         if (!status) {
3032                                 uport->hw_stopped = 1;
3033                                 uport->ops->stop_tx(uport);
3034                         }
3035                 }
3036
3037         }
3038 }
3039 EXPORT_SYMBOL_GPL(uart_handle_cts_change);
3040
3041 /**
3042  * uart_insert_char - push a char to the uart layer
3043  *
3044  * User is responsible to call tty_flip_buffer_push when they are done with
3045  * insertion.
3046  *
3047  * @port: corresponding port
3048  * @status: state of the serial port RX buffer (LSR for 8250)
3049  * @overrun: mask of overrun bits in @status
3050  * @ch: character to push
3051  * @flag: flag for the character (see TTY_NORMAL and friends)
3052  */
3053 void uart_insert_char(struct uart_port *port, unsigned int status,
3054                  unsigned int overrun, unsigned int ch, unsigned int flag)
3055 {
3056         struct tty_port *tport = &port->state->port;
3057
3058         if ((status & port->ignore_status_mask & ~overrun) == 0)
3059                 if (tty_insert_flip_char(tport, ch, flag) == 0)
3060                         ++port->icount.buf_overrun;
3061
3062         /*
3063          * Overrun is special.  Since it's reported immediately,
3064          * it doesn't affect the current character.
3065          */
3066         if (status & ~port->ignore_status_mask & overrun)
3067                 if (tty_insert_flip_char(tport, 0, TTY_OVERRUN) == 0)
3068                         ++port->icount.buf_overrun;
3069 }
3070 EXPORT_SYMBOL_GPL(uart_insert_char);
3071
3072 EXPORT_SYMBOL(uart_write_wakeup);
3073 EXPORT_SYMBOL(uart_register_driver);
3074 EXPORT_SYMBOL(uart_unregister_driver);
3075 EXPORT_SYMBOL(uart_suspend_port);
3076 EXPORT_SYMBOL(uart_resume_port);
3077 EXPORT_SYMBOL(uart_add_one_port);
3078 EXPORT_SYMBOL(uart_remove_one_port);
3079
3080 MODULE_DESCRIPTION("Serial driver core");
3081 MODULE_LICENSE("GPL");