static int hdcd_integrate(HDCDContext *ctx, hdcd_state_t *state, int *flag, const int32_t *samples, int count, int stride)

{

    uint32_t bits = 0;

    int result = FFMIN(state->readahead, count);

    int i;

    *flag = 0;

    for (i = result - 1; i >= 0; i--) {

        bits |= (*samples & 1) << i; /* might be better as a conditional? */

        samples += stride;

    }

    state->window = (state->window << result) | bits;

    state->readahead -= result;

    if (state->readahead > 0)

        return result;

    bits = (state->window ^ state->window >> 5 ^ state->window >> 23);

    if (state->arg) {

        if ((bits & 0x0fa00500) == 0x0fa00500) {

            /* A: 8-bit code */

            if ((bits & 0xc8) == 0) {

                /*                   [..pt gggg]

                 * 0x0fa005[..] -> 0b[00.. 0...], gain part doubled */

                state->control = (bits & 255) + (bits & 7);

                *flag = 1;

                state->code_counterA++;

            } else {

                /* one of bits 3, 6, or 7 was not 0 */

                state->code_counterA_almost++;

                av_log(ctx->fctx, AV_LOG_VERBOSE,

                    "hdcd error: Control A almost: 0x%02x near %d\n", bits & 0xff, ctx->sample_count);

            }

        } else if ((bits & 0xa0060000) == 0xa0060000) {

            /* B: 8-bit code, 8-bit XOR check */

            if (((bits ^ (~bits >> 8 & 255)) & 0xffff00ff) == 0xa0060000) {

                /*          check:   [..pt gggg ~(..pt gggg)]

                 * 0xa006[....] -> 0b[.... ....   .... .... ] */

                state->control = bits >> 8 & 255;

                *flag = 1;

                state->code_counterB++;

            } else {

                /* XOR check failed */

                state->code_counterB_checkfails++;

                av_log(ctx->fctx, AV_LOG_VERBOSE,

                       "hdcd error: Control B check failed: 0x%04x (0x%02x vs 0x%02x) near %d\n", bits & 0xffff, (bits & 0xff00) >> 8, ~bits & 0xff, ctx->sample_count);

            }

        } else {

            /* told to look for a code, but didn't match one */

            state->code_counterC_unmatched++;

            av_log(ctx->fctx, AV_LOG_VERBOSE,

                   "hdcd error: Unmatched code: 0x%08x near %d\n", bits, ctx->sample_count);

        }

        if (*flag) hdcd_update_info(state);

        state->arg = 0;

    }

    if (bits == 0x7e0fa005 || bits == 0x7e0fa006) {

        state->readahead = (bits & 3) * 8;

        state->arg = 1;

        state->code_counterC++;

    } else {

        if (bits)

            state->readahead = readaheadtab[bits & 0xff];

        else

            state->readahead = 31; /* ffwd over digisilence */

    }

    return result;

}


static void gen_mtspr(DisasContext *ctx)

{

    void (*write_cb)(DisasContext *ctx, int sprn, int gprn);

    uint32_t sprn = SPR(ctx->opcode);

#if defined(CONFIG_USER_ONLY)

    write_cb = ctx->spr_cb[sprn].uea_write;

#else

    if (ctx->pr) {

        write_cb = ctx->spr_cb[sprn].uea_write;

    } else if (ctx->hv) {

        write_cb = ctx->spr_cb[sprn].hea_write;

    } else {

        write_cb = ctx->spr_cb[sprn].oea_write;

    }

#endif

    if (likely(write_cb != NULL)) {

        if (likely(write_cb != SPR_NOACCESS)) {

            (*write_cb)(ctx, sprn, rS(ctx->opcode));

        } else {

            /* Privilege exception */

            fprintf(stderr, "Trying to write privileged spr %d (0x%03x) at "

                    TARGET_FMT_lx "\n", sprn, sprn, ctx->nip - 4);

            if (qemu_log_separate()) {

                qemu_log("Trying to write privileged spr %d (0x%03x) at "

                         TARGET_FMT_lx "\n", sprn, sprn, ctx->nip - 4);

            }

            gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

        }

    } else {

        /* Not defined */

        if (qemu_log_separate()) {

            qemu_log("Trying to write invalid spr %d (0x%03x) at "

                     TARGET_FMT_lx "\n", sprn, sprn, ctx->nip - 4);

        }

        fprintf(stderr, "Trying to write invalid spr %d (0x%03x) at "

                TARGET_FMT_lx "\n", sprn, sprn, ctx->nip - 4);

        gen_inval_exception(ctx, POWERPC_EXCP_INVAL_SPR);

    }

}


static void usage(const char *cmd)

{

    printf(

"Usage: %s [-m <method> -p <path>] [<options>]\n"

"QEMU Guest Agent %s\n"

"\n"

"  -m, --method      transport method: one of unix-listen, virtio-serial, or\n"

"                    isa-serial (virtio-serial is the default)\n"

"  -p, --path        device/socket path (the default for virtio-serial is:\n"

"                    %s)\n"

"  -l, --logfile     set logfile path, logs to stderr by default\n"

"  -f, --pidfile     specify pidfile (default is %s)\n"

"  -v, --verbose     log extra debugging information\n"

"  -V, --version     print version information and exit\n"

"  -d, --daemonize   become a daemon\n"

#ifdef _WIN32

"  -s, --service     service commands: install, uninstall\n"

#endif

"  -b, --blacklist   comma-separated list of RPCs to disable (no spaces, \"?\"\n"

"                    to list available RPCs)\n"

"  -h, --help        display this help and exit\n"

"\n"

"Report bugs to <mdroth@linux.vnet.ibm.com>\n"

    , cmd, QGA_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT);

}


static void await_reference_mb_row(const H264Context *const h, H264Picture *ref,

                                   int mb_y)

{

    int ref_field         = ref->reference - 1;

    int ref_field_picture = ref->field_picture;

    int ref_height        = 16 * h->mb_height >> ref_field_picture;

    if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_FRAME))

        return;

    /* FIXME: It can be safe to access mb stuff

     * even if pixels aren't deblocked yet. */

    ff_thread_await_progress(&ref->tf,

                             FFMIN(16 * mb_y >> ref_field_picture,

                                   ref_height - 1),

                             ref_field_picture && ref_field);

}


static int gxf_packet(AVFormatContext *s, AVPacket *pkt) {

    ByteIOContext *pb = s->pb;

    pkt_type_t pkt_type;

    int pkt_len;

    while (!url_feof(pb)) {

        int track_type, track_id, ret;

        int field_nr;

        if (!parse_packet_header(pb, &pkt_type, &pkt_len)) {

            if (!url_feof(pb))

                av_log(s, AV_LOG_ERROR, "GXF: sync lost\n");

            return -1;

        }

        if (pkt_type == PKT_FLT) {

            gxf_read_index(s, pkt_len);

            continue;

        }

        if (pkt_type != PKT_MEDIA) {

            url_fskip(pb, pkt_len);

            continue;

        }

        if (pkt_len < 16) {

            av_log(s, AV_LOG_ERROR, "GXF: invalid media packet length\n");

            continue;

        }

        pkt_len -= 16;

        track_type = get_byte(pb);

        track_id = get_byte(pb);

        field_nr = get_be32(pb);

        get_be32(pb); // field information

        get_be32(pb); // "timeline" field number

        get_byte(pb); // flags

        get_byte(pb); // reserved

        // NOTE: there is also data length information in the

        // field information, it might be better to take this into account

        // as well.

        ret = av_get_packet(pb, pkt, pkt_len);

        pkt->stream_index = get_sindex(s, track_id, track_type);

        pkt->dts = field_nr;

        return ret;

    }

    return AVERROR(EIO);

}


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

{

    DriveInfo *dinfo = NULL;

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

    dinfo = add_init_drive(opts);

    if (!dinfo) {

        goto err;

    }

    if (dinfo->devaddr) {

        monitor_printf(mon, "Parameter addr not supported\n");

        goto err;

    }

    switch (dinfo->type) {

    case IF_NONE:

        monitor_printf(mon, "OK\n");

        break;

    default:

        if (pci_drive_hot_add(mon, qdict, dinfo)) {

            goto err;

        }

    }

    return;

err:

    if (dinfo) {

        blk_unref(blk_by_legacy_dinfo(dinfo));

    }

}


char *ff_AMediaCodecList_getCodecNameByType(const char *mime, int width, int height, void *log_ctx)

{

    int ret;

    char *name = NULL;

    char *supported_type = NULL;

    int attached = 0;

    JNIEnv *env = NULL;

    struct JNIAMediaCodecListFields jfields = { 0 };

    jobject format = NULL;

    jobject codec = NULL;

    jstring tmp = NULL;

    jobject info = NULL;

    jobject type = NULL;

    jobjectArray types = NULL;

    JNI_ATTACH_ENV_OR_RETURN(env, &attached, log_ctx, NULL);

    if ((ret = ff_jni_init_jfields(env, &jfields, jni_amediacodeclist_mapping, 0, log_ctx)) < 0) {

        goto done;

    }

    if (jfields.init_id && jfields.find_decoder_for_format_id) {

        tmp = ff_jni_utf_chars_to_jstring(env, mime, log_ctx);

        if (!tmp) {

            goto done;

        }

        format = (*env)->CallStaticObjectMethod(env, jfields.mediaformat_class, jfields.create_video_format_id, tmp, width, height);

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

            goto done;

        }

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

        tmp = NULL;

        codec = (*env)->NewObject(env, jfields.mediacodec_list_class, jfields.init_id, 0);

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

            goto done;

        }

        tmp = (*env)->CallObjectMethod(env, codec, jfields.find_decoder_for_format_id, format);

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

            goto done;

        }

        if (!tmp) {

            av_log(NULL, AV_LOG_ERROR, "Could not find decoder in media codec list "

                                       "for format { mime=%s width=%d height=%d }\n", mime, width, height);

            goto done;

        }

        name = ff_jni_jstring_to_utf_chars(env, tmp, log_ctx);

        if (!name) {

            goto done;

        }

    } else {

        int i;

        int codec_count;

        codec_count = (*env)->CallStaticIntMethod(env, jfields.mediacodec_list_class, jfields.get_codec_count_id);

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

            goto done;

        }

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

            int j;

            int type_count;

            int is_encoder;

            info = (*env)->CallStaticObjectMethod(env, jfields.mediacodec_list_class, jfields.get_codec_info_at_id, i);

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

                goto done;

            }

            types = (*env)->CallObjectMethod(env, info, jfields.get_supported_types_id);

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

                goto done;

            }

            is_encoder = (*env)->CallBooleanMethod(env, info, jfields.is_encoder_id);

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

                goto done;

            }

            if (is_encoder) {

                continue;

            }

            type_count = (*env)->GetArrayLength(env, types);

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

                type = (*env)->GetObjectArrayElement(env, types, j);

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

                    goto done;

                }

                supported_type = ff_jni_jstring_to_utf_chars(env, type, log_ctx);

                if (!supported_type) {

                    goto done;

                }

                if (!av_strcasecmp(supported_type, mime)) {

                    jobject codec_name;

                    codec_name = (*env)->CallObjectMethod(env, info, jfields.get_name_id);

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

                        goto done;

                    }

                    name = ff_jni_jstring_to_utf_chars(env, codec_name, log_ctx);

                    if (!name) {

                        goto done;

                    }

                    if (strstr(name, "OMX.google")) {

                        av_freep(&name);

                        continue;

                    }

                }

                av_freep(&supported_type);

            }

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

            info = NULL;

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

            types = NULL;

            if (name)

                break;

        }

    }

done:

    if (format) {

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

    }

    if (codec) {

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

    }

    if (tmp) {

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

    }

    if (info) {

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

    }

    if (type) {

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

    }

    if (types) {

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

    }

    av_freep(&supported_type);

    ff_jni_reset_jfields(env, &jfields, jni_amediacodeclist_mapping, 0, log_ctx);

    JNI_DETACH_ENV(attached, log_ctx);

    return name;

}


static void cchip_write(void *opaque, target_phys_addr_t addr,

                        uint64_t v32, unsigned size)

