static int process_tns_coeffs(TemporalNoiseShaping *tns, float *tns_coefs_raw,

                              int order, int w, int filt)

{

    int i, j;

    int *idx = tns->coef_idx[w][filt];

    float *lpc = tns->coef[w][filt];

    const int iqfac_p = ((1 << (MAX_LPC_PRECISION-1)) - 0.5)/(M_PI/2.0);

    const int iqfac_m = ((1 << (MAX_LPC_PRECISION-1)) + 0.5)/(M_PI/2.0);

    float temp[TNS_MAX_ORDER] = {0.0f}, out[TNS_MAX_ORDER] = {0.0f};

    /* Quantization */

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

        idx[i] = ceilf(asin(tns_coefs_raw[i])*((tns_coefs_raw[i] >= 0) ? iqfac_p : iqfac_m));

        lpc[i] = 2*sin(idx[i]/((idx[i] >= 0) ? iqfac_p : iqfac_m));

    }

    /* Trim any coeff less than 0.1f from the end */

    for (i = order; i > -1; i--) {

        lpc[i] = (fabs(lpc[i]) > 0.1f) ? lpc[i] : 0.0f;

        if (lpc[i] != 0.0 ) {

            order = i;

            break;

        }

    }

    if (!order)

        return 0;

    /* Step up procedure, convert to LPC coeffs */

    out[0] = 1.0f;

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

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

            temp[j] = out[j] + lpc[i]*out[i-j];

        }

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

            out[j] = temp[j];

        }

        out[i] = lpc[i-1];

    }

    memcpy(lpc, out, TNS_MAX_ORDER*sizeof(float));

    return order;

}


static inline void downmix_3f_to_stereo(float *samples)

{

    int i;

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

        samples[i] += samples[i + 256];

        samples[i + 256] = samples[i + 512];

        samples[i + 512] = 0;

    }

}


static int vfio_set_resample_eventfd(VFIOINTp *intp)

{

    VFIODevice *vbasedev = &intp->vdev->vbasedev;

    struct vfio_irq_set *irq_set;

    int argsz, ret;

    int32_t *pfd;

    argsz = sizeof(*irq_set) + sizeof(*pfd);

    irq_set = g_malloc0(argsz);

    irq_set->argsz = argsz;

    irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_UNMASK;

    irq_set->index = intp->pin;

    irq_set->start = 0;

    irq_set->count = 1;

    pfd = (int32_t *)&irq_set->data;

    *pfd = event_notifier_get_fd(&intp->unmask);

    qemu_set_fd_handler(*pfd, NULL, NULL, NULL);

    ret = ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, irq_set);

    g_free(irq_set);

    if (ret < 0) {

        error_report("vfio: Failed to set resample eventfd: %m");

    }

    return ret;

}


static void test_io_channel_unix_fd_pass(void)

{

    SocketAddress *listen_addr = g_new0(SocketAddress, 1);

    SocketAddress *connect_addr = g_new0(SocketAddress, 1);

    QIOChannel *src, *dst;

    int testfd;

    int fdsend[3];

    int *fdrecv = NULL;

    size_t nfdrecv = 0;

    size_t i;

    char bufsend[12], bufrecv[12];

    struct iovec iosend[1], iorecv[1];

#define TEST_SOCKET "test-io-channel-socket.sock"

#define TEST_FILE "test-io-channel-socket.txt"

    testfd = open(TEST_FILE, O_RDWR|O_TRUNC|O_CREAT, 0700);

    g_assert(testfd != -1);

    fdsend[0] = testfd;

    fdsend[1] = testfd;

    fdsend[2] = testfd;

    listen_addr->type = SOCKET_ADDRESS_KIND_UNIX;

    listen_addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);

    listen_addr->u.q_unix.data->path = g_strdup(TEST_SOCKET);

    connect_addr->type = SOCKET_ADDRESS_KIND_UNIX;

    connect_addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);

    connect_addr->u.q_unix.data->path = g_strdup(TEST_SOCKET);

    test_io_channel_setup_sync(listen_addr, connect_addr, &src, &dst);

    memcpy(bufsend, "Hello World", G_N_ELEMENTS(bufsend));

    iosend[0].iov_base = bufsend;

    iosend[0].iov_len = G_N_ELEMENTS(bufsend);

    iorecv[0].iov_base = bufrecv;

    iorecv[0].iov_len = G_N_ELEMENTS(bufrecv);

    g_assert(qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_FD_PASS));

    g_assert(qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_FD_PASS));

    qio_channel_writev_full(src,

                            iosend,

                            G_N_ELEMENTS(iosend),

                            fdsend,

                            G_N_ELEMENTS(fdsend),

                            &error_abort);

    qio_channel_readv_full(dst,

                           iorecv,

                           G_N_ELEMENTS(iorecv),

                           &fdrecv,

                           &nfdrecv,

                           &error_abort);

    g_assert(nfdrecv == G_N_ELEMENTS(fdsend));

    /* Each recvd FD should be different from sent FD */

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

        g_assert_cmpint(fdrecv[i], !=, testfd);

    }

    /* Each recvd FD should be different from each other */

    g_assert_cmpint(fdrecv[0], !=, fdrecv[1]);

    g_assert_cmpint(fdrecv[0], !=, fdrecv[2]);

    g_assert_cmpint(fdrecv[1], !=, fdrecv[2]);

    /* Check the I/O buf we sent at the same time matches */

    g_assert(memcmp(bufsend, bufrecv, G_N_ELEMENTS(bufsend)) == 0);

    /* Write some data into the FD we received */

    g_assert(write(fdrecv[0], bufsend, G_N_ELEMENTS(bufsend)) ==

             G_N_ELEMENTS(bufsend));

    /* Read data from the original FD and make sure it matches */

    memset(bufrecv, 0, G_N_ELEMENTS(bufrecv));

    g_assert(lseek(testfd, 0, SEEK_SET) == 0);

    g_assert(read(testfd, bufrecv, G_N_ELEMENTS(bufrecv)) ==

             G_N_ELEMENTS(bufrecv));

    g_assert(memcmp(bufsend, bufrecv, G_N_ELEMENTS(bufsend)) == 0);

    object_unref(OBJECT(src));

    object_unref(OBJECT(dst));

    qapi_free_SocketAddress(listen_addr);

    qapi_free_SocketAddress(connect_addr);

    unlink(TEST_SOCKET);

    unlink(TEST_FILE);

    close(testfd);

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

        close(fdrecv[i]);

    }

    g_free(fdrecv);

}


static int raw_open_common(BlockDriverState *bs, const char *filename,

                           int bdrv_flags, int open_flags)

{

    BDRVRawState *s = bs->opaque;

    int fd, ret;

    ret = raw_normalize_devicepath(&filename);

    if (ret != 0) {

        return ret;

    }

    s->open_flags = open_flags | O_BINARY;

    s->open_flags &= ~O_ACCMODE;

    if (bdrv_flags & BDRV_O_RDWR) {

        s->open_flags |= O_RDWR;

    } else {

        s->open_flags |= O_RDONLY;

    }

    /* Use O_DSYNC for write-through caching, no flags for write-back caching,

     * and O_DIRECT for no caching. */

    if ((bdrv_flags & BDRV_O_NOCACHE))

        s->open_flags |= O_DIRECT;

    if (!(bdrv_flags & BDRV_O_CACHE_WB))

        s->open_flags |= O_DSYNC;

    s->fd = -1;

    fd = qemu_open(filename, s->open_flags, 0644);

    if (fd < 0) {

        ret = -errno;

        if (ret == -EROFS)

            ret = -EACCES;

        return ret;

    }

    s->fd = fd;

    s->aligned_buf = NULL;

    if ((bdrv_flags & BDRV_O_NOCACHE)) {

        /*

         * Allocate a buffer for read/modify/write cycles.  Chose the size

         * pessimistically as we don't know the block size yet.

         */

        s->aligned_buf_size = 32 * MAX_BLOCKSIZE;

        s->aligned_buf = qemu_memalign(MAX_BLOCKSIZE, s->aligned_buf_size);

        if (s->aligned_buf == NULL) {

            goto out_close;

        }

    }

    /* We're falling back to POSIX AIO in some cases so init always */

    if (paio_init() < 0) {

        goto out_free_buf;

    }

#ifdef CONFIG_LINUX_AIO

    /*

     * Currently Linux do AIO only for files opened with O_DIRECT

     * specified so check NOCACHE flag too

     */

    if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==

                      (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {

        s->aio_ctx = laio_init();

        if (!s->aio_ctx) {

            goto out_free_buf;

        }

        s->use_aio = 1;

    } else

#endif

    {

#ifdef CONFIG_LINUX_AIO

        s->use_aio = 0;

#endif

    }

#ifdef CONFIG_XFS

    if (platform_test_xfs_fd(s->fd)) {

        s->is_xfs = 1;

    }

#endif

    return 0;

out_free_buf:

    qemu_vfree(s->aligned_buf);

out_close:

    qemu_close(fd);

    return -errno;

}


static int proxy_close(FsContext *ctx, V9fsFidOpenState *fs)

{

    return close(fs->fd);

}


uint64_t ldq_be_phys(target_phys_addr_t addr)

{

    return ldq_phys_internal(addr, DEVICE_BIG_ENDIAN);

}


static hwaddr intel_hda_addr(uint32_t lbase, uint32_t ubase)

{

    hwaddr addr;

    addr = ((uint64_t)ubase << 32) | lbase;

    return addr;

}


static int nbd_send_rep(int csock, uint32_t type, uint32_t opt)

{

    uint64_t magic;

    uint32_t len;

    magic = cpu_to_be64(NBD_REP_MAGIC);

    if (write_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {

        LOG("write failed (rep magic)");

        return -EINVAL;

    }

    opt = cpu_to_be32(opt);

    if (write_sync(csock, &opt, sizeof(opt)) != sizeof(opt)) {

        LOG("write failed (rep opt)");

        return -EINVAL;

    }

    type = cpu_to_be32(type);

    if (write_sync(csock, &type, sizeof(type)) != sizeof(type)) {

        LOG("write failed (rep type)");

        return -EINVAL;

    }

    len = cpu_to_be32(0);

    if (write_sync(csock, &len, sizeof(len)) != sizeof(len)) {

        LOG("write failed (rep data length)");

        return -EINVAL;

    }

    return 0;

}


void virtio_blk_data_plane_create(VirtIODevice *vdev, VirtIOBlkConf *conf,

                                  VirtIOBlockDataPlane **dataplane,

                                  Error **errp)

{

    VirtIOBlockDataPlane *s;

    Error *local_err = NULL;

    BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));

    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);

    *dataplane = NULL;

    if (!conf->data_plane && !conf->iothread) {

        return;

    }

    /* Don't try if transport does not support notifiers. */

    if (!k->set_guest_notifiers || !k->set_host_notifier) {

        error_setg(errp,

                   "device is incompatible with x-data-plane "

                   "(transport does not support notifiers)");

        return;

    }

    /* If dataplane is (re-)enabled while the guest is running there could be

     * block jobs that can conflict.

     */

    if (bdrv_op_is_blocked(conf->conf.bs, BLOCK_OP_TYPE_DATAPLANE,

                           &local_err)) {

        error_setg(errp, "cannot start dataplane thread: %s",

                   error_get_pretty(local_err));

        error_free(local_err);

        return;

    }

    s = g_new0(VirtIOBlockDataPlane, 1);

    s->vdev = vdev;

    s->conf = conf;

    if (conf->iothread) {

        s->iothread = conf->iothread;

        object_ref(OBJECT(s->iothread));

    } else {

        /* Create per-device IOThread if none specified.  This is for

         * x-data-plane option compatibility.  If x-data-plane is removed we

         * can drop this.

         */

        object_initialize(&s->internal_iothread_obj,

                          sizeof(s->internal_iothread_obj),

                          TYPE_IOTHREAD);

        user_creatable_complete(OBJECT(&s->internal_iothread_obj), &error_abort);

        s->iothread = &s->internal_iothread_obj;

    }

    s->ctx = iothread_get_aio_context(s->iothread);

    s->bh = aio_bh_new(s->ctx, notify_guest_bh, s);

    error_setg(&s->blocker, "block device is in use by data plane");

    bdrv_op_block_all(conf->conf.bs, s->blocker);

    bdrv_op_unblock(conf->conf.bs, BLOCK_OP_TYPE_RESIZE, s->blocker);

    bdrv_op_unblock(conf->conf.bs, BLOCK_OP_TYPE_DRIVE_DEL, s->blocker);

    *dataplane = s;

}


uint32_t HELPER(servc)(uint32_t r1, uint64_t r2)

{

    if (sclp_service_call(env, r1, r2)) {

        return 3;

    }

    return 0;

}


