static int vmdk_create(const char *filename, QEMUOptionParameter *options,

                       Error **errp)

{

    int fd, idx = 0;

    char desc[BUF_SIZE];

    int64_t total_size = 0, filesize;

    const char *adapter_type = NULL;

    const char *backing_file = NULL;

    const char *fmt = NULL;

    int flags = 0;

    int ret = 0;

    bool flat, split, compress;

    char ext_desc_lines[BUF_SIZE] = "";

    char path[PATH_MAX], prefix[PATH_MAX], postfix[PATH_MAX];

    const int64_t split_size = 0x80000000;  /* VMDK has constant split size */

    const char *desc_extent_line;

    char parent_desc_line[BUF_SIZE] = "";

    uint32_t parent_cid = 0xffffffff;

    uint32_t number_heads = 16;

    bool zeroed_grain = false;

    const char desc_template[] =

        "# Disk DescriptorFile\n"

        "version=1\n"

        "CID=%x\n"

        "parentCID=%x\n"

        "createType=\"%s\"\n"

        "%s"

        "\n"

        "# Extent description\n"

        "%s"

        "\n"

        "# The Disk Data Base\n"

        "#DDB\n"

        "\n"

        "ddb.virtualHWVersion = \"%d\"\n"

        "ddb.geometry.cylinders = \"%" PRId64 "\"\n"

        "ddb.geometry.heads = \"%d\"\n"

        "ddb.geometry.sectors = \"63\"\n"

        "ddb.adapterType = \"%s\"\n";

    if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) {

        return -EINVAL;

    }

    /* Read out options */

    while (options && options->name) {

        if (!strcmp(options->name, BLOCK_OPT_SIZE)) {

            total_size = options->value.n;

        } else if (!strcmp(options->name, BLOCK_OPT_ADAPTER_TYPE)) {

            adapter_type = options->value.s;

        } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {

            backing_file = options->value.s;

        } else if (!strcmp(options->name, BLOCK_OPT_COMPAT6)) {

            flags |= options->value.n ? BLOCK_FLAG_COMPAT6 : 0;

        } else if (!strcmp(options->name, BLOCK_OPT_SUBFMT)) {

            fmt = options->value.s;

        } else if (!strcmp(options->name, BLOCK_OPT_ZEROED_GRAIN)) {

            zeroed_grain |= options->value.n;

        }

        options++;

    }

    if (!adapter_type) {

        adapter_type = "ide";

    } else if (strcmp(adapter_type, "ide") &&

               strcmp(adapter_type, "buslogic") &&

               strcmp(adapter_type, "lsilogic") &&

               strcmp(adapter_type, "legacyESX")) {

        error_setg(errp, "Unknown adapter type: '%s'", adapter_type);

        return -EINVAL;

    }

    if (strcmp(adapter_type, "ide") != 0) {

        /* that's the number of heads with which vmware operates when

           creating, exporting, etc. vmdk files with a non-ide adapter type */

        number_heads = 255;

    }

    if (!fmt) {

        /* Default format to monolithicSparse */

        fmt = "monolithicSparse";

    } else if (strcmp(fmt, "monolithicFlat") &&

               strcmp(fmt, "monolithicSparse") &&

               strcmp(fmt, "twoGbMaxExtentSparse") &&

               strcmp(fmt, "twoGbMaxExtentFlat") &&

               strcmp(fmt, "streamOptimized")) {

        error_setg(errp, "Unknown subformat: '%s'", fmt);

        return -EINVAL;

    }

    split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&

              strcmp(fmt, "twoGbMaxExtentSparse"));

    flat = !(strcmp(fmt, "monolithicFlat") &&

             strcmp(fmt, "twoGbMaxExtentFlat"));

    compress = !strcmp(fmt, "streamOptimized");

    if (flat) {

        desc_extent_line = "RW %lld FLAT \"%s\" 0\n";

    } else {

        desc_extent_line = "RW %lld SPARSE \"%s\"\n";

    }

    if (flat && backing_file) {

        error_setg(errp, "Flat image can't have backing file");

        return -ENOTSUP;

    }

    if (flat && zeroed_grain) {

        error_setg(errp, "Flat image can't enable zeroed grain");

        return -ENOTSUP;

    }

    if (backing_file) {

        BlockDriverState *bs = bdrv_new("");

        ret = bdrv_open(bs, backing_file, NULL, 0, NULL, errp);

        if (ret != 0) {

            bdrv_unref(bs);

            return ret;

        }

        if (strcmp(bs->drv->format_name, "vmdk")) {

            bdrv_unref(bs);

            return -EINVAL;

        }

        parent_cid = vmdk_read_cid(bs, 0);

        bdrv_unref(bs);

        snprintf(parent_desc_line, sizeof(parent_desc_line),

                "parentFileNameHint=\"%s\"", backing_file);

    }

    /* Create extents */

    filesize = total_size;

    while (filesize > 0) {

        char desc_line[BUF_SIZE];

        char ext_filename[PATH_MAX];

        char desc_filename[PATH_MAX];

        int64_t size = filesize;

        if (split && size > split_size) {

            size = split_size;

        }

        if (split) {

            snprintf(desc_filename, sizeof(desc_filename), "%s-%c%03d%s",

                    prefix, flat ? 'f' : 's', ++idx, postfix);

        } else if (flat) {

            snprintf(desc_filename, sizeof(desc_filename), "%s-flat%s",

                    prefix, postfix);

        } else {

            snprintf(desc_filename, sizeof(desc_filename), "%s%s",

                    prefix, postfix);

        }

        snprintf(ext_filename, sizeof(ext_filename), "%s%s",

                path, desc_filename);

        if (vmdk_create_extent(ext_filename, size,

                               flat, compress, zeroed_grain)) {

            return -EINVAL;

        }

        filesize -= size;

        /* Format description line */

        snprintf(desc_line, sizeof(desc_line),

                    desc_extent_line, size / 512, desc_filename);

        pstrcat(ext_desc_lines, sizeof(ext_desc_lines), desc_line);

    }

    /* generate descriptor file */

    snprintf(desc, sizeof(desc), desc_template,

            (unsigned int)time(NULL),

            parent_cid,

            fmt,

            parent_desc_line,

            ext_desc_lines,

            (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),

            total_size / (int64_t)(63 * number_heads * 512), number_heads,

                adapter_type);

    if (split || flat) {

        fd = qemu_open(filename,

                       O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,

                       0644);

    } else {

        fd = qemu_open(filename,

                       O_WRONLY | O_BINARY | O_LARGEFILE,

                       0644);

    }

    if (fd < 0) {

        return -errno;

    }

    /* the descriptor offset = 0x200 */

    if (!split && !flat && 0x200 != lseek(fd, 0x200, SEEK_SET)) {

        ret = -errno;

        goto exit;

    }

    ret = qemu_write_full(fd, desc, strlen(desc));

    if (ret != strlen(desc)) {

        ret = -errno;

        goto exit;

    }

    ret = 0;

exit:

    qemu_close(fd);

    return ret;

}


static void rtas_ibm_get_config_addr_info2(PowerPCCPU *cpu,

                                           sPAPREnvironment *spapr,

                                           uint32_t token, uint32_t nargs,

                                           target_ulong args, uint32_t nret,

                                           target_ulong rets)

{

    sPAPRPHBState *sphb;

    sPAPRPHBClass *spc;

    PCIDevice *pdev;

    uint32_t addr, option;

    uint64_t buid;

    if ((nargs != 4) || (nret != 2)) {

        goto param_error_exit;

    }

    buid = ((uint64_t)rtas_ld(args, 1) << 32) | rtas_ld(args, 2);

    sphb = find_phb(spapr, buid);

    if (!sphb) {

        goto param_error_exit;

    }

    spc = SPAPR_PCI_HOST_BRIDGE_GET_CLASS(sphb);

    if (!spc->eeh_set_option) {

        goto param_error_exit;

    }

    /*

     * We always have PE address of form "00BB0001". "BB"

     * represents the bus number of PE's primary bus.

     */

    option = rtas_ld(args, 3);

    switch (option) {

    case RTAS_GET_PE_ADDR:

        addr = rtas_ld(args, 0);

        pdev = find_dev(spapr, buid, addr);

        if (!pdev) {

            goto param_error_exit;

        }

        rtas_st(rets, 1, (pci_bus_num(pdev->bus) << 16) + 1);

        break;

    case RTAS_GET_PE_MODE:

        rtas_st(rets, 1, RTAS_PE_MODE_SHARED);

        break;

    default:

        goto param_error_exit;

    }

    rtas_st(rets, 0, RTAS_OUT_SUCCESS);

    return;

param_error_exit:

    rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);

}


__org_qemu_x_Union1 *qmp___org_qemu_x_command(__org_qemu_x_EnumList *a,

                                              __org_qemu_x_StructList *b,

                                              __org_qemu_x_Union2 *c,

                                              __org_qemu_x_Alt *d,

                                              Error **errp)

{

    __org_qemu_x_Union1 *ret = g_new0(__org_qemu_x_Union1, 1);

    ret->kind = ORG_QEMU_X_UNION1_KIND___ORG_QEMU_X_BRANCH;

    ret->__org_qemu_x_branch = strdup("blah1");

    return ret;

}


static CURLState *curl_init_state(BDRVCURLState *s)

{

    CURLState *state = NULL;

    int i, j;

    do {

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

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

                if (s->states[i].acb[j])

                    continue;

            if (s->states[i].in_use)

                continue;

            state = &s->states[i];

            state->in_use = 1;

            break;

        }

        if (!state) {

            qemu_aio_wait();

        }

    } while(!state);

    if (!state->curl) {

        state->curl = curl_easy_init();

        if (!state->curl) {

            return NULL;

        }

        curl_easy_setopt(state->curl, CURLOPT_URL, s->url);

        curl_easy_setopt(state->curl, CURLOPT_SSL_VERIFYPEER,

                         (long) s->sslverify);

        curl_easy_setopt(state->curl, CURLOPT_TIMEOUT, 5);

        curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION,

                         (void *)curl_read_cb);

        curl_easy_setopt(state->curl, CURLOPT_WRITEDATA, (void *)state);

        curl_easy_setopt(state->curl, CURLOPT_PRIVATE, (void *)state);

        curl_easy_setopt(state->curl, CURLOPT_AUTOREFERER, 1);

        curl_easy_setopt(state->curl, CURLOPT_FOLLOWLOCATION, 1);

        curl_easy_setopt(state->curl, CURLOPT_NOSIGNAL, 1);

        curl_easy_setopt(state->curl, CURLOPT_ERRORBUFFER, state->errmsg);

        curl_easy_setopt(state->curl, CURLOPT_FAILONERROR, 1);

        /* Restrict supported protocols to avoid security issues in the more

         * obscure protocols.  For example, do not allow POP3/SMTP/IMAP see

         * CVE-2013-0249.

         *

         * Restricting protocols is only supported from 7.19.4 upwards.

         */

#if LIBCURL_VERSION_NUM >= 0x071304

        curl_easy_setopt(state->curl, CURLOPT_PROTOCOLS, PROTOCOLS);

        curl_easy_setopt(state->curl, CURLOPT_REDIR_PROTOCOLS, PROTOCOLS);

#endif

#ifdef DEBUG_VERBOSE

        curl_easy_setopt(state->curl, CURLOPT_VERBOSE, 1);

#endif

    }

    state->s = s;

    return state;

}


static inline int check_physical(CPUPPCState *env, mmu_ctx_t *ctx,

                                 target_ulong eaddr, int rw)

