static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed,

                               int completion)

{

    int dir;

    size_t len = 0;

#ifdef DEBUG_ISOCH

    const char *str = NULL;

#endif

    int pid;

    int ret;

    int i;

    USBDevice *dev;

    struct ohci_iso_td iso_td;

    uint32_t addr;

    uint16_t starting_frame;

    int16_t relative_frame_number;

    int frame_count;

    uint32_t start_offset, next_offset, end_offset = 0;

    uint32_t start_addr, end_addr;

    addr = ed->head & OHCI_DPTR_MASK;

    if (!ohci_read_iso_td(ohci, addr, &iso_td)) {

        printf("usb-ohci: ISO_TD read error at %x\n", addr);

        return 0;

    }

    starting_frame = OHCI_BM(iso_td.flags, TD_SF);

    frame_count = OHCI_BM(iso_td.flags, TD_FC);

    relative_frame_number = USUB(ohci->frame_number, starting_frame);

#ifdef DEBUG_ISOCH

    printf("--- ISO_TD ED head 0x%.8x tailp 0x%.8x\n"

           "0x%.8x 0x%.8x 0x%.8x 0x%.8x\n"

           "0x%.8x 0x%.8x 0x%.8x 0x%.8x\n"

           "0x%.8x 0x%.8x 0x%.8x 0x%.8x\n"

           "frame_number 0x%.8x starting_frame 0x%.8x\n"

           "frame_count  0x%.8x relative %d\n"

           "di 0x%.8x cc 0x%.8x\n",

           ed->head & OHCI_DPTR_MASK, ed->tail & OHCI_DPTR_MASK,

           iso_td.flags, iso_td.bp, iso_td.next, iso_td.be,

           iso_td.offset[0], iso_td.offset[1], iso_td.offset[2], iso_td.offset[3],

           iso_td.offset[4], iso_td.offset[5], iso_td.offset[6], iso_td.offset[7],

           ohci->frame_number, starting_frame,

           frame_count, relative_frame_number,

           OHCI_BM(iso_td.flags, TD_DI), OHCI_BM(iso_td.flags, TD_CC));

#endif

    if (relative_frame_number < 0) {

        DPRINTF("usb-ohci: ISO_TD R=%d < 0\n", relative_frame_number);

        return 1;

    } else if (relative_frame_number > frame_count) {

        /* ISO TD expired - retire the TD to the Done Queue and continue with

           the next ISO TD of the same ED */

        DPRINTF("usb-ohci: ISO_TD R=%d > FC=%d\n", relative_frame_number,

               frame_count);

        OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_DATAOVERRUN);

        ed->head &= ~OHCI_DPTR_MASK;

        ed->head |= (iso_td.next & OHCI_DPTR_MASK);

        iso_td.next = ohci->done;

        ohci->done = addr;

        i = OHCI_BM(iso_td.flags, TD_DI);

        if (i < ohci->done_count)

            ohci->done_count = i;

        ohci_put_iso_td(ohci, addr, &iso_td);

        return 0;

    }

    dir = OHCI_BM(ed->flags, ED_D);

    switch (dir) {

    case OHCI_TD_DIR_IN:

#ifdef DEBUG_ISOCH

        str = "in";

#endif

        pid = USB_TOKEN_IN;

        break;

    case OHCI_TD_DIR_OUT:

#ifdef DEBUG_ISOCH

        str = "out";

#endif

        pid = USB_TOKEN_OUT;

        break;

    case OHCI_TD_DIR_SETUP:

#ifdef DEBUG_ISOCH

        str = "setup";

#endif

        pid = USB_TOKEN_SETUP;

        break;

    default:

        printf("usb-ohci: Bad direction %d\n", dir);

        return 1;

    }

    if (!iso_td.bp || !iso_td.be) {

        printf("usb-ohci: ISO_TD bp 0x%.8x be 0x%.8x\n", iso_td.bp, iso_td.be);

        return 1;

    }

    start_offset = iso_td.offset[relative_frame_number];

    next_offset = iso_td.offset[relative_frame_number + 1];

    if (!(OHCI_BM(start_offset, TD_PSW_CC) & 0xe) ||

        ((relative_frame_number < frame_count) &&

         !(OHCI_BM(next_offset, TD_PSW_CC) & 0xe))) {

        printf("usb-ohci: ISO_TD cc != not accessed 0x%.8x 0x%.8x\n",

               start_offset, next_offset);

        return 1;

    }

    if ((relative_frame_number < frame_count) && (start_offset > next_offset)) {

        printf("usb-ohci: ISO_TD start_offset=0x%.8x > next_offset=0x%.8x\n",

                start_offset, next_offset);

        return 1;

    }

    if ((start_offset & 0x1000) == 0) {

        start_addr = (iso_td.bp & OHCI_PAGE_MASK) |

            (start_offset & OHCI_OFFSET_MASK);

    } else {

        start_addr = (iso_td.be & OHCI_PAGE_MASK) |

            (start_offset & OHCI_OFFSET_MASK);

    }

    if (relative_frame_number < frame_count) {

        end_offset = next_offset - 1;

        if ((end_offset & 0x1000) == 0) {

            end_addr = (iso_td.bp & OHCI_PAGE_MASK) |

                (end_offset & OHCI_OFFSET_MASK);

        } else {

            end_addr = (iso_td.be & OHCI_PAGE_MASK) |

                (end_offset & OHCI_OFFSET_MASK);

        }

    } else {

        /* Last packet in the ISO TD */

        end_addr = iso_td.be;

    }

    if ((start_addr & OHCI_PAGE_MASK) != (end_addr & OHCI_PAGE_MASK)) {

        len = (end_addr & OHCI_OFFSET_MASK) + 0x1001

            - (start_addr & OHCI_OFFSET_MASK);

    } else {

        len = end_addr - start_addr + 1;

    }

    if (len && dir != OHCI_TD_DIR_IN) {

        ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, len, 0);

    }

    if (completion) {

        ret = ohci->usb_packet.result;

    } else {

        usb_packet_setup(&ohci->usb_packet, pid,

                         OHCI_BM(ed->flags, ED_FA),

                         OHCI_BM(ed->flags, ED_EN));

        usb_packet_addbuf(&ohci->usb_packet, ohci->usb_buf, len);

        dev = ohci_find_device(ohci, ohci->usb_packet.devaddr);

        ret = usb_handle_packet(dev, &ohci->usb_packet);

        if (ret == USB_RET_ASYNC) {

            return 1;

        }

    }

#ifdef DEBUG_ISOCH

    printf("so 0x%.8x eo 0x%.8x\nsa 0x%.8x ea 0x%.8x\ndir %s len %zu ret %d\n",

           start_offset, end_offset, start_addr, end_addr, str, len, ret);

#endif

    /* Writeback */

    if (dir == OHCI_TD_DIR_IN && ret >= 0 && ret <= len) {

        /* IN transfer succeeded */

        ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, ret, 1);

        OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,

                    OHCI_CC_NOERROR);

        OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, ret);

    } else if (dir == OHCI_TD_DIR_OUT && ret == len) {

        /* OUT transfer succeeded */

        OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,

                    OHCI_CC_NOERROR);

        OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, 0);

    } else {

        if (ret > (ssize_t) len) {

            printf("usb-ohci: DataOverrun %d > %zu\n", ret, len);

            OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,

                        OHCI_CC_DATAOVERRUN);

            OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,

                        len);

        } else if (ret >= 0) {

            printf("usb-ohci: DataUnderrun %d\n", ret);

            OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,

                        OHCI_CC_DATAUNDERRUN);

        } else {

            switch (ret) {

            case USB_RET_NODEV:

                OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,

                            OHCI_CC_DEVICENOTRESPONDING);

                OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,

                            0);

                break;

            case USB_RET_NAK:

            case USB_RET_STALL:

                printf("usb-ohci: got NAK/STALL %d\n", ret);

                OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,

                            OHCI_CC_STALL);

                OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,

                            0);

                break;

            default:

                printf("usb-ohci: Bad device response %d\n", ret);

                OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,

                            OHCI_CC_UNDEXPETEDPID);

                break;

            }

        }

    }

    if (relative_frame_number == frame_count) {

        /* Last data packet of ISO TD - retire the TD to the Done Queue */

        OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_NOERROR);

        ed->head &= ~OHCI_DPTR_MASK;

        ed->head |= (iso_td.next & OHCI_DPTR_MASK);

        iso_td.next = ohci->done;

        ohci->done = addr;

        i = OHCI_BM(iso_td.flags, TD_DI);

        if (i < ohci->done_count)

            ohci->done_count = i;

    }

    ohci_put_iso_td(ohci, addr, &iso_td);

    return 1;

}


static QObject *parse_literal(JSONParserContext *ctxt, QList **tokens)

{

    QObject *token, *obj;

    QList *working = qlist_copy(*tokens);

    token = qlist_pop(working);

    if (token == NULL) {

        goto out;

    }

    switch (token_get_type(token)) {

    case JSON_STRING:

        obj = QOBJECT(qstring_from_escaped_str(ctxt, token));

        break;

    case JSON_INTEGER:

        obj = QOBJECT(qint_from_int(strtoll(token_get_value(token), NULL, 10)));

        break;

    case JSON_FLOAT:

        /* FIXME dependent on locale */

        obj = QOBJECT(qfloat_from_double(strtod(token_get_value(token), NULL)));

        break;

    default:

        goto out;

    }

    qobject_decref(token);

    QDECREF(*tokens);

    *tokens = working;

    return obj;

out:

    qobject_decref(token);

    QDECREF(working);

    return NULL;

}


static int spapr_populate_pci_child_dt(PCIDevice *dev, void *fdt, int offset,

                                       int phb_index, int drc_index,

                                       sPAPRPHBState *sphb)

{

    ResourceProps rp;

    bool is_bridge = false;

    int pci_status, err;

    char *buf = NULL;

    if (pci_default_read_config(dev, PCI_HEADER_TYPE, 1) ==

        PCI_HEADER_TYPE_BRIDGE) {

        is_bridge = true;

    }

    /* in accordance with PAPR+ v2.7 13.6.3, Table 181 */

    _FDT(fdt_setprop_cell(fdt, offset, "vendor-id",

                          pci_default_read_config(dev, PCI_VENDOR_ID, 2)));

    _FDT(fdt_setprop_cell(fdt, offset, "device-id",

                          pci_default_read_config(dev, PCI_DEVICE_ID, 2)));

    _FDT(fdt_setprop_cell(fdt, offset, "revision-id",

                          pci_default_read_config(dev, PCI_REVISION_ID, 1)));

    _FDT(fdt_setprop_cell(fdt, offset, "class-code",

                          pci_default_read_config(dev, PCI_CLASS_PROG, 3)));

    if (pci_default_read_config(dev, PCI_INTERRUPT_PIN, 1)) {

        _FDT(fdt_setprop_cell(fdt, offset, "interrupts",

                 pci_default_read_config(dev, PCI_INTERRUPT_PIN, 1)));

    }

    if (!is_bridge) {

        _FDT(fdt_setprop_cell(fdt, offset, "min-grant",

            pci_default_read_config(dev, PCI_MIN_GNT, 1)));

        _FDT(fdt_setprop_cell(fdt, offset, "max-latency",

            pci_default_read_config(dev, PCI_MAX_LAT, 1)));

    }

    if (pci_default_read_config(dev, PCI_SUBSYSTEM_ID, 2)) {

        _FDT(fdt_setprop_cell(fdt, offset, "subsystem-id",

                 pci_default_read_config(dev, PCI_SUBSYSTEM_ID, 2)));

    }

    if (pci_default_read_config(dev, PCI_SUBSYSTEM_VENDOR_ID, 2)) {

        _FDT(fdt_setprop_cell(fdt, offset, "subsystem-vendor-id",

                 pci_default_read_config(dev, PCI_SUBSYSTEM_VENDOR_ID, 2)));

    }

    _FDT(fdt_setprop_cell(fdt, offset, "cache-line-size",

        pci_default_read_config(dev, PCI_CACHE_LINE_SIZE, 1)));

    /* the following fdt cells are masked off the pci status register */

    pci_status = pci_default_read_config(dev, PCI_STATUS, 2);

    _FDT(fdt_setprop_cell(fdt, offset, "devsel-speed",

                          PCI_STATUS_DEVSEL_MASK & pci_status));

    if (pci_status & PCI_STATUS_FAST_BACK) {

        _FDT(fdt_setprop(fdt, offset, "fast-back-to-back", NULL, 0));

    }

    if (pci_status & PCI_STATUS_66MHZ) {

        _FDT(fdt_setprop(fdt, offset, "66mhz-capable", NULL, 0));

    }

    if (pci_status & PCI_STATUS_UDF) {

        _FDT(fdt_setprop(fdt, offset, "udf-supported", NULL, 0));

    }

    /* NOTE: this is normally generated by firmware via path/unit name,

     * but in our case we must set it manually since it does not get

     * processed by OF beforehand

     */

    _FDT(fdt_setprop_string(fdt, offset, "name", "pci"));

    buf = spapr_phb_get_loc_code(sphb, dev);

    if (!buf) {

        error_report("Failed setting the ibm,loc-code");

        return -1;

    }

    err = fdt_setprop_string(fdt, offset, "ibm,loc-code", buf);

    g_free(buf);

    if (err < 0) {

        return err;

    }

    _FDT(fdt_setprop_cell(fdt, offset, "ibm,my-drc-index", drc_index));

    _FDT(fdt_setprop_cell(fdt, offset, "#address-cells",

                          RESOURCE_CELLS_ADDRESS));

    _FDT(fdt_setprop_cell(fdt, offset, "#size-cells",

                          RESOURCE_CELLS_SIZE));

    _FDT(fdt_setprop_cell(fdt, offset, "ibm,req#msi-x",

                          RESOURCE_CELLS_SIZE));

    populate_resource_props(dev, &rp);

    _FDT(fdt_setprop(fdt, offset, "reg", (uint8_t *)rp.reg, rp.reg_len));

    _FDT(fdt_setprop(fdt, offset, "assigned-addresses",

                     (uint8_t *)rp.assigned, rp.assigned_len));

    return 0;

}


