static void mov_fix_index(MOVContext *mov, AVStream *st)

{

    MOVStreamContext *msc = st->priv_data;

    AVIndexEntry *e_old = st->index_entries;

    int nb_old = st->nb_index_entries;

    const AVIndexEntry *e_old_end = e_old + nb_old;

    const AVIndexEntry *current = NULL;

    MOVStts *ctts_data_old = msc->ctts_data;

    int64_t ctts_index_old = 0;

    int64_t ctts_sample_old = 0;

    int64_t ctts_count_old = msc->ctts_count;

    int64_t edit_list_media_time = 0;

    int64_t edit_list_duration = 0;

    int64_t frame_duration = 0;

    int64_t edit_list_dts_counter = 0;

    int64_t edit_list_dts_entry_end = 0;

    int64_t edit_list_start_ctts_sample = 0;

    int64_t curr_cts;

    int64_t curr_ctts = 0;

    int64_t min_corrected_pts = -1;

    int64_t empty_edits_sum_duration = 0;

    int64_t edit_list_index = 0;

    int64_t index;

    int flags;

    int64_t start_dts = 0;

    int64_t edit_list_start_encountered = 0;

    int64_t search_timestamp = 0;

    int64_t* frame_duration_buffer = NULL;

    int num_discarded_begin = 0;

    int first_non_zero_audio_edit = -1;

    int packet_skip_samples = 0;

    MOVIndexRange *current_index_range;

    int i;

    int found_keyframe_after_edit = 0;

    if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {

        return;

    }

    // allocate the index ranges array

    msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0]));

    if (!msc->index_ranges) {

        av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");

        return;

    }

    msc->current_index_range = msc->index_ranges;

    current_index_range = msc->index_ranges - 1;

    // Clean AVStream from traces of old index

    st->index_entries = NULL;

    st->index_entries_allocated_size = 0;

    st->nb_index_entries = 0;

    // Clean ctts fields of MOVStreamContext

    msc->ctts_data = NULL;

    msc->ctts_count = 0;

    msc->ctts_index = 0;

    msc->ctts_sample = 0;

    msc->ctts_allocated_size = 0;

    // If the dts_shift is positive (in case of negative ctts values in mov),

    // then negate the DTS by dts_shift

    if (msc->dts_shift > 0) {

        edit_list_dts_entry_end -= msc->dts_shift;

        av_log(mov->fc, AV_LOG_DEBUG, "Shifting DTS by %d because of negative CTTS.\n", msc->dts_shift);

    }

    start_dts = edit_list_dts_entry_end;

    while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,

                               &edit_list_duration, mov->time_scale)) {

        av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",

               st->index, edit_list_index, edit_list_media_time, edit_list_duration);

        edit_list_index++;

        edit_list_dts_counter = edit_list_dts_entry_end;

        edit_list_dts_entry_end += edit_list_duration;

        num_discarded_begin = 0;

        if (edit_list_media_time == -1) {

            empty_edits_sum_duration += edit_list_duration;

            continue;

        }

        // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them

        // according to the edit list below.

        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {

            if (first_non_zero_audio_edit < 0) {

                first_non_zero_audio_edit = 1;

            } else {

                first_non_zero_audio_edit = 0;

            }

            if (first_non_zero_audio_edit > 0)

                st->skip_samples = msc->start_pad = 0;

        }

        // While reordering frame index according to edit list we must handle properly

        // the scenario when edit list entry starts from none key frame.

        // We find closest previous key frame and preserve it and consequent frames in index.

        // All frames which are outside edit list entry time boundaries will be dropped after decoding.

        search_timestamp = edit_list_media_time;

        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {

            // Audio decoders like AAC need need a decoder delay samples previous to the current sample,

            // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the

            // edit_list_media_time to cover the decoder delay.

            search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp);

        }

        if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, 0,

                                    &index, &ctts_index_old, &ctts_sample_old) < 0) {

            av_log(mov->fc, AV_LOG_WARNING,

                   "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n",

                   st->index, edit_list_index, search_timestamp);

            if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, AVSEEK_FLAG_ANY,

                                        &index, &ctts_index_old, &ctts_sample_old) < 0) {

                av_log(mov->fc, AV_LOG_WARNING,

                       "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n",

                       st->index, edit_list_index, search_timestamp);

                index = 0;

                ctts_index_old = 0;

                ctts_sample_old = 0;

            }

        }

        current = e_old + index;

        edit_list_start_ctts_sample = ctts_sample_old;

        // Iterate over index and arrange it according to edit list

        edit_list_start_encountered = 0;

        found_keyframe_after_edit = 0;

        for (; current < e_old_end; current++, index++) {

            // check  if frame outside edit list mark it for discard

            frame_duration = (current + 1 <  e_old_end) ?

                             ((current + 1)->timestamp - current->timestamp) : edit_list_duration;

            flags = current->flags;

            // frames (pts) before or after edit list

            curr_cts = current->timestamp + msc->dts_shift;

            curr_ctts = 0;

            if (ctts_data_old && ctts_index_old < ctts_count_old) {

                curr_ctts = ctts_data_old[ctts_index_old].duration;

                av_log(mov->fc, AV_LOG_DEBUG, "stts: %"PRId64" ctts: %"PRId64", ctts_index: %"PRId64", ctts_count: %"PRId64"\n",

                       curr_cts, curr_ctts, ctts_index_old, ctts_count_old);

                curr_cts += curr_ctts;

                ctts_sample_old++;

                if (ctts_sample_old == ctts_data_old[ctts_index_old].count) {

                    if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,

                                       &msc->ctts_allocated_size,

                                       ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,

                                       ctts_data_old[ctts_index_old].duration) == -1) {

                        av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",

                               ctts_index_old,

                               ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,

                               ctts_data_old[ctts_index_old].duration);

                        break;

                    }

                    ctts_index_old++;

                    ctts_sample_old = 0;

                    edit_list_start_ctts_sample = 0;

                }

            }

            if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {

                if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&

                    curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&

                    first_non_zero_audio_edit > 0) {

                    packet_skip_samples = edit_list_media_time - curr_cts;

                    st->skip_samples += packet_skip_samples;

                    // Shift the index entry timestamp by packet_skip_samples to be correct.

                    edit_list_dts_counter -= packet_skip_samples;

                    if (edit_list_start_encountered == 0)  {

                        edit_list_start_encountered = 1;

                        // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for

                        // discarded packets.

                        if (frame_duration_buffer) {

                            fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,

                                                       frame_duration_buffer, num_discarded_begin);

                        }

                    }

                    av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);

                } else {

                    flags |= AVINDEX_DISCARD_FRAME;

                    av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);

                    if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && edit_list_start_encountered == 0) {

                        num_discarded_begin++;

                        frame_duration_buffer = av_realloc(frame_duration_buffer,

                                                           num_discarded_begin * sizeof(int64_t));

                        if (!frame_duration_buffer) {

                            av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");

                            break;

                        }

                        frame_duration_buffer[num_discarded_begin - 1] = frame_duration;

                        // Increment skip_samples for the first non-zero audio edit list

                        if (first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {

                            st->skip_samples += frame_duration;

                        }

                    }

                }

            } else {

                if (min_corrected_pts < 0) {

                    min_corrected_pts = edit_list_dts_counter + curr_ctts + msc->dts_shift;

                } else {

                    min_corrected_pts = FFMIN(min_corrected_pts, edit_list_dts_counter + curr_ctts + msc->dts_shift);

                }

                if (edit_list_start_encountered == 0) {

                    edit_list_start_encountered = 1;

                    // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for

                    // discarded packets.

                    if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && frame_duration_buffer) {

                        fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,

                                                   frame_duration_buffer, num_discarded_begin);

                    }

                }

            }

            if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,

                                current->min_distance, flags) == -1) {

                av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");

                break;

            }

            // Update the index ranges array

            if (current_index_range < msc->index_ranges || index != current_index_range->end) {

                current_index_range++;

                current_index_range->start = index;

            }

            current_index_range->end = index + 1;

            // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.

            if (edit_list_start_encountered > 0) {

                edit_list_dts_counter = edit_list_dts_counter + frame_duration;

            }

            // Break when found first key frame after edit entry completion

            if ((curr_cts + frame_duration >= (edit_list_duration + edit_list_media_time)) &&

                ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) {

                if (ctts_data_old) {

                    // If we have CTTS and this is the the first keyframe after edit elist,

                    // wait for one more, because there might be trailing B-frames after this I-frame

                    // that do belong to the edit.

                    if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO && found_keyframe_after_edit == 0) {

                        found_keyframe_after_edit = 1;

                        continue;

                    }

                    if (ctts_sample_old != 0) {

                        if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,

                                           &msc->ctts_allocated_size,

                                           ctts_sample_old - edit_list_start_ctts_sample,

                                           ctts_data_old[ctts_index_old].duration) == -1) {

                            av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",

                                   ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample,

                                   ctts_data_old[ctts_index_old].duration);

                            break;

                        }

                    }

                }

                break;

            }

        }

    }

    // If there are empty edits, then min_corrected_pts might be positive intentionally. So we subtract the

    // sum duration of emtpy edits here.

    min_corrected_pts -= empty_edits_sum_duration;

    // If the minimum pts turns out to be greater than zero after fixing the index, then we subtract the

    // dts by that amount to make the first pts zero.

    if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && min_corrected_pts > 0) {

        av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by %"PRId64" to make first pts zero.\n", min_corrected_pts);

        for (i = 0; i < st->nb_index_entries; ++i) {

            st->index_entries[i].timestamp -= min_corrected_pts;

        }

    }

    // Update av stream length

    st->duration = edit_list_dts_entry_end - start_dts;

    msc->start_pad = st->skip_samples;

    // Free the old index and the old CTTS structures

    av_free(e_old);

    av_free(ctts_data_old);

    // Null terminate the index ranges array

    current_index_range++;

    current_index_range->start = 0;

    current_index_range->end = 0;

    msc->current_index = msc->index_ranges[0].start;

}


int ff_win32_open(const char *filename_utf8, int oflag, int pmode)

{

    int fd;

    int num_chars;

    wchar_t *filename_w;

    /* convert UTF-8 to wide chars */

    num_chars = MultiByteToWideChar(CP_UTF8, 0, filename_utf8, -1, NULL, 0);

    if (num_chars <= 0)

        return -1;

    filename_w = av_mallocz(sizeof(wchar_t) * num_chars);

    MultiByteToWideChar(CP_UTF8, 0, filename_utf8, -1, filename_w, num_chars);

    fd = _wsopen(filename_w, oflag, SH_DENYNO, pmode);

    av_freep(&filename_w);

    /* filename maybe be in CP_ACP */

    if (fd == -1 && !(oflag & O_CREAT))

        return _sopen(filename_utf8, oflag, SH_DENYNO, pmode);

    return fd;

}


static always_inline target_phys_addr_t get_pgaddr (target_phys_addr_t sdr1,

                                                    int sdr_sh,

                                                    target_phys_addr_t hash,

                                                    target_phys_addr_t mask)

{

    return (sdr1 & ((target_ulong)(-1ULL) << sdr_sh)) | (hash & mask);

}


static void ahci_init_d2h(AHCIDevice *ad)

{

    IDEState *ide_state = &ad->port.ifs[0];

    AHCIPortRegs *pr = &ad->port_regs;

    if (ad->init_d2h_sent) {

        return;

    }

    if (ahci_write_fis_d2h(ad)) {

        ad->init_d2h_sent = true;

        /* We're emulating receiving the first Reg H2D Fis from the device;

         * Update the SIG register, but otherwise proceed as normal. */

        pr->sig = (ide_state->hcyl << 24) |

            (ide_state->lcyl << 16) |

            (ide_state->sector << 8) |

            (ide_state->nsector & 0xFF);

    }

}


static void acpi_get_pm_info(AcpiPmInfo *pm)

