serial.c 30.7 KB
Newer Older
1
/*
2
 * QEMU 16550A UART emulation
3
 *
4
 * Copyright (c) 2003-2004 Fabrice Bellard
5
 * Copyright (c) 2008 Citrix Systems, Inc.
6
 *
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
Gerd Hoffmann's avatar
Gerd Hoffmann committed
25

Peter Maydell's avatar
Peter Maydell committed
26
#include "qemu/osdep.h"
27
#include "hw/char/serial.h"
28
#include "chardev/char-serial.h"
29
#include "qapi/error.h"
30
#include "qemu/timer.h"
31
#include "exec/address-spaces.h"
32
#include "qemu/error-report.h"
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

//#define DEBUG_SERIAL

#define UART_LCR_DLAB	0x80	/* Divisor latch access bit */

#define UART_IER_MSI	0x08	/* Enable Modem status interrupt */
#define UART_IER_RLSI	0x04	/* Enable receiver line status interrupt */
#define UART_IER_THRI	0x02	/* Enable Transmitter holding register int. */
#define UART_IER_RDI	0x01	/* Enable receiver data interrupt */

#define UART_IIR_NO_INT	0x01	/* No interrupts pending */
#define UART_IIR_ID	0x06	/* Mask for the interrupt ID */

#define UART_IIR_MSI	0x00	/* Modem status interrupt */
#define UART_IIR_THRI	0x02	/* Transmitter holding register empty */
#define UART_IIR_RDI	0x04	/* Receiver data interrupt */
#define UART_IIR_RLSI	0x06	/* Receiver line status interrupt */
50 51 52 53
#define UART_IIR_CTI    0x0C    /* Character Timeout Indication */

#define UART_IIR_FENF   0x80    /* Fifo enabled, but not functionning */
#define UART_IIR_FE     0xC0    /* Fifo enabled */
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83

/*
 * These are the definitions for the Modem Control Register
 */
#define UART_MCR_LOOP	0x10	/* Enable loopback test mode */
#define UART_MCR_OUT2	0x08	/* Out2 complement */
#define UART_MCR_OUT1	0x04	/* Out1 complement */
#define UART_MCR_RTS	0x02	/* RTS complement */
#define UART_MCR_DTR	0x01	/* DTR complement */

/*
 * These are the definitions for the Modem Status Register
 */
#define UART_MSR_DCD	0x80	/* Data Carrier Detect */
#define UART_MSR_RI	0x40	/* Ring Indicator */
#define UART_MSR_DSR	0x20	/* Data Set Ready */
#define UART_MSR_CTS	0x10	/* Clear to Send */
#define UART_MSR_DDCD	0x08	/* Delta DCD */
#define UART_MSR_TERI	0x04	/* Trailing edge ring indicator */
#define UART_MSR_DDSR	0x02	/* Delta DSR */
#define UART_MSR_DCTS	0x01	/* Delta CTS */
#define UART_MSR_ANY_DELTA 0x0F	/* Any of the delta bits! */

#define UART_LSR_TEMT	0x40	/* Transmitter empty */
#define UART_LSR_THRE	0x20	/* Transmit-hold-register empty */
#define UART_LSR_BI	0x10	/* Break interrupt indicator */
#define UART_LSR_FE	0x08	/* Frame error indicator */
#define UART_LSR_PE	0x04	/* Parity error indicator */
#define UART_LSR_OE	0x02	/* Overrun error indicator */
#define UART_LSR_DR	0x01	/* Receiver data ready */
84
#define UART_LSR_INT_ANY 0x1E	/* Any of the lsr-interrupt-triggering status bits */
85

86 87 88 89 90 91 92 93 94 95 96 97 98 99
/* Interrupt trigger levels. The byte-counts are for 16550A - in newer UARTs the byte-count for each ITL is higher. */

#define UART_FCR_ITL_1      0x00 /* 1 byte ITL */
#define UART_FCR_ITL_2      0x40 /* 4 bytes ITL */
#define UART_FCR_ITL_3      0x80 /* 8 bytes ITL */
#define UART_FCR_ITL_4      0xC0 /* 14 bytes ITL */

#define UART_FCR_DMS        0x08    /* DMA Mode Select */
#define UART_FCR_XFR        0x04    /* XMIT Fifo Reset */
#define UART_FCR_RFR        0x02    /* RCVR Fifo Reset */
#define UART_FCR_FE         0x01    /* FIFO Enable */

#define MAX_XMIT_RETRY      4

