static int cinvideo_decode_frame(AVCodecContext *avctx,

                                 void *data, int *data_size,

                                 AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    CinVideoContext *cin = avctx->priv_data;

    int i, y, palette_type, palette_colors_count, bitmap_frame_type, bitmap_frame_size, res = 0;

    palette_type = buf[0];

    palette_colors_count = AV_RL16(buf+1);

    bitmap_frame_type = buf[3];

    buf += 4;

    bitmap_frame_size = buf_size - 4;

    /* handle palette */

    if (bitmap_frame_size < palette_colors_count * (3 + (palette_type != 0)))

        return AVERROR_INVALIDDATA;

    if (palette_type == 0) {

        if (palette_colors_count > 256)

            return AVERROR_INVALIDDATA;

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

            cin->palette[i] = 0xFFU << 24 | bytestream_get_le24(&buf);

            bitmap_frame_size -= 3;

        }

    } else {

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

            cin->palette[buf[0]] = 0xFFU << 24 | AV_RL24(buf+1);

            buf += 4;

            bitmap_frame_size -= 4;

        }

    }

    /* note: the decoding routines below assumes that surface.width = surface.pitch */

    switch (bitmap_frame_type) {

    case 9:

        cin_decode_rle(buf, bitmap_frame_size,

          cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);

        break;

    case 34:

        cin_decode_rle(buf, bitmap_frame_size,

          cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);

        cin_apply_delta_data(cin->bitmap_table[CIN_PRE_BMP],

          cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);

        break;

    case 35:

        cin_decode_huffman(buf, bitmap_frame_size,

          cin->bitmap_table[CIN_INT_BMP], cin->bitmap_size);

        cin_decode_rle(cin->bitmap_table[CIN_INT_BMP], bitmap_frame_size,

          cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);

        break;

    case 36:

        bitmap_frame_size = cin_decode_huffman(buf, bitmap_frame_size,

          cin->bitmap_table[CIN_INT_BMP], cin->bitmap_size);

        cin_decode_rle(cin->bitmap_table[CIN_INT_BMP], bitmap_frame_size,

          cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);

        cin_apply_delta_data(cin->bitmap_table[CIN_PRE_BMP],

          cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);

        break;

    case 37:

        cin_decode_huffman(buf, bitmap_frame_size,

          cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);

        break;

    case 38:

        res = cin_decode_lzss(buf, bitmap_frame_size,

                              cin->bitmap_table[CIN_CUR_BMP],

                              cin->bitmap_size);

        if (res < 0)

            return res;

        break;

    case 39:

        res = cin_decode_lzss(buf, bitmap_frame_size,

                              cin->bitmap_table[CIN_CUR_BMP],

                              cin->bitmap_size);

        if (res < 0)

            return res;

        cin_apply_delta_data(cin->bitmap_table[CIN_PRE_BMP],

          cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);

        break;

    }

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

    if ((res = avctx->reget_buffer(avctx, &cin->frame))) {

        av_log(cin->avctx, AV_LOG_ERROR, "failed to allocate a frame\n");

        return res;

    }

    memcpy(cin->frame.data[1], cin->palette, sizeof(cin->palette));

    cin->frame.palette_has_changed = 1;

    for (y = 0; y < cin->avctx->height; ++y)

        memcpy(cin->frame.data[0] + (cin->avctx->height - 1 - y) * cin->frame.linesize[0],

          cin->bitmap_table[CIN_CUR_BMP] + y * cin->avctx->width,

          cin->avctx->width);

    FFSWAP(uint8_t *, cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_table[CIN_PRE_BMP]);

    *data_size = sizeof(AVFrame);

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

    return buf_size;

}


static void check_threshold_8(void){

    LOCAL_ALIGNED_32(uint8_t, in       , [WIDTH_PADDED]);

    LOCAL_ALIGNED_32(uint8_t, threshold, [WIDTH_PADDED]);

    LOCAL_ALIGNED_32(uint8_t, min      , [WIDTH_PADDED]);

    LOCAL_ALIGNED_32(uint8_t, max      , [WIDTH_PADDED]);

    LOCAL_ALIGNED_32(uint8_t, out_ref  , [WIDTH_PADDED]);

    LOCAL_ALIGNED_32(uint8_t, out_new  , [WIDTH_PADDED]);

    ptrdiff_t line_size = WIDTH_PADDED;

    int w = WIDTH;

    ThresholdContext s;

    s.depth = 8;

    ff_threshold_init(&s);

    declare_func(void, const uint8_t *in, const uint8_t *threshold,

                 const uint8_t *min, const uint8_t *max, uint8_t *out,

                 ptrdiff_t ilinesize, ptrdiff_t tlinesize,

                 ptrdiff_t flinesize, ptrdiff_t slinesize,

                 ptrdiff_t olinesize, int w, int h);

    memset(in,     0, WIDTH_PADDED);

    memset(threshold, 0, WIDTH_PADDED);

    memset(min, 0, WIDTH_PADDED);

    memset(max, 0, WIDTH_PADDED);

    memset(out_ref, 0, WIDTH_PADDED);

    memset(out_new, 0, WIDTH_PADDED);

    randomize_buffers(in, WIDTH);

    randomize_buffers(threshold, WIDTH);

    randomize_buffers(min, WIDTH);

    randomize_buffers(max, WIDTH);

    if (check_func(s.threshold, "threshold8")) {

        call_ref(in, threshold, min, max, out_ref, line_size, line_size, line_size, line_size, line_size, w, 1);

        call_new(in, threshold, min, max, out_new, line_size, line_size, line_size, line_size, line_size, w, 1);

        if (memcmp(out_ref, out_new, w))

            fail();

        bench_new(in, threshold, min, max, out_new, line_size, line_size, line_size, line_size, line_size, w, 1);

    }

}


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

{

    PCIDevice *d = PCI_DEVICE(dev);

    GenPCIERootPort *grp = GEN_PCIE_ROOT_PORT(d);

    PCIERootPortClass *rpc = PCIE_ROOT_PORT_GET_CLASS(d);

    rpc->parent_realize(dev, errp);

    int rc = pci_bridge_qemu_reserve_cap_init(d, 0, grp->bus_reserve,

            grp->io_reserve, grp->mem_reserve, grp->pref32_reserve,

            grp->pref64_reserve, errp);

    if (rc < 0) {

        rpc->parent_class.exit(d);

        return;

    }

    if (!grp->io_reserve) {

        pci_word_test_and_clear_mask(d->wmask + PCI_COMMAND,

                                     PCI_COMMAND_IO);

        d->wmask[PCI_IO_BASE] = 0;

        d->wmask[PCI_IO_LIMIT] = 0;

    }

}


static bool megasas_use_msi(MegasasState *s)

{

    return s->msi != ON_OFF_AUTO_OFF;

}


int32_t scsi_send_command(SCSIDevice *s, uint32_t tag, uint8_t *buf, int lun)

{

    int64_t nb_sectors;

    uint32_t lba;

    uint32_t len;

    int cmdlen;

    int is_write;

    s->command = buf[0];

    s->tag = tag;

    s->sector_count = 0;

    s->buf_pos = 0;

    s->buf_len = 0;

    is_write = 0;

    DPRINTF("Command: 0x%02x", buf[0]);

    switch (s->command >> 5) {

    case 0:

        lba = buf[3] | (buf[2] << 8) | ((buf[1] & 0x1f) << 16);

        len = buf[4];

        cmdlen = 6;

        break;

    case 1:

    case 2:

        lba = buf[5] | (buf[4] << 8) | (buf[3] << 16) | (buf[2] << 24);

        len = buf[8] | (buf[7] << 8);

        cmdlen = 10;

        break;

    case 4:

        lba = buf[5] | (buf[4] << 8) | (buf[3] << 16) | (buf[2] << 24);

        len = buf[13] | (buf[12] << 8) | (buf[11] << 16) | (buf[10] << 24);

        cmdlen = 16;

        break;

    case 5:

        lba = buf[5] | (buf[4] << 8) | (buf[3] << 16) | (buf[2] << 24);

        len = buf[9] | (buf[8] << 8) | (buf[7] << 16) | (buf[6] << 24);

        cmdlen = 12;

        break;

    default:

        BADF("Unsupported command length, command %x\n", s->command);

        goto fail;

    }

#ifdef DEBUG_SCSI

    {

        int i;

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

            printf(" 0x%02x", buf[i]);

        }

        printf("\n");

    }

#endif

    if (lun || buf[1] >> 5) {

        /* Only LUN 0 supported.  */

        DPRINTF("Unimplemented LUN %d\n", lun ? lun : buf[1] >> 5);

        goto fail;

    }

    switch (s->command) {

    case 0x0:

	DPRINTF("Test Unit Ready\n");

	break;

    case 0x03:

        DPRINTF("Request Sense (len %d)\n", len);

        if (len < 4)

            goto fail;

        memset(buf, 0, 4);

        s->buf[0] = 0xf0;

        s->buf[1] = 0;

        s->buf[2] = s->sense;

        s->buf_len = 4;

        break;

    case 0x12:

        DPRINTF("Inquiry (len %d)\n", len);

        if (len < 36) {

            BADF("Inquiry buffer too small (%d)\n", len);

        }

	memset(s->buf, 0, 36);

	if (bdrv_get_type_hint(s->bdrv) == BDRV_TYPE_CDROM) {

	    s->buf[0] = 5;

            s->buf[1] = 0x80;

	    memcpy(&s->buf[16], "QEMU CD-ROM    ", 16);

	} else {

	    s->buf[0] = 0;

	    memcpy(&s->buf[16], "QEMU HARDDISK  ", 16);

	}

	memcpy(&s->buf[8], "QEMU   ", 8);

        memcpy(&s->buf[32], QEMU_VERSION, 4);

        /* Identify device as SCSI-3 rev 1.

           Some later commands are also implemented. */

	s->buf[2] = 3;

	s->buf[3] = 2; /* Format 2 */

	s->buf[4] = 32;

	s->buf_len = 36;

	break;

    case 0x16:

        DPRINTF("Reserve(6)\n");

        if (buf[1] & 1)

            goto fail;

        break;

    case 0x17:

        DPRINTF("Release(6)\n");

        if (buf[1] & 1)

            goto fail;

        break;

    case 0x1a:

    case 0x5a:

        {

            char *p;

            int page;

            page = buf[2] & 0x3f;

            DPRINTF("Mode Sense (page %d, len %d)\n", page, len);

            p = s->buf;

            memset(p, 0, 4);

            s->buf[1] = 0; /* Default media type.  */

            s->buf[3] = 0; /* Block descriptor length.  */

            if (bdrv_get_type_hint(s->bdrv) == BDRV_TYPE_CDROM) {

                s->buf[2] = 0x80; /* Readonly.  */

            }

            p += 4;

            if ((page == 8 || page == 0x3f)) {

                /* Caching page.  */

                p[0] = 8;

                p[1] = 0x12;

                p[2] = 4; /* WCE */

                p += 19;

            }

            if ((page == 0x3f || page == 0x2a)

                    && (bdrv_get_type_hint(s->bdrv) == BDRV_TYPE_CDROM)) {

                /* CD Capabilities and Mechanical Status page. */

                p[0] = 0x2a;

                p[1] = 0x14;

                p[2] = 3; // CD-R & CD-RW read

                p[3] = 0; // Writing not supported

                p[4] = 0x7f; /* Audio, composite, digital out,

                                         mode 2 form 1&2, multi session */

                p[5] = 0xff; /* CD DA, DA accurate, RW supported,

                                         RW corrected, C2 errors, ISRC,

                                         UPC, Bar code */

                p[6] = 0x2d | (bdrv_is_locked(s->bdrv)? 2 : 0);

                /* Locking supported, jumper present, eject, tray */

                p[7] = 0; /* no volume & mute control, no

                                      changer */

                p[8] = (50 * 176) >> 8; // 50x read speed

                p[9] = (50 * 176) & 0xff;

                p[10] = 0 >> 8; // No volume

                p[11] = 0 & 0xff;

                p[12] = 2048 >> 8; // 2M buffer

                p[13] = 2048 & 0xff;

                p[14] = (16 * 176) >> 8; // 16x read speed current

                p[15] = (16 * 176) & 0xff;

                p[18] = (16 * 176) >> 8; // 16x write speed

                p[19] = (16 * 176) & 0xff;

                p[20] = (16 * 176) >> 8; // 16x write speed current

                p[21] = (16 * 176) & 0xff;

                p += 21;

            }

            s->buf_len = p - s->buf;

            s->buf[0] = s->buf_len - 4;

            if (s->buf_len > len)

                s->buf_len = len;

        }

        break;

    case 0x1b:

        DPRINTF("Start Stop Unit\n");

	break;

    case 0x1e:

        DPRINTF("Prevent Allow Medium Removal (prevent = %d)\n", buf[4] & 3);

        bdrv_set_locked(s->bdrv, buf[4] & 1);

	break;

    case 0x25:

	DPRINTF("Read Capacity\n");

        /* The normal LEN field for this command is zero.  */

	memset(s->buf, 0, 8);

	bdrv_get_geometry(s->bdrv, &nb_sectors);

	s->buf[0] = (nb_sectors >> 24) & 0xff;

	s->buf[1] = (nb_sectors >> 16) & 0xff;

	s->buf[2] = (nb_sectors >> 8) & 0xff;

	s->buf[3] = nb_sectors & 0xff;

	s->buf[4] = 0;

	s->buf[5] = 0;

        s->buf[6] = s->cluster_size * 2;

	s->buf[7] = 0;

	s->buf_len = 8;

	break;

    case 0x08:

    case 0x28:

        DPRINTF("Read (sector %d, count %d)\n", lba, len);

        s->sector = lba * s->cluster_size;

        s->sector_count = len * s->cluster_size;

        break;

    case 0x0a:

    case 0x2a:

        DPRINTF("Write (sector %d, count %d)\n", lba, len);

        s->sector = lba * s->cluster_size;

        s->sector_count = len * s->cluster_size;

        is_write = 1;

        break;

    case 0x35:

        DPRINTF("Syncronise cache (sector %d, count %d)\n", lba, len);

        bdrv_flush(s->bdrv);

        break;

    case 0x43:

        {

            int start_track, format, msf, toclen;

            msf = buf[1] & 2;

            format = buf[2] & 0xf;

            start_track = buf[6];

            bdrv_get_geometry(s->bdrv, &nb_sectors);

            DPRINTF("Read TOC (track %d format %d msf %d)\n", start_track, format, msf >> 1);

            switch(format) {

            case 0:

                toclen = cdrom_read_toc(nb_sectors, s->buf, msf, start_track);

                break;

            case 1:

                /* multi session : only a single session defined */

                toclen = 12;

                memset(s->buf, 0, 12);

                s->buf[1] = 0x0a;

                s->buf[2] = 0x01;

                s->buf[3] = 0x01;

                break;

            case 2:

                toclen = cdrom_read_toc_raw(nb_sectors, s->buf, msf, start_track);

                break;

            default:

                goto error_cmd;

            }

            if (toclen > 0) {

                if (len > toclen)

                  len = toclen;

                s->buf_len = len;

                break;

            }

        error_cmd:

            DPRINTF("Read TOC error\n");

            goto fail;

        }

    case 0x46:

        DPRINTF("Get Configuration (rt %d, maxlen %d)\n", buf[1] & 3, len);

        memset(s->buf, 0, 8);

        /* ??? This shoud probably return much more information.  For now

           just return the basic header indicating the CD-ROM profile.  */

        s->buf[7] = 8; // CD-ROM

        s->buf_len = 8;

        break;

    case 0x56:

        DPRINTF("Reserve(10)\n");

        if (buf[1] & 3)

            goto fail;

        break;

    case 0x57:

        DPRINTF("Release(10)\n");

        if (buf[1] & 3)

            goto fail;

        break;

    case 0xa0:

        DPRINTF("Report LUNs (len %d)\n", len);

        if (len < 16)

            goto fail;

        memset(s->buf, 0, 16);

        s->buf[3] = 8;

        s->buf_len = 16;

        break;

    default:

	DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);

    fail:

        scsi_command_complete(s, SENSE_ILLEGAL_REQUEST);

	return 0;

    }

    if (s->sector_count == 0 && s->buf_len == 0) {

        scsi_command_complete(s, SENSE_NO_SENSE);

    }

    len = s->sector_count * 512 + s->buf_len;

    return is_write ? -len : len;

}


