static void qemu_tcg_init_vcpu(CPUState *cpu)

{

    char thread_name[VCPU_THREAD_NAME_SIZE];

    static QemuCond *tcg_halt_cond;

    static QemuThread *tcg_cpu_thread;

    tcg_cpu_address_space_init(cpu, cpu->as);

    /* share a single thread for all cpus with TCG */

    if (!tcg_cpu_thread) {

        cpu->thread = g_malloc0(sizeof(QemuThread));

        cpu->halt_cond = g_malloc0(sizeof(QemuCond));

        qemu_cond_init(cpu->halt_cond);

        tcg_halt_cond = cpu->halt_cond;

        snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "CPU %d/TCG",

                 cpu->cpu_index);

        qemu_thread_create(cpu->thread, thread_name, qemu_tcg_cpu_thread_fn,

                           cpu, QEMU_THREAD_JOINABLE);

#ifdef _WIN32

        cpu->hThread = qemu_thread_get_handle(cpu->thread);

#endif

        while (!cpu->created) {

            qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);

        }

        tcg_cpu_thread = cpu->thread;

    } else {

        cpu->thread = tcg_cpu_thread;

        cpu->halt_cond = tcg_halt_cond;

    }

}


AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)

{

    AVChapter *chapter = NULL;

    int i;

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

        if(s->chapters[i]->id == id)

            chapter = s->chapters[i];

    if(!chapter){

        chapter= av_mallocz(sizeof(AVChapter));

        if(!chapter)

            return NULL;

        dynarray_add(&s->chapters, &s->nb_chapters, chapter);

    }

    if(chapter->title)

        av_free(chapter->title);

    chapter->title = av_strdup(title);

    chapter->id    = id;

    chapter->time_base= time_base;

    chapter->start = start;

    chapter->end   = end;

    return chapter;

}


int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes)

{

    QEMUIOVector qiov;

    struct iovec iov = {

        .iov_base = (void *)buf,

        .iov_len = bytes,

    };

    int ret;

    if (bytes < 0) {

        return -EINVAL;

    }

    qemu_iovec_init_external(&qiov, &iov, 1);

    ret = bdrv_prwv_co(bs, offset, &qiov, false, 0);

    if (ret < 0) {

        return ret;

    }

    return bytes;

}


static void gen_dmtc0(DisasContext *ctx, TCGv arg, int reg, int sel)