static void usb_host_set_config(USBHostDevice *s, int config, USBPacket *p)

{

    int rc;

    trace_usb_host_set_config(s->bus_num, s->addr, config);

    usb_host_release_interfaces(s);

    usb_host_detach_kernel(s);

    rc = libusb_set_configuration(s->dh, config);

    if (rc != 0) {

        usb_host_libusb_error("libusb_set_configuration", rc);

        p->status = USB_RET_STALL;

        if (rc == LIBUSB_ERROR_NO_DEVICE) {

            usb_host_nodev(s);

        }

        return;

    }

    p->status = usb_host_claim_interfaces(s, config);

    if (p->status != USB_RET_SUCCESS) {

        return;

    }

    usb_host_ep_update(s);

}


static __attribute__((unused)) void map_exec(void *addr, long size)

{

    unsigned long start, end, page_size;

    page_size = getpagesize();

    start = (unsigned long)addr;

    start &= ~(page_size - 1);

    end = (unsigned long)addr + size;

    end += page_size - 1;

    end &= ~(page_size - 1);

    mprotect((void *)start, end - start,

             PROT_READ | PROT_WRITE | PROT_EXEC);

}


static int QEMU_WARN_UNUSED_RESULT update_refcount(BlockDriverState *bs,

    int64_t offset, int64_t length, int addend)

{

    BDRVQcowState *s = bs->opaque;

    int64_t start, last, cluster_offset;

    int64_t refcount_block_offset = 0;

    int64_t table_index = -1, old_table_index;

    int first_index = -1, last_index = -1;

    int ret;

#ifdef DEBUG_ALLOC2

    printf("update_refcount: offset=%" PRId64 " size=%" PRId64 " addend=%d\n",

           offset, length, addend);

#endif

    if (length < 0) {

        return -EINVAL;

    } else if (length == 0) {

        return 0;

    }

    start = offset & ~(s->cluster_size - 1);

    last = (offset + length - 1) & ~(s->cluster_size - 1);

    for(cluster_offset = start; cluster_offset <= last;

        cluster_offset += s->cluster_size)

    {

        int block_index, refcount;

        int64_t cluster_index = cluster_offset >> s->cluster_bits;

        int64_t new_block;

        /* Only write refcount block to disk when we are done with it */

        old_table_index = table_index;

        table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);

        if ((old_table_index >= 0) && (table_index != old_table_index)) {

            ret = write_refcount_block_entries(bs, refcount_block_offset,

                first_index, last_index);

            if (ret < 0) {

                return ret;

            }

            first_index = -1;

            last_index = -1;

        }

        /* Load the refcount block and allocate it if needed */

        new_block = alloc_refcount_block(bs, cluster_index);

        if (new_block < 0) {

            ret = new_block;

            goto fail;

        }

        refcount_block_offset = new_block;

        /* we can update the count and save it */

        block_index = cluster_index &

            ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);

        if (first_index == -1 || block_index < first_index) {

            first_index = block_index;

        }

        if (block_index > last_index) {

            last_index = block_index;

        }

        refcount = be16_to_cpu(s->refcount_block_cache[block_index]);

        refcount += addend;

        if (refcount < 0 || refcount > 0xffff) {

            ret = -EINVAL;

            goto fail;

        }

        if (refcount == 0 && cluster_index < s->free_cluster_index) {

            s->free_cluster_index = cluster_index;

        }

        s->refcount_block_cache[block_index] = cpu_to_be16(refcount);

    }

    ret = 0;

fail:

    /* Write last changed block to disk */

    if (refcount_block_offset != 0) {

        int wret;

        wret = write_refcount_block_entries(bs, refcount_block_offset,

            first_index, last_index);

        if (wret < 0) {

            return ret < 0 ? ret : wret;

        }

    }

    /*

     * Try do undo any updates if an error is returned (This may succeed in

     * some cases like ENOSPC for allocating a new refcount block)

     */

    if (ret < 0) {

        int dummy;

        dummy = update_refcount(bs, offset, cluster_offset - offset, -addend);

    }

    bdrv_flush(bs->file);

    return ret;

}


int fw_cfg_add_i16(FWCfgState *s, uint16_t key, uint16_t value)

{

    uint16_t *copy;

    copy = g_malloc(sizeof(value));

    *copy = cpu_to_le16(value);

    return fw_cfg_add_bytes(s, key, (uint8_t *)copy, sizeof(value));

}


int pcistg_service_call(S390CPU *cpu, uint8_t r1, uint8_t r2)

{

    CPUS390XState *env = &cpu->env;

    uint64_t offset, data;

    S390PCIBusDevice *pbdev;

    MemoryRegion *mr;

    uint8_t len;

    uint32_t fh;

    uint8_t pcias;

    cpu_synchronize_state(CPU(cpu));

    if (env->psw.mask & PSW_MASK_PSTATE) {

        program_interrupt(env, PGM_PRIVILEGED, 4);

        return 0;

    }

    if (r2 & 0x1) {

        program_interrupt(env, PGM_SPECIFICATION, 4);

        return 0;

    }

    fh = env->regs[r2] >> 32;

    pcias = (env->regs[r2] >> 16) & 0xf;

    len = env->regs[r2] & 0xf;

    offset = env->regs[r2 + 1];

    pbdev = s390_pci_find_dev_by_fh(fh);

    if (!pbdev) {

        DPRINTF("pcistg no pci dev\n");

        setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);

        return 0;

    }

    switch (pbdev->state) {

    case ZPCI_FS_RESERVED:

    case ZPCI_FS_STANDBY:

    case ZPCI_FS_DISABLED:

    case ZPCI_FS_PERMANENT_ERROR:

        setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);

        return 0;

    case ZPCI_FS_ERROR:

        setcc(cpu, ZPCI_PCI_LS_ERR);

        s390_set_status_code(env, r2, ZPCI_PCI_ST_BLOCKED);

        return 0;

    default:

        break;

    }

    data = env->regs[r1];

    if (pcias < 6) {

        if ((8 - (offset & 0x7)) < len) {

            program_interrupt(env, PGM_OPERAND, 4);

            return 0;

        }

        if (trap_msix(pbdev, offset, pcias)) {

            offset = offset - pbdev->msix.table_offset;

            mr = &pbdev->pdev->msix_table_mmio;

            update_msix_table_msg_data(pbdev, offset, &data, len);

        } else {

            mr = pbdev->pdev->io_regions[pcias].memory;

        }

        memory_region_dispatch_write(mr, offset, data, len,

                                     MEMTXATTRS_UNSPECIFIED);

    } else if (pcias == 15) {

        if ((4 - (offset & 0x3)) < len) {

            program_interrupt(env, PGM_OPERAND, 4);

            return 0;

        }

        switch (len) {

        case 1:

            break;

        case 2:

            data = bswap16(data);

            break;

        case 4:

            data = bswap32(data);

            break;

        case 8:

            data = bswap64(data);

            break;

        default:

            program_interrupt(env, PGM_OPERAND, 4);

            return 0;

        }

        pci_host_config_write_common(pbdev->pdev, offset,

                                     pci_config_size(pbdev->pdev),

                                     data, len);

    } else {

        DPRINTF("pcistg invalid space\n");

        setcc(cpu, ZPCI_PCI_LS_ERR);

        s390_set_status_code(env, r2, ZPCI_PCI_ST_INVAL_AS);

        return 0;

    }

    setcc(cpu, ZPCI_PCI_LS_OK);

    return 0;

}


static int dv_decode_video_segment(AVCodecContext *avctx, void *arg)

{

    DVVideoContext *s = avctx->priv_data;

    DVwork_chunk *work_chunk = arg;

    int quant, dc, dct_mode, class1, j;

    int mb_index, mb_x, mb_y, last_index;

    int y_stride, linesize;

    DCTELEM *block, *block1;

    int c_offset;

    uint8_t *y_ptr;

    const uint8_t *buf_ptr;

    PutBitContext pb, vs_pb;

    GetBitContext gb;

    BlockInfo mb_data[5 * DV_MAX_BPM], *mb, *mb1;

    LOCAL_ALIGNED_16(DCTELEM, sblock, [5*DV_MAX_BPM], [64]);

    LOCAL_ALIGNED_16(uint8_t, mb_bit_buffer, [80 + 4]); /* allow some slack */

    LOCAL_ALIGNED_16(uint8_t, vs_bit_buffer, [5 * 80 + 4]); /* allow some slack */

    const int log2_blocksize = 3-s->avctx->lowres;

    int is_field_mode[5];

    assert((((int)mb_bit_buffer) & 7) == 0);

    assert((((int)vs_bit_buffer) & 7) == 0);

    memset(sblock, 0, 5*DV_MAX_BPM*sizeof(*sblock));

    /* pass 1: read DC and AC coefficients in blocks */

    buf_ptr = &s->buf[work_chunk->buf_offset*80];

    block1  = &sblock[0][0];

    mb1     = mb_data;

    init_put_bits(&vs_pb, vs_bit_buffer, 5 * 80);

    for (mb_index = 0; mb_index < 5; mb_index++, mb1 += s->sys->bpm, block1 += s->sys->bpm * 64) {

        /* skip header */

        quant = buf_ptr[3] & 0x0f;

        buf_ptr += 4;

        init_put_bits(&pb, mb_bit_buffer, 80);

        mb    = mb1;

        block = block1;

        is_field_mode[mb_index] = 0;

        for (j = 0; j < s->sys->bpm; j++) {

            last_index = s->sys->block_sizes[j];

            init_get_bits(&gb, buf_ptr, last_index);

            /* get the DC */

            dc       = get_sbits(&gb, 9);

            dct_mode = get_bits1(&gb);

            class1   = get_bits(&gb, 2);

            if (DV_PROFILE_IS_HD(s->sys)) {

                mb->idct_put     = s->idct_put[0];

                mb->scan_table   = s->dv_zigzag[0];

                mb->factor_table = &s->sys->idct_factor[(j >= 4)*4*16*64 + class1*16*64 + quant*64];

                is_field_mode[mb_index] |= !j && dct_mode;

            } else {

                mb->idct_put     = s->idct_put[dct_mode && log2_blocksize == 3];

                mb->scan_table   = s->dv_zigzag[dct_mode];

                mb->factor_table = &s->sys->idct_factor[(class1 == 3)*2*22*64 + dct_mode*22*64 +

                                                        (quant + dv_quant_offset[class1])*64];

            }

            dc = dc << 2;

            /* convert to unsigned because 128 is not added in the

               standard IDCT */

            dc += 1024;

            block[0] = dc;

            buf_ptr += last_index >> 3;

            mb->pos               = 0;

            mb->partial_bit_count = 0;

            av_dlog(avctx, "MB block: %d, %d ", mb_index, j);

            dv_decode_ac(&gb, mb, block);

            /* write the remaining bits in a new buffer only if the

               block is finished */

            if (mb->pos >= 64)

                bit_copy(&pb, &gb);

            block += 64;

            mb++;

        }

        /* pass 2: we can do it just after */

        av_dlog(avctx, "***pass 2 size=%d MB#=%d\n", put_bits_count(&pb), mb_index);

        block = block1;

        mb    = mb1;

        init_get_bits(&gb, mb_bit_buffer, put_bits_count(&pb));

        flush_put_bits(&pb);

        for (j = 0; j < s->sys->bpm; j++, block += 64, mb++) {

            if (mb->pos < 64 && get_bits_left(&gb) > 0) {

                dv_decode_ac(&gb, mb, block);

                /* if still not finished, no need to parse other blocks */

                if (mb->pos < 64)

                    break;

            }

        }

        /* all blocks are finished, so the extra bytes can be used at

           the video segment level */

        if (j >= s->sys->bpm)

            bit_copy(&vs_pb, &gb);

    }

    /* we need a pass over the whole video segment */

    av_dlog(avctx, "***pass 3 size=%d\n", put_bits_count(&vs_pb));

    block = &sblock[0][0];

    mb    = mb_data;

    init_get_bits(&gb, vs_bit_buffer, put_bits_count(&vs_pb));

    flush_put_bits(&vs_pb);

    for (mb_index = 0; mb_index < 5; mb_index++) {

        for (j = 0; j < s->sys->bpm; j++) {

            if (mb->pos < 64) {

                av_dlog(avctx, "start %d:%d\n", mb_index, j);

                dv_decode_ac(&gb, mb, block);

            }

            if (mb->pos >= 64 && mb->pos < 127)

                av_log(avctx, AV_LOG_ERROR, "AC EOB marker is absent pos=%d\n", mb->pos);

            block += 64;

            mb++;

        }

    }

    /* compute idct and place blocks */

    block = &sblock[0][0];

    mb    = mb_data;

    for (mb_index = 0; mb_index < 5; mb_index++) {

        dv_calculate_mb_xy(s, work_chunk, mb_index, &mb_x, &mb_y);

        /* idct_put'ting luminance */

        if ((s->sys->pix_fmt == PIX_FMT_YUV420P) ||

            (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x >= (704 / 8)) ||

            (s->sys->height >= 720 && mb_y != 134)) {

            y_stride = (s->picture.linesize[0] << ((!is_field_mode[mb_index]) * log2_blocksize));

        } else {

            y_stride = (2 << log2_blocksize);

        }

        y_ptr = s->picture.data[0] + ((mb_y * s->picture.linesize[0] + mb_x) << log2_blocksize);

        linesize = s->picture.linesize[0] << is_field_mode[mb_index];

        mb[0]    .idct_put(y_ptr                                   , linesize, block + 0*64);

        if (s->sys->video_stype == 4) { /* SD 422 */

            mb[2].idct_put(y_ptr + (1 << log2_blocksize)           , linesize, block + 2*64);

        } else {

            mb[1].idct_put(y_ptr + (1 << log2_blocksize)           , linesize, block + 1*64);

            mb[2].idct_put(y_ptr                         + y_stride, linesize, block + 2*64);

            mb[3].idct_put(y_ptr + (1 << log2_blocksize) + y_stride, linesize, block + 3*64);

        }

        mb += 4;

        block += 4*64;

        /* idct_put'ting chrominance */

        c_offset = (((mb_y >>  (s->sys->pix_fmt == PIX_FMT_YUV420P)) * s->picture.linesize[1] +

                     (mb_x >> ((s->sys->pix_fmt == PIX_FMT_YUV411P) ? 2 : 1))) << log2_blocksize);

        for (j = 2; j; j--) {

            uint8_t *c_ptr = s->picture.data[j] + c_offset;

            if (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x >= (704 / 8)) {

                  uint64_t aligned_pixels[64/8];

                  uint8_t *pixels = (uint8_t*)aligned_pixels;

                  uint8_t *c_ptr1, *ptr1;

                  int x, y;

                  mb->idct_put(pixels, 8, block);

                  for (y = 0; y < (1 << log2_blocksize); y++, c_ptr += s->picture.linesize[j], pixels += 8) {

                      ptr1   = pixels + (1 << (log2_blocksize - 1));

                      c_ptr1 = c_ptr + (s->picture.linesize[j] << log2_blocksize);

                      for (x = 0; x < (1 << (log2_blocksize - 1)); x++) {

                          c_ptr[x]  = pixels[x];

                          c_ptr1[x] = ptr1[x];

                      }

                  }

                  block += 64; mb++;

            } else {

                  y_stride = (mb_y == 134) ? (1 << log2_blocksize) :

                                             s->picture.linesize[j] << ((!is_field_mode[mb_index]) * log2_blocksize);

                  linesize = s->picture.linesize[j] << is_field_mode[mb_index];

                  (mb++)->    idct_put(c_ptr           , linesize, block); block += 64;

                  if (s->sys->bpm == 8) {

                      (mb++)->idct_put(c_ptr + y_stride, linesize, block); block += 64;

                  }

            }

        }

    }

    return 0;

}


