xref: /openbmc/qemu/hw/char/serial.c (revision 80e5db30)
1 /*
2  * QEMU 16550A UART emulation
3  *
4  * Copyright (c) 2003-2004 Fabrice Bellard
5  * Copyright (c) 2008 Citrix Systems, Inc.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25 
26 #include "qemu/osdep.h"
27 #include "hw/char/serial.h"
28 #include "sysemu/char.h"
29 #include "qapi/error.h"
30 #include "qemu/timer.h"
31 #include "exec/address-spaces.h"
32 #include "qemu/error-report.h"
33 
34 //#define DEBUG_SERIAL
35 
36 #define UART_LCR_DLAB	0x80	/* Divisor latch access bit */
37 
38 #define UART_IER_MSI	0x08	/* Enable Modem status interrupt */
39 #define UART_IER_RLSI	0x04	/* Enable receiver line status interrupt */
40 #define UART_IER_THRI	0x02	/* Enable Transmitter holding register int. */
41 #define UART_IER_RDI	0x01	/* Enable receiver data interrupt */
42 
43 #define UART_IIR_NO_INT	0x01	/* No interrupts pending */
44 #define UART_IIR_ID	0x06	/* Mask for the interrupt ID */
45 
46 #define UART_IIR_MSI	0x00	/* Modem status interrupt */
47 #define UART_IIR_THRI	0x02	/* Transmitter holding register empty */
48 #define UART_IIR_RDI	0x04	/* Receiver data interrupt */
49 #define UART_IIR_RLSI	0x06	/* Receiver line status interrupt */
50 #define UART_IIR_CTI    0x0C    /* Character Timeout Indication */
51 
52 #define UART_IIR_FENF   0x80    /* Fifo enabled, but not functionning */
53 #define UART_IIR_FE     0xC0    /* Fifo enabled */
54 
55 /*
56  * These are the definitions for the Modem Control Register
57  */
58 #define UART_MCR_LOOP	0x10	/* Enable loopback test mode */
59 #define UART_MCR_OUT2	0x08	/* Out2 complement */
60 #define UART_MCR_OUT1	0x04	/* Out1 complement */
61 #define UART_MCR_RTS	0x02	/* RTS complement */
62 #define UART_MCR_DTR	0x01	/* DTR complement */
63 
64 /*
65  * These are the definitions for the Modem Status Register
66  */
67 #define UART_MSR_DCD	0x80	/* Data Carrier Detect */
68 #define UART_MSR_RI	0x40	/* Ring Indicator */
69 #define UART_MSR_DSR	0x20	/* Data Set Ready */
70 #define UART_MSR_CTS	0x10	/* Clear to Send */
71 #define UART_MSR_DDCD	0x08	/* Delta DCD */
72 #define UART_MSR_TERI	0x04	/* Trailing edge ring indicator */
73 #define UART_MSR_DDSR	0x02	/* Delta DSR */
74 #define UART_MSR_DCTS	0x01	/* Delta CTS */
75 #define UART_MSR_ANY_DELTA 0x0F	/* Any of the delta bits! */
76 
77 #define UART_LSR_TEMT	0x40	/* Transmitter empty */
78 #define UART_LSR_THRE	0x20	/* Transmit-hold-register empty */
79 #define UART_LSR_BI	0x10	/* Break interrupt indicator */
80 #define UART_LSR_FE	0x08	/* Frame error indicator */
81 #define UART_LSR_PE	0x04	/* Parity error indicator */
82 #define UART_LSR_OE	0x02	/* Overrun error indicator */
83 #define UART_LSR_DR	0x01	/* Receiver data ready */
84 #define UART_LSR_INT_ANY 0x1E	/* Any of the lsr-interrupt-triggering status bits */
85 
86 /* Interrupt trigger levels. The byte-counts are for 16550A - in newer UARTs the byte-count for each ITL is higher. */
87 
88 #define UART_FCR_ITL_1      0x00 /* 1 byte ITL */
89 #define UART_FCR_ITL_2      0x40 /* 4 bytes ITL */
90 #define UART_FCR_ITL_3      0x80 /* 8 bytes ITL */
91 #define UART_FCR_ITL_4      0xC0 /* 14 bytes ITL */
92 
93 #define UART_FCR_DMS        0x08    /* DMA Mode Select */
94 #define UART_FCR_XFR        0x04    /* XMIT Fifo Reset */
95 #define UART_FCR_RFR        0x02    /* RCVR Fifo Reset */
96 #define UART_FCR_FE         0x01    /* FIFO Enable */
97 
98 #define MAX_XMIT_RETRY      4
99 
100 #ifdef DEBUG_SERIAL
101 #define DPRINTF(fmt, ...) \
102 do { fprintf(stderr, "serial: " fmt , ## __VA_ARGS__); } while (0)
103 #else
104 #define DPRINTF(fmt, ...) \
105 do {} while (0)
106 #endif
107 
108 static void serial_receive1(void *opaque, const uint8_t *buf, int size);
109 static void serial_xmit(SerialState *s);
110 
111 static inline void recv_fifo_put(SerialState *s, uint8_t chr)
112 {
113     /* Receive overruns do not overwrite FIFO contents. */
114     if (!fifo8_is_full(&s->recv_fifo)) {
115         fifo8_push(&s->recv_fifo, chr);
116     } else {
117         s->lsr |= UART_LSR_OE;
118     }
119 }
120 
121 static void serial_update_irq(SerialState *s)
122 {
123     uint8_t tmp_iir = UART_IIR_NO_INT;
124 
125     if ((s->ier & UART_IER_RLSI) && (s->lsr & UART_LSR_INT_ANY)) {
126         tmp_iir = UART_IIR_RLSI;
127     } else if ((s->ier & UART_IER_RDI) && s->timeout_ipending) {
128         /* Note that(s->ier & UART_IER_RDI) can mask this interrupt,
129          * this is not in the specification but is observed on existing
130          * hardware.  */
131         tmp_iir = UART_IIR_CTI;
132     } else if ((s->ier & UART_IER_RDI) && (s->lsr & UART_LSR_DR) &&
133                (!(s->fcr & UART_FCR_FE) ||
134                 s->recv_fifo.num >= s->recv_fifo_itl)) {
135         tmp_iir = UART_IIR_RDI;
136     } else if ((s->ier & UART_IER_THRI) && s->thr_ipending) {
137         tmp_iir = UART_IIR_THRI;
138     } else if ((s->ier & UART_IER_MSI) && (s->msr & UART_MSR_ANY_DELTA)) {
139         tmp_iir = UART_IIR_MSI;
140     }
141 
142     s->iir = tmp_iir | (s->iir & 0xF0);
143 
144     if (tmp_iir != UART_IIR_NO_INT) {
145         qemu_irq_raise(s->irq);
146     } else {
147         qemu_irq_lower(s->irq);
148     }
149 }
150 
151 static void serial_update_parameters(SerialState *s)
152 {
153     int speed, parity, data_bits, stop_bits, frame_size;
154     QEMUSerialSetParams ssp;
155 
156     if (s->divider == 0 || s->divider > s->baudbase) {
157         return;
158     }
159 
160     /* Start bit. */
161     frame_size = 1;
162     if (s->lcr & 0x08) {
163         /* Parity bit. */
164         frame_size++;
165         if (s->lcr & 0x10)
166             parity = 'E';
167         else
168             parity = 'O';
169     } else {
170             parity = 'N';
171     }
172     if (s->lcr & 0x04)
173         stop_bits = 2;
174     else
175         stop_bits = 1;
176 
177     data_bits = (s->lcr & 0x03) + 5;
178     frame_size += data_bits + stop_bits;
179     speed = s->baudbase / s->divider;
180     ssp.speed = speed;
181     ssp.parity = parity;
182     ssp.data_bits = data_bits;
183     ssp.stop_bits = stop_bits;
184     s->char_transmit_time =  (NANOSECONDS_PER_SECOND / speed) * frame_size;
185     qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_SET_PARAMS, &ssp);
186 
187     DPRINTF("speed=%d parity=%c data=%d stop=%d\n",
188            speed, parity, data_bits, stop_bits);
189 }
190 
191 static void serial_update_msl(SerialState *s)
192 {
193     uint8_t omsr;
194     int flags;
195 
196     timer_del(s->modem_status_poll);
197 
198     if (qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_GET_TIOCM,
199                           &flags) == -ENOTSUP) {
200         s->poll_msl = -1;
201         return;
202     }
203 
204     omsr = s->msr;
205 
206     s->msr = (flags & CHR_TIOCM_CTS) ? s->msr | UART_MSR_CTS : s->msr & ~UART_MSR_CTS;
207     s->msr = (flags & CHR_TIOCM_DSR) ? s->msr | UART_MSR_DSR : s->msr & ~UART_MSR_DSR;
208     s->msr = (flags & CHR_TIOCM_CAR) ? s->msr | UART_MSR_DCD : s->msr & ~UART_MSR_DCD;
209     s->msr = (flags & CHR_TIOCM_RI) ? s->msr | UART_MSR_RI : s->msr & ~UART_MSR_RI;
210 
211     if (s->msr != omsr) {
212          /* Set delta bits */
213          s->msr = s->msr | ((s->msr >> 4) ^ (omsr >> 4));
214          /* UART_MSR_TERI only if change was from 1 -> 0 */
215          if ((s->msr & UART_MSR_TERI) && !(omsr & UART_MSR_RI))
216              s->msr &= ~UART_MSR_TERI;
217          serial_update_irq(s);
218     }
219 
220     /* The real 16550A apparently has a 250ns response latency to line status changes.
221        We'll be lazy and poll only every 10ms, and only poll it at all if MSI interrupts are turned on */
222 
223     if (s->poll_msl) {
224         timer_mod(s->modem_status_poll, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
225                   NANOSECONDS_PER_SECOND / 100);
226     }
227 }
228 
229 static gboolean serial_watch_cb(GIOChannel *chan, GIOCondition cond,
230                                 void *opaque)
231 {
232     SerialState *s = opaque;
233     s->watch_tag = 0;
234     serial_xmit(s);
235     return FALSE;
236 }
237 
238 static void serial_xmit(SerialState *s)
239 {
240     do {
241         assert(!(s->lsr & UART_LSR_TEMT));
242         if (s->tsr_retry == 0) {
243             assert(!(s->lsr & UART_LSR_THRE));
244 
245             if (s->fcr & UART_FCR_FE) {
246                 assert(!fifo8_is_empty(&s->xmit_fifo));
247                 s->tsr = fifo8_pop(&s->xmit_fifo);
248                 if (!s->xmit_fifo.num) {
249                     s->lsr |= UART_LSR_THRE;
250                 }
251             } else {
252                 s->tsr = s->thr;
253                 s->lsr |= UART_LSR_THRE;
254             }
255             if ((s->lsr & UART_LSR_THRE) && !s->thr_ipending) {
256                 s->thr_ipending = 1;
257                 serial_update_irq(s);
258             }
259         }
260 
261         if (s->mcr & UART_MCR_LOOP) {
262             /* in loopback mode, say that we just received a char */
263             serial_receive1(s, &s->tsr, 1);
264         } else if (qemu_chr_fe_write(&s->chr, &s->tsr, 1) != 1 &&
265                    s->tsr_retry < MAX_XMIT_RETRY) {
266             assert(s->watch_tag == 0);
267             s->watch_tag =
268                 qemu_chr_fe_add_watch(&s->chr, G_IO_OUT | G_IO_HUP,
269                                       serial_watch_cb, s);
270             if (s->watch_tag > 0) {
271                 s->tsr_retry++;
272                 return;
273             }
274         }
275         s->tsr_retry = 0;
276 
277         /* Transmit another byte if it is already available. It is only
278            possible when FIFO is enabled and not empty. */
279     } while (!(s->lsr & UART_LSR_THRE));
280 
281     s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
282     s->lsr |= UART_LSR_TEMT;
283 }
284 
285 /* Setter for FCR.
286    is_load flag means, that value is set while loading VM state
287    and interrupt should not be invoked */
288 static void serial_write_fcr(SerialState *s, uint8_t val)
289 {
290     /* Set fcr - val only has the bits that are supposed to "stick" */
291     s->fcr = val;
292 
293     if (val & UART_FCR_FE) {
294         s->iir |= UART_IIR_FE;
295         /* Set recv_fifo trigger Level */
296         switch (val & 0xC0) {
297         case UART_FCR_ITL_1:
298             s->recv_fifo_itl = 1;
299             break;
300         case UART_FCR_ITL_2:
301             s->recv_fifo_itl = 4;
302             break;
303         case UART_FCR_ITL_3:
304             s->recv_fifo_itl = 8;
305             break;
306         case UART_FCR_ITL_4:
307             s->recv_fifo_itl = 14;
308             break;
309         }
310     } else {
311         s->iir &= ~UART_IIR_FE;
312     }
313 }
314 
315 static void serial_ioport_write(void *opaque, hwaddr addr, uint64_t val,
316                                 unsigned size)
317 {
318     SerialState *s = opaque;
319 
320     addr &= 7;
321     DPRINTF("write addr=0x%" HWADDR_PRIx " val=0x%" PRIx64 "\n", addr, val);
322     switch(addr) {
323     default:
324     case 0:
325         if (s->lcr & UART_LCR_DLAB) {
326             s->divider = (s->divider & 0xff00) | val;
327             serial_update_parameters(s);
328         } else {
329             s->thr = (uint8_t) val;
330             if(s->fcr & UART_FCR_FE) {
331                 /* xmit overruns overwrite data, so make space if needed */
332                 if (fifo8_is_full(&s->xmit_fifo)) {
333                     fifo8_pop(&s->xmit_fifo);
334                 }
335                 fifo8_push(&s->xmit_fifo, s->thr);
336             }
337             s->thr_ipending = 0;
338             s->lsr &= ~UART_LSR_THRE;
339             s->lsr &= ~UART_LSR_TEMT;
340             serial_update_irq(s);
341             if (s->tsr_retry == 0) {
342                 serial_xmit(s);
343             }
344         }
345         break;
346     case 1:
347         if (s->lcr & UART_LCR_DLAB) {
348             s->divider = (s->divider & 0x00ff) | (val << 8);
349             serial_update_parameters(s);
350         } else {
351             uint8_t changed = (s->ier ^ val) & 0x0f;
352             s->ier = val & 0x0f;
353             /* If the backend device is a real serial port, turn polling of the modem
354              * status lines on physical port on or off depending on UART_IER_MSI state.
355              */
356             if ((changed & UART_IER_MSI) && s->poll_msl >= 0) {
357                 if (s->ier & UART_IER_MSI) {
358                      s->poll_msl = 1;
359                      serial_update_msl(s);
360                 } else {
361                      timer_del(s->modem_status_poll);
362                      s->poll_msl = 0;
363                 }
364             }
365 
366             /* Turning on the THRE interrupt on IER can trigger the interrupt
367              * if LSR.THRE=1, even if it had been masked before by reading IIR.
368              * This is not in the datasheet, but Windows relies on it.  It is
369              * unclear if THRE has to be resampled every time THRI becomes
370              * 1, or only on the rising edge.  Bochs does the latter, and Windows
371              * always toggles IER to all zeroes and back to all ones, so do the
372              * same.
373              *
374              * If IER.THRI is zero, thr_ipending is not used.  Set it to zero
375              * so that the thr_ipending subsection is not migrated.
376              */
377             if (changed & UART_IER_THRI) {
378                 if ((s->ier & UART_IER_THRI) && (s->lsr & UART_LSR_THRE)) {
379                     s->thr_ipending = 1;
380                 } else {
381                     s->thr_ipending = 0;
382                 }
383             }
384 
385             if (changed) {
386                 serial_update_irq(s);
387             }
388         }
389         break;
390     case 2:
391         /* Did the enable/disable flag change? If so, make sure FIFOs get flushed */
392         if ((val ^ s->fcr) & UART_FCR_FE) {
393             val |= UART_FCR_XFR | UART_FCR_RFR;
394         }
395 
396         /* FIFO clear */
397 
398         if (val & UART_FCR_RFR) {
399             s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
400             timer_del(s->fifo_timeout_timer);
401             s->timeout_ipending = 0;
402             fifo8_reset(&s->recv_fifo);
403         }
404 
405         if (val & UART_FCR_XFR) {
406             s->lsr |= UART_LSR_THRE;
407             s->thr_ipending = 1;
408             fifo8_reset(&s->xmit_fifo);
409         }
410 
411         serial_write_fcr(s, val & 0xC9);
412         serial_update_irq(s);
413         break;
414     case 3:
415         {
416             int break_enable;
417             s->lcr = val;
418             serial_update_parameters(s);
419             break_enable = (val >> 6) & 1;
420             if (break_enable != s->last_break_enable) {
421                 s->last_break_enable = break_enable;
422                 qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_SET_BREAK,
423                                   &break_enable);
424             }
425         }
426         break;
427     case 4:
428         {
429             int flags;
430             int old_mcr = s->mcr;
431             s->mcr = val & 0x1f;
432             if (val & UART_MCR_LOOP)
433                 break;
434 
435             if (s->poll_msl >= 0 && old_mcr != s->mcr) {
436 
437                 qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_GET_TIOCM, &flags);
438 
439                 flags &= ~(CHR_TIOCM_RTS | CHR_TIOCM_DTR);
440 
441                 if (val & UART_MCR_RTS)
442                     flags |= CHR_TIOCM_RTS;
443                 if (val & UART_MCR_DTR)
444                     flags |= CHR_TIOCM_DTR;
445 
446                 qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_SET_TIOCM, &flags);
447                 /* Update the modem status after a one-character-send wait-time, since there may be a response
448                    from the device/computer at the other end of the serial line */
449                 timer_mod(s->modem_status_poll, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time);
450             }
451         }
452         break;
453     case 5:
454         break;
455     case 6:
456         break;
457     case 7:
458         s->scr = val;
459         break;
460     }
461 }
462 
463 static uint64_t serial_ioport_read(void *opaque, hwaddr addr, unsigned size)
464 {
465     SerialState *s = opaque;
466     uint32_t ret;
467 
468     addr &= 7;
469     switch(addr) {
470     default:
471     case 0:
472         if (s->lcr & UART_LCR_DLAB) {
473             ret = s->divider & 0xff;
474         } else {
475             if(s->fcr & UART_FCR_FE) {
476                 ret = fifo8_is_empty(&s->recv_fifo) ?
477                             0 : fifo8_pop(&s->recv_fifo);
478                 if (s->recv_fifo.num == 0) {
479                     s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
480                 } else {
481                     timer_mod(s->fifo_timeout_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time * 4);
482                 }
483                 s->timeout_ipending = 0;
484             } else {
485                 ret = s->rbr;
486                 s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
487             }
488             serial_update_irq(s);
489             if (!(s->mcr & UART_MCR_LOOP)) {
490                 /* in loopback mode, don't receive any data */
491                 qemu_chr_fe_accept_input(&s->chr);
492             }
493         }
494         break;
495     case 1:
496         if (s->lcr & UART_LCR_DLAB) {
497             ret = (s->divider >> 8) & 0xff;
498         } else {
499             ret = s->ier;
500         }
501         break;
502     case 2:
503         ret = s->iir;
504         if ((ret & UART_IIR_ID) == UART_IIR_THRI) {
505             s->thr_ipending = 0;
506             serial_update_irq(s);
507         }
508         break;
509     case 3:
510         ret = s->lcr;
511         break;
512     case 4:
513         ret = s->mcr;
514         break;
515     case 5:
516         ret = s->lsr;
517         /* Clear break and overrun interrupts */
518         if (s->lsr & (UART_LSR_BI|UART_LSR_OE)) {
519             s->lsr &= ~(UART_LSR_BI|UART_LSR_OE);
520             serial_update_irq(s);
521         }
522         break;
523     case 6:
524         if (s->mcr & UART_MCR_LOOP) {
525             /* in loopback, the modem output pins are connected to the
526                inputs */
527             ret = (s->mcr & 0x0c) << 4;
528             ret |= (s->mcr & 0x02) << 3;
529             ret |= (s->mcr & 0x01) << 5;
530         } else {
531             if (s->poll_msl >= 0)
532                 serial_update_msl(s);
533             ret = s->msr;
534             /* Clear delta bits & msr int after read, if they were set */
535             if (s->msr & UART_MSR_ANY_DELTA) {
536                 s->msr &= 0xF0;
537                 serial_update_irq(s);
538             }
539         }
540         break;
541     case 7:
542         ret = s->scr;
543         break;
544     }
545     DPRINTF("read addr=0x%" HWADDR_PRIx " val=0x%02x\n", addr, ret);
546     return ret;
547 }
548 
549 static int serial_can_receive(SerialState *s)
550 {
551     if(s->fcr & UART_FCR_FE) {
552         if (s->recv_fifo.num < UART_FIFO_LENGTH) {
553             /*
554              * Advertise (fifo.itl - fifo.count) bytes when count < ITL, and 1
555              * if above. If UART_FIFO_LENGTH - fifo.count is advertised the
556              * effect will be to almost always fill the fifo completely before
557              * the guest has a chance to respond, effectively overriding the ITL
558              * that the guest has set.
559              */
560             return (s->recv_fifo.num <= s->recv_fifo_itl) ?
561                         s->recv_fifo_itl - s->recv_fifo.num : 1;
562         } else {
563             return 0;
564         }
565     } else {
566         return !(s->lsr & UART_LSR_DR);
567     }
568 }
569 
570 static void serial_receive_break(SerialState *s)
571 {
572     s->rbr = 0;
573     /* When the LSR_DR is set a null byte is pushed into the fifo */
574     recv_fifo_put(s, '\0');
575     s->lsr |= UART_LSR_BI | UART_LSR_DR;
576     serial_update_irq(s);
577 }
578 
579 /* There's data in recv_fifo and s->rbr has not been read for 4 char transmit times */
580 static void fifo_timeout_int (void *opaque) {
581     SerialState *s = opaque;
582     if (s->recv_fifo.num) {
583         s->timeout_ipending = 1;
584         serial_update_irq(s);
585     }
586 }
587 
588 static int serial_can_receive1(void *opaque)
589 {
590     SerialState *s = opaque;
591     return serial_can_receive(s);
592 }
593 
594 static void serial_receive1(void *opaque, const uint8_t *buf, int size)
595 {
596     SerialState *s = opaque;
597 
598     if (s->wakeup) {
599         qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
600     }
601     if(s->fcr & UART_FCR_FE) {
602         int i;
603         for (i = 0; i < size; i++) {
604             recv_fifo_put(s, buf[i]);
605         }
606         s->lsr |= UART_LSR_DR;
607         /* call the timeout receive callback in 4 char transmit time */
608         timer_mod(s->fifo_timeout_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time * 4);
609     } else {
610         if (s->lsr & UART_LSR_DR)
611             s->lsr |= UART_LSR_OE;
612         s->rbr = buf[0];
613         s->lsr |= UART_LSR_DR;
614     }
615     serial_update_irq(s);
616 }
617 
618 static void serial_event(void *opaque, int event)
619 {
620     SerialState *s = opaque;
621     DPRINTF("event %x\n", event);
622     if (event == CHR_EVENT_BREAK)
623         serial_receive_break(s);
624 }
625 
626 static void serial_pre_save(void *opaque)
627 {
628     SerialState *s = opaque;
629     s->fcr_vmstate = s->fcr;
630 }
631 
632 static int serial_pre_load(void *opaque)
633 {
634     SerialState *s = opaque;
635     s->thr_ipending = -1;
636     s->poll_msl = -1;
637     return 0;
638 }
639 
640 static int serial_post_load(void *opaque, int version_id)
641 {
642     SerialState *s = opaque;
643 
644     if (version_id < 3) {
645         s->fcr_vmstate = 0;
646     }
647     if (s->thr_ipending == -1) {
648         s->thr_ipending = ((s->iir & UART_IIR_ID) == UART_IIR_THRI);
649     }
650 
651     if (s->tsr_retry > 0) {
652         /* tsr_retry > 0 implies LSR.TEMT = 0 (transmitter not empty).  */
653         if (s->lsr & UART_LSR_TEMT) {
654             error_report("inconsistent state in serial device "
655                          "(tsr empty, tsr_retry=%d", s->tsr_retry);
656             return -1;
657         }
658 
659         if (s->tsr_retry > MAX_XMIT_RETRY) {
660             s->tsr_retry = MAX_XMIT_RETRY;
661         }
662 
663         assert(s->watch_tag == 0);
664         s->watch_tag = qemu_chr_fe_add_watch(&s->chr, G_IO_OUT | G_IO_HUP,
665                                              serial_watch_cb, s);
666     } else {
667         /* tsr_retry == 0 implies LSR.TEMT = 1 (transmitter empty).  */
668         if (!(s->lsr & UART_LSR_TEMT)) {
669             error_report("inconsistent state in serial device "
670                          "(tsr not empty, tsr_retry=0");
671             return -1;
672         }
673     }
674 
675     s->last_break_enable = (s->lcr >> 6) & 1;
676     /* Initialize fcr via setter to perform essential side-effects */
677     serial_write_fcr(s, s->fcr_vmstate);
678     serial_update_parameters(s);
679     return 0;
680 }
681 
682 static bool serial_thr_ipending_needed(void *opaque)
683 {
684     SerialState *s = opaque;
685 
686     if (s->ier & UART_IER_THRI) {
687         bool expected_value = ((s->iir & UART_IIR_ID) == UART_IIR_THRI);
688         return s->thr_ipending != expected_value;
689     } else {
690         /* LSR.THRE will be sampled again when the interrupt is
691          * enabled.  thr_ipending is not used in this case, do
692          * not migrate it.
693          */
694         return false;
695     }
696 }
697 
698 static const VMStateDescription vmstate_serial_thr_ipending = {
699     .name = "serial/thr_ipending",
700     .version_id = 1,
701     .minimum_version_id = 1,
702     .needed = serial_thr_ipending_needed,
703     .fields = (VMStateField[]) {
704         VMSTATE_INT32(thr_ipending, SerialState),
705         VMSTATE_END_OF_LIST()
706     }
707 };
708 
709 static bool serial_tsr_needed(void *opaque)
710 {
711     SerialState *s = (SerialState *)opaque;
712     return s->tsr_retry != 0;
713 }
714 
715 static const VMStateDescription vmstate_serial_tsr = {
716     .name = "serial/tsr",
717     .version_id = 1,
718     .minimum_version_id = 1,
719     .needed = serial_tsr_needed,
720     .fields = (VMStateField[]) {
721         VMSTATE_UINT32(tsr_retry, SerialState),
722         VMSTATE_UINT8(thr, SerialState),
723         VMSTATE_UINT8(tsr, SerialState),
724         VMSTATE_END_OF_LIST()
725     }
726 };
727 
728 static bool serial_recv_fifo_needed(void *opaque)
729 {
730     SerialState *s = (SerialState *)opaque;
731     return !fifo8_is_empty(&s->recv_fifo);
732 
733 }
734 
735 static const VMStateDescription vmstate_serial_recv_fifo = {
736     .name = "serial/recv_fifo",
737     .version_id = 1,
738     .minimum_version_id = 1,
739     .needed = serial_recv_fifo_needed,
740     .fields = (VMStateField[]) {
741         VMSTATE_STRUCT(recv_fifo, SerialState, 1, vmstate_fifo8, Fifo8),
742         VMSTATE_END_OF_LIST()
743     }
744 };
745 
746 static bool serial_xmit_fifo_needed(void *opaque)
747 {
748     SerialState *s = (SerialState *)opaque;
749     return !fifo8_is_empty(&s->xmit_fifo);
750 }
751 
752 static const VMStateDescription vmstate_serial_xmit_fifo = {
753     .name = "serial/xmit_fifo",
754     .version_id = 1,
755     .minimum_version_id = 1,
756     .needed = serial_xmit_fifo_needed,
757     .fields = (VMStateField[]) {
758         VMSTATE_STRUCT(xmit_fifo, SerialState, 1, vmstate_fifo8, Fifo8),
759         VMSTATE_END_OF_LIST()
760     }
761 };
762 
763 static bool serial_fifo_timeout_timer_needed(void *opaque)
764 {
765     SerialState *s = (SerialState *)opaque;
766     return timer_pending(s->fifo_timeout_timer);
767 }
768 
769 static const VMStateDescription vmstate_serial_fifo_timeout_timer = {
770     .name = "serial/fifo_timeout_timer",
771     .version_id = 1,
772     .minimum_version_id = 1,
773     .needed = serial_fifo_timeout_timer_needed,
774     .fields = (VMStateField[]) {
775         VMSTATE_TIMER_PTR(fifo_timeout_timer, SerialState),
776         VMSTATE_END_OF_LIST()
777     }
778 };
779 
780 static bool serial_timeout_ipending_needed(void *opaque)
781 {
782     SerialState *s = (SerialState *)opaque;
783     return s->timeout_ipending != 0;
784 }
785 
786 static const VMStateDescription vmstate_serial_timeout_ipending = {
787     .name = "serial/timeout_ipending",
788     .version_id = 1,
789     .minimum_version_id = 1,
790     .needed = serial_timeout_ipending_needed,
791     .fields = (VMStateField[]) {
792         VMSTATE_INT32(timeout_ipending, SerialState),
793         VMSTATE_END_OF_LIST()
794     }
795 };
796 
797 static bool serial_poll_needed(void *opaque)
798 {
799     SerialState *s = (SerialState *)opaque;
800     return s->poll_msl >= 0;
801 }
802 
803 static const VMStateDescription vmstate_serial_poll = {
804     .name = "serial/poll",
805     .version_id = 1,
806     .needed = serial_poll_needed,
807     .minimum_version_id = 1,
808     .fields = (VMStateField[]) {
809         VMSTATE_INT32(poll_msl, SerialState),
810         VMSTATE_TIMER_PTR(modem_status_poll, SerialState),
811         VMSTATE_END_OF_LIST()
812     }
813 };
814 
815 const VMStateDescription vmstate_serial = {
816     .name = "serial",
817     .version_id = 3,
818     .minimum_version_id = 2,
819     .pre_save = serial_pre_save,
820     .pre_load = serial_pre_load,
821     .post_load = serial_post_load,
822     .fields = (VMStateField[]) {
823         VMSTATE_UINT16_V(divider, SerialState, 2),
824         VMSTATE_UINT8(rbr, SerialState),
825         VMSTATE_UINT8(ier, SerialState),
826         VMSTATE_UINT8(iir, SerialState),
827         VMSTATE_UINT8(lcr, SerialState),
828         VMSTATE_UINT8(mcr, SerialState),
829         VMSTATE_UINT8(lsr, SerialState),
830         VMSTATE_UINT8(msr, SerialState),
831         VMSTATE_UINT8(scr, SerialState),
832         VMSTATE_UINT8_V(fcr_vmstate, SerialState, 3),
833         VMSTATE_END_OF_LIST()
834     },
835     .subsections = (const VMStateDescription*[]) {
836         &vmstate_serial_thr_ipending,
837         &vmstate_serial_tsr,
838         &vmstate_serial_recv_fifo,
839         &vmstate_serial_xmit_fifo,
840         &vmstate_serial_fifo_timeout_timer,
841         &vmstate_serial_timeout_ipending,
842         &vmstate_serial_poll,
843         NULL
844     }
845 };
846 
847 static void serial_reset(void *opaque)
848 {
849     SerialState *s = opaque;
850 
851     if (s->watch_tag > 0) {
852         g_source_remove(s->watch_tag);
853         s->watch_tag = 0;
854     }
855 
856     s->rbr = 0;
857     s->ier = 0;
858     s->iir = UART_IIR_NO_INT;
859     s->lcr = 0;
860     s->lsr = UART_LSR_TEMT | UART_LSR_THRE;
861     s->msr = UART_MSR_DCD | UART_MSR_DSR | UART_MSR_CTS;
862     /* Default to 9600 baud, 1 start bit, 8 data bits, 1 stop bit, no parity. */
863     s->divider = 0x0C;
864     s->mcr = UART_MCR_OUT2;
865     s->scr = 0;
866     s->tsr_retry = 0;
867     s->char_transmit_time = (NANOSECONDS_PER_SECOND / 9600) * 10;
868     s->poll_msl = 0;
869 
870     s->timeout_ipending = 0;
871     timer_del(s->fifo_timeout_timer);
872     timer_del(s->modem_status_poll);
873 
874     fifo8_reset(&s->recv_fifo);
875     fifo8_reset(&s->xmit_fifo);
876 
877     s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
878 
879     s->thr_ipending = 0;
880     s->last_break_enable = 0;
881     qemu_irq_lower(s->irq);
882 
883     serial_update_msl(s);
884     s->msr &= ~UART_MSR_ANY_DELTA;
885 }
886 
887 void serial_realize_core(SerialState *s, Error **errp)
888 {
889     if (!qemu_chr_fe_get_driver(&s->chr)) {
890         error_setg(errp, "Can't create serial device, empty char device");
891         return;
892     }
893 
894     s->modem_status_poll = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) serial_update_msl, s);
895 
896     s->fifo_timeout_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) fifo_timeout_int, s);
897     qemu_register_reset(serial_reset, s);
898 
899     qemu_chr_fe_set_handlers(&s->chr, serial_can_receive1, serial_receive1,
900                              serial_event, s, NULL, true);
901     fifo8_create(&s->recv_fifo, UART_FIFO_LENGTH);
902     fifo8_create(&s->xmit_fifo, UART_FIFO_LENGTH);
903     serial_reset(s);
904 }
905 
906 void serial_exit_core(SerialState *s)
907 {
908     qemu_chr_fe_deinit(&s->chr);
909 
910     timer_del(s->modem_status_poll);
911     timer_free(s->modem_status_poll);
912 
913     timer_del(s->fifo_timeout_timer);
914     timer_free(s->fifo_timeout_timer);
915 
916     fifo8_destroy(&s->recv_fifo);
917     fifo8_destroy(&s->xmit_fifo);
918 
919     qemu_unregister_reset(serial_reset, s);
920 }
921 
922 /* Change the main reference oscillator frequency. */
923 void serial_set_frequency(SerialState *s, uint32_t frequency)
924 {
925     s->baudbase = frequency;
926     serial_update_parameters(s);
927 }
928 
929 const MemoryRegionOps serial_io_ops = {
930     .read = serial_ioport_read,
931     .write = serial_ioport_write,
932     .impl = {
933         .min_access_size = 1,
934         .max_access_size = 1,
935     },
936     .endianness = DEVICE_LITTLE_ENDIAN,
937 };
938 
939 SerialState *serial_init(int base, qemu_irq irq, int baudbase,
940                          CharDriverState *chr, MemoryRegion *system_io)
941 {
942     SerialState *s;
943 
944     s = g_malloc0(sizeof(SerialState));
945 
946     s->irq = irq;
947     s->baudbase = baudbase;
948     qemu_chr_fe_init(&s->chr, chr, &error_abort);
949     serial_realize_core(s, &error_fatal);
950 
951     vmstate_register(NULL, base, &vmstate_serial, s);
952 
953     memory_region_init_io(&s->io, NULL, &serial_io_ops, s, "serial", 8);
954     memory_region_add_subregion(system_io, base, &s->io);
955 
956     return s;
957 }
958 
959 /* Memory mapped interface */
960 static uint64_t serial_mm_read(void *opaque, hwaddr addr,
961                                unsigned size)
962 {
963     SerialState *s = opaque;
964     return serial_ioport_read(s, addr >> s->it_shift, 1);
965 }
966 
967 static void serial_mm_write(void *opaque, hwaddr addr,
968                             uint64_t value, unsigned size)
969 {
970     SerialState *s = opaque;
971     value &= ~0u >> (32 - (size * 8));
972     serial_ioport_write(s, addr >> s->it_shift, value, 1);
973 }
974 
975 static const MemoryRegionOps serial_mm_ops[3] = {
976     [DEVICE_NATIVE_ENDIAN] = {
977         .read = serial_mm_read,
978         .write = serial_mm_write,
979         .endianness = DEVICE_NATIVE_ENDIAN,
980     },
981     [DEVICE_LITTLE_ENDIAN] = {
982         .read = serial_mm_read,
983         .write = serial_mm_write,
984         .endianness = DEVICE_LITTLE_ENDIAN,
985     },
986     [DEVICE_BIG_ENDIAN] = {
987         .read = serial_mm_read,
988         .write = serial_mm_write,
989         .endianness = DEVICE_BIG_ENDIAN,
990     },
991 };
992 
993 SerialState *serial_mm_init(MemoryRegion *address_space,
994                             hwaddr base, int it_shift,
995                             qemu_irq irq, int baudbase,
996                             CharDriverState *chr, enum device_endian end)
997 {
998     SerialState *s;
999 
1000     s = g_malloc0(sizeof(SerialState));
1001 
1002     s->it_shift = it_shift;
1003     s->irq = irq;
1004     s->baudbase = baudbase;
1005     qemu_chr_fe_init(&s->chr, chr, &error_abort);
1006 
1007     serial_realize_core(s, &error_fatal);
1008     vmstate_register(NULL, base, &vmstate_serial, s);
1009 
1010     memory_region_init_io(&s->io, NULL, &serial_mm_ops[end], s,
1011                           "serial", 8 << it_shift);
1012     memory_region_add_subregion(address_space, base, &s->io);
1013     return s;
1014 }
1015