static int usb_serial_handle_data(USBDevice *dev, USBPacket *p)

{

    USBSerialState *s = (USBSerialState *)dev;

    int i, ret = 0;

    uint8_t devep = p->devep;

    struct iovec *iov;

    uint8_t header[2];

    int first_len, len;

    switch (p->pid) {

    case USB_TOKEN_OUT:

        if (devep != 2)

            goto fail;

        for (i = 0; i < p->iov.niov; i++) {

            iov = p->iov.iov + i;

            qemu_chr_fe_write(s->cs, iov->iov_base, iov->iov_len);

        }

        break;

    case USB_TOKEN_IN:

        if (devep != 1)

            goto fail;

        first_len = RECV_BUF - s->recv_ptr;

        len = p->iov.size;

        if (len <= 2) {

            ret = USB_RET_NAK;

            break;

        }

        header[0] = usb_get_modem_lines(s) | 1;

        /* We do not have the uart details */

        /* handle serial break */

        if (s->event_trigger && s->event_trigger & FTDI_BI) {

            s->event_trigger &= ~FTDI_BI;

            header[1] = FTDI_BI;

            usb_packet_copy(p, header, 2);

            ret = 2;

            break;

        } else {

            header[1] = 0;

        }

        len -= 2;

        if (len > s->recv_used)

            len = s->recv_used;

        if (!len) {

            ret = USB_RET_NAK;

            break;

        }

        if (first_len > len)

            first_len = len;

        usb_packet_copy(p, header, 2);

        usb_packet_copy(p, s->recv_buf + s->recv_ptr, first_len);

        if (len > first_len)

            usb_packet_copy(p, s->recv_buf, len - first_len);

        s->recv_used -= len;

        s->recv_ptr = (s->recv_ptr + len) % RECV_BUF;

        ret = len + 2;

        break;

    default:

        DPRINTF("Bad token\n");

    fail:

        ret = USB_RET_STALL;

        break;

    }

    return ret;

}


static void handle_hmp_command(Monitor *mon, const char *cmdline)

{

    QDict *qdict;

    const mon_cmd_t *cmd;

    qdict = qdict_new();

    cmd = monitor_parse_command(mon, cmdline, 0, mon->cmd_table, qdict);

    if (cmd) {

        cmd->mhandler.cmd(mon, qdict);

    }

    QDECREF(qdict);

}


static uint16_t dummy_section(MemoryRegion *mr)

{

    MemoryRegionSection section = {

        .mr = mr,

        .offset_within_address_space = 0,

        .offset_within_region = 0,

        .size = int128_2_64(),

    };

    return phys_section_add(&section);

}


static int kvm_physical_sync_dirty_bitmap(MemoryRegionSection *section)

{

    KVMState *s = kvm_state;

    unsigned long size, allocated_size = 0;

    KVMDirtyLog d;

    KVMSlot *mem;

    int ret = 0;

    hwaddr start_addr = section->offset_within_address_space;

    hwaddr end_addr = start_addr + int128_get64(section->size);

    d.dirty_bitmap = NULL;

    while (start_addr < end_addr) {

        mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);

        if (mem == NULL) {

            break;

        }

        /* XXX bad kernel interface alert

         * For dirty bitmap, kernel allocates array of size aligned to

         * bits-per-long.  But for case when the kernel is 64bits and

         * the userspace is 32bits, userspace can't align to the same

         * bits-per-long, since sizeof(long) is different between kernel

         * and user space.  This way, userspace will provide buffer which

         * may be 4 bytes less than the kernel will use, resulting in

         * userspace memory corruption (which is not detectable by valgrind

         * too, in most cases).

         * So for now, let's align to 64 instead of HOST_LONG_BITS here, in

         * a hope that sizeof(long) wont become >8 any time soon.

         */

        size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),

                     /*HOST_LONG_BITS*/ 64) / 8;

        if (!d.dirty_bitmap) {

            d.dirty_bitmap = g_malloc(size);

        } else if (size > allocated_size) {

            d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);

        }

        allocated_size = size;

        memset(d.dirty_bitmap, 0, allocated_size);

        d.slot = mem->slot;

        if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {

            DPRINTF("ioctl failed %d\n", errno);

            ret = -1;

            break;

        }

        kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);

        start_addr = mem->start_addr + mem->memory_size;

    }

    g_free(d.dirty_bitmap);

    return ret;

}


void av_bsf_list_free(AVBSFList **lst)

{

    int i;

    if (*lst)

        return;

    for (i = 0; i < (*lst)->nb_bsfs; ++i)

        av_bsf_free(&(*lst)->bsfs[i]);

    av_free((*lst)->bsfs);

    av_freep(lst);

}


static inline int get_bat(CPUState *env, mmu_ctx_t *ctx, target_ulong virtual,

                          int rw, int type)

{

    target_ulong *BATlt, *BATut, *BATu, *BATl;

    target_ulong BEPIl, BEPIu, bl;

    int i, valid, prot;

    int ret = -1;

    LOG_BATS("%s: %cBAT v " TARGET_FMT_lx "\n", __func__,

             type == ACCESS_CODE ? 'I' : 'D', virtual);

    switch (type) {

    case ACCESS_CODE:

        BATlt = env->IBAT[1];

        BATut = env->IBAT[0];

        break;

    default:

        BATlt = env->DBAT[1];

        BATut = env->DBAT[0];

        break;

    }

    for (i = 0; i < env->nb_BATs; i++) {

        BATu = &BATut[i];

        BATl = &BATlt[i];

        BEPIu = *BATu & 0xF0000000;

        BEPIl = *BATu & 0x0FFE0000;

        if (unlikely(env->mmu_model == POWERPC_MMU_601)) {

            bat_601_size_prot(env, &bl, &valid, &prot, BATu, BATl);

        } else {

            bat_size_prot(env, &bl, &valid, &prot, BATu, BATl);

        }

        LOG_BATS("%s: %cBAT%d v " TARGET_FMT_lx " BATu " TARGET_FMT_lx

                 " BATl " TARGET_FMT_lx "\n", __func__,

                 type == ACCESS_CODE ? 'I' : 'D', i, virtual, *BATu, *BATl);

        if ((virtual & 0xF0000000) == BEPIu &&

            ((virtual & 0x0FFE0000) & ~bl) == BEPIl) {

            /* BAT matches */

            if (valid != 0) {

                /* Get physical address */

                ctx->raddr = (*BATl & 0xF0000000) |

                    ((virtual & 0x0FFE0000 & bl) | (*BATl & 0x0FFE0000)) |

                    (virtual & 0x0001F000);

                /* Compute access rights */

                ctx->prot = prot;

                ret = check_prot(ctx->prot, rw, type);

                if (ret == 0)

                    LOG_BATS("BAT %d match: r " TARGET_FMT_plx " prot=%c%c\n",

                             i, ctx->raddr, ctx->prot & PAGE_READ ? 'R' : '-',

                             ctx->prot & PAGE_WRITE ? 'W' : '-');

                break;

            }

        }

    }

    if (ret < 0) {

#if defined(DEBUG_BATS)

        if (qemu_log_enabled()) {

            LOG_BATS("no BAT match for " TARGET_FMT_lx ":\n", virtual);

            for (i = 0; i < 4; i++) {

                BATu = &BATut[i];

                BATl = &BATlt[i];

                BEPIu = *BATu & 0xF0000000;

                BEPIl = *BATu & 0x0FFE0000;

                bl = (*BATu & 0x00001FFC) << 15;

                LOG_BATS("%s: %cBAT%d v " TARGET_FMT_lx " BATu " TARGET_FMT_lx

                         " BATl " TARGET_FMT_lx " \n\t" TARGET_FMT_lx " "

                         TARGET_FMT_lx " " TARGET_FMT_lx "\n",

                         __func__, type == ACCESS_CODE ? 'I' : 'D', i, virtual,

                         *BATu, *BATl, BEPIu, BEPIl, bl);

            }

        }

#endif

    }

    /* No hit */

    return ret;

}


static int net_vde_init(VLANState *vlan, const char *model,

                        const char *name, const char *sock,

                        int port, const char *group, int mode)

{

    VDEState *s;

    char *init_group = strlen(group) ? (char *)group : NULL;

    char *init_sock = strlen(sock) ? (char *)sock : NULL;

    struct vde_open_args args = {

        .port = port,

        .group = init_group,

        .mode = mode,

    };

    s = qemu_mallocz(sizeof(VDEState));

    s->vde = vde_open(init_sock, (char *)"QEMU", &args);

    if (!s->vde){

        free(s);

        return -1;

    }

    s->vc = qemu_new_vlan_client(vlan, model, name, NULL, vde_from_qemu,

                                 NULL, vde_cleanup, s);

    qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);

    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",

             sock, vde_datafd(s->vde));

    return 0;

}


static void rtas_ibm_slot_error_detail(PowerPCCPU *cpu,

                                       sPAPREnvironment *spapr,

                                       uint32_t token, uint32_t nargs,

                                       target_ulong args, uint32_t nret,

                                       target_ulong rets)

{

    sPAPRPHBState *sphb;

    sPAPRPHBClass *spc;

    int option;

    uint64_t buid;

    if ((nargs != 8) || (nret != 1)) {

        goto param_error_exit;

    }

    buid = ((uint64_t)rtas_ld(args, 1) << 32) | rtas_ld(args, 2);

    sphb = find_phb(spapr, buid);

    if (!sphb) {

        goto param_error_exit;

    }

    spc = SPAPR_PCI_HOST_BRIDGE_GET_CLASS(sphb);

    if (!spc->eeh_set_option) {

        goto param_error_exit;

    }

    option = rtas_ld(args, 7);

    switch (option) {

    case RTAS_SLOT_TEMP_ERR_LOG:

    case RTAS_SLOT_PERM_ERR_LOG:

        break;

    default:

        goto param_error_exit;

    }

    /* We don't have error log yet */

    rtas_st(rets, 0, RTAS_OUT_NO_ERRORS_FOUND);

    return;

param_error_exit:

    rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);

}