100 101
#ifdef DEBUG_SERIAL
#define DPRINTF(fmt, ...) \
102
do { fprintf(stderr, "serial: " fmt , ## __VA_ARGS__); } while (0)
103 104
#else
#define DPRINTF(fmt, ...) \
105
do {} while (0)
106 107
#endif

108
static void serial_receive1(void *opaque, const uint8_t *buf, int size);
109
static void serial_xmit(SerialState *s);
110

111
static inline void recv_fifo_put(SerialState *s, uint8_t chr)
112
{
113
    /* Receive overruns do not overwrite FIFO contents. */
114 115 116
    if (!fifo8_is_full(&s->recv_fifo)) {
        fifo8_push(&s->recv_fifo, chr);
    } else {
117
        s->lsr |= UART_LSR_OE;
118
    }
119
}
120

121 122 123 124 125 126
static void serial_update_irq(SerialState *s)
{
    uint8_t tmp_iir = UART_IIR_NO_INT;

    if ((s->ier & UART_IER_RLSI) && (s->lsr & UART_LSR_INT_ANY)) {
        tmp_iir = UART_IIR_RLSI;
127
    } else if ((s->ier & UART_IER_RDI) && s->timeout_ipending) {
128 129 130
        /* Note that(s->ier & UART_IER_RDI) can mask this interrupt,
         * this is not in the specification but is observed on existing
         * hardware.  */
131
        tmp_iir = UART_IIR_CTI;
132 133
    } else if ((s->ier & UART_IER_RDI) && (s->lsr & UART_LSR_DR) &&
               (!(s->fcr & UART_FCR_FE) ||
134
                s->recv_fifo.num >= s->recv_fifo_itl)) {
135
        tmp_iir = UART_IIR_RDI;
136 137 138 139 140 141 142 143 144 145 146 147
    } else if ((s->ier & UART_IER_THRI) && s->thr_ipending) {
        tmp_iir = UART_IIR_THRI;
    } else if ((s->ier & UART_IER_MSI) && (s->msr & UART_MSR_ANY_DELTA)) {
        tmp_iir = UART_IIR_MSI;
    }

    s->iir = tmp_iir | (s->iir & 0xF0);

    if (tmp_iir != UART_IIR_NO_INT) {
        qemu_irq_raise(s->irq);
    } else {
        qemu_irq_lower(s->irq);
148 149 150
    }
}

bellard's avatar
bellard committed
151 152
static void serial_update_parameters(SerialState *s)
{
153
    int speed, parity, data_bits, stop_bits, frame_size;
bellard's avatar
bellard committed
154
    QEMUSerialSetParams ssp;
bellard's avatar
bellard committed
155

156
    if (s->divider == 0 || s->divider > s->baudbase) {
157
        return;
158
    }
159

Stefan Weil's avatar
Stefan Weil committed
160
    /* Start bit. */
161
    frame_size = 1;
bellard's avatar
bellard committed
162
    if (s->lcr & 0x08) {
Stefan Weil's avatar
Stefan Weil committed
163 164
        /* Parity bit. */
        frame_size++;
bellard's avatar
bellard committed
165 166 167 168 169 170 171
        if (s->lcr & 0x10)
            parity = 'E';
        else
            parity = 'O';
    } else {
            parity = 'N';
    }
172
    if (s->lcr & 0x04)
bellard's avatar
bellard committed
173 174 175
        stop_bits = 2;
    else
        stop_bits = 1;
176

bellard's avatar
bellard committed
177
    data_bits = (s->lcr & 0x03) + 5;
178
    frame_size += data_bits + stop_bits;
aurel32's avatar
aurel32 committed
179
    speed = s->baudbase / s->divider;
bellard's avatar
bellard committed
180 181 182 183
    ssp.speed = speed;
    ssp.parity = parity;
    ssp.data_bits = data_bits;
    ssp.stop_bits = stop_bits;
184
    s->char_transmit_time =  (NANOSECONDS_PER_SECOND / speed) * frame_size;
185
    qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_SET_PARAMS, &ssp);
186 187

    DPRINTF("speed=%d parity=%c data=%d stop=%d\n",
bellard's avatar
bellard committed
188 189 190
           speed, parity, data_bits, stop_bits);
}

191 192 193 194 195
static void serial_update_msl(SerialState *s)
{
    uint8_t omsr;
    int flags;

196
    timer_del(s->modem_status_poll);
197

198
    if (qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_GET_TIOCM,
199
                          &flags) == -ENOTSUP) {
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
        s->poll_msl = -1;
        return;
    }

    omsr = s->msr;

    s->msr = (flags & CHR_TIOCM_CTS) ? s->msr | UART_MSR_CTS : s->msr & ~UART_MSR_CTS;
    s->msr = (flags & CHR_TIOCM_DSR) ? s->msr | UART_MSR_DSR : s->msr & ~UART_MSR_DSR;
    s->msr = (flags & CHR_TIOCM_CAR) ? s->msr | UART_MSR_DCD : s->msr & ~UART_MSR_DCD;
    s->msr = (flags & CHR_TIOCM_RI) ? s->msr | UART_MSR_RI : s->msr & ~UART_MSR_RI;

    if (s->msr != omsr) {
         /* Set delta bits */
         s->msr = s->msr | ((s->msr >> 4) ^ (omsr >> 4));
         /* UART_MSR_TERI only if change was from 1 -> 0 */
         if ((s->msr & UART_MSR_TERI) && !(omsr & UART_MSR_RI))
             s->msr &= ~UART_MSR_TERI;
         serial_update_irq(s);
    }

    /* The real 16550A apparently has a 250ns response latency to line status changes.
       We'll be lazy and poll only every 10ms, and only poll it at all if MSI interrupts are turned on */

223 224 225 226
    if (s->poll_msl) {
        timer_mod(s->modem_status_poll, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
                  NANOSECONDS_PER_SECOND / 100);
    }
227 228
}