{

    const char *rn = "invalid";

    if (sel != 0)

        check_insn(ctx, ISA_MIPS64);

    if (use_icount)

        gen_io_start();

    switch (reg) {

    case 0:

        switch (sel) {

        case 0:

            gen_helper_mtc0_index(cpu_env, arg);

            rn = "Index";

            break;

        case 1:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_mvpcontrol(cpu_env, arg);

            rn = "MVPControl";

            break;

        case 2:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            /* ignored */

            rn = "MVPConf0";

            break;

        case 3:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            /* ignored */

            rn = "MVPConf1";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 1:

        switch (sel) {

        case 0:

            /* ignored */

            rn = "Random";

            break;

        case 1:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_vpecontrol(cpu_env, arg);

            rn = "VPEControl";

            break;

        case 2:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_vpeconf0(cpu_env, arg);

            rn = "VPEConf0";

            break;

        case 3:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_vpeconf1(cpu_env, arg);

            rn = "VPEConf1";

            break;

        case 4:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_yqmask(cpu_env, arg);

            rn = "YQMask";

            break;

        case 5:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            tcg_gen_st_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_VPESchedule));

            rn = "VPESchedule";

            break;

        case 6:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            tcg_gen_st_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_VPEScheFBack));

            rn = "VPEScheFBack";

            break;

        case 7:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_vpeopt(cpu_env, arg);

            rn = "VPEOpt";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 2:

        switch (sel) {

        case 0:

            gen_helper_dmtc0_entrylo0(cpu_env, arg);

            rn = "EntryLo0";

            break;

        case 1:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tcstatus(cpu_env, arg);

            rn = "TCStatus";

            break;

        case 2:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tcbind(cpu_env, arg);

            rn = "TCBind";

            break;

        case 3:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tcrestart(cpu_env, arg);

            rn = "TCRestart";

            break;

        case 4:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tchalt(cpu_env, arg);

            rn = "TCHalt";

            break;

        case 5:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tccontext(cpu_env, arg);

            rn = "TCContext";

            break;

        case 6:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tcschedule(cpu_env, arg);

            rn = "TCSchedule";

            break;

        case 7:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mtc0_tcschefback(cpu_env, arg);

            rn = "TCScheFBack";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 3:

        switch (sel) {

        case 0:

            gen_helper_dmtc0_entrylo1(cpu_env, arg);

            rn = "EntryLo1";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 4:

        switch (sel) {

        case 0:

            gen_helper_mtc0_context(cpu_env, arg);

            rn = "Context";

            break;

        case 1:

//           gen_helper_mtc0_contextconfig(cpu_env, arg); /* SmartMIPS ASE */

            rn = "ContextConfig";

            goto cp0_unimplemented;

//           break;

        case 2:

            CP0_CHECK(ctx->ulri);

            tcg_gen_st_tl(arg, cpu_env,

                          offsetof(CPUMIPSState, active_tc.CP0_UserLocal));

            rn = "UserLocal";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 5:

        switch (sel) {

        case 0:

            gen_helper_mtc0_pagemask(cpu_env, arg);

            rn = "PageMask";

            break;

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_pagegrain(cpu_env, arg);

            rn = "PageGrain";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 6:

        switch (sel) {

        case 0:

            gen_helper_mtc0_wired(cpu_env, arg);

            rn = "Wired";

            break;

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsconf0(cpu_env, arg);

            rn = "SRSConf0";

            break;

        case 2:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsconf1(cpu_env, arg);

            rn = "SRSConf1";

            break;

        case 3:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsconf2(cpu_env, arg);

            rn = "SRSConf2";

            break;

        case 4:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsconf3(cpu_env, arg);

            rn = "SRSConf3";

            break;

        case 5:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsconf4(cpu_env, arg);

            rn = "SRSConf4";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 7:

        switch (sel) {

        case 0:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_hwrena(cpu_env, arg);

            ctx->bstate = BS_STOP;

            rn = "HWREna";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 8:

        switch (sel) {

        case 0:

            /* ignored */

            rn = "BadVAddr";

            break;

        case 1:

            /* ignored */

            rn = "BadInstr";

            break;

        case 2:

            /* ignored */

            rn = "BadInstrP";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 9:

        switch (sel) {

        case 0:

            gen_helper_mtc0_count(cpu_env, arg);

            rn = "Count";

            break;

        /* 6,7 are implementation dependent */

        default:

            goto cp0_unimplemented;

        }

        /* Stop translation as we may have switched the execution mode */

        ctx->bstate = BS_STOP;

        break;

    case 10:

        switch (sel) {

        case 0:

            gen_helper_mtc0_entryhi(cpu_env, arg);

            rn = "EntryHi";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 11:

        switch (sel) {

        case 0:

            gen_helper_mtc0_compare(cpu_env, arg);

            rn = "Compare";

            break;

        /* 6,7 are implementation dependent */

        default:

            goto cp0_unimplemented;

        }

        /* Stop translation as we may have switched the execution mode */

        ctx->bstate = BS_STOP;

        break;

    case 12:

        switch (sel) {

        case 0:

            save_cpu_state(ctx, 1);

            gen_helper_mtc0_status(cpu_env, arg);

            /* BS_STOP isn't good enough here, hflags may have changed. */

            gen_save_pc(ctx->pc + 4);

            ctx->bstate = BS_EXCP;

            rn = "Status";

            break;

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_intctl(cpu_env, arg);

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            rn = "IntCtl";

            break;

        case 2:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_srsctl(cpu_env, arg);

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            rn = "SRSCtl";

            break;

        case 3:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mtc0_store32(arg, offsetof(CPUMIPSState, CP0_SRSMap));

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            rn = "SRSMap";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 13:

        switch (sel) {

        case 0:

            save_cpu_state(ctx, 1);

            /* Mark as an IO operation because we may trigger a software

               interrupt.  */

            if (use_icount) {

                gen_io_start();

            }

            gen_helper_mtc0_cause(cpu_env, arg);

            if (use_icount) {

                gen_io_end();

            }

            /* Stop translation as we may have triggered an intetrupt */

            ctx->bstate = BS_STOP;

            rn = "Cause";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 14:

        switch (sel) {

        case 0:

            tcg_gen_st_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_EPC));

            rn = "EPC";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 15:

        switch (sel) {

        case 0:

            /* ignored */

            rn = "PRid";

            break;

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_helper_mtc0_ebase(cpu_env, arg);

            rn = "EBase";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 16:

        switch (sel) {

        case 0:

            gen_helper_mtc0_config0(cpu_env, arg);

            rn = "Config";

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            break;

        case 1:

            /* ignored, read only */

            rn = "Config1";

            break;

        case 2:

            gen_helper_mtc0_config2(cpu_env, arg);

            rn = "Config2";

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            break;

        case 3:

            /* ignored */

            rn = "Config3";

            break;

        case 4:

            /* currently ignored */

            rn = "Config4";

            break;

        case 5:

            gen_helper_mtc0_config5(cpu_env, arg);

            rn = "Config5";

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            break;

        /* 6,7 are implementation dependent */

        default:

            rn = "Invalid config selector";

            goto cp0_unimplemented;

        }

        break;

    case 17:

        switch (sel) {

        case 0:

            gen_helper_mtc0_lladdr(cpu_env, arg);

            rn = "LLAddr";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 18:

        switch (sel) {

        case 0 ... 7:

            gen_helper_0e1i(mtc0_watchlo, arg, sel);

            rn = "WatchLo";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 19:

        switch (sel) {

        case 0 ... 7:

            gen_helper_0e1i(mtc0_watchhi, arg, sel);

            rn = "WatchHi";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 20:

        switch (sel) {

        case 0:

            check_insn(ctx, ISA_MIPS3);

            gen_helper_mtc0_xcontext(cpu_env, arg);

            rn = "XContext";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 21:

       /* Officially reserved, but sel 0 is used for R1x000 framemask */

        CP0_CHECK(!(ctx->insn_flags & ISA_MIPS32R6));

        switch (sel) {

        case 0:

            gen_helper_mtc0_framemask(cpu_env, arg);

            rn = "Framemask";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 22:

        /* ignored */

        rn = "Diagnostic"; /* implementation dependent */

        break;

    case 23:

        switch (sel) {

        case 0:

            gen_helper_mtc0_debug(cpu_env, arg); /* EJTAG support */

            /* BS_STOP isn't good enough here, hflags may have changed. */

            gen_save_pc(ctx->pc + 4);

            ctx->bstate = BS_EXCP;

            rn = "Debug";

            break;

        case 1:

//            gen_helper_mtc0_tracecontrol(cpu_env, arg); /* PDtrace support */

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            rn = "TraceControl";

//            break;

        case 2:

//            gen_helper_mtc0_tracecontrol2(cpu_env, arg); /* PDtrace support */

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            rn = "TraceControl2";

//            break;

        case 3:

//            gen_helper_mtc0_usertracedata(cpu_env, arg); /* PDtrace support */

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            rn = "UserTraceData";

//            break;

        case 4:

//            gen_helper_mtc0_tracebpc(cpu_env, arg); /* PDtrace support */

            /* Stop translation as we may have switched the execution mode */

            ctx->bstate = BS_STOP;

            rn = "TraceBPC";

//            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 24:

        switch (sel) {

        case 0:

            /* EJTAG support */

            tcg_gen_st_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_DEPC));

            rn = "DEPC";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 25:

        switch (sel) {

        case 0:

            gen_helper_mtc0_performance0(cpu_env, arg);

            rn = "Performance0";

            break;

        case 1:

//            gen_helper_mtc0_performance1(cpu_env, arg);

            rn = "Performance1";

//            break;

        case 2:

//            gen_helper_mtc0_performance2(cpu_env, arg);

            rn = "Performance2";

//            break;

        case 3:

//            gen_helper_mtc0_performance3(cpu_env, arg);

            rn = "Performance3";

//            break;

        case 4:

//            gen_helper_mtc0_performance4(cpu_env, arg);

            rn = "Performance4";

//            break;

        case 5:

//            gen_helper_mtc0_performance5(cpu_env, arg);

            rn = "Performance5";

//            break;

        case 6:

//            gen_helper_mtc0_performance6(cpu_env, arg);

            rn = "Performance6";

//            break;

        case 7:

//            gen_helper_mtc0_performance7(cpu_env, arg);

            rn = "Performance7";

//            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 26:

        /* ignored */

        rn = "ECC";

        break;

    case 27:

        switch (sel) {

        case 0 ... 3:

            /* ignored */

            rn = "CacheErr";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 28:

        switch (sel) {

        case 0:

        case 2:

        case 4:

        case 6:

            gen_helper_mtc0_taglo(cpu_env, arg);

            rn = "TagLo";

            break;

        case 1:

        case 3:

        case 5:

        case 7:

            gen_helper_mtc0_datalo(cpu_env, arg);

            rn = "DataLo";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 29:

        switch (sel) {

        case 0:

        case 2:

        case 4:

        case 6:

            gen_helper_mtc0_taghi(cpu_env, arg);

            rn = "TagHi";

            break;

        case 1:

        case 3:

        case 5:

        case 7:

            gen_helper_mtc0_datahi(cpu_env, arg);

            rn = "DataHi";

            break;

        default:

            rn = "invalid sel";

            goto cp0_unimplemented;

        }

        break;

    case 30:

        switch (sel) {

        case 0:

            tcg_gen_st_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_ErrorEPC));

            rn = "ErrorEPC";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 31:

        switch (sel) {

        case 0:

            /* EJTAG support */

            gen_mtc0_store32(arg, offsetof(CPUMIPSState, CP0_DESAVE));

            rn = "DESAVE";

            break;

        case 2 ... 7:

            CP0_CHECK(ctx->kscrexist & (1 << sel));

            tcg_gen_st_tl(arg, cpu_env,

                          offsetof(CPUMIPSState, CP0_KScratch[sel-2]));

            rn = "KScratch";

            break;

        default:

            goto cp0_unimplemented;

        }

        /* Stop translation as we may have switched the execution mode */

        ctx->bstate = BS_STOP;

        break;

    default:

        goto cp0_unimplemented;

    }

    (void)rn; /* avoid a compiler warning */

    LOG_DISAS("dmtc0 %s (reg %d sel %d)\n", rn, reg, sel);

    /* For simplicity assume that all writes can cause interrupts.  */

    if (use_icount) {

        gen_io_end();

        ctx->bstate = BS_STOP;

    }

    return;

cp0_unimplemented:

    LOG_DISAS("dmtc0 %s (reg %d sel %d)\n", rn, reg, sel);

}


void pc_basic_device_init(ISABus *isa_bus, qemu_irq *gsi,

                          ISADevice **rtc_state,

                          bool create_fdctrl,

                          bool no_vmport,

                          uint32 hpet_irqs)

{

    int i;

    DriveInfo *fd[MAX_FD];

    DeviceState *hpet = NULL;

    int pit_isa_irq = 0;

    qemu_irq pit_alt_irq = NULL;

    qemu_irq rtc_irq = NULL;

    qemu_irq *a20_line;

    ISADevice *i8042, *port92, *vmmouse, *pit = NULL;

    qemu_irq *cpu_exit_irq;

    MemoryRegion *ioport80_io = g_new(MemoryRegion, 1);

    MemoryRegion *ioportF0_io = g_new(MemoryRegion, 1);

    memory_region_init_io(ioport80_io, NULL, &ioport80_io_ops, NULL, "ioport80", 1);

    memory_region_add_subregion(isa_bus->address_space_io, 0x80, ioport80_io);

    memory_region_init_io(ioportF0_io, NULL, &ioportF0_io_ops, NULL, "ioportF0", 1);

    memory_region_add_subregion(isa_bus->address_space_io, 0xf0, ioportF0_io);

    /*

     * Check if an HPET shall be created.

     *

     * Without KVM_CAP_PIT_STATE2, we cannot switch off the in-kernel PIT

     * when the HPET wants to take over. Thus we have to disable the latter.

     */

    if (!no_hpet && (!kvm_irqchip_in_kernel() || kvm_has_pit_state2())) {

        /* In order to set property, here not using sysbus_try_create_simple */

        hpet = qdev_try_create(NULL, TYPE_HPET);

        if (hpet) {

            /* For pc-piix-*, hpet's intcap is always IRQ2. For pc-q35-1.7

             * and earlier, use IRQ2 for compat. Otherwise, use IRQ16~23,

             * IRQ8 and IRQ2.

             */

            uint8_t compat = object_property_get_int(OBJECT(hpet),

                    HPET_INTCAP, NULL);

            if (!compat) {

                qdev_prop_set_uint32(hpet, HPET_INTCAP, hpet_irqs);

            }

            qdev_init_nofail(hpet);

            sysbus_mmio_map(SYS_BUS_DEVICE(hpet), 0, HPET_BASE);

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

                sysbus_connect_irq(SYS_BUS_DEVICE(hpet), i, gsi[i]);

            }

            pit_isa_irq = -1;

            pit_alt_irq = qdev_get_gpio_in(hpet, HPET_LEGACY_PIT_INT);

            rtc_irq = qdev_get_gpio_in(hpet, HPET_LEGACY_RTC_INT);

        }

    }

    *rtc_state = rtc_init(isa_bus, 2000, rtc_irq);

    qemu_register_boot_set(pc_boot_set, *rtc_state);

    if (!xen_enabled()) {

        if (kvm_irqchip_in_kernel()) {

            pit = kvm_pit_init(isa_bus, 0x40);

        } else {

            pit = pit_init(isa_bus, 0x40, pit_isa_irq, pit_alt_irq);

        }

        if (hpet) {

            /* connect PIT to output control line of the HPET */

            qdev_connect_gpio_out(hpet, 0, qdev_get_gpio_in(DEVICE(pit), 0));

        }

        pcspk_init(isa_bus, pit);

    }

    serial_hds_isa_init(isa_bus, MAX_SERIAL_PORTS);

    parallel_hds_isa_init(isa_bus, MAX_PARALLEL_PORTS);

    a20_line = qemu_allocate_irqs(handle_a20_line_change, first_cpu, 2);

    i8042 = isa_create_simple(isa_bus, "i8042");

    i8042_setup_a20_line(i8042, &a20_line[0]);

    if (!no_vmport) {

        vmport_init(isa_bus);

        vmmouse = isa_try_create(isa_bus, "vmmouse");

    } else {

        vmmouse = NULL;

    }

    if (vmmouse) {

        DeviceState *dev = DEVICE(vmmouse);

        qdev_prop_set_ptr(dev, "ps2_mouse", i8042);

        qdev_init_nofail(dev);

    }

    port92 = isa_create_simple(isa_bus, "port92");

    port92_init(port92, &a20_line[1]);

    cpu_exit_irq = qemu_allocate_irqs(cpu_request_exit, NULL, 1);

    DMA_init(0, cpu_exit_irq);

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

        fd[i] = drive_get(IF_FLOPPY, 0, i);

        create_fdctrl |= !!fd[i];

    }

    if (create_fdctrl) {

        fdctrl_init_isa(isa_bus, fd);

    }

}


static int qemu_gluster_parseuri(GlusterConf *gconf, const char *filename)

{

    URI *uri;

    QueryParams *qp = NULL;

    bool is_unix = false;

    int ret = 0;

    uri = uri_parse(filename);

    if (!uri) {

        return -EINVAL;

    }

    /* transport */

    if (!strcmp(uri->scheme, "gluster")) {

        gconf->transport = g_strdup("tcp");

    } else if (!strcmp(uri->scheme, "gluster+tcp")) {

        gconf->transport = g_strdup("tcp");

    } else if (!strcmp(uri->scheme, "gluster+unix")) {

        gconf->transport = g_strdup("unix");

        is_unix = true;

    } else if (!strcmp(uri->scheme, "gluster+rdma")) {

        gconf->transport = g_strdup("rdma");

    } else {

        ret = -EINVAL;

        goto out;

    }

    ret = parse_volume_options(gconf, uri->path);

    if (ret < 0) {

        goto out;

    }

    qp = query_params_parse(uri->query);

    if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {

        ret = -EINVAL;

        goto out;

    }

    if (is_unix) {

        if (uri->server || uri->port) {

            ret = -EINVAL;

            goto out;

        }

        if (strcmp(qp->p[0].name, "socket")) {

            ret = -EINVAL;

            goto out;

        }

        gconf->server = g_strdup(qp->p[0].value);

    } else {

        gconf->server = g_strdup(uri->server);

        gconf->port = uri->port;

    }

out:

    if (qp) {

        query_params_free(qp);

    }

    uri_free(uri);

    return ret;

}


static void omap_prcm_write(void *opaque, hwaddr addr,

                            uint64_t value, unsigned size)

{

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

    if (size != 4) {

        omap_badwidth_write32(opaque, addr, value);

        return;

    }

    switch (addr) {

    case 0x000:	/* PRCM_REVISION */

    case 0x054:	/* PRCM_VOLTST */

    case 0x084:	/* PRCM_CLKCFG_STATUS */

    case 0x1e4:	/* PM_PWSTST_MPU */

    case 0x220:	/* CM_IDLEST1_CORE */

    case 0x224:	/* CM_IDLEST2_CORE */

    case 0x22c:	/* CM_IDLEST4_CORE */

    case 0x2c8:	/* PM_WKDEP_CORE */

    case 0x2e4:	/* PM_PWSTST_CORE */

    case 0x320:	/* CM_IDLEST_GFX */

    case 0x3e4:	/* PM_PWSTST_GFX */

    case 0x420:	/* CM_IDLEST_WKUP */

    case 0x520:	/* CM_IDLEST_CKGEN */

    case 0x820:	/* CM_IDLEST_DSP */

    case 0x8e4:	/* PM_PWSTST_DSP */

        OMAP_RO_REG(addr);

        return;

    case 0x010:	/* PRCM_SYSCONFIG */

        s->sysconfig = value & 1;

        break;

    case 0x018:	/* PRCM_IRQSTATUS_MPU */

        s->irqst[0] &= ~value;

        omap_prcm_int_update(s, 0);

        break;

    case 0x01c:	/* PRCM_IRQENABLE_MPU */

        s->irqen[0] = value & 0x3f;

        omap_prcm_int_update(s, 0);

        break;

    case 0x050:	/* PRCM_VOLTCTRL */

        s->voltctrl = value & 0xf1c3;

        break;

    case 0x060:	/* PRCM_CLKSRC_CTRL */

        s->clksrc[0] = value & 0xdb;

        /* TODO update clocks */

        break;

    case 0x070:	/* PRCM_CLKOUT_CTRL */

        s->clkout[0] = value & 0xbbbb;

        /* TODO update clocks */

        break;

    case 0x078:	/* PRCM_CLKEMUL_CTRL */

        s->clkemul[0] = value & 1;

        /* TODO update clocks */

        break;

    case 0x080:	/* PRCM_CLKCFG_CTRL */

        break;

    case 0x090:	/* PRCM_VOLTSETUP */

        s->setuptime[0] = value & 0xffff;

        break;

    case 0x094:	/* PRCM_CLKSSETUP */

        s->setuptime[1] = value & 0xffff;

        break;

    case 0x098:	/* PRCM_POLCTRL */

        s->clkpol[0] = value & 0x701;

        break;

    case 0x0b0:	/* GENERAL_PURPOSE1 */

    case 0x0b4:	/* GENERAL_PURPOSE2 */

    case 0x0b8:	/* GENERAL_PURPOSE3 */

    case 0x0bc:	/* GENERAL_PURPOSE4 */

    case 0x0c0:	/* GENERAL_PURPOSE5 */

    case 0x0c4:	/* GENERAL_PURPOSE6 */

    case 0x0c8:	/* GENERAL_PURPOSE7 */

    case 0x0cc:	/* GENERAL_PURPOSE8 */

    case 0x0d0:	/* GENERAL_PURPOSE9 */

    case 0x0d4:	/* GENERAL_PURPOSE10 */

    case 0x0d8:	/* GENERAL_PURPOSE11 */

    case 0x0dc:	/* GENERAL_PURPOSE12 */

    case 0x0e0:	/* GENERAL_PURPOSE13 */

    case 0x0e4:	/* GENERAL_PURPOSE14 */

    case 0x0e8:	/* GENERAL_PURPOSE15 */

    case 0x0ec:	/* GENERAL_PURPOSE16 */

    case 0x0f0:	/* GENERAL_PURPOSE17 */

    case 0x0f4:	/* GENERAL_PURPOSE18 */

    case 0x0f8:	/* GENERAL_PURPOSE19 */

    case 0x0fc:	/* GENERAL_PURPOSE20 */

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

        break;

    case 0x140:	/* CM_CLKSEL_MPU */

        s->clksel[0] = value & 0x1f;

        /* TODO update clocks */

        break;

    case 0x148:	/* CM_CLKSTCTRL_MPU */

        s->clkctrl[0] = value & 0x1f;

        break;

    case 0x158:	/* RM_RSTST_MPU */

        s->rst[0] &= ~value;

        break;

    case 0x1c8:	/* PM_WKDEP_MPU */

        s->wkup[0] = value & 0x15;

        break;

    case 0x1d4:	/* PM_EVGENCTRL_MPU */

        s->ev = value & 0x1f;

        break;

    case 0x1d8:	/* PM_EVEGENONTIM_MPU */

        s->evtime[0] = value;

        break;

    case 0x1dc:	/* PM_EVEGENOFFTIM_MPU */

        s->evtime[1] = value;

        break;

    case 0x1e0:	/* PM_PWSTCTRL_MPU */

        s->power[0] = value & 0xc0f;

        break;

    case 0x200:	/* CM_FCLKEN1_CORE */

        s->clken[0] = value & 0xbfffffff;

        /* TODO update clocks */

        /* The EN_EAC bit only gets/puts func_96m_clk.  */

        break;

    case 0x204:	/* CM_FCLKEN2_CORE */

        s->clken[1] = value & 0x00000007;

        /* TODO update clocks */

        break;

    case 0x210:	/* CM_ICLKEN1_CORE */

        s->clken[2] = value & 0xfffffff9;

        /* TODO update clocks */

        /* The EN_EAC bit only gets/puts core_l4_iclk.  */

        break;

    case 0x214:	/* CM_ICLKEN2_CORE */

        s->clken[3] = value & 0x00000007;

        /* TODO update clocks */

        break;

    case 0x21c:	/* CM_ICLKEN4_CORE */

        s->clken[4] = value & 0x0000001f;

        /* TODO update clocks */

        break;

    case 0x230:	/* CM_AUTOIDLE1_CORE */

        s->clkidle[0] = value & 0xfffffff9;

        /* TODO update clocks */

        break;

    case 0x234:	/* CM_AUTOIDLE2_CORE */

        s->clkidle[1] = value & 0x00000007;

        /* TODO update clocks */

        break;

    case 0x238:	/* CM_AUTOIDLE3_CORE */

        s->clkidle[2] = value & 0x00000007;

        /* TODO update clocks */

        break;

    case 0x23c:	/* CM_AUTOIDLE4_CORE */

        s->clkidle[3] = value & 0x0000001f;

        /* TODO update clocks */

        break;

    case 0x240:	/* CM_CLKSEL1_CORE */

        s->clksel[1] = value & 0x0fffbf7f;

        /* TODO update clocks */

        break;

    case 0x244:	/* CM_CLKSEL2_CORE */

        s->clksel[2] = value & 0x00fffffc;

        /* TODO update clocks */

        break;

    case 0x248:	/* CM_CLKSTCTRL_CORE */

        s->clkctrl[1] = value & 0x7;

        break;

    case 0x2a0:	/* PM_WKEN1_CORE */

        s->wken[0] = value & 0x04667ff8;

        break;

    case 0x2a4:	/* PM_WKEN2_CORE */

        s->wken[1] = value & 0x00000005;

        break;

    case 0x2b0:	/* PM_WKST1_CORE */

        s->wkst[0] &= ~value;

        break;

    case 0x2b4:	/* PM_WKST2_CORE */

        s->wkst[1] &= ~value;

        break;

    case 0x2e0:	/* PM_PWSTCTRL_CORE */

        s->power[1] = (value & 0x00fc3f) | (1 << 2);

        break;

    case 0x300:	/* CM_FCLKEN_GFX */

        s->clken[5] = value & 6;

        /* TODO update clocks */

        break;

    case 0x310:	/* CM_ICLKEN_GFX */

        s->clken[6] = value & 1;

        /* TODO update clocks */

        break;

    case 0x340:	/* CM_CLKSEL_GFX */

        s->clksel[3] = value & 7;

        /* TODO update clocks */

        break;

    case 0x348:	/* CM_CLKSTCTRL_GFX */

        s->clkctrl[2] = value & 1;

        break;

    case 0x350:	/* RM_RSTCTRL_GFX */

        s->rstctrl[0] = value & 1;

        /* TODO: reset */

        break;

    case 0x358:	/* RM_RSTST_GFX */

        s->rst[1] &= ~value;

        break;

    case 0x3c8:	/* PM_WKDEP_GFX */

        s->wkup[1] = value & 0x13;

        break;

    case 0x3e0:	/* PM_PWSTCTRL_GFX */

        s->power[2] = (value & 0x00c0f) | (3 << 2);

        break;

    case 0x400:	/* CM_FCLKEN_WKUP */

        s->clken[7] = value & 0xd;

        /* TODO update clocks */

        break;

    case 0x410:	/* CM_ICLKEN_WKUP */

        s->clken[8] = value & 0x3f;

        /* TODO update clocks */

        break;

    case 0x430:	/* CM_AUTOIDLE_WKUP */

        s->clkidle[4] = value & 0x0000003f;

        /* TODO update clocks */

        break;

    case 0x440:	/* CM_CLKSEL_WKUP */

        s->clksel[4] = value & 3;

        /* TODO update clocks */

        break;

    case 0x450:	/* RM_RSTCTRL_WKUP */

        /* TODO: reset */

        if (value & 2)

            qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);

        break;

    case 0x454:	/* RM_RSTTIME_WKUP */

        s->rsttime_wkup = value & 0x1fff;

        break;

    case 0x458:	/* RM_RSTST_WKUP */

        s->rst[2] &= ~value;

        break;

    case 0x4a0:	/* PM_WKEN_WKUP */

        s->wken[2] = value & 0x00000005;

        break;

    case 0x4b0:	/* PM_WKST_WKUP */

        s->wkst[2] &= ~value;

        break;

    case 0x500:	/* CM_CLKEN_PLL */

        if (value & 0xffffff30)

            fprintf(stderr, "%s: write 0s in CM_CLKEN_PLL for "

                            "future compatibility\n", __FUNCTION__);

        if ((s->clken[9] ^ value) & 0xcc) {

            s->clken[9] &= ~0xcc;

            s->clken[9] |= value & 0xcc;

            omap_prcm_apll_update(s);

        }

        if ((s->clken[9] ^ value) & 3) {

            s->clken[9] &= ~3;

            s->clken[9] |= value & 3;

            omap_prcm_dpll_update(s);

        }

        break;

    case 0x530:	/* CM_AUTOIDLE_PLL */

        s->clkidle[5] = value & 0x000000cf;

        /* TODO update clocks */

        break;

    case 0x540:	/* CM_CLKSEL1_PLL */

        if (value & 0xfc4000d7)

            fprintf(stderr, "%s: write 0s in CM_CLKSEL1_PLL for "

                            "future compatibility\n", __FUNCTION__);

        if ((s->clksel[5] ^ value) & 0x003fff00) {

            s->clksel[5] = value & 0x03bfff28;

            omap_prcm_dpll_update(s);

        }

        /* TODO update the other clocks */

        s->clksel[5] = value & 0x03bfff28;

        break;

    case 0x544:	/* CM_CLKSEL2_PLL */

        if (value & ~3)

            fprintf(stderr, "%s: write 0s in CM_CLKSEL2_PLL[31:2] for "

                            "future compatibility\n", __FUNCTION__);

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

            s->clksel[6] = value & 3;

            omap_prcm_dpll_update(s);

        }

        break;

    case 0x800:	/* CM_FCLKEN_DSP */

        s->clken[10] = value & 0x501;

        /* TODO update clocks */

        break;

    case 0x810:	/* CM_ICLKEN_DSP */

        s->clken[11] = value & 0x2;

        /* TODO update clocks */

        break;

    case 0x830:	/* CM_AUTOIDLE_DSP */

        s->clkidle[6] = value & 0x2;

        /* TODO update clocks */

        break;

    case 0x840:	/* CM_CLKSEL_DSP */

        s->clksel[7] = value & 0x3fff;

        /* TODO update clocks */

        break;

    case 0x848:	/* CM_CLKSTCTRL_DSP */

        s->clkctrl[3] = value & 0x101;

        break;

    case 0x850:	/* RM_RSTCTRL_DSP */

        /* TODO: reset */

        break;

    case 0x858:	/* RM_RSTST_DSP */

        s->rst[3] &= ~value;

        break;

    case 0x8c8:	/* PM_WKDEP_DSP */

        s->wkup[2] = value & 0x13;

        break;

    case 0x8e0:	/* PM_PWSTCTRL_DSP */

        s->power[3] = (value & 0x03017) | (3 << 2);

        break;

    case 0x8f0:	/* PRCM_IRQSTATUS_DSP */

        s->irqst[1] &= ~value;

        omap_prcm_int_update(s, 1);

        break;

    case 0x8f4:	/* PRCM_IRQENABLE_DSP */

        s->irqen[1] = value & 0x7;

        omap_prcm_int_update(s, 1);

        break;

    case 0x8f8:	/* PRCM_IRQSTATUS_IVA */

        s->irqst[2] &= ~value;

        omap_prcm_int_update(s, 2);

        break;

    case 0x8fc:	/* PRCM_IRQENABLE_IVA */

        s->irqen[2] = value & 0x7;

        omap_prcm_int_update(s, 2);

        break;

    default:

        OMAP_BAD_REG(addr);

        return;

    }

}


int kvm_arch_init(KVMState *s, int smp_cpus)

{

    int ret;

    struct utsname utsname;

    uname(&utsname);

    lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;

    /* create vm86 tss.  KVM uses vm86 mode to emulate 16-bit code

     * directly.  In order to use vm86 mode, a TSS is needed.  Since this

     * must be part of guest physical memory, we need to allocate it.  Older

     * versions of KVM just assumed that it would be at the end of physical

     * memory but that doesn't work with more than 4GB of memory.  We simply

     * refuse to work with those older versions of KVM. */

    ret = kvm_check_extension(s, KVM_CAP_SET_TSS_ADDR);

    if (ret <= 0) {

        fprintf(stderr, "kvm does not support KVM_CAP_SET_TSS_ADDR\n");

        return ret;

    }

    /* this address is 3 pages before the bios, and the bios should present

     * as unavaible memory.  FIXME, need to ensure the e820 map deals with

     * this?

     */

    /*

     * Tell fw_cfg to notify the BIOS to reserve the range.

     */

    if (e820_add_entry(0xfffbc000, 0x4000, E820_RESERVED) < 0) {

        perror("e820_add_entry() table is full");

        exit(1);

    }

    ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, 0xfffbd000);

    if (ret < 0) {

        return ret;

    }

    return kvm_init_identity_map_page(s);

}


static void bootp_reply(Slirp *slirp, const struct bootp_t *bp)

{

    BOOTPClient *bc = NULL;

    struct mbuf *m;

    struct bootp_t *rbp;

    struct sockaddr_in saddr, daddr;

    struct in_addr preq_addr;

    int dhcp_msg_type, val;

    uint8_t *q;

    uint8_t client_ethaddr[ETH_ALEN];

    /* extract exact DHCP msg type */

    dhcp_decode(bp, &dhcp_msg_type, &preq_addr);

    DPRINTF("bootp packet op=%d msgtype=%d", bp->bp_op, dhcp_msg_type);

    if (preq_addr.s_addr != htonl(0L))

        DPRINTF(" req_addr=%08" PRIx32 "\n", ntohl(preq_addr.s_addr));

    else

        DPRINTF("\n");

    if (dhcp_msg_type == 0)

        dhcp_msg_type = DHCPREQUEST; /* Force reply for old BOOTP clients */

    if (dhcp_msg_type != DHCPDISCOVER &&

        dhcp_msg_type != DHCPREQUEST)

        return;

    /* Get client's hardware address from bootp request */

    memcpy(client_ethaddr, bp->bp_hwaddr, ETH_ALEN);

    m = m_get(slirp);

    if (!m) {

        return;

    }

    m->m_data += IF_MAXLINKHDR;

    rbp = (struct bootp_t *)m->m_data;

    m->m_data += sizeof(struct udpiphdr);

    memset(rbp, 0, sizeof(struct bootp_t));

    if (dhcp_msg_type == DHCPDISCOVER) {

        if (preq_addr.s_addr != htonl(0L)) {

            bc = request_addr(slirp, &preq_addr, client_ethaddr);

            if (bc) {

                daddr.sin_addr = preq_addr;

            }

        }

        if (!bc) {

         new_addr:

            bc = get_new_addr(slirp, &daddr.sin_addr, client_ethaddr);

            if (!bc) {

                DPRINTF("no address left\n");

                return;

            }

        }

        memcpy(bc->macaddr, client_ethaddr, ETH_ALEN);

    } else if (preq_addr.s_addr != htonl(0L)) {

        bc = request_addr(slirp, &preq_addr, client_ethaddr);

        if (bc) {

            daddr.sin_addr = preq_addr;

            memcpy(bc->macaddr, client_ethaddr, ETH_ALEN);

        } else {

            /* DHCPNAKs should be sent to broadcast */

            daddr.sin_addr.s_addr = 0xffffffff;

        }

    } else {

        bc = find_addr(slirp, &daddr.sin_addr, bp->bp_hwaddr);

        if (!bc) {

            /* if never assigned, behaves as if it was already

               assigned (windows fix because it remembers its address) */

            goto new_addr;

        }

    }

    /* Update ARP table for this IP address */

    arp_table_add(slirp, daddr.sin_addr.s_addr, client_ethaddr);

    saddr.sin_addr = slirp->vhost_addr;

    saddr.sin_port = htons(BOOTP_SERVER);

    daddr.sin_port = htons(BOOTP_CLIENT);

    rbp->bp_op = BOOTP_REPLY;

    rbp->bp_xid = bp->bp_xid;

    rbp->bp_htype = 1;

    rbp->bp_hlen = 6;

    memcpy(rbp->bp_hwaddr, bp->bp_hwaddr, ETH_ALEN);

    rbp->bp_yiaddr = daddr.sin_addr; /* Client IP address */

    rbp->bp_siaddr = saddr.sin_addr; /* Server IP address */

    q = rbp->bp_vend;

    memcpy(q, rfc1533_cookie, 4);

    q += 4;

    if (bc) {

        DPRINTF("%s addr=%08" PRIx32 "\n",

                (dhcp_msg_type == DHCPDISCOVER) ? "offered" : "ack'ed",

                ntohl(daddr.sin_addr.s_addr));

        if (dhcp_msg_type == DHCPDISCOVER) {

            *q++ = RFC2132_MSG_TYPE;

            *q++ = 1;

            *q++ = DHCPOFFER;

        } else /* DHCPREQUEST */ {

            *q++ = RFC2132_MSG_TYPE;

            *q++ = 1;

            *q++ = DHCPACK;

        }

        if (slirp->bootp_filename)

            snprintf((char *)rbp->bp_file, sizeof(rbp->bp_file), "%s",

                     slirp->bootp_filename);

        *q++ = RFC2132_SRV_ID;

        *q++ = 4;

        memcpy(q, &saddr.sin_addr, 4);

        q += 4;

        *q++ = RFC1533_NETMASK;

        *q++ = 4;

        memcpy(q, &slirp->vnetwork_mask, 4);

        q += 4;

        if (!slirp->restricted) {

            *q++ = RFC1533_GATEWAY;

            *q++ = 4;

            memcpy(q, &saddr.sin_addr, 4);

            q += 4;

            *q++ = RFC1533_DNS;

            *q++ = 4;

            memcpy(q, &slirp->vnameserver_addr, 4);

            q += 4;

        }

        *q++ = RFC2132_LEASE_TIME;

        *q++ = 4;

        val = htonl(LEASE_TIME);

        memcpy(q, &val, 4);

        q += 4;

        if (*slirp->client_hostname) {

            val = strlen(slirp->client_hostname);

            *q++ = RFC1533_HOSTNAME;

            *q++ = val;

            memcpy(q, slirp->client_hostname, val);

            q += val;

        }

        if (slirp->vdnssearch) {

            size_t spaceleft = sizeof(rbp->bp_vend) - (q - rbp->bp_vend);

            val = slirp->vdnssearch_len;

            if (val + 1 > spaceleft) {

                g_warning("DHCP packet size exceeded, "

                    "omitting domain-search option.");

            } else {

                memcpy(q, slirp->vdnssearch, val);

                q += val;

            }

        }

    } else {

        static const char nak_msg[] = "requested address not available";

        DPRINTF("nak'ed addr=%08" PRIx32 "\n", ntohl(preq_addr.s_addr));

        *q++ = RFC2132_MSG_TYPE;

        *q++ = 1;

        *q++ = DHCPNAK;

        *q++ = RFC2132_MESSAGE;

        *q++ = sizeof(nak_msg) - 1;

        memcpy(q, nak_msg, sizeof(nak_msg) - 1);

        q += sizeof(nak_msg) - 1;

    }

    *q = RFC1533_END;

    daddr.sin_addr.s_addr = 0xffffffffu;

    m->m_len = sizeof(struct bootp_t) -

        sizeof(struct ip) - sizeof(struct udphdr);

    udp_output2(NULL, m, &saddr, &daddr, IPTOS_LOWDELAY);

}


static void hmp_logfile(Monitor *mon, const QDict *qdict)

{

    qemu_set_log_filename(qdict_get_str(qdict, "filename"));

}


iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,

                    void *private_data)

{

    IscsiAIOCB *acb = (IscsiAIOCB *)private_data;

    scsi_free_scsi_task(acb->task);

    acb->task = NULL;

}


int bdrv_all_delete_snapshot(const char *name, BlockDriverState **first_bad_bs,

                             Error **err)

{

    int ret = 0;

    BlockDriverState *bs;

    BdrvNextIterator *it = NULL;

    QEMUSnapshotInfo sn1, *snapshot = &sn1;

    while (ret == 0 && (it = bdrv_next(it, &bs))) {

        AioContext *ctx = bdrv_get_aio_context(bs);

        aio_context_acquire(ctx);

        if (bdrv_can_snapshot(bs) &&

                bdrv_snapshot_find(bs, snapshot, name) >= 0) {

            ret = bdrv_snapshot_delete_by_id_or_name(bs, name, err);

        }

        aio_context_release(ctx);

    }

    *first_bad_bs = bs;

    return ret;

}


int ff_hevc_split_packet(HEVCContext *s, HEVCPacket *pkt, const uint8_t *buf, int length,

                         AVCodecContext *avctx, int is_nalff, int nal_length_size)

{

    int consumed, ret = 0;

    pkt->nb_nals = 0;

    while (length >= 4) {

        HEVCNAL *nal;

        int extract_length = 0;

        if (is_nalff) {

            int i;

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

                extract_length = (extract_length << 8) | buf[i];

            buf    += nal_length_size;

            length -= nal_length_size;

            if (extract_length > length) {

                av_log(avctx, AV_LOG_ERROR, "Invalid NAL unit size.\n");

                return AVERROR_INVALIDDATA;

            }

        } else {

            /* search start code */

            while (buf[0] != 0 || buf[1] != 0 || buf[2] != 1) {

                ++buf;

                --length;

                if (length < 4) {

                    if (pkt->nb_nals > 0) {

                        // No more start codes: we discarded some irrelevant

                        // bytes at the end of the packet.

                        return 0;

                    } else {

                        av_log(avctx, AV_LOG_ERROR, "No start code is found.\n");

                        return AVERROR_INVALIDDATA;

                    }

                }

            }

            buf           += 3;

            length        -= 3;

            extract_length = length;

        }

        if (pkt->nals_allocated < pkt->nb_nals + 1) {

            int new_size = pkt->nals_allocated + 1;

            void *tmp = av_realloc_array(pkt->nals, new_size, sizeof(*pkt->nals));

            if (!tmp)

                return AVERROR(ENOMEM);

            pkt->nals = tmp;

            memset(pkt->nals + pkt->nals_allocated, 0,

                   (new_size - pkt->nals_allocated) * sizeof(*pkt->nals));

            nal = &pkt->nals[pkt->nb_nals];

            nal->skipped_bytes_pos_size = 1024; // initial buffer size

            nal->skipped_bytes_pos = av_malloc_array(nal->skipped_bytes_pos_size, sizeof(*nal->skipped_bytes_pos));

            if (!nal->skipped_bytes_pos)

                return AVERROR(ENOMEM);

            pkt->nals_allocated = new_size;

        }

        nal = &pkt->nals[pkt->nb_nals];

        consumed = ff_hevc_extract_rbsp(s, buf, extract_length, nal);

        if (consumed < 0)

            return consumed;

        pkt->nb_nals++;

        ret = init_get_bits8(&nal->gb, nal->data, nal->size);

        if (ret < 0)

            return ret;

        ret = hls_nal_unit(nal, avctx);

        if (ret <= 0) {

            if (ret < 0) {

                av_log(avctx, AV_LOG_ERROR, "Invalid NAL unit %d, skipping.\n",

                       nal->type);

            }

            pkt->nb_nals--;

        }

        buf    += consumed;

        length -= consumed;

    }

    return 0;

}


static int nvme_start_ctrl(NvmeCtrl *n)

{

    uint32_t page_bits = NVME_CC_MPS(n->bar.cc) + 12;

    uint32_t page_size = 1 << page_bits;

    if (n->cq[0] || n->sq[0] || !n->bar.asq || !n->bar.acq ||

            n->bar.asq & (page_size - 1) || n->bar.acq & (page_size - 1) ||

            NVME_CC_MPS(n->bar.cc) < NVME_CAP_MPSMIN(n->bar.cap) ||

            NVME_CC_MPS(n->bar.cc) > NVME_CAP_MPSMAX(n->bar.cap) ||

            NVME_CC_IOCQES(n->bar.cc) < NVME_CTRL_CQES_MIN(n->id_ctrl.cqes) ||

            NVME_CC_IOCQES(n->bar.cc) > NVME_CTRL_CQES_MAX(n->id_ctrl.cqes) ||

            NVME_CC_IOSQES(n->bar.cc) < NVME_CTRL_SQES_MIN(n->id_ctrl.sqes) ||

            NVME_CC_IOSQES(n->bar.cc) > NVME_CTRL_SQES_MAX(n->id_ctrl.sqes) ||

            !NVME_AQA_ASQS(n->bar.aqa) || !NVME_AQA_ACQS(n->bar.aqa)) {

        return -1;

    }

    n->page_bits = page_bits;

    n->page_size = page_size;

    n->max_prp_ents = n->page_size / sizeof(uint64_t);

    n->cqe_size = 1 << NVME_CC_IOCQES(n->bar.cc);

    n->sqe_size = 1 << NVME_CC_IOSQES(n->bar.cc);

    nvme_init_cq(&n->admin_cq, n, n->bar.acq, 0, 0,

        NVME_AQA_ACQS(n->bar.aqa) + 1, 1);

    nvme_init_sq(&n->admin_sq, n, n->bar.asq, 0, 0,

        NVME_AQA_ASQS(n->bar.aqa) + 1);

    return 0;

}


static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv)

{

    static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};

    MXFContext *mxf = s->priv_data;

    AVIOContext *pb = s->pb;

    int64_t end = avio_tell(pb) + klv->length;

    uint64_t size;

    uint64_t orig_size;

    uint64_t plaintext_size;

    uint8_t ivec[16];

    uint8_t tmpbuf[16];

    int index;

    if (!mxf->aesc && s->key && s->keylen == 16) {

        mxf->aesc = av_malloc(av_aes_size);

        if (!mxf->aesc)

            return -1;

        av_aes_init(mxf->aesc, s->key, 128, 1);

    }

    // crypto context

    avio_skip(pb, klv_decode_ber_length(pb));

    // plaintext offset

    klv_decode_ber_length(pb);

    plaintext_size = avio_rb64(pb);

    // source klv key

    klv_decode_ber_length(pb);

    avio_read(pb, klv->key, 16);

    if (!IS_KLV_KEY(klv, mxf_essence_element_key))

        return -1;

    index = mxf_get_stream_index(s, klv);

    if (index < 0)

        return -1;

    // source size

    klv_decode_ber_length(pb);

    orig_size = avio_rb64(pb);

    if (orig_size < plaintext_size)

        return -1;

    // enc. code

    size = klv_decode_ber_length(pb);

    if (size < 32 || size - 32 < orig_size)

        return -1;

    avio_read(pb, ivec, 16);

    avio_read(pb, tmpbuf, 16);

    if (mxf->aesc)

        av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);

    if (memcmp(tmpbuf, checkv, 16))

        av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");

    size -= 32;

    av_get_packet(pb, pkt, size);

    size -= plaintext_size;

    if (mxf->aesc)

        av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],

                     &pkt->data[plaintext_size], size >> 4, ivec, 1);

    pkt->size = orig_size;

    pkt->stream_index = index;

    avio_skip(pb, end - avio_tell(pb));

    return 0;

}


void avfilter_register_all(void)

{

    static int initialized;

    if (initialized)

        return;

    initialized = 1;

    REGISTER_FILTER (ACONVERT,    aconvert,    af);

    REGISTER_FILTER (AFIFO,       afifo,       af);

    REGISTER_FILTER (AFORMAT,     aformat,     af);

    REGISTER_FILTER (AMERGE,      amerge,      af);

    REGISTER_FILTER (AMIX,        amix,        af);

    REGISTER_FILTER (ANULL,       anull,       af);

    REGISTER_FILTER (ARESAMPLE,   aresample,   af);

    REGISTER_FILTER (ASETNSAMPLES, asetnsamples, af);

    REGISTER_FILTER (ASETPTS,     asetpts,     af);

    REGISTER_FILTER (ASETTB,      asettb,      af);

    REGISTER_FILTER (ASHOWINFO,   ashowinfo,   af);

    REGISTER_FILTER (ASPLIT,      asplit,      af);

    REGISTER_FILTER (ASTREAMSYNC, astreamsync, af);

    REGISTER_FILTER (ASYNCTS,     asyncts,     af);

    REGISTER_FILTER (ATEMPO,      atempo,      af);

    REGISTER_FILTER (CHANNELMAP,  channelmap,  af);

    REGISTER_FILTER (CHANNELSPLIT,channelsplit,af);

    REGISTER_FILTER (EARWAX,      earwax,      af);

    REGISTER_FILTER (JOIN,        join,        af);

    REGISTER_FILTER (PAN,         pan,         af);

    REGISTER_FILTER (SILENCEDETECT, silencedetect, af);

    REGISTER_FILTER (VOLUME,      volume,      af);

    REGISTER_FILTER (VOLUMEDETECT,volumedetect,af);

    REGISTER_FILTER (RESAMPLE,    resample,    af);

    REGISTER_FILTER (AEVALSRC,    aevalsrc,    asrc);

    REGISTER_FILTER (ANULLSRC,    anullsrc,    asrc);

    REGISTER_FILTER (FLITE,       flite,       asrc);

    REGISTER_FILTER (ABUFFERSINK, abuffersink, asink);

    REGISTER_FILTER (ANULLSINK,   anullsink,   asink);

    REGISTER_FILTER (ALPHAEXTRACT, alphaextract, vf);

    REGISTER_FILTER (ALPHAMERGE,  alphamerge,  vf);

    REGISTER_FILTER (ASS,         ass,         vf);

    REGISTER_FILTER (BBOX,        bbox,        vf);

    REGISTER_FILTER (BLACKDETECT, blackdetect, vf);

    REGISTER_FILTER (BLACKFRAME,  blackframe,  vf);

    REGISTER_FILTER (BOXBLUR,     boxblur,     vf);

    REGISTER_FILTER (COLORMATRIX, colormatrix, vf);

    REGISTER_FILTER (COPY,        copy,        vf);

    REGISTER_FILTER (CROP,        crop,        vf);

    REGISTER_FILTER (CROPDETECT,  cropdetect,  vf);

    REGISTER_FILTER (DECIMATE,    decimate,    vf);

    REGISTER_FILTER (DELOGO,      delogo,      vf);

    REGISTER_FILTER (DESHAKE,     deshake,     vf);

    REGISTER_FILTER (DRAWBOX,     drawbox,     vf);

    REGISTER_FILTER (DRAWTEXT,    drawtext,    vf);

    REGISTER_FILTER (EDGEDETECT,  edgedetect,  vf);

    REGISTER_FILTER (FADE,        fade,        vf);

    REGISTER_FILTER (FIELDORDER,  fieldorder,  vf);

    REGISTER_FILTER (FIFO,        fifo,        vf);

    REGISTER_FILTER (FORMAT,      format,      vf);

    REGISTER_FILTER (FPS,         fps,         vf);

    REGISTER_FILTER (FRAMESTEP,   framestep,   vf);

    REGISTER_FILTER (FREI0R,      frei0r,      vf);

    REGISTER_FILTER (GRADFUN,     gradfun,     vf);

    REGISTER_FILTER (HFLIP,       hflip,       vf);

    REGISTER_FILTER (HQDN3D,      hqdn3d,      vf);

    REGISTER_FILTER (HUE,         hue,         vf);

    REGISTER_FILTER (IDET,        idet,        vf);

    REGISTER_FILTER (LUT,         lut,         vf);

    REGISTER_FILTER (LUTRGB,      lutrgb,      vf);

    REGISTER_FILTER (LUTYUV,      lutyuv,      vf);

    REGISTER_FILTER (MP,          mp,          vf);

    REGISTER_FILTER (NEGATE,      negate,      vf);

    REGISTER_FILTER (NOFORMAT,    noformat,    vf);

    REGISTER_FILTER (NULL,        null,        vf);

    REGISTER_FILTER (OCV,         ocv,         vf);

    REGISTER_FILTER (OVERLAY,     overlay,     vf);

    REGISTER_FILTER (PAD,         pad,         vf);

    REGISTER_FILTER (PIXDESCTEST, pixdesctest, vf);

    REGISTER_FILTER (REMOVELOGO,  removelogo,  vf);

    REGISTER_FILTER (SCALE,       scale,       vf);

    REGISTER_FILTER (SELECT,      select,      vf);

    REGISTER_FILTER (SETDAR,      setdar,      vf);

    REGISTER_FILTER (SETFIELD,    setfield,    vf);

    REGISTER_FILTER (SETPTS,      setpts,      vf);

    REGISTER_FILTER (SETSAR,      setsar,      vf);

    REGISTER_FILTER (SETTB,       settb,       vf);

    REGISTER_FILTER (SHOWINFO,    showinfo,    vf);

    REGISTER_FILTER (SLICIFY,     slicify,     vf);

    REGISTER_FILTER (SMARTBLUR,   smartblur,   vf);

    REGISTER_FILTER (SPLIT,       split,       vf);

    REGISTER_FILTER (SUPER2XSAI,  super2xsai,  vf);

    REGISTER_FILTER (SWAPUV,      swapuv,      vf);

    REGISTER_FILTER (THUMBNAIL,   thumbnail,   vf);

    REGISTER_FILTER (TILE,        tile,        vf);

    REGISTER_FILTER (TINTERLACE,  tinterlace,  vf);

    REGISTER_FILTER (TRANSPOSE,   transpose,   vf);

    REGISTER_FILTER (UNSHARP,     unsharp,     vf);

    REGISTER_FILTER (VFLIP,       vflip,       vf);

    REGISTER_FILTER (YADIF,       yadif,       vf);

    REGISTER_FILTER (CELLAUTO,    cellauto,    vsrc);

    REGISTER_FILTER (COLOR,       color,       vsrc);

    REGISTER_FILTER (FREI0R,      frei0r_src,  vsrc);

    REGISTER_FILTER (LIFE,        life,        vsrc);

    REGISTER_FILTER (MANDELBROT,  mandelbrot,  vsrc);

    REGISTER_FILTER (MPTESTSRC,   mptestsrc,   vsrc);

    REGISTER_FILTER (NULLSRC,     nullsrc,     vsrc);

    REGISTER_FILTER (RGBTESTSRC,  rgbtestsrc,  vsrc);

    REGISTER_FILTER (SMPTEBARS,   smptebars,   vsrc);

    REGISTER_FILTER (TESTSRC,     testsrc,     vsrc);

    REGISTER_FILTER (BUFFERSINK,  buffersink,  vsink);

    REGISTER_FILTER (FFBUFFERSINK,ffbuffersink,vsink);

    REGISTER_FILTER (NULLSINK,    nullsink,    vsink);

    /* multimedia filters */

    REGISTER_FILTER (CONCAT,      concat,      avf);

    REGISTER_FILTER (SHOWSPECTRUM,showspectrum,avf);

    REGISTER_FILTER (SHOWWAVES,   showwaves,   avf);

    /* multimedia sources */

    REGISTER_FILTER (AMOVIE,      amovie,      avsrc);

    REGISTER_FILTER (MOVIE,       movie,       avsrc);

    /* those filters are part of public or internal API => registered

     * unconditionally */

    {

        extern AVFilter avfilter_vsrc_buffer;

        avfilter_register(&avfilter_vsrc_buffer);

    }

    {

        extern AVFilter avfilter_asrc_abuffer;

        avfilter_register(&avfilter_asrc_abuffer);

    }

    {

        extern AVFilter avfilter_vsink_buffer;

        avfilter_register(&avfilter_vsink_buffer);

    }

    {

        extern AVFilter avfilter_asink_abuffer;

        avfilter_register(&avfilter_asink_abuffer);

    }

}


void show_banner(void)

{

    fprintf(stderr, "%s version " FFMPEG_VERSION ", Copyright (c) %d-%d the FFmpeg developers\n",

            program_name, program_birth_year, this_year);

    fprintf(stderr, "  built on %s %s with %s %s\n",

            __DATE__, __TIME__, CC_TYPE, CC_VERSION);

    fprintf(stderr, "  configuration: " FFMPEG_CONFIGURATION "\n");

    print_all_libs_info(stderr, INDENT|SHOW_CONFIG);

    print_all_libs_info(stderr, INDENT|SHOW_VERSION);

}


static int decode_delta_block (bit_buffer_t *bitbuf,

			uint8_t *current, uint8_t *previous, int pitch,

			svq1_pmv_t *motion, int x, int y) {

  uint32_t bit_cache;

  uint32_t block_type;

  int	   result = 0;

  /* get block type */

  bit_cache = get_bit_cache (bitbuf);

  bit_cache	>>= (32 - 3);

  block_type	  = block_type_table[bit_cache].value;

  skip_bits(bitbuf,block_type_table[bit_cache].length);

  /* reset motion vectors */

  if (block_type == SVQ1_BLOCK_SKIP || block_type == SVQ1_BLOCK_INTRA) {

    motion[0].x		  = 0;

    motion[0].y		  = 0;

    motion[(x / 8) + 2].x = 0;

    motion[(x / 8) + 2].y = 0;

    motion[(x / 8) + 3].x = 0;

    motion[(x / 8) + 3].y = 0;

  }

  switch (block_type) {

  case SVQ1_BLOCK_SKIP:

    skip_block (current, previous, pitch, x, y);

    break;

  case SVQ1_BLOCK_INTER:

    result = motion_inter_block (bitbuf, current, previous, pitch, motion, x, y);

    if (result != 0)

    {

#ifdef DEBUG_SVQ1

    printf("Error in motion_inter_block %i\n",result);

#endif

      break;

    }

    result = decode_svq1_block (bitbuf, current, pitch, 0);

    break;

  case SVQ1_BLOCK_INTER_4V:

    result = motion_inter_4v_block (bitbuf, current, previous, pitch, motion, x, y);

    if (result != 0)

    {

#ifdef DEBUG_SVQ1

    printf("Error in motion_inter_4v_block %i\n",result);

#endif

      break;

    }

    result = decode_svq1_block (bitbuf, current, pitch, 0);

    break;

  case SVQ1_BLOCK_INTRA:

    result = decode_svq1_block (bitbuf, current, pitch, 1);

    break;

  }

  return result;

}


static int pci_ich9_uninit(PCIDevice *dev)

{

    struct AHCIPCIState *d;

    d = DO_UPCAST(struct AHCIPCIState, card, dev);

    if (msi_enabled(dev)) {

        msi_uninit(dev);

    }

    qemu_unregister_reset(ahci_reset, d);

    ahci_uninit(&d->ahci);

    return 0;

}


void powerpc_display_perf_report(void)

{

  int i;

#ifndef POWERPC_PERF_USE_PMC

  fprintf(stderr, "PowerPC performance report\n Values are from the Time Base register, and represent 4 bus cycles.\n");

#else /* POWERPC_PERF_USE_PMC */

  fprintf(stderr, "PowerPC performance report\n Values are from the PMC registers, and represent whatever the registers are set to record.\n");

#endif /* POWERPC_PERF_USE_PMC */

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

  {

    if (perfdata[i][powerpc_data_num] != (unsigned long long)0)

      fprintf(stderr, " Function \"%s\" (pmc1):\n\tmin: %llu\n\tmax: %llu\n\tavg: %1.2lf (%llu)\n",

              perfname[i],

              perfdata[i][powerpc_data_min],

              perfdata[i][powerpc_data_max],

              (double)perfdata[i][powerpc_data_sum] /

              (double)perfdata[i][powerpc_data_num],

              perfdata[i][powerpc_data_num]);

#ifdef POWERPC_PERF_USE_PMC

    if (perfdata_pmc2[i][powerpc_data_num] != (unsigned long long)0)

      fprintf(stderr, " Function \"%s\" (pmc2):\n\tmin: %llu\n\tmax: %llu\n\tavg: %1.2lf (%llu)\n",

              perfname[i],

              perfdata_pmc2[i][powerpc_data_min],

              perfdata_pmc2[i][powerpc_data_max],

              (double)perfdata_pmc2[i][powerpc_data_sum] /

              (double)perfdata_pmc2[i][powerpc_data_num],

              perfdata_pmc2[i][powerpc_data_num]);

    if (perfdata_pmc3[i][powerpc_data_num] != (unsigned long long)0)

      fprintf(stderr, " Function \"%s\" (pmc3):\n\tmin: %llu\n\tmax: %llu\n\tavg: %1.2lf (%llu)\n",

              perfname[i],

              perfdata_pmc3[i][powerpc_data_min],

              perfdata_pmc3[i][powerpc_data_max],

              (double)perfdata_pmc3[i][powerpc_data_sum] /

              (double)perfdata_pmc3[i][powerpc_data_num],

              perfdata_pmc3[i][powerpc_data_num]);

#endif

  }

}


void ccw_dstream_init(CcwDataStream *cds, CCW1 const *ccw, ORB const *orb)
{
    /*
     * We don't support MIDA (an optional facility) yet and we
     * catch this earlier. Just for expressing the precondition.
     */
    g_assert(!(orb->ctrl1 & ORB_CTRL1_MASK_MIDAW));
    cds->flags = (orb->ctrl0 & ORB_CTRL0_MASK_I2K ? CDS_F_I2K : 0) |
                 (orb->ctrl0 & ORB_CTRL0_MASK_C64 ? CDS_F_C64 : 0) |
                 (ccw->flags & CCW_FLAG_IDA ? CDS_F_IDA : 0);
    cds->count = ccw->count;
    cds->cda_orig = ccw->cda;
    ccw_dstream_rewind(cds);
    if (!(cds->flags & CDS_F_IDA)) {
        cds->op_handler = ccw_dstream_rw_noflags;
    } else {
        assert(false);
    }
}


static int msrle_decode_pal4(AVCodecContext *avctx, AVPicture *pic,

                              const uint8_t *data, int data_size)

{

    int stream_ptr = 0;

    unsigned char rle_code;

    unsigned char extra_byte, odd_pixel;

    unsigned char stream_byte;

    int pixel_ptr = 0;

    int row_dec = pic->linesize[0];

    int row_ptr = (avctx->height - 1) * row_dec;

    int frame_size = row_dec * avctx->height;

    int i;

    while (row_ptr >= 0) {

        FETCH_NEXT_STREAM_BYTE();

        rle_code = stream_byte;

        if (rle_code == 0) {

            /* fetch the next byte to see how to handle escape code */

            FETCH_NEXT_STREAM_BYTE();

            if (stream_byte == 0) {

                /* line is done, goto the next one */

                row_ptr -= row_dec;

                pixel_ptr = 0;

            } else if (stream_byte == 1) {

                /* decode is done */

                return 0;

            } else if (stream_byte == 2) {

                /* reposition frame decode coordinates */

                FETCH_NEXT_STREAM_BYTE();

                pixel_ptr += stream_byte;

                FETCH_NEXT_STREAM_BYTE();

                row_ptr -= stream_byte * row_dec;

            } else {

                // copy pixels from encoded stream

                odd_pixel =  stream_byte & 1;

                rle_code = (stream_byte + 1) / 2;

                extra_byte = rle_code & 0x01;

                if (row_ptr + pixel_ptr + stream_byte > frame_size) {

                    av_log(avctx, AV_LOG_ERROR, " MS RLE: frame ptr just went out of bounds (1)\n");

                    return -1;

                }

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

                    if (pixel_ptr >= avctx->width)

                        break;

                    FETCH_NEXT_STREAM_BYTE();

                    pic->data[0][row_ptr + pixel_ptr] = stream_byte >> 4;

                    pixel_ptr++;

                    if (i + 1 == rle_code && odd_pixel)

                        break;

                    if (pixel_ptr >= avctx->width)

                        break;

                    pic->data[0][row_ptr + pixel_ptr] = stream_byte & 0x0F;

                    pixel_ptr++;

                }

                // if the RLE code is odd, skip a byte in the stream

                if (extra_byte)

                    stream_ptr++;

            }

        } else {

            // decode a run of data

            if (row_ptr + pixel_ptr + stream_byte > frame_size) {

                av_log(avctx, AV_LOG_ERROR, " MS RLE: frame ptr just went out of bounds (1)\n");

                return -1;

            }

            FETCH_NEXT_STREAM_BYTE();

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

                if (pixel_ptr >= avctx->width)

                    break;

                if ((i & 1) == 0)

                    pic->data[0][row_ptr + pixel_ptr] = stream_byte >> 4;

                else

                    pic->data[0][row_ptr + pixel_ptr] = stream_byte & 0x0F;

                pixel_ptr++;

            }

        }

    }

    /* one last sanity check on the way out */

    if (stream_ptr < data_size) {

        av_log(avctx, AV_LOG_ERROR, " MS RLE: ended frame decode with bytes left over (%d < %d)\n",

            stream_ptr, data_size);

        return -1;

    }

    return 0;

}


static int vnc_update_client(VncState *vs, int has_dirty, bool sync)

{

    vs->has_dirty += has_dirty;

    if (vs->need_update && vs->ioc != NULL) {

        VncDisplay *vd = vs->vd;

        VncJob *job;

        int y;

        int height, width;

        int n = 0;

        if (vs->output.offset && !vs->audio_cap && !vs->force_update)

            /* kernel send buffers are full -> drop frames to throttle */

            return 0;

        if (!vs->has_dirty && !vs->audio_cap && !vs->force_update)

            return 0;

        /*

         * Send screen updates to the vnc client using the server

         * surface and server dirty map.  guest surface updates

         * happening in parallel don't disturb us, the next pass will

         * send them to the client.

         */

        job = vnc_job_new(vs);

        height = pixman_image_get_height(vd->server);

        width = pixman_image_get_width(vd->server);

        y = 0;

        for (;;) {

            int x, h;

            unsigned long x2;

            unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,

                                                 height * VNC_DIRTY_BPL(vs),

                                                 y * VNC_DIRTY_BPL(vs));

            if (offset == height * VNC_DIRTY_BPL(vs)) {

                /* no more dirty bits */

                break;

            }

            y = offset / VNC_DIRTY_BPL(vs);

            x = offset % VNC_DIRTY_BPL(vs);

            x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],

                                    VNC_DIRTY_BPL(vs), x);

            bitmap_clear(vs->dirty[y], x, x2 - x);

            h = find_and_clear_dirty_height(vs, y, x, x2, height);

            x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);

            if (x2 > x) {

                n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,

                                      (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);

            }

            if (!x && x2 == width / VNC_DIRTY_PIXELS_PER_BIT) {

                y += h;

                if (y == height) {

                    break;

                }

            }

        }

        vnc_job_push(job);

        if (sync) {

            vnc_jobs_join(vs);

        }

        vs->force_update = 0;

        vs->has_dirty = 0;

        return n;

    }

    if (vs->disconnecting) {

        vnc_disconnect_finish(vs);

    } else if (sync) {

        vnc_jobs_join(vs);

    }

    return 0;

}


