static av_cold int g726_encode_init(AVCodecContext *avctx)

{

    G726Context* c = avctx->priv_data;

    if (avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL &&

        avctx->sample_rate != 8000) {

        av_log(avctx, AV_LOG_ERROR, "Sample rates other than 8kHz are not "

               "allowed when the compliance level is higher than unofficial. "

               "Resample or reduce the compliance level.\n");

        return AVERROR(EINVAL);

    }

    av_assert0(avctx->sample_rate > 0);

    if(avctx->channels != 1){

        av_log(avctx, AV_LOG_ERROR, "Only mono is supported\n");

        return -1;

    }

    if (avctx->bit_rate % avctx->sample_rate) {

        av_log(avctx, AV_LOG_ERROR, "Bitrate - Samplerate combination is invalid\n");

        return AVERROR(EINVAL);

    }

    c->code_size = (avctx->bit_rate + avctx->sample_rate/2) / avctx->sample_rate;

    if (c->code_size < 2 || c->code_size > 5) {

        av_log(avctx, AV_LOG_ERROR, "Invalid number of bits %d\n", c->code_size);

        return AVERROR(EINVAL);

    }

    avctx->bits_per_coded_sample = c->code_size;

    g726_reset(c, c->code_size - 2);

    avctx->coded_frame = avcodec_alloc_frame();

    if (!avctx->coded_frame)

        return AVERROR(ENOMEM);

    avctx->coded_frame->key_frame = 1;

    /* select a frame size that will end on a byte boundary and have a size of

       approximately 1024 bytes */

    avctx->frame_size = ((int[]){ 4096, 2736, 2048, 1640 })[c->code_size - 2];

    return 0;

}


int qemu_acl_insert(qemu_acl *acl,

                    int deny,

                    const char *match,

                    int index)

{

    qemu_acl_entry *entry;

    qemu_acl_entry *tmp;

    int i = 0;

    if (index <= 0)

        return -1;

    if (index >= acl->nentries)

        return qemu_acl_append(acl, deny, match);

    entry = qemu_malloc(sizeof(*entry));

    entry->match = qemu_strdup(match);

    entry->deny = deny;

    TAILQ_FOREACH(tmp, &acl->entries, next) {

        i++;

        if (i == index) {

            TAILQ_INSERT_BEFORE(tmp, entry, next);

            acl->nentries++;

            break;

        }

    }

    return i;

}


int64_t bdrv_get_block_status(BlockDriverState *bs,

                              int64_t sector_num,

                              int nb_sectors, int *pnum,

                              BlockDriverState **file)

{

    return bdrv_get_block_status_above(bs, backing_bs(bs),

                                       sector_num, nb_sectors, pnum, file);

}


static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)

{

    uint32_t magic;

    if (buf_size < 4)

        return 0;

    magic = be32_to_cpu(*(uint32_t *)buf);

    if (magic == VMDK3_MAGIC ||

        magic == VMDK4_MAGIC) {

        return 100;

    } else {

        const char *p = (const char *)buf;

        const char *end = p + buf_size;

        while (p < end) {

            if (*p == '#') {

                /* skip comment line */

                while (p < end && *p != '\n') {

                    p++;

                }

                p++;

                continue;

            }

            if (*p == ' ') {

                while (p < end && *p == ' ') {

                    p++;

                }

                /* skip '\r' if windows line endings used. */

                if (p < end && *p == '\r') {

                    p++;

                }

                /* only accept blank lines before 'version=' line */

                if (p == end || *p != '\n') {

                    return 0;

                }

                p++;

                continue;

            }

            if (end - p >= strlen("version=X\n")) {

                if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||

                    strncmp("version=2\n", p, strlen("version=2\n")) == 0) {

                    return 100;

                }

            }

            if (end - p >= strlen("version=X\r\n")) {

                if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||

                    strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0) {

                    return 100;

                }

            }

            return 0;

        }

        return 0;

    }

}


static int write_elf64_note(DumpState *s)

{

    Elf64_Phdr phdr;

    int endian = s->dump_info.d_endian;

    target_phys_addr_t begin = s->memory_offset - s->note_size;

    int ret;

    memset(&phdr, 0, sizeof(Elf64_Phdr));

    phdr.p_type = cpu_convert_to_target32(PT_NOTE, endian);

    phdr.p_offset = cpu_convert_to_target64(begin, endian);

    phdr.p_paddr = 0;

    phdr.p_filesz = cpu_convert_to_target64(s->note_size, endian);

    phdr.p_memsz = cpu_convert_to_target64(s->note_size, endian);

    phdr.p_vaddr = 0;

    ret = fd_write_vmcore(&phdr, sizeof(Elf64_Phdr), s);

    if (ret < 0) {

        dump_error(s, "dump: failed to write program header table.\n");

        return -1;

    }

    return 0;

}


void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)

{

    assert(!bdrv_requests_pending(bs_top));

    assert(!bdrv_requests_pending(bs_new));

    bdrv_ref(bs_top);

    change_parent_backing_link(bs_top, bs_new);

    bdrv_set_backing_hd(bs_new, bs_top);

    bdrv_unref(bs_top);

    /* bs_new is now referenced by its new parents, we don't need the

     * additional reference any more. */

    bdrv_unref(bs_new);

}


static void restore_sigcontext(CPUSH4State *regs, struct target_sigcontext *sc,

                               target_ulong *r0_p)

{

    int i;

#define COPY(x)         __get_user(regs->x, &sc->sc_##x)

    COPY(gregs[1]);

    COPY(gregs[2]); COPY(gregs[3]);

    COPY(gregs[4]); COPY(gregs[5]);

    COPY(gregs[6]); COPY(gregs[7]);

    COPY(gregs[8]); COPY(gregs[9]);

    COPY(gregs[10]); COPY(gregs[11]);

    COPY(gregs[12]); COPY(gregs[13]);

    COPY(gregs[14]); COPY(gregs[15]);

    COPY(gbr); COPY(mach);

    COPY(macl); COPY(pr);

    COPY(sr); COPY(pc);

#undef COPY

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

        __get_user(regs->fregs[i], &sc->sc_fpregs[i]);

    }

    __get_user(regs->fpscr, &sc->sc_fpscr);

    __get_user(regs->fpul, &sc->sc_fpul);

    regs->tra = -1;         /* disable syscall checks */

    __get_user(*r0_p, &sc->sc_gregs[0]);

}


static void vtd_update_iotlb(IntelIOMMUState *s, uint16_t source_id,

                             uint16_t domain_id, hwaddr addr, uint64_t slpte,

                             bool read_flags, bool write_flags)

{

    VTDIOTLBEntry *entry = g_malloc(sizeof(*entry));

    uint64_t *key = g_malloc(sizeof(*key));

    uint64_t gfn = addr >> VTD_PAGE_SHIFT_4K;

    VTD_DPRINTF(CACHE, "update iotlb sid 0x%"PRIx16 " gpa 0x%"PRIx64

                " slpte 0x%"PRIx64 " did 0x%"PRIx16, source_id, addr, slpte,

                domain_id);

    if (g_hash_table_size(s->iotlb) >= VTD_IOTLB_MAX_SIZE) {

        VTD_DPRINTF(CACHE, "iotlb exceeds size limit, forced to reset");

        vtd_reset_iotlb(s);

    }

    entry->gfn = gfn;

    entry->domain_id = domain_id;

    entry->slpte = slpte;

    entry->read_flags = read_flags;

    entry->write_flags = write_flags;

    *key = gfn | ((uint64_t)(source_id) << VTD_IOTLB_SID_SHIFT);

    g_hash_table_replace(s->iotlb, key, entry);

}


static void armv7m_nvic_init(SysBusDevice *dev)

{

    nvic_state *s= FROM_SYSBUSGIC(nvic_state, dev);

    CPUState *env;

    env = qdev_get_prop_ptr(&dev->qdev, "cpu");

    gic_init(&s->gic);

    cpu_register_physical_memory(0xe000e000, 0x1000, s->gic.iomemtype);

    s->systick.timer = qemu_new_timer(vm_clock, systick_timer_tick, s);

    if (env->v7m.nvic)

        hw_error("CPU can only have one NVIC\n");

    env->v7m.nvic = s;

    register_savevm("armv7m_nvic", -1, 1, nvic_save, nvic_load, s);

}


lookup_scalar(const OptsVisitor *ov, const char *name, Error **errp)

{

    if (ov->repeated_opts == NULL) {

        GQueue *list;

        /* the last occurrence of any QemuOpt takes effect when queried by name

         */

        list = lookup_distinct(ov, name, errp);

        return list ? g_queue_peek_tail(list) : NULL;

    }

    return g_queue_peek_head(ov->repeated_opts);

}


static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)

{

    ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);

    ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);

}


static void RENAME(hyscale_fast)(SwsContext *c, int16_t *dst,

                                 int dstWidth, const uint8_t *src,

                                 int srcW, int xInc)

{

    int16_t *filterPos = c->hLumFilterPos;

    int16_t *filter    = c->hLumFilter;

    void    *mmx2FilterCode= c->lumMmx2FilterCode;

    int i;

#if defined(PIC)

    uint64_t ebxsave;

#endif

#if ARCH_X86_64

    uint64_t retsave;

#endif

    __asm__ volatile(

#if defined(PIC)

        "mov               %%"REG_b", %5        \n\t"

#if ARCH_X86_64

        "mov               -8(%%rsp), %%"REG_a" \n\t"

        "mov               %%"REG_a", %6        \n\t"

#endif

#else

#if ARCH_X86_64

        "mov               -8(%%rsp), %%"REG_a" \n\t"

        "mov               %%"REG_a", %5        \n\t"

#endif

#endif

        "pxor                  %%mm7, %%mm7     \n\t"

        "mov                      %0, %%"REG_c" \n\t"

        "mov                      %1, %%"REG_D" \n\t"

        "mov                      %2, %%"REG_d" \n\t"

        "mov                      %3, %%"REG_b" \n\t"

        "xor               %%"REG_a", %%"REG_a" \n\t" // i

        PREFETCH"        (%%"REG_c")            \n\t"

        PREFETCH"      32(%%"REG_c")            \n\t"

        PREFETCH"      64(%%"REG_c")            \n\t"

#if ARCH_X86_64

#define CALL_MMX2_FILTER_CODE \

        "movl            (%%"REG_b"), %%esi     \n\t"\

        "call                    *%4            \n\t"\

        "movl (%%"REG_b", %%"REG_a"), %%esi     \n\t"\

        "add               %%"REG_S", %%"REG_c" \n\t"\

        "add               %%"REG_a", %%"REG_D" \n\t"\

        "xor               %%"REG_a", %%"REG_a" \n\t"\

#else

#define CALL_MMX2_FILTER_CODE \

        "movl (%%"REG_b"), %%esi        \n\t"\

        "call         *%4                       \n\t"\

        "addl (%%"REG_b", %%"REG_a"), %%"REG_c" \n\t"\

        "add               %%"REG_a", %%"REG_D" \n\t"\

        "xor               %%"REG_a", %%"REG_a" \n\t"\

#endif /* ARCH_X86_64 */

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

#if defined(PIC)

        "mov                      %5, %%"REG_b" \n\t"

#if ARCH_X86_64

        "mov                      %6, %%"REG_a" \n\t"

        "mov               %%"REG_a", -8(%%rsp) \n\t"

#endif

#else

#if ARCH_X86_64

        "mov                      %5, %%"REG_a" \n\t"

        "mov               %%"REG_a", -8(%%rsp) \n\t"

#endif

#endif

        :: "m" (src), "m" (dst), "m" (filter), "m" (filterPos),

           "m" (mmx2FilterCode)

#if defined(PIC)

          ,"m" (ebxsave)

#endif

#if ARCH_X86_64

          ,"m"(retsave)

#endif

        : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S, "%"REG_D

#if !defined(PIC)

         ,"%"REG_b

#endif

    );

    for (i=dstWidth-1; (i*xInc)>>16 >=srcW-1; i--)

        dst[i] = src[srcW-1]*128;

}


static int decode_dc_progressive(MJpegDecodeContext *s, int16_t *block,

                                 int component, int dc_index,

                                 uint16_t *quant_matrix, int Al)

{

    int val;

    s->bdsp.clear_block(block);

    val = mjpeg_decode_dc(s, dc_index);

    if (val == 0xfffff) {

        av_log(s->avctx, AV_LOG_ERROR, "error dc\n");

        return AVERROR_INVALIDDATA;

    }

    val = (val * (quant_matrix[0] << Al)) + s->last_dc[component];

    s->last_dc[component] = val;

    block[0] = val;

    return 0;

}


static void vga_screen_dump_common(VGAState *s, const char *filename,

                                   int w, int h)

{

    DisplayState *saved_ds, ds1, *ds = &ds1;

    DisplayChangeListener dcl;

    /* XXX: this is a little hackish */

    vga_invalidate_display(s);

    saved_ds = s->ds;

    memset(ds, 0, sizeof(DisplayState));

    memset(&dcl, 0, sizeof(DisplayChangeListener));

    dcl.dpy_update = vga_save_dpy_update;

    dcl.dpy_resize = vga_save_dpy_resize;

    dcl.dpy_refresh = vga_save_dpy_refresh;

    register_displaychangelistener(ds, &dcl);

    ds->surface = qemu_create_displaysurface(ds, w, h);

    s->ds = ds;

    s->graphic_mode = -1;

    vga_update_display(s);

    ppm_save(filename, ds->surface);

    qemu_free_displaysurface(ds);

    s->ds = saved_ds;

}


static int ehci_state_execute(EHCIQueue *q)