void build_legacy_cpu_hotplug_aml(Aml *ctx, MachineState *machine,

                                  uint16_t io_base)

{

    Aml *dev;

    Aml *crs;

    Aml *pkg;

    Aml *field;

    Aml *method;

    Aml *if_ctx;

    Aml *else_ctx;

    int i, apic_idx;

    Aml *sb_scope = aml_scope("_SB");

    uint8_t madt_tmpl[8] = {0x00, 0x08, 0x00, 0x00, 0x00, 0, 0, 0};

    Aml *cpu_id = aml_arg(1);

    Aml *apic_id = aml_arg(0);

    Aml *cpu_on = aml_local(0);

    Aml *madt = aml_local(1);

    Aml *cpus_map = aml_name(CPU_ON_BITMAP);

    Aml *zero = aml_int(0);

    Aml *one = aml_int(1);

    MachineClass *mc = MACHINE_GET_CLASS(machine);

    CPUArchIdList *apic_ids = mc->possible_cpu_arch_ids(machine);

    PCMachineState *pcms = PC_MACHINE(machine);

    /*

     * _MAT method - creates an madt apic buffer

     * apic_id = Arg0 = Local APIC ID

     * cpu_id  = Arg1 = Processor ID

     * cpu_on = Local0 = CPON flag for this cpu

     * madt = Local1 = Buffer (in madt apic form) to return

     */

    method = aml_method(CPU_MAT_METHOD, 2, AML_NOTSERIALIZED);

    aml_append(method,

        aml_store(aml_derefof(aml_index(cpus_map, apic_id)), cpu_on));

    aml_append(method,

        aml_store(aml_buffer(sizeof(madt_tmpl), madt_tmpl), madt));

    /* Update the processor id, lapic id, and enable/disable status */

    aml_append(method, aml_store(cpu_id, aml_index(madt, aml_int(2))));

    aml_append(method, aml_store(apic_id, aml_index(madt, aml_int(3))));

    aml_append(method, aml_store(cpu_on, aml_index(madt, aml_int(4))));

    aml_append(method, aml_return(madt));

    aml_append(sb_scope, method);

    /*

     * _STA method - return ON status of cpu

     * apic_id = Arg0 = Local APIC ID

     * cpu_on = Local0 = CPON flag for this cpu

     */

    method = aml_method(CPU_STATUS_METHOD, 1, AML_NOTSERIALIZED);

    aml_append(method,

        aml_store(aml_derefof(aml_index(cpus_map, apic_id)), cpu_on));

    if_ctx = aml_if(cpu_on);

    {

        aml_append(if_ctx, aml_return(aml_int(0xF)));

    }

    aml_append(method, if_ctx);

    else_ctx = aml_else();

    {

        aml_append(else_ctx, aml_return(zero));

    }

    aml_append(method, else_ctx);

    aml_append(sb_scope, method);

    method = aml_method(CPU_EJECT_METHOD, 2, AML_NOTSERIALIZED);

    aml_append(method, aml_sleep(200));

    aml_append(sb_scope, method);

    method = aml_method(CPU_SCAN_METHOD, 0, AML_NOTSERIALIZED);

    {

        Aml *while_ctx, *if_ctx2, *else_ctx2;

        Aml *bus_check_evt = aml_int(1);

        Aml *remove_evt = aml_int(3);

        Aml *status_map = aml_local(5); /* Local5 = active cpu bitmap */

        Aml *byte = aml_local(2); /* Local2 = last read byte from bitmap */

        Aml *idx = aml_local(0); /* Processor ID / APIC ID iterator */

        Aml *is_cpu_on = aml_local(1); /* Local1 = CPON flag for cpu */

        Aml *status = aml_local(3); /* Local3 = active state for cpu */

        aml_append(method, aml_store(aml_name(CPU_STATUS_MAP), status_map));

        aml_append(method, aml_store(zero, byte));

        aml_append(method, aml_store(zero, idx));

        /* While (idx < SizeOf(CPON)) */

        while_ctx = aml_while(aml_lless(idx, aml_sizeof(cpus_map)));

        aml_append(while_ctx,

            aml_store(aml_derefof(aml_index(cpus_map, idx)), is_cpu_on));

        if_ctx = aml_if(aml_and(idx, aml_int(0x07), NULL));

        {

            /* Shift down previously read bitmap byte */

            aml_append(if_ctx, aml_shiftright(byte, one, byte));

        }

        aml_append(while_ctx, if_ctx);

        else_ctx = aml_else();

        {

            /* Read next byte from cpu bitmap */

            aml_append(else_ctx, aml_store(aml_derefof(aml_index(status_map,

                       aml_shiftright(idx, aml_int(3), NULL))), byte));

        }

        aml_append(while_ctx, else_ctx);

        aml_append(while_ctx, aml_store(aml_and(byte, one, NULL), status));

        if_ctx = aml_if(aml_lnot(aml_equal(is_cpu_on, status)));

        {

            /* State change - update CPON with new state */

            aml_append(if_ctx, aml_store(status, aml_index(cpus_map, idx)));

            if_ctx2 = aml_if(aml_equal(status, one));

            {

                aml_append(if_ctx2,

                    aml_call2(AML_NOTIFY_METHOD, idx, bus_check_evt));

            }

            aml_append(if_ctx, if_ctx2);

            else_ctx2 = aml_else();

            {

                aml_append(else_ctx2,

                    aml_call2(AML_NOTIFY_METHOD, idx, remove_evt));

            }

        }

        aml_append(if_ctx, else_ctx2);

        aml_append(while_ctx, if_ctx);

        aml_append(while_ctx, aml_increment(idx)); /* go to next cpu */

        aml_append(method, while_ctx);

    }

    aml_append(sb_scope, method);

    /* The current AML generator can cover the APIC ID range [0..255],

     * inclusive, for VCPU hotplug. */

    QEMU_BUILD_BUG_ON(ACPI_CPU_HOTPLUG_ID_LIMIT > 256);

    g_assert(pcms->apic_id_limit <= ACPI_CPU_HOTPLUG_ID_LIMIT);

    /* create PCI0.PRES device and its _CRS to reserve CPU hotplug MMIO */

    dev = aml_device("PCI0." stringify(CPU_HOTPLUG_RESOURCE_DEVICE));

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

    aml_append(dev,

        aml_name_decl("_UID", aml_string("CPU Hotplug resources"))

    );

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

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

    crs = aml_resource_template();

    aml_append(crs,

        aml_io(AML_DECODE16, io_base, io_base, 1, ACPI_GPE_PROC_LEN)

    );

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

    aml_append(sb_scope, dev);

    /* declare CPU hotplug MMIO region and PRS field to access it */

    aml_append(sb_scope, aml_operation_region(

        "PRST", AML_SYSTEM_IO, aml_int(io_base), ACPI_GPE_PROC_LEN));

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

    aml_append(field, aml_named_field("PRS", 256));

    aml_append(sb_scope, field);

    /* build Processor object for each processor */

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

        int apic_id = apic_ids->cpus[i].arch_id;

        assert(apic_id < ACPI_CPU_HOTPLUG_ID_LIMIT);

        dev = aml_processor(i, 0, 0, "CP%.02X", apic_id);

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

        aml_append(method,

            aml_return(aml_call2(CPU_MAT_METHOD, aml_int(apic_id), aml_int(i))

        ));

        aml_append(dev, method);

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

        aml_append(method,

            aml_return(aml_call1(CPU_STATUS_METHOD, aml_int(apic_id))));

        aml_append(dev, method);

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

        aml_append(method,

            aml_return(aml_call2(CPU_EJECT_METHOD, aml_int(apic_id),

                aml_arg(0)))

        );

        aml_append(dev, method);

        aml_append(sb_scope, dev);

    }

    /* build this code:

     *   Method(NTFY, 2) {If (LEqual(Arg0, 0x00)) {Notify(CP00, Arg1)} ...}

     */

    /* Arg0 = APIC ID */

    method = aml_method(AML_NOTIFY_METHOD, 2, AML_NOTSERIALIZED);

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

        int apic_id = apic_ids->cpus[i].arch_id;

        if_ctx = aml_if(aml_equal(aml_arg(0), aml_int(apic_id)));

        aml_append(if_ctx,

            aml_notify(aml_name("CP%.02X", apic_id), aml_arg(1))

        );

        aml_append(method, if_ctx);

    }

    aml_append(sb_scope, method);

    /* build "Name(CPON, Package() { One, One, ..., Zero, Zero, ... })"

     *

     * Note: The ability to create variable-sized packages was first

     * introduced in ACPI 2.0. ACPI 1.0 only allowed fixed-size packages

     * ith up to 255 elements. Windows guests up to win2k8 fail when

     * VarPackageOp is used.

     */

    pkg = pcms->apic_id_limit <= 255 ? aml_package(pcms->apic_id_limit) :

                                       aml_varpackage(pcms->apic_id_limit);

    for (i = 0, apic_idx = 0; i < apic_ids->len; i++) {

        int apic_id = apic_ids->cpus[i].arch_id;

        for (; apic_idx < apic_id; apic_idx++) {

            aml_append(pkg, aml_int(0));

        }

        aml_append(pkg, aml_int(apic_ids->cpus[i].cpu ? 1 : 0));

        apic_idx = apic_id + 1;

    }

    aml_append(sb_scope, aml_name_decl(CPU_ON_BITMAP, pkg));

    g_free(apic_ids);

    aml_append(ctx, sb_scope);

    method = aml_method("\\_GPE._E02", 0, AML_NOTSERIALIZED);

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

    aml_append(ctx, method);

}


static void test_dispatch_cmd_io(void)

