static int mpeg4_unpack_bframes_filter(AVBSFContext *ctx, AVPacket *out)

{

    UnpackBFramesBSFContext *s = ctx->priv_data;

    int pos_p = -1, nb_vop = 0, pos_vop2 = -1, ret = 0;

    AVPacket *in;

    ret = ff_bsf_get_packet(ctx, &in);

    if (ret < 0)

        return ret;

    scan_buffer(in->data, in->size, &pos_p, &nb_vop, &pos_vop2);

    av_log(ctx, AV_LOG_DEBUG, "Found %d VOP startcode(s) in this packet.\n", nb_vop);

    if (pos_vop2 >= 0) {

        if (s->b_frame_buf) {

            av_log(ctx, AV_LOG_WARNING,

                   "Missing one N-VOP packet, discarding one B-frame.\n");

            av_freep(&s->b_frame_buf);

            s->b_frame_buf_size = 0;

        }

        /* store the packed B-frame in the BSFContext */

        s->b_frame_buf_size = in->size - pos_vop2;

        s->b_frame_buf      = create_new_buffer(in->data + pos_vop2, s->b_frame_buf_size);

        if (!s->b_frame_buf) {

            s->b_frame_buf_size = 0;

            av_packet_free(&in);

            return AVERROR(ENOMEM);

        }

    }

    if (nb_vop > 2) {

        av_log(ctx, AV_LOG_WARNING,

       "Found %d VOP headers in one packet, only unpacking one.\n", nb_vop);

    }

    if (nb_vop == 1 && s->b_frame_buf) {

        /* use frame from BSFContext */

        ret = av_packet_copy_props(out, in);

        if (ret < 0) {

            av_packet_free(&in);

            return ret;

        }

        av_packet_from_data(out, s->b_frame_buf, s->b_frame_buf_size);

        if (in->size <= MAX_NVOP_SIZE) {

            /* N-VOP */

            av_log(ctx, AV_LOG_DEBUG, "Skipping N-VOP.\n");

            s->b_frame_buf      = NULL;

            s->b_frame_buf_size = 0;

        } else {

            /* copy packet into BSFContext */

            s->b_frame_buf_size = in->size;

            s->b_frame_buf      = create_new_buffer(in->data, in->size);

            if (!s->b_frame_buf) {

                s->b_frame_buf_size = 0;

                av_packet_unref(out);

                av_packet_free(&in);

                return AVERROR(ENOMEM);

            }

        }

    } else if (nb_vop >= 2) {

        /* use first frame of the packet */

        av_packet_move_ref(out, in);

        out->size = pos_vop2;

    } else if (pos_p >= 0) {

        av_log(ctx, AV_LOG_DEBUG, "Updating DivX userdata (remove trailing 'p').\n");

        av_packet_move_ref(out, in);

        /* remove 'p' (packed) from the end of the (DivX) userdata string */

        out->data[pos_p] = '\0';

    } else {

        /* copy packet */

        av_packet_move_ref(out, in);

    }

    av_packet_free(&in);

    return 0;

}


static int set_string_number(void *obj, void *target_obj, const AVOption *o, const char *val, void *dst)

{

    int ret = 0;

    int num, den;

    char c;

    if (sscanf(val, "%d%*1[:/]%d%c", &num, &den, &c) == 2) {

        if ((ret = write_number(obj, o, dst, 1, den, num)) >= 0)

            return ret;

        ret = 0;

    }

    for (;;) {

        int i = 0;

        char buf[256];

        int cmd = 0;

        double d;

        int64_t intnum = 1;

        if (o->type == AV_OPT_TYPE_FLAGS) {

            if (*val == '+' || *val == '-')

                cmd = *(val++);

            for (; i < sizeof(buf) - 1 && val[i] && val[i] != '+' && val[i] != '-'; i++)

                buf[i] = val[i];

            buf[i] = 0;

        }

        {

            const AVOption *o_named = av_opt_find(target_obj, buf, o->unit, 0, 0);

            int res;

            int ci = 0;

            double const_values[64];

            const char * const_names[64];

            if (o_named && o_named->type == AV_OPT_TYPE_CONST)

                d = DEFAULT_NUMVAL(o_named);

            else {

                if (o->unit) {

                    for (o_named = NULL; o_named = av_opt_next(target_obj, o_named); ) {

                        if (o_named->type == AV_OPT_TYPE_CONST &&

                            o_named->unit &&

                            !strcmp(o_named->unit, o->unit)) {

                            if (ci + 6 >= FF_ARRAY_ELEMS(const_values)) {

                                av_log(obj, AV_LOG_ERROR, "const_values array too small for %s\n", o->unit);

                                return AVERROR_PATCHWELCOME;

                            }

                            const_names [ci  ] = o_named->name;

                            const_values[ci++] = DEFAULT_NUMVAL(o_named);

                        }

                    }

                }

                const_names [ci  ] = "default";

                const_values[ci++] = DEFAULT_NUMVAL(o);

                const_names [ci  ] = "max";

                const_values[ci++] = o->max;

                const_names [ci  ] = "min";

                const_values[ci++] = o->min;

                const_names [ci  ] = "none";

                const_values[ci++] = 0;

                const_names [ci  ] = "all";

                const_values[ci++] = ~0;

                const_names [ci] = NULL;

                const_values[ci] = 0;

                res = av_expr_parse_and_eval(&d, i ? buf : val, const_names,

                                            const_values, NULL, NULL, NULL, NULL, NULL, 0, obj);

                if (res < 0) {

                    av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\"\n", val);

                    return res;

                }

            }

        }

        if (o->type == AV_OPT_TYPE_FLAGS) {

            read_number(o, dst, NULL, NULL, &intnum);

            if      (cmd == '+') d = intnum | (int64_t)d;

            else if (cmd == '-') d = intnum &~(int64_t)d;

        }

        if ((ret = write_number(obj, o, dst, d, 1, 1)) < 0)

            return ret;

        val += i;

        if (!i || !*val)

            return 0;

    }

    return 0;

}


static void qmp_input_pop(QmpInputVisitor *qiv, Error **errp)

{

    StackObject *tos = &qiv->stack[qiv->nb_stack - 1];

    assert(qiv->nb_stack > 0);

    if (qiv->strict) {

        GHashTable *const top_ht = tos->h;

        if (top_ht) {

            GHashTableIter iter;

            const char *key;

            g_hash_table_iter_init(&iter, top_ht);

            if (g_hash_table_iter_next(&iter, (void **)&key, NULL)) {

                error_setg(errp, QERR_QMP_EXTRA_MEMBER, key);

            }

            g_hash_table_unref(top_ht);

        }

        tos->h = NULL;

    }

    qiv->nb_stack--;

}


static void large_dict(void)

{

    GString *gstr = g_string_new("");

    QObject *obj;

    gen_test_json(gstr, 10, 100);

    obj = qobject_from_json(gstr->str, NULL);

    g_assert(obj != NULL);

    qobject_decref(obj);

    g_string_free(gstr, true);

}


static uint32_t m25p80_transfer8(SSISlave *ss, uint32_t tx)

{

    Flash *s = M25P80(ss);

    uint32_t r = 0;

    switch (s->state) {

    case STATE_PAGE_PROGRAM:

        DB_PRINT_L(1, "page program cur_addr=%#" PRIx64 " data=%" PRIx8 "\n",

                   s->cur_addr, (uint8_t)tx);

        flash_write8(s, s->cur_addr, (uint8_t)tx);

        s->cur_addr++;

        break;

    case STATE_READ:

        r = s->storage[s->cur_addr];

        DB_PRINT_L(1, "READ 0x%" PRIx64 "=%" PRIx8 "\n", s->cur_addr,

                   (uint8_t)r);

        s->cur_addr = (s->cur_addr + 1) % s->size;

        break;

    case STATE_COLLECTING_DATA:

    case STATE_COLLECTING_VAR_LEN_DATA:

        s->data[s->len] = (uint8_t)tx;

        s->len++;

        if (s->len == s->needed_bytes) {

            complete_collecting_data(s);

        }

        break;

    case STATE_READING_DATA:

        r = s->data[s->pos];

        s->pos++;

        if (s->pos == s->len) {

            s->pos = 0;

            s->state = STATE_IDLE;

        }

        break;

    default:

    case STATE_IDLE:

        decode_new_cmd(s, (uint8_t)tx);

        break;

    }

    return r;

}


static void dec_scall(DisasContext *dc)

{

    if (dc->imm5 == 7) {

        LOG_DIS("scall\n");

    } else if (dc->imm5 == 2) {

        LOG_DIS("break\n");

    } else {

        cpu_abort(dc->env, "invalid opcode\n");

    }

    if (dc->imm5 == 7) {

        tcg_gen_movi_tl(cpu_pc, dc->pc);

        t_gen_raise_exception(dc, EXCP_SYSTEMCALL);

    } else {

        tcg_gen_movi_tl(cpu_pc, dc->pc);

        t_gen_raise_exception(dc, EXCP_BREAKPOINT);

    }

}


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.len;

    } else {

        ret = USB_RET_NODEV;

        for (i = 0; i < ohci->num_ports; i++) {

            dev = ohci->rhport[i].port.dev;

            if ((ohci->rhport[i].ctrl & OHCI_PORT_PES) == 0)

                continue;

            ohci->usb_packet.pid = pid;

            ohci->usb_packet.devaddr = OHCI_BM(ed->flags, ED_FA);

            ohci->usb_packet.devep = OHCI_BM(ed->flags, ED_EN);

            ohci->usb_packet.data = ohci->usb_buf;

            ohci->usb_packet.len = len;

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

            if (ret != USB_RET_NODEV)

                break;

        }

        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;

}


int spapr_vio_send_crq(VIOsPAPRDevice *dev, uint8_t *crq)

{

    int rc;

    uint8_t byte;

    if (!dev->crq.qsize) {

        fprintf(stderr, "spapr_vio_send_creq on uninitialized queue\n");

        return -1;

    }

    /* Maybe do a fast path for KVM just writing to the pages */

    rc = spapr_tce_dma_read(dev, dev->crq.qladdr + dev->crq.qnext, &byte, 1);

    if (rc) {

        return rc;

    }

    if (byte != 0) {

        return 1;

    }

    rc = spapr_tce_dma_write(dev, dev->crq.qladdr + dev->crq.qnext + 8,

                             &crq[8], 8);

    if (rc) {

        return rc;

    }

    kvmppc_eieio();

    rc = spapr_tce_dma_write(dev, dev->crq.qladdr + dev->crq.qnext, crq, 8);

    if (rc) {

        return rc;

    }

    dev->crq.qnext = (dev->crq.qnext + 16) % dev->crq.qsize;

    if (dev->signal_state & 1) {

        qemu_irq_pulse(dev->qirq);

    }

    return 0;

}


static void vhost_log_put(struct vhost_dev *dev, bool sync)

{

    struct vhost_log *log = dev->log;

    if (!log) {

        return;

    }

    dev->log = NULL;

    dev->log_size = 0;

    --log->refcnt;

    if (log->refcnt == 0) {

        /* Sync only the range covered by the old log */

        if (dev->log_size && sync) {

            vhost_log_sync_range(dev, 0, dev->log_size * VHOST_LOG_CHUNK - 1);

        }

        if (vhost_log == log) {

            g_free(log->log);

            vhost_log = NULL;

        } else if (vhost_log_shm == log) {

            qemu_memfd_free(log->log, log->size * sizeof(*(log->log)),

                            log->fd);

            vhost_log_shm = NULL;

        }

        g_free(log);

    }

}


static void mirror_set_speed(BlockJob *job, int64_t speed, Error **errp)

