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