static void vc1_mc_4mv_chroma4(VC1Context *v)

{

    MpegEncContext *s = &v->s;

    DSPContext *dsp = &v->s.dsp;

    uint8_t *srcU, *srcV;

    int uvsrc_x, uvsrc_y;

    int uvmx_field[4], uvmy_field[4];

    int i, off, tx, ty;

    int fieldmv = v->blk_mv_type[s->block_index[0]];

    static const int s_rndtblfield[16] = { 0, 0, 1, 2, 4, 4, 5, 6, 2, 2, 3, 8, 6, 6, 7, 12 };

    int v_dist = fieldmv ? 1 : 4; // vertical offset for lower sub-blocks

    int v_edge_pos = s->v_edge_pos >> 1;

    if (!v->s.last_picture.f.data[0])

        return;

    if (s->flags & CODEC_FLAG_GRAY)

        return;

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

        tx = s->mv[0][i][0];

        uvmx_field[i] = (tx + ((tx & 3) == 3)) >> 1;

        ty = s->mv[0][i][1];

        if (fieldmv)

            uvmy_field[i] = (ty >> 4) * 8 + s_rndtblfield[ty & 0xF];

        else

            uvmy_field[i] = (ty + ((ty & 3) == 3)) >> 1;

    }

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

        off = (i & 1) * 4 + ((i & 2) ? v_dist * s->uvlinesize : 0);

        uvsrc_x = s->mb_x * 8 +  (i & 1) * 4           + (uvmx_field[i] >> 2);

        uvsrc_y = s->mb_y * 8 + ((i & 2) ? v_dist : 0) + (uvmy_field[i] >> 2);

        // FIXME: implement proper pull-back (see vc1cropmv.c, vc1CROPMV_ChromaPullBack())

        uvsrc_x = av_clip(uvsrc_x, -8, s->avctx->coded_width  >> 1);

        uvsrc_y = av_clip(uvsrc_y, -8, s->avctx->coded_height >> 1);

        srcU = s->last_picture.f.data[1] + uvsrc_y * s->uvlinesize + uvsrc_x;

        srcV = s->last_picture.f.data[2] + uvsrc_y * s->uvlinesize + uvsrc_x;

        uvmx_field[i] = (uvmx_field[i] & 3) << 1;

        uvmy_field[i] = (uvmy_field[i] & 3) << 1;

        if (fieldmv && !(uvsrc_y & 1))

            v_edge_pos--;

        if (fieldmv && (uvsrc_y & 1) && uvsrc_y < 2)

            uvsrc_y--;

        if ((v->mv_mode == MV_PMODE_INTENSITY_COMP)

            || s->h_edge_pos < 10 || v_edge_pos < (5 << fieldmv)

            || (unsigned)uvsrc_x > (s->h_edge_pos >> 1) - 5

            || (unsigned)uvsrc_y > v_edge_pos - (5 << fieldmv)) {

            s->dsp.emulated_edge_mc(s->edge_emu_buffer, srcU, s->uvlinesize,

                                    5, (5 << fieldmv), uvsrc_x, uvsrc_y,

                                    s->h_edge_pos >> 1, v_edge_pos);

            s->dsp.emulated_edge_mc(s->edge_emu_buffer + 16, srcV, s->uvlinesize,

                                    5, (5 << fieldmv), uvsrc_x, uvsrc_y,

                                    s->h_edge_pos >> 1, v_edge_pos);

            srcU = s->edge_emu_buffer;

            srcV = s->edge_emu_buffer + 16;

            /* if we deal with intensity compensation we need to scale source blocks */

            if (v->mv_mode == MV_PMODE_INTENSITY_COMP) {

                int i, j;

                uint8_t *src, *src2;

                src  = srcU;

                src2 = srcV;

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

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

                        src[i]  = v->lutuv[src[i]];

                        src2[i] = v->lutuv[src2[i]];

                    }

                    src  += s->uvlinesize << 1;

                    src2 += s->uvlinesize << 1;

                }

            }

        }

        if (!v->rnd) {

            dsp->put_h264_chroma_pixels_tab[1](s->dest[1] + off, srcU, s->uvlinesize << fieldmv, 4, uvmx_field[i], uvmy_field[i]);

            dsp->put_h264_chroma_pixels_tab[1](s->dest[2] + off, srcV, s->uvlinesize << fieldmv, 4, uvmx_field[i], uvmy_field[i]);

        } else {

            v->vc1dsp.put_no_rnd_vc1_chroma_pixels_tab[1](s->dest[1] + off, srcU, s->uvlinesize << fieldmv, 4, uvmx_field[i], uvmy_field[i]);

            v->vc1dsp.put_no_rnd_vc1_chroma_pixels_tab[1](s->dest[2] + off, srcV, s->uvlinesize << fieldmv, 4, uvmx_field[i], uvmy_field[i]);

        }

    }

}


