static int mmu_translate_segment(CPUS390XState *env, target_ulong vaddr,

                                 uint64_t asc, uint64_t st_entry,

                                 target_ulong *raddr, int *flags, int rw)

{

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

    uint64_t origin, offs, pt_entry;

    if (st_entry & _SEGMENT_ENTRY_RO) {

        *flags &= ~PAGE_WRITE;

    }

    if ((st_entry & _SEGMENT_ENTRY_FC) && (env->cregs[0] & CR0_EDAT)) {

        /* Decode EDAT1 segment frame absolute address (1MB page) */

        *raddr = (st_entry & 0xfffffffffff00000ULL) | (vaddr & 0xfffff);

        PTE_DPRINTF("%s: SEG=0x%" PRIx64 "\n", __func__, st_entry);

        return 0;

    }

    /* Look up 4KB page entry */

    origin = st_entry & _SEGMENT_ENTRY_ORIGIN;

    offs  = (vaddr & VADDR_PX) >> 9;

    pt_entry = ldq_phys(cs->as, origin + offs);

    PTE_DPRINTF("%s: 0x%" PRIx64 " + 0x%" PRIx64 " => 0x%016" PRIx64 "\n",

                __func__, origin, offs, pt_entry);

    return mmu_translate_pte(env, vaddr, asc, pt_entry, raddr, flags, rw);

}


static int64_t coroutine_fn bdrv_co_get_block_status_above(BlockDriverState *bs,

        BlockDriverState *base,

        int64_t sector_num,

        int nb_sectors,

        int *pnum,

        BlockDriverState **file)

{

    BlockDriverState *p;

    int64_t ret = 0;

    bool first = true;

    assert(bs != base);

    for (p = bs; p != base; p = backing_bs(p)) {

        ret = bdrv_co_get_block_status(p, sector_num, nb_sectors, pnum, file);

        if (ret < 0) {

            break;

        }

        if (ret & BDRV_BLOCK_ZERO && ret & BDRV_BLOCK_EOF && !first) {

            /*

             * Reading beyond the end of the file continues to read

             * zeroes, but we can only widen the result to the

             * unallocated length we learned from an earlier

             * iteration.

             */

            *pnum = nb_sectors;

        }

        if (ret & (BDRV_BLOCK_ZERO | BDRV_BLOCK_DATA)) {

            break;

        }

        /* [sector_num, pnum] unallocated on this layer, which could be only

         * the first part of [sector_num, nb_sectors].  */

        nb_sectors = MIN(nb_sectors, *pnum);

        first = false;

    }

    return ret;

}


static uint64_t openpic_src_read(void *opaque, uint64_t addr, unsigned len)

{

    OpenPICState *opp = opaque;

    uint32_t retval;

    int idx;

    DPRINTF("%s: addr %#" HWADDR_PRIx "\n", __func__, addr);

    retval = 0xFFFFFFFF;

    if (addr & 0xF) {

        return retval;

    }

    addr = addr & 0xFFF0;

    idx = addr >> 5;

    if (addr & 0x10) {

        /* EXDE / IFEDE / IEEDE */

        retval = read_IRQreg_idr(opp, idx);

    } else {

        /* EXVP / IFEVP / IEEVP */

        retval = read_IRQreg_ivpr(opp, idx);

    }

    DPRINTF("%s: => 0x%08x\n", __func__, retval);

    return retval;

}


static CharDriverState *chr_baum_init(const char *id,

                                      ChardevBackend *backend,

                                      ChardevReturn *ret,

                                      Error **errp)

{

    BaumDriverState *baum;

    CharDriverState *chr;

    brlapi_handle_t *handle;

#if defined(CONFIG_SDL)

#if SDL_COMPILEDVERSION < SDL_VERSIONNUM(2, 0, 0)

    SDL_SysWMinfo info;

#endif

#endif

    int tty;

    baum = g_malloc0(sizeof(BaumDriverState));

    baum->chr = chr = qemu_chr_alloc();

    chr->opaque = baum;

    chr->chr_write = baum_write;

    chr->chr_accept_input = baum_accept_input;

    chr->chr_close = baum_close;

    handle = g_malloc0(brlapi_getHandleSize());

    baum->brlapi = handle;

    baum->brlapi_fd = brlapi__openConnection(handle, NULL, NULL);

    if (baum->brlapi_fd == -1) {

        error_setg(errp, "brlapi__openConnection: %s",

                   brlapi_strerror(brlapi_error_location()));

        goto fail_handle;

    }

    baum->cellCount_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, baum_cellCount_timer_cb, baum);

    if (brlapi__getDisplaySize(handle, &baum->x, &baum->y) == -1) {

        error_setg(errp, "brlapi__getDisplaySize: %s",

                   brlapi_strerror(brlapi_error_location()));

        goto fail;

    }

#if defined(CONFIG_SDL)

#if SDL_COMPILEDVERSION < SDL_VERSIONNUM(2, 0, 0)

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

    SDL_VERSION(&info.version);

    if (SDL_GetWMInfo(&info))

        tty = info.info.x11.wmwindow;

    else

#endif

#endif

        tty = BRLAPI_TTY_DEFAULT;

    if (brlapi__enterTtyMode(handle, tty, NULL) == -1) {

        error_setg(errp, "brlapi__enterTtyMode: %s",

                   brlapi_strerror(brlapi_error_location()));

        goto fail;

    }

    qemu_set_fd_handler(baum->brlapi_fd, baum_chr_read, NULL, baum);

    return chr;

fail:

    timer_free(baum->cellCount_timer);

    brlapi__closeConnection(handle);

fail_handle:

    g_free(handle);

    g_free(chr);

    g_free(baum);

    return NULL;

}


QemuOpts *qemu_opts_create(QemuOptsList *list, const char *id, int fail_if_exists)

{

    QemuOpts *opts = NULL;

    if (id) {

        if (!id_wellformed(id)) {

            qerror_report(QERR_INVALID_PARAMETER_VALUE, "id", "an identifier");

            error_printf_unless_qmp("Identifiers consist of letters, digits, '-', '.', '_', starting with a letter.\n");

            return NULL;

        }

        opts = qemu_opts_find(list, id);

        if (opts != NULL) {

            if (fail_if_exists && !list->merge_lists) {

                qerror_report(QERR_DUPLICATE_ID, id, list->name);

                return NULL;

            } else {

                return opts;

            }

        }

    } else if (list->merge_lists) {

        opts = qemu_opts_find(list, NULL);

        if (opts) {

            return opts;

        }

    }

    opts = g_malloc0(sizeof(*opts));

    if (id) {

        opts->id = g_strdup(id);

    }

    opts->list = list;

    loc_save(&opts->loc);

    QTAILQ_INIT(&opts->head);

    QTAILQ_INSERT_TAIL(&list->head, opts, next);

    return opts;

}


static int yuv4_read_header(AVFormatContext *s)

