static int xvag_read_header(AVFormatContext *s)

{

    unsigned offset, big_endian, codec;

    AVStream *st;

    avio_skip(s->pb, 4);

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;

    offset     = avio_rl32(s->pb);

    big_endian = offset > av_bswap32(offset);

    if (big_endian) {

        offset                 = av_bswap32(offset);

        avio_skip(s->pb, 28);

        codec                  = avio_rb32(s->pb);

        st->codecpar->channels = avio_rb32(s->pb);

        avio_skip(s->pb, 4);

        st->duration           = avio_rb32(s->pb);

        avio_skip(s->pb, 8);

        st->codecpar->sample_rate = avio_rb32(s->pb);

    } else {

        avio_skip(s->pb, 28);

        codec                  = avio_rl32(s->pb);

        st->codecpar->channels = avio_rl32(s->pb);

        avio_skip(s->pb, 4);

        st->duration           = avio_rl32(s->pb);

        avio_skip(s->pb, 8);

        st->codecpar->sample_rate = avio_rl32(s->pb);

    }

    if (st->codecpar->sample_rate <= 0)

        return AVERROR_INVALIDDATA;

    if (st->codecpar->channels <= 0)

        return AVERROR_INVALIDDATA;

    switch (codec) {

    case 0x1c:

        st->codecpar->codec_id    = AV_CODEC_ID_ADPCM_PSX;

        st->codecpar->block_align = 16 * st->codecpar->channels;

        break;

    default:

        avpriv_request_sample(s, "codec %X", codec);

        return AVERROR_PATCHWELCOME;

    };

    avio_skip(s->pb, offset - avio_tell(s->pb));

    if (avio_rb16(s->pb) == 0xFFFB) {

        st->codecpar->codec_id    = AV_CODEC_ID_MP3;

        st->codecpar->block_align = 0x1000;

        st->need_parsing       = AVSTREAM_PARSE_FULL_RAW;

    }

    avio_skip(s->pb, -2);

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

    return 0;

}


void ff_imdct_calc_sse(MDCTContext *s, FFTSample *output,

                       const FFTSample *input, FFTSample *tmp)

{

    x86_reg k;

    long n8, n4, n2, n;

    const uint16_t *revtab = s->fft.revtab;

    const FFTSample *tcos = s->tcos;

    const FFTSample *tsin = s->tsin;

    const FFTSample *in1, *in2;

    FFTComplex *z = (FFTComplex *)tmp;

    n = 1 << s->nbits;

    n2 = n >> 1;

    n4 = n >> 2;

    n8 = n >> 3;

#ifdef ARCH_X86_64

    asm volatile ("movaps %0, %%xmm8\n\t"::"m"(*p1m1p1m1));

#define P1M1P1M1 "%%xmm8"

#else

#define P1M1P1M1 "%4"

#endif

    /* pre rotation */

    in1 = input;

    in2 = input + n2 - 4;

    /* Complex multiplication */

    for (k = 0; k < n4; k += 4) {

        asm volatile (

            "movaps          %0, %%xmm0 \n\t"   // xmm0 = r0 X  r1 X : in2

            "movaps          %1, %%xmm3 \n\t"   // xmm3 = X  i1 X  i0: in1

            "movaps    -16+1*%0, %%xmm4 \n\t"   // xmm4 = r0 X  r1 X : in2

            "movaps     16+1*%1, %%xmm7 \n\t"   // xmm7 = X  i1 X  i0: in1

            "movlps          %2, %%xmm1 \n\t"   // xmm1 = X  X  R1 R0: tcos

            "movlps          %3, %%xmm2 \n\t"   // xmm2 = X  X  I1 I0: tsin

            "movlps      8+1*%2, %%xmm5 \n\t"   // xmm5 = X  X  R1 R0: tcos

            "movlps      8+1*%3, %%xmm6 \n\t"   // xmm6 = X  X  I1 I0: tsin

            "shufps $95, %%xmm0, %%xmm0 \n\t"   // xmm0 = r1 r1 r0 r0

            "shufps $160,%%xmm3, %%xmm3 \n\t"   // xmm3 = i1 i1 i0 i0

            "shufps $95, %%xmm4, %%xmm4 \n\t"   // xmm4 = r1 r1 r0 r0

            "shufps $160,%%xmm7, %%xmm7 \n\t"   // xmm7 = i1 i1 i0 i0

            "unpcklps    %%xmm2, %%xmm1 \n\t"   // xmm1 = I1 R1 I0 R0

            "unpcklps    %%xmm6, %%xmm5 \n\t"   // xmm5 = I1 R1 I0 R0

            "movaps      %%xmm1, %%xmm2 \n\t"   // xmm2 = I1 R1 I0 R0

            "movaps      %%xmm5, %%xmm6 \n\t"   // xmm6 = I1 R1 I0 R0

            "xorps   "P1M1P1M1", %%xmm2 \n\t"   // xmm2 = -I1 R1 -I0 R0

            "xorps   "P1M1P1M1", %%xmm6 \n\t"   // xmm6 = -I1 R1 -I0 R0

            "mulps       %%xmm1, %%xmm0 \n\t"   // xmm0 = rI rR rI rR

            "mulps       %%xmm5, %%xmm4 \n\t"   // xmm4 = rI rR rI rR

            "shufps $177,%%xmm2, %%xmm2 \n\t"   // xmm2 = R1 -I1 R0 -I0

            "shufps $177,%%xmm6, %%xmm6 \n\t"   // xmm6 = R1 -I1 R0 -I0

            "mulps       %%xmm2, %%xmm3 \n\t"   // xmm3 = Ri -Ii Ri -Ii

            "mulps       %%xmm6, %%xmm7 \n\t"   // xmm7 = Ri -Ii Ri -Ii

            "addps       %%xmm3, %%xmm0 \n\t"   // xmm0 = result

            "addps       %%xmm7, %%xmm4 \n\t"   // xmm4 = result

            ::"m"(in2[-2*k]), "m"(in1[2*k]),

              "m"(tcos[k]), "m"(tsin[k])

#ifndef ARCH_X86_64

              ,"m"(*p1m1p1m1)

#endif

        );

        /* Should be in the same block, hack for gcc2.95 & gcc3 */

        asm (

            "movlps      %%xmm0, %0     \n\t"

            "movhps      %%xmm0, %1     \n\t"

            "movlps      %%xmm4, %2     \n\t"

            "movhps      %%xmm4, %3     \n\t"

            :"=m"(z[revtab[k]]), "=m"(z[revtab[k + 1]]),

             "=m"(z[revtab[k + 2]]), "=m"(z[revtab[k + 3]])

        );

    }

    ff_fft_calc_sse(&s->fft, z);

#ifndef ARCH_X86_64

#undef P1M1P1M1

#define P1M1P1M1 "%3"

#endif

    /* post rotation + reordering */

    for (k = 0; k < n4; k += 4) {

        asm (

            "movaps          %0, %%xmm0 \n\t"   // xmm0 = i1 r1 i0 r0: z

            "movaps     16+1*%0, %%xmm4 \n\t"   // xmm4 = i1 r1 i0 r0: z

            "movlps          %1, %%xmm1 \n\t"   // xmm1 = X  X  R1 R0: tcos

            "movlps      8+1*%1, %%xmm5 \n\t"   // xmm5 = X  X  R1 R0: tcos

            "movaps      %%xmm0, %%xmm3 \n\t"   // xmm3 = i1 r1 i0 r0

            "movaps      %%xmm4, %%xmm7 \n\t"   // xmm7 = i1 r1 i0 r0

            "movlps          %2, %%xmm2 \n\t"   // xmm2 = X  X  I1 I0: tsin

            "movlps      8+1*%2, %%xmm6 \n\t"   // xmm6 = X  X  I1 I0: tsin

            "shufps $160,%%xmm0, %%xmm0 \n\t"   // xmm0 = r1 r1 r0 r0

            "shufps $245,%%xmm3, %%xmm3 \n\t"   // xmm3 = i1 i1 i0 i0

            "shufps $160,%%xmm4, %%xmm4 \n\t"   // xmm4 = r1 r1 r0 r0

            "shufps $245,%%xmm7, %%xmm7 \n\t"   // xmm7 = i1 i1 i0 i0

            "unpcklps    %%xmm2, %%xmm1 \n\t"   // xmm1 = I1 R1 I0 R0

            "unpcklps    %%xmm6, %%xmm5 \n\t"   // xmm5 = I1 R1 I0 R0

            "movaps      %%xmm1, %%xmm2 \n\t"   // xmm2 = I1 R1 I0 R0

            "movaps      %%xmm5, %%xmm6 \n\t"   // xmm6 = I1 R1 I0 R0

            "xorps   "P1M1P1M1", %%xmm2 \n\t"   // xmm2 = -I1 R1 -I0 R0

            "mulps       %%xmm1, %%xmm0 \n\t"   // xmm0 = rI rR rI rR

            "xorps   "P1M1P1M1", %%xmm6 \n\t"   // xmm6 = -I1 R1 -I0 R0

            "mulps       %%xmm5, %%xmm4 \n\t"   // xmm4 = rI rR rI rR

            "shufps $177,%%xmm2, %%xmm2 \n\t"   // xmm2 = R1 -I1 R0 -I0

            "shufps $177,%%xmm6, %%xmm6 \n\t"   // xmm6 = R1 -I1 R0 -I0

            "mulps       %%xmm2, %%xmm3 \n\t"   // xmm3 = Ri -Ii Ri -Ii

            "mulps       %%xmm6, %%xmm7 \n\t"   // xmm7 = Ri -Ii Ri -Ii

            "addps       %%xmm3, %%xmm0 \n\t"   // xmm0 = result

            "addps       %%xmm7, %%xmm4 \n\t"   // xmm4 = result

            "movaps      %%xmm0, %0     \n\t"

            "movaps      %%xmm4, 16+1*%0\n\t"

            :"+m"(z[k])

            :"m"(tcos[k]), "m"(tsin[k])

#ifndef ARCH_X86_64

             ,"m"(*p1m1p1m1)

#endif

        );

    }

    /*

       Mnemonics:

       0 = z[k].re

       1 = z[k].im

       2 = z[k + 1].re

       3 = z[k + 1].im

       4 = z[-k - 2].re

       5 = z[-k - 2].im

       6 = z[-k - 1].re

       7 = z[-k - 1].im

    */

    k = 16-n;

    asm volatile("movaps %0, %%xmm7 \n\t"::"m"(*m1m1m1m1));

    asm volatile(

        "1: \n\t"

        "movaps  -16(%4,%0), %%xmm1 \n\t"   // xmm1 = 4 5 6 7 = z[-2-k]

        "neg %0 \n\t"

        "movaps     (%4,%0), %%xmm0 \n\t"   // xmm0 = 0 1 2 3 = z[k]

        "xorps       %%xmm7, %%xmm0 \n\t"   // xmm0 = -0 -1 -2 -3

        "movaps      %%xmm0, %%xmm2 \n\t"   // xmm2 = -0 -1 -2 -3

        "shufps $141,%%xmm1, %%xmm0 \n\t"   // xmm0 = -1 -3 4 6

        "shufps $216,%%xmm1, %%xmm2 \n\t"   // xmm2 = -0 -2 5 7

        "shufps $156,%%xmm0, %%xmm0 \n\t"   // xmm0 = -1 6 -3 4 !

        "shufps $156,%%xmm2, %%xmm2 \n\t"   // xmm2 = -0 7 -2 5 !

        "movaps      %%xmm0, (%1,%0) \n\t"  // output[2*k]

        "movaps      %%xmm2, (%2,%0) \n\t"  // output[n2+2*k]

        "neg %0 \n\t"

        "shufps $27, %%xmm0, %%xmm0 \n\t"   // xmm0 = 4 -3 6 -1

        "xorps       %%xmm7, %%xmm0 \n\t"   // xmm0 = -4 3 -6 1 !

        "shufps $27, %%xmm2, %%xmm2 \n\t"   // xmm2 = 5 -2 7 -0 !

        "movaps      %%xmm0, -16(%2,%0) \n\t" // output[n2-4-2*k]

        "movaps      %%xmm2, -16(%3,%0) \n\t" // output[n-4-2*k]

        "add $16, %0 \n\t"

        "jle 1b \n\t"

        :"+r"(k)

        :"r"(output), "r"(output+n2), "r"(output+n), "r"(z+n8)

        :"memory"

    );

}


static void nvme_init_sq(NvmeSQueue *sq, NvmeCtrl *n, uint64_t dma_addr,

    uint16_t sqid, uint16_t cqid, uint16_t size)

{

    int i;

    NvmeCQueue *cq;

    sq->ctrl = n;

    sq->dma_addr = dma_addr;

    sq->sqid = sqid;

    sq->size = size;

    sq->cqid = cqid;

    sq->head = sq->tail = 0;

    sq->io_req = g_malloc(sq->size * sizeof(*sq->io_req));

    QTAILQ_INIT(&sq->req_list);

    QTAILQ_INIT(&sq->out_req_list);

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

        sq->io_req[i].sq = sq;

        QTAILQ_INSERT_TAIL(&(sq->req_list), &sq->io_req[i], entry);

    }

    sq->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, nvme_process_sq, sq);

    assert(n->cq[cqid]);

    cq = n->cq[cqid];

    QTAILQ_INSERT_TAIL(&(cq->sq_list), sq, entry);

    n->sq[sqid] = sq;

}