{

    int in_plb, ret;

    ctx->raddr = eaddr;

    ctx->prot = PAGE_READ | PAGE_EXEC;

    ret = 0;

    switch (env->mmu_model) {

    case POWERPC_MMU_32B:

    case POWERPC_MMU_601:

    case POWERPC_MMU_SOFT_6xx:

    case POWERPC_MMU_SOFT_74xx:

    case POWERPC_MMU_SOFT_4xx:

    case POWERPC_MMU_REAL:

    case POWERPC_MMU_BOOKE:

        ctx->prot |= PAGE_WRITE;

        break;

#if defined(TARGET_PPC64)

    case POWERPC_MMU_64B:

    case POWERPC_MMU_2_06:

    case POWERPC_MMU_2_06d:

        /* Real address are 60 bits long */

        ctx->raddr &= 0x0FFFFFFFFFFFFFFFULL;

        ctx->prot |= PAGE_WRITE;

        break;

#endif

    case POWERPC_MMU_SOFT_4xx_Z:

        if (unlikely(msr_pe != 0)) {

            /* 403 family add some particular protections,

             * using PBL/PBU registers for accesses with no translation.

             */

            in_plb =

                /* Check PLB validity */

                (env->pb[0] < env->pb[1] &&

                 /* and address in plb area */

                 eaddr >= env->pb[0] && eaddr < env->pb[1]) ||

                (env->pb[2] < env->pb[3] &&

                 eaddr >= env->pb[2] && eaddr < env->pb[3]) ? 1 : 0;

            if (in_plb ^ msr_px) {

                /* Access in protected area */

                if (rw == 1) {

                    /* Access is not allowed */

                    ret = -2;

                }

            } else {

                /* Read-write access is allowed */

                ctx->prot |= PAGE_WRITE;

            }

        }

        break;

    case POWERPC_MMU_MPC8xx:

        /* XXX: TODO */

        cpu_abort(env, "MPC8xx MMU model is not implemented\n");

        break;

    case POWERPC_MMU_BOOKE206:

        cpu_abort(env, "BookE 2.06 MMU doesn't have physical real mode\n");

        break;

    default:

        cpu_abort(env, "Unknown or invalid MMU model\n");

        return -1;

    }

    return ret;

}


static void onenand_command(OneNANDState *s)

{

    int b;

    int sec;

    void *buf;

#define SETADDR(block, page)			\

    sec = (s->addr[page] & 3) +			\

            ((((s->addr[page] >> 2) & 0x3f) +	\

              (((s->addr[block] & 0xfff) |	\

                (s->addr[block] >> 15 ?		\

                 s->density_mask : 0)) << 6)) << (PAGE_SHIFT - 9));

#define SETBUF_M()				\

    buf = (s->bufaddr & 8) ?			\

            s->data[(s->bufaddr >> 2) & 1][0] : s->boot[0];	\

    buf += (s->bufaddr & 3) << 9;

#define SETBUF_S()				\

    buf = (s->bufaddr & 8) ?			\

            s->data[(s->bufaddr >> 2) & 1][1] : s->boot[1];	\

    buf += (s->bufaddr & 3) << 4;

    switch (s->command) {

    case 0x00:	/* Load single/multiple sector data unit into buffer */

        SETADDR(ONEN_BUF_BLOCK, ONEN_BUF_PAGE)

        SETBUF_M()

        if (onenand_load_main(s, sec, s->count, buf))

            s->status |= ONEN_ERR_CMD | ONEN_ERR_LOAD;

#if 0

        SETBUF_S()

        if (onenand_load_spare(s, sec, s->count, buf))

            s->status |= ONEN_ERR_CMD | ONEN_ERR_LOAD;

#endif

        /* TODO: if (s->bufaddr & 3) + s->count was > 4 (2k-pages)

         * or    if (s->bufaddr & 1) + s->count was > 2 (1k-pages)

         * then we need two split the read/write into two chunks.

         */

        s->intstatus |= ONEN_INT | ONEN_INT_LOAD;

        break;

    case 0x13:	/* Load single/multiple spare sector into buffer */

        SETADDR(ONEN_BUF_BLOCK, ONEN_BUF_PAGE)

        SETBUF_S()

        if (onenand_load_spare(s, sec, s->count, buf))

            s->status |= ONEN_ERR_CMD | ONEN_ERR_LOAD;

        /* TODO: if (s->bufaddr & 3) + s->count was > 4 (2k-pages)

         * or    if (s->bufaddr & 1) + s->count was > 2 (1k-pages)

         * then we need two split the read/write into two chunks.

         */

        s->intstatus |= ONEN_INT | ONEN_INT_LOAD;

        break;

    case 0x80:	/* Program single/multiple sector data unit from buffer */

        SETADDR(ONEN_BUF_BLOCK, ONEN_BUF_PAGE)

        SETBUF_M()

        if (onenand_prog_main(s, sec, s->count, buf))

            s->status |= ONEN_ERR_CMD | ONEN_ERR_PROG;

#if 0

        SETBUF_S()

        if (onenand_prog_spare(s, sec, s->count, buf))

            s->status |= ONEN_ERR_CMD | ONEN_ERR_PROG;

#endif

        /* TODO: if (s->bufaddr & 3) + s->count was > 4 (2k-pages)

         * or    if (s->bufaddr & 1) + s->count was > 2 (1k-pages)

         * then we need two split the read/write into two chunks.

         */

        s->intstatus |= ONEN_INT | ONEN_INT_PROG;

        break;

    case 0x1a:	/* Program single/multiple spare area sector from buffer */

        SETADDR(ONEN_BUF_BLOCK, ONEN_BUF_PAGE)

        SETBUF_S()

        if (onenand_prog_spare(s, sec, s->count, buf))

            s->status |= ONEN_ERR_CMD | ONEN_ERR_PROG;

        /* TODO: if (s->bufaddr & 3) + s->count was > 4 (2k-pages)

         * or    if (s->bufaddr & 1) + s->count was > 2 (1k-pages)

         * then we need two split the read/write into two chunks.

         */

        s->intstatus |= ONEN_INT | ONEN_INT_PROG;

        break;

    case 0x1b:	/* Copy-back program */

        SETBUF_S()

        SETADDR(ONEN_BUF_BLOCK, ONEN_BUF_PAGE)

        if (onenand_load_main(s, sec, s->count, buf))

            s->status |= ONEN_ERR_CMD | ONEN_ERR_PROG;

        SETADDR(ONEN_BUF_DEST_BLOCK, ONEN_BUF_DEST_PAGE)

        if (onenand_prog_main(s, sec, s->count, buf))

            s->status |= ONEN_ERR_CMD | ONEN_ERR_PROG;

        /* TODO: spare areas */

        s->intstatus |= ONEN_INT | ONEN_INT_PROG;

        break;

    case 0x23:	/* Unlock NAND array block(s) */

        s->intstatus |= ONEN_INT;

        /* XXX the previous (?) area should be locked automatically */

        for (b = s->unladdr[0]; b <= s->unladdr[1]; b ++) {

            if (b >= s->blocks) {

                s->status |= ONEN_ERR_CMD;

                break;

            }

            if (s->blockwp[b] == ONEN_LOCK_LOCKTIGHTEN)

                break;

            s->wpstatus = s->blockwp[b] = ONEN_LOCK_UNLOCKED;

        }

        break;

    case 0x27:	/* Unlock All NAND array blocks */

        s->intstatus |= ONEN_INT;

        for (b = 0; b < s->blocks; b ++) {

            if (b >= s->blocks) {

                s->status |= ONEN_ERR_CMD;

                break;

            }

            if (s->blockwp[b] == ONEN_LOCK_LOCKTIGHTEN)

                break;

            s->wpstatus = s->blockwp[b] = ONEN_LOCK_UNLOCKED;

        }

        break;

    case 0x2a:	/* Lock NAND array block(s) */

        s->intstatus |= ONEN_INT;

        for (b = s->unladdr[0]; b <= s->unladdr[1]; b ++) {

            if (b >= s->blocks) {

                s->status |= ONEN_ERR_CMD;

                break;

            }

            if (s->blockwp[b] == ONEN_LOCK_LOCKTIGHTEN)

                break;

            s->wpstatus = s->blockwp[b] = ONEN_LOCK_LOCKED;

        }

        break;

    case 0x2c:	/* Lock-tight NAND array block(s) */

        s->intstatus |= ONEN_INT;

        for (b = s->unladdr[0]; b <= s->unladdr[1]; b ++) {

            if (b >= s->blocks) {

                s->status |= ONEN_ERR_CMD;

                break;

            }

            if (s->blockwp[b] == ONEN_LOCK_UNLOCKED)

                continue;

            s->wpstatus = s->blockwp[b] = ONEN_LOCK_LOCKTIGHTEN;

        }

        break;

    case 0x71:	/* Erase-Verify-Read */

        s->intstatus |= ONEN_INT;

        break;

    case 0x95:	/* Multi-block erase */

        qemu_irq_pulse(s->intr);

        /* Fall through.  */

    case 0x94:	/* Block erase */

        sec = ((s->addr[ONEN_BUF_BLOCK] & 0xfff) |

                        (s->addr[ONEN_BUF_BLOCK] >> 15 ? s->density_mask : 0))

                << (BLOCK_SHIFT - 9);

        if (onenand_erase(s, sec, 1 << (BLOCK_SHIFT - 9)))

            s->status |= ONEN_ERR_CMD | ONEN_ERR_ERASE;

        s->intstatus |= ONEN_INT | ONEN_INT_ERASE;

        break;

    case 0xb0:	/* Erase suspend */

        break;

    case 0x30:	/* Erase resume */

        s->intstatus |= ONEN_INT | ONEN_INT_ERASE;

        break;

    case 0xf0:	/* Reset NAND Flash core */

        onenand_reset(s, 0);

        break;

    case 0xf3:	/* Reset OneNAND */

        onenand_reset(s, 0);

        break;

    case 0x65:	/* OTP Access */

        s->intstatus |= ONEN_INT;

        s->bdrv_cur = NULL;

        s->current = s->otp;

        s->secs_cur = 1 << (BLOCK_SHIFT - 9);

        s->addr[ONEN_BUF_BLOCK] = 0;

        s->otpmode = 1;

        break;

    default:

        s->status |= ONEN_ERR_CMD;

        s->intstatus |= ONEN_INT;

        fprintf(stderr, "%s: unknown OneNAND command %x\n",

                        __func__, s->command);

    }

    onenand_intr_update(s);

}


void address_space_destroy(AddressSpace *as)

{

    /* Flush out anything from MemoryListeners listening in on this */

    memory_region_transaction_begin();

    as->root = NULL;

    memory_region_transaction_commit();

    QTAILQ_REMOVE(&address_spaces, as, address_spaces_link);

    address_space_destroy_dispatch(as);

    flatview_destroy(as->current_map);

    g_free(as->name);

    g_free(as->current_map);

    g_free(as->ioeventfds);

}


int qemu_set_fd_handler2(int fd,

                         IOCanReadHandler *fd_read_poll,

                         IOHandler *fd_read,

                         IOHandler *fd_write,

                         void *opaque)

{

    IOHandlerRecord *ioh;

    assert(fd >= 0);

    if (!fd_read && !fd_write) {

        QLIST_FOREACH(ioh, &io_handlers, next) {

            if (ioh->fd == fd) {

                ioh->deleted = 1;

                break;

            }

        }

    } else {

        QLIST_FOREACH(ioh, &io_handlers, next) {

            if (ioh->fd == fd)

                goto found;

        }

        ioh = g_malloc0(sizeof(IOHandlerRecord));

        QLIST_INSERT_HEAD(&io_handlers, ioh, next);

    found:

        ioh->fd = fd;

        ioh->fd_read_poll = fd_read_poll;

        ioh->fd_read = fd_read;

        ioh->fd_write = fd_write;

        ioh->opaque = opaque;

        ioh->pollfds_idx = -1;

        ioh->deleted = 0;

        qemu_notify_event();

    }

    return 0;

}


static int tap_can_send(void *opaque)

{

    TAPState *s = opaque;

    return qemu_can_send_packet(&s->nc);

}


static void net_slirp_cleanup(VLANClientState *vc)

{

    SlirpState *s = vc->opaque;

    slirp_cleanup(s->slirp);

    slirp_smb_cleanup(s);

    TAILQ_REMOVE(&slirp_stacks, s, entry);

    qemu_free(s);

}


static int assign_device(AssignedDevice *dev)

