static inline void RENAME(rgb16tobgr24)(const uint8_t *src, uint8_t *dst, int src_size)

{

    const uint16_t *end;

    const uint16_t *mm_end;

    uint8_t *d = (uint8_t *)dst;

    const uint16_t *s = (const uint16_t *)src;

    end = s + src_size/2;

    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");

    mm_end = end - 7;

    while (s < mm_end) {

        __asm__ volatile(

            PREFETCH"    32%1           \n\t"

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

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

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

            "pand          %2, %%mm0    \n\t"

            "pand          %3, %%mm1    \n\t"

            "pand          %4, %%mm2    \n\t"

            "psllq         $3, %%mm0    \n\t"

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

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

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

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

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

            "punpcklwd     %5, %%mm0    \n\t"

            "punpcklwd     %5, %%mm1    \n\t"

            "punpcklwd     %5, %%mm2    \n\t"

            "punpckhwd     %5, %%mm3    \n\t"

            "punpckhwd     %5, %%mm4    \n\t"

            "punpckhwd     %5, %%mm5    \n\t"

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

            "psllq        $16, %%mm2    \n\t"

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

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

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

            "psllq        $16, %%mm5    \n\t"

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

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

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

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

            "movq         8%1, %%mm0    \n\t"

            "movq         8%1, %%mm1    \n\t"

            "movq         8%1, %%mm2    \n\t"

            "pand          %2, %%mm0    \n\t"

            "pand          %3, %%mm1    \n\t"

            "pand          %4, %%mm2    \n\t"

            "psllq         $3, %%mm0    \n\t"

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

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

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

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

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

            "punpcklwd     %5, %%mm0    \n\t"

            "punpcklwd     %5, %%mm1    \n\t"

            "punpcklwd     %5, %%mm2    \n\t"

            "punpckhwd     %5, %%mm3    \n\t"

            "punpckhwd     %5, %%mm4    \n\t"

            "punpckhwd     %5, %%mm5    \n\t"

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

            "psllq        $16, %%mm2    \n\t"

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

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

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

            "psllq        $16, %%mm5    \n\t"

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

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

            :"=m"(*d)

            :"m"(*s),"m"(mask16b),"m"(mask16g),"m"(mask16r),"m"(mmx_null)

            :"memory");

        /* borrowed 32 to 24 */

        __asm__ volatile(

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

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

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

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

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

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

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

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

            STORE_BGR24_MMX

            :"=m"(*d)

            :"m"(*s)

            :"memory");

        d += 24;

        s += 8;

    }

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

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

    while (s < end) {

        register uint16_t bgr;

        bgr = *s++;

        *d++ = (bgr&0x1F)<<3;

        *d++ = (bgr&0x7E0)>>3;

        *d++ = (bgr&0xF800)>>8;

    }

}


static void thread_pool_cancel(BlockDriverAIOCB *acb)

{

    ThreadPoolElement *elem = (ThreadPoolElement *)acb;

    ThreadPool *pool = elem->pool;

    trace_thread_pool_cancel(elem, elem->common.opaque);

    qemu_mutex_lock(&pool->lock);

    if (elem->state == THREAD_QUEUED &&

        /* No thread has yet started working on elem. we can try to "steal"

         * the item from the worker if we can get a signal from the

         * semaphore.  Because this is non-blocking, we can do it with

         * the lock taken and ensure that elem will remain THREAD_QUEUED.

         */

        qemu_sem_timedwait(&pool->sem, 0) == 0) {

        QTAILQ_REMOVE(&pool->request_list, elem, reqs);

        elem->state = THREAD_CANCELED;

        event_notifier_set(&pool->notifier);

    } else {

        pool->pending_cancellations++;

        while (elem->state != THREAD_CANCELED && elem->state != THREAD_DONE) {

            qemu_cond_wait(&pool->check_cancel, &pool->lock);

        }

        pool->pending_cancellations--;

    }

    qemu_mutex_unlock(&pool->lock);

}


static void vhost_dev_unassign_memory(struct vhost_dev *dev,

                                      uint64_t start_addr,

                                      uint64_t size)

{

    int from, to, n = dev->mem->nregions;

    /* Track overlapping/split regions for sanity checking. */

    int overlap_start = 0, overlap_end = 0, overlap_middle = 0, split = 0;

    for (from = 0, to = 0; from < n; ++from, ++to) {

        struct vhost_memory_region *reg = dev->mem->regions + to;

        uint64_t reglast;

        uint64_t memlast;

        uint64_t change;

        /* clone old region */

        if (to != from) {

            memcpy(reg, dev->mem->regions + from, sizeof *reg);

        }

        /* No overlap is simple */

        if (!ranges_overlap(reg->guest_phys_addr, reg->memory_size,

                            start_addr, size)) {

            continue;

        }

        /* Split only happens if supplied region

         * is in the middle of an existing one. Thus it can not

         * overlap with any other existing region. */

        assert(!split);

        reglast = range_get_last(reg->guest_phys_addr, reg->memory_size);

        memlast = range_get_last(start_addr, size);

        /* Remove whole region */

        if (start_addr <= reg->guest_phys_addr && memlast >= reglast) {

            --dev->mem->nregions;

            --to;

            assert(to >= 0);

            ++overlap_middle;

            continue;

        }

        /* Shrink region */

        if (memlast >= reglast) {

            reg->memory_size = start_addr - reg->guest_phys_addr;

            assert(reg->memory_size);

            assert(!overlap_end);

            ++overlap_end;

            continue;

        }

        /* Shift region */

        if (start_addr <= reg->guest_phys_addr) {

            change = memlast + 1 - reg->guest_phys_addr;

            reg->memory_size -= change;

            reg->guest_phys_addr += change;

            reg->userspace_addr += change;

            assert(reg->memory_size);

            assert(!overlap_start);

            ++overlap_start;

            continue;

        }

        /* This only happens if supplied region

         * is in the middle of an existing one. Thus it can not

         * overlap with any other existing region. */

        assert(!overlap_start);

        assert(!overlap_end);

        assert(!overlap_middle);

        /* Split region: shrink first part, shift second part. */

        memcpy(dev->mem->regions + n, reg, sizeof *reg);

        reg->memory_size = start_addr - reg->guest_phys_addr;

        assert(reg->memory_size);

        change = memlast + 1 - reg->guest_phys_addr;

        reg = dev->mem->regions + n;

        reg->memory_size -= change;

        assert(reg->memory_size);

        reg->guest_phys_addr += change;

        reg->userspace_addr += change;

        /* Never add more than 1 region */

        assert(dev->mem->nregions == n);

        ++dev->mem->nregions;

        ++split;

    }

}


static int pfpu_decode_insn(MilkymistPFPUState *s)

