tty/serial: atmel: Add is_half_duplex helper
[linux-2.6-block.git] / drivers / tty / serial / atmel_serial.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *  Driver for Atmel AT91 Serial ports
4  *  Copyright (C) 2003 Rick Bronson
5  *
6  *  Based on drivers/char/serial_sa1100.c, by Deep Blue Solutions Ltd.
7  *  Based on drivers/char/serial.c, by Linus Torvalds, Theodore Ts'o.
8  *
9  *  DMA support added by Chip Coldwell.
10  */
11 #include <linux/tty.h>
12 #include <linux/ioport.h>
13 #include <linux/slab.h>
14 #include <linux/init.h>
15 #include <linux/serial.h>
16 #include <linux/clk.h>
17 #include <linux/console.h>
18 #include <linux/sysrq.h>
19 #include <linux/tty_flip.h>
20 #include <linux/platform_device.h>
21 #include <linux/of.h>
22 #include <linux/of_device.h>
23 #include <linux/of_gpio.h>
24 #include <linux/dma-mapping.h>
25 #include <linux/dmaengine.h>
26 #include <linux/atmel_pdc.h>
27 #include <linux/uaccess.h>
28 #include <linux/platform_data/atmel.h>
29 #include <linux/timer.h>
30 #include <linux/gpio.h>
31 #include <linux/gpio/consumer.h>
32 #include <linux/err.h>
33 #include <linux/irq.h>
34 #include <linux/suspend.h>
35 #include <linux/mm.h>
36
37 #include <asm/div64.h>
38 #include <asm/io.h>
39 #include <asm/ioctls.h>
40
41 #define PDC_BUFFER_SIZE         512
42 /* Revisit: We should calculate this based on the actual port settings */
43 #define PDC_RX_TIMEOUT          (3 * 10)                /* 3 bytes */
44
45 /* The minium number of data FIFOs should be able to contain */
46 #define ATMEL_MIN_FIFO_SIZE     8
47 /*
48  * These two offsets are substracted from the RX FIFO size to define the RTS
49  * high and low thresholds
50  */
51 #define ATMEL_RTS_HIGH_OFFSET   16
52 #define ATMEL_RTS_LOW_OFFSET    20
53
54 #if defined(CONFIG_SERIAL_ATMEL_CONSOLE) && defined(CONFIG_MAGIC_SYSRQ)
55 #define SUPPORT_SYSRQ
56 #endif
57
58 #include <linux/serial_core.h>
59
60 #include "serial_mctrl_gpio.h"
61 #include "atmel_serial.h"
62
63 static void atmel_start_rx(struct uart_port *port);
64 static void atmel_stop_rx(struct uart_port *port);
65
66 #ifdef CONFIG_SERIAL_ATMEL_TTYAT
67
68 /* Use device name ttyAT, major 204 and minor 154-169.  This is necessary if we
69  * should coexist with the 8250 driver, such as if we have an external 16C550
70  * UART. */
71 #define SERIAL_ATMEL_MAJOR      204
72 #define MINOR_START             154
73 #define ATMEL_DEVICENAME        "ttyAT"
74
75 #else
76
77 /* Use device name ttyS, major 4, minor 64-68.  This is the usual serial port
78  * name, but it is legally reserved for the 8250 driver. */
79 #define SERIAL_ATMEL_MAJOR      TTY_MAJOR
80 #define MINOR_START             64
81 #define ATMEL_DEVICENAME        "ttyS"
82
83 #endif
84
85 #define ATMEL_ISR_PASS_LIMIT    256
86
87 struct atmel_dma_buffer {
88         unsigned char   *buf;
89         dma_addr_t      dma_addr;
90         unsigned int    dma_size;
91         unsigned int    ofs;
92 };
93
94 struct atmel_uart_char {
95         u16             status;
96         u16             ch;
97 };
98
99 /*
100  * Be careful, the real size of the ring buffer is
101  * sizeof(atmel_uart_char) * ATMEL_SERIAL_RINGSIZE. It means that ring buffer
102  * can contain up to 1024 characters in PIO mode and up to 4096 characters in
103  * DMA mode.
104  */
105 #define ATMEL_SERIAL_RINGSIZE 1024
106
107 /*
108  * at91: 6 USARTs and one DBGU port (SAM9260)
109  * samx7: 3 USARTs and 5 UARTs
110  */
111 #define ATMEL_MAX_UART          8
112
113 /*
114  * We wrap our port structure around the generic uart_port.
115  */
116 struct atmel_uart_port {
117         struct uart_port        uart;           /* uart */
118         struct clk              *clk;           /* uart clock */
119         int                     may_wakeup;     /* cached value of device_may_wakeup for times we need to disable it */
120         u32                     backup_imr;     /* IMR saved during suspend */
121         int                     break_active;   /* break being received */
122
123         bool                    use_dma_rx;     /* enable DMA receiver */
124         bool                    use_pdc_rx;     /* enable PDC receiver */
125         short                   pdc_rx_idx;     /* current PDC RX buffer */
126         struct atmel_dma_buffer pdc_rx[2];      /* PDC receier */
127
128         bool                    use_dma_tx;     /* enable DMA transmitter */
129         bool                    use_pdc_tx;     /* enable PDC transmitter */
130         struct atmel_dma_buffer pdc_tx;         /* PDC transmitter */
131
132         spinlock_t                      lock_tx;        /* port lock */
133         spinlock_t                      lock_rx;        /* port lock */
134         struct dma_chan                 *chan_tx;
135         struct dma_chan                 *chan_rx;
136         struct dma_async_tx_descriptor  *desc_tx;
137         struct dma_async_tx_descriptor  *desc_rx;
138         dma_cookie_t                    cookie_tx;
139         dma_cookie_t                    cookie_rx;
140         struct scatterlist              sg_tx;
141         struct scatterlist              sg_rx;
142         struct tasklet_struct   tasklet_rx;
143         struct tasklet_struct   tasklet_tx;
144         atomic_t                tasklet_shutdown;
145         unsigned int            irq_status_prev;
146         unsigned int            tx_len;
147
148         struct circ_buf         rx_ring;
149
150         struct mctrl_gpios      *gpios;
151         u32                     backup_mode;    /* MR saved during iso7816 operations */
152         u32                     backup_brgr;    /* BRGR saved during iso7816 operations */
153         unsigned int            tx_done_mask;
154         u32                     fifo_size;
155         u32                     rts_high;
156         u32                     rts_low;
157         bool                    ms_irq_enabled;
158         u32                     rtor;   /* address of receiver timeout register if it exists */
159         bool                    has_frac_baudrate;
160         bool                    has_hw_timer;
161         struct timer_list       uart_timer;
162
163         bool                    tx_stopped;
164         bool                    suspended;
165         unsigned int            pending;
166         unsigned int            pending_status;
167         spinlock_t              lock_suspended;
168
169         /* ISO7816 */
170         unsigned int            fidi_min;
171         unsigned int            fidi_max;
172
173 #ifdef CONFIG_PM
174         struct {
175                 u32             cr;
176                 u32             mr;
177                 u32             imr;
178                 u32             brgr;
179                 u32             rtor;
180                 u32             ttgr;
181                 u32             fmr;
182                 u32             fimr;
183         } cache;
184 #endif
185
186         int (*prepare_rx)(struct uart_port *port);
187         int (*prepare_tx)(struct uart_port *port);
188         void (*schedule_rx)(struct uart_port *port);
189         void (*schedule_tx)(struct uart_port *port);
190         void (*release_rx)(struct uart_port *port);
191         void (*release_tx)(struct uart_port *port);
192 };
193
194 static struct atmel_uart_port atmel_ports[ATMEL_MAX_UART];
195 static DECLARE_BITMAP(atmel_ports_in_use, ATMEL_MAX_UART);
196
197 #ifdef SUPPORT_SYSRQ
198 static struct console atmel_console;
199 #endif
200
201 #if defined(CONFIG_OF)
202 static const struct of_device_id atmel_serial_dt_ids[] = {
203         { .compatible = "atmel,at91rm9200-usart-serial" },
204         { /* sentinel */ }
205 };
206 #endif
207
208 static inline struct atmel_uart_port *
209 to_atmel_uart_port(struct uart_port *uart)
210 {
211         return container_of(uart, struct atmel_uart_port, uart);
212 }
213
214 static inline u32 atmel_uart_readl(struct uart_port *port, u32 reg)
215 {
216         return __raw_readl(port->membase + reg);
217 }
218
219 static inline void atmel_uart_writel(struct uart_port *port, u32 reg, u32 value)
220 {
221         __raw_writel(value, port->membase + reg);
222 }
223
224 static inline u8 atmel_uart_read_char(struct uart_port *port)
225 {
226         return __raw_readb(port->membase + ATMEL_US_RHR);
227 }
228
229 static inline void atmel_uart_write_char(struct uart_port *port, u8 value)
230 {
231         __raw_writeb(value, port->membase + ATMEL_US_THR);
232 }
233
234 static inline int atmel_uart_is_half_duplex(struct uart_port *port)
235 {
236         return ((port->rs485.flags & SER_RS485_ENABLED) &&
237                 !(port->rs485.flags & SER_RS485_RX_DURING_TX)) ||
238                 (port->iso7816.flags & SER_ISO7816_ENABLED);
239 }
240
241 #ifdef CONFIG_SERIAL_ATMEL_PDC
242 static bool atmel_use_pdc_rx(struct uart_port *port)
243 {
244         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
245
246         return atmel_port->use_pdc_rx;
247 }
248
249 static bool atmel_use_pdc_tx(struct uart_port *port)
250 {
251         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
252
253         return atmel_port->use_pdc_tx;
254 }
255 #else
256 static bool atmel_use_pdc_rx(struct uart_port *port)
257 {
258         return false;
259 }
260
261 static bool atmel_use_pdc_tx(struct uart_port *port)
262 {
263         return false;
264 }
265 #endif
266
267 static bool atmel_use_dma_tx(struct uart_port *port)
268 {
269         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
270
271         return atmel_port->use_dma_tx;
272 }
273
274 static bool atmel_use_dma_rx(struct uart_port *port)
275 {
276         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
277
278         return atmel_port->use_dma_rx;
279 }
280
281 static bool atmel_use_fifo(struct uart_port *port)
282 {
283         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
284
285         return atmel_port->fifo_size;
286 }
287
288 static void atmel_tasklet_schedule(struct atmel_uart_port *atmel_port,
289                                    struct tasklet_struct *t)
290 {
291         if (!atomic_read(&atmel_port->tasklet_shutdown))
292                 tasklet_schedule(t);
293 }
294
295 static unsigned int atmel_get_lines_status(struct uart_port *port)
296 {
297         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
298         unsigned int status, ret = 0;
299
300         status = atmel_uart_readl(port, ATMEL_US_CSR);
301
302         mctrl_gpio_get(atmel_port->gpios, &ret);
303
304         if (!IS_ERR_OR_NULL(mctrl_gpio_to_gpiod(atmel_port->gpios,
305                                                 UART_GPIO_CTS))) {
306                 if (ret & TIOCM_CTS)
307                         status &= ~ATMEL_US_CTS;
308                 else
309                         status |= ATMEL_US_CTS;
310         }
311
312         if (!IS_ERR_OR_NULL(mctrl_gpio_to_gpiod(atmel_port->gpios,
313                                                 UART_GPIO_DSR))) {
314                 if (ret & TIOCM_DSR)
315                         status &= ~ATMEL_US_DSR;
316                 else
317                         status |= ATMEL_US_DSR;
318         }
319
320         if (!IS_ERR_OR_NULL(mctrl_gpio_to_gpiod(atmel_port->gpios,
321                                                 UART_GPIO_RI))) {
322                 if (ret & TIOCM_RI)
323                         status &= ~ATMEL_US_RI;
324                 else
325                         status |= ATMEL_US_RI;
326         }
327
328         if (!IS_ERR_OR_NULL(mctrl_gpio_to_gpiod(atmel_port->gpios,
329                                                 UART_GPIO_DCD))) {
330                 if (ret & TIOCM_CD)
331                         status &= ~ATMEL_US_DCD;
332                 else
333                         status |= ATMEL_US_DCD;
334         }
335
336         return status;
337 }
338
339 /* Enable or disable the rs485 support */
340 static int atmel_config_rs485(struct uart_port *port,
341                               struct serial_rs485 *rs485conf)
342 {
343         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
344         unsigned int mode;
345
346         /* Disable interrupts */
347         atmel_uart_writel(port, ATMEL_US_IDR, atmel_port->tx_done_mask);
348
349         mode = atmel_uart_readl(port, ATMEL_US_MR);
350
351         /* Resetting serial mode to RS232 (0x0) */
352         mode &= ~ATMEL_US_USMODE;
353
354         port->rs485 = *rs485conf;
355
356         if (rs485conf->flags & SER_RS485_ENABLED) {
357                 dev_dbg(port->dev, "Setting UART to RS485\n");
358                 atmel_port->tx_done_mask = ATMEL_US_TXEMPTY;
359                 atmel_uart_writel(port, ATMEL_US_TTGR,
360                                   rs485conf->delay_rts_after_send);
361                 mode |= ATMEL_US_USMODE_RS485;
362         } else {
363                 dev_dbg(port->dev, "Setting UART to RS232\n");
364                 if (atmel_use_pdc_tx(port))
365                         atmel_port->tx_done_mask = ATMEL_US_ENDTX |
366                                 ATMEL_US_TXBUFE;
367                 else
368                         atmel_port->tx_done_mask = ATMEL_US_TXRDY;
369         }
370         atmel_uart_writel(port, ATMEL_US_MR, mode);
371
372         /* Enable interrupts */
373         atmel_uart_writel(port, ATMEL_US_IER, atmel_port->tx_done_mask);
374
375         return 0;
376 }
377
378 static unsigned int atmel_calc_cd(struct uart_port *port,
379                                   struct serial_iso7816 *iso7816conf)
380 {
381         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
382         unsigned int cd;
383         u64 mck_rate;
384
385         mck_rate = (u64)clk_get_rate(atmel_port->clk);
386         do_div(mck_rate, iso7816conf->clk);
387         cd = mck_rate;
388         return cd;
389 }
390
391 static unsigned int atmel_calc_fidi(struct uart_port *port,
392                                     struct serial_iso7816 *iso7816conf)
393 {
394         u64 fidi = 0;
395
396         if (iso7816conf->sc_fi && iso7816conf->sc_di) {
397                 fidi = (u64)iso7816conf->sc_fi;
398                 do_div(fidi, iso7816conf->sc_di);
399         }
400         return (u32)fidi;
401 }
402
403 /* Enable or disable the iso7816 support */
404 /* Called with interrupts disabled */
405 static int atmel_config_iso7816(struct uart_port *port,
406                                 struct serial_iso7816 *iso7816conf)
407 {
408         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
409         unsigned int mode;
410         unsigned int cd, fidi;
411         int ret = 0;
412
413         /* Disable interrupts */
414         atmel_uart_writel(port, ATMEL_US_IDR, atmel_port->tx_done_mask);
415
416         mode = atmel_uart_readl(port, ATMEL_US_MR);
417
418         if (iso7816conf->flags & SER_ISO7816_ENABLED) {
419                 mode &= ~ATMEL_US_USMODE;
420
421                 if (iso7816conf->tg > 255) {
422                         dev_err(port->dev, "ISO7816: Timeguard exceeding 255\n");
423                         memset(iso7816conf, 0, sizeof(struct serial_iso7816));
424                         ret = -EINVAL;
425                         goto err_out;
426                 }
427
428                 if ((iso7816conf->flags & SER_ISO7816_T_PARAM)
429                     == SER_ISO7816_T(0)) {
430                         mode |= ATMEL_US_USMODE_ISO7816_T0 | ATMEL_US_DSNACK;
431                 } else if ((iso7816conf->flags & SER_ISO7816_T_PARAM)
432                            == SER_ISO7816_T(1)) {
433                         mode |= ATMEL_US_USMODE_ISO7816_T1 | ATMEL_US_INACK;
434                 } else {
435                         dev_err(port->dev, "ISO7816: Type not supported\n");
436                         memset(iso7816conf, 0, sizeof(struct serial_iso7816));
437                         ret = -EINVAL;
438                         goto err_out;
439                 }
440
441                 mode &= ~(ATMEL_US_USCLKS | ATMEL_US_NBSTOP | ATMEL_US_PAR);
442
443                 /* select mck clock, and output  */
444                 mode |= ATMEL_US_USCLKS_MCK | ATMEL_US_CLKO;
445                 /* set parity for normal/inverse mode + max iterations */
446                 mode |= ATMEL_US_PAR_EVEN | ATMEL_US_NBSTOP_1 | ATMEL_US_MAX_ITER(3);
447
448                 cd = atmel_calc_cd(port, iso7816conf);
449                 fidi = atmel_calc_fidi(port, iso7816conf);
450                 if (fidi == 0) {
451                         dev_warn(port->dev, "ISO7816 fidi = 0, Generator generates no signal\n");
452                 } else if (fidi < atmel_port->fidi_min
453                            || fidi > atmel_port->fidi_max) {
454                         dev_err(port->dev, "ISO7816 fidi = %u, value not supported\n", fidi);
455                         memset(iso7816conf, 0, sizeof(struct serial_iso7816));
456                         ret = -EINVAL;
457                         goto err_out;
458                 }
459
460                 if (!(port->iso7816.flags & SER_ISO7816_ENABLED)) {
461                         /* port not yet in iso7816 mode: store configuration */
462                         atmel_port->backup_mode = atmel_uart_readl(port, ATMEL_US_MR);
463                         atmel_port->backup_brgr = atmel_uart_readl(port, ATMEL_US_BRGR);
464                 }
465
466                 atmel_uart_writel(port, ATMEL_US_TTGR, iso7816conf->tg);
467                 atmel_uart_writel(port, ATMEL_US_BRGR, cd);
468                 atmel_uart_writel(port, ATMEL_US_FIDI, fidi);
469
470                 atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_TXDIS | ATMEL_US_RXEN);
471                 atmel_port->tx_done_mask = ATMEL_US_TXEMPTY | ATMEL_US_NACK | ATMEL_US_ITERATION;
472         } else {
473                 dev_dbg(port->dev, "Setting UART back to RS232\n");
474                 /* back to last RS232 settings */
475                 mode = atmel_port->backup_mode;
476                 memset(iso7816conf, 0, sizeof(struct serial_iso7816));
477                 atmel_uart_writel(port, ATMEL_US_TTGR, 0);
478                 atmel_uart_writel(port, ATMEL_US_BRGR, atmel_port->backup_brgr);
479                 atmel_uart_writel(port, ATMEL_US_FIDI, 0x174);
480
481                 if (atmel_use_pdc_tx(port))
482                         atmel_port->tx_done_mask = ATMEL_US_ENDTX |
483                                                    ATMEL_US_TXBUFE;
484                 else
485                         atmel_port->tx_done_mask = ATMEL_US_TXRDY;
486         }
487
488         port->iso7816 = *iso7816conf;
489
490         atmel_uart_writel(port, ATMEL_US_MR, mode);
491
492 err_out:
493         /* Enable interrupts */
494         atmel_uart_writel(port, ATMEL_US_IER, atmel_port->tx_done_mask);
495
496         return ret;
497 }
498
499 /*
500  * Return TIOCSER_TEMT when transmitter FIFO and Shift register is empty.
501  */
502 static u_int atmel_tx_empty(struct uart_port *port)
503 {
504         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
505
506         if (atmel_port->tx_stopped)
507                 return TIOCSER_TEMT;
508         return (atmel_uart_readl(port, ATMEL_US_CSR) & ATMEL_US_TXEMPTY) ?
509                 TIOCSER_TEMT :
510                 0;
511 }
512
513 /*
514  * Set state of the modem control output lines
515  */
516 static void atmel_set_mctrl(struct uart_port *port, u_int mctrl)
517 {
518         unsigned int control = 0;
519         unsigned int mode = atmel_uart_readl(port, ATMEL_US_MR);
520         unsigned int rts_paused, rts_ready;
521         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
522
523         /* override mode to RS485 if needed, otherwise keep the current mode */
524         if (port->rs485.flags & SER_RS485_ENABLED) {
525                 atmel_uart_writel(port, ATMEL_US_TTGR,
526                                   port->rs485.delay_rts_after_send);
527                 mode &= ~ATMEL_US_USMODE;
528                 mode |= ATMEL_US_USMODE_RS485;
529         }
530
531         /* set the RTS line state according to the mode */
532         if ((mode & ATMEL_US_USMODE) == ATMEL_US_USMODE_HWHS) {
533                 /* force RTS line to high level */
534                 rts_paused = ATMEL_US_RTSEN;
535
536                 /* give the control of the RTS line back to the hardware */
537                 rts_ready = ATMEL_US_RTSDIS;
538         } else {
539                 /* force RTS line to high level */
540                 rts_paused = ATMEL_US_RTSDIS;
541
542                 /* force RTS line to low level */
543                 rts_ready = ATMEL_US_RTSEN;
544         }
545
546         if (mctrl & TIOCM_RTS)
547                 control |= rts_ready;
548         else
549                 control |= rts_paused;
550
551         if (mctrl & TIOCM_DTR)
552                 control |= ATMEL_US_DTREN;
553         else
554                 control |= ATMEL_US_DTRDIS;
555
556         atmel_uart_writel(port, ATMEL_US_CR, control);
557
558         mctrl_gpio_set(atmel_port->gpios, mctrl);
559
560         /* Local loopback mode? */
561         mode &= ~ATMEL_US_CHMODE;
562         if (mctrl & TIOCM_LOOP)
563                 mode |= ATMEL_US_CHMODE_LOC_LOOP;
564         else
565                 mode |= ATMEL_US_CHMODE_NORMAL;
566
567         atmel_uart_writel(port, ATMEL_US_MR, mode);
568 }
569
570 /*
571  * Get state of the modem control input lines
572  */
573 static u_int atmel_get_mctrl(struct uart_port *port)
574 {
575         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
576         unsigned int ret = 0, status;
577
578         status = atmel_uart_readl(port, ATMEL_US_CSR);
579
580         /*
581          * The control signals are active low.
582          */
583         if (!(status & ATMEL_US_DCD))
584                 ret |= TIOCM_CD;
585         if (!(status & ATMEL_US_CTS))
586                 ret |= TIOCM_CTS;
587         if (!(status & ATMEL_US_DSR))
588                 ret |= TIOCM_DSR;
589         if (!(status & ATMEL_US_RI))
590                 ret |= TIOCM_RI;
591
592         return mctrl_gpio_get(atmel_port->gpios, &ret);
593 }
594
595 /*
596  * Stop transmitting.
597  */
598 static void atmel_stop_tx(struct uart_port *port)
599 {
600         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
601
602         if (atmel_use_pdc_tx(port)) {
603                 /* disable PDC transmit */
604                 atmel_uart_writel(port, ATMEL_PDC_PTCR, ATMEL_PDC_TXTDIS);
605         }
606
607         /*
608          * Disable the transmitter.
609          * This is mandatory when DMA is used, otherwise the DMA buffer
610          * is fully transmitted.
611          */
612         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_TXDIS);
613         atmel_port->tx_stopped = true;
614
615         /* Disable interrupts */
616         atmel_uart_writel(port, ATMEL_US_IDR, atmel_port->tx_done_mask);
617
618         if (atmel_uart_is_half_duplex(port))
619                 atmel_start_rx(port);
620
621 }
622
623 /*
624  * Start transmitting.
625  */
626 static void atmel_start_tx(struct uart_port *port)
627 {
628         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
629
630         if (atmel_use_pdc_tx(port) && (atmel_uart_readl(port, ATMEL_PDC_PTSR)
631                                        & ATMEL_PDC_TXTEN))
632                 /* The transmitter is already running.  Yes, we
633                    really need this.*/
634                 return;
635
636         if (atmel_use_pdc_tx(port) || atmel_use_dma_tx(port))
637                 if (atmel_uart_is_half_duplex(port))
638                         atmel_stop_rx(port);
639
640         if (atmel_use_pdc_tx(port))
641                 /* re-enable PDC transmit */
642                 atmel_uart_writel(port, ATMEL_PDC_PTCR, ATMEL_PDC_TXTEN);
643
644         /* Enable interrupts */
645         atmel_uart_writel(port, ATMEL_US_IER, atmel_port->tx_done_mask);
646
647         /* re-enable the transmitter */
648         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_TXEN);
649         atmel_port->tx_stopped = false;
650 }
651
652 /*
653  * start receiving - port is in process of being opened.
654  */
655 static void atmel_start_rx(struct uart_port *port)
656 {
657         /* reset status and receiver */
658         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_RSTSTA);
659
660         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_RXEN);
661
662         if (atmel_use_pdc_rx(port)) {
663                 /* enable PDC controller */
664                 atmel_uart_writel(port, ATMEL_US_IER,
665                                   ATMEL_US_ENDRX | ATMEL_US_TIMEOUT |
666                                   port->read_status_mask);
667                 atmel_uart_writel(port, ATMEL_PDC_PTCR, ATMEL_PDC_RXTEN);
668         } else {
669                 atmel_uart_writel(port, ATMEL_US_IER, ATMEL_US_RXRDY);
670         }
671 }
672
673 /*
674  * Stop receiving - port is in process of being closed.
675  */
676 static void atmel_stop_rx(struct uart_port *port)
677 {
678         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_RXDIS);
679
680         if (atmel_use_pdc_rx(port)) {
681                 /* disable PDC receive */
682                 atmel_uart_writel(port, ATMEL_PDC_PTCR, ATMEL_PDC_RXTDIS);
683                 atmel_uart_writel(port, ATMEL_US_IDR,
684                                   ATMEL_US_ENDRX | ATMEL_US_TIMEOUT |
685                                   port->read_status_mask);
686         } else {
687                 atmel_uart_writel(port, ATMEL_US_IDR, ATMEL_US_RXRDY);
688         }
689 }
690
691 /*
692  * Enable modem status interrupts
693  */
694 static void atmel_enable_ms(struct uart_port *port)
695 {
696         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
697         uint32_t ier = 0;
698
699         /*
700          * Interrupt should not be enabled twice
701          */
702         if (atmel_port->ms_irq_enabled)
703                 return;
704
705         atmel_port->ms_irq_enabled = true;
706
707         if (!mctrl_gpio_to_gpiod(atmel_port->gpios, UART_GPIO_CTS))
708                 ier |= ATMEL_US_CTSIC;
709
710         if (!mctrl_gpio_to_gpiod(atmel_port->gpios, UART_GPIO_DSR))
711                 ier |= ATMEL_US_DSRIC;
712
713         if (!mctrl_gpio_to_gpiod(atmel_port->gpios, UART_GPIO_RI))
714                 ier |= ATMEL_US_RIIC;
715
716         if (!mctrl_gpio_to_gpiod(atmel_port->gpios, UART_GPIO_DCD))
717                 ier |= ATMEL_US_DCDIC;
718
719         atmel_uart_writel(port, ATMEL_US_IER, ier);
720
721         mctrl_gpio_enable_ms(atmel_port->gpios);
722 }
723
724 /*
725  * Disable modem status interrupts
726  */
727 static void atmel_disable_ms(struct uart_port *port)
728 {
729         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
730         uint32_t idr = 0;
731
732         /*
733          * Interrupt should not be disabled twice
734          */
735         if (!atmel_port->ms_irq_enabled)
736                 return;
737
738         atmel_port->ms_irq_enabled = false;
739
740         mctrl_gpio_disable_ms(atmel_port->gpios);
741
742         if (!mctrl_gpio_to_gpiod(atmel_port->gpios, UART_GPIO_CTS))
743                 idr |= ATMEL_US_CTSIC;
744
745         if (!mctrl_gpio_to_gpiod(atmel_port->gpios, UART_GPIO_DSR))
746                 idr |= ATMEL_US_DSRIC;
747
748         if (!mctrl_gpio_to_gpiod(atmel_port->gpios, UART_GPIO_RI))
749                 idr |= ATMEL_US_RIIC;
750
751         if (!mctrl_gpio_to_gpiod(atmel_port->gpios, UART_GPIO_DCD))
752                 idr |= ATMEL_US_DCDIC;
753
754         atmel_uart_writel(port, ATMEL_US_IDR, idr);
755 }
756
757 /*
758  * Control the transmission of a break signal
759  */
760 static void atmel_break_ctl(struct uart_port *port, int break_state)
761 {
762         if (break_state != 0)
763                 /* start break */
764                 atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_STTBRK);
765         else
766                 /* stop break */
767                 atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_STPBRK);
768 }
769
770 /*
771  * Stores the incoming character in the ring buffer
772  */
773 static void
774 atmel_buffer_rx_char(struct uart_port *port, unsigned int status,
775                      unsigned int ch)
776 {
777         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
778         struct circ_buf *ring = &atmel_port->rx_ring;
779         struct atmel_uart_char *c;
780
781         if (!CIRC_SPACE(ring->head, ring->tail, ATMEL_SERIAL_RINGSIZE))
782                 /* Buffer overflow, ignore char */
783                 return;
784
785         c = &((struct atmel_uart_char *)ring->buf)[ring->head];
786         c->status       = status;
787         c->ch           = ch;
788
789         /* Make sure the character is stored before we update head. */
790         smp_wmb();
791
792         ring->head = (ring->head + 1) & (ATMEL_SERIAL_RINGSIZE - 1);
793 }
794
795 /*
796  * Deal with parity, framing and overrun errors.
797  */
798 static void atmel_pdc_rxerr(struct uart_port *port, unsigned int status)
799 {
800         /* clear error */
801         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_RSTSTA);
802
803         if (status & ATMEL_US_RXBRK) {
804                 /* ignore side-effect */
805                 status &= ~(ATMEL_US_PARE | ATMEL_US_FRAME);
806                 port->icount.brk++;
807         }
808         if (status & ATMEL_US_PARE)
809                 port->icount.parity++;
810         if (status & ATMEL_US_FRAME)
811                 port->icount.frame++;
812         if (status & ATMEL_US_OVRE)
813                 port->icount.overrun++;
814 }
815
816 /*
817  * Characters received (called from interrupt handler)
818  */
819 static void atmel_rx_chars(struct uart_port *port)
820 {
821         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
822         unsigned int status, ch;
823
824         status = atmel_uart_readl(port, ATMEL_US_CSR);
825         while (status & ATMEL_US_RXRDY) {
826                 ch = atmel_uart_read_char(port);
827
828                 /*
829                  * note that the error handling code is
830                  * out of the main execution path
831                  */
832                 if (unlikely(status & (ATMEL_US_PARE | ATMEL_US_FRAME
833                                        | ATMEL_US_OVRE | ATMEL_US_RXBRK)
834                              || atmel_port->break_active)) {
835
836                         /* clear error */
837                         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_RSTSTA);
838
839                         if (status & ATMEL_US_RXBRK
840                             && !atmel_port->break_active) {
841                                 atmel_port->break_active = 1;
842                                 atmel_uart_writel(port, ATMEL_US_IER,
843                                                   ATMEL_US_RXBRK);
844                         } else {
845                                 /*
846                                  * This is either the end-of-break
847                                  * condition or we've received at
848                                  * least one character without RXBRK
849                                  * being set. In both cases, the next
850                                  * RXBRK will indicate start-of-break.
851                                  */
852                                 atmel_uart_writel(port, ATMEL_US_IDR,
853                                                   ATMEL_US_RXBRK);
854                                 status &= ~ATMEL_US_RXBRK;
855                                 atmel_port->break_active = 0;
856                         }
857                 }
858
859                 atmel_buffer_rx_char(port, status, ch);
860                 status = atmel_uart_readl(port, ATMEL_US_CSR);
861         }
862
863         atmel_tasklet_schedule(atmel_port, &atmel_port->tasklet_rx);
864 }
865
866 /*
867  * Transmit characters (called from tasklet with TXRDY interrupt
868  * disabled)
869  */
870 static void atmel_tx_chars(struct uart_port *port)
871 {
872         struct circ_buf *xmit = &port->state->xmit;
873         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
874
875         if (port->x_char &&
876             (atmel_uart_readl(port, ATMEL_US_CSR) & atmel_port->tx_done_mask)) {
877                 atmel_uart_write_char(port, port->x_char);
878                 port->icount.tx++;
879                 port->x_char = 0;
880         }
881         if (uart_circ_empty(xmit) || uart_tx_stopped(port))
882                 return;
883
884         while (atmel_uart_readl(port, ATMEL_US_CSR) &
885                atmel_port->tx_done_mask) {
886                 atmel_uart_write_char(port, xmit->buf[xmit->tail]);
887                 xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1);
888                 port->icount.tx++;
889                 if (uart_circ_empty(xmit))
890                         break;
891         }
892
893         if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
894                 uart_write_wakeup(port);
895
896         if (!uart_circ_empty(xmit))
897                 /* Enable interrupts */
898                 atmel_uart_writel(port, ATMEL_US_IER,
899                                   atmel_port->tx_done_mask);
900 }
901
902 static void atmel_complete_tx_dma(void *arg)
903 {
904         struct atmel_uart_port *atmel_port = arg;
905         struct uart_port *port = &atmel_port->uart;
906         struct circ_buf *xmit = &port->state->xmit;
907         struct dma_chan *chan = atmel_port->chan_tx;
908         unsigned long flags;
909
910         spin_lock_irqsave(&port->lock, flags);
911
912         if (chan)
913                 dmaengine_terminate_all(chan);
914         xmit->tail += atmel_port->tx_len;
915         xmit->tail &= UART_XMIT_SIZE - 1;
916
917         port->icount.tx += atmel_port->tx_len;
918
919         spin_lock_irq(&atmel_port->lock_tx);
920         async_tx_ack(atmel_port->desc_tx);
921         atmel_port->cookie_tx = -EINVAL;
922         atmel_port->desc_tx = NULL;
923         spin_unlock_irq(&atmel_port->lock_tx);
924
925         if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
926                 uart_write_wakeup(port);
927
928         /*
929          * xmit is a circular buffer so, if we have just send data from
930          * xmit->tail to the end of xmit->buf, now we have to transmit the
931          * remaining data from the beginning of xmit->buf to xmit->head.
932          */
933         if (!uart_circ_empty(xmit))
934                 atmel_tasklet_schedule(atmel_port, &atmel_port->tasklet_tx);
935         else if (atmel_uart_is_half_duplex(port)) {
936                 /* DMA done, stop TX, start RX for RS485 */
937                 atmel_start_rx(port);
938         }
939
940         spin_unlock_irqrestore(&port->lock, flags);
941 }
942
943 static void atmel_release_tx_dma(struct uart_port *port)
944 {
945         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
946         struct dma_chan *chan = atmel_port->chan_tx;
947
948         if (chan) {
949                 dmaengine_terminate_all(chan);
950                 dma_release_channel(chan);
951                 dma_unmap_sg(port->dev, &atmel_port->sg_tx, 1,
952                                 DMA_TO_DEVICE);
953         }
954
955         atmel_port->desc_tx = NULL;
956         atmel_port->chan_tx = NULL;
957         atmel_port->cookie_tx = -EINVAL;
958 }
959
960 /*
961  * Called from tasklet with TXRDY interrupt is disabled.
962  */
963 static void atmel_tx_dma(struct uart_port *port)
964 {
965         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
966         struct circ_buf *xmit = &port->state->xmit;
967         struct dma_chan *chan = atmel_port->chan_tx;
968         struct dma_async_tx_descriptor *desc;
969         struct scatterlist sgl[2], *sg, *sg_tx = &atmel_port->sg_tx;
970         unsigned int tx_len, part1_len, part2_len, sg_len;
971         dma_addr_t phys_addr;
972
973         /* Make sure we have an idle channel */
974         if (atmel_port->desc_tx != NULL)
975                 return;
976
977         if (!uart_circ_empty(xmit) && !uart_tx_stopped(port)) {
978                 /*
979                  * DMA is idle now.
980                  * Port xmit buffer is already mapped,
981                  * and it is one page... Just adjust
982                  * offsets and lengths. Since it is a circular buffer,
983                  * we have to transmit till the end, and then the rest.
984                  * Take the port lock to get a
985                  * consistent xmit buffer state.
986                  */
987                 tx_len = CIRC_CNT_TO_END(xmit->head,
988                                          xmit->tail,
989                                          UART_XMIT_SIZE);
990
991                 if (atmel_port->fifo_size) {
992                         /* multi data mode */
993                         part1_len = (tx_len & ~0x3); /* DWORD access */
994                         part2_len = (tx_len & 0x3); /* BYTE access */
995                 } else {
996                         /* single data (legacy) mode */
997                         part1_len = 0;
998                         part2_len = tx_len; /* BYTE access only */
999                 }
1000
1001                 sg_init_table(sgl, 2);
1002                 sg_len = 0;
1003                 phys_addr = sg_dma_address(sg_tx) + xmit->tail;
1004                 if (part1_len) {
1005                         sg = &sgl[sg_len++];
1006                         sg_dma_address(sg) = phys_addr;
1007                         sg_dma_len(sg) = part1_len;
1008
1009                         phys_addr += part1_len;
1010                 }
1011
1012                 if (part2_len) {
1013                         sg = &sgl[sg_len++];
1014                         sg_dma_address(sg) = phys_addr;
1015                         sg_dma_len(sg) = part2_len;
1016                 }
1017
1018                 /*
1019                  * save tx_len so atmel_complete_tx_dma() will increase
1020                  * xmit->tail correctly
1021                  */
1022                 atmel_port->tx_len = tx_len;
1023
1024                 desc = dmaengine_prep_slave_sg(chan,
1025                                                sgl,
1026                                                sg_len,
1027                                                DMA_MEM_TO_DEV,
1028                                                DMA_PREP_INTERRUPT |
1029                                                DMA_CTRL_ACK);
1030                 if (!desc) {
1031                         dev_err(port->dev, "Failed to send via dma!\n");
1032                         return;
1033                 }
1034
1035                 dma_sync_sg_for_device(port->dev, sg_tx, 1, DMA_TO_DEVICE);
1036
1037                 atmel_port->desc_tx = desc;
1038                 desc->callback = atmel_complete_tx_dma;
1039                 desc->callback_param = atmel_port;
1040                 atmel_port->cookie_tx = dmaengine_submit(desc);
1041         }
1042
1043         if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
1044                 uart_write_wakeup(port);
1045 }
1046
1047 static int atmel_prepare_tx_dma(struct uart_port *port)
1048 {
1049         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1050         struct device *mfd_dev = port->dev->parent;
1051         dma_cap_mask_t          mask;
1052         struct dma_slave_config config;
1053         int ret, nent;
1054
1055         dma_cap_zero(mask);
1056         dma_cap_set(DMA_SLAVE, mask);
1057
1058         atmel_port->chan_tx = dma_request_slave_channel(mfd_dev, "tx");
1059         if (atmel_port->chan_tx == NULL)
1060                 goto chan_err;
1061         dev_info(port->dev, "using %s for tx DMA transfers\n",
1062                 dma_chan_name(atmel_port->chan_tx));
1063
1064         spin_lock_init(&atmel_port->lock_tx);
1065         sg_init_table(&atmel_port->sg_tx, 1);
1066         /* UART circular tx buffer is an aligned page. */
1067         BUG_ON(!PAGE_ALIGNED(port->state->xmit.buf));
1068         sg_set_page(&atmel_port->sg_tx,
1069                         virt_to_page(port->state->xmit.buf),
1070                         UART_XMIT_SIZE,
1071                         offset_in_page(port->state->xmit.buf));
1072         nent = dma_map_sg(port->dev,
1073                                 &atmel_port->sg_tx,
1074                                 1,
1075                                 DMA_TO_DEVICE);
1076
1077         if (!nent) {
1078                 dev_dbg(port->dev, "need to release resource of dma\n");
1079                 goto chan_err;
1080         } else {
1081                 dev_dbg(port->dev, "%s: mapped %d@%p to %pad\n", __func__,
1082                         sg_dma_len(&atmel_port->sg_tx),
1083                         port->state->xmit.buf,
1084                         &sg_dma_address(&atmel_port->sg_tx));
1085         }
1086
1087         /* Configure the slave DMA */
1088         memset(&config, 0, sizeof(config));
1089         config.direction = DMA_MEM_TO_DEV;
1090         config.dst_addr_width = (atmel_port->fifo_size) ?
1091                                 DMA_SLAVE_BUSWIDTH_4_BYTES :
1092                                 DMA_SLAVE_BUSWIDTH_1_BYTE;
1093         config.dst_addr = port->mapbase + ATMEL_US_THR;
1094         config.dst_maxburst = 1;
1095
1096         ret = dmaengine_slave_config(atmel_port->chan_tx,
1097                                      &config);
1098         if (ret) {
1099                 dev_err(port->dev, "DMA tx slave configuration failed\n");
1100                 goto chan_err;
1101         }
1102
1103         return 0;
1104
1105 chan_err:
1106         dev_err(port->dev, "TX channel not available, switch to pio\n");
1107         atmel_port->use_dma_tx = 0;
1108         if (atmel_port->chan_tx)
1109                 atmel_release_tx_dma(port);
1110         return -EINVAL;
1111 }
1112
1113 static void atmel_complete_rx_dma(void *arg)
1114 {
1115         struct uart_port *port = arg;
1116         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1117
1118         atmel_tasklet_schedule(atmel_port, &atmel_port->tasklet_rx);
1119 }
1120
1121 static void atmel_release_rx_dma(struct uart_port *port)
1122 {
1123         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1124         struct dma_chan *chan = atmel_port->chan_rx;
1125
1126         if (chan) {
1127                 dmaengine_terminate_all(chan);
1128                 dma_release_channel(chan);
1129                 dma_unmap_sg(port->dev, &atmel_port->sg_rx, 1,
1130                                 DMA_FROM_DEVICE);
1131         }
1132
1133         atmel_port->desc_rx = NULL;
1134         atmel_port->chan_rx = NULL;
1135         atmel_port->cookie_rx = -EINVAL;
1136 }
1137
1138 static void atmel_rx_from_dma(struct uart_port *port)
1139 {
1140         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1141         struct tty_port *tport = &port->state->port;
1142         struct circ_buf *ring = &atmel_port->rx_ring;
1143         struct dma_chan *chan = atmel_port->chan_rx;
1144         struct dma_tx_state state;
1145         enum dma_status dmastat;
1146         size_t count;
1147
1148
1149         /* Reset the UART timeout early so that we don't miss one */
1150         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_STTTO);
1151         dmastat = dmaengine_tx_status(chan,
1152                                 atmel_port->cookie_rx,
1153                                 &state);
1154         /* Restart a new tasklet if DMA status is error */
1155         if (dmastat == DMA_ERROR) {
1156                 dev_dbg(port->dev, "Get residue error, restart tasklet\n");
1157                 atmel_uart_writel(port, ATMEL_US_IER, ATMEL_US_TIMEOUT);
1158                 atmel_tasklet_schedule(atmel_port, &atmel_port->tasklet_rx);
1159                 return;
1160         }
1161
1162         /* CPU claims ownership of RX DMA buffer */
1163         dma_sync_sg_for_cpu(port->dev,
1164                             &atmel_port->sg_rx,
1165                             1,
1166                             DMA_FROM_DEVICE);
1167
1168         /*
1169          * ring->head points to the end of data already written by the DMA.
1170          * ring->tail points to the beginning of data to be read by the
1171          * framework.
1172          * The current transfer size should not be larger than the dma buffer
1173          * length.
1174          */
1175         ring->head = sg_dma_len(&atmel_port->sg_rx) - state.residue;
1176         BUG_ON(ring->head > sg_dma_len(&atmel_port->sg_rx));
1177         /*
1178          * At this point ring->head may point to the first byte right after the
1179          * last byte of the dma buffer:
1180          * 0 <= ring->head <= sg_dma_len(&atmel_port->sg_rx)
1181          *
1182          * However ring->tail must always points inside the dma buffer:
1183          * 0 <= ring->tail <= sg_dma_len(&atmel_port->sg_rx) - 1
1184          *
1185          * Since we use a ring buffer, we have to handle the case
1186          * where head is lower than tail. In such a case, we first read from
1187          * tail to the end of the buffer then reset tail.
1188          */
1189         if (ring->head < ring->tail) {
1190                 count = sg_dma_len(&atmel_port->sg_rx) - ring->tail;
1191
1192                 tty_insert_flip_string(tport, ring->buf + ring->tail, count);
1193                 ring->tail = 0;
1194                 port->icount.rx += count;
1195         }
1196
1197         /* Finally we read data from tail to head */
1198         if (ring->tail < ring->head) {
1199                 count = ring->head - ring->tail;
1200
1201                 tty_insert_flip_string(tport, ring->buf + ring->tail, count);
1202                 /* Wrap ring->head if needed */
1203                 if (ring->head >= sg_dma_len(&atmel_port->sg_rx))
1204                         ring->head = 0;
1205                 ring->tail = ring->head;
1206                 port->icount.rx += count;
1207         }
1208
1209         /* USART retreives ownership of RX DMA buffer */
1210         dma_sync_sg_for_device(port->dev,
1211                                &atmel_port->sg_rx,
1212                                1,
1213                                DMA_FROM_DEVICE);
1214
1215         /*
1216          * Drop the lock here since it might end up calling
1217          * uart_start(), which takes the lock.
1218          */
1219         spin_unlock(&port->lock);
1220         tty_flip_buffer_push(tport);
1221         spin_lock(&port->lock);
1222
1223         atmel_uart_writel(port, ATMEL_US_IER, ATMEL_US_TIMEOUT);
1224 }
1225
1226 static int atmel_prepare_rx_dma(struct uart_port *port)
1227 {
1228         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1229         struct device *mfd_dev = port->dev->parent;
1230         struct dma_async_tx_descriptor *desc;
1231         dma_cap_mask_t          mask;
1232         struct dma_slave_config config;
1233         struct circ_buf         *ring;
1234         int ret, nent;
1235
1236         ring = &atmel_port->rx_ring;
1237
1238         dma_cap_zero(mask);
1239         dma_cap_set(DMA_CYCLIC, mask);
1240
1241         atmel_port->chan_rx = dma_request_slave_channel(mfd_dev, "rx");
1242         if (atmel_port->chan_rx == NULL)
1243                 goto chan_err;
1244         dev_info(port->dev, "using %s for rx DMA transfers\n",
1245                 dma_chan_name(atmel_port->chan_rx));
1246
1247         spin_lock_init(&atmel_port->lock_rx);
1248         sg_init_table(&atmel_port->sg_rx, 1);
1249         /* UART circular rx buffer is an aligned page. */
1250         BUG_ON(!PAGE_ALIGNED(ring->buf));
1251         sg_set_page(&atmel_port->sg_rx,
1252                     virt_to_page(ring->buf),
1253                     sizeof(struct atmel_uart_char) * ATMEL_SERIAL_RINGSIZE,
1254                     offset_in_page(ring->buf));
1255         nent = dma_map_sg(port->dev,
1256                           &atmel_port->sg_rx,
1257                           1,
1258                           DMA_FROM_DEVICE);
1259
1260         if (!nent) {
1261                 dev_dbg(port->dev, "need to release resource of dma\n");
1262                 goto chan_err;
1263         } else {
1264                 dev_dbg(port->dev, "%s: mapped %d@%p to %pad\n", __func__,
1265                         sg_dma_len(&atmel_port->sg_rx),
1266                         ring->buf,
1267                         &sg_dma_address(&atmel_port->sg_rx));
1268         }
1269
1270         /* Configure the slave DMA */
1271         memset(&config, 0, sizeof(config));
1272         config.direction = DMA_DEV_TO_MEM;
1273         config.src_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE;
1274         config.src_addr = port->mapbase + ATMEL_US_RHR;
1275         config.src_maxburst = 1;
1276
1277         ret = dmaengine_slave_config(atmel_port->chan_rx,
1278                                      &config);
1279         if (ret) {
1280                 dev_err(port->dev, "DMA rx slave configuration failed\n");
1281                 goto chan_err;
1282         }
1283         /*
1284          * Prepare a cyclic dma transfer, assign 2 descriptors,
1285          * each one is half ring buffer size
1286          */
1287         desc = dmaengine_prep_dma_cyclic(atmel_port->chan_rx,
1288                                          sg_dma_address(&atmel_port->sg_rx),
1289                                          sg_dma_len(&atmel_port->sg_rx),
1290                                          sg_dma_len(&atmel_port->sg_rx)/2,
1291                                          DMA_DEV_TO_MEM,
1292                                          DMA_PREP_INTERRUPT);
1293         if (!desc) {
1294                 dev_err(port->dev, "Preparing DMA cyclic failed\n");
1295                 goto chan_err;
1296         }
1297         desc->callback = atmel_complete_rx_dma;
1298         desc->callback_param = port;
1299         atmel_port->desc_rx = desc;
1300         atmel_port->cookie_rx = dmaengine_submit(desc);
1301
1302         return 0;
1303
1304 chan_err:
1305         dev_err(port->dev, "RX channel not available, switch to pio\n");
1306         atmel_port->use_dma_rx = 0;
1307         if (atmel_port->chan_rx)
1308                 atmel_release_rx_dma(port);
1309         return -EINVAL;
1310 }
1311
1312 static void atmel_uart_timer_callback(struct timer_list *t)
1313 {
1314         struct atmel_uart_port *atmel_port = from_timer(atmel_port, t,
1315                                                         uart_timer);
1316         struct uart_port *port = &atmel_port->uart;
1317
1318         if (!atomic_read(&atmel_port->tasklet_shutdown)) {
1319                 tasklet_schedule(&atmel_port->tasklet_rx);
1320                 mod_timer(&atmel_port->uart_timer,
1321                           jiffies + uart_poll_timeout(port));
1322         }
1323 }
1324
1325 /*
1326  * receive interrupt handler.
1327  */
1328 static void
1329 atmel_handle_receive(struct uart_port *port, unsigned int pending)
1330 {
1331         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1332
1333         if (atmel_use_pdc_rx(port)) {
1334                 /*
1335                  * PDC receive. Just schedule the tasklet and let it
1336                  * figure out the details.
1337                  *
1338                  * TODO: We're not handling error flags correctly at
1339                  * the moment.
1340                  */
1341                 if (pending & (ATMEL_US_ENDRX | ATMEL_US_TIMEOUT)) {
1342                         atmel_uart_writel(port, ATMEL_US_IDR,
1343                                           (ATMEL_US_ENDRX | ATMEL_US_TIMEOUT));
1344                         atmel_tasklet_schedule(atmel_port,
1345                                                &atmel_port->tasklet_rx);
1346                 }
1347
1348                 if (pending & (ATMEL_US_RXBRK | ATMEL_US_OVRE |
1349                                 ATMEL_US_FRAME | ATMEL_US_PARE))
1350                         atmel_pdc_rxerr(port, pending);
1351         }
1352
1353         if (atmel_use_dma_rx(port)) {
1354                 if (pending & ATMEL_US_TIMEOUT) {
1355                         atmel_uart_writel(port, ATMEL_US_IDR,
1356                                           ATMEL_US_TIMEOUT);
1357                         atmel_tasklet_schedule(atmel_port,
1358                                                &atmel_port->tasklet_rx);
1359                 }
1360         }
1361
1362         /* Interrupt receive */
1363         if (pending & ATMEL_US_RXRDY)
1364                 atmel_rx_chars(port);
1365         else if (pending & ATMEL_US_RXBRK) {
1366                 /*
1367                  * End of break detected. If it came along with a
1368                  * character, atmel_rx_chars will handle it.
1369                  */
1370                 atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_RSTSTA);
1371                 atmel_uart_writel(port, ATMEL_US_IDR, ATMEL_US_RXBRK);
1372                 atmel_port->break_active = 0;
1373         }
1374 }
1375
1376 /*
1377  * transmit interrupt handler. (Transmit is IRQF_NODELAY safe)
1378  */
1379 static void
1380 atmel_handle_transmit(struct uart_port *port, unsigned int pending)
1381 {
1382         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1383
1384         if (pending & atmel_port->tx_done_mask) {
1385                 /* Either PDC or interrupt transmission */
1386                 atmel_uart_writel(port, ATMEL_US_IDR,
1387                                   atmel_port->tx_done_mask);
1388                 atmel_tasklet_schedule(atmel_port, &atmel_port->tasklet_tx);
1389         }
1390 }
1391
1392 /*
1393  * status flags interrupt handler.
1394  */
1395 static void
1396 atmel_handle_status(struct uart_port *port, unsigned int pending,
1397                     unsigned int status)
1398 {
1399         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1400         unsigned int status_change;
1401
1402         if (pending & (ATMEL_US_RIIC | ATMEL_US_DSRIC | ATMEL_US_DCDIC
1403                                 | ATMEL_US_CTSIC)) {
1404                 status_change = status ^ atmel_port->irq_status_prev;
1405                 atmel_port->irq_status_prev = status;
1406
1407                 if (status_change & (ATMEL_US_RI | ATMEL_US_DSR
1408                                         | ATMEL_US_DCD | ATMEL_US_CTS)) {
1409                         /* TODO: All reads to CSR will clear these interrupts! */
1410                         if (status_change & ATMEL_US_RI)
1411                                 port->icount.rng++;
1412                         if (status_change & ATMEL_US_DSR)
1413                                 port->icount.dsr++;
1414                         if (status_change & ATMEL_US_DCD)
1415                                 uart_handle_dcd_change(port, !(status & ATMEL_US_DCD));
1416                         if (status_change & ATMEL_US_CTS)
1417                                 uart_handle_cts_change(port, !(status & ATMEL_US_CTS));
1418
1419                         wake_up_interruptible(&port->state->port.delta_msr_wait);
1420                 }
1421         }
1422
1423         if (pending & (ATMEL_US_NACK | ATMEL_US_ITERATION))
1424                 dev_dbg(port->dev, "ISO7816 ERROR (0x%08x)\n", pending);
1425 }
1426
1427 /*
1428  * Interrupt handler
1429  */
1430 static irqreturn_t atmel_interrupt(int irq, void *dev_id)
1431 {
1432         struct uart_port *port = dev_id;
1433         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1434         unsigned int status, pending, mask, pass_counter = 0;
1435
1436         spin_lock(&atmel_port->lock_suspended);
1437
1438         do {
1439                 status = atmel_get_lines_status(port);
1440                 mask = atmel_uart_readl(port, ATMEL_US_IMR);
1441                 pending = status & mask;
1442                 if (!pending)
1443                         break;
1444
1445                 if (atmel_port->suspended) {
1446                         atmel_port->pending |= pending;
1447                         atmel_port->pending_status = status;
1448                         atmel_uart_writel(port, ATMEL_US_IDR, mask);
1449                         pm_system_wakeup();
1450                         break;
1451                 }
1452
1453                 atmel_handle_receive(port, pending);
1454                 atmel_handle_status(port, pending, status);
1455                 atmel_handle_transmit(port, pending);
1456         } while (pass_counter++ < ATMEL_ISR_PASS_LIMIT);
1457
1458         spin_unlock(&atmel_port->lock_suspended);
1459
1460         return pass_counter ? IRQ_HANDLED : IRQ_NONE;
1461 }
1462
1463 static void atmel_release_tx_pdc(struct uart_port *port)
1464 {
1465         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1466         struct atmel_dma_buffer *pdc = &atmel_port->pdc_tx;
1467
1468         dma_unmap_single(port->dev,
1469                          pdc->dma_addr,
1470                          pdc->dma_size,
1471                          DMA_TO_DEVICE);
1472 }
1473
1474 /*
1475  * Called from tasklet with ENDTX and TXBUFE interrupts disabled.
1476  */
1477 static void atmel_tx_pdc(struct uart_port *port)
1478 {
1479         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1480         struct circ_buf *xmit = &port->state->xmit;
1481         struct atmel_dma_buffer *pdc = &atmel_port->pdc_tx;
1482         int count;
1483
1484         /* nothing left to transmit? */
1485         if (atmel_uart_readl(port, ATMEL_PDC_TCR))
1486                 return;
1487
1488         xmit->tail += pdc->ofs;
1489         xmit->tail &= UART_XMIT_SIZE - 1;
1490
1491         port->icount.tx += pdc->ofs;
1492         pdc->ofs = 0;
1493
1494         /* more to transmit - setup next transfer */
1495
1496         /* disable PDC transmit */
1497         atmel_uart_writel(port, ATMEL_PDC_PTCR, ATMEL_PDC_TXTDIS);
1498
1499         if (!uart_circ_empty(xmit) && !uart_tx_stopped(port)) {
1500                 dma_sync_single_for_device(port->dev,
1501                                            pdc->dma_addr,
1502                                            pdc->dma_size,
1503                                            DMA_TO_DEVICE);
1504
1505                 count = CIRC_CNT_TO_END(xmit->head, xmit->tail, UART_XMIT_SIZE);
1506                 pdc->ofs = count;
1507
1508                 atmel_uart_writel(port, ATMEL_PDC_TPR,
1509                                   pdc->dma_addr + xmit->tail);
1510                 atmel_uart_writel(port, ATMEL_PDC_TCR, count);
1511                 /* re-enable PDC transmit */
1512                 atmel_uart_writel(port, ATMEL_PDC_PTCR, ATMEL_PDC_TXTEN);
1513                 /* Enable interrupts */
1514                 atmel_uart_writel(port, ATMEL_US_IER,
1515                                   atmel_port->tx_done_mask);
1516         } else {
1517                 if (atmel_uart_is_half_duplex(port)) {
1518                         /* DMA done, stop TX, start RX for RS485 */
1519                         atmel_start_rx(port);
1520                 }
1521         }
1522
1523         if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
1524                 uart_write_wakeup(port);
1525 }
1526
1527 static int atmel_prepare_tx_pdc(struct uart_port *port)
1528 {
1529         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1530         struct atmel_dma_buffer *pdc = &atmel_port->pdc_tx;
1531         struct circ_buf *xmit = &port->state->xmit;
1532
1533         pdc->buf = xmit->buf;
1534         pdc->dma_addr = dma_map_single(port->dev,
1535                                         pdc->buf,
1536                                         UART_XMIT_SIZE,
1537                                         DMA_TO_DEVICE);
1538         pdc->dma_size = UART_XMIT_SIZE;
1539         pdc->ofs = 0;
1540
1541         return 0;
1542 }
1543
1544 static void atmel_rx_from_ring(struct uart_port *port)
1545 {
1546         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1547         struct circ_buf *ring = &atmel_port->rx_ring;
1548         unsigned int flg;
1549         unsigned int status;
1550
1551         while (ring->head != ring->tail) {
1552                 struct atmel_uart_char c;
1553
1554                 /* Make sure c is loaded after head. */
1555                 smp_rmb();
1556
1557                 c = ((struct atmel_uart_char *)ring->buf)[ring->tail];
1558
1559                 ring->tail = (ring->tail + 1) & (ATMEL_SERIAL_RINGSIZE - 1);
1560
1561                 port->icount.rx++;
1562                 status = c.status;
1563                 flg = TTY_NORMAL;
1564
1565                 /*
1566                  * note that the error handling code is
1567                  * out of the main execution path
1568                  */
1569                 if (unlikely(status & (ATMEL_US_PARE | ATMEL_US_FRAME
1570                                        | ATMEL_US_OVRE | ATMEL_US_RXBRK))) {
1571                         if (status & ATMEL_US_RXBRK) {
1572                                 /* ignore side-effect */
1573                                 status &= ~(ATMEL_US_PARE | ATMEL_US_FRAME);
1574
1575                                 port->icount.brk++;
1576                                 if (uart_handle_break(port))
1577                                         continue;
1578                         }
1579                         if (status & ATMEL_US_PARE)
1580                                 port->icount.parity++;
1581                         if (status & ATMEL_US_FRAME)
1582                                 port->icount.frame++;
1583                         if (status & ATMEL_US_OVRE)
1584                                 port->icount.overrun++;
1585
1586                         status &= port->read_status_mask;
1587
1588                         if (status & ATMEL_US_RXBRK)
1589                                 flg = TTY_BREAK;
1590                         else if (status & ATMEL_US_PARE)
1591                                 flg = TTY_PARITY;
1592                         else if (status & ATMEL_US_FRAME)
1593                                 flg = TTY_FRAME;
1594                 }
1595
1596
1597                 if (uart_handle_sysrq_char(port, c.ch))
1598                         continue;
1599
1600                 uart_insert_char(port, status, ATMEL_US_OVRE, c.ch, flg);
1601         }
1602
1603         /*
1604          * Drop the lock here since it might end up calling
1605          * uart_start(), which takes the lock.
1606          */
1607         spin_unlock(&port->lock);
1608         tty_flip_buffer_push(&port->state->port);
1609         spin_lock(&port->lock);
1610 }
1611
1612 static void atmel_release_rx_pdc(struct uart_port *port)
1613 {
1614         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1615         int i;
1616
1617         for (i = 0; i < 2; i++) {
1618                 struct atmel_dma_buffer *pdc = &atmel_port->pdc_rx[i];
1619
1620                 dma_unmap_single(port->dev,
1621                                  pdc->dma_addr,
1622                                  pdc->dma_size,
1623                                  DMA_FROM_DEVICE);
1624                 kfree(pdc->buf);
1625         }
1626 }
1627
1628 static void atmel_rx_from_pdc(struct uart_port *port)
1629 {
1630         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1631         struct tty_port *tport = &port->state->port;
1632         struct atmel_dma_buffer *pdc;
1633         int rx_idx = atmel_port->pdc_rx_idx;
1634         unsigned int head;
1635         unsigned int tail;
1636         unsigned int count;
1637
1638         do {
1639                 /* Reset the UART timeout early so that we don't miss one */
1640                 atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_STTTO);
1641
1642                 pdc = &atmel_port->pdc_rx[rx_idx];
1643                 head = atmel_uart_readl(port, ATMEL_PDC_RPR) - pdc->dma_addr;
1644                 tail = pdc->ofs;
1645
1646                 /* If the PDC has switched buffers, RPR won't contain
1647                  * any address within the current buffer. Since head
1648                  * is unsigned, we just need a one-way comparison to
1649                  * find out.
1650                  *
1651                  * In this case, we just need to consume the entire
1652                  * buffer and resubmit it for DMA. This will clear the
1653                  * ENDRX bit as well, so that we can safely re-enable
1654                  * all interrupts below.
1655                  */
1656                 head = min(head, pdc->dma_size);
1657
1658                 if (likely(head != tail)) {
1659                         dma_sync_single_for_cpu(port->dev, pdc->dma_addr,
1660                                         pdc->dma_size, DMA_FROM_DEVICE);
1661
1662                         /*
1663                          * head will only wrap around when we recycle
1664                          * the DMA buffer, and when that happens, we
1665                          * explicitly set tail to 0. So head will
1666                          * always be greater than tail.
1667                          */
1668                         count = head - tail;
1669
1670                         tty_insert_flip_string(tport, pdc->buf + pdc->ofs,
1671                                                 count);
1672
1673                         dma_sync_single_for_device(port->dev, pdc->dma_addr,
1674                                         pdc->dma_size, DMA_FROM_DEVICE);
1675
1676                         port->icount.rx += count;
1677                         pdc->ofs = head;
1678                 }
1679
1680                 /*
1681                  * If the current buffer is full, we need to check if
1682                  * the next one contains any additional data.
1683                  */
1684                 if (head >= pdc->dma_size) {
1685                         pdc->ofs = 0;
1686                         atmel_uart_writel(port, ATMEL_PDC_RNPR, pdc->dma_addr);
1687                         atmel_uart_writel(port, ATMEL_PDC_RNCR, pdc->dma_size);
1688
1689                         rx_idx = !rx_idx;
1690                         atmel_port->pdc_rx_idx = rx_idx;
1691                 }
1692         } while (head >= pdc->dma_size);
1693
1694         /*
1695          * Drop the lock here since it might end up calling
1696          * uart_start(), which takes the lock.
1697          */
1698         spin_unlock(&port->lock);
1699         tty_flip_buffer_push(tport);
1700         spin_lock(&port->lock);
1701
1702         atmel_uart_writel(port, ATMEL_US_IER,
1703                           ATMEL_US_ENDRX | ATMEL_US_TIMEOUT);
1704 }
1705
1706 static int atmel_prepare_rx_pdc(struct uart_port *port)
1707 {
1708         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1709         int i;
1710
1711         for (i = 0; i < 2; i++) {
1712                 struct atmel_dma_buffer *pdc = &atmel_port->pdc_rx[i];
1713
1714                 pdc->buf = kmalloc(PDC_BUFFER_SIZE, GFP_KERNEL);
1715                 if (pdc->buf == NULL) {
1716                         if (i != 0) {
1717                                 dma_unmap_single(port->dev,
1718                                         atmel_port->pdc_rx[0].dma_addr,
1719                                         PDC_BUFFER_SIZE,
1720                                         DMA_FROM_DEVICE);
1721                                 kfree(atmel_port->pdc_rx[0].buf);
1722                         }
1723                         atmel_port->use_pdc_rx = 0;
1724                         return -ENOMEM;
1725                 }
1726                 pdc->dma_addr = dma_map_single(port->dev,
1727                                                 pdc->buf,
1728                                                 PDC_BUFFER_SIZE,
1729                                                 DMA_FROM_DEVICE);
1730                 pdc->dma_size = PDC_BUFFER_SIZE;
1731                 pdc->ofs = 0;
1732         }
1733
1734         atmel_port->pdc_rx_idx = 0;
1735
1736         atmel_uart_writel(port, ATMEL_PDC_RPR, atmel_port->pdc_rx[0].dma_addr);
1737         atmel_uart_writel(port, ATMEL_PDC_RCR, PDC_BUFFER_SIZE);
1738
1739         atmel_uart_writel(port, ATMEL_PDC_RNPR,
1740                           atmel_port->pdc_rx[1].dma_addr);
1741         atmel_uart_writel(port, ATMEL_PDC_RNCR, PDC_BUFFER_SIZE);
1742
1743         return 0;
1744 }
1745
1746 /*
1747  * tasklet handling tty stuff outside the interrupt handler.
1748  */
1749 static void atmel_tasklet_rx_func(unsigned long data)
1750 {
1751         struct uart_port *port = (struct uart_port *)data;
1752         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1753
1754         /* The interrupt handler does not take the lock */
1755         spin_lock(&port->lock);
1756         atmel_port->schedule_rx(port);
1757         spin_unlock(&port->lock);
1758 }
1759
1760 static void atmel_tasklet_tx_func(unsigned long data)
1761 {
1762         struct uart_port *port = (struct uart_port *)data;
1763         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1764
1765         /* The interrupt handler does not take the lock */
1766         spin_lock(&port->lock);
1767         atmel_port->schedule_tx(port);
1768         spin_unlock(&port->lock);
1769 }
1770
1771 static void atmel_init_property(struct atmel_uart_port *atmel_port,
1772                                 struct platform_device *pdev)
1773 {
1774         struct device_node *np = pdev->dev.of_node;
1775
1776         /* DMA/PDC usage specification */
1777         if (of_property_read_bool(np, "atmel,use-dma-rx")) {
1778                 if (of_property_read_bool(np, "dmas")) {
1779                         atmel_port->use_dma_rx  = true;
1780                         atmel_port->use_pdc_rx  = false;
1781                 } else {
1782                         atmel_port->use_dma_rx  = false;
1783                         atmel_port->use_pdc_rx  = true;
1784                 }
1785         } else {
1786                 atmel_port->use_dma_rx  = false;
1787                 atmel_port->use_pdc_rx  = false;
1788         }
1789
1790         if (of_property_read_bool(np, "atmel,use-dma-tx")) {
1791                 if (of_property_read_bool(np, "dmas")) {
1792                         atmel_port->use_dma_tx  = true;
1793                         atmel_port->use_pdc_tx  = false;
1794                 } else {
1795                         atmel_port->use_dma_tx  = false;
1796                         atmel_port->use_pdc_tx  = true;
1797                 }
1798         } else {
1799                 atmel_port->use_dma_tx  = false;
1800                 atmel_port->use_pdc_tx  = false;
1801         }
1802 }
1803
1804 static void atmel_set_ops(struct uart_port *port)
1805 {
1806         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1807
1808         if (atmel_use_dma_rx(port)) {
1809                 atmel_port->prepare_rx = &atmel_prepare_rx_dma;
1810                 atmel_port->schedule_rx = &atmel_rx_from_dma;
1811                 atmel_port->release_rx = &atmel_release_rx_dma;
1812         } else if (atmel_use_pdc_rx(port)) {
1813                 atmel_port->prepare_rx = &atmel_prepare_rx_pdc;
1814                 atmel_port->schedule_rx = &atmel_rx_from_pdc;
1815                 atmel_port->release_rx = &atmel_release_rx_pdc;
1816         } else {
1817                 atmel_port->prepare_rx = NULL;
1818                 atmel_port->schedule_rx = &atmel_rx_from_ring;
1819                 atmel_port->release_rx = NULL;
1820         }
1821
1822         if (atmel_use_dma_tx(port)) {
1823                 atmel_port->prepare_tx = &atmel_prepare_tx_dma;
1824                 atmel_port->schedule_tx = &atmel_tx_dma;
1825                 atmel_port->release_tx = &atmel_release_tx_dma;
1826         } else if (atmel_use_pdc_tx(port)) {
1827                 atmel_port->prepare_tx = &atmel_prepare_tx_pdc;
1828                 atmel_port->schedule_tx = &atmel_tx_pdc;
1829                 atmel_port->release_tx = &atmel_release_tx_pdc;
1830         } else {
1831                 atmel_port->prepare_tx = NULL;
1832                 atmel_port->schedule_tx = &atmel_tx_chars;
1833                 atmel_port->release_tx = NULL;
1834         }
1835 }
1836
1837 /*
1838  * Get ip name usart or uart
1839  */
1840 static void atmel_get_ip_name(struct uart_port *port)
1841 {
1842         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1843         int name = atmel_uart_readl(port, ATMEL_US_NAME);
1844         u32 version;
1845         u32 usart, dbgu_uart, new_uart;
1846         /* ASCII decoding for IP version */
1847         usart = 0x55534152;     /* USAR(T) */
1848         dbgu_uart = 0x44424755; /* DBGU */
1849         new_uart = 0x55415254;  /* UART */
1850
1851         /*
1852          * Only USART devices from at91sam9260 SOC implement fractional
1853          * baudrate. It is available for all asynchronous modes, with the
1854          * following restriction: the sampling clock's duty cycle is not
1855          * constant.
1856          */
1857         atmel_port->has_frac_baudrate = false;
1858         atmel_port->has_hw_timer = false;
1859
1860         if (name == new_uart) {
1861                 dev_dbg(port->dev, "Uart with hw timer");
1862                 atmel_port->has_hw_timer = true;
1863                 atmel_port->rtor = ATMEL_UA_RTOR;
1864         } else if (name == usart) {
1865                 dev_dbg(port->dev, "Usart\n");
1866                 atmel_port->has_frac_baudrate = true;
1867                 atmel_port->has_hw_timer = true;
1868                 atmel_port->rtor = ATMEL_US_RTOR;
1869                 version = atmel_uart_readl(port, ATMEL_US_VERSION);
1870                 switch (version) {
1871                 case 0x814:     /* sama5d2 */
1872                         /* fall through */
1873                 case 0x701:     /* sama5d4 */
1874                         atmel_port->fidi_min = 3;
1875                         atmel_port->fidi_max = 65535;
1876                         break;
1877                 case 0x502:     /* sam9x5, sama5d3 */
1878                         atmel_port->fidi_min = 3;
1879                         atmel_port->fidi_max = 2047;
1880                         break;
1881                 default:
1882                         atmel_port->fidi_min = 1;
1883                         atmel_port->fidi_max = 2047;
1884                 }
1885         } else if (name == dbgu_uart) {
1886                 dev_dbg(port->dev, "Dbgu or uart without hw timer\n");
1887         } else {
1888                 /* fallback for older SoCs: use version field */
1889                 version = atmel_uart_readl(port, ATMEL_US_VERSION);
1890                 switch (version) {
1891                 case 0x302:
1892                 case 0x10213:
1893                 case 0x10302:
1894                         dev_dbg(port->dev, "This version is usart\n");
1895                         atmel_port->has_frac_baudrate = true;
1896                         atmel_port->has_hw_timer = true;
1897                         atmel_port->rtor = ATMEL_US_RTOR;
1898                         break;
1899                 case 0x203:
1900                 case 0x10202:
1901                         dev_dbg(port->dev, "This version is uart\n");
1902                         break;
1903                 default:
1904                         dev_err(port->dev, "Not supported ip name nor version, set to uart\n");
1905                 }
1906         }
1907 }
1908
1909 /*
1910  * Perform initialization and enable port for reception
1911  */
1912 static int atmel_startup(struct uart_port *port)
1913 {
1914         struct platform_device *pdev = to_platform_device(port->dev);
1915         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
1916         int retval;
1917
1918         /*
1919          * Ensure that no interrupts are enabled otherwise when
1920          * request_irq() is called we could get stuck trying to
1921          * handle an unexpected interrupt
1922          */
1923         atmel_uart_writel(port, ATMEL_US_IDR, -1);
1924         atmel_port->ms_irq_enabled = false;
1925
1926         /*
1927          * Allocate the IRQ
1928          */
1929         retval = request_irq(port->irq, atmel_interrupt,
1930                              IRQF_SHARED | IRQF_COND_SUSPEND,
1931                              dev_name(&pdev->dev), port);
1932         if (retval) {
1933                 dev_err(port->dev, "atmel_startup - Can't get irq\n");
1934                 return retval;
1935         }
1936
1937         atomic_set(&atmel_port->tasklet_shutdown, 0);
1938         tasklet_init(&atmel_port->tasklet_rx, atmel_tasklet_rx_func,
1939                         (unsigned long)port);
1940         tasklet_init(&atmel_port->tasklet_tx, atmel_tasklet_tx_func,
1941                         (unsigned long)port);
1942
1943         /*
1944          * Initialize DMA (if necessary)
1945          */
1946         atmel_init_property(atmel_port, pdev);
1947         atmel_set_ops(port);
1948
1949         if (atmel_port->prepare_rx) {
1950                 retval = atmel_port->prepare_rx(port);
1951                 if (retval < 0)
1952                         atmel_set_ops(port);
1953         }
1954
1955         if (atmel_port->prepare_tx) {
1956                 retval = atmel_port->prepare_tx(port);
1957                 if (retval < 0)
1958                         atmel_set_ops(port);
1959         }
1960
1961         /*
1962          * Enable FIFO when available
1963          */
1964         if (atmel_port->fifo_size) {
1965                 unsigned int txrdym = ATMEL_US_ONE_DATA;
1966                 unsigned int rxrdym = ATMEL_US_ONE_DATA;
1967                 unsigned int fmr;
1968
1969                 atmel_uart_writel(port, ATMEL_US_CR,
1970                                   ATMEL_US_FIFOEN |
1971                                   ATMEL_US_RXFCLR |
1972                                   ATMEL_US_TXFLCLR);
1973
1974                 if (atmel_use_dma_tx(port))
1975                         txrdym = ATMEL_US_FOUR_DATA;
1976
1977                 fmr = ATMEL_US_TXRDYM(txrdym) | ATMEL_US_RXRDYM(rxrdym);
1978                 if (atmel_port->rts_high &&
1979                     atmel_port->rts_low)
1980                         fmr |=  ATMEL_US_FRTSC |
1981                                 ATMEL_US_RXFTHRES(atmel_port->rts_high) |
1982                                 ATMEL_US_RXFTHRES2(atmel_port->rts_low);
1983
1984                 atmel_uart_writel(port, ATMEL_US_FMR, fmr);
1985         }
1986
1987         /* Save current CSR for comparison in atmel_tasklet_func() */
1988         atmel_port->irq_status_prev = atmel_get_lines_status(port);
1989
1990         /*
1991          * Finally, enable the serial port
1992          */
1993         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_RSTSTA | ATMEL_US_RSTRX);
1994         /* enable xmit & rcvr */
1995         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_TXEN | ATMEL_US_RXEN);
1996         atmel_port->tx_stopped = false;
1997
1998         timer_setup(&atmel_port->uart_timer, atmel_uart_timer_callback, 0);
1999
2000         if (atmel_use_pdc_rx(port)) {
2001                 /* set UART timeout */
2002                 if (!atmel_port->has_hw_timer) {
2003                         mod_timer(&atmel_port->uart_timer,
2004                                         jiffies + uart_poll_timeout(port));
2005                 /* set USART timeout */
2006                 } else {
2007                         atmel_uart_writel(port, atmel_port->rtor,
2008                                           PDC_RX_TIMEOUT);
2009                         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_STTTO);
2010
2011                         atmel_uart_writel(port, ATMEL_US_IER,
2012                                           ATMEL_US_ENDRX | ATMEL_US_TIMEOUT);
2013                 }
2014                 /* enable PDC controller */
2015                 atmel_uart_writel(port, ATMEL_PDC_PTCR, ATMEL_PDC_RXTEN);
2016         } else if (atmel_use_dma_rx(port)) {
2017                 /* set UART timeout */
2018                 if (!atmel_port->has_hw_timer) {
2019                         mod_timer(&atmel_port->uart_timer,
2020                                         jiffies + uart_poll_timeout(port));
2021                 /* set USART timeout */
2022                 } else {
2023                         atmel_uart_writel(port, atmel_port->rtor,
2024                                           PDC_RX_TIMEOUT);
2025                         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_STTTO);
2026
2027                         atmel_uart_writel(port, ATMEL_US_IER,
2028                                           ATMEL_US_TIMEOUT);
2029                 }
2030         } else {
2031                 /* enable receive only */
2032                 atmel_uart_writel(port, ATMEL_US_IER, ATMEL_US_RXRDY);
2033         }
2034
2035         return 0;
2036 }
2037
2038 /*
2039  * Flush any TX data submitted for DMA. Called when the TX circular
2040  * buffer is reset.
2041  */
2042 static void atmel_flush_buffer(struct uart_port *port)
2043 {
2044         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
2045
2046         if (atmel_use_pdc_tx(port)) {
2047                 atmel_uart_writel(port, ATMEL_PDC_TCR, 0);
2048                 atmel_port->pdc_tx.ofs = 0;
2049         }
2050         /*
2051          * in uart_flush_buffer(), the xmit circular buffer has just
2052          * been cleared, so we have to reset tx_len accordingly.
2053          */
2054         atmel_port->tx_len = 0;
2055 }
2056
2057 /*
2058  * Disable the port
2059  */
2060 static void atmel_shutdown(struct uart_port *port)
2061 {
2062         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
2063
2064         /* Disable modem control lines interrupts */
2065         atmel_disable_ms(port);
2066
2067         /* Disable interrupts at device level */
2068         atmel_uart_writel(port, ATMEL_US_IDR, -1);
2069
2070         /* Prevent spurious interrupts from scheduling the tasklet */
2071         atomic_inc(&atmel_port->tasklet_shutdown);
2072
2073         /*
2074          * Prevent any tasklets being scheduled during
2075          * cleanup
2076          */
2077         del_timer_sync(&atmel_port->uart_timer);
2078
2079         /* Make sure that no interrupt is on the fly */
2080         synchronize_irq(port->irq);
2081
2082         /*
2083          * Clear out any scheduled tasklets before
2084          * we destroy the buffers
2085          */
2086         tasklet_kill(&atmel_port->tasklet_rx);
2087         tasklet_kill(&atmel_port->tasklet_tx);
2088
2089         /*
2090          * Ensure everything is stopped and
2091          * disable port and break condition.
2092          */
2093         atmel_stop_rx(port);
2094         atmel_stop_tx(port);
2095
2096         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_RSTSTA);
2097
2098         /*
2099          * Shut-down the DMA.
2100          */
2101         if (atmel_port->release_rx)
2102                 atmel_port->release_rx(port);
2103         if (atmel_port->release_tx)
2104                 atmel_port->release_tx(port);
2105
2106         /*
2107          * Reset ring buffer pointers
2108          */
2109         atmel_port->rx_ring.head = 0;
2110         atmel_port->rx_ring.tail = 0;
2111
2112         /*
2113          * Free the interrupts
2114          */
2115         free_irq(port->irq, port);
2116
2117         atmel_flush_buffer(port);
2118 }
2119
2120 /*
2121  * Power / Clock management.
2122  */
2123 static void atmel_serial_pm(struct uart_port *port, unsigned int state,
2124                             unsigned int oldstate)
2125 {
2126         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
2127
2128         switch (state) {
2129         case 0:
2130                 /*
2131                  * Enable the peripheral clock for this serial port.
2132                  * This is called on uart_open() or a resume event.
2133                  */
2134                 clk_prepare_enable(atmel_port->clk);
2135
2136                 /* re-enable interrupts if we disabled some on suspend */
2137                 atmel_uart_writel(port, ATMEL_US_IER, atmel_port->backup_imr);
2138                 break;
2139         case 3:
2140                 /* Back up the interrupt mask and disable all interrupts */
2141                 atmel_port->backup_imr = atmel_uart_readl(port, ATMEL_US_IMR);
2142                 atmel_uart_writel(port, ATMEL_US_IDR, -1);
2143
2144                 /*
2145                  * Disable the peripheral clock for this serial port.
2146                  * This is called on uart_close() or a suspend event.
2147                  */
2148                 clk_disable_unprepare(atmel_port->clk);
2149                 break;
2150         default:
2151                 dev_err(port->dev, "atmel_serial: unknown pm %d\n", state);
2152         }
2153 }
2154
2155 /*
2156  * Change the port parameters
2157  */
2158 static void atmel_set_termios(struct uart_port *port, struct ktermios *termios,
2159                               struct ktermios *old)
2160 {
2161         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
2162         unsigned long flags;
2163         unsigned int old_mode, mode, imr, quot, baud, div, cd, fp = 0;
2164
2165         /* save the current mode register */
2166         mode = old_mode = atmel_uart_readl(port, ATMEL_US_MR);
2167
2168         /* reset the mode, clock divisor, parity, stop bits and data size */
2169         mode &= ~(ATMEL_US_USCLKS | ATMEL_US_CHRL | ATMEL_US_NBSTOP |
2170                   ATMEL_US_PAR | ATMEL_US_USMODE);
2171
2172         baud = uart_get_baud_rate(port, termios, old, 0, port->uartclk / 16);
2173
2174         /* byte size */
2175         switch (termios->c_cflag & CSIZE) {
2176         case CS5:
2177                 mode |= ATMEL_US_CHRL_5;
2178                 break;
2179         case CS6:
2180                 mode |= ATMEL_US_CHRL_6;
2181                 break;
2182         case CS7:
2183                 mode |= ATMEL_US_CHRL_7;
2184                 break;
2185         default:
2186                 mode |= ATMEL_US_CHRL_8;
2187                 break;
2188         }
2189
2190         /* stop bits */
2191         if (termios->c_cflag & CSTOPB)
2192                 mode |= ATMEL_US_NBSTOP_2;
2193
2194         /* parity */
2195         if (termios->c_cflag & PARENB) {
2196                 /* Mark or Space parity */
2197                 if (termios->c_cflag & CMSPAR) {
2198                         if (termios->c_cflag & PARODD)
2199                                 mode |= ATMEL_US_PAR_MARK;
2200                         else
2201                                 mode |= ATMEL_US_PAR_SPACE;
2202                 } else if (termios->c_cflag & PARODD)
2203                         mode |= ATMEL_US_PAR_ODD;
2204                 else
2205                         mode |= ATMEL_US_PAR_EVEN;
2206         } else
2207                 mode |= ATMEL_US_PAR_NONE;
2208
2209         spin_lock_irqsave(&port->lock, flags);
2210
2211         port->read_status_mask = ATMEL_US_OVRE;
2212         if (termios->c_iflag & INPCK)
2213                 port->read_status_mask |= (ATMEL_US_FRAME | ATMEL_US_PARE);
2214         if (termios->c_iflag & (IGNBRK | BRKINT | PARMRK))
2215                 port->read_status_mask |= ATMEL_US_RXBRK;
2216
2217         if (atmel_use_pdc_rx(port))
2218                 /* need to enable error interrupts */
2219                 atmel_uart_writel(port, ATMEL_US_IER, port->read_status_mask);
2220
2221         /*
2222          * Characters to ignore
2223          */
2224         port->ignore_status_mask = 0;
2225         if (termios->c_iflag & IGNPAR)
2226                 port->ignore_status_mask |= (ATMEL_US_FRAME | ATMEL_US_PARE);
2227         if (termios->c_iflag & IGNBRK) {
2228                 port->ignore_status_mask |= ATMEL_US_RXBRK;
2229                 /*
2230                  * If we're ignoring parity and break indicators,
2231                  * ignore overruns too (for real raw support).
2232                  */
2233                 if (termios->c_iflag & IGNPAR)
2234                         port->ignore_status_mask |= ATMEL_US_OVRE;
2235         }
2236         /* TODO: Ignore all characters if CREAD is set.*/
2237
2238         /* update the per-port timeout */
2239         uart_update_timeout(port, termios->c_cflag, baud);
2240
2241         /*
2242          * save/disable interrupts. The tty layer will ensure that the
2243          * transmitter is empty if requested by the caller, so there's
2244          * no need to wait for it here.
2245          */
2246         imr = atmel_uart_readl(port, ATMEL_US_IMR);
2247         atmel_uart_writel(port, ATMEL_US_IDR, -1);
2248
2249         /* disable receiver and transmitter */
2250         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_TXDIS | ATMEL_US_RXDIS);
2251         atmel_port->tx_stopped = true;
2252
2253         /* mode */
2254         if (port->rs485.flags & SER_RS485_ENABLED) {
2255                 atmel_uart_writel(port, ATMEL_US_TTGR,
2256                                   port->rs485.delay_rts_after_send);
2257                 mode |= ATMEL_US_USMODE_RS485;
2258         } else if (port->iso7816.flags & SER_ISO7816_ENABLED) {
2259                 atmel_uart_writel(port, ATMEL_US_TTGR, port->iso7816.tg);
2260                 /* select mck clock, and output  */
2261                 mode |= ATMEL_US_USCLKS_MCK | ATMEL_US_CLKO;
2262                 /* set max iterations */
2263                 mode |= ATMEL_US_MAX_ITER(3);
2264                 if ((port->iso7816.flags & SER_ISO7816_T_PARAM)
2265                                 == SER_ISO7816_T(0))
2266                         mode |= ATMEL_US_USMODE_ISO7816_T0;
2267                 else
2268                         mode |= ATMEL_US_USMODE_ISO7816_T1;
2269         } else if (termios->c_cflag & CRTSCTS) {
2270                 /* RS232 with hardware handshake (RTS/CTS) */
2271                 if (atmel_use_fifo(port) &&
2272                     !mctrl_gpio_to_gpiod(atmel_port->gpios, UART_GPIO_CTS)) {
2273                         /*
2274                          * with ATMEL_US_USMODE_HWHS set, the controller will
2275                          * be able to drive the RTS pin high/low when the RX
2276                          * FIFO is above RXFTHRES/below RXFTHRES2.
2277                          * It will also disable the transmitter when the CTS
2278                          * pin is high.
2279                          * This mode is not activated if CTS pin is a GPIO
2280                          * because in this case, the transmitter is always
2281                          * disabled (there must be an internal pull-up
2282                          * responsible for this behaviour).
2283                          * If the RTS pin is a GPIO, the controller won't be
2284                          * able to drive it according to the FIFO thresholds,
2285                          * but it will be handled by the driver.
2286                          */
2287                         mode |= ATMEL_US_USMODE_HWHS;
2288                 } else {
2289                         /*
2290                          * For platforms without FIFO, the flow control is
2291                          * handled by the driver.
2292                          */
2293                         mode |= ATMEL_US_USMODE_NORMAL;
2294                 }
2295         } else {
2296                 /* RS232 without hadware handshake */
2297                 mode |= ATMEL_US_USMODE_NORMAL;
2298         }
2299
2300         /* set the mode, clock divisor, parity, stop bits and data size */
2301         atmel_uart_writel(port, ATMEL_US_MR, mode);
2302
2303         /*
2304          * when switching the mode, set the RTS line state according to the
2305          * new mode, otherwise keep the former state
2306          */
2307         if ((old_mode & ATMEL_US_USMODE) != (mode & ATMEL_US_USMODE)) {
2308                 unsigned int rts_state;
2309
2310                 if ((mode & ATMEL_US_USMODE) == ATMEL_US_USMODE_HWHS) {
2311                         /* let the hardware control the RTS line */
2312                         rts_state = ATMEL_US_RTSDIS;
2313                 } else {
2314                         /* force RTS line to low level */
2315                         rts_state = ATMEL_US_RTSEN;
2316                 }
2317
2318                 atmel_uart_writel(port, ATMEL_US_CR, rts_state);
2319         }
2320
2321         /*
2322          * Set the baud rate:
2323          * Fractional baudrate allows to setup output frequency more
2324          * accurately. This feature is enabled only when using normal mode.
2325          * baudrate = selected clock / (8 * (2 - OVER) * (CD + FP / 8))
2326          * Currently, OVER is always set to 0 so we get
2327          * baudrate = selected clock / (16 * (CD + FP / 8))
2328          * then
2329          * 8 CD + FP = selected clock / (2 * baudrate)
2330          */
2331         if (atmel_port->has_frac_baudrate) {
2332                 div = DIV_ROUND_CLOSEST(port->uartclk, baud * 2);
2333                 cd = div >> 3;
2334                 fp = div & ATMEL_US_FP_MASK;
2335         } else {
2336                 cd = uart_get_divisor(port, baud);
2337         }
2338
2339         if (cd > 65535) {       /* BRGR is 16-bit, so switch to slower clock */
2340                 cd /= 8;
2341                 mode |= ATMEL_US_USCLKS_MCK_DIV8;
2342         }
2343         quot = cd | fp << ATMEL_US_FP_OFFSET;
2344
2345         if (!(port->iso7816.flags & SER_ISO7816_ENABLED))
2346                 atmel_uart_writel(port, ATMEL_US_BRGR, quot);
2347         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_RSTSTA | ATMEL_US_RSTRX);
2348         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_TXEN | ATMEL_US_RXEN);
2349         atmel_port->tx_stopped = false;
2350
2351         /* restore interrupts */
2352         atmel_uart_writel(port, ATMEL_US_IER, imr);
2353
2354         /* CTS flow-control and modem-status interrupts */
2355         if (UART_ENABLE_MS(port, termios->c_cflag))
2356                 atmel_enable_ms(port);
2357         else
2358                 atmel_disable_ms(port);
2359
2360         spin_unlock_irqrestore(&port->lock, flags);
2361 }
2362
2363 static void atmel_set_ldisc(struct uart_port *port, struct ktermios *termios)
2364 {
2365         if (termios->c_line == N_PPS) {
2366                 port->flags |= UPF_HARDPPS_CD;
2367                 spin_lock_irq(&port->lock);
2368                 atmel_enable_ms(port);
2369                 spin_unlock_irq(&port->lock);
2370         } else {
2371                 port->flags &= ~UPF_HARDPPS_CD;
2372                 if (!UART_ENABLE_MS(port, termios->c_cflag)) {
2373                         spin_lock_irq(&port->lock);
2374                         atmel_disable_ms(port);
2375                         spin_unlock_irq(&port->lock);
2376                 }
2377         }
2378 }
2379
2380 /*
2381  * Return string describing the specified port
2382  */
2383 static const char *atmel_type(struct uart_port *port)
2384 {
2385         return (port->type == PORT_ATMEL) ? "ATMEL_SERIAL" : NULL;
2386 }
2387
2388 /*
2389  * Release the memory region(s) being used by 'port'.
2390  */
2391 static void atmel_release_port(struct uart_port *port)
2392 {
2393         struct platform_device *mpdev = to_platform_device(port->dev->parent);
2394         int size = resource_size(mpdev->resource);
2395
2396         release_mem_region(port->mapbase, size);
2397
2398         if (port->flags & UPF_IOREMAP) {
2399                 iounmap(port->membase);
2400                 port->membase = NULL;
2401         }
2402 }
2403
2404 /*
2405  * Request the memory region(s) being used by 'port'.
2406  */
2407 static int atmel_request_port(struct uart_port *port)
2408 {
2409         struct platform_device *mpdev = to_platform_device(port->dev->parent);
2410         int size = resource_size(mpdev->resource);
2411
2412         if (!request_mem_region(port->mapbase, size, "atmel_serial"))
2413                 return -EBUSY;
2414
2415         if (port->flags & UPF_IOREMAP) {
2416                 port->membase = ioremap(port->mapbase, size);
2417                 if (port->membase == NULL) {
2418                         release_mem_region(port->mapbase, size);
2419                         return -ENOMEM;
2420                 }
2421         }
2422
2423         return 0;
2424 }
2425
2426 /*
2427  * Configure/autoconfigure the port.
2428  */
2429 static void atmel_config_port(struct uart_port *port, int flags)
2430 {
2431         if (flags & UART_CONFIG_TYPE) {
2432                 port->type = PORT_ATMEL;
2433                 atmel_request_port(port);
2434         }
2435 }
2436
2437 /*
2438  * Verify the new serial_struct (for TIOCSSERIAL).
2439  */
2440 static int atmel_verify_port(struct uart_port *port, struct serial_struct *ser)
2441 {
2442         int ret = 0;
2443         if (ser->type != PORT_UNKNOWN && ser->type != PORT_ATMEL)
2444                 ret = -EINVAL;
2445         if (port->irq != ser->irq)
2446                 ret = -EINVAL;
2447         if (ser->io_type != SERIAL_IO_MEM)
2448                 ret = -EINVAL;
2449         if (port->uartclk / 16 != ser->baud_base)
2450                 ret = -EINVAL;
2451         if (port->mapbase != (unsigned long)ser->iomem_base)
2452                 ret = -EINVAL;
2453         if (port->iobase != ser->port)
2454                 ret = -EINVAL;
2455         if (ser->hub6 != 0)
2456                 ret = -EINVAL;
2457         return ret;
2458 }
2459
2460 #ifdef CONFIG_CONSOLE_POLL
2461 static int atmel_poll_get_char(struct uart_port *port)
2462 {
2463         while (!(atmel_uart_readl(port, ATMEL_US_CSR) & ATMEL_US_RXRDY))
2464                 cpu_relax();
2465
2466         return atmel_uart_read_char(port);
2467 }
2468
2469 static void atmel_poll_put_char(struct uart_port *port, unsigned char ch)
2470 {
2471         while (!(atmel_uart_readl(port, ATMEL_US_CSR) & ATMEL_US_TXRDY))
2472                 cpu_relax();
2473
2474         atmel_uart_write_char(port, ch);
2475 }
2476 #endif
2477
2478 static const struct uart_ops atmel_pops = {
2479         .tx_empty       = atmel_tx_empty,
2480         .set_mctrl      = atmel_set_mctrl,
2481         .get_mctrl      = atmel_get_mctrl,
2482         .stop_tx        = atmel_stop_tx,
2483         .start_tx       = atmel_start_tx,
2484         .stop_rx        = atmel_stop_rx,
2485         .enable_ms      = atmel_enable_ms,
2486         .break_ctl      = atmel_break_ctl,
2487         .startup        = atmel_startup,
2488         .shutdown       = atmel_shutdown,
2489         .flush_buffer   = atmel_flush_buffer,
2490         .set_termios    = atmel_set_termios,
2491         .set_ldisc      = atmel_set_ldisc,
2492         .type           = atmel_type,
2493         .release_port   = atmel_release_port,
2494         .request_port   = atmel_request_port,
2495         .config_port    = atmel_config_port,
2496         .verify_port    = atmel_verify_port,
2497         .pm             = atmel_serial_pm,
2498 #ifdef CONFIG_CONSOLE_POLL
2499         .poll_get_char  = atmel_poll_get_char,
2500         .poll_put_char  = atmel_poll_put_char,
2501 #endif
2502 };
2503
2504 /*
2505  * Configure the port from the platform device resource info.
2506  */
2507 static int atmel_init_port(struct atmel_uart_port *atmel_port,
2508                                       struct platform_device *pdev)
2509 {
2510         int ret;
2511         struct uart_port *port = &atmel_port->uart;
2512         struct platform_device *mpdev = to_platform_device(pdev->dev.parent);
2513
2514         atmel_init_property(atmel_port, pdev);
2515         atmel_set_ops(port);
2516
2517         uart_get_rs485_mode(&mpdev->dev, &port->rs485);
2518
2519         port->iotype            = UPIO_MEM;
2520         port->flags             = UPF_BOOT_AUTOCONF | UPF_IOREMAP;
2521         port->ops               = &atmel_pops;
2522         port->fifosize          = 1;
2523         port->dev               = &pdev->dev;
2524         port->mapbase           = mpdev->resource[0].start;
2525         port->irq               = mpdev->resource[1].start;
2526         port->rs485_config      = atmel_config_rs485;
2527         port->iso7816_config    = atmel_config_iso7816;
2528         port->membase           = NULL;
2529
2530         memset(&atmel_port->rx_ring, 0, sizeof(atmel_port->rx_ring));
2531
2532         /* for console, the clock could already be configured */
2533         if (!atmel_port->clk) {
2534                 atmel_port->clk = clk_get(&mpdev->dev, "usart");
2535                 if (IS_ERR(atmel_port->clk)) {
2536                         ret = PTR_ERR(atmel_port->clk);
2537                         atmel_port->clk = NULL;
2538                         return ret;
2539                 }
2540                 ret = clk_prepare_enable(atmel_port->clk);
2541                 if (ret) {
2542                         clk_put(atmel_port->clk);
2543                         atmel_port->clk = NULL;
2544                         return ret;
2545                 }
2546                 port->uartclk = clk_get_rate(atmel_port->clk);
2547                 clk_disable_unprepare(atmel_port->clk);
2548                 /* only enable clock when USART is in use */
2549         }
2550
2551         /*
2552          * Use TXEMPTY for interrupt when rs485 or ISO7816 else TXRDY or
2553          * ENDTX|TXBUFE
2554          */
2555         if (port->rs485.flags & SER_RS485_ENABLED ||
2556             port->iso7816.flags & SER_ISO7816_ENABLED)
2557                 atmel_port->tx_done_mask = ATMEL_US_TXEMPTY;
2558         else if (atmel_use_pdc_tx(port)) {
2559                 port->fifosize = PDC_BUFFER_SIZE;
2560                 atmel_port->tx_done_mask = ATMEL_US_ENDTX | ATMEL_US_TXBUFE;
2561         } else {
2562                 atmel_port->tx_done_mask = ATMEL_US_TXRDY;
2563         }
2564
2565         return 0;
2566 }
2567
2568 #ifdef CONFIG_SERIAL_ATMEL_CONSOLE
2569 static void atmel_console_putchar(struct uart_port *port, int ch)
2570 {
2571         while (!(atmel_uart_readl(port, ATMEL_US_CSR) & ATMEL_US_TXRDY))
2572                 cpu_relax();
2573         atmel_uart_write_char(port, ch);
2574 }
2575
2576 /*
2577  * Interrupts are disabled on entering
2578  */
2579 static void atmel_console_write(struct console *co, const char *s, u_int count)
2580 {
2581         struct uart_port *port = &atmel_ports[co->index].uart;
2582         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
2583         unsigned int status, imr;
2584         unsigned int pdc_tx;
2585
2586         /*
2587          * First, save IMR and then disable interrupts
2588          */
2589         imr = atmel_uart_readl(port, ATMEL_US_IMR);
2590         atmel_uart_writel(port, ATMEL_US_IDR,
2591                           ATMEL_US_RXRDY | atmel_port->tx_done_mask);
2592
2593         /* Store PDC transmit status and disable it */
2594         pdc_tx = atmel_uart_readl(port, ATMEL_PDC_PTSR) & ATMEL_PDC_TXTEN;
2595         atmel_uart_writel(port, ATMEL_PDC_PTCR, ATMEL_PDC_TXTDIS);
2596
2597         /* Make sure that tx path is actually able to send characters */
2598         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_TXEN);
2599         atmel_port->tx_stopped = false;
2600
2601         uart_console_write(port, s, count, atmel_console_putchar);
2602
2603         /*
2604          * Finally, wait for transmitter to become empty
2605          * and restore IMR
2606          */
2607         do {
2608                 status = atmel_uart_readl(port, ATMEL_US_CSR);
2609         } while (!(status & ATMEL_US_TXRDY));
2610
2611         /* Restore PDC transmit status */
2612         if (pdc_tx)
2613                 atmel_uart_writel(port, ATMEL_PDC_PTCR, ATMEL_PDC_TXTEN);
2614
2615         /* set interrupts back the way they were */
2616         atmel_uart_writel(port, ATMEL_US_IER, imr);
2617 }
2618
2619 /*
2620  * If the port was already initialised (eg, by a boot loader),
2621  * try to determine the current setup.
2622  */
2623 static void __init atmel_console_get_options(struct uart_port *port, int *baud,
2624                                              int *parity, int *bits)
2625 {
2626         unsigned int mr, quot;
2627
2628         /*
2629          * If the baud rate generator isn't running, the port wasn't
2630          * initialized by the boot loader.
2631          */
2632         quot = atmel_uart_readl(port, ATMEL_US_BRGR) & ATMEL_US_CD;
2633         if (!quot)
2634                 return;
2635
2636         mr = atmel_uart_readl(port, ATMEL_US_MR) & ATMEL_US_CHRL;
2637         if (mr == ATMEL_US_CHRL_8)
2638                 *bits = 8;
2639         else
2640                 *bits = 7;
2641
2642         mr = atmel_uart_readl(port, ATMEL_US_MR) & ATMEL_US_PAR;
2643         if (mr == ATMEL_US_PAR_EVEN)
2644                 *parity = 'e';
2645         else if (mr == ATMEL_US_PAR_ODD)
2646                 *parity = 'o';
2647
2648         /*
2649          * The serial core only rounds down when matching this to a
2650          * supported baud rate. Make sure we don't end up slightly
2651          * lower than one of those, as it would make us fall through
2652          * to a much lower baud rate than we really want.
2653          */
2654         *baud = port->uartclk / (16 * (quot - 1));
2655 }
2656
2657 static int __init atmel_console_setup(struct console *co, char *options)
2658 {
2659         int ret;
2660         struct uart_port *port = &atmel_ports[co->index].uart;
2661         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
2662         int baud = 115200;
2663         int bits = 8;
2664         int parity = 'n';
2665         int flow = 'n';
2666
2667         if (port->membase == NULL) {
2668                 /* Port not initialized yet - delay setup */
2669                 return -ENODEV;
2670         }
2671
2672         ret = clk_prepare_enable(atmel_ports[co->index].clk);
2673         if (ret)
2674                 return ret;
2675
2676         atmel_uart_writel(port, ATMEL_US_IDR, -1);
2677         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_RSTSTA | ATMEL_US_RSTRX);
2678         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_TXEN | ATMEL_US_RXEN);
2679         atmel_port->tx_stopped = false;
2680
2681         if (options)
2682                 uart_parse_options(options, &baud, &parity, &bits, &flow);
2683         else
2684                 atmel_console_get_options(port, &baud, &parity, &bits);
2685
2686         return uart_set_options(port, co, baud, parity, bits, flow);
2687 }
2688
2689 static struct uart_driver atmel_uart;
2690
2691 static struct console atmel_console = {
2692         .name           = ATMEL_DEVICENAME,
2693         .write          = atmel_console_write,
2694         .device         = uart_console_device,
2695         .setup          = atmel_console_setup,
2696         .flags          = CON_PRINTBUFFER,
2697         .index          = -1,
2698         .data           = &atmel_uart,
2699 };
2700
2701 #define ATMEL_CONSOLE_DEVICE    (&atmel_console)
2702
2703 static inline bool atmel_is_console_port(struct uart_port *port)
2704 {
2705         return port->cons && port->cons->index == port->line;
2706 }
2707
2708 #else
2709 #define ATMEL_CONSOLE_DEVICE    NULL
2710
2711 static inline bool atmel_is_console_port(struct uart_port *port)
2712 {
2713         return false;
2714 }
2715 #endif
2716
2717 static struct uart_driver atmel_uart = {
2718         .owner          = THIS_MODULE,
2719         .driver_name    = "atmel_serial",
2720         .dev_name       = ATMEL_DEVICENAME,
2721         .major          = SERIAL_ATMEL_MAJOR,
2722         .minor          = MINOR_START,
2723         .nr             = ATMEL_MAX_UART,
2724         .cons           = ATMEL_CONSOLE_DEVICE,
2725 };
2726
2727 #ifdef CONFIG_PM
2728 static bool atmel_serial_clk_will_stop(void)
2729 {
2730 #ifdef CONFIG_ARCH_AT91
2731         return at91_suspend_entering_slow_clock();
2732 #else
2733         return false;
2734 #endif
2735 }
2736
2737 static int atmel_serial_suspend(struct platform_device *pdev,
2738                                 pm_message_t state)
2739 {
2740         struct uart_port *port = platform_get_drvdata(pdev);
2741         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
2742
2743         if (atmel_is_console_port(port) && console_suspend_enabled) {
2744                 /* Drain the TX shifter */
2745                 while (!(atmel_uart_readl(port, ATMEL_US_CSR) &
2746                          ATMEL_US_TXEMPTY))
2747                         cpu_relax();
2748         }
2749
2750         if (atmel_is_console_port(port) && !console_suspend_enabled) {
2751                 /* Cache register values as we won't get a full shutdown/startup
2752                  * cycle
2753                  */
2754                 atmel_port->cache.mr = atmel_uart_readl(port, ATMEL_US_MR);
2755                 atmel_port->cache.imr = atmel_uart_readl(port, ATMEL_US_IMR);
2756                 atmel_port->cache.brgr = atmel_uart_readl(port, ATMEL_US_BRGR);
2757                 atmel_port->cache.rtor = atmel_uart_readl(port,
2758                                                           atmel_port->rtor);
2759                 atmel_port->cache.ttgr = atmel_uart_readl(port, ATMEL_US_TTGR);
2760                 atmel_port->cache.fmr = atmel_uart_readl(port, ATMEL_US_FMR);
2761                 atmel_port->cache.fimr = atmel_uart_readl(port, ATMEL_US_FIMR);
2762         }
2763
2764         /* we can not wake up if we're running on slow clock */
2765         atmel_port->may_wakeup = device_may_wakeup(&pdev->dev);
2766         if (atmel_serial_clk_will_stop()) {
2767                 unsigned long flags;
2768
2769                 spin_lock_irqsave(&atmel_port->lock_suspended, flags);
2770                 atmel_port->suspended = true;
2771                 spin_unlock_irqrestore(&atmel_port->lock_suspended, flags);
2772                 device_set_wakeup_enable(&pdev->dev, 0);
2773         }
2774
2775         uart_suspend_port(&atmel_uart, port);
2776
2777         return 0;
2778 }
2779
2780 static int atmel_serial_resume(struct platform_device *pdev)
2781 {
2782         struct uart_port *port = platform_get_drvdata(pdev);
2783         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
2784         unsigned long flags;
2785
2786         if (atmel_is_console_port(port) && !console_suspend_enabled) {
2787                 atmel_uart_writel(port, ATMEL_US_MR, atmel_port->cache.mr);
2788                 atmel_uart_writel(port, ATMEL_US_IER, atmel_port->cache.imr);
2789                 atmel_uart_writel(port, ATMEL_US_BRGR, atmel_port->cache.brgr);
2790                 atmel_uart_writel(port, atmel_port->rtor,
2791                                   atmel_port->cache.rtor);
2792                 atmel_uart_writel(port, ATMEL_US_TTGR, atmel_port->cache.ttgr);
2793
2794                 if (atmel_port->fifo_size) {
2795                         atmel_uart_writel(port, ATMEL_US_CR, ATMEL_US_FIFOEN |
2796                                           ATMEL_US_RXFCLR | ATMEL_US_TXFLCLR);
2797                         atmel_uart_writel(port, ATMEL_US_FMR,
2798                                           atmel_port->cache.fmr);
2799                         atmel_uart_writel(port, ATMEL_US_FIER,
2800                                           atmel_port->cache.fimr);
2801                 }
2802                 atmel_start_rx(port);
2803         }
2804
2805         spin_lock_irqsave(&atmel_port->lock_suspended, flags);
2806         if (atmel_port->pending) {
2807                 atmel_handle_receive(port, atmel_port->pending);
2808                 atmel_handle_status(port, atmel_port->pending,
2809                                     atmel_port->pending_status);
2810                 atmel_handle_transmit(port, atmel_port->pending);
2811                 atmel_port->pending = 0;
2812         }
2813         atmel_port->suspended = false;
2814         spin_unlock_irqrestore(&atmel_port->lock_suspended, flags);
2815
2816         uart_resume_port(&atmel_uart, port);
2817         device_set_wakeup_enable(&pdev->dev, atmel_port->may_wakeup);
2818
2819         return 0;
2820 }
2821 #else
2822 #define atmel_serial_suspend NULL
2823 #define atmel_serial_resume NULL
2824 #endif
2825
2826 static void atmel_serial_probe_fifos(struct atmel_uart_port *atmel_port,
2827                                      struct platform_device *pdev)
2828 {
2829         atmel_port->fifo_size = 0;
2830         atmel_port->rts_low = 0;
2831         atmel_port->rts_high = 0;
2832
2833         if (of_property_read_u32(pdev->dev.of_node,
2834                                  "atmel,fifo-size",
2835                                  &atmel_port->fifo_size))
2836                 return;
2837
2838         if (!atmel_port->fifo_size)
2839                 return;
2840
2841         if (atmel_port->fifo_size < ATMEL_MIN_FIFO_SIZE) {
2842                 atmel_port->fifo_size = 0;
2843                 dev_err(&pdev->dev, "Invalid FIFO size\n");
2844                 return;
2845         }
2846
2847         /*
2848          * 0 <= rts_low <= rts_high <= fifo_size
2849          * Once their CTS line asserted by the remote peer, some x86 UARTs tend
2850          * to flush their internal TX FIFO, commonly up to 16 data, before
2851          * actually stopping to send new data. So we try to set the RTS High
2852          * Threshold to a reasonably high value respecting this 16 data
2853          * empirical rule when possible.
2854          */
2855         atmel_port->rts_high = max_t(int, atmel_port->fifo_size >> 1,
2856                                atmel_port->fifo_size - ATMEL_RTS_HIGH_OFFSET);
2857         atmel_port->rts_low  = max_t(int, atmel_port->fifo_size >> 2,
2858                                atmel_port->fifo_size - ATMEL_RTS_LOW_OFFSET);
2859
2860         dev_info(&pdev->dev, "Using FIFO (%u data)\n",
2861                  atmel_port->fifo_size);
2862         dev_dbg(&pdev->dev, "RTS High Threshold : %2u data\n",
2863                 atmel_port->rts_high);
2864         dev_dbg(&pdev->dev, "RTS Low Threshold  : %2u data\n",
2865                 atmel_port->rts_low);
2866 }
2867
2868 static int atmel_serial_probe(struct platform_device *pdev)
2869 {
2870         struct atmel_uart_port *atmel_port;
2871         struct device_node *np = pdev->dev.parent->of_node;
2872         void *data;
2873         int ret = -ENODEV;
2874         bool rs485_enabled;
2875
2876         BUILD_BUG_ON(ATMEL_SERIAL_RINGSIZE & (ATMEL_SERIAL_RINGSIZE - 1));
2877
2878         /*
2879          * In device tree there is no node with "atmel,at91rm9200-usart-serial"
2880          * as compatible string. This driver is probed by at91-usart mfd driver
2881          * which is just a wrapper over the atmel_serial driver and
2882          * spi-at91-usart driver. All attributes needed by this driver are
2883          * found in of_node of parent.
2884          */
2885         pdev->dev.of_node = np;
2886
2887         ret = of_alias_get_id(np, "serial");
2888         if (ret < 0)
2889                 /* port id not found in platform data nor device-tree aliases:
2890                  * auto-enumerate it */
2891                 ret = find_first_zero_bit(atmel_ports_in_use, ATMEL_MAX_UART);
2892
2893         if (ret >= ATMEL_MAX_UART) {
2894                 ret = -ENODEV;
2895                 goto err;
2896         }
2897
2898         if (test_and_set_bit(ret, atmel_ports_in_use)) {
2899                 /* port already in use */
2900                 ret = -EBUSY;
2901                 goto err;
2902         }
2903
2904         atmel_port = &atmel_ports[ret];
2905         atmel_port->backup_imr = 0;
2906         atmel_port->uart.line = ret;
2907         atmel_serial_probe_fifos(atmel_port, pdev);
2908
2909         atomic_set(&atmel_port->tasklet_shutdown, 0);
2910         spin_lock_init(&atmel_port->lock_suspended);
2911
2912         ret = atmel_init_port(atmel_port, pdev);
2913         if (ret)
2914                 goto err_clear_bit;
2915
2916         atmel_port->gpios = mctrl_gpio_init(&atmel_port->uart, 0);
2917         if (IS_ERR(atmel_port->gpios)) {
2918                 ret = PTR_ERR(atmel_port->gpios);
2919                 goto err_clear_bit;
2920         }
2921
2922         if (!atmel_use_pdc_rx(&atmel_port->uart)) {
2923                 ret = -ENOMEM;
2924                 data = kmalloc_array(ATMEL_SERIAL_RINGSIZE,
2925                                      sizeof(struct atmel_uart_char),
2926                                      GFP_KERNEL);
2927                 if (!data)
2928                         goto err_alloc_ring;
2929                 atmel_port->rx_ring.buf = data;
2930         }
2931
2932         rs485_enabled = atmel_port->uart.rs485.flags & SER_RS485_ENABLED;
2933
2934         ret = uart_add_one_port(&atmel_uart, &atmel_port->uart);
2935         if (ret)
2936                 goto err_add_port;
2937
2938 #ifdef CONFIG_SERIAL_ATMEL_CONSOLE
2939         if (atmel_is_console_port(&atmel_port->uart)
2940                         && ATMEL_CONSOLE_DEVICE->flags & CON_ENABLED) {
2941                 /*
2942                  * The serial core enabled the clock for us, so undo
2943                  * the clk_prepare_enable() in atmel_console_setup()
2944                  */
2945                 clk_disable_unprepare(atmel_port->clk);
2946         }
2947 #endif
2948
2949         device_init_wakeup(&pdev->dev, 1);
2950         platform_set_drvdata(pdev, atmel_port);
2951
2952         /*
2953          * The peripheral clock has been disabled by atmel_init_port():
2954          * enable it before accessing I/O registers
2955          */
2956         clk_prepare_enable(atmel_port->clk);
2957
2958         if (rs485_enabled) {
2959                 atmel_uart_writel(&atmel_port->uart, ATMEL_US_MR,
2960                                   ATMEL_US_USMODE_NORMAL);
2961                 atmel_uart_writel(&atmel_port->uart, ATMEL_US_CR,
2962                                   ATMEL_US_RTSEN);
2963         }
2964
2965         /*
2966          * Get port name of usart or uart
2967          */
2968         atmel_get_ip_name(&atmel_port->uart);
2969
2970         /*
2971          * The peripheral clock can now safely be disabled till the port
2972          * is used
2973          */
2974         clk_disable_unprepare(atmel_port->clk);
2975
2976         return 0;
2977
2978 err_add_port:
2979         kfree(atmel_port->rx_ring.buf);
2980         atmel_port->rx_ring.buf = NULL;
2981 err_alloc_ring:
2982         if (!atmel_is_console_port(&atmel_port->uart)) {
2983                 clk_put(atmel_port->clk);
2984                 atmel_port->clk = NULL;
2985         }
2986 err_clear_bit:
2987         clear_bit(atmel_port->uart.line, atmel_ports_in_use);
2988 err:
2989         return ret;
2990 }
2991
2992 /*
2993  * Even if the driver is not modular, it makes sense to be able to
2994  * unbind a device: there can be many bound devices, and there are
2995  * situations where dynamic binding and unbinding can be useful.
2996  *
2997  * For example, a connected device can require a specific firmware update
2998  * protocol that needs bitbanging on IO lines, but use the regular serial
2999  * port in the normal case.
3000  */
3001 static int atmel_serial_remove(struct platform_device *pdev)
3002 {
3003         struct uart_port *port = platform_get_drvdata(pdev);
3004         struct atmel_uart_port *atmel_port = to_atmel_uart_port(port);
3005         int ret = 0;
3006
3007         tasklet_kill(&atmel_port->tasklet_rx);
3008         tasklet_kill(&atmel_port->tasklet_tx);
3009
3010         device_init_wakeup(&pdev->dev, 0);
3011
3012         ret = uart_remove_one_port(&atmel_uart, port);
3013
3014         kfree(atmel_port->rx_ring.buf);
3015
3016         /* "port" is allocated statically, so we shouldn't free it */
3017
3018         clear_bit(port->line, atmel_ports_in_use);
3019
3020         clk_put(atmel_port->clk);
3021         atmel_port->clk = NULL;
3022         pdev->dev.of_node = NULL;
3023
3024         return ret;
3025 }
3026
3027 static struct platform_driver atmel_serial_driver = {
3028         .probe          = atmel_serial_probe,
3029         .remove         = atmel_serial_remove,
3030         .suspend        = atmel_serial_suspend,
3031         .resume         = atmel_serial_resume,
3032         .driver         = {
3033                 .name                   = "atmel_usart_serial",
3034                 .of_match_table         = of_match_ptr(atmel_serial_dt_ids),
3035         },
3036 };
3037
3038 static int __init atmel_serial_init(void)
3039 {
3040         int ret;
3041
3042         ret = uart_register_driver(&atmel_uart);
3043         if (ret)
3044                 return ret;
3045
3046         ret = platform_driver_register(&atmel_serial_driver);
3047         if (ret)
3048                 uart_unregister_driver(&atmel_uart);
3049
3050         return ret;
3051 }
3052 device_initcall(atmel_serial_init);