static bool aio_dispatch_handlers(AioContext *ctx, HANDLE event)

{

    AioHandler *node;

    bool progress = false;

    /*

     * We have to walk very carefully in case aio_set_fd_handler is

     * called while we're walking.

     */

    node = QLIST_FIRST(&ctx->aio_handlers);

    while (node) {

        AioHandler *tmp;

        ctx->walking_handlers++;

        if (!node->deleted &&

            (node->pfd.revents || event_notifier_get_handle(node->e) == event) &&

            node->io_notify) {

            node->pfd.revents = 0;

            node->io_notify(node->e);

            /* aio_notify() does not count as progress */

            if (node->e != &ctx->notifier) {

                progress = true;

            }

        }

        tmp = node;

        node = QLIST_NEXT(node, node);

        ctx->walking_handlers--;

        if (!ctx->walking_handlers && tmp->deleted) {

            QLIST_REMOVE(tmp, node);

            g_free(tmp);

        }

    }

    return progress;

}


static void monitor_control_read(void *opaque, const uint8_t *buf, int size)

{

    Monitor *old_mon = cur_mon;

    cur_mon = opaque;

    // TODO: read QMP input

    cur_mon = old_mon;

}


int kvm_log_stop(target_phys_addr_t phys_addr, ram_addr_t size)

{

        return kvm_dirty_pages_log_change(phys_addr, size,

                                          0,

                                          KVM_MEM_LOG_DIRTY_PAGES);

}


static int curl_find_buf(BDRVCURLState *s, size_t start, size_t len,

                         CURLAIOCB *acb)

{

    int i;

    size_t end = start + len;

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

        CURLState *state = &s->states[i];

        size_t buf_end = (state->buf_start + state->buf_off);

        size_t buf_fend = (state->buf_start + state->buf_len);

        if (!state->orig_buf)

            continue;

        if (!state->buf_off)

            continue;

        // Does the existing buffer cover our section?

        if ((start >= state->buf_start) &&

            (start <= buf_end) &&

            (end >= state->buf_start) &&

            (end <= buf_end))

        {

            char *buf = state->orig_buf + (start - state->buf_start);

            qemu_iovec_from_buf(acb->qiov, 0, buf, len);

            acb->common.cb(acb->common.opaque, 0);

            return FIND_RET_OK;

        }

        // Wait for unfinished chunks

        if ((start >= state->buf_start) &&

            (start <= buf_fend) &&

            (end >= state->buf_start) &&

            (end <= buf_fend))

        {

            int j;

            acb->start = start - state->buf_start;

            acb->end = acb->start + len;

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

                if (!state->acb[j]) {

                    state->acb[j] = acb;

                    return FIND_RET_WAIT;

                }

            }

        }

    }

    return FIND_RET_NONE;

}


static uint64_t mcf_intc_read(void *opaque, target_phys_addr_t addr,

                              unsigned size)

{

    int offset;

    mcf_intc_state *s = (mcf_intc_state *)opaque;

    offset = addr & 0xff;

    if (offset >= 0x40 && offset < 0x80) {

        return s->icr[offset - 0x40];

    }

    switch (offset) {

    case 0x00:

        return (uint32_t)(s->ipr >> 32);

    case 0x04:

        return (uint32_t)s->ipr;

    case 0x08:

        return (uint32_t)(s->imr >> 32);

    case 0x0c:

        return (uint32_t)s->imr;

    case 0x10:

        return (uint32_t)(s->ifr >> 32);

    case 0x14:

        return (uint32_t)s->ifr;

    case 0xe0: /* SWIACK.  */

        return s->active_vector;

    case 0xe1: case 0xe2: case 0xe3: case 0xe4:

    case 0xe5: case 0xe6: case 0xe7:

        /* LnIACK */

        hw_error("mcf_intc_read: LnIACK not implemented\n");

    default:

        return 0;

    }

}


int ff_hls_write_file_entry(AVIOContext *out, int insert_discont,

                             int byterange_mode,

                             double duration, int round_duration,

                             int64_t size, int64_t pos, //Used only if HLS_SINGLE_FILE flag is set

                             char *baseurl, //Ignored if NULL

                             char *filename, double *prog_date_time) {

    if (!out || !filename)

        return AVERROR(EINVAL);

    if (insert_discont) {

        avio_printf(out, "#EXT-X-DISCONTINUITY\n");

    }

    if (round_duration)

        avio_printf(out, "#EXTINF:%ld,\n",  lrint(duration));

    else

        avio_printf(out, "#EXTINF:%f,\n", duration);

    if (byterange_mode)

        avio_printf(out, "#EXT-X-BYTERANGE:%"PRId64"@%"PRId64"\n", size, pos);

    if (prog_date_time) {

        time_t tt, wrongsecs;

        int milli;

        struct tm *tm, tmpbuf;

        char buf0[128], buf1[128];

        tt = (int64_t)*prog_date_time;

        milli = av_clip(lrint(1000*(*prog_date_time - tt)), 0, 999);

        tm = localtime_r(&tt, &tmpbuf);

        strftime(buf0, sizeof(buf0), "%Y-%m-%dT%H:%M:%S", tm);

        if (!strftime(buf1, sizeof(buf1), "%z", tm) || buf1[1]<'0' ||buf1[1]>'2') {

            int tz_min, dst = tm->tm_isdst;

            tm = gmtime_r(&tt, &tmpbuf);

            tm->tm_isdst = dst;

            wrongsecs = mktime(tm);

            tz_min = (FFABS(wrongsecs - tt) + 30) / 60;

            snprintf(buf1, sizeof(buf1),

                     "%c%02d%02d",

                     wrongsecs <= tt ? '+' : '-',

                     tz_min / 60,

                     tz_min % 60);

        }

        avio_printf(out, "#EXT-X-PROGRAM-DATE-TIME:%s.%03d%s\n", buf0, milli, buf1);

        *prog_date_time += duration;

    }

    if (baseurl)

        avio_printf(out, "%s", baseurl);

    avio_printf(out, "%s\n", filename);

    return 0;

}


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

{

    int addr_reg, data_reg, data_reg2, bswap;

#ifdef CONFIG_SOFTMMU

    int mem_index, s_bits;

# if TARGET_LONG_BITS == 64

    int addr_reg2;

# endif

    uint32_t *label_ptr;

#endif

#ifdef TARGET_WORDS_BIGENDIAN

    bswap = 1;

#else

    bswap = 0;

#endif

    data_reg = *args++;

    if (opc == 3)

        data_reg2 = *args++;

    else

        data_reg2 = 0; /* suppress warning */

    addr_reg = *args++;

#ifdef CONFIG_SOFTMMU

# if TARGET_LONG_BITS == 64

    addr_reg2 = *args++;

# endif

    mem_index = *args;

    s_bits = opc & 3;

    /* Should generate something like the following:

     *  shr r8, addr_reg, #TARGET_PAGE_BITS

     *  and r0, r8, #(CPU_TLB_SIZE - 1)   @ Assumption: CPU_TLB_BITS <= 8

     *  add r0, env, r0 lsl #CPU_TLB_ENTRY_BITS

     */

#  if CPU_TLB_BITS > 8

#   error

#  endif

    tcg_out_dat_reg(s, COND_AL, ARITH_MOV, TCG_REG_R8,

                    0, addr_reg, SHIFT_IMM_LSR(TARGET_PAGE_BITS));

    tcg_out_dat_imm(s, COND_AL, ARITH_AND,

                    TCG_REG_R0, TCG_REG_R8, CPU_TLB_SIZE - 1);

    tcg_out_dat_reg(s, COND_AL, ARITH_ADD, TCG_REG_R0, TCG_AREG0,

                    TCG_REG_R0, SHIFT_IMM_LSL(CPU_TLB_ENTRY_BITS));

    /* In the

     *  ldr r1 [r0, #(offsetof(CPUState, tlb_table[mem_index][0].addr_read))]

     * below, the offset is likely to exceed 12 bits if mem_index != 0 and

     * not exceed otherwise, so use an

     *  add r0, r0, #(mem_index * sizeof *CPUState.tlb_table)

     * before.

     */

    if (mem_index)

        tcg_out_dat_imm(s, COND_AL, ARITH_ADD, TCG_REG_R0, TCG_REG_R0,

                        (mem_index << (TLB_SHIFT & 1)) |

                        ((16 - (TLB_SHIFT >> 1)) << 8));

    tcg_out_ld32_12(s, COND_AL, TCG_REG_R1, TCG_REG_R0,

                    offsetof(CPUState, tlb_table[0][0].addr_read));

    tcg_out_dat_reg(s, COND_AL, ARITH_CMP, 0, TCG_REG_R1,

                    TCG_REG_R8, SHIFT_IMM_LSL(TARGET_PAGE_BITS));

    /* Check alignment.  */

    if (s_bits)

        tcg_out_dat_imm(s, COND_EQ, ARITH_TST,

                        0, addr_reg, (1 << s_bits) - 1);

#  if TARGET_LONG_BITS == 64

    /* XXX: possibly we could use a block data load or writeback in

     * the first access.  */

    tcg_out_ld32_12(s, COND_EQ, TCG_REG_R1, TCG_REG_R0,

                    offsetof(CPUState, tlb_table[0][0].addr_read) + 4);

    tcg_out_dat_reg(s, COND_EQ, ARITH_CMP, 0,

                    TCG_REG_R1, addr_reg2, SHIFT_IMM_LSL(0));

#  endif

    tcg_out_ld32_12(s, COND_EQ, TCG_REG_R1, TCG_REG_R0,

                    offsetof(CPUState, tlb_table[0][0].addend));

    switch (opc) {

    case 0:

        tcg_out_ld8_r(s, COND_EQ, data_reg, addr_reg, TCG_REG_R1);

        break;

    case 0 | 4:

        tcg_out_ld8s_r(s, COND_EQ, data_reg, addr_reg, TCG_REG_R1);

        break;

    case 1:

        tcg_out_ld16u_r(s, COND_EQ, data_reg, addr_reg, TCG_REG_R1);

        if (bswap) {

            tcg_out_bswap16(s, COND_EQ, data_reg, data_reg);

        }

        break;

    case 1 | 4:

        if (bswap) {

            tcg_out_ld16u_r(s, COND_EQ, data_reg, addr_reg, TCG_REG_R1);

            tcg_out_bswap16s(s, COND_EQ, data_reg, data_reg);

        } else {

            tcg_out_ld16s_r(s, COND_EQ, data_reg, addr_reg, TCG_REG_R1);

        }

        break;

    case 2:

    default:

        tcg_out_ld32_r(s, COND_EQ, data_reg, addr_reg, TCG_REG_R1);

        if (bswap) {

            tcg_out_bswap32(s, COND_EQ, data_reg, data_reg);

        }

        break;

    case 3:

        if (bswap) {

            tcg_out_ld32_rwb(s, COND_EQ, data_reg2, TCG_REG_R1, addr_reg);

            tcg_out_ld32_12(s, COND_EQ, data_reg, TCG_REG_R1, 4);

            tcg_out_bswap32(s, COND_EQ, data_reg2, data_reg2);

            tcg_out_bswap32(s, COND_EQ, data_reg, data_reg);

        } else {

            tcg_out_ld32_rwb(s, COND_EQ, data_reg, TCG_REG_R1, addr_reg);

            tcg_out_ld32_12(s, COND_EQ, data_reg2, TCG_REG_R1, 4);

        }

        break;

    }

    label_ptr = (void *) s->code_ptr;

    tcg_out_b(s, COND_EQ, 8);

    /* TODO: move this code to where the constants pool will be */

    if (addr_reg != TCG_REG_R0) {

        tcg_out_dat_reg(s, COND_AL, ARITH_MOV,

                        TCG_REG_R0, 0, addr_reg, SHIFT_IMM_LSL(0));

    }

# if TARGET_LONG_BITS == 32

    tcg_out_dat_imm(s, COND_AL, ARITH_MOV, TCG_REG_R1, 0, mem_index);

# else

    if (addr_reg2 != TCG_REG_R1) {

        tcg_out_dat_reg(s, COND_AL, ARITH_MOV,

                        TCG_REG_R1, 0, addr_reg2, SHIFT_IMM_LSL(0));

    }

    tcg_out_dat_imm(s, COND_AL, ARITH_MOV, TCG_REG_R2, 0, mem_index);

# endif

    tcg_out_bl(s, COND_AL, (tcg_target_long) qemu_ld_helpers[s_bits] -

                    (tcg_target_long) s->code_ptr);

    switch (opc) {

    case 0 | 4:

        tcg_out_ext8s(s, COND_AL, data_reg, TCG_REG_R0);

        break;

    case 1 | 4:

        tcg_out_ext16s(s, COND_AL, data_reg, TCG_REG_R0);

        break;

    case 0:

    case 1:

    case 2:

    default:

        if (data_reg != TCG_REG_R0) {

            tcg_out_dat_reg(s, COND_AL, ARITH_MOV,

                            data_reg, 0, TCG_REG_R0, SHIFT_IMM_LSL(0));

        }

        break;

    case 3:

        if (data_reg != TCG_REG_R0) {

            tcg_out_dat_reg(s, COND_AL, ARITH_MOV,

                            data_reg, 0, TCG_REG_R0, SHIFT_IMM_LSL(0));

        }

        if (data_reg2 != TCG_REG_R1) {

            tcg_out_dat_reg(s, COND_AL, ARITH_MOV,

                            data_reg2, 0, TCG_REG_R1, SHIFT_IMM_LSL(0));

        }

        break;

    }

    *label_ptr += ((void *) s->code_ptr - (void *) label_ptr - 8) >> 2;

#else /* !CONFIG_SOFTMMU */

    if (GUEST_BASE) {

        uint32_t offset = GUEST_BASE;

        int i;

        int rot;

        while (offset) {

            i = ctz32(offset) & ~1;

            rot = ((32 - i) << 7) & 0xf00;

            tcg_out_dat_imm(s, COND_AL, ARITH_ADD, TCG_REG_R8, addr_reg,

                            ((offset >> i) & 0xff) | rot);

            addr_reg = TCG_REG_R8;

            offset &= ~(0xff << i);

        }

    }

    switch (opc) {

    case 0:

        tcg_out_ld8_12(s, COND_AL, data_reg, addr_reg, 0);

        break;

    case 0 | 4:

        tcg_out_ld8s_8(s, COND_AL, data_reg, addr_reg, 0);

        break;

    case 1:

        tcg_out_ld16u_8(s, COND_AL, data_reg, addr_reg, 0);

        if (bswap) {

            tcg_out_bswap16(s, COND_AL, data_reg, data_reg);

        }

        break;

    case 1 | 4:

        if (bswap) {

            tcg_out_ld16u_8(s, COND_AL, data_reg, addr_reg, 0);

            tcg_out_bswap16s(s, COND_AL, data_reg, data_reg);

        } else {

            tcg_out_ld16s_8(s, COND_AL, data_reg, addr_reg, 0);

        }

        break;

    case 2:

    default:

        tcg_out_ld32_12(s, COND_AL, data_reg, addr_reg, 0);

        if (bswap) {

            tcg_out_bswap32(s, COND_AL, data_reg, data_reg);

        }

        break;

    case 3:

        /* TODO: use block load -

         * check that data_reg2 > data_reg or the other way */

        if (data_reg == addr_reg) {

            tcg_out_ld32_12(s, COND_AL, data_reg2, addr_reg, bswap ? 0 : 4);

            tcg_out_ld32_12(s, COND_AL, data_reg, addr_reg, bswap ? 4 : 0);

        } else {

            tcg_out_ld32_12(s, COND_AL, data_reg, addr_reg, bswap ? 4 : 0);

            tcg_out_ld32_12(s, COND_AL, data_reg2, addr_reg, bswap ? 0 : 4);

        }

        if (bswap) {

            tcg_out_bswap32(s, COND_AL, data_reg, data_reg);

            tcg_out_bswap32(s, COND_AL, data_reg2, data_reg2);

        }

        break;

    }

#endif

}


