void qio_channel_socket_dgram_async(QIOChannelSocket *ioc,

                                    SocketAddress *localAddr,

                                    SocketAddress *remoteAddr,

                                    QIOTaskFunc callback,

                                    gpointer opaque,

                                    GDestroyNotify destroy)

{

    QIOTask *task = qio_task_new(

        OBJECT(ioc), callback, opaque, destroy);

    struct QIOChannelSocketDGramWorkerData *data = g_new0(

        struct QIOChannelSocketDGramWorkerData, 1);

    data->localAddr = QAPI_CLONE(SocketAddress, localAddr);

    data->remoteAddr = QAPI_CLONE(SocketAddress, remoteAddr);

    trace_qio_channel_socket_dgram_async(ioc, localAddr, remoteAddr);

    qio_task_run_in_thread(task,

                           qio_channel_socket_dgram_worker,

                           data,

                           qio_channel_socket_dgram_worker_free);

}


static av_cold int libx265_encode_init(AVCodecContext *avctx)

{

    libx265Context *ctx = avctx->priv_data;

    ctx->api = x265_api_get(av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth_minus1 + 1);

    if (!ctx->api)

        ctx->api = x265_api_get(0);

    if (avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL &&

        !av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_w) {

        av_log(avctx, AV_LOG_ERROR,

               "4:2:2 and 4:4:4 support is not fully defined for HEVC yet. "

               "Set -strict experimental to encode anyway.\n");

        return AVERROR(ENOSYS);

    }

    avctx->coded_frame = av_frame_alloc();

    if (!avctx->coded_frame) {

        av_log(avctx, AV_LOG_ERROR, "Could not allocate frame.\n");

        return AVERROR(ENOMEM);

    }

    ctx->params = ctx->api->param_alloc();

    if (!ctx->params) {

        av_log(avctx, AV_LOG_ERROR, "Could not allocate x265 param structure.\n");

        return AVERROR(ENOMEM);

    }

    if (ctx->api->param_default_preset(ctx->params, ctx->preset, ctx->tune) < 0) {

        int i;

        av_log(avctx, AV_LOG_ERROR, "Error setting preset/tune %s/%s.\n", ctx->preset, ctx->tune);

        av_log(avctx, AV_LOG_INFO, "Possible presets:");

        for (i = 0; x265_preset_names[i]; i++)

            av_log(avctx, AV_LOG_INFO, " %s", x265_preset_names[i]);

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

        av_log(avctx, AV_LOG_INFO, "Possible tunes:");

        for (i = 0; x265_tune_names[i]; i++)

            av_log(avctx, AV_LOG_INFO, " %s", x265_tune_names[i]);

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

        return AVERROR(EINVAL);

    }

    ctx->params->frameNumThreads = avctx->thread_count;

    ctx->params->fpsNum          = avctx->time_base.den;

    ctx->params->fpsDenom        = avctx->time_base.num * avctx->ticks_per_frame;

    ctx->params->sourceWidth     = avctx->width;

    ctx->params->sourceHeight    = avctx->height;

    ctx->params->bEnablePsnr     = !!(avctx->flags & CODEC_FLAG_PSNR);

    if ((avctx->color_primaries <= AVCOL_PRI_BT2020 &&

         avctx->color_primaries != AVCOL_PRI_UNSPECIFIED) ||

        (avctx->color_trc <= AVCOL_TRC_BT2020_12 &&

         avctx->color_trc != AVCOL_TRC_UNSPECIFIED) ||

        (avctx->colorspace <= AVCOL_SPC_BT2020_CL &&

         avctx->colorspace != AVCOL_SPC_UNSPECIFIED)) {

        ctx->params->vui.bEnableVideoSignalTypePresentFlag  = 1;

        ctx->params->vui.bEnableColorDescriptionPresentFlag = 1;

        // x265 validates the parameters internally

        ctx->params->vui.colorPrimaries          = avctx->color_primaries;

        ctx->params->vui.transferCharacteristics = avctx->color_trc;

        ctx->params->vui.matrixCoeffs            = avctx->colorspace;

    }

    if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {

        char sar[12];

        int sar_num, sar_den;

        av_reduce(&sar_num, &sar_den,

                  avctx->sample_aspect_ratio.num,

                  avctx->sample_aspect_ratio.den, 65535);

        snprintf(sar, sizeof(sar), "%d:%d", sar_num, sar_den);

        if (ctx->api->param_parse(ctx->params, "sar", sar) == X265_PARAM_BAD_VALUE) {

            av_log(avctx, AV_LOG_ERROR, "Invalid SAR: %d:%d.\n", sar_num, sar_den);

            return AVERROR_INVALIDDATA;

        }

    }

    switch (avctx->pix_fmt) {

    case AV_PIX_FMT_YUV420P:

    case AV_PIX_FMT_YUV420P10:

        ctx->params->internalCsp = X265_CSP_I420;

        break;

    case AV_PIX_FMT_YUV422P:

    case AV_PIX_FMT_YUV422P10:

        ctx->params->internalCsp = X265_CSP_I422;

        break;

    case AV_PIX_FMT_YUV444P:

    case AV_PIX_FMT_YUV444P10:

        ctx->params->internalCsp = X265_CSP_I444;

        break;

    }

    if (ctx->crf >= 0) {

        char crf[6];

        snprintf(crf, sizeof(crf), "%2.2f", ctx->crf);

        if (ctx->api->param_parse(ctx->params, "crf", crf) == X265_PARAM_BAD_VALUE) {

            av_log(avctx, AV_LOG_ERROR, "Invalid crf: %2.2f.\n", ctx->crf);

            return AVERROR(EINVAL);

        }

    } else if (avctx->bit_rate > 0) {

        ctx->params->rc.bitrate         = avctx->bit_rate / 1000;

        ctx->params->rc.rateControlMode = X265_RC_ABR;

    }

    if (!(avctx->flags & CODEC_FLAG_GLOBAL_HEADER))

        ctx->params->bRepeatHeaders = 1;

    if (ctx->x265_opts) {

        AVDictionary *dict    = NULL;

        AVDictionaryEntry *en = NULL;

        if (!av_dict_parse_string(&dict, ctx->x265_opts, "=", ":", 0)) {

            while ((en = av_dict_get(dict, "", en, AV_DICT_IGNORE_SUFFIX))) {

                int parse_ret = ctx->api->param_parse(ctx->params, en->key, en->value);

                switch (parse_ret) {

                case X265_PARAM_BAD_NAME:

                    av_log(avctx, AV_LOG_WARNING,

                          "Unknown option: %s.\n", en->key);

                    break;

                case X265_PARAM_BAD_VALUE:

                    av_log(avctx, AV_LOG_WARNING,

                          "Invalid value for %s: %s.\n", en->key, en->value);

                    break;

                default:

                    break;

                }

            }

            av_dict_free(&dict);

        }

    }

    ctx->encoder = ctx->api->encoder_open(ctx->params);

    if (!ctx->encoder) {

        av_log(avctx, AV_LOG_ERROR, "Cannot open libx265 encoder.\n");

        libx265_encode_close(avctx);

        return AVERROR_INVALIDDATA;

    }

    if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {

        x265_nal *nal;

        int nnal;

        avctx->extradata_size = ctx->api->encoder_headers(ctx->encoder, &nal, &nnal);

        if (avctx->extradata_size <= 0) {

            av_log(avctx, AV_LOG_ERROR, "Cannot encode headers.\n");

            libx265_encode_close(avctx);

            return AVERROR_INVALIDDATA;

        }

        avctx->extradata = av_malloc(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);

        if (!avctx->extradata) {

            av_log(avctx, AV_LOG_ERROR,

                   "Cannot allocate HEVC header of size %d.\n", avctx->extradata_size);

            libx265_encode_close(avctx);

            return AVERROR(ENOMEM);

        }

        memcpy(avctx->extradata, nal[0].payload, avctx->extradata_size);

    }

    return 0;

}


static uint32_t set_allocation_state(sPAPRDRConnector *drc,

                                     sPAPRDRAllocationState state)

{

    sPAPRDRConnectorClass *drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);

    trace_spapr_drc_set_allocation_state(get_index(drc), state);

    if (state == SPAPR_DR_ALLOCATION_STATE_USABLE) {

        /* if there's no resource/device associated with the DRC, there's

         * no way for us to put it in an allocation state consistent with

         * being 'USABLE'. PAPR 2.7, 13.5.3.4 documents that this should

         * result in an RTAS return code of -3 / "no such indicator"

         */

        if (!drc->dev) {

            return RTAS_OUT_NO_SUCH_INDICATOR;

        }

        if (drc->awaiting_release && drc->awaiting_allocation) {

            /* kernel is acknowledging a previous hotplug event

             * while we are already removing it.

             * it's safe to ignore awaiting_allocation here since we know the

             * situation is predicated on the guest either already having done

             * so (boot-time hotplug), or never being able to acquire in the

             * first place (hotplug followed by immediate unplug).

             */

            drc->awaiting_allocation_skippable = true;

            return RTAS_OUT_NO_SUCH_INDICATOR;

        }

    }

    if (drc->type != SPAPR_DR_CONNECTOR_TYPE_PCI) {

        drc->allocation_state = state;

        if (drc->awaiting_release &&

            drc->allocation_state == SPAPR_DR_ALLOCATION_STATE_UNUSABLE) {

            trace_spapr_drc_set_allocation_state_finalizing(get_index(drc));

            drck->detach(drc, DEVICE(drc->dev), drc->detach_cb,

                         drc->detach_cb_opaque, NULL);

        } else if (drc->allocation_state == SPAPR_DR_ALLOCATION_STATE_USABLE) {

            drc->awaiting_allocation = false;

        }

    }

    return RTAS_OUT_SUCCESS;

}


static void vfio_pci_reset_handler(void *opaque)

{

    VFIOGroup *group;

    VFIOPCIDevice *vdev;

    QLIST_FOREACH(group, &group_list, next) {

        QLIST_FOREACH(vdev, &group->device_list, next) {

            if (!vdev->reset_works || (!vdev->has_flr && vdev->has_pm_reset)) {

                vdev->needs_reset = true;

            }

        }

    }

    QLIST_FOREACH(group, &group_list, next) {

        QLIST_FOREACH(vdev, &group->device_list, next) {

            if (vdev->needs_reset) {

                vfio_pci_hot_reset_multi(vdev);

            }

        }

    }

}


static void virt_machine_class_init(ObjectClass *oc, void *data)

{

    MachineClass *mc = MACHINE_CLASS(oc);

    mc->init = machvirt_init;

    /* Start max_cpus at the maximum QEMU supports. We'll further restrict

     * it later in machvirt_init, where we have more information about the

     * configuration of the particular instance.

     */

    mc->max_cpus = MAX_CPUMASK_BITS;

    mc->has_dynamic_sysbus = true;

    mc->block_default_type = IF_VIRTIO;

    mc->no_cdrom = 1;

    mc->pci_allow_0_address = true;

}


static void xtensa_lx60_init(MachineState *machine)

{

    static const LxBoardDesc lx60_board = {

        .flash_base = 0xf8000000,

        .flash_size = 0x00400000,

        .flash_sector_size = 0x10000,

        .sram_size = 0x20000,

    };

    lx_init(&lx60_board, machine);

}


int udp_output2(struct socket *so, struct mbuf *m,

                struct sockaddr_in *saddr, struct sockaddr_in *daddr,

                int iptos)

