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