static void lan9118_writel(void *opaque, target_phys_addr_t offset,

                           uint64_t val, unsigned size)

{

    lan9118_state *s = (lan9118_state *)opaque;

    offset &= 0xff;

    //DPRINTF("Write reg 0x%02x = 0x%08x\n", (int)offset, val);

    if (offset >= 0x20 && offset < 0x40) {

        /* TX FIFO */

        tx_fifo_push(s, val);

        return;

    }

    switch (offset) {

    case CSR_IRQ_CFG:

        /* TODO: Implement interrupt deassertion intervals.  */

        val &= (IRQ_EN | IRQ_POL | IRQ_TYPE);

        s->irq_cfg = (s->irq_cfg & IRQ_INT) | val;

        break;

    case CSR_INT_STS:

        s->int_sts &= ~val;

        break;

    case CSR_INT_EN:

        s->int_en = val & ~RESERVED_INT;

        s->int_sts |= val & SW_INT;

        break;

    case CSR_FIFO_INT:

        DPRINTF("FIFO INT levels %08x\n", val);

        s->fifo_int = val;

        break;

    case CSR_RX_CFG:

        if (val & 0x8000) {

            /* RX_DUMP */

            s->rx_fifo_used = 0;

            s->rx_status_fifo_used = 0;

            s->rx_packet_size_tail = s->rx_packet_size_head;

            s->rx_packet_size[s->rx_packet_size_head] = 0;

        }

        s->rx_cfg = val & 0xcfff1ff0;

        break;

    case CSR_TX_CFG:

        if (val & 0x8000) {

            s->tx_status_fifo_used = 0;

        }

        if (val & 0x4000) {

            s->txp->state = TX_IDLE;

            s->txp->fifo_used = 0;

            s->txp->cmd_a = 0xffffffff;

        }

        s->tx_cfg = val & 6;

        break;

    case CSR_HW_CFG:

        if (val & 1) {

            /* SRST */

            lan9118_reset(&s->busdev.qdev);

        } else {

            s->hw_cfg = (val & 0x003f300) | (s->hw_cfg & 0x4);

        }

        break;

    case CSR_RX_DP_CTRL:

        if (val & 0x80000000) {

            /* Skip forward to next packet.  */

            s->rxp_pad = 0;

            s->rxp_offset = 0;

            if (s->rxp_size == 0) {

                /* Pop a word to start the next packet.  */

                rx_fifo_pop(s);

                s->rxp_pad = 0;

                s->rxp_offset = 0;

            }

            s->rx_fifo_head += s->rxp_size;

            if (s->rx_fifo_head >= s->rx_fifo_size) {

                s->rx_fifo_head -= s->rx_fifo_size;

            }

        }

        break;

    case CSR_PMT_CTRL:

        if (val & 0x400) {

            phy_reset(s);

        }

        s->pmt_ctrl &= ~0x34e;

        s->pmt_ctrl |= (val & 0x34e);

        break;

    case CSR_GPIO_CFG:

        /* Probably just enabling LEDs.  */

        s->gpio_cfg = val & 0x7777071f;

        break;

    case CSR_GPT_CFG:

        if ((s->gpt_cfg ^ val) & GPT_TIMER_EN) {

            if (val & GPT_TIMER_EN) {

                ptimer_set_count(s->timer, val & 0xffff);

                ptimer_run(s->timer, 0);

            } else {

                ptimer_stop(s->timer);

                ptimer_set_count(s->timer, 0xffff);

            }

        }

        s->gpt_cfg = val & (GPT_TIMER_EN | 0xffff);

        break;

    case CSR_WORD_SWAP:

        /* Ignored because we're in 32-bit mode.  */

        s->word_swap = val;

        break;

    case CSR_MAC_CSR_CMD:

        s->mac_cmd = val & 0x4000000f;

        if (val & 0x80000000) {

            if (val & 0x40000000) {

                s->mac_data = do_mac_read(s, val & 0xf);

                DPRINTF("MAC read %d = 0x%08x\n", val & 0xf, s->mac_data);

            } else {

                DPRINTF("MAC write %d = 0x%08x\n", val & 0xf, s->mac_data);

                do_mac_write(s, val & 0xf, s->mac_data);

            }

        }

        break;

    case CSR_MAC_CSR_DATA:

        s->mac_data = val;

        break;

    case CSR_AFC_CFG:

        s->afc_cfg = val & 0x00ffffff;

        break;

    case CSR_E2P_CMD:

        lan9118_eeprom_cmd(s, (val >> 28) & 7, val & 0x7f);

        break;

    case CSR_E2P_DATA:

        s->e2p_data = val & 0xff;

        break;

    default:

        hw_error("lan9118_write: Bad reg 0x%x = %x\n", (int)offset, (int)val);

        break;

    }

    lan9118_update(s);

}


float64 HELPER(ucf64_muld)(float64 a, float64 b, CPUUniCore32State *env)

{

    return float64_mul(a, b, &env->ucf64.fp_status);

}


static int check_physical (CPUState *env, mmu_ctx_t *ctx,

                           target_ulong eaddr, int rw)

{

    int in_plb, ret;

    ctx->raddr = eaddr;

    ctx->prot = PAGE_READ;

    ret = 0;

    switch (env->mmu_model) {

    case POWERPC_MMU_32B:

    case POWERPC_MMU_SOFT_6xx:

    case POWERPC_MMU_SOFT_74xx:

    case POWERPC_MMU_SOFT_4xx:

    case POWERPC_MMU_REAL_4xx:

    case POWERPC_MMU_BOOKE:

        ctx->prot |= PAGE_WRITE;

        break;

#if defined(TARGET_PPC64)

    case POWERPC_MMU_64B:

        /* Real address are 60 bits long */

        ctx->raddr &= 0x0FFFFFFFFFFFFFFFULL;

        ctx->prot |= PAGE_WRITE;

        break;

#endif

    case POWERPC_MMU_SOFT_4xx_Z:

        if (unlikely(msr_pe != 0)) {

            /* 403 family add some particular protections,

             * using PBL/PBU registers for accesses with no translation.

             */

            in_plb =

                /* Check PLB validity */

                (env->pb[0] < env->pb[1] &&

                 /* and address in plb area */

                 eaddr >= env->pb[0] && eaddr < env->pb[1]) ||

                (env->pb[2] < env->pb[3] &&

                 eaddr >= env->pb[2] && eaddr < env->pb[3]) ? 1 : 0;

            if (in_plb ^ msr_px) {

                /* Access in protected area */

                if (rw == 1) {

                    /* Access is not allowed */

                    ret = -2;

                }

            } else {

                /* Read-write access is allowed */

                ctx->prot |= PAGE_WRITE;

            }

        }

        break;

    case POWERPC_MMU_BOOKE_FSL:

        /* XXX: TODO */

        cpu_abort(env, "BookE FSL MMU model not implemented\n");

        break;

    default:

        cpu_abort(env, "Unknown or invalid MMU model\n");

        return -1;

    }

    return ret;

}


static int cirrus_bitblt_videotovideo_copy(CirrusVGAState * s)

{

    if (blit_is_unsafe(s))

        return 0;

    cirrus_do_copy(s, s->cirrus_blt_dstaddr - s->vga.start_addr,

            s->cirrus_blt_srcaddr - s->vga.start_addr,

            s->cirrus_blt_width, s->cirrus_blt_height);

    return 1;

}


static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,

    int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

    BlockDriverCompletionFunc *cb, void *opaque)

{

    return bdrv_aio_writev(bs->file, sector_num, qiov, nb_sectors, cb, opaque);

}


static void xen_main_loop_prepare(XenIOState *state)

{

    int evtchn_fd = -1;

    if (state->xce_handle != XC_HANDLER_INITIAL_VALUE) {

        evtchn_fd = xc_evtchn_fd(state->xce_handle);

    }

    state->buffered_io_timer = timer_new_ms(QEMU_CLOCK_REALTIME, handle_buffered_io,

                                                 state);

    if (evtchn_fd != -1) {

        CPUState *cpu_state;

        DPRINTF("%s: Init cpu_by_vcpu_id\n", __func__);

        CPU_FOREACH(cpu_state) {

            DPRINTF("%s: cpu_by_vcpu_id[%d]=%p\n",

                    __func__, cpu_state->cpu_index, cpu_state);

            state->cpu_by_vcpu_id[cpu_state->cpu_index] = cpu_state;

        }

        qemu_set_fd_handler(evtchn_fd, cpu_handle_ioreq, NULL, state);

    }

}


static void blk_mig_cleanup(void)

{

    BlkMigDevState *bmds;

    BlkMigBlock *blk;

    bdrv_drain_all();

    unset_dirty_tracking();

    blk_mig_lock();

    while ((bmds = QSIMPLEQ_FIRST(&block_mig_state.bmds_list)) != NULL) {

        QSIMPLEQ_REMOVE_HEAD(&block_mig_state.bmds_list, entry);

        bdrv_set_in_use(bmds->bs, 0);

        bdrv_unref(bmds->bs);

        g_free(bmds->aio_bitmap);

        g_free(bmds);

    }

    while ((blk = QSIMPLEQ_FIRST(&block_mig_state.blk_list)) != NULL) {

        QSIMPLEQ_REMOVE_HEAD(&block_mig_state.blk_list, entry);

        g_free(blk->buf);

        g_free(blk);

    }

    blk_mig_unlock();

}