{

    MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);

    if (speed < 0) {

        error_setg(errp, QERR_INVALID_PARAMETER, "speed");

        return;

    }

    ratelimit_set_speed(&s->limit, speed / BDRV_SECTOR_SIZE, SLICE_TIME);

}


static uint16_t nvme_map_prp(QEMUSGList *qsg, QEMUIOVector *iov, uint64_t prp1,

                             uint64_t prp2, uint32_t len, NvmeCtrl *n)

{

    hwaddr trans_len = n->page_size - (prp1 % n->page_size);

    trans_len = MIN(len, trans_len);

    int num_prps = (len >> n->page_bits) + 1;

    if (!prp1) {

        return NVME_INVALID_FIELD | NVME_DNR;

    } else if (n->cmbsz && prp1 >= n->ctrl_mem.addr &&

               prp1 < n->ctrl_mem.addr + int128_get64(n->ctrl_mem.size)) {

        qsg->nsg = 0;

        qemu_iovec_init(iov, num_prps);

        qemu_iovec_add(iov, (void *)&n->cmbuf[prp1 - n->ctrl_mem.addr], trans_len);

    } else {

        pci_dma_sglist_init(qsg, &n->parent_obj, num_prps);

        qemu_sglist_add(qsg, prp1, trans_len);

    }

    len -= trans_len;

    if (len) {

        if (!prp2) {

            goto unmap;

        }

        if (len > n->page_size) {

            uint64_t prp_list[n->max_prp_ents];

            uint32_t nents, prp_trans;

            int i = 0;

            nents = (len + n->page_size - 1) >> n->page_bits;

            prp_trans = MIN(n->max_prp_ents, nents) * sizeof(uint64_t);

            nvme_addr_read(n, prp2, (void *)prp_list, prp_trans);

            while (len != 0) {

                uint64_t prp_ent = le64_to_cpu(prp_list[i]);

                if (i == n->max_prp_ents - 1 && len > n->page_size) {

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

                        goto unmap;

                    }

                    i = 0;

                    nents = (len + n->page_size - 1) >> n->page_bits;

                    prp_trans = MIN(n->max_prp_ents, nents) * sizeof(uint64_t);

                    nvme_addr_read(n, prp_ent, (void *)prp_list,

                        prp_trans);

                    prp_ent = le64_to_cpu(prp_list[i]);

                }

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

                    goto unmap;

                }

                trans_len = MIN(len, n->page_size);

                if (qsg->nsg){

                    qemu_sglist_add(qsg, prp_ent, trans_len);

                } else {

                    qemu_iovec_add(iov, (void *)&n->cmbuf[prp_ent - n->ctrl_mem.addr], trans_len);

                }

                len -= trans_len;

                i++;

            }

        } else {

            if (prp2 & (n->page_size - 1)) {

                goto unmap;

            }

            if (qsg->nsg) {

                qemu_sglist_add(qsg, prp2, len);

            } else {

                qemu_iovec_add(iov, (void *)&n->cmbuf[prp2 - n->ctrl_mem.addr], trans_len);

            }

        }

    }

    return NVME_SUCCESS;

 unmap:

    qemu_sglist_destroy(qsg);

    return NVME_INVALID_FIELD | NVME_DNR;

}


static int init_input(AVFormatContext *s, const char *filename, AVDictionary **options)

{

    int ret;

    AVProbeData pd = {filename, NULL, 0};

    if(s->iformat && !strlen(filename))

        return 0;

    if (s->pb) {

        s->flags |= AVFMT_FLAG_CUSTOM_IO;

        if (!s->iformat)

            return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, 0);

        else if (s->iformat->flags & AVFMT_NOFILE)

            av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "

                                      "will be ignored with AVFMT_NOFILE format.\n");

        return 0;

    }

    if ( (s->iformat && s->iformat->flags & AVFMT_NOFILE) ||

        (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0))))

        return 0;

    if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ,

                          &s->interrupt_callback, options)) < 0)

        return ret;

    if (s->iformat)

        return 0;

    return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, 0);

}


static GuestPCIAddress *get_pci_info(char *guid, Error **errp)

{

    HDEVINFO dev_info;

    SP_DEVINFO_DATA dev_info_data;

    DWORD size = 0;

    int i;

    char dev_name[MAX_PATH];

    char *buffer = NULL;

    GuestPCIAddress *pci = NULL;

    char *name = g_strdup(&guid[4]);

    if (!QueryDosDevice(name, dev_name, ARRAY_SIZE(dev_name))) {

        error_setg_win32(errp, GetLastError(), "failed to get dos device name");

        goto out;

    }

    dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_VOLUME, 0, 0,

                                   DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

    if (dev_info == INVALID_HANDLE_VALUE) {

        error_setg_win32(errp, GetLastError(), "failed to get devices tree");

        goto out;

    }

    dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);

    for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {

        DWORD addr, bus, slot, func, dev, data, size2;

        while (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,

                                            SPDRP_PHYSICAL_DEVICE_OBJECT_NAME,

                                            &data, (PBYTE)buffer, size,

                                            &size2)) {

            size = MAX(size, size2);

            if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {

                g_free(buffer);

                /* Double the size to avoid problems on

                 * W2k MBCS systems per KB 888609.

                 * https://support.microsoft.com/en-us/kb/259695 */

                buffer = g_malloc(size * 2);

            } else {

                error_setg_win32(errp, GetLastError(),

                        "failed to get device name");

                goto out;

            }

        }

        if (g_strcmp0(buffer, dev_name)) {

            continue;

        }

        /* There is no need to allocate buffer in the next functions. The size

         * is known and ULONG according to

         * https://support.microsoft.com/en-us/kb/253232

         * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx

         */

        if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,

                   SPDRP_BUSNUMBER, &data, (PBYTE)&bus, size, NULL)) {

            break;

        }

        /* The function retrieves the device's address. This value will be

         * transformed into device function and number */

        if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,

                   SPDRP_ADDRESS, &data, (PBYTE)&addr, size, NULL)) {

            break;

        }

        /* This call returns UINumber of DEVICE_CAPABILITIES structure.

         * This number is typically a user-perceived slot number. */

        if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,

                   SPDRP_UI_NUMBER, &data, (PBYTE)&slot, size, NULL)) {

            break;

        }

        /* SetupApi gives us the same information as driver with

         * IoGetDeviceProperty. According to Microsoft

         * https://support.microsoft.com/en-us/kb/253232

         * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF);

         * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF);

         * SPDRP_ADDRESS is propertyAddress, so we do the same.*/

        func = addr & 0x0000FFFF;

        dev = (addr >> 16) & 0x0000FFFF;

        pci = g_malloc0(sizeof(*pci));

        pci->domain = dev;

        pci->slot = slot;

        pci->function = func;

        pci->bus = bus;

        break;

    }

out:

    g_free(buffer);

    g_free(name);

    return pci;

}


int target_get_monitor_def(CPUState *cs, const char *name, uint64_t *pval)

{

    int i, regnum;

    PowerPCCPU *cpu = POWERPC_CPU(cs);

    CPUPPCState *env = &cpu->env;

    /* General purpose registers */

    if ((tolower(name[0]) == 'r') &&

        ppc_cpu_get_reg_num(name + 1, ARRAY_SIZE(env->gpr), &regnum)) {

        *pval = env->gpr[regnum];

        return 0;

    }

    /* Floating point registers */

    if ((tolower(name[0]) == 'f') &&

        ppc_cpu_get_reg_num(name + 1, ARRAY_SIZE(env->fpr), &regnum)) {

        *pval = env->fpr[regnum];

        return 0;

    }

    /* Special purpose registers */

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

        ppc_spr_t *spr = &env->spr_cb[i];

        if (spr->name && (strcasecmp(name, spr->name) == 0)) {

            *pval = env->spr[i];

            return 0;

        }

    }

    /* Segment registers */

#if !defined(CONFIG_USER_ONLY)

    if ((strncasecmp(name, "sr", 2) == 0) &&

        ppc_cpu_get_reg_num(name + 2, ARRAY_SIZE(env->sr), &regnum)) {

        *pval = env->sr[regnum];

        return 0;

    }

#endif

    return -EINVAL;

}


PPC_OP(update_nip)

{

    env->nip = PARAM(1);

    RETURN();

}


static int mpeg1_decode_sequence(AVCodecContext *avctx,

                                 const uint8_t *buf, int buf_size)

{

    Mpeg1Context *s1  = avctx->priv_data;

    MpegEncContext *s = &s1->mpeg_enc_ctx;

    int width, height;

    int i, v, j;

    init_get_bits(&s->gb, buf, buf_size * 8);

    width  = get_bits(&s->gb, 12);

    height = get_bits(&s->gb, 12);

    if (width == 0 || height == 0) {

        av_log(avctx, AV_LOG_WARNING,

               "Invalid horizontal or vertical size value.\n");

        if (avctx->err_recognition & (AV_EF_BITSTREAM | AV_EF_COMPLIANT))

            return AVERROR_INVALIDDATA;

    }

    s->aspect_ratio_info = get_bits(&s->gb, 4);

    if (s->aspect_ratio_info == 0) {

        av_log(avctx, AV_LOG_ERROR, "aspect ratio has forbidden 0 value\n");

        if (avctx->err_recognition & (AV_EF_BITSTREAM | AV_EF_COMPLIANT))

            return AVERROR_INVALIDDATA;

    }

    s->frame_rate_index = get_bits(&s->gb, 4);

    if (s->frame_rate_index == 0 || s->frame_rate_index > 13) {

        av_log(avctx, AV_LOG_WARNING,

               "frame_rate_index %d is invalid\n", s->frame_rate_index);

        s->frame_rate_index = 1;

    }

    s->bit_rate = get_bits(&s->gb, 18) * 400;

    if (check_marker(&s->gb, "in sequence header") == 0) {

        return AVERROR_INVALIDDATA;

    }

    s->avctx->rc_buffer_size = get_bits(&s->gb, 10) * 1024 * 16;

    skip_bits(&s->gb, 1);

    /* get matrix */

    if (get_bits1(&s->gb)) {

        load_matrix(s, s->chroma_intra_matrix, s->intra_matrix, 1);

    } else {

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

            j = s->idsp.idct_permutation[i];

            v = ff_mpeg1_default_intra_matrix[i];

            s->intra_matrix[j]        = v;

            s->chroma_intra_matrix[j] = v;

        }

    }

    if (get_bits1(&s->gb)) {

        load_matrix(s, s->chroma_inter_matrix, s->inter_matrix, 0);

    } else {

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

            int j = s->idsp.idct_permutation[i];

            v = ff_mpeg1_default_non_intra_matrix[i];

            s->inter_matrix[j]        = v;

            s->chroma_inter_matrix[j] = v;

        }

    }

    if (show_bits(&s->gb, 23) != 0) {

        av_log(s->avctx, AV_LOG_ERROR, "sequence header damaged\n");

        return AVERROR_INVALIDDATA;

    }

    s->width  = width;

    s->height = height;

    /* We set MPEG-2 parameters so that it emulates MPEG-1. */

    s->progressive_sequence = 1;

    s->progressive_frame    = 1;

    s->picture_structure    = PICT_FRAME;

    s->first_field          = 0;

    s->frame_pred_frame_dct = 1;

    s->chroma_format        = 1;

    s->codec_id             =

    s->avctx->codec_id      = AV_CODEC_ID_MPEG1VIDEO;

    s->out_format           = FMT_MPEG1;

    s->swap_uv              = 0; // AFAIK VCR2 does not have SEQ_HEADER

    if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)

        s->low_delay = 1;

    if (s->avctx->debug & FF_DEBUG_PICT_INFO)

        av_log(s->avctx, AV_LOG_DEBUG, "vbv buffer: %d, bitrate:%"PRId64", aspect_ratio_info: %d \n",

               s->avctx->rc_buffer_size, s->bit_rate, s->aspect_ratio_info);

    return 0;

}