{

    uint32_t pc = s->regs[R_PC];

    uint32_t insn = s->microcode[pc];

    uint32_t reg_a = (insn >> 18) & 0x7f;

    uint32_t reg_b = (insn >> 11) & 0x7f;

    uint32_t op = (insn >> 7) & 0xf;

    uint32_t reg_d = insn & 0x7f;

    uint32_t r;

    int latency = 0;

    switch (op) {

    case OP_NOP:

        break;

    case OP_FADD:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = a + b;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_FADD;

        D_EXEC(qemu_log("ADD a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_FSUB:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = a - b;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_FSUB;

        D_EXEC(qemu_log("SUB a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_FMUL:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = a * b;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_FMUL;

        D_EXEC(qemu_log("MUL a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_FABS:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float t = fabsf(a);

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_FABS;

        D_EXEC(qemu_log("ABS a=%f t=%f, r=%08x\n", a, t, r));

    } break;

    case OP_F2I:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        int32_t t = a;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_F2I;

        D_EXEC(qemu_log("F2I a=%f t=%d, r=%08x\n", a, t, r));

    } break;

    case OP_I2F:

    {

        int32_t a = REINTERPRET_CAST(int32_t, s->gp_regs[reg_a]);

        float t = a;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_I2F;

        D_EXEC(qemu_log("I2F a=%08x t=%f, r=%08x\n", a, t, r));

    } break;

    case OP_VECTOUT:

    {

        uint32_t a = cpu_to_be32(s->gp_regs[reg_a]);

        uint32_t b = cpu_to_be32(s->gp_regs[reg_b]);

        target_phys_addr_t dma_ptr =

            get_dma_address(s->regs[R_MESHBASE],

                    s->gp_regs[GPR_X], s->gp_regs[GPR_Y]);

        cpu_physical_memory_write(dma_ptr, (uint8_t *)&a, 4);

        cpu_physical_memory_write(dma_ptr + 4, (uint8_t *)&b, 4);

        s->regs[R_LASTDMA] = dma_ptr + 4;

        D_EXEC(qemu_log("VECTOUT a=%08x b=%08x dma=%08x\n", a, b, dma_ptr));

        trace_milkymist_pfpu_vectout(a, b, dma_ptr);

    } break;

    case OP_SIN:

    {

        int32_t a = REINTERPRET_CAST(int32_t, s->gp_regs[reg_a]);

        float t = sinf(a * (1.0f / (M_PI * 4096.0f)));

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_SIN;

        D_EXEC(qemu_log("SIN a=%d t=%f, r=%08x\n", a, t, r));

    } break;

    case OP_COS:

    {

        int32_t a = REINTERPRET_CAST(int32_t, s->gp_regs[reg_a]);

        float t = cosf(a * (1.0f / (M_PI * 4096.0f)));

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_COS;

        D_EXEC(qemu_log("COS a=%d t=%f, r=%08x\n", a, t, r));

    } break;

    case OP_ABOVE:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = (a > b) ? 1.0f : 0.0f;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_ABOVE;

        D_EXEC(qemu_log("ABOVE a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_EQUAL:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = (a == b) ? 1.0f : 0.0f;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_EQUAL;

        D_EXEC(qemu_log("EQUAL a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_COPY:

    {

        r = s->gp_regs[reg_a];

        latency = LATENCY_COPY;

        D_EXEC(qemu_log("COPY"));

    } break;

    case OP_IF:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        uint32_t f = s->gp_regs[GPR_FLAGS];

        float t = (f != 0) ? a : b;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_IF;

        D_EXEC(qemu_log("IF f=%u a=%f b=%f t=%f, r=%08x\n", f, a, b, t, r));

    } break;

    case OP_TSIGN:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = (b < 0) ? -a : a;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_TSIGN;

        D_EXEC(qemu_log("TSIGN a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_QUAKE:

    {

        uint32_t a = s->gp_regs[reg_a];

        r = 0x5f3759df - (a >> 1);

        latency = LATENCY_QUAKE;

        D_EXEC(qemu_log("QUAKE a=%d r=%08x\n", a, r));

    } break;

    default:

        error_report("milkymist_pfpu: unknown opcode %d\n", op);

        break;

    }

    if (!reg_d) {

        D_EXEC(qemu_log("%04d %8s R%03d, R%03d <L=%d, E=%04d>\n",

                    s->regs[R_PC], opcode_to_str[op], reg_a, reg_b, latency,

                    s->regs[R_PC] + latency));

    } else {

        D_EXEC(qemu_log("%04d %8s R%03d, R%03d <L=%d, E=%04d> -> R%03d\n",

                    s->regs[R_PC], opcode_to_str[op], reg_a, reg_b, latency,

                    s->regs[R_PC] + latency, reg_d));

    }

    if (op == OP_VECTOUT) {

        return 0;

    }

    /* store output for this cycle */

    if (reg_d) {

        uint32_t val = output_queue_remove(s);

        D_EXEC(qemu_log("R%03d <- 0x%08x\n", reg_d, val));

        s->gp_regs[reg_d] = val;

    }

    output_queue_advance(s);

    /* store op output */

    if (op != OP_NOP) {

        output_queue_insert(s, r, latency-1);

    }

    /* advance PC */

    s->regs[R_PC]++;

    return 1;

};


static inline int mxf_read_utf16_string(AVIOContext *pb, int size, char** str, int be)

{

    int ret;

    size_t buf_size;

    if (size < 0)

        return AVERROR(EINVAL);

    buf_size = size + size / 2 + 1;

    *str = av_malloc(buf_size);

    if (!*str)

        return AVERROR(ENOMEM);

    if (be)

        ret = avio_get_str16be(pb, size, *str, buf_size);

    else

        ret = avio_get_str16le(pb, size, *str, buf_size);

    if (ret < 0) {

        av_freep(str);

        return ret;

    }

    return ret;

}


static void synth_block_fcb_acb(WMAVoiceContext *s, GetBitContext *gb,

                                int block_idx, int size,

                                int block_pitch_sh2,

                                const struct frame_type_desc *frame_desc,

                                float *excitation)

{

    static const float gain_coeff[6] = {

        0.8169, -0.06545, 0.1726, 0.0185, -0.0359, 0.0458

    };

    float pulses[MAX_FRAMESIZE / 2], pred_err, acb_gain, fcb_gain;

    int n, idx, gain_weight;

    AMRFixed fcb;

    assert(size <= MAX_FRAMESIZE / 2);

    memset(pulses, 0, sizeof(*pulses) * size);

    fcb.pitch_lag      = block_pitch_sh2 >> 2;

    fcb.pitch_fac      = 1.0;

    fcb.no_repeat_mask = 0;

    fcb.n              = 0;

    /* For the other frame types, this is where we apply the innovation

     * (fixed) codebook pulses of the speech signal. */

    if (frame_desc->fcb_type == FCB_TYPE_AW_PULSES) {

        aw_pulse_set1(s, gb, block_idx, &fcb);

        aw_pulse_set2(s, gb, block_idx, &fcb);

    } else /* FCB_TYPE_EXC_PULSES */ {

        int offset_nbits = 5 - frame_desc->log_n_blocks;

        fcb.no_repeat_mask = -1;

        /* similar to ff_decode_10_pulses_35bits(), but with single pulses

         * (instead of double) for a subset of pulses */

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

            float sign;

            int pos1, pos2;

            sign           = get_bits1(gb) ? 1.0 : -1.0;

            pos1           = get_bits(gb, offset_nbits);

            fcb.x[fcb.n]   = n + 5 * pos1;

            fcb.y[fcb.n++] = sign;

            if (n < frame_desc->dbl_pulses) {

                pos2           = get_bits(gb, offset_nbits);

                fcb.x[fcb.n]   = n + 5 * pos2;

                fcb.y[fcb.n++] = (pos1 < pos2) ? -sign : sign;

            }

        }

    }

    ff_set_fixed_vector(pulses, &fcb, 1.0, size);

    /* Calculate gain for adaptive & fixed codebook signal.

     * see ff_amr_set_fixed_gain(). */

    idx = get_bits(gb, 7);

    fcb_gain = expf(avpriv_scalarproduct_float_c(s->gain_pred_err,

                                                 gain_coeff, 6) -

                    5.2409161640 + wmavoice_gain_codebook_fcb[idx]);

    acb_gain = wmavoice_gain_codebook_acb[idx];

    pred_err = av_clipf(wmavoice_gain_codebook_fcb[idx],

                        -2.9957322736 /* log(0.05) */,

                         1.6094379124 /* log(5.0)  */);

    gain_weight = 8 >> frame_desc->log_n_blocks;

    memmove(&s->gain_pred_err[gain_weight], s->gain_pred_err,

            sizeof(*s->gain_pred_err) * (6 - gain_weight));

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

        s->gain_pred_err[n] = pred_err;

    /* Calculation of adaptive codebook */

    if (frame_desc->acb_type == ACB_TYPE_ASYMMETRIC) {

        int len;

        for (n = 0; n < size; n += len) {

            int next_idx_sh16;

            int abs_idx    = block_idx * size + n;

            int pitch_sh16 = (s->last_pitch_val << 16) +

                             s->pitch_diff_sh16 * abs_idx;

            int pitch      = (pitch_sh16 + 0x6FFF) >> 16;

            int idx_sh16   = ((pitch << 16) - pitch_sh16) * 8 + 0x58000;

            idx            = idx_sh16 >> 16;

            if (s->pitch_diff_sh16) {

                if (s->pitch_diff_sh16 > 0) {

                    next_idx_sh16 = (idx_sh16) &~ 0xFFFF;

                } else

                    next_idx_sh16 = (idx_sh16 + 0x10000) &~ 0xFFFF;

                len = av_clip((idx_sh16 - next_idx_sh16) / s->pitch_diff_sh16 / 8,

                              1, size - n);

            } else

                len = size;

            ff_acelp_interpolatef(&excitation[n], &excitation[n - pitch],

                                  wmavoice_ipol1_coeffs, 17,

                                  idx, 9, len);

        }

    } else /* ACB_TYPE_HAMMING */ {

        int block_pitch = block_pitch_sh2 >> 2;

        idx             = block_pitch_sh2 & 3;

        if (idx) {

            ff_acelp_interpolatef(excitation, &excitation[-block_pitch],

                                  wmavoice_ipol2_coeffs, 4,

                                  idx, 8, size);

        } else

            av_memcpy_backptr((uint8_t *) excitation, sizeof(float) * block_pitch,

                              sizeof(float) * size);

    }

    /* Interpolate ACB/FCB and use as excitation signal */

    ff_weighted_vector_sumf(excitation, excitation, pulses,

                            acb_gain, fcb_gain, size);

}


type_init(serial_register_types)

static bool serial_isa_init(ISABus *bus, int index, CharDriverState *chr)

{

    DeviceState *dev;

    ISADevice *isadev;

    isadev = isa_try_create(bus, TYPE_ISA_SERIAL);

    if (!isadev) {

        return false;

    }

    dev = DEVICE(isadev);

    qdev_prop_set_uint32(dev, "index", index);

    qdev_prop_set_chr(dev, "chardev", chr);

    if (qdev_init(dev) < 0) {

        return false;

    }

    return true;

}


void url_split(char *proto, int proto_size,

               char *hostname, int hostname_size,

               int *port_ptr,

               char *path, int path_size,

               const char *url)

{

    const char *p;

    char *q;

    int port;

    port = -1;

    p = url;

    q = proto;

    while (*p != ':' && *p != '\0') {

        if ((q - proto) < proto_size - 1)

            *q++ = *p;

        p++;

    }

    if (proto_size > 0)

        *q = '\0';

    if (*p == '\0') {

        if (proto_size > 0)

            proto[0] = '\0';

        if (hostname_size > 0)

            hostname[0] = '\0';

        p = url;

    } else {

        p++;

        if (*p == '/')

            p++;

        if (*p == '/')

            p++;

        q = hostname;

        while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {

            if ((q - hostname) < hostname_size - 1)

                *q++ = *p;

            p++;

        }

        if (hostname_size > 0)

            *q = '\0';

        if (*p == ':') {

            p++;

            port = strtoul(p, (char **)&p, 10);

        }

    }

    if (port_ptr)

        *port_ptr = port;

    pstrcpy(path, path_size, p);

}


static unsigned long iv_decode_frame(Indeo3DecodeContext *s,

                                     const uint8_t *buf, int buf_size)

{

    unsigned int image_width, image_height,

                 chroma_width, chroma_height;

    unsigned long flags, cb_offset, data_size,

                  y_offset, v_offset, u_offset, mc_vector_count;

    const uint8_t *hdr_pos, *buf_pos;

    buf_pos = buf;

    buf_pos += 18; /* skip OS header (16 bytes) and version number */

    flags = bytestream_get_le16(&buf_pos);

    data_size = bytestream_get_le32(&buf_pos);

    cb_offset = *buf_pos++;

    buf_pos += 3; /* skip reserved byte and checksum */

    image_height = bytestream_get_le16(&buf_pos);

    image_width  = bytestream_get_le16(&buf_pos);

    if(avcodec_check_dimensions(NULL, image_width, image_height))

        return -1;

    chroma_height = ((image_height >> 2) + 3) & 0x7ffc;

    chroma_width = ((image_width >> 2) + 3) & 0x7ffc;

    y_offset = bytestream_get_le32(&buf_pos);

    v_offset = bytestream_get_le32(&buf_pos);

    u_offset = bytestream_get_le32(&buf_pos);

    buf_pos += 4; /* reserved */

    hdr_pos = buf_pos;

    if(data_size == 0x80) return 4;

    if(flags & 0x200) {

        s->cur_frame = s->iv_frame + 1;

        s->ref_frame = s->iv_frame;

    } else {

        s->cur_frame = s->iv_frame;

        s->ref_frame = s->iv_frame + 1;

    }

    buf_pos = buf + 16 + y_offset;

    mc_vector_count = bytestream_get_le32(&buf_pos);

    iv_Decode_Chunk(s, s->cur_frame->Ybuf, s->ref_frame->Ybuf, image_width,

                    image_height, buf_pos + mc_vector_count * 2, cb_offset, hdr_pos, buf_pos,

                    FFMIN(image_width, 160));

    if (!(s->avctx->flags & CODEC_FLAG_GRAY))

    {

        buf_pos = buf + 16 + v_offset;

        mc_vector_count = bytestream_get_le32(&buf_pos);

        iv_Decode_Chunk(s, s->cur_frame->Vbuf, s->ref_frame->Vbuf, chroma_width,

                chroma_height, buf_pos + mc_vector_count * 2, cb_offset, hdr_pos, buf_pos,

                FFMIN(chroma_width, 40));

        buf_pos = buf + 16 + u_offset;

        mc_vector_count = bytestream_get_le32(&buf_pos);

        iv_Decode_Chunk(s, s->cur_frame->Ubuf, s->ref_frame->Ubuf, chroma_width,

                chroma_height, buf_pos + mc_vector_count * 2, cb_offset, hdr_pos, buf_pos,

                FFMIN(chroma_width, 40));

    }

    return 8;

}


static void rtsp_send_cmd_async (AVFormatContext *s,

                          const char *cmd, RTSPMessageHeader *reply,

                          unsigned char **content_ptr)

{

    RTSPState *rt = s->priv_data;

    char buf[4096], buf1[1024];

    rt->seq++;

    av_strlcpy(buf, cmd, sizeof(buf));

    snprintf(buf1, sizeof(buf1), "CSeq: %d\r\n", rt->seq);

    av_strlcat(buf, buf1, sizeof(buf));

    if (rt->session_id[0] != '\0' && !strstr(cmd, "\nIf-Match:")) {

        snprintf(buf1, sizeof(buf1), "Session: %s\r\n", rt->session_id);

        av_strlcat(buf, buf1, sizeof(buf));

    }

    if (rt->auth_b64)

        av_strlcatf(buf, sizeof(buf),

                    "Authorization: Basic %s\r\n",

                    rt->auth_b64);

    av_strlcat(buf, "\r\n", sizeof(buf));

    dprintf(s, "Sending:\n%s--\n", buf);

    url_write(rt->rtsp_hd, buf, strlen(buf));

    rt->last_cmd_time = av_gettime();

}


static void apply_channel_coupling(AC3EncodeContext *s)

{

    LOCAL_ALIGNED_16(CoefType, cpl_coords,      [AC3_MAX_BLOCKS], [AC3_MAX_CHANNELS][16]);

#if CONFIG_AC3ENC_FLOAT

    LOCAL_ALIGNED_16(int32_t, fixed_cpl_coords, [AC3_MAX_BLOCKS], [AC3_MAX_CHANNELS][16]);

#else

    int32_t (*fixed_cpl_coords)[AC3_MAX_CHANNELS][16] = cpl_coords;

#endif

    int blk, ch, bnd, i, j;

    CoefSumType energy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};

    int cpl_start, num_cpl_coefs;

    memset(cpl_coords,       0, AC3_MAX_BLOCKS * sizeof(*cpl_coords));

#if CONFIG_AC3ENC_FLOAT

    memset(fixed_cpl_coords, 0, AC3_MAX_BLOCKS * sizeof(*cpl_coords));

#endif

    /* align start to 16-byte boundary. align length to multiple of 32.

        note: coupling start bin % 4 will always be 1 */

    cpl_start     = s->start_freq[CPL_CH] - 1;

    num_cpl_coefs = FFALIGN(s->num_cpl_subbands * 12 + 1, 32);

    cpl_start     = FFMIN(256, cpl_start + num_cpl_coefs) - num_cpl_coefs;

    /* calculate coupling channel from fbw channels */

    for (blk = 0; blk < s->num_blocks; blk++) {

        AC3Block *block = &s->blocks[blk];

        CoefType *cpl_coef = &block->mdct_coef[CPL_CH][cpl_start];

        if (!block->cpl_in_use)

            continue;

        memset(cpl_coef, 0, num_cpl_coefs * sizeof(*cpl_coef));

        for (ch = 1; ch <= s->fbw_channels; ch++) {

            CoefType *ch_coef = &block->mdct_coef[ch][cpl_start];

            if (!block->channel_in_cpl[ch])

                continue;

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

                cpl_coef[i] += ch_coef[i];

        }

        /* coefficients must be clipped in order to be encoded */

        clip_coefficients(&s->dsp, cpl_coef, num_cpl_coefs);

    }

    /* calculate energy in each band in coupling channel and each fbw channel */

    /* TODO: possibly use SIMD to speed up energy calculation */

    bnd = 0;

    i = s->start_freq[CPL_CH];

    while (i < s->cpl_end_freq) {

        int band_size = s->cpl_band_sizes[bnd];

        for (ch = CPL_CH; ch <= s->fbw_channels; ch++) {

            for (blk = 0; blk < s->num_blocks; blk++) {

                AC3Block *block = &s->blocks[blk];

                if (!block->cpl_in_use || (ch > CPL_CH && !block->channel_in_cpl[ch]))

                    continue;

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

                    CoefType v = block->mdct_coef[ch][i+j];

                    MAC_COEF(energy[blk][ch][bnd], v, v);

                }

            }

        }

        i += band_size;

        bnd++;

    }

    /* calculate coupling coordinates for all blocks for all channels */

    for (blk = 0; blk < s->num_blocks; blk++) {

        AC3Block *block  = &s->blocks[blk];

        if (!block->cpl_in_use)

            continue;

        for (ch = 1; ch <= s->fbw_channels; ch++) {

            if (!block->channel_in_cpl[ch])

                continue;

            for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {

                cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy[blk][ch][bnd],

                                                          energy[blk][CPL_CH][bnd]);

            }

        }

    }

    /* determine which blocks to send new coupling coordinates for */

    for (blk = 0; blk < s->num_blocks; blk++) {

        AC3Block *block  = &s->blocks[blk];

        AC3Block *block0 = blk ? &s->blocks[blk-1] : NULL;

        memset(block->new_cpl_coords, 0, sizeof(block->new_cpl_coords));

        if (block->cpl_in_use) {

            /* send new coordinates if this is the first block, if previous

             * block did not use coupling but this block does, the channels

             * using coupling has changed from the previous block, or the

             * coordinate difference from the last block for any channel is

             * greater than a threshold value. */

            if (blk == 0 || !block0->cpl_in_use) {

                for (ch = 1; ch <= s->fbw_channels; ch++)

                    block->new_cpl_coords[ch] = 1;

            } else {

                for (ch = 1; ch <= s->fbw_channels; ch++) {

                    if (!block->channel_in_cpl[ch])

                        continue;

                    if (!block0->channel_in_cpl[ch]) {

                        block->new_cpl_coords[ch] = 1;

                    } else {

                        CoefSumType coord_diff = 0;

                        for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {

                            coord_diff += FFABS(cpl_coords[blk-1][ch][bnd] -

                                                cpl_coords[blk  ][ch][bnd]);

                        }

                        coord_diff /= s->num_cpl_bands;

                        if (coord_diff > NEW_CPL_COORD_THRESHOLD)

                            block->new_cpl_coords[ch] = 1;

                    }

                }

            }

        }

    }

    /* calculate final coupling coordinates, taking into account reusing of

       coordinates in successive blocks */

    for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {

        blk = 0;

        while (blk < s->num_blocks) {

            int av_uninit(blk1);

            AC3Block *block  = &s->blocks[blk];

            if (!block->cpl_in_use) {

                blk++;

                continue;

            }

            for (ch = 1; ch <= s->fbw_channels; ch++) {

                CoefSumType energy_ch, energy_cpl;

                if (!block->channel_in_cpl[ch])

                    continue;

                energy_cpl = energy[blk][CPL_CH][bnd];

                energy_ch = energy[blk][ch][bnd];

                blk1 = blk+1;

                while (!s->blocks[blk1].new_cpl_coords[ch] && blk1 < s->num_blocks) {

                    if (s->blocks[blk1].cpl_in_use) {

                        energy_cpl += energy[blk1][CPL_CH][bnd];

                        energy_ch += energy[blk1][ch][bnd];

                    }

                    blk1++;

                }

                cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy_ch, energy_cpl);

            }

            blk = blk1;

        }

    }

    /* calculate exponents/mantissas for coupling coordinates */

    for (blk = 0; blk < s->num_blocks; blk++) {

        AC3Block *block = &s->blocks[blk];

        if (!block->cpl_in_use)

            continue;

#if CONFIG_AC3ENC_FLOAT

        s->ac3dsp.float_to_fixed24(fixed_cpl_coords[blk][1],

                                   cpl_coords[blk][1],

                                   s->fbw_channels * 16);

#endif

        s->ac3dsp.extract_exponents(block->cpl_coord_exp[1],

                                    fixed_cpl_coords[blk][1],

                                    s->fbw_channels * 16);

        for (ch = 1; ch <= s->fbw_channels; ch++) {

            int bnd, min_exp, max_exp, master_exp;

            if (!block->new_cpl_coords[ch])

                continue;

            /* determine master exponent */

            min_exp = max_exp = block->cpl_coord_exp[ch][0];

            for (bnd = 1; bnd < s->num_cpl_bands; bnd++) {

                int exp = block->cpl_coord_exp[ch][bnd];

                min_exp = FFMIN(exp, min_exp);

                max_exp = FFMAX(exp, max_exp);

            }

            master_exp = ((max_exp - 15) + 2) / 3;

            master_exp = FFMAX(master_exp, 0);

            while (min_exp < master_exp * 3)

                master_exp--;

            for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {

                block->cpl_coord_exp[ch][bnd] = av_clip(block->cpl_coord_exp[ch][bnd] -

                                                        master_exp * 3, 0, 15);

            }

            block->cpl_master_exp[ch] = master_exp;

            /* quantize mantissas */

            for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {

                int cpl_exp  = block->cpl_coord_exp[ch][bnd];

                int cpl_mant = (fixed_cpl_coords[blk][ch][bnd] << (5 + cpl_exp + master_exp * 3)) >> 24;

                if (cpl_exp == 15)

                    cpl_mant >>= 1;

                else

                    cpl_mant -= 16;

                block->cpl_coord_mant[ch][bnd] = cpl_mant;

            }

        }

    }

    if (CONFIG_EAC3_ENCODER && s->eac3)

        ff_eac3_set_cpl_states(s);

}


static int get_high_utility_cell(elbg_data *elbg)

{

    int i=0;

    /* Using linear search, do binary if it ever turns to be speed critical */

    int r = av_lfg_get(elbg->rand_state)%elbg->utility_inc[elbg->numCB-1] + 1;

    while (elbg->utility_inc[i] < r)

        i++;

    av_assert2(elbg->cells[i]);

    return i;

}


static uint32_t acpi_find_vgia(void)

{

    uint32_t rsdp_offset;

    uint32_t guid_offset = 0;

    AcpiRsdpDescriptor rsdp_table;

    uint32_t rsdt;

    AcpiRsdtDescriptorRev1 rsdt_table;

    int tables_nr;

    uint32_t *tables;

    AcpiTableHeader ssdt_table;

    VgidTable vgid_table;

    int i;

    /* Tables may take a short time to be set up by the guest */

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

        rsdp_offset = acpi_find_rsdp_address();

        if (rsdp_offset < RSDP_ADDR_INVALID) {

            break;

        }

        g_usleep(RSDP_SLEEP_US);

    }

    g_assert_cmphex(rsdp_offset, <, RSDP_ADDR_INVALID);

    acpi_parse_rsdp_table(rsdp_offset, &rsdp_table);

    rsdt = rsdp_table.rsdt_physical_address;

    /* read the header */

    ACPI_READ_TABLE_HEADER(&rsdt_table, rsdt);

    ACPI_ASSERT_CMP(rsdt_table.signature, "RSDT");

    /* compute the table entries in rsdt */

    tables_nr = (rsdt_table.length - sizeof(AcpiRsdtDescriptorRev1)) /

                sizeof(uint32_t);

    g_assert_cmpint(tables_nr, >, 0);

    /* get the addresses of the tables pointed by rsdt */

    tables = g_new0(uint32_t, tables_nr);

    ACPI_READ_ARRAY_PTR(tables, tables_nr, rsdt);

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

        ACPI_READ_TABLE_HEADER(&ssdt_table, tables[i]);

        if (!strncmp((char *)ssdt_table.oem_table_id, "VMGENID", 7)) {

            /* the first entry in the table should be VGIA

             * That's all we need

             */

            ACPI_READ_FIELD(vgid_table.name_op, tables[i]);

            g_assert(vgid_table.name_op == 0x08);  /* name */

            ACPI_READ_ARRAY(vgid_table.vgia, tables[i]);

            g_assert(memcmp(vgid_table.vgia, "VGIA", 4) == 0);

            ACPI_READ_FIELD(vgid_table.val_op, tables[i]);

            g_assert(vgid_table.val_op == 0x0C);  /* dword */

            ACPI_READ_FIELD(vgid_table.vgia_val, tables[i]);

            /* The GUID is written at a fixed offset into the fw_cfg file

             * in order to implement the "OVMF SDT Header probe suppressor"

             * see docs/specs/vmgenid.txt for more details

             */

            guid_offset = vgid_table.vgia_val + VMGENID_GUID_OFFSET;

            break;

        }

    }

    g_free(tables);

    return guid_offset;

}


static void ff_jref_idct1_put(uint8_t *dest, int line_size, DCTELEM *block)

{

    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;

    dest[0] = cm[(block[0] + 4)>>3];

}


int cpu_load(QEMUFile *f, void *opaque, int version_id)

{

    CPUState *env = opaque;

    int i;

    uint32_t tmp;

    if (version_id != 5)

        return -EINVAL;

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

        qemu_get_betls(f, &env->gregs[i]);

    qemu_get_be32s(f, &env->nwindows);

    for(i = 0; i < env->nwindows * 16; i++)

        qemu_get_betls(f, &env->regbase[i]);

    /* FPU */

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

        union {

            float32 f;

            uint32_t i;

        } u;

        u.i = qemu_get_be32(f);

        env->fpr[i] = u.f;

    }

    qemu_get_betls(f, &env->pc);

    qemu_get_betls(f, &env->npc);

    qemu_get_betls(f, &env->y);

    tmp = qemu_get_be32(f);

    env->cwp = 0; /* needed to ensure that the wrapping registers are

                     correctly updated */

    PUT_PSR(env, tmp);

    qemu_get_betls(f, &env->fsr);

    qemu_get_betls(f, &env->tbr);

    tmp = qemu_get_be32(f);

    env->interrupt_index = tmp;

    qemu_get_be32s(f, &env->pil_in);

#ifndef TARGET_SPARC64

    qemu_get_be32s(f, &env->wim);

    /* MMU */

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

        qemu_get_be32s(f, &env->mmuregs[i]);

#else

    qemu_get_be64s(f, &env->lsu);

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

        qemu_get_be64s(f, &env->immuregs[i]);

        qemu_get_be64s(f, &env->dmmuregs[i]);

    }

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

        qemu_get_be64s(f, &env->itlb[i].tag);

        qemu_get_be64s(f, &env->itlb[i].tte);

        qemu_get_be64s(f, &env->dtlb[i].tag);

        qemu_get_be64s(f, &env->dtlb[i].tte);

    }

    qemu_get_be32s(f, &env->mmu_version);

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

        qemu_get_be64s(f, &env->ts[i].tpc);

        qemu_get_be64s(f, &env->ts[i].tnpc);

        qemu_get_be64s(f, &env->ts[i].tstate);

        qemu_get_be32s(f, &env->ts[i].tt);

    }

    qemu_get_be32s(f, &env->xcc);

    qemu_get_be32s(f, &env->asi);

    qemu_get_be32s(f, &env->pstate);

    qemu_get_be32s(f, &env->tl);

    env->tsptr = &env->ts[env->tl & MAXTL_MASK];

    qemu_get_be32s(f, &env->cansave);

    qemu_get_be32s(f, &env->canrestore);

    qemu_get_be32s(f, &env->otherwin);

    qemu_get_be32s(f, &env->wstate);

    qemu_get_be32s(f, &env->cleanwin);

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

        qemu_get_be64s(f, &env->agregs[i]);

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

        qemu_get_be64s(f, &env->bgregs[i]);

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

        qemu_get_be64s(f, &env->igregs[i]);

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

        qemu_get_be64s(f, &env->mgregs[i]);

    qemu_get_be64s(f, &env->fprs);

    qemu_get_be64s(f, &env->tick_cmpr);

    qemu_get_be64s(f, &env->stick_cmpr);

    qemu_get_ptimer(f, env->tick);

    qemu_get_ptimer(f, env->stick);

    qemu_get_be64s(f, &env->gsr);

    qemu_get_be32s(f, &env->gl);

    qemu_get_be64s(f, &env->hpstate);

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

        qemu_get_be64s(f, &env->htstate[i]);

    qemu_get_be64s(f, &env->hintp);

    qemu_get_be64s(f, &env->htba);

    qemu_get_be64s(f, &env->hver);

    qemu_get_be64s(f, &env->hstick_cmpr);

    qemu_get_be64s(f, &env->ssr);

    qemu_get_ptimer(f, env->hstick);

