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