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