{

    char header[MAX_YUV4_HEADER + 10];  // Include headroom for

                                        // the longest option

    char *tokstart, *tokend, *header_end;

    int i;

    AVIOContext *pb = s->pb;

    int width = -1, height  = -1, raten   = 0,

        rated =  0, aspectn =  0, aspectd = 0;

    enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE, alt_pix_fmt = AV_PIX_FMT_NONE;

    enum AVChromaLocation chroma_sample_location = AVCHROMA_LOC_UNSPECIFIED;

    AVStream *st;

    enum AVFieldOrder field_order;

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

        header[i] = avio_r8(pb);

        if (header[i] == '\n') {

            header[i + 1] = 0x20;  // Add a space after last option.

                                   // Makes parsing "444" vs "444alpha" easier.

            header[i + 2] = 0;

            break;

        }

    }

    if (i == MAX_YUV4_HEADER)

        return -1;

    if (strncmp(header, Y4M_MAGIC, strlen(Y4M_MAGIC)))

        return -1;

    header_end = &header[i + 1]; // Include space

    for (tokstart = &header[strlen(Y4M_MAGIC) + 1];

         tokstart < header_end; tokstart++) {

        if (*tokstart == 0x20)

            continue;

        switch (*tokstart++) {

        case 'W': // Width. Required.

            width    = strtol(tokstart, &tokend, 10);

            tokstart = tokend;

            break;

        case 'H': // Height. Required.

            height   = strtol(tokstart, &tokend, 10);

            tokstart = tokend;

            break;

        case 'C': // Color space

            if (strncmp("420jpeg", tokstart, 7) == 0) {

                pix_fmt = AV_PIX_FMT_YUV420P;

                chroma_sample_location = AVCHROMA_LOC_CENTER;

            } else if (strncmp("420mpeg2", tokstart, 8) == 0) {

                pix_fmt = AV_PIX_FMT_YUV420P;

                chroma_sample_location = AVCHROMA_LOC_LEFT;

            } else if (strncmp("420paldv", tokstart, 8) == 0) {

                pix_fmt = AV_PIX_FMT_YUV420P;

                chroma_sample_location = AVCHROMA_LOC_TOPLEFT;

            } else if (strncmp("420p16", tokstart, 6) == 0) {

                pix_fmt = AV_PIX_FMT_YUV420P16;

            } else if (strncmp("422p16", tokstart, 6) == 0) {

                pix_fmt = AV_PIX_FMT_YUV422P16;

            } else if (strncmp("444p16", tokstart, 6) == 0) {

                pix_fmt = AV_PIX_FMT_YUV444P16;

            } else if (strncmp("420p14", tokstart, 6) == 0) {

                pix_fmt = AV_PIX_FMT_YUV420P14;

            } else if (strncmp("422p14", tokstart, 6) == 0) {

                pix_fmt = AV_PIX_FMT_YUV422P14;

            } else if (strncmp("444p14", tokstart, 6) == 0) {

                pix_fmt = AV_PIX_FMT_YUV444P14;

            } else if (strncmp("420p12", tokstart, 6) == 0) {

                pix_fmt = AV_PIX_FMT_YUV420P12;

            } else if (strncmp("422p12", tokstart, 6) == 0) {

                pix_fmt = AV_PIX_FMT_YUV422P12;

            } else if (strncmp("444p12", tokstart, 6) == 0) {

                pix_fmt = AV_PIX_FMT_YUV444P12;

            } else if (strncmp("420p10", tokstart, 6) == 0) {

                pix_fmt = AV_PIX_FMT_YUV420P10;

            } else if (strncmp("422p10", tokstart, 6) == 0) {

                pix_fmt = AV_PIX_FMT_YUV422P10;

            } else if (strncmp("444p10", tokstart, 6) == 0) {

                pix_fmt = AV_PIX_FMT_YUV444P10;

            } else if (strncmp("420p9", tokstart, 5) == 0) {

                pix_fmt = AV_PIX_FMT_YUV420P9;

            } else if (strncmp("422p9", tokstart, 5) == 0) {

                pix_fmt = AV_PIX_FMT_YUV422P9;

            } else if (strncmp("444p9", tokstart, 5) == 0) {

                pix_fmt = AV_PIX_FMT_YUV444P9;

            } else if (strncmp("420", tokstart, 3) == 0) {

                pix_fmt = AV_PIX_FMT_YUV420P;

                chroma_sample_location = AVCHROMA_LOC_CENTER;

            } else if (strncmp("411", tokstart, 3) == 0) {

                pix_fmt = AV_PIX_FMT_YUV411P;

            } else if (strncmp("422", tokstart, 3) == 0) {

                pix_fmt = AV_PIX_FMT_YUV422P;

            } else if (strncmp("444alpha", tokstart, 8) == 0 ) {

                av_log(s, AV_LOG_ERROR, "Cannot handle 4:4:4:4 "

                       "YUV4MPEG stream.\n");

                return -1;

            } else if (strncmp("444", tokstart, 3) == 0) {

                pix_fmt = AV_PIX_FMT_YUV444P;

            } else if (strncmp("mono16", tokstart, 6) == 0) {

                pix_fmt = AV_PIX_FMT_GRAY16;

            } else if (strncmp("mono", tokstart, 4) == 0) {

                pix_fmt = AV_PIX_FMT_GRAY8;

            } else {

                av_log(s, AV_LOG_ERROR, "YUV4MPEG stream contains an unknown "

                       "pixel format.\n");

                return -1;

            }

            while (tokstart < header_end && *tokstart != 0x20)

                tokstart++;

            break;

        case 'I': // Interlace type

            switch (*tokstart++){

            case '?':

                field_order = AV_FIELD_UNKNOWN;

                break;

            case 'p':

                field_order = AV_FIELD_PROGRESSIVE;

                break;

            case 't':

                field_order = AV_FIELD_TT;

                break;

            case 'b':

                field_order = AV_FIELD_BB;

                break;

            case 'm':

                av_log(s, AV_LOG_ERROR, "YUV4MPEG stream contains mixed "

                       "interlaced and non-interlaced frames.\n");

            default:

                av_log(s, AV_LOG_ERROR, "YUV4MPEG has invalid header.\n");

                return AVERROR(EINVAL);

            }

            break;

        case 'F': // Frame rate

            sscanf(tokstart, "%d:%d", &raten, &rated); // 0:0 if unknown

            while (tokstart < header_end && *tokstart != 0x20)

                tokstart++;

            break;

        case 'A': // Pixel aspect

            sscanf(tokstart, "%d:%d", &aspectn, &aspectd); // 0:0 if unknown

            while (tokstart < header_end && *tokstart != 0x20)

                tokstart++;

            break;

        case 'X': // Vendor extensions

            if (strncmp("YSCSS=", tokstart, 6) == 0) {

                // Older nonstandard pixel format representation

                tokstart += 6;

                if (strncmp("420JPEG", tokstart, 7) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV420P;

                else if (strncmp("420MPEG2", tokstart, 8) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV420P;

                else if (strncmp("420PALDV", tokstart, 8) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV420P;

                else if (strncmp("420P9", tokstart, 5) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV420P9;

                else if (strncmp("422P9", tokstart, 5) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV422P9;

                else if (strncmp("444P9", tokstart, 5) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV444P9;

                else if (strncmp("420P10", tokstart, 6) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV420P10;

                else if (strncmp("422P10", tokstart, 6) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV422P10;

                else if (strncmp("444P10", tokstart, 6) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV444P10;

                else if (strncmp("420P12", tokstart, 6) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV420P12;

                else if (strncmp("422P12", tokstart, 6) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV422P12;

                else if (strncmp("444P12", tokstart, 6) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV444P12;

                else if (strncmp("420P14", tokstart, 6) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV420P14;

                else if (strncmp("422P14", tokstart, 6) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV422P14;

                else if (strncmp("444P14", tokstart, 6) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV444P14;

                else if (strncmp("420P16", tokstart, 6) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV420P16;

                else if (strncmp("422P16", tokstart, 6) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV422P16;

                else if (strncmp("444P16", tokstart, 6) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV444P16;

                else if (strncmp("411", tokstart, 3) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV411P;

                else if (strncmp("422", tokstart, 3) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV422P;

                else if (strncmp("444", tokstart, 3) == 0)

                    alt_pix_fmt = AV_PIX_FMT_YUV444P;

            }

            while (tokstart < header_end && *tokstart != 0x20)

                tokstart++;

            break;

        }

    }

    if (width == -1 || height == -1) {

        av_log(s, AV_LOG_ERROR, "YUV4MPEG has invalid header.\n");

        return -1;

    }

    if (pix_fmt == AV_PIX_FMT_NONE) {

        if (alt_pix_fmt == AV_PIX_FMT_NONE)

            pix_fmt = AV_PIX_FMT_YUV420P;

        else

            pix_fmt = alt_pix_fmt;

    }

    if (raten <= 0 || rated <= 0) {

        // Frame rate unknown

        raten = 25;

        rated = 1;

    }

    if (aspectn == 0 && aspectd == 0) {

        // Pixel aspect unknown

        aspectd = 1;

    }

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    st->codec->width  = width;

    st->codec->height = height;

    av_reduce(&raten, &rated, raten, rated, (1UL << 31) - 1);

    avpriv_set_pts_info(st, 64, rated, raten);

    st->avg_frame_rate                = av_inv_q(st->time_base);

    st->codec->pix_fmt                = pix_fmt;

    st->codec->codec_type             = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id               = AV_CODEC_ID_RAWVIDEO;

    st->sample_aspect_ratio           = (AVRational){ aspectn, aspectd };

    st->codec->chroma_sample_location = chroma_sample_location;

    st->codec->field_order            = field_order;

    return 0;

}


static uint64_t uart_read(void *opaque, target_phys_addr_t offset,

        unsigned size)

{

    UartState *s = (UartState *)opaque;

    uint32_t c = 0;

    offset >>= 2;

    if (offset > R_MAX) {

        return 0;

    } else if (offset == R_TX_RX) {

        uart_read_rx_fifo(s, &c);

        return c;

    }

    return s->r[offset];

}


static av_cold void alloc_temp(HYuvContext *s)

{

    int i;

    if (s->bitstream_bpp<24) {

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

            s->temp[i]= av_malloc(s->width + 16);

        }

    } else {

        s->temp[0]= av_mallocz(4*s->width + 16);

    }

}


static int r3d_read_red1(AVFormatContext *s)

{

    AVStream *st = avformat_new_stream(s, NULL);

    char filename[258];

    int tmp;

    int av_unused tmp2;

    AVRational framerate;

    if (!st)

        return AVERROR(ENOMEM);

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id = CODEC_ID_JPEG2000;

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

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

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

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

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

    tmp = avio_rb32(s->pb);

    avpriv_set_pts_info(st, 32, 1, tmp);

    tmp = avio_rb32(s->pb); // filenum

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

    avio_skip(s->pb, 32); // unknown

    st->codec->width  = avio_rb32(s->pb);

    st->codec->height = avio_rb32(s->pb);

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

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

    framerate.num = avio_rb16(s->pb);

    framerate.den = avio_rb16(s->pb);

    if (framerate.num && framerate.den)

        st->r_frame_rate = st->avg_frame_rate = framerate;

    tmp = avio_r8(s->pb); // audio channels

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

    if (tmp > 0) {

        AVStream *ast = avformat_new_stream(s, NULL);

        if (!ast)

            return AVERROR(ENOMEM);

        ast->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        ast->codec->codec_id = CODEC_ID_PCM_S32BE;

        ast->codec->channels = tmp;

        avpriv_set_pts_info(ast, 32, 1, st->time_base.den);

    }

    avio_read(s->pb, filename, 257);

    filename[sizeof(filename)-1] = 0;

    av_dict_set(&st->metadata, "filename", filename, 0);

    av_dlog(s, "filename %s\n", filename);

    av_dlog(s, "resolution %dx%d\n", st->codec->width, st->codec->height);

    av_dlog(s, "timescale %d\n", st->time_base.den);

    av_dlog(s, "frame rate %d/%d\n",

            framerate.num, framerate.den);

    return 0;

}


unsigned int avpriv_toupper4(unsigned int x)

{

    return av_toupper(x & 0xFF) +

          (av_toupper((x >>  8) & 0xFF) << 8)  +

          (av_toupper((x >> 16) & 0xFF) << 16) +

          (av_toupper((x >> 24) & 0xFF) << 24);

}


void pcie_cap_slot_hot_unplug_cb(HotplugHandler *hotplug_dev, DeviceState *dev,

                                 Error **errp)

{

    uint8_t *exp_cap;

    pcie_cap_slot_hotplug_common(PCI_DEVICE(hotplug_dev), dev, &exp_cap, errp);

    object_unparent(OBJECT(dev));

    pci_word_test_and_clear_mask(exp_cap + PCI_EXP_SLTSTA,

                                 PCI_EXP_SLTSTA_PDS);

    pcie_cap_slot_event(PCI_DEVICE(hotplug_dev), PCI_EXP_HP_EV_PDC);

}


int av_write_trailer(AVFormatContext *s)

{

    int ret;

    while(s->packet_buffer){

        int ret;

        AVPacketList *pktl= s->packet_buffer;

//av_log(s, AV_LOG_DEBUG, "write_trailer st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);

        truncate_ts(s->streams[pktl->pkt.stream_index], &pktl->pkt);

        ret= s->oformat->write_packet(s, &pktl->pkt);

        s->packet_buffer= pktl->next;

        av_free_packet(&pktl->pkt);

        av_freep(&pktl);

        if(ret<0)

            return ret;

    }

    ret = s->oformat->write_trailer(s);

    av_freep(&s->priv_data);

    return ret;

}


int ff_dca_xll_filter_frame(DCAXllDecoder *s, AVFrame *frame)

{

    AVCodecContext *avctx = s->avctx;

    DCAContext *dca = avctx->priv_data;

    DCAExssAsset *asset = &dca->exss.assets[0];

    DCAXllChSet *p = &s->chset[0], *c;

    enum AVMatrixEncoding matrix_encoding = AV_MATRIX_ENCODING_NONE;

    int i, j, k, ret, shift, nsamples, request_mask;

    int ch_remap[DCA_SPEAKER_COUNT];

    // Force lossy downmixed output during recovery

    if (dca->packet & DCA_PACKET_RECOVERY) {

        for (i = 0, c = s->chset; i < s->nchsets; i++, c++) {

            if (i < s->nactivechsets)

                force_lossy_output(s, c);

            if (!c->primary_chset)

                c->dmix_embedded = 0;

        }

        s->scalable_lsbs = 0;

        s->fixed_lsb_width = 0;

    }

    // Filter frequency bands for active channel sets

    s->output_mask = 0;

    for (i = 0, c = s->chset; i < s->nactivechsets; i++, c++) {

        chs_filter_band_data(s, c, 0);

        if (c->residual_encode != (1 << c->nchannels) - 1

            && (ret = combine_residual_frame(s, c)) < 0)

            return ret;

        if (s->scalable_lsbs)

            chs_assemble_msbs_lsbs(s, c, 0);

        if (c->nfreqbands > 1) {

            chs_filter_band_data(s, c, 1);

            chs_assemble_msbs_lsbs(s, c, 1);

        }

        s->output_mask |= c->ch_mask;

    }

    // Undo hierarchial downmix and/or apply scaling

    for (i = 1, c = &s->chset[1]; i < s->nchsets; i++, c++) {

        if (!is_hier_dmix_chset(c))

            continue;

        if (i >= s->nactivechsets) {

            for (j = 0; j < c->nfreqbands; j++)

                if (c->bands[j].dmix_embedded)

                    scale_down_mix(s, c, j);

            break;

        }

        for (j = 0; j < c->nfreqbands; j++)

            if (c->bands[j].dmix_embedded)

                undo_down_mix(s, c, j);

    }

    // Assemble frequency bands for active channel sets

    if (s->nfreqbands > 1) {

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

            if ((ret = chs_assemble_freq_bands(s, &s->chset[i])) < 0)

                return ret;

    }

    // Normalize to regular 5.1 layout if downmixing

    if (dca->request_channel_layout) {

        if (s->output_mask & DCA_SPEAKER_MASK_Lss) {

            s->output_samples[DCA_SPEAKER_Ls] = s->output_samples[DCA_SPEAKER_Lss];

            s->output_mask = (s->output_mask & ~DCA_SPEAKER_MASK_Lss) | DCA_SPEAKER_MASK_Ls;

        }

        if (s->output_mask & DCA_SPEAKER_MASK_Rss) {

            s->output_samples[DCA_SPEAKER_Rs] = s->output_samples[DCA_SPEAKER_Rss];

            s->output_mask = (s->output_mask & ~DCA_SPEAKER_MASK_Rss) | DCA_SPEAKER_MASK_Rs;

        }

    }

    // Handle downmixing to stereo request

    if (dca->request_channel_layout == DCA_SPEAKER_LAYOUT_STEREO

        && DCA_HAS_STEREO(s->output_mask) && p->dmix_embedded

        && (p->dmix_type == DCA_DMIX_TYPE_LoRo ||

            p->dmix_type == DCA_DMIX_TYPE_LtRt))

        request_mask = DCA_SPEAKER_LAYOUT_STEREO;

    else

        request_mask = s->output_mask;

    if (!ff_dca_set_channel_layout(avctx, ch_remap, request_mask))

        return AVERROR(EINVAL);

    avctx->sample_rate = p->freq << (s->nfreqbands - 1);

    switch (p->storage_bit_res) {

    case 16:

        avctx->sample_fmt = AV_SAMPLE_FMT_S16P;

        shift = 16 - p->pcm_bit_res;

        break;

    case 20:

    case 24:

        avctx->sample_fmt = AV_SAMPLE_FMT_S32P;

        shift = 24 - p->pcm_bit_res;

        break;

    default:

        return AVERROR(EINVAL);

    }

    avctx->bits_per_raw_sample = p->storage_bit_res;

    avctx->profile = FF_PROFILE_DTS_HD_MA;

    avctx->bit_rate = 0;

    frame->nb_samples = nsamples = s->nframesamples << (s->nfreqbands - 1);

    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)

        return ret;

    // Downmix primary channel set to stereo

    if (request_mask != s->output_mask) {

        ff_dca_downmix_to_stereo_fixed(s->dcadsp, s->output_samples,

                                       p->dmix_coeff, nsamples,

                                       s->output_mask);

    }

    for (i = 0; i < avctx->channels; i++) {

        int32_t *samples = s->output_samples[ch_remap[i]];

        if (frame->format == AV_SAMPLE_FMT_S16P) {

            int16_t *plane = (int16_t *)frame->extended_data[i];

            for (k = 0; k < nsamples; k++)

                plane[k] = av_clip_int16(samples[k] * (1 << shift));

        } else {

            int32_t *plane = (int32_t *)frame->extended_data[i];

            for (k = 0; k < nsamples; k++)

                plane[k] = clip23(samples[k] * (1 << shift)) * (1 << 8);

        }

    }

    if (!asset->one_to_one_map_ch_to_spkr) {

        if (asset->representation_type == DCA_REPR_TYPE_LtRt)

            matrix_encoding = AV_MATRIX_ENCODING_DOLBY;

        else if (asset->representation_type == DCA_REPR_TYPE_LhRh)

            matrix_encoding = AV_MATRIX_ENCODING_DOLBYHEADPHONE;

    } else if (request_mask != s->output_mask && p->dmix_type == DCA_DMIX_TYPE_LtRt) {

        matrix_encoding = AV_MATRIX_ENCODING_DOLBY;

    }

    if ((ret = ff_side_data_update_matrix_encoding(frame, matrix_encoding)) < 0)

        return ret;

    return 0;

}


static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)

{

    bs->bl.max_discard = UINT32_MAX >> BDRV_SECTOR_BITS;

    bs->bl.max_transfer_length = UINT32_MAX >> BDRV_SECTOR_BITS;

}


static void posix_aio_read(void *opaque)

{

    PosixAioState *s = opaque;

    ssize_t len;

    /* read all bytes from signal pipe */

    for (;;) {

        char bytes[16];

        len = read(s->rfd, bytes, sizeof(bytes));

        if (len == -1 && errno == EINTR)

            continue; /* try again */

        if (len == sizeof(bytes))

            continue; /* more to read */

        break;

    }

    posix_aio_process_queue(s);

}


static int qemu_rdma_register_and_get_keys(RDMAContext *rdma,

        RDMALocalBlock *block, uint8_t *host_addr,

        uint32_t *lkey, uint32_t *rkey, int chunk,

        uint8_t *chunk_start, uint8_t *chunk_end)

{

    if (block->mr) {

        if (lkey) {

            *lkey = block->mr->lkey;

        }

        if (rkey) {

            *rkey = block->mr->rkey;

        }

        return 0;

    }

    /* allocate memory to store chunk MRs */

    if (!block->pmr) {

        block->pmr = g_malloc0(block->nb_chunks * sizeof(struct ibv_mr *));

        if (!block->pmr) {

            return -1;

        }

    }

    /*

     * If 'rkey', then we're the destination, so grant access to the source.

     *

     * If 'lkey', then we're the source VM, so grant access only to ourselves.

     */

    if (!block->pmr[chunk]) {

        uint64_t len = chunk_end - chunk_start;

        DDPRINTF("Registering %" PRIu64 " bytes @ %p\n",

                 len, chunk_start);

        block->pmr[chunk] = ibv_reg_mr(rdma->pd,

                chunk_start, len,

                (rkey ? (IBV_ACCESS_LOCAL_WRITE |

                        IBV_ACCESS_REMOTE_WRITE) : 0));

        if (!block->pmr[chunk]) {

            perror("Failed to register chunk!");

            fprintf(stderr, "Chunk details: block: %d chunk index %d"

                            " start %" PRIu64 " end %" PRIu64 " host %" PRIu64

                            " local %" PRIu64 " registrations: %d\n",

                            block->index, chunk, (uint64_t) chunk_start,

                            (uint64_t) chunk_end, (uint64_t) host_addr,

                            (uint64_t) block->local_host_addr,

                            rdma->total_registrations);

            return -1;

        }

        rdma->total_registrations++;

    }

    if (lkey) {

        *lkey = block->pmr[chunk]->lkey;

    }

    if (rkey) {

        *rkey = block->pmr[chunk]->rkey;

    }

    return 0;

}


static int get_logical_cpus(AVCodecContext *avctx)

{

    int ret, nb_cpus = 1;

#if HAVE_SCHED_GETAFFINITY && defined(CPU_COUNT)

    cpu_set_t cpuset;

    CPU_ZERO(&cpuset);

    ret = sched_getaffinity(0, sizeof(cpuset), &cpuset);

    if (!ret) {

        nb_cpus = CPU_COUNT(&cpuset);

    }

#elif HAVE_GETSYSTEMINFO

    SYSTEM_INFO sysinfo;

    GetSystemInfo(&sysinfo);

    nb_cpus = sysinfo.dwNumberOfProcessors;

#elif HAVE_SYSCTL && defined(HW_NCPU)

    int mib[2] = { CTL_HW, HW_NCPU };

    size_t len = sizeof(nb_cpus);

    ret = sysctl(mib, 2, &nb_cpus, &len, NULL, 0);

    if (ret == -1)

        nb_cpus = 0;

#elif HAVE_SYSCONF && defined(_SC_NPROC_ONLN)

    nb_cpus = sysconf(_SC_NPROC_ONLN);

#elif HAVE_SYSCONF && defined(_SC_NPROCESSORS_ONLN)

    nb_cpus = sysconf(_SC_NPROCESSORS_ONLN);

#endif

    av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);

    return FFMIN(nb_cpus, MAX_AUTO_THREADS);

}


static av_cold int ljpeg_encode_close(AVCodecContext *avctx)

{

    LJpegEncContext *s = avctx->priv_data;

    av_frame_free(&avctx->coded_frame);

    av_freep(&s->scratch);

    return 0;

}


bool timerlistgroup_run_timers(QEMUTimerListGroup *tlg)

{

    QEMUClockType type;

    bool progress = false;

    for (type = 0; type < QEMU_CLOCK_MAX; type++) {

        progress |= timerlist_run_timers(tlg->tl[type]);

    }

    return progress;

}


static void channel_load_c(struct fs_dma_ctrl *ctrl, int c)

{

	target_phys_addr_t addr = channel_reg(ctrl, c, RW_GROUP_DOWN);

	/* Load and decode. FIXME: handle endianness.  */

	cpu_physical_memory_read (addr,

				  (void *) &ctrl->channels[c].current_c,

				  sizeof ctrl->channels[c].current_c);

	D(dump_c(c, &ctrl->channels[c].current_c));

	/* I guess this should update the current pos.  */

	ctrl->channels[c].regs[RW_SAVED_DATA] =

		(uint32_t)(unsigned long)ctrl->channels[c].current_c.saved_data;

	ctrl->channels[c].regs[RW_SAVED_DATA_BUF] =

		(uint32_t)(unsigned long)ctrl->channels[c].current_c.saved_data_buf;

}


static void sigfd_handler(void *opaque)

{

    int fd = (intptr_t)opaque;

    struct qemu_signalfd_siginfo info;

    struct sigaction action;

    ssize_t len;

    while (1) {

        do {

            len = read(fd, &info, sizeof(info));

        } while (len == -1 && errno == EINTR);

        if (len == -1 && errno == EAGAIN) {

            break;

        }

        if (len != sizeof(info)) {

            printf("read from sigfd returned %zd: %m\n", len);

            return;

        }

        sigaction(info.ssi_signo, NULL, &action);

        if ((action.sa_flags & SA_SIGINFO) && action.sa_sigaction) {

            action.sa_sigaction(info.ssi_signo,

                                (siginfo_t *)&info, NULL);

        } else if (action.sa_handler) {

            action.sa_handler(info.ssi_signo);

        }

    }

}


build_srat(GArray *table_data, GArray *linker)

{

    AcpiSystemResourceAffinityTable *srat;

    AcpiSratProcessorAffinity *core;

    AcpiSratMemoryAffinity *numamem;

    int i;

    uint64_t curnode;

    int srat_start, numa_start, slots;

    uint64_t mem_len, mem_base, next_base;

    PCMachineState *pcms = PC_MACHINE(qdev_get_machine());

    ram_addr_t hotplugabble_address_space_size =

        object_property_get_int(OBJECT(pcms), PC_MACHINE_MEMHP_REGION_SIZE,

                                NULL);

    srat_start = table_data->len;

    srat = acpi_data_push(table_data, sizeof *srat);

    srat->reserved1 = cpu_to_le32(1);

    core = (void *)(srat + 1);

    for (i = 0; i < pcms->apic_id_limit; ++i) {

        core = acpi_data_push(table_data, sizeof *core);

        core->type = ACPI_SRAT_PROCESSOR;

        core->length = sizeof(*core);

        core->local_apic_id = i;

        curnode = pcms->node_cpu[i];

        core->proximity_lo = curnode;

        memset(core->proximity_hi, 0, 3);

        core->local_sapic_eid = 0;

        core->flags = cpu_to_le32(1);

    }

    /* the memory map is a bit tricky, it contains at least one hole

     * from 640k-1M and possibly another one from 3.5G-4G.

     */

    next_base = 0;

    numa_start = table_data->len;

    numamem = acpi_data_push(table_data, sizeof *numamem);

    acpi_build_srat_memory(numamem, 0, 640*1024, 0, MEM_AFFINITY_ENABLED);

    next_base = 1024 * 1024;

    for (i = 1; i < pcms->numa_nodes + 1; ++i) {

        mem_base = next_base;

        mem_len = pcms->node_mem[i - 1];

        if (i == 1) {

            mem_len -= 1024 * 1024;

        }

        next_base = mem_base + mem_len;

        /* Cut out the ACPI_PCI hole */

        if (mem_base <= pcms->below_4g_mem_size &&

            next_base > pcms->below_4g_mem_size) {

            mem_len -= next_base - pcms->below_4g_mem_size;

            if (mem_len > 0) {

                numamem = acpi_data_push(table_data, sizeof *numamem);

                acpi_build_srat_memory(numamem, mem_base, mem_len, i - 1,

                                       MEM_AFFINITY_ENABLED);

            }

            mem_base = 1ULL << 32;

            mem_len = next_base - pcms->below_4g_mem_size;

            next_base += (1ULL << 32) - pcms->below_4g_mem_size;

        }

        numamem = acpi_data_push(table_data, sizeof *numamem);

        acpi_build_srat_memory(numamem, mem_base, mem_len, i - 1,

                               MEM_AFFINITY_ENABLED);

    }

    slots = (table_data->len - numa_start) / sizeof *numamem;

    for (; slots < pcms->numa_nodes + 2; slots++) {

        numamem = acpi_data_push(table_data, sizeof *numamem);

        acpi_build_srat_memory(numamem, 0, 0, 0, MEM_AFFINITY_NOFLAGS);

    }

    /*

     * Entry is required for Windows to enable memory hotplug in OS.

     * Memory devices may override proximity set by this entry,

     * providing _PXM method if necessary.

     */

    if (hotplugabble_address_space_size) {

        numamem = acpi_data_push(table_data, sizeof *numamem);

        acpi_build_srat_memory(numamem, pcms->hotplug_memory.base,

                               hotplugabble_address_space_size, 0,

                               MEM_AFFINITY_HOTPLUGGABLE |

                               MEM_AFFINITY_ENABLED);

    }

    build_header(linker, table_data,

                 (void *)(table_data->data + srat_start),

                 "SRAT",

                 table_data->len - srat_start, 1, NULL);

}


static inline bool gluster_supports_zerofill(void)

{

    return 0;

}


static void trigger_page_fault(CPUS390XState *env, target_ulong vaddr,

                               uint32_t type, uint64_t asc, int rw)

{

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

    int ilen = ILEN_LATER;

    int bits = trans_bits(env, asc);

    /* Code accesses have an undefined ilc.  */

    if (rw == 2) {

        ilen = 2;

    }

    DPRINTF("%s: vaddr=%016" PRIx64 " bits=%d\n", __func__, vaddr, bits);

    stq_phys(cs->as,

             env->psa + offsetof(LowCore, trans_exc_code), vaddr | bits);

    trigger_pgm_exception(env, type, ilen);

}


build_dsdt(GArray *table_data, GArray *linker,

           AcpiCpuInfo *cpu, AcpiPmInfo *pm, AcpiMiscInfo *misc,

           PcPciInfo *pci, MachineState *machine)

{

    CrsRangeEntry *entry;

    Aml *dsdt, *sb_scope, *scope, *dev, *method, *field, *pkg, *crs;

    GPtrArray *mem_ranges = g_ptr_array_new_with_free_func(crs_range_free);

    GPtrArray *io_ranges = g_ptr_array_new_with_free_func(crs_range_free);

    PCMachineState *pcms = PC_MACHINE(machine);

    uint32_t nr_mem = machine->ram_slots;

    int root_bus_limit = 0xFF;

    PCIBus *bus = NULL;

    int i;

    dsdt = init_aml_allocator();

    /* Reserve space for header */

    acpi_data_push(dsdt->buf, sizeof(AcpiTableHeader));

    build_dbg_aml(dsdt);

    if (misc->is_piix4) {

        sb_scope = aml_scope("_SB");

        dev = aml_device("PCI0");

        aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A03")));

        aml_append(dev, aml_name_decl("_ADR", aml_int(0)));

        aml_append(dev, aml_name_decl("_UID", aml_int(1)));

        aml_append(sb_scope, dev);

        aml_append(dsdt, sb_scope);

        build_hpet_aml(dsdt);

        build_piix4_pm(dsdt);

        build_piix4_isa_bridge(dsdt);

        build_isa_devices_aml(dsdt);

        build_piix4_pci_hotplug(dsdt);

        build_piix4_pci0_int(dsdt);

    } else {

        sb_scope = aml_scope("_SB");

        aml_append(sb_scope,

            aml_operation_region("PCST", AML_SYSTEM_IO, aml_int(0xae00), 0x0c));

        aml_append(sb_scope,

            aml_operation_region("PCSB", AML_SYSTEM_IO, aml_int(0xae0c), 0x01));

        field = aml_field("PCSB", AML_ANY_ACC, AML_NOLOCK, AML_WRITE_AS_ZEROS);

        aml_append(field, aml_named_field("PCIB", 8));

        aml_append(sb_scope, field);

        aml_append(dsdt, sb_scope);

        sb_scope = aml_scope("_SB");

        dev = aml_device("PCI0");

        aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A08")));

        aml_append(dev, aml_name_decl("_CID", aml_eisaid("PNP0A03")));

        aml_append(dev, aml_name_decl("_ADR", aml_int(0)));

        aml_append(dev, aml_name_decl("_UID", aml_int(1)));

        aml_append(dev, aml_name_decl("SUPP", aml_int(0)));

        aml_append(dev, aml_name_decl("CTRL", aml_int(0)));

        aml_append(dev, build_q35_osc_method());

        aml_append(sb_scope, dev);

        aml_append(dsdt, sb_scope);

        build_hpet_aml(dsdt);

        build_q35_isa_bridge(dsdt);

        build_isa_devices_aml(dsdt);

        build_q35_pci0_int(dsdt);

    }

    build_cpu_hotplug_aml(dsdt);

    build_memory_hotplug_aml(dsdt, nr_mem, pm->mem_hp_io_base,

                             pm->mem_hp_io_len);

    scope =  aml_scope("_GPE");

    {

        aml_append(scope, aml_name_decl("_HID", aml_string("ACPI0006")));

        aml_append(scope, aml_method("_L00", 0, AML_NOTSERIALIZED));

        if (misc->is_piix4) {

            method = aml_method("_E01", 0, AML_NOTSERIALIZED);

            aml_append(method,

                aml_acquire(aml_name("\\_SB.PCI0.BLCK"), 0xFFFF));

            aml_append(method, aml_call0("\\_SB.PCI0.PCNT"));

            aml_append(method, aml_release(aml_name("\\_SB.PCI0.BLCK")));

            aml_append(scope, method);

        } else {

            aml_append(scope, aml_method("_L01", 0, AML_NOTSERIALIZED));

        }

        method = aml_method("_E02", 0, AML_NOTSERIALIZED);

        aml_append(method, aml_call0("\\_SB." CPU_SCAN_METHOD));

        aml_append(scope, method);

        method = aml_method("_E03", 0, AML_NOTSERIALIZED);

        aml_append(method, aml_call0(MEMORY_HOTPLUG_HANDLER_PATH));

        aml_append(scope, method);

        aml_append(scope, aml_method("_L04", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L05", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L06", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L07", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L08", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L09", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L0A", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L0B", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L0C", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L0D", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L0E", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L0F", 0, AML_NOTSERIALIZED));

    }

    aml_append(dsdt, scope);

    bus = PC_MACHINE(machine)->bus;

    if (bus) {

        QLIST_FOREACH(bus, &bus->child, sibling) {

            uint8_t bus_num = pci_bus_num(bus);

            uint8_t numa_node = pci_bus_numa_node(bus);

            /* look only for expander root buses */

            if (!pci_bus_is_root(bus)) {

                continue;

            }

            if (bus_num < root_bus_limit) {

                root_bus_limit = bus_num - 1;

            }

            scope = aml_scope("\\_SB");

            dev = aml_device("PC%.02X", bus_num);

            aml_append(dev, aml_name_decl("_UID", aml_int(bus_num)));

            aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A03")));

            aml_append(dev, aml_name_decl("_BBN", aml_int(bus_num)));

            if (numa_node != NUMA_NODE_UNASSIGNED) {

                aml_append(dev, aml_name_decl("_PXM", aml_int(numa_node)));

            }

            aml_append(dev, build_prt(false));

            crs = build_crs(PCI_HOST_BRIDGE(BUS(bus)->parent),

                            io_ranges, mem_ranges);

            aml_append(dev, aml_name_decl("_CRS", crs));

            aml_append(scope, dev);

            aml_append(dsdt, scope);

        }

    }

    scope = aml_scope("\\_SB.PCI0");

    /* build PCI0._CRS */

    crs = aml_resource_template();

    aml_append(crs,

        aml_word_bus_number(AML_MIN_FIXED, AML_MAX_FIXED, AML_POS_DECODE,

                            0x0000, 0x0, root_bus_limit,

                            0x0000, root_bus_limit + 1));

    aml_append(crs, aml_io(AML_DECODE16, 0x0CF8, 0x0CF8, 0x01, 0x08));

    aml_append(crs,

        aml_word_io(AML_MIN_FIXED, AML_MAX_FIXED,

                    AML_POS_DECODE, AML_ENTIRE_RANGE,

                    0x0000, 0x0000, 0x0CF7, 0x0000, 0x0CF8));

    crs_replace_with_free_ranges(io_ranges, 0x0D00, 0xFFFF);

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

        entry = g_ptr_array_index(io_ranges, i);

        aml_append(crs,

            aml_word_io(AML_MIN_FIXED, AML_MAX_FIXED,

                        AML_POS_DECODE, AML_ENTIRE_RANGE,

                        0x0000, entry->base, entry->limit,

                        0x0000, entry->limit - entry->base + 1));

    }

    aml_append(crs,

        aml_dword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,

                         AML_CACHEABLE, AML_READ_WRITE,

                         0, 0x000A0000, 0x000BFFFF, 0, 0x00020000));

    crs_replace_with_free_ranges(mem_ranges, pci->w32.begin, pci->w32.end - 1);

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

        entry = g_ptr_array_index(mem_ranges, i);

        aml_append(crs,

            aml_dword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,

                             AML_NON_CACHEABLE, AML_READ_WRITE,

                             0, entry->base, entry->limit,

                             0, entry->limit - entry->base + 1));

    }

    if (pci->w64.begin) {

        aml_append(crs,

            aml_qword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,

                             AML_CACHEABLE, AML_READ_WRITE,

                             0, pci->w64.begin, pci->w64.end - 1, 0,

                             pci->w64.end - pci->w64.begin));

    }

    aml_append(scope, aml_name_decl("_CRS", crs));

    /* reserve GPE0 block resources */

    dev = aml_device("GPE0");

    aml_append(dev, aml_name_decl("_HID", aml_string("PNP0A06")));

    aml_append(dev, aml_name_decl("_UID", aml_string("GPE0 resources")));

    /* device present, functioning, decoding, not shown in UI */

    aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));

    crs = aml_resource_template();

    aml_append(crs,

        aml_io(AML_DECODE16, pm->gpe0_blk, pm->gpe0_blk, 1, pm->gpe0_blk_len)

    );

    aml_append(dev, aml_name_decl("_CRS", crs));

    aml_append(scope, dev);

    g_ptr_array_free(io_ranges, true);

    g_ptr_array_free(mem_ranges, true);

    /* reserve PCIHP resources */

    if (pm->pcihp_io_len) {

        dev = aml_device("PHPR");

        aml_append(dev, aml_name_decl("_HID", aml_string("PNP0A06")));

        aml_append(dev,

            aml_name_decl("_UID", aml_string("PCI Hotplug resources")));

        /* device present, functioning, decoding, not shown in UI */

        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));

        crs = aml_resource_template();

        aml_append(crs,

            aml_io(AML_DECODE16, pm->pcihp_io_base, pm->pcihp_io_base, 1,

                   pm->pcihp_io_len)

        );

        aml_append(dev, aml_name_decl("_CRS", crs));

        aml_append(scope, dev);

    }

    aml_append(dsdt, scope);

    /*  create S3_ / S4_ / S5_ packages if necessary */

    scope = aml_scope("\\");

    if (!pm->s3_disabled) {

        pkg = aml_package(4);

        aml_append(pkg, aml_int(1)); /* PM1a_CNT.SLP_TYP */

        aml_append(pkg, aml_int(1)); /* PM1b_CNT.SLP_TYP, FIXME: not impl. */

        aml_append(pkg, aml_int(0)); /* reserved */

        aml_append(pkg, aml_int(0)); /* reserved */

        aml_append(scope, aml_name_decl("_S3", pkg));

    }

    if (!pm->s4_disabled) {

        pkg = aml_package(4);

        aml_append(pkg, aml_int(pm->s4_val)); /* PM1a_CNT.SLP_TYP */

        /* PM1b_CNT.SLP_TYP, FIXME: not impl. */

        aml_append(pkg, aml_int(pm->s4_val));

        aml_append(pkg, aml_int(0)); /* reserved */

        aml_append(pkg, aml_int(0)); /* reserved */

        aml_append(scope, aml_name_decl("_S4", pkg));

    }

    pkg = aml_package(4);

    aml_append(pkg, aml_int(0)); /* PM1a_CNT.SLP_TYP */

    aml_append(pkg, aml_int(0)); /* PM1b_CNT.SLP_TYP not impl. */

    aml_append(pkg, aml_int(0)); /* reserved */

    aml_append(pkg, aml_int(0)); /* reserved */

    aml_append(scope, aml_name_decl("_S5", pkg));

    aml_append(dsdt, scope);

    /* create fw_cfg node, unconditionally */

    {

        /* when using port i/o, the 8-bit data register *always* overlaps

         * with half of the 16-bit control register. Hence, the total size

         * of the i/o region used is FW_CFG_CTL_SIZE; when using DMA, the

         * DMA control register is located at FW_CFG_DMA_IO_BASE + 4 */

        uint8_t io_size = object_property_get_bool(OBJECT(pcms->fw_cfg),

                                                   "dma_enabled", NULL) ?

                          ROUND_UP(FW_CFG_CTL_SIZE, 4) + sizeof(dma_addr_t) :

                          FW_CFG_CTL_SIZE;

        scope = aml_scope("\\_SB.PCI0");

        dev = aml_device("FWCF");

        aml_append(dev, aml_name_decl("_HID", aml_string("QEMU0002")));

        /* device present, functioning, decoding, not shown in UI */

        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));

        crs = aml_resource_template();

        aml_append(crs,

            aml_io(AML_DECODE16, FW_CFG_IO_BASE, FW_CFG_IO_BASE, 0x01, io_size)

        );

        aml_append(dev, aml_name_decl("_CRS", crs));

        aml_append(scope, dev);

        aml_append(dsdt, scope);

    }

    if (misc->applesmc_io_base) {

        scope = aml_scope("\\_SB.PCI0.ISA");

        dev = aml_device("SMC");

        aml_append(dev, aml_name_decl("_HID", aml_eisaid("APP0001")));

        /* device present, functioning, decoding, not shown in UI */

        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));

        crs = aml_resource_template();

        aml_append(crs,

            aml_io(AML_DECODE16, misc->applesmc_io_base, misc->applesmc_io_base,

                   0x01, APPLESMC_MAX_DATA_LENGTH)

        );

        aml_append(crs, aml_irq_no_flags(6));

        aml_append(dev, aml_name_decl("_CRS", crs));

        aml_append(scope, dev);

        aml_append(dsdt, scope);

    }

    if (misc->pvpanic_port) {

        scope = aml_scope("\\_SB.PCI0.ISA");

        dev = aml_device("PEVT");

        aml_append(dev, aml_name_decl("_HID", aml_string("QEMU0001")));

        crs = aml_resource_template();

        aml_append(crs,

            aml_io(AML_DECODE16, misc->pvpanic_port, misc->pvpanic_port, 1, 1)

        );

        aml_append(dev, aml_name_decl("_CRS", crs));

        aml_append(dev, aml_operation_region("PEOR", AML_SYSTEM_IO,

                                              aml_int(misc->pvpanic_port), 1));

        field = aml_field("PEOR", AML_BYTE_ACC, AML_NOLOCK, AML_PRESERVE);

        aml_append(field, aml_named_field("PEPT", 8));

        aml_append(dev, field);

        /* device present, functioning, decoding, shown in UI */

        aml_append(dev, aml_name_decl("_STA", aml_int(0xF)));

        method = aml_method("RDPT", 0, AML_NOTSERIALIZED);

        aml_append(method, aml_store(aml_name("PEPT"), aml_local(0)));

        aml_append(method, aml_return(aml_local(0)));

        aml_append(dev, method);

        method = aml_method("WRPT", 1, AML_NOTSERIALIZED);

        aml_append(method, aml_store(aml_arg(0), aml_name("PEPT")));

        aml_append(dev, method);

        aml_append(scope, dev);

        aml_append(dsdt, scope);

    }

    sb_scope = aml_scope("\\_SB");

    {

        build_processor_devices(sb_scope, pcms->apic_id_limit, cpu, pm);

        build_memory_devices(sb_scope, nr_mem, pm->mem_hp_io_base,

                             pm->mem_hp_io_len);

        {

            Object *pci_host;

            PCIBus *bus = NULL;

            pci_host = acpi_get_i386_pci_host();

            if (pci_host) {

                bus = PCI_HOST_BRIDGE(pci_host)->bus;

            }

            if (bus) {

                Aml *scope = aml_scope("PCI0");

                /* Scan all PCI buses. Generate tables to support hotplug. */

                build_append_pci_bus_devices(scope, bus, pm->pcihp_bridge_en);

                if (misc->tpm_version != TPM_VERSION_UNSPEC) {

                    dev = aml_device("ISA.TPM");

                    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0C31")));

                    aml_append(dev, aml_name_decl("_STA", aml_int(0xF)));

                    crs = aml_resource_template();

                    aml_append(crs, aml_memory32_fixed(TPM_TIS_ADDR_BASE,

                               TPM_TIS_ADDR_SIZE, AML_READ_WRITE));

                    aml_append(crs, aml_irq_no_flags(TPM_TIS_IRQ));

                    aml_append(dev, aml_name_decl("_CRS", crs));

                    aml_append(scope, dev);

                }

                aml_append(sb_scope, scope);

            }

        }

        aml_append(dsdt, sb_scope);

    }

    /* copy AML table into ACPI tables blob and patch header there */

    g_array_append_vals(table_data, dsdt->buf->data, dsdt->buf->len);

    build_header(linker, table_data,

        (void *)(table_data->data + table_data->len - dsdt->buf->len),

        "DSDT", dsdt->buf->len, 1, NULL, NULL);

    free_aml_allocator();

}


static void setup_frame(int sig, struct target_sigaction * ka,

                        target_sigset_t *set, CPUMIPSState *regs)

{

    struct sigframe *frame;

    abi_ulong frame_addr;

    int i;

    frame_addr = get_sigframe(ka, regs, sizeof(*frame));

    if (!lock_user_struct(VERIFY_WRITE, frame, frame_addr, 0))

	goto give_sigsegv;

    install_sigtramp(frame->sf_code, TARGET_NR_sigreturn);

    if(setup_sigcontext(regs, &frame->sf_sc))

	goto give_sigsegv;

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

	if(__put_user(set->sig[i], &frame->sf_mask.sig[i]))

	    goto give_sigsegv;

    }

    /*

    * Arguments to signal handler:

    *

    *   a0 = signal number

    *   a1 = 0 (should be cause)

    *   a2 = pointer to struct sigcontext

    *

    * $25 and PC point to the signal handler, $29 points to the

    * struct sigframe.

    */

    regs->active_tc.gpr[ 4] = sig;

    regs->active_tc.gpr[ 5] = 0;

    regs->active_tc.gpr[ 6] = frame_addr + offsetof(struct sigframe, sf_sc);

    regs->active_tc.gpr[29] = frame_addr;

    regs->active_tc.gpr[31] = frame_addr + offsetof(struct sigframe, sf_code);

    /* The original kernel code sets CP0_EPC to the handler

    * since it returns to userland using eret

    * we cannot do this here, and we must set PC directly */

    regs->active_tc.PC = regs->active_tc.gpr[25] = ka->_sa_handler;

    mips_set_hflags_isa_mode_from_pc(regs);

    unlock_user_struct(frame, frame_addr, 1);

    return;

give_sigsegv:

    unlock_user_struct(frame, frame_addr, 1);

    force_sig(TARGET_SIGSEGV/*, current*/);

}


void helper_fcmpo(CPUPPCState *env, uint64_t arg1, uint64_t arg2,

                  uint32_t crfD)

{

    CPU_DoubleU farg1, farg2;

    uint32_t ret = 0;

    farg1.ll = arg1;

    farg2.ll = arg2;

    if (unlikely(float64_is_any_nan(farg1.d) ||

                 float64_is_any_nan(farg2.d))) {

        ret = 0x01UL;

    } else if (float64_lt(farg1.d, farg2.d, &env->fp_status)) {

        ret = 0x08UL;

    } else if (!float64_le(farg1.d, farg2.d, &env->fp_status)) {

        ret = 0x04UL;

    } else {

        ret = 0x02UL;

    }

    env->fpscr &= ~(0x0F << FPSCR_FPRF);

    env->fpscr |= ret << FPSCR_FPRF;

    env->crf[crfD] = ret;

    if (unlikely(ret == 0x01UL)) {

        if (float64_is_signaling_nan(farg1.d) ||

            float64_is_signaling_nan(farg2.d)) {

            /* sNaN comparison */

            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN |

                                  POWERPC_EXCP_FP_VXVC);

        } else {

            /* qNaN comparison */

            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXVC);

        }

    }

}


static void taihu_cpld_writew (void *opaque,

                               hwaddr addr, uint32_t value)

{

    taihu_cpld_writeb(opaque, addr, (value >> 8) & 0xFF);

    taihu_cpld_writeb(opaque, addr + 1, value & 0xFF);

}


void ff_imdct_calc_sse(MDCTContext *s, FFTSample *output,

                       const FFTSample *input, FFTSample *tmp)

{

    long k, n8, n4, n2, n;

    const uint16_t *revtab = s->fft.revtab;

    const FFTSample *tcos = s->tcos;

    const FFTSample *tsin = s->tsin;

    const FFTSample *in1, *in2;

    FFTComplex *z = (FFTComplex *)tmp;

    n = 1 << s->nbits;

    n2 = n >> 1;

    n4 = n >> 2;

    n8 = n >> 3;

    asm volatile ("movaps %0, %%xmm7\n\t"::"m"(*p1m1p1m1));

    /* pre rotation */

    in1 = input;

    in2 = input + n2 - 4;

    /* Complex multiplication

       Two complex products per iteration, we could have 4 with 8 xmm

       registers, 8 with 16 xmm registers.

       Maybe we should unroll more.

    */

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

        asm volatile (

            "movaps          %0, %%xmm0 \n\t"   // xmm0 = r0 X  r1 X : in2

            "movaps          %1, %%xmm3 \n\t"   // xmm3 = X  i1 X  i0: in1

            "movlps          %2, %%xmm1 \n\t"   // xmm1 = X  X  R1 R0: tcos

            "movlps          %3, %%xmm2 \n\t"   // xmm2 = X  X  I1 I0: tsin

            "shufps $95, %%xmm0, %%xmm0 \n\t"   // xmm0 = r1 r1 r0 r0

            "shufps $160,%%xmm3, %%xmm3 \n\t"   // xmm3 = i1 i1 i0 i0

            "unpcklps    %%xmm2, %%xmm1 \n\t"   // xmm1 = I1 R1 I0 R0

            "movaps      %%xmm1, %%xmm2 \n\t"   // xmm2 = I1 R1 I0 R0

            "xorps       %%xmm7, %%xmm2 \n\t"   // xmm2 = -I1 R1 -I0 R0

            "mulps       %%xmm1, %%xmm0 \n\t"   // xmm0 = rI rR rI rR

            "shufps $177,%%xmm2, %%xmm2 \n\t"   // xmm2 = R1 -I1 R0 -I0

            "mulps       %%xmm2, %%xmm3 \n\t"   // xmm3 = Ri -Ii Ri -Ii

            "addps       %%xmm3, %%xmm0 \n\t"   // xmm0 = result

            ::"m"(in2[-2*k]), "m"(in1[2*k]),

              "m"(tcos[k]), "m"(tsin[k])

        );

        /* Should be in the same block, hack for gcc2.95 & gcc3 */

        asm (

            "movlps      %%xmm0, %0     \n\t"

            "movhps      %%xmm0, %1     \n\t"

            :"=m"(z[revtab[k]]), "=m"(z[revtab[k + 1]])

        );

    }

    ff_fft_calc_sse(&s->fft, z);

    /* Not currently needed, added for safety */

    asm volatile ("movaps %0, %%xmm7\n\t"::"m"(*p1m1p1m1));

    /* post rotation + reordering */

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

        asm (

            "movaps          %0, %%xmm0 \n\t"   // xmm0 = i1 r1 i0 r0: z

            "movlps          %1, %%xmm1 \n\t"   // xmm1 = X  X  R1 R0: tcos

            "movaps      %%xmm0, %%xmm3 \n\t"   // xmm3 = i1 r1 i0 r0

            "movlps          %2, %%xmm2 \n\t"   // xmm2 = X  X  I1 I0: tsin

            "shufps $160,%%xmm0, %%xmm0 \n\t"   // xmm0 = r1 r1 r0 r0

            "shufps $245,%%xmm3, %%xmm3 \n\t"   // xmm3 = i1 i1 i0 i0

            "unpcklps    %%xmm2, %%xmm1 \n\t"   // xmm1 = I1 R1 I0 R0

            "movaps      %%xmm1, %%xmm2 \n\t"   // xmm2 = I1 R1 I0 R0

            "xorps       %%xmm7, %%xmm2 \n\t"   // xmm2 = -I1 R1 -I0 R0

            "mulps       %%xmm1, %%xmm0 \n\t"   // xmm0 = rI rR rI rR

            "shufps $177,%%xmm2, %%xmm2 \n\t"   // xmm2 = R1 -I1 R0 -I0

            "mulps       %%xmm2, %%xmm3 \n\t"   // xmm3 = Ri -Ii Ri -Ii

            "addps       %%xmm3, %%xmm0 \n\t"   // xmm0 = result

            "movaps      %%xmm0, %0     \n\t"

            :"+m"(z[k])

            :"m"(tcos[k]), "m"(tsin[k])

        );

    }

    /*

       Mnemonics:

       0 = z[k].re

       1 = z[k].im

       2 = z[k + 1].re

       3 = z[k + 1].im

       4 = z[-k - 2].re

       5 = z[-k - 2].im

       6 = z[-k - 1].re

       7 = z[-k - 1].im

    */

    k = 16-n;

    asm volatile("movaps %0, %%xmm7 \n\t"::"m"(*m1m1m1m1));

    asm volatile(

        "1: \n\t"

        "movaps  -16(%4,%0), %%xmm1 \n\t"   // xmm1 = 4 5 6 7 = z[-2-k]

        "neg %0 \n\t"

        "movaps     (%4,%0), %%xmm0 \n\t"   // xmm0 = 0 1 2 3 = z[k]

        "xorps       %%xmm7, %%xmm0 \n\t"   // xmm0 = -0 -1 -2 -3

        "movaps      %%xmm0, %%xmm2 \n\t"   // xmm2 = -0 -1 -2 -3

        "shufps $141,%%xmm1, %%xmm0 \n\t"   // xmm0 = -1 -3 4 6

        "shufps $216,%%xmm1, %%xmm2 \n\t"   // xmm2 = -0 -2 5 7

        "shufps $156,%%xmm0, %%xmm0 \n\t"   // xmm0 = -1 6 -3 4 !

        "shufps $156,%%xmm2, %%xmm2 \n\t"   // xmm2 = -0 7 -2 5 !

        "movaps      %%xmm0, (%1,%0) \n\t"  // output[2*k]

        "movaps      %%xmm2, (%2,%0) \n\t"  // output[n2+2*k]

        "neg %0 \n\t"

        "shufps $27, %%xmm0, %%xmm0 \n\t"   // xmm0 = 4 -3 6 -1

        "xorps       %%xmm7, %%xmm0 \n\t"   // xmm0 = -4 3 -6 1 !

        "shufps $27, %%xmm2, %%xmm2 \n\t"   // xmm2 = 5 -2 7 -0 !

        "movaps      %%xmm0, -16(%2,%0) \n\t" // output[n2-4-2*k]

        "movaps      %%xmm2, -16(%3,%0) \n\t" // output[n-4-2*k]

        "add $16, %0 \n\t"

        "jle 1b \n\t"

        :"+r"(k)

        :"r"(output), "r"(output+n2), "r"(output+n), "r"(z+n8)

        :"memory"

    );

}