static int qemu_chr_open_pp(QemuOpts *opts, CharDriverState **_chr)

{

    const char *filename = qemu_opt_get(opts, "path");

    CharDriverState *chr;

    int fd;

    fd = qemu_open(filename, O_RDWR);

    if (fd < 0) {

        return -errno;

    }

    chr = g_malloc0(sizeof(CharDriverState));

    chr->opaque = (void *)(intptr_t)fd;

    chr->chr_write = null_chr_write;

    chr->chr_ioctl = pp_ioctl;

    *_chr = chr;

    return 0;

}


static int kvm_put_fpu(X86CPU *cpu)

{

    CPUX86State *env = &cpu->env;

    struct kvm_fpu fpu;

    int i;

    memset(&fpu, 0, sizeof fpu);

    fpu.fsw = env->fpus & ~(7 << 11);

    fpu.fsw |= (env->fpstt & 7) << 11;

    fpu.fcw = env->fpuc;

    fpu.last_opcode = env->fpop;

    fpu.last_ip = env->fpip;

    fpu.last_dp = env->fpdp;

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

        fpu.ftwx |= (!env->fptags[i]) << i;

    }

    memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);

    memcpy(fpu.xmm, env->xmm_regs, sizeof env->xmm_regs);

    fpu.mxcsr = env->mxcsr;

    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);

}


static void test_visitor_out_native_list_int64(TestOutputVisitorData *data,

                                               const void *unused)

{

    test_native_list(data, unused, USER_DEF_NATIVE_LIST_UNION_KIND_S64);

}


static void v9fs_req_recv(P9Req *req, uint8_t id)

{

    QVirtIO9P *v9p = req->v9p;

    P9Hdr hdr;

    int i;

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

        qvirtio_wait_queue_isr(v9p->dev, v9p->vq, 1000 * 1000);

        v9fs_memread(req, &hdr, 7);

        le32_to_cpus(&hdr.size);

        le16_to_cpus(&hdr.tag);

        if (hdr.size >= 7) {

            break;

        }

        v9fs_memrewind(req, 7);

    }

    g_assert_cmpint(hdr.size, >=, 7);

    g_assert_cmpint(hdr.size, <=, P9_MAX_SIZE);

    g_assert_cmpint(hdr.tag, ==, req->tag);

    if (hdr.id != id) {

        g_printerr("Received response %d (%s) instead of %d (%s)\n",

                   hdr.id, rmessage_name(hdr.id), id, rmessage_name(id));

        if (hdr.id == P9_RLERROR) {

            uint32_t err;

            v9fs_uint32_read(req, &err);

            g_printerr("Rlerror has errno %d (%s)\n", err, strerror(err));

        }

    }

    g_assert_cmpint(hdr.id, ==, id);

}


static void set_algorythm( OPL_CH *CH)

{

	INT32 *carrier = &outd[0];

	CH->connect1 = CH->CON ? carrier : &feedback2;

	CH->connect2 = carrier;

}


void bios_linker_loader_alloc(GArray *linker,

                              const char *file,

                              uint32_t alloc_align,

                              bool alloc_fseg)

{

    BiosLinkerLoaderEntry entry;

    memset(&entry, 0, sizeof entry);

    strncpy(entry.alloc.file, file, sizeof entry.alloc.file - 1);

    entry.command = cpu_to_le32(BIOS_LINKER_LOADER_COMMAND_ALLOCATE);

    entry.alloc.align = cpu_to_le32(alloc_align);

    entry.alloc.zone = cpu_to_le32(alloc_fseg ?

                                    BIOS_LINKER_LOADER_ALLOC_ZONE_FSEG :

                                    BIOS_LINKER_LOADER_ALLOC_ZONE_HIGH);

    /* Alloc entries must come first, so prepend them */

    g_array_prepend_val(linker, entry);

}


static int count_contiguous_clusters(uint64_t nb_clusters, int cluster_size,

        uint64_t *l2_table, uint64_t stop_flags)

{

    int i;

    uint64_t mask = stop_flags | L2E_OFFSET_MASK | QCOW_OFLAG_COMPRESSED;

    uint64_t first_entry = be64_to_cpu(l2_table[0]);

    uint64_t offset = first_entry & mask;

    if (!offset)

        return 0;

    assert(qcow2_get_cluster_type(first_entry) != QCOW2_CLUSTER_COMPRESSED);

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

        uint64_t l2_entry = be64_to_cpu(l2_table[i]) & mask;

        if (offset + (uint64_t) i * cluster_size != l2_entry) {

            break;

        }

    }

	return i;

}


START_TEST(qlist_iter_test)

{

    int i;

    QList *qlist;

    qlist = qlist_new();

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

        qlist_append(qlist, qint_from_int(i));

    iter_called = 0;

    qlist_iter(qlist, iter_func, NULL);

    fail_unless(iter_called == iter_max);

    QDECREF(qlist);

}


static int setup_sigcontext(struct target_sigcontext *sc,

                            CPUOpenRISCState *regs,

                            unsigned long mask)

{

    int err = 0;

    unsigned long usp = regs->gpr[1];

    /* copy the regs. they are first in sc so we can use sc directly */

    /*copy_to_user(&sc, regs, sizeof(struct target_pt_regs));*/

    /* Set the frametype to CRIS_FRAME_NORMAL for the execution of

       the signal handler. The frametype will be restored to its previous

       value in restore_sigcontext. */

    /*regs->frametype = CRIS_FRAME_NORMAL;*/

    /* then some other stuff */

    __put_user(mask, &sc->oldmask);

    __put_user(usp, &sc->usp); return err;

}


void ff_avg_h264_qpel16_mc11_msa(uint8_t *dst, const uint8_t *src,

                                 ptrdiff_t stride)

{

    avc_luma_hv_qrt_and_aver_dst_16x16_msa(src - 2,

                                           src - (stride * 2),

                                           stride, dst, stride);

}


build_fadt(GArray *table_data, BIOSLinker *linker, AcpiPmInfo *pm,

           unsigned facs_tbl_offset, unsigned dsdt_tbl_offset,

           const char *oem_id, const char *oem_table_id)

{

    AcpiFadtDescriptorRev1 *fadt = acpi_data_push(table_data, sizeof(*fadt));

    unsigned fw_ctrl_offset = (char *)&fadt->firmware_ctrl - table_data->data;

    unsigned dsdt_entry_offset = (char *)&fadt->dsdt - table_data->data;

    /* FACS address to be filled by Guest linker */

    bios_linker_loader_add_pointer(linker,

        ACPI_BUILD_TABLE_FILE, fw_ctrl_offset, sizeof(fadt->firmware_ctrl),

        ACPI_BUILD_TABLE_FILE, facs_tbl_offset);

    /* DSDT address to be filled by Guest linker */

    fadt_setup(fadt, pm);

    bios_linker_loader_add_pointer(linker,

        ACPI_BUILD_TABLE_FILE, dsdt_entry_offset, sizeof(fadt->dsdt),

        ACPI_BUILD_TABLE_FILE, dsdt_tbl_offset);

    build_header(linker, table_data,

                 (void *)fadt, "FACP", sizeof(*fadt), 1, oem_id, oem_table_id);

}


static void m68k_cpu_reset(CPUState *s)

{

    M68kCPU *cpu = M68K_CPU(s);

    M68kCPUClass *mcc = M68K_CPU_GET_CLASS(cpu);

    CPUM68KState *env = &cpu->env;

    mcc->parent_reset(s);

    memset(env, 0, offsetof(CPUM68KState, end_reset_fields));

#if !defined(CONFIG_USER_ONLY)

    env->sr = 0x2700;

#endif

    m68k_switch_sp(env);

    /* ??? FP regs should be initialized to NaN.  */

    cpu_m68k_set_ccr(env, 0);

    /* TODO: We should set PC from the interrupt vector.  */

    env->pc = 0;

}


static void subpage_ram_write(void *opaque, target_phys_addr_t addr,

                              uint64_t value, unsigned size)

{

    ram_addr_t raddr = addr;

    void *ptr = qemu_get_ram_ptr(raddr);

    switch (size) {

    case 1: return stb_p(ptr, value);

    case 2: return stw_p(ptr, value);

    case 4: return stl_p(ptr, value);

    default: abort();

    }

}


static bool vfio_listener_skipped_section(MemoryRegionSection *section)

{

    return !memory_region_is_ram(section->mr);

}


coroutine_fn iscsi_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,

                                    int count, BdrvRequestFlags flags)

{

    IscsiLun *iscsilun = bs->opaque;

    struct IscsiTask iTask;

    uint64_t lba;

    uint32_t nb_blocks;

    bool use_16_for_ws = iscsilun->use_16_for_rw;

    if (!is_byte_request_lun_aligned(offset, count, iscsilun)) {

        return -ENOTSUP;

    }

    if (flags & BDRV_REQ_MAY_UNMAP) {

        if (!use_16_for_ws && !iscsilun->lbp.lbpws10) {

            /* WRITESAME10 with UNMAP is unsupported try WRITESAME16 */

            use_16_for_ws = true;

        }

        if (use_16_for_ws && !iscsilun->lbp.lbpws) {

            /* WRITESAME16 with UNMAP is not supported by the target,

             * fall back and try WRITESAME10/16 without UNMAP */

            flags &= ~BDRV_REQ_MAY_UNMAP;

            use_16_for_ws = iscsilun->use_16_for_rw;

        }

    }

    if (!(flags & BDRV_REQ_MAY_UNMAP) && !iscsilun->has_write_same) {

        /* WRITESAME without UNMAP is not supported by the target */

        return -ENOTSUP;

    }

    lba = offset / iscsilun->block_size;

    nb_blocks = count / iscsilun->block_size;

    if (iscsilun->zeroblock == NULL) {

        iscsilun->zeroblock = g_try_malloc0(iscsilun->block_size);

        if (iscsilun->zeroblock == NULL) {

            return -ENOMEM;

        }

    }

    iscsi_co_init_iscsitask(iscsilun, &iTask);

retry:

    if (use_16_for_ws) {

        iTask.task = iscsi_writesame16_task(iscsilun->iscsi, iscsilun->lun, lba,

                                            iscsilun->zeroblock, iscsilun->block_size,

                                            nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),

                                            0, 0, iscsi_co_generic_cb, &iTask);

    } else {

        iTask.task = iscsi_writesame10_task(iscsilun->iscsi, iscsilun->lun, lba,

                                            iscsilun->zeroblock, iscsilun->block_size,

                                            nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),

                                            0, 0, iscsi_co_generic_cb, &iTask);

    }

    if (iTask.task == NULL) {

        return -ENOMEM;

    }

    while (!iTask.complete) {

        iscsi_set_events(iscsilun);

        qemu_coroutine_yield();

    }

    if (iTask.status == SCSI_STATUS_CHECK_CONDITION &&

        iTask.task->sense.key == SCSI_SENSE_ILLEGAL_REQUEST &&

        (iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE ||

         iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_FIELD_IN_CDB)) {

        /* WRITE SAME is not supported by the target */

        iscsilun->has_write_same = false;

        scsi_free_scsi_task(iTask.task);

        return -ENOTSUP;

    }

    if (iTask.task != NULL) {

        scsi_free_scsi_task(iTask.task);

        iTask.task = NULL;

    }

    if (iTask.do_retry) {

        iTask.complete = 0;

        goto retry;

    }

    if (iTask.status != SCSI_STATUS_GOOD) {

        return iTask.err_code;

    }

    if (flags & BDRV_REQ_MAY_UNMAP) {

        iscsi_allocationmap_clear(iscsilun, offset >> BDRV_SECTOR_BITS,

                                  count >> BDRV_SECTOR_BITS);

    } else {

        iscsi_allocationmap_set(iscsilun, offset >> BDRV_SECTOR_BITS,

                                count >> BDRV_SECTOR_BITS);

    }

    return 0;

}


void net_slirp_redir(const char *redir_str)

{

    int is_udp;

    char buf[256], *r;

    const char *p;

    struct in_addr guest_addr;

    int host_port, guest_port;

    if (!slirp_inited) {

        slirp_inited = 1;

        slirp_init(0, NULL);

    }

    p = redir_str;

    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)

        goto fail;

    if (!strcmp(buf, "tcp")) {

        is_udp = 0;

    } else if (!strcmp(buf, "udp")) {

        is_udp = 1;

    } else {

        goto fail;

    }

    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)

        goto fail;

    host_port = strtol(buf, &r, 0);

    if (r == buf)

        goto fail;

    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)

        goto fail;

    if (buf[0] == '\0') {

        pstrcpy(buf, sizeof(buf), "10.0.2.15");

    }

    if (!inet_aton(buf, &guest_addr))

        goto fail;

    guest_port = strtol(p, &r, 0);

    if (r == p)

        goto fail;

    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {

        fprintf(stderr, "qemu: could not set up redirection\n");

        exit(1);

    }

    return;

 fail:

    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");

    exit(1);

}


static uint64_t omap2_inth_read(void *opaque, target_phys_addr_t addr,

                                unsigned size)

