serial.c 31.7 KB
Newer Older
B
bellard 已提交
1
/*
2
 * QEMU 16550A UART emulation
3
 *
B
bellard 已提交
4
 * Copyright (c) 2003-2004 Fabrice Bellard
5
 * Copyright (c) 2008 Citrix Systems, Inc.
6
 *
B
bellard 已提交
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.
 */
G
Gerd Hoffmann 已提交
25

P
Peter Maydell 已提交
26
#include "qemu/osdep.h"
P
Paolo Bonzini 已提交
27
#include "hw/char/serial.h"
28
#include "chardev/char-serial.h"
29
#include "qapi/error.h"
30
#include "qemu/timer.h"
31
#include "qemu/error-report.h"
32
#include "trace.h"
B
bellard 已提交
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 */
B
bellard 已提交
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 */
B
bellard 已提交
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)
B
bellard 已提交
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
}
A
aurel32 已提交
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);
A
aurel32 已提交
148 149 150
    }
}

B
bellard 已提交
151 152
static void serial_update_parameters(SerialState *s)
{
153 154
    float speed;
    int parity, data_bits, stop_bits, frame_size;
B
bellard 已提交
155
    QEMUSerialSetParams ssp;
B
bellard 已提交
156

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

B
bellard 已提交
175
    data_bits = (s->lcr & 0x03) + 5;
176
    frame_size += data_bits + stop_bits;
177 178
    /* Zero divisor should give about 3500 baud */
    speed = (s->divider == 0) ? 3500 : (float) s->baudbase / s->divider;
B
bellard 已提交
179 180 181 182
    ssp.speed = speed;
    ssp.parity = parity;
    ssp.data_bits = data_bits;
    ssp.stop_bits = stop_bits;
183
    s->char_transmit_time =  (NANOSECONDS_PER_SECOND / speed) * frame_size;
184
    qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_SET_PARAMS, &ssp);
185

186
    DPRINTF("speed=%.2f parity=%c data=%d stop=%d\n",
B
bellard 已提交
187 188 189
           speed, parity, data_bits, stop_bits);
}

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

195
    timer_del(s->modem_status_poll);
196