QemuConsole *graphic_console_init(graphic_hw_update_ptr update,

                                  graphic_hw_invalidate_ptr invalidate,

                                  graphic_hw_screen_dump_ptr screen_dump,

                                  graphic_hw_text_update_ptr text_update,

                                  void *opaque)

{

    int width = 640;

    int height = 480;

    QemuConsole *s;

    DisplayState *ds;

    ds = get_alloc_displaystate();

    trace_console_gfx_new();

    s = new_console(ds, GRAPHIC_CONSOLE);

    s->hw_update = update;

    s->hw_invalidate = invalidate;

    s->hw_screen_dump = screen_dump;

    s->hw_text_update = text_update;

    s->hw = opaque;

    s->surface = qemu_create_displaysurface(width, height);

    return s;

}


virtio_crypto_check_cryptodev_is_used(const Object *obj, const char *name,

                                      Object *val, Error **errp)

{

    if (cryptodev_backend_is_used(CRYPTODEV_BACKEND(val))) {

        char *path = object_get_canonical_path_component(val);

        error_setg(errp,

            "can't use already used cryptodev backend: %s", path);

        g_free(path);

    } else {

        qdev_prop_allow_set_link_before_realize(obj, name, val, errp);

    }

}


static void device_unparent(Object *obj)

{

    DeviceState *dev = DEVICE(obj);

    if (dev->parent_bus != NULL) {

        bus_remove_child(dev->parent_bus, dev);

    }

}