static void vga_invalidate_display(void *opaque)

{

    VGAState *s = (VGAState *)opaque;

    s->last_width = -1;

    s->last_height = -1;

}


static void virtio_setup(uint64_t dev_info)

{

    struct schib schib;

    int ssid;

    bool found = false;

    uint16_t dev_no;

    /*

     * We unconditionally enable mss support. In every sane configuration,

     * this will succeed; and even if it doesn't, stsch_err() can deal

     * with the consequences.

     */

    enable_mss_facility();

    if (dev_info != -1) {

        dev_no = dev_info & 0xffff;

        debug_print_int("device no. ", dev_no);

        blk_schid.ssid = (dev_info >> 16) & 0x3;

        debug_print_int("ssid ", blk_schid.ssid);

        found = find_dev(&schib, dev_no);

    } else {

        for (ssid = 0; ssid < 0x3; ssid++) {

            blk_schid.ssid = ssid;

            found = find_dev(&schib, -1);

            if (found) {

                break;

            }

        }

    }

    if (!found) {

        virtio_panic("No virtio-blk device found!\n");

    }

    virtio_setup_block(blk_schid);

    if (!virtio_ipl_disk_is_valid()) {

        virtio_panic("No valid hard disk detected.\n");

    }

}


static void qemu_cleanup_net_client(NetClientState *nc)

