static void filter_mb_mbaff_edgev( H264Context *h, uint8_t *pix, int stride, int16_t bS[8], int qp[2] ) {

    int i;

    for( i = 0; i < 16; i++, pix += stride) {

        int index_a;

        int alpha;

        int beta;

        int qp_index;

        int bS_index = (i >> 1);

        if (!MB_FIELD) {

            bS_index &= ~1;

            bS_index |= (i & 1);

        }

        if( bS[bS_index] == 0 ) {

            continue;

        }

        qp_index = MB_FIELD ? (i >> 3) : (i & 1);

        index_a = qp[qp_index] + h->slice_alpha_c0_offset;

        alpha = (alpha_table+52)[index_a];

        beta  = (beta_table+52)[qp[qp_index] + h->slice_beta_offset];

        if( bS[bS_index] < 4 ) {

            const int tc0 = (tc0_table+52)[index_a][bS[bS_index] - 1];

            const int p0 = pix[-1];

            const int p1 = pix[-2];

            const int p2 = pix[-3];

            const int q0 = pix[0];

            const int q1 = pix[1];

            const int q2 = pix[2];

            if( FFABS( p0 - q0 ) < alpha &&

                FFABS( p1 - p0 ) < beta &&

                FFABS( q1 - q0 ) < beta ) {

                int tc = tc0;

                int i_delta;

                if( FFABS( p2 - p0 ) < beta ) {

                    pix[-2] = p1 + av_clip( ( p2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( p1 << 1 ) ) >> 1, -tc0, tc0 );

                    tc++;

                }

                if( FFABS( q2 - q0 ) < beta ) {

                    pix[1] = q1 + av_clip( ( q2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( q1 << 1 ) ) >> 1, -tc0, tc0 );

                    tc++;

                }

                i_delta = av_clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );

                pix[-1] = av_clip_uint8( p0 + i_delta );    /* p0' */

                pix[0]  = av_clip_uint8( q0 - i_delta );    /* q0' */

                tprintf(h->s.avctx, "filter_mb_mbaff_edgev i:%d, qp:%d, indexA:%d, alpha:%d, beta:%d, tc:%d\n# bS:%d -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x]\n", i, qp[qp_index], index_a, alpha, beta, tc, bS[bS_index], pix[-3], p1, p0, q0, q1, pix[2], p1, pix[-1], pix[0], q1);

            }

        }else{

            const int p0 = pix[-1];

            const int p1 = pix[-2];

            const int p2 = pix[-3];

            const int q0 = pix[0];

            const int q1 = pix[1];

            const int q2 = pix[2];

            if( FFABS( p0 - q0 ) < alpha &&

                FFABS( p1 - p0 ) < beta &&

                FFABS( q1 - q0 ) < beta ) {

                if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){

                    if( FFABS( p2 - p0 ) < beta)

                    {

                        const int p3 = pix[-4];

                        /* p0', p1', p2' */

                        pix[-1] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;

                        pix[-2] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;

                        pix[-3] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;

                    } else {

                        /* p0' */

                        pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;

                    }

                    if( FFABS( q2 - q0 ) < beta)

                    {

                        const int q3 = pix[3];

                        /* q0', q1', q2' */

                        pix[0] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;

                        pix[1] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;

                        pix[2] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;

                    } else {

                        /* q0' */

                        pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;

                    }

                }else{

                    /* p0', q0' */

                    pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;

                    pix[ 0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;

                }

                tprintf(h->s.avctx, "filter_mb_mbaff_edgev i:%d, qp:%d, indexA:%d, alpha:%d, beta:%d\n# bS:4 -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x, %02x, %02x]\n", i, qp[qp_index], index_a, alpha, beta, p2, p1, p0, q0, q1, q2, pix[-3], pix[-2], pix[-1], pix[0], pix[1], pix[2]);

            }

        }

    }

}


static void do_audio_out(AVFormatContext *s,

                         AVOutputStream *ost,

                         AVInputStream *ist,

                         unsigned char *buf, int size)

{

    uint8_t *buftmp;

    static uint8_t *audio_buf = NULL;

    static uint8_t *audio_out = NULL;

    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;

    int size_out, frame_bytes, ret;

    AVCodecContext *enc;

    /* SC: dynamic allocation of buffers */

    if (!audio_buf)

        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);

    if (!audio_out)

        audio_out = av_malloc(audio_out_size);

    if (!audio_buf || !audio_out)

        return;               /* Should signal an error ! */

    enc = &ost->st->codec;

    if (ost->audio_resample) {

        buftmp = audio_buf;

        size_out = audio_resample(ost->resample,

                                  (short *)buftmp, (short *)buf,

                                  size / (ist->st->codec.channels * 2));

        size_out = size_out * enc->channels * 2;

    } else {

        buftmp = buf;

        size_out = size;

    }

    /* now encode as many frames as possible */

    if (enc->frame_size > 1) {

        /* output resampled raw samples */

        fifo_write(&ost->fifo, buftmp, size_out,

                   &ost->fifo.wptr);

        frame_bytes = enc->frame_size * 2 * enc->channels;

        while (fifo_read(&ost->fifo, audio_buf, frame_bytes,

                     &ost->fifo.rptr) == 0) {

            AVPacket pkt;

            av_init_packet(&pkt);

            ret = avcodec_encode_audio(enc, audio_out, audio_out_size,

                                       (short *)audio_buf);

            audio_size += ret;

            pkt.stream_index= ost->index;

            pkt.data= audio_out;

            pkt.size= ret;

            if(enc->coded_frame)

                pkt.pts= enc->coded_frame->pts;

            pkt.flags |= PKT_FLAG_KEY;

            av_write_frame(s, &pkt);

        }

    } else {

        AVPacket pkt;

        av_init_packet(&pkt);

        /* output a pcm frame */

        /* XXX: change encoding codec API to avoid this ? */

        switch(enc->codec->id) {

        case CODEC_ID_PCM_S16LE:

        case CODEC_ID_PCM_S16BE:

        case CODEC_ID_PCM_U16LE:

        case CODEC_ID_PCM_U16BE:

            break;

        default:

            size_out = size_out >> 1;

            break;

        }

        ret = avcodec_encode_audio(enc, audio_out, size_out,

				   (short *)buftmp);

        audio_size += ret;

        pkt.stream_index= ost->index;

        pkt.data= audio_out;

        pkt.size= ret;

        if(enc->coded_frame)

            pkt.pts= enc->coded_frame->pts;

        pkt.flags |= PKT_FLAG_KEY;

        av_write_frame(s, &pkt);

    }

}


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

                          const AVFrame *frame, int *got_packet_ptr)

{

    LibopusEncContext *opus = avctx->priv_data;

    const int sample_size   = avctx->channels *

                              av_get_bytes_per_sample(avctx->sample_fmt);

    uint8_t *audio;

    int ret;

    int discard_padding;

    if (frame) {

        ret = ff_af_queue_add(&opus->afq, frame);

        if (ret < 0)

            return ret;

        if (frame->nb_samples < opus->opts.packet_size) {

            audio = opus->samples;

            memcpy(audio, frame->data[0], frame->nb_samples * sample_size);

        } else

            audio = frame->data[0];

    } else {

        if (!opus->afq.remaining_samples)

            return 0;

        audio = opus->samples;

        memset(audio, 0, opus->opts.packet_size * sample_size);

    }

    /* Maximum packet size taken from opusenc in opus-tools. 60ms packets

     * consist of 3 frames in one packet. The maximum frame size is 1275

     * bytes along with the largest possible packet header of 7 bytes. */

    if ((ret = ff_alloc_packet2(avctx, avpkt, (1275 * 3 + 7) * opus->stream_count, 0)) < 0)

        return ret;

    if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT)

        ret = opus_multistream_encode_float(opus->enc, (float *)audio,

                                            opus->opts.packet_size,

                                            avpkt->data, avpkt->size);

    else

        ret = opus_multistream_encode(opus->enc, (opus_int16 *)audio,

                                      opus->opts.packet_size,

                                      avpkt->data, avpkt->size);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR,

               "Error encoding frame: %s\n", opus_strerror(ret));

        return ff_opus_error_to_averror(ret);

    }

    av_shrink_packet(avpkt, ret);

    ff_af_queue_remove(&opus->afq, opus->opts.packet_size,

                       &avpkt->pts, &avpkt->duration);

    discard_padding = opus->opts.packet_size - avpkt->duration;

    // Check if subtraction resulted in an overflow

    if ((discard_padding < opus->opts.packet_size) != (avpkt->duration > 0)) {

        av_free_packet(avpkt);

        av_free(avpkt);

        return AVERROR(EINVAL);

    }

    if (discard_padding > 0) {

        uint8_t* side_data = av_packet_new_side_data(avpkt,

                                                     AV_PKT_DATA_SKIP_SAMPLES,

                                                     10);

        if(!side_data) {

            av_free_packet(avpkt);

            av_free(avpkt);

            return AVERROR(ENOMEM);

        }

        AV_WL32(side_data + 4, discard_padding);

    }

    *got_packet_ptr = 1;

    return 0;

}


static void vnc_connect(VncDisplay *vd, int csock, int skipauth, bool websocket)

{

    VncState *vs = g_malloc0(sizeof(VncState));

    int i;

    vs->csock = csock;

    if (skipauth) {

	vs->auth = VNC_AUTH_NONE;

#ifdef CONFIG_VNC_TLS

	vs->subauth = VNC_AUTH_INVALID;

#endif

    } else {

	vs->auth = vd->auth;

#ifdef CONFIG_VNC_TLS

	vs->subauth = vd->subauth;

#endif

    }

    vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));

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

        vs->lossy_rect[i] = g_malloc0(VNC_STAT_COLS * sizeof (uint8_t));

    }

    VNC_DEBUG("New client on socket %d\n", csock);

    dcl->idle = 0;

    socket_set_nonblock(vs->csock);

#ifdef CONFIG_VNC_WS

    if (websocket) {

        vs->websocket = 1;

        qemu_set_fd_handler2(vs->csock, NULL, vncws_handshake_read, NULL, vs);

    } else

#endif /* CONFIG_VNC_WS */

    {

        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);

    }

    vnc_client_cache_addr(vs);

    vnc_qmp_event(vs, QEVENT_VNC_CONNECTED);

    vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);

    vs->vd = vd;

#ifdef CONFIG_VNC_WS

    if (!vs->websocket)

#endif

    {

        vnc_init_state(vs);

    }

}


static void v9fs_open(void *opaque)

{

    int flags;

    int iounit;

    int32_t fid;

    int32_t mode;

    V9fsQID qid;

    ssize_t err = 0;

    size_t offset = 7;

    struct stat stbuf;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    if (s->proto_version == V9FS_PROTO_2000L) {

        pdu_unmarshal(pdu, offset, "dd", &fid, &mode);

    } else {

        pdu_unmarshal(pdu, offset, "db", &fid, &mode);

    }

    trace_v9fs_open(pdu->tag, pdu->id, fid, mode);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -ENOENT;

        goto out_nofid;

    }

    BUG_ON(fidp->fid_type != P9_FID_NONE);

    err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);

    if (err < 0) {

        goto out;

    }

    stat_to_qid(&stbuf, &qid);

    if (S_ISDIR(stbuf.st_mode)) {

        err = v9fs_co_opendir(pdu, fidp);

        if (err < 0) {

            goto out;

        }

        fidp->fid_type = P9_FID_DIR;

        offset += pdu_marshal(pdu, offset, "Qd", &qid, 0);

        err = offset;

    } else {

        if (s->proto_version == V9FS_PROTO_2000L) {

            flags = get_dotl_openflags(s, mode);

        } else {

            flags = omode_to_uflags(mode);

        }

        err = v9fs_co_open(pdu, fidp, flags);

        if (err < 0) {

            goto out;

        }

        fidp->fid_type = P9_FID_FILE;

        fidp->open_flags = flags;

        if (flags & O_EXCL) {

            /*

             * We let the host file system do O_EXCL check

             * We should not reclaim such fd

             */

            fidp->flags |= FID_NON_RECLAIMABLE;

        }

        iounit = get_iounit(pdu, &fidp->path);

        offset += pdu_marshal(pdu, offset, "Qd", &qid, iounit);

        err = offset;

    }

