static inline void RENAME(hcscale_fast)(SwsContext *c, int16_t *dst,

                                        long dstWidth, const uint8_t *src1,

                                        const uint8_t *src2, int srcW, int xInc)

{

#if ARCH_X86

#if COMPILE_TEMPLATE_MMX2

    int32_t *filterPos = c->hChrFilterPos;

    int16_t *filter    = c->hChrFilter;

    int     canMMX2BeUsed  = c->canMMX2BeUsed;

    void    *mmx2FilterCode= c->chrMmx2FilterCode;

    int i;

#if defined(PIC)

    DECLARE_ALIGNED(8, uint64_t, ebxsave);

#endif

    if (canMMX2BeUsed) {

        __asm__ volatile(

#if defined(PIC)

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

#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"

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

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

            "mov                 %5, %%"REG_c"  \n\t" // src

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

            "add              $"AV_STRINGIFY(VOF)", %%"REG_D"  \n\t"

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

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

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

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

#if defined(PIC)

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

#endif

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

            "m" (mmx2FilterCode), "m" (src2)

#if defined(PIC)

            ,"m" (ebxsave)

#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--) {

            //printf("%d %d %d\n", dstWidth, i, srcW);

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

            dst[i+VOFW] = src2[srcW-1]*128;

        }

    } else {

#endif /* COMPILE_TEMPLATE_MMX2 */

        x86_reg xInc_shr16 = (x86_reg) (xInc >> 16);

        uint16_t xInc_mask = xInc & 0xffff;

        x86_reg dstWidth_reg = dstWidth;

        __asm__ volatile(

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

            "xor %%"REG_d", %%"REG_d"               \n\t" // xx

            "xorl    %%ecx, %%ecx                   \n\t" // xalpha

            ".p2align    4                          \n\t"

            "1:                                     \n\t"

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

            "movzbl  (%%"REG_S", %%"REG_d"), %%edi  \n\t" //src[xx]

            "movzbl 1(%%"REG_S", %%"REG_d"), %%esi  \n\t" //src[xx+1]

            FAST_BILINEAR_X86

            "movw     %%si, (%%"REG_D", %%"REG_a", 2)   \n\t"

            "movzbl    (%5, %%"REG_d"), %%edi       \n\t" //src[xx]

            "movzbl   1(%5, %%"REG_d"), %%esi       \n\t" //src[xx+1]

            FAST_BILINEAR_X86

            "movw     %%si, "AV_STRINGIFY(VOF)"(%%"REG_D", %%"REG_a", 2)   \n\t"

            "addw       %4, %%cx                    \n\t" //xalpha += xInc&0xFFFF

            "adc        %3, %%"REG_d"               \n\t" //xx+= xInc>>16 + carry

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

            "cmp        %2, %%"REG_a"               \n\t"

            " jb        1b                          \n\t"

/* GCC 3.3 makes MPlayer crash on IA-32 machines when using "g" operand here,

which is needed to support GCC 4.0. */

#if ARCH_X86_64 && AV_GCC_VERSION_AT_LEAST(3,4)

            :: "m" (src1), "m" (dst), "g" (dstWidth_reg), "m" (xInc_shr16), "m" (xInc_mask),

#else

            :: "m" (src1), "m" (dst), "m" (dstWidth_reg), "m" (xInc_shr16), "m" (xInc_mask),

#endif

            "r" (src2)

            : "%"REG_a, "%"REG_d, "%ecx", "%"REG_D, "%esi"

        );

#if COMPILE_TEMPLATE_MMX2

    } //if MMX2 can't be used

#endif

#else

    int i;

    unsigned int xpos=0;

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

        register unsigned int xx=xpos>>16;

        register unsigned int xalpha=(xpos&0xFFFF)>>9;

        dst[i]=(src1[xx]*(xalpha^127)+src1[xx+1]*xalpha);

        dst[i+VOFW]=(src2[xx]*(xalpha^127)+src2[xx+1]*xalpha);

        /* slower

        dst[i]= (src1[xx]<<7) + (src1[xx+1] - src1[xx])*xalpha;

        dst[i+VOFW]=(src2[xx]<<7) + (src2[xx+1] - src2[xx])*xalpha;

        */

        xpos+=xInc;

    }

#endif /* ARCH_X86 */

}


static void ga_channel_listen_close(GAChannel *c)

{

    g_assert(c->method == GA_CHANNEL_UNIX_LISTEN);

    g_assert(c->listen_channel);

    g_io_channel_shutdown(c->listen_channel, true, NULL);

    g_io_channel_unref(c->listen_channel);

    c->listen_channel = NULL;

}


static int v9fs_do_setuid(V9fsState *s, uid_t uid)

{

    return s->ops->setuid(&s->ctx, uid);

}


static void vgafb_update_display(void *opaque)

{

    MilkymistVgafbState *s = opaque;

    SysBusDevice *sbd;

    DisplaySurface *surface = qemu_console_surface(s->con);

    int first = 0;

    int last = 0;

    drawfn fn;

    if (!vgafb_enabled(s)) {

        return;

    }

    sbd = SYS_BUS_DEVICE(s);

    int dest_width = s->regs[R_HRES];

    switch (surface_bits_per_pixel(surface)) {

    case 0:

        return;

    case 8:

        fn = draw_line_8;

        break;

    case 15:

        fn = draw_line_15;

        dest_width *= 2;

        break;

    case 16:

        fn = draw_line_16;

        dest_width *= 2;

        break;

    case 24:

        fn = draw_line_24;

        dest_width *= 3;

        break;

    case 32:

        fn = draw_line_32;

        dest_width *= 4;

        break;

    default:

        hw_error("milkymist_vgafb: bad color depth\n");

        break;

    }

    framebuffer_update_display(surface, sysbus_address_space(sbd),

                               s->regs[R_BASEADDRESS] + s->fb_offset,

                               s->regs[R_HRES],

                               s->regs[R_VRES],

                               s->regs[R_HRES] * 2,

                               dest_width,

                               0,

                               s->invalidate,

                               fn,

                               NULL,

                               &first, &last);

    if (first >= 0) {

        dpy_gfx_update(s->con, 0, first, s->regs[R_HRES], last - first + 1);

    }

    s->invalidate = 0;

}


static void mainstone_common_init(int ram_size, int vga_ram_size,

                DisplayState *ds, const char *kernel_filename,

                const char *kernel_cmdline, const char *initrd_filename,

                const char *cpu_model, enum mainstone_model_e model, int arm_id)

{

    uint32_t mainstone_ram = 0x04000000;

    uint32_t mainstone_rom = 0x00800000;

    struct pxa2xx_state_s *cpu;

    qemu_irq *mst_irq;

    int index;

    if (!cpu_model)

        cpu_model = "pxa270-c5";

    /* Setup CPU & memory */

    if (ram_size < mainstone_ram + mainstone_rom + PXA2XX_INTERNAL_SIZE) {

        fprintf(stderr, "This platform requires %i bytes of memory\n",

                        mainstone_ram + mainstone_rom + PXA2XX_INTERNAL_SIZE);

        exit(1);

    }

    cpu = pxa270_init(mainstone_ram, ds, cpu_model);

    cpu_register_physical_memory(0, mainstone_rom,

                    qemu_ram_alloc(mainstone_rom) | IO_MEM_ROM);

    /* Setup initial (reset) machine state */

    cpu->env->regs[15] = PXA2XX_SDRAM_BASE;

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

    index = drive_get_index(IF_PFLASH, 0, 0);

    if (index == -1) {

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

                "'pflash' parameter\n");

        exit(1);

    }

    if (!pflash_register(MST_FLASH_0, mainstone_ram + PXA2XX_INTERNAL_SIZE,

                         drives_table[index].bdrv,

                         256 * 1024, 128, 4, 0, 0, 0, 0)) {

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

        exit(1);

    }

    index = drive_get_index(IF_PFLASH, 0, 1);

    if (index == -1) {

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

                "'pflash' parameter\n");

        exit(1);

    }

    if (!pflash_register(MST_FLASH_1, mainstone_ram + PXA2XX_INTERNAL_SIZE,

                         drives_table[index].bdrv,

                         256 * 1024, 128, 4, 0, 0, 0, 0)) {

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

        exit(1);

    }

    mst_irq = mst_irq_init(cpu, MST_FPGA_PHYS, PXA2XX_PIC_GPIO_0);

    /* MMC/SD host */

    pxa2xx_mmci_handlers(cpu->mmc, mst_irq[MMC_IRQ], mst_irq[MMC_IRQ]);

    smc91c111_init(&nd_table[0], MST_ETH_PHYS, mst_irq[ETHERNET_IRQ]);

    arm_load_kernel(cpu->env, mainstone_ram, kernel_filename, kernel_cmdline,

                    initrd_filename, arm_id, PXA2XX_SDRAM_BASE);

}


uint32_t HELPER(xc)(CPUS390XState *env, uint32_t l, uint64_t dest,

                    uint64_t src)

{

    int i;

    unsigned char x;

    uint32_t cc = 0;

    HELPER_LOG("%s l %d dest %" PRIx64 " src %" PRIx64 "\n",

               __func__, l, dest, src);

#ifndef CONFIG_USER_ONLY

    /* xor with itself is the same as memset(0) */

    if ((l > 32) && (src == dest) &&

        (src & TARGET_PAGE_MASK) == ((src + l) & TARGET_PAGE_MASK)) {

        mvc_fast_memset(env, l + 1, dest, 0);

        return 0;

    }

#else

    if (src == dest) {

        memset(g2h(dest), 0, l + 1);

        return 0;

    }

#endif

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

        x = cpu_ldub_data(env, dest + i) ^ cpu_ldub_data(env, src + i);

        if (x) {

            cc = 1;

        }

        cpu_stb_data(env, dest + i, x);

    }

    return cc;

}


static int xen_pt_pci_config_access_check(PCIDevice *d, uint32_t addr, int len)

{

    /* check offset range */

    if (addr >= 0xFF) {

        XEN_PT_ERR(d, "Failed to access register with offset exceeding 0xFF. "

                   "(addr: 0x%02x, len: %d)\n", addr, len);

        return -1;

    }

    /* check read size */

    if ((len != 1) && (len != 2) && (len != 4)) {

        XEN_PT_ERR(d, "Failed to access register with invalid access length. "

                   "(addr: 0x%02x, len: %d)\n", addr, len);

        return -1;

    }

    /* check offset alignment */

    if (addr & (len - 1)) {

        XEN_PT_ERR(d, "Failed to access register with invalid access size "

                   "alignment. (addr: 0x%02x, len: %d)\n", addr, len);

        return -1;

    }

    return 0;

}


static inline int dmg_read_chunk(BlockDriverState *bs, int sector_num)

{

    BDRVDMGState *s = bs->opaque;

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

	int ret;

	uint32_t chunk = search_chunk(s,sector_num);

	if(chunk>=s->n_chunks)

	    return -1;

	s->current_chunk = s->n_chunks;

	switch(s->types[chunk]) {

	case 0x80000005: { /* zlib compressed */

	    int i;

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

	     * inflated. */

	    i=0;

	    do {

                ret = bdrv_pread(bs->file, s->offsets[chunk] + i,

                                 s->compressed_chunk+i, s->lengths[chunk]-i);

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

		    ret=0;

		i+=ret;

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

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

		return -1;

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

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

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

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

	    ret = inflateReset(&s->zstream);

	    if(ret != Z_OK)

		return -1;

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

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

		return -1;

	    break; }

	case 1: /* copy */

	    ret = bdrv_pread(bs->file, s->offsets[chunk],

                             s->uncompressed_chunk, s->lengths[chunk]);

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

		return -1;

	    break;

	case 2: /* zero */

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

	    break;

	}

	s->current_chunk = chunk;

    }

    return 0;

}


void object_property_add_child(Object *obj, const char *name,

                               Object *child, Error **errp)

{

    Error *local_err = NULL;

    gchar *type;

    type = g_strdup_printf("child<%s>", object_get_typename(OBJECT(child)));

    object_property_add(obj, name, type, object_get_child_property, NULL,

                        object_finalize_child_property, child, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        goto out;

    }

    object_ref(child);

    g_assert(child->parent == NULL);

    child->parent = obj;

out:

    g_free(type);

}


void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,

              int mmu_idx, uintptr_t retaddr)

