static void arm_cpu_reset(CPUState *s)

{

    ARMCPU *cpu = ARM_CPU(s);

    ARMCPUClass *acc = ARM_CPU_GET_CLASS(cpu);

    CPUARMState *env = &cpu->env;

    acc->parent_reset(s);

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

    g_hash_table_foreach(cpu->cp_regs, cp_reg_reset, cpu);

    g_hash_table_foreach(cpu->cp_regs, cp_reg_check_reset, cpu);

    env->vfp.xregs[ARM_VFP_FPSID] = cpu->reset_fpsid;

    env->vfp.xregs[ARM_VFP_MVFR0] = cpu->mvfr0;

    env->vfp.xregs[ARM_VFP_MVFR1] = cpu->mvfr1;

    env->vfp.xregs[ARM_VFP_MVFR2] = cpu->mvfr2;

    cpu->powered_off = cpu->start_powered_off;

    s->halted = cpu->start_powered_off;

    if (arm_feature(env, ARM_FEATURE_IWMMXT)) {

        env->iwmmxt.cregs[ARM_IWMMXT_wCID] = 0x69051000 | 'Q';

    }

    if (arm_feature(env, ARM_FEATURE_AARCH64)) {

        /* 64 bit CPUs always start in 64 bit mode */

        env->aarch64 = 1;

#if defined(CONFIG_USER_ONLY)

        env->pstate = PSTATE_MODE_EL0t;

        /* Userspace expects access to DC ZVA, CTL_EL0 and the cache ops */

        env->cp15.sctlr_el[1] |= SCTLR_UCT | SCTLR_UCI | SCTLR_DZE;

        /* and to the FP/Neon instructions */

        env->cp15.cpacr_el1 = deposit64(env->cp15.cpacr_el1, 20, 2, 3);

#else

        /* Reset into the highest available EL */

        if (arm_feature(env, ARM_FEATURE_EL3)) {

            env->pstate = PSTATE_MODE_EL3h;

        } else if (arm_feature(env, ARM_FEATURE_EL2)) {

            env->pstate = PSTATE_MODE_EL2h;

        } else {

            env->pstate = PSTATE_MODE_EL1h;

        }

        env->pc = cpu->rvbar;

#endif

    } else {

#if defined(CONFIG_USER_ONLY)

        /* Userspace expects access to cp10 and cp11 for FP/Neon */

        env->cp15.cpacr_el1 = deposit64(env->cp15.cpacr_el1, 20, 4, 0xf);

#endif

    }

#if defined(CONFIG_USER_ONLY)

    env->uncached_cpsr = ARM_CPU_MODE_USR;

    /* For user mode we must enable access to coprocessors */

    env->vfp.xregs[ARM_VFP_FPEXC] = 1 << 30;

    if (arm_feature(env, ARM_FEATURE_IWMMXT)) {

        env->cp15.c15_cpar = 3;

    } else if (arm_feature(env, ARM_FEATURE_XSCALE)) {

        env->cp15.c15_cpar = 1;

    }

#else

    /* SVC mode with interrupts disabled.  */

    env->uncached_cpsr = ARM_CPU_MODE_SVC;

    env->daif = PSTATE_D | PSTATE_A | PSTATE_I | PSTATE_F;

    if (arm_feature(env, ARM_FEATURE_M)) {

        uint32_t initial_msp; /* Loaded from 0x0 */

        uint32_t initial_pc; /* Loaded from 0x4 */

        uint8_t *rom;

        /* For M profile we store FAULTMASK and PRIMASK in the

         * PSTATE F and I bits; these are both clear at reset.

         */

        env->daif &= ~(PSTATE_I | PSTATE_F);

        /* The reset value of this bit is IMPDEF, but ARM recommends

         * that it resets to 1, so QEMU always does that rather than making

         * it dependent on CPU model.

         */

        env->v7m.ccr = R_V7M_CCR_STKALIGN_MASK;

        /* Unlike A/R profile, M profile defines the reset LR value */

        env->regs[14] = 0xffffffff;

        /* Load the initial SP and PC from the vector table at address 0 */

        rom = rom_ptr(0);

        if (rom) {

            /* Address zero is covered by ROM which hasn't yet been

             * copied into physical memory.

             */

            initial_msp = ldl_p(rom);

            initial_pc = ldl_p(rom + 4);

        } else {

            /* Address zero not covered by a ROM blob, or the ROM blob

             * is in non-modifiable memory and this is a second reset after

             * it got copied into memory. In the latter case, rom_ptr

             * will return a NULL pointer and we should use ldl_phys instead.

             */

            initial_msp = ldl_phys(s->as, 0);

            initial_pc = ldl_phys(s->as, 4);

        }

        env->regs[13] = initial_msp & 0xFFFFFFFC;

        env->regs[15] = initial_pc & ~1;

        env->thumb = initial_pc & 1;

    }

    /* AArch32 has a hard highvec setting of 0xFFFF0000.  If we are currently

     * executing as AArch32 then check if highvecs are enabled and

     * adjust the PC accordingly.

     */

    if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {

        env->regs[15] = 0xFFFF0000;

    }

    env->vfp.xregs[ARM_VFP_FPEXC] = 0;

#endif

    set_flush_to_zero(1, &env->vfp.standard_fp_status);

    set_flush_inputs_to_zero(1, &env->vfp.standard_fp_status);

    set_default_nan_mode(1, &env->vfp.standard_fp_status);

    set_float_detect_tininess(float_tininess_before_rounding,

                              &env->vfp.fp_status);

    set_float_detect_tininess(float_tininess_before_rounding,

                              &env->vfp.standard_fp_status);

#ifndef CONFIG_USER_ONLY

    if (kvm_enabled()) {

        kvm_arm_reset_vcpu(cpu);

    }

#endif

    hw_breakpoint_update_all(cpu);

    hw_watchpoint_update_all(cpu);

}


void tcg_add_target_add_op_defs(const TCGTargetOpDef *tdefs)

