serial.c 28.3 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
Paolo Bonzini 已提交
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"
B
bellard 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

//#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 */
48 49 50 51
#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 已提交
52 53 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

/*
 * 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 */
82
#define UART_LSR_INT_ANY 0x1E	/* Any of the lsr-interrupt-triggering status bits */
B
bellard 已提交
83

84 85 86 87 88 89 90 91 92 93 94 95 96 97
/* 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

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

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)
B
bellard 已提交
109
{
110
    /* Receive overruns do not overwrite FIFO contents. */
111 112 113
    if (!fifo8_is_full(&s->recv_fifo)) {
        fifo8_push(&s->recv_fifo, chr);
    } else {
114
        s->lsr |= UART_LSR_OE;
115
    }
116
}
A
aurel32 已提交
117

118 119 120 121 122 123
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;
124
    } else if ((s->ier & UART_IER_RDI) && s->timeout_ipending) {
125 126 127
        /* Note that(s->ier & UART_IER_RDI) can mask this interrupt,
         * this is not in the specification but is observed on existing
         * hardware.  */
128
        tmp_iir = UART_IIR_CTI;
129 130
    } else if ((s->ier & UART_IER_RDI) && (s->lsr & UART_LSR_DR) &&
               (!(s->fcr & UART_FCR_FE) ||
131
                s->recv_fifo.num >= s->recv_fifo_itl)) {
132
        tmp_iir = UART_IIR_RDI;
133 134 135 136 137 138 139 140 141 142 143 144
    } 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 已提交
145 146 147
    }
}

B
bellard 已提交
148 149
static void serial_update_parameters(SerialState *s)
{
150
    int speed, parity, data_bits, stop_bits, frame_size;
B
bellard 已提交
151
    QEMUSerialSetParams ssp;
B
bellard 已提交
152

153 154 155
    if (s->divider == 0)
        return;

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

B
bellard 已提交
173
    data_bits = (s->lcr & 0x03) + 5;
174
    frame_size += data_bits + stop_bits;
A
aurel32 已提交
175
    speed = s->baudbase / s->divider;
B
bellard 已提交
176 177 178 179
    ssp.speed = speed;
    ssp.parity = parity;
    ssp.data_bits = data_bits;
    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",
B
bellard 已提交
184 185 186
           speed, parity, data_bits, stop_bits);
}