{

    QDict *req = qdict_new();

    QDict *args = qdict_new();

    QDict *args3 = qdict_new();

    QDict *ud1a = qdict_new();

    QDict *ud1b = qdict_new();

    QDict *ret, *ret_dict, *ret_dict_dict, *ret_dict_dict_userdef;

    QDict *ret_dict_dict2, *ret_dict_dict2_userdef;

    QInt *ret3;

    qdict_put_obj(ud1a, "integer", QOBJECT(qint_from_int(42)));

    qdict_put_obj(ud1a, "string", QOBJECT(qstring_from_str("hello")));

    qdict_put_obj(ud1b, "integer", QOBJECT(qint_from_int(422)));

    qdict_put_obj(ud1b, "string", QOBJECT(qstring_from_str("hello2")));

    qdict_put_obj(args, "ud1a", QOBJECT(ud1a));

    qdict_put_obj(args, "ud1b", QOBJECT(ud1b));

    qdict_put_obj(req, "arguments", QOBJECT(args));

    qdict_put_obj(req, "execute", QOBJECT(qstring_from_str("user_def_cmd2")));

    ret = qobject_to_qdict(test_qmp_dispatch(req));

    assert(!strcmp(qdict_get_str(ret, "string"), "blah1"));

    ret_dict = qdict_get_qdict(ret, "dict");

    assert(!strcmp(qdict_get_str(ret_dict, "string"), "blah2"));

    ret_dict_dict = qdict_get_qdict(ret_dict, "dict");

    ret_dict_dict_userdef = qdict_get_qdict(ret_dict_dict, "userdef");

    assert(qdict_get_int(ret_dict_dict_userdef, "integer") == 42);

    assert(!strcmp(qdict_get_str(ret_dict_dict_userdef, "string"), "hello"));

    assert(!strcmp(qdict_get_str(ret_dict_dict, "string"), "blah3"));

    ret_dict_dict2 = qdict_get_qdict(ret_dict, "dict2");

    ret_dict_dict2_userdef = qdict_get_qdict(ret_dict_dict2, "userdef");

    assert(qdict_get_int(ret_dict_dict2_userdef, "integer") == 422);

    assert(!strcmp(qdict_get_str(ret_dict_dict2_userdef, "string"), "hello2"));

    assert(!strcmp(qdict_get_str(ret_dict_dict2, "string"), "blah4"));

    QDECREF(ret);

    qdict_put(args3, "a", qint_from_int(66));

    qdict_put(req, "arguments", args3);

    qdict_put(req, "execute", qstring_from_str("user_def_cmd3"));

    ret3 = qobject_to_qint(test_qmp_dispatch(req));

    assert(qint_get_int(ret3) == 66);

    QDECREF(ret3);

    QDECREF(req);

}


static void coroutine_fn bdrv_flush_co_entry(void *opaque)

{

    RwCo *rwco = opaque;

    rwco->ret = bdrv_co_flush(rwco->bs);

}


static inline void t_gen_add_flag(TCGv d, int flag)

{

	TCGv c;

	c = tcg_temp_new(TCG_TYPE_TL);

	t_gen_mov_TN_preg(c, PR_CCS);

	/* Propagate carry into d.  */

	tcg_gen_andi_tl(c, c, 1 << flag);

	if (flag)

		tcg_gen_shri_tl(c, c, flag);

	tcg_gen_add_tl(d, d, c);

	tcg_temp_free(c);

}


void console_select(unsigned int index)

{

    TextConsole *s;

    if (index >= MAX_CONSOLES)

        return;

    s = consoles[index];

    if (s) {

        active_console = s;

        if (s->g_width && s->g_height

            && (s->g_width != s->ds->width || s->g_height != s->ds->height))

            dpy_resize(s->ds, s->g_width, s->g_height);

        vga_hw_invalidate();

    }

}


static void update_max_chunk_size(BDRVDMGState *s, uint32_t chunk,

                                  uint32_t *max_compressed_size,

                                  uint32_t *max_sectors_per_chunk)

{

    uint32_t compressed_size = 0;

    uint32_t uncompressed_sectors = 0;

    switch (s->types[chunk]) {

    case 0x80000005: /* zlib compressed */

    case 0x80000006: /* bzip2 compressed */

        compressed_size = s->lengths[chunk];

        uncompressed_sectors = s->sectorcounts[chunk];

        break;

    case 1: /* copy */

        uncompressed_sectors = (s->lengths[chunk] + 511) / 512;

        break;

    case 2: /* zero */

        uncompressed_sectors = s->sectorcounts[chunk];

        break;

    }

    if (compressed_size > *max_compressed_size) {

        *max_compressed_size = compressed_size;

    }

    if (uncompressed_sectors > *max_sectors_per_chunk) {

        *max_sectors_per_chunk = uncompressed_sectors;

    }

}


static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr){

    AVFormatContext *s= nut->avf;

    ByteIOContext *bc = &s->pb;

    int64_t end, tmp;

    AVRational time_base;

    nut->last_syncpoint_pos= url_ftell(bc)-8;

    end= get_packetheader(nut, bc, 1);

    end += url_ftell(bc);

    tmp= get_v(bc);

    *back_ptr= nut->last_syncpoint_pos - 16*get_v(bc);

    if(*back_ptr < 0)

        return -1;

    ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count], tmp);

    if(skip_reserved(bc, end) || get_checksum(bc)){

        av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");

        return -1;

    }

    *ts= tmp / s->nb_streams * av_q2d(nut->time_base[tmp % s->nb_streams])*AV_TIME_BASE;

    add_sp(nut, nut->last_syncpoint_pos, *back_ptr, *ts);

    return 0;

}


int av_image_fill_linesizes(int linesizes[4], enum PixelFormat pix_fmt, int width)

{

    int i;

    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];

    int max_step     [4];       /* max pixel step for each plane */

    int max_step_comp[4];       /* the component for each plane which has the max pixel step */

    memset(linesizes, 0, 4*sizeof(linesizes[0]));

    if (desc->flags & PIX_FMT_HWACCEL)

        return AVERROR(EINVAL);

    if (desc->flags & PIX_FMT_BITSTREAM) {

        linesizes[0] = (width * (desc->comp[0].step_minus1+1) + 7) >> 3;

        return 0;

    }

    av_image_fill_max_pixsteps(max_step, max_step_comp, desc);

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

        int s = (max_step_comp[i] == 1 || max_step_comp[i] == 2) ? desc->log2_chroma_w : 0;

        linesizes[i] = max_step[i] * (((width + (1 << s) - 1)) >> s);

    }

    return 0;

}


static void qmp_output_type_int64(Visitor *v, const char *name, int64_t *obj,

                                  Error **errp)

{

    QmpOutputVisitor *qov = to_qov(v);

    qmp_output_add(qov, name, qint_from_int(*obj));

}


void qemu_bh_cancel(QEMUBH *bh)

{

    bh->scheduled = 0;

}


static int cdrom_probe_device(const char *filename)

{

    int fd, ret;

    int prio = 0;

    if (strstart(filename, "/dev/cd", NULL))

        prio = 50;

    fd = open(filename, O_RDONLY | O_NONBLOCK);

    if (fd < 0) {

        goto out;

    }

    /* Attempt to detect via a CDROM specific ioctl */

    ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);

    if (ret >= 0)

        prio = 100;

    close(fd);

out:

    return prio;

}


static uint64_t megasas_mmio_read(void *opaque, target_phys_addr_t addr,

                                  unsigned size)

{

    MegasasState *s = opaque;

    uint32_t retval = 0;

    switch (addr) {

    case MFI_IDB:

        retval = 0;

        break;

    case MFI_OMSG0:

    case MFI_OSP0:

        retval = (megasas_use_msix(s) ? MFI_FWSTATE_MSIX_SUPPORTED : 0) |

            (s->fw_state & MFI_FWSTATE_MASK) |

            ((s->fw_sge & 0xff) << 16) |

            (s->fw_cmds & 0xFFFF);

        break;

    case MFI_OSTS:

        if (megasas_intr_enabled(s) && s->doorbell) {

            retval = MFI_1078_RM | 1;

        }

        break;

    case MFI_OMSK:

        retval = s->intr_mask;

        break;

    case MFI_ODCR0:

        retval = s->doorbell;

        break;

    default:

        trace_megasas_mmio_invalid_readl(addr);

        break;

    }

    trace_megasas_mmio_readl(addr, retval);

    return retval;

}


static uint64_t pxa2xx_rtc_read(void *opaque, hwaddr addr,

                                unsigned size)

{

    PXA2xxRTCState *s = (PXA2xxRTCState *) opaque;

    switch (addr) {

    case RTTR:

        return s->rttr;

    case RTSR:

        return s->rtsr;

    case RTAR:

        return s->rtar;

    case RDAR1:

        return s->rdar1;

    case RDAR2:

        return s->rdar2;

    case RYAR1:

        return s->ryar1;

    case RYAR2:

        return s->ryar2;

    case SWAR1:

        return s->swar1;

    case SWAR2:

        return s->swar2;

    case PIAR:

        return s->piar;

    case RCNR:

        return s->last_rcnr +

            ((qemu_clock_get_ms(rtc_clock) - s->last_hz) << 15) /

            (1000 * ((s->rttr & 0xffff) + 1));

    case RDCR:

        return s->last_rdcr +

            ((qemu_clock_get_ms(rtc_clock) - s->last_hz) << 15) /

            (1000 * ((s->rttr & 0xffff) + 1));

    case RYCR:

        return s->last_rycr;

    case SWCR:

        if (s->rtsr & (1 << 12))

            return s->last_swcr +

                (qemu_clock_get_ms(rtc_clock) - s->last_sw) / 10;

        else

            return s->last_swcr;

    default:

        printf("%s: Bad register " REG_FMT "\n", __FUNCTION__, addr);

        break;

    }

    return 0;

}


static void test_visitor_out_union_flat(TestOutputVisitorData *data,

                                        const void *unused)

{

    QObject *arg;

    QDict *qdict;

    Error *err = NULL;

    UserDefFlatUnion *tmp = g_malloc0(sizeof(UserDefFlatUnion));

    tmp->enum1 = ENUM_ONE_VALUE1;

    tmp->string = g_strdup("str");

    tmp->value1 = g_malloc0(sizeof(UserDefA));

    /* TODO when generator bug is fixed: tmp->integer = 41; */

    tmp->value1->boolean = true;

    visit_type_UserDefFlatUnion(data->ov, &tmp, NULL, &err);

    g_assert(err == NULL);

    arg = qmp_output_get_qobject(data->qov);

    g_assert(qobject_type(arg) == QTYPE_QDICT);

    qdict = qobject_to_qdict(arg);

    g_assert_cmpstr(qdict_get_str(qdict, "enum1"), ==, "value1");

    g_assert_cmpstr(qdict_get_str(qdict, "string"), ==, "str");

    /* TODO g_assert_cmpint(qdict_get_int(qdict, "integer"), ==, 41); */

    g_assert_cmpint(qdict_get_bool(qdict, "boolean"), ==, true);

    qapi_free_UserDefFlatUnion(tmp);

    QDECREF(qdict);

}


static SaveStateEntry *find_se(const char *idstr, int instance_id)

{

    SaveStateEntry *se;

    QTAILQ_FOREACH(se, &savevm_handlers, entry) {

        if (!strcmp(se->idstr, idstr) &&

            instance_id == se->instance_id)

            return se;

    }

    return NULL;

}


av_cold void ff_vorbisdsp_init_x86(VorbisDSPContext *dsp)

{

#if HAVE_YASM

    int cpu_flags = av_get_cpu_flags();

#if ARCH_X86_32

    if (cpu_flags & AV_CPU_FLAG_3DNOW)

        dsp->vorbis_inverse_coupling = ff_vorbis_inverse_coupling_3dnow;

#endif /* ARCH_X86_32 */

    if (cpu_flags & AV_CPU_FLAG_SSE)

        dsp->vorbis_inverse_coupling = ff_vorbis_inverse_coupling_sse;

#endif /* HAVE_YASM */

}


static void output_packet(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)

{

    int ret = 0;

    /* apply the output bitstream filters, if any */

    if (ost->nb_bitstream_filters) {

        int idx;

        ret = av_bsf_send_packet(ost->bsf_ctx[0], pkt);

        if (ret < 0)

            goto finish;

        idx = 1;

        while (idx) {

            /* get a packet from the previous filter up the chain */

            ret = av_bsf_receive_packet(ost->bsf_ctx[idx - 1], pkt);

            if (ret == AVERROR(EAGAIN)) {

                ret = 0;

                idx--;

                continue;

            } else if (ret < 0)

                goto finish;

            /* send it to the next filter down the chain or to the muxer */

            if (idx < ost->nb_bitstream_filters) {

                ret = av_bsf_send_packet(ost->bsf_ctx[idx], pkt);

                if (ret < 0)

                    goto finish;

                idx++;

            } else

                write_packet(s, pkt, ost);

        }

    } else

        write_packet(s, pkt, ost);

finish:

    if (ret < 0 && ret != AVERROR_EOF) {

        av_log(NULL, AV_LOG_FATAL, "Error applying bitstream filters to an output "

               "packet for stream #%d:%d.\n", ost->file_index, ost->index);

        exit_program(1);

    }

}


static void pred_temp_direct_motion(const H264Context *const h, H264SliceContext *sl,

                                    int *mb_type)