{

    uint32_t flags = KVM_DEV_ASSIGN_ENABLE_IOMMU;

    int r;

    /* Only pass non-zero PCI segment to capable module */

    if (!kvm_check_extension(kvm_state, KVM_CAP_PCI_SEGMENT) &&

        dev->host.domain) {

        error_report("Can't assign device inside non-zero PCI segment "

                     "as this KVM module doesn't support it.");

        return -ENODEV;

    }

    if (!kvm_check_extension(kvm_state, KVM_CAP_IOMMU)) {

        error_report("No IOMMU found.  Unable to assign device \"%s\"",

                     dev->dev.qdev.id);

        return -ENODEV;

    }

    if (dev->features & ASSIGNED_DEVICE_SHARE_INTX_MASK &&

        kvm_has_intx_set_mask()) {

        flags |= KVM_DEV_ASSIGN_PCI_2_3;

    }

    r = kvm_device_pci_assign(kvm_state, &dev->host, flags, &dev->dev_id);

    if (r < 0) {

        switch (r) {

        case -EBUSY: {

            char *cause;

            cause = assign_failed_examine(dev);

            error_report("Failed to assign device \"%s\" : %s\n%s",

                         dev->dev.qdev.id, strerror(-r), cause);

            g_free(cause);

            break;

        }

        default:

            error_report("Failed to assign device \"%s\" : %s",

                         dev->dev.qdev.id, strerror(-r));

            break;

        }

    }

    return r;

}


void helper_fdtoq(CPUSPARCState *env, float64 src)

{

    clear_float_exceptions(env);

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

    check_ieee_exceptions(env);

}


static uint64_t ecc_diag_mem_read(void *opaque, target_phys_addr_t addr,

                                  unsigned size)

{

    ECCState *s = opaque;

    uint32_t ret = s->diag[(int)addr];

    trace_ecc_diag_mem_readb(addr, ret);

    return ret;

}


static void uart_write(void *opaque, target_phys_addr_t offset,

                          uint64_t value, unsigned size)

{

    UartState *s = (UartState *)opaque;

    DB_PRINT(" offset:%x data:%08x\n", offset, (unsigned)value);

    offset >>= 2;

    switch (offset) {

    case R_IER: /* ier (wts imr) */

        s->r[R_IMR] |= value;

        break;

    case R_IDR: /* idr (wtc imr) */

        s->r[R_IMR] &= ~value;

        break;

    case R_IMR: /* imr (read only) */

        break;

    case R_CISR: /* cisr (wtc) */

        s->r[R_CISR] &= ~value;

        break;

    case R_TX_RX: /* UARTDR */

        switch (s->r[R_MR] & UART_MR_CHMODE) {

        case NORMAL_MODE:

            uart_write_tx_fifo(s, (uint8_t *) &value, 1);

            break;

        case LOCAL_LOOPBACK:

            uart_write_rx_fifo(opaque, (uint8_t *) &value, 1);

            break;

        }

        break;

    default:

        s->r[offset] = value;

    }

    switch (offset) {

    case R_CR:

        uart_ctrl_update(s);

        break;

    case R_MR:

        uart_parameters_setup(s);

        break;

    }

}


static inline int handle_cpu_signal(unsigned long pc, unsigned long address,

                                    int is_write, sigset_t *old_set)

{

    TranslationBlock *tb;

    int ret;

    uint32_t found_pc;

#if defined(DEBUG_SIGNAL)

    printf("qemu: SIGSEGV pc=0x%08lx address=%08lx wr=%d oldset=0x%08lx\n",

           pc, address, is_write, *(unsigned long *)old_set);

#endif

    /* XXX: locking issue */

    if (is_write && page_unprotect(address)) {

        return 1;

    }

    tb = tb_find_pc(pc);

    if (tb) {

        /* the PC is inside the translated code. It means that we have

           a virtual CPU fault */

        ret = cpu_x86_search_pc(tb, &found_pc, pc);

        if (ret < 0)

            return 0;

        env->eip = found_pc - tb->cs_base;

        env->cr2 = address;

        /* we restore the process signal mask as the sigreturn should

           do it (XXX: use sigsetjmp) */

        sigprocmask(SIG_SETMASK, old_set, NULL);

        raise_exception_err(EXCP0E_PAGE, 4 | (is_write << 1));

        /* never comes here */

        return 1;

    } else {

        return 0;

    }

}


START_TEST(qobject_to_qstring_test)

{

    QString *qstring;

    qstring = qstring_from_str("foo");

    fail_unless(qobject_to_qstring(QOBJECT(qstring)) == qstring);

    QDECREF(qstring);

}


 static MachineClass *machine_parse(const char *name)

{

    MachineClass *mc = NULL;

    GSList *el, *machines = object_class_get_list(TYPE_MACHINE, false);

    if (name) {

        mc = find_machine(name);

    }

    if (mc) {

        return mc;

    }

    if (name && !is_help_option(name)) {

        error_report("Unsupported machine type");

        error_printf("Use -machine help to list supported machines!\n");

    } else {

        printf("Supported machines are:\n");

        machines = g_slist_sort(machines, machine_class_cmp);

        for (el = machines; el; el = el->next) {

            MachineClass *mc = el->data;

            if (mc->alias) {

                printf("%-20s %s (alias of %s)\n", mc->alias, mc->desc, mc->name);

            }

            printf("%-20s %s%s\n", mc->name, mc->desc,

                   mc->is_default ? " (default)" : "");

        }

    }

    exit(!name || !is_help_option(name));

}


static int decode_wmv9(AVCodecContext *avctx, const uint8_t *buf, int buf_size,

                       int x, int y, int w, int h, int wmv9_mask)

{

    MSS2Context *ctx  = avctx->priv_data;

    MSS12Context *c   = &ctx->c;

    VC1Context *v     = avctx->priv_data;

    MpegEncContext *s = &v->s;

    AVFrame *f;

    int ret;

    ff_mpeg_flush(avctx);

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

    s->loop_filter = avctx->skip_loop_filter < AVDISCARD_ALL;

    if (ff_vc1_parse_frame_header(v, &s->gb) < 0) {

        av_log(v->s.avctx, AV_LOG_ERROR, "header error\n");

        return AVERROR_INVALIDDATA;

    }

    if (s->pict_type != AV_PICTURE_TYPE_I) {

        av_log(v->s.avctx, AV_LOG_ERROR, "expected I-frame\n");

        return AVERROR_INVALIDDATA;

    }

    avctx->pix_fmt = AV_PIX_FMT_YUV420P;

    if ((ret = ff_MPV_frame_start(s, avctx)) < 0) {

        av_log(v->s.avctx, AV_LOG_ERROR, "ff_MPV_frame_start error\n");

        avctx->pix_fmt = AV_PIX_FMT_RGB24;

        return ret;

    }

    ff_mpeg_er_frame_start(s);

    v->bits = buf_size * 8;

    v->end_mb_x = (w + 15) >> 4;

    s->end_mb_y = (h + 15) >> 4;

    if (v->respic & 1)

        v->end_mb_x = v->end_mb_x + 1 >> 1;

    if (v->respic & 2)

        s->end_mb_y = s->end_mb_y + 1 >> 1;

    ff_vc1_decode_blocks(v);

    ff_er_frame_end(&s->er);

    ff_MPV_frame_end(s);

    f = &s->current_picture.f;

    if (v->respic == 3) {

        ctx->dsp.upsample_plane(f->data[0], f->linesize[0], w,      h);

        ctx->dsp.upsample_plane(f->data[1], f->linesize[1], w >> 1, h >> 1);

        ctx->dsp.upsample_plane(f->data[2], f->linesize[2], w >> 1, h >> 1);

    } else if (v->respic)

        avpriv_request_sample(v->s.avctx,

                              "Asymmetric WMV9 rectangle subsampling");

    av_assert0(f->linesize[1] == f->linesize[2]);

    if (wmv9_mask != -1)

        ctx->dsp.mss2_blit_wmv9_masked(c->rgb_pic + y * c->rgb_stride + x * 3,

                                       c->rgb_stride, wmv9_mask,

                                       c->pal_pic + y * c->pal_stride + x,

                                       c->pal_stride,

                                       f->data[0], f->linesize[0],

                                       f->data[1], f->data[2], f->linesize[1],

                                       w, h);

    else

        ctx->dsp.mss2_blit_wmv9(c->rgb_pic + y * c->rgb_stride + x * 3,

                                c->rgb_stride,

                                f->data[0], f->linesize[0],

                                f->data[1], f->data[2], f->linesize[1],

                                w, h);

    avctx->pix_fmt = AV_PIX_FMT_RGB24;

    return 0;

}


yuv2rgb_1_c_template(SwsContext *c, const int16_t *buf0,
                     const int16_t *ubuf[2], const int16_t *vbuf[2],
                     const int16_t *abuf0, uint8_t *dest, int dstW,
                     int uvalpha, int y, enum PixelFormat target,
                     int hasAlpha)
{
    const int16_t *ubuf0 = ubuf[0], *vbuf0 = vbuf[0];
    int i;
    if (uvalpha < 2048) {
        for (i = 0; i < (dstW >> 1); i++) {
            int Y1 = buf0[i * 2]     >> 7;
            int Y2 = buf0[i * 2 + 1] >> 7;
            int U  = ubuf0[i]        >> 7;
            int V  = vbuf0[i]        >> 7;
            int A1, A2;
            const void *r =  c->table_rV[V],
                       *g = (c->table_gU[U] + c->table_gV[V]),
                       *b =  c->table_bU[U];
            if (hasAlpha) {
                A1 = abuf0[i * 2    ] >> 7;
                A2 = abuf0[i * 2 + 1] >> 7;
            }
            yuv2rgb_write(dest, i, Y1, Y2, hasAlpha ? A1 : 0, hasAlpha ? A2 : 0,
                          r, g, b, y, target, hasAlpha);
        }
    } else {
        const int16_t *ubuf1 = ubuf[1], *vbuf1 = vbuf[1];
        for (i = 0; i < (dstW >> 1); i++) {
            int Y1 =  buf0[i * 2]          >> 7;
            int Y2 =  buf0[i * 2 + 1]      >> 7;
            int U  = (ubuf0[i] + ubuf1[i]) >> 8;
            int V  = (vbuf0[i] + vbuf1[i]) >> 8;
            int A1, A2;
            const void *r =  c->table_rV[V],
                       *g = (c->table_gU[U] + c->table_gV[V]),
                       *b =  c->table_bU[U];
            if (hasAlpha) {
                A1 = abuf0[i * 2    ] >> 7;
                A2 = abuf0[i * 2 + 1] >> 7;
            }
            yuv2rgb_write(dest, i, Y1, Y2, hasAlpha ? A1 : 0, hasAlpha ? A2 : 0,
                          r, g, b, y, target, hasAlpha);
        }
    }
}


static int pci_qdev_init(DeviceState *qdev, DeviceInfo *base)

{

    PCIDevice *pci_dev = (PCIDevice *)qdev;

    PCIDeviceInfo *info = container_of(base, PCIDeviceInfo, qdev);

    PCIBus *bus;

    int devfn, rc;

    /* initialize cap_present for pci_is_express() and pci_config_size() */

    if (info->is_express) {

        pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;

    }

    bus = FROM_QBUS(PCIBus, qdev_get_parent_bus(qdev));

    devfn = pci_dev->devfn;

    pci_dev = do_pci_register_device(pci_dev, bus, base->name, devfn,

                                     info->config_read, info->config_write,

                                     info->header_type);

    assert(pci_dev);

    rc = info->init(pci_dev);

    if (rc != 0)

        return rc;

    if (qdev->hotplugged)

        bus->hotplug(pci_dev, 1);

    return 0;

}


static AVStream * parse_media_type(AVFormatContext *s, AVStream *st, int sid,

                                   ff_asf_guid mediatype, ff_asf_guid subtype,

                                   ff_asf_guid formattype, int size)

