static void do_subtitle_out(AVFormatContext *s,
                            OutputStream *ost,
                            InputStream *ist,
                            AVSubtitle *sub)
{
    int subtitle_out_max_size = 1024 * 1024;
    int subtitle_out_size, nb, i;
    AVCodecContext *enc;
    AVPacket pkt;
    int64_t pts;
    if (sub->pts == AV_NOPTS_VALUE) {
        av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
        if (exit_on_error)
            exit_program(1);
        return;
    }
    enc = ost->enc_ctx;
    if (!subtitle_out) {
        subtitle_out = av_malloc(subtitle_out_max_size);
    }
    /* Note: DVB subtitle need one packet to draw them and one other
       packet to clear them */
    /* XXX: signal it in the codec context ? */
    if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
        nb = 2;
    else
        nb = 1;
    /* shift timestamp to honor -ss and make check_recording_time() work with -t */
    pts = sub->pts;
    if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)
        pts -= output_files[ost->file_index]->start_time;
    for (i = 0; i < nb; i++) {
        ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
        if (!check_recording_time(ost))
            return;
        sub->pts = pts;
        // start_display_time is required to be 0
        sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
        sub->end_display_time  -= sub->start_display_time;
        sub->start_display_time = 0;
        if (i == 1)
            sub->num_rects = 0;
        ost->frames_encoded++;
        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
                                                    subtitle_out_max_size, sub);
        if (i == 1)
            sub->num_rects = save_num_rects;
        if (subtitle_out_size < 0) {
            av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
            exit_program(1);
        }
        av_init_packet(&pkt);
        pkt.data = subtitle_out;
        pkt.size = subtitle_out_size;
        pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
        pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
        if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
            /* XXX: the pts correction is handled here. Maybe handling
               it in the codec would be better */
            if (i == 0)
                pkt.pts += 90 * sub->start_display_time;
            else
                pkt.pts += 90 * sub->end_display_time;
        }
        pkt.dts = pkt.pts;
        write_frame(s, &pkt, ost);
    }
}


static uint32_t uhci_ioport_readw(void *opaque, uint32_t addr)

{

    UHCIState *s = opaque;

    uint32_t val;

    addr &= 0x1f;

    switch(addr) {

    case 0x00:

        val = s->cmd;

        break;

    case 0x02:

        val = s->status;

        break;

    case 0x04:

        val = s->intr;

        break;

    case 0x06:

        val = s->frnum;

        break;

    case 0x10 ... 0x1f:

        {

            UHCIPort *port;

            int n;

            n = (addr >> 1) & 7;

            if (n >= NB_PORTS)

                goto read_default;

            port = &s->ports[n];

            val = port->ctrl;

        }

        break;

    default:

    read_default:

        val = 0xff7f; /* disabled port */

        break;

    }

#ifdef DEBUG

    printf("uhci readw port=0x%04x val=0x%04x\n", addr, val);

#endif

    return val;

}


cac_delete_pki_applet_private(VCardAppletPrivate *applet_private)

{

    CACPKIAppletData *pki_applet_data = NULL;

    if (applet_private == NULL) {

        return;

    }

    pki_applet_data = &(applet_private->u.pki_data);

    if (pki_applet_data->cert != NULL) {

        g_free(pki_applet_data->cert);

    }

    if (pki_applet_data->sign_buffer != NULL) {

        g_free(pki_applet_data->sign_buffer);

    }

    if (pki_applet_data->key != NULL) {

        vcard_emul_delete_key(pki_applet_data->key);

    }

    g_free(applet_private);

}


static void cpu_handle_debug_exception(CPUState *env)

{

    CPUWatchpoint *wp;

    if (!env->watchpoint_hit)

        TAILQ_FOREACH(wp, &env->watchpoints, entry)

            wp->flags &= ~BP_WATCHPOINT_HIT;

    if (debug_excp_handler)

        debug_excp_handler(env);

}


static int do_co_pwrite_zeroes(BlockBackend *blk, int64_t offset,

                               int64_t count, int flags, int64_t *total)

{

    Coroutine *co;

    CoWriteZeroes data = {

        .blk    = blk,

        .offset = offset,

        .count  = count,

        .total  = total,

        .flags  = flags,

        .done   = false,

    };

    if (count >> BDRV_SECTOR_BITS > INT_MAX) {

        return -ERANGE;

    }

    co = qemu_coroutine_create(co_pwrite_zeroes_entry, &data);

    qemu_coroutine_enter(co);

    while (!data.done) {

        aio_poll(blk_get_aio_context(blk), true);

    }

    if (data.ret < 0) {

        return data.ret;

    } else {

        return 1;

    }

}


static inline void cow_set_bits(uint8_t *bitmap, int start, int64_t nb_sectors)

{

    int64_t bitnum = start, last = start + nb_sectors;

    while (bitnum < last) {

        if ((bitnum & 7) == 0 && bitnum + 8 <= last) {

            bitmap[bitnum / 8] = 0xFF;

            bitnum += 8;

            continue;

        }

        bitmap[bitnum/8] |= (1 << (bitnum % 8));

        bitnum++;

    }

}


int bdrv_open2(BlockDriverState *bs, const char *filename, int flags,

               BlockDriver *drv)

{

    int ret, open_flags;

    char tmp_filename[PATH_MAX];

    char backing_filename[PATH_MAX];

    bs->is_temporary = 0;

    bs->encrypted = 0;

    bs->valid_key = 0;

    /* buffer_alignment defaulted to 512, drivers can change this value */

    bs->buffer_alignment = 512;

    if (flags & BDRV_O_SNAPSHOT) {

        BlockDriverState *bs1;

        int64_t total_size;

        int is_protocol = 0;

        BlockDriver *bdrv_qcow2;

        QEMUOptionParameter *options;

        /* if snapshot, we create a temporary backing file and open it

           instead of opening 'filename' directly */

        /* if there is a backing file, use it */

        bs1 = bdrv_new("");

        ret = bdrv_open2(bs1, filename, 0, drv);

        if (ret < 0) {

            bdrv_delete(bs1);

            return ret;

        }

        total_size = bdrv_getlength(bs1) >> BDRV_SECTOR_BITS;

        if (bs1->drv && bs1->drv->protocol_name)

            is_protocol = 1;

        bdrv_delete(bs1);

        get_tmp_filename(tmp_filename, sizeof(tmp_filename));

        /* Real path is meaningless for protocols */

        if (is_protocol)

            snprintf(backing_filename, sizeof(backing_filename),

                     "%s", filename);

        else if (!realpath(filename, backing_filename))

            return -errno;

        bdrv_qcow2 = bdrv_find_format("qcow2");

        options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);

        set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size * 512);

        set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);

        if (drv) {

            set_option_parameter(options, BLOCK_OPT_BACKING_FMT,

                drv->format_name);

        }

        ret = bdrv_create(bdrv_qcow2, tmp_filename, options);

        if (ret < 0) {

            return ret;

        }

        filename = tmp_filename;

        drv = bdrv_qcow2;

        bs->is_temporary = 1;

    }

    pstrcpy(bs->filename, sizeof(bs->filename), filename);

    if (flags & BDRV_O_FILE) {

        drv = find_protocol(filename);

    } else if (!drv) {

        drv = find_hdev_driver(filename);

        if (!drv) {

            drv = find_image_format(filename);

        }

    }

    if (!drv) {

        ret = -ENOENT;

        goto unlink_and_fail;

    }

    bs->drv = drv;

    bs->opaque = qemu_mallocz(drv->instance_size);

    /*

     * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a

     * write cache to the guest.  We do need the fdatasync to flush

     * out transactions for block allocations, and we maybe have a

     * volatile write cache in our backing device to deal with.

     */

    if (flags & (BDRV_O_CACHE_WB|BDRV_O_NOCACHE))

        bs->enable_write_cache = 1;

    bs->read_only = (flags & BDRV_O_RDWR) == 0;

    if (!(flags & BDRV_O_FILE)) {

        open_flags = (flags & (BDRV_O_RDWR | BDRV_O_CACHE_MASK|BDRV_O_NATIVE_AIO));

        if (bs->is_temporary) { /* snapshot should be writeable */

            open_flags |= BDRV_O_RDWR;

        }

    } else {

        open_flags = flags & ~(BDRV_O_FILE | BDRV_O_SNAPSHOT);

    }

    if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {

        ret = -ENOTSUP;

    } else {

        ret = drv->bdrv_open(bs, filename, open_flags);

    }

    if (ret < 0) {

        qemu_free(bs->opaque);

        bs->opaque = NULL;

        bs->drv = NULL;

    unlink_and_fail:

        if (bs->is_temporary)

            unlink(filename);

        return ret;

    }

    if (drv->bdrv_getlength) {

        bs->total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;

    }

#ifndef _WIN32

    if (bs->is_temporary) {

        unlink(filename);

    }

#endif

    if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {

        /* if there is a backing file, use it */

        BlockDriver *back_drv = NULL;

        bs->backing_hd = bdrv_new("");

        path_combine(backing_filename, sizeof(backing_filename),

                     filename, bs->backing_file);

        if (bs->backing_format[0] != '\0')

            back_drv = bdrv_find_format(bs->backing_format);

        ret = bdrv_open2(bs->backing_hd, backing_filename, open_flags,

                         back_drv);

        bs->backing_hd->read_only =  (open_flags & BDRV_O_RDWR) == 0;

        if (ret < 0) {

            bdrv_close(bs);

            return ret;

        }

    }

    if (!bdrv_key_required(bs)) {

        /* call the change callback */

        bs->media_changed = 1;

        if (bs->change_cb)

            bs->change_cb(bs->change_opaque);

    }

    return 0;

}


milkymist_init(QEMUMachineInitArgs *args)

{

    const char *cpu_model = args->cpu_model;

    const char *kernel_filename = args->kernel_filename;

    const char *kernel_cmdline = args->kernel_cmdline;

    const char *initrd_filename = args->initrd_filename;

    LM32CPU *cpu;

    CPULM32State *env;

    int kernel_size;

    DriveInfo *dinfo;

    MemoryRegion *address_space_mem = get_system_memory();

    MemoryRegion *phys_sdram = g_new(MemoryRegion, 1);

    qemu_irq irq[32], *cpu_irq;

    int i;

    char *bios_filename;

    ResetInfo *reset_info;

    /* memory map */

    target_phys_addr_t flash_base   = 0x00000000;

    size_t flash_sector_size        = 128 * 1024;

    size_t flash_size               = 32 * 1024 * 1024;

    target_phys_addr_t sdram_base   = 0x40000000;

    size_t sdram_size               = 128 * 1024 * 1024;

    target_phys_addr_t initrd_base  = sdram_base + 0x1002000;

    target_phys_addr_t cmdline_base = sdram_base + 0x1000000;

    size_t initrd_max = sdram_size - 0x1002000;

    reset_info = g_malloc0(sizeof(ResetInfo));

    if (cpu_model == NULL) {

        cpu_model = "lm32-full";

    }

    cpu = cpu_lm32_init(cpu_model);

    env = &cpu->env;

    reset_info->cpu = cpu;

    cpu_lm32_set_phys_msb_ignore(env, 1);

    memory_region_init_ram(phys_sdram, "milkymist.sdram", sdram_size);

    vmstate_register_ram_global(phys_sdram);

    memory_region_add_subregion(address_space_mem, sdram_base, phys_sdram);

    dinfo = drive_get(IF_PFLASH, 0, 0);

    /* Numonyx JS28F256J3F105 */

    pflash_cfi01_register(flash_base, NULL, "milkymist.flash", flash_size,

                          dinfo ? dinfo->bdrv : NULL, flash_sector_size,

                          flash_size / flash_sector_size, 2,

                          0x00, 0x89, 0x00, 0x1d, 1);

    /* create irq lines */

    cpu_irq = qemu_allocate_irqs(cpu_irq_handler, env, 1);

    env->pic_state = lm32_pic_init(*cpu_irq);

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

        irq[i] = qdev_get_gpio_in(env->pic_state, i);

    }

    /* load bios rom */

    if (bios_name == NULL) {

        bios_name = BIOS_FILENAME;

    }

    bios_filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    if (bios_filename) {

        load_image_targphys(bios_filename, BIOS_OFFSET, BIOS_SIZE);

    }

    reset_info->bootstrap_pc = BIOS_OFFSET;

    /* if no kernel is given no valid bios rom is a fatal error */

    if (!kernel_filename && !dinfo && !bios_filename) {

        fprintf(stderr, "qemu: could not load Milkymist One bios '%s'\n",

                bios_name);

        exit(1);

    }

    milkymist_uart_create(0x60000000, irq[0]);

    milkymist_sysctl_create(0x60001000, irq[1], irq[2], irq[3],

            80000000, 0x10014d31, 0x0000041f, 0x00000001);

    milkymist_hpdmc_create(0x60002000);

    milkymist_vgafb_create(0x60003000, 0x40000000, 0x0fffffff);

    milkymist_memcard_create(0x60004000);

    milkymist_ac97_create(0x60005000, irq[4], irq[5], irq[6], irq[7]);

    milkymist_pfpu_create(0x60006000, irq[8]);

    milkymist_tmu2_create(0x60007000, irq[9]);

    milkymist_minimac2_create(0x60008000, 0x30000000, irq[10], irq[11]);

    milkymist_softusb_create(0x6000f000, irq[15],

            0x20000000, 0x1000, 0x20020000, 0x2000);

    /* make sure juart isn't the first chardev */

    env->juart_state = lm32_juart_init();

    if (kernel_filename) {

        uint64_t entry;

        /* Boots a kernel elf binary.  */

        kernel_size = load_elf(kernel_filename, NULL, NULL, &entry, NULL, NULL,

                               1, ELF_MACHINE, 0);

        reset_info->bootstrap_pc = entry;

        if (kernel_size < 0) {

            kernel_size = load_image_targphys(kernel_filename, sdram_base,

                                              sdram_size);

            reset_info->bootstrap_pc = sdram_base;

        }

        if (kernel_size < 0) {

            fprintf(stderr, "qemu: could not load kernel '%s'\n",

                    kernel_filename);

            exit(1);

        }

    }

    if (kernel_cmdline && strlen(kernel_cmdline)) {

        pstrcpy_targphys("cmdline", cmdline_base, TARGET_PAGE_SIZE,

                kernel_cmdline);

        reset_info->cmdline_base = (uint32_t)cmdline_base;

    }

    if (initrd_filename) {

        size_t initrd_size;

        initrd_size = load_image_targphys(initrd_filename, initrd_base,

                initrd_max);

        reset_info->initrd_base = (uint32_t)initrd_base;

        reset_info->initrd_size = (uint32_t)initrd_size;

    }

    qemu_register_reset(main_cpu_reset, reset_info);

}


