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