187 188 189 190 191
static void serial_update_msl(SerialState *s)
{
    uint8_t omsr;
    int flags;

192
    timer_del(s->modem_status_poll);
193

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

    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 225
{
    SerialState *s = opaque;

226 227 228 229 230 231 232 233 234 235 236
    do {
        if (s->tsr_retry <= 0) {
            if (s->fcr & UART_FCR_FE) {
                if (fifo8_is_empty(&s->xmit_fifo)) {
                    return FALSE;
                }
                s->tsr = fifo8_pop(&s->xmit_fifo);
                if (!s->xmit_fifo.num) {
                    s->lsr |= UART_LSR_THRE;
                }
            } else if ((s->lsr & UART_LSR_THRE)) {
D
Don Slutz 已提交
237
                return FALSE;
238 239
            } else {
                s->tsr = s->thr;
240
                s->lsr |= UART_LSR_THRE;
241
                s->lsr &= ~UART_LSR_TEMT;
P
Peter Crosthwaite 已提交
242
            }
243 244
        }

245 246 247 248 249 250 251 252 253 254 255 256 257
        if (s->mcr & UART_MCR_LOOP) {
            /* in loopback mode, say that we just received a char */
            serial_receive1(s, &s->tsr, 1);
        } else if (qemu_chr_fe_write(s->chr, &s->tsr, 1) != 1) {
            if (s->tsr_retry >= 0 && s->tsr_retry < MAX_XMIT_RETRY &&
                qemu_chr_fe_add_watch(s->chr, G_IO_OUT|G_IO_HUP,
                                      serial_xmit, s) > 0) {
                s->tsr_retry++;
                return FALSE;
            }
            s->tsr_retry = 0;
        } else {
            s->tsr_retry = 0;
258
        }
259 260 261
        /* Transmit another byte if it is already available. It is only
           possible when FIFO is enabled and not empty. */
    } 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 266 267 268 269

    if (s->lsr & UART_LSR_THRE) {
        s->lsr |= UART_LSR_TEMT;
        s->thr_ipending = 1;
        serial_update_irq(s);
    }
270 271

    return FALSE;
272 273 274
}


275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
/* 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;
    }
}

305 306
static void serial_ioport_write(void *opaque, hwaddr addr, uint64_t val,
                                unsigned size)
B
bellard 已提交
307
{
B
bellard 已提交
308
    SerialState *s = opaque;
309

B
bellard 已提交
310
    addr &= 7;
K
Kevin Wolf 已提交
311
    DPRINTF("write addr=0x%" HWADDR_PRIx " val=0x%" PRIx64 "\n", addr, val);
B
bellard 已提交
312 313 314 315 316
    switch(addr) {
    default:
    case 0:
        if (s->lcr & UART_LCR_DLAB) {
            s->divider = (s->divider & 0xff00) | val;
B
bellard 已提交
317
            serial_update_parameters(s);
B
bellard 已提交
318
        } else {
319 320
            s->thr = (uint8_t) val;
            if(s->fcr & UART_FCR_FE) {
321 322 323 324 325
                /* 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
Aurelien Jarno 已提交
326
                s->lsr &= ~UART_LSR_TEMT;
A
aurel32 已提交
327
            }
328 329 330
            s->thr_ipending = 0;
            s->lsr &= ~UART_LSR_THRE;
            serial_update_irq(s);
331 332 333
            if (s->tsr_retry <= 0) {
                serial_xmit(NULL, G_IO_OUT, s);
            }
B
bellard 已提交
334 335 336 337 338
        }
        break;
    case 1:
        if (s->lcr & UART_LCR_DLAB) {
            s->divider = (s->divider & 0x00ff) | (val << 8);
B
bellard 已提交
339
            serial_update_parameters(s);
B
bellard 已提交
340
        } else {
B
bellard 已提交
341
            s->ier = val & 0x0f;
342 343 344 345 346 347 348
            /* If the backend device is a real serial port, turn polling of the modem
               status lines on physical port on or off depending on UART_IER_MSI state */
            if (s->poll_msl >= 0) {
                if (s->ier & UART_IER_MSI) {
                     s->poll_msl = 1;
                     serial_update_msl(s);
                } else {
349
                     timer_del(s->modem_status_poll);
350 351 352
                     s->poll_msl = 0;
                }
            }
B
bellard 已提交
353 354
            if (s->lsr & UART_LSR_THRE) {
                s->thr_ipending = 1;
355
                serial_update_irq(s);
B
bellard 已提交
356
            }
B
bellard 已提交
357 358 359
        }
        break;
    case 2:
360
        /* Did the enable/disable flag change? If so, make sure FIFOs get flushed */
361
        if ((val ^ s->fcr) & UART_FCR_FE) {
362
            val |= UART_FCR_XFR | UART_FCR_RFR;
363
        }
364 365 366 367

        /* FIFO clear */

        if (val & UART_FCR_RFR) {
368
            timer_del(s->fifo_timeout_timer);
369
            s->timeout_ipending = 0;
370
            fifo8_reset(&s->recv_fifo);
371 372 373
        }

        if (val & UART_FCR_XFR) {
374
            fifo8_reset(&s->xmit_fifo);
375 376
        }

377
        serial_write_fcr(s, val & 0xC9);
378
        serial_update_irq(s);
B
bellard 已提交
379 380
        break;
    case 3:
B
bellard 已提交
381 382 383 384 385 386 387
        {
            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;
388
                qemu_chr_fe_ioctl(s->chr, CHR_IOCTL_SERIAL_SET_BREAK,
B
bellard 已提交
389
                               &break_enable);
B
bellard 已提交
390 391
            }
        }
B
bellard 已提交
392 393
        break;
    case 4:
394 395 396 397 398 399 400 401 402
        {
            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) {

403
                qemu_chr_fe_ioctl(s->chr,CHR_IOCTL_SERIAL_GET_TIOCM, &flags);
404 405 406 407 408 409 410 411

                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;

412
                qemu_chr_fe_ioctl(s->chr,CHR_IOCTL_SERIAL_SET_TIOCM, &flags);
413 414
                /* 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 */
415
                timer_mod(s->modem_status_poll, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time);
416 417
            }
        }
B
bellard 已提交
418 419 420 421 422 423 424 425 426 427 428
        break;
    case 5:
        break;
    case 6:
        break;
    case 7:
        s->scr = val;
        break;
    }
}

429
static uint64_t serial_ioport_read(void *opaque, hwaddr addr, unsigned size)
B
bellard 已提交
430
{
B
bellard 已提交
431
    SerialState *s = opaque;
B
bellard 已提交
432 433 434 435 436 437 438
    uint32_t ret;

    addr &= 7;
    switch(addr) {
    default:
    case 0:
        if (s->lcr & UART_LCR_DLAB) {
439
            ret = s->divider & 0xff;
B
bellard 已提交
440
        } else {
441
            if(s->fcr & UART_FCR_FE) {
442
                ret = fifo8_is_empty(&s->recv_fifo) ?
443 444
                            0 : fifo8_pop(&s->recv_fifo);
                if (s->recv_fifo.num == 0) {
445
                    s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
P
Peter Crosthwaite 已提交
446
                } else {
447
                    timer_mod(s->fifo_timeout_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time * 4);
P
Peter Crosthwaite 已提交
448
                }
449 450 451 452 453
                s->timeout_ipending = 0;
            } else {
                ret = s->rbr;
                s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
            }
B
bellard 已提交
454
            serial_update_irq(s);
455 456 457 458
            if (!(s->mcr & UART_MCR_LOOP)) {
                /* in loopback mode, don't receive any data */
                qemu_chr_accept_input(s->chr);
            }
B
bellard 已提交
459 460 461 462 463 464 465 466 467 468 469
        }
        break;
    case 1:
        if (s->lcr & UART_LCR_DLAB) {
            ret = (s->divider >> 8) & 0xff;
        } else {
            ret = s->ier;
        }
        break;
    case 2:
        ret = s->iir;
470
        if ((ret & UART_IIR_ID) == UART_IIR_THRI) {
B
bellard 已提交
471
            s->thr_ipending = 0;
472 473
            serial_update_irq(s);
        }
B
bellard 已提交
474 475 476 477 478 479 480 481 482
        break;
    case 3:
        ret = s->lcr;
        break;
    case 4:
        ret = s->mcr;
        break;
    case 5:
        ret = s->lsr;
483 484 485
        /* Clear break and overrun interrupts */
        if (s->lsr & (UART_LSR_BI|UART_LSR_OE)) {
            s->lsr &= ~(UART_LSR_BI|UART_LSR_OE);
486 487
            serial_update_irq(s);
        }
B
bellard 已提交
488 489 490 491 492 493 494 495 496
        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 {
497 498
            if (s->poll_msl >= 0)
                serial_update_msl(s);
B
bellard 已提交
499
            ret = s->msr;
500 501 502 503 504
            /* 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 已提交
505 506 507 508 509 510
        }
        break;
    case 7:
        ret = s->scr;
        break;
    }
K
Kevin Wolf 已提交
511
    DPRINTF("read addr=0x%" HWADDR_PRIx " val=0x%02x\n", addr, ret);
B
bellard 已提交
512 513 514
    return ret;
}

B
bellard 已提交
515
static int serial_can_receive(SerialState *s)
B
bellard 已提交
516
{
517
    if(s->fcr & UART_FCR_FE) {
518
        if (s->recv_fifo.num < UART_FIFO_LENGTH) {
P
Peter Crosthwaite 已提交
519 520 521 522 523 524 525
            /*
             * 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.
             */
526 527
            return (s->recv_fifo.num <= s->recv_fifo_itl) ?
                        s->recv_fifo_itl - s->recv_fifo.num : 1;
P
Peter Crosthwaite 已提交
528 529 530
        } else {
            return 0;
        }
531
    } else {
P
Peter Crosthwaite 已提交
532
        return !(s->lsr & UART_LSR_DR);
533
    }
B
bellard 已提交
534 535
}