static int decode_rle(GetBitContext *gb, uint8_t *pal_dst, int pal_stride,

                      uint8_t *rgb_dst, int rgb_stride, uint32_t *pal,

                      int keyframe, int kf_slipt, int slice, int w, int h)

{

    uint8_t bits[270] = { 0 };

    uint32_t codes[270];

    VLC vlc;

    int current_length = 0, read_codes = 0, next_code = 0, current_codes = 0;

    int remaining_codes, surplus_codes, i;

    const int alphabet_size = 270 - keyframe;

    int last_symbol = 0, repeat = 0, prev_avail = 0;

    if (!keyframe) {

        int x, y, clipw, cliph;

        x     = get_bits(gb, 12);

        y     = get_bits(gb, 12);

        clipw = get_bits(gb, 12) + 1;

        cliph = get_bits(gb, 12) + 1;

        if (x + clipw > w || y + cliph > h)

            return AVERROR_INVALIDDATA;

        pal_dst += pal_stride * y + x;

        rgb_dst += rgb_stride * y + x * 3;

        w        = clipw;

        h        = cliph;

        if (y)

            prev_avail = 1;

    } else {

        if (slice > 0) {

            pal_dst   += pal_stride * kf_slipt;

            rgb_dst   += rgb_stride * kf_slipt;

            prev_avail = 1;

            h         -= kf_slipt;

        } else

            h = kf_slipt;

    }

    /* read explicit codes */

    do {

        while (current_codes--) {

            int symbol = get_bits(gb, 8);

            if (symbol >= 204 - keyframe)

                symbol += 14 - keyframe;

            else if (symbol > 189)

                symbol = get_bits1(gb) + (symbol << 1) - 190;

            if (bits[symbol])

                return AVERROR_INVALIDDATA;

            bits[symbol]  = current_length;

            codes[symbol] = next_code++;

            read_codes++;

        }

        current_length++;

        next_code     <<= 1;

        remaining_codes = (1 << current_length) - next_code;

        current_codes   = get_bits(gb, av_ceil_log2(remaining_codes + 1));

        if (current_length > 22 || current_codes > remaining_codes)

            return AVERROR_INVALIDDATA;

    } while (current_codes != remaining_codes);

    remaining_codes = alphabet_size - read_codes;

    /* determine the minimum length to fit the rest of the alphabet */

    while ((surplus_codes = (2 << current_length) -

                            (next_code << 1) - remaining_codes) < 0) {

        current_length++;

        next_code <<= 1;

    }

    /* add the rest of the symbols lexicographically */

    for (i = 0; i < alphabet_size; i++)

        if (!bits[i]) {

            if (surplus_codes-- == 0) {

                current_length++;

                next_code <<= 1;

            }

            bits[i]  = current_length;

            codes[i] = next_code++;

        }

    if (next_code != 1 << current_length)

        return AVERROR_INVALIDDATA;

    if (i = init_vlc(&vlc, 9, alphabet_size, bits, 1, 1, codes, 4, 4, 0))

        return i;

    /* frame decode */

    do {

        uint8_t *pp = pal_dst;

        uint8_t *rp = rgb_dst;

        do {

            if (repeat-- < 1) {

                int b = get_vlc2(gb, vlc.table, 9, 3);

                if (b < 256)

                    last_symbol = b;

                else if (b < 268) {

                    b -= 256;

                    if (b == 11)

                        b = get_bits(gb, 4) + 10;

                    if (!b)

                        repeat = 0;

                    else

                        repeat = get_bits(gb, b);

                    repeat += (1 << b) - 1;

                    if (last_symbol == -2) {

                        int skip = FFMIN(repeat, pal_dst + w - pp);

                        repeat -= skip;

                        pp     += skip;

                        rp     += skip * 3;

                    }

                } else

                    last_symbol = 267 - b;

            }

            if (last_symbol >= 0) {

                *pp = last_symbol;

                AV_WB24(rp, pal[last_symbol]);

            } else if (last_symbol == -1 && prev_avail) {

                *pp = *(pp - pal_stride);

                memcpy(rp, rp - rgb_stride, 3);

            }

            rp += 3;

        } while (++pp < pal_dst + w);

        pal_dst   += pal_stride;

        rgb_dst   += rgb_stride;

        prev_avail = 1;

    } while (--h);

    ff_free_vlc(&vlc);

    return 0;

}


static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)

{

    ARMCPU *cpu = arm_env_get_cpu(env);

    env->cp15.c3 = value;

    tlb_flush(CPU(cpu), 1); /* Flush TLB as domain not tracked in TLB */

}


void bdrv_io_unplugged_end(BlockDriverState *bs)

{

    BdrvChild *child;

    assert(bs->io_plug_disabled);

    QLIST_FOREACH(child, &bs->children, next) {

        bdrv_io_unplugged_end(child->bs);

    }

    if (--bs->io_plug_disabled == 0 && bs->io_plugged > 0) {

        BlockDriver *drv = bs->drv;

        if (drv && drv->bdrv_io_plug) {

            drv->bdrv_io_plug(bs);

        }

    }

}


static uint64_t omap_prcm_read(void *opaque, target_phys_addr_t addr,

                               unsigned size)