static int aac_decode_frame_int(AVCodecContext *avctx, void *data,

                                int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)

{

    AACContext *ac = avctx->priv_data;

    ChannelElement *che = NULL, *che_prev = NULL;

    enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;

    int err, elem_id;

    int samples = 0, multiplier, audio_found = 0, pce_found = 0;

    int is_dmono, sce_count = 0;

    ac->frame = data;

    if (show_bits(gb, 12) == 0xfff) {

        if (parse_adts_frame_header(ac, gb) < 0) {

            av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");

            err = -1;

            goto fail;

        }

        if (ac->oc[1].m4ac.sampling_index > 12) {

            av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);

            err = -1;

            goto fail;

        }

    }

    if (frame_configure_elements(avctx) < 0) {

        err = -1;

        goto fail;

    }

    ac->tags_mapped = 0;

    // parse

    while ((elem_type = get_bits(gb, 3)) != TYPE_END) {

        elem_id = get_bits(gb, 4);

        if (elem_type < TYPE_DSE) {

            if (!(che=get_che(ac, elem_type, elem_id))) {

                av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",

                       elem_type, elem_id);

                err = -1;

                goto fail;

            }

            samples = 1024;

        }

        switch (elem_type) {

        case TYPE_SCE:

            err = decode_ics(ac, &che->ch[0], gb, 0, 0);

            audio_found = 1;

            sce_count++;

            break;

        case TYPE_CPE:

            err = decode_cpe(ac, gb, che);

            audio_found = 1;

            break;

        case TYPE_CCE:

            err = decode_cce(ac, gb, che);

            break;

        case TYPE_LFE:

            err = decode_ics(ac, &che->ch[0], gb, 0, 0);

            audio_found = 1;

            break;

        case TYPE_DSE:

            err = skip_data_stream_element(ac, gb);

            break;

        case TYPE_PCE: {

            uint8_t layout_map[MAX_ELEM_ID*4][3];

            int tags;

            push_output_configuration(ac);

            tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);

            if (tags < 0) {

                err = tags;

                break;

            }

            if (pce_found) {

                av_log(avctx, AV_LOG_ERROR,

                       "Not evaluating a further program_config_element as this construct is dubious at best.\n");

                pop_output_configuration(ac);

            } else {

                err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);

                if (!err)

                    ac->oc[1].m4ac.chan_config = 0;

                pce_found = 1;

            }

            break;

        }

        case TYPE_FIL:

            if (elem_id == 15)

                elem_id += get_bits(gb, 8) - 1;

            if (get_bits_left(gb) < 8 * elem_id) {

                    av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);

                    err = -1;

                    goto fail;

            }

            while (elem_id > 0)

                elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);

            err = 0; /* FIXME */

            break;

        default:

            err = -1; /* should not happen, but keeps compiler happy */

            break;

        }

        che_prev       = che;

        elem_type_prev = elem_type;

        if (err)

            goto fail;

        if (get_bits_left(gb) < 3) {

            av_log(avctx, AV_LOG_ERROR, overread_err);

            err = -1;

            goto fail;

        }

    }

    spectral_to_sample(ac);

    multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;

    samples <<= multiplier;

    /* for dual-mono audio (SCE + SCE) */

    is_dmono = ac->dmono_mode && sce_count == 2 &&

               ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);

    if (samples)

        ac->frame->nb_samples = samples;

    *got_frame_ptr = !!samples;

    if (is_dmono) {

        if (ac->dmono_mode == 1)

            ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];

        else if (ac->dmono_mode == 2)

            ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];

    }

    if (ac->oc[1].status && audio_found) {

        avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;

        avctx->frame_size = samples;

        ac->oc[1].status = OC_LOCKED;

    }

    if (multiplier) {

        int side_size;

        uint32_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);

        if (side && side_size>=4)

            AV_WL32(side, 2*AV_RL32(side));

    }

    return 0;

fail:

    pop_output_configuration(ac);

    return err;

}


void pc_cmos_init(ram_addr_t ram_size, ram_addr_t above_4g_mem_size,

                  const char *boot_device,

                  BusState *idebus0, BusState *idebus1,

                  FDCtrl *floppy_controller, ISADevice *s)

{

    int val, nb;

    FDriveType fd0, fd1;

    static pc_cmos_init_late_arg arg;

    /* various important CMOS locations needed by PC/Bochs bios */

    /* memory size */

    val = 640; /* base memory in K */

    rtc_set_memory(s, 0x15, val);

    rtc_set_memory(s, 0x16, val >> 8);

    val = (ram_size / 1024) - 1024;

    if (val > 65535)

        val = 65535;

    rtc_set_memory(s, 0x17, val);

    rtc_set_memory(s, 0x18, val >> 8);

    rtc_set_memory(s, 0x30, val);

    rtc_set_memory(s, 0x31, val >> 8);

    if (above_4g_mem_size) {

        rtc_set_memory(s, 0x5b, (unsigned int)above_4g_mem_size >> 16);

        rtc_set_memory(s, 0x5c, (unsigned int)above_4g_mem_size >> 24);

        rtc_set_memory(s, 0x5d, (uint64_t)above_4g_mem_size >> 32);

    }

    if (ram_size > (16 * 1024 * 1024))

        val = (ram_size / 65536) - ((16 * 1024 * 1024) / 65536);

    else

        val = 0;

    if (val > 65535)

        val = 65535;

    rtc_set_memory(s, 0x34, val);

    rtc_set_memory(s, 0x35, val >> 8);

    /* set the number of CPU */

    rtc_set_memory(s, 0x5f, smp_cpus - 1);

    /* set boot devices, and disable floppy signature check if requested */

    if (set_boot_dev(s, boot_device, fd_bootchk)) {

        exit(1);

    }

    /* floppy type */

    fd0 = fdctrl_get_drive_type(floppy_controller, 0);

    fd1 = fdctrl_get_drive_type(floppy_controller, 1);

    val = (cmos_get_fd_drive_type(fd0) << 4) | cmos_get_fd_drive_type(fd1);

    rtc_set_memory(s, 0x10, val);

    val = 0;

    nb = 0;

    if (fd0 < FDRIVE_DRV_NONE) {

        nb++;

    }

    if (fd1 < FDRIVE_DRV_NONE) {

        nb++;

    }

    switch (nb) {

    case 0:

        break;

    case 1:

        val |= 0x01; /* 1 drive, ready for boot */

        break;

    case 2:

        val |= 0x41; /* 2 drives, ready for boot */

        break;

    }

    val |= 0x02; /* FPU is there */

    val |= 0x04; /* PS/2 mouse installed */

    rtc_set_memory(s, REG_EQUIPMENT_BYTE, val);

    /* hard drives */

    arg.rtc_state = s;

    arg.idebus0 = idebus0;

    arg.idebus1 = idebus1;

    qemu_register_reset(pc_cmos_init_late, &arg);

}


START_TEST(unterminated_dict_comma)

{

    QObject *obj = qobject_from_json("{'abc':32,");

    fail_unless(obj == NULL);

}


void qemu_iovec_concat(QEMUIOVector *dst,

                       QEMUIOVector *src, size_t soffset, size_t sbytes)

{

    int i;

    size_t done;

    struct iovec *siov = src->iov;

    assert(dst->nalloc != -1);

    assert(src->size >= soffset);

    for (i = 0, done = 0; done < sbytes && i < src->niov; i++) {

        if (soffset < siov[i].iov_len) {

            size_t len = MIN(siov[i].iov_len - soffset, sbytes - done);

            qemu_iovec_add(dst, siov[i].iov_base + soffset, len);

            done += len;

            soffset = 0;

        } else {

            soffset -= siov[i].iov_len;

        }

    }

    /* return done; */

}


void net_host_device_add(Monitor *mon, const char *device, const char *opts)

{

    if (!net_host_check_device(device)) {

        monitor_printf(mon, "invalid host network device %s\n", device);

        return;

    }

    if (net_client_init(device, opts ? : "") < 0) {

        monitor_printf(mon, "adding host network device %s failed\n", device);

    }

}


static void musicpal_register_devices(void)

{

    sysbus_register_dev("mv88w8618_pic", sizeof(mv88w8618_pic_state),

                        mv88w8618_pic_init);

    sysbus_register_dev("mv88w8618_pit", sizeof(mv88w8618_pit_state),

                        mv88w8618_pit_init);

    sysbus_register_dev("mv88w8618_flashcfg", sizeof(mv88w8618_flashcfg_state),

                        mv88w8618_flashcfg_init);

    sysbus_register_dev("mv88w8618_eth", sizeof(mv88w8618_eth_state),

                        mv88w8618_eth_init);

    sysbus_register_dev("mv88w8618_wlan", sizeof(SysBusDevice),

                        mv88w8618_wlan_init);

    sysbus_register_dev("musicpal_lcd", sizeof(musicpal_lcd_state),

                        musicpal_lcd_init);

    sysbus_register_withprop(&musicpal_gpio_info);

    sysbus_register_dev("musicpal_key", sizeof(musicpal_key_state),

                        musicpal_key_init);

}


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

                      Error **errp)