static void gen_spr_403 (CPUPPCState *env)

{

    /* MMU */

    spr_register(env, SPR_403_PBL1,  "PBL1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_403_pbr, &spr_write_403_pbr,

                 0x00000000);

    spr_register(env, SPR_403_PBU1,  "PBU1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_403_pbr, &spr_write_403_pbr,

                 0x00000000);

    spr_register(env, SPR_403_PBL2,  "PBL2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_403_pbr, &spr_write_403_pbr,

                 0x00000000);

    spr_register(env, SPR_403_PBU2,  "PBU2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_403_pbr, &spr_write_403_pbr,

                 0x00000000);

    /* Debug */

    /* XXX : not implemented */

    spr_register(env, SPR_40x_DAC2, "DAC2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_40x_IAC2, "IAC2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

}


static gnutls_certificate_credentials_t vnc_tls_initialize_x509_cred(VncState *vs)

{

    gnutls_certificate_credentials_t x509_cred;

    int ret;

    if (!vs->vd->x509cacert) {

	VNC_DEBUG("No CA x509 certificate specified\n");

	return NULL;

    }

    if (!vs->vd->x509cert) {

	VNC_DEBUG("No server x509 certificate specified\n");

	return NULL;

    }

    if (!vs->vd->x509key) {

	VNC_DEBUG("No server private key specified\n");

	return NULL;

    }

    if ((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0) {

	VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));

	return NULL;

    }

    if ((ret = gnutls_certificate_set_x509_trust_file(x509_cred,

						      vs->vd->x509cacert,

						      GNUTLS_X509_FMT_PEM)) < 0) {

	VNC_DEBUG("Cannot load CA certificate %s\n", gnutls_strerror(ret));

	gnutls_certificate_free_credentials(x509_cred);

	return NULL;

    }

    if ((ret = gnutls_certificate_set_x509_key_file (x509_cred,

						     vs->vd->x509cert,

						     vs->vd->x509key,

						     GNUTLS_X509_FMT_PEM)) < 0) {

	VNC_DEBUG("Cannot load certificate & key %s\n", gnutls_strerror(ret));

	gnutls_certificate_free_credentials(x509_cred);

	return NULL;

    }

    if (vs->vd->x509cacrl) {

	if ((ret = gnutls_certificate_set_x509_crl_file(x509_cred,

							vs->vd->x509cacrl,

							GNUTLS_X509_FMT_PEM)) < 0) {

	    VNC_DEBUG("Cannot load CRL %s\n", gnutls_strerror(ret));

	    gnutls_certificate_free_credentials(x509_cred);

	    return NULL;

	}

    }

    gnutls_certificate_set_dh_params (x509_cred, dh_params);

    return x509_cred;

}


CPUState *ppc440ep_init(ram_addr_t *ram_size, PCIBus **pcip,

                        const unsigned int pci_irq_nrs[4], int do_init,

                        const char *cpu_model)

{

    target_phys_addr_t ram_bases[PPC440EP_SDRAM_NR_BANKS];

    target_phys_addr_t ram_sizes[PPC440EP_SDRAM_NR_BANKS];

    CPUState *env;

    qemu_irq *pic;

    qemu_irq *irqs;

    qemu_irq *pci_irqs;

    if (cpu_model == NULL) {

        cpu_model = "440-Xilinx"; // XXX: should be 440EP

    }

    env = cpu_init(cpu_model);

    if (!env) {

        fprintf(stderr, "Unable to initialize CPU!\n");

        exit(1);

    }

    ppc_dcr_init(env, NULL, NULL);

    /* interrupt controller */

    irqs = g_malloc0(sizeof(qemu_irq) * PPCUIC_OUTPUT_NB);

    irqs[PPCUIC_OUTPUT_INT] = ((qemu_irq *)env->irq_inputs)[PPC40x_INPUT_INT];

    irqs[PPCUIC_OUTPUT_CINT] = ((qemu_irq *)env->irq_inputs)[PPC40x_INPUT_CINT];

    pic = ppcuic_init(env, irqs, 0x0C0, 0, 1);

    /* SDRAM controller */

    memset(ram_bases, 0, sizeof(ram_bases));

    memset(ram_sizes, 0, sizeof(ram_sizes));

    *ram_size = ppc4xx_sdram_adjust(*ram_size, PPC440EP_SDRAM_NR_BANKS,

                                    ram_bases, ram_sizes,

                                    ppc440ep_sdram_bank_sizes);

    /* XXX 440EP's ECC interrupts are on UIC1, but we've only created UIC0. */

    ppc4xx_sdram_init(env, pic[14], PPC440EP_SDRAM_NR_BANKS, ram_bases,

                      ram_sizes, do_init);

    /* PCI */

    pci_irqs = g_malloc(sizeof(qemu_irq) * 4);

    pci_irqs[0] = pic[pci_irq_nrs[0]];

    pci_irqs[1] = pic[pci_irq_nrs[1]];

    pci_irqs[2] = pic[pci_irq_nrs[2]];

    pci_irqs[3] = pic[pci_irq_nrs[3]];

    *pcip = ppc4xx_pci_init(env, pci_irqs,

                            PPC440EP_PCI_CONFIG,

                            PPC440EP_PCI_INTACK,

                            PPC440EP_PCI_SPECIAL,

                            PPC440EP_PCI_REGS);

    if (!*pcip)

        printf("couldn't create PCI controller!\n");

    isa_mmio_init(PPC440EP_PCI_IO, PPC440EP_PCI_IOLEN);

    if (serial_hds[0] != NULL) {

        serial_mm_init(0xef600300, 0, pic[0], PPC_SERIAL_MM_BAUDBASE,

                       serial_hds[0], 1, 1);

    }

    if (serial_hds[1] != NULL) {

        serial_mm_init(0xef600400, 0, pic[1], PPC_SERIAL_MM_BAUDBASE,

                       serial_hds[1], 1, 1);

    }

    return env;

}


void *cpu_register_map_client(void *opaque, void (*callback)(void *opaque))

{

    MapClient *client = g_malloc(sizeof(*client));

    qemu_mutex_lock(&map_client_list_lock);

    client->opaque = opaque;

    client->callback = callback;

    QLIST_INSERT_HEAD(&map_client_list, client, link);

    if (!atomic_read(&bounce.in_use)) {

        cpu_notify_map_clients_locked();

    }

    qemu_mutex_unlock(&map_client_list_lock);

    return client;

}


static int svag_read_header(AVFormatContext *s)

{

    unsigned size, align;

    AVStream *st;

    avio_skip(s->pb, 4);

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    size                   = avio_rl32(s->pb);

    st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;

    st->codec->codec_id    = AV_CODEC_ID_ADPCM_PSX;

    st->codec->sample_rate = avio_rl32(s->pb);

    if (st->codec->sample_rate <= 0)

        return AVERROR_INVALIDDATA;

    st->codec->channels    = avio_rl32(s->pb);

    if (st->codec->channels <= 0)

        return AVERROR_INVALIDDATA;

    st->duration           = size / (16 * st->codec->channels) * 28;

    align                  = avio_rl32(s->pb);

    if (align <= 0 || align > INT_MAX / st->codec->channels)

        return AVERROR_INVALIDDATA;

    st->codec->block_align = align * st->codec->channels;

    avio_skip(s->pb, 0x800 - avio_tell(s->pb));

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

    return 0;

}


int ff_mpeg_update_thread_context(AVCodecContext *dst,
                                  const AVCodecContext *src)
{
    int i;
    MpegEncContext *s = dst->priv_data, *s1 = src->priv_data;
    if (dst == src || !s1->context_initialized)
        return 0;
    // FIXME can parameters change on I-frames?
    // in that case dst may need a reinit
    if (!s->context_initialized) {
        memcpy(s, s1, sizeof(MpegEncContext));
        s->avctx                 = dst;
        s->picture_range_start  += MAX_PICTURE_COUNT;
        s->picture_range_end    += MAX_PICTURE_COUNT;
        s->bitstream_buffer      = NULL;
        s->bitstream_buffer_size = s->allocated_bitstream_buffer_size = 0;
        ff_MPV_common_init(s);
    }
    if (s->height != s1->height || s->width != s1->width || s->context_reinit) {
        int err;
        s->context_reinit = 0;
        s->height = s1->height;
        s->width  = s1->width;
        if ((err = ff_MPV_common_frame_size_change(s)) < 0)
            return err;
    }
    s->avctx->coded_height  = s1->avctx->coded_height;
    s->avctx->coded_width   = s1->avctx->coded_width;
    s->avctx->width         = s1->avctx->width;
    s->avctx->height        = s1->avctx->height;
    s->coded_picture_number = s1->coded_picture_number;
    s->picture_number       = s1->picture_number;
    s->input_picture_number = s1->input_picture_number;
    memcpy(s->picture, s1->picture, s1->picture_count * sizeof(Picture));
    memcpy(&s->last_picture, &s1->last_picture,
           (char *) &s1->last_picture_ptr - (char *) &s1->last_picture);
    s->last_picture_ptr    = REBASE_PICTURE(s1->last_picture_ptr,    s, s1);
    s->current_picture_ptr = REBASE_PICTURE(s1->current_picture_ptr, s, s1);
    s->next_picture_ptr    = REBASE_PICTURE(s1->next_picture_ptr,    s, s1);
    // Error/bug resilience
    s->next_p_frame_damaged = s1->next_p_frame_damaged;
    s->workaround_bugs      = s1->workaround_bugs;
    // MPEG4 timing info
    memcpy(&s->time_increment_bits, &s1->time_increment_bits,
           (char *) &s1->shape - (char *) &s1->time_increment_bits);
    // B-frame info
    s->max_b_frames = s1->max_b_frames;
    s->low_delay    = s1->low_delay;
    s->dropable     = s1->dropable;
    // DivX handling (doesn't work)
    s->divx_packed  = s1->divx_packed;
    if (s1->bitstream_buffer) {
        if (s1->bitstream_buffer_size +
            FF_INPUT_BUFFER_PADDING_SIZE > s->allocated_bitstream_buffer_size)
            av_fast_malloc(&s->bitstream_buffer,
                           &s->allocated_bitstream_buffer_size,
                           s1->allocated_bitstream_buffer_size);
            s->bitstream_buffer_size = s1->bitstream_buffer_size;
        memcpy(s->bitstream_buffer, s1->bitstream_buffer,
               s1->bitstream_buffer_size);
        memset(s->bitstream_buffer + s->bitstream_buffer_size, 0,
               FF_INPUT_BUFFER_PADDING_SIZE);
    }
    // MPEG2/interlacing info
    memcpy(&s->progressive_sequence, &s1->progressive_sequence,
           (char *) &s1->rtp_mode - (char *) &s1->progressive_sequence);
    if (!s1->first_field) {
        s->last_pict_type = s1->pict_type;
        if (s1->current_picture_ptr)
            s->last_lambda_for[s1->pict_type] = s1->current_picture_ptr->f.quality;
        if (s1->pict_type != AV_PICTURE_TYPE_B) {
            s->last_non_b_pict_type = s1->pict_type;
        }
    }
    return 0;
}