{

    int b8_stride = 2;

    int b4_stride = h->b_stride;

    int mb_xy = sl->mb_xy, mb_y = sl->mb_y;

    int mb_type_col[2];

    const int16_t (*l1mv0)[2], (*l1mv1)[2];

    const int8_t *l1ref0, *l1ref1;

    const int is_b8x8 = IS_8X8(*mb_type);

    unsigned int sub_mb_type;

    int i8, i4;

    assert(sl->ref_list[1][0].reference & 3);

    await_reference_mb_row(h, sl->ref_list[1][0].parent,

                           sl->mb_y + !!IS_INTERLACED(*mb_type));

    if (IS_INTERLACED(sl->ref_list[1][0].parent->mb_type[mb_xy])) { // AFL/AFR/FR/FL -> AFL/FL

        if (!IS_INTERLACED(*mb_type)) {                    //     AFR/FR    -> AFL/FL

            mb_y  = (sl->mb_y & ~1) + sl->col_parity;

            mb_xy = sl->mb_x +

                    ((sl->mb_y & ~1) + sl->col_parity) * h->mb_stride;

            b8_stride = 0;

        } else {

            mb_y  += sl->col_fieldoff;

            mb_xy += h->mb_stride * sl->col_fieldoff; // non-zero for FL -> FL & differ parity

        }

        goto single_col;

    } else {                                        // AFL/AFR/FR/FL -> AFR/FR

        if (IS_INTERLACED(*mb_type)) {              // AFL       /FL -> AFR/FR

            mb_y           = sl->mb_y & ~1;

            mb_xy          = sl->mb_x + (sl->mb_y & ~1) * h->mb_stride;

            mb_type_col[0] = sl->ref_list[1][0].parent->mb_type[mb_xy];

            mb_type_col[1] = sl->ref_list[1][0].parent->mb_type[mb_xy + h->mb_stride];

            b8_stride      = 2 + 4 * h->mb_stride;

            b4_stride     *= 6;

            if (IS_INTERLACED(mb_type_col[0]) !=

                IS_INTERLACED(mb_type_col[1])) {

                mb_type_col[0] &= ~MB_TYPE_INTERLACED;

                mb_type_col[1] &= ~MB_TYPE_INTERLACED;

            }

            sub_mb_type = MB_TYPE_16x16 | MB_TYPE_P0L0 | MB_TYPE_P0L1 |

                          MB_TYPE_DIRECT2;                  /* B_SUB_8x8 */

            if ((mb_type_col[0] & MB_TYPE_16x16_OR_INTRA) &&

                (mb_type_col[1] & MB_TYPE_16x16_OR_INTRA) &&

                !is_b8x8) {

                *mb_type |= MB_TYPE_16x8 | MB_TYPE_L0L1 |

                            MB_TYPE_DIRECT2;                /* B_16x8 */

            } else {

                *mb_type |= MB_TYPE_8x8 | MB_TYPE_L0L1;

            }

        } else {                                    //     AFR/FR    -> AFR/FR

single_col:

            mb_type_col[0]     =

                mb_type_col[1] = sl->ref_list[1][0].parent->mb_type[mb_xy];

            sub_mb_type = MB_TYPE_16x16 | MB_TYPE_P0L0 | MB_TYPE_P0L1 |

                          MB_TYPE_DIRECT2;                  /* B_SUB_8x8 */

            if (!is_b8x8 && (mb_type_col[0] & MB_TYPE_16x16_OR_INTRA)) {

                *mb_type |= MB_TYPE_16x16 | MB_TYPE_P0L0 | MB_TYPE_P0L1 |

                            MB_TYPE_DIRECT2;                /* B_16x16 */

            } else if (!is_b8x8 &&

                       (mb_type_col[0] & (MB_TYPE_16x8 | MB_TYPE_8x16))) {

                *mb_type |= MB_TYPE_L0L1 | MB_TYPE_DIRECT2 |

                            (mb_type_col[0] & (MB_TYPE_16x8 | MB_TYPE_8x16));

            } else {

                if (!h->sps.direct_8x8_inference_flag) {

                    /* FIXME: save sub mb types from previous frames (or derive

                     * from MVs) so we know exactly what block size to use */

                    sub_mb_type = MB_TYPE_8x8 | MB_TYPE_P0L0 | MB_TYPE_P0L1 |

                                  MB_TYPE_DIRECT2;          /* B_SUB_4x4 */

                }

                *mb_type |= MB_TYPE_8x8 | MB_TYPE_L0L1;

            }

        }

    }

    await_reference_mb_row(h, sl->ref_list[1][0].parent, mb_y);

    l1mv0  = &sl->ref_list[1][0].parent->motion_val[0][h->mb2b_xy[mb_xy]];

    l1mv1  = &sl->ref_list[1][0].parent->motion_val[1][h->mb2b_xy[mb_xy]];

    l1ref0 = &sl->ref_list[1][0].parent->ref_index[0][4 * mb_xy];

    l1ref1 = &sl->ref_list[1][0].parent->ref_index[1][4 * mb_xy];

    if (!b8_stride) {

        if (sl->mb_y & 1) {

            l1ref0 += 2;

            l1ref1 += 2;

            l1mv0  += 2 * b4_stride;

            l1mv1  += 2 * b4_stride;

        }

    }

    {

        const int *map_col_to_list0[2] = { sl->map_col_to_list0[0],

                                           sl->map_col_to_list0[1] };

        const int *dist_scale_factor = sl->dist_scale_factor;

        int ref_offset;

        if (FRAME_MBAFF(h) && IS_INTERLACED(*mb_type)) {

            map_col_to_list0[0] = sl->map_col_to_list0_field[sl->mb_y & 1][0];

            map_col_to_list0[1] = sl->map_col_to_list0_field[sl->mb_y & 1][1];

            dist_scale_factor   = sl->dist_scale_factor_field[sl->mb_y & 1];

        }

        ref_offset = (sl->ref_list[1][0].parent->mbaff << 4) & (mb_type_col[0] >> 3);

        if (IS_INTERLACED(*mb_type) != IS_INTERLACED(mb_type_col[0])) {

            int y_shift = 2 * !IS_INTERLACED(*mb_type);

            assert(h->sps.direct_8x8_inference_flag);

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

                const int x8 = i8 & 1;

                const int y8 = i8 >> 1;

                int ref0, scale;

                const int16_t (*l1mv)[2] = l1mv0;

                if (is_b8x8 && !IS_DIRECT(sl->sub_mb_type[i8]))

                    continue;

                sl->sub_mb_type[i8] = sub_mb_type;

                fill_rectangle(&sl->ref_cache[1][scan8[i8 * 4]], 2, 2, 8, 0, 1);

                if (IS_INTRA(mb_type_col[y8])) {

                    fill_rectangle(&sl->ref_cache[0][scan8[i8 * 4]], 2, 2, 8, 0, 1);

                    fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, 0, 4);

                    fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2, 8, 0, 4);

                    continue;

                }

                ref0 = l1ref0[x8 + y8 * b8_stride];

                if (ref0 >= 0)

                    ref0 = map_col_to_list0[0][ref0 + ref_offset];

                else {

                    ref0 = map_col_to_list0[1][l1ref1[x8 + y8 * b8_stride] +

                                               ref_offset];

                    l1mv = l1mv1;

                }

                scale = dist_scale_factor[ref0];

                fill_rectangle(&sl->ref_cache[0][scan8[i8 * 4]], 2, 2, 8,

                               ref0, 1);

                {

                    const int16_t *mv_col = l1mv[x8 * 3 + y8 * b4_stride];

                    int my_col            = (mv_col[1] << y_shift) / 2;

                    int mx                = (scale * mv_col[0] + 128) >> 8;

                    int my                = (scale * my_col    + 128) >> 8;

                    fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8,

                                   pack16to32(mx, my), 4);

                    fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2, 8,

                                   pack16to32(mx - mv_col[0], my - my_col), 4);

                }

            }

            return;

        }

        /* one-to-one mv scaling */

        if (IS_16X16(*mb_type)) {

            int ref, mv0, mv1;

            fill_rectangle(&sl->ref_cache[1][scan8[0]], 4, 4, 8, 0, 1);

            if (IS_INTRA(mb_type_col[0])) {

                ref = mv0 = mv1 = 0;

            } else {

                const int ref0 = l1ref0[0] >= 0 ? map_col_to_list0[0][l1ref0[0] + ref_offset]

                                                : map_col_to_list0[1][l1ref1[0] + ref_offset];

                const int scale = dist_scale_factor[ref0];

                const int16_t *mv_col = l1ref0[0] >= 0 ? l1mv0[0] : l1mv1[0];

                int mv_l0[2];

                mv_l0[0] = (scale * mv_col[0] + 128) >> 8;

                mv_l0[1] = (scale * mv_col[1] + 128) >> 8;

                ref      = ref0;

                mv0      = pack16to32(mv_l0[0], mv_l0[1]);

                mv1      = pack16to32(mv_l0[0] - mv_col[0], mv_l0[1] - mv_col[1]);

            }

            fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);

            fill_rectangle(&sl->mv_cache[0][scan8[0]], 4, 4, 8, mv0, 4);

            fill_rectangle(&sl->mv_cache[1][scan8[0]], 4, 4, 8, mv1, 4);

        } else {

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

                const int x8 = i8 & 1;

                const int y8 = i8 >> 1;

                int ref0, scale;

                const int16_t (*l1mv)[2] = l1mv0;

                if (is_b8x8 && !IS_DIRECT(sl->sub_mb_type[i8]))

                    continue;

                sl->sub_mb_type[i8] = sub_mb_type;

                fill_rectangle(&sl->ref_cache[1][scan8[i8 * 4]], 2, 2, 8, 0, 1);

                if (IS_INTRA(mb_type_col[0])) {

                    fill_rectangle(&sl->ref_cache[0][scan8[i8 * 4]], 2, 2, 8, 0, 1);

                    fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, 0, 4);

                    fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2, 8, 0, 4);

                    continue;

                }

                assert(b8_stride == 2);

                ref0 = l1ref0[i8];

                if (ref0 >= 0)

                    ref0 = map_col_to_list0[0][ref0 + ref_offset];

                else {

                    ref0 = map_col_to_list0[1][l1ref1[i8] + ref_offset];

                    l1mv = l1mv1;

                }

                scale = dist_scale_factor[ref0];

                fill_rectangle(&sl->ref_cache[0][scan8[i8 * 4]], 2, 2, 8,

                               ref0, 1);

                if (IS_SUB_8X8(sub_mb_type)) {

                    const int16_t *mv_col = l1mv[x8 * 3 + y8 * 3 * b4_stride];

                    int mx                = (scale * mv_col[0] + 128) >> 8;

                    int my                = (scale * mv_col[1] + 128) >> 8;

                    fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8,

                                   pack16to32(mx, my), 4);

                    fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2, 8,

                                   pack16to32(mx - mv_col[0], my - mv_col[1]), 4);

                } else {

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

                        const int16_t *mv_col = l1mv[x8 * 2 + (i4 & 1) +

                                                     (y8 * 2 + (i4 >> 1)) * b4_stride];

                        int16_t *mv_l0 = sl->mv_cache[0][scan8[i8 * 4 + i4]];

                        mv_l0[0] = (scale * mv_col[0] + 128) >> 8;

                        mv_l0[1] = (scale * mv_col[1] + 128) >> 8;

                        AV_WN32A(sl->mv_cache[1][scan8[i8 * 4 + i4]],

                                 pack16to32(mv_l0[0] - mv_col[0],

                                            mv_l0[1] - mv_col[1]));

                    }

                }

            }

        }

    }

}


static int vaapi_vc1_start_frame(AVCodecContext *avctx, av_unused const uint8_t *buffer, av_unused uint32_t size)

