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