void helper_st_asi(target_ulong addr, target_ulong val, int asi, int size)

{

#ifdef DEBUG_ASI

    dump_asi("write", addr, asi, size, val);

#endif

    asi &= 0xff;

    if ((asi < 0x80 && (env->pstate & PS_PRIV) == 0)

        || ((env->def->features & CPU_FEATURE_HYPV)

            && asi >= 0x30 && asi < 0x80

            && !(env->hpstate & HS_PRIV)))

        raise_exception(TT_PRIV_ACT);

    helper_check_align(addr, size - 1);

    /* Convert to little endian */

    switch (asi) {

    case 0x0c: // Nucleus Little Endian (LE)

    case 0x18: // As if user primary LE

    case 0x19: // As if user secondary LE

    case 0x1c: // Bypass LE

    case 0x1d: // Bypass, non-cacheable LE

    case 0x88: // Primary LE

    case 0x89: // Secondary LE

        switch(size) {

        case 2:

            val = bswap16(val);

            break;

        case 4:

            val = bswap32(val);

            break;

        case 8:

            val = bswap64(val);

            break;

        default:

            break;

        }

    default:

        break;

    }

    switch(asi) {

    case 0x10: // As if user primary

    case 0x11: // As if user secondary

    case 0x18: // As if user primary LE

    case 0x19: // As if user secondary LE

    case 0x80: // Primary

    case 0x81: // Secondary

    case 0x88: // Primary LE

    case 0x89: // Secondary LE

    case 0xe2: // UA2007 Primary block init

    case 0xe3: // UA2007 Secondary block init

        if ((asi & 0x80) && (env->pstate & PS_PRIV)) {

            if ((env->def->features & CPU_FEATURE_HYPV)

                && env->hpstate & HS_PRIV) {

                switch(size) {

                case 1:

                    stb_hypv(addr, val);

                    break;

                case 2:

                    stw_hypv(addr, val);

                    break;

                case 4:

                    stl_hypv(addr, val);

                    break;

                case 8:

                default:

                    stq_hypv(addr, val);

                    break;

                }

            } else {

                /* secondary space access has lowest asi bit equal to 1 */

                if (asi & 1) {

                    switch(size) {

                    case 1:

                        stb_kernel_secondary(addr, val);

                        break;

                    case 2:

                        stw_kernel_secondary(addr, val);

                        break;

                    case 4:

                        stl_kernel_secondary(addr, val);

                        break;

                    case 8:

                    default:

                        stq_kernel_secondary(addr, val);

                        break;

                    }

                } else {

                    switch(size) {

                    case 1:

                        stb_kernel(addr, val);

                        break;

                    case 2:

                        stw_kernel(addr, val);

                        break;

                    case 4:

                        stl_kernel(addr, val);

                        break;

                    case 8:

                    default:

                        stq_kernel(addr, val);

                        break;

                    }

                }

            }

        } else {

            /* secondary space access has lowest asi bit equal to 1 */

            if (asi & 1) {

                switch(size) {

                case 1:

                    stb_user_secondary(addr, val);

                    break;

                case 2:

                    stw_user_secondary(addr, val);

                    break;

                case 4:

                    stl_user_secondary(addr, val);

                    break;

                case 8:

                default:

                    stq_user_secondary(addr, val);

                    break;

                }

            } else {

                switch(size) {

                case 1:

                    stb_user(addr, val);

                    break;

                case 2:

                    stw_user(addr, val);

                    break;

                case 4:

                    stl_user(addr, val);

                    break;

                case 8:

                default:

                    stq_user(addr, val);

                    break;

                }

            }

        }

        break;

    case 0x14: // Bypass

    case 0x15: // Bypass, non-cacheable

    case 0x1c: // Bypass LE

    case 0x1d: // Bypass, non-cacheable LE

        {

            switch(size) {

            case 1:

                stb_phys(addr, val);

                break;

            case 2:

                stw_phys(addr, val);

                break;

            case 4:

                stl_phys(addr, val);

                break;

            case 8:

            default:

                stq_phys(addr, val);

                break;

            }

        }

        return;

    case 0x24: // Nucleus quad LDD 128 bit atomic

    case 0x2c: // Nucleus quad LDD 128 bit atomic LE

        //  Only ldda allowed

        raise_exception(TT_ILL_INSN);

        return;

    case 0x04: // Nucleus

    case 0x0c: // Nucleus Little Endian (LE)

    {

        switch(size) {

        case 1:

            stb_nucleus(addr, val);

            break;

        case 2:

            stw_nucleus(addr, val);

            break;

        case 4:

            stl_nucleus(addr, val);

            break;

        default:

        case 8:

            stq_nucleus(addr, val);

            break;

        }

        break;

    }

    case 0x4a: // UPA config

        // XXX

        return;

    case 0x45: // LSU

        {

            uint64_t oldreg;

            oldreg = env->lsu;

            env->lsu = val & (DMMU_E | IMMU_E);

            // Mappings generated during D/I MMU disabled mode are

            // invalid in normal mode

            if (oldreg != env->lsu) {

                DPRINTF_MMU("LSU change: 0x%" PRIx64 " -> 0x%" PRIx64 "\n",

                            oldreg, env->lsu);

#ifdef DEBUG_MMU

                dump_mmu(env);

#endif

                tlb_flush(env, 1);

            }

            return;

        }

    case 0x50: // I-MMU regs

        {

            int reg = (addr >> 3) & 0xf;

            uint64_t oldreg;

            oldreg = env->immuregs[reg];

            switch(reg) {

            case 0: // RO

                return;

            case 1: // Not in I-MMU

            case 2:

                return;

            case 3: // SFSR

                if ((val & 1) == 0)

                    val = 0; // Clear SFSR

                env->immu.sfsr = val;

                break;

            case 4: // RO

                return;

            case 5: // TSB access

                DPRINTF_MMU("immu TSB write: 0x%016" PRIx64 " -> 0x%016"

                            PRIx64 "\n", env->immu.tsb, val);

                env->immu.tsb = val;

                break;

            case 6: // Tag access

                env->immu.tag_access = val;

                break;

            case 7:

            case 8:

                return;

            default:

                break;

            }

            if (oldreg != env->immuregs[reg]) {

                DPRINTF_MMU("immu change reg[%d]: 0x%016" PRIx64 " -> 0x%016"

                            PRIx64 "\n", reg, oldreg, env->immuregs[reg]);

            }

#ifdef DEBUG_MMU

            dump_mmu(env);

#endif

            return;

        }

    case 0x54: // I-MMU data in

        replace_tlb_1bit_lru(env->itlb, env->immu.tag_access, val, "immu", env);

        return;

    case 0x55: // I-MMU data access

        {

            // TODO: auto demap

            unsigned int i = (addr >> 3) & 0x3f;

            replace_tlb_entry(&env->itlb[i], env->immu.tag_access, val, env);

#ifdef DEBUG_MMU

            DPRINTF_MMU("immu data access replaced entry [%i]\n", i);

            dump_mmu(env);

#endif

            return;

        }

    case 0x57: // I-MMU demap

        demap_tlb(env->itlb, addr, "immu", env);

        return;

    case 0x58: // D-MMU regs

        {

            int reg = (addr >> 3) & 0xf;

            uint64_t oldreg;

            oldreg = env->dmmuregs[reg];

            switch(reg) {

            case 0: // RO

            case 4:

                return;

            case 3: // SFSR

                if ((val & 1) == 0) {

                    val = 0; // Clear SFSR, Fault address

                    env->dmmu.sfar = 0;

                }

                env->dmmu.sfsr = val;

                break;

            case 1: // Primary context

                env->dmmu.mmu_primary_context = val;

                break;

            case 2: // Secondary context

                env->dmmu.mmu_secondary_context = val;

                break;

            case 5: // TSB access

                DPRINTF_MMU("dmmu TSB write: 0x%016" PRIx64 " -> 0x%016"

                            PRIx64 "\n", env->dmmu.tsb, val);

                env->dmmu.tsb = val;

                break;

            case 6: // Tag access

                env->dmmu.tag_access = val;

                break;

            case 7: // Virtual Watchpoint

            case 8: // Physical Watchpoint

            default:

                env->dmmuregs[reg] = val;

                break;

            }

            if (oldreg != env->dmmuregs[reg]) {

                DPRINTF_MMU("dmmu change reg[%d]: 0x%016" PRIx64 " -> 0x%016"

                            PRIx64 "\n", reg, oldreg, env->dmmuregs[reg]);

            }

#ifdef DEBUG_MMU

            dump_mmu(env);

#endif

            return;

        }

    case 0x5c: // D-MMU data in

        replace_tlb_1bit_lru(env->dtlb, env->dmmu.tag_access, val, "dmmu", env);

        return;

    case 0x5d: // D-MMU data access

        {

            unsigned int i = (addr >> 3) & 0x3f;

            replace_tlb_entry(&env->dtlb[i], env->dmmu.tag_access, val, env);

#ifdef DEBUG_MMU

            DPRINTF_MMU("dmmu data access replaced entry [%i]\n", i);

            dump_mmu(env);

#endif

            return;

        }

    case 0x5f: // D-MMU demap

        demap_tlb(env->dtlb, addr, "dmmu", env);

        return;

    case 0x49: // Interrupt data receive

        // XXX

        return;

    case 0x46: // D-cache data

    case 0x47: // D-cache tag access

    case 0x4b: // E-cache error enable

    case 0x4c: // E-cache asynchronous fault status

    case 0x4d: // E-cache asynchronous fault address

    case 0x4e: // E-cache tag data

    case 0x66: // I-cache instruction access

    case 0x67: // I-cache tag access

    case 0x6e: // I-cache predecode

    case 0x6f: // I-cache LRU etc.

    case 0x76: // E-cache tag

    case 0x7e: // E-cache tag

        return;

    case 0x51: // I-MMU 8k TSB pointer, RO

    case 0x52: // I-MMU 64k TSB pointer, RO

    case 0x56: // I-MMU tag read, RO

    case 0x59: // D-MMU 8k TSB pointer, RO

    case 0x5a: // D-MMU 64k TSB pointer, RO

    case 0x5b: // D-MMU data pointer, RO

    case 0x5e: // D-MMU tag read, RO

    case 0x48: // Interrupt dispatch, RO

    case 0x7f: // Incoming interrupt vector, RO

    case 0x82: // Primary no-fault, RO

    case 0x83: // Secondary no-fault, RO

    case 0x8a: // Primary no-fault LE, RO

    case 0x8b: // Secondary no-fault LE, RO

    default:

        do_unassigned_access(addr, 1, 0, 1, size);

        return;

    }

}


