static int hwupload_query_formats(AVFilterContext *avctx)

{

    HWUploadContext *ctx = avctx->priv;

    AVHWFramesConstraints *constraints = NULL;

    const enum AVPixelFormat *input_pix_fmts, *output_pix_fmts;

    AVFilterFormats *input_formats = NULL;

    int err, i;

    if (!avctx->hw_device_ctx) {

        av_log(ctx, AV_LOG_ERROR, "A hardware device reference is required "

               "to upload frames to.\n");

        return AVERROR(EINVAL);

    }

    ctx->hwdevice_ref = av_buffer_ref(avctx->hw_device_ctx);

    if (!ctx->hwdevice_ref)

        return AVERROR(ENOMEM);

    ctx->hwdevice = (AVHWDeviceContext*)ctx->hwdevice_ref->data;

    constraints = av_hwdevice_get_hwframe_constraints(ctx->hwdevice_ref, NULL);

    if (!constraints) {

        err = AVERROR(EINVAL);

        goto fail;

    }

    input_pix_fmts  = constraints->valid_sw_formats;

    output_pix_fmts = constraints->valid_hw_formats;

    input_formats = ff_make_format_list(output_pix_fmts);

    if (!input_formats) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    if (input_pix_fmts) {

        for (i = 0; input_pix_fmts[i] != AV_PIX_FMT_NONE; i++) {

            err = ff_add_format(&input_formats, input_pix_fmts[i]);

            if (err < 0) {

                ff_formats_unref(&input_formats);

                goto fail;

            }

        }

    }

    ff_formats_ref(input_formats, &avctx->inputs[0]->out_formats);

    ff_formats_ref(ff_make_format_list(output_pix_fmts),

                   &avctx->outputs[0]->in_formats);

    av_hwframe_constraints_free(&constraints);

    return 0;

fail:

    av_buffer_unref(&ctx->hwdevice_ref);

    av_hwframe_constraints_free(&constraints);

    return err;

}


void error_setg_win32(Error **errp, int win32_err, const char *fmt, ...)

{

    va_list ap;

    char *msg1, *msg2;

    if (errp == NULL) {

        return;

    }

    va_start(ap, fmt);

    error_setv(errp, ERROR_CLASS_GENERIC_ERROR, fmt, ap);

    va_end(ap);

    if (win32_err != 0) {

        msg1 = (*errp)->msg;

        msg2 = g_win32_error_message(win32_err);

        (*errp)->msg = g_strdup_printf("%s: %s (error: %x)", msg1, msg2,

                                       (unsigned)win32_err);

        g_free(msg2);

        g_free(msg1);

    }

}


void ff_MPV_frame_end(MpegEncContext *s)

{

    int i;

    /* redraw edges for the frame if decoding didn't complete */

    // just to make sure that all data is rendered.

    if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration) {

        ff_xvmc_field_end(s);

   } else if((s->error_count || s->encoding || !(s->avctx->codec->capabilities&CODEC_CAP_DRAW_HORIZ_BAND)) &&

              !s->avctx->hwaccel &&

              !(s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) &&

              s->unrestricted_mv &&

              s->current_picture.f.reference &&

              !s->intra_only &&

              !(s->flags & CODEC_FLAG_EMU_EDGE)) {

        int hshift = av_pix_fmt_descriptors[s->avctx->pix_fmt].log2_chroma_w;

        int vshift = av_pix_fmt_descriptors[s->avctx->pix_fmt].log2_chroma_h;

        s->dsp.draw_edges(s->current_picture.f.data[0], s->current_picture.f.linesize[0],

                          s->h_edge_pos, s->v_edge_pos,

                          EDGE_WIDTH, EDGE_WIDTH,

                          EDGE_TOP | EDGE_BOTTOM);

        s->dsp.draw_edges(s->current_picture.f.data[1], s->current_picture.f.linesize[1],

                          s->h_edge_pos >> hshift, s->v_edge_pos >> vshift,

                          EDGE_WIDTH >> hshift, EDGE_WIDTH >> vshift,

                          EDGE_TOP | EDGE_BOTTOM);

        s->dsp.draw_edges(s->current_picture.f.data[2], s->current_picture.f.linesize[2],

                          s->h_edge_pos >> hshift, s->v_edge_pos >> vshift,

                          EDGE_WIDTH >> hshift, EDGE_WIDTH >> vshift,

                          EDGE_TOP | EDGE_BOTTOM);

    }

    emms_c();

    s->last_pict_type                 = s->pict_type;

    s->last_lambda_for [s->pict_type] = s->current_picture_ptr->f.quality;

    if (s->pict_type!= AV_PICTURE_TYPE_B) {

        s->last_non_b_pict_type = s->pict_type;

    }

#if 0

    /* copy back current_picture variables */

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

        if (s->picture[i].f.data[0] == s->current_picture.f.data[0]) {

            s->picture[i] = s->current_picture;

            break;

        }

    }

    assert(i < MAX_PICTURE_COUNT);

#endif

    if (s->encoding) {

        /* release non-reference frames */

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

            if (s->picture[i].f.data[0] && !s->picture[i].f.reference

                /* && s->picture[i].type != FF_BUFFER_TYPE_SHARED */) {

                free_frame_buffer(s, &s->picture[i]);

            }

        }

    }

    // clear copies, to avoid confusion

#if 0

    memset(&s->last_picture,    0, sizeof(Picture));

    memset(&s->next_picture,    0, sizeof(Picture));

    memset(&s->current_picture, 0, sizeof(Picture));

#endif

    s->avctx->coded_frame = &s->current_picture_ptr->f;

    if (s->codec_id != AV_CODEC_ID_H264 && s->current_picture.f.reference) {

        ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);

    }

}


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

{

    int size, l;

    if (f->is_write)

        abort();

    size = size1;

    while (size > 0) {

        l = f->buf_size - f->buf_index;

        if (l == 0) {

            qemu_fill_buffer(f);

            l = f->buf_size - f->buf_index;

            if (l == 0)

                break;

        }

        if (l > size)

            l = size;

        memcpy(buf, f->buf + f->buf_index, l);

        f->buf_index += l;

        buf += l;

        size -= l;

    }

    return size1 - size;

}


void *rom_ptr(target_phys_addr_t addr)

{

    Rom *rom;

    rom = find_rom(addr);

    if (!rom || !rom->data)

        return NULL;

    return rom->data + (addr - rom->addr);

}


static void *do_data_decompress(void *opaque)

{

    DecompressParam *param = opaque;

    unsigned long pagesize;

    while (!quit_decomp_thread) {

        qemu_mutex_lock(&param->mutex);

        while (!param->start && !quit_decomp_thread) {

            qemu_cond_wait(&param->cond, &param->mutex);

        }

        if (!quit_decomp_thread) {

            pagesize = TARGET_PAGE_SIZE;

            /* uncompress() will return failed in some case, especially

             * when the page is dirted when doing the compression, it's

             * not a problem because the dirty page will be retransferred

             * and uncompress() won't break the data in other pages.

             */

            uncompress((Bytef *)param->des, &pagesize,

                       (const Bytef *)param->compbuf, param->len);

        }

        param->start = false;

        qemu_mutex_unlock(&param->mutex);

        qemu_mutex_lock(&decomp_done_lock);

        param->done = true;

        qemu_cond_signal(&decomp_done_cond);

        qemu_mutex_unlock(&decomp_done_lock);

    }

    return NULL;

}


long do_sigreturn(CPUSH4State *regs)

{

    struct target_sigframe *frame;

    abi_ulong frame_addr;

    sigset_t blocked;

    target_sigset_t target_set;

    target_ulong r0;

    int i;

    int err = 0;

#if defined(DEBUG_SIGNAL)

    fprintf(stderr, "do_sigreturn\n");

#endif

    frame_addr = regs->gregs[15];

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

   	goto badframe;

    __get_user(target_set.sig[0], &frame->sc.oldmask);

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

        __get_user(target_set.sig[i], &frame->extramask[i - 1]);

    }

    if (err)

        goto badframe;

    target_to_host_sigset_internal(&blocked, &target_set);

    do_sigprocmask(SIG_SETMASK, &blocked, NULL);

    if (restore_sigcontext(regs, &frame->sc, &r0))

        goto badframe;

    unlock_user_struct(frame, frame_addr, 0);

    return r0;

badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV);

    return 0;

}


static void apic_reset_common(DeviceState *dev)

{

    APICCommonState *s = APIC_COMMON(dev);

    APICCommonClass *info = APIC_COMMON_GET_CLASS(s);

    bool bsp;

    bsp = cpu_is_bsp(s->cpu);

    s->apicbase = APIC_DEFAULT_ADDRESS |

        (bsp ? MSR_IA32_APICBASE_BSP : 0) | MSR_IA32_APICBASE_ENABLE;

    s->vapic_paddr = 0;

    info->vapic_base_update(s);

    apic_init_reset(dev);

    if (bsp) {

        /*

         * LINT0 delivery mode on CPU #0 is set to ExtInt at initialization

         * time typically by BIOS, so PIC interrupt can be delivered to the

         * processor when local APIC is enabled.

         */

        s->lvt[APIC_LVT_LINT0] = 0x700;

    }

}


static void omap_pwt_init(target_phys_addr_t base, struct omap_mpu_state_s *s,

                omap_clk clk)

{

    int iomemtype;

    s->pwt.base = base;

    s->pwt.clk = clk;

    omap_pwt_reset(s);

    iomemtype = cpu_register_io_memory(0, omap_pwt_readfn,

                    omap_pwt_writefn, s);

    cpu_register_physical_memory(s->pwt.base, 0x800, iomemtype);

}


int vnc_hextile_send_framebuffer_update(VncState *vs, int x,

                                        int y, int w, int h)

{

    int i, j;

    int has_fg, has_bg;

    uint8_t *last_fg, *last_bg;

    VncDisplay *vd = vs->vd;

    last_fg = (uint8_t *) qemu_malloc(vd->server->pf.bytes_per_pixel);

    last_bg = (uint8_t *) qemu_malloc(vd->server->pf.bytes_per_pixel);

    has_fg = has_bg = 0;

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

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

            vs->send_hextile_tile(vs, i, j,

                                  MIN(16, x + w - i), MIN(16, y + h - j),

                                  last_bg, last_fg, &has_bg, &has_fg);

        }

    }

    free(last_fg);

    free(last_bg);

    return 1;

}


static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,

                        uint8_t *buf, int nb_sectors)

{

    int async_ret;

    BlockDriverAIOCB *acb;

    struct iovec iov;

    QEMUIOVector qiov;

    async_ret = NOT_DONE;

    iov.iov_base = (void *)buf;

    iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;

    qemu_iovec_init_external(&qiov, &iov, 1);

    acb = bs->drv->bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,

                                  bdrv_rw_em_cb, &async_ret);

    if (acb == NULL) {

        async_ret = -1;

        goto fail;

    }

    while (async_ret == NOT_DONE) {

        qemu_aio_wait();

    }

fail:

    return async_ret;

}


static int kvmppc_get_books_sregs(PowerPCCPU *cpu)

{

    CPUPPCState *env = &cpu->env;

    struct kvm_sregs sregs;

    int ret;

    int i;

    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);

    if (ret < 0) {

        return ret;

    }

    if (!env->external_htab) {

        ppc_store_sdr1(env, sregs.u.s.sdr1);

    }

    /* Sync SLB */

#ifdef TARGET_PPC64

    /*

     * The packed SLB array we get from KVM_GET_SREGS only contains

     * information about valid entries. So we flush our internal copy

     * to get rid of stale ones, then put all valid SLB entries back

     * in.

     */

    memset(env->slb, 0, sizeof(env->slb));

    for (i = 0; i < ARRAY_SIZE(env->slb); i++) {

        target_ulong rb = sregs.u.s.ppc64.slb[i].slbe;

        target_ulong rs = sregs.u.s.ppc64.slb[i].slbv;

        /*

         * Only restore valid entries

         */

        if (rb & SLB_ESID_V) {

            ppc_store_slb(cpu, rb & 0xfff, rb & ~0xfffULL, rs);

        }

    }

#endif

    /* Sync SRs */

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

        env->sr[i] = sregs.u.s.ppc32.sr[i];

    }

    /* Sync BATs */

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

        env->DBAT[0][i] = sregs.u.s.ppc32.dbat[i] & 0xffffffff;

        env->DBAT[1][i] = sregs.u.s.ppc32.dbat[i] >> 32;

        env->IBAT[0][i] = sregs.u.s.ppc32.ibat[i] & 0xffffffff;

        env->IBAT[1][i] = sregs.u.s.ppc32.ibat[i] >> 32;

    }

    return 0;

}


static void integratorcp_init(ram_addr_t ram_size, int vga_ram_size,

                     const char *boot_device, DisplayState *ds,

                     const char *kernel_filename, const char *kernel_cmdline,

                     const char *initrd_filename, const char *cpu_model)