{

    WtvContext *wtv = s->priv_data;

    AVIOContext *pb = wtv->pb;

    if (!ff_guidcmp(subtype, ff_mediasubtype_cpfilters_processed) &&

        !ff_guidcmp(formattype, ff_format_cpfilters_processed)) {

        ff_asf_guid actual_subtype;

        ff_asf_guid actual_formattype;

        if (size < 32) {

            av_log(s, AV_LOG_WARNING, "format buffer size underflow\n");

            avio_skip(pb, size);

            return NULL;

        }

        avio_skip(pb, size - 32);

        ff_get_guid(pb, &actual_subtype);

        ff_get_guid(pb, &actual_formattype);

        avio_seek(pb, -size, SEEK_CUR);

        st = parse_media_type(s, st, sid, mediatype, actual_subtype, actual_formattype, size - 32);

        avio_skip(pb, 32);

        return st;

    } else if (!ff_guidcmp(mediatype, ff_mediatype_audio)) {

        st = new_stream(s, st, sid, AVMEDIA_TYPE_AUDIO);

        if (!st)

            return NULL;

        if (!ff_guidcmp(formattype, ff_format_waveformatex)) {

            int ret = ff_get_wav_header(pb, st->codec, size);

            if (ret < 0)

                return NULL;

        } else {

            if (ff_guidcmp(formattype, ff_format_none))

                av_log(s, AV_LOG_WARNING, "unknown formattype:"FF_PRI_GUID"\n", FF_ARG_GUID(formattype));

            avio_skip(pb, size);

        }

        if (!memcmp(subtype + 4, (const uint8_t[]){FF_MEDIASUBTYPE_BASE_GUID}, 12)) {

            st->codec->codec_id = ff_wav_codec_get_id(AV_RL32(subtype), st->codec->bits_per_coded_sample);

        } else if (!ff_guidcmp(subtype, mediasubtype_mpeg1payload)) {

            if (st->codec->extradata && st->codec->extradata_size >= 22)

                parse_mpeg1waveformatex(st);

            else

                av_log(s, AV_LOG_WARNING, "MPEG1WAVEFORMATEX underflow\n");

        } else {

            st->codec->codec_id = ff_codec_guid_get_id(ff_codec_wav_guids, subtype);

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

                av_log(s, AV_LOG_WARNING, "unknown subtype:"FF_PRI_GUID"\n", FF_ARG_GUID(subtype));

        }

        return st;

    } else if (!ff_guidcmp(mediatype, ff_mediatype_video)) {

        st = new_stream(s, st, sid, AVMEDIA_TYPE_VIDEO);

        if (!st)

            return NULL;

        if (!ff_guidcmp(formattype, ff_format_videoinfo2)) {

            int consumed = parse_videoinfoheader2(s, st);

            avio_skip(pb, FFMAX(size - consumed, 0));

        } else if (!ff_guidcmp(formattype, ff_format_mpeg2_video)) {

            int consumed = parse_videoinfoheader2(s, st);

            int count;

            avio_skip(pb, 4);

            count = avio_rl32(pb);

            avio_skip(pb, 12);

            if (count && ff_get_extradata(st->codec, pb, count) < 0) {

               ff_free_stream(s, st);

               return NULL;

            }

            consumed += 20 + count;

            avio_skip(pb, FFMAX(size - consumed, 0));

        } else {

            if (ff_guidcmp(formattype, ff_format_none))

                av_log(s, AV_LOG_WARNING, "unknown formattype:"FF_PRI_GUID"\n", FF_ARG_GUID(formattype));

            avio_skip(pb, size);

        }

        if (!memcmp(subtype + 4, (const uint8_t[]){FF_MEDIASUBTYPE_BASE_GUID}, 12)) {

            st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, AV_RL32(subtype));

        } else {

            st->codec->codec_id = ff_codec_guid_get_id(ff_video_guids, subtype);

        }

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

            av_log(s, AV_LOG_WARNING, "unknown subtype:"FF_PRI_GUID"\n", FF_ARG_GUID(subtype));

        return st;

    } else if (!ff_guidcmp(mediatype, mediatype_mpeg2_pes) &&

               !ff_guidcmp(subtype, mediasubtype_dvb_subtitle)) {

        st = new_stream(s, st, sid, AVMEDIA_TYPE_SUBTITLE);

        if (!st)

            return NULL;

        if (ff_guidcmp(formattype, ff_format_none))

            av_log(s, AV_LOG_WARNING, "unknown formattype:"FF_PRI_GUID"\n", FF_ARG_GUID(formattype));

        avio_skip(pb, size);

        st->codec->codec_id = AV_CODEC_ID_DVB_SUBTITLE;

        return st;

    } else if (!ff_guidcmp(mediatype, mediatype_mstvcaption) &&

               (!ff_guidcmp(subtype, mediasubtype_teletext) || !ff_guidcmp(subtype, mediasubtype_dtvccdata))) {

        st = new_stream(s, st, sid, AVMEDIA_TYPE_SUBTITLE);

        if (!st)

            return NULL;

        if (ff_guidcmp(formattype, ff_format_none))

            av_log(s, AV_LOG_WARNING, "unknown formattype:"FF_PRI_GUID"\n", FF_ARG_GUID(formattype));

        avio_skip(pb, size);

        st->codec->codec_id = !ff_guidcmp(subtype, mediasubtype_teletext) ? AV_CODEC_ID_DVB_TELETEXT : AV_CODEC_ID_EIA_608;

        return st;

    } else if (!ff_guidcmp(mediatype, mediatype_mpeg2_sections) &&

               !ff_guidcmp(subtype, mediasubtype_mpeg2_sections)) {

        if (ff_guidcmp(formattype, ff_format_none))

            av_log(s, AV_LOG_WARNING, "unknown formattype:"FF_PRI_GUID"\n", FF_ARG_GUID(formattype));

        avio_skip(pb, size);

        return NULL;

    }

    av_log(s, AV_LOG_WARNING, "unknown media type, mediatype:"FF_PRI_GUID

                              ", subtype:"FF_PRI_GUID", formattype:"FF_PRI_GUID"\n",

                              FF_ARG_GUID(mediatype), FF_ARG_GUID(subtype), FF_ARG_GUID(formattype));

    avio_skip(pb, size);

    return NULL;

}


static void intra_predict_dc_4blk_8x8_msa(uint8_t *src, int32_t stride)

{

    uint8_t lp_cnt;

    uint32_t src0, src1, src3, src2 = 0;

    uint32_t out0, out1, out2, out3;

    v16u8 src_top;

    v8u16 add;

    v4u32 sum;

    src_top = LD_UB(src - stride);

    add = __msa_hadd_u_h((v16u8) src_top, (v16u8) src_top);

    sum = __msa_hadd_u_w(add, add);

    src0 = __msa_copy_u_w((v4i32) sum, 0);

    src1 = __msa_copy_u_w((v4i32) sum, 1);

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

        src0 += src[lp_cnt * stride - 1];

        src2 += src[(4 + lp_cnt) * stride - 1];

    }

    src0 = (src0 + 4) >> 3;

    src3 = (src1 + src2 + 4) >> 3;

    src1 = (src1 + 2) >> 2;

    src2 = (src2 + 2) >> 2;

    out0 = src0 * 0x01010101;

    out1 = src1 * 0x01010101;

    out2 = src2 * 0x01010101;

    out3 = src3 * 0x01010101;

    for (lp_cnt = 4; lp_cnt--;) {

        SW(out0, src);

        SW(out1, (src + 4));

        SW(out2, (src + 4 * stride));

        SW(out3, (src + 4 * stride + 4));

        src += stride;

    }

}


static int init_poc(H264Context *h){

    MpegEncContext * const s = &h->s;

    const int max_frame_num= 1<<h->sps.log2_max_frame_num;

    int field_poc[2];

    h->frame_num_offset= h->prev_frame_num_offset;

    if(h->frame_num < h->prev_frame_num)

        h->frame_num_offset += max_frame_num;

    if(h->sps.poc_type==0){

        const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;

        if     (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)

            h->poc_msb = h->prev_poc_msb + max_poc_lsb;

        else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)

            h->poc_msb = h->prev_poc_msb - max_poc_lsb;

        else

            h->poc_msb = h->prev_poc_msb;

//printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);

        field_poc[0] =

        field_poc[1] = h->poc_msb + h->poc_lsb;

        if(s->picture_structure == PICT_FRAME)

            field_poc[1] += h->delta_poc_bottom;

    }else if(h->sps.poc_type==1){

        int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;

        int i;

        if(h->sps.poc_cycle_length != 0)

            abs_frame_num = h->frame_num_offset + h->frame_num;

        else

            abs_frame_num = 0;

        if(h->nal_ref_idc==0 && abs_frame_num > 0)

            abs_frame_num--;

        expected_delta_per_poc_cycle = 0;

        for(i=0; i < h->sps.poc_cycle_length; i++)

            expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse

        if(abs_frame_num > 0){

            int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;

            int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;

            expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;

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

                expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];

        } else

            expectedpoc = 0;

        if(h->nal_ref_idc == 0)

            expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;

        field_poc[0] = expectedpoc + h->delta_poc[0];

        field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;

        if(s->picture_structure == PICT_FRAME)

            field_poc[1] += h->delta_poc[1];

    }else{

        int poc= 2*(h->frame_num_offset + h->frame_num);

        if(!h->nal_ref_idc)

            poc--;

        field_poc[0]= poc;

        field_poc[1]= poc;

    }

    if(s->picture_structure != PICT_BOTTOM_FIELD) {

        s->current_picture_ptr->field_poc[0]= field_poc[0];

        s->current_picture_ptr->poc = field_poc[0];

    }

    if(s->picture_structure != PICT_TOP_FIELD) {

        s->current_picture_ptr->field_poc[1]= field_poc[1];

        s->current_picture_ptr->poc = field_poc[1];

    }

    if(!FIELD_PICTURE || !s->first_field) {

        Picture *cur = s->current_picture_ptr;

        cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);

    }

    return 0;

}


static void sdhci_set_inserted(DeviceState *dev, bool level)

{

    SDHCIState *s = (SDHCIState *)dev;

    DPRINT_L1("Card state changed: %s!\n", level ? "insert" : "eject");

    if ((s->norintsts & SDHC_NIS_REMOVE) && level) {

        /* Give target some time to notice card ejection */

        timer_mod(s->insert_timer,

                       qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + SDHC_INSERTION_DELAY);

    } else {

        if (level) {

            s->prnsts = 0x1ff0000;

            if (s->norintstsen & SDHC_NISEN_INSERT) {

                s->norintsts |= SDHC_NIS_INSERT;

            }

        } else {

            s->prnsts = 0x1fa0000;

            s->pwrcon &= ~SDHC_POWER_ON;

            s->clkcon &= ~SDHC_CLOCK_SDCLK_EN;

            if (s->norintstsen & SDHC_NISEN_REMOVE) {

                s->norintsts |= SDHC_NIS_REMOVE;

            }

        }

        sdhci_update_irq(s);

    }

}


static void get_sensor_type(IPMIBmcSim *ibs,

                               uint8_t *cmd, unsigned int cmd_len,

                               uint8_t *rsp, unsigned int *rsp_len,

                               unsigned int max_rsp_len)

{

    IPMISensor *sens;

    IPMI_CHECK_CMD_LEN(3);

    if ((cmd[2] > MAX_SENSORS) ||

            !IPMI_SENSOR_GET_PRESENT(ibs->sensors + cmd[2])) {

        rsp[2] = IPMI_CC_REQ_ENTRY_NOT_PRESENT;

        return;

    }

    sens = ibs->sensors + cmd[2];

    IPMI_ADD_RSP_DATA(sens->sensor_type);

    IPMI_ADD_RSP_DATA(sens->evt_reading_type_code);

}


static int avui_encode_frame(AVCodecContext *avctx, AVPacket *pkt,

                             const AVFrame *pic, int *got_packet)

{

    uint8_t *dst, *src = pic->data[0];

    int i, j, skip, ret, size, interlaced;

    interlaced = avctx->field_order > AV_FIELD_PROGRESSIVE;

    if (avctx->height == 486) {

        skip = 10;

    } else {

        skip = 16;

    }

    size = 2 * avctx->width * (avctx->height + skip) + 8 * interlaced;

    if ((ret = ff_alloc_packet2(avctx, pkt, size)) < 0)

        return ret;

    dst = pkt->data;

    if (!(avctx->extradata = av_mallocz(24 + FF_INPUT_BUFFER_PADDING_SIZE)))

        return AVERROR(ENOMEM);

    avctx->extradata_size = 24;

    memcpy(avctx->extradata, "\0\0\0\x18""APRGAPRG0001", 16);

    if (interlaced) {

        avctx->extradata[19] = 2;

    } else {

        avctx->extradata[19] = 1;

        dst += avctx->width * skip;

    }

    avctx->coded_frame->reference = 0;

    avctx->coded_frame->key_frame = 1;

    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;

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

        if (interlaced && avctx->height == 486) {

            src = pic->data[0] + (1 - i) * pic->linesize[0];

        } else {

            src = pic->data[0] + i * pic->linesize[0];

        }

        dst += avctx->width * skip + 4 * i;

        for (j = 0; j < avctx->height; j += interlaced + 1) {

            memcpy(dst, src, avctx->width * 2);

            src += (interlaced + 1) * pic->linesize[0];

            dst += avctx->width * 2;

        }

    }

    pkt->flags |= AV_PKT_FLAG_KEY;

    *got_packet = 1;

    return 0;

}


