xref: /openbmc/qemu/hw/char/serial.c (revision 88c1ee73)
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 "hw/char/serial.h"
27 #include "sysemu/char.h"
28 #include "qemu/timer.h"
29 #include "exec/address-spaces.h"
30 #include "qemu/error-report.h"
31 
32 //#define DEBUG_SERIAL
33 
34 #define UART_LCR_DLAB	0x80	/* Divisor latch access bit */
35 
36 #define UART_IER_MSI	0x08	/* Enable Modem status interrupt */
37 #define UART_IER_RLSI	0x04	/* Enable receiver line status interrupt */
38 #define UART_IER_THRI	0x02	/* Enable Transmitter holding register int. */
39 #define UART_IER_RDI	0x01	/* Enable receiver data interrupt */
40 
41 #define UART_IIR_NO_INT	0x01	/* No interrupts pending */
42 #define UART_IIR_ID	0x06	/* Mask for the interrupt ID */
43 
44 #define UART_IIR_MSI	0x00	/* Modem status interrupt */
45 #define UART_IIR_THRI	0x02	/* Transmitter holding register empty */
46 #define UART_IIR_RDI	0x04	/* Receiver data interrupt */
47 #define UART_IIR_RLSI	0x06	/* Receiver line status interrupt */
48 #define UART_IIR_CTI    0x0C    /* Character Timeout Indication */
49 
50 #define UART_IIR_FENF   0x80    /* Fifo enabled, but not functionning */
51 #define UART_IIR_FE     0xC0    /* Fifo enabled */
52 
53 /*
54  * These are the definitions for the Modem Control Register
55  */
56 #define UART_MCR_LOOP	0x10	/* Enable loopback test mode */
57 #define UART_MCR_OUT2	0x08	/* Out2 complement */
58 #define UART_MCR_OUT1	0x04	/* Out1 complement */
59 #define UART_MCR_RTS	0x02	/* RTS complement */
60 #define UART_MCR_DTR	0x01	/* DTR complement */
61 
62 /*
63  * These are the definitions for the Modem Status Register
64  */
65 #define UART_MSR_DCD	0x80	/* Data Carrier Detect */
66 #define UART_MSR_RI	0x40	/* Ring Indicator */
67 #define UART_MSR_DSR	0x20	/* Data Set Ready */
68 #define UART_MSR_CTS	0x10	/* Clear to Send */
69 #define UART_MSR_DDCD	0x08	/* Delta DCD */
70 #define UART_MSR_TERI	0x04	/* Trailing edge ring indicator */
71 #define UART_MSR_DDSR	0x02	/* Delta DSR */
72 #define UART_MSR_DCTS	0x01	/* Delta CTS */
73 #define UART_MSR_ANY_DELTA 0x0F	/* Any of the delta bits! */
74 
75 #define UART_LSR_TEMT	0x40	/* Transmitter empty */
76 #define UART_LSR_THRE	0x20	/* Transmit-hold-register empty */
77 #define UART_LSR_BI	0x10	/* Break interrupt indicator */
78 #define UART_LSR_FE	0x08	/* Frame error indicator */
79 #define UART_LSR_PE	0x04	/* Parity error indicator */
80 #define UART_LSR_OE	0x02	/* Overrun error indicator */
81 #define UART_LSR_DR	0x01	/* Receiver data ready */
82 #define UART_LSR_INT_ANY 0x1E	/* Any of the lsr-interrupt-triggering status bits */
83 
84 /* Interrupt trigger levels. The byte-counts are for 16550A - in newer UARTs the byte-count for each ITL is higher. */
85 
86 #define UART_FCR_ITL_1      0x00 /* 1 byte ITL */
87 #define UART_FCR_ITL_2      0x40 /* 4 bytes ITL */
88 #define UART_FCR_ITL_3      0x80 /* 8 bytes ITL */
89 #define UART_FCR_ITL_4      0xC0 /* 14 bytes ITL */
90 
91 #define UART_FCR_DMS        0x08    /* DMA Mode Select */
92 #define UART_FCR_XFR        0x04    /* XMIT Fifo Reset */
93 #define UART_FCR_RFR        0x02    /* RCVR Fifo Reset */
94 #define UART_FCR_FE         0x01    /* FIFO Enable */
95 
96 #define MAX_XMIT_RETRY      4
97 
98 #ifdef DEBUG_SERIAL
99 #define DPRINTF(fmt, ...) \
100 do { fprintf(stderr, "serial: " fmt , ## __VA_ARGS__); } while (0)
101 #else
102 #define DPRINTF(fmt, ...) \
103 do {} while (0)
104 #endif
105 
106 static void serial_receive1(void *opaque, const uint8_t *buf, int size);
107 
108 static inline void recv_fifo_put(SerialState *s, uint8_t chr)
109 {
110     /* Receive overruns do not overwrite FIFO contents. */
111     if (!fifo8_is_full(&s->recv_fifo)) {
112         fifo8_push(&s->recv_fifo, chr);
113     } else {
114         s->lsr |= UART_LSR_OE;
115     }
116 }
117 
118 static void serial_update_irq(SerialState *s)
119 {
120     uint8_t tmp_iir = UART_IIR_NO_INT;
121 
122     if ((s->ier & UART_IER_RLSI) && (s->lsr & UART_LSR_INT_ANY)) {
123         tmp_iir = UART_IIR_RLSI;
124     } else if ((s->ier & UART_IER_RDI) && s->timeout_ipending) {
125         /* Note that(s->ier & UART_IER_RDI) can mask this interrupt,
126          * this is not in the specification but is observed on existing
127          * hardware.  */
128         tmp_iir = UART_IIR_CTI;
129     } else if ((s->ier & UART_IER_RDI) && (s->lsr & UART_LSR_DR) &&
130                (!(s->fcr & UART_FCR_FE) ||
131                 s->recv_fifo.num >= s->recv_fifo_itl)) {
132         tmp_iir = UART_IIR_RDI;
133     } else if ((s->ier & UART_IER_THRI) && s->thr_ipending) {
134         tmp_iir = UART_IIR_THRI;
135     } else if ((s->ier & UART_IER_MSI) && (s->msr & UART_MSR_ANY_DELTA)) {
136         tmp_iir = UART_IIR_MSI;
137     }
138 
139     s->iir = tmp_iir | (s->iir & 0xF0);
140 
141     if (tmp_iir != UART_IIR_NO_INT) {
142         qemu_irq_raise(s->irq);
143     } else {
144         qemu_irq_lower(s->irq);
145     }
146 }
147 
148 static void serial_update_parameters(SerialState *s)
149 {
150     int speed, parity, data_bits, stop_bits, frame_size;
151     QEMUSerialSetParams ssp;
152 
153     if (s->divider == 0)
154         return;
155 
156     /* Start bit. */
157     frame_size = 1;
158     if (s->lcr & 0x08) {
159         /* Parity bit. */
160         frame_size++;
161         if (s->lcr & 0x10)
162             parity = 'E';
163         else
164             parity = 'O';
165     } else {
166             parity = 'N';
167     }
168     if (s->lcr & 0x04)
169         stop_bits = 2;
170     else
171         stop_bits = 1;
172 
173     data_bits = (s->lcr & 0x03) + 5;
174     frame_size += data_bits + stop_bits;
175     speed = s->baudbase / s->divider;
176     ssp.speed = speed;
177     ssp.parity = parity;
178     ssp.data_bits = data_bits;
179     ssp.stop_bits = stop_bits;
180     s->char_transmit_time =  (get_ticks_per_sec() / speed) * frame_size;
181     qemu_chr_fe_ioctl(s->chr, CHR_IOCTL_SERIAL_SET_PARAMS, &ssp);
182 
183     DPRINTF("speed=%d parity=%c data=%d stop=%d\n",
184            speed, parity, data_bits, stop_bits);
185 }
186 
187 static void serial_update_msl(SerialState *s)
188 {
189     uint8_t omsr;
190     int flags;
191 
192     timer_del(s->modem_status_poll);
193 
194     if (qemu_chr_fe_ioctl(s->chr,CHR_IOCTL_SERIAL_GET_TIOCM, &flags) == -ENOTSUP) {
195         s->poll_msl = -1;
196         return;
197     }
198 
199     omsr = s->msr;
200 
201     s->msr = (flags & CHR_TIOCM_CTS) ? s->msr | UART_MSR_CTS : s->msr & ~UART_MSR_CTS;
202     s->msr = (flags & CHR_TIOCM_DSR) ? s->msr | UART_MSR_DSR : s->msr & ~UART_MSR_DSR;
203     s->msr = (flags & CHR_TIOCM_CAR) ? s->msr | UART_MSR_DCD : s->msr & ~UART_MSR_DCD;
204     s->msr = (flags & CHR_TIOCM_RI) ? s->msr | UART_MSR_RI : s->msr & ~UART_MSR_RI;
205 
206     if (s->msr != omsr) {
207          /* Set delta bits */
208          s->msr = s->msr | ((s->msr >> 4) ^ (omsr >> 4));
209          /* UART_MSR_TERI only if change was from 1 -> 0 */
210          if ((s->msr & UART_MSR_TERI) && !(omsr & UART_MSR_RI))
211              s->msr &= ~UART_MSR_TERI;
212          serial_update_irq(s);
213     }
214 
215     /* The real 16550A apparently has a 250ns response latency to line status changes.
216        We'll be lazy and poll only every 10ms, and only poll it at all if MSI interrupts are turned on */
217 
218     if (s->poll_msl)
219         timer_mod(s->modem_status_poll, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + get_ticks_per_sec() / 100);
220 }
221 
222 static gboolean serial_xmit(GIOChannel *chan, GIOCondition cond, void *opaque)
223 {
224     SerialState *s = opaque;
225 
226     if (s->tsr_retry <= 0) {
227         if (s->fcr & UART_FCR_FE) {
228             s->tsr = fifo8_is_empty(&s->xmit_fifo) ?
229                         0 : fifo8_pop(&s->xmit_fifo);
230             if (!s->xmit_fifo.num) {
231                 s->lsr |= UART_LSR_THRE;
232             }
233         } else if ((s->lsr & UART_LSR_THRE)) {
234             return FALSE;
235         } else {
236             s->tsr = s->thr;
237             s->lsr |= UART_LSR_THRE;
238             s->lsr &= ~UART_LSR_TEMT;
239         }
240     }
241 
242     if (s->mcr & UART_MCR_LOOP) {
243         /* in loopback mode, say that we just received a char */
244         serial_receive1(s, &s->tsr, 1);
245     } else if (qemu_chr_fe_write(s->chr, &s->tsr, 1) != 1) {
246         if (s->tsr_retry >= 0 && s->tsr_retry < MAX_XMIT_RETRY &&
247             qemu_chr_fe_add_watch(s->chr, G_IO_OUT, serial_xmit, s) > 0) {
248             s->tsr_retry++;
249             return FALSE;
250         }
251         s->tsr_retry = 0;
252     } else {
253         s->tsr_retry = 0;
254     }
255 
256     s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
257 
258     if (s->lsr & UART_LSR_THRE) {
259         s->lsr |= UART_LSR_TEMT;
260         s->thr_ipending = 1;
261         serial_update_irq(s);
262     }
263 
264     return FALSE;
265 }
266 
267 
268 static void serial_ioport_write(void *opaque, hwaddr addr, uint64_t val,
269                                 unsigned size)
270 {
271     SerialState *s = opaque;
272 
273     addr &= 7;
274     DPRINTF("write addr=0x%" HWADDR_PRIx " val=0x%" PRIx64 "\n", addr, val);
275     switch(addr) {
276     default:
277     case 0:
278         if (s->lcr & UART_LCR_DLAB) {
279             s->divider = (s->divider & 0xff00) | val;
280             serial_update_parameters(s);
281         } else {
282             s->thr = (uint8_t) val;
283             if(s->fcr & UART_FCR_FE) {
284                 /* xmit overruns overwrite data, so make space if needed */
285                 if (fifo8_is_full(&s->xmit_fifo)) {
286                     fifo8_pop(&s->xmit_fifo);
287                 }
288                 fifo8_push(&s->xmit_fifo, s->thr);
289                 s->lsr &= ~UART_LSR_TEMT;
290             }
291             s->thr_ipending = 0;
292             s->lsr &= ~UART_LSR_THRE;
293             serial_update_irq(s);
294             serial_xmit(NULL, G_IO_OUT, s);
295         }
296         break;
297     case 1:
298         if (s->lcr & UART_LCR_DLAB) {
299             s->divider = (s->divider & 0x00ff) | (val << 8);
300             serial_update_parameters(s);
301         } else {
302             s->ier = val & 0x0f;
303             /* If the backend device is a real serial port, turn polling of the modem
304                status lines on physical port on or off depending on UART_IER_MSI state */
305             if (s->poll_msl >= 0) {
306                 if (s->ier & UART_IER_MSI) {
307                      s->poll_msl = 1;
308                      serial_update_msl(s);
309                 } else {
310                      timer_del(s->modem_status_poll);
311                      s->poll_msl = 0;
312                 }
313             }
314             if (s->lsr & UART_LSR_THRE) {
315                 s->thr_ipending = 1;
316                 serial_update_irq(s);
317             }
318         }
319         break;
320     case 2:
321         val = val & 0xFF;
322 
323         if (s->fcr == val)
324             break;
325 
326         /* Did the enable/disable flag change? If so, make sure FIFOs get flushed */
327         if ((val ^ s->fcr) & UART_FCR_FE)
328             val |= UART_FCR_XFR | UART_FCR_RFR;
329 
330         /* FIFO clear */
331 
332         if (val & UART_FCR_RFR) {
333             timer_del(s->fifo_timeout_timer);
334             s->timeout_ipending=0;
335             fifo8_reset(&s->recv_fifo);
336         }
337 
338         if (val & UART_FCR_XFR) {
339             fifo8_reset(&s->xmit_fifo);
340         }
341 
342         if (val & UART_FCR_FE) {
343             s->iir |= UART_IIR_FE;
344             /* Set recv_fifo trigger Level */
345             switch (val & 0xC0) {
346             case UART_FCR_ITL_1:
347                 s->recv_fifo_itl = 1;
348                 break;
349             case UART_FCR_ITL_2:
350                 s->recv_fifo_itl = 4;
351                 break;
352             case UART_FCR_ITL_3:
353                 s->recv_fifo_itl = 8;
354                 break;
355             case UART_FCR_ITL_4:
356                 s->recv_fifo_itl = 14;
357                 break;
358             }
359         } else
360             s->iir &= ~UART_IIR_FE;
361 
362         /* Set fcr - or at least the bits in it that are supposed to "stick" */
363         s->fcr = val & 0xC9;
364         serial_update_irq(s);
365         break;
366     case 3:
367         {
368             int break_enable;
369             s->lcr = val;
370             serial_update_parameters(s);
371             break_enable = (val >> 6) & 1;
372             if (break_enable != s->last_break_enable) {
373                 s->last_break_enable = break_enable;
374                 qemu_chr_fe_ioctl(s->chr, CHR_IOCTL_SERIAL_SET_BREAK,
375                                &break_enable);
376             }
377         }
378         break;
379     case 4:
380         {
381             int flags;
382             int old_mcr = s->mcr;
383             s->mcr = val & 0x1f;
384             if (val & UART_MCR_LOOP)
385                 break;
386 
387             if (s->poll_msl >= 0 && old_mcr != s->mcr) {
388 
389                 qemu_chr_fe_ioctl(s->chr,CHR_IOCTL_SERIAL_GET_TIOCM, &flags);
390 
391                 flags &= ~(CHR_TIOCM_RTS | CHR_TIOCM_DTR);
392 
393                 if (val & UART_MCR_RTS)
394                     flags |= CHR_TIOCM_RTS;
395                 if (val & UART_MCR_DTR)
396                     flags |= CHR_TIOCM_DTR;
397 
398                 qemu_chr_fe_ioctl(s->chr,CHR_IOCTL_SERIAL_SET_TIOCM, &flags);
399                 /* Update the modem status after a one-character-send wait-time, since there may be a response
400                    from the device/computer at the other end of the serial line */
401                 timer_mod(s->modem_status_poll, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time);
402             }
403         }
404         break;
405     case 5:
406         break;
407     case 6:
408         break;
409     case 7:
410         s->scr = val;
411         break;
412     }
413 }
414 
415 static uint64_t serial_ioport_read(void *opaque, hwaddr addr, unsigned size)
416 {
417     SerialState *s = opaque;
418     uint32_t ret;
419 
420     addr &= 7;
421     switch(addr) {
422     default:
423     case 0:
424         if (s->lcr & UART_LCR_DLAB) {
425             ret = s->divider & 0xff;
426         } else {
427             if(s->fcr & UART_FCR_FE) {
428                 ret = fifo8_is_empty(&s->recv_fifo) ?
429                             0 : fifo8_pop(&s->recv_fifo);
430                 if (s->recv_fifo.num == 0) {
431                     s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
432                 } else {
433                     timer_mod(s->fifo_timeout_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time * 4);
434                 }
435                 s->timeout_ipending = 0;
436             } else {
437                 ret = s->rbr;
438                 s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
439             }
440             serial_update_irq(s);
441             if (!(s->mcr & UART_MCR_LOOP)) {
442                 /* in loopback mode, don't receive any data */
443                 qemu_chr_accept_input(s->chr);
444             }
445         }
446         break;
447     case 1:
448         if (s->lcr & UART_LCR_DLAB) {
449             ret = (s->divider >> 8) & 0xff;
450         } else {
451             ret = s->ier;
452         }
453         break;
454     case 2:
455         ret = s->iir;
456         if ((ret & UART_IIR_ID) == UART_IIR_THRI) {
457             s->thr_ipending = 0;
458             serial_update_irq(s);
459         }
460         break;
461     case 3:
462         ret = s->lcr;
463         break;
464     case 4:
465         ret = s->mcr;
466         break;
467     case 5:
468         ret = s->lsr;
469         /* Clear break and overrun interrupts */
470         if (s->lsr & (UART_LSR_BI|UART_LSR_OE)) {
471             s->lsr &= ~(UART_LSR_BI|UART_LSR_OE);
472             serial_update_irq(s);
473         }
474         break;
475     case 6:
476         if (s->mcr & UART_MCR_LOOP) {
477             /* in loopback, the modem output pins are connected to the
478                inputs */
479             ret = (s->mcr & 0x0c) << 4;
480             ret |= (s->mcr & 0x02) << 3;
481             ret |= (s->mcr & 0x01) << 5;
482         } else {
483             if (s->poll_msl >= 0)
484                 serial_update_msl(s);
485             ret = s->msr;
486             /* Clear delta bits & msr int after read, if they were set */
487             if (s->msr & UART_MSR_ANY_DELTA) {
488                 s->msr &= 0xF0;
489                 serial_update_irq(s);
490             }
491         }
492         break;
493     case 7:
494         ret = s->scr;
495         break;
496     }
497     DPRINTF("read addr=0x%" HWADDR_PRIx " val=0x%02x\n", addr, ret);
498     return ret;
499 }
500 
501 static int serial_can_receive(SerialState *s)
502 {
503     if(s->fcr & UART_FCR_FE) {
504         if (s->recv_fifo.num < UART_FIFO_LENGTH) {
505             /*
506              * Advertise (fifo.itl - fifo.count) bytes when count < ITL, and 1
507              * if above. If UART_FIFO_LENGTH - fifo.count is advertised the
508              * effect will be to almost always fill the fifo completely before
509              * the guest has a chance to respond, effectively overriding the ITL
510              * that the guest has set.
511              */
512             return (s->recv_fifo.num <= s->recv_fifo_itl) ?
513                         s->recv_fifo_itl - s->recv_fifo.num : 1;
514         } else {
515             return 0;
516         }
517     } else {
518         return !(s->lsr & UART_LSR_DR);
519     }
520 }
521 
522 static void serial_receive_break(SerialState *s)
523 {
524     s->rbr = 0;
525     /* When the LSR_DR is set a null byte is pushed into the fifo */
526     recv_fifo_put(s, '\0');
527     s->lsr |= UART_LSR_BI | UART_LSR_DR;
528     serial_update_irq(s);
529 }
530 
531 /* There's data in recv_fifo and s->rbr has not been read for 4 char transmit times */
532 static void fifo_timeout_int (void *opaque) {
533     SerialState *s = opaque;
534     if (s->recv_fifo.num) {
535         s->timeout_ipending = 1;
536         serial_update_irq(s);
537     }
538 }
539 
540 static int serial_can_receive1(void *opaque)
541 {
542     SerialState *s = opaque;
543     return serial_can_receive(s);
544 }
545 
546 static void serial_receive1(void *opaque, const uint8_t *buf, int size)
547 {
548     SerialState *s = opaque;
549 
550     if (s->wakeup) {
551         qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
552     }
553     if(s->fcr & UART_FCR_FE) {
554         int i;
555         for (i = 0; i < size; i++) {
556             recv_fifo_put(s, buf[i]);
557         }
558         s->lsr |= UART_LSR_DR;
559         /* call the timeout receive callback in 4 char transmit time */
560         timer_mod(s->fifo_timeout_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time * 4);
561     } else {
562         if (s->lsr & UART_LSR_DR)
563             s->lsr |= UART_LSR_OE;
564         s->rbr = buf[0];
565         s->lsr |= UART_LSR_DR;
566     }
567     serial_update_irq(s);
568 }
569 
570 static void serial_event(void *opaque, int event)
571 {
572     SerialState *s = opaque;
573     DPRINTF("event %x\n", event);
574     if (event == CHR_EVENT_BREAK)
575         serial_receive_break(s);
576 }
577 
578 static void serial_pre_save(void *opaque)
579 {
580     SerialState *s = opaque;
581     s->fcr_vmstate = s->fcr;
582 }
583 
584 static int serial_post_load(void *opaque, int version_id)
585 {
586     SerialState *s = opaque;
587 
588     if (version_id < 3) {
589         s->fcr_vmstate = 0;
590     }
591     /* Initialize fcr via setter to perform essential side-effects */
592     serial_ioport_write(s, 0x02, s->fcr_vmstate, 1);
593     serial_update_parameters(s);
594     return 0;
595 }
596 
597 const VMStateDescription vmstate_serial = {
598     .name = "serial",
599     .version_id = 3,
600     .minimum_version_id = 2,
601     .pre_save = serial_pre_save,
602     .post_load = serial_post_load,
603     .fields      = (VMStateField []) {
604         VMSTATE_UINT16_V(divider, SerialState, 2),
605         VMSTATE_UINT8(rbr, SerialState),
606         VMSTATE_UINT8(ier, SerialState),
607         VMSTATE_UINT8(iir, SerialState),
608         VMSTATE_UINT8(lcr, SerialState),
609         VMSTATE_UINT8(mcr, SerialState),
610         VMSTATE_UINT8(lsr, SerialState),
611         VMSTATE_UINT8(msr, SerialState),
612         VMSTATE_UINT8(scr, SerialState),
613         VMSTATE_UINT8_V(fcr_vmstate, SerialState, 3),
614         VMSTATE_END_OF_LIST()
615     }
616 };
617 
618 static void serial_reset(void *opaque)
619 {
620     SerialState *s = opaque;
621 
622     s->rbr = 0;
623     s->ier = 0;
624     s->iir = UART_IIR_NO_INT;
625     s->lcr = 0;
626     s->lsr = UART_LSR_TEMT | UART_LSR_THRE;
627     s->msr = UART_MSR_DCD | UART_MSR_DSR | UART_MSR_CTS;
628     /* Default to 9600 baud, 1 start bit, 8 data bits, 1 stop bit, no parity. */
629     s->divider = 0x0C;
630     s->mcr = UART_MCR_OUT2;
631     s->scr = 0;
632     s->tsr_retry = 0;
633     s->char_transmit_time = (get_ticks_per_sec() / 9600) * 10;
634     s->poll_msl = 0;
635 
636     fifo8_reset(&s->recv_fifo);
637     fifo8_reset(&s->xmit_fifo);
638 
639     s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
640 
641     s->thr_ipending = 0;
642     s->last_break_enable = 0;
643     qemu_irq_lower(s->irq);
644 }
645 
646 void serial_realize_core(SerialState *s, Error **errp)
647 {
648     if (!s->chr) {
649         error_setg(errp, "Can't create serial device, empty char device");
650         return;
651     }
652 
653     s->modem_status_poll = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) serial_update_msl, s);
654 
655     s->fifo_timeout_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) fifo_timeout_int, s);
656     qemu_register_reset(serial_reset, s);
657 
658     qemu_chr_add_handlers(s->chr, serial_can_receive1, serial_receive1,
659                           serial_event, s);
660     fifo8_create(&s->recv_fifo, UART_FIFO_LENGTH);
661     fifo8_create(&s->xmit_fifo, UART_FIFO_LENGTH);
662 }
663 
664 void serial_exit_core(SerialState *s)
665 {
666     qemu_chr_add_handlers(s->chr, NULL, NULL, NULL, NULL);
667     qemu_unregister_reset(serial_reset, s);
668 }
669 
670 /* Change the main reference oscillator frequency. */
671 void serial_set_frequency(SerialState *s, uint32_t frequency)
672 {
673     s->baudbase = frequency;
674     serial_update_parameters(s);
675 }
676 
677 const MemoryRegionOps serial_io_ops = {
678     .read = serial_ioport_read,
679     .write = serial_ioport_write,
680     .impl = {
681         .min_access_size = 1,
682         .max_access_size = 1,
683     },
684     .endianness = DEVICE_LITTLE_ENDIAN,
685 };
686 
687 SerialState *serial_init(int base, qemu_irq irq, int baudbase,
688                          CharDriverState *chr, MemoryRegion *system_io)
689 {
690     SerialState *s;
691     Error *err = NULL;
692 
693     s = g_malloc0(sizeof(SerialState));
694 
695     s->irq = irq;
696     s->baudbase = baudbase;
697     s->chr = chr;
698     serial_realize_core(s, &err);
699     if (err != NULL) {
700         error_report("%s", error_get_pretty(err));
701         error_free(err);
702         exit(1);
703     }
704 
705     vmstate_register(NULL, base, &vmstate_serial, s);
706 
707     memory_region_init_io(&s->io, NULL, &serial_io_ops, s, "serial", 8);
708     memory_region_add_subregion(system_io, base, &s->io);
709 
710     return s;
711 }
712 
713 /* Memory mapped interface */
714 static uint64_t serial_mm_read(void *opaque, hwaddr addr,
715                                unsigned size)
716 {
717     SerialState *s = opaque;
718     return serial_ioport_read(s, addr >> s->it_shift, 1);
719 }
720 
721 static void serial_mm_write(void *opaque, hwaddr addr,
722                             uint64_t value, unsigned size)
723 {
724     SerialState *s = opaque;
725     value &= ~0u >> (32 - (size * 8));
726     serial_ioport_write(s, addr >> s->it_shift, value, 1);
727 }
728 
729 static const MemoryRegionOps serial_mm_ops[3] = {
730     [DEVICE_NATIVE_ENDIAN] = {
731         .read = serial_mm_read,
732         .write = serial_mm_write,
733         .endianness = DEVICE_NATIVE_ENDIAN,
734     },
735     [DEVICE_LITTLE_ENDIAN] = {
736         .read = serial_mm_read,
737         .write = serial_mm_write,
738         .endianness = DEVICE_LITTLE_ENDIAN,
739     },
740     [DEVICE_BIG_ENDIAN] = {
741         .read = serial_mm_read,
742         .write = serial_mm_write,
743         .endianness = DEVICE_BIG_ENDIAN,
744     },
745 };
746 
747 SerialState *serial_mm_init(MemoryRegion *address_space,
748                             hwaddr base, int it_shift,
749                             qemu_irq irq, int baudbase,
750                             CharDriverState *chr, enum device_endian end)
751 {
752     SerialState *s;
753     Error *err = NULL;
754 
755     s = g_malloc0(sizeof(SerialState));
756 
757     s->it_shift = it_shift;
758     s->irq = irq;
759     s->baudbase = baudbase;
760     s->chr = chr;
761 
762     serial_realize_core(s, &err);
763     if (err != NULL) {
764         error_report("%s", error_get_pretty(err));
765         error_free(err);
766         exit(1);
767     }
768     vmstate_register(NULL, base, &vmstate_serial, s);
769 
770     memory_region_init_io(&s->io, NULL, &serial_mm_ops[end], s,
771                           "serial", 8 << it_shift);
772     memory_region_add_subregion(address_space, base, &s->io);
773 
774     serial_update_msl(s);
775     return s;
776 }
777