BlockDeviceInfo *bdrv_block_device_info(BlockBackend *blk,

                                        BlockDriverState *bs, Error **errp)

{

    ImageInfo **p_image_info;

    BlockDriverState *bs0;

    BlockDeviceInfo *info = g_malloc0(sizeof(*info));

    info->file                   = g_strdup(bs->filename);

    info->ro                     = bs->read_only;

    info->drv                    = g_strdup(bs->drv->format_name);

    info->encrypted              = bs->encrypted;

    info->encryption_key_missing = false;

    info->cache = g_new(BlockdevCacheInfo, 1);

    *info->cache = (BlockdevCacheInfo) {

        .writeback      = blk ? blk_enable_write_cache(blk) : true,

        .direct         = !!(bs->open_flags & BDRV_O_NOCACHE),

        .no_flush       = !!(bs->open_flags & BDRV_O_NO_FLUSH),

    };

    if (bs->node_name[0]) {

        info->has_node_name = true;

        info->node_name = g_strdup(bs->node_name);

    }

    if (bs->backing_file[0]) {

        info->has_backing_file = true;

        info->backing_file = g_strdup(bs->backing_file);

    }

    info->detect_zeroes = bs->detect_zeroes;

    if (blk && blk_get_public(blk)->throttle_state) {

        ThrottleConfig cfg;

        throttle_group_get_config(blk, &cfg);

        info->bps     = cfg.buckets[THROTTLE_BPS_TOTAL].avg;

        info->bps_rd  = cfg.buckets[THROTTLE_BPS_READ].avg;

        info->bps_wr  = cfg.buckets[THROTTLE_BPS_WRITE].avg;

        info->iops    = cfg.buckets[THROTTLE_OPS_TOTAL].avg;

        info->iops_rd = cfg.buckets[THROTTLE_OPS_READ].avg;

        info->iops_wr = cfg.buckets[THROTTLE_OPS_WRITE].avg;

        info->has_bps_max     = cfg.buckets[THROTTLE_BPS_TOTAL].max;

        info->bps_max         = cfg.buckets[THROTTLE_BPS_TOTAL].max;

        info->has_bps_rd_max  = cfg.buckets[THROTTLE_BPS_READ].max;

        info->bps_rd_max      = cfg.buckets[THROTTLE_BPS_READ].max;

        info->has_bps_wr_max  = cfg.buckets[THROTTLE_BPS_WRITE].max;

        info->bps_wr_max      = cfg.buckets[THROTTLE_BPS_WRITE].max;

        info->has_iops_max    = cfg.buckets[THROTTLE_OPS_TOTAL].max;

        info->iops_max        = cfg.buckets[THROTTLE_OPS_TOTAL].max;

        info->has_iops_rd_max = cfg.buckets[THROTTLE_OPS_READ].max;

        info->iops_rd_max     = cfg.buckets[THROTTLE_OPS_READ].max;

        info->has_iops_wr_max = cfg.buckets[THROTTLE_OPS_WRITE].max;

        info->iops_wr_max     = cfg.buckets[THROTTLE_OPS_WRITE].max;

        info->has_bps_max_length     = info->has_bps_max;

        info->bps_max_length         =

            cfg.buckets[THROTTLE_BPS_TOTAL].burst_length;

        info->has_bps_rd_max_length  = info->has_bps_rd_max;

        info->bps_rd_max_length      =

            cfg.buckets[THROTTLE_BPS_READ].burst_length;

        info->has_bps_wr_max_length  = info->has_bps_wr_max;

        info->bps_wr_max_length      =

            cfg.buckets[THROTTLE_BPS_WRITE].burst_length;

        info->has_iops_max_length    = info->has_iops_max;

        info->iops_max_length        =

            cfg.buckets[THROTTLE_OPS_TOTAL].burst_length;

        info->has_iops_rd_max_length = info->has_iops_rd_max;

        info->iops_rd_max_length     =

            cfg.buckets[THROTTLE_OPS_READ].burst_length;

        info->has_iops_wr_max_length = info->has_iops_wr_max;

        info->iops_wr_max_length     =

            cfg.buckets[THROTTLE_OPS_WRITE].burst_length;

        info->has_iops_size = cfg.op_size;

        info->iops_size = cfg.op_size;

        info->has_group = true;

        info->group = g_strdup(throttle_group_get_name(blk));

    }

    info->write_threshold = bdrv_write_threshold_get(bs);

    bs0 = bs;

    p_image_info = &info->image;

    info->backing_file_depth = 0;

    while (1) {

        Error *local_err = NULL;

        bdrv_query_image_info(bs0, p_image_info, &local_err);

        if (local_err) {

            error_propagate(errp, local_err);

            qapi_free_BlockDeviceInfo(info);

            return NULL;

        }

        if (bs0->drv && bs0->backing) {

            info->backing_file_depth++;

            bs0 = bs0->backing->bs;

            (*p_image_info)->has_backing_image = true;

            p_image_info = &((*p_image_info)->backing_image);

        } else {

            break;

        }

        /* Skip automatically inserted nodes that the user isn't aware of for

         * query-block (blk != NULL), but not for query-named-block-nodes */

        while (blk && bs0 && bs0->drv && bs0->implicit) {

            bs0 = backing_bs(bs0);

        }

    }

    return info;

}


void qemu_clock_unregister_reset_notifier(QEMUClockType type,

                                          Notifier *notifier)

{

    notifier_remove(notifier);

}


static void ppc_core99_init (int ram_size, int vga_ram_size,

                             const char *boot_device, DisplayState *ds,

                             const char **fd_filename, int snapshot,

                             const char *kernel_filename,

                             const char *kernel_cmdline,

                             const char *initrd_filename,

                             const char *cpu_model)

{

    CPUState *env = NULL, *envs[MAX_CPUS];

    char buf[1024];

    qemu_irq *pic, **openpic_irqs;

    int unin_memory;

    int linux_boot, i;

    unsigned long bios_offset, vga_bios_offset;

    uint32_t kernel_base, kernel_size, initrd_base, initrd_size;

    PCIBus *pci_bus;

    nvram_t nvram;

#if 0

    MacIONVRAMState *nvr;

    int nvram_mem_index;

#endif

    m48t59_t *m48t59;

    int vga_bios_size, bios_size;

    qemu_irq *dummy_irq;

    int pic_mem_index, dbdma_mem_index, cuda_mem_index;

    int ide_mem_index[2];

    int ppc_boot_device = boot_device[0];

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (cpu_model == NULL)

        cpu_model = "default";

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

        env = cpu_init(cpu_model);

        if (!env) {

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

            exit(1);

        }

        /* Set time-base frequency to 100 Mhz */

        cpu_ppc_tb_init(env, 100UL * 1000UL * 1000UL);

#if 0

        env->osi_call = vga_osi_call;

#endif

        qemu_register_reset(&cpu_ppc_reset, env);

        register_savevm("cpu", 0, 3, cpu_save, cpu_load, env);

        envs[i] = env;

    }

    if (env->nip < 0xFFF80000) {

        /* Special test for PowerPC 601:

         * the boot vector is at 0xFFF00100, then we need a 1MB BIOS.

         * But the NVRAM is located at 0xFFF04000...

         */

        cpu_abort(env, "Mac99 hardware can not handle 1 MB BIOS\n");

    }

    /* allocate RAM */

    cpu_register_physical_memory(0, ram_size, IO_MEM_RAM);

    /* allocate and load BIOS */

    bios_offset = ram_size + vga_ram_size;

    if (bios_name == NULL)

        bios_name = BIOS_FILENAME;

    snprintf(buf, sizeof(buf), "%s/%s", bios_dir, bios_name);

    bios_size = load_image(buf, phys_ram_base + bios_offset);

    if (bios_size < 0 || bios_size > BIOS_SIZE) {

        cpu_abort(env, "qemu: could not load PowerPC bios '%s'\n", buf);

        exit(1);

    }

    bios_size = (bios_size + 0xfff) & ~0xfff;

    if (bios_size > 0x00080000) {

        /* As the NVRAM is located at 0xFFF04000, we cannot use 1 MB BIOSes */

        cpu_abort(env, "Mac99 hardware can not handle 1 MB BIOS\n");

    }

    cpu_register_physical_memory((uint32_t)(-bios_size),

                                 bios_size, bios_offset | IO_MEM_ROM);

    /* allocate and load VGA BIOS */

    vga_bios_offset = bios_offset + bios_size;

    snprintf(buf, sizeof(buf), "%s/%s", bios_dir, VGABIOS_FILENAME);

    vga_bios_size = load_image(buf, phys_ram_base + vga_bios_offset + 8);

    if (vga_bios_size < 0) {

        /* if no bios is present, we can still work */

        fprintf(stderr, "qemu: warning: could not load VGA bios '%s'\n", buf);

        vga_bios_size = 0;

    } else {

        /* set a specific header (XXX: find real Apple format for NDRV

           drivers) */

        phys_ram_base[vga_bios_offset] = 'N';

        phys_ram_base[vga_bios_offset + 1] = 'D';

        phys_ram_base[vga_bios_offset + 2] = 'R';

        phys_ram_base[vga_bios_offset + 3] = 'V';

        cpu_to_be32w((uint32_t *)(phys_ram_base + vga_bios_offset + 4),

                     vga_bios_size);

        vga_bios_size += 8;

    }

    vga_bios_size = (vga_bios_size + 0xfff) & ~0xfff;

    if (linux_boot) {

        kernel_base = KERNEL_LOAD_ADDR;

        /* now we can load the kernel */

        kernel_size = load_image(kernel_filename, phys_ram_base + kernel_base);

        if (kernel_size < 0) {

            cpu_abort(env, "qemu: could not load kernel '%s'\n",

                      kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_base = INITRD_LOAD_ADDR;

            initrd_size = load_image(initrd_filename,

                                     phys_ram_base + initrd_base);

            if (initrd_size < 0) {

                cpu_abort(env, "qemu: could not load initial ram disk '%s'\n",

                          initrd_filename);

                exit(1);

            }

        } else {

            initrd_base = 0;

            initrd_size = 0;

        }

        ppc_boot_device = 'm';

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

    }

    isa_mem_base = 0x80000000;

    /* Register 8 MB of ISA IO space */

    isa_mmio_init(0xf2000000, 0x00800000);

    /* UniN init */

    unin_memory = cpu_register_io_memory(0, unin_read, unin_write, NULL);

    cpu_register_physical_memory(0xf8000000, 0x00001000, unin_memory);

    openpic_irqs = qemu_mallocz(smp_cpus * sizeof(qemu_irq *));

    openpic_irqs[0] =

        qemu_mallocz(smp_cpus * sizeof(qemu_irq) * OPENPIC_OUTPUT_NB);

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

        /* Mac99 IRQ connection between OpenPIC outputs pins

         * and PowerPC input pins

         */

        switch (PPC_INPUT(env)) {

        case PPC_FLAGS_INPUT_6xx:

            openpic_irqs[i] = openpic_irqs[0] + (i * OPENPIC_OUTPUT_NB);

            openpic_irqs[i][OPENPIC_OUTPUT_INT] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_CINT] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_MCK] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_MCP];

            /* Not connected ? */

            openpic_irqs[i][OPENPIC_OUTPUT_DEBUG] = NULL;

            /* Check this */

            openpic_irqs[i][OPENPIC_OUTPUT_RESET] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_HRESET];

            break;

#if defined(TARGET_PPC64)

        case PPC_FLAGS_INPUT_970:

            openpic_irqs[i] = openpic_irqs[0] + (i * OPENPIC_OUTPUT_NB);

            openpic_irqs[i][OPENPIC_OUTPUT_INT] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_CINT] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_MCK] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_MCP];

            /* Not connected ? */

            openpic_irqs[i][OPENPIC_OUTPUT_DEBUG] = NULL;

            /* Check this */

            openpic_irqs[i][OPENPIC_OUTPUT_RESET] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_HRESET];

            break;