{

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

    int offset = addr;

    int bank_no, line_no;

    struct omap_intr_handler_bank_s *bank = NULL;

    if ((offset & 0xf80) == 0x80) {

        bank_no = (offset & 0x60) >> 5;

        if (bank_no < s->nbanks) {

            offset &= ~0x60;

            bank = &s->bank[bank_no];

        }

    }

    switch (offset) {

    case 0x00:	/* INTC_REVISION */

        return 0x21;

    case 0x10:	/* INTC_SYSCONFIG */

        return (s->autoidle >> 2) & 1;

    case 0x14:	/* INTC_SYSSTATUS */

        return 1;						/* RESETDONE */

    case 0x40:	/* INTC_SIR_IRQ */

        return s->sir_intr[0];

    case 0x44:	/* INTC_SIR_FIQ */

        return s->sir_intr[1];

    case 0x48:	/* INTC_CONTROL */

        return (!s->mask) << 2;					/* GLOBALMASK */

    case 0x4c:	/* INTC_PROTECTION */

        return 0;

    case 0x50:	/* INTC_IDLE */

        return s->autoidle & 3;

    /* Per-bank registers */

    case 0x80:	/* INTC_ITR */

        return bank->inputs;

    case 0x84:	/* INTC_MIR */

        return bank->mask;

    case 0x88:	/* INTC_MIR_CLEAR */

    case 0x8c:	/* INTC_MIR_SET */

        return 0;

    case 0x90:	/* INTC_ISR_SET */

        return bank->swi;

    case 0x94:	/* INTC_ISR_CLEAR */

        return 0;

    case 0x98:	/* INTC_PENDING_IRQ */

        return bank->irqs & ~bank->mask & ~bank->fiq;

    case 0x9c:	/* INTC_PENDING_FIQ */

        return bank->irqs & ~bank->mask & bank->fiq;

    /* Per-line registers */

    case 0x100 ... 0x300:	/* INTC_ILR */

        bank_no = (offset - 0x100) >> 7;

        if (bank_no > s->nbanks)

            break;

        bank = &s->bank[bank_no];

        line_no = (offset & 0x7f) >> 2;

        return (bank->priority[line_no] << 2) |

                ((bank->fiq >> line_no) & 1);

    }

    OMAP_BAD_REG(addr);

    return 0;

}


static int wav_read_header(AVFormatContext *s)

{

    int64_t size, av_uninit(data_size);

    int64_t sample_count = 0;

    int rf64;

    uint32_t tag;

    AVIOContext *pb      = s->pb;

    AVStream *st         = NULL;

    WAVDemuxContext *wav = s->priv_data;

    int ret, got_fmt = 0;

    int64_t next_tag_ofs, data_ofs = -1;

    wav->unaligned = avio_tell(s->pb) & 1;

    wav->smv_data_ofs = -1;

    /* check RIFF header */

    tag = avio_rl32(pb);

    rf64 = tag == MKTAG('R', 'F', '6', '4');

    wav->rifx = tag == MKTAG('R', 'I', 'F', 'X');

    if (!rf64 && !wav->rifx && tag != MKTAG('R', 'I', 'F', 'F'))

        return AVERROR_INVALIDDATA;

    avio_rl32(pb); /* file size */

    tag = avio_rl32(pb);

    if (tag != MKTAG('W', 'A', 'V', 'E'))

        return AVERROR_INVALIDDATA;

    if (rf64) {

        if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))

            return AVERROR_INVALIDDATA;

        size = avio_rl32(pb);

        if (size < 24)

            return AVERROR_INVALIDDATA;

        avio_rl64(pb); /* RIFF size */

        data_size    = avio_rl64(pb);

        sample_count = avio_rl64(pb);

        if (data_size < 0 || sample_count < 0) {

            av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "

                   "ds64: data_size = %"PRId64", sample_count = %"PRId64"\n",

                   data_size, sample_count);

            return AVERROR_INVALIDDATA;

        }

        avio_skip(pb, size - 24); /* skip rest of ds64 chunk */

    }

    for (;;) {

        AVStream *vst;

        size         = next_tag(pb, &tag, wav->rifx);

        next_tag_ofs = avio_tell(pb) + size;

        if (avio_feof(pb))

            break;

        switch (tag) {

        case MKTAG('f', 'm', 't', ' '):

            /* only parse the first 'fmt ' tag found */

            if (!got_fmt && (ret = wav_parse_fmt_tag(s, size, &st)) < 0) {

                return ret;

            } else if (got_fmt)

                av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");

            got_fmt = 1;

            break;

        case MKTAG('d', 'a', 't', 'a'):

            if (!got_fmt) {

                av_log(s, AV_LOG_ERROR,

                       "found no 'fmt ' tag before the 'data' tag\n");

                return AVERROR_INVALIDDATA;

            }

            if (rf64) {

                next_tag_ofs = wav->data_end = avio_tell(pb) + data_size;

            } else {

                data_size    = size;

                next_tag_ofs = wav->data_end = size ? next_tag_ofs : INT64_MAX;

            }

            data_ofs = avio_tell(pb);

            /* don't look for footer metadata if we can't seek or if we don't

             * know where the data tag ends

             */

            if (!pb->seekable || (!rf64 && !size))

                goto break_loop;

            break;

        case MKTAG('f', 'a', 'c', 't'):

            if (!sample_count)

                sample_count = (!wav->rifx ? avio_rl32(pb) : avio_rb32(pb));

            break;

        case MKTAG('b', 'e', 'x', 't'):

            if ((ret = wav_parse_bext_tag(s, size)) < 0)

                return ret;

            break;

        case MKTAG('S','M','V','0'):

            if (!got_fmt) {

                av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'SMV0' tag\n");

                return AVERROR_INVALIDDATA;

            }

            // SMV file, a wav file with video appended.

            if (size != MKTAG('0','2','0','0')) {

                av_log(s, AV_LOG_ERROR, "Unknown SMV version found\n");

                goto break_loop;

            }

            av_log(s, AV_LOG_DEBUG, "Found SMV data\n");

            wav->smv_given_first = 0;

            vst = avformat_new_stream(s, NULL);

            if (!vst)

                return AVERROR(ENOMEM);

            avio_r8(pb);

            vst->id = 1;

            vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;

            vst->codec->codec_id = AV_CODEC_ID_SMVJPEG;

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

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

            if (ff_alloc_extradata(vst->codec, 4)) {

                av_log(s, AV_LOG_ERROR, "Could not allocate extradata.\n");

                return AVERROR(ENOMEM);

            }

            size = avio_rl24(pb);

            wav->smv_data_ofs = avio_tell(pb) + (size - 5) * 3;

            avio_rl24(pb);

            wav->smv_block_size = avio_rl24(pb);

            avpriv_set_pts_info(vst, 32, 1, avio_rl24(pb));

            vst->duration = avio_rl24(pb);

            avio_rl24(pb);

            avio_rl24(pb);

            wav->smv_frames_per_jpeg = avio_rl24(pb);

            if (wav->smv_frames_per_jpeg > 65536) {

                av_log(s, AV_LOG_ERROR, "too many frames per jpeg\n");

                return AVERROR_INVALIDDATA;

            }

            AV_WL32(vst->codec->extradata, wav->smv_frames_per_jpeg);

            wav->smv_cur_pt = 0;

            goto break_loop;

        case MKTAG('L', 'I', 'S', 'T'):

            if (size < 4) {

                av_log(s, AV_LOG_ERROR, "too short LIST tag\n");

                return AVERROR_INVALIDDATA;

            }

            switch (avio_rl32(pb)) {

            case MKTAG('I', 'N', 'F', 'O'):

                ff_read_riff_info(s, size - 4);

            }

            break;

        }

        /* seek to next tag unless we know that we'll run into EOF */

        if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||

            wav_seek_tag(wav, pb, next_tag_ofs, SEEK_SET) < 0) {

            break;

        }

    }

break_loop:

    if (data_ofs < 0) {

        av_log(s, AV_LOG_ERROR, "no 'data' tag found\n");

        return AVERROR_INVALIDDATA;

    }

    avio_seek(pb, data_ofs, SEEK_SET);

    if (   data_size > 0 && sample_count && st->codec->channels

        && data_size / sample_count / st->codec->channels > 8) {

        av_log(s, AV_LOG_WARNING, "ignoring wrong sample_count %"PRId64"\n", sample_count);

        sample_count = 0;

    }

    if (!sample_count || av_get_exact_bits_per_sample(st->codec->codec_id) > 0)

        if (   st->codec->channels

            && data_size

            && av_get_bits_per_sample(st->codec->codec_id)

            && wav->data_end <= avio_size(pb))

            sample_count = (data_size << 3)

                                  /

                (st->codec->channels * (uint64_t)av_get_bits_per_sample(st->codec->codec_id));

    if (sample_count)

        st->duration = sample_count;

    ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);

    ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);

    return 0;

}


static void pc_init1(ram_addr_t ram_size, int vga_ram_size,

                     const char *boot_device, DisplayState *ds,

                     const char *kernel_filename, const char *kernel_cmdline,

                     const char *initrd_filename,

                     int pci_enabled, const char *cpu_model)