static void sparc_cpu_initfn(Object *obj)

{

    CPUState *cs = CPU(obj);

    SPARCCPU *cpu = SPARC_CPU(obj);

    CPUSPARCState *env = &cpu->env;

    cs->env_ptr = env;

    cpu_exec_init(cs, &error_abort);

    if (tcg_enabled()) {

        gen_intermediate_code_init(env);

    }

}


static void register_to_network(RDMARegister *reg)

{

    reg->key.current_addr = htonll(reg->key.current_addr);

    reg->current_index = htonl(reg->current_index);

    reg->chunks = htonll(reg->chunks);

}


int av_resample(AVResampleContext *c, short *dst, short *src, int *consumed, int src_size, int dst_size, int update_ctx){

    int dst_index, i;

    int index= c->index;

    int frac= c->frac;

    int dst_incr_frac= c->dst_incr % c->src_incr;

    int dst_incr=      c->dst_incr / c->src_incr;

    int compensation_distance= c->compensation_distance;

  if(compensation_distance == 0 && c->filter_length == 1 && c->phase_shift==0){

        int64_t index2= ((int64_t)index)<<32;

        int64_t incr= (1LL<<32) * c->dst_incr / c->src_incr;

        dst_size= FFMIN(dst_size, (src_size-1-index) * (int64_t)c->src_incr / c->dst_incr);

        for(dst_index=0; dst_index < dst_size; dst_index++){

            dst[dst_index] = src[index2>>32];

            index2 += incr;

        }

        frac += dst_index * dst_incr_frac;

        index += dst_index * dst_incr;

        index += frac / c->src_incr;

        frac %= c->src_incr;

  }else{

    for(dst_index=0; dst_index < dst_size; dst_index++){

        FELEM *filter= c->filter_bank + c->filter_length*(index & c->phase_mask);

        int sample_index= index >> c->phase_shift;

        FELEM2 val=0;

        if(sample_index < 0){

            for(i=0; i<c->filter_length; i++)

                val += src[FFABS(sample_index + i) % src_size] * filter[i];

        }else if(sample_index + c->filter_length > src_size){

            break;

        }else if(c->linear){

            FELEM2 v2=0;

            for(i=0; i<c->filter_length; i++){

                val += src[sample_index + i] * (FELEM2)filter[i];

                v2  += src[sample_index + i] * (FELEM2)filter[i + c->filter_length];

            }

            val+=(v2-val)*(FELEML)frac / c->src_incr;

        }else{

            for(i=0; i<c->filter_length; i++){

                val += src[sample_index + i] * (FELEM2)filter[i];

            }

        }

#ifdef CONFIG_RESAMPLE_AUDIOPHILE_KIDDY_MODE

        dst[dst_index] = av_clip_int16(lrintf(val));

#else

        val = (val + (1<<(FILTER_SHIFT-1)))>>FILTER_SHIFT;

        dst[dst_index] = (unsigned)(val + 32768) > 65535 ? (val>>31) ^ 32767 : val;

#endif

        frac += dst_incr_frac;

        index += dst_incr;

        if(frac >= c->src_incr){

            frac -= c->src_incr;

            index++;

        }

        if(dst_index + 1 == compensation_distance){

            compensation_distance= 0;

            dst_incr_frac= c->ideal_dst_incr % c->src_incr;

            dst_incr=      c->ideal_dst_incr / c->src_incr;

        }

    }

  }

    *consumed= FFMAX(index, 0) >> c->phase_shift;

    if(index>=0) index &= c->phase_mask;

    if(compensation_distance){

        compensation_distance -= dst_index;

        assert(compensation_distance > 0);

    }

    if(update_ctx){

        c->frac= frac;

        c->index= index;

        c->dst_incr= dst_incr_frac + c->src_incr*dst_incr;

        c->compensation_distance= compensation_distance;

    }

#if 0

    if(update_ctx && !c->compensation_distance){

#undef rand

        av_resample_compensate(c, rand() % (8000*2) - 8000, 8000*2);

av_log(NULL, AV_LOG_DEBUG, "%d %d %d\n", c->dst_incr, c->ideal_dst_incr, c->compensation_distance);

    }

#endif

    return dst_index;

}


static void FUNCC(pred4x4_128_dc)(uint8_t *_src, const uint8_t *topright, int _stride){

    pixel *src = (pixel*)_src;

    int stride = _stride/sizeof(pixel);

    ((pixel4*)(src+0*stride))[0]=

    ((pixel4*)(src+1*stride))[0]=

    ((pixel4*)(src+2*stride))[0]=

    ((pixel4*)(src+3*stride))[0]= PIXEL_SPLAT_X4(1<<(BIT_DEPTH-1));

}


void nand_setio(DeviceState *dev, uint32_t value)

{

    int i;

    NANDFlashState *s = (NANDFlashState *) dev;

    if (!s->ce && s->cle) {

        if (nand_flash_ids[s->chip_id].options & NAND_SAMSUNG_LP) {

            if (s->cmd == NAND_CMD_READ0 && value == NAND_CMD_LPREAD2)

                return;

            if (value == NAND_CMD_RANDOMREAD1) {

                s->addr &= ~((1 << s->addr_shift) - 1);

                s->addrlen = 0;

                return;

            }

        }

        if (value == NAND_CMD_READ0)

            s->offset = 0;

	else if (value == NAND_CMD_READ1) {

            s->offset = 0x100;

            value = NAND_CMD_READ0;

        }

	else if (value == NAND_CMD_READ2) {

            s->offset = 1 << s->page_shift;

            value = NAND_CMD_READ0;

        }

        s->cmd = value;

        if (s->cmd == NAND_CMD_READSTATUS ||

                s->cmd == NAND_CMD_PAGEPROGRAM2 ||

                s->cmd == NAND_CMD_BLOCKERASE1 ||

                s->cmd == NAND_CMD_BLOCKERASE2 ||

                s->cmd == NAND_CMD_NOSERIALREAD2 ||

                s->cmd == NAND_CMD_RANDOMREAD2 ||

                s->cmd == NAND_CMD_RESET)

            nand_command(s);

        if (s->cmd != NAND_CMD_RANDOMREAD2) {

            s->addrlen = 0;

        }

    }

    if (s->ale) {

        unsigned int shift = s->addrlen * 8;

        unsigned int mask = ~(0xff << shift);

        unsigned int v = value << shift;

        s->addr = (s->addr & mask) | v;

        s->addrlen ++;

        switch (s->addrlen) {

        case 1:

            if (s->cmd == NAND_CMD_READID) {

                nand_command(s);

            }

            break;

        case 2: /* fix cache address as a byte address */

            s->addr <<= (s->buswidth - 1);

            break;

        case 3:

            if (!(nand_flash_ids[s->chip_id].options & NAND_SAMSUNG_LP) &&

                    (s->cmd == NAND_CMD_READ0 ||

                     s->cmd == NAND_CMD_PAGEPROGRAM1)) {

                nand_command(s);

            }

            break;

        case 4:

            if ((nand_flash_ids[s->chip_id].options & NAND_SAMSUNG_LP) &&

                    nand_flash_ids[s->chip_id].size < 256 && /* 1Gb or less */

                    (s->cmd == NAND_CMD_READ0 ||

                     s->cmd == NAND_CMD_PAGEPROGRAM1)) {

                nand_command(s);

            }

            break;

        case 5:

            if ((nand_flash_ids[s->chip_id].options & NAND_SAMSUNG_LP) &&

                    nand_flash_ids[s->chip_id].size >= 256 && /* 2Gb or more */

                    (s->cmd == NAND_CMD_READ0 ||

                     s->cmd == NAND_CMD_PAGEPROGRAM1)) {

                nand_command(s);

            }

            break;

        default:

            break;

        }

    }

    if (!s->cle && !s->ale && s->cmd == NAND_CMD_PAGEPROGRAM1) {

        if (s->iolen < (1 << s->page_shift) + (1 << s->oob_shift)) {

            for (i = s->buswidth; i--; value >>= 8) {

                s->io[s->iolen ++] = (uint8_t) (value & 0xff);

            }

        }

    } else if (!s->cle && !s->ale && s->cmd == NAND_CMD_COPYBACKPRG1) {

        if ((s->addr & ((1 << s->addr_shift) - 1)) <

                (1 << s->page_shift) + (1 << s->oob_shift)) {

            for (i = s->buswidth; i--; s->addr++, value >>= 8) {

                s->io[s->iolen + (s->addr & ((1 << s->addr_shift) - 1))] =

                    (uint8_t) (value & 0xff);

            }

        }

    }

}


static int bdrv_qed_check(BlockDriverState *bs, BdrvCheckResult *result)

{

    return -ENOTSUP;

}


int ff_dirac_golomb_read_16bit(DiracGolombLUT *lut_ctx, const uint8_t *buf,
                               int bytes, uint8_t *_dst, int coeffs)
{
    int i, b, c_idx = 0;
    int16_t *dst = (int16_t *)_dst;
    DiracGolombLUT *future[4], *l = &lut_ctx[2*LUT_SIZE + buf[0]];
    INIT_RESIDUE(res);
    for (b = 1; b <= bytes; b++) {
        future[0] = &lut_ctx[buf[b]];
        future[1] = future[0] + 1*LUT_SIZE;
        future[2] = future[0] + 2*LUT_SIZE;
        future[3] = future[0] + 3*LUT_SIZE;
        if ((c_idx + 1) > coeffs)
            return c_idx;
        if (res_bits && l->sign) {
            int32_t coeff = 1;
            APPEND_RESIDUE(res, l->preamble);
            for (i = 0; i < (res_bits >> 1) - 1; i++) {
                coeff <<= 1;
                coeff |= (res >> (RSIZE_BITS - 2*i - 2)) & 1;
            }
            dst[c_idx++] = l->sign * (coeff - 1);
        }
        for (i = 0; i < LUT_BITS; i++)
            dst[c_idx + i] = l->ready[i];
        c_idx += l->ready_num;
        APPEND_RESIDUE(res, l->leftover);
        l = future[l->need_s ? 3 : !res_bits ? 2 : res_bits & 1];
    }
    return c_idx;
}


static int bdrv_wr_badreq_sectors(BlockDriverState *bs,

                                  int64_t sector_num, int nb_sectors)

{

    if (sector_num < 0 ||

        nb_sectors < 0)

        return 1;

    if (sector_num > bs->total_sectors - nb_sectors) {

        if (bs->autogrow)

            bs->total_sectors = sector_num + nb_sectors;

        else

            return 1;

    }

    return 0;

}


static int ram_save_complete(QEMUFile *f, void *opaque)

{

    rcu_read_lock();

    migration_bitmap_sync();

    ram_control_before_iterate(f, RAM_CONTROL_FINISH);

    /* try transferring iterative blocks of memory */

    /* flush all remaining blocks regardless of rate limiting */

    while (true) {

        int pages;

        pages = ram_find_and_save_block(f, true, &bytes_transferred);

        /* no more blocks to sent */

        if (pages == 0) {

            break;

        }

    }

    flush_compressed_data(f);

    ram_control_after_iterate(f, RAM_CONTROL_FINISH);

    migration_end();

    rcu_read_unlock();

    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);

    return 0;

}


void ff_add_pixels_clamped_c(const DCTELEM *block, uint8_t *restrict pixels,

                             int line_size)

{

    int i;

    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;

    /* read the pixels */

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

        pixels[0] = cm[pixels[0] + block[0]];

        pixels[1] = cm[pixels[1] + block[1]];

        pixels[2] = cm[pixels[2] + block[2]];

        pixels[3] = cm[pixels[3] + block[3]];

        pixels[4] = cm[pixels[4] + block[4]];

        pixels[5] = cm[pixels[5] + block[5]];

        pixels[6] = cm[pixels[6] + block[6]];

        pixels[7] = cm[pixels[7] + block[7]];

        pixels += line_size;

        block += 8;

    }

}


static inline int ohci_put_ed(OHCIState *ohci,

                              uint32_t addr, struct ohci_ed *ed)