{

    BDRVQcowState *s = bs->opaque;

    int len, i, ret = 0;

    QCowHeader header;

    QemuOpts *opts;

    Error *local_err = NULL;

    uint64_t ext_end;

    uint64_t l1_vm_state_index;

    const char *opt_overlap_check;

    int overlap_check_template = 0;

    ret = bdrv_pread(bs->file, 0, &header, sizeof(header));

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not read qcow2 header");

        goto fail;

    }

    be32_to_cpus(&header.magic);

    be32_to_cpus(&header.version);

    be64_to_cpus(&header.backing_file_offset);

    be32_to_cpus(&header.backing_file_size);

    be64_to_cpus(&header.size);

    be32_to_cpus(&header.cluster_bits);

    be32_to_cpus(&header.crypt_method);

    be64_to_cpus(&header.l1_table_offset);

    be32_to_cpus(&header.l1_size);

    be64_to_cpus(&header.refcount_table_offset);

    be32_to_cpus(&header.refcount_table_clusters);

    be64_to_cpus(&header.snapshots_offset);

    be32_to_cpus(&header.nb_snapshots);

    if (header.magic != QCOW_MAGIC) {

        error_setg(errp, "Image is not in qcow2 format");

        ret = -EMEDIUMTYPE;

        goto fail;

    }

    if (header.version < 2 || header.version > 3) {

        report_unsupported(bs, errp, "QCOW version %d", header.version);

        ret = -ENOTSUP;

        goto fail;

    }

    s->qcow_version = header.version;

    /* Initialise version 3 header fields */

    if (header.version == 2) {

        header.incompatible_features    = 0;

        header.compatible_features      = 0;

        header.autoclear_features       = 0;

        header.refcount_order           = 4;

        header.header_length            = 72;

    } else {

        be64_to_cpus(&header.incompatible_features);

        be64_to_cpus(&header.compatible_features);

        be64_to_cpus(&header.autoclear_features);

        be32_to_cpus(&header.refcount_order);

        be32_to_cpus(&header.header_length);

    }

    if (header.header_length > sizeof(header)) {

        s->unknown_header_fields_size = header.header_length - sizeof(header);

        s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);

        ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,

                         s->unknown_header_fields_size);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "

                             "fields");

            goto fail;

        }

    }

    if (header.backing_file_offset) {

        ext_end = header.backing_file_offset;

    } else {

        ext_end = 1 << header.cluster_bits;

    }

    /* Handle feature bits */

    s->incompatible_features    = header.incompatible_features;

    s->compatible_features      = header.compatible_features;

    s->autoclear_features       = header.autoclear_features;

    if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {

        void *feature_table = NULL;

        qcow2_read_extensions(bs, header.header_length, ext_end,

                              &feature_table, NULL);

        report_unsupported_feature(bs, errp, feature_table,

                                   s->incompatible_features &

                                   ~QCOW2_INCOMPAT_MASK);

        ret = -ENOTSUP;

        goto fail;

    }

    if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {

        /* Corrupt images may not be written to unless they are being repaired

         */

        if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {

            error_setg(errp, "qcow2: Image is corrupt; cannot be opened "

                       "read/write");

            ret = -EACCES;

            goto fail;

        }

    }

    /* Check support for various header values */

    if (header.refcount_order != 4) {

        report_unsupported(bs, errp, "%d bit reference counts",

                           1 << header.refcount_order);

        ret = -ENOTSUP;

        goto fail;

    }

    s->refcount_order = header.refcount_order;

    if (header.cluster_bits < MIN_CLUSTER_BITS ||

        header.cluster_bits > MAX_CLUSTER_BITS) {

        error_setg(errp, "Unsupported cluster size: 2^%i", header.cluster_bits);

        ret = -EINVAL;

        goto fail;

    }

    if (header.crypt_method > QCOW_CRYPT_AES) {

        error_setg(errp, "Unsupported encryption method: %i",

                   header.crypt_method);

        ret = -EINVAL;

        goto fail;

    }

    s->crypt_method_header = header.crypt_method;

    if (s->crypt_method_header) {

        bs->encrypted = 1;

    }

    s->cluster_bits = header.cluster_bits;

    s->cluster_size = 1 << s->cluster_bits;

    s->cluster_sectors = 1 << (s->cluster_bits - 9);

    s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */

    s->l2_size = 1 << s->l2_bits;

    bs->total_sectors = header.size / 512;

    s->csize_shift = (62 - (s->cluster_bits - 8));

    s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;

    s->cluster_offset_mask = (1LL << s->csize_shift) - 1;

    s->refcount_table_offset = header.refcount_table_offset;

    s->refcount_table_size =

        header.refcount_table_clusters << (s->cluster_bits - 3);

    s->snapshots_offset = header.snapshots_offset;

    s->nb_snapshots = header.nb_snapshots;

    /* read the level 1 table */

    s->l1_size = header.l1_size;

    l1_vm_state_index = size_to_l1(s, header.size);

    if (l1_vm_state_index > INT_MAX) {

        error_setg(errp, "Image is too big");

        ret = -EFBIG;

        goto fail;

    }

    s->l1_vm_state_index = l1_vm_state_index;

    /* the L1 table must contain at least enough entries to put

       header.size bytes */

    if (s->l1_size < s->l1_vm_state_index) {

        error_setg(errp, "L1 table is too small");

        ret = -EINVAL;

        goto fail;

    }

    s->l1_table_offset = header.l1_table_offset;

    if (s->l1_size > 0) {

        s->l1_table = g_malloc0(

            align_offset(s->l1_size * sizeof(uint64_t), 512));

        ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,

                         s->l1_size * sizeof(uint64_t));

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not read L1 table");

            goto fail;

        }

        for(i = 0;i < s->l1_size; i++) {

            be64_to_cpus(&s->l1_table[i]);

        }

    }

    /* alloc L2 table/refcount block cache */

    s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);

    s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);

    s->cluster_cache = g_malloc(s->cluster_size);

    /* one more sector for decompressed data alignment */

    s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size

                                  + 512);

    s->cluster_cache_offset = -1;

    s->flags = flags;

    ret = qcow2_refcount_init(bs);

    if (ret != 0) {

        error_setg_errno(errp, -ret, "Could not initialize refcount handling");

        goto fail;

    }

    QLIST_INIT(&s->cluster_allocs);

    QTAILQ_INIT(&s->discards);

    /* read qcow2 extensions */

    if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,

        &local_err)) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    /* read the backing file name */

    if (header.backing_file_offset != 0) {

        len = header.backing_file_size;

        if (len > 1023) {

            len = 1023;

        }

        ret = bdrv_pread(bs->file, header.backing_file_offset,

                         bs->backing_file, len);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not read backing file name");

            goto fail;

        }

        bs->backing_file[len] = '\0';

    }

    ret = qcow2_read_snapshots(bs);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not read snapshots");

        goto fail;

    }

    /* Clear unknown autoclear feature bits */

    if (!bs->read_only && s->autoclear_features != 0) {

        s->autoclear_features = 0;

        ret = qcow2_update_header(bs);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not update qcow2 header");

            goto fail;

        }

    }

    /* Initialise locks */

    qemu_co_mutex_init(&s->lock);

    /* Repair image if dirty */

    if (!(flags & BDRV_O_CHECK) && !bs->read_only &&

        (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {

        BdrvCheckResult result = {0};

        ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not repair dirty image");

            goto fail;

        }

    }

    /* Enable lazy_refcounts according to image and command line options */

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

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,

        (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));

    s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;

    s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;

    s->discard_passthrough[QCOW2_DISCARD_REQUEST] =

        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,

                          flags & BDRV_O_UNMAP);

    s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =

        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);

    s->discard_passthrough[QCOW2_DISCARD_OTHER] =

        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);

    opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";

    if (!strcmp(opt_overlap_check, "none")) {

        overlap_check_template = 0;

    } else if (!strcmp(opt_overlap_check, "constant")) {

        overlap_check_template = QCOW2_OL_CONSTANT;

    } else if (!strcmp(opt_overlap_check, "cached")) {

        overlap_check_template = QCOW2_OL_CACHED;

    } else if (!strcmp(opt_overlap_check, "all")) {

        overlap_check_template = QCOW2_OL_ALL;

    } else {

        error_setg(errp, "Unsupported value '%s' for qcow2 option "

                   "'overlap-check'. Allowed are either of the following: "

                   "none, constant, cached, all", opt_overlap_check);

        qemu_opts_del(opts);

        ret = -EINVAL;

        goto fail;

    }

    s->overlap_check = 0;

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

        /* overlap-check defines a template bitmask, but every flag may be

         * overwritten through the associated boolean option */

        s->overlap_check |=

            qemu_opt_get_bool(opts, overlap_bool_option_names[i],

                              overlap_check_template & (1 << i)) << i;

    }

    qemu_opts_del(opts);

    if (s->use_lazy_refcounts && s->qcow_version < 3) {

        error_setg(errp, "Lazy refcounts require a qcow2 image with at least "

                   "qemu 1.1 compatibility level");

        ret = -EINVAL;

        goto fail;

    }

#ifdef DEBUG_ALLOC

    {

        BdrvCheckResult result = {0};

        qcow2_check_refcounts(bs, &result, 0);

    }

#endif

    return ret;

 fail:

    g_free(s->unknown_header_fields);

    cleanup_unknown_header_ext(bs);

    qcow2_free_snapshots(bs);

    qcow2_refcount_close(bs);

    g_free(s->l1_table);

    /* else pre-write overlap checks in cache_destroy may crash */

    s->l1_table = NULL;

    if (s->l2_table_cache) {

        qcow2_cache_destroy(bs, s->l2_table_cache);

    }

    g_free(s->cluster_cache);

    qemu_vfree(s->cluster_data);

    return ret;

}


