vcard_emul_mirror_card(VReader *vreader)

{

    /*

     * lookup certs using the C_FindObjects. The Stan Cert handle won't give

     * us the real certs until we log in.

     */

    PK11GenericObject *firstObj, *thisObj;

    int cert_count;

    unsigned char **certs;

    int *cert_len;

    VCardKey **keys;

    PK11SlotInfo *slot;

    VCard *card;

    slot = vcard_emul_reader_get_slot(vreader);

    if (slot == NULL) {

        return NULL;

    }

    firstObj = PK11_FindGenericObjects(slot, CKO_CERTIFICATE);

    if (firstObj == NULL) {

        return NULL;

    }

    /* count the certs */

    cert_count = 0;

    for (thisObj = firstObj; thisObj;

                             thisObj = PK11_GetNextGenericObject(thisObj)) {

        cert_count++;

    }

    if (cert_count == 0) {

        PK11_DestroyGenericObjects(firstObj);

        return NULL;

    }

    /* allocate the arrays */

    vcard_emul_alloc_arrays(&certs, &cert_len, &keys, cert_count);

    /* fill in the arrays */

    cert_count = 0;

    for (thisObj = firstObj; thisObj;

                             thisObj = PK11_GetNextGenericObject(thisObj)) {

        SECItem derCert;

        CERTCertificate *cert;

        SECStatus rv;

        rv = PK11_ReadRawAttribute(PK11_TypeGeneric, thisObj,

                                   CKA_VALUE, &derCert);

        if (rv != SECSuccess) {

            continue;

        }

        /* create floating temp cert. This gives us a cert structure even if

         * the token isn't logged in */

        cert = CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &derCert,

                                       NULL, PR_FALSE, PR_TRUE);

        SECITEM_FreeItem(&derCert, PR_FALSE);

        if (cert == NULL) {

            continue;

        }

        certs[cert_count] = cert->derCert.data;

        cert_len[cert_count] = cert->derCert.len;

        keys[cert_count] = vcard_emul_make_key(slot, cert);

        cert_count++;

        CERT_DestroyCertificate(cert); /* key obj still has a reference */

    }

    /* now create the card */

    card = vcard_emul_make_card(vreader, certs, cert_len, keys, cert_count);

    g_free(certs);

    g_free(cert_len);

    g_free(keys);

    return card;

}


static uint64_t megasas_fw_time(void)

{

    struct tm curtime;

    uint64_t bcd_time;

    qemu_get_timedate(&curtime, 0);

    bcd_time = ((uint64_t)curtime.tm_sec & 0xff) << 48 |

        ((uint64_t)curtime.tm_min & 0xff)  << 40 |

        ((uint64_t)curtime.tm_hour & 0xff) << 32 |

        ((uint64_t)curtime.tm_mday & 0xff) << 24 |

        ((uint64_t)curtime.tm_mon & 0xff)  << 16 |

        ((uint64_t)(curtime.tm_year + 1900) & 0xffff);

    return bcd_time;

}


static OfDpaFlow *of_dpa_flow_alloc(uint64_t cookie)

{

    OfDpaFlow *flow;

    int64_t now = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) / 1000;

    flow = g_new0(OfDpaFlow, 1);

    if (!flow) {

        return NULL;

    }

    flow->cookie = cookie;

    flow->mask.tbl_id = 0xffffffff;

    flow->stats.install_time = flow->stats.refresh_time = now;

    return flow;

}


static int rtp_open(URLContext *h, const char *uri, int flags)

{

    RTPContext *s;

    int port, is_output, ttl, local_port;

    char hostname[256];

    char buf[1024];

    char path[1024];

    const char *p;

    is_output = (flags & URL_WRONLY);

    s = av_mallocz(sizeof(RTPContext));

    if (!s)

        return AVERROR(ENOMEM);

    h->priv_data = s;

    url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port,

              path, sizeof(path), uri);

    /* extract parameters */

    ttl = -1;

    local_port = -1;

    p = strchr(uri, '?');

    if (p) {

        if (find_info_tag(buf, sizeof(buf), "ttl", p)) {

            ttl = strtol(buf, NULL, 10);

        }

        if (find_info_tag(buf, sizeof(buf), "localport", p)) {

            local_port = strtol(buf, NULL, 10);

        }

    }

    build_udp_url(buf, sizeof(buf),

                  hostname, port, local_port, ttl);

    if (url_open(&s->rtp_hd, buf, flags) < 0)

        goto fail;

    local_port = udp_get_local_port(s->rtp_hd);

    /* XXX: need to open another connection if the port is not even */

    /* well, should suppress localport in path */

    build_udp_url(buf, sizeof(buf),

                  hostname, port + 1, local_port + 1, ttl);

    if (url_open(&s->rtcp_hd, buf, flags) < 0)

        goto fail;

    /* just to ease handle access. XXX: need to suppress direct handle

       access */

    s->rtp_fd = udp_get_file_handle(s->rtp_hd);

    s->rtcp_fd = udp_get_file_handle(s->rtcp_hd);

    h->max_packet_size = url_get_max_packet_size(s->rtp_hd);

    h->is_streamed = 1;

    return 0;

 fail:

    if (s->rtp_hd)

        url_close(s->rtp_hd);

    if (s->rtcp_hd)

        url_close(s->rtcp_hd);

    av_free(s);

    return AVERROR(EIO);

}


static float get_band_cost_UPAIR7_mips(struct AACEncContext *s,

                                       PutBitContext *pb, const float *in,

                                       const float *scaled, int size, int scale_idx,

                                       int cb, const float lambda, const float uplim,

                                       int *bits)

{

    const float Q34 = ff_aac_pow34sf_tab[POW_SF2_ZERO - scale_idx + SCALE_ONE_POS - SCALE_DIV_512];

    const float IQ  = ff_aac_pow2sf_tab [POW_SF2_ZERO + scale_idx - SCALE_ONE_POS + SCALE_DIV_512];

    int i;

    float cost = 0;

    int qc1, qc2, qc3, qc4;

    int curbits = 0;

    uint8_t *p_bits  = (uint8_t *)ff_aac_spectral_bits[cb-1];

    float   *p_codes = (float   *)ff_aac_codebook_vectors[cb-1];

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

        const float *vec, *vec2;

        int curidx, curidx2, sign1, count1, sign2, count2;

        int   *in_int = (int   *)&in[i];

        float *in_pos = (float *)&in[i];

        float di0, di1, di2, di3;

        int t0, t1, t2, t3, t4;

        qc1 = scaled[i  ] * Q34 + ROUND_STANDARD;

        qc2 = scaled[i+1] * Q34 + ROUND_STANDARD;

        qc3 = scaled[i+2] * Q34 + ROUND_STANDARD;

        qc4 = scaled[i+3] * Q34 + ROUND_STANDARD;

        __asm__ volatile (

            ".set push                                          \n\t"

            ".set noreorder                                     \n\t"

            "ori        %[t4],      $zero,      7               \n\t"

            "ori        %[sign1],   $zero,      0               \n\t"

            "ori        %[sign2],   $zero,      0               \n\t"

            "slt        %[t0],      %[t4],      %[qc1]          \n\t"

            "slt        %[t1],      %[t4],      %[qc2]          \n\t"

            "slt        %[t2],      %[t4],      %[qc3]          \n\t"

            "slt        %[t3],      %[t4],      %[qc4]          \n\t"

            "movn       %[qc1],     %[t4],      %[t0]           \n\t"

            "movn       %[qc2],     %[t4],      %[t1]           \n\t"

            "movn       %[qc3],     %[t4],      %[t2]           \n\t"

            "movn       %[qc4],     %[t4],      %[t3]           \n\t"

            "lw         %[t0],      0(%[in_int])                \n\t"

            "lw         %[t1],      4(%[in_int])                \n\t"

            "lw         %[t2],      8(%[in_int])                \n\t"

            "lw         %[t3],      12(%[in_int])               \n\t"

            "slt        %[t0],      %[t0],      $zero           \n\t"

            "movn       %[sign1],   %[t0],      %[qc1]          \n\t"

            "slt        %[t2],      %[t2],      $zero           \n\t"

            "movn       %[sign2],   %[t2],      %[qc3]          \n\t"

            "slt        %[t1],      %[t1],      $zero           \n\t"

            "sll        %[t0],      %[sign1],   1               \n\t"

            "or         %[t0],      %[t0],      %[t1]           \n\t"

            "movn       %[sign1],   %[t0],      %[qc2]          \n\t"

            "slt        %[t3],      %[t3],      $zero           \n\t"

            "sll        %[t0],      %[sign2],   1               \n\t"

            "or         %[t0],      %[t0],      %[t3]           \n\t"

            "movn       %[sign2],   %[t0],      %[qc4]          \n\t"

            "slt        %[count1],  $zero,      %[qc1]          \n\t"

            "slt        %[t1],      $zero,      %[qc2]          \n\t"

            "slt        %[count2],  $zero,      %[qc3]          \n\t"

            "slt        %[t2],      $zero,      %[qc4]          \n\t"

            "addu       %[count1],  %[count1],  %[t1]           \n\t"

            "addu       %[count2],  %[count2],  %[t2]           \n\t"

            ".set pop                                           \n\t"

            : [qc1]"+r"(qc1), [qc2]"+r"(qc2),

              [qc3]"+r"(qc3), [qc4]"+r"(qc4),

              [sign1]"=&r"(sign1), [count1]"=&r"(count1),

              [sign2]"=&r"(sign2), [count2]"=&r"(count2),

              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),

              [t4]"=&r"(t4)

            : [in_int]"r"(in_int)

            : "memory"

        );

        curidx = 8 * qc1;

        curidx += qc2;

        curidx2 = 8 * qc3;

        curidx2 += qc4;

        curbits += p_bits[curidx];

        curbits += upair7_sign_bits[curidx];

        vec     = &p_codes[curidx*2];

        curbits += p_bits[curidx2];

        curbits += upair7_sign_bits[curidx2];

        vec2    = &p_codes[curidx2*2];

        __asm__ volatile (

            ".set push                                          \n\t"

            ".set noreorder                                     \n\t"

            "lwc1       %[di0],     0(%[in_pos])                \n\t"

            "lwc1       %[di1],     4(%[in_pos])                \n\t"

            "lwc1       %[di2],     8(%[in_pos])                \n\t"

            "lwc1       %[di3],     12(%[in_pos])               \n\t"

            "abs.s      %[di0],     %[di0]                      \n\t"

            "abs.s      %[di1],     %[di1]                      \n\t"

            "abs.s      %[di2],     %[di2]                      \n\t"

            "abs.s      %[di3],     %[di3]                      \n\t"

            "lwc1       $f0,        0(%[vec])                   \n\t"

            "lwc1       $f1,        4(%[vec])                   \n\t"

            "lwc1       $f2,        0(%[vec2])                  \n\t"

            "lwc1       $f3,        4(%[vec2])                  \n\t"

            "nmsub.s    %[di0],     %[di0],     $f0,    %[IQ]   \n\t"

            "nmsub.s    %[di1],     %[di1],     $f1,    %[IQ]   \n\t"

            "nmsub.s    %[di2],     %[di2],     $f2,    %[IQ]   \n\t"

            "nmsub.s    %[di3],     %[di3],     $f3,    %[IQ]   \n\t"

            ".set pop                                           \n\t"

            : [di0]"=&f"(di0), [di1]"=&f"(di1),

              [di2]"=&f"(di2), [di3]"=&f"(di3)

            : [in_pos]"r"(in_pos), [vec]"r"(vec),

              [vec2]"r"(vec2), [IQ]"f"(IQ)

            : "$f0", "$f1", "$f2", "$f3",

              "memory"

        );

        cost += di0 * di0 + di1 * di1

                + di2 * di2 + di3 * di3;

    }

    if (bits)

        *bits = curbits;

    return cost * lambda + curbits;

}


QObject *json_parser_parse_err(QList *tokens, va_list *ap, Error **errp)

{

    JSONParserContext ctxt = {};

    QList *working = qlist_copy(tokens);

    QObject *result;

    result = parse_value(&ctxt, &working, ap);

    QDECREF(working);

    error_propagate(errp, ctxt.err);

    return result;

}


static int init_directories(BDRVVVFATState* s,

                            const char *dirname, int heads, int secs,

                            Error **errp)