static int xan_decode_frame_type0(AVCodecContext *avctx, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    XanContext *s = avctx->priv_data;

    uint8_t *ybuf, *prev_buf, *src = s->scratch_buffer;

    unsigned  chroma_off, corr_off;

    int cur, last, size;

    int i, j;

    int ret;

    corr_off   = AV_RL32(buf + 8);

    chroma_off = AV_RL32(buf + 4);

    if ((ret = xan_decode_chroma(avctx, avpkt)) != 0)

        return ret;

    size = avpkt->size - 4;

    if (corr_off >= avpkt->size) {

        av_log(avctx, AV_LOG_WARNING, "Ignoring invalid correction block position\n");

        corr_off = 0;

    }

    if (corr_off)

        size = corr_off;

    if (chroma_off)

        size = FFMIN(size, chroma_off);

    ret = xan_unpack_luma(buf + 12, size, src, s->buffer_size >> 1);

    if (ret) {

        av_log(avctx, AV_LOG_ERROR, "Luma decoding failed\n");

        return ret;

    }

    ybuf = s->y_buffer;

    last = *src++;

    ybuf[0] = last << 1;

    for (j = 1; j < avctx->width - 1; j += 2) {

        cur = (last + *src++) & 0x1F;

        ybuf[j]   = last + cur;

        ybuf[j+1] = cur << 1;

        last = cur;

    }

    ybuf[j]  = last << 1;

    prev_buf = ybuf;

    ybuf += avctx->width;

    for (i = 1; i < avctx->height; i++) {

        last = ((prev_buf[0] >> 1) + *src++) & 0x1F;

        ybuf[0] = last << 1;

        for (j = 1; j < avctx->width - 1; j += 2) {

            cur = ((prev_buf[j + 1] >> 1) + *src++) & 0x1F;

            ybuf[j]   = last + cur;

            ybuf[j+1] = cur << 1;

            last = cur;

        }

        ybuf[j] = last << 1;

        prev_buf = ybuf;

        ybuf += avctx->width;

    }

    if (corr_off) {

        int corr_end, dec_size;

        corr_end = avpkt->size;

        if (chroma_off > corr_off)

            corr_end = chroma_off;

        dec_size = xan_unpack(s->scratch_buffer, s->buffer_size,

                              avpkt->data + 8 + corr_off,

                              corr_end - corr_off);

        if (dec_size < 0)

            dec_size = 0;

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

            s->y_buffer[i*2+1] = (s->y_buffer[i*2+1] + (s->scratch_buffer[i] << 1)) & 0x3F;

    }

    src  = s->y_buffer;

    ybuf = s->pic.data[0];

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

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

            ybuf[i] = (src[i] << 2) | (src[i] >> 3);

        src  += avctx->width;

        ybuf += s->pic.linesize[0];

    }

    return 0;

}


static void set_chr(Object *obj, Visitor *v, const char *name, void *opaque,

                    Error **errp)

{

    DeviceState *dev = DEVICE(obj);

    Error *local_err = NULL;

    Property *prop = opaque;

    CharBackend *be = qdev_get_prop_ptr(dev, prop);

    CharDriverState *s;

    char *str;

    if (dev->realized) {

        qdev_prop_set_after_realize(dev, name, errp);

        return;

    }

    visit_type_str(v, name, &str, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    if (!*str) {

        g_free(str);

        be->chr = NULL;

        return;

    }

    s = qemu_chr_find(str);

    g_free(str);

    if (s == NULL) {

        error_setg(errp, "Property '%s.%s' can't find value '%s'",

                   object_get_typename(obj), prop->name, str);

        return;

    }

    if (!qemu_chr_fe_init(be, s, errp)) {

        error_prepend(errp, "Property '%s.%s' can't take value '%s': ",

                      object_get_typename(obj), prop->name, str);

        return;

    }

}


void acpi_pcihp_init(Object *owner, AcpiPciHpState *s, PCIBus *root_bus,

                     MemoryRegion *address_space_io, bool bridges_enabled)

{

    s->io_len = ACPI_PCIHP_SIZE;

    s->io_base = ACPI_PCIHP_ADDR;

    s->root= root_bus;

    s->legacy_piix = !bridges_enabled;

    if (s->legacy_piix) {

        unsigned *bus_bsel = g_malloc(sizeof *bus_bsel);

        s->io_len = ACPI_PCIHP_LEGACY_SIZE;

        *bus_bsel = ACPI_PCIHP_BSEL_DEFAULT;

        object_property_add_uint32_ptr(OBJECT(root_bus), ACPI_PCIHP_PROP_BSEL,

                                       bus_bsel, NULL);

    }

    memory_region_init_io(&s->io, owner, &acpi_pcihp_io_ops, s,

                          "acpi-pci-hotplug", s->io_len);

    memory_region_add_subregion(address_space_io, s->io_base, &s->io);

    object_property_add_uint16_ptr(owner, ACPI_PCIHP_IO_BASE_PROP, &s->io_base,

                                   &error_abort);

    object_property_add_uint16_ptr(owner, ACPI_PCIHP_IO_LEN_PROP, &s->io_len,

                                   &error_abort);

}


paint_mouse_pointer(XImage *image, struct x11grab *s)

{

    int x_off = s->x_off;

    int y_off = s->y_off;

    int width = s->width;

    int height = s->height;

    Display *dpy = s->dpy;

    XFixesCursorImage *xcim;

    int x, y;

    int line, column;

    int to_line, to_column;

    int pixstride = image->bits_per_pixel >> 3;

    /* Warning: in its insanity, xlib provides unsigned image data through a

     * char* pointer, so we have to make it uint8_t to make things not break.

     * Anyone who performs further investigation of the xlib API likely risks

     * permanent brain damage. */

    uint8_t *pix = image->data;

    Cursor c;

    Window w;

    XSetWindowAttributes attr;

    /* Code doesn't currently support 16-bit or PAL8 */

    if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)

        return;

    c = XCreateFontCursor(dpy, XC_left_ptr);

    w = DefaultRootWindow(dpy);

    attr.cursor = c;

    XChangeWindowAttributes(dpy, w, CWCursor, &attr);

    xcim = XFixesGetCursorImage(dpy);

    x = xcim->x - xcim->xhot;

    y = xcim->y - xcim->yhot;

    to_line = FFMIN((y + xcim->height), (height + y_off));

    to_column = FFMIN((x + xcim->width), (width + x_off));

    for (line = FFMAX(y, y_off); line < to_line; line++) {

        for (column = FFMAX(x, x_off); column < to_column; column++) {

            int  xcim_addr = (line - y) * xcim->width + column - x;

            int image_addr = ((line - y_off) * width + column - x_off) * pixstride;

            int r = (uint8_t)(xcim->pixels[xcim_addr] >>  0);

            int g = (uint8_t)(xcim->pixels[xcim_addr] >>  8);

            int b = (uint8_t)(xcim->pixels[xcim_addr] >> 16);

            int a = (uint8_t)(xcim->pixels[xcim_addr] >> 24);

            if (a == 255) {

                pix[image_addr+0] = r;

                pix[image_addr+1] = g;

                pix[image_addr+2] = b;

            } else if (a) {

                /* pixel values from XFixesGetCursorImage come premultiplied by alpha */

                pix[image_addr+0] = r + (pix[image_addr+0]*(255-a) + 255/2) / 255;

                pix[image_addr+1] = g + (pix[image_addr+1]*(255-a) + 255/2) / 255;

                pix[image_addr+2] = b + (pix[image_addr+2]*(255-a) + 255/2) / 255;

            }

        }

    }

    XFree(xcim);

    xcim = NULL;

}


int coroutine_fn bdrv_co_pdiscard(BlockDriverState *bs, int64_t offset,

                                  int bytes)

