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