out:

    put_fid(pdu, fidp);

out_nofid:

    complete_pdu(s, pdu, err);

}


static void tcp_chr_disconnect(CharDriverState *chr)

{

    TCPCharDriver *s = chr->opaque;

    s->connected = 0;

    if (s->listen_chan) {

        s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,

                                       tcp_chr_accept, chr);

    }

    remove_fd_in_watch(chr);

    g_io_channel_unref(s->chan);

    s->chan = NULL;

    closesocket(s->fd);

    s->fd = -1;

    SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,

                         "disconnected:", s->addr, s->is_listen, s->is_telnet);

    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);

    if (s->reconnect_time) {

        qemu_chr_socket_restart_timer(chr);

    }

}


float64 HELPER(ucf64_si2df)(float32 x, CPUUniCore32State *env)

{

    return int32_to_float64(ucf64_stoi(x), &env->ucf64.fp_status);

}


static QObject *parse_literal(JSONParserContext *ctxt)

{

    QObject *token;

    token = parser_context_pop_token(ctxt);

    assert(token);

    switch (token_get_type(token)) {

    case JSON_STRING:

        return QOBJECT(qstring_from_escaped_str(ctxt, token));

    case JSON_INTEGER: {

        /* A possibility exists that this is a whole-valued float where the

         * fractional part was left out due to being 0 (.0). It's not a big

         * deal to treat these as ints in the parser, so long as users of the

         * resulting QObject know to expect a QInt in place of a QFloat in

         * cases like these.

         *

         * However, in some cases these values will overflow/underflow a

         * QInt/int64 container, thus we should assume these are to be handled

         * as QFloats/doubles rather than silently changing their values.

         *

         * strtoll() indicates these instances by setting errno to ERANGE

         */

        int64_t value;

        errno = 0; /* strtoll doesn't set errno on success */

        value = strtoll(token_get_value(token), NULL, 10);

        if (errno != ERANGE) {

            return QOBJECT(qint_from_int(value));

        }

        /* fall through to JSON_FLOAT */

    }

    case JSON_FLOAT:

        /* FIXME dependent on locale */

        return QOBJECT(qfloat_from_double(strtod(token_get_value(token),

                                                 NULL)));

    default:

        abort();

    }

}


uint64_t esp_reg_read(ESPState *s, uint32_t saddr)

{

    uint32_t old_val;

    trace_esp_mem_readb(saddr, s->rregs[saddr]);

    switch (saddr) {

    case ESP_FIFO:

        if (s->ti_size > 0) {

            s->ti_size--;

            if ((s->rregs[ESP_RSTAT] & STAT_PIO_MASK) == 0) {

                /* Data out.  */

                qemu_log_mask(LOG_UNIMP,

                              "esp: PIO data read not implemented\n");

                s->rregs[ESP_FIFO] = 0;

            } else {

                s->rregs[ESP_FIFO] = s->ti_buf[s->ti_rptr++];

            }

            esp_raise_irq(s);

        }

        if (s->ti_size == 0) {

            s->ti_rptr = 0;

            s->ti_wptr = 0;

        }

        break;

    case ESP_RINTR:

        /* Clear sequence step, interrupt register and all status bits

           except TC */

        old_val = s->rregs[ESP_RINTR];

        s->rregs[ESP_RINTR] = 0;

        s->rregs[ESP_RSTAT] &= ~STAT_TC;

        s->rregs[ESP_RSEQ] = SEQ_CD;

        esp_lower_irq(s);

        return old_val;

    case ESP_TCHI:

        /* Return the unique id if the value has never been written */

        if (!s->tchi_written) {

            return s->chip_id;

        }

    default:

        break;

    }

    return s->rregs[saddr];

}


static void co_test_cb(void *opaque)

{

    WorkerTestData *data = opaque;

    active = 1;

    data->n = 0;

    data->ret = -EINPROGRESS;

    thread_pool_submit_co(worker_cb, data);

    /* The test continues in test_submit_co, after qemu_coroutine_enter... */

    g_assert_cmpint(data->n, ==, 1);

    data->ret = 0;

    active--;

    /* The test continues in test_submit_co, after qemu_aio_wait_all... */

}


print_insn_microblaze (bfd_vma memaddr, struct disassemble_info * info)

{

  fprintf_ftype       fprintf = info->fprintf_func;

  void *              stream = info->stream;

  unsigned long       inst, prev_inst;

  struct op_code_struct * op, *pop;

  int                 immval = 0;

  bfd_boolean         immfound = FALSE;

  static bfd_vma prev_insn_addr = -1; /*init the prev insn addr */

  static int     prev_insn_vma = -1;  /*init the prev insn vma */

  int            curr_insn_vma = info->buffer_vma;

  info->bytes_per_chunk = 4;

  inst = read_insn_microblaze (memaddr, info, &op);

  if (inst == 0) {

    return -1;

  }

  if (prev_insn_vma == curr_insn_vma) {

  if (memaddr-(info->bytes_per_chunk) == prev_insn_addr) {

    prev_inst = read_insn_microblaze (prev_insn_addr, info, &pop);

    if (prev_inst == 0)

      return -1;

    if (pop->instr == imm) {

      immval = (get_int_field_imm(prev_inst) << 16) & 0xffff0000;

      immfound = TRUE;

    }

    else {

      immval = 0;

      immfound = FALSE;

    }

  }

  }

  /* make curr insn as prev insn */

  prev_insn_addr = memaddr;

  prev_insn_vma = curr_insn_vma;

  if (op->name == 0) {

    fprintf (stream, ".short 0x%04lx", inst);

  }

  else

    {

      fprintf (stream, "%s", op->name);

      switch (op->inst_type)

	{

  case INST_TYPE_RD_R1_R2:

     fprintf(stream, "\t%s, %s, %s", get_field_rd(inst), get_field_r1(inst), get_field_r2(inst));

     break;

        case INST_TYPE_RD_R1_IMM:

	  fprintf(stream, "\t%s, %s, %s", get_field_rd(inst), get_field_r1(inst), get_field_imm(inst));

	  if (info->print_address_func && get_int_field_r1(inst) == 0 && info->symbol_at_address_func) {

	    if (immfound)

	      immval |= (get_int_field_imm(inst) & 0x0000ffff);

	    else {

	      immval = get_int_field_imm(inst);

	      if (immval & 0x8000)

		immval |= 0xFFFF0000;

	    }

	    if (immval > 0 && info->symbol_at_address_func(immval, info)) {

	      fprintf (stream, "\t// ");

	      info->print_address_func (immval, info);

	    }

	  }

	  break;

	case INST_TYPE_RD_R1_IMM5:

	  fprintf(stream, "\t%s, %s, %s", get_field_rd(inst), get_field_r1(inst), get_field_imm5(inst));

	  break;

	case INST_TYPE_RD_RFSL:

	  fprintf(stream, "\t%s, %s", get_field_rd(inst), get_field_rfsl(inst));

	  break;

	case INST_TYPE_R1_RFSL:

	  fprintf(stream, "\t%s, %s", get_field_r1(inst), get_field_rfsl(inst));

	  break;

	case INST_TYPE_RD_SPECIAL:

	  fprintf(stream, "\t%s, %s", get_field_rd(inst), get_field_special(inst, op));

	  break;

	case INST_TYPE_SPECIAL_R1:

	  fprintf(stream, "\t%s, %s", get_field_special(inst, op), get_field_r1(inst));

	  break;

	case INST_TYPE_RD_R1:

	  fprintf(stream, "\t%s, %s", get_field_rd(inst), get_field_r1(inst));

	  break;

	case INST_TYPE_R1_R2:

	  fprintf(stream, "\t%s, %s", get_field_r1(inst), get_field_r2(inst));

	  break;

	case INST_TYPE_R1_IMM:

	  fprintf(stream, "\t%s, %s", get_field_r1(inst), get_field_imm(inst));

	  /* The non-pc relative instructions are returns, which shouldn't

	     have a label printed */

	  if (info->print_address_func && op->inst_offset_type == INST_PC_OFFSET && info->symbol_at_address_func) {

	    if (immfound)

	      immval |= (get_int_field_imm(inst) & 0x0000ffff);

	    else {

	      immval = get_int_field_imm(inst);

	      if (immval & 0x8000)

		immval |= 0xFFFF0000;

	    }

	    immval += memaddr;

	    if (immval > 0 && info->symbol_at_address_func(immval, info)) {

	      fprintf (stream, "\t// ");

	      info->print_address_func (immval, info);

	    } else {

	      fprintf (stream, "\t\t// ");

	      fprintf (stream, "%x", immval);

	    }

	  }

	  break;

        case INST_TYPE_RD_IMM:

	  fprintf(stream, "\t%s, %s", get_field_rd(inst), get_field_imm(inst));

	  if (info->print_address_func && info->symbol_at_address_func) {

	    if (immfound)

	      immval |= (get_int_field_imm(inst) & 0x0000ffff);

	    else {

	      immval = get_int_field_imm(inst);

	      if (immval & 0x8000)

		immval |= 0xFFFF0000;

	    }

	    if (op->inst_offset_type == INST_PC_OFFSET)

	      immval += (int) memaddr;

	    if (info->symbol_at_address_func(immval, info)) {

	      fprintf (stream, "\t// ");

	      info->print_address_func (immval, info);

	    }

	  }

	  break;

        case INST_TYPE_IMM:

	  fprintf(stream, "\t%s", get_field_imm(inst));

	  if (info->print_address_func && info->symbol_at_address_func && op->instr != imm) {

	    if (immfound)

	      immval |= (get_int_field_imm(inst) & 0x0000ffff);

	    else {

	      immval = get_int_field_imm(inst);

	      if (immval & 0x8000)

		immval |= 0xFFFF0000;

	    }

	    if (op->inst_offset_type == INST_PC_OFFSET)

	      immval += (int) memaddr;

	    if (immval > 0 && info->symbol_at_address_func(immval, info)) {

	      fprintf (stream, "\t// ");

	      info->print_address_func (immval, info);

	    } else if (op->inst_offset_type == INST_PC_OFFSET) {

	      fprintf (stream, "\t\t// ");

	      fprintf (stream, "%x", immval);

	    }

	  }

	  break;

        case INST_TYPE_RD_R2:

	  fprintf(stream, "\t%s, %s", get_field_rd(inst), get_field_r2(inst));

	  break;

  case INST_TYPE_R2:

     fprintf(stream, "\t%s", get_field_r2(inst));

     break;

  case INST_TYPE_R1:

     fprintf(stream, "\t%s", get_field_r1(inst));

     break;

  case INST_TYPE_RD_R1_SPECIAL:

     fprintf(stream, "\t%s, %s", get_field_rd(inst), get_field_r2(inst));

     break;

  case INST_TYPE_RD_IMM15:

     fprintf(stream, "\t%s, %s", get_field_rd(inst), get_field_imm15(inst));

     break;

     /* For tuqula instruction */

  case INST_TYPE_RD:

     fprintf(stream, "\t%s", get_field_rd(inst));

     break;

  case INST_TYPE_RFSL:

     fprintf(stream, "\t%s", get_field_rfsl(inst));

     break;

  default:

	  /* if the disassembler lags the instruction set */

	  fprintf (stream, "\tundecoded operands, inst is 0x%04lx", inst);

	  break;

	}

    }

  /* Say how many bytes we consumed? */

  return 4;

}


int nbd_client_session_co_flush(NbdClientSession *client)

{

    struct nbd_request request = { .type = NBD_CMD_FLUSH };

    struct nbd_reply reply;

    ssize_t ret;

    if (!(client->nbdflags & NBD_FLAG_SEND_FLUSH)) {

        return 0;

    }

    if (client->nbdflags & NBD_FLAG_SEND_FUA) {

        request.type |= NBD_CMD_FLAG_FUA;

    }

    request.from = 0;

    request.len = 0;

    nbd_coroutine_start(client, &request);

    ret = nbd_co_send_request(client, &request, NULL, 0);

    if (ret < 0) {

        reply.error = -ret;

    } else {

        nbd_co_receive_reply(client, &request, &reply, NULL, 0);

    }

    nbd_coroutine_end(client, &request);

    return -reply.error;

}


static void i440fx_pcihost_initfn(Object *obj)

