static int handle_secondary_tcp_pkt(NetFilterState *nf,

                                    Connection *conn,

                                    Packet *pkt)

{

    struct tcphdr *tcp_pkt;

    tcp_pkt = (struct tcphdr *)pkt->transport_header;

    if (trace_event_get_state(TRACE_COLO_FILTER_REWRITER_DEBUG)) {

        trace_colo_filter_rewriter_pkt_info(__func__,

                    inet_ntoa(pkt->ip->ip_src), inet_ntoa(pkt->ip->ip_dst),

                    ntohl(tcp_pkt->th_seq), ntohl(tcp_pkt->th_ack),

                    tcp_pkt->th_flags);

        trace_colo_filter_rewriter_conn_offset(conn->offset);

    }

    if (((tcp_pkt->th_flags & (TH_ACK | TH_SYN)) == (TH_ACK | TH_SYN))) {

        /*

         * save offset = secondary_seq and then

         * in handle_primary_tcp_pkt make offset

         * = secondary_seq - primary_seq

         */

        conn->offset = ntohl(tcp_pkt->th_seq);

    }

    if ((tcp_pkt->th_flags & (TH_ACK | TH_SYN)) == TH_ACK) {

        /* handle packets to the primary from the secondary*/

        tcp_pkt->th_seq = htonl(ntohl(tcp_pkt->th_seq) - conn->offset);

        net_checksum_calculate((uint8_t *)pkt->data, pkt->size);

    }

    return 0;

}


static void nvdimm_dsm_reserved_root(AcpiNVDIMMState *state, NvdimmDsmIn *in,

                                     hwaddr dsm_mem_addr)

{

    switch (in->function) {

    case 0x0:

        nvdimm_dsm_function0(0x1 | 1 << 1 /* Read FIT */, dsm_mem_addr);

        return;

    case 0x1 /* Read FIT */:

        nvdimm_dsm_func_read_fit(state, in, dsm_mem_addr);

        return;

    }

    nvdimm_dsm_no_payload(NVDIMM_DSM_RET_STATUS_UNSUPPORT, dsm_mem_addr);

}


static void omap_prcm_dpll_update(struct omap_prcm_s *s)

{

    omap_clk dpll = omap_findclk(s->mpu, "dpll");

    omap_clk dpll_x2 = omap_findclk(s->mpu, "dpll");

    omap_clk core = omap_findclk(s->mpu, "core_clk");

    int mode = (s->clken[9] >> 0) & 3;

    int mult, div;

    mult = (s->clksel[5] >> 12) & 0x3ff;

    div = (s->clksel[5] >> 8) & 0xf;

    if (mult == 0 || mult == 1)

        mode = 1;	/* Bypass */

    s->dpll_lock = 0;

    switch (mode) {

    case 0:

        fprintf(stderr, "%s: bad EN_DPLL\n", __FUNCTION__);

        break;

    case 1:	/* Low-power bypass mode (Default) */

    case 2:	/* Fast-relock bypass mode */

        omap_clk_setrate(dpll, 1, 1);

        omap_clk_setrate(dpll_x2, 1, 1);

        break;

    case 3:	/* Lock mode */

        s->dpll_lock = 1; /* After 20 FINT cycles (ref_clk / (div + 1)).  */

        omap_clk_setrate(dpll, div + 1, mult);

        omap_clk_setrate(dpll_x2, div + 1, mult * 2);

        break;

    }

    switch ((s->clksel[6] >> 0) & 3) {

    case 0:

        omap_clk_reparent(core, omap_findclk(s->mpu, "clk32-kHz"));

        break;

    case 1:

        omap_clk_reparent(core, dpll);

        break;

    case 2:

        /* Default */

        omap_clk_reparent(core, dpll_x2);

        break;

    case 3:

        fprintf(stderr, "%s: bad CORE_CLK_SRC\n", __FUNCTION__);

        break;

    }

}


void HELPER(dc_zva)(CPUARMState *env, uint64_t vaddr_in)

{

    /* Implement DC ZVA, which zeroes a fixed-length block of memory.

     * Note that we do not implement the (architecturally mandated)

     * alignment fault for attempts to use this on Device memory

     * (which matches the usual QEMU behaviour of not implementing either

     * alignment faults or any memory attribute handling).

     */

    ARMCPU *cpu = arm_env_get_cpu(env);

    uint64_t blocklen = 4 << cpu->dcz_blocksize;

    uint64_t vaddr = vaddr_in & ~(blocklen - 1);

#ifndef CONFIG_USER_ONLY

    {

        /* Slightly awkwardly, QEMU's TARGET_PAGE_SIZE may be less than

         * the block size so we might have to do more than one TLB lookup.

         * We know that in fact for any v8 CPU the page size is at least 4K

         * and the block size must be 2K or less, but TARGET_PAGE_SIZE is only

         * 1K as an artefact of legacy v5 subpage support being present in the

         * same QEMU executable.

         */

        int maxidx = DIV_ROUND_UP(blocklen, TARGET_PAGE_SIZE);

        void *hostaddr[maxidx];

        int try, i;

        unsigned mmu_idx = cpu_mmu_index(env, false);

        TCGMemOpIdx oi = make_memop_idx(MO_UB, mmu_idx);

        for (try = 0; try < 2; try++) {

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

                hostaddr[i] = tlb_vaddr_to_host(env,

                                                vaddr + TARGET_PAGE_SIZE * i,

                                                1, mmu_idx);

                if (!hostaddr[i]) {

                    break;

                }

            }

            if (i == maxidx) {

                /* If it's all in the TLB it's fair game for just writing to;

                 * we know we don't need to update dirty status, etc.

                 */

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

                    memset(hostaddr[i], 0, TARGET_PAGE_SIZE);

                }

                memset(hostaddr[i], 0, blocklen - (i * TARGET_PAGE_SIZE));

                return;

            }

            /* OK, try a store and see if we can populate the tlb. This

             * might cause an exception if the memory isn't writable,

             * in which case we will longjmp out of here. We must for

             * this purpose use the actual register value passed to us

             * so that we get the fault address right.

             */

            helper_ret_stb_mmu(env, vaddr_in, 0, oi, GETRA());

            /* Now we can populate the other TLB entries, if any */

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

                uint64_t va = vaddr + TARGET_PAGE_SIZE * i;

                if (va != (vaddr_in & TARGET_PAGE_MASK)) {

                    helper_ret_stb_mmu(env, va, 0, oi, GETRA());

                }

            }

        }

        /* Slow path (probably attempt to do this to an I/O device or

         * similar, or clearing of a block of code we have translations

         * cached for). Just do a series of byte writes as the architecture

         * demands. It's not worth trying to use a cpu_physical_memory_map(),

         * memset(), unmap() sequence here because:

         *  + we'd need to account for the blocksize being larger than a page

         *  + the direct-RAM access case is almost always going to be dealt

         *    with in the fastpath code above, so there's no speed benefit

         *  + we would have to deal with the map returning NULL because the

         *    bounce buffer was in use

         */

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

            helper_ret_stb_mmu(env, vaddr + i, 0, oi, GETRA());

        }

    }

#else

    memset(g2h(vaddr), 0, blocklen);

#endif

}


static void slirp_bootp_load(QEMUFile *f, Slirp *slirp)

{

    int i;

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

        slirp->bootp_clients[i].allocated = qemu_get_be16(f);

        qemu_get_buffer(f, slirp->bootp_clients[i].macaddr, 6);

    }

}


static int scsi_handle_rw_error(SCSIDiskReq *r, int error)

{

    bool is_read = (r->req.cmd.xfer == SCSI_XFER_FROM_DEV);

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);

    BlockErrorAction action = bdrv_get_error_action(s->qdev.conf.bs, is_read, error);

    if (action == BLOCK_ERROR_ACTION_REPORT) {

        switch (error) {

        case ENOMEDIUM:

            scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));

            break;

        case ENOMEM:

            scsi_check_condition(r, SENSE_CODE(TARGET_FAILURE));

            break;

        case EINVAL:

            scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));

            break;

        case ENOSPC:

            scsi_check_condition(r, SENSE_CODE(SPACE_ALLOC_FAILED));

            break;

        default:

            scsi_check_condition(r, SENSE_CODE(IO_ERROR));

            break;

        }

    }

    bdrv_error_action(s->qdev.conf.bs, action, is_read, error);

    if (action == BLOCK_ERROR_ACTION_STOP) {

        scsi_req_retry(&r->req);

    }

    return action != BLOCK_ERROR_ACTION_IGNORE;

}


void migrate_fd_connect(MigrationState *s)

{

    s->state = MIG_STATE_ACTIVE;

    trace_migrate_set_state(MIG_STATE_ACTIVE);

    s->bytes_xfer = 0;

    /* This is a best 1st approximation. ns to ms */

    s->expected_downtime = max_downtime/1000000;

    s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);

    s->file = qemu_fopen_ops(s, &migration_file_ops);

    qemu_file_set_rate_limit(s->file,

                             s->bandwidth_limit / XFER_LIMIT_RATIO);

    qemu_thread_create(&s->thread, migration_thread, s,

                       QEMU_THREAD_JOINABLE);

    notifier_list_notify(&migration_state_notifiers, s);

}


void *iommu_dma_memory_map(DMAContext *dma, dma_addr_t addr, dma_addr_t *len,

                           DMADirection dir)

{

    int err;

    target_phys_addr_t paddr, plen;

    void *buf;

    if (dma->map) {

        return dma->map(dma, addr, len, dir);

    }

    plen = *len;

    err = dma->translate(dma, addr, &paddr, &plen, dir);

    if (err) {

        return NULL;

    }

    /*

     * If this is true, the virtual region is contiguous,

     * but the translated physical region isn't. We just

     * clamp *len, much like address_space_map() does.

     */

    if (plen < *len) {

        *len = plen;

    }

    buf = address_space_map(dma->as, paddr, &plen, dir == DMA_DIRECTION_FROM_DEVICE);

    *len = plen;

    return buf;

}


static void lx_init(const LxBoardDesc *board, MachineState *machine)