{

	register struct udpiphdr *ui;

	int error = 0;

	DEBUG_CALL("udp_output");

	DEBUG_ARG("so = %p", so);

	DEBUG_ARG("m = %p", m);

	DEBUG_ARG("saddr = %lx", (long)saddr->sin_addr.s_addr);

	DEBUG_ARG("daddr = %lx", (long)daddr->sin_addr.s_addr);

	/*

	 * Adjust for header

	 */

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

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

	/*

	 * Fill in mbuf with extended UDP header

	 * and addresses and length put into network format.

	 */

	ui = mtod(m, struct udpiphdr *);

    memset(&ui->ui_i.ih_mbuf, 0 , sizeof(struct mbuf_ptr));

	ui->ui_x1 = 0;

	ui->ui_pr = IPPROTO_UDP;

	ui->ui_len = htons(m->m_len - sizeof(struct ip));

	/* XXXXX Check for from-one-location sockets, or from-any-location sockets */

        ui->ui_src = saddr->sin_addr;

	ui->ui_dst = daddr->sin_addr;

	ui->ui_sport = saddr->sin_port;

	ui->ui_dport = daddr->sin_port;

	ui->ui_ulen = ui->ui_len;

	/*

	 * Stuff checksum and output datagram.

	 */

	ui->ui_sum = 0;

	if ((ui->ui_sum = cksum(m, m->m_len)) == 0)

		ui->ui_sum = 0xffff;

	((struct ip *)ui)->ip_len = m->m_len;

	((struct ip *)ui)->ip_ttl = IPDEFTTL;

	((struct ip *)ui)->ip_tos = iptos;

	error = ip_output(so, m);

	return (error);

}


static void sigp_initial_cpu_reset(CPUState *cs, run_on_cpu_data arg)

{

    S390CPU *cpu = S390_CPU(cs);

    S390CPUClass *scc = S390_CPU_GET_CLASS(cpu);

    SigpInfo *si = arg.host_ptr;

    cpu_synchronize_state(cs);

    scc->initial_cpu_reset(cs);

    cpu_synchronize_post_reset(cs);

    si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;

}


void cris_cpu_list(FILE *f, int (*cpu_fprintf)(FILE *f, const char *fmt, ...))

{

    unsigned int i;

    (*cpu_fprintf)(f, "Available CPUs:\n");

    for (i = 0; i < ARRAY_SIZE(cris_cores); i++) {

        (*cpu_fprintf)(f, "  %s\n", cris_cores[i].name);

    }

}


void GCC_FMT_ATTR(2, 3) virtio_error(VirtIODevice *vdev, const char *fmt, ...)

{

    va_list ap;

    va_start(ap, fmt);

    error_vreport(fmt, ap);

    va_end(ap);

    vdev->broken = true;

    if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {

        virtio_set_status(vdev, vdev->status | VIRTIO_CONFIG_S_NEEDS_RESET);

        virtio_notify_config(vdev);

    }

}


const char *avcodec_configuration(void)

{

    return FFMPEG_CONFIGURATION;

}


av_cold void ff_ps_ctx_init(PSContext *ps)

{

    ipdopd_reset(ps->ipd_hist, ps->opd_hist);

}


void omap_mpuio_key(struct omap_mpuio_s *s, int row, int col, int down)

{

    if (row >= 5 || row < 0)

        hw_error("%s: No key %i-%i\n", __FUNCTION__, col, row);

    if (down)

        s->buttons[row] |= 1 << col;

    else

        s->buttons[row] &= ~(1 << col);

    omap_mpuio_kbd_update(s);

}


int ff_put_wav_header(AVIOContext *pb, AVCodecContext *enc)

{

    int bps, blkalign, bytespersec;

    int hdrsize = 18;

    int waveformatextensible;

    uint8_t temp[256];

    uint8_t *riff_extradata= temp;

    uint8_t *riff_extradata_start= temp;

    if(!enc->codec_tag || enc->codec_tag > 0xffff)

        return -1;

    waveformatextensible =   (enc->channels > 2 && enc->channel_layout)

                          || enc->sample_rate > 48000

                          || av_get_bits_per_sample(enc->codec_id) > 16;

    if (waveformatextensible) {

        avio_wl16(pb, 0xfffe);

    } else {

        avio_wl16(pb, enc->codec_tag);

    }

    avio_wl16(pb, enc->channels);

    avio_wl32(pb, enc->sample_rate);

    if (enc->codec_id == CODEC_ID_MP2 || enc->codec_id == CODEC_ID_MP3 || enc->codec_id == CODEC_ID_GSM_MS) {

        bps = 0;

    } else if (enc->codec_id == CODEC_ID_ADPCM_G726) {

        bps = 4;

    } else {

        if (!(bps = av_get_bits_per_sample(enc->codec_id)))

            bps = 16; // default to 16

    }

    if(bps != enc->bits_per_coded_sample && enc->bits_per_coded_sample){

        av_log(enc, AV_LOG_WARNING, "requested bits_per_coded_sample (%d) and actually stored (%d) differ\n", enc->bits_per_coded_sample, bps);

    }

    if (enc->codec_id == CODEC_ID_MP2 || enc->codec_id == CODEC_ID_MP3) {

        blkalign = enc->frame_size; //this is wrong, but it seems many demuxers do not work if this is set correctly

        //blkalign = 144 * enc->bit_rate/enc->sample_rate;

    } else if (enc->codec_id == CODEC_ID_AC3) {

            blkalign = 3840; //maximum bytes per frame

    } else if (enc->codec_id == CODEC_ID_ADPCM_G726) { //

        blkalign = 1;

    } else if (enc->block_align != 0) { /* specified by the codec */

        blkalign = enc->block_align;

    } else

        blkalign = enc->channels*bps >> 3;

    if (enc->codec_id == CODEC_ID_PCM_U8 ||

        enc->codec_id == CODEC_ID_PCM_S24LE ||

        enc->codec_id == CODEC_ID_PCM_S32LE ||

        enc->codec_id == CODEC_ID_PCM_F32LE ||

        enc->codec_id == CODEC_ID_PCM_F64LE ||

        enc->codec_id == CODEC_ID_PCM_S16LE) {

        bytespersec = enc->sample_rate * blkalign;

    } else {

        bytespersec = enc->bit_rate / 8;

    }

    avio_wl32(pb, bytespersec); /* bytes per second */

    avio_wl16(pb, blkalign); /* block align */

    avio_wl16(pb, bps); /* bits per sample */

    if (enc->codec_id == CODEC_ID_MP3) {

        hdrsize += 12;

        bytestream_put_le16(&riff_extradata, 1);    /* wID */

        bytestream_put_le32(&riff_extradata, 2);    /* fdwFlags */

        bytestream_put_le16(&riff_extradata, 1152); /* nBlockSize */

        bytestream_put_le16(&riff_extradata, 1);    /* nFramesPerBlock */

        bytestream_put_le16(&riff_extradata, 1393); /* nCodecDelay */

    } else if (enc->codec_id == CODEC_ID_MP2) {

        hdrsize += 22;

        bytestream_put_le16(&riff_extradata, 2);                          /* fwHeadLayer */

        bytestream_put_le32(&riff_extradata, enc->bit_rate);              /* dwHeadBitrate */

        bytestream_put_le16(&riff_extradata, enc->channels == 2 ? 1 : 8); /* fwHeadMode */

        bytestream_put_le16(&riff_extradata, 0);                          /* fwHeadModeExt */

        bytestream_put_le16(&riff_extradata, 1);                          /* wHeadEmphasis */

        bytestream_put_le16(&riff_extradata, 16);                         /* fwHeadFlags */

        bytestream_put_le32(&riff_extradata, 0);                          /* dwPTSLow */

        bytestream_put_le32(&riff_extradata, 0);                          /* dwPTSHigh */

    } else if (enc->codec_id == CODEC_ID_GSM_MS || enc->codec_id == CODEC_ID_ADPCM_IMA_WAV) {

        hdrsize += 2;

        bytestream_put_le16(&riff_extradata, enc->frame_size); /* wSamplesPerBlock */

    } else if(enc->extradata_size){

        riff_extradata_start= enc->extradata;

        riff_extradata= enc->extradata + enc->extradata_size;

        hdrsize += enc->extradata_size;

    } else if (!waveformatextensible){

        hdrsize -= 2;

    }

    if(waveformatextensible) {                                    /* write WAVEFORMATEXTENSIBLE extensions */

        hdrsize += 22;

        avio_wl16(pb, riff_extradata - riff_extradata_start + 22); /* 22 is WAVEFORMATEXTENSIBLE size */

        avio_wl16(pb, enc->bits_per_coded_sample);                 /* ValidBitsPerSample || SamplesPerBlock || Reserved */

        avio_wl32(pb, enc->channel_layout);                        /* dwChannelMask */

        avio_wl32(pb, enc->codec_tag);                             /* GUID + next 3 */

        avio_wl32(pb, 0x00100000);

        avio_wl32(pb, 0xAA000080);

        avio_wl32(pb, 0x719B3800);

    } else if(riff_extradata - riff_extradata_start) {

        avio_wl16(pb, riff_extradata - riff_extradata_start);

    }

    avio_write(pb, riff_extradata_start, riff_extradata - riff_extradata_start);

    if(hdrsize&1){

        hdrsize++;

        avio_w8(pb, 0);

    }

    return hdrsize;

}


static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)

{

    CPUState *cpu = current_cpu;

    CPUClass *cc = CPU_GET_CLASS(cpu);

    CPUArchState *env = cpu->env_ptr;

    target_ulong pc, cs_base;

    target_ulong vaddr;

    CPUWatchpoint *wp;

    uint32_t cpu_flags;

    assert(tcg_enabled());

    if (cpu->watchpoint_hit) {

        /* We re-entered the check after replacing the TB. Now raise

         * the debug interrupt so that is will trigger after the

         * current instruction. */

        cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);

        return;

    }

    vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;

    vaddr = cc->adjust_watchpoint_address(cpu, vaddr, len);

    QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {

        if (cpu_watchpoint_address_matches(wp, vaddr, len)

            && (wp->flags & flags)) {

            if (flags == BP_MEM_READ) {

                wp->flags |= BP_WATCHPOINT_HIT_READ;

            } else {

                wp->flags |= BP_WATCHPOINT_HIT_WRITE;

            }

            wp->hitaddr = vaddr;

            wp->hitattrs = attrs;

            if (!cpu->watchpoint_hit) {

                if (wp->flags & BP_CPU &&

                    !cc->debug_check_watchpoint(cpu, wp)) {

                    wp->flags &= ~BP_WATCHPOINT_HIT;

                    continue;

                }

                cpu->watchpoint_hit = wp;

                /* Both tb_lock and iothread_mutex will be reset when

                 * cpu_loop_exit or cpu_loop_exit_noexc longjmp

                 * back into the cpu_exec main loop.

                 */

                tb_lock();

                tb_check_watchpoint(cpu);

                if (wp->flags & BP_STOP_BEFORE_ACCESS) {

                    cpu->exception_index = EXCP_DEBUG;

                    cpu_loop_exit(cpu);

                } else {

                    cpu_get_tb_cpu_state(env, &pc, &cs_base, &cpu_flags);

                    tb_gen_code(cpu, pc, cs_base, cpu_flags, 1 | curr_cflags());

                    cpu_loop_exit_noexc(cpu);

                }

            }

        } else {

            wp->flags &= ~BP_WATCHPOINT_HIT;

        }

    }

}


dbdma_control_write(DBDMA_channel *ch)