#endif /* defined(TARGET_PPC64) */

        default:

            cpu_abort(env, "Bus model not supported on mac99 machine\n");

            exit(1);

        }

    }

    pic = openpic_init(NULL, &pic_mem_index, smp_cpus, openpic_irqs, NULL);

    pci_bus = pci_pmac_init(pic);

    /* init basic PC hardware */

    pci_vga_init(pci_bus, ds, phys_ram_base + ram_size,

                 ram_size, vga_ram_size,

                 vga_bios_offset, vga_bios_size);

    /* XXX: suppress that */

    dummy_irq = i8259_init(NULL);

    /* XXX: use Mac Serial port */

    serial_init(0x3f8, dummy_irq[4], serial_hds[0]);

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

        if (!nd_table[i].model)

            nd_table[i].model = "ne2k_pci";

        pci_nic_init(pci_bus, &nd_table[i], -1);

    }

#if 1

    ide_mem_index[0] = pmac_ide_init(&bs_table[0], pic[0x13]);

    ide_mem_index[1] = pmac_ide_init(&bs_table[2], pic[0x14]);

#else

    pci_cmd646_ide_init(pci_bus, &bs_table[0], 0);

#endif

    /* cuda also initialize ADB */

    cuda_init(&cuda_mem_index, pic[0x19]);

    adb_kbd_init(&adb_bus);

    adb_mouse_init(&adb_bus);

    dbdma_init(&dbdma_mem_index);

    macio_init(pci_bus, 0x0022, 0, pic_mem_index, dbdma_mem_index,

               cuda_mem_index, NULL, 2, ide_mem_index);

    if (usb_enabled) {

        usb_ohci_init_pci(pci_bus, 3, -1);

    }

    if (graphic_depth != 15 && graphic_depth != 32 && graphic_depth != 8)

        graphic_depth = 15;

#if 0 /* XXX: this is ugly but needed for now, or OHW won't boot */

    /* The NewWorld NVRAM is not located in the MacIO device */

    nvr = macio_nvram_init(&nvram_mem_index, 0x2000);

    pmac_format_nvram_partition(nvr, 0x2000);

    macio_nvram_map(nvr, 0xFFF04000);

    nvram.opaque = nvr;

    nvram.read_fn = &macio_nvram_read;

    nvram.write_fn = &macio_nvram_write;

#else

    m48t59 = m48t59_init(dummy_irq[8], 0xFFF04000, 0x0074, NVRAM_SIZE, 59);

    nvram.opaque = m48t59;

    nvram.read_fn = &m48t59_read;

    nvram.write_fn = &m48t59_write;

#endif

    PPC_NVRAM_set_params(&nvram, NVRAM_SIZE, "MAC99", ram_size,

                         ppc_boot_device, kernel_base, kernel_size,

                         kernel_cmdline,

                         initrd_base, initrd_size,

                         /* XXX: need an option to load a NVRAM image */

                         0,

                         graphic_width, graphic_height, graphic_depth);

    /* No PCI init: the BIOS will do it */

    /* Special port to get debug messages from Open-Firmware */

    register_ioport_write(0x0F00, 4, 1, &PPC_debug_write, NULL);

 }


POWERPC_FAMILY(POWER5P)(ObjectClass *oc, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    PowerPCCPUClass *pcc = POWERPC_CPU_CLASS(oc);

    dc->fw_name = "PowerPC,POWER5";

    dc->desc = "POWER5+";

    pcc->init_proc = init_proc_power5plus;

    pcc->check_pow = check_pow_970FX;

    pcc->insns_flags = PPC_INSNS_BASE | PPC_STRING | PPC_MFTB |

                       PPC_FLOAT | PPC_FLOAT_FSEL | PPC_FLOAT_FRES |

                       PPC_FLOAT_FSQRT | PPC_FLOAT_FRSQRTE |

                       PPC_FLOAT_STFIWX |

                       PPC_CACHE | PPC_CACHE_ICBI | PPC_CACHE_DCBZ |

                       PPC_MEM_SYNC | PPC_MEM_EIEIO |

                       PPC_MEM_TLBIE | PPC_MEM_TLBSYNC |

                       PPC_64B |

                       PPC_SEGMENT_64B | PPC_SLBI;

    pcc->msr_mask = (1ull << MSR_SF) |

                    (1ull << MSR_VR) |

                    (1ull << MSR_POW) |

                    (1ull << MSR_EE) |

                    (1ull << MSR_PR) |

                    (1ull << MSR_FP) |

                    (1ull << MSR_ME) |

                    (1ull << MSR_FE0) |

                    (1ull << MSR_SE) |

                    (1ull << MSR_DE) |

                    (1ull << MSR_FE1) |

                    (1ull << MSR_IR) |

                    (1ull << MSR_DR) |

                    (1ull << MSR_PMM) |

                    (1ull << MSR_RI);

    pcc->mmu_model = POWERPC_MMU_64B;

#if defined(CONFIG_SOFTMMU)

    pcc->handle_mmu_fault = ppc_hash64_handle_mmu_fault;

#endif

    pcc->excp_model = POWERPC_EXCP_970;

    pcc->bus_model = PPC_FLAGS_INPUT_970;

    pcc->bfd_mach = bfd_mach_ppc64;

    pcc->flags = POWERPC_FLAG_VRE | POWERPC_FLAG_SE |

                 POWERPC_FLAG_BE | POWERPC_FLAG_PMM |

                 POWERPC_FLAG_BUS_CLK;

    pcc->l1_dcache_size = 0x8000;

    pcc->l1_icache_size = 0x10000;

}


static unsigned int dec_addi_acr(DisasContext *dc)

{

	TCGv t0;

	DIS(fprintf (logfile, "addi.%c $r%u, $r%u, $acr\n",

		  memsize_char(memsize_zz(dc)), dc->op2, dc->op1));

	cris_cc_mask(dc, 0);

	t0 = tcg_temp_new(TCG_TYPE_TL);

	tcg_gen_shl_tl(t0, cpu_R[dc->op2], tcg_const_tl(dc->zzsize));

	tcg_gen_add_tl(cpu_R[R_ACR], cpu_R[dc->op1], t0);

	tcg_temp_free(t0);

	return 2;

}


static void test_visitor_out_list_qapi_free(TestOutputVisitorData *data,

                                            const void *unused)

{

    UserDefTwoList *p, *head = NULL;

    const char string[] = "foo bar";

    int i, max_count = 1024;

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

        p = g_malloc0(sizeof(*p));

        p->value = g_malloc0(sizeof(*p->value));

        p->value->string0 = g_strdup(string);

        p->value->dict1 = g_new0(UserDefTwoDict, 1);

        p->value->dict1->string1 = g_strdup(string);

        p->value->dict1->dict2 = g_new0(UserDefTwoDictDict, 1);

        p->value->dict1->dict2->userdef = g_new0(UserDefOne, 1);

        p->value->dict1->dict2->userdef->string = g_strdup(string);

        p->value->dict1->dict2->userdef->integer = 42;

        p->value->dict1->dict2->string = g_strdup(string);

        p->value->dict1->has_dict3 = false;

        p->next = head;

        head = p;

    }

    qapi_free_UserDefTwoList(head);

}


void bdrv_io_limits_enable(BlockDriverState *bs, const char *group)

{

    assert(!bs->throttle_state);

    throttle_group_register_bs(bs, group);

}


static bool select_accel_fn(const void *buf, size_t len)

{

    uintptr_t ibuf = (uintptr_t)buf;

#ifdef CONFIG_AVX2_OPT

    if (len % 128 == 0 && ibuf % 32 == 0 && (cpuid_cache & CACHE_AVX2)) {

        return buffer_zero_avx2(buf, len);

    }

    if (len % 64 == 0 && ibuf % 16 == 0 && (cpuid_cache & CACHE_SSE4)) {

        return buffer_zero_sse4(buf, len);

    }

#endif

    if (len % 64 == 0 && ibuf % 16 == 0 && (cpuid_cache & CACHE_SSE2)) {

        return buffer_zero_sse2(buf, len);

    }

    return buffer_zero_int(buf, len);

}


static void cpu_ppc_set_tb_clk (void *opaque, uint32_t freq)

{

    CPUState *env = opaque;

    ppc_tb_t *tb_env = env->tb_env;

    tb_env->tb_freq = freq;

    tb_env->decr_freq = freq;

    /* There is a bug in Linux 2.4 kernels:

     * if a decrementer exception is pending when it enables msr_ee at startup,

     * it's not ready to handle it...

     */

    _cpu_ppc_store_decr(env, 0xFFFFFFFF, 0xFFFFFFFF, 0);

#if defined(TARGET_PPC64H)

    _cpu_ppc_store_hdecr(env, 0xFFFFFFFF, 0xFFFFFFFF, 0);

    cpu_ppc_store_purr(env, 0x0000000000000000ULL);

#endif /* defined(TARGET_PPC64H) */

}


static int init_filter_param(AVFilterContext *ctx, FilterParam *fp, const char *effect_type, int width)

{

    int z;

    const char *effect = fp->amount == 0 ? "none" : fp->amount < 0 ? "blur" : "sharpen";

    if  (!(fp->msize_x & fp->msize_y & 1)) {

        av_log(ctx, AV_LOG_ERROR,

               "Invalid even size for %s matrix size %dx%d\n",

               effect_type, fp->msize_x, fp->msize_y);

        return AVERROR(EINVAL);

    }

    av_log(ctx, AV_LOG_VERBOSE, "effect:%s type:%s msize_x:%d msize_y:%d amount:%0.2f\n",

           effect, effect_type, fp->msize_x, fp->msize_y, fp->amount / 65535.0);

    for (z = 0; z < 2 * fp->steps_y; z++)

        fp->sc[z] = av_malloc(sizeof(*(fp->sc[z])) * (width + 2 * fp->steps_x));

    return 0;

}


static void do_video_out(AVFormatContext *s,

                         AVOutputStream *ost,

                         AVInputStream *ist,

                         AVFrame *in_picture,

                         int *frame_size)

{

    int nb_frames, i, ret;

    AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;

    AVFrame picture_crop_temp, picture_pad_temp;

    AVCodecContext *enc, *dec;

    avcodec_get_frame_defaults(&picture_crop_temp);

    avcodec_get_frame_defaults(&picture_pad_temp);

    enc = ost->st->codec;

    dec = ist->st->codec;

    /* by default, we output a single frame */

    nb_frames = 1;

    *frame_size = 0;

    if(video_sync_method>0 || (video_sync_method && av_q2d(enc->time_base) > 0.001)){

        double vdelta;

        vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;

        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c

        if (vdelta < -1.1)

            nb_frames = 0;

        else if (video_sync_method == 2)

            ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));

        else if (vdelta > 1.1)

            nb_frames = lrintf(vdelta);