static void encode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h, int stride[3]){

    int x, y, p, i;

    const int ring_size= s->avctx->context_model ? 3 : 2;

    int16_t *sample[4][3];

    int lbd=  s->avctx->bits_per_raw_sample <= 8;

    int bits= s->avctx->bits_per_raw_sample > 0 ? s->avctx->bits_per_raw_sample : 8;

    int offset= 1 << bits;

    s->run_index=0;

    memset(s->sample_buffer, 0, ring_size*4*(w+6)*sizeof(*s->sample_buffer));

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

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

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

                sample[p][i]= s->sample_buffer + p*ring_size*(w+6) + ((h+i-y)%ring_size)*(w+6) + 3;

        for(x=0; x<w; x++){

            int b,g,r,a;

            if(lbd){

                unsigned v= *((uint32_t*)(src[0] + x*4 + stride[0]*y));

                b= v&0xFF;

                g= (v>>8)&0xFF;

                r= (v>>16)&0xFF;

                a=  v>>24;

            }else{

                b= *((uint16_t*)(src[0] + x*2 + stride[0]*y));

                g= *((uint16_t*)(src[1] + x*2 + stride[1]*y));

                r= *((uint16_t*)(src[2] + x*2 + stride[2]*y));

            }

            b -= g;

            r -= g;

            g += (b + r)>>2;

            b += offset;

            r += offset;

//            assert(g>=0 && b>=0 && r>=0);

//            assert(g<256 && b<512 && r<512);

            sample[0][0][x]= g;

            sample[1][0][x]= b;

            sample[2][0][x]= r;

            sample[3][0][x]= a;

        }

        for(p=0; p<3 + s->transparency; p++){

            sample[p][0][-1]= sample[p][1][0  ];

            sample[p][1][ w]= sample[p][1][w-1];

            if (lbd)

                encode_line(s, w, sample[p], (p+1)/2, 9);

            else

                encode_line(s, w, sample[p], (p+1)/2, bits+1);

        }

    }

}


static void test_flush(void)

{

    QPCIDevice *dev;

    QPCIBar bmdma_bar, ide_bar;

    uint8_t data;

    ide_test_start(

        "-drive file=blkdebug::%s,if=ide,cache=writeback,format=raw",

        tmp_path);

    dev = get_pci_device(&bmdma_bar, &ide_bar);

    qtest_irq_intercept_in(global_qtest, "ioapic");

    /* Dirty media so that CMD_FLUSH_CACHE will actually go to disk */

    make_dirty(0);

    /* Delay the completion of the flush request until we explicitly do it */

    g_free(hmp("qemu-io ide0-hd0 \"break flush_to_os A\""));

    /* FLUSH CACHE command on device 0*/

    qpci_io_writeb(dev, ide_bar, reg_device, 0);

    qpci_io_writeb(dev, ide_bar, reg_command, CMD_FLUSH_CACHE);

    /* Check status while request is in flight*/

    data = qpci_io_readb(dev, ide_bar, reg_status);

    assert_bit_set(data, BSY | DRDY);

    assert_bit_clear(data, DF | ERR | DRQ);

    /* Complete the command */

    g_free(hmp("qemu-io ide0-hd0 \"resume A\""));

    /* Check registers */

    data = qpci_io_readb(dev, ide_bar, reg_device);

    g_assert_cmpint(data & DEV, ==, 0);

    do {

        data = qpci_io_readb(dev, ide_bar, reg_status);

    } while (data & BSY);

    assert_bit_set(data, DRDY);

    assert_bit_clear(data, BSY | DF | ERR | DRQ);

    ide_test_quit();

}


static int protocol_client_auth_sasl_start(VncState *vs, uint8_t *data, size_t len)

{

    uint32_t datalen = len;

    const char *serverout;

    unsigned int serveroutlen;

    int err;

    char *clientdata = NULL;

    /* NB, distinction of NULL vs "" is *critical* in SASL */

    if (datalen) {

        clientdata = (char*)data;

        clientdata[datalen-1] = '\0'; /* Should be on wire, but make sure */

        datalen--; /* Don't count NULL byte when passing to _start() */

    }

    VNC_DEBUG("Start SASL auth with mechanism %s. Data %p (%d bytes)\n",

              vs->sasl.mechlist, clientdata, datalen);

    err = sasl_server_start(vs->sasl.conn,

                            vs->sasl.mechlist,

                            clientdata,

                            datalen,

                            &serverout,

                            &serveroutlen);

    if (err != SASL_OK &&

        err != SASL_CONTINUE) {

        VNC_DEBUG("sasl start failed %d (%s)\n",

                  err, sasl_errdetail(vs->sasl.conn));

        sasl_dispose(&vs->sasl.conn);

        vs->sasl.conn = NULL;

        goto authabort;

    }

    if (serveroutlen > SASL_DATA_MAX_LEN) {

        VNC_DEBUG("sasl start reply data too long %d\n",

                  serveroutlen);

        sasl_dispose(&vs->sasl.conn);

        vs->sasl.conn = NULL;

        goto authabort;

    }

    VNC_DEBUG("SASL return data %d bytes, nil; %d\n",

              serveroutlen, serverout ? 0 : 1);

    if (serveroutlen) {

        vnc_write_u32(vs, serveroutlen + 1);

        vnc_write(vs, serverout, serveroutlen + 1);

    } else {

        vnc_write_u32(vs, 0);

    }

    /* Whether auth is complete */

    vnc_write_u8(vs, err == SASL_CONTINUE ? 0 : 1);

    if (err == SASL_CONTINUE) {

        VNC_DEBUG("%s", "Authentication must continue\n");

        /* Wait for step length */

        vnc_read_when(vs, protocol_client_auth_sasl_step_len, 4);

    } else {

        if (!vnc_auth_sasl_check_ssf(vs)) {

            VNC_DEBUG("Authentication rejected for weak SSF %p\n", vs->ioc);

            goto authreject;

        }

        /* Check username whitelist ACL */

        if (vnc_auth_sasl_check_access(vs) < 0) {

            VNC_DEBUG("Authentication rejected for ACL %p\n", vs->ioc);

            goto authreject;

        }

        VNC_DEBUG("Authentication successful %p\n", vs->ioc);

        vnc_write_u32(vs, 0); /* Accept auth */

        start_client_init(vs);

    }

    return 0;

 authreject:

    vnc_write_u32(vs, 1); /* Reject auth */

    vnc_write_u32(vs, sizeof("Authentication failed"));

    vnc_write(vs, "Authentication failed", sizeof("Authentication failed"));

    vnc_flush(vs);

    vnc_client_error(vs);

    return -1;

 authabort:

    vnc_client_error(vs);

    return -1;

}


static int decode_init(AVCodecContext * avctx)

{

    MPADecodeContext *s = avctx->priv_data;

    static int init=0;

    int i, j, k;

#if defined(USE_HIGHPRECISION) && defined(CONFIG_AUDIO_NONSHORT)

    avctx->sample_fmt= SAMPLE_FMT_S32;

#else

    avctx->sample_fmt= SAMPLE_FMT_S16;

#endif

    if(avctx->antialias_algo != FF_AA_FLOAT)

        s->compute_antialias= compute_antialias_integer;

    else

        s->compute_antialias= compute_antialias_float;

    if (!init && !avctx->parse_only) {

        /* scale factors table for layer 1/2 */

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

            int shift, mod;

            /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */

            shift = (i / 3);

            mod = i % 3;

            scale_factor_modshift[i] = mod | (shift << 2);

        }

        /* scale factor multiply for layer 1 */

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

            int n, norm;

            n = i + 2;

            norm = ((int64_t_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);

            scale_factor_mult[i][0] = MULL(FIXR(1.0 * 2.0), norm);

            scale_factor_mult[i][1] = MULL(FIXR(0.7937005259 * 2.0), norm);

            scale_factor_mult[i][2] = MULL(FIXR(0.6299605249 * 2.0), norm);

            dprintf("%d: norm=%x s=%x %x %x\n",

                    i, norm,

                    scale_factor_mult[i][0],

                    scale_factor_mult[i][1],

                    scale_factor_mult[i][2]);

        }

	ff_mpa_synth_init(window);

        /* huffman decode tables */

        huff_code_table[0] = NULL;

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

            const HuffTable *h = &mpa_huff_tables[i];

	    int xsize, x, y;

            unsigned int n;

            uint8_t *code_table;

            xsize = h->xsize;

            n = xsize * xsize;

            /* XXX: fail test */

            init_vlc(&huff_vlc[i], 8, n,

                     h->bits, 1, 1, h->codes, 2, 2, 1);

            code_table = av_mallocz(n);

            j = 0;

            for(x=0;x<xsize;x++) {

                for(y=0;y<xsize;y++)

                    code_table[j++] = (x << 4) | y;

            }

            huff_code_table[i] = code_table;

        }

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

            init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,

                     mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1, 1);

        }

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

            k = 0;

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

                band_index_long[i][j] = k;

                k += band_size_long[i][j];

            }

            band_index_long[i][22] = k;

        }

	/* compute n ^ (4/3) and store it in mantissa/exp format */

	table_4_3_exp= av_mallocz_static(TABLE_4_3_SIZE * sizeof(table_4_3_exp[0]));

        if(!table_4_3_exp)

	    return -1;

	table_4_3_value= av_mallocz_static(TABLE_4_3_SIZE * sizeof(table_4_3_value[0]));

        if(!table_4_3_value)

            return -1;

        int_pow_init();

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

            double f, fm;

            int e, m;

            f = pow((double)(i/4), 4.0 / 3.0) * pow(2, (i&3)*0.25);

            fm = frexp(f, &e);

            m = FIXHR(fm*0.5);

            e+= FRAC_BITS - 31;

            /* normalized to FRAC_BITS */

            table_4_3_value[i] = m;

//            av_log(NULL, AV_LOG_DEBUG, "%d %d %f\n", i, m, pow((double)i, 4.0 / 3.0));

            table_4_3_exp[i] = -e;

        }

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

            float f;

            int v;

            if (i != 6) {

                f = tan((double)i * M_PI / 12.0);

                v = FIXR(f / (1.0 + f));

            } else {

                v = FIXR(1.0);

            }

            is_table[0][i] = v;

            is_table[1][6 - i] = v;

        }

        /* invalid values */

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

            is_table[0][i] = is_table[1][i] = 0.0;

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

            double f;

            int e, k;

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

                e = -(j + 1) * ((i + 1) >> 1);

                f = pow(2.0, e / 4.0);

                k = i & 1;

                is_table_lsf[j][k ^ 1][i] = FIXR(f);

                is_table_lsf[j][k][i] = FIXR(1.0);

                dprintf("is_table_lsf %d %d: %x %x\n",

                        i, j, is_table_lsf[j][0][i], is_table_lsf[j][1][i]);

            }

        }

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

            float ci, cs, ca;

            ci = ci_table[i];

            cs = 1.0 / sqrt(1.0 + ci * ci);

            ca = cs * ci;

            csa_table[i][0] = FIXHR(cs/4);

            csa_table[i][1] = FIXHR(ca/4);

            csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);

            csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);

            csa_table_float[i][0] = cs;

            csa_table_float[i][1] = ca;

            csa_table_float[i][2] = ca + cs;

            csa_table_float[i][3] = ca - cs;

//            printf("%d %d %d %d\n", FIX(cs), FIX(cs-1), FIX(ca), FIX(cs)-FIX(ca));