{

    EHCIPacket *p = QTAILQ_FIRST(&q->packets);

    int again = 0;

    assert(p != NULL);

    assert(p->qtdaddr == q->qtdaddr);

    if (ehci_qh_do_overlay(q) != 0) {

        return -1;

    }

    // TODO verify enough time remains in the uframe as in 4.4.1.1

    // TODO write back ptr to async list when done or out of time

    // TODO Windows does not seem to ever set the MULT field

    if (!q->async) {

        int transactCtr = get_field(q->qh.epcap, QH_EPCAP_MULT);

        if (!transactCtr) {

            ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);

            again = 1;

            goto out;

        }

    }

    if (q->async) {

        ehci_set_usbsts(q->ehci, USBSTS_REC);

    }

    p->usb_status = ehci_execute(p, "process");

    if (p->usb_status == USB_RET_PROCERR) {

        again = -1;

        goto out;

    }

    if (p->usb_status == USB_RET_ASYNC) {

        ehci_flush_qh(q);

        trace_usb_ehci_packet_action(p->queue, p, "async");

        p->async = EHCI_ASYNC_INFLIGHT;

        ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);

        again = (ehci_fill_queue(p) == USB_RET_PROCERR) ? -1 : 1;

        goto out;

    }

    ehci_set_state(q->ehci, q->async, EST_EXECUTING);

    again = 1;

out:

    return again;

}


static void update_msix_table_msg_data(S390PCIBusDevice *pbdev, uint64_t offset,

                                       uint64_t *data, uint8_t len)

{

    uint32_t val;

    uint8_t *msg_data;

    if (offset % PCI_MSIX_ENTRY_SIZE != 8) {

        return;

    }

    if (len != 4) {

        DPRINTF("access msix table msg data but len is %d\n", len);

        return;

    }

    msg_data = (uint8_t *)data - offset % PCI_MSIX_ENTRY_SIZE +

               PCI_MSIX_ENTRY_VECTOR_CTRL;

    val = pci_get_long(msg_data) | (pbdev->fid << ZPCI_MSI_VEC_BITS);

    pci_set_long(msg_data, val);

    DPRINTF("update msix msg_data to 0x%" PRIx64 "\n", *data);

}


void ff_er_add_slice(ERContext *s, int startx, int starty,

                     int endx, int endy, int status)

{

    const int start_i  = av_clip(startx + starty * s->mb_width, 0, s->mb_num - 1);

    const int end_i    = av_clip(endx   + endy   * s->mb_width, 0, s->mb_num);

    const int start_xy = s->mb_index2xy[start_i];

    const int end_xy   = s->mb_index2xy[end_i];

    int mask           = -1;

    if (s->avctx->hwaccel && s->avctx->hwaccel->decode_slice)

        return;

    if (start_i > end_i || start_xy > end_xy) {

        av_log(s->avctx, AV_LOG_ERROR,

               "internal error, slice end before start\n");

        return;

    }

    if (!s->avctx->error_concealment)

        return;

    mask &= ~VP_START;

    if (status & (ER_AC_ERROR | ER_AC_END)) {

        mask           &= ~(ER_AC_ERROR | ER_AC_END);

        s->error_count -= end_i - start_i + 1;

    }

    if (status & (ER_DC_ERROR | ER_DC_END)) {

        mask           &= ~(ER_DC_ERROR | ER_DC_END);

        s->error_count -= end_i - start_i + 1;

    }

    if (status & (ER_MV_ERROR | ER_MV_END)) {

        mask           &= ~(ER_MV_ERROR | ER_MV_END);

        s->error_count -= end_i - start_i + 1;

    }

    if (status & ER_MB_ERROR) {

        s->error_occurred = 1;

        s->error_count    = INT_MAX;

    }

    if (mask == ~0x7F) {

        memset(&s->error_status_table[start_xy], 0,

               (end_xy - start_xy) * sizeof(uint8_t));

    } else {

        int i;

        for (i = start_xy; i < end_xy; i++)

            s->error_status_table[i] &= mask;

    }

    if (end_i == s->mb_num)

        s->error_count = INT_MAX;

    else {

        s->error_status_table[end_xy] &= mask;

        s->error_status_table[end_xy] |= status;

    }

    s->error_status_table[start_xy] |= VP_START;

    if (start_xy > 0 && !(s->avctx->active_thread_type & FF_THREAD_SLICE) &&

        er_supported(s) && s->avctx->skip_top * s->mb_width < start_i) {

        int prev_status = s->error_status_table[s->mb_index2xy[start_i - 1]];

        prev_status &= ~ VP_START;

        if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END)) {

            s->error_occurred = 1;

            s->error_count = INT_MAX;

        }

    }

}


static inline void RENAME(yuv2yuvX)(SwsContext *c, const int16_t *lumFilter,

                                    const int16_t **lumSrc, int lumFilterSize,

                                    const int16_t *chrFilter, const int16_t **chrUSrc,

                                    const int16_t **chrVSrc,

                                    int chrFilterSize, const int16_t **alpSrc,

                                    uint8_t *dest, uint8_t *uDest, uint8_t *vDest,

                                    uint8_t *aDest, long dstW, long chrDstW)

{

    if (uDest) {

        YSCALEYUV2YV12X(CHR_MMX_FILTER_OFFSET, uDest, chrDstW, 0)

        YSCALEYUV2YV12X(CHR_MMX_FILTER_OFFSET, vDest, chrDstW + c->uv_off, c->uv_off)

    }

    if (CONFIG_SWSCALE_ALPHA && aDest) {

        YSCALEYUV2YV12X(ALP_MMX_FILTER_OFFSET, aDest, dstW, 0)

    }

    YSCALEYUV2YV12X(LUM_MMX_FILTER_OFFSET, dest, dstW, 0)

}


void bitmap_clear(unsigned long *map, long start, long nr)
{
    unsigned long *p = map + BIT_WORD(start);
    const long size = start + nr;
    int bits_to_clear = BITS_PER_LONG - (start % BITS_PER_LONG);
    unsigned long mask_to_clear = BITMAP_FIRST_WORD_MASK(start);
    while (nr - bits_to_clear >= 0) {
        *p &= ~mask_to_clear;
        nr -= bits_to_clear;
        bits_to_clear = BITS_PER_LONG;
        mask_to_clear = ~0UL;
        p++;
    }
    if (nr) {
        mask_to_clear &= BITMAP_LAST_WORD_MASK(size);
        *p &= ~mask_to_clear;
    }
}


static inline void tcg_temp_free_internal(int idx)
{
    TCGContext *s = &tcg_ctx;
    TCGTemp *ts;
    int k;
    assert(idx >= s->nb_globals && idx < s->nb_temps);
    ts = &s->temps[idx];
    assert(ts->temp_allocated != 0);
    ts->temp_allocated = 0;
    k = ts->base_type;
    if (ts->temp_local)
        k += TCG_TYPE_COUNT;
    ts->next_free_temp = s->first_free_temp[k];
    s->first_free_temp[k] = idx;


static void mcf_uart_do_tx(mcf_uart_state *s)

{

    if (s->tx_enabled && (s->sr & MCF_UART_TxEMP) == 0) {

        if (s->chr)

            qemu_chr_fe_write(s->chr, (unsigned char *)&s->tb, 1);

        s->sr |= MCF_UART_TxEMP;

    }

    if (s->tx_enabled) {

        s->sr |= MCF_UART_TxRDY;

    } else {

        s->sr &= ~MCF_UART_TxRDY;

    }

}


int av_cold ff_mlp_init_crc2D(AVCodecParserContext *s)

{

    if (!crc_init_2D) {

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

        crc_init_2D = 1;

    }

    return 0;

}


static void mainstone_common_init(MemoryRegion *address_space_mem,

                                  MachineState *machine,

                                  enum mainstone_model_e model, int arm_id)

{

    uint32_t sector_len = 256 * 1024;

    hwaddr mainstone_flash_base[] = { MST_FLASH_0, MST_FLASH_1 };

    PXA2xxState *mpu;

    DeviceState *mst_irq;

    DriveInfo *dinfo;

    int i;

    int be;

    MemoryRegion *rom = g_new(MemoryRegion, 1);

    const char *cpu_model = machine->cpu_model;

    if (!cpu_model)

        cpu_model = "pxa270-c5";

    /* Setup CPU & memory */

    mpu = pxa270_init(address_space_mem, mainstone_binfo.ram_size, cpu_model);

    memory_region_init_ram(rom, NULL, "mainstone.rom", MAINSTONE_ROM,

                           &error_abort);

    vmstate_register_ram_global(rom);

    memory_region_set_readonly(rom, true);

    memory_region_add_subregion(address_space_mem, 0, rom);

#ifdef TARGET_WORDS_BIGENDIAN

    be = 1;

#else

    be = 0;

#endif

    /* There are two 32MiB flash devices on the board */

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

        dinfo = drive_get(IF_PFLASH, 0, i);

        if (!dinfo) {

            if (qtest_enabled()) {

                break;

            }

            fprintf(stderr, "Two flash images must be given with the "

                    "'pflash' parameter\n");

            exit(1);

        }

        if (!pflash_cfi01_register(mainstone_flash_base[i], NULL,

                                   i ? "mainstone.flash1" : "mainstone.flash0",

                                   MAINSTONE_FLASH,

                                   blk_by_legacy_dinfo(dinfo),

                                   sector_len, MAINSTONE_FLASH / sector_len,

                                   4, 0, 0, 0, 0, be)) {

            fprintf(stderr, "qemu: Error registering flash memory.\n");

            exit(1);

        }

    }

    mst_irq = sysbus_create_simple("mainstone-fpga", MST_FPGA_PHYS,

                    qdev_get_gpio_in(mpu->gpio, 0));

    /* setup keypad */

    pxa27x_register_keypad(mpu->kp, map, 0xe0);

    /* MMC/SD host */

    pxa2xx_mmci_handlers(mpu->mmc, NULL, qdev_get_gpio_in(mst_irq, MMC_IRQ));

    pxa2xx_pcmcia_set_irq_cb(mpu->pcmcia[0],

            qdev_get_gpio_in(mst_irq, S0_IRQ),

            qdev_get_gpio_in(mst_irq, S0_CD_IRQ));

    pxa2xx_pcmcia_set_irq_cb(mpu->pcmcia[1],

            qdev_get_gpio_in(mst_irq, S1_IRQ),

            qdev_get_gpio_in(mst_irq, S1_CD_IRQ));

    smc91c111_init(&nd_table[0], MST_ETH_PHYS,

                    qdev_get_gpio_in(mst_irq, ETHERNET_IRQ));

    mainstone_binfo.kernel_filename = machine->kernel_filename;

    mainstone_binfo.kernel_cmdline = machine->kernel_cmdline;

    mainstone_binfo.initrd_filename = machine->initrd_filename;

    mainstone_binfo.board_id = arm_id;

    arm_load_kernel(mpu->cpu, &mainstone_binfo);

}


Visitor *validate_test_init(TestInputVisitorData *data,

                             const char *json_string, ...)

{

    Visitor *v;

    va_list ap;

    va_start(ap, json_string);

    data->obj = qobject_from_jsonv(json_string, &ap);

    va_end(ap);

    g_assert(data->obj != NULL);

    data->qiv = qmp_input_visitor_new_strict(data->obj);

    g_assert(data->qiv != NULL);

    v = qmp_input_get_visitor(data->qiv);

    g_assert(v != NULL);

    return v;

}


void vmstate_save_state(QEMUFile *f, const VMStateDescription *vmsd,

                        void *opaque, QJSON *vmdesc)

{

    VMStateField *field = vmsd->fields;

    trace_vmstate_save_state_top(vmsd->name);

    if (vmsd->pre_save) {

        vmsd->pre_save(opaque);

    }

    if (vmdesc) {

        json_prop_str(vmdesc, "vmsd_name", vmsd->name);

        json_prop_int(vmdesc, "version", vmsd->version_id);

        json_start_array(vmdesc, "fields");

    }

    while (field->name) {

        if (!field->field_exists ||

            field->field_exists(opaque, vmsd->version_id)) {

            void *first_elem = opaque + field->offset;

            int i, n_elems = vmstate_n_elems(opaque, field);

            int size = vmstate_size(opaque, field);

            int64_t old_offset, written_bytes;

            QJSON *vmdesc_loop = vmdesc;

            trace_vmstate_save_state_loop(vmsd->name, field->name, n_elems);

            if (field->flags & VMS_POINTER) {

                first_elem = *(void **)first_elem;

                assert(first_elem  || !n_elems);

            }

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

                void *curr_elem = first_elem + size * i;

                vmsd_desc_field_start(vmsd, vmdesc_loop, field, i, n_elems);

                old_offset = qemu_ftell_fast(f);

                if (field->flags & VMS_ARRAY_OF_POINTER) {

                    assert(curr_elem);

                    curr_elem = *(void **)curr_elem;

                }

                if (field->flags & VMS_STRUCT) {

                    vmstate_save_state(f, field->vmsd, curr_elem, vmdesc_loop);

                } else {

                    field->info->put(f, curr_elem, size, field, vmdesc_loop);

                }

                written_bytes = qemu_ftell_fast(f) - old_offset;

                vmsd_desc_field_end(vmsd, vmdesc_loop, field, written_bytes, i);

                /* Compressed arrays only care about the first element */

                if (vmdesc_loop && vmsd_can_compress(field)) {

                    vmdesc_loop = NULL;

                }

            }

        } else {

            if (field->flags & VMS_MUST_EXIST) {

                error_report("Output state validation failed: %s/%s",

                        vmsd->name, field->name);

                assert(!(field->flags & VMS_MUST_EXIST));

            }

        }

        field++;

    }

    if (vmdesc) {

        json_end_array(vmdesc);

    }

    vmstate_subsection_save(f, vmsd, opaque, vmdesc);

}


static AVStream *add_av_stream1(FFServerStream *stream,

                                AVCodecContext *codec, int copy)