//fprintf(stderr, "vdelta:%f, ost->sync_opts:%"PRId64", ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, ost->sync_ipts, nb_frames);

        if (nb_frames == 0){

            ++nb_frames_drop;

            if (verbose>2)

                fprintf(stderr, "*** drop!\n");

        }else if (nb_frames > 1) {

            nb_frames_dup += nb_frames;

            if (verbose>2)

                fprintf(stderr, "*** %d dup!\n", nb_frames-1);

        }

    }else

        ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));

    nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);

    if (nb_frames <= 0)

        return;

    if (ost->video_crop) {

        if (av_picture_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {

            av_log(NULL, AV_LOG_ERROR, "error cropping picture\n");

            if (exit_on_error)

                av_exit(1);

            return;

        }

        formatted_picture = &picture_crop_temp;

    } else {

        formatted_picture = in_picture;

    }

    final_picture = formatted_picture;

    padding_src = formatted_picture;

    resampling_dst = &ost->pict_tmp;

    if (ost->video_pad) {

        final_picture = &ost->pict_tmp;

        if (ost->video_resample) {

            if (av_picture_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {

                av_log(NULL, AV_LOG_ERROR, "error padding picture\n");

                if (exit_on_error)

                    av_exit(1);

                return;

            }

            resampling_dst = &picture_pad_temp;

        }

    }

    if (ost->video_resample) {

        padding_src = NULL;

        final_picture = &ost->pict_tmp;

        sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,

              0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);

    }

    if (ost->video_pad) {

        av_picture_pad((AVPicture*)final_picture, (AVPicture *)padding_src,

                enc->height, enc->width, enc->pix_fmt,

                ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);

    }

    /* duplicates frame if needed */

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

        AVPacket pkt;

        av_init_packet(&pkt);

        pkt.stream_index= ost->index;

        if (s->oformat->flags & AVFMT_RAWPICTURE) {

            /* raw pictures are written as AVPicture structure to

               avoid any copies. We support temorarily the older

               method. */

            AVFrame* old_frame = enc->coded_frame;

            enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack

            pkt.data= (uint8_t *)final_picture;

            pkt.size=  sizeof(AVPicture);

            pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);

            pkt.flags |= PKT_FLAG_KEY;

            write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);

            enc->coded_frame = old_frame;

        } else {

            AVFrame big_picture;

            big_picture= *final_picture;

            /* better than nothing: use input picture interlaced

               settings */

            big_picture.interlaced_frame = in_picture->interlaced_frame;

            if(avctx_opts[CODEC_TYPE_VIDEO]->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){

                if(top_field_first == -1)

                    big_picture.top_field_first = in_picture->top_field_first;

                else

                    big_picture.top_field_first = top_field_first;

            }

            /* handles sameq here. This is not correct because it may

               not be a global option */

            if (same_quality) {

                big_picture.quality = ist->st->quality;

            }else

                big_picture.quality = ost->st->quality;

            if(!me_threshold)

                big_picture.pict_type = 0;

//            big_picture.pts = AV_NOPTS_VALUE;

            big_picture.pts= ost->sync_opts;

//            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);

//av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);

            ret = avcodec_encode_video(enc,

                                       bit_buffer, bit_buffer_size,

                                       &big_picture);

            if (ret == -1) {

                fprintf(stderr, "Video encoding failed\n");

                av_exit(1);

            }

            //enc->frame_number = enc->real_pict_num;

            if(ret>0){

                pkt.data= bit_buffer;

                pkt.size= ret;

                if(enc->coded_frame->pts != AV_NOPTS_VALUE)

                    pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);

/*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",

   pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,

   pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/

                if(enc->coded_frame->key_frame)

                    pkt.flags |= PKT_FLAG_KEY;

                write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);

                *frame_size = ret;

                video_size += ret;

                //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",

                //        enc->frame_number-1, enc->real_pict_num, ret,

                //        enc->pict_type);

                /* if two pass, output log */

                if (ost->logfile && enc->stats_out) {

                    fprintf(ost->logfile, "%s", enc->stats_out);

                }

            }

        }

        ost->sync_opts++;

        ost->frame_number++;

    }

}


static void pci_apb_iowritel (void *opaque, target_phys_addr_t addr,

                                uint32_t val)

{

    cpu_outl(addr & IOPORTS_MASK, bswap32(val));

}


tight_detect_smooth_image24(VncState *vs, int w, int h)

{

    int off;

    int x, y, d, dx;

    uint c;

    uint stats[256];

    int pixels = 0;

    int pix, left[3];

    uint errors;

    unsigned char *buf = vs->tight.buffer;

    /*

     * If client is big-endian, color samples begin from the second

     * byte (offset 1) of a 32-bit pixel value.

     */

    off = !!(vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG);

    memset(stats, 0, sizeof (stats));

    for (y = 0, x = 0; y < h && x < w;) {

        for (d = 0; d < h - y && d < w - x - VNC_TIGHT_DETECT_SUBROW_WIDTH;

             d++) {

            for (c = 0; c < 3; c++) {

                left[c] = buf[((y+d)*w+x+d)*4+off+c] & 0xFF;

            }

            for (dx = 1; dx <= VNC_TIGHT_DETECT_SUBROW_WIDTH; dx++) {

                for (c = 0; c < 3; c++) {

                    pix = buf[((y+d)*w+x+d+dx)*4+off+c] & 0xFF;

                    stats[abs(pix - left[c])]++;

                    left[c] = pix;

                }

                pixels++;

            }

        }

        if (w > h) {

            x += h;

            y = 0;

        } else {

            x = 0;

            y += w;

        }

    }

    /* 95% smooth or more ... */

    if (stats[0] * 33 / pixels >= 95) {

        return 0;

    }

    errors = 0;

    for (c = 1; c < 8; c++) {

        errors += stats[c] * (c * c);

        if (stats[c] == 0 || stats[c] > stats[c-1] * 2) {

            return 0;

        }

    }

    for (; c < 256; c++) {

        errors += stats[c] * (c * c);

    }

    errors /= (pixels * 3 - stats[0]);

    return errors;

}


static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,

                         uint64_t value)

{

    env->cp15.c0_cssel = value & 0xf;

}


bool net_tx_pkt_send(struct NetTxPkt *pkt, NetClientState *nc)

{

    assert(pkt);

    if (!pkt->has_virt_hdr &&

        pkt->virt_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {

        net_tx_pkt_do_sw_csum(pkt);

    }

    /*

     * Since underlying infrastructure does not support IP datagrams longer

     * than 64K we should drop such packets and don't even try to send

     */

    if (VIRTIO_NET_HDR_GSO_NONE != pkt->virt_hdr.gso_type) {

        if (pkt->payload_len >

            ETH_MAX_IP_DGRAM_LEN -

            pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_len) {

            return false;

        }

    }

    if (pkt->has_virt_hdr ||

        pkt->virt_hdr.gso_type == VIRTIO_NET_HDR_GSO_NONE) {

        qemu_sendv_packet(nc, pkt->vec,

            pkt->payload_frags + NET_TX_PKT_PL_START_FRAG);

        return true;

    }

    return net_tx_pkt_do_sw_fragmentation(pkt, nc);

}


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

                                 target_ulong address, int rw, int access_type)

{

    ppcemb_tlb_t *tlb;

    target_phys_addr_t raddr;

    int i, ret, zsel, zpr, pr;

    ret = -1;

    raddr = (target_phys_addr_t)-1ULL;

    pr = msr_pr;

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

        tlb = &env->tlb[i].tlbe;

        if (ppcemb_tlb_check(env, tlb, &raddr, address,

                             env->spr[SPR_40x_PID], 0, i) < 0)

            continue;

        zsel = (tlb->attr >> 4) & 0xF;

        zpr = (env->spr[SPR_40x_ZPR] >> (28 - (2 * zsel))) & 0x3;

        LOG_SWTLB("%s: TLB %d zsel %d zpr %d rw %d attr %08x\n",

                    __func__, i, zsel, zpr, rw, tlb->attr);

        /* Check execute enable bit */

        switch (zpr) {

        case 0x2:

            if (pr != 0)

                goto check_perms;

            /* No break here */

        case 0x3:

            /* All accesses granted */

            ctx->prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;

            ret = 0;

            break;

        case 0x0:

            if (pr != 0) {

                ctx->prot = 0;

                ret = -2;

                break;

            }

            /* No break here */

        case 0x1:

        check_perms:

            /* Check from TLB entry */

            /* XXX: there is a problem here or in the TLB fill code... */

            ctx->prot = tlb->prot;

            ctx->prot |= PAGE_EXEC;

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

            break;

        }

        if (ret >= 0) {

            ctx->raddr = raddr;

            LOG_SWTLB("%s: access granted " TARGET_FMT_lx " => " TARGET_FMT_plx

                      " %d %d\n", __func__, address, ctx->raddr, ctx->prot,

                      ret);

            return 0;

        }

    }

    LOG_SWTLB("%s: access refused " TARGET_FMT_lx " => " TARGET_FMT_plx

              " %d %d\n", __func__, address, raddr, ctx->prot, ret);

    return ret;

}


int bdrv_read(BlockDriverState *bs, int64_t sector_num,

              uint8_t *buf, int nb_sectors)

{

    BlockDriver *drv = bs->drv;

    if (!drv)

        return -ENOMEDIUM;

    if (sector_num == 0 && bs->boot_sector_enabled && nb_sectors > 0) {

            memcpy(buf, bs->boot_sector_data, 512);

        sector_num++;

        nb_sectors--;

        buf += 512;

        if (nb_sectors == 0)

            return 0;

    }

    if (drv->bdrv_pread) {

        int ret, len;

        len = nb_sectors * 512;

        ret = drv->bdrv_pread(bs, sector_num * 512, buf, len);

        if (ret < 0)

            return ret;

        else if (ret != len)

            return -EINVAL;

        else {

	    bs->rd_bytes += (unsigned) len;

	    bs->rd_ops ++;

            return 0;

	}

    } else {

        return drv->bdrv_read(bs, sector_num, buf, nb_sectors);

    }

}


int socket_connect(SocketAddress *addr, Error **errp,

                   NonBlockingConnectHandler *callback, void *opaque)

{

    int fd;

    switch (addr->type) {

    case SOCKET_ADDRESS_KIND_INET:

        fd = inet_connect_saddr(addr->u.inet, errp, callback, opaque);

        break;

    case SOCKET_ADDRESS_KIND_UNIX:

        fd = unix_connect_saddr(addr->u.q_unix, errp, callback, opaque);

        break;

    case SOCKET_ADDRESS_KIND_FD:

        fd = monitor_get_fd(cur_mon, addr->u.fd->str, errp);

        if (fd >= 0 && callback) {

            qemu_set_nonblock(fd);

            callback(fd, NULL, opaque);

        }

        break;

    default:

        abort();

    }

    return fd;

}


static int process_ea_header(AVFormatContext *s) {

    uint32_t blockid, size = 0;

    EaDemuxContext *ea = s->priv_data;

    ByteIOContext *pb = &s->pb;

    blockid = get_le32(pb);

    if (blockid == MVhd_TAG) {

        size = get_le32(pb);

        process_video_header_vp6(s);

        url_fskip(pb, size-32);

        blockid = get_le32(pb);

    }

    if (blockid != SCHl_TAG)

        return 0;

    size += get_le32(pb);

    blockid = get_le32(pb);

    if (blockid == GSTR_TAG) {

        url_fskip(pb, 4);

    } else if (blockid != PT00_TAG) {

        av_log (s, AV_LOG_ERROR, "unknown SCHl headerid\n");

        return 0;

    }

    process_audio_header_elements(s);

    /* skip to the start of the data */

    url_fseek(pb, size, SEEK_SET);

    return 1;

}


static void check_external_clock_sync(VideoState *is, double pts) {

    if (fabs(get_external_clock(is) - pts) > AV_NOSYNC_THRESHOLD) {

        update_external_clock_pts(is, pts);

    }

}


static int vhost_client_sync_dirty_bitmap(CPUPhysMemoryClient *client,

                                          target_phys_addr_t start_addr,

                                          target_phys_addr_t end_addr)

{

    struct vhost_dev *dev = container_of(client, struct vhost_dev, client);

    int i;

    if (!dev->log_enabled || !dev->started) {

        return 0;

    }

    for (i = 0; i < dev->mem->nregions; ++i) {

        struct vhost_memory_region *reg = dev->mem->regions + i;

        vhost_dev_sync_region(dev, start_addr, end_addr,

                              reg->guest_phys_addr,

                              range_get_last(reg->guest_phys_addr,

                                             reg->memory_size));

    }

    for (i = 0; i < dev->nvqs; ++i) {

        struct vhost_virtqueue *vq = dev->vqs + i;

        vhost_dev_sync_region(dev, start_addr, end_addr, vq->used_phys,

                              range_get_last(vq->used_phys, vq->used_size));

    }

    return 0;

}


static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)