static always_inline int isnormal (float64 d)

{

    CPU_DoubleU u;

    u.d = d;

    uint32_t exp = (u.ll >> 52) & 0x7FF;

    return ((0 < exp) && (exp < 0x7FF));

}


static void virtio_set_status(struct subchannel_id schid,

                              unsigned long dev_addr)

{

    unsigned char status = dev_addr;

    run_ccw(schid, CCW_CMD_WRITE_STATUS, &status, sizeof(status));

}


bool has_help_option(const char *param)

{

    size_t buflen = strlen(param) + 1;

    char *buf = g_malloc(buflen);

    const char *p = param;

    bool result = false;

    while (*p) {

        p = get_opt_value(buf, buflen, p);

        if (*p) {

            p++;

        }

        if (is_help_option(buf)) {

            result = true;

            goto out;

        }

    }

out:

    free(buf);

    return result;

}


setup_sigcontext(CPUMIPSState *regs, struct target_sigcontext *sc)

{

    int err = 0;

    int i;

    __put_user(exception_resume_pc(regs), &sc->sc_pc);

    regs->hflags &= ~MIPS_HFLAG_BMASK;

    __put_user(0, &sc->sc_regs[0]);

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

        __put_user(regs->active_tc.gpr[i], &sc->sc_regs[i]);

    }

    __put_user(regs->active_tc.HI[0], &sc->sc_mdhi);

    __put_user(regs->active_tc.LO[0], &sc->sc_mdlo);

    /* Rather than checking for dsp existence, always copy.  The storage

       would just be garbage otherwise.  */

    __put_user(regs->active_tc.HI[1], &sc->sc_hi1);

    __put_user(regs->active_tc.HI[2], &sc->sc_hi2);

    __put_user(regs->active_tc.HI[3], &sc->sc_hi3);

    __put_user(regs->active_tc.LO[1], &sc->sc_lo1);

    __put_user(regs->active_tc.LO[2], &sc->sc_lo2);

    __put_user(regs->active_tc.LO[3], &sc->sc_lo3);

    {

        uint32_t dsp = cpu_rddsp(0x3ff, regs);

        __put_user(dsp, &sc->sc_dsp);

    }

    __put_user(1, &sc->sc_used_math);

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

        __put_user(regs->active_fpu.fpr[i].d, &sc->sc_fpregs[i]);

    }

    return err;

}


