serial.c 32.4 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"
M
Markus Armbruster 已提交
28
#include "hw/irq.h"
29
#include "migration/vmstate.h"
30
#include "chardev/char-serial.h"
31
#include "qapi/error.h"
32
#include "qemu/timer.h"
33
#include "sysemu/reset.h"
34
#include "sysemu/runstate.h"
35
#include "qemu/error-report.h"
36
#include "trace.h"
B
bellard 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

//#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 */
54 55 56 57
#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 已提交
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 84 85 86 87

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

90 91 92 93 94 95 96 97 98 99 100 101 102 103
/* 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

104 105
#ifdef DEBUG_SERIAL
#define DPRINTF(fmt, ...) \
106
do { fprintf(stderr, "serial: " fmt , ## __VA_ARGS__); } while (0)
107 108
#else
#define DPRINTF(fmt, ...) \
109
do {} while (0)
110 111
#endif

112
static void serial_receive1(void *opaque, const uint8_t *buf, int size);
113
static void serial_xmit(SerialState *s);
114

115
static inline void recv_fifo_put(SerialState *s, uint8_t chr)
B
bellard 已提交
116
{
117
    /* Receive overruns do not overwrite FIFO contents. */
118 119 120
    if (!fifo8_is_full(&s->recv_fifo)) {
        fifo8_push(&s->recv_fifo, chr);
    } else {
121
        s->lsr |= UART_LSR_OE;
122
    }
123
}
A
aurel32 已提交
124

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

B
bellard 已提交
155 156
static void serial_update_parameters(SerialState *s)
{
157 158
    float speed;
    int parity, data_bits, stop_bits, frame_size;
B
bellard 已提交
159
    QEMUSerialSetParams ssp;
B
bellard 已提交
160

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

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

190
    DPRINTF("speed=%.2f parity=%c data=%d stop=%d\n",
B
bellard 已提交
191 192 193
           speed, parity, data_bits, stop_bits);
}

194 195 196 197 198
static void serial_update_msl(SerialState *s)
{
    uint8_t omsr;
    int flags;

199
    timer_del(s->modem_status_poll);
200

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

226 227 228 229
    if (s->poll_msl) {
        timer_mod(s->modem_status_poll, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
                  NANOSECONDS_PER_SECOND / 100);
    }
230 231
}

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

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

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

264 265 266
        if (s->mcr & UART_MCR_LOOP) {
            /* in loopback mode, say that we just received a char */
            serial_receive1(s, &s->tsr, 1);
267 268 269 270 271 272 273 274 275 276 277 278 279 280
        } 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;
                }
281
            }
282
        }
P
Paolo Bonzini 已提交
283
        s->tsr_retry = 0;
284

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

289
    s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
290
    s->lsr |= UART_LSR_TEMT;
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 319 320 321 322
/* 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;
    }
}

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
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);
}

341 342
static void serial_ioport_write(void *opaque, hwaddr addr, uint64_t val,
                                unsigned size)
B
bellard 已提交
343
{
B
bellard 已提交
344
    SerialState *s = opaque;
345

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

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

        /* FIFO clear */

        if (val & UART_FCR_RFR) {
429
            s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
430
            timer_del(s->fifo_timeout_timer);
431
            s->timeout_ipending = 0;
432
            fifo8_reset(&s->recv_fifo);
433 434 435
        }

        if (val & UART_FCR_XFR) {
436 437
            s->lsr |= UART_LSR_THRE;
            s->thr_ipending = 1;
438
            fifo8_reset(&s->xmit_fifo);
439 440
        }

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

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