//            av_log(NULL, AV_LOG_DEBUG,"%f %f %f %f\n", cs, ca, ca+cs, ca-cs);

        }

        /* compute mdct windows */

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

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

                double d;

                if(j==2 && i%3 != 1)

                    continue;

                d= sin(M_PI * (i + 0.5) / 36.0);

                if(j==1){

                    if     (i>=30) d= 0;

                    else if(i>=24) d= sin(M_PI * (i - 18 + 0.5) / 12.0);

                    else if(i>=18) d= 1;

                }else if(j==3){

                    if     (i<  6) d= 0;

                    else if(i< 12) d= sin(M_PI * (i -  6 + 0.5) / 12.0);

                    else if(i< 18) d= 1;

                }

                //merge last stage of imdct into the window coefficients

                d*= 0.5 / cos(M_PI*(2*i + 19)/72);

                if(j==2)

                    mdct_win[j][i/3] = FIXHR((d / (1<<5)));

                else

                    mdct_win[j][i  ] = FIXHR((d / (1<<5)));

//                av_log(NULL, AV_LOG_DEBUG, "%2d %d %f\n", i,j,d / (1<<5));

            }

        }

        /* NOTE: we do frequency inversion adter the MDCT by changing

           the sign of the right window coefs */

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

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

                mdct_win[j + 4][i] = mdct_win[j][i];

                mdct_win[j + 4][i + 1] = -mdct_win[j][i + 1];

            }

        }

#if defined(DEBUG)

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

            printf("win%d=\n", j);

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

                printf("%f, ", (double)mdct_win[j][i] / FRAC_ONE);

            printf("\n");

        }

#endif

        init = 1;

    }

    s->inbuf_index = 0;

    s->inbuf = &s->inbuf1[s->inbuf_index][BACKSTEP_SIZE];

    s->inbuf_ptr = s->inbuf;

#ifdef DEBUG

    s->frame_count = 0;

#endif

    if (avctx->codec_id == CODEC_ID_MP3ADU)

        s->adu_mode = 1;

    return 0;

}


static int init_muxer(AVFormatContext *s, AVDictionary **options)

{

    int ret = 0, i;

    AVStream *st;

    AVDictionary *tmp = NULL;

    AVCodecParameters *par = NULL;

    AVOutputFormat *of = s->oformat;

    const AVCodecDescriptor *desc;

    AVDictionaryEntry *e;

    if (options)

        av_dict_copy(&tmp, *options, 0);

    if ((ret = av_opt_set_dict(s, &tmp)) < 0)

        goto fail;

    if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&

        (ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)

        goto fail;

#if FF_API_LAVF_AVCTX

FF_DISABLE_DEPRECATION_WARNINGS

    if (s->nb_streams && s->streams[0]->codec->flags & AV_CODEC_FLAG_BITEXACT) {

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

#if FF_API_LAVF_BITEXACT

            av_log(s, AV_LOG_WARNING,

                   "Setting the AVFormatContext to bitexact mode, because "

                   "the AVCodecContext is in that mode. This behavior will "

                   "change in the future. To keep the current behavior, set "

                   "AVFormatContext.flags |= AVFMT_FLAG_BITEXACT.\n");

            s->flags |= AVFMT_FLAG_BITEXACT;

#else

            av_log(s, AV_LOG_WARNING,

                   "The AVFormatContext is not in set to bitexact mode, only "

                   "the AVCodecContext. If this is not intended, set "

                   "AVFormatContext.flags |= AVFMT_FLAG_BITEXACT.\n");

#endif

        }

    }

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    // some sanity checks

    if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {

        av_log(s, AV_LOG_ERROR, "No streams to mux were specified\n");

        ret = AVERROR(EINVAL);

        goto fail;

    }

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

        st  = s->streams[i];

        par = st->codecpar;

#if FF_API_LAVF_CODEC_TB

FF_DISABLE_DEPRECATION_WARNINGS

        if (!st->time_base.num && st->codec->time_base.num) {

            av_log(s, AV_LOG_WARNING, "Using AVStream.codec.time_base as a "

                   "timebase hint to the muxer is deprecated. Set "

                   "AVStream.time_base instead.\n");

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

        }

FF_ENABLE_DEPRECATION_WARNINGS

#endif

#if FF_API_LAVF_AVCTX

FF_DISABLE_DEPRECATION_WARNINGS

        if (st->codecpar->codec_type == AVMEDIA_TYPE_UNKNOWN &&

            st->codec->codec_type    != AVMEDIA_TYPE_UNKNOWN) {

            av_log(s, AV_LOG_WARNING, "Using AVStream.codec to pass codec "

                   "parameters to muxers is deprecated, use AVStream.codecpar "

                   "instead.\n");

            ret = avcodec_parameters_from_context(st->codecpar, st->codec);

            if (ret < 0)

                goto fail;

        }

FF_ENABLE_DEPRECATION_WARNINGS

#endif

        /* update internal context from codecpar, old bsf api needs this

         * FIXME: remove when autobsf uses new bsf API */

        ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);

        if (ret < 0)

            goto fail;

        if (!st->time_base.num) {

            /* fall back on the default timebase values */

            if (par->codec_type == AVMEDIA_TYPE_AUDIO && par->sample_rate)

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

            else

                avpriv_set_pts_info(st, 33, 1, 90000);

        }

        switch (par->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            if (par->sample_rate <= 0) {

                av_log(s, AV_LOG_ERROR, "sample rate not set\n");

                ret = AVERROR(EINVAL);

                goto fail;

            }

            if (!par->block_align)

                par->block_align = par->channels *

                                   av_get_bits_per_sample(par->codec_id) >> 3;

            break;

        case AVMEDIA_TYPE_VIDEO:

            if ((par->width <= 0 || par->height <= 0) &&

                !(of->flags & AVFMT_NODIMENSIONS)) {

                av_log(s, AV_LOG_ERROR, "dimensions not set\n");

                ret = AVERROR(EINVAL);

                goto fail;

            }

            if (av_cmp_q(st->sample_aspect_ratio, par->sample_aspect_ratio)

                && fabs(av_q2d(st->sample_aspect_ratio) - av_q2d(par->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)

            ) {

                if (st->sample_aspect_ratio.num != 0 &&

                    st->sample_aspect_ratio.den != 0 &&

                    par->sample_aspect_ratio.num != 0 &&

                    par->sample_aspect_ratio.den != 0) {

                    av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "

                           "(%d/%d) and encoder layer (%d/%d)\n",

                           st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,

                           par->sample_aspect_ratio.num,

                           par->sample_aspect_ratio.den);

                    ret = AVERROR(EINVAL);

                    goto fail;

                }

            }

            break;

        }

        desc = avcodec_descriptor_get(par->codec_id);

        if (desc && desc->props & AV_CODEC_PROP_REORDER)

            st->internal->reorder = 1;

        if (of->codec_tag) {

            if (   par->codec_tag

                && par->codec_id == AV_CODEC_ID_RAWVIDEO

                && (   av_codec_get_tag(of->codec_tag, par->codec_id) == 0

                    || av_codec_get_tag(of->codec_tag, par->codec_id) == MKTAG('r', 'a', 'w', ' '))

                && !validate_codec_tag(s, st)) {

                // the current rawvideo encoding system ends up setting

                // the wrong codec_tag for avi/mov, we override it here

                par->codec_tag = 0;

            }

            if (par->codec_tag) {

                if (!validate_codec_tag(s, st)) {

                    char tagbuf[32], tagbuf2[32];

                    av_get_codec_tag_string(tagbuf, sizeof(tagbuf), par->codec_tag);

                    av_get_codec_tag_string(tagbuf2, sizeof(tagbuf2), av_codec_get_tag(s->oformat->codec_tag, par->codec_id));

                    av_log(s, AV_LOG_ERROR,

                           "Tag %s/0x%08x incompatible with output codec id '%d' (%s)\n",

                           tagbuf, par->codec_tag, par->codec_id, tagbuf2);

                    ret = AVERROR_INVALIDDATA;

                    goto fail;

                }

            } else

                par->codec_tag = av_codec_get_tag(of->codec_tag, par->codec_id);

        }

        if (par->codec_type != AVMEDIA_TYPE_ATTACHMENT)

            s->internal->nb_interleaved_streams++;

    }

    if (!s->priv_data && of->priv_data_size > 0) {

        s->priv_data = av_mallocz(of->priv_data_size);

        if (!s->priv_data) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        if (of->priv_class) {

            *(const AVClass **)s->priv_data = of->priv_class;

            av_opt_set_defaults(s->priv_data);

            if ((ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)

                goto fail;

        }

    }

    /* set muxer identification string */

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

        av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);

    } else {

        av_dict_set(&s->metadata, "encoder", NULL, 0);

    }

    for (e = NULL; e = av_dict_get(s->metadata, "encoder-", e, AV_DICT_IGNORE_SUFFIX); ) {

        av_dict_set(&s->metadata, e->key, NULL, 0);

    }

    if (options) {

         av_dict_free(options);

         *options = tmp;

    }

    if (s->oformat->init && (ret = s->oformat->init(s)) < 0) {

        s->oformat->deinit(s);

        goto fail;

    }

    return 0;

fail:

    av_dict_free(&tmp);

    return ret;

}


static void qtest_irq_handler(void *opaque, int n, int level)

{

    qemu_irq old_irq = *(qemu_irq *)opaque;

    qemu_set_irq(old_irq, level);

    if (irq_levels[n] != level) {

        CharDriverState *chr = qtest_chr;

        irq_levels[n] = level;

        qtest_send_prefix(chr);

        qtest_send(chr, "IRQ %s %d\n",

                   level ? "raise" : "lower", n);

    }

}


void gmc1_altivec(uint8_t *dst /* align 8 */, uint8_t *src /* align1 */, int stride, int h, int x16, int y16, int rounder)

{

POWERPC_TBL_DECLARE(altivec_gmc1_num, GMC1_PERF_COND);

#ifdef ALTIVEC_USE_REFERENCE_C_CODE

    const int A=(16-x16)*(16-y16);

    const int B=(   x16)*(16-y16);

    const int C=(16-x16)*(   y16);

    const int D=(   x16)*(   y16);

    int i;

POWERPC_TBL_START_COUNT(altivec_gmc1_num, GMC1_PERF_COND);

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

    {

        dst[0]= (A*src[0] + B*src[1] + C*src[stride+0] + D*src[stride+1] + rounder)>>8;

        dst[1]= (A*src[1] + B*src[2] + C*src[stride+1] + D*src[stride+2] + rounder)>>8;

        dst[2]= (A*src[2] + B*src[3] + C*src[stride+2] + D*src[stride+3] + rounder)>>8;

        dst[3]= (A*src[3] + B*src[4] + C*src[stride+3] + D*src[stride+4] + rounder)>>8;

        dst[4]= (A*src[4] + B*src[5] + C*src[stride+4] + D*src[stride+5] + rounder)>>8;

        dst[5]= (A*src[5] + B*src[6] + C*src[stride+5] + D*src[stride+6] + rounder)>>8;

        dst[6]= (A*src[6] + B*src[7] + C*src[stride+6] + D*src[stride+7] + rounder)>>8;

        dst[7]= (A*src[7] + B*src[8] + C*src[stride+7] + D*src[stride+8] + rounder)>>8;

        dst+= stride;

        src+= stride;

    }

POWERPC_TBL_STOP_COUNT(altivec_gmc1_num, GMC1_PERF_COND);

#else /* ALTIVEC_USE_REFERENCE_C_CODE */

    const unsigned short __attribute__ ((aligned(16))) rounder_a[8] =

      {rounder, rounder, rounder, rounder,

       rounder, rounder, rounder, rounder};

    const unsigned short __attribute__ ((aligned(16))) ABCD[8] =

      {

        (16-x16)*(16-y16), /* A */

        (   x16)*(16-y16), /* B */

        (16-x16)*(   y16), /* C */

        (   x16)*(   y16), /* D */

        0, 0, 0, 0         /* padding */

      };

    register const vector unsigned char vczero = (const vector unsigned char)vec_splat_u8(0);

    register const vector unsigned short vcsr8 = (const vector unsigned short)vec_splat_u16(8);

    register vector unsigned char dstv, dstv2, src_0, src_1, srcvA, srcvB, srcvC, srcvD;

    register vector unsigned short Av, Bv, Cv, Dv, rounderV, tempA, tempB, tempC, tempD;

    int i;

    unsigned long dst_odd = (unsigned long)dst & 0x0000000F;

    unsigned long src_really_odd = (unsigned long)src & 0x0000000F;

POWERPC_TBL_START_COUNT(altivec_gmc1_num, GMC1_PERF_COND);

    tempA = vec_ld(0, (unsigned short*)ABCD);

    Av = vec_splat(tempA, 0);

    Bv = vec_splat(tempA, 1);

    Cv = vec_splat(tempA, 2);

    Dv = vec_splat(tempA, 3);

    rounderV = vec_ld(0, (unsigned short*)rounder_a);

    // we'll be able to pick-up our 9 char elements

    // at src from those 32 bytes

    // we load the first batch here, as inside the loop

    // we can re-use 'src+stride' from one iteration

    // as the 'src' of the next.

    src_0 = vec_ld(0, src);

    src_1 = vec_ld(16, src);

    srcvA = vec_perm(src_0, src_1, vec_lvsl(0, src));

    if (src_really_odd != 0x0000000F)

    { // if src & 0xF == 0xF, then (src+1) is properly aligned on the second vector.

      srcvB = vec_perm(src_0, src_1, vec_lvsl(1, src));

    }

    else

    {

      srcvB = src_1;

    }

    srcvA = vec_mergeh(vczero, srcvA);

    srcvB = vec_mergeh(vczero, srcvB);

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

    {

      dst_odd = (unsigned long)dst & 0x0000000F;

      src_really_odd = (((unsigned long)src) + stride) & 0x0000000F;

      dstv = vec_ld(0, dst);

      // we we'll be able to pick-up our 9 char elements

      // at src + stride from those 32 bytes

      // then reuse the resulting 2 vectors srvcC and srcvD

      // as the next srcvA and srcvB

      src_0 = vec_ld(stride + 0, src);

      src_1 = vec_ld(stride + 16, src);

      srcvC = vec_perm(src_0, src_1, vec_lvsl(stride + 0, src));

      if (src_really_odd != 0x0000000F)

      { // if src & 0xF == 0xF, then (src+1) is properly aligned on the second vector.

        srcvD = vec_perm(src_0, src_1, vec_lvsl(stride + 1, src));

      }

      else

      {

        srcvD = src_1;

      }

      srcvC = vec_mergeh(vczero, srcvC);

      srcvD = vec_mergeh(vczero, srcvD);

      // OK, now we (finally) do the math :-)

      // those four instructions replaces 32 int muls & 32 int adds.

      // isn't AltiVec nice ?

      tempA = vec_mladd((vector unsigned short)srcvA, Av, rounderV);

      tempB = vec_mladd((vector unsigned short)srcvB, Bv, tempA);

      tempC = vec_mladd((vector unsigned short)srcvC, Cv, tempB);

      tempD = vec_mladd((vector unsigned short)srcvD, Dv, tempC);

      srcvA = srcvC;

      srcvB = srcvD;

      tempD = vec_sr(tempD, vcsr8);

      dstv2 = vec_pack(tempD, (vector unsigned short)vczero);

      if (dst_odd)

      {

        dstv2 = vec_perm(dstv, dstv2, vcprm(0,1,s0,s1));

      }

      else

      {

        dstv2 = vec_perm(dstv, dstv2, vcprm(s0,s1,2,3));

      }

      vec_st(dstv2, 0, dst);

      dst += stride;

      src += stride;

    }

POWERPC_TBL_STOP_COUNT(altivec_gmc1_num, GMC1_PERF_COND);

#endif /* ALTIVEC_USE_REFERENCE_C_CODE */

}