{

    TCGOpcode op;

    TCGOpDef *def;

    const char *ct_str;

    int i, nb_args;

    for(;;) {

        if (tdefs->op == (TCGOpcode)-1)

            break;

        op = tdefs->op;

        assert(op >= 0 && op < NB_OPS);

        def = &tcg_op_defs[op];

#if defined(CONFIG_DEBUG_TCG)

        /* Duplicate entry in op definitions? */

        assert(!def->used);

        def->used = 1;

#endif

        nb_args = def->nb_iargs + def->nb_oargs;

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

            ct_str = tdefs->args_ct_str[i];

            /* Incomplete TCGTargetOpDef entry? */

            assert(ct_str != NULL);

            tcg_regset_clear(def->args_ct[i].u.regs);

            def->args_ct[i].ct = 0;

            if (ct_str[0] >= '0' && ct_str[0] <= '9') {

                int oarg;

                oarg = ct_str[0] - '0';

                assert(oarg < def->nb_oargs);

                assert(def->args_ct[oarg].ct & TCG_CT_REG);

                /* TCG_CT_ALIAS is for the output arguments. The input

                   argument is tagged with TCG_CT_IALIAS. */

                def->args_ct[i] = def->args_ct[oarg];

                def->args_ct[oarg].ct = TCG_CT_ALIAS;

                def->args_ct[oarg].alias_index = i;

                def->args_ct[i].ct |= TCG_CT_IALIAS;

                def->args_ct[i].alias_index = oarg;

            } else {

                for(;;) {

                    if (*ct_str == '\0')

                        break;

                    switch(*ct_str) {

                    case 'i':

                        def->args_ct[i].ct |= TCG_CT_CONST;

                        ct_str++;

                        break;

                    default:

                        if (target_parse_constraint(&def->args_ct[i], &ct_str) < 0) {

                            fprintf(stderr, "Invalid constraint '%s' for arg %d of operation '%s'\n",

                                    ct_str, i, def->name);

                            exit(1);

                        }

                    }

                }

            }

        }

        /* TCGTargetOpDef entry with too much information? */

        assert(i == TCG_MAX_OP_ARGS || tdefs->args_ct_str[i] == NULL);

        /* sort the constraints (XXX: this is just an heuristic) */

        sort_constraints(def, 0, def->nb_oargs);

        sort_constraints(def, def->nb_oargs, def->nb_iargs);

#if 0

        {

            int i;

            printf("%s: sorted=", def->name);

            for(i = 0; i < def->nb_oargs + def->nb_iargs; i++)

                printf(" %d", def->sorted_args[i]);

            printf("\n");

        }

#endif

        tdefs++;

    }

#if defined(CONFIG_DEBUG_TCG)

    i = 0;

    for (op = 0; op < ARRAY_SIZE(tcg_op_defs); op++) {

        if (op < INDEX_op_call || op == INDEX_op_debug_insn_start) {

            /* Wrong entry in op definitions? */

            if (tcg_op_defs[op].used) {

                fprintf(stderr, "Invalid op definition for %s\n",

                        tcg_op_defs[op].name);

                i = 1;

            }

        } else {

            /* Missing entry in op definitions? */

            if (!tcg_op_defs[op].used) {

                fprintf(stderr, "Missing op definition for %s\n",

                        tcg_op_defs[op].name);

                i = 1;

            }

        }

    }

    if (i == 1) {

        tcg_abort();

    }

#endif

}


static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)

{

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

    int64_t seconds;

    if (!s->bit_rate)

        return AVERROR_INVALIDDATA;

    if (sample_time < 0)

        sample_time = 0;

    seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);

    avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET);

    ff_update_cur_dts(s, st, sample_time);

    return 0;

}


static inline int _find_pte (mmu_ctx_t *ctx, int is_64b, int h, int rw)

{

    target_ulong base, pte0, pte1;

    int i, good = -1;

    int ret, r;

    ret = -1; /* No entry found */

    base = ctx->pg_addr[h];

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

#if defined(TARGET_PPC64)

        if (is_64b) {

            pte0 = ldq_phys(base + (i * 16));

            pte1 =  ldq_phys(base + (i * 16) + 8);

            r = pte64_check(ctx, pte0, pte1, h, rw);

        } else

#endif

        {

            pte0 = ldl_phys(base + (i * 8));

            pte1 =  ldl_phys(base + (i * 8) + 4);

            r = pte32_check(ctx, pte0, pte1, h, rw);

        }

#if defined (DEBUG_MMU)

        if (loglevel != 0) {

            fprintf(logfile, "Load pte from 0x" ADDRX " => 0x" ADDRX

                    " 0x" ADDRX " %d %d %d 0x" ADDRX "\n",

                    base + (i * 8), pte0, pte1,

                    (int)(pte0 >> 31), h, (int)((pte0 >> 6) & 1), ctx->ptem);

        }

#endif

        switch (r) {

        case -3:

            /* PTE inconsistency */

            return -1;

        case -2:

            /* Access violation */

            ret = -2;

            good = i;

            break;

        case -1:

        default:

            /* No PTE match */

            break;

        case 0:

            /* access granted */

            /* XXX: we should go on looping to check all PTEs consistency

             *      but if we can speed-up the whole thing as the

             *      result would be undefined if PTEs are not consistent.

             */

            ret = 0;

            good = i;

            goto done;

        }

    }

    if (good != -1) {

    done:

#if defined (DEBUG_MMU)

        if (loglevel != 0) {

            fprintf(logfile, "found PTE at addr 0x" PADDRX " prot=0x%01x "

                    "ret=%d\n",

                    ctx->raddr, ctx->prot, ret);

        }

#endif

        /* Update page flags */

        pte1 = ctx->raddr;

        if (pte_update_flags(ctx, &pte1, ret, rw) == 1) {

#if defined(TARGET_PPC64)

            if (is_64b) {

                stq_phys_notdirty(base + (good * 16) + 8, pte1);

            } else

#endif

            {

                stl_phys_notdirty(base + (good * 8) + 4, pte1);

            }

        }

    }

    return ret;

}


