static void virtio_ccw_notify(DeviceState *d, uint16_t vector)

{

    VirtioCcwDevice *dev = to_virtio_ccw_dev_fast(d);

    SubchDev *sch = dev->sch;

    uint64_t indicators;

    if (vector >= 128) {

        return;

    }

    if (vector < VIRTIO_PCI_QUEUE_MAX) {

        if (!dev->indicators) {

            return;

        }

        if (sch->thinint_active) {

            /*

             * In the adapter interrupt case, indicators points to a

             * memory area that may be (way) larger than 64 bit and

             * ind_bit indicates the start of the indicators in a big

             * endian notation.

             */

            uint64_t ind_bit = dev->routes.adapter.ind_offset;

            virtio_set_ind_atomic(sch, dev->indicators->addr +

                                  (ind_bit + vector) / 8,

                                  0x80 >> ((ind_bit + vector) % 8));

            if (!virtio_set_ind_atomic(sch, dev->summary_indicator->addr,

                                       0x01)) {

                css_adapter_interrupt(dev->thinint_isc);

            }

        } else {

            indicators = address_space_ldq(&address_space_memory,

                                           dev->indicators->addr,

                                           MEMTXATTRS_UNSPECIFIED,

                                           NULL);

            indicators |= 1ULL << vector;

            address_space_stq(&address_space_memory, dev->indicators->addr,

                              indicators, MEMTXATTRS_UNSPECIFIED, NULL);

            css_conditional_io_interrupt(sch);

        }

    } else {

        if (!dev->indicators2) {

            return;

        }

        vector = 0;

        indicators = address_space_ldq(&address_space_memory,

                                       dev->indicators2->addr,

                                       MEMTXATTRS_UNSPECIFIED,

                                       NULL);

        indicators |= 1ULL << vector;

        address_space_stq(&address_space_memory, dev->indicators2->addr,

                          indicators, MEMTXATTRS_UNSPECIFIED, NULL);

        css_conditional_io_interrupt(sch);

    }

}


void cpu_x86_load_seg(CPUX86State *s, int seg_reg, int selector)

{

    CPUX86State *saved_env;

    saved_env = env;

    env = s;

    if (env->eflags & VM_MASK) {

        SegmentCache *sc;

        selector &= 0xffff;

        sc = &env->seg_cache[seg_reg];

        /* NOTE: in VM86 mode, limit and seg_32bit are never reloaded,

           so we must load them here */

        sc->base = (void *)(selector << 4);

        sc->limit = 0xffff;

        sc->seg_32bit = 0;

        env->segs[seg_reg] = selector;

    } else {

        load_seg(seg_reg, selector, 0);

    }

    env = saved_env;

}


static char *sysbus_get_fw_dev_path(DeviceState *dev)

{

    SysBusDevice *s = sysbus_from_qdev(dev);

    char path[40];

    int off;

    off = snprintf(path, sizeof(path), "%s", qdev_fw_name(dev));

    if (s->num_mmio) {

        snprintf(path + off, sizeof(path) - off, "@"TARGET_FMT_plx,

                 s->mmio[0].addr);

    } else if (s->num_pio) {

        snprintf(path + off, sizeof(path) - off, "@i%04x", s->pio[0]);

    }

    return strdup(path);

}


void hmp_info_memory_devices(Monitor *mon, const QDict *qdict)

{

    Error *err = NULL;

    MemoryDeviceInfoList *info_list = qmp_query_memory_devices(&err);

    MemoryDeviceInfoList *info;

    MemoryDeviceInfo *value;

    PCDIMMDeviceInfo *di;

    for (info = info_list; info; info = info->next) {

        value = info->value;

        if (value) {

            switch (value->kind) {

            case MEMORY_DEVICE_INFO_KIND_DIMM:

                di = value->dimm;

                monitor_printf(mon, "Memory device [%s]: \"%s\"\n",

                               MemoryDeviceInfoKind_lookup[value->kind],

                               di->id ? di->id : "");

                monitor_printf(mon, "  addr: 0x%" PRIx64 "\n", di->addr);

                monitor_printf(mon, "  slot: %" PRId64 "\n", di->slot);

                monitor_printf(mon, "  node: %" PRId64 "\n", di->node);

                monitor_printf(mon, "  size: %" PRIu64 "\n", di->size);

                monitor_printf(mon, "  memdev: %s\n", di->memdev);

                monitor_printf(mon, "  hotplugged: %s\n",

                               di->hotplugged ? "true" : "false");

                monitor_printf(mon, "  hotpluggable: %s\n",

                               di->hotpluggable ? "true" : "false");

                break;

            default:

                break;

            }

        }

    }

    qapi_free_MemoryDeviceInfoList(info_list);

}


static void v9fs_synth_seekdir(FsContext *ctx, V9fsFidOpenState *fs, off_t off)

{

    V9fsSynthOpenState *synth_open = fs->private;

    synth_open->offset = off;

}


static struct vm_area_struct *vma_first(const struct mm_struct *mm)

{

    return (TAILQ_FIRST(&mm->mm_mmap));

}


static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)

{

    DNXHDEncContext *ctx = avctx->priv_data;

    int mb_y = jobnr, mb_x;

    ctx = ctx->thread[threadnr];

    if (ctx->cid_table->bit_depth == 8) {

        uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y<<4) * ctx->m.linesize);

        for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x, pix += 16) {

            unsigned mb  = mb_y * ctx->m.mb_width + mb_x;

            int sum = ctx->m.dsp.pix_sum(pix, ctx->m.linesize);

            int varc = (ctx->m.dsp.pix_norm1(pix, ctx->m.linesize) - (((unsigned)(sum*sum))>>8)+128)>>8;

            ctx->mb_cmp[mb].value = varc;

            ctx->mb_cmp[mb].mb = mb;

        }

    } else { // 10-bit

        int const linesize = ctx->m.linesize >> 1;

        for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x) {

            uint16_t *pix = (uint16_t*)ctx->thread[0]->src[0] + ((mb_y << 4) * linesize) + (mb_x << 4);

            unsigned mb  = mb_y * ctx->m.mb_width + mb_x;

            int sum = 0;

            int sqsum = 0;

            int mean, sqmean;

            // Macroblocks are 16x16 pixels, unlike DCT blocks which are 8x8.

            for (int i = 0; i < 16; ++i) {

                for (int j = 0; j < 16; ++j) {

                    // Turn 16-bit pixels into 10-bit ones.

                    int const sample = (unsigned)pix[j] >> 6;

                    sum += sample;

                    sqsum += sample * sample;

                    // 2^10 * 2^10 * 16 * 16 = 2^28, which is less than INT_MAX

                }

                pix += linesize;

            }

            mean = sum >> 8; // 16*16 == 2^8

            sqmean = sqsum >> 8;

            ctx->mb_cmp[mb].value = sqmean - mean * mean;

            ctx->mb_cmp[mb].mb = mb;

        }

    }

    return 0;

}


static void xan_wc3_decode_frame(XanContext *s) {

    int width = s->avctx->width;

    int height = s->avctx->height;

    int total_pixels = width * height;

    unsigned char opcode;

    unsigned char flag = 0;

    int size = 0;

    int motion_x, motion_y;

    int x, y;

    unsigned char *opcode_buffer = s->buffer1;

    int opcode_buffer_size = s->buffer1_size;

    const unsigned char *imagedata_buffer = s->buffer2;

    /* pointers to segments inside the compressed chunk */

    const unsigned char *huffman_segment;

    const unsigned char *size_segment;

    const unsigned char *vector_segment;

    const unsigned char *imagedata_segment;

    huffman_segment =   s->buf + AV_RL16(&s->buf[0]);

    size_segment =      s->buf + AV_RL16(&s->buf[2]);

    vector_segment =    s->buf + AV_RL16(&s->buf[4]);

    imagedata_segment = s->buf + AV_RL16(&s->buf[6]);

    xan_huffman_decode(opcode_buffer, opcode_buffer_size,

                       huffman_segment, s->size - (huffman_segment - s->buf) );

    if (imagedata_segment[0] == 2)

        xan_unpack(s->buffer2, &imagedata_segment[1], s->buffer2_size);

    else

        imagedata_buffer = &imagedata_segment[1];

    /* use the decoded data segments to build the frame */

    x = y = 0;

    while (total_pixels) {

        opcode = *opcode_buffer++;

        size = 0;

        switch (opcode) {

        case 0:

            flag ^= 1;

            continue;

        case 1:

        case 2:

        case 3:

        case 4:

        case 5:

        case 6:

        case 7:

        case 8:

            size = opcode;

            break;

        case 12:

        case 13:

        case 14:

        case 15:

        case 16:

        case 17:

        case 18:

            size += (opcode - 10);

            break;

        case 9:

        case 19:

            size = *size_segment++;

            break;

        case 10:

        case 20:

            size = AV_RB16(&size_segment[0]);

            size_segment += 2;

            break;

        case 11:

        case 21:

            size = AV_RB24(size_segment);

            size_segment += 3;

            break;

        }

        if (opcode < 12) {

            flag ^= 1;

            if (flag) {

                /* run of (size) pixels is unchanged from last frame */

                xan_wc3_copy_pixel_run(s, x, y, size, 0, 0);

            } else {

                /* output a run of pixels from imagedata_buffer */

                xan_wc3_output_pixel_run(s, imagedata_buffer, x, y, size);

                imagedata_buffer += size;

            }

        } else {

            /* run-based motion compensation from last frame */

            motion_x = sign_extend(*vector_segment >> 4,  4);

            motion_y = sign_extend(*vector_segment & 0xF, 4);

            vector_segment++;

            /* copy a run of pixels from the previous frame */

            xan_wc3_copy_pixel_run(s, x, y, size, motion_x, motion_y);

            flag = 0;

        }

        /* coordinate accounting */

        total_pixels -= size;

        y += (x + size) / width;

        x  = (x + size) % width;

    }

}


static void qmp_input_start_alternate(Visitor *v, const char *name,

                                      GenericAlternate **obj, size_t size,

                                      bool promote_int, Error **errp)

{

    QmpInputVisitor *qiv = to_qiv(v);

    QObject *qobj = qmp_input_get_object(qiv, name, false, errp);

    if (!qobj) {

        *obj = NULL;

        return;

    }

    *obj = g_malloc0(size);

    (*obj)->type = qobject_type(qobj);

    if (promote_int && (*obj)->type == QTYPE_QINT) {

        (*obj)->type = QTYPE_QFLOAT;

    }

}


static void ac97_write(void *opaque, target_phys_addr_t addr, uint64_t value,

                       unsigned size)

{

    MilkymistAC97State *s = opaque;

    trace_milkymist_ac97_memory_write(addr, value);

    addr >>= 2;

    switch (addr) {

    case R_AC97_CTRL:

        /* always raise an IRQ according to the direction */

        if (value & AC97_CTRL_RQEN) {

            if (value & AC97_CTRL_WRITE) {

                trace_milkymist_ac97_pulse_irq_crrequest();

                qemu_irq_pulse(s->crrequest_irq);

            } else {

                trace_milkymist_ac97_pulse_irq_crreply();

                qemu_irq_pulse(s->crreply_irq);

            }

        }

        /* RQEN is self clearing */

        s->regs[addr] = value & ~AC97_CTRL_RQEN;

        break;

    case R_D_CTRL:

    case R_U_CTRL:

        s->regs[addr] = value;

        update_voices(s);

        break;

    case R_AC97_ADDR:

    case R_AC97_DATAOUT:

    case R_AC97_DATAIN:

    case R_D_ADDR:

    case R_D_REMAINING:

    case R_U_ADDR:

    case R_U_REMAINING:

        s->regs[addr] = value;

        break;

    default:

        error_report("milkymist_ac97: write access to unknown register 0x"

                TARGET_FMT_plx, addr);

        break;

    }

}


static void mch_realize(PCIDevice *d, Error **errp)

