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