#endif

    tlb_flush(env, 1);

    return 0;

}


static av_cold int v410_encode_close(AVCodecContext *avctx)

{

    av_freep(&avctx->coded_frame);

    return 0;

}


static int vp3_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            uint8_t *buf, int buf_size)

{

    Vp3DecodeContext *s = avctx->priv_data;

    GetBitContext gb;

    static int counter = 0;

    init_get_bits(&gb, buf, buf_size * 8);

    if (s->theora && get_bits1(&gb))

    {

	int ptype = get_bits(&gb, 7);

	skip_bits(&gb, 6*8); /* "theora" */

	switch(ptype)

	{

	    case 1:

		theora_decode_comments(avctx, gb);

		break;

	    case 2:

		theora_decode_tables(avctx, gb);

    		init_dequantizer(s);

		break;

	    default:

		av_log(avctx, AV_LOG_ERROR, "Unknown Theora config packet: %d\n", ptype);

	}

	return buf_size;

    }

    s->keyframe = !get_bits1(&gb);

    if (!s->theora)

	skip_bits(&gb, 1);

    s->last_quality_index = s->quality_index;

    s->quality_index = get_bits(&gb, 6);

    if (s->theora >= 0x030200)

        skip_bits1(&gb);

    if (s->avctx->debug & FF_DEBUG_PICT_INFO)

	av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",

	    s->keyframe?"key":"", counter, s->quality_index);

    counter++;

    if (s->quality_index != s->last_quality_index)

        init_dequantizer(s);

    if (s->keyframe) {

	if (!s->theora)

	{

	    skip_bits(&gb, 4); /* width code */

	    skip_bits(&gb, 4); /* height code */

	    if (s->version)

	    {

		s->version = get_bits(&gb, 5);

		if (counter == 1)

		    av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);

	    }

	}

	if (s->version || s->theora)

	{

    	    if (get_bits1(&gb))

    	        av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n");

	    skip_bits(&gb, 2); /* reserved? */

	}

        if (s->last_frame.data[0] == s->golden_frame.data[0]) {

            if (s->golden_frame.data[0])

                avctx->release_buffer(avctx, &s->golden_frame);

            s->last_frame= s->golden_frame; /* ensure that we catch any access to this released frame */

        } else {

            if (s->golden_frame.data[0])

                avctx->release_buffer(avctx, &s->golden_frame);

            if (s->last_frame.data[0])

                avctx->release_buffer(avctx, &s->last_frame);

        }

        s->golden_frame.reference = 3;

        if(avctx->get_buffer(avctx, &s->golden_frame) < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "vp3: get_buffer() failed\n");

            return -1;

        }

        /* golden frame is also the current frame */

        memcpy(&s->current_frame, &s->golden_frame, sizeof(AVFrame));

        /* time to figure out pixel addresses? */

        if (!s->pixel_addresses_inited)

	{

	    if (!s->flipped_image)

        	vp3_calculate_pixel_addresses(s);

	    else

		theora_calculate_pixel_addresses(s);

	}

    } else {

        /* allocate a new current frame */

        s->current_frame.reference = 3;

        if(avctx->get_buffer(avctx, &s->current_frame) < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "vp3: get_buffer() failed\n");

            return -1;

        }

    }

    s->current_frame.qscale_table= s->qscale_table; //FIXME allocate individual tables per AVFrame

    s->current_frame.qstride= 0;

    init_frame(s, &gb);