{

    uint16_t mask, value;

    uint32_t status;

    mask = (ch->regs[DBDMA_CONTROL] >> 16) & 0xffff;

    value = ch->regs[DBDMA_CONTROL] & 0xffff;

    value &= (RUN | PAUSE | FLUSH | WAKE | DEVSTAT);

    status = ch->regs[DBDMA_STATUS];

    status = (value & mask) | (status & ~mask);

    if (status & WAKE)

        status |= ACTIVE;

    if (status & RUN) {

        status |= ACTIVE;

        status &= ~DEAD;

    }

    if (status & PAUSE)

        status &= ~ACTIVE;

    if ((ch->regs[DBDMA_STATUS] & RUN) && !(status & RUN)) {

        /* RUN is cleared */

        status &= ~(ACTIVE|DEAD);

    }

    DBDMA_DPRINTF("    status 0x%08x\n", status);

    ch->regs[DBDMA_STATUS] = status;

    if (status & ACTIVE)

        qemu_bh_schedule(dbdma_bh);

    if (status & FLUSH)

        ch->flush(&ch->io);

}


static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,

                               int access_type, ARMMMUIdx mmu_idx,

                               hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,

                               target_ulong *page_size_ptr, uint32_t *fsr,

                               ARMMMUFaultInfo *fi)

{

    ARMCPU *cpu = arm_env_get_cpu(env);

    CPUState *cs = CPU(cpu);

    /* Read an LPAE long-descriptor translation table. */

    MMUFaultType fault_type = translation_fault;

    uint32_t level;

    uint32_t epd = 0;

    int32_t t0sz, t1sz;

    uint32_t tg;

    uint64_t ttbr;

    int ttbr_select;

    hwaddr descaddr, indexmask, indexmask_grainsize;

    uint32_t tableattrs;

    target_ulong page_size;

    uint32_t attrs;

    int32_t stride = 9;

    int32_t va_size;

    int inputsize;

    int32_t tbi = 0;

    TCR *tcr = regime_tcr(env, mmu_idx);

    int ap, ns, xn, pxn;

    uint32_t el = regime_el(env, mmu_idx);

    bool ttbr1_valid = true;

    uint64_t descaddrmask;

    /* TODO:

     * This code does not handle the different format TCR for VTCR_EL2.

     * This code also does not support shareability levels.

     * Attribute and permission bit handling should also be checked when adding

     * support for those page table walks.

     */

    if (arm_el_is_aa64(env, el)) {

        level = 0;

        va_size = 64;

        if (el > 1) {

            if (mmu_idx != ARMMMUIdx_S2NS) {

                tbi = extract64(tcr->raw_tcr, 20, 1);

            }

        } else {

            if (extract64(address, 55, 1)) {

                tbi = extract64(tcr->raw_tcr, 38, 1);

            } else {

                tbi = extract64(tcr->raw_tcr, 37, 1);

            }

        }

        tbi *= 8;

        /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it

         * invalid.

         */

        if (el > 1) {

            ttbr1_valid = false;

        }

    } else {

        level = 1;

        va_size = 32;

        /* There is no TTBR1 for EL2 */

        if (el == 2) {

            ttbr1_valid = false;

        }

    }

    /* Determine whether this address is in the region controlled by

     * TTBR0 or TTBR1 (or if it is in neither region and should fault).

     * This is a Non-secure PL0/1 stage 1 translation, so controlled by

     * TTBCR/TTBR0/TTBR1 in accordance with ARM ARM DDI0406C table B-32:

     */

    if (va_size == 64) {

        /* AArch64 translation.  */

        t0sz = extract32(tcr->raw_tcr, 0, 6);

        t0sz = MIN(t0sz, 39);

        t0sz = MAX(t0sz, 16);

    } else if (mmu_idx != ARMMMUIdx_S2NS) {

        /* AArch32 stage 1 translation.  */

        t0sz = extract32(tcr->raw_tcr, 0, 3);

    } else {

        /* AArch32 stage 2 translation.  */

        bool sext = extract32(tcr->raw_tcr, 4, 1);

        bool sign = extract32(tcr->raw_tcr, 3, 1);

        t0sz = sextract32(tcr->raw_tcr, 0, 4);

        /* If the sign-extend bit is not the same as t0sz[3], the result

         * is unpredictable. Flag this as a guest error.  */

        if (sign != sext) {

            qemu_log_mask(LOG_GUEST_ERROR,

                          "AArch32: VTCR.S / VTCR.T0SZ[3] missmatch\n");

        }

    }

    t1sz = extract32(tcr->raw_tcr, 16, 6);

    if (va_size == 64) {

        t1sz = MIN(t1sz, 39);

        t1sz = MAX(t1sz, 16);

    }

    if (t0sz && !extract64(address, va_size - t0sz, t0sz - tbi)) {

        /* there is a ttbr0 region and we are in it (high bits all zero) */

        ttbr_select = 0;

    } else if (ttbr1_valid && t1sz &&

               !extract64(~address, va_size - t1sz, t1sz - tbi)) {

        /* there is a ttbr1 region and we are in it (high bits all one) */

        ttbr_select = 1;

    } else if (!t0sz) {

        /* ttbr0 region is "everything not in the ttbr1 region" */

        ttbr_select = 0;

    } else if (!t1sz && ttbr1_valid) {

        /* ttbr1 region is "everything not in the ttbr0 region" */

        ttbr_select = 1;

    } else {

        /* in the gap between the two regions, this is a Translation fault */

        fault_type = translation_fault;

        goto do_fault;

    }

    /* Note that QEMU ignores shareability and cacheability attributes,

     * so we don't need to do anything with the SH, ORGN, IRGN fields

     * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the

     * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently

     * implement any ASID-like capability so we can ignore it (instead

     * we will always flush the TLB any time the ASID is changed).

     */

    if (ttbr_select == 0) {

        ttbr = regime_ttbr(env, mmu_idx, 0);

        if (el < 2) {

            epd = extract32(tcr->raw_tcr, 7, 1);

        }

        inputsize = va_size - t0sz;

        tg = extract32(tcr->raw_tcr, 14, 2);

        if (tg == 1) { /* 64KB pages */

            stride = 13;

        }

        if (tg == 2) { /* 16KB pages */

            stride = 11;

        }

    } else {

        /* We should only be here if TTBR1 is valid */

        assert(ttbr1_valid);

        ttbr = regime_ttbr(env, mmu_idx, 1);

        epd = extract32(tcr->raw_tcr, 23, 1);

        inputsize = va_size - t1sz;

        tg = extract32(tcr->raw_tcr, 30, 2);

        if (tg == 3)  { /* 64KB pages */

            stride = 13;

        }

        if (tg == 1) { /* 16KB pages */

            stride = 11;

        }

    }

    /* Here we should have set up all the parameters for the translation:

     * va_size, inputsize, ttbr, epd, stride, tbi

     */

    if (epd) {

        /* Translation table walk disabled => Translation fault on TLB miss

         * Note: This is always 0 on 64-bit EL2 and EL3.

         */

        goto do_fault;

    }

    if (mmu_idx != ARMMMUIdx_S2NS) {

        /* The starting level depends on the virtual address size (which can

         * be up to 48 bits) and the translation granule size. It indicates

         * the number of strides (stride bits at a time) needed to

         * consume the bits of the input address. In the pseudocode this is:

         *  level = 4 - RoundUp((inputsize - grainsize) / stride)

         * where their 'inputsize' is our 'inputsize', 'grainsize' is

         * our 'stride + 3' and 'stride' is our 'stride'.

         * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:

         * = 4 - (inputsize - stride - 3 + stride - 1) / stride

         * = 4 - (inputsize - 4) / stride;

         */

        level = 4 - (inputsize - 4) / stride;

    } else {

        /* For stage 2 translations the starting level is specified by the

         * VTCR_EL2.SL0 field (whose interpretation depends on the page size)

         */

        uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);

        uint32_t startlevel;

        bool ok;

        if (va_size == 32 || stride == 9) {

            /* AArch32 or 4KB pages */

            startlevel = 2 - sl0;

        } else {

            /* 16KB or 64KB pages */

            startlevel = 3 - sl0;

        }

        /* Check that the starting level is valid. */

        ok = check_s2_mmu_setup(cpu, va_size == 64, startlevel,

                                inputsize, stride);

        if (!ok) {

            fault_type = translation_fault;

            goto do_fault;

        }

        level = startlevel;

    }

    indexmask_grainsize = (1ULL << (stride + 3)) - 1;

    indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;

    /* Now we can extract the actual base address from the TTBR */

    descaddr = extract64(ttbr, 0, 48);

    descaddr &= ~indexmask;

    /* The address field in the descriptor goes up to bit 39 for ARMv7

     * but up to bit 47 for ARMv8, but we use the descaddrmask

     * up to bit 39 for AArch32, because we don't need other bits in that case

     * to construct next descriptor address (anyway they should be all zeroes).

     */

    descaddrmask = ((1ull << (va_size == 64 ? 48 : 40)) - 1) &

                   ~indexmask_grainsize;

    /* Secure accesses start with the page table in secure memory and

     * can be downgraded to non-secure at any step. Non-secure accesses

     * remain non-secure. We implement this by just ORing in the NSTable/NS

     * bits at each step.

     */

    tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);

    for (;;) {

        uint64_t descriptor;

        bool nstable;

        descaddr |= (address >> (stride * (4 - level))) & indexmask;

        descaddr &= ~7ULL;

        nstable = extract32(tableattrs, 4, 1);

        descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fsr, fi);

        if (fi->s1ptw) {

            goto do_fault;

        }

        if (!(descriptor & 1) ||

            (!(descriptor & 2) && (level == 3))) {

            /* Invalid, or the Reserved level 3 encoding */

            goto do_fault;

        }

        descaddr = descriptor & descaddrmask;

        if ((descriptor & 2) && (level < 3)) {

            /* Table entry. The top five bits are attributes which  may

             * propagate down through lower levels of the table (and

             * which are all arranged so that 0 means "no effect", so

             * we can gather them up by ORing in the bits at each level).

             */

            tableattrs |= extract64(descriptor, 59, 5);

            level++;

            indexmask = indexmask_grainsize;

            continue;

        }

        /* Block entry at level 1 or 2, or page entry at level 3.

         * These are basically the same thing, although the number

         * of bits we pull in from the vaddr varies.

         */

        page_size = (1ULL << ((stride * (4 - level)) + 3));

        descaddr |= (address & (page_size - 1));

        /* Extract attributes from the descriptor */

        attrs = extract64(descriptor, 2, 10)

            | (extract64(descriptor, 52, 12) << 10);

        if (mmu_idx == ARMMMUIdx_S2NS) {

            /* Stage 2 table descriptors do not include any attribute fields */

            break;

        }

        /* Merge in attributes from table descriptors */

        attrs |= extract32(tableattrs, 0, 2) << 11; /* XN, PXN */

        attrs |= extract32(tableattrs, 3, 1) << 5; /* APTable[1] => AP[2] */

        /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1

         * means "force PL1 access only", which means forcing AP[1] to 0.

         */

        if (extract32(tableattrs, 2, 1)) {

            attrs &= ~(1 << 4);

        }

        attrs |= nstable << 3; /* NS */

        break;

    }

    /* Here descaddr is the final physical address, and attributes

     * are all in attrs.

     */

    fault_type = access_fault;

    if ((attrs & (1 << 8)) == 0) {

        /* Access flag */

        goto do_fault;

    }

    ap = extract32(attrs, 4, 2);

    xn = extract32(attrs, 12, 1);

    if (mmu_idx == ARMMMUIdx_S2NS) {

        ns = true;

        *prot = get_S2prot(env, ap, xn);

    } else {

        ns = extract32(attrs, 3, 1);

        pxn = extract32(attrs, 11, 1);

        *prot = get_S1prot(env, mmu_idx, va_size == 64, ap, ns, xn, pxn);

    }

    fault_type = permission_fault;

    if (!(*prot & (1 << access_type))) {

        goto do_fault;

    }

    if (ns) {

        /* The NS bit will (as required by the architecture) have no effect if

         * the CPU doesn't support TZ or this is a non-secure translation

         * regime, because the attribute will already be non-secure.

         */

        txattrs->secure = false;

    }

    *phys_ptr = descaddr;

    *page_size_ptr = page_size;

    return false;