197
    if (qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_GET_TIOCM,
198
                          &flags) == -ENOTSUP) {
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
        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 */

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

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

237 238
static void serial_xmit(SerialState *s)
{
239
    do {
240
        assert(!(s->lsr & UART_LSR_TEMT));
P
Paolo Bonzini 已提交
241
        if (s->tsr_retry == 0) {
242 243
            assert(!(s->lsr & UART_LSR_THRE));

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

260 261 262
        if (s->mcr & UART_MCR_LOOP) {
            /* in loopback mode, say that we just received a char */
            serial_receive1(s, &s->tsr, 1);
263 264 265 266 267 268 269 270 271 272 273 274 275 276
        } else {
            int rc = qemu_chr_fe_write(&s->chr, &s->tsr, 1);

            if ((rc == 0 ||
                 (rc == -1 && errno == EAGAIN)) &&
                s->tsr_retry < MAX_XMIT_RETRY) {
                assert(s->watch_tag == 0);
                s->watch_tag =
                    qemu_chr_fe_add_watch(&s->chr, G_IO_OUT | G_IO_HUP,
                                          serial_watch_cb, s);
                if (s->watch_tag > 0) {
                    s->tsr_retry++;
                    return;
                }
277
            }
278
        }
P
Paolo Bonzini 已提交
279
        s->tsr_retry = 0;
280

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

285
    s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
286
    s->lsr |= UART_LSR_TEMT;
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 315 316 317 318
/* 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;
    }
}

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
static void serial_update_tiocm(SerialState *s)
{
    int flags;

    qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_GET_TIOCM, &flags);

    flags &= ~(CHR_TIOCM_RTS | CHR_TIOCM_DTR);

    if (s->mcr & UART_MCR_RTS) {
        flags |= CHR_TIOCM_RTS;
    }
    if (s->mcr & UART_MCR_DTR) {
        flags |= CHR_TIOCM_DTR;
    }

    qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_SET_TIOCM, &flags);
}

337 338
static void serial_ioport_write(void *opaque, hwaddr addr, uint64_t val,
                                unsigned size)
B
bellard 已提交
339
{
B
bellard 已提交
340
    SerialState *s = opaque;
341

B
bellard 已提交
342
    addr &= 7;
343
    trace_serial_ioport_write(addr, val);
B
bellard 已提交
344 345 346 347
    switch(addr) {
    default:
    case 0:
        if (s->lcr & UART_LCR_DLAB) {
P
Paolo Bonzini 已提交
348
            if (size == 1) {
349
                s->divider = (s->divider & 0xff00) | val;
P
Paolo Bonzini 已提交
350
            } else {
351 352
                s->divider = val;
            }
B
bellard 已提交
353
            serial_update_parameters(s);
B
bellard 已提交
354
        } else {
355 356
            s->thr = (uint8_t) val;
            if(s->fcr & UART_FCR_FE) {
357 358 359 360 361
                /* 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);
A
aurel32 已提交
362
            }
363 364
            s->thr_ipending = 0;
            s->lsr &= ~UART_LSR_THRE;
365
            s->lsr &= ~UART_LSR_TEMT;
366
            serial_update_irq(s);
P
Paolo Bonzini 已提交
367
            if (s->tsr_retry == 0) {
368
                serial_xmit(s);
369
            }
B
bellard 已提交
370 371 372 373 374
        }
        break;
    case 1:
        if (s->lcr & UART_LCR_DLAB) {
            s->divider = (s->divider & 0x00ff) | (val << 8);
B
bellard 已提交
375
            serial_update_parameters(s);
B
bellard 已提交
376
        } else {
377
            uint8_t changed = (s->ier ^ val) & 0x0f;
B
bellard 已提交
378
            s->ier = val & 0x0f;
379
            /* If the backend device is a real serial port, turn polling of the modem
380 381 382
             * status lines on physical port on or off depending on UART_IER_MSI state.
             */
            if ((changed & UART_IER_MSI) && s->poll_msl >= 0) {
383 384 385 386
                if (s->ier & UART_IER_MSI) {
                     s->poll_msl = 1;
                     serial_update_msl(s);
                } else {
387
                     timer_del(s->modem_status_poll);
388 389 390
                     s->poll_msl = 0;
                }
            }
391 392 393 394 395 396

            /* 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
397 398
             * always toggles IER to all zeroes and back to all ones, so do the
             * same.
399 400 401 402
             *
             * If IER.THRI is zero, thr_ipending is not used.  Set it to zero
             * so that the thr_ipending subsection is not migrated.
             */
403 404 405 406 407 408 409 410 411 412
            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);
B
bellard 已提交
413
            }
B
bellard 已提交
414 415 416
        }
        break;
    case 2:
417
        /* Did the enable/disable flag change? If so, make sure FIFOs get flushed */
418
        if ((val ^ s->fcr) & UART_FCR_FE) {
419
            val |= UART_FCR_XFR | UART_FCR_RFR;
420
        }
421 422 423 424

        /* FIFO clear */

        if (val & UART_FCR_RFR) {
425
            s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
426
            timer_del(s->fifo_timeout_timer);
427
            s->timeout_ipending = 0;
428
            fifo8_reset(&s->recv_fifo);
429 430 431
        }

        if (val & UART_FCR_XFR) {
432 433
            s->lsr |= UART_LSR_THRE;
            s->thr_ipending = 1;
434
            fifo8_reset(&s->xmit_fifo);
435 436
        }

437
        serial_write_fcr(s, val & 0xC9);
438
        serial_update_irq(s);
B
bellard 已提交
439 440
        break;
    case 3:
B
bellard 已提交
441 442 443 444 445 446 447
        {
            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;
448 449
                qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_SET_BREAK,
                                  &break_enable);
B
bellard 已提交
450 451
            }
        }
B
bellard 已提交
452 453
        break;
    case 4:
454 455 456 457 458 459 460
        {
            int old_mcr = s->mcr;
            s->mcr = val & 0x1f;
            if (val & UART_MCR_LOOP)
                break;

            if (s->poll_msl >= 0 && old_mcr != s->mcr) {
461
                serial_update_tiocm(s);
462 463
                /* 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 */
464
                timer_mod(s->modem_status_poll, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time);
465 466
            }
        }
B
bellard 已提交
467 468 469 470 471 472 473 474 475 476 477
        break;
    case 5:
        break;
    case 6:
        break;
    case 7:
        s->scr = val;
        break;
    }
}

