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