{

    Object *piix = piix4_pm_find();

    Object *lpc = ich9_lpc_find();

    Object *obj = NULL;

    QObject *o;

    pm->pcihp_io_base = 0;

    pm->pcihp_io_len = 0;

    if (piix) {

        obj = piix;

        pm->cpu_hp_io_base = PIIX4_CPU_HOTPLUG_IO_BASE;

        pm->pcihp_io_base =

            object_property_get_int(obj, ACPI_PCIHP_IO_BASE_PROP, NULL);

        pm->pcihp_io_len =

            object_property_get_int(obj, ACPI_PCIHP_IO_LEN_PROP, NULL);

    }

    if (lpc) {

        obj = lpc;

        pm->cpu_hp_io_base = ICH9_CPU_HOTPLUG_IO_BASE;

    }

    assert(obj);

    pm->cpu_hp_io_len = ACPI_GPE_PROC_LEN;

    pm->mem_hp_io_base = ACPI_MEMORY_HOTPLUG_BASE;

    pm->mem_hp_io_len = ACPI_MEMORY_HOTPLUG_IO_LEN;

    /* Fill in optional s3/s4 related properties */

    o = object_property_get_qobject(obj, ACPI_PM_PROP_S3_DISABLED, NULL);

    if (o) {

        pm->s3_disabled = qint_get_int(qobject_to_qint(o));

    } else {

        pm->s3_disabled = false;

    }

    qobject_decref(o);

    o = object_property_get_qobject(obj, ACPI_PM_PROP_S4_DISABLED, NULL);

    if (o) {

        pm->s4_disabled = qint_get_int(qobject_to_qint(o));

    } else {

        pm->s4_disabled = false;

    }

    qobject_decref(o);

    o = object_property_get_qobject(obj, ACPI_PM_PROP_S4_VAL, NULL);

    if (o) {

        pm->s4_val = qint_get_int(qobject_to_qint(o));

    } else {

        pm->s4_val = false;

    }

    qobject_decref(o);

    /* Fill in mandatory properties */

    pm->sci_int = object_property_get_int(obj, ACPI_PM_PROP_SCI_INT, NULL);

    pm->acpi_enable_cmd = object_property_get_int(obj,

                                                  ACPI_PM_PROP_ACPI_ENABLE_CMD,

                                                  NULL);

    pm->acpi_disable_cmd = object_property_get_int(obj,

                                                  ACPI_PM_PROP_ACPI_DISABLE_CMD,

                                                  NULL);

    pm->io_base = object_property_get_int(obj, ACPI_PM_PROP_PM_IO_BASE,

                                          NULL);

    pm->gpe0_blk = object_property_get_int(obj, ACPI_PM_PROP_GPE0_BLK,

                                           NULL);

    pm->gpe0_blk_len = object_property_get_int(obj, ACPI_PM_PROP_GPE0_BLK_LEN,

                                               NULL);

    pm->pcihp_bridge_en =

        object_property_get_bool(obj, "acpi-pci-hotplug-with-bridge-support",

                                 NULL);

}


SerialState *serial_mm_init (target_phys_addr_t base, int it_shift,

                             qemu_irq irq, int baudbase,

                             CharDriverState *chr, int ioregister)

{

    SerialState *s;

    int s_io_memory;

    s = qemu_mallocz(sizeof(SerialState));

    if (!s)

        return NULL;

    s->irq = irq;

    s->base = base;

    s->it_shift = it_shift;

    s->baudbase= baudbase;

    s->tx_timer = qemu_new_timer(vm_clock, serial_tx_done, s);

    if (!s->tx_timer)

        return NULL;

    qemu_register_reset(serial_reset, s);

    serial_reset(s);

    register_savevm("serial", base, 2, serial_save, serial_load, s);

    if (ioregister) {

        s_io_memory = cpu_register_io_memory(0, serial_mm_read,

                                             serial_mm_write, s);

        cpu_register_physical_memory(base, 8 << it_shift, s_io_memory);

    }

    s->chr = chr;

    qemu_chr_add_handlers(chr, serial_can_receive1, serial_receive1,

                          serial_event, s);

    return s;

}


int qemu_opts_foreach(QemuOptsList *list, qemu_opts_loopfunc func,

                      void *opaque, Error **errp)

{

    Location loc;

    QemuOpts *opts;

    int rc;

    loc_push_none(&loc);

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

        loc_restore(&opts->loc);

        rc = func(opaque, opts, errp);

        if (rc) {

            return rc;

        }

        assert(!errp || !*errp);

    }

    loc_pop(&loc);

    return 0;

}


void bitmap_set_atomic(unsigned long *map, long start, long nr)
{
    unsigned long *p = map + BIT_WORD(start);
    const long size = start + nr;
    int bits_to_set = BITS_PER_LONG - (start % BITS_PER_LONG);
    unsigned long mask_to_set = BITMAP_FIRST_WORD_MASK(start);
    /* First word */
    if (nr - bits_to_set > 0) {
        atomic_or(p, mask_to_set);
        nr -= bits_to_set;
        bits_to_set = BITS_PER_LONG;
        mask_to_set = ~0UL;
        p++;
    }
    /* Full words */
    if (bits_to_set == BITS_PER_LONG) {
        while (nr >= BITS_PER_LONG) {
            *p = ~0UL;
            nr -= BITS_PER_LONG;
            p++;
        }
    }
    /* Last word */
    if (nr) {
        mask_to_set &= BITMAP_LAST_WORD_MASK(size);
        atomic_or(p, mask_to_set);
    } else {
        /* If we avoided the full barrier in atomic_or(), issue a
         * barrier to account for the assignments in the while loop.
         */
        smp_mb();
    }
}


static void test_io_channel_ipv4_fd(void)
{
    QIOChannel *ioc;
    int fd = -1;
    fd = socket(AF_INET, SOCK_STREAM, 0);
    g_assert_cmpint(fd, >, -1);
    ioc = qio_channel_new_fd(fd, &error_abort);
    g_assert_cmpstr(object_get_typename(OBJECT(ioc)),
                    ==,
                    TYPE_QIO_CHANNEL_SOCKET);
    object_unref(OBJECT(ioc));


e1000e_io_read(void *opaque, hwaddr addr, unsigned size)

{

    E1000EState *s = opaque;

    uint32_t idx;

    uint64_t val;

    switch (addr) {

    case E1000_IOADDR:

        trace_e1000e_io_read_addr(s->ioaddr);

        return s->ioaddr;

    case E1000_IODATA:

        if (e1000e_io_get_reg_index(s, &idx)) {

            val = e1000e_core_read(&s->core, idx, sizeof(val));

            trace_e1000e_io_read_data(idx, val);

            return val;

        }

        return 0;

    default:

        trace_e1000e_wrn_io_read_unknown(addr);

        return 0;

    }

}


static void qemu_mutex_unlock_iothread(void)

{

    qemu_mutex_unlock(&qemu_global_mutex);

}


static int s302m_encode2_frame(AVCodecContext *avctx, AVPacket *avpkt,

                               const AVFrame *frame, int *got_packet_ptr)

{

    S302MEncContext *s = avctx->priv_data;

    const int buf_size = AES3_HEADER_LEN +

                        (frame->nb_samples *

                         avctx->channels *

                        (avctx->bits_per_raw_sample + 4)) / 8;

    int ret, c, channels;

    uint8_t *o;

    PutBitContext pb;

    if ((ret = ff_alloc_packet2(avctx, avpkt, buf_size)) < 0)

        return ret;

    o = avpkt->data;

    init_put_bits(&pb, o, buf_size * 8);

    put_bits(&pb, 16, buf_size - AES3_HEADER_LEN);

    put_bits(&pb, 2, (avctx->channels - 2) >> 1);   // number of channels

    put_bits(&pb, 8, 0);                            // channel ID

    put_bits(&pb, 2, (avctx->bits_per_raw_sample - 16) / 4); // bits per samples (0 = 16bit, 1 = 20bit, 2 = 24bit)

    put_bits(&pb, 4, 0);                            // alignments

    flush_put_bits(&pb);

    o += AES3_HEADER_LEN;

    if (avctx->bits_per_raw_sample == 24) {

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

        for (c = 0; c < frame->nb_samples; c++) {

            uint8_t vucf = s->framing_index == 0 ? 0x10: 0;

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

                o[0] = ff_reverse[(samples[0] & 0x0000FF00) >> 8];

                o[1] = ff_reverse[(samples[0] & 0x00FF0000) >> 16];

                o[2] = ff_reverse[(samples[0] & 0xFF000000) >> 24];

                o[3] = ff_reverse[(samples[1] & 0x00000F00) >> 4] | vucf;

                o[4] = ff_reverse[(samples[1] & 0x000FF000) >> 12];

                o[5] = ff_reverse[(samples[1] & 0x0FF00000) >> 20];

                o[6] = ff_reverse[(samples[1] & 0xF0000000) >> 28];

                o += 7;

                samples += 2;

            }

            s->framing_index++;

            if (s->framing_index >= 192)

                s->framing_index = 0;

        }

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

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

        for (c = 0; c < frame->nb_samples; c++) {

            uint8_t vucf = s->framing_index == 0 ? 0x80: 0;

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

                o[0] = ff_reverse[ (samples[0] & 0x000FF000) >> 12];

                o[1] = ff_reverse[ (samples[0] & 0x0FF00000) >> 20];

                o[2] = ff_reverse[((samples[0] & 0xF0000000) >> 28) | vucf];

                o[3] = ff_reverse[ (samples[1] & 0x000FF000) >> 12];

                o[4] = ff_reverse[ (samples[1] & 0x0FF00000) >> 20];

                o[5] = ff_reverse[ (samples[1] & 0xF0000000) >> 28];

                o += 6;

                samples += 2;

            }

            s->framing_index++;

            if (s->framing_index >= 192)

                s->framing_index = 0;

        }

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

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

        for (c = 0; c < frame->nb_samples; c++) {

            uint8_t vucf = s->framing_index == 0 ? 0x10 : 0;

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

                o[0] = ff_reverse[ samples[0] & 0xFF];

                o[1] = ff_reverse[(samples[0] & 0xFF00) >>  8];

                o[2] = ff_reverse[(samples[1] & 0x0F)   <<  4] | vucf;

                o[3] = ff_reverse[(samples[1] & 0x0FF0) >>  4];

                o[4] = ff_reverse[(samples[1] & 0xF000) >> 12];

                o += 5;

                samples += 2;

            }

            s->framing_index++;

            if (s->framing_index >= 192)

                s->framing_index = 0;

        }

    }

    *got_packet_ptr = 1;

    return 0;

}


static int qcow_write(BlockDriverState *bs, int64_t sector_num,

                      const uint8_t *buf, int nb_sectors)

{

    Coroutine *co;

    AioContext *aio_context = bdrv_get_aio_context(bs);

    QcowWriteCo data = {

        .bs         = bs,

        .sector_num = sector_num,

        .buf        = buf,

        .nb_sectors = nb_sectors,

        .ret        = -EINPROGRESS,

    };

    co = qemu_coroutine_create(qcow_write_co_entry);

    qemu_coroutine_enter(co, &data);

    while (data.ret == -EINPROGRESS) {

        aio_poll(aio_context, true);

    }

    return data.ret;

}


void dump_format(AVFormatContext *ic,

                 int index,

                 const char *url,

                 int is_output)

{

    int i;

    uint8_t *printed = av_mallocz(ic->nb_streams);

    if (ic->nb_streams && !printed)

        return;

    av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",

            is_output ? "Output" : "Input",

            index,

            is_output ? ic->oformat->name : ic->iformat->name,

            is_output ? "to" : "from", url);

    dump_metadata(NULL, ic->metadata, "  ");

    if (!is_output) {

        av_log(NULL, AV_LOG_INFO, "  Duration: ");

        if (ic->duration != AV_NOPTS_VALUE) {

            int hours, mins, secs, us;

            secs = ic->duration / AV_TIME_BASE;

            us = ic->duration % AV_TIME_BASE;

            mins = secs / 60;

            secs %= 60;

            hours = mins / 60;

            mins %= 60;

            av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,

                   (100 * us) / AV_TIME_BASE);

        } else {

            av_log(NULL, AV_LOG_INFO, "N/A");

        }

        if (ic->start_time != AV_NOPTS_VALUE) {

            int secs, us;

            av_log(NULL, AV_LOG_INFO, ", start: ");

            secs = ic->start_time / AV_TIME_BASE;

            us = ic->start_time % AV_TIME_BASE;

            av_log(NULL, AV_LOG_INFO, "%d.%06d",

                   secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));

        }

        av_log(NULL, AV_LOG_INFO, ", bitrate: ");

        if (ic->bit_rate) {

            av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);

        } else {

            av_log(NULL, AV_LOG_INFO, "N/A");

        }

        av_log(NULL, AV_LOG_INFO, "\n");

    }

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

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

        av_log(NULL, AV_LOG_INFO, "    Chapter #%d.%d: ", index, i);

        av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));

        av_log(NULL, AV_LOG_INFO, "end %f\n",   ch->end   * av_q2d(ch->time_base));

        dump_metadata(NULL, ch->metadata, "    ");

    }

    if(ic->nb_programs) {

        int j, k, total = 0;

        for(j=0; j<ic->nb_programs; j++) {

            AVMetadataTag *name = av_metadata_get(ic->programs[j]->metadata,

                                                  "name", NULL, 0);

            av_log(NULL, AV_LOG_INFO, "  Program %d %s\n", ic->programs[j]->id,

                   name ? name->value : "");

            dump_metadata(NULL, ic->programs[j]->metadata, "    ");

            for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {

                dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);

                printed[ic->programs[j]->stream_index[k]] = 1;

            }

            total += ic->programs[j]->nb_stream_indexes;

        }

        if (total < ic->nb_streams)

            av_log(NULL, AV_LOG_INFO, "  No Program\n");

    }

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

        if (!printed[i])

            dump_stream_format(ic, i, index, is_output);

    av_free(printed);

}


