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