#if KEYFRAMES_ONLY

if (!s->keyframe) {

    memcpy(s->current_frame.data[0], s->golden_frame.data[0],

        s->current_frame.linesize[0] * s->height);

    memcpy(s->current_frame.data[1], s->golden_frame.data[1],

        s->current_frame.linesize[1] * s->height / 2);

    memcpy(s->current_frame.data[2], s->golden_frame.data[2],

        s->current_frame.linesize[2] * s->height / 2);

} else {

#endif

    if (unpack_superblocks(s, &gb) ||

        unpack_modes(s, &gb) ||

        unpack_vectors(s, &gb) ||

        unpack_dct_coeffs(s, &gb)) {

        av_log(s->avctx, AV_LOG_ERROR, "  vp3: could not decode frame\n");

        return -1;

    }

    reverse_dc_prediction(s, 0, s->fragment_width, s->fragment_height);

    render_fragments(s, 0, s->width, s->height, 0);

//    apply_loop_filter(s);

    if ((avctx->flags & CODEC_FLAG_GRAY) == 0) {

        reverse_dc_prediction(s, s->u_fragment_start,

            s->fragment_width / 2, s->fragment_height / 2);

        reverse_dc_prediction(s, s->v_fragment_start,

            s->fragment_width / 2, s->fragment_height / 2);

        render_fragments(s, s->u_fragment_start, s->width / 2, s->height / 2, 1);

        render_fragments(s, s->v_fragment_start, s->width / 2, s->height / 2, 2);

    } else {

        memset(s->current_frame.data[1], 0x80, s->width * s->height / 4);

        memset(s->current_frame.data[2], 0x80, s->width * s->height / 4);

    }

#if KEYFRAMES_ONLY

}

#endif

    *data_size=sizeof(AVFrame);

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

    /* release the last frame, if it is allocated and if it is not the

     * golden frame */

    if ((s->last_frame.data[0]) &&

        (s->last_frame.data[0] != s->golden_frame.data[0]))

        avctx->release_buffer(avctx, &s->last_frame);

    /* shuffle frames (last = current) */

    memcpy(&s->last_frame, &s->current_frame, sizeof(AVFrame));

    s->current_frame.data[0]= NULL; /* ensure that we catch any access to this released frame */

    return buf_size;

}


static int au_read_header(AVFormatContext *s)

{

    int size;

    unsigned int tag;

    AVIOContext *pb = s->pb;

    unsigned int id, channels, rate;

    enum AVCodecID codec;

    AVStream *st;

    /* check ".snd" header */

    tag = avio_rl32(pb);

    if (tag != MKTAG('.', 's', 'n', 'd'))

        return -1;

    size = avio_rb32(pb); /* header size */

    avio_rb32(pb); /* data size */

    id = avio_rb32(pb);

    rate = avio_rb32(pb);

    channels = avio_rb32(pb);

    codec = ff_codec_get_id(codec_au_tags, id);

    if (!av_get_bits_per_sample(codec)) {

        av_log_ask_for_sample(s, "could not determine bits per sample\n");

        return AVERROR_PATCHWELCOME;

    }

    if (channels == 0 || channels > 64) {

        av_log(s, AV_LOG_ERROR, "Invalid number of channels %d\n", channels);

        return AVERROR_INVALIDDATA;

    }

    if (size >= 24) {

        /* skip unused data */

        avio_skip(pb, size - 24);

    }

    /* now we are ready: build format streams */

    st = avformat_new_stream(s, NULL);

    if (!st)

        return -1;

    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

    st->codec->codec_tag = id;

    st->codec->codec_id = codec;

    st->codec->channels = channels;

    st->codec->sample_rate = rate;

    avpriv_set_pts_info(st, 64, 1, rate);

    return 0;

}


static void mtree_print_mr(fprintf_function mon_printf, void *f,

                           const MemoryRegion *mr, unsigned int level,

                           target_phys_addr_t base,

                           MemoryRegionListHead *alias_print_queue)

{

    MemoryRegionList *new_ml, *ml, *next_ml;

    MemoryRegionListHead submr_print_queue;

    const MemoryRegion *submr;

    unsigned int i;

    if (!mr) {

        return;

    }

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

        mon_printf(f, "  ");

    }

    if (mr->alias) {

        MemoryRegionList *ml;

        bool found = false;

        /* check if the alias is already in the queue */

        QTAILQ_FOREACH(ml, alias_print_queue, queue) {

            if (ml->mr == mr->alias && !ml->printed) {

                found = true;

            }

        }

        if (!found) {

            ml = g_new(MemoryRegionList, 1);

            ml->mr = mr->alias;

            ml->printed = false;

            QTAILQ_INSERT_TAIL(alias_print_queue, ml, queue);

        }

        mon_printf(f, TARGET_FMT_plx "-" TARGET_FMT_plx " (prio %d): alias %s @%s "

                   TARGET_FMT_plx "-" TARGET_FMT_plx "\n",

                   base + mr->addr,

                   base + mr->addr

                   + (target_phys_addr_t)int128_get64(mr->size) - 1,

                   mr->priority,

                   mr->name,

                   mr->alias->name,

                   mr->alias_offset,

                   mr->alias_offset

                   + (target_phys_addr_t)int128_get64(mr->size) - 1);

    } else {

        mon_printf(f, TARGET_FMT_plx "-" TARGET_FMT_plx " (prio %d): %s\n",

                   base + mr->addr,

                   base + mr->addr

                   + (target_phys_addr_t)int128_get64(mr->size) - 1,

                   mr->priority,

                   mr->name);

    }

    QTAILQ_INIT(&submr_print_queue);

    QTAILQ_FOREACH(submr, &mr->subregions, subregions_link) {

        new_ml = g_new(MemoryRegionList, 1);

        new_ml->mr = submr;

        QTAILQ_FOREACH(ml, &submr_print_queue, queue) {

            if (new_ml->mr->addr < ml->mr->addr ||

                (new_ml->mr->addr == ml->mr->addr &&

                 new_ml->mr->priority > ml->mr->priority)) {

                QTAILQ_INSERT_BEFORE(ml, new_ml, queue);

                new_ml = NULL;

                break;

            }

        }

        if (new_ml) {

            QTAILQ_INSERT_TAIL(&submr_print_queue, new_ml, queue);

        }

    }

    QTAILQ_FOREACH(ml, &submr_print_queue, queue) {

        mtree_print_mr(mon_printf, f, ml->mr, level + 1, base + mr->addr,

                       alias_print_queue);

    }

    QTAILQ_FOREACH_SAFE(next_ml, &submr_print_queue, queue, ml) {

        g_free(ml);

    }

}


int spapr_vio_check_tces(VIOsPAPRDevice *dev, target_ulong ioba,

                         target_ulong len, enum VIOsPAPR_TCEAccess access)

{

    int start, end, i;

    start = ioba >> SPAPR_VIO_TCE_PAGE_SHIFT;

    end = (ioba + len - 1) >> SPAPR_VIO_TCE_PAGE_SHIFT;

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

        if ((dev->rtce_table[i].tce & access) != access) {

#ifdef DEBUG_TCE

            fprintf(stderr, "FAIL on %d\n", i);

#endif

            return -1;

        }

    }

    return 0;

}


void qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)