restore_sigcontext(CPUX86State *env, struct target_sigcontext *sc, int *peax)

{

    unsigned int err = 0;

    abi_ulong fpstate_addr;

    unsigned int tmpflags;

    cpu_x86_load_seg(env, R_GS, tswap16(sc->gs));

    cpu_x86_load_seg(env, R_FS, tswap16(sc->fs));

    cpu_x86_load_seg(env, R_ES, tswap16(sc->es));

    cpu_x86_load_seg(env, R_DS, tswap16(sc->ds));

    env->regs[R_EDI] = tswapl(sc->edi);

    env->regs[R_ESI] = tswapl(sc->esi);

    env->regs[R_EBP] = tswapl(sc->ebp);

    env->regs[R_ESP] = tswapl(sc->esp);

    env->regs[R_EBX] = tswapl(sc->ebx);

    env->regs[R_EDX] = tswapl(sc->edx);

    env->regs[R_ECX] = tswapl(sc->ecx);

    env->eip = tswapl(sc->eip);

    cpu_x86_load_seg(env, R_CS, lduw_p(&sc->cs) | 3);

    cpu_x86_load_seg(env, R_SS, lduw_p(&sc->ss) | 3);

    tmpflags = tswapl(sc->eflags);

    env->eflags = (env->eflags & ~0x40DD5) | (tmpflags & 0x40DD5);

    //		regs->orig_eax = -1;		/* disable syscall checks */

    fpstate_addr = tswapl(sc->fpstate);

    if (fpstate_addr != 0) {

        if (!access_ok(VERIFY_READ, fpstate_addr,

                       sizeof(struct target_fpstate)))

            goto badframe;

        cpu_x86_frstor(env, fpstate_addr, 1);

    }

    *peax = tswapl(sc->eax);

    return err;

badframe:

    return 1;

}


