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