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