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