{

    AVStream *fst;

    if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))

        return NULL;

    fst = av_mallocz(sizeof(AVStream));

    if (!fst)

        return NULL;

    if (copy) {

        fst->codec = avcodec_alloc_context3(codec->codec);

        if (!fst->codec) {

            av_free(fst);

            return NULL;

        }

        avcodec_copy_context(fst->codec, codec);

    } else

        /* live streams must use the actual feed's codec since it may be

         * updated later to carry extradata needed by them.

         */

        fst->codec = codec;

    fst->priv_data = av_mallocz(sizeof(FeedData));

    fst->index = stream->nb_streams;

    avpriv_set_pts_info(fst, 33, 1, 90000);

    fst->sample_aspect_ratio = codec->sample_aspect_ratio;

    stream->streams[stream->nb_streams++] = fst;

    return fst;

}


static av_cold int vp3_decode_init(AVCodecContext *avctx)

{

    Vp3DecodeContext *s = avctx->priv_data;

    int i, inter, plane;

    int c_width;

    int c_height;

    int y_fragment_count, c_fragment_count;

    if (avctx->codec_tag == MKTAG('V','P','3','0'))

        s->version = 0;

    else

        s->version = 1;

    s->avctx = avctx;

    s->width = FFALIGN(avctx->width, 16);

    s->height = FFALIGN(avctx->height, 16);

    if (avctx->pix_fmt == PIX_FMT_NONE)

        avctx->pix_fmt = PIX_FMT_YUV420P;

    avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;

    if(avctx->idct_algo==FF_IDCT_AUTO)

        avctx->idct_algo=FF_IDCT_VP3;

    ff_dsputil_init(&s->dsp, avctx);

    ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);

    /* initialize to an impossible value which will force a recalculation

     * in the first frame decode */

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

        s->qps[i] = -1;

    avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);

    s->y_superblock_width = (s->width + 31) / 32;

    s->y_superblock_height = (s->height + 31) / 32;

    s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;

    /* work out the dimensions for the C planes */

    c_width = s->width >> s->chroma_x_shift;

    c_height = s->height >> s->chroma_y_shift;

    s->c_superblock_width = (c_width + 31) / 32;

    s->c_superblock_height = (c_height + 31) / 32;

    s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;

    s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);

    s->u_superblock_start = s->y_superblock_count;

    s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;

    s->macroblock_width = (s->width + 15) / 16;

    s->macroblock_height = (s->height + 15) / 16;

    s->macroblock_count = s->macroblock_width * s->macroblock_height;

    s->fragment_width[0] = s->width / FRAGMENT_PIXELS;

    s->fragment_height[0] = s->height / FRAGMENT_PIXELS;

    s->fragment_width[1]  = s->fragment_width[0]  >> s->chroma_x_shift;

    s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;

    /* fragment count covers all 8x8 blocks for all 3 planes */

    y_fragment_count     = s->fragment_width[0] * s->fragment_height[0];

    c_fragment_count     = s->fragment_width[1] * s->fragment_height[1];

    s->fragment_count    = y_fragment_count + 2*c_fragment_count;

    s->fragment_start[1] = y_fragment_count;

    s->fragment_start[2] = y_fragment_count + c_fragment_count;

    if (!s->theora_tables)

    {

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

            s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];

            s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];

            s->base_matrix[0][i] = vp31_intra_y_dequant[i];

            s->base_matrix[1][i] = vp31_intra_c_dequant[i];

            s->base_matrix[2][i] = vp31_inter_dequant[i];

            s->filter_limit_values[i] = vp31_filter_limit_values[i];

        }

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

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

                s->qr_count[inter][plane]= 1;

                s->qr_size [inter][plane][0]= 63;

                s->qr_base [inter][plane][0]=

                s->qr_base [inter][plane][1]= 2*inter + (!!plane)*!inter;

            }

        }

        /* init VLC tables */

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

            /* DC histograms */

            init_vlc(&s->dc_vlc[i], 11, 32,

                &dc_bias[i][0][1], 4, 2,

                &dc_bias[i][0][0], 4, 2, 0);

            /* group 1 AC histograms */

            init_vlc(&s->ac_vlc_1[i], 11, 32,

                &ac_bias_0[i][0][1], 4, 2,

                &ac_bias_0[i][0][0], 4, 2, 0);

            /* group 2 AC histograms */

            init_vlc(&s->ac_vlc_2[i], 11, 32,

                &ac_bias_1[i][0][1], 4, 2,

                &ac_bias_1[i][0][0], 4, 2, 0);

            /* group 3 AC histograms */

            init_vlc(&s->ac_vlc_3[i], 11, 32,

                &ac_bias_2[i][0][1], 4, 2,

                &ac_bias_2[i][0][0], 4, 2, 0);

            /* group 4 AC histograms */

            init_vlc(&s->ac_vlc_4[i], 11, 32,

                &ac_bias_3[i][0][1], 4, 2,

                &ac_bias_3[i][0][0], 4, 2, 0);

        }

    } else {

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

            /* DC histograms */

            if (init_vlc(&s->dc_vlc[i], 11, 32,

                &s->huffman_table[i][0][1], 8, 4,

                &s->huffman_table[i][0][0], 8, 4, 0) < 0)

                goto vlc_fail;

            /* group 1 AC histograms */

            if (init_vlc(&s->ac_vlc_1[i], 11, 32,

                &s->huffman_table[i+16][0][1], 8, 4,

                &s->huffman_table[i+16][0][0], 8, 4, 0) < 0)

                goto vlc_fail;

            /* group 2 AC histograms */

            if (init_vlc(&s->ac_vlc_2[i], 11, 32,

                &s->huffman_table[i+16*2][0][1], 8, 4,

                &s->huffman_table[i+16*2][0][0], 8, 4, 0) < 0)

                goto vlc_fail;

            /* group 3 AC histograms */

            if (init_vlc(&s->ac_vlc_3[i], 11, 32,

                &s->huffman_table[i+16*3][0][1], 8, 4,

                &s->huffman_table[i+16*3][0][0], 8, 4, 0) < 0)

                goto vlc_fail;

            /* group 4 AC histograms */

            if (init_vlc(&s->ac_vlc_4[i], 11, 32,

                &s->huffman_table[i+16*4][0][1], 8, 4,

                &s->huffman_table[i+16*4][0][0], 8, 4, 0) < 0)

                goto vlc_fail;

        }

    }

    init_vlc(&s->superblock_run_length_vlc, 6, 34,

        &superblock_run_length_vlc_table[0][1], 4, 2,

        &superblock_run_length_vlc_table[0][0], 4, 2, 0);

    init_vlc(&s->fragment_run_length_vlc, 5, 30,

        &fragment_run_length_vlc_table[0][1], 4, 2,

        &fragment_run_length_vlc_table[0][0], 4, 2, 0);

    init_vlc(&s->mode_code_vlc, 3, 8,

        &mode_code_vlc_table[0][1], 2, 1,

        &mode_code_vlc_table[0][0], 2, 1, 0);

    init_vlc(&s->motion_vector_vlc, 6, 63,

        &motion_vector_vlc_table[0][1], 2, 1,

        &motion_vector_vlc_table[0][0], 2, 1, 0);

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

        s->current_frame.data[i] = NULL;

        s->last_frame.data[i] = NULL;

        s->golden_frame.data[i] = NULL;

    }

    return allocate_tables(avctx);

vlc_fail:

    av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");

    return -1;

}


static inline void RENAME(bgr24ToUV)(uint8_t *dstU, uint8_t *dstV, uint8_t *src1, uint8_t *src2, long width)

{

#ifdef HAVE_MMX

	asm volatile(

		"mov %4, %%"REG_a"		\n\t"

		"movq "MANGLE(w1111)", %%mm5		\n\t"

		"movq "MANGLE(bgr2UCoeff)", %%mm6		\n\t"

		"pxor %%mm7, %%mm7		\n\t"

		"lea (%%"REG_a", %%"REG_a", 2), %%"REG_b"	\n\t"

		"add %%"REG_b", %%"REG_b"	\n\t"

		ASMALIGN16

		"1:				\n\t"

		PREFETCH" 64(%0, %%"REG_b")	\n\t"

		PREFETCH" 64(%1, %%"REG_b")	\n\t"

#if defined (HAVE_MMX2) || defined (HAVE_3DNOW)

		"movq (%0, %%"REG_b"), %%mm0	\n\t"

		"movq (%1, %%"REG_b"), %%mm1	\n\t"

		"movq 6(%0, %%"REG_b"), %%mm2	\n\t"

		"movq 6(%1, %%"REG_b"), %%mm3	\n\t"

		PAVGB(%%mm1, %%mm0)

		PAVGB(%%mm3, %%mm2)

		"movq %%mm0, %%mm1		\n\t"

		"movq %%mm2, %%mm3		\n\t"

		"psrlq $24, %%mm0		\n\t"

		"psrlq $24, %%mm2		\n\t"

		PAVGB(%%mm1, %%mm0)

		PAVGB(%%mm3, %%mm2)

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

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

#else

		"movd (%0, %%"REG_b"), %%mm0	\n\t"

		"movd (%1, %%"REG_b"), %%mm1	\n\t"

		"movd 3(%0, %%"REG_b"), %%mm2	\n\t"

		"movd 3(%1, %%"REG_b"), %%mm3	\n\t"

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

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

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

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

		"paddw %%mm1, %%mm0		\n\t"

		"paddw %%mm3, %%mm2		\n\t"

		"paddw %%mm2, %%mm0		\n\t"

		"movd 6(%0, %%"REG_b"), %%mm4	\n\t"

		"movd 6(%1, %%"REG_b"), %%mm1	\n\t"

		"movd 9(%0, %%"REG_b"), %%mm2	\n\t"

		"movd 9(%1, %%"REG_b"), %%mm3	\n\t"

		"punpcklbw %%mm7, %%mm4		\n\t"

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

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

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

		"paddw %%mm1, %%mm4		\n\t"

		"paddw %%mm3, %%mm2		\n\t"

		"paddw %%mm4, %%mm2		\n\t"

		"psrlw $2, %%mm0		\n\t"

		"psrlw $2, %%mm2		\n\t"

#endif

		"movq "MANGLE(bgr2VCoeff)", %%mm1		\n\t"

		"movq "MANGLE(bgr2VCoeff)", %%mm3		\n\t"

		"pmaddwd %%mm0, %%mm1		\n\t"

		"pmaddwd %%mm2, %%mm3		\n\t"

		"pmaddwd %%mm6, %%mm0		\n\t"

		"pmaddwd %%mm6, %%mm2		\n\t"

#ifndef FAST_BGR2YV12

		"psrad $8, %%mm0		\n\t"

		"psrad $8, %%mm1		\n\t"

		"psrad $8, %%mm2		\n\t"

		"psrad $8, %%mm3		\n\t"

#endif

		"packssdw %%mm2, %%mm0		\n\t"

		"packssdw %%mm3, %%mm1		\n\t"

		"pmaddwd %%mm5, %%mm0		\n\t"

		"pmaddwd %%mm5, %%mm1		\n\t"

		"packssdw %%mm1, %%mm0		\n\t" // V1 V0 U1 U0

		"psraw $7, %%mm0		\n\t"

#if defined (HAVE_MMX2) || defined (HAVE_3DNOW)

		"movq 12(%0, %%"REG_b"), %%mm4	\n\t"

		"movq 12(%1, %%"REG_b"), %%mm1	\n\t"

		"movq 18(%0, %%"REG_b"), %%mm2	\n\t"

		"movq 18(%1, %%"REG_b"), %%mm3	\n\t"

		PAVGB(%%mm1, %%mm4)

		PAVGB(%%mm3, %%mm2)

		"movq %%mm4, %%mm1		\n\t"

		"movq %%mm2, %%mm3		\n\t"

		"psrlq $24, %%mm4		\n\t"

		"psrlq $24, %%mm2		\n\t"

		PAVGB(%%mm1, %%mm4)

		PAVGB(%%mm3, %%mm2)

		"punpcklbw %%mm7, %%mm4		\n\t"

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

#else

		"movd 12(%0, %%"REG_b"), %%mm4	\n\t"

		"movd 12(%1, %%"REG_b"), %%mm1	\n\t"

		"movd 15(%0, %%"REG_b"), %%mm2	\n\t"

		"movd 15(%1, %%"REG_b"), %%mm3	\n\t"

		"punpcklbw %%mm7, %%mm4		\n\t"

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

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

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

		"paddw %%mm1, %%mm4		\n\t"

		"paddw %%mm3, %%mm2		\n\t"

		"paddw %%mm2, %%mm4		\n\t"

		"movd 18(%0, %%"REG_b"), %%mm5	\n\t"

		"movd 18(%1, %%"REG_b"), %%mm1	\n\t"

		"movd 21(%0, %%"REG_b"), %%mm2	\n\t"

		"movd 21(%1, %%"REG_b"), %%mm3	\n\t"

		"punpcklbw %%mm7, %%mm5		\n\t"

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

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

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

		"paddw %%mm1, %%mm5		\n\t"

		"paddw %%mm3, %%mm2		\n\t"

		"paddw %%mm5, %%mm2		\n\t"

		"movq "MANGLE(w1111)", %%mm5		\n\t"

		"psrlw $2, %%mm4		\n\t"

		"psrlw $2, %%mm2		\n\t"

#endif

		"movq "MANGLE(bgr2VCoeff)", %%mm1		\n\t"

		"movq "MANGLE(bgr2VCoeff)", %%mm3		\n\t"

		"pmaddwd %%mm4, %%mm1		\n\t"

		"pmaddwd %%mm2, %%mm3		\n\t"

		"pmaddwd %%mm6, %%mm4		\n\t"

		"pmaddwd %%mm6, %%mm2		\n\t"

#ifndef FAST_BGR2YV12

		"psrad $8, %%mm4		\n\t"

		"psrad $8, %%mm1		\n\t"

		"psrad $8, %%mm2		\n\t"

		"psrad $8, %%mm3		\n\t"

#endif

		"packssdw %%mm2, %%mm4		\n\t"

		"packssdw %%mm3, %%mm1		\n\t"

		"pmaddwd %%mm5, %%mm4		\n\t"

		"pmaddwd %%mm5, %%mm1		\n\t"

		"add $24, %%"REG_b"		\n\t"

		"packssdw %%mm1, %%mm4		\n\t" // V3 V2 U3 U2

		"psraw $7, %%mm4		\n\t"

		"movq %%mm0, %%mm1		\n\t"

		"punpckldq %%mm4, %%mm0		\n\t"

		"punpckhdq %%mm4, %%mm1		\n\t"

		"packsswb %%mm1, %%mm0		\n\t"

		"paddb "MANGLE(bgr2UVOffset)", %%mm0	\n\t"

		"movd %%mm0, (%2, %%"REG_a")	\n\t"

		"punpckhdq %%mm0, %%mm0		\n\t"

		"movd %%mm0, (%3, %%"REG_a")	\n\t"

		"add $4, %%"REG_a"		\n\t"

		" js 1b				\n\t"

		: : "r" (src1+width*6), "r" (src2+width*6), "r" (dstU+width), "r" (dstV+width), "g" (-width)

		: "%"REG_a, "%"REG_b

	);

#else

	int i;

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

	{

		int b= src1[6*i + 0] + src1[6*i + 3] + src2[6*i + 0] + src2[6*i + 3];

		int g= src1[6*i + 1] + src1[6*i + 4] + src2[6*i + 1] + src2[6*i + 4];

		int r= src1[6*i + 2] + src1[6*i + 5] + src2[6*i + 2] + src2[6*i + 5];

		dstU[i]= ((RU*r + GU*g + BU*b)>>(RGB2YUV_SHIFT+2)) + 128;

		dstV[i]= ((RV*r + GV*g + BV*b)>>(RGB2YUV_SHIFT+2)) + 128;

	}

#endif

}


