xref: /openbmc/qemu/hw/char/serial.c (revision 80adf54e)
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 "chardev/char-serial.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_update_tiocm(SerialState *s)
316 {
317     int flags;
318 
319     qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_GET_TIOCM, &flags);
320 
321     flags &= ~(CHR_TIOCM_RTS | CHR_TIOCM_DTR);
322 
323     if (s->mcr & UART_MCR_RTS) {
324         flags |= CHR_TIOCM_RTS;
325     }
326     if (s->mcr & UART_MCR_DTR) {
327         flags |= CHR_TIOCM_DTR;
328     }
329 
330     qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_SET_TIOCM, &flags);
331 }
332 
333 static void serial_ioport_write(void *opaque, hwaddr addr, uint64_t val,
334                                 unsigned size)
335 {
336     SerialState *s = opaque;
337 
338     addr &= 7;
339     DPRINTF("write addr=0x%" HWADDR_PRIx " val=0x%" PRIx64 "\n", addr, val);
340     switch(addr) {
341     default:
342     case 0:
343         if (s->lcr & UART_LCR_DLAB) {
344             s->divider = (s->divider & 0xff00) | val;
345             serial_update_parameters(s);
346         } else {
347             s->thr = (uint8_t) val;
348             if(s->fcr & UART_FCR_FE) {
349                 /* xmit overruns overwrite data, so make space if needed */
350                 if (fifo8_is_full(&s->xmit_fifo)) {
351                     fifo8_pop(&s->xmit_fifo);
352                 }
353                 fifo8_push(&s->xmit_fifo, s->thr);
354             }
355             s->thr_ipending = 0;
356             s->lsr &= ~UART_LSR_THRE;
357             s->lsr &= ~UART_LSR_TEMT;
358             serial_update_irq(s);
359             if (s->tsr_retry == 0) {
360                 serial_xmit(s);
361             }
362         }
363         break;
364     case 1:
365         if (s->lcr & UART_LCR_DLAB) {
366             s->divider = (s->divider & 0x00ff) | (val << 8);
367             serial_update_parameters(s);
368         } else {
369             uint8_t changed = (s->ier ^ val) & 0x0f;
370             s->ier = val & 0x0f;
371             /* If the backend device is a real serial port, turn polling of the modem
372              * status lines on physical port on or off depending on UART_IER_MSI state.
373              */
374             if ((changed & UART_IER_MSI) && s->poll_msl >= 0) {
375                 if (s->ier & UART_IER_MSI) {
376                      s->poll_msl = 1;
377                      serial_update_msl(s);
378                 } else {
379                      timer_del(s->modem_status_poll);
380                      s->poll_msl = 0;
381                 }
382             }
383 
384             /* Turning on the THRE interrupt on IER can trigger the interrupt
385              * if LSR.THRE=1, even if it had been masked before by reading IIR.
386              * This is not in the datasheet, but Windows relies on it.  It is
387              * unclear if THRE has to be resampled every time THRI becomes
388              * 1, or only on the rising edge.  Bochs does the latter, and Windows
389              * always toggles IER to all zeroes and back to all ones, so do the
390              * same.
391              *
392              * If IER.THRI is zero, thr_ipending is not used.  Set it to zero
393              * so that the thr_ipending subsection is not migrated.
394              */
395             if (changed & UART_IER_THRI) {
396                 if ((s->ier & UART_IER_THRI) && (s->lsr & UART_LSR_THRE)) {
397                     s->thr_ipending = 1;
398                 } else {
399                     s->thr_ipending = 0;
400                 }
401             }
402 
403             if (changed) {
404                 serial_update_irq(s);
405             }
406         }
407         break;
408     case 2:
409         /* Did the enable/disable flag change? If so, make sure FIFOs get flushed */
410         if ((val ^ s->fcr) & UART_FCR_FE) {
411             val |= UART_FCR_XFR | UART_FCR_RFR;
412         }
413 
414         /* FIFO clear */
415 
416         if (val & UART_FCR_RFR) {
417             s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
418             timer_del(s->fifo_timeout_timer);
419             s->timeout_ipending = 0;
420             fifo8_reset(&s->recv_fifo);
421         }
422 
423         if (val & UART_FCR_XFR) {
424             s->lsr |= UART_LSR_THRE;
425             s->thr_ipending = 1;
426             fifo8_reset(&s->xmit_fifo);
427         }
428 
429         serial_write_fcr(s, val & 0xC9);
430         serial_update_irq(s);
431         break;
432     case 3:
433         {
434             int break_enable;
435             s->lcr = val;
436             serial_update_parameters(s);
437             break_enable = (val >> 6) & 1;
438             if (break_enable != s->last_break_enable) {
439                 s->last_break_enable = break_enable;
440                 qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_SET_BREAK,
441                                   &break_enable);
442             }
443         }
444         break;
445     case 4:
446         {
447             int old_mcr = s->mcr;
448             s->mcr = val & 0x1f;
449             if (val & UART_MCR_LOOP)
450                 break;
451 
452             if (s->poll_msl >= 0 && old_mcr != s->mcr) {
453                 serial_update_tiocm(s);
454                 /* Update the modem status after a one-character-send wait-time, since there may be a response
455                    from the device/computer at the other end of the serial line */
456                 timer_mod(s->modem_status_poll, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time);
457             }
458         }
459         break;
460     case 5:
461         break;
462     case 6:
463         break;
464     case 7:
465         s->scr = val;
466         break;
467     }
468 }
469 
470 static uint64_t serial_ioport_read(void *opaque, hwaddr addr, unsigned size)
471 {
472     SerialState *s = opaque;
473     uint32_t ret;
474 
475     addr &= 7;
476     switch(addr) {
477     default:
478     case 0:
479         if (s->lcr & UART_LCR_DLAB) {
480             ret = s->divider & 0xff;
481         } else {
482             if(s->fcr & UART_FCR_FE) {
483                 ret = fifo8_is_empty(&s->recv_fifo) ?
484                             0 : fifo8_pop(&s->recv_fifo);
485                 if (s->recv_fifo.num == 0) {
486                     s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
487                 } else {
488                     timer_mod(s->fifo_timeout_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time * 4);
489                 }
490                 s->timeout_ipending = 0;
491             } else {
492                 ret = s->rbr;
493                 s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
494             }
495             serial_update_irq(s);
496             if (!(s->mcr & UART_MCR_LOOP)) {
497                 /* in loopback mode, don't receive any data */
498                 qemu_chr_fe_accept_input(&s->chr);
499             }
500         }
501         break;
502     case 1:
503         if (s->lcr & UART_LCR_DLAB) {
504             ret = (s->divider >> 8) & 0xff;
505         } else {
506             ret = s->ier;
507         }
508         break;
509     case 2:
510         ret = s->iir;
511         if ((ret & UART_IIR_ID) == UART_IIR_THRI) {
512             s->thr_ipending = 0;
513             serial_update_irq(s);
514         }
515         break;
516     case 3:
517         ret = s->lcr;
518         break;
519     case 4:
520         ret = s->mcr;
521         break;
522     case 5:
523         ret = s->lsr;
524         /* Clear break and overrun interrupts */
525         if (s->lsr & (UART_LSR_BI|UART_LSR_OE)) {
526             s->lsr &= ~(UART_LSR_BI|UART_LSR_OE);
527             serial_update_irq(s);
528         }
529         break;
530     case 6:
531         if (s->mcr & UART_MCR_LOOP) {
532             /* in loopback, the modem output pins are connected to the
533                inputs */
534             ret = (s->mcr & 0x0c) << 4;
535             ret |= (s->mcr & 0x02) << 3;
536             ret |= (s->mcr & 0x01) << 5;
537         } else {
538             if (s->poll_msl >= 0)
539                 serial_update_msl(s);
540             ret = s->msr;
541             /* Clear delta bits & msr int after read, if they were set */
542             if (s->msr & UART_MSR_ANY_DELTA) {
543                 s->msr &= 0xF0;
544                 serial_update_irq(s);
545             }
546         }
547         break;
548     case 7:
549         ret = s->scr;
550         break;
551     }
552     DPRINTF("read addr=0x%" HWADDR_PRIx " val=0x%02x\n", addr, ret);
553     return ret;
554 }
555 
556 static int serial_can_receive(SerialState *s)
557 {
558     if(s->fcr & UART_FCR_FE) {
559         if (s->recv_fifo.num < UART_FIFO_LENGTH) {
560             /*
561              * Advertise (fifo.itl - fifo.count) bytes when count < ITL, and 1
562              * if above. If UART_FIFO_LENGTH - fifo.count is advertised the
563              * effect will be to almost always fill the fifo completely before
564              * the guest has a chance to respond, effectively overriding the ITL
565              * that the guest has set.
566              */
567             return (s->recv_fifo.num <= s->recv_fifo_itl) ?
568                         s->recv_fifo_itl - s->recv_fifo.num : 1;
569         } else {
570             return 0;
571         }
572     } else {
573         return !(s->lsr & UART_LSR_DR);
574     }
575 }
576 
577 static void serial_receive_break(SerialState *s)
578 {
579     s->rbr = 0;
580     /* When the LSR_DR is set a null byte is pushed into the fifo */
581     recv_fifo_put(s, '\0');
582     s->lsr |= UART_LSR_BI | UART_LSR_DR;
583     serial_update_irq(s);
584 }
585 
586 /* There's data in recv_fifo and s->rbr has not been read for 4 char transmit times */
587 static void fifo_timeout_int (void *opaque) {
588     SerialState *s = opaque;
589     if (s->recv_fifo.num) {
590         s->timeout_ipending = 1;
591         serial_update_irq(s);
592     }
593 }
594 
595 static int serial_can_receive1(void *opaque)
596 {
597     SerialState *s = opaque;
598     return serial_can_receive(s);
599 }
600 
601 static void serial_receive1(void *opaque, const uint8_t *buf, int size)
602 {
603     SerialState *s = opaque;
604 
605     if (s->wakeup) {
606         qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
607     }
608     if(s->fcr & UART_FCR_FE) {
609         int i;
610         for (i = 0; i < size; i++) {
611             recv_fifo_put(s, buf[i]);
612         }
613         s->lsr |= UART_LSR_DR;
614         /* call the timeout receive callback in 4 char transmit time */
615         timer_mod(s->fifo_timeout_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time * 4);
616     } else {
617         if (s->lsr & UART_LSR_DR)
618             s->lsr |= UART_LSR_OE;
619         s->rbr = buf[0];
620         s->lsr |= UART_LSR_DR;
621     }
622     serial_update_irq(s);
623 }
624 
625 static void serial_event(void *opaque, int event)
626 {
627     SerialState *s = opaque;
628     DPRINTF("event %x\n", event);
629     if (event == CHR_EVENT_BREAK)
630         serial_receive_break(s);
631 }
632 
633 static void serial_pre_save(void *opaque)
634 {
635     SerialState *s = opaque;
636     s->fcr_vmstate = s->fcr;
637 }
638 
639 static int serial_pre_load(void *opaque)
640 {
641     SerialState *s = opaque;
642     s->thr_ipending = -1;
643     s->poll_msl = -1;
644     return 0;
645 }
646 
647 static int serial_post_load(void *opaque, int version_id)
648 {
649     SerialState *s = opaque;
650 
651     if (version_id < 3) {
652         s->fcr_vmstate = 0;
653     }
654     if (s->thr_ipending == -1) {
655         s->thr_ipending = ((s->iir & UART_IIR_ID) == UART_IIR_THRI);
656     }
657 
658     if (s->tsr_retry > 0) {
659         /* tsr_retry > 0 implies LSR.TEMT = 0 (transmitter not empty).  */
660         if (s->lsr & UART_LSR_TEMT) {
661             error_report("inconsistent state in serial device "
662                          "(tsr empty, tsr_retry=%d", s->tsr_retry);
663             return -1;
664         }
665 
666         if (s->tsr_retry > MAX_XMIT_RETRY) {
667             s->tsr_retry = MAX_XMIT_RETRY;
668         }
669 
670         assert(s->watch_tag == 0);
671         s->watch_tag = qemu_chr_fe_add_watch(&s->chr, G_IO_OUT | G_IO_HUP,
672                                              serial_watch_cb, s);
673     } else {
674         /* tsr_retry == 0 implies LSR.TEMT = 1 (transmitter empty).  */
675         if (!(s->lsr & UART_LSR_TEMT)) {
676             error_report("inconsistent state in serial device "
677                          "(tsr not empty, tsr_retry=0");
678             return -1;
679         }
680     }
681 
682     s->last_break_enable = (s->lcr >> 6) & 1;
683     /* Initialize fcr via setter to perform essential side-effects */
684     serial_write_fcr(s, s->fcr_vmstate);
685     serial_update_parameters(s);
686     return 0;
687 }
688 
689 static bool serial_thr_ipending_needed(void *opaque)
690 {
691     SerialState *s = opaque;
692 
693     if (s->ier & UART_IER_THRI) {
694         bool expected_value = ((s->iir & UART_IIR_ID) == UART_IIR_THRI);
695         return s->thr_ipending != expected_value;
696     } else {
697         /* LSR.THRE will be sampled again when the interrupt is
698          * enabled.  thr_ipending is not used in this case, do
699          * not migrate it.
700          */
701         return false;
702     }
703 }
704 
705 static const VMStateDescription vmstate_serial_thr_ipending = {
706     .name = "serial/thr_ipending",
707     .version_id = 1,
708     .minimum_version_id = 1,
709     .needed = serial_thr_ipending_needed,
710     .fields = (VMStateField[]) {
711         VMSTATE_INT32(thr_ipending, SerialState),
712         VMSTATE_END_OF_LIST()
713     }
714 };
715 
716 static bool serial_tsr_needed(void *opaque)
717 {
718     SerialState *s = (SerialState *)opaque;
719     return s->tsr_retry != 0;
720 }
721 
722 static const VMStateDescription vmstate_serial_tsr = {
723     .name = "serial/tsr",
724     .version_id = 1,
725     .minimum_version_id = 1,
726     .needed = serial_tsr_needed,
727     .fields = (VMStateField[]) {
728         VMSTATE_UINT32(tsr_retry, SerialState),
729         VMSTATE_UINT8(thr, SerialState),
730         VMSTATE_UINT8(tsr, SerialState),
731         VMSTATE_END_OF_LIST()
732     }
733 };
734 
735 static bool serial_recv_fifo_needed(void *opaque)
736 {
737     SerialState *s = (SerialState *)opaque;
738     return !fifo8_is_empty(&s->recv_fifo);
739 
740 }
741 
742 static const VMStateDescription vmstate_serial_recv_fifo = {
743     .name = "serial/recv_fifo",
744     .version_id = 1,
745     .minimum_version_id = 1,
746     .needed = serial_recv_fifo_needed,
747     .fields = (VMStateField[]) {
748         VMSTATE_STRUCT(recv_fifo, SerialState, 1, vmstate_fifo8, Fifo8),
749         VMSTATE_END_OF_LIST()
750     }
751 };
752 
753 static bool serial_xmit_fifo_needed(void *opaque)
754 {
755     SerialState *s = (SerialState *)opaque;
756     return !fifo8_is_empty(&s->xmit_fifo);
757 }
758 
759 static const VMStateDescription vmstate_serial_xmit_fifo = {
760     .name = "serial/xmit_fifo",
761     .version_id = 1,
762     .minimum_version_id = 1,
763     .needed = serial_xmit_fifo_needed,
764     .fields = (VMStateField[]) {
765         VMSTATE_STRUCT(xmit_fifo, SerialState, 1, vmstate_fifo8, Fifo8),
766         VMSTATE_END_OF_LIST()
767     }
768 };
769 
770 static bool serial_fifo_timeout_timer_needed(void *opaque)
771 {
772     SerialState *s = (SerialState *)opaque;
773     return timer_pending(s->fifo_timeout_timer);
774 }
775 
776 static const VMStateDescription vmstate_serial_fifo_timeout_timer = {
777     .name = "serial/fifo_timeout_timer",
778     .version_id = 1,
779     .minimum_version_id = 1,
780     .needed = serial_fifo_timeout_timer_needed,
781     .fields = (VMStateField[]) {
782         VMSTATE_TIMER_PTR(fifo_timeout_timer, SerialState),
783         VMSTATE_END_OF_LIST()
784     }
785 };
786 
787 static bool serial_timeout_ipending_needed(void *opaque)
788 {
789     SerialState *s = (SerialState *)opaque;
790     return s->timeout_ipending != 0;
791 }
792 
793 static const VMStateDescription vmstate_serial_timeout_ipending = {
794     .name = "serial/timeout_ipending",
795     .version_id = 1,
796     .minimum_version_id = 1,
797     .needed = serial_timeout_ipending_needed,
798     .fields = (VMStateField[]) {
799         VMSTATE_INT32(timeout_ipending, SerialState),
800         VMSTATE_END_OF_LIST()
801     }
802 };
803 
804 static bool serial_poll_needed(void *opaque)
805 {
806     SerialState *s = (SerialState *)opaque;
807     return s->poll_msl >= 0;
808 }
809 
810 static const VMStateDescription vmstate_serial_poll = {
811     .name = "serial/poll",
812     .version_id = 1,
813     .needed = serial_poll_needed,
814     .minimum_version_id = 1,
815     .fields = (VMStateField[]) {
816         VMSTATE_INT32(poll_msl, SerialState),
817         VMSTATE_TIMER_PTR(modem_status_poll, SerialState),
818         VMSTATE_END_OF_LIST()
819     }
820 };
821 
822 const VMStateDescription vmstate_serial = {
823     .name = "serial",
824     .version_id = 3,
825     .minimum_version_id = 2,
826     .pre_save = serial_pre_save,
827     .pre_load = serial_pre_load,
828     .post_load = serial_post_load,
829     .fields = (VMStateField[]) {
830         VMSTATE_UINT16_V(divider, SerialState, 2),
831         VMSTATE_UINT8(rbr, SerialState),
832         VMSTATE_UINT8(ier, SerialState),
833         VMSTATE_UINT8(iir, SerialState),
834         VMSTATE_UINT8(lcr, SerialState),
835         VMSTATE_UINT8(mcr, SerialState),
836         VMSTATE_UINT8(lsr, SerialState),
837         VMSTATE_UINT8(msr, SerialState),
838         VMSTATE_UINT8(scr, SerialState),
839         VMSTATE_UINT8_V(fcr_vmstate, SerialState, 3),
840         VMSTATE_END_OF_LIST()
841     },
842     .subsections = (const VMStateDescription*[]) {
843         &vmstate_serial_thr_ipending,
844         &vmstate_serial_tsr,
845         &vmstate_serial_recv_fifo,
846         &vmstate_serial_xmit_fifo,
847         &vmstate_serial_fifo_timeout_timer,
848         &vmstate_serial_timeout_ipending,
849         &vmstate_serial_poll,
850         NULL
851     }
852 };
853 
854 static void serial_reset(void *opaque)
855 {
856     SerialState *s = opaque;
857 
858     if (s->watch_tag > 0) {
859         g_source_remove(s->watch_tag);
860         s->watch_tag = 0;
861     }
862 
863     s->rbr = 0;
864     s->ier = 0;
865     s->iir = UART_IIR_NO_INT;
866     s->lcr = 0;
867     s->lsr = UART_LSR_TEMT | UART_LSR_THRE;
868     s->msr = UART_MSR_DCD | UART_MSR_DSR | UART_MSR_CTS;
869     /* Default to 9600 baud, 1 start bit, 8 data bits, 1 stop bit, no parity. */
870     s->divider = 0x0C;
871     s->mcr = UART_MCR_OUT2;
872     s->scr = 0;
873     s->tsr_retry = 0;
874     s->char_transmit_time = (NANOSECONDS_PER_SECOND / 9600) * 10;
875     s->poll_msl = 0;
876 
877     s->timeout_ipending = 0;
878     timer_del(s->fifo_timeout_timer);
879     timer_del(s->modem_status_poll);
880 
881     fifo8_reset(&s->recv_fifo);
882     fifo8_reset(&s->xmit_fifo);
883 
884     s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
885 
886     s->thr_ipending = 0;
887     s->last_break_enable = 0;
888     qemu_irq_lower(s->irq);
889 
890     serial_update_msl(s);
891     s->msr &= ~UART_MSR_ANY_DELTA;
892 }
893 
894 static int serial_be_change(void *opaque)
895 {
896     SerialState *s = opaque;
897 
898     qemu_chr_fe_set_handlers(&s->chr, serial_can_receive1, serial_receive1,
899                              serial_event, serial_be_change, s, NULL, true);
900 
901     serial_update_parameters(s);
902 
903     qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_SET_BREAK,
904                       &s->last_break_enable);
905 
906     s->poll_msl = (s->ier & UART_IER_MSI) ? 1 : 0;
907     serial_update_msl(s);
908 
909     if (s->poll_msl >= 0 && !(s->mcr & UART_MCR_LOOP)) {
910         serial_update_tiocm(s);
911     }
912 
913     if (s->watch_tag > 0) {
914         g_source_remove(s->watch_tag);
915         s->watch_tag = qemu_chr_fe_add_watch(&s->chr, G_IO_OUT | G_IO_HUP,
916                                              serial_watch_cb, s);
917     }
918 
919     return 0;
920 }
921 
922 void serial_realize_core(SerialState *s, Error **errp)
923 {
924     if (!qemu_chr_fe_backend_connected(&s->chr)) {
925         error_setg(errp, "Can't create serial device, empty char device");
926         return;
927     }
928 
929     s->modem_status_poll = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) serial_update_msl, s);
930 
931     s->fifo_timeout_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) fifo_timeout_int, s);
932     qemu_register_reset(serial_reset, s);
933 
934     qemu_chr_fe_set_handlers(&s->chr, serial_can_receive1, serial_receive1,
935                              serial_event, serial_be_change, s, NULL, true);
936     fifo8_create(&s->recv_fifo, UART_FIFO_LENGTH);
937     fifo8_create(&s->xmit_fifo, UART_FIFO_LENGTH);
938     serial_reset(s);
939 }
940 
941 void serial_exit_core(SerialState *s)
942 {
943     qemu_chr_fe_deinit(&s->chr, false);
944 
945     timer_del(s->modem_status_poll);
946     timer_free(s->modem_status_poll);
947 
948     timer_del(s->fifo_timeout_timer);
949     timer_free(s->fifo_timeout_timer);
950 
951     fifo8_destroy(&s->recv_fifo);
952     fifo8_destroy(&s->xmit_fifo);
953 
954     qemu_unregister_reset(serial_reset, s);
955 }
956 
957 /* Change the main reference oscillator frequency. */
958 void serial_set_frequency(SerialState *s, uint32_t frequency)
959 {
960     s->baudbase = frequency;
961     serial_update_parameters(s);
962 }
963 
964 const MemoryRegionOps serial_io_ops = {
965     .read = serial_ioport_read,
966     .write = serial_ioport_write,
967     .impl = {
968         .min_access_size = 1,
969         .max_access_size = 1,
970     },
971     .endianness = DEVICE_LITTLE_ENDIAN,
972 };
973 
974 SerialState *serial_init(int base, qemu_irq irq, int baudbase,
975                          Chardev *chr, MemoryRegion *system_io)
976 {
977     SerialState *s;
978 
979     s = g_malloc0(sizeof(SerialState));
980 
981     s->irq = irq;
982     s->baudbase = baudbase;
983     qemu_chr_fe_init(&s->chr, chr, &error_abort);
984     serial_realize_core(s, &error_fatal);
985 
986     vmstate_register(NULL, base, &vmstate_serial, s);
987 
988     memory_region_init_io(&s->io, NULL, &serial_io_ops, s, "serial", 8);
989     memory_region_add_subregion(system_io, base, &s->io);
990 
991     return s;
992 }
993 
994 /* Memory mapped interface */
995 static uint64_t serial_mm_read(void *opaque, hwaddr addr,
996                                unsigned size)
997 {
998     SerialState *s = opaque;
999     return serial_ioport_read(s, addr >> s->it_shift, 1);
1000 }
1001 
1002 static void serial_mm_write(void *opaque, hwaddr addr,
1003                             uint64_t value, unsigned size)
1004 {
1005     SerialState *s = opaque;
1006     value &= ~0u >> (32 - (size * 8));
1007     serial_ioport_write(s, addr >> s->it_shift, value, 1);
1008 }
1009 
1010 static const MemoryRegionOps serial_mm_ops[3] = {
1011     [DEVICE_NATIVE_ENDIAN] = {
1012         .read = serial_mm_read,
1013         .write = serial_mm_write,
1014         .endianness = DEVICE_NATIVE_ENDIAN,
1015     },
1016     [DEVICE_LITTLE_ENDIAN] = {
1017         .read = serial_mm_read,
1018         .write = serial_mm_write,
1019         .endianness = DEVICE_LITTLE_ENDIAN,
1020     },
1021     [DEVICE_BIG_ENDIAN] = {
1022         .read = serial_mm_read,
1023         .write = serial_mm_write,
1024         .endianness = DEVICE_BIG_ENDIAN,
1025     },
1026 };
1027 
1028 SerialState *serial_mm_init(MemoryRegion *address_space,
1029                             hwaddr base, int it_shift,
1030                             qemu_irq irq, int baudbase,
1031                             Chardev *chr, enum device_endian end)
1032 {
1033     SerialState *s;
1034 
1035     s = g_malloc0(sizeof(SerialState));
1036 
1037     s->it_shift = it_shift;
1038     s->irq = irq;
1039     s->baudbase = baudbase;
1040     qemu_chr_fe_init(&s->chr, chr, &error_abort);
1041 
1042     serial_realize_core(s, &error_fatal);
1043     vmstate_register(NULL, base, &vmstate_serial, s);
1044 
1045     memory_region_init_io(&s->io, NULL, &serial_mm_ops[end], s,
1046                           "serial", 8 << it_shift);
1047     memory_region_add_subregion(address_space, base, &s->io);
1048     return s;
1049 }
1050