static int vda_h264_uninit(AVCodecContext *avctx)

{

    VDAContext *vda = avctx->internal->hwaccel_priv_data;

    av_freep(&vda->bitstream);

    if (vda->frame)

        CVPixelBufferRelease(vda->frame);

    return 0;

}


static void usb_mtp_handle_data(USBDevice *dev, USBPacket *p)

{

    MTPState *s = USB_MTP(dev);

    MTPControl cmd;

    mtp_container container;

    uint32_t params[5];

    int i, rc;

    switch (p->ep->nr) {

    case EP_DATA_IN:

        if (s->data_out != NULL) {

            /* guest bug */

            trace_usb_mtp_stall(s->dev.addr, "awaiting data-out");

            p->status = USB_RET_STALL;

            return;

        }

        if (p->iov.size < sizeof(container)) {

            trace_usb_mtp_stall(s->dev.addr, "packet too small");

            p->status = USB_RET_STALL;

            return;

        }

        if (s->data_in !=  NULL) {

            MTPData *d = s->data_in;

            int dlen = d->length - d->offset;

            if (d->first) {

                trace_usb_mtp_data_in(s->dev.addr, d->trans, d->length);

                container.length = cpu_to_le32(d->length + sizeof(container));

                container.type   = cpu_to_le16(TYPE_DATA);

                container.code   = cpu_to_le16(d->code);

                container.trans  = cpu_to_le32(d->trans);

                usb_packet_copy(p, &container, sizeof(container));

                d->first = false;

                if (dlen > p->iov.size - sizeof(container)) {

                    dlen = p->iov.size - sizeof(container);

                }

            } else {

                if (dlen > p->iov.size) {

                    dlen = p->iov.size;

                }

            }

            if (d->fd == -1) {

                usb_packet_copy(p, d->data + d->offset, dlen);

            } else {

                if (d->alloc < p->iov.size) {

                    d->alloc = p->iov.size;

                    d->data = g_realloc(d->data, d->alloc);

                }

                rc = read(d->fd, d->data, dlen);

                if (rc != dlen) {

                    memset(d->data, 0, dlen);

                    s->result->code = RES_INCOMPLETE_TRANSFER;

                }

                usb_packet_copy(p, d->data, dlen);

            }

            d->offset += dlen;

            if (d->offset == d->length) {

                usb_mtp_data_free(s->data_in);

                s->data_in = NULL;

            }

        } else if (s->result != NULL) {

            MTPControl *r = s->result;

            int length = sizeof(container) + r->argc * sizeof(uint32_t);

            if (r->code == RES_OK) {

                trace_usb_mtp_success(s->dev.addr, r->trans,

                                      (r->argc > 0) ? r->argv[0] : 0,

                                      (r->argc > 1) ? r->argv[1] : 0);

            } else {

                trace_usb_mtp_error(s->dev.addr, r->code, r->trans,

                                    (r->argc > 0) ? r->argv[0] : 0,

                                    (r->argc > 1) ? r->argv[1] : 0);

            }

            container.length = cpu_to_le32(length);

            container.type   = cpu_to_le16(TYPE_RESPONSE);

            container.code   = cpu_to_le16(r->code);

            container.trans  = cpu_to_le32(r->trans);

            for (i = 0; i < r->argc; i++) {

                params[i] = cpu_to_le32(r->argv[i]);

            }

            usb_packet_copy(p, &container, sizeof(container));

            usb_packet_copy(p, &params, length - sizeof(container));

            g_free(s->result);

            s->result = NULL;

        }

        break;

    case EP_DATA_OUT:

        if (p->iov.size < sizeof(container)) {

            trace_usb_mtp_stall(s->dev.addr, "packet too small");

            p->status = USB_RET_STALL;

            return;

        }

        usb_packet_copy(p, &container, sizeof(container));

        switch (le16_to_cpu(container.type)) {

        case TYPE_COMMAND:

            if (s->data_in || s->data_out || s->result) {

                trace_usb_mtp_stall(s->dev.addr, "transaction inflight");

                p->status = USB_RET_STALL;

                return;

            }

            cmd.code = le16_to_cpu(container.code);

            cmd.argc = (le32_to_cpu(container.length) - sizeof(container))

                / sizeof(uint32_t);

            cmd.trans = le32_to_cpu(container.trans);

            if (cmd.argc > ARRAY_SIZE(cmd.argv)) {

                cmd.argc = ARRAY_SIZE(cmd.argv);

            }

            if (p->iov.size < sizeof(container) + cmd.argc * sizeof(uint32_t)) {

                trace_usb_mtp_stall(s->dev.addr, "packet too small");

                p->status = USB_RET_STALL;

                return;

            }

            usb_packet_copy(p, &params, cmd.argc * sizeof(uint32_t));

            for (i = 0; i < cmd.argc; i++) {

                cmd.argv[i] = le32_to_cpu(params[i]);

            }

            trace_usb_mtp_command(s->dev.addr, cmd.code, cmd.trans,

                                  (cmd.argc > 0) ? cmd.argv[0] : 0,

                                  (cmd.argc > 1) ? cmd.argv[1] : 0,

                                  (cmd.argc > 2) ? cmd.argv[2] : 0,

                                  (cmd.argc > 3) ? cmd.argv[3] : 0,

                                  (cmd.argc > 4) ? cmd.argv[4] : 0);

            usb_mtp_command(s, &cmd);

            break;

        default:

            /* not needed as long as the mtp device is read-only */

            p->status = USB_RET_STALL;

            return;

        }

        break;

    case EP_EVENT:

#ifdef __linux__

        if (!QTAILQ_EMPTY(&s->events)) {

            struct MTPMonEntry *e = QTAILQ_LAST(&s->events, events);

            uint32_t handle;

            int len = sizeof(container) + sizeof(uint32_t);

            if (p->iov.size < len) {

                trace_usb_mtp_stall(s->dev.addr,

                                    "packet too small to send event");

                p->status = USB_RET_STALL;

                return;

            }

            QTAILQ_REMOVE(&s->events, e, next);

            container.length = cpu_to_le32(len);

            container.type = cpu_to_le32(TYPE_EVENT);

            container.code = cpu_to_le16(e->event);

            container.trans = 0; /* no trans specific events */

            handle = cpu_to_le32(e->handle);

            usb_packet_copy(p, &container, sizeof(container));

            usb_packet_copy(p, &handle, sizeof(uint32_t));

            g_free(e);

            return;

        }

#endif

        p->status = USB_RET_NAK;

        return;

    default:

        trace_usb_mtp_stall(s->dev.addr, "invalid endpoint");

        p->status = USB_RET_STALL;

        return;

    }

    if (p->actual_length == 0) {

        trace_usb_mtp_nak(s->dev.addr, p->ep->nr);

        p->status = USB_RET_NAK;

        return;

    } else {

        trace_usb_mtp_xfer(s->dev.addr, p->ep->nr, p->actual_length,

                           p->iov.size);

        return;

    }

}


ReadLineState *readline_init(ReadLinePrintfFunc *printf_func,

                             ReadLineFlushFunc *flush_func,

                             void *opaque,

                             ReadLineCompletionFunc *completion_finder)

{

    ReadLineState *rs = g_malloc0(sizeof(*rs));

    rs->hist_entry = -1;

    rs->opaque = opaque;

    rs->printf_func = printf_func;

    rs->flush_func = flush_func;

    rs->completion_finder = completion_finder;

    return rs;

}


static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist,

                                int32_t offset)

{

    AHCICmdHdr *cmd = ad->cur_cmd;

    uint16_t opts = le16_to_cpu(cmd->opts);

    uint16_t prdtl = le16_to_cpu(cmd->prdtl);

    uint64_t cfis_addr = le64_to_cpu(cmd->tbl_addr);

    uint64_t prdt_addr = cfis_addr + 0x80;

    dma_addr_t prdt_len = (prdtl * sizeof(AHCI_SG));

    dma_addr_t real_prdt_len = prdt_len;

    uint8_t *prdt;

    int i;

    int r = 0;

    uint64_t sum = 0;

    int off_idx = -1;

    int64_t off_pos = -1;

    int tbl_entry_size;

    IDEBus *bus = &ad->port;

    BusState *qbus = BUS(bus);

    /*

     * Note: AHCI PRDT can describe up to 256GiB. SATA/ATA only support

     * transactions of up to 32MiB as of ATA8-ACS3 rev 1b, assuming a

     * 512 byte sector size. We limit the PRDT in this implementation to

     * a reasonably large 2GiB, which can accommodate the maximum transfer

     * request for sector sizes up to 32K.

     */

    if (!prdtl) {

        DPRINTF(ad->port_no, "no sg list given by guest: 0x%08x\n", opts);

        return -1;

    }

    /* map PRDT */

    if (!(prdt = dma_memory_map(ad->hba->as, prdt_addr, &prdt_len,

                                DMA_DIRECTION_TO_DEVICE))){

        DPRINTF(ad->port_no, "map failed\n");

        return -1;

    }

    if (prdt_len < real_prdt_len) {

        DPRINTF(ad->port_no, "mapped less than expected\n");

        r = -1;

        goto out;

    }

    /* Get entries in the PRDT, init a qemu sglist accordingly */

    if (prdtl > 0) {

        AHCI_SG *tbl = (AHCI_SG *)prdt;

        sum = 0;

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

            /* flags_size is zero-based */

            tbl_entry_size = prdt_tbl_entry_size(&tbl[i]);

            if (offset <= (sum + tbl_entry_size)) {

                off_idx = i;

                off_pos = offset - sum;

                break;

            }

            sum += tbl_entry_size;

        }

        if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) {

            DPRINTF(ad->port_no, "%s: Incorrect offset! "

                            "off_idx: %d, off_pos: %"PRId64"\n",

                            __func__, off_idx, off_pos);

            r = -1;

            goto out;

        }

        qemu_sglist_init(sglist, qbus->parent, (prdtl - off_idx),

                         ad->hba->as);

        qemu_sglist_add(sglist, le64_to_cpu(tbl[off_idx].addr) + off_pos,

                        prdt_tbl_entry_size(&tbl[off_idx]) - off_pos);

        for (i = off_idx + 1; i < prdtl; i++) {

            /* flags_size is zero-based */

            qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr),

                            prdt_tbl_entry_size(&tbl[i]));

            if (sglist->size > INT32_MAX) {

                error_report("AHCI Physical Region Descriptor Table describes "

                             "more than 2 GiB.\n");

                qemu_sglist_destroy(sglist);

                r = -1;

                goto out;

            }

        }

    }