void ff_put_h264_qpel4_mc12_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avc_luma_midh_qrt_4w_msa(src - (2 * stride) - 2, stride, dst, stride, 4, 0);

}


enum AVCodecID avpriv_fmt_v4l2codec(uint32_t v4l2_fmt)

{

    int i;

    for (i = 0; avpriv_fmt_conversion_table[i].codec_id != AV_CODEC_ID_NONE; i++) {

        if (avpriv_fmt_conversion_table[i].v4l2_fmt == v4l2_fmt) {

            return avpriv_fmt_conversion_table[i].codec_id;

        }

    }

    return AV_CODEC_ID_NONE;

}


static int read_sbr_channel_pair_element(AACContext *ac,

                                          SpectralBandReplication *sbr,

                                          GetBitContext *gb)

{

    if (get_bits1(gb))    // bs_data_extra

        skip_bits(gb, 8); // bs_reserved

    if ((sbr->bs_coupling = get_bits1(gb))) {

        if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]))

            return -1;

        copy_sbr_grid(&sbr->data[1], &sbr->data[0]);

        read_sbr_dtdf(sbr, gb, &sbr->data[0]);

        read_sbr_dtdf(sbr, gb, &sbr->data[1]);

        read_sbr_invf(sbr, gb, &sbr->data[0]);

        memcpy(sbr->data[1].bs_invf_mode[1], sbr->data[1].bs_invf_mode[0], sizeof(sbr->data[1].bs_invf_mode[0]));

        memcpy(sbr->data[1].bs_invf_mode[0], sbr->data[0].bs_invf_mode[0], sizeof(sbr->data[1].bs_invf_mode[0]));

        read_sbr_envelope(sbr, gb, &sbr->data[0], 0);

        read_sbr_noise(sbr, gb, &sbr->data[0], 0);

        read_sbr_envelope(sbr, gb, &sbr->data[1], 1);

        read_sbr_noise(sbr, gb, &sbr->data[1], 1);

    } else {

        if (read_sbr_grid(ac, sbr, gb, &sbr->data[0]) ||

            read_sbr_grid(ac, sbr, gb, &sbr->data[1]))

            return -1;

        read_sbr_dtdf(sbr, gb, &sbr->data[0]);

        read_sbr_dtdf(sbr, gb, &sbr->data[1]);

        read_sbr_invf(sbr, gb, &sbr->data[0]);

        read_sbr_invf(sbr, gb, &sbr->data[1]);

        read_sbr_envelope(sbr, gb, &sbr->data[0], 0);

        read_sbr_envelope(sbr, gb, &sbr->data[1], 1);

        read_sbr_noise(sbr, gb, &sbr->data[0], 0);

        read_sbr_noise(sbr, gb, &sbr->data[1], 1);

    }

    if ((sbr->data[0].bs_add_harmonic_flag = get_bits1(gb)))

        get_bits1_vector(gb, sbr->data[0].bs_add_harmonic, sbr->n[1]);

    if ((sbr->data[1].bs_add_harmonic_flag = get_bits1(gb)))

        get_bits1_vector(gb, sbr->data[1].bs_add_harmonic, sbr->n[1]);

    return 0;

}


static av_cold int alac_encode_close(AVCodecContext *avctx)

{

    AlacEncodeContext *s = avctx->priv_data;

    ff_lpc_end(&s->lpc_ctx);

    av_freep(&avctx->extradata);

    avctx->extradata_size = 0;

    av_freep(&avctx->coded_frame);

    return 0;

}


av_cold int ff_mpv_encode_init(AVCodecContext *avctx)

{

    MpegEncContext *s = avctx->priv_data;

    AVCPBProperties *cpb_props;

    int i, ret, format_supported;

    mpv_encode_defaults(s);

    switch (avctx->codec_id) {

    case AV_CODEC_ID_MPEG2VIDEO:

        if (avctx->pix_fmt != AV_PIX_FMT_YUV420P &&

            avctx->pix_fmt != AV_PIX_FMT_YUV422P) {

            av_log(avctx, AV_LOG_ERROR,

                   "only YUV420 and YUV422 are supported\n");

            return -1;

        }

        break;

    case AV_CODEC_ID_MJPEG:

        format_supported = 0;

        /* JPEG color space */

        if (avctx->pix_fmt == AV_PIX_FMT_YUVJ420P ||

            avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||

            (avctx->color_range == AVCOL_RANGE_JPEG &&

             (avctx->pix_fmt == AV_PIX_FMT_YUV420P ||

              avctx->pix_fmt == AV_PIX_FMT_YUV422P)))

            format_supported = 1;

        /* MPEG color space */

        else if (avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL &&

                 (avctx->pix_fmt == AV_PIX_FMT_YUV420P ||

                  avctx->pix_fmt == AV_PIX_FMT_YUV422P))

            format_supported = 1;

        if (!format_supported) {

            av_log(avctx, AV_LOG_ERROR, "colorspace not supported in jpeg\n");

            return -1;

        }

        break;

    default:

        if (avctx->pix_fmt != AV_PIX_FMT_YUV420P) {

            av_log(avctx, AV_LOG_ERROR, "only YUV420 is supported\n");

            return -1;

        }

    }

    switch (avctx->pix_fmt) {

    case AV_PIX_FMT_YUVJ422P:

    case AV_PIX_FMT_YUV422P:

        s->chroma_format = CHROMA_422;

        break;

    case AV_PIX_FMT_YUVJ420P:

    case AV_PIX_FMT_YUV420P:

    default:

        s->chroma_format = CHROMA_420;

        break;

    }

    s->bit_rate = avctx->bit_rate;

    s->width    = avctx->width;

    s->height   = avctx->height;

    if (avctx->gop_size > 600 &&

        avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {

        av_log(avctx, AV_LOG_ERROR,

               "Warning keyframe interval too large! reducing it ...\n");

        avctx->gop_size = 600;

    }

    s->gop_size     = avctx->gop_size;

    s->avctx        = avctx;

    if (avctx->max_b_frames > MAX_B_FRAMES) {

        av_log(avctx, AV_LOG_ERROR, "Too many B-frames requested, maximum "

               "is %d.\n", MAX_B_FRAMES);

    }

    s->max_b_frames = avctx->max_b_frames;

    s->codec_id     = avctx->codec->id;

    s->strict_std_compliance = avctx->strict_std_compliance;

    s->quarter_sample     = (avctx->flags & AV_CODEC_FLAG_QPEL) != 0;

    s->mpeg_quant         = avctx->mpeg_quant;

    s->rtp_mode           = !!avctx->rtp_payload_size;

    s->intra_dc_precision = avctx->intra_dc_precision;

    s->user_specified_pts = AV_NOPTS_VALUE;

    if (s->gop_size <= 1) {

        s->intra_only = 1;

        s->gop_size   = 12;

    } else {

        s->intra_only = 0;

    }

#if FF_API_MOTION_EST

FF_DISABLE_DEPRECATION_WARNINGS

    s->me_method = avctx->me_method;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    /* Fixed QSCALE */

    s->fixed_qscale = !!(avctx->flags & AV_CODEC_FLAG_QSCALE);

#if FF_API_MPV_OPT

    FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->border_masking != 0.0)

        s->border_masking = avctx->border_masking;

    FF_ENABLE_DEPRECATION_WARNINGS

#endif

    s->adaptive_quant = (s->avctx->lumi_masking ||

                         s->avctx->dark_masking ||

                         s->avctx->temporal_cplx_masking ||

                         s->avctx->spatial_cplx_masking  ||

                         s->avctx->p_masking      ||

                         s->border_masking ||

                         (s->mpv_flags & FF_MPV_FLAG_QP_RD)) &&

                        !s->fixed_qscale;

    s->loop_filter = !!(s->avctx->flags & AV_CODEC_FLAG_LOOP_FILTER);

    if (avctx->rc_max_rate && !avctx->rc_buffer_size) {

        av_log(avctx, AV_LOG_ERROR,

               "a vbv buffer size is needed, "

               "for encoding with a maximum bitrate\n");

        return -1;

    }

    if (avctx->rc_min_rate && avctx->rc_max_rate != avctx->rc_min_rate) {

        av_log(avctx, AV_LOG_INFO,

               "Warning min_rate > 0 but min_rate != max_rate isn't recommended!\n");

    }

    if (avctx->rc_min_rate && avctx->rc_min_rate > avctx->bit_rate) {

        av_log(avctx, AV_LOG_ERROR, "bitrate below min bitrate\n");

        return -1;

    }

    if (avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate) {

        av_log(avctx, AV_LOG_INFO, "bitrate above max bitrate\n");

        return -1;

    }

    if (avctx->rc_max_rate &&

        avctx->rc_max_rate == avctx->bit_rate &&

        avctx->rc_max_rate != avctx->rc_min_rate) {

        av_log(avctx, AV_LOG_INFO,

               "impossible bitrate constraints, this will fail\n");

    }

    if (avctx->rc_buffer_size &&

        avctx->bit_rate * (int64_t)avctx->time_base.num >

            avctx->rc_buffer_size * (int64_t)avctx->time_base.den) {

        av_log(avctx, AV_LOG_ERROR, "VBV buffer too small for bitrate\n");

        return -1;

    }

    if (!s->fixed_qscale &&

        avctx->bit_rate * av_q2d(avctx->time_base) >

            avctx->bit_rate_tolerance) {

        av_log(avctx, AV_LOG_ERROR,

               "bitrate tolerance too small for bitrate\n");

        return -1;

    }

    if (s->avctx->rc_max_rate &&

        s->avctx->rc_min_rate == s->avctx->rc_max_rate &&

        (s->codec_id == AV_CODEC_ID_MPEG1VIDEO ||

         s->codec_id == AV_CODEC_ID_MPEG2VIDEO) &&

        90000LL * (avctx->rc_buffer_size - 1) >

            s->avctx->rc_max_rate * 0xFFFFLL) {

        av_log(avctx, AV_LOG_INFO,

               "Warning vbv_delay will be set to 0xFFFF (=VBR) as the "

               "specified vbv buffer is too large for the given bitrate!\n");

    }

    if ((s->avctx->flags & AV_CODEC_FLAG_4MV) && s->codec_id != AV_CODEC_ID_MPEG4 &&

        s->codec_id != AV_CODEC_ID_H263 && s->codec_id != AV_CODEC_ID_H263P &&

        s->codec_id != AV_CODEC_ID_FLV1) {

        av_log(avctx, AV_LOG_ERROR, "4MV not supported by codec\n");

        return -1;

    }

    if (s->obmc && s->avctx->mb_decision != FF_MB_DECISION_SIMPLE) {

        av_log(avctx, AV_LOG_ERROR,

               "OBMC is only supported with simple mb decision\n");

        return -1;

    }

    if (s->quarter_sample && s->codec_id != AV_CODEC_ID_MPEG4) {

        av_log(avctx, AV_LOG_ERROR, "qpel not supported by codec\n");

        return -1;

    }

    if (s->max_b_frames                    &&

        s->codec_id != AV_CODEC_ID_MPEG4      &&

        s->codec_id != AV_CODEC_ID_MPEG1VIDEO &&

        s->codec_id != AV_CODEC_ID_MPEG2VIDEO) {

        av_log(avctx, AV_LOG_ERROR, "b frames not supported by codec\n");

        return -1;

    }

    if ((s->codec_id == AV_CODEC_ID_MPEG4 ||

         s->codec_id == AV_CODEC_ID_H263  ||

         s->codec_id == AV_CODEC_ID_H263P) &&

        (avctx->sample_aspect_ratio.num > 255 ||

         avctx->sample_aspect_ratio.den > 255)) {

        av_log(avctx, AV_LOG_ERROR,

               "Invalid pixel aspect ratio %i/%i, limit is 255/255\n",

               avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);

        return -1;

    }

    if ((s->avctx->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME)) &&

        s->codec_id != AV_CODEC_ID_MPEG4 && s->codec_id != AV_CODEC_ID_MPEG2VIDEO) {

        av_log(avctx, AV_LOG_ERROR, "interlacing not supported by codec\n");

        return -1;

    }

    // FIXME mpeg2 uses that too

    if (s->mpeg_quant && s->codec_id != AV_CODEC_ID_MPEG4) {

        av_log(avctx, AV_LOG_ERROR,

               "mpeg2 style quantization not supported by codec\n");

        return -1;

    }

    if ((s->mpv_flags & FF_MPV_FLAG_CBP_RD) && !avctx->trellis) {

        av_log(avctx, AV_LOG_ERROR, "CBP RD needs trellis quant\n");

        return -1;

    }

    if ((s->mpv_flags & FF_MPV_FLAG_QP_RD) &&

        s->avctx->mb_decision != FF_MB_DECISION_RD) {

        av_log(avctx, AV_LOG_ERROR, "QP RD needs mbd=2\n");

        return -1;

    }

    if (s->avctx->scenechange_threshold < 1000000000 &&

        (s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP)) {

        av_log(avctx, AV_LOG_ERROR,

               "closed gop with scene change detection are not supported yet, "

               "set threshold to 1000000000\n");

        return -1;

    }

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

        if (s->codec_id != AV_CODEC_ID_MPEG2VIDEO) {

            av_log(avctx, AV_LOG_ERROR,

                  "low delay forcing is only available for mpeg2\n");

            return -1;

        }

        if (s->max_b_frames != 0) {

            av_log(avctx, AV_LOG_ERROR,

                   "b frames cannot be used with low delay\n");

            return -1;

        }

    }

    if (s->q_scale_type == 1) {

        if (avctx->qmax > 12) {

            av_log(avctx, AV_LOG_ERROR,

                   "non linear quant only supports qmax <= 12 currently\n");

            return -1;

        }

    }

    if (avctx->slices > 1 &&

        (avctx->codec_id == AV_CODEC_ID_FLV1 || avctx->codec_id == AV_CODEC_ID_H261)) {

        av_log(avctx, AV_LOG_ERROR, "Multiple slices are not supported by this codec\n");

        return AVERROR(EINVAL);

    }

    if (s->avctx->thread_count > 1         &&

        s->codec_id != AV_CODEC_ID_MPEG4      &&

        s->codec_id != AV_CODEC_ID_MPEG1VIDEO &&

        s->codec_id != AV_CODEC_ID_MPEG2VIDEO &&

        (s->codec_id != AV_CODEC_ID_H263P)) {

        av_log(avctx, AV_LOG_ERROR,

               "multi threaded encoding not supported by codec\n");

        return -1;

    }

    if (s->avctx->thread_count < 1) {

        av_log(avctx, AV_LOG_ERROR,

               "automatic thread number detection not supported by codec,"

               "patch welcome\n");

        return -1;

    }

    if (!avctx->time_base.den || !avctx->time_base.num) {

        av_log(avctx, AV_LOG_ERROR, "framerate not set\n");

        return -1;

    }

    if (avctx->b_frame_strategy && (avctx->flags & AV_CODEC_FLAG_PASS2)) {

        av_log(avctx, AV_LOG_INFO,

               "notice: b_frame_strategy only affects the first pass\n");

        avctx->b_frame_strategy = 0;

    }

    i = av_gcd(avctx->time_base.den, avctx->time_base.num);

    if (i > 1) {

        av_log(avctx, AV_LOG_INFO, "removing common factors from framerate\n");

        avctx->time_base.den /= i;

        avctx->time_base.num /= i;

        //return -1;

    }

    if (s->mpeg_quant || s->codec_id == AV_CODEC_ID_MPEG1VIDEO ||

        s->codec_id == AV_CODEC_ID_MPEG2VIDEO || s->codec_id == AV_CODEC_ID_MJPEG) {

        // (a + x * 3 / 8) / x

        s->intra_quant_bias = 3 << (QUANT_BIAS_SHIFT - 3);

        s->inter_quant_bias = 0;

    } else {

        s->intra_quant_bias = 0;

        // (a - x / 4) / x

        s->inter_quant_bias = -(1 << (QUANT_BIAS_SHIFT - 2));

    }