{

    bootsector_t* bootsector;

    mapping_t* mapping;

    unsigned int i;

    unsigned int cluster;

    memset(&(s->first_sectors[0]),0,0x40*0x200);

    s->cluster_size=s->sectors_per_cluster*0x200;

    s->cluster_buffer=g_malloc(s->cluster_size);

    /*

     * The formula: sc = spf+1+spf*spc*(512*8/fat_type),

     * where sc is sector_count,

     * spf is sectors_per_fat,

     * spc is sectors_per_clusters, and

     * fat_type = 12, 16 or 32.

     */

    i = 1+s->sectors_per_cluster*0x200*8/s->fat_type;

    s->sectors_per_fat=(s->sector_count+i)/i; /* round up */

    s->offset_to_fat = s->offset_to_bootsector + 1;

    s->offset_to_root_dir = s->offset_to_fat + s->sectors_per_fat * 2;

    array_init(&(s->mapping),sizeof(mapping_t));

    array_init(&(s->directory),sizeof(direntry_t));

    /* add volume label */

    {

        direntry_t* entry=array_get_next(&(s->directory));

        entry->attributes=0x28; /* archive | volume label */

        memcpy(entry->name, s->volume_label, sizeof(entry->name));

    }

    /* Now build FAT, and write back information into directory */

    init_fat(s);

    s->cluster_count=sector2cluster(s, s->sector_count);

    mapping = array_get_next(&(s->mapping));

    mapping->begin = 0;

    mapping->dir_index = 0;

    mapping->info.dir.parent_mapping_index = -1;

    mapping->first_mapping_index = -1;

    mapping->path = g_strdup(dirname);

    i = strlen(mapping->path);

    if (i > 0 && mapping->path[i - 1] == '/')

        mapping->path[i - 1] = '\0';

    mapping->mode = MODE_DIRECTORY;

    mapping->read_only = 0;

    s->path = mapping->path;

    for (i = 0, cluster = 0; i < s->mapping.next; i++) {

        /* MS-DOS expects the FAT to be 0 for the root directory

         * (except for the media byte). */

        /* LATER TODO: still true for FAT32? */

        int fix_fat = (i != 0);

        mapping = array_get(&(s->mapping), i);

        if (mapping->mode & MODE_DIRECTORY) {

            mapping->begin = cluster;

            if(read_directory(s, i)) {

                error_setg(errp, "Could not read directory %s",

                           mapping->path);

                return -1;

            }

            mapping = array_get(&(s->mapping), i);

        } else {

            assert(mapping->mode == MODE_UNDEFINED);

            mapping->mode=MODE_NORMAL;

            mapping->begin = cluster;

            if (mapping->end > 0) {

                direntry_t* direntry = array_get(&(s->directory),

                        mapping->dir_index);

                mapping->end = cluster + 1 + (mapping->end-1)/s->cluster_size;

                set_begin_of_direntry(direntry, mapping->begin);

            } else {

                mapping->end = cluster + 1;

                fix_fat = 0;

            }

        }

        assert(mapping->begin < mapping->end);

        /* next free cluster */

        cluster = mapping->end;

        if(cluster > s->cluster_count) {

            error_setg(errp,

                       "Directory does not fit in FAT%d (capacity %.2f MB)",

                       s->fat_type, s->sector_count / 2000.0);

            return -1;

        }

        /* fix fat for entry */

        if (fix_fat) {

            int j;

            for(j = mapping->begin; j < mapping->end - 1; j++)

                fat_set(s, j, j+1);

            fat_set(s, mapping->end - 1, s->max_fat_value);

        }

    }

    mapping = array_get(&(s->mapping), 0);

    s->sectors_of_root_directory = mapping->end * s->sectors_per_cluster;

    s->last_cluster_of_root_directory = mapping->end;

    /* the FAT signature */

    fat_set(s,0,s->max_fat_value);

    fat_set(s,1,s->max_fat_value);

    s->current_mapping = NULL;

    bootsector = (bootsector_t *)(s->first_sectors

                                  + s->offset_to_bootsector * 0x200);

    bootsector->jump[0]=0xeb;

    bootsector->jump[1]=0x3e;

    bootsector->jump[2]=0x90;

    memcpy(bootsector->name,"QEMU    ",8);

    bootsector->sector_size=cpu_to_le16(0x200);

    bootsector->sectors_per_cluster=s->sectors_per_cluster;

    bootsector->reserved_sectors=cpu_to_le16(1);

    bootsector->number_of_fats=0x2; /* number of FATs */

    bootsector->root_entries=cpu_to_le16(s->sectors_of_root_directory*0x10);

    bootsector->total_sectors16=s->sector_count>0xffff?0:cpu_to_le16(s->sector_count);

    /* media descriptor: hard disk=0xf8, floppy=0xf0 */

    bootsector->media_type = (s->offset_to_bootsector > 0 ? 0xf8 : 0xf0);

    s->fat.pointer[0] = bootsector->media_type;

    bootsector->sectors_per_fat=cpu_to_le16(s->sectors_per_fat);

    bootsector->sectors_per_track = cpu_to_le16(secs);

    bootsector->number_of_heads = cpu_to_le16(heads);

    bootsector->hidden_sectors = cpu_to_le32(s->offset_to_bootsector);

    bootsector->total_sectors=cpu_to_le32(s->sector_count>0xffff?s->sector_count:0);

    /* LATER TODO: if FAT32, this is wrong */

    /* drive_number: fda=0, hda=0x80 */

    bootsector->u.fat16.drive_number = s->offset_to_bootsector == 0 ? 0 : 0x80;

    bootsector->u.fat16.signature=0x29;

    bootsector->u.fat16.id=cpu_to_le32(0xfabe1afd);

    memcpy(bootsector->u.fat16.volume_label, s->volume_label,

           sizeof(bootsector->u.fat16.volume_label));

    memcpy(bootsector->u.fat16.fat_type,

           s->fat_type == 12 ? "FAT12   " : "FAT16   ", 8);

    bootsector->magic[0]=0x55; bootsector->magic[1]=0xaa;

    return 0;

}


void pxa25x_timer_init(target_phys_addr_t base, qemu_irq *irqs)

{

    pxa2xx_timer_info *s = pxa2xx_timer_init(base, irqs);

    s->freq = PXA25X_FREQ;

    s->tm4 = NULL;

}


struct omap_mpu_state_s *omap2420_mpu_init(unsigned long sdram_size,

                const char *core)