{

    TyphoonState *s = opaque;

    uint64_t val, oldval, newval;

    if (addr & 4) {

        val = v32 << 32 | s->latch_tmp;

        addr ^= 4;

    } else {

        s->latch_tmp = v32;

        return;

    }

    switch (addr) {

    case 0x0000:

        /* CSC: Cchip System Configuration Register.  */

        /* All sorts of data here; nothing relevant RW.  */

        break;

    case 0x0040:

        /* MTR: Memory Timing Register.  */

        /* All sorts of stuff related to real DRAM.  */

        break;

    case 0x0080:

        /* MISC: Miscellaneous Register.  */

        newval = oldval = s->cchip.misc;

        newval &= ~(val & 0x10000ff0);     /* W1C fields */

        if (val & 0x100000) {

            newval &= ~0xff0000ull;        /* ACL clears ABT and ABW */

        } else {

            newval |= val & 0x00f00000;    /* ABT field is W1S */

            if ((newval & 0xf0000) == 0) {

                newval |= val & 0xf0000;   /* ABW field is W1S iff zero */

            }

        }

        newval |= (val & 0xf000) >> 4;     /* IPREQ field sets IPINTR.  */

        newval &= ~0xf0000000000ull;       /* WO and RW fields */

        newval |= val & 0xf0000000000ull;

        s->cchip.misc = newval;

        /* Pass on changes to IPI and ITI state.  */

        if ((newval ^ oldval) & 0xff0) {

            int i;

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

                CPUAlphaState *env = s->cchip.cpu[i];

                if (env) {

                    /* IPI can be either cleared or set by the write.  */

                    if (newval & (1 << (i + 8))) {

                        cpu_interrupt(env, CPU_INTERRUPT_SMP);

                    } else {

                        cpu_reset_interrupt(env, CPU_INTERRUPT_SMP);

                    }

                    /* ITI can only be cleared by the write.  */

                    if ((newval & (1 << (i + 4))) == 0) {

                        cpu_reset_interrupt(env, CPU_INTERRUPT_TIMER);

                    }

                }

            }

        }

        break;

    case 0x00c0:

        /* MPD: Memory Presence Detect Register.  */

        break;

    case 0x0100: /* AAR0 */

    case 0x0140: /* AAR1 */

    case 0x0180: /* AAR2 */

    case 0x01c0: /* AAR3 */

        /* AAR: Array Address Register.  */

        /* All sorts of information about DRAM.  */

        break;

    case 0x0200: /* DIM0 */

        /* DIM: Device Interrupt Mask Register, CPU0.  */

        s->cchip.dim[0] = val;

        cpu_irq_change(s->cchip.cpu[0], val & s->cchip.drir);

        break;

    case 0x0240: /* DIM1 */

        /* DIM: Device Interrupt Mask Register, CPU1.  */

        s->cchip.dim[0] = val;

        cpu_irq_change(s->cchip.cpu[1], val & s->cchip.drir);

        break;

    case 0x0280: /* DIR0 (RO) */

    case 0x02c0: /* DIR1 (RO) */

    case 0x0300: /* DRIR (RO) */

        break;

    case 0x0340:

        /* PRBEN: Probe Enable Register.  */

        break;

    case 0x0380: /* IIC0 */

        s->cchip.iic[0] = val & 0xffffff;

        break;

    case 0x03c0: /* IIC1 */

        s->cchip.iic[1] = val & 0xffffff;

        break;

    case 0x0400: /* MPR0 */

    case 0x0440: /* MPR1 */

    case 0x0480: /* MPR2 */

    case 0x04c0: /* MPR3 */

        /* MPR: Memory Programming Register.  */

        break;

    case 0x0580:

        /* TTR: TIGbus Timing Register.  */

        /* All sorts of stuff related to interrupt delivery timings.  */

        break;

    case 0x05c0:

        /* TDR: TIGbug Device Timing Register.  */

        break;

    case 0x0600:

        /* DIM2: Device Interrupt Mask Register, CPU2.  */

        s->cchip.dim[2] = val;

        cpu_irq_change(s->cchip.cpu[2], val & s->cchip.drir);

        break;

    case 0x0640:

        /* DIM3: Device Interrupt Mask Register, CPU3.  */

        s->cchip.dim[3] = val;

        cpu_irq_change(s->cchip.cpu[3], val & s->cchip.drir);

        break;

    case 0x0680: /* DIR2 (RO) */

    case 0x06c0: /* DIR3 (RO) */

        break;

    case 0x0700: /* IIC2 */

        s->cchip.iic[2] = val & 0xffffff;

        break;

    case 0x0740: /* IIC3 */

        s->cchip.iic[3] = val & 0xffffff;

        break;

    case 0x0780:

        /* PWR: Power Management Control.   */

        break;

    case 0x0c00: /* CMONCTLA */

    case 0x0c40: /* CMONCTLB */

    case 0x0c80: /* CMONCNT01 */

    case 0x0cc0: /* CMONCNT23 */

        break;

    default:

        cpu_unassigned_access(cpu_single_env, addr, 1, 0, 0, size);

        return;

    }

}


static void *atomic_mmu_lookup(CPUArchState *env, target_ulong addr,

                               TCGMemOpIdx oi, uintptr_t retaddr)

{

    size_t mmu_idx = get_mmuidx(oi);

    size_t index = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1);

    CPUTLBEntry *tlbe = &env->tlb_table[mmu_idx][index];

    target_ulong tlb_addr = tlbe->addr_write;

    TCGMemOp mop = get_memop(oi);

    int a_bits = get_alignment_bits(mop);

    int s_bits = mop & MO_SIZE;

    /* Adjust the given return address.  */

    retaddr -= GETPC_ADJ;

    /* Enforce guest required alignment.  */

    if (unlikely(a_bits > 0 && (addr & ((1 << a_bits) - 1)))) {

        /* ??? Maybe indicate atomic op to cpu_unaligned_access */

        cpu_unaligned_access(ENV_GET_CPU(env), addr, MMU_DATA_STORE,

                             mmu_idx, retaddr);

    }

    /* Enforce qemu required alignment.  */

    if (unlikely(addr & ((1 << s_bits) - 1))) {

        /* We get here if guest alignment was not requested,

           or was not enforced by cpu_unaligned_access above.

           We might widen the access and emulate, but for now

           mark an exception and exit the cpu loop.  */

        goto stop_the_world;

    }

    /* Check TLB entry and enforce page permissions.  */

    if ((addr & TARGET_PAGE_MASK)

        != (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK))) {

        if (!VICTIM_TLB_HIT(addr_write, addr)) {

            tlb_fill(ENV_GET_CPU(env), addr, MMU_DATA_STORE, mmu_idx, retaddr);

        }

        tlb_addr = tlbe->addr_write;

    }

    /* Check notdirty */

    if (unlikely(tlb_addr & TLB_NOTDIRTY)) {

        tlb_set_dirty(ENV_GET_CPU(env), addr);

        tlb_addr = tlb_addr & ~TLB_NOTDIRTY;

    }

    /* Notice an IO access  */

    if (unlikely(tlb_addr & ~TARGET_PAGE_MASK)) {

        /* There's really nothing that can be done to

           support this apart from stop-the-world.  */

        goto stop_the_world;

    }

    /* Let the guest notice RMW on a write-only page.  */

    if (unlikely(tlbe->addr_read != tlb_addr)) {

        tlb_fill(ENV_GET_CPU(env), addr, MMU_DATA_LOAD, mmu_idx, retaddr);

        /* Since we don't support reads and writes to different addresses,

           and we do have the proper page loaded for write, this shouldn't

           ever return.  But just in case, handle via stop-the-world.  */

        goto stop_the_world;

    }

    return (void *)((uintptr_t)addr + tlbe->addend);

 stop_the_world:

    cpu_loop_exit_atomic(ENV_GET_CPU(env), retaddr);

}


BlockAIOCB *dma_bdrv_read(BlockDriverState *bs,

                          QEMUSGList *sg, uint64_t sector,

                          void (*cb)(void *opaque, int ret), void *opaque)

{

    return dma_bdrv_io(bs, sg, sector, bdrv_aio_readv, cb, opaque,

                       DMA_DIRECTION_FROM_DEVICE);

}


TCGv_i32 tcg_global_reg_new_i32(int reg, const char *name)

{

    int idx;

    idx = tcg_global_reg_new_internal(TCG_TYPE_I32, reg, name);

    return MAKE_TCGV_I32(idx);

}


static void check_pred8x8l(H264PredContext *h, uint8_t *buf0, uint8_t *buf1,

                           int codec, int chroma_format, int bit_depth)

{

    if (chroma_format == 1 && codec_ids[codec] == AV_CODEC_ID_H264) {

        int pred_mode;

        for (pred_mode = 0; pred_mode < 12; pred_mode++) {

            if (check_pred_func(h->pred8x8l[pred_mode], "8x8l", pred4x4_modes[codec][pred_mode])) {

                int neighbors;

                for (neighbors = 0; neighbors <= 0xc000; neighbors += 0x4000) {

                    int has_topleft  = neighbors & 0x8000;

                    int has_topright = neighbors & 0x4000;

                    if ((pred_mode == DIAG_DOWN_RIGHT_PRED || pred_mode == VERT_RIGHT_PRED) && !has_topleft)

                        continue; /* Those aren't allowed according to the spec */

                    randomize_buffers();

                    call_ref(src0, has_topleft, has_topright, (ptrdiff_t)24*SIZEOF_PIXEL);

                    call_new(src1, has_topleft, has_topright, (ptrdiff_t)24*SIZEOF_PIXEL);

                    if (memcmp(buf0, buf1, BUF_SIZE))

                        fail();

                    bench_new(src1, has_topleft, has_topright, (ptrdiff_t)24*SIZEOF_PIXEL);

                }

            }

        }

    }

}


opts_next_list(Visitor *v, GenericList **list, Error **errp)

{

    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);

    GenericList **link;

    if (ov->repeated_opts_first) {

        ov->repeated_opts_first = false;

        link = list;

    } else {

        const QemuOpt *opt;

        opt = g_queue_pop_head(ov->repeated_opts);

        if (g_queue_is_empty(ov->repeated_opts)) {

            g_hash_table_remove(ov->unprocessed_opts, opt->name);

            return NULL;

        }

        link = &(*list)->next;

    }

    *link = g_malloc0(sizeof **link);

    return *link;

}


static inline int gen_neon_add(int size, TCGv t0, TCGv t1)

{

    switch (size) {

    case 0: gen_helper_neon_add_u8(t0, t0, t1); break;

    case 1: gen_helper_neon_add_u16(t0, t0, t1); break;

    case 2: tcg_gen_add_i32(t0, t0, t1); break;

    default: return 1;

    }

    return 0;

}


static void bt_l2cap_sdp_sdu_in(void *opaque, const uint8_t *data, int len)

{

    struct bt_l2cap_sdp_state_s *sdp = opaque;

    enum bt_sdp_cmd pdu_id;

    uint8_t rsp[MAX_PDU_OUT_SIZE - PDU_HEADER_SIZE], *sdu_out;

    int transaction_id, plen;

    int err = 0;

    int rsp_len = 0;

    if (len < 5) {

        fprintf(stderr, "%s: short SDP PDU (%iB).\n", __func__, len);

        return;

    }

    pdu_id = *data ++;

    transaction_id = (data[0] << 8) | data[1];

    plen = (data[2] << 8) | data[3];

    data += 4;

    len -= 5;

    if (len != plen) {

        fprintf(stderr, "%s: wrong SDP PDU length (%iB != %iB).\n",

                        __func__, plen, len);

        err = SDP_INVALID_PDU_SIZE;

        goto respond;

    }

    switch (pdu_id) {

    case SDP_SVC_SEARCH_REQ:

        rsp_len = sdp_svc_search(sdp, rsp, data, len);

        pdu_id = SDP_SVC_SEARCH_RSP;

        break;

    case SDP_SVC_ATTR_REQ:

        rsp_len = sdp_attr_get(sdp, rsp, data, len);

        pdu_id = SDP_SVC_ATTR_RSP;

        break;

    case SDP_SVC_SEARCH_ATTR_REQ:

        rsp_len = sdp_svc_search_attr_get(sdp, rsp, data, len);

        pdu_id = SDP_SVC_SEARCH_ATTR_RSP;

        break;

    case SDP_ERROR_RSP:

    case SDP_SVC_ATTR_RSP:

    case SDP_SVC_SEARCH_RSP:

    case SDP_SVC_SEARCH_ATTR_RSP:

    default:

        fprintf(stderr, "%s: unexpected SDP PDU ID %02x.\n",

                        __func__, pdu_id);

        err = SDP_INVALID_SYNTAX;

        break;

    }

    if (rsp_len < 0) {

        err = -rsp_len;

        rsp_len = 0;

    }

respond:

    if (err) {

        pdu_id = SDP_ERROR_RSP;

        rsp[rsp_len ++] = err >> 8;

        rsp[rsp_len ++] = err & 0xff;

    }

    sdu_out = sdp->channel->sdu_out(sdp->channel, rsp_len + PDU_HEADER_SIZE);

    sdu_out[0] = pdu_id;

    sdu_out[1] = transaction_id >> 8;

    sdu_out[2] = transaction_id & 0xff;

    sdu_out[3] = rsp_len >> 8;

    sdu_out[4] = rsp_len & 0xff;

    memcpy(sdu_out + PDU_HEADER_SIZE, rsp, rsp_len);

    sdp->channel->sdu_submit(sdp->channel);

}