478
static uint64_t serial_ioport_read(void *opaque, hwaddr addr, unsigned size)
B
bellard 已提交
479
{
B
bellard 已提交
480
    SerialState *s = opaque;
B
bellard 已提交
481 482 483 484 485 486 487
    uint32_t ret;

    addr &= 7;
    switch(addr) {
    default:
    case 0:
        if (s->lcr & UART_LCR_DLAB) {
488
            ret = s->divider & 0xff;
B
bellard 已提交
489
        } else {
490
            if(s->fcr & UART_FCR_FE) {
491
                ret = fifo8_is_empty(&s->recv_fifo) ?
492 493
                            0 : fifo8_pop(&s->recv_fifo);
                if (s->recv_fifo.num == 0) {
494
                    s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
P
Peter Crosthwaite 已提交
495
                } else {
496
                    timer_mod(s->fifo_timeout_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time * 4);
P
Peter Crosthwaite 已提交
497
                }
498 499 500 501 502
                s->timeout_ipending = 0;
            } else {
                ret = s->rbr;
                s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
            }
B
bellard 已提交
503
            serial_update_irq(s);
504 505
            if (!(s->mcr & UART_MCR_LOOP)) {
                /* in loopback mode, don't receive any data */
506
                qemu_chr_fe_accept_input(&s->chr);
507
            }
B
bellard 已提交
508 509 510 511 512 513 514 515 516 517 518
        }
        break;
    case 1:
        if (s->lcr & UART_LCR_DLAB) {
            ret = (s->divider >> 8) & 0xff;
        } else {
            ret = s->ier;
        }
        break;
    case 2:
        ret = s->iir;
519
        if ((ret & UART_IIR_ID) == UART_IIR_THRI) {
B
bellard 已提交
520
            s->thr_ipending = 0;
521 522
            serial_update_irq(s);
        }
B
bellard 已提交
523 524 525 526 527 528 529 530 531
        break;
    case 3:
        ret = s->lcr;
        break;
    case 4:
        ret = s->mcr;
        break;
    case 5:
        ret = s->lsr;
532 533 534
        /* Clear break and overrun interrupts */
        if (s->lsr & (UART_LSR_BI|UART_LSR_OE)) {
            s->lsr &= ~(UART_LSR_BI|UART_LSR_OE);
535 536
            serial_update_irq(s);
        }
B
bellard 已提交
537 538 539 540 541 542 543 544 545
        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 {
546 547
            if (s->poll_msl >= 0)
                serial_update_msl(s);
B
bellard 已提交
548
            ret = s->msr;
549 550 551 552 553
            /* 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);
            }
B
bellard 已提交
554 555 556 557 558 559
        }
        break;
    case 7:
        ret = s->scr;
        break;
    }
560
    trace_serial_ioport_read(addr, ret);
B
bellard 已提交
561 562 563
    return ret;
}

B
bellard 已提交
564
static int serial_can_receive(SerialState *s)
B
bellard 已提交
565
{
566
    if(s->fcr & UART_FCR_FE) {
567
        if (s->recv_fifo.num < UART_FIFO_LENGTH) {
P
Peter Crosthwaite 已提交
568 569 570 571 572 573 574
            /*
             * 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.
             */
575 576
            return (s->recv_fifo.num <= s->recv_fifo_itl) ?
                        s->recv_fifo_itl - s->recv_fifo.num : 1;
P
Peter Crosthwaite 已提交
577 578 579
        } else {
            return 0;
        }
580
    } else {
P
Peter Crosthwaite 已提交
581
        return !(s->lsr & UART_LSR_DR);
582
    }
B
bellard 已提交
583 584
}

B
bellard 已提交
585
static void serial_receive_break(SerialState *s)
B
bellard 已提交
586 587
{
    s->rbr = 0;
588
    /* When the LSR_DR is set a null byte is pushed into the fifo */
589
    recv_fifo_put(s, '\0');
B
bellard 已提交
590
    s->lsr |= UART_LSR_BI | UART_LSR_DR;
B
bellard 已提交
591
    serial_update_irq(s);
B
bellard 已提交
592 593
}

594 595 596
/* 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;
597
    if (s->recv_fifo.num) {
598 599 600 601 602
        s->timeout_ipending = 1;
        serial_update_irq(s);
    }
}

B
bellard 已提交
603
static int serial_can_receive1(void *opaque)
B
bellard 已提交
604
{
B
bellard 已提交
605 606 607 608 609 610 611
    SerialState *s = opaque;
    return serial_can_receive(s);
}

static void serial_receive1(void *opaque, const uint8_t *buf, int size)
{
    SerialState *s = opaque;
612 613

    if (s->wakeup) {
614
        qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
615
    }
616 617 618
    if(s->fcr & UART_FCR_FE) {
        int i;
        for (i = 0; i < size; i++) {
619
            recv_fifo_put(s, buf[i]);
620 621 622
        }
        s->lsr |= UART_LSR_DR;
        /* call the timeout receive callback in 4 char transmit time */