static av_cold int fbdev_write_header(AVFormatContext *h)

{

    FBDevContext *fbdev = h->priv_data;

    enum AVPixelFormat pix_fmt;

    AVStream *st = NULL;

    int ret, flags = O_RDWR;

    int i;

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

        if (h->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {

            if (!st) {

                fbdev->index = i;

                st = h->streams[i];

            } else {

                av_log(h, AV_LOG_WARNING, "More than one video stream found. First one is used.\n");

                break;

            }

        }

    }

    if (!st) {

        av_log(h, AV_LOG_ERROR, "No video stream found.\n");

        return AVERROR(EINVAL);

    }

    if ((fbdev->fd = avpriv_open(h->filename, flags)) == -1) {

        ret = AVERROR(errno);

        av_log(h, AV_LOG_ERROR,

               "Could not open framebuffer device '%s': %s\n",

               h->filename, av_err2str(ret));

        return ret;

    }

    if (ioctl(fbdev->fd, FBIOGET_VSCREENINFO, &fbdev->varinfo) < 0) {

        ret = AVERROR(errno);

        av_log(h, AV_LOG_ERROR, "FBIOGET_VSCREENINFO: %s\n", av_err2str(ret));

        goto fail;

    }

    if (ioctl(fbdev->fd, FBIOGET_FSCREENINFO, &fbdev->fixinfo) < 0) {

        ret = AVERROR(errno);

        av_log(h, AV_LOG_ERROR, "FBIOGET_FSCREENINFO: %s\n", av_err2str(ret));

        goto fail;

    }

    pix_fmt = ff_get_pixfmt_from_fb_varinfo(&fbdev->varinfo);

    if (pix_fmt == AV_PIX_FMT_NONE) {

        ret = AVERROR(EINVAL);

        av_log(h, AV_LOG_ERROR, "Framebuffer pixel format not supported.\n");

        goto fail;

    }

    fbdev->data = mmap(NULL, fbdev->fixinfo.smem_len, PROT_WRITE, MAP_SHARED, fbdev->fd, 0);

    if (fbdev->data == MAP_FAILED) {

        ret = AVERROR(errno);

        av_log(h, AV_LOG_ERROR, "Error in mmap(): %s\n", av_err2str(ret));

        goto fail;

    }

    return 0;

  fail:

    close(fbdev->fd);

    return ret;

}


static int qcow2_truncate(BlockDriverState *bs, int64_t offset)

{

    BDRVQcowState *s = bs->opaque;

    int ret, new_l1_size;

    if (offset & 511) {

        return -EINVAL;

    }

    /* cannot proceed if image has snapshots */

    if (s->nb_snapshots) {

        return -ENOTSUP;

    }

    /* shrinking is currently not supported */

    if (offset < bs->total_sectors * 512) {

        return -ENOTSUP;

    }

    new_l1_size = size_to_l1(s, offset);

    ret = qcow2_grow_l1_table(bs, new_l1_size);

    if (ret < 0) {

        return ret;

    }

    /* write updated header.size */

    offset = cpu_to_be64(offset);

    ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, size),

                      &offset, sizeof(uint64_t));

    if (ret < 0) {

        return ret;

    }

    s->l1_vm_state_index = new_l1_size;

    return 0;

}


int qemu_mutex_trylock(QemuMutex *mutex)

{

    int owned;

    owned = TryEnterCriticalSection(&mutex->lock);

    if (owned) {

        assert(mutex->owner == 0);

        mutex->owner = GetCurrentThreadId();

    }

    return !owned;

}


static void nic_reset(void *opaque)

{

    EEPRO100State *s = opaque;

    TRACE(OTHER, logout("%p\n", s));

    /* TODO: Clearing of multicast table for selective reset, too? */

    memset(&s->mult[0], 0, sizeof(s->mult));

    nic_selective_reset(s);

}


static void usb_mtp_object_readdir(MTPState *s, MTPObject *o)

{

    struct dirent *entry;

    DIR *dir;

    if (o->have_children) {

        return;

    }

    o->have_children = true;

    dir = opendir(o->path);

    if (!dir) {

        return;

    }

#ifdef __linux__

    int watchfd = usb_mtp_add_watch(s->inotifyfd, o->path);

    if (watchfd == -1) {

        fprintf(stderr, "usb-mtp: failed to add watch for %s\n", o->path);

    } else {

        trace_usb_mtp_inotify_event(s->dev.addr, o->path,

                                    0, "Watch Added");

        o->watchfd = watchfd;

    }

#endif

    while ((entry = readdir(dir)) != NULL) {

        usb_mtp_add_child(s, o, entry->d_name);

    }

    closedir(dir);

}


static int swScale(SwsContext *c, const uint8_t *src[],

                   int srcStride[], int srcSliceY,

                   int srcSliceH, uint8_t *dst[], int dstStride[])