{

    QTAILQ_REMOVE(&net_clients, nc, next);

    nc->info->cleanup(nc);

}


static void tcg_out_op (TCGContext *s, int opc, const TCGArg *args,

                        const int *const_args)

{

    int c;

    switch (opc) {

    case INDEX_op_exit_tb:

        tcg_out_movi (s, TCG_TYPE_I64, TCG_REG_R3, args[0]);

        tcg_out_b (s, 0, (tcg_target_long) tb_ret_addr);

        break;

    case INDEX_op_goto_tb:

        if (s->tb_jmp_offset) {

            /* direct jump method */

            s->tb_jmp_offset[args[0]] = s->code_ptr - s->code_buf;

            s->code_ptr += 28;

        }

        else {

            tcg_abort ();

        }

        s->tb_next_offset[args[0]] = s->code_ptr - s->code_buf;

        break;

    case INDEX_op_br:

        {

            TCGLabel *l = &s->labels[args[0]];

            if (l->has_value) {

                tcg_out_b (s, 0, l->u.value);

            }

            else {

                uint32_t val = *(uint32_t *) s->code_ptr;

                /* Thanks to Andrzej Zaborowski */

                tcg_out32 (s, B | (val & 0x3fffffc));

                tcg_out_reloc (s, s->code_ptr - 4, R_PPC_REL24, args[0], 0);

            }

        }

        break;

    case INDEX_op_call:

        tcg_out_call (s, args[0], const_args[0]);

        break;

    case INDEX_op_jmp:

        if (const_args[0]) {

            tcg_out_b (s, 0, args[0]);

        }

        else {

            tcg_out32 (s, MTSPR | RS (args[0]) | CTR);

            tcg_out32 (s, BCCTR | BO_ALWAYS);

        }

        break;

    case INDEX_op_movi_i32:

        tcg_out_movi (s, TCG_TYPE_I32, args[0], args[1]);

        break;

    case INDEX_op_movi_i64:

        tcg_out_movi (s, TCG_TYPE_I64, args[0], args[1]);

        break;

    case INDEX_op_ld8u_i32:

    case INDEX_op_ld8u_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], LBZ, LBZX);

        break;

    case INDEX_op_ld8s_i32:

    case INDEX_op_ld8s_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], LBZ, LBZX);

        tcg_out32 (s, EXTSB | RS (args[0]) | RA (args[0]));

        break;

    case INDEX_op_ld16u_i32:

    case INDEX_op_ld16u_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], LHZ, LHZX);

        break;

    case INDEX_op_ld16s_i32:

    case INDEX_op_ld16s_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], LHA, LHAX);

        break;

    case INDEX_op_ld_i32:

    case INDEX_op_ld32u_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], LWZ, LWZX);

        break;

    case INDEX_op_ld32s_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], LWA, LWAX);

        break;

    case INDEX_op_ld_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], LD, LDX);

        break;

    case INDEX_op_st8_i32:

    case INDEX_op_st8_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], STB, STBX);

        break;

    case INDEX_op_st16_i32:

    case INDEX_op_st16_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], STH, STHX);

        break;

    case INDEX_op_st_i32:

    case INDEX_op_st32_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], STW, STWX);

        break;

    case INDEX_op_st_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], STD, STDX);

        break;

    case INDEX_op_add_i32:

        if (const_args[2])

            ppc_addi32 (s, args[0], args[1], args[2]);

        else

            tcg_out32 (s, ADD | TAB (args[0], args[1], args[2]));

        break;

    case INDEX_op_sub_i32:

        if (const_args[2])

            ppc_addi32 (s, args[0], args[1], -args[2]);

        else

            tcg_out32 (s, SUBF | TAB (args[0], args[2], args[1]));

        break;

    case INDEX_op_and_i64:

    case INDEX_op_and_i32:

        if (const_args[2]) {

            if ((args[2] & 0xffff) == args[2])

                tcg_out32 (s, ANDI | RS (args[1]) | RA (args[0]) | args[2]);

            else if ((args[2] & 0xffff0000) == args[2])

                tcg_out32 (s, ANDIS | RS (args[1]) | RA (args[0])

                           | ((args[2] >> 16) & 0xffff));

            else {

                tcg_out_movi (s, (opc == INDEX_op_and_i32

                                  ? TCG_TYPE_I32

                                  : TCG_TYPE_I64),

                              0, args[2]);

                tcg_out32 (s, AND | SAB (args[1], args[0], 0));

            }

        }

        else

            tcg_out32 (s, AND | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_or_i64:

    case INDEX_op_or_i32:

        if (const_args[2]) {

            if (args[2] & 0xffff) {

                tcg_out32 (s, ORI | RS (args[1]) | RA (args[0])

                           | (args[2] & 0xffff));

                if (args[2] >> 16)

                    tcg_out32 (s, ORIS | RS (args[0])  | RA (args[0])

                               | ((args[2] >> 16) & 0xffff));

            }

            else {

                tcg_out32 (s, ORIS | RS (args[1])  | RA (args[0])

                           | ((args[2] >> 16) & 0xffff));

            }

        }

        else

            tcg_out32 (s, OR | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_xor_i64:

    case INDEX_op_xor_i32:

        if (const_args[2]) {

            if ((args[2] & 0xffff) == args[2])

                tcg_out32 (s, XORI | RS (args[1])  | RA (args[0])

                           | (args[2] & 0xffff));

            else if ((args[2] & 0xffff0000) == args[2])

                tcg_out32 (s, XORIS | RS (args[1])  | RA (args[0])

                           | ((args[2] >> 16) & 0xffff));

            else {

                tcg_out_movi (s, (opc == INDEX_op_and_i32

                                  ? TCG_TYPE_I32

                                  : TCG_TYPE_I64),

                              0, args[2]);

                tcg_out32 (s, XOR | SAB (args[1], args[0], 0));

            }

        }

        else

            tcg_out32 (s, XOR | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_mul_i32:

        if (const_args[2]) {

            if (args[2] == (int16_t) args[2])

                tcg_out32 (s, MULLI | RT (args[0]) | RA (args[1])

                           | (args[2] & 0xffff));

            else {

                tcg_out_movi (s, TCG_TYPE_I32, 0, args[2]);

                tcg_out32 (s, MULLW | TAB (args[0], args[1], 0));

            }

        }

        else

            tcg_out32 (s, MULLW | TAB (args[0], args[1], args[2]));

        break;

    case INDEX_op_div_i32:

        tcg_out32 (s, DIVW | TAB (args[0], args[1], args[2]));

        break;

    case INDEX_op_divu_i32:

        tcg_out32 (s, DIVWU | TAB (args[0], args[1], args[2]));

        break;

    case INDEX_op_rem_i32:

        tcg_out32 (s, DIVW | TAB (0, args[1], args[2]));

        tcg_out32 (s, MULLW | TAB (0, 0, args[2]));

        tcg_out32 (s, SUBF | TAB (args[0], 0, args[1]));

        break;

    case INDEX_op_remu_i32:

        tcg_out32 (s, DIVWU | TAB (0, args[1], args[2]));

        tcg_out32 (s, MULLW | TAB (0, 0, args[2]));

        tcg_out32 (s, SUBF | TAB (args[0], 0, args[1]));

        break;

    case INDEX_op_shl_i32:

        if (const_args[2]) {

            tcg_out32 (s, (RLWINM

                           | RA (args[0])

                           | RS (args[1])

                           | SH (args[2])

                           | MB (0)

                           | ME (31 - args[2])

                           )

                );

        }

        else

            tcg_out32 (s, SLW | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_shr_i32:

        if (const_args[2]) {

            tcg_out32 (s, (RLWINM

                           | RA (args[0])

                           | RS (args[1])

                           | SH (32 - args[2])

                           | MB (args[2])

                           | ME (31)

                           )

                );

        }

        else

            tcg_out32 (s, SRW | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_sar_i32:

        if (const_args[2])

            tcg_out32 (s, SRAWI | RS (args[1]) | RA (args[0]) | SH (args[2]));

        else

            tcg_out32 (s, SRAW | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_brcond_i32:

        tcg_out_brcond (s, args[2], args[0], args[1], const_args[1], args[3], 0);

        break;

    case INDEX_op_brcond_i64:

        tcg_out_brcond (s, args[2], args[0], args[1], const_args[1], args[3], 1);

        break;

    case INDEX_op_neg_i32:

    case INDEX_op_neg_i64:

        tcg_out32 (s, NEG | RT (args[0]) | RA (args[1]));

        break;

    case INDEX_op_add_i64:

        if (const_args[2])

            ppc_addi64 (s, args[0], args[1], args[2]);

        else

            tcg_out32 (s, ADD | TAB (args[0], args[1], args[2]));

        break;

    case INDEX_op_sub_i64:

        if (const_args[2])

            ppc_addi64 (s, args[0], args[1], -args[2]);

        else

            tcg_out32 (s, SUBF | TAB (args[0], args[2], args[1]));

        break;

    case INDEX_op_shl_i64:

        if (const_args[2])

            tcg_out_rld (s, RLDICR, args[0], args[1], args[2], 63 - args[2]);

        else

            tcg_out32 (s, SLD | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_shr_i64:

        if (const_args[2])

            tcg_out_rld (s, RLDICL, args[0], args[1], 64 - args[2], args[2]);

        else

            tcg_out32 (s, SRD | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_sar_i64:

        if (const_args[2]) {

            int sh = SH (args[2] & 0x1f) | (((args[2] >> 5) & 1) << 1);

            tcg_out32 (s, SRADI | RA (args[0]) | RS (args[1]) | sh);

        }

        else

            tcg_out32 (s, SRAD | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_mul_i64:

        tcg_out32 (s, MULLD | TAB (args[0], args[1], args[2]));

        break;

    case INDEX_op_div_i64:

        tcg_out32 (s, DIVD | TAB (args[0], args[1], args[2]));

        break;

    case INDEX_op_divu_i64:

        tcg_out32 (s, DIVDU | TAB (args[0], args[1], args[2]));

        break;

    case INDEX_op_rem_i64:

        tcg_out32 (s, DIVD | TAB (0, args[1], args[2]));

        tcg_out32 (s, MULLD | TAB (0, 0, args[2]));

        tcg_out32 (s, SUBF | TAB (args[0], 0, args[1]));

        break;

    case INDEX_op_remu_i64:

        tcg_out32 (s, DIVDU | TAB (0, args[1], args[2]));

        tcg_out32 (s, MULLD | TAB (0, 0, args[2]));

        tcg_out32 (s, SUBF | TAB (args[0], 0, args[1]));

        break;

    case INDEX_op_qemu_ld8u:

        tcg_out_qemu_ld (s, args, 0);

        break;

    case INDEX_op_qemu_ld8s:

        tcg_out_qemu_ld (s, args, 0 | 4);

        break;

    case INDEX_op_qemu_ld16u:

        tcg_out_qemu_ld (s, args, 1);

        break;

    case INDEX_op_qemu_ld16s:

        tcg_out_qemu_ld (s, args, 1 | 4);

        break;

    case INDEX_op_qemu_ld32u:

        tcg_out_qemu_ld (s, args, 2);

        break;

    case INDEX_op_qemu_ld32s:

        tcg_out_qemu_ld (s, args, 2 | 4);

        break;

    case INDEX_op_qemu_ld64:

        tcg_out_qemu_ld (s, args, 3);

        break;

    case INDEX_op_qemu_st8:

        tcg_out_qemu_st (s, args, 0);

        break;

    case INDEX_op_qemu_st16:

        tcg_out_qemu_st (s, args, 1);

        break;

    case INDEX_op_qemu_st32:

        tcg_out_qemu_st (s, args, 2);

        break;

    case INDEX_op_qemu_st64:

        tcg_out_qemu_st (s, args, 3);

        break;

    case INDEX_op_ext8s_i32:

    case INDEX_op_ext8s_i64:

        c = EXTSB;

        goto gen_ext;

    case INDEX_op_ext16s_i32:

    case INDEX_op_ext16s_i64:

        c = EXTSH;

        goto gen_ext;

    case INDEX_op_ext32s_i64:

        c = EXTSW;

        goto gen_ext;

    gen_ext:

        tcg_out32 (s, c | RS (args[1]) | RA (args[0]));

        break;

    default:

        tcg_dump_ops (s, stderr);

        tcg_abort ();

    }

}


static int socket_accept(int sock)

{

    struct sockaddr_un addr;

    socklen_t addrlen;

    int ret;

    addrlen = sizeof(addr);

    do {

        ret = accept(sock, (struct sockaddr *)&addr, &addrlen);

    } while (ret == -1 && errno == EINTR);

    g_assert_no_errno(ret);

    close(sock);

    return ret;

}


ivshmem_server_handle_new_conn(IvshmemServer *server)

{

    IvshmemServerPeer *peer, *other_peer;

    struct sockaddr_un unaddr;

    socklen_t unaddr_len;

    int newfd;

    unsigned i;

    /* accept the incoming connection */

    unaddr_len = sizeof(unaddr);

    newfd = qemu_accept(server->sock_fd,

                        (struct sockaddr *)&unaddr, &unaddr_len);

    if (newfd < 0) {

        IVSHMEM_SERVER_DEBUG(server, "cannot accept() %s\n", strerror(errno));

        return -1;

    }

    qemu_set_nonblock(newfd);

    IVSHMEM_SERVER_DEBUG(server, "accept()=%d\n", newfd);

    /* allocate new structure for this peer */

    peer = g_malloc0(sizeof(*peer));

    peer->sock_fd = newfd;

    /* get an unused peer id */

    /* XXX: this could use id allocation such as Linux IDA, or simply

     * a free-list */

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

        if (ivshmem_server_search_peer(server, server->cur_id) == NULL) {

            break;

        }

        server->cur_id++;

    }

    if (i == G_MAXUINT16) {

        IVSHMEM_SERVER_DEBUG(server, "cannot allocate new client id\n");

        goto fail;

    }

    peer->id = server->cur_id++;

    /* create eventfd, one per vector */

    peer->vectors_count = server->n_vectors;

    for (i = 0; i < peer->vectors_count; i++) {

        if (event_notifier_init(&peer->vectors[i], FALSE) < 0) {

            IVSHMEM_SERVER_DEBUG(server, "cannot create eventfd\n");

            goto fail;

        }

    }

    /* send peer id and shm fd */

    if (ivshmem_server_send_initial_info(server, peer) < 0) {

        IVSHMEM_SERVER_DEBUG(server, "cannot send initial info\n");

        goto fail;

    }

    /* advertise the new peer to others */

    QTAILQ_FOREACH(other_peer, &server->peer_list, next) {

        for (i = 0; i < peer->vectors_count; i++) {

            ivshmem_server_send_one_msg(other_peer->sock_fd, peer->id,

                                        peer->vectors[i].wfd);

        }

    }

    /* advertise the other peers to the new one */

    QTAILQ_FOREACH(other_peer, &server->peer_list, next) {

        for (i = 0; i < peer->vectors_count; i++) {

            ivshmem_server_send_one_msg(peer->sock_fd, other_peer->id,

                                        other_peer->vectors[i].wfd);

        }

    }

    /* advertise the new peer to itself */

    for (i = 0; i < peer->vectors_count; i++) {

        ivshmem_server_send_one_msg(peer->sock_fd, peer->id,

                                    event_notifier_get_fd(&peer->vectors[i]));

    }

    QTAILQ_INSERT_TAIL(&server->peer_list, peer, next);

    IVSHMEM_SERVER_DEBUG(server, "new peer id = %" PRId64 "\n",

                         peer->id);

    return 0;

fail:

    while (i--) {

        event_notifier_cleanup(&peer->vectors[i]);

    }

    close(newfd);

    g_free(peer);

    return -1;

}


static int mjpegb_decode_frame(AVCodecContext *avctx,

                              void *data, int *data_size,

                              UINT8 *buf, int buf_size)

{

    MJpegDecodeContext *s = avctx->priv_data;

    UINT8 *buf_end, *buf_ptr;

    int i;

    AVPicture *picture = data;

    GetBitContext hgb; /* for the header */

    uint32_t dqt_offs, dht_offs, sof_offs, sos_offs, second_field_offs;

    uint32_t field_size;

    *data_size = 0;

    /* no supplementary picture */

    if (buf_size == 0)

        return 0;

    buf_ptr = buf;

    buf_end = buf + buf_size;

read_header:

    /* reset on every SOI */

    s->restart_interval = 0;

    init_get_bits(&hgb, buf_ptr, /*buf_size*/buf_end - buf_ptr);

    skip_bits(&hgb, 32); /* reserved zeros */

    if (get_bits(&hgb, 32) != be2me_32(ff_get_fourcc("mjpg")))

    {

	dprintf("not mjpeg-b (bad fourcc)\n");

	return 0;

    }

    field_size = get_bits(&hgb, 32); /* field size */

    dprintf("field size: 0x%x\n", field_size);

    skip_bits(&hgb, 32); /* padded field size */

    second_field_offs = get_bits(&hgb, 32);

    dprintf("second field offs: 0x%x\n", second_field_offs);

    if (second_field_offs)

	s->interlaced = 1;

    dqt_offs = get_bits(&hgb, 32);

    dprintf("dqt offs: 0x%x\n", dqt_offs);

    if (dqt_offs)

    {

	init_get_bits(&s->gb, buf+dqt_offs, buf_end - (buf+dqt_offs));

	s->start_code = DQT;

	mjpeg_decode_dqt(s);

    }

    dht_offs = get_bits(&hgb, 32);

    dprintf("dht offs: 0x%x\n", dht_offs);

    if (dht_offs)

    {

	init_get_bits(&s->gb, buf+dht_offs, buf_end - (buf+dht_offs));

	s->start_code = DHT;

	mjpeg_decode_dht(s);

    }

    sof_offs = get_bits(&hgb, 32);

    dprintf("sof offs: 0x%x\n", sof_offs);

    if (sof_offs)

    {

	init_get_bits(&s->gb, buf+sof_offs, buf_end - (buf+sof_offs));

	s->start_code = SOF0;

	if (mjpeg_decode_sof0(s) < 0)

	    return -1;

    }

    sos_offs = get_bits(&hgb, 32);

    dprintf("sos offs: 0x%x\n", sos_offs);

    if (sos_offs)

    {

//	init_get_bits(&s->gb, buf+sos_offs, buf_end - (buf+sos_offs));

	init_get_bits(&s->gb, buf+sos_offs, field_size);

	s->start_code = SOS;

	mjpeg_decode_sos(s);

    }

    skip_bits(&hgb, 32); /* start of data offset */

    if (s->interlaced) {

        s->bottom_field ^= 1;

        /* if not bottom field, do not output image yet */

        if (s->bottom_field && second_field_offs)

	{

	    buf_ptr = buf + second_field_offs;

	    second_field_offs = 0;

	    goto read_header;

    	}

    }

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

        picture->data[i] = s->current_picture[i];

        picture->linesize[i] = (s->interlaced) ?

    	    s->linesize[i] >> 1 : s->linesize[i];

    }

    *data_size = sizeof(AVPicture);

    avctx->height = s->height;

    if (s->interlaced)

        avctx->height *= 2;

    avctx->width = s->width;

    /* XXX: not complete test ! */

    switch((s->h_count[0] << 4) | s->v_count[0]) {

        case 0x11:

    	    avctx->pix_fmt = PIX_FMT_YUV444P;

            break;

        case 0x21:

            avctx->pix_fmt = PIX_FMT_YUV422P;

            break;

        default:

	case 0x22:

            avctx->pix_fmt = PIX_FMT_YUV420P;

            break;

    }

    /* dummy quality */

    /* XXX: infer it with matrix */

//    avctx->quality = 3;

    return buf_ptr - buf;

}


static int idcin_read_seek(AVFormatContext *s, int stream_index,

                           int64_t timestamp, int flags)

{

    IdcinDemuxContext *idcin = s->priv_data;

    if (idcin->first_pkt_pos > 0) {

        int ret = avio_seek(s->pb, idcin->first_pkt_pos, SEEK_SET);

        if (ret < 0)

            return ret;

        ff_update_cur_dts(s, s->streams[idcin->video_stream_index], 0);

        idcin->next_chunk_is_video = 1;

        idcin->current_audio_chunk = 0;

        return 0;

    }

    return -1;

}


static int multiwrite_req_compare(const void *a, const void *b)

{

    return (((BlockRequest*) a)->sector - ((BlockRequest*) b)->sector);

}


static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
{
    AVFrame *src = srcp->f;
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
    int i;
    int ret = av_frame_ref(dst, src);
    if (ret < 0)
        return ret;
    av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
    if (srcp->sei_recovery_frame_cnt == 0)
        dst->key_frame = 1;
    if (!srcp->crop)
        return 0;
    for (i = 0; i < desc->nb_components; i++) {
        int hshift = (i > 0) ? desc->log2_chroma_w : 0;
        int vshift = (i > 0) ? desc->log2_chroma_h : 0;
        int off    = ((srcp->crop_left >> hshift) << h->pixel_shift) +
                      (srcp->crop_top  >> vshift) * dst->linesize[i];
        dst->data[i] += off;
    }
    return 0;
}