{

    char buf[1024];

    int ret, linux_boot, i;

    ram_addr_t ram_addr, vga_ram_addr, bios_offset, vga_bios_offset;

    ram_addr_t below_4g_mem_size, above_4g_mem_size = 0;

    int bios_size, isa_bios_size, vga_bios_size;

    PCIBus *pci_bus;

    int piix3_devfn = -1;

    CPUState *env;

    NICInfo *nd;

    qemu_irq *cpu_irq;

    qemu_irq *i8259;

    int index;

    BlockDriverState *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    BlockDriverState *fd[MAX_FD];

    if (ram_size >= 0xe0000000 ) {

        above_4g_mem_size = ram_size - 0xe0000000;

        below_4g_mem_size = 0xe0000000;

    } else {

        below_4g_mem_size = ram_size;

    }

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (cpu_model == NULL) {

#ifdef TARGET_X86_64

        cpu_model = "qemu64";

#else

        cpu_model = "qemu32";

#endif

    }

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

        env = cpu_init(cpu_model);

        if (!env) {

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

            exit(1);

        }

        if (i != 0)

            env->halted = 1;

        if (smp_cpus > 1) {

            /* XXX: enable it in all cases */

            env->cpuid_features |= CPUID_APIC;

        }

        qemu_register_reset(main_cpu_reset, env);

        if (pci_enabled) {

            apic_init(env);

        }

    }

    vmport_init();

    /* allocate RAM */

    ram_addr = qemu_ram_alloc(0xa0000);

    cpu_register_physical_memory(0, 0xa0000, ram_addr);

    /* Allocate, even though we won't register, so we don't break the

     * phys_ram_base + PA assumption. This range includes vga (0xa0000 - 0xc0000),

     * and some bios areas, which will be registered later

     */

    ram_addr = qemu_ram_alloc(0x100000 - 0xa0000);

    ram_addr = qemu_ram_alloc(below_4g_mem_size - 0x100000);

    cpu_register_physical_memory(0x100000,

                 below_4g_mem_size - 0x100000,

                 ram_addr);

    /* above 4giga memory allocation */

    if (above_4g_mem_size > 0) {

        ram_addr = qemu_ram_alloc(above_4g_mem_size);

        cpu_register_physical_memory(0x100000000ULL,

                                     above_4g_mem_size,

                                     ram_addr);

    }

    /* allocate VGA RAM */

    vga_ram_addr = qemu_ram_alloc(vga_ram_size);

    /* BIOS load */

    if (bios_name == NULL)

        bios_name = BIOS_FILENAME;

    snprintf(buf, sizeof(buf), "%s/%s", bios_dir, bios_name);

    bios_size = get_image_size(buf);

    if (bios_size <= 0 ||

        (bios_size % 65536) != 0) {

        goto bios_error;

    }

    bios_offset = qemu_ram_alloc(bios_size);

    ret = load_image(buf, phys_ram_base + bios_offset);

    if (ret != bios_size) {

    bios_error:

        fprintf(stderr, "qemu: could not load PC BIOS '%s'\n", buf);

        exit(1);

    }

    /* VGA BIOS load */

    if (cirrus_vga_enabled) {

        snprintf(buf, sizeof(buf), "%s/%s", bios_dir, VGABIOS_CIRRUS_FILENAME);

    } else {

        snprintf(buf, sizeof(buf), "%s/%s", bios_dir, VGABIOS_FILENAME);

    }

    vga_bios_size = get_image_size(buf);

    if (vga_bios_size <= 0 || vga_bios_size > 65536)

        goto vga_bios_error;

    vga_bios_offset = qemu_ram_alloc(65536);

    ret = load_image(buf, phys_ram_base + vga_bios_offset);

    if (ret != vga_bios_size) {

    vga_bios_error:

        fprintf(stderr, "qemu: could not load VGA BIOS '%s'\n", buf);

        exit(1);

    }

    /* setup basic memory access */

    cpu_register_physical_memory(0xc0000, 0x10000,

                                 vga_bios_offset | IO_MEM_ROM);

    /* map the last 128KB of the BIOS in ISA space */

    isa_bios_size = bios_size;

    if (isa_bios_size > (128 * 1024))

        isa_bios_size = 128 * 1024;

    cpu_register_physical_memory(0x100000 - isa_bios_size,

                                 isa_bios_size,

                                 (bios_offset + bios_size - isa_bios_size) | IO_MEM_ROM);

    {

        ram_addr_t option_rom_offset;

        int size, offset;

        offset = 0;

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

            size = get_image_size(option_rom[i]);

            if (size < 0) {

                fprintf(stderr, "Could not load option rom '%s'\n",

                        option_rom[i]);

                exit(1);

            }

            if (size > (0x10000 - offset))

                goto option_rom_error;

            option_rom_offset = qemu_ram_alloc(size);

            ret = load_image(option_rom[i], phys_ram_base + option_rom_offset);

            if (ret != size) {

            option_rom_error:

                fprintf(stderr, "Too many option ROMS\n");

                exit(1);

            }

            size = (size + 4095) & ~4095;

            cpu_register_physical_memory(0xd0000 + offset,

                                         size, option_rom_offset | IO_MEM_ROM);

            offset += size;

        }

    }

    /* map all the bios at the top of memory */

    cpu_register_physical_memory((uint32_t)(-bios_size),

                                 bios_size, bios_offset | IO_MEM_ROM);

    bochs_bios_init();

    if (linux_boot)

	load_linux(kernel_filename, initrd_filename, kernel_cmdline);

    cpu_irq = qemu_allocate_irqs(pic_irq_request, NULL, 1);

    i8259 = i8259_init(cpu_irq[0]);

    ferr_irq = i8259[13];

    if (pci_enabled) {

        pci_bus = i440fx_init(&i440fx_state, i8259);

        piix3_devfn = piix3_init(pci_bus, -1);

    } else {

        pci_bus = NULL;

    }

    /* init basic PC hardware */

    register_ioport_write(0x80, 1, 1, ioport80_write, NULL);

    register_ioport_write(0xf0, 1, 1, ioportF0_write, NULL);

    if (cirrus_vga_enabled) {

        if (pci_enabled) {

            pci_cirrus_vga_init(pci_bus,

                                ds, phys_ram_base + vga_ram_addr,

                                vga_ram_addr, vga_ram_size);

        } else {

            isa_cirrus_vga_init(ds, phys_ram_base + vga_ram_addr,

                                vga_ram_addr, vga_ram_size);

        }

    } else if (vmsvga_enabled) {

        if (pci_enabled)

            pci_vmsvga_init(pci_bus, ds, phys_ram_base + vga_ram_addr,

                            vga_ram_addr, vga_ram_size);

        else

            fprintf(stderr, "%s: vmware_vga: no PCI bus\n", __FUNCTION__);

    } else {

        if (pci_enabled) {

            pci_vga_init(pci_bus, ds, phys_ram_base + vga_ram_addr,

                         vga_ram_addr, vga_ram_size, 0, 0);

        } else {

            isa_vga_init(ds, phys_ram_base + vga_ram_addr,

                         vga_ram_addr, vga_ram_size);

        }

    }

    rtc_state = rtc_init(0x70, i8259[8]);

    qemu_register_boot_set(pc_boot_set, rtc_state);

    register_ioport_read(0x92, 1, 1, ioport92_read, NULL);

    register_ioport_write(0x92, 1, 1, ioport92_write, NULL);

    if (pci_enabled) {

        ioapic = ioapic_init();

    }

    pit = pit_init(0x40, i8259[0]);

    pcspk_init(pit);

    if (pci_enabled) {

        pic_set_alt_irq_func(isa_pic, ioapic_set_irq, ioapic);

    }

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

        if (serial_hds[i]) {

            serial_init(serial_io[i], i8259[serial_irq[i]], 115200,

                        serial_hds[i]);

        }

    }

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

        if (parallel_hds[i]) {

            parallel_init(parallel_io[i], i8259[parallel_irq[i]],

                          parallel_hds[i]);

        }

    }

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

        nd = &nd_table[i];

        if (!nd->model) {

            if (pci_enabled) {

                nd->model = "ne2k_pci";

            } else {

                nd->model = "ne2k_isa";

            }

        }

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

            pc_init_ne2k_isa(nd, i8259);

        } else if (pci_enabled) {

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

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

            pci_nic_init(pci_bus, nd, -1);

        } else if (strcmp(nd->model, "?") == 0) {

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

            exit(1);

        } else {

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

            exit(1);

        }

    }

    if (drive_get_max_bus(IF_IDE) >= MAX_IDE_BUS) {

        fprintf(stderr, "qemu: too many IDE bus\n");

        exit(1);

    }

    for(i = 0; i < MAX_IDE_BUS * MAX_IDE_DEVS; i++) {

        index = drive_get_index(IF_IDE, i / MAX_IDE_DEVS, i % MAX_IDE_DEVS);

	if (index != -1)

	    hd[i] = drives_table[index].bdrv;

	else

	    hd[i] = NULL;

    }

    if (pci_enabled) {

        pci_piix3_ide_init(pci_bus, hd, piix3_devfn + 1, i8259);

    } else {

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

            isa_ide_init(ide_iobase[i], ide_iobase2[i], i8259[ide_irq[i]],

	                 hd[MAX_IDE_DEVS * i], hd[MAX_IDE_DEVS * i + 1]);

        }

    }

    i8042_init(i8259[1], i8259[12], 0x60);

    DMA_init(0);

#ifdef HAS_AUDIO

    audio_init(pci_enabled ? pci_bus : NULL, i8259);

#endif

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

        index = drive_get_index(IF_FLOPPY, 0, i);

	if (index != -1)

	    fd[i] = drives_table[index].bdrv;

	else

	    fd[i] = NULL;

    }

    floppy_controller = fdctrl_init(i8259[6], 2, 0, 0x3f0, fd);

    cmos_init(below_4g_mem_size, above_4g_mem_size, boot_device, hd);

    if (pci_enabled && usb_enabled) {

        usb_uhci_piix3_init(pci_bus, piix3_devfn + 2);

    }

    if (pci_enabled && acpi_enabled) {

        uint8_t *eeprom_buf = qemu_mallocz(8 * 256); /* XXX: make this persistent */

        i2c_bus *smbus;

        /* TODO: Populate SPD eeprom data.  */

        smbus = piix4_pm_init(pci_bus, piix3_devfn + 3, 0xb100, i8259[9]);

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

            smbus_eeprom_device_init(smbus, 0x50 + i, eeprom_buf + (i * 256));

        }

    }

    if (i440fx_state) {

        i440fx_init_memory_mappings(i440fx_state);

    }

    if (pci_enabled) {

	int max_bus;

        int bus, unit;

        void *scsi;

        max_bus = drive_get_max_bus(IF_SCSI);

	for (bus = 0; bus <= max_bus; bus++) {

            scsi = lsi_scsi_init(pci_bus, -1);

            for (unit = 0; unit < LSI_MAX_DEVS; unit++) {

	        index = drive_get_index(IF_SCSI, bus, unit);

		if (index == -1)

		    continue;

		lsi_scsi_attach(scsi, drives_table[index].bdrv, unit);

	    }

        }

    }

}


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

{

    PCIBonitoState *s = opaque;

    uint32_t saddr;

    int reset = 0;

    saddr = (addr - BONITO_REGBASE) >> 2;

    DPRINTF("bonito_writel "TARGET_FMT_plx" val %x saddr %x \n", addr, val, saddr);

    switch (saddr) {

    case BONITO_BONPONCFG:

    case BONITO_IODEVCFG:

    case BONITO_SDCFG:

    case BONITO_PCIMAP:

    case BONITO_PCIMEMBASECFG:

    case BONITO_PCIMAP_CFG:

    case BONITO_GPIODATA:

    case BONITO_GPIOIE:

    case BONITO_INTEDGE:

    case BONITO_INTSTEER:

    case BONITO_INTPOL:

    case BONITO_PCIMAIL0:

    case BONITO_PCIMAIL1:

    case BONITO_PCIMAIL2:

    case BONITO_PCIMAIL3:

    case BONITO_PCICACHECTRL:

    case BONITO_PCICACHETAG:

    case BONITO_PCIBADADDR:

    case BONITO_PCIMSTAT:

    case BONITO_TIMECFG:

    case BONITO_CPUCFG:

    case BONITO_DQCFG:

    case BONITO_MEMSIZE:

        s->regs[saddr] = val;

        break;

    case BONITO_BONGENCFG:

        if (!(s->regs[saddr] & 0x04) && (val & 0x04)) {

            reset = 1; /* bit 2 jump from 0 to 1 cause reset */

        }

        s->regs[saddr] = val;

        if (reset) {

            qemu_system_reset_request();

        }

        break;

    case BONITO_INTENSET:

        s->regs[BONITO_INTENSET] = val;

        s->regs[BONITO_INTEN] |= val;

        break;

    case BONITO_INTENCLR:

        s->regs[BONITO_INTENCLR] = val;

        s->regs[BONITO_INTEN] &= ~val;

        break;

    case BONITO_INTEN:

    case BONITO_INTISR:

        DPRINTF("write to readonly bonito register %x \n", saddr);

        break;

    default:

        DPRINTF("write to unknown bonito register %x \n", saddr);

        break;

    }

}


int socket_dgram(SocketAddressLegacy *remote, SocketAddressLegacy *local, Error **errp)

{

    int fd;

    /*

     * TODO SOCKET_ADDRESS_LEGACY_KIND_FD when fd is AF_INET or AF_INET6

     * (although other address families can do SOCK_DGRAM, too)

     */

    switch (remote->type) {

    case SOCKET_ADDRESS_LEGACY_KIND_INET:

        fd = inet_dgram_saddr(remote->u.inet.data,

                              local ? local->u.inet.data : NULL, errp);

        break;

    default:

        error_setg(errp, "socket type unsupported for datagram");

        fd = -1;

    }

    return fd;

}


static void filter_line_c(uint8_t *dst,

                          uint8_t *prev, uint8_t *cur, uint8_t *next,

                          int w, int refs, int parity, int mode)

{

    int x;

    uint8_t *prev2 = parity ? prev : cur ;

    uint8_t *next2 = parity ? cur  : next;

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

        int c = cur[-refs];

        int d = (prev2[0] + next2[0])>>1;

        int e = cur[+refs];

        int temporal_diff0 = FFABS(prev2[0] - next2[0]);

        int temporal_diff1 =(FFABS(prev[-refs] - c) + FFABS(prev[+refs] - e) )>>1;

        int temporal_diff2 =(FFABS(next[-refs] - c) + FFABS(next[+refs] - e) )>>1;

        int diff = FFMAX3(temporal_diff0>>1, temporal_diff1, temporal_diff2);

        int spatial_pred = (c+e)>>1;

        int spatial_score = FFABS(cur[-refs-1] - cur[+refs-1]) + FFABS(c-e)

                          + FFABS(cur[-refs+1] - cur[+refs+1]) - 1;

#define CHECK(j)\

    {   int score = FFABS(cur[-refs-1+j] - cur[+refs-1-j])\

                  + FFABS(cur[-refs  +j] - cur[+refs  -j])\

                  + FFABS(cur[-refs+1+j] - cur[+refs+1-j]);\

        if (score < spatial_score) {\

            spatial_score= score;\

            spatial_pred= (cur[-refs  +j] + cur[+refs  -j])>>1;\

        CHECK(-1) CHECK(-2) }} }}


static void opt_video_channel(const char *arg)

{

    video_channel = strtol(arg, NULL, 0);

}


static int parse_tag(AVFormatContext *s, const uint8_t *buf)

{

    int genre;

    if (!(buf[0] == 'T' &&

          buf[1] == 'A' &&

          buf[2] == 'G'))

        return -1;

    get_string(s, "title",   buf +  3, 30);

    get_string(s, "artist",  buf + 33, 30);

    get_string(s, "album",   buf + 63, 30);

    get_string(s, "date",    buf + 93,  4);

    get_string(s, "comment", buf + 97, 30);

    if (buf[125] == 0 && buf[126] != 0)

        av_metadata_set2(&s->metadata, "track", av_d2str(buf[126]), AV_METADATA_DONT_STRDUP_VAL);

    genre = buf[127];

    if (genre <= ID3v1_GENRE_MAX)

        av_metadata_set2(&s->metadata, "genre", ff_id3v1_genre_str[genre], 0);

    return 0;

}


static void vnc_update(VncState *vs, int x, int y, int w, int h)

{

    int i;

    h += y;

    /* round x down to ensure the loop only spans one 16-pixel block per,

       iteration.  otherwise, if (x % 16) != 0, the last iteration may span

       two 16-pixel blocks but we only mark the first as dirty

    */

    w += (x % 16);

    x -= (x % 16);

    x = MIN(x, vs->serverds.width);

    y = MIN(y, vs->serverds.height);

    w = MIN(x + w, vs->serverds.width) - x;

    h = MIN(h, vs->serverds.height);

    for (; y < h; y++)

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

            vnc_set_bit(vs->dirty_row[y], (x + i) / 16);

}


int qemu_ftruncate64(int fd, int64_t length)

{

    LARGE_INTEGER li;

    LONG high;

    HANDLE h;

    BOOL res;

    if ((GetVersion() & 0x80000000UL) && (length >> 32) != 0)

	return -1;

    h = (HANDLE)_get_osfhandle(fd);

    /* get current position, ftruncate do not change position */

    li.HighPart = 0;

    li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_CURRENT);

    if (li.LowPart == 0xffffffffUL && GetLastError() != NO_ERROR)

	return -1;

    high = length >> 32;

    if (!SetFilePointer(h, (DWORD) length, &high, FILE_BEGIN))

	return -1;

    res = SetEndOfFile(h);

    /* back to old position */

    SetFilePointer(h, li.LowPart, &li.HighPart, FILE_BEGIN);

    return res ? 0 : -1;

}


I2CBus *aux_get_i2c_bus(AUXBus *bus)