{

    /* load a few things into local vars to make the code more readable?

     * and faster */

    const int srcW                   = c->srcW;

    const int dstW                   = c->dstW;

    const int dstH                   = c->dstH;

    const int chrDstW                = c->chrDstW;

    const int chrSrcW                = c->chrSrcW;

    const int lumXInc                = c->lumXInc;

    const int chrXInc                = c->chrXInc;

    const enum PixelFormat dstFormat = c->dstFormat;

    const int flags                  = c->flags;

    int32_t *vLumFilterPos           = c->vLumFilterPos;

    int32_t *vChrFilterPos           = c->vChrFilterPos;

    int32_t *hLumFilterPos           = c->hLumFilterPos;

    int32_t *hChrFilterPos           = c->hChrFilterPos;

    int16_t *vLumFilter              = c->vLumFilter;

    int16_t *vChrFilter              = c->vChrFilter;

    int16_t *hLumFilter              = c->hLumFilter;

    int16_t *hChrFilter              = c->hChrFilter;

    int32_t *lumMmxFilter            = c->lumMmxFilter;

    int32_t *chrMmxFilter            = c->chrMmxFilter;

    const int vLumFilterSize         = c->vLumFilterSize;

    const int vChrFilterSize         = c->vChrFilterSize;

    const int hLumFilterSize         = c->hLumFilterSize;

    const int hChrFilterSize         = c->hChrFilterSize;

    int16_t **lumPixBuf              = c->lumPixBuf;

    int16_t **chrUPixBuf             = c->chrUPixBuf;

    int16_t **chrVPixBuf             = c->chrVPixBuf;

    int16_t **alpPixBuf              = c->alpPixBuf;

    const int vLumBufSize            = c->vLumBufSize;

    const int vChrBufSize            = c->vChrBufSize;

    uint8_t *formatConvBuffer        = c->formatConvBuffer;

    uint32_t *pal                    = c->pal_yuv;

    yuv2planar1_fn yuv2plane1        = c->yuv2plane1;

    yuv2planarX_fn yuv2planeX        = c->yuv2planeX;

    yuv2interleavedX_fn yuv2nv12cX   = c->yuv2nv12cX;

    yuv2packed1_fn yuv2packed1       = c->yuv2packed1;

    yuv2packed2_fn yuv2packed2       = c->yuv2packed2;

    yuv2packedX_fn yuv2packedX       = c->yuv2packedX;

    const int chrSrcSliceY           =     srcSliceY  >> c->chrSrcVSubSample;

    const int chrSrcSliceH           = -((-srcSliceH) >> c->chrSrcVSubSample);

    int should_dither                = is9_OR_10BPS(c->srcFormat) ||

                                       is16BPS(c->srcFormat);

    int lastDstY;

    /* vars which will change and which we need to store back in the context */

    int dstY         = c->dstY;

    int lumBufIndex  = c->lumBufIndex;

    int chrBufIndex  = c->chrBufIndex;

    int lastInLumBuf = c->lastInLumBuf;

    int lastInChrBuf = c->lastInChrBuf;

    if (isPacked(c->srcFormat)) {

        src[0] =

        src[1] =

        src[2] =

        src[3] = src[0];

        srcStride[0] =

        srcStride[1] =

        srcStride[2] =

        srcStride[3] = srcStride[0];

    }

    srcStride[1] <<= c->vChrDrop;

    srcStride[2] <<= c->vChrDrop;

    DEBUG_BUFFERS("swScale() %p[%d] %p[%d] %p[%d] %p[%d] -> %p[%d] %p[%d] %p[%d] %p[%d]\n",

                  src[0], srcStride[0], src[1], srcStride[1],

                  src[2], srcStride[2], src[3], srcStride[3],

                  dst[0], dstStride[0], dst[1], dstStride[1],

                  dst[2], dstStride[2], dst[3], dstStride[3]);

    DEBUG_BUFFERS("srcSliceY: %d srcSliceH: %d dstY: %d dstH: %d\n",

                  srcSliceY, srcSliceH, dstY, dstH);

    DEBUG_BUFFERS("vLumFilterSize: %d vLumBufSize: %d vChrFilterSize: %d vChrBufSize: %d\n",

                  vLumFilterSize, vLumBufSize, vChrFilterSize, vChrBufSize);

    if (dstStride[0] % 8 != 0 || dstStride[1] % 8 != 0 ||

        dstStride[2] % 8 != 0 || dstStride[3] % 8 != 0) {

        static int warnedAlready = 0; // FIXME maybe move this into the context

        if (flags & SWS_PRINT_INFO && !warnedAlready) {

            av_log(c, AV_LOG_WARNING,

                   "Warning: dstStride is not aligned!\n"

                   "         ->cannot do aligned memory accesses anymore\n");

            warnedAlready = 1;

        }

    }

    /* Note the user might start scaling the picture in the middle so this

     * will not get executed. This is not really intended but works

     * currently, so people might do it. */

    if (srcSliceY == 0) {

        lumBufIndex  = -1;

        chrBufIndex  = -1;

        dstY         = 0;

        lastInLumBuf = -1;

        lastInChrBuf = -1;

    }

    if (!should_dither) {

        c->chrDither8 = c->lumDither8 = ff_sws_pb_64;

    }

    lastDstY = dstY;

    for (; dstY < dstH; dstY++) {

        const int chrDstY = dstY >> c->chrDstVSubSample;

        uint8_t *dest[4]  = {

            dst[0] + dstStride[0] * dstY,

            dst[1] + dstStride[1] * chrDstY,

            dst[2] + dstStride[2] * chrDstY,

            (CONFIG_SWSCALE_ALPHA && alpPixBuf) ? dst[3] + dstStride[3] * dstY : NULL,

        };

        // First line needed as input

        const int firstLumSrcY  = FFMAX(1 - vLumFilterSize, vLumFilterPos[dstY]);

        const int firstLumSrcY2 = FFMAX(1 - vLumFilterSize, vLumFilterPos[FFMIN(dstY | ((1 << c->chrDstVSubSample) - 1), dstH - 1)]);

        // First line needed as input

        const int firstChrSrcY  = FFMAX(1 - vChrFilterSize, vChrFilterPos[chrDstY]);

        // Last line needed as input

        int lastLumSrcY  = FFMIN(c->srcH,    firstLumSrcY  + vLumFilterSize) - 1;

        int lastLumSrcY2 = FFMIN(c->srcH,    firstLumSrcY2 + vLumFilterSize) - 1;

        int lastChrSrcY  = FFMIN(c->chrSrcH, firstChrSrcY  + vChrFilterSize) - 1;

        int enough_lines;

        // handle holes (FAST_BILINEAR & weird filters)

        if (firstLumSrcY > lastInLumBuf)

            lastInLumBuf = firstLumSrcY - 1;

        if (firstChrSrcY > lastInChrBuf)

            lastInChrBuf = firstChrSrcY - 1;

        assert(firstLumSrcY >= lastInLumBuf - vLumBufSize + 1);

        assert(firstChrSrcY >= lastInChrBuf - vChrBufSize + 1);

        DEBUG_BUFFERS("dstY: %d\n", dstY);

        DEBUG_BUFFERS("\tfirstLumSrcY: %d lastLumSrcY: %d lastInLumBuf: %d\n",

                      firstLumSrcY, lastLumSrcY, lastInLumBuf);

        DEBUG_BUFFERS("\tfirstChrSrcY: %d lastChrSrcY: %d lastInChrBuf: %d\n",

                      firstChrSrcY, lastChrSrcY, lastInChrBuf);

        // Do we have enough lines in this slice to output the dstY line

        enough_lines = lastLumSrcY2 < srcSliceY + srcSliceH &&

                       lastChrSrcY < -((-srcSliceY - srcSliceH) >> c->chrSrcVSubSample);

        if (!enough_lines) {

            lastLumSrcY = srcSliceY + srcSliceH - 1;

            lastChrSrcY = chrSrcSliceY + chrSrcSliceH - 1;

            DEBUG_BUFFERS("buffering slice: lastLumSrcY %d lastChrSrcY %d\n",

                          lastLumSrcY, lastChrSrcY);

        }

        // Do horizontal scaling

        while (lastInLumBuf < lastLumSrcY) {

            const uint8_t *src1[4] = {

                src[0] + (lastInLumBuf + 1 - srcSliceY) * srcStride[0],

                src[1] + (lastInLumBuf + 1 - srcSliceY) * srcStride[1],

                src[2] + (lastInLumBuf + 1 - srcSliceY) * srcStride[2],

                src[3] + (lastInLumBuf + 1 - srcSliceY) * srcStride[3],

            };

            lumBufIndex++;

            assert(lumBufIndex < 2 * vLumBufSize);

            assert(lastInLumBuf + 1 - srcSliceY < srcSliceH);

            assert(lastInLumBuf + 1 - srcSliceY >= 0);

            hyscale(c, lumPixBuf[lumBufIndex], dstW, src1, srcW, lumXInc,

                    hLumFilter, hLumFilterPos, hLumFilterSize,

                    formatConvBuffer, pal, 0);

            if (CONFIG_SWSCALE_ALPHA && alpPixBuf)

                hyscale(c, alpPixBuf[lumBufIndex], dstW, src1, srcW,

                        lumXInc, hLumFilter, hLumFilterPos, hLumFilterSize,

                        formatConvBuffer, pal, 1);

            lastInLumBuf++;

            DEBUG_BUFFERS("\t\tlumBufIndex %d: lastInLumBuf: %d\n",

                          lumBufIndex, lastInLumBuf);

        }

        while (lastInChrBuf < lastChrSrcY) {

            const uint8_t *src1[4] = {

                src[0] + (lastInChrBuf + 1 - chrSrcSliceY) * srcStride[0],

                src[1] + (lastInChrBuf + 1 - chrSrcSliceY) * srcStride[1],

                src[2] + (lastInChrBuf + 1 - chrSrcSliceY) * srcStride[2],

                src[3] + (lastInChrBuf + 1 - chrSrcSliceY) * srcStride[3],

            };

            chrBufIndex++;

            assert(chrBufIndex < 2 * vChrBufSize);

            assert(lastInChrBuf + 1 - chrSrcSliceY < (chrSrcSliceH));

            assert(lastInChrBuf + 1 - chrSrcSliceY >= 0);

            // FIXME replace parameters through context struct (some at least)

            if (c->needs_hcscale)

                hcscale(c, chrUPixBuf[chrBufIndex], chrVPixBuf[chrBufIndex],

                        chrDstW, src1, chrSrcW, chrXInc,

                        hChrFilter, hChrFilterPos, hChrFilterSize,

                        formatConvBuffer, pal);

            lastInChrBuf++;

            DEBUG_BUFFERS("\t\tchrBufIndex %d: lastInChrBuf: %d\n",

                          chrBufIndex, lastInChrBuf);

        }

        // wrap buf index around to stay inside the ring buffer

        if (lumBufIndex >= vLumBufSize)

            lumBufIndex -= vLumBufSize;

        if (chrBufIndex >= vChrBufSize)

            chrBufIndex -= vChrBufSize;

        if (!enough_lines)

            break;  // we can't output a dstY line so let's try with the next slice

#if HAVE_MMX

        updateMMXDitherTables(c, dstY, lumBufIndex, chrBufIndex,

                              lastInLumBuf, lastInChrBuf);

#endif

        if (should_dither) {

            c->chrDither8 = dither_8x8_128[chrDstY & 7];

            c->lumDither8 = dither_8x8_128[dstY    & 7];

        }

        if (dstY >= dstH - 2) {

            /* hmm looks like we can't use MMX here without overwriting

             * this array's tail */

            ff_sws_init_output_funcs(c, &yuv2plane1, &yuv2planeX, &yuv2nv12cX,

                                     &yuv2packed1, &yuv2packed2, &yuv2packedX);

        }

        {

            const int16_t **lumSrcPtr  = (const int16_t **)lumPixBuf  + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize;

            const int16_t **chrUSrcPtr = (const int16_t **)chrUPixBuf + chrBufIndex + firstChrSrcY - lastInChrBuf + vChrBufSize;

            const int16_t **chrVSrcPtr = (const int16_t **)chrVPixBuf + chrBufIndex + firstChrSrcY - lastInChrBuf + vChrBufSize;

            const int16_t **alpSrcPtr  = (CONFIG_SWSCALE_ALPHA && alpPixBuf) ?

                                         (const int16_t **)alpPixBuf  + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize : NULL;

            if (firstLumSrcY < 0 || firstLumSrcY + vLumFilterSize > c->srcH) {

                const int16_t **tmpY = (const int16_t **)lumPixBuf +

                                       2 * vLumBufSize;

                int neg = -firstLumSrcY, i;

                int end = FFMIN(c->srcH - firstLumSrcY, vLumFilterSize);

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

                    tmpY[i] = lumSrcPtr[neg];

                for (; i < end; i++)

                    tmpY[i] = lumSrcPtr[i];

                for (; i < vLumFilterSize; i++)

                    tmpY[i] = tmpY[i - 1];

                lumSrcPtr = tmpY;

                if (alpSrcPtr) {

                    const int16_t **tmpA = (const int16_t **)alpPixBuf +

                                           2 * vLumBufSize;

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

                        tmpA[i] = alpSrcPtr[neg];

                    for (; i < end; i++)

                        tmpA[i] = alpSrcPtr[i];

                    for (; i < vLumFilterSize; i++)

                        tmpA[i] = tmpA[i - 1];

                    alpSrcPtr = tmpA;

                }

            }

            if (firstChrSrcY < 0 ||

                firstChrSrcY + vChrFilterSize > c->chrSrcH) {

                const int16_t **tmpU = (const int16_t **)chrUPixBuf + 2 * vChrBufSize,

                **tmpV               = (const int16_t **)chrVPixBuf + 2 * vChrBufSize;

                int neg = -firstChrSrcY, i;

                int end = FFMIN(c->chrSrcH - firstChrSrcY, vChrFilterSize);

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

                    tmpU[i] = chrUSrcPtr[neg];

                    tmpV[i] = chrVSrcPtr[neg];

                }

                for (; i < end; i++) {

                    tmpU[i] = chrUSrcPtr[i];

                    tmpV[i] = chrVSrcPtr[i];

                }

                for (; i < vChrFilterSize; i++) {

                    tmpU[i] = tmpU[i - 1];

                    tmpV[i] = tmpV[i - 1];

                }

                chrUSrcPtr = tmpU;

                chrVSrcPtr = tmpV;

            }

            if (isPlanarYUV(dstFormat) ||

                (isGray(dstFormat) && !isALPHA(dstFormat))) { // YV12 like

                const int chrSkipMask = (1 << c->chrDstVSubSample) - 1;

                if (vLumFilterSize == 1) {

                    yuv2plane1(lumSrcPtr[0], dest[0], dstW, c->lumDither8, 0);

                } else {

                    yuv2planeX(vLumFilter + dstY * vLumFilterSize,

                               vLumFilterSize, lumSrcPtr, dest[0],

                               dstW, c->lumDither8, 0);

                }

                if (!((dstY & chrSkipMask) || isGray(dstFormat))) {

                    if (yuv2nv12cX) {

                        yuv2nv12cX(c, vChrFilter + chrDstY * vChrFilterSize,

                                   vChrFilterSize, chrUSrcPtr, chrVSrcPtr,

                                   dest[1], chrDstW);

                    } else if (vChrFilterSize == 1) {

                        yuv2plane1(chrUSrcPtr[0], dest[1], chrDstW, c->chrDither8, 0);

                        yuv2plane1(chrVSrcPtr[0], dest[2], chrDstW, c->chrDither8, 3);

                    } else {

                        yuv2planeX(vChrFilter + chrDstY * vChrFilterSize,

                                   vChrFilterSize, chrUSrcPtr, dest[1],

                                   chrDstW, c->chrDither8, 0);

                        yuv2planeX(vChrFilter + chrDstY * vChrFilterSize,

                                   vChrFilterSize, chrVSrcPtr, dest[2],

                                   chrDstW, c->chrDither8, 3);

                    }

                }

                if (CONFIG_SWSCALE_ALPHA && alpPixBuf) {

                    if (vLumFilterSize == 1) {

                        yuv2plane1(alpSrcPtr[0], dest[3], dstW,

                                   c->lumDither8, 0);

                    } else {

                        yuv2planeX(vLumFilter + dstY * vLumFilterSize,

                                   vLumFilterSize, alpSrcPtr, dest[3],

                                   dstW, c->lumDither8, 0);

                    }

                }

            } else {

                assert(lumSrcPtr  + vLumFilterSize - 1 < lumPixBuf  + vLumBufSize * 2);

                assert(chrUSrcPtr + vChrFilterSize - 1 < chrUPixBuf + vChrBufSize * 2);

                if (c->yuv2packed1 && vLumFilterSize == 1 &&

                    vChrFilterSize <= 2) { // unscaled RGB

                    int chrAlpha = vChrFilterSize == 1 ? 0 : vChrFilter[2 * dstY + 1];

                    yuv2packed1(c, *lumSrcPtr, chrUSrcPtr, chrVSrcPtr,

                                alpPixBuf ? *alpSrcPtr : NULL,

                                dest[0], dstW, chrAlpha, dstY);

                } else if (c->yuv2packed2 && vLumFilterSize == 2 &&

                           vChrFilterSize == 2) { // bilinear upscale RGB

                    int lumAlpha = vLumFilter[2 * dstY + 1];

                    int chrAlpha = vChrFilter[2 * dstY + 1];

                    lumMmxFilter[2] =

                    lumMmxFilter[3] = vLumFilter[2 * dstY]    * 0x10001;

                    chrMmxFilter[2] =

                    chrMmxFilter[3] = vChrFilter[2 * chrDstY] * 0x10001;

                    yuv2packed2(c, lumSrcPtr, chrUSrcPtr, chrVSrcPtr,

                                alpPixBuf ? alpSrcPtr : NULL,

                                dest[0], dstW, lumAlpha, chrAlpha, dstY);

                } else { // general RGB

                    yuv2packedX(c, vLumFilter + dstY * vLumFilterSize,

                                lumSrcPtr, vLumFilterSize,

                                vChrFilter + dstY * vChrFilterSize,

                                chrUSrcPtr, chrVSrcPtr, vChrFilterSize,

                                alpSrcPtr, dest[0], dstW, dstY);

                }

            }

        }

    }

    if (isPlanar(dstFormat) && isALPHA(dstFormat) && !alpPixBuf)

        fillPlane(dst[3], dstStride[3], dstW, dstY - lastDstY, lastDstY, 255);

#if HAVE_MMX2

    if (av_get_cpu_flags() & AV_CPU_FLAG_MMX2)

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

#endif

    emms_c();

    /* store changed local vars back in the context */

    c->dstY         = dstY;

    c->lumBufIndex  = lumBufIndex;

    c->chrBufIndex  = chrBufIndex;

    c->lastInLumBuf = lastInLumBuf;

    c->lastInChrBuf = lastInChrBuf;

    return dstY - lastDstY;

}


static inline int spx_strategy(AC3DecodeContext *s, int blk)

{

    GetBitContext *bc = &s->gbc;

    int fbw_channels = s->fbw_channels;

    int dst_start_freq, dst_end_freq, src_start_freq,

        start_subband, end_subband, ch;

    /* determine which channels use spx */

    if (s->channel_mode == AC3_CHMODE_MONO) {

        s->channel_uses_spx[1] = 1;

    } else {

        for (ch = 1; ch <= fbw_channels; ch++)

            s->channel_uses_spx[ch] = get_bits1(bc);

    }

    /* get the frequency bins of the spx copy region and the spx start

       and end subbands */

    dst_start_freq = get_bits(bc, 2);

    start_subband  = get_bits(bc, 3) + 2;

    if (start_subband > 7)

        start_subband += start_subband - 7;

    end_subband    = get_bits(bc, 3) + 5;

#if USE_FIXED

    s->spx_dst_end_freq = end_freq_inv_tab[end_subband-5];

#endif

    if (end_subband   > 7)

        end_subband   += end_subband   - 7;

    dst_start_freq = dst_start_freq * 12 + 25;

    src_start_freq = start_subband  * 12 + 25;

    dst_end_freq   = end_subband    * 12 + 25;

    /* check validity of spx ranges */

    if (start_subband >= end_subband) {

        av_log(s->avctx, AV_LOG_ERROR, "invalid spectral extension "

               "range (%d >= %d)\n", start_subband, end_subband);

        return AVERROR_INVALIDDATA;

    }

    if (dst_start_freq >= src_start_freq) {

        av_log(s->avctx, AV_LOG_ERROR, "invalid spectral extension "

               "copy start bin (%d >= %d)\n", dst_start_freq, src_start_freq);

        return AVERROR_INVALIDDATA;

    }

    s->spx_dst_start_freq = dst_start_freq;

    s->spx_src_start_freq = src_start_freq;

    if (!USE_FIXED)

        s->spx_dst_end_freq   = dst_end_freq;

    decode_band_structure(bc, blk, s->eac3, 0,

                          start_subband, end_subband,

                          ff_eac3_default_spx_band_struct,

                          &s->num_spx_bands,

                          s->spx_band_sizes);

    return 0;

}


