OSDN Git Service

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