static inline void memcpy_tofs(void * to, const void * from, unsigned long n)

{

	memcpy(to, from, n);

}


static IOMMUTLBEntry s390_translate_iommu(MemoryRegion *iommu, hwaddr addr,

                                          bool is_write)

{

    uint64_t pte;

    uint32_t flags;

    S390PCIBusDevice *pbdev = container_of(iommu, S390PCIBusDevice, mr);

    S390pciState *s;

    IOMMUTLBEntry ret = {

        .target_as = &address_space_memory,

        .iova = 0,

        .translated_addr = 0,

        .addr_mask = ~(hwaddr)0,

        .perm = IOMMU_NONE,

    };

    if (!pbdev->configured || !pbdev->pdev) {

        return ret;

    }

    DPRINTF("iommu trans addr 0x%" PRIx64 "\n", addr);

    s = S390_PCI_HOST_BRIDGE(pci_device_root_bus(pbdev->pdev)->qbus.parent);

    /* s390 does not have an APIC mapped to main storage so we use

     * a separate AddressSpace only for msix notifications

     */

    if (addr == ZPCI_MSI_ADDR) {

        ret.target_as = &s->msix_notify_as;

        ret.iova = addr;

        ret.translated_addr = addr;

        ret.addr_mask = 0xfff;

        ret.perm = IOMMU_RW;

        return ret;

    }

    if (!pbdev->g_iota) {

        pbdev->error_state = true;

        pbdev->lgstg_blocked = true;

        s390_pci_generate_error_event(ERR_EVENT_INVALAS, pbdev->fh, pbdev->fid,

                                      addr, 0);

        return ret;

    }

    if (addr < pbdev->pba || addr > pbdev->pal) {

        pbdev->error_state = true;

        pbdev->lgstg_blocked = true;

        s390_pci_generate_error_event(ERR_EVENT_OORANGE, pbdev->fh, pbdev->fid,

                                      addr, 0);

        return ret;

    }

    pte = s390_guest_io_table_walk(s390_pci_get_table_origin(pbdev->g_iota),

                                   addr);

    if (!pte) {

        pbdev->error_state = true;

        pbdev->lgstg_blocked = true;

        s390_pci_generate_error_event(ERR_EVENT_SERR, pbdev->fh, pbdev->fid,

                                      addr, ERR_EVENT_Q_BIT);

        return ret;

    }

    flags = pte & ZPCI_PTE_FLAG_MASK;

    ret.iova = addr;

    ret.translated_addr = pte & ZPCI_PTE_ADDR_MASK;

    ret.addr_mask = 0xfff;

    if (flags & ZPCI_PTE_INVALID) {

        ret.perm = IOMMU_NONE;

    } else {

        ret.perm = IOMMU_RW;

    }

    return ret;

}


static GenericList *qmp_output_next_list(Visitor *v, GenericList **listp,

                                         size_t size)

{

    GenericList *list = *listp;

    QmpOutputVisitor *qov = to_qov(v);

    QStackEntry *e = QTAILQ_FIRST(&qov->stack);

    assert(e);

    if (e->is_list_head) {

        e->is_list_head = false;

        return list;

    }

    return list ? list->next : NULL;

}


static CharDriverState *qemu_chr_open_win_path(const char *filename,

                                               Error **errp)

{

    CharDriverState *chr;

    WinCharState *s;

    chr = qemu_chr_alloc();

    s = g_new0(WinCharState, 1);

    chr->opaque = s;

    chr->chr_write = win_chr_write;

    chr->chr_close = win_chr_close;

    if (win_chr_init(chr, filename, errp) < 0) {

        g_free(s);

        g_free(chr);

        return NULL;

    }

    return chr;

}


void smbios_add_field(int type, int offset, const void *data, size_t len)

{

    struct smbios_field *field;

    smbios_check_collision(type, SMBIOS_FIELD_ENTRY);

    if (!smbios_entries) {

        smbios_entries_len = sizeof(uint16_t);

        smbios_entries = g_malloc0(smbios_entries_len);

    }

    smbios_entries = g_realloc(smbios_entries, smbios_entries_len +

                                                  sizeof(*field) + len);

    field = (struct smbios_field *)(smbios_entries + smbios_entries_len);

    field->header.type = SMBIOS_FIELD_ENTRY;

    field->header.length = cpu_to_le16(sizeof(*field) + len);

    field->type = type;

    field->offset = cpu_to_le16(offset);

    memcpy(field->data, data, len);

    smbios_entries_len += sizeof(*field) + len;

    (*(uint16_t *)smbios_entries) =

            cpu_to_le16(le16_to_cpu(*(uint16_t *)smbios_entries) + 1);

}


Visitor *qmp_output_visitor_new(QObject **result)

{

    QmpOutputVisitor *v;

    v = g_malloc0(sizeof(*v));

    v->visitor.type = VISITOR_OUTPUT;

    v->visitor.start_struct = qmp_output_start_struct;

    v->visitor.end_struct = qmp_output_end_struct;

    v->visitor.start_list = qmp_output_start_list;

    v->visitor.next_list = qmp_output_next_list;

    v->visitor.end_list = qmp_output_end_list;

    v->visitor.type_int64 = qmp_output_type_int64;

    v->visitor.type_uint64 = qmp_output_type_uint64;

    v->visitor.type_bool = qmp_output_type_bool;

    v->visitor.type_str = qmp_output_type_str;

    v->visitor.type_number = qmp_output_type_number;

    v->visitor.type_any = qmp_output_type_any;

    v->visitor.type_null = qmp_output_type_null;

    v->visitor.complete = qmp_output_complete;

    v->visitor.free = qmp_output_free;

    *result = NULL;

    v->result = result;

    return &v->visitor;

}


static int ast2500_rambits(AspeedSDMCState *s)

{

    switch (s->ram_size >> 20) {

    case 128:

        return ASPEED_SDMC_AST2500_128MB;

    case 256:

        return ASPEED_SDMC_AST2500_256MB;

    case 512:

        return ASPEED_SDMC_AST2500_512MB;

    case 1024:

        return ASPEED_SDMC_AST2500_1024MB;

    default:

        break;

    }

    /* use a common default */

    error_report("warning: Invalid RAM size 0x%" PRIx64

                 ". Using default 512M", s->ram_size);

    s->ram_size = 512 << 20;

    return ASPEED_SDMC_AST2500_512MB;

}


void helper_lswx(CPUPPCState *env, target_ulong addr, uint32_t reg,

                 uint32_t ra, uint32_t rb)

{

    if (likely(xer_bc != 0)) {

        int num_used_regs = (xer_bc + 3) / 4;

        if (unlikely((ra != 0 && reg < ra && (reg + num_used_regs) > ra) ||

                     (reg < rb && (reg + num_used_regs) > rb))) {

            helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,

                                       POWERPC_EXCP_INVAL |

                                       POWERPC_EXCP_INVAL_LSWX);

        } else {

            helper_lsw(env, addr, xer_bc, reg);

        }

    }

}


static void ioreq_release(struct ioreq *ioreq)

{

    struct XenBlkDev *blkdev = ioreq->blkdev;

    LIST_REMOVE(ioreq, list);

    memset(ioreq, 0, sizeof(*ioreq));

    ioreq->blkdev = blkdev;

    LIST_INSERT_HEAD(&blkdev->freelist, ioreq, list);

    blkdev->requests_finished--;

}


static void static_write(void *opaque, hwaddr offset, uint64_t value,

                         unsigned size)

{

#ifdef SPY

    printf("%s: value %08lx written at " PA_FMT "\n",

                    __FUNCTION__, value, offset);

#endif

}


static inline void set_fsr(CPUSPARCState *env)

{

    int rnd_mode;

    switch (env->fsr & FSR_RD_MASK) {

    case FSR_RD_NEAREST:

        rnd_mode = float_round_nearest_even;

        break;

    default:

    case FSR_RD_ZERO:

        rnd_mode = float_round_to_zero;

        break;

    case FSR_RD_POS:

        rnd_mode = float_round_up;

        break;

    case FSR_RD_NEG:

        rnd_mode = float_round_down;

        break;

    }

    set_float_rounding_mode(rnd_mode, &env->fp_status);

}


static void *kvm_cpu_thread_fn(void *arg)

{

    CPUState *env = arg;

    int r;

    qemu_mutex_lock(&qemu_global_mutex);

    qemu_thread_self(env->thread);

    r = kvm_init_vcpu(env);

    if (r < 0) {

        fprintf(stderr, "kvm_init_vcpu failed: %s\n", strerror(-r));

        exit(1);

    }

    qemu_kvm_init_cpu_signals(env);

    /* signal CPU creation */

    env->created = 1;

    qemu_cond_signal(&qemu_cpu_cond);

    /* and wait for machine initialization */

    while (!qemu_system_ready)

        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);

    while (1) {

        if (cpu_can_run(env))

            qemu_cpu_exec(env);

        qemu_kvm_wait_io_event(env);

    }

    return NULL;

}


void HELPER(stfl)(CPUS390XState *env)

{

    uint64_t words[MAX_STFL_WORDS];

    LowCore *lowcore;

    lowcore = cpu_map_lowcore(env);

    do_stfle(env, words);

    lowcore->stfl_fac_list = cpu_to_be32(words[0] >> 32);

    cpu_unmap_lowcore(lowcore);

}


static int nbd_can_accept(void *opaque)

{

    return nb_fds < shared;

}


static void pci_update_mappings(PCIDevice *d)

{

    PCIIORegion *r;

    int i;

    pcibus_t new_addr;

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

        r = &d->io_regions[i];

        /* this region isn't registered */

        if (!r->size)

            continue;

        new_addr = pci_bar_address(d, i, r->type, r->size);

        /* This bar isn't changed */

        if (new_addr == r->addr)

            continue;

        /* now do the real mapping */

        if (r->addr != PCI_BAR_UNMAPPED) {

            trace_pci_update_mappings_del(d, pci_bus_num(d->bus),

                                          PCI_SLOT(d->devfn),

                                          PCI_FUNC(d->devfn),

                                          i, r->addr, r->size);

            memory_region_del_subregion(r->address_space, r->memory);

        }

        r->addr = new_addr;

        if (r->addr != PCI_BAR_UNMAPPED) {

            trace_pci_update_mappings_add(d, pci_bus_num(d->bus),

                                          PCI_SLOT(d->devfn),

                                          PCI_FUNC(d->devfn),

                                          i, r->addr, r->size);

            memory_region_add_subregion_overlap(r->address_space,

                                                r->addr, r->memory, 1);

        }

    }

    pci_update_vga(d);

}


static QObject* bdrv_info_stats_bs(BlockDriverState *bs)