TPMInfo *tpm_backend_query_tpm(TPMBackend *s)

{

    TPMInfo *info = g_new0(TPMInfo, 1);

    TPMBackendClass *k = TPM_BACKEND_GET_CLASS(s);

    TPMIfClass *tic = TPM_IF_GET_CLASS(s->tpmif);

    info->id = g_strdup(s->id);

    info->model = tic->model;

    if (k->get_tpm_options) {

        info->options = k->get_tpm_options(s);

    }

    return info;

}


static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)

{

    if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE) {

        int64_t addend;

        int delta_timestamp;

        /* compute pts from timestamp with received ntp_time */

        delta_timestamp = timestamp - s->last_rtcp_timestamp;

        /* convert to the PTS timebase */

        addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time, s->st->time_base.den, (uint64_t)s->st->time_base.num << 32);

        pkt->pts = addend + delta_timestamp;

    }

}


static void h264_v_loop_filter_chroma_intra_c(uint8_t *pix, int stride, int alpha, int beta)

{

    h264_loop_filter_chroma_intra_c(pix, stride, 1, alpha, beta);

}


static void v9fs_remove(void *opaque)

{

    int32_t fid;

    int err = 0;

    size_t offset = 7;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

    pdu_unmarshal(pdu, offset, "d", &fid);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    /* if fs driver is not path based, return EOPNOTSUPP */

    if (!pdu->s->ctx.flags & PATHNAME_FSCONTEXT) {

        err = -EOPNOTSUPP;

        goto out_err;

    }

    /*

     * IF the file is unlinked, we cannot reopen

     * the file later. So don't reclaim fd

     */

    err = v9fs_mark_fids_unreclaim(pdu, &fidp->path);

    if (err < 0) {

        goto out_err;

    }

    err = v9fs_co_remove(pdu, &fidp->path);

    if (!err) {

        err = offset;

    }

out_err:

    /* For TREMOVE we need to clunk the fid even on failed remove */

    clunk_fid(pdu->s, fidp->fid);

    put_fid(pdu, fidp);

out_nofid:

    complete_pdu(pdu->s, pdu, err);

}


static void gen_msgclr(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    GEN_PRIV;

#else

    CHK_SV;

    gen_helper_msgclr(cpu_env, cpu_gpr[rB(ctx->opcode)]);

#endif /* defined(CONFIG_USER_ONLY) */

}


static av_always_inline int small_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;

    int next_dir=-1;

    LOAD_COMMON

    LOAD_COMMON2

    unsigned map_generation = c->map_generation;

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

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

    { /* ensure that the best point is in the MAP as h/qpel refinement needs it */

        const unsigned key = (best[1]<<ME_MAP_MV_BITS) + best[0] + map_generation;

        const int index= ((best[1]<<ME_MAP_SHIFT) + best[0])&(ME_MAP_SIZE-1);

        if(map[index]!=key){ //this will be executed only very rarey

            score_map[index]= cmp(s, best[0], best[1], 0, 0, size, h, ref_index, src_index, cmpf, chroma_cmpf, flags);

            map[index]= key;

        }

    }

    for(;;){

        int d;

        const int dir= next_dir;

        const int x= best[0];

        const int y= best[1];

        next_dir=-1;

        if(dir!=2 && x>xmin) CHECK_MV_DIR(x-1, y  , 0)

        if(dir!=3 && y>ymin) CHECK_MV_DIR(x  , y-1, 1)

        if(dir!=0 && x<xmax) CHECK_MV_DIR(x+1, y  , 2)

        if(dir!=1 && y<ymax) CHECK_MV_DIR(x  , y+1, 3)

        if(next_dir==-1){

            return dmin;

        }

    }

}


void mips_cpu_do_interrupt(CPUState *cs)

{

#if !defined(CONFIG_USER_ONLY)

    MIPSCPU *cpu = MIPS_CPU(cs);

    CPUMIPSState *env = &cpu->env;

    target_ulong offset;

    int cause = -1;

    const char *name;

    if (qemu_log_enabled() && cs->exception_index != EXCP_EXT_INTERRUPT) {

        if (cs->exception_index < 0 || cs->exception_index > EXCP_LAST) {

            name = "unknown";

        } else {

            name = excp_names[cs->exception_index];

        }

        qemu_log("%s enter: PC " TARGET_FMT_lx " EPC " TARGET_FMT_lx " %s exception\n",

                 __func__, env->active_tc.PC, env->CP0_EPC, name);

    }

    if (cs->exception_index == EXCP_EXT_INTERRUPT &&

        (env->hflags & MIPS_HFLAG_DM)) {

        cs->exception_index = EXCP_DINT;

    }

    offset = 0x180;

    switch (cs->exception_index) {

    case EXCP_DSS:

        env->CP0_Debug |= 1 << CP0DB_DSS;

        /* Debug single step cannot be raised inside a delay slot and

           resume will always occur on the next instruction

           (but we assume the pc has always been updated during

           code translation). */

        env->CP0_DEPC = env->active_tc.PC | !!(env->hflags & MIPS_HFLAG_M16);

        goto enter_debug_mode;

    case EXCP_DINT:

        env->CP0_Debug |= 1 << CP0DB_DINT;

        goto set_DEPC;

    case EXCP_DIB:

        env->CP0_Debug |= 1 << CP0DB_DIB;

        goto set_DEPC;

    case EXCP_DBp:

        env->CP0_Debug |= 1 << CP0DB_DBp;

        goto set_DEPC;

    case EXCP_DDBS:

        env->CP0_Debug |= 1 << CP0DB_DDBS;

        goto set_DEPC;

    case EXCP_DDBL:

        env->CP0_Debug |= 1 << CP0DB_DDBL;

    set_DEPC:

        env->CP0_DEPC = exception_resume_pc(env);

        env->hflags &= ~MIPS_HFLAG_BMASK;

 enter_debug_mode:

        env->hflags |= MIPS_HFLAG_DM | MIPS_HFLAG_64 | MIPS_HFLAG_CP0;

        env->hflags &= ~(MIPS_HFLAG_KSU);

        /* EJTAG probe trap enable is not implemented... */

        if (!(env->CP0_Status & (1 << CP0St_EXL)))

            env->CP0_Cause &= ~(1 << CP0Ca_BD);

        env->active_tc.PC = (int32_t)0xBFC00480;

        set_hflags_for_handler(env);

        break;

    case EXCP_RESET:

        cpu_reset(CPU(cpu));

        break;

    case EXCP_SRESET:

        env->CP0_Status |= (1 << CP0St_SR);

        memset(env->CP0_WatchLo, 0, sizeof(*env->CP0_WatchLo));

        goto set_error_EPC;

    case EXCP_NMI:

        env->CP0_Status |= (1 << CP0St_NMI);

 set_error_EPC:

        env->CP0_ErrorEPC = exception_resume_pc(env);

        env->hflags &= ~MIPS_HFLAG_BMASK;

        env->CP0_Status |= (1 << CP0St_ERL) | (1 << CP0St_BEV);

        env->hflags |= MIPS_HFLAG_64 | MIPS_HFLAG_CP0;

        env->hflags &= ~(MIPS_HFLAG_KSU);

        if (!(env->CP0_Status & (1 << CP0St_EXL)))

            env->CP0_Cause &= ~(1 << CP0Ca_BD);

        env->active_tc.PC = (int32_t)0xBFC00000;

        set_hflags_for_handler(env);

        break;

    case EXCP_EXT_INTERRUPT:

        cause = 0;

        if (env->CP0_Cause & (1 << CP0Ca_IV))

            offset = 0x200;

        if (env->CP0_Config3 & ((1 << CP0C3_VInt) | (1 << CP0C3_VEIC))) {

            /* Vectored Interrupts.  */

            unsigned int spacing;

            unsigned int vector;

            unsigned int pending = (env->CP0_Cause & CP0Ca_IP_mask) >> 8;

            pending &= env->CP0_Status >> 8;

            /* Compute the Vector Spacing.  */

            spacing = (env->CP0_IntCtl >> CP0IntCtl_VS) & ((1 << 6) - 1);

            spacing <<= 5;

            if (env->CP0_Config3 & (1 << CP0C3_VInt)) {

                /* For VInt mode, the MIPS computes the vector internally.  */

                for (vector = 7; vector > 0; vector--) {

                    if (pending & (1 << vector)) {

                        /* Found it.  */

                        break;

                    }

                }

            } else {

                /* For VEIC mode, the external interrupt controller feeds the

                   vector through the CP0Cause IP lines.  */

                vector = pending;

            }

            offset = 0x200 + vector * spacing;

        }

        goto set_EPC;

    case EXCP_LTLBL:

        cause = 1;

        goto set_EPC;

    case EXCP_TLBL:

        cause = 2;

        if (env->error_code == 1 && !(env->CP0_Status & (1 << CP0St_EXL))) {

#if defined(TARGET_MIPS64)

            int R = env->CP0_BadVAddr >> 62;

            int UX = (env->CP0_Status & (1 << CP0St_UX)) != 0;

            int SX = (env->CP0_Status & (1 << CP0St_SX)) != 0;

            int KX = (env->CP0_Status & (1 << CP0St_KX)) != 0;

            if (((R == 0 && UX) || (R == 1 && SX) || (R == 3 && KX)) &&

                (!(env->insn_flags & (INSN_LOONGSON2E | INSN_LOONGSON2F))))

                offset = 0x080;

            else

#endif

                offset = 0x000;

        }

        goto set_EPC;

    case EXCP_TLBS:

        cause = 3;

        if (env->error_code == 1 && !(env->CP0_Status & (1 << CP0St_EXL))) {

#if defined(TARGET_MIPS64)

            int R = env->CP0_BadVAddr >> 62;

            int UX = (env->CP0_Status & (1 << CP0St_UX)) != 0;

            int SX = (env->CP0_Status & (1 << CP0St_SX)) != 0;

            int KX = (env->CP0_Status & (1 << CP0St_KX)) != 0;

            if (((R == 0 && UX) || (R == 1 && SX) || (R == 3 && KX)) &&

                (!(env->insn_flags & (INSN_LOONGSON2E | INSN_LOONGSON2F))))

                offset = 0x080;

            else

#endif

                offset = 0x000;

        }

        goto set_EPC;

    case EXCP_AdEL:

        cause = 4;

        goto set_EPC;

    case EXCP_AdES:

        cause = 5;

        goto set_EPC;

    case EXCP_IBE:

        cause = 6;

        goto set_EPC;

    case EXCP_DBE:

        cause = 7;

        goto set_EPC;

    case EXCP_SYSCALL:

        cause = 8;

        goto set_EPC;

    case EXCP_BREAK:

        cause = 9;

        goto set_EPC;

    case EXCP_RI:

        cause = 10;

        goto set_EPC;

    case EXCP_CpU:

        cause = 11;

        env->CP0_Cause = (env->CP0_Cause & ~(0x3 << CP0Ca_CE)) |

                         (env->error_code << CP0Ca_CE);

        goto set_EPC;

    case EXCP_OVERFLOW:

        cause = 12;

        goto set_EPC;

    case EXCP_TRAP:

        cause = 13;

        goto set_EPC;

    case EXCP_FPE:

        cause = 15;

        goto set_EPC;

    case EXCP_C2E:

        cause = 18;

        goto set_EPC;

    case EXCP_MDMX:

        cause = 22;

        goto set_EPC;

    case EXCP_DWATCH:

        cause = 23;

        /* XXX: TODO: manage defered watch exceptions */

        goto set_EPC;

    case EXCP_MCHECK:

        cause = 24;

        goto set_EPC;

    case EXCP_THREAD:

        cause = 25;

        goto set_EPC;

    case EXCP_DSPDIS:

        cause = 26;

        goto set_EPC;

    case EXCP_CACHE:

        cause = 30;

        if (env->CP0_Status & (1 << CP0St_BEV)) {

            offset = 0x100;

        } else {

            offset = 0x20000100;

        }

 set_EPC:

        if (!(env->CP0_Status & (1 << CP0St_EXL))) {

            env->CP0_EPC = exception_resume_pc(env);

            if (env->hflags & MIPS_HFLAG_BMASK) {

                env->CP0_Cause |= (1 << CP0Ca_BD);

            } else {

                env->CP0_Cause &= ~(1 << CP0Ca_BD);

            }

            env->CP0_Status |= (1 << CP0St_EXL);

            env->hflags |= MIPS_HFLAG_64 | MIPS_HFLAG_CP0;

            env->hflags &= ~(MIPS_HFLAG_KSU);

        }

        env->hflags &= ~MIPS_HFLAG_BMASK;

        if (env->CP0_Status & (1 << CP0St_BEV)) {

            env->active_tc.PC = (int32_t)0xBFC00200;

        } else {

            env->active_tc.PC = (int32_t)(env->CP0_EBase & ~0x3ff);

        }

        env->active_tc.PC += offset;

        set_hflags_for_handler(env);

        env->CP0_Cause = (env->CP0_Cause & ~(0x1f << CP0Ca_EC)) | (cause << CP0Ca_EC);

        break;

    default:

        qemu_log("Invalid MIPS exception %d. Exiting\n", cs->exception_index);

        printf("Invalid MIPS exception %d. Exiting\n", cs->exception_index);

        exit(1);

    }

    if (qemu_log_enabled() && cs->exception_index != EXCP_EXT_INTERRUPT) {

        qemu_log("%s: PC " TARGET_FMT_lx " EPC " TARGET_FMT_lx " cause %d\n"

                "    S %08x C %08x A " TARGET_FMT_lx " D " TARGET_FMT_lx "\n",

                __func__, env->active_tc.PC, env->CP0_EPC, cause,

                env->CP0_Status, env->CP0_Cause, env->CP0_BadVAddr,

                env->CP0_DEPC);

    }

#endif

    cs->exception_index = EXCP_NONE;

}