{

    int ret = 0;

    FsMountList mounts;

    struct FsMount *mount;

    int fd;

    Error *local_err = NULL;

    struct fstrim_range r = {

        .start = 0,

        .len = -1,

        .minlen = has_minimum ? minimum : 0,

    };

    slog("guest-fstrim called");

    QTAILQ_INIT(&mounts);

    build_fs_mount_list(&mounts, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    QTAILQ_FOREACH(mount, &mounts, next) {

        fd = qemu_open(mount->dirname, O_RDONLY);

        if (fd == -1) {

            error_setg_errno(errp, errno, "failed to open %s", mount->dirname);

            goto error;

        }

        /* We try to cull filesytems we know won't work in advance, but other

         * filesytems may not implement fstrim for less obvious reasons.  These

         * will report EOPNOTSUPP; we simply ignore these errors.  Any other

         * error means an unexpected error, so return it in those cases.  In

         * some other cases ENOTTY will be reported (e.g. CD-ROMs).

         */

        ret = ioctl(fd, FITRIM, &r);

        if (ret == -1) {

            if (errno != ENOTTY && errno != EOPNOTSUPP) {

                error_setg_errno(errp, errno, "failed to trim %s",

                                 mount->dirname);

                close(fd);

                goto error;

            }

        }

        close(fd);

    }

error:

    free_fs_mount_list(&mounts);

}


static av_always_inline void encode_mb_internal(MpegEncContext *s, int motion_x, int motion_y, int mb_block_height, int mb_block_count)

{

    int16_t weight[8][64];

    DCTELEM orig[8][64];

    const int mb_x= s->mb_x;

    const int mb_y= s->mb_y;

    int i;

    int skip_dct[8];

    int dct_offset   = s->linesize*8; //default for progressive frames

    uint8_t *ptr_y, *ptr_cb, *ptr_cr;

    int wrap_y, wrap_c;

    for(i=0; i<mb_block_count; i++) skip_dct[i]=s->skipdct;

    if(s->adaptive_quant){

        const int last_qp= s->qscale;

        const int mb_xy= mb_x + mb_y*s->mb_stride;

        s->lambda= s->lambda_table[mb_xy];

        update_qscale(s);

        if(!(s->flags&CODEC_FLAG_QP_RD)){

            s->qscale= s->current_picture_ptr->qscale_table[mb_xy];

            s->dquant= s->qscale - last_qp;

            if(s->out_format==FMT_H263){

                s->dquant= av_clip(s->dquant, -2, 2);

                if(s->codec_id==CODEC_ID_MPEG4){

                    if(!s->mb_intra){

                        if(s->pict_type == FF_B_TYPE){

                            if(s->dquant&1 || s->mv_dir&MV_DIRECT)

                                s->dquant= 0;

                        }

                        if(s->mv_type==MV_TYPE_8X8)

                            s->dquant=0;

                    }

                }

            }

        }

        ff_set_qscale(s, last_qp + s->dquant);

    }else if(s->flags&CODEC_FLAG_QP_RD)

        ff_set_qscale(s, s->qscale + s->dquant);

    wrap_y = s->linesize;

    wrap_c = s->uvlinesize;

    ptr_y = s->new_picture.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;

    ptr_cb = s->new_picture.data[1] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;

    ptr_cr = s->new_picture.data[2] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;

    if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){

        uint8_t *ebuf= s->edge_emu_buffer + 32;

        ff_emulated_edge_mc(ebuf            , ptr_y , wrap_y,16,16,mb_x*16,mb_y*16, s->width   , s->height);

        ptr_y= ebuf;

        ff_emulated_edge_mc(ebuf+18*wrap_y  , ptr_cb, wrap_c, 8, mb_block_height, mb_x*8, mb_y*8, s->width>>1, s->height>>1);

        ptr_cb= ebuf+18*wrap_y;

        ff_emulated_edge_mc(ebuf+18*wrap_y+8, ptr_cr, wrap_c, 8, mb_block_height, mb_x*8, mb_y*8, s->width>>1, s->height>>1);

        ptr_cr= ebuf+18*wrap_y+8;

    }

    if (s->mb_intra) {

        if(s->flags&CODEC_FLAG_INTERLACED_DCT){

            int progressive_score, interlaced_score;

            s->interlaced_dct=0;

            progressive_score= s->dsp.ildct_cmp[4](s, ptr_y           , NULL, wrap_y, 8)

                              +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y*8, NULL, wrap_y, 8) - 400;

            if(progressive_score > 0){

                interlaced_score = s->dsp.ildct_cmp[4](s, ptr_y           , NULL, wrap_y*2, 8)

                                  +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y  , NULL, wrap_y*2, 8);

                if(progressive_score > interlaced_score){

                    s->interlaced_dct=1;

                    dct_offset= wrap_y;

                    wrap_y<<=1;

                    if (s->chroma_format == CHROMA_422)

                        wrap_c<<=1;

                }

            }

        }

        s->dsp.get_pixels(s->block[0], ptr_y                 , wrap_y);

        s->dsp.get_pixels(s->block[1], ptr_y              + 8, wrap_y);

        s->dsp.get_pixels(s->block[2], ptr_y + dct_offset    , wrap_y);

        s->dsp.get_pixels(s->block[3], ptr_y + dct_offset + 8, wrap_y);

        if(s->flags&CODEC_FLAG_GRAY){

            skip_dct[4]= 1;

            skip_dct[5]= 1;

        }else{

            s->dsp.get_pixels(s->block[4], ptr_cb, wrap_c);

            s->dsp.get_pixels(s->block[5], ptr_cr, wrap_c);

            if(!s->chroma_y_shift){ /* 422 */

                s->dsp.get_pixels(s->block[6], ptr_cb + (dct_offset>>1), wrap_c);

                s->dsp.get_pixels(s->block[7], ptr_cr + (dct_offset>>1), wrap_c);

            }

        }

    }else{

        op_pixels_func (*op_pix)[4];

        qpel_mc_func (*op_qpix)[16];

        uint8_t *dest_y, *dest_cb, *dest_cr;

        dest_y  = s->dest[0];

        dest_cb = s->dest[1];

        dest_cr = s->dest[2];

        if ((!s->no_rounding) || s->pict_type==FF_B_TYPE){

            op_pix = s->dsp.put_pixels_tab;

            op_qpix= s->dsp.put_qpel_pixels_tab;

        }else{

            op_pix = s->dsp.put_no_rnd_pixels_tab;

            op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;

        }

        if (s->mv_dir & MV_DIR_FORWARD) {

            MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);

            op_pix = s->dsp.avg_pixels_tab;

            op_qpix= s->dsp.avg_qpel_pixels_tab;

        }

        if (s->mv_dir & MV_DIR_BACKWARD) {

            MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);

        }

        if(s->flags&CODEC_FLAG_INTERLACED_DCT){

            int progressive_score, interlaced_score;

            s->interlaced_dct=0;

            progressive_score= s->dsp.ildct_cmp[0](s, dest_y           , ptr_y           , wrap_y, 8)

                              +s->dsp.ildct_cmp[0](s, dest_y + wrap_y*8, ptr_y + wrap_y*8, wrap_y, 8) - 400;

            if(s->avctx->ildct_cmp == FF_CMP_VSSE) progressive_score -= 400;

            if(progressive_score>0){

                interlaced_score = s->dsp.ildct_cmp[0](s, dest_y           , ptr_y           , wrap_y*2, 8)

                                  +s->dsp.ildct_cmp[0](s, dest_y + wrap_y  , ptr_y + wrap_y  , wrap_y*2, 8);

                if(progressive_score > interlaced_score){

                    s->interlaced_dct=1;

                    dct_offset= wrap_y;

                    wrap_y<<=1;

                    if (s->chroma_format == CHROMA_422)

                        wrap_c<<=1;

                }

            }

        }

        s->dsp.diff_pixels(s->block[0], ptr_y                 , dest_y                 , wrap_y);

        s->dsp.diff_pixels(s->block[1], ptr_y              + 8, dest_y              + 8, wrap_y);

        s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset    , dest_y + dct_offset    , wrap_y);

        s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8, dest_y + dct_offset + 8, wrap_y);

        if(s->flags&CODEC_FLAG_GRAY){

            skip_dct[4]= 1;

            skip_dct[5]= 1;

        }else{

            s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);

            s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);

            if(!s->chroma_y_shift){ /* 422 */

                s->dsp.diff_pixels(s->block[6], ptr_cb + (dct_offset>>1), dest_cb + (dct_offset>>1), wrap_c);

                s->dsp.diff_pixels(s->block[7], ptr_cr + (dct_offset>>1), dest_cr + (dct_offset>>1), wrap_c);

            }

        }

        /* pre quantization */

        if(s->current_picture.mc_mb_var[s->mb_stride*mb_y+ mb_x]<2*s->qscale*s->qscale){

            //FIXME optimize

            if(s->dsp.sad[1](NULL, ptr_y               , dest_y               , wrap_y, 8) < 20*s->qscale) skip_dct[0]= 1;

            if(s->dsp.sad[1](NULL, ptr_y            + 8, dest_y            + 8, wrap_y, 8) < 20*s->qscale) skip_dct[1]= 1;

            if(s->dsp.sad[1](NULL, ptr_y +dct_offset   , dest_y +dct_offset   , wrap_y, 8) < 20*s->qscale) skip_dct[2]= 1;

            if(s->dsp.sad[1](NULL, ptr_y +dct_offset+ 8, dest_y +dct_offset+ 8, wrap_y, 8) < 20*s->qscale) skip_dct[3]= 1;

            if(s->dsp.sad[1](NULL, ptr_cb              , dest_cb              , wrap_c, 8) < 20*s->qscale) skip_dct[4]= 1;

            if(s->dsp.sad[1](NULL, ptr_cr              , dest_cr              , wrap_c, 8) < 20*s->qscale) skip_dct[5]= 1;

            if(!s->chroma_y_shift){ /* 422 */

                if(s->dsp.sad[1](NULL, ptr_cb +(dct_offset>>1), dest_cb +(dct_offset>>1), wrap_c, 8) < 20*s->qscale) skip_dct[6]= 1;

                if(s->dsp.sad[1](NULL, ptr_cr +(dct_offset>>1), dest_cr +(dct_offset>>1), wrap_c, 8) < 20*s->qscale) skip_dct[7]= 1;

            }

        }

    }

    if(s->avctx->quantizer_noise_shaping){

        if(!skip_dct[0]) get_visual_weight(weight[0], ptr_y                 , wrap_y);

        if(!skip_dct[1]) get_visual_weight(weight[1], ptr_y              + 8, wrap_y);

        if(!skip_dct[2]) get_visual_weight(weight[2], ptr_y + dct_offset    , wrap_y);

        if(!skip_dct[3]) get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);

        if(!skip_dct[4]) get_visual_weight(weight[4], ptr_cb                , wrap_c);

        if(!skip_dct[5]) get_visual_weight(weight[5], ptr_cr                , wrap_c);

        if(!s->chroma_y_shift){ /* 422 */

            if(!skip_dct[6]) get_visual_weight(weight[6], ptr_cb + (dct_offset>>1), wrap_c);

            if(!skip_dct[7]) get_visual_weight(weight[7], ptr_cr + (dct_offset>>1), wrap_c);

        }

        memcpy(orig[0], s->block[0], sizeof(DCTELEM)*64*mb_block_count);

    }

    /* DCT & quantize */

    assert(s->out_format!=FMT_MJPEG || s->qscale==8);

    {

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

            if(!skip_dct[i]){

                int overflow;

                s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);

            // FIXME we could decide to change to quantizer instead of clipping

            // JS: I don't think that would be a good idea it could lower quality instead

            //     of improve it. Just INTRADC clipping deserves changes in quantizer

                if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);

            }else

                s->block_last_index[i]= -1;

        }

        if(s->avctx->quantizer_noise_shaping){

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

                if(!skip_dct[i]){

                    s->block_last_index[i] = dct_quantize_refine(s, s->block[i], weight[i], orig[i], i, s->qscale);

                }

            }

        }

        if(s->luma_elim_threshold && !s->mb_intra)

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

                dct_single_coeff_elimination(s, i, s->luma_elim_threshold);

        if(s->chroma_elim_threshold && !s->mb_intra)

            for(i=4; i<mb_block_count; i++)

                dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);

        if(s->flags & CODEC_FLAG_CBP_RD){

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

                if(s->block_last_index[i] == -1)

                    s->coded_score[i]= INT_MAX/256;

            }

        }

    }

    if((s->flags&CODEC_FLAG_GRAY) && s->mb_intra){

        s->block_last_index[4]=

        s->block_last_index[5]= 0;

        s->block[4][0]=

        s->block[5][0]= (1024 + s->c_dc_scale/2)/ s->c_dc_scale;

    }

    //non c quantize code returns incorrect block_last_index FIXME

    if(s->alternate_scan && s->dct_quantize != dct_quantize_c){

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

            int j;

            if(s->block_last_index[i]>0){

                for(j=63; j>0; j--){

                    if(s->block[i][ s->intra_scantable.permutated[j] ]) break;

                }

                s->block_last_index[i]= j;

            }

        }

    }

    /* huffman encode */

    switch(s->codec_id){ //FIXME funct ptr could be slightly faster

    case CODEC_ID_MPEG1VIDEO:

    case CODEC_ID_MPEG2VIDEO:

        if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)

            mpeg1_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case CODEC_ID_MPEG4:

        if (CONFIG_MPEG4_ENCODER)

            mpeg4_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case CODEC_ID_MSMPEG4V2:

    case CODEC_ID_MSMPEG4V3:

    case CODEC_ID_WMV1:

        if (CONFIG_MSMPEG4_ENCODER)

            msmpeg4_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case CODEC_ID_WMV2:

        if (CONFIG_WMV2_ENCODER)

            ff_wmv2_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case CODEC_ID_H261:

        if (CONFIG_H261_ENCODER)

            ff_h261_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case CODEC_ID_H263:

    case CODEC_ID_H263P:

    case CODEC_ID_FLV1:

    case CODEC_ID_RV10:

    case CODEC_ID_RV20:

        if (CONFIG_H263_ENCODER || CONFIG_H263P_ENCODER ||

            CONFIG_FLV_ENCODER  || CONFIG_RV10_ENCODER  || CONFIG_RV20_ENCODER)

            h263_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case CODEC_ID_MJPEG:

        if (CONFIG_MJPEG_ENCODER)

            ff_mjpeg_encode_mb(s, s->block);

        break;

    default:

        assert(0);

    }

}


vpc_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,

               QEMUIOVector *qiov, int flags)

{

    BDRVVPCState *s = bs->opaque;

    int64_t image_offset;

    int64_t n_bytes;

    int64_t bytes_done = 0;

    int ret;

    VHDFooter *footer =  (VHDFooter *) s->footer_buf;

    QEMUIOVector local_qiov;

    if (be32_to_cpu(footer->type) == VHD_FIXED) {

        return bdrv_co_pwritev(bs->file, offset, bytes, qiov, 0);

    }

    qemu_co_mutex_lock(&s->lock);

    qemu_iovec_init(&local_qiov, qiov->niov);

    while (bytes > 0) {

        image_offset = get_image_offset(bs, offset, true);

        n_bytes = MIN(bytes, s->block_size - (offset % s->block_size));

        if (image_offset == -1) {

            image_offset = alloc_block(bs, offset);

            if (image_offset < 0) {

                ret = image_offset;

                goto fail;

            }

        }

        qemu_iovec_reset(&local_qiov);

        qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);

        ret = bdrv_co_pwritev(bs->file, image_offset, n_bytes,

                              &local_qiov, 0);

        if (ret < 0) {

            goto fail;

        }

        bytes -= n_bytes;

        offset += n_bytes;

        bytes_done += n_bytes;

    }

    ret = 0;

fail:

    qemu_iovec_destroy(&local_qiov);

    qemu_co_mutex_unlock(&s->lock);

    return ret;

}


bool memory_region_present(MemoryRegion *container, hwaddr addr)

{

    MemoryRegion *mr = memory_region_find(container, addr, 1).mr;

    if (!mr || (mr == container)) {

        return false;

    }

    memory_region_unref(mr);

    return true;

}


static void tcg_out_qemu_ld_slow_path(TCGContext *s, TCGLabelQemuLdst *l)

