qemu/hw/char/serial.c
<<
>>
Prefs
   1/*
   2 * QEMU 16550A UART emulation
   3 *
   4 * Copyright (c) 2003-2004 Fabrice Bellard
   5 * Copyright (c) 2008 Citrix Systems, Inc.
   6 *
   7 * Permission is hereby granted, free of charge, to any person obtaining a copy
   8 * of this software and associated documentation files (the "Software"), to deal
   9 * in the Software without restriction, including without limitation the rights
  10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11 * copies of the Software, and to permit persons to whom the Software is
  12 * furnished to do so, subject to the following conditions:
  13 *
  14 * The above copyright notice and this permission notice shall be included in
  15 * all copies or substantial portions of the Software.
  16 *
  17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23 * THE SOFTWARE.
  24 */
  25
  26#include "hw/char/serial.h"
  27#include "sysemu/char.h"
  28#include "qemu/timer.h"
  29#include "exec/address-spaces.h"
  30#include "qemu/error-report.h"
  31
  32//#define DEBUG_SERIAL
  33
  34#define UART_LCR_DLAB   0x80    /* Divisor latch access bit */
  35
  36#define UART_IER_MSI    0x08    /* Enable Modem status interrupt */
  37#define UART_IER_RLSI   0x04    /* Enable receiver line status interrupt */
  38#define UART_IER_THRI   0x02    /* Enable Transmitter holding register int. */
  39#define UART_IER_RDI    0x01    /* Enable receiver data interrupt */
  40
  41#define UART_IIR_NO_INT 0x01    /* No interrupts pending */
  42#define UART_IIR_ID     0x06    /* Mask for the interrupt ID */
  43
  44#define UART_IIR_MSI    0x00    /* Modem status interrupt */
  45#define UART_IIR_THRI   0x02    /* Transmitter holding register empty */
  46#define UART_IIR_RDI    0x04    /* Receiver data interrupt */
  47#define UART_IIR_RLSI   0x06    /* Receiver line status interrupt */
  48#define UART_IIR_CTI    0x0C    /* Character Timeout Indication */
  49
  50#define UART_IIR_FENF   0x80    /* Fifo enabled, but not functionning */
  51#define UART_IIR_FE     0xC0    /* Fifo enabled */
  52
  53/*
  54 * These are the definitions for the Modem Control Register
  55 */
  56#define UART_MCR_LOOP   0x10    /* Enable loopback test mode */
  57#define UART_MCR_OUT2   0x08    /* Out2 complement */
  58#define UART_MCR_OUT1   0x04    /* Out1 complement */
  59#define UART_MCR_RTS    0x02    /* RTS complement */
  60#define UART_MCR_DTR    0x01    /* DTR complement */
  61
  62/*
  63 * These are the definitions for the Modem Status Register
  64 */
  65#define UART_MSR_DCD    0x80    /* Data Carrier Detect */
  66#define UART_MSR_RI     0x40    /* Ring Indicator */
  67#define UART_MSR_DSR    0x20    /* Data Set Ready */
  68#define UART_MSR_CTS    0x10    /* Clear to Send */
  69#define UART_MSR_DDCD   0x08    /* Delta DCD */
  70#define UART_MSR_TERI   0x04    /* Trailing edge ring indicator */
  71#define UART_MSR_DDSR   0x02    /* Delta DSR */
  72#define UART_MSR_DCTS   0x01    /* Delta CTS */
  73#define UART_MSR_ANY_DELTA 0x0F /* Any of the delta bits! */
  74
  75#define UART_LSR_TEMT   0x40    /* Transmitter empty */
  76#define UART_LSR_THRE   0x20    /* Transmit-hold-register empty */
  77#define UART_LSR_BI     0x10    /* Break interrupt indicator */
  78#define UART_LSR_FE     0x08    /* Frame error indicator */
  79#define UART_LSR_PE     0x04    /* Parity error indicator */
  80#define UART_LSR_OE     0x02    /* Overrun error indicator */
  81#define UART_LSR_DR     0x01    /* Receiver data ready */
  82#define UART_LSR_INT_ANY 0x1E   /* Any of the lsr-interrupt-triggering status bits */
  83
  84/* Interrupt trigger levels. The byte-counts are for 16550A - in newer UARTs the byte-count for each ITL is higher. */
  85
  86#define UART_FCR_ITL_1      0x00 /* 1 byte ITL */
  87#define UART_FCR_ITL_2      0x40 /* 4 bytes ITL */
  88#define UART_FCR_ITL_3      0x80 /* 8 bytes ITL */
  89#define UART_FCR_ITL_4      0xC0 /* 14 bytes ITL */
  90
  91#define UART_FCR_DMS        0x08    /* DMA Mode Select */
  92#define UART_FCR_XFR        0x04    /* XMIT Fifo Reset */
  93#define UART_FCR_RFR        0x02    /* RCVR Fifo Reset */
  94#define UART_FCR_FE         0x01    /* FIFO Enable */
  95
  96#define MAX_XMIT_RETRY      4
  97
  98#ifdef DEBUG_SERIAL
  99#define DPRINTF(fmt, ...) \
 100do { fprintf(stderr, "serial: " fmt , ## __VA_ARGS__); } while (0)
 101#else
 102#define DPRINTF(fmt, ...) \
 103do {} while (0)
 104#endif
 105
 106static void serial_receive1(void *opaque, const uint8_t *buf, int size);
 107
 108static inline void recv_fifo_put(SerialState *s, uint8_t chr)
 109{
 110    /* Receive overruns do not overwrite FIFO contents. */
 111    if (!fifo8_is_full(&s->recv_fifo)) {
 112        fifo8_push(&s->recv_fifo, chr);
 113    } else {
 114        s->lsr |= UART_LSR_OE;
 115    }
 116}
 117
 118static void serial_update_irq(SerialState *s)
 119{
 120    uint8_t tmp_iir = UART_IIR_NO_INT;
 121
 122    if ((s->ier & UART_IER_RLSI) && (s->lsr & UART_LSR_INT_ANY)) {
 123        tmp_iir = UART_IIR_RLSI;
 124    } else if ((s->ier & UART_IER_RDI) && s->timeout_ipending) {
 125        /* Note that(s->ier & UART_IER_RDI) can mask this interrupt,
 126         * this is not in the specification but is observed on existing
 127         * hardware.  */
 128        tmp_iir = UART_IIR_CTI;
 129    } else if ((s->ier & UART_IER_RDI) && (s->lsr & UART_LSR_DR) &&
 130               (!(s->fcr & UART_FCR_FE) ||
 131                s->recv_fifo.num >= s->recv_fifo_itl)) {
 132        tmp_iir = UART_IIR_RDI;
 133    } else if ((s->ier & UART_IER_THRI) && s->thr_ipending) {
 134        tmp_iir = UART_IIR_THRI;
 135    } else if ((s->ier & UART_IER_MSI) && (s->msr & UART_MSR_ANY_DELTA)) {
 136        tmp_iir = UART_IIR_MSI;
 137    }
 138
 139    s->iir = tmp_iir | (s->iir & 0xF0);
 140
 141    if (tmp_iir != UART_IIR_NO_INT) {
 142        qemu_irq_raise(s->irq);
 143    } else {
 144        qemu_irq_lower(s->irq);
 145    }
 146}
 147
 148static void serial_update_parameters(SerialState *s)
 149{
 150    int speed, parity, data_bits, stop_bits, frame_size;
 151    QEMUSerialSetParams ssp;
 152
 153    if (s->divider == 0)
 154        return;
 155
 156    /* Start bit. */
 157    frame_size = 1;
 158    if (s->lcr & 0x08) {
 159        /* Parity bit. */
 160        frame_size++;
 161        if (s->lcr & 0x10)
 162            parity = 'E';
 163        else
 164            parity = 'O';
 165    } else {
 166            parity = 'N';
 167    }
 168    if (s->lcr & 0x04)
 169        stop_bits = 2;
 170    else
 171        stop_bits = 1;
 172
 173    data_bits = (s->lcr & 0x03) + 5;
 174    frame_size += data_bits + stop_bits;
 175    speed = s->baudbase / s->divider;
 176    ssp.speed = speed;
 177    ssp.parity = parity;
 178    ssp.data_bits = data_bits;
 179    ssp.stop_bits = stop_bits;
 180    s->char_transmit_time =  (get_ticks_per_sec() / speed) * frame_size;
 181    qemu_chr_fe_ioctl(s->chr, CHR_IOCTL_SERIAL_SET_PARAMS, &ssp);
 182
 183    DPRINTF("speed=%d parity=%c data=%d stop=%d\n",
 184           speed, parity, data_bits, stop_bits);
 185}
 186
 187static void serial_update_msl(SerialState *s)
 188{
 189    uint8_t omsr;
 190    int flags;
 191
 192    timer_del(s->modem_status_poll);
 193
 194    if (qemu_chr_fe_ioctl(s->chr,CHR_IOCTL_SERIAL_GET_TIOCM, &flags) == -ENOTSUP) {
 195        s->poll_msl = -1;
 196        return;
 197    }
 198
 199    omsr = s->msr;
 200
 201    s->msr = (flags & CHR_TIOCM_CTS) ? s->msr | UART_MSR_CTS : s->msr & ~UART_MSR_CTS;
 202    s->msr = (flags & CHR_TIOCM_DSR) ? s->msr | UART_MSR_DSR : s->msr & ~UART_MSR_DSR;
 203    s->msr = (flags & CHR_TIOCM_CAR) ? s->msr | UART_MSR_DCD : s->msr & ~UART_MSR_DCD;
 204    s->msr = (flags & CHR_TIOCM_RI) ? s->msr | UART_MSR_RI : s->msr & ~UART_MSR_RI;
 205
 206    if (s->msr != omsr) {
 207         /* Set delta bits */
 208         s->msr = s->msr | ((s->msr >> 4) ^ (omsr >> 4));
 209         /* UART_MSR_TERI only if change was from 1 -> 0 */
 210         if ((s->msr & UART_MSR_TERI) && !(omsr & UART_MSR_RI))
 211             s->msr &= ~UART_MSR_TERI;
 212         serial_update_irq(s);
 213    }
 214
 215    /* The real 16550A apparently has a 250ns response latency to line status changes.
 216       We'll be lazy and poll only every 10ms, and only poll it at all if MSI interrupts are turned on */
 217
 218    if (s->poll_msl)
 219        timer_mod(s->modem_status_poll, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + get_ticks_per_sec() / 100);
 220}
 221
 222static gboolean serial_xmit(GIOChannel *chan, GIOCondition cond, void *opaque)
 223{
 224    SerialState *s = opaque;
 225
 226    do {
 227        assert(!(s->lsr & UART_LSR_TEMT));
 228        if (s->tsr_retry <= 0) {
 229            assert(!(s->lsr & UART_LSR_THRE));
 230
 231            if (s->fcr & UART_FCR_FE) {
 232                assert(!fifo8_is_empty(&s->xmit_fifo));
 233                s->tsr = fifo8_pop(&s->xmit_fifo);
 234                if (!s->xmit_fifo.num) {
 235                    s->lsr |= UART_LSR_THRE;
 236                }
 237            } else {
 238                s->tsr = s->thr;
 239                s->lsr |= UART_LSR_THRE;
 240            }
 241            if ((s->lsr & UART_LSR_THRE) && !s->thr_ipending) {
 242                s->thr_ipending = 1;
 243                serial_update_irq(s);
 244            }
 245        }
 246
 247        if (s->mcr & UART_MCR_LOOP) {
 248            /* in loopback mode, say that we just received a char */
 249            serial_receive1(s, &s->tsr, 1);
 250        } else if (qemu_chr_fe_write(s->chr, &s->tsr, 1) != 1) {
 251            if (s->tsr_retry >= 0 && s->tsr_retry < MAX_XMIT_RETRY &&
 252                qemu_chr_fe_add_watch(s->chr, G_IO_OUT|G_IO_HUP,
 253                                      serial_xmit, s) > 0) {
 254                s->tsr_retry++;
 255                return FALSE;
 256            }
 257            s->tsr_retry = 0;
 258        } else {
 259            s->tsr_retry = 0;
 260        }
 261
 262        /* Transmit another byte if it is already available. It is only
 263           possible when FIFO is enabled and not empty. */
 264    } while (!(s->lsr & UART_LSR_THRE));
 265
 266    s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
 267    s->lsr |= UART_LSR_TEMT;
 268
 269    return FALSE;
 270}
 271
 272
 273/* Setter for FCR.
 274   is_load flag means, that value is set while loading VM state
 275   and interrupt should not be invoked */
 276static void serial_write_fcr(SerialState *s, uint8_t val)
 277{
 278    /* Set fcr - val only has the bits that are supposed to "stick" */
 279    s->fcr = val;
 280
 281    if (val & UART_FCR_FE) {
 282        s->iir |= UART_IIR_FE;
 283        /* Set recv_fifo trigger Level */
 284        switch (val & 0xC0) {
 285        case UART_FCR_ITL_1:
 286            s->recv_fifo_itl = 1;
 287            break;
 288        case UART_FCR_ITL_2:
 289            s->recv_fifo_itl = 4;
 290            break;
 291        case UART_FCR_ITL_3:
 292            s->recv_fifo_itl = 8;
 293            break;
 294        case UART_FCR_ITL_4:
 295            s->recv_fifo_itl = 14;
 296            break;
 297        }
 298    } else {
 299        s->iir &= ~UART_IIR_FE;
 300    }
 301}
 302
 303static void serial_ioport_write(void *opaque, hwaddr addr, uint64_t val,
 304                                unsigned size)
 305{
 306    SerialState *s = opaque;
 307
 308    addr &= 7;
 309    DPRINTF("write addr=0x%" HWADDR_PRIx " val=0x%" PRIx64 "\n", addr, val);
 310    switch(addr) {
 311    default:
 312    case 0:
 313        if (s->lcr & UART_LCR_DLAB) {
 314            s->divider = (s->divider & 0xff00) | val;
 315            serial_update_parameters(s);
 316        } else {
 317            s->thr = (uint8_t) val;
 318            if(s->fcr & UART_FCR_FE) {
 319                /* xmit overruns overwrite data, so make space if needed */
 320                if (fifo8_is_full(&s->xmit_fifo)) {
 321                    fifo8_pop(&s->xmit_fifo);
 322                }
 323                fifo8_push(&s->xmit_fifo, s->thr);
 324            }
 325            s->thr_ipending = 0;
 326            s->lsr &= ~UART_LSR_THRE;
 327            s->lsr &= ~UART_LSR_TEMT;
 328            serial_update_irq(s);
 329            if (s->tsr_retry <= 0) {
 330                serial_xmit(NULL, G_IO_OUT, s);
 331            }
 332        }
 333        break;
 334    case 1:
 335        if (s->lcr & UART_LCR_DLAB) {
 336            s->divider = (s->divider & 0x00ff) | (val << 8);
 337            serial_update_parameters(s);
 338        } else {
 339            uint8_t changed = (s->ier ^ val) & 0x0f;
 340            s->ier = val & 0x0f;
 341            /* If the backend device is a real serial port, turn polling of the modem
 342             * status lines on physical port on or off depending on UART_IER_MSI state.
 343             */
 344            if ((changed & UART_IER_MSI) && s->poll_msl >= 0) {
 345                if (s->ier & UART_IER_MSI) {
 346                     s->poll_msl = 1;
 347                     serial_update_msl(s);
 348                } else {
 349                     timer_del(s->modem_status_poll);
 350                     s->poll_msl = 0;
 351                }
 352            }
 353
 354            /* Turning on the THRE interrupt on IER can trigger the interrupt
 355             * if LSR.THRE=1, even if it had been masked before by reading IIR.
 356             * This is not in the datasheet, but Windows relies on it.  It is
 357             * unclear if THRE has to be resampled every time THRI becomes
 358             * 1, or only on the rising edge.  Bochs does the latter, and Windows
 359             * always toggles IER to all zeroes and back to all ones, so do the
 360             * same.
 361             *
 362             * If IER.THRI is zero, thr_ipending is not used.  Set it to zero
 363             * so that the thr_ipending subsection is not migrated.
 364             */
 365            if (changed & UART_IER_THRI) {
 366                if ((s->ier & UART_IER_THRI) && (s->lsr & UART_LSR_THRE)) {
 367                    s->thr_ipending = 1;
 368                } else {
 369                    s->thr_ipending = 0;
 370                }
 371            }
 372
 373            if (changed) {
 374                serial_update_irq(s);
 375            }
 376        }
 377        break;
 378    case 2:
 379        /* Did the enable/disable flag change? If so, make sure FIFOs get flushed */
 380        if ((val ^ s->fcr) & UART_FCR_FE) {
 381            val |= UART_FCR_XFR | UART_FCR_RFR;
 382        }
 383
 384        /* FIFO clear */
 385
 386        if (val & UART_FCR_RFR) {
 387            s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
 388            timer_del(s->fifo_timeout_timer);
 389            s->timeout_ipending = 0;
 390            fifo8_reset(&s->recv_fifo);
 391        }
 392
 393        if (val & UART_FCR_XFR) {
 394            s->lsr |= UART_LSR_THRE;
 395            s->thr_ipending = 1;
 396            fifo8_reset(&s->xmit_fifo);
 397        }
 398
 399        serial_write_fcr(s, val & 0xC9);
 400        serial_update_irq(s);
 401        break;
 402    case 3:
 403        {
 404            int break_enable;
 405            s->lcr = val;
 406            serial_update_parameters(s);
 407            break_enable = (val >> 6) & 1;
 408            if (break_enable != s->last_break_enable) {
 409                s->last_break_enable = break_enable;
 410                qemu_chr_fe_ioctl(s->chr, CHR_IOCTL_SERIAL_SET_BREAK,
 411                               &break_enable);
 412            }
 413        }
 414        break;
 415    case 4:
 416        {
 417            int flags;
 418            int old_mcr = s->mcr;
 419            s->mcr = val & 0x1f;
 420            if (val & UART_MCR_LOOP)
 421                break;
 422
 423            if (s->poll_msl >= 0 && old_mcr != s->mcr) {
 424
 425                qemu_chr_fe_ioctl(s->chr,CHR_IOCTL_SERIAL_GET_TIOCM, &flags);
 426
 427                flags &= ~(CHR_TIOCM_RTS | CHR_TIOCM_DTR);
 428
 429                if (val & UART_MCR_RTS)
 430                    flags |= CHR_TIOCM_RTS;
 431                if (val & UART_MCR_DTR)
 432                    flags |= CHR_TIOCM_DTR;
 433
 434                qemu_chr_fe_ioctl(s->chr,CHR_IOCTL_SERIAL_SET_TIOCM, &flags);
 435                /* Update the modem status after a one-character-send wait-time, since there may be a response
 436                   from the device/computer at the other end of the serial line */
 437                timer_mod(s->modem_status_poll, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time);
 438            }
 439        }
 440        break;
 441    case 5:
 442        break;
 443    case 6:
 444        break;
 445    case 7:
 446        s->scr = val;
 447        break;
 448    }
 449}
 450
 451static uint64_t serial_ioport_read(void *opaque, hwaddr addr, unsigned size)
 452{
 453    SerialState *s = opaque;
 454    uint32_t ret;
 455
 456    addr &= 7;
 457    switch(addr) {
 458    default:
 459    case 0:
 460        if (s->lcr & UART_LCR_DLAB) {
 461            ret = s->divider & 0xff;
 462        } else {
 463            if(s->fcr & UART_FCR_FE) {
 464                ret = fifo8_is_empty(&s->recv_fifo) ?
 465                            0 : fifo8_pop(&s->recv_fifo);
 466                if (s->recv_fifo.num == 0) {
 467                    s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
 468                } else {
 469                    timer_mod(s->fifo_timeout_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time * 4);
 470                }
 471                s->timeout_ipending = 0;
 472            } else {
 473                ret = s->rbr;
 474                s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
 475            }
 476            serial_update_irq(s);
 477            if (!(s->mcr & UART_MCR_LOOP)) {
 478                /* in loopback mode, don't receive any data */
 479                qemu_chr_accept_input(s->chr);
 480            }
 481        }
 482        break;
 483    case 1:
 484        if (s->lcr & UART_LCR_DLAB) {
 485            ret = (s->divider >> 8) & 0xff;
 486        } else {
 487            ret = s->ier;
 488        }
 489        break;
 490    case 2:
 491        ret = s->iir;
 492        if ((ret & UART_IIR_ID) == UART_IIR_THRI) {
 493            s->thr_ipending = 0;
 494            serial_update_irq(s);
 495        }
 496        break;
 497    case 3:
 498        ret = s->lcr;
 499        break;
 500    case 4:
 501        ret = s->mcr;
 502        break;
 503    case 5:
 504        ret = s->lsr;
 505        /* Clear break and overrun interrupts */
 506        if (s->lsr & (UART_LSR_BI|UART_LSR_OE)) {
 507            s->lsr &= ~(UART_LSR_BI|UART_LSR_OE);
 508            serial_update_irq(s);
 509        }
 510        break;
 511    case 6:
 512        if (s->mcr & UART_MCR_LOOP) {
 513            /* in loopback, the modem output pins are connected to the
 514               inputs */
 515            ret = (s->mcr & 0x0c) << 4;
 516            ret |= (s->mcr & 0x02) << 3;
 517            ret |= (s->mcr & 0x01) << 5;
 518        } else {
 519            if (s->poll_msl >= 0)
 520                serial_update_msl(s);
 521            ret = s->msr;
 522            /* Clear delta bits & msr int after read, if they were set */
 523            if (s->msr & UART_MSR_ANY_DELTA) {
 524                s->msr &= 0xF0;
 525                serial_update_irq(s);
 526            }
 527        }
 528        break;
 529    case 7:
 530        ret = s->scr;
 531        break;
 532    }
 533    DPRINTF("read addr=0x%" HWADDR_PRIx " val=0x%02x\n", addr, ret);
 534    return ret;
 535}
 536
 537static int serial_can_receive(SerialState *s)
 538{
 539    if(s->fcr & UART_FCR_FE) {
 540        if (s->recv_fifo.num < UART_FIFO_LENGTH) {
 541            /*
 542             * Advertise (fifo.itl - fifo.count) bytes when count < ITL, and 1
 543             * if above. If UART_FIFO_LENGTH - fifo.count is advertised the
 544             * effect will be to almost always fill the fifo completely before
 545             * the guest has a chance to respond, effectively overriding the ITL
 546             * that the guest has set.
 547             */
 548            return (s->recv_fifo.num <= s->recv_fifo_itl) ?
 549                        s->recv_fifo_itl - s->recv_fifo.num : 1;
 550        } else {
 551            return 0;
 552        }
 553    } else {
 554        return !(s->lsr & UART_LSR_DR);
 555    }
 556}
 557
 558static void serial_receive_break(SerialState *s)
 559{
 560    s->rbr = 0;
 561    /* When the LSR_DR is set a null byte is pushed into the fifo */
 562    recv_fifo_put(s, '\0');
 563    s->lsr |= UART_LSR_BI | UART_LSR_DR;
 564    serial_update_irq(s);
 565}
 566
 567/* There's data in recv_fifo and s->rbr has not been read for 4 char transmit times */
 568static void fifo_timeout_int (void *opaque) {
 569    SerialState *s = opaque;
 570    if (s->recv_fifo.num) {
 571        s->timeout_ipending = 1;
 572        serial_update_irq(s);
 573    }
 574}
 575
 576static int serial_can_receive1(void *opaque)
 577{
 578    SerialState *s = opaque;
 579    return serial_can_receive(s);
 580}
 581
 582static void serial_receive1(void *opaque, const uint8_t *buf, int size)
 583{
 584    SerialState *s = opaque;
 585
 586    if (s->wakeup) {
 587        qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
 588    }
 589    if(s->fcr & UART_FCR_FE) {
 590        int i;
 591        for (i = 0; i < size; i++) {
 592            recv_fifo_put(s, buf[i]);
 593        }
 594        s->lsr |= UART_LSR_DR;
 595        /* call the timeout receive callback in 4 char transmit time */
 596        timer_mod(s->fifo_timeout_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time * 4);
 597    } else {
 598        if (s->lsr & UART_LSR_DR)
 599            s->lsr |= UART_LSR_OE;
 600        s->rbr = buf[0];
 601        s->lsr |= UART_LSR_DR;
 602    }
 603    serial_update_irq(s);
 604}
 605
 606static void serial_event(void *opaque, int event)
 607{
 608    SerialState *s = opaque;
 609    DPRINTF("event %x\n", event);
 610    if (event == CHR_EVENT_BREAK)
 611        serial_receive_break(s);
 612}
 613
 614static void serial_pre_save(void *opaque)
 615{
 616    SerialState *s = opaque;
 617    s->fcr_vmstate = s->fcr;
 618}
 619
 620static int serial_pre_load(void *opaque)
 621{
 622    SerialState *s = opaque;
 623    s->thr_ipending = -1;
 624    s->poll_msl = -1;
 625    return 0;
 626}
 627
 628static int serial_post_load(void *opaque, int version_id)
 629{
 630    SerialState *s = opaque;
 631
 632    if (version_id < 3) {
 633        s->fcr_vmstate = 0;
 634    }
 635    if (s->thr_ipending == -1) {
 636        s->thr_ipending = ((s->iir & UART_IIR_ID) == UART_IIR_THRI);
 637    }
 638    s->last_break_enable = (s->lcr >> 6) & 1;
 639    /* Initialize fcr via setter to perform essential side-effects */
 640    serial_write_fcr(s, s->fcr_vmstate);
 641    serial_update_parameters(s);
 642    return 0;
 643}
 644
 645static bool serial_thr_ipending_needed(void *opaque)
 646{
 647    SerialState *s = opaque;
 648
 649    if (s->ier & UART_IER_THRI) {
 650        bool expected_value = ((s->iir & UART_IIR_ID) == UART_IIR_THRI);
 651        return s->thr_ipending != expected_value;
 652    } else {
 653        /* LSR.THRE will be sampled again when the interrupt is
 654         * enabled.  thr_ipending is not used in this case, do
 655         * not migrate it.
 656         */
 657        return false;
 658    }
 659}
 660
 661static const VMStateDescription vmstate_serial_thr_ipending = {
 662    .name = "serial/thr_ipending",
 663    .version_id = 1,
 664    .minimum_version_id = 1,
 665    .fields = (VMStateField[]) {
 666        VMSTATE_INT32(thr_ipending, SerialState),
 667        VMSTATE_END_OF_LIST()
 668    }
 669};
 670
 671static bool serial_tsr_needed(void *opaque)
 672{
 673    SerialState *s = (SerialState *)opaque;
 674    return s->tsr_retry != 0;
 675}
 676
 677static const VMStateDescription vmstate_serial_tsr = {
 678    .name = "serial/tsr",
 679    .version_id = 1,
 680    .minimum_version_id = 1,
 681    .fields = (VMStateField[]) {
 682        VMSTATE_INT32(tsr_retry, SerialState),
 683        VMSTATE_UINT8(thr, SerialState),
 684        VMSTATE_UINT8(tsr, SerialState),
 685        VMSTATE_END_OF_LIST()
 686    }
 687};
 688
 689static bool serial_recv_fifo_needed(void *opaque)
 690{
 691    SerialState *s = (SerialState *)opaque;
 692    return !fifo8_is_empty(&s->recv_fifo);
 693
 694}
 695
 696static const VMStateDescription vmstate_serial_recv_fifo = {
 697    .name = "serial/recv_fifo",
 698    .version_id = 1,
 699    .minimum_version_id = 1,
 700    .fields = (VMStateField[]) {
 701        VMSTATE_STRUCT(recv_fifo, SerialState, 1, vmstate_fifo8, Fifo8),
 702        VMSTATE_END_OF_LIST()
 703    }
 704};
 705
 706static bool serial_xmit_fifo_needed(void *opaque)
 707{
 708    SerialState *s = (SerialState *)opaque;
 709    return !fifo8_is_empty(&s->xmit_fifo);
 710}
 711
 712static const VMStateDescription vmstate_serial_xmit_fifo = {
 713    .name = "serial/xmit_fifo",
 714    .version_id = 1,
 715    .minimum_version_id = 1,
 716    .fields = (VMStateField[]) {
 717        VMSTATE_STRUCT(xmit_fifo, SerialState, 1, vmstate_fifo8, Fifo8),
 718        VMSTATE_END_OF_LIST()
 719    }
 720};
 721
 722static bool serial_fifo_timeout_timer_needed(void *opaque)
 723{
 724    SerialState *s = (SerialState *)opaque;
 725    return timer_pending(s->fifo_timeout_timer);
 726}
 727
 728static const VMStateDescription vmstate_serial_fifo_timeout_timer = {
 729    .name = "serial/fifo_timeout_timer",
 730    .version_id = 1,
 731    .minimum_version_id = 1,
 732    .fields = (VMStateField[]) {
 733        VMSTATE_TIMER_PTR(fifo_timeout_timer, SerialState),
 734        VMSTATE_END_OF_LIST()
 735    }
 736};
 737
 738static bool serial_timeout_ipending_needed(void *opaque)
 739{
 740    SerialState *s = (SerialState *)opaque;
 741    return s->timeout_ipending != 0;
 742}
 743
 744static const VMStateDescription vmstate_serial_timeout_ipending = {
 745    .name = "serial/timeout_ipending",
 746    .version_id = 1,
 747    .minimum_version_id = 1,
 748    .fields = (VMStateField[]) {
 749        VMSTATE_INT32(timeout_ipending, SerialState),
 750        VMSTATE_END_OF_LIST()
 751    }
 752};
 753
 754static bool serial_poll_needed(void *opaque)
 755{
 756    SerialState *s = (SerialState *)opaque;
 757    return s->poll_msl >= 0;
 758}
 759
 760static const VMStateDescription vmstate_serial_poll = {
 761    .name = "serial/poll",
 762    .version_id = 1,
 763    .minimum_version_id = 1,
 764    .fields = (VMStateField[]) {
 765        VMSTATE_INT32(poll_msl, SerialState),
 766        VMSTATE_TIMER_PTR(modem_status_poll, SerialState),
 767        VMSTATE_END_OF_LIST()
 768    }
 769};
 770
 771const VMStateDescription vmstate_serial = {
 772    .name = "serial",
 773    .version_id = 3,
 774    .minimum_version_id = 2,
 775    .pre_save = serial_pre_save,
 776    .pre_load = serial_pre_load,
 777    .post_load = serial_post_load,
 778    .fields = (VMStateField[]) {
 779        VMSTATE_UINT16_V(divider, SerialState, 2),
 780        VMSTATE_UINT8(rbr, SerialState),
 781        VMSTATE_UINT8(ier, SerialState),
 782        VMSTATE_UINT8(iir, SerialState),
 783        VMSTATE_UINT8(lcr, SerialState),
 784        VMSTATE_UINT8(mcr, SerialState),
 785        VMSTATE_UINT8(lsr, SerialState),
 786        VMSTATE_UINT8(msr, SerialState),
 787        VMSTATE_UINT8(scr, SerialState),
 788        VMSTATE_UINT8_V(fcr_vmstate, SerialState, 3),
 789        VMSTATE_END_OF_LIST()
 790    },
 791    .subsections = (VMStateSubsection[]) {
 792        {
 793            .vmsd = &vmstate_serial_thr_ipending,
 794            .needed = &serial_thr_ipending_needed,
 795        } , {
 796            .vmsd = &vmstate_serial_tsr,
 797            .needed = &serial_tsr_needed,
 798        } , {
 799            .vmsd = &vmstate_serial_recv_fifo,
 800            .needed = &serial_recv_fifo_needed,
 801        } , {
 802            .vmsd = &vmstate_serial_xmit_fifo,
 803            .needed = &serial_xmit_fifo_needed,
 804        } , {
 805            .vmsd = &vmstate_serial_fifo_timeout_timer,
 806            .needed = &serial_fifo_timeout_timer_needed,
 807        } , {
 808            .vmsd = &vmstate_serial_timeout_ipending,
 809            .needed = &serial_timeout_ipending_needed,
 810        } , {
 811            .vmsd = &vmstate_serial_poll,
 812            .needed = &serial_poll_needed,
 813        } , {
 814            /* empty */
 815        }
 816    }
 817};
 818
 819static void serial_reset(void *opaque)
 820{
 821    SerialState *s = opaque;
 822
 823    s->rbr = 0;
 824    s->ier = 0;
 825    s->iir = UART_IIR_NO_INT;
 826    s->lcr = 0;
 827    s->lsr = UART_LSR_TEMT | UART_LSR_THRE;
 828    s->msr = UART_MSR_DCD | UART_MSR_DSR | UART_MSR_CTS;
 829    /* Default to 9600 baud, 1 start bit, 8 data bits, 1 stop bit, no parity. */
 830    s->divider = 0x0C;
 831    s->mcr = UART_MCR_OUT2;
 832    s->scr = 0;
 833    s->tsr_retry = 0;
 834    s->char_transmit_time = (get_ticks_per_sec() / 9600) * 10;
 835    s->poll_msl = 0;
 836
 837    s->timeout_ipending = 0;
 838    timer_del(s->fifo_timeout_timer);
 839    timer_del(s->modem_status_poll);
 840
 841    fifo8_reset(&s->recv_fifo);
 842    fifo8_reset(&s->xmit_fifo);
 843
 844    s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
 845
 846    s->thr_ipending = 0;
 847    s->last_break_enable = 0;
 848    qemu_irq_lower(s->irq);
 849
 850    serial_update_msl(s);
 851    s->msr &= ~UART_MSR_ANY_DELTA;
 852}
 853
 854void serial_realize_core(SerialState *s, Error **errp)
 855{
 856    if (!s->chr) {
 857        error_setg(errp, "Can't create serial device, empty char device");
 858        return;
 859    }
 860
 861    s->modem_status_poll = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) serial_update_msl, s);
 862
 863    s->fifo_timeout_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) fifo_timeout_int, s);
 864    qemu_register_reset(serial_reset, s);
 865
 866    qemu_chr_add_handlers(s->chr, serial_can_receive1, serial_receive1,
 867                          serial_event, s);
 868    fifo8_create(&s->recv_fifo, UART_FIFO_LENGTH);
 869    fifo8_create(&s->xmit_fifo, UART_FIFO_LENGTH);
 870    serial_reset(s);
 871}
 872
 873void serial_exit_core(SerialState *s)
 874{
 875    qemu_chr_add_handlers(s->chr, NULL, NULL, NULL, NULL);
 876    qemu_unregister_reset(serial_reset, s);
 877}
 878
 879/* Change the main reference oscillator frequency. */
 880void serial_set_frequency(SerialState *s, uint32_t frequency)
 881{
 882    s->baudbase = frequency;
 883    serial_update_parameters(s);
 884}
 885
 886const MemoryRegionOps serial_io_ops = {
 887    .read = serial_ioport_read,
 888    .write = serial_ioport_write,
 889    .impl = {
 890        .min_access_size = 1,
 891        .max_access_size = 1,
 892    },
 893    .endianness = DEVICE_LITTLE_ENDIAN,
 894};
 895
 896SerialState *serial_init(int base, qemu_irq irq, int baudbase,
 897                         CharDriverState *chr, MemoryRegion *system_io)
 898{
 899    SerialState *s;
 900    Error *err = NULL;
 901
 902    s = g_malloc0(sizeof(SerialState));
 903
 904    s->irq = irq;
 905    s->baudbase = baudbase;
 906    s->chr = chr;
 907    serial_realize_core(s, &err);
 908    if (err != NULL) {
 909        error_report_err(err);
 910        exit(1);
 911    }
 912
 913    vmstate_register(NULL, base, &vmstate_serial, s);
 914
 915    memory_region_init_io(&s->io, NULL, &serial_io_ops, s, "serial", 8);
 916    memory_region_add_subregion(system_io, base, &s->io);
 917
 918    return s;
 919}
 920
 921/* Memory mapped interface */
 922static uint64_t serial_mm_read(void *opaque, hwaddr addr,
 923                               unsigned size)
 924{
 925    SerialState *s = opaque;
 926    return serial_ioport_read(s, addr >> s->it_shift, 1);
 927}
 928
 929static void serial_mm_write(void *opaque, hwaddr addr,
 930                            uint64_t value, unsigned size)
 931{
 932    SerialState *s = opaque;
 933    value &= ~0u >> (32 - (size * 8));
 934    serial_ioport_write(s, addr >> s->it_shift, value, 1);
 935}
 936
 937static const MemoryRegionOps serial_mm_ops[3] = {
 938    [DEVICE_NATIVE_ENDIAN] = {
 939        .read = serial_mm_read,
 940        .write = serial_mm_write,
 941        .endianness = DEVICE_NATIVE_ENDIAN,
 942    },
 943    [DEVICE_LITTLE_ENDIAN] = {
 944        .read = serial_mm_read,
 945        .write = serial_mm_write,
 946        .endianness = DEVICE_LITTLE_ENDIAN,
 947    },
 948    [DEVICE_BIG_ENDIAN] = {
 949        .read = serial_mm_read,
 950        .write = serial_mm_write,
 951        .endianness = DEVICE_BIG_ENDIAN,
 952    },
 953};
 954
 955SerialState *serial_mm_init(MemoryRegion *address_space,
 956                            hwaddr base, int it_shift,
 957                            qemu_irq irq, int baudbase,
 958                            CharDriverState *chr, enum device_endian end)
 959{
 960    SerialState *s;
 961    Error *err = NULL;
 962
 963    s = g_malloc0(sizeof(SerialState));
 964
 965    s->it_shift = it_shift;
 966    s->irq = irq;
 967    s->baudbase = baudbase;
 968    s->chr = chr;
 969
 970    serial_realize_core(s, &err);
 971    if (err != NULL) {
 972        error_report_err(err);
 973        exit(1);
 974    }
 975    vmstate_register(NULL, base, &vmstate_serial, s);
 976
 977    memory_region_init_io(&s->io, NULL, &serial_mm_ops[end], s,
 978                          "serial", 8 << it_shift);
 979    memory_region_add_subregion(address_space, base, &s->io);
 980    return s;
 981}
 982