{

    return put_dwords(ohci, addr, (uint32_t *)ed, sizeof(*ed) >> 2);

}


static int read_cpuinfo(const char *field, char *value, int len)

{

    FILE *f;

    int ret = -1;

    int field_len = strlen(field);

    char line[512];

    f = fopen("/proc/cpuinfo", "r");

    if (!f) {

        return -1;

    }

    do {

        if(!fgets(line, sizeof(line), f)) {

            break;

        }

        if (!strncmp(line, field, field_len)) {

            strncpy(value, line, len);

            ret = 0;

            break;

        }

    } while(*line);

    fclose(f);

    return ret;

}


static void puv3_board_init(CPUUniCore32State *env, ram_addr_t ram_size)

{

    MemoryRegion *ram_memory = g_new(MemoryRegion, 1);

    /* SDRAM at address zero.  */

    memory_region_init_ram(ram_memory, NULL, "puv3.ram", ram_size,

                           &error_abort);

    vmstate_register_ram_global(ram_memory);

    memory_region_add_subregion(get_system_memory(), 0, ram_memory);

}


void show_help(void)

{

    const OptionDef *po;

    int i, expert;

    printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000,2001 Gerard Lantau\n"

           "usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"

           "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n"

           "\n"

           "Main options are:\n");

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

        if (i == 1)

            printf("\nAdvanced options are:\n");

        for(po = options; po->name != NULL; po++) {

            char buf[64];

            expert = (po->flags & OPT_EXPERT) != 0;

            if (expert == i) {

                strcpy(buf, po->name);

                if (po->flags & HAS_ARG) {

                    strcat(buf, " ");

                    strcat(buf, po->argname);

                }

                printf("-%-17s  %s\n", buf, po->help);

            }

        }

    }

    exit(1);

}


static int ftp_shutdown(URLContext *h, int flags)

{

    FTPContext *s = h->priv_data;

    av_dlog(h, "ftp protocol shutdown\n");

    if (s->conn_data)

        return ffurl_shutdown(s->conn_data, flags);

    return AVERROR(EIO);

}


static inline void RENAME(yuv2yuvX)(int16_t *lumFilter, int16_t **lumSrc, int lumFilterSize,

				    int16_t *chrFilter, int16_t **chrSrc, int chrFilterSize,

				    uint8_t *dest, uint8_t *uDest, uint8_t *vDest, int dstW,

				    int16_t * lumMmxFilter, int16_t * chrMmxFilter)

{

#ifdef HAVE_MMX

	if(uDest != NULL)

	{

		asm volatile(

				YSCALEYUV2YV12X(0)

				:: "m" (-chrFilterSize), "r" (chrSrc+chrFilterSize),

				"r" (chrMmxFilter+chrFilterSize*4), "r" (uDest), "m" (dstW>>1)

				: "%eax", "%edx", "%esi"

			);

		asm volatile(

				YSCALEYUV2YV12X(4096)

				:: "m" (-chrFilterSize), "r" (chrSrc+chrFilterSize),

				"r" (chrMmxFilter+chrFilterSize*4), "r" (vDest), "m" (dstW>>1)

				: "%eax", "%edx", "%esi"

			);

	}

	asm volatile(

			YSCALEYUV2YV12X(0)

			:: "m" (-lumFilterSize), "r" (lumSrc+lumFilterSize),

			   "r" (lumMmxFilter+lumFilterSize*4), "r" (dest), "m" (dstW)

			: "%eax", "%edx", "%esi"

		);

#else

	//FIXME Optimize (just quickly writen not opti..)

	int i;

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

	{

		int val=0;

		int j;

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

			val += lumSrc[j][i] * lumFilter[j];

		dest[i]= MIN(MAX(val>>19, 0), 255);

	}

	if(uDest != NULL)

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

		{

			int u=0;

			int v=0;

			int j;

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

			{

				u += chrSrc[j][i] * chrFilter[j];

				v += chrSrc[j][i + 2048] * chrFilter[j];

			}

			uDest[i]= MIN(MAX(u>>19, 0), 255);

			vDest[i]= MIN(MAX(v>>19, 0), 255);

		}

#endif

}


void enable_kvm_pv_eoi(void)

{

    kvm_default_features |= kvm_pv_eoi_features;

}