do_fault:

    /* Long-descriptor format IFSR/DFSR value */

    *fsr = (1 << 9) | (fault_type << 2) | level;

    /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */

    fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);

    return true;

}


static void monitor_parse(const char *optarg, const char *mode, bool pretty)

{

    static int monitor_device_index = 0;

    Error *local_err = NULL;

    QemuOpts *opts;

    const char *p;

    char label[32];

    int def = 0;

    if (strstart(optarg, "chardev:", &p)) {

        snprintf(label, sizeof(label), "%s", p);

    } else {

        snprintf(label, sizeof(label), "compat_monitor%d",

                 monitor_device_index);

        if (monitor_device_index == 0) {

            def = 1;

        }

        opts = qemu_chr_parse_compat(label, optarg);

        if (!opts) {

            fprintf(stderr, "parse error: %s\n", optarg);

            exit(1);

        }

    }

    opts = qemu_opts_create(qemu_find_opts("mon"), label, 1, &local_err);

    if (!opts) {

        error_report_err(local_err);

        exit(1);

    }

    qemu_opt_set(opts, "mode", mode, &error_abort);

    qemu_opt_set(opts, "chardev", label, &error_abort);

    qemu_opt_set_bool(opts, "pretty", pretty, &error_abort);

    if (def)

        qemu_opt_set(opts, "default", "on", &error_abort);

    monitor_device_index++;

}


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

{

    int dom, pci_bus;

    unsigned slot;

    int type, bus;

    int success = 0;

    PCIDevice *dev;

    DriveInfo *dinfo;

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

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

    BusState *scsibus;

    if (pci_read_devaddr(mon, pci_addr, &dom, &pci_bus, &slot)) {

        return;

    }

    dev = pci_find_device(pci_bus, slot, 0);

    if (!dev) {

        monitor_printf(mon, "no pci device with address %s\n", pci_addr);

        return;

    }

    dinfo = add_init_drive(opts);

    if (!dinfo)

        return;

    if (dinfo->devaddr) {

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

        return;

    }

    type = dinfo->type;

    bus = drive_get_max_bus (type);

    switch (type) {

    case IF_SCSI:

        success = 1;

        scsibus = LIST_FIRST(&dev->qdev.child_bus);

        scsi_bus_legacy_add_drive(DO_UPCAST(SCSIBus, qbus, scsibus),

                                  dinfo, dinfo->unit);

        break;

    default:

        monitor_printf(mon, "Can't hot-add drive to type %d\n", type);

    }

    if (success)

        monitor_printf(mon, "OK bus %d, unit %d\n",

                       dinfo->bus,

                       dinfo->unit);

    return;

}


build_append_notify(GArray *device, const char *name,

                    const char *format, int skip, int count)

{

    int i;

    GArray *method = build_alloc_array();

    uint8_t op = 0x14; /* MethodOp */

    build_append_nameseg(method, "%s", name);

    build_append_byte(method, 0x02); /* MethodFlags: ArgCount */

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

        GArray *target = build_alloc_array();

        build_append_nameseg(target, format, i);

        assert(i < 256); /* Fits in 1 byte */

        build_append_notify_target(method, target, i, 1);

        build_free_array(target);

    }

    build_package(method, op, 2);

    build_append_array(device, method);

    build_free_array(method);

}


void virtio_input_send(VirtIOInput *vinput, virtio_input_event *event)

{

    VirtQueueElement *elem;

    unsigned have, need;

    int i, len;

    if (!vinput->active) {

        return;

    }

    /* queue up events ... */

    if (vinput->qindex == vinput->qsize) {

        vinput->qsize++;

        vinput->queue = g_realloc(vinput->queue, vinput->qsize *

                                  sizeof(virtio_input_event));

    }

    vinput->queue[vinput->qindex++] = *event;

    /* ... until we see a report sync ... */

    if (event->type != cpu_to_le16(EV_SYN) ||

        event->code != cpu_to_le16(SYN_REPORT)) {

        return;

    }

    /* ... then check available space ... */

    need = sizeof(virtio_input_event) * vinput->qindex;

    virtqueue_get_avail_bytes(vinput->evt, &have, NULL, need, 0);

    if (have < need) {

        vinput->qindex = 0;

        trace_virtio_input_queue_full();

        return;

    }

    /* ... and finally pass them to the guest */

    for (i = 0; i < vinput->qindex; i++) {

        elem = virtqueue_pop(vinput->evt, sizeof(VirtQueueElement));

        if (!elem) {

            /* should not happen, we've checked for space beforehand */

            fprintf(stderr, "%s: Huh?  No vq elem available ...\n", __func__);

            return;

        }

        len = iov_from_buf(elem->in_sg, elem->in_num,

                           0, vinput->queue+i, sizeof(virtio_input_event));

        virtqueue_push(vinput->evt, elem, len);

        g_free(elem);

    }

    virtio_notify(VIRTIO_DEVICE(vinput), vinput->evt);

    vinput->qindex = 0;

}


int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)

{

    MultiwriteCB *mcb;

    int i;

    /* don't submit writes if we don't have a medium */

    if (bs->drv == NULL) {

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

            reqs[i].error = -ENOMEDIUM;

        }

        return -1;

    }

    if (num_reqs == 0) {

        return 0;

    }

    // Create MultiwriteCB structure

    mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));

    mcb->num_requests = 0;

    mcb->num_callbacks = num_reqs;

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

        mcb->callbacks[i].cb = reqs[i].cb;

        mcb->callbacks[i].opaque = reqs[i].opaque;

    }

    // Check for mergable requests

    num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);

    trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);

    /* Run the aio requests. */

    mcb->num_requests = num_reqs;

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

        bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov,

                              reqs[i].nb_sectors, reqs[i].flags,

                              multiwrite_cb, mcb,

                              true);

    }

    return 0;

}


static void omap_sti_fifo_write(void *opaque, target_phys_addr_t addr,

                                uint64_t value, unsigned size)

{

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

    int ch = addr >> 6;

    uint8_t byte = value;

    if (size != 1) {

        return omap_badwidth_write8(opaque, addr, size);

    }

    if (ch == STI_TRACE_CONTROL_CHANNEL) {

        /* Flush channel value.  */

        qemu_chr_fe_write(s->chr, (const uint8_t *) "\r", 1);

    } else if (ch == STI_TRACE_CONSOLE_CHANNEL || 1) {

        if (value == 0xc0 || value == 0xc3) {

            /* Open channel ch.  */

        } else if (value == 0x00)

            qemu_chr_fe_write(s->chr, (const uint8_t *) "\n", 1);

        else

            qemu_chr_fe_write(s->chr, &byte, 1);

    }

}


static void active_parameter_sets(HEVCContext *s)

{

    GetBitContext *gb = &s->HEVClc->gb;

    int num_sps_ids_minus1;

    int i;

    get_bits(gb, 4); // active_video_parameter_set_id

    get_bits(gb, 1); // self_contained_cvs_flag

    get_bits(gb, 1); // num_sps_ids_minus1

    num_sps_ids_minus1 = get_ue_golomb_long(gb); // num_sps_ids_minus1

    s->active_seq_parameter_set_id = get_ue_golomb_long(gb);

    for (i = 1; i <= num_sps_ids_minus1; i++)

        get_ue_golomb_long(gb); // active_seq_parameter_set_id[i]

}


static void term_backward_char(void)

{

    if (term_cmd_buf_index > 0) {

        term_cmd_buf_index--;

    }

}


static int omap_validate_tipb_mpui_addr(struct omap_mpu_state_s *s,

                target_phys_addr_t addr)

{

    return range_covers_byte(0xe1010000, 0xe1020004 - 0xe1010000, addr);

}


static void notdirty_mem_writeb(void *opaque, target_phys_addr_t ram_addr,

                                uint32_t val)

{

    int dirty_flags;

    dirty_flags = phys_ram_dirty[ram_addr >> TARGET_PAGE_BITS];

    if (!(dirty_flags & CODE_DIRTY_FLAG)) {

#if !defined(CONFIG_USER_ONLY)

        tb_invalidate_phys_page_fast(ram_addr, 1);

        dirty_flags = phys_ram_dirty[ram_addr >> TARGET_PAGE_BITS];

#endif

    }

    stb_p(qemu_get_ram_ptr(ram_addr), val);

#ifdef CONFIG_KQEMU

    if (cpu_single_env->kqemu_enabled &&

        (dirty_flags & KQEMU_MODIFY_PAGE_MASK) != KQEMU_MODIFY_PAGE_MASK)

        kqemu_modify_page(cpu_single_env, ram_addr);

#endif

    dirty_flags |= (0xff & ~CODE_DIRTY_FLAG);

    phys_ram_dirty[ram_addr >> TARGET_PAGE_BITS] = dirty_flags;

    /* we remove the notdirty callback only if the code has been

       flushed */

    if (dirty_flags == 0xff)

        tlb_set_dirty(cpu_single_env, cpu_single_env->mem_io_vaddr);

}


BlockJob *backup_job_create(const char *job_id, BlockDriverState *bs,

                  BlockDriverState *target, int64_t speed,

                  MirrorSyncMode sync_mode, BdrvDirtyBitmap *sync_bitmap,

                  bool compress,

                  BlockdevOnError on_source_error,

                  BlockdevOnError on_target_error,

                  int creation_flags,

                  BlockCompletionFunc *cb, void *opaque,

                  BlockJobTxn *txn, Error **errp)