static void gen_arm_parallel_addsub(int op1, int op2, TCGv a, TCGv b)

{

    TCGv tmp;

    switch (op1) {

#define gen_pas_helper(name) glue(gen_helper_,name)(a, a, b, tmp)

    case 1:

        tmp = tcg_temp_new(TCG_TYPE_PTR);

        tcg_gen_addi_ptr(tmp, cpu_env, offsetof(CPUState, GE));

        PAS_OP(s)

        break;

    case 5:

        tmp = tcg_temp_new(TCG_TYPE_PTR);

        tcg_gen_addi_ptr(tmp, cpu_env, offsetof(CPUState, GE));

        PAS_OP(u)

        break;

#undef gen_pas_helper

#define gen_pas_helper(name) glue(gen_helper_,name)(a, a, b)

    case 2:

        PAS_OP(q);

        break;

    case 3:

        PAS_OP(sh);

        break;

    case 6:

        PAS_OP(uq);

        break;

    case 7:

        PAS_OP(uh);

        break;

#undef gen_pas_helper

    }

}


static void bdrv_dirty_bitmap_truncate(BlockDriverState *bs)

{

    BdrvDirtyBitmap *bitmap;

    uint64_t size = bdrv_nb_sectors(bs);

    QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {

        if (bdrv_dirty_bitmap_frozen(bitmap)) {

            continue;

        }

        hbitmap_truncate(bitmap->bitmap, size);

        bitmap->size = size;

    }

}


static int asf_write_header1(AVFormatContext *s, int64_t file_size, int64_t data_chunk_size)

{

    ASFContext *asf = s->priv_data;

    AVIOContext *pb = s->pb;

    AVDictionaryEntry *tags[5];

    int header_size, n, extra_size, extra_size2, wav_extra_size, file_time;

    int has_title;

    int metadata_count;

    AVCodecContext *enc;

    int64_t header_offset, cur_pos, hpos;

    int bit_rate;

    int64_t duration;

    ff_metadata_conv(&s->metadata, ff_asf_metadata_conv, NULL);

    tags[0] = av_dict_get(s->metadata, "title"    , NULL, 0);

    tags[1] = av_dict_get(s->metadata, "author"   , NULL, 0);

    tags[2] = av_dict_get(s->metadata, "copyright", NULL, 0);

    tags[3] = av_dict_get(s->metadata, "comment"  , NULL, 0);

    tags[4] = av_dict_get(s->metadata, "rating"   , NULL, 0);

    duration = asf->duration + PREROLL_TIME * 10000;

    has_title = tags[0] || tags[1] || tags[2] || tags[3] || tags[4];

    metadata_count = s->metadata ? s->metadata->count : 0;

    bit_rate = 0;

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

        enc = s->streams[n]->codec;

        av_set_pts_info(s->streams[n], 32, 1, 1000); /* 32 bit pts in ms */

        bit_rate += enc->bit_rate;

    }

    if (asf->is_streamed) {

        put_chunk(s, 0x4824, 0, 0xc00); /* start of stream (length will be patched later) */

    }

    put_guid(pb, &ff_asf_header);

    avio_wl64(pb, -1); /* header length, will be patched after */

    avio_wl32(pb, 3 + has_title + !!metadata_count + s->nb_streams); /* number of chunks in header */

    avio_w8(pb, 1); /* ??? */

    avio_w8(pb, 2); /* ??? */

    /* file header */

    header_offset = avio_tell(pb);

    hpos = put_header(pb, &ff_asf_file_header);

    put_guid(pb, &ff_asf_my_guid);

    avio_wl64(pb, file_size);

    file_time = 0;

    avio_wl64(pb, unix_to_file_time(file_time));

    avio_wl64(pb, asf->nb_packets); /* number of packets */

    avio_wl64(pb, duration); /* end time stamp (in 100ns units) */

    avio_wl64(pb, asf->duration); /* duration (in 100ns units) */

    avio_wl64(pb, PREROLL_TIME); /* start time stamp */

    avio_wl32(pb, (asf->is_streamed || !pb->seekable ) ? 3 : 2); /* ??? */

    avio_wl32(pb, s->packet_size); /* packet size */

    avio_wl32(pb, s->packet_size); /* packet size */

    avio_wl32(pb, bit_rate); /* Nominal data rate in bps */

    end_header(pb, hpos);

    /* unknown headers */

    hpos = put_header(pb, &ff_asf_head1_guid);

    put_guid(pb, &ff_asf_head2_guid);

    avio_wl32(pb, 6);

    avio_wl16(pb, 0);

    end_header(pb, hpos);

    /* title and other infos */

    if (has_title) {

        int len;

        uint8_t *buf;

        AVIOContext *dyn_buf;

        if (avio_open_dyn_buf(&dyn_buf) < 0)

            return AVERROR(ENOMEM);

        hpos = put_header(pb, &ff_asf_comment_header);

        for (n = 0; n < FF_ARRAY_ELEMS(tags); n++) {

            len = tags[n] ? avio_put_str16le(dyn_buf, tags[n]->value) : 0;

            avio_wl16(pb, len);

        }

        len = avio_close_dyn_buf(dyn_buf, &buf);

        avio_write(pb, buf, len);

        av_freep(&buf);

        end_header(pb, hpos);

    }

    if (metadata_count) {

        AVDictionaryEntry *tag = NULL;

        hpos = put_header(pb, &ff_asf_extended_content_header);

        avio_wl16(pb, metadata_count);

        while ((tag = av_dict_get(s->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {

            put_str16(pb, tag->key);

            avio_wl16(pb, 0);

            put_str16(pb, tag->value);

        }

        end_header(pb, hpos);

    }

    /* stream headers */

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

        int64_t es_pos;

        //        ASFStream *stream = &asf->streams[n];

        enc = s->streams[n]->codec;

        asf->streams[n].num = n + 1;

        asf->streams[n].seq = 0;

        switch(enc->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            wav_extra_size = 0;

            extra_size = 18 + wav_extra_size;

            extra_size2 = 8;

            break;

        default:

        case AVMEDIA_TYPE_VIDEO:

            wav_extra_size = enc->extradata_size;

            extra_size = 0x33 + wav_extra_size;

            extra_size2 = 0;

            break;

        }

        hpos = put_header(pb, &ff_asf_stream_header);

        if (enc->codec_type == AVMEDIA_TYPE_AUDIO) {

            put_guid(pb, &ff_asf_audio_stream);

            put_guid(pb, &ff_asf_audio_conceal_spread);

        } else {

            put_guid(pb, &ff_asf_video_stream);

            put_guid(pb, &ff_asf_video_conceal_none);

        }

        avio_wl64(pb, 0); /* ??? */

        es_pos = avio_tell(pb);

        avio_wl32(pb, extra_size); /* wav header len */

        avio_wl32(pb, extra_size2); /* additional data len */

        avio_wl16(pb, n + 1); /* stream number */

        avio_wl32(pb, 0); /* ??? */

        if (enc->codec_type == AVMEDIA_TYPE_AUDIO) {

            /* WAVEFORMATEX header */

            int wavsize = ff_put_wav_header(pb, enc);

            if ((enc->codec_id != CODEC_ID_MP3) && (enc->codec_id != CODEC_ID_MP2) && (enc->codec_id != CODEC_ID_ADPCM_IMA_WAV) && (enc->extradata_size==0)) {

                wavsize += 2;

                avio_wl16(pb, 0);

            }

            if (wavsize < 0)

                return -1;

            if (wavsize != extra_size) {

                cur_pos = avio_tell(pb);

                avio_seek(pb, es_pos, SEEK_SET);

                avio_wl32(pb, wavsize); /* wav header len */

                avio_seek(pb, cur_pos, SEEK_SET);

            }

            /* ERROR Correction */

            avio_w8(pb, 0x01);

            if(enc->codec_id == CODEC_ID_ADPCM_G726 || !enc->block_align){

                avio_wl16(pb, 0x0190);

                avio_wl16(pb, 0x0190);

            }else{

                avio_wl16(pb, enc->block_align);

                avio_wl16(pb, enc->block_align);

            }

            avio_wl16(pb, 0x01);

            avio_w8(pb, 0x00);

        } else {

            avio_wl32(pb, enc->width);

            avio_wl32(pb, enc->height);

            avio_w8(pb, 2); /* ??? */

            avio_wl16(pb, 40 + enc->extradata_size); /* size */

            /* BITMAPINFOHEADER header */

            ff_put_bmp_header(pb, enc, ff_codec_bmp_tags, 1);

        }

        end_header(pb, hpos);

    }

    /* media comments */

    hpos = put_header(pb, &ff_asf_codec_comment_header);

    put_guid(pb, &ff_asf_codec_comment1_header);

    avio_wl32(pb, s->nb_streams);

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

        AVCodec *p;

        const char *desc;

        int len;

        uint8_t *buf;

        AVIOContext *dyn_buf;

        enc = s->streams[n]->codec;

        p = avcodec_find_encoder(enc->codec_id);

        if(enc->codec_type == AVMEDIA_TYPE_AUDIO)

            avio_wl16(pb, 2);

        else if(enc->codec_type == AVMEDIA_TYPE_VIDEO)

            avio_wl16(pb, 1);

        else

            avio_wl16(pb, -1);

        if(enc->codec_id == CODEC_ID_WMAV2)

            desc = "Windows Media Audio V8";

        else

            desc = p ? p->name : enc->codec_name;

        if ( avio_open_dyn_buf(&dyn_buf) < 0)

            return AVERROR(ENOMEM);

        avio_put_str16le(dyn_buf, desc);

        len = avio_close_dyn_buf(dyn_buf, &buf);

        avio_wl16(pb, len / 2); // "number of characters" = length in bytes / 2

        avio_write(pb, buf, len);

        av_freep(&buf);

        avio_wl16(pb, 0); /* no parameters */

        /* id */

        if (enc->codec_type == AVMEDIA_TYPE_AUDIO) {

            avio_wl16(pb, 2);

            avio_wl16(pb, enc->codec_tag);

        } else {

            avio_wl16(pb, 4);

            avio_wl32(pb, enc->codec_tag);

        }

        if(!enc->codec_tag)

            return -1;

    }

    end_header(pb, hpos);

    /* patch the header size fields */

    cur_pos = avio_tell(pb);

    header_size = cur_pos - header_offset;

    if (asf->is_streamed) {

        header_size += 8 + 30 + 50;

        avio_seek(pb, header_offset - 10 - 30, SEEK_SET);

        avio_wl16(pb, header_size);

        avio_seek(pb, header_offset - 2 - 30, SEEK_SET);

        avio_wl16(pb, header_size);

        header_size -= 8 + 30 + 50;

    }

    header_size += 24 + 6;

    avio_seek(pb, header_offset - 14, SEEK_SET);

    avio_wl64(pb, header_size);

    avio_seek(pb, cur_pos, SEEK_SET);

    /* movie chunk, followed by packets of packet_size */

    asf->data_offset = cur_pos;

    put_guid(pb, &ff_asf_data_header);

    avio_wl64(pb, data_chunk_size);

    put_guid(pb, &ff_asf_my_guid);

    avio_wl64(pb, asf->nb_packets); /* nb packets */

    avio_w8(pb, 1); /* ??? */

    avio_w8(pb, 1); /* ??? */

    return 0;

}