static void bastardized_rice_decompress(ALACContext *alac,

                                        int32_t *output_buffer,

                                        int output_size,

                                        int readsamplesize,

                                        int rice_history_mult)

{

    int output_count;

    unsigned int history = alac->rice_initial_history;

    int sign_modifier = 0;

    for (output_count = 0; output_count < output_size; output_count++) {

        int32_t x;

        int32_t x_modified;

        int32_t final_val;

        /* standard rice encoding */

        int k; /* size of extra bits */

        /* read k, that is bits as is */

        k = av_log2((history >> 9) + 3);

        x = decode_scalar(&alac->gb, k, alac->rice_limit, readsamplesize);

        x_modified = sign_modifier + x;

        final_val = (x_modified + 1) / 2;

        if (x_modified & 1) final_val *= -1;

        output_buffer[output_count] = final_val;

        sign_modifier = 0;

        /* now update the history */

        history += x_modified * rice_history_mult -

                    ((history * rice_history_mult) >> 9);

        if (x_modified > 0xffff)

            history = 0xffff;

        /* special case: there may be compressed blocks of 0 */

        if ((history < 128) && (output_count+1 < output_size)) {

            int k;

            unsigned int block_size;

            sign_modifier = 1;

            k = 7 - av_log2(history) + ((history + 16) >> 6 /* / 64 */);

            block_size = decode_scalar(&alac->gb, k, alac->rice_limit, 16);

            if (block_size > 0) {

                if(block_size >= output_size - output_count){

                    av_log(alac->avctx, AV_LOG_ERROR, "invalid zero block size of %d %d %d\n", block_size, output_size, output_count);

                    block_size= output_size - output_count - 1;

                }

                memset(&output_buffer[output_count+1], 0, block_size * 4);

                output_count += block_size;

            }

            if (block_size > 0xffff)

                sign_modifier = 0;

            history = 0;

        }

    }

}


void MPV_common_end(MpegEncContext *s)

{

    int i;

    av_freep(&s->mb_type);

    av_freep(&s->p_mv_table);

    av_freep(&s->b_forw_mv_table);

    av_freep(&s->b_back_mv_table);

    av_freep(&s->b_bidir_forw_mv_table);

    av_freep(&s->b_bidir_back_mv_table);

    av_freep(&s->b_direct_mv_table);

    av_freep(&s->motion_val);

    av_freep(&s->dc_val[0]);

    av_freep(&s->ac_val[0]);

    av_freep(&s->coded_block);

    av_freep(&s->mbintra_table);

    av_freep(&s->cbp_table);

    av_freep(&s->pred_dir_table);

    av_freep(&s->me.scratchpad);

    av_freep(&s->me.map);

    av_freep(&s->me.score_map);

    av_freep(&s->mbskip_table);

    av_freep(&s->bitstream_buffer);

    av_freep(&s->tex_pb_buffer);

    av_freep(&s->pb2_buffer);

    av_freep(&s->edge_emu_buffer);

    av_freep(&s->co_located_type_table);

    av_freep(&s->field_mv_table);

    av_freep(&s->field_select_table);

    av_freep(&s->avctx->stats_out);

    av_freep(&s->ac_stats);

    av_freep(&s->error_status_table);

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

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

    }

    s->context_initialized = 0;

}


static void mpeg_decode_sequence_extension(Mpeg1Context *s1)

{

    MpegEncContext *s = &s1->mpeg_enc_ctx;

    int horiz_size_ext, vert_size_ext;

    int bit_rate_ext;

    skip_bits(&s->gb, 1); /* profile and level esc*/

    s->avctx->profile       = get_bits(&s->gb, 3);

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

    s->progressive_sequence = get_bits1(&s->gb);   /* progressive_sequence */

    s->chroma_format        = get_bits(&s->gb, 2); /* chroma_format 1=420, 2=422, 3=444 */

    horiz_size_ext          = get_bits(&s->gb, 2);

    vert_size_ext           = get_bits(&s->gb, 2);

    s->width  |= (horiz_size_ext << 12);

    s->height |= (vert_size_ext  << 12);

    bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */

    s->bit_rate += (bit_rate_ext << 18) * 400;

    skip_bits1(&s->gb); /* marker */

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

    s->low_delay = get_bits1(&s->gb);

    if (s->flags & CODEC_FLAG_LOW_DELAY)

        s->low_delay = 1;

    s1->frame_rate_ext.num = get_bits(&s->gb, 2) + 1;

    s1->frame_rate_ext.den = get_bits(&s->gb, 5) + 1;

    av_dlog(s->avctx, "sequence extension\n");

    s->codec_id = s->avctx->codec_id = AV_CODEC_ID_MPEG2VIDEO;

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

        av_log(s->avctx, AV_LOG_DEBUG,

               "profile: %d, level: %d ps: %d cf:%d vbv buffer: %d, bitrate:%d\n",

               s->avctx->profile, s->avctx->level, s->progressive_sequence, s->chroma_format,

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

}


static TCGArg *tcg_constant_folding(TCGContext *s, uint16_t *tcg_opc_ptr,

                                    TCGArg *args, TCGOpDef *tcg_op_defs)

{

    int i, nb_ops, op_index, nb_temps, nb_globals, nb_call_args;

    TCGOpcode op;

    const TCGOpDef *def;

    TCGArg *gen_args;

    TCGArg tmp;

    /* Array VALS has an element for each temp.

       If this temp holds a constant then its value is kept in VALS' element.

       If this temp is a copy of other ones then this equivalence class'

       representative is kept in VALS' element.

       If this temp is neither copy nor constant then corresponding VALS'

       element is unused. */

    nb_temps = s->nb_temps;

    nb_globals = s->nb_globals;

    memset(temps, 0, nb_temps * sizeof(struct tcg_temp_info));

    nb_ops = tcg_opc_ptr - gen_opc_buf;

    gen_args = args;

    for (op_index = 0; op_index < nb_ops; op_index++) {

        op = gen_opc_buf[op_index];

        def = &tcg_op_defs[op];

        /* Do copy propagation */

        if (!(def->flags & (TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS))) {

            assert(op != INDEX_op_call);

            for (i = def->nb_oargs; i < def->nb_oargs + def->nb_iargs; i++) {

                if (temps[args[i]].state == TCG_TEMP_COPY) {

                    args[i] = temps[args[i]].val;

                }

            }

        }

        /* For commutative operations make constant second argument */

        switch (op) {

        CASE_OP_32_64(add):

        CASE_OP_32_64(mul):

        CASE_OP_32_64(and):

        CASE_OP_32_64(or):

        CASE_OP_32_64(xor):

        CASE_OP_32_64(eqv):

        CASE_OP_32_64(nand):

        CASE_OP_32_64(nor):

            if (temps[args[1]].state == TCG_TEMP_CONST) {

                tmp = args[1];

                args[1] = args[2];

                args[2] = tmp;

            }

            break;

        CASE_OP_32_64(brcond):

            if (temps[args[0]].state == TCG_TEMP_CONST

                && temps[args[1]].state != TCG_TEMP_CONST) {

                tmp = args[0];

                args[0] = args[1];

                args[1] = tmp;

                args[2] = tcg_swap_cond(args[2]);

            }

            break;

        CASE_OP_32_64(setcond):

            if (temps[args[1]].state == TCG_TEMP_CONST

                && temps[args[2]].state != TCG_TEMP_CONST) {

                tmp = args[1];

                args[1] = args[2];

                args[2] = tmp;

                args[3] = tcg_swap_cond(args[3]);

            }

            break;

        default:

            break;

        }

        /* Simplify expressions for "shift/rot r, 0, a => movi r, 0" */

        switch (op) {

        CASE_OP_32_64(shl):

        CASE_OP_32_64(shr):

        CASE_OP_32_64(sar):

        CASE_OP_32_64(rotl):

        CASE_OP_32_64(rotr):

            if (temps[args[1]].state == TCG_TEMP_CONST

                && temps[args[1]].val == 0) {

                gen_opc_buf[op_index] = op_to_movi(op);

                tcg_opt_gen_movi(gen_args, args[0], 0, nb_temps, nb_globals);

                args += 3;

                gen_args += 2;

                continue;

            }

            break;

        default:

            break;

        }

        /* Simplify expression for "op r, a, 0 => mov r, a" cases */

        switch (op) {

        CASE_OP_32_64(add):

        CASE_OP_32_64(sub):

        CASE_OP_32_64(shl):

        CASE_OP_32_64(shr):

        CASE_OP_32_64(sar):

        CASE_OP_32_64(rotl):

        CASE_OP_32_64(rotr):

        CASE_OP_32_64(or):

        CASE_OP_32_64(xor):

            if (temps[args[1]].state == TCG_TEMP_CONST) {

                /* Proceed with possible constant folding. */

                break;

            }

            if (temps[args[2]].state == TCG_TEMP_CONST

                && temps[args[2]].val == 0) {

                if ((temps[args[0]].state == TCG_TEMP_COPY

                    && temps[args[0]].val == args[1])

                    || args[0] == args[1]) {

                    gen_opc_buf[op_index] = INDEX_op_nop;

                } else {

                    gen_opc_buf[op_index] = op_to_mov(op);

                    tcg_opt_gen_mov(gen_args, args[0], args[1],

                                    nb_temps, nb_globals);

                    gen_args += 2;

                }

                args += 3;

                continue;

            }

            break;

        default:

            break;

        }

        /* Simplify expression for "op r, a, 0 => movi r, 0" cases */

        switch (op) {

        CASE_OP_32_64(and):

        CASE_OP_32_64(mul):

            if ((temps[args[2]].state == TCG_TEMP_CONST

                && temps[args[2]].val == 0)) {

                gen_opc_buf[op_index] = op_to_movi(op);

                tcg_opt_gen_movi(gen_args, args[0], 0, nb_temps, nb_globals);

                args += 3;

                gen_args += 2;

                continue;

            }

            break;

        default:

            break;

        }

        /* Simplify expression for "op r, a, a => mov r, a" cases */

        switch (op) {

        CASE_OP_32_64(or):

        CASE_OP_32_64(and):

            if (args[1] == args[2]) {

                if (args[1] == args[0]) {

                    gen_opc_buf[op_index] = INDEX_op_nop;

                } else {

                    gen_opc_buf[op_index] = op_to_mov(op);

                    tcg_opt_gen_mov(gen_args, args[0], args[1], nb_temps,

                                    nb_globals);

                    gen_args += 2;

                }

                args += 3;

                continue;

            }

            break;

        default:

            break;

        }

        /* Propagate constants through copy operations and do constant

           folding.  Constants will be substituted to arguments by register

           allocator where needed and possible.  Also detect copies. */

        switch (op) {

        CASE_OP_32_64(mov):

            if ((temps[args[1]].state == TCG_TEMP_COPY

                && temps[args[1]].val == args[0])

                || args[0] == args[1]) {

                args += 2;

                gen_opc_buf[op_index] = INDEX_op_nop;

                break;

            }

            if (temps[args[1]].state != TCG_TEMP_CONST) {

                tcg_opt_gen_mov(gen_args, args[0], args[1],

                                nb_temps, nb_globals);

                gen_args += 2;

                args += 2;

                break;

            }

            /* Source argument is constant.  Rewrite the operation and

               let movi case handle it. */

            op = op_to_movi(op);

            gen_opc_buf[op_index] = op;

            args[1] = temps[args[1]].val;

            /* fallthrough */

        CASE_OP_32_64(movi):

            tcg_opt_gen_movi(gen_args, args[0], args[1], nb_temps, nb_globals);

            gen_args += 2;

            args += 2;

            break;

        CASE_OP_32_64(not):

        CASE_OP_32_64(neg):

        CASE_OP_32_64(ext8s):

        CASE_OP_32_64(ext8u):

        CASE_OP_32_64(ext16s):

        CASE_OP_32_64(ext16u):

        case INDEX_op_ext32s_i64:

        case INDEX_op_ext32u_i64:

            if (temps[args[1]].state == TCG_TEMP_CONST) {

                gen_opc_buf[op_index] = op_to_movi(op);

                tmp = do_constant_folding(op, temps[args[1]].val, 0);

                tcg_opt_gen_movi(gen_args, args[0], tmp, nb_temps, nb_globals);

            } else {

                reset_temp(args[0], nb_temps, nb_globals);

                gen_args[0] = args[0];

                gen_args[1] = args[1];

            }

            gen_args += 2;

            args += 2;

            break;

        CASE_OP_32_64(add):

        CASE_OP_32_64(sub):

        CASE_OP_32_64(mul):

        CASE_OP_32_64(or):

        CASE_OP_32_64(and):

        CASE_OP_32_64(xor):

        CASE_OP_32_64(shl):

        CASE_OP_32_64(shr):

        CASE_OP_32_64(sar):

        CASE_OP_32_64(rotl):

        CASE_OP_32_64(rotr):

        CASE_OP_32_64(andc):

        CASE_OP_32_64(orc):

        CASE_OP_32_64(eqv):

        CASE_OP_32_64(nand):

        CASE_OP_32_64(nor):

            if (temps[args[1]].state == TCG_TEMP_CONST

                && temps[args[2]].state == TCG_TEMP_CONST) {

                gen_opc_buf[op_index] = op_to_movi(op);

                tmp = do_constant_folding(op, temps[args[1]].val,

                                          temps[args[2]].val);

                tcg_opt_gen_movi(gen_args, args[0], tmp, nb_temps, nb_globals);

                gen_args += 2;

            } else {

                reset_temp(args[0], nb_temps, nb_globals);

                gen_args[0] = args[0];

                gen_args[1] = args[1];

                gen_args[2] = args[2];

                gen_args += 3;

            }

            args += 3;

            break;

        CASE_OP_32_64(setcond):

            if (temps[args[1]].state == TCG_TEMP_CONST

                && temps[args[2]].state == TCG_TEMP_CONST) {

                gen_opc_buf[op_index] = op_to_movi(op);

                tmp = do_constant_folding_cond(op, temps[args[1]].val,

                                               temps[args[2]].val, args[3]);

                tcg_opt_gen_movi(gen_args, args[0], tmp, nb_temps, nb_globals);

                gen_args += 2;

            } else {

                reset_temp(args[0], nb_temps, nb_globals);

                gen_args[0] = args[0];

                gen_args[1] = args[1];

                gen_args[2] = args[2];

                gen_args[3] = args[3];

                gen_args += 4;

            }

            args += 4;

            break;

        CASE_OP_32_64(brcond):

            if (temps[args[0]].state == TCG_TEMP_CONST

                && temps[args[1]].state == TCG_TEMP_CONST) {

                if (do_constant_folding_cond(op, temps[args[0]].val,

                                             temps[args[1]].val, args[2])) {

                    memset(temps, 0, nb_temps * sizeof(struct tcg_temp_info));

                    gen_opc_buf[op_index] = INDEX_op_br;

                    gen_args[0] = args[3];

                    gen_args += 1;

                } else {

                    gen_opc_buf[op_index] = INDEX_op_nop;

                }

            } else {

                memset(temps, 0, nb_temps * sizeof(struct tcg_temp_info));

                reset_temp(args[0], nb_temps, nb_globals);

                gen_args[0] = args[0];

                gen_args[1] = args[1];

                gen_args[2] = args[2];

                gen_args[3] = args[3];

                gen_args += 4;

            }

            args += 4;

            break;

        case INDEX_op_call:

            nb_call_args = (args[0] >> 16) + (args[0] & 0xffff);

            if (!(args[nb_call_args + 1] & (TCG_CALL_CONST | TCG_CALL_PURE))) {

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

                    reset_temp(i, nb_temps, nb_globals);

                }

            }

            for (i = 0; i < (args[0] >> 16); i++) {

                reset_temp(args[i + 1], nb_temps, nb_globals);

            }

            i = nb_call_args + 3;

            while (i) {

                *gen_args = *args;

                args++;

                gen_args++;

                i--;

            }

            break;

        case INDEX_op_set_label:

        case INDEX_op_jmp:

        case INDEX_op_br:

            memset(temps, 0, nb_temps * sizeof(struct tcg_temp_info));

            for (i = 0; i < def->nb_args; i++) {

                *gen_args = *args;

                args++;

                gen_args++;

            }

            break;

        default:

            /* Default case: we do know nothing about operation so no

               propagation is done.  We only trash output args.  */

            for (i = 0; i < def->nb_oargs; i++) {

                reset_temp(args[i], nb_temps, nb_globals);

            }

            for (i = 0; i < def->nb_args; i++) {

                gen_args[i] = args[i];

            }

            args += def->nb_args;

            gen_args += def->nb_args;

            break;

        }

    }

    return gen_args;

}


