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