B
bellard 已提交
536
static void serial_receive_break(SerialState *s)
B
bellard 已提交
537 538
{
    s->rbr = 0;
539
    /* When the LSR_DR is set a null byte is pushed into the fifo */
540
    recv_fifo_put(s, '\0');
B
bellard 已提交
541
    s->lsr |= UART_LSR_BI | UART_LSR_DR;
B
bellard 已提交
542
    serial_update_irq(s);
B
bellard 已提交
543 544
}

545 546 547
/* 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;
548
    if (s->recv_fifo.num) {
549 550 551 552 553
        s->timeout_ipending = 1;
        serial_update_irq(s);
    }
}

B
bellard 已提交
554
static int serial_can_receive1(void *opaque)
B
bellard 已提交
555
{
B
bellard 已提交
556 557 558 559 560 561 562
    SerialState *s = opaque;
    return serial_can_receive(s);
}

static void serial_receive1(void *opaque, const uint8_t *buf, int size)
{
    SerialState *s = opaque;
563 564 565 566

    if (s->wakeup) {
        qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
    }
567 568 569
    if(s->fcr & UART_FCR_FE) {
        int i;
        for (i = 0; i < size; i++) {
570
            recv_fifo_put(s, buf[i]);
571 572 573
        }
        s->lsr |= UART_LSR_DR;
        /* call the timeout receive callback in 4 char transmit time */
574
        timer_mod(s->fifo_timeout_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time * 4);
575
    } else {
576 577
        if (s->lsr & UART_LSR_DR)
            s->lsr |= UART_LSR_OE;
578 579 580 581
        s->rbr = buf[0];
        s->lsr |= UART_LSR_DR;
    }
    serial_update_irq(s);
B
bellard 已提交
582
}
B
bellard 已提交
583

B
bellard 已提交
584 585 586
static void serial_event(void *opaque, int event)
{
    SerialState *s = opaque;
587
    DPRINTF("event %x\n", event);
B
bellard 已提交
588 589 590 591
    if (event == CHR_EVENT_BREAK)
        serial_receive_break(s);
}

592
static void serial_pre_save(void *opaque)
593
{
594
    SerialState *s = opaque;
J
Juan Quintela 已提交
595
    s->fcr_vmstate = s->fcr;
596 597
}

598 599 600 601 602 603 604 605
static int serial_pre_load(void *opaque)
{
    SerialState *s = opaque;
    s->thr_ipending = -1;
    s->poll_msl = -1;
    return 0;
}

606
static int serial_post_load(void *opaque, int version_id)
J
Juan Quintela 已提交
607 608
{
    SerialState *s = opaque;
609

610 611 612
    if (version_id < 3) {
        s->fcr_vmstate = 0;
    }
613 614 615 616
    if (s->thr_ipending == -1) {
        s->thr_ipending = ((s->iir & UART_IIR_ID) == UART_IIR_THRI);
    }
    s->last_break_enable = (s->lcr >> 6) & 1;
617
    /* Initialize fcr via setter to perform essential side-effects */
618
    serial_write_fcr(s, s->fcr_vmstate);
619
    serial_update_parameters(s);
620 621 622
    return 0;
}

623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
static bool serial_thr_ipending_needed(void *opaque)
{
    SerialState *s = opaque;
    bool expected_value = ((s->iir & UART_IIR_ID) == UART_IIR_THRI);
    return s->thr_ipending != expected_value;
}

const VMStateDescription vmstate_serial_thr_ipending = {
    .name = "serial/thr_ipending",
    .version_id = 1,
    .minimum_version_id = 1,
    .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;
}

const VMStateDescription vmstate_serial_tsr = {
    .name = "serial/tsr",
    .version_id = 1,
    .minimum_version_id = 1,
    .fields = (VMStateField[]) {
        VMSTATE_INT32(tsr_retry, SerialState),
        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);

}