{

    int i;

    MCHPCIState *mch = MCH_PCI_DEVICE(d);

    /* setup pci memory mapping */

    pc_pci_as_mapping_init(OBJECT(mch), mch->system_memory,

                           mch->pci_address_space);

    /* if *disabled* show SMRAM to all CPUs */

    memory_region_init_alias(&mch->smram_region, OBJECT(mch), "smram-region",

                             mch->pci_address_space, 0xa0000, 0x20000);

    memory_region_add_subregion_overlap(mch->system_memory, 0xa0000,

                                        &mch->smram_region, 1);

    memory_region_set_enabled(&mch->smram_region, true);

    memory_region_init_alias(&mch->open_high_smram, OBJECT(mch), "smram-open-high",

                             mch->ram_memory, 0xa0000, 0x20000);

    memory_region_add_subregion_overlap(mch->system_memory, 0xfeda0000,

                                        &mch->open_high_smram, 1);

    memory_region_set_enabled(&mch->open_high_smram, false);

    /* smram, as seen by SMM CPUs */

    memory_region_init(&mch->smram, OBJECT(mch), "smram", 1ull << 32);

    memory_region_set_enabled(&mch->smram, true);

    memory_region_init_alias(&mch->low_smram, OBJECT(mch), "smram-low",

                             mch->ram_memory, 0xa0000, 0x20000);

    memory_region_set_enabled(&mch->low_smram, true);

    memory_region_add_subregion(&mch->smram, 0xa0000, &mch->low_smram);

    memory_region_init_alias(&mch->high_smram, OBJECT(mch), "smram-high",

                             mch->ram_memory, 0xa0000, 0x20000);

    memory_region_set_enabled(&mch->high_smram, true);

    memory_region_add_subregion(&mch->smram, 0xfeda0000, &mch->high_smram);

    memory_region_init_io(&mch->tseg_blackhole, OBJECT(mch),

                          &tseg_blackhole_ops, NULL,

                          "tseg-blackhole", 0);

    memory_region_set_enabled(&mch->tseg_blackhole, false);

    memory_region_add_subregion_overlap(mch->system_memory,

                                        mch->below_4g_mem_size,

                                        &mch->tseg_blackhole, 1);

    memory_region_init_alias(&mch->tseg_window, OBJECT(mch), "tseg-window",

                             mch->ram_memory, mch->below_4g_mem_size, 0);

    memory_region_set_enabled(&mch->tseg_window, false);

    memory_region_add_subregion(&mch->smram, mch->below_4g_mem_size,

                                &mch->tseg_window);

    object_property_add_const_link(qdev_get_machine(), "smram",

                                   OBJECT(&mch->smram), &error_abort);

    init_pam(DEVICE(mch), mch->ram_memory, mch->system_memory,

             mch->pci_address_space, &mch->pam_regions[0],

             PAM_BIOS_BASE, PAM_BIOS_SIZE);

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

        init_pam(DEVICE(mch), mch->ram_memory, mch->system_memory,

                 mch->pci_address_space, &mch->pam_regions[i+1],

                 PAM_EXPAN_BASE + i * PAM_EXPAN_SIZE, PAM_EXPAN_SIZE);

    }

    /* Intel IOMMU (VT-d) */

    if (machine_iommu(current_machine)) {

        mch_init_dmar(mch);

    }

}


static void arm_tr_translate_insn(DisasContextBase *dcbase, CPUState *cpu)

{

    DisasContext *dc = container_of(dcbase, DisasContext, base);

    CPUARMState *env = cpu->env_ptr;

#ifdef CONFIG_USER_ONLY

    /* Intercept jump to the magic kernel page.  */

    if (dc->pc >= 0xffff0000) {

        /* We always get here via a jump, so know we are not in a

           conditional execution block.  */

        gen_exception_internal(EXCP_KERNEL_TRAP);

        dc->base.is_jmp = DISAS_NORETURN;

        return;

    }

#endif

    if (dc->ss_active && !dc->pstate_ss) {

        /* Singlestep state is Active-pending.

         * If we're in this state at the start of a TB then either

         *  a) we just took an exception to an EL which is being debugged

         *     and this is the first insn in the exception handler

         *  b) debug exceptions were masked and we just unmasked them

         *     without changing EL (eg by clearing PSTATE.D)

         * In either case we're going to take a swstep exception in the

         * "did not step an insn" case, and so the syndrome ISV and EX

         * bits should be zero.

         */

        assert(dc->base.num_insns == 1);

        gen_exception(EXCP_UDEF, syn_swstep(dc->ss_same_el, 0, 0),

                      default_exception_el(dc));

        dc->base.is_jmp = DISAS_NORETURN;

        return;

    }

    if (dc->thumb) {

        disas_thumb_insn(env, dc);

        if (dc->condexec_mask) {

            dc->condexec_cond = (dc->condexec_cond & 0xe)

                | ((dc->condexec_mask >> 4) & 1);

            dc->condexec_mask = (dc->condexec_mask << 1) & 0x1f;

            if (dc->condexec_mask == 0) {

                dc->condexec_cond = 0;

            }

        }

    } else {

        unsigned int insn = arm_ldl_code(env, dc->pc, dc->sctlr_b);

        dc->pc += 4;

        disas_arm_insn(dc, insn);

    }

    if (dc->condjmp && !dc->base.is_jmp) {

        gen_set_label(dc->condlabel);

        dc->condjmp = 0;

    }

    if (dc->base.is_jmp == DISAS_NEXT) {

        /* Translation stops when a conditional branch is encountered.

         * Otherwise the subsequent code could get translated several times.

         * Also stop translation when a page boundary is reached.  This

         * ensures prefetch aborts occur at the right place.  */

        if (dc->pc >= dc->next_page_start ||

            (dc->pc >= dc->next_page_start - 3 &&

             insn_crosses_page(env, dc))) {

            /* We want to stop the TB if the next insn starts in a new page,

             * or if it spans between this page and the next. This means that

             * if we're looking at the last halfword in the page we need to

             * see if it's a 16-bit Thumb insn (which will fit in this TB)

             * or a 32-bit Thumb insn (which won't).

             * This is to avoid generating a silly TB with a single 16-bit insn

             * in it at the end of this page (which would execute correctly

             * but isn't very efficient).

             */

            dc->base.is_jmp = DISAS_TOO_MANY;

        }

    }

    dc->base.pc_next = dc->pc;

    translator_loop_temp_check(&dc->base);

}


void ppc_tlb_invalidate_one(CPUPPCState *env, target_ulong addr)

{

#if !defined(FLUSH_ALL_TLBS)

    PowerPCCPU *cpu = ppc_env_get_cpu(env);

    CPUState *cs;

    addr &= TARGET_PAGE_MASK;

    switch (env->mmu_model) {

    case POWERPC_MMU_SOFT_6xx:

    case POWERPC_MMU_SOFT_74xx:

        ppc6xx_tlb_invalidate_virt(env, addr, 0);

        if (env->id_tlbs == 1) {

            ppc6xx_tlb_invalidate_virt(env, addr, 1);

        }

        break;

    case POWERPC_MMU_SOFT_4xx:

    case POWERPC_MMU_SOFT_4xx_Z:

        ppc4xx_tlb_invalidate_virt(env, addr, env->spr[SPR_40x_PID]);

        break;

    case POWERPC_MMU_REAL:

        cpu_abort(CPU(cpu), "No TLB for PowerPC 4xx in real mode\n");

        break;

    case POWERPC_MMU_MPC8xx:

        /* XXX: TODO */

        cpu_abort(CPU(cpu), "MPC8xx MMU model is not implemented\n");

        break;

    case POWERPC_MMU_BOOKE:

        /* XXX: TODO */

        cpu_abort(CPU(cpu), "BookE MMU model is not implemented\n");

        break;

    case POWERPC_MMU_BOOKE206:

        /* XXX: TODO */

        cpu_abort(CPU(cpu), "BookE 2.06 MMU model is not implemented\n");

        break;

    case POWERPC_MMU_32B:

    case POWERPC_MMU_601:

        /* tlbie invalidate TLBs for all segments */

        addr &= ~((target_ulong)-1ULL << 28);

        cs = CPU(cpu);

        /* XXX: this case should be optimized,

         * giving a mask to tlb_flush_page

         */

        tlb_flush_page(cs, addr | (0x0 << 28));

        tlb_flush_page(cs, addr | (0x1 << 28));

        tlb_flush_page(cs, addr | (0x2 << 28));

        tlb_flush_page(cs, addr | (0x3 << 28));

        tlb_flush_page(cs, addr | (0x4 << 28));

        tlb_flush_page(cs, addr | (0x5 << 28));

        tlb_flush_page(cs, addr | (0x6 << 28));

        tlb_flush_page(cs, addr | (0x7 << 28));

        tlb_flush_page(cs, addr | (0x8 << 28));

        tlb_flush_page(cs, addr | (0x9 << 28));

        tlb_flush_page(cs, addr | (0xA << 28));

        tlb_flush_page(cs, addr | (0xB << 28));

        tlb_flush_page(cs, addr | (0xC << 28));

        tlb_flush_page(cs, addr | (0xD << 28));

        tlb_flush_page(cs, addr | (0xE << 28));

        tlb_flush_page(cs, addr | (0xF << 28));

        break;

#if defined(TARGET_PPC64)

    case POWERPC_MMU_64B:

    case POWERPC_MMU_2_03:

    case POWERPC_MMU_2_06:

    case POWERPC_MMU_2_06a:

    case POWERPC_MMU_2_07:

    case POWERPC_MMU_2_07a:

        /* tlbie invalidate TLBs for all segments */

        /* XXX: given the fact that there are too many segments to invalidate,

         *      and we still don't have a tlb_flush_mask(env, n, mask) in QEMU,

         *      we just invalidate all TLBs

         */

        tlb_flush(CPU(cpu), 1);

        break;

#endif /* defined(TARGET_PPC64) */

    default:

        /* XXX: TODO */

        cpu_abort(CPU(cpu), "Unknown MMU model\n");

        break;

    }

#else

    ppc_tlb_invalidate_all(env);

#endif

}


static int scsi_qdev_init(DeviceState *qdev)

{

    SCSIDevice *dev = SCSI_DEVICE(qdev);

    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus);

    SCSIDevice *d;

    int rc = -1;

    if (dev->channel > bus->info->max_channel) {

        error_report("bad scsi channel id: %d", dev->channel);

        goto err;

    }

    if (dev->id != -1 && dev->id > bus->info->max_target) {

        error_report("bad scsi device id: %d", dev->id);

        goto err;

    }

    if (dev->lun != -1 && dev->lun > bus->info->max_lun) {

        error_report("bad scsi device lun: %d", dev->lun);

        goto err;

    }

    if (dev->id == -1) {

        int id = -1;

        if (dev->lun == -1) {

            dev->lun = 0;

        }

        do {

            d = scsi_device_find(bus, dev->channel, ++id, dev->lun);

        } while (d && d->lun == dev->lun && id < bus->info->max_target);

        if (d && d->lun == dev->lun) {

            error_report("no free target");

            goto err;

        }

        dev->id = id;

    } else if (dev->lun == -1) {

        int lun = -1;

        do {

            d = scsi_device_find(bus, dev->channel, dev->id, ++lun);

        } while (d && d->lun == lun && lun < bus->info->max_lun);

        if (d && d->lun == lun) {

            error_report("no free lun");

            goto err;

        }

        dev->lun = lun;

    } else {

        d = scsi_device_find(bus, dev->channel, dev->id, dev->lun);

        assert(d);

        if (d->lun == dev->lun && dev != d) {

            error_report("lun already used by '%s'", d->qdev.id);

            goto err;

        }

    }

    QTAILQ_INIT(&dev->requests);

    rc = scsi_device_init(dev);

    if (rc == 0) {

        dev->vmsentry = qemu_add_vm_change_state_handler(scsi_dma_restart_cb,

                                                         dev);

    }

    if (bus->info->hotplug) {

        bus->info->hotplug(bus, dev);

    }

err:

    return rc;

}


static BusState *qbus_find_recursive(BusState *bus, const char *name,

                                     const BusInfo *info)

{

    DeviceState *dev;

    BusState *child, *ret;

    int match = 1;

    if (name && (strcmp(bus->name, name) != 0)) {

        match = 0;

    }

    if (info && (bus->info != info)) {

        match = 0;

    }

    if (match) {

        return bus;

    }

    LIST_FOREACH(dev, &bus->children, sibling) {

        LIST_FOREACH(child, &dev->child_bus, sibling) {

            ret = qbus_find_recursive(child, name, info);

            if (ret) {

                return ret;

            }

        }

    }

    return NULL;

}