{

    return aux_bridge_get_i2c_bus(bus->bridge);

}


static void lame_window_init(AacPsyContext *ctx, AVCodecContext *avctx) {

    int i;

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

        AacPsyChannel *pch = &ctx->ch[i];

        if (avctx->flags & CODEC_FLAG_QSCALE)

            pch->attack_threshold = psy_vbr_map[avctx->global_quality / FF_QP2LAMBDA].st_lrm;

        else

            pch->attack_threshold = lame_calc_attack_threshold(avctx->bit_rate / avctx->channels / 1000);

        for (i = 0; i < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; i++)

            pch->prev_energy_subshort[i] = 10.0f;

    }

}


static void pflash_cfi01_class_init(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = pflash_cfi01_realize;

    dc->props = pflash_cfi01_properties;

    dc->vmsd = &vmstate_pflash;

    set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);

}


static BlockDriverAIOCB *rbd_start_aio(BlockDriverState *bs,

                                       int64_t sector_num,

                                       QEMUIOVector *qiov,

                                       int nb_sectors,

                                       BlockDriverCompletionFunc *cb,

                                       void *opaque,

                                       RBDAIOCmd cmd)

{

    RBDAIOCB *acb;

    RADOSCB *rcb;

    rbd_completion_t c;

    int64_t off, size;

    char *buf;

    int r;

    BDRVRBDState *s = bs->opaque;

    acb = qemu_aio_get(&rbd_aiocb_info, bs, cb, opaque);

    acb->cmd = cmd;

    acb->qiov = qiov;

    if (cmd == RBD_AIO_DISCARD || cmd == RBD_AIO_FLUSH) {

        acb->bounce = NULL;

    } else {

        acb->bounce = qemu_blockalign(bs, qiov->size);

    }

    acb->ret = 0;

    acb->error = 0;

    acb->s = s;

    acb->cancelled = 0;

    acb->bh = NULL;

    acb->status = -EINPROGRESS;

    if (cmd == RBD_AIO_WRITE) {

        qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);

    }

    buf = acb->bounce;

    off = sector_num * BDRV_SECTOR_SIZE;

    size = nb_sectors * BDRV_SECTOR_SIZE;

    rcb = g_malloc(sizeof(RADOSCB));

    rcb->done = 0;

    rcb->acb = acb;

    rcb->buf = buf;

    rcb->s = acb->s;

    rcb->size = size;

    r = rbd_aio_create_completion(rcb, (rbd_callback_t) rbd_finish_aiocb, &c);

    if (r < 0) {

        goto failed;

    }

    switch (cmd) {

    case RBD_AIO_WRITE:

        r = rbd_aio_write(s->image, off, size, buf, c);

        break;

    case RBD_AIO_READ:

        r = rbd_aio_read(s->image, off, size, buf, c);

        break;

    case RBD_AIO_DISCARD:

        r = rbd_aio_discard_wrapper(s->image, off, size, c);

        break;

    case RBD_AIO_FLUSH:

        r = rbd_aio_flush_wrapper(s->image, c);

        break;

    default:

        r = -EINVAL;

    }

    if (r < 0) {

        goto failed;

    }

    return &acb->common;

failed:

    g_free(rcb);

    qemu_aio_release(acb);

    return NULL;

}


static inline void RENAME(initFilter)(int16_t *filter, int16_t *filterPos, int *filterSize, int xInc,

				      int srcW, int dstW, int filterAlign, int one)

{

	int i;

#ifdef HAVE_MMX

	asm volatile("emms\n\t"::: "memory"); //FIXME this shouldnt be required but it IS (even for non mmx versions)

#endif

	if(ABS(xInc - 0x10000) <10) // unscaled

	{

		int i;

		*filterSize= (1 +(filterAlign-1)) & (~(filterAlign-1)); // 1 or 4 normaly

		for(i=0; i<dstW*(*filterSize); i++) filter[i]=0;

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

		{

			filter[i*(*filterSize)]=1;

			filterPos[i]=i;

		}

	}

	else if(xInc <= (1<<16) || sws_flags==SWS_FAST_BILINEAR) // upscale

	{

		int i;

		int xDstInSrc;

		if(sws_flags==SWS_BICUBIC) *filterSize= 4;

		else			   *filterSize= 2;

//		printf("%d %d %d\n", filterSize, srcW, dstW);

		*filterSize= (*filterSize +(filterAlign-1)) & (~(filterAlign-1));

		xDstInSrc= xInc - 0x8000;

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

		{

			int xx= (xDstInSrc>>16) - (*filterSize>>1) + 1;

			int j;

			filterPos[i]= xx;

			if(sws_flags == SWS_BICUBIC)

			{

				double d= ABS(((xx+1)<<16) - xDstInSrc)/(double)(1<<16);

//				int coeff;

				int y1,y2,y3,y4;

				double A= -0.75;

					// Equation is from VirtualDub

		y1 = (int)floor(0.5 + (        +     A*d -       2.0*A*d*d +       A*d*d*d) * 16384.0);

		y2 = (int)floor(0.5 + (+ 1.0             -     (A+3.0)*d*d + (A+2.0)*d*d*d) * 16384.0);

		y3 = (int)floor(0.5 + (        -     A*d + (2.0*A+3.0)*d*d - (A+2.0)*d*d*d) * 16384.0);

		y4 = (int)floor(0.5 + (                  +           A*d*d -       A*d*d*d) * 16384.0);

//				printf("%d %d %d \n", coeff, (int)d, xDstInSrc);

				filter[i*(*filterSize) + 0]= y1;

				filter[i*(*filterSize) + 1]= y2;

				filter[i*(*filterSize) + 2]= y3;

				filter[i*(*filterSize) + 3]= y4;

//				printf("%1.3f %d, %d, %d, %d\n",d , y1, y2, y3, y4);

			}

			else

			{

				for(j=0; j<*filterSize; j++)

				{

					double d= ABS((xx<<16) - xDstInSrc)/(double)(1<<16);

					int coeff;

					coeff= (int)(0.5 + (1.0 - d)*(1<<14));

					if(coeff<0) coeff=0;

	//				printf("%d %d %d \n", coeff, (int)d, xDstInSrc);

					filter[i*(*filterSize) + j]= coeff;

					xx++;

				}

			}

			xDstInSrc+= xInc;

		}

	}

	else // downscale

	{

		int xDstInSrc;

		if(sws_flags==SWS_BICUBIC) *filterSize= (int)ceil(1 + 4.0*srcW / (double)dstW);

		else			   *filterSize= (int)ceil(1 + 2.0*srcW / (double)dstW);

//		printf("%d %d %d\n", *filterSize, srcW, dstW);

		*filterSize= (*filterSize +(filterAlign-1)) & (~(filterAlign-1));

		xDstInSrc= xInc - 0x8000;

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

		{

			int xx= (int)((double)xDstInSrc/(double)(1<<16) - *filterSize*0.5 + 0.5);

			int j;

			filterPos[i]= xx;

			for(j=0; j<*filterSize; j++)

			{

				double d= ABS((xx<<16) - xDstInSrc)/(double)xInc;

				int coeff;

				if(sws_flags == SWS_BICUBIC)

				{

					double A= -0.75;

//					d*=2;

					// Equation is from VirtualDub

					if(d<1.0)

						coeff = (int)floor(0.5 + (1.0 - (A+3.0)*d*d

						        + (A+2.0)*d*d*d) * (1<<14));

					else if(d<2.0)

						coeff = (int)floor(0.5 + (-4.0*A + 8.0*A*d

						        - 5.0*A*d*d + A*d*d*d) * (1<<14));

					else

						coeff=0;

				}

				else

				{

					coeff= (int)(0.5 + (1.0 - d)*(1<<14));

					if(coeff<0) coeff=0;

				}

//				if(filterAlign==1) printf("%d %d %d \n", coeff, (int)d, xDstInSrc);

				filter[i*(*filterSize) + j]= coeff;

				xx++;

			}

			xDstInSrc+= xInc;

		}

	}

	//fix borders

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

	{

		int j;

		if(filterPos[i] < 0)

		{

			// Move filter coeffs left to compensate for filterPos

			for(j=1; j<*filterSize; j++)

			{

				int left= MAX(j + filterPos[i], 0);

				filter[i*(*filterSize) + left] += filter[i*(*filterSize) + j];

				filter[i*(*filterSize) + j]=0;

			}

			filterPos[i]= 0;

		}

		if(filterPos[i] + *filterSize > srcW)

		{

			int shift= filterPos[i] + *filterSize - srcW;

			// Move filter coeffs right to compensate for filterPos

			for(j=*filterSize-2; j>=0; j--)

			{

				int right= MIN(j + shift, *filterSize-1);

				filter[i*(*filterSize) +right] += filter[i*(*filterSize) +j];

				filter[i*(*filterSize) +j]=0;

			}

			filterPos[i]= srcW - *filterSize;

		}

	}

	//FIXME try to align filterpos if possible / try to shift filterpos to put zeros at the end

	// and skip these than later

	//Normalize

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

	{

		int j;

		double sum=0;

		double scale= one;

		for(j=0; j<*filterSize; j++)

		{

			sum+= filter[i*(*filterSize) + j];

		}

		scale/= sum;

		for(j=0; j<*filterSize; j++)

		{

			filter[i*(*filterSize) + j]= (int)(filter[i*(*filterSize) + j]*scale);

		}

	}

}


static void latm_write_frame_header(AVFormatContext *s, PutBitContext *bs)

{

    LATMContext *ctx = s->priv_data;

    AVCodecContext *avctx = s->streams[0]->codec;

    GetBitContext gb;

    int header_size;

    /* AudioMuxElement */

    put_bits(bs, 1, !!ctx->counter);

    if (!ctx->counter) {

        init_get_bits(&gb, avctx->extradata, avctx->extradata_size * 8);

        /* StreamMuxConfig */

        put_bits(bs, 1, 0); /* audioMuxVersion */

        put_bits(bs, 1, 1); /* allStreamsSameTimeFraming */

        put_bits(bs, 6, 0); /* numSubFrames */

        put_bits(bs, 4, 0); /* numProgram */

        put_bits(bs, 3, 0); /* numLayer */

        /* AudioSpecificConfig */

        if (ctx->object_type == AOT_ALS) {

            header_size = avctx->extradata_size-(ctx->off + 7) >> 3;

            avpriv_copy_bits(bs, &avctx->extradata[ctx->off], header_size);

        } else {

            avpriv_copy_bits(bs, avctx->extradata, ctx->off + 3);

            if (!ctx->channel_conf) {

                avpriv_copy_pce_data(bs, &gb);

            }

        }

        put_bits(bs, 3, 0); /* frameLengthType */

        put_bits(bs, 8, 0xff); /* latmBufferFullness */

        put_bits(bs, 1, 0); /* otherDataPresent */

        put_bits(bs, 1, 0); /* crcCheckPresent */

    }

    ctx->counter++;

    ctx->counter %= ctx->mod;

}


static int decode_frame(AVCodecContext *avctx,

                        void *data, int *data_size,

                        AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    TM2Context * const l = avctx->priv_data;

    AVFrame * const p= (AVFrame*)&l->pic;

    int i, skip, t;

    uint8_t *swbuf;

    swbuf = av_malloc(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);

    if(!swbuf){

        av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer\n");

        return -1;

    }

    p->reference = 1;

    p->buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;

    if(avctx->reget_buffer(avctx, p) < 0){

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

        av_free(swbuf);

        return -1;

    }

    l->dsp.bswap_buf((uint32_t*)swbuf, (const uint32_t*)buf, buf_size >> 2);

    skip = tm2_read_header(l, swbuf);

    if(skip == -1){

        av_free(swbuf);

        return -1;

    }

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

        t = tm2_read_stream(l, swbuf + skip, tm2_stream_order[i]);

        if(t == -1){

            av_free(swbuf);

            return -1;

        }

        skip += t;

    }

    p->key_frame = tm2_decode_blocks(l, p);

    if(p->key_frame)

        p->pict_type = FF_I_TYPE;

    else

        p->pict_type = FF_P_TYPE;

    l->cur = !l->cur;

    *data_size = sizeof(AVFrame);

    *(AVFrame*)data = l->pic;

    av_free(swbuf);

    return buf_size;

}


static void apply_loop_filter(Vp3DecodeContext *s, int plane, int ystart, int yend)