{

    PCIHostState *s = PCI_HOST_BRIDGE(obj);

    I440FXState *d = I440FX_PCI_HOST_BRIDGE(obj);

    memory_region_init_io(&s->conf_mem, obj, &pci_host_conf_le_ops, s,

                          "pci-conf-idx", 4);

    memory_region_init_io(&s->data_mem, obj, &pci_host_data_le_ops, s,

                          "pci-conf-data", 4);

    object_property_add(obj, PCI_HOST_PROP_PCI_HOLE_START, "int",

                        i440fx_pcihost_get_pci_hole_start,

                        NULL, NULL, NULL, NULL);

    object_property_add(obj, PCI_HOST_PROP_PCI_HOLE_END, "int",

                        i440fx_pcihost_get_pci_hole_end,

                        NULL, NULL, NULL, NULL);

    object_property_add(obj, PCI_HOST_PROP_PCI_HOLE64_START, "int",

                        i440fx_pcihost_get_pci_hole64_start,

                        NULL, NULL, NULL, NULL);

    object_property_add(obj, PCI_HOST_PROP_PCI_HOLE64_END, "int",

                        i440fx_pcihost_get_pci_hole64_end,

                        NULL, NULL, NULL, NULL);

    d->pci_info.w32.end = IO_APIC_DEFAULT_ADDRESS;

}


int avio_open2(AVIOContext **s, const char *filename, int flags,

               const AVIOInterruptCB *int_cb, AVDictionary **options)

{

    AVIOInternal *internal;

    const URLProtocol **protocols;

    URLContext *h;

    int err;

    protocols = ffurl_get_protocols(NULL, NULL);

    if (!protocols)

        return AVERROR(ENOMEM);

    err = ffurl_open(&h, filename, flags, int_cb, options, protocols);

    if (err < 0) {

        av_freep(&protocols);

        return err;

    }

    err = ffio_fdopen(s, h);

    if (err < 0) {

        ffurl_close(h);

        av_freep(&protocols);

        return err;

    }

    internal = (*s)->opaque;

    internal->protocols = protocols;

    return 0;

}


static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)

{

    MpegEncContext *s = &ctx->m;

    int time_incr, time_increment;

    int64_t pts;

    s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I;        /* pict type: I = 0 , P = 1 */

    if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay &&

        s->vol_control_parameters == 0 && !(s->flags & CODEC_FLAG_LOW_DELAY)) {

        av_log(s->avctx, AV_LOG_ERROR, "low_delay flag incorrectly, clearing it\n");

        s->low_delay = 0;

    }

    s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;

    if (s->partitioned_frame)

        s->decode_mb = mpeg4_decode_partitioned_mb;

    else

        s->decode_mb = mpeg4_decode_mb;

    time_incr = 0;

    while (get_bits1(gb) != 0)

        time_incr++;

    check_marker(gb, "before time_increment");

    if (ctx->time_increment_bits == 0 ||

        !(show_bits(gb, ctx->time_increment_bits + 1) & 1)) {

        av_log(s->avctx, AV_LOG_ERROR,

               "hmm, seems the headers are not complete, trying to guess time_increment_bits\n");

        for (ctx->time_increment_bits = 1;

             ctx->time_increment_bits < 16;

             ctx->time_increment_bits++) {

            if (s->pict_type == AV_PICTURE_TYPE_P ||

                (s->pict_type == AV_PICTURE_TYPE_S &&

                 ctx->vol_sprite_usage == GMC_SPRITE)) {

                if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30)

                    break;

            } else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18)

                break;

        }

        av_log(s->avctx, AV_LOG_ERROR,

               "my guess is %d bits ;)\n", ctx->time_increment_bits);

        if (s->avctx->time_base.den && 4*s->avctx->time_base.den < 1<<ctx->time_increment_bits) {

            s->avctx->time_base.den = 1<<ctx->time_increment_bits;

        }

    }

    if (IS_3IV1)

        time_increment = get_bits1(gb);        // FIXME investigate further

    else

        time_increment = get_bits(gb, ctx->time_increment_bits);

    if (s->pict_type != AV_PICTURE_TYPE_B) {

        s->last_time_base = s->time_base;

        s->time_base     += time_incr;

        s->time = s->time_base * s->avctx->time_base.den + time_increment;

        if (s->workaround_bugs & FF_BUG_UMP4) {

            if (s->time < s->last_non_b_time) {

                /* header is not mpeg-4-compatible, broken encoder,

                 * trying to workaround */

                s->time_base++;

                s->time += s->avctx->time_base.den;

            }

        }

        s->pp_time         = s->time - s->last_non_b_time;

        s->last_non_b_time = s->time;

    } else {

        s->time    = (s->last_time_base + time_incr) * s->avctx->time_base.den + time_increment;

        s->pb_time = s->pp_time - (s->last_non_b_time - s->time);

        if (s->pp_time <= s->pb_time ||

            s->pp_time <= s->pp_time - s->pb_time ||

            s->pp_time <= 0) {

            /* messed up order, maybe after seeking? skipping current b-frame */

            return FRAME_SKIPPED;

        }

        ff_mpeg4_init_direct_mv(s);

        if (ctx->t_frame == 0)

            ctx->t_frame = s->pb_time;

        if (ctx->t_frame == 0)

            ctx->t_frame = 1;  // 1/0 protection

        s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) -

                            ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;

        s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) -

                            ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;

        if (!s->progressive_sequence) {

            if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1)

                return FRAME_SKIPPED;

        }

    }

    if (s->avctx->time_base.num)

        pts = ROUNDED_DIV(s->time, s->avctx->time_base.num);

    else

        pts = AV_NOPTS_VALUE;

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

        av_log(s->avctx, AV_LOG_DEBUG, "MPEG4 PTS: %"PRId64"\n",

               pts);

    check_marker(gb, "before vop_coded");

    /* vop coded */

    if (get_bits1(gb) != 1) {

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

            av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");

        return FRAME_SKIPPED;

    }

    if (ctx->new_pred)

        decode_new_pred(ctx, gb);

    if (ctx->shape != BIN_ONLY_SHAPE &&

                    (s->pict_type == AV_PICTURE_TYPE_P ||

                     (s->pict_type == AV_PICTURE_TYPE_S &&

                      ctx->vol_sprite_usage == GMC_SPRITE))) {

        /* rounding type for motion estimation */

        s->no_rounding = get_bits1(gb);

    } else {

        s->no_rounding = 0;

    }

    // FIXME reduced res stuff

    if (ctx->shape != RECT_SHAPE) {

        if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) {

            skip_bits(gb, 13);  /* width */

            skip_bits1(gb);     /* marker */

            skip_bits(gb, 13);  /* height */

            skip_bits1(gb);     /* marker */

            skip_bits(gb, 13);  /* hor_spat_ref */

            skip_bits1(gb);     /* marker */

            skip_bits(gb, 13);  /* ver_spat_ref */

        }

        skip_bits1(gb);         /* change_CR_disable */

        if (get_bits1(gb) != 0)

            skip_bits(gb, 8);   /* constant_alpha_value */

    }

    // FIXME complexity estimation stuff

    if (ctx->shape != BIN_ONLY_SHAPE) {

        skip_bits_long(gb, ctx->cplx_estimation_trash_i);

        if (s->pict_type != AV_PICTURE_TYPE_I)

            skip_bits_long(gb, ctx->cplx_estimation_trash_p);

        if (s->pict_type == AV_PICTURE_TYPE_B)

            skip_bits_long(gb, ctx->cplx_estimation_trash_b);

        if (get_bits_left(gb) < 3) {

            av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n");

            return -1;

        }

        ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)];

        if (!s->progressive_sequence) {

            s->top_field_first = get_bits1(gb);

            s->alternate_scan  = get_bits1(gb);

        } else

            s->alternate_scan = 0;

    }

    if (s->alternate_scan) {

        ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable,   ff_alternate_vertical_scan);

        ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable,   ff_alternate_vertical_scan);

        ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);

        ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);

    } else {

        ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable,   ff_zigzag_direct);

        ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable,   ff_zigzag_direct);

        ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);

        ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);

    }

    if (s->pict_type == AV_PICTURE_TYPE_S &&

        (ctx->vol_sprite_usage == STATIC_SPRITE ||

         ctx->vol_sprite_usage == GMC_SPRITE)) {

        if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0)

            return AVERROR_INVALIDDATA;

        if (ctx->sprite_brightness_change)

            av_log(s->avctx, AV_LOG_ERROR,

                   "sprite_brightness_change not supported\n");

        if (ctx->vol_sprite_usage == STATIC_SPRITE)

            av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");

    }

    if (ctx->shape != BIN_ONLY_SHAPE) {

        s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision);

        if (s->qscale == 0) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Error, header damaged or not MPEG4 header (qscale=0)\n");

            return -1;  // makes no sense to continue, as there is nothing left from the image then

        }

        if (s->pict_type != AV_PICTURE_TYPE_I) {

            s->f_code = get_bits(gb, 3);        /* fcode_for */

            if (s->f_code == 0) {

                av_log(s->avctx, AV_LOG_ERROR,

                       "Error, header damaged or not MPEG4 header (f_code=0)\n");

                s->f_code = 1;

                return -1;  // makes no sense to continue, as there is nothing left from the image then

            }

        } else

            s->f_code = 1;

        if (s->pict_type == AV_PICTURE_TYPE_B) {

            s->b_code = get_bits(gb, 3);

            if (s->b_code == 0) {

                av_log(s->avctx, AV_LOG_ERROR,

                       "Error, header damaged or not MPEG4 header (b_code=0)\n");

                s->b_code=1;

                return -1; // makes no sense to continue, as the MV decoding will break very quickly

            }

        } else

            s->b_code = 1;

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

            av_log(s->avctx, AV_LOG_DEBUG,

                   "qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d time:%"PRId64" tincr:%d\n",

                   s->qscale, s->f_code, s->b_code,

                   s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")),

                   gb->size_in_bits,s->progressive_sequence, s->alternate_scan,

                   s->top_field_first, s->quarter_sample ? "q" : "h",

                   s->data_partitioning, ctx->resync_marker,

                   ctx->num_sprite_warping_points, s->sprite_warping_accuracy,

                   1 - s->no_rounding, s->vo_type,

                   s->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold,

                   ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p,

                   ctx->cplx_estimation_trash_b,

                   s->time,

                   time_increment

                  );

        }

        if (!ctx->scalability) {

            if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I)

                skip_bits1(gb);  // vop shape coding type

        } else {

            if (ctx->enhancement_type) {

                int load_backward_shape = get_bits1(gb);

                if (load_backward_shape)

                    av_log(s->avctx, AV_LOG_ERROR,

                           "load backward shape isn't supported\n");

            }

            skip_bits(gb, 2);  // ref_select_code

        }

    }

    /* detect buggy encoders which don't set the low_delay flag

     * (divx4/xvid/opendivx). Note we cannot detect divx5 without b-frames

     * easily (although it's buggy too) */

    if (s->vo_type == 0 && s->vol_control_parameters == 0 &&

        ctx->divx_version == -1 && s->picture_number == 0) {

        av_log(s->avctx, AV_LOG_WARNING,

               "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");

        s->low_delay = 1;

    }

    s->picture_number++;  // better than pic number==0 always ;)

    // FIXME add short header support

    s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table;

    s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table;

    if (s->workaround_bugs & FF_BUG_EDGE) {

        s->h_edge_pos = s->width;

        s->v_edge_pos = s->height;

    }

    return 0;

}


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

{

    static int index;

    ISADevice *isadev = ISA_DEVICE(dev);

    ISAParallelState *isa = ISA_PARALLEL(dev);

    ParallelState *s = &isa->state;

    int base;

    uint8_t dummy;

    if (!s->chr) {

        error_setg(errp, "Can't create parallel device, empty char device");

        return;

    }

    if (isa->index == -1) {

        isa->index = index;

    }

    if (isa->index >= MAX_PARALLEL_PORTS) {

        error_setg(errp, "Max. supported number of parallel ports is %d.",

                   MAX_PARALLEL_PORTS);

        return;

    }

    if (isa->iobase == -1) {

        isa->iobase = isa_parallel_io[isa->index];

    }

    index++;

    base = isa->iobase;

    isa_init_irq(isadev, &s->irq, isa->isairq);

    qemu_register_reset(parallel_reset, s);

    if (qemu_chr_fe_ioctl(s->chr, CHR_IOCTL_PP_READ_STATUS, &dummy) == 0) {

        s->hw_driver = 1;

        s->status = dummy;

    }

    isa_register_portio_list(isadev, base,

                             (s->hw_driver

                              ? &isa_parallel_portio_hw_list[0]

                              : &isa_parallel_portio_sw_list[0]),

                             s, "parallel");

}