229 230
static gboolean serial_watch_cb(GIOChannel *chan, GIOCondition cond,
                                void *opaque)
231 232
{
    SerialState *s = opaque;
233
    s->watch_tag = 0;
234 235 236
    serial_xmit(s);
    return FALSE;
}
237

238 239
static void serial_xmit(SerialState *s)
{
240
    do {
241
        assert(!(s->lsr & UART_LSR_TEMT));
242
        if (s->tsr_retry == 0) {
243 244
            assert(!(s->lsr & UART_LSR_THRE));

245
            if (s->fcr & UART_FCR_FE) {
246
                assert(!fifo8_is_empty(&s->xmit_fifo));
247 248 249 250 251 252
                s->tsr = fifo8_pop(&s->xmit_fifo);
                if (!s->xmit_fifo.num) {
                    s->lsr |= UART_LSR_THRE;
                }
            } else {
                s->tsr = s->thr;
253
                s->lsr |= UART_LSR_THRE;
254 255 256 257
            }
            if ((s->lsr & UART_LSR_THRE) && !s->thr_ipending) {
                s->thr_ipending = 1;
                serial_update_irq(s);
258
            }
259 260
        }

261 262 263
        if (s->mcr & UART_MCR_LOOP) {
            /* in loopback mode, say that we just received a char */
            serial_receive1(s, &s->tsr, 1);
264
        } else if (qemu_chr_fe_write(&s->chr, &s->tsr, 1) != 1 &&
265 266
                   s->tsr_retry < MAX_XMIT_RETRY) {
            assert(s->watch_tag == 0);
267
            s->watch_tag =
268
                qemu_chr_fe_add_watch(&s->chr, G_IO_OUT | G_IO_HUP,
269
                                      serial_watch_cb, s);
270
            if (s->watch_tag > 0) {
271
                s->tsr_retry++;
272
                return;
273
            }
274
        }
275
        s->tsr_retry = 0;
276

277 278
        /* Transmit another byte if it is already available. It is only
           possible when FIFO is enabled and not empty. */
279
    } while (!(s->lsr & UART_LSR_THRE));
280

281
    s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
282
    s->lsr |= UART_LSR_TEMT;
283 284
}

285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
/* Setter for FCR.
   is_load flag means, that value is set while loading VM state
   and interrupt should not be invoked */
static void serial_write_fcr(SerialState *s, uint8_t val)
{
    /* Set fcr - val only has the bits that are supposed to "stick" */
    s->fcr = val;

    if (val & UART_FCR_FE) {
        s->iir |= UART_IIR_FE;
        /* Set recv_fifo trigger Level */
        switch (val & 0xC0) {
        case UART_FCR_ITL_1:
            s->recv_fifo_itl = 1;
            break;
        case UART_FCR_ITL_2:
            s->recv_fifo_itl = 4;
            break;
        case UART_FCR_ITL_3:
            s->recv_fifo_itl = 8;
            break;
        case UART_FCR_ITL_4:
            s->recv_fifo_itl = 14;
            break;
        }
    } else {
        s->iir &= ~UART_IIR_FE;
    }
}

315 316
static void serial_ioport_write(void *opaque, hwaddr addr, uint64_t val,
                                unsigned size)