{

#ifdef TARGET_WORDS_BIGENDIAN

    int be = 1;

#else

    int be = 0;

#endif

    MemoryRegion *system_memory = get_system_memory();

    XtensaCPU *cpu = NULL;

    CPUXtensaState *env = NULL;

    MemoryRegion *ram, *rom, *system_io;

    DriveInfo *dinfo;

    pflash_t *flash = NULL;

    QemuOpts *machine_opts = qemu_get_machine_opts();

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = qemu_opt_get(machine_opts, "kernel");

    const char *kernel_cmdline = qemu_opt_get(machine_opts, "append");

    const char *dtb_filename = qemu_opt_get(machine_opts, "dtb");

    const char *initrd_filename = qemu_opt_get(machine_opts, "initrd");

    int n;

    if (!cpu_model) {

        cpu_model = XTENSA_DEFAULT_CPU_MODEL;

    }

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

        cpu = cpu_xtensa_init(cpu_model);

        if (cpu == NULL) {

            error_report("unable to find CPU definition '%s'\n",

                         cpu_model);

            exit(EXIT_FAILURE);

        }

        env = &cpu->env;

        env->sregs[PRID] = n;

        qemu_register_reset(lx60_reset, cpu);

        /* Need MMU initialized prior to ELF loading,

         * so that ELF gets loaded into virtual addresses

         */

        cpu_reset(CPU(cpu));

    }

    ram = g_malloc(sizeof(*ram));

    memory_region_init_ram(ram, NULL, "lx60.dram", machine->ram_size,

                           &error_abort);

    vmstate_register_ram_global(ram);

    memory_region_add_subregion(system_memory, 0, ram);

    system_io = g_malloc(sizeof(*system_io));

    memory_region_init(system_io, NULL, "lx60.io", 224 * 1024 * 1024);

    memory_region_add_subregion(system_memory, 0xf0000000, system_io);

    lx60_fpga_init(system_io, 0x0d020000);

    if (nd_table[0].used) {

        lx60_net_init(system_io, 0x0d030000, 0x0d030400, 0x0d800000,

                xtensa_get_extint(env, 1), nd_table);

    }

    if (!serial_hds[0]) {

        serial_hds[0] = qemu_chr_new("serial0", "null", NULL);

    }

    serial_mm_init(system_io, 0x0d050020, 2, xtensa_get_extint(env, 0),

            115200, serial_hds[0], DEVICE_NATIVE_ENDIAN);

    dinfo = drive_get(IF_PFLASH, 0, 0);

    if (dinfo) {

        flash = pflash_cfi01_register(board->flash_base,

                NULL, "lx60.io.flash", board->flash_size,

                blk_bs(blk_by_legacy_dinfo(dinfo)),

                board->flash_sector_size,

                board->flash_size / board->flash_sector_size,

                4, 0x0000, 0x0000, 0x0000, 0x0000, be);

        if (flash == NULL) {

            error_report("unable to mount pflash\n");

            exit(EXIT_FAILURE);

        }

    }

    /* Use presence of kernel file name as 'boot from SRAM' switch. */

    if (kernel_filename) {

        uint32_t entry_point = env->pc;

        size_t bp_size = 3 * get_tag_size(0); /* first/last and memory tags */

        uint32_t tagptr = 0xfe000000 + board->sram_size;

        uint32_t cur_tagptr;

        BpMemInfo memory_location = {

            .type = tswap32(MEMORY_TYPE_CONVENTIONAL),

            .start = tswap32(0),

            .end = tswap32(machine->ram_size),

        };

        uint32_t lowmem_end = machine->ram_size < 0x08000000 ?

            machine->ram_size : 0x08000000;

        uint32_t cur_lowmem = QEMU_ALIGN_UP(lowmem_end / 2, 4096);

        rom = g_malloc(sizeof(*rom));

        memory_region_init_ram(rom, NULL, "lx60.sram", board->sram_size,

                               &error_abort);

        vmstate_register_ram_global(rom);

        memory_region_add_subregion(system_memory, 0xfe000000, rom);

        if (kernel_cmdline) {

            bp_size += get_tag_size(strlen(kernel_cmdline) + 1);

        }

        if (dtb_filename) {

            bp_size += get_tag_size(sizeof(uint32_t));

        }

        if (initrd_filename) {

            bp_size += get_tag_size(sizeof(BpMemInfo));

        }

        /* Put kernel bootparameters to the end of that SRAM */

        tagptr = (tagptr - bp_size) & ~0xff;

        cur_tagptr = put_tag(tagptr, BP_TAG_FIRST, 0, NULL);

        cur_tagptr = put_tag(cur_tagptr, BP_TAG_MEMORY,

                             sizeof(memory_location), &memory_location);

        if (kernel_cmdline) {

            cur_tagptr = put_tag(cur_tagptr, BP_TAG_COMMAND_LINE,

                                 strlen(kernel_cmdline) + 1, kernel_cmdline);

        }

        if (dtb_filename) {

            int fdt_size;

            void *fdt = load_device_tree(dtb_filename, &fdt_size);

            uint32_t dtb_addr = tswap32(cur_lowmem);

            if (!fdt) {

                error_report("could not load DTB '%s'\n", dtb_filename);

                exit(EXIT_FAILURE);

            }

            cpu_physical_memory_write(cur_lowmem, fdt, fdt_size);

            cur_tagptr = put_tag(cur_tagptr, BP_TAG_FDT,

                                 sizeof(dtb_addr), &dtb_addr);

            cur_lowmem = QEMU_ALIGN_UP(cur_lowmem + fdt_size, 4096);

        }

        if (initrd_filename) {

            BpMemInfo initrd_location = { 0 };

            int initrd_size = load_ramdisk(initrd_filename, cur_lowmem,

                                           lowmem_end - cur_lowmem);

            if (initrd_size < 0) {

                initrd_size = load_image_targphys(initrd_filename,

                                                  cur_lowmem,

                                                  lowmem_end - cur_lowmem);

            }

            if (initrd_size < 0) {

                error_report("could not load initrd '%s'\n", initrd_filename);

                exit(EXIT_FAILURE);

            }

            initrd_location.start = tswap32(cur_lowmem);

            initrd_location.end = tswap32(cur_lowmem + initrd_size);

            cur_tagptr = put_tag(cur_tagptr, BP_TAG_INITRD,

                                 sizeof(initrd_location), &initrd_location);

            cur_lowmem = QEMU_ALIGN_UP(cur_lowmem + initrd_size, 4096);

        }

        cur_tagptr = put_tag(cur_tagptr, BP_TAG_LAST, 0, NULL);

        env->regs[2] = tagptr;

        uint64_t elf_entry;

        uint64_t elf_lowaddr;

        int success = load_elf(kernel_filename, translate_phys_addr, cpu,

                &elf_entry, &elf_lowaddr, NULL, be, ELF_MACHINE, 0);

        if (success > 0) {

            entry_point = elf_entry;

        } else {

            hwaddr ep;

            int is_linux;

            success = load_uimage(kernel_filename, &ep, NULL, &is_linux);

            if (success > 0 && is_linux) {

                entry_point = ep;

            } else {

                error_report("could not load kernel '%s'\n",

                             kernel_filename);

                exit(EXIT_FAILURE);

            }

        }

        if (entry_point != env->pc) {

            static const uint8_t jx_a0[] = {

#ifdef TARGET_WORDS_BIGENDIAN

                0x0a, 0, 0,

#else

                0xa0, 0, 0,

#endif

            };

            env->regs[0] = entry_point;

            cpu_physical_memory_write(env->pc, jx_a0, sizeof(jx_a0));

        }

    } else {

        if (flash) {

            MemoryRegion *flash_mr = pflash_cfi01_get_memory(flash);

            MemoryRegion *flash_io = g_malloc(sizeof(*flash_io));

            memory_region_init_alias(flash_io, NULL, "lx60.flash",

                    flash_mr, board->flash_boot_base,

                    board->flash_size - board->flash_boot_base < 0x02000000 ?

                    board->flash_size - board->flash_boot_base : 0x02000000);

            memory_region_add_subregion(system_memory, 0xfe000000,

                    flash_io);

        }

    }

}


void kvm_arch_reset_vcpu(X86CPU *cpu)

{

    CPUX86State *env = &cpu->env;

    env->exception_injected = -1;

    env->interrupt_injected = -1;

    env->xcr0 = 1;

    if (kvm_irqchip_in_kernel()) {

        env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :

                                          KVM_MP_STATE_UNINITIALIZED;

    } else {

        env->mp_state = KVM_MP_STATE_RUNNABLE;

    }

    if (cpu->hyperv_synic) {

        int i;

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

            env->msr_hv_synic_sint[i] = HV_SINT_MASKED;

        }

    }

}


static int speex_header(AVFormatContext *s, int idx) {

    struct ogg *ogg = s->priv_data;

    struct ogg_stream *os = ogg->streams + idx;

    struct speex_params *spxp = os->private;

    AVStream *st = s->streams[idx];

    uint8_t *p = os->buf + os->pstart;

    if (!spxp) {

        spxp = av_mallocz(sizeof(*spxp));

        os->private = spxp;

    }

    if (spxp->seq > 1)

        return 0;

    if (spxp->seq == 0) {

        int frames_per_packet;

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        st->codec->codec_id = AV_CODEC_ID_SPEEX;

        if (os->psize < 68) {

            av_log(s, AV_LOG_ERROR, "speex packet too small\n");

            return AVERROR_INVALIDDATA;

        }

        st->codec->sample_rate = AV_RL32(p + 36);

        st->codec->channels = AV_RL32(p + 48);

        if (st->codec->channels < 1 || st->codec->channels > 2) {

            av_log(s, AV_LOG_ERROR, "invalid channel count. Speex must be mono or stereo.\n");

            return AVERROR_INVALIDDATA;

        }

        st->codec->channel_layout = st->codec->channels == 1 ? AV_CH_LAYOUT_MONO :

                                                               AV_CH_LAYOUT_STEREO;

        spxp->packet_size  = AV_RL32(p + 56);

        frames_per_packet  = AV_RL32(p + 64);

        if (frames_per_packet)

            spxp->packet_size *= frames_per_packet;

        ff_alloc_extradata(st->codec, os->psize);

        memcpy(st->codec->extradata, p, st->codec->extradata_size);

        avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);

    } else

        ff_vorbis_comment(s, &st->metadata, p, os->psize);

    spxp->seq++;

    return 1;

}


static ExitStatus trans_fop_wed_0e(DisasContext *ctx, uint32_t insn,

                                   const DisasInsn *di)

{

    unsigned rt = assemble_rt64(insn);

    unsigned ra = extract32(insn, 21, 5);

    return do_fop_wed(ctx, rt, ra, di->f_wed);

}


void filter_level_for_mb(VP8Context *s, VP8Macroblock *mb, VP8FilterStrength *f)

{

    int interior_limit, filter_level;

    if (s->segmentation.enabled) {

        filter_level = s->segmentation.filter_level[mb->segment];

        if (!s->segmentation.absolute_vals)

            filter_level += s->filter.level;

    } else

        filter_level = s->filter.level;

    if (s->lf_delta.enabled) {

        filter_level += s->lf_delta.ref[mb->ref_frame];

        filter_level += s->lf_delta.mode[mb->mode];

    }

    filter_level = av_clip_uintp2(filter_level, 6);

    interior_limit = filter_level;

    if (s->filter.sharpness) {

        interior_limit >>= (s->filter.sharpness + 3) >> 2;

        interior_limit = FFMIN(interior_limit, 9 - s->filter.sharpness);

    }

    interior_limit = FFMAX(interior_limit, 1);

    f->filter_level = filter_level;

    f->inner_limit = interior_limit;

    f->inner_filter = !mb->skip || mb->mode == MODE_I4x4 ||

                      mb->mode == VP8_MVMODE_SPLIT;

}


static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)