{

    BdrvTrackedRequest req;

    int max_pdiscard, ret;

    int head, tail, align;

        return -ENOMEDIUM;

    if (bdrv_has_readonly_bitmaps(bs)) {

        return -EPERM;

    ret = bdrv_check_byte_request(bs, offset, bytes);

    if (ret < 0) {

        return ret;

    } else if (bs->read_only) {

        return -EPERM;

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

    /* Do nothing if disabled.  */

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

        return 0;

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

        return 0;

    /* Discard is advisory, but some devices track and coalesce

     * unaligned requests, so we must pass everything down rather than

     * round here.  Still, most devices will just silently ignore

     * unaligned requests (by returning -ENOTSUP), so we must fragment

     * the request accordingly.  */

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

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

    head = offset % align;

    tail = (offset + bytes) % align;

    bdrv_inc_in_flight(bs);

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

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

    if (ret < 0) {

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

                                   align);

    assert(max_pdiscard >= bs->bl.request_alignment);

    while (bytes > 0) {

        int num = bytes;

        if (head) {

            /* Make small requests to get to alignment boundaries. */

            num = MIN(bytes, align - head);

            if (!QEMU_IS_ALIGNED(num, bs->bl.request_alignment)) {

                num %= bs->bl.request_alignment;

            head = (head + num) % align;

            assert(num < max_pdiscard);

        } else if (tail) {

            if (num > align) {

                /* Shorten the request to the last aligned cluster.  */

                num -= tail;

            } else if (!QEMU_IS_ALIGNED(tail, bs->bl.request_alignment) &&

                       tail > bs->bl.request_alignment) {

                tail %= bs->bl.request_alignment;

                num -= tail;

        /* limit request size */

        if (num > max_pdiscard) {

            num = max_pdiscard;

        if (bs->drv->bdrv_co_pdiscard) {

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

        } else {

            BlockAIOCB *acb;

            CoroutineIOCompletion co = {

                .coroutine = qemu_coroutine_self(),

            };

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

                                             bdrv_co_io_em_complete, &co);

            if (acb == NULL) {

                ret = -EIO;

            } else {

                qemu_coroutine_yield();

                ret = co.ret;

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

        offset += num;

        bytes -= num;

    ret = 0;

out:

    atomic_inc(&bs->write_gen);

    bdrv_set_dirty(bs, req.offset, req.bytes);

    tracked_request_end(&req);

    bdrv_dec_in_flight(bs);

    return ret;


int ff_mediacodec_dec_close(AVCodecContext *avctx, MediaCodecDecContext *s)
{
    if (s->codec) {
        ff_AMediaCodec_delete(s->codec);
        s->codec = NULL;
    }
    if (s->format) {
        ff_AMediaFormat_delete(s->format);
        s->format = NULL;
    }
    return 0;
}


static void uhci_async_validate_end(UHCIState *s)

{

    UHCIQueue *queue, *n;

    QTAILQ_FOREACH_SAFE(queue, &s->queues, next, n) {

        if (!queue->valid) {

            uhci_queue_free(queue);

        }

    }

}


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

                            int *got_frame, AVPacket *avpkt)

{

    FICContext *ctx = avctx->priv_data;

    uint8_t *src = avpkt->data;

    int ret;

    int slice, nslices;

    int msize;

    int tsize;

    int cur_x, cur_y;

    int skip_cursor = ctx->skip_cursor;

    uint8_t *sdata;

    if ((ret = ff_reget_buffer(avctx, ctx->frame)) < 0)

        return ret;

    /* Header + at least one slice (4) */

    if (avpkt->size < FIC_HEADER_SIZE + 4) {

        av_log(avctx, AV_LOG_ERROR, "Frame data is too small.\n");

        return AVERROR_INVALIDDATA;

    }

    /* Check for header. */

    if (memcmp(src, fic_header, 7))

        av_log(avctx, AV_LOG_WARNING, "Invalid FIC Header.\n");

    /* Is it a skip frame? */

    if (src[17]) {

        if (!ctx->final_frame) {

            av_log(avctx, AV_LOG_WARNING, "Initial frame is skipped\n");

            return AVERROR_INVALIDDATA;

        }

        goto skip;

    }

    nslices = src[13];

    if (!nslices) {

        av_log(avctx, AV_LOG_ERROR, "Zero slices found.\n");

        return AVERROR_INVALIDDATA;

    }

    /* High or Low Quality Matrix? */

    ctx->qmat = src[23] ? fic_qmat_hq : fic_qmat_lq;

    /* Skip cursor data. */

    tsize = AV_RB24(src + 24);

    if (tsize > avpkt->size - FIC_HEADER_SIZE) {

        av_log(avctx, AV_LOG_ERROR,

               "Packet is too small to contain cursor (%d vs %d bytes).\n",

               tsize, avpkt->size - FIC_HEADER_SIZE);

        return AVERROR_INVALIDDATA;

    }

    if (!tsize || !AV_RL16(src + 37) || !AV_RL16(src + 39))

        skip_cursor = 1;

    if (!skip_cursor && tsize < 32) {

        av_log(avctx, AV_LOG_WARNING,

               "Cursor data too small. Skipping cursor.\n");

        skip_cursor = 1;

    }

    /* Cursor position. */

    cur_x = AV_RL16(src + 33);

    cur_y = AV_RL16(src + 35);

    if (!skip_cursor && (cur_x > avctx->width || cur_y > avctx->height)) {

        av_log(avctx, AV_LOG_DEBUG,

               "Invalid cursor position: (%d,%d). Skipping cursor.\n",

               cur_x, cur_y);

        skip_cursor = 1;

    }

    if (!skip_cursor && (AV_RL16(src + 37) != 32 || AV_RL16(src + 39) != 32)) {

        av_log(avctx, AV_LOG_WARNING,

               "Invalid cursor size. Skipping cursor.\n");

        skip_cursor = 1;

    }

    /* Slice height for all but the last slice. */

    ctx->slice_h = 16 * (ctx->aligned_height >> 4) / nslices;

    if (ctx->slice_h % 16)

        ctx->slice_h = FFALIGN(ctx->slice_h - 16, 16);

    /* First slice offset and remaining data. */

    sdata = src + tsize + FIC_HEADER_SIZE + 4 * nslices;

    msize = avpkt->size - nslices * 4 - tsize - FIC_HEADER_SIZE;

    if (msize <= 0) {

        av_log(avctx, AV_LOG_ERROR, "Not enough frame data to decode.\n");

        return AVERROR_INVALIDDATA;

    }

    /*

     * Set the frametype to I initially. It will be set to P if the frame

     * has any dependencies (skip blocks). There will be a race condition

     * inside the slice decode function to set these, but we do not care.

     * since they will only ever be set to 0/P.

     */

    ctx->frame->key_frame = 1;

    ctx->frame->pict_type = AV_PICTURE_TYPE_I;

    /* Allocate slice data. */

    av_fast_malloc(&ctx->slice_data, &ctx->slice_data_size,

                   nslices * sizeof(ctx->slice_data[0]));

    if (!ctx->slice_data_size) {

        av_log(avctx, AV_LOG_ERROR, "Could not allocate slice data.\n");

        return AVERROR(ENOMEM);

    }

    memset(ctx->slice_data, 0, nslices * sizeof(ctx->slice_data[0]));

    for (slice = 0; slice < nslices; slice++) {

        unsigned slice_off = AV_RB32(src + tsize + FIC_HEADER_SIZE + slice * 4);

        unsigned slice_size;

        int y_off   = ctx->slice_h * slice;

        int slice_h = ctx->slice_h;

        /*

         * Either read the slice size, or consume all data left.

         * Also, special case the last slight height.

         */

        if (slice == nslices - 1) {

            slice_size   = msize;

            slice_h      = FFALIGN(avctx->height - ctx->slice_h * (nslices - 1), 16);

        } else {

            slice_size = AV_RB32(src + tsize + FIC_HEADER_SIZE + slice * 4 + 4);

        }

        if (slice_size < slice_off || slice_size > msize)

            continue;

        slice_size -= slice_off;

        ctx->slice_data[slice].src      = sdata + slice_off;

        ctx->slice_data[slice].src_size = slice_size;

        ctx->slice_data[slice].slice_h  = slice_h;

        ctx->slice_data[slice].y_off    = y_off;

    }

    if ((ret = avctx->execute(avctx, fic_decode_slice, ctx->slice_data,

                              NULL, nslices, sizeof(ctx->slice_data[0]))) < 0)

        return ret;

    av_frame_free(&ctx->final_frame);

    ctx->final_frame = av_frame_clone(ctx->frame);

    if (!ctx->final_frame) {

        av_log(avctx, AV_LOG_ERROR, "Could not clone frame buffer.\n");

        return AVERROR(ENOMEM);

    }

    /* Make sure we use a user-supplied buffer. */

    if ((ret = ff_reget_buffer(avctx, ctx->final_frame)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Could not make frame writable.\n");

        return ret;

    }

    /* Draw cursor. */

    if (!skip_cursor) {

        memcpy(ctx->cursor_buf, src + 59, 32 * 32 * 4);

        fic_draw_cursor(avctx, cur_x, cur_y);

    }

skip:

    *got_frame = 1;

    if ((ret = av_frame_ref(data, ctx->final_frame)) < 0)

        return ret;

    return avpkt->size;

}


static void cdrom_pio_impl(int nblocks)

{

    QPCIDevice *dev;

    void *bmdma_base, *ide_base;

    FILE *fh;

    int patt_blocks = MAX(16, nblocks);

    size_t patt_len = ATAPI_BLOCK_SIZE * patt_blocks;

    char *pattern = g_malloc(patt_len);

    size_t rxsize = ATAPI_BLOCK_SIZE * nblocks;

    uint16_t *rx = g_malloc0(rxsize);

    int i, j;

    uint8_t data;

    uint16_t limit;

    /* Prepopulate the CDROM with an interesting pattern */

    generate_pattern(pattern, patt_len, ATAPI_BLOCK_SIZE);

    fh = fopen(tmp_path, "w+");

    fwrite(pattern, ATAPI_BLOCK_SIZE, patt_blocks, fh);

    fclose(fh);

    ide_test_start("-drive if=none,file=%s,media=cdrom,format=raw,id=sr0,index=0 "

                   "-device ide-cd,drive=sr0,bus=ide.0", tmp_path);

    dev = get_pci_device(&bmdma_base, &ide_base);

    qtest_irq_intercept_in(global_qtest, "ioapic");

    /* PACKET command on device 0 */

    qpci_io_writeb(dev, ide_base + reg_device, 0);

    qpci_io_writeb(dev, ide_base + reg_lba_middle, BYTE_COUNT_LIMIT & 0xFF);

    qpci_io_writeb(dev, ide_base + reg_lba_high,

                   (BYTE_COUNT_LIMIT >> 8 & 0xFF));

    qpci_io_writeb(dev, ide_base + reg_command, CMD_PACKET);

    /* HP0: Check_Status_A State */

    nsleep(400);

    data = ide_wait_clear(BSY);

    /* HP1: Send_Packet State */

    assert_bit_set(data, DRQ | DRDY);

    assert_bit_clear(data, ERR | DF | BSY);

    /* SCSI CDB (READ10) -- read n*2048 bytes from block 0 */

    send_scsi_cdb_read10(dev, ide_base, 0, nblocks);

    /* Read data back: occurs in bursts of 'BYTE_COUNT_LIMIT' bytes.

     * If BYTE_COUNT_LIMIT is odd, we transfer BYTE_COUNT_LIMIT - 1 bytes.

     * We allow an odd limit only when the remaining transfer size is

     * less than BYTE_COUNT_LIMIT. However, SCSI's read10 command can only

     * request n blocks, so our request size is always even.

     * For this reason, we assume there is never a hanging byte to fetch. */

    g_assert(!(rxsize & 1));

    limit = BYTE_COUNT_LIMIT & ~1;

    for (i = 0; i < DIV_ROUND_UP(rxsize, limit); i++) {

        size_t offset = i * (limit / 2);

        size_t rem = (rxsize / 2) - offset;

        /* HP3: INTRQ_Wait */

        ide_wait_intr(IDE_PRIMARY_IRQ);

        /* HP2: Check_Status_B (and clear IRQ) */

        data = ide_wait_clear(BSY);

        assert_bit_set(data, DRQ | DRDY);

        assert_bit_clear(data, ERR | DF | BSY);

        /* HP4: Transfer_Data */

        for (j = 0; j < MIN((limit / 2), rem); j++) {

            rx[offset + j] = cpu_to_le16(qpci_io_readw(dev,

                                                       ide_base + reg_data));

        }

    }

    /* Check for final completion IRQ */

    ide_wait_intr(IDE_PRIMARY_IRQ);

    /* Sanity check final state */

    data = ide_wait_clear(DRQ);

    assert_bit_set(data, DRDY);

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

    g_assert_cmpint(memcmp(pattern, rx, rxsize), ==, 0);

    g_free(pattern);

    g_free(rx);

    test_bmdma_teardown();

}


static int append_to_cached_buf(AVCodecContext *avctx,

                                const uint8_t *buf, int buf_size)

{

    DVDSubContext *ctx = avctx->priv_data;

    if (ctx->buf_size > 0xffff - buf_size) {

        av_log(avctx, AV_LOG_WARNING, "Attempt to reconstruct "

               "too large SPU packets aborted.\n");

        av_freep(&ctx->buf);

        return AVERROR_INVALIDDATA;

    }

    ctx->buf = av_realloc(ctx->buf, ctx->buf_size + buf_size);

    if (!ctx->buf)

        return AVERROR(ENOMEM);

    memcpy(ctx->buf + ctx->buf_size, buf, buf_size);

    ctx->buf_size += buf_size;

    return 0;

}


static RxFilterInfo *virtio_net_query_rxfilter(NetClientState *nc)

{

    VirtIONet *n = qemu_get_nic_opaque(nc);

    VirtIODevice *vdev = VIRTIO_DEVICE(n);

    RxFilterInfo *info;

    strList *str_list, *entry;

    int i;

    info = g_malloc0(sizeof(*info));

    info->name = g_strdup(nc->name);

    info->promiscuous = n->promisc;

    if (n->nouni) {

        info->unicast = RX_STATE_NONE;

    } else if (n->alluni) {

        info->unicast = RX_STATE_ALL;

    } else {

        info->unicast = RX_STATE_NORMAL;

    }

    if (n->nomulti) {

        info->multicast = RX_STATE_NONE;

    } else if (n->allmulti) {

        info->multicast = RX_STATE_ALL;

    } else {

        info->multicast = RX_STATE_NORMAL;

    }

    info->broadcast_allowed = n->nobcast;

    info->multicast_overflow = n->mac_table.multi_overflow;

    info->unicast_overflow = n->mac_table.uni_overflow;

    info->main_mac = mac_strdup_printf(n->mac);

    str_list = NULL;

    for (i = 0; i < n->mac_table.first_multi; i++) {

        entry = g_malloc0(sizeof(*entry));

        entry->value = mac_strdup_printf(n->mac_table.macs + i * ETH_ALEN);

        entry->next = str_list;

        str_list = entry;

    }

    info->unicast_table = str_list;

    str_list = NULL;

    for (i = n->mac_table.first_multi; i < n->mac_table.in_use; i++) {

        entry = g_malloc0(sizeof(*entry));

        entry->value = mac_strdup_printf(n->mac_table.macs + i * ETH_ALEN);

        entry->next = str_list;

        str_list = entry;

    }

    info->multicast_table = str_list;

    info->vlan_table = get_vlan_table(n);

    if (!((1 << VIRTIO_NET_F_CTRL_VLAN) & vdev->guest_features)) {

        info->vlan = RX_STATE_ALL;

    } else if (!info->vlan_table) {

        info->vlan = RX_STATE_NONE;

    } else {

        info->vlan = RX_STATE_NORMAL;

    }

    /* enable event notification after query */

    nc->rxfilter_notify_enabled = 1;

    return info;

}


static inline int64_t get_sector_offset(BlockDriverState *bs,

    int64_t sector_num, int write)

{

    BDRVVPCState *s = bs->opaque;

    uint64_t offset = sector_num * 512;

    uint64_t bitmap_offset, block_offset;

    uint32_t pagetable_index, pageentry_index;

    pagetable_index = offset / s->block_size;

    pageentry_index = (offset % s->block_size) / 512;

    if (pagetable_index >= s->max_table_entries || s->pagetable[pagetable_index] == 0xffffffff)

        return -1; // not allocated

    bitmap_offset = 512 * (uint64_t) s->pagetable[pagetable_index];

    block_offset = bitmap_offset + s->bitmap_size + (512 * pageentry_index);

    // We must ensure that we don't write to any sectors which are marked as

    // unused in the bitmap. We get away with setting all bits in the block

    // bitmap each time we write to a new block. This might cause Virtual PC to

    // miss sparse read optimization, but it's not a problem in terms of

    // correctness.

    if (write && (s->last_bitmap_offset != bitmap_offset)) {

        uint8_t bitmap[s->bitmap_size];

        s->last_bitmap_offset = bitmap_offset;

        memset(bitmap, 0xff, s->bitmap_size);

        bdrv_pwrite_sync(bs->file, bitmap_offset, bitmap, s->bitmap_size);

    }

//    printf("sector: %" PRIx64 ", index: %x, offset: %x, bioff: %" PRIx64 ", bloff: %" PRIx64 "\n",

//	sector_num, pagetable_index, pageentry_index,

//	bitmap_offset, block_offset);

// disabled by reason

#if 0

#ifdef CACHE

    if (bitmap_offset != s->last_bitmap)

    {

	lseek(s->fd, bitmap_offset, SEEK_SET);

	s->last_bitmap = bitmap_offset;

	// Scary! Bitmap is stored as big endian 32bit entries,

	// while we used to look it up byte by byte

	read(s->fd, s->pageentry_u8, 512);

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

	    be32_to_cpus(&s->pageentry_u32[i]);

    }

    if ((s->pageentry_u8[pageentry_index / 8] >> (pageentry_index % 8)) & 1)

	return -1;

#else

    lseek(s->fd, bitmap_offset + (pageentry_index / 8), SEEK_SET);

    read(s->fd, &bitmap_entry, 1);

    if ((bitmap_entry >> (pageentry_index % 8)) & 1)

	return -1; // not allocated

#endif

#endif

    return block_offset;

}


av_cold void ff_dcadsp_init_x86(DCADSPContext *s)

{

    int cpu_flags = av_get_cpu_flags();

    if (EXTERNAL_SSE(cpu_flags)) {

#if ARCH_X86_32

        s->int8x8_fmul_int32 = ff_int8x8_fmul_int32_sse;

#endif

        s->lfe_fir[0]        = ff_dca_lfe_fir0_sse;

        s->lfe_fir[1]        = ff_dca_lfe_fir1_sse;

    }

    if (EXTERNAL_SSE2(cpu_flags)) {

        s->int8x8_fmul_int32 = ff_int8x8_fmul_int32_sse2;

    }

    if (EXTERNAL_SSE4(cpu_flags)) {

        s->int8x8_fmul_int32 = ff_int8x8_fmul_int32_sse4;

    }

}


vpc_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,

              QEMUIOVector *qiov, int flags)

{

    BDRVVPCState *s = bs->opaque;

    int ret;

    int64_t image_offset;

    int64_t n_bytes;

    int64_t bytes_done = 0;

    VHDFooter *footer = (VHDFooter *) s->footer_buf;

    QEMUIOVector local_qiov;

    if (be32_to_cpu(footer->type) == VHD_FIXED) {

        return bdrv_co_preadv(bs->file->bs, offset, bytes, qiov, 0);

    }

    qemu_co_mutex_lock(&s->lock);

    qemu_iovec_init(&local_qiov, qiov->niov);

    while (bytes > 0) {

        image_offset = get_image_offset(bs, offset, false);

        n_bytes = MIN(bytes, s->block_size - (offset % s->block_size));

        if (image_offset == -1) {

            qemu_iovec_memset(qiov, bytes_done, 0, n_bytes);

        } else {

            qemu_iovec_reset(&local_qiov);

            qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);

            ret = bdrv_co_preadv(bs->file->bs, image_offset, n_bytes,

                                 &local_qiov, 0);

            if (ret < 0) {

                goto fail;

            }

        }

        bytes -= n_bytes;

        offset += n_bytes;

        bytes_done += n_bytes;

    }

    ret = 0;

fail:

    qemu_iovec_destroy(&local_qiov);

    qemu_co_mutex_unlock(&s->lock);

    return ret;

}


void do_store_dcr (void)

{

    if (unlikely(env->dcr_env == NULL)) {

        if (loglevel != 0) {

            fprintf(logfile, "No DCR environment\n");

        }

        do_raise_exception_err(EXCP_PROGRAM, EXCP_INVAL | EXCP_INVAL_INVAL);

    } else if (unlikely(ppc_dcr_write(env->dcr_env, T0, T1) != 0)) {

        if (loglevel != 0) {

            fprintf(logfile, "DCR write error %d %03x\n", (int)T0, (int)T0);

        }

        do_raise_exception_err(EXCP_PROGRAM, EXCP_INVAL | EXCP_PRIV_REG);

    }

}


static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,

    int64_t offset, unsigned int bytes, QEMUIOVector *qiov, int flags)

{

    BlockDriver *drv = bs->drv;

    BdrvTrackedRequest req;

    int ret;

    int64_t sector_num = offset >> BDRV_SECTOR_BITS;

    unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;

    assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);

    assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);

    if (bs->copy_on_read_in_flight) {

        wait_for_overlapping_requests(bs, offset, bytes);

    }

    tracked_request_begin(&req, bs, offset, bytes, true);

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

    if (ret < 0) {

        /* Do nothing, write notifier decided to fail this request */

    } else if (flags & BDRV_REQ_ZERO_WRITE) {

        ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);

    } else {

        ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);

    }

    if (ret == 0 && !bs->enable_write_cache) {

        ret = bdrv_co_flush(bs);

    }

    bdrv_set_dirty(bs, sector_num, nb_sectors);

    if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {

        bs->wr_highest_sector = sector_num + nb_sectors - 1;

    }

    if (bs->growable && ret >= 0) {

        bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);

    }

    tracked_request_end(&req);

    return ret;

}


INLINE flag extractFloat64Sign( float64 a )

{

    return a>>63;

}


static void read_storage_element1_info(SCLPDevice *sclp, SCCB *sccb)

{

    ReadStorageElementInfo *storage_info = (ReadStorageElementInfo *) sccb;

    sclpMemoryHotplugDev *mhd = get_sclp_memory_hotplug_dev();

    assert(mhd);

    if ((mhd->standby_mem_size >> mhd->increment_size) >= 0x10000) {

        sccb->h.response_code = cpu_to_be16(SCLP_RC_SCCB_BOUNDARY_VIOLATION);

        return;

    }

    /* Return information regarding standby memory */

    storage_info->max_id = cpu_to_be16(mhd->standby_mem_size ? 1 : 0);

    storage_info->assigned = cpu_to_be16(mhd->standby_mem_size >>

                                         mhd->increment_size);

    storage_info->standby = cpu_to_be16(mhd->standby_mem_size >>

                                        mhd->increment_size);

    sccb->h.response_code = cpu_to_be16(SCLP_RC_STANDBY_READ_COMPLETION);

}


uint32_t HELPER(get_cp15)(CPUState *env, uint32_t insn)

{

    cpu_abort(env, "cp15 insn %08x\n", insn);

    return 0;

}


static void tcg_out_st(TCGContext *s, TCGType type, TCGReg arg, TCGReg arg1,

                       intptr_t arg2)

{

    uint8_t *old_code_ptr = s->code_ptr;

    if (type == TCG_TYPE_I32) {

        tcg_out_op_t(s, INDEX_op_st_i32);

        tcg_out_r(s, arg);

        tcg_out_r(s, arg1);

        tcg_out32(s, arg2);

    } else {

        assert(type == TCG_TYPE_I64);

#if TCG_TARGET_REG_BITS == 64

        tcg_out_op_t(s, INDEX_op_st_i64);

        tcg_out_r(s, arg);

        tcg_out_r(s, arg1);

        tcg_out32(s, arg2);

#else

        TODO();

#endif

    }

    old_code_ptr[1] = s->code_ptr - old_code_ptr;

}


static void sdram_unmap_bcr (ppc4xx_sdram_t *sdram)

{

    int i;

    for (i = 0; i < sdram->nbanks; i++) {

#ifdef DEBUG_SDRAM

        printf("%s: Unmap RAM area " TARGET_FMT_plx " " TARGET_FMT_lx "\n",

               __func__, sdram_base(sdram->bcr[i]), sdram_size(sdram->bcr[i]));

#endif

        cpu_register_physical_memory(sdram_base(sdram->bcr[i]),

                                     sdram_size(sdram->bcr[i]),

                                     IO_MEM_UNASSIGNED);

    }

}


static int find_pte64(CPUPPCState *env, struct mmu_ctx_hash64 *ctx, int h,

                      int rw, int type, int target_page_bits)

{

    hwaddr pteg_off;

    target_ulong pte0, pte1;

    int i, good = -1;

    int ret, r;

    ret = -1; /* No entry found */

    pteg_off = (ctx->hash[h] * HASH_PTEG_SIZE_64) & env->htab_mask;

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

        pte0 = ppc_hash64_load_hpte0(env, pteg_off + i*HASH_PTE_SIZE_64);

        pte1 = ppc_hash64_load_hpte1(env, pteg_off + i*HASH_PTE_SIZE_64);

        r = pte64_check(ctx, pte0, pte1, h, rw, type);

        LOG_MMU("Load pte from %016" HWADDR_PRIx " => " TARGET_FMT_lx " "

                TARGET_FMT_lx " %d %d %d " TARGET_FMT_lx "\n",

                pteg_off + (i * 16), pte0, pte1, (int)(pte0 & 1), h,

                (int)((pte0 >> 1) & 1), ctx->ptem);

        switch (r) {

        case -3:

            /* PTE inconsistency */

            return -1;

        case -2:

            /* Access violation */

            ret = -2;

            good = i;

            break;

        case -1:

        default:

            /* No PTE match */

            break;

        case 0:

            /* access granted */

            /* XXX: we should go on looping to check all PTEs consistency

             *      but if we can speed-up the whole thing as the

             *      result would be undefined if PTEs are not consistent.

             */

            ret = 0;

            good = i;

            goto done;

        }

    }

    if (good != -1) {

    done:

        LOG_MMU("found PTE at addr %08" HWADDR_PRIx " prot=%01x ret=%d\n",

                ctx->raddr, ctx->prot, ret);

        /* Update page flags */

        pte1 = ctx->raddr;

        if (ppc_hash64_pte_update_flags(ctx, &pte1, ret, rw) == 1) {

            ppc_hash64_store_hpte1(env, pteg_off + good * HASH_PTE_SIZE_64, pte1);

        }

    }

    /* We have a TLB that saves 4K pages, so let's

     * split a huge page to 4k chunks */

    if (target_page_bits != TARGET_PAGE_BITS) {

        ctx->raddr |= (ctx->eaddr & ((1 << target_page_bits) - 1))

                      & TARGET_PAGE_MASK;

    }

    return ret;

}