{

    AVStream *st = c->fc->streams[c->fc->nb_streams-1];

    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;

    int entries, frames_per_sample;

    uint32_t format;

    print_atom("stsd", atom);

    get_byte(pb); /* version */

    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */

    entries = get_be32(pb);

    while(entries--) {

        enum CodecID id;

	int size = get_be32(pb); /* size */

        format = get_le32(pb); /* data format */

        get_be32(pb); /* reserved */

        get_be16(pb); /* reserved */

        get_be16(pb); /* index */

        /* for MPEG4: set codec type by looking for it */

        id = codec_get_id(mov_video_tags, format);

        if (id >= 0) {

            AVCodec *codec;

	    codec = avcodec_find_decoder(id);

            if (codec)

		st->codec.codec_type = codec->type;

        }

#ifdef DEBUG

        printf("size=%d 4CC= %c%c%c%c codec_type=%d\n",

               size,

               (format >> 0) & 0xff,

               (format >> 8) & 0xff,

               (format >> 16) & 0xff,

               (format >> 24) & 0xff,

               st->codec.codec_type);

#endif

	st->codec.codec_tag = format;

	if(st->codec.codec_type==CODEC_TYPE_VIDEO) {

	    MOV_atom_t a = { 0, 0, 0 };

            st->codec.codec_id = id;

            get_be16(pb); /* version */

            get_be16(pb); /* revision level */

            get_be32(pb); /* vendor */

            get_be32(pb); /* temporal quality */

            get_be32(pb); /* spacial quality */

            st->codec.width = get_be16(pb); /* width */

            st->codec.height = get_be16(pb); /* height */

#if 1

            if (st->codec.codec_id == CODEC_ID_MPEG4) {

                /* in some MPEG4 the width/height are not correct, so

                   we ignore this info */

                st->codec.width = 0;

                st->codec.height = 0;

            }

#endif

            get_be32(pb); /* horiz resolution */

            get_be32(pb); /* vert resolution */

            get_be32(pb); /* data size, always 0 */

            frames_per_sample = get_be16(pb); /* frames per samples */

#ifdef DEBUG

	    printf("frames/samples = %d\n", frames_per_sample);

#endif

	    get_buffer(pb, (uint8_t *)st->codec.codec_name, 32); /* codec name */

	    st->codec.bits_per_sample = get_be16(pb); /* depth */

            st->codec.color_table_id = get_be16(pb); /* colortable id */

            st->codec.frame_rate      = 25;

            st->codec.frame_rate_base = 1;

	    size -= (16+8*4+2+32+2*2);

#if 0

	    while (size >= 8) {

		MOV_atom_t a;

                int64_t start_pos;

		a.size = get_be32(pb);

		a.type = get_le32(pb);

		size -= 8;

#ifdef DEBUG

                printf("VIDEO: atom_type=%c%c%c%c atom.size=%Ld size_left=%d\n",

                       (a.type >> 0) & 0xff,

                       (a.type >> 8) & 0xff,

                       (a.type >> 16) & 0xff,

                       (a.type >> 24) & 0xff,

		       a.size, size);

#endif

                start_pos = url_ftell(pb);

		switch(a.type) {

                case MKTAG('e', 's', 'd', 's'):

                    {

                        int tag, len;

                        /* Well, broken but suffisant for some MP4 streams */

                        get_be32(pb); /* version + flags */

			len = mov_mp4_read_descr(pb, &tag);

                        if (tag == 0x03) {

                            /* MP4ESDescrTag */

                            get_be16(pb); /* ID */

                            get_byte(pb); /* priority */

			    len = mov_mp4_read_descr(pb, &tag);

                            if (tag != 0x04)

                                goto fail;

                            /* MP4DecConfigDescrTag */

                            get_byte(pb); /* objectTypeId */

                            get_be32(pb); /* streamType + buffer size */

			    get_be32(pb); /* max bit rate */

                            get_be32(pb); /* avg bit rate */

                            len = mp4_read_descr(pb, &tag);

                            if (tag != 0x05)

                                goto fail;

                            /* MP4DecSpecificDescrTag */

#ifdef DEBUG

                            printf("Specific MPEG4 header len=%d\n", len);

#endif

                            sc->header_data = av_mallocz(len);

                            if (sc->header_data) {

                                get_buffer(pb, sc->header_data, len);

				sc->header_len = len;

                            }

                        }

                        /* in any case, skip garbage */

                    }

                    break;

                default:

                    break;

                }

	    fail:

		printf("ATOMENEWSIZE %Ld   %d\n", atom.size, url_ftell(pb) - start_pos);

		if (atom.size > 8) {

		    url_fskip(pb, (atom.size - 8) -

			      ((url_ftell(pb) - start_pos)));

		    size -= atom.size - 8;

		}

	    }

            if (size > 0) {

                /* unknown extension */

                url_fskip(pb, size);

            }

#else

            a.size = size;

	    mov_read_default(c, pb, a);

#endif

	} else {

            get_be16(pb); /* version */

            get_be16(pb); /* revision level */

            get_be32(pb); /* vendor */

            st->codec.channels = get_be16(pb);		/* channel count */

	    st->codec.bits_per_sample = get_be16(pb);	/* sample size */

	    st->codec.codec_id = codec_get_id(mov_audio_tags, format);

            /* handle specific s8 codec */

            get_be16(pb); /* compression id = 0*/

            get_be16(pb); /* packet size = 0 */

            st->codec.sample_rate = ((get_be32(pb) >> 16));

	    //printf("CODECID %d  %d  %.4s\n", st->codec.codec_id, CODEC_ID_PCM_S16BE, (char*)&format);

	    switch (st->codec.codec_id) {

	    case CODEC_ID_PCM_S16BE:

		if (st->codec.bits_per_sample == 8)

		    st->codec.codec_id = CODEC_ID_PCM_S8;

                /* fall */

	    case CODEC_ID_PCM_U8:

		st->codec.bit_rate = st->codec.sample_rate * 8;

		break;

	    default:

                ;

	    }

	    get_be32(pb); /* samples per packet */

	    get_be32(pb); /* bytes per packet */

            get_be32(pb); /* bytes per frame */

            get_be32(pb); /* bytes per sample */

	    {

		MOV_atom_t a = { format, url_ftell(pb), size - (16 + 20 + 16 + 8) };

		mov_read_default(c, pb, a);

	    }

        }

    }

    return 0;

}


void scsi_req_free(SCSIRequest *req)

{

    scsi_req_dequeue(req);

    qemu_free(req);

}


void qpci_memwrite(QPCIDevice *dev, void *data, const void *buf, size_t len)

{

    uintptr_t addr = (uintptr_t)data;

    g_assert(addr >= QPCI_PIO_LIMIT);

    dev->bus->memwrite(dev->bus, addr, buf, len);

}


e1000e_init_msi(E1000EState *s)

{

    int res;

    res = msi_init(PCI_DEVICE(s),

                   0xD0,   /* MSI capability offset              */

                   1,      /* MAC MSI interrupts                 */

                   true,   /* 64-bit message addresses supported */

                   false); /* Per vector mask supported          */

    if (res > 0) {

        s->intr_state |= E1000E_USE_MSI;

    } else {

        trace_e1000e_msi_init_fail(res);

    }

}


int av_packet_add_side_data(AVPacket *pkt, enum AVPacketSideDataType type,

                            uint8_t *data, size_t size)

{

    int elems = pkt->side_data_elems;

    if ((unsigned)elems + 1 > INT_MAX / sizeof(*pkt->side_data))

        return AVERROR(ERANGE);

    pkt->side_data = av_realloc(pkt->side_data,

                                (elems + 1) * sizeof(*pkt->side_data));

    if (!pkt->side_data)

        return AVERROR(ENOMEM);

    pkt->side_data[elems].data = data;

    pkt->side_data[elems].size = size;

    pkt->side_data[elems].type = type;

    pkt->side_data_elems++;

    return 0;

}


static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,

                         int nb_sectors, QEMUIOVector *qiov)

{

    BDRVQcowState *s = bs->opaque;

    int index_in_cluster;

    int ret = 0, n;

    uint64_t cluster_offset;

    struct iovec hd_iov;

    QEMUIOVector hd_qiov;

    uint8_t *buf;

    void *orig_buf;

    if (qiov->niov > 1) {

        buf = orig_buf = qemu_try_blockalign(bs, qiov->size);

        if (buf == NULL) {

            return -ENOMEM;

        }

    } else {

        orig_buf = NULL;

        buf = (uint8_t *)qiov->iov->iov_base;

    }

    qemu_co_mutex_lock(&s->lock);

    while (nb_sectors != 0) {

        /* prepare next request */

        cluster_offset = get_cluster_offset(bs, sector_num << 9,

                                                 0, 0, 0, 0);

        index_in_cluster = sector_num & (s->cluster_sectors - 1);

        n = s->cluster_sectors - index_in_cluster;

        if (n > nb_sectors) {

            n = nb_sectors;

        }

        if (!cluster_offset) {

            if (bs->backing) {

                /* read from the base image */

                hd_iov.iov_base = (void *)buf;

                hd_iov.iov_len = n * 512;

                qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);

                qemu_co_mutex_unlock(&s->lock);

                ret = bdrv_co_readv(bs->backing, sector_num, n, &hd_qiov);

                qemu_co_mutex_lock(&s->lock);

                if (ret < 0) {

                    goto fail;

                }

            } else {

                /* Note: in this case, no need to wait */

                memset(buf, 0, 512 * n);

            }

        } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {

            /* add AIO support for compressed blocks ? */

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

                goto fail;

            }

            memcpy(buf,

                   s->cluster_cache + index_in_cluster * 512, 512 * n);

        } else {

            if ((cluster_offset & 511) != 0) {

                goto fail;

            }

            hd_iov.iov_base = (void *)buf;

            hd_iov.iov_len = n * 512;

            qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);

            qemu_co_mutex_unlock(&s->lock);

            ret = bdrv_co_readv(bs->file,

                                (cluster_offset >> 9) + index_in_cluster,

                                n, &hd_qiov);

            qemu_co_mutex_lock(&s->lock);

            if (ret < 0) {

                break;

            }

            if (bs->encrypted) {

                assert(s->crypto);

                if (qcrypto_block_decrypt(s->crypto, sector_num, buf,

                                          n * BDRV_SECTOR_SIZE, NULL) < 0) {

                    goto fail;

                }

            }

        }

        ret = 0;

        nb_sectors -= n;

        sector_num += n;

        buf += n * 512;

    }

done:

    qemu_co_mutex_unlock(&s->lock);

    if (qiov->niov > 1) {

        qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size);

        qemu_vfree(orig_buf);

    }

    return ret;

fail:

    ret = -EIO;

    goto done;

}


static inline I2CBus *aux_bridge_get_i2c_bus(AUXTOI2CState *bridge)

{

    return bridge->i2c_bus;

}


static int usb_host_auto_scan(void *opaque, int bus_num, int addr,

                     int class_id, int vendor_id, int product_id,

                     const char *product_name, int speed)

{

    struct USBAutoFilter *f;

    struct USBDevice *dev;

    /* Ignore hubs */

    if (class_id == 9)

        return 0;

    for (f = usb_auto_filter; f; f = f->next) {

	if (f->bus_num >= 0 && f->bus_num != bus_num)

            continue;

	if (f->addr >= 0 && f->addr != addr)

            continue;

	if (f->vendor_id >= 0 && f->vendor_id != vendor_id)

            continue;

	if (f->product_id >= 0 && f->product_id != product_id)

            continue;

        /* We got a match */

        /* Allredy attached ? */

        if (hostdev_find(bus_num, addr))

            return 0;

        dprintf("husb: auto open: bus_num %d addr %d\n", bus_num, addr);

	dev = usb_host_device_open_addr(bus_num, addr, product_name);

    }

    return 0;

}


