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