{

    struct omap_mpu_state_s *s = (struct omap_mpu_state_s *)

            g_malloc0(sizeof(struct omap_mpu_state_s));

    ram_addr_t sram_base, q2_base;

    qemu_irq *cpu_irq;

    qemu_irq dma_irqs[4];

    DriveInfo *dinfo;

    int i;

    SysBusDevice *busdev;

    struct omap_target_agent_s *ta;

    /* Core */

    s->mpu_model = omap2420;

    s->env = cpu_init(core ?: "arm1136-r2");

    if (!s->env) {

        fprintf(stderr, "Unable to find CPU definition\n");

        exit(1);

    }

    s->sdram_size = sdram_size;

    s->sram_size = OMAP242X_SRAM_SIZE;

    s->wakeup = qemu_allocate_irqs(omap_mpu_wakeup, s, 1)[0];

    /* Clocks */

    omap_clk_init(s);

    /* Memory-mapped stuff */

    cpu_register_physical_memory(OMAP2_Q2_BASE, s->sdram_size,

                    (q2_base = qemu_ram_alloc(NULL, "omap2.dram",

                                              s->sdram_size)) | IO_MEM_RAM);

    cpu_register_physical_memory(OMAP2_SRAM_BASE, s->sram_size,

                    (sram_base = qemu_ram_alloc(NULL, "omap2.sram",

                                                s->sram_size)) | IO_MEM_RAM);

    s->l4 = omap_l4_init(OMAP2_L4_BASE, 54);

    /* Actually mapped at any 2K boundary in the ARM11 private-peripheral if */

    cpu_irq = arm_pic_init_cpu(s->env);

    s->ih[0] = omap2_inth_init(0x480fe000, 0x1000, 3, &s->irq[0],

                    cpu_irq[ARM_PIC_CPU_IRQ], cpu_irq[ARM_PIC_CPU_FIQ],

                    omap_findclk(s, "mpu_intc_fclk"),

                    omap_findclk(s, "mpu_intc_iclk"));

    s->prcm = omap_prcm_init(omap_l4tao(s->l4, 3),

                    s->irq[0][OMAP_INT_24XX_PRCM_MPU_IRQ], NULL, NULL, s);

    s->sysc = omap_sysctl_init(omap_l4tao(s->l4, 1),

                    omap_findclk(s, "omapctrl_iclk"), s);

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

        dma_irqs[i] =

                s->irq[omap2_dma_irq_map[i].ih][omap2_dma_irq_map[i].intr];

    s->dma = omap_dma4_init(0x48056000, dma_irqs, s, 256, 32,

                    omap_findclk(s, "sdma_iclk"),

                    omap_findclk(s, "sdma_fclk"));

    s->port->addr_valid = omap2_validate_addr;

    /* Register SDRAM and SRAM ports for fast DMA transfers.  */

    soc_dma_port_add_mem(s->dma, qemu_get_ram_ptr(q2_base),

                         OMAP2_Q2_BASE, s->sdram_size);

    soc_dma_port_add_mem(s->dma, qemu_get_ram_ptr(sram_base),

                         OMAP2_SRAM_BASE, s->sram_size);

    s->uart[0] = omap2_uart_init(omap_l4ta(s->l4, 19),

                    s->irq[0][OMAP_INT_24XX_UART1_IRQ],

                    omap_findclk(s, "uart1_fclk"),

                    omap_findclk(s, "uart1_iclk"),

                    s->drq[OMAP24XX_DMA_UART1_TX],

                    s->drq[OMAP24XX_DMA_UART1_RX],

                    "uart1",

                    serial_hds[0]);

    s->uart[1] = omap2_uart_init(omap_l4ta(s->l4, 20),

                    s->irq[0][OMAP_INT_24XX_UART2_IRQ],

                    omap_findclk(s, "uart2_fclk"),

                    omap_findclk(s, "uart2_iclk"),

                    s->drq[OMAP24XX_DMA_UART2_TX],

                    s->drq[OMAP24XX_DMA_UART2_RX],

                    "uart2",

                    serial_hds[0] ? serial_hds[1] : NULL);

    s->uart[2] = omap2_uart_init(omap_l4ta(s->l4, 21),

                    s->irq[0][OMAP_INT_24XX_UART3_IRQ],

                    omap_findclk(s, "uart3_fclk"),

                    omap_findclk(s, "uart3_iclk"),

                    s->drq[OMAP24XX_DMA_UART3_TX],

                    s->drq[OMAP24XX_DMA_UART3_RX],

                    "uart3",

                    serial_hds[0] && serial_hds[1] ? serial_hds[2] : NULL);

    s->gptimer[0] = omap_gp_timer_init(omap_l4ta(s->l4, 7),

                    s->irq[0][OMAP_INT_24XX_GPTIMER1],

                    omap_findclk(s, "wu_gpt1_clk"),

                    omap_findclk(s, "wu_l4_iclk"));

    s->gptimer[1] = omap_gp_timer_init(omap_l4ta(s->l4, 8),

                    s->irq[0][OMAP_INT_24XX_GPTIMER2],

                    omap_findclk(s, "core_gpt2_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[2] = omap_gp_timer_init(omap_l4ta(s->l4, 22),

                    s->irq[0][OMAP_INT_24XX_GPTIMER3],

                    omap_findclk(s, "core_gpt3_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[3] = omap_gp_timer_init(omap_l4ta(s->l4, 23),

                    s->irq[0][OMAP_INT_24XX_GPTIMER4],

                    omap_findclk(s, "core_gpt4_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[4] = omap_gp_timer_init(omap_l4ta(s->l4, 24),

                    s->irq[0][OMAP_INT_24XX_GPTIMER5],

                    omap_findclk(s, "core_gpt5_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[5] = omap_gp_timer_init(omap_l4ta(s->l4, 25),

                    s->irq[0][OMAP_INT_24XX_GPTIMER6],

                    omap_findclk(s, "core_gpt6_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[6] = omap_gp_timer_init(omap_l4ta(s->l4, 26),

                    s->irq[0][OMAP_INT_24XX_GPTIMER7],

                    omap_findclk(s, "core_gpt7_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[7] = omap_gp_timer_init(omap_l4ta(s->l4, 27),

                    s->irq[0][OMAP_INT_24XX_GPTIMER8],

                    omap_findclk(s, "core_gpt8_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[8] = omap_gp_timer_init(omap_l4ta(s->l4, 28),

                    s->irq[0][OMAP_INT_24XX_GPTIMER9],

                    omap_findclk(s, "core_gpt9_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[9] = omap_gp_timer_init(omap_l4ta(s->l4, 29),

                    s->irq[0][OMAP_INT_24XX_GPTIMER10],

                    omap_findclk(s, "core_gpt10_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[10] = omap_gp_timer_init(omap_l4ta(s->l4, 30),

                    s->irq[0][OMAP_INT_24XX_GPTIMER11],

                    omap_findclk(s, "core_gpt11_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[11] = omap_gp_timer_init(omap_l4ta(s->l4, 31),

                    s->irq[0][OMAP_INT_24XX_GPTIMER12],

                    omap_findclk(s, "core_gpt12_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    omap_tap_init(omap_l4ta(s->l4, 2), s);

    s->synctimer = omap_synctimer_init(omap_l4tao(s->l4, 2), s,

                    omap_findclk(s, "clk32-kHz"),

                    omap_findclk(s, "core_l4_iclk"));

    s->i2c[0] = omap2_i2c_init(omap_l4tao(s->l4, 5),

                    s->irq[0][OMAP_INT_24XX_I2C1_IRQ],

                    &s->drq[OMAP24XX_DMA_I2C1_TX],

                    omap_findclk(s, "i2c1.fclk"),

                    omap_findclk(s, "i2c1.iclk"));

    s->i2c[1] = omap2_i2c_init(omap_l4tao(s->l4, 6),

                    s->irq[0][OMAP_INT_24XX_I2C2_IRQ],

                    &s->drq[OMAP24XX_DMA_I2C2_TX],

                    omap_findclk(s, "i2c2.fclk"),

                    omap_findclk(s, "i2c2.iclk"));

    s->gpio = qdev_create(NULL, "omap2-gpio");

    qdev_prop_set_int32(s->gpio, "mpu_model", s->mpu_model);

    qdev_prop_set_ptr(s->gpio, "iclk", omap_findclk(s, "gpio_iclk"));

    qdev_prop_set_ptr(s->gpio, "fclk0", omap_findclk(s, "gpio1_dbclk"));

    qdev_prop_set_ptr(s->gpio, "fclk1", omap_findclk(s, "gpio2_dbclk"));

    qdev_prop_set_ptr(s->gpio, "fclk2", omap_findclk(s, "gpio3_dbclk"));

    qdev_prop_set_ptr(s->gpio, "fclk3", omap_findclk(s, "gpio4_dbclk"));

    if (s->mpu_model == omap2430) {

        qdev_prop_set_ptr(s->gpio, "fclk4", omap_findclk(s, "gpio5_dbclk"));

    }

    qdev_init_nofail(s->gpio);

    busdev = sysbus_from_qdev(s->gpio);

    sysbus_connect_irq(busdev, 0, s->irq[0][OMAP_INT_24XX_GPIO_BANK1]);

    sysbus_connect_irq(busdev, 3, s->irq[0][OMAP_INT_24XX_GPIO_BANK2]);

    sysbus_connect_irq(busdev, 6, s->irq[0][OMAP_INT_24XX_GPIO_BANK3]);

    sysbus_connect_irq(busdev, 9, s->irq[0][OMAP_INT_24XX_GPIO_BANK4]);

    ta = omap_l4ta(s->l4, 3);

    sysbus_mmio_map(busdev, 0, omap_l4_region_base(ta, 1));

    sysbus_mmio_map(busdev, 1, omap_l4_region_base(ta, 0));

    sysbus_mmio_map(busdev, 2, omap_l4_region_base(ta, 2));

    sysbus_mmio_map(busdev, 3, omap_l4_region_base(ta, 4));

    sysbus_mmio_map(busdev, 4, omap_l4_region_base(ta, 5));

    s->sdrc = omap_sdrc_init(0x68009000);

    s->gpmc = omap_gpmc_init(s, 0x6800a000, s->irq[0][OMAP_INT_24XX_GPMC_IRQ],

                             s->drq[OMAP24XX_DMA_GPMC]);

    dinfo = drive_get(IF_SD, 0, 0);

    if (!dinfo) {

        fprintf(stderr, "qemu: missing SecureDigital device\n");

        exit(1);

    }

    s->mmc = omap2_mmc_init(omap_l4tao(s->l4, 9), dinfo->bdrv,

                    s->irq[0][OMAP_INT_24XX_MMC_IRQ],

                    &s->drq[OMAP24XX_DMA_MMC1_TX],

                    omap_findclk(s, "mmc_fclk"), omap_findclk(s, "mmc_iclk"));

    s->mcspi[0] = omap_mcspi_init(omap_l4ta(s->l4, 35), 4,

                    s->irq[0][OMAP_INT_24XX_MCSPI1_IRQ],

                    &s->drq[OMAP24XX_DMA_SPI1_TX0],

                    omap_findclk(s, "spi1_fclk"),

                    omap_findclk(s, "spi1_iclk"));

    s->mcspi[1] = omap_mcspi_init(omap_l4ta(s->l4, 36), 2,

                    s->irq[0][OMAP_INT_24XX_MCSPI2_IRQ],

                    &s->drq[OMAP24XX_DMA_SPI2_TX0],

                    omap_findclk(s, "spi2_fclk"),

                    omap_findclk(s, "spi2_iclk"));

    s->dss = omap_dss_init(omap_l4ta(s->l4, 10), 0x68000800,

                    /* XXX wire M_IRQ_25, D_L2_IRQ_30 and I_IRQ_13 together */

                    s->irq[0][OMAP_INT_24XX_DSS_IRQ], s->drq[OMAP24XX_DMA_DSS],

                    omap_findclk(s, "dss_clk1"), omap_findclk(s, "dss_clk2"),

                    omap_findclk(s, "dss_54m_clk"),

                    omap_findclk(s, "dss_l3_iclk"),

                    omap_findclk(s, "dss_l4_iclk"));

    omap_sti_init(omap_l4ta(s->l4, 18), 0x54000000,

                    s->irq[0][OMAP_INT_24XX_STI], omap_findclk(s, "emul_ck"),

                    serial_hds[0] && serial_hds[1] && serial_hds[2] ?

                    serial_hds[3] : NULL);

    s->eac = omap_eac_init(omap_l4ta(s->l4, 32),

                    s->irq[0][OMAP_INT_24XX_EAC_IRQ],

                    /* Ten consecutive lines */

                    &s->drq[OMAP24XX_DMA_EAC_AC_RD],

                    omap_findclk(s, "func_96m_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    /* All register mappings (includin those not currenlty implemented):

     * SystemControlMod	48000000 - 48000fff

     * SystemControlL4	48001000 - 48001fff

     * 32kHz Timer Mod	48004000 - 48004fff

     * 32kHz Timer L4	48005000 - 48005fff

     * PRCM ModA	48008000 - 480087ff

     * PRCM ModB	48008800 - 48008fff

     * PRCM L4		48009000 - 48009fff

     * TEST-BCM Mod	48012000 - 48012fff

     * TEST-BCM L4	48013000 - 48013fff

     * TEST-TAP Mod	48014000 - 48014fff

     * TEST-TAP L4	48015000 - 48015fff

     * GPIO1 Mod	48018000 - 48018fff

     * GPIO Top		48019000 - 48019fff

     * GPIO2 Mod	4801a000 - 4801afff

     * GPIO L4		4801b000 - 4801bfff

     * GPIO3 Mod	4801c000 - 4801cfff

     * GPIO4 Mod	4801e000 - 4801efff

     * WDTIMER1 Mod	48020000 - 48010fff

     * WDTIMER Top	48021000 - 48011fff

     * WDTIMER2 Mod	48022000 - 48012fff

     * WDTIMER L4	48023000 - 48013fff

     * WDTIMER3 Mod	48024000 - 48014fff

     * WDTIMER3 L4	48025000 - 48015fff

     * WDTIMER4 Mod	48026000 - 48016fff

     * WDTIMER4 L4	48027000 - 48017fff

     * GPTIMER1 Mod	48028000 - 48018fff

     * GPTIMER1 L4	48029000 - 48019fff

     * GPTIMER2 Mod	4802a000 - 4801afff

     * GPTIMER2 L4	4802b000 - 4801bfff

     * L4-Config AP	48040000 - 480407ff

     * L4-Config IP	48040800 - 48040fff

     * L4-Config LA	48041000 - 48041fff

     * ARM11ETB Mod	48048000 - 48049fff

     * ARM11ETB L4	4804a000 - 4804afff

     * DISPLAY Top	48050000 - 480503ff

     * DISPLAY DISPC	48050400 - 480507ff

     * DISPLAY RFBI	48050800 - 48050bff

     * DISPLAY VENC	48050c00 - 48050fff

     * DISPLAY L4	48051000 - 48051fff

     * CAMERA Top	48052000 - 480523ff

     * CAMERA core	48052400 - 480527ff

     * CAMERA DMA	48052800 - 48052bff

     * CAMERA MMU	48052c00 - 48052fff

     * CAMERA L4	48053000 - 48053fff

     * SDMA Mod		48056000 - 48056fff

     * SDMA L4		48057000 - 48057fff

     * SSI Top		48058000 - 48058fff

     * SSI GDD		48059000 - 48059fff

     * SSI Port1	4805a000 - 4805afff

     * SSI Port2	4805b000 - 4805bfff

     * SSI L4		4805c000 - 4805cfff

     * USB Mod		4805e000 - 480fefff

     * USB L4		4805f000 - 480fffff

     * WIN_TRACER1 Mod	48060000 - 48060fff

     * WIN_TRACER1 L4	48061000 - 48061fff

     * WIN_TRACER2 Mod	48062000 - 48062fff

     * WIN_TRACER2 L4	48063000 - 48063fff

     * WIN_TRACER3 Mod	48064000 - 48064fff

     * WIN_TRACER3 L4	48065000 - 48065fff

     * WIN_TRACER4 Top	48066000 - 480660ff

     * WIN_TRACER4 ETT	48066100 - 480661ff

     * WIN_TRACER4 WT	48066200 - 480662ff

     * WIN_TRACER4 L4	48067000 - 48067fff

     * XTI Mod		48068000 - 48068fff

     * XTI L4		48069000 - 48069fff

     * UART1 Mod	4806a000 - 4806afff

     * UART1 L4		4806b000 - 4806bfff

     * UART2 Mod	4806c000 - 4806cfff

     * UART2 L4		4806d000 - 4806dfff

     * UART3 Mod	4806e000 - 4806efff

     * UART3 L4		4806f000 - 4806ffff

     * I2C1 Mod		48070000 - 48070fff

     * I2C1 L4		48071000 - 48071fff

     * I2C2 Mod		48072000 - 48072fff

     * I2C2 L4		48073000 - 48073fff

     * McBSP1 Mod	48074000 - 48074fff

     * McBSP1 L4	48075000 - 48075fff

     * McBSP2 Mod	48076000 - 48076fff

     * McBSP2 L4	48077000 - 48077fff

     * GPTIMER3 Mod	48078000 - 48078fff

     * GPTIMER3 L4	48079000 - 48079fff

     * GPTIMER4 Mod	4807a000 - 4807afff

     * GPTIMER4 L4	4807b000 - 4807bfff

     * GPTIMER5 Mod	4807c000 - 4807cfff

     * GPTIMER5 L4	4807d000 - 4807dfff

     * GPTIMER6 Mod	4807e000 - 4807efff

     * GPTIMER6 L4	4807f000 - 4807ffff

     * GPTIMER7 Mod	48080000 - 48080fff

     * GPTIMER7 L4	48081000 - 48081fff

     * GPTIMER8 Mod	48082000 - 48082fff

     * GPTIMER8 L4	48083000 - 48083fff

     * GPTIMER9 Mod	48084000 - 48084fff

     * GPTIMER9 L4	48085000 - 48085fff

     * GPTIMER10 Mod	48086000 - 48086fff

     * GPTIMER10 L4	48087000 - 48087fff

     * GPTIMER11 Mod	48088000 - 48088fff

     * GPTIMER11 L4	48089000 - 48089fff

     * GPTIMER12 Mod	4808a000 - 4808afff

     * GPTIMER12 L4	4808b000 - 4808bfff

     * EAC Mod		48090000 - 48090fff

     * EAC L4		48091000 - 48091fff

     * FAC Mod		48092000 - 48092fff

     * FAC L4		48093000 - 48093fff

     * MAILBOX Mod	48094000 - 48094fff

     * MAILBOX L4	48095000 - 48095fff

     * SPI1 Mod		48098000 - 48098fff

     * SPI1 L4		48099000 - 48099fff

     * SPI2 Mod		4809a000 - 4809afff

     * SPI2 L4		4809b000 - 4809bfff

     * MMC/SDIO Mod	4809c000 - 4809cfff

     * MMC/SDIO L4	4809d000 - 4809dfff

     * MS_PRO Mod	4809e000 - 4809efff

     * MS_PRO L4	4809f000 - 4809ffff

     * RNG Mod		480a0000 - 480a0fff

     * RNG L4		480a1000 - 480a1fff

     * DES3DES Mod	480a2000 - 480a2fff

     * DES3DES L4	480a3000 - 480a3fff

     * SHA1MD5 Mod	480a4000 - 480a4fff

     * SHA1MD5 L4	480a5000 - 480a5fff

     * AES Mod		480a6000 - 480a6fff

     * AES L4		480a7000 - 480a7fff

     * PKA Mod		480a8000 - 480a9fff

     * PKA L4		480aa000 - 480aafff

     * MG Mod		480b0000 - 480b0fff

     * MG L4		480b1000 - 480b1fff

     * HDQ/1-wire Mod	480b2000 - 480b2fff

     * HDQ/1-wire L4	480b3000 - 480b3fff

     * MPU interrupt	480fe000 - 480fefff

     * STI channel base	54000000 - 5400ffff

     * IVA RAM		5c000000 - 5c01ffff

     * IVA ROM		5c020000 - 5c027fff

     * IMG_BUF_A	5c040000 - 5c040fff

     * IMG_BUF_B	5c042000 - 5c042fff

     * VLCDS		5c048000 - 5c0487ff

     * IMX_COEF		5c049000 - 5c04afff

     * IMX_CMD		5c051000 - 5c051fff

     * VLCDQ		5c053000 - 5c0533ff

     * VLCDH		5c054000 - 5c054fff

     * SEQ_CMD		5c055000 - 5c055fff

     * IMX_REG		5c056000 - 5c0560ff

     * VLCD_REG		5c056100 - 5c0561ff

     * SEQ_REG		5c056200 - 5c0562ff

     * IMG_BUF_REG	5c056300 - 5c0563ff

     * SEQIRQ_REG	5c056400 - 5c0564ff

     * OCP_REG		5c060000 - 5c060fff

     * SYSC_REG		5c070000 - 5c070fff

     * MMU_REG		5d000000 - 5d000fff

     * sDMA R		68000400 - 680005ff

     * sDMA W		68000600 - 680007ff

     * Display Control	68000800 - 680009ff

     * DSP subsystem	68000a00 - 68000bff

     * MPU subsystem	68000c00 - 68000dff

     * IVA subsystem	68001000 - 680011ff

     * USB		68001200 - 680013ff

     * Camera		68001400 - 680015ff

     * VLYNQ (firewall)	68001800 - 68001bff

     * VLYNQ		68001e00 - 68001fff

     * SSI		68002000 - 680021ff

     * L4		68002400 - 680025ff

     * DSP (firewall)	68002800 - 68002bff

     * DSP subsystem	68002e00 - 68002fff

     * IVA (firewall)	68003000 - 680033ff

     * IVA		68003600 - 680037ff

     * GFX		68003a00 - 68003bff

     * CMDWR emulation	68003c00 - 68003dff

     * SMS		68004000 - 680041ff

     * OCM		68004200 - 680043ff

     * GPMC		68004400 - 680045ff

     * RAM (firewall)	68005000 - 680053ff

     * RAM (err login)	68005400 - 680057ff

     * ROM (firewall)	68005800 - 68005bff

     * ROM (err login)	68005c00 - 68005fff

     * GPMC (firewall)	68006000 - 680063ff

     * GPMC (err login)	68006400 - 680067ff

     * SMS (err login)	68006c00 - 68006fff

     * SMS registers	68008000 - 68008fff

     * SDRC registers	68009000 - 68009fff

     * GPMC registers	6800a000   6800afff

     */

    qemu_register_reset(omap2_mpu_reset, s);

    return s;

}


static void tcg_out_qemu_ld_slow_path (TCGContext *s, TCGLabelQemuLdst *label)

{

    int s_bits;

    int ir;

    int opc = label->opc;

    int mem_index = label->mem_index;

    int data_reg = label->datalo_reg;

    int data_reg2 = label->datahi_reg;

    int addr_reg = label->addrlo_reg;

    uint8_t *raddr = label->raddr;

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

    s_bits = opc & 3;

    /* resolve label address */

    reloc_pc14 (label_ptr[0], (tcg_target_long) s->code_ptr);

    /* slow path */

    ir = 3;

    tcg_out_mov (s, TCG_TYPE_I32, ir++, TCG_AREG0);

#if TARGET_LONG_BITS == 32

    tcg_out_mov (s, TCG_TYPE_I32, ir++, addr_reg);

#else

#ifdef TCG_TARGET_CALL_ALIGN_ARGS

    ir |= 1;

#endif

    tcg_out_mov (s, TCG_TYPE_I32, ir++, label->addrhi_reg);

    tcg_out_mov (s, TCG_TYPE_I32, ir++, addr_reg);

#endif

    tcg_out_movi (s, TCG_TYPE_I32, ir, mem_index);

    tcg_out_call (s, (tcg_target_long) qemu_ld_helpers[s_bits], 1);

    tcg_out32 (s, B | 8);

    tcg_out32 (s, (tcg_target_long) raddr);

    switch (opc) {

    case 0|4:

        tcg_out32 (s, EXTSB | RA (data_reg) | RS (3));

        break;

    case 1|4:

        tcg_out32 (s, EXTSH | RA (data_reg) | RS (3));

        break;

    case 0:

    case 1:

    case 2:

        if (data_reg != 3)

            tcg_out_mov (s, TCG_TYPE_I32, data_reg, 3);

        break;

    case 3:

        if (data_reg == 3) {

            if (data_reg2 == 4) {

                tcg_out_mov (s, TCG_TYPE_I32, 0, 4);

                tcg_out_mov (s, TCG_TYPE_I32, 4, 3);

                tcg_out_mov (s, TCG_TYPE_I32, 3, 0);

            }

            else {

                tcg_out_mov (s, TCG_TYPE_I32, data_reg2, 3);

                tcg_out_mov (s, TCG_TYPE_I32, 3, 4);

            }

        }

        else {

            if (data_reg != 4) tcg_out_mov (s, TCG_TYPE_I32, data_reg, 4);

            if (data_reg2 != 3) tcg_out_mov (s, TCG_TYPE_I32, data_reg2, 3);

        }

        break;

    }

    /* Jump to the code corresponding to next IR of qemu_st */

    tcg_out_b (s, 0, (tcg_target_long) raddr);

}


static int nbd_negotiate_handle_info(NBDClient *client, uint32_t length,

                                     uint32_t opt, uint16_t myflags,

                                     Error **errp)

{

    int rc;

    char name[NBD_MAX_NAME_SIZE + 1];

    NBDExport *exp;

    uint16_t requests;

    uint16_t request;

    uint32_t namelen;

    bool sendname = false;

    bool blocksize = false;

    uint32_t sizes[3];

    char buf[sizeof(uint64_t) + sizeof(uint16_t)];

    const char *msg;

    /* Client sends:

        4 bytes: L, name length (can be 0)

        L bytes: export name

        2 bytes: N, number of requests (can be 0)

        N * 2 bytes: N requests

    */

    if (length < sizeof(namelen) + sizeof(requests)) {

        msg = "overall request too short";

        goto invalid;

    }

    if (nbd_read(client->ioc, &namelen, sizeof(namelen), errp) < 0) {

        return -EIO;

    }

    be32_to_cpus(&namelen);

    length -= sizeof(namelen);

    if (namelen > length - sizeof(requests) || (length - namelen) % 2) {

        msg = "name length is incorrect";

        goto invalid;

    }

    if (nbd_read(client->ioc, name, namelen, errp) < 0) {

        return -EIO;

    }

    name[namelen] = '\0';

    length -= namelen;

    trace_nbd_negotiate_handle_export_name_request(name);

    if (nbd_read(client->ioc, &requests, sizeof(requests), errp) < 0) {

        return -EIO;

    }

    be16_to_cpus(&requests);

    length -= sizeof(requests);

    trace_nbd_negotiate_handle_info_requests(requests);

    if (requests != length / sizeof(request)) {

        msg = "incorrect number of  requests for overall length";

        goto invalid;

    }

    while (requests--) {

        if (nbd_read(client->ioc, &request, sizeof(request), errp) < 0) {

            return -EIO;

        }

        be16_to_cpus(&request);

        length -= sizeof(request);

        trace_nbd_negotiate_handle_info_request(request,

                                                nbd_info_lookup(request));

        /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;

         * everything else is either a request we don't know or

         * something we send regardless of request */

        switch (request) {

        case NBD_INFO_NAME:

            sendname = true;

            break;

        case NBD_INFO_BLOCK_SIZE:

            blocksize = true;

            break;

        }

    }

    exp = nbd_export_find(name);

    if (!exp) {

        return nbd_negotiate_send_rep_err(client->ioc, NBD_REP_ERR_UNKNOWN,

                                          opt, errp, "export '%s' not present",

                                          name);

    }

    /* Don't bother sending NBD_INFO_NAME unless client requested it */

    if (sendname) {

        rc = nbd_negotiate_send_info(client, opt, NBD_INFO_NAME, length, name,

                                     errp);

        if (rc < 0) {

            return rc;

        }

    }

    /* Send NBD_INFO_DESCRIPTION only if available, regardless of

     * client request */

    if (exp->description) {

        size_t len = strlen(exp->description);

        rc = nbd_negotiate_send_info(client, opt, NBD_INFO_DESCRIPTION,

                                     len, exp->description, errp);

        if (rc < 0) {

            return rc;

        }

    }

    /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size

     * according to whether the client requested it, and according to

     * whether this is OPT_INFO or OPT_GO. */

    /* minimum - 1 for back-compat, or 512 if client is new enough.

     * TODO: consult blk_bs(blk)->bl.request_alignment? */

    sizes[0] = (opt == NBD_OPT_INFO || blocksize) ? BDRV_SECTOR_SIZE : 1;

    /* preferred - Hard-code to 4096 for now.

     * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */

    sizes[1] = 4096;

    /* maximum - At most 32M, but smaller as appropriate. */

    sizes[2] = MIN(blk_get_max_transfer(exp->blk), NBD_MAX_BUFFER_SIZE);

    trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);

    cpu_to_be32s(&sizes[0]);

    cpu_to_be32s(&sizes[1]);

    cpu_to_be32s(&sizes[2]);

    rc = nbd_negotiate_send_info(client, opt, NBD_INFO_BLOCK_SIZE,

                                 sizeof(sizes), sizes, errp);

    if (rc < 0) {

        return rc;

    }

    /* Send NBD_INFO_EXPORT always */

    trace_nbd_negotiate_new_style_size_flags(exp->size,

                                             exp->nbdflags | myflags);

    stq_be_p(buf, exp->size);

    stw_be_p(buf + 8, exp->nbdflags | myflags);

    rc = nbd_negotiate_send_info(client, opt, NBD_INFO_EXPORT,

                                 sizeof(buf), buf, errp);

    if (rc < 0) {

        return rc;

    }

    /* If the client is just asking for NBD_OPT_INFO, but forgot to

     * request block sizes, return an error.

     * TODO: consult blk_bs(blk)->request_align, and only error if it

     * is not 1? */

    if (opt == NBD_OPT_INFO && !blocksize) {

        return nbd_negotiate_send_rep_err(client->ioc,

                                          NBD_REP_ERR_BLOCK_SIZE_REQD, opt,

                                          errp,

                                          "request NBD_INFO_BLOCK_SIZE to "

                                          "use this export");

    }

    /* Final reply */

    rc = nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, opt, errp);

    if (rc < 0) {

        return rc;

    }

    if (opt == NBD_OPT_GO) {

        client->exp = exp;

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

        nbd_export_get(client->exp);

        rc = 1;

    }

    return rc;

 invalid:

    if (nbd_drop(client->ioc, length, errp) < 0) {

        return -EIO;

    }

    return nbd_negotiate_send_rep_err(client->ioc, NBD_REP_ERR_INVALID, opt,

                                      errp, "%s", msg);

}


static int scsi_req_stream_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)

{

    switch (buf[0]) {

    /* stream commands */

    case ERASE_12:

    case ERASE_16:

        cmd->xfer = 0;

        break;

    case READ_6:

    case READ_REVERSE:

    case RECOVER_BUFFERED_DATA:

    case WRITE_6:

        cmd->len = 6;

        cmd->xfer = buf[4] | (buf[3] << 8) | (buf[2] << 16);

        if (buf[1] & 0x01) { /* fixed */

            cmd->xfer *= dev->blocksize;

        }

        break;

    case READ_16:

    case READ_REVERSE_16:

    case VERIFY_16:

    case WRITE_16:

        cmd->len = 16;

        cmd->xfer = buf[14] | (buf[13] << 8) | (buf[12] << 16);

        if (buf[1] & 0x01) { /* fixed */

            cmd->xfer *= dev->blocksize;

        }

        break;

    case REWIND:

    case LOAD_UNLOAD:

        cmd->len = 6;

        cmd->xfer = 0;

        break;

    case SPACE_16:

        cmd->xfer = buf[13] | (buf[12] << 8);

        break;

    case READ_POSITION:

        cmd->xfer = buf[8] | (buf[7] << 8);

        break;

    case FORMAT_UNIT:

        cmd->xfer = buf[4] | (buf[3] << 8);

        break;

    /* generic commands */

    default:

        return scsi_req_length(cmd, dev, buf);

    }

    return 0;

}


static void gen_tst_cc (DisasContext *dc, TCGv cc, int cond)

{

	int arith_opt, move_opt;

	/* TODO: optimize more condition codes.  */

	/*

	 * If the flags are live, we've gotta look into the bits of CCS.

	 * Otherwise, if we just did an arithmetic operation we try to

	 * evaluate the condition code faster.

	 *

	 * When this function is done, T0 should be non-zero if the condition

	 * code is true.

	 */

	arith_opt = arith_cc(dc) && !dc->flags_uptodate;

	move_opt = (dc->cc_op == CC_OP_MOVE) && dc->flags_uptodate;

	switch (cond) {

		case CC_EQ:

			if (arith_opt || move_opt) {

				/* If cc_result is zero, T0 should be

				   non-zero otherwise T0 should be zero.  */

				int l1;

				l1 = gen_new_label();

				tcg_gen_movi_tl(cc, 0);

				tcg_gen_brcondi_tl(TCG_COND_NE, cc_result,

						   0, l1);

				tcg_gen_movi_tl(cc, 1);

				gen_set_label(l1);

			}

			else {

				cris_evaluate_flags(dc);

				tcg_gen_andi_tl(cc,

						cpu_PR[PR_CCS], Z_FLAG);

			}

			break;

		case CC_NE:

			if (arith_opt || move_opt)

				tcg_gen_mov_tl(cc, cc_result);

			else {

				cris_evaluate_flags(dc);

				tcg_gen_xori_tl(cc, cpu_PR[PR_CCS],

						Z_FLAG);

				tcg_gen_andi_tl(cc, cc, Z_FLAG);

			}

			break;

		case CC_CS:

			cris_evaluate_flags(dc);

			tcg_gen_andi_tl(cc, cpu_PR[PR_CCS], C_FLAG);

			break;

		case CC_CC:

			cris_evaluate_flags(dc);

			tcg_gen_xori_tl(cc, cpu_PR[PR_CCS], C_FLAG);

			tcg_gen_andi_tl(cc, cc, C_FLAG);

			break;

		case CC_VS:

			cris_evaluate_flags(dc);

			tcg_gen_andi_tl(cc, cpu_PR[PR_CCS], V_FLAG);

			break;

		case CC_VC:

			cris_evaluate_flags(dc);

			tcg_gen_xori_tl(cc, cpu_PR[PR_CCS],

					V_FLAG);

			tcg_gen_andi_tl(cc, cc, V_FLAG);

			break;

		case CC_PL:

			if (arith_opt || move_opt) {

				int bits = 31;

				if (dc->cc_size == 1)

					bits = 7;

				else if (dc->cc_size == 2)

					bits = 15;

				tcg_gen_shri_tl(cc, cc_result, bits);

				tcg_gen_xori_tl(cc, cc, 1);

			} else {

				cris_evaluate_flags(dc);

				tcg_gen_xori_tl(cc, cpu_PR[PR_CCS],

						N_FLAG);

				tcg_gen_andi_tl(cc, cc, N_FLAG);

			}

			break;

		case CC_MI:

			if (arith_opt || move_opt) {

				int bits = 31;

				if (dc->cc_size == 1)

					bits = 7;

				else if (dc->cc_size == 2)

					bits = 15;

				tcg_gen_shri_tl(cc, cc_result, 31);

			}

			else {

				cris_evaluate_flags(dc);

				tcg_gen_andi_tl(cc, cpu_PR[PR_CCS],

						N_FLAG);

			}

			break;

		case CC_LS:

			cris_evaluate_flags(dc);

			tcg_gen_andi_tl(cc, cpu_PR[PR_CCS],

					C_FLAG | Z_FLAG);

			break;

		case CC_HI:

			cris_evaluate_flags(dc);

			{

				TCGv tmp;

				tmp = tcg_temp_new(TCG_TYPE_TL);

				tcg_gen_xori_tl(tmp, cpu_PR[PR_CCS],

						C_FLAG | Z_FLAG);

				/* Overlay the C flag on top of the Z.  */

				tcg_gen_shli_tl(cc, tmp, 2);

				tcg_gen_and_tl(cc, tmp, cc);

				tcg_gen_andi_tl(cc, cc, Z_FLAG);

				tcg_temp_free(tmp);

			}

			break;

		case CC_GE:

			cris_evaluate_flags(dc);

			/* Overlay the V flag on top of the N.  */

			tcg_gen_shli_tl(cc, cpu_PR[PR_CCS], 2);

			tcg_gen_xor_tl(cc,

				       cpu_PR[PR_CCS], cc);

			tcg_gen_andi_tl(cc, cc, N_FLAG);

			tcg_gen_xori_tl(cc, cc, N_FLAG);

			break;

		case CC_LT:

			cris_evaluate_flags(dc);

			/* Overlay the V flag on top of the N.  */

			tcg_gen_shli_tl(cc, cpu_PR[PR_CCS], 2);

			tcg_gen_xor_tl(cc,

				       cpu_PR[PR_CCS], cc);

			tcg_gen_andi_tl(cc, cc, N_FLAG);

			break;

		case CC_GT:

			cris_evaluate_flags(dc);

			{

				TCGv n, z;

				n = tcg_temp_new(TCG_TYPE_TL);

				z = tcg_temp_new(TCG_TYPE_TL);

				/* To avoid a shift we overlay everything on

				   the V flag.  */

				tcg_gen_shri_tl(n, cpu_PR[PR_CCS], 2);

				tcg_gen_shri_tl(z, cpu_PR[PR_CCS], 1);

				/* invert Z.  */

				tcg_gen_xori_tl(z, z, 2);

				tcg_gen_xor_tl(n, n, cpu_PR[PR_CCS]);

				tcg_gen_xori_tl(n, n, 2);

				tcg_gen_and_tl(cc, z, n);

				tcg_gen_andi_tl(cc, cc, 2);

				tcg_temp_free(n);

				tcg_temp_free(z);

			}

			break;

		case CC_LE:

			cris_evaluate_flags(dc);

			{

				TCGv n, z;

				n = tcg_temp_new(TCG_TYPE_TL);

				z = tcg_temp_new(TCG_TYPE_TL);

				/* To avoid a shift we overlay everything on

				   the V flag.  */

				tcg_gen_shri_tl(n, cpu_PR[PR_CCS], 2);

				tcg_gen_shri_tl(z, cpu_PR[PR_CCS], 1);

				tcg_gen_xor_tl(n, n, cpu_PR[PR_CCS]);

				tcg_gen_or_tl(cc, z, n);

				tcg_gen_andi_tl(cc, cc, 2);

				tcg_temp_free(n);

				tcg_temp_free(z);

			}

			break;

		case CC_P:

			cris_evaluate_flags(dc);

			tcg_gen_andi_tl(cc, cpu_PR[PR_CCS], P_FLAG);

			break;

		case CC_A:

			tcg_gen_movi_tl(cc, 1);

			break;

		default:

			BUG();

			break;

	};

}


void do_smm_enter(X86CPU *cpu)

{

    CPUX86State *env = &cpu->env;

    CPUState *cs = CPU(cpu);

    target_ulong sm_state;

    SegmentCache *dt;

    int i, offset;

    qemu_log_mask(CPU_LOG_INT, "SMM: enter\n");

    log_cpu_state_mask(CPU_LOG_INT, CPU(cpu), CPU_DUMP_CCOP);

    env->hflags |= HF_SMM_MASK;

    if (env->hflags2 & HF2_NMI_MASK) {

        env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;

    } else {

        env->hflags2 |= HF2_NMI_MASK;

    }

    cpu_smm_update(env);

    sm_state = env->smbase + 0x8000;

#ifdef TARGET_X86_64

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

        dt = &env->segs[i];

        offset = 0x7e00 + i * 16;

        x86_stw_phys(cs, sm_state + offset, dt->selector);

        x86_stw_phys(cs, sm_state + offset + 2, (dt->flags >> 8) & 0xf0ff);

        x86_stl_phys(cs, sm_state + offset + 4, dt->limit);

        x86_stq_phys(cs, sm_state + offset + 8, dt->base);

    }

    x86_stq_phys(cs, sm_state + 0x7e68, env->gdt.base);

    x86_stl_phys(cs, sm_state + 0x7e64, env->gdt.limit);

    x86_stw_phys(cs, sm_state + 0x7e70, env->ldt.selector);

    x86_stq_phys(cs, sm_state + 0x7e78, env->ldt.base);

    x86_stl_phys(cs, sm_state + 0x7e74, env->ldt.limit);

    x86_stw_phys(cs, sm_state + 0x7e72, (env->ldt.flags >> 8) & 0xf0ff);

    x86_stq_phys(cs, sm_state + 0x7e88, env->idt.base);

    x86_stl_phys(cs, sm_state + 0x7e84, env->idt.limit);

    x86_stw_phys(cs, sm_state + 0x7e90, env->tr.selector);

    x86_stq_phys(cs, sm_state + 0x7e98, env->tr.base);

    x86_stl_phys(cs, sm_state + 0x7e94, env->tr.limit);

    x86_stw_phys(cs, sm_state + 0x7e92, (env->tr.flags >> 8) & 0xf0ff);

    x86_stq_phys(cs, sm_state + 0x7ed0, env->efer);

    x86_stq_phys(cs, sm_state + 0x7ff8, env->regs[R_EAX]);

    x86_stq_phys(cs, sm_state + 0x7ff0, env->regs[R_ECX]);

    x86_stq_phys(cs, sm_state + 0x7fe8, env->regs[R_EDX]);

    x86_stq_phys(cs, sm_state + 0x7fe0, env->regs[R_EBX]);

    x86_stq_phys(cs, sm_state + 0x7fd8, env->regs[R_ESP]);

    x86_stq_phys(cs, sm_state + 0x7fd0, env->regs[R_EBP]);

    x86_stq_phys(cs, sm_state + 0x7fc8, env->regs[R_ESI]);

    x86_stq_phys(cs, sm_state + 0x7fc0, env->regs[R_EDI]);

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

        x86_stq_phys(cs, sm_state + 0x7ff8 - i * 8, env->regs[i]);

    }

    x86_stq_phys(cs, sm_state + 0x7f78, env->eip);

    x86_stl_phys(cs, sm_state + 0x7f70, cpu_compute_eflags(env));

    x86_stl_phys(cs, sm_state + 0x7f68, env->dr[6]);

    x86_stl_phys(cs, sm_state + 0x7f60, env->dr[7]);

    x86_stl_phys(cs, sm_state + 0x7f48, env->cr[4]);

    x86_stq_phys(cs, sm_state + 0x7f50, env->cr[3]);

    x86_stl_phys(cs, sm_state + 0x7f58, env->cr[0]);

    x86_stl_phys(cs, sm_state + 0x7efc, SMM_REVISION_ID);

    x86_stl_phys(cs, sm_state + 0x7f00, env->smbase);

#else

    x86_stl_phys(cs, sm_state + 0x7ffc, env->cr[0]);

    x86_stl_phys(cs, sm_state + 0x7ff8, env->cr[3]);

    x86_stl_phys(cs, sm_state + 0x7ff4, cpu_compute_eflags(env));

    x86_stl_phys(cs, sm_state + 0x7ff0, env->eip);

    x86_stl_phys(cs, sm_state + 0x7fec, env->regs[R_EDI]);

    x86_stl_phys(cs, sm_state + 0x7fe8, env->regs[R_ESI]);

    x86_stl_phys(cs, sm_state + 0x7fe4, env->regs[R_EBP]);

    x86_stl_phys(cs, sm_state + 0x7fe0, env->regs[R_ESP]);

    x86_stl_phys(cs, sm_state + 0x7fdc, env->regs[R_EBX]);

    x86_stl_phys(cs, sm_state + 0x7fd8, env->regs[R_EDX]);

    x86_stl_phys(cs, sm_state + 0x7fd4, env->regs[R_ECX]);

    x86_stl_phys(cs, sm_state + 0x7fd0, env->regs[R_EAX]);

    x86_stl_phys(cs, sm_state + 0x7fcc, env->dr[6]);

    x86_stl_phys(cs, sm_state + 0x7fc8, env->dr[7]);

    x86_stl_phys(cs, sm_state + 0x7fc4, env->tr.selector);

    x86_stl_phys(cs, sm_state + 0x7f64, env->tr.base);

    x86_stl_phys(cs, sm_state + 0x7f60, env->tr.limit);

    x86_stl_phys(cs, sm_state + 0x7f5c, (env->tr.flags >> 8) & 0xf0ff);

    x86_stl_phys(cs, sm_state + 0x7fc0, env->ldt.selector);

    x86_stl_phys(cs, sm_state + 0x7f80, env->ldt.base);

    x86_stl_phys(cs, sm_state + 0x7f7c, env->ldt.limit);

    x86_stl_phys(cs, sm_state + 0x7f78, (env->ldt.flags >> 8) & 0xf0ff);

    x86_stl_phys(cs, sm_state + 0x7f74, env->gdt.base);

    x86_stl_phys(cs, sm_state + 0x7f70, env->gdt.limit);

    x86_stl_phys(cs, sm_state + 0x7f58, env->idt.base);

    x86_stl_phys(cs, sm_state + 0x7f54, env->idt.limit);

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

        dt = &env->segs[i];

        if (i < 3) {

            offset = 0x7f84 + i * 12;

        } else {

            offset = 0x7f2c + (i - 3) * 12;

        }

        x86_stl_phys(cs, sm_state + 0x7fa8 + i * 4, dt->selector);

        x86_stl_phys(cs, sm_state + offset + 8, dt->base);

        x86_stl_phys(cs, sm_state + offset + 4, dt->limit);

        x86_stl_phys(cs, sm_state + offset, (dt->flags >> 8) & 0xf0ff);

    }

    x86_stl_phys(cs, sm_state + 0x7f14, env->cr[4]);

    x86_stl_phys(cs, sm_state + 0x7efc, SMM_REVISION_ID);

    x86_stl_phys(cs, sm_state + 0x7ef8, env->smbase);

#endif

    /* init SMM cpu state */

#ifdef TARGET_X86_64

    cpu_load_efer(env, 0);

#endif

    cpu_load_eflags(env, 0, ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C |

                              DF_MASK));

    env->eip = 0x00008000;

    cpu_x86_update_cr0(env,

                       env->cr[0] & ~(CR0_PE_MASK | CR0_EM_MASK | CR0_TS_MASK |

                                      CR0_PG_MASK));

    cpu_x86_update_cr4(env, 0);

    env->dr[7] = 0x00000400;

    cpu_x86_load_seg_cache(env, R_CS, (env->smbase >> 4) & 0xffff, env->smbase,

                           0xffffffff,

                           DESC_P_MASK | DESC_S_MASK | DESC_W_MASK |

                           DESC_A_MASK);

    cpu_x86_load_seg_cache(env, R_DS, 0, 0, 0xffffffff,

                           DESC_P_MASK | DESC_S_MASK | DESC_W_MASK |

                           DESC_A_MASK);

    cpu_x86_load_seg_cache(env, R_ES, 0, 0, 0xffffffff,

                           DESC_P_MASK | DESC_S_MASK | DESC_W_MASK |

                           DESC_A_MASK);

    cpu_x86_load_seg_cache(env, R_SS, 0, 0, 0xffffffff,

                           DESC_P_MASK | DESC_S_MASK | DESC_W_MASK |

                           DESC_A_MASK);

    cpu_x86_load_seg_cache(env, R_FS, 0, 0, 0xffffffff,

                           DESC_P_MASK | DESC_S_MASK | DESC_W_MASK |

                           DESC_A_MASK);

    cpu_x86_load_seg_cache(env, R_GS, 0, 0, 0xffffffff,

                           DESC_P_MASK | DESC_S_MASK | DESC_W_MASK |

                           DESC_A_MASK);

}


PCIDevice *pci_nic_init(NICInfo *nd, const char *default_model,

                        const char *default_devaddr)

{

    const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;

    PCIDevice *pci_dev;

    DeviceState *dev;

    int i;

    i = qemu_check_nic_model_list(nd, pci_nic_models, default_model);

    pci_dev = pci_create(pci_nic_names[i], devaddr);

    dev = &pci_dev->qdev;

    if (nd->id)

        dev->id = qemu_strdup(nd->id);

    dev->nd = nd;

    qdev_init(dev);

    nd->private = dev;

    return pci_dev;

}


void ff_mlp_init_x86(DSPContext* c, AVCodecContext *avctx)

{

#if HAVE_7REGS && HAVE_TEN_OPERANDS

    c->mlp_filter_channel = mlp_filter_channel_x86;

#endif

}


static av_cold int roq_encode_init(AVCodecContext *avctx)
{
    RoqContext *enc = avctx->priv_data;
    av_lfg_init(&enc->randctx, 1);
    enc->framesSinceKeyframe = 0;
    if ((avctx->width & 0xf) || (avctx->height & 0xf)) {
        av_log(avctx, AV_LOG_ERROR, "Dimensions must be divisible by 16\n");
        return AVERROR(EINVAL);
    if (avctx->width > 65535 || avctx->height > 65535) {
        av_log(avctx, AV_LOG_ERROR, "Dimensions are max %d\n", enc->quake3_compat ? 32768 : 65535);
        return AVERROR(EINVAL);
    if (((avctx->width)&(avctx->width-1))||((avctx->height)&(avctx->height-1)))
        av_log(avctx, AV_LOG_ERROR, "Warning: dimensions not power of two, this is not supported by quake\n");
    enc->width = avctx->width;
    enc->height = avctx->height;
    enc->framesSinceKeyframe = 0;
    enc->first_frame = 1;
    enc->last_frame    = av_frame_alloc();
    enc->current_frame = av_frame_alloc();
    if (!enc->last_frame || !enc->current_frame) {
    enc->tmpData      = av_malloc(sizeof(RoqTempdata));
    enc->this_motion4 =
        av_mallocz_array((enc->width*enc->height/16), sizeof(motion_vect));
    enc->last_motion4 =
        av_malloc_array ((enc->width*enc->height/16), sizeof(motion_vect));
    enc->this_motion8 =
        av_mallocz_array((enc->width*enc->height/64), sizeof(motion_vect));
    enc->last_motion8 =
        av_malloc_array ((enc->width*enc->height/64), sizeof(motion_vect));
    return 0;


void ff_h264_flush_change(H264Context *h)

{

    int i, j;

    h->next_outputed_poc = INT_MIN;

    h->prev_interlaced_frame = 1;

    idr(h);

    h->poc.prev_frame_num = -1;

    if (h->cur_pic_ptr) {

        h->cur_pic_ptr->reference = 0;

        for (j=i=0; h->delayed_pic[i]; i++)

            if (h->delayed_pic[i] != h->cur_pic_ptr)

                h->delayed_pic[j++] = h->delayed_pic[i];

        h->delayed_pic[j] = NULL;

    }

    ff_h264_unref_picture(h, &h->last_pic_for_ec);

    h->first_field = 0;

    ff_h264_sei_uninit(&h->sei);

    h->recovery_frame = -1;

    h->frame_recovered = 0;

    h->current_slice = 0;

    h->mmco_reset = 1;

    for (i = 0; i < h->nb_slice_ctx; i++)

        h->slice_ctx[i].list_count = 0;

}


static int av_set_number2(void *obj, const char *name, double num, int den, int64_t intnum, const AVOption **o_out)

{

    const AVOption *o = av_opt_find(obj, name, NULL, 0, 0);

    void *dst;

    if (o_out)

        *o_out= o;

    if (!o || o->offset<=0)

        return AVERROR_OPTION_NOT_FOUND;

    if (o->max*den < num*intnum || o->min*den > num*intnum) {

        av_log(obj, AV_LOG_ERROR, "Value %lf for parameter '%s' out of range\n", num, name);

        return AVERROR(ERANGE);

    }

    dst= ((uint8_t*)obj) + o->offset;

    switch (o->type) {

    case FF_OPT_TYPE_FLAGS:

    case FF_OPT_TYPE_INT:   *(int       *)dst= llrint(num/den)*intnum; break;

    case FF_OPT_TYPE_INT64: *(int64_t   *)dst= llrint(num/den)*intnum; break;

    case FF_OPT_TYPE_FLOAT: *(float     *)dst= num*intnum/den;         break;

    case FF_OPT_TYPE_DOUBLE:*(double    *)dst= num*intnum/den;         break;

    case FF_OPT_TYPE_RATIONAL:

        if ((int)num == num) *(AVRational*)dst= (AVRational){num*intnum, den};

        else                 *(AVRational*)dst= av_d2q(num*intnum/den, 1<<24);

        break;

    default:

        return AVERROR(EINVAL);

    }

    return 0;

}


static void qxl_realize_common(PCIQXLDevice *qxl, Error **errp)

{

    uint8_t* config = qxl->pci.config;

    uint32_t pci_device_rev;

    uint32_t io_size;

    qxl->mode = QXL_MODE_UNDEFINED;

    qxl->generation = 1;

    qxl->num_memslots = NUM_MEMSLOTS;

    qemu_mutex_init(&qxl->track_lock);

    qemu_mutex_init(&qxl->async_lock);

    qxl->current_async = QXL_UNDEFINED_IO;

    qxl->guest_bug = 0;

    switch (qxl->revision) {

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

        pci_device_rev = QXL_REVISION_STABLE_V04;

        io_size = 8;

        break;

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

        pci_device_rev = QXL_REVISION_STABLE_V06;

        io_size = 16;

        break;

    case 3: /* qxl-3 */

        pci_device_rev = QXL_REVISION_STABLE_V10;

        io_size = 32; /* PCI region size must be pow2 */

        break;

    case 4: /* qxl-4 */

        pci_device_rev = QXL_REVISION_STABLE_V12;

        io_size = pow2ceil(QXL_IO_RANGE_SIZE);

        break;

    default:

        error_setg(errp, "Invalid revision %d for qxl device (max %d)",

                   qxl->revision, QXL_DEFAULT_REVISION);

        return;

    }

    pci_set_byte(&config[PCI_REVISION_ID], pci_device_rev);

    pci_set_byte(&config[PCI_INTERRUPT_PIN], 1);

    qxl->rom_size = qxl_rom_size();

    memory_region_init_ram(&qxl->rom_bar, OBJECT(qxl), "qxl.vrom",

                           qxl->rom_size, &error_abort);

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

    init_qxl_rom(qxl);

    init_qxl_ram(qxl);

    qxl->guest_surfaces.cmds = g_new0(QXLPHYSICAL, qxl->ssd.num_surfaces);

    memory_region_init_ram(&qxl->vram_bar, OBJECT(qxl), "qxl.vram",

                           qxl->vram_size, &error_abort);

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

    memory_region_init_alias(&qxl->vram32_bar, OBJECT(qxl), "qxl.vram32",

                             &qxl->vram_bar, 0, qxl->vram32_size);

    memory_region_init_io(&qxl->io_bar, OBJECT(qxl), &qxl_io_ops, qxl,

                          "qxl-ioports", io_size);

    if (qxl->id == 0) {

        vga_dirty_log_start(&qxl->vga);

    }

    memory_region_set_flush_coalesced(&qxl->io_bar);

    pci_register_bar(&qxl->pci, QXL_IO_RANGE_INDEX,

                     PCI_BASE_ADDRESS_SPACE_IO, &qxl->io_bar);

    pci_register_bar(&qxl->pci, QXL_ROM_RANGE_INDEX,

                     PCI_BASE_ADDRESS_SPACE_MEMORY, &qxl->rom_bar);

    pci_register_bar(&qxl->pci, QXL_RAM_RANGE_INDEX,

                     PCI_BASE_ADDRESS_SPACE_MEMORY, &qxl->vga.vram);

    pci_register_bar(&qxl->pci, QXL_VRAM_RANGE_INDEX,

                     PCI_BASE_ADDRESS_SPACE_MEMORY, &qxl->vram32_bar);

    if (qxl->vram32_size < qxl->vram_size) {

        /*

         * Make the 64bit vram bar show up only in case it is

         * configured to be larger than the 32bit vram bar.

         */

        pci_register_bar(&qxl->pci, QXL_VRAM64_RANGE_INDEX,

                         PCI_BASE_ADDRESS_SPACE_MEMORY |

                         PCI_BASE_ADDRESS_MEM_TYPE_64 |

                         PCI_BASE_ADDRESS_MEM_PREFETCH,

                         &qxl->vram_bar);

    }

    /* print pci bar details */

    dprint(qxl, 1, "ram/%s: %d MB [region 0]\n",

           qxl->id == 0 ? "pri" : "sec",

           qxl->vga.vram_size / (1024*1024));

    dprint(qxl, 1, "vram/32: %d MB [region 1]\n",

           qxl->vram32_size / (1024*1024));

    dprint(qxl, 1, "vram/64: %d MB %s\n",

           qxl->vram_size / (1024*1024),

           qxl->vram32_size < qxl->vram_size ? "[region 4]" : "[unmapped]");

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

    if (qemu_spice_add_display_interface(&qxl->ssd.qxl, qxl->vga.con) != 0) {

        error_setg(errp, "qxl interface %d.%d not supported by spice-server",

                   SPICE_INTERFACE_QXL_MAJOR, SPICE_INTERFACE_QXL_MINOR);

        return;

    }

    qemu_add_vm_change_state_handler(qxl_vm_change_state_handler, qxl);

    qxl->update_irq = qemu_bh_new(qxl_update_irq_bh, qxl);

    qxl_reset_state(qxl);

    qxl->update_area_bh = qemu_bh_new(qxl_render_update_area_bh, qxl);

    qxl->ssd.cursor_bh = qemu_bh_new(qemu_spice_cursor_refresh_bh, &qxl->ssd);

}


static void vc1_inv_trans_8x4_dc_c(uint8_t *dest, int linesize, DCTELEM *block)

{

    int i;

    int dc = block[0];

    const uint8_t *cm;

    dc = ( 3 * dc +  1) >> 1;

    dc = (17 * dc + 64) >> 7;

    cm = ff_cropTbl + MAX_NEG_CROP + dc;

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

        dest[0] = cm[dest[0]];

        dest[1] = cm[dest[1]];

        dest[2] = cm[dest[2]];

        dest[3] = cm[dest[3]];

        dest[4] = cm[dest[4]];

        dest[5] = cm[dest[5]];

        dest[6] = cm[dest[6]];

        dest[7] = cm[dest[7]];

        dest += linesize;

    }

}


static always_inline uint8_t vc1_mspel_filter(const uint8_t *src, int stride, int mode, int r)

{

    switch(mode){

    case 0: //no shift

        return src[0];

    case 1: // 1/4 shift

        return (-4*src[-stride] + 53*src[0] + 18*src[stride] - 3*src[stride*2] + 32 - r) >> 6;

    case 2: // 1/2 shift

        return (-src[-stride] + 9*src[0] + 9*src[stride] - src[stride*2] + 8 - r) >> 4;

    case 3: // 3/4 shift

        return (-3*src[-stride] + 18*src[0] + 53*src[stride] - 4*src[stride*2] + 32 - r) >> 6;

    }

    return 0; //should not occur

}


static uint64_t openpic_tmr_read(void *opaque, hwaddr addr, unsigned len)

{

    OpenPICState *opp = opaque;

    uint32_t retval = -1;

    int idx;

    DPRINTF("%s: addr %08x\n", __func__, addr);

    if (addr & 0xF) {

        goto out;

    }

    idx = (addr >> 6) & 0x3;

    if (addr == 0x0) {

        /* TIFR (TFRR) */

        retval = opp->tifr;

        goto out;

    }

    switch (addr & 0x30) {

    case 0x00: /* TICC (GTCCR) */

        retval = opp->timers[idx].ticc;

        break;

    case 0x10: /* TIBC (GTBCR) */

        retval = opp->timers[idx].tibc;

        break;

    case 0x20: /* TIPV (TIPV) */

        retval = read_IRQreg_ipvp(opp, opp->irq_tim0 + idx);

        break;

    case 0x30: /* TIDE (TIDR) */

        retval = read_IRQreg_ide(opp, opp->irq_tim0 + idx);

        break;

    }

out:

    DPRINTF("%s: => %08x\n", __func__, retval);

    return retval;

}


static void gen_exception_insn(DisasContext *s, int offset, int excp)

{

    gen_a64_set_pc_im(s->pc - offset);

    gen_exception(excp);

    s->is_jmp = DISAS_JUMP;

}


static QDict *qmp_dispatch_check_obj(const QObject *request, Error **errp)

{

    const QDictEntry *ent;

    const char *arg_name;

    const QObject *arg_obj;

    bool has_exec_key = false;

    QDict *dict = NULL;

    if (qobject_type(request) != QTYPE_QDICT) {

        error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT,

                   "request is not a dictionary");

        return NULL;

    }

    dict = qobject_to_qdict(request);

    for (ent = qdict_first(dict); ent;

         ent = qdict_next(dict, ent)) {

        arg_name = qdict_entry_key(ent);

        arg_obj = qdict_entry_value(ent);

        if (!strcmp(arg_name, "execute")) {

            if (qobject_type(arg_obj) != QTYPE_QSTRING) {

                error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "execute",

                           "string");

                return NULL;

            }

            has_exec_key = true;

        } else if (strcmp(arg_name, "arguments")) {

            error_setg(errp, QERR_QMP_EXTRA_MEMBER, arg_name);

            return NULL;

        }

    }

    if (!has_exec_key) {

        error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");

        return NULL;

    }

    return dict;

}


static int get_int64(QEMUFile *f, void *pv, size_t size)

{

    int64_t *v = pv;

    qemu_get_sbe64s(f, v);

    return 0;

}


static void acpi_build_update(void *build_opaque, uint32_t offset)

{

    AcpiBuildState *build_state = build_opaque;

    AcpiBuildTables tables;

    /* No state to update or already patched? Nothing to do. */

    if (!build_state || build_state->patched) {

        return;

    }

    build_state->patched = 1;

    acpi_build_tables_init(&tables);

    acpi_build(build_state->guest_info, &tables);

    assert(acpi_data_len(tables.table_data) == build_state->table_size);

    memcpy(build_state->table_ram, tables.table_data->data,

           build_state->table_size);

    acpi_build_tables_cleanup(&tables, true);

}


static av_cold int amr_nb_encode_init(AVCodecContext *avctx)

{

    AMRContext *s = avctx->priv_data;

    if (avctx->sample_rate != 8000) {

        av_log(avctx, AV_LOG_ERROR, "Only 8000Hz sample rate supported\n");

        return AVERROR(ENOSYS);

    }

    if (avctx->channels != 1) {

        av_log(avctx, AV_LOG_ERROR, "Only mono supported\n");

        return AVERROR(ENOSYS);

    }

    avctx->frame_size  = 160;

    avctx->coded_frame = avcodec_alloc_frame();

    s->enc_state = Encoder_Interface_init(s->enc_dtx);

    if (!s->enc_state) {

        av_log(avctx, AV_LOG_ERROR, "Encoder_Interface_init error\n");

        return -1;

    }

    s->enc_mode    = get_bitrate_mode(avctx->bit_rate, avctx);

    s->enc_bitrate = avctx->bit_rate;

    return 0;

}


void help(void)

{

    printf("dct-test [-i] [<test-number>]\n"

           "test-number 0 -> test with random matrixes\n"

           "            1 -> test with random sparse matrixes\n"

           "            2 -> do 3. test from mpeg4 std\n"

           "-i          test IDCT implementations\n"

           "-4          test IDCT248 implementations\n");

    exit(1);

}


static int get_num(ByteIOContext *pb, int *len)

{

    int n, n1;

    n = get_be16(pb);

    (*len)-=2;

//    n &= 0x7FFF;

    if (n >= 0x4000) {

        return n - 0x4000;

    } else {

        n1 = get_be16(pb);

        (*len)-=2;

        return (n << 16) | n1;

    }

}


CPUState *ppc440ep_init(MemoryRegion *address_space_mem, ram_addr_t *ram_size,

                        PCIBus **pcip, const unsigned int pci_irq_nrs[4],

                        int do_init, const char *cpu_model)

{

    MemoryRegion *ram_memories

        = g_malloc(PPC440EP_SDRAM_NR_BANKS * sizeof(*ram_memories));

    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_booke_timers_init(env, 400000000, 0);

    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_memories,

                                    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_memories,

                      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(address_space_mem, 0xef600300, 0, pic[0],

                       PPC_SERIAL_MM_BAUDBASE, serial_hds[0],

                       DEVICE_BIG_ENDIAN);

    }

    if (serial_hds[1] != NULL) {

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

                       PPC_SERIAL_MM_BAUDBASE, serial_hds[1],

                       DEVICE_BIG_ENDIAN);

    }

    return env;

}


static int piix4_initfn(PCIDevice *dev)

{

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

    uint8_t *pci_conf;

    isa_bus_new(&d->dev.qdev);

    pci_conf = d->dev.config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_INTEL_82371AB_0); // 82371AB/EB/MB PIIX4 PCI-to-ISA bridge

    pci_config_set_class(pci_conf, PCI_CLASS_BRIDGE_ISA);

    piix4_dev = &d->dev;

    qemu_register_reset(piix4_reset, d);

    return 0;

}


static void FUNCC(ff_h264_add_pixels8)(uint8_t *_dst, int16_t *_src, int stride)

{

    int i;

    pixel *dst = (pixel *) _dst;

    dctcoef *src = (dctcoef *) _src;

    stride /= sizeof(pixel);

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

        dst[0] += src[0];

        dst[1] += src[1];

        dst[2] += src[2];

        dst[3] += src[3];

        dst[4] += src[4];

        dst[5] += src[5];

        dst[6] += src[6];

        dst[7] += src[7];

        dst += stride;

        src += 8;

    }

    memset(_src, 0, sizeof(dctcoef) * 64);

}


static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)

{

    int i;

    int ret = av_frame_ref(dst, src);

    if (ret < 0)

        return ret;

    if (!h->sps.crop)

        return 0;

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

        int hshift = (i > 0) ? h->chroma_x_shift : 0;

        int vshift = (i > 0) ? h->chroma_y_shift : 0;

        int off    = ((h->sps.crop_left >> hshift) << h->pixel_shift) +

            (h->sps.crop_top  >> vshift) * dst->linesize[i];

        dst->data[i] += off;

    }

    return 0;

}


void throttle_account(ThrottleState *ts, bool is_write, uint64_t size)

{

    double units = 1.0;

    /* if cfg.op_size is defined and smaller than size we compute unit count */

    if (ts->cfg.op_size && size > ts->cfg.op_size) {

        units = (double) size / ts->cfg.op_size;

    }

    ts->cfg.buckets[THROTTLE_BPS_TOTAL].level += size;

    ts->cfg.buckets[THROTTLE_OPS_TOTAL].level += units;

    if (is_write) {

        ts->cfg.buckets[THROTTLE_BPS_WRITE].level += size;

        ts->cfg.buckets[THROTTLE_OPS_WRITE].level += units;

    } else {

        ts->cfg.buckets[THROTTLE_BPS_READ].level += size;

        ts->cfg.buckets[THROTTLE_OPS_READ].level += units;

    }

}


void bdrv_remove_aio_context_notifier(BlockDriverState *bs,

                                      void (*attached_aio_context)(AioContext *,

                                                                   void *),

                                      void (*detach_aio_context)(void *),

                                      void *opaque)

{

    BdrvAioNotifier *ban, *ban_next;

    QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {

        if (ban->attached_aio_context == attached_aio_context &&

            ban->detach_aio_context   == detach_aio_context   &&

            ban->opaque               == opaque)

        {

            QLIST_REMOVE(ban, list);

            g_free(ban);

            return;

        }

    }

    abort();

}


static void gen_addq_lo(DisasContext *s, TCGv_i64 val, int rlow)

{

    TCGv_i64 tmp;

    TCGv tmp2;

    /* Load value and extend to 64 bits.  */

    tmp = tcg_temp_new_i64();

    tmp2 = load_reg(s, rlow);

    tcg_gen_extu_i32_i64(tmp, tmp2);

    dead_tmp(tmp2);

    tcg_gen_add_i64(val, val, tmp);

    tcg_temp_free_i64(tmp);

}


static void test_bmdma_simple_rw(void)

{

    QPCIDevice *dev;

    void *bmdma_base, *ide_base;

    uint8_t status;

    uint8_t *buf;

    uint8_t *cmpbuf;

    size_t len = 512;

    uintptr_t guest_buf = guest_alloc(guest_malloc, len);

    PrdtEntry prdt[] = {

        {

            .addr = cpu_to_le32(guest_buf),

            .size = cpu_to_le32(len | PRDT_EOT),

        },

    };

    dev = get_pci_device(&bmdma_base, &ide_base);

    buf = g_malloc(len);

    cmpbuf = g_malloc(len);

    /* Write 0x55 pattern to sector 0 */

    memset(buf, 0x55, len);

    memwrite(guest_buf, buf, len);

    status = send_dma_request(CMD_WRITE_DMA, 0, 1, prdt,

                              ARRAY_SIZE(prdt), NULL);

    g_assert_cmphex(status, ==, BM_STS_INTR);

    assert_bit_clear(qpci_io_readb(dev, ide_base + reg_status), DF | ERR);

    /* Write 0xaa pattern to sector 1 */

    memset(buf, 0xaa, len);

    memwrite(guest_buf, buf, len);

    status = send_dma_request(CMD_WRITE_DMA, 1, 1, prdt,

                              ARRAY_SIZE(prdt), NULL);

    g_assert_cmphex(status, ==, BM_STS_INTR);

    assert_bit_clear(qpci_io_readb(dev, ide_base + reg_status), DF | ERR);

    /* Read and verify 0x55 pattern in sector 0 */

    memset(cmpbuf, 0x55, len);

    status = send_dma_request(CMD_READ_DMA, 0, 1, prdt, ARRAY_SIZE(prdt), NULL);

    g_assert_cmphex(status, ==, BM_STS_INTR);

    assert_bit_clear(qpci_io_readb(dev, ide_base + reg_status), DF | ERR);

    memread(guest_buf, buf, len);

    g_assert(memcmp(buf, cmpbuf, len) == 0);

    /* Read and verify 0xaa pattern in sector 1 */

    memset(cmpbuf, 0xaa, len);

    status = send_dma_request(CMD_READ_DMA, 1, 1, prdt, ARRAY_SIZE(prdt), NULL);

    g_assert_cmphex(status, ==, BM_STS_INTR);

    assert_bit_clear(qpci_io_readb(dev, ide_base + reg_status), DF | ERR);

    memread(guest_buf, buf, len);

    g_assert(memcmp(buf, cmpbuf, len) == 0);

    g_free(buf);

    g_free(cmpbuf);

}


static int idcin_read_packet(AVFormatContext *s,

                             AVPacket *pkt)

{

    int ret;

    unsigned int command;

    unsigned int chunk_size;

    IdcinDemuxContext *idcin = s->priv_data;

    AVIOContext *pb = s->pb;

    int i;

    int palette_scale;

    unsigned char r, g, b;

    unsigned char palette_buffer[768];

    uint32_t palette[256];

    if (s->pb->eof_reached)

        return AVERROR(EIO);

    if (idcin->next_chunk_is_video) {

        command = avio_rl32(pb);

        if (command == 2) {

            return AVERROR(EIO);

        } else if (command == 1) {

            /* trigger a palette change */

            if (avio_read(pb, palette_buffer, 768) != 768)

                return AVERROR(EIO);

            /* scale the palette as necessary */

            palette_scale = 2;

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

                if (palette_buffer[i] > 63) {

                    palette_scale = 0;

                    break;

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

                r = palette_buffer[i * 3    ] << palette_scale;

                g = palette_buffer[i * 3 + 1] << palette_scale;

                b = palette_buffer[i * 3 + 2] << palette_scale;

                palette[i] = (r << 16) | (g << 8) | (b);

        chunk_size = avio_rl32(pb);

        /* skip the number of decoded bytes (always equal to width * height) */

        avio_skip(pb, 4);

        chunk_size -= 4;

        ret= av_get_packet(pb, pkt, chunk_size);

        if (ret < 0)

            return ret;

        if (command == 1) {

            uint8_t *pal;

            pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE,

                                          AVPALETTE_SIZE);

            if (ret < 0)

                return ret;

            memcpy(pal, palette, AVPALETTE_SIZE);

            pkt->flags |= AV_PKT_FLAG_KEY;

        pkt->stream_index = idcin->video_stream_index;

        pkt->duration     = 1;

    } else {

        /* send out the audio chunk */

        if (idcin->current_audio_chunk)

            chunk_size = idcin->audio_chunk_size2;

        else

            chunk_size = idcin->audio_chunk_size1;

        ret= av_get_packet(pb, pkt, chunk_size);

        if (ret < 0)

            return ret;

        pkt->stream_index = idcin->audio_stream_index;

        pkt->duration     = chunk_size / idcin->block_align;

        idcin->current_audio_chunk ^= 1;

    if (idcin->audio_present)

        idcin->next_chunk_is_video ^= 1;

    return ret;


static inline void RENAME(yuv2rgb555_2)(SwsContext *c, const uint16_t *buf0,

                                        const uint16_t *buf1, const uint16_t *ubuf0,

                                        const uint16_t *ubuf1, const uint16_t *vbuf0,

                                        const uint16_t *vbuf1, const uint16_t *abuf0,

                                        const uint16_t *abuf1, uint8_t *dest,

                                        int dstW, int yalpha, int uvalpha, int y)

{

    x86_reg uv_off = c->uv_off << 1;

    //Note 8280 == DSTW_OFFSET but the preprocessor can't handle that there :(

    __asm__ volatile(

        "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

        "mov        %4, %%"REG_b"               \n\t"

        "push %%"REG_BP"                        \n\t"

        YSCALEYUV2RGB(%%REGBP, %5, %6)

        "pxor    %%mm7, %%mm7                   \n\t"

        /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

        "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"

        "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"

        "paddusb "RED_DITHER"(%5), %%mm5      \n\t"

#endif

        WRITERGB15(%%REGb, 8280(%5), %%REGBP)

        "pop %%"REG_BP"                         \n\t"

        "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

        :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

           "a" (&c->redDither), "m"(uv_off)

    );

}


static VirtIOBlockReq *virtio_blk_get_request(VirtIOBlock *s)

{

    VirtIOBlockReq *req = virtio_blk_alloc_request(s);

    if (!virtqueue_pop(s->vq, &req->elem)) {

        virtio_blk_free_request(req);

        return NULL;

    }

    return req;

}


static int output_packet(InputStream *ist, const AVPacket *pkt)

{

    int ret = 0, i;

    int got_output;

    AVPacket avpkt;

    if (!ist->saw_first_ts) {

        ist->dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;

        ist->pts = 0;

        if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {

            ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);

            ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong

        }

        ist->saw_first_ts = 1;

    }

    if (ist->next_dts == AV_NOPTS_VALUE)

        ist->next_dts = ist->dts;

    if (ist->next_pts == AV_NOPTS_VALUE)

        ist->next_pts = ist->pts;

    if (pkt == NULL) {

        /* EOF handling */

        av_init_packet(&avpkt);

        avpkt.data = NULL;

        avpkt.size = 0;

        goto handle_eof;

    } else {

        avpkt = *pkt;

    }

    if (pkt->dts != AV_NOPTS_VALUE) {

        ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);

        if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)

            ist->next_pts = ist->pts = ist->dts;

    }

    // while we have more to decode or while the decoder did output something on EOF

    while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {

        int duration;

    handle_eof:

        ist->pts = ist->next_pts;

        ist->dts = ist->next_dts;

        if (avpkt.size && avpkt.size != pkt->size) {

            av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,

                   "Multiple frames in a packet from stream %d\n", pkt->stream_index);

            ist->showed_multi_packet_warning = 1;

        }

        switch (ist->st->codec->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            ret = decode_audio    (ist, &avpkt, &got_output);

            break;

        case AVMEDIA_TYPE_VIDEO:

            ret = decode_video    (ist, &avpkt, &got_output);

            if (avpkt.duration) {

                duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);

            } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {

                int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;

                duration = ((int64_t)AV_TIME_BASE *

                                ist->st->codec->time_base.num * ticks) /

                                ist->st->codec->time_base.den;

            } else

                duration = 0;

            if(ist->dts != AV_NOPTS_VALUE && duration) {

                ist->next_dts += duration;

            }else

                ist->next_dts = AV_NOPTS_VALUE;

            if (got_output)

                ist->next_pts += duration; //FIXME the duration is not correct in some cases

            break;

        case AVMEDIA_TYPE_SUBTITLE:

            ret = transcode_subtitles(ist, &avpkt, &got_output);

            break;

        default:

            return -1;

        }

        if (ret < 0)

            return ret;

        avpkt.dts=

        avpkt.pts= AV_NOPTS_VALUE;

        // touch data and size only if not EOF

        if (pkt) {

            if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)

                ret = avpkt.size;

            avpkt.data += ret;

            avpkt.size -= ret;

        }

        if (!got_output) {

            continue;

        }

    }

    /* handle stream copy */

    if (!ist->decoding_needed) {

        rate_emu_sleep(ist);

        ist->dts = ist->next_dts;

        switch (ist->st->codec->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /

                             ist->st->codec->sample_rate;

            break;

        case AVMEDIA_TYPE_VIDEO:

            if (pkt->duration) {

                ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);

            } else if(ist->st->codec->time_base.num != 0) {

                int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;

                ist->next_dts += ((int64_t)AV_TIME_BASE *

                                  ist->st->codec->time_base.num * ticks) /

                                  ist->st->codec->time_base.den;

            }

            break;

        }

        ist->pts = ist->dts;

        ist->next_pts = ist->next_dts;

    }

    for (i = 0; pkt && i < nb_output_streams; i++) {

        OutputStream *ost = output_streams[i];

        if (!check_output_constraints(ist, ost) || ost->encoding_needed)

            continue;

        do_streamcopy(ist, ost, pkt);

    }

    return 0;

}