static int nbd_send_reply(int csock, struct nbd_reply *reply)

{

    uint8_t buf[4 + 4 + 8];

    /* Reply

       [ 0 ..  3]    magic   (NBD_REPLY_MAGIC)

       [ 4 ..  7]    error   (0 == no error)

       [ 7 .. 15]    handle

     */

    cpu_to_be32w((uint32_t*)buf, NBD_REPLY_MAGIC);

    cpu_to_be32w((uint32_t*)(buf + 4), reply->error);

    cpu_to_be64w((uint64_t*)(buf + 8), reply->handle);

    TRACE("Sending response to client");

    if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {

        LOG("writing to socket failed");

        errno = EINVAL;

        return -1;

    }

    return 0;

}


static int encode_apng(AVCodecContext *avctx, AVPacket *pkt,

                       const AVFrame *pict, int *got_packet)

{

    PNGEncContext *s = avctx->priv_data;

    int ret;

    int enc_row_size;

    size_t max_packet_size;

    APNGFctlChunk fctl_chunk;

    if (pict && avctx->codec_id == AV_CODEC_ID_APNG && s->color_type == PNG_COLOR_TYPE_PALETTE) {

        uint32_t checksum = ~av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), ~0U, pict->data[1], 256 * sizeof(uint32_t));

        if (avctx->frame_number == 0) {

            s->palette_checksum = checksum;

        } else if (checksum != s->palette_checksum) {

            av_log(avctx, AV_LOG_ERROR,

                   "Input contains more than one unique palette. APNG does not support multiple palettes.\n");

            return -1;

        }

    }

    enc_row_size    = deflateBound(&s->zstream, (avctx->width * s->bits_per_pixel + 7) >> 3);

    max_packet_size =

        AV_INPUT_BUFFER_MIN_SIZE + // headers

        avctx->height * (

            enc_row_size +

            (4 + 12) * (((int64_t)enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) // fdAT * ceil(enc_row_size / IOBUF_SIZE)

        );

    if (max_packet_size > INT_MAX)

        return AVERROR(ENOMEM);

    if (avctx->frame_number == 0) {

        s->bytestream = avctx->extradata = av_malloc(FF_MIN_BUFFER_SIZE);

        if (!avctx->extradata)

            return AVERROR(ENOMEM);

        ret = encode_headers(avctx, pict);

        if (ret < 0)

            return ret;

        avctx->extradata_size = s->bytestream - avctx->extradata;

        s->last_frame_packet = av_malloc(max_packet_size);

        if (!s->last_frame_packet)

            return AVERROR(ENOMEM);

    } else if (s->last_frame) {

        ret = ff_alloc_packet2(avctx, pkt, max_packet_size, 0);

        if (ret < 0)

            return ret;

        memcpy(pkt->data, s->last_frame_packet, s->last_frame_packet_size);

        pkt->size = s->last_frame_packet_size;

        pkt->pts = pkt->dts = s->last_frame->pts;

    }

    if (pict) {

        s->bytestream_start =

        s->bytestream       = s->last_frame_packet;

        s->bytestream_end   = s->bytestream + max_packet_size;

        // We're encoding the frame first, so we have to do a bit of shuffling around

        // to have the image data write to the correct place in the buffer

        fctl_chunk.sequence_number = s->sequence_number;

        ++s->sequence_number;

        s->bytestream += 26 + 12;

        ret = apng_encode_frame(avctx, pict, &fctl_chunk, &s->last_frame_fctl);

        if (ret < 0)

            return ret;

        fctl_chunk.delay_num = 0; // delay filled in during muxing

        fctl_chunk.delay_den = 0;

    } else {

        s->last_frame_fctl.dispose_op = APNG_DISPOSE_OP_NONE;

    }

    if (s->last_frame) {

        uint8_t* last_fctl_chunk_start = pkt->data;

        uint8_t buf[26];

        AV_WB32(buf + 0, s->last_frame_fctl.sequence_number);

        AV_WB32(buf + 4, s->last_frame_fctl.width);

        AV_WB32(buf + 8, s->last_frame_fctl.height);

        AV_WB32(buf + 12, s->last_frame_fctl.x_offset);

        AV_WB32(buf + 16, s->last_frame_fctl.y_offset);

        AV_WB16(buf + 20, s->last_frame_fctl.delay_num);

        AV_WB16(buf + 22, s->last_frame_fctl.delay_den);

        buf[24] = s->last_frame_fctl.dispose_op;

        buf[25] = s->last_frame_fctl.blend_op;

        png_write_chunk(&last_fctl_chunk_start, MKTAG('f', 'c', 'T', 'L'), buf, 26);

        *got_packet = 1;

    }

    if (pict) {

        if (!s->last_frame) {

            s->last_frame = av_frame_alloc();

            if (!s->last_frame)

                return AVERROR(ENOMEM);

        } else if (s->last_frame_fctl.dispose_op != APNG_DISPOSE_OP_PREVIOUS) {

            if (!s->prev_frame) {

                s->prev_frame = av_frame_alloc();

                if (!s->prev_frame)

                    return AVERROR(ENOMEM);

                s->prev_frame->format = pict->format;

                s->prev_frame->width = pict->width;

                s->prev_frame->height = pict->height;

                if ((ret = av_frame_get_buffer(s->prev_frame, 32)) < 0)

                    return ret;

            }

            // Do disposal, but not blending

            memcpy(s->prev_frame->data[0], s->last_frame->data[0],

                   s->last_frame->linesize[0] * s->last_frame->height);

            if (s->last_frame_fctl.dispose_op == APNG_DISPOSE_OP_BACKGROUND) {

                uint32_t y;

                uint8_t bpp = (s->bits_per_pixel + 7) >> 3;

                for (y = s->last_frame_fctl.y_offset; y < s->last_frame_fctl.y_offset + s->last_frame_fctl.height; ++y) {

                    size_t row_start = s->last_frame->linesize[0] * y + bpp * s->last_frame_fctl.x_offset;

                    memset(s->prev_frame->data[0] + row_start, 0, bpp * s->last_frame_fctl.width);

                }

            }

        }

        av_frame_unref(s->last_frame);

        ret = av_frame_ref(s->last_frame, (AVFrame*)pict);

        if (ret < 0)

            return ret;

        s->last_frame_fctl = fctl_chunk;

        s->last_frame_packet_size = s->bytestream - s->bytestream_start;

    } else {

        av_frame_free(&s->last_frame);

    }

    return 0;

}


