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