{

    TCGMemOp opc = l->opc;

    TCGReg data_reg;

    uint8_t **label_ptr = &l->label_ptr[0];

    /* resolve label address */

    *(uint32_t *)label_ptr[0] = (uint32_t)(s->code_ptr - label_ptr[0] - 4);

    if (TARGET_LONG_BITS > TCG_TARGET_REG_BITS) {

        *(uint32_t *)label_ptr[1] = (uint32_t)(s->code_ptr - label_ptr[1] - 4);

    }

    if (TCG_TARGET_REG_BITS == 32) {

        int ofs = 0;

        tcg_out_st(s, TCG_TYPE_PTR, TCG_AREG0, TCG_REG_ESP, ofs);

        ofs += 4;

        tcg_out_st(s, TCG_TYPE_I32, l->addrlo_reg, TCG_REG_ESP, ofs);

        ofs += 4;

        if (TARGET_LONG_BITS == 64) {

            tcg_out_st(s, TCG_TYPE_I32, l->addrhi_reg, TCG_REG_ESP, ofs);

            ofs += 4;

        }

        tcg_out_sti(s, TCG_TYPE_I32, TCG_REG_ESP, ofs, l->mem_index);

        ofs += 4;

        tcg_out_sti(s, TCG_TYPE_I32, TCG_REG_ESP, ofs, (uintptr_t)l->raddr);

    } else {

        tcg_out_mov(s, TCG_TYPE_PTR, tcg_target_call_iarg_regs[0], TCG_AREG0);

        /* The second argument is already loaded with addrlo.  */

        tcg_out_movi(s, TCG_TYPE_I32, tcg_target_call_iarg_regs[2],

                     l->mem_index);

        tcg_out_movi(s, TCG_TYPE_PTR, tcg_target_call_iarg_regs[3],

                     (uintptr_t)l->raddr);

    }

    tcg_out_calli(s, (uintptr_t)qemu_ld_helpers[opc & ~MO_SIGN]);

    data_reg = l->datalo_reg;

    switch (opc & MO_SSIZE) {

    case MO_SB:

        tcg_out_ext8s(s, data_reg, TCG_REG_EAX, P_REXW);

        break;

    case MO_SW:

        tcg_out_ext16s(s, data_reg, TCG_REG_EAX, P_REXW);

        break;

#if TCG_TARGET_REG_BITS == 64

    case MO_SL:

        tcg_out_ext32s(s, data_reg, TCG_REG_EAX);

        break;

#endif

    case MO_UB:

    case MO_UW:

        /* Note that the helpers have zero-extended to tcg_target_long.  */

    case MO_UL:

        tcg_out_mov(s, TCG_TYPE_I32, data_reg, TCG_REG_EAX);

        break;

    case MO_Q:

        if (TCG_TARGET_REG_BITS == 64) {

            tcg_out_mov(s, TCG_TYPE_I64, data_reg, TCG_REG_RAX);

        } else if (data_reg == TCG_REG_EDX) {

            /* xchg %edx, %eax */

            tcg_out_opc(s, OPC_XCHG_ax_r32 + TCG_REG_EDX, 0, 0, 0);

            tcg_out_mov(s, TCG_TYPE_I32, l->datahi_reg, TCG_REG_EAX);

        } else {

            tcg_out_mov(s, TCG_TYPE_I32, data_reg, TCG_REG_EAX);

            tcg_out_mov(s, TCG_TYPE_I32, l->datahi_reg, TCG_REG_EDX);

        }

        break;

    default:

        tcg_abort();

    }

    /* Jump to the code corresponding to next IR of qemu_st */

    tcg_out_jmp(s, (uintptr_t)l->raddr);

}


static long do_sigreturn_v1(CPUARMState *env)

{

        abi_ulong frame_addr;

	struct sigframe_v1 *frame;

	target_sigset_t set;

        sigset_t host_set;

        int i;

	/*

	 * Since we stacked the signal on a 64-bit boundary,

	 * then 'sp' should be word aligned here.  If it's

	 * not, then the user is trying to mess with us.

	 */

	if (env->regs[13] & 7)

		goto badframe;

        frame_addr = env->regs[13];

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

                goto badframe;

	if (__get_user(set.sig[0], &frame->sc.oldmask))

            goto badframe;

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

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

                goto badframe;

        }

        target_to_host_sigset_internal(&host_set, &set);

        sigprocmask(SIG_SETMASK, &host_set, NULL);

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

		goto badframe;

#if 0

	/* Send SIGTRAP if we're single-stepping */

	if (ptrace_cancel_bpt(current))

		send_sig(SIGTRAP, current, 1);

#endif

	unlock_user_struct(frame, frame_addr, 0);

        return env->regs[0];

badframe:

	unlock_user_struct(frame, frame_addr, 0);

        force_sig(TARGET_SIGSEGV /* , current */);

	return 0;

}


static void tcp_chr_connect(void *opaque)

{

    CharDriverState *chr = opaque;

    TCPCharDriver *s = chr->opaque;

    QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(s->ioc);

    g_free(chr->filename);

    chr->filename = sockaddr_to_str(&sioc->localAddr, sioc->localAddrLen,

                                    &sioc->remoteAddr, sioc->remoteAddrLen,

                                    s->is_listen, s->is_telnet);

    s->connected = 1;

    if (s->ioc) {

        chr->fd_in_tag = io_add_watch_poll(s->ioc,

                                           tcp_chr_read_poll,

                                           tcp_chr_read, chr);

    }

    qemu_chr_be_generic_open(chr);

}


static void gen_muldiv (DisasContext *ctx, uint32_t opc,

                        int rs, int rt)

{

    const char *opn = "mul/div";

    TCGv t0, t1;

    unsigned int acc;

    switch (opc) {

    case OPC_DIV:

    case OPC_DIVU:

#if defined(TARGET_MIPS64)

    case OPC_DDIV:

    case OPC_DDIVU:

#endif

        t0 = tcg_temp_local_new();

        t1 = tcg_temp_local_new();

        break;

    default:

        t0 = tcg_temp_new();

        t1 = tcg_temp_new();

        break;

    }

    gen_load_gpr(t0, rs);

    gen_load_gpr(t1, rt);

    switch (opc) {

    case OPC_DIV:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            tcg_gen_ext32s_tl(t0, t0);

            tcg_gen_ext32s_tl(t1, t1);

            tcg_gen_brcondi_tl(TCG_COND_EQ, t1, 0, l1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t0, INT_MIN, l2);

            tcg_gen_brcondi_tl(TCG_COND_NE, t1, -1, l2);

            tcg_gen_mov_tl(cpu_LO[0], t0);

            tcg_gen_movi_tl(cpu_HI[0], 0);

            tcg_gen_br(l1);

            gen_set_label(l2);

            tcg_gen_div_tl(cpu_LO[0], t0, t1);

            tcg_gen_rem_tl(cpu_HI[0], t0, t1);

            tcg_gen_ext32s_tl(cpu_LO[0], cpu_LO[0]);

            tcg_gen_ext32s_tl(cpu_HI[0], cpu_HI[0]);

            gen_set_label(l1);

        }

        opn = "div";

        break;

    case OPC_DIVU:

        {

            int l1 = gen_new_label();

            tcg_gen_ext32u_tl(t0, t0);

            tcg_gen_ext32u_tl(t1, t1);

            tcg_gen_brcondi_tl(TCG_COND_EQ, t1, 0, l1);

            tcg_gen_divu_tl(cpu_LO[0], t0, t1);

            tcg_gen_remu_tl(cpu_HI[0], t0, t1);

            tcg_gen_ext32s_tl(cpu_LO[0], cpu_LO[0]);

            tcg_gen_ext32s_tl(cpu_HI[0], cpu_HI[0]);

            gen_set_label(l1);

        }

        opn = "divu";

        break;

    case OPC_MULT:

        {

            TCGv_i64 t2 = tcg_temp_new_i64();

            TCGv_i64 t3 = tcg_temp_new_i64();

            acc = ((ctx->opcode) >> 11) & 0x03;

            if (acc != 0) {

                check_dsp(ctx);

            }

            tcg_gen_ext_tl_i64(t2, t0);

            tcg_gen_ext_tl_i64(t3, t1);

            tcg_gen_mul_i64(t2, t2, t3);

            tcg_temp_free_i64(t3);

            tcg_gen_trunc_i64_tl(t0, t2);

            tcg_gen_shri_i64(t2, t2, 32);

            tcg_gen_trunc_i64_tl(t1, t2);

            tcg_temp_free_i64(t2);

            tcg_gen_ext32s_tl(cpu_LO[acc], t0);

            tcg_gen_ext32s_tl(cpu_HI[acc], t1);

        }

        opn = "mult";

        break;

    case OPC_MULTU:

        {

            TCGv_i64 t2 = tcg_temp_new_i64();

            TCGv_i64 t3 = tcg_temp_new_i64();

            acc = ((ctx->opcode) >> 11) & 0x03;

            if (acc != 0) {

                check_dsp(ctx);

            }

            tcg_gen_ext32u_tl(t0, t0);

            tcg_gen_ext32u_tl(t1, t1);

            tcg_gen_extu_tl_i64(t2, t0);

            tcg_gen_extu_tl_i64(t3, t1);

            tcg_gen_mul_i64(t2, t2, t3);

            tcg_temp_free_i64(t3);

            tcg_gen_trunc_i64_tl(t0, t2);

            tcg_gen_shri_i64(t2, t2, 32);

            tcg_gen_trunc_i64_tl(t1, t2);

            tcg_temp_free_i64(t2);

            tcg_gen_ext32s_tl(cpu_LO[acc], t0);

            tcg_gen_ext32s_tl(cpu_HI[acc], t1);

        }

        opn = "multu";

        break;

#if defined(TARGET_MIPS64)

    case OPC_DDIV:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            tcg_gen_brcondi_tl(TCG_COND_EQ, t1, 0, l1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t0, -1LL << 63, l2);

            tcg_gen_brcondi_tl(TCG_COND_NE, t1, -1LL, l2);

            tcg_gen_mov_tl(cpu_LO[0], t0);

            tcg_gen_movi_tl(cpu_HI[0], 0);

            tcg_gen_br(l1);

            gen_set_label(l2);

            tcg_gen_div_i64(cpu_LO[0], t0, t1);

            tcg_gen_rem_i64(cpu_HI[0], t0, t1);

            gen_set_label(l1);

        }

        opn = "ddiv";

        break;

    case OPC_DDIVU:

        {

            int l1 = gen_new_label();

            tcg_gen_brcondi_tl(TCG_COND_EQ, t1, 0, l1);

            tcg_gen_divu_i64(cpu_LO[0], t0, t1);

            tcg_gen_remu_i64(cpu_HI[0], t0, t1);

            gen_set_label(l1);

        }

        opn = "ddivu";

        break;

    case OPC_DMULT:

        gen_helper_dmult(cpu_env, t0, t1);

        opn = "dmult";

        break;

    case OPC_DMULTU:

        gen_helper_dmultu(cpu_env, t0, t1);

        opn = "dmultu";

        break;

#endif

    case OPC_MADD:

        {

            TCGv_i64 t2 = tcg_temp_new_i64();

            TCGv_i64 t3 = tcg_temp_new_i64();

            acc = ((ctx->opcode) >> 11) & 0x03;

            if (acc != 0) {

                check_dsp(ctx);

            }

            tcg_gen_ext_tl_i64(t2, t0);

            tcg_gen_ext_tl_i64(t3, t1);

            tcg_gen_mul_i64(t2, t2, t3);

            tcg_gen_concat_tl_i64(t3, cpu_LO[acc], cpu_HI[acc]);

            tcg_gen_add_i64(t2, t2, t3);

            tcg_temp_free_i64(t3);

            tcg_gen_trunc_i64_tl(t0, t2);

            tcg_gen_shri_i64(t2, t2, 32);

            tcg_gen_trunc_i64_tl(t1, t2);

            tcg_temp_free_i64(t2);

            tcg_gen_ext32s_tl(cpu_LO[acc], t0);

            tcg_gen_ext32s_tl(cpu_HI[acc], t1);

        }

        opn = "madd";

        break;

    case OPC_MADDU:

        {

            TCGv_i64 t2 = tcg_temp_new_i64();

            TCGv_i64 t3 = tcg_temp_new_i64();

            acc = ((ctx->opcode) >> 11) & 0x03;

            if (acc != 0) {

                check_dsp(ctx);

            }

            tcg_gen_ext32u_tl(t0, t0);

            tcg_gen_ext32u_tl(t1, t1);

            tcg_gen_extu_tl_i64(t2, t0);

            tcg_gen_extu_tl_i64(t3, t1);

            tcg_gen_mul_i64(t2, t2, t3);

            tcg_gen_concat_tl_i64(t3, cpu_LO[acc], cpu_HI[acc]);

            tcg_gen_add_i64(t2, t2, t3);

            tcg_temp_free_i64(t3);

            tcg_gen_trunc_i64_tl(t0, t2);

            tcg_gen_shri_i64(t2, t2, 32);

            tcg_gen_trunc_i64_tl(t1, t2);

            tcg_temp_free_i64(t2);

            tcg_gen_ext32s_tl(cpu_LO[acc], t0);

            tcg_gen_ext32s_tl(cpu_HI[acc], t1);

        }

        opn = "maddu";

        break;

    case OPC_MSUB:

        {

            TCGv_i64 t2 = tcg_temp_new_i64();

            TCGv_i64 t3 = tcg_temp_new_i64();

            acc = ((ctx->opcode) >> 11) & 0x03;

            if (acc != 0) {

                check_dsp(ctx);

            }

            tcg_gen_ext_tl_i64(t2, t0);

            tcg_gen_ext_tl_i64(t3, t1);

            tcg_gen_mul_i64(t2, t2, t3);

            tcg_gen_concat_tl_i64(t3, cpu_LO[acc], cpu_HI[acc]);

            tcg_gen_sub_i64(t2, t3, t2);

            tcg_temp_free_i64(t3);

            tcg_gen_trunc_i64_tl(t0, t2);

            tcg_gen_shri_i64(t2, t2, 32);

            tcg_gen_trunc_i64_tl(t1, t2);

            tcg_temp_free_i64(t2);

            tcg_gen_ext32s_tl(cpu_LO[acc], t0);

            tcg_gen_ext32s_tl(cpu_HI[acc], t1);

        }

        opn = "msub";

        break;

    case OPC_MSUBU:

        {

            TCGv_i64 t2 = tcg_temp_new_i64();

            TCGv_i64 t3 = tcg_temp_new_i64();

            acc = ((ctx->opcode) >> 11) & 0x03;

            if (acc != 0) {

                check_dsp(ctx);

            }

            tcg_gen_ext32u_tl(t0, t0);

            tcg_gen_ext32u_tl(t1, t1);

            tcg_gen_extu_tl_i64(t2, t0);

            tcg_gen_extu_tl_i64(t3, t1);

            tcg_gen_mul_i64(t2, t2, t3);

            tcg_gen_concat_tl_i64(t3, cpu_LO[acc], cpu_HI[acc]);

            tcg_gen_sub_i64(t2, t3, t2);

            tcg_temp_free_i64(t3);

            tcg_gen_trunc_i64_tl(t0, t2);

            tcg_gen_shri_i64(t2, t2, 32);

            tcg_gen_trunc_i64_tl(t1, t2);

            tcg_temp_free_i64(t2);

            tcg_gen_ext32s_tl(cpu_LO[acc], t0);

            tcg_gen_ext32s_tl(cpu_HI[acc], t1);

        }

        opn = "msubu";

        break;

    default:

        MIPS_INVAL(opn);

        generate_exception(ctx, EXCP_RI);

        goto out;

    }

    (void)opn; /* avoid a compiler warning */

    MIPS_DEBUG("%s %s %s", opn, regnames[rs], regnames[rt]);

 out:

    tcg_temp_free(t0);

    tcg_temp_free(t1);

}