{

    bool ret;

    uint32_t fsr = 0;

    ARMMMUFaultInfo fi = {};

    ret = arm_tlb_fill(cs, addr, access_type, mmu_idx, &fsr, &fi);

    if (unlikely(ret)) {

        ARMCPU *cpu = ARM_CPU(cs);

        CPUARMState *env = &cpu->env;

        uint32_t syn, exc;

        unsigned int target_el;

        bool same_el;

        if (retaddr) {

            /* now we have a real cpu fault */

            cpu_restore_state(cs, retaddr);

        }

        target_el = exception_target_el(env);

        if (fi.stage2) {

            target_el = 2;

            env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;

        }

        same_el = arm_current_el(env) == target_el;

        /* AArch64 syndrome does not have an LPAE bit */

        syn = fsr & ~(1 << 9);

        /* For insn and data aborts we assume there is no instruction syndrome

         * information; this is always true for exceptions reported to EL1.

         */

        if (access_type == MMU_INST_FETCH) {

            syn = syn_insn_abort(same_el, 0, fi.s1ptw, syn);

            exc = EXCP_PREFETCH_ABORT;

        } else {

            syn = merge_syn_data_abort(env->exception.syndrome, target_el,

                                       same_el, fi.s1ptw,

                                       access_type == MMU_DATA_STORE, syn);

            if (access_type == MMU_DATA_STORE

                && arm_feature(env, ARM_FEATURE_V6)) {

                fsr |= (1 << 11);

            }

            exc = EXCP_DATA_ABORT;

        }

        env->exception.vaddress = addr;

        env->exception.fsr = fsr;

        raise_exception(env, exc, syn, target_el);

    }

}


static inline FFAMediaCodec *codec_create(int method, const char *arg)