static int tpm_passthrough_open_sysfs_cancel(TPMPassthruState *tpm_pt)

{

    int fd = -1;

    char *dev;

    char path[PATH_MAX];

    if (tpm_pt->options->cancel_path) {

        fd = qemu_open(tpm_pt->options->cancel_path, O_WRONLY);

        if (fd < 0) {

            error_report("Could not open TPM cancel path : %s",

                         strerror(errno));

        }

        return fd;

    }

    dev = strrchr(tpm_pt->tpm_dev, '/');

    if (dev) {

        dev++;

        if (snprintf(path, sizeof(path), "/sys/class/misc/%s/device/cancel",

                     dev) < sizeof(path)) {

            fd = qemu_open(path, O_WRONLY);

            if (fd >= 0) {

                tpm_pt->options->cancel_path = g_strdup(path);

            } else {

                error_report("tpm_passthrough: Could not open TPM cancel "

                             "path %s : %s", path, strerror(errno));

            }

        }

    } else {

       error_report("tpm_passthrough: Bad TPM device path %s",

                    tpm_pt->tpm_dev);

    }

    return fd;

}


int ff_combine_frame(ParseContext *pc, int next, const uint8_t **buf, int *buf_size)

{

    if(pc->overread){

        av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n",

                pc->overread, pc->state, next, pc->index, pc->overread_index);

        av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1], (*buf)[2], (*buf)[3]);

    }

    /* Copy overread bytes from last frame into buffer. */

    for(; pc->overread>0; pc->overread--){

        pc->buffer[pc->index++]= pc->buffer[pc->overread_index++];

    }

    /* flush remaining if EOF */

    if(!*buf_size && next == END_NOT_FOUND){

        next= 0;

    }

    pc->last_index= pc->index;

    /* copy into buffer end return */

    if(next == END_NOT_FOUND){

        void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, (*buf_size) + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);

        if(!new_buffer)

            return AVERROR(ENOMEM);

        pc->buffer = new_buffer;

        memcpy(&pc->buffer[pc->index], *buf, *buf_size);

        pc->index += *buf_size;

        return -1;

    }

    *buf_size=

    pc->overread_index= pc->index + next;

    /* append to buffer */

    if(pc->index){

        void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, next + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);

        if(!new_buffer)

            return AVERROR(ENOMEM);

        pc->buffer = new_buffer;

        memcpy(&pc->buffer[pc->index], *buf, next + FF_INPUT_BUFFER_PADDING_SIZE );

        pc->index = 0;

        *buf= pc->buffer;

    }

    /* store overread bytes */

    for(;next < 0; next++){

        pc->state = (pc->state<<8) | pc->buffer[pc->last_index + next];

        pc->state64 = (pc->state64<<8) | pc->buffer[pc->last_index + next];

        pc->overread++;

    }

    if(pc->overread){

        av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n",

                pc->overread, pc->state, next, pc->index, pc->overread_index);

        av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]);

    }

    return 0;

}


static void qtrle_decode_1bpp(QtrleContext *s, int stream_ptr, int row_ptr, int lines_to_change)

{

    int rle_code;

    int pixel_ptr = 0;

    int row_inc = s->frame.linesize[0];

    unsigned char pi0, pi1;  /* 2 8-pixel values */

    unsigned char *rgb = s->frame.data[0];

    int pixel_limit = s->frame.linesize[0] * s->avctx->height;

    int skip;

    while (lines_to_change) {

        CHECK_STREAM_PTR(2);

        skip = s->buf[stream_ptr++];

        rle_code = (signed char)s->buf[stream_ptr++];

        if (rle_code == 0)

            break;

        if(skip & 0x80) {

            lines_to_change--;

            row_ptr += row_inc;

            pixel_ptr = row_ptr + 2 * (skip & 0x7f);

        } else

            pixel_ptr += 2 * skip;

        CHECK_PIXEL_PTR(0);  /* make sure pixel_ptr is positive */

        if (rle_code < 0) {

            /* decode the run length code */

            rle_code = -rle_code;

            /* get the next 2 bytes from the stream, treat them as groups

             * of 8 pixels, and output them rle_code times */

            CHECK_STREAM_PTR(2);

            pi0 = s->buf[stream_ptr++];

            pi1 = s->buf[stream_ptr++];

            CHECK_PIXEL_PTR(rle_code * 2);

            while (rle_code--) {

                rgb[pixel_ptr++] = pi0;

                rgb[pixel_ptr++] = pi1;

            }

        } else {

            /* copy the same pixel directly to output 2 times */

            rle_code *= 2;

            CHECK_STREAM_PTR(rle_code);

            CHECK_PIXEL_PTR(rle_code);

            while (rle_code--)

                rgb[pixel_ptr++] = s->buf[stream_ptr++];

        }

    }

}


static void lm32_cpu_initfn(Object *obj)

{

    CPUState *cs = CPU(obj);

    LM32CPU *cpu = LM32_CPU(obj);

    CPULM32State *env = &cpu->env;

    static bool tcg_initialized;

    cs->env_ptr = env;

    cpu_exec_init(cs, &error_abort);

    env->flags = 0;

    if (tcg_enabled() && !tcg_initialized) {

        tcg_initialized = true;

        lm32_translate_init();

    }

}


static int find_and_check_chardev(CharDriverState **chr,

                                  char *chr_name,

                                  Error **errp)