{

    CPUState *env;

    uint32_t ram_offset;

    qemu_irq *pic;

    qemu_irq *cpu_pic;

    int sd;

    if (!cpu_model)

        cpu_model = "arm926";

    env = cpu_init(cpu_model);

    if (!env) {

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

        exit(1);

    }

    ram_offset = qemu_ram_alloc(ram_size);

    /* ??? On a real system the first 1Mb is mapped as SSRAM or boot flash.  */

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

    /* SDRAM at address zero*/

    cpu_register_physical_memory(0, ram_size, ram_offset | IO_MEM_RAM);

    /* And again at address 0x80000000 */

    cpu_register_physical_memory(0x80000000, ram_size, ram_offset | IO_MEM_RAM);

    integratorcm_init(ram_size >> 20);

    cpu_pic = arm_pic_init_cpu(env);

    pic = icp_pic_init(0x14000000, cpu_pic[ARM_PIC_CPU_IRQ],

                       cpu_pic[ARM_PIC_CPU_FIQ]);

    icp_pic_init(0xca000000, pic[26], NULL);

    icp_pit_init(0x13000000, pic, 5);

    pl031_init(0x15000000, pic[8]);

    pl011_init(0x16000000, pic[1], serial_hds[0], PL011_ARM);

    pl011_init(0x17000000, pic[2], serial_hds[1], PL011_ARM);

    icp_control_init(0xcb000000);

    pl050_init(0x18000000, pic[3], 0);

    pl050_init(0x19000000, pic[4], 1);

    sd = drive_get_index(IF_SD, 0, 0);

    if (sd == -1) {

        fprintf(stderr, "qemu: missing SecureDigital card\n");

        exit(1);

    }

    pl181_init(0x1c000000, drives_table[sd].bdrv, pic[23], pic[24]);

    if (nd_table[0].vlan) {

        if (nd_table[0].model == NULL

            || strcmp(nd_table[0].model, "smc91c111") == 0) {

            smc91c111_init(&nd_table[0], 0xc8000000, pic[27]);

        } else if (strcmp(nd_table[0].model, "?") == 0) {

            fprintf(stderr, "qemu: Supported NICs: smc91c111\n");

            exit (1);

        } else {

            fprintf(stderr, "qemu: Unsupported NIC: %s\n", nd_table[0].model);

            exit (1);

        }

    }

    pl110_init(ds, 0xc0000000, pic[22], 0);

    integrator_binfo.ram_size = ram_size;

    integrator_binfo.kernel_filename = kernel_filename;

    integrator_binfo.kernel_cmdline = kernel_cmdline;

    integrator_binfo.initrd_filename = initrd_filename;

    arm_load_kernel(env, &integrator_binfo);

}


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

{

    BlockInfoList *bdev_list, *bdev;

    Error *err = NULL;

    bdev_list = qmp_query_block(NULL);

    for (bdev = bdev_list; bdev; bdev = bdev->next) {

        if (key_is_missing(bdev->value)) {

            monitor_read_block_device_key(mon, bdev->value->device,

                                          hmp_cont_cb, NULL);

            goto out;

        }

    }

    qmp_cont(&err);

    hmp_handle_error(mon, &err);

out:

    qapi_free_BlockInfoList(bdev_list);

}


static int decode_5(SANMVideoContext *ctx)

{

#if HAVE_BIGENDIAN

    uint16_t *frm;

    int npixels;

#endif

    uint8_t *dst = (uint8_t*)ctx->frm0;

    if (rle_decode(ctx, dst, ctx->buf_size))

        return AVERROR_INVALIDDATA;

#if HAVE_BIGENDIAN

    npixels = ctx->npixels;

    frm = ctx->frm0;

    while (npixels--)

        *frm++ = av_bswap16(*frm);

#endif

    return 0;

}


static void aux_bridge_init(Object *obj)

{

    AUXTOI2CState *s = AUXTOI2C(obj);

    s->i2c_bus = i2c_init_bus(DEVICE(obj), "aux-i2c");

}


static void bdrv_co_drain_bh_cb(void *opaque)

{

    BdrvCoDrainData *data = opaque;

    Coroutine *co = data->co;

    qemu_bh_delete(data->bh);

    bdrv_drain_poll(data->bs);

    data->done = true;

    qemu_coroutine_enter(co, NULL);

}


static int add_graphics_client(Monitor *mon, const QDict *qdict, QObject **ret_data)

{

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

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

    CharDriverState *s;

    if (strcmp(protocol, "spice") == 0) {

        int fd = monitor_get_fd(mon, fdname, NULL);

        int skipauth = qdict_get_try_bool(qdict, "skipauth", 0);

        int tls = qdict_get_try_bool(qdict, "tls", 0);

        if (!using_spice) {

            /* correct one? spice isn't a device ,,, */

            qerror_report(QERR_DEVICE_NOT_ACTIVE, "spice");

            return -1;

        }

        if (qemu_spice_display_add_client(fd, skipauth, tls) < 0) {

            close(fd);

        }

        return 0;

#ifdef CONFIG_VNC

    } else if (strcmp(protocol, "vnc") == 0) {

	int fd = monitor_get_fd(mon, fdname, NULL);

        int skipauth = qdict_get_try_bool(qdict, "skipauth", 0);

	vnc_display_add_client(NULL, fd, skipauth);

	return 0;

#endif

    } else if ((s = qemu_chr_find(protocol)) != NULL) {

	int fd = monitor_get_fd(mon, fdname, NULL);

	if (qemu_chr_add_client(s, fd) < 0) {

	    qerror_report(QERR_ADD_CLIENT_FAILED);

	    return -1;

	}

	return 0;

    }

    qerror_report(QERR_INVALID_PARAMETER, "protocol");

    return -1;

}


static gboolean qio_channel_tls_handshake_io(QIOChannel *ioc,

                                             GIOCondition condition,

                                             gpointer user_data)

{

    QIOTask *task = user_data;

    QIOChannelTLS *tioc = QIO_CHANNEL_TLS(

        qio_task_get_source(task));

    qio_channel_tls_handshake_task(

       tioc, task);

    object_unref(OBJECT(tioc));

    return FALSE;

}


static void pm_update_sci(VT686PMState *s)

{

    int sci_level, pmsts;

    pmsts = acpi_pm1_evt_get_sts(&s->ar, s->ar.tmr.overflow_time);

    sci_level = (((pmsts & s->ar.pm1.evt.en) &

                  (ACPI_BITMASK_RT_CLOCK_ENABLE |

                   ACPI_BITMASK_POWER_BUTTON_ENABLE |

                   ACPI_BITMASK_GLOBAL_LOCK_ENABLE |

                   ACPI_BITMASK_TIMER_ENABLE)) != 0);

    qemu_set_irq(s->dev.irq[0], sci_level);

    /* schedule a timer interruption if needed */

    acpi_pm_tmr_update(&s->ar, (s->ar.pm1.evt.en & ACPI_BITMASK_TIMER_ENABLE) &&

                       !(pmsts & ACPI_BITMASK_TIMER_STATUS));

}


static void flat_print_key_prefix(WriterContext *wctx)

{

    FlatContext *flat = wctx->priv;

    const struct section *parent_section = wctx->section[wctx->level-1];

    printf("%s", flat->section_header[wctx->level].str);

    if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {

        int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?

            wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];

        printf("%d%s", n, flat->sep_str);

    }

}


static int sdp_parse_fmtp_config_h264(AVStream *stream,

                                      PayloadContext *h264_data,

                                      char *attr, char *value)

{

    AVCodecContext *codec = stream->codec;

    assert(codec->codec_id == CODEC_ID_H264);

    assert(h264_data != NULL);

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

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

        h264_data->packetization_mode = atoi(value);

        /*

         * Packetization Mode:

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

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

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

         *                      and 29 (FU-B) are allowed.

         */

        if (h264_data->packetization_mode > 1)

            av_log(codec, AV_LOG_ERROR,

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

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

        if (strlen(value) == 6) {

            char buffer[3];

            // 6 characters=3 bytes, in hex.

            uint8_t profile_idc;

            uint8_t profile_iop;

            uint8_t level_idc;

            buffer[0]   = value[0];

            buffer[1]   = value[1];

            buffer[2]   = '\0';

            profile_idc = strtol(buffer, NULL, 16);

            buffer[0]   = value[2];

            buffer[1]   = value[3];

            profile_iop = strtol(buffer, NULL, 16);

            buffer[0]   = value[4];

            buffer[1]   = value[5];

            level_idc   = strtol(buffer, NULL, 16);

            av_log(codec, AV_LOG_DEBUG,

                   "RTP Profile IDC: %x Profile IOP: %x Level: %x\n",

                   profile_idc, profile_iop, level_idc);

            h264_data->profile_idc = profile_idc;

            h264_data->profile_iop = profile_iop;

            h264_data->level_idc   = level_idc;

        }

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

        codec->extradata_size = 0;

        codec->extradata      = NULL;

        while (*value) {

            char base64packet[1024];

            uint8_t decoded_packet[1024];

            int packet_size;

            char *dst = base64packet;

            while (*value && *value != ','

                   && (dst - base64packet) < sizeof(base64packet) - 1) {

                *dst++ = *value++;

            }

            *dst++ = '\0';

            if (*value == ',')

                value++;

            packet_size = av_base64_decode(decoded_packet, base64packet,

                                           sizeof(decoded_packet));

            if (packet_size > 0) {

                uint8_t *dest = av_malloc(packet_size + sizeof(start_sequence) +

                                          codec->extradata_size +

                                          FF_INPUT_BUFFER_PADDING_SIZE);

                if (!dest) {

                    av_log(codec, AV_LOG_ERROR,

                           "Unable to allocate memory for extradata!");

                    return AVERROR(ENOMEM);

                }

                if (codec->extradata_size) {

                    memcpy(dest, codec->extradata, codec->extradata_size);

                    av_free(codec->extradata);

                }

                memcpy(dest + codec->extradata_size, start_sequence,

                       sizeof(start_sequence));

                memcpy(dest + codec->extradata_size + sizeof(start_sequence),

                       decoded_packet, packet_size);

                memset(dest + codec->extradata_size + sizeof(start_sequence) +

                       packet_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);

                codec->extradata       = dest;

                codec->extradata_size += sizeof(start_sequence) + packet_size;

            }

        }

        av_log(codec, AV_LOG_DEBUG, "Extradata set to %p (size: %d)!",

               codec->extradata, codec->extradata_size);

    }

    return 0;

}