{

    int x, y;

    int *bounding_values= s->bounding_values_array+127;

    int width           = s->fragment_width[!!plane];

    int height          = s->fragment_height[!!plane];

    int fragment        = s->fragment_start        [plane] + ystart * width;

    int stride          = s->current_frame.linesize[plane];

    uint8_t *plane_data = s->current_frame.data    [plane];

    if (!s->flipped_image) stride = -stride;

    plane_data += s->data_offset[plane] + 8*ystart*stride;

    for (y = ystart; y < yend; y++) {

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

            /* This code basically just deblocks on the edges of coded blocks.

             * However, it has to be much more complicated because of the

             * braindamaged deblock ordering used in VP3/Theora. Order matters

             * because some pixels get filtered twice. */

            if( s->all_fragments[fragment].coding_method != MODE_COPY )

            {

                /* do not perform left edge filter for left columns frags */

                if (x > 0) {

                    s->dsp.vp3_h_loop_filter(

                        plane_data + 8*x,

                        stride, bounding_values);

                }

                /* do not perform top edge filter for top row fragments */

                if (y > 0) {

                    s->dsp.vp3_v_loop_filter(

                        plane_data + 8*x,

                        stride, bounding_values);

                }

                /* do not perform right edge filter for right column

                 * fragments or if right fragment neighbor is also coded

                 * in this frame (it will be filtered in next iteration) */

                if ((x < width - 1) &&

                    (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {

                    s->dsp.vp3_h_loop_filter(

                        plane_data + 8*x + 8,

                        stride, bounding_values);

                }

                /* do not perform bottom edge filter for bottom row

                 * fragments or if bottom fragment neighbor is also coded

                 * in this frame (it will be filtered in the next row) */

                if ((y < height - 1) &&

                    (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {

                    s->dsp.vp3_v_loop_filter(

                        plane_data + 8*x + 8*stride,

                        stride, bounding_values);

                }

            }

            fragment++;

        }

        plane_data += 8*stride;

    }

}


static int matroska_probe(AVProbeData *p)

{

    uint64_t total = 0;

    int len_mask = 0x80, size = 1, n = 1, i;

    /* EBML header? */

    if (AV_RB32(p->buf) != EBML_ID_HEADER)

        return 0;

    /* length of header */

    total = p->buf[4];

    while (size <= 8 && !(total & len_mask)) {

        size++;

        len_mask >>= 1;

    }

    if (size > 8)

      return 0;

    total &= (len_mask - 1);

    while (n < size)

        total = (total << 8) | p->buf[4 + n++];

    /* Does the probe data contain the whole header? */

    if (p->buf_size < 4 + size + total)

      return 0;

    /* The header should contain a known document type. For now,

     * we don't parse the whole header but simply check for the

     * availability of that array of characters inside the header.

     * Not fully fool-proof, but good enough. */

    for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {

        int probelen = strlen(matroska_doctypes[i]);

        for (n = 4+size; n <= 4+size+total-probelen; n++)

            if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))

                return AVPROBE_SCORE_MAX;

    }

    // probably valid EBML header but no recognized doctype

    return AVPROBE_SCORE_MAX/2;

}


void palette8torgb32(const uint8_t *src, uint8_t *dst, unsigned num_pixels, const uint8_t *palette)

{

	unsigned i;

/*

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

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

*/

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

	{

		#ifdef WORDS_BIGENDIAN

		dst[3]= palette[ src[i]*4+2 ];

		dst[2]= palette[ src[i]*4+1 ];

		dst[1]= palette[ src[i]*4+0 ];

		#else

		//FIXME slow?

		dst[0]= palette[ src[i]*4+2 ];

		dst[1]= palette[ src[i]*4+1 ];

		dst[2]= palette[ src[i]*4+0 ];

//		dst[3]= 0; /* do we need this cleansing? */

		#endif

		dst+= 4;

	}

}


void visit_get_next_type(Visitor *v, int *obj, const int *qtypes,

                         const char *name, Error **errp)

{

    if (v->get_next_type) {

        v->get_next_type(v, obj, qtypes, name, errp);

    }

}


static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)

{

    /* Return true if it is not valid for us to switch to

     * this CPU mode (ie all the UNPREDICTABLE cases in

     * the ARM ARM CPSRWriteByInstr pseudocode).

    /* Changes to or from Hyp via MSR and CPS are illegal. */

        ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||

         mode == ARM_CPU_MODE_HYP)) {

    switch (mode) {

    case ARM_CPU_MODE_USR:

        return 0;

    case ARM_CPU_MODE_SYS:

    case ARM_CPU_MODE_SVC:

    case ARM_CPU_MODE_ABT:

    case ARM_CPU_MODE_UND:

    case ARM_CPU_MODE_IRQ:

    case ARM_CPU_MODE_FIQ:

        /* Note that we don't implement the IMPDEF NSACR.RFR which in v7

         * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)

        return 0;

    case ARM_CPU_MODE_HYP:

        return !arm_feature(env, ARM_FEATURE_EL2)

            || arm_current_el(env) < 2 || arm_is_secure(env);

    case ARM_CPU_MODE_MON:

        return arm_current_el(env) < 3;

    default:


static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid)

{

    MXFStructuralComponent *source_clip = arg;

    switch(tag) {

    case 0x0202:

        source_clip->duration = avio_rb64(pb);

        break;

    case 0x1201:

        source_clip->start_position = avio_rb64(pb);

        break;

    case 0x1101:

        /* UMID, only get last 16 bytes */

        avio_skip(pb, 16);

        avio_read(pb, source_clip->source_package_uid, 16);

        break;

    case 0x1102:

        source_clip->source_track_id = avio_rb32(pb);

        break;

    }

    return 0;

}


static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)

{

    char buf[1024];

    AVBPrint buf_script;

    OutputStream *ost;

    AVFormatContext *oc;

    int64_t total_size;

    AVCodecContext *enc;

    int frame_number, vid, i;

    double bitrate;

    double speed;

    int64_t pts = INT64_MIN + 1;

    static int64_t last_time = -1;

    static int qp_histogram[52];

    int hours, mins, secs, us;

    float t;

    if (!print_stats && !is_last_report && !progress_avio)

        return;

    if (!is_last_report) {

        if (last_time == -1) {

            last_time = cur_time;

            return;

        }

        if ((cur_time - last_time) < 500000)

            return;

        last_time = cur_time;

    }

    t = (cur_time-timer_start) / 1000000.0;

    oc = output_files[0]->ctx;

    total_size = avio_size(oc->pb);

    if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too

        total_size = avio_tell(oc->pb);

    buf[0] = '\0';

    vid = 0;

    av_bprint_init(&buf_script, 0, 1);

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

        float q = -1;

        ost = output_streams[i];

        enc = ost->enc_ctx;

        if (!ost->stream_copy)

            q = ost->quality / (float) FF_QP2LAMBDA;

        if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {

            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);

            av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",

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

        }

        if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {

            float fps;

            frame_number = ost->frame_number;

            fps = t > 1 ? frame_number / t : 0;

            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",

                     frame_number, fps < 9.95, fps, q);

            av_bprintf(&buf_script, "frame=%d\n", frame_number);

            av_bprintf(&buf_script, "fps=%.1f\n", fps);

            av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",

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

            if (is_last_report)

                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");

            if (qp_hist) {

                int j;

                int qp = lrintf(q);

                if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))

                    qp_histogram[qp]++;

                for (j = 0; j < 32; j++)

                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));

            }

            if ((enc->flags & AV_CODEC_FLAG_PSNR) && (ost->pict_type != AV_PICTURE_TYPE_NONE || is_last_report)) {

                int j;

                double error, error_sum = 0;

                double scale, scale_sum = 0;

                double p;

                char type[3] = { 'Y','U','V' };

                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");

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

                    if (is_last_report) {

                        error = enc->error[j];

                        scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;

                    } else {

                        error = ost->error[j];

                        scale = enc->width * enc->height * 255.0 * 255.0;

                    }

                    if (j)

                        scale /= 4;

                    error_sum += error;

                    scale_sum += scale;

                    p = psnr(error / scale);

                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);

                    av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",

                               ost->file_index, ost->index, type[j] | 32, p);

                }

                p = psnr(error_sum / scale_sum);

                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));

                av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",

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

            }

            vid = 1;

        }

        /* compute min output value */

        if (av_stream_get_end_pts(ost->st) != AV_NOPTS_VALUE)

            pts = FFMAX(pts, av_rescale_q(av_stream_get_end_pts(ost->st),

                                          ost->st->time_base, AV_TIME_BASE_Q));

        if (is_last_report)

            nb_frames_drop += ost->last_dropped;

    }

    secs = FFABS(pts) / AV_TIME_BASE;

    us = FFABS(pts) % AV_TIME_BASE;

    mins = secs / 60;

    secs %= 60;

    hours = mins / 60;

    mins %= 60;

    bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;

    speed = t != 0.0 ? (double)pts / AV_TIME_BASE / t : -1;

    if (total_size < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),

                                 "size=N/A time=");

    else                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),

                                 "size=%8.0fkB time=", total_size / 1024.0);

    if (pts < 0)

        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "-");

    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),

             "%02d:%02d:%02d.%02d ", hours, mins, secs,

             (100 * us) / AV_TIME_BASE);

    if (bitrate < 0) {

        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),"bitrate=N/A");

        av_bprintf(&buf_script, "bitrate=N/A\n");

    }else{

        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),"bitrate=%6.1fkbits/s", bitrate);

        av_bprintf(&buf_script, "bitrate=%6.1fkbits/s\n", bitrate);

    }

    if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");

    else                av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);

    av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);

    av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",

               hours, mins, secs, us);

    if (nb_frames_dup || nb_frames_drop)

        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",

                nb_frames_dup, nb_frames_drop);

    av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);

    av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);

    if (speed < 0) {

        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf)," speed=N/A");

        av_bprintf(&buf_script, "speed=N/A\n");

    } else {

        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf)," speed=%4.3gx", speed);

        av_bprintf(&buf_script, "speed=%4.3gx\n", speed);

    }

    if (print_stats || is_last_report) {

        const char end = is_last_report ? '\n' : '\r';

        if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {

            fprintf(stderr, "%s    %c", buf, end);

        } else

            av_log(NULL, AV_LOG_INFO, "%s    %c", buf, end);

    fflush(stderr);

    }

    if (progress_avio) {

        av_bprintf(&buf_script, "progress=%s\n",

                   is_last_report ? "end" : "continue");

        avio_write(progress_avio, buf_script.str,

                   FFMIN(buf_script.len, buf_script.size - 1));

        avio_flush(progress_avio);

        av_bprint_finalize(&buf_script, NULL);

        if (is_last_report) {

            avio_closep(&progress_avio);

        }

    }

    if (is_last_report)

        print_final_stats(total_size);

}


static int htab_load(QEMUFile *f, void *opaque, int version_id)

{

    sPAPRMachineState *spapr = opaque;

    uint32_t section_hdr;

    int fd = -1;

    if (version_id < 1 || version_id > 1) {

        error_report("htab_load() bad version");

        return -EINVAL;

    }

    section_hdr = qemu_get_be32(f);

    if (section_hdr) {

        Error *local_err;

        /* First section gives the htab size */

        spapr_reallocate_hpt(spapr, section_hdr, &local_err);

        if (local_err) {

            error_report_err(local_err);

            return -EINVAL;

        }

        return 0;

    }

    if (!spapr->htab) {

        assert(kvm_enabled());

        fd = kvmppc_get_htab_fd(true);

        if (fd < 0) {

            error_report("Unable to open fd to restore KVM hash table: %s",

                         strerror(errno));

        }

    }

    while (true) {

        uint32_t index;

        uint16_t n_valid, n_invalid;

        index = qemu_get_be32(f);

        n_valid = qemu_get_be16(f);

        n_invalid = qemu_get_be16(f);

        if ((index == 0) && (n_valid == 0) && (n_invalid == 0)) {

            /* End of Stream */

            break;

        }

        if ((index + n_valid + n_invalid) >

            (HTAB_SIZE(spapr) / HASH_PTE_SIZE_64)) {

            /* Bad index in stream */

            error_report(

                "htab_load() bad index %d (%hd+%hd entries) in htab stream (htab_shift=%d)",

                index, n_valid, n_invalid, spapr->htab_shift);

            return -EINVAL;

        }

        if (spapr->htab) {

            if (n_valid) {

                qemu_get_buffer(f, HPTE(spapr->htab, index),

                                HASH_PTE_SIZE_64 * n_valid);

            }

            if (n_invalid) {

                memset(HPTE(spapr->htab, index + n_valid), 0,

                       HASH_PTE_SIZE_64 * n_invalid);

            }

        } else {

            int rc;

            assert(fd >= 0);

            rc = kvmppc_load_htab_chunk(f, fd, index, n_valid, n_invalid);

            if (rc < 0) {

                return rc;

            }

        }

    }

    if (!spapr->htab) {

        assert(fd >= 0);

        close(fd);

    }

    return 0;

}


static av_cold void dump_enc_cfg(AVCodecContext *avctx,

                                 const struct vpx_codec_enc_cfg *cfg)

