serial: stm32: add earlycon support
[linux-2.6-microblaze.git] / drivers / tty / serial / stm32-usart.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) Maxime Coquelin 2015
4  * Copyright (C) STMicroelectronics SA 2017
5  * Authors:  Maxime Coquelin <mcoquelin.stm32@gmail.com>
6  *           Gerald Baeza <gerald.baeza@foss.st.com>
7  *           Erwan Le Ray <erwan.leray@foss.st.com>
8  *
9  * Inspired by st-asc.c from STMicroelectronics (c)
10  */
11
12 #include <linux/clk.h>
13 #include <linux/console.h>
14 #include <linux/delay.h>
15 #include <linux/dma-direction.h>
16 #include <linux/dmaengine.h>
17 #include <linux/dma-mapping.h>
18 #include <linux/io.h>
19 #include <linux/iopoll.h>
20 #include <linux/irq.h>
21 #include <linux/module.h>
22 #include <linux/of.h>
23 #include <linux/of_platform.h>
24 #include <linux/pinctrl/consumer.h>
25 #include <linux/platform_device.h>
26 #include <linux/pm_runtime.h>
27 #include <linux/pm_wakeirq.h>
28 #include <linux/serial_core.h>
29 #include <linux/serial.h>
30 #include <linux/spinlock.h>
31 #include <linux/sysrq.h>
32 #include <linux/tty_flip.h>
33 #include <linux/tty.h>
34
35 #include "serial_mctrl_gpio.h"
36 #include "stm32-usart.h"
37
38 static void stm32_usart_stop_tx(struct uart_port *port);
39 static void stm32_usart_transmit_chars(struct uart_port *port);
40 static void __maybe_unused stm32_usart_console_putchar(struct uart_port *port, unsigned char ch);
41
42 static inline struct stm32_port *to_stm32_port(struct uart_port *port)
43 {
44         return container_of(port, struct stm32_port, port);
45 }
46
47 static void stm32_usart_set_bits(struct uart_port *port, u32 reg, u32 bits)
48 {
49         u32 val;
50
51         val = readl_relaxed(port->membase + reg);
52         val |= bits;
53         writel_relaxed(val, port->membase + reg);
54 }
55
56 static void stm32_usart_clr_bits(struct uart_port *port, u32 reg, u32 bits)
57 {
58         u32 val;
59
60         val = readl_relaxed(port->membase + reg);
61         val &= ~bits;
62         writel_relaxed(val, port->membase + reg);
63 }
64
65 static void stm32_usart_config_reg_rs485(u32 *cr1, u32 *cr3, u32 delay_ADE,
66                                          u32 delay_DDE, u32 baud)
67 {
68         u32 rs485_deat_dedt;
69         u32 rs485_deat_dedt_max = (USART_CR1_DEAT_MASK >> USART_CR1_DEAT_SHIFT);
70         bool over8;
71
72         *cr3 |= USART_CR3_DEM;
73         over8 = *cr1 & USART_CR1_OVER8;
74
75         if (over8)
76                 rs485_deat_dedt = delay_ADE * baud * 8;
77         else
78                 rs485_deat_dedt = delay_ADE * baud * 16;
79
80         rs485_deat_dedt = DIV_ROUND_CLOSEST(rs485_deat_dedt, 1000);
81         rs485_deat_dedt = rs485_deat_dedt > rs485_deat_dedt_max ?
82                           rs485_deat_dedt_max : rs485_deat_dedt;
83         rs485_deat_dedt = (rs485_deat_dedt << USART_CR1_DEAT_SHIFT) &
84                            USART_CR1_DEAT_MASK;
85         *cr1 |= rs485_deat_dedt;
86
87         if (over8)
88                 rs485_deat_dedt = delay_DDE * baud * 8;
89         else
90                 rs485_deat_dedt = delay_DDE * baud * 16;
91
92         rs485_deat_dedt = DIV_ROUND_CLOSEST(rs485_deat_dedt, 1000);
93         rs485_deat_dedt = rs485_deat_dedt > rs485_deat_dedt_max ?
94                           rs485_deat_dedt_max : rs485_deat_dedt;
95         rs485_deat_dedt = (rs485_deat_dedt << USART_CR1_DEDT_SHIFT) &
96                            USART_CR1_DEDT_MASK;
97         *cr1 |= rs485_deat_dedt;
98 }
99
100 static int stm32_usart_config_rs485(struct uart_port *port,
101                                     struct serial_rs485 *rs485conf)
102 {
103         struct stm32_port *stm32_port = to_stm32_port(port);
104         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
105         const struct stm32_usart_config *cfg = &stm32_port->info->cfg;
106         u32 usartdiv, baud, cr1, cr3;
107         bool over8;
108
109         stm32_usart_clr_bits(port, ofs->cr1, BIT(cfg->uart_enable_bit));
110
111         rs485conf->flags |= SER_RS485_RX_DURING_TX;
112
113         if (rs485conf->flags & SER_RS485_ENABLED) {
114                 cr1 = readl_relaxed(port->membase + ofs->cr1);
115                 cr3 = readl_relaxed(port->membase + ofs->cr3);
116                 usartdiv = readl_relaxed(port->membase + ofs->brr);
117                 usartdiv = usartdiv & GENMASK(15, 0);
118                 over8 = cr1 & USART_CR1_OVER8;
119
120                 if (over8)
121                         usartdiv = usartdiv | (usartdiv & GENMASK(4, 0))
122                                    << USART_BRR_04_R_SHIFT;
123
124                 baud = DIV_ROUND_CLOSEST(port->uartclk, usartdiv);
125                 stm32_usart_config_reg_rs485(&cr1, &cr3,
126                                              rs485conf->delay_rts_before_send,
127                                              rs485conf->delay_rts_after_send,
128                                              baud);
129
130                 if (rs485conf->flags & SER_RS485_RTS_ON_SEND)
131                         cr3 &= ~USART_CR3_DEP;
132                 else
133                         cr3 |= USART_CR3_DEP;
134
135                 writel_relaxed(cr3, port->membase + ofs->cr3);
136                 writel_relaxed(cr1, port->membase + ofs->cr1);
137         } else {
138                 stm32_usart_clr_bits(port, ofs->cr3,
139                                      USART_CR3_DEM | USART_CR3_DEP);
140                 stm32_usart_clr_bits(port, ofs->cr1,
141                                      USART_CR1_DEDT_MASK | USART_CR1_DEAT_MASK);
142         }
143
144         stm32_usart_set_bits(port, ofs->cr1, BIT(cfg->uart_enable_bit));
145
146         return 0;
147 }
148
149 static int stm32_usart_init_rs485(struct uart_port *port,
150                                   struct platform_device *pdev)
151 {
152         struct serial_rs485 *rs485conf = &port->rs485;
153
154         rs485conf->flags = 0;
155         rs485conf->delay_rts_before_send = 0;
156         rs485conf->delay_rts_after_send = 0;
157
158         if (!pdev->dev.of_node)
159                 return -ENODEV;
160
161         return uart_get_rs485_mode(port);
162 }
163
164 static bool stm32_usart_rx_dma_enabled(struct uart_port *port)
165 {
166         struct stm32_port *stm32_port = to_stm32_port(port);
167         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
168
169         if (!stm32_port->rx_ch)
170                 return false;
171
172         return !!(readl_relaxed(port->membase + ofs->cr3) & USART_CR3_DMAR);
173 }
174
175 /* Return true when data is pending (in pio mode), and false when no data is pending. */
176 static bool stm32_usart_pending_rx_pio(struct uart_port *port, u32 *sr)
177 {
178         struct stm32_port *stm32_port = to_stm32_port(port);
179         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
180
181         *sr = readl_relaxed(port->membase + ofs->isr);
182         /* Get pending characters in RDR or FIFO */
183         if (*sr & USART_SR_RXNE) {
184                 /* Get all pending characters from the RDR or the FIFO when using interrupts */
185                 if (!stm32_usart_rx_dma_enabled(port))
186                         return true;
187
188                 /* Handle only RX data errors when using DMA */
189                 if (*sr & USART_SR_ERR_MASK)
190                         return true;
191         }
192
193         return false;
194 }
195
196 static unsigned long stm32_usart_get_char_pio(struct uart_port *port)
197 {
198         struct stm32_port *stm32_port = to_stm32_port(port);
199         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
200         unsigned long c;
201
202         c = readl_relaxed(port->membase + ofs->rdr);
203         /* Apply RDR data mask */
204         c &= stm32_port->rdr_mask;
205
206         return c;
207 }
208
209 static unsigned int stm32_usart_receive_chars_pio(struct uart_port *port)
210 {
211         struct stm32_port *stm32_port = to_stm32_port(port);
212         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
213         unsigned long c;
214         unsigned int size = 0;
215         u32 sr;
216         char flag;
217
218         while (stm32_usart_pending_rx_pio(port, &sr)) {
219                 sr |= USART_SR_DUMMY_RX;
220                 flag = TTY_NORMAL;
221
222                 /*
223                  * Status bits has to be cleared before reading the RDR:
224                  * In FIFO mode, reading the RDR will pop the next data
225                  * (if any) along with its status bits into the SR.
226                  * Not doing so leads to misalignement between RDR and SR,
227                  * and clear status bits of the next rx data.
228                  *
229                  * Clear errors flags for stm32f7 and stm32h7 compatible
230                  * devices. On stm32f4 compatible devices, the error bit is
231                  * cleared by the sequence [read SR - read DR].
232                  */
233                 if ((sr & USART_SR_ERR_MASK) && ofs->icr != UNDEF_REG)
234                         writel_relaxed(sr & USART_SR_ERR_MASK,
235                                        port->membase + ofs->icr);
236
237                 c = stm32_usart_get_char_pio(port);
238                 port->icount.rx++;
239                 size++;
240                 if (sr & USART_SR_ERR_MASK) {
241                         if (sr & USART_SR_ORE) {
242                                 port->icount.overrun++;
243                         } else if (sr & USART_SR_PE) {
244                                 port->icount.parity++;
245                         } else if (sr & USART_SR_FE) {
246                                 /* Break detection if character is null */
247                                 if (!c) {
248                                         port->icount.brk++;
249                                         if (uart_handle_break(port))
250                                                 continue;
251                                 } else {
252                                         port->icount.frame++;
253                                 }
254                         }
255
256                         sr &= port->read_status_mask;
257
258                         if (sr & USART_SR_PE) {
259                                 flag = TTY_PARITY;
260                         } else if (sr & USART_SR_FE) {
261                                 if (!c)
262                                         flag = TTY_BREAK;
263                                 else
264                                         flag = TTY_FRAME;
265                         }
266                 }
267
268                 if (uart_prepare_sysrq_char(port, c))
269                         continue;
270                 uart_insert_char(port, sr, USART_SR_ORE, c, flag);
271         }
272
273         return size;
274 }
275
276 static void stm32_usart_push_buffer_dma(struct uart_port *port, unsigned int dma_size)
277 {
278         struct stm32_port *stm32_port = to_stm32_port(port);
279         struct tty_port *ttyport = &stm32_port->port.state->port;
280         unsigned char *dma_start;
281         int dma_count, i;
282
283         dma_start = stm32_port->rx_buf + (RX_BUF_L - stm32_port->last_res);
284
285         /*
286          * Apply rdr_mask on buffer in order to mask parity bit.
287          * This loop is useless in cs8 mode because DMA copies only
288          * 8 bits and already ignores parity bit.
289          */
290         if (!(stm32_port->rdr_mask == (BIT(8) - 1)))
291                 for (i = 0; i < dma_size; i++)
292                         *(dma_start + i) &= stm32_port->rdr_mask;
293
294         dma_count = tty_insert_flip_string(ttyport, dma_start, dma_size);
295         port->icount.rx += dma_count;
296         if (dma_count != dma_size)
297                 port->icount.buf_overrun++;
298         stm32_port->last_res -= dma_count;
299         if (stm32_port->last_res == 0)
300                 stm32_port->last_res = RX_BUF_L;
301 }
302
303 static unsigned int stm32_usart_receive_chars_dma(struct uart_port *port)
304 {
305         struct stm32_port *stm32_port = to_stm32_port(port);
306         unsigned int dma_size, size = 0;
307
308         /* DMA buffer is configured in cyclic mode and handles the rollback of the buffer. */
309         if (stm32_port->rx_dma_state.residue > stm32_port->last_res) {
310                 /* Conditional first part: from last_res to end of DMA buffer */
311                 dma_size = stm32_port->last_res;
312                 stm32_usart_push_buffer_dma(port, dma_size);
313                 size = dma_size;
314         }
315
316         dma_size = stm32_port->last_res - stm32_port->rx_dma_state.residue;
317         stm32_usart_push_buffer_dma(port, dma_size);
318         size += dma_size;
319
320         return size;
321 }
322
323 static unsigned int stm32_usart_receive_chars(struct uart_port *port, bool force_dma_flush)
324 {
325         struct stm32_port *stm32_port = to_stm32_port(port);
326         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
327         enum dma_status rx_dma_status;
328         u32 sr;
329         unsigned int size = 0;
330
331         if (stm32_usart_rx_dma_enabled(port) || force_dma_flush) {
332                 rx_dma_status = dmaengine_tx_status(stm32_port->rx_ch,
333                                                     stm32_port->rx_ch->cookie,
334                                                     &stm32_port->rx_dma_state);
335                 if (rx_dma_status == DMA_IN_PROGRESS) {
336                         /* Empty DMA buffer */
337                         size = stm32_usart_receive_chars_dma(port);
338                         sr = readl_relaxed(port->membase + ofs->isr);
339                         if (sr & USART_SR_ERR_MASK) {
340                                 /* Disable DMA request line */
341                                 stm32_usart_clr_bits(port, ofs->cr3, USART_CR3_DMAR);
342
343                                 /* Switch to PIO mode to handle the errors */
344                                 size += stm32_usart_receive_chars_pio(port);
345
346                                 /* Switch back to DMA mode */
347                                 stm32_usart_set_bits(port, ofs->cr3, USART_CR3_DMAR);
348                         }
349                 } else {
350                         /* Disable RX DMA */
351                         dmaengine_terminate_async(stm32_port->rx_ch);
352                         stm32_usart_clr_bits(port, ofs->cr3, USART_CR3_DMAR);
353                         /* Fall back to interrupt mode */
354                         dev_dbg(port->dev, "DMA error, fallback to irq mode\n");
355                         size = stm32_usart_receive_chars_pio(port);
356                 }
357         } else {
358                 size = stm32_usart_receive_chars_pio(port);
359         }
360
361         return size;
362 }
363
364 static void stm32_usart_tx_dma_terminate(struct stm32_port *stm32_port)
365 {
366         dmaengine_terminate_async(stm32_port->tx_ch);
367         stm32_port->tx_dma_busy = false;
368 }
369
370 static bool stm32_usart_tx_dma_started(struct stm32_port *stm32_port)
371 {
372         /*
373          * We cannot use the function "dmaengine_tx_status" to know the
374          * status of DMA. This function does not show if the "dma complete"
375          * callback of the DMA transaction has been called. So we prefer
376          * to use "tx_dma_busy" flag to prevent dual DMA transaction at the
377          * same time.
378          */
379         return stm32_port->tx_dma_busy;
380 }
381
382 static bool stm32_usart_tx_dma_enabled(struct stm32_port *stm32_port)
383 {
384         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
385
386         return !!(readl_relaxed(stm32_port->port.membase + ofs->cr3) & USART_CR3_DMAT);
387 }
388
389 static void stm32_usart_tx_dma_complete(void *arg)
390 {
391         struct uart_port *port = arg;
392         struct stm32_port *stm32port = to_stm32_port(port);
393         const struct stm32_usart_offsets *ofs = &stm32port->info->ofs;
394         unsigned long flags;
395
396         stm32_usart_clr_bits(port, ofs->cr3, USART_CR3_DMAT);
397         stm32_usart_tx_dma_terminate(stm32port);
398
399         /* Let's see if we have pending data to send */
400         spin_lock_irqsave(&port->lock, flags);
401         stm32_usart_transmit_chars(port);
402         spin_unlock_irqrestore(&port->lock, flags);
403 }
404
405 static void stm32_usart_tx_interrupt_enable(struct uart_port *port)
406 {
407         struct stm32_port *stm32_port = to_stm32_port(port);
408         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
409
410         /*
411          * Enables TX FIFO threashold irq when FIFO is enabled,
412          * or TX empty irq when FIFO is disabled
413          */
414         if (stm32_port->fifoen && stm32_port->txftcfg >= 0)
415                 stm32_usart_set_bits(port, ofs->cr3, USART_CR3_TXFTIE);
416         else
417                 stm32_usart_set_bits(port, ofs->cr1, USART_CR1_TXEIE);
418 }
419
420 static void stm32_usart_rx_dma_complete(void *arg)
421 {
422         struct uart_port *port = arg;
423         struct tty_port *tport = &port->state->port;
424         unsigned int size;
425         unsigned long flags;
426
427         spin_lock_irqsave(&port->lock, flags);
428         size = stm32_usart_receive_chars(port, false);
429         uart_unlock_and_check_sysrq_irqrestore(port, flags);
430         if (size)
431                 tty_flip_buffer_push(tport);
432 }
433
434 static void stm32_usart_tx_interrupt_disable(struct uart_port *port)
435 {
436         struct stm32_port *stm32_port = to_stm32_port(port);
437         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
438
439         if (stm32_port->fifoen && stm32_port->txftcfg >= 0)
440                 stm32_usart_clr_bits(port, ofs->cr3, USART_CR3_TXFTIE);
441         else
442                 stm32_usart_clr_bits(port, ofs->cr1, USART_CR1_TXEIE);
443 }
444
445 static void stm32_usart_transmit_chars_pio(struct uart_port *port)
446 {
447         struct stm32_port *stm32_port = to_stm32_port(port);
448         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
449         struct circ_buf *xmit = &port->state->xmit;
450
451         if (stm32_usart_tx_dma_enabled(stm32_port))
452                 stm32_usart_clr_bits(port, ofs->cr3, USART_CR3_DMAT);
453
454         while (!uart_circ_empty(xmit)) {
455                 /* Check that TDR is empty before filling FIFO */
456                 if (!(readl_relaxed(port->membase + ofs->isr) & USART_SR_TXE))
457                         break;
458                 writel_relaxed(xmit->buf[xmit->tail], port->membase + ofs->tdr);
459                 xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1);
460                 port->icount.tx++;
461         }
462
463         /* rely on TXE irq (mask or unmask) for sending remaining data */
464         if (uart_circ_empty(xmit))
465                 stm32_usart_tx_interrupt_disable(port);
466         else
467                 stm32_usart_tx_interrupt_enable(port);
468 }
469
470 static void stm32_usart_transmit_chars_dma(struct uart_port *port)
471 {
472         struct stm32_port *stm32port = to_stm32_port(port);
473         const struct stm32_usart_offsets *ofs = &stm32port->info->ofs;
474         struct circ_buf *xmit = &port->state->xmit;
475         struct dma_async_tx_descriptor *desc = NULL;
476         unsigned int count;
477
478         if (stm32_usart_tx_dma_started(stm32port)) {
479                 if (!stm32_usart_tx_dma_enabled(stm32port))
480                         stm32_usart_set_bits(port, ofs->cr3, USART_CR3_DMAT);
481                 return;
482         }
483
484         count = uart_circ_chars_pending(xmit);
485
486         if (count > TX_BUF_L)
487                 count = TX_BUF_L;
488
489         if (xmit->tail < xmit->head) {
490                 memcpy(&stm32port->tx_buf[0], &xmit->buf[xmit->tail], count);
491         } else {
492                 size_t one = UART_XMIT_SIZE - xmit->tail;
493                 size_t two;
494
495                 if (one > count)
496                         one = count;
497                 two = count - one;
498
499                 memcpy(&stm32port->tx_buf[0], &xmit->buf[xmit->tail], one);
500                 if (two)
501                         memcpy(&stm32port->tx_buf[one], &xmit->buf[0], two);
502         }
503
504         desc = dmaengine_prep_slave_single(stm32port->tx_ch,
505                                            stm32port->tx_dma_buf,
506                                            count,
507                                            DMA_MEM_TO_DEV,
508                                            DMA_PREP_INTERRUPT);
509
510         if (!desc)
511                 goto fallback_err;
512
513         /*
514          * Set "tx_dma_busy" flag. This flag will be released when
515          * dmaengine_terminate_async will be called. This flag helps
516          * transmit_chars_dma not to start another DMA transaction
517          * if the callback of the previous is not yet called.
518          */
519         stm32port->tx_dma_busy = true;
520
521         desc->callback = stm32_usart_tx_dma_complete;
522         desc->callback_param = port;
523
524         /* Push current DMA TX transaction in the pending queue */
525         if (dma_submit_error(dmaengine_submit(desc))) {
526                 /* dma no yet started, safe to free resources */
527                 stm32_usart_tx_dma_terminate(stm32port);
528                 goto fallback_err;
529         }
530
531         /* Issue pending DMA TX requests */
532         dma_async_issue_pending(stm32port->tx_ch);
533
534         stm32_usart_set_bits(port, ofs->cr3, USART_CR3_DMAT);
535
536         xmit->tail = (xmit->tail + count) & (UART_XMIT_SIZE - 1);
537         port->icount.tx += count;
538         return;
539
540 fallback_err:
541         stm32_usart_transmit_chars_pio(port);
542 }
543
544 static void stm32_usart_transmit_chars(struct uart_port *port)
545 {
546         struct stm32_port *stm32_port = to_stm32_port(port);
547         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
548         struct circ_buf *xmit = &port->state->xmit;
549         u32 isr;
550         int ret;
551
552         if (port->x_char) {
553                 if (stm32_usart_tx_dma_started(stm32_port) &&
554                     stm32_usart_tx_dma_enabled(stm32_port))
555                         stm32_usart_clr_bits(port, ofs->cr3, USART_CR3_DMAT);
556
557                 /* Check that TDR is empty before filling FIFO */
558                 ret =
559                 readl_relaxed_poll_timeout_atomic(port->membase + ofs->isr,
560                                                   isr,
561                                                   (isr & USART_SR_TXE),
562                                                   10, 1000);
563                 if (ret)
564                         dev_warn(port->dev, "1 character may be erased\n");
565
566                 writel_relaxed(port->x_char, port->membase + ofs->tdr);
567                 port->x_char = 0;
568                 port->icount.tx++;
569                 if (stm32_usart_tx_dma_started(stm32_port))
570                         stm32_usart_set_bits(port, ofs->cr3, USART_CR3_DMAT);
571                 return;
572         }
573
574         if (uart_circ_empty(xmit) || uart_tx_stopped(port)) {
575                 stm32_usart_tx_interrupt_disable(port);
576                 return;
577         }
578
579         if (ofs->icr == UNDEF_REG)
580                 stm32_usart_clr_bits(port, ofs->isr, USART_SR_TC);
581         else
582                 writel_relaxed(USART_ICR_TCCF, port->membase + ofs->icr);
583
584         if (stm32_port->tx_ch)
585                 stm32_usart_transmit_chars_dma(port);
586         else
587                 stm32_usart_transmit_chars_pio(port);
588
589         if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
590                 uart_write_wakeup(port);
591
592         if (uart_circ_empty(xmit))
593                 stm32_usart_tx_interrupt_disable(port);
594 }
595
596 static irqreturn_t stm32_usart_interrupt(int irq, void *ptr)
597 {
598         struct uart_port *port = ptr;
599         struct tty_port *tport = &port->state->port;
600         struct stm32_port *stm32_port = to_stm32_port(port);
601         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
602         u32 sr;
603         unsigned int size;
604
605         sr = readl_relaxed(port->membase + ofs->isr);
606
607         if ((sr & USART_SR_RTOF) && ofs->icr != UNDEF_REG)
608                 writel_relaxed(USART_ICR_RTOCF,
609                                port->membase + ofs->icr);
610
611         if ((sr & USART_SR_WUF) && ofs->icr != UNDEF_REG) {
612                 /* Clear wake up flag and disable wake up interrupt */
613                 writel_relaxed(USART_ICR_WUCF,
614                                port->membase + ofs->icr);
615                 stm32_usart_clr_bits(port, ofs->cr3, USART_CR3_WUFIE);
616                 if (irqd_is_wakeup_set(irq_get_irq_data(port->irq)))
617                         pm_wakeup_event(tport->tty->dev, 0);
618         }
619
620         /*
621          * rx errors in dma mode has to be handled ASAP to avoid overrun as the DMA request
622          * line has been masked by HW and rx data are stacking in FIFO.
623          */
624         if (!stm32_port->throttled) {
625                 if (((sr & USART_SR_RXNE) && !stm32_usart_rx_dma_enabled(port)) ||
626                     ((sr & USART_SR_ERR_MASK) && stm32_usart_rx_dma_enabled(port))) {
627                         spin_lock(&port->lock);
628                         size = stm32_usart_receive_chars(port, false);
629                         uart_unlock_and_check_sysrq(port);
630                         if (size)
631                                 tty_flip_buffer_push(tport);
632                 }
633         }
634
635         if ((sr & USART_SR_TXE) && !(stm32_port->tx_ch)) {
636                 spin_lock(&port->lock);
637                 stm32_usart_transmit_chars(port);
638                 spin_unlock(&port->lock);
639         }
640
641         if (stm32_usart_rx_dma_enabled(port))
642                 return IRQ_WAKE_THREAD;
643         else
644                 return IRQ_HANDLED;
645 }
646
647 static irqreturn_t stm32_usart_threaded_interrupt(int irq, void *ptr)
648 {
649         struct uart_port *port = ptr;
650         struct tty_port *tport = &port->state->port;
651         struct stm32_port *stm32_port = to_stm32_port(port);
652         unsigned int size;
653         unsigned long flags;
654
655         /* Receiver timeout irq for DMA RX */
656         if (!stm32_port->throttled) {
657                 spin_lock_irqsave(&port->lock, flags);
658                 size = stm32_usart_receive_chars(port, false);
659                 uart_unlock_and_check_sysrq_irqrestore(port, flags);
660                 if (size)
661                         tty_flip_buffer_push(tport);
662         }
663
664         return IRQ_HANDLED;
665 }
666
667 static unsigned int stm32_usart_tx_empty(struct uart_port *port)
668 {
669         struct stm32_port *stm32_port = to_stm32_port(port);
670         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
671
672         if (readl_relaxed(port->membase + ofs->isr) & USART_SR_TC)
673                 return TIOCSER_TEMT;
674
675         return 0;
676 }
677
678 static void stm32_usart_set_mctrl(struct uart_port *port, unsigned int mctrl)
679 {
680         struct stm32_port *stm32_port = to_stm32_port(port);
681         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
682
683         if ((mctrl & TIOCM_RTS) && (port->status & UPSTAT_AUTORTS))
684                 stm32_usart_set_bits(port, ofs->cr3, USART_CR3_RTSE);
685         else
686                 stm32_usart_clr_bits(port, ofs->cr3, USART_CR3_RTSE);
687
688         mctrl_gpio_set(stm32_port->gpios, mctrl);
689 }
690
691 static unsigned int stm32_usart_get_mctrl(struct uart_port *port)
692 {
693         struct stm32_port *stm32_port = to_stm32_port(port);
694         unsigned int ret;
695
696         /* This routine is used to get signals of: DCD, DSR, RI, and CTS */
697         ret = TIOCM_CAR | TIOCM_DSR | TIOCM_CTS;
698
699         return mctrl_gpio_get(stm32_port->gpios, &ret);
700 }
701
702 static void stm32_usart_enable_ms(struct uart_port *port)
703 {
704         mctrl_gpio_enable_ms(to_stm32_port(port)->gpios);
705 }
706
707 static void stm32_usart_disable_ms(struct uart_port *port)
708 {
709         mctrl_gpio_disable_ms(to_stm32_port(port)->gpios);
710 }
711
712 /* Transmit stop */
713 static void stm32_usart_stop_tx(struct uart_port *port)
714 {
715         struct stm32_port *stm32_port = to_stm32_port(port);
716         struct serial_rs485 *rs485conf = &port->rs485;
717         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
718
719         stm32_usart_tx_interrupt_disable(port);
720         if (stm32_usart_tx_dma_started(stm32_port) && stm32_usart_tx_dma_enabled(stm32_port))
721                 stm32_usart_clr_bits(port, ofs->cr3, USART_CR3_DMAT);
722
723         if (rs485conf->flags & SER_RS485_ENABLED) {
724                 if (rs485conf->flags & SER_RS485_RTS_ON_SEND) {
725                         mctrl_gpio_set(stm32_port->gpios,
726                                         stm32_port->port.mctrl & ~TIOCM_RTS);
727                 } else {
728                         mctrl_gpio_set(stm32_port->gpios,
729                                         stm32_port->port.mctrl | TIOCM_RTS);
730                 }
731         }
732 }
733
734 /* There are probably characters waiting to be transmitted. */
735 static void stm32_usart_start_tx(struct uart_port *port)
736 {
737         struct stm32_port *stm32_port = to_stm32_port(port);
738         struct serial_rs485 *rs485conf = &port->rs485;
739         struct circ_buf *xmit = &port->state->xmit;
740
741         if (uart_circ_empty(xmit) && !port->x_char)
742                 return;
743
744         if (rs485conf->flags & SER_RS485_ENABLED) {
745                 if (rs485conf->flags & SER_RS485_RTS_ON_SEND) {
746                         mctrl_gpio_set(stm32_port->gpios,
747                                         stm32_port->port.mctrl | TIOCM_RTS);
748                 } else {
749                         mctrl_gpio_set(stm32_port->gpios,
750                                         stm32_port->port.mctrl & ~TIOCM_RTS);
751                 }
752         }
753
754         stm32_usart_transmit_chars(port);
755 }
756
757 /* Flush the transmit buffer. */
758 static void stm32_usart_flush_buffer(struct uart_port *port)
759 {
760         struct stm32_port *stm32_port = to_stm32_port(port);
761         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
762
763         if (stm32_port->tx_ch) {
764                 stm32_usart_tx_dma_terminate(stm32_port);
765                 stm32_usart_clr_bits(port, ofs->cr3, USART_CR3_DMAT);
766         }
767 }
768
769 /* Throttle the remote when input buffer is about to overflow. */
770 static void stm32_usart_throttle(struct uart_port *port)
771 {
772         struct stm32_port *stm32_port = to_stm32_port(port);
773         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
774         unsigned long flags;
775
776         spin_lock_irqsave(&port->lock, flags);
777
778         /*
779          * Disable DMA request line if enabled, so the RX data gets queued into the FIFO.
780          * Hardware flow control is triggered when RX FIFO is full.
781          */
782         if (stm32_usart_rx_dma_enabled(port))
783                 stm32_usart_clr_bits(port, ofs->cr3, USART_CR3_DMAR);
784
785         stm32_usart_clr_bits(port, ofs->cr1, stm32_port->cr1_irq);
786         if (stm32_port->cr3_irq)
787                 stm32_usart_clr_bits(port, ofs->cr3, stm32_port->cr3_irq);
788
789         stm32_port->throttled = true;
790         spin_unlock_irqrestore(&port->lock, flags);
791 }
792
793 /* Unthrottle the remote, the input buffer can now accept data. */
794 static void stm32_usart_unthrottle(struct uart_port *port)
795 {
796         struct stm32_port *stm32_port = to_stm32_port(port);
797         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
798         unsigned long flags;
799
800         spin_lock_irqsave(&port->lock, flags);
801         stm32_usart_set_bits(port, ofs->cr1, stm32_port->cr1_irq);
802         if (stm32_port->cr3_irq)
803                 stm32_usart_set_bits(port, ofs->cr3, stm32_port->cr3_irq);
804
805         /*
806          * Switch back to DMA mode (re-enable DMA request line).
807          * Hardware flow control is stopped when FIFO is not full any more.
808          */
809         if (stm32_port->rx_ch)
810                 stm32_usart_set_bits(port, ofs->cr3, USART_CR3_DMAR);
811
812         stm32_port->throttled = false;
813         spin_unlock_irqrestore(&port->lock, flags);
814 }
815
816 /* Receive stop */
817 static void stm32_usart_stop_rx(struct uart_port *port)
818 {
819         struct stm32_port *stm32_port = to_stm32_port(port);
820         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
821
822         /* Disable DMA request line. */
823         if (stm32_port->rx_ch)
824                 stm32_usart_clr_bits(port, ofs->cr3, USART_CR3_DMAR);
825
826         stm32_usart_clr_bits(port, ofs->cr1, stm32_port->cr1_irq);
827         if (stm32_port->cr3_irq)
828                 stm32_usart_clr_bits(port, ofs->cr3, stm32_port->cr3_irq);
829 }
830
831 /* Handle breaks - ignored by us */
832 static void stm32_usart_break_ctl(struct uart_port *port, int break_state)
833 {
834 }
835
836 static int stm32_usart_start_rx_dma_cyclic(struct uart_port *port)
837 {
838         struct stm32_port *stm32_port = to_stm32_port(port);
839         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
840         struct dma_async_tx_descriptor *desc;
841         int ret;
842
843         stm32_port->last_res = RX_BUF_L;
844         /* Prepare a DMA cyclic transaction */
845         desc = dmaengine_prep_dma_cyclic(stm32_port->rx_ch,
846                                          stm32_port->rx_dma_buf,
847                                          RX_BUF_L, RX_BUF_P,
848                                          DMA_DEV_TO_MEM,
849                                          DMA_PREP_INTERRUPT);
850         if (!desc) {
851                 dev_err(port->dev, "rx dma prep cyclic failed\n");
852                 return -ENODEV;
853         }
854
855         desc->callback = stm32_usart_rx_dma_complete;
856         desc->callback_param = port;
857
858         /* Push current DMA transaction in the pending queue */
859         ret = dma_submit_error(dmaengine_submit(desc));
860         if (ret) {
861                 dmaengine_terminate_sync(stm32_port->rx_ch);
862                 return ret;
863         }
864
865         /* Issue pending DMA requests */
866         dma_async_issue_pending(stm32_port->rx_ch);
867
868         /*
869          * DMA request line not re-enabled at resume when port is throttled.
870          * It will be re-enabled by unthrottle ops.
871          */
872         if (!stm32_port->throttled)
873                 stm32_usart_set_bits(port, ofs->cr3, USART_CR3_DMAR);
874
875         return 0;
876 }
877
878 static int stm32_usart_startup(struct uart_port *port)
879 {
880         struct stm32_port *stm32_port = to_stm32_port(port);
881         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
882         const struct stm32_usart_config *cfg = &stm32_port->info->cfg;
883         const char *name = to_platform_device(port->dev)->name;
884         u32 val;
885         int ret;
886
887         ret = request_threaded_irq(port->irq, stm32_usart_interrupt,
888                                    stm32_usart_threaded_interrupt,
889                                    IRQF_ONESHOT | IRQF_NO_SUSPEND,
890                                    name, port);
891         if (ret)
892                 return ret;
893
894         if (stm32_port->swap) {
895                 val = readl_relaxed(port->membase + ofs->cr2);
896                 val |= USART_CR2_SWAP;
897                 writel_relaxed(val, port->membase + ofs->cr2);
898         }
899
900         /* RX FIFO Flush */
901         if (ofs->rqr != UNDEF_REG)
902                 writel_relaxed(USART_RQR_RXFRQ, port->membase + ofs->rqr);
903
904         if (stm32_port->rx_ch) {
905                 ret = stm32_usart_start_rx_dma_cyclic(port);
906                 if (ret) {
907                         free_irq(port->irq, port);
908                         return ret;
909                 }
910         }
911
912         /* RX enabling */
913         val = stm32_port->cr1_irq | USART_CR1_RE | BIT(cfg->uart_enable_bit);
914         stm32_usart_set_bits(port, ofs->cr1, val);
915
916         return 0;
917 }
918
919 static void stm32_usart_shutdown(struct uart_port *port)
920 {
921         struct stm32_port *stm32_port = to_stm32_port(port);
922         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
923         const struct stm32_usart_config *cfg = &stm32_port->info->cfg;
924         u32 val, isr;
925         int ret;
926
927         if (stm32_usart_tx_dma_enabled(stm32_port))
928                 stm32_usart_clr_bits(port, ofs->cr3, USART_CR3_DMAT);
929
930         if (stm32_usart_tx_dma_started(stm32_port))
931                 stm32_usart_tx_dma_terminate(stm32_port);
932
933         /* Disable modem control interrupts */
934         stm32_usart_disable_ms(port);
935
936         val = USART_CR1_TXEIE | USART_CR1_TE;
937         val |= stm32_port->cr1_irq | USART_CR1_RE;
938         val |= BIT(cfg->uart_enable_bit);
939         if (stm32_port->fifoen)
940                 val |= USART_CR1_FIFOEN;
941
942         ret = readl_relaxed_poll_timeout(port->membase + ofs->isr,
943                                          isr, (isr & USART_SR_TC),
944                                          10, 100000);
945
946         /* Send the TC error message only when ISR_TC is not set */
947         if (ret)
948                 dev_err(port->dev, "Transmission is not complete\n");
949
950         /* Disable RX DMA. */
951         if (stm32_port->rx_ch)
952                 dmaengine_terminate_async(stm32_port->rx_ch);
953
954         /* flush RX & TX FIFO */
955         if (ofs->rqr != UNDEF_REG)
956                 writel_relaxed(USART_RQR_TXFRQ | USART_RQR_RXFRQ,
957                                port->membase + ofs->rqr);
958
959         stm32_usart_clr_bits(port, ofs->cr1, val);
960
961         free_irq(port->irq, port);
962 }
963
964 static void stm32_usart_set_termios(struct uart_port *port,
965                                     struct ktermios *termios,
966                                     struct ktermios *old)
967 {
968         struct stm32_port *stm32_port = to_stm32_port(port);
969         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
970         const struct stm32_usart_config *cfg = &stm32_port->info->cfg;
971         struct serial_rs485 *rs485conf = &port->rs485;
972         unsigned int baud, bits;
973         u32 usartdiv, mantissa, fraction, oversampling;
974         tcflag_t cflag = termios->c_cflag;
975         u32 cr1, cr2, cr3, isr;
976         unsigned long flags;
977         int ret;
978
979         if (!stm32_port->hw_flow_control)
980                 cflag &= ~CRTSCTS;
981
982         baud = uart_get_baud_rate(port, termios, old, 0, port->uartclk / 8);
983
984         spin_lock_irqsave(&port->lock, flags);
985
986         ret = readl_relaxed_poll_timeout_atomic(port->membase + ofs->isr,
987                                                 isr,
988                                                 (isr & USART_SR_TC),
989                                                 10, 100000);
990
991         /* Send the TC error message only when ISR_TC is not set. */
992         if (ret)
993                 dev_err(port->dev, "Transmission is not complete\n");
994
995         /* Stop serial port and reset value */
996         writel_relaxed(0, port->membase + ofs->cr1);
997
998         /* flush RX & TX FIFO */
999         if (ofs->rqr != UNDEF_REG)
1000                 writel_relaxed(USART_RQR_TXFRQ | USART_RQR_RXFRQ,
1001                                port->membase + ofs->rqr);
1002
1003         cr1 = USART_CR1_TE | USART_CR1_RE;
1004         if (stm32_port->fifoen)
1005                 cr1 |= USART_CR1_FIFOEN;
1006         cr2 = stm32_port->swap ? USART_CR2_SWAP : 0;
1007
1008         /* Tx and RX FIFO configuration */
1009         cr3 = readl_relaxed(port->membase + ofs->cr3);
1010         cr3 &= USART_CR3_TXFTIE | USART_CR3_RXFTIE;
1011         if (stm32_port->fifoen) {
1012                 if (stm32_port->txftcfg >= 0)
1013                         cr3 |= stm32_port->txftcfg << USART_CR3_TXFTCFG_SHIFT;
1014                 if (stm32_port->rxftcfg >= 0)
1015                         cr3 |= stm32_port->rxftcfg << USART_CR3_RXFTCFG_SHIFT;
1016         }
1017
1018         if (cflag & CSTOPB)
1019                 cr2 |= USART_CR2_STOP_2B;
1020
1021         bits = tty_get_char_size(cflag);
1022         stm32_port->rdr_mask = (BIT(bits) - 1);
1023
1024         if (cflag & PARENB) {
1025                 bits++;
1026                 cr1 |= USART_CR1_PCE;
1027         }
1028
1029         /*
1030          * Word length configuration:
1031          * CS8 + parity, 9 bits word aka [M1:M0] = 0b01
1032          * CS7 or (CS6 + parity), 7 bits word aka [M1:M0] = 0b10
1033          * CS8 or (CS7 + parity), 8 bits word aka [M1:M0] = 0b00
1034          * M0 and M1 already cleared by cr1 initialization.
1035          */
1036         if (bits == 9)
1037                 cr1 |= USART_CR1_M0;
1038         else if ((bits == 7) && cfg->has_7bits_data)
1039                 cr1 |= USART_CR1_M1;
1040         else if (bits != 8)
1041                 dev_dbg(port->dev, "Unsupported data bits config: %u bits\n"
1042                         , bits);
1043
1044         if (ofs->rtor != UNDEF_REG && (stm32_port->rx_ch ||
1045                                        (stm32_port->fifoen &&
1046                                         stm32_port->rxftcfg >= 0))) {
1047                 if (cflag & CSTOPB)
1048                         bits = bits + 3; /* 1 start bit + 2 stop bits */
1049                 else
1050                         bits = bits + 2; /* 1 start bit + 1 stop bit */
1051
1052                 /* RX timeout irq to occur after last stop bit + bits */
1053                 stm32_port->cr1_irq = USART_CR1_RTOIE;
1054                 writel_relaxed(bits, port->membase + ofs->rtor);
1055                 cr2 |= USART_CR2_RTOEN;
1056                 /*
1057                  * Enable fifo threshold irq in two cases, either when there is no DMA, or when
1058                  * wake up over usart, from low power until the DMA gets re-enabled by resume.
1059                  */
1060                 stm32_port->cr3_irq =  USART_CR3_RXFTIE;
1061         }
1062
1063         cr1 |= stm32_port->cr1_irq;
1064         cr3 |= stm32_port->cr3_irq;
1065
1066         if (cflag & PARODD)
1067                 cr1 |= USART_CR1_PS;
1068
1069         port->status &= ~(UPSTAT_AUTOCTS | UPSTAT_AUTORTS);
1070         if (cflag & CRTSCTS) {
1071                 port->status |= UPSTAT_AUTOCTS | UPSTAT_AUTORTS;
1072                 cr3 |= USART_CR3_CTSE | USART_CR3_RTSE;
1073         }
1074
1075         usartdiv = DIV_ROUND_CLOSEST(port->uartclk, baud);
1076
1077         /*
1078          * The USART supports 16 or 8 times oversampling.
1079          * By default we prefer 16 times oversampling, so that the receiver
1080          * has a better tolerance to clock deviations.
1081          * 8 times oversampling is only used to achieve higher speeds.
1082          */
1083         if (usartdiv < 16) {
1084                 oversampling = 8;
1085                 cr1 |= USART_CR1_OVER8;
1086                 stm32_usart_set_bits(port, ofs->cr1, USART_CR1_OVER8);
1087         } else {
1088                 oversampling = 16;
1089                 cr1 &= ~USART_CR1_OVER8;
1090                 stm32_usart_clr_bits(port, ofs->cr1, USART_CR1_OVER8);
1091         }
1092
1093         mantissa = (usartdiv / oversampling) << USART_BRR_DIV_M_SHIFT;
1094         fraction = usartdiv % oversampling;
1095         writel_relaxed(mantissa | fraction, port->membase + ofs->brr);
1096
1097         uart_update_timeout(port, cflag, baud);
1098
1099         port->read_status_mask = USART_SR_ORE;
1100         if (termios->c_iflag & INPCK)
1101                 port->read_status_mask |= USART_SR_PE | USART_SR_FE;
1102         if (termios->c_iflag & (IGNBRK | BRKINT | PARMRK))
1103                 port->read_status_mask |= USART_SR_FE;
1104
1105         /* Characters to ignore */
1106         port->ignore_status_mask = 0;
1107         if (termios->c_iflag & IGNPAR)
1108                 port->ignore_status_mask = USART_SR_PE | USART_SR_FE;
1109         if (termios->c_iflag & IGNBRK) {
1110                 port->ignore_status_mask |= USART_SR_FE;
1111                 /*
1112                  * If we're ignoring parity and break indicators,
1113                  * ignore overruns too (for real raw support).
1114                  */
1115                 if (termios->c_iflag & IGNPAR)
1116                         port->ignore_status_mask |= USART_SR_ORE;
1117         }
1118
1119         /* Ignore all characters if CREAD is not set */
1120         if ((termios->c_cflag & CREAD) == 0)
1121                 port->ignore_status_mask |= USART_SR_DUMMY_RX;
1122
1123         if (stm32_port->rx_ch) {
1124                 /*
1125                  * Setup DMA to collect only valid data and enable error irqs.
1126                  * This also enables break reception when using DMA.
1127                  */
1128                 cr1 |= USART_CR1_PEIE;
1129                 cr3 |= USART_CR3_EIE;
1130                 cr3 |= USART_CR3_DMAR;
1131                 cr3 |= USART_CR3_DDRE;
1132         }
1133
1134         if (rs485conf->flags & SER_RS485_ENABLED) {
1135                 stm32_usart_config_reg_rs485(&cr1, &cr3,
1136                                              rs485conf->delay_rts_before_send,
1137                                              rs485conf->delay_rts_after_send,
1138                                              baud);
1139                 if (rs485conf->flags & SER_RS485_RTS_ON_SEND) {
1140                         cr3 &= ~USART_CR3_DEP;
1141                         rs485conf->flags &= ~SER_RS485_RTS_AFTER_SEND;
1142                 } else {
1143                         cr3 |= USART_CR3_DEP;
1144                         rs485conf->flags |= SER_RS485_RTS_AFTER_SEND;
1145                 }
1146
1147         } else {
1148                 cr3 &= ~(USART_CR3_DEM | USART_CR3_DEP);
1149                 cr1 &= ~(USART_CR1_DEDT_MASK | USART_CR1_DEAT_MASK);
1150         }
1151
1152         /* Configure wake up from low power on start bit detection */
1153         if (stm32_port->wakeup_src) {
1154                 cr3 &= ~USART_CR3_WUS_MASK;
1155                 cr3 |= USART_CR3_WUS_START_BIT;
1156         }
1157
1158         writel_relaxed(cr3, port->membase + ofs->cr3);
1159         writel_relaxed(cr2, port->membase + ofs->cr2);
1160         writel_relaxed(cr1, port->membase + ofs->cr1);
1161
1162         stm32_usart_set_bits(port, ofs->cr1, BIT(cfg->uart_enable_bit));
1163         spin_unlock_irqrestore(&port->lock, flags);
1164
1165         /* Handle modem control interrupts */
1166         if (UART_ENABLE_MS(port, termios->c_cflag))
1167                 stm32_usart_enable_ms(port);
1168         else
1169                 stm32_usart_disable_ms(port);
1170 }
1171
1172 static const char *stm32_usart_type(struct uart_port *port)
1173 {
1174         return (port->type == PORT_STM32) ? DRIVER_NAME : NULL;
1175 }
1176
1177 static void stm32_usart_release_port(struct uart_port *port)
1178 {
1179 }
1180
1181 static int stm32_usart_request_port(struct uart_port *port)
1182 {
1183         return 0;
1184 }
1185
1186 static void stm32_usart_config_port(struct uart_port *port, int flags)
1187 {
1188         if (flags & UART_CONFIG_TYPE)
1189                 port->type = PORT_STM32;
1190 }
1191
1192 static int
1193 stm32_usart_verify_port(struct uart_port *port, struct serial_struct *ser)
1194 {
1195         /* No user changeable parameters */
1196         return -EINVAL;
1197 }
1198
1199 static void stm32_usart_pm(struct uart_port *port, unsigned int state,
1200                            unsigned int oldstate)
1201 {
1202         struct stm32_port *stm32port = container_of(port,
1203                         struct stm32_port, port);
1204         const struct stm32_usart_offsets *ofs = &stm32port->info->ofs;
1205         const struct stm32_usart_config *cfg = &stm32port->info->cfg;
1206         unsigned long flags;
1207
1208         switch (state) {
1209         case UART_PM_STATE_ON:
1210                 pm_runtime_get_sync(port->dev);
1211                 break;
1212         case UART_PM_STATE_OFF:
1213                 spin_lock_irqsave(&port->lock, flags);
1214                 stm32_usart_clr_bits(port, ofs->cr1, BIT(cfg->uart_enable_bit));
1215                 spin_unlock_irqrestore(&port->lock, flags);
1216                 pm_runtime_put_sync(port->dev);
1217                 break;
1218         }
1219 }
1220
1221 #if defined(CONFIG_CONSOLE_POLL)
1222
1223  /* Callbacks for characters polling in debug context (i.e. KGDB). */
1224 static int stm32_usart_poll_init(struct uart_port *port)
1225 {
1226         struct stm32_port *stm32_port = to_stm32_port(port);
1227
1228         return clk_prepare_enable(stm32_port->clk);
1229 }
1230
1231 static int stm32_usart_poll_get_char(struct uart_port *port)
1232 {
1233         struct stm32_port *stm32_port = to_stm32_port(port);
1234         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
1235
1236         if (!(readl_relaxed(port->membase + ofs->isr) & USART_SR_RXNE))
1237                 return NO_POLL_CHAR;
1238
1239         return readl_relaxed(port->membase + ofs->rdr) & stm32_port->rdr_mask;
1240 }
1241
1242 static void stm32_usart_poll_put_char(struct uart_port *port, unsigned char ch)
1243 {
1244         stm32_usart_console_putchar(port, ch);
1245 }
1246 #endif /* CONFIG_CONSOLE_POLL */
1247
1248 static const struct uart_ops stm32_uart_ops = {
1249         .tx_empty       = stm32_usart_tx_empty,
1250         .set_mctrl      = stm32_usart_set_mctrl,
1251         .get_mctrl      = stm32_usart_get_mctrl,
1252         .stop_tx        = stm32_usart_stop_tx,
1253         .start_tx       = stm32_usart_start_tx,
1254         .throttle       = stm32_usart_throttle,
1255         .unthrottle     = stm32_usart_unthrottle,
1256         .stop_rx        = stm32_usart_stop_rx,
1257         .enable_ms      = stm32_usart_enable_ms,
1258         .break_ctl      = stm32_usart_break_ctl,
1259         .startup        = stm32_usart_startup,
1260         .shutdown       = stm32_usart_shutdown,
1261         .flush_buffer   = stm32_usart_flush_buffer,
1262         .set_termios    = stm32_usart_set_termios,
1263         .pm             = stm32_usart_pm,
1264         .type           = stm32_usart_type,
1265         .release_port   = stm32_usart_release_port,
1266         .request_port   = stm32_usart_request_port,
1267         .config_port    = stm32_usart_config_port,
1268         .verify_port    = stm32_usart_verify_port,
1269 #if defined(CONFIG_CONSOLE_POLL)
1270         .poll_init      = stm32_usart_poll_init,
1271         .poll_get_char  = stm32_usart_poll_get_char,
1272         .poll_put_char  = stm32_usart_poll_put_char,
1273 #endif /* CONFIG_CONSOLE_POLL */
1274 };
1275
1276 /*
1277  * STM32H7 RX & TX FIFO threshold configuration (CR3 RXFTCFG / TXFTCFG)
1278  * Note: 1 isn't a valid value in RXFTCFG / TXFTCFG. In this case,
1279  * RXNEIE / TXEIE can be used instead of threshold irqs: RXFTIE / TXFTIE.
1280  * So, RXFTCFG / TXFTCFG bitfields values are encoded as array index + 1.
1281  */
1282 static const u32 stm32h7_usart_fifo_thresh_cfg[] = { 1, 2, 4, 8, 12, 14, 16 };
1283
1284 static void stm32_usart_get_ftcfg(struct platform_device *pdev, const char *p,
1285                                   int *ftcfg)
1286 {
1287         u32 bytes, i;
1288
1289         /* DT option to get RX & TX FIFO threshold (default to 8 bytes) */
1290         if (of_property_read_u32(pdev->dev.of_node, p, &bytes))
1291                 bytes = 8;
1292
1293         for (i = 0; i < ARRAY_SIZE(stm32h7_usart_fifo_thresh_cfg); i++)
1294                 if (stm32h7_usart_fifo_thresh_cfg[i] >= bytes)
1295                         break;
1296         if (i >= ARRAY_SIZE(stm32h7_usart_fifo_thresh_cfg))
1297                 i = ARRAY_SIZE(stm32h7_usart_fifo_thresh_cfg) - 1;
1298
1299         dev_dbg(&pdev->dev, "%s set to %d bytes\n", p,
1300                 stm32h7_usart_fifo_thresh_cfg[i]);
1301
1302         /* Provide FIFO threshold ftcfg (1 is invalid: threshold irq unused) */
1303         if (i)
1304                 *ftcfg = i - 1;
1305         else
1306                 *ftcfg = -EINVAL;
1307 }
1308
1309 static void stm32_usart_deinit_port(struct stm32_port *stm32port)
1310 {
1311         clk_disable_unprepare(stm32port->clk);
1312 }
1313
1314 static int stm32_usart_init_port(struct stm32_port *stm32port,
1315                                  struct platform_device *pdev)
1316 {
1317         struct uart_port *port = &stm32port->port;
1318         struct resource *res;
1319         int ret, irq;
1320
1321         irq = platform_get_irq(pdev, 0);
1322         if (irq < 0)
1323                 return irq;
1324
1325         port->iotype    = UPIO_MEM;
1326         port->flags     = UPF_BOOT_AUTOCONF;
1327         port->ops       = &stm32_uart_ops;
1328         port->dev       = &pdev->dev;
1329         port->fifosize  = stm32port->info->cfg.fifosize;
1330         port->has_sysrq = IS_ENABLED(CONFIG_SERIAL_STM32_CONSOLE);
1331         port->irq = irq;
1332         port->rs485_config = stm32_usart_config_rs485;
1333
1334         ret = stm32_usart_init_rs485(port, pdev);
1335         if (ret)
1336                 return ret;
1337
1338         stm32port->wakeup_src = stm32port->info->cfg.has_wakeup &&
1339                 of_property_read_bool(pdev->dev.of_node, "wakeup-source");
1340
1341         stm32port->swap = stm32port->info->cfg.has_swap &&
1342                 of_property_read_bool(pdev->dev.of_node, "rx-tx-swap");
1343
1344         stm32port->fifoen = stm32port->info->cfg.has_fifo;
1345         if (stm32port->fifoen) {
1346                 stm32_usart_get_ftcfg(pdev, "rx-threshold",
1347                                       &stm32port->rxftcfg);
1348                 stm32_usart_get_ftcfg(pdev, "tx-threshold",
1349                                       &stm32port->txftcfg);
1350         }
1351
1352         port->membase = devm_platform_get_and_ioremap_resource(pdev, 0, &res);
1353         if (IS_ERR(port->membase))
1354                 return PTR_ERR(port->membase);
1355         port->mapbase = res->start;
1356
1357         spin_lock_init(&port->lock);
1358
1359         stm32port->clk = devm_clk_get(&pdev->dev, NULL);
1360         if (IS_ERR(stm32port->clk))
1361                 return PTR_ERR(stm32port->clk);
1362
1363         /* Ensure that clk rate is correct by enabling the clk */
1364         ret = clk_prepare_enable(stm32port->clk);
1365         if (ret)
1366                 return ret;
1367
1368         stm32port->port.uartclk = clk_get_rate(stm32port->clk);
1369         if (!stm32port->port.uartclk) {
1370                 ret = -EINVAL;
1371                 goto err_clk;
1372         }
1373
1374         stm32port->gpios = mctrl_gpio_init(&stm32port->port, 0);
1375         if (IS_ERR(stm32port->gpios)) {
1376                 ret = PTR_ERR(stm32port->gpios);
1377                 goto err_clk;
1378         }
1379
1380         /*
1381          * Both CTS/RTS gpios and "st,hw-flow-ctrl" (deprecated) or "uart-has-rtscts"
1382          * properties should not be specified.
1383          */
1384         if (stm32port->hw_flow_control) {
1385                 if (mctrl_gpio_to_gpiod(stm32port->gpios, UART_GPIO_CTS) ||
1386                     mctrl_gpio_to_gpiod(stm32port->gpios, UART_GPIO_RTS)) {
1387                         dev_err(&pdev->dev, "Conflicting RTS/CTS config\n");
1388                         ret = -EINVAL;
1389                         goto err_clk;
1390                 }
1391         }
1392
1393         return ret;
1394
1395 err_clk:
1396         clk_disable_unprepare(stm32port->clk);
1397
1398         return ret;
1399 }
1400
1401 static struct stm32_port *stm32_usart_of_get_port(struct platform_device *pdev)
1402 {
1403         struct device_node *np = pdev->dev.of_node;
1404         int id;
1405
1406         if (!np)
1407                 return NULL;
1408
1409         id = of_alias_get_id(np, "serial");
1410         if (id < 0) {
1411                 dev_err(&pdev->dev, "failed to get alias id, errno %d\n", id);
1412                 return NULL;
1413         }
1414
1415         if (WARN_ON(id >= STM32_MAX_PORTS))
1416                 return NULL;
1417
1418         stm32_ports[id].hw_flow_control =
1419                 of_property_read_bool (np, "st,hw-flow-ctrl") /*deprecated*/ ||
1420                 of_property_read_bool (np, "uart-has-rtscts");
1421         stm32_ports[id].port.line = id;
1422         stm32_ports[id].cr1_irq = USART_CR1_RXNEIE;
1423         stm32_ports[id].cr3_irq = 0;
1424         stm32_ports[id].last_res = RX_BUF_L;
1425         return &stm32_ports[id];
1426 }
1427
1428 #ifdef CONFIG_OF
1429 static const struct of_device_id stm32_match[] = {
1430         { .compatible = "st,stm32-uart", .data = &stm32f4_info},
1431         { .compatible = "st,stm32f7-uart", .data = &stm32f7_info},
1432         { .compatible = "st,stm32h7-uart", .data = &stm32h7_info},
1433         {},
1434 };
1435
1436 MODULE_DEVICE_TABLE(of, stm32_match);
1437 #endif
1438
1439 static void stm32_usart_of_dma_rx_remove(struct stm32_port *stm32port,
1440                                          struct platform_device *pdev)
1441 {
1442         if (stm32port->rx_buf)
1443                 dma_free_coherent(&pdev->dev, RX_BUF_L, stm32port->rx_buf,
1444                                   stm32port->rx_dma_buf);
1445 }
1446
1447 static int stm32_usart_of_dma_rx_probe(struct stm32_port *stm32port,
1448                                        struct platform_device *pdev)
1449 {
1450         const struct stm32_usart_offsets *ofs = &stm32port->info->ofs;
1451         struct uart_port *port = &stm32port->port;
1452         struct device *dev = &pdev->dev;
1453         struct dma_slave_config config;
1454         int ret;
1455
1456         /*
1457          * Using DMA and threaded handler for the console could lead to
1458          * deadlocks.
1459          */
1460         if (uart_console(port))
1461                 return -ENODEV;
1462
1463         stm32port->rx_buf = dma_alloc_coherent(dev, RX_BUF_L,
1464                                                &stm32port->rx_dma_buf,
1465                                                GFP_KERNEL);
1466         if (!stm32port->rx_buf)
1467                 return -ENOMEM;
1468
1469         /* Configure DMA channel */
1470         memset(&config, 0, sizeof(config));
1471         config.src_addr = port->mapbase + ofs->rdr;
1472         config.src_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE;
1473
1474         ret = dmaengine_slave_config(stm32port->rx_ch, &config);
1475         if (ret < 0) {
1476                 dev_err(dev, "rx dma channel config failed\n");
1477                 stm32_usart_of_dma_rx_remove(stm32port, pdev);
1478                 return ret;
1479         }
1480
1481         return 0;
1482 }
1483
1484 static void stm32_usart_of_dma_tx_remove(struct stm32_port *stm32port,
1485                                          struct platform_device *pdev)
1486 {
1487         if (stm32port->tx_buf)
1488                 dma_free_coherent(&pdev->dev, TX_BUF_L, stm32port->tx_buf,
1489                                   stm32port->tx_dma_buf);
1490 }
1491
1492 static int stm32_usart_of_dma_tx_probe(struct stm32_port *stm32port,
1493                                        struct platform_device *pdev)
1494 {
1495         const struct stm32_usart_offsets *ofs = &stm32port->info->ofs;
1496         struct uart_port *port = &stm32port->port;
1497         struct device *dev = &pdev->dev;
1498         struct dma_slave_config config;
1499         int ret;
1500
1501         stm32port->tx_buf = dma_alloc_coherent(dev, TX_BUF_L,
1502                                                &stm32port->tx_dma_buf,
1503                                                GFP_KERNEL);
1504         if (!stm32port->tx_buf)
1505                 return -ENOMEM;
1506
1507         /* Configure DMA channel */
1508         memset(&config, 0, sizeof(config));
1509         config.dst_addr = port->mapbase + ofs->tdr;
1510         config.dst_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE;
1511
1512         ret = dmaengine_slave_config(stm32port->tx_ch, &config);
1513         if (ret < 0) {
1514                 dev_err(dev, "tx dma channel config failed\n");
1515                 stm32_usart_of_dma_tx_remove(stm32port, pdev);
1516                 return ret;
1517         }
1518
1519         return 0;
1520 }
1521
1522 static int stm32_usart_serial_probe(struct platform_device *pdev)
1523 {
1524         struct stm32_port *stm32port;
1525         int ret;
1526
1527         stm32port = stm32_usart_of_get_port(pdev);
1528         if (!stm32port)
1529                 return -ENODEV;
1530
1531         stm32port->info = of_device_get_match_data(&pdev->dev);
1532         if (!stm32port->info)
1533                 return -EINVAL;
1534
1535         ret = stm32_usart_init_port(stm32port, pdev);
1536         if (ret)
1537                 return ret;
1538
1539         if (stm32port->wakeup_src) {
1540                 device_set_wakeup_capable(&pdev->dev, true);
1541                 ret = dev_pm_set_wake_irq(&pdev->dev, stm32port->port.irq);
1542                 if (ret)
1543                         goto err_deinit_port;
1544         }
1545
1546         stm32port->rx_ch = dma_request_chan(&pdev->dev, "rx");
1547         if (PTR_ERR(stm32port->rx_ch) == -EPROBE_DEFER) {
1548                 ret = -EPROBE_DEFER;
1549                 goto err_wakeirq;
1550         }
1551         /* Fall back in interrupt mode for any non-deferral error */
1552         if (IS_ERR(stm32port->rx_ch))
1553                 stm32port->rx_ch = NULL;
1554
1555         stm32port->tx_ch = dma_request_chan(&pdev->dev, "tx");
1556         if (PTR_ERR(stm32port->tx_ch) == -EPROBE_DEFER) {
1557                 ret = -EPROBE_DEFER;
1558                 goto err_dma_rx;
1559         }
1560         /* Fall back in interrupt mode for any non-deferral error */
1561         if (IS_ERR(stm32port->tx_ch))
1562                 stm32port->tx_ch = NULL;
1563
1564         if (stm32port->rx_ch && stm32_usart_of_dma_rx_probe(stm32port, pdev)) {
1565                 /* Fall back in interrupt mode */
1566                 dma_release_channel(stm32port->rx_ch);
1567                 stm32port->rx_ch = NULL;
1568         }
1569
1570         if (stm32port->tx_ch && stm32_usart_of_dma_tx_probe(stm32port, pdev)) {
1571                 /* Fall back in interrupt mode */
1572                 dma_release_channel(stm32port->tx_ch);
1573                 stm32port->tx_ch = NULL;
1574         }
1575
1576         if (!stm32port->rx_ch)
1577                 dev_info(&pdev->dev, "interrupt mode for rx (no dma)\n");
1578         if (!stm32port->tx_ch)
1579                 dev_info(&pdev->dev, "interrupt mode for tx (no dma)\n");
1580
1581         platform_set_drvdata(pdev, &stm32port->port);
1582
1583         pm_runtime_get_noresume(&pdev->dev);
1584         pm_runtime_set_active(&pdev->dev);
1585         pm_runtime_enable(&pdev->dev);
1586
1587         ret = uart_add_one_port(&stm32_usart_driver, &stm32port->port);
1588         if (ret)
1589                 goto err_port;
1590
1591         pm_runtime_put_sync(&pdev->dev);
1592
1593         return 0;
1594
1595 err_port:
1596         pm_runtime_disable(&pdev->dev);
1597         pm_runtime_set_suspended(&pdev->dev);
1598         pm_runtime_put_noidle(&pdev->dev);
1599
1600         if (stm32port->tx_ch) {
1601                 stm32_usart_of_dma_tx_remove(stm32port, pdev);
1602                 dma_release_channel(stm32port->tx_ch);
1603         }
1604
1605         if (stm32port->rx_ch)
1606                 stm32_usart_of_dma_rx_remove(stm32port, pdev);
1607
1608 err_dma_rx:
1609         if (stm32port->rx_ch)
1610                 dma_release_channel(stm32port->rx_ch);
1611
1612 err_wakeirq:
1613         if (stm32port->wakeup_src)
1614                 dev_pm_clear_wake_irq(&pdev->dev);
1615
1616 err_deinit_port:
1617         if (stm32port->wakeup_src)
1618                 device_set_wakeup_capable(&pdev->dev, false);
1619
1620         stm32_usart_deinit_port(stm32port);
1621
1622         return ret;
1623 }
1624
1625 static int stm32_usart_serial_remove(struct platform_device *pdev)
1626 {
1627         struct uart_port *port = platform_get_drvdata(pdev);
1628         struct stm32_port *stm32_port = to_stm32_port(port);
1629         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
1630         int err;
1631         u32 cr3;
1632
1633         pm_runtime_get_sync(&pdev->dev);
1634         err = uart_remove_one_port(&stm32_usart_driver, port);
1635         if (err)
1636                 return(err);
1637
1638         pm_runtime_disable(&pdev->dev);
1639         pm_runtime_set_suspended(&pdev->dev);
1640         pm_runtime_put_noidle(&pdev->dev);
1641
1642         stm32_usart_clr_bits(port, ofs->cr1, USART_CR1_PEIE);
1643         cr3 = readl_relaxed(port->membase + ofs->cr3);
1644         cr3 &= ~USART_CR3_EIE;
1645         cr3 &= ~USART_CR3_DMAR;
1646         cr3 &= ~USART_CR3_DDRE;
1647         writel_relaxed(cr3, port->membase + ofs->cr3);
1648
1649         if (stm32_port->tx_ch) {
1650                 stm32_usart_of_dma_tx_remove(stm32_port, pdev);
1651                 dma_release_channel(stm32_port->tx_ch);
1652         }
1653
1654         if (stm32_port->rx_ch) {
1655                 stm32_usart_of_dma_rx_remove(stm32_port, pdev);
1656                 dma_release_channel(stm32_port->rx_ch);
1657         }
1658
1659         stm32_usart_clr_bits(port, ofs->cr3, USART_CR3_DMAT);
1660
1661         if (stm32_port->wakeup_src) {
1662                 dev_pm_clear_wake_irq(&pdev->dev);
1663                 device_init_wakeup(&pdev->dev, false);
1664         }
1665
1666         stm32_usart_deinit_port(stm32_port);
1667
1668         return 0;
1669 }
1670
1671 static void __maybe_unused stm32_usart_console_putchar(struct uart_port *port, unsigned char ch)
1672 {
1673         struct stm32_port *stm32_port = to_stm32_port(port);
1674         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
1675         u32 isr;
1676         int ret;
1677
1678         ret = readl_relaxed_poll_timeout_atomic(port->membase + ofs->isr, isr,
1679                                                 (isr & USART_SR_TXE), 100,
1680                                                 STM32_USART_TIMEOUT_USEC);
1681         if (ret != 0) {
1682                 dev_err(port->dev, "Error while sending data in UART TX : %d\n", ret);
1683                 return;
1684         }
1685         writel_relaxed(ch, port->membase + ofs->tdr);
1686 }
1687
1688 #ifdef CONFIG_SERIAL_STM32_CONSOLE
1689 static void stm32_usart_console_write(struct console *co, const char *s,
1690                                       unsigned int cnt)
1691 {
1692         struct uart_port *port = &stm32_ports[co->index].port;
1693         struct stm32_port *stm32_port = to_stm32_port(port);
1694         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
1695         const struct stm32_usart_config *cfg = &stm32_port->info->cfg;
1696         unsigned long flags;
1697         u32 old_cr1, new_cr1;
1698         int locked = 1;
1699
1700         if (oops_in_progress)
1701                 locked = spin_trylock_irqsave(&port->lock, flags);
1702         else
1703                 spin_lock_irqsave(&port->lock, flags);
1704
1705         /* Save and disable interrupts, enable the transmitter */
1706         old_cr1 = readl_relaxed(port->membase + ofs->cr1);
1707         new_cr1 = old_cr1 & ~USART_CR1_IE_MASK;
1708         new_cr1 |=  USART_CR1_TE | BIT(cfg->uart_enable_bit);
1709         writel_relaxed(new_cr1, port->membase + ofs->cr1);
1710
1711         uart_console_write(port, s, cnt, stm32_usart_console_putchar);
1712
1713         /* Restore interrupt state */
1714         writel_relaxed(old_cr1, port->membase + ofs->cr1);
1715
1716         if (locked)
1717                 spin_unlock_irqrestore(&port->lock, flags);
1718 }
1719
1720 static int stm32_usart_console_setup(struct console *co, char *options)
1721 {
1722         struct stm32_port *stm32port;
1723         int baud = 9600;
1724         int bits = 8;
1725         int parity = 'n';
1726         int flow = 'n';
1727
1728         if (co->index >= STM32_MAX_PORTS)
1729                 return -ENODEV;
1730
1731         stm32port = &stm32_ports[co->index];
1732
1733         /*
1734          * This driver does not support early console initialization
1735          * (use ARM early printk support instead), so we only expect
1736          * this to be called during the uart port registration when the
1737          * driver gets probed and the port should be mapped at that point.
1738          */
1739         if (stm32port->port.mapbase == 0 || !stm32port->port.membase)
1740                 return -ENXIO;
1741
1742         if (options)
1743                 uart_parse_options(options, &baud, &parity, &bits, &flow);
1744
1745         return uart_set_options(&stm32port->port, co, baud, parity, bits, flow);
1746 }
1747
1748 static struct console stm32_console = {
1749         .name           = STM32_SERIAL_NAME,
1750         .device         = uart_console_device,
1751         .write          = stm32_usart_console_write,
1752         .setup          = stm32_usart_console_setup,
1753         .flags          = CON_PRINTBUFFER,
1754         .index          = -1,
1755         .data           = &stm32_usart_driver,
1756 };
1757
1758 #define STM32_SERIAL_CONSOLE (&stm32_console)
1759
1760 #else
1761 #define STM32_SERIAL_CONSOLE NULL
1762 #endif /* CONFIG_SERIAL_STM32_CONSOLE */
1763
1764 #ifdef CONFIG_SERIAL_EARLYCON
1765 static void early_stm32_usart_console_putchar(struct uart_port *port, unsigned char ch)
1766 {
1767         struct stm32_usart_info *info = port->private_data;
1768
1769         while (!(readl_relaxed(port->membase + info->ofs.isr) & USART_SR_TXE))
1770                 cpu_relax();
1771
1772         writel_relaxed(ch, port->membase + info->ofs.tdr);
1773 }
1774
1775 static void early_stm32_serial_write(struct console *console, const char *s, unsigned int count)
1776 {
1777         struct earlycon_device *device = console->data;
1778         struct uart_port *port = &device->port;
1779
1780         uart_console_write(port, s, count, early_stm32_usart_console_putchar);
1781 }
1782
1783 static int __init early_stm32_h7_serial_setup(struct earlycon_device *device, const char *options)
1784 {
1785         if (!(device->port.membase || device->port.iobase))
1786                 return -ENODEV;
1787         device->port.private_data = &stm32h7_info;
1788         device->con->write = early_stm32_serial_write;
1789         return 0;
1790 }
1791
1792 static int __init early_stm32_f7_serial_setup(struct earlycon_device *device, const char *options)
1793 {
1794         if (!(device->port.membase || device->port.iobase))
1795                 return -ENODEV;
1796         device->port.private_data = &stm32f7_info;
1797         device->con->write = early_stm32_serial_write;
1798         return 0;
1799 }
1800
1801 static int __init early_stm32_f4_serial_setup(struct earlycon_device *device, const char *options)
1802 {
1803         if (!(device->port.membase || device->port.iobase))
1804                 return -ENODEV;
1805         device->port.private_data = &stm32f4_info;
1806         device->con->write = early_stm32_serial_write;
1807         return 0;
1808 }
1809
1810 OF_EARLYCON_DECLARE(stm32, "st,stm32h7-uart", early_stm32_h7_serial_setup);
1811 OF_EARLYCON_DECLARE(stm32, "st,stm32f7-uart", early_stm32_f7_serial_setup);
1812 OF_EARLYCON_DECLARE(stm32, "st,stm32-uart", early_stm32_f4_serial_setup);
1813 #endif /* CONFIG_SERIAL_EARLYCON */
1814
1815 static struct uart_driver stm32_usart_driver = {
1816         .driver_name    = DRIVER_NAME,
1817         .dev_name       = STM32_SERIAL_NAME,
1818         .major          = 0,
1819         .minor          = 0,
1820         .nr             = STM32_MAX_PORTS,
1821         .cons           = STM32_SERIAL_CONSOLE,
1822 };
1823
1824 static int __maybe_unused stm32_usart_serial_en_wakeup(struct uart_port *port,
1825                                                        bool enable)
1826 {
1827         struct stm32_port *stm32_port = to_stm32_port(port);
1828         const struct stm32_usart_offsets *ofs = &stm32_port->info->ofs;
1829         struct tty_port *tport = &port->state->port;
1830         int ret;
1831         unsigned int size;
1832         unsigned long flags;
1833
1834         if (!stm32_port->wakeup_src || !tty_port_initialized(tport))
1835                 return 0;
1836
1837         /*
1838          * Enable low-power wake-up and wake-up irq if argument is set to
1839          * "enable", disable low-power wake-up and wake-up irq otherwise
1840          */
1841         if (enable) {
1842                 stm32_usart_set_bits(port, ofs->cr1, USART_CR1_UESM);
1843                 stm32_usart_set_bits(port, ofs->cr3, USART_CR3_WUFIE);
1844                 mctrl_gpio_enable_irq_wake(stm32_port->gpios);
1845
1846                 /*
1847                  * When DMA is used for reception, it must be disabled before
1848                  * entering low-power mode and re-enabled when exiting from
1849                  * low-power mode.
1850                  */
1851                 if (stm32_port->rx_ch) {
1852                         spin_lock_irqsave(&port->lock, flags);
1853                         /* Avoid race with RX IRQ when DMAR is cleared */
1854                         stm32_usart_clr_bits(port, ofs->cr3, USART_CR3_DMAR);
1855                         /* Poll data from DMA RX buffer if any */
1856                         size = stm32_usart_receive_chars(port, true);
1857                         dmaengine_terminate_async(stm32_port->rx_ch);
1858                         uart_unlock_and_check_sysrq_irqrestore(port, flags);
1859                         if (size)
1860                                 tty_flip_buffer_push(tport);
1861                 }
1862
1863                 /* Poll data from RX FIFO if any */
1864                 stm32_usart_receive_chars(port, false);
1865         } else {
1866                 if (stm32_port->rx_ch) {
1867                         ret = stm32_usart_start_rx_dma_cyclic(port);
1868                         if (ret)
1869                                 return ret;
1870                 }
1871                 mctrl_gpio_disable_irq_wake(stm32_port->gpios);
1872                 stm32_usart_clr_bits(port, ofs->cr1, USART_CR1_UESM);
1873                 stm32_usart_clr_bits(port, ofs->cr3, USART_CR3_WUFIE);
1874         }
1875
1876         return 0;
1877 }
1878
1879 static int __maybe_unused stm32_usart_serial_suspend(struct device *dev)
1880 {
1881         struct uart_port *port = dev_get_drvdata(dev);
1882         int ret;
1883
1884         uart_suspend_port(&stm32_usart_driver, port);
1885
1886         if (device_may_wakeup(dev) || device_wakeup_path(dev)) {
1887                 ret = stm32_usart_serial_en_wakeup(port, true);
1888                 if (ret)
1889                         return ret;
1890         }
1891
1892         /*
1893          * When "no_console_suspend" is enabled, keep the pinctrl default state
1894          * and rely on bootloader stage to restore this state upon resume.
1895          * Otherwise, apply the idle or sleep states depending on wakeup
1896          * capabilities.
1897          */
1898         if (console_suspend_enabled || !uart_console(port)) {
1899                 if (device_may_wakeup(dev) || device_wakeup_path(dev))
1900                         pinctrl_pm_select_idle_state(dev);
1901                 else
1902                         pinctrl_pm_select_sleep_state(dev);
1903         }
1904
1905         return 0;
1906 }
1907
1908 static int __maybe_unused stm32_usart_serial_resume(struct device *dev)
1909 {
1910         struct uart_port *port = dev_get_drvdata(dev);
1911         int ret;
1912
1913         pinctrl_pm_select_default_state(dev);
1914
1915         if (device_may_wakeup(dev) || device_wakeup_path(dev)) {
1916                 ret = stm32_usart_serial_en_wakeup(port, false);
1917                 if (ret)
1918                         return ret;
1919         }
1920
1921         return uart_resume_port(&stm32_usart_driver, port);
1922 }
1923
1924 static int __maybe_unused stm32_usart_runtime_suspend(struct device *dev)
1925 {
1926         struct uart_port *port = dev_get_drvdata(dev);
1927         struct stm32_port *stm32port = container_of(port,
1928                         struct stm32_port, port);
1929
1930         clk_disable_unprepare(stm32port->clk);
1931
1932         return 0;
1933 }
1934
1935 static int __maybe_unused stm32_usart_runtime_resume(struct device *dev)
1936 {
1937         struct uart_port *port = dev_get_drvdata(dev);
1938         struct stm32_port *stm32port = container_of(port,
1939                         struct stm32_port, port);
1940
1941         return clk_prepare_enable(stm32port->clk);
1942 }
1943
1944 static const struct dev_pm_ops stm32_serial_pm_ops = {
1945         SET_RUNTIME_PM_OPS(stm32_usart_runtime_suspend,
1946                            stm32_usart_runtime_resume, NULL)
1947         SET_SYSTEM_SLEEP_PM_OPS(stm32_usart_serial_suspend,
1948                                 stm32_usart_serial_resume)
1949 };
1950
1951 static struct platform_driver stm32_serial_driver = {
1952         .probe          = stm32_usart_serial_probe,
1953         .remove         = stm32_usart_serial_remove,
1954         .driver = {
1955                 .name   = DRIVER_NAME,
1956                 .pm     = &stm32_serial_pm_ops,
1957                 .of_match_table = of_match_ptr(stm32_match),
1958         },
1959 };
1960
1961 static int __init stm32_usart_init(void)
1962 {
1963         static char banner[] __initdata = "STM32 USART driver initialized";
1964         int ret;
1965
1966         pr_info("%s\n", banner);
1967
1968         ret = uart_register_driver(&stm32_usart_driver);
1969         if (ret)
1970                 return ret;
1971
1972         ret = platform_driver_register(&stm32_serial_driver);
1973         if (ret)
1974                 uart_unregister_driver(&stm32_usart_driver);
1975
1976         return ret;
1977 }
1978
1979 static void __exit stm32_usart_exit(void)
1980 {
1981         platform_driver_unregister(&stm32_serial_driver);
1982         uart_unregister_driver(&stm32_usart_driver);
1983 }
1984
1985 module_init(stm32_usart_init);
1986 module_exit(stm32_usart_exit);
1987
1988 MODULE_ALIAS("platform:" DRIVER_NAME);
1989 MODULE_DESCRIPTION("STMicroelectronics STM32 serial port driver");
1990 MODULE_LICENSE("GPL v2");