static void test_bmdma_long_prdt(void)

{

    QPCIDevice *dev;

    QPCIBar bmdma_bar, ide_bar;

    uint8_t status;

    PrdtEntry prdt[] = {

        {

            .addr = 0,

            .size = cpu_to_le32(0x1000 | PRDT_EOT),

        },

    };

    dev = get_pci_device(&bmdma_bar, &ide_bar);

    /* Normal request */

    status = send_dma_request(CMD_READ_DMA, 0, 1,

                              prdt, ARRAY_SIZE(prdt), NULL);

    g_assert_cmphex(status, ==, BM_STS_ACTIVE | BM_STS_INTR);

    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);

    /* Abort the request before it completes */

    status = send_dma_request(CMD_READ_DMA | CMDF_ABORT, 0, 1,

                              prdt, ARRAY_SIZE(prdt), NULL);

    g_assert_cmphex(status, ==, BM_STS_INTR);

    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);

}


static void memory_region_update_coalesced_range(MemoryRegion *mr)

{

    FlatRange *fr;

    CoalescedMemoryRange *cmr;

    AddrRange tmp;

    FOR_EACH_FLAT_RANGE(fr, &address_space_memory.current_map) {

        if (fr->mr == mr) {

            qemu_unregister_coalesced_mmio(int128_get64(fr->addr.start),

                                           int128_get64(fr->addr.size));

            QTAILQ_FOREACH(cmr, &mr->coalesced, link) {

                tmp = addrrange_shift(cmr->addr,

                                      int128_sub(fr->addr.start,

                                                 int128_make64(fr->offset_in_region)));

                if (!addrrange_intersects(tmp, fr->addr)) {

                    continue;

                }

                tmp = addrrange_intersection(tmp, fr->addr);

                qemu_register_coalesced_mmio(int128_get64(tmp.start),

                                             int128_get64(tmp.size));

            }

        }

    }

}


static int qxl_init_secondary(PCIDevice *dev)

{

    static int device_id = 1;

    PCIQXLDevice *qxl = DO_UPCAST(PCIQXLDevice, pci, dev);

    qxl->id = device_id++;

    qxl_init_ramsize(qxl, 16);

    memory_region_init_ram(&qxl->vga.vram, "qxl.vgavram", qxl->vga.vram_size);

    vmstate_register_ram(&qxl->vga.vram, &qxl->pci.qdev);

    qxl->vga.vram_ptr = memory_region_get_ram_ptr(&qxl->vga.vram);

    return qxl_init_common(qxl);

}


static void tcg_out_qemu_st_slow_path(TCGContext *s, TCGLabelQemuLdst *l)

{

    TCGMemOp opc = l->opc;

    TCGMemOp s_bits = opc & MO_SIZE;

    uint8_t **label_ptr = &l->label_ptr[0];

    TCGReg retaddr;

    /* resolve label address */

    *(uint32_t *)label_ptr[0] = (uint32_t)(s->code_ptr - label_ptr[0] - 4);

    if (TARGET_LONG_BITS > TCG_TARGET_REG_BITS) {

        *(uint32_t *)label_ptr[1] = (uint32_t)(s->code_ptr - label_ptr[1] - 4);

    }

    if (TCG_TARGET_REG_BITS == 32) {

        int ofs = 0;

        tcg_out_st(s, TCG_TYPE_PTR, TCG_AREG0, TCG_REG_ESP, ofs);

        ofs += 4;

        tcg_out_st(s, TCG_TYPE_I32, l->addrlo_reg, TCG_REG_ESP, ofs);

        ofs += 4;

        if (TARGET_LONG_BITS == 64) {

            tcg_out_st(s, TCG_TYPE_I32, l->addrhi_reg, TCG_REG_ESP, ofs);

            ofs += 4;

        }

        tcg_out_st(s, TCG_TYPE_I32, l->datalo_reg, TCG_REG_ESP, ofs);

        ofs += 4;

        if (s_bits == MO_64) {

            tcg_out_st(s, TCG_TYPE_I32, l->datahi_reg, TCG_REG_ESP, ofs);

            ofs += 4;

        }

        tcg_out_sti(s, TCG_TYPE_I32, TCG_REG_ESP, ofs, l->mem_index);

        ofs += 4;

        retaddr = TCG_REG_EAX;

        tcg_out_movi(s, TCG_TYPE_I32, retaddr, (uintptr_t)l->raddr);

        tcg_out_st(s, TCG_TYPE_I32, retaddr, TCG_REG_ESP, ofs);

    } else {

        tcg_out_mov(s, TCG_TYPE_PTR, tcg_target_call_iarg_regs[0], TCG_AREG0);

        /* The second argument is already loaded with addrlo.  */

        tcg_out_mov(s, (s_bits == MO_64 ? TCG_TYPE_I64 : TCG_TYPE_I32),

                    tcg_target_call_iarg_regs[2], l->datalo_reg);

        tcg_out_movi(s, TCG_TYPE_I32, tcg_target_call_iarg_regs[3],

                     l->mem_index);

        if (ARRAY_SIZE(tcg_target_call_iarg_regs) > 4) {

            retaddr = tcg_target_call_iarg_regs[4];

            tcg_out_movi(s, TCG_TYPE_PTR, retaddr, (uintptr_t)l->raddr);

        } else {

            retaddr = TCG_REG_RAX;

            tcg_out_movi(s, TCG_TYPE_PTR, retaddr, (uintptr_t)l->raddr);

            tcg_out_st(s, TCG_TYPE_PTR, retaddr, TCG_REG_ESP, 0);

        }

    }

    /* "Tail call" to the helper, with the return address back inline.  */

    tcg_out_push(s, retaddr);

    tcg_out_jmp(s, (uintptr_t)qemu_st_helpers[opc]);

}


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

                               const AVFrame *frame, int *got_packet_ptr)

{

    vorbis_enc_context *venc = avctx->priv_data;

    int i, ret, need_more;

    int samples = 0, frame_size = 1 << (venc->log2_blocksize[1] - 1);

    vorbis_enc_mode *mode;

    vorbis_enc_mapping *mapping;

    PutBitContext pb;

    if (frame) {

        if ((ret = ff_af_queue_add(&venc->afq, frame)) < 0)

            return ret;

        ff_bufqueue_add(avctx, &venc->bufqueue, av_frame_clone(frame));

    } else

        if (!venc->afq.remaining_samples)

            return 0;

    need_more = venc->bufqueue.available * avctx->frame_size < frame_size;

    need_more = frame && need_more;

    if (need_more)

        return 0;

    /* Pad the bufqueue with empty frames for encoding the last packet. */

    if (!frame) {

        if (venc->bufqueue.available * avctx->frame_size < frame_size) {

            int frames_needed = (frame_size/avctx->frame_size) - venc->bufqueue.available;

            for (int i = 0; i < frames_needed; i++) {

               AVFrame *empty = spawn_empty_frame(avctx, venc->channels);

               if (!empty)

                   return AVERROR(ENOMEM);

               ff_bufqueue_add(avctx, &venc->bufqueue, empty);

            }

        }

    }

    move_audio(venc, venc->scratch, &samples, avctx->frame_size);

    if (!apply_window_and_mdct(venc, venc->scratch, samples))

        return 0;

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

        return ret;

    init_put_bits(&pb, avpkt->data, avpkt->size);

    if (pb.size_in_bits - put_bits_count(&pb) < 1 + ilog(venc->nmodes - 1)) {

        av_log(avctx, AV_LOG_ERROR, "output buffer is too small\n");

        return AVERROR(EINVAL);

    }

    put_bits(&pb, 1, 0); // magic bit

    put_bits(&pb, ilog(venc->nmodes - 1), 0); // 0 bits, the mode

    mode    = &venc->modes[0];

    mapping = &venc->mappings[mode->mapping];

    if (mode->blockflag) {

        put_bits(&pb, 1, 0);

        put_bits(&pb, 1, 0);

    }

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

        vorbis_enc_floor *fc = &venc->floors[mapping->floor[mapping->mux[i]]];

        uint16_t posts[MAX_FLOOR_VALUES];

        floor_fit(venc, fc, &venc->coeffs[i * samples], posts, samples);

        if (floor_encode(venc, fc, &pb, posts, &venc->floor[i * samples], samples)) {

            av_log(avctx, AV_LOG_ERROR, "output buffer is too small\n");

            return AVERROR(EINVAL);

        }

    }

    for (i = 0; i < venc->channels * samples; i++)

        venc->coeffs[i] /= venc->floor[i];

    for (i = 0; i < mapping->coupling_steps; i++) {

        float *mag = venc->coeffs + mapping->magnitude[i] * samples;

        float *ang = venc->coeffs + mapping->angle[i]     * samples;

        int j;

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

            float a = ang[j];

            ang[j] -= mag[j];

            if (mag[j] > 0)

                ang[j] = -ang[j];

            if (ang[j] < 0)

                mag[j] = a;

        }

    }

    if (residue_encode(venc, &venc->residues[mapping->residue[mapping->mux[0]]],

                       &pb, venc->coeffs, samples, venc->channels)) {

        av_log(avctx, AV_LOG_ERROR, "output buffer is too small\n");

        return AVERROR(EINVAL);

    }

    flush_put_bits(&pb);

    avpkt->size = put_bits_count(&pb) >> 3;

    ff_af_queue_remove(&venc->afq, frame_size, &avpkt->pts, &avpkt->duration);

    if (frame_size > avpkt->duration) {

        uint8_t *side = av_packet_new_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, 10);

        if (!side)

            return AVERROR(ENOMEM);

        AV_WL32(&side[4], frame_size - avpkt->duration);

    }

    *got_packet_ptr = 1;

    return 0;

}