void ff_acelp_interpolate(

        int16_t* out,

        const int16_t* in,

        const int16_t* filter_coeffs,

        int precision,

        int frac_pos,

        int filter_length,

        int length)

{

    int n, i;

    assert(pitch_delay_frac >= 0 && pitch_delay_frac < precision);

    for(n=0; n<length; n++)

    {

        int idx = 0;

        int v = 0x4000;

        for(i=0; i<filter_length;)

        {

            /* The reference G.729 and AMR fixed point code performs clipping after

               each of the two following accumulations.

               Since clipping affects only the synthetic OVERFLOW test without

               causing an int type overflow, it was moved outside the loop. */

            /*  R(x):=ac_v[-k+x]

                v += R(n-i)*ff_acelp_interp_filter(t+6i)

                v += R(n+i+1)*ff_acelp_interp_filter(6-t+6i) */

            v += in[n + i] * filter_coeffs[idx + frac_pos];

            idx += precision;

            i++;

            v += in[n - i] * filter_coeffs[idx - frac_pos];

        }

        out[n] = av_clip_int16(v >> 15);

    }

}


static void init_ppc_proc (CPUPPCState *env, ppc_def_t *def)

{

    env->reserve = -1;

    /* Default MMU definitions */

    env->nb_BATs = -1;

    env->nb_tlb = 0;

    env->nb_ways = 0;

    /* XXX: missing:

     * 32 bits PowerPC:

     * - MPC5xx(x)

     * - MPC8xx(x)

     * - RCPU (same as MPC5xx ?)

     */

    spr_register(env, SPR_PVR, "PVR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, SPR_NOACCESS,

                 def->pvr);

    printf("%s: PVR %08x mask %08x => %08x\n", __func__,

           def->pvr, def->pvr_mask, def->pvr & def->pvr_mask);

    switch (def->pvr) {

    /* Embedded PowerPC from IBM                           */

    case CPU_PPC_401A1:   /* 401 A1 family                 */

    case CPU_PPC_401B2:   /* 401 B2 family                 */

    case CPU_PPC_401C2:   /* 401 C2 family                 */

    case CPU_PPC_401D2:   /* 401 D2 family                 */

    case CPU_PPC_401E2:   /* 401 E2 family                 */

    case CPU_PPC_401F2:   /* 401 F2 family                 */

    case CPU_PPC_401G2:   /* 401 G2 family                 */

    case CPU_PPC_IOP480:  /* IOP 480 family                */

    case CPU_PPC_COBRA:   /* IBM Processor for Network Resources */

        gen_spr_generic(env);

        gen_spr_40x(env);

        gen_spr_401_403(env);

#if defined (TODO)

        /* XXX: optional ? */

        gen_spr_compress(env);

#endif

        env->nb_BATs = 0;

        env->nb_tlb = 64;

        env->nb_ways = 1;

        env->id_tlbs = 0;

        /* XXX: TODO: allocate internal IRQ controller */

        break;

    case CPU_PPC_403GA:   /* 403 GA family                 */

    case CPU_PPC_403GB:   /* 403 GB family                 */

    case CPU_PPC_403GC:   /* 403 GC family                 */

    case CPU_PPC_403GCX:  /* 403 GCX family                */

        gen_spr_generic(env);

        gen_spr_40x(env);

        gen_spr_401_403(env);

        gen_spr_403(env);

        env->nb_BATs = 0;

        env->nb_tlb = 64;

        env->nb_ways = 1;

        env->id_tlbs = 0;

        /* XXX: TODO: allocate internal IRQ controller */

        break;

    case CPU_PPC_405CR:   /* 405 GP/CR family              */

    case CPU_PPC_405EP:   /* 405 EP family                 */

    case CPU_PPC_405GPR:  /* 405 GPR family                */

    case CPU_PPC_405D2:   /* 405 D2 family                 */

    case CPU_PPC_405D4:   /* 405 D4 family                 */

        gen_spr_generic(env);

        /* Time base */

        gen_tbl(env);

        gen_spr_40x(env);

        gen_spr_405(env);

        env->nb_BATs = 0;

        env->nb_tlb = 64;

        env->nb_ways = 1;

        env->id_tlbs = 0;

        /* Allocate hardware IRQ controller */

        ppc405_irq_init(env);

        break;

    case CPU_PPC_NPE405H: /* NPe405 H family               */

    case CPU_PPC_NPE405H2:

    case CPU_PPC_NPE405L: /* Npe405 L family               */

        gen_spr_generic(env);

        /* Time base */

        gen_tbl(env);

        gen_spr_40x(env);

        gen_spr_405(env);

        env->nb_BATs = 0;

        env->nb_tlb = 64;

        env->nb_ways = 1;

        env->id_tlbs = 0;

        /* Allocate hardware IRQ controller */

        ppc405_irq_init(env);

        break;

#if defined (TODO)

    case CPU_PPC_STB01000:

#endif

#if defined (TODO)

    case CPU_PPC_STB01010:

#endif

#if defined (TODO)

    case CPU_PPC_STB0210:

#endif

    case CPU_PPC_STB03:   /* STB03 family                  */

#if defined (TODO)

    case CPU_PPC_STB043:  /* STB043 family                  */

#endif

#if defined (TODO)

    case CPU_PPC_STB045:  /* STB045 family                  */

#endif

    case CPU_PPC_STB25:   /* STB25 family                  */

#if defined (TODO)

    case CPU_PPC_STB130:  /* STB130 family                 */

#endif

        gen_spr_generic(env);

        /* Time base */

        gen_tbl(env);

        gen_spr_40x(env);

        gen_spr_405(env);

        env->nb_BATs = 0;

        env->nb_tlb = 64;

        env->nb_ways = 1;

        env->id_tlbs = 0;

        /* Allocate hardware IRQ controller */

        ppc405_irq_init(env);

        break;

    case CPU_PPC_440EP:   /* 440 EP family                 */

    case CPU_PPC_440GP:   /* 440 GP family                 */

    case CPU_PPC_440GX:   /* 440 GX family                 */

    case CPU_PPC_440GXc:  /* 440 GXc family                */

    case CPU_PPC_440GXf:  /* 440 GXf family                */

    case CPU_PPC_440SP:   /* 440 SP family                 */

    case CPU_PPC_440SP2:

    case CPU_PPC_440SPE:  /* 440 SPE family                */

        gen_spr_generic(env);

        /* Time base */

        gen_tbl(env);

        gen_spr_BookE(env);

        gen_spr_440(env);

        env->nb_BATs = 0;

        env->nb_tlb = 64;

        env->nb_ways = 1;

        env->id_tlbs = 0;

        /* XXX: TODO: allocate internal IRQ controller */

        break;

    /* Embedded PowerPC from Freescale                     */

#if defined (TODO)

    case CPU_PPC_5xx:

        break;

#endif

#if defined (TODO)

    case CPU_PPC_8xx:     /* MPC821 / 823 / 850 / 860      */

        break;

#endif

#if defined (TODO)

    case CPU_PPC_82xx_HIP3:    /* MPC8240 / 8260                */

    case CPU_PPC_82xx_HIP4:    /* MPC8240 / 8260                */

        break;

#endif

#if defined (TODO)

    case CPU_PPC_827x:    /* MPC 827x / 828x               */

        break;

#endif

    /* XXX: Use MPC8540 PVR to implement a test PowerPC BookE target */

    case CPU_PPC_e500v110:

    case CPU_PPC_e500v120:

    case CPU_PPC_e500v210:

    case CPU_PPC_e500v220:

        gen_spr_generic(env);

        /* Time base */

        gen_tbl(env);

        gen_spr_BookE(env);

        gen_spr_BookE_FSL(env);

        env->nb_BATs = 0;

        env->nb_tlb = 64;

        env->nb_ways = 1;

        env->id_tlbs = 0;

        /* XXX: TODO: allocate internal IRQ controller */

        break;

#if defined (TODO)

    case CPU_PPC_e600:

        break;

#endif

    /* 32 bits PowerPC                                     */

    case CPU_PPC_601:     /* PowerPC 601                   */

        gen_spr_generic(env);

        gen_spr_ne_601(env);

        gen_spr_601(env);

        /* Hardware implementation registers */

        /* XXX : not implemented */

        spr_register(env, SPR_HID0, "HID0",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

        spr_register(env, SPR_HID1, "HID1",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

        spr_register(env, SPR_601_HID2, "HID2",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

        spr_register(env, SPR_601_HID5, "HID5",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

#if 0 /* ? */

        spr_register(env, SPR_601_HID15, "HID15",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

#endif

        env->nb_tlb = 64;

        env->nb_ways = 2;

        env->id_tlbs = 0;

        env->id_tlbs = 0;

        /* XXX: TODO: allocate internal IRQ controller */

        break;

    case CPU_PPC_602:     /* PowerPC 602                   */

        gen_spr_generic(env);

        gen_spr_ne_601(env);

        /* Memory management */

        gen_low_BATs(env);

        /* Time base */

        gen_tbl(env);

        gen_6xx_7xx_soft_tlb(env, 64, 2);

        gen_spr_602(env);

        /* hardware implementation registers */

        /* XXX : not implemented */

        spr_register(env, SPR_HID0, "HID0",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

        spr_register(env, SPR_HID1, "HID1",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* Allocate hardware IRQ controller */

        ppc6xx_irq_init(env);

        break;

    case CPU_PPC_603:     /* PowerPC 603                   */

    case CPU_PPC_603E:    /* PowerPC 603e                  */

    case CPU_PPC_603E7v:

    case CPU_PPC_603E7v2:

    case CPU_PPC_603P:    /* PowerPC 603p                  */

    case CPU_PPC_603R:    /* PowerPC 603r                  */

        gen_spr_generic(env);

        gen_spr_ne_601(env);

        /* Memory management */

        gen_low_BATs(env);

        /* Time base */

        gen_tbl(env);

        gen_6xx_7xx_soft_tlb(env, 64, 2);

        gen_spr_603(env);

        /* hardware implementation registers */

        /* XXX : not implemented */

        spr_register(env, SPR_HID0, "HID0",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

        spr_register(env, SPR_HID1, "HID1",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* Allocate hardware IRQ controller */

        ppc6xx_irq_init(env);

        break;

    case CPU_PPC_G2:      /* PowerPC G2 family             */

    case CPU_PPC_G2H4:

    case CPU_PPC_G2gp:

    case CPU_PPC_G2ls:

    case CPU_PPC_G2LE:    /* PowerPC G2LE family           */

    case CPU_PPC_G2LEgp:

    case CPU_PPC_G2LEls:

        gen_spr_generic(env);

        gen_spr_ne_601(env);

        /* Memory management */

        gen_low_BATs(env);

        /* Time base */

        gen_tbl(env);

        /* Memory management */

        gen_high_BATs(env);

        gen_6xx_7xx_soft_tlb(env, 64, 2);

        gen_spr_G2_755(env);

        gen_spr_G2(env);

        /* Hardware implementation register */

        /* XXX : not implemented */

        spr_register(env, SPR_HID0, "HID0",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

        spr_register(env, SPR_HID1, "HID1",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

        spr_register(env, SPR_HID2, "HID2",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* Allocate hardware IRQ controller */

        ppc6xx_irq_init(env);

        break;

    case CPU_PPC_604:     /* PowerPC 604                   */

    case CPU_PPC_604E:    /* PowerPC 604e                  */

    case CPU_PPC_604R:    /* PowerPC 604r                  */

        gen_spr_generic(env);

        gen_spr_ne_601(env);

        /* Memory management */

        gen_low_BATs(env);

        /* Time base */

        gen_tbl(env);

        gen_spr_604(env);

        /* Hardware implementation registers */

        /* XXX : not implemented */

        spr_register(env, SPR_HID0, "HID0",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

        spr_register(env, SPR_HID1, "HID1",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* Allocate hardware IRQ controller */

        ppc6xx_irq_init(env);

        break;

    case CPU_PPC_74x:     /* PowerPC 740 / 750             */

    case CPU_PPC_740E:

    case CPU_PPC_750E:

    case CPU_PPC_74xP:    /* PowerPC 740P / 750P           */

    case CPU_PPC_750CXE21: /* IBM PowerPC 750cxe            */

    case CPU_PPC_750CXE22:

    case CPU_PPC_750CXE23:

    case CPU_PPC_750CXE24:

    case CPU_PPC_750CXE24b:

    case CPU_PPC_750CXE31:

    case CPU_PPC_750CXE31b:

    case CPU_PPC_750CXR:

        gen_spr_generic(env);

        gen_spr_ne_601(env);

        /* Memory management */

        gen_low_BATs(env);

        /* Time base */

        gen_tbl(env);

        gen_spr_7xx(env);

        /* Hardware implementation registers */

        /* XXX : not implemented */

        spr_register(env, SPR_HID0, "HID0",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

        spr_register(env, SPR_HID1, "HID1",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* Allocate hardware IRQ controller */

        ppc6xx_irq_init(env);

        break;

    case CPU_PPC_750FX10: /* IBM PowerPC 750 FX            */

    case CPU_PPC_750FX20:

    case CPU_PPC_750FX21:

    case CPU_PPC_750FX22:

    case CPU_PPC_750FX23:

    case CPU_PPC_750GX10: /* IBM PowerPC 750 GX            */

    case CPU_PPC_750GX11:

    case CPU_PPC_750GX12:

        gen_spr_generic(env);

        gen_spr_ne_601(env);

        /* Memory management */

        gen_low_BATs(env);

        /* PowerPC 750fx & 750gx has 8 DBATs and 8 IBATs */

        gen_high_BATs(env);

        /* Time base */

        gen_tbl(env);

        gen_spr_7xx(env);

        /* Hardware implementation registers */

        /* XXX : not implemented */

        spr_register(env, SPR_HID0, "HID0",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

        spr_register(env, SPR_HID1, "HID1",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

        spr_register(env, SPR_750_HID2, "HID2",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* Allocate hardware IRQ controller */

        ppc6xx_irq_init(env);

        break;

    case CPU_PPC_755_10:  /* PowerPC 755                   */

    case CPU_PPC_755_11:

    case CPU_PPC_755_20:

    case CPU_PPC_755D:

    case CPU_PPC_755E:

        gen_spr_generic(env);

        gen_spr_ne_601(env);

        /* Memory management */

        gen_low_BATs(env);

        /* Time base */

        gen_tbl(env);

        /* Memory management */

        gen_high_BATs(env);

        gen_6xx_7xx_soft_tlb(env, 64, 2);

        gen_spr_G2_755(env);

        /* L2 cache control */

        /* XXX : not implemented */

        spr_register(env, SPR_ICTC, "ICTC",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

        spr_register(env, SPR_L2PM, "L2PM",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* Hardware implementation registers */

        /* XXX : not implemented */

        spr_register(env, SPR_HID0, "HID0",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

        spr_register(env, SPR_HID1, "HID1",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

        spr_register(env, SPR_HID2, "HID2",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* Allocate hardware IRQ controller */

        ppc6xx_irq_init(env);

        break;

#if defined (TODO)

    /* G4 family */

    case CPU_PPC_7400:    /* PowerPC 7400                  */

    case CPU_PPC_7410C:   /* PowerPC 7410                  */

    case CPU_PPC_7410D:

    case CPU_PPC_7410E:

    case CPU_PPC_7441:    /* PowerPC 7441                  */

    case CPU_PPC_7445:    /* PowerPC 7445                  */

    case CPU_PPC_7447:    /* PowerPC 7447                  */

    case CPU_PPC_7447A:   /* PowerPC 7447A                 */

    case CPU_PPC_7448:    /* PowerPC 7448                  */

    case CPU_PPC_7450:    /* PowerPC 7450                  */

    case CPU_PPC_7450b:

    case CPU_PPC_7451:    /* PowerPC 7451                  */

    case CPU_PPC_7451G:

    case CPU_PPC_7455:    /* PowerPC 7455                  */

    case CPU_PPC_7455F:

    case CPU_PPC_7455G:

    case CPU_PPC_7457:    /* PowerPC 7457                  */

    case CPU_PPC_7457C:

    case CPU_PPC_7457A:   /* PowerPC 7457A                 */

        break;

#endif

    /* 64 bits PowerPC                                     */

#if defined (TARGET_PPC64)

#if defined (TODO)

    case CPU_PPC_620:     /* PowerPC 620                   */

    case CPU_PPC_630:     /* PowerPC 630 (Power 3)         */

    case CPU_PPC_631:     /* PowerPC 631 (Power 3+)        */

    case CPU_PPC_POWER4:  /* Power 4                       */

    case CPU_PPC_POWER4P: /* Power 4+                      */

    case CPU_PPC_POWER5:  /* Power 5                       */

    case CPU_PPC_POWER5P: /* Power 5+                      */

#endif

        break;

    case CPU_PPC_970:     /* PowerPC 970                   */

    case CPU_PPC_970FX10: /* PowerPC 970 FX                */

    case CPU_PPC_970FX20:

    case CPU_PPC_970FX21:

    case CPU_PPC_970FX30:

    case CPU_PPC_970FX31:

    case CPU_PPC_970MP10: /* PowerPC 970 MP                */

    case CPU_PPC_970MP11:

        gen_spr_generic(env);

        gen_spr_ne_601(env);

        /* XXX: not correct */

        gen_low_BATs(env);

        /* Time base */

        gen_tbl(env);

        gen_spr_7xx(env);

        /* Hardware implementation registers */

        /* XXX : not implemented */

        spr_register(env, SPR_HID0, "HID0",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

        spr_register(env, SPR_HID1, "HID1",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* XXX : not implemented */

        spr_register(env, SPR_750_HID2, "HID2",

                     SPR_NOACCESS, SPR_NOACCESS,

                     &spr_read_generic, &spr_write_generic,

                     0x00000000);

        /* Allocate hardware IRQ controller */

        ppc970_irq_init(env);

        break;

#if defined (TODO)

    case CPU_PPC_CELL10:  /* Cell family                   */

    case CPU_PPC_CELL20:

    case CPU_PPC_CELL30:

    case CPU_PPC_CELL31:

#endif

        break;

#if defined (TODO)

    case CPU_PPC_RS64:    /* Apache (RS64/A35)             */

    case CPU_PPC_RS64II:  /* NorthStar (RS64-II/A50)       */

    case CPU_PPC_RS64III: /* Pulsar (RS64-III)             */

    case CPU_PPC_RS64IV:  /* IceStar/IStar/SStar (RS64-IV) */

#endif

        break;

#endif /* defined (TARGET_PPC64) */

#if defined (TODO)

        /* POWER                                               */

    case CPU_POWER:       /* POWER                         */

    case CPU_POWER2:      /* POWER2                        */

        break;

#endif

    default:

        gen_spr_generic(env);

        /* XXX: TODO: allocate internal IRQ controller */

        break;

    }

    if (env->nb_BATs == -1)

        env->nb_BATs = 4;

    /* Allocate TLBs buffer when needed */

    if (env->nb_tlb != 0) {

        int nb_tlb = env->nb_tlb;

        if (env->id_tlbs != 0)

            nb_tlb *= 2;

        env->tlb = qemu_mallocz(nb_tlb * sizeof(ppc_tlb_t));

        /* Pre-compute some useful values */

        env->tlb_per_way = env->nb_tlb / env->nb_ways;

    }

}


static void nop(DBDMA_channel *ch)

{

    dbdma_cmd *current = &ch->current;

    if (conditional_wait(ch))

        goto wait;

    current->xfer_status = cpu_to_le16(be32_to_cpu(ch->regs[DBDMA_STATUS]));

    dbdma_cmdptr_save(ch);

    conditional_interrupt(ch);

    conditional_branch(ch);

wait:

    qemu_bh_schedule(dbdma_bh);

}


static TileExcp decode_y1(DisasContext *dc, tilegx_bundle_bits bundle)

{

    unsigned opc = get_Opcode_Y1(bundle);

    unsigned ext = get_RRROpcodeExtension_Y1(bundle);

    unsigned dest = get_Dest_Y1(bundle);

    unsigned srca = get_SrcA_Y1(bundle);

    unsigned srcb;

    int imm;

    switch (get_Opcode_Y1(bundle)) {

    case RRR_1_OPCODE_Y1:

        if (ext == UNARY_RRR_1_OPCODE_Y0) {

            ext = get_UnaryOpcodeExtension_Y1(bundle);

            return gen_rr_opcode(dc, OE(opc, ext, Y1), dest, srca);

        }

        /* fallthru */

    case RRR_0_OPCODE_Y1:

    case RRR_2_OPCODE_Y1:

    case RRR_3_OPCODE_Y1:

    case RRR_4_OPCODE_Y1:

    case RRR_5_OPCODE_Y1:

    case RRR_6_OPCODE_Y1:

    case RRR_7_OPCODE_Y1:

        srcb = get_SrcB_Y1(bundle);

        return gen_rrr_opcode(dc, OE(opc, ext, Y1), dest, srca, srcb);

    case SHIFT_OPCODE_Y1:

        ext = get_ShiftOpcodeExtension_Y1(bundle);

        imm = get_ShAmt_Y1(bundle);

        return gen_rri_opcode(dc, OE(opc, ext, Y1), dest, srca, imm);

    case ADDI_OPCODE_Y1:

    case ADDXI_OPCODE_Y1:

    case ANDI_OPCODE_Y1:

    case CMPEQI_OPCODE_Y1:

    case CMPLTSI_OPCODE_Y1:

        imm = (int8_t)get_Imm8_Y1(bundle);

        return gen_rri_opcode(dc, OE(opc, 0, Y1), dest, srca, imm);

    default:

        return TILEGX_EXCP_OPCODE_UNIMPLEMENTED;

    }

}


static void versatile_init(ram_addr_t ram_size,

                     const char *boot_device,

                     const char *kernel_filename, const char *kernel_cmdline,

                     const char *initrd_filename, const char *cpu_model,

                     int board_id)

{

    CPUState *env;

    ram_addr_t ram_offset;

    qemu_irq *cpu_pic;

    qemu_irq pic[32];

    qemu_irq sic[32];

    DeviceState *dev;

    PCIBus *pci_bus;

    NICInfo *nd;

    int n;

    int done_smc = 0;

    if (!cpu_model)

        cpu_model = "arm926";

    env = cpu_init(cpu_model);

    if (!env) {

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

        exit(1);

    }

    ram_offset = qemu_ram_alloc(ram_size);

    /* ??? RAM should repeat to fill physical memory space.  */

    /* SDRAM at address zero.  */

    cpu_register_physical_memory(0, ram_size, ram_offset | IO_MEM_RAM);

    arm_sysctl_init(0x10000000, 0x41007004);

    cpu_pic = arm_pic_init_cpu(env);

    dev = sysbus_create_varargs("pl190", 0x10140000,

                                cpu_pic[0], cpu_pic[1], NULL);

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

        pic[n] = qdev_get_gpio_in(dev, n);

    }

    dev = sysbus_create_simple("versatilepb_sic", 0x10003000, NULL);

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

        sysbus_connect_irq(sysbus_from_qdev(dev), n, pic[n]);

        sic[n] = qdev_get_gpio_in(dev, n);

    }

    sysbus_create_simple("pl050_keyboard", 0x10006000, sic[3]);

    sysbus_create_simple("pl050_mouse", 0x10007000, sic[4]);

    dev = sysbus_create_varargs("versatile_pci", 0x40000000,

                                sic[27], sic[28], sic[29], sic[30], NULL);

    pci_bus = (PCIBus *)qdev_get_child_bus(dev, "pci");

    /* The Versatile PCI bridge does not provide access to PCI IO space,

       so many of the qemu PCI devices are not useable.  */

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

        nd = &nd_table[n];

        if ((!nd->model && !done_smc) || strcmp(nd->model, "smc91c111") == 0) {

            smc91c111_init(nd, 0x10010000, sic[25]);

            done_smc = 1;

        } else {

            pci_nic_init_nofail(nd, "rtl8139", NULL);

        }

    }

    if (usb_enabled) {

        usb_ohci_init_pci(pci_bus, -1);

    }

    n = drive_get_max_bus(IF_SCSI);

    while (n >= 0) {

        pci_create_simple(pci_bus, -1, "lsi53c895a");

        n--;

    }

    sysbus_create_simple("pl011", 0x101f1000, pic[12]);

    sysbus_create_simple("pl011", 0x101f2000, pic[13]);

    sysbus_create_simple("pl011", 0x101f3000, pic[14]);

    sysbus_create_simple("pl011", 0x10009000, sic[6]);

    sysbus_create_simple("pl080", 0x10130000, pic[17]);

    sysbus_create_simple("sp804", 0x101e2000, pic[4]);

    sysbus_create_simple("sp804", 0x101e3000, pic[5]);

    /* The versatile/PB actually has a modified Color LCD controller

       that includes hardware cursor support from the PL111.  */

    sysbus_create_simple("pl110_versatile", 0x10120000, pic[16]);

    sysbus_create_varargs("pl181", 0x10005000, sic[22], sic[1], NULL);

    sysbus_create_varargs("pl181", 0x1000b000, sic[23], sic[2], NULL);

    /* Add PL031 Real Time Clock. */

    sysbus_create_simple("pl031", 0x101e8000, pic[10]);

    /* Memory map for Versatile/PB:  */

    /* 0x10000000 System registers.  */

    /* 0x10001000 PCI controller config registers.  */

    /* 0x10002000 Serial bus interface.  */

    /*  0x10003000 Secondary interrupt controller.  */

    /* 0x10004000 AACI (audio).  */

    /*  0x10005000 MMCI0.  */

    /*  0x10006000 KMI0 (keyboard).  */

    /*  0x10007000 KMI1 (mouse).  */

    /* 0x10008000 Character LCD Interface.  */

    /*  0x10009000 UART3.  */

    /* 0x1000a000 Smart card 1.  */

    /*  0x1000b000 MMCI1.  */

    /*  0x10010000 Ethernet.  */

    /* 0x10020000 USB.  */

    /* 0x10100000 SSMC.  */

    /* 0x10110000 MPMC.  */

    /*  0x10120000 CLCD Controller.  */

    /*  0x10130000 DMA Controller.  */

    /*  0x10140000 Vectored interrupt controller.  */

    /* 0x101d0000 AHB Monitor Interface.  */

    /* 0x101e0000 System Controller.  */

    /* 0x101e1000 Watchdog Interface.  */

    /* 0x101e2000 Timer 0/1.  */

    /* 0x101e3000 Timer 2/3.  */

    /* 0x101e4000 GPIO port 0.  */

    /* 0x101e5000 GPIO port 1.  */

    /* 0x101e6000 GPIO port 2.  */

    /* 0x101e7000 GPIO port 3.  */

    /* 0x101e8000 RTC.  */

    /* 0x101f0000 Smart card 0.  */

    /*  0x101f1000 UART0.  */

    /*  0x101f2000 UART1.  */

    /*  0x101f3000 UART2.  */

    /* 0x101f4000 SSPI.  */

    versatile_binfo.ram_size = ram_size;

    versatile_binfo.kernel_filename = kernel_filename;

    versatile_binfo.kernel_cmdline = kernel_cmdline;

    versatile_binfo.initrd_filename = initrd_filename;

    versatile_binfo.board_id = board_id;

    arm_load_kernel(env, &versatile_binfo);

}


static void tftp_send_next_block(struct tftp_session *spt,

                                 struct tftp_t *recv_tp)

{

  struct sockaddr_in saddr, daddr;

  struct mbuf *m;

  struct tftp_t *tp;

  int nobytes;

  m = m_get(spt->slirp);

  if (!m) {

    return;

  }

  memset(m->m_data, 0, m->m_size);

  m->m_data += IF_MAXLINKHDR;

  tp = (void *)m->m_data;

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

  tp->tp_op = htons(TFTP_DATA);

  tp->x.tp_data.tp_block_nr = htons((spt->block_nr + 1) & 0xffff);

  saddr.sin_addr = recv_tp->ip.ip_dst;

  saddr.sin_port = recv_tp->udp.uh_dport;

  daddr.sin_addr = spt->client_ip;

  daddr.sin_port = spt->client_port;

  nobytes = tftp_read_data(spt, spt->block_nr, tp->x.tp_data.tp_buf, 512);

  if (nobytes < 0) {

    m_free(m);

    /* send "file not found" error back */

    tftp_send_error(spt, 1, "File not found", tp);

    return;

  }

  m->m_len = sizeof(struct tftp_t) - (512 - nobytes) -

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

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

  if (nobytes == 512) {

    tftp_session_update(spt);

  }

  else {

    tftp_session_terminate(spt);

  }

  spt->block_nr++;

}


static void cas_handle_compat_cpu(PowerPCCPUClass *pcc, uint32_t pvr,

                                  unsigned max_lvl, unsigned *compat_lvl,

                                  unsigned *cpu_version)

{

    unsigned lvl = get_compat_level(pvr);

    bool is205, is206;

    if (!lvl) {

        return;

    }

    /* If it is a logical PVR, try to determine the highest level */

    is205 = (pcc->pcr_mask & PCR_COMPAT_2_05) &&

            (lvl == get_compat_level(CPU_POWERPC_LOGICAL_2_05));

    is206 = (pcc->pcr_mask & PCR_COMPAT_2_06) &&

            ((lvl == get_compat_level(CPU_POWERPC_LOGICAL_2_06)) ||

             (lvl == get_compat_level(CPU_POWERPC_LOGICAL_2_06_PLUS)));

    if (is205 || is206) {

        if (!max_lvl) {

            /* User did not set the level, choose the highest */

            if (*compat_lvl <= lvl) {

                *compat_lvl = lvl;

                *cpu_version = pvr;

            }

        } else if (max_lvl >= lvl) {

            /* User chose the level, don't set higher than this */

            *compat_lvl = lvl;

            *cpu_version = pvr;

        }

    }

}


static void qobject_input_type_str(Visitor *v, const char *name, char **obj,

                                   Error **errp)

{

    QObjectInputVisitor *qiv = to_qiv(v);

    QObject *qobj = qobject_input_get_object(qiv, name, true, errp);

    QString *qstr;

    *obj = NULL;

    if (!qobj) {

        return;

    }

    qstr = qobject_to_qstring(qobj);

    if (!qstr) {

        error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name ? name : "null",

                   "string");

        return;

    }

    *obj = g_strdup(qstring_get_str(qstr));

}


static void gen_or(DisasContext *ctx)

{

    int rs, ra, rb;

    rs = rS(ctx->opcode);

    ra = rA(ctx->opcode);

    rb = rB(ctx->opcode);

    /* Optimisation for mr. ri case */

    if (rs != ra || rs != rb) {

        if (rs != rb)

            tcg_gen_or_tl(cpu_gpr[ra], cpu_gpr[rs], cpu_gpr[rb]);

        else

            tcg_gen_mov_tl(cpu_gpr[ra], cpu_gpr[rs]);

        if (unlikely(Rc(ctx->opcode) != 0))

            gen_set_Rc0(ctx, cpu_gpr[ra]);

    } else if (unlikely(Rc(ctx->opcode) != 0)) {

        gen_set_Rc0(ctx, cpu_gpr[rs]);

#if defined(TARGET_PPC64)

    } else {

        int prio = 0;

        switch (rs) {

        case 1:

            /* Set process priority to low */

            prio = 2;

            break;

        case 6:

            /* Set process priority to medium-low */

            prio = 3;

            break;

        case 2:

            /* Set process priority to normal */

            prio = 4;

            break;

#if !defined(CONFIG_USER_ONLY)

        case 31:

            if (!ctx->pr) {

                /* Set process priority to very low */

                prio = 1;

            }

            break;

        case 5:

            if (!ctx->pr) {

                /* Set process priority to medium-hight */

                prio = 5;

            }

            break;

        case 3:

            if (!ctx->pr) {

                /* Set process priority to high */

                prio = 6;

            }

            break;

        case 7:

            if (ctx->hv) {

                /* Set process priority to very high */

                prio = 7;

            }

            break;

#endif

        default:

            /* nop */

            break;

        }

        if (prio) {

            TCGv t0 = tcg_temp_new();

            gen_load_spr(t0, SPR_PPR);

            tcg_gen_andi_tl(t0, t0, ~0x001C000000000000ULL);

            tcg_gen_ori_tl(t0, t0, ((uint64_t)prio) << 50);

            gen_store_spr(SPR_PPR, t0);

            tcg_temp_free(t0);

        }

#endif

    }

}


target_ulong helper_dvpe(CPUMIPSState *env)

{

    CPUMIPSState *other_cpu = first_cpu;

    target_ulong prev = env->mvp->CP0_MVPControl;

    do {

        /* Turn off all VPEs except the one executing the dvpe.  */

        if (other_cpu != env) {

            other_cpu->mvp->CP0_MVPControl &= ~(1 << CP0MVPCo_EVP);

            mips_vpe_sleep(other_cpu);

        }

        other_cpu = other_cpu->next_cpu;

    } while (other_cpu);

    return prev;

}


static int sbr_make_f_master(AACContext *ac, SpectralBandReplication *sbr,

                             SpectrumParameters *spectrum)

{

    unsigned int temp, max_qmf_subbands;

    unsigned int start_min, stop_min;

    int k;

    const int8_t *sbr_offset_ptr;

    int16_t stop_dk[13];

    if (sbr->sample_rate < 32000) {

        temp = 3000;

    } else if (sbr->sample_rate < 64000) {

        temp = 4000;

    } else

        temp = 5000;

    switch (sbr->sample_rate) {

    case 16000:

        sbr_offset_ptr = sbr_offset[0];

        break;

    case 22050:

        sbr_offset_ptr = sbr_offset[1];

        break;

    case 24000:

        sbr_offset_ptr = sbr_offset[2];

        break;

    case 32000:

        sbr_offset_ptr = sbr_offset[3];

        break;

    case 44100: case 48000: case 64000:

        sbr_offset_ptr = sbr_offset[4];

        break;

    case 88200: case 96000: case 128000: case 176400: case 192000:

        sbr_offset_ptr = sbr_offset[5];

        break;

    default:

        av_log(ac->avctx, AV_LOG_ERROR,

               "Unsupported sample rate for SBR: %d\n", sbr->sample_rate);

        return -1;

    }

    start_min = ((temp << 7) + (sbr->sample_rate >> 1)) / sbr->sample_rate;

    stop_min  = ((temp << 8) + (sbr->sample_rate >> 1)) / sbr->sample_rate;

    sbr->k[0] = start_min + sbr_offset_ptr[spectrum->bs_start_freq];

    if (spectrum->bs_stop_freq < 14) {

        sbr->k[2] = stop_min;

        make_bands(stop_dk, stop_min, 64, 13);

        qsort(stop_dk, 13, sizeof(stop_dk[0]), qsort_comparison_function_int16);

        for (k = 0; k < spectrum->bs_stop_freq; k++)

            sbr->k[2] += stop_dk[k];

    } else if (spectrum->bs_stop_freq == 14) {

        sbr->k[2] = 2*sbr->k[0];

    } else if (spectrum->bs_stop_freq == 15) {

        sbr->k[2] = 3*sbr->k[0];

    } else {

        av_log(ac->avctx, AV_LOG_ERROR,

               "Invalid bs_stop_freq: %d\n", spectrum->bs_stop_freq);

        return -1;

    }

    sbr->k[2] = FFMIN(64, sbr->k[2]);

    // Requirements (14496-3 sp04 p205)

    if (sbr->sample_rate <= 32000) {

        max_qmf_subbands = 48;

    } else if (sbr->sample_rate == 44100) {

        max_qmf_subbands = 35;

    } else if (sbr->sample_rate >= 48000)

        max_qmf_subbands = 32;

    if (sbr->k[2] - sbr->k[0] > max_qmf_subbands) {

        av_log(ac->avctx, AV_LOG_ERROR,

               "Invalid bitstream, too many QMF subbands: %d\n", sbr->k[2] - sbr->k[0]);

        return -1;

    }

    if (!spectrum->bs_freq_scale) {

        int dk, k2diff;

        dk = spectrum->bs_alter_scale + 1;

        sbr->n_master = ((sbr->k[2] - sbr->k[0] + (dk&2)) >> dk) << 1;

        if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))

            return -1;

        for (k = 1; k <= sbr->n_master; k++)

            sbr->f_master[k] = dk;

        k2diff = sbr->k[2] - sbr->k[0] - sbr->n_master * dk;

        if (k2diff < 0) {

            sbr->f_master[1]--;

            sbr->f_master[2]-= (k2diff < -1);

        } else if (k2diff) {

            sbr->f_master[sbr->n_master]++;

        }

        sbr->f_master[0] = sbr->k[0];

        for (k = 1; k <= sbr->n_master; k++)

            sbr->f_master[k] += sbr->f_master[k - 1];

    } else {

        int half_bands = 7 - spectrum->bs_freq_scale;      // bs_freq_scale  = {1,2,3}

        int two_regions, num_bands_0;

        int vdk0_max, vdk1_min;

        int16_t vk0[49];

        if (49 * sbr->k[2] > 110 * sbr->k[0]) {

            two_regions = 1;

            sbr->k[1] = 2 * sbr->k[0];

        } else {

            two_regions = 0;

            sbr->k[1] = sbr->k[2];

        }

        num_bands_0 = lrintf(half_bands * log2f(sbr->k[1] / (float)sbr->k[0])) * 2;

        if (num_bands_0 <= 0) { // Requirements (14496-3 sp04 p205)

            av_log(ac->avctx, AV_LOG_ERROR, "Invalid num_bands_0: %d\n", num_bands_0);

            return -1;

        }

        vk0[0] = 0;

        make_bands(vk0+1, sbr->k[0], sbr->k[1], num_bands_0);

        qsort(vk0 + 1, num_bands_0, sizeof(vk0[1]), qsort_comparison_function_int16);

        vdk0_max = vk0[num_bands_0];

        vk0[0] = sbr->k[0];

        for (k = 1; k <= num_bands_0; k++) {

            if (vk0[k] <= 0) { // Requirements (14496-3 sp04 p205)

                av_log(ac->avctx, AV_LOG_ERROR, "Invalid vDk0[%d]: %d\n", k, vk0[k]);

                return -1;

            }

            vk0[k] += vk0[k-1];

        }

        if (two_regions) {

            int16_t vk1[49];

            float invwarp = spectrum->bs_alter_scale ? 0.76923076923076923077f

                                                     : 1.0f; // bs_alter_scale = {0,1}

            int num_bands_1 = lrintf(half_bands * invwarp *

                                     log2f(sbr->k[2] / (float)sbr->k[1])) * 2;

            make_bands(vk1+1, sbr->k[1], sbr->k[2], num_bands_1);

            vdk1_min = array_min_int16(vk1 + 1, num_bands_1);

            if (vdk1_min < vdk0_max) {

                int change;

                qsort(vk1 + 1, num_bands_1, sizeof(vk1[1]), qsort_comparison_function_int16);

                change = FFMIN(vdk0_max - vk1[1], (vk1[num_bands_1] - vk1[1]) >> 1);

                vk1[1]           += change;

                vk1[num_bands_1] -= change;

            }

            qsort(vk1 + 1, num_bands_1, sizeof(vk1[1]), qsort_comparison_function_int16);

            vk1[0] = sbr->k[1];

            for (k = 1; k <= num_bands_1; k++) {

                if (vk1[k] <= 0) { // Requirements (14496-3 sp04 p205)

                    av_log(ac->avctx, AV_LOG_ERROR, "Invalid vDk1[%d]: %d\n", k, vk1[k]);

                    return -1;

                }

                vk1[k] += vk1[k-1];

            }

            sbr->n_master = num_bands_0 + num_bands_1;

            if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))

                return -1;

            memcpy(&sbr->f_master[0],               vk0,

                   (num_bands_0 + 1) * sizeof(sbr->f_master[0]));

            memcpy(&sbr->f_master[num_bands_0 + 1], vk1 + 1,

                    num_bands_1      * sizeof(sbr->f_master[0]));

        } else {

            sbr->n_master = num_bands_0;

            if (check_n_master(ac->avctx, sbr->n_master, sbr->spectrum_params.bs_xover_band))

                return -1;

            memcpy(sbr->f_master, vk0, (num_bands_0 + 1) * sizeof(sbr->f_master[0]));

        }

    }

    return 0;

}


static void event_loop(VideoState *cur_stream)

{

    SDL_Event event;

    double incr, pos, frac;

    for (;;) {

        double x;

        refresh_loop_wait_event(cur_stream, &event);

        switch (event.type) {

        case SDL_KEYDOWN:

            if (exit_on_keydown) {

                do_exit(cur_stream);

                break;

            }

            switch (event.key.keysym.sym) {

            case SDLK_ESCAPE:

            case SDLK_q:

                do_exit(cur_stream);

                break;

            case SDLK_f:

                toggle_full_screen(cur_stream);

                cur_stream->force_refresh = 1;

                break;

            case SDLK_p:

            case SDLK_SPACE:

                toggle_pause(cur_stream);

                break;

            case SDLK_s: // S: Step to next frame

                step_to_next_frame(cur_stream);

                break;

            case SDLK_a:

                stream_cycle_channel(cur_stream, AVMEDIA_TYPE_AUDIO);

                break;

            case SDLK_v:

                stream_cycle_channel(cur_stream, AVMEDIA_TYPE_VIDEO);

                break;

            case SDLK_t:

                stream_cycle_channel(cur_stream, AVMEDIA_TYPE_SUBTITLE);

                break;

            case SDLK_w:

                toggle_audio_display(cur_stream);

                break;

            case SDLK_PAGEUP:

                incr = 600.0;

                goto do_seek;

            case SDLK_PAGEDOWN:

                incr = -600.0;

                goto do_seek;

            case SDLK_LEFT:

                incr = -10.0;

                goto do_seek;

            case SDLK_RIGHT:

                incr = 10.0;

                goto do_seek;

            case SDLK_UP:

                incr = 60.0;

                goto do_seek;

            case SDLK_DOWN:

                incr = -60.0;

            do_seek:

                    if (seek_by_bytes) {

                        if (cur_stream->video_stream >= 0 && cur_stream->video_current_pos >= 0) {

                            pos = cur_stream->video_current_pos;

                        } else if (cur_stream->audio_stream >= 0 && cur_stream->audio_pkt.pos >= 0) {

                            pos = cur_stream->audio_pkt.pos;

                        } else

                            pos = avio_tell(cur_stream->ic->pb);

                        if (cur_stream->ic->bit_rate)

                            incr *= cur_stream->ic->bit_rate / 8.0;

                        else

                            incr *= 180000.0;

                        pos += incr;

                        stream_seek(cur_stream, pos, incr, 1);

                    } else {

                        pos = get_master_clock(cur_stream);

                        if (isnan(pos))

                            pos = (double)cur_stream->seek_pos / AV_TIME_BASE;

                        pos += incr;

                        if (cur_stream->ic->start_time != AV_NOPTS_VALUE && pos < cur_stream->ic->start_time / (double)AV_TIME_BASE)

                            pos = cur_stream->ic->start_time / (double)AV_TIME_BASE;

                        stream_seek(cur_stream, (int64_t)(pos * AV_TIME_BASE), (int64_t)(incr * AV_TIME_BASE), 0);

                    }

                break;

            default:

                break;

            }

            break;

        case SDL_VIDEOEXPOSE:

            cur_stream->force_refresh = 1;

            break;

        case SDL_MOUSEBUTTONDOWN:

            if (exit_on_mousedown) {

                do_exit(cur_stream);

                break;

            }

        case SDL_MOUSEMOTION:

            if (cursor_hidden) {

                SDL_ShowCursor(1);

                cursor_hidden = 0;

            }

            cursor_last_shown = av_gettime();

            if (event.type == SDL_MOUSEBUTTONDOWN) {

                x = event.button.x;

            } else {

                if (event.motion.state != SDL_PRESSED)

                    break;

                x = event.motion.x;

            }

                if (seek_by_bytes || cur_stream->ic->duration <= 0) {

                    uint64_t size =  avio_size(cur_stream->ic->pb);

                    stream_seek(cur_stream, size*x/cur_stream->width, 0, 1);

                } else {

                    int64_t ts;

                    int ns, hh, mm, ss;

                    int tns, thh, tmm, tss;

                    tns  = cur_stream->ic->duration / 1000000LL;

                    thh  = tns / 3600;

                    tmm  = (tns % 3600) / 60;

                    tss  = (tns % 60);

                    frac = x / cur_stream->width;

                    ns   = frac * tns;

                    hh   = ns / 3600;

                    mm   = (ns % 3600) / 60;

                    ss   = (ns % 60);

                    fprintf(stderr, "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d)       \n", frac*100,

                            hh, mm, ss, thh, tmm, tss);

                    ts = frac * cur_stream->ic->duration;

                    if (cur_stream->ic->start_time != AV_NOPTS_VALUE)

                        ts += cur_stream->ic->start_time;

                    stream_seek(cur_stream, ts, 0, 0);

                }

            break;

        case SDL_VIDEORESIZE:

                screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0,

                                          SDL_HWSURFACE|SDL_RESIZABLE|SDL_ASYNCBLIT|SDL_HWACCEL);

                screen_width  = cur_stream->width  = event.resize.w;

                screen_height = cur_stream->height = event.resize.h;

                cur_stream->force_refresh = 1;

            break;

        case SDL_QUIT:

        case FF_QUIT_EVENT:

            do_exit(cur_stream);

            break;

        case FF_ALLOC_EVENT:

            alloc_picture(event.user.data1);

            break;

        default:

            break;

        }

    }

}


sdhci_write(void *opaque, hwaddr offset, uint64_t val, unsigned size)
{
    SDHCIState *s = (SDHCIState *)opaque;
    unsigned shift =  8 * (offset & 0x3);
    uint32_t mask = ~(((1ULL << (size * 8)) - 1) << shift);
    uint32_t value = val;
    value <<= shift;
    switch (offset & ~0x3) {
    case SDHC_SYSAD:
        s->sdmasysad = (s->sdmasysad & mask) | value;
        MASKED_WRITE(s->sdmasysad, mask, value);
        /* Writing to last byte of sdmasysad might trigger transfer */
        if (!(mask & 0xFF000000) && TRANSFERRING_DATA(s->prnsts) && s->blkcnt &&
                s->blksize && SDHC_DMA_TYPE(s->hostctl) == SDHC_CTRL_SDMA) {
            sdhci_sdma_transfer_multi_blocks(s);
        break;
    case SDHC_BLKSIZE:
        if (!TRANSFERRING_DATA(s->prnsts)) {
            MASKED_WRITE(s->blksize, mask, value);
            MASKED_WRITE(s->blkcnt, mask >> 16, value >> 16);
        break;
    case SDHC_ARGUMENT:
        MASKED_WRITE(s->argument, mask, value);
        break;
    case SDHC_TRNMOD:
        /* DMA can be enabled only if it is supported as indicated by
         * capabilities register */
        if (!(s->capareg & SDHC_CAN_DO_DMA)) {
            value &= ~SDHC_TRNS_DMA;
        MASKED_WRITE(s->trnmod, mask, value);
        MASKED_WRITE(s->cmdreg, mask >> 16, value >> 16);
        /* Writing to the upper byte of CMDREG triggers SD command generation */
        if ((mask & 0xFF000000) || !sdhci_can_issue_command(s)) {
            break;
        sdhci_send_command(s);
        break;
    case  SDHC_BDATA:
        if (sdhci_buff_access_is_sequential(s, offset - SDHC_BDATA)) {
            sdhci_write_dataport(s, value >> shift, size);
        break;
    case SDHC_HOSTCTL:
        if (!(mask & 0xFF0000)) {
            sdhci_blkgap_write(s, value >> 16);
        MASKED_WRITE(s->hostctl, mask, value);
        MASKED_WRITE(s->pwrcon, mask >> 8, value >> 8);
        MASKED_WRITE(s->wakcon, mask >> 24, value >> 24);
        if (!(s->prnsts & SDHC_CARD_PRESENT) || ((s->pwrcon >> 1) & 0x7) < 5 ||
                !(s->capareg & (1 << (31 - ((s->pwrcon >> 1) & 0x7))))) {
            s->pwrcon &= ~SDHC_POWER_ON;
        break;
    case SDHC_CLKCON:
        if (!(mask & 0xFF000000)) {
            sdhci_reset_write(s, value >> 24);
        MASKED_WRITE(s->clkcon, mask, value);
        MASKED_WRITE(s->timeoutcon, mask >> 16, value >> 16);
        if (s->clkcon & SDHC_CLOCK_INT_EN) {
            s->clkcon |= SDHC_CLOCK_INT_STABLE;
        } else {
            s->clkcon &= ~SDHC_CLOCK_INT_STABLE;
        break;
    case SDHC_NORINTSTS:
        if (s->norintstsen & SDHC_NISEN_CARDINT) {
            value &= ~SDHC_NIS_CARDINT;
        s->norintsts &= mask | ~value;
        s->errintsts &= (mask >> 16) | ~(value >> 16);
        if (s->errintsts) {
            s->norintsts |= SDHC_NIS_ERR;
        } else {
            s->norintsts &= ~SDHC_NIS_ERR;
        sdhci_update_irq(s);
        break;
    case SDHC_NORINTSTSEN:
        MASKED_WRITE(s->norintstsen, mask, value);
        MASKED_WRITE(s->errintstsen, mask >> 16, value >> 16);
        s->norintsts &= s->norintstsen;
        s->errintsts &= s->errintstsen;
        if (s->errintsts) {
            s->norintsts |= SDHC_NIS_ERR;
        } else {
            s->norintsts &= ~SDHC_NIS_ERR;
        sdhci_update_irq(s);
        break;
    case SDHC_NORINTSIGEN:
        MASKED_WRITE(s->norintsigen, mask, value);
        MASKED_WRITE(s->errintsigen, mask >> 16, value >> 16);
        sdhci_update_irq(s);
        break;
    case SDHC_ADMAERR:
        MASKED_WRITE(s->admaerr, mask, value);
        break;
    case SDHC_ADMASYSADDR:
        s->admasysaddr = (s->admasysaddr & (0xFFFFFFFF00000000ULL |
                (uint64_t)mask)) | (uint64_t)value;
        break;
    case SDHC_ADMASYSADDR + 4:
        s->admasysaddr = (s->admasysaddr & (0x00000000FFFFFFFFULL |
                ((uint64_t)mask << 32))) | ((uint64_t)value << 32);
        break;
    case SDHC_FEAER:
        s->acmd12errsts |= value;
        s->errintsts |= (value >> 16) & s->errintstsen;
        if (s->acmd12errsts) {
            s->errintsts |= SDHC_EIS_CMD12ERR;
        if (s->errintsts) {
            s->norintsts |= SDHC_NIS_ERR;
        sdhci_update_irq(s);
        break;
    default:
        ERRPRINT("bad %ub write offset: addr[0x%04x] <- %u(0x%x)\n",
                 size, (int)offset, value >> shift, value >> shift);
        break;
    DPRINT_L2("write %ub: addr[0x%04x] <- %u(0x%x)\n",
              size, (int)offset, value >> shift, value >> shift);


static void filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)

{

    AVFilterContext  *ctx = inlink->dst;

    ASyncContext       *s = ctx->priv;

    AVFilterLink *outlink = ctx->outputs[0];

    int nb_channels = av_get_channel_layout_nb_channels(buf->audio->channel_layout);

    int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :

                  av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);

    int out_size;

    int64_t delta;

    /* buffer data until we get the first timestamp */

    if (s->pts == AV_NOPTS_VALUE) {

        if (pts != AV_NOPTS_VALUE) {

            s->pts = pts - get_delay(s);

        }

        write_to_fifo(s, buf);

        return;

    }

    /* now wait for the next timestamp */

    if (pts == AV_NOPTS_VALUE) {

        write_to_fifo(s, buf);

        return;

    }

    /* when we have two timestamps, compute how many samples would we have

     * to add/remove to get proper sync between data and timestamps */

    delta    = pts - s->pts - get_delay(s);

    out_size = avresample_available(s->avr);

    if (labs(delta) > s->min_delta) {

        av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);

        out_size += delta;

    } else if (s->resample) {

        int comp = av_clip(delta, -s->max_comp, s->max_comp);

        av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);

        avresample_set_compensation(s->avr, delta, inlink->sample_rate);

    }

    if (out_size > 0) {

        AVFilterBufferRef *buf_out = ff_get_audio_buffer(outlink, AV_PERM_WRITE,

                                                         out_size);

        if (!buf_out)

            return;

        avresample_read(s->avr, (void**)buf_out->extended_data, out_size);

        buf_out->pts = s->pts;

        if (delta > 0) {

            av_samples_set_silence(buf_out->extended_data, out_size - delta,

                                   delta, nb_channels, buf->format);

        }

        ff_filter_samples(outlink, buf_out);

    } else {

        av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "

               "whole buffer.\n");

    }

    /* drain any remaining buffered data */

    avresample_read(s->avr, NULL, avresample_available(s->avr));

    s->pts = pts - avresample_get_delay(s->avr);

    avresample_convert(s->avr, NULL, 0, 0, (void**)buf->extended_data,

                       buf->linesize[0], buf->audio->nb_samples);

    avfilter_unref_buffer(buf);

}


static void bmdma_irq(void *opaque, int n, int level)

{

    BMDMAState *bm = opaque;

    if (!level) {

        /* pass through lower */

        qemu_set_irq(bm->irq, level);

        return;

    }

    if (bm) {

        bm->status |= BM_STATUS_INT;

    }

    /* trigger the real irq */

    qemu_set_irq(bm->irq, level);

}


iscsi_aio_cancel(BlockDriverAIOCB *blockacb)

{

    IscsiAIOCB *acb = (IscsiAIOCB *)blockacb;

    IscsiLun *iscsilun = acb->iscsilun;

    acb->common.cb(acb->common.opaque, -ECANCELED);

    acb->canceled = 1;

    /* send a task mgmt call to the target to cancel the task on the target */

    iscsi_task_mgmt_abort_task_async(iscsilun->iscsi, acb->task,

                                     iscsi_abort_task_cb, NULL);

    /* then also cancel the task locally in libiscsi */

    iscsi_scsi_task_cancel(iscsilun->iscsi, acb->task);

}


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

{

    RMDemuxContext *rm = s->priv_data;

    AVStream *st;

    int i, len, res, seq = 1;

    int64_t timestamp, pos;

    int flags;

    for (;;) {

        if (rm->audio_pkt_cnt) {

            // If there are queued audio packet return them first

            st = s->streams[rm->audio_stream_num];

            res = ff_rm_retrieve_cache(s, s->pb, st, st->priv_data, pkt);

            if(res < 0)

                return res;

            flags = 0;

        } else {

            if (rm->old_format) {

                RMStream *ast;

                st = s->streams[0];

                ast = st->priv_data;

                timestamp = AV_NOPTS_VALUE;

                len = !ast->audio_framesize ? RAW_PACKET_SIZE :

                    ast->coded_framesize * ast->sub_packet_h / 2;

                flags = (seq++ == 1) ? 2 : 0;

                pos = avio_tell(s->pb);

            } else {

                len=sync(s, &timestamp, &flags, &i, &pos);

                if (len > 0)

                    st = s->streams[i];

            }

            if(len<0 || url_feof(s->pb))

                return AVERROR(EIO);

            res = ff_rm_parse_packet (s, s->pb, st, st->priv_data, len, pkt,

                                      &seq, flags, timestamp);

            if((flags&2) && (seq&0x7F) == 1)

                av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);

            if (res)

                continue;

        }

        if(  (st->discard >= AVDISCARD_NONKEY && !(flags&2))

           || st->discard >= AVDISCARD_ALL){

            av_free_packet(pkt);

        } else

            break;

    }

    return 0;

}


static void do_pci_unregister_device(PCIDevice *pci_dev)

{

    pci_dev->bus->devices[pci_dev->devfn] = NULL;

    pci_config_free(pci_dev);

    memory_region_del_subregion(&pci_dev->bus_master_container_region,

                                &pci_dev->bus_master_enable_region);

    address_space_destroy(&pci_dev->bus_master_as);

}


static void vhost_user_cleanup(NetClientState *nc)

{

    VhostUserState *s = DO_UPCAST(VhostUserState, nc, nc);

    vhost_user_stop(s);

    qemu_purge_queued_packets(nc);

}


static void virtio_net_tx_timer(void *opaque)

{

    VirtIONetQueue *q = opaque;

    VirtIONet *n = q->n;

    VirtIODevice *vdev = VIRTIO_DEVICE(n);

    assert(vdev->vm_running);

    q->tx_waiting = 0;

    /* Just in case the driver is not ready on more */

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

        return;

    }

    virtio_queue_set_notification(q->tx_vq, 1);

    virtio_net_flush_tx(q);

}


static uint64_t omap_pwl_read(void *opaque, target_phys_addr_t addr,

                              unsigned size)

{

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

    int offset = addr & OMAP_MPUI_REG_MASK;

    if (size != 1) {

        return omap_badwidth_read8(opaque, addr);

    }

    switch (offset) {

    case 0x00:	/* PWL_LEVEL */

        return s->level;

    case 0x04:	/* PWL_CTRL */

        return s->enable;

    }

    OMAP_BAD_REG(addr);

    return 0;

}


int ff_parse_packing_format(int *ret, const char *arg, void *log_ctx)

{

    char *tail;

    int planar = strtol(arg, &tail, 10);

    if (*tail) {

        planar = (strcmp(arg, "packed") != 0);

    } else if (planar != 0 && planar != 1) {

        av_log(log_ctx, AV_LOG_ERROR, "Invalid packing format '%s'\n", arg);

        return AVERROR(EINVAL);

    }

    *ret = planar;

    return 0;

}


static int kvm_get_debugregs(CPUState *env)

{

#ifdef KVM_CAP_DEBUGREGS

    struct kvm_debugregs dbgregs;

    int i, ret;

    if (!kvm_has_debugregs()) {

        return 0;

    }

    ret = kvm_vcpu_ioctl(env, KVM_GET_DEBUGREGS, &dbgregs);

    if (ret < 0) {

       return ret;

    }

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

        env->dr[i] = dbgregs.db[i];

    }

    env->dr[4] = env->dr[6] = dbgregs.dr6;

    env->dr[5] = env->dr[7] = dbgregs.dr7;

#endif

    return 0;

}


static void scsi_hd_realize(SCSIDevice *dev, Error **errp)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);

    blkconf_blocksizes(&s->qdev.conf);

    s->qdev.blocksize = s->qdev.conf.logical_block_size;

    s->qdev.type = TYPE_DISK;

    if (!s->product) {

        s->product = g_strdup("QEMU HARDDISK");

    }

    scsi_realize(&s->qdev, errp);

}


static ssize_t virtio_net_receive(NetClientState *nc, const uint8_t *buf, size_t size)

{

    VirtIONet *n = qemu_get_nic_opaque(nc);

    VirtIONetQueue *q = virtio_net_get_subqueue(nc);

    VirtIODevice *vdev = VIRTIO_DEVICE(n);

    struct iovec mhdr_sg[VIRTQUEUE_MAX_SIZE];

    struct virtio_net_hdr_mrg_rxbuf mhdr;

    unsigned mhdr_cnt = 0;

    size_t offset, i, guest_offset;

    if (!virtio_net_can_receive(nc)) {

        return -1;

    }

    /* hdr_len refers to the header we supply to the guest */

    if (!virtio_net_has_buffers(q, size + n->guest_hdr_len - n->host_hdr_len)) {

        return 0;

    }

    if (!receive_filter(n, buf, size))

        return size;

    offset = i = 0;

    while (offset < size) {

        VirtQueueElement elem;

        int len, total;

        const struct iovec *sg = elem.in_sg;

        total = 0;

        if (virtqueue_pop(q->rx_vq, &elem) == 0) {

            if (i == 0)

                return -1;

            error_report("virtio-net unexpected empty queue: "

                         "i %zd mergeable %d offset %zd, size %zd, "

                         "guest hdr len %zd, host hdr len %zd "

                         "guest features 0x%" PRIx64,

                         i, n->mergeable_rx_bufs, offset, size,

                         n->guest_hdr_len, n->host_hdr_len,

                         vdev->guest_features);

            exit(1);

        }

        if (elem.in_num < 1) {

            error_report("virtio-net receive queue contains no in buffers");

            exit(1);

        }

        if (i == 0) {

            assert(offset == 0);

            if (n->mergeable_rx_bufs) {

                mhdr_cnt = iov_copy(mhdr_sg, ARRAY_SIZE(mhdr_sg),

                                    sg, elem.in_num,

                                    offsetof(typeof(mhdr), num_buffers),

                                    sizeof(mhdr.num_buffers));

            }

            receive_header(n, sg, elem.in_num, buf, size);

            offset = n->host_hdr_len;

            total += n->guest_hdr_len;

            guest_offset = n->guest_hdr_len;

        } else {

            guest_offset = 0;

        }

        /* copy in packet.  ugh */

        len = iov_from_buf(sg, elem.in_num, guest_offset,

                           buf + offset, size - offset);

        total += len;

        offset += len;

        /* If buffers can't be merged, at this point we

         * must have consumed the complete packet.

         * Otherwise, drop it. */

        if (!n->mergeable_rx_bufs && offset < size) {

            virtqueue_discard(q->rx_vq, &elem, total);

            return size;

        }

        /* signal other side */

        virtqueue_fill(q->rx_vq, &elem, total, i++);

    }

    if (mhdr_cnt) {

        virtio_stw_p(vdev, &mhdr.num_buffers, i);

        iov_from_buf(mhdr_sg, mhdr_cnt,

                     0,

                     &mhdr.num_buffers, sizeof mhdr.num_buffers);

    }

    virtqueue_flush(q->rx_vq, i);

    virtio_notify(vdev, q->rx_vq);

    return size;

}


int usb_claim_port(USBDevice *dev)

{

    USBBus *bus = usb_bus_from_device(dev);

    USBPort *port;

    assert(dev->port == NULL);

    if (dev->port_path) {

        QTAILQ_FOREACH(port, &bus->free, next) {

            if (strcmp(port->path, dev->port_path) == 0) {

                break;

            }

        }

        if (port == NULL) {

            error_report("Error: usb port %s (bus %s) not found (in use?)",

                         dev->port_path, bus->qbus.name);

            return -1;

        }

    } else {

        if (bus->nfree == 1 && strcmp(object_get_typename(OBJECT(dev)), "usb-hub") != 0) {

            /* Create a new hub and chain it on */

            usb_create_simple(bus, "usb-hub");

        }

        if (bus->nfree == 0) {

            error_report("Error: tried to attach usb device %s to a bus "

                         "with no free ports", dev->product_desc);

            return -1;

        }

        port = QTAILQ_FIRST(&bus->free);

    }

    trace_usb_port_claim(bus->busnr, port->path);

    QTAILQ_REMOVE(&bus->free, port, next);

    bus->nfree--;

    dev->port = port;

    port->dev = dev;

    QTAILQ_INSERT_TAIL(&bus->used, port, next);

    bus->nused++;

    return 0;

}


lqspi_read(void *opaque, hwaddr addr, unsigned int size)

{

    int i;

    XilinxQSPIPS *q = opaque;

    XilinxSPIPS *s = opaque;

    uint32_t ret;

    if (addr >= q->lqspi_cached_addr &&

            addr <= q->lqspi_cached_addr + LQSPI_CACHE_SIZE - 4) {

        ret = q->lqspi_buf[(addr - q->lqspi_cached_addr) >> 2];

        DB_PRINT("addr: %08x, data: %08x\n", (unsigned)addr, (unsigned)ret);

        return ret;

    } else {

        int flash_addr = (addr / num_effective_busses(s));

        int slave = flash_addr >> LQSPI_ADDRESS_BITS;

        int cache_entry = 0;

        DB_PRINT("config reg status: %08x\n", s->regs[R_LQSPI_CFG]);

        fifo8_reset(&s->tx_fifo);

        fifo8_reset(&s->rx_fifo);

        s->regs[R_CONFIG] &= ~CS;

        s->regs[R_CONFIG] |= ((~(1 << slave) << CS_SHIFT) & CS) | MANUAL_CS;

        xilinx_spips_update_cs_lines(s);

        /* instruction */

        DB_PRINT("pushing read instruction: %02x\n",

                 (uint8_t)(s->regs[R_LQSPI_CFG] & LQSPI_CFG_INST_CODE));

        fifo8_push(&s->tx_fifo, s->regs[R_LQSPI_CFG] & LQSPI_CFG_INST_CODE);

        /* read address */

        DB_PRINT("pushing read address %06x\n", flash_addr);

        fifo8_push(&s->tx_fifo, (uint8_t)(flash_addr >> 16));

        fifo8_push(&s->tx_fifo, (uint8_t)(flash_addr >> 8));

        fifo8_push(&s->tx_fifo, (uint8_t)flash_addr);

        /* mode bits */

        if (s->regs[R_LQSPI_CFG] & LQSPI_CFG_MODE_EN) {

            fifo8_push(&s->tx_fifo, extract32(s->regs[R_LQSPI_CFG],

                                              LQSPI_CFG_MODE_SHIFT,

                                              LQSPI_CFG_MODE_WIDTH));

        }

        /* dummy bytes */

        for (i = 0; i < (extract32(s->regs[R_LQSPI_CFG], LQSPI_CFG_DUMMY_SHIFT,

                                   LQSPI_CFG_DUMMY_WIDTH)); ++i) {

            DB_PRINT("pushing dummy byte\n");

            fifo8_push(&s->tx_fifo, 0);

        }

        xilinx_spips_update_cs_lines(s);

        xilinx_spips_flush_txfifo(s);

        fifo8_reset(&s->rx_fifo);

        DB_PRINT("starting QSPI data read\n");

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

            tx_data_bytes(s, 0, 4);

            xilinx_spips_flush_txfifo(s);

            rx_data_bytes(s, &q->lqspi_buf[cache_entry], 4);

            cache_entry++;

        }

        xilinx_spips_update_cs_lines(s);

        s->regs[R_CONFIG] |= CS;

        xilinx_spips_update_cs_lines(s);

        q->lqspi_cached_addr = addr;

        return lqspi_read(opaque, addr, size);

    }

}


static int send_jpeg_rect(VncState *vs, int x, int y, int w, int h, int quality)

{

    struct jpeg_compress_struct cinfo;

    struct jpeg_error_mgr jerr;

    struct jpeg_destination_mgr manager;

    JSAMPROW row[1];

    uint8_t *buf;

    int dy;

    if (ds_get_bytes_per_pixel(vs->ds) == 1)

        return send_full_color_rect(vs, w, h);

    buf = qemu_malloc(w * 3);

    row[0] = buf;

    buffer_reserve(&vs->tight_jpeg, 2048);

    cinfo.err = jpeg_std_error(&jerr);

    jpeg_create_compress(&cinfo);

    cinfo.client_data = vs;

    cinfo.image_width = w;

    cinfo.image_height = h;

    cinfo.input_components = 3;

    cinfo.in_color_space = JCS_RGB;

    jpeg_set_defaults(&cinfo);

    jpeg_set_quality(&cinfo, quality, true);

    manager.init_destination = jpeg_init_destination;

    manager.empty_output_buffer = jpeg_empty_output_buffer;

    manager.term_destination = jpeg_term_destination;

    cinfo.dest = &manager;

    jpeg_start_compress(&cinfo, true);

    for (dy = 0; dy < h; dy++) {

        jpeg_prepare_row(vs, buf, x, y + dy, w);

        jpeg_write_scanlines(&cinfo, row, 1);

    }

    jpeg_finish_compress(&cinfo);

    jpeg_destroy_compress(&cinfo);

    vnc_write_u8(vs, VNC_TIGHT_JPEG << 4);

    tight_send_compact_size(vs, vs->tight_jpeg.offset);

    vnc_write(vs, vs->tight_jpeg.buffer, vs->tight_jpeg.offset);

    buffer_reset(&vs->tight_jpeg);

    return 1;

}


static int alsa_init_out (HWVoiceOut *hw, audsettings_t *as)

{

    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;

    struct alsa_params_req req;

    struct alsa_params_obt obt;

    snd_pcm_t *handle;

    audsettings_t obt_as;

    req.fmt = aud_to_alsafmt (as->fmt);

    req.freq = as->freq;

    req.nchannels = as->nchannels;

    req.period_size = conf.period_size_out;

    req.buffer_size = conf.buffer_size_out;

    req.size_in_usec = conf.size_in_usec_out;

    req.override_mask = !!conf.period_size_out_overridden

        | (!!conf.buffer_size_out_overridden << 1);

    if (alsa_open (0, &req, &obt, &handle)) {

        return -1;

    }

    obt_as.freq = obt.freq;

    obt_as.nchannels = obt.nchannels;

    obt_as.fmt = obt.fmt;

    obt_as.endianness = obt.endianness;

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

    hw->samples = obt.samples;

    alsa->pcm_buf = audio_calloc (AUDIO_FUNC, obt.samples, 1 << hw->info.shift);

    if (!alsa->pcm_buf) {

        dolog ("Could not allocate DAC buffer (%d samples, each %d bytes)\n",

               hw->samples, 1 << hw->info.shift);

        alsa_anal_close (&handle);

        return -1;

    }

    alsa->handle = handle;

    return 0;

}


static int query_format(struct vf_instance *vf, unsigned int fmt)

{

    /* FIXME - figure out which other formats work */

    switch (fmt) {

    case IMGFMT_YV12:

    case IMGFMT_IYUV:

    case IMGFMT_I420:

        return ff_vf_next_query_format(vf, fmt);

    }

    return 0;

}


static void vfio_probe_ati_bar4_quirk(VFIOPCIDevice *vdev, int nr)

{

    VFIOQuirk *quirk;

    VFIOConfigWindowQuirk *window;

    /* This windows doesn't seem to be used except by legacy VGA code */

    if (!vfio_pci_is(vdev, PCI_VENDOR_ID_ATI, PCI_ANY_ID) ||

        !vdev->has_vga || nr != 4) {

        return;

    }

    quirk = g_malloc0(sizeof(*quirk));

    quirk->mem = g_new0(MemoryRegion, 2);

    quirk->nr_mem = 2;

    window = quirk->data = g_malloc0(sizeof(*window) +

                                     sizeof(VFIOConfigWindowMatch));

    window->vdev = vdev;

    window->address_offset = 0;

    window->data_offset = 4;

    window->nr_matches = 1;

    window->matches[0].match = 0x4000;

    window->matches[0].mask = PCIE_CONFIG_SPACE_SIZE - 1;

    window->bar = nr;

    window->addr_mem = &quirk->mem[0];

    window->data_mem = &quirk->mem[1];

    memory_region_init_io(window->addr_mem, OBJECT(vdev),

                          &vfio_generic_window_address_quirk, window,

                          "vfio-ati-bar4-window-address-quirk", 4);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        window->address_offset,

                                        window->addr_mem, 1);

    memory_region_init_io(window->data_mem, OBJECT(vdev),

                          &vfio_generic_window_data_quirk, window,

                          "vfio-ati-bar4-window-data-quirk", 4);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        window->data_offset,

                                        window->data_mem, 1);

    QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);

    trace_vfio_quirk_ati_bar4_probe(vdev->vbasedev.name);

}


int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,

                                      int64_t sector_num, int nb_sectors,

                                      BdrvRequestFlags flags)

{

    trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags);

    if (!(bs->open_flags & BDRV_O_UNMAP)) {

        flags &= ~BDRV_REQ_MAY_UNMAP;

    }

    return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,

                             BDRV_REQ_ZERO_WRITE | flags);

}


void axisdev88_init (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, const char *cpu_model)

{

    CPUState *env;

    struct etraxfs_pic *pic;

    void *etraxfs_dmac;

    struct etraxfs_dma_client *eth[2] = {NULL, NULL};

    int kernel_size;

    int i;

    int nand_regs;

    int gpio_regs;

    ram_addr_t phys_ram;

    ram_addr_t phys_intmem;

    /* init CPUs */

    if (cpu_model == NULL) {

        cpu_model = "crisv32";

    }

    env = cpu_init(cpu_model);

    qemu_register_reset(main_cpu_reset, env);

    /* allocate RAM */

    phys_ram = qemu_ram_alloc(ram_size);

    cpu_register_physical_memory(0x40000000, ram_size, phys_ram | IO_MEM_RAM);

    /* The ETRAX-FS has 128Kb on chip ram, the docs refer to it as the

       internal memory.  */

    phys_intmem = qemu_ram_alloc(INTMEM_SIZE);

    cpu_register_physical_memory(0x38000000, INTMEM_SIZE,

                                 phys_intmem | IO_MEM_RAM);

      /* Attach a NAND flash to CS1.  */

    nand_state.nand = nand_init(NAND_MFR_STMICRO, 0x39);

    nand_regs = cpu_register_io_memory(0, nand_read, nand_write, &nand_state);

    cpu_register_physical_memory(0x10000000, 0x05000000, nand_regs);

    gpio_state.nand = &nand_state;

    gpio_regs = cpu_register_io_memory(0, gpio_read, gpio_write, &gpio_state);

    cpu_register_physical_memory(0x3001a000, 0x5c, gpio_regs);

    pic = etraxfs_pic_init(env, 0x3001c000);

    etraxfs_dmac = etraxfs_dmac_init(env, 0x30000000, 10);

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

        /* On ETRAX, odd numbered channels are inputs.  */

        etraxfs_dmac_connect(etraxfs_dmac, i, pic->irq + 7 + i, i & 1);

    }

    /* Add the two ethernet blocks.  */

    eth[0] = etraxfs_eth_init(&nd_table[0], env, pic->irq + 25, 0x30034000);

    if (nb_nics > 1)

        eth[1] = etraxfs_eth_init(&nd_table[1], env, pic->irq + 26, 0x30036000);

    /* The DMA Connector block is missing, hardwire things for now.  */

    etraxfs_dmac_connect_client(etraxfs_dmac, 0, eth[0]);

    etraxfs_dmac_connect_client(etraxfs_dmac, 1, eth[0] + 1);

    if (eth[1]) {

        etraxfs_dmac_connect_client(etraxfs_dmac, 6, eth[1]);

        etraxfs_dmac_connect_client(etraxfs_dmac, 7, eth[1] + 1);

    }

    /* 2 timers.  */

    etraxfs_timer_init(env, pic->irq + 0x1b, pic->nmi + 1, 0x3001e000);

    etraxfs_timer_init(env, pic->irq + 0x1b, pic->nmi + 1, 0x3005e000);

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

        if (serial_hds[i]) {

            etraxfs_ser_init(env, pic->irq + 0x14 + i,

                             serial_hds[i], 0x30026000 + i * 0x2000);

        }

    }

    if (kernel_filename) {

        uint64_t entry, high;

        int kcmdline_len;

        /* Boots a kernel elf binary, os/linux-2.6/vmlinux from the axis

           devboard SDK.  */

        kernel_size = load_elf(kernel_filename, -0x80000000LL,

                               &entry, NULL, &high);

        bootstrap_pc = entry;

        if (kernel_size < 0) {

            /* Takes a kimage from the axis devboard SDK.  */

            kernel_size = load_image(kernel_filename, phys_ram_base + 0x4000);

            bootstrap_pc = 0x40004000;

            env->regs[9] = 0x40004000 + kernel_size;

        }

        env->regs[8] = 0x56902387; /* RAM init magic.  */

        if (kernel_cmdline && (kcmdline_len = strlen(kernel_cmdline))) {

            if (kcmdline_len > 256) {

                fprintf(stderr, "Too long CRIS kernel cmdline (max 256)\n");

                exit(1);

            }

            pstrcpy_targphys(high, 256, kernel_cmdline);

            /* Let the kernel know we are modifying the cmdline.  */

            env->regs[10] = 0x87109563;

            env->regs[11] = high;

        }

    }

    env->pc = bootstrap_pc;

    printf ("pc =%x\n", env->pc);

    printf ("ram size =%ld\n", ram_size);

}


uint32_t HELPER(neon_abd_f32)(uint32_t a, uint32_t b)

{

    float32 f0 = make_float32(a);

    float32 f1 = make_float32(b);

    return float32_val((float32_compare_quiet(f0, f1, NFS) == 1)

                    ? float32_sub(f0, f1, NFS)

                    : float32_sub(f1, f0, NFS));

}


static void xen_init_pv(MachineState *machine)

{

    DriveInfo *dinfo;

    int i;

    /* Initialize backend core & drivers */

    if (xen_be_init() != 0) {

        fprintf(stderr, "%s: xen backend core setup failed\n", __FUNCTION__);

        exit(1);

    }

    switch (xen_mode) {

    case XEN_ATTACH:

        /* nothing to do, xend handles everything */

        break;

#ifdef CONFIG_XEN_PV_DOMAIN_BUILD

    case XEN_CREATE: {

        const char *kernel_filename = machine->kernel_filename;

        const char *kernel_cmdline = machine->kernel_cmdline;

        const char *initrd_filename = machine->initrd_filename;

        if (xen_domain_build_pv(kernel_filename, initrd_filename,

                                kernel_cmdline) < 0) {

            fprintf(stderr, "xen pv domain creation failed\n");

            exit(1);

        }

        break;

    }

#endif

    case XEN_EMULATE:

        fprintf(stderr, "xen emulation not implemented (yet)\n");

        exit(1);

        break;

    default:

        fprintf(stderr, "unhandled xen_mode %d\n", xen_mode);

        exit(1);

        break;

    }

    xen_be_register_common();

    xen_be_register("vfb", &xen_framebuffer_ops);

    xen_be_register("qnic", &xen_netdev_ops);

    /* configure framebuffer */

    if (xenfb_enabled) {

        xen_config_dev_vfb(0, "vnc");

        xen_config_dev_vkbd(0);

    }

    /* configure disks */

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

        dinfo = drive_get(IF_XEN, 0, i);

        if (!dinfo)

            continue;

        xen_config_dev_blk(dinfo);

    }

    /* configure nics */

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

        if (!nd_table[i].model || 0 != strcmp(nd_table[i].model, "xen"))

            continue;

        xen_config_dev_nic(nd_table + i);

    }

    /* config cleanup hook */

    atexit(xen_config_cleanup);

    /* setup framebuffer */

    xen_init_display(xen_domid);

}


static void iohandler_init(void)

{

    if (!iohandler_ctx) {

        iohandler_ctx = aio_context_new(&error_abort);

    }

}


static void tcg_out_tb_finalize(TCGContext *s)

{

    static const void * const helpers[8] = {

        helper_ret_stb_mmu,

        helper_le_stw_mmu,

        helper_le_stl_mmu,

        helper_le_stq_mmu,

        helper_ret_ldub_mmu,

        helper_le_lduw_mmu,

        helper_le_ldul_mmu,

        helper_le_ldq_mmu,

    };

    tcg_insn_unit *thunks[8] = { };

    TCGLabelQemuLdst *l;

    for (l = s->be->labels; l != NULL; l = l->next) {

        long x = l->is_ld * 4 + l->size;

        tcg_insn_unit *dest = thunks[x];

        /* The out-of-line thunks are all the same; load the return address

           from B0, load the GP, and branch to the code.  Note that we are

           always post-call, so the register window has rolled, so we're

           using incoming parameter register numbers, not outgoing.  */

        if (dest == NULL) {

            uintptr_t *desc = (uintptr_t *)helpers[x];

            uintptr_t func = desc[0], gp = desc[1], disp;

            thunks[x] = dest = s->code_ptr;

            tcg_out_bundle(s, mlx,

                           INSN_NOP_M,

                           tcg_opc_l2 (gp),

                           tcg_opc_x2 (TCG_REG_P0, OPC_MOVL_X2,

                                       TCG_REG_R1, gp));

            tcg_out_bundle(s, mii,

                           INSN_NOP_M,

                           INSN_NOP_I,

                           tcg_opc_i22(TCG_REG_P0, OPC_MOV_I22,

                                       l->is_ld ? TCG_REG_R35 : TCG_REG_R36,

                                       TCG_REG_B0));

            disp = (tcg_insn_unit *)func - s->code_ptr;

            tcg_out_bundle(s, mLX,

                           INSN_NOP_M,

                           tcg_opc_l3 (disp),

                           tcg_opc_x3 (TCG_REG_P0, OPC_BRL_SPTK_MANY_X3, disp));

        }

        reloc_pcrel21b_slot2(l->label_ptr, dest);

    }

}


void bdrv_set_dirty_iter(HBitmapIter *hbi, int64_t offset)

{

    assert(hbi->hb);

    hbitmap_iter_init(hbi, hbi->hb, offset);

}


static uint32_t qpi_mem_readw(void *opaque, target_phys_addr_t addr)

{

    return 0;

}


static av_always_inline void hl_decode_mb_idct_luma(const H264Context *h, H264SliceContext *sl,

                                                    int mb_type, int simple,

                                                    int transform_bypass,

                                                    int pixel_shift,

                                                    const int *block_offset,

                                                    int linesize,

                                                    uint8_t *dest_y, int p)

{

    void (*idct_add)(uint8_t *dst, int16_t *block, int stride);

    int i;

    block_offset += 16 * p;

    if (!IS_INTRA4x4(mb_type)) {

        if (IS_INTRA16x16(mb_type)) {

            if (transform_bypass) {

                if (h->sps.profile_idc == 244 &&

                    (sl->intra16x16_pred_mode == VERT_PRED8x8 ||

                     sl->intra16x16_pred_mode == HOR_PRED8x8)) {

                    h->hpc.pred16x16_add[sl->intra16x16_pred_mode](dest_y, block_offset,

                                                                   sl->mb + (p * 256 << pixel_shift),

                                                                   linesize);

                } else {

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

                        if (sl->non_zero_count_cache[scan8[i + p * 16]] ||

                            dctcoef_get(sl->mb, pixel_shift, i * 16 + p * 256))

                            h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],

                                                              sl->mb + (i * 16 + p * 256 << pixel_shift),

                                                              linesize);

                }

            } else {

                h->h264dsp.h264_idct_add16intra(dest_y, block_offset,

                                                sl->mb + (p * 256 << pixel_shift),

                                                linesize,

                                                sl->non_zero_count_cache + p * 5 * 8);

            }

        } else if (sl->cbp & 15) {

            if (transform_bypass) {

                const int di = IS_8x8DCT(mb_type) ? 4 : 1;

                idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear

                    : h->h264dsp.h264_add_pixels4_clear;

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

                    if (sl->non_zero_count_cache[scan8[i + p * 16]])

                        idct_add(dest_y + block_offset[i],

                                 sl->mb + (i * 16 + p * 256 << pixel_shift),

                                 linesize);

            } else {

                if (IS_8x8DCT(mb_type))

                    h->h264dsp.h264_idct8_add4(dest_y, block_offset,

                                               sl->mb + (p * 256 << pixel_shift),

                                               linesize,

                                               sl->non_zero_count_cache + p * 5 * 8);

                else

                    h->h264dsp.h264_idct_add16(dest_y, block_offset,

                                               sl->mb + (p * 256 << pixel_shift),

                                               linesize,

                                               sl->non_zero_count_cache + p * 5 * 8);

            }

        }

    }

}


static void gen_ldstub_asi(DisasContext *dc, TCGv dst, TCGv addr, int insn)

{

    TCGv_i32 r_asi, r_size, r_sign;

    TCGv_i64 s64, d64 = tcg_temp_new_i64();

    r_asi = gen_get_asi(dc, insn);

    r_size = tcg_const_i32(1);

    r_sign = tcg_const_i32(0);

    gen_helper_ld_asi(d64, cpu_env, addr, r_asi, r_size, r_sign);

    tcg_temp_free_i32(r_sign);

    s64 = tcg_const_i64(0xff);

    gen_helper_st_asi(cpu_env, addr, s64, r_asi, r_size);

    tcg_temp_free_i64(s64);

    tcg_temp_free_i32(r_size);

    tcg_temp_free_i32(r_asi);

    tcg_gen_trunc_i64_tl(dst, d64);

    tcg_temp_free_i64(d64);

}


float32 HELPER(ucf64_df2si)(float64 x, CPUUniCore32State *env)

{

    return ucf64_itos(float64_to_int32(x, &env->ucf64.fp_status));

}


static int local_link(FsContext *ctx, V9fsPath *oldpath,

                      V9fsPath *dirpath, const char *name)

{

    int ret;

    V9fsString newpath;

    char buffer[PATH_MAX], buffer1[PATH_MAX];

    v9fs_string_init(&newpath);

    v9fs_string_sprintf(&newpath, "%s/%s", dirpath->data, name);

    ret = link(rpath(ctx, oldpath->data, buffer),

               rpath(ctx, newpath.data, buffer1));

    /* now link the virtfs_metadata files */

    if (!ret && (ctx->export_flags & V9FS_SM_MAPPED_FILE)) {

        /* Link the .virtfs_metadata files. Create the metada directory */

        ret = local_create_mapped_attr_dir(ctx, newpath.data);

        if (ret < 0) {

            goto err_out;

        }

        ret = link(local_mapped_attr_path(ctx, oldpath->data, buffer),

                   local_mapped_attr_path(ctx, newpath.data, buffer1));

        if (ret < 0 && errno != ENOENT) {

            goto err_out;

        }

    }

err_out:

    v9fs_string_free(&newpath);

    return ret;

}


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

                                ptrdiff_t stride)

{

    avc_luma_vt_and_aver_dst_4x4_msa(src - (stride * 2), stride, dst, stride);

}


static void commit_complete(BlockJob *job, void *opaque)

{

    CommitBlockJob *s = container_of(job, CommitBlockJob, common);

    CommitCompleteData *data = opaque;

    BlockDriverState *active = s->active;

    BlockDriverState *top = blk_bs(s->top);

    BlockDriverState *base = blk_bs(s->base);

    BlockDriverState *overlay_bs = bdrv_find_overlay(active, top);

    int ret = data->ret;

    if (!block_job_is_cancelled(&s->common) && ret == 0) {

        /* success */

        ret = bdrv_drop_intermediate(active, top, base, s->backing_file_str);

    }

    /* restore base open flags here if appropriate (e.g., change the base back

     * to r/o). These reopens do not need to be atomic, since we won't abort

     * even on failure here */

    if (s->base_flags != bdrv_get_flags(base)) {

        bdrv_reopen(base, s->base_flags, NULL);

    }

    if (overlay_bs && s->orig_overlay_flags != bdrv_get_flags(overlay_bs)) {

        bdrv_reopen(overlay_bs, s->orig_overlay_flags, NULL);

    }

    g_free(s->backing_file_str);

    blk_unref(s->top);

    blk_unref(s->base);

    block_job_completed(&s->common, ret);

    g_free(data);

}


static int ide_drive_post_load(void *opaque, int version_id)

{

    IDEState *s = opaque;

    if (s->identify_set) {

        blk_set_enable_write_cache(s->blk, !!(s->identify_data[85] & (1 << 5)));

    }

    return 0;

}


void do_migrate_set_downtime(Monitor *mon, const QDict *qdict)

{

    char *ptr;

    double d;

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

    d = strtod(value, &ptr);

    if (!strcmp(ptr,"ms")) {

        d *= 1000000;

    } else if (!strcmp(ptr,"us")) {

        d *= 1000;

    } else if (!strcmp(ptr,"ns")) {

    } else {

        /* all else considered to be seconds */

        d *= 1000000000;

    }

    max_downtime = (uint64_t)d;

}


int kvm_set_ioeventfd_pio_word(int fd, uint16_t addr, uint16_t val, bool assign)

{

    struct kvm_ioeventfd kick = {

        .datamatch = val,

        .addr = addr,

        .len = 2,

        .flags = KVM_IOEVENTFD_FLAG_DATAMATCH | KVM_IOEVENTFD_FLAG_PIO,

        .fd = fd,

    };

    int r;

    if (!kvm_enabled())

        return -ENOSYS;

    if (!assign)

        kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;

    r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);

    if (r < 0)

        return r;

    return 0;

}


static inline void gen_goto_tb(DisasContext *s, int n, target_ulong dest)

{

    if (use_goto_tb(s, dest)) {

        tcg_gen_goto_tb(n);

        gen_set_pc_im(s, dest);

        tcg_gen_exit_tb((uintptr_t)s->tb + n);

    } else {

        TCGv addr = tcg_temp_new();

        gen_set_pc_im(s, dest);

        tcg_gen_extu_i32_tl(addr, cpu_R[15]);

        tcg_gen_lookup_and_goto_ptr(addr);

        tcg_temp_free(addr);

    }

}