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