static int qcow2_create2(const char *filename, int64_t total_size,
                         const char *backing_file, const char *backing_format,
                         int flags, size_t cluster_size, int prealloc,
                         QEMUOptionParameter *options, int version,
                         Error **errp)
{
    /* Calculate cluster_bits */
    int cluster_bits;
    cluster_bits = ffs(cluster_size) - 1;
    if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
        (1 << cluster_bits) != cluster_size)
    {
        error_setg(errp, "Cluster size must be a power of two between %d and "
                   "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
        return -EINVAL;
    /*
     * Open the image file and write a minimal qcow2 header.
     *
     * We keep things simple and start with a zero-sized image. We also
     * do without refcount blocks or a L1 table for now. We'll fix the
     * inconsistency later.
     *
     * We do need a refcount table because growing the refcount table means
     * allocating two new refcount blocks - the seconds of which would be at
     * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
     * size for any qcow2 image.
     */
    BlockDriverState* bs;
    QCowHeader header;
    uint8_t* refcount_table;
    Error *local_err = NULL;
    int ret;
    ret = bdrv_create_file(filename, options, &local_err);
    if (ret < 0) {
        return ret;
    ret = bdrv_file_open(&bs, filename, NULL, BDRV_O_RDWR, &local_err);
    if (ret < 0) {
        return ret;
    /* Write the header */
    memset(&header, 0, sizeof(header));
    header.magic = cpu_to_be32(QCOW_MAGIC);
    header.version = cpu_to_be32(version);
    header.cluster_bits = cpu_to_be32(cluster_bits);
    header.size = cpu_to_be64(0);
    header.l1_table_offset = cpu_to_be64(0);
    header.l1_size = cpu_to_be32(0);
    header.refcount_table_offset = cpu_to_be64(cluster_size);
    header.refcount_table_clusters = cpu_to_be32(1);
    header.refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT);
    header.header_length = cpu_to_be32(sizeof(header));
    if (flags & BLOCK_FLAG_ENCRYPT) {
        header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
    } else {
        header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
    if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
        header.compatible_features |=
            cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
    ret = bdrv_pwrite(bs, 0, &header, sizeof(header));
    if (ret < 0) {
        error_setg_errno(errp, -ret, "Could not write qcow2 header");
    /* Write an empty refcount table */
    refcount_table = g_malloc0(cluster_size);
    ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
    g_free(refcount_table);
    if (ret < 0) {
        error_setg_errno(errp, -ret, "Could not write refcount table");
    /*
     * And now open the image and make it consistent first (i.e. increase the
     * refcount of the cluster that is occupied by the header and the refcount
     * table)
     */
    BlockDriver* drv = bdrv_find_format("qcow2");
    assert(drv != NULL);
        BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, &local_err);
    if (ret < 0) {
    ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
    if (ret < 0) {
        error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
                         "header and refcount table");
    } else if (ret != 0) {
        error_report("Huh, first cluster in empty image is already in use?");
        abort();
    /* Okay, now that we have a valid image, let's give it the right size */
    ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
    if (ret < 0) {
        error_setg_errno(errp, -ret, "Could not resize image");
    /* Want a backing file? There you go.*/
    if (backing_file) {
        ret = bdrv_change_backing_file(bs, backing_file, backing_format);
        if (ret < 0) {
            error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
                             "with format '%s'", backing_file, backing_format);
    /* And if we're supposed to preallocate metadata, do that now */
    if (prealloc) {
        BDRVQcowState *s = bs->opaque;
        qemu_co_mutex_lock(&s->lock);
        ret = preallocate(bs);
        qemu_co_mutex_unlock(&s->lock);
        if (ret < 0) {
            error_setg_errno(errp, -ret, "Could not preallocate metadata");
    ret = 0;
out:
    bdrv_unref(bs);
    return ret;


static void idr(H264Context *h){

    int i;

    ff_h264_remove_all_refs(h);

    h->prev_frame_num= -1;

    h->prev_frame_num_offset= 0;

    h->prev_poc_msb= 1<<16;

    h->prev_poc_lsb= 0;

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

        h->last_pocs[i] = INT_MIN;

}


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

{

    IntelHDAState *d = opaque;

    const IntelHDAReg *reg = intel_hda_reg_find(d, addr);

    intel_hda_reg_write(d, reg, val, 0xffffffff);

}


static void abort_codec_experimental(AVCodec *c, int encoder)

{

    const char *codec_string = encoder ? "encoder" : "decoder";

    AVCodec *codec;

    av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "

            "results.\nAdd '-strict experimental' if you want to use it.\n",

            codec_string, c->name);

    codec = encoder ? avcodec_find_encoder(c->id) : avcodec_find_decoder(c->id);

    if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))

        av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",

               codec_string, codec->name);

    exit(1);

}


static inline void hyscale_fast_c(SwsContext *c, int16_t *dst, int dstWidth,

                                  const uint8_t *src, int srcW, int xInc)

{

    int i;

    unsigned int xpos=0;

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

        register unsigned int xx=xpos>>16;

        register unsigned int xalpha=(xpos&0xFFFF)>>9;

        dst[i]= (src[xx]<<7) + (src[xx+1] - src[xx])*xalpha;

        xpos+=xInc;

    }

}


static int standard_decode_i_mbs(VC9Context *v)

{

    GetBitContext *gb = &v->s.gb;

    MpegEncContext *s = &v->s;

    int current_mb = 0; /* MB/Block Position info */

    uint8_t cbpcy[4], previous_cbpcy[4], predicted_cbpcy,

        *p_cbpcy /* Pointer to skip some math */;

    /* Reset CBPCY predictors */

    memset(v->previous_line_cbpcy, 0, s->mb_stride<<2);

    /* Select ttmb table depending on pq */

    if (v->pq < 5) v->ttmb_vlc = &vc9_ttmb_vlc[0];

    else if (v->pq < 13) v->ttmb_vlc = &vc9_ttmb_vlc[1];

    else v->ttmb_vlc = &vc9_ttmb_vlc[2];

    for (s->mb_y=0; s->mb_y<s->mb_height; s->mb_y++)

    {

        /* Init CBPCY for line */

        *((uint32_t*)previous_cbpcy) = 0x00000000;

        p_cbpcy = v->previous_line_cbpcy+4;

        for (s->mb_x=0; s->mb_x<s->mb_width; s->mb_x++, p_cbpcy += 4)

        {

            /* Get CBPCY */

            GET_CBPCY(ff_msmp4_mb_i_vlc.table, MB_INTRA_VLC_BITS);

            s->ac_pred = get_bits(gb, 1);

            /* TODO: Decode blocks from that mb wrt cbpcy */

            /* Update for next block */

#if TRACE > 2

            av_log(s->avctx, AV_LOG_DEBUG, "Block %4i: p_cbpcy=%i%i%i%i, previous_cbpcy=%i%i%i%i,"

                   " cbpcy=%i%i%i%i\n", current_mb,

                   p_cbpcy[0], p_cbpcy[1], p_cbpcy[2], p_cbpcy[3],

                   previous_cbpcy[0], previous_cbpcy[1], previous_cbpcy[2], previous_cbpcy[3],

                   cbpcy[0], cbpcy[1], cbpcy[2], cbpcy[3]);

#endif

            *((uint32_t*)p_cbpcy) = *((uint32_t*)previous_cbpcy);

            *((uint32_t*)previous_cbpcy) = *((uint32_t*)cbpcy);

            current_mb++;

        }

    }

    return 0;

}


static int jazz_led_init(SysBusDevice *dev)

{

    LedState *s = FROM_SYSBUS(LedState, dev);

    memory_region_init_io(&s->iomem, &led_ops, s, "led", 1);

    sysbus_init_mmio(dev, &s->iomem);

    s->ds = graphic_console_init(jazz_led_update_display,

                                 jazz_led_invalidate_display,

                                 jazz_led_screen_dump,

                                 jazz_led_text_update, s);

    return 0;

}


dma_read(void *opaque, target_phys_addr_t addr, unsigned int size)

{

        struct fs_dma_ctrl *ctrl = opaque;

	int c;

	uint32_t r = 0;

	if (size != 4) {

		dma_rinvalid(opaque, addr);

	}

	/* Make addr relative to this channel and bounded to nr regs.  */

	c = fs_channel(addr);

	addr &= 0xff;

	addr >>= 2;

	switch (addr)

	{

		case RW_STAT:

			r = ctrl->channels[c].state & 7;

			r |= ctrl->channels[c].eol << 5;

			r |= ctrl->channels[c].stream_cmd_src << 8;

			break;

		default:

			r = ctrl->channels[c].regs[addr];

			D(printf ("%s c=%d addr=" TARGET_FMT_plx "\n",

				  __func__, c, addr));

			break;

	}

	return r;

}


static void pxa2xx_descriptor_load(struct pxa2xx_lcdc_s *s)

{

    struct pxa_frame_descriptor_s desc;

    target_phys_addr_t descptr;

    int i;

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

        s->dma_ch[i].source = 0;

        if (!s->dma_ch[i].up)

            continue;

        if (s->dma_ch[i].branch & FBR_BRA) {

            descptr = s->dma_ch[i].branch & FBR_SRCADDR;

            if (s->dma_ch[i].branch & FBR_BINT)

                pxa2xx_dma_bs_set(s, i);

            s->dma_ch[i].branch &= ~FBR_BRA;

        } else

            descptr = s->dma_ch[i].descriptor;

        if (!(descptr >= PXA2XX_SDRAM_BASE && descptr +

                    sizeof(desc) <= PXA2XX_SDRAM_BASE + phys_ram_size))

            continue;

        cpu_physical_memory_read(descptr, (void *)&desc, sizeof(desc));

        s->dma_ch[i].descriptor = tswap32(desc.fdaddr);

        s->dma_ch[i].source = tswap32(desc.fsaddr);

        s->dma_ch[i].id = tswap32(desc.fidr);

        s->dma_ch[i].command = tswap32(desc.ldcmd);

    }

}


int spapr_populate_vdevice(VIOsPAPRBus *bus, void *fdt)

{

    DeviceState *qdev, **qdevs;

    BusChild *kid;

    int i, num, ret = 0;

    /* Count qdevs on the bus list */

    num = 0;

    QTAILQ_FOREACH(kid, &bus->bus.children, sibling) {

        num++;

    }

    /* Copy out into an array of pointers */

    qdevs = g_malloc(sizeof(qdev) * num);

    num = 0;

    QTAILQ_FOREACH(kid, &bus->bus.children, sibling) {

        qdevs[num++] = kid->child;

    }

    /* Sort the array */

    qsort(qdevs, num, sizeof(qdev), compare_reg);

    /* Hack alert. Give the devices to libfdt in reverse order, we happen

     * to know that will mean they are in forward order in the tree. */

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

        VIOsPAPRDevice *dev = (VIOsPAPRDevice *)(qdevs[i]);

        ret = vio_make_devnode(dev, fdt);

        if (ret < 0) {

            goto out;

        }

    }

    ret = 0;

out:

    free(qdevs);

    return ret;

}


void ppc_tlb_invalidate_all(CPUPPCState *env)

{

    switch (env->mmu_model) {

    case POWERPC_MMU_SOFT_6xx:

    case POWERPC_MMU_SOFT_74xx:

        ppc6xx_tlb_invalidate_all(env);

        break;

    case POWERPC_MMU_SOFT_4xx:

    case POWERPC_MMU_SOFT_4xx_Z:

        ppc4xx_tlb_invalidate_all(env);

        break;

    case POWERPC_MMU_REAL:

        cpu_abort(env, "No TLB for PowerPC 4xx in real mode\n");

        break;

    case POWERPC_MMU_MPC8xx:

        /* XXX: TODO */

        cpu_abort(env, "MPC8xx MMU model is not implemented\n");

        break;

    case POWERPC_MMU_BOOKE:

        tlb_flush(env, 1);

        break;

    case POWERPC_MMU_BOOKE206:

        booke206_flush_tlb(env, -1, 0);

        break;

    case POWERPC_MMU_32B:

    case POWERPC_MMU_601:

#if defined(TARGET_PPC64)

    case POWERPC_MMU_620:

    case POWERPC_MMU_64B:

    case POWERPC_MMU_2_06:

#endif /* defined(TARGET_PPC64) */

        tlb_flush(env, 1);

        break;

    default:

        /* XXX: TODO */

        cpu_abort(env, "Unknown MMU model\n");

        break;

    }

}


uint32_t HELPER(lcebr)(CPUS390XState *env, uint32_t f1, uint32_t f2)

{

    env->fregs[f1].l.upper = float32_chs(env->fregs[f2].l.upper);

    return set_cc_nz_f32(env->fregs[f1].l.upper);

}


static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,

                    AVDictionary *opts, AVDictionary *opts2, int *is_http)

{

    HLSContext *c = s->priv_data;

    AVDictionary *tmp = NULL;

    const char *proto_name = NULL;

    int ret;

    av_dict_copy(&tmp, opts, 0);

    av_dict_copy(&tmp, opts2, 0);

    if (av_strstart(url, "crypto", NULL)) {

        if (url[6] == '+' || url[6] == ':')

            proto_name = avio_find_protocol_name(url + 7);

    }

    if (!proto_name)

        proto_name = avio_find_protocol_name(url);

    if (!proto_name)

        return AVERROR_INVALIDDATA;

    // only http(s) & file are allowed

    if (av_strstart(proto_name, "file", NULL)) {

        if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {

            av_log(s, AV_LOG_ERROR,

                "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"

                "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",

                url);

            return AVERROR_INVALIDDATA;

        }

    } else if (av_strstart(proto_name, "http", NULL)) {

        ;

    } else

        return AVERROR_INVALIDDATA;

    if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')

        ;

    else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')

        ;

    else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))

        return AVERROR_INVALIDDATA;

    if (c->http_persistent && *pb && av_strstart(proto_name, "http", NULL)) {

        ret = open_url_keepalive(c->ctx, pb, url);

        if (ret == AVERROR_EXIT) {

            return ret;

        } else if (ret < 0) {

            if (ret != AVERROR_EOF)

                av_log(s, AV_LOG_WARNING,

                    "keepalive request failed for '%s', retrying with new connection: %s\n",

                    url, av_err2str(ret));

            ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);

        }

    } else {

        ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);

    }

    if (ret >= 0) {

        // update cookies on http response with setcookies.

        char *new_cookies = NULL;

        if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))

            av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);

        if (new_cookies) {

            av_free(c->cookies);

            c->cookies = new_cookies;

        }

        av_dict_set(&opts, "cookies", c->cookies, 0);

    }

    av_dict_free(&tmp);

    if (is_http)

        *is_http = av_strstart(proto_name, "http", NULL);

    return ret;

}


static int qemu_rdma_dest_init(RDMAContext *rdma, Error **errp)

