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