static void vnc_async_encoding_end(VncState *orig, VncState *local)
{
    orig->tight = local->tight;
    orig->zlib = local->zlib;
    orig->hextile = local->hextile;
    orig->zrle = local->zrle;
    orig->lossy_rect = local->lossy_rect;
}


static int s302m_decode_frame(AVCodecContext *avctx, void *data,

                              int *got_frame_ptr, AVPacket *avpkt)

{

    S302Context *s = avctx->priv_data;

    AVFrame *frame     = data;

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    int block_size, ret;

    int i;

    int non_pcm_data_type = -1;

    int frame_size = s302m_parse_frame_header(avctx, buf, buf_size);

    if (frame_size < 0)

        return frame_size;

    buf_size -= AES3_HEADER_LEN;

    buf      += AES3_HEADER_LEN;

    /* get output buffer */

    block_size = (avctx->bits_per_raw_sample + 4) / 4;

    frame->nb_samples = 2 * (buf_size / block_size) / avctx->channels;

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

        return ret;

    avctx->bit_rate = 48000 * avctx->channels * (avctx->bits_per_raw_sample + 4) +

                      32 * 48000 / frame->nb_samples;

    buf_size = (frame->nb_samples * avctx->channels / 2) * block_size;

    if (avctx->bits_per_raw_sample == 24) {

        uint32_t *o = (uint32_t *)frame->data[0];

        for (; buf_size > 6; buf_size -= 7) {

            *o++ = (ff_reverse[buf[2]]        << 24) |

                   (ff_reverse[buf[1]]        << 16) |

                   (ff_reverse[buf[0]]        <<  8);

            *o++ = (ff_reverse[buf[6] & 0xf0] << 28) |

                   (ff_reverse[buf[5]]        << 20) |

                   (ff_reverse[buf[4]]        << 12) |

                   (ff_reverse[buf[3] & 0x0f] <<  4);

            buf += 7;

        }

        o = (uint32_t *)frame->data[0];

        if (avctx->channels == 2)

            for (i=0; i<frame->nb_samples * 2 - 6; i+=2) {

                if (o[i] || o[i+1] || o[i+2] || o[i+3])

                    break;

                if (o[i+4] == 0x96F87200U && o[i+5] == 0xA54E1F00) {

                    non_pcm_data_type = (o[i+6] >> 16) & 0x1F;

                    break;

                }

            }

    } else if (avctx->bits_per_raw_sample == 20) {

        uint32_t *o = (uint32_t *)frame->data[0];

        for (; buf_size > 5; buf_size -= 6) {

            *o++ = (ff_reverse[buf[2] & 0xf0] << 28) |

                   (ff_reverse[buf[1]]        << 20) |

                   (ff_reverse[buf[0]]        << 12);

            *o++ = (ff_reverse[buf[5] & 0xf0] << 28) |

                   (ff_reverse[buf[4]]        << 20) |

                   (ff_reverse[buf[3]]        << 12);

            buf += 6;

        }

        o = (uint32_t *)frame->data[0];

        if (avctx->channels == 2)

            for (i=0; i<frame->nb_samples * 2 - 6; i+=2) {

                if (o[i] || o[i+1] || o[i+2] || o[i+3])

                    break;

                if (o[i+4] == 0x6F872000U && o[i+5] == 0x54E1F000) {

                    non_pcm_data_type = (o[i+6] >> 16) & 0x1F;

                    break;

                }

            }

    } else {

        uint16_t *o = (uint16_t *)frame->data[0];

        for (; buf_size > 4; buf_size -= 5) {

            *o++ = (ff_reverse[buf[1]]        <<  8) |

                    ff_reverse[buf[0]];

            *o++ = (ff_reverse[buf[4] & 0xf0] << 12) |

                   (ff_reverse[buf[3]]        <<  4) |

                   (ff_reverse[buf[2]]        >>  4);

            buf += 5;

        }

        o = (uint16_t *)frame->data[0];

        if (avctx->channels == 2)

            for (i=0; i<frame->nb_samples * 2 - 6; i+=2) {

                if (o[i] || o[i+1] || o[i+2] || o[i+3])

                    break;

                if (o[i+4] == 0xF872U && o[i+5] == 0x4E1F) {

                    non_pcm_data_type = (o[i+6] & 0x1F);

                    break;

                }

            }

    }

    if (non_pcm_data_type != -1) {

        if (s->non_pcm_mode == 3) {

            av_log(avctx, AV_LOG_ERROR,

                   "S302 non PCM mode with data type %d not supported\n",

                   non_pcm_data_type);

            return AVERROR_PATCHWELCOME;

        }

        if (s->non_pcm_mode & 1) {

            return avpkt->size;

        }

    }

    avctx->sample_rate = 48000;

    *got_frame_ptr = 1;

    return avpkt->size;

}


static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)

{

    CharDriverState *chr = opaque;

    TCPCharDriver *s = chr->opaque;

    uint8_t buf[READ_BUF_LEN];

    int len, size;

    if (!s->connected || s->max_size <= 0) {

        return FALSE;

    }

    len = sizeof(buf);

    if (len > s->max_size)

        len = s->max_size;

    size = tcp_chr_recv(chr, (void *)buf, len);

    if (size == 0) {

        /* connection closed */

        s->connected = 0;

        if (s->listen_chan) {

            s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);

        }

        if (s->tag) {

            g_source_remove(s->tag);

            s->tag = 0;

        }

        g_io_channel_unref(s->chan);

        s->chan = NULL;

        closesocket(s->fd);

        s->fd = -1;

        qemu_chr_be_event(chr, CHR_EVENT_CLOSED);

    } else if (size > 0) {

        if (s->do_telnetopt)

            tcp_chr_process_IAC_bytes(chr, s, buf, &size);

        if (size > 0)

            qemu_chr_be_write(chr, buf, size);

    }

    return TRUE;

}


static void ivshmem_realize(PCIDevice *dev, Error **errp)

{

    IVShmemState *s = IVSHMEM_COMMON(dev);

    if (!qtest_enabled()) {

        error_report("ivshmem is deprecated, please use ivshmem-plain"

                     " or ivshmem-doorbell instead");

    }

    if (!!qemu_chr_fe_get_driver(&s->server_chr) + !!s->shmobj != 1) {

        error_setg(errp, "You must specify either 'shm' or 'chardev'");

        return;

    }

    if (s->sizearg == NULL) {

        s->legacy_size = 4 << 20; /* 4 MB default */

    } else {

        int64_t size = qemu_strtosz_MiB(s->sizearg, NULL);

        if (size < 0 || (size_t)size != size || !is_power_of_2(size)) {

            error_setg(errp, "Invalid size %s", s->sizearg);

            return;

        }

        s->legacy_size = size;

    }

    /* check that role is reasonable */

    if (s->role) {

        if (strncmp(s->role, "peer", 5) == 0) {

            s->master = ON_OFF_AUTO_OFF;

        } else if (strncmp(s->role, "master", 7) == 0) {

            s->master = ON_OFF_AUTO_ON;

        } else {

            error_setg(errp, "'role' must be 'peer' or 'master'");

            return;

        }

    } else {

        s->master = ON_OFF_AUTO_AUTO;

    }

    if (s->shmobj) {

        desugar_shm(s);

    }

    /*

     * Note: we don't use INTx with IVSHMEM_MSI at all, so this is a

     * bald-faced lie then.  But it's a backwards compatible lie.

     */

    pci_config_set_interrupt_pin(dev->config, 1);

    ivshmem_common_realize(dev, errp);

}


void css_conditional_io_interrupt(SubchDev *sch)

{

    /*

     * If the subchannel is not currently status pending, make it pending

     * with alert status.

     */

    if (!(sch->curr_status.scsw.ctrl & SCSW_STCTL_STATUS_PEND)) {

        S390CPU *cpu = s390_cpu_addr2state(0);

        uint8_t isc = (sch->curr_status.pmcw.flags & PMCW_FLAGS_MASK_ISC) >> 11;

        trace_css_io_interrupt(sch->cssid, sch->ssid, sch->schid,

                               sch->curr_status.pmcw.intparm, isc,

                               "(unsolicited)");

        sch->curr_status.scsw.ctrl &= ~SCSW_CTRL_MASK_STCTL;

        sch->curr_status.scsw.ctrl |=

            SCSW_STCTL_ALERT | SCSW_STCTL_STATUS_PEND;

        /* Inject an I/O interrupt. */

        s390_io_interrupt(cpu,

                          css_build_subchannel_id(sch),

                          sch->schid,

                          sch->curr_status.pmcw.intparm,

                          (0x80 >> isc) << 24);

    }

}


int load_image_gzipped(const char *filename, hwaddr addr, uint64_t max_sz)

{

    uint8_t *compressed_data = NULL;

    uint8_t *data = NULL;

    gsize len;

    ssize_t bytes;

    int ret = -1;

    if (!g_file_get_contents(filename, (char **) &compressed_data, &len,

                             NULL)) {

        goto out;

    }

    /* Is it a gzip-compressed file? */

    if (len < 2 ||

        compressed_data[0] != 0x1f ||

        compressed_data[1] != 0x8b) {

        goto out;

    }

    if (max_sz > LOAD_IMAGE_MAX_GUNZIP_BYTES) {

        max_sz = LOAD_IMAGE_MAX_GUNZIP_BYTES;

    }

    data = g_malloc(max_sz);

    bytes = gunzip(data, max_sz, compressed_data, len);

    if (bytes < 0) {

        fprintf(stderr, "%s: unable to decompress gzipped kernel file\n",

                filename);

        goto out;

    }

    rom_add_blob_fixed(filename, data, bytes, addr);

    ret = bytes;

 out:

    g_free(compressed_data);

    g_free(data);

    return ret;

}


static ioreq_t *cpu_get_ioreq_from_shared_memory(XenIOState *state, int vcpu)

{

    ioreq_t *req = xen_vcpu_ioreq(state->shared_page, vcpu);

    if (req->state != STATE_IOREQ_READY) {

        DPRINTF("I/O request not ready: "

                "%x, ptr: %x, port: %"PRIx64", "

                "data: %"PRIx64", count: %" FMT_ioreq_size ", size: %" FMT_ioreq_size "\n",

                req->state, req->data_is_ptr, req->addr,

                req->data, req->count, req->size);

        return NULL;

    }

    xen_rmb(); /* see IOREQ_READY /then/ read contents of ioreq */

    req->state = STATE_IOREQ_INPROCESS;

    return req;

}


static void vfio_pci_write_config(PCIDevice *pdev, uint32_t addr,

                                  uint32_t val, int len)

{

    VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);

    uint32_t val_le = cpu_to_le32(val);

    DPRINTF("%s(%04x:%02x:%02x.%x, @0x%x, 0x%x, len=0x%x)\n", __func__,

            vdev->host.domain, vdev->host.bus, vdev->host.slot,

            vdev->host.function, addr, val, len);

    /* Write everything to VFIO, let it filter out what we can't write */

    if (pwrite(vdev->fd, &val_le, len, vdev->config_offset + addr) != len) {

        error_report("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x, 0x%x) failed: %m",

                     __func__, vdev->host.domain, vdev->host.bus,

                     vdev->host.slot, vdev->host.function, addr, val, len);

    }

    /* Write standard header bits to emulation */

    if (addr < PCI_CONFIG_HEADER_SIZE) {

        pci_default_write_config(pdev, addr, val, len);

        return;

    }

    /* MSI/MSI-X Enabling/Disabling */

    if (pdev->cap_present & QEMU_PCI_CAP_MSI &&

        ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size)) {

        int is_enabled, was_enabled = msi_enabled(pdev);

        pci_default_write_config(pdev, addr, val, len);

        is_enabled = msi_enabled(pdev);

        if (!was_enabled && is_enabled) {

            vfio_enable_msi(vdev);

        } else if (was_enabled && !is_enabled) {

            vfio_disable_msi(vdev);

        }

    }

    if (pdev->cap_present & QEMU_PCI_CAP_MSIX &&

        ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) {

        int is_enabled, was_enabled = msix_enabled(pdev);

        pci_default_write_config(pdev, addr, val, len);

        is_enabled = msix_enabled(pdev);

        if (!was_enabled && is_enabled) {

            vfio_enable_msix(vdev);

        } else if (was_enabled && !is_enabled) {

            vfio_disable_msix(vdev);

        }

    }

}


