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