623
        timer_mod(s->fifo_timeout_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time * 4);
624
    } else {
625 626
        if (s->lsr & UART_LSR_DR)
            s->lsr |= UART_LSR_OE;
627 628 629 630
        s->rbr = buf[0];
        s->lsr |= UART_LSR_DR;
    }
    serial_update_irq(s);
B
bellard 已提交
631
}
B
bellard 已提交
632

B
bellard 已提交
633 634 635
static void serial_event(void *opaque, int event)
{
    SerialState *s = opaque;
636
    DPRINTF("event %x\n", event);
B
bellard 已提交
637 638 639 640
    if (event == CHR_EVENT_BREAK)
        serial_receive_break(s);
}

641
static int serial_pre_save(void *opaque)
642
{
643
    SerialState *s = opaque;
J
Juan Quintela 已提交
644
    s->fcr_vmstate = s->fcr;
645 646

    return 0;
647 648
}

649 650 651 652 653 654 655 656
static int serial_pre_load(void *opaque)
{
    SerialState *s = opaque;
    s->thr_ipending = -1;
    s->poll_msl = -1;
    return 0;
}

657
static int serial_post_load(void *opaque, int version_id)
J
Juan Quintela 已提交
658 659
{
    SerialState *s = opaque;
660

661 662 663
    if (version_id < 3) {
        s->fcr_vmstate = 0;
    }
664 665 666
    if (s->thr_ipending == -1) {
        s->thr_ipending = ((s->iir & UART_IIR_ID) == UART_IIR_THRI);
    }
667 668 669 670 671 672 673 674 675 676 677 678 679 680

    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);
681
        s->watch_tag = qemu_chr_fe_add_watch(&s->chr, G_IO_OUT | G_IO_HUP,
682 683 684 685 686 687 688 689
                                             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;
        }
P
Paolo Bonzini 已提交
690 691
    }

692
    s->last_break_enable = (s->lcr >> 6) & 1;
693
    /* Initialize fcr via setter to perform essential side-effects */
694
    serial_write_fcr(s, s->fcr_vmstate);
695
    serial_update_parameters(s);
696 697 698
    return 0;
}

699 700 701
static bool serial_thr_ipending_needed(void *opaque)
{
    SerialState *s = opaque;
702 703 704 705 706 707 708 709 710 711 712

    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;
    }
713 714
}

715
static const VMStateDescription vmstate_serial_thr_ipending = {
716 717 718
    .name = "serial/thr_ipending",
    .version_id = 1,
    .minimum_version_id = 1,
719
    .needed = serial_thr_ipending_needed,
720 721 722 723 724 725 726 727 728 729 730 731
    .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;
}

732
static const VMStateDescription vmstate_serial_tsr = {
733 734 735
    .name = "serial/tsr",
    .version_id = 1,
    .minimum_version_id = 1,
736
    .needed = serial_tsr_needed,
737
    .fields = (VMStateField[]) {
P
Paolo Bonzini 已提交
738
        VMSTATE_UINT32(tsr_retry, SerialState),
739 740 741 742 743 744 745 746 747 748 749 750 751
        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);

}

752
static const VMStateDescription vmstate_serial_recv_fifo = {
753 754 755
    .name = "serial/recv_fifo",
    .version_id = 1,
    .minimum_version_id = 1,
756
    .needed = serial_recv_fifo_needed,
757 758 759 760 761 762 763 764 765 766 767 768
    .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);
}

769
static const VMStateDescription vmstate_serial_xmit_fifo = {
770 771 772
    .name = "serial/xmit_fifo",
    .version_id = 1,
    .minimum_version_id = 1,
773
    .needed = serial_xmit_fifo_needed,
774 775 776 777 778 779 780 781 782 783 784 785
    .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);
}

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

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

803
static const VMStateDescription vmstate_serial_timeout_ipending = {
804 805 806
    .name = "serial/timeout_ipending",
    .version_id = 1,
    .minimum_version_id = 1,
807
    .needed = serial_timeout_ipending_needed,
808 809 810 811 812 813 814 815 816 817 818 819
    .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;
}