void qemu_system_reset(void)

{

    QEMUResetEntry *re, *nre;

    /* reset all devices */

    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {

        re->func(re->opaque);

    }

}


static void sd_reset(SDState *sd, BlockDriverState *bdrv)

{

    uint64_t size;

    uint64_t sect;

    if (bdrv) {

        bdrv_get_geometry(bdrv, &sect);

    } else {

        sect = 0;

    }

    size = sect << 9;

    sect = (size >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT)) + 1;

    sd->state = sd_idle_state;

    sd->rca = 0x0000;

    sd_set_ocr(sd);

    sd_set_scr(sd);

    sd_set_cid(sd);

    sd_set_csd(sd, size);

    sd_set_cardstatus(sd);

    sd_set_sdstatus(sd);

    sd->bdrv = bdrv;

    if (sd->wp_groups)

        g_free(sd->wp_groups);

    sd->wp_switch = bdrv ? bdrv_is_read_only(bdrv) : 0;

    sd->wp_groups = (int *) g_malloc0(sizeof(int) * sect);

    memset(sd->function_group, 0, sizeof(int) * 6);

    sd->erase_start = 0;

    sd->erase_end = 0;

    sd->size = size;

    sd->blk_len = 0x200;

    sd->pwd_len = 0;

    sd->expecting_acmd = 0;

}