{

    int width = -30;

    int level = AV_LOG_DEBUG;

    av_log(avctx, level, "vpx_codec_enc_cfg\n");

    av_log(avctx, level, "generic settings\n"

           "  %*s%u\n  %*s%u\n  %*s%u\n  %*s%u\n  %*s%u\n"

#if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_IMG_FMT_HIGHBITDEPTH)

           "  %*s%u\n  %*s%u\n"

#endif

           "  %*s{%u/%u}\n  %*s%u\n  %*s%d\n  %*s%u\n",

           width, "g_usage:",           cfg->g_usage,

           width, "g_threads:",         cfg->g_threads,

           width, "g_profile:",         cfg->g_profile,

           width, "g_w:",               cfg->g_w,

           width, "g_h:",               cfg->g_h,

#if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_IMG_FMT_HIGHBITDEPTH)

           width, "g_bit_depth:",       cfg->g_bit_depth,

           width, "g_input_bit_depth:", cfg->g_input_bit_depth,

#endif

           width, "g_timebase:",        cfg->g_timebase.num, cfg->g_timebase.den,

           width, "g_error_resilient:", cfg->g_error_resilient,

           width, "g_pass:",            cfg->g_pass,

           width, "g_lag_in_frames:",   cfg->g_lag_in_frames);

    av_log(avctx, level, "rate control settings\n"

           "  %*s%u\n  %*s%u\n  %*s%u\n  %*s%u\n"

           "  %*s%d\n  %*s%p(%"SIZE_SPECIFIER")\n  %*s%u\n",

           width, "rc_dropframe_thresh:",   cfg->rc_dropframe_thresh,

           width, "rc_resize_allowed:",     cfg->rc_resize_allowed,

           width, "rc_resize_up_thresh:",   cfg->rc_resize_up_thresh,

           width, "rc_resize_down_thresh:", cfg->rc_resize_down_thresh,

           width, "rc_end_usage:",          cfg->rc_end_usage,

           width, "rc_twopass_stats_in:",   cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,

           width, "rc_target_bitrate:",     cfg->rc_target_bitrate);

    av_log(avctx, level, "quantizer settings\n"

           "  %*s%u\n  %*s%u\n",

           width, "rc_min_quantizer:", cfg->rc_min_quantizer,

           width, "rc_max_quantizer:", cfg->rc_max_quantizer);

    av_log(avctx, level, "bitrate tolerance\n"

           "  %*s%u\n  %*s%u\n",

           width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,

           width, "rc_overshoot_pct:",  cfg->rc_overshoot_pct);

    av_log(avctx, level, "decoder buffer model\n"

            "  %*s%u\n  %*s%u\n  %*s%u\n",

            width, "rc_buf_sz:",         cfg->rc_buf_sz,

            width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,

            width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);

    av_log(avctx, level, "2 pass rate control settings\n"

           "  %*s%u\n  %*s%u\n  %*s%u\n",

           width, "rc_2pass_vbr_bias_pct:",       cfg->rc_2pass_vbr_bias_pct,

           width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,

           width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);

    av_log(avctx, level, "keyframing settings\n"

           "  %*s%d\n  %*s%u\n  %*s%u\n",

           width, "kf_mode:",     cfg->kf_mode,

           width, "kf_min_dist:", cfg->kf_min_dist,

           width, "kf_max_dist:", cfg->kf_max_dist);

    av_log(avctx, level, "\n");

}


static int mpegps_read_packet(AVFormatContext *s,

                              AVPacket *pkt)

{

    AVStream *st;

    int len, startcode, i, type, codec_id;

    int64_t pts, dts;

 redo:

    len = mpegps_read_pes_header(s, NULL, &startcode, &pts, &dts, 1);

    if (len < 0)

        return len;

    /* now find stream */

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

        st = s->streams[i];

        if (st->id == startcode)

            goto found;

    }

    if (startcode >= 0x1e0 && startcode <= 0x1ef) {

        type = CODEC_TYPE_VIDEO;

        codec_id = CODEC_ID_MPEG2VIDEO;

    } else if (startcode >= 0x1c0 && startcode <= 0x1df) {

        type = CODEC_TYPE_AUDIO;

        codec_id = CODEC_ID_MP2;

    } else if (startcode >= 0x80 && startcode <= 0x9f) {

        type = CODEC_TYPE_AUDIO;

        codec_id = CODEC_ID_AC3;

    } else if (startcode >= 0xa0 && startcode <= 0xbf) {

        type = CODEC_TYPE_AUDIO;

        codec_id = CODEC_ID_PCM_S16BE;

    } else {

    skip:

        /* skip packet */

        url_fskip(&s->pb, len);

        goto redo;

    }

    /* no stream found: add a new stream */

    st = av_new_stream(s, startcode);

    if (!st)

        goto skip;

    st->codec.codec_type = type;

    st->codec.codec_id = codec_id;

    if (codec_id != CODEC_ID_PCM_S16BE)

        st->need_parsing = 1;

 found:

    if (startcode >= 0xa0 && startcode <= 0xbf) {

        int b1, freq;

        /* for LPCM, we just skip the header and consider it is raw

           audio data */

        if (len <= 3)

            goto skip;

        get_byte(&s->pb); /* emphasis (1), muse(1), reserved(1), frame number(5) */

        b1 = get_byte(&s->pb); /* quant (2), freq(2), reserved(1), channels(3) */

        get_byte(&s->pb); /* dynamic range control (0x80 = off) */

        len -= 3;

        freq = (b1 >> 4) & 3;

        st->codec.sample_rate = lpcm_freq_tab[freq];

        st->codec.channels = 1 + (b1 & 7);

        st->codec.bit_rate = st->codec.channels * st->codec.sample_rate * 2;

    }

    av_new_packet(pkt, len);

    get_buffer(&s->pb, pkt->data, pkt->size);

    pkt->pts = pts;

    pkt->dts = dts;

    pkt->stream_index = st->index;

#if 0

    printf("%d: pts=%0.3f dts=%0.3f\n",

           pkt->stream_index, pkt->pts / 90000.0, pkt->dts / 90000.0);

#endif

    return 0;

}


static void get_downmix_coeffs(AC3DecodeContext *ctx)

{

    int from = ctx->bsi.acmod;

    int to = ctx->output;

    float clev = clevs[ctx->bsi.cmixlev];

    float slev = slevs[ctx->bsi.surmixlev];

    ac3_audio_block *ab = &ctx->audio_block;

    if (to == AC3_OUTPUT_UNMODIFIED)

        return 0;

    switch (from) {

        case AC3_INPUT_DUALMONO:

            switch (to) {

                case AC3_OUTPUT_MONO:

                case AC3_OUTPUT_STEREO: /* We Assume that sum of both mono channels is requested */

                    ab->chcoeffs[0] *= LEVEL_MINUS_6DB;

                    ab->chcoeffs[1] *= LEVEL_MINUS_6DB;

                    break;

            }

            break;

        case AC3_INPUT_MONO:

            switch (to) {

                case AC3_OUTPUT_STEREO:

                    ab->chcoeffs[0] *= LEVEL_MINUS_3DB;

                    break;

            }

            break;

        case AC3_INPUT_STEREO:

            switch (to) {

                case AC3_OUTPUT_MONO:

                    ab->chcoeffs[0] *= LEVEL_MINUS_3DB;

                    ab->chcoeffs[1] *= LEVEL_MINUS_3DB;

                    break;

            }

            break;

        case AC3_INPUT_3F:

            switch (to) {

                case AC3_OUTPUT_MONO:

                    ab->chcoeffs[0] *= LEVEL_MINUS_3DB;

                    ab->chcoeffs[2] *= LEVEL_MINUS_3DB;

                    ab->chcoeffs[1] *= clev * LEVEL_PLUS_3DB;

                    break;

                case AC3_OUTPUT_STEREO:

                    ab->chcoeffs[1] *= clev;

                    break;

            }

            break;

        case AC3_INPUT_2F_1R:

            switch (to) {

                case AC3_OUTPUT_MONO:

                    ab->chcoeffs[0] *= LEVEL_MINUS_3DB;

                    ab->chcoeffs[1] *= LEVEL_MINUS_3DB;

                    ab->chcoeffs[2] *= slev * LEVEL_MINUS_3DB;

                    break;

                case AC3_OUTPUT_STEREO:

                    ab->chcoeffs[2] *= slev * LEVEL_MINUS_3DB;

                    break;

                case AC3_OUTPUT_DOLBY:

                    ab->chcoeffs[2] *= LEVEL_MINUS_3DB;

                    break;

            }

            break;

        case AC3_INPUT_3F_1R:

            switch (to) {

                case AC3_OUTPUT_MONO:

                    ab->chcoeffs[0] *= LEVEL_MINUS_3DB;

                    ab->chcoeffs[2] *= LEVEL_MINUS_3DB;

                    ab->chcoeffs[1] *= clev * LEVEL_PLUS_3DB;

                    ab->chcoeffs[3] *= slev * LEVEL_MINUS_3DB;

                    break;

                case AC3_OUTPUT_STEREO:

                    ab->chcoeffs[1] *= clev;

                    ab->chcoeffs[3] *= slev * LEVEL_MINUS_3DB;

                    break;

                case AC3_OUTPUT_DOLBY:

                    ab->chcoeffs[1] *= LEVEL_MINUS_3DB;

                    ab->chcoeffs[3] *= LEVEL_MINUS_3DB;

                    break;

            }

            break;

        case AC3_INPUT_2F_2R:

            switch (to) {

                case AC3_OUTPUT_MONO:

                    ab->chcoeffs[0] *= LEVEL_MINUS_3DB;

                    ab->chcoeffs[1] *= LEVEL_MINUS_3DB;

                    ab->chcoeffs[2] *= slev * LEVEL_MINUS_3DB;

                    ab->chcoeffs[3] *= slev * LEVEL_MINUS_3DB;

                    break;

                case AC3_OUTPUT_STEREO:

                    ab->chcoeffs[2] *= slev;

                    ab->chcoeffs[3] *= slev;

                    break;

                case AC3_OUTPUT_DOLBY:

                    ab->chcoeffs[2] *= LEVEL_MINUS_3DB;

                    ab->chcoeffs[3] *= LEVEL_MINUS_3DB;

                    break;

            }

            break;

        case AC3_INPUT_3F_2R:

            switch (to) {

                case AC3_OUTPUT_MONO:

                    ab->chcoeffs[0] *= LEVEL_MINUS_3DB;

                    ab->chcoeffs[2] *= LEVEL_MINUS_3DB;

                    ab->chcoeffs[1] *= clev * LEVEL_PLUS_3DB;

                    ab->chcoeffs[3] *= slev * LEVEL_MINUS_3DB;

                    ab->chcoeffs[4] *= slev * LEVEL_MINUS_3DB;

                    break;

                case AC3_OUTPUT_STEREO:

                    ab->chcoeffs[1] *= clev;

                    ab->chcoeffs[3] *= slev;

                    ab->chcoeffs[4] *= slev;

                    break;

                case AC3_OUTPUT_DOLBY:

                    ab->chcoeffs[1] *= LEVEL_MINUS_3DB;

                    ab->chcoeffs[3] *= LEVEL_MINUS_3DB;

                    ab->chcoeffs[4] *= LEVEL_MINUS_3DB;

                    break;

            }

            break;

    }

}


static av_cold void dsputil_init_mmx(DSPContext *c, AVCodecContext *avctx,

                                     int mm_flags)

{

    const int high_bit_depth = avctx->bits_per_raw_sample > 8;

#if HAVE_INLINE_ASM

    c->put_pixels_clamped        = ff_put_pixels_clamped_mmx;

    c->put_signed_pixels_clamped = ff_put_signed_pixels_clamped_mmx;

    c->add_pixels_clamped        = ff_add_pixels_clamped_mmx;

    if (!high_bit_depth) {

        c->clear_block  = clear_block_mmx;

        c->clear_blocks = clear_blocks_mmx;

        c->draw_edges   = draw_edges_mmx;

        SET_HPEL_FUNCS(put,        [0], 16, mmx);

        SET_HPEL_FUNCS(put_no_rnd, [0], 16, mmx);

        SET_HPEL_FUNCS(avg,        [0], 16, mmx);

        SET_HPEL_FUNCS(avg_no_rnd,    , 16, mmx);

        SET_HPEL_FUNCS(put,        [1],  8, mmx);

        SET_HPEL_FUNCS(put_no_rnd, [1],  8, mmx);

        SET_HPEL_FUNCS(avg,        [1],  8, mmx);

        switch (avctx->idct_algo) {

        case FF_IDCT_AUTO:

        case FF_IDCT_SIMPLEMMX:

            c->idct_put              = ff_simple_idct_put_mmx;

            c->idct_add              = ff_simple_idct_add_mmx;

            c->idct                  = ff_simple_idct_mmx;

            c->idct_permutation_type = FF_SIMPLE_IDCT_PERM;

            break;

        case FF_IDCT_XVIDMMX:

            c->idct_put              = ff_idct_xvid_mmx_put;

            c->idct_add              = ff_idct_xvid_mmx_add;

            c->idct                  = ff_idct_xvid_mmx;

            break;

        }

    }

    c->gmc = gmc_mmx;

    c->add_bytes = add_bytes_mmx;

    if (CONFIG_H263_DECODER || CONFIG_H263_ENCODER) {

        c->h263_v_loop_filter = h263_v_loop_filter_mmx;

        c->h263_h_loop_filter = h263_h_loop_filter_mmx;

    }

#endif /* HAVE_INLINE_ASM */

#if HAVE_YASM

    c->vector_clip_int32 = ff_vector_clip_int32_mmx;

#endif

}


static int pci_nic_uninit(PCIDevice *dev)

{

    PCIEEPRO100State *d = DO_UPCAST(PCIEEPRO100State, dev, dev);

    EEPRO100State *s = &d->eepro100;

    cpu_unregister_io_memory(s->mmio_index);

    return 0;

}


static int kvm_getput_regs(CPUState *env, int set)

{

    struct kvm_regs regs;

    int ret = 0;

    if (!set) {

        ret = kvm_vcpu_ioctl(env, KVM_GET_REGS, &regs);

        if (ret < 0)

            return ret;

    }

    kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);

    kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);

    kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);

    kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);

    kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);

    kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);

    kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);

    kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);

#ifdef TARGET_X86_64

    kvm_getput_reg(&regs.r8, &env->regs[8], set);

    kvm_getput_reg(&regs.r9, &env->regs[9], set);

    kvm_getput_reg(&regs.r10, &env->regs[10], set);

    kvm_getput_reg(&regs.r11, &env->regs[11], set);

    kvm_getput_reg(&regs.r12, &env->regs[12], set);

    kvm_getput_reg(&regs.r13, &env->regs[13], set);

    kvm_getput_reg(&regs.r14, &env->regs[14], set);

    kvm_getput_reg(&regs.r15, &env->regs[15], set);

