xref: /openbmc/qemu/hw/char/serial.c (revision 52f91c37)
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             if (fifo8_is_empty(&s->xmit_fifo)) {
229                 return FALSE;
230             }
231             s->tsr = fifo8_pop(&s->xmit_fifo);
232             if (!s->xmit_fifo.num) {
233                 s->lsr |= UART_LSR_THRE;
234             }
235         } else if ((s->lsr & UART_LSR_THRE)) {
236             return FALSE;
237         } else {
238             s->tsr = s->thr;
239             s->lsr |= UART_LSR_THRE;
240             s->lsr &= ~UART_LSR_TEMT;
241         }
242     }
243 
244     if (s->mcr & UART_MCR_LOOP) {
245         /* in loopback mode, say that we just received a char */
246         serial_receive1(s, &s->tsr, 1);
247     } else if (qemu_chr_fe_write(s->chr, &s->tsr, 1) != 1) {
248         if (s->tsr_retry >= 0 && s->tsr_retry < MAX_XMIT_RETRY &&
249             qemu_chr_fe_add_watch(s->chr, G_IO_OUT, serial_xmit, s) > 0) {
250             s->tsr_retry++;
251             return FALSE;
252         }
253         s->tsr_retry = 0;
254     } else {
255         s->tsr_retry = 0;
256     }
257 
258     s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
259 
260     if (s->lsr & UART_LSR_THRE) {
261         s->lsr |= UART_LSR_TEMT;
262         s->thr_ipending = 1;
263         serial_update_irq(s);
264     }
265 
266     return FALSE;
267 }
268 
269 
270 static void serial_ioport_write(void *opaque, hwaddr addr, uint64_t val,
271                                 unsigned size)
272 {
273     SerialState *s = opaque;
274 
275     addr &= 7;
276     DPRINTF("write addr=0x%" HWADDR_PRIx " val=0x%" PRIx64 "\n", addr, val);
277     switch(addr) {
278     default:
279     case 0:
280         if (s->lcr & UART_LCR_DLAB) {
281             s->divider = (s->divider & 0xff00) | val;
282             serial_update_parameters(s);
283         } else {
284             s->thr = (uint8_t) val;
285             if(s->fcr & UART_FCR_FE) {
286                 /* xmit overruns overwrite data, so make space if needed */
287                 if (fifo8_is_full(&s->xmit_fifo)) {
288                     fifo8_pop(&s->xmit_fifo);
289                 }
290                 fifo8_push(&s->xmit_fifo, s->thr);
291                 s->lsr &= ~UART_LSR_TEMT;
292             }
293             s->thr_ipending = 0;
294             s->lsr &= ~UART_LSR_THRE;
295             serial_update_irq(s);
296             serial_xmit(NULL, G_IO_OUT, s);
297         }
298         break;
299     case 1:
300         if (s->lcr & UART_LCR_DLAB) {
301             s->divider = (s->divider & 0x00ff) | (val << 8);
302             serial_update_parameters(s);
303         } else {
304             s->ier = val & 0x0f;
305             /* If the backend device is a real serial port, turn polling of the modem
306                status lines on physical port on or off depending on UART_IER_MSI state */
307             if (s->poll_msl >= 0) {
308                 if (s->ier & UART_IER_MSI) {
309                      s->poll_msl = 1;
310                      serial_update_msl(s);
311                 } else {
312                      timer_del(s->modem_status_poll);
313                      s->poll_msl = 0;
314                 }
315             }
316             if (s->lsr & UART_LSR_THRE) {
317                 s->thr_ipending = 1;
318                 serial_update_irq(s);
319             }
320         }
321         break;
322     case 2:
323         val = val & 0xFF;
324 
325         if (s->fcr == val)
326             break;
327 
328         /* Did the enable/disable flag change? If so, make sure FIFOs get flushed */
329         if ((val ^ s->fcr) & UART_FCR_FE)
330             val |= UART_FCR_XFR | UART_FCR_RFR;
331 
332         /* FIFO clear */
333 
334         if (val & UART_FCR_RFR) {
335             timer_del(s->fifo_timeout_timer);
336             s->timeout_ipending=0;
337             fifo8_reset(&s->recv_fifo);
338         }
339 
340         if (val & UART_FCR_XFR) {
341             fifo8_reset(&s->xmit_fifo);
342         }
343 
344         if (val & UART_FCR_FE) {
345             s->iir |= UART_IIR_FE;
346             /* Set recv_fifo trigger Level */
347             switch (val & 0xC0) {
348             case UART_FCR_ITL_1:
349                 s->recv_fifo_itl = 1;
350                 break;
351             case UART_FCR_ITL_2:
352                 s->recv_fifo_itl = 4;
353                 break;
354             case UART_FCR_ITL_3:
355                 s->recv_fifo_itl = 8;
356                 break;
357             case UART_FCR_ITL_4:
358                 s->recv_fifo_itl = 14;
359                 break;
360             }
361         } else
362             s->iir &= ~UART_IIR_FE;
363 
364         /* Set fcr - or at least the bits in it that are supposed to "stick" */
365         s->fcr = val & 0xC9;
366         serial_update_irq(s);
367         break;
368     case 3:
369         {
370             int break_enable;
371             s->lcr = val;
372             serial_update_parameters(s);
373             break_enable = (val >> 6) & 1;
374             if (break_enable != s->last_break_enable) {
375                 s->last_break_enable = break_enable;
376                 qemu_chr_fe_ioctl(s->chr, CHR_IOCTL_SERIAL_SET_BREAK,
377                                &break_enable);
378             }
379         }
380         break;
381     case 4:
382         {
383             int flags;
384             int old_mcr = s->mcr;
385             s->mcr = val & 0x1f;
386             if (val & UART_MCR_LOOP)
387                 break;
388 
389             if (s->poll_msl >= 0 && old_mcr != s->mcr) {
390 
391                 qemu_chr_fe_ioctl(s->chr,CHR_IOCTL_SERIAL_GET_TIOCM, &flags);
392 
393                 flags &= ~(CHR_TIOCM_RTS | CHR_TIOCM_DTR);
394 
395                 if (val & UART_MCR_RTS)
396                     flags |= CHR_TIOCM_RTS;
397                 if (val & UART_MCR_DTR)
398                     flags |= CHR_TIOCM_DTR;
399 
400                 qemu_chr_fe_ioctl(s->chr,CHR_IOCTL_SERIAL_SET_TIOCM, &flags);
401                 /* Update the modem status after a one-character-send wait-time, since there may be a response
402                    from the device/computer at the other end of the serial line */
403                 timer_mod(s->modem_status_poll, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time);
404             }
405         }
406         break;
407     case 5:
408         break;
409     case 6:
410         break;
411     case 7:
412         s->scr = val;
413         break;
414     }
415 }
416 
417 static uint64_t serial_ioport_read(void *opaque, hwaddr addr, unsigned size)
418 {
419     SerialState *s = opaque;
420     uint32_t ret;
421 
422     addr &= 7;
423     switch(addr) {
424     default:
425     case 0:
426         if (s->lcr & UART_LCR_DLAB) {
427             ret = s->divider & 0xff;
428         } else {
429             if(s->fcr & UART_FCR_FE) {
430                 ret = fifo8_is_empty(&s->recv_fifo) ?
431                             0 : fifo8_pop(&s->recv_fifo);
432                 if (s->recv_fifo.num == 0) {
433                     s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
434                 } else {
435                     timer_mod(s->fifo_timeout_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time * 4);
436                 }
437                 s->timeout_ipending = 0;
438             } else {
439                 ret = s->rbr;
440                 s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
441             }
442             serial_update_irq(s);
443             if (!(s->mcr & UART_MCR_LOOP)) {
444                 /* in loopback mode, don't receive any data */
445                 qemu_chr_accept_input(s->chr);
446             }
447         }
448         break;
449     case 1:
450         if (s->lcr & UART_LCR_DLAB) {
451             ret = (s->divider >> 8) & 0xff;
452         } else {
453             ret = s->ier;
454         }
455         break;
456     case 2:
457         ret = s->iir;
458         if ((ret & UART_IIR_ID) == UART_IIR_THRI) {
459             s->thr_ipending = 0;
460             serial_update_irq(s);
461         }
462         break;
463     case 3:
464         ret = s->lcr;
465         break;
466     case 4:
467         ret = s->mcr;
468         break;
469     case 5:
470         ret = s->lsr;
471         /* Clear break and overrun interrupts */
472         if (s->lsr & (UART_LSR_BI|UART_LSR_OE)) {
473             s->lsr &= ~(UART_LSR_BI|UART_LSR_OE);
474             serial_update_irq(s);
475         }
476         break;
477     case 6:
478         if (s->mcr & UART_MCR_LOOP) {
479             /* in loopback, the modem output pins are connected to the
480                inputs */
481             ret = (s->mcr & 0x0c) << 4;
482             ret |= (s->mcr & 0x02) << 3;
483             ret |= (s->mcr & 0x01) << 5;
484         } else {
485             if (s->poll_msl >= 0)
486                 serial_update_msl(s);
487             ret = s->msr;
488             /* Clear delta bits & msr int after read, if they were set */
489             if (s->msr & UART_MSR_ANY_DELTA) {
490                 s->msr &= 0xF0;
491                 serial_update_irq(s);
492             }
493         }
494         break;
495     case 7:
496         ret = s->scr;
497         break;
498     }
499     DPRINTF("read addr=0x%" HWADDR_PRIx " val=0x%02x\n", addr, ret);
500     return ret;
501 }
502 
503 static int serial_can_receive(SerialState *s)
504 {
505     if(s->fcr & UART_FCR_FE) {
506         if (s->recv_fifo.num < UART_FIFO_LENGTH) {
507             /*
508              * Advertise (fifo.itl - fifo.count) bytes when count < ITL, and 1
509              * if above. If UART_FIFO_LENGTH - fifo.count is advertised the
510              * effect will be to almost always fill the fifo completely before
511              * the guest has a chance to respond, effectively overriding the ITL
512              * that the guest has set.
513              */
514             return (s->recv_fifo.num <= s->recv_fifo_itl) ?
515                         s->recv_fifo_itl - s->recv_fifo.num : 1;
516         } else {
517             return 0;
518         }
519     } else {
520         return !(s->lsr & UART_LSR_DR);
521     }
522 }
523 
524 static void serial_receive_break(SerialState *s)
525 {
526     s->rbr = 0;
527     /* When the LSR_DR is set a null byte is pushed into the fifo */
528     recv_fifo_put(s, '\0');
529     s->lsr |= UART_LSR_BI | UART_LSR_DR;
530     serial_update_irq(s);
531 }
532 
533 /* There's data in recv_fifo and s->rbr has not been read for 4 char transmit times */
534 static void fifo_timeout_int (void *opaque) {
535     SerialState *s = opaque;
536     if (s->recv_fifo.num) {
537         s->timeout_ipending = 1;
538         serial_update_irq(s);
539     }
540 }
541 
542 static int serial_can_receive1(void *opaque)
543 {
544     SerialState *s = opaque;
545     return serial_can_receive(s);
546 }
547 
548 static void serial_receive1(void *opaque, const uint8_t *buf, int size)
549 {
550     SerialState *s = opaque;
551 
552     if (s->wakeup) {
553         qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
554     }
555     if(s->fcr & UART_FCR_FE) {
556         int i;
557         for (i = 0; i < size; i++) {
558             recv_fifo_put(s, buf[i]);
559         }
560         s->lsr |= UART_LSR_DR;
561         /* call the timeout receive callback in 4 char transmit time */
562         timer_mod(s->fifo_timeout_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time * 4);
563     } else {
564         if (s->lsr & UART_LSR_DR)
565             s->lsr |= UART_LSR_OE;
566         s->rbr = buf[0];
567         s->lsr |= UART_LSR_DR;
568     }
569     serial_update_irq(s);
570 }
571 
572 static void serial_event(void *opaque, int event)
573 {
574     SerialState *s = opaque;
575     DPRINTF("event %x\n", event);
576     if (event == CHR_EVENT_BREAK)
577         serial_receive_break(s);
578 }
579 
580 static void serial_pre_save(void *opaque)
581 {
582     SerialState *s = opaque;
583     s->fcr_vmstate = s->fcr;
584 }
585 
586 static int serial_post_load(void *opaque, int version_id)
587 {
588     SerialState *s = opaque;
589 
590     if (version_id < 3) {
591         s->fcr_vmstate = 0;
592     }
593     /* Initialize fcr via setter to perform essential side-effects */
594     serial_ioport_write(s, 0x02, s->fcr_vmstate, 1);
595     serial_update_parameters(s);
596     return 0;
597 }
598 
599 const VMStateDescription vmstate_serial = {
600     .name = "serial",
601     .version_id = 3,
602     .minimum_version_id = 2,
603     .pre_save = serial_pre_save,
604     .post_load = serial_post_load,
605     .fields      = (VMStateField []) {
606         VMSTATE_UINT16_V(divider, SerialState, 2),
607         VMSTATE_UINT8(rbr, SerialState),
608         VMSTATE_UINT8(ier, SerialState),
609         VMSTATE_UINT8(iir, SerialState),
610         VMSTATE_UINT8(lcr, SerialState),
611         VMSTATE_UINT8(mcr, SerialState),
612         VMSTATE_UINT8(lsr, SerialState),
613         VMSTATE_UINT8(msr, SerialState),
614         VMSTATE_UINT8(scr, SerialState),
615         VMSTATE_UINT8_V(fcr_vmstate, SerialState, 3),
616         VMSTATE_END_OF_LIST()
617     }
618 };
619 
620 static void serial_reset(void *opaque)
621 {
622     SerialState *s = opaque;
623 
624     s->rbr = 0;
625     s->ier = 0;
626     s->iir = UART_IIR_NO_INT;
627     s->lcr = 0;
628     s->lsr = UART_LSR_TEMT | UART_LSR_THRE;
629     s->msr = UART_MSR_DCD | UART_MSR_DSR | UART_MSR_CTS;
630     /* Default to 9600 baud, 1 start bit, 8 data bits, 1 stop bit, no parity. */
631     s->divider = 0x0C;
632     s->mcr = UART_MCR_OUT2;
633     s->scr = 0;
634     s->tsr_retry = 0;
635     s->char_transmit_time = (get_ticks_per_sec() / 9600) * 10;
636     s->poll_msl = 0;
637 
638     fifo8_reset(&s->recv_fifo);
639     fifo8_reset(&s->xmit_fifo);
640 
641     s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
642 
643     s->thr_ipending = 0;
644     s->last_break_enable = 0;
645     qemu_irq_lower(s->irq);
646 }
647 
648 void serial_realize_core(SerialState *s, Error **errp)
649 {
650     if (!s->chr) {
651         error_setg(errp, "Can't create serial device, empty char device");
652         return;
653     }
654 
655     s->modem_status_poll = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) serial_update_msl, s);
656 
657     s->fifo_timeout_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) fifo_timeout_int, s);
658     qemu_register_reset(serial_reset, s);
659 
660     qemu_chr_add_handlers(s->chr, serial_can_receive1, serial_receive1,
661                           serial_event, s);
662     fifo8_create(&s->recv_fifo, UART_FIFO_LENGTH);
663     fifo8_create(&s->xmit_fifo, UART_FIFO_LENGTH);
664 }
665 
666 void serial_exit_core(SerialState *s)
667 {
668     qemu_chr_add_handlers(s->chr, NULL, NULL, NULL, NULL);
669     qemu_unregister_reset(serial_reset, s);
670 }
671 
672 /* Change the main reference oscillator frequency. */
673 void serial_set_frequency(SerialState *s, uint32_t frequency)
674 {
675     s->baudbase = frequency;
676     serial_update_parameters(s);
677 }
678 
679 const MemoryRegionOps serial_io_ops = {
680     .read = serial_ioport_read,
681     .write = serial_ioport_write,
682     .impl = {
683         .min_access_size = 1,
684         .max_access_size = 1,
685     },
686     .endianness = DEVICE_LITTLE_ENDIAN,
687 };
688 
689 SerialState *serial_init(int base, qemu_irq irq, int baudbase,
690                          CharDriverState *chr, MemoryRegion *system_io)
691 {
692     SerialState *s;
693     Error *err = NULL;
694 
695     s = g_malloc0(sizeof(SerialState));
696 
697     s->irq = irq;
698     s->baudbase = baudbase;
699     s->chr = chr;
700     serial_realize_core(s, &err);
701     if (err != NULL) {
702         error_report("%s", error_get_pretty(err));
703         error_free(err);
704         exit(1);
705     }
706 
707     vmstate_register(NULL, base, &vmstate_serial, s);
708 
709     memory_region_init_io(&s->io, NULL, &serial_io_ops, s, "serial", 8);
710     memory_region_add_subregion(system_io, base, &s->io);
711 
712     return s;
713 }
714 
715 /* Memory mapped interface */
716 static uint64_t serial_mm_read(void *opaque, hwaddr addr,
717                                unsigned size)
718 {
719     SerialState *s = opaque;
720     return serial_ioport_read(s, addr >> s->it_shift, 1);
721 }
722 
723 static void serial_mm_write(void *opaque, hwaddr addr,
724                             uint64_t value, unsigned size)
725 {
726     SerialState *s = opaque;
727     value &= ~0u >> (32 - (size * 8));
728     serial_ioport_write(s, addr >> s->it_shift, value, 1);
729 }
730 
731 static const MemoryRegionOps serial_mm_ops[3] = {
732     [DEVICE_NATIVE_ENDIAN] = {
733         .read = serial_mm_read,
734         .write = serial_mm_write,
735         .endianness = DEVICE_NATIVE_ENDIAN,
736     },
737     [DEVICE_LITTLE_ENDIAN] = {
738         .read = serial_mm_read,
739         .write = serial_mm_write,
740         .endianness = DEVICE_LITTLE_ENDIAN,
741     },
742     [DEVICE_BIG_ENDIAN] = {
743         .read = serial_mm_read,
744         .write = serial_mm_write,
745         .endianness = DEVICE_BIG_ENDIAN,
746     },
747 };
748 
749 SerialState *serial_mm_init(MemoryRegion *address_space,
750                             hwaddr base, int it_shift,
751                             qemu_irq irq, int baudbase,
752                             CharDriverState *chr, enum device_endian end)
753 {
754     SerialState *s;
755     Error *err = NULL;
756 
757     s = g_malloc0(sizeof(SerialState));
758 
759     s->it_shift = it_shift;
760     s->irq = irq;
761     s->baudbase = baudbase;
762     s->chr = chr;
763 
764     serial_realize_core(s, &err);
765     if (err != NULL) {
766         error_report("%s", error_get_pretty(err));
767         error_free(err);
768         exit(1);
769     }
770     vmstate_register(NULL, base, &vmstate_serial, s);
771 
772     memory_region_init_io(&s->io, NULL, &serial_mm_ops[end], s,
773                           "serial", 8 << it_shift);
774     memory_region_add_subregion(address_space, base, &s->io);
775 
776     serial_update_msl(s);
777     return s;
778 }
779