{

    const VC1Context *v = avctx->priv_data;

    const MpegEncContext *s = &v->s;

    struct vaapi_context * const vactx = avctx->hwaccel_context;

    VAPictureParameterBufferVC1 *pic_param;

    vactx->slice_param_size = sizeof(VASliceParameterBufferVC1);

    /* Fill in VAPictureParameterBufferVC1 */

    pic_param = ff_vaapi_alloc_pic_param(vactx, sizeof(VAPictureParameterBufferVC1));

    if (!pic_param)

        return -1;

    pic_param->forward_reference_picture                            = VA_INVALID_ID;

    pic_param->backward_reference_picture                           = VA_INVALID_ID;

    pic_param->inloop_decoded_picture                               = VA_INVALID_ID;

    pic_param->sequence_fields.value                                = 0; /* reset all bits */

    pic_param->sequence_fields.bits.pulldown                        = v->broadcast;

    pic_param->sequence_fields.bits.interlace                       = v->interlace;

    pic_param->sequence_fields.bits.tfcntrflag                      = v->tfcntrflag;

    pic_param->sequence_fields.bits.finterpflag                     = v->finterpflag;

    pic_param->sequence_fields.bits.psf                             = v->psf;

    pic_param->sequence_fields.bits.multires                        = v->multires;

    pic_param->sequence_fields.bits.overlap                         = v->overlap;

    pic_param->sequence_fields.bits.syncmarker                      = v->resync_marker;

    pic_param->sequence_fields.bits.rangered                        = v->rangered;

    pic_param->sequence_fields.bits.max_b_frames                    = s->avctx->max_b_frames;

#if VA_CHECK_VERSION(0,32,0)

    pic_param->sequence_fields.bits.profile                         = v->profile;

#endif

    pic_param->coded_width                                          = s->avctx->coded_width;

    pic_param->coded_height                                         = s->avctx->coded_height;

    pic_param->entrypoint_fields.value                              = 0; /* reset all bits */

    pic_param->entrypoint_fields.bits.broken_link                   = v->broken_link;

    pic_param->entrypoint_fields.bits.closed_entry                  = v->closed_entry;

    pic_param->entrypoint_fields.bits.panscan_flag                  = v->panscanflag;

    pic_param->entrypoint_fields.bits.loopfilter                    = s->loop_filter;

    pic_param->conditional_overlap_flag                             = v->condover;

    pic_param->fast_uvmc_flag                                       = v->fastuvmc;

    pic_param->range_mapping_fields.value                           = 0; /* reset all bits */

    pic_param->range_mapping_fields.bits.luma_flag                  = v->range_mapy_flag;

    pic_param->range_mapping_fields.bits.luma                       = v->range_mapy;

    pic_param->range_mapping_fields.bits.chroma_flag                = v->range_mapuv_flag;

    pic_param->range_mapping_fields.bits.chroma                     = v->range_mapuv;

    pic_param->b_picture_fraction                                   = v->bfraction_lut_index;

    pic_param->cbp_table                                            = v->cbpcy_vlc ? v->cbpcy_vlc - ff_vc1_cbpcy_p_vlc : 0;

    pic_param->mb_mode_table                                        = 0; /* XXX: interlaced frame */

    pic_param->range_reduction_frame                                = v->rangeredfrm;

    pic_param->rounding_control                                     = v->rnd;

    pic_param->post_processing                                      = v->postproc;

    pic_param->picture_resolution_index                             = v->respic;

    pic_param->luma_scale                                           = v->lumscale;

    pic_param->luma_shift                                           = v->lumshift;

    pic_param->picture_fields.value                                 = 0; /* reset all bits */

    pic_param->picture_fields.bits.picture_type                     = vc1_get_PTYPE(v);

    pic_param->picture_fields.bits.frame_coding_mode                = v->fcm;

    pic_param->picture_fields.bits.top_field_first                  = v->tff;

    pic_param->picture_fields.bits.is_first_field                   = v->fcm == 0; /* XXX: interlaced frame */

    pic_param->picture_fields.bits.intensity_compensation           = v->mv_mode == MV_PMODE_INTENSITY_COMP;

    pic_param->raw_coding.value                                     = 0; /* reset all bits */

    pic_param->raw_coding.flags.mv_type_mb                          = v->mv_type_is_raw;

    pic_param->raw_coding.flags.direct_mb                           = v->dmb_is_raw;

    pic_param->raw_coding.flags.skip_mb                             = v->skip_is_raw;

    pic_param->raw_coding.flags.field_tx                            = 0; /* XXX: interlaced frame */

    pic_param->raw_coding.flags.forward_mb                          = 0; /* XXX: interlaced frame */

    pic_param->raw_coding.flags.ac_pred                             = v->acpred_is_raw;

    pic_param->raw_coding.flags.overflags                           = v->overflg_is_raw;

    pic_param->bitplane_present.value                               = 0; /* reset all bits */

    pic_param->bitplane_present.flags.bp_mv_type_mb                 = vc1_has_MVTYPEMB_bitplane(v);

    pic_param->bitplane_present.flags.bp_direct_mb                  = vc1_has_DIRECTMB_bitplane(v);

    pic_param->bitplane_present.flags.bp_skip_mb                    = vc1_has_SKIPMB_bitplane(v);

    pic_param->bitplane_present.flags.bp_field_tx                   = 0; /* XXX: interlaced frame */

    pic_param->bitplane_present.flags.bp_forward_mb                 = 0; /* XXX: interlaced frame */

    pic_param->bitplane_present.flags.bp_ac_pred                    = vc1_has_ACPRED_bitplane(v);

    pic_param->bitplane_present.flags.bp_overflags                  = vc1_has_OVERFLAGS_bitplane(v);

    pic_param->reference_fields.value                               = 0; /* reset all bits */

    pic_param->reference_fields.bits.reference_distance_flag        = v->refdist_flag;

    pic_param->reference_fields.bits.reference_distance             = 0; /* XXX: interlaced frame */

    pic_param->reference_fields.bits.num_reference_pictures         = 0; /* XXX: interlaced frame */

    pic_param->reference_fields.bits.reference_field_pic_indicator  = 0; /* XXX: interlaced frame */

    pic_param->mv_fields.value                                      = 0; /* reset all bits */

    pic_param->mv_fields.bits.mv_mode                               = vc1_get_MVMODE(v);

    pic_param->mv_fields.bits.mv_mode2                              = vc1_get_MVMODE2(v);

    pic_param->mv_fields.bits.mv_table                              = s->mv_table_index;

    pic_param->mv_fields.bits.two_mv_block_pattern_table            = 0; /* XXX: interlaced frame */

    pic_param->mv_fields.bits.four_mv_switch                        = 0; /* XXX: interlaced frame */

    pic_param->mv_fields.bits.four_mv_block_pattern_table           = 0; /* XXX: interlaced frame */

    pic_param->mv_fields.bits.extended_mv_flag                      = v->extended_mv;

    pic_param->mv_fields.bits.extended_mv_range                     = v->mvrange;

    pic_param->mv_fields.bits.extended_dmv_flag                     = v->extended_dmv;

    pic_param->mv_fields.bits.extended_dmv_range                    = 0; /* XXX: interlaced frame */

    pic_param->pic_quantizer_fields.value                           = 0; /* reset all bits */

    pic_param->pic_quantizer_fields.bits.dquant                     = v->dquant;

    pic_param->pic_quantizer_fields.bits.quantizer                  = v->quantizer_mode;

    pic_param->pic_quantizer_fields.bits.half_qp                    = v->halfpq;

    pic_param->pic_quantizer_fields.bits.pic_quantizer_scale        = v->pq;

    pic_param->pic_quantizer_fields.bits.pic_quantizer_type         = v->pquantizer;

    pic_param->pic_quantizer_fields.bits.dq_frame                   = v->dquantfrm;

    pic_param->pic_quantizer_fields.bits.dq_profile                 = v->dqprofile;

    pic_param->pic_quantizer_fields.bits.dq_sb_edge                 = v->dqprofile == DQPROFILE_SINGLE_EDGE  ? v->dqsbedge : 0;

    pic_param->pic_quantizer_fields.bits.dq_db_edge                 = v->dqprofile == DQPROFILE_DOUBLE_EDGES ? v->dqsbedge : 0;

    pic_param->pic_quantizer_fields.bits.dq_binary_level            = v->dqbilevel;

    pic_param->pic_quantizer_fields.bits.alt_pic_quantizer          = v->altpq;

    pic_param->transform_fields.value                               = 0; /* reset all bits */

    pic_param->transform_fields.bits.variable_sized_transform_flag  = v->vstransform;

    pic_param->transform_fields.bits.mb_level_transform_type_flag   = v->ttmbf;

    pic_param->transform_fields.bits.frame_level_transform_type     = vc1_get_TTFRM(v);

    pic_param->transform_fields.bits.transform_ac_codingset_idx1    = v->c_ac_table_index;

    pic_param->transform_fields.bits.transform_ac_codingset_idx2    = v->y_ac_table_index;

    pic_param->transform_fields.bits.intra_transform_dc_table       = v->s.dc_table_index;

    switch (s->pict_type) {

    case AV_PICTURE_TYPE_B:

        pic_param->backward_reference_picture = ff_vaapi_get_surface_id(s->next_picture.f);

        // fall-through

    case AV_PICTURE_TYPE_P:

        pic_param->forward_reference_picture = ff_vaapi_get_surface_id(s->last_picture.f);

        break;

    }

    if (pic_param->bitplane_present.value) {

        uint8_t *bitplane;

        const uint8_t *ff_bp[3];

        int x, y, n;

        switch (s->pict_type) {

        case AV_PICTURE_TYPE_P:

            ff_bp[0] = pic_param->bitplane_present.flags.bp_direct_mb  ? v->direct_mb_plane    : NULL;

            ff_bp[1] = pic_param->bitplane_present.flags.bp_skip_mb    ? s->mbskip_table       : NULL;

            ff_bp[2] = pic_param->bitplane_present.flags.bp_mv_type_mb ? v->mv_type_mb_plane   : NULL;

            break;

        case AV_PICTURE_TYPE_B:

            if (!v->bi_type) {

                ff_bp[0] = pic_param->bitplane_present.flags.bp_direct_mb ? v->direct_mb_plane : NULL;

                ff_bp[1] = pic_param->bitplane_present.flags.bp_skip_mb   ? s->mbskip_table    : NULL;

                ff_bp[2] = NULL; /* XXX: interlaced frame (FORWARD plane) */

                break;

            }

            /* fall-through (BI-type) */

        case AV_PICTURE_TYPE_I:

            ff_bp[0] = NULL; /* XXX: interlaced frame (FIELDTX plane) */

            ff_bp[1] = pic_param->bitplane_present.flags.bp_ac_pred    ? v->acpred_plane       : NULL;

            ff_bp[2] = pic_param->bitplane_present.flags.bp_overflags  ? v->over_flags_plane   : NULL;

            break;

        default:

            ff_bp[0] = NULL;

            ff_bp[1] = NULL;

            ff_bp[2] = NULL;

            break;

        }

        bitplane = ff_vaapi_alloc_bitplane(vactx, (s->mb_width * s->mb_height + 1) / 2);

        if (!bitplane)

            return -1;

        n = 0;

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

            for (x = 0; x < s->mb_width; x++, n++)

                vc1_pack_bitplanes(bitplane, n, ff_bp, x, y, s->mb_stride);

        if (n & 1) /* move last nibble to the high order */

            bitplane[n/2] <<= 4;

    }

    return 0;

}


static int read_huffman_tables(HYuvContext *s, uint8_t *src, int length){

    GetBitContext gb;

    int i;

    init_get_bits(&gb, src, length);

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

        read_len_table(s->len[i], &gb);

        if(generate_bits_table(s->bits[i], s->len[i])<0){

            return -1;

        }

#if 0

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

printf("%6X, %2d,  %3d\n", s->bits[i][j], s->len[i][j], j);

}

#endif

        init_vlc(&s->vlc[i], VLC_BITS, 256, s->len[i], 1, 1, s->bits[i], 4, 4);

    }

    return 0;

}


static void test_source_notify(void)

{

    while (g_main_context_iteration(NULL, false));

    aio_notify(ctx);

    g_assert(g_main_context_iteration(NULL, true));

    g_assert(!g_main_context_iteration(NULL, false));

}


static void virtio_crypto_dataq_bh(void *opaque)

{

    VirtIOCryptoQueue *q = opaque;

    VirtIOCrypto *vcrypto = q->vcrypto;

    VirtIODevice *vdev = VIRTIO_DEVICE(vcrypto);

    /* This happens when device was stopped but BH wasn't. */

    if (!vdev->vm_running) {

        return;

    }

    /* Just in case the driver is not ready on more */

    if (unlikely(!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK))) {

        return;

    }

    virtio_crypto_handle_dataq(vdev, q->dataq);

    virtio_queue_set_notification(q->dataq, 1);

}


static int load_dtb(hwaddr addr, const struct arm_boot_info *binfo,

                    hwaddr addr_limit)

{

    void *fdt = NULL;

    int size, rc;

    uint32_t acells, scells;

    if (binfo->dtb_filename) {

        char *filename;

        filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, binfo->dtb_filename);

        if (!filename) {

            fprintf(stderr, "Couldn't open dtb file %s\n", binfo->dtb_filename);

            goto fail;

        }

        fdt = load_device_tree(filename, &size);

        if (!fdt) {

            fprintf(stderr, "Couldn't open dtb file %s\n", filename);

            g_free(filename);

            goto fail;

        }

        g_free(filename);

    } else if (binfo->get_dtb) {

        fdt = binfo->get_dtb(binfo, &size);

        if (!fdt) {

            fprintf(stderr, "Board was unable to create a dtb blob\n");

            goto fail;

        }

    }

    if (addr_limit > addr && size > (addr_limit - addr)) {

        /* Installing the device tree blob at addr would exceed addr_limit.

         * Whether this constitutes failure is up to the caller to decide,

         * so just return 0 as size, i.e., no error.

         */

        g_free(fdt);

        return 0;

    }

    acells = qemu_fdt_getprop_cell(fdt, "/", "#address-cells");

    scells = qemu_fdt_getprop_cell(fdt, "/", "#size-cells");

    if (acells == 0 || scells == 0) {

        fprintf(stderr, "dtb file invalid (#address-cells or #size-cells 0)\n");

        goto fail;

    }

    if (scells < 2 && binfo->ram_size >= (1ULL << 32)) {

        /* This is user error so deserves a friendlier error message

         * than the failure of setprop_sized_cells would provide

         */

        fprintf(stderr, "qemu: dtb file not compatible with "

                "RAM size > 4GB\n");

        goto fail;

    }

    rc = qemu_fdt_setprop_sized_cells(fdt, "/memory", "reg",

                                      acells, binfo->loader_start,

                                      scells, binfo->ram_size);

    if (rc < 0) {

        fprintf(stderr, "couldn't set /memory/reg\n");

        goto fail;

    }

    if (binfo->kernel_cmdline && *binfo->kernel_cmdline) {

        rc = qemu_fdt_setprop_string(fdt, "/chosen", "bootargs",

                                     binfo->kernel_cmdline);

        if (rc < 0) {

            fprintf(stderr, "couldn't set /chosen/bootargs\n");

            goto fail;

        }

    }

    if (binfo->initrd_size) {

        rc = qemu_fdt_setprop_cell(fdt, "/chosen", "linux,initrd-start",

                                   binfo->initrd_start);

        if (rc < 0) {

            fprintf(stderr, "couldn't set /chosen/linux,initrd-start\n");

            goto fail;

        }

        rc = qemu_fdt_setprop_cell(fdt, "/chosen", "linux,initrd-end",

                                   binfo->initrd_start + binfo->initrd_size);

        if (rc < 0) {

            fprintf(stderr, "couldn't set /chosen/linux,initrd-end\n");

            goto fail;

        }

    }

    if (binfo->modify_dtb) {

        binfo->modify_dtb(binfo, fdt);

    }

    qemu_fdt_dumpdtb(fdt, size);

    /* Put the DTB into the memory map as a ROM image: this will ensure

     * the DTB is copied again upon reset, even if addr points into RAM.

     */

    rom_add_blob_fixed("dtb", fdt, size, addr);

    g_free(fdt);

    return size;