#endif

    kvm_getput_reg(&regs.rflags, &env->eflags, set);

    kvm_getput_reg(&regs.rip, &env->eip, set);

    if (set)

        ret = kvm_vcpu_ioctl(env, KVM_SET_REGS, &regs);

    return ret;

}


static void visitor_reset(TestOutputVisitorData *data)

{

    visitor_output_teardown(data, NULL);

    visitor_output_setup(data, NULL);

}


static int qemu_reset_requested(void)

{

    int r = reset_requested;

    reset_requested = 0;

    return r;

}


void cpu_interrupt(CPUState *s)

{

    s->interrupt_request = 1;

}


static void test_io_channel_setup_async(SocketAddressLegacy *listen_addr,

                                        SocketAddressLegacy *connect_addr,

                                        QIOChannel **src,

                                        QIOChannel **dst)

{

    QIOChannelSocket *lioc;

    struct TestIOChannelData data;

    data.loop = g_main_loop_new(g_main_context_default(),

                                TRUE);

    lioc = qio_channel_socket_new();

    qio_channel_socket_listen_async(

        lioc, listen_addr,

        test_io_channel_complete, &data, NULL);

    g_main_loop_run(data.loop);

    g_main_context_iteration(g_main_context_default(), FALSE);

    g_assert(!data.err);

    if (listen_addr->type == SOCKET_ADDRESS_LEGACY_KIND_INET) {

        SocketAddressLegacy *laddr = qio_channel_socket_get_local_address(

            lioc, &error_abort);

        g_free(connect_addr->u.inet.data->port);

        connect_addr->u.inet.data->port = g_strdup(laddr->u.inet.data->port);

        qapi_free_SocketAddressLegacy(laddr);

    }

    *src = QIO_CHANNEL(qio_channel_socket_new());

    qio_channel_socket_connect_async(

        QIO_CHANNEL_SOCKET(*src), connect_addr,

        test_io_channel_complete, &data, NULL);

    g_main_loop_run(data.loop);

    g_main_context_iteration(g_main_context_default(), FALSE);

    g_assert(!data.err);

    qio_channel_wait(QIO_CHANNEL(lioc), G_IO_IN);

    *dst = QIO_CHANNEL(qio_channel_socket_accept(lioc, &error_abort));

    g_assert(*dst);

    qio_channel_set_delay(*src, false);

    test_io_channel_set_socket_bufs(*src, *dst);

    object_unref(OBJECT(lioc));

    g_main_loop_unref(data.loop);

}


static int send_palette_rect(VncState *vs, int w, int h, struct QDict *palette)

{

    int stream = 2;

    int level = tight_conf[vs->tight_compression].idx_zlib_level;

    int colors;

    size_t bytes;

    colors = qdict_size(palette);

    vnc_write_u8(vs, (stream | VNC_TIGHT_EXPLICIT_FILTER) << 4);

    vnc_write_u8(vs, VNC_TIGHT_FILTER_PALETTE);

    vnc_write_u8(vs, colors - 1);

    switch(vs->clientds.pf.bytes_per_pixel) {

    case 4:

    {

        size_t old_offset, offset;

        uint32_t header[qdict_size(palette)];

        struct palette_cb_priv priv = { vs, (uint8_t *)header };

        old_offset = vs->output.offset;

        qdict_iter(palette, write_palette, &priv);

        vnc_write(vs, header, sizeof(header));

        if (vs->tight_pixel24) {

            tight_pack24(vs, vs->output.buffer + old_offset, colors, &offset);

            vs->output.offset = old_offset + offset;

        }

        tight_encode_indexed_rect32(vs->tight.buffer, w * h, palette);

        break;

    }

    case 2:

    {

        uint16_t header[qdict_size(palette)];

        struct palette_cb_priv priv = { vs, (uint8_t *)header };

        qdict_iter(palette, write_palette, &priv);

        vnc_write(vs, header, sizeof(header));

        tight_encode_indexed_rect16(vs->tight.buffer, w * h, palette);

        break;

    }

    default:

        return -1; /* No palette for 8bits colors */

        break;

    }

    bytes = w * h;

    vs->tight.offset = bytes;

    bytes = tight_compress_data(vs, stream, bytes,

                                level, Z_DEFAULT_STRATEGY);

    return (bytes >= 0);

}


static inline ioreq_t *xen_vcpu_ioreq(shared_iopage_t *shared_page, int vcpu)

{

    return &shared_page->vcpu_iodata[vcpu].vp_ioreq;

}


static void cirrus_bitblt_fill_nop(CirrusVGAState *s,

                                   uint8_t *dst,

                                   int dstpitch, int bltwidth,int bltheight)

{

}


static int copy_parameter_set(void **to, void **from, int count, int size)

{

    int i;

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

        if (to[i] && !from[i]) {

            av_freep(&to[i]);

        } else if (from[i] && !to[i]) {

            to[i] = av_malloc(size);

            if (!to[i])

                return AVERROR(ENOMEM);

        }

        if (from[i])

            memcpy(to[i], from[i], size);

    }

    return 0;

}


static int i2c_slave_qdev_init(DeviceState *dev)

{

    I2CSlave *s = I2C_SLAVE(dev);

    I2CSlaveClass *sc = I2C_SLAVE_GET_CLASS(s);

    return sc->init(s);

}


static void vtd_iommu_replay(MemoryRegion *mr, IOMMUNotifier *n)

{

    VTDAddressSpace *vtd_as = container_of(mr, VTDAddressSpace, iommu);

    IntelIOMMUState *s = vtd_as->iommu_state;

    uint8_t bus_n = pci_bus_num(vtd_as->bus);

    VTDContextEntry ce;

    if (vtd_dev_to_context_entry(s, bus_n, vtd_as->devfn, &ce) == 0) {

        /*

         * Scanned a valid context entry, walk over the pages and

         * notify when needed.

         */

        trace_vtd_replay_ce_valid(bus_n, PCI_SLOT(vtd_as->devfn),

                                  PCI_FUNC(vtd_as->devfn),

                                  VTD_CONTEXT_ENTRY_DID(ce.hi),

                                  ce.hi, ce.lo);

        vtd_page_walk(&ce, 0, ~0ULL, vtd_replay_hook, (void *)n);

    } else {

        trace_vtd_replay_ce_invalid(bus_n, PCI_SLOT(vtd_as->devfn),

                                    PCI_FUNC(vtd_as->devfn));

    }

    return;

}


static void monitor_protocol_emitter(Monitor *mon, QObject *data,

                                     QError *err)

{

    QDict *qmp;

    trace_monitor_protocol_emitter(mon);

    if (!err) {

        /* success response */

        qmp = qdict_new();

        if (data) {

            qobject_incref(data);

            qdict_put_obj(qmp, "return", data);

        } else {

            /* return an empty QDict by default */

            qdict_put(qmp, "return", qdict_new());

        }

    } else {

        /* error response */

        qmp = build_qmp_error_dict(err);

    }

    if (mon->mc->id) {

        qdict_put_obj(qmp, "id", mon->mc->id);

        mon->mc->id = NULL;

    }

    monitor_json_emitter(mon, QOBJECT(qmp));

    QDECREF(qmp);

}


static int msi_msix_setup(XenPCIPassthroughState *s,

                          uint64_t addr,

                          uint32_t data,

                          int *ppirq,

                          bool is_msix,

                          int msix_entry,

                          bool is_not_mapped)

{

    uint8_t gvec = msi_vector(data);

    int rc = 0;

    assert((!is_msix && msix_entry == 0) || is_msix);

    if (gvec == 0) {

        /* if gvec is 0, the guest is asking for a particular pirq that

         * is passed as dest_id */

        *ppirq = msi_ext_dest_id(addr >> 32) | msi_dest_id(addr);

        if (!*ppirq) {

            /* this probably identifies an misconfiguration of the guest,

             * try the emulated path */

            *ppirq = XEN_PT_UNASSIGNED_PIRQ;

        } else {

            XEN_PT_LOG(&s->dev, "requested pirq %d for MSI%s"

                       " (vec: %#x, entry: %#x)\n",

                       *ppirq, is_msix ? "-X" : "", gvec, msix_entry);

        }

    }

    if (is_not_mapped) {

        uint64_t table_base = 0;

        if (is_msix) {

            table_base = s->msix->table_base;

        }

        rc = xc_physdev_map_pirq_msi(xen_xc, xen_domid, XEN_PT_AUTO_ASSIGN,

                                     ppirq, PCI_DEVFN(s->real_device.dev,

                                                      s->real_device.func),

                                     s->real_device.bus,

                                     msix_entry, table_base);

        if (rc) {

            XEN_PT_ERR(&s->dev,

                       "Mapping of MSI%s (err: %i, vec: %#x, entry %#x)\n",

                       is_msix ? "-X" : "", errno, gvec, msix_entry);

            return rc;

        }

    }

    return 0;

}


void virtio_net_set_config_size(VirtIONet *n, uint32_t host_features)

{

    int i, config_size = 0;

    host_features |= (1 << VIRTIO_NET_F_MAC);

    for (i = 0; feature_sizes[i].flags != 0; i++) {

        if (host_features & feature_sizes[i].flags) {

            config_size = MAX(feature_sizes[i].end, config_size);

        }

    }

    n->config_size = config_size;

}


static void virtio_pci_vmstate_change(DeviceState *d, bool running)

{

    VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);

    VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);

    if (running) {

        /* Try to find out if the guest has bus master disabled, but is

           in ready state. Then we have a buggy guest OS. */

        if ((vdev->status & VIRTIO_CONFIG_S_DRIVER_OK) &&

            !(proxy->pci_dev.config[PCI_COMMAND] & PCI_COMMAND_MASTER)) {

            proxy->flags |= VIRTIO_PCI_FLAG_BUS_MASTER_BUG;

        }

        virtio_pci_start_ioeventfd(proxy);

    } else {

        virtio_pci_stop_ioeventfd(proxy);

    }

}


static void ide_dma_cb(void *opaque, int ret)

{

    IDEState *s = opaque;

    int n;

    int64_t sector_num;

    uint64_t offset;

    bool stay_active = false;

    if (ret == -ECANCELED) {

        return;

    }

    if (ret < 0) {

        if (ide_handle_rw_error(s, -ret, ide_dma_cmd_to_retry(s->dma_cmd))) {

            s->bus->dma->aiocb = NULL;

            dma_buf_commit(s, 0);

            return;

        }

    }

    n = s->io_buffer_size >> 9;

    if (n > s->nsector) {

        /* The PRDs were longer than needed for this request. Shorten them so

         * we don't get a negative remainder. The Active bit must remain set

         * after the request completes. */

        n = s->nsector;

        stay_active = true;

    }

    sector_num = ide_get_sector(s);

    if (n > 0) {

        assert(n * 512 == s->sg.size);

        dma_buf_commit(s, s->sg.size);

        sector_num += n;

        ide_set_sector(s, sector_num);

        s->nsector -= n;

    }

    /* end of transfer ? */

    if (s->nsector == 0) {

        s->status = READY_STAT | SEEK_STAT;

        ide_set_irq(s->bus);

        goto eot;

    }

    /* launch next transfer */

    n = s->nsector;

    s->io_buffer_index = 0;

    s->io_buffer_size = n * 512;

    if (s->bus->dma->ops->prepare_buf(s->bus->dma, s->io_buffer_size) < 512) {

        /* The PRDs were too short. Reset the Active bit, but don't raise an

         * interrupt. */

        s->status = READY_STAT | SEEK_STAT;

        dma_buf_commit(s, 0);

        goto eot;

    }

    trace_ide_dma_cb(s, sector_num, n, IDE_DMA_CMD_str(s->dma_cmd));

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

        !ide_sect_range_ok(s, sector_num, n)) {

        ide_dma_error(s);

        block_acct_invalid(blk_get_stats(s->blk), s->acct.type);

        return;

    }

    offset = sector_num << BDRV_SECTOR_BITS;

    switch (s->dma_cmd) {

    case IDE_DMA_READ:

        s->bus->dma->aiocb = dma_blk_read(s->blk, &s->sg, offset,

                                          BDRV_SECTOR_SIZE, ide_dma_cb, s);

        break;

    case IDE_DMA_WRITE:

        s->bus->dma->aiocb = dma_blk_write(s->blk, &s->sg, offset,

                                           BDRV_SECTOR_SIZE, ide_dma_cb, s);

        break;

    case IDE_DMA_TRIM:

        s->bus->dma->aiocb = dma_blk_io(blk_get_aio_context(s->blk),

                                        &s->sg, offset, BDRV_SECTOR_SIZE,

                                        ide_issue_trim, s->blk, ide_dma_cb, s,

                                        DMA_DIRECTION_TO_DEVICE);

        break;

    default:

        abort();

    }

    return;

eot:

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

        block_acct_done(blk_get_stats(s->blk), &s->acct);

    }

    ide_set_inactive(s, stay_active);

}


SSIBus *ssi_create_bus(DeviceState *parent, const char *name)

{

    BusState *bus;

    bus = qbus_create(BUS_TYPE_SSI, sizeof(SSIBus), parent, name);

    return FROM_QBUS(SSIBus, bus);

}