static int check_refblocks(BlockDriverState *bs, BdrvCheckResult *res,

                           BdrvCheckMode fix, uint16_t **refcount_table,

                           int64_t *nb_clusters)

{

    BDRVQcowState *s = bs->opaque;

    int64_t i;

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

        uint64_t offset, cluster;

        offset = s->refcount_table[i];

        cluster = offset >> s->cluster_bits;

        /* Refcount blocks are cluster aligned */

        if (offset_into_cluster(s, offset)) {

            fprintf(stderr, "ERROR refcount block %" PRId64 " is not "

                "cluster aligned; refcount table entry corrupted\n", i);

            res->corruptions++;

            continue;

        }

        if (cluster >= *nb_clusters) {

            fprintf(stderr, "ERROR refcount block %" PRId64

                    " is outside image\n", i);

            res->corruptions++;

            continue;

        }

        if (offset != 0) {

            inc_refcounts(bs, res, *refcount_table, *nb_clusters,

                offset, s->cluster_size);

            if ((*refcount_table)[cluster] != 1) {

                fprintf(stderr, "%s refcount block %" PRId64

                    " refcount=%d\n",

                    fix & BDRV_FIX_ERRORS ? "Repairing" :

                                            "ERROR",

                    i, (*refcount_table)[cluster]);

                if (fix & BDRV_FIX_ERRORS) {

                    int64_t new_offset;

                    new_offset = realloc_refcount_block(bs, i, offset);

                    if (new_offset < 0) {

                        res->corruptions++;

                        continue;

                    }

                    /* update refcounts */

                    if ((new_offset >> s->cluster_bits) >= *nb_clusters) {

                        /* increase refcount_table size if necessary */

                        int old_nb_clusters = *nb_clusters;

                        *nb_clusters = (new_offset >> s->cluster_bits) + 1;

                        *refcount_table = g_renew(uint16_t, *refcount_table,

                                                  *nb_clusters);

                        memset(&(*refcount_table)[old_nb_clusters], 0,

                               (*nb_clusters - old_nb_clusters) *

                               sizeof(uint16_t));

                    }

                    (*refcount_table)[cluster]--;

                    inc_refcounts(bs, res, *refcount_table, *nb_clusters,

                            new_offset, s->cluster_size);

                    res->corruptions_fixed++;

                } else {

                    res->corruptions++;

                }

            }

        }

    }

    return 0;

}


static void gen_lwarx(DisasContext *ctx)

{

    TCGv t0;

    gen_set_access_type(ctx, ACCESS_RES);

    t0 = tcg_temp_local_new();

    gen_addr_reg_index(ctx, t0);

    gen_check_align(ctx, t0, 0x03);

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

    tcg_gen_mov_tl(cpu_reserve, t0);

    tcg_temp_free(t0);

}


static inline void skip_hdr_extension(GetBitContext *gb)

{

    int i, len;

    do {

        len = get_bits(gb, 8);

        for (i = 0; i < len; i++) skip_bits(gb, 8);

    } while(len);

}


static int nbd_negotiate_options(NBDClient *client)

{

    uint32_t flags;

    /* Client sends:

        [ 0 ..   3]   client flags

        [ 0 ..   7]   NBD_OPTS_MAGIC

        [ 8 ..  11]   NBD option

        [12 ..  15]   Data length

        ...           Rest of request

        [ 0 ..   7]   NBD_OPTS_MAGIC

        [ 8 ..  11]   Second NBD option

        [12 ..  15]   Data length

        ...           Rest of request

    */

    if (nbd_negotiate_read(client->ioc, &flags, sizeof(flags)) !=

        sizeof(flags)) {

        LOG("read failed");

        return -EIO;

    }

    TRACE("Checking client flags");

    be32_to_cpus(&flags);

    if (flags != 0 && flags != NBD_FLAG_C_FIXED_NEWSTYLE) {

        LOG("Bad client flags received");

        return -EIO;

    }

    while (1) {

        int ret;

        uint32_t tmp, length;

        uint64_t magic;

        if (nbd_negotiate_read(client->ioc, &magic, sizeof(magic)) !=

            sizeof(magic)) {

            LOG("read failed");

            return -EINVAL;

        }

        TRACE("Checking opts magic");

        if (magic != be64_to_cpu(NBD_OPTS_MAGIC)) {

            LOG("Bad magic received");

            return -EINVAL;

        }

        if (nbd_negotiate_read(client->ioc, &tmp, sizeof(tmp)) != sizeof(tmp)) {

            LOG("read failed");

            return -EINVAL;

        }

        if (nbd_negotiate_read(client->ioc, &length, sizeof(length)) !=

            sizeof(length)) {

            LOG("read failed");

            return -EINVAL;

        }

        length = be32_to_cpu(length);

        TRACE("Checking option");

        switch (be32_to_cpu(tmp)) {

        case NBD_OPT_LIST:

            ret = nbd_negotiate_handle_list(client, length);

            if (ret < 0) {

                return ret;

            }

            break;

        case NBD_OPT_ABORT:

            return -EINVAL;

        case NBD_OPT_EXPORT_NAME:

            return nbd_negotiate_handle_export_name(client, length);

        default:

            tmp = be32_to_cpu(tmp);

            LOG("Unsupported option 0x%x", tmp);

            nbd_negotiate_send_rep(client->ioc, NBD_REP_ERR_UNSUP, tmp);

            return -EINVAL;

        }

    }

}


static void pxb_dev_realize(PCIDevice *dev, Error **errp)

{

    if (pci_bus_is_express(dev->bus)) {

        error_setg(errp, "pxb devices cannot reside on a PCIe bus");

        return;

    }

    pxb_dev_realize_common(dev, false, errp);

}


static void gen_arith_imm(DisasContext *ctx, uint32_t opc,

                          int rt, int rs, int16_t imm)

{

    target_ulong uimm = (target_long)imm; /* Sign extend to 32/64 bits */

    const char *opn = "imm arith";

    if (rt == 0 && opc != OPC_ADDI && opc != OPC_DADDI) {

        /* If no destination, treat it as a NOP.

           For addi, we must generate the overflow exception when needed. */

        MIPS_DEBUG("NOP");

        return;

    }

    switch (opc) {

    case OPC_ADDI:

        {

            TCGv t0 = tcg_temp_local_new();

            TCGv t1 = tcg_temp_new();

            TCGv t2 = tcg_temp_new();

            int l1 = gen_new_label();

            gen_load_gpr(t1, rs);

            tcg_gen_addi_tl(t0, t1, uimm);

            tcg_gen_ext32s_tl(t0, t0);

            tcg_gen_xori_tl(t1, t1, ~uimm);

            tcg_gen_xori_tl(t2, t0, uimm);

            tcg_gen_and_tl(t1, t1, t2);

            tcg_temp_free(t2);

            tcg_gen_brcondi_tl(TCG_COND_GE, t1, 0, l1);

            tcg_temp_free(t1);

            /* operands of same sign, result different sign */

            generate_exception(ctx, EXCP_OVERFLOW);

            gen_set_label(l1);

            tcg_gen_ext32s_tl(t0, t0);

            gen_store_gpr(t0, rt);

            tcg_temp_free(t0);

        }

        opn = "addi";

        break;

    case OPC_ADDIU:

        if (rs != 0) {

            tcg_gen_addi_tl(cpu_gpr[rt], cpu_gpr[rs], uimm);

            tcg_gen_ext32s_tl(cpu_gpr[rt], cpu_gpr[rt]);

        } else {

            tcg_gen_movi_tl(cpu_gpr[rt], uimm);

        }

        opn = "addiu";

        break;

#if defined(TARGET_MIPS64)

    case OPC_DADDI:

        {

            TCGv t0 = tcg_temp_local_new();

            TCGv t1 = tcg_temp_new();

            TCGv t2 = tcg_temp_new();

            int l1 = gen_new_label();

            gen_load_gpr(t1, rs);

            tcg_gen_addi_tl(t0, t1, uimm);

            tcg_gen_xori_tl(t1, t1, ~uimm);

            tcg_gen_xori_tl(t2, t0, uimm);

            tcg_gen_and_tl(t1, t1, t2);

            tcg_temp_free(t2);

            tcg_gen_brcondi_tl(TCG_COND_GE, t1, 0, l1);

            tcg_temp_free(t1);

            /* operands of same sign, result different sign */

            generate_exception(ctx, EXCP_OVERFLOW);

            gen_set_label(l1);

            gen_store_gpr(t0, rt);

            tcg_temp_free(t0);

        }

        opn = "daddi";

        break;

    case OPC_DADDIU:

        if (rs != 0) {

            tcg_gen_addi_tl(cpu_gpr[rt], cpu_gpr[rs], uimm);

        } else {

            tcg_gen_movi_tl(cpu_gpr[rt], uimm);

        }

        opn = "daddiu";

        break;

#endif

    }

    (void)opn; /* avoid a compiler warning */

    MIPS_DEBUG("%s %s, %s, " TARGET_FMT_lx, opn, regnames[rt], regnames[rs], uimm);

}


CPUCRISState *cpu_cris_init (const char *cpu_model)

{

	CPUCRISState *env;

	static int tcg_initialized = 0;

	int i;

	env = qemu_mallocz(sizeof(CPUCRISState));

	if (!env)

		return NULL;

	cpu_exec_init(env);

	cpu_reset(env);

	if (tcg_initialized)

		return env;

	tcg_initialized = 1;

	cpu_env = tcg_global_reg_new(TCG_TYPE_PTR, TCG_AREG0, "env");

	cc_x = tcg_global_mem_new(TCG_TYPE_TL, TCG_AREG0,

				  offsetof(CPUState, cc_x), "cc_x");

	cc_src = tcg_global_mem_new(TCG_TYPE_TL, TCG_AREG0,

				    offsetof(CPUState, cc_src), "cc_src");

	cc_dest = tcg_global_mem_new(TCG_TYPE_TL, TCG_AREG0,

				     offsetof(CPUState, cc_dest),

				     "cc_dest");

	cc_result = tcg_global_mem_new(TCG_TYPE_TL, TCG_AREG0,

				       offsetof(CPUState, cc_result),

				       "cc_result");

	cc_op = tcg_global_mem_new(TCG_TYPE_TL, TCG_AREG0,

				   offsetof(CPUState, cc_op), "cc_op");

	cc_size = tcg_global_mem_new(TCG_TYPE_TL, TCG_AREG0,

				     offsetof(CPUState, cc_size),

				     "cc_size");

	cc_mask = tcg_global_mem_new(TCG_TYPE_TL, TCG_AREG0,

				     offsetof(CPUState, cc_mask),

				     "cc_mask");

	env_pc = tcg_global_mem_new(TCG_TYPE_TL, TCG_AREG0,

				    offsetof(CPUState, pc),

				    "pc");

	env_btarget = tcg_global_mem_new(TCG_TYPE_TL, TCG_AREG0,

					 offsetof(CPUState, btarget),

					 "btarget");

	env_btaken = tcg_global_mem_new(TCG_TYPE_TL, TCG_AREG0,

					 offsetof(CPUState, btaken),

					 "btaken");

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

		cpu_R[i] = tcg_global_mem_new(TCG_TYPE_TL, TCG_AREG0,

					      offsetof(CPUState, regs[i]),

					      regnames[i]);

	}

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

		cpu_PR[i] = tcg_global_mem_new(TCG_TYPE_TL, TCG_AREG0,

					       offsetof(CPUState, pregs[i]),

					       pregnames[i]);

	}

	TCG_HELPER(helper_raise_exception);

	TCG_HELPER(helper_dump);

	TCG_HELPER(helper_tlb_flush_pid);

	TCG_HELPER(helper_movl_sreg_reg);

	TCG_HELPER(helper_movl_reg_sreg);

	TCG_HELPER(helper_rfe);

	TCG_HELPER(helper_rfn);

	TCG_HELPER(helper_evaluate_flags_muls);

	TCG_HELPER(helper_evaluate_flags_mulu);

	TCG_HELPER(helper_evaluate_flags_mcp);

	TCG_HELPER(helper_evaluate_flags_alu_4);

	TCG_HELPER(helper_evaluate_flags_move_4);

	TCG_HELPER(helper_evaluate_flags_move_2);

	TCG_HELPER(helper_evaluate_flags);

	TCG_HELPER(helper_top_evaluate_flags);

	return env;

}