{

    CompareChardevProps props;

    *chr = qemu_chr_find(chr_name);

    if (*chr == NULL) {

        error_setg(errp, "Device '%s' not found",

                   chr_name);

        return 1;

    }

    memset(&props, 0, sizeof(props));

    if (qemu_opt_foreach((*chr)->opts, compare_chardev_opts, &props, errp)) {

        return 1;

    }

    if (!props.is_socket) {

        error_setg(errp, "chardev \"%s\" is not a tcp socket",

                   chr_name);

        return 1;

    }

    return 0;

}


static void set_bit(Object *obj, Visitor *v, void *opaque,

                    const char *name, Error **errp)

{

    DeviceState *dev = DEVICE(obj);

    Property *prop = opaque;

    Error *local_err = NULL;

    bool value;

    if (dev->realized) {

        qdev_prop_set_after_realize(dev, name, errp);

        return;

    }

    visit_type_bool(v, &value, name, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    bit_prop_set(dev, prop, value);

}


static inline void gen_goto_tb(DisasContext *s, int tb_num, target_ulong eip)

{

    target_ulong pc = s->cs_base + eip;

    if (use_goto_tb(s, pc))  {

        /* jump to same page: we can use a direct jump */

        tcg_gen_goto_tb(tb_num);

        gen_jmp_im(eip);

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

    } else {

        /* jump to another page: currently not optimized */

        gen_jmp_im(eip);

        gen_eob(s);

    }

}


static const char *target_parse_constraint(TCGArgConstraint *ct,

                                           const char *ct_str, TCGType type)

{

    switch (*ct_str++) {

    case 'r':                  /* all registers */

        ct->ct |= TCG_CT_REG;

        tcg_regset_set32(ct->u.regs, 0, 0xffff);

        break;

    case 'L':                  /* qemu_ld/st constraint */

        ct->ct |= TCG_CT_REG;

        tcg_regset_set32(ct->u.regs, 0, 0xffff);

        tcg_regset_reset_reg (ct->u.regs, TCG_REG_R2);

        tcg_regset_reset_reg (ct->u.regs, TCG_REG_R3);

        tcg_regset_reset_reg (ct->u.regs, TCG_REG_R4);

        break;

    case 'a':                  /* force R2 for division */

        ct->ct |= TCG_CT_REG;

        tcg_regset_clear(ct->u.regs);

        tcg_regset_set_reg(ct->u.regs, TCG_REG_R2);

        break;

    case 'b':                  /* force R3 for division */

        ct->ct |= TCG_CT_REG;

        tcg_regset_clear(ct->u.regs);

        tcg_regset_set_reg(ct->u.regs, TCG_REG_R3);

        break;

    case 'A':

        ct->ct |= TCG_CT_CONST_S33;

        break;

    case 'I':

        ct->ct |= TCG_CT_CONST_S16;

        break;

    case 'J':

        ct->ct |= TCG_CT_CONST_S32;

        break;

    case 'O':

        ct->ct |= TCG_CT_CONST_ORI;

        break;

    case 'X':

        ct->ct |= TCG_CT_CONST_XORI;

        break;

    case 'C':

        /* ??? We have no insight here into whether the comparison is

           signed or unsigned.  The COMPARE IMMEDIATE insn uses a 32-bit

           signed immediate, and the COMPARE LOGICAL IMMEDIATE insn uses

           a 32-bit unsigned immediate.  If we were to use the (semi)

           obvious "val == (int32_t)val" we would be enabling unsigned

           comparisons vs very large numbers.  The only solution is to

           take the intersection of the ranges.  */

        /* ??? Another possible solution is to simply lie and allow all

           constants here and force the out-of-range values into a temp

           register in tgen_cmp when we have knowledge of the actual

           comparison code in use.  */

        ct->ct |= TCG_CT_CONST_U31;

        break;

    case 'Z':

        ct->ct |= TCG_CT_CONST_ZERO;

        break;

    default:

        return NULL;

    }

    return ct_str;

}


static uint64_t megasas_port_read(void *opaque, target_phys_addr_t addr,

                                  unsigned size)

{

    return megasas_mmio_read(opaque, addr & 0xff, size);

}


void arm_debug_excp_handler(CPUState *cs)

{

    /* Called by core code when a watchpoint or breakpoint fires;

     * need to check which one and raise the appropriate exception.

     */

    ARMCPU *cpu = ARM_CPU(cs);

    CPUARMState *env = &cpu->env;

    CPUWatchpoint *wp_hit = cs->watchpoint_hit;

    if (wp_hit) {

        if (wp_hit->flags & BP_CPU) {

            cs->watchpoint_hit = NULL;

            if (check_watchpoints(cpu)) {

                bool wnr = (wp_hit->flags & BP_WATCHPOINT_HIT_WRITE) != 0;

                bool same_el = arm_debug_target_el(env) == arm_current_el(env);

                if (extended_addresses_enabled(env)) {

                    env->exception.fsr = (1 << 9) | 0x22;

                } else {

                    env->exception.fsr = 0x2;

                }

                env->exception.vaddress = wp_hit->hitaddr;

                raise_exception(env, EXCP_DATA_ABORT,

                                syn_watchpoint(same_el, 0, wnr),

                                arm_debug_target_el(env));

            } else {

                cpu_resume_from_signal(cs, NULL);

            }

        }

    } else {

        uint64_t pc = is_a64(env) ? env->pc : env->regs[15];

        bool same_el = (arm_debug_target_el(env) == arm_current_el(env));

        /* (1) GDB breakpoints should be handled first.

         * (2) Do not raise a CPU exception if no CPU breakpoint has fired,

         * since singlestep is also done by generating a debug internal

         * exception.

         */

        if (cpu_breakpoint_test(cs, pc, BP_GDB)

            || !cpu_breakpoint_test(cs, pc, BP_CPU)) {

            return;

        }

        if (extended_addresses_enabled(env)) {

            env->exception.fsr = (1 << 9) | 0x22;

        } else {

            env->exception.fsr = 0x2;

        }

        /* FAR is UNKNOWN, so doesn't need setting */

        raise_exception(env, EXCP_PREFETCH_ABORT,

                        syn_breakpoint(same_el),

                        arm_debug_target_el(env));

    }

}


int load_elf_as(const char *filename,

                uint64_t (*translate_fn)(void *, uint64_t),

                void *translate_opaque, uint64_t *pentry, uint64_t *lowaddr,

                uint64_t *highaddr, int big_endian, int elf_machine,

                int clear_lsb, int data_swab, AddressSpace *as)

{

    int fd, data_order, target_data_order, must_swab, ret = ELF_LOAD_FAILED;

    uint8_t e_ident[EI_NIDENT];

    fd = open(filename, O_RDONLY | O_BINARY);

    if (fd < 0) {

        perror(filename);

        return -1;

    }

    if (read(fd, e_ident, sizeof(e_ident)) != sizeof(e_ident))

        goto fail;

    if (e_ident[0] != ELFMAG0 ||

        e_ident[1] != ELFMAG1 ||

        e_ident[2] != ELFMAG2 ||

        e_ident[3] != ELFMAG3) {

        ret = ELF_LOAD_NOT_ELF;

        goto fail;

    }

#ifdef HOST_WORDS_BIGENDIAN

    data_order = ELFDATA2MSB;

#else

    data_order = ELFDATA2LSB;

#endif

    must_swab = data_order != e_ident[EI_DATA];

    if (big_endian) {

        target_data_order = ELFDATA2MSB;

    } else {

        target_data_order = ELFDATA2LSB;

    }

    if (target_data_order != e_ident[EI_DATA]) {

        ret = ELF_LOAD_WRONG_ENDIAN;

        goto fail;

    }

    lseek(fd, 0, SEEK_SET);

    if (e_ident[EI_CLASS] == ELFCLASS64) {

        ret = load_elf64(filename, fd, translate_fn, translate_opaque, must_swab,

                         pentry, lowaddr, highaddr, elf_machine, clear_lsb,

                         data_swab, as);

    } else {

        ret = load_elf32(filename, fd, translate_fn, translate_opaque, must_swab,

                         pentry, lowaddr, highaddr, elf_machine, clear_lsb,

                         data_swab, as);

    }

 fail:

    close(fd);

    return ret;

}


static int vhost_net_start_one(struct vhost_net *net,

                               VirtIODevice *dev,

                               int vq_index)

{

    struct vhost_vring_file file = { };

    int r;

    if (net->dev.started) {

        return 0;

    }

    net->dev.nvqs = 2;

    net->dev.vqs = net->vqs;

    net->dev.vq_index = vq_index;

    r = vhost_dev_enable_notifiers(&net->dev, dev);

    if (r < 0) {

        goto fail_notifiers;

    }

    r = vhost_dev_start(&net->dev, dev);

    if (r < 0) {

        goto fail_start;

    }

    if (net->nc->info->poll) {

        net->nc->info->poll(net->nc, false);

    }

    if (net->nc->info->type == NET_CLIENT_OPTIONS_KIND_TAP) {

        qemu_set_fd_handler(net->backend, NULL, NULL, NULL);

        file.fd = net->backend;

        for (file.index = 0; file.index < net->dev.nvqs; ++file.index) {

            const VhostOps *vhost_ops = net->dev.vhost_ops;

            r = vhost_ops->vhost_call(&net->dev, VHOST_NET_SET_BACKEND,

                                      &file);

            if (r < 0) {

                r = -errno;

                goto fail;

            }

        }

    }

    return 0;

fail:

    file.fd = -1;

    if (net->nc->info->type == NET_CLIENT_OPTIONS_KIND_TAP) {

        while (file.index-- > 0) {

            const VhostOps *vhost_ops = net->dev.vhost_ops;

            int r = vhost_ops->vhost_call(&net->dev, VHOST_NET_SET_BACKEND,

                                          &file);

            assert(r >= 0);

        }

    }

    if (net->nc->info->poll) {

        net->nc->info->poll(net->nc, true);

    }

    vhost_dev_stop(&net->dev, dev);

fail_start:

    vhost_dev_disable_notifiers(&net->dev, dev);

fail_notifiers:

    return r;

}


mst_fpga_readb(void *opaque, target_phys_addr_t addr, unsigned size)

{

	mst_irq_state *s = (mst_irq_state *) opaque;

	switch (addr) {

	case MST_LEDDAT1:

		return s->leddat1;

	case MST_LEDDAT2:

		return s->leddat2;

	case MST_LEDCTRL:

		return s->ledctrl;

	case MST_GPSWR:

		return s->gpswr;

	case MST_MSCWR1:

		return s->mscwr1;

	case MST_MSCWR2:

		return s->mscwr2;

	case MST_MSCWR3:

		return s->mscwr3;

	case MST_MSCRD:

		return s->mscrd;

	case MST_INTMSKENA:

		return s->intmskena;

	case MST_INTSETCLR:

		return s->intsetclr;

	case MST_PCMCIA0:

		return s->pcmcia0;

	case MST_PCMCIA1:

		return s->pcmcia1;

	default:

		printf("Mainstone - mst_fpga_readb: Bad register offset "

			"0x" TARGET_FMT_plx "\n", addr);

	}

	return 0;

}


int ppcmas_tlb_check(CPUState *env, ppcmas_tlb_t *tlb,

                     target_phys_addr_t *raddrp,

                     target_ulong address, uint32_t pid)

{

    target_ulong mask;

    uint32_t tlb_pid;

    /* Check valid flag */

    if (!(tlb->mas1 & MAS1_VALID)) {

        return -1;

    }

    mask = ~(booke206_tlb_to_page_size(env, tlb) - 1);

    LOG_SWTLB("%s: TLB ADDR=0x" TARGET_FMT_lx " PID=0x%x MAS1=0x%x MAS2=0x%"

              PRIx64 " mask=0x" TARGET_FMT_lx " MAS7_3=0x%" PRIx64 " MAS8=%x\n",

              __func__, address, pid, tlb->mas1, tlb->mas2, mask, tlb->mas7_3,

              tlb->mas8);

    /* Check PID */

    tlb_pid = (tlb->mas1 & MAS1_TID_MASK) >> MAS1_TID_SHIFT;

    if (tlb_pid != 0 && tlb_pid != pid) {

        return -1;

    }

    /* Check effective address */

    if ((address & mask) != (tlb->mas2 & MAS2_EPN_MASK)) {

        return -1;

    }

    *raddrp = (tlb->mas7_3 & mask) | (address & ~mask);

    return 0;

}


static int libopenjpeg_encode_frame(AVCodecContext *avctx, AVPacket *pkt,

                                    const AVFrame *frame, int *got_packet)

{

    LibOpenJPEGContext *ctx = avctx->priv_data;

    opj_cinfo_t *compress = ctx->compress;

    opj_image_t *image    = ctx->image;

    opj_cio_t *stream     = ctx->stream;

    int cpyresult = 0;

    int ret, len;

    AVFrame *gbrframe;

    switch (avctx->pix_fmt) {

    case AV_PIX_FMT_RGB24:

    case AV_PIX_FMT_RGBA:

    case AV_PIX_FMT_GRAY8A:

        cpyresult = libopenjpeg_copy_packed8(avctx, frame, image);

        break;

    case AV_PIX_FMT_XYZ12:

        cpyresult = libopenjpeg_copy_packed12(avctx, frame, image);

        break;

    case AV_PIX_FMT_RGB48:

    case AV_PIX_FMT_RGBA64:

        cpyresult = libopenjpeg_copy_packed16(avctx, frame, image);

        break;

    case AV_PIX_FMT_GBR24P:

    case AV_PIX_FMT_GBRP9:

    case AV_PIX_FMT_GBRP10:

    case AV_PIX_FMT_GBRP12:

    case AV_PIX_FMT_GBRP14:

    case AV_PIX_FMT_GBRP16:

        gbrframe = av_frame_alloc();

        if (!gbrframe)

            return AVERROR(ENOMEM);

        av_frame_ref(gbrframe, frame);

        gbrframe->data[0] = frame->data[2]; // swap to be rgb

        gbrframe->data[1] = frame->data[0];

        gbrframe->data[2] = frame->data[1];

        gbrframe->linesize[0] = frame->linesize[2];

        gbrframe->linesize[1] = frame->linesize[0];

        gbrframe->linesize[2] = frame->linesize[1];

        if (avctx->pix_fmt == AV_PIX_FMT_GBR24P) {

            cpyresult = libopenjpeg_copy_unpacked8(avctx, gbrframe, image);

        } else {

            cpyresult = libopenjpeg_copy_unpacked16(avctx, gbrframe, image);

        }

        av_frame_free(&gbrframe);

        break;

    case AV_PIX_FMT_GRAY8:

    case AV_PIX_FMT_YUV410P:

    case AV_PIX_FMT_YUV411P:

    case AV_PIX_FMT_YUV420P:

    case AV_PIX_FMT_YUV422P:

    case AV_PIX_FMT_YUV440P:

    case AV_PIX_FMT_YUV444P:

    case AV_PIX_FMT_YUVA420P:

    case AV_PIX_FMT_YUVA422P:

    case AV_PIX_FMT_YUVA444P:

        cpyresult = libopenjpeg_copy_unpacked8(avctx, frame, image);

        break;

    case AV_PIX_FMT_GRAY16:

    case AV_PIX_FMT_YUV420P9:

    case AV_PIX_FMT_YUV422P9:

    case AV_PIX_FMT_YUV444P9:

    case AV_PIX_FMT_YUVA420P9:

    case AV_PIX_FMT_YUVA422P9:

    case AV_PIX_FMT_YUVA444P9:

    case AV_PIX_FMT_YUV444P10:

    case AV_PIX_FMT_YUV422P10:

    case AV_PIX_FMT_YUV420P10:

    case AV_PIX_FMT_YUVA444P10:

    case AV_PIX_FMT_YUVA422P10:

    case AV_PIX_FMT_YUVA420P10:

    case AV_PIX_FMT_YUV420P12:

    case AV_PIX_FMT_YUV422P12:

    case AV_PIX_FMT_YUV444P12:

    case AV_PIX_FMT_YUV420P14:

    case AV_PIX_FMT_YUV422P14:

    case AV_PIX_FMT_YUV444P14:

    case AV_PIX_FMT_YUV444P16:

    case AV_PIX_FMT_YUV422P16:

    case AV_PIX_FMT_YUV420P16:

    case AV_PIX_FMT_YUVA444P16:

    case AV_PIX_FMT_YUVA422P16:

    case AV_PIX_FMT_YUVA420P16:

        cpyresult = libopenjpeg_copy_unpacked16(avctx, frame, image);

        break;

    default:

        av_log(avctx, AV_LOG_ERROR,

               "The frame's pixel format '%s' is not supported\n",

               av_get_pix_fmt_name(avctx->pix_fmt));

        return AVERROR(EINVAL);

        break;

    }

    if (!cpyresult) {

        av_log(avctx, AV_LOG_ERROR,

               "Could not copy the frame data to the internal image buffer\n");

        return -1;

    }

    cio_seek(stream, 0);

    if (!opj_encode(compress, stream, image, NULL)) {

        av_log(avctx, AV_LOG_ERROR, "Error during the opj encode\n");

        return -1;

    }

    len = cio_tell(stream);

    if ((ret = ff_alloc_packet2(avctx, pkt, len)) < 0) {

        return ret;

    }

    memcpy(pkt->data, stream->buffer, len);

    pkt->flags |= AV_PKT_FLAG_KEY;

    *got_packet = 1;

    return 0;

}


static VFIOGroup *vfio_get_group(int groupid, AddressSpace *as)

{

    VFIOGroup *group;

    char path[32];

    struct vfio_group_status status = { .argsz = sizeof(status) };

    QLIST_FOREACH(group, &group_list, next) {

        if (group->groupid == groupid) {

            /* Found it.  Now is it already in the right context? */

            if (group->container->space->as == as) {

                return group;

            } else {

                error_report("vfio: group %d used in multiple address spaces",

                             group->groupid);

                return NULL;

            }

        }

    }

    group = g_malloc0(sizeof(*group));

    snprintf(path, sizeof(path), "/dev/vfio/%d", groupid);

    group->fd = qemu_open(path, O_RDWR);

    if (group->fd < 0) {

        error_report("vfio: error opening %s: %m", path);

        goto free_group_exit;

    }

    if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) {

        error_report("vfio: error getting group status: %m");

        goto close_fd_exit;

    }

    if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) {

        error_report("vfio: error, group %d is not viable, please ensure "

                     "all devices within the iommu_group are bound to their "

                     "vfio bus driver.", groupid);

        goto close_fd_exit;

    }

    group->groupid = groupid;

    QLIST_INIT(&group->device_list);

    if (vfio_connect_container(group, as)) {

        error_report("vfio: failed to setup container for group %d", groupid);

        goto close_fd_exit;

    }

    if (QLIST_EMPTY(&group_list)) {

        qemu_register_reset(vfio_pci_reset_handler, NULL);

    }

    QLIST_INSERT_HEAD(&group_list, group, next);

    vfio_kvm_device_add_group(group);

    return group;