{

    int64_t len;

    BlockDriverInfo bdi;

    BackupBlockJob *job = NULL;

    int ret;

    assert(bs);

    assert(target);

    if (bs == target) {

        error_setg(errp, "Source and target cannot be the same");

        return NULL;

    }

    if (!bdrv_is_inserted(bs)) {

        error_setg(errp, "Device is not inserted: %s",

                   bdrv_get_device_name(bs));

        return NULL;

    }

    if (!bdrv_is_inserted(target)) {

        error_setg(errp, "Device is not inserted: %s",

                   bdrv_get_device_name(target));

        return NULL;

    }

    if (compress && target->drv->bdrv_co_pwritev_compressed == NULL) {

        error_setg(errp, "Compression is not supported for this drive %s",

                   bdrv_get_device_name(target));

        return NULL;

    }

    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {

        return NULL;

    }

    if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_BACKUP_TARGET, errp)) {

        return NULL;

    }

    if (sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {

        if (!sync_bitmap) {

            error_setg(errp, "must provide a valid bitmap name for "

                             "\"incremental\" sync mode");

            return NULL;

        }

        /* Create a new bitmap, and freeze/disable this one. */

        if (bdrv_dirty_bitmap_create_successor(bs, sync_bitmap, errp) < 0) {

            return NULL;

        }

    } else if (sync_bitmap) {

        error_setg(errp,

                   "a sync_bitmap was provided to backup_run, "

                   "but received an incompatible sync_mode (%s)",

                   MirrorSyncMode_lookup[sync_mode]);

        return NULL;

    }

    len = bdrv_getlength(bs);

    if (len < 0) {

        error_setg_errno(errp, -len, "unable to get length for '%s'",

                         bdrv_get_device_name(bs));

        goto error;

    }

    /* job->common.len is fixed, so we can't allow resize */

    job = block_job_create(job_id, &backup_job_driver, bs,

                           BLK_PERM_CONSISTENT_READ,

                           BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE |

                           BLK_PERM_WRITE_UNCHANGED | BLK_PERM_GRAPH_MOD,

                           speed, creation_flags, cb, opaque, errp);

    if (!job) {

        goto error;

    }

    /* The target must match the source in size, so no resize here either */

    job->target = blk_new(BLK_PERM_WRITE,

                          BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE |

                          BLK_PERM_WRITE_UNCHANGED | BLK_PERM_GRAPH_MOD);

    ret = blk_insert_bs(job->target, target, errp);

    if (ret < 0) {

        goto error;

    }

    job->on_source_error = on_source_error;

    job->on_target_error = on_target_error;

    job->sync_mode = sync_mode;

    job->sync_bitmap = sync_mode == MIRROR_SYNC_MODE_INCREMENTAL ?

                       sync_bitmap : NULL;

    job->compress = compress;

    /* If there is no backing file on the target, we cannot rely on COW if our

     * backup cluster size is smaller than the target cluster size. Even for

     * targets with a backing file, try to avoid COW if possible. */

    ret = bdrv_get_info(target, &bdi);

    if (ret == -ENOTSUP && !target->backing) {

        /* Cluster size is not defined */

        error_report("WARNING: The target block device doesn't provide "

                     "information about the block size and it doesn't have a "

                     "backing file. The default block size of %u bytes is "

                     "used. If the actual block size of the target exceeds "

                     "this default, the backup may be unusable",

                     BACKUP_CLUSTER_SIZE_DEFAULT);

        job->cluster_size = BACKUP_CLUSTER_SIZE_DEFAULT;

    } else if (ret < 0 && !target->backing) {

        error_setg_errno(errp, -ret,

            "Couldn't determine the cluster size of the target image, "

            "which has no backing file");

        error_append_hint(errp,

            "Aborting, since this may create an unusable destination image\n");

        goto error;

    } else if (ret < 0 && target->backing) {

        /* Not fatal; just trudge on ahead. */

        job->cluster_size = BACKUP_CLUSTER_SIZE_DEFAULT;

    } else {

        job->cluster_size = MAX(BACKUP_CLUSTER_SIZE_DEFAULT, bdi.cluster_size);

    }

    /* Required permissions are already taken with target's blk_new() */

    block_job_add_bdrv(&job->common, "target", target, 0, BLK_PERM_ALL,

                       &error_abort);

    job->common.len = len;

    block_job_txn_add_job(txn, &job->common);

    return &job->common;

 error:

    if (sync_bitmap) {

        bdrv_reclaim_dirty_bitmap(bs, sync_bitmap, NULL);

    }

    if (job) {

        backup_clean(&job->common);

        block_job_early_fail(&job->common);

    }

    return NULL;

}


void helper_vmrun(CPUX86State *env, int aflag, int next_eip_addend)

{

    CPUState *cs = CPU(x86_env_get_cpu(env));

    target_ulong addr;

    uint32_t event_inj;

    uint32_t int_ctl;

    cpu_svm_check_intercept_param(env, SVM_EXIT_VMRUN, 0);

    if (aflag == 2) {

        addr = env->regs[R_EAX];

    } else {

        addr = (uint32_t)env->regs[R_EAX];

    }

    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmrun! " TARGET_FMT_lx "\n", addr);

    env->vm_vmcb = addr;

    /* save the current CPU state in the hsave page */

    stq_phys(cs->as, env->vm_hsave + offsetof(struct vmcb, save.gdtr.base),

             env->gdt.base);

    stl_phys(cs->as, env->vm_hsave + offsetof(struct vmcb, save.gdtr.limit),

             env->gdt.limit);

    stq_phys(cs->as, env->vm_hsave + offsetof(struct vmcb, save.idtr.base),

             env->idt.base);

    stl_phys(cs->as, env->vm_hsave + offsetof(struct vmcb, save.idtr.limit),

             env->idt.limit);

    stq_phys(cs->as,

             env->vm_hsave + offsetof(struct vmcb, save.cr0), env->cr[0]);

    stq_phys(cs->as,

             env->vm_hsave + offsetof(struct vmcb, save.cr2), env->cr[2]);

    stq_phys(cs->as,

             env->vm_hsave + offsetof(struct vmcb, save.cr3), env->cr[3]);

    stq_phys(cs->as,

             env->vm_hsave + offsetof(struct vmcb, save.cr4), env->cr[4]);

    stq_phys(cs->as,

             env->vm_hsave + offsetof(struct vmcb, save.dr6), env->dr[6]);

    stq_phys(cs->as,

             env->vm_hsave + offsetof(struct vmcb, save.dr7), env->dr[7]);

    stq_phys(cs->as,

             env->vm_hsave + offsetof(struct vmcb, save.efer), env->efer);

    stq_phys(cs->as,

             env->vm_hsave + offsetof(struct vmcb, save.rflags),

             cpu_compute_eflags(env));

    svm_save_seg(env, env->vm_hsave + offsetof(struct vmcb, save.es),

                 &env->segs[R_ES]);

    svm_save_seg(env, env->vm_hsave + offsetof(struct vmcb, save.cs),

                 &env->segs[R_CS]);

    svm_save_seg(env, env->vm_hsave + offsetof(struct vmcb, save.ss),

                 &env->segs[R_SS]);

    svm_save_seg(env, env->vm_hsave + offsetof(struct vmcb, save.ds),

                 &env->segs[R_DS]);

    stq_phys(cs->as, env->vm_hsave + offsetof(struct vmcb, save.rip),

             env->eip + next_eip_addend);

    stq_phys(cs->as,

             env->vm_hsave + offsetof(struct vmcb, save.rsp), env->regs[R_ESP]);

    stq_phys(cs->as,

             env->vm_hsave + offsetof(struct vmcb, save.rax), env->regs[R_EAX]);

    /* load the interception bitmaps so we do not need to access the

       vmcb in svm mode */

    env->intercept = ldq_phys(cs->as, env->vm_vmcb + offsetof(struct vmcb,

                                                      control.intercept));

    env->intercept_cr_read = lduw_phys(cs->as, env->vm_vmcb +

                                       offsetof(struct vmcb,

                                                control.intercept_cr_read));

    env->intercept_cr_write = lduw_phys(cs->as, env->vm_vmcb +

                                        offsetof(struct vmcb,

                                                 control.intercept_cr_write));

    env->intercept_dr_read = lduw_phys(cs->as, env->vm_vmcb +

                                       offsetof(struct vmcb,

                                                control.intercept_dr_read));

    env->intercept_dr_write = lduw_phys(cs->as, env->vm_vmcb +

                                        offsetof(struct vmcb,

                                                 control.intercept_dr_write));

    env->intercept_exceptions = ldl_phys(cs->as, env->vm_vmcb +

                                         offsetof(struct vmcb,

                                                  control.intercept_exceptions

                                                  ));

    /* enable intercepts */

    env->hflags |= HF_SVMI_MASK;

    env->tsc_offset = ldq_phys(cs->as, env->vm_vmcb +

                               offsetof(struct vmcb, control.tsc_offset));

    env->gdt.base  = ldq_phys(cs->as, env->vm_vmcb + offsetof(struct vmcb,

                                                      save.gdtr.base));

    env->gdt.limit = ldl_phys(cs->as, env->vm_vmcb + offsetof(struct vmcb,

                                                      save.gdtr.limit));

    env->idt.base  = ldq_phys(cs->as, env->vm_vmcb + offsetof(struct vmcb,

                                                      save.idtr.base));

    env->idt.limit = ldl_phys(cs->as, env->vm_vmcb + offsetof(struct vmcb,

                                                      save.idtr.limit));

    /* clear exit_info_2 so we behave like the real hardware */

    stq_phys(cs->as,

             env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2), 0);

    cpu_x86_update_cr0(env, ldq_phys(cs->as,

                                     env->vm_vmcb + offsetof(struct vmcb,

                                                             save.cr0)));

    cpu_x86_update_cr4(env, ldq_phys(cs->as,

                                     env->vm_vmcb + offsetof(struct vmcb,

                                                             save.cr4)));

    cpu_x86_update_cr3(env, ldq_phys(cs->as,

                                     env->vm_vmcb + offsetof(struct vmcb,

                                                             save.cr3)));

    env->cr[2] = ldq_phys(cs->as,

                          env->vm_vmcb + offsetof(struct vmcb, save.cr2));

    int_ctl = ldl_phys(cs->as,

                       env->vm_vmcb + offsetof(struct vmcb, control.int_ctl));

    env->hflags2 &= ~(HF2_HIF_MASK | HF2_VINTR_MASK);

    if (int_ctl & V_INTR_MASKING_MASK) {

        env->v_tpr = int_ctl & V_TPR_MASK;

        env->hflags2 |= HF2_VINTR_MASK;

        if (env->eflags & IF_MASK) {

            env->hflags2 |= HF2_HIF_MASK;

        }

    }

    cpu_load_efer(env,

                  ldq_phys(cs->as,

                           env->vm_vmcb + offsetof(struct vmcb, save.efer)));

    env->eflags = 0;

    cpu_load_eflags(env, ldq_phys(cs->as,

                                  env->vm_vmcb + offsetof(struct vmcb,

                                                          save.rflags)),

                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));

    CC_OP = CC_OP_EFLAGS;

    svm_load_seg_cache(env, env->vm_vmcb + offsetof(struct vmcb, save.es),

                       R_ES);

    svm_load_seg_cache(env, env->vm_vmcb + offsetof(struct vmcb, save.cs),

                       R_CS);

    svm_load_seg_cache(env, env->vm_vmcb + offsetof(struct vmcb, save.ss),

                       R_SS);

    svm_load_seg_cache(env, env->vm_vmcb + offsetof(struct vmcb, save.ds),

                       R_DS);

    env->eip = ldq_phys(cs->as,

                        env->vm_vmcb + offsetof(struct vmcb, save.rip));

    env->regs[R_ESP] = ldq_phys(cs->as,

                                env->vm_vmcb + offsetof(struct vmcb, save.rsp));

    env->regs[R_EAX] = ldq_phys(cs->as,

                                env->vm_vmcb + offsetof(struct vmcb, save.rax));

    env->dr[7] = ldq_phys(cs->as,

                          env->vm_vmcb + offsetof(struct vmcb, save.dr7));

    env->dr[6] = ldq_phys(cs->as,

                          env->vm_vmcb + offsetof(struct vmcb, save.dr6));

    cpu_x86_set_cpl(env, ldub_phys(cs->as,

                                   env->vm_vmcb + offsetof(struct vmcb,

                                                           save.cpl)));

    /* FIXME: guest state consistency checks */

    switch (ldub_phys(cs->as,

                      env->vm_vmcb + offsetof(struct vmcb, control.tlb_ctl))) {

    case TLB_CONTROL_DO_NOTHING:

        break;

    case TLB_CONTROL_FLUSH_ALL_ASID:

        /* FIXME: this is not 100% correct but should work for now */

        tlb_flush(cs, 1);

        break;

    }

    env->hflags2 |= HF2_GIF_MASK;

    if (int_ctl & V_IRQ_MASK) {

        CPUState *cs = CPU(x86_env_get_cpu(env));

        cs->interrupt_request |= CPU_INTERRUPT_VIRQ;

    }

    /* maybe we need to inject an event */

    event_inj = ldl_phys(cs->as, env->vm_vmcb + offsetof(struct vmcb,

                                                 control.event_inj));

    if (event_inj & SVM_EVTINJ_VALID) {

        uint8_t vector = event_inj & SVM_EVTINJ_VEC_MASK;

        uint16_t valid_err = event_inj & SVM_EVTINJ_VALID_ERR;

        uint32_t event_inj_err = ldl_phys(cs->as, env->vm_vmcb +

                                          offsetof(struct vmcb,

                                                   control.event_inj_err));

        qemu_log_mask(CPU_LOG_TB_IN_ASM, "Injecting(%#hx): ", valid_err);

        /* FIXME: need to implement valid_err */

        switch (event_inj & SVM_EVTINJ_TYPE_MASK) {

        case SVM_EVTINJ_TYPE_INTR:

            cs->exception_index = vector;

            env->error_code = event_inj_err;

            env->exception_is_int = 0;

            env->exception_next_eip = -1;

            qemu_log_mask(CPU_LOG_TB_IN_ASM, "INTR");

            /* XXX: is it always correct? */

            do_interrupt_x86_hardirq(env, vector, 1);

            break;

        case SVM_EVTINJ_TYPE_NMI:

            cs->exception_index = EXCP02_NMI;

            env->error_code = event_inj_err;

            env->exception_is_int = 0;

            env->exception_next_eip = env->eip;

            qemu_log_mask(CPU_LOG_TB_IN_ASM, "NMI");

            cpu_loop_exit(cs);

            break;

        case SVM_EVTINJ_TYPE_EXEPT:

            cs->exception_index = vector;

            env->error_code = event_inj_err;

            env->exception_is_int = 0;

            env->exception_next_eip = -1;

            qemu_log_mask(CPU_LOG_TB_IN_ASM, "EXEPT");

            cpu_loop_exit(cs);

            break;

        case SVM_EVTINJ_TYPE_SOFT:

            cs->exception_index = vector;

            env->error_code = event_inj_err;

            env->exception_is_int = 1;

            env->exception_next_eip = env->eip;

            qemu_log_mask(CPU_LOG_TB_IN_ASM, "SOFT");

            cpu_loop_exit(cs);

            break;

        }

        qemu_log_mask(CPU_LOG_TB_IN_ASM, " %#x %#x\n", cs->exception_index,

                      env->error_code);

    }

}