#if FF_API_QUANT_BIAS

FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)

        s->intra_quant_bias = avctx->intra_quant_bias;

    if (avctx->inter_quant_bias != FF_DEFAULT_QUANT_BIAS)

        s->inter_quant_bias = avctx->inter_quant_bias;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    if (avctx->codec_id == AV_CODEC_ID_MPEG4 &&

        s->avctx->time_base.den > (1 << 16) - 1) {

        av_log(avctx, AV_LOG_ERROR,

               "timebase %d/%d not supported by MPEG 4 standard, "

               "the maximum admitted value for the timebase denominator "

               "is %d\n", s->avctx->time_base.num, s->avctx->time_base.den,

               (1 << 16) - 1);

        return -1;

    }

    s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;

    switch (avctx->codec->id) {

    case AV_CODEC_ID_MPEG1VIDEO:

        s->out_format = FMT_MPEG1;

        s->low_delay  = !!(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY);

        avctx->delay  = s->low_delay ? 0 : (s->max_b_frames + 1);

        break;

    case AV_CODEC_ID_MPEG2VIDEO:

        s->out_format = FMT_MPEG1;

        s->low_delay  = !!(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY);

        avctx->delay  = s->low_delay ? 0 : (s->max_b_frames + 1);

        s->rtp_mode   = 1;

        break;

    case AV_CODEC_ID_MJPEG:

        s->out_format = FMT_MJPEG;

        s->intra_only = 1; /* force intra only for jpeg */

        if (!CONFIG_MJPEG_ENCODER ||

            ff_mjpeg_encode_init(s) < 0)

            return -1;

        avctx->delay = 0;

        s->low_delay = 1;

        break;

    case AV_CODEC_ID_H261:

        if (!CONFIG_H261_ENCODER)

            return -1;

        if (ff_h261_get_picture_format(s->width, s->height) < 0) {

            av_log(avctx, AV_LOG_ERROR,

                   "The specified picture size of %dx%d is not valid for the "

                   "H.261 codec.\nValid sizes are 176x144, 352x288\n",

                    s->width, s->height);

            return -1;

        }

        s->out_format = FMT_H261;

        avctx->delay  = 0;

        s->low_delay  = 1;

        s->rtp_mode   = 0; /* Sliced encoding not supported */

        break;

    case AV_CODEC_ID_H263:

        if (!CONFIG_H263_ENCODER)

        return -1;

        if (ff_match_2uint16(ff_h263_format, FF_ARRAY_ELEMS(ff_h263_format),

                             s->width, s->height) == 8) {

            av_log(avctx, AV_LOG_INFO,

                   "The specified picture size of %dx%d is not valid for "

                   "the H.263 codec.\nValid sizes are 128x96, 176x144, "

                   "352x288, 704x576, and 1408x1152."

                   "Try H.263+.\n", s->width, s->height);

            return -1;

        }

        s->out_format = FMT_H263;

        avctx->delay  = 0;

        s->low_delay  = 1;

        break;

    case AV_CODEC_ID_H263P:

        s->out_format = FMT_H263;

        s->h263_plus  = 1;

        /* Fx */

        s->h263_aic        = (avctx->flags & AV_CODEC_FLAG_AC_PRED) ? 1 : 0;

        s->modified_quant  = s->h263_aic;

        s->loop_filter     = (avctx->flags & AV_CODEC_FLAG_LOOP_FILTER) ? 1 : 0;

        s->unrestricted_mv = s->obmc || s->loop_filter || s->umvplus;

        /* /Fx */

        /* These are just to be sure */

        avctx->delay = 0;

        s->low_delay = 1;

        break;

    case AV_CODEC_ID_FLV1:

        s->out_format      = FMT_H263;

        s->h263_flv        = 2; /* format = 1; 11-bit codes */

        s->unrestricted_mv = 1;

        s->rtp_mode  = 0; /* don't allow GOB */

        avctx->delay = 0;

        s->low_delay = 1;

        break;

    case AV_CODEC_ID_RV10:

        s->out_format = FMT_H263;

        avctx->delay  = 0;

        s->low_delay  = 1;

        break;

    case AV_CODEC_ID_RV20:

        s->out_format      = FMT_H263;

        avctx->delay       = 0;

        s->low_delay       = 1;

        s->modified_quant  = 1;

        s->h263_aic        = 1;

        s->h263_plus       = 1;

        s->loop_filter     = 1;

        s->unrestricted_mv = 0;

        break;

    case AV_CODEC_ID_MPEG4:

        s->out_format      = FMT_H263;

        s->h263_pred       = 1;

        s->unrestricted_mv = 1;

        s->low_delay       = s->max_b_frames ? 0 : 1;

        avctx->delay       = s->low_delay ? 0 : (s->max_b_frames + 1);

        break;

    case AV_CODEC_ID_MSMPEG4V2:

        s->out_format      = FMT_H263;

        s->h263_pred       = 1;

        s->unrestricted_mv = 1;

        s->msmpeg4_version = 2;

        avctx->delay       = 0;

        s->low_delay       = 1;

        break;

    case AV_CODEC_ID_MSMPEG4V3:

        s->out_format        = FMT_H263;

        s->h263_pred         = 1;

        s->unrestricted_mv   = 1;

        s->msmpeg4_version   = 3;

        s->flipflop_rounding = 1;

        avctx->delay         = 0;

        s->low_delay         = 1;

        break;

    case AV_CODEC_ID_WMV1:

        s->out_format        = FMT_H263;

        s->h263_pred         = 1;

        s->unrestricted_mv   = 1;

        s->msmpeg4_version   = 4;

        s->flipflop_rounding = 1;

        avctx->delay         = 0;

        s->low_delay         = 1;

        break;

    case AV_CODEC_ID_WMV2:

        s->out_format        = FMT_H263;

        s->h263_pred         = 1;

        s->unrestricted_mv   = 1;

        s->msmpeg4_version   = 5;

        s->flipflop_rounding = 1;

        avctx->delay         = 0;

        s->low_delay         = 1;

        break;

    default:

        return -1;

    }

    avctx->has_b_frames = !s->low_delay;

    s->encoding = 1;

    s->progressive_frame    =

    s->progressive_sequence = !(avctx->flags & (AV_CODEC_FLAG_INTERLACED_DCT |

                                                AV_CODEC_FLAG_INTERLACED_ME) ||

                                s->alternate_scan);

    /* init */

    ff_mpv_idct_init(s);

    if (ff_mpv_common_init(s) < 0)

        return -1;

    if (ARCH_X86)

        ff_mpv_encode_init_x86(s);

    ff_fdctdsp_init(&s->fdsp, avctx);

    ff_me_cmp_init(&s->mecc, avctx);

    ff_mpegvideoencdsp_init(&s->mpvencdsp, avctx);

    ff_pixblockdsp_init(&s->pdsp, avctx);

    ff_qpeldsp_init(&s->qdsp);

    if (s->msmpeg4_version) {

        FF_ALLOCZ_OR_GOTO(s->avctx, s->ac_stats,

                          2 * 2 * (MAX_LEVEL + 1) *

                          (MAX_RUN + 1) * 2 * sizeof(int), fail);

    }

    FF_ALLOCZ_OR_GOTO(s->avctx, s->avctx->stats_out, 256, fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->q_intra_matrix,   64 * 32 * sizeof(int), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->q_inter_matrix,   64 * 32 * sizeof(int), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->q_intra_matrix16, 64 * 32 * 2 * sizeof(uint16_t), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->q_inter_matrix16, 64 * 32 * 2 * sizeof(uint16_t), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->input_picture,

                      MAX_PICTURE_COUNT * sizeof(Picture *), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->reordered_input_picture,

                      MAX_PICTURE_COUNT * sizeof(Picture *), fail);

    if (s->avctx->noise_reduction) {

        FF_ALLOCZ_OR_GOTO(s->avctx, s->dct_offset,

                          2 * 64 * sizeof(uint16_t), fail);

    }

    if (CONFIG_H263_ENCODER)

        ff_h263dsp_init(&s->h263dsp);

    if (!s->dct_quantize)

        s->dct_quantize = ff_dct_quantize_c;

    if (!s->denoise_dct)

        s->denoise_dct  = denoise_dct_c;

    s->fast_dct_quantize = s->dct_quantize;

    if (avctx->trellis)

        s->dct_quantize  = dct_quantize_trellis_c;

    if ((CONFIG_H263P_ENCODER || CONFIG_RV20_ENCODER) && s->modified_quant)

        s->chroma_qscale_table = ff_h263_chroma_qscale_table;

    if (s->slice_context_count > 1) {

        s->rtp_mode = 1;

        if (avctx->codec_id == AV_CODEC_ID_H263 || avctx->codec_id == AV_CODEC_ID_H263P)

            s->h263_slice_structured = 1;

    }

    s->quant_precision = 5;

    ff_set_cmp(&s->mecc, s->mecc.ildct_cmp,      s->avctx->ildct_cmp);

    ff_set_cmp(&s->mecc, s->mecc.frame_skip_cmp, s->avctx->frame_skip_cmp);

    if (CONFIG_H261_ENCODER && s->out_format == FMT_H261)

        ff_h261_encode_init(s);

    if (CONFIG_H263_ENCODER && s->out_format == FMT_H263)

        ff_h263_encode_init(s);

    if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)

        if ((ret = ff_msmpeg4_encode_init(s)) < 0)

            return ret;

    if ((CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)

        && s->out_format == FMT_MPEG1)

        ff_mpeg1_encode_init(s);

    /* init q matrix */

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

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

        if (CONFIG_MPEG4_ENCODER && s->codec_id == AV_CODEC_ID_MPEG4 &&

            s->mpeg_quant) {

            s->intra_matrix[j] = ff_mpeg4_default_intra_matrix[i];

            s->inter_matrix[j] = ff_mpeg4_default_non_intra_matrix[i];

        } else if (s->out_format == FMT_H263 || s->out_format == FMT_H261) {

            s->intra_matrix[j] =

            s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];

        } else {

            /* mpeg1/2 */

            s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];

            s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];

        }

        if (s->avctx->intra_matrix)

            s->intra_matrix[j] = s->avctx->intra_matrix[i];

        if (s->avctx->inter_matrix)

            s->inter_matrix[j] = s->avctx->inter_matrix[i];

    }

    /* precompute matrix */

    /* for mjpeg, we do include qscale in the matrix */

    if (s->out_format != FMT_MJPEG) {

        ff_convert_matrix(s, s->q_intra_matrix, s->q_intra_matrix16,

                          s->intra_matrix, s->intra_quant_bias, avctx->qmin,

                          31, 1);

        ff_convert_matrix(s, s->q_inter_matrix, s->q_inter_matrix16,

                          s->inter_matrix, s->inter_quant_bias, avctx->qmin,

                          31, 0);

    }

    if (ff_rate_control_init(s) < 0)

        return -1;