static void vexpress_a9_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 = NULL;

    MemoryRegion *sysmem = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *lowram = g_new(MemoryRegion, 1);

    MemoryRegion *vram = g_new(MemoryRegion, 1);

    MemoryRegion *sram = g_new(MemoryRegion, 1);

    MemoryRegion *hackram = g_new(MemoryRegion, 1);

    DeviceState *dev, *sysctl, *pl041;

    SysBusDevice *busdev;

    qemu_irq *irqp;

    qemu_irq pic[64];

    int n;

    qemu_irq cpu_irq[4];

    uint32_t proc_id;

    uint32_t sys_id;

    ram_addr_t low_ram_size, vram_size, sram_size;

    target_phys_addr_t *map = motherboard_legacy_map;

    if (!cpu_model) {

        cpu_model = "cortex-a9";

    }

    for (n = 0; n < smp_cpus; 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 (ram_size > 0x40000000) {

        /* 1GB is the maximum the address space permits */

        fprintf(stderr, "vexpress: cannot model more than 1GB RAM\n");

        exit(1);

    }

    memory_region_init_ram(ram, "vexpress.highmem", ram_size);

    vmstate_register_ram_global(ram);

    low_ram_size = ram_size;

    if (low_ram_size > 0x4000000) {

        low_ram_size = 0x4000000;

    }

    /* RAM is from 0x60000000 upwards. The bottom 64MB of the

     * address space should in theory be remappable to various

     * things including ROM or RAM; we always map the RAM there.

     */

    memory_region_init_alias(lowram, "vexpress.lowmem", ram, 0, low_ram_size);

    memory_region_add_subregion(sysmem, 0x0, lowram);

    memory_region_add_subregion(sysmem, 0x60000000, ram);

    /* 0x1e000000 A9MPCore (SCU) private memory region */

    dev = qdev_create(NULL, "a9mpcore_priv");

    qdev_prop_set_uint32(dev, "num-cpu", smp_cpus);

    qdev_init_nofail(dev);

    busdev = sysbus_from_qdev(dev);

    vexpress_binfo.smp_priv_base = 0x1e000000;

    sysbus_mmio_map(busdev, 0, vexpress_binfo.smp_priv_base);

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

        sysbus_connect_irq(busdev, n, cpu_irq[n]);

    }

    /* Interrupts [42:0] are from the motherboard;

     * [47:43] are reserved; [63:48] are daughterboard

     * peripherals. Note that some documentation numbers

     * external interrupts starting from 32 (because the

     * A9MP has internal interrupts 0..31).

     */

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

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

    }

    /* Motherboard peripherals: the wiring is the same but the

     * addresses vary between the legacy and A-Series memory maps.

     */

    sys_id = 0x1190f500;

    proc_id = 0x0c000191;

    sysctl = qdev_create(NULL, "realview_sysctl");

    qdev_prop_set_uint32(sysctl, "sys_id", sys_id);

    qdev_prop_set_uint32(sysctl, "proc_id", proc_id);

    qdev_init_nofail(sysctl);

    sysbus_mmio_map(sysbus_from_qdev(sysctl), 0, map[VE_SYSREGS]);

    /* VE_SP810: not modelled */

    /* VE_SERIALPCI: not modelled */

    pl041 = qdev_create(NULL, "pl041");

    qdev_prop_set_uint32(pl041, "nc_fifo_depth", 512);

    qdev_init_nofail(pl041);

    sysbus_mmio_map(sysbus_from_qdev(pl041), 0, map[VE_PL041]);

    sysbus_connect_irq(sysbus_from_qdev(pl041), 0, pic[11]);

    dev = sysbus_create_varargs("pl181", map[VE_MMCI], pic[9], pic[10], NULL);

    /* Wire up MMC card detect and read-only signals */

    qdev_connect_gpio_out(dev, 0,

                          qdev_get_gpio_in(sysctl, ARM_SYSCTL_GPIO_MMC_WPROT));

    qdev_connect_gpio_out(dev, 1,

                          qdev_get_gpio_in(sysctl, ARM_SYSCTL_GPIO_MMC_CARDIN));

    sysbus_create_simple("pl050_keyboard", map[VE_KMI0], pic[12]);

    sysbus_create_simple("pl050_mouse", map[VE_KMI1], pic[13]);

    sysbus_create_simple("pl011", map[VE_UART0], pic[5]);

    sysbus_create_simple("pl011", map[VE_UART1], pic[6]);

    sysbus_create_simple("pl011", map[VE_UART2], pic[7]);

    sysbus_create_simple("pl011", map[VE_UART3], pic[8]);

    sysbus_create_simple("sp804", map[VE_TIMER01], pic[2]);

    sysbus_create_simple("sp804", map[VE_TIMER23], pic[3]);

    /* VE_SERIALDVI: not modelled */

    sysbus_create_simple("pl031", map[VE_RTC], pic[4]); /* RTC */

    /* VE_COMPACTFLASH: not modelled */

    /* VE_CLCD: not modelled (we use the daughterboard CLCD only) */

    /* Daughterboard peripherals : 0x10020000 .. 0x20000000 */

    /* 0x10020000 PL111 CLCD (daughterboard) */

    sysbus_create_simple("pl111", 0x10020000, pic[44]);

    /* 0x10060000 AXI RAM */

    /* 0x100e0000 PL341 Dynamic Memory Controller */

    /* 0x100e1000 PL354 Static Memory Controller */

    /* 0x100e2000 System Configuration Controller */

    sysbus_create_simple("sp804", 0x100e4000, pic[48]);

    /* 0x100e5000 SP805 Watchdog module */

    /* 0x100e6000 BP147 TrustZone Protection Controller */

    /* 0x100e9000 PL301 'Fast' AXI matrix */

    /* 0x100ea000 PL301 'Slow' AXI matrix */

    /* 0x100ec000 TrustZone Address Space Controller */

    /* 0x10200000 CoreSight debug APB */

    /* 0x1e00a000 PL310 L2 Cache Controller */

    sysbus_create_varargs("l2x0", 0x1e00a000, NULL);

    /* VE_NORFLASH0: not modelled */

    /* VE_NORFLASH0ALIAS: not modelled */

    /* VE_NORFLASH1: not modelled */

    sram_size = 0x2000000;

    memory_region_init_ram(sram, "vexpress.sram", sram_size);

    vmstate_register_ram_global(sram);

    memory_region_add_subregion(sysmem, map[VE_SRAM], sram);

    vram_size = 0x800000;

    memory_region_init_ram(vram, "vexpress.vram", vram_size);

    vmstate_register_ram_global(vram);

    memory_region_add_subregion(sysmem, map[VE_VIDEORAM], vram);

    /* 0x4e000000 LAN9118 Ethernet */

    if (nd_table[0].vlan) {

        lan9118_init(&nd_table[0], map[VE_ETHERNET], pic[15]);

    }

    /* VE_USB: not modelled */

    /* VE_DAPROM: not modelled */

    /* ??? 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.  */

    memory_region_init_ram(hackram, "vexpress.hack", 0x1000);

    vmstate_register_ram_global(hackram);

    memory_region_add_subregion(sysmem, SMP_BOOT_ADDR, hackram);

    vexpress_binfo.ram_size = ram_size;

    vexpress_binfo.kernel_filename = kernel_filename;

    vexpress_binfo.kernel_cmdline = kernel_cmdline;

    vexpress_binfo.initrd_filename = initrd_filename;

    vexpress_binfo.nb_cpus = smp_cpus;

    vexpress_binfo.board_id = VEXPRESS_BOARD_ID;

    vexpress_binfo.loader_start = 0x60000000;

    vexpress_binfo.smp_bootreg_addr = map[VE_SYSREGS] + 0x30;

    arm_load_kernel(first_cpu, &vexpress_binfo);

}


static void gpollfds_to_select(int ret)

{

    int i;

    FD_ZERO(&rfds);

    FD_ZERO(&wfds);

    FD_ZERO(&xfds);

    if (ret <= 0) {

        return;

    }

    for (i = 0; i < gpollfds->len; i++) {

        int fd = g_array_index(gpollfds, GPollFD, i).fd;

        int revents = g_array_index(gpollfds, GPollFD, i).revents;

        if (revents & (G_IO_IN | G_IO_HUP | G_IO_ERR)) {

            FD_SET(fd, &rfds);

        }

        if (revents & (G_IO_OUT | G_IO_ERR)) {

            FD_SET(fd, &wfds);

        }

        if (revents & G_IO_PRI) {

            FD_SET(fd, &xfds);

        }

    }

}


static void cpu_4xx_pit_cb (void *opaque)

{

    CPUState *env;

    ppc_tb_t *tb_env;

    ppcemb_timer_t *ppcemb_timer;

    env = opaque;

    tb_env = env->tb_env;

    ppcemb_timer = tb_env->opaque;

    env->spr[SPR_40x_TSR] |= 1 << 27;

    if ((env->spr[SPR_40x_TCR] >> 26) & 0x1)

        ppc_set_irq(env, PPC_INTERRUPT_PIT, 1);

    start_stop_pit(env, tb_env, 1);

    LOG_TB("%s: ar %d ir %d TCR " TARGET_FMT_lx " TSR " TARGET_FMT_lx " "

           "%016" PRIx64 "\n", __func__,

           (int)((env->spr[SPR_40x_TCR] >> 22) & 0x1),

           (int)((env->spr[SPR_40x_TCR] >> 26) & 0x1),

           env->spr[SPR_40x_TCR], env->spr[SPR_40x_TSR],

           ppcemb_timer->pit_reload);

}


CPUArchState *cpu_copy(CPUArchState *env)

{

    CPUState *cpu = ENV_GET_CPU(env);

    CPUArchState *new_env = cpu_init(cpu_model);

    CPUState *new_cpu = ENV_GET_CPU(new_env);

#if defined(TARGET_HAS_ICE)

    CPUBreakpoint *bp;

    CPUWatchpoint *wp;

#endif

    /* Reset non arch specific state */

    cpu_reset(new_cpu);

    memcpy(new_env, env, sizeof(CPUArchState));

    /* Clone all break/watchpoints.

       Note: Once we support ptrace with hw-debug register access, make sure

       BP_CPU break/watchpoints are handled correctly on clone. */

    QTAILQ_INIT(&cpu->breakpoints);

    QTAILQ_INIT(&cpu->watchpoints);

#if defined(TARGET_HAS_ICE)

    QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {

        cpu_breakpoint_insert(new_cpu, bp->pc, bp->flags, NULL);

    }

    QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {

        cpu_watchpoint_insert(new_cpu, wp->vaddr, wp->len, wp->flags, NULL);

    }

#endif

    return new_env;

}


static void mdct512(AC3MDCTContext *mdct, float *out, float *in)

{

    mdct->fft.mdct_calc(&mdct->fft, out, in);

}


static void av_noinline qpeg_decode_inter(QpegContext *qctx, uint8_t *dst,

                              int stride, int width, int height,

                              int delta, const uint8_t *ctable,

                              uint8_t *refdata)

{

    int i, j;

    int code;

    int filled = 0;

    int orig_height;

    if(!refdata)

        refdata= dst;

    /* copy prev frame */

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

        memcpy(dst + (i * stride), refdata + (i * stride), width);

    orig_height = height;

    height--;

    dst = dst + height * stride;

    while ((bytestream2_get_bytes_left(&qctx->buffer) > 0) && (height >= 0)) {

        code = bytestream2_get_byte(&qctx->buffer);

        if(delta) {

            /* motion compensation */

            while(bytestream2_get_bytes_left(&qctx->buffer) > 0 && (code & 0xF0) == 0xF0) {

                if(delta == 1) {

                    int me_idx;

                    int me_w, me_h, me_x, me_y;

                    uint8_t *me_plane;

                    int corr, val;

                    /* get block size by index */

                    me_idx = code & 0xF;

                    me_w = qpeg_table_w[me_idx];

                    me_h = qpeg_table_h[me_idx];

                    /* extract motion vector */

                    corr = bytestream2_get_byte(&qctx->buffer);

                    val = corr >> 4;

                    if(val > 7)

                        val -= 16;

                    me_x = val;

                    val = corr & 0xF;

                    if(val > 7)

                        val -= 16;

                    me_y = val;

                    /* check motion vector */

                    if ((me_x + filled < 0) || (me_x + me_w + filled > width) ||

                       (height - me_y - me_h < 0) || (height - me_y >= orig_height) ||

                       (filled + me_w > width) || (height - me_h < 0))

                        av_log(NULL, AV_LOG_ERROR, "Bogus motion vector (%i,%i), block size %ix%i at %i,%i\n",

                               me_x, me_y, me_w, me_h, filled, height);

                    else {

                        /* do motion compensation */

                        me_plane = refdata + (filled + me_x) + (height - me_y) * stride;

                        for(j = 0; j < me_h; j++) {

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

                                dst[filled + i - (j * stride)] = me_plane[i - (j * stride)];

                        }

                    }

                }

                code = bytestream2_get_byte(&qctx->buffer);

            }

        }

        if(code == 0xE0) /* end-of-picture code */

            break;

        if(code > 0xE0) { /* run code: 0xE1..0xFF */

            int p;

            code &= 0x1F;

            p = bytestream2_get_byte(&qctx->buffer);

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

                dst[filled++] = p;

                if(filled >= width) {

                    filled = 0;

                    dst -= stride;

                    height--;

                    if (height < 0)

                        break;

                }

            }

        } else if(code >= 0xC0) { /* copy code: 0xC0..0xDF */

            code &= 0x1F;

            if(code + 1 > bytestream2_get_bytes_left(&qctx->buffer))

                break;

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

                dst[filled++] = bytestream2_get_byte(&qctx->buffer);

                if(filled >= width) {

                    filled = 0;

                    dst -= stride;

                    height--;

                    if (height < 0)

                        break;

                }

            }

        } else if(code >= 0x80) { /* skip code: 0x80..0xBF */

            int skip;

            code &= 0x3F;

            /* codes 0x80 and 0x81 are actually escape codes,

               skip value minus constant is in the next byte */

            if(!code)

                skip = bytestream2_get_byte(&qctx->buffer) +  64;

            else if(code == 1)

                skip = bytestream2_get_byte(&qctx->buffer) + 320;

            else

                skip = code;

            filled += skip;

            while( filled >= width) {

                filled -= width;

                dst -= stride;

                height--;

                if(height < 0)

                    break;

            }

        } else {

            /* zero code treated as one-pixel skip */

            if(code) {

                dst[filled++] = ctable[code & 0x7F];

            }

            else

                filled++;

            if(filled >= width) {

                filled = 0;

                dst -= stride;

                height--;

            }

        }

    }

}


static void block_job_detach_aio_context(void *opaque)

{

    BlockJob *job = opaque;

    /* In case the job terminates during aio_poll()... */

    block_job_ref(job);

    block_job_pause(job);

    if (!job->paused) {

        /* If job is !job->busy this kicks it into the next pause point. */

        block_job_enter(job);

    }

    while (!job->paused && !job->completed) {

        aio_poll(block_job_get_aio_context(job), true);

    }

    block_job_unref(job);

}


void numa_cpu_pre_plug(const CPUArchId *slot, DeviceState *dev, Error **errp)

{

    int mapped_node_id; /* set by -numa option */

    int node_id = object_property_get_int(OBJECT(dev), "node-id", &error_abort);

    /* by default CPUState::numa_node was 0 if it wasn't set explicitly

     * TODO: make it error when incomplete numa mapping support is removed

     */

    mapped_node_id = slot->props.node_id;

    if (!slot->props.has_node_id) {

        mapped_node_id = 0;

    }

    if (node_id == CPU_UNSET_NUMA_NODE_ID) {

        /* due to bug in libvirt, it doesn't pass node-id from props on

         * device_add as expected, so we have to fix it up here */

        object_property_set_int(OBJECT(dev), mapped_node_id, "node-id", errp);

    } else if (node_id != mapped_node_id) {

        error_setg(errp, "node-id=%d must match numa node specified "

                   "with -numa option", node_id);

    }

}


