xref: /openbmc/linux/drivers/tty/serial/sh-sci.c (revision fa0dadde)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * SuperH on-chip serial module support.  (SCI with no FIFO / with FIFO)
4  *
5  *  Copyright (C) 2002 - 2011  Paul Mundt
6  *  Copyright (C) 2015 Glider bvba
7  *  Modified to support SH7720 SCIF. Markus Brunner, Mark Jonas (Jul 2007).
8  *
9  * based off of the old drivers/char/sh-sci.c by:
10  *
11  *   Copyright (C) 1999, 2000  Niibe Yutaka
12  *   Copyright (C) 2000  Sugioka Toshinobu
13  *   Modified to support multiple serial ports. Stuart Menefy (May 2000).
14  *   Modified to support SecureEdge. David McCullough (2002)
15  *   Modified to support SH7300 SCIF. Takashi Kusuda (Jun 2003).
16  *   Removed SH7300 support (Jul 2007).
17  */
18 #undef DEBUG
19 
20 #include <linux/clk.h>
21 #include <linux/console.h>
22 #include <linux/ctype.h>
23 #include <linux/cpufreq.h>
24 #include <linux/delay.h>
25 #include <linux/dmaengine.h>
26 #include <linux/dma-mapping.h>
27 #include <linux/err.h>
28 #include <linux/errno.h>
29 #include <linux/init.h>
30 #include <linux/interrupt.h>
31 #include <linux/ioport.h>
32 #include <linux/ktime.h>
33 #include <linux/major.h>
34 #include <linux/minmax.h>
35 #include <linux/module.h>
36 #include <linux/mm.h>
37 #include <linux/of.h>
38 #include <linux/of_device.h>
39 #include <linux/platform_device.h>
40 #include <linux/pm_runtime.h>
41 #include <linux/reset.h>
42 #include <linux/scatterlist.h>
43 #include <linux/serial.h>
44 #include <linux/serial_sci.h>
45 #include <linux/sh_dma.h>
46 #include <linux/slab.h>
47 #include <linux/string.h>
48 #include <linux/sysrq.h>
49 #include <linux/timer.h>
50 #include <linux/tty.h>
51 #include <linux/tty_flip.h>
52 
53 #ifdef CONFIG_SUPERH
54 #include <asm/sh_bios.h>
55 #include <asm/platform_early.h>
56 #endif
57 
58 #include "serial_mctrl_gpio.h"
59 #include "sh-sci.h"
60 
61 /* Offsets into the sci_port->irqs array */
62 enum {
63 	SCIx_ERI_IRQ,
64 	SCIx_RXI_IRQ,
65 	SCIx_TXI_IRQ,
66 	SCIx_BRI_IRQ,
67 	SCIx_DRI_IRQ,
68 	SCIx_TEI_IRQ,
69 	SCIx_NR_IRQS,
70 
71 	SCIx_MUX_IRQ = SCIx_NR_IRQS,	/* special case */
72 };
73 
74 #define SCIx_IRQ_IS_MUXED(port)			\
75 	((port)->irqs[SCIx_ERI_IRQ] ==	\
76 	 (port)->irqs[SCIx_RXI_IRQ]) ||	\
77 	((port)->irqs[SCIx_ERI_IRQ] &&	\
78 	 ((port)->irqs[SCIx_RXI_IRQ] < 0))
79 
80 enum SCI_CLKS {
81 	SCI_FCK,		/* Functional Clock */
82 	SCI_SCK,		/* Optional External Clock */
83 	SCI_BRG_INT,		/* Optional BRG Internal Clock Source */
84 	SCI_SCIF_CLK,		/* Optional BRG External Clock Source */
85 	SCI_NUM_CLKS
86 };
87 
88 /* Bit x set means sampling rate x + 1 is supported */
89 #define SCI_SR(x)		BIT((x) - 1)
90 #define SCI_SR_RANGE(x, y)	GENMASK((y) - 1, (x) - 1)
91 
92 #define SCI_SR_SCIFAB		SCI_SR(5) | SCI_SR(7) | SCI_SR(11) | \
93 				SCI_SR(13) | SCI_SR(16) | SCI_SR(17) | \
94 				SCI_SR(19) | SCI_SR(27)
95 
96 #define min_sr(_port)		ffs((_port)->sampling_rate_mask)
97 #define max_sr(_port)		fls((_port)->sampling_rate_mask)
98 
99 /* Iterate over all supported sampling rates, from high to low */
100 #define for_each_sr(_sr, _port)						\
101 	for ((_sr) = max_sr(_port); (_sr) >= min_sr(_port); (_sr)--)	\
102 		if ((_port)->sampling_rate_mask & SCI_SR((_sr)))
103 
104 struct plat_sci_reg {
105 	u8 offset, size;
106 };
107 
108 struct sci_port_params {
109 	const struct plat_sci_reg regs[SCIx_NR_REGS];
110 	unsigned int fifosize;
111 	unsigned int overrun_reg;
112 	unsigned int overrun_mask;
113 	unsigned int sampling_rate_mask;
114 	unsigned int error_mask;
115 	unsigned int error_clear;
116 };
117 
118 struct sci_port {
119 	struct uart_port	port;
120 
121 	/* Platform configuration */
122 	const struct sci_port_params *params;
123 	const struct plat_sci_port *cfg;
124 	unsigned int		sampling_rate_mask;
125 	resource_size_t		reg_size;
126 	struct mctrl_gpios	*gpios;
127 
128 	/* Clocks */
129 	struct clk		*clks[SCI_NUM_CLKS];
130 	unsigned long		clk_rates[SCI_NUM_CLKS];
131 
132 	int			irqs[SCIx_NR_IRQS];
133 	char			*irqstr[SCIx_NR_IRQS];
134 
135 	struct dma_chan			*chan_tx;
136 	struct dma_chan			*chan_rx;
137 
138 #ifdef CONFIG_SERIAL_SH_SCI_DMA
139 	struct dma_chan			*chan_tx_saved;
140 	struct dma_chan			*chan_rx_saved;
141 	dma_cookie_t			cookie_tx;
142 	dma_cookie_t			cookie_rx[2];
143 	dma_cookie_t			active_rx;
144 	dma_addr_t			tx_dma_addr;
145 	unsigned int			tx_dma_len;
146 	struct scatterlist		sg_rx[2];
147 	void				*rx_buf[2];
148 	size_t				buf_len_rx;
149 	struct work_struct		work_tx;
150 	struct hrtimer			rx_timer;
151 	unsigned int			rx_timeout;	/* microseconds */
152 #endif
153 	unsigned int			rx_frame;
154 	int				rx_trigger;
155 	struct timer_list		rx_fifo_timer;
156 	int				rx_fifo_timeout;
157 	u16				hscif_tot;
158 
159 	bool has_rtscts;
160 	bool autorts;
161 };
162 
163 #define SCI_NPORTS CONFIG_SERIAL_SH_SCI_NR_UARTS
164 
165 static struct sci_port sci_ports[SCI_NPORTS];
166 static unsigned long sci_ports_in_use;
167 static struct uart_driver sci_uart_driver;
168 
169 static inline struct sci_port *
170 to_sci_port(struct uart_port *uart)
171 {
172 	return container_of(uart, struct sci_port, port);
173 }
174 
175 static const struct sci_port_params sci_port_params[SCIx_NR_REGTYPES] = {
176 	/*
177 	 * Common SCI definitions, dependent on the port's regshift
178 	 * value.
179 	 */
180 	[SCIx_SCI_REGTYPE] = {
181 		.regs = {
182 			[SCSMR]		= { 0x00,  8 },
183 			[SCBRR]		= { 0x01,  8 },
184 			[SCSCR]		= { 0x02,  8 },
185 			[SCxTDR]	= { 0x03,  8 },
186 			[SCxSR]		= { 0x04,  8 },
187 			[SCxRDR]	= { 0x05,  8 },
188 		},
189 		.fifosize = 1,
190 		.overrun_reg = SCxSR,
191 		.overrun_mask = SCI_ORER,
192 		.sampling_rate_mask = SCI_SR(32),
193 		.error_mask = SCI_DEFAULT_ERROR_MASK | SCI_ORER,
194 		.error_clear = SCI_ERROR_CLEAR & ~SCI_ORER,
195 	},
196 
197 	/*
198 	 * Common definitions for legacy IrDA ports.
199 	 */
200 	[SCIx_IRDA_REGTYPE] = {
201 		.regs = {
202 			[SCSMR]		= { 0x00,  8 },
203 			[SCBRR]		= { 0x02,  8 },
204 			[SCSCR]		= { 0x04,  8 },
205 			[SCxTDR]	= { 0x06,  8 },
206 			[SCxSR]		= { 0x08, 16 },
207 			[SCxRDR]	= { 0x0a,  8 },
208 			[SCFCR]		= { 0x0c,  8 },
209 			[SCFDR]		= { 0x0e, 16 },
210 		},
211 		.fifosize = 1,
212 		.overrun_reg = SCxSR,
213 		.overrun_mask = SCI_ORER,
214 		.sampling_rate_mask = SCI_SR(32),
215 		.error_mask = SCI_DEFAULT_ERROR_MASK | SCI_ORER,
216 		.error_clear = SCI_ERROR_CLEAR & ~SCI_ORER,
217 	},
218 
219 	/*
220 	 * Common SCIFA definitions.
221 	 */
222 	[SCIx_SCIFA_REGTYPE] = {
223 		.regs = {
224 			[SCSMR]		= { 0x00, 16 },
225 			[SCBRR]		= { 0x04,  8 },
226 			[SCSCR]		= { 0x08, 16 },
227 			[SCxTDR]	= { 0x20,  8 },
228 			[SCxSR]		= { 0x14, 16 },
229 			[SCxRDR]	= { 0x24,  8 },
230 			[SCFCR]		= { 0x18, 16 },
231 			[SCFDR]		= { 0x1c, 16 },
232 			[SCPCR]		= { 0x30, 16 },
233 			[SCPDR]		= { 0x34, 16 },
234 		},
235 		.fifosize = 64,
236 		.overrun_reg = SCxSR,
237 		.overrun_mask = SCIFA_ORER,
238 		.sampling_rate_mask = SCI_SR_SCIFAB,
239 		.error_mask = SCIF_DEFAULT_ERROR_MASK | SCIFA_ORER,
240 		.error_clear = SCIF_ERROR_CLEAR & ~SCIFA_ORER,
241 	},
242 
243 	/*
244 	 * Common SCIFB definitions.
245 	 */
246 	[SCIx_SCIFB_REGTYPE] = {
247 		.regs = {
248 			[SCSMR]		= { 0x00, 16 },
249 			[SCBRR]		= { 0x04,  8 },
250 			[SCSCR]		= { 0x08, 16 },
251 			[SCxTDR]	= { 0x40,  8 },
252 			[SCxSR]		= { 0x14, 16 },
253 			[SCxRDR]	= { 0x60,  8 },
254 			[SCFCR]		= { 0x18, 16 },
255 			[SCTFDR]	= { 0x38, 16 },
256 			[SCRFDR]	= { 0x3c, 16 },
257 			[SCPCR]		= { 0x30, 16 },
258 			[SCPDR]		= { 0x34, 16 },
259 		},
260 		.fifosize = 256,
261 		.overrun_reg = SCxSR,
262 		.overrun_mask = SCIFA_ORER,
263 		.sampling_rate_mask = SCI_SR_SCIFAB,
264 		.error_mask = SCIF_DEFAULT_ERROR_MASK | SCIFA_ORER,
265 		.error_clear = SCIF_ERROR_CLEAR & ~SCIFA_ORER,
266 	},
267 
268 	/*
269 	 * Common SH-2(A) SCIF definitions for ports with FIFO data
270 	 * count registers.
271 	 */
272 	[SCIx_SH2_SCIF_FIFODATA_REGTYPE] = {
273 		.regs = {
274 			[SCSMR]		= { 0x00, 16 },
275 			[SCBRR]		= { 0x04,  8 },
276 			[SCSCR]		= { 0x08, 16 },
277 			[SCxTDR]	= { 0x0c,  8 },
278 			[SCxSR]		= { 0x10, 16 },
279 			[SCxRDR]	= { 0x14,  8 },
280 			[SCFCR]		= { 0x18, 16 },
281 			[SCFDR]		= { 0x1c, 16 },
282 			[SCSPTR]	= { 0x20, 16 },
283 			[SCLSR]		= { 0x24, 16 },
284 		},
285 		.fifosize = 16,
286 		.overrun_reg = SCLSR,
287 		.overrun_mask = SCLSR_ORER,
288 		.sampling_rate_mask = SCI_SR(32),
289 		.error_mask = SCIF_DEFAULT_ERROR_MASK,
290 		.error_clear = SCIF_ERROR_CLEAR,
291 	},
292 
293 	/*
294 	 * The "SCIFA" that is in RZ/A2, RZ/G2L and RZ/T.
295 	 * It looks like a normal SCIF with FIFO data, but with a
296 	 * compressed address space. Also, the break out of interrupts
297 	 * are different: ERI/BRI, RXI, TXI, TEI, DRI.
298 	 */
299 	[SCIx_RZ_SCIFA_REGTYPE] = {
300 		.regs = {
301 			[SCSMR]		= { 0x00, 16 },
302 			[SCBRR]		= { 0x02,  8 },
303 			[SCSCR]		= { 0x04, 16 },
304 			[SCxTDR]	= { 0x06,  8 },
305 			[SCxSR]		= { 0x08, 16 },
306 			[SCxRDR]	= { 0x0A,  8 },
307 			[SCFCR]		= { 0x0C, 16 },
308 			[SCFDR]		= { 0x0E, 16 },
309 			[SCSPTR]	= { 0x10, 16 },
310 			[SCLSR]		= { 0x12, 16 },
311 			[SEMR]		= { 0x14, 8 },
312 		},
313 		.fifosize = 16,
314 		.overrun_reg = SCLSR,
315 		.overrun_mask = SCLSR_ORER,
316 		.sampling_rate_mask = SCI_SR(32),
317 		.error_mask = SCIF_DEFAULT_ERROR_MASK,
318 		.error_clear = SCIF_ERROR_CLEAR,
319 	},
320 
321 	/*
322 	 * Common SH-3 SCIF definitions.
323 	 */
324 	[SCIx_SH3_SCIF_REGTYPE] = {
325 		.regs = {
326 			[SCSMR]		= { 0x00,  8 },
327 			[SCBRR]		= { 0x02,  8 },
328 			[SCSCR]		= { 0x04,  8 },
329 			[SCxTDR]	= { 0x06,  8 },
330 			[SCxSR]		= { 0x08, 16 },
331 			[SCxRDR]	= { 0x0a,  8 },
332 			[SCFCR]		= { 0x0c,  8 },
333 			[SCFDR]		= { 0x0e, 16 },
334 		},
335 		.fifosize = 16,
336 		.overrun_reg = SCLSR,
337 		.overrun_mask = SCLSR_ORER,
338 		.sampling_rate_mask = SCI_SR(32),
339 		.error_mask = SCIF_DEFAULT_ERROR_MASK,
340 		.error_clear = SCIF_ERROR_CLEAR,
341 	},
342 
343 	/*
344 	 * Common SH-4(A) SCIF(B) definitions.
345 	 */
346 	[SCIx_SH4_SCIF_REGTYPE] = {
347 		.regs = {
348 			[SCSMR]		= { 0x00, 16 },
349 			[SCBRR]		= { 0x04,  8 },
350 			[SCSCR]		= { 0x08, 16 },
351 			[SCxTDR]	= { 0x0c,  8 },
352 			[SCxSR]		= { 0x10, 16 },
353 			[SCxRDR]	= { 0x14,  8 },
354 			[SCFCR]		= { 0x18, 16 },
355 			[SCFDR]		= { 0x1c, 16 },
356 			[SCSPTR]	= { 0x20, 16 },
357 			[SCLSR]		= { 0x24, 16 },
358 		},
359 		.fifosize = 16,
360 		.overrun_reg = SCLSR,
361 		.overrun_mask = SCLSR_ORER,
362 		.sampling_rate_mask = SCI_SR(32),
363 		.error_mask = SCIF_DEFAULT_ERROR_MASK,
364 		.error_clear = SCIF_ERROR_CLEAR,
365 	},
366 
367 	/*
368 	 * Common SCIF definitions for ports with a Baud Rate Generator for
369 	 * External Clock (BRG).
370 	 */
371 	[SCIx_SH4_SCIF_BRG_REGTYPE] = {
372 		.regs = {
373 			[SCSMR]		= { 0x00, 16 },
374 			[SCBRR]		= { 0x04,  8 },
375 			[SCSCR]		= { 0x08, 16 },
376 			[SCxTDR]	= { 0x0c,  8 },
377 			[SCxSR]		= { 0x10, 16 },
378 			[SCxRDR]	= { 0x14,  8 },
379 			[SCFCR]		= { 0x18, 16 },
380 			[SCFDR]		= { 0x1c, 16 },
381 			[SCSPTR]	= { 0x20, 16 },
382 			[SCLSR]		= { 0x24, 16 },
383 			[SCDL]		= { 0x30, 16 },
384 			[SCCKS]		= { 0x34, 16 },
385 		},
386 		.fifosize = 16,
387 		.overrun_reg = SCLSR,
388 		.overrun_mask = SCLSR_ORER,
389 		.sampling_rate_mask = SCI_SR(32),
390 		.error_mask = SCIF_DEFAULT_ERROR_MASK,
391 		.error_clear = SCIF_ERROR_CLEAR,
392 	},
393 
394 	/*
395 	 * Common HSCIF definitions.
396 	 */
397 	[SCIx_HSCIF_REGTYPE] = {
398 		.regs = {
399 			[SCSMR]		= { 0x00, 16 },
400 			[SCBRR]		= { 0x04,  8 },
401 			[SCSCR]		= { 0x08, 16 },
402 			[SCxTDR]	= { 0x0c,  8 },
403 			[SCxSR]		= { 0x10, 16 },
404 			[SCxRDR]	= { 0x14,  8 },
405 			[SCFCR]		= { 0x18, 16 },
406 			[SCFDR]		= { 0x1c, 16 },
407 			[SCSPTR]	= { 0x20, 16 },
408 			[SCLSR]		= { 0x24, 16 },
409 			[HSSRR]		= { 0x40, 16 },
410 			[SCDL]		= { 0x30, 16 },
411 			[SCCKS]		= { 0x34, 16 },
412 			[HSRTRGR]	= { 0x54, 16 },
413 			[HSTTRGR]	= { 0x58, 16 },
414 		},
415 		.fifosize = 128,
416 		.overrun_reg = SCLSR,
417 		.overrun_mask = SCLSR_ORER,
418 		.sampling_rate_mask = SCI_SR_RANGE(8, 32),
419 		.error_mask = SCIF_DEFAULT_ERROR_MASK,
420 		.error_clear = SCIF_ERROR_CLEAR,
421 	},
422 
423 	/*
424 	 * Common SH-4(A) SCIF(B) definitions for ports without an SCSPTR
425 	 * register.
426 	 */
427 	[SCIx_SH4_SCIF_NO_SCSPTR_REGTYPE] = {
428 		.regs = {
429 			[SCSMR]		= { 0x00, 16 },
430 			[SCBRR]		= { 0x04,  8 },
431 			[SCSCR]		= { 0x08, 16 },
432 			[SCxTDR]	= { 0x0c,  8 },
433 			[SCxSR]		= { 0x10, 16 },
434 			[SCxRDR]	= { 0x14,  8 },
435 			[SCFCR]		= { 0x18, 16 },
436 			[SCFDR]		= { 0x1c, 16 },
437 			[SCLSR]		= { 0x24, 16 },
438 		},
439 		.fifosize = 16,
440 		.overrun_reg = SCLSR,
441 		.overrun_mask = SCLSR_ORER,
442 		.sampling_rate_mask = SCI_SR(32),
443 		.error_mask = SCIF_DEFAULT_ERROR_MASK,
444 		.error_clear = SCIF_ERROR_CLEAR,
445 	},
446 
447 	/*
448 	 * Common SH-4(A) SCIF(B) definitions for ports with FIFO data
449 	 * count registers.
450 	 */
451 	[SCIx_SH4_SCIF_FIFODATA_REGTYPE] = {
452 		.regs = {
453 			[SCSMR]		= { 0x00, 16 },
454 			[SCBRR]		= { 0x04,  8 },
455 			[SCSCR]		= { 0x08, 16 },
456 			[SCxTDR]	= { 0x0c,  8 },
457 			[SCxSR]		= { 0x10, 16 },
458 			[SCxRDR]	= { 0x14,  8 },
459 			[SCFCR]		= { 0x18, 16 },
460 			[SCFDR]		= { 0x1c, 16 },
461 			[SCTFDR]	= { 0x1c, 16 },	/* aliased to SCFDR */
462 			[SCRFDR]	= { 0x20, 16 },
463 			[SCSPTR]	= { 0x24, 16 },
464 			[SCLSR]		= { 0x28, 16 },
465 		},
466 		.fifosize = 16,
467 		.overrun_reg = SCLSR,
468 		.overrun_mask = SCLSR_ORER,
469 		.sampling_rate_mask = SCI_SR(32),
470 		.error_mask = SCIF_DEFAULT_ERROR_MASK,
471 		.error_clear = SCIF_ERROR_CLEAR,
472 	},
473 
474 	/*
475 	 * SH7705-style SCIF(B) ports, lacking both SCSPTR and SCLSR
476 	 * registers.
477 	 */
478 	[SCIx_SH7705_SCIF_REGTYPE] = {
479 		.regs = {
480 			[SCSMR]		= { 0x00, 16 },
481 			[SCBRR]		= { 0x04,  8 },
482 			[SCSCR]		= { 0x08, 16 },
483 			[SCxTDR]	= { 0x20,  8 },
484 			[SCxSR]		= { 0x14, 16 },
485 			[SCxRDR]	= { 0x24,  8 },
486 			[SCFCR]		= { 0x18, 16 },
487 			[SCFDR]		= { 0x1c, 16 },
488 		},
489 		.fifosize = 64,
490 		.overrun_reg = SCxSR,
491 		.overrun_mask = SCIFA_ORER,
492 		.sampling_rate_mask = SCI_SR(16),
493 		.error_mask = SCIF_DEFAULT_ERROR_MASK | SCIFA_ORER,
494 		.error_clear = SCIF_ERROR_CLEAR & ~SCIFA_ORER,
495 	},
496 };
497 
498 #define sci_getreg(up, offset)		(&to_sci_port(up)->params->regs[offset])
499 
500 /*
501  * The "offset" here is rather misleading, in that it refers to an enum
502  * value relative to the port mapping rather than the fixed offset
503  * itself, which needs to be manually retrieved from the platform's
504  * register map for the given port.
505  */
506 static unsigned int sci_serial_in(struct uart_port *p, int offset)
507 {
508 	const struct plat_sci_reg *reg = sci_getreg(p, offset);
509 
510 	if (reg->size == 8)
511 		return ioread8(p->membase + (reg->offset << p->regshift));
512 	else if (reg->size == 16)
513 		return ioread16(p->membase + (reg->offset << p->regshift));
514 	else
515 		WARN(1, "Invalid register access\n");
516 
517 	return 0;
518 }
519 
520 static void sci_serial_out(struct uart_port *p, int offset, int value)
521 {
522 	const struct plat_sci_reg *reg = sci_getreg(p, offset);
523 
524 	if (reg->size == 8)
525 		iowrite8(value, p->membase + (reg->offset << p->regshift));
526 	else if (reg->size == 16)
527 		iowrite16(value, p->membase + (reg->offset << p->regshift));
528 	else
529 		WARN(1, "Invalid register access\n");
530 }
531 
532 static void sci_port_enable(struct sci_port *sci_port)
533 {
534 	unsigned int i;
535 
536 	if (!sci_port->port.dev)
537 		return;
538 
539 	pm_runtime_get_sync(sci_port->port.dev);
540 
541 	for (i = 0; i < SCI_NUM_CLKS; i++) {
542 		clk_prepare_enable(sci_port->clks[i]);
543 		sci_port->clk_rates[i] = clk_get_rate(sci_port->clks[i]);
544 	}
545 	sci_port->port.uartclk = sci_port->clk_rates[SCI_FCK];
546 }
547 
548 static void sci_port_disable(struct sci_port *sci_port)
549 {
550 	unsigned int i;
551 
552 	if (!sci_port->port.dev)
553 		return;
554 
555 	for (i = SCI_NUM_CLKS; i-- > 0; )
556 		clk_disable_unprepare(sci_port->clks[i]);
557 
558 	pm_runtime_put_sync(sci_port->port.dev);
559 }
560 
561 static inline unsigned long port_rx_irq_mask(struct uart_port *port)
562 {
563 	/*
564 	 * Not all ports (such as SCIFA) will support REIE. Rather than
565 	 * special-casing the port type, we check the port initialization
566 	 * IRQ enable mask to see whether the IRQ is desired at all. If
567 	 * it's unset, it's logically inferred that there's no point in
568 	 * testing for it.
569 	 */
570 	return SCSCR_RIE | (to_sci_port(port)->cfg->scscr & SCSCR_REIE);
571 }
572 
573 static void sci_start_tx(struct uart_port *port)
574 {
575 	struct sci_port *s = to_sci_port(port);
576 	unsigned short ctrl;
577 
578 #ifdef CONFIG_SERIAL_SH_SCI_DMA
579 	if (port->type == PORT_SCIFA || port->type == PORT_SCIFB) {
580 		u16 new, scr = serial_port_in(port, SCSCR);
581 		if (s->chan_tx)
582 			new = scr | SCSCR_TDRQE;
583 		else
584 			new = scr & ~SCSCR_TDRQE;
585 		if (new != scr)
586 			serial_port_out(port, SCSCR, new);
587 	}
588 
589 	if (s->chan_tx && !uart_circ_empty(&s->port.state->xmit) &&
590 	    dma_submit_error(s->cookie_tx)) {
591 		if (s->cfg->regtype == SCIx_RZ_SCIFA_REGTYPE)
592 			/* Switch irq from SCIF to DMA */
593 			disable_irq(s->irqs[SCIx_TXI_IRQ]);
594 
595 		s->cookie_tx = 0;
596 		schedule_work(&s->work_tx);
597 	}
598 #endif
599 
600 	if (!s->chan_tx || s->cfg->regtype == SCIx_RZ_SCIFA_REGTYPE ||
601 	    port->type == PORT_SCIFA || port->type == PORT_SCIFB) {
602 		/* Set TIE (Transmit Interrupt Enable) bit in SCSCR */
603 		ctrl = serial_port_in(port, SCSCR);
604 
605 		/*
606 		 * For SCI, TE (transmit enable) must be set after setting TIE
607 		 * (transmit interrupt enable) or in the same instruction to start
608 		 * the transmit process.
609 		 */
610 		if (port->type == PORT_SCI)
611 			ctrl |= SCSCR_TE;
612 
613 		serial_port_out(port, SCSCR, ctrl | SCSCR_TIE);
614 	}
615 }
616 
617 static void sci_stop_tx(struct uart_port *port)
618 {
619 	unsigned short ctrl;
620 
621 	/* Clear TIE (Transmit Interrupt Enable) bit in SCSCR */
622 	ctrl = serial_port_in(port, SCSCR);
623 
624 	if (port->type == PORT_SCIFA || port->type == PORT_SCIFB)
625 		ctrl &= ~SCSCR_TDRQE;
626 
627 	ctrl &= ~SCSCR_TIE;
628 
629 	serial_port_out(port, SCSCR, ctrl);
630 
631 #ifdef CONFIG_SERIAL_SH_SCI_DMA
632 	if (to_sci_port(port)->chan_tx &&
633 	    !dma_submit_error(to_sci_port(port)->cookie_tx)) {
634 		dmaengine_terminate_async(to_sci_port(port)->chan_tx);
635 		to_sci_port(port)->cookie_tx = -EINVAL;
636 	}
637 #endif
638 }
639 
640 static void sci_start_rx(struct uart_port *port)
641 {
642 	unsigned short ctrl;
643 
644 	ctrl = serial_port_in(port, SCSCR) | port_rx_irq_mask(port);
645 
646 	if (port->type == PORT_SCIFA || port->type == PORT_SCIFB)
647 		ctrl &= ~SCSCR_RDRQE;
648 
649 	serial_port_out(port, SCSCR, ctrl);
650 }
651 
652 static void sci_stop_rx(struct uart_port *port)
653 {
654 	unsigned short ctrl;
655 
656 	ctrl = serial_port_in(port, SCSCR);
657 
658 	if (port->type == PORT_SCIFA || port->type == PORT_SCIFB)
659 		ctrl &= ~SCSCR_RDRQE;
660 
661 	ctrl &= ~port_rx_irq_mask(port);
662 
663 	serial_port_out(port, SCSCR, ctrl);
664 }
665 
666 static void sci_clear_SCxSR(struct uart_port *port, unsigned int mask)
667 {
668 	if (port->type == PORT_SCI) {
669 		/* Just store the mask */
670 		serial_port_out(port, SCxSR, mask);
671 	} else if (to_sci_port(port)->params->overrun_mask == SCIFA_ORER) {
672 		/* SCIFA/SCIFB and SCIF on SH7705/SH7720/SH7721 */
673 		/* Only clear the status bits we want to clear */
674 		serial_port_out(port, SCxSR,
675 				serial_port_in(port, SCxSR) & mask);
676 	} else {
677 		/* Store the mask, clear parity/framing errors */
678 		serial_port_out(port, SCxSR, mask & ~(SCIF_FERC | SCIF_PERC));
679 	}
680 }
681 
682 #if defined(CONFIG_CONSOLE_POLL) || defined(CONFIG_SERIAL_SH_SCI_CONSOLE) || \
683     defined(CONFIG_SERIAL_SH_SCI_EARLYCON)
684 
685 #ifdef CONFIG_CONSOLE_POLL
686 static int sci_poll_get_char(struct uart_port *port)
687 {
688 	unsigned short status;
689 	int c;
690 
691 	do {
692 		status = serial_port_in(port, SCxSR);
693 		if (status & SCxSR_ERRORS(port)) {
694 			sci_clear_SCxSR(port, SCxSR_ERROR_CLEAR(port));
695 			continue;
696 		}
697 		break;
698 	} while (1);
699 
700 	if (!(status & SCxSR_RDxF(port)))
701 		return NO_POLL_CHAR;
702 
703 	c = serial_port_in(port, SCxRDR);
704 
705 	/* Dummy read */
706 	serial_port_in(port, SCxSR);
707 	sci_clear_SCxSR(port, SCxSR_RDxF_CLEAR(port));
708 
709 	return c;
710 }
711 #endif
712 
713 static void sci_poll_put_char(struct uart_port *port, unsigned char c)
714 {
715 	unsigned short status;
716 
717 	do {
718 		status = serial_port_in(port, SCxSR);
719 	} while (!(status & SCxSR_TDxE(port)));
720 
721 	serial_port_out(port, SCxTDR, c);
722 	sci_clear_SCxSR(port, SCxSR_TDxE_CLEAR(port) & ~SCxSR_TEND(port));
723 }
724 #endif /* CONFIG_CONSOLE_POLL || CONFIG_SERIAL_SH_SCI_CONSOLE ||
725 	  CONFIG_SERIAL_SH_SCI_EARLYCON */
726 
727 static void sci_init_pins(struct uart_port *port, unsigned int cflag)
728 {
729 	struct sci_port *s = to_sci_port(port);
730 
731 	/*
732 	 * Use port-specific handler if provided.
733 	 */
734 	if (s->cfg->ops && s->cfg->ops->init_pins) {
735 		s->cfg->ops->init_pins(port, cflag);
736 		return;
737 	}
738 
739 	if (port->type == PORT_SCIFA || port->type == PORT_SCIFB) {
740 		u16 data = serial_port_in(port, SCPDR);
741 		u16 ctrl = serial_port_in(port, SCPCR);
742 
743 		/* Enable RXD and TXD pin functions */
744 		ctrl &= ~(SCPCR_RXDC | SCPCR_TXDC);
745 		if (to_sci_port(port)->has_rtscts) {
746 			/* RTS# is output, active low, unless autorts */
747 			if (!(port->mctrl & TIOCM_RTS)) {
748 				ctrl |= SCPCR_RTSC;
749 				data |= SCPDR_RTSD;
750 			} else if (!s->autorts) {
751 				ctrl |= SCPCR_RTSC;
752 				data &= ~SCPDR_RTSD;
753 			} else {
754 				/* Enable RTS# pin function */
755 				ctrl &= ~SCPCR_RTSC;
756 			}
757 			/* Enable CTS# pin function */
758 			ctrl &= ~SCPCR_CTSC;
759 		}
760 		serial_port_out(port, SCPDR, data);
761 		serial_port_out(port, SCPCR, ctrl);
762 	} else if (sci_getreg(port, SCSPTR)->size) {
763 		u16 status = serial_port_in(port, SCSPTR);
764 
765 		/* RTS# is always output; and active low, unless autorts */
766 		status |= SCSPTR_RTSIO;
767 		if (!(port->mctrl & TIOCM_RTS))
768 			status |= SCSPTR_RTSDT;
769 		else if (!s->autorts)
770 			status &= ~SCSPTR_RTSDT;
771 		/* CTS# and SCK are inputs */
772 		status &= ~(SCSPTR_CTSIO | SCSPTR_SCKIO);
773 		serial_port_out(port, SCSPTR, status);
774 	}
775 }
776 
777 static int sci_txfill(struct uart_port *port)
778 {
779 	struct sci_port *s = to_sci_port(port);
780 	unsigned int fifo_mask = (s->params->fifosize << 1) - 1;
781 	const struct plat_sci_reg *reg;
782 
783 	reg = sci_getreg(port, SCTFDR);
784 	if (reg->size)
785 		return serial_port_in(port, SCTFDR) & fifo_mask;
786 
787 	reg = sci_getreg(port, SCFDR);
788 	if (reg->size)
789 		return serial_port_in(port, SCFDR) >> 8;
790 
791 	return !(serial_port_in(port, SCxSR) & SCI_TDRE);
792 }
793 
794 static int sci_txroom(struct uart_port *port)
795 {
796 	return port->fifosize - sci_txfill(port);
797 }
798 
799 static int sci_rxfill(struct uart_port *port)
800 {
801 	struct sci_port *s = to_sci_port(port);
802 	unsigned int fifo_mask = (s->params->fifosize << 1) - 1;
803 	const struct plat_sci_reg *reg;
804 
805 	reg = sci_getreg(port, SCRFDR);
806 	if (reg->size)
807 		return serial_port_in(port, SCRFDR) & fifo_mask;
808 
809 	reg = sci_getreg(port, SCFDR);
810 	if (reg->size)
811 		return serial_port_in(port, SCFDR) & fifo_mask;
812 
813 	return (serial_port_in(port, SCxSR) & SCxSR_RDxF(port)) != 0;
814 }
815 
816 /* ********************************************************************** *
817  *                   the interrupt related routines                       *
818  * ********************************************************************** */
819 
820 static void sci_transmit_chars(struct uart_port *port)
821 {
822 	struct circ_buf *xmit = &port->state->xmit;
823 	unsigned int stopped = uart_tx_stopped(port);
824 	unsigned short status;
825 	unsigned short ctrl;
826 	int count;
827 
828 	status = serial_port_in(port, SCxSR);
829 	if (!(status & SCxSR_TDxE(port))) {
830 		ctrl = serial_port_in(port, SCSCR);
831 		if (uart_circ_empty(xmit))
832 			ctrl &= ~SCSCR_TIE;
833 		else
834 			ctrl |= SCSCR_TIE;
835 		serial_port_out(port, SCSCR, ctrl);
836 		return;
837 	}
838 
839 	count = sci_txroom(port);
840 
841 	do {
842 		unsigned char c;
843 
844 		if (port->x_char) {
845 			c = port->x_char;
846 			port->x_char = 0;
847 		} else if (!uart_circ_empty(xmit) && !stopped) {
848 			c = xmit->buf[xmit->tail];
849 			xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1);
850 		} else if (port->type == PORT_SCI && uart_circ_empty(xmit)) {
851 			ctrl = serial_port_in(port, SCSCR);
852 			ctrl &= ~SCSCR_TE;
853 			serial_port_out(port, SCSCR, ctrl);
854 			return;
855 		} else {
856 			break;
857 		}
858 
859 		serial_port_out(port, SCxTDR, c);
860 
861 		port->icount.tx++;
862 	} while (--count > 0);
863 
864 	sci_clear_SCxSR(port, SCxSR_TDxE_CLEAR(port));
865 
866 	if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
867 		uart_write_wakeup(port);
868 	if (uart_circ_empty(xmit)) {
869 		if (port->type == PORT_SCI) {
870 			ctrl = serial_port_in(port, SCSCR);
871 			ctrl &= ~SCSCR_TIE;
872 			ctrl |= SCSCR_TEIE;
873 			serial_port_out(port, SCSCR, ctrl);
874 		}
875 
876 		sci_stop_tx(port);
877 	}
878 }
879 
880 static void sci_receive_chars(struct uart_port *port)
881 {
882 	struct tty_port *tport = &port->state->port;
883 	int i, count, copied = 0;
884 	unsigned short status;
885 	unsigned char flag;
886 
887 	status = serial_port_in(port, SCxSR);
888 	if (!(status & SCxSR_RDxF(port)))
889 		return;
890 
891 	while (1) {
892 		/* Don't copy more bytes than there is room for in the buffer */
893 		count = tty_buffer_request_room(tport, sci_rxfill(port));
894 
895 		/* If for any reason we can't copy more data, we're done! */
896 		if (count == 0)
897 			break;
898 
899 		if (port->type == PORT_SCI) {
900 			char c = serial_port_in(port, SCxRDR);
901 			if (uart_handle_sysrq_char(port, c))
902 				count = 0;
903 			else
904 				tty_insert_flip_char(tport, c, TTY_NORMAL);
905 		} else {
906 			for (i = 0; i < count; i++) {
907 				char c;
908 
909 				if (port->type == PORT_SCIF ||
910 				    port->type == PORT_HSCIF) {
911 					status = serial_port_in(port, SCxSR);
912 					c = serial_port_in(port, SCxRDR);
913 				} else {
914 					c = serial_port_in(port, SCxRDR);
915 					status = serial_port_in(port, SCxSR);
916 				}
917 				if (uart_handle_sysrq_char(port, c)) {
918 					count--; i--;
919 					continue;
920 				}
921 
922 				/* Store data and status */
923 				if (status & SCxSR_FER(port)) {
924 					flag = TTY_FRAME;
925 					port->icount.frame++;
926 				} else if (status & SCxSR_PER(port)) {
927 					flag = TTY_PARITY;
928 					port->icount.parity++;
929 				} else
930 					flag = TTY_NORMAL;
931 
932 				tty_insert_flip_char(tport, c, flag);
933 			}
934 		}
935 
936 		serial_port_in(port, SCxSR); /* dummy read */
937 		sci_clear_SCxSR(port, SCxSR_RDxF_CLEAR(port));
938 
939 		copied += count;
940 		port->icount.rx += count;
941 	}
942 
943 	if (copied) {
944 		/* Tell the rest of the system the news. New characters! */
945 		tty_flip_buffer_push(tport);
946 	} else {
947 		/* TTY buffers full; read from RX reg to prevent lockup */
948 		serial_port_in(port, SCxRDR);
949 		serial_port_in(port, SCxSR); /* dummy read */
950 		sci_clear_SCxSR(port, SCxSR_RDxF_CLEAR(port));
951 	}
952 }
953 
954 static int sci_handle_errors(struct uart_port *port)
955 {
956 	int copied = 0;
957 	unsigned short status = serial_port_in(port, SCxSR);
958 	struct tty_port *tport = &port->state->port;
959 	struct sci_port *s = to_sci_port(port);
960 
961 	/* Handle overruns */
962 	if (status & s->params->overrun_mask) {
963 		port->icount.overrun++;
964 
965 		/* overrun error */
966 		if (tty_insert_flip_char(tport, 0, TTY_OVERRUN))
967 			copied++;
968 	}
969 
970 	if (status & SCxSR_FER(port)) {
971 		/* frame error */
972 		port->icount.frame++;
973 
974 		if (tty_insert_flip_char(tport, 0, TTY_FRAME))
975 			copied++;
976 	}
977 
978 	if (status & SCxSR_PER(port)) {
979 		/* parity error */
980 		port->icount.parity++;
981 
982 		if (tty_insert_flip_char(tport, 0, TTY_PARITY))
983 			copied++;
984 	}
985 
986 	if (copied)
987 		tty_flip_buffer_push(tport);
988 
989 	return copied;
990 }
991 
992 static int sci_handle_fifo_overrun(struct uart_port *port)
993 {
994 	struct tty_port *tport = &port->state->port;
995 	struct sci_port *s = to_sci_port(port);
996 	const struct plat_sci_reg *reg;
997 	int copied = 0;
998 	u16 status;
999 
1000 	reg = sci_getreg(port, s->params->overrun_reg);
1001 	if (!reg->size)
1002 		return 0;
1003 
1004 	status = serial_port_in(port, s->params->overrun_reg);
1005 	if (status & s->params->overrun_mask) {
1006 		status &= ~s->params->overrun_mask;
1007 		serial_port_out(port, s->params->overrun_reg, status);
1008 
1009 		port->icount.overrun++;
1010 
1011 		tty_insert_flip_char(tport, 0, TTY_OVERRUN);
1012 		tty_flip_buffer_push(tport);
1013 		copied++;
1014 	}
1015 
1016 	return copied;
1017 }
1018 
1019 static int sci_handle_breaks(struct uart_port *port)
1020 {
1021 	int copied = 0;
1022 	unsigned short status = serial_port_in(port, SCxSR);
1023 	struct tty_port *tport = &port->state->port;
1024 
1025 	if (uart_handle_break(port))
1026 		return 0;
1027 
1028 	if (status & SCxSR_BRK(port)) {
1029 		port->icount.brk++;
1030 
1031 		/* Notify of BREAK */
1032 		if (tty_insert_flip_char(tport, 0, TTY_BREAK))
1033 			copied++;
1034 	}
1035 
1036 	if (copied)
1037 		tty_flip_buffer_push(tport);
1038 
1039 	copied += sci_handle_fifo_overrun(port);
1040 
1041 	return copied;
1042 }
1043 
1044 static int scif_set_rtrg(struct uart_port *port, int rx_trig)
1045 {
1046 	unsigned int bits;
1047 
1048 	if (rx_trig >= port->fifosize)
1049 		rx_trig = port->fifosize - 1;
1050 	if (rx_trig < 1)
1051 		rx_trig = 1;
1052 
1053 	/* HSCIF can be set to an arbitrary level. */
1054 	if (sci_getreg(port, HSRTRGR)->size) {
1055 		serial_port_out(port, HSRTRGR, rx_trig);
1056 		return rx_trig;
1057 	}
1058 
1059 	switch (port->type) {
1060 	case PORT_SCIF:
1061 		if (rx_trig < 4) {
1062 			bits = 0;
1063 			rx_trig = 1;
1064 		} else if (rx_trig < 8) {
1065 			bits = SCFCR_RTRG0;
1066 			rx_trig = 4;
1067 		} else if (rx_trig < 14) {
1068 			bits = SCFCR_RTRG1;
1069 			rx_trig = 8;
1070 		} else {
1071 			bits = SCFCR_RTRG0 | SCFCR_RTRG1;
1072 			rx_trig = 14;
1073 		}
1074 		break;
1075 	case PORT_SCIFA:
1076 	case PORT_SCIFB:
1077 		if (rx_trig < 16) {
1078 			bits = 0;
1079 			rx_trig = 1;
1080 		} else if (rx_trig < 32) {
1081 			bits = SCFCR_RTRG0;
1082 			rx_trig = 16;
1083 		} else if (rx_trig < 48) {
1084 			bits = SCFCR_RTRG1;
1085 			rx_trig = 32;
1086 		} else {
1087 			bits = SCFCR_RTRG0 | SCFCR_RTRG1;
1088 			rx_trig = 48;
1089 		}
1090 		break;
1091 	default:
1092 		WARN(1, "unknown FIFO configuration");
1093 		return 1;
1094 	}
1095 
1096 	serial_port_out(port, SCFCR,
1097 		(serial_port_in(port, SCFCR) &
1098 		~(SCFCR_RTRG1 | SCFCR_RTRG0)) | bits);
1099 
1100 	return rx_trig;
1101 }
1102 
1103 static int scif_rtrg_enabled(struct uart_port *port)
1104 {
1105 	if (sci_getreg(port, HSRTRGR)->size)
1106 		return serial_port_in(port, HSRTRGR) != 0;
1107 	else
1108 		return (serial_port_in(port, SCFCR) &
1109 			(SCFCR_RTRG0 | SCFCR_RTRG1)) != 0;
1110 }
1111 
1112 static void rx_fifo_timer_fn(struct timer_list *t)
1113 {
1114 	struct sci_port *s = from_timer(s, t, rx_fifo_timer);
1115 	struct uart_port *port = &s->port;
1116 
1117 	dev_dbg(port->dev, "Rx timed out\n");
1118 	scif_set_rtrg(port, 1);
1119 }
1120 
1121 static ssize_t rx_fifo_trigger_show(struct device *dev,
1122 				    struct device_attribute *attr, char *buf)
1123 {
1124 	struct uart_port *port = dev_get_drvdata(dev);
1125 	struct sci_port *sci = to_sci_port(port);
1126 
1127 	return sprintf(buf, "%d\n", sci->rx_trigger);
1128 }
1129 
1130 static ssize_t rx_fifo_trigger_store(struct device *dev,
1131 				     struct device_attribute *attr,
1132 				     const char *buf, size_t count)
1133 {
1134 	struct uart_port *port = dev_get_drvdata(dev);
1135 	struct sci_port *sci = to_sci_port(port);
1136 	int ret;
1137 	long r;
1138 
1139 	ret = kstrtol(buf, 0, &r);
1140 	if (ret)
1141 		return ret;
1142 
1143 	sci->rx_trigger = scif_set_rtrg(port, r);
1144 	if (port->type == PORT_SCIFA || port->type == PORT_SCIFB)
1145 		scif_set_rtrg(port, 1);
1146 
1147 	return count;
1148 }
1149 
1150 static DEVICE_ATTR_RW(rx_fifo_trigger);
1151 
1152 static ssize_t rx_fifo_timeout_show(struct device *dev,
1153 			       struct device_attribute *attr,
1154 			       char *buf)
1155 {
1156 	struct uart_port *port = dev_get_drvdata(dev);
1157 	struct sci_port *sci = to_sci_port(port);
1158 	int v;
1159 
1160 	if (port->type == PORT_HSCIF)
1161 		v = sci->hscif_tot >> HSSCR_TOT_SHIFT;
1162 	else
1163 		v = sci->rx_fifo_timeout;
1164 
1165 	return sprintf(buf, "%d\n", v);
1166 }
1167 
1168 static ssize_t rx_fifo_timeout_store(struct device *dev,
1169 				struct device_attribute *attr,
1170 				const char *buf,
1171 				size_t count)
1172 {
1173 	struct uart_port *port = dev_get_drvdata(dev);
1174 	struct sci_port *sci = to_sci_port(port);
1175 	int ret;
1176 	long r;
1177 
1178 	ret = kstrtol(buf, 0, &r);
1179 	if (ret)
1180 		return ret;
1181 
1182 	if (port->type == PORT_HSCIF) {
1183 		if (r < 0 || r > 3)
1184 			return -EINVAL;
1185 		sci->hscif_tot = r << HSSCR_TOT_SHIFT;
1186 	} else {
1187 		sci->rx_fifo_timeout = r;
1188 		scif_set_rtrg(port, 1);
1189 		if (r > 0)
1190 			timer_setup(&sci->rx_fifo_timer, rx_fifo_timer_fn, 0);
1191 	}
1192 
1193 	return count;
1194 }
1195 
1196 static DEVICE_ATTR_RW(rx_fifo_timeout);
1197 
1198 
1199 #ifdef CONFIG_SERIAL_SH_SCI_DMA
1200 static void sci_dma_tx_complete(void *arg)
1201 {
1202 	struct sci_port *s = arg;
1203 	struct uart_port *port = &s->port;
1204 	struct circ_buf *xmit = &port->state->xmit;
1205 	unsigned long flags;
1206 
1207 	dev_dbg(port->dev, "%s(%d)\n", __func__, port->line);
1208 
1209 	spin_lock_irqsave(&port->lock, flags);
1210 
1211 	uart_xmit_advance(port, s->tx_dma_len);
1212 
1213 	if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
1214 		uart_write_wakeup(port);
1215 
1216 	if (!uart_circ_empty(xmit)) {
1217 		s->cookie_tx = 0;
1218 		schedule_work(&s->work_tx);
1219 	} else {
1220 		s->cookie_tx = -EINVAL;
1221 		if (port->type == PORT_SCIFA || port->type == PORT_SCIFB ||
1222 		    s->cfg->regtype == SCIx_RZ_SCIFA_REGTYPE) {
1223 			u16 ctrl = serial_port_in(port, SCSCR);
1224 			serial_port_out(port, SCSCR, ctrl & ~SCSCR_TIE);
1225 			if (s->cfg->regtype == SCIx_RZ_SCIFA_REGTYPE) {
1226 				/* Switch irq from DMA to SCIF */
1227 				dmaengine_pause(s->chan_tx_saved);
1228 				enable_irq(s->irqs[SCIx_TXI_IRQ]);
1229 			}
1230 		}
1231 	}
1232 
1233 	spin_unlock_irqrestore(&port->lock, flags);
1234 }
1235 
1236 /* Locking: called with port lock held */
1237 static int sci_dma_rx_push(struct sci_port *s, void *buf, size_t count)
1238 {
1239 	struct uart_port *port = &s->port;
1240 	struct tty_port *tport = &port->state->port;
1241 	int copied;
1242 
1243 	copied = tty_insert_flip_string(tport, buf, count);
1244 	if (copied < count)
1245 		port->icount.buf_overrun++;
1246 
1247 	port->icount.rx += copied;
1248 
1249 	return copied;
1250 }
1251 
1252 static int sci_dma_rx_find_active(struct sci_port *s)
1253 {
1254 	unsigned int i;
1255 
1256 	for (i = 0; i < ARRAY_SIZE(s->cookie_rx); i++)
1257 		if (s->active_rx == s->cookie_rx[i])
1258 			return i;
1259 
1260 	return -1;
1261 }
1262 
1263 static void sci_dma_rx_chan_invalidate(struct sci_port *s)
1264 {
1265 	unsigned int i;
1266 
1267 	s->chan_rx = NULL;
1268 	for (i = 0; i < ARRAY_SIZE(s->cookie_rx); i++)
1269 		s->cookie_rx[i] = -EINVAL;
1270 	s->active_rx = 0;
1271 }
1272 
1273 static void sci_dma_rx_release(struct sci_port *s)
1274 {
1275 	struct dma_chan *chan = s->chan_rx_saved;
1276 
1277 	s->chan_rx_saved = NULL;
1278 	sci_dma_rx_chan_invalidate(s);
1279 	dmaengine_terminate_sync(chan);
1280 	dma_free_coherent(chan->device->dev, s->buf_len_rx * 2, s->rx_buf[0],
1281 			  sg_dma_address(&s->sg_rx[0]));
1282 	dma_release_channel(chan);
1283 }
1284 
1285 static void start_hrtimer_us(struct hrtimer *hrt, unsigned long usec)
1286 {
1287 	long sec = usec / 1000000;
1288 	long nsec = (usec % 1000000) * 1000;
1289 	ktime_t t = ktime_set(sec, nsec);
1290 
1291 	hrtimer_start(hrt, t, HRTIMER_MODE_REL);
1292 }
1293 
1294 static void sci_dma_rx_reenable_irq(struct sci_port *s)
1295 {
1296 	struct uart_port *port = &s->port;
1297 	u16 scr;
1298 
1299 	/* Direct new serial port interrupts back to CPU */
1300 	scr = serial_port_in(port, SCSCR);
1301 	if (port->type == PORT_SCIFA || port->type == PORT_SCIFB ||
1302 	    s->cfg->regtype == SCIx_RZ_SCIFA_REGTYPE) {
1303 		enable_irq(s->irqs[SCIx_RXI_IRQ]);
1304 		if (s->cfg->regtype == SCIx_RZ_SCIFA_REGTYPE)
1305 			scif_set_rtrg(port, s->rx_trigger);
1306 		else
1307 			scr &= ~SCSCR_RDRQE;
1308 	}
1309 	serial_port_out(port, SCSCR, scr | SCSCR_RIE);
1310 }
1311 
1312 static void sci_dma_rx_complete(void *arg)
1313 {
1314 	struct sci_port *s = arg;
1315 	struct dma_chan *chan = s->chan_rx;
1316 	struct uart_port *port = &s->port;
1317 	struct dma_async_tx_descriptor *desc;
1318 	unsigned long flags;
1319 	int active, count = 0;
1320 
1321 	dev_dbg(port->dev, "%s(%d) active cookie %d\n", __func__, port->line,
1322 		s->active_rx);
1323 
1324 	spin_lock_irqsave(&port->lock, flags);
1325 
1326 	active = sci_dma_rx_find_active(s);
1327 	if (active >= 0)
1328 		count = sci_dma_rx_push(s, s->rx_buf[active], s->buf_len_rx);
1329 
1330 	start_hrtimer_us(&s->rx_timer, s->rx_timeout);
1331 
1332 	if (count)
1333 		tty_flip_buffer_push(&port->state->port);
1334 
1335 	desc = dmaengine_prep_slave_sg(s->chan_rx, &s->sg_rx[active], 1,
1336 				       DMA_DEV_TO_MEM,
1337 				       DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
1338 	if (!desc)
1339 		goto fail;
1340 
1341 	desc->callback = sci_dma_rx_complete;
1342 	desc->callback_param = s;
1343 	s->cookie_rx[active] = dmaengine_submit(desc);
1344 	if (dma_submit_error(s->cookie_rx[active]))
1345 		goto fail;
1346 
1347 	s->active_rx = s->cookie_rx[!active];
1348 
1349 	dma_async_issue_pending(chan);
1350 
1351 	spin_unlock_irqrestore(&port->lock, flags);
1352 	dev_dbg(port->dev, "%s: cookie %d #%d, new active cookie %d\n",
1353 		__func__, s->cookie_rx[active], active, s->active_rx);
1354 	return;
1355 
1356 fail:
1357 	spin_unlock_irqrestore(&port->lock, flags);
1358 	dev_warn(port->dev, "Failed submitting Rx DMA descriptor\n");
1359 	/* Switch to PIO */
1360 	spin_lock_irqsave(&port->lock, flags);
1361 	dmaengine_terminate_async(chan);
1362 	sci_dma_rx_chan_invalidate(s);
1363 	sci_dma_rx_reenable_irq(s);
1364 	spin_unlock_irqrestore(&port->lock, flags);
1365 }
1366 
1367 static void sci_dma_tx_release(struct sci_port *s)
1368 {
1369 	struct dma_chan *chan = s->chan_tx_saved;
1370 
1371 	cancel_work_sync(&s->work_tx);
1372 	s->chan_tx_saved = s->chan_tx = NULL;
1373 	s->cookie_tx = -EINVAL;
1374 	dmaengine_terminate_sync(chan);
1375 	dma_unmap_single(chan->device->dev, s->tx_dma_addr, UART_XMIT_SIZE,
1376 			 DMA_TO_DEVICE);
1377 	dma_release_channel(chan);
1378 }
1379 
1380 static int sci_dma_rx_submit(struct sci_port *s, bool port_lock_held)
1381 {
1382 	struct dma_chan *chan = s->chan_rx;
1383 	struct uart_port *port = &s->port;
1384 	unsigned long flags;
1385 	int i;
1386 
1387 	for (i = 0; i < 2; i++) {
1388 		struct scatterlist *sg = &s->sg_rx[i];
1389 		struct dma_async_tx_descriptor *desc;
1390 
1391 		desc = dmaengine_prep_slave_sg(chan,
1392 			sg, 1, DMA_DEV_TO_MEM,
1393 			DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
1394 		if (!desc)
1395 			goto fail;
1396 
1397 		desc->callback = sci_dma_rx_complete;
1398 		desc->callback_param = s;
1399 		s->cookie_rx[i] = dmaengine_submit(desc);
1400 		if (dma_submit_error(s->cookie_rx[i]))
1401 			goto fail;
1402 
1403 	}
1404 
1405 	s->active_rx = s->cookie_rx[0];
1406 
1407 	dma_async_issue_pending(chan);
1408 	return 0;
1409 
1410 fail:
1411 	/* Switch to PIO */
1412 	if (!port_lock_held)
1413 		spin_lock_irqsave(&port->lock, flags);
1414 	if (i)
1415 		dmaengine_terminate_async(chan);
1416 	sci_dma_rx_chan_invalidate(s);
1417 	sci_start_rx(port);
1418 	if (!port_lock_held)
1419 		spin_unlock_irqrestore(&port->lock, flags);
1420 	return -EAGAIN;
1421 }
1422 
1423 static void sci_dma_tx_work_fn(struct work_struct *work)
1424 {
1425 	struct sci_port *s = container_of(work, struct sci_port, work_tx);
1426 	struct dma_async_tx_descriptor *desc;
1427 	struct dma_chan *chan = s->chan_tx;
1428 	struct uart_port *port = &s->port;
1429 	struct circ_buf *xmit = &port->state->xmit;
1430 	unsigned long flags;
1431 	dma_addr_t buf;
1432 	int head, tail;
1433 
1434 	/*
1435 	 * DMA is idle now.
1436 	 * Port xmit buffer is already mapped, and it is one page... Just adjust
1437 	 * offsets and lengths. Since it is a circular buffer, we have to
1438 	 * transmit till the end, and then the rest. Take the port lock to get a
1439 	 * consistent xmit buffer state.
1440 	 */
1441 	spin_lock_irq(&port->lock);
1442 	head = xmit->head;
1443 	tail = xmit->tail;
1444 	buf = s->tx_dma_addr + tail;
1445 	s->tx_dma_len = CIRC_CNT_TO_END(head, tail, UART_XMIT_SIZE);
1446 	if (!s->tx_dma_len) {
1447 		/* Transmit buffer has been flushed */
1448 		spin_unlock_irq(&port->lock);
1449 		return;
1450 	}
1451 
1452 	desc = dmaengine_prep_slave_single(chan, buf, s->tx_dma_len,
1453 					   DMA_MEM_TO_DEV,
1454 					   DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
1455 	if (!desc) {
1456 		spin_unlock_irq(&port->lock);
1457 		dev_warn(port->dev, "Failed preparing Tx DMA descriptor\n");
1458 		goto switch_to_pio;
1459 	}
1460 
1461 	dma_sync_single_for_device(chan->device->dev, buf, s->tx_dma_len,
1462 				   DMA_TO_DEVICE);
1463 
1464 	desc->callback = sci_dma_tx_complete;
1465 	desc->callback_param = s;
1466 	s->cookie_tx = dmaengine_submit(desc);
1467 	if (dma_submit_error(s->cookie_tx)) {
1468 		spin_unlock_irq(&port->lock);
1469 		dev_warn(port->dev, "Failed submitting Tx DMA descriptor\n");
1470 		goto switch_to_pio;
1471 	}
1472 
1473 	spin_unlock_irq(&port->lock);
1474 	dev_dbg(port->dev, "%s: %p: %d...%d, cookie %d\n",
1475 		__func__, xmit->buf, tail, head, s->cookie_tx);
1476 
1477 	dma_async_issue_pending(chan);
1478 	return;
1479 
1480 switch_to_pio:
1481 	spin_lock_irqsave(&port->lock, flags);
1482 	s->chan_tx = NULL;
1483 	sci_start_tx(port);
1484 	spin_unlock_irqrestore(&port->lock, flags);
1485 	return;
1486 }
1487 
1488 static enum hrtimer_restart sci_dma_rx_timer_fn(struct hrtimer *t)
1489 {
1490 	struct sci_port *s = container_of(t, struct sci_port, rx_timer);
1491 	struct dma_chan *chan = s->chan_rx;
1492 	struct uart_port *port = &s->port;
1493 	struct dma_tx_state state;
1494 	enum dma_status status;
1495 	unsigned long flags;
1496 	unsigned int read;
1497 	int active, count;
1498 
1499 	dev_dbg(port->dev, "DMA Rx timed out\n");
1500 
1501 	spin_lock_irqsave(&port->lock, flags);
1502 
1503 	active = sci_dma_rx_find_active(s);
1504 	if (active < 0) {
1505 		spin_unlock_irqrestore(&port->lock, flags);
1506 		return HRTIMER_NORESTART;
1507 	}
1508 
1509 	status = dmaengine_tx_status(s->chan_rx, s->active_rx, &state);
1510 	if (status == DMA_COMPLETE) {
1511 		spin_unlock_irqrestore(&port->lock, flags);
1512 		dev_dbg(port->dev, "Cookie %d #%d has already completed\n",
1513 			s->active_rx, active);
1514 
1515 		/* Let packet complete handler take care of the packet */
1516 		return HRTIMER_NORESTART;
1517 	}
1518 
1519 	dmaengine_pause(chan);
1520 
1521 	/*
1522 	 * sometimes DMA transfer doesn't stop even if it is stopped and
1523 	 * data keeps on coming until transaction is complete so check
1524 	 * for DMA_COMPLETE again
1525 	 * Let packet complete handler take care of the packet
1526 	 */
1527 	status = dmaengine_tx_status(s->chan_rx, s->active_rx, &state);
1528 	if (status == DMA_COMPLETE) {
1529 		spin_unlock_irqrestore(&port->lock, flags);
1530 		dev_dbg(port->dev, "Transaction complete after DMA engine was stopped");
1531 		return HRTIMER_NORESTART;
1532 	}
1533 
1534 	/* Handle incomplete DMA receive */
1535 	dmaengine_terminate_async(s->chan_rx);
1536 	read = sg_dma_len(&s->sg_rx[active]) - state.residue;
1537 
1538 	if (read) {
1539 		count = sci_dma_rx_push(s, s->rx_buf[active], read);
1540 		if (count)
1541 			tty_flip_buffer_push(&port->state->port);
1542 	}
1543 
1544 	if (port->type == PORT_SCIFA || port->type == PORT_SCIFB ||
1545 	    s->cfg->regtype == SCIx_RZ_SCIFA_REGTYPE)
1546 		sci_dma_rx_submit(s, true);
1547 
1548 	sci_dma_rx_reenable_irq(s);
1549 
1550 	spin_unlock_irqrestore(&port->lock, flags);
1551 
1552 	return HRTIMER_NORESTART;
1553 }
1554 
1555 static struct dma_chan *sci_request_dma_chan(struct uart_port *port,
1556 					     enum dma_transfer_direction dir)
1557 {
1558 	struct dma_chan *chan;
1559 	struct dma_slave_config cfg;
1560 	int ret;
1561 
1562 	chan = dma_request_slave_channel(port->dev,
1563 					 dir == DMA_MEM_TO_DEV ? "tx" : "rx");
1564 	if (!chan) {
1565 		dev_dbg(port->dev, "dma_request_slave_channel failed\n");
1566 		return NULL;
1567 	}
1568 
1569 	memset(&cfg, 0, sizeof(cfg));
1570 	cfg.direction = dir;
1571 	cfg.dst_addr = port->mapbase +
1572 		(sci_getreg(port, SCxTDR)->offset << port->regshift);
1573 	cfg.dst_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE;
1574 	cfg.src_addr = port->mapbase +
1575 		(sci_getreg(port, SCxRDR)->offset << port->regshift);
1576 	cfg.src_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE;
1577 
1578 	ret = dmaengine_slave_config(chan, &cfg);
1579 	if (ret) {
1580 		dev_warn(port->dev, "dmaengine_slave_config failed %d\n", ret);
1581 		dma_release_channel(chan);
1582 		return NULL;
1583 	}
1584 
1585 	return chan;
1586 }
1587 
1588 static void sci_request_dma(struct uart_port *port)
1589 {
1590 	struct sci_port *s = to_sci_port(port);
1591 	struct dma_chan *chan;
1592 
1593 	dev_dbg(port->dev, "%s: port %d\n", __func__, port->line);
1594 
1595 	/*
1596 	 * DMA on console may interfere with Kernel log messages which use
1597 	 * plain putchar(). So, simply don't use it with a console.
1598 	 */
1599 	if (uart_console(port))
1600 		return;
1601 
1602 	if (!port->dev->of_node)
1603 		return;
1604 
1605 	s->cookie_tx = -EINVAL;
1606 
1607 	/*
1608 	 * Don't request a dma channel if no channel was specified
1609 	 * in the device tree.
1610 	 */
1611 	if (!of_property_present(port->dev->of_node, "dmas"))
1612 		return;
1613 
1614 	chan = sci_request_dma_chan(port, DMA_MEM_TO_DEV);
1615 	dev_dbg(port->dev, "%s: TX: got channel %p\n", __func__, chan);
1616 	if (chan) {
1617 		/* UART circular tx buffer is an aligned page. */
1618 		s->tx_dma_addr = dma_map_single(chan->device->dev,
1619 						port->state->xmit.buf,
1620 						UART_XMIT_SIZE,
1621 						DMA_TO_DEVICE);
1622 		if (dma_mapping_error(chan->device->dev, s->tx_dma_addr)) {
1623 			dev_warn(port->dev, "Failed mapping Tx DMA descriptor\n");
1624 			dma_release_channel(chan);
1625 		} else {
1626 			dev_dbg(port->dev, "%s: mapped %lu@%p to %pad\n",
1627 				__func__, UART_XMIT_SIZE,
1628 				port->state->xmit.buf, &s->tx_dma_addr);
1629 
1630 			INIT_WORK(&s->work_tx, sci_dma_tx_work_fn);
1631 			s->chan_tx_saved = s->chan_tx = chan;
1632 		}
1633 	}
1634 
1635 	chan = sci_request_dma_chan(port, DMA_DEV_TO_MEM);
1636 	dev_dbg(port->dev, "%s: RX: got channel %p\n", __func__, chan);
1637 	if (chan) {
1638 		unsigned int i;
1639 		dma_addr_t dma;
1640 		void *buf;
1641 
1642 		s->buf_len_rx = 2 * max_t(size_t, 16, port->fifosize);
1643 		buf = dma_alloc_coherent(chan->device->dev, s->buf_len_rx * 2,
1644 					 &dma, GFP_KERNEL);
1645 		if (!buf) {
1646 			dev_warn(port->dev,
1647 				 "Failed to allocate Rx dma buffer, using PIO\n");
1648 			dma_release_channel(chan);
1649 			return;
1650 		}
1651 
1652 		for (i = 0; i < 2; i++) {
1653 			struct scatterlist *sg = &s->sg_rx[i];
1654 
1655 			sg_init_table(sg, 1);
1656 			s->rx_buf[i] = buf;
1657 			sg_dma_address(sg) = dma;
1658 			sg_dma_len(sg) = s->buf_len_rx;
1659 
1660 			buf += s->buf_len_rx;
1661 			dma += s->buf_len_rx;
1662 		}
1663 
1664 		hrtimer_init(&s->rx_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1665 		s->rx_timer.function = sci_dma_rx_timer_fn;
1666 
1667 		s->chan_rx_saved = s->chan_rx = chan;
1668 
1669 		if (port->type == PORT_SCIFA || port->type == PORT_SCIFB ||
1670 		    s->cfg->regtype == SCIx_RZ_SCIFA_REGTYPE)
1671 			sci_dma_rx_submit(s, false);
1672 	}
1673 }
1674 
1675 static void sci_free_dma(struct uart_port *port)
1676 {
1677 	struct sci_port *s = to_sci_port(port);
1678 
1679 	if (s->chan_tx_saved)
1680 		sci_dma_tx_release(s);
1681 	if (s->chan_rx_saved)
1682 		sci_dma_rx_release(s);
1683 }
1684 
1685 static void sci_flush_buffer(struct uart_port *port)
1686 {
1687 	struct sci_port *s = to_sci_port(port);
1688 
1689 	/*
1690 	 * In uart_flush_buffer(), the xmit circular buffer has just been
1691 	 * cleared, so we have to reset tx_dma_len accordingly, and stop any
1692 	 * pending transfers
1693 	 */
1694 	s->tx_dma_len = 0;
1695 	if (s->chan_tx) {
1696 		dmaengine_terminate_async(s->chan_tx);
1697 		s->cookie_tx = -EINVAL;
1698 	}
1699 }
1700 #else /* !CONFIG_SERIAL_SH_SCI_DMA */
1701 static inline void sci_request_dma(struct uart_port *port)
1702 {
1703 }
1704 
1705 static inline void sci_free_dma(struct uart_port *port)
1706 {
1707 }
1708 
1709 #define sci_flush_buffer	NULL
1710 #endif /* !CONFIG_SERIAL_SH_SCI_DMA */
1711 
1712 static irqreturn_t sci_rx_interrupt(int irq, void *ptr)
1713 {
1714 	struct uart_port *port = ptr;
1715 	struct sci_port *s = to_sci_port(port);
1716 
1717 #ifdef CONFIG_SERIAL_SH_SCI_DMA
1718 	if (s->chan_rx) {
1719 		u16 scr = serial_port_in(port, SCSCR);
1720 		u16 ssr = serial_port_in(port, SCxSR);
1721 
1722 		/* Disable future Rx interrupts */
1723 		if (port->type == PORT_SCIFA || port->type == PORT_SCIFB ||
1724 		    s->cfg->regtype == SCIx_RZ_SCIFA_REGTYPE) {
1725 			disable_irq_nosync(s->irqs[SCIx_RXI_IRQ]);
1726 			if (s->cfg->regtype == SCIx_RZ_SCIFA_REGTYPE) {
1727 				scif_set_rtrg(port, 1);
1728 				scr |= SCSCR_RIE;
1729 			} else {
1730 				scr |= SCSCR_RDRQE;
1731 			}
1732 		} else {
1733 			if (sci_dma_rx_submit(s, false) < 0)
1734 				goto handle_pio;
1735 
1736 			scr &= ~SCSCR_RIE;
1737 		}
1738 		serial_port_out(port, SCSCR, scr);
1739 		/* Clear current interrupt */
1740 		serial_port_out(port, SCxSR,
1741 				ssr & ~(SCIF_DR | SCxSR_RDxF(port)));
1742 		dev_dbg(port->dev, "Rx IRQ %lu: setup t-out in %u us\n",
1743 			jiffies, s->rx_timeout);
1744 		start_hrtimer_us(&s->rx_timer, s->rx_timeout);
1745 
1746 		return IRQ_HANDLED;
1747 	}
1748 
1749 handle_pio:
1750 #endif
1751 
1752 	if (s->rx_trigger > 1 && s->rx_fifo_timeout > 0) {
1753 		if (!scif_rtrg_enabled(port))
1754 			scif_set_rtrg(port, s->rx_trigger);
1755 
1756 		mod_timer(&s->rx_fifo_timer, jiffies + DIV_ROUND_UP(
1757 			  s->rx_frame * HZ * s->rx_fifo_timeout, 1000000));
1758 	}
1759 
1760 	/* I think sci_receive_chars has to be called irrespective
1761 	 * of whether the I_IXOFF is set, otherwise, how is the interrupt
1762 	 * to be disabled?
1763 	 */
1764 	sci_receive_chars(port);
1765 
1766 	return IRQ_HANDLED;
1767 }
1768 
1769 static irqreturn_t sci_tx_interrupt(int irq, void *ptr)
1770 {
1771 	struct uart_port *port = ptr;
1772 	unsigned long flags;
1773 
1774 	spin_lock_irqsave(&port->lock, flags);
1775 	sci_transmit_chars(port);
1776 	spin_unlock_irqrestore(&port->lock, flags);
1777 
1778 	return IRQ_HANDLED;
1779 }
1780 
1781 static irqreturn_t sci_tx_end_interrupt(int irq, void *ptr)
1782 {
1783 	struct uart_port *port = ptr;
1784 	unsigned long flags;
1785 	unsigned short ctrl;
1786 
1787 	if (port->type != PORT_SCI)
1788 		return sci_tx_interrupt(irq, ptr);
1789 
1790 	spin_lock_irqsave(&port->lock, flags);
1791 	ctrl = serial_port_in(port, SCSCR);
1792 	ctrl &= ~(SCSCR_TE | SCSCR_TEIE);
1793 	serial_port_out(port, SCSCR, ctrl);
1794 	spin_unlock_irqrestore(&port->lock, flags);
1795 
1796 	return IRQ_HANDLED;
1797 }
1798 
1799 static irqreturn_t sci_br_interrupt(int irq, void *ptr)
1800 {
1801 	struct uart_port *port = ptr;
1802 
1803 	/* Handle BREAKs */
1804 	sci_handle_breaks(port);
1805 
1806 	/* drop invalid character received before break was detected */
1807 	serial_port_in(port, SCxRDR);
1808 
1809 	sci_clear_SCxSR(port, SCxSR_BREAK_CLEAR(port));
1810 
1811 	return IRQ_HANDLED;
1812 }
1813 
1814 static irqreturn_t sci_er_interrupt(int irq, void *ptr)
1815 {
1816 	struct uart_port *port = ptr;
1817 	struct sci_port *s = to_sci_port(port);
1818 
1819 	if (s->irqs[SCIx_ERI_IRQ] == s->irqs[SCIx_BRI_IRQ]) {
1820 		/* Break and Error interrupts are muxed */
1821 		unsigned short ssr_status = serial_port_in(port, SCxSR);
1822 
1823 		/* Break Interrupt */
1824 		if (ssr_status & SCxSR_BRK(port))
1825 			sci_br_interrupt(irq, ptr);
1826 
1827 		/* Break only? */
1828 		if (!(ssr_status & SCxSR_ERRORS(port)))
1829 			return IRQ_HANDLED;
1830 	}
1831 
1832 	/* Handle errors */
1833 	if (port->type == PORT_SCI) {
1834 		if (sci_handle_errors(port)) {
1835 			/* discard character in rx buffer */
1836 			serial_port_in(port, SCxSR);
1837 			sci_clear_SCxSR(port, SCxSR_RDxF_CLEAR(port));
1838 		}
1839 	} else {
1840 		sci_handle_fifo_overrun(port);
1841 		if (!s->chan_rx)
1842 			sci_receive_chars(port);
1843 	}
1844 
1845 	sci_clear_SCxSR(port, SCxSR_ERROR_CLEAR(port));
1846 
1847 	/* Kick the transmission */
1848 	if (!s->chan_tx)
1849 		sci_tx_interrupt(irq, ptr);
1850 
1851 	return IRQ_HANDLED;
1852 }
1853 
1854 static irqreturn_t sci_mpxed_interrupt(int irq, void *ptr)
1855 {
1856 	unsigned short ssr_status, scr_status, err_enabled, orer_status = 0;
1857 	struct uart_port *port = ptr;
1858 	struct sci_port *s = to_sci_port(port);
1859 	irqreturn_t ret = IRQ_NONE;
1860 
1861 	ssr_status = serial_port_in(port, SCxSR);
1862 	scr_status = serial_port_in(port, SCSCR);
1863 	if (s->params->overrun_reg == SCxSR)
1864 		orer_status = ssr_status;
1865 	else if (sci_getreg(port, s->params->overrun_reg)->size)
1866 		orer_status = serial_port_in(port, s->params->overrun_reg);
1867 
1868 	err_enabled = scr_status & port_rx_irq_mask(port);
1869 
1870 	/* Tx Interrupt */
1871 	if ((ssr_status & SCxSR_TDxE(port)) && (scr_status & SCSCR_TIE) &&
1872 	    !s->chan_tx)
1873 		ret = sci_tx_interrupt(irq, ptr);
1874 
1875 	/*
1876 	 * Rx Interrupt: if we're using DMA, the DMA controller clears RDF /
1877 	 * DR flags
1878 	 */
1879 	if (((ssr_status & SCxSR_RDxF(port)) || s->chan_rx) &&
1880 	    (scr_status & SCSCR_RIE))
1881 		ret = sci_rx_interrupt(irq, ptr);
1882 
1883 	/* Error Interrupt */
1884 	if ((ssr_status & SCxSR_ERRORS(port)) && err_enabled)
1885 		ret = sci_er_interrupt(irq, ptr);
1886 
1887 	/* Break Interrupt */
1888 	if (s->irqs[SCIx_ERI_IRQ] != s->irqs[SCIx_BRI_IRQ] &&
1889 	    (ssr_status & SCxSR_BRK(port)) && err_enabled)
1890 		ret = sci_br_interrupt(irq, ptr);
1891 
1892 	/* Overrun Interrupt */
1893 	if (orer_status & s->params->overrun_mask) {
1894 		sci_handle_fifo_overrun(port);
1895 		ret = IRQ_HANDLED;
1896 	}
1897 
1898 	return ret;
1899 }
1900 
1901 static const struct sci_irq_desc {
1902 	const char	*desc;
1903 	irq_handler_t	handler;
1904 } sci_irq_desc[] = {
1905 	/*
1906 	 * Split out handlers, the default case.
1907 	 */
1908 	[SCIx_ERI_IRQ] = {
1909 		.desc = "rx err",
1910 		.handler = sci_er_interrupt,
1911 	},
1912 
1913 	[SCIx_RXI_IRQ] = {
1914 		.desc = "rx full",
1915 		.handler = sci_rx_interrupt,
1916 	},
1917 
1918 	[SCIx_TXI_IRQ] = {
1919 		.desc = "tx empty",
1920 		.handler = sci_tx_interrupt,
1921 	},
1922 
1923 	[SCIx_BRI_IRQ] = {
1924 		.desc = "break",
1925 		.handler = sci_br_interrupt,
1926 	},
1927 
1928 	[SCIx_DRI_IRQ] = {
1929 		.desc = "rx ready",
1930 		.handler = sci_rx_interrupt,
1931 	},
1932 
1933 	[SCIx_TEI_IRQ] = {
1934 		.desc = "tx end",
1935 		.handler = sci_tx_end_interrupt,
1936 	},
1937 
1938 	/*
1939 	 * Special muxed handler.
1940 	 */
1941 	[SCIx_MUX_IRQ] = {
1942 		.desc = "mux",
1943 		.handler = sci_mpxed_interrupt,
1944 	},
1945 };
1946 
1947 static int sci_request_irq(struct sci_port *port)
1948 {
1949 	struct uart_port *up = &port->port;
1950 	int i, j, w, ret = 0;
1951 
1952 	for (i = j = 0; i < SCIx_NR_IRQS; i++, j++) {
1953 		const struct sci_irq_desc *desc;
1954 		int irq;
1955 
1956 		/* Check if already registered (muxed) */
1957 		for (w = 0; w < i; w++)
1958 			if (port->irqs[w] == port->irqs[i])
1959 				w = i + 1;
1960 		if (w > i)
1961 			continue;
1962 
1963 		if (SCIx_IRQ_IS_MUXED(port)) {
1964 			i = SCIx_MUX_IRQ;
1965 			irq = up->irq;
1966 		} else {
1967 			irq = port->irqs[i];
1968 
1969 			/*
1970 			 * Certain port types won't support all of the
1971 			 * available interrupt sources.
1972 			 */
1973 			if (unlikely(irq < 0))
1974 				continue;
1975 		}
1976 
1977 		desc = sci_irq_desc + i;
1978 		port->irqstr[j] = kasprintf(GFP_KERNEL, "%s:%s",
1979 					    dev_name(up->dev), desc->desc);
1980 		if (!port->irqstr[j]) {
1981 			ret = -ENOMEM;
1982 			goto out_nomem;
1983 		}
1984 
1985 		ret = request_irq(irq, desc->handler, up->irqflags,
1986 				  port->irqstr[j], port);
1987 		if (unlikely(ret)) {
1988 			dev_err(up->dev, "Can't allocate %s IRQ\n", desc->desc);
1989 			goto out_noirq;
1990 		}
1991 	}
1992 
1993 	return 0;
1994 
1995 out_noirq:
1996 	while (--i >= 0)
1997 		free_irq(port->irqs[i], port);
1998 
1999 out_nomem:
2000 	while (--j >= 0)
2001 		kfree(port->irqstr[j]);
2002 
2003 	return ret;
2004 }
2005 
2006 static void sci_free_irq(struct sci_port *port)
2007 {
2008 	int i, j;
2009 
2010 	/*
2011 	 * Intentionally in reverse order so we iterate over the muxed
2012 	 * IRQ first.
2013 	 */
2014 	for (i = 0; i < SCIx_NR_IRQS; i++) {
2015 		int irq = port->irqs[i];
2016 
2017 		/*
2018 		 * Certain port types won't support all of the available
2019 		 * interrupt sources.
2020 		 */
2021 		if (unlikely(irq < 0))
2022 			continue;
2023 
2024 		/* Check if already freed (irq was muxed) */
2025 		for (j = 0; j < i; j++)
2026 			if (port->irqs[j] == irq)
2027 				j = i + 1;
2028 		if (j > i)
2029 			continue;
2030 
2031 		free_irq(port->irqs[i], port);
2032 		kfree(port->irqstr[i]);
2033 
2034 		if (SCIx_IRQ_IS_MUXED(port)) {
2035 			/* If there's only one IRQ, we're done. */
2036 			return;
2037 		}
2038 	}
2039 }
2040 
2041 static unsigned int sci_tx_empty(struct uart_port *port)
2042 {
2043 	unsigned short status = serial_port_in(port, SCxSR);
2044 	unsigned short in_tx_fifo = sci_txfill(port);
2045 
2046 	return (status & SCxSR_TEND(port)) && !in_tx_fifo ? TIOCSER_TEMT : 0;
2047 }
2048 
2049 static void sci_set_rts(struct uart_port *port, bool state)
2050 {
2051 	if (port->type == PORT_SCIFA || port->type == PORT_SCIFB) {
2052 		u16 data = serial_port_in(port, SCPDR);
2053 
2054 		/* Active low */
2055 		if (state)
2056 			data &= ~SCPDR_RTSD;
2057 		else
2058 			data |= SCPDR_RTSD;
2059 		serial_port_out(port, SCPDR, data);
2060 
2061 		/* RTS# is output */
2062 		serial_port_out(port, SCPCR,
2063 				serial_port_in(port, SCPCR) | SCPCR_RTSC);
2064 	} else if (sci_getreg(port, SCSPTR)->size) {
2065 		u16 ctrl = serial_port_in(port, SCSPTR);
2066 
2067 		/* Active low */
2068 		if (state)
2069 			ctrl &= ~SCSPTR_RTSDT;
2070 		else
2071 			ctrl |= SCSPTR_RTSDT;
2072 		serial_port_out(port, SCSPTR, ctrl);
2073 	}
2074 }
2075 
2076 static bool sci_get_cts(struct uart_port *port)
2077 {
2078 	if (port->type == PORT_SCIFA || port->type == PORT_SCIFB) {
2079 		/* Active low */
2080 		return !(serial_port_in(port, SCPDR) & SCPDR_CTSD);
2081 	} else if (sci_getreg(port, SCSPTR)->size) {
2082 		/* Active low */
2083 		return !(serial_port_in(port, SCSPTR) & SCSPTR_CTSDT);
2084 	}
2085 
2086 	return true;
2087 }
2088 
2089 /*
2090  * Modem control is a bit of a mixed bag for SCI(F) ports. Generally
2091  * CTS/RTS is supported in hardware by at least one port and controlled
2092  * via SCSPTR (SCxPCR for SCIFA/B parts), or external pins (presently
2093  * handled via the ->init_pins() op, which is a bit of a one-way street,
2094  * lacking any ability to defer pin control -- this will later be
2095  * converted over to the GPIO framework).
2096  *
2097  * Other modes (such as loopback) are supported generically on certain
2098  * port types, but not others. For these it's sufficient to test for the
2099  * existence of the support register and simply ignore the port type.
2100  */
2101 static void sci_set_mctrl(struct uart_port *port, unsigned int mctrl)
2102 {
2103 	struct sci_port *s = to_sci_port(port);
2104 
2105 	if (mctrl & TIOCM_LOOP) {
2106 		const struct plat_sci_reg *reg;
2107 
2108 		/*
2109 		 * Standard loopback mode for SCFCR ports.
2110 		 */
2111 		reg = sci_getreg(port, SCFCR);
2112 		if (reg->size)
2113 			serial_port_out(port, SCFCR,
2114 					serial_port_in(port, SCFCR) |
2115 					SCFCR_LOOP);
2116 	}
2117 
2118 	mctrl_gpio_set(s->gpios, mctrl);
2119 
2120 	if (!s->has_rtscts)
2121 		return;
2122 
2123 	if (!(mctrl & TIOCM_RTS)) {
2124 		/* Disable Auto RTS */
2125 		serial_port_out(port, SCFCR,
2126 				serial_port_in(port, SCFCR) & ~SCFCR_MCE);
2127 
2128 		/* Clear RTS */
2129 		sci_set_rts(port, 0);
2130 	} else if (s->autorts) {
2131 		if (port->type == PORT_SCIFA || port->type == PORT_SCIFB) {
2132 			/* Enable RTS# pin function */
2133 			serial_port_out(port, SCPCR,
2134 				serial_port_in(port, SCPCR) & ~SCPCR_RTSC);
2135 		}
2136 
2137 		/* Enable Auto RTS */
2138 		serial_port_out(port, SCFCR,
2139 				serial_port_in(port, SCFCR) | SCFCR_MCE);
2140 	} else {
2141 		/* Set RTS */
2142 		sci_set_rts(port, 1);
2143 	}
2144 }
2145 
2146 static unsigned int sci_get_mctrl(struct uart_port *port)
2147 {
2148 	struct sci_port *s = to_sci_port(port);
2149 	struct mctrl_gpios *gpios = s->gpios;
2150 	unsigned int mctrl = 0;
2151 
2152 	mctrl_gpio_get(gpios, &mctrl);
2153 
2154 	/*
2155 	 * CTS/RTS is handled in hardware when supported, while nothing
2156 	 * else is wired up.
2157 	 */
2158 	if (s->autorts) {
2159 		if (sci_get_cts(port))
2160 			mctrl |= TIOCM_CTS;
2161 	} else if (!mctrl_gpio_to_gpiod(gpios, UART_GPIO_CTS)) {
2162 		mctrl |= TIOCM_CTS;
2163 	}
2164 	if (!mctrl_gpio_to_gpiod(gpios, UART_GPIO_DSR))
2165 		mctrl |= TIOCM_DSR;
2166 	if (!mctrl_gpio_to_gpiod(gpios, UART_GPIO_DCD))
2167 		mctrl |= TIOCM_CAR;
2168 
2169 	return mctrl;
2170 }
2171 
2172 static void sci_enable_ms(struct uart_port *port)
2173 {
2174 	mctrl_gpio_enable_ms(to_sci_port(port)->gpios);
2175 }
2176 
2177 static void sci_break_ctl(struct uart_port *port, int break_state)
2178 {
2179 	unsigned short scscr, scsptr;
2180 	unsigned long flags;
2181 
2182 	/* check whether the port has SCSPTR */
2183 	if (!sci_getreg(port, SCSPTR)->size) {
2184 		/*
2185 		 * Not supported by hardware. Most parts couple break and rx
2186 		 * interrupts together, with break detection always enabled.
2187 		 */
2188 		return;
2189 	}
2190 
2191 	spin_lock_irqsave(&port->lock, flags);
2192 	scsptr = serial_port_in(port, SCSPTR);
2193 	scscr = serial_port_in(port, SCSCR);
2194 
2195 	if (break_state == -1) {
2196 		scsptr = (scsptr | SCSPTR_SPB2IO) & ~SCSPTR_SPB2DT;
2197 		scscr &= ~SCSCR_TE;
2198 	} else {
2199 		scsptr = (scsptr | SCSPTR_SPB2DT) & ~SCSPTR_SPB2IO;
2200 		scscr |= SCSCR_TE;
2201 	}
2202 
2203 	serial_port_out(port, SCSPTR, scsptr);
2204 	serial_port_out(port, SCSCR, scscr);
2205 	spin_unlock_irqrestore(&port->lock, flags);
2206 }
2207 
2208 static int sci_startup(struct uart_port *port)
2209 {
2210 	struct sci_port *s = to_sci_port(port);
2211 	int ret;
2212 
2213 	dev_dbg(port->dev, "%s(%d)\n", __func__, port->line);
2214 
2215 	sci_request_dma(port);
2216 
2217 	ret = sci_request_irq(s);
2218 	if (unlikely(ret < 0)) {
2219 		sci_free_dma(port);
2220 		return ret;
2221 	}
2222 
2223 	return 0;
2224 }
2225 
2226 static void sci_shutdown(struct uart_port *port)
2227 {
2228 	struct sci_port *s = to_sci_port(port);
2229 	unsigned long flags;
2230 	u16 scr;
2231 
2232 	dev_dbg(port->dev, "%s(%d)\n", __func__, port->line);
2233 
2234 	s->autorts = false;
2235 	mctrl_gpio_disable_ms(to_sci_port(port)->gpios);
2236 
2237 	spin_lock_irqsave(&port->lock, flags);
2238 	sci_stop_rx(port);
2239 	sci_stop_tx(port);
2240 	/*
2241 	 * Stop RX and TX, disable related interrupts, keep clock source
2242 	 * and HSCIF TOT bits
2243 	 */
2244 	scr = serial_port_in(port, SCSCR);
2245 	serial_port_out(port, SCSCR, scr &
2246 			(SCSCR_CKE1 | SCSCR_CKE0 | s->hscif_tot));
2247 	spin_unlock_irqrestore(&port->lock, flags);
2248 
2249 #ifdef CONFIG_SERIAL_SH_SCI_DMA
2250 	if (s->chan_rx_saved) {
2251 		dev_dbg(port->dev, "%s(%d) deleting rx_timer\n", __func__,
2252 			port->line);
2253 		hrtimer_cancel(&s->rx_timer);
2254 	}
2255 #endif
2256 
2257 	if (s->rx_trigger > 1 && s->rx_fifo_timeout > 0)
2258 		del_timer_sync(&s->rx_fifo_timer);
2259 	sci_free_irq(s);
2260 	sci_free_dma(port);
2261 }
2262 
2263 static int sci_sck_calc(struct sci_port *s, unsigned int bps,
2264 			unsigned int *srr)
2265 {
2266 	unsigned long freq = s->clk_rates[SCI_SCK];
2267 	int err, min_err = INT_MAX;
2268 	unsigned int sr;
2269 
2270 	if (s->port.type != PORT_HSCIF)
2271 		freq *= 2;
2272 
2273 	for_each_sr(sr, s) {
2274 		err = DIV_ROUND_CLOSEST(freq, sr) - bps;
2275 		if (abs(err) >= abs(min_err))
2276 			continue;
2277 
2278 		min_err = err;
2279 		*srr = sr - 1;
2280 
2281 		if (!err)
2282 			break;
2283 	}
2284 
2285 	dev_dbg(s->port.dev, "SCK: %u%+d bps using SR %u\n", bps, min_err,
2286 		*srr + 1);
2287 	return min_err;
2288 }
2289 
2290 static int sci_brg_calc(struct sci_port *s, unsigned int bps,
2291 			unsigned long freq, unsigned int *dlr,
2292 			unsigned int *srr)
2293 {
2294 	int err, min_err = INT_MAX;
2295 	unsigned int sr, dl;
2296 
2297 	if (s->port.type != PORT_HSCIF)
2298 		freq *= 2;
2299 
2300 	for_each_sr(sr, s) {
2301 		dl = DIV_ROUND_CLOSEST(freq, sr * bps);
2302 		dl = clamp(dl, 1U, 65535U);
2303 
2304 		err = DIV_ROUND_CLOSEST(freq, sr * dl) - bps;
2305 		if (abs(err) >= abs(min_err))
2306 			continue;
2307 
2308 		min_err = err;
2309 		*dlr = dl;
2310 		*srr = sr - 1;
2311 
2312 		if (!err)
2313 			break;
2314 	}
2315 
2316 	dev_dbg(s->port.dev, "BRG: %u%+d bps using DL %u SR %u\n", bps,
2317 		min_err, *dlr, *srr + 1);
2318 	return min_err;
2319 }
2320 
2321 /* calculate sample rate, BRR, and clock select */
2322 static int sci_scbrr_calc(struct sci_port *s, unsigned int bps,
2323 			  unsigned int *brr, unsigned int *srr,
2324 			  unsigned int *cks)
2325 {
2326 	unsigned long freq = s->clk_rates[SCI_FCK];
2327 	unsigned int sr, br, prediv, scrate, c;
2328 	int err, min_err = INT_MAX;
2329 
2330 	if (s->port.type != PORT_HSCIF)
2331 		freq *= 2;
2332 
2333 	/*
2334 	 * Find the combination of sample rate and clock select with the
2335 	 * smallest deviation from the desired baud rate.
2336 	 * Prefer high sample rates to maximise the receive margin.
2337 	 *
2338 	 * M: Receive margin (%)
2339 	 * N: Ratio of bit rate to clock (N = sampling rate)
2340 	 * D: Clock duty (D = 0 to 1.0)
2341 	 * L: Frame length (L = 9 to 12)
2342 	 * F: Absolute value of clock frequency deviation
2343 	 *
2344 	 *  M = |(0.5 - 1 / 2 * N) - ((L - 0.5) * F) -
2345 	 *      (|D - 0.5| / N * (1 + F))|
2346 	 *  NOTE: Usually, treat D for 0.5, F is 0 by this calculation.
2347 	 */
2348 	for_each_sr(sr, s) {
2349 		for (c = 0; c <= 3; c++) {
2350 			/* integerized formulas from HSCIF documentation */
2351 			prediv = sr << (2 * c + 1);
2352 
2353 			/*
2354 			 * We need to calculate:
2355 			 *
2356 			 *     br = freq / (prediv * bps) clamped to [1..256]
2357 			 *     err = freq / (br * prediv) - bps
2358 			 *
2359 			 * Watch out for overflow when calculating the desired
2360 			 * sampling clock rate!
2361 			 */
2362 			if (bps > UINT_MAX / prediv)
2363 				break;
2364 
2365 			scrate = prediv * bps;
2366 			br = DIV_ROUND_CLOSEST(freq, scrate);
2367 			br = clamp(br, 1U, 256U);
2368 
2369 			err = DIV_ROUND_CLOSEST(freq, br * prediv) - bps;
2370 			if (abs(err) >= abs(min_err))
2371 				continue;
2372 
2373 			min_err = err;
2374 			*brr = br - 1;
2375 			*srr = sr - 1;
2376 			*cks = c;
2377 
2378 			if (!err)
2379 				goto found;
2380 		}
2381 	}
2382 
2383 found:
2384 	dev_dbg(s->port.dev, "BRR: %u%+d bps using N %u SR %u cks %u\n", bps,
2385 		min_err, *brr, *srr + 1, *cks);
2386 	return min_err;
2387 }
2388 
2389 static void sci_reset(struct uart_port *port)
2390 {
2391 	const struct plat_sci_reg *reg;
2392 	unsigned int status;
2393 	struct sci_port *s = to_sci_port(port);
2394 
2395 	serial_port_out(port, SCSCR, s->hscif_tot);	/* TE=0, RE=0, CKE1=0 */
2396 
2397 	reg = sci_getreg(port, SCFCR);
2398 	if (reg->size)
2399 		serial_port_out(port, SCFCR, SCFCR_RFRST | SCFCR_TFRST);
2400 
2401 	sci_clear_SCxSR(port,
2402 			SCxSR_RDxF_CLEAR(port) & SCxSR_ERROR_CLEAR(port) &
2403 			SCxSR_BREAK_CLEAR(port));
2404 	if (sci_getreg(port, SCLSR)->size) {
2405 		status = serial_port_in(port, SCLSR);
2406 		status &= ~(SCLSR_TO | SCLSR_ORER);
2407 		serial_port_out(port, SCLSR, status);
2408 	}
2409 
2410 	if (s->rx_trigger > 1) {
2411 		if (s->rx_fifo_timeout) {
2412 			scif_set_rtrg(port, 1);
2413 			timer_setup(&s->rx_fifo_timer, rx_fifo_timer_fn, 0);
2414 		} else {
2415 			if (port->type == PORT_SCIFA ||
2416 			    port->type == PORT_SCIFB)
2417 				scif_set_rtrg(port, 1);
2418 			else
2419 				scif_set_rtrg(port, s->rx_trigger);
2420 		}
2421 	}
2422 }
2423 
2424 static void sci_set_termios(struct uart_port *port, struct ktermios *termios,
2425 		            const struct ktermios *old)
2426 {
2427 	unsigned int baud, smr_val = SCSMR_ASYNC, scr_val = 0, i, bits;
2428 	unsigned int brr = 255, cks = 0, srr = 15, dl = 0, sccks = 0;
2429 	unsigned int brr1 = 255, cks1 = 0, srr1 = 15, dl1 = 0;
2430 	struct sci_port *s = to_sci_port(port);
2431 	const struct plat_sci_reg *reg;
2432 	int min_err = INT_MAX, err;
2433 	unsigned long max_freq = 0;
2434 	int best_clk = -1;
2435 	unsigned long flags;
2436 
2437 	if ((termios->c_cflag & CSIZE) == CS7) {
2438 		smr_val |= SCSMR_CHR;
2439 	} else {
2440 		termios->c_cflag &= ~CSIZE;
2441 		termios->c_cflag |= CS8;
2442 	}
2443 	if (termios->c_cflag & PARENB)
2444 		smr_val |= SCSMR_PE;
2445 	if (termios->c_cflag & PARODD)
2446 		smr_val |= SCSMR_PE | SCSMR_ODD;
2447 	if (termios->c_cflag & CSTOPB)
2448 		smr_val |= SCSMR_STOP;
2449 
2450 	/*
2451 	 * earlyprintk comes here early on with port->uartclk set to zero.
2452 	 * the clock framework is not up and running at this point so here
2453 	 * we assume that 115200 is the maximum baud rate. please note that
2454 	 * the baud rate is not programmed during earlyprintk - it is assumed
2455 	 * that the previous boot loader has enabled required clocks and
2456 	 * setup the baud rate generator hardware for us already.
2457 	 */
2458 	if (!port->uartclk) {
2459 		baud = uart_get_baud_rate(port, termios, old, 0, 115200);
2460 		goto done;
2461 	}
2462 
2463 	for (i = 0; i < SCI_NUM_CLKS; i++)
2464 		max_freq = max(max_freq, s->clk_rates[i]);
2465 
2466 	baud = uart_get_baud_rate(port, termios, old, 0, max_freq / min_sr(s));
2467 	if (!baud)
2468 		goto done;
2469 
2470 	/*
2471 	 * There can be multiple sources for the sampling clock.  Find the one
2472 	 * that gives us the smallest deviation from the desired baud rate.
2473 	 */
2474 
2475 	/* Optional Undivided External Clock */
2476 	if (s->clk_rates[SCI_SCK] && port->type != PORT_SCIFA &&
2477 	    port->type != PORT_SCIFB) {
2478 		err = sci_sck_calc(s, baud, &srr1);
2479 		if (abs(err) < abs(min_err)) {
2480 			best_clk = SCI_SCK;
2481 			scr_val = SCSCR_CKE1;
2482 			sccks = SCCKS_CKS;
2483 			min_err = err;
2484 			srr = srr1;
2485 			if (!err)
2486 				goto done;
2487 		}
2488 	}
2489 
2490 	/* Optional BRG Frequency Divided External Clock */
2491 	if (s->clk_rates[SCI_SCIF_CLK] && sci_getreg(port, SCDL)->size) {
2492 		err = sci_brg_calc(s, baud, s->clk_rates[SCI_SCIF_CLK], &dl1,
2493 				   &srr1);
2494 		if (abs(err) < abs(min_err)) {
2495 			best_clk = SCI_SCIF_CLK;
2496 			scr_val = SCSCR_CKE1;
2497 			sccks = 0;
2498 			min_err = err;
2499 			dl = dl1;
2500 			srr = srr1;
2501 			if (!err)
2502 				goto done;
2503 		}
2504 	}
2505 
2506 	/* Optional BRG Frequency Divided Internal Clock */
2507 	if (s->clk_rates[SCI_BRG_INT] && sci_getreg(port, SCDL)->size) {
2508 		err = sci_brg_calc(s, baud, s->clk_rates[SCI_BRG_INT], &dl1,
2509 				   &srr1);
2510 		if (abs(err) < abs(min_err)) {
2511 			best_clk = SCI_BRG_INT;
2512 			scr_val = SCSCR_CKE1;
2513 			sccks = SCCKS_XIN;
2514 			min_err = err;
2515 			dl = dl1;
2516 			srr = srr1;
2517 			if (!min_err)
2518 				goto done;
2519 		}
2520 	}
2521 
2522 	/* Divided Functional Clock using standard Bit Rate Register */
2523 	err = sci_scbrr_calc(s, baud, &brr1, &srr1, &cks1);
2524 	if (abs(err) < abs(min_err)) {
2525 		best_clk = SCI_FCK;
2526 		scr_val = 0;
2527 		min_err = err;
2528 		brr = brr1;
2529 		srr = srr1;
2530 		cks = cks1;
2531 	}
2532 
2533 done:
2534 	if (best_clk >= 0)
2535 		dev_dbg(port->dev, "Using clk %pC for %u%+d bps\n",
2536 			s->clks[best_clk], baud, min_err);
2537 
2538 	sci_port_enable(s);
2539 
2540 	/*
2541 	 * Program the optional External Baud Rate Generator (BRG) first.
2542 	 * It controls the mux to select (H)SCK or frequency divided clock.
2543 	 */
2544 	if (best_clk >= 0 && sci_getreg(port, SCCKS)->size) {
2545 		serial_port_out(port, SCDL, dl);
2546 		serial_port_out(port, SCCKS, sccks);
2547 	}
2548 
2549 	spin_lock_irqsave(&port->lock, flags);
2550 
2551 	sci_reset(port);
2552 
2553 	uart_update_timeout(port, termios->c_cflag, baud);
2554 
2555 	/* byte size and parity */
2556 	bits = tty_get_frame_size(termios->c_cflag);
2557 
2558 	if (sci_getreg(port, SEMR)->size)
2559 		serial_port_out(port, SEMR, 0);
2560 
2561 	if (best_clk >= 0) {
2562 		if (port->type == PORT_SCIFA || port->type == PORT_SCIFB)
2563 			switch (srr + 1) {
2564 			case 5:  smr_val |= SCSMR_SRC_5;  break;
2565 			case 7:  smr_val |= SCSMR_SRC_7;  break;
2566 			case 11: smr_val |= SCSMR_SRC_11; break;
2567 			case 13: smr_val |= SCSMR_SRC_13; break;
2568 			case 16: smr_val |= SCSMR_SRC_16; break;
2569 			case 17: smr_val |= SCSMR_SRC_17; break;
2570 			case 19: smr_val |= SCSMR_SRC_19; break;
2571 			case 27: smr_val |= SCSMR_SRC_27; break;
2572 			}
2573 		smr_val |= cks;
2574 		serial_port_out(port, SCSCR, scr_val | s->hscif_tot);
2575 		serial_port_out(port, SCSMR, smr_val);
2576 		serial_port_out(port, SCBRR, brr);
2577 		if (sci_getreg(port, HSSRR)->size) {
2578 			unsigned int hssrr = srr | HSCIF_SRE;
2579 			/* Calculate deviation from intended rate at the
2580 			 * center of the last stop bit in sampling clocks.
2581 			 */
2582 			int last_stop = bits * 2 - 1;
2583 			int deviation = DIV_ROUND_CLOSEST(min_err * last_stop *
2584 							  (int)(srr + 1),
2585 							  2 * (int)baud);
2586 
2587 			if (abs(deviation) >= 2) {
2588 				/* At least two sampling clocks off at the
2589 				 * last stop bit; we can increase the error
2590 				 * margin by shifting the sampling point.
2591 				 */
2592 				int shift = clamp(deviation / 2, -8, 7);
2593 
2594 				hssrr |= (shift << HSCIF_SRHP_SHIFT) &
2595 					 HSCIF_SRHP_MASK;
2596 				hssrr |= HSCIF_SRDE;
2597 			}
2598 			serial_port_out(port, HSSRR, hssrr);
2599 		}
2600 
2601 		/* Wait one bit interval */
2602 		udelay((1000000 + (baud - 1)) / baud);
2603 	} else {
2604 		/* Don't touch the bit rate configuration */
2605 		scr_val = s->cfg->scscr & (SCSCR_CKE1 | SCSCR_CKE0);
2606 		smr_val |= serial_port_in(port, SCSMR) &
2607 			   (SCSMR_CKEDG | SCSMR_SRC_MASK | SCSMR_CKS);
2608 		serial_port_out(port, SCSCR, scr_val | s->hscif_tot);
2609 		serial_port_out(port, SCSMR, smr_val);
2610 	}
2611 
2612 	sci_init_pins(port, termios->c_cflag);
2613 
2614 	port->status &= ~UPSTAT_AUTOCTS;
2615 	s->autorts = false;
2616 	reg = sci_getreg(port, SCFCR);
2617 	if (reg->size) {
2618 		unsigned short ctrl = serial_port_in(port, SCFCR);
2619 
2620 		if ((port->flags & UPF_HARD_FLOW) &&
2621 		    (termios->c_cflag & CRTSCTS)) {
2622 			/* There is no CTS interrupt to restart the hardware */
2623 			port->status |= UPSTAT_AUTOCTS;
2624 			/* MCE is enabled when RTS is raised */
2625 			s->autorts = true;
2626 		}
2627 
2628 		/*
2629 		 * As we've done a sci_reset() above, ensure we don't
2630 		 * interfere with the FIFOs while toggling MCE. As the
2631 		 * reset values could still be set, simply mask them out.
2632 		 */
2633 		ctrl &= ~(SCFCR_RFRST | SCFCR_TFRST);
2634 
2635 		serial_port_out(port, SCFCR, ctrl);
2636 	}
2637 	if (port->flags & UPF_HARD_FLOW) {
2638 		/* Refresh (Auto) RTS */
2639 		sci_set_mctrl(port, port->mctrl);
2640 	}
2641 
2642 	/*
2643 	 * For SCI, TE (transmit enable) must be set after setting TIE
2644 	 * (transmit interrupt enable) or in the same instruction to
2645 	 * start the transmitting process. So skip setting TE here for SCI.
2646 	 */
2647 	if (port->type != PORT_SCI)
2648 		scr_val |= SCSCR_TE;
2649 	scr_val |= SCSCR_RE | (s->cfg->scscr & ~(SCSCR_CKE1 | SCSCR_CKE0));
2650 	serial_port_out(port, SCSCR, scr_val | s->hscif_tot);
2651 	if ((srr + 1 == 5) &&
2652 	    (port->type == PORT_SCIFA || port->type == PORT_SCIFB)) {
2653 		/*
2654 		 * In asynchronous mode, when the sampling rate is 1/5, first
2655 		 * received data may become invalid on some SCIFA and SCIFB.
2656 		 * To avoid this problem wait more than 1 serial data time (1
2657 		 * bit time x serial data number) after setting SCSCR.RE = 1.
2658 		 */
2659 		udelay(DIV_ROUND_UP(10 * 1000000, baud));
2660 	}
2661 
2662 	/* Calculate delay for 2 DMA buffers (4 FIFO). */
2663 	s->rx_frame = (10000 * bits) / (baud / 100);
2664 #ifdef CONFIG_SERIAL_SH_SCI_DMA
2665 	s->rx_timeout = s->buf_len_rx * 2 * s->rx_frame;
2666 #endif
2667 
2668 	if ((termios->c_cflag & CREAD) != 0)
2669 		sci_start_rx(port);
2670 
2671 	spin_unlock_irqrestore(&port->lock, flags);
2672 
2673 	sci_port_disable(s);
2674 
2675 	if (UART_ENABLE_MS(port, termios->c_cflag))
2676 		sci_enable_ms(port);
2677 }
2678 
2679 static void sci_pm(struct uart_port *port, unsigned int state,
2680 		   unsigned int oldstate)
2681 {
2682 	struct sci_port *sci_port = to_sci_port(port);
2683 
2684 	switch (state) {
2685 	case UART_PM_STATE_OFF:
2686 		sci_port_disable(sci_port);
2687 		break;
2688 	default:
2689 		sci_port_enable(sci_port);
2690 		break;
2691 	}
2692 }
2693 
2694 static const char *sci_type(struct uart_port *port)
2695 {
2696 	switch (port->type) {
2697 	case PORT_IRDA:
2698 		return "irda";
2699 	case PORT_SCI:
2700 		return "sci";
2701 	case PORT_SCIF:
2702 		return "scif";
2703 	case PORT_SCIFA:
2704 		return "scifa";
2705 	case PORT_SCIFB:
2706 		return "scifb";
2707 	case PORT_HSCIF:
2708 		return "hscif";
2709 	}
2710 
2711 	return NULL;
2712 }
2713 
2714 static int sci_remap_port(struct uart_port *port)
2715 {
2716 	struct sci_port *sport = to_sci_port(port);
2717 
2718 	/*
2719 	 * Nothing to do if there's already an established membase.
2720 	 */
2721 	if (port->membase)
2722 		return 0;
2723 
2724 	if (port->dev->of_node || (port->flags & UPF_IOREMAP)) {
2725 		port->membase = ioremap(port->mapbase, sport->reg_size);
2726 		if (unlikely(!port->membase)) {
2727 			dev_err(port->dev, "can't remap port#%d\n", port->line);
2728 			return -ENXIO;
2729 		}
2730 	} else {
2731 		/*
2732 		 * For the simple (and majority of) cases where we don't
2733 		 * need to do any remapping, just cast the cookie
2734 		 * directly.
2735 		 */
2736 		port->membase = (void __iomem *)(uintptr_t)port->mapbase;
2737 	}
2738 
2739 	return 0;
2740 }
2741 
2742 static void sci_release_port(struct uart_port *port)
2743 {
2744 	struct sci_port *sport = to_sci_port(port);
2745 
2746 	if (port->dev->of_node || (port->flags & UPF_IOREMAP)) {
2747 		iounmap(port->membase);
2748 		port->membase = NULL;
2749 	}
2750 
2751 	release_mem_region(port->mapbase, sport->reg_size);
2752 }
2753 
2754 static int sci_request_port(struct uart_port *port)
2755 {
2756 	struct resource *res;
2757 	struct sci_port *sport = to_sci_port(port);
2758 	int ret;
2759 
2760 	res = request_mem_region(port->mapbase, sport->reg_size,
2761 				 dev_name(port->dev));
2762 	if (unlikely(res == NULL)) {
2763 		dev_err(port->dev, "request_mem_region failed.");
2764 		return -EBUSY;
2765 	}
2766 
2767 	ret = sci_remap_port(port);
2768 	if (unlikely(ret != 0)) {
2769 		release_resource(res);
2770 		return ret;
2771 	}
2772 
2773 	return 0;
2774 }
2775 
2776 static void sci_config_port(struct uart_port *port, int flags)
2777 {
2778 	if (flags & UART_CONFIG_TYPE) {
2779 		struct sci_port *sport = to_sci_port(port);
2780 
2781 		port->type = sport->cfg->type;
2782 		sci_request_port(port);
2783 	}
2784 }
2785 
2786 static int sci_verify_port(struct uart_port *port, struct serial_struct *ser)
2787 {
2788 	if (ser->baud_base < 2400)
2789 		/* No paper tape reader for Mitch.. */
2790 		return -EINVAL;
2791 
2792 	return 0;
2793 }
2794 
2795 static const struct uart_ops sci_uart_ops = {
2796 	.tx_empty	= sci_tx_empty,
2797 	.set_mctrl	= sci_set_mctrl,
2798 	.get_mctrl	= sci_get_mctrl,
2799 	.start_tx	= sci_start_tx,
2800 	.stop_tx	= sci_stop_tx,
2801 	.stop_rx	= sci_stop_rx,
2802 	.enable_ms	= sci_enable_ms,
2803 	.break_ctl	= sci_break_ctl,
2804 	.startup	= sci_startup,
2805 	.shutdown	= sci_shutdown,
2806 	.flush_buffer	= sci_flush_buffer,
2807 	.set_termios	= sci_set_termios,
2808 	.pm		= sci_pm,
2809 	.type		= sci_type,
2810 	.release_port	= sci_release_port,
2811 	.request_port	= sci_request_port,
2812 	.config_port	= sci_config_port,
2813 	.verify_port	= sci_verify_port,
2814 #ifdef CONFIG_CONSOLE_POLL
2815 	.poll_get_char	= sci_poll_get_char,
2816 	.poll_put_char	= sci_poll_put_char,
2817 #endif
2818 };
2819 
2820 static int sci_init_clocks(struct sci_port *sci_port, struct device *dev)
2821 {
2822 	const char *clk_names[] = {
2823 		[SCI_FCK] = "fck",
2824 		[SCI_SCK] = "sck",
2825 		[SCI_BRG_INT] = "brg_int",
2826 		[SCI_SCIF_CLK] = "scif_clk",
2827 	};
2828 	struct clk *clk;
2829 	unsigned int i;
2830 
2831 	if (sci_port->cfg->type == PORT_HSCIF)
2832 		clk_names[SCI_SCK] = "hsck";
2833 
2834 	for (i = 0; i < SCI_NUM_CLKS; i++) {
2835 		clk = devm_clk_get_optional(dev, clk_names[i]);
2836 		if (IS_ERR(clk))
2837 			return PTR_ERR(clk);
2838 
2839 		if (!clk && i == SCI_FCK) {
2840 			/*
2841 			 * Not all SH platforms declare a clock lookup entry
2842 			 * for SCI devices, in which case we need to get the
2843 			 * global "peripheral_clk" clock.
2844 			 */
2845 			clk = devm_clk_get(dev, "peripheral_clk");
2846 			if (IS_ERR(clk))
2847 				return dev_err_probe(dev, PTR_ERR(clk),
2848 						     "failed to get %s\n",
2849 						     clk_names[i]);
2850 		}
2851 
2852 		if (!clk)
2853 			dev_dbg(dev, "failed to get %s\n", clk_names[i]);
2854 		else
2855 			dev_dbg(dev, "clk %s is %pC rate %lu\n", clk_names[i],
2856 				clk, clk_get_rate(clk));
2857 		sci_port->clks[i] = clk;
2858 	}
2859 	return 0;
2860 }
2861 
2862 static const struct sci_port_params *
2863 sci_probe_regmap(const struct plat_sci_port *cfg)
2864 {
2865 	unsigned int regtype;
2866 
2867 	if (cfg->regtype != SCIx_PROBE_REGTYPE)
2868 		return &sci_port_params[cfg->regtype];
2869 
2870 	switch (cfg->type) {
2871 	case PORT_SCI:
2872 		regtype = SCIx_SCI_REGTYPE;
2873 		break;
2874 	case PORT_IRDA:
2875 		regtype = SCIx_IRDA_REGTYPE;
2876 		break;
2877 	case PORT_SCIFA:
2878 		regtype = SCIx_SCIFA_REGTYPE;
2879 		break;
2880 	case PORT_SCIFB:
2881 		regtype = SCIx_SCIFB_REGTYPE;
2882 		break;
2883 	case PORT_SCIF:
2884 		/*
2885 		 * The SH-4 is a bit of a misnomer here, although that's
2886 		 * where this particular port layout originated. This
2887 		 * configuration (or some slight variation thereof)
2888 		 * remains the dominant model for all SCIFs.
2889 		 */
2890 		regtype = SCIx_SH4_SCIF_REGTYPE;
2891 		break;
2892 	case PORT_HSCIF:
2893 		regtype = SCIx_HSCIF_REGTYPE;
2894 		break;
2895 	default:
2896 		pr_err("Can't probe register map for given port\n");
2897 		return NULL;
2898 	}
2899 
2900 	return &sci_port_params[regtype];
2901 }
2902 
2903 static int sci_init_single(struct platform_device *dev,
2904 			   struct sci_port *sci_port, unsigned int index,
2905 			   const struct plat_sci_port *p, bool early)
2906 {
2907 	struct uart_port *port = &sci_port->port;
2908 	const struct resource *res;
2909 	unsigned int i;
2910 	int ret;
2911 
2912 	sci_port->cfg	= p;
2913 
2914 	port->ops	= &sci_uart_ops;
2915 	port->iotype	= UPIO_MEM;
2916 	port->line	= index;
2917 	port->has_sysrq = IS_ENABLED(CONFIG_SERIAL_SH_SCI_CONSOLE);
2918 
2919 	res = platform_get_resource(dev, IORESOURCE_MEM, 0);
2920 	if (res == NULL)
2921 		return -ENOMEM;
2922 
2923 	port->mapbase = res->start;
2924 	sci_port->reg_size = resource_size(res);
2925 
2926 	for (i = 0; i < ARRAY_SIZE(sci_port->irqs); ++i) {
2927 		if (i)
2928 			sci_port->irqs[i] = platform_get_irq_optional(dev, i);
2929 		else
2930 			sci_port->irqs[i] = platform_get_irq(dev, i);
2931 	}
2932 
2933 	/*
2934 	 * The fourth interrupt on SCI port is transmit end interrupt, so
2935 	 * shuffle the interrupts.
2936 	 */
2937 	if (p->type == PORT_SCI)
2938 		swap(sci_port->irqs[SCIx_BRI_IRQ], sci_port->irqs[SCIx_TEI_IRQ]);
2939 
2940 	/* The SCI generates several interrupts. They can be muxed together or
2941 	 * connected to different interrupt lines. In the muxed case only one
2942 	 * interrupt resource is specified as there is only one interrupt ID.
2943 	 * In the non-muxed case, up to 6 interrupt signals might be generated
2944 	 * from the SCI, however those signals might have their own individual
2945 	 * interrupt ID numbers, or muxed together with another interrupt.
2946 	 */
2947 	if (sci_port->irqs[0] < 0)
2948 		return -ENXIO;
2949 
2950 	if (sci_port->irqs[1] < 0)
2951 		for (i = 1; i < ARRAY_SIZE(sci_port->irqs); i++)
2952 			sci_port->irqs[i] = sci_port->irqs[0];
2953 
2954 	sci_port->params = sci_probe_regmap(p);
2955 	if (unlikely(sci_port->params == NULL))
2956 		return -EINVAL;
2957 
2958 	switch (p->type) {
2959 	case PORT_SCIFB:
2960 		sci_port->rx_trigger = 48;
2961 		break;
2962 	case PORT_HSCIF:
2963 		sci_port->rx_trigger = 64;
2964 		break;
2965 	case PORT_SCIFA:
2966 		sci_port->rx_trigger = 32;
2967 		break;
2968 	case PORT_SCIF:
2969 		if (p->regtype == SCIx_SH7705_SCIF_REGTYPE)
2970 			/* RX triggering not implemented for this IP */
2971 			sci_port->rx_trigger = 1;
2972 		else
2973 			sci_port->rx_trigger = 8;
2974 		break;
2975 	default:
2976 		sci_port->rx_trigger = 1;
2977 		break;
2978 	}
2979 
2980 	sci_port->rx_fifo_timeout = 0;
2981 	sci_port->hscif_tot = 0;
2982 
2983 	/* SCIFA on sh7723 and sh7724 need a custom sampling rate that doesn't
2984 	 * match the SoC datasheet, this should be investigated. Let platform
2985 	 * data override the sampling rate for now.
2986 	 */
2987 	sci_port->sampling_rate_mask = p->sampling_rate
2988 				     ? SCI_SR(p->sampling_rate)
2989 				     : sci_port->params->sampling_rate_mask;
2990 
2991 	if (!early) {
2992 		ret = sci_init_clocks(sci_port, &dev->dev);
2993 		if (ret < 0)
2994 			return ret;
2995 
2996 		port->dev = &dev->dev;
2997 
2998 		pm_runtime_enable(&dev->dev);
2999 	}
3000 
3001 	port->type		= p->type;
3002 	port->flags		= UPF_FIXED_PORT | UPF_BOOT_AUTOCONF | p->flags;
3003 	port->fifosize		= sci_port->params->fifosize;
3004 
3005 	if (port->type == PORT_SCI && !dev->dev.of_node) {
3006 		if (sci_port->reg_size >= 0x20)
3007 			port->regshift = 2;
3008 		else
3009 			port->regshift = 1;
3010 	}
3011 
3012 	/*
3013 	 * The UART port needs an IRQ value, so we peg this to the RX IRQ
3014 	 * for the multi-IRQ ports, which is where we are primarily
3015 	 * concerned with the shutdown path synchronization.
3016 	 *
3017 	 * For the muxed case there's nothing more to do.
3018 	 */
3019 	port->irq		= sci_port->irqs[SCIx_RXI_IRQ];
3020 	port->irqflags		= 0;
3021 
3022 	port->serial_in		= sci_serial_in;
3023 	port->serial_out	= sci_serial_out;
3024 
3025 	return 0;
3026 }
3027 
3028 static void sci_cleanup_single(struct sci_port *port)
3029 {
3030 	pm_runtime_disable(port->port.dev);
3031 }
3032 
3033 #if defined(CONFIG_SERIAL_SH_SCI_CONSOLE) || \
3034     defined(CONFIG_SERIAL_SH_SCI_EARLYCON)
3035 static void serial_console_putchar(struct uart_port *port, unsigned char ch)
3036 {
3037 	sci_poll_put_char(port, ch);
3038 }
3039 
3040 /*
3041  *	Print a string to the serial port trying not to disturb
3042  *	any possible real use of the port...
3043  */
3044 static void serial_console_write(struct console *co, const char *s,
3045 				 unsigned count)
3046 {
3047 	struct sci_port *sci_port = &sci_ports[co->index];
3048 	struct uart_port *port = &sci_port->port;
3049 	unsigned short bits, ctrl, ctrl_temp;
3050 	unsigned long flags;
3051 	int locked = 1;
3052 
3053 	if (port->sysrq)
3054 		locked = 0;
3055 	else if (oops_in_progress)
3056 		locked = spin_trylock_irqsave(&port->lock, flags);
3057 	else
3058 		spin_lock_irqsave(&port->lock, flags);
3059 
3060 	/* first save SCSCR then disable interrupts, keep clock source */
3061 	ctrl = serial_port_in(port, SCSCR);
3062 	ctrl_temp = SCSCR_RE | SCSCR_TE |
3063 		    (sci_port->cfg->scscr & ~(SCSCR_CKE1 | SCSCR_CKE0)) |
3064 		    (ctrl & (SCSCR_CKE1 | SCSCR_CKE0));
3065 	serial_port_out(port, SCSCR, ctrl_temp | sci_port->hscif_tot);
3066 
3067 	uart_console_write(port, s, count, serial_console_putchar);
3068 
3069 	/* wait until fifo is empty and last bit has been transmitted */
3070 	bits = SCxSR_TDxE(port) | SCxSR_TEND(port);
3071 	while ((serial_port_in(port, SCxSR) & bits) != bits)
3072 		cpu_relax();
3073 
3074 	/* restore the SCSCR */
3075 	serial_port_out(port, SCSCR, ctrl);
3076 
3077 	if (locked)
3078 		spin_unlock_irqrestore(&port->lock, flags);
3079 }
3080 
3081 static int serial_console_setup(struct console *co, char *options)
3082 {
3083 	struct sci_port *sci_port;
3084 	struct uart_port *port;
3085 	int baud = 115200;
3086 	int bits = 8;
3087 	int parity = 'n';
3088 	int flow = 'n';
3089 	int ret;
3090 
3091 	/*
3092 	 * Refuse to handle any bogus ports.
3093 	 */
3094 	if (co->index < 0 || co->index >= SCI_NPORTS)
3095 		return -ENODEV;
3096 
3097 	sci_port = &sci_ports[co->index];
3098 	port = &sci_port->port;
3099 
3100 	/*
3101 	 * Refuse to handle uninitialized ports.
3102 	 */
3103 	if (!port->ops)
3104 		return -ENODEV;
3105 
3106 	ret = sci_remap_port(port);
3107 	if (unlikely(ret != 0))
3108 		return ret;
3109 
3110 	if (options)
3111 		uart_parse_options(options, &baud, &parity, &bits, &flow);
3112 
3113 	return uart_set_options(port, co, baud, parity, bits, flow);
3114 }
3115 
3116 static struct console serial_console = {
3117 	.name		= "ttySC",
3118 	.device		= uart_console_device,
3119 	.write		= serial_console_write,
3120 	.setup		= serial_console_setup,
3121 	.flags		= CON_PRINTBUFFER,
3122 	.index		= -1,
3123 	.data		= &sci_uart_driver,
3124 };
3125 
3126 #ifdef CONFIG_SUPERH
3127 static char early_serial_buf[32];
3128 
3129 static int early_serial_console_setup(struct console *co, char *options)
3130 {
3131 	/*
3132 	 * This early console is always registered using the earlyprintk=
3133 	 * parameter, which does not call add_preferred_console(). Thus
3134 	 * @options is always NULL and the options for this early console
3135 	 * are passed using a custom buffer.
3136 	 */
3137 	WARN_ON(options);
3138 
3139 	return serial_console_setup(co, early_serial_buf);
3140 }
3141 
3142 static struct console early_serial_console = {
3143 	.name           = "early_ttySC",
3144 	.write          = serial_console_write,
3145 	.setup		= early_serial_console_setup,
3146 	.flags          = CON_PRINTBUFFER,
3147 	.index		= -1,
3148 };
3149 
3150 static int sci_probe_earlyprintk(struct platform_device *pdev)
3151 {
3152 	const struct plat_sci_port *cfg = dev_get_platdata(&pdev->dev);
3153 
3154 	if (early_serial_console.data)
3155 		return -EEXIST;
3156 
3157 	early_serial_console.index = pdev->id;
3158 
3159 	sci_init_single(pdev, &sci_ports[pdev->id], pdev->id, cfg, true);
3160 
3161 	if (!strstr(early_serial_buf, "keep"))
3162 		early_serial_console.flags |= CON_BOOT;
3163 
3164 	register_console(&early_serial_console);
3165 	return 0;
3166 }
3167 #endif
3168 
3169 #define SCI_CONSOLE	(&serial_console)
3170 
3171 #else
3172 static inline int sci_probe_earlyprintk(struct platform_device *pdev)
3173 {
3174 	return -EINVAL;
3175 }
3176 
3177 #define SCI_CONSOLE	NULL
3178 
3179 #endif /* CONFIG_SERIAL_SH_SCI_CONSOLE || CONFIG_SERIAL_SH_SCI_EARLYCON */
3180 
3181 static const char banner[] __initconst = "SuperH (H)SCI(F) driver initialized";
3182 
3183 static DEFINE_MUTEX(sci_uart_registration_lock);
3184 static struct uart_driver sci_uart_driver = {
3185 	.owner		= THIS_MODULE,
3186 	.driver_name	= "sci",
3187 	.dev_name	= "ttySC",
3188 	.major		= SCI_MAJOR,
3189 	.minor		= SCI_MINOR_START,
3190 	.nr		= SCI_NPORTS,
3191 	.cons		= SCI_CONSOLE,
3192 };
3193 
3194 static int sci_remove(struct platform_device *dev)
3195 {
3196 	struct sci_port *port = platform_get_drvdata(dev);
3197 	unsigned int type = port->port.type;	/* uart_remove_... clears it */
3198 
3199 	sci_ports_in_use &= ~BIT(port->port.line);
3200 	uart_remove_one_port(&sci_uart_driver, &port->port);
3201 
3202 	sci_cleanup_single(port);
3203 
3204 	if (port->port.fifosize > 1)
3205 		device_remove_file(&dev->dev, &dev_attr_rx_fifo_trigger);
3206 	if (type == PORT_SCIFA || type == PORT_SCIFB || type == PORT_HSCIF)
3207 		device_remove_file(&dev->dev, &dev_attr_rx_fifo_timeout);
3208 
3209 	return 0;
3210 }
3211 
3212 
3213 #define SCI_OF_DATA(type, regtype)	(void *)((type) << 16 | (regtype))
3214 #define SCI_OF_TYPE(data)		((unsigned long)(data) >> 16)
3215 #define SCI_OF_REGTYPE(data)		((unsigned long)(data) & 0xffff)
3216 
3217 static const struct of_device_id of_sci_match[] __maybe_unused = {
3218 	/* SoC-specific types */
3219 	{
3220 		.compatible = "renesas,scif-r7s72100",
3221 		.data = SCI_OF_DATA(PORT_SCIF, SCIx_SH2_SCIF_FIFODATA_REGTYPE),
3222 	},
3223 	{
3224 		.compatible = "renesas,scif-r7s9210",
3225 		.data = SCI_OF_DATA(PORT_SCIF, SCIx_RZ_SCIFA_REGTYPE),
3226 	},
3227 	{
3228 		.compatible = "renesas,scif-r9a07g044",
3229 		.data = SCI_OF_DATA(PORT_SCIF, SCIx_RZ_SCIFA_REGTYPE),
3230 	},
3231 	/* Family-specific types */
3232 	{
3233 		.compatible = "renesas,rcar-gen1-scif",
3234 		.data = SCI_OF_DATA(PORT_SCIF, SCIx_SH4_SCIF_BRG_REGTYPE),
3235 	}, {
3236 		.compatible = "renesas,rcar-gen2-scif",
3237 		.data = SCI_OF_DATA(PORT_SCIF, SCIx_SH4_SCIF_BRG_REGTYPE),
3238 	}, {
3239 		.compatible = "renesas,rcar-gen3-scif",
3240 		.data = SCI_OF_DATA(PORT_SCIF, SCIx_SH4_SCIF_BRG_REGTYPE),
3241 	}, {
3242 		.compatible = "renesas,rcar-gen4-scif",
3243 		.data = SCI_OF_DATA(PORT_SCIF, SCIx_SH4_SCIF_BRG_REGTYPE),
3244 	},
3245 	/* Generic types */
3246 	{
3247 		.compatible = "renesas,scif",
3248 		.data = SCI_OF_DATA(PORT_SCIF, SCIx_SH4_SCIF_REGTYPE),
3249 	}, {
3250 		.compatible = "renesas,scifa",
3251 		.data = SCI_OF_DATA(PORT_SCIFA, SCIx_SCIFA_REGTYPE),
3252 	}, {
3253 		.compatible = "renesas,scifb",
3254 		.data = SCI_OF_DATA(PORT_SCIFB, SCIx_SCIFB_REGTYPE),
3255 	}, {
3256 		.compatible = "renesas,hscif",
3257 		.data = SCI_OF_DATA(PORT_HSCIF, SCIx_HSCIF_REGTYPE),
3258 	}, {
3259 		.compatible = "renesas,sci",
3260 		.data = SCI_OF_DATA(PORT_SCI, SCIx_SCI_REGTYPE),
3261 	}, {
3262 		/* Terminator */
3263 	},
3264 };
3265 MODULE_DEVICE_TABLE(of, of_sci_match);
3266 
3267 static void sci_reset_control_assert(void *data)
3268 {
3269 	reset_control_assert(data);
3270 }
3271 
3272 static struct plat_sci_port *sci_parse_dt(struct platform_device *pdev,
3273 					  unsigned int *dev_id)
3274 {
3275 	struct device_node *np = pdev->dev.of_node;
3276 	struct reset_control *rstc;
3277 	struct plat_sci_port *p;
3278 	struct sci_port *sp;
3279 	const void *data;
3280 	int id, ret;
3281 
3282 	if (!IS_ENABLED(CONFIG_OF) || !np)
3283 		return ERR_PTR(-EINVAL);
3284 
3285 	data = of_device_get_match_data(&pdev->dev);
3286 
3287 	rstc = devm_reset_control_get_optional_exclusive(&pdev->dev, NULL);
3288 	if (IS_ERR(rstc))
3289 		return ERR_PTR(dev_err_probe(&pdev->dev, PTR_ERR(rstc),
3290 					     "failed to get reset ctrl\n"));
3291 
3292 	ret = reset_control_deassert(rstc);
3293 	if (ret) {
3294 		dev_err(&pdev->dev, "failed to deassert reset %d\n", ret);
3295 		return ERR_PTR(ret);
3296 	}
3297 
3298 	ret = devm_add_action_or_reset(&pdev->dev, sci_reset_control_assert, rstc);
3299 	if (ret) {
3300 		dev_err(&pdev->dev, "failed to register assert devm action, %d\n",
3301 			ret);
3302 		return ERR_PTR(ret);
3303 	}
3304 
3305 	p = devm_kzalloc(&pdev->dev, sizeof(struct plat_sci_port), GFP_KERNEL);
3306 	if (!p)
3307 		return ERR_PTR(-ENOMEM);
3308 
3309 	/* Get the line number from the aliases node. */
3310 	id = of_alias_get_id(np, "serial");
3311 	if (id < 0 && ~sci_ports_in_use)
3312 		id = ffz(sci_ports_in_use);
3313 	if (id < 0) {
3314 		dev_err(&pdev->dev, "failed to get alias id (%d)\n", id);
3315 		return ERR_PTR(-EINVAL);
3316 	}
3317 	if (id >= ARRAY_SIZE(sci_ports)) {
3318 		dev_err(&pdev->dev, "serial%d out of range\n", id);
3319 		return ERR_PTR(-EINVAL);
3320 	}
3321 
3322 	sp = &sci_ports[id];
3323 	*dev_id = id;
3324 
3325 	p->type = SCI_OF_TYPE(data);
3326 	p->regtype = SCI_OF_REGTYPE(data);
3327 
3328 	sp->has_rtscts = of_property_read_bool(np, "uart-has-rtscts");
3329 
3330 	return p;
3331 }
3332 
3333 static int sci_probe_single(struct platform_device *dev,
3334 				      unsigned int index,
3335 				      struct plat_sci_port *p,
3336 				      struct sci_port *sciport)
3337 {
3338 	int ret;
3339 
3340 	/* Sanity check */
3341 	if (unlikely(index >= SCI_NPORTS)) {
3342 		dev_notice(&dev->dev, "Attempting to register port %d when only %d are available\n",
3343 			   index+1, SCI_NPORTS);
3344 		dev_notice(&dev->dev, "Consider bumping CONFIG_SERIAL_SH_SCI_NR_UARTS!\n");
3345 		return -EINVAL;
3346 	}
3347 	BUILD_BUG_ON(SCI_NPORTS > sizeof(sci_ports_in_use) * 8);
3348 	if (sci_ports_in_use & BIT(index))
3349 		return -EBUSY;
3350 
3351 	mutex_lock(&sci_uart_registration_lock);
3352 	if (!sci_uart_driver.state) {
3353 		ret = uart_register_driver(&sci_uart_driver);
3354 		if (ret) {
3355 			mutex_unlock(&sci_uart_registration_lock);
3356 			return ret;
3357 		}
3358 	}
3359 	mutex_unlock(&sci_uart_registration_lock);
3360 
3361 	ret = sci_init_single(dev, sciport, index, p, false);
3362 	if (ret)
3363 		return ret;
3364 
3365 	sciport->gpios = mctrl_gpio_init(&sciport->port, 0);
3366 	if (IS_ERR(sciport->gpios))
3367 		return PTR_ERR(sciport->gpios);
3368 
3369 	if (sciport->has_rtscts) {
3370 		if (mctrl_gpio_to_gpiod(sciport->gpios, UART_GPIO_CTS) ||
3371 		    mctrl_gpio_to_gpiod(sciport->gpios, UART_GPIO_RTS)) {
3372 			dev_err(&dev->dev, "Conflicting RTS/CTS config\n");
3373 			return -EINVAL;
3374 		}
3375 		sciport->port.flags |= UPF_HARD_FLOW;
3376 	}
3377 
3378 	ret = uart_add_one_port(&sci_uart_driver, &sciport->port);
3379 	if (ret) {
3380 		sci_cleanup_single(sciport);
3381 		return ret;
3382 	}
3383 
3384 	return 0;
3385 }
3386 
3387 static int sci_probe(struct platform_device *dev)
3388 {
3389 	struct plat_sci_port *p;
3390 	struct sci_port *sp;
3391 	unsigned int dev_id;
3392 	int ret;
3393 
3394 	/*
3395 	 * If we've come here via earlyprintk initialization, head off to
3396 	 * the special early probe. We don't have sufficient device state
3397 	 * to make it beyond this yet.
3398 	 */
3399 #ifdef CONFIG_SUPERH
3400 	if (is_sh_early_platform_device(dev))
3401 		return sci_probe_earlyprintk(dev);
3402 #endif
3403 
3404 	if (dev->dev.of_node) {
3405 		p = sci_parse_dt(dev, &dev_id);
3406 		if (IS_ERR(p))
3407 			return PTR_ERR(p);
3408 	} else {
3409 		p = dev->dev.platform_data;
3410 		if (p == NULL) {
3411 			dev_err(&dev->dev, "no platform data supplied\n");
3412 			return -EINVAL;
3413 		}
3414 
3415 		dev_id = dev->id;
3416 	}
3417 
3418 	sp = &sci_ports[dev_id];
3419 	platform_set_drvdata(dev, sp);
3420 
3421 	ret = sci_probe_single(dev, dev_id, p, sp);
3422 	if (ret)
3423 		return ret;
3424 
3425 	if (sp->port.fifosize > 1) {
3426 		ret = device_create_file(&dev->dev, &dev_attr_rx_fifo_trigger);
3427 		if (ret)
3428 			return ret;
3429 	}
3430 	if (sp->port.type == PORT_SCIFA || sp->port.type == PORT_SCIFB ||
3431 	    sp->port.type == PORT_HSCIF) {
3432 		ret = device_create_file(&dev->dev, &dev_attr_rx_fifo_timeout);
3433 		if (ret) {
3434 			if (sp->port.fifosize > 1) {
3435 				device_remove_file(&dev->dev,
3436 						   &dev_attr_rx_fifo_trigger);
3437 			}
3438 			return ret;
3439 		}
3440 	}
3441 
3442 #ifdef CONFIG_SH_STANDARD_BIOS
3443 	sh_bios_gdb_detach();
3444 #endif
3445 
3446 	sci_ports_in_use |= BIT(dev_id);
3447 	return 0;
3448 }
3449 
3450 static __maybe_unused int sci_suspend(struct device *dev)
3451 {
3452 	struct sci_port *sport = dev_get_drvdata(dev);
3453 
3454 	if (sport)
3455 		uart_suspend_port(&sci_uart_driver, &sport->port);
3456 
3457 	return 0;
3458 }
3459 
3460 static __maybe_unused int sci_resume(struct device *dev)
3461 {
3462 	struct sci_port *sport = dev_get_drvdata(dev);
3463 
3464 	if (sport)
3465 		uart_resume_port(&sci_uart_driver, &sport->port);
3466 
3467 	return 0;
3468 }
3469 
3470 static SIMPLE_DEV_PM_OPS(sci_dev_pm_ops, sci_suspend, sci_resume);
3471 
3472 static struct platform_driver sci_driver = {
3473 	.probe		= sci_probe,
3474 	.remove		= sci_remove,
3475 	.driver		= {
3476 		.name	= "sh-sci",
3477 		.pm	= &sci_dev_pm_ops,
3478 		.of_match_table = of_match_ptr(of_sci_match),
3479 	},
3480 };
3481 
3482 static int __init sci_init(void)
3483 {
3484 	pr_info("%s\n", banner);
3485 
3486 	return platform_driver_register(&sci_driver);
3487 }
3488 
3489 static void __exit sci_exit(void)
3490 {
3491 	platform_driver_unregister(&sci_driver);
3492 
3493 	if (sci_uart_driver.state)
3494 		uart_unregister_driver(&sci_uart_driver);
3495 }
3496 
3497 #if defined(CONFIG_SUPERH) && defined(CONFIG_SERIAL_SH_SCI_CONSOLE)
3498 sh_early_platform_init_buffer("earlyprintk", &sci_driver,
3499 			   early_serial_buf, ARRAY_SIZE(early_serial_buf));
3500 #endif
3501 #ifdef CONFIG_SERIAL_SH_SCI_EARLYCON
3502 static struct plat_sci_port port_cfg __initdata;
3503 
3504 static int __init early_console_setup(struct earlycon_device *device,
3505 				      int type)
3506 {
3507 	if (!device->port.membase)
3508 		return -ENODEV;
3509 
3510 	device->port.serial_in = sci_serial_in;
3511 	device->port.serial_out	= sci_serial_out;
3512 	device->port.type = type;
3513 	memcpy(&sci_ports[0].port, &device->port, sizeof(struct uart_port));
3514 	port_cfg.type = type;
3515 	sci_ports[0].cfg = &port_cfg;
3516 	sci_ports[0].params = sci_probe_regmap(&port_cfg);
3517 	port_cfg.scscr = sci_serial_in(&sci_ports[0].port, SCSCR);
3518 	sci_serial_out(&sci_ports[0].port, SCSCR,
3519 		       SCSCR_RE | SCSCR_TE | port_cfg.scscr);
3520 
3521 	device->con->write = serial_console_write;
3522 	return 0;
3523 }
3524 static int __init sci_early_console_setup(struct earlycon_device *device,
3525 					  const char *opt)
3526 {
3527 	return early_console_setup(device, PORT_SCI);
3528 }
3529 static int __init scif_early_console_setup(struct earlycon_device *device,
3530 					  const char *opt)
3531 {
3532 	return early_console_setup(device, PORT_SCIF);
3533 }
3534 static int __init rzscifa_early_console_setup(struct earlycon_device *device,
3535 					  const char *opt)
3536 {
3537 	port_cfg.regtype = SCIx_RZ_SCIFA_REGTYPE;
3538 	return early_console_setup(device, PORT_SCIF);
3539 }
3540 
3541 static int __init scifa_early_console_setup(struct earlycon_device *device,
3542 					  const char *opt)
3543 {
3544 	return early_console_setup(device, PORT_SCIFA);
3545 }
3546 static int __init scifb_early_console_setup(struct earlycon_device *device,
3547 					  const char *opt)
3548 {
3549 	return early_console_setup(device, PORT_SCIFB);
3550 }
3551 static int __init hscif_early_console_setup(struct earlycon_device *device,
3552 					  const char *opt)
3553 {
3554 	return early_console_setup(device, PORT_HSCIF);
3555 }
3556 
3557 OF_EARLYCON_DECLARE(sci, "renesas,sci", sci_early_console_setup);
3558 OF_EARLYCON_DECLARE(scif, "renesas,scif", scif_early_console_setup);
3559 OF_EARLYCON_DECLARE(scif, "renesas,scif-r7s9210", rzscifa_early_console_setup);
3560 OF_EARLYCON_DECLARE(scif, "renesas,scif-r9a07g044", rzscifa_early_console_setup);
3561 OF_EARLYCON_DECLARE(scifa, "renesas,scifa", scifa_early_console_setup);
3562 OF_EARLYCON_DECLARE(scifb, "renesas,scifb", scifb_early_console_setup);
3563 OF_EARLYCON_DECLARE(hscif, "renesas,hscif", hscif_early_console_setup);
3564 #endif /* CONFIG_SERIAL_SH_SCI_EARLYCON */
3565 
3566 module_init(sci_init);
3567 module_exit(sci_exit);
3568 
3569 MODULE_LICENSE("GPL");
3570 MODULE_ALIAS("platform:sh-sci");
3571 MODULE_AUTHOR("Paul Mundt");
3572 MODULE_DESCRIPTION("SuperH (H)SCI(F) serial driver");
3573