static int get_siz(J2kDecoderContext *s)
{
    int i, ret;
    if (s->buf_end - s->buf < 36)
                        bytestream_get_be16(&s->buf); // Rsiz (skipped)
             s->width = bytestream_get_be32(&s->buf); // width
            s->height = bytestream_get_be32(&s->buf); // height
    s->image_offset_x = bytestream_get_be32(&s->buf); // X0Siz
    s->image_offset_y = bytestream_get_be32(&s->buf); // Y0Siz
        s->tile_width = bytestream_get_be32(&s->buf); // XTSiz
       s->tile_height = bytestream_get_be32(&s->buf); // YTSiz
     s->tile_offset_x = bytestream_get_be32(&s->buf); // XT0Siz
     s->tile_offset_y = bytestream_get_be32(&s->buf); // YT0Siz
       s->ncomponents = bytestream_get_be16(&s->buf); // CSiz
    if (s->buf_end - s->buf < 2 * s->ncomponents)
    for (i = 0; i < s->ncomponents; i++){ // Ssiz_i XRsiz_i, YRsiz_i
        uint8_t x = bytestream_get_byte(&s->buf);
        s->cbps[i] = (x & 0x7f) + 1;
        s->precision = FFMAX(s->cbps[i], s->precision);
        s->sgnd[i] = !!(x & 0x80);
        s->cdx[i] = bytestream_get_byte(&s->buf);
        s->cdy[i] = bytestream_get_byte(&s->buf);
    }
    s->numXtiles = ff_j2k_ceildiv(s->width - s->tile_offset_x, s->tile_width);
    s->numYtiles = ff_j2k_ceildiv(s->height - s->tile_offset_y, s->tile_height);
    s->tile = av_mallocz(s->numXtiles * s->numYtiles * sizeof(J2kTile));
    if (!s->tile)
        return AVERROR(ENOMEM);
    for (i = 0; i < s->numXtiles * s->numYtiles; i++){
        J2kTile *tile = s->tile + i;
        tile->comp = av_mallocz(s->ncomponents * sizeof(J2kComponent));
        if (!tile->comp)
            return AVERROR(ENOMEM);
    }
    s->avctx->width = s->width - s->image_offset_x;
    s->avctx->height = s->height - s->image_offset_y;
    switch(s->ncomponents){
        case 1: if (s->precision > 8) {
                    s->avctx->pix_fmt    = PIX_FMT_GRAY16;
                } else s->avctx->pix_fmt = PIX_FMT_GRAY8;
                break;
        case 3: if (s->precision > 8) {
                    s->avctx->pix_fmt    = PIX_FMT_RGB48;
                } else s->avctx->pix_fmt = PIX_FMT_RGB24;
                break;
        case 4: s->avctx->pix_fmt = PIX_FMT_BGRA; break;
    }
    if (s->picture.data[0])
        s->avctx->release_buffer(s->avctx, &s->picture);
    if ((ret = s->avctx->get_buffer(s->avctx, &s->picture)) < 0)
        return ret;
    s->picture.pict_type = FF_I_TYPE;
    s->picture.key_frame = 1;
    return 0;
}


static int decode_ref_pic_marking(H264Context *h, GetBitContext *gb){

    MpegEncContext * const s = &h->s;

    int i;

    if(h->nal_unit_type == NAL_IDR_SLICE){ //FIXME fields

        s->broken_link= get_bits1(gb) -1;

        h->mmco[0].long_arg= get_bits1(gb) - 1; // current_long_term_idx

        if(h->mmco[0].long_arg == -1)

        else{

            h->mmco[0].opcode= MMCO_LONG;

            h->mmco_index= 1;

        }

    }else{

        if(get_bits1(gb)){ // adaptive_ref_pic_marking_mode_flag

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

                MMCOOpcode opcode= get_ue_golomb(gb);

                h->mmco[i].opcode= opcode;

                if(opcode==MMCO_SHORT2UNUSED || opcode==MMCO_SHORT2LONG){

                    h->mmco[i].short_pic_num= (h->curr_pic_num - get_ue_golomb(gb) - 1) & (h->max_pic_num - 1);

/*                    if(h->mmco[i].short_pic_num >= h->short_ref_count || h->short_ref[ h->mmco[i].short_pic_num ] == NULL){

                        av_log(s->avctx, AV_LOG_ERROR, "illegal short ref in memory management control operation %d\n", mmco);

                        return -1;

                    }*/

                }

                if(opcode==MMCO_SHORT2LONG || opcode==MMCO_LONG2UNUSED || opcode==MMCO_LONG || opcode==MMCO_SET_MAX_LONG){

                    unsigned int long_arg= get_ue_golomb(gb);

                    if(long_arg >= 32 || (long_arg >= 16 && !(opcode == MMCO_LONG2UNUSED && FIELD_PICTURE))){

                        av_log(h->s.avctx, AV_LOG_ERROR, "illegal long ref in memory management control operation %d\n", opcode);

                        return -1;

                    }

                    h->mmco[i].long_arg= long_arg;

                }

                if(opcode > (unsigned)MMCO_LONG){

                    av_log(h->s.avctx, AV_LOG_ERROR, "illegal memory management control operation %d\n", opcode);

                    return -1;

                }

                if(opcode == MMCO_END)

                    break;

            }

            h->mmco_index= i;

        }else{

            assert(h->long_ref_count + h->short_ref_count <= h->sps.ref_frame_count);

            if(h->short_ref_count && h->long_ref_count + h->short_ref_count == h->sps.ref_frame_count &&

                    !(FIELD_PICTURE && !s->first_field && s->current_picture_ptr->reference)) {

                h->mmco[0].opcode= MMCO_SHORT2UNUSED;

                h->mmco[0].short_pic_num= h->short_ref[ h->short_ref_count - 1 ]->frame_num;

                h->mmco_index= 1;

                if (FIELD_PICTURE) {

                    h->mmco[0].short_pic_num *= 2;

                    h->mmco[1].opcode= MMCO_SHORT2UNUSED;

                    h->mmco[1].short_pic_num= h->mmco[0].short_pic_num + 1;

                    h->mmco_index= 2;

                }

            }else

        }

    }

    return 0;

}


static int decode_main_header(NUTContext *nut){

    AVFormatContext *s= nut->avf;

    ByteIOContext *bc = &s->pb;

    uint64_t tmp, end;

    unsigned int stream_count;

    int i, j, tmp_stream, tmp_mul, tmp_pts, tmp_size, count, tmp_res;

    end= get_packetheader(nut, bc, 1);

    end += url_ftell(bc) - 4;

    GET_V(tmp              , tmp >=2 && tmp <= 3)

    GET_V(stream_count     , tmp > 0 && tmp <=MAX_STREAMS)

    nut->max_distance = get_v(bc);

    if(nut->max_distance > 65536){

        av_log(s, AV_LOG_DEBUG, "max_distance %d\n", nut->max_distance);

        nut->max_distance= 65536;

    }

    GET_V(nut->time_base_count, tmp>0 && tmp<INT_MAX / sizeof(AVRational))

    nut->time_base= av_malloc(nut->time_base_count * sizeof(AVRational));

    for(i=0; i<nut->time_base_count; i++){

        GET_V(nut->time_base[i].num, tmp>0 && tmp<(1ULL<<31))

        GET_V(nut->time_base[i].den, tmp>0 && tmp<(1ULL<<31))

        if(ff_gcd(nut->time_base[i].num, nut->time_base[i].den) != 1){

            av_log(s, AV_LOG_ERROR, "time base invalid\n");

            return -1;

        }

    }

    tmp_pts=0;

    tmp_mul=1;

    tmp_stream=0;

    for(i=0; i<256;){

        int tmp_flags = get_v(bc);

        int tmp_fields= get_v(bc);

        if(tmp_fields>0) tmp_pts   = get_s(bc);

        if(tmp_fields>1) tmp_mul   = get_v(bc);

        if(tmp_fields>2) tmp_stream= get_v(bc);

        if(tmp_fields>3) tmp_size  = get_v(bc);

        else             tmp_size  = 0;

        if(tmp_fields>4) tmp_res   = get_v(bc);

        else             tmp_res   = 0;

        if(tmp_fields>5) count     = get_v(bc);

        else             count     = tmp_mul - tmp_size;

        while(tmp_fields-- > 6)

           get_v(bc);

        if(count == 0 || i+count > 256){

            av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);

            return -1;

        }

        if(tmp_stream >= stream_count){

            av_log(s, AV_LOG_ERROR, "illegal stream number\n");

            return -1;

        }

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

            if (i == 'N') {

                nut->frame_code[i].flags= FLAG_INVALID;

                j--;

                continue;

            }

            nut->frame_code[i].flags           = tmp_flags ;

            nut->frame_code[i].pts_delta       = tmp_pts   ;

            nut->frame_code[i].stream_id       = tmp_stream;

            nut->frame_code[i].size_mul        = tmp_mul   ;

            nut->frame_code[i].size_lsb        = tmp_size+j;

            nut->frame_code[i].reserved_count  = tmp_res   ;

        }

    }

    assert(nut->frame_code['N'].flags == FLAG_INVALID);

    if(skip_reserved(bc, end) || check_checksum(bc)){

        av_log(s, AV_LOG_ERROR, "Main header checksum mismatch\n");

        return -1;

    }

    nut->stream = av_mallocz(sizeof(StreamContext)*stream_count);

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

        av_new_stream(s, i);

    }

    return 0;

}


void add_migration_state_change_notifier(Notifier *notify)

{

    notifier_list_add(&migration_state_notifiers, notify);

}


static void enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)

{

    uint16_t seq   = AV_RB16(buf + 2);

    RTPPacket **cur = &s->queue, *packet;

    /* Find the correct place in the queue to insert the packet */

    while (*cur) {

        int16_t diff = seq - (*cur)->seq;

        if (diff < 0)

            break;

        cur = &(*cur)->next;

    }

    packet = av_mallocz(sizeof(*packet));

    if (!packet)

        return;

    packet->recvtime = av_gettime_relative();

    packet->seq      = seq;

    packet->len      = len;

    packet->buf      = buf;

    packet->next     = *cur;

    *cur = packet;

    s->queue_len++;

}


int ff_rv34_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            const uint8_t *buf, int buf_size)

{

    RV34DecContext *r = avctx->priv_data;

    MpegEncContext *s = &r->s;

    AVFrame *pict = data;

    SliceInfo si;

    int i;

    int slice_count;

    const uint8_t *slices_hdr = NULL;

    int last = 0;

    /* no supplementary picture */

    if (buf_size == 0) {

        /* special case for last picture */

        if (s->low_delay==0 && s->next_picture_ptr) {

            *pict= *(AVFrame*)s->next_picture_ptr;

            s->next_picture_ptr= NULL;

            *data_size = sizeof(AVFrame);

        }

        return 0;

    }

    if(!avctx->slice_count){

        slice_count = (*buf++) + 1;

        slices_hdr = buf + 4;

        buf += 8 * slice_count;

    }else

        slice_count = avctx->slice_count;

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

        int offset= get_slice_offset(avctx, slices_hdr, i);

        int size;

        if(i+1 == slice_count)

            size= buf_size - offset;

        else

            size= get_slice_offset(avctx, slices_hdr, i+1) - offset;

        if(offset > buf_size){

            av_log(avctx, AV_LOG_ERROR, "Slice offset is greater than frame size\n");

            break;

        }

        r->si.end = s->mb_width * s->mb_height;

        if(i+1 < slice_count){

            init_get_bits(&s->gb, buf+get_slice_offset(avctx, slices_hdr, i+1), (buf_size-get_slice_offset(avctx, slices_hdr, i+1))*8);

            if(r->parse_slice_header(r, &r->s.gb, &si) < 0){

                if(i+2 < slice_count)

                    size = get_slice_offset(avctx, slices_hdr, i+2) - offset;

                else

                    size = buf_size - offset;

            }else

                r->si.end = si.start;

        }

        if(!i && si.type == FF_B_TYPE && (!s->last_picture_ptr || !s->last_picture_ptr->data[0]))

            return -1;

        last = rv34_decode_slice(r, r->si.end, buf + offset, size);

        s->mb_num_left = r->s.mb_x + r->s.mb_y*r->s.mb_width - r->si.start;

        if(last)

            break;

    }

    if(last){

        if(r->loop_filter)

            r->loop_filter(r, s->mb_height - 1);

        ff_er_frame_end(s);

        MPV_frame_end(s);

        if (s->pict_type == FF_B_TYPE || s->low_delay) {

            *pict= *(AVFrame*)s->current_picture_ptr;

        } else if (s->last_picture_ptr != NULL) {

            *pict= *(AVFrame*)s->last_picture_ptr;

        }

        if(s->last_picture_ptr || s->low_delay){

            *data_size = sizeof(AVFrame);

            ff_print_debug_info(s, pict);

        }

        s->current_picture_ptr= NULL; //so we can detect if frame_end wasnt called (find some nicer solution...)

    }

    return buf_size;

}


