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