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