820
static const VMStateDescription vmstate_serial_poll = {
821 822
    .name = "serial/poll",
    .version_id = 1,
823
    .needed = serial_poll_needed,
824 825 826
    .minimum_version_id = 1,
    .fields = (VMStateField[]) {
        VMSTATE_INT32(poll_msl, SerialState),
827
        VMSTATE_TIMER_PTR(modem_status_poll, SerialState),
828 829 830 831
        VMSTATE_END_OF_LIST()
    }
};

G
Gerd Hoffmann 已提交
832
const VMStateDescription vmstate_serial = {
J
Juan Quintela 已提交
833 834 835 836
    .name = "serial",
    .version_id = 3,
    .minimum_version_id = 2,
    .pre_save = serial_pre_save,
837
    .pre_load = serial_pre_load,
J
Juan Quintela 已提交
838
    .post_load = serial_post_load,
839
    .fields = (VMStateField[]) {
J
Juan Quintela 已提交
840 841 842 843 844 845 846 847 848 849 850
        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()
851
    },
852 853 854 855 856 857 858 859 860
    .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
J
Juan Quintela 已提交
861 862 863
    }
};

864 865 866 867
static void serial_reset(void *opaque)
{
    SerialState *s = opaque;

P
Paolo Bonzini 已提交
868 869 870 871 872
    if (s->watch_tag > 0) {
        g_source_remove(s->watch_tag);
        s->watch_tag = 0;
    }

873 874 875 876 877 878
    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;
S
Stefan Weil 已提交
879
    /* Default to 9600 baud, 1 start bit, 8 data bits, 1 stop bit, no parity. */
880 881
    s->divider = 0x0C;
    s->mcr = UART_MCR_OUT2;
882
    s->scr = 0;
883
    s->tsr_retry = 0;
884
    s->char_transmit_time = (NANOSECONDS_PER_SECOND / 9600) * 10;
885 886
    s->poll_msl = 0;

887 888 889 890
    s->timeout_ipending = 0;
    timer_del(s->fifo_timeout_timer);
    timer_del(s->modem_status_poll);

891 892
    fifo8_reset(&s->recv_fifo);
    fifo8_reset(&s->xmit_fifo);
893

894
    s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
895 896 897 898

    s->thr_ipending = 0;
    s->last_break_enable = 0;
    qemu_irq_lower(s->irq);
899 900 901

    serial_update_msl(s);
    s->msr &= ~UART_MSR_ANY_DELTA;
902 903
}

A
Anton Nefedov 已提交
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
static int serial_be_change(void *opaque)
{
    SerialState *s = opaque;

    qemu_chr_fe_set_handlers(&s->chr, serial_can_receive1, serial_receive1,
                             serial_event, serial_be_change, s, NULL, true);

    serial_update_parameters(s);

    qemu_chr_fe_ioctl(&s->chr, CHR_IOCTL_SERIAL_SET_BREAK,
                      &s->last_break_enable);

    s->poll_msl = (s->ier & UART_IER_MSI) ? 1 : 0;
    serial_update_msl(s);

    if (s->poll_msl >= 0 && !(s->mcr & UART_MCR_LOOP)) {
        serial_update_tiocm(s);
    }

    if (s->watch_tag > 0) {
        g_source_remove(s->watch_tag);
        s->watch_tag = qemu_chr_fe_add_watch(&s->chr, G_IO_OUT | G_IO_HUP,
                                             serial_watch_cb, s);
    }

    return 0;
}

932
void serial_realize_core(SerialState *s, Error **errp)
933
{
934
    s->modem_status_poll = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) serial_update_msl, s);
935

936
    s->fifo_timeout_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) fifo_timeout_int, s);
937
    qemu_register_reset(serial_reset, s);
938

939
    qemu_chr_fe_set_handlers(&s->chr, serial_can_receive1, serial_receive1,
A
Anton Nefedov 已提交
940
                             serial_event, serial_be_change, s, NULL, true);
941 942
    fifo8_create(&s->recv_fifo, UART_FIFO_LENGTH);
    fifo8_create(&s->xmit_fifo, UART_FIFO_LENGTH);
P
Paolo Bonzini 已提交
943
    serial_reset(s);
944 945
}

G
Gerd Hoffmann 已提交
946 947
void serial_exit_core(SerialState *s)
{
948
    qemu_chr_fe_deinit(&s->chr, false);
949 950 951 952 953 954 955 956 957 958

    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);

G
Gerd Hoffmann 已提交
959 960 961
    qemu_unregister_reset(serial_reset, s);
}