static void multiwrite_cb(void *opaque, int ret)

{

    MultiwriteCB *mcb = opaque;

    trace_multiwrite_cb(mcb, ret);

    if (ret < 0 && !mcb->error) {

        mcb->error = ret;

    }

    mcb->num_requests--;

    if (mcb->num_requests == 0) {

        multiwrite_user_cb(mcb);

        g_free(mcb);

    }

}


static void qdict_setup(void)

{

    tests_dict = qdict_new();

    fail_unless(tests_dict != NULL);

}


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

                          Error **errp)

{

    BDRVParallelsState *s = bs->opaque;

    int i;

    ParallelsHeader ph;

    int ret;

    ret = bdrv_pread(bs->file, 0, &ph, sizeof(ph));

    if (ret < 0) {

        goto fail;

    }

    bs->total_sectors = le64_to_cpu(ph.nb_sectors);

    if (le32_to_cpu(ph.version) != HEADER_VERSION) {

        goto fail_format;

    }

    if (!memcmp(ph.magic, HEADER_MAGIC, 16)) {

        s->off_multiplier = 1;

        bs->total_sectors = 0xffffffff & bs->total_sectors;

    } else if (!memcmp(ph.magic, HEADER_MAGIC2, 16)) {

        s->off_multiplier = le32_to_cpu(ph.tracks);

    } else {

        goto fail_format;

    }

    s->tracks = le32_to_cpu(ph.tracks);

    if (s->tracks == 0) {

        error_setg(errp, "Invalid image: Zero sectors per track");

        ret = -EINVAL;

        goto fail;

    }

    if (s->tracks > INT32_MAX/513) {

        error_setg(errp, "Invalid image: Too big cluster");

        ret = -EFBIG;

        goto fail;

    }

    s->catalog_size = le32_to_cpu(ph.catalog_entries);

    if (s->catalog_size > INT_MAX / sizeof(uint32_t)) {

        error_setg(errp, "Catalog too large");

        ret = -EFBIG;

        goto fail;

    }

    s->catalog_bitmap = g_try_new(uint32_t, s->catalog_size);

    if (s->catalog_size && s->catalog_bitmap == NULL) {

        ret = -ENOMEM;

        goto fail;

    }

    ret = bdrv_pread(bs->file, sizeof(ParallelsHeader),

                     s->catalog_bitmap, s->catalog_size * sizeof(uint32_t));

    if (ret < 0) {

        goto fail;

    }

    for (i = 0; i < s->catalog_size; i++)

        le32_to_cpus(&s->catalog_bitmap[i]);

    s->has_truncate = bdrv_has_zero_init(bs->file) &&

                      bdrv_truncate(bs->file, bdrv_getlength(bs->file)) == 0;

    qemu_co_mutex_init(&s->lock);

    return 0;

fail_format:

    error_setg(errp, "Image not in Parallels format");

    ret = -EINVAL;

fail:

    g_free(s->catalog_bitmap);

    return ret;

}


void imx_timerp_create(const target_phys_addr_t addr,

                              qemu_irq irq,

                              DeviceState *ccm)

{

    IMXTimerPState *pp;

    DeviceState *dev;

    dev = sysbus_create_simple("imx_timerp", addr, irq);

    pp = container_of(dev, IMXTimerPState, busdev.qdev);

    pp->ccm = ccm;

}


if_start(Slirp *slirp)

{

    uint64_t now = qemu_get_clock_ns(rt_clock);

    int requeued = 0;

    bool from_batchq = false;

	struct mbuf *ifm, *ifqt;

	DEBUG_CALL("if_start");

	if (slirp->if_queued == 0)

	   return; /* Nothing to do */

 again:

        /* check if we can really output */

        if (!slirp_can_output(slirp->opaque))

            return;

	/*

	 * See which queue to get next packet from

	 * If there's something in the fastq, select it immediately

	 */

	if (slirp->if_fastq.ifq_next != &slirp->if_fastq) {

		ifm = slirp->if_fastq.ifq_next;

	} else {

		/* Nothing on fastq, see if next_m is valid */

		if (slirp->next_m != &slirp->if_batchq)

		   ifm = slirp->next_m;

		else

		   ifm = slirp->if_batchq.ifq_next;

                from_batchq = true;

	}

        slirp->if_queued--;

        /* Try to send packet unless it already expired */

        if (ifm->expiration_date >= now && !if_encap(slirp, ifm)) {

            /* Packet is delayed due to pending ARP resolution */

            requeued++;

            goto out;

        }

        if (from_batchq) {

            /* Set which packet to send on next iteration */

            slirp->next_m = ifm->ifq_next;

        }

	/* Remove it from the queue */

	ifqt = ifm->ifq_prev;

	remque(ifm);

	/* If there are more packets for this session, re-queue them */

	if (ifm->ifs_next != /* ifm->ifs_prev != */ ifm) {

		insque(ifm->ifs_next, ifqt);

		ifs_remque(ifm);

	}

	/* Update so_queued */

	if (ifm->ifq_so) {

		if (--ifm->ifq_so->so_queued == 0)

		   /* If there's no more queued, reset nqueued */

		   ifm->ifq_so->so_nqueued = 0;

	}

        m_free(ifm);

 out:

	if (slirp->if_queued)

	   goto again;

        slirp->if_queued = requeued;

}


e1000_cleanup(NetClientState *nc)

{

    E1000State *s = qemu_get_nic_opaque(nc);

    s->nic = NULL;

}


static void sdram_set_bcr (uint32_t *bcrp, uint32_t bcr, int enabled)

{

    if (*bcrp & 0x00000001) {

        /* Unmap RAM */

#ifdef DEBUG_SDRAM

        printf("%s: unmap RAM area " TARGET_FMT_plx " " TARGET_FMT_lx "\n",

               __func__, sdram_base(*bcrp), sdram_size(*bcrp));

#endif

        cpu_register_physical_memory(sdram_base(*bcrp), sdram_size(*bcrp),

                                     IO_MEM_UNASSIGNED);

    }

    *bcrp = bcr & 0xFFDEE001;

    if (enabled && (bcr & 0x00000001)) {

#ifdef DEBUG_SDRAM

        printf("%s: Map RAM area " TARGET_FMT_plx " " TARGET_FMT_lx "\n",

               __func__, sdram_base(bcr), sdram_size(bcr));

#endif

        cpu_register_physical_memory(sdram_base(bcr), sdram_size(bcr),

                                     sdram_base(bcr) | IO_MEM_RAM);

    }

}


static Suite *qfloat_suite(void)

{

    Suite *s;

    TCase *qfloat_public_tcase;

    s = suite_create("QFloat test-suite");

    qfloat_public_tcase = tcase_create("Public Interface");

    suite_add_tcase(s, qfloat_public_tcase);

    tcase_add_test(qfloat_public_tcase, qfloat_from_double_test);

    tcase_add_test(qfloat_public_tcase, qfloat_destroy_test);

    return s;

}


void qemu_unregister_clock_reset_notifier(QEMUClock *clock,

                                          Notifier *notifier)

{

    qemu_clock_unregister_reset_notifier(clock->type, notifier);

}


target_ulong cpu_get_phys_page_debug(CPUState *env, target_ulong addr)

{

    uint8_t *pde_ptr, *pte_ptr;

    uint32_t pde, pte, paddr, page_offset, page_size;

    if (!(env->cr[0] & CR0_PG_MASK)) {

        pte = addr;

        page_size = 4096;

    } else {

        /* page directory entry */

        pde_ptr = phys_ram_base +

            (((env->cr[3] & ~0xfff) + ((addr >> 20) & ~3)) & a20_mask);

        pde = ldl_raw(pde_ptr);

        if (!(pde & PG_PRESENT_MASK))

            return -1;

        if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {

            pte = pde & ~0x003ff000; /* align to 4MB */

            page_size = 4096 * 1024;

        } else {

            /* page directory entry */

            pte_ptr = phys_ram_base +

                (((pde & ~0xfff) + ((addr >> 10) & 0xffc)) & a20_mask);

            pte = ldl_raw(pte_ptr);

            if (!(pte & PG_PRESENT_MASK))

                return -1;

            page_size = 4096;

        }

    }

    pte = pte & a20_mask;

    page_offset = (addr & TARGET_PAGE_MASK) & (page_size - 1);

    paddr = (pte & TARGET_PAGE_MASK) + page_offset;

    return paddr;

}


static uint64_t imx_serial_read(void *opaque, target_phys_addr_t offset,

                                unsigned size)

{

    IMXSerialState *s = (IMXSerialState *)opaque;

    uint32_t c;

    DPRINTF("read(offset=%x)\n", offset >> 2);

    switch (offset >> 2) {

    case 0x0: /* URXD */

        c = s->readbuff;

        if (!(s->uts1 & UTS1_RXEMPTY)) {

            /* Character is valid */

            c |= URXD_CHARRDY;

            s->usr1 &= ~USR1_RRDY;

            s->usr2 &= ~USR2_RDR;

            s->uts1 |= UTS1_RXEMPTY;

            imx_update(s);

            qemu_chr_accept_input(s->chr);

        }

        return c;

    case 0x20: /* UCR1 */

        return s->ucr1;

    case 0x21: /* UCR2 */

        return s->ucr2;

    case 0x25: /* USR1 */

        return s->usr1;

    case 0x26: /* USR2 */

        return s->usr2;

    case 0x2A: /* BRM Modulator */

        return s->ubmr;

    case 0x2B: /* Baud Rate Count */

        return s->ubrc;

    case 0x2d: /* Test register */

        return s->uts1;

    case 0x24: /* UFCR */

        return s->ufcr;

    case 0x2c:

        return s->onems;

    case 0x22: /* UCR3 */

        return s->ucr3;

    case 0x23: /* UCR4 */

    case 0x29: /* BRM Incremental */

        return 0x0; /* TODO */

    default:

        IPRINTF("imx_serial_read: bad offset: 0x%x\n", (int)offset);

        return 0;

    }

}


void qemu_del_net_client(NetClientState *nc)

{

    NetClientState *ncs[MAX_QUEUE_NUM];

    int queues, i;

    /* If the NetClientState belongs to a multiqueue backend, we will change all

     * other NetClientStates also.

     */

    queues = qemu_find_net_clients_except(nc->name, ncs,

                                          NET_CLIENT_OPTIONS_KIND_NIC,

                                          MAX_QUEUE_NUM);

    assert(queues != 0);

    /* If there is a peer NIC, delete and cleanup client, but do not free. */

    if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {

        NICState *nic = qemu_get_nic(nc->peer);

        if (nic->peer_deleted) {

            return;

        }

        nic->peer_deleted = true;

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

            ncs[i]->peer->link_down = true;

        }

        if (nc->peer->info->link_status_changed) {

            nc->peer->info->link_status_changed(nc->peer);

        }

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

            qemu_cleanup_net_client(ncs[i]);

        }

        return;

    }

    assert(nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC);

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

        qemu_cleanup_net_client(ncs[i]);

        qemu_free_net_client(ncs[i]);

    }

}


static inline void omap_gp_timer_trigger(struct omap_gp_timer_s *timer)

{

    if (timer->pt)

        /* TODO in overflow-and-match mode if the first event to

         * occurs is the match, don't toggle.  */

        omap_gp_timer_out(timer, !timer->out_val);

    else

        /* TODO inverted pulse on timer->out_val == 1?  */

        qemu_irq_pulse(timer->out);

}


timer_write(void *opaque, target_phys_addr_t addr,

            uint64_t val64, unsigned int size)

{

    struct etrax_timer *t = opaque;

    uint32_t value = val64;

    switch (addr)

    {

        case RW_TMR0_DIV:

            t->rw_tmr0_div = value;

            break;

        case RW_TMR0_CTRL:

            D(printf ("RW_TMR0_CTRL=%x\n", value));

            t->rw_tmr0_ctrl = value;

            update_ctrl(t, 0);

            break;

        case RW_TMR1_DIV:

            t->rw_tmr1_div = value;

            break;

        case RW_TMR1_CTRL:

            D(printf ("RW_TMR1_CTRL=%x\n", value));

            t->rw_tmr1_ctrl = value;

            update_ctrl(t, 1);

            break;

        case RW_INTR_MASK:

            D(printf ("RW_INTR_MASK=%x\n", value));

            t->rw_intr_mask = value;

            timer_update_irq(t);

            break;

        case RW_WD_CTRL:

            timer_watchdog_update(t, value);

            break;

        case RW_ACK_INTR:

            t->rw_ack_intr = value;

            timer_update_irq(t);

            t->rw_ack_intr = 0;

            break;

        default:

            printf ("%s " TARGET_FMT_plx " %x\n",

                __func__, addr, value);

            break;

    }

}


void mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)

{

    mpeg1_encode_sequence_header(s);

    /* mpeg1 picture header */

    put_header(s, PICTURE_START_CODE);

    /* temporal reference */

    // RAL: s->picture_number instead of s->fake_picture_number

    put_bits(&s->pb, 10, (s->picture_number -

                          s->gop_picture_number) & 0x3ff);

    s->fake_picture_number++;

    put_bits(&s->pb, 3, s->pict_type);

    s->vbv_delay_ptr= s->pb.buf + get_bit_count(&s->pb)/8;

    put_bits(&s->pb, 16, 0xFFFF); /* vbv_delay */

    // RAL: Forward f_code also needed for B frames

    if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {

        put_bits(&s->pb, 1, 0); /* half pel coordinates */

        if(s->codec_id == CODEC_ID_MPEG1VIDEO)

            put_bits(&s->pb, 3, s->f_code); /* forward_f_code */

        else

            put_bits(&s->pb, 3, 7); /* forward_f_code */

    }

    // RAL: Backward f_code necessary for B frames

    if (s->pict_type == B_TYPE) {

        put_bits(&s->pb, 1, 0); /* half pel coordinates */

        if(s->codec_id == CODEC_ID_MPEG1VIDEO)

            put_bits(&s->pb, 3, s->b_code); /* backward_f_code */

        else

            put_bits(&s->pb, 3, 7); /* backward_f_code */

    }

    put_bits(&s->pb, 1, 0); /* extra bit picture */

    s->frame_pred_frame_dct = 1;

    if(s->codec_id == CODEC_ID_MPEG2VIDEO){

        put_header(s, EXT_START_CODE);

        put_bits(&s->pb, 4, 8); //pic ext

        if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {

            put_bits(&s->pb, 4, s->f_code);

            put_bits(&s->pb, 4, s->f_code);

        }else{

            put_bits(&s->pb, 8, 255);

        }

        if (s->pict_type == B_TYPE) {

            put_bits(&s->pb, 4, s->b_code);

            put_bits(&s->pb, 4, s->b_code);

        }else{

            put_bits(&s->pb, 8, 255);

        }

        put_bits(&s->pb, 2, s->intra_dc_precision);

        put_bits(&s->pb, 2, s->picture_structure= PICT_FRAME);

        if (s->progressive_sequence) {

            put_bits(&s->pb, 1, 0); /* no repeat */

        } else {

            put_bits(&s->pb, 1, s->current_picture_ptr->top_field_first);

        }

        /* XXX: optimize the generation of this flag with entropy

           measures */

        s->frame_pred_frame_dct = s->progressive_sequence;

        put_bits(&s->pb, 1, s->frame_pred_frame_dct);

        put_bits(&s->pb, 1, s->concealment_motion_vectors);

        put_bits(&s->pb, 1, s->q_scale_type);

        put_bits(&s->pb, 1, s->intra_vlc_format);

        put_bits(&s->pb, 1, s->alternate_scan);

        put_bits(&s->pb, 1, s->repeat_first_field);

        put_bits(&s->pb, 1, s->chroma_420_type=1);

        s->progressive_frame = s->progressive_sequence;

        put_bits(&s->pb, 1, s->progressive_frame);

        put_bits(&s->pb, 1, 0); //composite_display_flag

    }

    if(s->flags & CODEC_FLAG_SVCD_SCAN_OFFSET){

        int i;

        put_header(s, USER_START_CODE);

        for(i=0; i<sizeof(svcd_scan_offset_placeholder); i++){

            put_bits(&s->pb, 8, svcd_scan_offset_placeholder[i]);

        }

    }

    s->mb_y=0;

    ff_mpeg1_encode_slice_header(s);

}


static inline void gen_op_fcmpd(int fccno, TCGv_i64 r_rs1, TCGv_i64 r_rs2)

{

    gen_helper_fcmpd(cpu_env, r_rs1, r_rs2);

}


int pcistb_service_call(S390CPU *cpu, uint8_t r1, uint8_t r3, uint64_t gaddr,

                        uint8_t ar, uintptr_t ra)

{

    CPUS390XState *env = &cpu->env;

    S390PCIBusDevice *pbdev;

    MemoryRegion *mr;

    MemTxResult result;

    int i;

    uint32_t fh;

    uint8_t pcias;

    uint8_t len;

    uint8_t buffer[128];

    if (env->psw.mask & PSW_MASK_PSTATE) {

        s390_program_interrupt(env, PGM_PRIVILEGED, 6, ra);

        return 0;

    }

    fh = env->regs[r1] >> 32;

    pcias = (env->regs[r1] >> 16) & 0xf;

    len = env->regs[r1] & 0xff;

    if (pcias > 5) {

        DPRINTF("pcistb invalid space\n");

        setcc(cpu, ZPCI_PCI_LS_ERR);

        s390_set_status_code(env, r1, ZPCI_PCI_ST_INVAL_AS);

        return 0;

    }

    switch (len) {

    case 16:

    case 32:

    case 64:

    case 128:

        break;

    default:

        s390_program_interrupt(env, PGM_SPECIFICATION, 6, ra);

        return 0;

    }

    pbdev = s390_pci_find_dev_by_fh(s390_get_phb(), fh);

    if (!pbdev) {

        DPRINTF("pcistb no pci dev fh 0x%x\n", fh);

        setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);

        return 0;

    }

    switch (pbdev->state) {

    case ZPCI_FS_RESERVED:

    case ZPCI_FS_STANDBY:

    case ZPCI_FS_DISABLED:

    case ZPCI_FS_PERMANENT_ERROR:

        setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);

        return 0;

    case ZPCI_FS_ERROR:

        setcc(cpu, ZPCI_PCI_LS_ERR);

        s390_set_status_code(env, r1, ZPCI_PCI_ST_BLOCKED);

        return 0;

    default:

        break;

    }

    mr = pbdev->pdev->io_regions[pcias].memory;

    if (!memory_region_access_valid(mr, env->regs[r3], len, true)) {

        s390_program_interrupt(env, PGM_OPERAND, 6, ra);

        return 0;

    }

    if (s390_cpu_virt_mem_read(cpu, gaddr, ar, buffer, len)) {

        s390_cpu_virt_mem_handle_exc(cpu, ra);

        return 0;

    }

    for (i = 0; i < len / 8; i++) {

        result = memory_region_dispatch_write(mr, env->regs[r3] + i * 8,

                                     ldq_p(buffer + i * 8), 8,

                                     MEMTXATTRS_UNSPECIFIED);

        if (result != MEMTX_OK) {

            s390_program_interrupt(env, PGM_OPERAND, 6, ra);

            return 0;

        }

    }

    setcc(cpu, ZPCI_PCI_LS_OK);

    return 0;

}


static void *spapr_create_fdt_skel(const char *cpu_model,

                                   target_phys_addr_t rma_size,

                                   target_phys_addr_t initrd_base,

                                   target_phys_addr_t initrd_size,

                                   const char *boot_device,

                                   const char *kernel_cmdline,

                                   long hash_shift)

{

    void *fdt;

    CPUState *env;

    uint64_t mem_reg_property_rma[] = { 0, cpu_to_be64(rma_size) };

    uint64_t mem_reg_property_nonrma[] = { cpu_to_be64(rma_size),

                                           cpu_to_be64(ram_size - rma_size) };

    uint32_t start_prop = cpu_to_be32(initrd_base);

    uint32_t end_prop = cpu_to_be32(initrd_base + initrd_size);

    uint32_t pft_size_prop[] = {0, cpu_to_be32(hash_shift)};

    char hypertas_prop[] = "hcall-pft\0hcall-term\0hcall-dabr\0hcall-interrupt"

        "\0hcall-tce\0hcall-vio\0hcall-splpar\0hcall-bulk";

    uint32_t interrupt_server_ranges_prop[] = {0, cpu_to_be32(smp_cpus)};

    int i;

    char *modelname;

    int smt = kvmppc_smt_threads();

#define _FDT(exp) \

    do { \

        int ret = (exp);                                           \

        if (ret < 0) {                                             \

            fprintf(stderr, "qemu: error creating device tree: %s: %s\n", \

                    #exp, fdt_strerror(ret));                      \

            exit(1);                                               \

        }                                                          \

    } while (0)

    fdt = g_malloc0(FDT_MAX_SIZE);

    _FDT((fdt_create(fdt, FDT_MAX_SIZE)));

    _FDT((fdt_finish_reservemap(fdt)));

    /* Root node */

    _FDT((fdt_begin_node(fdt, "")));

    _FDT((fdt_property_string(fdt, "device_type", "chrp")));

    _FDT((fdt_property_string(fdt, "model", "IBM pSeries (emulated by qemu)")));

    _FDT((fdt_property_cell(fdt, "#address-cells", 0x2)));

    _FDT((fdt_property_cell(fdt, "#size-cells", 0x2)));

    /* /chosen */

    _FDT((fdt_begin_node(fdt, "chosen")));

    _FDT((fdt_property_string(fdt, "bootargs", kernel_cmdline)));

    _FDT((fdt_property(fdt, "linux,initrd-start",

                       &start_prop, sizeof(start_prop))));

    _FDT((fdt_property(fdt, "linux,initrd-end",

                       &end_prop, sizeof(end_prop))));

    _FDT((fdt_property_string(fdt, "qemu,boot-device", boot_device)));

    _FDT((fdt_end_node(fdt)));

    /* memory node(s) */

    _FDT((fdt_begin_node(fdt, "memory@0")));

    _FDT((fdt_property_string(fdt, "device_type", "memory")));

    _FDT((fdt_property(fdt, "reg", mem_reg_property_rma,

                       sizeof(mem_reg_property_rma))));

    _FDT((fdt_end_node(fdt)));

    if (ram_size > rma_size) {

        char mem_name[32];

        sprintf(mem_name, "memory@%" PRIx64, (uint64_t)rma_size);

        _FDT((fdt_begin_node(fdt, mem_name)));

        _FDT((fdt_property_string(fdt, "device_type", "memory")));

        _FDT((fdt_property(fdt, "reg", mem_reg_property_nonrma,

                           sizeof(mem_reg_property_nonrma))));

        _FDT((fdt_end_node(fdt)));

    }

    /* cpus */

    _FDT((fdt_begin_node(fdt, "cpus")));

    _FDT((fdt_property_cell(fdt, "#address-cells", 0x1)));

    _FDT((fdt_property_cell(fdt, "#size-cells", 0x0)));

    modelname = g_strdup(cpu_model);

    for (i = 0; i < strlen(modelname); i++) {

        modelname[i] = toupper(modelname[i]);

    }

    for (env = first_cpu; env != NULL; env = env->next_cpu) {

        int index = env->cpu_index;

        uint32_t servers_prop[smp_threads];

        uint32_t gservers_prop[smp_threads * 2];

        char *nodename;

        uint32_t segs[] = {cpu_to_be32(28), cpu_to_be32(40),

                           0xffffffff, 0xffffffff};

        uint32_t tbfreq = kvm_enabled() ? kvmppc_get_tbfreq() : TIMEBASE_FREQ;

        uint32_t cpufreq = kvm_enabled() ? kvmppc_get_clockfreq() : 1000000000;

        uint32_t vmx = kvm_enabled() ? kvmppc_get_vmx() : 0;

        uint32_t dfp = kvm_enabled() ? kvmppc_get_dfp() : 0;

        if ((index % smt) != 0) {

            continue;

        }

        if (asprintf(&nodename, "%s@%x", modelname, index) < 0) {

            fprintf(stderr, "Allocation failure\n");

            exit(1);

        }

        _FDT((fdt_begin_node(fdt, nodename)));

        free(nodename);

        _FDT((fdt_property_cell(fdt, "reg", index)));

        _FDT((fdt_property_string(fdt, "device_type", "cpu")));

        _FDT((fdt_property_cell(fdt, "cpu-version", env->spr[SPR_PVR])));

        _FDT((fdt_property_cell(fdt, "dcache-block-size",

                                env->dcache_line_size)));

        _FDT((fdt_property_cell(fdt, "icache-block-size",

                                env->icache_line_size)));

        _FDT((fdt_property_cell(fdt, "timebase-frequency", tbfreq)));

        _FDT((fdt_property_cell(fdt, "clock-frequency", cpufreq)));

        _FDT((fdt_property_cell(fdt, "ibm,slb-size", env->slb_nr)));

        _FDT((fdt_property(fdt, "ibm,pft-size",

                           pft_size_prop, sizeof(pft_size_prop))));

        _FDT((fdt_property_string(fdt, "status", "okay")));

        _FDT((fdt_property(fdt, "64-bit", NULL, 0)));

        /* Build interrupt servers and gservers properties */

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

            servers_prop[i] = cpu_to_be32(index + i);

            /* Hack, direct the group queues back to cpu 0 */

            gservers_prop[i*2] = cpu_to_be32(index + i);

            gservers_prop[i*2 + 1] = 0;

        }

        _FDT((fdt_property(fdt, "ibm,ppc-interrupt-server#s",

                           servers_prop, sizeof(servers_prop))));

        _FDT((fdt_property(fdt, "ibm,ppc-interrupt-gserver#s",

                           gservers_prop, sizeof(gservers_prop))));

        if (env->mmu_model & POWERPC_MMU_1TSEG) {

            _FDT((fdt_property(fdt, "ibm,processor-segment-sizes",

                               segs, sizeof(segs))));

        }

        /* Advertise VMX/VSX (vector extensions) if available

         *   0 / no property == no vector extensions

         *   1               == VMX / Altivec available

         *   2               == VSX available */

        if (vmx) {

            _FDT((fdt_property_cell(fdt, "ibm,vmx", vmx)));

        }

        /* Advertise DFP (Decimal Floating Point) if available

         *   0 / no property == no DFP

         *   1               == DFP available */

        if (dfp) {

            _FDT((fdt_property_cell(fdt, "ibm,dfp", dfp)));

        }

        _FDT((fdt_end_node(fdt)));

    }

    g_free(modelname);

    _FDT((fdt_end_node(fdt)));

    /* RTAS */

    _FDT((fdt_begin_node(fdt, "rtas")));

    _FDT((fdt_property(fdt, "ibm,hypertas-functions", hypertas_prop,

                       sizeof(hypertas_prop))));

    _FDT((fdt_end_node(fdt)));

    /* interrupt controller */

    _FDT((fdt_begin_node(fdt, "interrupt-controller")));

    _FDT((fdt_property_string(fdt, "device_type",

                              "PowerPC-External-Interrupt-Presentation")));

    _FDT((fdt_property_string(fdt, "compatible", "IBM,ppc-xicp")));

    _FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));

    _FDT((fdt_property(fdt, "ibm,interrupt-server-ranges",

                       interrupt_server_ranges_prop,

                       sizeof(interrupt_server_ranges_prop))));

    _FDT((fdt_property_cell(fdt, "#interrupt-cells", 2)));

    _FDT((fdt_property_cell(fdt, "linux,phandle", PHANDLE_XICP)));

    _FDT((fdt_property_cell(fdt, "phandle", PHANDLE_XICP)));

    _FDT((fdt_end_node(fdt)));

    /* vdevice */

    _FDT((fdt_begin_node(fdt, "vdevice")));

    _FDT((fdt_property_string(fdt, "device_type", "vdevice")));

    _FDT((fdt_property_string(fdt, "compatible", "IBM,vdevice")));

    _FDT((fdt_property_cell(fdt, "#address-cells", 0x1)));

    _FDT((fdt_property_cell(fdt, "#size-cells", 0x0)));

    _FDT((fdt_property_cell(fdt, "#interrupt-cells", 0x2)));

    _FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));

    _FDT((fdt_end_node(fdt)));

    _FDT((fdt_end_node(fdt))); /* close root node */

    _FDT((fdt_finish(fdt)));

    return fdt;

}