void qmp_drive_mirror(const char *device, const char *target,

                      bool has_format, const char *format,

                      enum MirrorSyncMode sync,

                      bool has_mode, enum NewImageMode mode,

                      bool has_speed, int64_t speed,

                      bool has_granularity, uint32_t granularity,

                      bool has_buf_size, int64_t buf_size,

                      bool has_on_source_error, BlockdevOnError on_source_error,

                      bool has_on_target_error, BlockdevOnError on_target_error,

                      Error **errp)

{

    BlockDriverState *bs;

    BlockDriverState *source, *target_bs;

    BlockDriver *drv = NULL;

    Error *local_err = NULL;

    int flags;

    int64_t size;

    int ret;

    if (!has_speed) {

        speed = 0;

    }

    if (!has_on_source_error) {

        on_source_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    if (!has_on_target_error) {

        on_target_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    if (!has_mode) {

        mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;

    }

    if (!has_granularity) {

        granularity = 0;

    }

    if (!has_buf_size) {

        buf_size = DEFAULT_MIRROR_BUF_SIZE;

    }

    if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {

        error_set(errp, QERR_INVALID_PARAMETER, device);

        return;

    }

    if (granularity & (granularity - 1)) {

        error_set(errp, QERR_INVALID_PARAMETER, device);

        return;

    }

    bs = bdrv_find(device);

    if (!bs) {

        error_set(errp, QERR_DEVICE_NOT_FOUND, device);

        return;

    }

    if (!bdrv_is_inserted(bs)) {

        error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);

        return;

    }

    if (!has_format) {

        format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;

    }

    if (format) {

        drv = bdrv_find_format(format);

        if (!drv) {

            error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);

            return;

        }

    }

    if (bdrv_in_use(bs)) {

        error_set(errp, QERR_DEVICE_IN_USE, device);

        return;

    }

    flags = bs->open_flags | BDRV_O_RDWR;

    source = bs->backing_hd;

    if (!source && sync == MIRROR_SYNC_MODE_TOP) {

        sync = MIRROR_SYNC_MODE_FULL;

    }

    size = bdrv_getlength(bs);

    if (size < 0) {

        error_setg_errno(errp, -size, "bdrv_getlength failed");

        return;

    }

    if (sync == MIRROR_SYNC_MODE_FULL && mode != NEW_IMAGE_MODE_EXISTING) {

        /* create new image w/o backing file */

        assert(format && drv);

        bdrv_img_create(target, format,

                        NULL, NULL, NULL, size, flags, &local_err, false);

    } else {

        switch (mode) {

        case NEW_IMAGE_MODE_EXISTING:

            break;

        case NEW_IMAGE_MODE_ABSOLUTE_PATHS:

            /* create new image with backing file */

            bdrv_img_create(target, format,

                            source->filename,

                            source->drv->format_name,

                            NULL, size, flags, &local_err, false);

            break;

        default:

            abort();

        }

    }

    if (error_is_set(&local_err)) {

        error_propagate(errp, local_err);

        return;

    }

    /* Mirroring takes care of copy-on-write using the source's backing

     * file.

     */

    target_bs = bdrv_new("");

    ret = bdrv_open(target_bs, target, NULL, flags | BDRV_O_NO_BACKING, drv,

                    &local_err);

    if (ret < 0) {

        bdrv_unref(target_bs);

        error_propagate(errp, local_err);

        return;

    }

    mirror_start(bs, target_bs, speed, granularity, buf_size, sync,

                 on_source_error, on_target_error,

                 block_job_cb, bs, &local_err);

    if (local_err != NULL) {

        bdrv_unref(target_bs);

        error_propagate(errp, local_err);

        return;

    }

}


static void opt_frame_aspect_ratio(const char *arg)

{

    int x = 0, y = 0;

    double ar = 0;

    const char *p;

    char *end;

    p = strchr(arg, ':');

    if (p) {

        x = strtol(arg, &end, 10);

        if (end == p)

            y = strtol(end+1, &end, 10);

        if (x > 0 && y > 0)

            ar = (double)x / (double)y;

    } else

        ar = strtod(arg, NULL);

    if (!ar) {

        fprintf(stderr, "Incorrect aspect ratio specification.\n");

        ffmpeg_exit(1);

    }

    frame_aspect_ratio = ar;

    x = vfilters ? strlen(vfilters) : 0;

    vfilters = av_realloc(vfilters, x+100);

    snprintf(vfilters+x, x+100, "%csetdar=%f\n", x?',':' ', ar);

}


static int tcp_write(URLContext *h, uint8_t *buf, int size)

{

    TCPContext *s = h->priv_data;

    int ret, size1, fd_max;

    fd_set wfds;

    struct timeval tv;

    size1 = size;

    while (size > 0) {

        if (url_interrupt_cb())

            return -EINTR;

        fd_max = s->fd;

        FD_ZERO(&wfds);

        FD_SET(s->fd, &wfds);

        tv.tv_sec = 0;

        tv.tv_usec = 100 * 1000;

        select(fd_max + 1, NULL, &wfds, NULL, &tv);

#ifdef __BEOS__

        ret = send(s->fd, buf, size, 0);

#else

        ret = write(s->fd, buf, size);

#endif

        if (ret < 0) {

            if (errno != EINTR && errno != EAGAIN) {

#ifdef __BEOS__

                return errno;

#else

                return -errno;

#endif

            }

            continue;

        }

        size -= ret;

        buf += ret;

    }

    return size1 - size;

}


static void glfs_clear_preopened(glfs_t *fs)

{

    ListElement *entry = NULL;

    if (fs == NULL) {

        return;

    }

    QLIST_FOREACH(entry, &glfs_list, list) {

        if (entry->saved.fs == fs) {

            if (--entry->saved.ref) {

                return;

            }

            QLIST_REMOVE(entry, list);

            glfs_fini(entry->saved.fs);

            g_free(entry->saved.volume);

            g_free(entry);

        }

    }

}


static av_cold int mm_decode_init(AVCodecContext *avctx)
{
    MmContext *s = avctx->priv_data;
    s->avctx = avctx;
    avctx->pix_fmt = AV_PIX_FMT_PAL8;
    s->frame = av_frame_alloc();
    if (!s->frame)
        return AVERROR(ENOMEM);
    return 0;


static void uhci_process_frame(UHCIState *s)

{

    uint32_t frame_addr, link, old_td_ctrl, val, int_mask;

    uint32_t curr_qh, td_count = 0;

    int cnt, ret;

    UHCI_TD td;

    UHCI_QH qh;

    QhDb qhdb;

    frame_addr = s->fl_base_addr + ((s->frnum & 0x3ff) << 2);

    pci_dma_read(&s->dev, frame_addr, &link, 4);

    le32_to_cpus(&link);

    int_mask = 0;

    curr_qh  = 0;

    qhdb_reset(&qhdb);

    for (cnt = FRAME_MAX_LOOPS; is_valid(link) && cnt; cnt--) {

        if (s->frame_bytes >= s->frame_bandwidth) {

            /* We've reached the usb 1.1 bandwidth, which is

               1280 bytes/frame, stop processing */

            trace_usb_uhci_frame_stop_bandwidth();

            break;

        }

        if (is_qh(link)) {

            /* QH */

            trace_usb_uhci_qh_load(link & ~0xf);

            if (qhdb_insert(&qhdb, link)) {

                /*

                 * We're going in circles. Which is not a bug because

                 * HCD is allowed to do that as part of the BW management.

                 *

                 * Stop processing here if no transaction has been done

                 * since we've been here last time.

                 */

                if (td_count == 0) {

                    trace_usb_uhci_frame_loop_stop_idle();

                    break;

                } else {

                    trace_usb_uhci_frame_loop_continue();

                    td_count = 0;

                    qhdb_reset(&qhdb);

                    qhdb_insert(&qhdb, link);

                }

            }

            pci_dma_read(&s->dev, link & ~0xf, &qh, sizeof(qh));

            le32_to_cpus(&qh.link);

            le32_to_cpus(&qh.el_link);

            if (!is_valid(qh.el_link)) {

                /* QH w/o elements */

                curr_qh = 0;

                link = qh.link;

            } else {

                /* QH with elements */

            	curr_qh = link;

            	link = qh.el_link;

            }

            continue;

        }

        /* TD */

        uhci_read_td(s, &td, link);

        trace_usb_uhci_td_load(curr_qh & ~0xf, link & ~0xf, td.ctrl, td.token);

        old_td_ctrl = td.ctrl;

        ret = uhci_handle_td(s, NULL, &td, link, &int_mask);

        if (old_td_ctrl != td.ctrl) {

            /* update the status bits of the TD */

            val = cpu_to_le32(td.ctrl);

            pci_dma_write(&s->dev, (link & ~0xf) + 4, &val, sizeof(val));

        }

        switch (ret) {

        case TD_RESULT_STOP_FRAME: /* interrupted frame */

            goto out;

        case TD_RESULT_NEXT_QH:

        case TD_RESULT_ASYNC_CONT:

            trace_usb_uhci_td_nextqh(curr_qh & ~0xf, link & ~0xf);

            link = curr_qh ? qh.link : td.link;

            continue;

        case TD_RESULT_ASYNC_START:

            trace_usb_uhci_td_async(curr_qh & ~0xf, link & ~0xf);

            link = curr_qh ? qh.link : td.link;

            continue;

        case TD_RESULT_COMPLETE:

            trace_usb_uhci_td_complete(curr_qh & ~0xf, link & ~0xf);

            link = td.link;

            td_count++;

            s->frame_bytes += (td.ctrl & 0x7ff) + 1;

            if (curr_qh) {

                /* update QH element link */

                qh.el_link = link;

                val = cpu_to_le32(qh.el_link);

                pci_dma_write(&s->dev, (curr_qh & ~0xf) + 4, &val, sizeof(val));

                if (!depth_first(link)) {

                    /* done with this QH */

                    curr_qh = 0;

                    link    = qh.link;

                }

            }

            break;

        default:

            assert(!"unknown return code");

        }

        /* go to the next entry */

    }

out:

    s->pending_int_mask |= int_mask;

}


static void test_validate_fail_alternate(TestInputVisitorData *data,

                                         const void *unused)

{

    UserDefAlternate *tmp;

    Visitor *v;

    Error *err = NULL;

    v = validate_test_init(data, "3.14");

    visit_type_UserDefAlternate(v, NULL, &tmp, &err);

    error_free_or_abort(&err);

    g_assert(!tmp);

}


void sclp_print(const char *str)

{

    int len = _strlen(str);

    WriteEventData *sccb = (void*)_sccb;

    sccb->h.length = sizeof(WriteEventData) + len;

    sccb->h.function_code = SCLP_FC_NORMAL_WRITE;

    sccb->ebh.length = sizeof(EventBufferHeader) + len;

    sccb->ebh.type = SCLP_EVENT_ASCII_CONSOLE_DATA;

    sccb->ebh.flags = 0;

    _memcpy(sccb->data, str, len);

    sclp_service_call(SCLP_CMD_WRITE_EVENT_DATA, sccb);

}


float64 helper_fstod(CPUSPARCState *env, float32 src)

{

    float64 ret;

    clear_float_exceptions(env);

    ret = float32_to_float64(src, &env->fp_status);

    check_ieee_exceptions(env);

    return ret;

}


static void do_log(int loglevel, const char *format, ...)

{

    va_list ap;

    va_start(ap, format);

    if (is_daemon) {

        vsyslog(LOG_CRIT, format, ap);

    } else {

        vfprintf(stderr, format, ap);

    }

    va_end(ap);

}


static void gic_reset(gic_state *s)

{

    int i;

    memset(s->irq_state, 0, GIC_NIRQ * sizeof(gic_irq_state));

    for (i = 0 ; i < NUM_CPU(s); i++) {

        s->priority_mask[i] = 0xf0;

        s->current_pending[i] = 1023;

        s->running_irq[i] = 1023;

        s->running_priority[i] = 0x100;

#ifdef NVIC

        /* The NVIC doesn't have per-cpu interfaces, so enable by default.  */

        s->cpu_enabled[i] = 1;

#else

        s->cpu_enabled[i] = 0;

#endif

    }

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

        GIC_SET_ENABLED(i);

        GIC_SET_TRIGGER(i);

    }

#ifdef NVIC

    /* The NVIC is always enabled.  */

    s->enabled = 1;

#else

    s->enabled = 0;

#endif

}


static void xhci_er_reset(XHCIState *xhci, int v)

{

    XHCIInterrupter *intr = &xhci->intr[v];

    XHCIEvRingSeg seg;

    if (intr->erstsz == 0) {

        /* disabled */

        intr->er_start = 0;

        intr->er_size = 0;

        return;

    }

    /* cache the (sole) event ring segment location */

    if (intr->erstsz != 1) {

        DPRINTF("xhci: invalid value for ERSTSZ: %d\n", intr->erstsz);

        xhci_die(xhci);

        return;

    }

    dma_addr_t erstba = xhci_addr64(intr->erstba_low, intr->erstba_high);

    pci_dma_read(PCI_DEVICE(xhci), erstba, &seg, sizeof(seg));

    le32_to_cpus(&seg.addr_low);

    le32_to_cpus(&seg.addr_high);

    le32_to_cpus(&seg.size);

    if (seg.size < 16 || seg.size > 4096) {

        DPRINTF("xhci: invalid value for segment size: %d\n", seg.size);

        xhci_die(xhci);

        return;

    }

    intr->er_start = xhci_addr64(seg.addr_low, seg.addr_high);

    intr->er_size = seg.size;

    intr->er_ep_idx = 0;

    intr->er_pcs = 1;

    DPRINTF("xhci: event ring[%d]:" DMA_ADDR_FMT " [%d]\n",

            v, intr->er_start, intr->er_size);

}