long do_rt_sigreturn(CPUPPCState *env)

{

    struct target_rt_sigframe *rt_sf = NULL;

    target_ulong rt_sf_addr;

    rt_sf_addr = env->gpr[1] + SIGNAL_FRAMESIZE + 16;

    if (!lock_user_struct(VERIFY_READ, rt_sf, rt_sf_addr, 1))

        goto sigsegv;

    if (do_setcontext(&rt_sf->uc, env, 1))

        goto sigsegv;

    do_sigaltstack(rt_sf_addr

                   + offsetof(struct target_rt_sigframe, uc.tuc_stack),

                   0, env->gpr[1]);

    unlock_user_struct(rt_sf, rt_sf_addr, 1);

    return -TARGET_QEMU_ESIGRETURN;

sigsegv:

    unlock_user_struct(rt_sf, rt_sf_addr, 1);

    force_sig(TARGET_SIGSEGV);

    return 0;

}


void dp83932_init(NICInfo *nd, target_phys_addr_t base, int it_shift,

                  qemu_irq irq, void* mem_opaque,

                  void (*memory_rw)(void *opaque, target_phys_addr_t addr, uint8_t *buf, int len, int is_write))

{

    dp8393xState *s;

    int io;

    qemu_check_nic_model(nd, "dp83932");

    s = qemu_mallocz(sizeof(dp8393xState));

    s->mem_opaque = mem_opaque;

    s->memory_rw = memory_rw;

    s->it_shift = it_shift;

    s->irq = irq;

    s->watchdog = qemu_new_timer(vm_clock, dp8393x_watchdog, s);

    s->regs[SONIC_SR] = 0x0004; /* only revision recognized by Linux */

    s->vc = qemu_new_vlan_client(nd->vlan, nd->model, nd->name,

                                 nic_receive, nic_can_receive, s);

    qemu_format_nic_info_str(s->vc, nd->macaddr);

    qemu_register_reset(nic_reset, s);

    nic_reset(s);

    io = cpu_register_io_memory(0, dp8393x_read, dp8393x_write, s);

    cpu_register_physical_memory(base, 0x40 << it_shift, io);

}


static void v9fs_readdir(void *opaque)

{

    int32_t fid;

    V9fsFidState *fidp;

    ssize_t retval = 0;

    size_t offset = 7;

    int64_t initial_offset;

    int32_t count, max_count;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    pdu_unmarshal(pdu, offset, "dqd", &fid, &initial_offset, &max_count);

    trace_v9fs_readdir(pdu->tag, pdu->id, fid, initial_offset, max_count);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        retval = -EINVAL;

        goto out_nofid;

    }

    if (!fidp->fs.dir) {

        retval = -EINVAL;

        goto out;

    }

    if (initial_offset == 0) {

        v9fs_co_rewinddir(pdu, fidp);

    } else {

        v9fs_co_seekdir(pdu, fidp, initial_offset);

    }

    count = v9fs_do_readdir(pdu, fidp, max_count);

    if (count < 0) {

        retval = count;

        goto out;

    }

    retval = offset;

    retval += pdu_marshal(pdu, offset, "d", count);

    retval += count;

out:

    put_fid(pdu, fidp);

out_nofid:

    complete_pdu(s, pdu, retval);

}


static int IRQ_get_next(OpenPICState *opp, IRQ_queue_t *q)

{

    if (q->next == -1) {

        /* XXX: optimize */

        IRQ_check(opp, q);

    }

    return q->next;

}


int ff_h264_queue_decode_slice(H264Context *h, const H2645NAL *nal)

{

    H264SliceContext *sl = h->slice_ctx + h->nb_slice_ctx_queued;

    int first_slice = sl == h->slice_ctx && !h->current_slice;

    int ret;

    sl->gb = nal->gb;

    ret = h264_slice_header_parse(h, sl, nal);

    if (ret < 0)

        return ret;

    // discard redundant pictures

    if (sl->redundant_pic_count > 0)

        return 0;

    if (sl->first_mb_addr == 0 || !h->current_slice) {

        if (h->setup_finished) {

            av_log(h->avctx, AV_LOG_ERROR, "Too many fields\n");

            return AVERROR_INVALIDDATA;

        }

    }

    if (sl->first_mb_addr == 0) { // FIXME better field boundary detection

        if (h->current_slice) {

            // this slice starts a new field

            // first decode any pending queued slices

            if (h->nb_slice_ctx_queued) {

                H264SliceContext tmp_ctx;

                ret = ff_h264_execute_decode_slices(h);

                if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))

                    return ret;

                memcpy(&tmp_ctx, h->slice_ctx, sizeof(tmp_ctx));

                memcpy(h->slice_ctx, sl, sizeof(tmp_ctx));

                memcpy(sl, &tmp_ctx, sizeof(tmp_ctx));

                sl = h->slice_ctx;

            }

            if (h->cur_pic_ptr && FIELD_PICTURE(h) && h->first_field) {

                ret = ff_h264_field_end(h, h->slice_ctx, 1);

                if (ret < 0)

                    return ret;

            } else if (h->cur_pic_ptr && !FIELD_PICTURE(h) && !h->first_field && h->nal_unit_type  == H264_NAL_IDR_SLICE) {

                av_log(h, AV_LOG_WARNING, "Broken frame packetizing\n");

                ret = ff_h264_field_end(h, h->slice_ctx, 1);

                ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);

                ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);

                h->cur_pic_ptr = NULL;

                if (ret < 0)

                    return ret;

            } else

                return AVERROR_INVALIDDATA;

        }

        if (!h->first_field) {

            if (h->cur_pic_ptr && !h->droppable) {

                ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,

                                          h->picture_structure == PICT_BOTTOM_FIELD);

            }

            h->cur_pic_ptr = NULL;

        }

    }

    if (!h->current_slice)

        av_assert0(sl == h->slice_ctx);

    if (h->current_slice == 0 && !h->first_field) {

        if (

            (h->avctx->skip_frame >= AVDISCARD_NONREF && !h->nal_ref_idc) ||

            (h->avctx->skip_frame >= AVDISCARD_BIDIR  && sl->slice_type_nos == AV_PICTURE_TYPE_B) ||

            (h->avctx->skip_frame >= AVDISCARD_NONINTRA && sl->slice_type_nos != AV_PICTURE_TYPE_I) ||

            (h->avctx->skip_frame >= AVDISCARD_NONKEY && h->nal_unit_type != H264_NAL_IDR_SLICE && h->sei.recovery_point.recovery_frame_cnt < 0) ||

            h->avctx->skip_frame >= AVDISCARD_ALL) {

            return 0;

        }

    }

    if (!first_slice) {

        const PPS *pps = (const PPS*)h->ps.pps_list[sl->pps_id]->data;

        if (h->ps.pps->sps_id != pps->sps_id ||

            h->ps.pps->transform_8x8_mode != pps->transform_8x8_mode /*||

            (h->setup_finished && h->ps.pps != pps)*/) {

            av_log(h->avctx, AV_LOG_ERROR, "PPS changed between slices\n");

            return AVERROR_INVALIDDATA;

        }

        if (h->ps.sps != (const SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data) {

            av_log(h->avctx, AV_LOG_ERROR,

               "SPS changed in the middle of the frame\n");

            return AVERROR_INVALIDDATA;

        }

    }

    if (h->current_slice == 0) {

        ret = h264_field_start(h, sl, nal, first_slice);

        if (ret < 0)

            return ret;

    } else {

        if (h->picture_structure != sl->picture_structure ||

            h->droppable         != (nal->ref_idc == 0)) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "Changing field mode (%d -> %d) between slices is not allowed\n",

                   h->picture_structure, sl->picture_structure);

            return AVERROR_INVALIDDATA;

        } else if (!h->cur_pic_ptr) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "unset cur_pic_ptr on slice %d\n",

                   h->current_slice + 1);

            return AVERROR_INVALIDDATA;

        }

    }

    ret = h264_slice_init(h, sl, nal);

    if (ret < 0)

        return ret;

    h->nb_slice_ctx_queued++;

    return 0;

}


