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