const VMStateDescription vmstate_serial_recv_fifo = {
    .name = "serial/recv_fifo",
    .version_id = 1,
    .minimum_version_id = 1,
    .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);
}

const VMStateDescription vmstate_serial_xmit_fifo = {
    .name = "serial/xmit_fifo",
    .version_id = 1,
    .minimum_version_id = 1,
    .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);
}

const VMStateDescription vmstate_serial_fifo_timeout_timer = {
    .name = "serial/fifo_timeout_timer",
    .version_id = 1,
    .minimum_version_id = 1,
    .fields = (VMStateField[]) {
        VMSTATE_TIMER(fifo_timeout_timer, SerialState),
        VMSTATE_END_OF_LIST()
    }
};

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

const VMStateDescription vmstate_serial_timeout_ipending = {
    .name = "serial/timeout_ipending",
    .version_id = 1,
    .minimum_version_id = 1,
    .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;
}

const VMStateDescription vmstate_serial_poll = {
    .name = "serial/poll",
    .version_id = 1,
    .minimum_version_id = 1,
    .fields = (VMStateField[]) {
        VMSTATE_INT32(poll_msl, SerialState),
        VMSTATE_TIMER(modem_status_poll, SerialState),
        VMSTATE_END_OF_LIST()
    }
};

G
Gerd Hoffmann 已提交
740
const VMStateDescription vmstate_serial = {
J
Juan Quintela 已提交
741 742 743 744
    .name = "serial",
    .version_id = 3,
    .minimum_version_id = 2,
    .pre_save = serial_pre_save,
745
    .pre_load = serial_pre_load,
J
Juan Quintela 已提交
746
    .post_load = serial_post_load,
747
    .fields = (VMStateField[]) {
J
Juan Quintela 已提交
748 749 750 751 752 753 754 755 756 757 758
        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()
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
    },
    .subsections = (VMStateSubsection[]) {
        {
            .vmsd = &vmstate_serial_thr_ipending,
            .needed = &serial_thr_ipending_needed,
        } , {
            .vmsd = &vmstate_serial_tsr,
            .needed = &serial_tsr_needed,
        } , {
            .vmsd = &vmstate_serial_recv_fifo,
            .needed = &serial_recv_fifo_needed,
        } , {
            .vmsd = &vmstate_serial_xmit_fifo,
            .needed = &serial_xmit_fifo_needed,
        } , {
            .vmsd = &vmstate_serial_fifo_timeout_timer,
            .needed = &serial_fifo_timeout_timer_needed,
        } , {
            .vmsd = &vmstate_serial_timeout_ipending,
            .needed = &serial_timeout_ipending_needed,
        } , {
            .vmsd = &vmstate_serial_poll,
            .needed = &serial_poll_needed,
        } , {
            /* empty */
        }
J
Juan Quintela 已提交
785 786 787
    }
};

788 789 790 791 792 793 794 795 796 797
static void serial_reset(void *opaque)
{
    SerialState *s = opaque;

    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 已提交
798
    /* Default to 9600 baud, 1 start bit, 8 data bits, 1 stop bit, no parity. */
799 800
    s->divider = 0x0C;
    s->mcr = UART_MCR_OUT2;
801
    s->scr = 0;
802
    s->tsr_retry = 0;
S
Stefan Weil 已提交
803
    s->char_transmit_time = (get_ticks_per_sec() / 9600) * 10;
804 805
    s->poll_msl = 0;

806 807 808 809
    s->timeout_ipending = 0;
    timer_del(s->fifo_timeout_timer);
    timer_del(s->modem_status_poll);

810 811
    fifo8_reset(&s->recv_fifo);
    fifo8_reset(&s->xmit_fifo);
812

813
    s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
814 815 816 817

    s->thr_ipending = 0;
    s->last_break_enable = 0;
    qemu_irq_lower(s->irq);
818 819 820

    serial_update_msl(s);
    s->msr &= ~UART_MSR_ANY_DELTA;
821 822
}

823
void serial_realize_core(SerialState *s, Error **errp)
824
{
G
Gerd Hoffmann 已提交
825
    if (!s->chr) {
826 827
        error_setg(errp, "Can't create serial device, empty char device");
        return;
828 829
    }

830
    s->modem_status_poll = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) serial_update_msl, s);