static void test_primitives(gconstpointer opaque)

{

    TestArgs *args = (TestArgs *) opaque;

    const SerializeOps *ops = args->ops;

    PrimitiveType *pt = args->test_data;

    PrimitiveType *pt_copy = g_malloc0(sizeof(*pt_copy));

    Error *err = NULL;

    void *serialize_data;

    pt_copy->type = pt->type;

    ops->serialize(pt, &serialize_data, visit_primitive_type, &err);

    ops->deserialize((void **)&pt_copy, serialize_data, visit_primitive_type, &err);

    g_assert(err == NULL);

    g_assert(pt_copy != NULL);

    if (pt->type == PTYPE_STRING) {

        g_assert_cmpstr(pt->value.string, ==, pt_copy->value.string);

        g_free((char *)pt_copy->value.string);

    } else if (pt->type == PTYPE_NUMBER) {

        GString *double_expected = g_string_new("");

        GString *double_actual = g_string_new("");

        /* we serialize with %f for our reference visitors, so rather than fuzzy

         * floating math to test "equality", just compare the formatted values

         */

        g_string_printf(double_expected, "%.6f", pt->value.number);

        g_string_printf(double_actual, "%.6f", pt_copy->value.number);

        g_assert_cmpstr(double_actual->str, ==, double_expected->str);

        g_string_free(double_expected, true);

        g_string_free(double_actual, true);

    } else if (pt->type == PTYPE_BOOLEAN) {

        g_assert_cmpint(!!pt->value.max, ==, !!pt->value.max);

    } else {

        g_assert_cmpint(pt->value.max, ==, pt_copy->value.max);

    }

    ops->cleanup(serialize_data);

    g_free(args);

    g_free(pt_copy);

}


static inline void tcg_out_ld_ptr(TCGContext *s, TCGReg ret, uintptr_t arg)

{

    TCGReg base = TCG_REG_G0;

    if (!check_fit_tl(arg, 10)) {

        tcg_out_movi(s, TCG_TYPE_PTR, ret, arg & ~0x3ff);

        base = ret;

    }

    tcg_out_ld(s, TCG_TYPE_PTR, ret, base, arg & 0x3ff);

}


void json_end_array(QJSON *json)

{

    qstring_append(json->str, " ]");

    json->omit_comma = false;

}


static void device_set_bootindex(Object *obj, Visitor *v, const char *name,

                                 void *opaque, Error **errp)

{

    BootIndexProperty *prop = opaque;

    int32_t boot_index;

    Error *local_err = NULL;

    visit_type_int32(v, name, &boot_index, &local_err);

    if (local_err) {

        goto out;

    }

    /* check whether bootindex is present in fw_boot_order list  */

    check_boot_index(boot_index, &local_err);

    if (local_err) {

        goto out;

    }

    /* change bootindex to a new one */

    *prop->bootindex = boot_index;

    add_boot_device_path(*prop->bootindex, prop->dev, prop->suffix);

out:

    if (local_err) {

        error_propagate(errp, local_err);

    }

}


static void q35_host_get_pci_hole_end(Object *obj, Visitor *v,

                                      const char *name, void *opaque,

                                      Error **errp)

{

    Q35PCIHost *s = Q35_HOST_DEVICE(obj);

    uint32_t value = s->mch.pci_hole.end;

    visit_type_uint32(v, name, &value, errp);

}


static int mp_dacl_setxattr(FsContext *ctx, const char *path, const char *name,

                            void *value, size_t size, int flags)

{

    char *buffer;

    int ret;

    buffer = rpath(ctx, path);

    ret = lsetxattr(buffer, MAP_ACL_DEFAULT, value, size, flags);

    g_free(buffer);

    return ret;

}


static void clear_tco_status(const TestData *d)

{

    qpci_io_writew(d->dev, d->tco_io_base + TCO1_STS, 0x0008);

    qpci_io_writew(d->dev, d->tco_io_base + TCO2_STS, 0x0002);

    qpci_io_writew(d->dev, d->tco_io_base + TCO2_STS, 0x0004);

}


static int qemu_rdma_registration_stop(QEMUFile *f, void *opaque,

                                       uint64_t flags)

{

    Error *local_err = NULL, **errp = &local_err;

    QEMUFileRDMA *rfile = opaque;

    RDMAContext *rdma = rfile->rdma;

    RDMAControlHeader head = { .len = 0, .repeat = 1 };

    int ret = 0;

    CHECK_ERROR_STATE();

    qemu_fflush(f);

    ret = qemu_rdma_drain_cq(f, rdma);

    if (ret < 0) {

        goto err;

    }

    if (flags == RAM_CONTROL_SETUP) {

        RDMAControlHeader resp = {.type = RDMA_CONTROL_RAM_BLOCKS_RESULT };

        RDMALocalBlocks *local = &rdma->local_ram_blocks;

        int reg_result_idx, i, j, nb_remote_blocks;

        head.type = RDMA_CONTROL_RAM_BLOCKS_REQUEST;

        DPRINTF("Sending registration setup for ram blocks...\n");

        /*

         * Make sure that we parallelize the pinning on both sides.

         * For very large guests, doing this serially takes a really

         * long time, so we have to 'interleave' the pinning locally

         * with the control messages by performing the pinning on this

         * side before we receive the control response from the other

         * side that the pinning has completed.

         */

        ret = qemu_rdma_exchange_send(rdma, &head, NULL, &resp,

                    &reg_result_idx, rdma->pin_all ?

                    qemu_rdma_reg_whole_ram_blocks : NULL);

        if (ret < 0) {

            ERROR(errp, "receiving remote info!");

            return ret;

        }

        nb_remote_blocks = resp.len / sizeof(RDMARemoteBlock);

        /*

         * The protocol uses two different sets of rkeys (mutually exclusive):

         * 1. One key to represent the virtual address of the entire ram block.

         *    (dynamic chunk registration disabled - pin everything with one rkey.)

         * 2. One to represent individual chunks within a ram block.

         *    (dynamic chunk registration enabled - pin individual chunks.)

         *

         * Once the capability is successfully negotiated, the destination transmits

         * the keys to use (or sends them later) including the virtual addresses

         * and then propagates the remote ram block descriptions to his local copy.

         */

        if (local->nb_blocks != nb_remote_blocks) {

            ERROR(errp, "ram blocks mismatch #1! "

                        "Your QEMU command line parameters are probably "

                        "not identical on both the source and destination.");

            return -EINVAL;

        }

        qemu_rdma_move_header(rdma, reg_result_idx, &resp);

        memcpy(rdma->block,

            rdma->wr_data[reg_result_idx].control_curr, resp.len);

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

            network_to_remote_block(&rdma->block[i]);

            /* search local ram blocks */

            for (j = 0; j < local->nb_blocks; j++) {

                if (rdma->block[i].offset != local->block[j].offset) {

                    continue;

                }

                if (rdma->block[i].length != local->block[j].length) {

                    ERROR(errp, "ram blocks mismatch #2! "

                        "Your QEMU command line parameters are probably "

                        "not identical on both the source and destination.");

                    return -EINVAL;

                }

                local->block[j].remote_host_addr =

                        rdma->block[i].remote_host_addr;

                local->block[j].remote_rkey = rdma->block[i].remote_rkey;

                break;

            }

            if (j >= local->nb_blocks) {

                ERROR(errp, "ram blocks mismatch #3! "

                        "Your QEMU command line parameters are probably "

                        "not identical on both the source and destination.");

                return -EINVAL;

            }

        }

    }

    DDDPRINTF("Sending registration finish %" PRIu64 "...\n", flags);

    head.type = RDMA_CONTROL_REGISTER_FINISHED;

    ret = qemu_rdma_exchange_send(rdma, &head, NULL, NULL, NULL, NULL);

    if (ret < 0) {

        goto err;

    }

    return 0;

err:

    rdma->error_state = ret;

    return ret;

}


static void adpcm_compress_trellis(AVCodecContext *avctx,

                                   const int16_t *samples, uint8_t *dst,

                                   ADPCMChannelStatus *c, int n, int stride)

{

    //FIXME 6% faster if frontier is a compile-time constant

    ADPCMEncodeContext *s = avctx->priv_data;

    const int frontier = 1 << avctx->trellis;

    const int version  = avctx->codec->id;

    TrellisPath *paths       = s->paths, *p;

    TrellisNode *node_buf    = s->node_buf;

    TrellisNode **nodep_buf  = s->nodep_buf;

    TrellisNode **nodes      = nodep_buf; // nodes[] is always sorted by .ssd

    TrellisNode **nodes_next = nodep_buf + frontier;

    int pathn = 0, froze = -1, i, j, k, generation = 0;

    uint8_t *hash = s->trellis_hash;

    memset(hash, 0xff, 65536 * sizeof(*hash));

    memset(nodep_buf, 0, 2 * frontier * sizeof(*nodep_buf));

    nodes[0]          = node_buf + frontier;

    nodes[0]->ssd     = 0;

    nodes[0]->path    = 0;

    nodes[0]->step    = c->step_index;

    nodes[0]->sample1 = c->sample1;

    nodes[0]->sample2 = c->sample2;

    if (version == AV_CODEC_ID_ADPCM_IMA_WAV ||

        version == AV_CODEC_ID_ADPCM_IMA_QT  ||

        version == AV_CODEC_ID_ADPCM_SWF)

        nodes[0]->sample1 = c->prev_sample;

    if (version == AV_CODEC_ID_ADPCM_MS)

        nodes[0]->step = c->idelta;

    if (version == AV_CODEC_ID_ADPCM_YAMAHA) {

        if (c->step == 0) {

            nodes[0]->step    = 127;

            nodes[0]->sample1 = 0;

        } else {

            nodes[0]->step    = c->step;

            nodes[0]->sample1 = c->predictor;

        }

    }

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

        TrellisNode *t = node_buf + frontier*(i&1);

        TrellisNode **u;

        int sample   = samples[i * stride];

        int heap_pos = 0;

        memset(nodes_next, 0, frontier * sizeof(TrellisNode*));

        for (j = 0; j < frontier && nodes[j]; j++) {

            // higher j have higher ssd already, so they're likely

            // to yield a suboptimal next sample too

            const int range = (j < frontier / 2) ? 1 : 0;

            const int step  = nodes[j]->step;

            int nidx;

            if (version == AV_CODEC_ID_ADPCM_MS) {

                const int predictor = ((nodes[j]->sample1 * c->coeff1) +

                                       (nodes[j]->sample2 * c->coeff2)) / 64;

                const int div  = (sample - predictor) / step;

                const int nmin = av_clip(div-range, -8, 6);

                const int nmax = av_clip(div+range, -7, 7);

                for (nidx = nmin; nidx <= nmax; nidx++) {

                    const int nibble = nidx & 0xf;

                    int dec_sample   = predictor + nidx * step;

#define STORE_NODE(NAME, STEP_INDEX)\

                    int d;\

                    uint32_t ssd;\

                    int pos;\

                    TrellisNode *u;\

                    uint8_t *h;\

                    dec_sample = av_clip_int16(dec_sample);\

                    d = sample - dec_sample;\

                    ssd = nodes[j]->ssd + d*d;\

                    /* Check for wraparound, skip such samples completely. \

                     * Note, changing ssd to a 64 bit variable would be \

                     * simpler, avoiding this check, but it's slower on \

                     * x86 32 bit at the moment. */\

                    if (ssd < nodes[j]->ssd)\

                        goto next_##NAME;\

                    /* Collapse any two states with the same previous sample value. \

                     * One could also distinguish states by step and by 2nd to last

                     * sample, but the effects of that are negligible.

                     * Since nodes in the previous generation are iterated

                     * through a heap, they're roughly ordered from better to

                     * worse, but not strictly ordered. Therefore, an earlier

                     * node with the same sample value is better in most cases

                     * (and thus the current is skipped), but not strictly

                     * in all cases. Only skipping samples where ssd >=

                     * ssd of the earlier node with the same sample gives

                     * slightly worse quality, though, for some reason. */ \

                    h = &hash[(uint16_t) dec_sample];\

                    if (*h == generation)\

                        goto next_##NAME;\

                    if (heap_pos < frontier) {\

                        pos = heap_pos++;\

                    } else {\

                        /* Try to replace one of the leaf nodes with the new \

                         * one, but try a different slot each time. */\

                        pos = (frontier >> 1) +\

                              (heap_pos & ((frontier >> 1) - 1));\

                        if (ssd > nodes_next[pos]->ssd)\

                            goto next_##NAME;\

                        heap_pos++;\

                    }\

                    *h = generation;\

                    u  = nodes_next[pos];\

                    if (!u) {\

                        av_assert1(pathn < FREEZE_INTERVAL << avctx->trellis);\

                        u = t++;\

                        nodes_next[pos] = u;\

                        u->path = pathn++;\

                    }\

                    u->ssd  = ssd;\

                    u->step = STEP_INDEX;\

                    u->sample2 = nodes[j]->sample1;\

                    u->sample1 = dec_sample;\

                    paths[u->path].nibble = nibble;\

                    paths[u->path].prev   = nodes[j]->path;\

                    /* Sift the newly inserted node up in the heap to \

                     * restore the heap property. */\

                    while (pos > 0) {\

                        int parent = (pos - 1) >> 1;\

                        if (nodes_next[parent]->ssd <= ssd)\

                            break;\

                        FFSWAP(TrellisNode*, nodes_next[parent], nodes_next[pos]);\

                        pos = parent;\

                    }\

                    next_##NAME:;

                    STORE_NODE(ms, FFMAX(16,

                               (ff_adpcm_AdaptationTable[nibble] * step) >> 8));

                }

            } else if (version == AV_CODEC_ID_ADPCM_IMA_WAV ||

                       version == AV_CODEC_ID_ADPCM_IMA_QT  ||

                       version == AV_CODEC_ID_ADPCM_SWF) {

#define LOOP_NODES(NAME, STEP_TABLE, STEP_INDEX)\

                const int predictor = nodes[j]->sample1;\

                const int div = (sample - predictor) * 4 / STEP_TABLE;\

                int nmin = av_clip(div - range, -7, 6);\

                int nmax = av_clip(div + range, -6, 7);\

                if (nmin <= 0)\

                    nmin--; /* distinguish -0 from +0 */\

                if (nmax < 0)\

                    nmax--;\

                for (nidx = nmin; nidx <= nmax; nidx++) {\

                    const int nibble = nidx < 0 ? 7 - nidx : nidx;\

                    int dec_sample = predictor +\

                                    (STEP_TABLE *\

                                     ff_adpcm_yamaha_difflookup[nibble]) / 8;\

                    STORE_NODE(NAME, STEP_INDEX);\

                }

                LOOP_NODES(ima, ff_adpcm_step_table[step],

                           av_clip(step + ff_adpcm_index_table[nibble], 0, 88));

            } else { //AV_CODEC_ID_ADPCM_YAMAHA

                LOOP_NODES(yamaha, step,

                           av_clip((step * ff_adpcm_yamaha_indexscale[nibble]) >> 8,

                                   127, 24567));

#undef LOOP_NODES

#undef STORE_NODE

            }

        }

        u = nodes;

        nodes = nodes_next;

        nodes_next = u;

        generation++;

        if (generation == 255) {

            memset(hash, 0xff, 65536 * sizeof(*hash));

            generation = 0;

        }

        // prevent overflow

        if (nodes[0]->ssd > (1 << 28)) {

            for (j = 1; j < frontier && nodes[j]; j++)

                nodes[j]->ssd -= nodes[0]->ssd;

            nodes[0]->ssd = 0;

        }

        // merge old paths to save memory

        if (i == froze + FREEZE_INTERVAL) {

            p = &paths[nodes[0]->path];

            for (k = i; k > froze; k--) {

                dst[k] = p->nibble;

                p = &paths[p->prev];

            }

            froze = i;

            pathn = 0;

            // other nodes might use paths that don't coincide with the frozen one.

            // checking which nodes do so is too slow, so just kill them all.

            // this also slightly improves quality, but I don't know why.

            memset(nodes + 1, 0, (frontier - 1) * sizeof(TrellisNode*));

        }

    }

    p = &paths[nodes[0]->path];

    for (i = n - 1; i > froze; i--) {

        dst[i] = p->nibble;

        p = &paths[p->prev];

    }

    c->predictor  = nodes[0]->sample1;

    c->sample1    = nodes[0]->sample1;

    c->sample2    = nodes[0]->sample2;

    c->step_index = nodes[0]->step;

    c->step       = nodes[0]->step;

    c->idelta     = nodes[0]->step;

}