iscsi_aio_writev(BlockDriverState *bs, int64_t sector_num,
                 QEMUIOVector *qiov, int nb_sectors,
                 BlockDriverCompletionFunc *cb,
                 void *opaque)
{
    IscsiLun *iscsilun = bs->opaque;
    IscsiAIOCB *acb;
    acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
    trace_iscsi_aio_writev(iscsilun->iscsi, sector_num, nb_sectors, opaque, acb);
    acb->iscsilun    = iscsilun;
    acb->qiov        = qiov;
    acb->nb_sectors  = nb_sectors;
    acb->sector_num  = sector_num;
    acb->retries     = ISCSI_CMD_RETRIES;
    if (iscsi_aio_writev_acb(acb) != 0) {
        qemu_aio_release(acb);
    iscsi_set_events(iscsilun);
    return &acb->common;


static void qemu_s390_flic_class_init(ObjectClass *oc, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    S390FLICStateClass *fsc = S390_FLIC_COMMON_CLASS(oc);

    dc->reset = qemu_s390_flic_reset;

    fsc->register_io_adapter = qemu_s390_register_io_adapter;

    fsc->io_adapter_map = qemu_s390_io_adapter_map;

    fsc->add_adapter_routes = qemu_s390_add_adapter_routes;

    fsc->release_adapter_routes = qemu_s390_release_adapter_routes;

    fsc->clear_io_irq = qemu_s390_clear_io_flic;

    fsc->modify_ais_mode = qemu_s390_modify_ais_mode;

}


static always_inline void gen_op_subfeo_64 (void)

{

    gen_op_move_T2_T0();

    gen_op_subfe_64();

    gen_op_check_subfo_64();

}


static ssize_t rtl8139_do_receive(NetClientState *nc, const uint8_t *buf, size_t size_, int do_interrupt)

{

    RTL8139State *s = qemu_get_nic_opaque(nc);

    PCIDevice *d = PCI_DEVICE(s);

    /* size is the length of the buffer passed to the driver */

    int size = size_;

    const uint8_t *dot1q_buf = NULL;

    uint32_t packet_header = 0;

    uint8_t buf1[MIN_BUF_SIZE + VLAN_HLEN];

    static const uint8_t broadcast_macaddr[6] =

        { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };

    DPRINTF(">>> received len=%d\n", size);

    /* test if board clock is stopped */

    if (!s->clock_enabled)

    {

        DPRINTF("stopped ==========================\n");

        return -1;

    }

    /* first check if receiver is enabled */

    if (!rtl8139_receiver_enabled(s))

    {

        DPRINTF("receiver disabled ================\n");

        return -1;

    }

    /* XXX: check this */

    if (s->RxConfig & AcceptAllPhys) {

        /* promiscuous: receive all */

        DPRINTF(">>> packet received in promiscuous mode\n");

    } else {

        if (!memcmp(buf,  broadcast_macaddr, 6)) {

            /* broadcast address */

            if (!(s->RxConfig & AcceptBroadcast))

            {

                DPRINTF(">>> broadcast packet rejected\n");

                /* update tally counter */

                ++s->tally_counters.RxERR;

                return size;

            }

            packet_header |= RxBroadcast;

            DPRINTF(">>> broadcast packet received\n");

            /* update tally counter */

            ++s->tally_counters.RxOkBrd;

        } else if (buf[0] & 0x01) {

            /* multicast */

            if (!(s->RxConfig & AcceptMulticast))

            {

                DPRINTF(">>> multicast packet rejected\n");

                /* update tally counter */

                ++s->tally_counters.RxERR;

                return size;

            }

            int mcast_idx = compute_mcast_idx(buf);

            if (!(s->mult[mcast_idx >> 3] & (1 << (mcast_idx & 7))))

            {

                DPRINTF(">>> multicast address mismatch\n");

                /* update tally counter */

                ++s->tally_counters.RxERR;

                return size;

            }

            packet_header |= RxMulticast;

            DPRINTF(">>> multicast packet received\n");

            /* update tally counter */

            ++s->tally_counters.RxOkMul;

        } else if (s->phys[0] == buf[0] &&

                   s->phys[1] == buf[1] &&

                   s->phys[2] == buf[2] &&

                   s->phys[3] == buf[3] &&

                   s->phys[4] == buf[4] &&

                   s->phys[5] == buf[5]) {

            /* match */

            if (!(s->RxConfig & AcceptMyPhys))

            {

                DPRINTF(">>> rejecting physical address matching packet\n");

                /* update tally counter */

                ++s->tally_counters.RxERR;

                return size;

            }

            packet_header |= RxPhysical;

            DPRINTF(">>> physical address matching packet received\n");

            /* update tally counter */

            ++s->tally_counters.RxOkPhy;

        } else {

            DPRINTF(">>> unknown packet\n");

            /* update tally counter */

            ++s->tally_counters.RxERR;

            return size;

        }

    }

    /* if too small buffer, then expand it

     * Include some tailroom in case a vlan tag is later removed. */

    if (size < MIN_BUF_SIZE + VLAN_HLEN) {

        memcpy(buf1, buf, size);

        memset(buf1 + size, 0, MIN_BUF_SIZE + VLAN_HLEN - size);

        buf = buf1;

        if (size < MIN_BUF_SIZE) {

            size = MIN_BUF_SIZE;

        }

    }

    if (rtl8139_cp_receiver_enabled(s))

    {

        if (!rtl8139_cp_rx_valid(s)) {

            return size;

        }

        DPRINTF("in C+ Rx mode ================\n");

        /* begin C+ receiver mode */

/* w0 ownership flag */

#define CP_RX_OWN (1<<31)

/* w0 end of ring flag */

#define CP_RX_EOR (1<<30)

/* w0 bits 0...12 : buffer size */

#define CP_RX_BUFFER_SIZE_MASK ((1<<13) - 1)

/* w1 tag available flag */

#define CP_RX_TAVA (1<<16)

/* w1 bits 0...15 : VLAN tag */

#define CP_RX_VLAN_TAG_MASK ((1<<16) - 1)

/* w2 low  32bit of Rx buffer ptr */

/* w3 high 32bit of Rx buffer ptr */

        int descriptor = s->currCPlusRxDesc;

        dma_addr_t cplus_rx_ring_desc;

        cplus_rx_ring_desc = rtl8139_addr64(s->RxRingAddrLO, s->RxRingAddrHI);

        cplus_rx_ring_desc += 16 * descriptor;

        DPRINTF("+++ C+ mode reading RX descriptor %d from host memory at "

            "%08x %08x = "DMA_ADDR_FMT"\n", descriptor, s->RxRingAddrHI,

            s->RxRingAddrLO, cplus_rx_ring_desc);

        uint32_t val, rxdw0,rxdw1,rxbufLO,rxbufHI;

        pci_dma_read(d, cplus_rx_ring_desc, &val, 4);

        rxdw0 = le32_to_cpu(val);

        pci_dma_read(d, cplus_rx_ring_desc+4, &val, 4);

        rxdw1 = le32_to_cpu(val);

        pci_dma_read(d, cplus_rx_ring_desc+8, &val, 4);

        rxbufLO = le32_to_cpu(val);

        pci_dma_read(d, cplus_rx_ring_desc+12, &val, 4);

        rxbufHI = le32_to_cpu(val);

        DPRINTF("+++ C+ mode RX descriptor %d %08x %08x %08x %08x\n",

            descriptor, rxdw0, rxdw1, rxbufLO, rxbufHI);

        if (!(rxdw0 & CP_RX_OWN))

        {

            DPRINTF("C+ Rx mode : descriptor %d is owned by host\n",

                descriptor);

            s->IntrStatus |= RxOverflow;

            ++s->RxMissed;

            /* update tally counter */

            ++s->tally_counters.RxERR;

            ++s->tally_counters.MissPkt;

            rtl8139_update_irq(s);

            return size_;

        }

        uint32_t rx_space = rxdw0 & CP_RX_BUFFER_SIZE_MASK;

        /* write VLAN info to descriptor variables. */

        if (s->CpCmd & CPlusRxVLAN && be16_to_cpup((uint16_t *)

                &buf[ETH_ALEN * 2]) == ETH_P_VLAN) {

            dot1q_buf = &buf[ETH_ALEN * 2];

            size -= VLAN_HLEN;

            /* if too small buffer, use the tailroom added duing expansion */

            if (size < MIN_BUF_SIZE) {

                size = MIN_BUF_SIZE;

            }

            rxdw1 &= ~CP_RX_VLAN_TAG_MASK;

            /* BE + ~le_to_cpu()~ + cpu_to_le() = BE */

            rxdw1 |= CP_RX_TAVA | le16_to_cpup((uint16_t *)

                &dot1q_buf[ETHER_TYPE_LEN]);

            DPRINTF("C+ Rx mode : extracted vlan tag with tci: ""%u\n",

                be16_to_cpup((uint16_t *)&dot1q_buf[ETHER_TYPE_LEN]));

        } else {

            /* reset VLAN tag flag */

            rxdw1 &= ~CP_RX_TAVA;

        }

        /* TODO: scatter the packet over available receive ring descriptors space */

        if (size+4 > rx_space)

        {

            DPRINTF("C+ Rx mode : descriptor %d size %d received %d + 4\n",

                descriptor, rx_space, size);

            s->IntrStatus |= RxOverflow;

            ++s->RxMissed;

            /* update tally counter */

            ++s->tally_counters.RxERR;

            ++s->tally_counters.MissPkt;

            rtl8139_update_irq(s);

            return size_;

        }

        dma_addr_t rx_addr = rtl8139_addr64(rxbufLO, rxbufHI);

        /* receive/copy to target memory */

        if (dot1q_buf) {

            pci_dma_write(d, rx_addr, buf, 2 * ETH_ALEN);

            pci_dma_write(d, rx_addr + 2 * ETH_ALEN,

                          buf + 2 * ETH_ALEN + VLAN_HLEN,

                          size - 2 * ETH_ALEN);

        } else {

            pci_dma_write(d, rx_addr, buf, size);

        }

        if (s->CpCmd & CPlusRxChkSum)

        {

            /* do some packet checksumming */

        }

        /* write checksum */

        val = cpu_to_le32(crc32(0, buf, size_));

        pci_dma_write(d, rx_addr+size, (uint8_t *)&val, 4);

/* first segment of received packet flag */

#define CP_RX_STATUS_FS (1<<29)

/* last segment of received packet flag */

#define CP_RX_STATUS_LS (1<<28)

/* multicast packet flag */

#define CP_RX_STATUS_MAR (1<<26)

/* physical-matching packet flag */

#define CP_RX_STATUS_PAM (1<<25)

/* broadcast packet flag */

#define CP_RX_STATUS_BAR (1<<24)

/* runt packet flag */

#define CP_RX_STATUS_RUNT (1<<19)

/* crc error flag */

#define CP_RX_STATUS_CRC (1<<18)

/* IP checksum error flag */

#define CP_RX_STATUS_IPF (1<<15)

/* UDP checksum error flag */

#define CP_RX_STATUS_UDPF (1<<14)

/* TCP checksum error flag */

#define CP_RX_STATUS_TCPF (1<<13)

        /* transfer ownership to target */

        rxdw0 &= ~CP_RX_OWN;

        /* set first segment bit */

        rxdw0 |= CP_RX_STATUS_FS;

        /* set last segment bit */

        rxdw0 |= CP_RX_STATUS_LS;

        /* set received packet type flags */

        if (packet_header & RxBroadcast)

            rxdw0 |= CP_RX_STATUS_BAR;

        if (packet_header & RxMulticast)

            rxdw0 |= CP_RX_STATUS_MAR;

        if (packet_header & RxPhysical)

            rxdw0 |= CP_RX_STATUS_PAM;

        /* set received size */

        rxdw0 &= ~CP_RX_BUFFER_SIZE_MASK;

        rxdw0 |= (size+4);

        /* update ring data */

        val = cpu_to_le32(rxdw0);

        pci_dma_write(d, cplus_rx_ring_desc, (uint8_t *)&val, 4);

        val = cpu_to_le32(rxdw1);

        pci_dma_write(d, cplus_rx_ring_desc+4, (uint8_t *)&val, 4);

        /* update tally counter */

        ++s->tally_counters.RxOk;

        /* seek to next Rx descriptor */

        if (rxdw0 & CP_RX_EOR)

        {

            s->currCPlusRxDesc = 0;

        }

        else

        {

            ++s->currCPlusRxDesc;

        }

        DPRINTF("done C+ Rx mode ----------------\n");

    }

    else

    {

        DPRINTF("in ring Rx mode ================\n");

        /* begin ring receiver mode */

        int avail = MOD2(s->RxBufferSize + s->RxBufPtr - s->RxBufAddr, s->RxBufferSize);

        /* if receiver buffer is empty then avail == 0 */

#define RX_ALIGN(x) (((x) + 3) & ~0x3)

        if (avail != 0 && RX_ALIGN(size + 8) >= avail)

        {

            DPRINTF("rx overflow: rx buffer length %d head 0x%04x "

                "read 0x%04x === available 0x%04x need 0x%04x\n",

                s->RxBufferSize, s->RxBufAddr, s->RxBufPtr, avail, size + 8);

            s->IntrStatus |= RxOverflow;

            ++s->RxMissed;

            rtl8139_update_irq(s);

            return size_;

        }

        packet_header |= RxStatusOK;

        packet_header |= (((size+4) << 16) & 0xffff0000);

        /* write header */

        uint32_t val = cpu_to_le32(packet_header);

        rtl8139_write_buffer(s, (uint8_t *)&val, 4);

        rtl8139_write_buffer(s, buf, size);

        /* write checksum */

        val = cpu_to_le32(crc32(0, buf, size));

        rtl8139_write_buffer(s, (uint8_t *)&val, 4);

        /* correct buffer write pointer */

        s->RxBufAddr = MOD2(RX_ALIGN(s->RxBufAddr), s->RxBufferSize);

        /* now we can signal we have received something */

        DPRINTF("received: rx buffer length %d head 0x%04x read 0x%04x\n",

            s->RxBufferSize, s->RxBufAddr, s->RxBufPtr);

    }

    s->IntrStatus |= RxOK;

    if (do_interrupt)

    {

        rtl8139_update_irq(s);

    }

    return size_;

}


void start_auth_sasl(VncState *vs)

{

    const char *mechlist = NULL;

    sasl_security_properties_t secprops;

    int err;

    char *localAddr, *remoteAddr;

    int mechlistlen;

    VNC_DEBUG("Initialize SASL auth %d\n", vs->csock);

    /* Get local & remote client addresses in form  IPADDR;PORT */

    if (!(localAddr = vnc_socket_local_addr("%s;%s", vs->csock)))

        goto authabort;

    if (!(remoteAddr = vnc_socket_remote_addr("%s;%s", vs->csock))) {

        g_free(localAddr);

        goto authabort;

    }

    err = sasl_server_new("vnc",

                          NULL, /* FQDN - just delegates to gethostname */

                          NULL, /* User realm */

                          localAddr,

                          remoteAddr,

                          NULL, /* Callbacks, not needed */

                          SASL_SUCCESS_DATA,

                          &vs->sasl.conn);

    g_free(localAddr);

    g_free(remoteAddr);

    localAddr = remoteAddr = NULL;

    if (err != SASL_OK) {

        VNC_DEBUG("sasl context setup failed %d (%s)",

                  err, sasl_errstring(err, NULL, NULL));

        vs->sasl.conn = NULL;

        goto authabort;

    }

#ifdef CONFIG_VNC_TLS

    /* Inform SASL that we've got an external SSF layer from TLS/x509 */

    if (vs->auth == VNC_AUTH_VENCRYPT &&

        vs->subauth == VNC_AUTH_VENCRYPT_X509SASL) {

        gnutls_cipher_algorithm_t cipher;

        sasl_ssf_t ssf;

        cipher = gnutls_cipher_get(vs->tls.session);

        if (!(ssf = (sasl_ssf_t)gnutls_cipher_get_key_size(cipher))) {

            VNC_DEBUG("%s", "cannot TLS get cipher size\n");

            sasl_dispose(&vs->sasl.conn);

            vs->sasl.conn = NULL;

            goto authabort;

        }

        ssf *= 8; /* tls key size is bytes, sasl wants bits */

        err = sasl_setprop(vs->sasl.conn, SASL_SSF_EXTERNAL, &ssf);

        if (err != SASL_OK) {

            VNC_DEBUG("cannot set SASL external SSF %d (%s)\n",

                      err, sasl_errstring(err, NULL, NULL));

            sasl_dispose(&vs->sasl.conn);

            vs->sasl.conn = NULL;

            goto authabort;

        }

    } else

#endif /* CONFIG_VNC_TLS */

        vs->sasl.wantSSF = 1;

    memset (&secprops, 0, sizeof secprops);

    /* Inform SASL that we've got an external SSF layer from TLS */

    if (vs->vd->is_unix

#ifdef CONFIG_VNC_TLS

        /* Disable SSF, if using TLS+x509+SASL only. TLS without x509

           is not sufficiently strong */

        || (vs->auth == VNC_AUTH_VENCRYPT &&

            vs->subauth == VNC_AUTH_VENCRYPT_X509SASL)

#endif /* CONFIG_VNC_TLS */

        ) {

        /* If we've got TLS or UNIX domain sock, we don't care about SSF */

        secprops.min_ssf = 0;

        secprops.max_ssf = 0;

        secprops.maxbufsize = 8192;

        secprops.security_flags = 0;

    } else {

        /* Plain TCP, better get an SSF layer */

        secprops.min_ssf = 56; /* Good enough to require kerberos */

        secprops.max_ssf = 100000; /* Arbitrary big number */

        secprops.maxbufsize = 8192;

        /* Forbid any anonymous or trivially crackable auth */

        secprops.security_flags =

            SASL_SEC_NOANONYMOUS | SASL_SEC_NOPLAINTEXT;

    }

    err = sasl_setprop(vs->sasl.conn, SASL_SEC_PROPS, &secprops);

    if (err != SASL_OK) {

        VNC_DEBUG("cannot set SASL security props %d (%s)\n",

                  err, sasl_errstring(err, NULL, NULL));

        sasl_dispose(&vs->sasl.conn);

        vs->sasl.conn = NULL;

        goto authabort;

    }

    err = sasl_listmech(vs->sasl.conn,

                        NULL, /* Don't need to set user */

                        "", /* Prefix */

                        ",", /* Separator */

                        "", /* Suffix */

                        &mechlist,

                        NULL,

                        NULL);

    if (err != SASL_OK) {

        VNC_DEBUG("cannot list SASL mechanisms %d (%s)\n",

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

        sasl_dispose(&vs->sasl.conn);

        vs->sasl.conn = NULL;

        goto authabort;

    }

    VNC_DEBUG("Available mechanisms for client: '%s'\n", mechlist);

    vs->sasl.mechlist = g_strdup(mechlist);

    mechlistlen = strlen(mechlist);

    vnc_write_u32(vs, mechlistlen);

    vnc_write(vs, mechlist, mechlistlen);

    vnc_flush(vs);

    VNC_DEBUG("Wait for client mechname length\n");

    vnc_read_when(vs, protocol_client_auth_sasl_mechname_len, 4);

    return;

 authabort:

    vnc_client_error(vs);

}


fork_exec(struct socket *so, const char *ex, int do_pty)

{

	int s;

	struct sockaddr_in addr;

	socklen_t addrlen = sizeof(addr);

	int opt;

	const char *argv[256];

	/* don't want to clobber the original */

	char *bptr;

	const char *curarg;

	int c, i, ret;

	pid_t pid;

	DEBUG_CALL("fork_exec");

	DEBUG_ARG("so = %p", so);

	DEBUG_ARG("ex = %p", ex);

	DEBUG_ARG("do_pty = %x", do_pty);

	if (do_pty == 2) {

                return 0;

	} else {

		addr.sin_family = AF_INET;

		addr.sin_port = 0;

		addr.sin_addr.s_addr = INADDR_ANY;

		if ((s = qemu_socket(AF_INET, SOCK_STREAM, 0)) < 0 ||

		    bind(s, (struct sockaddr *)&addr, addrlen) < 0 ||

		    listen(s, 1) < 0) {

			error_report("Error: inet socket: %s", strerror(errno));

			closesocket(s);

			return 0;

		}

	}

	pid = fork();

	switch(pid) {

	 case -1:

		error_report("Error: fork failed: %s", strerror(errno));

		close(s);

		return 0;

	 case 0:

                setsid();

		/* Set the DISPLAY */

                getsockname(s, (struct sockaddr *)&addr, &addrlen);

                close(s);

                /*

                 * Connect to the socket

                 * XXX If any of these fail, we're in trouble!

                 */

                s = qemu_socket(AF_INET, SOCK_STREAM, 0);

                addr.sin_addr = loopback_addr;

                do {

                    ret = connect(s, (struct sockaddr *)&addr, addrlen);

                } while (ret < 0 && errno == EINTR);

		dup2(s, 0);

		dup2(s, 1);

		dup2(s, 2);

		for (s = getdtablesize() - 1; s >= 3; s--)

		   close(s);

		i = 0;

		bptr = g_strdup(ex); /* No need to free() this */

		if (do_pty == 1) {

			/* Setup "slirp.telnetd -x" */

			argv[i++] = "slirp.telnetd";

			argv[i++] = "-x";

			argv[i++] = bptr;

		} else

		   do {

			/* Change the string into argv[] */

			curarg = bptr;

			while (*bptr != ' ' && *bptr != (char)0)

			   bptr++;

			c = *bptr;

			*bptr++ = (char)0;

			argv[i++] = g_strdup(curarg);

		   } while (c);

                argv[i] = NULL;

		execvp(argv[0], (char **)argv);

		/* Ooops, failed, let's tell the user why */

        fprintf(stderr, "Error: execvp of %s failed: %s\n",

                argv[0], strerror(errno));

		close(0); close(1); close(2); /* XXX */

		exit(1);

	 default:

		qemu_add_child_watch(pid);

                /*

                 * XXX this could block us...

                 * XXX Should set a timer here, and if accept() doesn't

                 * return after X seconds, declare it a failure

                 * The only reason this will block forever is if socket()

                 * of connect() fail in the child process

                 */

                do {

                    so->s = accept(s, (struct sockaddr *)&addr, &addrlen);

                } while (so->s < 0 && errno == EINTR);

                closesocket(s);

                socket_set_fast_reuse(so->s);

                opt = 1;

                qemu_setsockopt(so->s, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(int));

		qemu_set_nonblock(so->s);

		/* Append the telnet options now */

                if (so->so_m != NULL && do_pty == 1)  {

			sbappend(so, so->so_m);

                        so->so_m = NULL;

		}

		return 1;

	}

}


static int huff_build12(VLC *vlc, uint8_t *len)

{

    HuffEntry he[4096];

    uint32_t codes[4096];

    uint8_t bits[4096];

    uint16_t syms[4096];

    uint32_t code;

    int i;

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

        he[i].sym = 4095 - i;

        he[i].len = len[i];

        if (len[i] == 0)

            return AVERROR_INVALIDDATA;

    }

    AV_QSORT(he, 4096, HuffEntry, huff_cmp_len12);

    code = 1;

    for (i = 4095; i >= 0; i--) {

        codes[i] = code >> (32 - he[i].len);

        bits[i]  = he[i].len;

        syms[i]  = he[i].sym;

        code += 0x80000000u >> (he[i].len - 1);

    }

    ff_free_vlc(vlc);

    return ff_init_vlc_sparse(vlc, FFMIN(he[4095].len, 14), 4096,

                              bits,  sizeof(*bits),  sizeof(*bits),

                              codes, sizeof(*codes), sizeof(*codes),

                              syms,  sizeof(*syms),  sizeof(*syms), 0);

}


static int vnc_set_x509_credential(VncDisplay *vd,

                                   const char *certdir,

                                   const char *filename,

                                   char **cred,

                                   int ignoreMissing)

{

    struct stat sb;

    g_free(*cred);

    *cred = g_malloc(strlen(certdir) + strlen(filename) + 2);

    strcpy(*cred, certdir);

    strcat(*cred, "/");

    strcat(*cred, filename);

    VNC_DEBUG("Check %s\n", *cred);

    if (stat(*cred, &sb) < 0) {

        g_free(*cred);

        *cred = NULL;

        if (ignoreMissing && errno == ENOENT)

            return 0;

        return -1;

    }

    return 0;

}


int kvmppc_remove_spapr_tce(void *table, int fd, uint32_t window_size)

{

    long len;

    if (fd < 0) {

        return -1;

    }

    len = (window_size / SPAPR_VIO_TCE_PAGE_SIZE)*sizeof(VIOsPAPR_RTCE);

    if ((munmap(table, len) < 0) ||

        (close(fd) < 0)) {

        fprintf(stderr, "KVM: Unexpected error removing KVM SPAPR TCE "

                "table: %s", strerror(errno));

        /* Leak the table */

    }

    return 0;

}


int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic){

    int i;

    int w= s->width;

    int h= s->height;

    InternalBuffer *buf;

    int *picture_number;

    assert(pic->data[0]==NULL);

    assert(INTERNAL_BUFFER_SIZE > s->internal_buffer_count);

    if(avcodec_check_dimensions(s,w,h))

        return -1;

    if(s->internal_buffer==NULL){

        s->internal_buffer= av_mallocz(INTERNAL_BUFFER_SIZE*sizeof(InternalBuffer));

    }

#if 0

    s->internal_buffer= av_fast_realloc(

        s->internal_buffer,

        &s->internal_buffer_size,

        sizeof(InternalBuffer)*FFMAX(99,  s->internal_buffer_count+1)/*FIXME*/

        );

#endif

    buf= &((InternalBuffer*)s->internal_buffer)[s->internal_buffer_count];

    picture_number= &(((InternalBuffer*)s->internal_buffer)[INTERNAL_BUFFER_SIZE-1]).last_pic_num; //FIXME ugly hack

    (*picture_number)++;

    if(buf->base[0]){

        pic->age= *picture_number - buf->last_pic_num;

        buf->last_pic_num= *picture_number;

    }else{

        int h_chroma_shift, v_chroma_shift;

        int pixel_size, size[3];

        AVPicture picture;

        avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);

        avcodec_align_dimensions(s, &w, &h);

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

            w+= EDGE_WIDTH*2;

            h+= EDGE_WIDTH*2;

        }

        avpicture_fill(&picture, NULL, s->pix_fmt, w, h);

        pixel_size= picture.linesize[0]*8 / w;

//av_log(NULL, AV_LOG_ERROR, "%d %d %d %d\n", (int)picture.data[1], w, h, s->pix_fmt);

        assert(pixel_size>=1);

            //FIXME next ensures that linesize= 2^x uvlinesize, thats needed because some MC code assumes it

        if(pixel_size == 3*8)

            w= ALIGN(w, STRIDE_ALIGN<<h_chroma_shift);

        else

            w= ALIGN(pixel_size*w, STRIDE_ALIGN<<(h_chroma_shift+3)) / pixel_size;

        size[1] = avpicture_fill(&picture, NULL, s->pix_fmt, w, h);

        size[0] = picture.linesize[0] * h;

        size[1] -= size[0];

        if(picture.data[2])

            size[1]= size[2]= size[1]/2;

        else

            size[2]= 0;

        buf->last_pic_num= -256*256*256*64;

        memset(buf->base, 0, sizeof(buf->base));

        memset(buf->data, 0, sizeof(buf->data));

        for(i=0; i<3 && size[i]; i++){

            const int h_shift= i==0 ? 0 : h_chroma_shift;

            const int v_shift= i==0 ? 0 : v_chroma_shift;

            buf->linesize[i]= picture.linesize[i];

            buf->base[i]= av_malloc(size[i]+16); //FIXME 16

            if(buf->base[i]==NULL) return -1;

            memset(buf->base[i], 128, size[i]);

            // no edge if EDEG EMU or not planar YUV, we check for PAL8 redundantly to protect against a exploitable bug regression ...

            if((s->flags&CODEC_FLAG_EMU_EDGE) || (s->pix_fmt == PIX_FMT_PAL8) || !size[2])

                buf->data[i] = buf->base[i];

            else

                buf->data[i] = buf->base[i] + ALIGN((buf->linesize[i]*EDGE_WIDTH>>v_shift) + (EDGE_WIDTH>>h_shift), STRIDE_ALIGN);

        }

        pic->age= 256*256*256*64;

    }

    pic->type= FF_BUFFER_TYPE_INTERNAL;

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

        pic->base[i]= buf->base[i];

        pic->data[i]= buf->data[i];

        pic->linesize[i]= buf->linesize[i];

    }

    s->internal_buffer_count++;

    return 0;

}