close_fd_exit:

    close(group->fd);

free_group_exit:

    g_free(group);

    return NULL;

}


int main_loop_init(void)

{

    int ret;

    qemu_mutex_lock_iothread();

    ret = qemu_signal_init();

    if (ret) {

        return ret;

    }

    /* Note eventfd must be drained before signalfd handlers run */

    ret = qemu_event_init();

    if (ret) {

        return ret;

    }

    return 0;

}


bool aio_poll(AioContext *ctx, bool blocking)

{

    AioHandler *node;

    int i;

    int ret = 0;

    bool progress;

    int64_t timeout;

    int64_t start = 0;

    /* aio_notify can avoid the expensive event_notifier_set if

     * everything (file descriptors, bottom halves, timers) will

     * be re-evaluated before the next blocking poll().  This is

     * already true when aio_poll is called with blocking == false;

     * if blocking == true, it is only true after poll() returns,

     * so disable the optimization now.

     */

    if (blocking) {

        atomic_add(&ctx->notify_me, 2);

    }

    qemu_lockcnt_inc(&ctx->list_lock);

    if (ctx->poll_max_ns) {

        start = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);

    }

    progress = try_poll_mode(ctx, blocking);

    if (!progress) {

        assert(npfd == 0);

        /* fill pollfds */

        if (!aio_epoll_enabled(ctx)) {

            QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {

                if (!node->deleted && node->pfd.events

                    && aio_node_check(ctx, node->is_external)) {

                    add_pollfd(node);

                }

            }

        }

        timeout = blocking ? aio_compute_timeout(ctx) : 0;

        /* wait until next event */

        if (aio_epoll_check_poll(ctx, pollfds, npfd, timeout)) {

            AioHandler epoll_handler;

            epoll_handler.pfd.fd = ctx->epollfd;

            epoll_handler.pfd.events = G_IO_IN | G_IO_OUT | G_IO_HUP | G_IO_ERR;

            npfd = 0;

            add_pollfd(&epoll_handler);

            ret = aio_epoll(ctx, pollfds, npfd, timeout);

        } else  {

            ret = qemu_poll_ns(pollfds, npfd, timeout);

        }

    }

    if (blocking) {

        atomic_sub(&ctx->notify_me, 2);

    }

    /* Adjust polling time */

    if (ctx->poll_max_ns) {

        int64_t block_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - start;

        if (block_ns <= ctx->poll_ns) {

            /* This is the sweet spot, no adjustment needed */

        } else if (block_ns > ctx->poll_max_ns) {

            /* We'd have to poll for too long, poll less */

            int64_t old = ctx->poll_ns;

            if (ctx->poll_shrink) {

                ctx->poll_ns /= ctx->poll_shrink;

            } else {

                ctx->poll_ns = 0;

            }

            trace_poll_shrink(ctx, old, ctx->poll_ns);

        } else if (ctx->poll_ns < ctx->poll_max_ns &&

                   block_ns < ctx->poll_max_ns) {

            /* There is room to grow, poll longer */

            int64_t old = ctx->poll_ns;

            int64_t grow = ctx->poll_grow;

            if (grow == 0) {

                grow = 2;

            }

            if (ctx->poll_ns) {

                ctx->poll_ns *= grow;

            } else {

                ctx->poll_ns = 4000; /* start polling at 4 microseconds */

            }

            if (ctx->poll_ns > ctx->poll_max_ns) {

                ctx->poll_ns = ctx->poll_max_ns;

            }

            trace_poll_grow(ctx, old, ctx->poll_ns);

        }

    }

    aio_notify_accept(ctx);

    /* if we have any readable fds, dispatch event */

    if (ret > 0) {

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

            nodes[i]->pfd.revents = pollfds[i].revents;

        }

    }

    npfd = 0;

    qemu_lockcnt_dec(&ctx->list_lock);

    /* Run dispatch even if there were no readable fds to run timers */

    if (aio_dispatch(ctx, ret > 0)) {

        progress = true;

    }

    return progress;

}


void qio_channel_socket_listen_async(QIOChannelSocket *ioc,

                                     SocketAddress *addr,

                                     QIOTaskFunc callback,

                                     gpointer opaque,

                                     GDestroyNotify destroy)

{

    QIOTask *task = qio_task_new(

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

    SocketAddress *addrCopy;

    addrCopy = QAPI_CLONE(SocketAddress, addr);

    /* socket_listen() blocks in DNS lookups, so we must use a thread */

    trace_qio_channel_socket_listen_async(ioc, addr);

    qio_task_run_in_thread(task,

                           qio_channel_socket_listen_worker,

                           addrCopy,

                           (GDestroyNotify)qapi_free_SocketAddress);

}