static void gd_set_keycode_type(GtkDisplayState *s)
{
#ifdef GDK_WINDOWING_X11
    GdkDisplay *display = gtk_widget_get_display(s->window);
    if (GDK_IS_X11_DISPLAY(display)) {
        Display *x11_display = gdk_x11_display_get_xdisplay(display);
        XkbDescPtr desc = XkbGetKeyboard(x11_display, XkbGBN_AllComponentsMask,
                                         XkbUseCoreKbd);
        char *keycodes = NULL;
        if (desc && desc->names) {
            keycodes = XGetAtomName(x11_display, desc->names->keycodes);
        if (keycodes == NULL) {
            fprintf(stderr, "could not lookup keycode name\n");
        } else if (strstart(keycodes, "evdev", NULL)) {
            s->has_evdev = true;
        } else if (!strstart(keycodes, "xfree86", NULL)) {
            fprintf(stderr, "unknown keycodes `%s', please report to "
                    "qemu-devel@nongnu.org\n", keycodes);
#endif


static void kvm_client_set_memory(struct CPUPhysMemoryClient *client,

				  target_phys_addr_t start_addr,

				  ram_addr_t size,

				  ram_addr_t phys_offset)

{

	kvm_set_phys_mem(start_addr, size, phys_offset);

}


int coroutine_fn bdrv_co_pdiscard(BlockDriverState *bs, int64_t offset,

                                  int count)

{

    BdrvTrackedRequest req;

    int max_pdiscard, ret;

    int head, align;

    if (!bs->drv) {

        return -ENOMEDIUM;

    }

    ret = bdrv_check_byte_request(bs, offset, count);

    if (ret < 0) {

        return ret;

    } else if (bs->read_only) {

        return -EPERM;

    }

    assert(!(bs->open_flags & BDRV_O_INACTIVE));

    /* Do nothing if disabled.  */

    if (!(bs->open_flags & BDRV_O_UNMAP)) {

        return 0;

    }

    if (!bs->drv->bdrv_co_pdiscard && !bs->drv->bdrv_aio_pdiscard) {

        return 0;

    }

    /* Discard is advisory, so ignore any unaligned head or tail */

    align = MAX(bs->bl.pdiscard_alignment, bs->bl.request_alignment);

    assert(align % bs->bl.request_alignment == 0);

    head = offset % align;

    if (head) {

        head = MIN(count, align - head);

        count -= head;

        offset += head;

    }

    count = QEMU_ALIGN_DOWN(count, align);

    if (!count) {

        return 0;

    }

    bdrv_inc_in_flight(bs);

    tracked_request_begin(&req, bs, offset, count, BDRV_TRACKED_DISCARD);

    ret = notifier_with_return_list_notify(&bs->before_write_notifiers, &req);

    if (ret < 0) {

        goto out;

    }

    max_pdiscard = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_pdiscard, INT_MAX),

                                   align);

    assert(max_pdiscard);

    while (count > 0) {

        int ret;

        int num = MIN(count, max_pdiscard);

        if (bs->drv->bdrv_co_pdiscard) {

            ret = bs->drv->bdrv_co_pdiscard(bs, offset, num);

        } else {

            BlockAIOCB *acb;

            CoroutineIOCompletion co = {

                .coroutine = qemu_coroutine_self(),

            };

            acb = bs->drv->bdrv_aio_pdiscard(bs, offset, num,

                                             bdrv_co_io_em_complete, &co);

            if (acb == NULL) {

                ret = -EIO;

                goto out;

            } else {

                qemu_coroutine_yield();

                ret = co.ret;

            }

        }

        if (ret && ret != -ENOTSUP) {

            goto out;

        }

        offset += num;

        count -= num;

    }

    ret = 0;

out:

    ++bs->write_gen;

    bdrv_set_dirty(bs, req.offset >> BDRV_SECTOR_BITS,

                   req.bytes >> BDRV_SECTOR_BITS);

    tracked_request_end(&req);

    bdrv_dec_in_flight(bs);

    return ret;

}


static inline int fp_reg_offset(int regno, TCGMemOp size)

{

    int offs = offsetof(CPUARMState, vfp.regs[regno * 2]);

#ifdef HOST_WORDS_BIGENDIAN

    offs += (8 - (1 << size));

#endif

    return offs;

}


static inline void RENAME(rgb24tobgr16)(const uint8_t *src, uint8_t *dst, unsigned int src_size)

{

	const uint8_t *s = src;

	const uint8_t *end;

#ifdef HAVE_MMX

	const uint8_t *mm_end;

#endif

	uint16_t *d = (uint16_t *)dst;

	end = s + src_size;

#ifdef HAVE_MMX

	__asm __volatile(PREFETCH"	%0"::"m"(*src):"memory");

	__asm __volatile(

	    "movq	%0, %%mm7\n\t"

	    "movq	%1, %%mm6\n\t"

	    ::"m"(red_16mask),"m"(green_16mask));

	mm_end = end - 15;

	while(s < mm_end)

	{

	    __asm __volatile(

		PREFETCH" 32%1\n\t"

		"movd	%1, %%mm0\n\t"

		"movd	3%1, %%mm3\n\t"

		"punpckldq 6%1, %%mm0\n\t"

		"punpckldq 9%1, %%mm3\n\t"

		"movq	%%mm0, %%mm1\n\t"

		"movq	%%mm0, %%mm2\n\t"

		"movq	%%mm3, %%mm4\n\t"

		"movq	%%mm3, %%mm5\n\t"

		"psllq	$8, %%mm0\n\t"

		"psllq	$8, %%mm3\n\t"

		"pand	%%mm7, %%mm0\n\t"

		"pand	%%mm7, %%mm3\n\t"

		"psrlq	$5, %%mm1\n\t"

		"psrlq	$5, %%mm4\n\t"

		"pand	%%mm6, %%mm1\n\t"

		"pand	%%mm6, %%mm4\n\t"

		"psrlq	$19, %%mm2\n\t"

		"psrlq	$19, %%mm5\n\t"

		"pand	%2, %%mm2\n\t"

		"pand	%2, %%mm5\n\t"

		"por	%%mm1, %%mm0\n\t"

		"por	%%mm4, %%mm3\n\t"

		"por	%%mm2, %%mm0\n\t"

		"por	%%mm5, %%mm3\n\t"

		"psllq	$16, %%mm3\n\t"

		"por	%%mm3, %%mm0\n\t"

		MOVNTQ"	%%mm0, %0\n\t"

		:"=m"(*d):"m"(*s),"m"(blue_16mask):"memory");

		d += 4;

		s += 12;

	}

	__asm __volatile(SFENCE:::"memory");

	__asm __volatile(EMMS:::"memory");

#endif

	while(s < end)

	{

		const int r= *s++;

		const int g= *s++;

		const int b= *s++;

		*d++ = (b>>3) | ((g&0xFC)<<3) | ((r&0xF8)<<8);

	}

}


static int probe_file(WriterContext *wctx, const char *filename)

{

    AVFormatContext *fmt_ctx;

    int ret, i;

    int section_id;

    do_read_frames = do_show_frames || do_count_frames;

    do_read_packets = do_show_packets || do_count_packets;

    ret = open_input_file(&fmt_ctx, filename);

    if (ret < 0)

        return ret;

    nb_streams_frames  = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_frames));

    nb_streams_packets = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_packets));

    selected_streams   = av_calloc(fmt_ctx->nb_streams, sizeof(*selected_streams));

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

        if (stream_specifier) {

            ret = avformat_match_stream_specifier(fmt_ctx,

                                                  fmt_ctx->streams[i],

                                                  stream_specifier);

            if (ret < 0)

                goto end;

            else

                selected_streams[i] = ret;

            ret = 0;

        } else {

            selected_streams[i] = 1;

        }

    }

    if (do_read_frames || do_read_packets) {

        if (do_show_frames && do_show_packets &&

            wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)

            section_id = SECTION_ID_PACKETS_AND_FRAMES;

        else if (do_show_packets && !do_show_frames)

            section_id = SECTION_ID_PACKETS;

        else // (!do_show_packets && do_show_frames)

            section_id = SECTION_ID_FRAMES;

        if (do_show_frames || do_show_packets)

            writer_print_section_header(wctx, section_id);

        read_packets(wctx, fmt_ctx);

        if (do_show_frames || do_show_packets)

            writer_print_section_footer(wctx);

    }

    if (do_show_programs)

        show_programs(wctx, fmt_ctx);

    if (do_show_streams)

        show_streams(wctx, fmt_ctx);

    if (do_show_chapters)

        show_chapters(wctx, fmt_ctx);

    if (do_show_format)

        show_format(wctx, fmt_ctx);

end:

    close_input_file(&fmt_ctx);

    av_freep(&nb_streams_frames);

    av_freep(&nb_streams_packets);

    av_freep(&selected_streams);

    return ret;

}


static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,

                              int64_t pos)

{

    BDRVQcowState *s = bs->opaque;

    int64_t total_sectors = bs->total_sectors;

    int growable = bs->growable;

    int ret;

    BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);

    bs->growable = 1;

    ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);

    bs->growable = growable;

    /* bdrv_co_do_writev will have increased the total_sectors value to include

     * the VM state - the VM state is however not an actual part of the block

     * device, therefore, we need to restore the old value. */

    bs->total_sectors = total_sectors;

    return ret;

}


static int decode_frame_header(AVCodecContext *ctx,

                               const uint8_t *data, int size, int *ref)