static void usb_msd_copy_data(MSDState *s)

{

    uint32_t len;

    len = s->usb_len;

    if (len > s->scsi_len)

        len = s->scsi_len;

    if (s->mode == USB_MSDM_DATAIN) {

        memcpy(s->usb_buf, s->scsi_buf, len);

    } else {

        memcpy(s->scsi_buf, s->usb_buf, len);

    }

    s->usb_len -= len;

    s->scsi_len -= len;

    s->usb_buf += len;

    s->scsi_buf += len;

    s->data_len -= len;

    if (s->scsi_len == 0 || s->data_len == 0) {

        if (s->mode == USB_MSDM_DATAIN) {

            s->scsi_dev->info->read_data(s->scsi_dev, s->tag);

        } else if (s->mode == USB_MSDM_DATAOUT) {

            s->scsi_dev->info->write_data(s->scsi_dev, s->tag);

        }

    }

}


void av_log_format_line(void *ptr, int level, const char *fmt, va_list vl,

                        char *line, int line_size, int *print_prefix)

{

    char part[3][512];

    format_line(ptr, level, fmt, vl, part, sizeof(part[0]), print_prefix, NULL);

    snprintf(line, line_size, "%s%s%s", part[0], part[1], part[2]);

}


static inline void RENAME(rgb32tobgr15)(const uint8_t *src, uint8_t *dst, long src_size)

{

	const uint8_t *s = src;

	const uint8_t *end;

#ifdef HAVE_MMX

	const uint8_t *mm_end;

#endif

	uint16_t *d = (uint16_t *)dst;

	end = s + src_size;

#ifdef HAVE_MMX

	__asm __volatile(PREFETCH"	%0"::"m"(*src):"memory");

	__asm __volatile(

	    "movq	%0, %%mm7\n\t"

	    "movq	%1, %%mm6\n\t"

	    ::"m"(red_15mask),"m"(green_15mask));

	mm_end = end - 15;

	while(s < mm_end)

	{

	    __asm __volatile(

		PREFETCH" 32%1\n\t"

		"movd	%1, %%mm0\n\t"

		"movd	4%1, %%mm3\n\t"

		"punpckldq 8%1, %%mm0\n\t"

		"punpckldq 12%1, %%mm3\n\t"

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

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

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

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

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

		"psllq	$7, %%mm3\n\t"

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

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

		"psrlq	$6, %%mm1\n\t"

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

		"pand	%%mm6, %%mm1\n\t"

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

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

		"psrlq	$19, %%mm5\n\t"

		"pand	%2, %%mm2\n\t"

		"pand	%2, %%mm5\n\t"

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

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

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

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

		"psllq	$16, %%mm3\n\t"

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

		MOVNTQ"	%%mm0, %0\n\t"

		:"=m"(*d):"m"(*s),"m"(blue_15mask):"memory");

		d += 4;

		s += 16;

	}

	__asm __volatile(SFENCE:::"memory");

	__asm __volatile(EMMS:::"memory");

#endif

	while(s < end)

	{

		register int rgb = *(uint32_t*)s; s += 4;

		*d++ = ((rgb&0xF8)<<7) + ((rgb&0xF800)>>6) + ((rgb&0xF80000)>>19);

	}

}


static int http_receive_data(HTTPContext *c)

{

    HTTPContext *c1;

    if (c->buffer_end > c->buffer_ptr) {

        int len;

        len = recv(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);

        if (len < 0) {

            if (ff_neterrno() != FF_NETERROR(EAGAIN) &&

                ff_neterrno() != FF_NETERROR(EINTR))

                /* error : close connection */

                goto fail;

        } else if (len == 0)

            /* end of connection : close it */

            goto fail;

        else {

            c->buffer_ptr += len;

            c->data_count += len;

            update_datarate(&c->datarate, c->data_count);

        }

    }

    if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {

        if (c->buffer[0] != 'f' ||

            c->buffer[1] != 'm') {

            http_log("Feed stream has become desynchronized -- disconnecting\n");

            goto fail;

        }

    }

    if (c->buffer_ptr >= c->buffer_end) {

        FFStream *feed = c->stream;

        /* a packet has been received : write it in the store, except

           if header */

        if (c->data_count > FFM_PACKET_SIZE) {

            //            printf("writing pos=0x%"PRIx64" size=0x%"PRIx64"\n", feed->feed_write_index, feed->feed_size);

            /* XXX: use llseek or url_seek */

            lseek(c->feed_fd, feed->feed_write_index, SEEK_SET);

            if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {

                http_log("Error writing to feed file: %s\n", strerror(errno));

                goto fail;

            }

            feed->feed_write_index += FFM_PACKET_SIZE;

            /* update file size */

            if (feed->feed_write_index > c->stream->feed_size)

                feed->feed_size = feed->feed_write_index;

            /* handle wrap around if max file size reached */

            if (c->stream->feed_max_size && feed->feed_write_index >= c->stream->feed_max_size)

                feed->feed_write_index = FFM_PACKET_SIZE;

            /* write index */

            ffm_write_write_index(c->feed_fd, feed->feed_write_index);

            /* wake up any waiting connections */

            for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {

                if (c1->state == HTTPSTATE_WAIT_FEED &&

                    c1->stream->feed == c->stream->feed)

                    c1->state = HTTPSTATE_SEND_DATA;

            }

        } else {

            /* We have a header in our hands that contains useful data */

            AVFormatContext *s = NULL;

            ByteIOContext *pb;

            AVInputFormat *fmt_in;

            int i;

            url_open_buf(&pb, c->buffer, c->buffer_end - c->buffer, URL_RDONLY);

            pb->is_streamed = 1;

            /* use feed output format name to find corresponding input format */

            fmt_in = av_find_input_format(feed->fmt->name);

            if (!fmt_in)

                goto fail;

            av_open_input_stream(&s, pb, c->stream->feed_filename, fmt_in, NULL);

            /* Now we have the actual streams */

            if (s->nb_streams != feed->nb_streams) {

                av_close_input_stream(s);

                av_free(pb);

                goto fail;

            }

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

                memcpy(feed->streams[i]->codec,

                       s->streams[i]->codec, sizeof(AVCodecContext));

            av_close_input_stream(s);

            av_free(pb);

        }

        c->buffer_ptr = c->buffer;

    }

    return 0;

 fail:

    c->stream->feed_opened = 0;

    close(c->feed_fd);

    /* wake up any waiting connections to stop waiting for feed */

    for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {

        if (c1->state == HTTPSTATE_WAIT_FEED &&

            c1->stream->feed == c->stream->feed)

            c1->state = HTTPSTATE_SEND_DATA_TRAILER;

    }

    return -1;

}


uint32_t kvmppc_get_dfp(void)

{

    return kvmppc_read_int_cpu_dt("ibm,dfp");

}


static int send_full_color_rect(VncState *vs, int w, int h)

{

    int stream = 0;

    size_t bytes;

    vnc_write_u8(vs, stream << 4); /* no flushing, no filter */

    if (vs->tight_pixel24) {

        tight_pack24(vs, vs->tight.buffer, w * h, &vs->tight.offset);

        bytes = 3;

    } else {

        bytes = vs->clientds.pf.bytes_per_pixel;

    }

    bytes = tight_compress_data(vs, stream, w * h * bytes,

                                tight_conf[vs->tight_compression].raw_zlib_level,

                                Z_DEFAULT_STRATEGY);

    return (bytes >= 0);

}


static void test_visitor_in_string(TestInputVisitorData *data,

                                   const void *unused)

{

    char *res = NULL, *value = (char *) "Q E M U";

    Visitor *v;

    v = visitor_input_test_init(data, "%s", value);

    visit_type_str(v, NULL, &res, &error_abort);

    g_assert_cmpstr(res, ==, value);

    g_free(res);

}


static int kvm_init(MachineState *ms)

{

    MachineClass *mc = MACHINE_GET_CLASS(ms);

    static const char upgrade_note[] =

        "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"

        "(see http://sourceforge.net/projects/kvm).\n";

    struct {

        const char *name;

        int num;

    } num_cpus[] = {

        { "SMP",          smp_cpus },

        { "hotpluggable", max_cpus },

        { NULL, }

    }, *nc = num_cpus;

    int soft_vcpus_limit, hard_vcpus_limit;

    KVMState *s;

    const KVMCapabilityInfo *missing_cap;

    int ret;

    int type = 0;

    const char *kvm_type;

    s = KVM_STATE(ms->accelerator);

    /*

     * On systems where the kernel can support different base page

     * sizes, host page size may be different from TARGET_PAGE_SIZE,

     * even with KVM.  TARGET_PAGE_SIZE is assumed to be the minimum

     * page size for the system though.

     */

    assert(TARGET_PAGE_SIZE <= getpagesize());

    page_size_init();

    s->sigmask_len = 8;

#ifdef KVM_CAP_SET_GUEST_DEBUG

    QTAILQ_INIT(&s->kvm_sw_breakpoints);

#endif

    s->vmfd = -1;

    s->fd = qemu_open("/dev/kvm", O_RDWR);

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

        fprintf(stderr, "Could not access KVM kernel module: %m\n");

        ret = -errno;

        goto err;

    }

    ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);

    if (ret < KVM_API_VERSION) {

        if (ret >= 0) {

            ret = -EINVAL;

        }

        fprintf(stderr, "kvm version too old\n");

        goto err;

    }

    if (ret > KVM_API_VERSION) {

        ret = -EINVAL;

        fprintf(stderr, "kvm version not supported\n");

        goto err;

    }

    s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);

    /* If unspecified, use the default value */

    if (!s->nr_slots) {

        s->nr_slots = 32;

    }

    /* check the vcpu limits */

    soft_vcpus_limit = kvm_recommended_vcpus(s);

    hard_vcpus_limit = kvm_max_vcpus(s);

    while (nc->name) {

        if (nc->num > soft_vcpus_limit) {

            fprintf(stderr,

                    "Warning: Number of %s cpus requested (%d) exceeds "

                    "the recommended cpus supported by KVM (%d)\n",

                    nc->name, nc->num, soft_vcpus_limit);

            if (nc->num > hard_vcpus_limit) {

                fprintf(stderr, "Number of %s cpus requested (%d) exceeds "

                        "the maximum cpus supported by KVM (%d)\n",

                        nc->name, nc->num, hard_vcpus_limit);

                exit(1);

            }

        }

        nc++;

    }

    kvm_type = qemu_opt_get(qemu_get_machine_opts(), "kvm-type");

    if (mc->kvm_type) {

        type = mc->kvm_type(kvm_type);

    } else if (kvm_type) {

        ret = -EINVAL;

        fprintf(stderr, "Invalid argument kvm-type=%s\n", kvm_type);

        goto err;

    }

    do {

        ret = kvm_ioctl(s, KVM_CREATE_VM, type);

    } while (ret == -EINTR);

    if (ret < 0) {

        fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,

                strerror(-ret));