{

    struct omap_prcm_s *s = (struct omap_prcm_s *) opaque;

    uint32_t ret;

    if (size != 4) {

        return omap_badwidth_read32(opaque, addr);

    }

    switch (addr) {

    case 0x000:	/* PRCM_REVISION */

        return 0x10;

    case 0x010:	/* PRCM_SYSCONFIG */

        return s->sysconfig;

    case 0x018:	/* PRCM_IRQSTATUS_MPU */

        return s->irqst[0];

    case 0x01c:	/* PRCM_IRQENABLE_MPU */

        return s->irqen[0];

    case 0x050:	/* PRCM_VOLTCTRL */

        return s->voltctrl;

    case 0x054:	/* PRCM_VOLTST */

        return s->voltctrl & 3;

    case 0x060:	/* PRCM_CLKSRC_CTRL */

        return s->clksrc[0];

    case 0x070:	/* PRCM_CLKOUT_CTRL */

        return s->clkout[0];

    case 0x078:	/* PRCM_CLKEMUL_CTRL */

        return s->clkemul[0];

    case 0x080:	/* PRCM_CLKCFG_CTRL */

    case 0x084:	/* PRCM_CLKCFG_STATUS */

        return 0;

    case 0x090:	/* PRCM_VOLTSETUP */

        return s->setuptime[0];

    case 0x094:	/* PRCM_CLKSSETUP */

        return s->setuptime[1];

    case 0x098:	/* PRCM_POLCTRL */

        return s->clkpol[0];

    case 0x0b0:	/* GENERAL_PURPOSE1 */

    case 0x0b4:	/* GENERAL_PURPOSE2 */

    case 0x0b8:	/* GENERAL_PURPOSE3 */

    case 0x0bc:	/* GENERAL_PURPOSE4 */

    case 0x0c0:	/* GENERAL_PURPOSE5 */

    case 0x0c4:	/* GENERAL_PURPOSE6 */

    case 0x0c8:	/* GENERAL_PURPOSE7 */

    case 0x0cc:	/* GENERAL_PURPOSE8 */

    case 0x0d0:	/* GENERAL_PURPOSE9 */

    case 0x0d4:	/* GENERAL_PURPOSE10 */

    case 0x0d8:	/* GENERAL_PURPOSE11 */

    case 0x0dc:	/* GENERAL_PURPOSE12 */

    case 0x0e0:	/* GENERAL_PURPOSE13 */

    case 0x0e4:	/* GENERAL_PURPOSE14 */

    case 0x0e8:	/* GENERAL_PURPOSE15 */

    case 0x0ec:	/* GENERAL_PURPOSE16 */

    case 0x0f0:	/* GENERAL_PURPOSE17 */

    case 0x0f4:	/* GENERAL_PURPOSE18 */

    case 0x0f8:	/* GENERAL_PURPOSE19 */

    case 0x0fc:	/* GENERAL_PURPOSE20 */

        return s->scratch[(addr - 0xb0) >> 2];

    case 0x140:	/* CM_CLKSEL_MPU */

        return s->clksel[0];

    case 0x148:	/* CM_CLKSTCTRL_MPU */

        return s->clkctrl[0];

    case 0x158:	/* RM_RSTST_MPU */

        return s->rst[0];

    case 0x1c8:	/* PM_WKDEP_MPU */

        return s->wkup[0];

    case 0x1d4:	/* PM_EVGENCTRL_MPU */

        return s->ev;

    case 0x1d8:	/* PM_EVEGENONTIM_MPU */

        return s->evtime[0];

    case 0x1dc:	/* PM_EVEGENOFFTIM_MPU */

        return s->evtime[1];

    case 0x1e0:	/* PM_PWSTCTRL_MPU */

        return s->power[0];

    case 0x1e4:	/* PM_PWSTST_MPU */

        return 0;

    case 0x200:	/* CM_FCLKEN1_CORE */

        return s->clken[0];

    case 0x204:	/* CM_FCLKEN2_CORE */

        return s->clken[1];

    case 0x210:	/* CM_ICLKEN1_CORE */

        return s->clken[2];

    case 0x214:	/* CM_ICLKEN2_CORE */

        return s->clken[3];

    case 0x21c:	/* CM_ICLKEN4_CORE */

        return s->clken[4];

    case 0x220:	/* CM_IDLEST1_CORE */

        /* TODO: check the actual iclk status */

        return 0x7ffffff9;

    case 0x224:	/* CM_IDLEST2_CORE */

        /* TODO: check the actual iclk status */

        return 0x00000007;

    case 0x22c:	/* CM_IDLEST4_CORE */

        /* TODO: check the actual iclk status */

        return 0x0000001f;

    case 0x230:	/* CM_AUTOIDLE1_CORE */

        return s->clkidle[0];

    case 0x234:	/* CM_AUTOIDLE2_CORE */

        return s->clkidle[1];

    case 0x238:	/* CM_AUTOIDLE3_CORE */

        return s->clkidle[2];

    case 0x23c:	/* CM_AUTOIDLE4_CORE */

        return s->clkidle[3];

    case 0x240:	/* CM_CLKSEL1_CORE */

        return s->clksel[1];

    case 0x244:	/* CM_CLKSEL2_CORE */

        return s->clksel[2];

    case 0x248:	/* CM_CLKSTCTRL_CORE */

        return s->clkctrl[1];

    case 0x2a0:	/* PM_WKEN1_CORE */

        return s->wken[0];

    case 0x2a4:	/* PM_WKEN2_CORE */

        return s->wken[1];

    case 0x2b0:	/* PM_WKST1_CORE */

        return s->wkst[0];

    case 0x2b4:	/* PM_WKST2_CORE */

        return s->wkst[1];

    case 0x2c8:	/* PM_WKDEP_CORE */

        return 0x1e;

    case 0x2e0:	/* PM_PWSTCTRL_CORE */

        return s->power[1];

    case 0x2e4:	/* PM_PWSTST_CORE */

        return 0x000030 | (s->power[1] & 0xfc00);

    case 0x300:	/* CM_FCLKEN_GFX */

        return s->clken[5];

    case 0x310:	/* CM_ICLKEN_GFX */

        return s->clken[6];

    case 0x320:	/* CM_IDLEST_GFX */

        /* TODO: check the actual iclk status */

        return 0x00000001;

    case 0x340:	/* CM_CLKSEL_GFX */

        return s->clksel[3];

    case 0x348:	/* CM_CLKSTCTRL_GFX */

        return s->clkctrl[2];

    case 0x350:	/* RM_RSTCTRL_GFX */

        return s->rstctrl[0];

    case 0x358:	/* RM_RSTST_GFX */

        return s->rst[1];

    case 0x3c8:	/* PM_WKDEP_GFX */

        return s->wkup[1];

    case 0x3e0:	/* PM_PWSTCTRL_GFX */

        return s->power[2];

    case 0x3e4:	/* PM_PWSTST_GFX */

        return s->power[2] & 3;

    case 0x400:	/* CM_FCLKEN_WKUP */

        return s->clken[7];

    case 0x410:	/* CM_ICLKEN_WKUP */

        return s->clken[8];

    case 0x420:	/* CM_IDLEST_WKUP */

        /* TODO: check the actual iclk status */

        return 0x0000003f;

    case 0x430:	/* CM_AUTOIDLE_WKUP */

        return s->clkidle[4];

    case 0x440:	/* CM_CLKSEL_WKUP */

        return s->clksel[4];

    case 0x450:	/* RM_RSTCTRL_WKUP */

        return 0;

    case 0x454:	/* RM_RSTTIME_WKUP */

        return s->rsttime_wkup;

    case 0x458:	/* RM_RSTST_WKUP */

        return s->rst[2];

    case 0x4a0:	/* PM_WKEN_WKUP */

        return s->wken[2];

    case 0x4b0:	/* PM_WKST_WKUP */

        return s->wkst[2];

    case 0x500:	/* CM_CLKEN_PLL */

        return s->clken[9];

    case 0x520:	/* CM_IDLEST_CKGEN */

        ret = 0x0000070 | (s->apll_lock[0] << 9) | (s->apll_lock[1] << 8);

        if (!(s->clksel[6] & 3))

            /* Core uses 32-kHz clock */

            ret |= 3 << 0;

        else if (!s->dpll_lock)

            /* DPLL not locked, core uses ref_clk */

            ret |= 1 << 0;

        else

            /* Core uses DPLL */

            ret |= 2 << 0;

        return ret;

    case 0x530:	/* CM_AUTOIDLE_PLL */

        return s->clkidle[5];

    case 0x540:	/* CM_CLKSEL1_PLL */

        return s->clksel[5];

    case 0x544:	/* CM_CLKSEL2_PLL */

        return s->clksel[6];

    case 0x800:	/* CM_FCLKEN_DSP */

        return s->clken[10];

    case 0x810:	/* CM_ICLKEN_DSP */

        return s->clken[11];

    case 0x820:	/* CM_IDLEST_DSP */

        /* TODO: check the actual iclk status */

        return 0x00000103;

    case 0x830:	/* CM_AUTOIDLE_DSP */

        return s->clkidle[6];

    case 0x840:	/* CM_CLKSEL_DSP */

        return s->clksel[7];

    case 0x848:	/* CM_CLKSTCTRL_DSP */

        return s->clkctrl[3];

    case 0x850:	/* RM_RSTCTRL_DSP */

        return 0;

    case 0x858:	/* RM_RSTST_DSP */

        return s->rst[3];

    case 0x8c8:	/* PM_WKDEP_DSP */

        return s->wkup[2];

    case 0x8e0:	/* PM_PWSTCTRL_DSP */

        return s->power[3];

    case 0x8e4:	/* PM_PWSTST_DSP */

        return 0x008030 | (s->power[3] & 0x3003);

    case 0x8f0:	/* PRCM_IRQSTATUS_DSP */

        return s->irqst[1];

    case 0x8f4:	/* PRCM_IRQENABLE_DSP */

        return s->irqen[1];

    case 0x8f8:	/* PRCM_IRQSTATUS_IVA */

        return s->irqst[2];

    case 0x8fc:	/* PRCM_IRQENABLE_IVA */

        return s->irqen[2];

    }

    OMAP_BAD_REG(addr);

    return 0;

}


float64 HELPER(ucf64_negd)(float64 a)

{

    return float64_chs(a);

}


static int tcp_chr_add_client(CharDriverState *chr, int fd)

{

    TCPCharDriver *s = chr->opaque;

    if (s->fd != -1)

	return -1;

    qemu_set_nonblock(fd);

    if (s->do_nodelay)

        socket_set_nodelay(fd);

    s->fd = fd;

    s->chan = io_channel_from_socket(fd);

    g_source_remove(s->listen_tag);

    s->listen_tag = 0;

    tcp_chr_connect(chr);

    return 0;

}


static uint64_t omap_tipb_bridge_read(void *opaque, target_phys_addr_t addr,

                                      unsigned size)

{

    struct omap_tipb_bridge_s *s = (struct omap_tipb_bridge_s *) opaque;

    if (size < 2) {

        return omap_badwidth_read16(opaque, addr);

    }

    switch (addr) {

    case 0x00:	/* TIPB_CNTL */

        return s->control;

    case 0x04:	/* TIPB_BUS_ALLOC */

        return s->alloc;

    case 0x08:	/* MPU_TIPB_CNTL */

        return s->buffer;

    case 0x0c:	/* ENHANCED_TIPB_CNTL */

        return s->enh_control;

    case 0x10:	/* ADDRESS_DBG */

    case 0x14:	/* DATA_DEBUG_LOW */

    case 0x18:	/* DATA_DEBUG_HIGH */

        return 0xffff;

    case 0x1c:	/* DEBUG_CNTR_SIG */

        return 0x00f8;

    }

    OMAP_BAD_REG(addr);

    return 0;

}


static void lan9118_writel(void *opaque, hwaddr offset,

                           uint64_t val, unsigned size)

{

    lan9118_state *s = (lan9118_state *)opaque;

    offset &= 0xff;

    //DPRINTF("Write reg 0x%02x = 0x%08x\n", (int)offset, val);

    if (offset >= 0x20 && offset < 0x40) {

        /* TX FIFO */

        tx_fifo_push(s, val);

        return;

    }

    switch (offset) {

    case CSR_IRQ_CFG:

        /* TODO: Implement interrupt deassertion intervals.  */

        val &= (IRQ_EN | IRQ_POL | IRQ_TYPE);

        s->irq_cfg = (s->irq_cfg & IRQ_INT) | val;

        break;

    case CSR_INT_STS:

        s->int_sts &= ~val;

        break;

    case CSR_INT_EN:

        s->int_en = val & ~RESERVED_INT;

        s->int_sts |= val & SW_INT;

        break;

    case CSR_FIFO_INT:

        DPRINTF("FIFO INT levels %08x\n", val);

        s->fifo_int = val;

        break;

    case CSR_RX_CFG:

        if (val & 0x8000) {

            /* RX_DUMP */

            s->rx_fifo_used = 0;

            s->rx_status_fifo_used = 0;

            s->rx_packet_size_tail = s->rx_packet_size_head;

            s->rx_packet_size[s->rx_packet_size_head] = 0;

        }

        s->rx_cfg = val & 0xcfff1ff0;

        break;

    case CSR_TX_CFG:

        if (val & 0x8000) {

            s->tx_status_fifo_used = 0;

        }

        if (val & 0x4000) {

            s->txp->state = TX_IDLE;

            s->txp->fifo_used = 0;

            s->txp->cmd_a = 0xffffffff;

        }

        s->tx_cfg = val & 6;

        break;

    case CSR_HW_CFG:

        if (val & 1) {

            /* SRST */

            lan9118_reset(DEVICE(s));

        } else {

            s->hw_cfg = (val & 0x003f300) | (s->hw_cfg & 0x4);

        }

        break;

    case CSR_RX_DP_CTRL:

        if (val & 0x80000000) {

            /* Skip forward to next packet.  */

            s->rxp_pad = 0;

            s->rxp_offset = 0;

            if (s->rxp_size == 0) {

                /* Pop a word to start the next packet.  */

                rx_fifo_pop(s);

                s->rxp_pad = 0;

                s->rxp_offset = 0;

            }

            s->rx_fifo_head += s->rxp_size;

            if (s->rx_fifo_head >= s->rx_fifo_size) {

                s->rx_fifo_head -= s->rx_fifo_size;

            }

        }

        break;

    case CSR_PMT_CTRL:

        if (val & 0x400) {

            phy_reset(s);

        }

        s->pmt_ctrl &= ~0x34e;

        s->pmt_ctrl |= (val & 0x34e);

        break;

    case CSR_GPIO_CFG:

        /* Probably just enabling LEDs.  */

        s->gpio_cfg = val & 0x7777071f;

        break;

    case CSR_GPT_CFG:

        if ((s->gpt_cfg ^ val) & GPT_TIMER_EN) {

            if (val & GPT_TIMER_EN) {

                ptimer_set_count(s->timer, val & 0xffff);

                ptimer_run(s->timer, 0);

            } else {

                ptimer_stop(s->timer);

                ptimer_set_count(s->timer, 0xffff);

            }

        }

        s->gpt_cfg = val & (GPT_TIMER_EN | 0xffff);

        break;

    case CSR_WORD_SWAP:

        /* Ignored because we're in 32-bit mode.  */

        s->word_swap = val;

        break;

    case CSR_MAC_CSR_CMD:

        s->mac_cmd = val & 0x4000000f;

        if (val & 0x80000000) {

            if (val & 0x40000000) {

                s->mac_data = do_mac_read(s, val & 0xf);

                DPRINTF("MAC read %d = 0x%08x\n", val & 0xf, s->mac_data);

            } else {

                DPRINTF("MAC write %d = 0x%08x\n", val & 0xf, s->mac_data);

                do_mac_write(s, val & 0xf, s->mac_data);

            }

        }

        break;

    case CSR_MAC_CSR_DATA:

        s->mac_data = val;

        break;

    case CSR_AFC_CFG:

        s->afc_cfg = val & 0x00ffffff;

        break;

    case CSR_E2P_CMD:

        lan9118_eeprom_cmd(s, (val >> 28) & 7, val & 0x7f);

        break;

    case CSR_E2P_DATA:

        s->e2p_data = val & 0xff;

        break;

    default:

        hw_error("lan9118_write: Bad reg 0x%x = %x\n", (int)offset, (int)val);

        break;

    }

    lan9118_update(s);

}


