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