static target_phys_addr_t get_offset(target_phys_addr_t phys_addr,

                                     DumpState *s)

{

    RAMBlock *block;

    target_phys_addr_t offset = s->memory_offset;

    int64_t size_in_block, start;

    if (s->has_filter) {

        if (phys_addr < s->begin || phys_addr >= s->begin + s->length) {

            return -1;

        }

    }

    QLIST_FOREACH(block, &ram_list.blocks, next) {

        if (s->has_filter) {

            if (block->offset >= s->begin + s->length ||

                block->offset + block->length <= s->begin) {

                /* This block is out of the range */

                continue;

            }

            if (s->begin <= block->offset) {

                start = block->offset;

            } else {

                start = s->begin;

            }

            size_in_block = block->length - (start - block->offset);

            if (s->begin + s->length < block->offset + block->length) {

                size_in_block -= block->offset + block->length -

                                 (s->begin + s->length);

            }

        } else {

            start = block->offset;

            size_in_block = block->length;

        }

        if (phys_addr >= start && phys_addr < start + size_in_block) {

            return phys_addr - start + offset;

        }

        offset += size_in_block;

    }

    return -1;

}


static MegasasCmd *megasas_enqueue_frame(MegasasState *s,

    target_phys_addr_t frame, uint64_t context, int count)

{

    MegasasCmd *cmd = NULL;

    int frame_size = MFI_FRAME_SIZE * 16;

    target_phys_addr_t frame_size_p = frame_size;

    cmd = megasas_next_frame(s, frame);

    /* All frames busy */

    if (!cmd) {

        return NULL;

    }

    if (!cmd->pa) {

        cmd->pa = frame;

        /* Map all possible frames */

        cmd->frame = cpu_physical_memory_map(frame, &frame_size_p, 0);

        if (frame_size_p != frame_size) {

            trace_megasas_qf_map_failed(cmd->index, (unsigned long)frame);

            if (cmd->frame) {

                cpu_physical_memory_unmap(cmd->frame, frame_size_p, 0, 0);

                cmd->frame = NULL;

                cmd->pa = 0;

            }

            s->event_count++;

            return NULL;

        }

        cmd->pa_size = frame_size_p;

        cmd->context = context;

        if (!megasas_use_queue64(s)) {

            cmd->context &= (uint64_t)0xFFFFFFFF;

        }

    }

    cmd->count = count;

    s->busy++;

    trace_megasas_qf_enqueue(cmd->index, cmd->count, cmd->context,

                             s->reply_queue_head, s->busy);

    return cmd;

}


void helper_stl_raw(uint64_t t0, uint64_t t1)

{

    stl_raw(t1, t0);

}


static void string_deserialize(void **native_out, void *datap,

                               VisitorFunc visit, Error **errp)

{

    StringSerializeData *d = datap;

    d->string = string_output_get_string(d->sov);

    d->siv = string_input_visitor_new(d->string);

    visit(d->siv, native_out, errp);

}


static uint16_t mlp_checksum16(const uint8_t *buf, unsigned int buf_size)

{

    uint16_t crc;

    if (!crc_init) {

        av_crc_init(crc_2D, 0, 16, 0x002D, sizeof(crc_2D));

        crc_init = 1;

    }

    crc = av_crc(crc_2D, 0, buf, buf_size - 2);

    crc ^= AV_RL16(buf + buf_size - 2);

    return crc;

}


static void blkdebug_debug_event(BlockDriverState *bs, BlkDebugEvent event)

{

    BDRVBlkdebugState *s = bs->opaque;

    struct BlkdebugRule *rule;

    bool injected;

    assert((int)event >= 0 && event < BLKDBG_EVENT_MAX);

    injected = false;

    s->new_state = s->state;

    QLIST_FOREACH(rule, &s->rules[event], next) {

        injected = process_rule(bs, rule, injected);

    }

    s->state = s->new_state;

}


static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)

{

    char buf[1024];

    VncShareMode mode;

    int size;

    mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;

    switch (vs->vd->share_policy) {

    case VNC_SHARE_POLICY_IGNORE:

        /*

         * Ignore the shared flag.  Nothing to do here.

         *

         * Doesn't conform to the rfb spec but is traditional qemu

         * behavior, thus left here as option for compatibility

         * reasons.

         */

        break;

    case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:

        /*

         * Policy: Allow clients ask for exclusive access.

         *

         * Implementation: When a client asks for exclusive access,

         * disconnect all others. Shared connects are allowed as long

         * as no exclusive connection exists.

         *

         * This is how the rfb spec suggests to handle the shared flag.

         */

        if (mode == VNC_SHARE_MODE_EXCLUSIVE) {

            VncState *client;

            QTAILQ_FOREACH(client, &vs->vd->clients, next) {

                if (vs == client) {

                    continue;

                }

                if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&

                    client->share_mode != VNC_SHARE_MODE_SHARED) {

                    continue;

                }

                vnc_disconnect_start(client);

            }

        }

        if (mode == VNC_SHARE_MODE_SHARED) {

            if (vs->vd->num_exclusive > 0) {

                vnc_disconnect_start(vs);

                return 0;

            }

        }

        break;

    case VNC_SHARE_POLICY_FORCE_SHARED:

        /*

         * Policy: Shared connects only.

         * Implementation: Disallow clients asking for exclusive access.

         *

         * Useful for shared desktop sessions where you don't want

         * someone forgetting to say -shared when running the vnc

         * client disconnect everybody else.

         */

        if (mode == VNC_SHARE_MODE_EXCLUSIVE) {

            vnc_disconnect_start(vs);

            return 0;

        }

        break;

    }

    vnc_set_share_mode(vs, mode);

    if (vs->vd->num_shared > vs->vd->connections_limit) {

        vnc_disconnect_start(vs);

        return 0;

    }

    vs->client_width = pixman_image_get_width(vs->vd->server);

    vs->client_height = pixman_image_get_height(vs->vd->server);

    vnc_write_u16(vs, vs->client_width);

    vnc_write_u16(vs, vs->client_height);

    pixel_format_message(vs);

    if (qemu_name)

        size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);

    else

        size = snprintf(buf, sizeof(buf), "QEMU");

    vnc_write_u32(vs, size);

    vnc_write(vs, buf, size);

    vnc_flush(vs);

    vnc_client_cache_auth(vs);

    vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);

    vnc_read_when(vs, protocol_client_msg, 1);

    return 0;

}


static void migration_completion(MigrationState *s, int current_active_state,

                                 bool *old_vm_running,

                                 int64_t *start_time)

{

    int ret;

    if (s->state == MIGRATION_STATUS_ACTIVE) {

        qemu_mutex_lock_iothread();

        *start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);

        qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);

        *old_vm_running = runstate_is_running();

        ret = global_state_store();

        if (!ret) {

            ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);

            if (ret >= 0) {

                ret = bdrv_inactivate_all();

            }

            if (ret >= 0) {

                qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);

                qemu_savevm_state_complete_precopy(s->to_dst_file, false);

            }

        }

        qemu_mutex_unlock_iothread();

        if (ret < 0) {

            goto fail;

        }

    } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {

        trace_migration_completion_postcopy_end();

        qemu_savevm_state_complete_postcopy(s->to_dst_file);

        trace_migration_completion_postcopy_end_after_complete();

    }

    /*

     * If rp was opened we must clean up the thread before

     * cleaning everything else up (since if there are no failures

     * it will wait for the destination to send it's status in

     * a SHUT command).

     * Postcopy opens rp if enabled (even if it's not avtivated)

     */

    if (migrate_postcopy_ram()) {

        int rp_error;

        trace_migration_completion_postcopy_end_before_rp();

        rp_error = await_return_path_close_on_source(s);

        trace_migration_completion_postcopy_end_after_rp(rp_error);

        if (rp_error) {

            goto fail_invalidate;

        }

    }

    if (qemu_file_get_error(s->to_dst_file)) {

        trace_migration_completion_file_err();

        goto fail_invalidate;

    }

    migrate_set_state(&s->state, current_active_state,

                      MIGRATION_STATUS_COMPLETED);

    return;

fail_invalidate:

    /* If not doing postcopy, vm_start() will be called: let's regain

     * control on images.

     */

    if (s->state == MIGRATION_STATUS_ACTIVE) {

        Error *local_err = NULL;

        bdrv_invalidate_cache_all(&local_err);

        if (local_err) {

            error_report_err(local_err);

        }

    }

fail:

    migrate_set_state(&s->state, current_active_state,

                      MIGRATION_STATUS_FAILED);

}


void replay_read_next_clock(ReplayClockKind kind)

{

    unsigned int read_kind = replay_data_kind - EVENT_CLOCK;

    assert(read_kind == kind);

    int64_t clock = replay_get_qword();

    replay_check_error();

    replay_finish_event();

    replay_state.cached_clock[read_kind] = clock;

}