USBDevice *usbdevice_create(const char *cmdline)
{
    USBBus *bus = usb_bus_find(-1 /* any */);
    LegacyUSBFactory *f = NULL;
    Error *err = NULL;
    GSList *i;
    char driver[32];
    const char *params;
    int len;
    USBDevice *dev;
    ObjectClass *klass;
    DeviceClass *dc;
    params = strchr(cmdline,':');
    if (params) {
        params++;
        len = params - cmdline;
        if (len > sizeof(driver))
            len = sizeof(driver);
        pstrcpy(driver, len, cmdline);
    } else {
        params = "";
        pstrcpy(driver, sizeof(driver), cmdline);
    for (i = legacy_usb_factory; i; i = i->next) {
        f = i->data;
        if (strcmp(f->usbdevice_name, driver) == 0) {
            break;
    if (i == NULL) {
#if 0
        /* no error because some drivers are not converted (yet) */
        error_report("usbdevice %s not found", driver);
#endif
    if (!bus) {
        error_report("Error: no usb bus to attach usbdevice %s, "
                     "please try -machine usb=on and check that "
                     "the machine model supports USB", driver);
    if (f->usbdevice_init) {
        dev = f->usbdevice_init(bus, params);
    } else {
        if (*params) {
            error_report("usbdevice %s accepts no params", driver);
        dev = usb_create(bus, f->name);
    if (!dev) {
        error_report("Failed to create USB device '%s'", f->name);
    object_property_set_bool(OBJECT(dev), true, "realized", &err);
    if (err) {
        error_reportf_err(err, "Failed to initialize USB device '%s': ",
                          f->name);
        object_unparent(OBJECT(dev));
    return dev;


e1000e_write_ext_rx_descr(E1000ECore *core, uint8_t *desc,

                          struct NetRxPkt *pkt,

                          const E1000E_RSSInfo *rss_info,

                          uint16_t length)

{

    union e1000_rx_desc_extended *d = (union e1000_rx_desc_extended *) desc;

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

    d->wb.upper.length = cpu_to_le16(length);

    e1000e_build_rx_metadata(core, pkt, pkt != NULL,

                             rss_info,

                             &d->wb.lower.hi_dword.rss,

                             &d->wb.lower.mrq,

                             &d->wb.upper.status_error,

                             &d->wb.lower.hi_dword.csum_ip.ip_id,

                             &d->wb.upper.vlan);

}


static inline uint16_t mipsdsp_sub_i16(int16_t a, int16_t b, CPUMIPSState *env)

{

    int16_t  temp;

    temp = a - b;

    if (MIPSDSP_OVERFLOW(a, -b, temp, 0x8000)) {

        set_DSPControl_overflow_flag(1, 20, env);

    }

    return temp;

}


int ff_g723_1_scale_vector(int16_t *dst, const int16_t *vector, int length)

{

    int bits, max = 0;

    int i;

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

        max |= FFABS(vector[i]);

    bits= 14 - av_log2_16bit(max);

    bits= FFMAX(bits, 0);

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

        dst[i] = vector[i] << bits >> 3;

    return bits - 3;

}


void sws_freeFilter(SwsFilter *filter)

{

    if (!filter)

        return;

    if (filter->lumH)

        sws_freeVec(filter->lumH);

    if (filter->lumV)

        sws_freeVec(filter->lumV);

    if (filter->chrH)

        sws_freeVec(filter->chrH);

    if (filter->chrV)

        sws_freeVec(filter->chrV);

    av_free(filter);

}


static void phys_sections_clear(void)

{

    phys_sections_nb = 0;

}


void add_codec(FFStream *stream, AVCodecContext *av)

{

    AVStream *st;

    /* compute default parameters */

    switch(av->codec_type) {

    case CODEC_TYPE_AUDIO:

        if (av->bit_rate == 0)

            av->bit_rate = 64000;

        if (av->sample_rate == 0)

            av->sample_rate = 22050;

        if (av->channels == 0)

            av->channels = 1;

        break;

    case CODEC_TYPE_VIDEO:

        if (av->bit_rate == 0)

            av->bit_rate = 64000;

        if (av->frame_rate == 0)

            av->frame_rate = 5 * FRAME_RATE_BASE;

        if (av->width == 0 || av->height == 0) {

            av->width = 160;

            av->height = 128;

        }

        /* Bitrate tolerance is less for streaming */

        if (av->bit_rate_tolerance == 0)

            av->bit_rate_tolerance = av->bit_rate / 4;

        if (av->qmin == 0)

            av->qmin = 3;

        if (av->qmax == 0)

            av->qmax = 31;

        if (av->max_qdiff == 0)

            av->max_qdiff = 3;

        av->qcompress = 0.5;

        av->qblur = 0.5;

        break;

    default:

        abort();

    }

    st = av_mallocz(sizeof(AVStream));

    if (!st)

        return;

    stream->streams[stream->nb_streams++] = st;

    memcpy(&st->codec, av, sizeof(AVCodecContext));

}


static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)

{

    AVFrame *src = srcp->f;

    int ret;

    if (src->format == AV_PIX_FMT_VIDEOTOOLBOX && src->buf[0]->size == 1)

        return AVERROR_EXTERNAL;

    ret = av_frame_ref(dst, src);

    if (ret < 0)

        return ret;

    av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(&h->sei.frame_packing), 0);

    if (srcp->sei_recovery_frame_cnt == 0)

        dst->key_frame = 1;

    return 0;

}


int ff_dxva2_is_d3d11(const AVCodecContext *avctx)

{

    if (CONFIG_D3D11VA)

        return avctx->pix_fmt == AV_PIX_FMT_D3D11VA_VLD;

    else

        return 0;

}


static int nsv_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)

{

    NSVContext *nsv = s->priv_data;

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

    NSVStream *nst = st->priv_data;

    int index;

    index = av_index_search_timestamp(st, timestamp, flags);

    if(index < 0)

        return -1;

    avio_seek(s->pb, st->index_entries[index].pos, SEEK_SET);

    nst->frame_offset = st->index_entries[index].timestamp;

    nsv->state = NSV_UNSYNC;

    return 0;

}


static inline abi_long do_semctl(int semid, int semnum, int cmd,

                                 union target_semun target_su)

{

    union semun arg;

    struct semid_ds dsarg;

    unsigned short *array;

    struct seminfo seminfo;

    abi_long ret = -TARGET_EINVAL;

    abi_long err;

    cmd &= 0xff;

    switch( cmd ) {

	case GETVAL:

	case SETVAL:

            arg.val = tswapl(target_su.val);

            ret = get_errno(semctl(semid, semnum, cmd, arg));

            target_su.val = tswapl(arg.val);

            break;

	case GETALL:

	case SETALL:

            err = target_to_host_semarray(semid, &array, target_su.array);

            if (err)

                return err;

            arg.array = array;

            ret = get_errno(semctl(semid, semnum, cmd, arg));

            err = host_to_target_semarray(semid, target_su.array, &array);

            if (err)

                return err;

            break;

	case IPC_STAT:

	case IPC_SET:

	case SEM_STAT:

            err = target_to_host_semid_ds(&dsarg, target_su.buf);

            if (err)

                return err;

            arg.buf = &dsarg;

            ret = get_errno(semctl(semid, semnum, cmd, arg));

            err = host_to_target_semid_ds(target_su.buf, &dsarg);

            if (err)

                return err;

            break;

	case IPC_INFO:

	case SEM_INFO:

            arg.__buf = &seminfo;

            ret = get_errno(semctl(semid, semnum, cmd, arg));

            err = host_to_target_seminfo(target_su.__buf, &seminfo);

            if (err)

                return err;

            break;

	case IPC_RMID:

	case GETPID:

	case GETNCNT:

	case GETZCNT:

            ret = get_errno(semctl(semid, semnum, cmd, NULL));

            break;

    }

    return ret;

}


DISAS_INSN(wdebug)

{

    if (IS_USER(s)) {

        gen_exception(s, s->pc - 2, EXCP_PRIVILEGE);

        return;

    }

    /* TODO: Implement wdebug.  */

    qemu_assert(0, "WDEBUG not implemented");

}


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

                                 uint8_t *buf, int nb_sectors)

{

    BDRVCowState *s = bs->opaque;

    int ret, n;

    while (nb_sectors > 0) {

        if (cow_co_is_allocated(bs, sector_num, nb_sectors, &n)) {

            ret = bdrv_pread(bs->file,

                        s->cow_sectors_offset + sector_num * 512,

                        buf, n * 512);

            if (ret < 0) {

                return ret;

            }

        } else {

            if (bs->backing_hd) {

                /* read from the base image */

                ret = bdrv_read(bs->backing_hd, sector_num, buf, n);

                if (ret < 0) {

                    return ret;

                }

            } else {

                memset(buf, 0, n * 512);

            }

        }

        nb_sectors -= n;

        sector_num += n;

        buf += n * 512;

    }

    return 0;

}


int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)

{

    AVStream *st;

    int tag;

    if (fc->nb_streams < 1)

        return 0;

    st = fc->streams[fc->nb_streams-1];

    avio_rb32(pb); /* version + flags */

    ff_mp4_read_descr(fc, pb, &tag);

    if (tag == MP4ESDescrTag) {

        ff_mp4_parse_es_descr(pb, NULL);

    } else

        avio_rb16(pb); /* ID */

    ff_mp4_read_descr(fc, pb, &tag);

    if (tag == MP4DecConfigDescrTag)

        ff_mp4_read_dec_config_descr(fc, st, pb);

    return 0;

}