317
{
bellard's avatar
bellard committed
318
    SerialState *s = opaque;
319

320
    addr &= 7;
321
    DPRINTF("write addr=0x%" HWADDR_PRIx " val=0x%" PRIx64 "\n", addr, val);
322 323 324 325 326
    switch(addr) {
    default:
    case 0:
        if (s->lcr & UART_LCR_DLAB) {
            s->divider = (s->divider & 0xff00) | val;
bellard's avatar
bellard committed
327
            serial_update_parameters(s);
328
        } else {
329 330
            s->thr = (uint8_t) val;
            if(s->fcr & UART_FCR_FE) {
331 332 333 334 335
                /* xmit overruns overwrite data, so make space if needed */
                if (fifo8_is_full(&s->xmit_fifo)) {
                    fifo8_pop(&s->xmit_fifo);
                }
                fifo8_push(&s->xmit_fifo, s->thr);
336
            }
337 338
            s->thr_ipending = 0;
            s->lsr &= ~UART_LSR_THRE;
339
            s->lsr &= ~UART_LSR_TEMT;
340
            serial_update_irq(s);
341
            if (s->tsr_retry == 0) {
342
                serial_xmit(s);
343
            }
344 345 346 347 348
        }
        break;
    case 1:
        if (s->lcr & UART_LCR_DLAB) {
            s->divider = (s->divider & 0x00ff) | (val << 8);
bellard's avatar
bellard committed
349
            serial_update_parameters(s);
350
        } else {
351
            uint8_t changed = (s->ier ^ val) & 0x0f;
352
            s->ier = val & 0x0f;
353
            /* If the backend device is a real serial port, turn polling of the modem
354 355 356
             * status lines on physical port on or off depending on UART_IER_MSI state.
             */
            if ((changed & UART_IER_MSI) && s->poll_msl >= 0) {
357 358 359 360
                if (s->ier & UART_IER_MSI) {
                     s->poll_msl = 1;
                     serial_update_msl(s);
                } else {
361
                     timer_del(s->modem_status_poll);
362 363 364
                     s->poll_msl = 0;
                }
            }
365 366 367 368 369 370

            /* Turning on the THRE interrupt on IER can trigger the interrupt
             * if LSR.THRE=1, even if it had been masked before by reading IIR.
             * This is not in the datasheet, but Windows relies on it.  It is
             * unclear if THRE has to be resampled every time THRI becomes
             * 1, or only on the rising edge.  Bochs does the latter, and Windows
371 372
             * always toggles IER to all zeroes and back to all ones, so do the
             * same.
373 374 375 376
             *
             * If IER.THRI is zero, thr_ipending is not used.  Set it to zero
             * so that the thr_ipending subsection is not migrated.
             */
377 378 379 380 381 382 383 384 385 386
            if (changed & UART_IER_THRI) {
                if ((s->ier & UART_IER_THRI) && (s->lsr & UART_LSR_THRE)) {
                    s->thr_ipending = 1;
                } else {
                    s->thr_ipending = 0;
                }
            }

            if (changed) {
                serial_update_irq(s);
387
            }
388 389 390
        }
        break;
    case 2:
391
        /* Did the enable/disable flag change? If so, make sure FIFOs get flushed */
392
        if ((val ^ s->fcr) & UART_FCR_FE) {
393
            val |= UART_FCR_XFR | UART_FCR_RFR;
394
        }
395 396 397 398

        /* FIFO clear */

        if (val & UART_FCR_RFR) {
399
            s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
400
            timer_del(s->fifo_timeout_timer);
401
            s->timeout_ipending = 0;
402
            fifo8_reset(&s->recv_fifo);
403 404 405
        }

        if (val & UART_FCR_XFR) {
406 407
            s->lsr |= UART_LSR_THRE;
            s->thr_ipending = 1;
408
            fifo8_reset(&s->xmit_fifo);
409 410
        }

411
        serial_write_fcr(s, val & 0xC9);
412
        serial_update_irq(s);
413 414
        break;
    case 3:
bellard's avatar
bellard committed
415 416 417 418 419 420 421
        {
            int break_enable;
            s->lcr = val;
            serial_update_parameters(s);
            break_enable = (val >> 6) & 1;
            if (break_enable != s->last_break_enable) {
                s->last_break_enable = break_enable;
422 423
                qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_SET_BREAK,
                                  &break_enable);
bellard's avatar
bellard committed
424 425
            }
        }
426 427
        break;
    case 4:
428 429 430 431 432 433 434 435 436
        {
            int flags;
            int old_mcr = s->mcr;
            s->mcr = val & 0x1f;
            if (val & UART_MCR_LOOP)
                break;

            if (s->poll_msl >= 0 && old_mcr != s->mcr) {

437
                qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_GET_TIOCM, &flags);
438 439 440 441 442 443 444 445

                flags &= ~(CHR_TIOCM_RTS | CHR_TIOCM_DTR);

                if (val & UART_MCR_RTS)
                    flags |= CHR_TIOCM_RTS;
                if (val & UART_MCR_DTR)
                    flags |= CHR_TIOCM_DTR;

446
                qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_SET_TIOCM, &flags);
447 448
                /* Update the modem status after a one-character-send wait-time, since there may be a response
                   from the device/computer at the other end of the serial line */
449
                timer_mod(s->modem_status_poll, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time);
450 451
            }
        }
452 453 454 455 456 457 458 459 460 461 462
        break;
    case 5:
        break;
    case 6:
        break;
    case 7:
        s->scr = val;
        break;
    }
}