{

    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);

    uint64_t nb_sectors;

    uint8_t *outbuf;

    int buflen;

    switch (req->cmd.buf[0]) {

    case INQUIRY:

    case MODE_SENSE:

    case MODE_SENSE_10:

    case RESERVE:

    case RESERVE_10:

    case RELEASE:

    case RELEASE_10:

    case START_STOP:

    case ALLOW_MEDIUM_REMOVAL:

    case GET_CONFIGURATION:

    case GET_EVENT_STATUS_NOTIFICATION:

    case MECHANISM_STATUS:

    case REQUEST_SENSE:

        break;

    default:

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

            scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));

            return 0;

        }

        break;

    }

    /*

     * FIXME: we shouldn't return anything bigger than 4k, but the code

     * requires the buffer to be as big as req->cmd.xfer in several

     * places.  So, do not allow CDBs with a very large ALLOCATION

     * LENGTH.  The real fix would be to modify scsi_read_data and

     * dma_buf_read, so that they return data beyond the buflen

     * as all zeros.

     */

    if (req->cmd.xfer > 65536) {

        goto illegal_request;

    }

    r->buflen = MAX(4096, req->cmd.xfer);

    if (!r->iov.iov_base) {

        r->iov.iov_base = qemu_blockalign(s->qdev.conf.bs, r->buflen);

    }

    buflen = req->cmd.xfer;

    outbuf = r->iov.iov_base;

    memset(outbuf, 0, r->buflen);

    switch (req->cmd.buf[0]) {

    case TEST_UNIT_READY:

        assert(!s->tray_open && bdrv_is_inserted(s->qdev.conf.bs));

        break;

    case INQUIRY:

        buflen = scsi_disk_emulate_inquiry(req, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case MODE_SENSE:

    case MODE_SENSE_10:

        buflen = scsi_disk_emulate_mode_sense(r, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case READ_TOC:

        buflen = scsi_disk_emulate_read_toc(req, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case RESERVE:

        if (req->cmd.buf[1] & 1) {

            goto illegal_request;

        }

        break;

    case RESERVE_10:

        if (req->cmd.buf[1] & 3) {

            goto illegal_request;

        }

        break;

    case RELEASE:

        if (req->cmd.buf[1] & 1) {

            goto illegal_request;

        }

        break;

    case RELEASE_10:

        if (req->cmd.buf[1] & 3) {

            goto illegal_request;

        }

        break;

    case START_STOP:

        if (scsi_disk_emulate_start_stop(r) < 0) {

            return 0;

        }

        break;

    case ALLOW_MEDIUM_REMOVAL:

        s->tray_locked = req->cmd.buf[4] & 1;

        bdrv_lock_medium(s->qdev.conf.bs, req->cmd.buf[4] & 1);

        break;

    case READ_CAPACITY_10:

        /* The normal LEN field for this command is zero.  */

        memset(outbuf, 0, 8);

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

        if (!nb_sectors) {

            scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));

            return 0;

        }

        if ((req->cmd.buf[8] & 1) == 0 && req->cmd.lba) {

            goto illegal_request;

        }

        nb_sectors /= s->qdev.blocksize / 512;

        /* Returned value is the address of the last sector.  */

        nb_sectors--;

        /* Remember the new size for read/write sanity checking. */

        s->qdev.max_lba = nb_sectors;

        /* Clip to 2TB, instead of returning capacity modulo 2TB. */

        if (nb_sectors > UINT32_MAX) {

            nb_sectors = UINT32_MAX;

        }

        outbuf[0] = (nb_sectors >> 24) & 0xff;

        outbuf[1] = (nb_sectors >> 16) & 0xff;

        outbuf[2] = (nb_sectors >> 8) & 0xff;

        outbuf[3] = nb_sectors & 0xff;

        outbuf[4] = 0;

        outbuf[5] = 0;

        outbuf[6] = s->qdev.blocksize >> 8;

        outbuf[7] = 0;

        break;

    case REQUEST_SENSE:

        /* Just return "NO SENSE".  */

        buflen = scsi_build_sense(NULL, 0, outbuf, r->buflen,

                                  (req->cmd.buf[1] & 1) == 0);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case MECHANISM_STATUS:

        buflen = scsi_emulate_mechanism_status(s, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case GET_CONFIGURATION:

        buflen = scsi_get_configuration(s, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case GET_EVENT_STATUS_NOTIFICATION:

        buflen = scsi_get_event_status_notification(s, r, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case READ_DISC_INFORMATION:

        buflen = scsi_read_disc_information(s, r, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case READ_DVD_STRUCTURE:

        buflen = scsi_read_dvd_structure(s, r, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case SERVICE_ACTION_IN_16:

        /* Service Action In subcommands. */

        if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) {

            DPRINTF("SAI READ CAPACITY(16)\n");

            memset(outbuf, 0, req->cmd.xfer);

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

            if (!nb_sectors) {

                scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));

                return 0;

            }

            if ((req->cmd.buf[14] & 1) == 0 && req->cmd.lba) {

                goto illegal_request;

            }

            nb_sectors /= s->qdev.blocksize / 512;

            /* Returned value is the address of the last sector.  */

            nb_sectors--;

            /* Remember the new size for read/write sanity checking. */

            s->qdev.max_lba = nb_sectors;

            outbuf[0] = (nb_sectors >> 56) & 0xff;

            outbuf[1] = (nb_sectors >> 48) & 0xff;

            outbuf[2] = (nb_sectors >> 40) & 0xff;

            outbuf[3] = (nb_sectors >> 32) & 0xff;

            outbuf[4] = (nb_sectors >> 24) & 0xff;

            outbuf[5] = (nb_sectors >> 16) & 0xff;

            outbuf[6] = (nb_sectors >> 8) & 0xff;

            outbuf[7] = nb_sectors & 0xff;

            outbuf[8] = 0;

            outbuf[9] = 0;

            outbuf[10] = s->qdev.blocksize >> 8;

            outbuf[11] = 0;

            outbuf[12] = 0;

            outbuf[13] = get_physical_block_exp(&s->qdev.conf);

            /* set TPE bit if the format supports discard */

            if (s->qdev.conf.discard_granularity) {

                outbuf[14] = 0x80;

            }

            /* Protection, exponent and lowest lba field left blank. */

            break;

        }

        DPRINTF("Unsupported Service Action In\n");

        goto illegal_request;

    case SYNCHRONIZE_CACHE:

        /* The request is used as the AIO opaque value, so add a ref.  */

        scsi_req_ref(&r->req);

        bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);

        r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r);

        return 0;

    case SEEK_10:

        DPRINTF("Seek(10) (sector %" PRId64 ")\n", r->req.cmd.lba);

        if (r->req.cmd.lba > s->qdev.max_lba) {

            goto illegal_lba;

        }

        break;

    case MODE_SELECT:

        DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);

        break;

    case MODE_SELECT_10:

        DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);

        break;

    case UNMAP:

        DPRINTF("Unmap (len %lu)\n", (long)r->req.cmd.xfer);

        break;

    case WRITE_SAME_10:

    case WRITE_SAME_16:

        nb_sectors = scsi_data_cdb_length(r->req.cmd.buf);

        if (bdrv_is_read_only(s->qdev.conf.bs)) {

            scsi_check_condition(r, SENSE_CODE(WRITE_PROTECTED));

            return 0;

        }

        if (!check_lba_range(s, r->req.cmd.lba, nb_sectors)) {

            goto illegal_lba;

        }

        /*

         * We only support WRITE SAME with the unmap bit set for now.

         */

        if (!(req->cmd.buf[1] & 0x8)) {

            goto illegal_request;

        }

        /* The request is used as the AIO opaque value, so add a ref.  */

        scsi_req_ref(&r->req);

        r->req.aiocb = bdrv_aio_discard(s->qdev.conf.bs,

                                        r->req.cmd.lba * (s->qdev.blocksize / 512),

                                        nb_sectors * (s->qdev.blocksize / 512),

                                        scsi_aio_complete, r);

        return 0;

    default:

        DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);

        scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));

        return 0;

    }

    assert(!r->req.aiocb);

    r->iov.iov_len = MIN(r->buflen, req->cmd.xfer);

    if (r->iov.iov_len == 0) {

        scsi_req_complete(&r->req, GOOD);

    }

    if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {

        assert(r->iov.iov_len == req->cmd.xfer);

        return -r->iov.iov_len;

    } else {

        return r->iov.iov_len;

    }

illegal_request:

    if (r->req.status == -1) {

        scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));

    }

    return 0;

illegal_lba:

    scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));

    return 0;

}


static int decode_syncpoint(NUTContext *nut){

    AVFormatContext *s= nut->avf;

    ByteIOContext *bc = &s->pb;

    int64_t end;

    uint64_t tmp;

    int i;

    AVRational time_base;

    nut->last_syncpoint_pos= url_ftell(bc)-8;

    end= get_packetheader(nut, bc, 1);

    end += url_ftell(bc) - 4;

    tmp= get_v(bc);

    get_v(bc); //back_ptr_div16

    time_base= nut->time_base[tmp % nut->time_base_count];

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

        nut->stream[i].last_pts= av_rescale_rnd(

            tmp / nut->time_base_count,

            time_base.num * (int64_t)nut->stream[i].time_base.den,

            time_base.den * (int64_t)nut->stream[i].time_base.num,

            AV_ROUND_DOWN);

        //last_key_frame ?

    }

    //FIXME put this in a reset func maybe

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

        av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");

        return -1;

    }

    return 0;

}


static void mips_jazz_init(MachineState *machine,

                           enum jazz_model_e jazz_model)

{

    MemoryRegion *address_space = get_system_memory();

    const char *cpu_model = machine->cpu_model;

    char *filename;

    int bios_size, n;

    MIPSCPU *cpu;

    CPUClass *cc;

    CPUMIPSState *env;

    qemu_irq *i8259;

    rc4030_dma *dmas;

    MemoryRegion *rc4030_dma_mr;

    MemoryRegion *isa_mem = g_new(MemoryRegion, 1);

    MemoryRegion *isa_io = g_new(MemoryRegion, 1);

    MemoryRegion *rtc = g_new(MemoryRegion, 1);

    MemoryRegion *i8042 = g_new(MemoryRegion, 1);

    MemoryRegion *dma_dummy = g_new(MemoryRegion, 1);

    NICInfo *nd;

    DeviceState *dev, *rc4030;

    SysBusDevice *sysbus;

    ISABus *isa_bus;

    ISADevice *pit;

    DriveInfo *fds[MAX_FD];

    qemu_irq esp_reset, dma_enable;

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *bios = g_new(MemoryRegion, 1);

    MemoryRegion *bios2 = g_new(MemoryRegion, 1);

    /* init CPUs */

    if (cpu_model == NULL) {

        cpu_model = "R4000";

    }

    cpu = cpu_mips_init(cpu_model);

    if (cpu == NULL) {

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

        exit(1);

    }

    env = &cpu->env;

    qemu_register_reset(main_cpu_reset, cpu);

    /* Chipset returns 0 in invalid reads and do not raise data exceptions.

     * However, we can't simply add a global memory region to catch

     * everything, as memory core directly call unassigned_mem_read/write

     * on some invalid accesses, which call do_unassigned_access on the

     * CPU, which raise an exception.

     * Handle that case by hijacking the do_unassigned_access method on

     * the CPU, and do not raise exceptions for data access. */

    cc = CPU_GET_CLASS(cpu);

    real_do_unassigned_access = cc->do_unassigned_access;

    cc->do_unassigned_access = mips_jazz_do_unassigned_access;

    /* allocate RAM */

    memory_region_allocate_system_memory(ram, NULL, "mips_jazz.ram",

                                         machine->ram_size);

    memory_region_add_subregion(address_space, 0, ram);

    memory_region_init_ram(bios, NULL, "mips_jazz.bios", MAGNUM_BIOS_SIZE,

                           &error_abort);

    vmstate_register_ram_global(bios);

    memory_region_set_readonly(bios, true);

    memory_region_init_alias(bios2, NULL, "mips_jazz.bios", bios,

                             0, MAGNUM_BIOS_SIZE);

    memory_region_add_subregion(address_space, 0x1fc00000LL, bios);

    memory_region_add_subregion(address_space, 0xfff00000LL, bios2);

    /* load the BIOS image. */

    if (bios_name == NULL)

        bios_name = BIOS_FILENAME;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    if (filename) {

        bios_size = load_image_targphys(filename, 0xfff00000LL,

                                        MAGNUM_BIOS_SIZE);

        g_free(filename);

    } else {

        bios_size = -1;

    }

    if ((bios_size < 0 || bios_size > MAGNUM_BIOS_SIZE) && !qtest_enabled()) {

        error_report("Could not load MIPS bios '%s'", bios_name);

        exit(1);

    }

    /* Init CPU internal devices */

    cpu_mips_irq_init_cpu(env);

    cpu_mips_clock_init(env);

    /* Chipset */

    rc4030 = rc4030_init(&dmas, &rc4030_dma_mr);

    sysbus = SYS_BUS_DEVICE(rc4030);

    sysbus_connect_irq(sysbus, 0, env->irq[6]);

    sysbus_connect_irq(sysbus, 1, env->irq[3]);

    memory_region_add_subregion(address_space, 0x80000000,

                                sysbus_mmio_get_region(sysbus, 0));

    memory_region_add_subregion(address_space, 0xf0000000,

                                sysbus_mmio_get_region(sysbus, 1));

    memory_region_init_io(dma_dummy, NULL, &dma_dummy_ops, NULL, "dummy_dma", 0x1000);

    memory_region_add_subregion(address_space, 0x8000d000, dma_dummy);

    /* ISA bus: IO space at 0x90000000, mem space at 0x91000000 */

    memory_region_init(isa_io, NULL, "isa-io", 0x00010000);

    memory_region_init(isa_mem, NULL, "isa-mem", 0x01000000);

    memory_region_add_subregion(address_space, 0x90000000, isa_io);

    memory_region_add_subregion(address_space, 0x91000000, isa_mem);

    isa_bus = isa_bus_new(NULL, isa_mem, isa_io);

    /* ISA devices */

    i8259 = i8259_init(isa_bus, env->irq[4]);

    isa_bus_irqs(isa_bus, i8259);

    DMA_init(0);

    pit = pit_init(isa_bus, 0x40, 0, NULL);

    pcspk_init(isa_bus, pit);

    /* Video card */

    switch (jazz_model) {

    case JAZZ_MAGNUM:

        dev = qdev_create(NULL, "sysbus-g364");

        qdev_init_nofail(dev);

        sysbus = SYS_BUS_DEVICE(dev);

        sysbus_mmio_map(sysbus, 0, 0x60080000);

        sysbus_mmio_map(sysbus, 1, 0x40000000);

        sysbus_connect_irq(sysbus, 0, qdev_get_gpio_in(rc4030, 3));

        {

            /* Simple ROM, so user doesn't have to provide one */

            MemoryRegion *rom_mr = g_new(MemoryRegion, 1);

            memory_region_init_ram(rom_mr, NULL, "g364fb.rom", 0x80000,

                                   &error_abort);

            vmstate_register_ram_global(rom_mr);

            memory_region_set_readonly(rom_mr, true);

            uint8_t *rom = memory_region_get_ram_ptr(rom_mr);

            memory_region_add_subregion(address_space, 0x60000000, rom_mr);

            rom[0] = 0x10; /* Mips G364 */

        }

        break;

    case JAZZ_PICA61:

        isa_vga_mm_init(0x40000000, 0x60000000, 0, get_system_memory());

        break;

    default:

        break;

    }

    /* Network controller */

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

        nd = &nd_table[n];

        if (!nd->model)