{

    VP9Context *s = ctx->priv_data;

    int c, i, j, k, l, m, n, w, h, max, size2, res, sharp;

    int last_invisible;

    const uint8_t *data2;

    /* general header */

    if ((res = init_get_bits8(&s->gb, data, size)) < 0) {

        av_log(ctx, AV_LOG_ERROR, "Failed to initialize bitstream reader\n");

        return res;

    }

    if (get_bits(&s->gb, 2) != 0x2) { // frame marker

        av_log(ctx, AV_LOG_ERROR, "Invalid frame marker\n");

        return AVERROR_INVALIDDATA;

    }

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

    if (get_bits1(&s->gb)) { // reserved bit

        av_log(ctx, AV_LOG_ERROR, "Reserved bit should be zero\n");

        return AVERROR_INVALIDDATA;

    }

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

        *ref = get_bits(&s->gb, 3);

        return 0;

    }

    s->last_uses_2pass = s->uses_2pass;

    s->last_keyframe  = s->keyframe;

    s->keyframe       = !get_bits1(&s->gb);

    last_invisible    = s->invisible;

    s->invisible      = !get_bits1(&s->gb);

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

    s->use_last_frame_mvs = !s->errorres && !last_invisible;

    if (s->keyframe) {

        if (get_bits_long(&s->gb, 24) != VP9_SYNCCODE) { // synccode

            av_log(ctx, AV_LOG_ERROR, "Invalid sync code\n");

            return AVERROR_INVALIDDATA;

        }

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

        if (s->colorspace == 7) { // RGB = profile 1

            av_log(ctx, AV_LOG_ERROR, "RGB not supported in profile 0\n");

            return AVERROR_INVALIDDATA;

        }

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

        // for profile 1, here follows the subsampling bits

        s->refreshrefmask = 0xff;

        w = get_bits(&s->gb, 16) + 1;

        h = get_bits(&s->gb, 16) + 1;

        if (get_bits1(&s->gb)) // display size

            skip_bits(&s->gb, 32);

    } else {

        s->intraonly  = s->invisible ? get_bits1(&s->gb) : 0;

        s->resetctx   = s->errorres ? 0 : get_bits(&s->gb, 2);

        if (s->intraonly) {

            if (get_bits_long(&s->gb, 24) != VP9_SYNCCODE) { // synccode

                av_log(ctx, AV_LOG_ERROR, "Invalid sync code\n");

                return AVERROR_INVALIDDATA;

            }

            s->refreshrefmask = get_bits(&s->gb, 8);

            w = get_bits(&s->gb, 16) + 1;

            h = get_bits(&s->gb, 16) + 1;

            if (get_bits1(&s->gb)) // display size

                skip_bits(&s->gb, 32);

        } else {

            s->refreshrefmask = get_bits(&s->gb, 8);

            s->refidx[0]      = get_bits(&s->gb, 3);

            s->signbias[0]    = get_bits1(&s->gb);

            s->refidx[1]      = get_bits(&s->gb, 3);

            s->signbias[1]    = get_bits1(&s->gb);

            s->refidx[2]      = get_bits(&s->gb, 3);

            s->signbias[2]    = get_bits1(&s->gb);

            if (!s->refs[s->refidx[0]].f->data[0] ||

                !s->refs[s->refidx[1]].f->data[0] ||

                !s->refs[s->refidx[2]].f->data[0]) {

                av_log(ctx, AV_LOG_ERROR, "Not all references are available\n");

                return AVERROR_INVALIDDATA;

            }

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

                w = s->refs[s->refidx[0]].f->width;

                h = s->refs[s->refidx[0]].f->height;

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

                w = s->refs[s->refidx[1]].f->width;

                h = s->refs[s->refidx[1]].f->height;

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

                w = s->refs[s->refidx[2]].f->width;

                h = s->refs[s->refidx[2]].f->height;

            } else {

                w = get_bits(&s->gb, 16) + 1;

                h = get_bits(&s->gb, 16) + 1;

            }

            // Note that in this code, "CUR_FRAME" is actually before we

            // have formally allocated a frame, and thus actually represents

            // the _last_ frame

            s->use_last_frame_mvs &= s->frames[CUR_FRAME].tf.f->width == w &&

                                     s->frames[CUR_FRAME].tf.f->height == h;

            if (get_bits1(&s->gb)) // display size

                skip_bits(&s->gb, 32);

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

            s->filtermode = get_bits1(&s->gb) ? FILTER_SWITCHABLE :

                                                get_bits(&s->gb, 2);

            s->allowcompinter = s->signbias[0] != s->signbias[1] ||

                                s->signbias[0] != s->signbias[2];

            if (s->allowcompinter) {

                if (s->signbias[0] == s->signbias[1]) {

                    s->fixcompref    = 2;

                    s->varcompref[0] = 0;

                    s->varcompref[1] = 1;

                } else if (s->signbias[0] == s->signbias[2]) {

                    s->fixcompref    = 1;

                    s->varcompref[0] = 0;

                    s->varcompref[1] = 2;

                } else {

                    s->fixcompref    = 0;

                    s->varcompref[0] = 1;

                    s->varcompref[1] = 2;

                }

            }

        }

    }

    s->refreshctx   = s->errorres ? 0 : get_bits1(&s->gb);

    s->parallelmode = s->errorres ? 1 : get_bits1(&s->gb);

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

    /* loopfilter header data */

    s->filter.level = get_bits(&s->gb, 6);

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

    // if sharpness changed, reinit lim/mblim LUTs. if it didn't change, keep

    // the old cache values since they are still valid

    if (s->filter.sharpness != sharp)

        memset(s->filter.lim_lut, 0, sizeof(s->filter.lim_lut));

    s->filter.sharpness = sharp;

    if ((s->lf_delta.enabled = get_bits1(&s->gb))) {

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

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

                if (get_bits1(&s->gb))

                    s->lf_delta.ref[i] = get_sbits_inv(&s->gb, 6);

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

                if (get_bits1(&s->gb))

                    s->lf_delta.mode[i] = get_sbits_inv(&s->gb, 6);

        }

    } else {

        memset(&s->lf_delta, 0, sizeof(s->lf_delta));

    }

    /* quantization header data */

    s->yac_qi      = get_bits(&s->gb, 8);

    s->ydc_qdelta  = get_bits1(&s->gb) ? get_sbits_inv(&s->gb, 4) : 0;

    s->uvdc_qdelta = get_bits1(&s->gb) ? get_sbits_inv(&s->gb, 4) : 0;

    s->uvac_qdelta = get_bits1(&s->gb) ? get_sbits_inv(&s->gb, 4) : 0;

    s->lossless    = s->yac_qi == 0 && s->ydc_qdelta == 0 &&

                     s->uvdc_qdelta == 0 && s->uvac_qdelta == 0;

    /* segmentation header info */

    if ((s->segmentation.enabled = get_bits1(&s->gb))) {

        if ((s->segmentation.update_map = get_bits1(&s->gb))) {

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

                s->prob.seg[i] = get_bits1(&s->gb) ?

                                 get_bits(&s->gb, 8) : 255;

            if ((s->segmentation.temporal = get_bits1(&s->gb)))

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

                    s->prob.segpred[i] = get_bits1(&s->gb) ?

                                         get_bits(&s->gb, 8) : 255;

        } else {

            s->use_last_frame_segmap = !s->keyframe && !s->intraonly &&

                s->frames[CUR_FRAME].tf.f->width == w &&

                s->frames[CUR_FRAME].tf.f->height == h;

        }

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

            s->segmentation.absolute_vals = get_bits1(&s->gb);

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

                if ((s->segmentation.feat[i].q_enabled = get_bits1(&s->gb)))

                    s->segmentation.feat[i].q_val = get_sbits_inv(&s->gb, 8);

                if ((s->segmentation.feat[i].lf_enabled = get_bits1(&s->gb)))

                    s->segmentation.feat[i].lf_val = get_sbits_inv(&s->gb, 6);

                if ((s->segmentation.feat[i].ref_enabled = get_bits1(&s->gb)))

                    s->segmentation.feat[i].ref_val = get_bits(&s->gb, 2);

                s->segmentation.feat[i].skip_enabled = get_bits1(&s->gb);

            }

        }

    } else {

        s->segmentation.feat[0].q_enabled    = 0;

        s->segmentation.feat[0].lf_enabled   = 0;

        s->segmentation.feat[0].skip_enabled = 0;

        s->segmentation.feat[0].ref_enabled  = 0;

    }

    // set qmul[] based on Y/UV, AC/DC and segmentation Q idx deltas

    for (i = 0; i < (s->segmentation.enabled ? 8 : 1); i++) {

        int qyac, qydc, quvac, quvdc, lflvl, sh;

        if (s->segmentation.feat[i].q_enabled) {

            if (s->segmentation.absolute_vals)

                qyac = s->segmentation.feat[i].q_val;

            else

                qyac = s->yac_qi + s->segmentation.feat[i].q_val;

        } else {

            qyac  = s->yac_qi;

        }

        qydc  = av_clip_uintp2(qyac + s->ydc_qdelta, 8);

        quvdc = av_clip_uintp2(qyac + s->uvdc_qdelta, 8);

        quvac = av_clip_uintp2(qyac + s->uvac_qdelta, 8);

        qyac  = av_clip_uintp2(qyac, 8);

        s->segmentation.feat[i].qmul[0][0] = vp9_dc_qlookup[qydc];

        s->segmentation.feat[i].qmul[0][1] = vp9_ac_qlookup[qyac];

        s->segmentation.feat[i].qmul[1][0] = vp9_dc_qlookup[quvdc];

        s->segmentation.feat[i].qmul[1][1] = vp9_ac_qlookup[quvac];

        sh = s->filter.level >= 32;

        if (s->segmentation.feat[i].lf_enabled) {

            if (s->segmentation.absolute_vals)

                lflvl = s->segmentation.feat[i].lf_val;

            else

                lflvl = s->filter.level + s->segmentation.feat[i].lf_val;

        } else {

            lflvl  = s->filter.level;

        }

        s->segmentation.feat[i].lflvl[0][0] =

        s->segmentation.feat[i].lflvl[0][1] =

            av_clip_uintp2(lflvl + (s->lf_delta.ref[0] << sh), 6);

        for (j = 1; j < 4; j++) {

            s->segmentation.feat[i].lflvl[j][0] =

                av_clip_uintp2(lflvl + ((s->lf_delta.ref[j] +

                                         s->lf_delta.mode[0]) << sh), 6);

            s->segmentation.feat[i].lflvl[j][1] =

                av_clip_uintp2(lflvl + ((s->lf_delta.ref[j] +

                                         s->lf_delta.mode[1]) << sh), 6);

        }

    }

    /* tiling info */

    if ((res = update_size(ctx, w, h)) < 0) {

        av_log(ctx, AV_LOG_ERROR, "Failed to initialize decoder for %dx%d\n", w, h);

        return res;

    }

    for (s->tiling.log2_tile_cols = 0;

         (s->sb_cols >> s->tiling.log2_tile_cols) > 64;

         s->tiling.log2_tile_cols++) ;

    for (max = 0; (s->sb_cols >> max) >= 4; max++) ;

    max = FFMAX(0, max - 1);

    while (max > s->tiling.log2_tile_cols) {

        if (get_bits1(&s->gb))

            s->tiling.log2_tile_cols++;

        else

            break;

    }

    s->tiling.log2_tile_rows = decode012(&s->gb);

    s->tiling.tile_rows = 1 << s->tiling.log2_tile_rows;

    if (s->tiling.tile_cols != (1 << s->tiling.log2_tile_cols)) {

        s->tiling.tile_cols = 1 << s->tiling.log2_tile_cols;

        s->c_b = av_fast_realloc(s->c_b, &s->c_b_size,

                                 sizeof(VP56RangeCoder) * s->tiling.tile_cols);

        if (!s->c_b) {

            av_log(ctx, AV_LOG_ERROR, "Ran out of memory during range coder init\n");

            return AVERROR(ENOMEM);

        }

    }

    if (s->keyframe || s->errorres || s->intraonly) {

        s->prob_ctx[0].p = s->prob_ctx[1].p = s->prob_ctx[2].p =

                           s->prob_ctx[3].p = vp9_default_probs;

        memcpy(s->prob_ctx[0].coef, vp9_default_coef_probs,

               sizeof(vp9_default_coef_probs));

        memcpy(s->prob_ctx[1].coef, vp9_default_coef_probs,

               sizeof(vp9_default_coef_probs));

        memcpy(s->prob_ctx[2].coef, vp9_default_coef_probs,

               sizeof(vp9_default_coef_probs));

        memcpy(s->prob_ctx[3].coef, vp9_default_coef_probs,

               sizeof(vp9_default_coef_probs));

    }

    // next 16 bits is size of the rest of the header (arith-coded)

    size2 = get_bits(&s->gb, 16);

    data2 = align_get_bits(&s->gb);

    if (size2 > size - (data2 - data)) {

        av_log(ctx, AV_LOG_ERROR, "Invalid compressed header size\n");

        return AVERROR_INVALIDDATA;

    }

    ff_vp56_init_range_decoder(&s->c, data2, size2);

    if (vp56_rac_get_prob_branchy(&s->c, 128)) { // marker bit

        av_log(ctx, AV_LOG_ERROR, "Marker bit was set\n");

        return AVERROR_INVALIDDATA;

    }

    if (s->keyframe || s->intraonly) {

        memset(s->counts.coef, 0, sizeof(s->counts.coef) + sizeof(s->counts.eob));

    } else {

        memset(&s->counts, 0, sizeof(s->counts));

    }

    // FIXME is it faster to not copy here, but do it down in the fw updates

    // as explicit copies if the fw update is missing (and skip the copy upon

    // fw update)?

    s->prob.p = s->prob_ctx[c].p;

    // txfm updates

    if (s->lossless) {

        s->txfmmode = TX_4X4;

    } else {

        s->txfmmode = vp8_rac_get_uint(&s->c, 2);

        if (s->txfmmode == 3)

            s->txfmmode += vp8_rac_get(&s->c);

        if (s->txfmmode == TX_SWITCHABLE) {

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

                if (vp56_rac_get_prob_branchy(&s->c, 252))

                    s->prob.p.tx8p[i] = update_prob(&s->c, s->prob.p.tx8p[i]);

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

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

                    if (vp56_rac_get_prob_branchy(&s->c, 252))

                        s->prob.p.tx16p[i][j] =

                            update_prob(&s->c, s->prob.p.tx16p[i][j]);

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

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

                    if (vp56_rac_get_prob_branchy(&s->c, 252))

                        s->prob.p.tx32p[i][j] =

                            update_prob(&s->c, s->prob.p.tx32p[i][j]);

        }

    }

    // coef updates

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

        uint8_t (*ref)[2][6][6][3] = s->prob_ctx[c].coef[i];

        if (vp8_rac_get(&s->c)) {

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

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

                    for (l = 0; l < 6; l++)

                        for (m = 0; m < 6; m++) {

                            uint8_t *p = s->prob.coef[i][j][k][l][m];

                            uint8_t *r = ref[j][k][l][m];

                            if (m >= 3 && l == 0) // dc only has 3 pt

                                break;

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

                                if (vp56_rac_get_prob_branchy(&s->c, 252)) {

                                    p[n] = update_prob(&s->c, r[n]);

                                } else {

                                    p[n] = r[n];

                                }

                            }

                            p[3] = 0;

                        }

        } else {

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

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

                    for (l = 0; l < 6; l++)

                        for (m = 0; m < 6; m++) {

                            uint8_t *p = s->prob.coef[i][j][k][l][m];

                            uint8_t *r = ref[j][k][l][m];

                            if (m > 3 && l == 0) // dc only has 3 pt

                                break;

                            memcpy(p, r, 3);

                            p[3] = 0;

                        }

        }

        if (s->txfmmode == i)

            break;

    }

    // mode updates

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

        if (vp56_rac_get_prob_branchy(&s->c, 252))

            s->prob.p.skip[i] = update_prob(&s->c, s->prob.p.skip[i]);

    if (!s->keyframe && !s->intraonly) {

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

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

                if (vp56_rac_get_prob_branchy(&s->c, 252))

                    s->prob.p.mv_mode[i][j] =

                        update_prob(&s->c, s->prob.p.mv_mode[i][j]);

        if (s->filtermode == FILTER_SWITCHABLE)

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

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

                    if (vp56_rac_get_prob_branchy(&s->c, 252))

                        s->prob.p.filter[i][j] =

                            update_prob(&s->c, s->prob.p.filter[i][j]);

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

            if (vp56_rac_get_prob_branchy(&s->c, 252))

                s->prob.p.intra[i] = update_prob(&s->c, s->prob.p.intra[i]);

        if (s->allowcompinter) {

            s->comppredmode = vp8_rac_get(&s->c);

            if (s->comppredmode)

                s->comppredmode += vp8_rac_get(&s->c);

            if (s->comppredmode == PRED_SWITCHABLE)

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

                    if (vp56_rac_get_prob_branchy(&s->c, 252))

                        s->prob.p.comp[i] =

                            update_prob(&s->c, s->prob.p.comp[i]);

        } else {

            s->comppredmode = PRED_SINGLEREF;

        }

        if (s->comppredmode != PRED_COMPREF) {

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

                if (vp56_rac_get_prob_branchy(&s->c, 252))

                    s->prob.p.single_ref[i][0] =

                        update_prob(&s->c, s->prob.p.single_ref[i][0]);

                if (vp56_rac_get_prob_branchy(&s->c, 252))

                    s->prob.p.single_ref[i][1] =

                        update_prob(&s->c, s->prob.p.single_ref[i][1]);

            }

        }

        if (s->comppredmode != PRED_SINGLEREF) {

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

                if (vp56_rac_get_prob_branchy(&s->c, 252))

                    s->prob.p.comp_ref[i] =

                        update_prob(&s->c, s->prob.p.comp_ref[i]);

        }

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

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

                if (vp56_rac_get_prob_branchy(&s->c, 252))

                    s->prob.p.y_mode[i][j] =

                        update_prob(&s->c, s->prob.p.y_mode[i][j]);

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

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

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

                    if (vp56_rac_get_prob_branchy(&s->c, 252))

                        s->prob.p.partition[3 - i][j][k] =

                            update_prob(&s->c, s->prob.p.partition[3 - i][j][k]);

        // mv fields don't use the update_prob subexp model for some reason

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

            if (vp56_rac_get_prob_branchy(&s->c, 252))

                s->prob.p.mv_joint[i] = (vp8_rac_get_uint(&s->c, 7) << 1) | 1;

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

            if (vp56_rac_get_prob_branchy(&s->c, 252))

                s->prob.p.mv_comp[i].sign = (vp8_rac_get_uint(&s->c, 7) << 1) | 1;

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

                if (vp56_rac_get_prob_branchy(&s->c, 252))

                    s->prob.p.mv_comp[i].classes[j] =

                        (vp8_rac_get_uint(&s->c, 7) << 1) | 1;

            if (vp56_rac_get_prob_branchy(&s->c, 252))

                s->prob.p.mv_comp[i].class0 = (vp8_rac_get_uint(&s->c, 7) << 1) | 1;

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

                if (vp56_rac_get_prob_branchy(&s->c, 252))

                    s->prob.p.mv_comp[i].bits[j] =

                        (vp8_rac_get_uint(&s->c, 7) << 1) | 1;

        }

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

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

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

                    if (vp56_rac_get_prob_branchy(&s->c, 252))

                        s->prob.p.mv_comp[i].class0_fp[j][k] =

                            (vp8_rac_get_uint(&s->c, 7) << 1) | 1;

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

                if (vp56_rac_get_prob_branchy(&s->c, 252))

                    s->prob.p.mv_comp[i].fp[j] =

                        (vp8_rac_get_uint(&s->c, 7) << 1) | 1;

        }

        if (s->highprecisionmvs) {

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

                if (vp56_rac_get_prob_branchy(&s->c, 252))

                    s->prob.p.mv_comp[i].class0_hp =

                        (vp8_rac_get_uint(&s->c, 7) << 1) | 1;

                if (vp56_rac_get_prob_branchy(&s->c, 252))

                    s->prob.p.mv_comp[i].hp =

                        (vp8_rac_get_uint(&s->c, 7) << 1) | 1;

            }

        }

    }

    return (data2 - data) + size2;

}