{

    int ret = -EINVAL, idx;

    struct rdma_cm_id *listen_id;

    char ip[40] = "unknown";

    struct rdma_addrinfo *res;

    char port_str[16];

    for (idx = 0; idx < RDMA_WRID_MAX; idx++) {

        rdma->wr_data[idx].control_len = 0;

        rdma->wr_data[idx].control_curr = NULL;

    }

    if (rdma->host == NULL) {

        ERROR(errp, "RDMA host is not set!");

        rdma->error_state = -EINVAL;

        return -1;

    }

    /* create CM channel */

    rdma->channel = rdma_create_event_channel();

    if (!rdma->channel) {

        ERROR(errp, "could not create rdma event channel");

        rdma->error_state = -EINVAL;

        return -1;

    }

    /* create CM id */

    ret = rdma_create_id(rdma->channel, &listen_id, NULL, RDMA_PS_TCP);

    if (ret) {

        ERROR(errp, "could not create cm_id!");

        goto err_dest_init_create_listen_id;

    }

    snprintf(port_str, 16, "%d", rdma->port);

    port_str[15] = '\0';

    if (rdma->host && strcmp("", rdma->host)) {

        struct rdma_addrinfo *e;

        ret = rdma_getaddrinfo(rdma->host, port_str, NULL, &res);

        if (ret < 0) {

            ERROR(errp, "could not rdma_getaddrinfo address %s", rdma->host);

            goto err_dest_init_bind_addr;

        }

        for (e = res; e != NULL; e = e->ai_next) {

            inet_ntop(e->ai_family,

                &((struct sockaddr_in *) e->ai_dst_addr)->sin_addr, ip, sizeof ip);

            trace_qemu_rdma_dest_init_trying(rdma->host, ip);

            ret = rdma_bind_addr(listen_id, e->ai_dst_addr);

            if (!ret) {

                if (e->ai_family == AF_INET6) {

                    ret = qemu_rdma_broken_ipv6_kernel(errp, listen_id->verbs);

                    if (ret) {

                        continue;

                    }

                }

                goto listen;

            }

        }

        ERROR(errp, "Error: could not rdma_bind_addr!");

        goto err_dest_init_bind_addr;

    } else {

        ERROR(errp, "migration host and port not specified!");

        ret = -EINVAL;

        goto err_dest_init_bind_addr;

    }

listen:

    rdma->listen_id = listen_id;

    qemu_rdma_dump_gid("dest_init", listen_id);

    return 0;

err_dest_init_bind_addr:

    rdma_destroy_id(listen_id);

err_dest_init_create_listen_id:

    rdma_destroy_event_channel(rdma->channel);

    rdma->channel = NULL;

    rdma->error_state = ret;

    return ret;

}


int cksum(struct mbuf *m, int len)

{

	register uint16_t *w;

	register int sum = 0;

	register int mlen = 0;

	int byte_swapped = 0;

	union {

		uint8_t  c[2];

		uint16_t s;

	} s_util;

	union {

		uint16_t s[2];

		uint32_t l;

	} l_util;

	if (m->m_len == 0)

	   goto cont;

	w = mtod(m, uint16_t *);

	mlen = m->m_len;

	if (len < mlen)

	   mlen = len;

#ifdef DEBUG

	len -= mlen;

#endif

	/*

	 * Force to even boundary.

	 */

	if ((1 & (long) w) && (mlen > 0)) {

		REDUCE;

		sum <<= 8;

		s_util.c[0] = *(uint8_t *)w;

		w = (uint16_t *)((int8_t *)w + 1);

		mlen--;

		byte_swapped = 1;

	}

	/*

	 * Unroll the loop to make overhead from

	 * branches &c small.

	 */

	while ((mlen -= 32) >= 0) {

		sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];

		sum += w[4]; sum += w[5]; sum += w[6]; sum += w[7];

		sum += w[8]; sum += w[9]; sum += w[10]; sum += w[11];

		sum += w[12]; sum += w[13]; sum += w[14]; sum += w[15];

		w += 16;

	}

	mlen += 32;

	while ((mlen -= 8) >= 0) {

		sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];

		w += 4;

	}

	mlen += 8;

	if (mlen == 0 && byte_swapped == 0)

	   goto cont;

	REDUCE;

	while ((mlen -= 2) >= 0) {

		sum += *w++;

	}

	if (byte_swapped) {

		REDUCE;

		sum <<= 8;

		if (mlen == -1) {

			s_util.c[1] = *(uint8_t *)w;

			sum += s_util.s;

			mlen = 0;

		} else

		   mlen = -1;

	} else if (mlen == -1)

	   s_util.c[0] = *(uint8_t *)w;

cont:

#ifdef DEBUG

	if (len) {

		DEBUG_ERROR((dfd, "cksum: out of data\n"));

		DEBUG_ERROR((dfd, " len = %d\n", len));

	}

#endif

	if (mlen == -1) {

		/* The last mbuf has odd # of bytes. Follow the

		 standard (the odd byte may be shifted left by 8 bits

			   or not as determined by endian-ness of the machine) */

		s_util.c[1] = 0;

		sum += s_util.s;

	}

	REDUCE;

	return (~sum & 0xffff);

}


void address_space_unmap(AddressSpace *as, void *buffer, target_phys_addr_t len,

                         int is_write, target_phys_addr_t access_len)

{

    if (buffer != bounce.buffer) {

        if (is_write) {

            ram_addr_t addr1 = qemu_ram_addr_from_host_nofail(buffer);

            while (access_len) {

                unsigned l;

                l = TARGET_PAGE_SIZE;

                if (l > access_len)

                    l = access_len;

                invalidate_and_set_dirty(addr1, l);

                addr1 += l;

                access_len -= l;

            }

        }

        if (xen_enabled()) {

            xen_invalidate_map_cache_entry(buffer);

        }

        return;

    }

    if (is_write) {

        address_space_write(as, bounce.addr, bounce.buffer, access_len);

    }

    qemu_vfree(bounce.buffer);

    bounce.buffer = NULL;

    cpu_notify_map_clients();

}


static av_cold int atrac3_decode_init(AVCodecContext *avctx)

{

    int i, ret;

    int version, delay, samples_per_frame, frame_factor;

    const uint8_t *edata_ptr = avctx->extradata;

    ATRAC3Context *q = avctx->priv_data;

    if (avctx->channels <= 0 || avctx->channels > 2) {

        av_log(avctx, AV_LOG_ERROR, "Channel configuration error!\n");

    }

    /* Take care of the codec-specific extradata. */

    if (avctx->extradata_size == 14) {

        /* Parse the extradata, WAV format */

        av_log(avctx, AV_LOG_DEBUG, "[0-1] %d\n",

               bytestream_get_le16(&edata_ptr));  // Unknown value always 1

        edata_ptr += 4;                             // samples per channel

        q->coding_mode = bytestream_get_le16(&edata_ptr);

        av_log(avctx, AV_LOG_DEBUG,"[8-9] %d\n",

               bytestream_get_le16(&edata_ptr));  //Dupe of coding mode

        frame_factor = bytestream_get_le16(&edata_ptr);  // Unknown always 1

        av_log(avctx, AV_LOG_DEBUG,"[12-13] %d\n",

               bytestream_get_le16(&edata_ptr));  // Unknown always 0

        /* setup */

        samples_per_frame    = SAMPLES_PER_FRAME * avctx->channels;

        version              = 4;

        delay                = 0x88E;

        q->coding_mode       = q->coding_mode ? JOINT_STEREO : STEREO;

        q->scrambled_stream  = 0;

        if (avctx->block_align !=  96 * avctx->channels * frame_factor &&

            avctx->block_align != 152 * avctx->channels * frame_factor &&

            avctx->block_align != 192 * avctx->channels * frame_factor) {

            av_log(avctx, AV_LOG_ERROR, "Unknown frame/channel/frame_factor "

                   "configuration %d/%d/%d\n", avctx->block_align,

                   avctx->channels, frame_factor);

            return AVERROR_INVALIDDATA;

        }

    } else if (avctx->extradata_size == 10) {

        /* Parse the extradata, RM format. */

        version                = bytestream_get_be32(&edata_ptr);

        samples_per_frame      = bytestream_get_be16(&edata_ptr);

        delay                  = bytestream_get_be16(&edata_ptr);

        q->coding_mode         = bytestream_get_be16(&edata_ptr);

        q->scrambled_stream    = 1;

    } else {

        av_log(NULL, AV_LOG_ERROR, "Unknown extradata size %d.\n",

               avctx->extradata_size);

    }

    /* Check the extradata */

    if (version != 4) {

        av_log(avctx, AV_LOG_ERROR, "Version %d != 4.\n", version);

        return AVERROR_INVALIDDATA;

    }

    if (samples_per_frame != SAMPLES_PER_FRAME &&

        samples_per_frame != SAMPLES_PER_FRAME * 2) {

        av_log(avctx, AV_LOG_ERROR, "Unknown amount of samples per frame %d.\n",

               samples_per_frame);

        return AVERROR_INVALIDDATA;

    }

    if (delay != 0x88E) {

        av_log(avctx, AV_LOG_ERROR, "Unknown amount of delay %x != 0x88E.\n",

               delay);

        return AVERROR_INVALIDDATA;

    }

    if (q->coding_mode == STEREO)

        av_log(avctx, AV_LOG_DEBUG, "Normal stereo detected.\n");

    else if (q->coding_mode == JOINT_STEREO)

        av_log(avctx, AV_LOG_DEBUG, "Joint stereo detected.\n");

    else {

        av_log(avctx, AV_LOG_ERROR, "Unknown channel coding mode %x!\n",

               q->coding_mode);

        return AVERROR_INVALIDDATA;

    }

    if (avctx->block_align >= UINT_MAX / 2)

    q->decoded_bytes_buffer = av_mallocz(FFALIGN(avctx->block_align, 4) +

                                         FF_INPUT_BUFFER_PADDING_SIZE);

    if (q->decoded_bytes_buffer == NULL)

        return AVERROR(ENOMEM);

    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;

    /* initialize the MDCT transform */

    if ((ret = ff_mdct_init(&q->mdct_ctx, 9, 1, 1.0 / 32768)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");

        av_freep(&q->decoded_bytes_buffer);

        return ret;

    }

    /* init the joint-stereo decoding data */

    q->weighting_delay[0] = 0;

    q->weighting_delay[1] = 7;

    q->weighting_delay[2] = 0;

    q->weighting_delay[3] = 7;

    q->weighting_delay[4] = 0;

    q->weighting_delay[5] = 7;

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

        q->matrix_coeff_index_prev[i] = 3;

        q->matrix_coeff_index_now[i]  = 3;

        q->matrix_coeff_index_next[i] = 3;

    }

    avpriv_float_dsp_init(&q->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);

    ff_fmt_convert_init(&q->fmt_conv, avctx);

    q->units = av_mallocz(sizeof(*q->units) * avctx->channels);

    if (!q->units) {

        atrac3_decode_close(avctx);

        return AVERROR(ENOMEM);

    }

    avcodec_get_frame_defaults(&q->frame);

    avctx->coded_frame = &q->frame;

    return 0;

}


static uint32_t unassigned_mem_readl(void *opaque, target_phys_addr_t addr)

{

#ifdef DEBUG_UNASSIGNED

    printf("Unassigned mem read " TARGET_FMT_plx "\n", addr);

#endif

#if defined(TARGET_ALPHA) || defined(TARGET_SPARC) || defined(TARGET_MICROBLAZE)

    do_unassigned_access(addr, 0, 0, 0, 4);

#endif

    return 0;

}


static TCGv_i64 gen_addq_msw(TCGv_i64 a, TCGv b)

{

    TCGv_i64 tmp64 = tcg_temp_new_i64();

    tcg_gen_extu_i32_i64(tmp64, b);

    dead_tmp(b);

    tcg_gen_shli_i64(tmp64, tmp64, 32);

    tcg_gen_add_i64(a, tmp64, a);

    tcg_temp_free_i64(tmp64);

    return a;

}


static void qvirtio_scsi_pci_free(QVirtIOSCSI *vs)

{

    int i;

    for (i = 0; i < vs->num_queues + 2; i++) {

        qvirtqueue_cleanup(vs->dev->bus, vs->vq[i], vs->alloc);

    }

    pc_alloc_uninit(vs->alloc);

    qvirtio_pci_device_disable(container_of(vs->dev, QVirtioPCIDevice, vdev));

    g_free(vs->dev);

    qpci_free_pc(vs->bus);

    g_free(vs);

}


void spapr_clear_pending_events(sPAPRMachineState *spapr)

{

    sPAPREventLogEntry *entry = NULL;

    QTAILQ_FOREACH(entry, &spapr->pending_events, next) {

        QTAILQ_REMOVE(&spapr->pending_events, entry, next);

        g_free(entry->extended_log);

        g_free(entry);

    }

}


static void sclp_set_write_mask(void)

{

    WriteEventMask *sccb = (void*)_sccb;

    sccb->h.length = sizeof(WriteEventMask);

    sccb->mask_length = sizeof(unsigned int);

    sccb->receive_mask = SCLP_EVENT_MASK_MSG_ASCII;

    sccb->cp_receive_mask = SCLP_EVENT_MASK_MSG_ASCII;

    sccb->send_mask = SCLP_EVENT_MASK_MSG_ASCII;

    sccb->cp_send_mask = SCLP_EVENT_MASK_MSG_ASCII;

    sclp_service_call(SCLP_CMD_WRITE_EVENT_MASK, sccb);

}


void json_prop_int(QJSON *json, const char *name, int64_t val)

{

    json_emit_element(json, name);

    qstring_append_int(json->str, val);

}


static void pm_update_sci(PIIX4PMState *s)

{

    int sci_level, pmsts;

    pmsts = acpi_pm1_evt_get_sts(&s->ar);

    sci_level = (((pmsts & s->ar.pm1.evt.en) &

                  (ACPI_BITMASK_RT_CLOCK_ENABLE |

                   ACPI_BITMASK_POWER_BUTTON_ENABLE |

                   ACPI_BITMASK_GLOBAL_LOCK_ENABLE |

                   ACPI_BITMASK_TIMER_ENABLE)) != 0) ||

        (((s->ar.gpe.sts[0] & s->ar.gpe.en[0]) &

          (PIIX4_PCI_HOTPLUG_STATUS | PIIX4_CPU_HOTPLUG_STATUS)) != 0);

    qemu_set_irq(s->irq, sci_level);

    /* schedule a timer interruption if needed */

    acpi_pm_tmr_update(&s->ar, (s->ar.pm1.evt.en & ACPI_BITMASK_TIMER_ENABLE) &&

                       !(pmsts & ACPI_BITMASK_TIMER_STATUS));

}