            nd->model = g_strdup("dp83932");

        if (strcmp(nd->model, "dp83932") == 0) {

            qemu_check_nic_model(nd, "dp83932");

            dev = qdev_create(NULL, "dp8393x");

            qdev_set_nic_properties(dev, nd);

            qdev_prop_set_uint8(dev, "it_shift", 2);

            qdev_prop_set_ptr(dev, "dma_mr", rc4030_dma_mr);

            qdev_init_nofail(dev);

            sysbus = SYS_BUS_DEVICE(dev);

            sysbus_mmio_map(sysbus, 0, 0x80001000);

            sysbus_mmio_map(sysbus, 1, 0x8000b000);

            sysbus_connect_irq(sysbus, 0, qdev_get_gpio_in(rc4030, 4));

            break;

        } else if (is_help_option(nd->model)) {

            fprintf(stderr, "qemu: Supported NICs: dp83932\n");

            exit(1);

        } else {

            fprintf(stderr, "qemu: Unsupported NIC: %s\n", nd->model);

            exit(1);

        }

    }

    /* SCSI adapter */

    esp_init(0x80002000, 0,

             rc4030_dma_read, rc4030_dma_write, dmas[0],

             qdev_get_gpio_in(rc4030, 5), &esp_reset, &dma_enable);

    /* Floppy */

    if (drive_get_max_bus(IF_FLOPPY) >= MAX_FD) {

        fprintf(stderr, "qemu: too many floppy drives\n");

        exit(1);

    }

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

        fds[n] = drive_get(IF_FLOPPY, 0, n);

    }

    fdctrl_init_sysbus(qdev_get_gpio_in(rc4030, 1), 0, 0x80003000, fds);

    /* Real time clock */

    rtc_init(isa_bus, 1980, NULL);

    memory_region_init_io(rtc, NULL, &rtc_ops, NULL, "rtc", 0x1000);

    memory_region_add_subregion(address_space, 0x80004000, rtc);

    /* Keyboard (i8042) */

    i8042_mm_init(qdev_get_gpio_in(rc4030, 6), qdev_get_gpio_in(rc4030, 7),

                  i8042, 0x1000, 0x1);

    memory_region_add_subregion(address_space, 0x80005000, i8042);

    /* Serial ports */

    if (serial_hds[0]) {

        serial_mm_init(address_space, 0x80006000, 0,

                       qdev_get_gpio_in(rc4030, 8), 8000000/16,

                       serial_hds[0], DEVICE_NATIVE_ENDIAN);

    }

    if (serial_hds[1]) {

        serial_mm_init(address_space, 0x80007000, 0,

                       qdev_get_gpio_in(rc4030, 9), 8000000/16,

                       serial_hds[1], DEVICE_NATIVE_ENDIAN);

    }

    /* Parallel port */

    if (parallel_hds[0])

        parallel_mm_init(address_space, 0x80008000, 0,

                         qdev_get_gpio_in(rc4030, 0), parallel_hds[0]);

    /* FIXME: missing Jazz sound at 0x8000c000, rc4030[2] */

    /* NVRAM */

    dev = qdev_create(NULL, "ds1225y");

    qdev_init_nofail(dev);

    sysbus = SYS_BUS_DEVICE(dev);

    sysbus_mmio_map(sysbus, 0, 0x80009000);

    /* LED indicator */

    sysbus_create_simple("jazz-led", 0x8000f000, NULL);

}


static void free_texture(void *opaque, uint8_t *data)

{

    ID3D11Texture2D_Release((ID3D11Texture2D *)opaque);

}


static int alac_decode_frame(AVCodecContext *avctx,
                             void *outbuffer, int *outputsize,
                             const uint8_t *inbuffer, int input_buffer_size)
{
    ALACContext *alac = avctx->priv_data;
    int channels;
    unsigned int outputsamples;
    int hassize;
    int readsamplesize;
    int wasted_bytes;
    int isnotcompressed;
    uint8_t interlacing_shift;
    uint8_t interlacing_leftweight;
    /* short-circuit null buffers */
    if (!inbuffer || !input_buffer_size)
        return input_buffer_size;
    /* initialize from the extradata */
    if (!alac->context_initialized) {
        if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
            av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
                ALAC_EXTRADATA_SIZE);
            return input_buffer_size;
        if (alac_set_info(alac)) {
            av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
            return input_buffer_size;
        alac->context_initialized = 1;
    init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
    channels = get_bits(&alac->gb, 3) + 1;
    if (channels > MAX_CHANNELS) {
        av_log(avctx, AV_LOG_ERROR, "channels > %d not supported\n",
               MAX_CHANNELS);
        return input_buffer_size;
    /* 2^result = something to do with output waiting.
     * perhaps matters if we read > 1 frame in a pass?
     */
    skip_bits(&alac->gb, 4);
    skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
    /* the output sample size is stored soon */
    hassize = get_bits1(&alac->gb);
    wasted_bytes = get_bits(&alac->gb, 2); /* unknown ? */
    /* whether the frame is compressed */
    isnotcompressed = get_bits1(&alac->gb);
    if (hassize) {
        /* now read the number of samples as a 32bit integer */
        outputsamples = get_bits(&alac->gb, 32);
        if(outputsamples > alac->setinfo_max_samples_per_frame){
            av_log(avctx, AV_LOG_ERROR, "outputsamples %d > %d\n", outputsamples, alac->setinfo_max_samples_per_frame);
    } else
        outputsamples = alac->setinfo_max_samples_per_frame;
    *outputsize = outputsamples * alac->bytespersample;
    readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8) + channels - 1;
    if (!isnotcompressed) {
        /* so it is compressed */
        int16_t predictor_coef_table[channels][32];
        int predictor_coef_num[channels];
        int prediction_type[channels];
        int prediction_quantitization[channels];
        int ricemodifier[channels];
        int i, chan;
        interlacing_shift = get_bits(&alac->gb, 8);
        interlacing_leftweight = get_bits(&alac->gb, 8);
        for (chan = 0; chan < channels; chan++) {
            prediction_type[chan] = get_bits(&alac->gb, 4);
            prediction_quantitization[chan] = get_bits(&alac->gb, 4);
            ricemodifier[chan] = get_bits(&alac->gb, 3);
            predictor_coef_num[chan] = get_bits(&alac->gb, 5);
            /* read the predictor table */
            for (i = 0; i < predictor_coef_num[chan]; i++)
                predictor_coef_table[chan][i] = (int16_t)get_bits(&alac->gb, 16);
        if (wasted_bytes)
            av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
        for (chan = 0; chan < channels; chan++) {
            bastardized_rice_decompress(alac,
                                        alac->predicterror_buffer[chan],
                                        outputsamples,
                                        readsamplesize,
                                        alac->setinfo_rice_initialhistory,
                                        alac->setinfo_rice_kmodifier,
                                        ricemodifier[chan] * alac->setinfo_rice_historymult / 4,
                                        (1 << alac->setinfo_rice_kmodifier) - 1);
            if (prediction_type[chan] == 0) {
                /* adaptive fir */
                predictor_decompress_fir_adapt(alac->predicterror_buffer[chan],
                                               alac->outputsamples_buffer[chan],
                                               outputsamples,
                                               readsamplesize,
                                               predictor_coef_table[chan],
                                               predictor_coef_num[chan],
                                               prediction_quantitization[chan]);
            } else {
                av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[chan]);
                /* I think the only other prediction type (or perhaps this is
                 * just a boolean?) runs adaptive fir twice.. like:
                 * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
                 * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
                 * little strange..
                 */
    } else {
        /* not compressed, easy case */
        if (alac->setinfo_sample_size <= 16) {
            int i, chan;
            for (chan = 0; chan < channels; chan++)
                for (i = 0; i < outputsamples; i++) {
                    int32_t audiobits;
                    audiobits = get_bits(&alac->gb, alac->setinfo_sample_size);
                    audiobits = extend_sign32(audiobits, readsamplesize);
                    alac->outputsamples_buffer[chan][i] = audiobits;
        } else {
            int i, chan;
            for (chan = 0; chan < channels; chan++)
                for (i = 0; i < outputsamples; i++) {
                    int32_t audiobits;
                    audiobits = get_bits(&alac->gb, 16);
                    /* special case of sign extension..
                     * as we'll be ORing the low 16bits into this */
                    audiobits = audiobits << 16;
                    audiobits = audiobits >> (32 - alac->setinfo_sample_size);
                    audiobits |= get_bits(&alac->gb, alac->setinfo_sample_size - 16);
                    alac->outputsamples_buffer[chan][i] = audiobits;
        /* wasted_bytes = 0; */
        interlacing_shift = 0;
        interlacing_leftweight = 0;
    if (get_bits(&alac->gb, 3) != 7)
        av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
    switch(alac->setinfo_sample_size) {
    case 16:
        if (channels == 2) {
            reconstruct_stereo_16(alac->outputsamples_buffer,
                                  (int16_t*)outbuffer,
                                  alac->numchannels,
                                  outputsamples,
                                  interlacing_shift,
                                  interlacing_leftweight);
        } else {
            int i;
            for (i = 0; i < outputsamples; i++) {
                int16_t sample = alac->outputsamples_buffer[0][i];
                ((int16_t*)outbuffer)[i * alac->numchannels] = sample;
        break;
    case 20:
    case 24:
        // It is not clear if there exist any encoder that creates 24 bit ALAC
        // files. iTunes convert 24 bit raw files to 16 bit before encoding.
    case 32:
        av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
        break;
    default:
        break;
    if (input_buffer_size * 8 - get_bits_count(&alac->gb) > 8)
        av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n", input_buffer_size * 8 - get_bits_count(&alac->gb));
    return input_buffer_size;


int bdrv_truncate(BlockDriverState *bs, int64_t offset)

{

    BlockDriver *drv = bs->drv;

    int ret;

    if (!drv)

        return -ENOMEDIUM;

    if (!drv->bdrv_truncate)

        return -ENOTSUP;

    if (bs->read_only)

        return -EACCES;

    ret = drv->bdrv_truncate(bs, offset);

    if (ret == 0) {

        ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);

        bdrv_dirty_bitmap_truncate(bs);

        bdrv_parent_cb_resize(bs);

    }

    return ret;

}


static void gen_sub(DisasContext *dc, TCGv dest, TCGv srca, TCGv srcb)

{

    TCGv res = tcg_temp_new();

    TCGv sr_cy = tcg_temp_new();

    TCGv sr_ov = tcg_temp_new();

    tcg_gen_sub_tl(res, srca, srcb);

    tcg_gen_xor_tl(sr_cy, srca, srcb);

    tcg_gen_xor_tl(sr_ov, res, srcb);

    tcg_gen_and_tl(sr_ov, sr_ov, sr_cy);

    tcg_gen_setcond_tl(TCG_COND_LTU, sr_cy, srca, srcb);

    tcg_gen_mov_tl(dest, res);

    tcg_temp_free(res);

    tcg_gen_shri_tl(sr_ov, sr_ov, TARGET_LONG_BITS - 1);

    tcg_gen_deposit_tl(cpu_sr, cpu_sr, sr_cy, ctz32(SR_CY), 1);

    tcg_gen_deposit_tl(cpu_sr, cpu_sr, sr_ov, ctz32(SR_OV), 1);

    gen_ove_cyov(dc, sr_ov, sr_cy);

    tcg_temp_free(sr_ov);

    tcg_temp_free(sr_cy);

}


static void ecc_mem_writel(void *opaque, target_phys_addr_t addr, uint32_t val)

{

    ECCState *s = opaque;

    switch (addr & ECC_ADDR_MASK) {

    case ECC_MER:

        s->regs[0] = (s->regs[0] & (ECC_MER_VER | ECC_MER_IMPL)) |

                     (val & ~(ECC_MER_VER | ECC_MER_IMPL));

        DPRINTF("Write memory enable %08x\n", val);

        break;

    case ECC_MDR:

        s->regs[1] =  val & ECC_MDR_MASK;

        DPRINTF("Write memory delay %08x\n", val);

        break;

    case ECC_MFSR:

        s->regs[2] =  val;

        DPRINTF("Write memory fault status %08x\n", val);

        break;

    case ECC_VCR:

        s->regs[3] =  val;

        DPRINTF("Write slot configuration %08x\n", val);

        break;

    case ECC_DR:

        s->regs[6] =  val;

        DPRINTF("Write diagnosiic %08x\n", val);

        break;

    case ECC_ECR0:

        s->regs[7] =  val;

        DPRINTF("Write event count 1 %08x\n", val);

        break;

    case ECC_ECR1:

        s->regs[7] =  val;

        DPRINTF("Write event count 2 %08x\n", val);

        break;

    }

}


static int qmp_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,

                                 const QDict *params)

{

    return cmd->mhandler.cmd_async(mon, params, qmp_monitor_complete, mon);

}


static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)

{

    AVBitStreamFilterContext *bsfc = ost->bitstream_filters;

    AVCodecContext          *avctx = ost->encoding_needed ? ost->enc_ctx : ost->st->codec;

    int ret;

    if (!ost->st->codec->extradata_size && ost->enc_ctx->extradata_size) {

        ost->st->codec->extradata = av_mallocz(ost->enc_ctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);

        if (ost->st->codec->extradata) {

            memcpy(ost->st->codec->extradata, ost->enc_ctx->extradata, ost->enc_ctx->extradata_size);

            ost->st->codec->extradata_size = ost->enc_ctx->extradata_size;

        }

    }

    if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||

        (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))

        pkt->pts = pkt->dts = AV_NOPTS_VALUE;

    /*

     * Audio encoders may split the packets --  #frames in != #packets out.

     * But there is no reordering, so we can limit the number of output packets

     * by simply dropping them here.

     * Counting encoded video frames needs to be done separately because of

     * reordering, see do_video_out()

     */

    if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {

        if (ost->frame_number >= ost->max_frames) {

            av_free_packet(pkt);

            return;

        }

        ost->frame_number++;

    }

    if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {

        int i;

        uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_STATS,

                                              NULL);

        ost->quality = sd ? AV_RL32(sd) : -1;

        ost->pict_type = sd ? sd[4] : AV_PICTURE_TYPE_NONE;

        for (i = 0; i<FF_ARRAY_ELEMS(ost->error); i++) {

            if (sd && i < sd[5])

                ost->error[i] = AV_RL64(sd + 8 + 8*i);

            else

                ost->error[i] = -1;

        }

    }

    if (bsfc)

        av_packet_split_side_data(pkt);

    while (bsfc) {

        AVPacket new_pkt = *pkt;

        AVDictionaryEntry *bsf_arg = av_dict_get(ost->bsf_args,

                                                 bsfc->filter->name,

                                                 NULL, 0);

        int a = av_bitstream_filter_filter(bsfc, avctx,

                                           bsf_arg ? bsf_arg->value : NULL,

                                           &new_pkt.data, &new_pkt.size,

                                           pkt->data, pkt->size,

                                           pkt->flags & AV_PKT_FLAG_KEY);

        if(a == 0 && new_pkt.data != pkt->data && new_pkt.destruct) {

            uint8_t *t = av_malloc(new_pkt.size + AV_INPUT_BUFFER_PADDING_SIZE); //the new should be a subset of the old so cannot overflow

            if(t) {

                memcpy(t, new_pkt.data, new_pkt.size);

                memset(t + new_pkt.size, 0, AV_INPUT_BUFFER_PADDING_SIZE);

                new_pkt.data = t;

                new_pkt.buf = NULL;

                a = 1;

            } else

                a = AVERROR(ENOMEM);

        }

        if (a > 0) {

            pkt->side_data = NULL;

            pkt->side_data_elems = 0;

            av_free_packet(pkt);

            new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,

                                           av_buffer_default_free, NULL, 0);

            if (!new_pkt.buf)

                exit_program(1);

        } else if (a < 0) {

            new_pkt = *pkt;

            av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",

                   bsfc->filter->name, pkt->stream_index,

                   avctx->codec ? avctx->codec->name : "copy");

            print_error("", a);

            if (exit_on_error)

                exit_program(1);

        }

        *pkt = new_pkt;

        bsfc = bsfc->next;

    }

    if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {

        if (pkt->dts != AV_NOPTS_VALUE &&

            pkt->pts != AV_NOPTS_VALUE &&

            pkt->dts > pkt->pts) {

            av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d, replacing by guess\n",

                   pkt->dts, pkt->pts,

                   ost->file_index, ost->st->index);

            pkt->pts =

            pkt->dts = pkt->pts + pkt->dts + ost->last_mux_dts + 1

                     - FFMIN3(pkt->pts, pkt->dts, ost->last_mux_dts + 1)

                     - FFMAX3(pkt->pts, pkt->dts, ost->last_mux_dts + 1);

        }

     if(

        (avctx->codec_type == AVMEDIA_TYPE_AUDIO || avctx->codec_type == AVMEDIA_TYPE_VIDEO) &&

        pkt->dts != AV_NOPTS_VALUE &&

        ost->last_mux_dts != AV_NOPTS_VALUE) {

      int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);

      if (pkt->dts < max) {

        int loglevel = max - pkt->dts > 2 || avctx->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;

        av_log(s, loglevel, "Non-monotonous DTS in output stream "

               "%d:%d; previous: %"PRId64", current: %"PRId64"; ",

               ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);

        if (exit_on_error) {

            av_log(NULL, AV_LOG_FATAL, "aborting.\n");

            exit_program(1);

        }

        av_log(s, loglevel, "changing to %"PRId64". This may result "

               "in incorrect timestamps in the output file.\n",

               max);

        if(pkt->pts >= pkt->dts)

            pkt->pts = FFMAX(pkt->pts, max);

        pkt->dts = max;

      }

     }

    }

    ost->last_mux_dts = pkt->dts;

    ost->data_size += pkt->size;

    ost->packets_written++;

    pkt->stream_index = ost->index;

    if (debug_ts) {

        av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "

                "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",

                av_get_media_type_string(ost->enc_ctx->codec_type),

                av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),

                av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),

                pkt->size

              );

    }

    ret = av_interleaved_write_frame(s, pkt);

    if (ret < 0) {

        print_error("av_interleaved_write_frame()", ret);

        main_return_code = 1;

        close_all_output_streams(ost, MUXER_FINISHED | ENCODER_FINISHED, ENCODER_FINISHED);

    }

    av_free_packet(pkt);

}