int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)

{

    BlockDriver *drv;

    Error *local_err = NULL;

    int ret;

    drv = bdrv_find_protocol(filename, true, errp);

    if (drv == NULL) {

        return -ENOENT;

    }

    ret = bdrv_create(drv, filename, opts, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

    }

    return ret;

}


static int tcg_match_add2i(TCGType type, tcg_target_long val)

{

    if (facilities & FACILITY_EXT_IMM) {

        if (type == TCG_TYPE_I32) {

            return 1;

        } else if (val >= -0xffffffffll && val <= 0xffffffffll) {

            return 1;

        }

    }

    return 0;

}


int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,

                                   int nb_sectors, int *pnum)

{

    return bdrv_get_block_status(bs, sector_num, nb_sectors, pnum);

}


static void fw_cfg_init1(DeviceState *dev)

{

    FWCfgState *s = FW_CFG(dev);

    MachineState *machine = MACHINE(qdev_get_machine());

    assert(!object_resolve_path(FW_CFG_PATH, NULL));

    object_property_add_child(OBJECT(machine), FW_CFG_NAME, OBJECT(s), NULL);

    qdev_init_nofail(dev);

    fw_cfg_add_bytes(s, FW_CFG_SIGNATURE, (char *)"QEMU", 4);

    fw_cfg_add_bytes(s, FW_CFG_UUID, &qemu_uuid, 16);

    fw_cfg_add_i16(s, FW_CFG_NOGRAPHIC, (uint16_t)!machine->enable_graphics);

    fw_cfg_add_i16(s, FW_CFG_NB_CPUS, (uint16_t)smp_cpus);

    fw_cfg_add_i16(s, FW_CFG_BOOT_MENU, (uint16_t)boot_menu);

    fw_cfg_bootsplash(s);

    fw_cfg_reboot(s);

    s->machine_ready.notify = fw_cfg_machine_ready;

    qemu_add_machine_init_done_notifier(&s->machine_ready);

}


static av_cold int vsink_init(AVFilterContext *ctx, const char *args, void *opaque)

{

    BufferSinkContext *buf = ctx->priv;

    av_unused AVBufferSinkParams *params;

    if (!opaque) {

        av_log(ctx, AV_LOG_ERROR,

               "No opaque field provided\n");

        return AVERROR(EINVAL);

    } else {

#if FF_API_OLD_VSINK_API

        buf->pixel_fmts = (const enum PixelFormat *)opaque;

#else

        params = (AVBufferSinkParams *)opaque;

        buf->pixel_fmts = params->pixel_fmts;

#endif

    }

    return common_init(ctx);

}


int ff_adts_write_frame_header(ADTSContext *ctx,

                               uint8_t *buf, int size, int pce_size)

{

    PutBitContext pb;

    init_put_bits(&pb, buf, ADTS_HEADER_SIZE);

    /* adts_fixed_header */

    put_bits(&pb, 12, 0xfff);   /* syncword */

    put_bits(&pb, 1, 0);        /* ID */

    put_bits(&pb, 2, 0);        /* layer */

    put_bits(&pb, 1, 1);        /* protection_absent */

    put_bits(&pb, 2, ctx->objecttype); /* profile_objecttype */

    put_bits(&pb, 4, ctx->sample_rate_index);

    put_bits(&pb, 1, 0);        /* private_bit */

    put_bits(&pb, 3, ctx->channel_conf); /* channel_configuration */

    put_bits(&pb, 1, 0);        /* original_copy */

    put_bits(&pb, 1, 0);        /* home */

    /* adts_variable_header */

    put_bits(&pb, 1, 0);        /* copyright_identification_bit */

    put_bits(&pb, 1, 0);        /* copyright_identification_start */

    put_bits(&pb, 13, ADTS_HEADER_SIZE + size + pce_size); /* aac_frame_length */

    put_bits(&pb, 11, 0x7ff);   /* adts_buffer_fullness */

    put_bits(&pb, 2, 0);        /* number_of_raw_data_blocks_in_frame */

    flush_put_bits(&pb);

    return 0;

}


static int fbdev_read_packet(AVFormatContext *avctx, AVPacket *pkt)

{

    FBDevContext *fbdev = avctx->priv_data;

    int64_t curtime, delay;

    struct timespec ts;

    int i, ret;

    uint8_t *pin, *pout;

    if (fbdev->time_frame == AV_NOPTS_VALUE)

        fbdev->time_frame = av_gettime();

    /* wait based on the frame rate */

    while (1) {

        curtime = av_gettime();

        delay = fbdev->time_frame - curtime;

        av_dlog(avctx,

                "time_frame:%"PRId64" curtime:%"PRId64" delay:%"PRId64"\n",

                fbdev->time_frame, curtime, delay);

        if (delay <= 0) {

            fbdev->time_frame += INT64_C(1000000) * av_q2d(fbdev->time_base);

            break;

        }

        if (avctx->flags & AVFMT_FLAG_NONBLOCK)

            return AVERROR(EAGAIN);

        ts.tv_sec  =  delay / 1000000;

        ts.tv_nsec = (delay % 1000000) * 1000;

        while (nanosleep(&ts, &ts) == EINTR);

    }

    if ((ret = av_new_packet(pkt, fbdev->frame_size)) < 0)

        return ret;

    /* refresh fbdev->varinfo, visible data position may change at each call */

    if (ioctl(fbdev->fd, FBIOGET_VSCREENINFO, &fbdev->varinfo) < 0)

        av_log(avctx, AV_LOG_WARNING,

               "Error refreshing variable info: %s\n", strerror(errno));

    pkt->pts = curtime;

    /* compute visible data offset */

    pin = fbdev->data + fbdev->bytes_per_pixel * fbdev->varinfo.xoffset +

                        fbdev->varinfo.yoffset * fbdev->fixinfo.line_length;

    pout = pkt->data;

    for (i = 0; i < fbdev->heigth; i++) {

        memcpy(pout, pin, fbdev->frame_linesize);

        pin  += fbdev->fixinfo.line_length;

        pout += fbdev->frame_linesize;

    }

    return fbdev->frame_size;

}


static int virtio_ccw_set_guest_notifier(VirtioCcwDevice *dev, int n,

                                         bool assign, bool with_irqfd)

{

    VirtIODevice *vdev = virtio_bus_get_device(&dev->bus);

    VirtQueue *vq = virtio_get_queue(vdev, n);

    EventNotifier *notifier = virtio_queue_get_guest_notifier(vq);

    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);

    if (assign) {

        int r = event_notifier_init(notifier, 0);

        if (r < 0) {

            return r;

        }

        virtio_queue_set_guest_notifier_fd_handler(vq, true, with_irqfd);

        if (with_irqfd) {

            r = virtio_ccw_add_irqfd(dev, n);

            if (r) {

                virtio_queue_set_guest_notifier_fd_handler(vq, false,

                                                           with_irqfd);

                return r;

            }

        }

        /*

         * We do not support individual masking for channel devices, so we

         * need to manually trigger any guest masking callbacks here.

         */

        if (k->guest_notifier_mask) {

            k->guest_notifier_mask(vdev, n, false);

        }

        /* get lost events and re-inject */

        if (k->guest_notifier_pending &&

            k->guest_notifier_pending(vdev, n)) {

            event_notifier_set(notifier);

        }

    } else {

        if (k->guest_notifier_mask) {

            k->guest_notifier_mask(vdev, n, true);

        }

        if (with_irqfd) {

            virtio_ccw_remove_irqfd(dev, n);

        }

        virtio_queue_set_guest_notifier_fd_handler(vq, false, with_irqfd);

        event_notifier_cleanup(notifier);

    }

    return 0;

}