static void exynos4210_gfrc_event(void *opaque)

{

    Exynos4210MCTState *s = (Exynos4210MCTState *)opaque;

    int i;

    uint64_t distance;

    DPRINTF("\n");

    s->g_timer.reg.cnt += s->g_timer.count;

    /* Process all comparators */

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

        if (s->g_timer.reg.cnt == s->g_timer.reg.comp[i]) {

            /* reached nearest comparator */

            s->g_timer.reg.int_cstat |= G_INT_CSTAT_COMP(i);

            /* Auto increment */

            if (s->g_timer.reg.tcon & G_TCON_AUTO_ICREMENT(i)) {

                s->g_timer.reg.comp[i] += s->g_timer.reg.comp_add_incr[i];

            }

            /* IRQ */

            exynos4210_gcomp_raise_irq(&s->g_timer, i);

        }

    }

    /* Reload FRC to reach nearest comparator */

    s->g_timer.curr_comp = exynos4210_gcomp_find(s);

    distance = exynos4210_gcomp_get_distance(s, s->g_timer.curr_comp);

    if (distance > MCT_GT_COUNTER_STEP) {

        distance = MCT_GT_COUNTER_STEP;

    }

    exynos4210_gfrc_set_count(&s->g_timer, distance);

    exynos4210_gfrc_start(&s->g_timer);

}


static void lance_init(NICInfo *nd, target_phys_addr_t leaddr,

                       void *dma_opaque, qemu_irq irq)

{

    DeviceState *dev;

    SysBusDevice *s;

    qemu_irq reset;

    qemu_check_nic_model(&nd_table[0], "lance");

    dev = qdev_create(NULL, "lance");

    dev->nd = nd;

    qdev_prop_set_ptr(dev, "dma", dma_opaque);

    qdev_init(dev);

    s = sysbus_from_qdev(dev);

    sysbus_mmio_map(s, 0, leaddr);

    sysbus_connect_irq(s, 0, irq);

    reset = qdev_get_gpio_in(dev, 0);

    qdev_connect_gpio_out(dma_opaque, 0, reset);

}


int ff_mpeg_ref_picture(MpegEncContext *s, Picture *dst, Picture *src)

{

    int ret;

    av_assert0(!dst->f.buf[0]);

    av_assert0(src->f.buf[0]);

    src->tf.f = &src->f;

    dst->tf.f = &dst->f;

    ret = ff_thread_ref_frame(&dst->tf, &src->tf);

    if (ret < 0)

        goto fail;

    ret = update_picture_tables(dst, src);

    if (ret < 0)

        goto fail;

    if (src->hwaccel_picture_private) {

        dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);

        if (!dst->hwaccel_priv_buf)

            goto fail;

        dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;

    }

    dst->field_picture           = src->field_picture;

    dst->mb_var_sum              = src->mb_var_sum;

    dst->mc_mb_var_sum           = src->mc_mb_var_sum;

    dst->b_frame_score           = src->b_frame_score;

    dst->needs_realloc           = src->needs_realloc;

    dst->reference               = src->reference;

    dst->shared                  = src->shared;

    return 0;

fail:

    ff_mpeg_unref_picture(s, dst);

    return ret;

}


static int encode_slices(VC2EncContext *s)

{

    uint8_t *buf;

    int i, slice_x, slice_y, skip = 0;

    int bytes_left = 0;

    SliceArgs *enc_args = s->slice_args;

    int bytes_top[SLICE_REDIST_TOTAL] = {0};

    SliceArgs *top_loc[SLICE_REDIST_TOTAL] = {NULL};

    avpriv_align_put_bits(&s->pb);

    flush_put_bits(&s->pb);

    buf = put_bits_ptr(&s->pb);

    for (slice_y = 0; slice_y < s->num_y; slice_y++) {

        for (slice_x = 0; slice_x < s->num_x; slice_x++) {

            SliceArgs *args = &enc_args[s->num_x*slice_y + slice_x];

            bytes_left += args->bytes_left;

            for (i = 0; i < FFMIN(SLICE_REDIST_TOTAL, s->num_x*s->num_y); i++) {

                if (args->bytes > bytes_top[i]) {

                    bytes_top[i] = args->bytes;

                    top_loc[i] = args;

                    break;

                }

            }

        }

    }

    while (1) {

        int distributed = 0;

        for (i = 0; i < FFMIN(SLICE_REDIST_TOTAL, s->num_x*s->num_y); i++) {

            SliceArgs *args;

            int bits, bytes, diff, prev_bytes, new_idx;

            if (bytes_left <= 0)

                break;

            if (!top_loc[i] || !top_loc[i]->quant_idx)

                break;

            args = top_loc[i];

            prev_bytes = args->bytes;

            new_idx = av_clip(args->quant_idx - 1, 0, s->q_ceil);

            bits = count_hq_slice(s, args->cache, args->x, args->y, new_idx);

            bytes = FFALIGN((bits >> 3), s->size_scaler) + 4 + s->prefix_bytes;

            diff = bytes - prev_bytes;

            if ((bytes_left - diff) >= 0) {

                args->quant_idx = new_idx;

                args->bytes = bytes;

                bytes_left -= diff;

                distributed++;

            }

        }

        if (!distributed)

            break;

    }

    for (slice_y = 0; slice_y < s->num_y; slice_y++) {

        for (slice_x = 0; slice_x < s->num_x; slice_x++) {

            SliceArgs *args = &enc_args[s->num_x*slice_y + slice_x];

            init_put_bits(&args->pb, buf + skip, args->bytes);

            s->q_avg = (s->q_avg + args->quant_idx)/2;

            skip += args->bytes;

        }

    }

    s->avctx->execute(s->avctx, encode_hq_slice, enc_args, NULL, s->num_x*s->num_y,

                      sizeof(SliceArgs));

    skip_put_bytes(&s->pb, skip);

    return 0;

}


int64_t parse_time_or_die(const char *context, const char *timestr,

                          int is_duration)

{

    int64_t us;

    if (av_parse_time(&us, timestr, is_duration) < 0) {

        av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",

               is_duration ? "duration" : "date", context, timestr);

        exit(1);

    }

    return us;

}


static void rtas_stop_self(PowerPCCPU *cpu, sPAPRMachineState *spapr,

                           uint32_t token, uint32_t nargs,

                           target_ulong args,

                           uint32_t nret, target_ulong rets)

{

    CPUState *cs = CPU(cpu);

    CPUPPCState *env = &cpu->env;

    cs->halted = 1;

    qemu_cpu_kick(cs);

    /*

     * While stopping a CPU, the guest calls H_CPPR which

     * effectively disables interrupts on XICS level.

     * However decrementer interrupts in TCG can still

     * wake the CPU up so here we disable interrupts in MSR

     * as well.

     * As rtas_start_cpu() resets the whole MSR anyway, there is

     * no need to bother with specific bits, we just clear it.

     */

    env->msr = 0;

    /* Disable Power-saving mode Exit Cause exceptions for the CPU.

     * This could deliver an interrupt on a dying CPU and crash the

     * guest */

    env->spr[SPR_LPCR] &= ~pcc->lpcr_pm;

}


static int get_cluster_offset(BlockDriverState *bs,

                              uint64_t offset, int allocate,

                              int compressed_size,

                              int n_start, int n_end, uint64_t *result)

{

    BDRVQcowState *s = bs->opaque;

    int min_index, i, j, l1_index, l2_index, ret;

    uint64_t l2_offset, *l2_table, cluster_offset, tmp;

    uint32_t min_count;

    int new_l2_table;

    *result = 0;

    l1_index = offset >> (s->l2_bits + s->cluster_bits);

    l2_offset = s->l1_table[l1_index];

    new_l2_table = 0;

    if (!l2_offset) {

        if (!allocate)

            return 0;

        /* allocate a new l2 entry */

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

        /* round to cluster size */

        l2_offset = (l2_offset + s->cluster_size - 1) & ~(s->cluster_size - 1);

        /* update the L1 entry */

        s->l1_table[l1_index] = l2_offset;

        tmp = cpu_to_be64(l2_offset);

        ret = bdrv_pwrite_sync(bs->file,

                               s->l1_table_offset + l1_index * sizeof(tmp),

                               &tmp, sizeof(tmp));

        if (ret < 0) {

            return ret;

        }

        new_l2_table = 1;

    }

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

        if (l2_offset == s->l2_cache_offsets[i]) {

            /* increment the hit count */

            if (++s->l2_cache_counts[i] == 0xffffffff) {

                for(j = 0; j < L2_CACHE_SIZE; j++) {

                    s->l2_cache_counts[j] >>= 1;

                }

            }

            l2_table = s->l2_cache + (i << s->l2_bits);

            goto found;

        }

    }

    /* not found: load a new entry in the least used one */

    min_index = 0;

    min_count = 0xffffffff;

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

        if (s->l2_cache_counts[i] < min_count) {

            min_count = s->l2_cache_counts[i];

            min_index = i;

        }

    }

    l2_table = s->l2_cache + (min_index << s->l2_bits);

    if (new_l2_table) {

        memset(l2_table, 0, s->l2_size * sizeof(uint64_t));

        ret = bdrv_pwrite_sync(bs->file, l2_offset, l2_table,

                               s->l2_size * sizeof(uint64_t));

        if (ret < 0) {

            return ret;

        }

    } else {

        ret = bdrv_pread(bs->file, l2_offset, l2_table,

                         s->l2_size * sizeof(uint64_t));

        if (ret < 0) {

            return ret;

        }

    }

    s->l2_cache_offsets[min_index] = l2_offset;

    s->l2_cache_counts[min_index] = 1;

 found:

    l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);

    cluster_offset = be64_to_cpu(l2_table[l2_index]);

    if (!cluster_offset ||

        ((cluster_offset & QCOW_OFLAG_COMPRESSED) && allocate == 1)) {

        if (!allocate)

            return 0;

        /* allocate a new cluster */

        if ((cluster_offset & QCOW_OFLAG_COMPRESSED) &&

            (n_end - n_start) < s->cluster_sectors) {

            /* if the cluster is already compressed, we must

               decompress it in the case it is not completely

               overwritten */

            if (decompress_cluster(bs, cluster_offset) < 0) {

                return -EIO;

            }

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

            cluster_offset = (cluster_offset + s->cluster_size - 1) &

                ~(s->cluster_size - 1);

            /* write the cluster content */

            ret = bdrv_pwrite(bs->file, cluster_offset, s->cluster_cache,

                              s->cluster_size);

            if (ret < 0) {

                return ret;

            }

        } else {

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

            if (allocate == 1) {

                /* round to cluster size */

                cluster_offset = (cluster_offset + s->cluster_size - 1) &

                    ~(s->cluster_size - 1);

                bdrv_truncate(bs->file, cluster_offset + s->cluster_size,

                              PREALLOC_MODE_OFF, NULL);

                /* if encrypted, we must initialize the cluster

                   content which won't be written */

                if (bs->encrypted &&

                    (n_end - n_start) < s->cluster_sectors) {

                    uint64_t start_sect;

                    assert(s->crypto);

                    start_sect = (offset & ~(s->cluster_size - 1)) >> 9;

                    for(i = 0; i < s->cluster_sectors; i++) {

                        if (i < n_start || i >= n_end) {

                            memset(s->cluster_data, 0x00, 512);

                            if (qcrypto_block_encrypt(s->crypto, start_sect + i,

                                                      s->cluster_data,

                                                      BDRV_SECTOR_SIZE,

                                                      NULL) < 0) {

                                return -EIO;

                            }

                            ret = bdrv_pwrite(bs->file,

                                              cluster_offset + i * 512,

                                              s->cluster_data, 512);

                            if (ret < 0) {

                                return ret;

                            }

                        }

                    }

                }

            } else if (allocate == 2) {

                cluster_offset |= QCOW_OFLAG_COMPRESSED |

                    (uint64_t)compressed_size << (63 - s->cluster_bits);

            }

        }

        /* update L2 table */

        tmp = cpu_to_be64(cluster_offset);

        l2_table[l2_index] = tmp;

        ret = bdrv_pwrite_sync(bs->file, l2_offset + l2_index * sizeof(tmp),

                               &tmp, sizeof(tmp));

        if (ret < 0) {

            return ret;

        }

    }

    *result = cluster_offset;

    return 1;

}