static av_cold int mss2_decode_init(AVCodecContext *avctx)

{

    MSS2Context * const ctx = avctx->priv_data;

    MSS12Context *c = &ctx->c;

    int ret;

    c->avctx = avctx;

    avctx->coded_frame = &ctx->pic;

    if (ret = ff_mss12_decode_init(c, 1, &ctx->sc[0], &ctx->sc[1]))

        return ret;

    c->pal_stride   = c->mask_stride;

    c->pal_pic      = av_malloc(c->pal_stride * avctx->height);

    c->last_pal_pic = av_malloc(c->pal_stride * avctx->height);

    if (!c->pal_pic || !c->last_pal_pic) {

        mss2_decode_end(avctx);

        return AVERROR(ENOMEM);

    }

    if (ret = wmv9_init(avctx)) {

        mss2_decode_end(avctx);

        return ret;

    }

    ff_mss2dsp_init(&ctx->dsp);

    avctx->pix_fmt = c->free_colours == 127 ? AV_PIX_FMT_RGB555

                                            : AV_PIX_FMT_RGB24;

    return 0;

}


static void build_file_streams(void)

{

    FFStream *stream, *stream_next;

    AVFormatContext *infile;

    int i;

    /* gather all streams */

    for(stream = first_stream; stream != NULL; stream = stream_next) {

        stream_next = stream->next;

        if (stream->stream_type == STREAM_TYPE_LIVE &&

            !stream->feed) {

            /* the stream comes from a file */

            /* try to open the file */

            /* open stream */

            stream->ap_in = av_mallocz(sizeof(AVFormatParameters));

            if (!strcmp(stream->fmt->name, "rtp")) {

                /* specific case : if transport stream output to RTP,

                   we use a raw transport stream reader */

                stream->ap_in->mpeg2ts_raw = 1;

                stream->ap_in->mpeg2ts_compute_pcr = 1;

            }

            if (av_open_input_file(&infile, stream->feed_filename,

                                   stream->ifmt, 0, stream->ap_in) < 0) {

                http_log("%s not found", stream->feed_filename);

                /* remove stream (no need to spend more time on it) */

            fail:

                remove_stream(stream);

            } else {

                /* find all the AVStreams inside and reference them in

                   'stream' */

                if (av_find_stream_info(infile) < 0) {

                    http_log("Could not find codec parameters from '%s'",

                             stream->feed_filename);

                    av_close_input_file(infile);

                    goto fail;

                }

                extract_mpeg4_header(infile);

                for(i=0;i<infile->nb_streams;i++)

                    add_av_stream1(stream, infile->streams[i]->codec);

                av_close_input_file(infile);

            }

        }

    }

}


void OPPROTO op_addco (void)

{

    do_addco();

    RETURN();

}


static inline void vring_used_flags_set_bit(VirtQueue *vq, int mask)

{

    VRingMemoryRegionCaches *caches = atomic_rcu_read(&vq->vring.caches);

    VirtIODevice *vdev = vq->vdev;

    hwaddr pa = offsetof(VRingUsed, flags);

    uint16_t flags = virtio_lduw_phys_cached(vq->vdev, &caches->used, pa);

    virtio_stw_phys_cached(vdev, &caches->used, pa, flags | mask);

    address_space_cache_invalidate(&caches->used, pa, sizeof(flags));

}


static int iscsi_truncate(BlockDriverState *bs, int64_t offset)

{

    IscsiLun *iscsilun = bs->opaque;

    Error *local_err = NULL;

    if (iscsilun->type != TYPE_DISK) {

        return -ENOTSUP;

    }

    iscsi_readcapacity_sync(iscsilun, &local_err);

    if (local_err != NULL) {

        error_free(local_err);

        return -EIO;

    }

    if (offset > iscsi_getlength(bs)) {

        return -EINVAL;

    }

    if (iscsilun->allocationmap != NULL) {

        g_free(iscsilun->allocationmap);

        iscsilun->allocationmap =

            bitmap_new(DIV_ROUND_UP(bs->total_sectors,

                                    iscsilun->cluster_sectors));

    }

    return 0;

}


static void xan_unpack(unsigned char *dest, unsigned char *src)

{

    unsigned char opcode;

    int size;

    int offset;

    int byte1, byte2, byte3;

    for (;;) {

        opcode = *src++;

        if ( (opcode & 0x80) == 0 ) {

            offset = *src++;

            size = opcode & 3;

            bytecopy(dest, src, size);  dest += size;  src += size;

            size = ((opcode & 0x1c) >> 2) + 3;

            bytecopy (dest, dest - (((opcode & 0x60) << 3) + offset + 1), size);

            dest += size;

        } else if ( (opcode & 0x40) == 0 ) {

            byte1 = *src++;

            byte2 = *src++;

            size = byte1 >> 6;

            bytecopy (dest, src, size);  dest += size;  src += size;

            size = (opcode & 0x3f) + 4;

            bytecopy (dest, dest - (((byte1 & 0x3f) << 8) + byte2 + 1), size);

            dest += size;

        } else if ( (opcode & 0x20) == 0 ) {

            byte1 = *src++;

            byte2 = *src++;

            byte3 = *src++;

            size = opcode & 3;

            bytecopy (dest, src, size);  dest += size;  src += size;

            size = byte3 + 5 + ((opcode & 0xc) << 6);

            bytecopy (dest,

                dest - ((((opcode & 0x10) >> 4) << 0x10) + 1 + (byte1 << 8) + byte2),

                size);

            dest += size;

        } else {

            size = ((opcode & 0x1f) << 2) + 4;

            if (size > 0x70)

                break;

            bytecopy (dest, src, size);  dest += size;  src += size;

        }

    }

    size = opcode & 3;

    bytecopy(dest, src, size);  dest += size;  src += size;

}


START_TEST(qdict_del_test)

{

    const char *key = "key test";

    qdict_put(tests_dict, key, qstring_from_str("foo"));

    fail_unless(qdict_size(tests_dict) == 1);

    qdict_del(tests_dict, key);

    fail_unless(qdict_size(tests_dict) == 0);

    fail_unless(qdict_haskey(tests_dict, key) == 0);

}


static void spawn_thread(ThreadPool *pool)

{

    pool->cur_threads++;

    pool->new_threads++;

    /* If there are threads being created, they will spawn new workers, so

     * we don't spend time creating many threads in a loop holding a mutex or

     * starving the current vcpu.

     *

     * If there are no idle threads, ask the main thread to create one, so we

     * inherit the correct affinity instead of the vcpu affinity.

     */

    if (!pool->pending_threads) {

        qemu_bh_schedule(pool->new_thread_bh);

    }

}


static void vnc_display_close(VncDisplay *vs)

{

    if (!vs)

        return;

    g_free(vs->display);

    vs->display = NULL;

    if (vs->lsock != -1) {

        qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);

        close(vs->lsock);

        vs->lsock = -1;

    }

#ifdef CONFIG_VNC_WS

    g_free(vs->ws_display);

    vs->ws_display = NULL;

    if (vs->lwebsock != -1) {

        qemu_set_fd_handler2(vs->lwebsock, NULL, NULL, NULL, NULL);

        close(vs->lwebsock);

        vs->lwebsock = -1;

    }

#endif /* CONFIG_VNC_WS */

    vs->auth = VNC_AUTH_INVALID;

#ifdef CONFIG_VNC_TLS

    vs->subauth = VNC_AUTH_INVALID;

    vs->tls.x509verify = 0;

#endif

}


void kvm_s390_crw_mchk(S390CPU *cpu)

{

    kvm_s390_interrupt_internal(cpu, KVM_S390_MCHK, 1 << 28,

                                0x00400f1d40330000, 1);

}


static int pxa2xx_i2c_slave_init(I2CSlave *i2c)

{

    /* Nothing to do.  */

    return 0;

}


static void openpic_cpu_write_internal(void *opaque, hwaddr addr,

                                       uint32_t val, int idx)

{

    openpic_t *opp = opaque;

    IRQ_src_t *src;

    IRQ_dst_t *dst;

    int s_IRQ, n_IRQ;

    DPRINTF("%s: cpu %d addr " TARGET_FMT_plx " <= %08x\n", __func__, idx,

            addr, val);

    if (addr & 0xF)

        return;

    dst = &opp->dst[idx];

    addr &= 0xFF0;

    switch (addr) {

    case 0x40: /* IPIDR */

    case 0x50:

    case 0x60:

    case 0x70:

        idx = (addr - 0x40) >> 4;

        /* we use IDE as mask which CPUs to deliver the IPI to still. */

        write_IRQreg_ide(opp, opp->irq_ipi0 + idx,

                         opp->src[opp->irq_ipi0 + idx].ide | val);

        openpic_set_irq(opp, opp->irq_ipi0 + idx, 1);

        openpic_set_irq(opp, opp->irq_ipi0 + idx, 0);

        break;

    case 0x80: /* PCTP */

        dst->pctp = val & 0x0000000F;

        break;

    case 0x90: /* WHOAMI */

        /* Read-only register */

        break;

    case 0xA0: /* PIAC */

        /* Read-only register */

        break;

    case 0xB0: /* PEOI */

        DPRINTF("PEOI\n");

        s_IRQ = IRQ_get_next(opp, &dst->servicing);

        IRQ_resetbit(&dst->servicing, s_IRQ);

        dst->servicing.next = -1;

        /* Set up next servicing IRQ */

        s_IRQ = IRQ_get_next(opp, &dst->servicing);

        /* Check queued interrupts. */

        n_IRQ = IRQ_get_next(opp, &dst->raised);

        src = &opp->src[n_IRQ];

        if (n_IRQ != -1 &&

            (s_IRQ == -1 ||

             IPVP_PRIORITY(src->ipvp) > dst->servicing.priority)) {

            DPRINTF("Raise OpenPIC INT output cpu %d irq %d\n",

                    idx, n_IRQ);

            opp->irq_raise(opp, idx, src);

        }

        break;

    default:

        break;

    }

}


static inline int dmg_read_chunk(BDRVDMGState *s,int sector_num)

{

    if(!is_sector_in_chunk(s,s->current_chunk,sector_num)) {

	int ret;

	uint32_t chunk = search_chunk(s,sector_num);

	if(chunk>=s->n_chunks)

	    return -1;

	s->current_chunk = s->n_chunks;

	switch(s->types[chunk]) {

	case 0x80000005: { /* zlib compressed */

	    int i;

	    /* we need to buffer, because only the chunk as whole can be

	     * inflated. */

	    i=0;

	    do {

		ret = pread(s->fd, s->compressed_chunk+i, s->lengths[chunk]-i,

                            s->offsets[chunk] + i);

		if(ret<0 && errno==EINTR)

		    ret=0;

		i+=ret;

	    } while(ret>=0 && ret+i<s->lengths[chunk]);

	    if (ret != s->lengths[chunk])

		return -1;

	    s->zstream.next_in = s->compressed_chunk;

	    s->zstream.avail_in = s->lengths[chunk];

	    s->zstream.next_out = s->uncompressed_chunk;

	    s->zstream.avail_out = 512*s->sectorcounts[chunk];

	    ret = inflateReset(&s->zstream);

	    if(ret != Z_OK)

		return -1;

	    ret = inflate(&s->zstream, Z_FINISH);

	    if(ret != Z_STREAM_END || s->zstream.total_out != 512*s->sectorcounts[chunk])

		return -1;

	    break; }

	case 1: /* copy */

	    ret = pread(s->fd, s->uncompressed_chunk, s->lengths[chunk],

                        s->offsets[chunk]);

	    if (ret != s->lengths[chunk])

		return -1;

	    break;

	case 2: /* zero */

	    memset(s->uncompressed_chunk, 0, 512*s->sectorcounts[chunk]);

	    break;

	}

	s->current_chunk = chunk;

    }

    return 0;

}


