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