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