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