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