static void end_frame(AVFilterLink *inlink)

{

    GradFunContext *gf = inlink->dst->priv;

    AVFilterBufferRef *inpic = inlink->cur_buf;

    AVFilterLink *outlink = inlink->dst->outputs[0];

    AVFilterBufferRef *outpic = outlink->out_buf;

    int p;

    for (p = 0; p < 4 && inpic->data[p]; p++) {

        int w = inlink->w;

        int h = inlink->h;

        int r = gf->radius;

        if (p) {

            w = gf->chroma_w;

            h = gf->chroma_h;

            r = gf->chroma_r;

        }

        if (FFMIN(w, h) > 2 * r)

            filter(gf, outpic->data[p], inpic->data[p], w, h, outpic->linesize[p], inpic->linesize[p], r);

        else if (outpic->data[p] != inpic->data[p])

            av_image_copy_plane(outpic->data[p], outpic->linesize[p], inpic->data[p], inpic->linesize[p], w, h);

    }

    avfilter_draw_slice(outlink, 0, inlink->h, 1);

    avfilter_end_frame(outlink);

    avfilter_unref_buffer(inpic);

    avfilter_unref_buffer(outpic);

}


SCSIRequest *scsi_req_find(SCSIDevice *d, uint32_t tag)

{

    SCSIRequest *req;

    QTAILQ_FOREACH(req, &d->requests, next) {

        if (req->tag == tag) {

            return req;

        }

    }

    return NULL;

}


static void vbe_update_vgaregs(VGACommonState *s)

{

    int h, shift_control;

    if (!vbe_enabled(s)) {

        /* vbe is turned off -- nothing to do */

        return;

    }

    /* graphic mode + memory map 1 */

    s->gr[VGA_GFX_MISC] = (s->gr[VGA_GFX_MISC] & ~0x0c) | 0x04 |

        VGA_GR06_GRAPHICS_MODE;

    s->cr[VGA_CRTC_MODE] |= 3; /* no CGA modes */

    s->cr[VGA_CRTC_OFFSET] = s->vbe_line_offset >> 3;

    /* width */

    s->cr[VGA_CRTC_H_DISP] =

        (s->vbe_regs[VBE_DISPI_INDEX_XRES] >> 3) - 1;

    /* height (only meaningful if < 1024) */

    h = s->vbe_regs[VBE_DISPI_INDEX_YRES] - 1;

    s->cr[VGA_CRTC_V_DISP_END] = h;

    s->cr[VGA_CRTC_OVERFLOW] = (s->cr[VGA_CRTC_OVERFLOW] & ~0x42) |

        ((h >> 7) & 0x02) | ((h >> 3) & 0x40);

    /* line compare to 1023 */

    s->cr[VGA_CRTC_LINE_COMPARE] = 0xff;

    s->cr[VGA_CRTC_OVERFLOW] |= 0x10;

    s->cr[VGA_CRTC_MAX_SCAN] |= 0x40;

    if (s->vbe_regs[VBE_DISPI_INDEX_BPP] == 4) {

        shift_control = 0;

        s->sr[VGA_SEQ_CLOCK_MODE] &= ~8; /* no double line */

    } else {

        shift_control = 2;

        /* set chain 4 mode */

        s->sr[VGA_SEQ_MEMORY_MODE] |= VGA_SR04_CHN_4M;

        /* activate all planes */

        s->sr[VGA_SEQ_PLANE_WRITE] |= VGA_SR02_ALL_PLANES;

    }

    s->gr[VGA_GFX_MODE] = (s->gr[VGA_GFX_MODE] & ~0x60) |

        (shift_control << 5);

    s->cr[VGA_CRTC_MAX_SCAN] &= ~0x9f; /* no double scan */

}


static void nvdimm_dsm_set_label_data(NVDIMMDevice *nvdimm, NvdimmDsmIn *in,

                                      hwaddr dsm_mem_addr)

{

    NVDIMMClass *nvc = NVDIMM_GET_CLASS(nvdimm);

    NvdimmFuncSetLabelDataIn *set_label_data;

    uint32_t status;

    set_label_data = (NvdimmFuncSetLabelDataIn *)in->arg3;

    le32_to_cpus(&set_label_data->offset);

    le32_to_cpus(&set_label_data->length);

    nvdimm_debug("Write Label Data: offset %#x length %#x.\n",

                 set_label_data->offset, set_label_data->length);

    status = nvdimm_rw_label_data_check(nvdimm, set_label_data->offset,

                                        set_label_data->length);

    if (status != 0 /* Success */) {

        nvdimm_dsm_no_payload(status, dsm_mem_addr);

        return;

    }

    assert(sizeof(*in) + sizeof(*set_label_data) + set_label_data->length <=

           4096);

    nvc->write_label_data(nvdimm, set_label_data->in_buf,

                          set_label_data->length, set_label_data->offset);

    nvdimm_dsm_no_payload(0 /* Success */, dsm_mem_addr);

}


static int64_t load_kernel (CPUMIPSState *env)

{

    int64_t kernel_entry, kernel_low, kernel_high;

    int index = 0;

    long initrd_size;

    ram_addr_t initrd_offset;

    uint32_t *prom_buf;

    long prom_size;

    if (load_elf(loaderparams.kernel_filename, cpu_mips_kseg0_to_phys, NULL,

                 (uint64_t *)&kernel_entry, (uint64_t *)&kernel_low,

                 (uint64_t *)&kernel_high, 0, ELF_MACHINE, 1) < 0) {

        fprintf(stderr, "qemu: could not load kernel '%s'\n",

                loaderparams.kernel_filename);

        exit(1);

    }

    /* load initrd */

    initrd_size = 0;

    initrd_offset = 0;

    if (loaderparams.initrd_filename) {

        initrd_size = get_image_size (loaderparams.initrd_filename);

        if (initrd_size > 0) {

            initrd_offset = (kernel_high + ~INITRD_PAGE_MASK) & INITRD_PAGE_MASK;

            if (initrd_offset + initrd_size > ram_size) {

                fprintf(stderr,

                        "qemu: memory too small for initial ram disk '%s'\n",

                        loaderparams.initrd_filename);

                exit(1);

            }

            initrd_size = load_image_targphys(loaderparams.initrd_filename,

                                     initrd_offset, ram_size - initrd_offset);

        }

        if (initrd_size == (target_ulong) -1) {

            fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",

                    loaderparams.initrd_filename);

            exit(1);

        }

    }

    /* Setup prom parameters. */

    prom_size = ENVP_NB_ENTRIES * (sizeof(int32_t) + ENVP_ENTRY_SIZE);

    prom_buf = g_malloc(prom_size);

    prom_set(prom_buf, index++, "%s", loaderparams.kernel_filename);

    if (initrd_size > 0) {

        prom_set(prom_buf, index++, "rd_start=0x%" PRIx64 " rd_size=%li %s",

                 cpu_mips_phys_to_kseg0(NULL, initrd_offset), initrd_size,

                 loaderparams.kernel_cmdline);

    } else {

        prom_set(prom_buf, index++, "%s", loaderparams.kernel_cmdline);

    }

    /* Setup minimum environment variables */

    prom_set(prom_buf, index++, "busclock=33000000");

    prom_set(prom_buf, index++, "cpuclock=100000000");

    prom_set(prom_buf, index++, "memsize=%i", loaderparams.ram_size/1024/1024);

    prom_set(prom_buf, index++, "modetty0=38400n8r");

    prom_set(prom_buf, index++, NULL);

    rom_add_blob_fixed("prom", prom_buf, prom_size,

                       cpu_mips_kseg0_to_phys(NULL, ENVP_ADDR));

    return kernel_entry;

}


static inline void decode_subband_slice_buffered(SnowContext *s, SubBand *b, slice_buffer * sb, int start_y, int h, int save_state[1]){

    const int w= b->width;

    int y;

    const int qlog= av_clip(s->qlog + b->qlog, 0, QROOT*16);

    int qmul= ff_qexp[qlog&(QROOT-1)]<<(qlog>>QSHIFT);

    int qadd= (s->qbias*qmul)>>QBIAS_SHIFT;

    int new_index = 0;

    if(b->ibuf == s->spatial_idwt_buffer || s->qlog == LOSSLESS_QLOG){

        qadd= 0;

        qmul= 1<<QEXPSHIFT;

    }

    /* If we are on the second or later slice, restore our index. */

    if (start_y != 0)

        new_index = save_state[0];

    for(y=start_y; y<h; y++){

        int x = 0;

        int v;

        IDWTELEM * line = slice_buffer_get_line(sb, y * b->stride_line + b->buf_y_offset) + b->buf_x_offset;

        memset(line, 0, b->width*sizeof(IDWTELEM));

        v = b->x_coeff[new_index].coeff;

        x = b->x_coeff[new_index++].x;

        while(x < w){

            register int t= ( (v>>1)*qmul + qadd)>>QEXPSHIFT;

            register int u= -(v&1);

            line[x] = (t^u) - u;

            v = b->x_coeff[new_index].coeff;

            x = b->x_coeff[new_index++].x;

        }

    }

    /* Save our variables for the next slice. */

    save_state[0] = new_index;

    return;

}


static void coroutine_fn aio_read_response(void *opaque)