void ff_aac_search_for_pred(AACEncContext *s, SingleChannelElement *sce)

{

    int sfb, i, count = 0, cost_coeffs = 0, cost_pred = 0;

    const int pmax = FFMIN(sce->ics.max_sfb, ff_aac_pred_sfb_max[s->samplerate_index]);

    float *O34  = &s->scoefs[128*0], *P34 = &s->scoefs[128*1];

    float *SENT = &s->scoefs[128*2], *S34 = &s->scoefs[128*3];

    float *QERR = &s->scoefs[128*4];

    if (sce->ics.window_sequence[0] == EIGHT_SHORT_SEQUENCE) {

        sce->ics.predictor_present = 0;

        return;

    }

    if (!sce->ics.predictor_initialized) {

        reset_all_predictors(sce->predictor_state);

        sce->ics.predictor_initialized = 1;

        memcpy(sce->prcoeffs, sce->coeffs, 1024*sizeof(float));

        for (i = 1; i < 31; i++)

            sce->ics.predictor_reset_count[i] = i;

    }

    update_pred_resets(sce);

    memcpy(sce->band_alt, sce->band_type, sizeof(sce->band_type));

    for (sfb = PRED_SFB_START; sfb < pmax; sfb++) {

        int cost1, cost2, cb_p;

        float dist1, dist2, dist_spec_err = 0.0f;

        const int cb_n = sce->band_type[sfb];

        const int start_coef = sce->ics.swb_offset[sfb];

        const int num_coeffs = sce->ics.swb_offset[sfb + 1] - start_coef;

        const FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[sfb];

        if (start_coef + num_coeffs > MAX_PREDICTORS ||

            (s->cur_channel && sce->band_type[sfb] >= INTENSITY_BT2) ||

            sce->band_type[sfb] == NOISE_BT)

            continue;

        /* Normal coefficients */

        abs_pow34_v(O34, &sce->coeffs[start_coef], num_coeffs);

        dist1 = quantize_and_encode_band_cost(s, NULL, &sce->coeffs[start_coef], NULL,

                                              O34, num_coeffs, sce->sf_idx[sfb],

                                              cb_n, s->lambda / band->threshold, INFINITY, &cost1, NULL, 0);

        cost_coeffs += cost1;

        /* Encoded coefficients - needed for #bits, band type and quant. error */

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

            SENT[i] = sce->coeffs[start_coef + i] - sce->prcoeffs[start_coef + i];

        abs_pow34_v(S34, SENT, num_coeffs);

        if (cb_n < RESERVED_BT)

            cb_p = find_min_book(find_max_val(1, num_coeffs, S34), sce->sf_idx[sfb]);

        else

            cb_p = cb_n;

        quantize_and_encode_band_cost(s, NULL, SENT, QERR, S34, num_coeffs,

                                      sce->sf_idx[sfb], cb_p, s->lambda / band->threshold, INFINITY,

                                      &cost2, NULL, 0);

        /* Reconstructed coefficients - needed for distortion measurements */

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

            sce->prcoeffs[start_coef + i] += QERR[i] != 0.0f ? (sce->prcoeffs[start_coef + i] - QERR[i]) : 0.0f;

        abs_pow34_v(P34, &sce->prcoeffs[start_coef], num_coeffs);

        if (cb_n < RESERVED_BT)

            cb_p = find_min_book(find_max_val(1, num_coeffs, P34), sce->sf_idx[sfb]);

        else

            cb_p = cb_n;

        dist2 = quantize_and_encode_band_cost(s, NULL, &sce->prcoeffs[start_coef], NULL,

                                              P34, num_coeffs, sce->sf_idx[sfb],

                                              cb_p, s->lambda / band->threshold, INFINITY, NULL, NULL, 0);

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

            dist_spec_err += (O34[i] - P34[i])*(O34[i] - P34[i]);

        dist_spec_err *= s->lambda / band->threshold;

        dist2 += dist_spec_err;

        if (dist2 <= dist1 && cb_p <= cb_n) {

            cost_pred += cost2;

            sce->ics.prediction_used[sfb] = 1;

            sce->band_alt[sfb]  = cb_n;

            sce->band_type[sfb] = cb_p;

            count++;

        } else {

            cost_pred += cost1;

            sce->band_alt[sfb] = cb_p;

        }

    }

    if (count && cost_coeffs < cost_pred) {

        count = 0;

        for (sfb = PRED_SFB_START; sfb < pmax; sfb++)

            RESTORE_PRED(sce, sfb);

        memset(&sce->ics.prediction_used, 0, sizeof(sce->ics.prediction_used));

    }

    sce->ics.predictor_present = !!count;

}


static int scan_file(AVFormatContext *avctx, AVStream *vst, AVStream *ast, int file)