463
static uint64_t serial_ioport_read(void *opaque, hwaddr addr, unsigned size)
464
{
bellard's avatar
bellard committed
465
    SerialState *s = opaque;
466 467 468 469 470 471 472
    uint32_t ret;

    addr &= 7;
    switch(addr) {
    default:
    case 0:
        if (s->lcr & UART_LCR_DLAB) {
473
            ret = s->divider & 0xff;
474
        } else {
475
            if(s->fcr & UART_FCR_FE) {
476
                ret = fifo8_is_empty(&s->recv_fifo) ?
477 478
                            0 : fifo8_pop(&s->recv_fifo);
                if (s->recv_fifo.num == 0) {
479
                    s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
480
                } else {
481
                    timer_mod(s->fifo_timeout_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time * 4);
482
                }
483 484 485 486 487
                s->timeout_ipending = 0;
            } else {
                ret = s->rbr;
                s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
            }
bellard's avatar
bellard committed
488
            serial_update_irq(s);
489 490
            if (!(s->mcr & UART_MCR_LOOP)) {
                /* in loopback mode, don't receive any data */
491
                qemu_chr_fe_accept_input(&s->chr);
492
            }
493 494 495 496 497 498 499 500 501 502 503
        }
        break;
    case 1:
        if (s->lcr & UART_LCR_DLAB) {
            ret = (s->divider >> 8) & 0xff;
        } else {
            ret = s->ier;
        }
        break;
    case 2:
        ret = s->iir;
504
        if ((ret & UART_IIR_ID) == UART_IIR_THRI) {
505
            s->thr_ipending = 0;
506 507
            serial_update_irq(s);
        }
508 509 510 511 512 513 514 515 516
        break;
    case 3:
        ret = s->lcr;
        break;
    case 4:
        ret = s->mcr;
        break;
    case 5:
        ret = s->lsr;
517 518 519
        /* Clear break and overrun interrupts */
        if (s->lsr & (UART_LSR_BI|UART_LSR_OE)) {
            s->lsr &= ~(UART_LSR_BI|UART_LSR_OE);
520 521
            serial_update_irq(s);
        }
522 523 524 525 526 527 528 529 530
        break;
    case 6:
        if (s->mcr & UART_MCR_LOOP) {
            /* in loopback, the modem output pins are connected to the
               inputs */
            ret = (s->mcr & 0x0c) << 4;
            ret |= (s->mcr & 0x02) << 3;
            ret |= (s->mcr & 0x01) << 5;
        } else {
531 532
            if (s->poll_msl >= 0)
                serial_update_msl(s);
533
            ret = s->msr;
534 535 536 537 538
            /* Clear delta bits & msr int after read, if they were set */
            if (s->msr & UART_MSR_ANY_DELTA) {
                s->msr &= 0xF0;
                serial_update_irq(s);
            }
539 540 541 542 543 544
        }
        break;
    case 7:
        ret = s->scr;
        break;
    }
545
    DPRINTF("read addr=0x%" HWADDR_PRIx " val=0x%02x\n", addr, ret);
546 547 548
    return ret;
}

bellard's avatar
bellard committed
549
static int serial_can_receive(SerialState *s)
550
{
551
    if(s->fcr & UART_FCR_FE) {
552
        if (s->recv_fifo.num < UART_FIFO_LENGTH) {
553 554 555 556 557 558 559
            /*
             * Advertise (fifo.itl - fifo.count) bytes when count < ITL, and 1
             * if above. If UART_FIFO_LENGTH - fifo.count is advertised the
             * effect will be to almost always fill the fifo completely before
             * the guest has a chance to respond, effectively overriding the ITL
             * that the guest has set.
             */
560 561
            return (s->recv_fifo.num <= s->recv_fifo_itl) ?
                        s->recv_fifo_itl - s->recv_fifo.num : 1;
562 563 564
        } else {
            return 0;
        }
565
    } else {
566
        return !(s->lsr & UART_LSR_DR);
567
    }
568 569
}

bellard's avatar
bellard committed
570
static void serial_receive_break(SerialState *s)
571 572
{
    s->rbr = 0;
573
    /* When the LSR_DR is set a null byte is pushed into the fifo */
574
    recv_fifo_put(s, '\0');
575
    s->lsr |= UART_LSR_BI | UART_LSR_DR;
bellard's avatar
bellard committed
576
    serial_update_irq(s);
577 578
}

579 580 581
/* There's data in recv_fifo and s->rbr has not been read for 4 char transmit times */
static void fifo_timeout_int (void *opaque) {
    SerialState *s = opaque;
582
    if (s->recv_fifo.num) {
583 584 585 586 587
        s->timeout_ipending = 1;
        serial_update_irq(s);
    }
}

bellard's avatar
bellard committed
588
static int serial_can_receive1(void *opaque)
589
{
bellard's avatar
bellard committed
590 591 592 593 594 595 596
    SerialState *s = opaque;
    return serial_can_receive(s);
}

static void serial_receive1(void *opaque, const uint8_t *buf, int size)
{
    SerialState *s = opaque;
597 598 599 600

    if (s->wakeup) {
        qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
    }
601 602 603
    if(s->fcr & UART_FCR_FE) {
        int i;
        for (i = 0; i < size; i++) {
604
            recv_fifo_put(s, buf[i]);
605 606 607
        }
        s->lsr |= UART_LSR_DR;
        /* call the timeout receive callback in 4 char transmit time */
608
        timer_mod(s->fifo_timeout_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time * 4);
609
    } else {
610 611
        if (s->lsr & UART_LSR_DR)
            s->lsr |= UART_LSR_OE;
612 613 614 615
        s->rbr = buf[0];
        s->lsr |= UART_LSR_DR;
    }
    serial_update_irq(s);
bellard's avatar
bellard committed
616
}
617

bellard's avatar
bellard committed
618 619 620
static void serial_event(void *opaque, int event)
{
    SerialState *s = opaque;
621
    DPRINTF("event %x\n", event);
bellard's avatar
bellard committed
622 623 624 625
    if (event == CHR_EVENT_BREAK)
        serial_receive_break(s);
}

626
static void serial_pre_save(void *opaque)
627
{
628
    SerialState *s = opaque;
629
    s->fcr_vmstate = s->fcr;
630 631
}

632 633 634 635 636 637 638 639
static int serial_pre_load(void *opaque)
{
    SerialState *s = opaque;
    s->thr_ipending = -1;
    s->poll_msl = -1;
    return 0;
}