#if FF_API_ERROR_RATE

    FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->error_rate)

        s->error_rate = avctx->error_rate;

    FF_ENABLE_DEPRECATION_WARNINGS;

#endif

#if FF_API_NORMALIZE_AQP

    FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->flags & CODEC_FLAG_NORMALIZE_AQP)

        s->mpv_flags |= FF_MPV_FLAG_NAQ;

    FF_ENABLE_DEPRECATION_WARNINGS;

#endif

#if FF_API_MV0

    FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->flags & CODEC_FLAG_MV0)

        s->mpv_flags |= FF_MPV_FLAG_MV0;

    FF_ENABLE_DEPRECATION_WARNINGS

#endif

#if FF_API_MPV_OPT

    FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->rc_qsquish != 0.0)

        s->rc_qsquish = avctx->rc_qsquish;

    if (avctx->rc_qmod_amp != 0.0)

        s->rc_qmod_amp = avctx->rc_qmod_amp;

    if (avctx->rc_qmod_freq)

        s->rc_qmod_freq = avctx->rc_qmod_freq;

    if (avctx->rc_buffer_aggressivity != 1.0)

        s->rc_buffer_aggressivity = avctx->rc_buffer_aggressivity;

    if (avctx->rc_initial_cplx != 0.0)

        s->rc_initial_cplx = avctx->rc_initial_cplx;

    if (avctx->lmin)

        s->lmin = avctx->lmin;

    if (avctx->lmax)

        s->lmax = avctx->lmax;

    if (avctx->rc_eq) {

        av_freep(&s->rc_eq);

        s->rc_eq = av_strdup(avctx->rc_eq);

        if (!s->rc_eq)

            return AVERROR(ENOMEM);

    }

    FF_ENABLE_DEPRECATION_WARNINGS

#endif

    if (avctx->b_frame_strategy == 2) {

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

            s->tmp_frames[i] = av_frame_alloc();

            if (!s->tmp_frames[i])

                return AVERROR(ENOMEM);

            s->tmp_frames[i]->format = AV_PIX_FMT_YUV420P;

            s->tmp_frames[i]->width  = s->width  >> avctx->brd_scale;

            s->tmp_frames[i]->height = s->height >> avctx->brd_scale;

            ret = av_frame_get_buffer(s->tmp_frames[i], 32);

            if (ret < 0)

                return ret;

        }

    }

    cpb_props = ff_add_cpb_side_data(avctx);

    if (!cpb_props)

        return AVERROR(ENOMEM);

    cpb_props->max_bitrate = avctx->rc_max_rate;

    cpb_props->min_bitrate = avctx->rc_min_rate;

    cpb_props->avg_bitrate = avctx->bit_rate;

    cpb_props->buffer_size = avctx->rc_buffer_size;

    return 0;

fail:

    ff_mpv_encode_end(avctx);

    return AVERROR_UNKNOWN;

}


static inline void gen_op_eval_fbg(TCGv dst, TCGv src,

                                    unsigned int fcc_offset)

{

    gen_mov_reg_FCC0(dst, src, fcc_offset);

    tcg_gen_xori_tl(dst, dst, 0x1);

    gen_mov_reg_FCC1(cpu_tmp0, src, fcc_offset);

    tcg_gen_and_tl(dst, dst, cpu_tmp0);

}


static void disas_simd_across_lanes(DisasContext *s, uint32_t insn)

{

    unsupported_encoding(s, insn);

}


static int readv_f(int argc, char **argv)

{

    struct timeval t1, t2;

    int Cflag = 0, qflag = 0, vflag = 0;

    int c, cnt;

    char *buf;

    int64_t offset;

    /* Some compilers get confused and warn if this is not initialized.  */

    int total = 0;

    int nr_iov;

    QEMUIOVector qiov;

    int pattern = 0;

    int Pflag = 0;

    while ((c = getopt(argc, argv, "CP:qv")) != EOF) {

        switch (c) {

        case 'C':

            Cflag = 1;

            break;

        case 'P':

            Pflag = 1;

            pattern = parse_pattern(optarg);

            if (pattern < 0) {

                return 0;

            }

            break;

        case 'q':

            qflag = 1;

            break;

        case 'v':

            vflag = 1;

            break;

        default:

            return command_usage(&readv_cmd);

        }

    }

    if (optind > argc - 2) {

        return command_usage(&readv_cmd);

    }

    offset = cvtnum(argv[optind]);

    if (offset < 0) {

        printf("non-numeric length argument -- %s\n", argv[optind]);

        return 0;

    }

    optind++;

    if (offset & 0x1ff) {

        printf("offset %" PRId64 " is not sector aligned\n",

               offset);

        return 0;

    }

    nr_iov = argc - optind;

    buf = create_iovec(&qiov, &argv[optind], nr_iov, 0xab);

    if (buf == NULL) {

        return 0;

    }

    gettimeofday(&t1, NULL);

    cnt = do_aio_readv(&qiov, offset, &total);

    gettimeofday(&t2, NULL);

    if (cnt < 0) {

        printf("readv failed: %s\n", strerror(-cnt));

        goto out;

    }

    if (Pflag) {

        void *cmp_buf = malloc(qiov.size);

        memset(cmp_buf, pattern, qiov.size);

        if (memcmp(buf, cmp_buf, qiov.size)) {

            printf("Pattern verification failed at offset %"

                   PRId64 ", %zd bytes\n", offset, qiov.size);

        }

        free(cmp_buf);

    }

    if (qflag) {

        goto out;

    }

    if (vflag) {

        dump_buffer(buf, offset, qiov.size);

    }

    /* Finally, report back -- -C gives a parsable format */

    t2 = tsub(t2, t1);

    print_report("read", &t2, offset, qiov.size, total, cnt, Cflag);

out:

    qemu_io_free(buf);

    return 0;

}


void nbd_client_put(NBDClient *client)

{

    if (--client->refcount == 0) {

        /* The last reference should be dropped by client->close,

         * which is called by nbd_client_close.

         */

        assert(client->closing);

        nbd_unset_handlers(client);

        close(client->sock);

        client->sock = -1;

        if (client->exp) {

            QTAILQ_REMOVE(&client->exp->clients, client, next);

            nbd_export_put(client->exp);

        }

        g_free(client);

    }

}


static void arm11mpcore_initfn(Object *obj)

{

    ARMCPU *cpu = ARM_CPU(obj);

    set_feature(&cpu->env, ARM_FEATURE_V6K);

    set_feature(&cpu->env, ARM_FEATURE_VFP);

    set_feature(&cpu->env, ARM_FEATURE_VAPA);

    cpu->midr = ARM_CPUID_ARM11MPCORE;

    cpu->reset_fpsid = 0x410120b4;

    cpu->mvfr0 = 0x11111111;

    cpu->mvfr1 = 0x00000000;

    cpu->ctr = 0x1dd20d2;

    cpu->id_pfr0 = 0x111;

    cpu->id_pfr1 = 0x1;

    cpu->id_dfr0 = 0;

    cpu->id_afr0 = 0x2;

    cpu->id_mmfr0 = 0x01100103;

    cpu->id_mmfr1 = 0x10020302;

    cpu->id_mmfr2 = 0x01222000;

    cpu->id_isar0 = 0x00100011;

    cpu->id_isar1 = 0x12002111;

    cpu->id_isar2 = 0x11221011;

    cpu->id_isar3 = 0x01102131;

    cpu->id_isar4 = 0x141;

}


void pci_device_hot_add(Monitor *mon, const QDict *qdict)

{

    PCIDevice *dev = NULL;

    const char *pci_addr = qdict_get_str(qdict, "pci_addr");

    const char *type = qdict_get_str(qdict, "type");

    const char *opts = qdict_get_try_str(qdict, "opts");

    /* strip legacy tag */

    if (!strncmp(pci_addr, "pci_addr=", 9)) {

        pci_addr += 9;

    }

    if (!opts) {

        opts = "";

    }

    if (!strcmp(pci_addr, "auto"))

        pci_addr = NULL;

    if (strcmp(type, "nic") == 0) {

        dev = qemu_pci_hot_add_nic(mon, pci_addr, opts);

    } else if (strcmp(type, "storage") == 0) {

        dev = qemu_pci_hot_add_storage(mon, pci_addr, opts);

    } else {

        monitor_printf(mon, "invalid type: %s\n", type);

    }

    if (dev) {

        monitor_printf(mon, "OK domain %d, bus %d, slot %d, function %d\n",

                       pci_find_domain(dev->bus),

                       pci_bus_num(dev->bus), PCI_SLOT(dev->devfn),

                       PCI_FUNC(dev->devfn));

    } else

        monitor_printf(mon, "failed to add %s\n", opts);

}


float32 helper_fsqrts(CPUSPARCState *env, float32 src)

{

    float32 ret;

    clear_float_exceptions(env);

    ret = float32_sqrt(src, &env->fp_status);

    check_ieee_exceptions(env);

    return ret;

}


ser_read(void *opaque, target_phys_addr_t addr, unsigned int size)

{

    struct etrax_serial *s = opaque;

    D(CPUCRISState *env = s->env);

    uint32_t r = 0;

    addr >>= 2;

    switch (addr)

    {

        case R_STAT_DIN:

            r = s->rx_fifo[(s->rx_fifo_pos - s->rx_fifo_len) & 15];

            if (s->rx_fifo_len) {

                r |= 1 << STAT_DAV;

            }

            r |= 1 << STAT_TR_RDY;

            r |= 1 << STAT_TR_IDLE;

            break;

        case RS_STAT_DIN:

            r = s->rx_fifo[(s->rx_fifo_pos - s->rx_fifo_len) & 15];

            if (s->rx_fifo_len) {

                r |= 1 << STAT_DAV;

                s->rx_fifo_len--;

            }

            r |= 1 << STAT_TR_RDY;

            r |= 1 << STAT_TR_IDLE;

            break;

        default:

            r = s->regs[addr];

            D(qemu_log("%s " TARGET_FMT_plx "=%x\n", __func__, addr, r));

            break;

    }

    return r;

}