{

    MlvContext *mlv = avctx->priv_data;

    AVIOContext *pb = mlv->pb[file];

    int ret;

    while (!avio_feof(pb)) {

        int type;

        unsigned int size;

        type = avio_rl32(pb);

        size = avio_rl32(pb);

        avio_skip(pb, 8); //timestamp

        if (size < 16)

            break;

        size -= 16;

        if (vst && type == MKTAG('R','A','W','I') && size >= 164) {

            vst->codec->width  = avio_rl16(pb);

            vst->codec->height = avio_rl16(pb);

            if (avio_rl32(pb) != 1)

                avpriv_request_sample(avctx, "raw api version");

            avio_skip(pb, 20); // pointer, width, height, pitch, frame_size

            vst->codec->bits_per_coded_sample = avio_rl32(pb);

            avio_skip(pb, 8 + 16 + 24); // black_level, white_level, xywh, active_area, exposure_bias

            if (avio_rl32(pb) != 0x2010100) /* RGGB */

                avpriv_request_sample(avctx, "cfa_pattern");

            avio_skip(pb, 80); // calibration_illuminant1, color_matrix1, dynamic_range

            vst->codec->pix_fmt  = AV_PIX_FMT_BAYER_RGGB16LE;

            vst->codec->codec_tag = MKTAG('B', 'I', 'T', 16);

            size -= 164;

        } else if (ast && type == MKTAG('W', 'A', 'V', 'I') && size >= 16) {

            ret = ff_get_wav_header(pb, ast->codec, 16);

            if (ret < 0)

                return ret;

            size -= 16;

        } else if (type == MKTAG('I','N','F','O')) {

            if (size > 0)

                read_string(avctx, pb, "info", size);

            continue;

        } else if (type == MKTAG('I','D','N','T') && size >= 36) {

            read_string(avctx, pb, "cameraName", 32);

            read_uint32(avctx, pb, "cameraModel", "0x%"PRIx32);

            size -= 36;

            if (size >= 32) {

                read_string(avctx, pb, "cameraSerial", 32);

                size -= 32;

            }

        } else if (type == MKTAG('L','E','N','S') && size >= 48) {

            read_uint16(avctx, pb, "focalLength", "%i");

            read_uint16(avctx, pb, "focalDist", "%i");

            read_uint16(avctx, pb, "aperture", "%i");

            read_uint8(avctx, pb, "stabilizerMode", "%i");

            read_uint8(avctx, pb, "autofocusMode", "%i");

            read_uint32(avctx, pb, "flags", "0x%"PRIx32);

            read_uint32(avctx, pb, "lensID", "%"PRIi32);

            read_string(avctx, pb, "lensName", 32);

            size -= 48;

            if (size >= 32) {

                read_string(avctx, pb, "lensSerial", 32);

                size -= 32;

            }

        } else if (vst && type == MKTAG('V', 'I', 'D', 'F') && size >= 4) {

            uint64_t pts = avio_rl32(pb);

            ff_add_index_entry(&vst->index_entries, &vst->nb_index_entries, &vst->index_entries_allocated_size,

                               avio_tell(pb) - 20, pts, file, 0, AVINDEX_KEYFRAME);

            size -= 4;

        } else if (ast && type == MKTAG('A', 'U', 'D', 'F') && size >= 4) {

            uint64_t pts = avio_rl32(pb);

            ff_add_index_entry(&ast->index_entries, &ast->nb_index_entries, &ast->index_entries_allocated_size,

                               avio_tell(pb) - 20, pts, file, 0, AVINDEX_KEYFRAME);

            size -= 4;

        } else if (vst && type == MKTAG('W','B','A','L') && size >= 28) {

            read_uint32(avctx, pb, "wb_mode", "%"PRIi32);

            read_uint32(avctx, pb, "kelvin", "%"PRIi32);

            read_uint32(avctx, pb, "wbgain_r", "%"PRIi32);

            read_uint32(avctx, pb, "wbgain_g", "%"PRIi32);

            read_uint32(avctx, pb, "wbgain_b", "%"PRIi32);

            read_uint32(avctx, pb, "wbs_gm", "%"PRIi32);

            read_uint32(avctx, pb, "wbs_ba", "%"PRIi32);

            size -= 28;

        } else if (type == MKTAG('R','T','C','I') && size >= 20) {

            char str[32];

            struct tm time = { 0 };

            time.tm_sec    = avio_rl16(pb);

            time.tm_min    = avio_rl16(pb);

            time.tm_hour   = avio_rl16(pb);

            time.tm_mday   = avio_rl16(pb);

            time.tm_mon    = avio_rl16(pb);

            time.tm_year   = avio_rl16(pb);

            time.tm_wday   = avio_rl16(pb);

            time.tm_yday   = avio_rl16(pb);

            time.tm_isdst  = avio_rl16(pb);

            avio_skip(pb, 2);

            strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", &time);

            av_dict_set(&avctx->metadata, "time", str, 0);

            size -= 20;

        } else if (type == MKTAG('E','X','P','O') && size >= 16) {

            av_dict_set(&avctx->metadata, "isoMode", avio_rl32(pb) ? "auto" : "manual", 0);

            read_uint32(avctx, pb, "isoValue", "%"PRIi32);

            read_uint32(avctx, pb, "isoAnalog", "%"PRIi32);

            read_uint32(avctx, pb, "digitalGain", "%"PRIi32);

            size -= 16;

            if (size >= 8) {

                read_uint64(avctx, pb, "shutterValue", "%"PRIi64);

                size -= 8;

            }

        } else if (type == MKTAG('S','T','Y','L') && size >= 36) {

            read_uint32(avctx, pb, "picStyleId", "%"PRIi32);

            read_uint32(avctx, pb, "contrast", "%"PRIi32);

            read_uint32(avctx, pb, "sharpness", "%"PRIi32);

            read_uint32(avctx, pb, "saturation", "%"PRIi32);

            read_uint32(avctx, pb, "colortone", "%"PRIi32);

            read_string(avctx, pb, "picStyleName", 16);

            size -= 36;

        } else if (type == MKTAG('M','A','R','K')) {

        } else if (type == MKTAG('N','U','L','L')) {

        } else if (type == MKTAG('M','L','V','I')) { /* occurs when MLV and Mnn files are concatenated */

        } else {

            av_log(avctx, AV_LOG_INFO, "unsupported tag %c%c%c%c, size %u\n", type&0xFF, (type>>8)&0xFF, (type>>16)&0xFF, (type>>24)&0xFF, size);

        }

        avio_skip(pb, size);

    }

    return 0;

}


static int sab_diamond_search(MpegEncContext * s, int *best, int dmin,

                                       int src_index, int ref_index, int const penalty_factor,

                                       int size, int h, int flags)

{

    MotionEstContext * const c= &s->me;

    me_cmp_func cmpf, chroma_cmpf;

    Minima minima[MAX_SAB_SIZE];

    const int minima_count= FFABS(c->dia_size);

    int i, j;

    LOAD_COMMON

    LOAD_COMMON2

    unsigned map_generation = c->map_generation;

    av_assert1(minima_count <= MAX_SAB_SIZE);

    cmpf        = s->mecc.me_cmp[size];

    chroma_cmpf = s->mecc.me_cmp[size + 1];

    /*Note j<MAX_SAB_SIZE is needed if MAX_SAB_SIZE < ME_MAP_SIZE as j can

      become larger due to MVs overflowing their ME_MAP_MV_BITS bits space in map

     */

    for(j=i=0; i<ME_MAP_SIZE && j<MAX_SAB_SIZE; i++){

        uint32_t key= map[i];

        key += (1<<(ME_MAP_MV_BITS-1)) + (1<<(2*ME_MAP_MV_BITS-1));

        if((key&((-1)<<(2*ME_MAP_MV_BITS))) != map_generation) continue;

        minima[j].height= score_map[i];

        minima[j].x= key & ((1<<ME_MAP_MV_BITS)-1); key>>=ME_MAP_MV_BITS;

        minima[j].y= key & ((1<<ME_MAP_MV_BITS)-1);

        minima[j].x-= (1<<(ME_MAP_MV_BITS-1));

        minima[j].y-= (1<<(ME_MAP_MV_BITS-1));

        // all entries in map should be in range except if the mv overflows their ME_MAP_MV_BITS bits space

        if(   minima[j].x > xmax || minima[j].x < xmin

           || minima[j].y > ymax || minima[j].y < ymin)

            continue;

        minima[j].checked=0;

        if(minima[j].x || minima[j].y)

            minima[j].height+= (mv_penalty[((minima[j].x)<<shift)-pred_x] + mv_penalty[((minima[j].y)<<shift)-pred_y])*penalty_factor;

        j++;

    }

    qsort(minima, j, sizeof(Minima), minima_cmp);

    for(; j<minima_count; j++){

        minima[j].height=256*256*256*64;

        minima[j].checked=0;

        minima[j].x= minima[j].y=0;

    }

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

        const int x= minima[i].x;

        const int y= minima[i].y;

        int d;

        if(minima[i].checked) continue;

        if(   x >= xmax || x <= xmin

           || y >= ymax || y <= ymin)

           continue;

        SAB_CHECK_MV(x-1, y)

        SAB_CHECK_MV(x+1, y)

        SAB_CHECK_MV(x  , y-1)

        SAB_CHECK_MV(x  , y+1)

        minima[i].checked= 1;

    }

    best[0]= minima[0].x;

    best[1]= minima[0].y;

    dmin= minima[0].height;

    if(   best[0] < xmax && best[0] > xmin

       && best[1] < ymax && best[1] > ymin){

        int d;

        //ensure that the refernece samples for hpel refinement are in the map

        CHECK_MV(best[0]-1, best[1])

        CHECK_MV(best[0]+1, best[1])

        CHECK_MV(best[0], best[1]-1)

        CHECK_MV(best[0], best[1]+1)

    }

    return dmin;

}


static int configure_filtergraph(FilterGraph *fg)

{

    return fg->graph_desc ? configure_complex_filter(fg) : configure_video_filters(fg);

}


void palette8torgb15(const uint8_t *src, uint8_t *dst, long num_pixels, const uint8_t *palette)

{

	long i;

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

		((uint16_t *)dst)[i] = ((uint16_t *)palette)[ src[i] ];

}


void st_set_trace_file_enabled(bool enable)

{

    if (enable == !!trace_fp) {

        return; /* no change */

    }

    /* Halt trace writeout */

    flush_trace_file(true);

    trace_writeout_enabled = false;

    flush_trace_file(true);

    if (enable) {

        static const TraceRecord header = {

            .event = HEADER_EVENT_ID,

            .timestamp_ns = HEADER_MAGIC,

            .x1 = HEADER_VERSION,

        };

        trace_fp = fopen(trace_file_name, "w");

        if (!trace_fp) {

            return;

        }

        if (fwrite(&header, sizeof header, 1, trace_fp) != 1) {

            fclose(trace_fp);

            trace_fp = NULL;

            return;

        }

        /* Resume trace writeout */

        trace_writeout_enabled = true;

        flush_trace_file(false);

    } else {

        fclose(trace_fp);

        trace_fp = NULL;

    }

}


void ff_ac3_bit_alloc_calc_mask(AC3BitAllocParameters *s, int16_t *band_psd,

                                int start, int end, int fast_gain, int is_lfe,

                                int dba_mode, int dba_nsegs, uint8_t *dba_offsets,

                                uint8_t *dba_lengths, uint8_t *dba_values,

                                int16_t *mask)

{

    int16_t excite[50]; /* excitation */

    int bin, k;

    int bndstrt, bndend, begin, end1, tmp;

    int lowcomp, fastleak, slowleak;

    /* excitation function */

    bndstrt = bin_to_band_tab[start];

    bndend = bin_to_band_tab[end-1] + 1;

    if (bndstrt == 0) {

        lowcomp = 0;

        lowcomp = calc_lowcomp1(lowcomp, band_psd[0], band_psd[1], 384);

        excite[0] = band_psd[0] - fast_gain - lowcomp;

        lowcomp = calc_lowcomp1(lowcomp, band_psd[1], band_psd[2], 384);

        excite[1] = band_psd[1] - fast_gain - lowcomp;

        begin = 7;

        for (bin = 2; bin < 7; bin++) {

            if (!(is_lfe && bin == 6))

                lowcomp = calc_lowcomp1(lowcomp, band_psd[bin], band_psd[bin+1], 384);

            fastleak = band_psd[bin] - fast_gain;

            slowleak = band_psd[bin] - s->slow_gain;

            excite[bin] = fastleak - lowcomp;

            if (!(is_lfe && bin == 6)) {

                if (band_psd[bin] <= band_psd[bin+1]) {

                    begin = bin + 1;

                    break;

                }

            }

        }

        end1=bndend;

        if (end1 > 22) end1=22;

        for (bin = begin; bin < end1; bin++) {

            if (!(is_lfe && bin == 6))

                lowcomp = calc_lowcomp(lowcomp, band_psd[bin], band_psd[bin+1], bin);

            fastleak = FFMAX(fastleak - s->fast_decay, band_psd[bin] - fast_gain);

            slowleak = FFMAX(slowleak - s->slow_decay, band_psd[bin] - s->slow_gain);

            excite[bin] = FFMAX(fastleak - lowcomp, slowleak);

        }

        begin = 22;

    } else {

        /* coupling channel */

        begin = bndstrt;

        fastleak = (s->cpl_fast_leak << 8) + 768;

        slowleak = (s->cpl_slow_leak << 8) + 768;

    }

    for (bin = begin; bin < bndend; bin++) {

        fastleak = FFMAX(fastleak - s->fast_decay, band_psd[bin] - fast_gain);

        slowleak = FFMAX(slowleak - s->slow_decay, band_psd[bin] - s->slow_gain);

        excite[bin] = FFMAX(fastleak, slowleak);

    }

    /* compute masking curve */

    for (bin = bndstrt; bin < bndend; bin++) {

        tmp = s->db_per_bit - band_psd[bin];

        if (tmp > 0) {

            excite[bin] += tmp >> 2;

        }

        mask[bin] = FFMAX(ff_ac3_hearing_threshold_tab[bin >> s->sr_shift][s->sr_code], excite[bin]);

    }

    /* delta bit allocation */

    if (dba_mode == DBA_REUSE || dba_mode == DBA_NEW) {

        int band, seg, delta;

        band = 0;

        for (seg = 0; seg < dba_nsegs; seg++) {

            band += dba_offsets[seg];

            if (dba_values[seg] >= 4) {

                delta = (dba_values[seg] - 3) << 7;

            } else {

                delta = (dba_values[seg] - 4) << 7;

            }

            for (k = 0; k < dba_lengths[seg]; k++) {

                mask[band] += delta;

                band++;

            }

        }

    }

}