{

    SheepdogObjRsp rsp;

    BDRVSheepdogState *s = opaque;

    int fd = s->fd;

    int ret;

    AIOReq *aio_req = NULL;

    SheepdogAIOCB *acb;

    uint64_t idx;

    /* read a header */

    ret = qemu_co_recv(fd, &rsp, sizeof(rsp));

    if (ret != sizeof(rsp)) {

        error_report("failed to get the header, %s", strerror(errno));

        goto err;

    }

    /* find the right aio_req from the inflight aio list */

    QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) {

        if (aio_req->id == rsp.id) {

            break;

        }

    }

    if (!aio_req) {

        error_report("cannot find aio_req %x", rsp.id);

        goto err;

    }

    acb = aio_req->aiocb;

    switch (acb->aiocb_type) {

    case AIOCB_WRITE_UDATA:

        /* this coroutine context is no longer suitable for co_recv

         * because we may send data to update vdi objects */

        s->co_recv = NULL;

        if (!is_data_obj(aio_req->oid)) {

            break;

        }

        idx = data_oid_to_idx(aio_req->oid);

        if (s->inode.data_vdi_id[idx] != s->inode.vdi_id) {

            /*

             * If the object is newly created one, we need to update

             * the vdi object (metadata object).  min_dirty_data_idx

             * and max_dirty_data_idx are changed to include updated

             * index between them.

             */

            if (rsp.result == SD_RES_SUCCESS) {

                s->inode.data_vdi_id[idx] = s->inode.vdi_id;

                s->max_dirty_data_idx = MAX(idx, s->max_dirty_data_idx);

                s->min_dirty_data_idx = MIN(idx, s->min_dirty_data_idx);

            }

            /*

             * Some requests may be blocked because simultaneous

             * create requests are not allowed, so we search the

             * pending requests here.

             */

            send_pending_req(s, aio_req->oid);

        }

        break;

    case AIOCB_READ_UDATA:

        ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov,

                            aio_req->iov_offset, rsp.data_length);

        if (ret != rsp.data_length) {

            error_report("failed to get the data, %s", strerror(errno));

            goto err;

        }

        break;

    case AIOCB_FLUSH_CACHE:

        if (rsp.result == SD_RES_INVALID_PARMS) {

            DPRINTF("disable cache since the server doesn't support it\n");

            s->cache_flags = SD_FLAG_CMD_DIRECT;

            rsp.result = SD_RES_SUCCESS;

        }

        break;

    case AIOCB_DISCARD_OBJ:

        switch (rsp.result) {

        case SD_RES_INVALID_PARMS:

            error_report("sheep(%s) doesn't support discard command",

                         s->host_spec);

            rsp.result = SD_RES_SUCCESS;

            s->discard_supported = false;

            break;

        case SD_RES_SUCCESS:

            idx = data_oid_to_idx(aio_req->oid);

            s->inode.data_vdi_id[idx] = 0;

            break;

        default:

            break;

        }

    }

    switch (rsp.result) {

    case SD_RES_SUCCESS:

        break;

    case SD_RES_READONLY:

        if (s->inode.vdi_id == oid_to_vid(aio_req->oid)) {

            ret = reload_inode(s, 0, "");

            if (ret < 0) {

                goto err;

            }

        }

        if (is_data_obj(aio_req->oid)) {

            aio_req->oid = vid_to_data_oid(s->inode.vdi_id,

                                           data_oid_to_idx(aio_req->oid));

        } else {

            aio_req->oid = vid_to_vdi_oid(s->inode.vdi_id);

        }

        resend_aioreq(s, aio_req);

        goto out;

    default:

        acb->ret = -EIO;

        error_report("%s", sd_strerror(rsp.result));

        break;

    }

    free_aio_req(s, aio_req);

    if (!acb->nr_pending) {

        /*

         * We've finished all requests which belong to the AIOCB, so

         * we can switch back to sd_co_readv/writev now.

         */

        acb->aio_done_func(acb);

    }

out:

    s->co_recv = NULL;

    return;

err:

    s->co_recv = NULL;

    reconnect_to_sdog(opaque);

}


static void dec_rcsr(DisasContext *dc)

{

    LOG_DIS("rcsr r%d, %d\n", dc->r2, dc->csr);

    switch (dc->csr) {

    case CSR_IE:

        tcg_gen_mov_tl(cpu_R[dc->r2], cpu_ie);

        break;

    case CSR_IM:

        gen_helper_rcsr_im(cpu_R[dc->r2], cpu_env);

        break;

    case CSR_IP:

        gen_helper_rcsr_ip(cpu_R[dc->r2], cpu_env);

        break;

    case CSR_CC:

        tcg_gen_mov_tl(cpu_R[dc->r2], cpu_cc);

        break;

    case CSR_CFG:

        tcg_gen_mov_tl(cpu_R[dc->r2], cpu_cfg);

        break;

    case CSR_EBA:

        tcg_gen_mov_tl(cpu_R[dc->r2], cpu_eba);

        break;

    case CSR_DC:

        tcg_gen_mov_tl(cpu_R[dc->r2], cpu_dc);

        break;

    case CSR_DEBA:

        tcg_gen_mov_tl(cpu_R[dc->r2], cpu_deba);

        break;

    case CSR_JTX:

        gen_helper_rcsr_jtx(cpu_R[dc->r2], cpu_env);

        break;

    case CSR_JRX:

        gen_helper_rcsr_jrx(cpu_R[dc->r2], cpu_env);

        break;

    case CSR_ICC:

    case CSR_DCC:

    case CSR_BP0:

    case CSR_BP1:

    case CSR_BP2:

    case CSR_BP3:

    case CSR_WP0:

    case CSR_WP1:

    case CSR_WP2:

    case CSR_WP3:

        cpu_abort(dc->env, "invalid read access csr=%x\n", dc->csr);

        break;

    default:

        cpu_abort(dc->env, "read_csr: unknown csr=%x\n", dc->csr);

        break;

    }

}


uint64_t helper_mulldo(CPUPPCState *env, uint64_t arg1, uint64_t arg2)

{

    int64_t th;

    uint64_t tl;

    muls64(&tl, (uint64_t *)&th, arg1, arg2);

    /* If th != 0 && th != -1, then we had an overflow */

    if (likely((uint64_t)(th + 1) <= 1)) {

        env->ov = 0;

    } else {

        env->so = env->ov = 1;

    }

    return (int64_t)tl;

}


static void pc_init1(MemoryRegion *system_memory,

                     MemoryRegion *system_io,

                     ram_addr_t ram_size,

                     const char *boot_device,

                     const char *kernel_filename,

                     const char *kernel_cmdline,

                     const char *initrd_filename,

                     const char *cpu_model,

                     int pci_enabled,

                     int kvmclock_enabled)

{

    int i;

    ram_addr_t below_4g_mem_size, above_4g_mem_size;

    PCIBus *pci_bus;

    ISABus *isa_bus;

    PCII440FXState *i440fx_state;

    int piix3_devfn = -1;

    qemu_irq *cpu_irq;

    qemu_irq *gsi;

    qemu_irq *i8259;

    qemu_irq *smi_irq;

    GSIState *gsi_state;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    BusState *idebus[MAX_IDE_BUS];

    ISADevice *rtc_state;

    ISADevice *floppy;

    MemoryRegion *ram_memory;

    MemoryRegion *pci_memory;

    MemoryRegion *rom_memory;

    DeviceState *icc_bridge;

    FWCfgState *fw_cfg = NULL;

    PcGuestInfo *guest_info;

    if (xen_enabled() && xen_hvm_init() != 0) {

        fprintf(stderr, "xen hardware virtual machine initialisation failed\n");

        exit(1);

    }

    icc_bridge = qdev_create(NULL, TYPE_ICC_BRIDGE);

    object_property_add_child(qdev_get_machine(), "icc-bridge",

                              OBJECT(icc_bridge), NULL);

    pc_cpus_init(cpu_model, icc_bridge);

    pc_acpi_init("acpi-dsdt.aml");

    if (kvm_enabled() && kvmclock_enabled) {

        kvmclock_create();

    }

    if (ram_size >= 0xe0000000 ) {

        above_4g_mem_size = ram_size - 0xe0000000;

        below_4g_mem_size = 0xe0000000;

    } else {

        above_4g_mem_size = 0;

        below_4g_mem_size = ram_size;

    }

    if (pci_enabled) {

        pci_memory = g_new(MemoryRegion, 1);

        memory_region_init(pci_memory, NULL, "pci", INT64_MAX);

        rom_memory = pci_memory;

    } else {

        pci_memory = NULL;

        rom_memory = system_memory;

    }

    guest_info = pc_guest_info_init(below_4g_mem_size, above_4g_mem_size);

    guest_info->has_pci_info = has_pci_info;

    /* Set PCI window size the way seabios has always done it. */

    /* Power of 2 so bios can cover it with a single MTRR */

    if (ram_size <= 0x80000000)

        guest_info->pci_info.w32.begin = 0x80000000;

    else if (ram_size <= 0xc0000000)

        guest_info->pci_info.w32.begin = 0xc0000000;

    else

        guest_info->pci_info.w32.begin = 0xe0000000;

    /* allocate ram and load rom/bios */

    if (!xen_enabled()) {

        fw_cfg = pc_memory_init(system_memory,

                       kernel_filename, kernel_cmdline, initrd_filename,

                       below_4g_mem_size, above_4g_mem_size,

                       rom_memory, &ram_memory, guest_info);

    }

    gsi_state = g_malloc0(sizeof(*gsi_state));

    if (kvm_irqchip_in_kernel()) {

        kvm_pc_setup_irq_routing(pci_enabled);

        gsi = qemu_allocate_irqs(kvm_pc_gsi_handler, gsi_state,

                                 GSI_NUM_PINS);

    } else {

        gsi = qemu_allocate_irqs(gsi_handler, gsi_state, GSI_NUM_PINS);

    }

    if (pci_enabled) {

        pci_bus = i440fx_init(&i440fx_state, &piix3_devfn, &isa_bus, gsi,

                              system_memory, system_io, ram_size,

                              below_4g_mem_size,

                              0x100000000ULL - below_4g_mem_size,

                              0x100000000ULL + above_4g_mem_size,

                              (sizeof(hwaddr) == 4

                               ? 0

                               : ((uint64_t)1 << 62)),

                              pci_memory, ram_memory);

    } else {

        pci_bus = NULL;

        i440fx_state = NULL;

        isa_bus = isa_bus_new(NULL, system_io);

        no_hpet = 1;

    }

    isa_bus_irqs(isa_bus, gsi);

    if (kvm_irqchip_in_kernel()) {

        i8259 = kvm_i8259_init(isa_bus);

    } else if (xen_enabled()) {

        i8259 = xen_interrupt_controller_init();

    } else {

        cpu_irq = pc_allocate_cpu_irq();

        i8259 = i8259_init(isa_bus, cpu_irq[0]);

    }

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

        gsi_state->i8259_irq[i] = i8259[i];

    }

    if (pci_enabled) {

        ioapic_init_gsi(gsi_state, "i440fx");

    }

    qdev_init_nofail(icc_bridge);

    pc_register_ferr_irq(gsi[13]);

    pc_vga_init(isa_bus, pci_enabled ? pci_bus : NULL);

    /* init basic PC hardware */

    pc_basic_device_init(isa_bus, gsi, &rtc_state, &floppy, xen_enabled());

    pc_nic_init(isa_bus, pci_bus);

    ide_drive_get(hd, MAX_IDE_BUS);

    if (pci_enabled) {

        PCIDevice *dev;

        if (xen_enabled()) {

            dev = pci_piix3_xen_ide_init(pci_bus, hd, piix3_devfn + 1);

        } else {

            dev = pci_piix3_ide_init(pci_bus, hd, piix3_devfn + 1);

        }

        idebus[0] = qdev_get_child_bus(&dev->qdev, "ide.0");

        idebus[1] = qdev_get_child_bus(&dev->qdev, "ide.1");

    } else {

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

            ISADevice *dev;

            dev = isa_ide_init(isa_bus, ide_iobase[i], ide_iobase2[i],

                               ide_irq[i],

                               hd[MAX_IDE_DEVS * i], hd[MAX_IDE_DEVS * i + 1]);

            idebus[i] = qdev_get_child_bus(DEVICE(dev), "ide.0");

        }

    }

    pc_cmos_init(below_4g_mem_size, above_4g_mem_size, boot_device,

                 floppy, idebus[0], idebus[1], rtc_state);

    if (pci_enabled && usb_enabled(false)) {

        pci_create_simple(pci_bus, piix3_devfn + 2, "piix3-usb-uhci");

    }

    if (pci_enabled && acpi_enabled) {

        i2c_bus *smbus;

        smi_irq = qemu_allocate_irqs(pc_acpi_smi_interrupt, first_cpu, 1);

        /* TODO: Populate SPD eeprom data.  */

        smbus = piix4_pm_init(pci_bus, piix3_devfn + 3, 0xb100,

                              gsi[9], *smi_irq,

                              kvm_enabled(), fw_cfg);

        smbus_eeprom_init(smbus, 8, NULL, 0);

    }

    if (pci_enabled) {

        pc_pci_device_init(pci_bus);

    }

    if (has_pvpanic) {

        pvpanic_init(isa_bus);

    }

}


static void verify_irqchip_in_kernel(Error **errp)

{

    if (kvm_irqchip_in_kernel()) {

        return;

    }

    error_setg(errp, "pci-assign requires KVM with in-kernel irqchip enabled");

}


static int ogg_write_header(AVFormatContext *s)