static QObject *pci_get_dev_dict(PCIDevice *dev, PCIBus *bus, int bus_num)

{

    int class;

    QObject *obj;

    obj = qobject_from_jsonf("{ 'bus': %d, 'slot': %d, 'function': %d,"                                       "'class_info': %p, 'id': %p, 'regions': %p,"

                              " 'qdev_id': %s }",

                              bus_num,

                              PCI_SLOT(dev->devfn), PCI_FUNC(dev->devfn),

                              pci_get_dev_class(dev), pci_get_dev_id(dev),

                              pci_get_regions_list(dev),

                              dev->qdev.id ? dev->qdev.id : "");

    if (dev->config[PCI_INTERRUPT_PIN] != 0) {

        QDict *qdict = qobject_to_qdict(obj);

        qdict_put(qdict, "irq", qint_from_int(dev->config[PCI_INTERRUPT_LINE]));

    }

    class = pci_get_word(dev->config + PCI_CLASS_DEVICE);

    if (class == 0x0604) {

        QDict *qdict;

        QObject *pci_bridge;

        pci_bridge = qobject_from_jsonf("{ 'bus': "

        "{ 'number': %d, 'secondary': %d, 'subordinate': %d }, "

        "'io_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "}, "

        "'memory_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "}, "

        "'prefetchable_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "} }",

        dev->config[0x19], dev->config[PCI_SECONDARY_BUS],

        dev->config[PCI_SUBORDINATE_BUS],

        pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_IO),

        pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_IO),

        pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY),

        pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY),

        pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY |

                               PCI_BASE_ADDRESS_MEM_PREFETCH),

        pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY |

                                PCI_BASE_ADDRESS_MEM_PREFETCH));

        if (dev->config[0x19] != 0) {

            qdict = qobject_to_qdict(pci_bridge);

            qdict_put_obj(qdict, "devices",

                          pci_get_devices_list(bus, dev->config[0x19]));

        }

        qdict = qobject_to_qdict(obj);

        qdict_put_obj(qdict, "pci_bridge", pci_bridge);

    }

    return obj;

}


static void vga_draw_graphic(VGAState *s, int full_update)

{

    int y1, y, update, page_min, page_max, linesize, y_start, double_scan, mask, depth;

    int width, height, shift_control, line_offset, page0, page1, bwidth, bits;

    int disp_width, multi_scan, multi_run;

    uint8_t *d;

    uint32_t v, addr1, addr;

    vga_draw_line_func *vga_draw_line;

    full_update |= update_basic_params(s);

    if (!full_update)

        vga_sync_dirty_bitmap(s);

    s->get_resolution(s, &width, &height);

    disp_width = width;

    shift_control = (s->gr[0x05] >> 5) & 3;

    double_scan = (s->cr[0x09] >> 7);

    if (shift_control != 1) {

        multi_scan = (((s->cr[0x09] & 0x1f) + 1) << double_scan) - 1;

    } else {

        /* in CGA modes, multi_scan is ignored */

        /* XXX: is it correct ? */

        multi_scan = double_scan;

    }

    multi_run = multi_scan;

    if (shift_control != s->shift_control ||

        double_scan != s->double_scan) {

        full_update = 1;

        s->shift_control = shift_control;

        s->double_scan = double_scan;

    }

    depth = s->get_bpp(s);

    if (s->line_offset != s->last_line_offset ||

        disp_width != s->last_width ||

        height != s->last_height ||

        s->last_depth != depth) {

#if defined(WORDS_BIGENDIAN) == defined(TARGET_WORDS_BIGENDIAN)

        if (depth == 16 || depth == 32) {

#else

        if (depth == 32) {

#endif

            if (is_graphic_console()) {

                qemu_free_displaysurface(s->ds);

                s->ds->surface = qemu_create_displaysurface_from(disp_width, height, depth,

                                                               s->line_offset,

                                                               s->vram_ptr + (s->start_addr * 4));

#if defined(WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)

                s->ds->surface->pf = qemu_different_endianness_pixelformat(depth);

#endif

                dpy_resize(s->ds);

            } else {

                qemu_console_resize(s->ds, disp_width, height);

            }

        } else {

            qemu_console_resize(s->ds, disp_width, height);

        }

        s->last_scr_width = disp_width;

        s->last_scr_height = height;

        s->last_width = disp_width;

        s->last_height = height;

        s->last_line_offset = s->line_offset;

        s->last_depth = depth;

        full_update = 1;

    } else if (is_graphic_console() && is_buffer_shared(s->ds->surface) &&

               (full_update || s->ds->surface->data != s->vram_ptr + (s->start_addr * 4))) {

        s->ds->surface->data = s->vram_ptr + (s->start_addr * 4);

        dpy_setdata(s->ds);

    }

    s->rgb_to_pixel =

        rgb_to_pixel_dup_table[get_depth_index(s->ds)];

    if (shift_control == 0) {

        full_update |= update_palette16(s);

        if (s->sr[0x01] & 8) {

            v = VGA_DRAW_LINE4D2;

            disp_width <<= 1;

        } else {

            v = VGA_DRAW_LINE4;

        }

        bits = 4;

    } else if (shift_control == 1) {

        full_update |= update_palette16(s);

        if (s->sr[0x01] & 8) {

            v = VGA_DRAW_LINE2D2;

            disp_width <<= 1;

        } else {

            v = VGA_DRAW_LINE2;

        }

        bits = 4;

    } else {

        switch(s->get_bpp(s)) {

        default:

        case 0:

            full_update |= update_palette256(s);

            v = VGA_DRAW_LINE8D2;

            bits = 4;

            break;

        case 8:

            full_update |= update_palette256(s);

            v = VGA_DRAW_LINE8;

            bits = 8;

            break;

        case 15:

            v = VGA_DRAW_LINE15;

            bits = 16;

            break;

        case 16:

            v = VGA_DRAW_LINE16;

            bits = 16;

            break;

        case 24:

            v = VGA_DRAW_LINE24;

            bits = 24;

            break;

        case 32:

            v = VGA_DRAW_LINE32;

            bits = 32;

            break;

        }

    }

    vga_draw_line = vga_draw_line_table[v * NB_DEPTHS + get_depth_index(s->ds)];

    if (!is_buffer_shared(s->ds->surface) && s->cursor_invalidate)

        s->cursor_invalidate(s);

    line_offset = s->line_offset;

#if 0

    printf("w=%d h=%d v=%d line_offset=%d cr[0x09]=0x%02x cr[0x17]=0x%02x linecmp=%d sr[0x01]=0x%02x\n",

           width, height, v, line_offset, s->cr[9], s->cr[0x17], s->line_compare, s->sr[0x01]);

#endif

    addr1 = (s->start_addr * 4);

    bwidth = (width * bits + 7) / 8;

    y_start = -1;

    page_min = 0x7fffffff;

    page_max = -1;

    d = ds_get_data(s->ds);

    linesize = ds_get_linesize(s->ds);

    y1 = 0;

    for(y = 0; y < height; y++) {

        addr = addr1;

        if (!(s->cr[0x17] & 1)) {

            int shift;

            /* CGA compatibility handling */

            shift = 14 + ((s->cr[0x17] >> 6) & 1);

            addr = (addr & ~(1 << shift)) | ((y1 & 1) << shift);

        }

        if (!(s->cr[0x17] & 2)) {

            addr = (addr & ~0x8000) | ((y1 & 2) << 14);

        }

        page0 = s->vram_offset + (addr & TARGET_PAGE_MASK);

        page1 = s->vram_offset + ((addr + bwidth - 1) & TARGET_PAGE_MASK);

        update = full_update |

            cpu_physical_memory_get_dirty(page0, VGA_DIRTY_FLAG) |

            cpu_physical_memory_get_dirty(page1, VGA_DIRTY_FLAG);

        if ((page1 - page0) > TARGET_PAGE_SIZE) {

            /* if wide line, can use another page */

            update |= cpu_physical_memory_get_dirty(page0 + TARGET_PAGE_SIZE,

                                                    VGA_DIRTY_FLAG);

        }

        /* explicit invalidation for the hardware cursor */

        update |= (s->invalidated_y_table[y >> 5] >> (y & 0x1f)) & 1;

        if (update) {

            if (y_start < 0)

                y_start = y;

            if (page0 < page_min)

                page_min = page0;

            if (page1 > page_max)

                page_max = page1;

            if (!(is_buffer_shared(s->ds->surface))) {

                vga_draw_line(s, d, s->vram_ptr + addr, width);

                if (s->cursor_draw_line)

                    s->cursor_draw_line(s, d, y);

            }

        } else {

            if (y_start >= 0) {

                /* flush to display */

                dpy_update(s->ds, 0, y_start,

                           disp_width, y - y_start);

                y_start = -1;

            }

        }

        if (!multi_run) {

            mask = (s->cr[0x17] & 3) ^ 3;

            if ((y1 & mask) == mask)

                addr1 += line_offset;

            y1++;

            multi_run = multi_scan;

        } else {

            multi_run--;

        }

        /* line compare acts on the displayed lines */

        if (y == s->line_compare)

            addr1 = 0;

        d += linesize;

    }

    if (y_start >= 0) {

        /* flush to display */

        dpy_update(s->ds, 0, y_start,

                   disp_width, y - y_start);

    }

    /* reset modified pages */

    if (page_max != -1) {

        cpu_physical_memory_reset_dirty(page_min, page_max + TARGET_PAGE_SIZE,

                                        VGA_DIRTY_FLAG);

    }

    memset(s->invalidated_y_table, 0, ((height + 31) >> 5) * 4);

}


static void qtest_process_command(CharDriverState *chr, gchar **words)

{

    const gchar *command;

    g_assert(words);

    command = words[0];

    if (qtest_log_fp) {

        qemu_timeval tv;

        int i;

        qtest_get_time(&tv);

        fprintf(qtest_log_fp, "[R +" FMT_timeval "]",

                (long) tv.tv_sec, (long) tv.tv_usec);

        for (i = 0; words[i]; i++) {

            fprintf(qtest_log_fp, " %s", words[i]);

        }

        fprintf(qtest_log_fp, "\n");

    }

    g_assert(command);

    if (strcmp(words[0], "irq_intercept_out") == 0

        || strcmp(words[0], "irq_intercept_in") == 0) {

        DeviceState *dev;

        NamedGPIOList *ngl;

        g_assert(words[1]);

        dev = DEVICE(object_resolve_path(words[1], NULL));

        if (!dev) {

            qtest_send_prefix(chr);

            qtest_send(chr, "FAIL Unknown device\n");

	    return;

        }

        if (irq_intercept_dev) {

            qtest_send_prefix(chr);

            if (irq_intercept_dev != dev) {

                qtest_send(chr, "FAIL IRQ intercept already enabled\n");

            } else {

                qtest_send(chr, "OK\n");

            }

	    return;

        }

        QLIST_FOREACH(ngl, &dev->gpios, node) {

            /* We don't support intercept of named GPIOs yet */

            if (ngl->name) {

                continue;

            }

            if (words[0][14] == 'o') {

                int i;

                for (i = 0; i < ngl->num_out; ++i) {

                    qemu_irq *disconnected = g_new0(qemu_irq, 1);

                    qemu_irq icpt = qemu_allocate_irq(qtest_irq_handler,

                                                      disconnected, i);

                    *disconnected = qdev_intercept_gpio_out(dev, icpt,

                                                            ngl->name, i);

                }

            } else {

                qemu_irq_intercept_in(ngl->in, qtest_irq_handler,

                                      ngl->num_in);

            }

        }

        irq_intercept_dev = dev;

        qtest_send_prefix(chr);

        qtest_send(chr, "OK\n");

    } else if (strcmp(words[0], "outb") == 0 ||

               strcmp(words[0], "outw") == 0 ||

               strcmp(words[0], "outl") == 0) {

        uint16_t addr;

        uint32_t value;

        g_assert(words[1] && words[2]);

        addr = strtoul(words[1], NULL, 0);

        value = strtoul(words[2], NULL, 0);

        if (words[0][3] == 'b') {

            cpu_outb(addr, value);

        } else if (words[0][3] == 'w') {

            cpu_outw(addr, value);

        } else if (words[0][3] == 'l') {

            cpu_outl(addr, value);

        }

        qtest_send_prefix(chr);

        qtest_send(chr, "OK\n");

    } else if (strcmp(words[0], "inb") == 0 ||

        strcmp(words[0], "inw") == 0 ||

        strcmp(words[0], "inl") == 0) {

        uint16_t addr;

        uint32_t value = -1U;

        g_assert(words[1]);

        addr = strtoul(words[1], NULL, 0);

        if (words[0][2] == 'b') {

            value = cpu_inb(addr);

        } else if (words[0][2] == 'w') {

            value = cpu_inw(addr);

        } else if (words[0][2] == 'l') {

            value = cpu_inl(addr);

        }

        qtest_send_prefix(chr);

        qtest_sendf(chr, "OK 0x%04x\n", value);

    } else if (strcmp(words[0], "writeb") == 0 ||

               strcmp(words[0], "writew") == 0 ||

               strcmp(words[0], "writel") == 0 ||

               strcmp(words[0], "writeq") == 0) {

        uint64_t addr;

        uint64_t value;

        g_assert(words[1] && words[2]);

        addr = strtoull(words[1], NULL, 0);

        value = strtoull(words[2], NULL, 0);

        if (words[0][5] == 'b') {

            uint8_t data = value;

            cpu_physical_memory_write(addr, &data, 1);

        } else if (words[0][5] == 'w') {

            uint16_t data = value;

            tswap16s(&data);

            cpu_physical_memory_write(addr, &data, 2);

        } else if (words[0][5] == 'l') {

            uint32_t data = value;

            tswap32s(&data);

            cpu_physical_memory_write(addr, &data, 4);

        } else if (words[0][5] == 'q') {

            uint64_t data = value;

            tswap64s(&data);

            cpu_physical_memory_write(addr, &data, 8);

        }

        qtest_send_prefix(chr);

        qtest_send(chr, "OK\n");

    } else if (strcmp(words[0], "readb") == 0 ||

               strcmp(words[0], "readw") == 0 ||

               strcmp(words[0], "readl") == 0 ||

               strcmp(words[0], "readq") == 0) {

        uint64_t addr;

        uint64_t value = UINT64_C(-1);

        g_assert(words[1]);

        addr = strtoull(words[1], NULL, 0);

        if (words[0][4] == 'b') {

            uint8_t data;

            cpu_physical_memory_read(addr, &data, 1);

            value = data;

        } else if (words[0][4] == 'w') {

            uint16_t data;

            cpu_physical_memory_read(addr, &data, 2);

            value = tswap16(data);

        } else if (words[0][4] == 'l') {

            uint32_t data;

            cpu_physical_memory_read(addr, &data, 4);

            value = tswap32(data);

        } else if (words[0][4] == 'q') {

            cpu_physical_memory_read(addr, &value, 8);

            tswap64s(&value);

        }

        qtest_send_prefix(chr);

        qtest_sendf(chr, "OK 0x%016" PRIx64 "\n", value);

    } else if (strcmp(words[0], "read") == 0) {

        uint64_t addr, len, i;

        uint8_t *data;

        char *enc;

        g_assert(words[1] && words[2]);

        addr = strtoull(words[1], NULL, 0);

        len = strtoull(words[2], NULL, 0);

        data = g_malloc(len);

        cpu_physical_memory_read(addr, data, len);

        enc = g_malloc(2 * len + 1);

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

            sprintf(&enc[i * 2], "%02x", data[i]);

        }

        qtest_send_prefix(chr);

        qtest_sendf(chr, "OK 0x%s\n", enc);

        g_free(data);

        g_free(enc);

    } else if (strcmp(words[0], "b64read") == 0) {

        uint64_t addr, len;

        uint8_t *data;

        gchar *b64_data;

        g_assert(words[1] && words[2]);

        addr = strtoull(words[1], NULL, 0);

        len = strtoull(words[2], NULL, 0);

        data = g_malloc(len);

        cpu_physical_memory_read(addr, data, len);

        b64_data = g_base64_encode(data, len);

        qtest_send_prefix(chr);

        qtest_sendf(chr, "OK %s\n", b64_data);

        g_free(data);

        g_free(b64_data);

    } else if (strcmp(words[0], "write") == 0) {

        uint64_t addr, len, i;

        uint8_t *data;

        size_t data_len;

        g_assert(words[1] && words[2] && words[3]);

        addr = strtoull(words[1], NULL, 0);

        len = strtoull(words[2], NULL, 0);

        data_len = strlen(words[3]);

        if (data_len < 3) {

            qtest_send(chr, "ERR invalid argument size\n");

            return;

        }

        data = g_malloc(len);

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

            if ((i * 2 + 4) <= data_len) {

                data[i] = hex2nib(words[3][i * 2 + 2]) << 4;

                data[i] |= hex2nib(words[3][i * 2 + 3]);

            } else {

                data[i] = 0;

            }

        }

        cpu_physical_memory_write(addr, data, len);

        g_free(data);

        qtest_send_prefix(chr);

        qtest_send(chr, "OK\n");

    } else if (strcmp(words[0], "memset") == 0) {

        uint64_t addr, len;

        uint8_t *data;

        uint8_t pattern;

        g_assert(words[1] && words[2] && words[3]);

        addr = strtoull(words[1], NULL, 0);

        len = strtoull(words[2], NULL, 0);

        pattern = strtoull(words[3], NULL, 0);

        if (len) {

            data = g_malloc(len);

            memset(data, pattern, len);

            cpu_physical_memory_write(addr, data, len);

            g_free(data);

        }

        qtest_send_prefix(chr);

        qtest_send(chr, "OK\n");

    }  else if (strcmp(words[0], "b64write") == 0) {

        uint64_t addr, len;

        uint8_t *data;

        size_t data_len;

        gsize out_len;

        g_assert(words[1] && words[2] && words[3]);

        addr = strtoull(words[1], NULL, 0);

        len = strtoull(words[2], NULL, 0);

        data_len = strlen(words[3]);

        if (data_len < 3) {

            qtest_send(chr, "ERR invalid argument size\n");

            return;

        }

        data = g_base64_decode_inplace(words[3], &out_len);

        if (out_len != len) {

            qtest_log_send("b64write: data length mismatch (told %"PRIu64", "

                           "found %zu)\n",

                           len, out_len);

            out_len = MIN(out_len, len);

        }

        cpu_physical_memory_write(addr, data, out_len);

        qtest_send_prefix(chr);

        qtest_send(chr, "OK\n");

    } else if (qtest_enabled() && strcmp(words[0], "clock_step") == 0) {

        int64_t ns;

        if (words[1]) {

            ns = strtoll(words[1], NULL, 0);

        } else {

            ns = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);

        }

        qtest_clock_warp(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + ns);

        qtest_send_prefix(chr);

        qtest_sendf(chr, "OK %"PRIi64"\n",

                    (int64_t)qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL));

    } else if (qtest_enabled() && strcmp(words[0], "clock_set") == 0) {

        int64_t ns;

        g_assert(words[1]);

        ns = strtoll(words[1], NULL, 0);

        qtest_clock_warp(ns);

        qtest_send_prefix(chr);

        qtest_sendf(chr, "OK %"PRIi64"\n",

                    (int64_t)qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL));

    } else {

        qtest_send_prefix(chr);

        qtest_sendf(chr, "FAIL Unknown command '%s'\n", words[0]);

    }

}