static void spr_write_ibatu (void *opaque, int sprn)

{

    DisasContext *ctx = opaque;

    gen_op_store_ibatu((sprn - SPR_IBAT0U) / 2);

    RET_STOP(ctx);

}


static void machine_numa_validate(MachineState *machine)

{

    int i;

    GString *s = g_string_new(NULL);

    MachineClass *mc = MACHINE_GET_CLASS(machine);

    const CPUArchIdList *possible_cpus = mc->possible_cpu_arch_ids(machine);

    assert(nb_numa_nodes);

    for (i = 0; i < possible_cpus->len; i++) {

        const CPUArchId *cpu_slot = &possible_cpus->cpus[i];

        /* at this point numa mappings are initilized by CLI options

         * or with default mappings so it's sufficient to list

         * all not yet mapped CPUs here */

        /* TODO: make it hard error in future */

        if (!cpu_slot->props.has_node_id) {

            char *cpu_str = cpu_slot_to_string(cpu_slot);

            g_string_append_printf(s, "%sCPU %d [%s]", s->len ? ", " : "", i,

                                   cpu_str);

            g_free(cpu_str);

        }

    }

    if (s->len) {

        error_report("warning: CPU(s) not present in any NUMA nodes: %s",

                     s->str);

        error_report("warning: All CPU(s) up to maxcpus should be described "

                     "in NUMA config, ability to start up with partial NUMA "

                     "mappings is obsoleted and will be removed in future");

    }

    g_string_free(s, true);

}


int qcow2_refcount_init(BlockDriverState *bs)

{

    BDRVQcowState *s = bs->opaque;

    unsigned int refcount_table_size2, i;

    int ret;

    assert(s->refcount_table_size <= INT_MAX / sizeof(uint64_t));

    refcount_table_size2 = s->refcount_table_size * sizeof(uint64_t);

    s->refcount_table = g_try_malloc(refcount_table_size2);

    if (s->refcount_table_size > 0) {

        if (s->refcount_table == NULL) {

            goto fail;

        }

        BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_LOAD);

        ret = bdrv_pread(bs->file, s->refcount_table_offset,

                         s->refcount_table, refcount_table_size2);

        if (ret != refcount_table_size2)

            goto fail;

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

            be64_to_cpus(&s->refcount_table[i]);

    }

    return 0;

 fail:

    return -ENOMEM;

}


static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)

{

    int j, k, l, sb_x, sb_y;

    int coding_mode;

    int motion_x[6];

    int motion_y[6];

    int last_motion_x = 0;

    int last_motion_y = 0;

    int prior_last_motion_x = 0;

    int prior_last_motion_y = 0;

    int current_macroblock;

    int current_fragment;

    if (s->keyframe)

        return 0;

    memset(motion_x, 0, 6 * sizeof(int));

    memset(motion_y, 0, 6 * sizeof(int));

    /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */

    coding_mode = get_bits1(gb);

    /* iterate through all of the macroblocks that contain 1 or more

     * coded fragments */

    for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {

        for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {

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

            int mb_x = 2*sb_x +   (j>>1);

            int mb_y = 2*sb_y + (((j>>1)+j)&1);

            current_macroblock = mb_y * s->macroblock_width + mb_x;

            if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height ||

                (s->macroblock_coding[current_macroblock] == MODE_COPY))

                continue;

            switch (s->macroblock_coding[current_macroblock]) {

            case MODE_INTER_PLUS_MV:

            case MODE_GOLDEN_MV:

                /* all 6 fragments use the same motion vector */

                if (coding_mode == 0) {

                    motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];

                    motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];

                } else {

                    motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];

                    motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];

                }

                /* vector maintenance, only on MODE_INTER_PLUS_MV */

                if (s->macroblock_coding[current_macroblock] ==

                    MODE_INTER_PLUS_MV) {

                    prior_last_motion_x = last_motion_x;

                    prior_last_motion_y = last_motion_y;

                    last_motion_x = motion_x[0];

                    last_motion_y = motion_y[0];

                }

                break;

            case MODE_INTER_FOURMV:

                /* vector maintenance */

                prior_last_motion_x = last_motion_x;

                prior_last_motion_y = last_motion_y;

                /* fetch 4 vectors from the bitstream, one for each

                 * Y fragment, then average for the C fragment vectors */

                motion_x[4] = motion_y[4] = 0;

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

                    current_fragment = BLOCK_Y*s->fragment_width + BLOCK_X;

                    for (l = 0; l < s->coded_fragment_list_index; l++)

                        if (s->coded_fragment_list[l] == current_fragment)

                            break;

                    if (l < s->coded_fragment_list_index) {

                        if (coding_mode == 0) {

                            motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];

                            motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];

                        } else {

                            motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];

                            motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];

                        }

                        last_motion_x = motion_x[k];

                        last_motion_y = motion_y[k];

                    } else {

                        motion_x[k] = 0;

                        motion_y[k] = 0;

                    }

                    motion_x[4] += motion_x[k];

                    motion_y[4] += motion_y[k];

                }

                motion_x[5]=

                motion_x[4]= RSHIFT(motion_x[4], 2);

                motion_y[5]=

                motion_y[4]= RSHIFT(motion_y[4], 2);

                break;

            case MODE_INTER_LAST_MV:

                /* all 6 fragments use the last motion vector */

                motion_x[0] = last_motion_x;

                motion_y[0] = last_motion_y;

                /* no vector maintenance (last vector remains the

                 * last vector) */

                break;

            case MODE_INTER_PRIOR_LAST:

                /* all 6 fragments use the motion vector prior to the

                 * last motion vector */

                motion_x[0] = prior_last_motion_x;

                motion_y[0] = prior_last_motion_y;

                /* vector maintenance */

                prior_last_motion_x = last_motion_x;

                prior_last_motion_y = last_motion_y;

                last_motion_x = motion_x[0];

                last_motion_y = motion_y[0];

                break;

            default:

                /* covers intra, inter without MV, golden without MV */

                motion_x[0] = 0;

                motion_y[0] = 0;

                /* no vector maintenance */

                break;

            }

            /* assign the motion vectors to the correct fragments */

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

                current_fragment =

                    BLOCK_Y*s->fragment_width + BLOCK_X;

                if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {

                    s->all_fragments[current_fragment].motion_x = motion_x[k];

                    s->all_fragments[current_fragment].motion_y = motion_y[k];

                } else {

                    s->all_fragments[current_fragment].motion_x = motion_x[0];

                    s->all_fragments[current_fragment].motion_y = motion_y[0];

                }

            }

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

                current_fragment = s->fragment_start[k+1] +

                    mb_y*(s->fragment_width>>1) + mb_x;

                if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {

                    s->all_fragments[current_fragment].motion_x = motion_x[k+4];

                    s->all_fragments[current_fragment].motion_y = motion_y[k+4];

                } else {

                    s->all_fragments[current_fragment].motion_x = motion_x[0];

                    s->all_fragments[current_fragment].motion_y = motion_y[0];

                }

            }

        }

        }

    }

    return 0;

}


void visit_type_int32(Visitor *v, int32_t *obj, const char *name, Error **errp)

{

    int64_t value;

    if (!error_is_set(errp)) {

        if (v->type_int32) {

            v->type_int32(v, obj, name, errp);

        } else {

            value = *obj;

            v->type_int(v, &value, name, errp);

            if (value < INT32_MIN || value > INT32_MAX) {

                error_set(errp, QERR_INVALID_PARAMETER_VALUE, name ? name : "null",

                          "int32_t");

                return;

            }

            *obj = value;

        }

    }

}


static inline void gen_bx_im(DisasContext *s, uint32_t addr)

{

    TCGv tmp;

    s->is_jmp = DISAS_UPDATE;

    if (s->thumb != (addr & 1)) {

        tmp = new_tmp();

        tcg_gen_movi_i32(tmp, addr & 1);

        tcg_gen_st_i32(tmp, cpu_env, offsetof(CPUState, thumb));

        dead_tmp(tmp);

    }

    tcg_gen_movi_i32(cpu_R[15], addr & ~1);

}


int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)

{

    int pending = size;

    int done = 0;

    while (pending > 0) {

        int res;

        res = qemu_peek_buffer(f, buf, pending, 0);

        if (res == 0) {

            return done;

        }

        qemu_file_skip(f, res);

        buf += res;

        pending -= res;

        done += res;

    }

    return done;

}


static void buffer_append(Buffer *buffer, const void *data, size_t len)

{

    memcpy(buffer->buffer + buffer->offset, data, len);

    buffer->offset += len;

}


void av_dump_format(AVFormatContext *ic,

                    int index,

                    const char *url,

                    int is_output)