640
static int serial_post_load(void *opaque, int version_id)
641 642
{
    SerialState *s = opaque;
643

644 645 646
    if (version_id < 3) {
        s->fcr_vmstate = 0;
    }
647 648 649
    if (s->thr_ipending == -1) {
        s->thr_ipending = ((s->iir & UART_IIR_ID) == UART_IIR_THRI);
    }
650 651 652 653 654 655 656 657 658 659 660 661 662 663

    if (s->tsr_retry > 0) {
        /* tsr_retry > 0 implies LSR.TEMT = 0 (transmitter not empty).  */
        if (s->lsr & UART_LSR_TEMT) {
            error_report("inconsistent state in serial device "
                         "(tsr empty, tsr_retry=%d", s->tsr_retry);
            return -1;
        }

        if (s->tsr_retry > MAX_XMIT_RETRY) {
            s->tsr_retry = MAX_XMIT_RETRY;
        }

        assert(s->watch_tag == 0);
664
        s->watch_tag = qemu_chr_fe_add_watch(&s->chr, G_IO_OUT | G_IO_HUP,
665 666 667 668 669 670 671 672
                                             serial_watch_cb, s);
    } else {
        /* tsr_retry == 0 implies LSR.TEMT = 1 (transmitter empty).  */
        if (!(s->lsr & UART_LSR_TEMT)) {
            error_report("inconsistent state in serial device "
                         "(tsr not empty, tsr_retry=0");
            return -1;
        }
673 674
    }

675
    s->last_break_enable = (s->lcr >> 6) & 1;
676
    /* Initialize fcr via setter to perform essential side-effects */
677
    serial_write_fcr(s, s->fcr_vmstate);
678
    serial_update_parameters(s);
679 680 681
    return 0;
}

682 683 684
static bool serial_thr_ipending_needed(void *opaque)
{
    SerialState *s = opaque;
685 686 687 688 689 690 691 692 693 694 695

    if (s->ier & UART_IER_THRI) {
        bool expected_value = ((s->iir & UART_IIR_ID) == UART_IIR_THRI);
        return s->thr_ipending != expected_value;
    } else {
        /* LSR.THRE will be sampled again when the interrupt is
         * enabled.  thr_ipending is not used in this case, do
         * not migrate it.
         */
        return false;
    }
696 697
}

698
static const VMStateDescription vmstate_serial_thr_ipending = {
699 700 701
    .name = "serial/thr_ipending",
    .version_id = 1,
    .minimum_version_id = 1,
702
    .needed = serial_thr_ipending_needed,
703 704 705 706 707 708 709 710 711 712 713 714
    .fields = (VMStateField[]) {
        VMSTATE_INT32(thr_ipending, SerialState),
        VMSTATE_END_OF_LIST()
    }
};

static bool serial_tsr_needed(void *opaque)
{
    SerialState *s = (SerialState *)opaque;
    return s->tsr_retry != 0;
}

715
static const VMStateDescription vmstate_serial_tsr = {
716 717 718
    .name = "serial/tsr",
    .version_id = 1,
    .minimum_version_id = 1,
719
    .needed = serial_tsr_needed,
720
    .fields = (VMStateField[]) {
721
        VMSTATE_UINT32(tsr_retry, SerialState),
722 723 724 725 726 727 728 729 730 731 732 733 734
        VMSTATE_UINT8(thr, SerialState),
        VMSTATE_UINT8(tsr, SerialState),
        VMSTATE_END_OF_LIST()
    }
};

static bool serial_recv_fifo_needed(void *opaque)
{
    SerialState *s = (SerialState *)opaque;
    return !fifo8_is_empty(&s->recv_fifo);

}

735
static const VMStateDescription vmstate_serial_recv_fifo = {
736 737 738
    .name = "serial/recv_fifo",
    .version_id = 1,
    .minimum_version_id = 1,
739
    .needed = serial_recv_fifo_needed,
740 741 742 743 744 745 746 747 748 749 750 751
    .fields = (VMStateField[]) {
        VMSTATE_STRUCT(recv_fifo, SerialState, 1, vmstate_fifo8, Fifo8),
        VMSTATE_END_OF_LIST()
    }
};

static bool serial_xmit_fifo_needed(void *opaque)
{
    SerialState *s = (SerialState *)opaque;
    return !fifo8_is_empty(&s->xmit_fifo);
}

752
static const VMStateDescription vmstate_serial_xmit_fifo = {
753 754 755
    .name = "serial/xmit_fifo",
    .version_id = 1,
    .minimum_version_id = 1,
756
    .needed = serial_xmit_fifo_needed,
757 758 759 760 761 762 763 764 765 766 767 768
    .fields = (VMStateField[]) {
        VMSTATE_STRUCT(xmit_fifo, SerialState, 1, vmstate_fifo8, Fifo8),
        VMSTATE_END_OF_LIST()
    }
};

static bool serial_fifo_timeout_timer_needed(void *opaque)
{
    SerialState *s = (SerialState *)opaque;
    return timer_pending(s->fifo_timeout_timer);
}

