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