static void pxa2xx_cm_write(void *opaque, hwaddr addr,

                            uint64_t value, unsigned size)

{

    PXA2xxState *s = (PXA2xxState *) opaque;

    switch (addr) {

    case CCCR:

    case CKEN:

        s->cm_regs[addr >> 2] = value;

        break;

    case OSCC:

        s->cm_regs[addr >> 2] &= ~0x6c;

        s->cm_regs[addr >> 2] |= value & 0x6e;

        if ((value >> 1) & 1)			/* OON */

            s->cm_regs[addr >> 2] |= 1 << 0;	/* Oscillator is now stable */

        break;

    default:

        printf("%s: Bad register " REG_FMT "\n", __FUNCTION__, addr);

        break;

    }

}


static void do_mac_write(lan9118_state *s, int reg, uint32_t val)

{

    switch (reg) {

    case MAC_CR:

        if ((s->mac_cr & MAC_CR_RXEN) != 0 && (val & MAC_CR_RXEN) == 0) {

            s->int_sts |= RXSTOP_INT;

        }

        s->mac_cr = val & ~MAC_CR_RESERVED;

        DPRINTF("MAC_CR: %08x\n", val);

        break;

    case MAC_ADDRH:

        s->conf.macaddr.a[4] = val & 0xff;

        s->conf.macaddr.a[5] = (val >> 8) & 0xff;

        lan9118_mac_changed(s);

        break;

    case MAC_ADDRL:

        s->conf.macaddr.a[0] = val & 0xff;

        s->conf.macaddr.a[1] = (val >> 8) & 0xff;

        s->conf.macaddr.a[2] = (val >> 16) & 0xff;

        s->conf.macaddr.a[3] = (val >> 24) & 0xff;

        lan9118_mac_changed(s);

        break;

    case MAC_HASHH:

        s->mac_hashh = val;

        break;

    case MAC_HASHL:

        s->mac_hashl = val;

        break;

    case MAC_MII_ACC:

        s->mac_mii_acc = val & 0xffc2;

        if (val & 2) {

            DPRINTF("PHY write %d = 0x%04x\n",

                    (val >> 6) & 0x1f, s->mac_mii_data);

            do_phy_write(s, (val >> 6) & 0x1f, s->mac_mii_data);

        } else {

            s->mac_mii_data = do_phy_read(s, (val >> 6) & 0x1f);

            DPRINTF("PHY read %d = 0x%04x\n",

                    (val >> 6) & 0x1f, s->mac_mii_data);

        }

        break;

    case MAC_MII_DATA:

        s->mac_mii_data = val & 0xffff;

        break;

    case MAC_FLOW:

        s->mac_flow = val & 0xffff0000;

        break;

    case MAC_VLAN1:

        /* Writing to this register changes a condition for

         * FrameTooLong bit in rx_status.  Since we do not set

         * FrameTooLong anyway, just ignore write to this.

         */

        break;

    default:

        hw_error("lan9118: Unimplemented MAC register write: %d = 0x%x\n",

                 s->mac_cmd & 0xf, val);

    }

}


static void decode_rrr_divide(CPUTriCoreState *env, DisasContext *ctx)

{

    uint32_t op2;

    int r1, r2, r3, r4;

    op2 = MASK_OP_RRR_OP2(ctx->opcode);

    r1 = MASK_OP_RRR_S1(ctx->opcode);

    r2 = MASK_OP_RRR_S2(ctx->opcode);

    r3 = MASK_OP_RRR_S3(ctx->opcode);

    r4 = MASK_OP_RRR_D(ctx->opcode);

    CHECK_REG_PAIR(r3);

    switch (op2) {

    case OPC2_32_RRR_DVADJ:

        CHECK_REG_PAIR(r4);

        GEN_HELPER_RRR(dvadj, cpu_gpr_d[r4], cpu_gpr_d[r4+1], cpu_gpr_d[r3],

                       cpu_gpr_d[r3+1], cpu_gpr_d[r2]);

        break;

    case OPC2_32_RRR_DVSTEP:

        CHECK_REG_PAIR(r4);

        GEN_HELPER_RRR(dvstep, cpu_gpr_d[r4], cpu_gpr_d[r4+1], cpu_gpr_d[r3],

                       cpu_gpr_d[r3+1], cpu_gpr_d[r2]);

        break;

    case OPC2_32_RRR_DVSTEP_U:

        CHECK_REG_PAIR(r4);

        GEN_HELPER_RRR(dvstep_u, cpu_gpr_d[r4], cpu_gpr_d[r4+1], cpu_gpr_d[r3],

                       cpu_gpr_d[r3+1], cpu_gpr_d[r2]);

        break;

    case OPC2_32_RRR_IXMAX:

        CHECK_REG_PAIR(r4);

        GEN_HELPER_RRR(ixmax, cpu_gpr_d[r4], cpu_gpr_d[r4+1], cpu_gpr_d[r3],

                       cpu_gpr_d[r3+1], cpu_gpr_d[r2]);

        break;

    case OPC2_32_RRR_IXMAX_U:

        CHECK_REG_PAIR(r4);

        GEN_HELPER_RRR(ixmax_u, cpu_gpr_d[r4], cpu_gpr_d[r4+1], cpu_gpr_d[r3],

                       cpu_gpr_d[r3+1], cpu_gpr_d[r2]);

        break;

    case OPC2_32_RRR_IXMIN:

        CHECK_REG_PAIR(r4);

        GEN_HELPER_RRR(ixmin, cpu_gpr_d[r4], cpu_gpr_d[r4+1], cpu_gpr_d[r3],

                       cpu_gpr_d[r3+1], cpu_gpr_d[r2]);

        break;

    case OPC2_32_RRR_IXMIN_U:

        CHECK_REG_PAIR(r4);

        GEN_HELPER_RRR(ixmin_u, cpu_gpr_d[r4], cpu_gpr_d[r4+1], cpu_gpr_d[r3],

                       cpu_gpr_d[r3+1], cpu_gpr_d[r2]);

        break;

    case OPC2_32_RRR_PACK:

        gen_helper_pack(cpu_gpr_d[r4], cpu_PSW_C, cpu_gpr_d[r3],

                        cpu_gpr_d[r3+1], cpu_gpr_d[r1]);

        break;

    default:

        generate_trap(ctx, TRAPC_INSN_ERR, TIN2_IOPC);

    }

}


static void qemu_input_transform_abs_rotate(InputEvent *evt)

{

    InputMoveEvent *move = evt->u.abs;

    switch (graphic_rotate) {

    case 90:

        if (move->axis == INPUT_AXIS_X) {

            move->axis = INPUT_AXIS_Y;

        } else if (move->axis == INPUT_AXIS_Y) {

            move->axis = INPUT_AXIS_X;

            move->value = INPUT_EVENT_ABS_SIZE - 1 - move->value;

        }

        break;

    case 180:

        move->value = INPUT_EVENT_ABS_SIZE - 1 - move->value;

        break;

    case 270:

        if (move->axis == INPUT_AXIS_X) {

            move->axis = INPUT_AXIS_Y;

            move->value = INPUT_EVENT_ABS_SIZE - 1 - move->value;

        } else if (move->axis == INPUT_AXIS_Y) {

            move->axis = INPUT_AXIS_X;

        }

        break;

    }

}


static int split_init(AVFilterContext *ctx, const char *args, void *opaque)

{

    int i, nb_outputs = 2;

    if (args) {

        nb_outputs = strtol(args, NULL, 0);

        if (nb_outputs <= 0) {

            av_log(ctx, AV_LOG_ERROR, "Invalid number of outputs specified: %d.\n",

                   nb_outputs);

            return AVERROR(EINVAL);

        }

    }

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

        char name[32];

        AVFilterPad pad = { 0 };

        snprintf(name, sizeof(name), "output%d", i);

        pad.type = !strcmp(ctx->name, "split") ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;

        pad.name = av_strdup(name);

        avfilter_insert_outpad(ctx, i, &pad);

    }

    return 0;

}


static int mcf_fec_can_receive(void *opaque)

{

    mcf_fec_state *s = (mcf_fec_state *)opaque;

    return s->rx_enabled;

}


static void qxl_realize_common(PCIQXLDevice *qxl, Error **errp)

{

    uint8_t* config = qxl->pci.config;

    uint32_t pci_device_rev;

    uint32_t io_size;

    qxl->mode = QXL_MODE_UNDEFINED;

    qxl->generation = 1;

    qxl->num_memslots = NUM_MEMSLOTS;

    qemu_mutex_init(&qxl->track_lock);

    qemu_mutex_init(&qxl->async_lock);

    qxl->current_async = QXL_UNDEFINED_IO;

    qxl->guest_bug = 0;

    switch (qxl->revision) {

    case 1: /* spice 0.4 -- qxl-1 */

        pci_device_rev = QXL_REVISION_STABLE_V04;

        io_size = 8;

        break;

    case 2: /* spice 0.6 -- qxl-2 */

        pci_device_rev = QXL_REVISION_STABLE_V06;

        io_size = 16;

        break;

    case 3: /* qxl-3 */

        pci_device_rev = QXL_REVISION_STABLE_V10;

        io_size = 32; /* PCI region size must be pow2 */

        break;

    case 4: /* qxl-4 */

        pci_device_rev = QXL_REVISION_STABLE_V12;

        io_size = pow2ceil(QXL_IO_RANGE_SIZE);

        break;

    default:

        error_setg(errp, "Invalid revision %d for qxl device (max %d)",

                   qxl->revision, QXL_DEFAULT_REVISION);

        return;

    }

    pci_set_byte(&config[PCI_REVISION_ID], pci_device_rev);

    pci_set_byte(&config[PCI_INTERRUPT_PIN], 1);

    qxl->rom_size = qxl_rom_size();

    memory_region_init_ram(&qxl->rom_bar, OBJECT(qxl), "qxl.vrom",

                           qxl->rom_size, &error_fatal);

    vmstate_register_ram(&qxl->rom_bar, &qxl->pci.qdev);

    init_qxl_rom(qxl);

    init_qxl_ram(qxl);

    qxl->guest_surfaces.cmds = g_new0(QXLPHYSICAL, qxl->ssd.num_surfaces);

    memory_region_init_ram(&qxl->vram_bar, OBJECT(qxl), "qxl.vram",

                           qxl->vram_size, &error_fatal);

    vmstate_register_ram(&qxl->vram_bar, &qxl->pci.qdev);

    memory_region_init_alias(&qxl->vram32_bar, OBJECT(qxl), "qxl.vram32",

                             &qxl->vram_bar, 0, qxl->vram32_size);

    memory_region_init_io(&qxl->io_bar, OBJECT(qxl), &qxl_io_ops, qxl,

                          "qxl-ioports", io_size);

    if (qxl->id == 0) {

        vga_dirty_log_start(&qxl->vga);

    }

    memory_region_set_flush_coalesced(&qxl->io_bar);

    pci_register_bar(&qxl->pci, QXL_IO_RANGE_INDEX,

                     PCI_BASE_ADDRESS_SPACE_IO, &qxl->io_bar);

    pci_register_bar(&qxl->pci, QXL_ROM_RANGE_INDEX,

                     PCI_BASE_ADDRESS_SPACE_MEMORY, &qxl->rom_bar);

    pci_register_bar(&qxl->pci, QXL_RAM_RANGE_INDEX,

                     PCI_BASE_ADDRESS_SPACE_MEMORY, &qxl->vga.vram);

    pci_register_bar(&qxl->pci, QXL_VRAM_RANGE_INDEX,

                     PCI_BASE_ADDRESS_SPACE_MEMORY, &qxl->vram32_bar);

    if (qxl->vram32_size < qxl->vram_size) {

        /*

         * Make the 64bit vram bar show up only in case it is

         * configured to be larger than the 32bit vram bar.

         */

        pci_register_bar(&qxl->pci, QXL_VRAM64_RANGE_INDEX,

                         PCI_BASE_ADDRESS_SPACE_MEMORY |

                         PCI_BASE_ADDRESS_MEM_TYPE_64 |

                         PCI_BASE_ADDRESS_MEM_PREFETCH,

                         &qxl->vram_bar);

    }

    /* print pci bar details */

    dprint(qxl, 1, "ram/%s: %d MB [region 0]\n",

           qxl->id == 0 ? "pri" : "sec",

           qxl->vga.vram_size / (1024*1024));

    dprint(qxl, 1, "vram/32: %d MB [region 1]\n",

           qxl->vram32_size / (1024*1024));

    dprint(qxl, 1, "vram/64: %d MB %s\n",

           qxl->vram_size / (1024*1024),

           qxl->vram32_size < qxl->vram_size ? "[region 4]" : "[unmapped]");

    qxl->ssd.qxl.base.sif = &qxl_interface.base;

    if (qemu_spice_add_display_interface(&qxl->ssd.qxl, qxl->vga.con) != 0) {

        error_setg(errp, "qxl interface %d.%d not supported by spice-server",

                   SPICE_INTERFACE_QXL_MAJOR, SPICE_INTERFACE_QXL_MINOR);

        return;

    }

    qemu_add_vm_change_state_handler(qxl_vm_change_state_handler, qxl);

    qxl->update_irq = qemu_bh_new(qxl_update_irq_bh, qxl);

    qxl_reset_state(qxl);

    qxl->update_area_bh = qemu_bh_new(qxl_render_update_area_bh, qxl);

    qxl->ssd.cursor_bh = qemu_bh_new(qemu_spice_cursor_refresh_bh, &qxl->ssd);

}