static void dump_metadata(void *ctx, AVDictionary *m, const char *indent)

{

    if(m && !(m->count == 1 && av_dict_get(m, "language", NULL, 0))){

        AVDictionaryEntry *tag=NULL;

        av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);

        while((tag=av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX))) {

            if(strcmp("language", tag->key)){

                const char *p = tag->value;

                av_log(ctx, AV_LOG_INFO, "%s  %-16s: ", indent, tag->key);

                while(*p) {

                    char tmp[256];

                    size_t len = strcspn(p, "\xd\xa");

                    av_strlcpy(tmp, p, FFMIN(sizeof(tmp), len+1));

                    av_log(ctx, AV_LOG_INFO, "%s", tmp);

                    p += len;

                    if (*p == 0xd) av_log(ctx, AV_LOG_INFO, " ");

                    if (*p == 0xa) av_log(ctx, AV_LOG_INFO, "\n%s  %-16s: ", indent, "");

                    if (*p) p++;

                }

                av_log(ctx, AV_LOG_INFO, "\n");

            }

        }

    }

}


X86CPU *cpu_x86_create(const char *cpu_model, Error **errp)

{

    X86CPU *cpu = NULL;

    ObjectClass *oc;

    CPUClass *cc;

    gchar **model_pieces;

    char *name, *features;

    Error *error = NULL;

    const char *typename;

    model_pieces = g_strsplit(cpu_model, ",", 2);

    if (!model_pieces[0]) {

        error_setg(&error, "Invalid/empty CPU model name");

        goto out;

    }

    name = model_pieces[0];

    features = model_pieces[1];

    oc = x86_cpu_class_by_name(name);

    if (oc == NULL) {

        error_setg(&error, "Unable to find CPU definition: %s", name);

        goto out;

    }

    cc = CPU_CLASS(oc);

    typename = object_class_get_name(oc);

    cc->parse_features(typename, features, &error);

    cpu = X86_CPU(object_new(typename));

    if (error) {

        goto out;

    }

out:

    if (error != NULL) {

        error_propagate(errp, error);

        if (cpu) {

            object_unref(OBJECT(cpu));

            cpu = NULL;

        }

    }

    g_strfreev(model_pieces);

    return cpu;

}


static QEMUClock *qemu_new_clock(int type)

{

    QEMUClock *clock;

    clock = g_malloc0(sizeof(QEMUClock));

    clock->type = type;

    clock->enabled = true;

    clock->last = INT64_MIN;

    notifier_list_init(&clock->reset_notifiers);

    return clock;

}


static gboolean gd_enter_event(GtkWidget *widget, GdkEventCrossing *crossing,

                               gpointer opaque)

{

    VirtualConsole *vc = opaque;

    GtkDisplayState *s = vc->s;

    if (!gd_is_grab_active(s) && gd_grab_on_hover(s)) {

        gd_grab_keyboard(vc);

    }

    return TRUE;

}


sd_co_get_block_status(BlockDriverState *bs, int64_t sector_num, int nb_sectors,

                       int *pnum)

{

    BDRVSheepdogState *s = bs->opaque;

    SheepdogInode *inode = &s->inode;

    uint32_t object_size = (UINT32_C(1) << inode->block_size_shift);

    uint64_t offset = sector_num * BDRV_SECTOR_SIZE;

    unsigned long start = offset / object_size,

                  end = DIV_ROUND_UP((sector_num + nb_sectors) *

                                     BDRV_SECTOR_SIZE, object_size);

    unsigned long idx;

    int64_t ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | offset;

    for (idx = start; idx < end; idx++) {

        if (inode->data_vdi_id[idx] == 0) {

            break;

        }

    }

    if (idx == start) {

        /* Get the longest length of unallocated sectors */

        ret = 0;

        for (idx = start + 1; idx < end; idx++) {

            if (inode->data_vdi_id[idx] != 0) {

                break;

            }

        }

    }

    *pnum = (idx - start) * object_size / BDRV_SECTOR_SIZE;

    if (*pnum > nb_sectors) {

        *pnum = nb_sectors;

    }

    return ret;

}


void laio_attach_aio_context(LinuxAioState *s, AioContext *new_context)

{

    s->aio_context = new_context;

    s->completion_bh = aio_bh_new(new_context, qemu_laio_completion_bh, s);

    aio_set_event_notifier(new_context, &s->e, false,

                           qemu_laio_completion_cb, NULL);

}


process_tx_desc(E1000State *s, struct e1000_tx_desc *dp)

{

    PCIDevice *d = PCI_DEVICE(s);

    uint32_t txd_lower = le32_to_cpu(dp->lower.data);

    uint32_t dtype = txd_lower & (E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D);

    unsigned int split_size = txd_lower & 0xffff, bytes, sz;

    unsigned int msh = 0xfffff;

    uint64_t addr;

    struct e1000_context_desc *xp = (struct e1000_context_desc *)dp;

    struct e1000_tx *tp = &s->tx;

    s->mit_ide |= (txd_lower & E1000_TXD_CMD_IDE);

    if (dtype == E1000_TXD_CMD_DEXT) {    /* context descriptor */

        e1000x_read_tx_ctx_descr(xp, &tp->props);

        tp->tso_frames = 0;

        if (tp->props.tucso == 0) {    /* this is probably wrong */

            DBGOUT(TXSUM, "TCP/UDP: cso 0!\n");

            tp->props.tucso = tp->props.tucss + (tp->props.tcp ? 16 : 6);

        }

        return;

    } else if (dtype == (E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D)) {

        // data descriptor

        if (tp->size == 0) {

            tp->props.sum_needed = le32_to_cpu(dp->upper.data) >> 8;

        }

        tp->props.cptse = (txd_lower & E1000_TXD_CMD_TSE) ? 1 : 0;

    } else {

        // legacy descriptor

        tp->props.cptse = 0;

    }

    if (e1000x_vlan_enabled(s->mac_reg) &&

        e1000x_is_vlan_txd(txd_lower) &&

        (tp->props.cptse || txd_lower & E1000_TXD_CMD_EOP)) {

        tp->vlan_needed = 1;

        stw_be_p(tp->vlan_header,

                      le16_to_cpu(s->mac_reg[VET]));

        stw_be_p(tp->vlan_header + 2,

                      le16_to_cpu(dp->upper.fields.special));

    }

    addr = le64_to_cpu(dp->buffer_addr);

    if (tp->props.tse && tp->props.cptse) {

        msh = tp->props.hdr_len + tp->props.mss;

        do {

            bytes = split_size;

            if (tp->size + bytes > msh)

                bytes = msh - tp->size;

            bytes = MIN(sizeof(tp->data) - tp->size, bytes);

            pci_dma_read(d, addr, tp->data + tp->size, bytes);

            sz = tp->size + bytes;

            if (sz >= tp->props.hdr_len && tp->size < tp->props.hdr_len) {

                memmove(tp->header, tp->data, tp->props.hdr_len);

            }

            tp->size = sz;

            addr += bytes;

            if (sz == msh) {

                xmit_seg(s);

                memmove(tp->data, tp->header, tp->props.hdr_len);

                tp->size = tp->props.hdr_len;

            }

            split_size -= bytes;

        } while (bytes && split_size);

    } else if (!tp->props.tse && tp->props.cptse) {

        // context descriptor TSE is not set, while data descriptor TSE is set

        DBGOUT(TXERR, "TCP segmentation error\n");

    } else {

        split_size = MIN(sizeof(tp->data) - tp->size, split_size);

        pci_dma_read(d, addr, tp->data + tp->size, split_size);

        tp->size += split_size;

    }

    if (!(txd_lower & E1000_TXD_CMD_EOP))

        return;

    if (!(tp->props.tse && tp->props.cptse && tp->size < tp->props.hdr_len)) {

        xmit_seg(s);

    }

    tp->tso_frames = 0;

    tp->props.sum_needed = 0;

    tp->vlan_needed = 0;

    tp->size = 0;

    tp->props.cptse = 0;

}


int unix_socket_outgoing(const char *path)

{

    Error *local_err = NULL;

    int fd = unix_connect(path, &local_err);

    if (local_err != NULL) {

        qerror_report_err(local_err);

        error_free(local_err);

    }

    return fd;

}


static ssize_t nbd_receive_request(int csock, struct nbd_request *request)

{

    uint8_t buf[4 + 4 + 8 + 8 + 4];

    uint32_t magic;

    if (read_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {

        LOG("read failed");

        errno = EINVAL;

        return -1;

    }

    /* Request

       [ 0 ..  3]   magic   (NBD_REQUEST_MAGIC)

       [ 4 ..  7]   type    (0 == READ, 1 == WRITE)

       [ 8 .. 15]   handle

       [16 .. 23]   from

       [24 .. 27]   len

     */

    magic = be32_to_cpup((uint32_t*)buf);

    request->type  = be32_to_cpup((uint32_t*)(buf + 4));

    request->handle = be64_to_cpup((uint64_t*)(buf + 8));

    request->from  = be64_to_cpup((uint64_t*)(buf + 16));

    request->len   = be32_to_cpup((uint32_t*)(buf + 24));

    TRACE("Got request: "

          "{ magic = 0x%x, .type = %d, from = %" PRIu64" , len = %u }",

          magic, request->type, request->from, request->len);

    if (magic != NBD_REQUEST_MAGIC) {

        LOG("invalid magic (got 0x%x)", magic);

        errno = EINVAL;

        return -1;

    }

    return 0;

}


static void raw_close_fd_pool(BDRVRawState *s)

{

    int i;

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

        if (s->fd_pool[i] != -1) {

            close(s->fd_pool[i]);

            s->fd_pool[i] = -1;

        }

    }

}


static UHCIAsync *uhci_async_alloc(UHCIState *s)

{

    UHCIAsync *async = g_malloc(sizeof(UHCIAsync));

    memset(&async->packet, 0, sizeof(async->packet));

    async->uhci  = s;

    async->valid = 0;

    async->td    = 0;

    async->token = 0;

    async->done  = 0;

    async->isoc  = 0;

    usb_packet_init(&async->packet);

    qemu_sglist_init(&async->sgl, 1);

    return async;

}


static void apic_startup(APICState *s, int vector_num)

{

    CPUState *env = s->cpu_env;

    if (!env->halted)

        return;

    env->eip = 0;

    cpu_x86_load_seg_cache(env, R_CS, vector_num << 8, vector_num << 12,

                           0xffff, 0);

    env->halted = 0;

}


void kvm_s390_virtio_irq(S390CPU *cpu, int config_change, uint64_t token)

{

    kvm_s390_interrupt_internal(cpu, KVM_S390_INT_VIRTIO, config_change,

                                token, 1);

}


static void bdrv_io_limits_intercept(BlockDriverState *bs,

                                     unsigned int bytes,

                                     bool is_write)

{

    /* does this io must wait */

    bool must_wait = throttle_schedule_timer(&bs->throttle_state, is_write);

    /* if must wait or any request of this type throttled queue the IO */

    if (must_wait ||

        !qemu_co_queue_empty(&bs->throttled_reqs[is_write])) {

        qemu_co_queue_wait(&bs->throttled_reqs[is_write]);

    }

    /* the IO will be executed, do the accounting */

    throttle_account(&bs->throttle_state, is_write, bytes);

    /* if the next request must wait -> do nothing */

    if (throttle_schedule_timer(&bs->throttle_state, is_write)) {

        return;

    }

    /* else queue next request for execution */

    qemu_co_queue_next(&bs->throttled_reqs[is_write]);

}


static int parse_bintree(Indeo3DecodeContext *ctx, AVCodecContext *avctx,

                         Plane *plane, int code, Cell *ref_cell,

                         const int depth, const int strip_width)