qemu_acl *qemu_acl_init(const char *aclname)

{

    qemu_acl *acl;

    acl = qemu_acl_find(aclname);

    if (acl)

        return acl;

    acl = qemu_malloc(sizeof(*acl));

    acl->aclname = qemu_strdup(aclname);

    /* Deny by default, so there is no window of "open

     * access" between QEMU starting, and the user setting

     * up ACLs in the monitor */

    acl->defaultDeny = 1;

    acl->nentries = 0;

    TAILQ_INIT(&acl->entries);

    acls = qemu_realloc(acls, sizeof(*acls) * (nacls +1));

    acls[nacls] = acl;

    nacls++;

    return acl;

}


static void notdirty_mem_writew(void *opaque, target_phys_addr_t ram_addr,

                                uint32_t val)

{

    int dirty_flags;

    dirty_flags = phys_ram_dirty[ram_addr >> TARGET_PAGE_BITS];

    if (!(dirty_flags & CODE_DIRTY_FLAG)) {

#if !defined(CONFIG_USER_ONLY)

        tb_invalidate_phys_page_fast(ram_addr, 2);

        dirty_flags = phys_ram_dirty[ram_addr >> TARGET_PAGE_BITS];

#endif

    }

    stw_p(qemu_get_ram_ptr(ram_addr), val);

#ifdef CONFIG_KQEMU

    if (cpu_single_env->kqemu_enabled &&

        (dirty_flags & KQEMU_MODIFY_PAGE_MASK) != KQEMU_MODIFY_PAGE_MASK)

        kqemu_modify_page(cpu_single_env, ram_addr);

#endif

    dirty_flags |= (0xff & ~CODE_DIRTY_FLAG);

    phys_ram_dirty[ram_addr >> TARGET_PAGE_BITS] = dirty_flags;

    /* we remove the notdirty callback only if the code has been

       flushed */

    if (dirty_flags == 0xff)

        tlb_set_dirty(cpu_single_env, cpu_single_env->mem_io_vaddr);

}


static void aio_signal_handler(int signum)

{

    if (posix_aio_state) {

        char byte = 0;

        write(posix_aio_state->wfd, &byte, sizeof(byte));

    }

    qemu_service_io();

}


inline qemu_irq omap_inth_get_pin(struct omap_intr_handler_s *s, int n)

{

    return s->pins[n];

}


static void realview_init(ram_addr_t ram_size,

                     const char *boot_device,

                     const char *kernel_filename, const char *kernel_cmdline,

                     const char *initrd_filename, const char *cpu_model)

{

    CPUState *env;

    ram_addr_t ram_offset;

    DeviceState *dev;

    qemu_irq *irqp;

    qemu_irq pic[64];

    PCIBus *pci_bus;

    NICInfo *nd;

    int n;

    int done_smc = 0;

    qemu_irq cpu_irq[4];

    int ncpu;

    if (!cpu_model)

        cpu_model = "arm926";

    /* FIXME: obey smp_cpus.  */

    if (strcmp(cpu_model, "arm11mpcore") == 0) {

        ncpu = 4;

    } else {

        ncpu = 1;

    }

    for (n = 0; n < ncpu; n++) {

        env = cpu_init(cpu_model);

        if (!env) {

            fprintf(stderr, "Unable to find CPU definition\n");

            exit(1);

        }

        irqp = arm_pic_init_cpu(env);

        cpu_irq[n] = irqp[ARM_PIC_CPU_IRQ];

        if (n > 0) {

            qemu_register_reset(secondary_cpu_reset, env);

        }

    }

    ram_offset = qemu_ram_alloc(ram_size);

    /* ??? RAM should repeat to fill physical memory space.  */

    /* SDRAM at address zero.  */

    cpu_register_physical_memory(0, ram_size, ram_offset | IO_MEM_RAM);

    arm_sysctl_init(0x10000000, 0xc1400400);

    if (ncpu == 1) {

        /* ??? The documentation says GIC1 is nFIQ and either GIC2 or GIC3

           is nIRQ (there are inconsistencies).  However Linux 2.6.17 expects

           GIC1 to be nIRQ and ignores all the others, so do that for now.  */

        dev = sysbus_create_simple("realview_gic", 0x10040000, cpu_irq[0]);

    } else {

        dev = sysbus_create_varargs("realview_mpcore", -1,

                                    cpu_irq[0], cpu_irq[1], cpu_irq[2],

                                    cpu_irq[3], NULL);

    }

    for (n = 0; n < 64; n++) {

        pic[n] = qdev_get_gpio_in(dev, n);

    }

    sysbus_create_simple("pl050_keyboard", 0x10006000, pic[20]);

    sysbus_create_simple("pl050_mouse", 0x10007000, pic[21]);

    sysbus_create_simple("pl011", 0x10009000, pic[12]);

    sysbus_create_simple("pl011", 0x1000a000, pic[13]);

    sysbus_create_simple("pl011", 0x1000b000, pic[14]);

    sysbus_create_simple("pl011", 0x1000c000, pic[15]);

    /* DMA controller is optional, apparently.  */

    sysbus_create_simple("pl081", 0x10030000, pic[24]);

    sysbus_create_simple("sp804", 0x10011000, pic[4]);

    sysbus_create_simple("sp804", 0x10012000, pic[5]);

    sysbus_create_simple("pl110_versatile", 0x10020000, pic[23]);

    sysbus_create_varargs("pl181", 0x10005000, pic[17], pic[18], NULL);

    sysbus_create_simple("pl031", 0x10017000, pic[10]);

    dev = sysbus_create_varargs("realview_pci", 0x60000000,

                                pic[48], pic[49], pic[50], pic[51], NULL);

    pci_bus = (PCIBus *)qdev_get_child_bus(dev, "pci");

    if (usb_enabled) {

        usb_ohci_init_pci(pci_bus, -1);

    }

    n = drive_get_max_bus(IF_SCSI);

    while (n >= 0) {

        pci_create_simple(pci_bus, -1, "lsi53c895a");

        n--;

    }

    for(n = 0; n < nb_nics; n++) {

        nd = &nd_table[n];

        if ((!nd->model && !done_smc) || strcmp(nd->model, "smc91c111") == 0) {

            smc91c111_init(nd, 0x4e000000, pic[28]);

            done_smc = 1;

        } else {

            pci_nic_init_nofail(nd, "rtl8139", NULL);

        }

    }

    /* Memory map for RealView Emulation Baseboard:  */

    /* 0x10000000 System registers.  */

    /*  0x10001000 System controller.  */

    /*  0x10002000 Two-Wire Serial Bus.  */

    /* 0x10003000 Reserved.  */

    /*  0x10004000 AACI.  */

    /*  0x10005000 MCI.  */

    /* 0x10006000 KMI0.  */

    /* 0x10007000 KMI1.  */

    /*  0x10008000 Character LCD.  */

    /* 0x10009000 UART0.  */

    /* 0x1000a000 UART1.  */

    /* 0x1000b000 UART2.  */

    /* 0x1000c000 UART3.  */

    /*  0x1000d000 SSPI.  */

    /*  0x1000e000 SCI.  */

    /* 0x1000f000 Reserved.  */

    /*  0x10010000 Watchdog.  */

    /* 0x10011000 Timer 0+1.  */

    /* 0x10012000 Timer 2+3.  */

    /*  0x10013000 GPIO 0.  */

    /*  0x10014000 GPIO 1.  */

    /*  0x10015000 GPIO 2.  */

    /* 0x10016000 Reserved.  */

    /* 0x10017000 RTC.  */

    /*  0x10018000 DMC.  */

    /*  0x10019000 PCI controller config.  */

    /*  0x10020000 CLCD.  */

    /* 0x10030000 DMA Controller.  */

    /* 0x10040000 GIC1.  */

    /* 0x10050000 GIC2.  */

    /* 0x10060000 GIC3.  */

    /* 0x10070000 GIC4.  */

    /*  0x10080000 SMC.  */

    /*  0x40000000 NOR flash.  */

    /*  0x44000000 DoC flash.  */

    /*  0x48000000 SRAM.  */

    /*  0x4c000000 Configuration flash.  */

    /* 0x4e000000 Ethernet.  */

    /*  0x4f000000 USB.  */

    /*  0x50000000 PISMO.  */

    /*  0x54000000 PISMO.  */

    /*  0x58000000 PISMO.  */

    /*  0x5c000000 PISMO.  */

    /* 0x60000000 PCI.  */

    /* 0x61000000 PCI Self Config.  */

    /* 0x62000000 PCI Config.  */

    /* 0x63000000 PCI IO.  */

    /* 0x64000000 PCI mem 0.  */

    /* 0x68000000 PCI mem 1.  */

    /* 0x6c000000 PCI mem 2.  */

    /* ??? Hack to map an additional page of ram for the secondary CPU

       startup code.  I guess this works on real hardware because the

       BootROM happens to be in ROM/flash or in memory that isn't clobbered

       until after Linux boots the secondary CPUs.  */

    ram_offset = qemu_ram_alloc(0x1000);

    cpu_register_physical_memory(0x80000000, 0x1000, ram_offset | IO_MEM_RAM);

    realview_binfo.ram_size = ram_size;

    realview_binfo.kernel_filename = kernel_filename;

    realview_binfo.kernel_cmdline = kernel_cmdline;

    realview_binfo.initrd_filename = initrd_filename;

    realview_binfo.nb_cpus = ncpu;

    arm_load_kernel(first_cpu, &realview_binfo);

}


static void gen_cop1_ldst(DisasContext *ctx, uint32_t op, int rt,

                          int rs, int16_t imm)