static void pxa2xx_lcdc_dma0_redraw_rot180(PXA2xxLCDState *s,

                hwaddr addr, int *miny, int *maxy)

{

    DisplaySurface *surface = qemu_console_surface(s->con);

    int src_width, dest_width;

    drawfn fn = NULL;

    if (s->dest_width) {

        fn = s->line_fn[s->transp][s->bpp];

    }

    if (!fn) {

        return;

    }

    src_width = (s->xres + 3) & ~3;     /* Pad to a 4 pixels multiple */

    if (s->bpp == pxa_lcdc_19pbpp || s->bpp == pxa_lcdc_18pbpp) {

        src_width *= 3;

    } else if (s->bpp > pxa_lcdc_16bpp) {

        src_width *= 4;

    } else if (s->bpp > pxa_lcdc_8bpp) {

        src_width *= 2;

    }

    dest_width = s->xres * s->dest_width;

    *miny = 0;

    framebuffer_update_display(surface, s->sysmem,

                               addr, s->xres, s->yres,

                               src_width, -dest_width, -s->dest_width,

                               s->invalidated,

                               fn, s->dma_ch[0].palette, miny, maxy);

}


static void gen_compute_branch(DisasContext *ctx, uint32_t opc, int r1,

                               int r2 , int32_t constant , int32_t offset)

{

    TCGv temp, temp2;

    int n;

    switch (opc) {

/* SB-format jumps */

    case OPC1_16_SB_J:

    case OPC1_32_B_J:

        gen_goto_tb(ctx, 0, ctx->pc + offset * 2);

        break;

    case OPC1_32_B_CALL:

    case OPC1_16_SB_CALL:

        gen_helper_1arg(call, ctx->next_pc);

        gen_goto_tb(ctx, 0, ctx->pc + offset * 2);

        break;

    case OPC1_16_SB_JZ:

        gen_branch_condi(ctx, TCG_COND_EQ, cpu_gpr_d[15], 0, offset);

        break;

    case OPC1_16_SB_JNZ:

        gen_branch_condi(ctx, TCG_COND_NE, cpu_gpr_d[15], 0, offset);

        break;

/* SBC-format jumps */

    case OPC1_16_SBC_JEQ:

        gen_branch_condi(ctx, TCG_COND_EQ, cpu_gpr_d[15], constant, offset);

        break;

    case OPC1_16_SBC_JNE:

        gen_branch_condi(ctx, TCG_COND_NE, cpu_gpr_d[15], constant, offset);

        break;

/* SBRN-format jumps */

    case OPC1_16_SBRN_JZ_T:

        temp = tcg_temp_new();

        tcg_gen_andi_tl(temp, cpu_gpr_d[15], 0x1u << constant);

        gen_branch_condi(ctx, TCG_COND_EQ, temp, 0, offset);

        tcg_temp_free(temp);

        break;

    case OPC1_16_SBRN_JNZ_T:

        temp = tcg_temp_new();

        tcg_gen_andi_tl(temp, cpu_gpr_d[15], 0x1u << constant);

        gen_branch_condi(ctx, TCG_COND_NE, temp, 0, offset);

        tcg_temp_free(temp);

        break;

/* SBR-format jumps */

    case OPC1_16_SBR_JEQ:

        gen_branch_cond(ctx, TCG_COND_EQ, cpu_gpr_d[r1], cpu_gpr_d[15],

                        offset);

        break;

    case OPC1_16_SBR_JNE:

        gen_branch_cond(ctx, TCG_COND_NE, cpu_gpr_d[r1], cpu_gpr_d[15],

                        offset);

        break;

    case OPC1_16_SBR_JNZ:

        gen_branch_condi(ctx, TCG_COND_NE, cpu_gpr_d[r1], 0, offset);

        break;

    case OPC1_16_SBR_JNZ_A:

        gen_branch_condi(ctx, TCG_COND_NE, cpu_gpr_a[r1], 0, offset);

        break;

    case OPC1_16_SBR_JGEZ:

        gen_branch_condi(ctx, TCG_COND_GE, cpu_gpr_d[r1], 0, offset);

        break;

    case OPC1_16_SBR_JGTZ:

        gen_branch_condi(ctx, TCG_COND_GT, cpu_gpr_d[r1], 0, offset);

        break;

    case OPC1_16_SBR_JLEZ:

        gen_branch_condi(ctx, TCG_COND_LE, cpu_gpr_d[r1], 0, offset);

        break;

    case OPC1_16_SBR_JLTZ:

        gen_branch_condi(ctx, TCG_COND_LT, cpu_gpr_d[r1], 0, offset);

        break;

    case OPC1_16_SBR_JZ:

        gen_branch_condi(ctx, TCG_COND_EQ, cpu_gpr_d[r1], 0, offset);

        break;

    case OPC1_16_SBR_JZ_A:

        gen_branch_condi(ctx, TCG_COND_EQ, cpu_gpr_a[r1], 0, offset);

        break;

    case OPC1_16_SBR_LOOP:

        gen_loop(ctx, r1, offset * 2 - 32);

        break;

/* SR-format jumps */

    case OPC1_16_SR_JI:

        tcg_gen_andi_tl(cpu_PC, cpu_gpr_a[r1], 0xfffffffe);

        tcg_gen_exit_tb(0);

        break;

    case OPC2_32_SYS_RET:

    case OPC2_16_SR_RET:

        gen_helper_ret(cpu_env);

        tcg_gen_exit_tb(0);

        break;

/* B-format */

    case OPC1_32_B_CALLA:

        gen_helper_1arg(call, ctx->next_pc);

        gen_goto_tb(ctx, 0, EA_B_ABSOLUT(offset));

        break;

    case OPC1_32_B_JLA:

        tcg_gen_movi_tl(cpu_gpr_a[11], ctx->next_pc);

        /* fall through */

    case OPC1_32_B_JA:

        gen_goto_tb(ctx, 0, EA_B_ABSOLUT(offset));

        break;

    case OPC1_32_B_JL:

        tcg_gen_movi_tl(cpu_gpr_a[11], ctx->next_pc);

        gen_goto_tb(ctx, 0, ctx->pc + offset * 2);

        break;

/* BOL format */

    case OPCM_32_BRC_EQ_NEQ:

         if (MASK_OP_BRC_OP2(ctx->opcode) == OPC2_32_BRC_JEQ) {

            gen_branch_condi(ctx, TCG_COND_EQ, cpu_gpr_d[r1], constant, offset);

         } else {

            gen_branch_condi(ctx, TCG_COND_NE, cpu_gpr_d[r1], constant, offset);

         }

         break;

    case OPCM_32_BRC_GE:

         if (MASK_OP_BRC_OP2(ctx->opcode) == OP2_32_BRC_JGE) {

            gen_branch_condi(ctx, TCG_COND_GE, cpu_gpr_d[r1], constant, offset);

         } else {

            constant = MASK_OP_BRC_CONST4(ctx->opcode);

            gen_branch_condi(ctx, TCG_COND_GEU, cpu_gpr_d[r1], constant,

                             offset);

         }

         break;

    case OPCM_32_BRC_JLT:

         if (MASK_OP_BRC_OP2(ctx->opcode) == OPC2_32_BRC_JLT) {

            gen_branch_condi(ctx, TCG_COND_LT, cpu_gpr_d[r1], constant, offset);

         } else {

            constant = MASK_OP_BRC_CONST4(ctx->opcode);

            gen_branch_condi(ctx, TCG_COND_LTU, cpu_gpr_d[r1], constant,

                             offset);

         }

         break;

    case OPCM_32_BRC_JNE:

        temp = tcg_temp_new();

        if (MASK_OP_BRC_OP2(ctx->opcode) == OPC2_32_BRC_JNED) {

            tcg_gen_mov_tl(temp, cpu_gpr_d[r1]);

            /* subi is unconditional */

            tcg_gen_subi_tl(cpu_gpr_d[r1], cpu_gpr_d[r1], 1);

            gen_branch_condi(ctx, TCG_COND_NE, temp, constant, offset);

        } else {

            tcg_gen_mov_tl(temp, cpu_gpr_d[r1]);

            /* addi is unconditional */

            tcg_gen_addi_tl(cpu_gpr_d[r1], cpu_gpr_d[r1], 1);

            gen_branch_condi(ctx, TCG_COND_NE, temp, constant, offset);

        }

        tcg_temp_free(temp);

        break;

/* BRN format */

    case OPCM_32_BRN_JTT:

        n = MASK_OP_BRN_N(ctx->opcode);

        temp = tcg_temp_new();

        tcg_gen_andi_tl(temp, cpu_gpr_d[r1], (1 << n));

        if (MASK_OP_BRN_OP2(ctx->opcode) == OPC2_32_BRN_JNZ_T) {

            gen_branch_condi(ctx, TCG_COND_NE, temp, 0, offset);

        } else {

            gen_branch_condi(ctx, TCG_COND_EQ, temp, 0, offset);

        }

        tcg_temp_free(temp);

        break;

/* BRR Format */

    case OPCM_32_BRR_EQ_NEQ:

        if (MASK_OP_BRR_OP2(ctx->opcode) == OPC2_32_BRR_JEQ) {

            gen_branch_cond(ctx, TCG_COND_EQ, cpu_gpr_d[r1], cpu_gpr_d[r2],

                            offset);

        } else {

            gen_branch_cond(ctx, TCG_COND_NE, cpu_gpr_d[r1], cpu_gpr_d[r2],

                            offset);

        }

        break;

    case OPCM_32_BRR_ADDR_EQ_NEQ:

        if (MASK_OP_BRR_OP2(ctx->opcode) == OPC2_32_BRR_JEQ_A) {

            gen_branch_cond(ctx, TCG_COND_EQ, cpu_gpr_a[r1], cpu_gpr_a[r2],

                            offset);

        } else {

            gen_branch_cond(ctx, TCG_COND_NE, cpu_gpr_a[r1], cpu_gpr_a[r2],

                            offset);

        }

        break;

    case OPCM_32_BRR_GE:

        if (MASK_OP_BRR_OP2(ctx->opcode) == OPC2_32_BRR_JGE) {

            gen_branch_cond(ctx, TCG_COND_GE, cpu_gpr_d[r1], cpu_gpr_d[r2],

                            offset);

        } else {

            gen_branch_cond(ctx, TCG_COND_GEU, cpu_gpr_d[r1], cpu_gpr_d[r2],

                            offset);

        }

        break;

    case OPCM_32_BRR_JLT:

        if (MASK_OP_BRR_OP2(ctx->opcode) == OPC2_32_BRR_JLT) {

            gen_branch_cond(ctx, TCG_COND_LT, cpu_gpr_d[r1], cpu_gpr_d[r2],

                            offset);

        } else {

            gen_branch_cond(ctx, TCG_COND_LTU, cpu_gpr_d[r1], cpu_gpr_d[r2],

                            offset);

        }

        break;

    case OPCM_32_BRR_LOOP:

        if (MASK_OP_BRR_OP2(ctx->opcode) == OPC2_32_BRR_LOOP) {

            gen_loop(ctx, r1, offset * 2);

        } else {

            /* OPC2_32_BRR_LOOPU */

            gen_goto_tb(ctx, 0, ctx->pc + offset * 2);

        }

        break;

    case OPCM_32_BRR_JNE:

        temp = tcg_temp_new();

        temp2 = tcg_temp_new();

        if (MASK_OP_BRC_OP2(ctx->opcode) == OPC2_32_BRR_JNED) {

            tcg_gen_mov_tl(temp, cpu_gpr_d[r1]);

            /* also save r2, in case of r1 == r2, so r2 is not decremented */

            tcg_gen_mov_tl(temp2, cpu_gpr_d[r2]);

            /* subi is unconditional */

            tcg_gen_subi_tl(cpu_gpr_d[r1], cpu_gpr_d[r1], 1);

            gen_branch_cond(ctx, TCG_COND_NE, temp, temp2, offset);

        } else {

            tcg_gen_mov_tl(temp, cpu_gpr_d[r1]);

            /* also save r2, in case of r1 == r2, so r2 is not decremented */

            tcg_gen_mov_tl(temp2, cpu_gpr_d[r2]);

            /* addi is unconditional */

            tcg_gen_addi_tl(cpu_gpr_d[r1], cpu_gpr_d[r1], 1);

            gen_branch_cond(ctx, TCG_COND_NE, temp, temp2, offset);

        }

        tcg_temp_free(temp);

        tcg_temp_free(temp2);

        break;

    case OPCM_32_BRR_JNZ:

        if (MASK_OP_BRR_OP2(ctx->opcode) == OPC2_32_BRR_JNZ_A) {

            gen_branch_condi(ctx, TCG_COND_NE, cpu_gpr_a[r1], 0, offset);

        } else {

            gen_branch_condi(ctx, TCG_COND_EQ, cpu_gpr_a[r1], 0, offset);

        }

        break;

    default:

        printf("Branch Error at %x\n", ctx->pc);

    }

    ctx->bstate = BS_BRANCH;

}