{

    Cell    curr_cell;

    int     bytes_used;

    if (depth <= 0) {

        av_log(avctx, AV_LOG_ERROR, "Stack overflow (corrupted binary tree)!\n");

        return AVERROR_INVALIDDATA; // unwind recursion

    }

    curr_cell = *ref_cell; // clone parent cell

    if (code == H_SPLIT) {

        SPLIT_CELL(ref_cell->height, curr_cell.height);

        ref_cell->ypos   += curr_cell.height;

        ref_cell->height -= curr_cell.height;

    } else if (code == V_SPLIT) {

        if (curr_cell.width > strip_width) {

            /* split strip */

            curr_cell.width = (curr_cell.width <= (strip_width << 1) ? 1 : 2) * strip_width;

        } else

            SPLIT_CELL(ref_cell->width, curr_cell.width);

        ref_cell->xpos  += curr_cell.width;

        ref_cell->width -= curr_cell.width;

    }

    while (1) { /* loop until return */

        RESYNC_BITSTREAM;

        switch (code = get_bits(&ctx->gb, 2)) {

        case H_SPLIT:

        case V_SPLIT:

            if (parse_bintree(ctx, avctx, plane, code, &curr_cell, depth - 1, strip_width))

                return AVERROR_INVALIDDATA;

            break;

        case INTRA_NULL:

            if (!curr_cell.tree) { /* MC tree INTRA code */

                curr_cell.mv_ptr = 0; /* mark the current strip as INTRA */

                curr_cell.tree   = 1; /* enter the VQ tree */

            } else { /* VQ tree NULL code */

                RESYNC_BITSTREAM;

                code = get_bits(&ctx->gb, 2);

                if (code >= 2) {

                    av_log(avctx, AV_LOG_ERROR, "Invalid VQ_NULL code: %d\n", code);

                    return AVERROR_INVALIDDATA;

                }

                if (code == 1)

                    av_log(avctx, AV_LOG_ERROR, "SkipCell procedure not implemented yet!\n");

                CHECK_CELL

                copy_cell(ctx, plane, &curr_cell);

                return 0;

            }

            break;

        case INTER_DATA:

            if (!curr_cell.tree) { /* MC tree INTER code */

                /* get motion vector index and setup the pointer to the mv set */

                if (!ctx->need_resync)

                    ctx->next_cell_data = &ctx->gb.buffer[(get_bits_count(&ctx->gb) + 7) >> 3];

                curr_cell.mv_ptr = &ctx->mc_vectors[*(ctx->next_cell_data++) << 1];

                curr_cell.tree   = 1; /* enter the VQ tree */

                UPDATE_BITPOS(8);

            } else { /* VQ tree DATA code */

                if (!ctx->need_resync)

                    ctx->next_cell_data = &ctx->gb.buffer[(get_bits_count(&ctx->gb) + 7) >> 3];

                CHECK_CELL

                bytes_used = decode_cell(ctx, avctx, plane, &curr_cell,

                                         ctx->next_cell_data, ctx->last_byte);

                if (bytes_used < 0)

                    return AVERROR_INVALIDDATA;

                UPDATE_BITPOS(bytes_used << 3);

                ctx->next_cell_data += bytes_used;

                return 0;

            }

            break;

        }

    }//while

    return 0;

}


int64_t swr_next_pts(struct SwrContext *s, int64_t pts){

    if(pts == INT64_MIN)

        return s->outpts;

    if(s->min_compensation >= FLT_MAX) {

        return (s->outpts = pts - swr_get_delay(s, s->in_sample_rate * (int64_t)s->out_sample_rate));

    } else {

        int64_t delta = pts - swr_get_delay(s, s->in_sample_rate * (int64_t)s->out_sample_rate) - s->outpts;

        double fdelta = delta /(double)(s->in_sample_rate * (int64_t)s->out_sample_rate);

        if(fabs(fdelta) > s->min_compensation) {

            if(!s->outpts || fabs(fdelta) > s->min_hard_compensation){

                int ret;

                if(delta > 0) ret = swr_inject_silence(s,  delta / s->out_sample_rate);

                else          ret = swr_drop_output   (s, -delta / s-> in_sample_rate);

                if(ret<0){

                    av_log(s, AV_LOG_ERROR, "Failed to compensate for timestamp delta of %f\n", fdelta);

                }

            } else if(s->soft_compensation_duration && s->max_soft_compensation) {

                int duration = s->out_sample_rate * s->soft_compensation_duration;

                double max_soft_compensation = s->max_soft_compensation / (s->max_soft_compensation < 0 ? -s->in_sample_rate : 1);

                int comp = av_clipf(fdelta, -max_soft_compensation, max_soft_compensation) * duration ;

                av_log(s, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n", fdelta, comp, duration);

                swr_set_compensation(s, comp, duration);

            }

        }

        return s->outpts;

    }

}


int av_utf8_decode(int32_t *codep, const uint8_t **bufp, const uint8_t *buf_end,

                   unsigned int flags)

{

    const uint8_t *p = *bufp;

    uint32_t top;

    uint64_t code;

    int ret = 0;

    if (p >= buf_end)

        return 0;

    code = *p++;

    /* first sequence byte starts with 10, or is 1111-1110 or 1111-1111,

       which is not admitted */

    if ((code & 0xc0) == 0x80 || code >= 0xFE) {

        ret = AVERROR(EILSEQ);

        goto end;

    }

    top = (code & 128) >> 1;

    while (code & top) {

        int tmp;

        if (p >= buf_end) {

            (*bufp) ++;

            return AVERROR(EILSEQ); /* incomplete sequence */

        }

        /* we assume the byte to be in the form 10xx-xxxx */

        tmp = *p++ - 128;   /* strip leading 1 */

        if (tmp>>6) {

            (*bufp) ++;

            return AVERROR(EILSEQ);

        }

        code = (code<<6) + tmp;

        top <<= 5;

    }

    code &= (top << 1) - 1;

    if (code >= 1<<31) {

        ret = AVERROR(EILSEQ);  /* out-of-range value */

        goto end;

    }

    *codep = code;

    if (code > 0x10FFFF &&

        !(flags & AV_UTF8_FLAG_ACCEPT_INVALID_BIG_CODES))

        ret = AVERROR(EILSEQ);

    if (code < 0x20 && code != 0x9 && code != 0xA && code != 0xD &&

        flags & AV_UTF8_FLAG_EXCLUDE_XML_INVALID_CONTROL_CODES)

        ret = AVERROR(EILSEQ);

    if (code >= 0xD800 && code <= 0xDFFF &&

        !(flags & AV_UTF8_FLAG_ACCEPT_SURROGATES))

        ret = AVERROR(EILSEQ);

    if ((code == 0xFFFE || code == 0xFFFF) &&

        !(flags & AV_UTF8_FLAG_ACCEPT_NON_CHARACTERS))

        ret = AVERROR(EILSEQ);

end:

    *bufp = p;

    return ret;

}


static av_always_inline av_flatten void h264_loop_filter_luma_intra_c(uint8_t *pix, int xstride, int ystride, int alpha, int beta)

{

    int d;

    for( d = 0; d < 16; d++ ) {

        const int p2 = pix[-3*xstride];

        const int p1 = pix[-2*xstride];

        const int p0 = pix[-1*xstride];

        const int q0 = pix[ 0*xstride];

        const int q1 = pix[ 1*xstride];

        const int q2 = pix[ 2*xstride];

        if( FFABS( p0 - q0 ) < alpha &&

            FFABS( p1 - p0 ) < beta &&

            FFABS( q1 - q0 ) < beta ) {

            if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){

                if( FFABS( p2 - p0 ) < beta)

                {

                    const int p3 = pix[-4*xstride];

                    /* p0', p1', p2' */

                    pix[-1*xstride] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;

                    pix[-2*xstride] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;

                    pix[-3*xstride] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;

                } else {

                    /* p0' */

                    pix[-1*xstride] = ( 2*p1 + p0 + q1 + 2 ) >> 2;

                }

                if( FFABS( q2 - q0 ) < beta)

                {

                    const int q3 = pix[3*xstride];

                    /* q0', q1', q2' */

                    pix[0*xstride] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;

                    pix[1*xstride] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;

                    pix[2*xstride] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;

                } else {

                    /* q0' */

                    pix[0*xstride] = ( 2*q1 + q0 + p1 + 2 ) >> 2;

                }

            }else{

                /* p0', q0' */

                pix[-1*xstride] = ( 2*p1 + p0 + q1 + 2 ) >> 2;

                pix[ 0*xstride] = ( 2*q1 + q0 + p1 + 2 ) >> 2;

            }

        }

        pix += ystride;

    }

}


static void sigbus_handler(int signal)

{

    siglongjmp(sigjump, 1);

}


void fw_cfg_add_bytes(FWCfgState *s, uint16_t key, uint8_t *data, uint32_t len)

{

    int arch = !!(key & FW_CFG_ARCH_LOCAL);

    key &= FW_CFG_ENTRY_MASK;

    assert(key < FW_CFG_MAX_ENTRY);

    s->entries[arch][key].data = data;

    s->entries[arch][key].len = len;

}


static void set_bmc_global_enables(IPMIBmcSim *ibs,

                                   uint8_t *cmd, unsigned int cmd_len,

                                   uint8_t *rsp, unsigned int *rsp_len,

                                   unsigned int max_rsp_len)

{

    IPMI_CHECK_CMD_LEN(3);

    set_global_enables(ibs, cmd[2]);

}