yuv2422_1_c_template(SwsContext *c, const int16_t *buf0,

                     const int16_t *ubuf[2], const int16_t *vbuf[2],

                     const int16_t *abuf0, uint8_t *dest, int dstW,

                     int uvalpha, int y, enum PixelFormat target)

{

    const int16_t *ubuf0 = ubuf[0], *ubuf1 = ubuf[1],

                  *vbuf0 = vbuf[0], *vbuf1 = vbuf[1];

    int i;

    if (uvalpha < 2048) {

        for (i = 0; i < (dstW >> 1); i++) {

            int Y1 = buf0[i * 2]     >> 7;

            int Y2 = buf0[i * 2 + 1] >> 7;

            int U  = ubuf1[i]        >> 7;

            int V  = vbuf1[i]        >> 7;

            output_pixels(i * 4, Y1, U, Y2, V);

        }

    } else {

        for (i = 0; i < (dstW >> 1); i++) {

            int Y1 =  buf0[i * 2]          >> 7;

            int Y2 =  buf0[i * 2 + 1]      >> 7;

            int U  = (ubuf0[i] + ubuf1[i]) >> 8;

            int V  = (vbuf0[i] + vbuf1[i]) >> 8;

            output_pixels(i * 4, Y1, U, Y2, V);

        }

    }

}


static void local_mapped_file_attr(int dirfd, const char *name,

                                   struct stat *stbuf)

{

    FILE *fp;

    char buf[ATTR_MAX];

    int map_dirfd;

    map_dirfd = openat(dirfd, VIRTFS_META_DIR,

                       O_RDONLY | O_DIRECTORY | O_NOFOLLOW);

    if (map_dirfd == -1) {

        return;

    }

    fp = local_fopenat(map_dirfd, name, "r");

    close_preserve_errno(map_dirfd);

    if (!fp) {

        return;

    }

    memset(buf, 0, ATTR_MAX);

    while (fgets(buf, ATTR_MAX, fp)) {

        if (!strncmp(buf, "virtfs.uid", 10)) {

            stbuf->st_uid = atoi(buf+11);

        } else if (!strncmp(buf, "virtfs.gid", 10)) {

            stbuf->st_gid = atoi(buf+11);

        } else if (!strncmp(buf, "virtfs.mode", 11)) {

            stbuf->st_mode = atoi(buf+12);

        } else if (!strncmp(buf, "virtfs.rdev", 11)) {

            stbuf->st_rdev = atoi(buf+12);

        }

        memset(buf, 0, ATTR_MAX);

    }

    fclose(fp);

}


pci_e1000_init(PCIBus *bus, NICInfo *nd, int devfn)

{

    E1000State *d;

    uint8_t *pci_conf;

    uint16_t checksum = 0;

    static const char info_str[] = "e1000";

    int i;

    d = (E1000State *)pci_register_device(bus, "e1000",

                sizeof(E1000State), devfn, NULL, NULL);

    pci_conf = d->dev.config;

    memset(pci_conf, 0, 256);

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);

    pci_config_set_device_id(pci_conf, E1000_DEVID);

    *(uint16_t *)(pci_conf+0x04) = cpu_to_le16(0x0407);

    *(uint16_t *)(pci_conf+0x06) = cpu_to_le16(0x0010);

    pci_conf[0x08] = 0x03;

    pci_config_set_class(pci_conf, PCI_CLASS_NETWORK_ETHERNET);

    pci_conf[0x0c] = 0x10;

    pci_conf[0x3d] = 1; // interrupt pin 0

    d->mmio_index = cpu_register_io_memory(0, e1000_mmio_read,

            e1000_mmio_write, d);

    pci_register_io_region((PCIDevice *)d, 0, PNPMMIO_SIZE,

                           PCI_ADDRESS_SPACE_MEM, e1000_mmio_map);

    pci_register_io_region((PCIDevice *)d, 1, IOPORT_SIZE,

                           PCI_ADDRESS_SPACE_IO, ioport_map);

    memmove(d->eeprom_data, e1000_eeprom_template,

        sizeof e1000_eeprom_template);

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

        d->eeprom_data[i] = (nd->macaddr[2*i+1]<<8) | nd->macaddr[2*i];

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

        checksum += d->eeprom_data[i];

    checksum = (uint16_t) EEPROM_SUM - checksum;

    d->eeprom_data[EEPROM_CHECKSUM_REG] = checksum;

    memset(d->phy_reg, 0, sizeof d->phy_reg);

    memmove(d->phy_reg, phy_reg_init, sizeof phy_reg_init);

    memset(d->mac_reg, 0, sizeof d->mac_reg);

    memmove(d->mac_reg, mac_reg_init, sizeof mac_reg_init);

    d->rxbuf_min_shift = 1;

    memset(&d->tx, 0, sizeof d->tx);

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

                                 e1000_receive, e1000_can_receive, d);

    d->vc->link_status_changed = e1000_set_link_status;

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

    register_savevm(info_str, -1, 2, nic_save, nic_load, d);

    d->dev.unregister = pci_e1000_uninit;

    return (PCIDevice *)d;

}


static void legacy_kbd_event(DeviceState *dev, QemuConsole *src,

                             InputEvent *evt)

{

    QEMUPutKbdEntry *entry = (QEMUPutKbdEntry *)dev;

    int scancodes[3], i, count;

    if (!entry || !entry->put_kbd) {

        return;

    }

    count = qemu_input_key_value_to_scancode(evt->key->key,

                                             evt->key->down,

                                             scancodes);

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

        entry->put_kbd(entry->opaque, scancodes[i]);

    }

}


PITState *pit_init(int base, qemu_irq irq)

{

    PITState *pit = &pit_state;

    PITChannelState *s;

    s = &pit->channels[0];

    /* the timer 0 is connected to an IRQ */

    s->irq_timer = qemu_new_timer(vm_clock, pit_irq_timer, s);

    s->irq = irq;

    vmstate_register(base, &vmstate_pit, pit);

    qemu_register_reset(pit_reset, pit);

    register_ioport_write(base, 4, 1, pit_ioport_write, pit);

    register_ioport_read(base, 3, 1, pit_ioport_read, pit);

    pit_reset(pit);

    return pit;

}


static int qxl_init_common(PCIQXLDevice *qxl)

{

    uint8_t* config = qxl->pci.config;

    uint32_t pci_device_id;

    uint32_t pci_device_rev;

    uint32_t io_size;

    qxl->mode = QXL_MODE_UNDEFINED;

    qxl->generation = 1;

    qxl->num_memslots = NUM_MEMSLOTS;

    qxl->num_surfaces = NUM_SURFACES;

    switch (qxl->revision) {

    case 1: /* spice 0.4 -- qxl-1 */

        pci_device_id  = QXL_DEVICE_ID_STABLE;

        pci_device_rev = QXL_REVISION_STABLE_V04;

        break;

    case 2: /* spice 0.6 -- qxl-2 */

        pci_device_id  = QXL_DEVICE_ID_STABLE;

        pci_device_rev = QXL_REVISION_STABLE_V06;

        break;

    default: /* experimental */

        pci_device_id  = QXL_DEVICE_ID_DEVEL;

        pci_device_rev = 1;

        break;

    }

    pci_config_set_vendor_id(config, REDHAT_PCI_VENDOR_ID);

    pci_config_set_device_id(config, pci_device_id);

    pci_set_byte(&config[PCI_REVISION_ID], pci_device_rev);

    pci_set_byte(&config[PCI_INTERRUPT_PIN], 1);

    qxl->rom_size = qxl_rom_size();

    qxl->rom_offset = qemu_ram_alloc(&qxl->pci.qdev, "qxl.vrom", qxl->rom_size);

    init_qxl_rom(qxl);

    init_qxl_ram(qxl);

    if (qxl->vram_size < 16 * 1024 * 1024) {

        qxl->vram_size = 16 * 1024 * 1024;

    }

    if (qxl->revision == 1) {

        qxl->vram_size = 4096;

    }

    qxl->vram_size = msb_mask(qxl->vram_size * 2 - 1);

    qxl->vram_offset = qemu_ram_alloc(&qxl->pci.qdev, "qxl.vram", qxl->vram_size);

    io_size = msb_mask(QXL_IO_RANGE_SIZE * 2 - 1);

    if (qxl->revision == 1) {

        io_size = 8;

    }

    pci_register_bar(&qxl->pci, QXL_IO_RANGE_INDEX,

                     io_size, PCI_BASE_ADDRESS_SPACE_IO, qxl_map);

    pci_register_bar(&qxl->pci, QXL_ROM_RANGE_INDEX,

                     qxl->rom_size, PCI_BASE_ADDRESS_SPACE_MEMORY,

                     qxl_map);

    pci_register_bar(&qxl->pci, QXL_RAM_RANGE_INDEX,

                     qxl->vga.vram_size, PCI_BASE_ADDRESS_SPACE_MEMORY,

                     qxl_map);

    pci_register_bar(&qxl->pci, QXL_VRAM_RANGE_INDEX, qxl->vram_size,

                     PCI_BASE_ADDRESS_SPACE_MEMORY, qxl_map);

    qxl->ssd.qxl.base.sif = &qxl_interface.base;

    qxl->ssd.qxl.id = qxl->id;

    qemu_spice_add_interface(&qxl->ssd.qxl.base);

    qemu_add_vm_change_state_handler(qxl_vm_change_state_handler, qxl);

    init_pipe_signaling(qxl);

    qxl_reset_state(qxl);

    return 0;

}