out:

    dma_memory_unmap(ad->hba->as, prdt, prdt_len,

                     DMA_DIRECTION_TO_DEVICE, prdt_len);

    return r;

}


static void simple_varargs(void)

{

    QObject *embedded_obj;

    QObject *obj;

    LiteralQObject decoded = QLIT_QLIST(((LiteralQObject[]){

            QLIT_QINT(1),

            QLIT_QINT(2),

            QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QINT(32),

                        QLIT_QINT(42),

                        {}})),

            {}}));

    embedded_obj = qobject_from_json("[32, 42]", NULL);

    g_assert(embedded_obj != NULL);

    obj = qobject_from_jsonf("[%d, 2, %p]", 1, embedded_obj);

    g_assert(compare_litqobj_to_qobj(&decoded, obj) == 1);

    qobject_decref(obj);

}


static ram_addr_t ram_block_add(RAMBlock *new_block, Error **errp)

{

    RAMBlock *block;

    RAMBlock *last_block = NULL;

    ram_addr_t old_ram_size, new_ram_size;

    old_ram_size = last_ram_offset() >> TARGET_PAGE_BITS;

    qemu_mutex_lock_ramlist();

    new_block->offset = find_ram_offset(new_block->max_length);

    if (!new_block->host) {

        if (xen_enabled()) {

            xen_ram_alloc(new_block->offset, new_block->max_length,

                          new_block->mr);

        } else {

            new_block->host = phys_mem_alloc(new_block->max_length,

                                             &new_block->mr->align);

            if (!new_block->host) {

                error_setg_errno(errp, errno,

                                 "cannot set up guest memory '%s'",

                                 memory_region_name(new_block->mr));

                qemu_mutex_unlock_ramlist();

                return -1;

            memory_try_enable_merging(new_block->host, new_block->max_length);

    /* Keep the list sorted from biggest to smallest block.  Unlike QTAILQ,

     * QLIST (which has an RCU-friendly variant) does not have insertion at

     * tail, so save the last element in last_block.

     */

    QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {

        last_block = block;

        if (block->max_length < new_block->max_length) {

            break;

    if (block) {

        QLIST_INSERT_BEFORE_RCU(block, new_block, next);

    } else if (last_block) {

        QLIST_INSERT_AFTER_RCU(last_block, new_block, next);

    } else { /* list is empty */

        QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);

    ram_list.mru_block = NULL;

    /* Write list before version */

    smp_wmb();

    ram_list.version++;

    qemu_mutex_unlock_ramlist();

    new_ram_size = last_ram_offset() >> TARGET_PAGE_BITS;

        int i;

        /* ram_list.dirty_memory[] is protected by the iothread lock.  */

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

            ram_list.dirty_memory[i] =

                bitmap_zero_extend(ram_list.dirty_memory[i],

                                   old_ram_size, new_ram_size);

    cpu_physical_memory_set_dirty_range(new_block->offset,

                                        new_block->used_length,

                                        DIRTY_CLIENTS_ALL);

    if (new_block->host) {

        qemu_ram_setup_dump(new_block->host, new_block->max_length);

        qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);

        qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);

        if (kvm_enabled()) {

            kvm_setup_guest_memory(new_block->host, new_block->max_length);

    return new_block->offset;


void qemu_set_log(int log_flags, bool use_own_buffers)

{

    qemu_loglevel = log_flags;

    if (qemu_loglevel && !qemu_logfile) {

        qemu_logfile = fopen(logfilename, log_append ? "a" : "w");

        if (!qemu_logfile) {

            perror(logfilename);

            _exit(1);

        }

        /* must avoid mmap() usage of glibc by setting a buffer "by hand" */

        if (use_own_buffers) {

            static char logfile_buf[4096];

            setvbuf(qemu_logfile, logfile_buf, _IOLBF, sizeof(logfile_buf));

        } else {

#if defined(_WIN32)

            /* Win32 doesn't support line-buffering, so use unbuffered output. */

            setvbuf(qemu_logfile, NULL, _IONBF, 0);

#else

            setvbuf(qemu_logfile, NULL, _IOLBF, 0);

#endif

            log_append = 1;

        }

    }

    if (!qemu_loglevel && qemu_logfile) {

        fclose(qemu_logfile);

        qemu_logfile = NULL;

    }

}


static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    const uint32_t ddts_size = 20;

    AVStream *st = NULL;

    uint8_t *buf = NULL;

    uint32_t frame_duration_code = 0;

    uint32_t channel_layout_code = 0;

    GetBitContext gb;

    buf = av_malloc(ddts_size + AV_INPUT_BUFFER_PADDING_SIZE);

    if (!buf) {

        return AVERROR(ENOMEM);

    }

    if (avio_read(pb, buf, ddts_size) < ddts_size) {

        return AVERROR_INVALIDDATA;

    }

    init_get_bits(&gb, buf, 8*ddts_size);

    if (c->fc->nb_streams < 1) {

        return 0;

    }

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

    st->codecpar->sample_rate = get_bits_long(&gb, 32);

    if (st->codecpar->sample_rate <= 0) {

        av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);

        return AVERROR_INVALIDDATA;

    }

    skip_bits_long(&gb, 32); /* max bitrate */

    st->codecpar->bit_rate = get_bits_long(&gb, 32);

    st->codecpar->bits_per_coded_sample = get_bits(&gb, 8);

    frame_duration_code = get_bits(&gb, 2);

    skip_bits(&gb, 30); /* various fields */

    channel_layout_code = get_bits(&gb, 16);

    st->codecpar->frame_size =

            (frame_duration_code == 0) ? 512 :

            (frame_duration_code == 1) ? 1024 :

            (frame_duration_code == 2) ? 2048 :

            (frame_duration_code == 3) ? 4096 : 0;

    if (channel_layout_code > 0xff) {

        av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");

    }

    st->codecpar->channel_layout =

            ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |

            ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |

            ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |

            ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |

            ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |

            ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);

    st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);

    return 0;

}


void OPPROTO op_check_subfo_64 (void)

{

    if (likely(!(((uint64_t)(~T2) ^ (uint64_t)T1 ^ UINT64_MAX) &

                 ((uint64_t)(~T2) ^ (uint64_t)T0) & (1ULL << 63)))) {

        xer_ov = 0;

    } else {

        xer_ov = 1;

        xer_so = 1;

    }

    RETURN();

}


void pci_data_write(PCIBus *s, uint32_t addr, uint32_t val, int len)

{

    PCIDevice *pci_dev = pci_dev_find_by_addr(s, addr);

    uint32_t config_addr = addr & (PCI_CONFIG_SPACE_SIZE - 1);

    if (!pci_dev)

        return;

    PCI_DPRINTF("%s: %s: addr=%02" PRIx32 " val=%08" PRIx32 " len=%d\n",

                __func__, pci_dev->name, config_addr, val, len);

    pci_dev->config_write(pci_dev, config_addr, val, len);

}


static int mkv_write_tags(AVFormatContext *s)

{

    ebml_master tags = {0};

    int i, ret;

    ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);

    if (av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX)) {

        ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);

        if (ret < 0) return ret;

    }

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

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

        if (!av_dict_get(st->metadata, "", 0, AV_DICT_IGNORE_SUFFIX))

            continue;

        ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);

        if (ret < 0) return ret;

    }

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

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

        if (!av_dict_get(ch->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))

            continue;

        ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);

        if (ret < 0) return ret;

    }

    if (tags.pos)

        end_ebml_master(s->pb, tags);

    return 0;

}


static av_always_inline void mc_chroma_dir(VP9Context *s, vp9_mc_func(*mc)[2],

                                           uint8_t *dst_u, uint8_t *dst_v,

                                           ptrdiff_t dst_stride,

                                           const uint8_t *ref_u,

                                           ptrdiff_t src_stride_u,

                                           const uint8_t *ref_v,

                                           ptrdiff_t src_stride_v,

                                           ThreadFrame *ref_frame,

                                           ptrdiff_t y, ptrdiff_t x,

                                           const VP56mv *mv,

                                           int bw, int bh, int w, int h)

{

    int mx = mv->x, my = mv->y;

    int th;

    y     += my >> 4;

    x     += mx >> 4;

    ref_u += y * src_stride_u + x;

    ref_v += y * src_stride_v + x;

    mx    &= 15;

    my    &= 15;

    // we use +7 because the last 7 pixels of each sbrow can be changed in

    // the longest loopfilter of the next sbrow

    th = (y + bh + 4 * !!my + 7) >> 5;

    ff_thread_await_progress(ref_frame, FFMAX(th, 0), 0);

    // FIXME bilinear filter only needs 0/1 pixels, not 3/4

    if (x < !!mx * 3 || y < !!my * 3 ||

        x + !!mx * 4 > w - bw || y + !!my * 4 > h - bh) {

        s->vdsp.emulated_edge_mc(s->edge_emu_buffer,

                                 ref_u - !!my * 3 * src_stride_u - !!mx * 3,

                                 80,

                                 src_stride_u,

                                 bw + !!mx * 7, bh + !!my * 7,

                                 x - !!mx * 3, y - !!my * 3, w, h);

        ref_u = s->edge_emu_buffer + !!my * 3 * 80 + !!mx * 3;

        mc[!!mx][!!my](dst_u, dst_stride, ref_u, 80, bh, mx, my);

        s->vdsp.emulated_edge_mc(s->edge_emu_buffer,

                                 ref_v - !!my * 3 * src_stride_v - !!mx * 3,

                                 80,

                                 src_stride_v,

                                 bw + !!mx * 7, bh + !!my * 7,

                                 x - !!mx * 3, y - !!my * 3, w, h);

        ref_v = s->edge_emu_buffer + !!my * 3 * 80 + !!mx * 3;

        mc[!!mx][!!my](dst_v, dst_stride, ref_v, 80, bh, mx, my);

    } else {

        mc[!!mx][!!my](dst_u, dst_stride, ref_u, src_stride_u, bh, mx, my);

        mc[!!mx][!!my](dst_v, dst_stride, ref_v, src_stride_v, bh, mx, my);

    }

}


void qmp_drive_mirror(DriveMirror *arg, Error **errp)

{

    BlockDriverState *bs;

    BlockDriverState *source, *target_bs;

    AioContext *aio_context;

    BlockMirrorBackingMode backing_mode;

    Error *local_err = NULL;

    QDict *options = NULL;

    int flags;

    int64_t size;

    const char *format = arg->format;

    bs = qmp_get_root_bs(arg->device, errp);

    if (!bs) {

        return;

    }

    aio_context = bdrv_get_aio_context(bs);

    aio_context_acquire(aio_context);

    if (!arg->has_mode) {

        arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;

    }

    if (!arg->has_format) {

        format = (arg->mode == NEW_IMAGE_MODE_EXISTING

                  ? NULL : bs->drv->format_name);

    }

    flags = bs->open_flags | BDRV_O_RDWR;

    source = backing_bs(bs);

    if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {

        arg->sync = MIRROR_SYNC_MODE_FULL;

    }

    if (arg->sync == MIRROR_SYNC_MODE_NONE) {

        source = bs;

    }

    size = bdrv_getlength(bs);

    if (size < 0) {

        error_setg_errno(errp, -size, "bdrv_getlength failed");

        goto out;

    }

    if (arg->has_replaces) {

        BlockDriverState *to_replace_bs;

        AioContext *replace_aio_context;

        int64_t replace_size;

        if (!arg->has_node_name) {

            error_setg(errp, "a node-name must be provided when replacing a"

                             " named node of the graph");

            goto out;

        }

        to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);

        if (!to_replace_bs) {

            error_propagate(errp, local_err);

            goto out;

        }

        replace_aio_context = bdrv_get_aio_context(to_replace_bs);

        aio_context_acquire(replace_aio_context);

        replace_size = bdrv_getlength(to_replace_bs);

        aio_context_release(replace_aio_context);

        if (size != replace_size) {

            error_setg(errp, "cannot replace image with a mirror image of "

                             "different size");

            goto out;

        }

    }

    if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {

        backing_mode = MIRROR_SOURCE_BACKING_CHAIN;

    } else {

        backing_mode = MIRROR_OPEN_BACKING_CHAIN;

    }

    if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)

        && arg->mode != NEW_IMAGE_MODE_EXISTING)

    {

        /* create new image w/o backing file */

        assert(format);

        bdrv_img_create(arg->target, format,

                        NULL, NULL, NULL, size, flags, false, &local_err);

    } else {

        switch (arg->mode) {

        case NEW_IMAGE_MODE_EXISTING:

            break;

        case NEW_IMAGE_MODE_ABSOLUTE_PATHS:

            /* create new image with backing file */

            bdrv_img_create(arg->target, format,

                            source->filename,

                            source->drv->format_name,

                            NULL, size, flags, false, &local_err);

            break;

        default:

            abort();

        }

    }

    if (local_err) {

        error_propagate(errp, local_err);

        goto out;

    }

    options = qdict_new();

    if (arg->has_node_name) {

        qdict_put_str(options, "node-name", arg->node_name);

    }

    if (format) {

        qdict_put_str(options, "driver", format);

    }

    /* Mirroring takes care of copy-on-write using the source's backing

     * file.

     */

    target_bs = bdrv_open(arg->target, NULL, options,

                          flags | BDRV_O_NO_BACKING, errp);

    if (!target_bs) {

        goto out;

    }

    bdrv_set_aio_context(target_bs, aio_context);

    blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,

                           arg->has_replaces, arg->replaces, arg->sync,

                           backing_mode, arg->has_speed, arg->speed,

                           arg->has_granularity, arg->granularity,

                           arg->has_buf_size, arg->buf_size,

                           arg->has_on_source_error, arg->on_source_error,

                           arg->has_on_target_error, arg->on_target_error,

                           arg->has_unmap, arg->unmap,

                           false, NULL,

                           &local_err);

    bdrv_unref(target_bs);

    error_propagate(errp, local_err);