static inline int wv_get_value_integer(WavpackFrameContext *s, uint32_t *crc, int S)

{

    int bit;

    if(s->extra_bits){

        S <<= s->extra_bits;

        if(s->got_extra_bits){

            S |= get_bits(&s->gb_extra_bits, s->extra_bits);

            *crc = *crc * 9 + (S&0xffff) * 3 + ((unsigned)S>>16);

        }

    }

    bit = (S & s->and) | s->or;

    return (((S + bit) << s->shift) - bit) << s->post_shift;

}


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;

    MXFContext* mxf = s->priv_data;

    int64_t seekpos;

    int ret;

    MXFIndexTable *t;

    if (mxf->nb_index_tables <= 0) {

    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);

    if ((ret = avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET)) < 0)

        return ret;

    ff_update_cur_dts(s, st, sample_time);

    mxf->current_edit_unit = sample_time;

    } else {

        t = &mxf->index_tables[0];

        /* clamp above zero, else ff_index_search_timestamp() returns negative

         * this also means we allow seeking before the start */

        sample_time = FFMAX(sample_time, 0);

        if (t->fake_index) {

            /* behave as if we have a proper index */

            if ((sample_time = ff_index_search_timestamp(t->fake_index, t->nb_ptses, sample_time, flags)) < 0)

                return sample_time;

        } else {

            /* no IndexEntryArray (one or more CBR segments)

             * make sure we don't seek past the end */

            sample_time = FFMIN(sample_time, st->duration - 1);

        }

        if ((ret = mxf_edit_unit_absolute_offset(mxf, t, sample_time, &sample_time, &seekpos, 1)) << 0)

            return ret;

        ff_update_cur_dts(s, st, sample_time);

        mxf->current_edit_unit = sample_time;

        avio_seek(s->pb, seekpos, SEEK_SET);

    }

    return 0;

}


if_start(Slirp *slirp)

{

    uint64_t now = qemu_get_clock_ns(rt_clock);

    int requeued = 0;

	struct mbuf *ifm, *ifqt;

	DEBUG_CALL("if_start");

	if (slirp->if_queued == 0)

	   return; /* Nothing to do */

 again:

        /* check if we can really output */

        if (!slirp_can_output(slirp->opaque))

            return;

	/*

	 * See which queue to get next packet from

	 * If there's something in the fastq, select it immediately

	 */

	if (slirp->if_fastq.ifq_next != &slirp->if_fastq) {

		ifm = slirp->if_fastq.ifq_next;

	} else {

		/* Nothing on fastq, see if next_m is valid */

		if (slirp->next_m != &slirp->if_batchq)

		   ifm = slirp->next_m;

		else

		   ifm = slirp->if_batchq.ifq_next;

		/* Set which packet to send on next iteration */

		slirp->next_m = ifm->ifq_next;

	}

	/* Remove it from the queue */

	ifqt = ifm->ifq_prev;

	remque(ifm);

	slirp->if_queued--;

	/* If there are more packets for this session, re-queue them */

	if (ifm->ifs_next != /* ifm->ifs_prev != */ ifm) {

		insque(ifm->ifs_next, ifqt);

		ifs_remque(ifm);

	}

	/* Update so_queued */

	if (ifm->ifq_so) {

		if (--ifm->ifq_so->so_queued == 0)

		   /* If there's no more queued, reset nqueued */

		   ifm->ifq_so->so_nqueued = 0;

	}

        if (ifm->expiration_date < now) {

            /* Expired */

            m_free(ifm);

        } else {

            /* Encapsulate the packet for sending */

            if (if_encap(slirp, ifm)) {

                m_free(ifm);

            } else {

                /* re-queue */

                insque(ifm, ifqt);

                requeued++;

            }

        }

	if (slirp->if_queued)

	   goto again;

        slirp->if_queued = requeued;

}


static void dump_human_image_check(ImageCheck *check)

{

    if (!(check->corruptions || check->leaks || check->check_errors)) {

        printf("No errors were found on the image.\n");

    } else {

        if (check->corruptions) {

            printf("\n%" PRId64 " errors were found on the image.\n"

                "Data may be corrupted, or further writes to the image "

                "may corrupt it.\n",

                check->corruptions);

        }

        if (check->leaks) {

            printf("\n%" PRId64 " leaked clusters were found on the image.\n"

                "This means waste of disk space, but no harm to data.\n",

                check->leaks);

        }

        if (check->check_errors) {

            printf("\n%" PRId64 " internal errors have occurred during the check.\n",

                check->check_errors);

        }

    }

    if (check->total_clusters != 0 && check->allocated_clusters != 0) {

        printf("%" PRId64 "/%" PRId64 "= %0.2f%% allocated, %0.2f%% fragmented\n",

        check->allocated_clusters, check->total_clusters,

        check->allocated_clusters * 100.0 / check->total_clusters,

        check->fragmented_clusters * 100.0 / check->allocated_clusters);

    }

    if (check->image_end_offset) {

        printf("Image end offset: %" PRId64 "\n", check->image_end_offset);

    }

}


float32 int32_to_float32( int32 a STATUS_PARAM )

{

    flag zSign;

    if ( a == 0 ) return 0;

    if ( a == (sbits32) 0x80000000 ) return packFloat32( 1, 0x9E, 0 );

    zSign = ( a < 0 );

    return normalizeRoundAndPackFloat32( zSign, 0x9C, zSign ? - a : a STATUS_VAR );

}


static int vfio_start_eventfd_injection(VFIOINTp *intp)

{

    int ret;

    ret = vfio_set_trigger_eventfd(intp, vfio_intp_interrupt);

    if (ret) {

        error_report("vfio: Error: Failed to pass IRQ fd to the driver: %m");

    }

    return ret;

}


static int bt_hid_in(struct bt_hid_device_s *s)

{

    USBPacket p;

    p.pid = USB_TOKEN_IN;

    p.devep = 1;

    p.data = s->datain.buffer;

    p.len = sizeof(s->datain.buffer);

    s->datain.len = s->usbdev->info->handle_data(s->usbdev, &p);

    return s->datain.len;

}


void qmp_inject_nmi(Error **errp)

{

#if defined(TARGET_I386)

    CPUState *cs;

    CPU_FOREACH(cs) {

        X86CPU *cpu = X86_CPU(cs);

        if (!cpu->apic_state) {

            cpu_interrupt(cs, CPU_INTERRUPT_NMI);

        } else {

            apic_deliver_nmi(cpu->apic_state);

        }

    }

#else

    nmi_monitor_handle(monitor_get_cpu_index(), errp);

#endif

}


eth_setup_ip4_fragmentation(const void *l2hdr, size_t l2hdr_len,

                            void *l3hdr, size_t l3hdr_len,

                            size_t l3payload_len,

                            size_t frag_offset, bool more_frags)

{

    if (eth_get_l3_proto(l2hdr, l2hdr_len) == ETH_P_IP) {

        uint16_t orig_flags;

        struct ip_header *iphdr = (struct ip_header *) l3hdr;

        uint16_t frag_off_units = frag_offset / IP_FRAG_UNIT_SIZE;

        uint16_t new_ip_off;

        assert(frag_offset % IP_FRAG_UNIT_SIZE == 0);

        assert((frag_off_units & ~IP_OFFMASK) == 0);

        orig_flags = be16_to_cpu(iphdr->ip_off) & ~(IP_OFFMASK|IP_MF);

        new_ip_off = frag_off_units | orig_flags  | (more_frags ? IP_MF : 0);

        iphdr->ip_off = cpu_to_be16(new_ip_off);

        iphdr->ip_len = cpu_to_be16(l3payload_len + l3hdr_len);

    }

}


float32 HELPER(ucf64_subs)(float32 a, float32 b, CPUUniCore32State *env)

{

    return float32_sub(a, b, &env->ucf64.fp_status);

}


do_cksum(uint8_t *dp, uint8_t *de)

{

    unsigned int bsum[2] = {0, 0}, i, sum;

    for (i = 1; dp < de; bsum[i^=1] += *dp++)

        ;

    sum = (bsum[0] << 8) + bsum[1];

    sum = (sum >> 16) + (sum & 0xffff);

    return ~(sum + (sum >> 16));

}


static void ics_simple_realize(DeviceState *dev, Error **errp)

{

    ICSState *ics = ICS_SIMPLE(dev);

    if (!ics->nr_irqs) {

        error_setg(errp, "Number of interrupts needs to be greater 0");

        return;

    }

    ics->irqs = g_malloc0(ics->nr_irqs * sizeof(ICSIRQState));

    ics->qirqs = qemu_allocate_irqs(ics_simple_set_irq, ics, ics->nr_irqs);

    qemu_register_reset(ics_simple_reset, dev);

}


static void vnc_flush(VncState *vs)

{

    if (vs->output.offset)

	vnc_client_write(vs);

}


static void do_subchannel_work(SubchDev *sch, ORB *orb)

{

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

    if (s->ctrl & SCSW_FCTL_CLEAR_FUNC) {

        sch_handle_clear_func(sch);

    } else if (s->ctrl & SCSW_FCTL_HALT_FUNC) {

        sch_handle_halt_func(sch);

    } else if (s->ctrl & SCSW_FCTL_START_FUNC) {

        /* Triggered by both ssch and rsch. */

        sch_handle_start_func(sch, orb);

    } else {

        /* Cannot happen. */

        return;

    }

    css_inject_io_interrupt(sch);

}


static int sd_snapshot_delete(BlockDriverState *bs,

                              const char *snapshot_id,

                              const char *name,

                              Error **errp)

{

    unsigned long snap_id = 0;

    char snap_tag[SD_MAX_VDI_TAG_LEN];

    Error *local_err = NULL;

    int fd, ret;

    char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];

    BDRVSheepdogState *s = bs->opaque;

    unsigned int wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN, rlen = 0;

    uint32_t vid;

    SheepdogVdiReq hdr = {

        .opcode = SD_OP_DEL_VDI,

        .data_length = wlen,

        .flags = SD_FLAG_CMD_WRITE,

    };

    SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;

    if (!remove_objects(s)) {

        return -1;

    }

    memset(buf, 0, sizeof(buf));

    memset(snap_tag, 0, sizeof(snap_tag));

    pstrcpy(buf, SD_MAX_VDI_LEN, s->name);

    ret = qemu_strtoul(snapshot_id, NULL, 10, &snap_id);

    if (ret || snap_id > UINT32_MAX) {

        error_setg(errp, "Invalid snapshot ID: %s",

                         snapshot_id ? snapshot_id : "<null>");

        return -EINVAL;

    }

    if (snap_id) {

        hdr.snapid = (uint32_t) snap_id;

    } else {

        pstrcpy(snap_tag, sizeof(snap_tag), snapshot_id);

        pstrcpy(buf + SD_MAX_VDI_LEN, SD_MAX_VDI_TAG_LEN, snap_tag);

    }

    ret = find_vdi_name(s, s->name, snap_id, snap_tag, &vid, true,

                        &local_err);

    if (ret) {

        return ret;

    }

    fd = connect_to_sdog(s, &local_err);

    if (fd < 0) {

        error_report_err(local_err);

        return -1;

    }

    ret = do_req(fd, s->bs, (SheepdogReq *)&hdr,

                 buf, &wlen, &rlen);

    closesocket(fd);

    if (ret) {

        return ret;

    }

    switch (rsp->result) {

    case SD_RES_NO_VDI:

        error_report("%s was already deleted", s->name);

    case SD_RES_SUCCESS:

        break;

    default:

        error_report("%s, %s", sd_strerror(rsp->result), s->name);

        return -1;

    }

    return ret;

}


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

{

    int ret;

    int64_t last_ftell = qemu_ftell(f);

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

            block_mig_state.submitted, block_mig_state.transferred);

    ret = flush_blks(f);

    if (ret) {

        return ret;

    }

    blk_mig_reset_dirty_cursor();

    /* control the rate of transfer */

    blk_mig_lock();

    while ((block_mig_state.submitted +

            block_mig_state.read_done) * BLOCK_SIZE <

           qemu_file_get_rate_limit(f)) {

        blk_mig_unlock();

        if (block_mig_state.bulk_completed == 0) {

            /* first finish the bulk phase */

            if (blk_mig_save_bulked_block(f) == 0) {

                /* finished saving bulk on all devices */

                block_mig_state.bulk_completed = 1;

            }

            ret = 0;

        } else {

            /* Always called with iothread lock taken for

             * simplicity, block_save_complete also calls it.

             */

            qemu_mutex_lock_iothread();

            ret = blk_mig_save_dirty_block(f, 1);

            qemu_mutex_unlock_iothread();

        }

        if (ret < 0) {

            return ret;

        }

        blk_mig_lock();

        if (ret != 0) {

            /* no more dirty blocks */

            break;

        }

    }

    blk_mig_unlock();

    ret = flush_blks(f);

    if (ret) {

        return ret;

    }

    qemu_put_be64(f, BLK_MIG_FLAG_EOS);

    return qemu_ftell(f) - last_ftell;

}


