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