static struct iovec *adjust_sg(struct iovec *sg, int len, int *iovcnt)

{

    while (len && *iovcnt) {

        if (len < sg->iov_len) {

            sg->iov_len -= len;

            sg->iov_base += len;

            len = 0;

        } else {

            len -= sg->iov_len;

            sg++;

            *iovcnt -= 1;

        }

    }

    return sg;

}


static int qemu_rdma_registration_start(QEMUFile *f, void *opaque,

                                        uint64_t flags)

{

    QEMUFileRDMA *rfile = opaque;

    RDMAContext *rdma = rfile->rdma;

    CHECK_ERROR_STATE();

    DDDPRINTF("start section: %" PRIu64 "\n", flags);

    qemu_put_be64(f, RAM_SAVE_FLAG_HOOK);

    qemu_fflush(f);

    return 0;

}


static int nbd_negotiate_handle_info(NBDClient *client, uint32_t length,

                                     uint32_t opt, uint16_t myflags,

                                     Error **errp)

{

    int rc;

    char name[NBD_MAX_NAME_SIZE + 1];

    NBDExport *exp;

    uint16_t requests;

    uint16_t request;

    uint32_t namelen;

    bool sendname = false;

    bool blocksize = false;

    uint32_t sizes[3];

    char buf[sizeof(uint64_t) + sizeof(uint16_t)];

    const char *msg;

    /* Client sends:

        4 bytes: L, name length (can be 0)

        L bytes: export name

        2 bytes: N, number of requests (can be 0)

        N * 2 bytes: N requests

    */

    if (length < sizeof(namelen) + sizeof(requests)) {

        msg = "overall request too short";

    if (nbd_read(client->ioc, &namelen, sizeof(namelen), errp) < 0) {

        return -EIO;

    be32_to_cpus(&namelen);

    length -= sizeof(namelen);

    if (namelen > length - sizeof(requests) || (length - namelen) % 2) {

        msg = "name length is incorrect";

    if (nbd_read(client->ioc, name, namelen, errp) < 0) {

        return -EIO;

    name[namelen] = '\0';

    length -= namelen;

    trace_nbd_negotiate_handle_export_name_request(name);

    if (nbd_read(client->ioc, &requests, sizeof(requests), errp) < 0) {

        return -EIO;

    be16_to_cpus(&requests);

    length -= sizeof(requests);

    trace_nbd_negotiate_handle_info_requests(requests);

    if (requests != length / sizeof(request)) {

        msg = "incorrect number of  requests for overall length";

    while (requests--) {

        if (nbd_read(client->ioc, &request, sizeof(request), errp) < 0) {

            return -EIO;

        be16_to_cpus(&request);

        length -= sizeof(request);

        trace_nbd_negotiate_handle_info_request(request,

                                                nbd_info_lookup(request));

        /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;

         * everything else is either a request we don't know or

         * something we send regardless of request */

        switch (request) {

        case NBD_INFO_NAME:

            sendname = true;

            break;

        case NBD_INFO_BLOCK_SIZE:

            blocksize = true;

            break;

    assert(length == 0);

    exp = nbd_export_find(name);

    if (!exp) {

        return nbd_negotiate_send_rep_err(client->ioc, NBD_REP_ERR_UNKNOWN,

                                          opt, errp, "export '%s' not present",

                                          name);

    /* Don't bother sending NBD_INFO_NAME unless client requested it */

    if (sendname) {

        rc = nbd_negotiate_send_info(client, opt, NBD_INFO_NAME, namelen, name,

                                     errp);

        if (rc < 0) {

            return rc;

    /* Send NBD_INFO_DESCRIPTION only if available, regardless of

     * client request */

    if (exp->description) {

        size_t len = strlen(exp->description);

        rc = nbd_negotiate_send_info(client, opt, NBD_INFO_DESCRIPTION,

                                     len, exp->description, errp);

        if (rc < 0) {

            return rc;

    /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size

     * according to whether the client requested it, and according to

     * whether this is OPT_INFO or OPT_GO. */

    /* minimum - 1 for back-compat, or 512 if client is new enough.

     * TODO: consult blk_bs(blk)->bl.request_alignment? */

    sizes[0] = (opt == NBD_OPT_INFO || blocksize) ? BDRV_SECTOR_SIZE : 1;

    /* preferred - Hard-code to 4096 for now.

     * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */

    sizes[1] = 4096;

    /* maximum - At most 32M, but smaller as appropriate. */

    sizes[2] = MIN(blk_get_max_transfer(exp->blk), NBD_MAX_BUFFER_SIZE);

    trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);

    cpu_to_be32s(&sizes[0]);

    cpu_to_be32s(&sizes[1]);

    cpu_to_be32s(&sizes[2]);

    rc = nbd_negotiate_send_info(client, opt, NBD_INFO_BLOCK_SIZE,

                                 sizeof(sizes), sizes, errp);

    if (rc < 0) {

        return rc;

    /* Send NBD_INFO_EXPORT always */

    trace_nbd_negotiate_new_style_size_flags(exp->size,

                                             exp->nbdflags | myflags);

    stq_be_p(buf, exp->size);

    stw_be_p(buf + 8, exp->nbdflags | myflags);

    rc = nbd_negotiate_send_info(client, opt, NBD_INFO_EXPORT,

                                 sizeof(buf), buf, errp);

    if (rc < 0) {

        return rc;

    /* If the client is just asking for NBD_OPT_INFO, but forgot to

     * request block sizes, return an error.

     * TODO: consult blk_bs(blk)->request_align, and only error if it

     * is not 1? */

    if (opt == NBD_OPT_INFO && !blocksize) {

        return nbd_negotiate_send_rep_err(client->ioc,

                                          NBD_REP_ERR_BLOCK_SIZE_REQD, opt,

                                          errp,

                                          "request NBD_INFO_BLOCK_SIZE to "

                                          "use this export");

    /* Final reply */

    rc = nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, opt, errp);

    if (rc < 0) {

        return rc;

    if (opt == NBD_OPT_GO) {

        client->exp = exp;

        QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);

        nbd_export_get(client->exp);

        rc = 1;

    return rc;

 invalid:

    if (nbd_drop(client->ioc, length, errp) < 0) {

        return -EIO;

    return nbd_negotiate_send_rep_err(client->ioc, NBD_REP_ERR_INVALID, opt,

                                      errp, "%s", msg);


static int unix_close(MigrationState *s)

{

    DPRINTF("unix_close\n");

    if (s->fd != -1) {

        close(s->fd);

        s->fd = -1;

    }

    return 0;

}


static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)

{

        MOVMuxContext *mov = s->priv_data;

        MOVTrack *trk = &mov->tracks[pkt->stream_index];

        AVCodecParameters *par = trk->par;

        int64_t frag_duration = 0;

        int size = pkt->size;

        int ret = check_pkt(s, pkt);

        if (ret < 0)

            return ret;

        if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {

            int i;

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

                mov->tracks[i].frag_discont = 1;

            mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;

        }

        if (!pkt->size) {

            if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {

                trk->start_dts = pkt->dts;

                if (pkt->pts != AV_NOPTS_VALUE)

                    trk->start_cts = pkt->pts - pkt->dts;

                else

                    trk->start_cts = 0;

            }

            if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||

                trk->par->codec_id == AV_CODEC_ID_FLAC) {

                int side_size = 0;

                uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);

                if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {

                    void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);

                    if (!newextra)

                        return AVERROR(ENOMEM);

                    av_free(par->extradata);

                    par->extradata = newextra;

                    memcpy(par->extradata, side, side_size);

                    par->extradata_size = side_size;

                    mov->need_rewrite_extradata = 1;

                }

            }

            return 0;             /* Discard 0 sized packets */

        }

        if (trk->entry && pkt->stream_index < s->nb_streams)

            frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,

                                         s->streams[pkt->stream_index]->time_base,

                                         AV_TIME_BASE_Q);

        if ((mov->max_fragment_duration &&

             frag_duration >= mov->max_fragment_duration) ||

             (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||

             (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&

              par->codec_type == AVMEDIA_TYPE_VIDEO &&

              trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {

            if (frag_duration >= mov->min_fragment_duration) {

                // Set the duration of this track to line up with the next

                // sample in this track. This avoids relying on AVPacket

                // duration, but only helps for this particular track, not

                // for the other ones that are flushed at the same time.

                trk->track_duration = pkt->dts - trk->start_dts;

                if (pkt->pts != AV_NOPTS_VALUE)

                    trk->end_pts = pkt->pts;

                else

                    trk->end_pts = pkt->dts;

                trk->end_reliable = 1;

                mov_auto_flush_fragment(s, 0);

            }

        }

        return ff_mov_write_packet(s, pkt);

}


static int msrle_decode_frame(AVCodecContext *avctx,

                              void *data, int *data_size,

                              AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MsrleContext *s = avctx->priv_data;

    int istride = FFALIGN(avctx->width*avctx->bits_per_coded_sample, 32) / 8;

    s->buf = buf;

    s->size = buf_size;

    s->frame.reference = 3;

    s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;

    if (avctx->reget_buffer(avctx, &s->frame)) {

        av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");

        return -1;

    }

    if (avctx->bits_per_coded_sample > 1 && avctx->bits_per_coded_sample <= 8) {

        const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);

        if (pal) {

            s->frame.palette_has_changed = 1;

            memcpy(s->pal, pal, AVPALETTE_SIZE);

        }

    }

    /* make the palette available */

    memcpy(s->frame.data[1], s->pal, AVPALETTE_SIZE);

    /* FIXME how to correctly detect RLE ??? */

    if (avctx->height * istride == avpkt->size) { /* assume uncompressed */

        int linesize = (avctx->width * avctx->bits_per_coded_sample + 7) / 8;

        uint8_t *ptr = s->frame.data[0];

        uint8_t *buf = avpkt->data + (avctx->height-1)*istride;

        int i, j;

        for (i = 0; i < avctx->height; i++) {

            if (avctx->bits_per_coded_sample == 4) {

                for (j = 0; j < avctx->width - 1; j += 2) {

                    ptr[j+0] = buf[j>>1] >> 4;

                    ptr[j+1] = buf[j>>1] & 0xF;

                }

                if (avctx->width & 1)

                    ptr[j+0] = buf[j>>1] >> 4;

            } else {

                memcpy(ptr, buf, linesize);

            }

            buf -= istride;

            ptr += s->frame.linesize[0];

        }

    } else {

        bytestream2_init(&s->gb, buf, buf_size);

        ff_msrle_decode(avctx, (AVPicture*)&s->frame, avctx->bits_per_coded_sample, &s->gb);

    }

    *data_size = sizeof(AVFrame);

    *(AVFrame*)data = s->frame;

    /* report that the buffer was completely consumed */

    return buf_size;

}


static int blk_root_inactivate(BdrvChild *child)

{

    BlockBackend *blk = child->opaque;

    if (blk->disable_perm) {

        return 0;

    }

    /* Only inactivate BlockBackends for guest devices (which are inactive at

     * this point because the VM is stopped) and unattached monitor-owned

     * BlockBackends. If there is still any other user like a block job, then

     * we simply can't inactivate the image. */

    if (!blk->dev && !blk->name[0]) {

        return -EPERM;

    }

    blk->disable_perm = true;

    if (blk->root) {

        bdrv_child_try_set_perm(blk->root, 0, BLK_PERM_ALL, &error_abort);

    }

    return 0;

}


qcrypto_tls_creds_x509_unload(QCryptoTLSCredsX509 *creds)

{

    if (creds->data) {

        gnutls_certificate_free_credentials(creds->data);

        creds->data = NULL;


static int xhci_submit(XHCIState *xhci, XHCITransfer *xfer, XHCIEPContext *epctx)

{

    uint64_t mfindex;

    DPRINTF("xhci_submit(slotid=%d,epid=%d)\n", xfer->slotid, xfer->epid);

    xfer->in_xfer = epctx->type>>2;

    switch(epctx->type) {

    case ET_INTR_OUT:

    case ET_INTR_IN:

    case ET_BULK_OUT:

    case ET_BULK_IN:

        xfer->pkts = 0;

        xfer->iso_xfer = false;

        break;

    case ET_ISO_OUT:

    case ET_ISO_IN:

        xfer->pkts = 1;

        xfer->iso_xfer = true;

        mfindex = xhci_mfindex_get(xhci);

        xhci_calc_iso_kick(xhci, xfer, epctx, mfindex);

        xhci_check_iso_kick(xhci, xfer, epctx, mfindex);

        if (xfer->running_retry) {

            return -1;

        }

        break;

    default:

        fprintf(stderr, "xhci: unknown or unhandled EP "

                "(type %d, in %d, ep %02x)\n",

                epctx->type, xfer->in_xfer, xfer->epid);

        return -1;

    }

    if (xhci_setup_packet(xfer) < 0) {

        return -1;

    }

    usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);

    xhci_complete_packet(xfer);

    if (!xfer->running_async && !xfer->running_retry) {

        xhci_kick_ep(xhci, xfer->slotid, xfer->epid, xfer->streamid);

    }

    return 0;

}


static inline void softusb_read_dmem(MilkymistSoftUsbState *s,

        uint32_t offset, uint8_t *buf, uint32_t len)

{

    if (offset + len >= s->dmem_size) {

        error_report("milkymist_softusb: read dmem out of bounds "

                "at offset 0x%x, len %d", offset, len);

        return;

    }

    memcpy(buf, s->dmem_ptr + offset, len);

}


static int request_frame(AVFilterLink *outlink)

{

    AVFilterBufferRef *outpicref;

    MovieContext *movie = outlink->src->priv;

    int ret;

    if (movie->is_done)

        return AVERROR_EOF;

    if ((ret = movie_get_frame(outlink)) < 0)

        return ret;

    outpicref = avfilter_ref_buffer(movie->picref, ~0);

    avfilter_start_frame(outlink, outpicref);

    avfilter_draw_slice(outlink, 0, outlink->h, 1);

    avfilter_end_frame(outlink);

    return 0;

}


static void baum_chr_open(Chardev *chr,

                          ChardevBackend *backend,

                          bool *be_opened,

                          Error **errp)

{

    BaumChardev *baum = BAUM_CHARDEV(chr);

    brlapi_handle_t *handle;

    handle = g_malloc0(brlapi_getHandleSize());

    baum->brlapi = handle;

    baum->brlapi_fd = brlapi__openConnection(handle, NULL, NULL);

    if (baum->brlapi_fd == -1) {

        error_setg(errp, "brlapi__openConnection: %s",

                   brlapi_strerror(brlapi_error_location()));

        g_free(handle);

        return;

    }

    baum->deferred_init = 0;

    baum->cellCount_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, baum_cellCount_timer_cb, baum);

    qemu_set_fd_handler(baum->brlapi_fd, baum_chr_read, NULL, baum);

}


static int can_safely_read(GetBitContext* gb, int bits) {

    return get_bits_left(gb) >= bits;

}


size_t qcrypto_cipher_get_block_len(QCryptoCipherAlgorithm alg)

{

    if (alg >= G_N_ELEMENTS(alg_key_len)) {

        return 0;

    }

    return alg_block_len[alg];

}


petalogix_ml605_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    MemoryRegion *address_space_mem = get_system_memory();

    DeviceState *dev, *dma, *eth0;

    Object *ds, *cs;

    MicroBlazeCPU *cpu;

    SysBusDevice *busdev;

    DriveInfo *dinfo;

    int i;

    MemoryRegion *phys_lmb_bram = g_new(MemoryRegion, 1);

    MemoryRegion *phys_ram = g_new(MemoryRegion, 1);

    qemu_irq irq[32];

    /* init CPUs */

    cpu = MICROBLAZE_CPU(object_new(TYPE_MICROBLAZE_CPU));

    object_property_set_bool(OBJECT(cpu), true, "realized", &error_abort);

    /* Attach emulated BRAM through the LMB.  */

    memory_region_init_ram(phys_lmb_bram, NULL, "petalogix_ml605.lmb_bram",

                           LMB_BRAM_SIZE, &error_abort);

    vmstate_register_ram_global(phys_lmb_bram);

    memory_region_add_subregion(address_space_mem, 0x00000000, phys_lmb_bram);

    memory_region_init_ram(phys_ram, NULL, "petalogix_ml605.ram", ram_size,

                           &error_abort);

    vmstate_register_ram_global(phys_ram);

    memory_region_add_subregion(address_space_mem, MEMORY_BASEADDR, phys_ram);

    dinfo = drive_get(IF_PFLASH, 0, 0);

    /* 5th parameter 2 means bank-width

     * 10th paremeter 0 means little-endian */

    pflash_cfi01_register(FLASH_BASEADDR,

                          NULL, "petalogix_ml605.flash", FLASH_SIZE,

                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,

                          (64 * 1024), FLASH_SIZE >> 16,

                          2, 0x89, 0x18, 0x0000, 0x0, 0);

    dev = qdev_create(NULL, "xlnx.xps-intc");

    qdev_prop_set_uint32(dev, "kind-of-intr", 1 << TIMER_IRQ);

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, INTC_BASEADDR);

    sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0,

                       qdev_get_gpio_in(DEVICE(cpu), MB_CPU_IRQ));

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

        irq[i] = qdev_get_gpio_in(dev, i);

    }

    serial_mm_init(address_space_mem, UART16550_BASEADDR + 0x1000, 2,

                   irq[UART16550_IRQ], 115200, serial_hds[0],

                   DEVICE_LITTLE_ENDIAN);

    /* 2 timers at irq 2 @ 100 Mhz.  */

    dev = qdev_create(NULL, "xlnx.xps-timer");

    qdev_prop_set_uint32(dev, "one-timer-only", 0);

    qdev_prop_set_uint32(dev, "clock-frequency", 100 * 1000000);

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, TIMER_BASEADDR);

    sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, irq[TIMER_IRQ]);

    /* axi ethernet and dma initialization. */

    qemu_check_nic_model(&nd_table[0], "xlnx.axi-ethernet");

    eth0 = qdev_create(NULL, "xlnx.axi-ethernet");

    dma = qdev_create(NULL, "xlnx.axi-dma");

    /* FIXME: attach to the sysbus instead */

    object_property_add_child(qdev_get_machine(), "xilinx-eth", OBJECT(eth0),

                              NULL);

    object_property_add_child(qdev_get_machine(), "xilinx-dma", OBJECT(dma),

                              NULL);

    ds = object_property_get_link(OBJECT(dma),

                                  "axistream-connected-target", NULL);

    cs = object_property_get_link(OBJECT(dma),

                                  "axistream-control-connected-target", NULL);

    qdev_set_nic_properties(eth0, &nd_table[0]);

    qdev_prop_set_uint32(eth0, "rxmem", 0x1000);

    qdev_prop_set_uint32(eth0, "txmem", 0x1000);

    object_property_set_link(OBJECT(eth0), OBJECT(ds),

                             "axistream-connected", &error_abort);

    object_property_set_link(OBJECT(eth0), OBJECT(cs),

                             "axistream-control-connected", &error_abort);

    qdev_init_nofail(eth0);

    sysbus_mmio_map(SYS_BUS_DEVICE(eth0), 0, AXIENET_BASEADDR);

    sysbus_connect_irq(SYS_BUS_DEVICE(eth0), 0, irq[AXIENET_IRQ]);

    ds = object_property_get_link(OBJECT(eth0),

                                  "axistream-connected-target", NULL);

    cs = object_property_get_link(OBJECT(eth0),

                                  "axistream-control-connected-target", NULL);

    qdev_prop_set_uint32(dma, "freqhz", 100 * 1000000);

    object_property_set_link(OBJECT(dma), OBJECT(ds),

                             "axistream-connected", &error_abort);

    object_property_set_link(OBJECT(dma), OBJECT(cs),

                             "axistream-control-connected", &error_abort);

    qdev_init_nofail(dma);

    sysbus_mmio_map(SYS_BUS_DEVICE(dma), 0, AXIDMA_BASEADDR);

    sysbus_connect_irq(SYS_BUS_DEVICE(dma), 0, irq[AXIDMA_IRQ0]);

    sysbus_connect_irq(SYS_BUS_DEVICE(dma), 1, irq[AXIDMA_IRQ1]);

    {

        SSIBus *spi;

        dev = qdev_create(NULL, "xlnx.xps-spi");

        qdev_prop_set_uint8(dev, "num-ss-bits", NUM_SPI_FLASHES);

        qdev_init_nofail(dev);

        busdev = SYS_BUS_DEVICE(dev);

        sysbus_mmio_map(busdev, 0, SPI_BASEADDR);

        sysbus_connect_irq(busdev, 0, irq[SPI_IRQ]);

        spi = (SSIBus *)qdev_get_child_bus(dev, "spi");

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

            qemu_irq cs_line;

            dev = ssi_create_slave(spi, "n25q128");

            cs_line = qdev_get_gpio_in_named(dev, SSI_GPIO_CS, 0);

            sysbus_connect_irq(busdev, i+1, cs_line);

        }

    }

    microblaze_load_kernel(cpu, MEMORY_BASEADDR, ram_size,

                           machine->initrd_filename,

                           BINARY_DEVICE_TREE_FILE,

                           machine_cpu_reset);

}


static int mmu_translate_sfaa(CPUS390XState *env, target_ulong vaddr,

                              uint64_t asc, uint64_t asce, target_ulong *raddr,

                              int *flags, int rw)

{

    if (asce & _SEGMENT_ENTRY_INV) {

        DPRINTF("%s: SEG=0x%" PRIx64 " invalid\n", __func__, asce);

        trigger_page_fault(env, vaddr, PGM_SEGMENT_TRANS, asc, rw);

        return -1;

    }

    if (asce & _SEGMENT_ENTRY_RO) {

        *flags &= ~PAGE_WRITE;

    }

    *raddr = (asce & 0xfffffffffff00000ULL) | (vaddr & 0xfffff);

    PTE_DPRINTF("%s: SEG=0x%" PRIx64 "\n", __func__, asce);

    return 0;

}


abi_long target_mremap(abi_ulong old_addr, abi_ulong old_size,

                       abi_ulong new_size, unsigned long flags,

                       abi_ulong new_addr)

{

    int prot;

    void *host_addr;

    mmap_lock();

    if (flags & MREMAP_FIXED) {

        host_addr = (void *) syscall(__NR_mremap, g2h(old_addr),

                                     old_size, new_size,

                                     flags,

                                     g2h(new_addr));

        if (RESERVED_VA && host_addr != MAP_FAILED) {

            /* If new and old addresses overlap then the above mremap will

               already have failed with EINVAL.  */

            mmap_reserve(old_addr, old_size);

        }

    } else if (flags & MREMAP_MAYMOVE) {

        abi_ulong mmap_start;

        mmap_start = mmap_find_vma(0, new_size);

        if (mmap_start == -1) {

            errno = ENOMEM;

            host_addr = MAP_FAILED;

        } else {

            host_addr = (void *) syscall(__NR_mremap, g2h(old_addr),

                                         old_size, new_size,

                                         flags | MREMAP_FIXED,

                                         g2h(mmap_start));

            mmap_reserve(old_addr, old_size);

        }

    } else {

        int prot = 0;

        if (RESERVED_VA && old_size < new_size) {

            abi_ulong addr;

            for (addr = old_addr + old_size;

                 addr < old_addr + new_size;

                 addr++) {

                prot |= page_get_flags(addr);

            }

        }

        if (prot == 0) {

            host_addr = mremap(g2h(old_addr), old_size, new_size, flags);

            if (host_addr != MAP_FAILED && RESERVED_VA && old_size > new_size) {

                mmap_reserve(old_addr + old_size, new_size - old_size);

            }

        } else {

            errno = ENOMEM;

            host_addr = MAP_FAILED;

        }

        /* Check if address fits target address space */

        if ((unsigned long)host_addr + new_size > (abi_ulong)-1) {

            /* Revert mremap() changes */

            host_addr = mremap(g2h(old_addr), new_size, old_size, flags);

            errno = ENOMEM;

            host_addr = MAP_FAILED;

        }

    }

    if (host_addr == MAP_FAILED) {

        new_addr = -1;

    } else {

        new_addr = h2g(host_addr);

        prot = page_get_flags(old_addr);

        page_set_flags(old_addr, old_addr + old_size, 0);

        page_set_flags(new_addr, new_addr + new_size, prot | PAGE_VALID);

    }

    mmap_unlock();

    return new_addr;

}


bool migration_is_blocked(Error **errp)

{

    if (qemu_savevm_state_blocked(errp)) {

        return true;

    }

    if (migration_blockers) {

        *errp = error_copy(migration_blockers->data);

        return true;

    }

    return false;

}