iscsi_aio_read16_cb(struct iscsi_context *iscsi, int status,

                    void *command_data, void *opaque)

{

    IscsiAIOCB *acb = opaque;

    trace_iscsi_aio_read16_cb(iscsi, status, acb, acb->canceled);

    if (acb->canceled) {

        qemu_aio_release(acb);

        return;

    }

    acb->status = 0;

    if (status != 0) {

        error_report("Failed to read16 data from iSCSI lun. %s",

                     iscsi_get_error(iscsi));

        acb->status = -EIO;

    }

    iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);

}


static int uhci_complete_td(UHCIState *s, UHCI_TD *td, UHCIAsync *async, uint32_t *int_mask)

{

    int len = 0, max_len, err, ret;

    uint8_t pid;

    max_len = ((td->token >> 21) + 1) & 0x7ff;

    pid = td->token & 0xff;

    ret = async->packet.len;

    if (td->ctrl & TD_CTRL_IOS)

        td->ctrl &= ~TD_CTRL_ACTIVE;

    if (ret < 0)

        goto out;

    len = async->packet.len;

    td->ctrl = (td->ctrl & ~0x7ff) | ((len - 1) & 0x7ff);

    /* The NAK bit may have been set by a previous frame, so clear it

       here.  The docs are somewhat unclear, but win2k relies on this

       behavior.  */

    td->ctrl &= ~(TD_CTRL_ACTIVE | TD_CTRL_NAK);

    if (td->ctrl & TD_CTRL_IOC)

        *int_mask |= 0x01;

    if (pid == USB_TOKEN_IN) {

        if (len > max_len) {

            ret = USB_RET_BABBLE;

            goto out;

        }

        if (len > 0) {

            /* write the data back */

            cpu_physical_memory_write(td->buffer, async->buffer, len);

        }

        if ((td->ctrl & TD_CTRL_SPD) && len < max_len) {

            *int_mask |= 0x02;

            /* short packet: do not update QH */

            DPRINTF("uhci: short packet. td 0x%x token 0x%x\n", async->td, async->token);

            return 1;

        }

    }

    /* success */

    return 0;

out:

    switch(ret) {

    case USB_RET_STALL:

        td->ctrl |= TD_CTRL_STALL;

        td->ctrl &= ~TD_CTRL_ACTIVE;

        s->status |= UHCI_STS_USBERR;

        if (td->ctrl & TD_CTRL_IOC) {

            *int_mask |= 0x01;

        }

        uhci_update_irq(s);

        return 1;

    case USB_RET_BABBLE:

        td->ctrl |= TD_CTRL_BABBLE | TD_CTRL_STALL;

        td->ctrl &= ~TD_CTRL_ACTIVE;

        s->status |= UHCI_STS_USBERR;

        if (td->ctrl & TD_CTRL_IOC) {

            *int_mask |= 0x01;

        }

        uhci_update_irq(s);

        /* frame interrupted */

        return -1;

    case USB_RET_NAK:

        td->ctrl |= TD_CTRL_NAK;

        if (pid == USB_TOKEN_SETUP)

            break;

	return 1;

    case USB_RET_NODEV:

    default:

	break;

    }

    /* Retry the TD if error count is not zero */

    td->ctrl |= TD_CTRL_TIMEOUT;

    err = (td->ctrl >> TD_CTRL_ERROR_SHIFT) & 3;

    if (err != 0) {

        err--;

        if (err == 0) {

            td->ctrl &= ~TD_CTRL_ACTIVE;

            s->status |= UHCI_STS_USBERR;

            if (td->ctrl & TD_CTRL_IOC)

                *int_mask |= 0x01;

            uhci_update_irq(s);

        }

    }

    td->ctrl = (td->ctrl & ~(3 << TD_CTRL_ERROR_SHIFT)) |

        (err << TD_CTRL_ERROR_SHIFT);

    return 1;

}