{

    QObject *res;

    QDict *dict;

    res = qobject_from_jsonf("{ 'stats': {"

                             "'rd_bytes': %" PRId64 ","

                             "'wr_bytes': %" PRId64 ","

                             "'rd_operations': %" PRId64 ","

                             "'wr_operations': %" PRId64 ","

                             "'wr_highest_offset': %" PRId64 ","

                             "'flush_operations': %" PRId64

                             "} }",

                             bs->nr_bytes[BDRV_ACCT_READ],

                             bs->nr_bytes[BDRV_ACCT_WRITE],

                             bs->nr_ops[BDRV_ACCT_READ],

                             bs->nr_ops[BDRV_ACCT_WRITE],

                             bs->wr_highest_sector *

                             (uint64_t)BDRV_SECTOR_SIZE,

                             bs->nr_ops[BDRV_ACCT_FLUSH]);

    dict  = qobject_to_qdict(res);

    if (*bs->device_name) {

        qdict_put(dict, "device", qstring_from_str(bs->device_name));

    }

    if (bs->file) {

        QObject *parent = bdrv_info_stats_bs(bs->file);

        qdict_put_obj(dict, "parent", parent);

    }

    return res;

}


static void sun4m_common_init(int ram_size, int boot_device, DisplayState *ds,

                              const char *kernel_filename, const char *kernel_cmdline,

                              const char *initrd_filename, const char *cpu_model,

                              unsigned int machine)

{

    sun4m_hw_init(&hwdefs[machine], ram_size, ds, cpu_model);

    sun4m_load_kernel(hwdefs[machine].vram_size, ram_size, boot_device,

                      kernel_filename, kernel_cmdline, initrd_filename,

                      hwdefs[machine].machine_id);

}


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

{

    PMPContext *pmp = s->priv_data;

    AVIOContext *pb = s->pb;

    int ret = 0;

    int i;

    if (url_feof(pb))

        return AVERROR_EOF;

    if (pmp->cur_stream == 0) {

        int num_packets;

        pmp->audio_packets = avio_r8(pb);

        num_packets = (pmp->num_streams - 1) * pmp->audio_packets + 1;

        avio_skip(pb, 8);

        pmp->current_packet = 0;

        av_fast_malloc(&pmp->packet_sizes,

                       &pmp->packet_sizes_alloc,

                       num_packets * sizeof(*pmp->packet_sizes));

        if (!pmp->packet_sizes_alloc) {

            av_log(s, AV_LOG_ERROR, "Cannot (re)allocate packet buffer\n");

            return AVERROR(ENOMEM);

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

            pmp->packet_sizes[i] = avio_rl32(pb);

    ret = av_get_packet(pb, pkt, pmp->packet_sizes[pmp->current_packet]);

    if (ret >= 0) {

        ret = 0;

        // FIXME: this is a hack that should be removed once

        // compute_pkt_fields() can handle timestamps properly

        if (pmp->cur_stream == 0)

            pkt->dts = s->streams[0]->cur_dts++;

        pkt->stream_index = pmp->cur_stream;

    if (pmp->current_packet % pmp->audio_packets == 0)

        pmp->cur_stream = (pmp->cur_stream + 1) % pmp->num_streams;

    pmp->current_packet++;

    return ret;


void virtio_queue_notify(VirtIODevice *vdev, int n)

{

    if (n < VIRTIO_PCI_QUEUE_MAX) {

        virtio_queue_notify_vq(&vdev->vq[n]);

    }

}


int av_picture_crop(AVPicture *dst, const AVPicture *src,

                    enum PixelFormat pix_fmt, int top_band, int left_band)

{

    int y_shift;

    int x_shift;

    if (pix_fmt < 0 || pix_fmt >= PIX_FMT_NB)

        return -1;

    y_shift = av_pix_fmt_descriptors[pix_fmt].log2_chroma_h;

    x_shift = av_pix_fmt_descriptors[pix_fmt].log2_chroma_w;

    if (is_yuv_planar(&pix_fmt_info[pix_fmt])) {

    dst->data[0] = src->data[0] + (top_band * src->linesize[0]) + left_band;

    dst->data[1] = src->data[1] + ((top_band >> y_shift) * src->linesize[1]) + (left_band >> x_shift);

    dst->data[2] = src->data[2] + ((top_band >> y_shift) * src->linesize[2]) + (left_band >> x_shift);

    } else{

        if(top_band % (1<<y_shift) || left_band % (1<<x_shift))

            return -1;

        if(left_band) //FIXME add support for this too

            return -1;

        dst->data[0] = src->data[0] + (top_band * src->linesize[0]) + left_band;

    }

    dst->linesize[0] = src->linesize[0];

    dst->linesize[1] = src->linesize[1];

    dst->linesize[2] = src->linesize[2];

    return 0;

}


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

                                 ptrdiff_t stride)

{

    avc_luma_hz_qrt_16w_msa(src - 2, stride, dst, stride, 16, 1);

}


static int wv_read_packet(AVFormatContext *s,

                          AVPacket *pkt)

{

    WVContext *wc = s->priv_data;

    int ret, samples;

    if (url_feof(&s->pb))

        return -EIO;

    if(wc->block_parsed){

        if(wv_read_block_header(s, &s->pb) < 0)

            return -1;

    }

    samples = LE_32(wc->extra);

    /* should not happen but who knows */

    if(samples * 2 * wc->chan > AVCODEC_MAX_AUDIO_FRAME_SIZE){

        av_log(s, AV_LOG_ERROR, "Packet size is too big to be handled in lavc!\n");

        return -EIO;

    }

    if(av_new_packet(pkt, wc->blksize + WV_EXTRA_SIZE) < 0)

        return AVERROR_NOMEM;

    memcpy(pkt->data, wc->extra, WV_EXTRA_SIZE);

    ret = get_buffer(&s->pb, pkt->data + WV_EXTRA_SIZE, wc->blksize);

    if(ret != wc->blksize){

        av_free_packet(pkt);

        return AVERROR_IO;

    }

    pkt->stream_index = 0;

    wc->block_parsed = 1;

    pkt->size = ret + WV_EXTRA_SIZE;

    return 0;

}


static void calc_masking(DCAEncContext *c, const int32_t *input)

{

    int i, k, band, ch, ssf;

    int32_t data[512];

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

        for (ssf = 0; ssf < SUBSUBFRAMES; ssf++)

            c->masking_curve_cb[ssf][i] = -2047;

    for (ssf = 0; ssf < SUBSUBFRAMES; ssf++)

        for (ch = 0; ch < c->fullband_channels; ch++) {

            const int chi = c->channel_order_tab[ch];

            for (i = 0, k = 128 + 256 * ssf; k < 512; i++, k++)

                data[i] = c->history[k][ch];

            for (k -= 512; i < 512; i++, k++)

                data[i] = input[k * c->channels + chi];

            adjust_jnd(c->samplerate_index, data, c->masking_curve_cb[ssf]);

        }

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

        int32_t m = 2048;

        for (ssf = 0; ssf < SUBSUBFRAMES; ssf++)

            if (c->masking_curve_cb[ssf][i] < m)

                m = c->masking_curve_cb[ssf][i];

        c->eff_masking_curve_cb[i] = m;

    }

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

        c->band_masking_cb[band] = 2048;

        walk_band_low(c, band, 0, update_band_masking, NULL);

        walk_band_high(c, band, 0, update_band_masking, NULL);

    }

}


static coroutine_fn void nbd_trip(void *opaque)

{

    NBDClient *client = opaque;

    NBDExport *exp = client->exp;

    NBDRequestData *req;

    NBDRequest request = { 0 };    /* GCC thinks it can be used uninitialized */

    int ret;

    int flags;

    int reply_data_len = 0;

    Error *local_err = NULL;

    char *msg = NULL;

    trace_nbd_trip();

    if (client->closing) {

        nbd_client_put(client);

        return;

    }

    req = nbd_request_get(client);

    ret = nbd_co_receive_request(req, &request, &local_err);

    client->recv_coroutine = NULL;

    nbd_client_receive_next_request(client);

    if (ret == -EIO) {

        goto disconnect;

    }

    if (ret < 0) {

        goto reply;

    }

    if (client->closing) {

        /*

         * The client may be closed when we are blocked in

         * nbd_co_receive_request()

         */

        goto done;

    }

    switch (request.type) {

    case NBD_CMD_READ:

        /* XXX: NBD Protocol only documents use of FUA with WRITE */

        if (request.flags & NBD_CMD_FLAG_FUA) {

            ret = blk_co_flush(exp->blk);

            if (ret < 0) {

                error_setg_errno(&local_err, -ret, "flush failed");

                break;

            }

        }

        ret = blk_pread(exp->blk, request.from + exp->dev_offset,

                        req->data, request.len);

        if (ret < 0) {

            error_setg_errno(&local_err, -ret, "reading from file failed");

            break;

        }

        reply_data_len = request.len;

        break;

    case NBD_CMD_WRITE:

        if (exp->nbdflags & NBD_FLAG_READ_ONLY) {

            error_setg(&local_err, "Export is read-only");

            ret = -EROFS;

            break;

        }

        flags = 0;

        if (request.flags & NBD_CMD_FLAG_FUA) {

            flags |= BDRV_REQ_FUA;

        }

        ret = blk_pwrite(exp->blk, request.from + exp->dev_offset,

                         req->data, request.len, flags);

        if (ret < 0) {

            error_setg_errno(&local_err, -ret, "writing to file failed");

        }

        break;

    case NBD_CMD_WRITE_ZEROES:

        if (exp->nbdflags & NBD_FLAG_READ_ONLY) {

            error_setg(&local_err, "Export is read-only");

            ret = -EROFS;

            break;

        }

        flags = 0;

        if (request.flags & NBD_CMD_FLAG_FUA) {

            flags |= BDRV_REQ_FUA;

        }

        if (!(request.flags & NBD_CMD_FLAG_NO_HOLE)) {

            flags |= BDRV_REQ_MAY_UNMAP;

        }

        ret = blk_pwrite_zeroes(exp->blk, request.from + exp->dev_offset,

                                request.len, flags);

        if (ret < 0) {

            error_setg_errno(&local_err, -ret, "writing to file failed");

        }

        break;

    case NBD_CMD_DISC:

        /* unreachable, thanks to special case in nbd_co_receive_request() */

        abort();

    case NBD_CMD_FLUSH:

        ret = blk_co_flush(exp->blk);

        if (ret < 0) {

            error_setg_errno(&local_err, -ret, "flush failed");

        }

        break;

    case NBD_CMD_TRIM:

        ret = blk_co_pdiscard(exp->blk, request.from + exp->dev_offset,

                              request.len);

        if (ret < 0) {

            error_setg_errno(&local_err, -ret, "discard failed");

        }

        break;

    default:

        error_setg(&local_err, "invalid request type (%" PRIu32 ") received",

                   request.type);

        ret = -EINVAL;

    }

reply:

    if (local_err) {

        /* If we get here, local_err was not a fatal error, and should be sent

         * to the client. */

        assert(ret < 0);

        msg = g_strdup(error_get_pretty(local_err));

        error_report_err(local_err);

        local_err = NULL;

    }

    if (client->structured_reply &&

        (ret < 0 || request.type == NBD_CMD_READ)) {

        if (ret < 0) {

            ret = nbd_co_send_structured_error(req->client, request.handle,

                                               -ret, msg, &local_err);

        } else {

            ret = nbd_co_send_structured_read(req->client, request.handle,

                                              request.from, req->data,

                                              reply_data_len, &local_err);

        }

    } else {

        ret = nbd_co_send_simple_reply(req->client, request.handle,

                                       ret < 0 ? -ret : 0,

                                       req->data, reply_data_len, &local_err);

    }

    g_free(msg);

    if (ret < 0) {

        error_prepend(&local_err, "Failed to send reply: ");

        goto disconnect;

    }

    /* We must disconnect after NBD_CMD_WRITE if we did not

     * read the payload.

     */

    if (!req->complete) {

        error_setg(&local_err, "Request handling failed in intermediate state");

        goto disconnect;

    }

done:

    nbd_request_put(req);

    nbd_client_put(client);

    return;

disconnect:

    if (local_err) {

        error_reportf_err(local_err, "Disconnect client, due to: ");

    }

    nbd_request_put(req);

    client_close(client, true);

    nbd_client_put(client);

}


static void quantize_mantissas_blk_ch(AC3EncodeContext *s, int32_t *fixed_coef,

                                      int8_t exp_shift, uint8_t *exp,

                                      uint8_t *bap, uint16_t *qmant, int n)

{

    int i;

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

        int v;

        int c = fixed_coef[i];

        int e = exp[i] - exp_shift;

        int b = bap[i];

        switch (b) {

        case 0:

            v = 0;

            break;

        case 1:

            v = sym_quant(c, e, 3);

            switch (s->mant1_cnt) {

            case 0:

                s->qmant1_ptr = &qmant[i];

                v = 9 * v;

                s->mant1_cnt = 1;

                break;

            case 1:

                *s->qmant1_ptr += 3 * v;

                s->mant1_cnt = 2;

                v = 128;

                break;

            default:

                *s->qmant1_ptr += v;

                s->mant1_cnt = 0;

                v = 128;

                break;

            }

            break;

        case 2:

            v = sym_quant(c, e, 5);

            switch (s->mant2_cnt) {

            case 0:

                s->qmant2_ptr = &qmant[i];

                v = 25 * v;

                s->mant2_cnt = 1;

                break;

            case 1:

                *s->qmant2_ptr += 5 * v;

                s->mant2_cnt = 2;

                v = 128;

                break;

            default:

                *s->qmant2_ptr += v;

                s->mant2_cnt = 0;

                v = 128;

                break;

            }

            break;

        case 3:

            v = sym_quant(c, e, 7);

            break;

        case 4:

            v = sym_quant(c, e, 11);

            switch (s->mant4_cnt) {

            case 0:

                s->qmant4_ptr = &qmant[i];

                v = 11 * v;

                s->mant4_cnt = 1;

                break;

            default:

                *s->qmant4_ptr += v;

                s->mant4_cnt = 0;

                v = 128;

                break;

            }

            break;

        case 5:

            v = sym_quant(c, e, 15);

            break;

        case 14:

            v = asym_quant(c, e, 14);

            break;

        case 15:

            v = asym_quant(c, e, 16);

            break;

        default:

            v = asym_quant(c, e, b - 1);

            break;

        }

        qmant[i] = v;

    }

}


