GNU Linux-libre 5.10.153-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                 ops->set_mctrl(uport, 0);
2258                 ops->stop_rx(uport);
2259                 spin_unlock_irq(&uport->lock);
2260
2261                 /*
2262                  * Wait for the transmitter to empty.
2263                  */
2264                 for (tries = 3; !ops->tx_empty(uport) && tries; tries--)
2265                         msleep(10);
2266                 if (!tries)
2267                         dev_err(uport->dev, "%s: Unable to drain transmitter\n",
2268                                 uport->name);
2269
2270                 ops->shutdown(uport);
2271         }
2272
2273         /*
2274          * Disable the console device before suspending.
2275          */
2276         if (uart_console(uport))
2277                 console_stop(uport->cons);
2278
2279         uart_change_pm(state, UART_PM_STATE_OFF);
2280 unlock:
2281         mutex_unlock(&port->mutex);
2282
2283         return 0;
2284 }
2285
2286 int uart_resume_port(struct uart_driver *drv, struct uart_port *uport)
2287 {
2288         struct uart_state *state = drv->state + uport->line;
2289         struct tty_port *port = &state->port;
2290         struct device *tty_dev;
2291         struct uart_match match = {uport, drv};
2292         struct ktermios termios;
2293
2294         mutex_lock(&port->mutex);
2295
2296         tty_dev = device_find_child(uport->dev, &match, serial_match_port);
2297         if (!uport->suspended && device_may_wakeup(tty_dev)) {
2298                 if (irqd_is_wakeup_set(irq_get_irq_data((uport->irq))))
2299                         disable_irq_wake(uport->irq);
2300                 put_device(tty_dev);
2301                 mutex_unlock(&port->mutex);
2302                 return 0;
2303         }
2304         put_device(tty_dev);
2305         uport->suspended = 0;
2306
2307         /*
2308          * Re-enable the console device after suspending.
2309          */
2310         if (uart_console(uport)) {
2311                 /*
2312                  * First try to use the console cflag setting.
2313                  */
2314                 memset(&termios, 0, sizeof(struct ktermios));
2315                 termios.c_cflag = uport->cons->cflag;
2316                 termios.c_ispeed = uport->cons->ispeed;
2317                 termios.c_ospeed = uport->cons->ospeed;
2318
2319                 /*
2320                  * If that's unset, use the tty termios setting.
2321                  */
2322                 if (port->tty && termios.c_cflag == 0)
2323                         termios = port->tty->termios;
2324
2325                 if (console_suspend_enabled)
2326                         uart_change_pm(state, UART_PM_STATE_ON);
2327                 uport->ops->set_termios(uport, &termios, NULL);
2328                 if (console_suspend_enabled)
2329                         console_start(uport->cons);
2330         }
2331
2332         if (tty_port_suspended(port)) {
2333                 const struct uart_ops *ops = uport->ops;
2334                 int ret;
2335
2336                 uart_change_pm(state, UART_PM_STATE_ON);
2337                 spin_lock_irq(&uport->lock);
2338                 if (!(uport->rs485.flags & SER_RS485_ENABLED))
2339                         ops->set_mctrl(uport, 0);
2340                 spin_unlock_irq(&uport->lock);
2341                 if (console_suspend_enabled || !uart_console(uport)) {
2342                         /* Protected by port mutex for now */
2343                         struct tty_struct *tty = port->tty;
2344
2345                         ret = ops->startup(uport);
2346                         if (ret == 0) {
2347                                 if (tty)
2348                                         uart_change_speed(tty, state, NULL);
2349                                 spin_lock_irq(&uport->lock);
2350                                 if (!(uport->rs485.flags & SER_RS485_ENABLED))
2351                                         ops->set_mctrl(uport, uport->mctrl);
2352                                 else
2353                                         uport->rs485_config(uport, &uport->rs485);
2354                                 ops->start_tx(uport);
2355                                 spin_unlock_irq(&uport->lock);
2356                                 tty_port_set_initialized(port, 1);
2357                         } else {
2358                                 /*
2359                                  * Failed to resume - maybe hardware went away?
2360                                  * Clear the "initialized" flag so we won't try
2361                                  * to call the low level drivers shutdown method.
2362                                  */
2363                                 uart_shutdown(tty, state);
2364                         }
2365                 }
2366
2367                 tty_port_set_suspended(port, 0);
2368         }
2369
2370         mutex_unlock(&port->mutex);
2371
2372         return 0;
2373 }
2374
2375 static inline void
2376 uart_report_port(struct uart_driver *drv, struct uart_port *port)
2377 {
2378         char address[64];
2379
2380         switch (port->iotype) {
2381         case UPIO_PORT:
2382                 snprintf(address, sizeof(address), "I/O 0x%lx", port->iobase);
2383                 break;
2384         case UPIO_HUB6:
2385                 snprintf(address, sizeof(address),
2386                          "I/O 0x%lx offset 0x%x", port->iobase, port->hub6);
2387                 break;
2388         case UPIO_MEM:
2389         case UPIO_MEM16:
2390         case UPIO_MEM32:
2391         case UPIO_MEM32BE:
2392         case UPIO_AU:
2393         case UPIO_TSI:
2394                 snprintf(address, sizeof(address),
2395                          "MMIO 0x%llx", (unsigned long long)port->mapbase);
2396                 break;
2397         default:
2398                 strlcpy(address, "*unknown*", sizeof(address));
2399                 break;
2400         }
2401
2402         pr_info("%s%s%s at %s (irq = %d, base_baud = %d) is a %s\n",
2403                port->dev ? dev_name(port->dev) : "",
2404                port->dev ? ": " : "",
2405                port->name,
2406                address, port->irq, port->uartclk / 16, uart_type(port));
2407 }
2408
2409 static void
2410 uart_configure_port(struct uart_driver *drv, struct uart_state *state,
2411                     struct uart_port *port)
2412 {
2413         unsigned int flags;
2414
2415         /*
2416          * If there isn't a port here, don't do anything further.
2417          */
2418         if (!port->iobase && !port->mapbase && !port->membase)
2419                 return;
2420
2421         /*
2422          * Now do the auto configuration stuff.  Note that config_port
2423          * is expected to claim the resources and map the port for us.
2424          */
2425         flags = 0;
2426         if (port->flags & UPF_AUTO_IRQ)
2427                 flags |= UART_CONFIG_IRQ;
2428         if (port->flags & UPF_BOOT_AUTOCONF) {
2429                 if (!(port->flags & UPF_FIXED_TYPE)) {
2430                         port->type = PORT_UNKNOWN;
2431                         flags |= UART_CONFIG_TYPE;
2432                 }
2433                 port->ops->config_port(port, flags);
2434         }
2435
2436         if (port->type != PORT_UNKNOWN) {
2437                 unsigned long flags;
2438
2439                 uart_report_port(drv, port);
2440
2441                 /* Power up port for set_mctrl() */
2442                 uart_change_pm(state, UART_PM_STATE_ON);
2443
2444                 /*
2445                  * Ensure that the modem control lines are de-activated.
2446                  * keep the DTR setting that is set in uart_set_options()
2447                  * We probably don't need a spinlock around this, but
2448                  */
2449                 spin_lock_irqsave(&port->lock, flags);
2450                 port->mctrl &= TIOCM_DTR;
2451                 if (!(port->rs485.flags & SER_RS485_ENABLED))
2452                         port->ops->set_mctrl(port, port->mctrl);
2453                 else
2454                         port->rs485_config(port, &port->rs485);
2455                 spin_unlock_irqrestore(&port->lock, flags);
2456
2457                 /*
2458                  * If this driver supports console, and it hasn't been
2459                  * successfully registered yet, try to re-register it.
2460                  * It may be that the port was not available.
2461                  */
2462                 if (port->cons && !(port->cons->flags & CON_ENABLED))
2463                         register_console(port->cons);
2464
2465                 /*
2466                  * Power down all ports by default, except the
2467                  * console if we have one.
2468                  */
2469                 if (!uart_console(port))
2470                         uart_change_pm(state, UART_PM_STATE_OFF);
2471         }
2472 }
2473
2474 #ifdef CONFIG_CONSOLE_POLL
2475
2476 static int uart_poll_init(struct tty_driver *driver, int line, char *options)
2477 {
2478         struct uart_driver *drv = driver->driver_state;
2479         struct uart_state *state = drv->state + line;
2480         struct tty_port *tport;
2481         struct uart_port *port;
2482         int baud = 9600;
2483         int bits = 8;
2484         int parity = 'n';
2485         int flow = 'n';
2486         int ret = 0;
2487
2488         tport = &state->port;
2489         mutex_lock(&tport->mutex);
2490
2491         port = uart_port_check(state);
2492         if (!port || !(port->ops->poll_get_char && port->ops->poll_put_char)) {
2493                 ret = -1;
2494                 goto out;
2495         }
2496
2497         if (port->ops->poll_init) {
2498                 /*
2499                  * We don't set initialized as we only initialized the hw,
2500                  * e.g. state->xmit is still uninitialized.
2501                  */
2502                 if (!tty_port_initialized(tport))
2503                         ret = port->ops->poll_init(port);
2504         }
2505
2506         if (!ret && options) {
2507                 uart_parse_options(options, &baud, &parity, &bits, &flow);
2508                 ret = uart_set_options(port, NULL, baud, parity, bits, flow);
2509         }
2510 out:
2511         mutex_unlock(&tport->mutex);
2512         return ret;
2513 }
2514
2515 static int uart_poll_get_char(struct tty_driver *driver, int line)
2516 {
2517         struct uart_driver *drv = driver->driver_state;
2518         struct uart_state *state = drv->state + line;
2519         struct uart_port *port;
2520         int ret = -1;
2521
2522         port = uart_port_ref(state);
2523         if (port) {
2524                 ret = port->ops->poll_get_char(port);
2525                 uart_port_deref(port);
2526         }
2527
2528         return ret;
2529 }
2530
2531 static void uart_poll_put_char(struct tty_driver *driver, int line, char ch)
2532 {
2533         struct uart_driver *drv = driver->driver_state;
2534         struct uart_state *state = drv->state + line;
2535         struct uart_port *port;
2536
2537         port = uart_port_ref(state);
2538         if (!port)
2539                 return;
2540
2541         if (ch == '\n')
2542                 port->ops->poll_put_char(port, '\r');
2543         port->ops->poll_put_char(port, ch);
2544         uart_port_deref(port);
2545 }
2546 #endif
2547
2548 static const struct tty_operations uart_ops = {
2549         .install        = uart_install,
2550         .open           = uart_open,
2551         .close          = uart_close,
2552         .write          = uart_write,
2553         .put_char       = uart_put_char,
2554         .flush_chars    = uart_flush_chars,
2555         .write_room     = uart_write_room,
2556         .chars_in_buffer= uart_chars_in_buffer,
2557         .flush_buffer   = uart_flush_buffer,
2558         .ioctl          = uart_ioctl,
2559         .throttle       = uart_throttle,
2560         .unthrottle     = uart_unthrottle,
2561         .send_xchar     = uart_send_xchar,
2562         .set_termios    = uart_set_termios,
2563         .set_ldisc      = uart_set_ldisc,
2564         .stop           = uart_stop,
2565         .start          = uart_start,
2566         .hangup         = uart_hangup,
2567         .break_ctl      = uart_break_ctl,
2568         .wait_until_sent= uart_wait_until_sent,
2569 #ifdef CONFIG_PROC_FS
2570         .proc_show      = uart_proc_show,
2571 #endif
2572         .tiocmget       = uart_tiocmget,
2573         .tiocmset       = uart_tiocmset,
2574         .set_serial     = uart_set_info_user,
2575         .get_serial     = uart_get_info_user,
2576         .get_icount     = uart_get_icount,
2577 #ifdef CONFIG_CONSOLE_POLL
2578         .poll_init      = uart_poll_init,
2579         .poll_get_char  = uart_poll_get_char,
2580         .poll_put_char  = uart_poll_put_char,
2581 #endif
2582 };
2583
2584 static const struct tty_port_operations uart_port_ops = {
2585         .carrier_raised = uart_carrier_raised,
2586         .dtr_rts        = uart_dtr_rts,
2587         .activate       = uart_port_activate,
2588         .shutdown       = uart_tty_port_shutdown,
2589 };
2590
2591 /**
2592  *      uart_register_driver - register a driver with the uart core layer
2593  *      @drv: low level driver structure
2594  *
2595  *      Register a uart driver with the core driver.  We in turn register
2596  *      with the tty layer, and initialise the core driver per-port state.
2597  *
2598  *      We have a proc file in /proc/tty/driver which is named after the
2599  *      normal driver.
2600  *
2601  *      drv->port should be NULL, and the per-port structures should be
2602  *      registered using uart_add_one_port after this call has succeeded.
2603  */
2604 int uart_register_driver(struct uart_driver *drv)
2605 {
2606         struct tty_driver *normal;
2607         int i, retval = -ENOMEM;
2608
2609         BUG_ON(drv->state);
2610
2611         /*
2612          * Maybe we should be using a slab cache for this, especially if
2613          * we have a large number of ports to handle.
2614          */
2615         drv->state = kcalloc(drv->nr, sizeof(struct uart_state), GFP_KERNEL);
2616         if (!drv->state)
2617                 goto out;
2618
2619         normal = alloc_tty_driver(drv->nr);
2620         if (!normal)
2621                 goto out_kfree;
2622
2623         drv->tty_driver = normal;
2624
2625         normal->driver_name     = drv->driver_name;
2626         normal->name            = drv->dev_name;
2627         normal->major           = drv->major;
2628         normal->minor_start     = drv->minor;
2629         normal->type            = TTY_DRIVER_TYPE_SERIAL;
2630         normal->subtype         = SERIAL_TYPE_NORMAL;
2631         normal->init_termios    = tty_std_termios;
2632         normal->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL;
2633         normal->init_termios.c_ispeed = normal->init_termios.c_ospeed = 9600;
2634         normal->flags           = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
2635         normal->driver_state    = drv;
2636         tty_set_operations(normal, &uart_ops);
2637
2638         /*
2639          * Initialise the UART state(s).
2640          */
2641         for (i = 0; i < drv->nr; i++) {
2642                 struct uart_state *state = drv->state + i;
2643                 struct tty_port *port = &state->port;
2644
2645                 tty_port_init(port);
2646                 port->ops = &uart_port_ops;
2647         }
2648
2649         retval = tty_register_driver(normal);
2650         if (retval >= 0)
2651                 return retval;
2652
2653         for (i = 0; i < drv->nr; i++)
2654                 tty_port_destroy(&drv->state[i].port);
2655         put_tty_driver(normal);
2656 out_kfree:
2657         kfree(drv->state);
2658 out:
2659         return retval;
2660 }
2661
2662 /**
2663  *      uart_unregister_driver - remove a driver from the uart core layer
2664  *      @drv: low level driver structure
2665  *
2666  *      Remove all references to a driver from the core driver.  The low
2667  *      level driver must have removed all its ports via the
2668  *      uart_remove_one_port() if it registered them with uart_add_one_port().
2669  *      (ie, drv->port == NULL)
2670  */
2671 void uart_unregister_driver(struct uart_driver *drv)
2672 {
2673         struct tty_driver *p = drv->tty_driver;
2674         unsigned int i;
2675
2676         tty_unregister_driver(p);
2677         put_tty_driver(p);
2678         for (i = 0; i < drv->nr; i++)
2679                 tty_port_destroy(&drv->state[i].port);
2680         kfree(drv->state);
2681         drv->state = NULL;
2682         drv->tty_driver = NULL;
2683 }
2684
2685 struct tty_driver *uart_console_device(struct console *co, int *index)
2686 {
2687         struct uart_driver *p = co->data;
2688         *index = co->index;
2689         return p->tty_driver;
2690 }
2691 EXPORT_SYMBOL_GPL(uart_console_device);
2692
2693 static ssize_t uartclk_show(struct device *dev,
2694         struct device_attribute *attr, char *buf)
2695 {
2696         struct serial_struct tmp;
2697         struct tty_port *port = dev_get_drvdata(dev);
2698
2699         uart_get_info(port, &tmp);
2700         return sprintf(buf, "%d\n", tmp.baud_base * 16);
2701 }
2702
2703 static ssize_t type_show(struct device *dev,
2704         struct device_attribute *attr, char *buf)
2705 {
2706         struct serial_struct tmp;
2707         struct tty_port *port = dev_get_drvdata(dev);
2708
2709         uart_get_info(port, &tmp);
2710         return sprintf(buf, "%d\n", tmp.type);
2711 }
2712
2713 static ssize_t line_show(struct device *dev,
2714         struct device_attribute *attr, char *buf)
2715 {
2716         struct serial_struct tmp;
2717         struct tty_port *port = dev_get_drvdata(dev);
2718
2719         uart_get_info(port, &tmp);
2720         return sprintf(buf, "%d\n", tmp.line);
2721 }
2722
2723 static ssize_t port_show(struct device *dev,
2724         struct device_attribute *attr, char *buf)
2725 {
2726         struct serial_struct tmp;
2727         struct tty_port *port = dev_get_drvdata(dev);
2728         unsigned long ioaddr;
2729
2730         uart_get_info(port, &tmp);
2731         ioaddr = tmp.port;
2732         if (HIGH_BITS_OFFSET)
2733                 ioaddr |= (unsigned long)tmp.port_high << HIGH_BITS_OFFSET;
2734         return sprintf(buf, "0x%lX\n", ioaddr);
2735 }
2736
2737 static ssize_t irq_show(struct device *dev,
2738         struct device_attribute *attr, char *buf)
2739 {
2740         struct serial_struct tmp;
2741         struct tty_port *port = dev_get_drvdata(dev);
2742
2743         uart_get_info(port, &tmp);
2744         return sprintf(buf, "%d\n", tmp.irq);
2745 }
2746
2747 static ssize_t flags_show(struct device *dev,
2748         struct device_attribute *attr, char *buf)
2749 {
2750         struct serial_struct tmp;
2751         struct tty_port *port = dev_get_drvdata(dev);
2752
2753         uart_get_info(port, &tmp);
2754         return sprintf(buf, "0x%X\n", tmp.flags);
2755 }
2756
2757 static ssize_t xmit_fifo_size_show(struct device *dev,
2758         struct device_attribute *attr, char *buf)
2759 {
2760         struct serial_struct tmp;
2761         struct tty_port *port = dev_get_drvdata(dev);
2762
2763         uart_get_info(port, &tmp);
2764         return sprintf(buf, "%d\n", tmp.xmit_fifo_size);
2765 }
2766
2767 static ssize_t close_delay_show(struct device *dev,
2768         struct device_attribute *attr, char *buf)
2769 {
2770         struct serial_struct tmp;
2771         struct tty_port *port = dev_get_drvdata(dev);
2772
2773         uart_get_info(port, &tmp);
2774         return sprintf(buf, "%d\n", tmp.close_delay);
2775 }
2776
2777 static ssize_t closing_wait_show(struct device *dev,
2778         struct device_attribute *attr, char *buf)
2779 {
2780         struct serial_struct tmp;
2781         struct tty_port *port = dev_get_drvdata(dev);
2782
2783         uart_get_info(port, &tmp);
2784         return sprintf(buf, "%d\n", tmp.closing_wait);
2785 }
2786
2787 static ssize_t custom_divisor_show(struct device *dev,
2788         struct device_attribute *attr, char *buf)
2789 {
2790         struct serial_struct tmp;
2791         struct tty_port *port = dev_get_drvdata(dev);
2792
2793         uart_get_info(port, &tmp);
2794         return sprintf(buf, "%d\n", tmp.custom_divisor);
2795 }
2796
2797 static ssize_t io_type_show(struct device *dev,
2798         struct device_attribute *attr, char *buf)
2799 {
2800         struct serial_struct tmp;
2801         struct tty_port *port = dev_get_drvdata(dev);
2802
2803         uart_get_info(port, &tmp);
2804         return sprintf(buf, "%d\n", tmp.io_type);
2805 }
2806
2807 static ssize_t iomem_base_show(struct device *dev,
2808         struct device_attribute *attr, char *buf)
2809 {
2810         struct serial_struct tmp;
2811         struct tty_port *port = dev_get_drvdata(dev);
2812
2813         uart_get_info(port, &tmp);
2814         return sprintf(buf, "0x%lX\n", (unsigned long)tmp.iomem_base);
2815 }
2816
2817 static ssize_t iomem_reg_shift_show(struct device *dev,
2818         struct device_attribute *attr, char *buf)
2819 {
2820         struct serial_struct tmp;
2821         struct tty_port *port = dev_get_drvdata(dev);
2822
2823         uart_get_info(port, &tmp);
2824         return sprintf(buf, "%d\n", tmp.iomem_reg_shift);
2825 }
2826
2827 static ssize_t console_show(struct device *dev,
2828         struct device_attribute *attr, char *buf)
2829 {
2830         struct tty_port *port = dev_get_drvdata(dev);
2831         struct uart_state *state = container_of(port, struct uart_state, port);
2832         struct uart_port *uport;
2833         bool console = false;
2834
2835         mutex_lock(&port->mutex);
2836         uport = uart_port_check(state);
2837         if (uport)
2838                 console = uart_console_enabled(uport);
2839         mutex_unlock(&port->mutex);
2840
2841         return sprintf(buf, "%c\n", console ? 'Y' : 'N');
2842 }
2843
2844 static ssize_t console_store(struct device *dev,
2845         struct device_attribute *attr, const char *buf, size_t count)
2846 {
2847         struct tty_port *port = dev_get_drvdata(dev);
2848         struct uart_state *state = container_of(port, struct uart_state, port);
2849         struct uart_port *uport;
2850         bool oldconsole, newconsole;
2851         int ret;
2852
2853         ret = kstrtobool(buf, &newconsole);
2854         if (ret)
2855                 return ret;
2856
2857         mutex_lock(&port->mutex);
2858         uport = uart_port_check(state);
2859         if (uport) {
2860                 oldconsole = uart_console_enabled(uport);
2861                 if (oldconsole && !newconsole) {
2862                         ret = unregister_console(uport->cons);
2863                 } else if (!oldconsole && newconsole) {
2864                         if (uart_console(uport)) {
2865                                 uport->console_reinit = 1;
2866                                 register_console(uport->cons);
2867                         } else {
2868                                 ret = -ENOENT;
2869                         }
2870                 }
2871         } else {
2872                 ret = -ENXIO;
2873         }
2874         mutex_unlock(&port->mutex);
2875
2876         return ret < 0 ? ret : count;
2877 }
2878
2879 static DEVICE_ATTR_RO(uartclk);
2880 static DEVICE_ATTR_RO(type);
2881 static DEVICE_ATTR_RO(line);
2882 static DEVICE_ATTR_RO(port);
2883 static DEVICE_ATTR_RO(irq);
2884 static DEVICE_ATTR_RO(flags);
2885 static DEVICE_ATTR_RO(xmit_fifo_size);
2886 static DEVICE_ATTR_RO(close_delay);
2887 static DEVICE_ATTR_RO(closing_wait);
2888 static DEVICE_ATTR_RO(custom_divisor);
2889 static DEVICE_ATTR_RO(io_type);
2890 static DEVICE_ATTR_RO(iomem_base);
2891 static DEVICE_ATTR_RO(iomem_reg_shift);
2892 static DEVICE_ATTR_RW(console);
2893
2894 static struct attribute *tty_dev_attrs[] = {
2895         &dev_attr_uartclk.attr,
2896         &dev_attr_type.attr,
2897         &dev_attr_line.attr,
2898         &dev_attr_port.attr,
2899         &dev_attr_irq.attr,
2900         &dev_attr_flags.attr,
2901         &dev_attr_xmit_fifo_size.attr,
2902         &dev_attr_close_delay.attr,
2903         &dev_attr_closing_wait.attr,
2904         &dev_attr_custom_divisor.attr,
2905         &dev_attr_io_type.attr,
2906         &dev_attr_iomem_base.attr,
2907         &dev_attr_iomem_reg_shift.attr,
2908         &dev_attr_console.attr,
2909         NULL
2910 };
2911
2912 static const struct attribute_group tty_dev_attr_group = {
2913         .attrs = tty_dev_attrs,
2914 };
2915
2916 /**
2917  *      uart_add_one_port - attach a driver-defined port structure
2918  *      @drv: pointer to the uart low level driver structure for this port
2919  *      @uport: uart port structure to use for this port.
2920  *
2921  *      This allows the driver to register its own uart_port structure
2922  *      with the core driver.  The main purpose is to allow the low
2923  *      level uart drivers to expand uart_port, rather than having yet
2924  *      more levels of structures.
2925  */
2926 int uart_add_one_port(struct uart_driver *drv, struct uart_port *uport)
2927 {
2928         struct uart_state *state;
2929         struct tty_port *port;
2930         int ret = 0;
2931         struct device *tty_dev;
2932         int num_groups;
2933
2934         BUG_ON(in_interrupt());
2935
2936         if (uport->line >= drv->nr)
2937                 return -EINVAL;
2938
2939         state = drv->state + uport->line;
2940         port = &state->port;
2941
2942         mutex_lock(&port_mutex);
2943         mutex_lock(&port->mutex);
2944         if (state->uart_port) {
2945                 ret = -EINVAL;
2946                 goto out;
2947         }
2948
2949         /* Link the port to the driver state table and vice versa */
2950         atomic_set(&state->refcount, 1);
2951         init_waitqueue_head(&state->remove_wait);
2952         state->uart_port = uport;
2953         uport->state = state;
2954
2955         state->pm_state = UART_PM_STATE_UNDEFINED;
2956         uport->cons = drv->cons;
2957         uport->minor = drv->tty_driver->minor_start + uport->line;
2958         uport->name = kasprintf(GFP_KERNEL, "%s%d", drv->dev_name,
2959                                 drv->tty_driver->name_base + uport->line);
2960         if (!uport->name) {
2961                 ret = -ENOMEM;
2962                 goto out;
2963         }
2964
2965         /*
2966          * If this port is in use as a console then the spinlock is already
2967          * initialised.
2968          */
2969         if (!uart_console_enabled(uport))
2970                 uart_port_spin_lock_init(uport);
2971
2972         if (uport->cons && uport->dev)
2973                 of_console_check(uport->dev->of_node, uport->cons->name, uport->line);
2974
2975         tty_port_link_device(port, drv->tty_driver, uport->line);
2976         uart_configure_port(drv, state, uport);
2977
2978         port->console = uart_console(uport);
2979
2980         num_groups = 2;
2981         if (uport->attr_group)
2982                 num_groups++;
2983
2984         uport->tty_groups = kcalloc(num_groups, sizeof(*uport->tty_groups),
2985                                     GFP_KERNEL);
2986         if (!uport->tty_groups) {
2987                 ret = -ENOMEM;
2988                 goto out;
2989         }
2990         uport->tty_groups[0] = &tty_dev_attr_group;
2991         if (uport->attr_group)
2992                 uport->tty_groups[1] = uport->attr_group;
2993
2994         /*
2995          * Register the port whether it's detected or not.  This allows
2996          * setserial to be used to alter this port's parameters.
2997          */
2998         tty_dev = tty_port_register_device_attr_serdev(port, drv->tty_driver,
2999                         uport->line, uport->dev, port, uport->tty_groups);
3000         if (!IS_ERR(tty_dev)) {
3001                 device_set_wakeup_capable(tty_dev, 1);
3002         } else {
3003                 dev_err(uport->dev, "Cannot register tty device on line %d\n",
3004                        uport->line);
3005         }
3006
3007         /*
3008          * Ensure UPF_DEAD is not set.
3009          */
3010         uport->flags &= ~UPF_DEAD;
3011
3012  out:
3013         mutex_unlock(&port->mutex);
3014         mutex_unlock(&port_mutex);
3015
3016         return ret;
3017 }
3018
3019 /**
3020  *      uart_remove_one_port - detach a driver defined port structure
3021  *      @drv: pointer to the uart low level driver structure for this port
3022  *      @uport: uart port structure for this port
3023  *
3024  *      This unhooks (and hangs up) the specified port structure from the
3025  *      core driver.  No further calls will be made to the low-level code
3026  *      for this port.
3027  */
3028 int uart_remove_one_port(struct uart_driver *drv, struct uart_port *uport)
3029 {
3030         struct uart_state *state = drv->state + uport->line;
3031         struct tty_port *port = &state->port;
3032         struct uart_port *uart_port;
3033         struct tty_struct *tty;
3034         int ret = 0;
3035
3036         BUG_ON(in_interrupt());
3037
3038         mutex_lock(&port_mutex);
3039
3040         /*
3041          * Mark the port "dead" - this prevents any opens from
3042          * succeeding while we shut down the port.
3043          */
3044         mutex_lock(&port->mutex);
3045         uart_port = uart_port_check(state);
3046         if (uart_port != uport)
3047                 dev_alert(uport->dev, "Removing wrong port: %p != %p\n",
3048                           uart_port, uport);
3049
3050         if (!uart_port) {
3051                 mutex_unlock(&port->mutex);
3052                 ret = -EINVAL;
3053                 goto out;
3054         }
3055         uport->flags |= UPF_DEAD;
3056         mutex_unlock(&port->mutex);
3057
3058         /*
3059          * Remove the devices from the tty layer
3060          */
3061         tty_port_unregister_device(port, drv->tty_driver, uport->line);
3062
3063         tty = tty_port_tty_get(port);
3064         if (tty) {
3065                 tty_vhangup(port->tty);
3066                 tty_kref_put(tty);
3067         }
3068
3069         /*
3070          * If the port is used as a console, unregister it
3071          */
3072         if (uart_console(uport))
3073                 unregister_console(uport->cons);
3074
3075         /*
3076          * Free the port IO and memory resources, if any.
3077          */
3078         if (uport->type != PORT_UNKNOWN && uport->ops->release_port)
3079                 uport->ops->release_port(uport);
3080         kfree(uport->tty_groups);
3081         kfree(uport->name);
3082
3083         /*
3084          * Indicate that there isn't a port here anymore.
3085          */
3086         uport->type = PORT_UNKNOWN;
3087
3088         mutex_lock(&port->mutex);
3089         WARN_ON(atomic_dec_return(&state->refcount) < 0);
3090         wait_event(state->remove_wait, !atomic_read(&state->refcount));
3091         state->uart_port = NULL;
3092         mutex_unlock(&port->mutex);
3093 out:
3094         mutex_unlock(&port_mutex);
3095
3096         return ret;
3097 }
3098
3099 /*
3100  *      Are the two ports equivalent?
3101  */
3102 int uart_match_port(struct uart_port *port1, struct uart_port *port2)
3103 {
3104         if (port1->iotype != port2->iotype)
3105                 return 0;
3106
3107         switch (port1->iotype) {
3108         case UPIO_PORT:
3109                 return (port1->iobase == port2->iobase);
3110         case UPIO_HUB6:
3111                 return (port1->iobase == port2->iobase) &&
3112                        (port1->hub6   == port2->hub6);
3113         case UPIO_MEM:
3114         case UPIO_MEM16:
3115         case UPIO_MEM32:
3116         case UPIO_MEM32BE:
3117         case UPIO_AU:
3118         case UPIO_TSI:
3119                 return (port1->mapbase == port2->mapbase);
3120         }
3121         return 0;
3122 }
3123 EXPORT_SYMBOL(uart_match_port);
3124
3125 /**
3126  *      uart_handle_dcd_change - handle a change of carrier detect state
3127  *      @uport: uart_port structure for the open port
3128  *      @status: new carrier detect status, nonzero if active
3129  *
3130  *      Caller must hold uport->lock
3131  */
3132 void uart_handle_dcd_change(struct uart_port *uport, unsigned int status)
3133 {
3134         struct tty_port *port = &uport->state->port;
3135         struct tty_struct *tty = port->tty;
3136         struct tty_ldisc *ld;
3137
3138         lockdep_assert_held_once(&uport->lock);
3139
3140         if (tty) {
3141                 ld = tty_ldisc_ref(tty);
3142                 if (ld) {
3143                         if (ld->ops->dcd_change)
3144                                 ld->ops->dcd_change(tty, status);
3145                         tty_ldisc_deref(ld);
3146                 }
3147         }
3148
3149         uport->icount.dcd++;
3150
3151         if (uart_dcd_enabled(uport)) {
3152                 if (status)
3153                         wake_up_interruptible(&port->open_wait);
3154                 else if (tty)
3155                         tty_hangup(tty);
3156         }
3157 }
3158 EXPORT_SYMBOL_GPL(uart_handle_dcd_change);
3159
3160 /**
3161  *      uart_handle_cts_change - handle a change of clear-to-send state
3162  *      @uport: uart_port structure for the open port
3163  *      @status: new clear to send status, nonzero if active
3164  *
3165  *      Caller must hold uport->lock
3166  */
3167 void uart_handle_cts_change(struct uart_port *uport, unsigned int status)
3168 {
3169         lockdep_assert_held_once(&uport->lock);
3170
3171         uport->icount.cts++;
3172
3173         if (uart_softcts_mode(uport)) {
3174                 if (uport->hw_stopped) {
3175                         if (status) {
3176                                 uport->hw_stopped = 0;
3177                                 uport->ops->start_tx(uport);
3178                                 uart_write_wakeup(uport);
3179                         }
3180                 } else {
3181                         if (!status) {
3182                                 uport->hw_stopped = 1;
3183                                 uport->ops->stop_tx(uport);
3184                         }
3185                 }
3186
3187         }
3188 }
3189 EXPORT_SYMBOL_GPL(uart_handle_cts_change);
3190
3191 /**
3192  * uart_insert_char - push a char to the uart layer
3193  *
3194  * User is responsible to call tty_flip_buffer_push when they are done with
3195  * insertion.
3196  *
3197  * @port: corresponding port
3198  * @status: state of the serial port RX buffer (LSR for 8250)
3199  * @overrun: mask of overrun bits in @status
3200  * @ch: character to push
3201  * @flag: flag for the character (see TTY_NORMAL and friends)
3202  */
3203 void uart_insert_char(struct uart_port *port, unsigned int status,
3204                  unsigned int overrun, unsigned int ch, unsigned int flag)
3205 {
3206         struct tty_port *tport = &port->state->port;
3207
3208         if ((status & port->ignore_status_mask & ~overrun) == 0)
3209                 if (tty_insert_flip_char(tport, ch, flag) == 0)
3210                         ++port->icount.buf_overrun;
3211
3212         /*
3213          * Overrun is special.  Since it's reported immediately,
3214          * it doesn't affect the current character.
3215          */
3216         if (status & ~port->ignore_status_mask & overrun)
3217                 if (tty_insert_flip_char(tport, 0, TTY_OVERRUN) == 0)
3218                         ++port->icount.buf_overrun;
3219 }
3220 EXPORT_SYMBOL_GPL(uart_insert_char);
3221
3222 #ifdef CONFIG_MAGIC_SYSRQ_SERIAL
3223 static const char sysrq_toggle_seq[] = CONFIG_MAGIC_SYSRQ_SERIAL_SEQUENCE;
3224
3225 static void uart_sysrq_on(struct work_struct *w)
3226 {
3227         int sysrq_toggle_seq_len = strlen(sysrq_toggle_seq);
3228
3229         sysrq_toggle_support(1);
3230         pr_info("SysRq is enabled by magic sequence '%*pE' on serial\n",
3231                 sysrq_toggle_seq_len, sysrq_toggle_seq);
3232 }
3233 static DECLARE_WORK(sysrq_enable_work, uart_sysrq_on);
3234
3235 /**
3236  *      uart_try_toggle_sysrq - Enables SysRq from serial line
3237  *      @port: uart_port structure where char(s) after BREAK met
3238  *      @ch: new character in the sequence after received BREAK
3239  *
3240  *      Enables magic SysRq when the required sequence is met on port
3241  *      (see CONFIG_MAGIC_SYSRQ_SERIAL_SEQUENCE).
3242  *
3243  *      Returns false if @ch is out of enabling sequence and should be
3244  *      handled some other way, true if @ch was consumed.
3245  */
3246 bool uart_try_toggle_sysrq(struct uart_port *port, unsigned int ch)
3247 {
3248         int sysrq_toggle_seq_len = strlen(sysrq_toggle_seq);
3249
3250         if (!sysrq_toggle_seq_len)
3251                 return false;
3252
3253         BUILD_BUG_ON(ARRAY_SIZE(sysrq_toggle_seq) >= U8_MAX);
3254         if (sysrq_toggle_seq[port->sysrq_seq] != ch) {
3255                 port->sysrq_seq = 0;
3256                 return false;
3257         }
3258
3259         if (++port->sysrq_seq < sysrq_toggle_seq_len) {
3260                 port->sysrq = jiffies + SYSRQ_TIMEOUT;
3261                 return true;
3262         }
3263
3264         schedule_work(&sysrq_enable_work);
3265
3266         port->sysrq = 0;
3267         return true;
3268 }
3269 EXPORT_SYMBOL_GPL(uart_try_toggle_sysrq);
3270 #endif
3271
3272 EXPORT_SYMBOL(uart_write_wakeup);
3273 EXPORT_SYMBOL(uart_register_driver);
3274 EXPORT_SYMBOL(uart_unregister_driver);
3275 EXPORT_SYMBOL(uart_suspend_port);
3276 EXPORT_SYMBOL(uart_resume_port);
3277 EXPORT_SYMBOL(uart_add_one_port);
3278 EXPORT_SYMBOL(uart_remove_one_port);
3279
3280 /**
3281  * uart_get_rs485_mode() - retrieve rs485 properties for given uart
3282  * @port: uart device's target port
3283  *
3284  * This function implements the device tree binding described in
3285  * Documentation/devicetree/bindings/serial/rs485.txt.
3286  */
3287 int uart_get_rs485_mode(struct uart_port *port)
3288 {
3289         struct serial_rs485 *rs485conf = &port->rs485;
3290         struct device *dev = port->dev;
3291         u32 rs485_delay[2];
3292         int ret;
3293
3294         ret = device_property_read_u32_array(dev, "rs485-rts-delay",
3295                                              rs485_delay, 2);
3296         if (!ret) {
3297                 rs485conf->delay_rts_before_send = rs485_delay[0];
3298                 rs485conf->delay_rts_after_send = rs485_delay[1];
3299         } else {
3300                 rs485conf->delay_rts_before_send = 0;
3301                 rs485conf->delay_rts_after_send = 0;
3302         }
3303
3304         /*
3305          * Clear full-duplex and enabled flags, set RTS polarity to active high
3306          * to get to a defined state with the following properties:
3307          */
3308         rs485conf->flags &= ~(SER_RS485_RX_DURING_TX | SER_RS485_ENABLED |
3309                               SER_RS485_TERMINATE_BUS |
3310                               SER_RS485_RTS_AFTER_SEND);
3311         rs485conf->flags |= SER_RS485_RTS_ON_SEND;
3312
3313         if (device_property_read_bool(dev, "rs485-rx-during-tx"))
3314                 rs485conf->flags |= SER_RS485_RX_DURING_TX;
3315
3316         if (device_property_read_bool(dev, "linux,rs485-enabled-at-boot-time"))
3317                 rs485conf->flags |= SER_RS485_ENABLED;
3318
3319         if (device_property_read_bool(dev, "rs485-rts-active-low")) {
3320                 rs485conf->flags &= ~SER_RS485_RTS_ON_SEND;
3321                 rs485conf->flags |= SER_RS485_RTS_AFTER_SEND;
3322         }
3323
3324         /*
3325          * Disabling termination by default is the safe choice:  Else if many
3326          * bus participants enable it, no communication is possible at all.
3327          * Works fine for short cables and users may enable for longer cables.
3328          */
3329         port->rs485_term_gpio = devm_gpiod_get_optional(dev, "rs485-term",
3330                                                         GPIOD_OUT_LOW);
3331         if (IS_ERR(port->rs485_term_gpio)) {
3332                 ret = PTR_ERR(port->rs485_term_gpio);
3333                 port->rs485_term_gpio = NULL;
3334                 return dev_err_probe(dev, ret, "Cannot get rs485-term-gpios\n");
3335         }
3336
3337         return 0;
3338 }
3339 EXPORT_SYMBOL_GPL(uart_get_rs485_mode);
3340
3341 MODULE_DESCRIPTION("Serial driver core");
3342 MODULE_LICENSE("GPL");