out:

    aio_context_release(aio_context);

}


void ff_thread_report_progress(ThreadFrame *f, int n, int field)

{

    PerThreadContext *p;

    atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;

    if (!progress ||

        atomic_load_explicit(&progress[field], memory_order_relaxed) >= n)

        return;

    p = f->owner[field]->internal->thread_ctx;

    if (f->owner[field]->debug&FF_DEBUG_THREADS)

        av_log(f->owner[field], AV_LOG_DEBUG,

               "%p finished %d field %d\n", progress, n, field);

    pthread_mutex_lock(&p->progress_mutex);

    atomic_store_explicit(&progress[field], n, memory_order_release);

    pthread_cond_broadcast(&p->progress_cond);

    pthread_mutex_unlock(&p->progress_mutex);

}


static inline int64_t bs_get_v(const uint8_t **bs)

{

    int64_t v = 0;

    int br = 0;

    int c;

    do {

        c = **bs; (*bs)++;

        v <<= 7;

        v |= c & 0x7F;

        br++;

        if (br > 10)

            return -1;

    } while (c & 0x80);

    return v - br;

}


static int nbd_receive_request(int csock, struct nbd_request *request)

{

    uint8_t buf[4 + 4 + 8 + 8 + 4];

    uint32_t magic;

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

        LOG("read failed");

        errno = EINVAL;

        return -1;

    }

    /* Request

       [ 0 ..  3]   magic   (NBD_REQUEST_MAGIC)

       [ 4 ..  7]   type    (0 == READ, 1 == WRITE)

       [ 8 .. 15]   handle

       [16 .. 23]   from

       [24 .. 27]   len

     */

    magic = be32_to_cpup((uint32_t*)buf);

    request->type  = be32_to_cpup((uint32_t*)(buf + 4));

    request->handle = be64_to_cpup((uint64_t*)(buf + 8));

    request->from  = be64_to_cpup((uint64_t*)(buf + 16));

    request->len   = be32_to_cpup((uint32_t*)(buf + 24));

    TRACE("Got request: "

          "{ magic = 0x%x, .type = %d, from = %" PRIu64" , len = %u }",

          magic, request->type, request->from, request->len);

    if (magic != NBD_REQUEST_MAGIC) {

        LOG("invalid magic (got 0x%x)", magic);

        errno = EINVAL;

        return -1;

    }

    return 0;

}


static int vp6_parse_header(VP56Context *s, const uint8_t *buf, int buf_size)

{

    VP56RangeCoder *c = &s->c;

    int parse_filter_info = 0;

    int coeff_offset = 0;

    int vrt_shift = 0;

    int sub_version;

    int rows, cols;

    int res = 0;

    int ret;

    int separated_coeff = buf[0] & 1;

    s->frames[VP56_FRAME_CURRENT]->key_frame = !(buf[0] & 0x80);

    ff_vp56_init_dequant(s, (buf[0] >> 1) & 0x3F);

    if (s->frames[VP56_FRAME_CURRENT]->key_frame) {

        sub_version = buf[1] >> 3;

        if (sub_version > 8)

            return AVERROR_INVALIDDATA;

        s->filter_header = buf[1] & 0x06;

        if (buf[1] & 1) {

            avpriv_report_missing_feature(s->avctx, "Interlacing");

            return AVERROR_PATCHWELCOME;

        }

        if (separated_coeff || !s->filter_header) {

            coeff_offset = AV_RB16(buf+2) - 2;

            buf += 2;

            buf_size -= 2;

        }

        rows = buf[2];  /* number of stored macroblock rows */

        cols = buf[3];  /* number of stored macroblock cols */

        /* buf[4] is number of displayed macroblock rows */

        /* buf[5] is number of displayed macroblock cols */

        if (!rows || !cols) {

            av_log(s->avctx, AV_LOG_ERROR, "Invalid size %dx%d\n", cols << 4, rows << 4);

            return AVERROR_INVALIDDATA;

        }

        if (!s->macroblocks || /* first frame */

            16*cols != s->avctx->coded_width ||

            16*rows != s->avctx->coded_height) {

            if (s->avctx->extradata_size == 0 &&

                FFALIGN(s->avctx->width,  16) == 16 * cols &&

                FFALIGN(s->avctx->height, 16) == 16 * rows) {

                // We assume this is properly signalled container cropping,

                // in an F4V file. Just set the coded_width/height, don't

                // touch the cropped ones.

                s->avctx->coded_width  = 16 * cols;

                s->avctx->coded_height = 16 * rows;

            } else {

                ret = ff_set_dimensions(s->avctx, 16 * cols, 16 * rows);

                if (ret < 0)

                    return ret;

                if (s->avctx->extradata_size == 1) {

                    s->avctx->width  -= s->avctx->extradata[0] >> 4;

                    s->avctx->height -= s->avctx->extradata[0] & 0x0F;

                }

            }

            res = VP56_SIZE_CHANGE;

        }

        ret = ff_vp56_init_range_decoder(c, buf+6, buf_size-6);

        if (ret < 0)

            return ret;

        vp56_rac_gets(c, 2);

        parse_filter_info = s->filter_header;

        if (sub_version < 8)

            vrt_shift = 5;

        s->sub_version = sub_version;

        s->golden_frame = 0;

    } else {

        if (!s->sub_version || !s->avctx->coded_width || !s->avctx->coded_height)

            return AVERROR_INVALIDDATA;

        if (separated_coeff || !s->filter_header) {

            coeff_offset = AV_RB16(buf+1) - 2;

            buf += 2;

            buf_size -= 2;

        }

        ret = ff_vp56_init_range_decoder(c, buf+1, buf_size-1);

        if (ret < 0)

            return ret;

        s->golden_frame = vp56_rac_get(c);

        if (s->filter_header) {

            s->deblock_filtering = vp56_rac_get(c);

            if (s->deblock_filtering)

                vp56_rac_get(c);

            if (s->sub_version > 7)

                parse_filter_info = vp56_rac_get(c);

        }

    }

    if (parse_filter_info) {

        if (vp56_rac_get(c)) {

            s->filter_mode = 2;

            s->sample_variance_threshold = vp56_rac_gets(c, 5) << vrt_shift;

            s->max_vector_length = 2 << vp56_rac_gets(c, 3);

        } else if (vp56_rac_get(c)) {

            s->filter_mode = 1;

        } else {

            s->filter_mode = 0;

        }

        if (s->sub_version > 7)

            s->filter_selection = vp56_rac_gets(c, 4);

        else

            s->filter_selection = 16;

    }

    s->use_huffman = vp56_rac_get(c);

    s->parse_coeff = vp6_parse_coeff;

    if (coeff_offset) {

        buf      += coeff_offset;

        buf_size -= coeff_offset;

        if (buf_size < 0) {

            if (s->frames[VP56_FRAME_CURRENT]->key_frame)

                ff_set_dimensions(s->avctx, 0, 0);

            return AVERROR_INVALIDDATA;

        }

        if (s->use_huffman) {

            s->parse_coeff = vp6_parse_coeff_huffman;

            init_get_bits(&s->gb, buf, buf_size<<3);

        } else {

            ret = ff_vp56_init_range_decoder(&s->cc, buf, buf_size);

            if (ret < 0)

                return ret;

            s->ccp = &s->cc;

        }

    } else {

        s->ccp = &s->c;

    }

    return res;

}


static void find_best_state(uint8_t best_state[256][256],

                            const uint8_t one_state[256])

{

    int i, j, k, m;

    double l2tab[256];

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

        l2tab[i] = log2(i / 256.0);

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

        double best_len[256];

        double p = i / 256.0;

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

            best_len[j] = 1 << 30;

        for (j = FFMAX(i - 10, 1); j < FFMIN(i + 11, 256); j++) {

            double occ[256] = { 0 };

            double len      = 0;

            occ[j] = 1.0;

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

                double newocc[256] = { 0 };

                for (m = 1; m < 256; m++)

                    if (occ[m]) {

                        len -= occ[m] *     (p  * l2tab[m] +

                                        (1 - p) * l2tab[256 - m]);

                    }

                if (len < best_len[k]) {

                    best_len[k]      = len;

                    best_state[i][k] = j;

                }

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

                    if (occ[m]) {

                        newocc[one_state[m]]             += occ[m] * p;

                        newocc[256 - one_state[256 - m]] += occ[m] * (1 - p);

                    }

                memcpy(occ, newocc, sizeof(occ));

            }

        }

    }

}


static ExitStatus gen_bcond(DisasContext *ctx, TCGCond cond, int ra,

                            int32_t disp, int mask)

{

    TCGv cmp_tmp;

    if (mask) {

        cmp_tmp = tcg_temp_new();

        tcg_gen_andi_i64(cmp_tmp, load_gpr(ctx, ra), 1);

    } else {

        cmp_tmp = load_gpr(ctx, ra);

    }

    return gen_bcond_internal(ctx, cond, cmp_tmp, disp);

}


static void tcg_out_qemu_st (TCGContext *s, const TCGArg *args, int opc)

{

    int addr_reg, r0, r1, data_reg, data_reg2, bswap, rbase;

#ifdef CONFIG_SOFTMMU

    int mem_index, r2, addr_reg2;

    uint8_t *label_ptr;

#endif

    data_reg = *args++;

    if (opc == 3)

        data_reg2 = *args++;

    else

        data_reg2 = 0;

    addr_reg = *args++;

#ifdef CONFIG_SOFTMMU

#if TARGET_LONG_BITS == 64

    addr_reg2 = *args++;

#else

    addr_reg2 = 0;

#endif

    mem_index = *args;

    r0 = 3;

    r1 = 4;

    r2 = 0;

    rbase = 0;

    tcg_out_tlb_check (

        s, r0, r1, r2, addr_reg, addr_reg2, opc & 3,

        offsetof (CPUArchState, tlb_table[mem_index][0].addr_write),

        offsetof (CPUTLBEntry, addend) - offsetof (CPUTLBEntry, addr_write),

        &label_ptr

        );

#else  /* !CONFIG_SOFTMMU */

    r0 = addr_reg;

    r1 = 3;

    rbase = GUEST_BASE ? TCG_GUEST_BASE_REG : 0;

#endif

#ifdef TARGET_WORDS_BIGENDIAN

    bswap = 0;

#else

    bswap = 1;

#endif

    switch (opc) {

    case 0:

        tcg_out32 (s, STBX | SAB (data_reg, rbase, r0));

        break;

    case 1:

        if (bswap)

            tcg_out32 (s, STHBRX | SAB (data_reg, rbase, r0));

        else

            tcg_out32 (s, STHX | SAB (data_reg, rbase, r0));

        break;

    case 2:

        if (bswap)

            tcg_out32 (s, STWBRX | SAB (data_reg, rbase, r0));

        else

            tcg_out32 (s, STWX | SAB (data_reg, rbase, r0));

        break;

    case 3:

        if (bswap) {

            tcg_out32 (s, ADDI | RT (r1) | RA (r0) | 4);

            tcg_out32 (s, STWBRX | SAB (data_reg,  rbase, r0));

            tcg_out32 (s, STWBRX | SAB (data_reg2, rbase, r1));

        }

        else {

#ifdef CONFIG_USE_GUEST_BASE

            tcg_out32 (s, STWX | SAB (data_reg2, rbase, r0));

            tcg_out32 (s, ADDI | RT (r1) | RA (r0) | 4);

            tcg_out32 (s, STWX | SAB (data_reg,  rbase, r1));

#else

            tcg_out32 (s, STW | RS (data_reg2) | RA (r0));

            tcg_out32 (s, STW | RS (data_reg) | RA (r0) | 4);

#endif

        }

        break;

    }

#ifdef CONFIG_SOFTMMU

    add_qemu_ldst_label (s,

                         0,

                         opc,

                         data_reg,

                         data_reg2,

                         addr_reg,

                         addr_reg2,

                         mem_index,

                         s->code_ptr,

                         label_ptr);

#endif

}


int qemu_opts_foreach(QemuOptsList *list, qemu_opts_loopfunc func, void *opaque,

                      int abort_on_failure)

{

    QemuOpts *opts;

    int rc = 0;

    QTAILQ_FOREACH(opts, &list->head, next) {

        rc = func(opts, opaque);

        if (abort_on_failure  &&  rc != 0)

            break;

    }

    return rc;

}