{

    int i;

    uint8_t *printed = av_mallocz(ic->nb_streams);

    if (ic->nb_streams && !printed)

        return;

    av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",

            is_output ? "Output" : "Input",

            index,

            is_output ? ic->oformat->name : ic->iformat->name,

            is_output ? "to" : "from", url);

    dump_metadata(NULL, ic->metadata, "  ");

    if (!is_output) {

        av_log(NULL, AV_LOG_INFO, "  Duration: ");

        if (ic->duration != AV_NOPTS_VALUE) {

            int hours, mins, secs, us;

            secs = ic->duration / AV_TIME_BASE;

            us = ic->duration % AV_TIME_BASE;

            mins = secs / 60;

            secs %= 60;

            hours = mins / 60;

            mins %= 60;

            av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,

                   (100 * us) / AV_TIME_BASE);

        } else {

            av_log(NULL, AV_LOG_INFO, "N/A");

        }

        if (ic->start_time != AV_NOPTS_VALUE) {

            int secs, us;

            av_log(NULL, AV_LOG_INFO, ", start: ");

            secs = ic->start_time / AV_TIME_BASE;

            us = abs(ic->start_time % AV_TIME_BASE);

            av_log(NULL, AV_LOG_INFO, "%d.%06d",

                   secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));

        }

        av_log(NULL, AV_LOG_INFO, ", bitrate: ");

        if (ic->bit_rate) {

            av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);

        } else {

            av_log(NULL, AV_LOG_INFO, "N/A");

        }

        av_log(NULL, AV_LOG_INFO, "\n");

    }

    for (i = 0; i < ic->nb_chapters; i++) {

        AVChapter *ch = ic->chapters[i];

        av_log(NULL, AV_LOG_INFO, "    Chapter #%d.%d: ", index, i);

        av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));

        av_log(NULL, AV_LOG_INFO, "end %f\n",   ch->end   * av_q2d(ch->time_base));

        dump_metadata(NULL, ch->metadata, "    ");

    }

    if(ic->nb_programs) {

        int j, k, total = 0;

        for(j=0; j<ic->nb_programs; j++) {

            AVDictionaryEntry *name = av_dict_get(ic->programs[j]->metadata,

                                                  "name", NULL, 0);

            av_log(NULL, AV_LOG_INFO, "  Program %d %s\n", ic->programs[j]->id,

                   name ? name->value : "");

            dump_metadata(NULL, ic->programs[j]->metadata, "    ");

            for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {

                dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);

                printed[ic->programs[j]->stream_index[k]] = 1;

            }

            total += ic->programs[j]->nb_stream_indexes;

        }

        if (total < ic->nb_streams)

            av_log(NULL, AV_LOG_INFO, "  No Program\n");

    }

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

        if (!printed[i])

            dump_stream_format(ic, i, index, is_output);

    av_free(printed);

}


static int r3d_read_redv(AVFormatContext *s, AVPacket *pkt, Atom *atom)

{

    AVStream *st = s->streams[0];

    int tmp;

    int av_unused tmp2;

    uint64_t pos = avio_tell(s->pb);

    unsigned dts;

    int ret;

    dts = avio_rb32(s->pb);

    tmp = avio_rb32(s->pb);

    av_dlog(s, "frame num %d\n", tmp);

    tmp  = avio_r8(s->pb); // major version

    tmp2 = avio_r8(s->pb); // minor version

    av_dlog(s, "version %d.%d\n", tmp, tmp2);

    tmp = avio_rb16(s->pb); // unknown

    av_dlog(s, "unknown %d\n", tmp);

    if (tmp > 4) {

        tmp = avio_rb16(s->pb); // unknown

        av_dlog(s, "unknown %d\n", tmp);

        tmp = avio_rb16(s->pb); // unknown

        av_dlog(s, "unknown %d\n", tmp);

        tmp = avio_rb32(s->pb);

        av_dlog(s, "width %d\n", tmp);

        tmp = avio_rb32(s->pb);

        av_dlog(s, "height %d\n", tmp);

        tmp = avio_rb32(s->pb);

        av_dlog(s, "metadata len %d\n", tmp);

    }

    tmp = atom->size - 8 - (avio_tell(s->pb) - pos);

    if (tmp < 0)

        return -1;

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

    if (ret < 0) {

        av_log(s, AV_LOG_ERROR, "error reading video packet\n");

        return -1;

    }

    pkt->stream_index = 0;

    pkt->dts = dts;

    if (st->avg_frame_rate.num)

        pkt->duration = (uint64_t)st->time_base.den*

            st->avg_frame_rate.den/st->avg_frame_rate.num;

    av_dlog(s, "pkt dts %"PRId64" duration %d\n", pkt->dts, pkt->duration);

    return 0;

}


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

{

    int i, j;

    w = (x + w) / VNC_STAT_RECT;

    h = (y + h) / VNC_STAT_RECT;

    x /= VNC_STAT_RECT;

    y /= VNC_STAT_RECT;

    for (j = y; j <= y + h; j++) {

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

            vs->lossy_rect[j][i] = 1;

        }

    }

}


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

{

    AssignedDevRegion *d = opaque;

    uint8_t *out = d->u.r_virtbase + addr;

    DEBUG("slow_bar_writeb addr=0x" TARGET_FMT_plx " val=0x%02x\n", addr, val);

    *out = val;

}


static void exynos4210_i2c_write(void *opaque, target_phys_addr_t offset,

                              uint64_t value, unsigned size)

{

    Exynos4210I2CState *s = (Exynos4210I2CState *)opaque;

    uint8_t v = value & 0xff;

    DPRINT("write %s [0x%02x] <- 0x%02x\n", exynos4_i2c_get_regname(offset),

            (unsigned int)offset, v);

    switch (offset) {

    case I2CCON_ADDR:

        s->i2ccon = (v & ~I2CCON_INT_PEND) | (s->i2ccon & I2CCON_INT_PEND);

        if ((s->i2ccon & I2CCON_INT_PEND) && !(v & I2CCON_INT_PEND)) {

            s->i2ccon &= ~I2CCON_INT_PEND;

            qemu_irq_lower(s->irq);

            if (!(s->i2ccon & I2CCON_INTRS_EN)) {

                s->i2cstat &= ~I2CSTAT_START_BUSY;

            }

            if (s->i2cstat & I2CSTAT_START_BUSY) {

                if (s->scl_free) {

                    if (EXYNOS4_I2C_MODE(s->i2cstat) == I2CMODE_MASTER_Tx) {

                        exynos4210_i2c_data_send(s);

                    } else if (EXYNOS4_I2C_MODE(s->i2cstat) ==

                            I2CMODE_MASTER_Rx) {

                        exynos4210_i2c_data_receive(s);

                    }

                } else {

                    s->i2ccon |= I2CCON_INT_PEND;

                    qemu_irq_raise(s->irq);

                }

            }

        }

        break;

    case I2CSTAT_ADDR:

        s->i2cstat =

                (s->i2cstat & I2CSTAT_START_BUSY) | (v & ~I2CSTAT_START_BUSY);

        if (!(s->i2cstat & I2CSTAT_OUTPUT_EN)) {

            s->i2cstat &= ~I2CSTAT_START_BUSY;

            s->scl_free = true;

            qemu_irq_lower(s->irq);

            break;

        }

        /* Nothing to do if in i2c slave mode */

        if (!I2C_IN_MASTER_MODE(s->i2cstat)) {

            break;

        }

        if (v & I2CSTAT_START_BUSY) {

            s->i2cstat &= ~I2CSTAT_LAST_BIT;

            s->i2cstat |= I2CSTAT_START_BUSY;    /* Line is busy */

            s->scl_free = false;

            /* Generate start bit and send slave address */

            if (i2c_start_transfer(s->bus, s->i2cds >> 1, s->i2cds & 0x1) &&

                    (s->i2ccon & I2CCON_ACK_GEN)) {

                s->i2cstat |= I2CSTAT_LAST_BIT;

            } else if (EXYNOS4_I2C_MODE(s->i2cstat) == I2CMODE_MASTER_Rx) {

                exynos4210_i2c_data_receive(s);

            }

            exynos4210_i2c_raise_interrupt(s);

        } else {

            i2c_end_transfer(s->bus);

            if (!(s->i2ccon & I2CCON_INT_PEND)) {

                s->i2cstat &= ~I2CSTAT_START_BUSY;

            }

            s->scl_free = true;

        }

        break;

    case I2CADD_ADDR:

        if ((s->i2cstat & I2CSTAT_OUTPUT_EN) == 0) {

            s->i2cadd = v;

        }

        break;

    case I2CDS_ADDR:

        if (s->i2cstat & I2CSTAT_OUTPUT_EN) {

            s->i2cds = v;

            s->scl_free = true;

            if (EXYNOS4_I2C_MODE(s->i2cstat) == I2CMODE_MASTER_Tx &&

                    (s->i2cstat & I2CSTAT_START_BUSY) &&

                    !(s->i2ccon & I2CCON_INT_PEND)) {

                exynos4210_i2c_data_send(s);

            }

        }

        break;

    case I2CLC_ADDR:

        s->i2clc = v;

        break;

    default:

        DPRINT("ERROR: Bad write offset 0x%x\n", (unsigned int)offset);

        break;

    }

}


static void virtio_net_apply_guest_offloads(VirtIONet *n)

{

    qemu_peer_set_offload(qemu_get_subqueue(n->nic, 0),

            !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_CSUM)),

            !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_TSO4)),

            !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_TSO6)),

            !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_ECN)),

            !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_UFO)));

}


static int xen_pt_msixctrl_reg_write(XenPCIPassthroughState *s,

                                     XenPTReg *cfg_entry, uint16_t *val,

                                     uint16_t dev_value, uint16_t valid_mask)

{

    XenPTRegInfo *reg = cfg_entry->reg;

    uint16_t writable_mask = 0;

    uint16_t throughable_mask = get_throughable_mask(s, reg, valid_mask);

    int debug_msix_enabled_old;

    /* modify emulate register */

    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;

    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);

    /* create value for writing to I/O device register */

    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);

    /* update MSI-X */

    if ((*val & PCI_MSIX_FLAGS_ENABLE)

        && !(*val & PCI_MSIX_FLAGS_MASKALL)) {

        xen_pt_msix_update(s);

    } else if (!(*val & PCI_MSIX_FLAGS_ENABLE) && s->msix->enabled) {

        xen_pt_msix_disable(s);

    }

    debug_msix_enabled_old = s->msix->enabled;

    s->msix->enabled = !!(*val & PCI_MSIX_FLAGS_ENABLE);

    if (s->msix->enabled != debug_msix_enabled_old) {

        XEN_PT_LOG(&s->dev, "%s MSI-X\n",

                   s->msix->enabled ? "enable" : "disable");

    }

    return 0;

}


int v9fs_co_mknod(V9fsState *s, V9fsString *path, uid_t uid,

                  gid_t gid, dev_t dev, mode_t mode)

{

    int err;

    FsCred cred;

    cred_init(&cred);

    cred.fc_uid  = uid;

    cred.fc_gid  = gid;

    cred.fc_mode = mode;

    cred.fc_rdev = dev;

    v9fs_co_run_in_worker(

        {

            err = s->ops->mknod(&s->ctx, path->data, &cred);

            if (err < 0) {

                err = -errno;

            }

        });

    return err;

}


static uint64_t icp_control_read(void *opaque, target_phys_addr_t offset,

                                 unsigned size)