static void phys_page_set(AddressSpaceDispatch *d,

                          target_phys_addr_t index, target_phys_addr_t nb,

                          uint16_t leaf)

{

    /* Wildly overreserve - it doesn't matter much. */

    phys_map_node_reserve(3 * P_L2_LEVELS);

    phys_page_set_level(&d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);

}


static inline void tcg_out_op(TCGContext *s, TCGOpcode opc, const TCGArg *args,

                              const int *const_args)

{

    int c;

    switch (opc) {

    case INDEX_op_exit_tb:

        if (check_fit_tl(args[0], 13)) {

            tcg_out_arithi(s, TCG_REG_G0, TCG_REG_I7, 8, RETURN);

            tcg_out_movi_imm13(s, TCG_REG_O0, args[0]);

        } else {

            tcg_out_movi(s, TCG_TYPE_PTR, TCG_REG_I0, args[0] & ~0x3ff);

            tcg_out_arithi(s, TCG_REG_G0, TCG_REG_I7, 8, RETURN);

            tcg_out_arithi(s, TCG_REG_O0, TCG_REG_O0,

                           args[0] & 0x3ff, ARITH_OR);

        }

        break;

    case INDEX_op_goto_tb:

        if (s->tb_jmp_offset) {

            /* direct jump method */

            uint32_t old_insn = *(uint32_t *)s->code_ptr;

            s->tb_jmp_offset[args[0]] = s->code_ptr - s->code_buf;

            /* Make sure to preserve links during retranslation.  */

            tcg_out32(s, CALL | (old_insn & ~INSN_OP(-1)));

        } else {

            /* indirect jump method */

            tcg_out_ld_ptr(s, TCG_REG_T1, (uintptr_t)(s->tb_next + args[0]));

            tcg_out_arithi(s, TCG_REG_G0, TCG_REG_T1, 0, JMPL);

        }

        tcg_out_nop(s);

        s->tb_next_offset[args[0]] = s->code_ptr - s->code_buf;

        break;

    case INDEX_op_call:

        if (const_args[0]) {

            tcg_out_calli(s, args[0]);

        } else {

            tcg_out_arithi(s, TCG_REG_O7, args[0], 0, JMPL);

        }

        /* delay slot */

        tcg_out_nop(s);

        break;

    case INDEX_op_br:

        tcg_out_bpcc(s, COND_A, BPCC_PT, args[0]);

        tcg_out_nop(s);

        break;

    case INDEX_op_movi_i32:

        tcg_out_movi(s, TCG_TYPE_I32, args[0], (uint32_t)args[1]);

        break;

#define OP_32_64(x)                             \

        glue(glue(case INDEX_op_, x), _i32):    \

        glue(glue(case INDEX_op_, x), _i64)

    OP_32_64(ld8u):

        tcg_out_ldst(s, args[0], args[1], args[2], LDUB);

        break;

    OP_32_64(ld8s):

        tcg_out_ldst(s, args[0], args[1], args[2], LDSB);

        break;

    OP_32_64(ld16u):

        tcg_out_ldst(s, args[0], args[1], args[2], LDUH);

        break;

    OP_32_64(ld16s):

        tcg_out_ldst(s, args[0], args[1], args[2], LDSH);

        break;

    case INDEX_op_ld_i32:

    case INDEX_op_ld32u_i64:

        tcg_out_ldst(s, args[0], args[1], args[2], LDUW);

        break;

    OP_32_64(st8):

        tcg_out_ldst(s, args[0], args[1], args[2], STB);

        break;

    OP_32_64(st16):

        tcg_out_ldst(s, args[0], args[1], args[2], STH);

        break;

    case INDEX_op_st_i32:

    case INDEX_op_st32_i64:

        tcg_out_ldst(s, args[0], args[1], args[2], STW);

        break;

    OP_32_64(add):

        c = ARITH_ADD;

        goto gen_arith;

    OP_32_64(sub):

        c = ARITH_SUB;

        goto gen_arith;

    OP_32_64(and):

        c = ARITH_AND;

        goto gen_arith;

    OP_32_64(andc):

        c = ARITH_ANDN;

        goto gen_arith;

    OP_32_64(or):

        c = ARITH_OR;

        goto gen_arith;

    OP_32_64(orc):

        c = ARITH_ORN;

        goto gen_arith;

    OP_32_64(xor):

        c = ARITH_XOR;

        goto gen_arith;

    case INDEX_op_shl_i32:

        c = SHIFT_SLL;

    do_shift32:

        /* Limit immediate shift count lest we create an illegal insn.  */

        tcg_out_arithc(s, args[0], args[1], args[2] & 31, const_args[2], c);

        break;

    case INDEX_op_shr_i32:

        c = SHIFT_SRL;

        goto do_shift32;

    case INDEX_op_sar_i32:

        c = SHIFT_SRA;

        goto do_shift32;

    case INDEX_op_mul_i32:

        c = ARITH_UMUL;

        goto gen_arith;

    OP_32_64(neg):

	c = ARITH_SUB;

	goto gen_arith1;

    OP_32_64(not):

	c = ARITH_ORN;

	goto gen_arith1;

    case INDEX_op_div_i32:

        tcg_out_div32(s, args[0], args[1], args[2], const_args[2], 0);

        break;

    case INDEX_op_divu_i32:

        tcg_out_div32(s, args[0], args[1], args[2], const_args[2], 1);

        break;

    case INDEX_op_brcond_i32:

        tcg_out_brcond_i32(s, args[2], args[0], args[1], const_args[1],

                           args[3]);

        break;

    case INDEX_op_setcond_i32:

        tcg_out_setcond_i32(s, args[3], args[0], args[1],

                            args[2], const_args[2]);

        break;

    case INDEX_op_movcond_i32:

        tcg_out_movcond_i32(s, args[5], args[0], args[1],

                            args[2], const_args[2], args[3], const_args[3]);

        break;

    case INDEX_op_add2_i32:

        tcg_out_addsub2(s, args[0], args[1], args[2], args[3],

                        args[4], const_args[4], args[5], const_args[5],

                        ARITH_ADDCC, ARITH_ADDX);

        break;

    case INDEX_op_sub2_i32:

        tcg_out_addsub2(s, args[0], args[1], args[2], args[3],

                        args[4], const_args[4], args[5], const_args[5],

                        ARITH_SUBCC, ARITH_SUBX);

        break;

    case INDEX_op_mulu2_i32:

        c = ARITH_UMUL;

        goto do_mul2;

    case INDEX_op_muls2_i32:

        c = ARITH_SMUL;

    do_mul2:

        /* The 32-bit multiply insns produce a full 64-bit result.  If the

           destination register can hold it, we can avoid the slower RDY.  */

        tcg_out_arithc(s, args[0], args[2], args[3], const_args[3], c);

        if (SPARC64 || args[0] <= TCG_REG_O7) {

            tcg_out_arithi(s, args[1], args[0], 32, SHIFT_SRLX);

        } else {

            tcg_out_rdy(s, args[1]);

        }

        break;

    case INDEX_op_qemu_ld_i32:

        tcg_out_qemu_ld(s, args[0], args[1], args[2], args[3], false);

        break;

    case INDEX_op_qemu_ld_i64:

        tcg_out_qemu_ld(s, args[0], args[1], args[2], args[3], true);

        break;

    case INDEX_op_qemu_st_i32:

        tcg_out_qemu_st(s, args[0], args[1], args[2], args[3]);

        break;

    case INDEX_op_qemu_st_i64:

        tcg_out_qemu_st(s, args[0], args[1], args[2], args[3]);

        break;

    case INDEX_op_movi_i64:

        tcg_out_movi(s, TCG_TYPE_I64, args[0], args[1]);

        break;

    case INDEX_op_ld32s_i64:

        tcg_out_ldst(s, args[0], args[1], args[2], LDSW);

        break;

    case INDEX_op_ld_i64:

        tcg_out_ldst(s, args[0], args[1], args[2], LDX);

        break;

    case INDEX_op_st_i64:

        tcg_out_ldst(s, args[0], args[1], args[2], STX);

        break;

    case INDEX_op_shl_i64:

        c = SHIFT_SLLX;

    do_shift64:

        /* Limit immediate shift count lest we create an illegal insn.  */

        tcg_out_arithc(s, args[0], args[1], args[2] & 63, const_args[2], c);

        break;

    case INDEX_op_shr_i64:

        c = SHIFT_SRLX;

        goto do_shift64;

    case INDEX_op_sar_i64:

        c = SHIFT_SRAX;

        goto do_shift64;

    case INDEX_op_mul_i64:

        c = ARITH_MULX;

        goto gen_arith;

    case INDEX_op_div_i64:

        c = ARITH_SDIVX;

        goto gen_arith;

    case INDEX_op_divu_i64:

        c = ARITH_UDIVX;

        goto gen_arith;

    case INDEX_op_ext32s_i64:

        tcg_out_arithi(s, args[0], args[1], 0, SHIFT_SRA);

        break;

    case INDEX_op_ext32u_i64:

        tcg_out_arithi(s, args[0], args[1], 0, SHIFT_SRL);

        break;

    case INDEX_op_trunc_shr_i32:

        if (args[2] == 0) {

            tcg_out_mov(s, TCG_TYPE_I32, args[0], args[1]);

        } else {

            tcg_out_arithi(s, args[0], args[1], args[2], SHIFT_SRLX);

        }

        break;

    case INDEX_op_brcond_i64:

        tcg_out_brcond_i64(s, args[2], args[0], args[1], const_args[1],

                           args[3]);

        break;

    case INDEX_op_setcond_i64:

        tcg_out_setcond_i64(s, args[3], args[0], args[1],

                            args[2], const_args[2]);

        break;

    case INDEX_op_movcond_i64:

        tcg_out_movcond_i64(s, args[5], args[0], args[1],

                            args[2], const_args[2], args[3], const_args[3]);

        break;

    gen_arith:

        tcg_out_arithc(s, args[0], args[1], args[2], const_args[2], c);

        break;

    gen_arith1:

	tcg_out_arithc(s, args[0], TCG_REG_G0, args[1], const_args[1], c);

	break;

    default:

        fprintf(stderr, "unknown opcode 0x%x\n", opc);

        tcg_abort();

    }

}


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

                                 int *got_frame_ptr, AVPacket *avpkt)