int qed_read_l2_table_sync(BDRVQEDState *s, QEDRequest *request, uint64_t offset)

{

    int ret = -EINPROGRESS;

    qed_read_l2_table(s, request, offset, qed_sync_cb, &ret);

    while (ret == -EINPROGRESS) {

        aio_poll(bdrv_get_aio_context(s->bs), true);

    }

    return ret;

}


static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)

{

    if (set)

        *kvm_reg = *qemu_reg;

    else

        *qemu_reg = *kvm_reg;

}


static bool sensor_type_is_dr(uint32_t sensor_type)

{

    switch (sensor_type) {

    case RTAS_SENSOR_TYPE_ISOLATION_STATE:

    case RTAS_SENSOR_TYPE_DR:

    case RTAS_SENSOR_TYPE_ALLOCATION_STATE:

        return true;

    }

    return false;

}


static uint64_t omap_mpuio_read(void *opaque, target_phys_addr_t addr,

                                unsigned size)

{

    struct omap_mpuio_s *s = (struct omap_mpuio_s *) opaque;

    int offset = addr & OMAP_MPUI_REG_MASK;

    uint16_t ret;

    if (size != 2) {

        return omap_badwidth_read16(opaque, addr);

    }

    switch (offset) {

    case 0x00:	/* INPUT_LATCH */

        return s->inputs;

    case 0x04:	/* OUTPUT_REG */

        return s->outputs;

    case 0x08:	/* IO_CNTL */

        return s->dir;

    case 0x10:	/* KBR_LATCH */

        return s->row_latch;

    case 0x14:	/* KBC_REG */

        return s->cols;

    case 0x18:	/* GPIO_EVENT_MODE_REG */

        return s->event;

    case 0x1c:	/* GPIO_INT_EDGE_REG */

        return s->edge;

    case 0x20:	/* KBD_INT */

        return (~s->row_latch & 0x1f) && !s->kbd_mask;

    case 0x24:	/* GPIO_INT */

        ret = s->ints;

        s->ints &= s->mask;

        if (ret)

            qemu_irq_lower(s->irq);

        return ret;

    case 0x28:	/* KBD_MASKIT */

        return s->kbd_mask;

    case 0x2c:	/* GPIO_MASKIT */

        return s->mask;

    case 0x30:	/* GPIO_DEBOUNCING_REG */

        return s->debounce;

    case 0x34:	/* GPIO_LATCH_REG */

        return s->latch;

    }

    OMAP_BAD_REG(addr);

    return 0;

}