static RemoveResult remove_hpte(PowerPCCPU *cpu, target_ulong ptex,

                                target_ulong avpn,

                                target_ulong flags,

                                target_ulong *vp, target_ulong *rp)

{

    CPUPPCState *env = &cpu->env;

    uint64_t token;

    target_ulong v, r;

    if (!valid_pte_index(env, ptex)) {

        return REMOVE_PARM;

    }

    token = ppc_hash64_start_access(cpu, ptex);

    v = ppc_hash64_load_hpte0(cpu, token, 0);

    r = ppc_hash64_load_hpte1(cpu, token, 0);

    ppc_hash64_stop_access(token);

    if ((v & HPTE64_V_VALID) == 0 ||

        ((flags & H_AVPN) && (v & ~0x7fULL) != avpn) ||

        ((flags & H_ANDCOND) && (v & avpn) != 0)) {

        return REMOVE_NOT_FOUND;

    }

    *vp = v;

    *rp = r;

    ppc_hash64_store_hpte(cpu, ptex, HPTE64_V_HPTE_DIRTY, 0);

    ppc_hash64_tlb_flush_hpte(cpu, ptex, v, r);

    return REMOVE_SUCCESS;

}


static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)

{

    BlockDriverAIOCBCoroutine *acb =

        container_of(blockacb, BlockDriverAIOCBCoroutine, common);

    bool done = false;

    acb->done = &done;

    while (!done) {

        qemu_aio_wait();

    }

}


static uint64_t vfio_rtl8168_window_quirk_read(void *opaque,

                                               hwaddr addr, unsigned size)

{

    VFIOQuirk *quirk = opaque;

    VFIOPCIDevice *vdev = quirk->vdev;

    switch (addr) {

    case 4: /* address */

        if (quirk->data.flags) {

            trace_vfio_rtl8168_window_quirk_read_fake(

                    memory_region_name(&quirk->mem),

                    vdev->vbasedev.name);

            return quirk->data.address_match ^ 0x10000000U;

        }

        break;

    case 0: /* data */

        if (quirk->data.flags) {

            uint64_t val;

            trace_vfio_rtl8168_window_quirk_read_table(

                    memory_region_name(&quirk->mem),

                    vdev->vbasedev.name);

            if (!(vdev->pdev.cap_present & QEMU_PCI_CAP_MSIX)) {

                return 0;

            }

            memory_region_dispatch_read(&vdev->pdev.msix_table_mmio,

                                        (hwaddr)(quirk->data.address_match

                                                 & 0xfff),

                                        &val,

                                        size,

                                        MEMTXATTRS_UNSPECIFIED);

            return val;

        }

    }

    trace_vfio_rtl8168_window_quirk_read_direct(memory_region_name(&quirk->mem),

                                                vdev->vbasedev.name);

    return vfio_region_read(&vdev->bars[quirk->data.bar].region,

                            addr + 0x70, size);

}


static void init_event_facility(Object *obj)

{

    SCLPEventFacility *event_facility = EVENT_FACILITY(obj);

    DeviceState *sdev = DEVICE(obj);

    /* Spawn a new bus for SCLP events */

    qbus_create_inplace(&event_facility->sbus, sizeof(event_facility->sbus),

                        TYPE_SCLP_EVENTS_BUS, sdev, NULL);

    object_initialize(&event_facility->quiesce_event, sizeof(SCLPEvent),

                      TYPE_SCLP_QUIESCE);

    qdev_set_parent_bus(DEVICE(&event_facility->quiesce_event),

                        &event_facility->sbus.qbus);

    object_initialize(&event_facility->cpu_hotplug_event, sizeof(SCLPEvent),

                      TYPE_SCLP_CPU_HOTPLUG);

    qdev_set_parent_bus(DEVICE(&event_facility->cpu_hotplug_event),

                        &event_facility->sbus.qbus);

    /* the facility will automatically realize the devices via the bus */

}