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