769
static const VMStateDescription vmstate_serial_fifo_timeout_timer = {
770 771 772
    .name = "serial/fifo_timeout_timer",
    .version_id = 1,
    .minimum_version_id = 1,
773
    .needed = serial_fifo_timeout_timer_needed,
774
    .fields = (VMStateField[]) {
775
        VMSTATE_TIMER_PTR(fifo_timeout_timer, SerialState),
776 777 778 779 780 781 782 783 784 785
        VMSTATE_END_OF_LIST()
    }
};

static bool serial_timeout_ipending_needed(void *opaque)
{
    SerialState *s = (SerialState *)opaque;
    return s->timeout_ipending != 0;
}

786
static const VMStateDescription vmstate_serial_timeout_ipending = {
787 788 789
    .name = "serial/timeout_ipending",
    .version_id = 1,
    .minimum_version_id = 1,
790
    .needed = serial_timeout_ipending_needed,
791 792 793 794 795 796 797 798 799 800 801 802
    .fields = (VMStateField[]) {
        VMSTATE_INT32(timeout_ipending, SerialState),
        VMSTATE_END_OF_LIST()
    }
};

static bool serial_poll_needed(void *opaque)
{
    SerialState *s = (SerialState *)opaque;
    return s->poll_msl >= 0;
}

803
static const VMStateDescription vmstate_serial_poll = {
804 805
    .name = "serial/poll",
    .version_id = 1,
806
    .needed = serial_poll_needed,
807 808 809
    .minimum_version_id = 1,
    .fields = (VMStateField[]) {
        VMSTATE_INT32(poll_msl, SerialState),
810
        VMSTATE_TIMER_PTR(modem_status_poll, SerialState),
811 812 813 814
        VMSTATE_END_OF_LIST()
    }
};

Gerd Hoffmann's avatar
Gerd Hoffmann committed
815
const VMStateDescription vmstate_serial = {
816 817 818 819
    .name = "serial",
    .version_id = 3,
    .minimum_version_id = 2,
    .pre_save = serial_pre_save,
820
    .pre_load = serial_pre_load,
821
    .post_load = serial_post_load,
822
    .fields = (VMStateField[]) {
823 824 825 826 827 828 829 830 831 832 833
        VMSTATE_UINT16_V(divider, SerialState, 2),
        VMSTATE_UINT8(rbr, SerialState),
        VMSTATE_UINT8(ier, SerialState),
        VMSTATE_UINT8(iir, SerialState),
        VMSTATE_UINT8(lcr, SerialState),
        VMSTATE_UINT8(mcr, SerialState),
        VMSTATE_UINT8(lsr, SerialState),
        VMSTATE_UINT8(msr, SerialState),
        VMSTATE_UINT8(scr, SerialState),
        VMSTATE_UINT8_V(fcr_vmstate, SerialState, 3),
        VMSTATE_END_OF_LIST()
834
    },
835 836 837 838 839 840 841 842 843
    .subsections = (const VMStateDescription*[]) {
        &vmstate_serial_thr_ipending,
        &vmstate_serial_tsr,
        &vmstate_serial_recv_fifo,
        &vmstate_serial_xmit_fifo,
        &vmstate_serial_fifo_timeout_timer,
        &vmstate_serial_timeout_ipending,
        &vmstate_serial_poll,
        NULL
844 845 846
    }
};

847 848 849 850
static void serial_reset(void *opaque)
{
    SerialState *s = opaque;

851 852 853 854 855
    if (s->watch_tag > 0) {
        g_source_remove(s->watch_tag);
        s->watch_tag = 0;
    }

856 857 858 859 860 861
    s->rbr = 0;
    s->ier = 0;
    s->iir = UART_IIR_NO_INT;
    s->lcr = 0;
    s->lsr = UART_LSR_TEMT | UART_LSR_THRE;
    s->msr = UART_MSR_DCD | UART_MSR_DSR | UART_MSR_CTS;
Stefan Weil's avatar
Stefan Weil committed
862
    /* Default to 9600 baud, 1 start bit, 8 data bits, 1 stop bit, no parity. */
863 864
    s->divider = 0x0C;
    s->mcr = UART_MCR_OUT2;
865
    s->scr = 0;
866
    s->tsr_retry = 0;
867
    s->char_transmit_time = (NANOSECONDS_PER_SECOND / 9600) * 10;
868 869
    s->poll_msl = 0;

870 871 872 873
    s->timeout_ipending = 0;
    timer_del(s->fifo_timeout_timer);
    timer_del(s->modem_status_poll);

874 875
    fifo8_reset(&s->recv_fifo);
    fifo8_reset(&s->xmit_fifo);
876

877
    s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
878 879 880 881

    s->thr_ipending = 0;
    s->last_break_enable = 0;
    qemu_irq_lower(s->irq);
882 883 884

    serial_update_msl(s);
    s->msr &= ~UART_MSR_ANY_DELTA;
885 886
}

887
void serial_realize_core(SerialState *s, Error **errp)
888
{
889
    if (!qemu_chr_fe_get_driver(&s->chr)) {
890 891
        error_setg(errp, "Can't create serial device, empty char device");
        return;
892 893
    }

894
    s->modem_status_poll = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) serial_update_msl, s);