int64_t qemu_get_clock_ns(QEMUClock *clock)

{

    return 0;

}


static always_inline void gen_qemu_stf (TCGv t0, TCGv t1, int flags)

{

    TCGv tmp = tcg_temp_new(TCG_TYPE_I32);

    tcg_gen_helper_1_1(helper_f_to_memory, tmp, t0);

    tcg_gen_qemu_st32(tmp, t1, flags);

    tcg_temp_free(tmp);

}


static void vfio_put_group(VFIOGroup *group)

{

    if (!QLIST_EMPTY(&group->device_list)) {

        return;

    }

    vfio_kvm_device_del_group(group);

    vfio_disconnect_container(group);

    QLIST_REMOVE(group, next);

    trace_vfio_put_group(group->fd);

    close(group->fd);

    g_free(group);

    if (QLIST_EMPTY(&group_list)) {

        qemu_unregister_reset(vfio_pci_reset_handler, NULL);

    }

}


static void virtio_ccw_start_ioeventfd(VirtioCcwDevice *dev)

{

    VirtIODevice *vdev;

    int n, r;

    if (!(dev->flags & VIRTIO_CCW_FLAG_USE_IOEVENTFD) ||

        dev->ioeventfd_disabled ||

        dev->ioeventfd_started) {

        return;

    }

    vdev = virtio_bus_get_device(&dev->bus);

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

        if (!virtio_queue_get_num(vdev, n)) {

            continue;

        }

        r = virtio_ccw_set_guest2host_notifier(dev, n, true, true);

        if (r < 0) {

            goto assign_error;

        }

    }

    dev->ioeventfd_started = true;

    return;

  assign_error:

    while (--n >= 0) {

        if (!virtio_queue_get_num(vdev, n)) {

            continue;

        }

        r = virtio_ccw_set_guest2host_notifier(dev, n, false, false);

        assert(r >= 0);

    }

    dev->ioeventfd_started = false;

    /* Disable ioeventfd for this device. */

    dev->flags &= ~VIRTIO_CCW_FLAG_USE_IOEVENTFD;

    error_report("%s: failed. Fallback to userspace (slower).", __func__);

}


void bdrv_set_read_only(BlockDriverState *bs, bool read_only)

{

    bs->read_only = read_only;

}


int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,

    int *num, uint64_t *cluster_offset)

{

    BDRVQcowState *s = bs->opaque;

    unsigned int l2_index;

    uint64_t l1_index, l2_offset, *l2_table;

    int l1_bits, c;

    unsigned int index_in_cluster, nb_clusters;

    uint64_t nb_available, nb_needed;

    int ret;

    index_in_cluster = (offset >> 9) & (s->cluster_sectors - 1);

    nb_needed = *num + index_in_cluster;

    l1_bits = s->l2_bits + s->cluster_bits;

    /* compute how many bytes there are between the offset and

     * the end of the l1 entry

     */

    nb_available = (1ULL << l1_bits) - (offset & ((1ULL << l1_bits) - 1));

    /* compute the number of available sectors */

    nb_available = (nb_available >> 9) + index_in_cluster;

    if (nb_needed > nb_available) {

        nb_needed = nb_available;

    }

    *cluster_offset = 0;

    /* seek the the l2 offset in the l1 table */

    l1_index = offset >> l1_bits;

    if (l1_index >= s->l1_size) {

        ret = QCOW2_CLUSTER_UNALLOCATED;

        goto out;

    }

    l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;

    if (!l2_offset) {

        ret = QCOW2_CLUSTER_UNALLOCATED;

        goto out;

    }

    /* load the l2 table in memory */

    ret = l2_load(bs, l2_offset, &l2_table);

    if (ret < 0) {

        return ret;

    }

    /* find the cluster offset for the given disk offset */

    l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);

    *cluster_offset = be64_to_cpu(l2_table[l2_index]);

    nb_clusters = size_to_clusters(s, nb_needed << 9);

    ret = qcow2_get_cluster_type(*cluster_offset);

    switch (ret) {

    case QCOW2_CLUSTER_COMPRESSED:

        /* Compressed clusters can only be processed one by one */

        c = 1;

        *cluster_offset &= L2E_COMPRESSED_OFFSET_SIZE_MASK;

        break;

    case QCOW2_CLUSTER_ZERO:

        if (s->qcow_version < 3) {

            qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);

            return -EIO;

        }

        c = count_contiguous_clusters(nb_clusters, s->cluster_size,

                &l2_table[l2_index], QCOW_OFLAG_ZERO);

        *cluster_offset = 0;

        break;

    case QCOW2_CLUSTER_UNALLOCATED:

        /* how many empty clusters ? */

        c = count_contiguous_free_clusters(nb_clusters, &l2_table[l2_index]);

        *cluster_offset = 0;

        break;

    case QCOW2_CLUSTER_NORMAL:

        /* how many allocated clusters ? */

        c = count_contiguous_clusters(nb_clusters, s->cluster_size,

                &l2_table[l2_index], QCOW_OFLAG_ZERO);

        *cluster_offset &= L2E_OFFSET_MASK;

        break;

    default:

        abort();

    }

    qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);

    nb_available = (c * s->cluster_sectors);

out:

    if (nb_available > nb_needed)

        nb_available = nb_needed;

    *num = nb_available - index_in_cluster;

    return ret;

}


static int v9fs_synth_mkdir(FsContext *fs_ctx, V9fsPath *path,

                       const char *buf, FsCred *credp)

{

    errno = EPERM;

    return -1;

}


static int rm_write_packet(AVFormatContext *s, AVPacket *pkt)

{

    if (s->streams[pkt->stream_index]->codec.codec_type ==

        CODEC_TYPE_AUDIO)

        return rm_write_audio(s, pkt->data, pkt->size);

    else

        return rm_write_video(s, pkt->data, pkt->size);

}


static uint64_t cs_mem_read(void *opaque, target_phys_addr_t addr,

                            unsigned size)

{

    CSState *s = opaque;

    uint32_t saddr, ret;

    saddr = addr >> 2;

    switch (saddr) {

    case 1:

        switch (CS_RAP(s)) {

        case 3: // Write only

            ret = 0;

            break;

        default:

            ret = s->dregs[CS_RAP(s)];

            break;

        }

        trace_cs4231_mem_readl_dreg(CS_RAP(s), ret);

        break;

    default:

        ret = s->regs[saddr];

        trace_cs4231_mem_readl_reg(saddr, ret);

        break;

    }

    return ret;

}


static int sctp_write(URLContext *h, const uint8_t *buf, int size)

{

    SCTPContext *s = h->priv_data;

    int ret;

    if (!(h->flags & AVIO_FLAG_NONBLOCK)) {

        ret = sctp_wait_fd(s->fd, 1);

        if (ret < 0)

            return ret;

    }

    if (s->max_streams) {

        /*StreamId is introduced as a 2byte code into the stream*/

        struct sctp_sndrcvinfo info = { 0 };

        info.sinfo_stream           = AV_RB16(buf);

        if (info.sinfo_stream > s->max_streams)

            abort();

        ret = ff_sctp_send(s->fd, buf + 2, size - 2, &info, MSG_EOR);

    } else

        ret = send(s->fd, buf, size, 0);

    return ret < 0 ? ff_neterrno() : ret;

}


int avformat_network_init(void)

{

#if CONFIG_NETWORK

    int ret;

    ff_network_inited_globally = 1;

    if ((ret = ff_network_init()) < 0)

        return ret;

    if ((ret = ff_tls_init()) < 0)

        return ret;

#endif

    return 0;

}


static inline void cvtyuvtoRGB (SwsContext *c,

			   vector signed short Y, vector signed short U, vector signed short V,

			   vector signed short *R, vector signed short *G, vector signed short *B)

{

  vector signed   short vx,ux,uvx;

  Y = vec_mradds (Y, c->CY, c->OY);

  U = vec_sub (U,(vector signed short)(128));

  V = vec_sub (V,(vector signed short)(128));

  //   ux  = (CBU*(u<<c->CSHIFT)+0x4000)>>15;

  ux = vec_sl (U, c->CSHIFT);

  *B = vec_mradds (ux, c->CBU, Y);

  // vx  = (CRV*(v<<c->CSHIFT)+0x4000)>>15;

  vx = vec_sl (V, c->CSHIFT);

  *R = vec_mradds (vx, c->CRV, Y);

  // uvx = ((CGU*u) + (CGV*v))>>15;

  uvx = vec_mradds (U, c->CGU, Y);

  *G = vec_mradds (V, c->CGV, uvx);

}


static void vaapi_encode_h264_write_sei(PutBitContext *pbc,

                                        VAAPIEncodeContext *ctx,

                                        VAAPIEncodePicture *pic)

{

    VAAPIEncodeH264Context *priv = ctx->priv_data;

    PutBitContext payload_bits;

    char payload[256];

    int payload_type, payload_size, i;

    void (*write_payload)(PutBitContext *pbc,

                          VAAPIEncodeContext *ctx,

                          VAAPIEncodePicture *pic) = NULL;

    vaapi_encode_h264_write_nal_header(pbc, NAL_SEI, 0);

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

        switch (payload_type) {

        case SEI_TYPE_BUFFERING_PERIOD:

            if (!priv->send_timing_sei ||

                pic->type != PICTURE_TYPE_IDR)

                continue;

            write_payload = &vaapi_encode_h264_write_buffering_period;

            break;

        case SEI_TYPE_PIC_TIMING:

            if (!priv->send_timing_sei)

                continue;

            write_payload = &vaapi_encode_h264_write_pic_timing;

            break;

        case SEI_TYPE_USER_DATA_UNREGISTERED:

            if (pic->encode_order != 0)

                continue;

            write_payload = &vaapi_encode_h264_write_identifier;

            break;

        default:

            continue;

        }

        init_put_bits(&payload_bits, payload, sizeof(payload));

        write_payload(&payload_bits, ctx, pic);

        if (put_bits_count(&payload_bits) & 7) {

            write_u(&payload_bits, 1, 1, bit_equal_to_one);

            while (put_bits_count(&payload_bits) & 7)

                write_u(&payload_bits, 1, 0, bit_equal_to_zero);

        }

        payload_size = put_bits_count(&payload_bits) / 8;

        flush_put_bits(&payload_bits);

        u(8, payload_type, last_payload_type_byte);

        u(8, payload_size, last_payload_size_byte);

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

            u(8, payload[i] & 0xff, sei_payload);

    }

    vaapi_encode_h264_write_trailing_rbsp(pbc);

}


Visitor *visitor_input_test_init(TestInputVisitorData *data,

                                 const char *json_string, ...)

{

    Visitor *v;

    va_list ap;

    va_start(ap, json_string);

    data->obj = qobject_from_jsonv(json_string, &ap);

    va_end(ap);

    g_assert(data->obj != NULL);

    data->qiv = qmp_input_visitor_new(data->obj);

    g_assert(data->qiv != NULL);

    v = qmp_input_get_visitor(data->qiv);

    g_assert(v != NULL);

    return v;

}


static void dump_syscall(CPUState *env)

{

    fprintf(logfile, "syscall r0=0x%08x r3=0x%08x r4=0x%08x "

            "r5=0x%08x r6=0x%08x nip=0x%08x\n",

            env->gpr[0], env->gpr[3], env->gpr[4],

            env->gpr[5], env->gpr[6], env->nip);

}


static int vnc_auth_sasl_check_ssf(VncState *vs)