static void gen_tlbsx_booke206(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    TCGv t0;

    if (unlikely(!ctx->mem_idx)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    if (rA(ctx->opcode)) {

        t0 = tcg_temp_new();

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

    } else {

        t0 = tcg_const_tl(0);

    }

    tcg_gen_add_tl(t0, t0, cpu_gpr[rB(ctx->opcode)]);

    gen_helper_booke206_tlbsx(cpu_env, t0);

#endif

}


static inline int parse_nal_units(AVCodecParserContext *s, const uint8_t *buf,
                           int buf_size, AVCodecContext *avctx)
{
    HEVCParserContext *ctx = s->priv_data;
    HEVCContext       *h   = &ctx->h;
    GetBitContext      *gb;
    SliceHeader        *sh = &h->sh;
    HEVCParamSets *ps = &h->ps;
    H2645Packet   *pkt = &ctx->pkt;
    const uint8_t *buf_end = buf + buf_size;
    int state = -1, i;
    H2645NAL *nal;
    int is_global = buf == avctx->extradata;
    if (!h->HEVClc)
        h->HEVClc = av_mallocz(sizeof(HEVCLocalContext));
    if (!h->HEVClc)
        return AVERROR(ENOMEM);
    gb = &h->HEVClc->gb;
    /* set some sane default values */
    s->pict_type         = AV_PICTURE_TYPE_I;
    s->key_frame         = 0;
    s->picture_structure = AV_PICTURE_STRUCTURE_UNKNOWN;
    h->avctx = avctx;
    if (!buf_size)
        return 0;
    if (pkt->nals_allocated < 1) {
        H2645NAL *tmp = av_realloc_array(pkt->nals, 1, sizeof(*tmp));
        if (!tmp)
            return AVERROR(ENOMEM);
        pkt->nals = tmp;
        memset(pkt->nals, 0, sizeof(*tmp));
        pkt->nals_allocated = 1;
    }
    nal = &pkt->nals[0];
    for (;;) {
        int src_length, consumed;
        int ret;
        buf = avpriv_find_start_code(buf, buf_end, &state);
        if (--buf + 2 >= buf_end)
            break;
        src_length = buf_end - buf;
        h->nal_unit_type = (*buf >> 1) & 0x3f;
        h->temporal_id   = (*(buf + 1) & 0x07) - 1;
        if (h->nal_unit_type <= NAL_CRA_NUT) {
            // Do not walk the whole buffer just to decode slice segment header
            if (src_length > 20)
                src_length = 20;
        }
        consumed = ff_h2645_extract_rbsp(buf, src_length, nal);
        if (consumed < 0)
            return consumed;
        ret = init_get_bits8(gb, nal->data + 2, nal->size);
        if (ret < 0)
            return ret;
        switch (h->nal_unit_type) {
        case NAL_VPS:
            ff_hevc_decode_nal_vps(gb, avctx, ps);
            break;
        case NAL_SPS:
            ff_hevc_decode_nal_sps(gb, avctx, ps, 1);
            break;
        case NAL_PPS:
            ff_hevc_decode_nal_pps(gb, avctx, ps);
            break;
        case NAL_SEI_PREFIX:
        case NAL_SEI_SUFFIX:
            ff_hevc_decode_nal_sei(h);
            break;
        case NAL_TRAIL_N:
        case NAL_TRAIL_R:
        case NAL_TSA_N:
        case NAL_TSA_R:
        case NAL_STSA_N:
        case NAL_STSA_R:
        case NAL_RADL_N:
        case NAL_RADL_R:
        case NAL_RASL_N:
        case NAL_RASL_R:
        case NAL_BLA_W_LP:
        case NAL_BLA_W_RADL:
        case NAL_BLA_N_LP:
        case NAL_IDR_W_RADL:
        case NAL_IDR_N_LP:
        case NAL_CRA_NUT:
            if (is_global) {
                av_log(avctx, AV_LOG_ERROR, "Invalid NAL unit: %d\n", h->nal_unit_type);
                return AVERROR_INVALIDDATA;
            }
            sh->first_slice_in_pic_flag = get_bits1(gb);
            s->picture_structure = h->picture_struct;
            s->field_order = h->picture_struct;
            if (IS_IRAP(h)) {
                s->key_frame = 1;
                sh->no_output_of_prior_pics_flag = get_bits1(gb);
            }
            sh->pps_id = get_ue_golomb(gb);
            if (sh->pps_id >= MAX_PPS_COUNT || !ps->pps_list[sh->pps_id]) {
                av_log(avctx, AV_LOG_ERROR, "PPS id out of range: %d\n", sh->pps_id);
                return AVERROR_INVALIDDATA;
            }
            ps->pps = (HEVCPPS*)ps->pps_list[sh->pps_id]->data;
            if (ps->pps->sps_id >= MAX_SPS_COUNT || !ps->sps_list[ps->pps->sps_id]) {
                av_log(avctx, AV_LOG_ERROR, "SPS id out of range: %d\n", ps->pps->sps_id);
                return AVERROR_INVALIDDATA;
            }
            if (ps->sps != (HEVCSPS*)ps->sps_list[ps->pps->sps_id]->data) {
                ps->sps = (HEVCSPS*)ps->sps_list[ps->pps->sps_id]->data;
                ps->vps = (HEVCVPS*)ps->vps_list[ps->sps->vps_id]->data;
            }
            if (!sh->first_slice_in_pic_flag) {
                int slice_address_length;
                if (ps->pps->dependent_slice_segments_enabled_flag)
                    sh->dependent_slice_segment_flag = get_bits1(gb);
                else
                    sh->dependent_slice_segment_flag = 0;
                slice_address_length = av_ceil_log2_c(ps->sps->ctb_width *
                                                      ps->sps->ctb_height);
                sh->slice_segment_addr = get_bitsz(gb, slice_address_length);
                if (sh->slice_segment_addr >= ps->sps->ctb_width * ps->sps->ctb_height) {
                    av_log(avctx, AV_LOG_ERROR, "Invalid slice segment address: %u.\n",
                           sh->slice_segment_addr);
                    return AVERROR_INVALIDDATA;
                }
            } else
                sh->dependent_slice_segment_flag = 0;
            if (sh->dependent_slice_segment_flag)
                break;
            for (i = 0; i < ps->pps->num_extra_slice_header_bits; i++)
                skip_bits(gb, 1); // slice_reserved_undetermined_flag[]
            sh->slice_type = get_ue_golomb(gb);
            if (!(sh->slice_type == I_SLICE || sh->slice_type == P_SLICE ||
                  sh->slice_type == B_SLICE)) {
                av_log(avctx, AV_LOG_ERROR, "Unknown slice type: %d.\n",
                       sh->slice_type);
                return AVERROR_INVALIDDATA;
            }
            s->pict_type = sh->slice_type == B_SLICE ? AV_PICTURE_TYPE_B :
                           sh->slice_type == P_SLICE ? AV_PICTURE_TYPE_P :
                                                       AV_PICTURE_TYPE_I;
            if (ps->pps->output_flag_present_flag)
                sh->pic_output_flag = get_bits1(gb);
            if (ps->sps->separate_colour_plane_flag)
                sh->colour_plane_id = get_bits(gb, 2);
            if (!IS_IDR(h)) {
                sh->pic_order_cnt_lsb = get_bits(gb, ps->sps->log2_max_poc_lsb);
                s->output_picture_number = h->poc = ff_hevc_compute_poc(h, sh->pic_order_cnt_lsb);
            } else
                s->output_picture_number = h->poc = 0;
            if (h->temporal_id == 0 &&
                h->nal_unit_type != NAL_TRAIL_N &&
                h->nal_unit_type != NAL_TSA_N &&
                h->nal_unit_type != NAL_STSA_N &&
                h->nal_unit_type != NAL_RADL_N &&
                h->nal_unit_type != NAL_RASL_N &&
                h->nal_unit_type != NAL_RADL_R &&
                h->nal_unit_type != NAL_RASL_R)
                h->pocTid0 = h->poc;
            return 0; /* no need to evaluate the rest */
        }
        buf += consumed;
    }
    /* didn't find a picture! */
    if (!is_global)
        av_log(h->avctx, AV_LOG_ERROR, "missing picture in access unit\n");
    return -1;
}


static int afx_init1(SysBusDevice *dev)

{

    AFXState *s = TCX_AFX(dev);

    memory_region_init_ram(&s->mem, OBJECT(s), "sun4m.afx", 4, &error_abort);

    vmstate_register_ram_global(&s->mem);

    sysbus_init_mmio(dev, &s->mem);

    return 0;

}


static void avc_loopfilter_luma_intra_edge_hor_msa(uint8_t *data,

                                                   uint8_t alpha_in,

                                                   uint8_t beta_in,

                                                   uint32_t img_width)

{

    v16u8 p2_asub_p0, q2_asub_q0, p0_asub_q0;

    v16u8 alpha, beta;

    v16u8 is_less_than, is_less_than_beta, negate_is_less_than_beta;

    v16u8 p2, p1, p0, q0, q1, q2;

    v16u8 p3_org, p2_org, p1_org, p0_org, q0_org, q1_org, q2_org, q3_org;

    v8i16 p1_org_r, p0_org_r, q0_org_r, q1_org_r;

    v8i16 p1_org_l, p0_org_l, q0_org_l, q1_org_l;

    v8i16 p2_r = { 0 };

    v8i16 p1_r = { 0 };

    v8i16 p0_r = { 0 };

    v8i16 q0_r = { 0 };

    v8i16 q1_r = { 0 };

    v8i16 q2_r = { 0 };

    v8i16 p2_l = { 0 };

    v8i16 p1_l = { 0 };

    v8i16 p0_l = { 0 };

    v8i16 q0_l = { 0 };

    v8i16 q1_l = { 0 };

    v8i16 q2_l = { 0 };

    v16u8 tmp_flag;

    v16i8 zero = { 0 };

    alpha = (v16u8) __msa_fill_b(alpha_in);

    beta = (v16u8) __msa_fill_b(beta_in);

    p1_org = LOAD_UB(data - (img_width << 1));

    p0_org = LOAD_UB(data - img_width);

    q0_org = LOAD_UB(data);

    q1_org = LOAD_UB(data + img_width);

    {

        v16u8 p1_asub_p0, q1_asub_q0, is_less_than_alpha;

        p0_asub_q0 = __msa_asub_u_b(p0_org, q0_org);

        p1_asub_p0 = __msa_asub_u_b(p1_org, p0_org);

        q1_asub_q0 = __msa_asub_u_b(q1_org, q0_org);

        is_less_than_alpha = (p0_asub_q0 < alpha);

        is_less_than_beta = (p1_asub_p0 < beta);

        is_less_than = is_less_than_beta & is_less_than_alpha;

        is_less_than_beta = (q1_asub_q0 < beta);

        is_less_than = is_less_than_beta & is_less_than;

    }

    if (!__msa_test_bz_v(is_less_than)) {

        q2_org = LOAD_UB(data + (2 * img_width));

        p3_org = LOAD_UB(data - (img_width << 2));

        p2_org = LOAD_UB(data - (3 * img_width));

        p1_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) p1_org);

        p0_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) p0_org);

        q0_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) q0_org);

        p1_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) p1_org);

        p0_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) p0_org);

        q0_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) q0_org);

        tmp_flag = alpha >> 2;

        tmp_flag = tmp_flag + 2;

        tmp_flag = (p0_asub_q0 < tmp_flag);

        p2_asub_p0 = __msa_asub_u_b(p2_org, p0_org);

        is_less_than_beta = (p2_asub_p0 < beta);

        is_less_than_beta = is_less_than_beta & tmp_flag;

        negate_is_less_than_beta = __msa_xori_b(is_less_than_beta, 0xff);

        is_less_than_beta = is_less_than_beta & is_less_than;

        negate_is_less_than_beta = negate_is_less_than_beta & is_less_than;

        {

            v8u16 is_less_than_beta_l, is_less_than_beta_r;

            q1_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) q1_org);

            is_less_than_beta_r =

                (v8u16) __msa_sldi_b((v16i8) is_less_than_beta, zero, 8);

            if (!__msa_test_bz_v((v16u8) is_less_than_beta_r)) {

                v8i16 p3_org_r;

                p3_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) p3_org);

                p2_r = (v8i16) __msa_ilvr_b(zero, (v16i8) p2_org);

                AVC_LOOP_FILTER_P0P1P2_OR_Q0Q1Q2(p3_org_r, p0_org_r,

                                                 q0_org_r, p1_org_r,

                                                 p2_r, q1_org_r,

                                                 p0_r, p1_r, p2_r);

            }

            q1_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) q1_org);

            is_less_than_beta_l =

                (v8u16) __msa_sldi_b(zero, (v16i8) is_less_than_beta, 8);

            if (!__msa_test_bz_v((v16u8) is_less_than_beta_l)) {

                v8i16 p3_org_l;

                p3_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) p3_org);

                p2_l = (v8i16) __msa_ilvl_b(zero, (v16i8) p2_org);

                AVC_LOOP_FILTER_P0P1P2_OR_Q0Q1Q2(p3_org_l, p0_org_l,

                                                 q0_org_l, p1_org_l,

                                                 p2_l, q1_org_l,

                                                 p0_l, p1_l, p2_l);

            }

        }

        /* combine and store */

        if (!__msa_test_bz_v(is_less_than_beta)) {

            p0 = (v16u8) __msa_pckev_b((v16i8) p0_l, (v16i8) p0_r);

            p1 = (v16u8) __msa_pckev_b((v16i8) p1_l, (v16i8) p1_r);

            p2 = (v16u8) __msa_pckev_b((v16i8) p2_l, (v16i8) p2_r);

            p0_org = __msa_bmnz_v(p0_org, p0, is_less_than_beta);

            p1_org = __msa_bmnz_v(p1_org, p1, is_less_than_beta);

            p2_org = __msa_bmnz_v(p2_org, p2, is_less_than_beta);

            STORE_UB(p1_org, data - (2 * img_width));

            STORE_UB(p2_org, data - (3 * img_width));

        }

        {

            v8u16 negate_is_less_than_beta_r, negate_is_less_than_beta_l;

            negate_is_less_than_beta_r =

                (v8u16) __msa_sldi_b((v16i8) negate_is_less_than_beta, zero, 8);

            if (!__msa_test_bz_v((v16u8) negate_is_less_than_beta_r)) {

                AVC_LOOP_FILTER_P0_OR_Q0(p0_org_r, q1_org_r, p1_org_r, p0_r);

            }

            negate_is_less_than_beta_l =

                (v8u16) __msa_sldi_b(zero, (v16i8) negate_is_less_than_beta, 8);

            if (!__msa_test_bz_v((v16u8) negate_is_less_than_beta_l)) {

                AVC_LOOP_FILTER_P0_OR_Q0(p0_org_l, q1_org_l, p1_org_l, p0_l);

            }

        }

        /* combine */

        if (!__msa_test_bz_v(negate_is_less_than_beta)) {

            p0 = (v16u8) __msa_pckev_b((v16i8) p0_l, (v16i8) p0_r);

            p0_org = __msa_bmnz_v(p0_org, p0, negate_is_less_than_beta);

        }

        STORE_UB(p0_org, data - img_width);

        /* if (tmpFlag && (unsigned)ABS(q2-q0) < thresholds->beta_in) */

        q3_org = LOAD_UB(data + (3 * img_width));

        q2_asub_q0 = __msa_asub_u_b(q2_org, q0_org);

        is_less_than_beta = (q2_asub_q0 < beta);

        is_less_than_beta = is_less_than_beta & tmp_flag;

        negate_is_less_than_beta = __msa_xori_b(is_less_than_beta, 0xff);

        is_less_than_beta = is_less_than_beta & is_less_than;

        negate_is_less_than_beta = negate_is_less_than_beta & is_less_than;

        {

            v8u16 is_less_than_beta_l, is_less_than_beta_r;

            is_less_than_beta_r =

                (v8u16) __msa_sldi_b((v16i8) is_less_than_beta, zero, 8);

            if (!__msa_test_bz_v((v16u8) is_less_than_beta_r)) {

                v8i16 q3_org_r;

                q3_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) q3_org);

                q2_r = (v8i16) __msa_ilvr_b(zero, (v16i8) q2_org);

                AVC_LOOP_FILTER_P0P1P2_OR_Q0Q1Q2(q3_org_r, q0_org_r,

                                                 p0_org_r, q1_org_r,

                                                 q2_r, p1_org_r,

                                                 q0_r, q1_r, q2_r);

            }

            is_less_than_beta_l =

                (v8u16) __msa_sldi_b(zero, (v16i8) is_less_than_beta, 8);

            if (!__msa_test_bz_v((v16u8) is_less_than_beta_l)) {

                v8i16 q3_org_l;

                q3_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) q3_org);

                q2_l = (v8i16) __msa_ilvl_b(zero, (v16i8) q2_org);

                AVC_LOOP_FILTER_P0P1P2_OR_Q0Q1Q2(q3_org_l, q0_org_l,

                                                 p0_org_l, q1_org_l,

                                                 q2_l, p1_org_l,

                                                 q0_l, q1_l, q2_l);

            }

        }

        /* combine and store */

        if (!__msa_test_bz_v(is_less_than_beta)) {

            q0 = (v16u8) __msa_pckev_b((v16i8) q0_l, (v16i8) q0_r);

            q1 = (v16u8) __msa_pckev_b((v16i8) q1_l, (v16i8) q1_r);

            q2 = (v16u8) __msa_pckev_b((v16i8) q2_l, (v16i8) q2_r);

            q0_org = __msa_bmnz_v(q0_org, q0, is_less_than_beta);

            q1_org = __msa_bmnz_v(q1_org, q1, is_less_than_beta);

            q2_org = __msa_bmnz_v(q2_org, q2, is_less_than_beta);

            STORE_UB(q1_org, data + img_width);

            STORE_UB(q2_org, data + 2 * img_width);

        }

        {

            v8u16 negate_is_less_than_beta_r, negate_is_less_than_beta_l;

            negate_is_less_than_beta_r =

                (v8u16) __msa_sldi_b((v16i8) negate_is_less_than_beta, zero, 8);

            if (!__msa_test_bz_v((v16u8) negate_is_less_than_beta_r)) {

                AVC_LOOP_FILTER_P0_OR_Q0(q0_org_r, p1_org_r, q1_org_r, q0_r);

            }

            negate_is_less_than_beta_l =

                (v8u16) __msa_sldi_b(zero, (v16i8) negate_is_less_than_beta, 8);

            if (!__msa_test_bz_v((v16u8) negate_is_less_than_beta_l)) {

                AVC_LOOP_FILTER_P0_OR_Q0(q0_org_l, p1_org_l, q1_org_l, q0_l);

            }

        }

        /* combine */

        if (!__msa_test_bz_v(negate_is_less_than_beta)) {

            q0 = (v16u8) __msa_pckev_b((v16i8) q0_l, (v16i8) q0_r);

            q0_org = __msa_bmnz_v(q0_org, q0, negate_is_less_than_beta);

        }

        STORE_UB(q0_org, data);

    }

}


