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