{

    switch (offset >> 2) {

    case 0: /* CP_IDFIELD */

        return 0x41034003;

    case 1: /* CP_FLASHPROG */

        return 0;

    case 2: /* CP_INTREG */

        return 0;

    case 3: /* CP_DECODE */

        return 0x11;

    default:

        hw_error("icp_control_read: Bad offset %x\n", (int)offset);

        return 0;

    }

}


int64_t bdrv_get_block_status_above(BlockDriverState *bs,

                                    BlockDriverState *base,

                                    int64_t sector_num,

                                    int nb_sectors, int *pnum,

                                    BlockDriverState **file)

{

    Coroutine *co;

    BdrvCoGetBlockStatusData data = {

        .bs = bs,

        .base = base,

        .file = file,

        .sector_num = sector_num,

        .nb_sectors = nb_sectors,

        .pnum = pnum,

        .done = false,

    };

    if (qemu_in_coroutine()) {

        /* Fast-path if already in coroutine context */

        bdrv_get_block_status_above_co_entry(&data);

    } else {

        AioContext *aio_context = bdrv_get_aio_context(bs);

        co = qemu_coroutine_create(bdrv_get_block_status_above_co_entry,

                                   &data);

        qemu_coroutine_enter(co);

        while (!data.done) {

            aio_poll(aio_context, true);

        }

    }

    return data.ret;

}


static int block_save_complete(QEMUFile *f, void *opaque)

{

    int ret;

    DPRINTF("Enter save live complete submitted %d transferred %d\n",

            block_mig_state.submitted, block_mig_state.transferred);

    ret = flush_blks(f);

    if (ret) {

        blk_mig_cleanup();

        return ret;

    }

    blk_mig_reset_dirty_cursor();

    /* we know for sure that save bulk is completed and

       all async read completed */

    assert(block_mig_state.submitted == 0);

    do {

        ret = blk_mig_save_dirty_block(f, 0);

    } while (ret == 0);

    blk_mig_cleanup();

    if (ret) {

        return ret;

    }

    /* report completion */

    qemu_put_be64(f, (100 << BDRV_SECTOR_BITS) | BLK_MIG_FLAG_PROGRESS);

    DPRINTF("Block migration completed\n");

    qemu_put_be64(f, BLK_MIG_FLAG_EOS);

    return 0;

}


static void omap_pwl_write(void *opaque, target_phys_addr_t addr,

                           uint64_t value, unsigned size)

{

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

    int offset = addr & OMAP_MPUI_REG_MASK;

    if (size != 1) {

        return omap_badwidth_write8(opaque, addr, value);

    }

    switch (offset) {

    case 0x00:	/* PWL_LEVEL */

        s->level = value;

        omap_pwl_update(s);

        break;

    case 0x04:	/* PWL_CTRL */

        s->enable = value & 1;

        omap_pwl_update(s);

        break;

    default:

        OMAP_BAD_REG(addr);

        return;

    }

}


static int id_wellformed(const char *id)

{

    int i;

    if (!qemu_isalpha(id[0])) {

        return 0;

    }

    for (i = 1; id[i]; i++) {

        if (!qemu_isalnum(id[i]) && !strchr("-._", id[i])) {

            return 0;

        }

    }

    return 1;

}


static void memory_region_iorange_destructor(IORange *iorange)

{

    g_free(container_of(iorange, MemoryRegionIORange, iorange));

}


static int qemu_rbd_open(BlockDriverState *bs, const char *filename, int flags)

{

    BDRVRBDState *s = bs->opaque;

    char pool[RBD_MAX_POOL_NAME_SIZE];

    char snap_buf[RBD_MAX_SNAP_NAME_SIZE];

    char conf[RBD_MAX_CONF_SIZE];

    int r;

    if (qemu_rbd_parsename(filename, pool, sizeof(pool),

                           snap_buf, sizeof(snap_buf),

                           s->name, sizeof(s->name),

                           conf, sizeof(conf)) < 0) {

        return -EINVAL;

    }

    s->snap = NULL;

    if (snap_buf[0] != '\0') {

        s->snap = g_strdup(snap_buf);

    }

    r = rados_create(&s->cluster, NULL);

    if (r < 0) {

        error_report("error initializing");

        return r;

    }

    if (strstr(conf, "conf=") == NULL) {

        r = rados_conf_read_file(s->cluster, NULL);

        if (r < 0) {

            error_report("error reading config file");

            rados_shutdown(s->cluster);

            return r;

        }

    }

    if (conf[0] != '\0') {

        r = qemu_rbd_set_conf(s->cluster, conf);

        if (r < 0) {

            error_report("error setting config options");

            rados_shutdown(s->cluster);

            return r;

        }

    }

    r = rados_connect(s->cluster);

    if (r < 0) {

        error_report("error connecting");

        rados_shutdown(s->cluster);

        return r;

    }

    r = rados_ioctx_create(s->cluster, pool, &s->io_ctx);

    if (r < 0) {

        error_report("error opening pool %s", pool);

        rados_shutdown(s->cluster);

        return r;

    }

    r = rbd_open(s->io_ctx, s->name, &s->image, s->snap);

    if (r < 0) {

        error_report("error reading header from %s", s->name);

        rados_ioctx_destroy(s->io_ctx);

        rados_shutdown(s->cluster);

        return r;

    }

    bs->read_only = (s->snap != NULL);

    s->event_reader_pos = 0;

    r = qemu_pipe(s->fds);

    if (r < 0) {

        error_report("error opening eventfd");

        goto failed;

    }

    fcntl(s->fds[0], F_SETFL, O_NONBLOCK);

    fcntl(s->fds[1], F_SETFL, O_NONBLOCK);

    qemu_aio_set_fd_handler(s->fds[RBD_FD_READ], qemu_rbd_aio_event_reader,

                            NULL, qemu_rbd_aio_flush_cb, NULL, s);

    return 0;

failed:

    rbd_close(s->image);

    rados_ioctx_destroy(s->io_ctx);

    rados_shutdown(s->cluster);

    return r;

}


static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, size_t size)

{

    NetSocketState *s = opaque;

    sendto(s->fd, buf, size, 0,

           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));

}


int cpu_ppc_register (CPUPPCState *env, ppc_def_t *def)

{

    env->msr_mask = def->msr_mask;

    env->mmu_model = def->mmu_model;

    env->excp_model = def->excp_model;

    env->bus_model = def->bus_model;

    env->bfd_mach = def->bfd_mach;

    if (create_ppc_opcodes(env, def) < 0)

        return -1;

    init_ppc_proc(env, def);

#if defined(PPC_DUMP_CPU)

    {

        const unsigned char *mmu_model, *excp_model, *bus_model;

        switch (env->mmu_model) {

        case POWERPC_MMU_32B:

            mmu_model = "PowerPC 32";

            break;

        case POWERPC_MMU_64B:

            mmu_model = "PowerPC 64";

            break;

        case POWERPC_MMU_601:

            mmu_model = "PowerPC 601";

            break;

        case POWERPC_MMU_SOFT_6xx:

            mmu_model = "PowerPC 6xx/7xx with software driven TLBs";

            break;

        case POWERPC_MMU_SOFT_74xx:

            mmu_model = "PowerPC 74xx with software driven TLBs";

            break;

        case POWERPC_MMU_SOFT_4xx:

            mmu_model = "PowerPC 4xx with software driven TLBs";

            break;

        case POWERPC_MMU_SOFT_4xx_Z:

            mmu_model = "PowerPC 4xx with software driven TLBs "

                "and zones protections";

            break;

        case POWERPC_MMU_REAL_4xx:

            mmu_model = "PowerPC 4xx real mode only";

            break;

        case POWERPC_MMU_BOOKE:

            mmu_model = "PowerPC BookE";

            break;

        case POWERPC_MMU_BOOKE_FSL:

            mmu_model = "PowerPC BookE FSL";

            break;

        case POWERPC_MMU_64BRIDGE:

            mmu_model = "PowerPC 64 bridge";

            break;

        default:

            mmu_model = "Unknown or invalid";

            break;

        }

        switch (env->excp_model) {

        case POWERPC_EXCP_STD:

            excp_model = "PowerPC";

            break;

        case POWERPC_EXCP_40x:

            excp_model = "PowerPC 40x";

            break;

        case POWERPC_EXCP_601:

            excp_model = "PowerPC 601";

            break;

        case POWERPC_EXCP_602:

            excp_model = "PowerPC 602";

            break;

        case POWERPC_EXCP_603:

            excp_model = "PowerPC 603";

            break;

        case POWERPC_EXCP_603E:

            excp_model = "PowerPC 603e";

            break;

        case POWERPC_EXCP_604:

            excp_model = "PowerPC 604";

            break;

        case POWERPC_EXCP_7x0:

            excp_model = "PowerPC 740/750";

            break;

        case POWERPC_EXCP_7x5:

            excp_model = "PowerPC 745/755";

            break;

        case POWERPC_EXCP_74xx:

            excp_model = "PowerPC 74xx";

            break;

        case POWERPC_EXCP_970:

            excp_model = "PowerPC 970";

            break;

        case POWERPC_EXCP_BOOKE:

            excp_model = "PowerPC BookE";

            break;

        default:

            excp_model = "Unknown or invalid";

            break;

        }

        switch (env->bus_model) {

        case PPC_FLAGS_INPUT_6xx:

            bus_model = "PowerPC 6xx";

            break;

        case PPC_FLAGS_INPUT_BookE:

            bus_model = "PowerPC BookE";

            break;

        case PPC_FLAGS_INPUT_405:

            bus_model = "PowerPC 405";

            break;

        case PPC_FLAGS_INPUT_970:

            bus_model = "PowerPC 970";

            break;

        case PPC_FLAGS_INPUT_401:

            bus_model = "PowerPC 401/403";

            break;

        default:

            bus_model = "Unknown or invalid";

            break;

        }

        printf("PowerPC %-12s : PVR %08x MSR %016" PRIx64 "\n"

               "    MMU model        : %s\n",

               def->name, def->pvr, def->msr_mask, mmu_model);

        if (env->tlb != NULL) {

            printf("                       %d %s TLB in %d ways\n",

                   env->nb_tlb, env->id_tlbs ? "splitted" : "merged",

                   env->nb_ways);

        }

        printf("    Exceptions model : %s\n"

               "    Bus model        : %s\n",

               excp_model, bus_model);

    }

    dump_ppc_insns(env);

    dump_ppc_sprs(env);

    fflush(stdout);

#endif

    return 0;

}


static char *get_human_readable_size(char *buf, int buf_size, int64_t size)

{

    static const char suffixes[NB_SUFFIXES] = "KMGT";

    int64_t base;

    int i;

    if (size <= 999) {

        snprintf(buf, buf_size, "%" PRId64, size);

    } else {

        base = 1024;

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

            if (size < (10 * base)) {

                snprintf(buf, buf_size, "%0.1f%c",

                         (double)size / base,

                         suffixes[i]);

                break;

            } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {

                snprintf(buf, buf_size, "%" PRId64 "%c",

                         ((size + (base >> 1)) / base),

                         suffixes[i]);

                break;

            }

            base = base * 1024;

        }

    }

    return buf;

}


static coroutine_fn int cloop_co_read(BlockDriverState *bs, int64_t sector_num,

                                      uint8_t *buf, int nb_sectors)

{

    int ret;

    BDRVCloopState *s = bs->opaque;

    qemu_co_mutex_lock(&s->lock);

    ret = cloop_read(bs, sector_num, buf, nb_sectors);

    qemu_co_mutex_unlock(&s->lock);

    return ret;

}