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