{

    if (ctx->CP0_Config1 & (1 << CP0C1_FP)) {

        check_cp1_enabled(ctx);

        gen_flt_ldst(ctx, op, rt, rs, imm);

    } else {

        generate_exception_err(ctx, EXCP_CpU, 1);

    }

}


static IOMMUTLBEntry s390_translate_iommu(MemoryRegion *mr, hwaddr addr,

                                          bool is_write)

{

    uint64_t pte;

    uint32_t flags;

    S390PCIIOMMU *iommu = container_of(mr, S390PCIIOMMU, iommu_mr);

    IOMMUTLBEntry ret = {

        .target_as = &address_space_memory,

        .iova = 0,

        .translated_addr = 0,

        .addr_mask = ~(hwaddr)0,

        .perm = IOMMU_NONE,

    };

    switch (iommu->pbdev->state) {

    case ZPCI_FS_ENABLED:

    case ZPCI_FS_BLOCKED:

        if (!iommu->enabled) {

            return ret;

        }

        break;

    default:

        return ret;

    }

    DPRINTF("iommu trans addr 0x%" PRIx64 "\n", addr);

    if (addr < iommu->pba || addr > iommu->pal) {

        return ret;

    }

    pte = s390_guest_io_table_walk(s390_pci_get_table_origin(iommu->g_iota),

                                   addr);

    if (!pte) {

        return ret;

    }

    flags = pte & ZPCI_PTE_FLAG_MASK;

    ret.iova = addr;

    ret.translated_addr = pte & ZPCI_PTE_ADDR_MASK;

    ret.addr_mask = 0xfff;

    if (flags & ZPCI_PTE_INVALID) {

        ret.perm = IOMMU_NONE;

    } else {

        ret.perm = IOMMU_RW;

    }

    return ret;

}


static void spr_write_dbatl (void *opaque, int sprn)

{

    DisasContext *ctx = opaque;

    gen_op_store_dbatl((sprn - SPR_DBAT0L) / 2);

    RET_STOP(ctx);

}


static uint32_t vbe_ioport_read_index(void *opaque, uint32_t addr)

{

    VGACommonState *s = opaque;

    uint32_t val;

    val = s->vbe_index;

    return val;

}


static int decode_dds1(GetByteContext *gb, uint8_t *frame, int width, int height)

{

    const uint8_t *frame_start = frame;

    const uint8_t *frame_end   = frame + width * height;

    int mask = 0x10000, bitbuf = 0;

    int i, v, offset, count, segments;

    segments = bytestream2_get_le16(gb);

    while (segments--) {

        if (bytestream2_get_bytes_left(gb) < 2)

            return -1;

        if (mask == 0x10000) {

            bitbuf = bytestream2_get_le16u(gb);

            mask = 1;

        }

        if (frame_end - frame < 2)

            return -1;

        if (bitbuf & mask) {

            v = bytestream2_get_le16(gb);

            offset = (v & 0x1FFF) << 2;

            count = ((v >> 13) + 2) << 1;

            if (frame - frame_start < offset || frame_end - frame < count*2 + width)

                return -1;

            for (i = 0; i < count; i++) {

                frame[0] = frame[1] =

                frame[width] = frame[width + 1] = frame[-offset];

                frame += 2;

            }

        } else if (bitbuf & (mask << 1)) {

            frame += bytestream2_get_le16(gb) * 2;

        } else {

            frame[0] = frame[1] =

            frame[width] = frame[width + 1] =  bytestream2_get_byte(gb);

            frame += 2;

            frame[0] = frame[1] =

            frame[width] = frame[width + 1] =  bytestream2_get_byte(gb);

            frame += 2;

        }

        mask <<= 2;

    }

    return 0;

}


static void netmap_update_fd_handler(NetmapState *s)

{

    qemu_set_fd_handler2(s->me.fd,

                         s->read_poll  ? netmap_can_send : NULL,

                         s->read_poll  ? netmap_send     : NULL,

                         s->write_poll ? netmap_writable : NULL,

                         s);

}


static sPAPRDREntitySense logical_entity_sense(sPAPRDRConnector *drc)

{

    if (drc->dev

        && (drc->allocation_state != SPAPR_DR_ALLOCATION_STATE_UNUSABLE)) {

        return SPAPR_DR_ENTITY_SENSE_PRESENT;

    } else {

        return SPAPR_DR_ENTITY_SENSE_UNUSABLE;

    }

}


void x86_cpudef_setup(void)

{

    int i, j;

    static const char *model_with_versions[] = { "qemu32", "qemu64", "athlon" };

    for (i = 0; i < ARRAY_SIZE(builtin_x86_defs); ++i) {

        X86CPUDefinition *def = &builtin_x86_defs[i];

        /* Look for specific "cpudef" models that */

        /* have the QEMU version in .model_id */

        for (j = 0; j < ARRAY_SIZE(model_with_versions); j++) {

            if (strcmp(model_with_versions[j], def->name) == 0) {

                pstrcpy(def->model_id, sizeof(def->model_id),

                        "QEMU Virtual CPU version ");

                pstrcat(def->model_id, sizeof(def->model_id),

                        qemu_get_version());

                break;

            }

        }

    }

}


static int scsi_read_dvd_structure(SCSIDiskState *s, SCSIDiskReq *r,

                                   uint8_t *outbuf)

{

    static const int rds_caps_size[5] = {

        [0] = 2048 + 4,

        [1] = 4 + 4,

        [3] = 188 + 4,

        [4] = 2048 + 4,

    };

    uint8_t media = r->req.cmd.buf[1];

    uint8_t layer = r->req.cmd.buf[6];

    uint8_t format = r->req.cmd.buf[7];

    int size = -1;

    if (s->qdev.type != TYPE_ROM) {

        return -1;

    }

    if (media != 0) {

        scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));

        return -1;

    }

    if (format != 0xff) {

        if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) {

            scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));

            return -1;

        }

        if (media_is_cd(s)) {

            scsi_check_condition(r, SENSE_CODE(INCOMPATIBLE_FORMAT));

            return -1;

        }

        if (format >= ARRAY_SIZE(rds_caps_size)) {

            return -1;

        }

        size = rds_caps_size[format];

        memset(outbuf, 0, size);

    }

    switch (format) {

    case 0x00: {

        /* Physical format information */

        uint64_t nb_sectors;

        if (layer != 0) {

            goto fail;

        }

        bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);

        outbuf[4] = 1;   /* DVD-ROM, part version 1 */

        outbuf[5] = 0xf; /* 120mm disc, minimum rate unspecified */

        outbuf[6] = 1;   /* one layer, read-only (per MMC-2 spec) */

        outbuf[7] = 0;   /* default densities */

        stl_be_p(&outbuf[12], (nb_sectors >> 2) - 1); /* end sector */

        stl_be_p(&outbuf[16], (nb_sectors >> 2) - 1); /* l0 end sector */

        break;

    }

    case 0x01: /* DVD copyright information, all zeros */

        break;

    case 0x03: /* BCA information - invalid field for no BCA info */

        return -1;

    case 0x04: /* DVD disc manufacturing information, all zeros */

        break;

    case 0xff: { /* List capabilities */

        int i;

        size = 4;

        for (i = 0; i < ARRAY_SIZE(rds_caps_size); i++) {

            if (!rds_caps_size[i]) {

                continue;

            }

            outbuf[size] = i;

            outbuf[size + 1] = 0x40; /* Not writable, readable */

            stw_be_p(&outbuf[size + 2], rds_caps_size[i]);

            size += 4;

        }

        break;

     }

    default:

        return -1;

    }

    /* Size of buffer, not including 2 byte size field */

    stw_be_p(outbuf, size - 2);

    return size;

fail:

    return -1;

}


START_TEST(qdict_get_not_exists_test)

{

    fail_unless(qdict_get(tests_dict, "foo") == NULL);

}


int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)

{

    BlockDriverState *bs;

    int ret;

    bs = bdrv_new("");

    if (!bs)

        return -ENOMEM;

    ret = bdrv_open2(bs, filename, flags | BDRV_O_FILE, NULL);

    if (ret < 0) {

        bdrv_delete(bs);

        return ret;

    }

    bs->growable = 1;

    *pbs = bs;

    return 0;

}


size_t slirp_socket_can_recv(Slirp *slirp, struct in_addr guest_addr,

                             int guest_port)

{

	struct iovec iov[2];

	struct socket *so;

	so = slirp_find_ctl_socket(slirp, guest_addr, guest_port);

	if (!so || so->so_state & SS_NOFDREF)

		return 0;

	if (!CONN_CANFRCV(so) || so->so_snd.sb_cc >= (so->so_snd.sb_datalen/2))

		return 0;

	return sopreprbuf(so, iov, NULL);

}


static void openpic_save(QEMUFile* f, void *opaque)

{

    OpenPICState *opp = (OpenPICState *)opaque;

    unsigned int i;

    qemu_put_be32s(f, &opp->glbc);

    qemu_put_be32s(f, &opp->veni);

    qemu_put_be32s(f, &opp->pint);

    qemu_put_be32s(f, &opp->spve);

    qemu_put_be32s(f, &opp->tifr);

    for (i = 0; i < opp->max_irq; i++) {

        qemu_put_be32s(f, &opp->src[i].ipvp);

        qemu_put_be32s(f, &opp->src[i].ide);

        qemu_put_sbe32s(f, &opp->src[i].last_cpu);

        qemu_put_sbe32s(f, &opp->src[i].pending);

    }

    qemu_put_be32s(f, &opp->nb_cpus);

    for (i = 0; i < opp->nb_cpus; i++) {

        qemu_put_be32s(f, &opp->dst[i].pctp);

        qemu_put_be32s(f, &opp->dst[i].pcsr);

        openpic_save_IRQ_queue(f, &opp->dst[i].raised);

        openpic_save_IRQ_queue(f, &opp->dst[i].servicing);

    }

    for (i = 0; i < MAX_TMR; i++) {

        qemu_put_be32s(f, &opp->timers[i].ticc);

        qemu_put_be32s(f, &opp->timers[i].tibc);

    }

}