{

    const void *val;

    int err, ssf;

    if (!vs->sasl.wantSSF)

        return 1;

    err = sasl_getprop(vs->sasl.conn, SASL_SSF, &val);

    if (err != SASL_OK)

        return 0;

    ssf = *(const int *)val;

    VNC_DEBUG("negotiated an SSF of %d\n", ssf);

    if (ssf < 56)

        return 0; /* 56 is good for Kerberos */

    /* Only setup for read initially, because we're about to send an RPC

     * reply which must be in plain text. When the next incoming RPC

     * arrives, we'll switch on writes too

     *

     * cf qemudClientReadSASL  in qemud.c

     */

    vs->sasl.runSSF = 1;

    /* We have a SSF that's good enough */

    return 1;

}


static int parse_metadata(DBEContext *s)

{

    int i, ret, key = parse_key(s), mtd_size;

    if ((ret = convert_input(s, 1, key)) < 0)

        return ret;

    skip_bits(&s->gb, 4);

    mtd_size = get_bits(&s->gb, 10);

    if (!mtd_size) {

        av_log(s->avctx, AV_LOG_ERROR, "Invalid metadata size\n");

        return AVERROR_INVALIDDATA;

    }

    if ((ret = convert_input(s, mtd_size, key)) < 0)

        return ret;

    skip_bits(&s->gb, 14);

    s->prog_conf = get_bits(&s->gb, 6);

    if (s->prog_conf > MAX_PROG_CONF) {

        av_log(s->avctx, AV_LOG_ERROR, "Invalid program configuration\n");

        return AVERROR_INVALIDDATA;

    }

    s->nb_channels = nb_channels_tab[s->prog_conf];

    s->nb_programs = nb_programs_tab[s->prog_conf];

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

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

    if (!sample_rate_tab[s->fr_code] ||

        !sample_rate_tab[s->fr_code_orig]) {

        av_log(s->avctx, AV_LOG_ERROR, "Invalid frame rate code\n");

        return AVERROR_INVALIDDATA;

    }

    skip_bits_long(&s->gb, 88);

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

        s->ch_size[i] = get_bits(&s->gb, 10);

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

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

    skip_bits_long(&s->gb, 10 * s->nb_programs);

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

        s->rev_id[i]     = get_bits(&s->gb,  4);

        skip_bits1(&s->gb);

        s->begin_gain[i] = get_bits(&s->gb, 10);

        s->end_gain[i]   = get_bits(&s->gb, 10);

    }

    if (get_bits_left(&s->gb) < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "Read past end of metadata\n");

        return AVERROR_INVALIDDATA;

    }

    skip_input(s, mtd_size + 1);

    return 0;

}


static void vp8_release_frame(VP8Context *s, AVFrame *f, int is_close)

{

    if (!is_close) {

        if (f->ref_index[0]) {

            assert(s->num_maps_to_be_freed < FF_ARRAY_ELEMS(s->segmentation_maps));

            s->segmentation_maps[s->num_maps_to_be_freed++] = f->ref_index[0];

            f->ref_index[0] = NULL;

        }

    } else {

        av_freep(&f->ref_index[0]);

    }

    ff_thread_release_buffer(s->avctx, f);

}


int qemu_socket(int domain, int type, int protocol)

{

    int ret;

#ifdef SOCK_CLOEXEC

    ret = socket(domain, type | SOCK_CLOEXEC, protocol);

#else

    ret = socket(domain, type, protocol);

    if (ret >= 0) {

        qemu_set_cloexec(ret);

    }

#endif

    return ret;

}


static int smacker_probe(AVProbeData *p)

{

    if(p->buf[0] == 'S' && p->buf[1] == 'M' && p->buf[2] == 'K'

        && (p->buf[3] == '2' || p->buf[3] == '4'))

        return AVPROBE_SCORE_MAX;

    else

        return 0;

}


static av_noinline void FUNC(hl_decode_mb)(H264Context *h, H264SliceContext *sl)

{

    const int mb_x    = h->mb_x;

    const int mb_y    = h->mb_y;

    const int mb_xy   = h->mb_xy;

    const int mb_type = h->cur_pic.mb_type[mb_xy];

    uint8_t *dest_y, *dest_cb, *dest_cr;

    int linesize, uvlinesize /*dct_offset*/;

    int i, j;

    int *block_offset = &h->block_offset[0];

    const int transform_bypass = !SIMPLE && (sl->qscale == 0 && h->sps.transform_bypass);

    /* is_h264 should always be true if SVQ3 is disabled. */

    const int is_h264 = !CONFIG_SVQ3_DECODER || SIMPLE || h->avctx->codec_id == AV_CODEC_ID_H264;

    void (*idct_add)(uint8_t *dst, int16_t *block, int stride);

    const int block_h   = 16 >> h->chroma_y_shift;

    const int chroma422 = CHROMA422(h);

    dest_y  = h->cur_pic.f.data[0] + ((mb_x << PIXEL_SHIFT)     + mb_y * h->linesize)  * 16;

    dest_cb = h->cur_pic.f.data[1] +  (mb_x << PIXEL_SHIFT) * 8 + mb_y * h->uvlinesize * block_h;

    dest_cr = h->cur_pic.f.data[2] +  (mb_x << PIXEL_SHIFT) * 8 + mb_y * h->uvlinesize * block_h;

    h->vdsp.prefetch(dest_y  + (h->mb_x & 3) * 4 * h->linesize   + (64 << PIXEL_SHIFT), h->linesize,       4);

    h->vdsp.prefetch(dest_cb + (h->mb_x & 7)     * h->uvlinesize + (64 << PIXEL_SHIFT), dest_cr - dest_cb, 2);

    h->list_counts[mb_xy] = sl->list_count;

    if (!SIMPLE && MB_FIELD(h)) {

        linesize     = sl->mb_linesize = h->linesize * 2;

        uvlinesize   = sl->mb_uvlinesize = h->uvlinesize * 2;

        block_offset = &h->block_offset[48];

        if (mb_y & 1) { // FIXME move out of this function?

            dest_y  -= h->linesize * 15;

            dest_cb -= h->uvlinesize * (block_h - 1);

            dest_cr -= h->uvlinesize * (block_h - 1);

        }

        if (FRAME_MBAFF(h)) {

            int list;

            for (list = 0; list < sl->list_count; list++) {

                if (!USES_LIST(mb_type, list))

                    continue;

                if (IS_16X16(mb_type)) {

                    int8_t *ref = &sl->ref_cache[list][scan8[0]];

                    fill_rectangle(ref, 4, 4, 8, (16 + *ref) ^ (h->mb_y & 1), 1);

                } else {

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

                        int ref = sl->ref_cache[list][scan8[i]];

                        if (ref >= 0)

                            fill_rectangle(&sl->ref_cache[list][scan8[i]], 2, 2,

                                           8, (16 + ref) ^ (h->mb_y & 1), 1);

                    }

                }

            }

        }

    } else {

        linesize   = sl->mb_linesize   = h->linesize;

        uvlinesize = sl->mb_uvlinesize = h->uvlinesize;

        // dct_offset = s->linesize * 16;

    }

    if (!SIMPLE && IS_INTRA_PCM(mb_type)) {

        if (PIXEL_SHIFT) {

            const int bit_depth = h->sps.bit_depth_luma;

            int j;

            GetBitContext gb;

            init_get_bits(&gb, sl->intra_pcm_ptr,

                          ff_h264_mb_sizes[h->sps.chroma_format_idc] * bit_depth);

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

                uint16_t *tmp_y = (uint16_t *)(dest_y + i * linesize);

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

                    tmp_y[j] = get_bits(&gb, bit_depth);

            }

            if (SIMPLE || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {

                if (!h->sps.chroma_format_idc) {

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

                        uint16_t *tmp_cb = (uint16_t *)(dest_cb + i * uvlinesize);

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

                            tmp_cb[j] = 1 << (bit_depth - 1);

                    }

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

                        uint16_t *tmp_cr = (uint16_t *)(dest_cr + i * uvlinesize);

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

                            tmp_cr[j] = 1 << (bit_depth - 1);

                    }

                } else {

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

                        uint16_t *tmp_cb = (uint16_t *)(dest_cb + i * uvlinesize);

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

                            tmp_cb[j] = get_bits(&gb, bit_depth);

                    }

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

                        uint16_t *tmp_cr = (uint16_t *)(dest_cr + i * uvlinesize);

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

                            tmp_cr[j] = get_bits(&gb, bit_depth);

                    }

                }

            }

        } else {

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

                memcpy(dest_y + i * linesize, sl->intra_pcm_ptr + i * 16, 16);

            if (SIMPLE || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {

                if (!h->sps.chroma_format_idc) {

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

                        memset(dest_cb + i * uvlinesize, 128, 8);

                        memset(dest_cr + i * uvlinesize, 128, 8);

                    }

                } else {

                    const uint8_t *src_cb = sl->intra_pcm_ptr + 256;

                    const uint8_t *src_cr = sl->intra_pcm_ptr + 256 + block_h * 8;

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

                        memcpy(dest_cb + i * uvlinesize, src_cb + i * 8, 8);

                        memcpy(dest_cr + i * uvlinesize, src_cr + i * 8, 8);

                    }

                }

            }

        }

    } else {

        if (IS_INTRA(mb_type)) {

            if (h->deblocking_filter)

                xchg_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,

                               uvlinesize, 1, 0, SIMPLE, PIXEL_SHIFT);

            if (SIMPLE || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {

                h->hpc.pred8x8[sl->chroma_pred_mode](dest_cb, uvlinesize);

                h->hpc.pred8x8[sl->chroma_pred_mode](dest_cr, uvlinesize);

            }

            hl_decode_mb_predict_luma(h, sl, mb_type, is_h264, SIMPLE,

                                      transform_bypass, PIXEL_SHIFT,

                                      block_offset, linesize, dest_y, 0);

            if (h->deblocking_filter)

                xchg_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,

                               uvlinesize, 0, 0, SIMPLE, PIXEL_SHIFT);

        } else if (is_h264) {

            if (chroma422) {

                FUNC(hl_motion_422)(h, sl, dest_y, dest_cb, dest_cr,

                              h->qpel_put, h->h264chroma.put_h264_chroma_pixels_tab,

                              h->qpel_avg, h->h264chroma.avg_h264_chroma_pixels_tab,

                              h->h264dsp.weight_h264_pixels_tab,

                              h->h264dsp.biweight_h264_pixels_tab);

            } else {

                FUNC(hl_motion_420)(h, sl, dest_y, dest_cb, dest_cr,

                              h->qpel_put, h->h264chroma.put_h264_chroma_pixels_tab,

                              h->qpel_avg, h->h264chroma.avg_h264_chroma_pixels_tab,

                              h->h264dsp.weight_h264_pixels_tab,

                              h->h264dsp.biweight_h264_pixels_tab);

            }

        }

        hl_decode_mb_idct_luma(h, sl, mb_type, is_h264, SIMPLE, transform_bypass,

                               PIXEL_SHIFT, block_offset, linesize, dest_y, 0);

        if ((SIMPLE || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) &&

            (sl->cbp & 0x30)) {

            uint8_t *dest[2] = { dest_cb, dest_cr };

            if (transform_bypass) {

                if (IS_INTRA(mb_type) && h->sps.profile_idc == 244 &&

                    (sl->chroma_pred_mode == VERT_PRED8x8 ||

                     sl->chroma_pred_mode == HOR_PRED8x8)) {

                    h->hpc.pred8x8_add[sl->chroma_pred_mode](dest[0],

                                                            block_offset + 16,

                                                            sl->mb + (16 * 16 * 1 << PIXEL_SHIFT),

                                                            uvlinesize);

                    h->hpc.pred8x8_add[sl->chroma_pred_mode](dest[1],

                                                            block_offset + 32,

                                                            sl->mb + (16 * 16 * 2 << PIXEL_SHIFT),

                                                            uvlinesize);

                } else {

                    idct_add = h->h264dsp.h264_add_pixels4_clear;

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

                        for (i = j * 16; i < j * 16 + 4; i++)

                            if (sl->non_zero_count_cache[scan8[i]] ||

                                dctcoef_get(sl->mb, PIXEL_SHIFT, i * 16))

                                idct_add(dest[j - 1] + block_offset[i],

                                         sl->mb + (i * 16 << PIXEL_SHIFT),

                                         uvlinesize);

                        if (chroma422) {

                            for (i = j * 16 + 4; i < j * 16 + 8; i++)

                                if (sl->non_zero_count_cache[scan8[i + 4]] ||

                                    dctcoef_get(sl->mb, PIXEL_SHIFT, i * 16))

                                    idct_add(dest[j - 1] + block_offset[i + 4],

                                             sl->mb + (i * 16 << PIXEL_SHIFT),

                                             uvlinesize);

                        }

                    }

                }

            } else {

                if (is_h264) {

                    int qp[2];

                    if (chroma422) {

                        qp[0] = sl->chroma_qp[0] + 3;

                        qp[1] = sl->chroma_qp[1] + 3;

                    } else {

                        qp[0] = sl->chroma_qp[0];

                        qp[1] = sl->chroma_qp[1];

                    }

                    if (sl->non_zero_count_cache[scan8[CHROMA_DC_BLOCK_INDEX + 0]])

                        h->h264dsp.h264_chroma_dc_dequant_idct(sl->mb + (16 * 16 * 1 << PIXEL_SHIFT),

                                                               h->dequant4_coeff[IS_INTRA(mb_type) ? 1 : 4][qp[0]][0]);

                    if (sl->non_zero_count_cache[scan8[CHROMA_DC_BLOCK_INDEX + 1]])

                        h->h264dsp.h264_chroma_dc_dequant_idct(sl->mb + (16 * 16 * 2 << PIXEL_SHIFT),

                                                               h->dequant4_coeff[IS_INTRA(mb_type) ? 2 : 5][qp[1]][0]);

                    h->h264dsp.h264_idct_add8(dest, block_offset,

                                              sl->mb, uvlinesize,

                                              sl->non_zero_count_cache);

                } else if (CONFIG_SVQ3_DECODER) {

                    h->h264dsp.h264_chroma_dc_dequant_idct(sl->mb + 16 * 16 * 1,

                                                           h->dequant4_coeff[IS_INTRA(mb_type) ? 1 : 4][sl->chroma_qp[0]][0]);

                    h->h264dsp.h264_chroma_dc_dequant_idct(sl->mb + 16 * 16 * 2,

                                                           h->dequant4_coeff[IS_INTRA(mb_type) ? 2 : 5][sl->chroma_qp[1]][0]);

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

                        for (i = j * 16; i < j * 16 + 4; i++)

                            if (sl->non_zero_count_cache[scan8[i]] || sl->mb[i * 16]) {

                                uint8_t *const ptr = dest[j - 1] + block_offset[i];

                                ff_svq3_add_idct_c(ptr, sl->mb + i * 16,

                                                   uvlinesize,

                                                   ff_h264_chroma_qp[0][sl->qscale + 12] - 12, 2);

                            }

                    }

                }

            }

        }

    }

}