static void ide_init1(IDEBus *bus, int unit, DriveInfo *dinfo)

{

    static int drive_serial = 1;

    IDEState *s = &bus->ifs[unit];

    s->bus = bus;

    s->unit = unit;

    s->drive_serial = drive_serial++;

    s->io_buffer = qemu_blockalign(s->bs, IDE_DMA_BUF_SECTORS*512 + 4);

    s->io_buffer_total_len = IDE_DMA_BUF_SECTORS*512 + 4;

    s->smart_selftest_data = qemu_blockalign(s->bs, 512);

    s->sector_write_timer = qemu_new_timer(vm_clock,

                                           ide_sector_write_timer_cb, s);

    ide_init_drive(s, dinfo, NULL);

}


static void scsi_disk_apply_mode_select(SCSIDiskState *s, int page, uint8_t *p)

{

    switch (page) {

    case MODE_PAGE_CACHING:

        bdrv_set_enable_write_cache(s->qdev.conf.bs, (p[0] & 4) != 0);

        break;

    default:

        break;

    }

}


int av_opt_set_dict2(void *obj, AVDictionary **options, int search_flags)

{

    AVDictionaryEntry *t = NULL;

    AVDictionary    *tmp = NULL;

    int ret = 0;

    if (!options)

        return 0;

    while ((t = av_dict_get(*options, "", t, AV_DICT_IGNORE_SUFFIX))) {

        ret = av_opt_set(obj, t->key, t->value, search_flags);

        if (ret == AVERROR_OPTION_NOT_FOUND)

            av_dict_set(&tmp, t->key, t->value, 0);

        else if (ret < 0) {

            av_log(obj, AV_LOG_ERROR, "Error setting option %s to value %s.\n", t->key, t->value);

            break;

        }

        ret = 0;

    }

    av_dict_free(options);

    *options = tmp;

    return ret;

}


START_TEST(empty_input)

{

    const char *empty = "";

    QObject *obj = qobject_from_json(empty);

    fail_unless(obj == NULL);

}


int net_client_init(const char *device, const char *p)

{

    static const char * const fd_params[] = {

        "vlan", "name", "fd", NULL

    };

    char buf[1024];

    int vlan_id, ret;

    VLANState *vlan;

    char *name = NULL;

    vlan_id = 0;

    if (get_param_value(buf, sizeof(buf), "vlan", p)) {

        vlan_id = strtol(buf, NULL, 0);

    }

    vlan = qemu_find_vlan(vlan_id);

    if (get_param_value(buf, sizeof(buf), "name", p)) {

        name = strdup(buf);

    }

    if (!strcmp(device, "nic")) {

        static const char * const nic_params[] = {

            "vlan", "name", "macaddr", "model", NULL

        };

        NICInfo *nd;

        uint8_t *macaddr;

        int idx = nic_get_free_idx();

        if (check_params(nic_params, p) < 0) {

            fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",

                    buf, p);

            return -1;

        }

        if (idx == -1 || nb_nics >= MAX_NICS) {

            fprintf(stderr, "Too Many NICs\n");

            ret = -1;

            goto out;

        }

        nd = &nd_table[idx];

        macaddr = nd->macaddr;

        macaddr[0] = 0x52;

        macaddr[1] = 0x54;

        macaddr[2] = 0x00;

        macaddr[3] = 0x12;

        macaddr[4] = 0x34;

        macaddr[5] = 0x56 + idx;

        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {

            if (parse_macaddr(macaddr, buf) < 0) {

                fprintf(stderr, "invalid syntax for ethernet address\n");

                ret = -1;

                goto out;

            }

        }

        if (get_param_value(buf, sizeof(buf), "model", p)) {

            nd->model = strdup(buf);

        }

        nd->vlan = vlan;

        nd->name = name;

        nd->used = 1;

        name = NULL;

        nb_nics++;

        vlan->nb_guest_devs++;

        ret = idx;

    } else

    if (!strcmp(device, "none")) {

        if (*p != '\0') {

            fprintf(stderr, "qemu: 'none' takes no parameters\n");

            return -1;

        }

        /* does nothing. It is needed to signal that no network cards

           are wanted */

        ret = 0;

    } else

#ifdef CONFIG_SLIRP

    if (!strcmp(device, "user")) {

        static const char * const slirp_params[] = {

            "vlan", "name", "hostname", "restrict", "ip", NULL

        };

        if (check_params(slirp_params, p) < 0) {

            fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",

                    buf, p);

            return -1;

        }

        if (get_param_value(buf, sizeof(buf), "hostname", p)) {

            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);

        }

        if (get_param_value(buf, sizeof(buf), "restrict", p)) {

            slirp_restrict = (buf[0] == 'y') ? 1 : 0;

        }

        if (get_param_value(buf, sizeof(buf), "ip", p)) {

            slirp_ip = strdup(buf);

        }

        vlan->nb_host_devs++;

        ret = net_slirp_init(vlan, device, name);

    } else if (!strcmp(device, "channel")) {

        long port;

        char name[20], *devname;

        struct VMChannel *vmc;

        port = strtol(p, &devname, 10);

        devname++;

        if (port < 1 || port > 65535) {

            fprintf(stderr, "vmchannel wrong port number\n");

            ret = -1;

            goto out;

        }

        vmc = malloc(sizeof(struct VMChannel));

        snprintf(name, 20, "vmchannel%ld", port);

        vmc->hd = qemu_chr_open(name, devname, NULL);

        if (!vmc->hd) {

            fprintf(stderr, "qemu: could not open vmchannel device"

                    "'%s'\n", devname);

            ret = -1;

            goto out;

        }

        vmc->port = port;

        slirp_add_exec(3, vmc->hd, 4, port);

        qemu_chr_add_handlers(vmc->hd, vmchannel_can_read, vmchannel_read,

                NULL, vmc);

        ret = 0;

    } else

#endif

#ifdef _WIN32

    if (!strcmp(device, "tap")) {

        static const char * const tap_params[] = {

            "vlan", "name", "ifname", NULL

        };

        char ifname[64];

        if (check_params(tap_params, p) < 0) {

            fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",

                    buf, p);

            return -1;

        }

        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {

            fprintf(stderr, "tap: no interface name\n");

            ret = -1;

            goto out;

        }

        vlan->nb_host_devs++;

        ret = tap_win32_init(vlan, device, name, ifname);

    } else

#elif defined (_AIX)

#else

    if (!strcmp(device, "tap")) {

        char ifname[64];

        char setup_script[1024], down_script[1024];

        int fd;

        vlan->nb_host_devs++;

        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {

            if (check_params(fd_params, p) < 0) {

                fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",

                        buf, p);

                return -1;

            }

            fd = strtol(buf, NULL, 0);

            fcntl(fd, F_SETFL, O_NONBLOCK);

            net_tap_fd_init(vlan, device, name, fd);

            ret = 0;

        } else {

            static const char * const tap_params[] = {

                "vlan", "name", "ifname", "script", "downscript", NULL

            };

            if (check_params(tap_params, p) < 0) {

                fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",

                        buf, p);

                return -1;

            }

            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {

                ifname[0] = '\0';

            }

            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {

                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);

            }

            if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {

                pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);

            }

            ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);

        }

    } else

#endif

    if (!strcmp(device, "socket")) {

        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {

            int fd;

            if (check_params(fd_params, p) < 0) {

                fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",

                        buf, p);

                return -1;

            }

            fd = strtol(buf, NULL, 0);

            ret = -1;

            if (net_socket_fd_init(vlan, device, name, fd, 1))

                ret = 0;

        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {

            static const char * const listen_params[] = {

                "vlan", "name", "listen", NULL

            };

            if (check_params(listen_params, p) < 0) {

                fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",

                        buf, p);

                return -1;

            }

            ret = net_socket_listen_init(vlan, device, name, buf);

        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {

            static const char * const connect_params[] = {

                "vlan", "name", "connect", NULL

            };

            if (check_params(connect_params, p) < 0) {

                fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",

                        buf, p);

                return -1;

            }

            ret = net_socket_connect_init(vlan, device, name, buf);

        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {

            static const char * const mcast_params[] = {

                "vlan", "name", "mcast", NULL

            };

            if (check_params(mcast_params, p) < 0) {

                fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",

                        buf, p);

                return -1;

            }

            ret = net_socket_mcast_init(vlan, device, name, buf);

        } else {

            fprintf(stderr, "Unknown socket options: %s\n", p);

            ret = -1;

            goto out;

        }

        vlan->nb_host_devs++;

    } else