{

    EightSvxContext *esc = avctx->priv_data;

    int n, out_data_size;

    int ch, ret;

    uint8_t *src;

    /* decode and interleave the first packet */

    if (!esc->samples && avpkt) {

        int packet_size = avpkt->size;

        if (packet_size % avctx->channels) {

            av_log(avctx, AV_LOG_WARNING, "Packet with odd size, ignoring last byte\n");

            if (packet_size < avctx->channels)

                return packet_size;

            packet_size -= packet_size % avctx->channels;

        }

        esc->samples_size = !esc->table ?

            packet_size : avctx->channels + (packet_size-avctx->channels) * 2;

        if (!(esc->samples = av_malloc(esc->samples_size)))

            return AVERROR(ENOMEM);

        /* decompress */

        if (esc->table) {

            const uint8_t *buf = avpkt->data;

            uint8_t *dst;

            int buf_size = avpkt->size;

            int i, n = esc->samples_size;

            if (buf_size < 2) {

                av_log(avctx, AV_LOG_ERROR, "packet size is too small\n");

                return AVERROR(EINVAL);

            }

            /* the uncompressed starting value is contained in the first byte */

            dst = esc->samples;

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

                *(dst++) = buf[0]+128;

                delta_decode(dst, buf + 1, buf_size / avctx->channels - 1, (buf[0]+128)&0xFF, esc->table);

                buf += buf_size / avctx->channels;

                dst += n / avctx->channels - 1;

            }

        } else {

            raw_decode(esc->samples, avpkt->data, esc->samples_size);

        }

    }

    /* get output buffer */

    av_assert1(!(esc->samples_size % avctx->channels || esc->samples_idx % avctx->channels));

    esc->frame.nb_samples = FFMIN(MAX_FRAME_SIZE, esc->samples_size - esc->samples_idx)  / avctx->channels;

    if ((ret = avctx->get_buffer(avctx, &esc->frame)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return ret;

    }

    *got_frame_ptr   = 1;

    *(AVFrame *)data = esc->frame;

    out_data_size = esc->frame.nb_samples;

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

        src = esc->samples + esc->samples_idx / avctx->channels + ch * esc->samples_size / avctx->channels;

        memcpy(esc->frame.data[ch], src, out_data_size);

    }

    out_data_size *= avctx->channels;

    esc->samples_idx += out_data_size;

    return esc->table ?

        (avctx->frame_number == 0)*2 + out_data_size / 2 :

        out_data_size;

}