{

    int ret = -1;

    JNIEnv *env = NULL;

    FFAMediaCodec *codec = NULL;

    jstring jarg = NULL;

    jobject object = NULL;

    jmethodID create_id = NULL;

    codec = av_mallocz(sizeof(FFAMediaCodec));

    if (!codec) {

        return NULL;

    codec->class = &amediacodec_class;

    env = ff_jni_get_env(codec);

    if (!env) {

        av_freep(&codec);

        return NULL;

    if (ff_jni_init_jfields(env, &codec->jfields, jni_amediacodec_mapping, 1, codec) < 0) {

        goto fail;

    jarg = ff_jni_utf_chars_to_jstring(env, arg, codec);

    if (!jarg) {

        goto fail;

    switch (method) {

    case CREATE_CODEC_BY_NAME:   create_id = codec->jfields.create_by_codec_name_id;   break;

    case CREATE_DECODER_BY_TYPE: create_id = codec->jfields.create_decoder_by_type_id; break;

    case CREATE_ENCODER_BY_TYPE: create_id = codec->jfields.create_encoder_by_type_id; break;

    default:

        av_assert0(0);

    object = (*env)->CallStaticObjectMethod(env,

                                            codec->jfields.mediacodec_class,

                                            create_id,

                                            jarg);

    if (ff_jni_exception_check(env, 1, codec) < 0) {

        goto fail;

    codec->object = (*env)->NewGlobalRef(env, object);

    if (!codec->object) {

        goto fail;

    if (codec_init_static_fields(codec) < 0) {

        goto fail;

    if (codec->jfields.get_input_buffer_id && codec->jfields.get_output_buffer_id) {

        codec->has_get_i_o_buffer = 1;

    ret = 0;

fail:

    if (jarg) {

        (*env)->DeleteLocalRef(env, jarg);

    if (object) {

        (*env)->DeleteLocalRef(env, object);

    if (ret < 0) {

        ff_jni_reset_jfields(env, &codec->jfields, jni_amediacodec_mapping, 1, codec);

        av_freep(&codec);

    return codec;


static int parse_header(OutputStream *os, const uint8_t *buf, int buf_size)

{

    if (buf_size < 13)

        return AVERROR_INVALIDDATA;

    if (memcmp(buf, "FLV", 3))

        return AVERROR_INVALIDDATA;

    buf      += 13;

    buf_size -= 13;

    while (buf_size >= 11 + 4) {

        int type = buf[0];

        int size = AV_RB24(&buf[1]) + 11 + 4;

        if (size > buf_size)

            return AVERROR_INVALIDDATA;

        if (type == 8 || type == 9) {

            if (os->nb_extra_packets > FF_ARRAY_ELEMS(os->extra_packets))

                return AVERROR_INVALIDDATA;

            os->extra_packet_sizes[os->nb_extra_packets] = size;

            os->extra_packets[os->nb_extra_packets] = av_malloc(size);

            if (!os->extra_packets[os->nb_extra_packets])

                return AVERROR(ENOMEM);

            memcpy(os->extra_packets[os->nb_extra_packets], buf, size);

            os->nb_extra_packets++;

        } else if (type == 0x12) {

            if (os->metadata)

                return AVERROR_INVALIDDATA;

            os->metadata_size = size - 11 - 4;

            os->metadata      = av_malloc(os->metadata_size);

            if (!os->metadata)

                return AVERROR(ENOMEM);

            memcpy(os->metadata, buf + 11, os->metadata_size);

        }

        buf      += size;

        buf_size -= size;

    }

    if (!os->metadata)

        return AVERROR_INVALIDDATA;

    return 0;

}


static void omap_i2c_send(I2CAdapter *i2c, uint8_t addr,

                          const uint8_t *buf, uint16_t len)

{

    OMAPI2C *s = (OMAPI2C *)i2c;

    uint16_t data;

    omap_i2c_set_slave_addr(s, addr);

    data = len;

    memwrite(s->addr + OMAP_I2C_CNT, &data, 2);

    data = OMAP_I2C_CON_I2C_EN |

           OMAP_I2C_CON_TRX |

           OMAP_I2C_CON_MST |

           OMAP_I2C_CON_STT |

           OMAP_I2C_CON_STP;

    memwrite(s->addr + OMAP_I2C_CON, &data, 2);

    memread(s->addr + OMAP_I2C_CON, &data, 2);

    g_assert((data & OMAP_I2C_CON_STP) != 0);

    memread(s->addr + OMAP_I2C_STAT, &data, 2);

    g_assert((data & OMAP_I2C_STAT_NACK) == 0);

    while (len > 1) {

        memread(s->addr + OMAP_I2C_STAT, &data, 2);

        g_assert((data & OMAP_I2C_STAT_XRDY) != 0);

        memwrite(s->addr + OMAP_I2C_DATA, buf, 2);

        buf = (uint8_t *)buf + 2;

        len -= 2;

    }

    if (len == 1) {

        memread(s->addr + OMAP_I2C_STAT, &data, 2);

        g_assert((data & OMAP_I2C_STAT_XRDY) != 0);

        memwrite(s->addr + OMAP_I2C_DATA, buf, 1);

    }

    memread(s->addr + OMAP_I2C_CON, &data, 2);

    g_assert((data & OMAP_I2C_CON_STP) == 0);

}


static void mps2_common_init(MachineState *machine)

{

    MPS2MachineState *mms = MPS2_MACHINE(machine);

    MPS2MachineClass *mmc = MPS2_MACHINE_GET_CLASS(machine);

    MemoryRegion *system_memory = get_system_memory();

    DeviceState *armv7m, *sccdev;

    if (!machine->cpu_model) {

        machine->cpu_model = mmc->cpu_model;

    }

    if (strcmp(machine->cpu_model, mmc->cpu_model) != 0) {

        error_report("This board can only be used with CPU %s", mmc->cpu_model);

        exit(1);

    }

    /* The FPGA images have an odd combination of different RAMs,

     * because in hardware they are different implementations and

     * connected to different buses, giving varying performance/size

     * tradeoffs. For QEMU they're all just RAM, though. We arbitrarily

     * call the 16MB our "system memory", as it's the largest lump.

     *

     * Common to both boards:

     *  0x21000000..0x21ffffff : PSRAM (16MB)

     * AN385 only:

     *  0x00000000 .. 0x003fffff : ZBT SSRAM1

     *  0x00400000 .. 0x007fffff : mirror of ZBT SSRAM1

     *  0x20000000 .. 0x203fffff : ZBT SSRAM 2&3

     *  0x20400000 .. 0x207fffff : mirror of ZBT SSRAM 2&3

     *  0x01000000 .. 0x01003fff : block RAM (16K)

     *  0x01004000 .. 0x01007fff : mirror of above

     *  0x01008000 .. 0x0100bfff : mirror of above

     *  0x0100c000 .. 0x0100ffff : mirror of above

     * AN511 only:

     *  0x00000000 .. 0x0003ffff : FPGA block RAM

     *  0x00400000 .. 0x007fffff : ZBT SSRAM1

     *  0x20000000 .. 0x2001ffff : SRAM

     *  0x20400000 .. 0x207fffff : ZBT SSRAM 2&3

     *

     * The AN385 has a feature where the lowest 16K can be mapped

     * either to the bottom of the ZBT SSRAM1 or to the block RAM.

     * This is of no use for QEMU so we don't implement it (as if

     * zbt_boot_ctrl is always zero).

     */

    memory_region_allocate_system_memory(&mms->psram,

                                         NULL, "mps.ram", 0x1000000);

    memory_region_add_subregion(system_memory, 0x21000000, &mms->psram);

    switch (mmc->fpga_type) {

    case FPGA_AN385:

        make_ram(&mms->ssram1, "mps.ssram1", 0x0, 0x400000);

        make_ram_alias(&mms->ssram1_m, "mps.ssram1_m", &mms->ssram1, 0x400000);

        make_ram(&mms->ssram23, "mps.ssram23", 0x20000000, 0x400000);

        make_ram_alias(&mms->ssram23_m, "mps.ssram23_m",

                       &mms->ssram23, 0x20400000);

        make_ram(&mms->blockram, "mps.blockram", 0x01000000, 0x4000);

        make_ram_alias(&mms->blockram_m1, "mps.blockram_m1",

                       &mms->blockram, 0x01004000);

        make_ram_alias(&mms->blockram_m2, "mps.blockram_m2",

                       &mms->blockram, 0x01008000);

        make_ram_alias(&mms->blockram_m3, "mps.blockram_m3",

                       &mms->blockram, 0x0100c000);

        break;

    case FPGA_AN511:

        make_ram(&mms->blockram, "mps.blockram", 0x0, 0x40000);

        make_ram(&mms->ssram1, "mps.ssram1", 0x00400000, 0x00800000);

        make_ram(&mms->sram, "mps.sram", 0x20000000, 0x20000);

        make_ram(&mms->ssram23, "mps.ssram23", 0x20400000, 0x400000);

        break;

    default:

        g_assert_not_reached();

    }

    object_initialize(&mms->armv7m, sizeof(mms->armv7m), TYPE_ARMV7M);

    armv7m = DEVICE(&mms->armv7m);

    qdev_set_parent_bus(armv7m, sysbus_get_default());

    switch (mmc->fpga_type) {

    case FPGA_AN385:

        qdev_prop_set_uint32(armv7m, "num-irq", 32);

        break;

    case FPGA_AN511:

        qdev_prop_set_uint32(armv7m, "num-irq", 64);

        break;

    default:

        g_assert_not_reached();

    }

    qdev_prop_set_string(armv7m, "cpu-model", machine->cpu_model);

    object_property_set_link(OBJECT(&mms->armv7m), OBJECT(system_memory),

                             "memory", &error_abort);

    object_property_set_bool(OBJECT(&mms->armv7m), true, "realized",

                             &error_fatal);

    create_unimplemented_device("zbtsmram mirror", 0x00400000, 0x00400000);

    create_unimplemented_device("RESERVED 1", 0x00800000, 0x00800000);

    create_unimplemented_device("Block RAM", 0x01000000, 0x00010000);

    create_unimplemented_device("RESERVED 2", 0x01010000, 0x1EFF0000);

    create_unimplemented_device("RESERVED 3", 0x20800000, 0x00800000);

    create_unimplemented_device("PSRAM", 0x21000000, 0x01000000);

    /* These three ranges all cover multiple devices; we may implement

     * some of them below (in which case the real device takes precedence

     * over the unimplemented-region mapping).

     */

    create_unimplemented_device("CMSDK APB peripheral region @0x40000000",

                                0x40000000, 0x00010000);

    create_unimplemented_device("CMSDK peripheral region @0x40010000",

                                0x40010000, 0x00010000);

    create_unimplemented_device("Extra peripheral region @0x40020000",

                                0x40020000, 0x00010000);

    create_unimplemented_device("RESERVED 4", 0x40030000, 0x001D0000);

    create_unimplemented_device("VGA", 0x41000000, 0x0200000);

    switch (mmc->fpga_type) {

    case FPGA_AN385:

    {

        /* The overflow IRQs for UARTs 0, 1 and 2 are ORed together.

         * Overflow for UARTs 4 and 5 doesn't trigger any interrupt.

         */

        Object *orgate;

        DeviceState *orgate_dev;

        int i;

        orgate = object_new(TYPE_OR_IRQ);

        object_property_set_int(orgate, 6, "num-lines", &error_fatal);

        object_property_set_bool(orgate, true, "realized", &error_fatal);

        orgate_dev = DEVICE(orgate);

        qdev_connect_gpio_out(orgate_dev, 0, qdev_get_gpio_in(armv7m, 12));

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

            static const hwaddr uartbase[] = {0x40004000, 0x40005000,

                                              0x40006000, 0x40007000,

                                              0x40009000};

            Chardev *uartchr = i < MAX_SERIAL_PORTS ? serial_hds[i] : NULL;

            /* RX irq number; TX irq is always one greater */

            static const int uartirq[] = {0, 2, 4, 18, 20};

            qemu_irq txovrint = NULL, rxovrint = NULL;

            if (i < 3) {

                txovrint = qdev_get_gpio_in(orgate_dev, i * 2);

                rxovrint = qdev_get_gpio_in(orgate_dev, i * 2 + 1);

            }

            cmsdk_apb_uart_create(uartbase[i],

                                  qdev_get_gpio_in(armv7m, uartirq[i] + 1),

                                  qdev_get_gpio_in(armv7m, uartirq[i]),

                                  txovrint, rxovrint,

                                  NULL,

                                  uartchr, SYSCLK_FRQ);

        }

        break;

    }

    case FPGA_AN511:

    {

        /* The overflow IRQs for all UARTs are ORed together.

         * Tx and Rx IRQs for each UART are ORed together.

         */

        Object *orgate;

        DeviceState *orgate_dev;

        int i;

        orgate = object_new(TYPE_OR_IRQ);

        object_property_set_int(orgate, 10, "num-lines", &error_fatal);

        object_property_set_bool(orgate, true, "realized", &error_fatal);

        orgate_dev = DEVICE(orgate);

        qdev_connect_gpio_out(orgate_dev, 0, qdev_get_gpio_in(armv7m, 12));

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

            /* system irq numbers for the combined tx/rx for each UART */

            static const int uart_txrx_irqno[] = {0, 2, 45, 46, 56};

            static const hwaddr uartbase[] = {0x40004000, 0x40005000,

                                              0x4002c000, 0x4002d000,

                                              0x4002e000};

            Chardev *uartchr = i < MAX_SERIAL_PORTS ? serial_hds[i] : NULL;

            Object *txrx_orgate;

            DeviceState *txrx_orgate_dev;

            txrx_orgate = object_new(TYPE_OR_IRQ);

            object_property_set_int(txrx_orgate, 2, "num-lines", &error_fatal);

            object_property_set_bool(txrx_orgate, true, "realized",

                                     &error_fatal);

            txrx_orgate_dev = DEVICE(txrx_orgate);

            qdev_connect_gpio_out(txrx_orgate_dev, 0,

                                  qdev_get_gpio_in(armv7m, uart_txrx_irqno[i]));

            cmsdk_apb_uart_create(uartbase[i],

                                  qdev_get_gpio_in(txrx_orgate_dev, 0),

                                  qdev_get_gpio_in(txrx_orgate_dev, 1),

                                  qdev_get_gpio_in(orgate_dev, 0),

                                  qdev_get_gpio_in(orgate_dev, 1),

                                  NULL,

                                  uartchr, SYSCLK_FRQ);

        }

        break;

    }

    default:

        g_assert_not_reached();

    }

    cmsdk_apb_timer_create(0x40000000, qdev_get_gpio_in(armv7m, 8), SYSCLK_FRQ);

    cmsdk_apb_timer_create(0x40001000, qdev_get_gpio_in(armv7m, 9), SYSCLK_FRQ);

    object_initialize(&mms->scc, sizeof(mms->scc), TYPE_MPS2_SCC);

    sccdev = DEVICE(&mms->scc);

    qdev_set_parent_bus(sccdev, sysbus_get_default());

    qdev_prop_set_uint32(sccdev, "scc-cfg4", 0x2);

    qdev_prop_set_uint32(sccdev, "scc-aid", 0x02000008);

    qdev_prop_set_uint32(sccdev, "scc-id", mmc->scc_id);

    object_property_set_bool(OBJECT(&mms->scc), true, "realized",

                             &error_fatal);

    sysbus_mmio_map(SYS_BUS_DEVICE(sccdev), 0, 0x4002f000);

    /* In hardware this is a LAN9220; the LAN9118 is software compatible

     * except that it doesn't support the checksum-offload feature.

     */

    lan9118_init(&nd_table[0], 0x40200000,

                 qdev_get_gpio_in(armv7m,

                                  mmc->fpga_type == FPGA_AN385 ? 13 : 47));

    system_clock_scale = NANOSECONDS_PER_SECOND / SYSCLK_FRQ;

    armv7m_load_kernel(ARM_CPU(first_cpu), machine->kernel_filename,

                       0x400000);

}


static int xbm_decode_frame(AVCodecContext *avctx, void *data,

                            int *got_frame, AVPacket *avpkt)

{

    AVFrame *p = data;

    const uint8_t *end, *ptr = avpkt->data;

    uint8_t *dst;

    int ret, linesize, i, j;

    end = avpkt->data + avpkt->size;

    while (!avctx->width || !avctx->height) {

        char name[256];

        int number, len;

        ptr += strcspn(ptr, "#");

        if (sscanf(ptr, "#define %256s %u", name, &number) != 2) {

            av_log(avctx, AV_LOG_ERROR, "Unexpected preprocessor directive\n");

            return AVERROR_INVALIDDATA;

        }

        len = strlen(name);

        if ((len > 6) && !avctx->height && !memcmp(name + len - 7, "_height", 7)) {

                avctx->height = number;

        } else if ((len > 5) && !avctx->width && !memcmp(name + len - 6, "_width", 6)) {

                avctx->width = number;

        } else {

            av_log(avctx, AV_LOG_ERROR, "Unknown define '%s'\n", name);

            return AVERROR_INVALIDDATA;

        }

        ptr += strcspn(ptr, "\n\r") + 1;

    }

    if ((ret = ff_get_buffer(avctx, p, 0)) < 0)

        return ret;

    // goto start of image data

    ptr += strcspn(ptr, "{") + 1;

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

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

        dst = p->data[0] + i * p->linesize[0];

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

            uint8_t val;

            ptr += strcspn(ptr, "x") + 1;

            if (ptr < end && av_isxdigit(*ptr)) {

                val = convert(*ptr);

                ptr++;

                if (av_isxdigit(*ptr))

                    val = (val << 4) + convert(*ptr);

                *dst++ = ff_reverse[val];

            } else {

                av_log(avctx, AV_LOG_ERROR, "Unexpected data at '%.8s'\n", ptr);

                return AVERROR_INVALIDDATA;

            }

        }

    }

    p->key_frame = 1;

    p->pict_type = AV_PICTURE_TYPE_I;

    *got_frame       = 1;

    return avpkt->size;

}


int mips_cpu_gdb_write_register(CPUState *cs, uint8_t *mem_buf, int n)

{

    MIPSCPU *cpu = MIPS_CPU(cs);

    CPUMIPSState *env = &cpu->env;

    target_ulong tmp;

    tmp = ldtul_p(mem_buf);

    if (n < 32) {

        env->active_tc.gpr[n] = tmp;

        return sizeof(target_ulong);

    }

    if (env->CP0_Config1 & (1 << CP0C1_FP)

            && n >= 38 && n < 73) {

        if (n < 70) {

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

                env->active_fpu.fpr[n - 38].d = tmp;

            } else {

                env->active_fpu.fpr[n - 38].w[FP_ENDIAN_IDX] = tmp;

            }

        }

        switch (n) {

        case 70:

            env->active_fpu.fcr31 = tmp & 0xFF83FFFF;

            /* set rounding mode */

            RESTORE_ROUNDING_MODE;

            break;

        case 71:

            env->active_fpu.fcr0 = tmp;

            break;

        }

        return sizeof(target_ulong);

    }

    switch (n) {

    case 32:

        env->CP0_Status = tmp;

        break;

    case 33:

        env->active_tc.LO[0] = tmp;

        break;

    case 34:

        env->active_tc.HI[0] = tmp;

        break;

    case 35:

        env->CP0_BadVAddr = tmp;

        break;

    case 36:

        env->CP0_Cause = tmp;

        break;

    case 37:

        env->active_tc.PC = tmp & ~(target_ulong)1;

        if (tmp & 1) {

            env->hflags |= MIPS_HFLAG_M16;

        } else {

            env->hflags &= ~(MIPS_HFLAG_M16);

        }

        break;

    case 72: /* fp, ignored */

        break;

    default:

        if (n > 89) {

            return 0;

        }

        /* Other registers are readonly.  Ignore writes.  */

        break;

    }

    return sizeof(target_ulong);

}


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

{

    int i;

    char header[MAX_FRAME_HEADER+1];

    int ret;

    int64_t off = avio_tell(s->pb);

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

        header[i] = avio_r8(s->pb);

        if (header[i] == '\n') {

            header[i + 1] = 0;

            break;

        }

    }

    if (s->pb->error)

        return s->pb->error;

    else if (s->pb->eof_reached)

        return AVERROR_EOF;

    else if (i == MAX_FRAME_HEADER)

        return AVERROR_INVALIDDATA;

    if (strncmp(header, Y4M_FRAME_MAGIC, strlen(Y4M_FRAME_MAGIC)))

        return AVERROR_INVALIDDATA;

    ret = av_get_packet(s->pb, pkt, s->packet_size - Y4M_FRAME_MAGIC_LEN);

    if (ret < 0)

        return ret;

    else if (ret != s->packet_size - Y4M_FRAME_MAGIC_LEN)

        return s->pb->eof_reached ? AVERROR_EOF : AVERROR(EIO);

    pkt->stream_index = 0;

    pkt->pts = (off - s->internal->data_offset) / s->packet_size;

    pkt->duration = 1;

    return 0;

}


uint64_t HELPER(neon_add_saturate_u64)(uint64_t src1, uint64_t src2)

{

    uint64_t res;

    res = src1 + src2;

    if (res < src1) {

        env->QF = 1;

        res = ~(uint64_t)0;

    }

    return res;

}


static void load_linux(PCMachineState *pcms,

                       FWCfgState *fw_cfg)

{

    uint16_t protocol;

    int setup_size, kernel_size, initrd_size = 0, cmdline_size;

    uint32_t initrd_max;

    uint8_t header[8192], *setup, *kernel, *initrd_data;

    hwaddr real_addr, prot_addr, cmdline_addr, initrd_addr = 0;

    FILE *f;

    char *vmode;

    MachineState *machine = MACHINE(pcms);

    const char *kernel_filename = machine->kernel_filename;

    const char *initrd_filename = machine->initrd_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    /* Align to 16 bytes as a paranoia measure */

    cmdline_size = (strlen(kernel_cmdline)+16) & ~15;

    /* load the kernel header */

    f = fopen(kernel_filename, "rb");

    if (!f || !(kernel_size = get_file_size(f)) ||

        fread(header, 1, MIN(ARRAY_SIZE(header), kernel_size), f) !=

        MIN(ARRAY_SIZE(header), kernel_size)) {

        fprintf(stderr, "qemu: could not load kernel '%s': %s\n",

                kernel_filename, strerror(errno));

    /* kernel protocol version */

#if 0

    fprintf(stderr, "header magic: %#x\n", ldl_p(header+0x202));

#endif

    if (ldl_p(header+0x202) == 0x53726448) {

        protocol = lduw_p(header+0x206);

    } else {

        /* This looks like a multiboot kernel. If it is, let's stop

           treating it like a Linux kernel. */

        if (load_multiboot(fw_cfg, f, kernel_filename, initrd_filename,

                           kernel_cmdline, kernel_size, header)) {

            return;

        protocol = 0;

    if (protocol < 0x200 || !(header[0x211] & 0x01)) {

        /* Low kernel */

        real_addr    = 0x90000;

        cmdline_addr = 0x9a000 - cmdline_size;

        prot_addr    = 0x10000;

    } else if (protocol < 0x202) {

        /* High but ancient kernel */

        real_addr    = 0x90000;

        cmdline_addr = 0x9a000 - cmdline_size;

        prot_addr    = 0x100000;

    } else {

        /* High and recent kernel */

        real_addr    = 0x10000;

        cmdline_addr = 0x20000;

        prot_addr    = 0x100000;

#if 0

    fprintf(stderr,

            "qemu: real_addr     = 0x" TARGET_FMT_plx "\n"

            "qemu: cmdline_addr  = 0x" TARGET_FMT_plx "\n"

            "qemu: prot_addr     = 0x" TARGET_FMT_plx "\n",

            real_addr,

            cmdline_addr,

            prot_addr);

#endif

    /* highest address for loading the initrd */

    if (protocol >= 0x203) {

        initrd_max = ldl_p(header+0x22c);

    } else {

        initrd_max = 0x37ffffff;

    if (initrd_max >= pcms->below_4g_mem_size - acpi_data_size) {

        initrd_max = pcms->below_4g_mem_size - acpi_data_size - 1;

    fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_ADDR, cmdline_addr);

    fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE, strlen(kernel_cmdline)+1);

    fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, kernel_cmdline);

    if (protocol >= 0x202) {

        stl_p(header+0x228, cmdline_addr);

    } else {

        stw_p(header+0x20, 0xA33F);

        stw_p(header+0x22, cmdline_addr-real_addr);

    /* handle vga= parameter */

    vmode = strstr(kernel_cmdline, "vga=");

    if (vmode) {

        unsigned int video_mode;

        /* skip "vga=" */

        vmode += 4;

        if (!strncmp(vmode, "normal", 6)) {

            video_mode = 0xffff;

        } else if (!strncmp(vmode, "ext", 3)) {

            video_mode = 0xfffe;

        } else if (!strncmp(vmode, "ask", 3)) {

            video_mode = 0xfffd;

        } else {

            video_mode = strtol(vmode, NULL, 0);

        stw_p(header+0x1fa, video_mode);

    /* loader type */

    /* High nybble = B reserved for QEMU; low nybble is revision number.

       If this code is substantially changed, you may want to consider

       incrementing the revision. */

    if (protocol >= 0x200) {

        header[0x210] = 0xB0;

    /* heap */

    if (protocol >= 0x201) {

        header[0x211] |= 0x80;	/* CAN_USE_HEAP */

        stw_p(header+0x224, cmdline_addr-real_addr-0x200);

    /* load initrd */

    if (initrd_filename) {

        if (protocol < 0x200) {

            fprintf(stderr, "qemu: linux kernel too old to load a ram disk\n");

        initrd_size = get_image_size(initrd_filename);

        if (initrd_size < 0) {

            fprintf(stderr, "qemu: error reading initrd %s: %s\n",

                    initrd_filename, strerror(errno));

        initrd_addr = (initrd_max-initrd_size) & ~4095;

        initrd_data = g_malloc(initrd_size);

        load_image(initrd_filename, initrd_data);

        fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_addr);

        fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);

        fw_cfg_add_bytes(fw_cfg, FW_CFG_INITRD_DATA, initrd_data, initrd_size);

        stl_p(header+0x218, initrd_addr);

        stl_p(header+0x21c, initrd_size);

    /* load kernel and setup */

    setup_size = header[0x1f1];

    if (setup_size == 0) {

        setup_size = 4;

    setup_size = (setup_size+1)*512;

    kernel_size -= setup_size;

    setup  = g_malloc(setup_size);

    kernel = g_malloc(kernel_size);

    fseek(f, 0, SEEK_SET);

    if (fread(setup, 1, setup_size, f) != setup_size) {

        fprintf(stderr, "fread() failed\n");

    if (fread(kernel, 1, kernel_size, f) != kernel_size) {

        fprintf(stderr, "fread() failed\n");

    fclose(f);

    memcpy(setup, header, MIN(sizeof(header), setup_size));

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, prot_addr);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);

    fw_cfg_add_bytes(fw_cfg, FW_CFG_KERNEL_DATA, kernel, kernel_size);

    fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_ADDR, real_addr);

    fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_SIZE, setup_size);

    fw_cfg_add_bytes(fw_cfg, FW_CFG_SETUP_DATA, setup, setup_size);

    option_rom[nb_option_roms].name = "linuxboot.bin";

    option_rom[nb_option_roms].bootindex = 0;

    nb_option_roms++;


void ga_command_state_add(GACommandState *cs,

                          void (*init)(void),

                          void (*cleanup)(void))

{

    GACommandGroup *cg = g_malloc0(sizeof(GACommandGroup));

    cg->init = init;

    cg->cleanup = cleanup;

    cs->groups = g_slist_append(cs->groups, cg);

}


static void new_pes_packet(PESContext *pes, AVPacket *pkt)

{

    av_init_packet(pkt);

    pkt->destruct = av_destruct_packet;

    pkt->data = pes->buffer;

    pkt->size = pes->data_index;

    memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);

    // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID

    if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)

        pkt->stream_index = pes->sub_st->index;

    else

        pkt->stream_index = pes->st->index;

    pkt->pts = pes->pts;

    pkt->dts = pes->dts;

    /* store position of first TS packet of this PES packet */

    pkt->pos = pes->ts_packet_pos;

    /* reset pts values */

    pes->pts = AV_NOPTS_VALUE;

    pes->dts = AV_NOPTS_VALUE;

    pes->buffer = NULL;

    pes->data_index = 0;

}


static int seqvideo_decode(SeqVideoContext *seq, const unsigned char *data, int data_size)

{

    const unsigned char *data_end = data + data_size;

    GetBitContext gb;

    int flags, i, j, x, y, op;

    unsigned char c[3];

    unsigned char *dst;

    uint32_t *palette;

    flags = *data++;

    if (flags & 1) {

        palette = (uint32_t *)seq->frame.data[1];

        if (data_end - data < 256 * 3)

            return AVERROR_INVALIDDATA;

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

            for (j = 0; j < 3; j++, data++)

                c[j] = (*data << 2) | (*data >> 4);

            palette[i] = 0xFF << 24 | AV_RB24(c);

        }

        seq->frame.palette_has_changed = 1;

    }

    if (flags & 2) {

        if (data_end - data < 128)

            return AVERROR_INVALIDDATA;

        init_get_bits(&gb, data, 128 * 8); data += 128;

        for (y = 0; y < 128; y += 8)

            for (x = 0; x < 256; x += 8) {

                dst = &seq->frame.data[0][y * seq->frame.linesize[0] + x];

                op = get_bits(&gb, 2);

                switch (op) {

                case 1:

                    data = seq_decode_op1(seq, data, data_end, dst);

                    break;

                case 2:

                    data = seq_decode_op2(seq, data, data_end, dst);

                    break;

                case 3:

                    data = seq_decode_op3(seq, data, data_end, dst);

                    break;

                }

                if (!data)

                    return AVERROR_INVALIDDATA;

            }

    }

    return 0;

}


QTestState *qtest_init_without_qmp_handshake(const char *extra_args)
{
    QTestState *s;
    int sock, qmpsock, i;
    gchar *socket_path;
    gchar *qmp_socket_path;
    gchar *command;
    const char *qemu_binary;
    qemu_binary = getenv("QTEST_QEMU_BINARY");
    g_assert(qemu_binary != NULL);
    s = g_malloc(sizeof(*s));
    socket_path = g_strdup_printf("/tmp/qtest-%d.sock", getpid());
    qmp_socket_path = g_strdup_printf("/tmp/qtest-%d.qmp", getpid());
    sock = init_socket(socket_path);
    qmpsock = init_socket(qmp_socket_path);
    qtest_add_abrt_handler(kill_qemu_hook_func, s);
    s->qemu_pid = fork();
    if (s->qemu_pid == 0) {
        setenv("QEMU_AUDIO_DRV", "none", true);
        command = g_strdup_printf("exec %s "
                                  "-qtest unix:%s,nowait "
                                  "-qtest-log %s "
                                  "-qmp unix:%s,nowait "
                                  "-machine accel=qtest "
                                  "-display none "
                                  "%s", qemu_binary, socket_path,
                                  getenv("QTEST_LOG") ? "/dev/fd/2" : "/dev/null",
                                  qmp_socket_path,
                                  extra_args ?: "");
        execlp("/bin/sh", "sh", "-c", command, NULL);
        exit(1);
    }
    s->fd = socket_accept(sock);
    if (s->fd >= 0) {
        s->qmp_fd = socket_accept(qmpsock);
    }
    g_free(socket_path);
    g_free(qmp_socket_path);
    g_assert(s->fd >= 0 && s->qmp_fd >= 0);
    s->rx = g_string_new("");
    for (i = 0; i < MAX_IRQ; i++) {
        s->irq_level[i] = false;
    }
    if (getenv("QTEST_STOP")) {
        kill(s->qemu_pid, SIGSTOP);
    }
    /* ask endianness of the target */
    s->big_endian = qtest_query_target_endianness(s);
    return s;
}


static inline void RENAME(yuv2packed2)(SwsContext *c, uint16_t *buf0, uint16_t *buf1, uint16_t *uvbuf0, uint16_t *uvbuf1,

			    uint8_t *dest, int dstW, int yalpha, int uvalpha, int y)

{

	int yalpha1=yalpha^4095;

	int uvalpha1=uvalpha^4095;

	int i;

#if 0 //isn't used

	if(flags&SWS_FULL_CHR_H_INT)

	{

		switch(dstFormat)

		{

#ifdef HAVE_MMX

		case PIX_FMT_RGB32:

			asm volatile(

FULL_YSCALEYUV2RGB

			"punpcklbw %%mm1, %%mm3		\n\t" // BGBGBGBG

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

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

			"punpcklwd %%mm0, %%mm3		\n\t" // BGR0BGR0

			"punpckhwd %%mm0, %%mm1		\n\t" // BGR0BGR0

			MOVNTQ(%%mm3, (%4, %%REGa, 4))

			MOVNTQ(%%mm1, 8(%4, %%REGa, 4))

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

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

			" jb 1b				\n\t"

			:: "r" (buf0), "r" (buf1), "r" (uvbuf0), "r" (uvbuf1), "r" (dest), "m" ((long)dstW),

			"m" (yalpha1), "m" (uvalpha1)

			: "%"REG_a

			);

			break;

		case PIX_FMT_BGR24:

			asm volatile(

FULL_YSCALEYUV2RGB

								// lsb ... msb

			"punpcklbw %%mm1, %%mm3		\n\t" // BGBGBGBG

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

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

			"punpcklwd %%mm0, %%mm3		\n\t" // BGR0BGR0

			"punpckhwd %%mm0, %%mm1		\n\t" // BGR0BGR0

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

			"psrlq $8, %%mm3		\n\t" // GR0BGR00

			"pand "MANGLE(bm00000111)", %%mm2\n\t" // BGR00000

			"pand "MANGLE(bm11111000)", %%mm3\n\t" // 000BGR00

			"por %%mm2, %%mm3		\n\t" // BGRBGR00

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

			"psllq $48, %%mm1		\n\t" // 000000BG

			"por %%mm1, %%mm3		\n\t" // BGRBGRBG

			"movq %%mm2, %%mm1		\n\t" // BGR0BGR0

			"psrld $16, %%mm2		\n\t" // R000R000

			"psrlq $24, %%mm1		\n\t" // 0BGR0000

			"por %%mm2, %%mm1		\n\t" // RBGRR000

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

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

#ifdef HAVE_MMX2

			//FIXME Alignment

			"movntq %%mm3, (%%"REG_b", %%"REG_a", 2)\n\t"

			"movntq %%mm1, 8(%%"REG_b", %%"REG_a", 2)\n\t"

#else

			"movd %%mm3, (%%"REG_b", %%"REG_a", 2)	\n\t"

			"psrlq $32, %%mm3		\n\t"

			"movd %%mm3, 4(%%"REG_b", %%"REG_a", 2)	\n\t"

			"movd %%mm1, 8(%%"REG_b", %%"REG_a", 2)	\n\t"

#endif

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

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

			" jb 1b				\n\t"

			:: "r" (buf0), "r" (buf1), "r" (uvbuf0), "r" (uvbuf1), "m" (dest), "m" (dstW),

			"m" (yalpha1), "m" (uvalpha1)

			: "%"REG_a, "%"REG_b

			);

			break;

		case PIX_FMT_BGR555:

			asm volatile(

FULL_YSCALEYUV2RGB

#ifdef DITHER1XBPP

			"paddusb "MANGLE(g5Dither)", %%mm1\n\t"

			"paddusb "MANGLE(r5Dither)", %%mm0\n\t"

			"paddusb "MANGLE(b5Dither)", %%mm3\n\t"

#endif

			"punpcklbw %%mm7, %%mm1		\n\t" // 0G0G0G0G

			"punpcklbw %%mm7, %%mm3		\n\t" // 0B0B0B0B

			"punpcklbw %%mm7, %%mm0		\n\t" // 0R0R0R0R

			"psrlw $3, %%mm3		\n\t"

			"psllw $2, %%mm1		\n\t"

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

			"pand "MANGLE(g15Mask)", %%mm1	\n\t"

			"pand "MANGLE(r15Mask)", %%mm0	\n\t"

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

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

			MOVNTQ(%%mm0, (%4, %%REGa, 2))

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

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

			" jb 1b				\n\t"

			:: "r" (buf0), "r" (buf1), "r" (uvbuf0), "r" (uvbuf1), "r" (dest), "m" (dstW),

			"m" (yalpha1), "m" (uvalpha1)

			: "%"REG_a

			);

			break;

		case PIX_FMT_BGR565:

			asm volatile(

FULL_YSCALEYUV2RGB

#ifdef DITHER1XBPP

			"paddusb "MANGLE(g6Dither)", %%mm1\n\t"

			"paddusb "MANGLE(r5Dither)", %%mm0\n\t"

			"paddusb "MANGLE(b5Dither)", %%mm3\n\t"

#endif

			"punpcklbw %%mm7, %%mm1		\n\t" // 0G0G0G0G

			"punpcklbw %%mm7, %%mm3		\n\t" // 0B0B0B0B

			"punpcklbw %%mm7, %%mm0		\n\t" // 0R0R0R0R

			"psrlw $3, %%mm3		\n\t"

			"psllw $3, %%mm1		\n\t"

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

			"pand "MANGLE(g16Mask)", %%mm1	\n\t"

			"pand "MANGLE(r16Mask)", %%mm0	\n\t"

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

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

			MOVNTQ(%%mm0, (%4, %%REGa, 2))

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

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

			" jb 1b				\n\t"

			:: "r" (buf0), "r" (buf1), "r" (uvbuf0), "r" (uvbuf1), "r" (dest), "m" (dstW),

			"m" (yalpha1), "m" (uvalpha1)

			: "%"REG_a

			);

		break;

#endif

		case PIX_FMT_BGR32:

#ifndef HAVE_MMX

		case PIX_FMT_RGB32:

#endif

		if(dstFormat==PIX_FMT_RGB32)

		{

			int i;

#ifdef WORDS_BIGENDIAN

			dest++;

#endif

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

				// vertical linear interpolation && yuv2rgb in a single step:

				int Y=yuvtab_2568[((buf0[i]*yalpha1+buf1[i]*yalpha)>>19)];

				int U=((uvbuf0[i]*uvalpha1+uvbuf1[i]*uvalpha)>>19);

				int V=((uvbuf0[i+2048]*uvalpha1+uvbuf1[i+2048]*uvalpha)>>19);

				dest[0]=clip_table[((Y + yuvtab_40cf[U]) >>13)];

				dest[1]=clip_table[((Y + yuvtab_1a1e[V] + yuvtab_0c92[U]) >>13)];

				dest[2]=clip_table[((Y + yuvtab_3343[V]) >>13)];

				dest+= 4;

			}

		}

		else if(dstFormat==PIX_FMT_BGR24)

		{

			int i;

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

				// vertical linear interpolation && yuv2rgb in a single step:

				int Y=yuvtab_2568[((buf0[i]*yalpha1+buf1[i]*yalpha)>>19)];

				int U=((uvbuf0[i]*uvalpha1+uvbuf1[i]*uvalpha)>>19);

				int V=((uvbuf0[i+2048]*uvalpha1+uvbuf1[i+2048]*uvalpha)>>19);

				dest[0]=clip_table[((Y + yuvtab_40cf[U]) >>13)];

				dest[1]=clip_table[((Y + yuvtab_1a1e[V] + yuvtab_0c92[U]) >>13)];

				dest[2]=clip_table[((Y + yuvtab_3343[V]) >>13)];

				dest+= 3;

			}

		}

		else if(dstFormat==PIX_FMT_BGR565)

		{

			int i;

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

				// vertical linear interpolation && yuv2rgb in a single step:

				int Y=yuvtab_2568[((buf0[i]*yalpha1+buf1[i]*yalpha)>>19)];

				int U=((uvbuf0[i]*uvalpha1+uvbuf1[i]*uvalpha)>>19);

				int V=((uvbuf0[i+2048]*uvalpha1+uvbuf1[i+2048]*uvalpha)>>19);

				((uint16_t*)dest)[i] =

					clip_table16b[(Y + yuvtab_40cf[U]) >>13] |

					clip_table16g[(Y + yuvtab_1a1e[V] + yuvtab_0c92[U]) >>13] |

					clip_table16r[(Y + yuvtab_3343[V]) >>13];

			}

		}

		else if(dstFormat==PIX_FMT_BGR555)

		{

			int i;

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

				// vertical linear interpolation && yuv2rgb in a single step:

				int Y=yuvtab_2568[((buf0[i]*yalpha1+buf1[i]*yalpha)>>19)];

				int U=((uvbuf0[i]*uvalpha1+uvbuf1[i]*uvalpha)>>19);

				int V=((uvbuf0[i+2048]*uvalpha1+uvbuf1[i+2048]*uvalpha)>>19);

				((uint16_t*)dest)[i] =

					clip_table15b[(Y + yuvtab_40cf[U]) >>13] |

					clip_table15g[(Y + yuvtab_1a1e[V] + yuvtab_0c92[U]) >>13] |

					clip_table15r[(Y + yuvtab_3343[V]) >>13];

			}

		}

	}//FULL_UV_IPOL

	else

	{

#endif // if 0

#ifdef HAVE_MMX

	switch(c->dstFormat)

	{

//Note 8280 == DSTW_OFFSET but the preprocessor can't handle that there :(

	case PIX_FMT_RGB32:

			asm volatile(

				"mov %%"REG_b", "ESP_OFFSET"(%5)	\n\t"

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

                                "push %%"REG_BP"                        \n\t"

				YSCALEYUV2RGB(%%REGBP, %5)

				WRITEBGR32(%%REGb, 8280(%5), %%REGBP)

                                "pop %%"REG_BP"                         \n\t"

				"mov "ESP_OFFSET"(%5), %%"REG_b"	\n\t"

			:: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

			"a" (&c->redDither)

			);

			return;

	case PIX_FMT_BGR24:

			asm volatile(

				"mov %%"REG_b", "ESP_OFFSET"(%5)	\n\t"

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

                                "push %%"REG_BP"                        \n\t"

				YSCALEYUV2RGB(%%REGBP, %5)

				WRITEBGR24(%%REGb, 8280(%5), %%REGBP)

                                "pop %%"REG_BP"                         \n\t"

				"mov "ESP_OFFSET"(%5), %%"REG_b"	\n\t"

			:: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

			"a" (&c->redDither)

			);

			return;

	case PIX_FMT_BGR555:

			asm volatile(

				"mov %%"REG_b", "ESP_OFFSET"(%5)	\n\t"

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

                                "push %%"REG_BP"                        \n\t"

				YSCALEYUV2RGB(%%REGBP, %5)

		/* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

				"paddusb "MANGLE(b5Dither)", %%mm2\n\t"

				"paddusb "MANGLE(g5Dither)", %%mm4\n\t"

				"paddusb "MANGLE(r5Dither)", %%mm5\n\t"

#endif

				WRITEBGR15(%%REGb, 8280(%5), %%REGBP)

                                "pop %%"REG_BP"                         \n\t"

				"mov "ESP_OFFSET"(%5), %%"REG_b"	\n\t"

			:: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

			"a" (&c->redDither)

			);

			return;

	case PIX_FMT_BGR565:

			asm volatile(

				"mov %%"REG_b", "ESP_OFFSET"(%5)	\n\t"

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

                                "push %%"REG_BP"                        \n\t"

				YSCALEYUV2RGB(%%REGBP, %5)

		/* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

				"paddusb "MANGLE(b5Dither)", %%mm2\n\t"

				"paddusb "MANGLE(g6Dither)", %%mm4\n\t"

				"paddusb "MANGLE(r5Dither)", %%mm5\n\t"

#endif

				WRITEBGR16(%%REGb, 8280(%5), %%REGBP)

                                "pop %%"REG_BP"                         \n\t"

				"mov "ESP_OFFSET"(%5), %%"REG_b"	\n\t"

			:: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

			"a" (&c->redDither)

			);

			return;

	case PIX_FMT_YUYV422:

			asm volatile(

				"mov %%"REG_b", "ESP_OFFSET"(%5)	\n\t"

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

                                "push %%"REG_BP"                        \n\t"

				YSCALEYUV2PACKED(%%REGBP, %5)

				WRITEYUY2(%%REGb, 8280(%5), %%REGBP)

                                "pop %%"REG_BP"                         \n\t"

				"mov "ESP_OFFSET"(%5), %%"REG_b"	\n\t"

			:: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

			"a" (&c->redDither)

			);

			return;

	default: break;

	}

#endif //HAVE_MMX

YSCALE_YUV_2_ANYRGB_C(YSCALE_YUV_2_RGB2_C, YSCALE_YUV_2_PACKED2_C)

}


static int http_parse_request(HTTPContext *c)

{

    const char *p;

    char *p1;

    enum RedirType redir_type;

    char cmd[32];

    char info[1024], filename[1024];

    char url[1024], *q;

    char protocol[32];

    char msg[1024];

    const char *mime_type;

    FFServerStream *stream;

    int i;

    char ratebuf[32];

    const char *useragent = 0;

    p = c->buffer;

    get_word(cmd, sizeof(cmd), &p);

    av_strlcpy(c->method, cmd, sizeof(c->method));

    if (!strcmp(cmd, "GET"))

        c->post = 0;

    else if (!strcmp(cmd, "POST"))

        c->post = 1;

    else

        return -1;

    get_word(url, sizeof(url), &p);

    av_strlcpy(c->url, url, sizeof(c->url));

    get_word(protocol, sizeof(protocol), (const char **)&p);

    if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))

        return -1;

    av_strlcpy(c->protocol, protocol, sizeof(c->protocol));

    if (config.debug)

        http_log("%s - - New connection: %s %s\n", inet_ntoa(c->from_addr.sin_addr), cmd, url);

    /* find the filename and the optional info string in the request */

    p1 = strchr(url, '?');

    if (p1) {

        av_strlcpy(info, p1, sizeof(info));

        *p1 = '\0';

    } else

        info[0] = '\0';

    av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);

    for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {

        if (av_strncasecmp(p, "User-Agent:", 11) == 0) {

            useragent = p + 11;

            if (*useragent && *useragent != '\n' && av_isspace(*useragent))

                useragent++;

            break;

        }

        p = strchr(p, '\n');

        if (!p)

            break;

        p++;

    }

    redir_type = REDIR_NONE;

    if (av_match_ext(filename, "asx")) {

        redir_type = REDIR_ASX;

        filename[strlen(filename)-1] = 'f';

    } else if (av_match_ext(filename, "asf") &&

        (!useragent || av_strncasecmp(useragent, "NSPlayer", 8) != 0)) {

        /* if this isn't WMP or lookalike, return the redirector file */

        redir_type = REDIR_ASF;

    } else if (av_match_ext(filename, "rpm,ram")) {

        redir_type = REDIR_RAM;

        strcpy(filename + strlen(filename)-2, "m");

    } else if (av_match_ext(filename, "rtsp")) {

        redir_type = REDIR_RTSP;

        compute_real_filename(filename, sizeof(filename) - 1);

    } else if (av_match_ext(filename, "sdp")) {

        redir_type = REDIR_SDP;

        compute_real_filename(filename, sizeof(filename) - 1);

    }

    // "redirect" / request to index.html

    if (!strlen(filename))

        av_strlcpy(filename, "index.html", sizeof(filename) - 1);

    stream = config.first_stream;

    while (stream) {

        if (!strcmp(stream->filename, filename) && validate_acl(stream, c))

            break;

        stream = stream->next;

    }

    if (!stream) {

        snprintf(msg, sizeof(msg), "File '%s' not found", url);

        http_log("File '%s' not found\n", url);

        goto send_error;

    }

    c->stream = stream;

    memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));

    memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));

    if (stream->stream_type == STREAM_TYPE_REDIRECT) {

        c->http_error = 301;

        q = c->buffer;

        snprintf(q, c->buffer_size,

                      "HTTP/1.0 301 Moved\r\n"

                      "Location: %s\r\n"

                      "Content-type: text/html\r\n"

                      "\r\n"

                      "<title>Moved</title>\r\n"

                      "You should be redirected.\r\n"

                      "\r\n", stream->feed_filename, stream->feed_filename);

        q += strlen(q);

        /* prepare output buffer */

        c->buffer_ptr = c->buffer;

        c->buffer_end = q;

        c->state = HTTPSTATE_SEND_HEADER;

        return 0;

    }

    /* If this is WMP, get the rate information */

    if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {

        if (modify_current_stream(c, ratebuf)) {

            for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {

                if (c->switch_feed_streams[i] >= 0)

                    c->switch_feed_streams[i] = -1;

            }

        }

    }

    if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)

        current_bandwidth += stream->bandwidth;

    /* If already streaming this feed, do not let start another feeder. */

    if (stream->feed_opened) {

        snprintf(msg, sizeof(msg), "This feed is already being received.");

        http_log("Feed '%s' already being received\n", stream->feed_filename);

        goto send_error;

    }

    if (c->post == 0 && config.max_bandwidth < current_bandwidth) {

        c->http_error = 503;

        q = c->buffer;

        snprintf(q, c->buffer_size,

                      "HTTP/1.0 503 Server too busy\r\n"

                      "Content-type: text/html\r\n"

                      "\r\n"

                      "<title>Too busy</title>\r\n"

                      "
The server is too busy to serve your request at this time.
\r\n"

                      "
The bandwidth being served (including your stream) is %"PRIu64"kbit/sec, "

                      "and this exceeds the limit of %"PRIu64"kbit/sec.
\r\n"

                      "\r\n", current_bandwidth, config.max_bandwidth);

        q += strlen(q);

        /* prepare output buffer */

        c->buffer_ptr = c->buffer;

        c->buffer_end = q;

        c->state = HTTPSTATE_SEND_HEADER;

        return 0;

    }

    if (redir_type != REDIR_NONE) {

        const char *hostinfo = 0;

        for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {

            if (av_strncasecmp(p, "Host:", 5) == 0) {

                hostinfo = p + 5;

                break;

            }

            p = strchr(p, '\n');

            if (!p)

                break;

            p++;

        }

        if (hostinfo) {

            char *eoh;

            char hostbuf[260];

            while (av_isspace(*hostinfo))

                hostinfo++;

            eoh = strchr(hostinfo, '\n');

            if (eoh) {

                if (eoh[-1] == '\r')

                    eoh--;

                if (eoh - hostinfo < sizeof(hostbuf) - 1) {

                    memcpy(hostbuf, hostinfo, eoh - hostinfo);

                    hostbuf[eoh - hostinfo] = 0;

                    c->http_error = 200;

                    q = c->buffer;

                    switch(redir_type) {

                    case REDIR_ASX:

                        snprintf(q, c->buffer_size,

                                      "HTTP/1.0 200 ASX Follows\r\n"

                                      "Content-type: video/x-ms-asf\r\n"

                                      "\r\n"

                                      "<ASX Version=\"3\">\r\n"

                                      //"\r\n"

                                      "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"

                                      "</ASX>\r\n", hostbuf, filename, info);

                        q += strlen(q);

                        break;

                    case REDIR_RAM:

                        snprintf(q, c->buffer_size,

                                      "HTTP/1.0 200 RAM Follows\r\n"

                                      "Content-type: audio/x-pn-realaudio\r\n"

                                      "\r\n"

                                      "# Autogenerated by ffserver\r\n"

                                      "http://%s/%s%s\r\n", hostbuf, filename, info);

                        q += strlen(q);

                        break;

                    case REDIR_ASF:

                        snprintf(q, c->buffer_size,

                                      "HTTP/1.0 200 ASF Redirect follows\r\n"

                                      "Content-type: video/x-ms-asf\r\n"

                                      "\r\n"

                                      "[Reference]\r\n"

                                      "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);

                        q += strlen(q);

                        break;

                    case REDIR_RTSP:

                        {

                            char hostname[256], *p;

                            /* extract only hostname */

                            av_strlcpy(hostname, hostbuf, sizeof(hostname));

                            p = strrchr(hostname, ':');

                            if (p)

                                *p = '\0';

                            snprintf(q, c->buffer_size,

                                          "HTTP/1.0 200 RTSP Redirect follows\r\n"

                                          /* XXX: incorrect MIME type ? */

                                          "Content-type: application/x-rtsp\r\n"

                                          "\r\n"

                                          "rtsp://%s:%d/%s\r\n", hostname, ntohs(config.rtsp_addr.sin_port), filename);

                            q += strlen(q);

                        }

                        break;

                    case REDIR_SDP:

                        {

                            uint8_t *sdp_data;

                            int sdp_data_size;

                            socklen_t len;

                            struct sockaddr_in my_addr;

                            snprintf(q, c->buffer_size,

                                          "HTTP/1.0 200 OK\r\n"

                                          "Content-type: application/sdp\r\n"

                                          "\r\n");

                            q += strlen(q);

                            len = sizeof(my_addr);

                            /* XXX: Should probably fail? */

                            if (getsockname(c->fd, (struct sockaddr *)&my_addr, &len))

                                http_log("getsockname() failed\n");

                            /* XXX: should use a dynamic buffer */

                            sdp_data_size = prepare_sdp_description(stream,

                                                                    &sdp_data,

                                                                    my_addr.sin_addr);

                            if (sdp_data_size > 0) {

                                memcpy(q, sdp_data, sdp_data_size);

                                q += sdp_data_size;

                                *q = '\0';

                                av_free(sdp_data);

                            }

                        }

                        break;

                    default:

                        abort();

                        break;

                    }

                    /* prepare output buffer */

                    c->buffer_ptr = c->buffer;

                    c->buffer_end = q;

                    c->state = HTTPSTATE_SEND_HEADER;

                    return 0;

                }

            }

        }

        snprintf(msg, sizeof(msg), "ASX/RAM file not handled");

        goto send_error;

    }

    stream->conns_served++;

    /* XXX: add there authenticate and IP match */

    if (c->post) {

        /* if post, it means a feed is being sent */

        if (!stream->is_feed) {

            /* However it might be a status report from WMP! Let us log the

             * data as it might come handy one day. */

            const char *logline = 0;

            int client_id = 0;

            for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {

                if (av_strncasecmp(p, "Pragma: log-line=", 17) == 0) {

                    logline = p;

                    break;

                }

                if (av_strncasecmp(p, "Pragma: client-id=", 18) == 0)

                    client_id = strtol(p + 18, 0, 10);

                p = strchr(p, '\n');

                if (!p)

                    break;

                p++;

            }

            if (logline) {

                char *eol = strchr(logline, '\n');

                logline += 17;

                if (eol) {

                    if (eol[-1] == '\r')

                        eol--;

                    http_log("%.*s\n", (int) (eol - logline), logline);

                    c->suppress_log = 1;

                }

            }

#ifdef DEBUG

            http_log("\nGot request:\n%s\n", c->buffer);

#endif

            if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {

                HTTPContext *wmpc;

                /* Now we have to find the client_id */

                for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {

                    if (wmpc->wmp_client_id == client_id)

                        break;

                }

                if (wmpc && modify_current_stream(wmpc, ratebuf))

                    wmpc->switch_pending = 1;

            }

            snprintf(msg, sizeof(msg), "POST command not handled");

            c->stream = 0;

            goto send_error;

        }

        if (http_start_receive_data(c) < 0) {

            snprintf(msg, sizeof(msg), "could not open feed");

            goto send_error;

        }

        c->http_error = 0;

        c->state = HTTPSTATE_RECEIVE_DATA;

        return 0;

    }

#ifdef DEBUG

    if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)

        http_log("\nGot request:\n%s\n", c->buffer);

#endif

    if (c->stream->stream_type == STREAM_TYPE_STATUS)

        goto send_status;

    /* open input stream */

    if (open_input_stream(c, info) < 0) {

        snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);

        goto send_error;

    }

    /* prepare HTTP header */

    c->buffer[0] = 0;

    av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.0 200 OK\r\n");

    mime_type = c->stream->fmt->mime_type;

    if (!mime_type)

        mime_type = "application/x-octet-stream";

    av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n");

    /* for asf, we need extra headers */

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

        /* Need to allocate a client id */

        c->wmp_client_id = av_lfg_get(&random_state);

        av_strlcatf(c->buffer, c->buffer_size, "Server: Cougar 4.1.0.3923\r\nCache-Control: no-cache\r\nPragma: client-id=%d\r\nPragma: features=\"broadcast\"\r\n", c->wmp_client_id);

    }

    av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type);

    av_strlcatf(c->buffer, c->buffer_size, "\r\n");

    q = c->buffer + strlen(c->buffer);

    /* prepare output buffer */

    c->http_error = 0;

    c->buffer_ptr = c->buffer;

    c->buffer_end = q;

    c->state = HTTPSTATE_SEND_HEADER;

    return 0;

 send_error:

    c->http_error = 404;

    q = c->buffer;

    htmlstrip(msg);

    snprintf(q, c->buffer_size,

                  "HTTP/1.0 404 Not Found\r\n"

                  "Content-type: text/html\r\n"

                  "\r\n"

                  "\n"

                  "<title>404 Not Found</title>\n"

                  "%s\n"

                  "\n", msg);

    q += strlen(q);

    /* prepare output buffer */

    c->buffer_ptr = c->buffer;

    c->buffer_end = q;

    c->state = HTTPSTATE_SEND_HEADER;

    return 0;

 send_status:

    compute_status(c);

    c->http_error = 200; /* horrible : we use this value to avoid

                            going to the send data state */

    c->state = HTTPSTATE_SEND_HEADER;

    return 0;

}


static int get_bitmap(QEMUFile *f, void *pv, size_t size)

{

    unsigned long *bmp = pv;

    int i, idx = 0;

    for (i = 0; i < BITS_TO_U64S(size); i++) {

        uint64_t w = qemu_get_be64(f);

        bmp[idx++] = w;

        if (sizeof(unsigned long) == 4 && idx < BITS_TO_LONGS(size)) {

            bmp[idx++] = w >> 32;

        }

    }

    return 0;

}


long do_sigreturn(CPUM68KState *env)

{

    struct target_sigframe *frame;

    abi_ulong frame_addr = env->aregs[7] - 4;

    target_sigset_t target_set;

    sigset_t set;

    int d0, i;

    if (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1))

        goto badframe;

    /* set blocked signals */

    if (__get_user(target_set.sig[0], &frame->sc.sc_mask))

        goto badframe;

    for(i = 1; i < TARGET_NSIG_WORDS; i++) {

        if (__get_user(target_set.sig[i], &frame->extramask[i - 1]))

            goto badframe;

    }

    target_to_host_sigset_internal(&set, &target_set);

    do_sigprocmask(SIG_SETMASK, &set, NULL);

    /* restore registers */

    if (restore_sigcontext(env, &frame->sc, &d0))

        goto badframe;

    unlock_user_struct(frame, frame_addr, 0);

    return d0;

badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV);

    return 0;

}


static int vscsi_send_adapter_info(VSCSIState *s, vscsi_req *req)

{

    struct viosrp_adapter_info *sinfo;

    struct mad_adapter_info_data info;

    int rc;

    sinfo = &req->iu.mad.adapter_info;

#if 0 /* What for ? */

    rc = spapr_tce_dma_read(&s->vdev, be64_to_cpu(sinfo->buffer),

                            &info, be16_to_cpu(sinfo->common.length));

    if (rc) {

        fprintf(stderr, "vscsi_send_adapter_info: DMA read failure !\n");

    }

#endif

    memset(&info, 0, sizeof(info));

    strcpy(info.srp_version, SRP_VERSION);

    strncpy(info.partition_name, "qemu", sizeof("qemu"));

    info.partition_number = cpu_to_be32(0);

    info.mad_version = cpu_to_be32(1);

    info.os_type = cpu_to_be32(2);

    info.port_max_txu[0] = cpu_to_be32(VSCSI_MAX_SECTORS << 9);

    rc = spapr_tce_dma_write(&s->vdev, be64_to_cpu(sinfo->buffer),

                             &info, be16_to_cpu(sinfo->common.length));

    if (rc)  {

        fprintf(stderr, "vscsi_send_adapter_info: DMA write failure !\n");

    }

    sinfo->common.status = rc ? cpu_to_be32(1) : 0;

    return vscsi_send_iu(s, req, sizeof(*sinfo), VIOSRP_MAD_FORMAT);

}


static void qmp_input_type_null(Visitor *v, const char *name, Error **errp)
{
    QmpInputVisitor *qiv = to_qiv(v);
    QObject *qobj = qmp_input_get_object(qiv, name, true);
    if (qobject_type(qobj) != QTYPE_QNULL) {
        error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name ? name : "null",
                   "null");


static void gen_spr_970_lpar(CPUPPCState *env)

{

    /* Logical partitionning */

    /* PPC970: HID4 is effectively the LPCR */

    spr_register(env, SPR_970_HID4, "HID4",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

}


static inline void *alloc_code_gen_buffer(void)

{

    void *buf = static_code_gen_buffer;

#ifdef __mips__

    if (cross_256mb(buf, tcg_ctx.code_gen_buffer_size)) {

        buf = split_cross_256mb(buf, tcg_ctx.code_gen_buffer_size);

    }

#endif

    map_exec(buf, tcg_ctx.code_gen_buffer_size);

    return buf;

}


static void intel_hda_update_int_sts(IntelHDAState *d)

{

    uint32_t sts = 0;

    uint32_t i;

    /* update controller status */

    if (d->rirb_sts & ICH6_RBSTS_IRQ) {

        sts |= (1 << 30);

    }

    if (d->rirb_sts & ICH6_RBSTS_OVERRUN) {

        sts |= (1 << 30);

    }

    if (d->state_sts & d->wake_en) {

        sts |= (1 << 30);

    }

    /* update stream status */

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

        /* buffer completion interrupt */

        if (d->st[i].ctl & (1 << 26)) {

            sts |= (1 << i);

        }

    }

    /* update global status */

    if (sts & d->int_ctl) {

        sts |= (1 << 31);

    }

    d->int_sts = sts;

}


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

{

    int saved_vm_running  = vm_running;

    const char *name = qdict_get_str(qdict, "name");

    vm_stop(0);

    if (load_vmstate(name) >= 0 && saved_vm_running)

        vm_start();

}


static av_always_inline void mc_chroma_scaled(VP9Context *s, vp9_scaled_mc_func smc,

                                              vp9_mc_func (*mc)[2],

                                              uint8_t *dst_u, uint8_t *dst_v,

                                              ptrdiff_t dst_stride,

                                              const uint8_t *ref_u, ptrdiff_t src_stride_u,

                                              const uint8_t *ref_v, ptrdiff_t src_stride_v,

                                              ThreadFrame *ref_frame,

                                              ptrdiff_t y, ptrdiff_t x, const VP56mv *in_mv,

                                              int px, int py, int pw, int ph,

                                              int bw, int bh, int w, int h, int bytesperpixel,

                                              const uint16_t *scale, const uint8_t *step)

{

    if (s->s.frames[CUR_FRAME].tf.f->width == ref_frame->f->width &&

        s->s.frames[CUR_FRAME].tf.f->height == ref_frame->f->height) {

        mc_chroma_unscaled(s, mc, dst_u, dst_v, dst_stride, ref_u, src_stride_u,

                           ref_v, src_stride_v, ref_frame,

                           y, x, in_mv, bw, bh, w, h, bytesperpixel);

    } else {

    int mx, my;

    int refbw_m1, refbh_m1;

    int th;

    VP56mv mv;

    if (s->ss_h) {

        // BUG https://code.google.com/p/webm/issues/detail?id=820

        mv.x = av_clip(in_mv->x, -(x + pw - px + 4) * 16, (s->cols * 4 - x + px + 3) * 16);

        mx = scale_mv(mv.x, 0) + (scale_mv(x * 16, 0) & ~15) + (scale_mv(x * 32, 0) & 15);

    } else {

        mv.x = av_clip(in_mv->x, -(x + pw - px + 4) * 8, (s->cols * 8 - x + px + 3) * 8);

        mx = scale_mv(mv.x * 2, 0) + scale_mv(x * 16, 0);

    }

    if (s->ss_v) {

        // BUG https://code.google.com/p/webm/issues/detail?id=820

        mv.y = av_clip(in_mv->y, -(y + ph - py + 4) * 16, (s->rows * 4 - y + py + 3) * 16);

        my = scale_mv(mv.y, 1) + (scale_mv(y * 16, 1) & ~15) + (scale_mv(y * 32, 1) & 15);

    } else {

        mv.y = av_clip(in_mv->y, -(y + ph - py + 4) * 8, (s->rows * 8 - y + py + 3) * 8);

        my = scale_mv(mv.y * 2, 1) + scale_mv(y * 16, 1);

    }

#undef scale_mv

    y = my >> 4;

    x = mx >> 4;

    ref_u += y * src_stride_u + x * bytesperpixel;

    ref_v += y * src_stride_v + x * bytesperpixel;

    mx &= 15;

    my &= 15;

    refbw_m1 = ((bw - 1) * step[0] + mx) >> 4;

    refbh_m1 = ((bh - 1) * step[1] + my) >> 4;

    // FIXME bilinear filter only needs 0/1 pixels, not 3/4

    // we use +7 because the last 7 pixels of each sbrow can be changed in

    // the longest loopfilter of the next sbrow

    th = (y + refbh_m1 + 4 + 7) >> (6 - s->ss_v);

    ff_thread_await_progress(ref_frame, FFMAX(th, 0), 0);

    if (x < 3 || y < 3 || x + 4 >= w - refbw_m1 || y + 4 >= h - refbh_m1) {

        s->vdsp.emulated_edge_mc(s->edge_emu_buffer,

                                 ref_u - 3 * src_stride_u - 3 * bytesperpixel,

                                 288, src_stride_u,

                                 refbw_m1 + 8, refbh_m1 + 8,

                                 x - 3, y - 3, w, h);

        ref_u = s->edge_emu_buffer + 3 * 288 + 3 * bytesperpixel;

        smc(dst_u, dst_stride, ref_u, 288, bh, mx, my, step[0], step[1]);

        s->vdsp.emulated_edge_mc(s->edge_emu_buffer,

                                 ref_v - 3 * src_stride_v - 3 * bytesperpixel,

                                 288, src_stride_v,

                                 refbw_m1 + 8, refbh_m1 + 8,

                                 x - 3, y - 3, w, h);

        ref_v = s->edge_emu_buffer + 3 * 288 + 3 * bytesperpixel;

        smc(dst_v, dst_stride, ref_v, 288, bh, mx, my, step[0], step[1]);

    } else {

        smc(dst_u, dst_stride, ref_u, src_stride_u, bh, mx, my, step[0], step[1]);

        smc(dst_v, dst_stride, ref_v, src_stride_v, bh, mx, my, step[0], step[1]);

    }

    }

}


static void gen_add_carry(TCGv dest, TCGv t0, TCGv t1)

{

    TCGv tmp;

    tcg_gen_add_i32(dest, t0, t1);

    tmp = load_cpu_field(CF);

    tcg_gen_add_i32(dest, dest, tmp);

    dead_tmp(tmp);

}


static int compat_decode(AVCodecContext *avctx, AVFrame *frame,

                         int *got_frame, AVPacket *pkt)

{

    AVCodecInternal *avci = avctx->internal;

    int ret;

    av_assert0(avci->compat_decode_consumed == 0);

    *got_frame = 0;

    avci->compat_decode = 1;

    if (avci->compat_decode_partial_size > 0 &&

        avci->compat_decode_partial_size != pkt->size) {

        av_log(avctx, AV_LOG_ERROR,

               "Got unexpected packet size after a partial decode\n");

        ret = AVERROR(EINVAL);

        goto finish;

    }

    if (!avci->compat_decode_partial_size) {

        ret = avcodec_send_packet(avctx, pkt);

        if (ret == AVERROR_EOF)

            ret = 0;

        else if (ret == AVERROR(EAGAIN)) {

            /* we fully drain all the output in each decode call, so this should not

             * ever happen */

            ret = AVERROR_BUG;

            goto finish;

        } else if (ret < 0)

            goto finish;

    }

    while (ret >= 0) {

        ret = avcodec_receive_frame(avctx, frame);

        if (ret < 0) {

            if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)

                ret = 0;

            goto finish;

        }

        if (frame != avci->compat_decode_frame) {

            if (!avctx->refcounted_frames) {

                ret = unrefcount_frame(avci, frame);

                if (ret < 0)

                    goto finish;

            }

            *got_frame = 1;

            frame = avci->compat_decode_frame;

        } else {

            if (!avci->compat_decode_warned) {

                av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "

                       "API cannot return all the frames for this decoder. "

                       "Some frames will be dropped. Update your code to the "

                       "new decoding API to fix this.\n");

                avci->compat_decode_warned = 1;

            }

        }

        if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))

            break;

    }