struct omap_mpu_state_s *omap2420_mpu_init(MemoryRegion *sysmem,

                unsigned long sdram_size,

                const char *core)

{

    struct omap_mpu_state_s *s = (struct omap_mpu_state_s *)

            g_malloc0(sizeof(struct omap_mpu_state_s));

    qemu_irq dma_irqs[4];

    DriveInfo *dinfo;

    int i;

    SysBusDevice *busdev;

    struct omap_target_agent_s *ta;

    /* Core */

    s->mpu_model = omap2420;

    s->cpu = cpu_arm_init(core ?: "arm1136-r2");

    if (s->cpu == NULL) {

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

        exit(1);

    }

    s->sdram_size = sdram_size;

    s->sram_size = OMAP242X_SRAM_SIZE;

    s->wakeup = qemu_allocate_irq(omap_mpu_wakeup, s, 0);

    /* Clocks */

    omap_clk_init(s);

    /* Memory-mapped stuff */

    memory_region_init_ram(&s->sdram, NULL, "omap2.dram", s->sdram_size,

                           &error_abort);

    vmstate_register_ram_global(&s->sdram);

    memory_region_add_subregion(sysmem, OMAP2_Q2_BASE, &s->sdram);

    memory_region_init_ram(&s->sram, NULL, "omap2.sram", s->sram_size,

                           &error_abort);

    vmstate_register_ram_global(&s->sram);

    memory_region_add_subregion(sysmem, OMAP2_SRAM_BASE, &s->sram);

    s->l4 = omap_l4_init(sysmem, OMAP2_L4_BASE, 54);

    /* Actually mapped at any 2K boundary in the ARM11 private-peripheral if */

    s->ih[0] = qdev_create(NULL, "omap2-intc");

    qdev_prop_set_uint8(s->ih[0], "revision", 0x21);

    qdev_prop_set_ptr(s->ih[0], "fclk", omap_findclk(s, "mpu_intc_fclk"));

    qdev_prop_set_ptr(s->ih[0], "iclk", omap_findclk(s, "mpu_intc_iclk"));

    qdev_init_nofail(s->ih[0]);

    busdev = SYS_BUS_DEVICE(s->ih[0]);

    sysbus_connect_irq(busdev, 0,

                       qdev_get_gpio_in(DEVICE(s->cpu), ARM_CPU_IRQ));

    sysbus_connect_irq(busdev, 1,

                       qdev_get_gpio_in(DEVICE(s->cpu), ARM_CPU_FIQ));

    sysbus_mmio_map(busdev, 0, 0x480fe000);

    s->prcm = omap_prcm_init(omap_l4tao(s->l4, 3),

                             qdev_get_gpio_in(s->ih[0],

                                              OMAP_INT_24XX_PRCM_MPU_IRQ),

                             NULL, NULL, s);

    s->sysc = omap_sysctl_init(omap_l4tao(s->l4, 1),

                    omap_findclk(s, "omapctrl_iclk"), s);

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

        dma_irqs[i] = qdev_get_gpio_in(s->ih[omap2_dma_irq_map[i].ih],

                                       omap2_dma_irq_map[i].intr);

    }

    s->dma = omap_dma4_init(0x48056000, dma_irqs, sysmem, s, 256, 32,

                    omap_findclk(s, "sdma_iclk"),

                    omap_findclk(s, "sdma_fclk"));

    s->port->addr_valid = omap2_validate_addr;

    /* Register SDRAM and SRAM ports for fast DMA transfers.  */

    soc_dma_port_add_mem(s->dma, memory_region_get_ram_ptr(&s->sdram),

                         OMAP2_Q2_BASE, s->sdram_size);

    soc_dma_port_add_mem(s->dma, memory_region_get_ram_ptr(&s->sram),

                         OMAP2_SRAM_BASE, s->sram_size);

    s->uart[0] = omap2_uart_init(sysmem, omap_l4ta(s->l4, 19),

                                 qdev_get_gpio_in(s->ih[0],

                                                  OMAP_INT_24XX_UART1_IRQ),

                    omap_findclk(s, "uart1_fclk"),

                    omap_findclk(s, "uart1_iclk"),

                    s->drq[OMAP24XX_DMA_UART1_TX],

                    s->drq[OMAP24XX_DMA_UART1_RX],

                    "uart1",

                    serial_hds[0]);

    s->uart[1] = omap2_uart_init(sysmem, omap_l4ta(s->l4, 20),

                                 qdev_get_gpio_in(s->ih[0],

                                                  OMAP_INT_24XX_UART2_IRQ),

                    omap_findclk(s, "uart2_fclk"),

                    omap_findclk(s, "uart2_iclk"),

                    s->drq[OMAP24XX_DMA_UART2_TX],

                    s->drq[OMAP24XX_DMA_UART2_RX],

                    "uart2",

                    serial_hds[0] ? serial_hds[1] : NULL);

    s->uart[2] = omap2_uart_init(sysmem, omap_l4ta(s->l4, 21),

                                 qdev_get_gpio_in(s->ih[0],

                                                  OMAP_INT_24XX_UART3_IRQ),

                    omap_findclk(s, "uart3_fclk"),

                    omap_findclk(s, "uart3_iclk"),

                    s->drq[OMAP24XX_DMA_UART3_TX],

                    s->drq[OMAP24XX_DMA_UART3_RX],

                    "uart3",

                    serial_hds[0] && serial_hds[1] ? serial_hds[2] : NULL);

    s->gptimer[0] = omap_gp_timer_init(omap_l4ta(s->l4, 7),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER1),

                    omap_findclk(s, "wu_gpt1_clk"),

                    omap_findclk(s, "wu_l4_iclk"));

    s->gptimer[1] = omap_gp_timer_init(omap_l4ta(s->l4, 8),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER2),

                    omap_findclk(s, "core_gpt2_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[2] = omap_gp_timer_init(omap_l4ta(s->l4, 22),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER3),

                    omap_findclk(s, "core_gpt3_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[3] = omap_gp_timer_init(omap_l4ta(s->l4, 23),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER4),

                    omap_findclk(s, "core_gpt4_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[4] = omap_gp_timer_init(omap_l4ta(s->l4, 24),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER5),

                    omap_findclk(s, "core_gpt5_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[5] = omap_gp_timer_init(omap_l4ta(s->l4, 25),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER6),

                    omap_findclk(s, "core_gpt6_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[6] = omap_gp_timer_init(omap_l4ta(s->l4, 26),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER7),

                    omap_findclk(s, "core_gpt7_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[7] = omap_gp_timer_init(omap_l4ta(s->l4, 27),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER8),

                    omap_findclk(s, "core_gpt8_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[8] = omap_gp_timer_init(omap_l4ta(s->l4, 28),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER9),

                    omap_findclk(s, "core_gpt9_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[9] = omap_gp_timer_init(omap_l4ta(s->l4, 29),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER10),

                    omap_findclk(s, "core_gpt10_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[10] = omap_gp_timer_init(omap_l4ta(s->l4, 30),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER11),

                    omap_findclk(s, "core_gpt11_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[11] = omap_gp_timer_init(omap_l4ta(s->l4, 31),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER12),

                    omap_findclk(s, "core_gpt12_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    omap_tap_init(omap_l4ta(s->l4, 2), s);

    s->synctimer = omap_synctimer_init(omap_l4tao(s->l4, 2), s,

                    omap_findclk(s, "clk32-kHz"),

                    omap_findclk(s, "core_l4_iclk"));

    s->i2c[0] = qdev_create(NULL, "omap_i2c");

    qdev_prop_set_uint8(s->i2c[0], "revision", 0x34);

    qdev_prop_set_ptr(s->i2c[0], "iclk", omap_findclk(s, "i2c1.iclk"));

    qdev_prop_set_ptr(s->i2c[0], "fclk", omap_findclk(s, "i2c1.fclk"));

    qdev_init_nofail(s->i2c[0]);

    busdev = SYS_BUS_DEVICE(s->i2c[0]);

    sysbus_connect_irq(busdev, 0,

                       qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_I2C1_IRQ));

    sysbus_connect_irq(busdev, 1, s->drq[OMAP24XX_DMA_I2C1_TX]);

    sysbus_connect_irq(busdev, 2, s->drq[OMAP24XX_DMA_I2C1_RX]);

    sysbus_mmio_map(busdev, 0, omap_l4_region_base(omap_l4tao(s->l4, 5), 0));

    s->i2c[1] = qdev_create(NULL, "omap_i2c");

    qdev_prop_set_uint8(s->i2c[1], "revision", 0x34);

    qdev_prop_set_ptr(s->i2c[1], "iclk", omap_findclk(s, "i2c2.iclk"));

    qdev_prop_set_ptr(s->i2c[1], "fclk", omap_findclk(s, "i2c2.fclk"));

    qdev_init_nofail(s->i2c[1]);

    busdev = SYS_BUS_DEVICE(s->i2c[1]);

    sysbus_connect_irq(busdev, 0,

                       qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_I2C2_IRQ));

    sysbus_connect_irq(busdev, 1, s->drq[OMAP24XX_DMA_I2C2_TX]);

    sysbus_connect_irq(busdev, 2, s->drq[OMAP24XX_DMA_I2C2_RX]);

    sysbus_mmio_map(busdev, 0, omap_l4_region_base(omap_l4tao(s->l4, 6), 0));

    s->gpio = qdev_create(NULL, "omap2-gpio");

    qdev_prop_set_int32(s->gpio, "mpu_model", s->mpu_model);

    qdev_prop_set_ptr(s->gpio, "iclk", omap_findclk(s, "gpio_iclk"));

    qdev_prop_set_ptr(s->gpio, "fclk0", omap_findclk(s, "gpio1_dbclk"));

    qdev_prop_set_ptr(s->gpio, "fclk1", omap_findclk(s, "gpio2_dbclk"));

    qdev_prop_set_ptr(s->gpio, "fclk2", omap_findclk(s, "gpio3_dbclk"));

    qdev_prop_set_ptr(s->gpio, "fclk3", omap_findclk(s, "gpio4_dbclk"));

    if (s->mpu_model == omap2430) {

        qdev_prop_set_ptr(s->gpio, "fclk4", omap_findclk(s, "gpio5_dbclk"));

    }

    qdev_init_nofail(s->gpio);

    busdev = SYS_BUS_DEVICE(s->gpio);

    sysbus_connect_irq(busdev, 0,

                       qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPIO_BANK1));

    sysbus_connect_irq(busdev, 3,

                       qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPIO_BANK2));

    sysbus_connect_irq(busdev, 6,

                       qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPIO_BANK3));

    sysbus_connect_irq(busdev, 9,

                       qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPIO_BANK4));

    if (s->mpu_model == omap2430) {

        sysbus_connect_irq(busdev, 12,

                           qdev_get_gpio_in(s->ih[0],

                                            OMAP_INT_243X_GPIO_BANK5));

    }

    ta = omap_l4ta(s->l4, 3);

    sysbus_mmio_map(busdev, 0, omap_l4_region_base(ta, 1));

    sysbus_mmio_map(busdev, 1, omap_l4_region_base(ta, 0));

    sysbus_mmio_map(busdev, 2, omap_l4_region_base(ta, 2));

    sysbus_mmio_map(busdev, 3, omap_l4_region_base(ta, 4));

    sysbus_mmio_map(busdev, 4, omap_l4_region_base(ta, 5));

    s->sdrc = omap_sdrc_init(sysmem, 0x68009000);

    s->gpmc = omap_gpmc_init(s, 0x6800a000,

                             qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPMC_IRQ),

                             s->drq[OMAP24XX_DMA_GPMC]);

    dinfo = drive_get(IF_SD, 0, 0);

    if (!dinfo) {

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

        exit(1);

    }

    s->mmc = omap2_mmc_init(omap_l4tao(s->l4, 9),

                    blk_bs(blk_by_legacy_dinfo(dinfo)),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_MMC_IRQ),

                    &s->drq[OMAP24XX_DMA_MMC1_TX],

                    omap_findclk(s, "mmc_fclk"), omap_findclk(s, "mmc_iclk"));

    s->mcspi[0] = omap_mcspi_init(omap_l4ta(s->l4, 35), 4,

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_MCSPI1_IRQ),

                    &s->drq[OMAP24XX_DMA_SPI1_TX0],

                    omap_findclk(s, "spi1_fclk"),

                    omap_findclk(s, "spi1_iclk"));

    s->mcspi[1] = omap_mcspi_init(omap_l4ta(s->l4, 36), 2,

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_MCSPI2_IRQ),

                    &s->drq[OMAP24XX_DMA_SPI2_TX0],

                    omap_findclk(s, "spi2_fclk"),

                    omap_findclk(s, "spi2_iclk"));

    s->dss = omap_dss_init(omap_l4ta(s->l4, 10), sysmem, 0x68000800,

                    /* XXX wire M_IRQ_25, D_L2_IRQ_30 and I_IRQ_13 together */

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_DSS_IRQ),

                           s->drq[OMAP24XX_DMA_DSS],

                    omap_findclk(s, "dss_clk1"), omap_findclk(s, "dss_clk2"),

                    omap_findclk(s, "dss_54m_clk"),

                    omap_findclk(s, "dss_l3_iclk"),

                    omap_findclk(s, "dss_l4_iclk"));

    omap_sti_init(omap_l4ta(s->l4, 18), sysmem, 0x54000000,

                  qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_STI),

                  omap_findclk(s, "emul_ck"),

                    serial_hds[0] && serial_hds[1] && serial_hds[2] ?

                    serial_hds[3] : NULL);

    s->eac = omap_eac_init(omap_l4ta(s->l4, 32),

                           qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_EAC_IRQ),

                    /* Ten consecutive lines */

                    &s->drq[OMAP24XX_DMA_EAC_AC_RD],

                    omap_findclk(s, "func_96m_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    /* All register mappings (includin those not currenlty implemented):

     * SystemControlMod	48000000 - 48000fff

     * SystemControlL4	48001000 - 48001fff

     * 32kHz Timer Mod	48004000 - 48004fff

     * 32kHz Timer L4	48005000 - 48005fff

     * PRCM ModA	48008000 - 480087ff

     * PRCM ModB	48008800 - 48008fff

     * PRCM L4		48009000 - 48009fff

     * TEST-BCM Mod	48012000 - 48012fff

     * TEST-BCM L4	48013000 - 48013fff

     * TEST-TAP Mod	48014000 - 48014fff

     * TEST-TAP L4	48015000 - 48015fff

     * GPIO1 Mod	48018000 - 48018fff

     * GPIO Top		48019000 - 48019fff

     * GPIO2 Mod	4801a000 - 4801afff

     * GPIO L4		4801b000 - 4801bfff

     * GPIO3 Mod	4801c000 - 4801cfff

     * GPIO4 Mod	4801e000 - 4801efff

     * WDTIMER1 Mod	48020000 - 48010fff

     * WDTIMER Top	48021000 - 48011fff

     * WDTIMER2 Mod	48022000 - 48012fff

     * WDTIMER L4	48023000 - 48013fff

     * WDTIMER3 Mod	48024000 - 48014fff

     * WDTIMER3 L4	48025000 - 48015fff

     * WDTIMER4 Mod	48026000 - 48016fff

     * WDTIMER4 L4	48027000 - 48017fff

     * GPTIMER1 Mod	48028000 - 48018fff

     * GPTIMER1 L4	48029000 - 48019fff

     * GPTIMER2 Mod	4802a000 - 4801afff

     * GPTIMER2 L4	4802b000 - 4801bfff

     * L4-Config AP	48040000 - 480407ff

     * L4-Config IP	48040800 - 48040fff

     * L4-Config LA	48041000 - 48041fff

     * ARM11ETB Mod	48048000 - 48049fff

     * ARM11ETB L4	4804a000 - 4804afff

     * DISPLAY Top	48050000 - 480503ff

     * DISPLAY DISPC	48050400 - 480507ff

     * DISPLAY RFBI	48050800 - 48050bff

     * DISPLAY VENC	48050c00 - 48050fff

     * DISPLAY L4	48051000 - 48051fff

     * CAMERA Top	48052000 - 480523ff

     * CAMERA core	48052400 - 480527ff

     * CAMERA DMA	48052800 - 48052bff

     * CAMERA MMU	48052c00 - 48052fff

     * CAMERA L4	48053000 - 48053fff

     * SDMA Mod		48056000 - 48056fff

     * SDMA L4		48057000 - 48057fff

     * SSI Top		48058000 - 48058fff

     * SSI GDD		48059000 - 48059fff

     * SSI Port1	4805a000 - 4805afff

     * SSI Port2	4805b000 - 4805bfff

     * SSI L4		4805c000 - 4805cfff

     * USB Mod		4805e000 - 480fefff

     * USB L4		4805f000 - 480fffff

     * WIN_TRACER1 Mod	48060000 - 48060fff

     * WIN_TRACER1 L4	48061000 - 48061fff

     * WIN_TRACER2 Mod	48062000 - 48062fff

     * WIN_TRACER2 L4	48063000 - 48063fff

     * WIN_TRACER3 Mod	48064000 - 48064fff

     * WIN_TRACER3 L4	48065000 - 48065fff

     * WIN_TRACER4 Top	48066000 - 480660ff

     * WIN_TRACER4 ETT	48066100 - 480661ff

     * WIN_TRACER4 WT	48066200 - 480662ff

     * WIN_TRACER4 L4	48067000 - 48067fff

     * XTI Mod		48068000 - 48068fff

     * XTI L4		48069000 - 48069fff

     * UART1 Mod	4806a000 - 4806afff

     * UART1 L4		4806b000 - 4806bfff

     * UART2 Mod	4806c000 - 4806cfff

     * UART2 L4		4806d000 - 4806dfff

     * UART3 Mod	4806e000 - 4806efff

     * UART3 L4		4806f000 - 4806ffff

     * I2C1 Mod		48070000 - 48070fff

     * I2C1 L4		48071000 - 48071fff

     * I2C2 Mod		48072000 - 48072fff

     * I2C2 L4		48073000 - 48073fff

     * McBSP1 Mod	48074000 - 48074fff

     * McBSP1 L4	48075000 - 48075fff

     * McBSP2 Mod	48076000 - 48076fff

     * McBSP2 L4	48077000 - 48077fff

     * GPTIMER3 Mod	48078000 - 48078fff

     * GPTIMER3 L4	48079000 - 48079fff

     * GPTIMER4 Mod	4807a000 - 4807afff

     * GPTIMER4 L4	4807b000 - 4807bfff

     * GPTIMER5 Mod	4807c000 - 4807cfff

     * GPTIMER5 L4	4807d000 - 4807dfff

     * GPTIMER6 Mod	4807e000 - 4807efff

     * GPTIMER6 L4	4807f000 - 4807ffff

     * GPTIMER7 Mod	48080000 - 48080fff

     * GPTIMER7 L4	48081000 - 48081fff

     * GPTIMER8 Mod	48082000 - 48082fff

     * GPTIMER8 L4	48083000 - 48083fff

     * GPTIMER9 Mod	48084000 - 48084fff

     * GPTIMER9 L4	48085000 - 48085fff

     * GPTIMER10 Mod	48086000 - 48086fff

     * GPTIMER10 L4	48087000 - 48087fff

     * GPTIMER11 Mod	48088000 - 48088fff

     * GPTIMER11 L4	48089000 - 48089fff

     * GPTIMER12 Mod	4808a000 - 4808afff

     * GPTIMER12 L4	4808b000 - 4808bfff

     * EAC Mod		48090000 - 48090fff

     * EAC L4		48091000 - 48091fff

     * FAC Mod		48092000 - 48092fff

     * FAC L4		48093000 - 48093fff

     * MAILBOX Mod	48094000 - 48094fff

     * MAILBOX L4	48095000 - 48095fff

     * SPI1 Mod		48098000 - 48098fff

     * SPI1 L4		48099000 - 48099fff

     * SPI2 Mod		4809a000 - 4809afff

     * SPI2 L4		4809b000 - 4809bfff

     * MMC/SDIO Mod	4809c000 - 4809cfff

     * MMC/SDIO L4	4809d000 - 4809dfff

     * MS_PRO Mod	4809e000 - 4809efff

     * MS_PRO L4	4809f000 - 4809ffff

     * RNG Mod		480a0000 - 480a0fff

     * RNG L4		480a1000 - 480a1fff

     * DES3DES Mod	480a2000 - 480a2fff

     * DES3DES L4	480a3000 - 480a3fff

     * SHA1MD5 Mod	480a4000 - 480a4fff

     * SHA1MD5 L4	480a5000 - 480a5fff

     * AES Mod		480a6000 - 480a6fff

     * AES L4		480a7000 - 480a7fff

     * PKA Mod		480a8000 - 480a9fff

     * PKA L4		480aa000 - 480aafff

     * MG Mod		480b0000 - 480b0fff

     * MG L4		480b1000 - 480b1fff

     * HDQ/1-wire Mod	480b2000 - 480b2fff

     * HDQ/1-wire L4	480b3000 - 480b3fff

     * MPU interrupt	480fe000 - 480fefff

     * STI channel base	54000000 - 5400ffff

     * IVA RAM		5c000000 - 5c01ffff

     * IVA ROM		5c020000 - 5c027fff

     * IMG_BUF_A	5c040000 - 5c040fff

     * IMG_BUF_B	5c042000 - 5c042fff

     * VLCDS		5c048000 - 5c0487ff

     * IMX_COEF		5c049000 - 5c04afff

     * IMX_CMD		5c051000 - 5c051fff

     * VLCDQ		5c053000 - 5c0533ff

     * VLCDH		5c054000 - 5c054fff

     * SEQ_CMD		5c055000 - 5c055fff

     * IMX_REG		5c056000 - 5c0560ff

     * VLCD_REG		5c056100 - 5c0561ff

     * SEQ_REG		5c056200 - 5c0562ff

     * IMG_BUF_REG	5c056300 - 5c0563ff

     * SEQIRQ_REG	5c056400 - 5c0564ff

     * OCP_REG		5c060000 - 5c060fff

     * SYSC_REG		5c070000 - 5c070fff

     * MMU_REG		5d000000 - 5d000fff

     * sDMA R		68000400 - 680005ff

     * sDMA W		68000600 - 680007ff

     * Display Control	68000800 - 680009ff

     * DSP subsystem	68000a00 - 68000bff

     * MPU subsystem	68000c00 - 68000dff

     * IVA subsystem	68001000 - 680011ff

     * USB		68001200 - 680013ff

     * Camera		68001400 - 680015ff

     * VLYNQ (firewall)	68001800 - 68001bff

     * VLYNQ		68001e00 - 68001fff

     * SSI		68002000 - 680021ff

     * L4		68002400 - 680025ff

     * DSP (firewall)	68002800 - 68002bff

     * DSP subsystem	68002e00 - 68002fff

     * IVA (firewall)	68003000 - 680033ff

     * IVA		68003600 - 680037ff

     * GFX		68003a00 - 68003bff

     * CMDWR emulation	68003c00 - 68003dff

     * SMS		68004000 - 680041ff

     * OCM		68004200 - 680043ff

     * GPMC		68004400 - 680045ff

     * RAM (firewall)	68005000 - 680053ff

     * RAM (err login)	68005400 - 680057ff

     * ROM (firewall)	68005800 - 68005bff

     * ROM (err login)	68005c00 - 68005fff

     * GPMC (firewall)	68006000 - 680063ff

     * GPMC (err login)	68006400 - 680067ff

     * SMS (err login)	68006c00 - 68006fff

     * SMS registers	68008000 - 68008fff

     * SDRC registers	68009000 - 68009fff

     * GPMC registers	6800a000   6800afff

     */

    qemu_register_reset(omap2_mpu_reset, s);

    return s;

}