static int hds_write_header(AVFormatContext *s)

{

    HDSContext *c = s->priv_data;

    int ret = 0, i;

    AVOutputFormat *oformat;

    mkdir(s->filename, 0777);

    oformat = av_guess_format("flv", NULL, NULL);

    if (!oformat) {

        ret = AVERROR_MUXER_NOT_FOUND;

        goto fail;

    }

    c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);

    if (!c->streams) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

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

        OutputStream *os = &c->streams[c->nb_streams];

        AVFormatContext *ctx;

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

        if (!st->codec->bit_rate) {

            av_log(s, AV_LOG_ERROR, "No bit rate set for stream %d\n", i);

            ret = AVERROR(EINVAL);

            goto fail;

        }

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

            if (os->has_video) {

                c->nb_streams++;

                os++;

            }

            os->has_video = 1;

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

            if (os->has_audio) {

                c->nb_streams++;

                os++;

            }

            os->has_audio = 1;

        } else {

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

            ret = AVERROR(EINVAL);

            goto fail;

        }

        os->bitrate += s->streams[i]->codec->bit_rate;

        if (!os->ctx) {

            os->first_stream = i;

            ctx = avformat_alloc_context();

            if (!ctx) {

                ret = AVERROR(ENOMEM);

                goto fail;

            }

            os->ctx = ctx;

            ctx->oformat = oformat;

            ctx->interrupt_callback = s->interrupt_callback;

            ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf),

                                         AVIO_FLAG_WRITE, os,

                                         NULL, hds_write, NULL);

            if (!ctx->pb) {

                ret = AVERROR(ENOMEM);

                goto fail;

            }

        } else {

            ctx = os->ctx;

        }

        s->streams[i]->id = c->nb_streams;

        if (!(st = avformat_new_stream(ctx, NULL))) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        avcodec_copy_context(st->codec, s->streams[i]->codec);

        st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;

    }

    if (c->streams[c->nb_streams].ctx)

        c->nb_streams++;

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

        OutputStream *os = &c->streams[i];

        int j;

        if ((ret = avformat_write_header(os->ctx, NULL)) < 0) {

             goto fail;

        }

        os->ctx_inited = 1;

        avio_flush(os->ctx->pb);

        for (j = 0; j < os->ctx->nb_streams; j++)

            s->streams[os->first_stream + j]->time_base = os->ctx->streams[j]->time_base;

        snprintf(os->temp_filename, sizeof(os->temp_filename),

                 "%s/stream%d_temp", s->filename, i);

        ret = init_file(s, os, 0);

        if (ret < 0)

            goto fail;

        if (!os->has_video && c->min_frag_duration <= 0) {

            av_log(s, AV_LOG_WARNING,

                   "No video stream in output stream %d and no min frag duration set\n", i);

            ret = AVERROR(EINVAL);

        }

        os->fragment_index = 1;

        write_abst(s, os, 0);

    }

    ret = write_manifest(s, 0);

fail:

    if (ret)

        hds_free(s);

    return ret;

}


static int disas_coproc_insn(DisasContext *s, uint32_t insn)

{

    int cpnum, is64, crn, crm, opc1, opc2, isread, rt, rt2;

    const ARMCPRegInfo *ri;

    cpnum = (insn >> 8) & 0xf;

    /* First check for coprocessor space used for XScale/iwMMXt insns */

    if (arm_dc_feature(s, ARM_FEATURE_XSCALE) && (cpnum < 2)) {

        if (extract32(s->c15_cpar, cpnum, 1) == 0) {

            return 1;

        }

        if (arm_dc_feature(s, ARM_FEATURE_IWMMXT)) {

            return disas_iwmmxt_insn(s, insn);

        } else if (arm_dc_feature(s, ARM_FEATURE_XSCALE)) {

            return disas_dsp_insn(s, insn);

        }

        return 1;

    }

    /* Otherwise treat as a generic register access */

    is64 = (insn & (1 << 25)) == 0;

    if (!is64 && ((insn & (1 << 4)) == 0)) {

        /* cdp */

        return 1;

    }

    crm = insn & 0xf;

    if (is64) {

        crn = 0;

        opc1 = (insn >> 4) & 0xf;

        opc2 = 0;

        rt2 = (insn >> 16) & 0xf;

    } else {

        crn = (insn >> 16) & 0xf;

        opc1 = (insn >> 21) & 7;

        opc2 = (insn >> 5) & 7;

        rt2 = 0;

    }

    isread = (insn >> 20) & 1;

    rt = (insn >> 12) & 0xf;

    ri = get_arm_cp_reginfo(s->cp_regs,

            ENCODE_CP_REG(cpnum, is64, s->ns, crn, crm, opc1, opc2));

    if (ri) {

        /* Check access permissions */

        if (!cp_access_ok(s->current_el, ri, isread)) {

            return 1;

        }

        if (ri->accessfn ||

            (arm_dc_feature(s, ARM_FEATURE_XSCALE) && cpnum < 14)) {

            /* Emit code to perform further access permissions checks at

             * runtime; this may result in an exception.

             * Note that on XScale all cp0..c13 registers do an access check

             * call in order to handle c15_cpar.

             */

            TCGv_ptr tmpptr;

            TCGv_i32 tcg_syn;

            uint32_t syndrome;

            /* Note that since we are an implementation which takes an

             * exception on a trapped conditional instruction only if the

             * instruction passes its condition code check, we can take

             * advantage of the clause in the ARM ARM that allows us to set

             * the COND field in the instruction to 0xE in all cases.

             * We could fish the actual condition out of the insn (ARM)

             * or the condexec bits (Thumb) but it isn't necessary.

             */

            switch (cpnum) {

            case 14:

                if (is64) {

                    syndrome = syn_cp14_rrt_trap(1, 0xe, opc1, crm, rt, rt2,

                                                 isread, s->thumb);

                } else {

                    syndrome = syn_cp14_rt_trap(1, 0xe, opc1, opc2, crn, crm,

                                                rt, isread, s->thumb);

                }

                break;

            case 15:

                if (is64) {

                    syndrome = syn_cp15_rrt_trap(1, 0xe, opc1, crm, rt, rt2,

                                                 isread, s->thumb);

                } else {

                    syndrome = syn_cp15_rt_trap(1, 0xe, opc1, opc2, crn, crm,

                                                rt, isread, s->thumb);

                }

                break;

            default:

                /* ARMv8 defines that only coprocessors 14 and 15 exist,

                 * so this can only happen if this is an ARMv7 or earlier CPU,

                 * in which case the syndrome information won't actually be

                 * guest visible.

                 */

                assert(!arm_dc_feature(s, ARM_FEATURE_V8));

                syndrome = syn_uncategorized();

                break;

            }

            gen_set_pc_im(s, s->pc);

            tmpptr = tcg_const_ptr(ri);

            tcg_syn = tcg_const_i32(syndrome);

            gen_helper_access_check_cp_reg(cpu_env, tmpptr, tcg_syn);

            tcg_temp_free_ptr(tmpptr);

            tcg_temp_free_i32(tcg_syn);

        }

        /* Handle special cases first */

        switch (ri->type & ~(ARM_CP_FLAG_MASK & ~ARM_CP_SPECIAL)) {

        case ARM_CP_NOP:

            return 0;

        case ARM_CP_WFI:

            if (isread) {

                return 1;

            }

            gen_set_pc_im(s, s->pc);

            s->is_jmp = DISAS_WFI;

            return 0;

        default:

            break;

        }

        if ((s->tb->cflags & CF_USE_ICOUNT) && (ri->type & ARM_CP_IO)) {

            gen_io_start();

        }

        if (isread) {

            /* Read */

            if (is64) {

                TCGv_i64 tmp64;

                TCGv_i32 tmp;

                if (ri->type & ARM_CP_CONST) {

                    tmp64 = tcg_const_i64(ri->resetvalue);

                } else if (ri->readfn) {

                    TCGv_ptr tmpptr;

                    tmp64 = tcg_temp_new_i64();

                    tmpptr = tcg_const_ptr(ri);

                    gen_helper_get_cp_reg64(tmp64, cpu_env, tmpptr);

                    tcg_temp_free_ptr(tmpptr);

                } else {

                    tmp64 = tcg_temp_new_i64();

                    tcg_gen_ld_i64(tmp64, cpu_env, ri->fieldoffset);

                }

                tmp = tcg_temp_new_i32();

                tcg_gen_trunc_i64_i32(tmp, tmp64);

                store_reg(s, rt, tmp);

                tcg_gen_shri_i64(tmp64, tmp64, 32);

                tmp = tcg_temp_new_i32();

                tcg_gen_trunc_i64_i32(tmp, tmp64);

                tcg_temp_free_i64(tmp64);

                store_reg(s, rt2, tmp);

            } else {

                TCGv_i32 tmp;

                if (ri->type & ARM_CP_CONST) {

                    tmp = tcg_const_i32(ri->resetvalue);

                } else if (ri->readfn) {

                    TCGv_ptr tmpptr;

                    tmp = tcg_temp_new_i32();

                    tmpptr = tcg_const_ptr(ri);

                    gen_helper_get_cp_reg(tmp, cpu_env, tmpptr);

                    tcg_temp_free_ptr(tmpptr);

                } else {

                    tmp = load_cpu_offset(ri->fieldoffset);

                }

                if (rt == 15) {

                    /* Destination register of r15 for 32 bit loads sets

                     * the condition codes from the high 4 bits of the value

                     */

                    gen_set_nzcv(tmp);

                    tcg_temp_free_i32(tmp);

                } else {

                    store_reg(s, rt, tmp);

                }

            }

        } else {

            /* Write */

            if (ri->type & ARM_CP_CONST) {

                /* If not forbidden by access permissions, treat as WI */

                return 0;

            }

            if (is64) {

                TCGv_i32 tmplo, tmphi;

                TCGv_i64 tmp64 = tcg_temp_new_i64();

                tmplo = load_reg(s, rt);

                tmphi = load_reg(s, rt2);

                tcg_gen_concat_i32_i64(tmp64, tmplo, tmphi);

                tcg_temp_free_i32(tmplo);

                tcg_temp_free_i32(tmphi);

                if (ri->writefn) {

                    TCGv_ptr tmpptr = tcg_const_ptr(ri);

                    gen_helper_set_cp_reg64(cpu_env, tmpptr, tmp64);

                    tcg_temp_free_ptr(tmpptr);

                } else {

                    tcg_gen_st_i64(tmp64, cpu_env, ri->fieldoffset);

                }

                tcg_temp_free_i64(tmp64);

            } else {

                if (ri->writefn) {

                    TCGv_i32 tmp;

                    TCGv_ptr tmpptr;

                    tmp = load_reg(s, rt);

                    tmpptr = tcg_const_ptr(ri);

                    gen_helper_set_cp_reg(cpu_env, tmpptr, tmp);

                    tcg_temp_free_ptr(tmpptr);

                    tcg_temp_free_i32(tmp);

                } else {

                    TCGv_i32 tmp = load_reg(s, rt);

                    store_cpu_offset(tmp, ri->fieldoffset);

                }

            }

        }

        if ((s->tb->cflags & CF_USE_ICOUNT) && (ri->type & ARM_CP_IO)) {

            /* I/O operations must end the TB here (whether read or write) */

            gen_io_end();

            gen_lookup_tb(s);

        } else if (!isread && !(ri->type & ARM_CP_SUPPRESS_TB_END)) {

            /* We default to ending the TB on a coprocessor register write,

             * but allow this to be suppressed by the register definition

             * (usually only necessary to work around guest bugs).

             */

            gen_lookup_tb(s);

        }

        return 0;

    }

    /* Unknown register; this might be a guest error or a QEMU

     * unimplemented feature.

     */

    if (is64) {

        qemu_log_mask(LOG_UNIMP, "%s access to unsupported AArch32 "

                      "64 bit system register cp:%d opc1: %d crm:%d "

                      "(%s)\n",

                      isread ? "read" : "write", cpnum, opc1, crm,

                      s->ns ? "non-secure" : "secure");

    } else {

        qemu_log_mask(LOG_UNIMP, "%s access to unsupported AArch32 "

                      "system register cp:%d opc1:%d crn:%d crm:%d opc2:%d "

                      "(%s)\n",

                      isread ? "read" : "write", cpnum, opc1, crn, crm, opc2,

                      s->ns ? "non-secure" : "secure");

    }

    return 1;

}


