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