static av_cold int fft_init(AVCodecContext *avctx, AC3MDCTContext *mdct, int ln)

{

    int i, n, n2;

    float alpha;

    n  = 1 << ln;

    n2 = n >> 1;

    FF_ALLOC_OR_GOTO(avctx, mdct->costab, n2 * sizeof(*mdct->costab), fft_alloc_fail);

    FF_ALLOC_OR_GOTO(avctx, mdct->sintab, n2 * sizeof(*mdct->sintab), fft_alloc_fail);

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

        alpha     = 2.0 * M_PI * i / n;

        mdct->costab[i] = FIX15(cos(alpha));

        mdct->sintab[i] = FIX15(sin(alpha));

    }

    return 0;

fft_alloc_fail:

    mdct_end(mdct);

    return AVERROR(ENOMEM);

}


static always_inline void gen_intermediate_code_internal (CPUState *env,

                                                          TranslationBlock *tb,

                                                          int search_pc)

{

#if defined ALPHA_DEBUG_DISAS

    static int insn_count;

#endif

    DisasContext ctx, *ctxp = &ctx;

    target_ulong pc_start;

    uint32_t insn;

    uint16_t *gen_opc_end;

    CPUBreakpoint *bp;

    int j, lj = -1;

    int ret;

    int num_insns;

    int max_insns;

    pc_start = tb->pc;

    gen_opc_end = gen_opc_buf + OPC_MAX_SIZE;

    ctx.pc = pc_start;

    ctx.amask = env->amask;

#if defined (CONFIG_USER_ONLY)

    ctx.mem_idx = 0;

#else

    ctx.mem_idx = ((env->ps >> 3) & 3);

    ctx.pal_mode = env->ipr[IPR_EXC_ADDR] & 1;

#endif

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0)

        max_insns = CF_COUNT_MASK;

    gen_icount_start();

    for (ret = 0; ret == 0;) {

        if (unlikely(!TAILQ_EMPTY(&env->breakpoints))) {

            TAILQ_FOREACH(bp, &env->breakpoints, entry) {

                if (bp->pc == ctx.pc) {

                    gen_excp(&ctx, EXCP_DEBUG, 0);

                    break;

                }

            }

        }

        if (search_pc) {

            j = gen_opc_ptr - gen_opc_buf;

            if (lj < j) {

                lj++;

                while (lj < j)

                    gen_opc_instr_start[lj++] = 0;

                gen_opc_pc[lj] = ctx.pc;

                gen_opc_instr_start[lj] = 1;

                gen_opc_icount[lj] = num_insns;

            }

        }

        if (num_insns + 1 == max_insns && (tb->cflags & CF_LAST_IO))

            gen_io_start();

#if defined ALPHA_DEBUG_DISAS

        insn_count++;

        LOG_DISAS("pc " TARGET_FMT_lx " mem_idx %d\n",

                  ctx.pc, ctx.mem_idx);

#endif

        insn = ldl_code(ctx.pc);

#if defined ALPHA_DEBUG_DISAS

        insn_count++;

        LOG_DISAS("opcode %08x %d\n", insn, insn_count);

#endif

        num_insns++;

        ctx.pc += 4;

        ret = translate_one(ctxp, insn);

        if (ret != 0)

            break;

        /* if we reach a page boundary or are single stepping, stop

         * generation

         */

        if (((ctx.pc & (TARGET_PAGE_SIZE - 1)) == 0) ||

            num_insns >= max_insns) {

            break;

        }

        if (env->singlestep_enabled) {

            gen_excp(&ctx, EXCP_DEBUG, 0);

            break;

	}

#if defined (DO_SINGLE_STEP)

        break;

#endif

    }

    if (ret != 1 && ret != 3) {

        tcg_gen_movi_i64(cpu_pc, ctx.pc);

    }

#if defined (DO_TB_FLUSH)

    gen_helper_tb_flush();

#endif

    if (tb->cflags & CF_LAST_IO)

        gen_io_end();

    /* Generate the return instruction */

    tcg_gen_exit_tb(0);

    gen_icount_end(tb, num_insns);

    *gen_opc_ptr = INDEX_op_end;

    if (search_pc) {

        j = gen_opc_ptr - gen_opc_buf;

        lj++;

        while (lj <= j)

            gen_opc_instr_start[lj++] = 0;

    } else {

        tb->size = ctx.pc - pc_start;

        tb->icount = num_insns;

    }

#if defined ALPHA_DEBUG_DISAS

    log_cpu_state_mask(CPU_LOG_TB_CPU, env, 0);

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        qemu_log("IN: %s\n", lookup_symbol(pc_start));

        log_target_disas(pc_start, ctx.pc - pc_start, 1);

        qemu_log("\n");

    }

#endif

}


VncJob *vnc_job_new(VncState *vs)

{

    VncJob *job = g_malloc0(sizeof(VncJob));

    job->vs = vs;

    vnc_lock_queue(queue);

    QLIST_INIT(&job->rectangles);

    vnc_unlock_queue(queue);

    return job;

}


static void nbd_client_closed(NBDClient *client)

{

    nb_fds--;

    if (nb_fds == 0 && !persistent && state == RUNNING) {

        state = TERMINATE;

    }

    nbd_update_server_watch();

    nbd_client_put(client);

}


static uint16_t nvme_create_sq(NvmeCtrl *n, NvmeCmd *cmd)

{

    NvmeSQueue *sq;

    NvmeCreateSq *c = (NvmeCreateSq *)cmd;

    uint16_t cqid = le16_to_cpu(c->cqid);

    uint16_t sqid = le16_to_cpu(c->sqid);

    uint16_t qsize = le16_to_cpu(c->qsize);

    uint16_t qflags = le16_to_cpu(c->sq_flags);

    uint64_t prp1 = le64_to_cpu(c->prp1);

    if (!cqid || nvme_check_cqid(n, cqid)) {

        return NVME_INVALID_CQID | NVME_DNR;

    }

    if (!sqid || !nvme_check_sqid(n, sqid)) {

        return NVME_INVALID_QID | NVME_DNR;

    }

    if (!qsize || qsize > NVME_CAP_MQES(n->bar.cap)) {

        return NVME_MAX_QSIZE_EXCEEDED | NVME_DNR;

    }

    if (!prp1 || prp1 & (n->page_size - 1)) {

        return NVME_INVALID_FIELD | NVME_DNR;

    }

    if (!(NVME_SQ_FLAGS_PC(qflags))) {

        return NVME_INVALID_FIELD | NVME_DNR;

    }

    sq = g_malloc0(sizeof(*sq));

    nvme_init_sq(sq, n, prp1, sqid, cqid, qsize + 1);

    return NVME_SUCCESS;

}


void ff_ac3_bit_alloc_calc_mask(AC3BitAllocParameters *s, int16_t *band_psd,

                                int start, int end, int fast_gain, int is_lfe,

                                int dba_mode, int dba_nsegs, uint8_t *dba_offsets,

                                uint8_t *dba_lengths, uint8_t *dba_values,

                                int16_t *mask)

{

    int16_t excite[50]; /* excitation */

    int bin, k;

    int bndstrt, bndend, begin, end1, tmp;

    int lowcomp, fastleak, slowleak;

    /* excitation function */

    bndstrt = bin_to_band_tab[start];

    bndend = bin_to_band_tab[end-1] + 1;

    if (bndstrt == 0) {

        lowcomp = 0;

        lowcomp = calc_lowcomp1(lowcomp, band_psd[0], band_psd[1], 384);

        excite[0] = band_psd[0] - fast_gain - lowcomp;

        lowcomp = calc_lowcomp1(lowcomp, band_psd[1], band_psd[2], 384);

        excite[1] = band_psd[1] - fast_gain - lowcomp;

        begin = 7;

        for (bin = 2; bin < 7; bin++) {

            if (!(is_lfe && bin == 6))

                lowcomp = calc_lowcomp1(lowcomp, band_psd[bin], band_psd[bin+1], 384);

            fastleak = band_psd[bin] - fast_gain;

            slowleak = band_psd[bin] - s->slow_gain;

            excite[bin] = fastleak - lowcomp;

            if (!(is_lfe && bin == 6)) {

                if (band_psd[bin] <= band_psd[bin+1]) {

                    begin = bin + 1;

                    break;

                }

            }

        }

        end1=bndend;

        if (end1 > 22) end1=22;

        for (bin = begin; bin < end1; bin++) {

            if (!(is_lfe && bin == 6))

                lowcomp = calc_lowcomp(lowcomp, band_psd[bin], band_psd[bin+1], bin);

            fastleak = FFMAX(fastleak - s->fast_decay, band_psd[bin] - fast_gain);

            slowleak = FFMAX(slowleak - s->slow_decay, band_psd[bin] - s->slow_gain);

            excite[bin] = FFMAX(fastleak - lowcomp, slowleak);

        }

        begin = 22;

    } else {

        /* coupling channel */

        begin = bndstrt;

        fastleak = (s->cpl_fast_leak << 8) + 768;

        slowleak = (s->cpl_slow_leak << 8) + 768;

    }

    for (bin = begin; bin < bndend; bin++) {

        fastleak = FFMAX(fastleak - s->fast_decay, band_psd[bin] - fast_gain);

        slowleak = FFMAX(slowleak - s->slow_decay, band_psd[bin] - s->slow_gain);

        excite[bin] = FFMAX(fastleak, slowleak);

    }

    /* compute masking curve */

    for (bin = bndstrt; bin < bndend; bin++) {

        tmp = s->db_per_bit - band_psd[bin];

        if (tmp > 0) {

            excite[bin] += tmp >> 2;

        }

        mask[bin] = FFMAX(ff_ac3_hearing_threshold_tab[bin >> s->sr_shift][s->sr_code], excite[bin]);

    }

    /* delta bit allocation */

    if (dba_mode == DBA_REUSE || dba_mode == DBA_NEW) {

        int band, seg, delta;

        band = 0;

        for (seg = 0; seg < FFMIN(8, dba_nsegs); seg++) {

            band = FFMIN(49, band + dba_offsets[seg]);

            if (dba_values[seg] >= 4) {

                delta = (dba_values[seg] - 3) << 7;

            } else {

                delta = (dba_values[seg] - 4) << 7;

            }

            for (k = 0; k < dba_lengths[seg]; k++) {

                mask[band] += delta;

                band++;

            }

        }

    }

}


static inline void vmsvga_update_rect_delayed(struct vmsvga_state_s *s,

                int x, int y, int w, int h)

{

    struct vmsvga_rect_s *rect = &s->redraw_fifo[s->redraw_fifo_last ++];

    s->redraw_fifo_last &= REDRAW_FIFO_LEN - 1;

    rect->x = x;

    rect->y = y;

    rect->w = w;

    rect->h = h;

}


static inline void t_gen_addx_carry(DisasContext *dc, TCGv d)

{

	if (dc->flagx_known) {

		if (dc->flags_x) {

			TCGv c;

			c = tcg_temp_new(TCG_TYPE_TL);

			t_gen_mov_TN_preg(c, PR_CCS);

			/* C flag is already at bit 0.  */

			tcg_gen_andi_tl(c, c, C_FLAG);

			tcg_gen_add_tl(d, d, c);

			tcg_temp_free(c);

		}

	} else {

		TCGv x, c;

		x = tcg_temp_new(TCG_TYPE_TL);

		c = tcg_temp_new(TCG_TYPE_TL);

		t_gen_mov_TN_preg(x, PR_CCS);

		tcg_gen_mov_tl(c, x);

		/* Propagate carry into d if X is set. Branch free.  */

		tcg_gen_andi_tl(c, c, C_FLAG);

		tcg_gen_andi_tl(x, x, X_FLAG);

		tcg_gen_shri_tl(x, x, 4);

		tcg_gen_and_tl(x, x, c);

		tcg_gen_add_tl(d, d, x);

		tcg_temp_free(x);

		tcg_temp_free(c);

	}

}


static void rtas_start_cpu(sPAPREnvironment *spapr,

                           uint32_t token, uint32_t nargs,

                           target_ulong args,

                           uint32_t nret, target_ulong rets)

{

    target_ulong id, start, r3;

    CPUState *cs;

    if (nargs != 3 || nret != 1) {

        rtas_st(rets, 0, -3);

        return;

    }

    id = rtas_ld(args, 0);

    start = rtas_ld(args, 1);

    r3 = rtas_ld(args, 2);

    cs = qemu_get_cpu(id);

    if (cs != NULL) {

        PowerPCCPU *cpu = POWERPC_CPU(cs);

        CPUPPCState *env = &cpu->env;

        if (!cs->halted) {

            rtas_st(rets, 0, -1);

            return;

        }

        /* This will make sure qemu state is up to date with kvm, and

         * mark it dirty so our changes get flushed back before the

         * new cpu enters */

        kvm_cpu_synchronize_state(cs);

        env->msr = (1ULL << MSR_SF) | (1ULL << MSR_ME);

        env->nip = start;

        env->gpr[3] = r3;

        cs->halted = 0;

        qemu_cpu_kick(cs);

        rtas_st(rets, 0, 0);

        return;

    }

    /* Didn't find a matching cpu */

    rtas_st(rets, 0, -3);

}