{

    OGGContext *ogg = s->priv_data;

    OGGStreamContext *oggstream = NULL;

    int i, j;

    if (ogg->pref_size)

        av_log(s, AV_LOG_WARNING, "The pagesize option is deprecated\n");

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

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

        unsigned serial_num = i;

        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

            if (st->codec->codec_id == AV_CODEC_ID_OPUS)

                /* Opus requires a fixed 48kHz clock */

                avpriv_set_pts_info(st, 64, 1, 48000);

            else

                avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);

        } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)

            avpriv_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);

        if (st->codec->codec_id != AV_CODEC_ID_VORBIS &&

            st->codec->codec_id != AV_CODEC_ID_THEORA &&

            st->codec->codec_id != AV_CODEC_ID_SPEEX  &&

            st->codec->codec_id != AV_CODEC_ID_FLAC   &&

            st->codec->codec_id != AV_CODEC_ID_OPUS) {

            av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);

            return -1;

        }

        if (!st->codec->extradata || !st->codec->extradata_size) {

            av_log(s, AV_LOG_ERROR, "No extradata present\n");

            return -1;

        }

        oggstream = av_mallocz(sizeof(*oggstream));

        if (!oggstream)

            return AVERROR(ENOMEM);

        oggstream->page.stream_index = i;

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

            do {

                serial_num = av_get_random_seed();

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

                    OGGStreamContext *sc = s->streams[j]->priv_data;

                    if (serial_num == sc->serial_num)

                        break;

                }

            } while (j < i);

        oggstream->serial_num = serial_num;

        av_dict_copy(&st->metadata, s->metadata, AV_DICT_DONT_OVERWRITE);

        st->priv_data = oggstream;

        if (st->codec->codec_id == AV_CODEC_ID_FLAC) {

            int err = ogg_build_flac_headers(st->codec, oggstream,

                                             s->flags & AVFMT_FLAG_BITEXACT,

                                             &st->metadata);

            if (err) {

                av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");

                av_freep(&st->priv_data);

                return err;

            }

        } else if (st->codec->codec_id == AV_CODEC_ID_SPEEX) {

            int err = ogg_build_speex_headers(st->codec, oggstream,

                                              s->flags & AVFMT_FLAG_BITEXACT,

                                              &st->metadata);

            if (err) {

                av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");

                av_freep(&st->priv_data);

                return err;

            }

        } else if (st->codec->codec_id == AV_CODEC_ID_OPUS) {

            int err = ogg_build_opus_headers(st->codec, oggstream,

                                             s->flags & AVFMT_FLAG_BITEXACT,

                                             &st->metadata);

            if (err) {

                av_log(s, AV_LOG_ERROR, "Error writing Opus headers\n");

                av_freep(&st->priv_data);

                return err;

            }

        } else {

            uint8_t *p;

            const char *cstr = st->codec->codec_id == AV_CODEC_ID_VORBIS ? "vorbis" : "theora";

            int header_type = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 3 : 0x81;

            int framing_bit = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 1 : 0;

            if (avpriv_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,

                                      st->codec->codec_id == AV_CODEC_ID_VORBIS ? 30 : 42,

                                      oggstream->header, oggstream->header_len) < 0) {

                av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");

                av_freep(&st->priv_data);

                return -1;

            }

            p = ogg_write_vorbiscomment(7, s->flags & AVFMT_FLAG_BITEXACT,

                                        &oggstream->header_len[1], &st->metadata,

                                        framing_bit);

            oggstream->header[1] = p;

            if (!p)

                return AVERROR(ENOMEM);

            bytestream_put_byte(&p, header_type);

            bytestream_put_buffer(&p, cstr, 6);

            if (st->codec->codec_id == AV_CODEC_ID_THEORA) {

                /** KFGSHIFT is the width of the less significant section of the granule position

                    The less significant section is the frame count since the last keyframe */

                oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);

                oggstream->vrev = oggstream->header[0][9];

                av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",

                       oggstream->kfgshift, oggstream->vrev);

            }

        }

    }

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

        OGGStreamContext *oggstream = s->streams[j]->priv_data;

        ogg_buffer_data(s, s->streams[j], oggstream->header[0],

                        oggstream->header_len[0], 0, 1);

        oggstream->page.flags |= 2; // bos

        ogg_buffer_page(s, oggstream);

    }

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

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

        OGGStreamContext *oggstream = st->priv_data;

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

            if (oggstream->header_len[i])

                ogg_buffer_data(s, st, oggstream->header[i],

                                oggstream->header_len[i], 0, 1);

        }

        ogg_buffer_page(s, oggstream);

    }

    oggstream->page.start_granule = AV_NOPTS_VALUE;

    ogg_write_pages(s, 1);

    return 0;

}


static int write_refcount_block(BlockDriverState *bs)

{

    BDRVQcowState *s = bs->opaque;

    size_t size = s->cluster_size;

    if (s->refcount_block_cache_offset == 0) {

        return 0;

    }

    BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_UPDATE);

    if (bdrv_pwrite(bs->file, s->refcount_block_cache_offset,

            s->refcount_block_cache, size) != size)

    {

        return -EIO;

    }

    return 0;

}


static int aiff_read_packet(AVFormatContext *s,

                            AVPacket *pkt)

{

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

    AIFFInputContext *aiff = s->priv_data;

    int64_t max_size;

    int res, size;

    /* calculate size of remaining data */

    max_size = aiff->data_end - avio_tell(s->pb);

    if (max_size <= 0)

        return AVERROR_EOF;

    /* Now for that packet */

    if (st->codec->block_align >= 33) // GSM, QCLP, IMA4

        size = st->codec->block_align;

    else

        size = (MAX_SIZE / st->codec->block_align) * st->codec->block_align;

    size = FFMIN(max_size, size);

    res = av_get_packet(s->pb, pkt, size);

    if (res < 0)

        return res;

    /* Only one stream in an AIFF file */

    pkt->stream_index = 0;

    pkt->duration     = (res / st->codec->block_align) * aiff->block_duration;

    return 0;

}


static target_long monitor_get_ccr (const struct MonitorDef *md, int val)

{

    CPUArchState *env = mon_get_cpu();

    unsigned int u;

    int i;

    u = 0;

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

        u |= env->crf[i] << (32 - (4 * i));

    return u;

}


static void yae_clear(ATempoContext *atempo)

{

    atempo->size = 0;

    atempo->head = 0;

    atempo->tail = 0;

    atempo->drift = 0;

    atempo->nfrag = 0;

    atempo->state = YAE_LOAD_FRAGMENT;

    atempo->position[0] = 0;

    atempo->position[1] = 0;

    atempo->frag[0].position[0] = 0;

    atempo->frag[0].position[1] = 0;

    atempo->frag[0].nsamples    = 0;

    atempo->frag[1].position[0] = 0;

    atempo->frag[1].position[1] = 0;

    atempo->frag[1].nsamples    = 0;

    // shift left position of 1st fragment by half a window

    // so that no re-normalization would be required for

    // the left half of the 1st fragment:

    atempo->frag[0].position[0] = -(int64_t)(atempo->window / 2);

    atempo->frag[0].position[1] = -(int64_t)(atempo->window / 2);

    av_frame_free(&atempo->dst_buffer);

    atempo->dst     = NULL;

    atempo->dst_end = NULL;

    atempo->request_fulfilled = 0;

    atempo->nsamples_in       = 0;

    atempo->nsamples_out      = 0;

}


static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s,

                                  Jpeg2000CodingStyle *codsty,

                                  Jpeg2000ResLevel *rlevel, int precno,

                                  int layno, uint8_t *expn, int numgbits)

{

    int bandno, cblkno, ret, nb_code_blocks;

    if (!(ret = get_bits(s, 1))) {

        jpeg2000_flush(s);

        return 0;

    } else if (ret < 0)

        return ret;

    for (bandno = 0; bandno < rlevel->nbands; bandno++) {

        Jpeg2000Band *band = rlevel->band + bandno;

        Jpeg2000Prec *prec = band->prec + precno;

        if (band->coord[0][0] == band->coord[0][1] ||

            band->coord[1][0] == band->coord[1][1])

            continue;

        prec->yi0 = 0;

        prec->xi0 = 0;

        nb_code_blocks =  prec->nb_codeblocks_height *

                          prec->nb_codeblocks_width;

        for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {

            Jpeg2000Cblk *cblk = prec->cblk + cblkno;

            int incl, newpasses, llen;

            if (cblk->npasses)

                incl = get_bits(s, 1);

            else

                incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;

            if (!incl)

                continue;

            else if (incl < 0)

                return incl;

            if (!cblk->npasses)

                cblk->nonzerobits = expn[bandno] + numgbits - 1 -

                                    tag_tree_decode(s, prec->zerobits + cblkno,

                                                    100);

            if ((newpasses = getnpasses(s)) < 0)

                return newpasses;

            if ((llen = getlblockinc(s)) < 0)

                return llen;

            cblk->lblock += llen;

            if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)

                return ret;

            cblk->lengthinc = ret;

            cblk->npasses  += newpasses;

        }

    }

    jpeg2000_flush(s);

    if (codsty->csty & JPEG2000_CSTY_EPH) {

        if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)

            bytestream2_skip(&s->g, 2);

        else

            av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");

    }

    for (bandno = 0; bandno < rlevel->nbands; bandno++) {

        Jpeg2000Band *band = rlevel->band + bandno;

        Jpeg2000Prec *prec = band->prec + precno;

        nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;

        for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {

            Jpeg2000Cblk *cblk = prec->cblk + cblkno;

            if (bytestream2_get_bytes_left(&s->g) < cblk->lengthinc)

                return AVERROR(EINVAL);

            /* Code-block data can be empty. In that case initialize data

             * with 0xFFFF. */

            if (cblk->lengthinc > 0) {

                bytestream2_get_bufferu(&s->g, cblk->data, cblk->lengthinc);

            } else {

                cblk->data[0] = 0xFF;

                cblk->data[1] = 0xFF;

            }

            cblk->length   += cblk->lengthinc;

            cblk->lengthinc = 0;

        }

    }

    return 0;

}


void ff_celp_lp_synthesis_filterf(float *out, const float *filter_coeffs,

                                  const float* in, int buffer_length,

                                  int filter_length)

{

    int i,n;

#if 0 // Unoptimized code path for improved readability

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

        out[n] = in[n];

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

            out[n] -= filter_coeffs[i-1] * out[n-i];

    }

#else

    float out0, out1, out2, out3;

    float old_out0, old_out1, old_out2, old_out3;

    float a,b,c;

    a = filter_coeffs[0];

    b = filter_coeffs[1];

    c = filter_coeffs[2];

    b -= filter_coeffs[0] * filter_coeffs[0];

    c -= filter_coeffs[1] * filter_coeffs[0];

    c -= filter_coeffs[0] * b;

    old_out0 = out[-4];

    old_out1 = out[-3];

    old_out2 = out[-2];

    old_out3 = out[-1];

    for (n = 0; n <= buffer_length - 4; n+=4) {

        float tmp0,tmp1,tmp2;

        float val;

        out0 = in[0];

        out1 = in[1];

        out2 = in[2];

        out3 = in[3];

        out0 -= filter_coeffs[2] * old_out1;

        out1 -= filter_coeffs[2] * old_out2;

        out2 -= filter_coeffs[2] * old_out3;

        out0 -= filter_coeffs[1] * old_out2;

        out1 -= filter_coeffs[1] * old_out3;

        out0 -= filter_coeffs[0] * old_out3;

        val = filter_coeffs[3];

        out0 -= val * old_out0;

        out1 -= val * old_out1;

        out2 -= val * old_out2;

        out3 -= val * old_out3;

        for (i = 5; i <= filter_length; i += 2) {

            old_out3 = out[-i];

            val = filter_coeffs[i-1];

            out0 -= val * old_out3;

            out1 -= val * old_out0;

            out2 -= val * old_out1;

            out3 -= val * old_out2;

            old_out2 = out[-i-1];

            val = filter_coeffs[i];

            out0 -= val * old_out2;

            out1 -= val * old_out3;

            out2 -= val * old_out0;

            out3 -= val * old_out1;

            FFSWAP(float, old_out0, old_out2);

            old_out1 = old_out3;

        }

        tmp0 = out0;

        tmp1 = out1;

        tmp2 = out2;

        out3 -= a * tmp2;

        out2 -= a * tmp1;

        out1 -= a * tmp0;

        out3 -= b * tmp1;

        out2 -= b * tmp0;

        out3 -= c * tmp0;

        out[0] = out0;

        out[1] = out1;

        out[2] = out2;

        out[3] = out3;

        old_out0 = out0;

        old_out1 = out1;

        old_out2 = out2;

        old_out3 = out3;

        out += 4;

        in  += 4;

    }

    out -= n;

    in -= n;

    for (; n < buffer_length; n++) {

        out[n] = in[n];

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

            out[n] -= filter_coeffs[i-1] * out[n-i];

    }