895

896
    s->fifo_timeout_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) fifo_timeout_int, s);
897
    qemu_register_reset(serial_reset, s);
898

899
    qemu_chr_fe_set_handlers(&s->chr, serial_can_receive1, serial_receive1,
900
                             serial_event, s, NULL, true);
901 902
    fifo8_create(&s->recv_fifo, UART_FIFO_LENGTH);
    fifo8_create(&s->xmit_fifo, UART_FIFO_LENGTH);
903
    serial_reset(s);
904 905
}

Gerd Hoffmann's avatar
Gerd Hoffmann committed
906 907
void serial_exit_core(SerialState *s)
{
908
    qemu_chr_fe_deinit(&s->chr, false);
909 910 911 912 913 914 915 916 917 918

    timer_del(s->modem_status_poll);
    timer_free(s->modem_status_poll);

    timer_del(s->fifo_timeout_timer);
    timer_free(s->fifo_timeout_timer);

    fifo8_destroy(&s->recv_fifo);
    fifo8_destroy(&s->xmit_fifo);

Gerd Hoffmann's avatar
Gerd Hoffmann committed
919 920 921
    qemu_unregister_reset(serial_reset, s);
}

922 923 924 925 926 927 928
/* Change the main reference oscillator frequency. */
void serial_set_frequency(SerialState *s, uint32_t frequency)
{
    s->baudbase = frequency;
    serial_update_parameters(s);
}

Gerd Hoffmann's avatar
Gerd Hoffmann committed
929
const MemoryRegionOps serial_io_ops = {
930 931 932 933 934 935 936
    .read = serial_ioport_read,
    .write = serial_ioport_write,
    .impl = {
        .min_access_size = 1,
        .max_access_size = 1,
    },
    .endianness = DEVICE_LITTLE_ENDIAN,
937 938
};

aurel32's avatar
aurel32 committed
939
SerialState *serial_init(int base, qemu_irq irq, int baudbase,
940
                         Chardev *chr, MemoryRegion *system_io)
bellard's avatar
bellard committed
941 942 943
{
    SerialState *s;

944
    s = g_malloc0(sizeof(SerialState));
945

946 947
    s->irq = irq;
    s->baudbase = baudbase;
948
    qemu_chr_fe_init(&s->chr, chr, &error_abort);
949
    serial_realize_core(s, &error_fatal);
bellard's avatar
bellard committed
950

951
    vmstate_register(NULL, base, &vmstate_serial, s);
952

953
    memory_region_init_io(&s->io, NULL, &serial_io_ops, s, "serial", 8);
954
    memory_region_add_subregion(system_io, base, &s->io);
955

bellard's avatar
bellard committed
956
    return s;
957
}
958 959

/* Memory mapped interface */
960
static uint64_t serial_mm_read(void *opaque, hwaddr addr,
961
                               unsigned size)
962 963
{
    SerialState *s = opaque;
964
    return serial_ioport_read(s, addr >> s->it_shift, 1);
965 966
}

967
static void serial_mm_write(void *opaque, hwaddr addr,
968
                            uint64_t value, unsigned size)
Blue Swirl's avatar
Blue Swirl committed
969 970
{
    SerialState *s = opaque;
971
    value &= ~0u >> (32 - (size * 8));
972
    serial_ioport_write(s, addr >> s->it_shift, value, 1);
Blue Swirl's avatar
Blue Swirl committed
973 974
}

975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
static const MemoryRegionOps serial_mm_ops[3] = {
    [DEVICE_NATIVE_ENDIAN] = {
        .read = serial_mm_read,
        .write = serial_mm_write,
        .endianness = DEVICE_NATIVE_ENDIAN,
    },
    [DEVICE_LITTLE_ENDIAN] = {
        .read = serial_mm_read,
        .write = serial_mm_write,
        .endianness = DEVICE_LITTLE_ENDIAN,
    },
    [DEVICE_BIG_ENDIAN] = {
        .read = serial_mm_read,
        .write = serial_mm_write,
        .endianness = DEVICE_BIG_ENDIAN,
    },
991 992
};

993
SerialState *serial_mm_init(MemoryRegion *address_space,
994
                            hwaddr base, int it_shift,
995
                            qemu_irq irq, int baudbase,
996
                            Chardev *chr, enum device_endian end)
997 998 999
{
    SerialState *s;

1000
    s = g_malloc0(sizeof(SerialState));
1001

1002
    s->it_shift = it_shift;
1003 1004
    s->irq = irq;
    s->baudbase = baudbase;
1005
    qemu_chr_fe_init(&s->chr, chr, &error_abort);
1006

1007
    serial_realize_core(s, &error_fatal);
1008
    vmstate_register(NULL, base, &vmstate_serial, s);
1009

1010
    memory_region_init_io(&s->io, NULL, &serial_mm_ops[end], s,
1011
                          "serial", 8 << it_shift);
1012
    memory_region_add_subregion(address_space, base, &s->io);
1013 1014
    return s;
}