static void vfio_unmap_bars(VFIOPCIDevice *vdev)

{

    int i;

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

        vfio_unmap_bar(vdev, i);

    }

    if (vdev->has_vga) {

        vfio_vga_quirk_teardown(vdev);

        pci_unregister_vga(&vdev->pdev);

    }

}


static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)

{

    PCIDevice *d = (PCIDevice *)dev;

    const pci_class_desc *desc;

    char ctxt[64];

    PCIIORegion *r;

    int i, class;

    class = pci_get_word(d->config + PCI_CLASS_DEVICE);

    desc = pci_class_descriptions;

    while (desc->desc && class != desc->class)

        desc++;

    if (desc->desc) {

        snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);

    } else {

        snprintf(ctxt, sizeof(ctxt), "Class %04x", class);

    }

    monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "

                   "pci id %04x:%04x (sub %04x:%04x)\n",

                   indent, "", ctxt, pci_bus_num(d->bus),

                   PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),

                   pci_get_word(d->config + PCI_VENDOR_ID),

                   pci_get_word(d->config + PCI_DEVICE_ID),

                   pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),

                   pci_get_word(d->config + PCI_SUBSYSTEM_ID));

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

        r = &d->io_regions[i];

        if (!r->size)

            continue;

        monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS

                       " [0x%"FMT_PCIBUS"]\n",

                       indent, "",

                       i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",

                       r->addr, r->addr + r->size - 1);

    }

}