static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
                            int parse_extradata)
{
    AVCodecContext *const avctx = h->avctx;
    H264SliceContext *sl;
    int buf_index;
    unsigned context_count;
    int next_avc;
    int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
    int nal_index;
    int idr_cleared=0;
    int ret = 0;
    h->nal_unit_type= 0;
    if(!h->slice_context_count)
         h->slice_context_count= 1;
    h->max_contexts = h->slice_context_count;
    if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
        h->current_slice = 0;
        if (!h->first_field)
            h->cur_pic_ptr = NULL;
        ff_h264_reset_sei(h);
    if (h->nal_length_size == 4) {
        if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
            h->is_avc = 0;
        }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
            h->is_avc = 1;
    if (avctx->active_thread_type & FF_THREAD_FRAME)
        nals_needed = get_last_needed_nal(h, buf, buf_size);
    {
        buf_index     = 0;
        context_count = 0;
        next_avc      = h->is_avc ? 0 : buf_size;
        nal_index     = 0;
        for (;;) {
            int consumed;
            int dst_length;
            int bit_length;
            const uint8_t *ptr;
            int nalsize = 0;
            int err;
            if (buf_index >= next_avc) {
                nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
                if (nalsize < 0)
                    break;
                next_avc = buf_index + nalsize;
            } else {
                buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
                if (buf_index >= buf_size)
                    break;
                if (buf_index >= next_avc)
                    continue;
            sl = &h->slice_ctx[context_count];
            ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
                                     &consumed, next_avc - buf_index);
            if (!ptr || dst_length < 0) {
                ret = -1;
                goto end;
            bit_length = get_bit_length(h, buf, ptr, dst_length,
                                        buf_index + consumed, next_avc);
            if (h->avctx->debug & FF_DEBUG_STARTCODE)
                av_log(h->avctx, AV_LOG_DEBUG,
                       "NAL %d/%d at %d/%d length %d\n",
                       h->nal_unit_type, h->nal_ref_idc, buf_index, buf_size, dst_length);
            if (h->is_avc && (nalsize != consumed) && nalsize)
                av_log(h->avctx, AV_LOG_DEBUG,
                       "AVC: Consumed only %d bytes instead of %d\n",
                       consumed, nalsize);
            buf_index += consumed;
            nal_index++;
            if (avctx->skip_frame >= AVDISCARD_NONREF &&
                h->nal_ref_idc == 0 &&
                h->nal_unit_type != NAL_SEI)
                continue;
again:
            /* Ignore per frame NAL unit type during extradata
             * parsing. Decoding slices is not possible in codec init
             * with frame-mt */
            if (parse_extradata) {
                switch (h->nal_unit_type) {
                case NAL_IDR_SLICE:
                case NAL_SLICE:
                case NAL_DPA:
                case NAL_DPB:
                case NAL_DPC:
                    av_log(h->avctx, AV_LOG_WARNING,
                           "Ignoring NAL %d in global header/extradata\n",
                           h->nal_unit_type);
                    // fall through to next case
                case NAL_AUXILIARY_SLICE:
                    h->nal_unit_type = NAL_FF_IGNORE;
            err = 0;
            switch (h->nal_unit_type) {
            case NAL_IDR_SLICE:
                if ((ptr[0] & 0xFC) == 0x98) {
                    av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
                    h->next_outputed_poc = INT_MIN;
                    ret = -1;
                    goto end;
                if (h->nal_unit_type != NAL_IDR_SLICE) {
                    av_log(h->avctx, AV_LOG_ERROR,
                           "Invalid mix of idr and non-idr slices\n");
                    ret = -1;
                    goto end;
                if(!idr_cleared) {
                    if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
                        av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
                        ret = AVERROR_INVALIDDATA;
                        goto end;
                    idr(h); // FIXME ensure we don't lose some frames if there is reordering
                idr_cleared = 1;
                h->has_recovery_point = 1;
            case NAL_SLICE:
                init_get_bits(&sl->gb, ptr, bit_length);
                if (   nals_needed >= nal_index
                    || (!(avctx->active_thread_type & FF_THREAD_FRAME) && !context_count))
                    h->au_pps_id = -1;
                if ((err = ff_h264_decode_slice_header(h, sl)))
                    break;
                if (h->sei_recovery_frame_cnt >= 0) {
                    if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
                        h->valid_recovery_point = 1;
                    if (   h->recovery_frame < 0
                        || av_mod_uintp2(h->recovery_frame - h->frame_num, h->sps.log2_max_frame_num) > h->sei_recovery_frame_cnt) {
                        h->recovery_frame = av_mod_uintp2(h->frame_num + h->sei_recovery_frame_cnt, h->sps.log2_max_frame_num);
                        if (!h->valid_recovery_point)
                            h->recovery_frame = h->frame_num;
                h->cur_pic_ptr->f->key_frame |=
                    (h->nal_unit_type == NAL_IDR_SLICE);
                if (h->nal_unit_type == NAL_IDR_SLICE ||
                    h->recovery_frame == h->frame_num) {
                    h->recovery_frame         = -1;
                    h->cur_pic_ptr->recovered = 1;
                // If we have an IDR, all frames after it in decoded order are
                // "recovered".
                if (h->nal_unit_type == NAL_IDR_SLICE)
                    h->frame_recovered |= FRAME_RECOVERED_IDR;
#if 1
                h->cur_pic_ptr->recovered |= h->frame_recovered;
#else
                h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
#endif
                if (h->current_slice == 1) {
                    if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
                        decode_postinit(h, nal_index >= nals_needed);
                    if (h->avctx->hwaccel &&
                        (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
                        goto end;
#if FF_API_CAP_VDPAU
                    if (CONFIG_H264_VDPAU_DECODER &&
                        h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU)
                        ff_vdpau_h264_picture_start(h);
#endif
                if (sl->redundant_pic_count == 0) {
                    if (avctx->hwaccel) {
                        ret = avctx->hwaccel->decode_slice(avctx,
                                                           &buf[buf_index - consumed],
                                                           consumed);
                        if (ret < 0)
                            goto end;
#if FF_API_CAP_VDPAU
                    } else if (CONFIG_H264_VDPAU_DECODER &&
                               h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU) {
                        ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
                                                start_code,
                                                sizeof(start_code));
                        ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
                                                &buf[buf_index - consumed],
                                                consumed);
#endif
                        context_count++;
                break;
            case NAL_DPA:
            case NAL_DPB:
            case NAL_DPC:
                avpriv_request_sample(avctx, "data partitioning");
                break;
            case NAL_SEI:
                init_get_bits(&h->gb, ptr, bit_length);
                ret = ff_h264_decode_sei(h);
                if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
                    goto end;
                break;
            case NAL_SPS:
                init_get_bits(&h->gb, ptr, bit_length);
                if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
                    break;
                if (h->is_avc ? nalsize : 1) {
                    av_log(h->avctx, AV_LOG_DEBUG,
                           "SPS decoding failure, trying again with the complete NAL\n");
                    if (h->is_avc)
                        av_assert0(next_avc - buf_index + consumed == nalsize);
                    if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
                        break;
                    init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
                                  8*(next_avc - buf_index + consumed - 1));
                    if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
                        break;
                init_get_bits(&h->gb, ptr, bit_length);
                ff_h264_decode_seq_parameter_set(h, 1);
                break;
            case NAL_PPS:
                init_get_bits(&h->gb, ptr, bit_length);
                ret = ff_h264_decode_picture_parameter_set(h, bit_length);
                if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
                    goto end;
                break;
            case NAL_AUD:
            case NAL_END_SEQUENCE:
            case NAL_END_STREAM:
            case NAL_FILLER_DATA:
            case NAL_SPS_EXT:
            case NAL_AUXILIARY_SLICE:
                break;
            case NAL_FF_IGNORE:
                break;
            default:
                av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
                       h->nal_unit_type, bit_length);
            if (context_count == h->max_contexts) {
                ret = ff_h264_execute_decode_slices(h, context_count);
                if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
                    goto end;
                context_count = 0;
            if (err < 0 || err == SLICE_SKIPED) {
                if (err < 0)
                    av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
                sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
            } else if (err == SLICE_SINGLETHREAD) {
                if (context_count > 1) {
                    ret = ff_h264_execute_decode_slices(h, context_count - 1);
                    if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
                        goto end;
                    context_count = 0;
                /* Slice could not be decoded in parallel mode, restart. Note
                 * that rbsp_buffer is not transferred, but since we no longer
                 * run in parallel mode this should not be an issue. */
                sl               = &h->slice_ctx[0];
                goto again;
    if (context_count) {
        ret = ff_h264_execute_decode_slices(h, context_count);
        if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
            goto end;
    ret = 0;
end:
    /* clean up */
    if (h->cur_pic_ptr && !h->droppable) {
        ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
                                  h->picture_structure == PICT_BOTTOM_FIELD);
    return (ret < 0) ? ret : buf_index;


int spapr_h_cas_compose_response(sPAPRMachineState *spapr,

                                 target_ulong addr, target_ulong size,

                                 sPAPROptionVector *ov5_updates)

{

    void *fdt, *fdt_skel;

    sPAPRDeviceTreeUpdateHeader hdr = { .version_id = 1 };

    size -= sizeof(hdr);

    /* Create sceleton */

    fdt_skel = g_malloc0(size);

    _FDT((fdt_create(fdt_skel, size)));

    _FDT((fdt_begin_node(fdt_skel, "")));

    _FDT((fdt_end_node(fdt_skel)));

    _FDT((fdt_finish(fdt_skel)));

    fdt = g_malloc0(size);

    _FDT((fdt_open_into(fdt_skel, fdt, size)));

    g_free(fdt_skel);

    /* Fixup cpu nodes */

    _FDT((spapr_fixup_cpu_dt(fdt, spapr)));

    if (spapr_dt_cas_updates(spapr, fdt, ov5_updates)) {

        return -1;

    }

    /* Pack resulting tree */

    _FDT((fdt_pack(fdt)));

    if (fdt_totalsize(fdt) + sizeof(hdr) > size) {

        trace_spapr_cas_failed(size);

        return -1;

    }

    cpu_physical_memory_write(addr, &hdr, sizeof(hdr));

    cpu_physical_memory_write(addr + sizeof(hdr), fdt, fdt_totalsize(fdt));

    trace_spapr_cas_continue(fdt_totalsize(fdt) + sizeof(hdr));

    g_free(fdt);

    return 0;

}


static MatroskaLevel1Element *matroska_find_level1_elem(MatroskaDemuxContext *matroska,
                                                        uint32_t id)
{
    int i;
    MatroskaLevel1Element *elem;
    // Some files link to all clusters; useless.
    if (id == MATROSKA_ID_CLUSTER)
    // There can be multiple seekheads.
    if (id != MATROSKA_ID_SEEKHEAD) {
        for (i = 0; i < matroska->num_level1_elems; i++) {
            if (matroska->level1_elems[i].id == id)
                return &matroska->level1_elems[i];
        }
    }
    // Only a completely broken file would have more elements.
    // It also provides a low-effort way to escape from circular seekheads
    // (every iteration will add a level1 entry).
    if (matroska->num_level1_elems >= FF_ARRAY_ELEMS(matroska->level1_elems)) {
        av_log(matroska->ctx, AV_LOG_ERROR, "Too many level1 elements or circular seekheads.\n");
    }
    elem = &matroska->level1_elems[matroska->num_level1_elems++];
    *elem = (MatroskaLevel1Element){.id = id};
    return elem;
}


static int mp_dacl_removexattr(FsContext *ctx,

                               const char *path, const char *name)

{

    int ret;

    char *buffer;

    buffer = rpath(ctx, path);

    ret  = lremovexattr(buffer, MAP_ACL_DEFAULT);

    if (ret == -1 && errno == ENODATA) {

        /*

         * We don't get ENODATA error when trying to remove a

         * posix acl that is not present. So don't throw the error

         * even in case of mapped security model

         */

        errno = 0;

        ret = 0;

    }

    g_free(buffer);

    return ret;

}


static void IRQ_local_pipe(OpenPICState *opp, int n_CPU, int n_IRQ)

{

    IRQ_dst_t *dst;

    IRQ_src_t *src;

    int priority;

    dst = &opp->dst[n_CPU];

    src = &opp->src[n_IRQ];

    priority = IPVP_PRIORITY(src->ipvp);

    if (priority <= dst->pctp) {

        /* Too low priority */

        DPRINTF("%s: IRQ %d has too low priority on CPU %d\n",

                __func__, n_IRQ, n_CPU);

        return;

    }

    if (IRQ_testbit(&dst->raised, n_IRQ)) {

        /* Interrupt miss */

        DPRINTF("%s: IRQ %d was missed on CPU %d\n",

                __func__, n_IRQ, n_CPU);

        return;

    }

    src->ipvp |= IPVP_ACTIVITY_MASK;

    IRQ_setbit(&dst->raised, n_IRQ);

    if (priority < dst->raised.priority) {

        /* An higher priority IRQ is already raised */

        DPRINTF("%s: IRQ %d is hidden by raised IRQ %d on CPU %d\n",

                __func__, n_IRQ, dst->raised.next, n_CPU);

        return;

    }

    IRQ_get_next(opp, &dst->raised);

    if (IRQ_get_next(opp, &dst->servicing) != -1 &&

        priority <= dst->servicing.priority) {

        DPRINTF("%s: IRQ %d is hidden by servicing IRQ %d on CPU %d\n",

                __func__, n_IRQ, dst->servicing.next, n_CPU);

        /* Already servicing a higher priority IRQ */

        return;

    }

    DPRINTF("Raise OpenPIC INT output cpu %d irq %d\n", n_CPU, n_IRQ);

    openpic_irq_raise(opp, n_CPU, src);

}


static void process_incoming_migration_bh(void *opaque)
{
    Error *local_err = NULL;
    MigrationIncomingState *mis = opaque;
    /* Make sure all file formats flush their mutable metadata */
    bdrv_invalidate_cache_all(&local_err);
        migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
                          MIGRATION_STATUS_FAILED);
        error_report_err(local_err);
        migrate_decompress_threads_join();
        exit(EXIT_FAILURE);
    /*
     * This must happen after all error conditions are dealt with and
     * we're sure the VM is going to be running on this host.
     */
    qemu_announce_self();
    /* If global state section was not received or we are in running
       state, we need to obey autostart. Any other state is set with
       runstate_set. */
    if (!global_state_received() ||
        global_state_get_runstate() == RUN_STATE_RUNNING) {
        if (autostart) {
            vm_start();
        } else {
            runstate_set(RUN_STATE_PAUSED);
    } else {
        runstate_set(global_state_get_runstate());
    migrate_decompress_threads_join();
    /*
     * This must happen after any state changes since as soon as an external
     * observer sees this event they might start to prod at the VM assuming
     * it's ready to use.
     */
    migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
                      MIGRATION_STATUS_COMPLETED);
    qemu_bh_delete(mis->bh);
    migration_incoming_state_destroy();


static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)

{

    if (s->state & PNG_IDAT) {

        av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");

        return AVERROR_INVALIDDATA;

    }

    avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);

    avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);

    if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)

        avctx->sample_aspect_ratio = (AVRational){ 0, 1 };

    bytestream2_skip(&s->gb, 1); /* unit specifier */

    bytestream2_skip(&s->gb, 4); /* crc */

    return 0;

}


static int xio3130_downstream_initfn(PCIDevice *d)

{

    PCIEPort *p = PCIE_PORT(d);

    PCIESlot *s = PCIE_SLOT(d);

    int rc;

    pci_bridge_initfn(d, TYPE_PCIE_BUS);

    pcie_port_init_reg(d);

    rc = msi_init(d, XIO3130_MSI_OFFSET, XIO3130_MSI_NR_VECTOR,

                  XIO3130_MSI_SUPPORTED_FLAGS & PCI_MSI_FLAGS_64BIT,

                  XIO3130_MSI_SUPPORTED_FLAGS & PCI_MSI_FLAGS_MASKBIT);

    if (rc < 0) {

        goto err_bridge;

    }

    rc = pci_bridge_ssvid_init(d, XIO3130_SSVID_OFFSET,

                               XIO3130_SSVID_SVID, XIO3130_SSVID_SSID);

    if (rc < 0) {

        goto err_bridge;

    }

    rc = pcie_cap_init(d, XIO3130_EXP_OFFSET, PCI_EXP_TYPE_DOWNSTREAM,

                       p->port);

    if (rc < 0) {

        goto err_msi;

    }

    pcie_cap_flr_init(d);

    pcie_cap_deverr_init(d);

    pcie_cap_slot_init(d, s->slot);

    pcie_cap_arifwd_init(d);

    pcie_chassis_create(s->chassis);

    rc = pcie_chassis_add_slot(s);

    if (rc < 0) {

        goto err_pcie_cap;

    }

    rc = pcie_aer_init(d, XIO3130_AER_OFFSET, PCI_ERR_SIZEOF);

    if (rc < 0) {

        goto err;

    }

    return 0;

err:

    pcie_chassis_del_slot(s);

err_pcie_cap:

    pcie_cap_exit(d);

err_msi:

    msi_uninit(d);

err_bridge:

    pci_bridge_exitfn(d);

    return rc;

}


static av_cold int hevc_decode_free(AVCodecContext *avctx)

{

    HEVCContext       *s = avctx->priv_data;

    HEVCLocalContext *lc = s->HEVClc;

    int i;

    pic_arrays_free(s);

    av_freep(&s->md5_ctx);

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

        av_freep(&s->skipped_bytes_pos_nal[i]);

    }

    av_freep(&s->skipped_bytes_pos_size_nal);

    av_freep(&s->skipped_bytes_nal);

    av_freep(&s->skipped_bytes_pos_nal);

    av_freep(&s->cabac_state);

    av_frame_free(&s->tmp_frame);

    av_frame_free(&s->output_frame);

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

        ff_hevc_unref_frame(s, &s->DPB[i], ~0);

        av_frame_free(&s->DPB[i].frame);

    }

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

        av_buffer_unref(&s->vps_list[i]);

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

        av_buffer_unref(&s->sps_list[i]);

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

        av_buffer_unref(&s->pps_list[i]);

    s->sps = NULL;

    s->pps = NULL;

    s->vps = NULL;

    av_buffer_unref(&s->current_sps);

    av_freep(&s->sh.entry_point_offset);

    av_freep(&s->sh.offset);

    av_freep(&s->sh.size);

    for (i = 1; i < s->threads_number; i++) {

        lc = s->HEVClcList[i];

        if (lc) {

            av_freep(&s->HEVClcList[i]);

            av_freep(&s->sList[i]);

        }

    }

    if (s->HEVClc == s->HEVClcList[0])

        s->HEVClc = NULL;

    av_freep(&s->HEVClcList[0]);

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

        av_freep(&s->nals[i].rbsp_buffer);

    av_freep(&s->nals);

    s->nals_allocated = 0;

    return 0;

}


static av_cold int dct_init(MpegEncContext *s)

{

    ff_blockdsp_init(&s->bdsp, s->avctx);

    ff_hpeldsp_init(&s->hdsp, s->avctx->flags);

    ff_me_cmp_init(&s->mecc, s->avctx);

    ff_mpegvideodsp_init(&s->mdsp);

    ff_videodsp_init(&s->vdsp, s->avctx->bits_per_raw_sample);

    s->dct_unquantize_h263_intra = dct_unquantize_h263_intra_c;

    s->dct_unquantize_h263_inter = dct_unquantize_h263_inter_c;

    s->dct_unquantize_mpeg1_intra = dct_unquantize_mpeg1_intra_c;

    s->dct_unquantize_mpeg1_inter = dct_unquantize_mpeg1_inter_c;

    s->dct_unquantize_mpeg2_intra = dct_unquantize_mpeg2_intra_c;

    if (s->flags & CODEC_FLAG_BITEXACT)

        s->dct_unquantize_mpeg2_intra = dct_unquantize_mpeg2_intra_bitexact;

    s->dct_unquantize_mpeg2_inter = dct_unquantize_mpeg2_inter_c;

    if (HAVE_INTRINSICS_NEON)

        ff_mpv_common_init_neon(s);

    if (ARCH_ARM)

        ff_mpv_common_init_arm(s);

    if (ARCH_PPC)

        ff_mpv_common_init_ppc(s);

    if (ARCH_X86)

        ff_mpv_common_init_x86(s);

    return 0;

}


static void filter_mb_edgeh( H264Context *h, uint8_t *pix, int stride, int bS[4], int qp ) {

    int i, d;

    const int index_a = clip( qp + h->slice_alpha_c0_offset, 0, 51 );

    const int alpha = alpha_table[index_a];

    const int beta  = beta_table[clip( qp + h->slice_beta_offset, 0, 51 )];

    const int pix_next  = stride;

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

        if( bS[i] == 0 ) {

            pix += 4;

            continue;

        }

        /* 4px edge length */

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

            const uint8_t p0 = pix[-1*pix_next];

            const uint8_t p1 = pix[-2*pix_next];

            const uint8_t p2 = pix[-3*pix_next];

            const uint8_t q0 = pix[0];

            const uint8_t q1 = pix[1*pix_next];

            const uint8_t q2 = pix[2*pix_next];

            if( abs( p0 - q0 ) >= alpha ||

                abs( p1 - p0 ) >= beta ||

                abs( q1 - q0 ) >= beta ) {

                pix++;

                continue;

            }

            if( bS[i] < 4 ) {

                const int tc0 = tc0_table[index_a][bS[i] - 1];

                int tc = tc0;

                int i_delta;

                if( abs( p2 - p0 ) < beta ) {

                    pix[-2*pix_next] = p1 + clip( ( p2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( p1 << 1 ) ) >> 1, -tc0, tc0 );

                    tc++;

                }

                if( abs( q2 - q0 ) < beta ) {

                    pix[pix_next] = q1 + clip( ( q2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( q1 << 1 ) ) >> 1, -tc0, tc0 );

                    tc++;

                }

                i_delta = clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );

                pix[-pix_next] = clip( p0 + i_delta, 0, 255 );    /* p0' */

                pix[0]         = clip( q0 - i_delta, 0, 255 );    /* q0' */

            }

            else

            {

                const uint8_t p3 = pix[-4*pix_next];

                const uint8_t q3 = pix[ 3*pix_next];

                const int c  = abs( p0 - q0 ) < (( alpha >> 2 ) + 2 );

                if( abs( p2 - p0 ) < beta && c ) {

                    /* p0', p1', p2' */

                    pix[-1*pix_next] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;

                    pix[-2*pix_next] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;

                    pix[-3*pix_next] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;

                } else {

                    /* p0' */

                    pix[-1*pix_next] = ( 2*p1 + p0 + q1 + 2 ) >> 2;

                }

                if( abs( q2 - q0 ) < beta && c ) {

                    /* q0', q1', q2' */

                    pix[0*pix_next] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;

                    pix[1*pix_next] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;

                    pix[2*pix_next] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;

                } else {

                    /* q0' */

                    pix[0*pix_next] = ( 2*q1 + q0 + p1 + 2 ) >> 2;

                }

            }

            pix++;

        }

    }

}


static void aflat(WaveformContext *s, AVFrame *in, AVFrame *out,

                  int component, int intensity, int offset, int column)

{

    const int plane = s->desc->comp[component].plane;

    const int mirror = s->mirror;

    const int c0_linesize = in->linesize[ plane + 0 ];

    const int c1_linesize = in->linesize[(plane + 1) % s->ncomp];

    const int c2_linesize = in->linesize[(plane + 2) % s->ncomp];

    const int d0_linesize = out->linesize[ plane + 0 ];

    const int d1_linesize = out->linesize[(plane + 1) % s->ncomp];

    const int d2_linesize = out->linesize[(plane + 2) % s->ncomp];

    const int max = 255 - intensity;

    const int src_h = in->height;

    const int src_w = in->width;

    int x, y;

    if (column) {

        const int d0_signed_linesize = d0_linesize * (mirror == 1 ? -1 : 1);

        const int d1_signed_linesize = d1_linesize * (mirror == 1 ? -1 : 1);

        const int d2_signed_linesize = d2_linesize * (mirror == 1 ? -1 : 1);

        for (x = 0; x < src_w; x++) {

            const uint8_t *c0_data = in->data[plane + 0];

            const uint8_t *c1_data = in->data[(plane + 1) % s->ncomp];

            const uint8_t *c2_data = in->data[(plane + 2) % s->ncomp];

            uint8_t *d0_data = out->data[plane] + offset * d0_linesize;

            uint8_t *d1_data = out->data[(plane + 1) % s->ncomp] + offset * d1_linesize;

            uint8_t *d2_data = out->data[(plane + 2) % s->ncomp] + offset * d2_linesize;

            uint8_t * const d0_bottom_line = d0_data + d0_linesize * (s->size - 1);

            uint8_t * const d0 = (mirror ? d0_bottom_line : d0_data);

            uint8_t * const d1_bottom_line = d1_data + d1_linesize * (s->size - 1);

            uint8_t * const d1 = (mirror ? d1_bottom_line : d1_data);

            uint8_t * const d2_bottom_line = d2_data + d2_linesize * (s->size - 1);

            uint8_t * const d2 = (mirror ? d2_bottom_line : d2_data);

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

                const int c0 = c0_data[x] + 128;

                const int c1 = c1_data[x] - 128;

                const int c2 = c2_data[x] - 128;

                uint8_t *target;

                int p;

                target = d0 + x + d0_signed_linesize * c0;

                update(target, max, intensity);

                for (p = c0 + c1; p < c0; p++) {

                    target = d1 + x + d1_signed_linesize * p;

                    update(target, max, 1);

                }

                for (p = c0 + c1 - 1; p > c0; p--) {

                    target = d1 + x + d1_signed_linesize * p;

                    update(target, max, 1);

                }

                for (p = c0 + c2; p < c0; p++) {

                    target = d2 + x + d2_signed_linesize * p;

                    update(target, max, 1);

                }

                for (p = c0 + c2 - 1; p > c0; p--) {

                    target = d2 + x + d2_signed_linesize * p;

                    update(target, max, 1);

                }

                c0_data += c0_linesize;

                c1_data += c1_linesize;

                c2_data += c2_linesize;

                d0_data += d0_linesize;

                d1_data += d1_linesize;

                d2_data += d2_linesize;

            }

        }

    } else {

        const uint8_t *c0_data = in->data[plane];

        const uint8_t *c1_data = in->data[(plane + 1) % s->ncomp];

        const uint8_t *c2_data = in->data[(plane + 2) % s->ncomp];

        uint8_t *d0_data = out->data[plane] + offset;

        uint8_t *d1_data = out->data[(plane + 1) % s->ncomp] + offset;

        uint8_t *d2_data = out->data[(plane + 2) % s->ncomp] + offset;

        if (mirror) {

            d0_data += s->size - 1;

            d1_data += s->size - 1;

            d2_data += s->size - 1;

        }

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

            for (x = 0; x < src_w; x++) {

                const int c0 = c0_data[x] + 128;

                const int c1 = c1_data[x] - 128;

                const int c2 = c2_data[x] - 128;

                uint8_t *target;

                int p;

                if (mirror)

                    target = d0_data - c0;

                else

                    target = d0_data + c0;

                update(target, max, intensity);

                for (p = c0 + c1; p < c0; p++) {

                    if (mirror)

                        target = d1_data - p;

                    else

                        target = d1_data + p;

                    update(target, max, 1);

                }

                for (p = c0 + 1; p < c0 + c1; p++) {

                    if (mirror)

                        target = d1_data - p;

                    else

                        target = d1_data + p;

                    update(target, max, 1);

                }

                for (p = c0 + c2; p < c0; p++) {

                    if (mirror)

                        target = d2_data - p;

                    else

                        target = d2_data + p;

                    update(target, max, 1);

                }

                for (p = c0 + 1; p < c0 + c2; p++) {

                    if (mirror)

                        target = d2_data - p;

                    else

                        target = d2_data + p;

                    update(target, max, 1);

                }

            }

            c0_data += c0_linesize;

            c1_data += c1_linesize;

            c2_data += c2_linesize;

            d0_data += d0_linesize;

            d1_data += d1_linesize;

            d2_data += d2_linesize;

        }

    }

    envelope(s, out, plane, (plane + 0) % s->ncomp);

    envelope(s, out, plane, (plane + 1) % s->ncomp);

    envelope(s, out, plane, (plane + 2) % s->ncomp);

}


int ff_dirac_golomb_read_32bit(DiracGolombLUT *lut_ctx, const uint8_t *buf,

                               int bytes, uint8_t *_dst, int coeffs)

{

    int i, b, c_idx = 0;

    int32_t *dst = (int32_t *)_dst;

    DiracGolombLUT *future[4], *l = &lut_ctx[2*LUT_SIZE + buf[0]];

    INIT_RESIDUE(res);

    for (b = 1; b <= bytes; b++) {

        future[0] = &lut_ctx[buf[b]];

        future[1] = future[0] + 1*LUT_SIZE;

        future[2] = future[0] + 2*LUT_SIZE;

        future[3] = future[0] + 3*LUT_SIZE;

        if ((c_idx + 1) > coeffs)

            return c_idx;

        /* res_bits is a hint for better branch prediction */

        if (res_bits && l->sign) {

            int32_t coeff = 1;

            APPEND_RESIDUE(res, l->preamble);

            for (i = 0; i < (res_bits >> 1) - 1; i++) {

                coeff <<= 1;

                coeff |= (res >> (RSIZE_BITS - 2*i - 2)) & 1;

            }

            dst[c_idx++] = l->sign * (coeff - 1);

            SET_RESIDUE(res, 0, 0);

        }

        memcpy(&dst[c_idx], l->ready, LUT_BITS*sizeof(int32_t));

        c_idx += l->ready_num;

        APPEND_RESIDUE(res, l->leftover);

        l = future[l->need_s ? 3 : !res_bits ? 2 : res_bits & 1];

    }

    return c_idx;

}


static int decode_i_frame(FourXContext *f, const uint8_t *buf, int length){

    int x, y;

    const int width= f->avctx->width;

    const int height= f->avctx->height;

    uint16_t *dst= (uint16_t*)f->current_picture.data[0];

    const int stride= f->current_picture.linesize[0]>>1;

    const unsigned int bitstream_size= AV_RL32(buf);

    const int token_count av_unused = AV_RL32(buf + bitstream_size + 8);

    unsigned int prestream_size= 4*AV_RL32(buf + bitstream_size + 4);

    const uint8_t *prestream= buf + bitstream_size + 12;

    if(prestream_size + bitstream_size + 12 != length

       || bitstream_size > (1<<26)

       || prestream_size > (1<<26)){

        av_log(f->avctx, AV_LOG_ERROR, "size mismatch %d %d %d\n", prestream_size, bitstream_size, length);

        return -1;

    }

    prestream= read_huffman_tables(f, prestream);

    init_get_bits(&f->gb, buf + 4, 8*bitstream_size);

    prestream_size= length + buf - prestream;

    av_fast_malloc(&f->bitstream_buffer, &f->bitstream_buffer_size, prestream_size + FF_INPUT_BUFFER_PADDING_SIZE);

    if (!f->bitstream_buffer)

        return AVERROR(ENOMEM);

    f->dsp.bswap_buf(f->bitstream_buffer, (const uint32_t*)prestream, prestream_size/4);

    memset((uint8_t*)f->bitstream_buffer + prestream_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);

    init_get_bits(&f->pre_gb, f->bitstream_buffer, 8*prestream_size);

    f->last_dc= 0*128*8*8;

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

        for(x=0; x<width; x+=16){

            if(decode_i_mb(f) < 0)

                return -1;

            idct_put(f, x, y);

        }

        dst += 16*stride;

    }

    if(get_vlc2(&f->pre_gb, f->pre_vlc.table, ACDC_VLC_BITS, 3) != 256)

        av_log(f->avctx, AV_LOG_ERROR, "end mismatch\n");

    return 0;

}


static int pci_pcnet_init(PCIDevice *pci_dev)

{

    PCIPCNetState *d = PCI_PCNET(pci_dev);

    PCNetState *s = &d->state;

    uint8_t *pci_conf;

#if 0

    printf("sizeof(RMD)=%d, sizeof(TMD)=%d\n",

        sizeof(struct pcnet_RMD), sizeof(struct pcnet_TMD));

#endif

    pci_conf = pci_dev->config;

    pci_set_word(pci_conf + PCI_STATUS,

                 PCI_STATUS_FAST_BACK | PCI_STATUS_DEVSEL_MEDIUM);

    pci_set_word(pci_conf + PCI_SUBSYSTEM_VENDOR_ID, 0x0);

    pci_set_word(pci_conf + PCI_SUBSYSTEM_ID, 0x0);

    pci_conf[PCI_INTERRUPT_PIN] = 1; /* interrupt pin A */

    pci_conf[PCI_MIN_GNT] = 0x06;

    pci_conf[PCI_MAX_LAT] = 0xff;

    /* Handler for memory-mapped I/O */

    memory_region_init_io(&d->state.mmio, OBJECT(d), &pcnet_mmio_ops, s,

                          "pcnet-mmio", PCNET_PNPMMIO_SIZE);

    memory_region_init_io(&d->io_bar, OBJECT(d), &pcnet_io_ops, s, "pcnet-io",

                          PCNET_IOPORT_SIZE);

    pci_register_bar(pci_dev, 0, PCI_BASE_ADDRESS_SPACE_IO, &d->io_bar);

    pci_register_bar(pci_dev, 1, 0, &s->mmio);

    s->irq = pci_allocate_irq(pci_dev);

    s->phys_mem_read = pci_physical_memory_read;

    s->phys_mem_write = pci_physical_memory_write;

    s->dma_opaque = pci_dev;

    return pcnet_common_init(DEVICE(pci_dev), s, &net_pci_pcnet_info);

}


void OPPROTO op_fdiv_STN_ST0(void)

{

    ST(PARAM1) /= ST0;

}


static int open_file(AVFormatContext *avf, unsigned fileno)

{

    ConcatContext *cat = avf->priv_data;

    ConcatFile *file = &cat->files[fileno];

    int ret;

    if (cat->avf)

        avformat_close_input(&cat->avf);

    cat->avf = avformat_alloc_context();

    if (!cat->avf)

        return AVERROR(ENOMEM);

    cat->avf->flags |= avf->flags;

    cat->avf->interrupt_callback = avf->interrupt_callback;

    if ((ret = ff_copy_whiteblacklists(cat->avf, avf)) < 0)

        return ret;

    if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||

        (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {

        av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);

        avformat_close_input(&cat->avf);

        return ret;

    }

    cat->cur_file = file;

    if (file->start_time == AV_NOPTS_VALUE)

        file->start_time = !fileno ? 0 :

                           cat->files[fileno - 1].start_time +

                           cat->files[fileno - 1].duration;

    file->file_start_time = (cat->avf->start_time == AV_NOPTS_VALUE) ? 0 : cat->avf->start_time;

    file->file_inpoint = (file->inpoint == AV_NOPTS_VALUE) ? file->file_start_time : file->inpoint;

    if (file->duration == AV_NOPTS_VALUE && file->outpoint != AV_NOPTS_VALUE)

        file->duration = file->outpoint - file->file_inpoint;

    if (cat->segment_time_metadata) {

        av_dict_set_int(&file->metadata, "lavf.concatdec.start_time", file->start_time, 0);

        if (file->duration != AV_NOPTS_VALUE)

            av_dict_set_int(&file->metadata, "lavf.concatdec.duration", file->duration, 0);

    }

    if ((ret = match_streams(avf)) < 0)

        return ret;

    if (file->inpoint != AV_NOPTS_VALUE) {

       if ((ret = avformat_seek_file(cat->avf, -1, INT64_MIN, file->inpoint, file->inpoint, 0)) < 0)

           return ret;

    }

    return 0;

}


BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)

{

    BdrvDirtyBitmap *bm;

    BlockDirtyInfoList *list = NULL;

    BlockDirtyInfoList **plist = &list;

    QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {

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

        BlockDirtyInfoList *entry = g_malloc0(sizeof(BlockDirtyInfoList));

        info->count = bdrv_get_dirty_count(bs, bm);

        info->granularity =

            ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap));

        entry->value = info;

        *plist = entry;

        plist = &entry->next;

    }

    return list;

}


void register_displaychangelistener(DisplayChangeListener *dcl)

{

    QemuConsole *con;

    trace_displaychangelistener_register(dcl, dcl->ops->dpy_name);

    dcl->ds = get_alloc_displaystate();

    QLIST_INSERT_HEAD(&dcl->ds->listeners, dcl, next);

    gui_setup_refresh(dcl->ds);

    if (dcl->con) {

        dcl->con->dcls++;

        con = dcl->con;

    } else {

        con = active_console;

    }

    if (dcl->ops->dpy_gfx_switch && con) {

        dcl->ops->dpy_gfx_switch(dcl, con->surface);

    }

}


static void cpu_ioreq_move(ioreq_t *req)

{

    int i, sign;

    sign = req->df ? -1 : 1;

    if (!req->data_is_ptr) {

        if (req->dir == IOREQ_READ) {

            for (i = 0; i < req->count; i++) {

                cpu_physical_memory_read(

                        req->addr + (sign * i * (int64_t)req->size),

                        (uint8_t *) &req->data, req->size);

            }

        } else if (req->dir == IOREQ_WRITE) {

            for (i = 0; i < req->count; i++) {

                cpu_physical_memory_write(

                        req->addr + (sign * i * (int64_t)req->size),

                        (uint8_t *) &req->data, req->size);

            }

        }

    } else {

        uint64_t tmp;

        if (req->dir == IOREQ_READ) {

            for (i = 0; i < req->count; i++) {

                cpu_physical_memory_read(

                        req->addr + (sign * i * (int64_t)req->size),

                        (uint8_t*) &tmp, req->size);

                cpu_physical_memory_write(

                        req->data + (sign * i * (int64_t)req->size),

                        (uint8_t*) &tmp, req->size);

            }

        } else if (req->dir == IOREQ_WRITE) {

            for (i = 0; i < req->count; i++) {

                cpu_physical_memory_read(

                        req->data + (sign * i * (int64_t)req->size),

                        (uint8_t*) &tmp, req->size);

                cpu_physical_memory_write(

                        req->addr + (sign * i * (int64_t)req->size),

                        (uint8_t*) &tmp, req->size);

            }

        }

    }

}


static void imc_get_coeffs(AVCodecContext *avctx,

                           IMCContext *q, IMCChannel *chctx)

{

    int i, j, cw_len, cw;

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

        if (!chctx->sumLenArr[i])

            continue;

        if (chctx->bandFlagsBuf[i] || chctx->bandWidthT[i]) {

            for (j = band_tab[i]; j < band_tab[i + 1]; j++) {

                cw_len = chctx->CWlengthT[j];

                cw = 0;

                if (get_bits_count(&q->gb) + cw_len > 512) {

                    av_log(avctx, AV_LOG_WARNING,

                           "Potential problem on band %i, coefficient %i"

                           ": cw_len=%i\n", i, j, cw_len);

                }

                if (cw_len && (!chctx->bandFlagsBuf[i] || !chctx->skipFlags[j]))

                    cw = get_bits(&q->gb, cw_len);

                chctx->codewords[j] = cw;

            }

        }

    }

}


void ff_generate_sliding_window_mmcos(H264Context *h, int first_slice)

{

    MpegEncContext * const s = &h->s;

    MMCO mmco_temp[MAX_MMCO_COUNT], *mmco = first_slice ? h->mmco : mmco_temp;

    int mmco_index = 0, i;

    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->f.reference)) {

        mmco[0].opcode = MMCO_SHORT2UNUSED;

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

        mmco_index = 1;

        if (FIELD_PICTURE) {

            mmco[0].short_pic_num *= 2;

            mmco[1].opcode = MMCO_SHORT2UNUSED;

            mmco[1].short_pic_num = mmco[0].short_pic_num + 1;

            mmco_index = 2;

        }

    }

    if (first_slice) {

        h->mmco_index = mmco_index;

    } else if (!first_slice && mmco_index >= 0 &&

               (mmco_index != h->mmco_index ||

                (i = check_opcodes(h->mmco, mmco_temp, mmco_index)))) {

        av_log(h->s.avctx, AV_LOG_ERROR,

               "Inconsistent MMCO state between slices [%d, %d, %d]\n",

               mmco_index, h->mmco_index, i);

        return AVERROR_INVALIDDATA;

    }

}


void virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)

{

    uint32_t type;

    struct iovec *in_iov = req->elem->in_sg;

    struct iovec *iov = req->elem->out_sg;

    unsigned in_num = req->elem->in_num;

    unsigned out_num = req->elem->out_num;

    if (req->elem->out_num < 1 || req->elem->in_num < 1) {

        error_report("virtio-blk missing headers");

        exit(1);

    }

    if (unlikely(iov_to_buf(iov, out_num, 0, &req->out,

                            sizeof(req->out)) != sizeof(req->out))) {

        error_report("virtio-blk request outhdr too short");

        exit(1);

    }

    iov_discard_front(&iov, &out_num, sizeof(req->out));

    if (in_num < 1 ||

        in_iov[in_num - 1].iov_len < sizeof(struct virtio_blk_inhdr)) {

        error_report("virtio-blk request inhdr too short");

        exit(1);

    }

    req->in = (void *)in_iov[in_num - 1].iov_base

              + in_iov[in_num - 1].iov_len

              - sizeof(struct virtio_blk_inhdr);

    iov_discard_back(in_iov, &in_num, sizeof(struct virtio_blk_inhdr));

    type = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type);

    if (type & VIRTIO_BLK_T_FLUSH) {

        virtio_blk_handle_flush(req, mrb);

    } else if (type & VIRTIO_BLK_T_SCSI_CMD) {

        virtio_blk_handle_scsi(req);

    } else if (type & VIRTIO_BLK_T_GET_ID) {

        VirtIOBlock *s = req->dev;

        /*

         * NB: per existing s/n string convention the string is

         * terminated by '\0' only when shorter than buffer.

         */

        strncpy(req->elem->in_sg[0].iov_base,

                s->blk.serial ? s->blk.serial : "",

                MIN(req->elem->in_sg[0].iov_len, VIRTIO_BLK_ID_BYTES));

        virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);

        virtio_blk_free_request(req);

    } else if (type & VIRTIO_BLK_T_OUT) {

        qemu_iovec_init_external(&req->qiov, &req->elem->out_sg[1],

                                 req->elem->out_num - 1);

        virtio_blk_handle_write(req, mrb);

    } else if (type == VIRTIO_BLK_T_IN || type == VIRTIO_BLK_T_BARRIER) {

        /* VIRTIO_BLK_T_IN is 0, so we can't just & it. */

        qemu_iovec_init_external(&req->qiov, &req->elem->in_sg[0],

                                 req->elem->in_num - 1);

        virtio_blk_handle_read(req);

    } else {

        virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);

        virtio_blk_free_request(req);

    }

}