static inline void tb_alloc_page(TranslationBlock *tb,

                                 unsigned int n, tb_page_addr_t page_addr)

{

    PageDesc *p;

#ifndef CONFIG_USER_ONLY

    bool page_already_protected;

#endif

    assert_memory_lock();

    tb->page_addr[n] = page_addr;

    p = page_find_alloc(page_addr >> TARGET_PAGE_BITS, 1);

    tb->page_next[n] = p->first_tb;

#ifndef CONFIG_USER_ONLY

    page_already_protected = p->first_tb != NULL;

#endif

    p->first_tb = (TranslationBlock *)((uintptr_t)tb | n);

    invalidate_page_bitmap(p);

#if defined(CONFIG_USER_ONLY)

    if (p->flags & PAGE_WRITE) {

        target_ulong addr;

        PageDesc *p2;

        int prot;

        /* force the host page as non writable (writes will have a

           page fault + mprotect overhead) */

        page_addr &= qemu_host_page_mask;

        prot = 0;

        for (addr = page_addr; addr < page_addr + qemu_host_page_size;

            addr += TARGET_PAGE_SIZE) {

            p2 = page_find(addr >> TARGET_PAGE_BITS);

            if (!p2) {

                continue;

            }

            prot |= p2->flags;

            p2->flags &= ~PAGE_WRITE;

          }

        mprotect(g2h(page_addr), qemu_host_page_size,

                 (prot & PAGE_BITS) & ~PAGE_WRITE);

#ifdef DEBUG_TB_INVALIDATE

        printf("protecting code page: 0x" TARGET_FMT_lx "\n",

               page_addr);

#endif

    }

#else

    /* if some code is already present, then the pages are already

       protected. So we handle the case where only the first TB is

       allocated in a physical page */

    if (!page_already_protected) {

        tlb_protect_code(page_addr);

    }

#endif

}


void address_space_destroy(AddressSpace *as)

{

    /* Flush out anything from MemoryListeners listening in on this */

    memory_region_transaction_begin();

    as->root = NULL;

    memory_region_transaction_commit();

    QTAILQ_REMOVE(&address_spaces, as, address_spaces_link);

    address_space_destroy_dispatch(as);

    flatview_destroy(as->current_map);

    g_free(as->current_map);

}


static void test_submit(void)

{

    WorkerTestData data = { .n = 0 };

    thread_pool_submit(pool, worker_cb, &data);

    qemu_aio_wait_all();

    g_assert_cmpint(data.n, ==, 1);

}


static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p,

                                  int *got_frame, uint8_t *data_start,

                                  unsigned int data_size)

{

    WebPContext *s = avctx->priv_data;

    AVPacket pkt;

    int ret;

    if (!s->initialized) {

        ff_vp8_decode_init(avctx);

        s->initialized = 1;

        if (s->has_alpha)

            avctx->pix_fmt = AV_PIX_FMT_YUVA420P;

    }

    s->lossless = 0;

    if (data_size > INT_MAX) {

        av_log(avctx, AV_LOG_ERROR, "unsupported chunk size\n");

        return AVERROR_PATCHWELCOME;

    }

    av_init_packet(&pkt);

    pkt.data = data_start;

    pkt.size = data_size;

    ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt);

    if (s->has_alpha) {

        ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data,

                                     s->alpha_data_size);

    }

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    VFIOCalxedaXgmacDeviceClass *vcxc =

        VFIO_CALXEDA_XGMAC_DEVICE_CLASS(klass);

    vcxc->parent_realize = dc->realize;

    dc->realize = calxeda_xgmac_realize;

    dc->desc = "VFIO Calxeda XGMAC";

    dc->vmsd = &vfio_platform_calxeda_xgmac_vmstate;

}


static void ppcuic_set_irq (void *opaque, int irq_num, int level)

{

    ppcuic_t *uic;

    uint32_t mask, sr;

    uic = opaque;

    mask = 1 << (31-irq_num);

    LOG_UIC("%s: irq %d level %d uicsr %08" PRIx32

                " mask %08" PRIx32 " => %08" PRIx32 " %08" PRIx32 "\n",

                __func__, irq_num, level,

                uic->uicsr, mask, uic->uicsr & mask, level << irq_num);

    if (irq_num < 0 || irq_num > 31)

        return;

    sr = uic->uicsr;

    /* Update status register */

    if (uic->uictr & mask) {

        /* Edge sensitive interrupt */

        if (level == 1)

            uic->uicsr |= mask;

    } else {

        /* Level sensitive interrupt */

        if (level == 1) {

            uic->uicsr |= mask;

            uic->level |= mask;

        } else {

            uic->uicsr &= ~mask;

            uic->level &= ~mask;

        }

    }

    LOG_UIC("%s: irq %d level %d sr %" PRIx32 " => "

                "%08" PRIx32 "\n", __func__, irq_num, level, uic->uicsr, sr);

    if (sr != uic->uicsr)

        ppcuic_trigger_irq(uic);

}