ObjectClass *object_class_dynamic_cast_assert(ObjectClass *class,

                                              const char *typename,

                                              const char *file, int line,

                                              const char *func)

{

    ObjectClass *ret;

    trace_object_class_dynamic_cast_assert(class ? class->type->name : "(null)",

                                           typename, file, line, func);

#ifdef CONFIG_QOM_CAST_DEBUG

    int i;

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

        if (class->cast_cache[i] == typename) {

            ret = class;

            goto out;

        }

    }

#else

    if (!class->interfaces) {

        return class;

    }

#endif

    ret = object_class_dynamic_cast(class, typename);

    if (!ret && class) {

        fprintf(stderr, "%s:%d:%s: Object %p is not an instance of type %s\n",

                file, line, func, class, typename);

        abort();

    }

#ifdef CONFIG_QOM_CAST_DEBUG

    if (ret == class) {

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

            class->cast_cache[i - 1] = class->cast_cache[i];

        }

        class->cast_cache[i - 1] = typename;

    }

out:

#endif

    return ret;

}


static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)

{

#define HWACCEL_MAX (CONFIG_H264_DXVA2_HWACCEL + \

                     CONFIG_H264_D3D11VA_HWACCEL + \

                     CONFIG_H264_VAAPI_HWACCEL + \

                     (CONFIG_H264_VDA_HWACCEL * 2) + \

                     CONFIG_H264_VIDEOTOOLBOX_HWACCEL + \

                     CONFIG_H264_VDPAU_HWACCEL)

    enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmt = pix_fmts;

    const enum AVPixelFormat *choices = pix_fmts;

    int i;

    switch (h->ps.sps->bit_depth_luma) {

    case 9:

        if (CHROMA444(h)) {

            if (h->avctx->colorspace == AVCOL_SPC_RGB) {

                *fmt++ = AV_PIX_FMT_GBRP9;

            } else

                *fmt++ = AV_PIX_FMT_YUV444P9;

        } else if (CHROMA422(h))

            *fmt++ = AV_PIX_FMT_YUV422P9;

        else

            *fmt++ = AV_PIX_FMT_YUV420P9;

        break;

    case 10:

        if (CHROMA444(h)) {

            if (h->avctx->colorspace == AVCOL_SPC_RGB) {

                *fmt++ = AV_PIX_FMT_GBRP10;

            } else

                *fmt++ = AV_PIX_FMT_YUV444P10;

        } else if (CHROMA422(h))

            *fmt++ = AV_PIX_FMT_YUV422P10;

        else

            *fmt++ = AV_PIX_FMT_YUV420P10;

        break;

    case 12:

        if (CHROMA444(h)) {

            if (h->avctx->colorspace == AVCOL_SPC_RGB) {

                *fmt++ = AV_PIX_FMT_GBRP12;

            } else

                *fmt++ = AV_PIX_FMT_YUV444P12;

        } else if (CHROMA422(h))

            *fmt++ = AV_PIX_FMT_YUV422P12;

        else

            *fmt++ = AV_PIX_FMT_YUV420P12;

        break;

    case 14:

        if (CHROMA444(h)) {

            if (h->avctx->colorspace == AVCOL_SPC_RGB) {

                *fmt++ = AV_PIX_FMT_GBRP14;

            } else

                *fmt++ = AV_PIX_FMT_YUV444P14;

        } else if (CHROMA422(h))

            *fmt++ = AV_PIX_FMT_YUV422P14;

        else

            *fmt++ = AV_PIX_FMT_YUV420P14;

        break;

    case 8:

#if CONFIG_H264_VDPAU_HWACCEL

        *fmt++ = AV_PIX_FMT_VDPAU;

#endif

        if (CHROMA444(h)) {

            if (h->avctx->colorspace == AVCOL_SPC_RGB)

                *fmt++ = AV_PIX_FMT_GBRP;

            else if (h->avctx->color_range == AVCOL_RANGE_JPEG)

                *fmt++ = AV_PIX_FMT_YUVJ444P;

            else

                *fmt++ = AV_PIX_FMT_YUV444P;

        } else if (CHROMA422(h)) {

            if (h->avctx->color_range == AVCOL_RANGE_JPEG)

                *fmt++ = AV_PIX_FMT_YUVJ422P;

            else

                *fmt++ = AV_PIX_FMT_YUV422P;

        } else {

#if CONFIG_H264_DXVA2_HWACCEL

            *fmt++ = AV_PIX_FMT_DXVA2_VLD;

#endif

#if CONFIG_H264_D3D11VA_HWACCEL

            *fmt++ = AV_PIX_FMT_D3D11VA_VLD;

#endif

#if CONFIG_H264_VAAPI_HWACCEL

            *fmt++ = AV_PIX_FMT_VAAPI;

#endif

#if CONFIG_H264_VDA_HWACCEL

            *fmt++ = AV_PIX_FMT_VDA_VLD;

            *fmt++ = AV_PIX_FMT_VDA;

#endif

#if CONFIG_H264_VIDEOTOOLBOX_HWACCEL

            *fmt++ = AV_PIX_FMT_VIDEOTOOLBOX;

#endif

            if (h->avctx->codec->pix_fmts)

                choices = h->avctx->codec->pix_fmts;

            else if (h->avctx->color_range == AVCOL_RANGE_JPEG)

                *fmt++ = AV_PIX_FMT_YUVJ420P;

            else

                *fmt++ = AV_PIX_FMT_YUV420P;

        }

        break;

    default:

        av_log(h->avctx, AV_LOG_ERROR,

               "Unsupported bit depth %d\n", h->ps.sps->bit_depth_luma);

        return AVERROR_INVALIDDATA;

    }

    *fmt = AV_PIX_FMT_NONE;

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

        if (choices[i] == h->avctx->pix_fmt && !force_callback)

            return choices[i];

    return ff_thread_get_format(h->avctx, choices);

}


void msix_load(PCIDevice *dev, QEMUFile *f)

{

    unsigned n = dev->msix_entries_nr;

    unsigned int vector;

    if (!(dev->cap_present & QEMU_PCI_CAP_MSIX)) {

        return;

    }

    msix_free_irq_entries(dev);

    qemu_get_buffer(f, dev->msix_table_page, n * PCI_MSIX_ENTRY_SIZE);

    qemu_get_buffer(f, dev->msix_table_page + MSIX_PAGE_PENDING, (n + 7) / 8);

    msix_update_function_masked(dev);

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

        msix_handle_mask_update(dev, vector, true);

    }

}


static void vga_update_display(void *opaque)

{

    VGACommonState *s = opaque;

    int full_update, graphic_mode;

    qemu_flush_coalesced_mmio_buffer();

    if (ds_get_bits_per_pixel(s->ds) == 0) {

        /* nothing to do */

    } else {

        full_update = 0;

        if (!(s->ar_index & 0x20) &&

            /* extra CGA compatibility hacks (not in standard VGA */

            (!(vga_cga_hacks & VGA_CGA_HACK_PALETTE_BLANKING) ||

             (s->ar_index != 0 && s->ar_flip_flop))) {

            graphic_mode = GMODE_BLANK;

        } else {

            graphic_mode = s->gr[VGA_GFX_MISC] & VGA_GR06_GRAPHICS_MODE;

        }

        if (graphic_mode != s->graphic_mode) {

            s->graphic_mode = graphic_mode;

            s->cursor_blink_time = qemu_get_clock_ms(vm_clock);

            full_update = 1;

        }

        switch(graphic_mode) {

        case GMODE_TEXT:

            vga_draw_text(s, full_update);

            break;

        case GMODE_GRAPH:

            vga_draw_graphic(s, full_update);

            break;

        case GMODE_BLANK:

        default:

            vga_draw_blank(s, full_update);

            break;

        }

    }

}


static bool eckd_valid_address(BootMapPointer *p)

{

    const uint64_t cylinder = p->eckd.cylinder

                            + ((p->eckd.head & 0xfff0) << 12);

    const uint64_t head = p->eckd.head & 0x000f;

    if (head >= virtio_get_heads()

        ||  p->eckd.sector > virtio_get_sectors()

        ||  p->eckd.sector <= 0) {

        return false;

    }

    if (!virtio_guessed_disk_nature() && cylinder >= virtio_get_cylinders()) {

        return false;

    }

    return true;

}


static void test_bh_delete_from_cb(void)

{

    BHTestData data1 = { .n = 0, .max = 1 };

    data1.bh = aio_bh_new(ctx, bh_delete_cb, &data1);

    qemu_bh_schedule(data1.bh);

    g_assert_cmpint(data1.n, ==, 0);

    wait_for_aio();

    g_assert_cmpint(data1.n, ==, data1.max);

    g_assert(data1.bh == NULL);

    g_assert(!aio_poll(ctx, false));

}