static void spapr_machine_class_init(ObjectClass *oc, void *data)

{

    MachineClass *mc = MACHINE_CLASS(oc);

    sPAPRMachineClass *smc = SPAPR_MACHINE_CLASS(oc);

    FWPathProviderClass *fwc = FW_PATH_PROVIDER_CLASS(oc);

    NMIClass *nc = NMI_CLASS(oc);

    HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc);

    mc->desc = "pSeries Logical Partition (PAPR compliant)";

    /*

     * We set up the default / latest behaviour here.  The class_init

     * functions for the specific versioned machine types can override

     * these details for backwards compatibility

     */

    mc->init = ppc_spapr_init;

    mc->reset = ppc_spapr_reset;

    mc->block_default_type = IF_SCSI;

    mc->max_cpus = MAX_CPUMASK_BITS;

    mc->no_parallel = 1;

    mc->default_boot_order = "";

    mc->default_ram_size = 512 * M_BYTE;

    mc->kvm_type = spapr_kvm_type;

    mc->has_dynamic_sysbus = true;

    mc->pci_allow_0_address = true;

    mc->get_hotplug_handler = spapr_get_hotpug_handler;

    hc->pre_plug = spapr_machine_device_pre_plug;

    hc->plug = spapr_machine_device_plug;

    hc->unplug = spapr_machine_device_unplug;

    mc->cpu_index_to_socket_id = spapr_cpu_index_to_socket_id;

    mc->query_hotpluggable_cpus = spapr_query_hotpluggable_cpus;

    smc->dr_lmb_enabled = true;

    smc->dr_cpu_enabled = true;

    fwc->get_dev_path = spapr_get_fw_dev_path;

    nc->nmi_monitor_handler = spapr_nmi;

}