#ifdef CONFIG_VDE

    if (!strcmp(device, "vde")) {

        static const char * const vde_params[] = {

            "vlan", "name", "sock", "port", "group", "mode", NULL

        };

        char vde_sock[1024], vde_group[512];

	int vde_port, vde_mode;

        if (check_params(vde_params, p) < 0) {

            fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",

                    buf, p);

            return -1;

        }

        vlan->nb_host_devs++;

        if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {

	    vde_sock[0] = '\0';

	}

	if (get_param_value(buf, sizeof(buf), "port", p) > 0) {

	    vde_port = strtol(buf, NULL, 10);

	} else {

	    vde_port = 0;

	}

	if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {

	    vde_group[0] = '\0';

	}

	if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {

	    vde_mode = strtol(buf, NULL, 8);

	} else {

	    vde_mode = 0700;

	}

	ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);

    } else

#endif

    if (!strcmp(device, "dump")) {

        int len = 65536;

        if (get_param_value(buf, sizeof(buf), "len", p) > 0) {

            len = strtol(buf, NULL, 0);

        }

        if (!get_param_value(buf, sizeof(buf), "file", p)) {

            snprintf(buf, sizeof(buf), "qemu-vlan%d.pcap", vlan_id);

        }

        ret = net_dump_init(vlan, device, name, buf, len);

    } else {

        fprintf(stderr, "Unknown network device: %s\n", device);

        ret = -1;

        goto out;

    }

    if (ret < 0) {

        fprintf(stderr, "Could not initialize device '%s'\n", device);

    }

out:

    if (name)

        free(name);

    return ret;

}


static int virtio_ccw_device_init(VirtioCcwDevice *dev, VirtIODevice *vdev)

{

    unsigned int cssid = 0;

    unsigned int ssid = 0;

    unsigned int schid;

    unsigned int devno;

    bool have_devno = false;

    bool found = false;

    SubchDev *sch;

    int ret;

    int num;

    DeviceState *parent = DEVICE(dev);

    sch = g_malloc0(sizeof(SubchDev));

    sch->driver_data = dev;

    dev->sch = sch;

    dev->indicators = NULL;

    /* Initialize subchannel structure. */

    sch->channel_prog = 0x0;

    sch->last_cmd_valid = false;

    sch->thinint_active = false;

    /*

     * Use a device number if provided. Otherwise, fall back to subchannel

     * number.

     */

    if (dev->bus_id) {

        num = sscanf(dev->bus_id, "%x.%x.%04x", &cssid, &ssid, &devno);

        if (num == 3) {

            if ((cssid > MAX_CSSID) || (ssid > MAX_SSID)) {

                ret = -EINVAL;

                error_report("Invalid cssid or ssid: cssid %x, ssid %x",

                             cssid, ssid);

                goto out_err;

            }

            /* Enforce use of virtual cssid. */

            if (cssid != VIRTUAL_CSSID) {

                ret = -EINVAL;

                error_report("cssid %x not valid for virtio devices", cssid);

                goto out_err;

            }

            if (css_devno_used(cssid, ssid, devno)) {

                ret = -EEXIST;

                error_report("Device %x.%x.%04x already exists", cssid, ssid,

                             devno);

                goto out_err;

            }

            sch->cssid = cssid;

            sch->ssid = ssid;

            sch->devno = devno;

            have_devno = true;

        } else {

            ret = -EINVAL;

            error_report("Malformed devno parameter '%s'", dev->bus_id);

            goto out_err;

        }

    }

    /* Find the next free id. */

    if (have_devno) {

        for (schid = 0; schid <= MAX_SCHID; schid++) {

            if (!css_find_subch(1, cssid, ssid, schid)) {

                sch->schid = schid;

                css_subch_assign(cssid, ssid, schid, devno, sch);

                found = true;

                break;

            }

        }

        if (!found) {

            ret = -ENODEV;

            error_report("No free subchannel found for %x.%x.%04x", cssid, ssid,

                         devno);

            goto out_err;

        }

        trace_virtio_ccw_new_device(cssid, ssid, schid, devno,

                                    "user-configured");

    } else {

        cssid = VIRTUAL_CSSID;

        for (ssid = 0; ssid <= MAX_SSID; ssid++) {

            for (schid = 0; schid <= MAX_SCHID; schid++) {

                if (!css_find_subch(1, cssid, ssid, schid)) {

                    sch->cssid = cssid;

                    sch->ssid = ssid;

                    sch->schid = schid;

                    devno = schid;

                    /*

                     * If the devno is already taken, look further in this

                     * subchannel set.

                     */

                    while (css_devno_used(cssid, ssid, devno)) {

                        if (devno == MAX_SCHID) {

                            devno = 0;

                        } else if (devno == schid - 1) {

                            ret = -ENODEV;

                            error_report("No free devno found");

                            goto out_err;

                        } else {

                            devno++;

                        }

                    }

                    sch->devno = devno;

                    css_subch_assign(cssid, ssid, schid, devno, sch);

                    found = true;

                    break;

                }

            }

            if (found) {

                break;

            }

        }

        if (!found) {

            ret = -ENODEV;

            error_report("Virtual channel subsystem is full!");

            goto out_err;

        }

        trace_virtio_ccw_new_device(cssid, ssid, schid, devno,

                                    "auto-configured");

    }

    /* Build initial schib. */

    css_sch_build_virtual_schib(sch, 0, VIRTIO_CCW_CHPID_TYPE);

    sch->ccw_cb = virtio_ccw_cb;

    /* Build senseid data. */

    memset(&sch->id, 0, sizeof(SenseId));

    sch->id.reserved = 0xff;

    sch->id.cu_type = VIRTIO_CCW_CU_TYPE;

    sch->id.cu_model = vdev->device_id;

    /* Only the first 32 feature bits are used. */

    dev->host_features[0] = virtio_bus_get_vdev_features(&dev->bus,

                                                         dev->host_features[0]);

    dev->host_features[0] |= 0x1 << VIRTIO_F_NOTIFY_ON_EMPTY;

    dev->host_features[0] |= 0x1 << VIRTIO_F_BAD_FEATURE;

    css_generate_sch_crws(sch->cssid, sch->ssid, sch->schid,

                          parent->hotplugged, 1);

    return 0;

out_err:

    dev->sch = NULL;

    g_free(sch);

    return ret;

}


static void pc_init_isa(MachineState *machine)

{

    pci_enabled = false;

    has_acpi_build = false;

    smbios_defaults = false;

    gigabyte_align = false;

    smbios_legacy_mode = true;

    has_reserved_memory = false;

    option_rom_has_mr = true;

    rom_file_has_mr = false;

    if (!machine->cpu_model) {

        machine->cpu_model = "486";

    }

    x86_cpu_change_kvm_default("kvm-pv-eoi", NULL);

    enable_compat_apic_id_mode();

    pc_init1(machine, TYPE_I440FX_PCI_HOST_BRIDGE, TYPE_I440FX_PCI_DEVICE);

}


void qemu_aio_ref(void *p)

{

    BlockAIOCB *acb = p;

    acb->refcnt++;

}


matroska_read_header (AVFormatContext    *s,

                      AVFormatParameters *ap)

{

    MatroskaDemuxContext *matroska = s->priv_data;

    char *doctype;

    int version, last_level, res = 0;

    uint32_t id;

    matroska->ctx = s;

    /* First read the EBML header. */

    doctype = NULL;

    if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)

        return res;

    if ((doctype == NULL) || strcmp(doctype, "matroska")) {

        av_log(matroska->ctx, AV_LOG_ERROR,

               "Wrong EBML doctype ('%s' != 'matroska').\n",

               doctype ? doctype : "(none)");

        if (doctype)

            av_free(doctype);

        return AVERROR_NOFMT;

    }

    av_free(doctype);

    if (version > 2) {

        av_log(matroska->ctx, AV_LOG_ERROR,

               "Matroska demuxer version 2 too old for file version %d\n",

               version);

        return AVERROR_NOFMT;

    }

    /* The next thing is a segment. */

    while (1) {

        if (!(id = ebml_peek_id(matroska, &last_level)))

            return AVERROR_IO;

        if (id == MATROSKA_ID_SEGMENT)

            break;

        /* oi! */

        av_log(matroska->ctx, AV_LOG_INFO,

               "Expected a Segment ID (0x%x), but received 0x%x!\n",

               MATROSKA_ID_SEGMENT, id);

        if ((res = ebml_read_skip(matroska)) < 0)

            return res;

    }

    /* We now have a Matroska segment.

     * Seeks are from the beginning of the segment,

     * after the segment ID/length. */

    if ((res = ebml_read_master(matroska, &id)) < 0)

        return res;

    matroska->segment_start = url_ftell(&s->pb);

    matroska->time_scale = 1000000;

    /* we've found our segment, start reading the different contents in here */

    while (res == 0) {

        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {

            res = AVERROR_IO;

            break;

        } else if (matroska->level_up) {

            matroska->level_up--;

            break;

        }

        switch (id) {

            /* stream info */

            case MATROSKA_ID_INFO: {

                if ((res = ebml_read_master(matroska, &id)) < 0)

                    break;

                res = matroska_parse_info(matroska);

                break;

            }

            /* track info headers */

            case MATROSKA_ID_TRACKS: {

                if ((res = ebml_read_master(matroska, &id)) < 0)

                    break;

                res = matroska_parse_tracks(matroska);

                break;

            }

            /* stream index */

            case MATROSKA_ID_CUES: {

                if (!matroska->index_parsed) {

                    if ((res = ebml_read_master(matroska, &id)) < 0)

                        break;

                    res = matroska_parse_index(matroska);

                } else

                    res = ebml_read_skip(matroska);

                break;

            }

            /* metadata */

            case MATROSKA_ID_TAGS: {

                if (!matroska->metadata_parsed) {

                    if ((res = ebml_read_master(matroska, &id)) < 0)

                        break;

                    res = matroska_parse_metadata(matroska);

                } else

                    res = ebml_read_skip(matroska);

                break;

            }

            /* file index (if seekable, seek to Cues/Tags to parse it) */

            case MATROSKA_ID_SEEKHEAD: {

                if ((res = ebml_read_master(matroska, &id)) < 0)

                    break;

                res = matroska_parse_seekhead(matroska);

                break;

            }

            case MATROSKA_ID_CLUSTER: {

                /* Do not read the master - this will be done in the next

                 * call to matroska_read_packet. */

                res = 1;

                break;

            }

            default:

                av_log(matroska->ctx, AV_LOG_INFO,

                       "Unknown matroska file header ID 0x%x\n", id);

            /* fall-through */

            case EBML_ID_VOID:

                res = ebml_read_skip(matroska);

                break;

        }

        if (matroska->level_up) {

            matroska->level_up--;

            break;

        }

    }

    /* Have we found a cluster? */

    if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {

        int i, j;

        MatroskaTrack *track;

        AVStream *st;

        for (i = 0; i < matroska->num_tracks; i++) {

            enum CodecID codec_id = CODEC_ID_NONE;

            uint8_t *extradata = NULL;

            int extradata_size = 0;

            int extradata_offset = 0;

            track = matroska->tracks[i];

            /* libavformat does not really support subtitles.

             * Also apply some sanity checks. */

            if ((track->type == MATROSKA_TRACK_TYPE_SUBTITLE) ||

                (track->codec_id == NULL))

                continue;

            for(j=0; codec_tags[j].str; j++){

                if(!strncmp(codec_tags[j].str, track->codec_id,

                            strlen(codec_tags[j].str))){

                    codec_id= codec_tags[j].id;

                    break;

                }

            }

            /* Set the FourCC from the CodecID. */

            /* This is the MS compatibility mode which stores a

             * BITMAPINFOHEADER in the CodecPrivate. */

            if (!strcmp(track->codec_id,

                        MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&

                (track->codec_priv_size >= 40) &&

                (track->codec_priv != NULL)) {

                unsigned char *p;

                /* Offset of biCompression. Stored in LE. */

                p = (unsigned char *)track->codec_priv + 16;

                ((MatroskaVideoTrack *)track)->fourcc = (p[3] << 24) |

                                 (p[2] << 16) | (p[1] << 8) | p[0];

                codec_id = codec_get_id(codec_bmp_tags, ((MatroskaVideoTrack *)track)->fourcc);

            }

            /* This is the MS compatibility mode which stores a

             * WAVEFORMATEX in the CodecPrivate. */

            else if (!strcmp(track->codec_id,

                             MATROSKA_CODEC_ID_AUDIO_ACM) &&

                (track->codec_priv_size >= 18) &&

                (track->codec_priv != NULL)) {

                unsigned char *p;

                uint16_t tag;

                /* Offset of wFormatTag. Stored in LE. */

                p = (unsigned char *)track->codec_priv;

                tag = (p[1] << 8) | p[0];

                codec_id = codec_get_id(codec_wav_tags, tag);

            }

            else if (codec_id == CODEC_ID_MPEG1VIDEO ||

                     codec_id == CODEC_ID_MPEG2VIDEO ||

                     codec_id == CODEC_ID_MPEG4      ||

                     codec_id == CODEC_ID_MSMPEG4V3  ||

                     codec_id == CODEC_ID_H264) {

                track->flags |= MATROSKA_TRACK_REORDER;

            }

            else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {

                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;

                int profile = matroska_aac_profile(track->codec_id);

                int sri = matroska_aac_sri(audiotrack->internal_samplerate);

                extradata = av_malloc(5);

                if (extradata == NULL)

                    return AVERROR_NOMEM;

                extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);

                extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);

                if (strstr(track->codec_id, "SBR")) {

                    sri = matroska_aac_sri(audiotrack->samplerate);

                    extradata[2] = 0x56;

                    extradata[3] = 0xE5;

                    extradata[4] = 0x80 | (sri<<3);

                    extradata_size = 5;

                } else {

                    extradata_size = 2;

                }

                track->default_duration = 1024*1000 / audiotrack->internal_samplerate;

            }

            else if (codec_id == CODEC_ID_TTA) {

                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;

                ByteIOContext b;

                extradata_size = 30;

                extradata = av_mallocz(extradata_size);

                if (extradata == NULL)

                    return AVERROR_NOMEM;

                init_put_byte(&b, extradata, extradata_size, 1,

                              NULL, NULL, NULL, NULL);

                put_buffer(&b, (uint8_t *) "TTA1", 4);

                put_le16(&b, 1);

                put_le16(&b, audiotrack->channels);

                put_le16(&b, audiotrack->bitdepth);

                put_le32(&b, audiotrack->samplerate);

                put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);

            }

            else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||

                     codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {

                extradata_offset = 26;

                track->codec_priv_size -= extradata_offset;

                track->flags |= MATROSKA_TRACK_REAL_V;

            }

            if (codec_id == CODEC_ID_NONE) {

                av_log(matroska->ctx, AV_LOG_INFO,

                       "Unknown/unsupported CodecID %s.\n",

                       track->codec_id);

            }

            track->stream_index = matroska->num_streams;

            matroska->num_streams++;

            st = av_new_stream(s, track->stream_index);

            if (st == NULL)

                return AVERROR_NOMEM;

            av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */

            st->codec->codec_id = codec_id;

            if (track->default_duration)

                av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,

                          track->default_duration, 1000, 30000);

            if(extradata){

                st->codec->extradata = extradata;

                st->codec->extradata_size = extradata_size;

            } else if(track->codec_priv && track->codec_priv_size > 0){

                st->codec->extradata = av_malloc(track->codec_priv_size);

                if(st->codec->extradata == NULL)

                    return AVERROR_NOMEM;

                st->codec->extradata_size = track->codec_priv_size;

                memcpy(st->codec->extradata,track->codec_priv+extradata_offset,

                       track->codec_priv_size);

            }

            if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {

                MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;

                st->codec->codec_type = CODEC_TYPE_VIDEO;

                st->codec->codec_tag = videotrack->fourcc;

                st->codec->width = videotrack->pixel_width;

                st->codec->height = videotrack->pixel_height;

                if (videotrack->display_width == 0)

                    videotrack->display_width= videotrack->pixel_width;

                if (videotrack->display_height == 0)

                    videotrack->display_height= videotrack->pixel_height;

                av_reduce(&st->codec->sample_aspect_ratio.num,

                          &st->codec->sample_aspect_ratio.den,

                          st->codec->height * videotrack->display_width,

                          st->codec-> width * videotrack->display_height,

                          255);

            } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {

                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;

                st->codec->codec_type = CODEC_TYPE_AUDIO;

                st->codec->sample_rate = audiotrack->samplerate;

                st->codec->channels = audiotrack->channels;

            } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {

                st->codec->codec_type = CODEC_TYPE_SUBTITLE;

            }

            /* What do we do with private data? E.g. for Vorbis. */

        }

        res = 0;

    }

    return res;

}