fail:

    g_free(fdt);

    return -1;

}


static NetSocketState *net_socket_fd_init_dgram(NetClientState *peer,

                                                const char *model,

                                                const char *name,

                                                int fd, int is_connected)

{

    struct sockaddr_in saddr;

    int newfd;

    socklen_t saddr_len = sizeof(saddr);

    NetClientState *nc;

    NetSocketState *s;

    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it

     * Because this may be "shared" socket from a "master" process, datagrams would be recv()

     * by ONLY ONE process: we must "clone" this dgram socket --jjo

     */

    if (is_connected) {

        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {

            /* must be bound */

            if (saddr.sin_addr.s_addr == 0) {

                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, "

                        "cannot setup multicast dst addr\n", fd);

                goto err;

            }

            /* clone dgram socket */

            newfd = net_socket_mcast_create(&saddr, NULL);

            if (newfd < 0) {

                /* error already reported by net_socket_mcast_create() */

                goto err;

            }

            /* clone newfd to fd, close newfd */

            dup2(newfd, fd);

            close(newfd);

        } else {

            fprintf(stderr,

                    "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",

                    fd, strerror(errno));

            goto err;

        }

    }

    nc = qemu_new_net_client(&net_dgram_socket_info, peer, model, name);

    snprintf(nc->info_str, sizeof(nc->info_str),

            "socket: fd=%d (%s mcast=%s:%d)",

            fd, is_connected ? "cloned" : "",

            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));

    s = DO_UPCAST(NetSocketState, nc, nc);

    s->fd = fd;

    s->listen_fd = -1;

    s->send_fn = net_socket_send_dgram;

    net_socket_read_poll(s, true);

    /* mcast: save bound address as dst */

    if (is_connected) {

        s->dgram_dst = saddr;

    }

    return s;

err:

    closesocket(fd);

    return NULL;

}


static int wc3_read_packet(AVFormatContext *s,

                           AVPacket *pkt)

{

    Wc3DemuxContext *wc3 = s->priv_data;

    ByteIOContext *pb = s->pb;

    unsigned int fourcc_tag;

    unsigned int size;

    int packet_read = 0;

    int ret = 0;

    unsigned char text[1024];

    unsigned int palette_number;

    int i;

    unsigned char r, g, b;

    int base_palette_index;

    while (!packet_read) {

        fourcc_tag = get_le32(pb);

        /* chunk sizes are 16-bit aligned */

        size = (get_be32(pb) + 1) & (~1);

        if (url_feof(pb))

            return AVERROR(EIO);

        switch (fourcc_tag) {

        case BRCH_TAG:

            /* no-op */

            break;

        case SHOT_TAG:

            /* load up new palette */

            palette_number = get_le32(pb);

            if (palette_number >= wc3->palette_count)

                return AVERROR_INVALIDDATA;

            base_palette_index = palette_number * PALETTE_COUNT * 3;

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

                r = wc3->palettes[base_palette_index + i * 3 + 0];

                g = wc3->palettes[base_palette_index + i * 3 + 1];

                b = wc3->palettes[base_palette_index + i * 3 + 2];

                wc3->palette_control.palette[i] = (r << 16) | (g << 8) | (b);

            }

            wc3->palette_control.palette_changed = 1;

            break;

        case VGA__TAG:

            /* send out video chunk */

            ret= av_get_packet(pb, pkt, size);

            pkt->stream_index = wc3->video_stream_index;

            pkt->pts = wc3->pts;

            packet_read = 1;

            break;

        case TEXT_TAG:

            /* subtitle chunk */

#if 0

            url_fseek(pb, size, SEEK_CUR);

#else

            if ((unsigned)size > sizeof(text) || (ret = get_buffer(pb, text, size)) != size)

                ret = AVERROR(EIO);

            else {

                int i = 0;

                av_log (s, AV_LOG_DEBUG, "Subtitle time!\n");

                av_log (s, AV_LOG_DEBUG, "  inglish: %s\n", &text[i + 1]);

                i += text[i] + 1;

                av_log (s, AV_LOG_DEBUG, "  doytsch: %s\n", &text[i + 1]);

                i += text[i] + 1;

                av_log (s, AV_LOG_DEBUG, "  fronsay: %s\n", &text[i + 1]);

            }

#endif

            break;

        case AUDI_TAG:

            /* send out audio chunk */

            ret= av_get_packet(pb, pkt, size);

            pkt->stream_index = wc3->audio_stream_index;

            pkt->pts = wc3->pts;

            /* time to advance pts */

            wc3->pts++;

            packet_read = 1;

            break;

        default:

            av_log (s, AV_LOG_ERROR, "  unrecognized WC3 chunk: %c%c%c%c (0x%02X%02X%02X%02X)\n",

                (uint8_t)fourcc_tag, (uint8_t)(fourcc_tag >> 8), (uint8_t)(fourcc_tag >> 16), (uint8_t)(fourcc_tag >> 24),

                (uint8_t)fourcc_tag, (uint8_t)(fourcc_tag >> 8), (uint8_t)(fourcc_tag >> 16), (uint8_t)(fourcc_tag >> 24));

            ret = AVERROR_INVALIDDATA;

            packet_read = 1;

            break;

        }

    }

    return ret;

}


void hmp_info_memdev(Monitor *mon, const QDict *qdict)
{
    Error *err = NULL;
    MemdevList *memdev_list = qmp_query_memdev(&err);
    MemdevList *m = memdev_list;
    StringOutputVisitor *ov;
    char *str;
    int i = 0;
    while (m) {
        ov = string_output_visitor_new(false);
        visit_type_uint16List(string_output_get_visitor(ov),
                              &m->value->host_nodes, NULL, NULL);
        monitor_printf(mon, "memory backend: %d\n", i);
        monitor_printf(mon, "  size:  %" PRId64 "\n", m->value->size);
        monitor_printf(mon, "  merge: %s\n",
                       m->value->merge ? "true" : "false");
        monitor_printf(mon, "  dump: %s\n",
                       m->value->dump ? "true" : "false");
        monitor_printf(mon, "  prealloc: %s\n",
                       m->value->prealloc ? "true" : "false");
        monitor_printf(mon, "  policy: %s\n",
                       HostMemPolicy_lookup[m->value->policy]);
        str = string_output_get_string(ov);
        monitor_printf(mon, "  host nodes: %s\n", str);
        g_free(str);
        string_output_visitor_cleanup(ov);
        m = m->next;
        i++;
    }
    monitor_printf(mon, "\n");
}


static void guest_suspend(const char *pmutils_bin, const char *sysfile_str,

                          Error **err)

{

    pid_t pid;

    char *pmutils_path;

    pmutils_path = g_find_program_in_path(pmutils_bin);

    pid = fork();

    if (pid == 0) {

        /* child */

        int fd;

        setsid();

        reopen_fd_to_null(0);

        reopen_fd_to_null(1);

        reopen_fd_to_null(2);

        if (pmutils_path) {

            execle(pmutils_path, pmutils_bin, NULL, environ);

        }

        /*

         * If we get here either pm-utils is not installed or execle() has

         * failed. Let's try the manual method if the caller wants it.

         */

        if (!sysfile_str) {

            _exit(EXIT_FAILURE);

        }

        fd = open(LINUX_SYS_STATE_FILE, O_WRONLY);

        if (fd < 0) {

            _exit(EXIT_FAILURE);

        }

        if (write(fd, sysfile_str, strlen(sysfile_str)) < 0) {

            _exit(EXIT_FAILURE);

        }

        _exit(EXIT_SUCCESS);

    }

    g_free(pmutils_path);

    if (pid < 0) {

        error_set(err, QERR_UNDEFINED_ERROR);

        return;

    }

}


static void test_qemu_strtoull_max(void)

{

    const char *str = g_strdup_printf("%llu", ULLONG_MAX);

    char f = 'X';

    const char *endptr = &f;

    uint64_t res = 999;

    int err;

    err = qemu_strtoull(str, &endptr, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, ULLONG_MAX);

    g_assert(endptr == str + strlen(str));

}


static int rate_control(AVCodecContext *avctx, void *arg)

{

    SliceArgs *slice_dat = arg;

    VC2EncContext *s = slice_dat->ctx;

    const int sx = slice_dat->x;

    const int sy = slice_dat->y;

    int quant_buf[2], bits_buf[2], quant = s->q_start, range = s->q_start/3;

    const int64_t top = slice_dat->bits_ceil;

    const double percent = s->tolerance;

    const double bottom = top - top*(percent/100.0f);

    int bits = count_hq_slice(s, sx, sy, quant);

    range -= range & 1; /* Make it an even number */

    while ((bits > top) || (bits < bottom)) {

        range *= bits > top ? +1 : -1;

        quant = av_clip(quant + range, 0, s->q_ceil);

        bits = count_hq_slice(s, sx, sy, quant);

        range = av_clip(range/2, 1, s->q_ceil);

        if (quant_buf[1] == quant) {

            quant = bits_buf[0] < bits ? quant_buf[0] : quant;

            bits = bits_buf[0] < bits ? bits_buf[0] : bits;

            break;

        }

        quant_buf[1] = quant_buf[0];

        quant_buf[0] = quant;

        bits_buf[1] = bits_buf[0];

        bits_buf[0] = bits;

    }

    slice_dat->quant_idx = av_clip(quant, 0, s->q_ceil);

    slice_dat->bytes = FFALIGN((bits >> 3), s->size_scaler) + 4 + s->prefix_bytes;

    return 0;

}


static int dmg_read_resource_fork(BlockDriverState *bs, DmgHeaderState *ds,

                                  uint64_t info_begin, uint64_t info_length)

{

    BDRVDMGState *s = bs->opaque;

    int ret;

    uint32_t count, rsrc_data_offset;

    uint8_t *buffer = NULL;

    uint64_t info_end;

    uint64_t offset;

    /* read offset from begin of resource fork (info_begin) to resource data */

    ret = read_uint32(bs, info_begin, &rsrc_data_offset);

    if (ret < 0) {

        goto fail;

    } else if (rsrc_data_offset > info_length) {

        ret = -EINVAL;

        goto fail;

    }

    /* read length of resource data */

    ret = read_uint32(bs, info_begin + 8, &count);

    if (ret < 0) {

        goto fail;

    } else if (count == 0 || rsrc_data_offset + count > info_length) {

        ret = -EINVAL;

        goto fail;

    }

    /* begin of resource data (consisting of one or more resources) */

    offset = info_begin + rsrc_data_offset;

    /* end of resource data (there is possibly a following resource map

     * which will be ignored). */

    info_end = offset + count;

    /* read offsets (mish blocks) from one or more resources in resource data */

    while (offset < info_end) {

        /* size of following resource */

        ret = read_uint32(bs, offset, &count);

        if (ret < 0) {

            goto fail;

        } else if (count == 0) {

            ret = -EINVAL;

            goto fail;

        }

        offset += 4;

        buffer = g_realloc(buffer, count);

        ret = bdrv_pread(bs->file, offset, buffer, count);

        if (ret < 0) {

            goto fail;

        }

        ret = dmg_read_mish_block(s, ds, buffer, count);

        if (ret < 0) {

            goto fail;

        }

        /* advance offset by size of resource */

        offset += count;

    }

    ret = 0;

fail:

    g_free(buffer);

    return ret;

}


static int ogg_read_page(AVFormatContext *s, int *str)