static TCGReg tcg_out_tlb_read(TCGContext* s, TCGReg addr_reg, TCGMemOp opc,

                               int mem_index, bool is_ld)

{

    int s_mask = (1 << (opc & MO_SIZE)) - 1;

    int ofs, a_off;

    uint64_t tlb_mask;

    /* For aligned accesses, we check the first byte and include the alignment

       bits within the address.  For unaligned access, we check that we don't

       cross pages using the address of the last byte of the access.  */

    if ((opc & MO_AMASK) == MO_ALIGN || s_mask == 0) {

        a_off = 0;

        tlb_mask = TARGET_PAGE_MASK | s_mask;

    } else {

        a_off = s_mask;

        tlb_mask = TARGET_PAGE_MASK;

    }

    if (facilities & FACILITY_GEN_INST_EXT) {

        tcg_out_risbg(s, TCG_REG_R2, addr_reg,

                      64 - CPU_TLB_BITS - CPU_TLB_ENTRY_BITS,

                      63 - CPU_TLB_ENTRY_BITS,

                      64 + CPU_TLB_ENTRY_BITS - TARGET_PAGE_BITS, 1);

        if (a_off) {

            tcg_out_insn(s, RX, LA, TCG_REG_R3, addr_reg, TCG_REG_NONE, a_off);

            tgen_andi(s, TCG_TYPE_TL, TCG_REG_R3, tlb_mask);

        } else {

            tgen_andi_risbg(s, TCG_REG_R3, addr_reg, tlb_mask);

        }

    } else {

        tcg_out_sh64(s, RSY_SRLG, TCG_REG_R2, addr_reg, TCG_REG_NONE,

                     TARGET_PAGE_BITS - CPU_TLB_ENTRY_BITS);

        tcg_out_insn(s, RX, LA, TCG_REG_R3, addr_reg, TCG_REG_NONE, a_off);

        tgen_andi(s, TCG_TYPE_I64, TCG_REG_R2,

                  (CPU_TLB_SIZE - 1) << CPU_TLB_ENTRY_BITS);

        tgen_andi(s, TCG_TYPE_TL, TCG_REG_R3, tlb_mask);

    }

    if (is_ld) {

        ofs = offsetof(CPUArchState, tlb_table[mem_index][0].addr_read);

    } else {

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

    }

    if (TARGET_LONG_BITS == 32) {

        tcg_out_mem(s, RX_C, RXY_CY, TCG_REG_R3, TCG_REG_R2, TCG_AREG0, ofs);

    } else {

        tcg_out_mem(s, 0, RXY_CG, TCG_REG_R3, TCG_REG_R2, TCG_AREG0, ofs);

    }

    ofs = offsetof(CPUArchState, tlb_table[mem_index][0].addend);

    tcg_out_mem(s, 0, RXY_LG, TCG_REG_R2, TCG_REG_R2, TCG_AREG0, ofs);

    if (TARGET_LONG_BITS == 32) {

        tgen_ext32u(s, TCG_REG_R3, addr_reg);

        return TCG_REG_R3;

    }

    return addr_reg;

}


static void unterminated_literal(void)

{

    QObject *obj = qobject_from_json("nul", NULL);

    g_assert(obj == NULL);

}


static void decode_sublayer_hrd(HEVCContext *s, int nb_cpb,

                                int subpic_params_present)

{

    GetBitContext *gb = &s->HEVClc.gb;

    int i;

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

        get_ue_golomb_long(gb); // bit_rate_value_minus1

        get_ue_golomb_long(gb); // cpb_size_value_minus1

        if (subpic_params_present) {

            get_ue_golomb_long(gb); // cpb_size_du_value_minus1

            get_ue_golomb_long(gb); // bit_rate_du_value_minus1

        }

        skip_bits1(gb); // cbr_flag

    }

}


static inline int onenand_load_main(OneNANDState *s, int sec, int secn,

                void *dest)

{

    if (s->blk_cur) {

        return blk_read(s->blk_cur, sec, dest, secn) < 0;

    } else if (sec + secn > s->secs_cur) {

        return 1;

    }

    memcpy(dest, s->current + (sec << 9), secn << 9);

    return 0;

}


static void flush_trace_file(void)

{

    /* If the trace file is not open yet, open it now */

    if (!trace_fp) {

        trace_fp = fopen(trace_file_name, "w");

        if (!trace_fp) {

            /* Avoid repeatedly trying to open file on failure */

            trace_file_enabled = false;

            return;

        }

        write_header(trace_fp);

    }

    if (trace_fp) {

        size_t unused; /* for when fwrite(3) is declared warn_unused_result */

        unused = fwrite(trace_buf, trace_idx * sizeof(trace_buf[0]), 1, trace_fp);

    }

}


void helper_fxtoq(CPUSPARCState *env, int64_t src)

{

    /* No possible exceptions converting long long to long double.  */

    QT0 = int64_to_float128(src, &env->fp_status);

}


static void v9fs_open(void *opaque)

{

    int flags;

    int32_t fid;

    int32_t mode;

    V9fsQID qid;

    int iounit = 0;

    ssize_t err = 0;

    size_t offset = 7;

    struct stat stbuf;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    if (s->proto_version == V9FS_PROTO_2000L) {

        pdu_unmarshal(pdu, offset, "dd", &fid, &mode);

    } else {

        pdu_unmarshal(pdu, offset, "db", &fid, &mode);

    }

    trace_v9fs_open(pdu->tag, pdu->id, fid, mode);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -ENOENT;

        goto out_nofid;

    }

    BUG_ON(fidp->fid_type != P9_FID_NONE);

    err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);

    if (err < 0) {

        goto out;

    }

    stat_to_qid(&stbuf, &qid);

    if (S_ISDIR(stbuf.st_mode)) {

        err = v9fs_co_opendir(pdu, fidp);

        if (err < 0) {

            goto out;

        }

        fidp->fid_type = P9_FID_DIR;

        offset += pdu_marshal(pdu, offset, "Qd", &qid, 0);

        err = offset;

    } else {

        if (s->proto_version == V9FS_PROTO_2000L) {

            flags = get_dotl_openflags(s, mode);

        } else {

            flags = omode_to_uflags(mode);

        }

        if (is_ro_export(&s->ctx)) {

            if (mode & O_WRONLY || mode & O_RDWR ||

                mode & O_APPEND || mode & O_TRUNC) {

                err = -EROFS;

                goto out;

            }

            flags |= O_NOATIME;

        }

        err = v9fs_co_open(pdu, fidp, flags);

        if (err < 0) {

            goto out;

        }

        fidp->fid_type = P9_FID_FILE;

        fidp->open_flags = flags;

        if (flags & O_EXCL) {

            /*

             * We let the host file system do O_EXCL check

             * We should not reclaim such fd

             */

            fidp->flags |= FID_NON_RECLAIMABLE;

        }

        iounit = get_iounit(pdu, &fidp->path);

        offset += pdu_marshal(pdu, offset, "Qd", &qid, iounit);

        err = offset;

    }

    trace_v9fs_open_return(pdu->tag, pdu->id,

                           qid.type, qid.version, qid.path, iounit);

out:

    put_fid(pdu, fidp);

out_nofid:

    complete_pdu(s, pdu, err);

}


static int pci_piix3_ide_initfn(PCIDevice *dev)

{

    PCIIDEState *d = DO_UPCAST(PCIIDEState, dev, dev);

    pci_config_set_vendor_id(d->dev.config, PCI_VENDOR_ID_INTEL);

    pci_config_set_device_id(d->dev.config, PCI_DEVICE_ID_INTEL_82371SB_1);

    return pci_piix_ide_initfn(d);

}


static abi_long do_getpeername(int fd, abi_ulong target_addr,

                               abi_ulong target_addrlen_addr)

{

    socklen_t addrlen;

    void *addr;

    abi_long ret;

    if (get_user_u32(addrlen, target_addrlen_addr))

        return -TARGET_EFAULT;

    if (addrlen < 0 || addrlen > MAX_SOCK_ADDR)

        return -TARGET_EINVAL;

    addr = alloca(addrlen);

    ret = get_errno(getpeername(fd, addr, &addrlen));

    if (!is_error(ret)) {

        host_to_target_sockaddr(target_addr, addr, addrlen);

        if (put_user_u32(addrlen, target_addrlen_addr))

            ret = -TARGET_EFAULT;

    }

    return ret;

}


void ppc_hash64_set_external_hpt(PowerPCCPU *cpu, void *hpt, int shift,

                                 Error **errp)

{

    CPUPPCState *env = &cpu->env;

    Error *local_err = NULL;

    cpu_synchronize_state(CPU(cpu));

    env->external_htab = hpt;

    ppc_hash64_set_sdr1(cpu, (target_ulong)(uintptr_t)hpt | (shift - 18),

                        &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    /* Not strictly necessary, but makes it clearer that an external

     * htab is in use when debugging */

    env->htab_base = -1;

    if (kvm_enabled()) {

        if (kvmppc_put_books_sregs(cpu) < 0) {

            error_setg(errp, "Unable to update SDR1 in KVM");

        }

    }

}


void numa_set_mem_node_id(ram_addr_t addr, uint64_t size, uint32_t node)

{

    struct numa_addr_range *range = g_malloc0(sizeof(*range));

    /*

     * Memory-less nodes can come here with 0 size in which case,

     * there is nothing to do.

     */

    if (!size) {

        return;

    }

    range->mem_start = addr;

    range->mem_end = addr + size - 1;

    QLIST_INSERT_HEAD(&numa_info[node].addr, range, entry);

}


static inline int cris_bound_d(int v, int b)

{

	int r = v;

	asm ("bound.d\t%1, %0\n" : "+r" (r) : "ri" (b));

	return r;

}


static void mpeg4_encode_visual_object_header(MpegEncContext * s){

    int profile_and_level_indication;

    int vo_ver_id;

    if(s->max_b_frames || s->quarter_sample){

        profile_and_level_indication= 0xF1; // adv simple level 1

        vo_ver_id= 5;

    }else{

        profile_and_level_indication= 0x01; // simple level 1

        vo_ver_id= 1;

    }

    //FIXME levels

    put_bits(&s->pb, 16, 0);

    put_bits(&s->pb, 16, VOS_STARTCODE);

    put_bits(&s->pb, 8, profile_and_level_indication);

    put_bits(&s->pb, 16, 0);

    put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);

    put_bits(&s->pb, 1, 1);

        put_bits(&s->pb, 4, vo_ver_id);

        put_bits(&s->pb, 3, 1); //priority

    put_bits(&s->pb, 4, 1); //visual obj type== video obj

    put_bits(&s->pb, 1, 0); //video signal type == no clue //FIXME

    ff_mpeg4_stuffing(&s->pb);

}


static void add_entry1(TiffEncoderContext *s,

                       enum TiffTags tag, enum TiffTypes type, int val)

{

    uint16_t w  = val;

    uint32_t dw = val;

    add_entry(s, tag, type, 1, type == TIFF_SHORT ? (void *)&w : (void *)&dw);

}


static const char *pxb_host_root_bus_path(PCIHostState *host_bridge,

                                          PCIBus *rootbus)

{

    PXBBus *bus = PXB_BUS(rootbus);

    snprintf(bus->bus_path, 8, "0000:%02x", pxb_bus_num(rootbus));

    return bus->bus_path;

}


int qemu_strtou64(const char *nptr, const char **endptr, int base,

                  uint64_t *result)

{

    char *p;

    int err = 0;

    if (!nptr) {

        if (endptr) {

            *endptr = nptr;

        }

        err = -EINVAL;

    } else {

        errno = 0;

        /* FIXME This assumes uint64_t is unsigned long long */

        *result = strtoull(nptr, &p, base);

        /* Windows returns 1 for negative out-of-range values.  */

        if (errno == ERANGE) {

            *result = -1;

        }

        err = check_strtox_error(nptr, p, endptr, errno);

    }

    return err;

}