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