{

    AVIOContext *bc = s->pb;

    struct ogg *ogg = s->priv_data;

    struct ogg_stream *os;

    int ret, i = 0;

    int flags, nsegs;

    uint64_t gp;

    uint32_t serial;

    int size, idx;

    uint8_t sync[4];

    int sp = 0;

    ret = avio_read(bc, sync, 4);

    if (ret < 4)

        return ret < 0 ? ret : AVERROR_EOF;

    do{

        int c;

        if (sync[sp & 3] == 'O' &&

            sync[(sp + 1) & 3] == 'g' &&

            sync[(sp + 2) & 3] == 'g' && sync[(sp + 3) & 3] == 'S')

            break;

        c = avio_r8(bc);

        if (bc->eof_reached)

            return AVERROR_EOF;

        sync[sp++ & 3] = c;

    }while (i++ < MAX_PAGE_SIZE);

    if (i >= MAX_PAGE_SIZE){

        av_log (s, AV_LOG_INFO, "ogg, can't find sync word\n");

        return AVERROR_INVALIDDATA;

    }

    if (avio_r8(bc) != 0)      /* version */

        return AVERROR_INVALIDDATA;

    flags = avio_r8(bc);

    gp = avio_rl64 (bc);

    serial = avio_rl32 (bc);

    avio_skip(bc, 8); /* seq, crc */

    nsegs = avio_r8(bc);

    idx = ogg_find_stream (ogg, serial);

    if (idx < 0){

        if (ogg->headers) {

            int n;

            for (n = 0; n < ogg->nstreams; n++) {

                av_freep(&ogg->streams[n].buf);

                if (!ogg->state || ogg->state->streams[n].private != ogg->streams[n].private)

                    av_freep(&ogg->streams[n].private);

            }

            ogg->curidx   = -1;

            ogg->nstreams = 0;

            idx = ogg_new_stream(s, serial, 0);

        } else {

            idx = ogg_new_stream(s, serial, 1);

        }

        if (idx < 0)

            return idx;

    }

    os = ogg->streams + idx;

    os->page_pos = avio_tell(bc) - 27;

    if(os->psize > 0)

        ogg_new_buf(ogg, idx);

    ret = avio_read(bc, os->segments, nsegs);

    if (ret < nsegs)

        return ret < 0 ? ret : AVERROR_EOF;

    os->nsegs = nsegs;

    os->segp = 0;

    size = 0;

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

        size += os->segments[i];

    if (flags & OGG_FLAG_CONT || os->incomplete){

        if (!os->psize){

            while (os->segp < os->nsegs){

                int seg = os->segments[os->segp++];

                os->pstart += seg;

                if (seg < 255)

                    break;

            }

            os->sync_pos = os->page_pos;

        }

    }else{

        os->psize = 0;

        os->sync_pos = os->page_pos;

    }

    if (os->bufsize - os->bufpos < size){

        uint8_t *nb = av_malloc (os->bufsize *= 2);

        memcpy (nb, os->buf, os->bufpos);

        av_free (os->buf);

        os->buf = nb;

    }

    ret = avio_read(bc, os->buf + os->bufpos, size);

    if (ret < size)

        return ret < 0 ? ret : AVERROR_EOF;

    os->bufpos += size;

    os->granule = gp;

    os->flags = flags;

    if (str)

        *str = idx;

    return 0;

}


static int qdev_add_one_global(QemuOpts *opts, void *opaque)

{

    GlobalProperty *g;

    ObjectClass *oc;

    g = g_malloc0(sizeof(*g));

    g->driver   = qemu_opt_get(opts, "driver");

    g->property = qemu_opt_get(opts, "property");

    g->value    = qemu_opt_get(opts, "value");

    oc = object_class_by_name(g->driver);

    if (oc) {

        DeviceClass *dc = DEVICE_CLASS(oc);

        if (dc->hotpluggable) {

            /* If hotpluggable then skip not_used checking. */

            g->not_used = false;

        } else {

            /* Maybe a typo. */

            g->not_used = true;

        }

    } else {

        /* Maybe a typo. */

        g->not_used = true;

    }

    qdev_prop_register_global(g);

    return 0;

}


void ff_ivi_recompose53(const IVIPlaneDesc *plane, uint8_t *dst,

                        const ptrdiff_t dst_pitch)

{

    int             x, y, indx;

    int32_t         p0, p1, p2, p3, tmp0, tmp1, tmp2;

    int32_t         b0_1, b0_2, b1_1, b1_2, b1_3, b2_1, b2_2, b2_3, b2_4, b2_5, b2_6;

    int32_t         b3_1, b3_2, b3_3, b3_4, b3_5, b3_6, b3_7, b3_8, b3_9;

    ptrdiff_t       pitch, back_pitch;

    const short     *b0_ptr, *b1_ptr, *b2_ptr, *b3_ptr;

    const int       num_bands = 4;

    /* all bands should have the same pitch */

    pitch = plane->bands[0].pitch;

    /* pixels at the position "y-1" will be set to pixels at the "y" for the 1st iteration */

    back_pitch = 0;

    /* get pointers to the wavelet bands */

    b0_ptr = plane->bands[0].buf;

    b1_ptr = plane->bands[1].buf;

    b2_ptr = plane->bands[2].buf;

    b3_ptr = plane->bands[3].buf;

    for (y = 0; y < plane->height; y += 2) {

        if (y+2 >= plane->height)

            pitch= 0;

        /* load storage variables with values */

        if (num_bands > 0) {

            b0_1 = b0_ptr[0];

            b0_2 = b0_ptr[pitch];

        }

        if (num_bands > 1) {

            b1_1 = b1_ptr[back_pitch];

            b1_2 = b1_ptr[0];

            b1_3 = b1_1 - b1_2*6 + b1_ptr[pitch];

        }

        if (num_bands > 2) {

            b2_2 = b2_ptr[0];     // b2[x,  y  ]

            b2_3 = b2_2;          // b2[x+1,y  ] = b2[x,y]

            b2_5 = b2_ptr[pitch]; // b2[x  ,y+1]

            b2_6 = b2_5;          // b2[x+1,y+1] = b2[x,y+1]

        }

        if (num_bands > 3) {

            b3_2 = b3_ptr[back_pitch]; // b3[x  ,y-1]

            b3_3 = b3_2;               // b3[x+1,y-1] = b3[x  ,y-1]

            b3_5 = b3_ptr[0];          // b3[x  ,y  ]

            b3_6 = b3_5;               // b3[x+1,y  ] = b3[x  ,y  ]

            b3_8 = b3_2 - b3_5*6 + b3_ptr[pitch];

            b3_9 = b3_8;

        }

        for (x = 0, indx = 0; x < plane->width; x+=2, indx++) {

            if (x+2 >= plane->width) {

                b0_ptr --;

                b1_ptr --;

                b2_ptr --;

                b3_ptr --;

            }

            /* some values calculated in the previous iterations can */

            /* be reused in the next ones, so do appropriate copying */

            b2_1 = b2_2; // b2[x-1,y  ] = b2[x,  y  ]

            b2_2 = b2_3; // b2[x  ,y  ] = b2[x+1,y  ]

            b2_4 = b2_5; // b2[x-1,y+1] = b2[x  ,y+1]

            b2_5 = b2_6; // b2[x  ,y+1] = b2[x+1,y+1]

            b3_1 = b3_2; // b3[x-1,y-1] = b3[x  ,y-1]

            b3_2 = b3_3; // b3[x  ,y-1] = b3[x+1,y-1]

            b3_4 = b3_5; // b3[x-1,y  ] = b3[x  ,y  ]

            b3_5 = b3_6; // b3[x  ,y  ] = b3[x+1,y  ]

            b3_7 = b3_8; // vert_HPF(x-1)

            b3_8 = b3_9; // vert_HPF(x  )

            p0 = p1 = p2 = p3 = 0;

            /* process the LL-band by applying LPF both vertically and horizontally */

            if (num_bands > 0) {

                tmp0 = b0_1;

                tmp2 = b0_2;

                b0_1 = b0_ptr[indx+1];

                b0_2 = b0_ptr[pitch+indx+1];

                tmp1 = tmp0 + b0_1;

                p0 =  tmp0 << 4;

                p1 =  tmp1 << 3;

                p2 = (tmp0 + tmp2) << 3;

                p3 = (tmp1 + tmp2 + b0_2) << 2;

            }

            /* process the HL-band by applying HPF vertically and LPF horizontally */

            if (num_bands > 1) {

                tmp0 = b1_2;

                tmp1 = b1_1;

                b1_2 = b1_ptr[indx+1];

                b1_1 = b1_ptr[back_pitch+indx+1];

                tmp2 = tmp1 - tmp0*6 + b1_3;

                b1_3 = b1_1 - b1_2*6 + b1_ptr[pitch+indx+1];

                p0 += (tmp0 + tmp1) << 3;

                p1 += (tmp0 + tmp1 + b1_1 + b1_2) << 2;

                p2 +=  tmp2 << 2;

                p3 += (tmp2 + b1_3) << 1;

            }

            /* process the LH-band by applying LPF vertically and HPF horizontally */

            if (num_bands > 2) {

                b2_3 = b2_ptr[indx+1];

                b2_6 = b2_ptr[pitch+indx+1];

                tmp0 = b2_1 + b2_2;

                tmp1 = b2_1 - b2_2*6 + b2_3;

                p0 += tmp0 << 3;

                p1 += tmp1 << 2;

                p2 += (tmp0 + b2_4 + b2_5) << 2;

                p3 += (tmp1 + b2_4 - b2_5*6 + b2_6) << 1;

            }

            /* process the HH-band by applying HPF both vertically and horizontally */

            if (num_bands > 3) {

                b3_6 = b3_ptr[indx+1];            // b3[x+1,y  ]

                b3_3 = b3_ptr[back_pitch+indx+1]; // b3[x+1,y-1]

                tmp0 = b3_1 + b3_4;

                tmp1 = b3_2 + b3_5;

                tmp2 = b3_3 + b3_6;

                b3_9 = b3_3 - b3_6*6 + b3_ptr[pitch+indx+1];

                p0 += (tmp0 + tmp1) << 2;

                p1 += (tmp0 - tmp1*6 + tmp2) << 1;

                p2 += (b3_7 + b3_8) << 1;

                p3 +=  b3_7 - b3_8*6 + b3_9;

            }

            /* output four pixels */

            dst[x]             = av_clip_uint8((p0 >> 6) + 128);

            dst[x+1]           = av_clip_uint8((p1 >> 6) + 128);

            dst[dst_pitch+x]   = av_clip_uint8((p2 >> 6) + 128);

            dst[dst_pitch+x+1] = av_clip_uint8((p3 >> 6) + 128);

        }// for x

        dst += dst_pitch << 1;

        back_pitch = -pitch;

        b0_ptr += pitch + 1;

        b1_ptr += pitch + 1;

        b2_ptr += pitch + 1;

        b3_ptr += pitch + 1;

    }

}


void virtio_scsi_common_realize(DeviceState *dev, Error **errp)

{

    VirtIODevice *vdev = VIRTIO_DEVICE(dev);

    VirtIOSCSICommon *s = VIRTIO_SCSI_COMMON(dev);

    int i;

    virtio_init(vdev, "virtio-scsi", VIRTIO_ID_SCSI,

                sizeof(VirtIOSCSIConfig));

    s->cmd_vqs = g_malloc0(s->conf.num_queues * sizeof(VirtQueue *));

    s->sense_size = VIRTIO_SCSI_SENSE_SIZE;

    s->cdb_size = VIRTIO_SCSI_CDB_SIZE;

    s->ctrl_vq = virtio_add_queue(vdev, VIRTIO_SCSI_VQ_SIZE,

                                  virtio_scsi_handle_ctrl);

    s->event_vq = virtio_add_queue(vdev, VIRTIO_SCSI_VQ_SIZE,

                                   virtio_scsi_handle_event);

    for (i = 0; i < s->conf.num_queues; i++) {

        s->cmd_vqs[i] = virtio_add_queue(vdev, VIRTIO_SCSI_VQ_SIZE,

                                         virtio_scsi_handle_cmd);

    }

}


static CharDriverState *qemu_chr_open_udp_fd(int fd)

{

    CharDriverState *chr = NULL;

    NetCharDriver *s = NULL;

    chr = qemu_chr_alloc();

    s = g_malloc0(sizeof(NetCharDriver));

    s->fd = fd;

    s->chan = io_channel_from_socket(s->fd);

    s->bufcnt = 0;

    s->bufptr = 0;

    chr->opaque = s;

    chr->chr_write = udp_chr_write;

    chr->chr_update_read_handler = udp_chr_update_read_handler;

    chr->chr_close = udp_chr_close;

    /* be isn't opened until we get a connection */

    chr->explicit_be_open = true;

    return chr;

}


static int genh_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    AVCodecContext *codec = s->streams[0]->codec;

    GENHDemuxContext *c = s->priv_data;

    int ret;

    if (c->dsp_int_type == 1 && codec->codec_id == AV_CODEC_ID_ADPCM_THP &&

        codec->channels > 1) {

        int i, ch;

        if (avio_feof(s->pb))

            return AVERROR_EOF;

        av_new_packet(pkt, 8 * codec->channels);

        for (i = 0; i < 8 / c->interleave_size; i++) {

            for (ch = 0; ch < codec->channels; ch++) {

                pkt->data[ch * 8 + i*c->interleave_size+0] = avio_r8(s->pb);

                pkt->data[ch * 8 + i*c->interleave_size+1] = avio_r8(s->pb);

            }

        }

        ret = 0;

    } else {

        ret = av_get_packet(s->pb, pkt, codec->block_align ? codec->block_align : 1024 * codec->channels);

    }

    pkt->stream_index = 0;

    return ret;

}


static void balloon_page(void *addr, int deflate)

{

#if defined(__linux__)

    if (!kvm_enabled() || kvm_has_sync_mmu())

        madvise(addr, TARGET_PAGE_SIZE,

                deflate ? MADV_WILLNEED : MADV_DONTNEED);

#endif

}


static void test_self(void)

{

    Coroutine *coroutine;

    coroutine = qemu_coroutine_create(verify_self);

    qemu_coroutine_enter(coroutine, &coroutine);

}


static void gen_wrteei(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    if (ctx->opcode & 0x00008000) {

        tcg_gen_ori_tl(cpu_msr, cpu_msr, (1 << MSR_EE));

        /* Stop translation to have a chance to raise an exception */

        gen_stop_exception(ctx);

    } else {

        tcg_gen_andi_tl(cpu_msr, cpu_msr, ~(1 << MSR_EE));

    }

#endif

}


void qemu_put_be16(QEMUFile *f, unsigned int v)

{

    qemu_put_byte(f, v >> 8);

    qemu_put_byte(f, v);

}