static inline int round_sample(int64_t *sum)

{

    int sum1;

    sum1 = (int)((*sum) >> OUT_SHIFT);

    *sum &= (1<<OUT_SHIFT)-1;

    return av_clip(sum1, OUT_MIN, OUT_MAX);

}


bool virtio_is_big_endian(void)

{

#if defined(TARGET_WORDS_BIGENDIAN)

    return true;

#else

    return false;

#endif

}


static int check_opt(const CmdArgs *cmd_args, const char *name, QDict *args)

{

    if (!cmd_args->optional) {

        qerror_report(QERR_MISSING_PARAMETER, name);

        return -1;

    }

    if (cmd_args->type == '-') {

        /* handlers expect a value, they need to be changed */

        qdict_put(args, name, qint_from_int(0));

    }

    return 0;

}


static void i440fx_pcihost_get_pci_hole_end(Object *obj, Visitor *v,

                                            const char *name, void *opaque,

                                            Error **errp)

{

    I440FXState *s = I440FX_PCI_HOST_BRIDGE(obj);

    uint32_t value = s->pci_hole.end;

    visit_type_uint32(v, name, &value, errp);

}


bool vring_enable_notification(VirtIODevice *vdev, Vring *vring)

{

    if (vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX)) {

        vring_avail_event(&vring->vr) = vring->vr.avail->idx;

    } else {

        vring_clear_used_flags(vdev, vring, VRING_USED_F_NO_NOTIFY);

    }

    smp_mb(); /* ensure update is seen before reading avail_idx */

    return !vring_more_avail(vdev, vring);

}


void helper_fcmpu (uint64_t arg1, uint64_t arg2, uint32_t crfD)

{

    CPU_DoubleU farg1, farg2;

    uint32_t ret = 0;

    farg1.ll = arg1;

    farg2.ll = arg2;

    if (unlikely(float64_is_nan(farg1.d) ||

                 float64_is_nan(farg2.d))) {

        ret = 0x01UL;

    } else if (float64_lt(farg1.d, farg2.d, &env->fp_status)) {

        ret = 0x08UL;

    } else if (!float64_le(farg1.d, farg2.d, &env->fp_status)) {

        ret = 0x04UL;

    } else {

        ret = 0x02UL;

    }

    env->fpscr &= ~(0x0F << FPSCR_FPRF);

    env->fpscr |= ret << FPSCR_FPRF;

    env->crf[crfD] = ret;

    if (unlikely(ret == 0x01UL

                 && (float64_is_signaling_nan(farg1.d) ||

                     float64_is_signaling_nan(farg2.d)))) {

        /* sNaN comparison */

        fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);

    }

}


static void dec_fpu(DisasContext *dc)

{

    if ((dc->tb_flags & MSR_EE_FLAG)

          && !(dc->env->pvr.regs[2] & PVR2_ILL_OPCODE_EXC_MASK)

          && !((dc->env->pvr.regs[2] & PVR2_USE_FPU_MASK))) {

        tcg_gen_movi_tl(cpu_SR[SR_ESR], ESR_EC_ILLEGAL_OP);

        t_gen_raise_exception(dc, EXCP_HW_EXCP);

        return;

    }

    qemu_log ("unimplemented FPU insn pc=%x opc=%x\n", dc->pc, dc->opcode);

    dc->abort_at_next_insn = 1;

}


static void cdrom_pio_impl(int nblocks)

{

    QPCIDevice *dev;

    QPCIBar bmdma_bar, ide_bar;

    FILE *fh;

    int patt_blocks = MAX(16, nblocks);

    size_t patt_len = ATAPI_BLOCK_SIZE * patt_blocks;

    char *pattern = g_malloc(patt_len);

    size_t rxsize = ATAPI_BLOCK_SIZE * nblocks;

    uint16_t *rx = g_malloc0(rxsize);

    int i, j;

    uint8_t data;

    uint16_t limit;

    /* Prepopulate the CDROM with an interesting pattern */

    generate_pattern(pattern, patt_len, ATAPI_BLOCK_SIZE);

    fh = fopen(tmp_path, "w+");

    fwrite(pattern, ATAPI_BLOCK_SIZE, patt_blocks, fh);

    fclose(fh);

    ide_test_start("-drive if=none,file=%s,media=cdrom,format=raw,id=sr0,index=0 "

                   "-device ide-cd,drive=sr0,bus=ide.0", tmp_path);

    dev = get_pci_device(&bmdma_bar, &ide_bar);

    qtest_irq_intercept_in(global_qtest, "ioapic");

    /* PACKET command on device 0 */

    qpci_io_writeb(dev, ide_bar, reg_device, 0);

    qpci_io_writeb(dev, ide_bar, reg_lba_middle, BYTE_COUNT_LIMIT & 0xFF);

    qpci_io_writeb(dev, ide_bar, reg_lba_high, (BYTE_COUNT_LIMIT >> 8 & 0xFF));

    qpci_io_writeb(dev, ide_bar, reg_command, CMD_PACKET);

    /* HP0: Check_Status_A State */

    nsleep(400);

    data = ide_wait_clear(BSY);

    /* HP1: Send_Packet State */

    assert_bit_set(data, DRQ | DRDY);

    assert_bit_clear(data, ERR | DF | BSY);

    /* SCSI CDB (READ10) -- read n*2048 bytes from block 0 */

    send_scsi_cdb_read10(dev, ide_bar, 0, nblocks);

    /* Read data back: occurs in bursts of 'BYTE_COUNT_LIMIT' bytes.

     * If BYTE_COUNT_LIMIT is odd, we transfer BYTE_COUNT_LIMIT - 1 bytes.

     * We allow an odd limit only when the remaining transfer size is

     * less than BYTE_COUNT_LIMIT. However, SCSI's read10 command can only

     * request n blocks, so our request size is always even.

     * For this reason, we assume there is never a hanging byte to fetch. */

    g_assert(!(rxsize & 1));

    limit = BYTE_COUNT_LIMIT & ~1;

    for (i = 0; i < DIV_ROUND_UP(rxsize, limit); i++) {

        size_t offset = i * (limit / 2);

        size_t rem = (rxsize / 2) - offset;

        /* HP3: INTRQ_Wait */

        ide_wait_intr(IDE_PRIMARY_IRQ);

        /* HP2: Check_Status_B (and clear IRQ) */

        data = ide_wait_clear(BSY);

        assert_bit_set(data, DRQ | DRDY);

        assert_bit_clear(data, ERR | DF | BSY);

        /* HP4: Transfer_Data */

        for (j = 0; j < MIN((limit / 2), rem); j++) {

            rx[offset + j] = cpu_to_le16(qpci_io_readw(dev, ide_bar,

                                                       reg_data));

        }

    }

    /* Check for final completion IRQ */

    ide_wait_intr(IDE_PRIMARY_IRQ);

    /* Sanity check final state */

    data = ide_wait_clear(DRQ);

    assert_bit_set(data, DRDY);

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

    g_assert_cmpint(memcmp(pattern, rx, rxsize), ==, 0);

    g_free(pattern);

    g_free(rx);

    test_bmdma_teardown();

    free_pci_device(dev);

}


static uint32_t m5206_mbar_readw(void *opaque, target_phys_addr_t offset)

{

    m5206_mbar_state *s = (m5206_mbar_state *)opaque;

    int width;

    offset &= 0x3ff;

    if (offset >= 0x200) {

        hw_error("Bad MBAR read offset 0x%x", (int)offset);

    }

    width = m5206_mbar_width[offset >> 2];

    if (width > 2) {

        uint32_t val;

        val = m5206_mbar_readl(opaque, offset & ~3);

        if ((offset & 3) == 0)

            val >>= 16;

        return val & 0xffff;

    } else if (width < 2) {

        uint16_t val;

        val = m5206_mbar_readb(opaque, offset) << 8;

        val |= m5206_mbar_readb(opaque, offset + 1);

        return val;

    }

    return m5206_mbar_read(s, offset, 2);

}


static void test_visitor_out_bool(TestOutputVisitorData *data,

                                  const void *unused)

{

    bool value = true;

    QObject *obj;

    visit_type_bool(data->ov, NULL, &value, &error_abort);

    obj = visitor_get(data);

    g_assert(qobject_type(obj) == QTYPE_QBOOL);

    g_assert(qbool_get_bool(qobject_to_qbool(obj)) == value);

}


static void do_dcbz(target_ulong addr, int dcache_line_size)

{

    addr &= ~(dcache_line_size - 1);

    int i;

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

        stl(addr + i , 0);

    }

    if (env->reserve == addr)

        env->reserve = (target_ulong)-1ULL;

}