int i2c_start_transfer(i2c_bus *bus, int address, int recv)

{

    DeviceState *qdev;

    i2c_slave *slave = NULL;

    LIST_FOREACH(qdev, &bus->qbus.children, sibling) {

        slave = I2C_SLAVE_FROM_QDEV(qdev);

        if (slave->address == address)

            break;

    }

    if (!slave)

        return 1;

    /* If the bus is already busy, assume this is a repeated

       start condition.  */

    bus->current_dev = slave;

    slave->info->event(slave, recv ? I2C_START_RECV : I2C_START_SEND);

    return 0;

}


static int aasc_decode_frame(AVCodecContext *avctx,

                              void *data, int *data_size,

                              AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    AascContext *s = avctx->priv_data;

    int compr, i, stride;

    s->frame.reference = 3;

    s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;

    if (avctx->reget_buffer(avctx, &s->frame)) {

        av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");

        return -1;

    }

    compr = AV_RL32(buf);

    buf += 4;

    buf_size -= 4;

    switch (avctx->codec_tag) {

    case MKTAG('A', 'A', 'S', '4'):

        bytestream2_init(&s->gb, buf - 4, buf_size + 4);

        ff_msrle_decode(avctx, (AVPicture*)&s->frame, 8, &s->gb);

        break;

    case MKTAG('A', 'A', 'S', 'C'):

    switch(compr){

    case 0:

        stride = (avctx->width * 3 + 3) & ~3;

        for(i = avctx->height - 1; i >= 0; i--){

            if(avctx->width*3 > buf_size){

                av_log(avctx, AV_LOG_ERROR, "Next line is beyond buffer bounds\n");

                break;

            }

            memcpy(s->frame.data[0] + i*s->frame.linesize[0], buf, avctx->width*3);

            buf += stride;

            buf_size -= stride;

        }

        break;

    case 1:

        bytestream2_init(&s->gb, buf, buf_size);

        ff_msrle_decode(avctx, (AVPicture*)&s->frame, 8, &s->gb);

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "Unknown compression type %d\n", compr);

        return -1;

    }

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "Unknown FourCC: %X\n", avctx->codec_tag);

        return -1;

    }

    *data_size = sizeof(AVFrame);

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

    /* report that the buffer was completely consumed */

    return buf_size;

}


int ff_h264_field_end(H264Context *h, int in_setup)
{
    AVCodecContext *const avctx = h->avctx;
    int err = 0;
    h->mb_y = 0;
    if (CONFIG_H264_VDPAU_DECODER &&
        h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
        ff_vdpau_h264_set_reference_frames(h);
    if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
        if (!h->droppable) {
            err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
            h->prev_poc_msb = h->poc_msb;
            h->prev_poc_lsb = h->poc_lsb;
        }
        h->prev_frame_num_offset = h->frame_num_offset;
        h->prev_frame_num        = h->frame_num;
        h->outputed_poc          = h->next_outputed_poc;
    }
    if (avctx->hwaccel) {
        if (avctx->hwaccel->end_frame(avctx) < 0)
            av_log(avctx, AV_LOG_ERROR,
                   "hardware accelerator failed to decode picture\n");
    }
    if (CONFIG_H264_VDPAU_DECODER &&
        h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
        ff_vdpau_h264_picture_complete(h);
#if CONFIG_ERROR_RESILIENCE
    /*
     * FIXME: Error handling code does not seem to support interlaced
     * when slices span multiple rows
     * The ff_er_add_slice calls don't work right for bottom
     * fields; they cause massive erroneous error concealing
     * Error marking covers both fields (top and bottom).
     * This causes a mismatched s->error_count
     * and a bad error table. Further, the error count goes to
     * INT_MAX when called for bottom field, because mb_y is
     * past end by one (callers fault) and resync_mb_y != 0
     * causes problems for the first MB line, too.
     */
    if (!FIELD_PICTURE(h) && h->current_slice && !h->sps.new) {
        ff_h264_set_erpic(&h->er.cur_pic, h->cur_pic_ptr);
        ff_er_frame_end(&h->er);
    }
#endif /* CONFIG_ERROR_RESILIENCE */
    if (!in_setup && !h->droppable)
        ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
                                  h->picture_structure == PICT_BOTTOM_FIELD);
    emms_c();
    h->current_slice = 0;
    return err;
}


static void sdhci_write_dataport(SDHCIState *s, uint32_t value, unsigned size)

{

    unsigned i;

    /* Check that there is free space left in a buffer */

    if (!(s->prnsts & SDHC_SPACE_AVAILABLE)) {

        ERRPRINT("Can't write to data buffer: buffer full\n");

        return;

    }

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

        s->fifo_buffer[s->data_count] = value & 0xFF;

        s->data_count++;

        value >>= 8;

        if (s->data_count >= (s->blksize & 0x0fff)) {

            DPRINT_L2("write buffer filled with %u bytes of data\n",

                    s->data_count);

            s->data_count = 0;

            s->prnsts &= ~SDHC_SPACE_AVAILABLE;

            if (s->prnsts & SDHC_DOING_WRITE) {

                sdhci_write_block_to_card(s);

            }

        }

    }

}


static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)

{

    const char *filename = opts->device;

    CharDriverState *chr;

    WinCharState *s;

    chr = qemu_chr_alloc();

    s = g_malloc0(sizeof(WinCharState));

    chr->opaque = s;

    chr->chr_write = win_chr_write;

    chr->chr_close = win_chr_close;

    if (win_chr_pipe_init(chr, filename) < 0) {

        g_free(s);

        g_free(chr);

        return NULL;

    }

    return chr;

}


static int sbr_hf_calc_npatches(AACContext *ac, SpectralBandReplication *sbr)

{

    int i, k, sb = 0;

    int msb = sbr->k[0];

    int usb = sbr->kx[1];

    int goal_sb = ((1000 << 11) + (sbr->sample_rate >> 1)) / sbr->sample_rate;

    sbr->num_patches = 0;

    if (goal_sb < sbr->kx[1] + sbr->m[1]) {

        for (k = 0; sbr->f_master[k] < goal_sb; k++) ;

    } else

        k = sbr->n_master;

    do {

        int odd = 0;

        for (i = k; i == k || sb > (sbr->k[0] - 1 + msb - odd); i--) {

            sb = sbr->f_master[i];

            odd = (sb + sbr->k[0]) & 1;

        }

        sbr->patch_num_subbands[sbr->num_patches]  = FFMAX(sb - usb, 0);

        sbr->patch_start_subband[sbr->num_patches] = sbr->k[0] - odd - sbr->patch_num_subbands[sbr->num_patches];

        if (sbr->patch_num_subbands[sbr->num_patches] > 0) {

            usb = sb;

            msb = sb;

            sbr->num_patches++;

        } else

            msb = sbr->kx[1];

        if (sbr->f_master[k] - sb < 3)

            k = sbr->n_master;

    } while (sb != sbr->kx[1] + sbr->m[1]);

    if (sbr->patch_num_subbands[sbr->num_patches-1] < 3 && sbr->num_patches > 1)

        sbr->num_patches--;

    // Requirements (14496-3 sp04 p205) sets the maximum number of patches to 5

    // However the Coding Technologies decoder check uses 6 patches

    if (sbr->num_patches > 6) {

        av_log(ac->avccontext, AV_LOG_ERROR, "Too many patches: %d\n", sbr->num_patches);

        return -1;

    }

    return 0;

}


static void *thread_func(void *p)

{

    struct thread_info *info = p;

    rcu_register_thread();

    atomic_inc(&n_ready_threads);

    while (!atomic_mb_read(&test_start)) {

        cpu_relax();

    }

    rcu_read_lock();

    while (!atomic_read(&test_stop)) {

        info->r = xorshift64star(info->r);

        info->func(info);

    }

    rcu_read_unlock();

    rcu_unregister_thread();

    return NULL;

}


static int http_start_receive_data(HTTPContext *c)

{

    int fd;

    if (c->stream->feed_opened)

        return -1;

    /* Don't permit writing to this one */

    if (c->stream->readonly)

        return -1;

    /* open feed */

    fd = open(c->stream->feed_filename, O_RDWR);

    if (fd < 0) {

        http_log("Error opening feeder file: %s\n", strerror(errno));

        return -1;

    }

    c->feed_fd = fd;

    if (c->stream->truncate) {

        /* truncate feed file */

        ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);

        ftruncate(c->feed_fd, FFM_PACKET_SIZE);

        http_log("Truncating feed file '%s'\n", c->stream->feed_filename);

    } else {

        if ((c->stream->feed_write_index = ffm_read_write_index(fd)) < 0) {

            http_log("Error reading write index from feed file: %s\n", strerror(errno));

            return -1;

        }

    }

    c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd), FFM_PACKET_SIZE);

    c->stream->feed_size = lseek(fd, 0, SEEK_END);

    lseek(fd, 0, SEEK_SET);

    /* init buffer input */

    c->buffer_ptr = c->buffer;

    c->buffer_end = c->buffer + FFM_PACKET_SIZE;

    c->stream->feed_opened = 1;

    c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");

    return 0;

}


static int usb_host_scan_dev(void *opaque, USBScanFunc *func)

{

    FILE *f = NULL;

    char line[1024];

    char buf[1024];

    int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;

    char product_name[512];

    int ret = 0;

    if (!usb_host_device_path) {

        perror("husb: USB Host Device Path not set");

        goto the_end;

    }

    snprintf(line, sizeof(line), "%s/devices", usb_host_device_path);

    f = fopen(line, "r");

    if (!f) {

        perror("husb: cannot open devices file");

        goto the_end;

    }

    device_count = 0;

    bus_num = addr = class_id = product_id = vendor_id = 0;

    speed = -1; /* Can't get the speed from /[proc|dev]/bus/usb/devices */

    for(;;) {

        if (fgets(line, sizeof(line), f) == NULL) {

            break;

        }

        if (strlen(line) > 0) {

            line[strlen(line) - 1] = '\0';

        }

        if (line[0] == 'T' && line[1] == ':') {

            if (device_count && (vendor_id || product_id)) {

                /* New device.  Add the previously discovered device.  */

                ret = func(opaque, bus_num, addr, 0, class_id, vendor_id,

                           product_id, product_name, speed);

                if (ret) {

                    goto the_end;

                }

            }

            if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0) {

                goto fail;

            }

            bus_num = atoi(buf);

            if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0) {

                goto fail;

            }

            addr = atoi(buf);

            if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0) {

                goto fail;

            }

            if (!strcmp(buf, "5000")) {

                speed = USB_SPEED_SUPER;

            } else if (!strcmp(buf, "480")) {

                speed = USB_SPEED_HIGH;

            } else if (!strcmp(buf, "1.5")) {

                speed = USB_SPEED_LOW;

            } else {

                speed = USB_SPEED_FULL;

            }

            product_name[0] = '\0';

            class_id = 0xff;

            device_count++;

            product_id = 0;

            vendor_id = 0;

        } else if (line[0] == 'P' && line[1] == ':') {

            if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0) {

                goto fail;

            }

            vendor_id = strtoul(buf, NULL, 16);

            if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0) {

                goto fail;

            }

            product_id = strtoul(buf, NULL, 16);

        } else if (line[0] == 'S' && line[1] == ':') {

            if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0) {

                goto fail;

            }

            pstrcpy(product_name, sizeof(product_name), buf);

        } else if (line[0] == 'D' && line[1] == ':') {

            if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0) {

                goto fail;

            }

            class_id = strtoul(buf, NULL, 16);

        }

    fail: ;

    }

    if (device_count && (vendor_id || product_id)) {

        /* Add the last device.  */

        ret = func(opaque, bus_num, addr, 0, class_id, vendor_id,

                   product_id, product_name, speed);

    }

 the_end:

    if (f) {

        fclose(f);

    }

    return ret;

}


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