static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)

{

    int ret;

    memset(s, 0, sizeof(*s));

    s->f = f;

    ret = inflateInit(&s->zstream);

    if (ret != Z_OK)

        return -1;

    return 0;

}


static int virtio_scsi_vring_init(VirtIOSCSI *s, VirtQueue *vq, int n)

{

    BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(s)));

    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);

    int rc;

    /* Set up virtqueue notify */

    rc = k->set_host_notifier(qbus->parent, n, true);

    if (rc != 0) {

        fprintf(stderr, "virtio-scsi: Failed to set host notifier (%d)\n",

                rc);

        s->dataplane_fenced = true;

        return rc;

    }

    virtio_queue_aio_set_host_notifier_handler(vq, s->ctx, true, true);

    return 0;

}


void qemu_get_guest_memory_mapping(MemoryMappingList *list, Error **errp)

{

    CPUState *cpu, *first_paging_enabled_cpu;

    RAMBlock *block;

    ram_addr_t offset, length;

    first_paging_enabled_cpu = find_paging_enabled_cpu(first_cpu);

    if (first_paging_enabled_cpu) {

        for (cpu = first_paging_enabled_cpu; cpu != NULL; cpu = cpu->next_cpu) {

            Error *err = NULL;

            cpu_get_memory_mapping(cpu, list, &err);

            if (err) {

                error_propagate(errp, err);

                return;

            }

        }

        return;

    }

    /*

     * If the guest doesn't use paging, the virtual address is equal to physical

     * address.

     */

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

        offset = block->offset;

        length = block->length;

        create_new_memory_mapping(list, offset, offset, length);

    }

}