static int ac3_parse_sync_info(AC3DecodeContext *ctx)

{

    ac3_sync_info *sync_info = &ctx->sync_info;

    GetBitContext *gb = &ctx->gb;

    sync_info->sync_word = get_bits(gb, 16);

    sync_info->crc1 = get_bits(gb, 16);

    sync_info->fscod = get_bits(gb, 2);

    if (sync_info->fscod == 0x03)

        return -1;

    sync_info->frmsizecod = get_bits(gb, 6);

    if (sync_info->frmsizecod >= 0x38)

        return -1;

    sync_info->sampling_rate = ac3_freqs[sync_info->fscod];

    sync_info->bit_rate = ac3_bitratetab[sync_info->frmsizecod >> 1];

    return 0;

}


static int curl_open(BlockDriverState *bs, QDict *options, int flags,

                     Error **errp)

{

    BDRVCURLState *s = bs->opaque;

    CURLState *state = NULL;

    QemuOpts *opts;

    Error *local_err = NULL;

    const char *file;

    double d;

    static int inited = 0;

    if (flags & BDRV_O_RDWR) {

        error_setg(errp, "curl block device does not support writes");

        return -EROFS;

    }

    opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        goto out_noclean;

    }

    s->readahead_size = qemu_opt_get_size(opts, "readahead", READ_AHEAD_SIZE);

    if ((s->readahead_size & 0x1ff) != 0) {

        error_setg(errp, "HTTP_READAHEAD_SIZE %zd is not a multiple of 512",

                   s->readahead_size);

        goto out_noclean;

    }

    file = qemu_opt_get(opts, "url");

    if (file == NULL) {

        error_setg(errp, "curl block driver requires an 'url' option");

        goto out_noclean;

    }

    if (!inited) {

        curl_global_init(CURL_GLOBAL_ALL);

        inited = 1;

    }

    DPRINTF("CURL: Opening %s\n", file);

    s->url = g_strdup(file);

    state = curl_init_state(s);

    if (!state)

        goto out_noclean;

    // Get file size

    s->accept_range = false;

    curl_easy_setopt(state->curl, CURLOPT_NOBODY, 1);

    curl_easy_setopt(state->curl, CURLOPT_HEADERFUNCTION,

                     curl_header_cb);

    curl_easy_setopt(state->curl, CURLOPT_HEADERDATA, s);

    if (curl_easy_perform(state->curl))

        goto out;

    curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d);

    if (d)

        s->len = (size_t)d;

    else if(!s->len)

        goto out;

    if ((!strncasecmp(s->url, "http://", strlen("http://"))

        || !strncasecmp(s->url, "https://", strlen("https://")))

        && !s->accept_range) {

        pstrcpy(state->errmsg, CURL_ERROR_SIZE,

                "Server does not support 'range' (byte ranges).");

        goto out;

    }

    DPRINTF("CURL: Size = %zd\n", s->len);

    curl_clean_state(state);

    curl_easy_cleanup(state->curl);

    state->curl = NULL;

    aio_timer_init(bdrv_get_aio_context(bs), &s->timer,

                   QEMU_CLOCK_REALTIME, SCALE_NS,

                   curl_multi_timeout_do, s);

    // Now we know the file exists and its size, so let's

    // initialize the multi interface!

    s->multi = curl_multi_init();

    curl_multi_setopt(s->multi, CURLMOPT_SOCKETDATA, s);

    curl_multi_setopt(s->multi, CURLMOPT_SOCKETFUNCTION, curl_sock_cb);

#ifdef NEED_CURL_TIMER_CALLBACK

    curl_multi_setopt(s->multi, CURLMOPT_TIMERDATA, s);

    curl_multi_setopt(s->multi, CURLMOPT_TIMERFUNCTION, curl_timer_cb);

#endif

    qemu_opts_del(opts);

    return 0;

out:

    error_setg(errp, "CURL: Error opening file: %s", state->errmsg);

    curl_easy_cleanup(state->curl);

    state->curl = NULL;

out_noclean:

    g_free(s->url);

    qemu_opts_del(opts);

    return -EINVAL;

}


static int raw_truncate(BlockDriverState *bs, int64_t offset)

{

    BDRVRawState *s = bs->opaque;

    LONG low, high;

    low = offset;

    high = offset >> 32;

    if (!SetFilePointer(s->hfile, low, &high, FILE_BEGIN))

	return -EIO;

    if (!SetEndOfFile(s->hfile))

        return -EIO;

    return 0;

}


static bool tb_invalidate_phys_page(tb_page_addr_t addr, uintptr_t pc)

{

    TranslationBlock *tb;

    PageDesc *p;

    int n;

#ifdef TARGET_HAS_PRECISE_SMC

    TranslationBlock *current_tb = NULL;

    CPUState *cpu = current_cpu;

    CPUArchState *env = NULL;

    int current_tb_modified = 0;

    target_ulong current_pc = 0;

    target_ulong current_cs_base = 0;

    uint32_t current_flags = 0;

#endif

    assert_memory_lock();

    addr &= TARGET_PAGE_MASK;

    p = page_find(addr >> TARGET_PAGE_BITS);

    if (!p) {

        return false;

    }

    tb_lock();

    tb = p->first_tb;

#ifdef TARGET_HAS_PRECISE_SMC

    if (tb && pc != 0) {

        current_tb = tb_find_pc(pc);

    }

    if (cpu != NULL) {

        env = cpu->env_ptr;

    }

#endif

    while (tb != NULL) {

        n = (uintptr_t)tb & 3;

        tb = (TranslationBlock *)((uintptr_t)tb & ~3);

#ifdef TARGET_HAS_PRECISE_SMC

        if (current_tb == tb &&

            (current_tb->cflags & CF_COUNT_MASK) != 1) {

                /* If we are modifying the current TB, we must stop

                   its execution. We could be more precise by checking

                   that the modification is after the current PC, but it

                   would require a specialized function to partially

                   restore the CPU state */

            current_tb_modified = 1;

            cpu_restore_state_from_tb(cpu, current_tb, pc);

            cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base,

                                 &current_flags);

        }

#endif /* TARGET_HAS_PRECISE_SMC */

        tb_phys_invalidate(tb, addr);

        tb = tb->page_next[n];

    }

    p->first_tb = NULL;

#ifdef TARGET_HAS_PRECISE_SMC

    if (current_tb_modified) {

        /* we generate a block containing just the instruction

           modifying the memory. It will ensure that it cannot modify

           itself */

        tb_gen_code(cpu, current_pc, current_cs_base, current_flags,

                    1 | curr_cflags());

        /* tb_lock will be reset after cpu_loop_exit_noexc longjmps

         * back into the cpu_exec loop. */

        return true;

    }

#endif

    tb_unlock();

    return false;

}


static int64_t raw_getlength(BlockDriverState *bs)

{

    int64_t len;

    BDRVRawState *s = bs->opaque;

    /* Update size. It should not change unless the file was externally

     * modified. */

    len = bdrv_getlength(bs->file->bs);

    if (len < 0) {

        return len;

    }

    if (len < s->offset) {

        s->size = 0;

    } else {

        if (s->has_size) {

            /* Try to honour the size */

            s->size = MIN(s->size, len - s->offset);

        } else {

            s->size = len - s->offset;

        }

    }

    return s->size;

}


void omap_rfbi_attach(struct omap_dss_s *s, int cs, struct rfbi_chip_s *chip)

{

    if (cs < 0 || cs > 1)

        hw_error("%s: wrong CS %i\n", __FUNCTION__, cs);

    s->rfbi.chip[cs] = chip;

}


int kvm_arch_init(MachineState *ms, KVMState *s)

{

    MachineClass *mc = MACHINE_GET_CLASS(ms);

    mc->default_cpu_type = S390_CPU_TYPE_NAME("host");

    cap_sync_regs = kvm_check_extension(s, KVM_CAP_SYNC_REGS);

    cap_async_pf = kvm_check_extension(s, KVM_CAP_ASYNC_PF);

    cap_mem_op = kvm_check_extension(s, KVM_CAP_S390_MEM_OP);

    cap_s390_irq = kvm_check_extension(s, KVM_CAP_S390_INJECT_IRQ);

    if (!kvm_check_extension(s, KVM_CAP_S390_GMAP)

        || !kvm_check_extension(s, KVM_CAP_S390_COW)) {

        phys_mem_set_alloc(legacy_s390_alloc);

    }

    kvm_vm_enable_cap(s, KVM_CAP_S390_USER_SIGP, 0);

    kvm_vm_enable_cap(s, KVM_CAP_S390_VECTOR_REGISTERS, 0);

    kvm_vm_enable_cap(s, KVM_CAP_S390_USER_STSI, 0);

    if (ri_allowed()) {

        if (kvm_vm_enable_cap(s, KVM_CAP_S390_RI, 0) == 0) {

            cap_ri = 1;

        }

    }

    if (gs_allowed()) {

        if (kvm_vm_enable_cap(s, KVM_CAP_S390_GS, 0) == 0) {

            cap_gs = 1;

        }

    }

    /*

     * The migration interface for ais was introduced with kernel 4.13

     * but the capability itself had been active since 4.12. As migration

     * support is considered necessary let's disable ais in the 2.10

     * machine.

     */

    /* kvm_vm_enable_cap(s, KVM_CAP_S390_AIS, 0); */

    qemu_mutex_init(&qemu_sigp_mutex);

    return 0;

}