482
static uint64_t serial_ioport_read(void *opaque, hwaddr addr, unsigned size)
B
bellard 已提交
483
{
B
bellard 已提交
484
    SerialState *s = opaque;
B
bellard 已提交
485 486 487 488 489 490 491
    uint32_t ret;

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

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

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

598 599 600
/* 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;
601
    if (s->recv_fifo.num) {
602 603 604 605 606
        s->timeout_ipending = 1;
        serial_update_irq(s);
    }
}

B
bellard 已提交
607
static int serial_can_receive1(void *opaque)
B
bellard 已提交
608
{
B
bellard 已提交
609 610 611 612 613 614 615
    SerialState *s = opaque;
    return serial_can_receive(s);
}

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

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

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

645
static int serial_pre_save(void *opaque)
646
{
647
    SerialState *s = opaque;
J
Juan Quintela 已提交
648
    s->fcr_vmstate = s->fcr;
649 650

    return 0;
651 652
}

653 654 655 656 657 658 659 660
static int serial_pre_load(void *opaque)
{
    SerialState *s = opaque;
    s->thr_ipending = -1;
    s->poll_msl = -1;
    return 0;
}

661
static int serial_post_load(void *opaque, int version_id)
J
Juan Quintela 已提交
662 663
{
    SerialState *s = opaque;
664

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

    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);
685
        s->watch_tag = qemu_chr_fe_add_watch(&s->chr, G_IO_OUT | G_IO_HUP,
686 687 688 689 690 691 692 693
                                             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 已提交
694 695
    }

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

703 704 705
static bool serial_thr_ipending_needed(void *opaque)
{
    SerialState *s = opaque;
706 707 708 709 710 711 712 713 714 715 716

    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;
    }
717 718
}

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

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

}

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

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

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

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

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

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

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

868 869 870 871
static void serial_reset(void *opaque)
{
    SerialState *s = opaque;

P
Paolo Bonzini 已提交
872 873 874 875 876
    if (s->watch_tag > 0) {
        g_source_remove(s->watch_tag);
        s->watch_tag = 0;
    }

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

891 892 893 894
    s->timeout_ipending = 0;
    timer_del(s->fifo_timeout_timer);
    timer_del(s->modem_status_poll);

895 896
    fifo8_reset(&s->recv_fifo);
    fifo8_reset(&s->xmit_fifo);
897

898
    s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
899 900 901 902

    s->thr_ipending = 0;
    s->last_break_enable = 0;
    qemu_irq_lower(s->irq);
903 904 905

    serial_update_msl(s);
    s->msr &= ~UART_MSR_ANY_DELTA;
906 907
}

A
Anton Nefedov 已提交
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
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;
}

936
void serial_realize_core(SerialState *s, Error **errp)
937
{
938
    s->modem_status_poll = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) serial_update_msl, s);
939

940
    s->fifo_timeout_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) fifo_timeout_int, s);
941
    qemu_register_reset(serial_reset, s);
942

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

G
Gerd Hoffmann 已提交
950 951
void serial_exit_core(SerialState *s)
{
952
    qemu_chr_fe_deinit(&s->chr, false);
953 954 955 956 957 958 959 960 961 962

    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 已提交
963 964 965
    qemu_unregister_reset(serial_reset, s);
}

966 967 968 969 970 971 972
/* 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 已提交
973
const MemoryRegionOps serial_io_ops = {
974 975 976 977 978 979 980
    .read = serial_ioport_read,
    .write = serial_ioport_write,
    .impl = {
        .min_access_size = 1,
        .max_access_size = 1,
    },
    .endianness = DEVICE_LITTLE_ENDIAN,
981 982
};

A
aurel32 已提交
983
SerialState *serial_init(int base, qemu_irq irq, int baudbase,
984
                         Chardev *chr, MemoryRegion *system_io)
B
bellard 已提交
985
{
986 987
    DeviceState *dev = DEVICE(object_new(TYPE_SERIAL));
    SerialState *s = SERIAL(dev);
A
aurel32 已提交
988

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

A
Alex Williamson 已提交
994
    vmstate_register(NULL, base, &vmstate_serial, s);
995
    qdev_init_nofail(dev);
996

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

B
bellard 已提交
1000
    return s;
B
bellard 已提交
1001
}
1002

1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
static void serial_class_init(ObjectClass *klass, void *data)
{
    DeviceClass *dc = DEVICE_CLASS(klass);

    /* internal device for serialio/serialmm, not user-creatable */
    dc->user_creatable = false;
}

static const TypeInfo serial_info = {
    .name = TYPE_SERIAL,
    .parent = TYPE_DEVICE,
    .instance_size = sizeof(SerialState),
    .class_init = serial_class_init,
};

1018
/* Memory mapped interface */
A
Avi Kivity 已提交
1019
static uint64_t serial_mm_read(void *opaque, hwaddr addr,
1020
                               unsigned size)
1021 1022
{
    SerialState *s = opaque;
1023
    return serial_ioport_read(s, addr >> s->it_shift, 1);
1024 1025
}

A
Avi Kivity 已提交
1026
static void serial_mm_write(void *opaque, hwaddr addr,
1027
                            uint64_t value, unsigned size)
B
Blue Swirl 已提交
1028 1029
{
    SerialState *s = opaque;
1030
    value &= 255;
1031
    serial_ioport_write(s, addr >> s->it_shift, value, 1);
B
Blue Swirl 已提交
1032 1033
}

1034 1035 1036 1037 1038
static const MemoryRegionOps serial_mm_ops[3] = {
    [DEVICE_NATIVE_ENDIAN] = {
        .read = serial_mm_read,
        .write = serial_mm_write,
        .endianness = DEVICE_NATIVE_ENDIAN,
1039 1040
        .valid.max_access_size = 8,
        .impl.max_access_size = 8,
1041 1042 1043 1044 1045
    },
    [DEVICE_LITTLE_ENDIAN] = {
        .read = serial_mm_read,
        .write = serial_mm_write,
        .endianness = DEVICE_LITTLE_ENDIAN,
1046 1047
        .valid.max_access_size = 8,
        .impl.max_access_size = 8,
1048 1049 1050 1051 1052
    },
    [DEVICE_BIG_ENDIAN] = {
        .read = serial_mm_read,
        .write = serial_mm_write,
        .endianness = DEVICE_BIG_ENDIAN,
1053 1054
        .valid.max_access_size = 8,
        .impl.max_access_size = 8,
1055
    },
1056 1057
};

1058
SerialState *serial_mm_init(MemoryRegion *address_space,
A
Avi Kivity 已提交
1059
                            hwaddr base, int it_shift,
1060
                            qemu_irq irq, int baudbase,
1061
                            Chardev *chr, enum device_endian end)
1062
{
1063 1064
    DeviceState *dev = DEVICE(object_new(TYPE_SERIAL));
    SerialState *s = SERIAL(dev);
1065

1066
    s->it_shift = it_shift;
G
Gerd Hoffmann 已提交
1067 1068
    s->irq = irq;
    s->baudbase = baudbase;
1069
    qemu_chr_fe_init(&s->chr, chr, &error_abort);
1070

1071
    serial_realize_core(s, &error_fatal);
A
Alex Williamson 已提交
1072
    vmstate_register(NULL, base, &vmstate_serial, s);
1073
    qdev_init_nofail(dev);
1074

1075
    memory_region_init_io(&s->io, NULL, &serial_mm_ops[end], s,
1076
                          "serial", 8 << it_shift);
1077
    memory_region_add_subregion(address_space, base, &s->io);
1078 1079
    return s;
}
1080 1081 1082 1083 1084 1085 1086

static void serial_register_types(void)
{
    type_register_static(&serial_info);
}

type_init(serial_register_types)