{

    PowerPCCPUClass *pcc = POWERPC_CPU_CLASS(oc);

    CPUClass *cc = CPU_CLASS(oc);

    DeviceClass *dc = DEVICE_CLASS(oc);

    pcc->parent_realize = dc->realize;

    pcc->pvr = CPU_POWERPC_DEFAULT_MASK;

    pcc->pvr_mask = CPU_POWERPC_DEFAULT_MASK;

    pcc->interrupts_big_endian = ppc_cpu_interrupts_big_endian_always;

    dc->realize = ppc_cpu_realizefn;

    dc->unrealize = ppc_cpu_unrealizefn;

    pcc->parent_reset = cc->reset;

    cc->reset = ppc_cpu_reset;

    cc->class_by_name = ppc_cpu_class_by_name;

    cc->has_work = ppc_cpu_has_work;

    cc->do_interrupt = ppc_cpu_do_interrupt;

    cc->dump_state = ppc_cpu_dump_state;

    cc->dump_statistics = ppc_cpu_dump_statistics;

    cc->set_pc = ppc_cpu_set_pc;

    cc->gdb_read_register = ppc_cpu_gdb_read_register;

    cc->gdb_write_register = ppc_cpu_gdb_write_register;

#ifdef CONFIG_USER_ONLY

    cc->handle_mmu_fault = ppc_cpu_handle_mmu_fault;

#else

    cc->get_phys_page_debug = ppc_cpu_get_phys_page_debug;

    cc->vmsd = &vmstate_ppc_cpu;

#if defined(TARGET_PPC64)

    cc->write_elf64_note = ppc64_cpu_write_elf64_note;

    cc->write_elf64_qemunote = ppc64_cpu_write_elf64_qemunote;

#endif

#endif

    cc->gdb_num_core_regs = 71;

#ifdef USE_APPLE_GDB

    cc->gdb_read_register = ppc_cpu_gdb_read_register_apple;

    cc->gdb_write_register = ppc_cpu_gdb_write_register_apple;

    cc->gdb_num_core_regs = 71 + 32;

#endif

#if defined(TARGET_PPC64)

    cc->gdb_core_xml_file = "power64-core.xml";

#else

    cc->gdb_core_xml_file = "power-core.xml";

#endif

#ifndef CONFIG_USER_ONLY

    cc->virtio_is_big_endian = ppc_cpu_is_big_endian;

#endif

    dc->fw_name = "PowerPC,UNKNOWN";

}


qemu_deliver_packet(VLANClientState *sender, const uint8_t *buf, int size)

{

    VLANClientState *vc;

    for (vc = sender->vlan->first_client; vc != NULL; vc = vc->next) {

        if (vc != sender && !vc->link_down) {

            vc->receive(vc->opaque, buf, size);

        }

    }

}


void ppc970_irq_init (CPUState *env)

{

    env->irq_inputs = (void **)qemu_allocate_irqs(&ppc970_set_irq, env, 7);

}


static void do_interrupt_protected(CPUX86State *env, int intno, int is_int,

                                   int error_code, unsigned int next_eip,

                                   int is_hw)

{

    SegmentCache *dt;

    target_ulong ptr, ssp;

    int type, dpl, selector, ss_dpl, cpl;

    int has_error_code, new_stack, shift;

    uint32_t e1, e2, offset, ss = 0, esp, ss_e1 = 0, ss_e2 = 0;

    uint32_t old_eip, sp_mask;

    int vm86 = env->eflags & VM_MASK;

    has_error_code = 0;

    if (!is_int && !is_hw) {

        has_error_code = exception_has_error_code(intno);

    }

    if (is_int) {

        old_eip = next_eip;

    } else {

        old_eip = env->eip;

    }

    dt = &env->idt;

    if (intno * 8 + 7 > dt->limit) {

        raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);

    }

    ptr = dt->base + intno * 8;

    e1 = cpu_ldl_kernel(env, ptr);

    e2 = cpu_ldl_kernel(env, ptr + 4);

    /* check gate type */

    type = (e2 >> DESC_TYPE_SHIFT) & 0x1f;

    switch (type) {

    case 5: /* task gate */

        /* must do that check here to return the correct error code */

        if (!(e2 & DESC_P_MASK)) {

            raise_exception_err(env, EXCP0B_NOSEG, intno * 8 + 2);

        }

        switch_tss(env, intno * 8, e1, e2, SWITCH_TSS_CALL, old_eip);

        if (has_error_code) {

            int type;

            uint32_t mask;

            /* push the error code */

            type = (env->tr.flags >> DESC_TYPE_SHIFT) & 0xf;

            shift = type >> 3;

            if (env->segs[R_SS].flags & DESC_B_MASK) {

                mask = 0xffffffff;

            } else {

                mask = 0xffff;

            }

            esp = (env->regs[R_ESP] - (2 << shift)) & mask;

            ssp = env->segs[R_SS].base + esp;

            if (shift) {

                cpu_stl_kernel(env, ssp, error_code);

            } else {

                cpu_stw_kernel(env, ssp, error_code);

            }

            SET_ESP(esp, mask);

        }

        return;

    case 6: /* 286 interrupt gate */

    case 7: /* 286 trap gate */

    case 14: /* 386 interrupt gate */

    case 15: /* 386 trap gate */

        break;

    default:

        raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);

        break;

    }

    dpl = (e2 >> DESC_DPL_SHIFT) & 3;

    cpl = env->hflags & HF_CPL_MASK;

    /* check privilege if software int */

    if (is_int && dpl < cpl) {

        raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);

    }

    /* check valid bit */

    if (!(e2 & DESC_P_MASK)) {

        raise_exception_err(env, EXCP0B_NOSEG, intno * 8 + 2);

    }

    selector = e1 >> 16;

    offset = (e2 & 0xffff0000) | (e1 & 0x0000ffff);

    if ((selector & 0xfffc) == 0) {

        raise_exception_err(env, EXCP0D_GPF, 0);

    }

    if (load_segment(env, &e1, &e2, selector) != 0) {

        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);

    }

    if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK))) {

        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);

    }

    dpl = (e2 >> DESC_DPL_SHIFT) & 3;

    if (dpl > cpl) {

        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);

    }

    if (!(e2 & DESC_P_MASK)) {

        raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);

    }

    if (!(e2 & DESC_C_MASK) && dpl < cpl) {

        /* to inner privilege */

        get_ss_esp_from_tss(env, &ss, &esp, dpl, 0);

        if ((ss & 0xfffc) == 0) {

            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);

        }

        if ((ss & 3) != dpl) {

            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);

        }

        if (load_segment(env, &ss_e1, &ss_e2, ss) != 0) {

            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);

        }

        ss_dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;

        if (ss_dpl != dpl) {

            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);

        }

        if (!(ss_e2 & DESC_S_MASK) ||

            (ss_e2 & DESC_CS_MASK) ||

            !(ss_e2 & DESC_W_MASK)) {

            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);

        }

        if (!(ss_e2 & DESC_P_MASK)) {

            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);

        }

        new_stack = 1;

        sp_mask = get_sp_mask(ss_e2);

        ssp = get_seg_base(ss_e1, ss_e2);

    } else if ((e2 & DESC_C_MASK) || dpl == cpl) {

        /* to same privilege */

        if (vm86) {

            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);

        }

        new_stack = 0;

        sp_mask = get_sp_mask(env->segs[R_SS].flags);

        ssp = env->segs[R_SS].base;

        esp = env->regs[R_ESP];

        dpl = cpl;

    } else {

        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);

        new_stack = 0; /* avoid warning */

        sp_mask = 0; /* avoid warning */

        ssp = 0; /* avoid warning */

        esp = 0; /* avoid warning */

    }

    shift = type >> 3;

#if 0

    /* XXX: check that enough room is available */

    push_size = 6 + (new_stack << 2) + (has_error_code << 1);

    if (vm86) {

        push_size += 8;

    }

    push_size <<= shift;

#endif

    if (shift == 1) {

        if (new_stack) {

            if (vm86) {

                PUSHL(ssp, esp, sp_mask, env->segs[R_GS].selector);

                PUSHL(ssp, esp, sp_mask, env->segs[R_FS].selector);

                PUSHL(ssp, esp, sp_mask, env->segs[R_DS].selector);

                PUSHL(ssp, esp, sp_mask, env->segs[R_ES].selector);

            }

            PUSHL(ssp, esp, sp_mask, env->segs[R_SS].selector);

            PUSHL(ssp, esp, sp_mask, env->regs[R_ESP]);

        }

        PUSHL(ssp, esp, sp_mask, cpu_compute_eflags(env));

        PUSHL(ssp, esp, sp_mask, env->segs[R_CS].selector);

        PUSHL(ssp, esp, sp_mask, old_eip);

        if (has_error_code) {

            PUSHL(ssp, esp, sp_mask, error_code);

        }

    } else {

        if (new_stack) {

            if (vm86) {

                PUSHW(ssp, esp, sp_mask, env->segs[R_GS].selector);

                PUSHW(ssp, esp, sp_mask, env->segs[R_FS].selector);

                PUSHW(ssp, esp, sp_mask, env->segs[R_DS].selector);

                PUSHW(ssp, esp, sp_mask, env->segs[R_ES].selector);

            }

            PUSHW(ssp, esp, sp_mask, env->segs[R_SS].selector);

            PUSHW(ssp, esp, sp_mask, env->regs[R_ESP]);

        }

        PUSHW(ssp, esp, sp_mask, cpu_compute_eflags(env));

        PUSHW(ssp, esp, sp_mask, env->segs[R_CS].selector);

        PUSHW(ssp, esp, sp_mask, old_eip);

        if (has_error_code) {

            PUSHW(ssp, esp, sp_mask, error_code);

        }

    }

    /* interrupt gate clear IF mask */

    if ((type & 1) == 0) {

        env->eflags &= ~IF_MASK;

    }

    env->eflags &= ~(TF_MASK | VM_MASK | RF_MASK | NT_MASK);

    if (new_stack) {

        if (vm86) {

            cpu_x86_load_seg_cache(env, R_ES, 0, 0, 0, 0);

            cpu_x86_load_seg_cache(env, R_DS, 0, 0, 0, 0);

            cpu_x86_load_seg_cache(env, R_FS, 0, 0, 0, 0);

            cpu_x86_load_seg_cache(env, R_GS, 0, 0, 0, 0);

        }

        ss = (ss & ~3) | dpl;

        cpu_x86_load_seg_cache(env, R_SS, ss,

                               ssp, get_seg_limit(ss_e1, ss_e2), ss_e2);

    }

    SET_ESP(esp, sp_mask);

    selector = (selector & ~3) | dpl;

    cpu_x86_load_seg_cache(env, R_CS, selector,

                   get_seg_base(e1, e2),

                   get_seg_limit(e1, e2),

                   e2);

    env->eip = offset;

}


static void kvm_start_vcpu(CPUState *env)

{

    env->thread = qemu_mallocz(sizeof(QemuThread));

    env->halt_cond = qemu_mallocz(sizeof(QemuCond));

    qemu_cond_init(env->halt_cond);

    qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);

    while (env->created == 0)

        qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);

}


static hwaddr ppc_hash64_pteg_search(PowerPCCPU *cpu, hwaddr hash,

                                     bool secondary, target_ulong ptem,

                                     ppc_hash_pte64_t *pte)

{

    CPUPPCState *env = &cpu->env;

    int i;

    uint64_t token;

    target_ulong pte0, pte1;

    target_ulong pte_index;

    pte_index = (hash & env->htab_mask) * HPTES_PER_GROUP;

    token = ppc_hash64_start_access(cpu, pte_index);

    if (!token) {

        return -1;

    }

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

        pte0 = ppc_hash64_load_hpte0(cpu, token, i);

        pte1 = ppc_hash64_load_hpte1(cpu, token, i);

        if ((pte0 & HPTE64_V_VALID)

            && (secondary == !!(pte0 & HPTE64_V_SECONDARY))

            && HPTE64_V_COMPARE(pte0, ptem)) {

            pte->pte0 = pte0;

            pte->pte1 = pte1;

            ppc_hash64_stop_access(token);

            return (pte_index + i) * HASH_PTE_SIZE_64;

        }

    }

    ppc_hash64_stop_access(token);

    /*

     * We didn't find a valid entry.

     */

    return -1;

}


static av_cold int dcadec_init(AVCodecContext *avctx)

{

    DCAContext *s = avctx->priv_data;

    s->avctx = avctx;

    s->core.avctx = avctx;

    s->exss.avctx = avctx;

    s->xll.avctx = avctx;

    s->lbr.avctx = avctx;

    ff_dca_init_vlcs();

    if (ff_dca_core_init(&s->core) < 0)

        return AVERROR(ENOMEM);

    if (ff_dca_lbr_init(&s->lbr) < 0)

        return AVERROR(ENOMEM);

    ff_dcadsp_init(&s->dcadsp);

    s->core.dcadsp = &s->dcadsp;

    s->xll.dcadsp = &s->dcadsp;

    s->lbr.dcadsp = &s->dcadsp;

    s->crctab = av_crc_get_table(AV_CRC_16_CCITT);

    switch (avctx->request_channel_layout & ~AV_CH_LAYOUT_NATIVE) {

    case 0:

        s->request_channel_layout = 0;

        break;

    case AV_CH_LAYOUT_STEREO:

    case AV_CH_LAYOUT_STEREO_DOWNMIX:

        s->request_channel_layout = DCA_SPEAKER_LAYOUT_STEREO;

        break;

    case AV_CH_LAYOUT_5POINT0:

        s->request_channel_layout = DCA_SPEAKER_LAYOUT_5POINT0;

        break;

    case AV_CH_LAYOUT_5POINT1:

        s->request_channel_layout = DCA_SPEAKER_LAYOUT_5POINT1;

        break;

    default:

        av_log(avctx, AV_LOG_WARNING, "Invalid request_channel_layout\n");

        break;

    }

    avctx->sample_fmt = AV_SAMPLE_FMT_S32P;

    avctx->bits_per_raw_sample = 24;

    return 0;

}