finish:

    if (ret == 0) {

        /* if there are any bsfs then assume full packet is always consumed */

        if (avctx->codec->bsfs)

            ret = pkt->size;

        else

            ret = FFMIN(avci->compat_decode_consumed, pkt->size);

    }

    avci->compat_decode_consumed = 0;

    avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;

    return ret;

}


static void gen_wsr_debugcause(DisasContext *dc, uint32_t sr, TCGv_i32 v)

{

}


static int jp2_find_codestream(Jpeg2000DecoderContext *s)

{

    uint32_t atom_size, atom, atom_end;

    int search_range = 10;

    while (search_range

           &&

           bytestream2_get_bytes_left(&s->g) >= 8) {

        atom_size = bytestream2_get_be32u(&s->g);

        atom      = bytestream2_get_be32u(&s->g);

        atom_end  = bytestream2_tell(&s->g) + atom_size - 8;

        if (atom == JP2_CODESTREAM)

            return 1;

        if (bytestream2_get_bytes_left(&s->g) < atom_size || atom_end < atom_size)

            return 0;

        if (atom == JP2_HEADER &&

                   atom_size >= 16) {

            uint32_t atom2_size, atom2, atom2_end;

            do {

                atom2_size = bytestream2_get_be32u(&s->g);

                atom2      = bytestream2_get_be32u(&s->g);

                atom2_end  = bytestream2_tell(&s->g) + atom2_size - 8;

                if (atom2_size < 8 || atom2_end > atom_end || atom2_end < atom2_size)

                    break;

                atom2_size -= 8;

                if (atom2 == JP2_CODESTREAM) {

                    return 1;

                } else if (atom2 == MKBETAG('c','o','l','r') && atom2_size >= 7) {

                    int method = bytestream2_get_byteu(&s->g);

                    bytestream2_skipu(&s->g, 2);

                    if (method == 1) {

                        s->colour_space = bytestream2_get_be32u(&s->g);

                } else if (atom2 == MKBETAG('p','c','l','r') && atom2_size >= 6) {

                    int i, size, colour_count, colour_channels, colour_depth[3];

                    uint32_t r, g, b;

                    colour_count = bytestream2_get_be16u(&s->g);

                    colour_channels = bytestream2_get_byteu(&s->g);

                    // FIXME: Do not ignore channel_sign

                    colour_depth[0] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;

                    colour_depth[1] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;

                    colour_depth[2] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;

                    size = (colour_depth[0] + 7 >> 3) * colour_count +

                           (colour_depth[1] + 7 >> 3) * colour_count +

                           (colour_depth[2] + 7 >> 3) * colour_count;

                    if (colour_count > 256   ||

                        colour_channels != 3 ||

                        colour_depth[0] > 16 ||

                        colour_depth[1] > 16 ||

                        colour_depth[2] > 16 ||

                        atom2_size < size) {

                        avpriv_request_sample(s->avctx, "Unknown palette");

                    s->pal8 = 1;

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

                        if (colour_depth[0] <= 8) {

                            r = bytestream2_get_byteu(&s->g) << 8 - colour_depth[0];

                            r |= r >> colour_depth[0];

                        } else {

                            r = bytestream2_get_be16u(&s->g) >> colour_depth[0] - 8;

                        if (colour_depth[1] <= 8) {

                            g = bytestream2_get_byteu(&s->g) << 8 - colour_depth[1];

                            r |= r >> colour_depth[1];

                        } else {

                            g = bytestream2_get_be16u(&s->g) >> colour_depth[1] - 8;

                        if (colour_depth[2] <= 8) {

                            b = bytestream2_get_byteu(&s->g) << 8 - colour_depth[2];

                            r |= r >> colour_depth[2];

                        } else {

                            b = bytestream2_get_be16u(&s->g) >> colour_depth[2] - 8;

                        s->palette[i] = 0xffu << 24 | r << 16 | g << 8 | b;

                } else if (atom2 == MKBETAG('c','d','e','f') && atom2_size >= 2) {

                    int n = bytestream2_get_be16u(&s->g);

                    for (; n>0; n--) {

                        int cn   = bytestream2_get_be16(&s->g);

                        int av_unused typ  = bytestream2_get_be16(&s->g);

                        int asoc = bytestream2_get_be16(&s->g);

                        if (cn < 4 && asoc < 4)

                            s->cdef[cn] = asoc;

                } else if (atom2 == MKBETAG('r','e','s',' ') && atom2_size >= 18) {

                    int64_t vnum, vden, hnum, hden, vexp, hexp;

                    uint32_t resx;

                    bytestream2_skip(&s->g, 4);

                    resx = bytestream2_get_be32u(&s->g);

                    if (resx != MKBETAG('r','e','s','c') && resx != MKBETAG('r','e','s','d')) {

                    vnum = bytestream2_get_be16u(&s->g);

                    vden = bytestream2_get_be16u(&s->g);

                    hnum = bytestream2_get_be16u(&s->g);

                    hden = bytestream2_get_be16u(&s->g);

                    vexp = bytestream2_get_byteu(&s->g);

                    hexp = bytestream2_get_byteu(&s->g);

                    if (vexp > hexp) {

                        vexp -= hexp;

                        hexp = 0;

                    } else {

                        hexp -= vexp;

                        vexp = 0;

                    if (   INT64_MAX / (hnum * vden) > pow(10, hexp)

                        && INT64_MAX / (vnum * hden) > pow(10, vexp))

                        av_reduce(&s->sar.den, &s->sar.num,

                                  hnum * vden * pow(10, hexp),

                                  vnum * hden * pow(10, vexp),

                                  INT32_MAX);

            } while (atom_end - atom2_end >= 8);

        } else {

            search_range--;

        bytestream2_seek(&s->g, atom_end, SEEK_SET);

    return 0;


static void i440fx_realize(PCIDevice *dev, Error **errp)

{

    dev->config[I440FX_SMRAM] = 0x02;

    if (object_property_get_bool(qdev_get_machine(), "iommu", NULL)) {

        error_report("warning: i440fx doesn't support emulated iommu");

    }

}


static inline unsigned char gif_clut_index(uint8_t r, uint8_t g, uint8_t b)

{

    return ((((r)/47)%6)*6*6+(((g)/47)%6)*6+(((b)/47)%6));

}


static void coroutine_fn bdrv_co_do_rw(void *opaque)

{

    BlockAIOCBCoroutine *acb = opaque;

    BlockDriverState *bs = acb->common.bs;

    if (!acb->is_write) {

        acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,

            acb->req.nb_sectors, acb->req.qiov, acb->req.flags);

    } else {

        acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,

            acb->req.nb_sectors, acb->req.qiov, acb->req.flags);

    }

    acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);

    qemu_bh_schedule(acb->bh);

}


static int xen_add_to_physmap(XenIOState *state,

                              hwaddr start_addr,

                              ram_addr_t size,

                              MemoryRegion *mr,

                              hwaddr offset_within_region)

{

    unsigned long i = 0;

    int rc = 0;

    XenPhysmap *physmap = NULL;

    hwaddr pfn, start_gpfn;

    hwaddr phys_offset = memory_region_get_ram_addr(mr);

    char path[80], value[17];

    const char *mr_name;

    if (get_physmapping(state, start_addr, size)) {

        return 0;

    }

    if (size <= 0) {

        return -1;

    }

    /* Xen can only handle a single dirty log region for now and we want

     * the linear framebuffer to be that region.

     * Avoid tracking any regions that is not videoram and avoid tracking

     * the legacy vga region. */

    if (mr == framebuffer && start_addr > 0xbffff) {

        goto go_physmap;

    }

    return -1;

go_physmap:

    DPRINTF("mapping vram to %"HWADDR_PRIx" - %"HWADDR_PRIx"\n",

            start_addr, start_addr + size);

    pfn = phys_offset >> TARGET_PAGE_BITS;

    start_gpfn = start_addr >> TARGET_PAGE_BITS;

    for (i = 0; i < size >> TARGET_PAGE_BITS; i++) {

        unsigned long idx = pfn + i;

        xen_pfn_t gpfn = start_gpfn + i;

        rc = xc_domain_add_to_physmap(xen_xc, xen_domid, XENMAPSPACE_gmfn, idx, gpfn);

        if (rc) {

            DPRINTF("add_to_physmap MFN %"PRI_xen_pfn" to PFN %"

                    PRI_xen_pfn" failed: %d (errno: %d)\n", idx, gpfn, rc, errno);

            return -rc;

        }

    }

    mr_name = memory_region_name(mr);

    physmap = g_malloc(sizeof (XenPhysmap));

    physmap->start_addr = start_addr;

    physmap->size = size;

    physmap->name = mr_name;

    physmap->phys_offset = phys_offset;

    QLIST_INSERT_HEAD(&state->physmap, physmap, list);

    xc_domain_pin_memory_cacheattr(xen_xc, xen_domid,

                                   start_addr >> TARGET_PAGE_BITS,

                                   (start_addr + size - 1) >> TARGET_PAGE_BITS,

                                   XEN_DOMCTL_MEM_CACHEATTR_WB);

    snprintf(path, sizeof(path),

            "/local/domain/0/device-model/%d/physmap/%"PRIx64"/start_addr",

            xen_domid, (uint64_t)phys_offset);

    snprintf(value, sizeof(value), "%"PRIx64, (uint64_t)start_addr);

    if (!xs_write(state->xenstore, 0, path, value, strlen(value))) {

        return -1;

    }

    snprintf(path, sizeof(path),

            "/local/domain/0/device-model/%d/physmap/%"PRIx64"/size",

            xen_domid, (uint64_t)phys_offset);

    snprintf(value, sizeof(value), "%"PRIx64, (uint64_t)size);

    if (!xs_write(state->xenstore, 0, path, value, strlen(value))) {

        return -1;

    }

    if (mr_name) {

        snprintf(path, sizeof(path),

                "/local/domain/0/device-model/%d/physmap/%"PRIx64"/name",

                xen_domid, (uint64_t)phys_offset);

        if (!xs_write(state->xenstore, 0, path, mr_name, strlen(mr_name))) {

            return -1;

        }

    }

    return 0;

}


static int fmod_init_in (HWVoiceIn *hw, audsettings_t *as)

{

    int bits16, mode;

    FMODVoiceIn *fmd = (FMODVoiceIn *) hw;

    audsettings_t obt_as = *as;

    if (conf.broken_adc) {

        return -1;

    }

    mode = aud_to_fmodfmt (as->fmt, as->nchannels == 2 ? 1 : 0);

    fmd->fmod_sample = FSOUND_Sample_Alloc (

        FSOUND_FREE,            /* index */

        conf.nb_samples,        /* length */

        mode,                   /* mode */

        as->freq,               /* freq */

        255,                    /* volume */

        128,                    /* pan */

        255                     /* priority */

        );

    if (!fmd->fmod_sample) {

        fmod_logerr2 ("ADC", "Failed to allocate FMOD sample\n");

        return -1;

    }

    /* FMOD always operates on little endian frames? */

    obt_as.endianness = 0;

    audio_pcm_init_info (&hw->info, &obt_as);

    bits16 = (mode & FSOUND_16BITS) != 0;

    hw->samples = conf.nb_samples;

    return 0;

}


static void monitor_control_event(void *opaque, int event)

{

    if (event == CHR_EVENT_OPENED) {

        QObject *data;

        Monitor *mon = opaque;

        json_message_parser_init(&mon->mc->parser, handle_qmp_command);

        data = qobject_from_jsonf("{ 'QMP': { 'capabilities': [] } }");

        assert(data != NULL);

        monitor_json_emitter(mon, data);

        qobject_decref(data);

    }

}


static void pmac_ide_transfer_cb(void *opaque, int ret)

{

    DBDMA_io *io = opaque;

    MACIOIDEState *m = io->opaque;

    IDEState *s = idebus_active_if(&m->bus);

    int n = 0;

    int64_t sector_num;

    int unaligned;

    if (ret < 0) {

        MACIO_DPRINTF("DMA error\n");

        m->aiocb = NULL;

        qemu_sglist_destroy(&s->sg);

        ide_dma_error(s);

        io->remainder_len = 0;

        goto done;

    }

    if (!m->dma_active) {

        MACIO_DPRINTF("waiting for data (%#x - %#x - %x)\n",

                      s->nsector, io->len, s->status);

        /* data not ready yet, wait for the channel to get restarted */

        io->processing = false;

        return;

    }

    sector_num = ide_get_sector(s);

    MACIO_DPRINTF("io_buffer_size = %#x\n", s->io_buffer_size);

    if (s->io_buffer_size > 0) {

        m->aiocb = NULL;

        qemu_sglist_destroy(&s->sg);

        n = (s->io_buffer_size + 0x1ff) >> 9;

        sector_num += n;

        ide_set_sector(s, sector_num);

        s->nsector -= n;

    }

    MACIO_DPRINTF("remainder: %d io->len: %d nsector: %d "

                  "sector_num: %" PRId64 "\n",

                  io->remainder_len, io->len, s->nsector, sector_num);

    if (io->remainder_len && io->len) {

        /* guest wants the rest of its previous transfer */

        int remainder_len = MIN(io->remainder_len, io->len);

        uint8_t *p = &io->remainder[0x200 - remainder_len];

        MACIO_DPRINTF("copying remainder %d bytes at %#" HWADDR_PRIx "\n",

                      remainder_len, io->addr);

        switch (s->dma_cmd) {

        case IDE_DMA_READ:

            cpu_physical_memory_write(io->addr, p, remainder_len);

            break;

        case IDE_DMA_WRITE:

            cpu_physical_memory_read(io->addr, p, remainder_len);

            bdrv_write(s->bs, sector_num - 1, io->remainder, 1);

            break;

        case IDE_DMA_TRIM:

            break;

        }

        io->addr += remainder_len;

        io->len -= remainder_len;

        io->remainder_len -= remainder_len;

    }

    if (s->nsector == 0 && !io->remainder_len) {

        MACIO_DPRINTF("end of transfer\n");

        s->status = READY_STAT | SEEK_STAT;

        ide_set_irq(s->bus);

        m->dma_active = false;

    }

    if (io->len == 0) {

        MACIO_DPRINTF("end of DMA\n");

        goto done;

    }

    /* launch next transfer */

    s->io_buffer_index = 0;

    s->io_buffer_size = MIN(io->len, s->nsector * 512);

    /* handle unaligned accesses first, get them over with and only do the

       remaining bulk transfer using our async DMA helpers */

    unaligned = io->len & 0x1ff;

    if (unaligned) {

        int nsector = io->len >> 9;

        MACIO_DPRINTF("precopying unaligned %d bytes to %#" HWADDR_PRIx "\n",

                      unaligned, io->addr + io->len - unaligned);

        switch (s->dma_cmd) {

        case IDE_DMA_READ:

            bdrv_read(s->bs, sector_num + nsector, io->remainder, 1);

            cpu_physical_memory_write(io->addr + io->len - unaligned,

                                      io->remainder, unaligned);

            break;

        case IDE_DMA_WRITE:

            /* cache the contents in our io struct */

            cpu_physical_memory_read(io->addr + io->len - unaligned,

                                     io->remainder, unaligned);

            break;

        case IDE_DMA_TRIM:

            break;

        }

        io->len -= unaligned;

    }

    MACIO_DPRINTF("io->len = %#x\n", io->len);

    qemu_sglist_init(&s->sg, DEVICE(m), io->len / MACIO_PAGE_SIZE + 1,

                     &address_space_memory);

    qemu_sglist_add(&s->sg, io->addr, io->len);

    io->addr += io->len + unaligned;

    io->remainder_len = (0x200 - unaligned) & 0x1ff;

    MACIO_DPRINTF("set remainder to: %d\n", io->remainder_len);

    /* We would read no data from the block layer, thus not get a callback.

       Just fake completion manually. */

    if (!io->len) {

        pmac_ide_transfer_cb(opaque, 0);

        return;

    }

    io->len = 0;

    MACIO_DPRINTF("sector_num=%" PRId64 " n=%d, nsector=%d, cmd_cmd=%d\n",

                  sector_num, n, s->nsector, s->dma_cmd);

    switch (s->dma_cmd) {

    case IDE_DMA_READ:

        m->aiocb = dma_bdrv_read(s->bs, &s->sg, sector_num,

                                 pmac_ide_transfer_cb, io);

        break;

    case IDE_DMA_WRITE:

        m->aiocb = dma_bdrv_write(s->bs, &s->sg, sector_num,

                                  pmac_ide_transfer_cb, io);

        break;

    case IDE_DMA_TRIM:

        m->aiocb = dma_bdrv_io(s->bs, &s->sg, sector_num,

                               ide_issue_trim, pmac_ide_transfer_cb, io,

                               DMA_DIRECTION_TO_DEVICE);

        break;

    }

    return;

done:

    if (s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) {

        bdrv_acct_done(s->bs, &s->acct);

    }

    io->dma_end(io);

}


static uint64_t bmdma_read(void *opaque, target_phys_addr_t addr,

                           unsigned size)

{

    BMDMAState *bm = opaque;

    PCIIDEState *pci_dev = bm->pci_dev;

    uint32_t val;

    if (size != 1) {

        return ((uint64_t)1 << (size * 8)) - 1;

    }

    switch(addr & 3) {

    case 0:

        val = bm->cmd;

        break;

    case 1:

        val = pci_dev->dev.config[MRDMODE];

        break;

    case 2:

        val = bm->status;

        break;

    case 3:

        if (bm == &pci_dev->bmdma[0]) {

            val = pci_dev->dev.config[UDIDETCR0];

        } else {

            val = pci_dev->dev.config[UDIDETCR1];

        }

        break;

    default:

        val = 0xff;

        break;

    }

#ifdef DEBUG_IDE

    printf("bmdma: readb 0x%02x : 0x%02x\n", addr, val);

#endif

    return val;

}


static void hash32_bat_size(CPUPPCState *env, target_ulong *blp, int *validp,

                            target_ulong batu, target_ulong batl)

{

    target_ulong bl;

    int valid;

    bl = (batu & BATU32_BL) << 15;

    valid = 0;

    if (((msr_pr == 0) && (batu & BATU32_VS)) ||

        ((msr_pr != 0) && (batu & BATU32_VP))) {

        valid = 1;

    }

    *blp = bl;

    *validp = valid;

}