962 963 964 965 966 967 968
/* Change the main reference oscillator frequency. */
void serial_set_frequency(SerialState *s, uint32_t frequency)
{
    s->baudbase = frequency;
    serial_update_parameters(s);
}

G
Gerd Hoffmann 已提交
969
const MemoryRegionOps serial_io_ops = {
970 971 972 973 974 975 976
    .read = serial_ioport_read,
    .write = serial_ioport_write,
    .impl = {
        .min_access_size = 1,
        .max_access_size = 1,
    },
    .endianness = DEVICE_LITTLE_ENDIAN,
977 978
};

A
aurel32 已提交
979
SerialState *serial_init(int base, qemu_irq irq, int baudbase,
980
                         Chardev *chr, MemoryRegion *system_io)
B
bellard 已提交
981 982 983
{
    SerialState *s;

984
    s = g_malloc0(sizeof(SerialState));
A
aurel32 已提交
985

G
Gerd Hoffmann 已提交
986 987
    s->irq = irq;
    s->baudbase = baudbase;
988
    qemu_chr_fe_init(&s->chr, chr, &error_abort);
989
    serial_realize_core(s, &error_fatal);
B
bellard 已提交
990

A
Alex Williamson 已提交
991
    vmstate_register(NULL, base, &vmstate_serial, s);
992

993
    memory_region_init_io(&s->io, NULL, &serial_io_ops, s, "serial", 8);
J
Julien Grall 已提交
994
    memory_region_add_subregion(system_io, base, &s->io);
995

B
bellard 已提交
996
    return s;
B
bellard 已提交
997
}
998 999

/* Memory mapped interface */
A
Avi Kivity 已提交
1000
static uint64_t serial_mm_read(void *opaque, hwaddr addr,
1001
                               unsigned size)
1002 1003
{
    SerialState *s = opaque;
1004
    return serial_ioport_read(s, addr >> s->it_shift, 1);
1005 1006
}

A
Avi Kivity 已提交
1007
static void serial_mm_write(void *opaque, hwaddr addr,
1008
                            uint64_t value, unsigned size)
B
Blue Swirl 已提交
1009 1010
{
    SerialState *s = opaque;
1011
    value &= 255;
1012
    serial_ioport_write(s, addr >> s->it_shift, value, 1);
B
Blue Swirl 已提交
1013 1014
}

1015 1016 1017 1018 1019
static const MemoryRegionOps serial_mm_ops[3] = {
    [DEVICE_NATIVE_ENDIAN] = {
        .read = serial_mm_read,
        .write = serial_mm_write,
        .endianness = DEVICE_NATIVE_ENDIAN,
1020 1021
        .valid.max_access_size = 8,
        .impl.max_access_size = 8,
1022 1023 1024 1025 1026
    },
    [DEVICE_LITTLE_ENDIAN] = {
        .read = serial_mm_read,
        .write = serial_mm_write,
        .endianness = DEVICE_LITTLE_ENDIAN,
1027 1028
        .valid.max_access_size = 8,
        .impl.max_access_size = 8,
1029 1030 1031 1032 1033
    },
    [DEVICE_BIG_ENDIAN] = {
        .read = serial_mm_read,
        .write = serial_mm_write,
        .endianness = DEVICE_BIG_ENDIAN,
1034 1035
        .valid.max_access_size = 8,
        .impl.max_access_size = 8,
1036
    },
1037 1038
};

1039
SerialState *serial_mm_init(MemoryRegion *address_space,
A
Avi Kivity 已提交
1040
                            hwaddr base, int it_shift,
1041
                            qemu_irq irq, int baudbase,
1042
                            Chardev *chr, enum device_endian end)
1043 1044 1045
{
    SerialState *s;

1046
    s = g_malloc0(sizeof(SerialState));
1047

1048
    s->it_shift = it_shift;
G
Gerd Hoffmann 已提交
1049 1050
    s->irq = irq;
    s->baudbase = baudbase;
1051
    qemu_chr_fe_init(&s->chr, chr, &error_abort);
1052

1053
    serial_realize_core(s, &error_fatal);
A
Alex Williamson 已提交
1054
    vmstate_register(NULL, base, &vmstate_serial, s);
1055

1056
    memory_region_init_io(&s->io, NULL, &serial_mm_ops[end], s,
1057
                          "serial", 8 << it_shift);
1058
    memory_region_add_subregion(address_space, base, &s->io);
1059 1060
    return s;
}