static inline void RENAME(rgb24tobgr32)(const uint8_t *src, uint8_t *dst, int src_size)

{

    uint8_t *dest = dst;

    const uint8_t *s = src;

    const uint8_t *end;

    const uint8_t *mm_end;

    end = s + src_size;

    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");

    mm_end = end - 23;

    __asm__ volatile("movq        %0, %%mm7"::"m"(mask32a):"memory");

    while (s < mm_end) {

        __asm__ volatile(

            PREFETCH"    32%1           \n\t"

            "movd          %1, %%mm0    \n\t"

            "punpckldq    3%1, %%mm0    \n\t"

            "movd         6%1, %%mm1    \n\t"

            "punpckldq    9%1, %%mm1    \n\t"

            "movd        12%1, %%mm2    \n\t"

            "punpckldq   15%1, %%mm2    \n\t"

            "movd        18%1, %%mm3    \n\t"

            "punpckldq   21%1, %%mm3    \n\t"

            "por        %%mm7, %%mm0    \n\t"

            "por        %%mm7, %%mm1    \n\t"

            "por        %%mm7, %%mm2    \n\t"

            "por        %%mm7, %%mm3    \n\t"

            MOVNTQ"     %%mm0,   %0     \n\t"

            MOVNTQ"     %%mm1,  8%0     \n\t"

            MOVNTQ"     %%mm2, 16%0     \n\t"

            MOVNTQ"     %%mm3, 24%0"

            :"=m"(*dest)

            :"m"(*s)

            :"memory");

        dest += 32;

        s += 24;

    }

    __asm__ volatile(SFENCE:::"memory");

    __asm__ volatile(EMMS:::"memory");

    while (s < end) {

        *dest++ = *s++;

        *dest++ = *s++;

        *dest++ = *s++;

        *dest++ = 255;

    }

}


int bdrv_open2(BlockDriverState *bs, const char *filename, int flags,
               BlockDriver *drv)
{
    int ret, open_flags;
    char tmp_filename[PATH_MAX];
    char backing_filename[PATH_MAX];
    bs->read_only = 0;
    bs->is_temporary = 0;
    bs->encrypted = 0;
    if (flags & BDRV_O_SNAPSHOT) {
        BlockDriverState *bs1;
        int64_t total_size;
        /* if snapshot, we create a temporary backing file and open it
           instead of opening 'filename' directly */
        /* if there is a backing file, use it */
        bs1 = bdrv_new("");
        if (!bs1) {
            return -ENOMEM;
        }
        if (bdrv_open(bs1, filename, 0) < 0) {
            bdrv_delete(bs1);
            return -1;
        }
        total_size = bdrv_getlength(bs1) >> SECTOR_BITS;
        bdrv_delete(bs1);
        get_tmp_filename(tmp_filename, sizeof(tmp_filename));
        realpath(filename, backing_filename);
        if (bdrv_create(&bdrv_qcow2, tmp_filename,
                        total_size, backing_filename, 0) < 0) {
            return -1;
        }
        filename = tmp_filename;
        bs->is_temporary = 1;
    }
    pstrcpy(bs->filename, sizeof(bs->filename), filename);
    if (flags & BDRV_O_FILE) {
        drv = find_protocol(filename);
        if (!drv)
            return -ENOENT;
    } else {
        if (!drv) {
            drv = find_image_format(filename);
            if (!drv)
                return -1;
        }
    }
    bs->drv = drv;
    bs->opaque = qemu_mallocz(drv->instance_size);
    bs->total_sectors = 0; /* driver will set if it does not do getlength */
    if (bs->opaque == NULL && drv->instance_size > 0)
        return -1;
    /* Note: for compatibility, we open disk image files as RDWR, and
       RDONLY as fallback */
    if (!(flags & BDRV_O_FILE))
        open_flags = BDRV_O_RDWR | (flags & BDRV_O_DIRECT);
    else
        open_flags = flags & ~(BDRV_O_FILE | BDRV_O_SNAPSHOT);
    ret = drv->bdrv_open(bs, filename, open_flags);
    if (ret == -EACCES && !(flags & BDRV_O_FILE)) {
        ret = drv->bdrv_open(bs, filename, BDRV_O_RDONLY);
        bs->read_only = 1;
    }
    if (ret < 0) {
        qemu_free(bs->opaque);
        bs->opaque = NULL;
        bs->drv = NULL;
        return ret;
    }
    if (drv->bdrv_getlength) {
        bs->total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
    }
#ifndef _WIN32
    if (bs->is_temporary) {
        unlink(filename);
    }
#endif
    if (bs->backing_file[0] != '\0') {
        /* if there is a backing file, use it */
        bs->backing_hd = bdrv_new("");
        if (!bs->backing_hd) {
        fail:
            bdrv_close(bs);
            return -ENOMEM;
        }
        path_combine(backing_filename, sizeof(backing_filename),
                     filename, bs->backing_file);
        if (bdrv_open(bs->backing_hd, backing_filename, 0) < 0)
            goto fail;
    }
    /* call the change callback */
    bs->media_changed = 1;
    if (bs->change_cb)
        bs->change_cb(bs->change_opaque);
    return 0;
}