#endif

}


static int decode_b_picture_header(VC9Context *v)

{

    int pqindex;

    /* Prolog common to all frametypes should be done in caller */

    if (v->profile == PROFILE_SIMPLE)

    {

        av_log(v, AV_LOG_ERROR, "Found a B frame while in Simple Profile!\n");

        return FRAME_SKIPED;

    }

    v->bfraction = vc9_bfraction_lut[get_vlc2(&v->gb, vc9_bfraction_vlc.table,

                                              VC9_BFRACTION_VLC_BITS, 2)];

    if (v->bfraction < -1)

    {

        av_log(v, AV_LOG_ERROR, "Invalid BFRaction\n");

        return FRAME_SKIPED;

    }

    else if (!v->bfraction)

    {

        /* We actually have a BI frame */

        return decode_bi_picture_header(v);

    }

    /* Read the quantization stuff */

    pqindex = get_bits(&v->gb, 5);

    if (v->quantizer_mode == QUANT_FRAME_IMPLICIT)

        v->pq = pquant_table[0][pqindex];

    else

    {

        v->pq = pquant_table[v->quantizer_mode-1][pqindex];

    }

    if (pqindex < 9) v->halfpq = get_bits(&v->gb, 1);

    if (v->quantizer_mode == QUANT_FRAME_EXPLICIT)

        v->pquantizer = get_bits(&v->gb, 1);

    /* Read the MV type/mode */

    if (v->extended_mv == 1)

        v->mvrange = get_prefix(&v->gb, 0, 3);

    v->mv_mode = get_bits(&v->gb, 1);

    if (v->pq < 13)

    {

        if (!v->mv_mode)

        {

            v->mv_mode = get_bits(&v->gb, 2);

            if (v->mv_mode)

                av_log(v, AV_LOG_ERROR,

                       "mv_mode for lowquant B frame was %i\n", v->mv_mode);

        }

    }

    else

    {

        if (!v->mv_mode)

        {

            if (get_bits(&v->gb, 1))

                av_log(v, AV_LOG_ERROR,

                       "mv_mode for highquant B frame was %i\n", v->mv_mode);

        }

        v->mv_mode = 1-v->mv_mode; //To match (pq < 13) mapping

    }

    if (v->mv_mode == MV_PMODE_MIXED_MV)

    {

        if (bitplane_decoding( v->mv_type_mb_plane, v->width_mb,

                                   v->height_mb, v)<0)

            return -1;

    }

    //bitplane

    bitplane_decoding(v->direct_mb_plane, v->width_mb, v->height_mb, v);

    bitplane_decoding(v->skip_mb_plane, v->width_mb, v->height_mb, v);

    /* FIXME: what is actually chosen for B frames ? */

    v->mv_diff_vlc = &vc9_mv_diff_vlc[get_bits(&v->gb, 2)];

    v->cbpcy_vlc = &vc9_cbpcy_p_vlc[get_bits(&v->gb, 2)];

    if (v->dquant)

    {

        vop_dquant_decoding(v);

    }

    if (v->vstransform)

    {

        v->ttmbf = get_bits(&v->gb, 1);

        if (v->ttmbf)

        {

            v->ttfrm = get_bits(&v->gb, 2);

            av_log(v, AV_LOG_INFO, "Transform used: %ix%i\n",

                   (v->ttfrm & 2) ? 4 : 8, (v->ttfrm & 1) ? 4 : 8);

        }

    }

    /* Epilog should be done in caller */

    return 0;

}


static int sipr_decode_frame(AVCodecContext *avctx, void *datap,

                             int *data_size, AVPacket *avpkt)

{

    SiprContext *ctx = avctx->priv_data;

    const uint8_t *buf=avpkt->data;

    SiprParameters parm;

    const SiprModeParam *mode_par = &modes[ctx->mode];

    GetBitContext gb;

    float *data = datap;

    int subframe_size = ctx->mode == MODE_16k ? L_SUBFR_16k : SUBFR_SIZE;

    int i;

    ctx->avctx = avctx;

    if (avpkt->size < (mode_par->bits_per_frame >> 3)) {

        av_log(avctx, AV_LOG_ERROR,

               "Error processing packet: packet size (%d) too small\n",

               avpkt->size);

        *data_size = 0;

        return -1;

    }

    if (*data_size < subframe_size * mode_par->subframe_count * sizeof(float)) {

        av_log(avctx, AV_LOG_ERROR,

               "Error processing packet: output buffer (%d) too small\n",

               *data_size);

        *data_size = 0;

        return -1;

    }

    init_get_bits(&gb, buf, mode_par->bits_per_frame);

    for (i = 0; i < mode_par->frames_per_packet; i++) {

        decode_parameters(&parm, &gb, mode_par);

        if (ctx->mode == MODE_16k)

            ff_sipr_decode_frame_16k(ctx, &parm, data);

        else

            decode_frame(ctx, &parm, data);

        data += subframe_size * mode_par->subframe_count;

    }

    *data_size = mode_par->frames_per_packet * subframe_size *

        mode_par->subframe_count * sizeof(float);

    return mode_par->bits_per_frame >> 3;

}


static void qapi_dealloc_end_list(Visitor *v)

{

    QapiDeallocVisitor *qov = to_qov(v);

    void *obj = qapi_dealloc_pop(qov);

    assert(obj == NULL); /* should've been list head tracker with no payload */

}


static int oss_init_in (HWVoiceIn *hw, audsettings_t *as)

{

    OSSVoiceIn *oss = (OSSVoiceIn *) hw;

    struct oss_params req, obt;

    int endianness;

    int err;

    int fd;

    audfmt_e effective_fmt;

    audsettings_t obt_as;

    oss->fd = -1;

    req.fmt = aud_to_ossfmt (as->fmt);

    req.freq = as->freq;

    req.nchannels = as->nchannels;

    req.fragsize = conf.fragsize;

    req.nfrags = conf.nfrags;

    if (oss_open (1, &req, &obt, &fd)) {

        return -1;

    }

    err = oss_to_audfmt (obt.fmt, &effective_fmt, &endianness);

    if (err) {

        oss_anal_close (&fd);

        return -1;

    }

    obt_as.freq = obt.freq;

    obt_as.nchannels = obt.nchannels;

    obt_as.fmt = effective_fmt;

    obt_as.endianness = endianness;

    audio_pcm_init_info (&hw->info, &obt_as);

    oss->nfrags = obt.nfrags;

    oss->fragsize = obt.fragsize;

    if (obt.nfrags * obt.fragsize & hw->info.align) {

        dolog ("warning: Misaligned ADC buffer, size %d, alignment %d\n",

               obt.nfrags * obt.fragsize, hw->info.align + 1);

    }

    hw->samples = (obt.nfrags * obt.fragsize) >> hw->info.shift;

    oss->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);

    if (!oss->pcm_buf) {

        dolog ("Could not allocate ADC buffer (%d samples, each %d bytes)\n",

               hw->samples, 1 << hw->info.shift);

        oss_anal_close (&fd);

        return -1;

    }

    oss->fd = fd;

    return 0;

}


static void gen_lswi(DisasContext *ctx)

{

    TCGv t0;

    TCGv_i32 t1, t2;

    int nb = NB(ctx->opcode);

    int start = rD(ctx->opcode);

    int ra = rA(ctx->opcode);

    int nr;

    if (nb == 0)

        nb = 32;

    nr = nb / 4;

    if (unlikely(((start + nr) > 32  &&

                  start <= ra && (start + nr - 32) > ra) ||

                 ((start + nr) <= 32 && start <= ra && (start + nr) > ra))) {

        gen_inval_exception(ctx, POWERPC_EXCP_INVAL_LSWX);

        return;

    }

    gen_set_access_type(ctx, ACCESS_INT);

    /* NIP cannot be restored if the memory exception comes from an helper */

    gen_update_nip(ctx, ctx->nip - 4);

    t0 = tcg_temp_new();

    gen_addr_register(ctx, t0);

    t1 = tcg_const_i32(nb);

    t2 = tcg_const_i32(start);

    gen_helper_lsw(cpu_env, t0, t1, t2);

    tcg_temp_free(t0);

    tcg_temp_free_i32(t1);

    tcg_temp_free_i32(t2);

}


static void vmsvga_value_write(void *opaque, uint32_t address, uint32_t value)

{

    struct vmsvga_state_s *s = opaque;

    switch (s->index) {

    case SVGA_REG_ID:

        if (value == SVGA_ID_2 || value == SVGA_ID_1 || value == SVGA_ID_0)

            s->svgaid = value;

        break;

    case SVGA_REG_ENABLE:

        s->enable = value;

        s->config &= !!value;

        s->width = -1;

        s->height = -1;

        s->invalidated = 1;

        s->vga.invalidate(&s->vga);

        if (s->enable) {

            s->fb_size = ((s->depth + 7) >> 3) * s->new_width * s->new_height;

            vga_dirty_log_stop(&s->vga);

        } else {

            vga_dirty_log_start(&s->vga);

        }

        break;

    case SVGA_REG_WIDTH:

        s->new_width = value;

        s->invalidated = 1;

        break;

    case SVGA_REG_HEIGHT:

        s->new_height = value;

        s->invalidated = 1;

        break;

    case SVGA_REG_DEPTH:

    case SVGA_REG_BITS_PER_PIXEL:

        if (value != s->depth) {

            printf("%s: Bad colour depth: %i bits\n", __FUNCTION__, value);

            s->config = 0;

        }

        break;

    case SVGA_REG_CONFIG_DONE:

        if (value) {

            s->fifo = (uint32_t *) s->fifo_ptr;

            /* Check range and alignment.  */

            if ((CMD(min) | CMD(max) |

                        CMD(next_cmd) | CMD(stop)) & 3)

                break;

            if (CMD(min) < (uint8_t *) s->cmd->fifo - (uint8_t *) s->fifo)

                break;

            if (CMD(max) > SVGA_FIFO_SIZE)

                break;

            if (CMD(max) < CMD(min) + 10 * 1024)

                break;

        }

        s->config = !!value;

        break;

    case SVGA_REG_SYNC:

        s->syncing = 1;

        vmsvga_fifo_run(s); /* Or should we just wait for update_display? */

        break;

    case SVGA_REG_GUEST_ID:

        s->guest = value;

#ifdef VERBOSE

        if (value >= GUEST_OS_BASE && value < GUEST_OS_BASE +

                ARRAY_SIZE(vmsvga_guest_id))

            printf("%s: guest runs %s.\n", __FUNCTION__,

                            vmsvga_guest_id[value - GUEST_OS_BASE]);

#endif

        break;

    case SVGA_REG_CURSOR_ID:

        s->cursor.id = value;

        break;

    case SVGA_REG_CURSOR_X:

        s->cursor.x = value;

        break;

    case SVGA_REG_CURSOR_Y:

        s->cursor.y = value;

        break;

    case SVGA_REG_CURSOR_ON:

        s->cursor.on |= (value == SVGA_CURSOR_ON_SHOW);

        s->cursor.on &= (value != SVGA_CURSOR_ON_HIDE);

#ifdef HW_MOUSE_ACCEL

        if (value <= SVGA_CURSOR_ON_SHOW) {

            dpy_mouse_set(s->vga.ds, s->cursor.x, s->cursor.y, s->cursor.on);

        }

#endif

        break;

    case SVGA_REG_MEM_REGS:

    case SVGA_REG_NUM_DISPLAYS:

    case SVGA_REG_PITCHLOCK:

    case SVGA_PALETTE_BASE ... SVGA_PALETTE_END:

        break;

    default:

        if (s->index >= SVGA_SCRATCH_BASE &&

                s->index < SVGA_SCRATCH_BASE + s->scratch_size) {

            s->scratch[s->index - SVGA_SCRATCH_BASE] = value;

            break;

        }

        printf("%s: Bad register %02x\n", __FUNCTION__, s->index);

    }

}