#ifdef TARGET_S390X

        if (ret == -EINVAL) {

            fprintf(stderr,

                    "Host kernel setup problem detected. Please verify:\n");

            fprintf(stderr, "- for kernels supporting the switch_amode or"

                    " user_mode parameters, whether\n");

            fprintf(stderr,

                    "  user space is running in primary address space\n");

            fprintf(stderr,

                    "- for kernels supporting the vm.allocate_pgste sysctl, "

                    "whether it is enabled\n");

        }

#endif

        goto err;

    }

    s->vmfd = ret;

    missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);

    if (!missing_cap) {

        missing_cap =

            kvm_check_extension_list(s, kvm_arch_required_capabilities);

    }

    if (missing_cap) {

        ret = -EINVAL;

        fprintf(stderr, "kvm does not support %s\n%s",

                missing_cap->name, upgrade_note);

        goto err;

    }

    s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);

    s->broken_set_mem_region = 1;

    ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);

    if (ret > 0) {

        s->broken_set_mem_region = 0;

    }

#ifdef KVM_CAP_VCPU_EVENTS

    s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);

#endif

    s->robust_singlestep =

        kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);

#ifdef KVM_CAP_DEBUGREGS

    s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);

#endif

#ifdef KVM_CAP_XSAVE

    s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE);

#endif

#ifdef KVM_CAP_XCRS

    s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS);

#endif

#ifdef KVM_CAP_PIT_STATE2

    s->pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);

#endif

#ifdef KVM_CAP_IRQ_ROUTING

    kvm_direct_msi_allowed = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);

#endif

    s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);

    s->irq_set_ioctl = KVM_IRQ_LINE;

    if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {

        s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;

    }

#ifdef KVM_CAP_READONLY_MEM

    kvm_readonly_mem_allowed =

        (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);

#endif

    kvm_eventfds_allowed =

        (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);

    kvm_irqfds_allowed =

        (kvm_check_extension(s, KVM_CAP_IRQFD) > 0);

    kvm_resamplefds_allowed =

        (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);

    kvm_vm_attributes_allowed =

        (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);

    ret = kvm_arch_init(ms, s);

    if (ret < 0) {

        goto err;

    }

    if (machine_kernel_irqchip_allowed(ms)) {

        kvm_irqchip_create(ms, s);

    }

    kvm_state = s;

    s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;

    s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;

    s->memory_listener.listener.coalesced_mmio_add = kvm_coalesce_mmio_region;

    s->memory_listener.listener.coalesced_mmio_del = kvm_uncoalesce_mmio_region;

    kvm_memory_listener_register(s, &s->memory_listener,

                                 &address_space_memory, 0);

    memory_listener_register(&kvm_io_listener,

                             &address_space_io);

    s->many_ioeventfds = kvm_check_many_ioeventfds();

    cpu_interrupt_handler = kvm_handle_interrupt;

    return 0;

err:

    assert(ret < 0);

    if (s->vmfd >= 0) {

        close(s->vmfd);

    }

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

        close(s->fd);

    }

    g_free(s->memory_listener.slots);

    return ret;

}


static void qemu_gluster_gconf_free(GlusterConf *gconf)

{

    g_free(gconf->server);

    g_free(gconf->volname);

    g_free(gconf->image);

    g_free(gconf->transport);

    g_free(gconf);

}


void net_tx_pkt_init(struct NetTxPkt **pkt, uint32_t max_frags,

    bool has_virt_hdr)

{

    struct NetTxPkt *p = g_malloc0(sizeof *p);

    p->vec = g_malloc((sizeof *p->vec) *

        (max_frags + NET_TX_PKT_PL_START_FRAG));

    p->raw = g_malloc((sizeof *p->raw) * max_frags);

    p->max_payload_frags = max_frags;

    p->max_raw_frags = max_frags;

    p->has_virt_hdr = has_virt_hdr;

    p->vec[NET_TX_PKT_VHDR_FRAG].iov_base = &p->virt_hdr;

    p->vec[NET_TX_PKT_VHDR_FRAG].iov_len =

        p->has_virt_hdr ? sizeof p->virt_hdr : 0;

    p->vec[NET_TX_PKT_L2HDR_FRAG].iov_base = &p->l2_hdr;

    p->vec[NET_TX_PKT_L3HDR_FRAG].iov_base = NULL;

    p->vec[NET_TX_PKT_L3HDR_FRAG].iov_len = 0;

    *pkt = p;

}


static void vtd_init(IntelIOMMUState *s)

{

    memset(s->csr, 0, DMAR_REG_SIZE);

    memset(s->wmask, 0, DMAR_REG_SIZE);

    memset(s->w1cmask, 0, DMAR_REG_SIZE);

    memset(s->womask, 0, DMAR_REG_SIZE);

    s->iommu_ops.translate = vtd_iommu_translate;

    s->root = 0;

    s->root_extended = false;

    s->dmar_enabled = false;

    s->iq_head = 0;

    s->iq_tail = 0;

    s->iq = 0;

    s->iq_size = 0;

    s->qi_enabled = false;

    s->iq_last_desc_type = VTD_INV_DESC_NONE;

    s->next_frcd_reg = 0;

    s->cap = VTD_CAP_FRO | VTD_CAP_NFR | VTD_CAP_ND | VTD_CAP_MGAW |

             VTD_CAP_SAGAW | VTD_CAP_MAMV | VTD_CAP_PSI;

    s->ecap = VTD_ECAP_QI | VTD_ECAP_IRO;

    vtd_reset_context_cache(s);

    vtd_reset_iotlb(s);

    /* Define registers with default values and bit semantics */

    vtd_define_long(s, DMAR_VER_REG, 0x10UL, 0, 0);

    vtd_define_quad(s, DMAR_CAP_REG, s->cap, 0, 0);

    vtd_define_quad(s, DMAR_ECAP_REG, s->ecap, 0, 0);

    vtd_define_long(s, DMAR_GCMD_REG, 0, 0xff800000UL, 0);

    vtd_define_long_wo(s, DMAR_GCMD_REG, 0xff800000UL);

    vtd_define_long(s, DMAR_GSTS_REG, 0, 0, 0);

    vtd_define_quad(s, DMAR_RTADDR_REG, 0, 0xfffffffffffff000ULL, 0);

    vtd_define_quad(s, DMAR_CCMD_REG, 0, 0xe0000003ffffffffULL, 0);

    vtd_define_quad_wo(s, DMAR_CCMD_REG, 0x3ffff0000ULL);

    /* Advanced Fault Logging not supported */

    vtd_define_long(s, DMAR_FSTS_REG, 0, 0, 0x11UL);

    vtd_define_long(s, DMAR_FECTL_REG, 0x80000000UL, 0x80000000UL, 0);

    vtd_define_long(s, DMAR_FEDATA_REG, 0, 0x0000ffffUL, 0);

    vtd_define_long(s, DMAR_FEADDR_REG, 0, 0xfffffffcUL, 0);

    /* Treated as RsvdZ when EIM in ECAP_REG is not supported

     * vtd_define_long(s, DMAR_FEUADDR_REG, 0, 0xffffffffUL, 0);

     */

    vtd_define_long(s, DMAR_FEUADDR_REG, 0, 0, 0);

    /* Treated as RO for implementations that PLMR and PHMR fields reported

     * as Clear in the CAP_REG.

     * vtd_define_long(s, DMAR_PMEN_REG, 0, 0x80000000UL, 0);

     */

    vtd_define_long(s, DMAR_PMEN_REG, 0, 0, 0);

    vtd_define_quad(s, DMAR_IQH_REG, 0, 0, 0);

    vtd_define_quad(s, DMAR_IQT_REG, 0, 0x7fff0ULL, 0);

    vtd_define_quad(s, DMAR_IQA_REG, 0, 0xfffffffffffff007ULL, 0);

    vtd_define_long(s, DMAR_ICS_REG, 0, 0, 0x1UL);

    vtd_define_long(s, DMAR_IECTL_REG, 0x80000000UL, 0x80000000UL, 0);

    vtd_define_long(s, DMAR_IEDATA_REG, 0, 0xffffffffUL, 0);

    vtd_define_long(s, DMAR_IEADDR_REG, 0, 0xfffffffcUL, 0);

    /* Treadted as RsvdZ when EIM in ECAP_REG is not supported */

    vtd_define_long(s, DMAR_IEUADDR_REG, 0, 0, 0);

    /* IOTLB registers */

    vtd_define_quad(s, DMAR_IOTLB_REG, 0, 0Xb003ffff00000000ULL, 0);

    vtd_define_quad(s, DMAR_IVA_REG, 0, 0xfffffffffffff07fULL, 0);

    vtd_define_quad_wo(s, DMAR_IVA_REG, 0xfffffffffffff07fULL);

    /* Fault Recording Registers, 128-bit */

    vtd_define_quad(s, DMAR_FRCD_REG_0_0, 0, 0, 0);

    vtd_define_quad(s, DMAR_FRCD_REG_0_2, 0, 0, 0x8000000000000000ULL);

}


static S390PCIBusDevice *s390_pci_find_dev_by_uid(uint16_t uid)

{

    int i;

    S390PCIBusDevice *pbdev;

    S390pciState *s = s390_get_phb();

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

        pbdev = s->pbdev[i];

        if (!pbdev) {

            continue;

        }

        if (pbdev->uid == uid) {

            return pbdev;

        }

    }

    return NULL;

}


static int usb_host_usbfs_type(USBHostDevice *s, USBPacket *p)

{

    static const int usbfs[] = {

        [USB_ENDPOINT_XFER_CONTROL] = USBDEVFS_URB_TYPE_CONTROL,

        [USB_ENDPOINT_XFER_ISOC]    = USBDEVFS_URB_TYPE_ISO,

        [USB_ENDPOINT_XFER_BULK]    = USBDEVFS_URB_TYPE_BULK,

        [USB_ENDPOINT_XFER_INT]     = USBDEVFS_URB_TYPE_INTERRUPT,

    };

    uint8_t type = usb_ep_get_type(&s->dev, p->pid, p->devep);

    assert(type < ARRAY_SIZE(usbfs));

    return usbfs[type];

}


static void scsi_cancel_io(SCSIRequest *req)

{

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

    DPRINTF("Cancel tag=0x%x\n", req->tag);

    if (r->req.aiocb) {

        bdrv_aio_cancel(r->req.aiocb);

        /* This reference was left in by scsi_*_data.  We take ownership of

         * it the moment scsi_req_cancel is called, independent of whether

         * bdrv_aio_cancel completes the request or not.  */

        scsi_req_unref(&r->req);

    }

    r->req.aiocb = NULL;

}


static uint32_t drc_unisolate_logical(sPAPRDRConnector *drc)

{

    /* cannot unisolate a non-existent resource, and, or resources

     * which are in an 'UNUSABLE' allocation state. (PAPR 2.7,

     * 13.5.3.5)

     */

    if (!drc->dev ||

        drc->allocation_state == SPAPR_DR_ALLOCATION_STATE_UNUSABLE) {

        return RTAS_OUT_NO_SUCH_INDICATOR;

    }

    drc->isolation_state = SPAPR_DR_ISOLATION_STATE_UNISOLATED;

    return RTAS_OUT_SUCCESS;

}


void do_blockdev_backup(const char *job_id, const char *device,

                        const char *target, enum MirrorSyncMode sync,

                         bool has_speed, int64_t speed,

                         bool has_on_source_error,

                         BlockdevOnError on_source_error,

                         bool has_on_target_error,

                         BlockdevOnError on_target_error,

                         BlockJobTxn *txn, Error **errp)

{

    BlockBackend *blk;

    BlockDriverState *bs;

    BlockDriverState *target_bs;

    Error *local_err = NULL;

    AioContext *aio_context;

    if (!has_speed) {

        speed = 0;

    }

    if (!has_on_source_error) {

        on_source_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    if (!has_on_target_error) {

        on_target_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    blk = blk_by_name(device);

    if (!blk) {

        error_setg(errp, "Device '%s' not found", device);

        return;

    }

    aio_context = blk_get_aio_context(blk);

    aio_context_acquire(aio_context);

    if (!blk_is_available(blk)) {

        error_setg(errp, "Device '%s' has no medium", device);

        goto out;

    }

    bs = blk_bs(blk);

    target_bs = bdrv_lookup_bs(target, target, errp);

    if (!target_bs) {

        goto out;

    }

    if (bdrv_get_aio_context(target_bs) != aio_context) {

        if (!bdrv_has_blk(target_bs)) {

            /* The target BDS is not attached, we can safely move it to another

             * AioContext. */

            bdrv_set_aio_context(target_bs, aio_context);

        } else {

            error_setg(errp, "Target is attached to a different thread from "

                             "source.");

            goto out;

        }

    }

    backup_start(job_id, bs, target_bs, speed, sync, NULL, on_source_error,

                 on_target_error, block_job_cb, bs, txn, &local_err);

    if (local_err != NULL) {

        error_propagate(errp, local_err);

    }

out:

    aio_context_release(aio_context);

}