static int avi_sync(AVFormatContext *s, int exit_early)
{
    AVIContext *avi = s->priv_data;
    AVIOContext *pb = s->pb;
    int n;
    unsigned int d[8];
    unsigned int size;
    int64_t i, sync;
start_sync:
    memset(d, -1, sizeof(d));
    for(i=sync=avio_tell(pb); !url_feof(pb); i++) {
        int j;
        for(j=0; j<7; j++)
            d[j]= d[j+1];
        d[7]= avio_r8(pb);
        size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
        n= get_stream_idx(d+2);
//av_log(s, AV_LOG_DEBUG, "%X %X %X %X %X %X %X %X %"PRId64" %d %d\n", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
        if(i + (uint64_t)size > avi->fsize || d[0] > 127)
        //parse ix##
        if(  (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
        //parse JUNK
           ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
           ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
            avio_skip(pb, size);
//av_log(s, AV_LOG_DEBUG, "SKIP\n");
            goto start_sync;
        //parse stray LIST
        if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
            avio_skip(pb, 4);
            goto start_sync;
        n= get_stream_idx(d);
        if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
        //detect ##ix chunk and skip
        if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
            avio_skip(pb, size);
            goto start_sync;
        //parse ##dc/##wb
        if(n < s->nb_streams){
            AVStream *st;
            AVIStream *ast;
            st = s->streams[n];
            ast = st->priv_data;
            if(s->nb_streams>=2){
                AVStream *st1  = s->streams[1];
                AVIStream *ast1= st1->priv_data;
                //workaround for broken small-file-bug402.avi
                if(   d[2] == 'w' && d[3] == 'b'
                   && n==0
                   && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
                   && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
                   && ast->prefix == 'd'*256+'c'
                   && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
                  ){
                    n=1;
                    st = st1;
                    ast = ast1;
                    av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
            if(   (st->discard >= AVDISCARD_DEFAULT && size==0)
               /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
               || st->discard >= AVDISCARD_ALL){
                if (!exit_early) {
                    ast->frame_offset += get_duration(ast, size);
                avio_skip(pb, size);
                goto start_sync;
            if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
                int k = avio_r8(pb);
                int last = (k + avio_r8(pb) - 1) & 0xFF;
                avio_rl16(pb); //flags
                for (; k <= last; k++)
                    ast->pal[k] = 0xFF<<24 | avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
                ast->has_pal= 1;
                goto start_sync;
            } else if(   ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
                         d[2]*256+d[3] == ast->prefix /*||
                         (d[2] == 'd' && d[3] == 'c') ||
                         (d[2] == 'w' && d[3] == 'b')*/) {
                if (exit_early)
                    return 0;
//av_log(s, AV_LOG_DEBUG, "OK\n");
                if(d[2]*256+d[3] == ast->prefix)
                    ast->prefix_count++;
                else{
                    ast->prefix= d[2]*256+d[3];
                    ast->prefix_count= 0;
                avi->stream_index= n;
                ast->packet_size= size + 8;
                ast->remaining= size;
                if(size || !ast->sample_size){
                    uint64_t pos= avio_tell(pb) - 8;
                    if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
                        av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
                return 0;
    if(pb->error)
        return pb->error;
    return AVERROR_EOF;


static void ide_atapi_cmd(IDEState *s)
{
    const uint8_t *packet;
    uint8_t *buf;
    int max_len;
    packet = s->io_buffer;
    buf = s->io_buffer;
#ifdef DEBUG_IDE_ATAPI
    {
        int i;
        printf("ATAPI limit=0x%x packet:", s->lcyl | (s->hcyl << 8));
        for(i = 0; i < ATAPI_PACKET_SIZE; i++) {
            printf(" %02x", packet[i]);
        printf("\n");
#endif
    /* If there's a UNIT_ATTENTION condition pending, only
       REQUEST_SENSE and INQUIRY commands are allowed to complete. */
    if (s->sense_key == SENSE_UNIT_ATTENTION &&
	s->io_buffer[0] != GPCMD_REQUEST_SENSE &&
	s->io_buffer[0] != GPCMD_INQUIRY) {
	ide_atapi_cmd_check_status(s);
	return;
    switch(s->io_buffer[0]) {
    case GPCMD_TEST_UNIT_READY:
        if (bdrv_is_inserted(s->bs) && !s->cdrom_changed) {
            ide_atapi_cmd_ok(s);
        } else {
            s->cdrom_changed = 0;
            ide_atapi_cmd_error(s, SENSE_NOT_READY,
                                ASC_MEDIUM_NOT_PRESENT);
    case GPCMD_MODE_SENSE_6:
    case GPCMD_MODE_SENSE_10:
        {
            int action, code;
            if (packet[0] == GPCMD_MODE_SENSE_10)
            else
                max_len = packet[4];
            action = packet[2] >> 6;
            code = packet[2] & 0x3f;
            switch(action) {
            case 0: /* current values */
                switch(code) {
                case GPMODE_R_W_ERROR_PAGE: /* error recovery */
                    cpu_to_ube16(&buf[0], 16 + 6);
                    buf[2] = 0x70;
                    buf[3] = 0;
                    buf[4] = 0;
                    buf[5] = 0;
                    buf[6] = 0;
                    buf[7] = 0;
                    buf[8] = 0x01;
                    buf[9] = 0x06;
                    buf[10] = 0x00;
                    buf[11] = 0x05;
                    buf[12] = 0x00;
                    buf[13] = 0x00;
                    buf[14] = 0x00;
                    buf[15] = 0x00;
                    ide_atapi_cmd_reply(s, 16, max_len);
                case GPMODE_AUDIO_CTL_PAGE:
                    cpu_to_ube16(&buf[0], 24 + 6);
                    buf[2] = 0x70;
                    buf[3] = 0;
                    buf[4] = 0;
                    buf[5] = 0;
                    buf[6] = 0;
                    buf[7] = 0;
                    /* Fill with CDROM audio volume */
                    buf[17] = 0;
                    buf[19] = 0;
                    buf[21] = 0;
                    buf[23] = 0;
                    ide_atapi_cmd_reply(s, 24, max_len);
                case GPMODE_CAPABILITIES_PAGE:
                    cpu_to_ube16(&buf[0], 28 + 6);
                    buf[2] = 0x70;
                    buf[3] = 0;
                    buf[4] = 0;
                    buf[5] = 0;
                    buf[6] = 0;
                    buf[7] = 0;
                    buf[8] = 0x2a;
                    buf[9] = 0x12;
                    buf[10] = 0x00;
                    buf[11] = 0x00;
                    /* Claim PLAY_AUDIO capability (0x01) since some Linux
                       code checks for this to automount media. */
                    buf[12] = 0x71;
                    buf[13] = 3 << 5;
                    buf[14] = (1 << 0) | (1 << 3) | (1 << 5);
                    if (bdrv_is_locked(s->bs))
                        buf[6] |= 1 << 1;
                    buf[15] = 0x00;
                    cpu_to_ube16(&buf[16], 706);
                    buf[18] = 0;
                    buf[19] = 2;
                    cpu_to_ube16(&buf[20], 512);
                    cpu_to_ube16(&buf[22], 706);
                    buf[24] = 0;
                    buf[25] = 0;
                    buf[26] = 0;
                    buf[27] = 0;
                    ide_atapi_cmd_reply(s, 28, max_len);
                default:
                    goto error_cmd;
            case 1: /* changeable values */
                goto error_cmd;
            case 2: /* default values */
                goto error_cmd;
            default:
            case 3: /* saved values */
                                    ASC_SAVING_PARAMETERS_NOT_SUPPORTED);
    case GPCMD_REQUEST_SENSE:
        max_len = packet[4];
        memset(buf, 0, 18);
        buf[0] = 0x70 | (1 << 7);
        buf[2] = s->sense_key;
        buf[7] = 10;
        buf[12] = s->asc;
        if (s->sense_key == SENSE_UNIT_ATTENTION)
            s->sense_key = SENSE_NONE;
        ide_atapi_cmd_reply(s, 18, max_len);
    case GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL:
        if (bdrv_is_inserted(s->bs)) {
            bdrv_set_locked(s->bs, packet[4] & 1);
            ide_atapi_cmd_ok(s);
        } else {
            ide_atapi_cmd_error(s, SENSE_NOT_READY,
                                ASC_MEDIUM_NOT_PRESENT);
    case GPCMD_READ_10:
    case GPCMD_READ_12:
        {
            int nb_sectors, lba;
            if (packet[0] == GPCMD_READ_10)
                nb_sectors = ube16_to_cpu(packet + 7);
            else
                nb_sectors = ube32_to_cpu(packet + 6);
            lba = ube32_to_cpu(packet + 2);
            if (nb_sectors == 0) {
                ide_atapi_cmd_ok(s);
            ide_atapi_cmd_read(s, lba, nb_sectors, 2048);
    case GPCMD_READ_CD:
        {
            int nb_sectors, lba, transfer_request;
            nb_sectors = (packet[6] << 16) | (packet[7] << 8) | packet[8];
            lba = ube32_to_cpu(packet + 2);
            if (nb_sectors == 0) {
                ide_atapi_cmd_ok(s);
            transfer_request = packet[9];
            switch(transfer_request & 0xf8) {
            case 0x00:
                /* nothing */
                ide_atapi_cmd_ok(s);
            case 0x10:
                /* normal read */
                ide_atapi_cmd_read(s, lba, nb_sectors, 2048);
            case 0xf8:
                /* read all data */
                ide_atapi_cmd_read(s, lba, nb_sectors, 2352);
            default:
    case GPCMD_SEEK:
        {
            unsigned int lba;
            uint64_t total_sectors;
            bdrv_get_geometry(s->bs, &total_sectors);
            total_sectors >>= 2;
            if (total_sectors == 0) {
                ide_atapi_cmd_error(s, SENSE_NOT_READY,
                                    ASC_MEDIUM_NOT_PRESENT);
            lba = ube32_to_cpu(packet + 2);
            if (lba >= total_sectors) {
                                    ASC_LOGICAL_BLOCK_OOR);
            ide_atapi_cmd_ok(s);
    case GPCMD_START_STOP_UNIT:
        {
            int start, eject, err = 0;
            start = packet[4] & 1;
            eject = (packet[4] >> 1) & 1;
            if (eject) {
                err = bdrv_eject(s->bs, !start);
            switch (err) {
            case 0:
                ide_atapi_cmd_ok(s);
            case -EBUSY:
                ide_atapi_cmd_error(s, SENSE_NOT_READY,
                                    ASC_MEDIA_REMOVAL_PREVENTED);
            default:
                ide_atapi_cmd_error(s, SENSE_NOT_READY,
                                    ASC_MEDIUM_NOT_PRESENT);
    case GPCMD_MECHANISM_STATUS:
        {
            max_len = ube16_to_cpu(packet + 8);
            cpu_to_ube16(buf, 0);
            /* no current LBA */
            buf[2] = 0;
            buf[3] = 0;
            buf[4] = 0;
            buf[5] = 1;
            cpu_to_ube16(buf + 6, 0);
            ide_atapi_cmd_reply(s, 8, max_len);
    case GPCMD_READ_TOC_PMA_ATIP:
        {
            int format, msf, start_track, len;
            uint64_t total_sectors;
            bdrv_get_geometry(s->bs, &total_sectors);
            total_sectors >>= 2;
            if (total_sectors == 0) {
                ide_atapi_cmd_error(s, SENSE_NOT_READY,
                                    ASC_MEDIUM_NOT_PRESENT);
            format = packet[9] >> 6;
            msf = (packet[1] >> 1) & 1;
            start_track = packet[6];
            switch(format) {
            case 0:
                len = cdrom_read_toc(total_sectors, buf, msf, start_track);
                if (len < 0)
                    goto error_cmd;
                ide_atapi_cmd_reply(s, len, max_len);
            case 1:
                /* multi session : only a single session defined */
                memset(buf, 0, 12);
                buf[1] = 0x0a;
                buf[2] = 0x01;
                buf[3] = 0x01;
                ide_atapi_cmd_reply(s, 12, max_len);
            case 2:
                len = cdrom_read_toc_raw(total_sectors, buf, msf, start_track);
                if (len < 0)
                    goto error_cmd;
                ide_atapi_cmd_reply(s, len, max_len);
            default:
            error_cmd:
    case GPCMD_READ_CDVD_CAPACITY:
        {
            uint64_t total_sectors;
            bdrv_get_geometry(s->bs, &total_sectors);
            total_sectors >>= 2;
            if (total_sectors == 0) {
                ide_atapi_cmd_error(s, SENSE_NOT_READY,
                                    ASC_MEDIUM_NOT_PRESENT);
            /* NOTE: it is really the number of sectors minus 1 */
            cpu_to_ube32(buf, total_sectors - 1);
            cpu_to_ube32(buf + 4, 2048);
            ide_atapi_cmd_reply(s, 8, 8);
    case GPCMD_READ_DVD_STRUCTURE:
        {
            int media = packet[1];
            int format = packet[7];
            int ret;
            max_len = ube16_to_cpu(packet + 8);
            if (format < 0xff) {
                if (media_is_cd(s)) {
                                        ASC_INCOMPATIBLE_FORMAT);
                } else if (!media_present(s)) {
            memset(buf, 0, max_len > IDE_DMA_BUF_SECTORS * 512 + 4 ?
                   IDE_DMA_BUF_SECTORS * 512 + 4 : max_len);
            switch (format) {
                case 0x00 ... 0x7f:
                case 0xff:
                    if (media == 0) {
                        ret = ide_dvd_read_structure(s, format, packet, buf);
                        if (ret < 0)
                            ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST, -ret);
                        else
                            ide_atapi_cmd_reply(s, ret, max_len);
                    /* TODO: BD support, fall through for now */
                /* Generic disk structures */
                case 0x80: /* TODO: AACS volume identifier */
                case 0x81: /* TODO: AACS media serial number */
                case 0x82: /* TODO: AACS media identifier */
                case 0x83: /* TODO: AACS media key block */
                case 0x90: /* TODO: List of recognized format layers */
                case 0xc0: /* TODO: Write protection status */
                default:
    case GPCMD_SET_SPEED:
        ide_atapi_cmd_ok(s);
    case GPCMD_INQUIRY:
        max_len = packet[4];
        buf[0] = 0x05; /* CD-ROM */
        buf[1] = 0x80; /* removable */
        buf[2] = 0x00; /* ISO */
        buf[3] = 0x21; /* ATAPI-2 (XXX: put ATAPI-4 ?) */
        buf[4] = 31; /* additional length */
        buf[5] = 0; /* reserved */
        buf[6] = 0; /* reserved */
        buf[7] = 0; /* reserved */
        padstr8(buf + 8, 8, "QEMU");
        padstr8(buf + 16, 16, "QEMU DVD-ROM");
        padstr8(buf + 32, 4, s->version);
        ide_atapi_cmd_reply(s, 36, max_len);
    case GPCMD_GET_CONFIGURATION:
        {
            uint32_t len;
            uint8_t index = 0;
            /* only feature 0 is supported */
            if (packet[2] != 0 || packet[3] != 0) {
            /* XXX: could result in alignment problems in some architectures */
            /*
             * XXX: avoid overflow for io_buffer if max_len is bigger than
             *      the size of that buffer (dimensioned to max number of
             *      sectors to transfer at once)
             *
             *      Only a problem if the feature/profiles grow.
             */
            if (max_len > 512) /* XXX: assume 1 sector */
                max_len = 512;
            memset(buf, 0, max_len);
            /*
             * the number of sectors from the media tells us which profile
             * to use as current.  0 means there is no media
             */
            if (media_is_dvd(s))
                cpu_to_ube16(buf + 6, MMC_PROFILE_DVD_ROM);
            else if (media_is_cd(s))
                cpu_to_ube16(buf + 6, MMC_PROFILE_CD_ROM);
            buf[10] = 0x02 | 0x01; /* persistent and current */
            len = 12; /* headers: 8 + 4 */
            len += ide_atapi_set_profile(buf, &index, MMC_PROFILE_DVD_ROM);
            len += ide_atapi_set_profile(buf, &index, MMC_PROFILE_CD_ROM);
            cpu_to_ube32(buf, len - 4); /* data length */
            ide_atapi_cmd_reply(s, len, max_len);
    default:
                            ASC_ILLEGAL_OPCODE);


void rgb16tobgr15(const uint8_t *src, uint8_t *dst, unsigned int src_size)

{

	unsigned i;

	unsigned num_pixels = src_size >> 1;

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

	{

	    unsigned b,g,r;

	    register uint16_t rgb;

	    rgb = src[2*i];

	    r = rgb&0x1F;

	    g = (rgb&0x7E0)>>5;

	    b = (rgb&0xF800)>>11;

	    dst[2*i] = (b&0x1F) | ((g&0x1F)<<5) | ((r&0x1F)<<10);

	}

}


static struct scsi_task *iscsi_do_inquiry(struct iscsi_context *iscsi, int lun,

                                          int evpd, int pc, void **inq, Error **errp)

{

    int full_size;

    struct scsi_task *task = NULL;

    task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, 64);

    if (task == NULL || task->status != SCSI_STATUS_GOOD) {

        goto fail;

    }

    full_size = scsi_datain_getfullsize(task);

    if (full_size > task->datain.size) {

        scsi_free_scsi_task(task);

        /* we need more data for the full list */

        task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, full_size);

        if (task == NULL || task->status != SCSI_STATUS_GOOD) {

            goto fail;

        }

    }

    *inq = scsi_datain_unmarshall(task);

    if (*inq == NULL) {

        error_setg(errp, "iSCSI: failed to unmarshall inquiry datain blob");

        goto fail;

    }

    return task;

fail:

    if (!error_is_set(errp)) {

        error_setg(errp, "iSCSI: Inquiry command failed : %s",

                   iscsi_get_error(iscsi));

    }

    if (task != NULL) {

        scsi_free_scsi_task(task);

    }

    return NULL;

}


int kvm_arch_handle_exit(CPUPPCState *env, struct kvm_run *run)

{

    int ret;

    switch (run->exit_reason) {

    case KVM_EXIT_DCR:

        if (run->dcr.is_write) {

            dprintf("handle dcr write\n");

            ret = kvmppc_handle_dcr_write(env, run->dcr.dcrn, run->dcr.data);

        } else {

            dprintf("handle dcr read\n");

            ret = kvmppc_handle_dcr_read(env, run->dcr.dcrn, &run->dcr.data);

        }

        break;

    case KVM_EXIT_HLT:

        dprintf("handle halt\n");

        ret = kvmppc_handle_halt(env);

        break;

#ifdef CONFIG_PSERIES

    case KVM_EXIT_PAPR_HCALL:

        dprintf("handle PAPR hypercall\n");

        run->papr_hcall.ret = spapr_hypercall(env, run->papr_hcall.nr,

                                              run->papr_hcall.args);

        ret = 1;

        break;

#endif

    default:

        fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);

        ret = -1;

        break;

    }

    return ret;

}


static void tgen_andi(TCGContext *s, TCGType type, TCGReg dest, uint64_t val)

{

    static const S390Opcode ni_insns[4] = {

        RI_NILL, RI_NILH, RI_NIHL, RI_NIHH

    };

    static const S390Opcode nif_insns[2] = {

        RIL_NILF, RIL_NIHF

    };

    uint64_t valid = (type == TCG_TYPE_I32 ? 0xffffffffull : -1ull);

    int i;

    /* Look for the zero-extensions.  */

    if ((val & valid) == 0xffffffff) {

        tgen_ext32u(s, dest, dest);

        return;

    }

    if (facilities & FACILITY_EXT_IMM) {

        if ((val & valid) == 0xff) {

            tgen_ext8u(s, TCG_TYPE_I64, dest, dest);

            return;

        }

        if ((val & valid) == 0xffff) {

            tgen_ext16u(s, TCG_TYPE_I64, dest, dest);

            return;

        }

    }

    /* Try all 32-bit insns that can perform it in one go.  */

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

        tcg_target_ulong mask = ~(0xffffull << i*16);

        if (((val | ~valid) & mask) == mask) {

            tcg_out_insn_RI(s, ni_insns[i], dest, val >> i*16);

            return;

        }

    }

    /* Try all 48-bit insns that can perform it in one go.  */

    if (facilities & FACILITY_EXT_IMM) {

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

            tcg_target_ulong mask = ~(0xffffffffull << i*32);

            if (((val | ~valid) & mask) == mask) {

                tcg_out_insn_RIL(s, nif_insns[i], dest, val >> i*32);

                return;

            }

        }

    }

    if ((facilities & FACILITY_GEN_INST_EXT) && risbg_mask(val)) {

        int msb, lsb;

        if ((val & 0x8000000000000001ull) == 0x8000000000000001ull) {

            /* Achieve wraparound by swapping msb and lsb.  */

            msb = 63 - ctz64(~val);

            lsb = clz64(~val) + 1;

        } else {

            msb = clz64(val);

            lsb = 63 - ctz64(val);

        }

        tcg_out_risbg(s, dest, dest, msb, lsb, 0, 1);

        return;

    }

    /* Fall back to loading the constant.  */

    tcg_out_movi(s, type, TCG_TMP0, val);

    if (type == TCG_TYPE_I32) {

        tcg_out_insn(s, RR, NR, dest, TCG_TMP0);

    } else {

        tcg_out_insn(s, RRE, NGR, dest, TCG_TMP0);

    }

}


static inline void RENAME(rgb16to24)(const uint8_t *src, uint8_t *dst, unsigned src_size)

{

	const uint16_t *end;

#ifdef HAVE_MMX

	const uint16_t *mm_end;

#endif

	uint8_t *d = (uint8_t *)dst;

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

	end = s + src_size/2;

#ifdef HAVE_MMX

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		MOVNTQ"	%%mm1, 8%0\n\t"

		MOVNTQ"	%%mm4, 16%0"

		:"=m"(*d)

		:"m"(*s),"m"(mask24l),"m"(mask24h),"m"(mask24hh),"m"(mask24hhh),"m"(mask24hhhh)

		:"memory");

		d += 24;

		s += 8;

	}

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

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

#endif

	while(s < end)

	{

		register uint16_t bgr;

		bgr = *s++;

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

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

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

	}

}


static void gen_tlbsx_40x(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    TCGv t0;

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    t0 = tcg_temp_new();

    gen_addr_reg_index(ctx, t0);

    gen_helper_4xx_tlbsx(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);

    tcg_temp_free(t0);

    if (Rc(ctx->opcode)) {

        TCGLabel *l1 = gen_new_label();

        tcg_gen_trunc_tl_i32(cpu_crf[0], cpu_so);

        tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_gpr[rD(ctx->opcode)], -1, l1);

        tcg_gen_ori_i32(cpu_crf[0], cpu_crf[0], 0x02);

        gen_set_label(l1);

    }

#endif

}


static int sdp_parse_fmtp_config_h264(AVFormatContext *s,

                                      AVStream *stream,

                                      PayloadContext *h264_data,

                                      const char *attr, const char *value)

{

    AVCodecParameters *par = stream->codecpar;

    if (!strcmp(attr, "packetization-mode")) {

        av_log(s, AV_LOG_DEBUG, "RTP Packetization Mode: %d\n", atoi(value));

        h264_data->packetization_mode = atoi(value);

        /*

         * Packetization Mode:

         * 0 or not present: Single NAL mode (Only nals from 1-23 are allowed)

         * 1: Non-interleaved Mode: 1-23, 24 (STAP-A), 28 (FU-A) are allowed.

         * 2: Interleaved Mode: 25 (STAP-B), 26 (MTAP16), 27 (MTAP24), 28 (FU-A),

         *                      and 29 (FU-B) are allowed.

         */

        if (h264_data->packetization_mode > 1)

            av_log(s, AV_LOG_ERROR,

                   "Interleaved RTP mode is not supported yet.\n");

    } else if (!strcmp(attr, "profile-level-id")) {

        if (strlen(value) == 6)

            parse_profile_level_id(s, h264_data, value);

    } else if (!strcmp(attr, "sprop-parameter-sets")) {

        int ret;

        if (value[strlen(value) - 1] == ',') {

            av_log(s, AV_LOG_WARNING, "Missing PPS in sprop-parameter-sets, ignoring\n");

            return 0;

        }

        par->extradata_size = 0;

        av_freep(&par->extradata);

        ret = ff_h264_parse_sprop_parameter_sets(s, &par->extradata,

                                                 &par->extradata_size, value);

        av_log(s, AV_LOG_DEBUG, "Extradata set to %p (size: %d)\n",

               par->extradata, par->extradata_size);

        return ret;

    }

    return 0;

}


int ff_mpv_reallocate_putbitbuffer(MpegEncContext *s, size_t threshold, size_t size_increase)
{
    if (   s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < threshold
        && s->slice_context_count == 1
        && s->pb.buf == s->avctx->internal->byte_buffer) {
        int lastgob_pos = s->ptr_lastgob - s->pb.buf;
        int vbv_pos     = s->vbv_delay_ptr - s->pb.buf;
        uint8_t *new_buffer = NULL;
        int new_buffer_size = 0;
        av_fast_padded_malloc(&new_buffer, &new_buffer_size,
                              s->avctx->internal->byte_buffer_size + size_increase);
        if (!new_buffer)
        memcpy(new_buffer, s->avctx->internal->byte_buffer, s->avctx->internal->byte_buffer_size);
        av_free(s->avctx->internal->byte_buffer);
        s->avctx->internal->byte_buffer      = new_buffer;
        s->avctx->internal->byte_buffer_size = new_buffer_size;
        rebase_put_bits(&s->pb, new_buffer, new_buffer_size);
        s->ptr_lastgob   = s->pb.buf + lastgob_pos;
        s->vbv_delay_ptr = s->pb.buf + vbv_pos;
    if (s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < threshold)
        return AVERROR(EINVAL);
    return 0;


int64_t object_property_get_int(Object *obj, const char *name,

                                Error **errp)

{

    QObject *ret = object_property_get_qobject(obj, name, errp);

    QInt *qint;

    int64_t retval;

    if (!ret) {

        return -1;

    }

    qint = qobject_to_qint(ret);

    if (!qint) {

        error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name, "int");

        retval = -1;

    } else {

        retval = qint_get_int(qint);

    }

    QDECREF(qint);

    return retval;

}


void av_get_channel_layout_string(char *buf, int buf_size,

                                  int nb_channels, uint64_t channel_layout)

{

    int i;

    if (nb_channels <= 0)

        nb_channels = av_get_channel_layout_nb_channels(channel_layout);

    for (i = 0; channel_layout_map[i].name; i++)

        if (nb_channels    == channel_layout_map[i].nb_channels &&

            channel_layout == channel_layout_map[i].layout) {

            av_strlcpy(buf, channel_layout_map[i].name, buf_size);

            return;

        }

    snprintf(buf, buf_size, "%d channels", nb_channels);

    if (channel_layout) {

        int i, ch;

        av_strlcat(buf, " (", buf_size);

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

            if ((channel_layout & (1L << i))) {

                const char *name = get_channel_name(i);

                if (name) {

                    if (ch > 0)

                        av_strlcat(buf, "|", buf_size);

                    av_strlcat(buf, name, buf_size);

                }

                ch++;

            }

        }

        av_strlcat(buf, ")", buf_size);

    }

}


int qemu_read_password(char *buf, int buf_size)

{

    uint8_t ch;

    int i, ret;

    printf("password: ");

    fflush(stdout);

    term_init();

    i = 0;

    for (;;) {

        ret = read(0, &ch, 1);

        if (ret == -1) {

            if (errno == EAGAIN || errno == EINTR) {

                continue;

            } else {

                break;

            }

        } else if (ret == 0) {

            ret = -1;

            break;

        } else {

            if (ch == '\r' ||

                ch == '\n') {

                ret = 0;

                break;

            }

            if (i < (buf_size - 1)) {

                buf[i++] = ch;

            }

        }

    }

    term_exit();

    buf[i] = '\0';

    printf("\n");

    return ret;

}


static void smbios_build_type_1_fields(const char *t)

{

    char buf[1024];

    if (get_param_value(buf, sizeof(buf), "manufacturer", t))

        smbios_add_field(1, offsetof(struct smbios_type_1, manufacturer_str),

                         strlen(buf) + 1, buf);

    if (get_param_value(buf, sizeof(buf), "product", t))

        smbios_add_field(1, offsetof(struct smbios_type_1, product_name_str),

                         strlen(buf) + 1, buf);

    if (get_param_value(buf, sizeof(buf), "version", t))

        smbios_add_field(1, offsetof(struct smbios_type_1, version_str),

                         strlen(buf) + 1, buf);

    if (get_param_value(buf, sizeof(buf), "serial", t))

        smbios_add_field(1, offsetof(struct smbios_type_1, serial_number_str),

                         strlen(buf) + 1, buf);

    if (get_param_value(buf, sizeof(buf), "uuid", t)) {

        if (qemu_uuid_parse(buf, qemu_uuid) != 0) {

            fprintf(stderr, "Invalid SMBIOS UUID string\n");

            exit(1);

        }

    }

    if (get_param_value(buf, sizeof(buf), "sku", t))

        smbios_add_field(1, offsetof(struct smbios_type_1, sku_number_str),

                         strlen(buf) + 1, buf);

    if (get_param_value(buf, sizeof(buf), "family", t))

        smbios_add_field(1, offsetof(struct smbios_type_1, family_str),

                         strlen(buf) + 1, buf);

}


int css_do_tsch_get_irb(SubchDev *sch, IRB *target_irb, int *irb_len)

{

    SCSW *s = &sch->curr_status.scsw;

    PMCW *p = &sch->curr_status.pmcw;

    uint16_t stctl;

    IRB irb;

    if (!(p->flags & (PMCW_FLAGS_MASK_DNV | PMCW_FLAGS_MASK_ENA))) {

        return 3;

    }

    stctl = s->ctrl & SCSW_CTRL_MASK_STCTL;

    /* Prepare the irb for the guest. */

    memset(&irb, 0, sizeof(IRB));

    /* Copy scsw from current status. */

    memcpy(&irb.scsw, s, sizeof(SCSW));

    if (stctl & SCSW_STCTL_STATUS_PEND) {

        if (s->cstat & (SCSW_CSTAT_DATA_CHECK |

                        SCSW_CSTAT_CHN_CTRL_CHK |

                        SCSW_CSTAT_INTF_CTRL_CHK)) {

            irb.scsw.flags |= SCSW_FLAGS_MASK_ESWF;

            irb.esw[0] = 0x04804000;

        } else {

            irb.esw[0] = 0x00800000;

        }

        /* If a unit check is pending, copy sense data. */

        if ((s->dstat & SCSW_DSTAT_UNIT_CHECK) &&

            (p->chars & PMCW_CHARS_MASK_CSENSE)) {

            int i;

            irb.scsw.flags |= SCSW_FLAGS_MASK_ESWF | SCSW_FLAGS_MASK_ECTL;

            /* Attention: sense_data is already BE! */

            memcpy(irb.ecw, sch->sense_data, sizeof(sch->sense_data));

            for (i = 0; i < ARRAY_SIZE(irb.ecw); i++) {

                irb.ecw[i] = be32_to_cpu(irb.ecw[i]);

            }

            irb.esw[1] = 0x01000000 | (sizeof(sch->sense_data) << 8);

        }

    }

    /* Store the irb to the guest. */

    copy_irb_to_guest(target_irb, &irb, p, irb_len);

    return ((stctl & SCSW_STCTL_STATUS_PEND) == 0);

}


void helper_ldq_kernel(uint64_t t0, uint64_t t1)

{

    ldq_kernel(t1, t0);

}


static void lm32_uclinux_init(MachineState *machine)

{

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    LM32CPU *cpu;

    CPULM32State *env;

    DriveInfo *dinfo;

    MemoryRegion *address_space_mem =  get_system_memory();

    MemoryRegion *phys_ram = g_new(MemoryRegion, 1);

    qemu_irq *cpu_irq, irq[32];

    HWSetup *hw;

    ResetInfo *reset_info;

    int i;

    /* memory map */

    hwaddr flash_base   = 0x04000000;

    size_t flash_sector_size        = 256 * 1024;

    size_t flash_size               = 32 * 1024 * 1024;

    hwaddr ram_base     = 0x08000000;

    size_t ram_size                 = 64 * 1024 * 1024;

    hwaddr uart0_base   = 0x80000000;

    hwaddr timer0_base  = 0x80002000;

    hwaddr timer1_base  = 0x80010000;

    hwaddr timer2_base  = 0x80012000;

    int uart0_irq                   = 0;

    int timer0_irq                  = 1;

    int timer1_irq                  = 20;

    int timer2_irq                  = 21;

    hwaddr hwsetup_base = 0x0bffe000;

    hwaddr cmdline_base = 0x0bfff000;

    hwaddr initrd_base  = 0x08400000;

    size_t initrd_max               = 0x01000000;

    reset_info = g_malloc0(sizeof(ResetInfo));

    if (cpu_model == NULL) {

        cpu_model = "lm32-full";

    }

    cpu = cpu_lm32_init(cpu_model);

    if (cpu == NULL) {

        fprintf(stderr, "qemu: unable to find CPU '%s'\n", cpu_model);

        exit(1);

    }

    env = &cpu->env;

    reset_info->cpu = cpu;

    reset_info->flash_base = flash_base;

    memory_region_init_ram(phys_ram, NULL, "lm32_uclinux.sdram", ram_size,

                           &error_abort);

    vmstate_register_ram_global(phys_ram);

    memory_region_add_subregion(address_space_mem, ram_base, phys_ram);

    dinfo = drive_get(IF_PFLASH, 0, 0);

    /* Spansion S29NS128P */

    pflash_cfi02_register(flash_base, NULL, "lm32_uclinux.flash", flash_size,

                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,

                          flash_sector_size, flash_size / flash_sector_size,

                          1, 2, 0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1);

    /* create irq lines */

    cpu_irq = qemu_allocate_irqs(cpu_irq_handler, env, 1);

    env->pic_state = lm32_pic_init(*cpu_irq);

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

        irq[i] = qdev_get_gpio_in(env->pic_state, i);

    }

    sysbus_create_simple("lm32-uart", uart0_base, irq[uart0_irq]);

    sysbus_create_simple("lm32-timer", timer0_base, irq[timer0_irq]);

    sysbus_create_simple("lm32-timer", timer1_base, irq[timer1_irq]);

    sysbus_create_simple("lm32-timer", timer2_base, irq[timer2_irq]);

    /* make sure juart isn't the first chardev */

    env->juart_state = lm32_juart_init();

    reset_info->bootstrap_pc = flash_base;

    if (kernel_filename) {

        uint64_t entry;

        int kernel_size;

        kernel_size = load_elf(kernel_filename, NULL, NULL, &entry, NULL, NULL,

                               1, ELF_MACHINE, 0);

        reset_info->bootstrap_pc = entry;

        if (kernel_size < 0) {

            kernel_size = load_image_targphys(kernel_filename, ram_base,

                                              ram_size);

            reset_info->bootstrap_pc = ram_base;

        }

        if (kernel_size < 0) {

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

                    kernel_filename);

            exit(1);

        }

    }

    /* generate a rom with the hardware description */

    hw = hwsetup_init();

    hwsetup_add_cpu(hw, "LM32", 75000000);

    hwsetup_add_flash(hw, "flash", flash_base, flash_size);

    hwsetup_add_ddr_sdram(hw, "ddr_sdram", ram_base, ram_size);

    hwsetup_add_timer(hw, "timer0", timer0_base, timer0_irq);

    hwsetup_add_timer(hw, "timer1_dev_only", timer1_base, timer1_irq);

    hwsetup_add_timer(hw, "timer2_dev_only", timer2_base, timer2_irq);

    hwsetup_add_uart(hw, "uart", uart0_base, uart0_irq);

    hwsetup_add_trailer(hw);

    hwsetup_create_rom(hw, hwsetup_base);

    hwsetup_free(hw);

    reset_info->hwsetup_base = hwsetup_base;

    if (kernel_cmdline && strlen(kernel_cmdline)) {

        pstrcpy_targphys("cmdline", cmdline_base, TARGET_PAGE_SIZE,

                kernel_cmdline);

        reset_info->cmdline_base = cmdline_base;

    }

    if (initrd_filename) {

        size_t initrd_size;

        initrd_size = load_image_targphys(initrd_filename, initrd_base,

                initrd_max);

        reset_info->initrd_base = initrd_base;

        reset_info->initrd_size = initrd_size;

    }

    qemu_register_reset(main_cpu_reset, reset_info);

}


static inline int retry_transfer_wrapper(URLContext *h, unsigned char *buf, int size, int size_min,

                                         int (*transfer_func)(URLContext *h, unsigned char *buf, int size))

{

    int ret, len;

    int fast_retries = 5;

    int64_t wait_since = 0;

    len = 0;

    while (len < size_min) {

        ret = transfer_func(h, buf+len, size-len);

        if (ret == AVERROR(EINTR))

            continue;

        if (h->flags & AVIO_FLAG_NONBLOCK)

            return ret;

        if (ret == AVERROR(EAGAIN)) {

            ret = 0;

            if (fast_retries) {

                fast_retries--;

            } else {

                if (h->rw_timeout) {

                    if (!wait_since)

                        wait_since = av_gettime();

                    else if (av_gettime() > wait_since + h->rw_timeout)

                        return AVERROR(EIO);

                }

                av_usleep(1000);

            }

        } else if (ret < 1)

            return (ret < 0 && ret != AVERROR_EOF) ? ret : len;

        if (ret)

           fast_retries = FFMAX(fast_retries, 2);

        len += ret;

        if (len < size && ff_check_interrupt(&h->interrupt_callback))

            return AVERROR_EXIT;

    }

    return len;

}


static void virtio_ccw_scsi_realize(VirtioCcwDevice *ccw_dev, Error **errp)

{

    VirtIOSCSICcw *dev = VIRTIO_SCSI_CCW(ccw_dev);

    DeviceState *vdev = DEVICE(&dev->vdev);

    DeviceState *qdev = DEVICE(ccw_dev);

    Error *err = NULL;

    char *bus_name;

    /*

     * For command line compatibility, this sets the virtio-scsi-device bus

     * name as before.

     */

    if (qdev->id) {

        bus_name = g_strdup_printf("%s.0", qdev->id);

        virtio_device_set_child_bus_name(VIRTIO_DEVICE(vdev), bus_name);

        g_free(bus_name);

    }

    qdev_set_parent_bus(vdev, BUS(&ccw_dev->bus));

    object_property_set_bool(OBJECT(vdev), true, "realized", &err);

    if (err) {

        error_propagate(errp, err);

    }

}


static void mpc8544_guts_write(void *opaque, target_phys_addr_t addr,

                               uint64_t value, unsigned size)

{

    addr &= MPC8544_GUTS_MMIO_SIZE - 1;

    switch (addr) {

    case MPC8544_GUTS_ADDR_RSTCR:

        if (value & MPC8544_GUTS_RSTCR_RESET) {

            qemu_system_reset_request();

        }

        break;

    default:

        fprintf(stderr, "guts: Unknown register write: %x = %x\n",

                (int)addr, (unsigned)value);

        break;

    }

}


static int v9fs_do_chown(V9fsState *s, V9fsString *path, uid_t uid, gid_t gid)

{

    return s->ops->chown(&s->ctx, path->data, uid, gid);

}


static int check_host_key_knownhosts(BDRVSSHState *s,

                                     const char *host, int port)

{

    const char *home;

    char *knh_file = NULL;

    LIBSSH2_KNOWNHOSTS *knh = NULL;

    struct libssh2_knownhost *found;

    int ret, r;

    const char *hostkey;

    size_t len;

    int type;

    hostkey = libssh2_session_hostkey(s->session, &len, &type);

    if (!hostkey) {

        ret = -EINVAL;

        session_error_report(s, "failed to read remote host key");

        goto out;

    }

    knh = libssh2_knownhost_init(s->session);

    if (!knh) {

        ret = -EINVAL;

        session_error_report(s, "failed to initialize known hosts support");

        goto out;

    }

    home = getenv("HOME");

    if (home) {

        knh_file = g_strdup_printf("%s/.ssh/known_hosts", home);

    } else {

        knh_file = g_strdup_printf("/root/.ssh/known_hosts");

    }

    /* Read all known hosts from OpenSSH-style known_hosts file. */

    libssh2_knownhost_readfile(knh, knh_file, LIBSSH2_KNOWNHOST_FILE_OPENSSH);

    r = libssh2_knownhost_checkp(knh, host, port, hostkey, len,

                                 LIBSSH2_KNOWNHOST_TYPE_PLAIN|

                                 LIBSSH2_KNOWNHOST_KEYENC_RAW,

                                 &found);

    switch (r) {

    case LIBSSH2_KNOWNHOST_CHECK_MATCH:

        /* OK */

        DPRINTF("host key OK: %s", found->key);

        break;

    case LIBSSH2_KNOWNHOST_CHECK_MISMATCH:

        ret = -EINVAL;

        session_error_report(s, "host key does not match the one in known_hosts (found key %s)",

                             found->key);

        goto out;

    case LIBSSH2_KNOWNHOST_CHECK_NOTFOUND:

        ret = -EINVAL;

        session_error_report(s, "no host key was found in known_hosts");

        goto out;

    case LIBSSH2_KNOWNHOST_CHECK_FAILURE:

        ret = -EINVAL;

        session_error_report(s, "failure matching the host key with known_hosts");

        goto out;

    default:

        ret = -EINVAL;

        session_error_report(s, "unknown error matching the host key with known_hosts (%d)",

                             r);

        goto out;

    }

    /* known_hosts checking successful. */

    ret = 0;

 out:

    if (knh != NULL) {

        libssh2_knownhost_free(knh);

    }

    g_free(knh_file);

    return ret;

}