void spapr_drc_detach(sPAPRDRConnector *drc)

{

    trace_spapr_drc_detach(spapr_drc_index(drc));

    drc->unplug_requested = true;

    if (drc->isolation_state != SPAPR_DR_ISOLATION_STATE_ISOLATED) {

        trace_spapr_drc_awaiting_isolated(spapr_drc_index(drc));

        return;

    }

    if (spapr_drc_type(drc) != SPAPR_DR_CONNECTOR_TYPE_PCI &&

        drc->allocation_state != SPAPR_DR_ALLOCATION_STATE_UNUSABLE) {

        trace_spapr_drc_awaiting_unusable(spapr_drc_index(drc));

        return;

    }

    spapr_drc_release(drc);

}


void cpu_outb(CPUState *env, pio_addr_t addr, uint8_t val)

{

    LOG_IOPORT("outb: %04"FMT_pioaddr" %02"PRIx8"\n", addr, val);

    ioport_write(0, addr, val);

#ifdef CONFIG_KQEMU

    if (env)

        env->last_io_time = cpu_get_time_fast();

#endif

}


void ff_id3v2_read_dict(AVIOContext *pb, AVDictionary **metadata,

                        const char *magic, ID3v2ExtraMeta **extra_meta)

{

    id3v2_read_internal(pb, metadata, NULL, magic, extra_meta);

}


int ff_lpc_calc_coefs(DSPContext *s,

                      const int32_t *samples, int blocksize, int min_order,

                      int max_order, int precision,

                      int32_t coefs[][MAX_LPC_ORDER], int *shift, int use_lpc,

                      int omethod, int max_shift, int zero_shift)

{

    double autoc[MAX_LPC_ORDER+1];

    double ref[MAX_LPC_ORDER];

    double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];

    int i, j, pass;

    int opt_order;

    assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER);

    if(use_lpc == 1){

        s->flac_compute_autocorr(samples, blocksize, max_order, autoc);

        compute_lpc_coefs(autoc, max_order, &lpc[0][0], MAX_LPC_ORDER, 0, 1);

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

            ref[i] = fabs(lpc[i][i]);

    }else{

        LLSModel m[2];

        double var[MAX_LPC_ORDER+1], weight;

        for(pass=0; pass<use_lpc-1; pass++){

            av_init_lls(&m[pass&1], max_order);

            weight=0;

            for(i=max_order; i<blocksize; i++){

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

                    var[j]= samples[i-j];

                if(pass){

                    double eval, inv, rinv;

                    eval= av_evaluate_lls(&m[(pass-1)&1], var+1, max_order-1);

                    eval= (512>>pass) + fabs(eval - var[0]);

                    inv = 1/eval;

                    rinv = sqrt(inv);

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

                        var[j] *= rinv;

                    weight += inv;

                }else

                    weight++;

                av_update_lls(&m[pass&1], var, 1.0);

            }

            av_solve_lls(&m[pass&1], 0.001, 0);

        }

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

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

                lpc[i][j]=-m[(pass-1)&1].coeff[i][j];

            ref[i]= sqrt(m[(pass-1)&1].variance[i] / weight) * (blocksize - max_order) / 4000;

        }

        for(i=max_order-1; i>0; i--)

            ref[i] = ref[i-1] - ref[i];

    }

    opt_order = max_order;

    if(omethod == ORDER_METHOD_EST) {

        opt_order = estimate_best_order(ref, min_order, max_order);

        i = opt_order-1;

        quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i], max_shift, zero_shift);

    } else {

        for(i=min_order-1; i<max_order; i++) {

            quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i], max_shift, zero_shift);

        }

    }

    return opt_order;

}


void xtensa_cpu_list(FILE *f, fprintf_function cpu_fprintf)

{

    cpu_fprintf(f, "Available CPUs:\n"

            "  Xtensa core\n");

}


static inline void gen_jcc1_noeob(DisasContext *s, int b, int l1)

{

    CCPrepare cc = gen_prepare_cc(s, b, cpu_T[0]);

    if (cc.mask != -1) {

        tcg_gen_andi_tl(cpu_T[0], cc.reg, cc.mask);

        cc.reg = cpu_T[0];

    }

    if (cc.use_reg2) {

        tcg_gen_brcond_tl(cc.cond, cc.reg, cc.reg2, l1);

    } else {

        tcg_gen_brcondi_tl(cc.cond, cc.reg, cc.imm, l1);

    }

}


static void *rcu_q_reader(void *arg)

{

    long long j, n_reads_local = 0;

    struct list_element *el;

    *(struct rcu_reader_data **)arg = &rcu_reader;

    atomic_inc(&nthreadsrunning);

    while (goflag == GOFLAG_INIT) {

        g_usleep(1000);

    }

    while (goflag == GOFLAG_RUN) {

        rcu_read_lock();

        QLIST_FOREACH_RCU(el, &Q_list_head, entry) {

            j = atomic_read(&el->val);

            (void)j;

            n_reads_local++;

            if (goflag == GOFLAG_STOP) {

                break;

            }

        }

        rcu_read_unlock();

        g_usleep(100);

    }

    atomic_add(&n_reads, n_reads_local);

    return NULL;

}


static ssize_t local_llistxattr(FsContext *ctx, const char *path,

                                void *value, size_t size)

{

    ssize_t retval;

    ssize_t actual_len = 0;

    char *orig_value, *orig_value_start;

    char *temp_value, *temp_value_start;

    ssize_t xattr_len, parsed_len = 0, attr_len;

    if (ctx->fs_sm != SM_MAPPED) {

        return llistxattr(rpath(ctx, path), value, size);

    }

    /* Get the actual len */

    xattr_len = llistxattr(rpath(ctx, path), value, 0);

    /* Now fetch the xattr and find the actual size */

    orig_value = qemu_malloc(xattr_len);

    xattr_len = llistxattr(rpath(ctx, path), orig_value, xattr_len);

    /*

     * For mapped security model drop user.virtfs namespace

     * from the list

     */

    temp_value = qemu_mallocz(xattr_len);

    temp_value_start = temp_value;

    orig_value_start = orig_value;

    while (xattr_len > parsed_len) {

        attr_len = strlen(orig_value) + 1;

        if (strncmp(orig_value, "user.virtfs.", 12) != 0) {

            /* Copy this entry */

            strcat(temp_value, orig_value);

            temp_value  += attr_len;

            actual_len += attr_len;

        }

        parsed_len += attr_len;

        orig_value += attr_len;

    }

    if (!size) {

        retval = actual_len;

        goto out;

    } else if (size >= actual_len) {

        /* now copy the parsed attribute list back */

        memset(value, 0, size);

        memcpy(value, temp_value_start, actual_len);

        retval = actual_len;

        goto out;

    }

    errno = ERANGE;

    retval = -1;

out:

    qemu_free(orig_value_start);

    qemu_free(temp_value_start);

    return retval;

}