static void vfio_probe_nvidia_bar0_88000_quirk(VFIODevice *vdev, int nr)

{

    PCIDevice *pdev = &vdev->pdev;

    VFIOQuirk *quirk;

    if (!vdev->has_vga || nr != 0 ||

        pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_NVIDIA) {

        return;

    }

    quirk = g_malloc0(sizeof(*quirk));

    quirk->vdev = vdev;

    quirk->data.flags = quirk->data.read_flags = quirk->data.write_flags = 1;

    quirk->data.address_match = 0x88000;

    quirk->data.address_mask = PCIE_CONFIG_SPACE_SIZE - 1;

    quirk->data.bar = nr;

    memory_region_init_io(&quirk->mem, OBJECT(vdev), &vfio_generic_quirk,

                          quirk, "vfio-nvidia-bar0-88000-quirk",

                          TARGET_PAGE_ALIGN(quirk->data.address_mask + 1));

    memory_region_add_subregion_overlap(&vdev->bars[nr].mem,

                          quirk->data.address_match & TARGET_PAGE_MASK,

                          &quirk->mem, 1);

    QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);

    DPRINTF("Enabled NVIDIA BAR0 0x88000 quirk for device %04x:%02x:%02x.%x\n",

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

            vdev->host.function);

}


static subpage_t *subpage_init(target_phys_addr_t base)

{

    subpage_t *mmio;

    mmio = g_malloc0(sizeof(subpage_t));

    mmio->base = base;

    memory_region_init_io(&mmio->iomem, &subpage_ops, mmio,

                          "subpage", TARGET_PAGE_SIZE);

    mmio->iomem.subpage = true;

#if defined(DEBUG_SUBPAGE)

    printf("%s: %p base " TARGET_FMT_plx " len %08x %d\n", __func__,

           mmio, base, TARGET_PAGE_SIZE, subpage_memory);

#endif

    subpage_register(mmio, 0, TARGET_PAGE_SIZE-1, phys_section_unassigned);

    return mmio;

}


static abi_long do_bind(int sockfd, abi_ulong target_addr,

                        socklen_t addrlen)

{

    void *addr;

    abi_long ret;

    if (addrlen < 0)

        return -TARGET_EINVAL;

    addr = alloca(addrlen+1);

    ret = target_to_host_sockaddr(addr, target_addr, addrlen);

    if (ret)

        return ret;

    return get_errno(bind(sockfd, addr, addrlen));

}


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

{

    static const char * const fd_params[] = {

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

    };

    char buf[1024];

    int vlan_id, ret;

    VLANState *vlan;

    char *name = NULL;

    vlan_id = 0;

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

        vlan_id = strtol(buf, NULL, 0);

    }

    vlan = qemu_find_vlan(vlan_id);

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

        name = qemu_strdup(buf);

    }

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

        static const char * const nic_params[] = {

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

        };

        NICInfo *nd;

        uint8_t *macaddr;

        int idx = nic_get_free_idx();

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

            config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);

            ret = -1;

            goto out;

        }

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

            config_error(mon, "Too Many NICs\n");

            ret = -1;

            goto out;

        }

        nd = &nd_table[idx];

        macaddr = nd->macaddr;

        macaddr[0] = 0x52;

        macaddr[1] = 0x54;

        macaddr[2] = 0x00;

        macaddr[3] = 0x12;

        macaddr[4] = 0x34;

        macaddr[5] = 0x56 + idx;

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

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

                config_error(mon, "invalid syntax for ethernet address\n");

                ret = -1;

                goto out;

            }

        }

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

            nd->model = strdup(buf);

        }

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

            nd->devaddr = strdup(buf);

        }

        nd->vlan = vlan;

        nd->name = name;

        nd->used = 1;

        name = NULL;

        nb_nics++;

        vlan->nb_guest_devs++;

        ret = idx;

    } else

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

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

            config_error(mon, "'none' takes no parameters\n");

            ret = -1;

            goto out;

        }

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

           are wanted */

        ret = 0;

    } else

#ifdef CONFIG_SLIRP

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

        static const char * const slirp_params[] = {

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

        };

        int restricted = 0;

        char *ip = NULL;

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

            config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);

            ret = -1;

            goto out;

        }

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

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

        }

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

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

        }

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

            ip = qemu_strdup(buf);

        }

        vlan->nb_host_devs++;

        ret = net_slirp_init(vlan, device, name, restricted, ip);

        qemu_free(ip);

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

        long port;

        char name[20], *devname;

        struct VMChannel *vmc;

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

        devname++;

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

            config_error(mon, "vmchannel wrong port number\n");

            ret = -1;

            goto out;

        }

        vmc = malloc(sizeof(struct VMChannel));

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

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

        if (!vmc->hd) {

            config_error(mon, "could not open vmchannel device '%s'\n",

                         devname);

            ret = -1;

            goto out;

        }

        vmc->port = port;

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

        qemu_chr_add_handlers(vmc->hd, vmchannel_can_read, vmchannel_read,

                NULL, vmc);

        ret = 0;

    } else

#endif

#ifdef _WIN32

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

        static const char * const tap_params[] = {

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

        };

        char ifname[64];

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

            config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);

            ret = -1;

            goto out;

        }

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

            config_error(mon, "tap: no interface name\n");

            ret = -1;

            goto out;

        }

        vlan->nb_host_devs++;

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

    } else

#elif defined (_AIX)

#else

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

        char ifname[64], chkbuf[64];

        char setup_script[1024], down_script[1024];

        TAPState *s;

        int fd;

        vlan->nb_host_devs++;

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

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

                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);

                ret = -1;

                goto out;

            }

            fd = strtol(buf, NULL, 0);

            fcntl(fd, F_SETFL, O_NONBLOCK);

            s = net_tap_fd_init(vlan, device, name, fd);

        } else {

            static const char * const tap_params[] = {

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

            };

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

                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);

                ret = -1;

                goto out;

            }

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

                ifname[0] = '\0';

            }

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

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

            }

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

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

            }

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

        }

        if (s != NULL) {

            ret = 0;

        } else {

            ret = -1;

        }

    } else

#endif

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

        char chkbuf[64];

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

            int fd;

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

                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);

                ret = -1;

                goto out;

            }

            fd = strtol(buf, NULL, 0);

            ret = -1;

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

                ret = 0;

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

            static const char * const listen_params[] = {

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

            };

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

                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);

                ret = -1;

                goto out;

            }

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

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

            static const char * const connect_params[] = {

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

            };

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

                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);

                ret = -1;

                goto out;

            }

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

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

            static const char * const mcast_params[] = {

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

            };

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

                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);

                ret = -1;

                goto out;

            }

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

        } else {

            config_error(mon, "Unknown socket options: %s\n", p);

            ret = -1;

            goto out;

        }

        vlan->nb_host_devs++;

    } else

#ifdef CONFIG_VDE

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

        static const char * const vde_params[] = {

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

        };

        char vde_sock[1024], vde_group[512];

	int vde_port, vde_mode;

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

            config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);

            ret = -1;

            goto out;

        }

        vlan->nb_host_devs++;

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

	    vde_sock[0] = '\0';

	}

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

	    vde_port = strtol(buf, NULL, 10);

	} else {

	    vde_port = 0;

	}

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

	    vde_group[0] = '\0';

	}

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

	    vde_mode = strtol(buf, NULL, 8);

	} else {

	    vde_mode = 0700;

	}

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

    } else

#endif

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

        int len = 65536;

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

            len = strtol(buf, NULL, 0);

        }

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

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

        }

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

    } else {

        config_error(mon, "Unknown network device: %s\n", device);

        ret = -1;

        goto out;

    }

    if (ret < 0) {

        config_error(mon, "Could not initialize device '%s'\n", device);

    }

out:

    qemu_free(name);

    return ret;

}


void tcg_target_qemu_prologue (TCGContext *s)

{

    int i, frame_size;

    frame_size = 0

        + 8                     /* back chain */

        + 8                     /* CR */

        + 8                     /* LR */

        + 8                     /* compiler doubleword */

        + 8                     /* link editor doubleword */

        + 8                     /* TOC save area */

        + TCG_STATIC_CALL_ARGS_SIZE

        + ARRAY_SIZE (tcg_target_callee_save_regs) * 8

        ;

    frame_size = (frame_size + 15) & ~15;

    tcg_out32 (s, MFSPR | RT (0) | LR);

    tcg_out32 (s, STDU | RS (1) | RA (1) | (-frame_size & 0xffff));

    for (i = 0; i < ARRAY_SIZE (tcg_target_callee_save_regs); ++i)

        tcg_out32 (s, (STD

                       | RS (tcg_target_callee_save_regs[i])

                       | RA (1)

                       | (i * 8 + 48 + TCG_STATIC_CALL_ARGS_SIZE)

                       )

            );

    tcg_out32 (s, STD | RS (0) | RA (1) | (frame_size + 20));

    tcg_out32 (s, STD | RS (2) | RA (1) | (frame_size + 40));

    tcg_out32 (s, MTSPR | RS (3) | CTR);

    tcg_out32 (s, BCCTR | BO_ALWAYS);

    tb_ret_addr = s->code_ptr;

    for (i = 0; i < ARRAY_SIZE (tcg_target_callee_save_regs); ++i)

        tcg_out32 (s, (LD

                       | RT (tcg_target_callee_save_regs[i])

                       | RA (1)

                       | (i * 8 + 48 + TCG_STATIC_CALL_ARGS_SIZE)

                       )

            );

    tcg_out32 (s, LD | RT (0) | RA (1) | (frame_size + 20));

    tcg_out32 (s, LD | RT (2) | RA (1) | (frame_size + 40));

    tcg_out32 (s, MTSPR | RS (0) | LR);

    tcg_out32 (s, ADDI | RT (1) | RA (1) | frame_size);

    tcg_out32 (s, BCLR | BO_ALWAYS);

}


static void pxa2xx_pm_write(void *opaque, hwaddr addr,

                            uint64_t value, unsigned size)

{

    PXA2xxState *s = (PXA2xxState *) opaque;

    switch (addr) {

    case PMCR:

        /* Clear the write-one-to-clear bits... */

        s->pm_regs[addr >> 2] &= ~(value & 0x2a);

        /* ...and set the plain r/w bits */

        s->pm_regs[addr >> 2] &= ~0x15;

        s->pm_regs[addr >> 2] |= value & 0x15;

        break;

    case PSSR:	/* Read-clean registers */

    case RCSR:

    case PKSR:

        s->pm_regs[addr >> 2] &= ~value;

        break;

    default:	/* Read-write registers */

        if (!(addr & 3)) {

            s->pm_regs[addr >> 2] = value;

            break;

        }

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

        break;

    }

}


static unsigned int dec_rfe_etc(DisasContext *dc)

{

	cris_cc_mask(dc, 0);

	if (dc->op2 == 15) /* ignore halt.  */

		return 2;

	switch (dc->op2 & 7) {

		case 2:

			/* rfe.  */

			DIS(fprintf(logfile, "rfe\n"));

			cris_evaluate_flags(dc);

			tcg_gen_helper_0_0(helper_rfe);

			dc->is_jmp = DISAS_UPDATE;

			break;

		case 5:

			/* rfn.  */

			DIS(fprintf(logfile, "rfn\n"));

			cris_evaluate_flags(dc);

			tcg_gen_helper_0_0(helper_rfn);

			dc->is_jmp = DISAS_UPDATE;

			break;

		case 6:

			DIS(fprintf(logfile, "break %d\n", dc->op1));

			cris_evaluate_flags (dc);

			/* break.  */

			tcg_gen_movi_tl(env_pc, dc->pc + 2);

			/* Breaks start at 16 in the exception vector.  */

			t_gen_mov_env_TN(trap_vector,

					 tcg_const_tl(dc->op1 + 16));

			t_gen_raise_exception(EXCP_BREAK);

			dc->is_jmp = DISAS_UPDATE;

			break;

		default:

			printf ("op2=%x\n", dc->op2);

			BUG();

			break;

	}

	return 2;

}


ram_addr_t get_current_ram_size(void)

{

    MemoryDeviceInfoList *info_list = NULL;

    MemoryDeviceInfoList **prev = &info_list;

    MemoryDeviceInfoList *info;

    ram_addr_t size = ram_size;

    qmp_pc_dimm_device_list(qdev_get_machine(), &prev);

    for (info = info_list; info; info = info->next) {

        MemoryDeviceInfo *value = info->value;

        if (value) {

            switch (value->kind) {

            case MEMORY_DEVICE_INFO_KIND_DIMM:

                size += value->dimm->size;

                break;

            default:

                break;

            }

        }

    }

    qapi_free_MemoryDeviceInfoList(info_list);

    return size;

}