831

832
    s->fifo_timeout_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) fifo_timeout_int, s);
833
    qemu_register_reset(serial_reset, s);
834

835 836
    qemu_chr_add_handlers(s->chr, serial_can_receive1, serial_receive1,
                          serial_event, s);
837 838
    fifo8_create(&s->recv_fifo, UART_FIFO_LENGTH);
    fifo8_create(&s->xmit_fifo, UART_FIFO_LENGTH);
P
Paolo Bonzini 已提交
839
    serial_reset(s);
840 841
}

G
Gerd Hoffmann 已提交
842 843 844 845 846 847
void serial_exit_core(SerialState *s)
{
    qemu_chr_add_handlers(s->chr, NULL, NULL, NULL, NULL);
    qemu_unregister_reset(serial_reset, s);
}

848 849 850 851 852 853 854
/* 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 已提交
855
const MemoryRegionOps serial_io_ops = {
856 857 858 859 860 861 862
    .read = serial_ioport_read,
    .write = serial_ioport_write,
    .impl = {
        .min_access_size = 1,
        .max_access_size = 1,
    },
    .endianness = DEVICE_LITTLE_ENDIAN,
863 864
};

A
aurel32 已提交
865
SerialState *serial_init(int base, qemu_irq irq, int baudbase,
J
Julien Grall 已提交
866
                         CharDriverState *chr, MemoryRegion *system_io)
B
bellard 已提交
867 868
{
    SerialState *s;
869
    Error *err = NULL;
B
bellard 已提交
870

871
    s = g_malloc0(sizeof(SerialState));
A
aurel32 已提交
872

G
Gerd Hoffmann 已提交
873 874 875
    s->irq = irq;
    s->baudbase = baudbase;
    s->chr = chr;
876 877
    serial_realize_core(s, &err);
    if (err != NULL) {
878
        error_report("%s", error_get_pretty(err));
879 880 881
        error_free(err);
        exit(1);
    }
B
bellard 已提交
882

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

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

B
bellard 已提交
888
    return s;
B
bellard 已提交
889
}
890 891

/* Memory mapped interface */
A
Avi Kivity 已提交
892
static uint64_t serial_mm_read(void *opaque, hwaddr addr,
893
                               unsigned size)
894 895
{
    SerialState *s = opaque;
896
    return serial_ioport_read(s, addr >> s->it_shift, 1);
897 898
}

A
Avi Kivity 已提交
899
static void serial_mm_write(void *opaque, hwaddr addr,
900
                            uint64_t value, unsigned size)
B
Blue Swirl 已提交
901 902
{
    SerialState *s = opaque;
903
    value &= ~0u >> (32 - (size * 8));
904
    serial_ioport_write(s, addr >> s->it_shift, value, 1);
B
Blue Swirl 已提交
905 906
}

907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
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,
    },
923 924
};

925
SerialState *serial_mm_init(MemoryRegion *address_space,
A
Avi Kivity 已提交
926
                            hwaddr base, int it_shift,
927 928
                            qemu_irq irq, int baudbase,
                            CharDriverState *chr, enum device_endian end)
929 930
{
    SerialState *s;
931
    Error *err = NULL;
932

933
    s = g_malloc0(sizeof(SerialState));
934

935
    s->it_shift = it_shift;
G
Gerd Hoffmann 已提交
936 937 938
    s->irq = irq;
    s->baudbase = baudbase;
    s->chr = chr;
939

940 941
    serial_realize_core(s, &err);
    if (err != NULL) {
942
        error_report("%s", error_get_pretty(err));
943 944 945
        error_free(err);
        exit(1);
    }
A
Alex Williamson 已提交
946
    vmstate_register(NULL, base, &vmstate_serial, s);
947

948
    memory_region_init_io(&s->io, NULL, &serial_mm_ops[end], s,
949
                          "serial", 8 << it_shift);
950
    memory_region_add_subregion(address_space, base, &s->io);
951 952
    return s;
}