uint32_t do_arm_semihosting(CPUState *env)

{

    target_ulong args;

    char * s;

    int nr;

    uint32_t ret;

    uint32_t len;

#ifdef CONFIG_USER_ONLY

    TaskState *ts = env->opaque;

#else

    CPUState *ts = env;

#endif

    nr = env->regs[0];

    args = env->regs[1];

    switch (nr) {

    case SYS_OPEN:

        if (!(s = lock_user_string(ARG(0))))

            /* FIXME - should this error code be -TARGET_EFAULT ? */

            return (uint32_t)-1;

        if (ARG(1) >= 12)

            return (uint32_t)-1;

        if (strcmp(s, ":tt") == 0) {

            if (ARG(1) < 4)

                return STDIN_FILENO;

            else

                return STDOUT_FILENO;

        }

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_cb, "open,%s,%x,1a4", ARG(0),

			   (int)ARG(2)+1, gdb_open_modeflags[ARG(1)]);

            return env->regs[0];

        } else {

            ret = set_swi_errno(ts, open(s, open_modeflags[ARG(1)], 0644));

        }

        unlock_user(s, ARG(0), 0);

        return ret;

    case SYS_CLOSE:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_cb, "close,%x", ARG(0));

            return env->regs[0];

        } else {

            return set_swi_errno(ts, close(ARG(0)));

        }

    case SYS_WRITEC:

        {

          char c;

          if (get_user_u8(c, args))

              /* FIXME - should this error code be -TARGET_EFAULT ? */

              return (uint32_t)-1;

          /* Write to debug console.  stderr is near enough.  */

          if (use_gdb_syscalls()) {

                gdb_do_syscall(arm_semi_cb, "write,2,%x,1", args);

                return env->regs[0];

          } else {

                return write(STDERR_FILENO, &c, 1);

          }

        }

    case SYS_WRITE0:

        if (!(s = lock_user_string(args)))

            /* FIXME - should this error code be -TARGET_EFAULT ? */

            return (uint32_t)-1;

        len = strlen(s);

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_cb, "write,2,%x,%x\n", args, len);

            ret = env->regs[0];

        } else {

            ret = write(STDERR_FILENO, s, len);

        }

        unlock_user(s, args, 0);

        return ret;

    case SYS_WRITE:

        len = ARG(2);

        if (use_gdb_syscalls()) {

            arm_semi_syscall_len = len;

            gdb_do_syscall(arm_semi_cb, "write,%x,%x,%x", ARG(0), ARG(1), len);

            return env->regs[0];

        } else {

            if (!(s = lock_user(VERIFY_READ, ARG(1), len, 1)))

                /* FIXME - should this error code be -TARGET_EFAULT ? */

                return (uint32_t)-1;

            ret = set_swi_errno(ts, write(ARG(0), s, len));

            unlock_user(s, ARG(1), 0);

            if (ret == (uint32_t)-1)

                return -1;

            return len - ret;

        }

    case SYS_READ:

        len = ARG(2);

        if (use_gdb_syscalls()) {

            arm_semi_syscall_len = len;

            gdb_do_syscall(arm_semi_cb, "read,%x,%x,%x", ARG(0), ARG(1), len);

            return env->regs[0];

        } else {

            if (!(s = lock_user(VERIFY_WRITE, ARG(1), len, 0)))

                /* FIXME - should this error code be -TARGET_EFAULT ? */

                return (uint32_t)-1;

            do

              ret = set_swi_errno(ts, read(ARG(0), s, len));

            while (ret == -1 && errno == EINTR);

            unlock_user(s, ARG(1), len);

            if (ret == (uint32_t)-1)

                return -1;

            return len - ret;

        }

    case SYS_READC:

       /* XXX: Read from debug cosole. Not implemented.  */

        return 0;

    case SYS_ISTTY:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_cb, "isatty,%x", ARG(0));

            return env->regs[0];

        } else {

            return isatty(ARG(0));

        }

    case SYS_SEEK:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_cb, "lseek,%x,%x,0", ARG(0), ARG(1));

            return env->regs[0];

        } else {

            ret = set_swi_errno(ts, lseek(ARG(0), ARG(1), SEEK_SET));

            if (ret == (uint32_t)-1)

              return -1;

            return 0;

        }

    case SYS_FLEN:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_flen_cb, "fstat,%x,%x",

			   ARG(0), env->regs[13]-64);

            return env->regs[0];

        } else {

            struct stat buf;

            ret = set_swi_errno(ts, fstat(ARG(0), &buf));

            if (ret == (uint32_t)-1)

                return -1;

            return buf.st_size;

        }

    case SYS_TMPNAM:

        /* XXX: Not implemented.  */

        return -1;

    case SYS_REMOVE:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_cb, "unlink,%s", ARG(0), (int)ARG(1)+1);

            ret = env->regs[0];

        } else {

            if (!(s = lock_user_string(ARG(0))))

                /* FIXME - should this error code be -TARGET_EFAULT ? */

                return (uint32_t)-1;

            ret =  set_swi_errno(ts, remove(s));

            unlock_user(s, ARG(0), 0);

        }

        return ret;

    case SYS_RENAME:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_cb, "rename,%s,%s",

                           ARG(0), (int)ARG(1)+1, ARG(2), (int)ARG(3)+1);

            return env->regs[0];

        } else {

            char *s2;

            s = lock_user_string(ARG(0));

            s2 = lock_user_string(ARG(2));

            if (!s || !s2)

                /* FIXME - should this error code be -TARGET_EFAULT ? */

                ret = (uint32_t)-1;

            else

                ret = set_swi_errno(ts, rename(s, s2));

            if (s2)

                unlock_user(s2, ARG(2), 0);

            if (s)

                unlock_user(s, ARG(0), 0);

            return ret;

        }

    case SYS_CLOCK:

        return clock() / (CLOCKS_PER_SEC / 100);

    case SYS_TIME:

        return set_swi_errno(ts, time(NULL));

    case SYS_SYSTEM:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_cb, "system,%s", ARG(0), (int)ARG(1)+1);

            return env->regs[0];

        } else {

            if (!(s = lock_user_string(ARG(0))))

                /* FIXME - should this error code be -TARGET_EFAULT ? */

                return (uint32_t)-1;

            ret = set_swi_errno(ts, system(s));

            unlock_user(s, ARG(0), 0);

            return ret;

        }

    case SYS_ERRNO:

#ifdef CONFIG_USER_ONLY

        return ts->swi_errno;

#else

        return syscall_err;

#endif

    case SYS_GET_CMDLINE:

#ifdef CONFIG_USER_ONLY

        /* Build a commandline from the original argv.  */

        {

            char *arm_cmdline_buffer;

            const char *host_cmdline_buffer;

            unsigned int i;

            unsigned int arm_cmdline_len = ARG(1);

            unsigned int host_cmdline_len =

                ts->info->arg_end-ts->info->arg_start;

            if (!arm_cmdline_len || host_cmdline_len > arm_cmdline_len) {

                return -1; /* not enough space to store command line */

            }

            if (!host_cmdline_len) {

                /* We special-case the "empty command line" case (argc==0).

                   Just provide the terminating 0. */

                arm_cmdline_buffer = lock_user(VERIFY_WRITE, ARG(0), 1, 0);

                arm_cmdline_buffer[0] = 0;

                unlock_user(arm_cmdline_buffer, ARG(0), 1);

                /* Adjust the commandline length argument. */

                SET_ARG(1, 0);

                return 0;

            }

            /* lock the buffers on the ARM side */

            arm_cmdline_buffer =

                lock_user(VERIFY_WRITE, ARG(0), host_cmdline_len, 0);

            host_cmdline_buffer =

                lock_user(VERIFY_READ, ts->info->arg_start,

                                       host_cmdline_len, 1);

            if (arm_cmdline_buffer && host_cmdline_buffer)

            {

                /* the last argument is zero-terminated;

                   no need for additional termination */

                memcpy(arm_cmdline_buffer, host_cmdline_buffer,

                       host_cmdline_len);

                /* separate arguments by white spaces */

                for (i = 0; i < host_cmdline_len-1; i++) {

                    if (arm_cmdline_buffer[i] == 0) {

                        arm_cmdline_buffer[i] = ' ';

                    }

                }

                /* Adjust the commandline length argument. */

                SET_ARG(1, host_cmdline_len-1);

            }

            /* Unlock the buffers on the ARM side.  */

            unlock_user(arm_cmdline_buffer, ARG(0), host_cmdline_len);

            unlock_user((void*)host_cmdline_buffer, ts->info->arg_start, 0);

            /* Return success if we could return a commandline.  */

            return (arm_cmdline_buffer && host_cmdline_buffer) ? 0 : -1;

        }

#else

        return -1;

#endif

    case SYS_HEAPINFO:

        {

            uint32_t *ptr;

            uint32_t limit;

#ifdef CONFIG_USER_ONLY

            /* Some C libraries assume the heap immediately follows .bss, so

               allocate it using sbrk.  */

            if (!ts->heap_limit) {

                long ret;

                ts->heap_base = do_brk(0);

                limit = ts->heap_base + ARM_ANGEL_HEAP_SIZE;

                /* Try a big heap, and reduce the size if that fails.  */

                for (;;) {

                    ret = do_brk(limit);

                    if (ret != -1)

                        break;

                    limit = (ts->heap_base >> 1) + (limit >> 1);

                }

                ts->heap_limit = limit;

            }

            if (!(ptr = lock_user(VERIFY_WRITE, ARG(0), 16, 0)))

                /* FIXME - should this error code be -TARGET_EFAULT ? */

                return (uint32_t)-1;

            ptr[0] = tswap32(ts->heap_base);

            ptr[1] = tswap32(ts->heap_limit);

            ptr[2] = tswap32(ts->stack_base);

            ptr[3] = tswap32(0); /* Stack limit.  */

            unlock_user(ptr, ARG(0), 16);

#else

            limit = ram_size;

            if (!(ptr = lock_user(VERIFY_WRITE, ARG(0), 16, 0)))

                /* FIXME - should this error code be -TARGET_EFAULT ? */

                return (uint32_t)-1;

            /* TODO: Make this use the limit of the loaded application.  */

            ptr[0] = tswap32(limit / 2);

            ptr[1] = tswap32(limit);

            ptr[2] = tswap32(limit); /* Stack base */

            ptr[3] = tswap32(0); /* Stack limit.  */

            unlock_user(ptr, ARG(0), 16);

#endif

            return 0;

        }

    case SYS_EXIT:

        gdb_exit(env, 0);

        exit(0);

    default:

        fprintf(stderr, "qemu: Unsupported SemiHosting SWI 0x%02x\n", nr);

        cpu_dump_state(env, stderr, fprintf, 0);

        abort();

    }

}


int inet_connect(const char *str, Error **errp)

{

    QemuOpts *opts;

    int sock = -1;

    opts = qemu_opts_create(&dummy_opts, NULL, 0, NULL);

    if (inet_parse(opts, str) == 0) {

        sock = inet_connect_opts(opts, true, NULL, errp);

    } else {

        error_set(errp, QERR_SOCKET_CREATE_FAILED);

    }

    qemu_opts_del(opts);

    return sock;

}


static void do_interrupt_user(CPUX86State *env, int intno, int is_int,

                              int error_code, target_ulong next_eip)

{

    SegmentCache *dt;

    target_ulong ptr;

    int dpl, cpl, shift;

    uint32_t e2;

    dt = &env->idt;

    if (env->hflags & HF_LMA_MASK) {

        shift = 4;

    } else {

        shift = 3;

    }

    ptr = dt->base + (intno << shift);

    e2 = cpu_ldl_kernel(env, ptr + 4);

    dpl = (e2 >> DESC_DPL_SHIFT) & 3;

    cpl = env->hflags & HF_CPL_MASK;

    /* check privilege if software int */

    if (is_int && dpl < cpl) {

        raise_exception_err(env, EXCP0D_GPF, (intno << shift) + 2);

    }

    /* Since we emulate only user space, we cannot do more than

       exiting the emulation with the suitable exception and error

       code. So update EIP for INT 0x80 and EXCP_SYSCALL. */

    if (is_int || intno == EXCP_SYSCALL) {

        env->eip = next_eip;

    }

}


static int64_t load_kernel(void)

{

    int64_t entry, kernel_high;

    long kernel_size, initrd_size, params_size;

    ram_addr_t initrd_offset;

    uint32_t *params_buf;

    int big_endian;

#ifdef TARGET_WORDS_BIGENDIAN

    big_endian = 1;

#else

    big_endian = 0;

#endif

    kernel_size = load_elf(loaderparams.kernel_filename, cpu_mips_kseg0_to_phys,

                           NULL, (uint64_t *)&entry, NULL,

                           (uint64_t *)&kernel_high, big_endian,

                           ELF_MACHINE, 1);

    if (kernel_size >= 0) {

        if ((entry & ~0x7fffffffULL) == 0x80000000)

            entry = (int32_t)entry;

    } else {

        fprintf(stderr, "qemu: could not load kernel '%s'\n",

                loaderparams.kernel_filename);

        exit(1);

    }

    /* load initrd */

    initrd_size = 0;

    initrd_offset = 0;

    if (loaderparams.initrd_filename) {

        initrd_size = get_image_size (loaderparams.initrd_filename);

        if (initrd_size > 0) {

            initrd_offset = (kernel_high + ~INITRD_PAGE_MASK) & INITRD_PAGE_MASK;

            if (initrd_offset + initrd_size > ram_size) {

                fprintf(stderr,

                        "qemu: memory too small for initial ram disk '%s'\n",

                        loaderparams.initrd_filename);

                exit(1);

            }

            initrd_size = load_image_targphys(loaderparams.initrd_filename,

                                              initrd_offset,

                                              ram_size - initrd_offset);

        }

        if (initrd_size == (target_ulong) -1) {

            fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",

                    loaderparams.initrd_filename);

            exit(1);

        }

    }

    /* Store command line.  */

    params_size = 264;

    params_buf = g_malloc(params_size);

    params_buf[0] = tswap32(ram_size);

    params_buf[1] = tswap32(0x12345678);

    if (initrd_size > 0) {

        snprintf((char *)params_buf + 8, 256, "rd_start=0x%" PRIx64 " rd_size=%li %s",

                 cpu_mips_phys_to_kseg0(NULL, initrd_offset),

                 initrd_size, loaderparams.kernel_cmdline);

    } else {

        snprintf((char *)params_buf + 8, 256, "%s", loaderparams.kernel_cmdline);

    }

    rom_add_blob_fixed("params", params_buf, params_size,

                       (16 << 20) - 264);

    return entry;

}


static int cin_read_frame_header(CinDemuxContext *cin, AVIOContext *pb) {

    CinFrameHeader *hdr = &cin->frame_header;

    hdr->video_frame_type = avio_r8(pb);

    hdr->audio_frame_type = avio_r8(pb);

    hdr->pal_colors_count = avio_rl16(pb);

    hdr->video_frame_size = avio_rl32(pb);

    hdr->audio_frame_size = avio_rl32(pb);

    if (pb->eof_reached || pb->error)

        return AVERROR(EIO);

    if (avio_rl32(pb) != 0xAA55AA55)

    return 0;

}


static void test_endianness_combine(gconstpointer data)

{

    const TestCase *test = data;

    char *args;

    args = g_strdup_printf("-display none -M %s%s%s -device pc-testdev",

                           test->machine,

                           test->superio ? " -device " : "",

                           test->superio ?: "");

    qtest_start(args);

    isa_outl(test, 0xe0, 0x87654321);

    g_assert_cmphex(isa_inl(test, 0xe8), ==, 0x87654321);

    g_assert_cmphex(isa_inw(test, 0xea), ==, 0x8765);

    g_assert_cmphex(isa_inw(test, 0xe8), ==, 0x4321);

    isa_outw(test, 0xe2, 0x8866);

    g_assert_cmphex(isa_inl(test, 0xe8), ==, 0x88664321);

    g_assert_cmphex(isa_inw(test, 0xea), ==, 0x8866);

    g_assert_cmphex(isa_inw(test, 0xe8), ==, 0x4321);

    isa_outw(test, 0xe0, 0x4422);

    g_assert_cmphex(isa_inl(test, 0xe8), ==, 0x88664422);

    g_assert_cmphex(isa_inw(test, 0xea), ==, 0x8866);

    g_assert_cmphex(isa_inw(test, 0xe8), ==, 0x4422);

    isa_outb(test, 0xe3, 0x87);

    g_assert_cmphex(isa_inl(test, 0xe8), ==, 0x87664422);

    g_assert_cmphex(isa_inw(test, 0xea), ==, 0x8766);

    isa_outb(test, 0xe2, 0x65);

    g_assert_cmphex(isa_inl(test, 0xe8), ==, 0x87654422);

    g_assert_cmphex(isa_inw(test, 0xea), ==, 0x8765);

    g_assert_cmphex(isa_inw(test, 0xe8), ==, 0x4422);

    isa_outb(test, 0xe1, 0x43);

    g_assert_cmphex(isa_inl(test, 0xe8), ==, 0x87654322);

    g_assert_cmphex(isa_inw(test, 0xea), ==, 0x8765);

    g_assert_cmphex(isa_inw(test, 0xe8), ==, 0x4322);

    isa_outb(test, 0xe0, 0x21);

    g_assert_cmphex(isa_inl(test, 0xe8), ==, 0x87654321);

    g_assert_cmphex(isa_inw(test, 0xea), ==, 0x8765);

    g_assert_cmphex(isa_inw(test, 0xe8), ==, 0x4321);

    qtest_quit(global_qtest);

    g_free(args);

}


int avpicture_deinterlace(AVPicture *dst, const AVPicture *src,

                          enum AVPixelFormat pix_fmt, int width, int height)

{

    int i;

    if (pix_fmt != AV_PIX_FMT_YUV420P &&

        pix_fmt != AV_PIX_FMT_YUVJ420P &&

        pix_fmt != AV_PIX_FMT_YUV422P &&

        pix_fmt != AV_PIX_FMT_YUVJ422P &&

        pix_fmt != AV_PIX_FMT_YUV444P &&

        pix_fmt != AV_PIX_FMT_YUV411P &&

        pix_fmt != AV_PIX_FMT_GRAY8)

        return -1;

    if ((width & 3) != 0 || (height & 3) != 0)

        return -1;

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

        if (i == 1) {

            switch(pix_fmt) {

            case AV_PIX_FMT_YUVJ420P:

            case AV_PIX_FMT_YUV420P:

                width >>= 1;

                height >>= 1;

                break;

            case AV_PIX_FMT_YUV422P:

            case AV_PIX_FMT_YUVJ422P:

                width >>= 1;

                break;

            case AV_PIX_FMT_YUV411P:

                width >>= 2;

                break;

            default:

                break;

            }

            if (pix_fmt == AV_PIX_FMT_GRAY8) {

                break;

            }

        }

        if (src == dst) {

            deinterlace_bottom_field_inplace(dst->data[i], dst->linesize[i],

                                 width, height);

        } else {

            deinterlace_bottom_field(dst->data[i],dst->linesize[i],

                                        src->data[i], src->linesize[i],

                                        width, height);

        }

    }

    emms_c();

    return 0;

}


static void chroma_mc(HEVCContext *s, int16_t *dst1, int16_t *dst2,

                      ptrdiff_t dststride, AVFrame *ref, const Mv *mv,

                      int x_off, int y_off, int block_w, int block_h)

{

    HEVCLocalContext *lc = &s->HEVClc;

    uint8_t *src1        = ref->data[1];

    uint8_t *src2        = ref->data[2];

    ptrdiff_t src1stride = ref->linesize[1];

    ptrdiff_t src2stride = ref->linesize[2];

    int pic_width        = s->ps.sps->width >> 1;

    int pic_height       = s->ps.sps->height >> 1;

    int mx = mv->x & 7;

    int my = mv->y & 7;

    x_off += mv->x >> 3;

    y_off += mv->y >> 3;

    src1  += y_off * src1stride + (x_off << s->ps.sps->pixel_shift);

    src2  += y_off * src2stride + (x_off << s->ps.sps->pixel_shift);

    if (x_off < EPEL_EXTRA_BEFORE || y_off < EPEL_EXTRA_AFTER ||

        x_off >= pic_width - block_w - EPEL_EXTRA_AFTER ||

        y_off >= pic_height - block_h - EPEL_EXTRA_AFTER) {

        const int edge_emu_stride = EDGE_EMU_BUFFER_STRIDE << s->ps.sps->pixel_shift;

        int offset1 = EPEL_EXTRA_BEFORE * (src1stride + (1 << s->ps.sps->pixel_shift));

        int buf_offset1 = EPEL_EXTRA_BEFORE *

                          (edge_emu_stride + (1 << s->ps.sps->pixel_shift));

        int offset2 = EPEL_EXTRA_BEFORE * (src2stride + (1 << s->ps.sps->pixel_shift));

        int buf_offset2 = EPEL_EXTRA_BEFORE *

                          (edge_emu_stride + (1 << s->ps.sps->pixel_shift));

        s->vdsp.emulated_edge_mc(lc->edge_emu_buffer, src1 - offset1,

                                 edge_emu_stride, src1stride,

                                 block_w + EPEL_EXTRA, block_h + EPEL_EXTRA,

                                 x_off - EPEL_EXTRA_BEFORE,

                                 y_off - EPEL_EXTRA_BEFORE,

                                 pic_width, pic_height);

        src1 = lc->edge_emu_buffer + buf_offset1;

        src1stride = edge_emu_stride;

        s->hevcdsp.put_hevc_epel[!!my][!!mx](dst1, dststride, src1, src1stride,

                                             block_w, block_h, mx, my, lc->mc_buffer);

        s->vdsp.emulated_edge_mc(lc->edge_emu_buffer, src2 - offset2,

                                 edge_emu_stride, src2stride,

                                 block_w + EPEL_EXTRA, block_h + EPEL_EXTRA,

                                 x_off - EPEL_EXTRA_BEFORE,

                                 y_off - EPEL_EXTRA_BEFORE,

                                 pic_width, pic_height);

        src2 = lc->edge_emu_buffer + buf_offset2;

        src2stride = edge_emu_stride;

        s->hevcdsp.put_hevc_epel[!!my][!!mx](dst2, dststride, src2, src2stride,

                                             block_w, block_h, mx, my,

                                             lc->mc_buffer);

    } else {

        s->hevcdsp.put_hevc_epel[!!my][!!mx](dst1, dststride, src1, src1stride,

                                             block_w, block_h, mx, my,

                                             lc->mc_buffer);

        s->hevcdsp.put_hevc_epel[!!my][!!mx](dst2, dststride, src2, src2stride,

                                             block_w, block_h, mx, my,

                                             lc->mc_buffer);

    }

}


static void mpegts_push_data(void *opaque,

                             const uint8_t *buf, int buf_size, int is_start)

{

    PESContext *pes = opaque;

    MpegTSContext *ts = pes->stream->priv_data;

    AVStream *st;

    const uint8_t *p;

    int len, code, codec_type, codec_id;

    if (is_start) {

        pes->state = MPEGTS_HEADER;

        pes->data_index = 0;

    }

    p = buf;

    while (buf_size > 0) {

        switch(pes->state) {

        case MPEGTS_HEADER:

            len = PES_START_SIZE - pes->data_index;

            if (len > buf_size)

                len = buf_size;

            memcpy(pes->header + pes->data_index, p, len);

            pes->data_index += len;

            p += len;

            buf_size -= len;

            if (pes->data_index == PES_START_SIZE) {

                /* we got all the PES or section header. We can now

                   decide */

#if 0

                av_hex_dump(pes->header, pes->data_index);

#endif

                if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&

                    pes->header[2] == 0x01) {

                    /* it must be an mpeg2 PES stream */

                    /* XXX: add AC3 support */

                    code = pes->header[3] | 0x100;

                    if (!((code >= 0x1c0 && code <= 0x1df) ||

                          (code >= 0x1e0 && code <= 0x1ef)))

                        goto skip;

                    if (!pes->st) {

                        /* allocate stream */

                        if (code >= 0x1c0 && code <= 0x1df) {

                            codec_type = CODEC_TYPE_AUDIO;

                            codec_id = CODEC_ID_MP2;

                        } else {

                            codec_type = CODEC_TYPE_VIDEO;

                            codec_id = CODEC_ID_MPEG1VIDEO;

                        }

                        st = av_new_stream(pes->stream, pes->pid);

                        if (st) {

                            st->priv_data = pes;

                            st->codec.codec_type = codec_type;

                            st->codec.codec_id = codec_id;

                            pes->st = st;

                        }

                    }

                    pes->state = MPEGTS_PESHEADER_FILL;

                    pes->total_size = (pes->header[4] << 8) | pes->header[5];

                    /* NOTE: a zero total size means the PES size is

                       unbounded */

                    if (pes->total_size)

                        pes->total_size += 6;

                    pes->pes_header_size = pes->header[8] + 9;

                } else {

                    /* otherwise, it should be a table */

                    /* skip packet */

                skip:

                    pes->state = MPEGTS_SKIP;

                    continue;

                }

            }

            break;

            /**********************************************/

            /* PES packing parsing */

        case MPEGTS_PESHEADER_FILL:

            len = pes->pes_header_size - pes->data_index;

            if (len > buf_size)

                len = buf_size;

            memcpy(pes->header + pes->data_index, p, len);

            pes->data_index += len;

            p += len;

            buf_size -= len;

            if (pes->data_index == pes->pes_header_size) {

                const uint8_t *r;

                unsigned int flags;

                flags = pes->header[7];

                r = pes->header + 9;

                pes->pts = AV_NOPTS_VALUE;

                pes->dts = AV_NOPTS_VALUE;

                if ((flags & 0xc0) == 0x80) {

                    pes->pts = get_pts(r);

                    r += 5;

                } else if ((flags & 0xc0) == 0xc0) {

                    pes->pts = get_pts(r);

                    r += 5;

                    pes->dts = get_pts(r);

                    r += 5;

                }

                /* we got the full header. We parse it and get the payload */

                pes->state = MPEGTS_PAYLOAD;

            }

            break;

        case MPEGTS_PAYLOAD:

            if (pes->total_size) {

                len = pes->total_size - pes->data_index;

                if (len > buf_size)

                    len = buf_size;

            } else {

                len = buf_size;

            }

            if (len > 0) {

                AVPacket *pkt = ts->pkt;

                if (pes->st && av_new_packet(pkt, len) == 0) {

                    memcpy(pkt->data, p, len);

                    pkt->stream_index = pes->st->index;

                    pkt->pts = pes->pts;

                    /* reset pts values */

                    pes->pts = AV_NOPTS_VALUE;

                    pes->dts = AV_NOPTS_VALUE;

                    ts->stop_parse = 1;

                    return;

                }

            }

            buf_size = 0;

            break;

        case MPEGTS_SKIP:

            buf_size = 0;

            break;

        }

    }

}


static bool gscb_needed(void *opaque)

{

    return kvm_s390_get_gs();

}


void do_fctiw (void)

{

    union {

        double d;

        uint64_t i;

    } p;

    /* XXX: higher bits are not supposed to be significant.

     *     to make tests easier, return the same as a real PowerPC 750 (aka G3)

     */

    p.i = float64_to_int32(FT0, &env->fp_status);

    p.i |= 0xFFF80000ULL << 32;

    FT0 = p.d;

}


static struct omap_mpu_timer_s *omap_mpu_timer_init(MemoryRegion *system_memory,

                hwaddr base,

                qemu_irq irq, omap_clk clk)

{

    struct omap_mpu_timer_s *s = (struct omap_mpu_timer_s *)

            g_malloc0(sizeof(struct omap_mpu_timer_s));

    s->irq = irq;

    s->clk = clk;

    s->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, omap_timer_tick, s);

    s->tick = qemu_bh_new(omap_timer_fire, s);

    omap_mpu_timer_reset(s);

    omap_timer_clk_setup(s);

    memory_region_init_io(&s->iomem, NULL, &omap_mpu_timer_ops, s,

                          "omap-mpu-timer", 0x100);

    memory_region_add_subregion(system_memory, base, &s->iomem);

    return s;

}


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

                                    const AVFrame *frame, int *got_packet)

{

    LibOpenJPEGContext *ctx = avctx->priv_data;

    opj_cinfo_t *compress = ctx->compress;

    opj_image_t *image    = ctx->image;

    opj_cio_t *stream     = ctx->stream;

    int cpyresult = 0;

    int ret, len;

    AVFrame *gbrframe;

    switch (avctx->pix_fmt) {

    case AV_PIX_FMT_RGB24:

    case AV_PIX_FMT_RGBA:

    case AV_PIX_FMT_GRAY8A:

        cpyresult = libopenjpeg_copy_packed8(avctx, frame, image);

        break;

    case AV_PIX_FMT_XYZ12:

        cpyresult = libopenjpeg_copy_packed12(avctx, frame, image);

        break;

    case AV_PIX_FMT_RGB48:

    case AV_PIX_FMT_RGBA64:

        cpyresult = libopenjpeg_copy_packed16(avctx, frame, image);

        break;

    case AV_PIX_FMT_GBR24P:

    case AV_PIX_FMT_GBRP9:

    case AV_PIX_FMT_GBRP10:

    case AV_PIX_FMT_GBRP12:

    case AV_PIX_FMT_GBRP14:

    case AV_PIX_FMT_GBRP16:

        gbrframe = av_frame_alloc();

        av_frame_ref(gbrframe, frame);

        gbrframe->data[0] = frame->data[2]; // swap to be rgb

        gbrframe->data[1] = frame->data[0];

        gbrframe->data[2] = frame->data[1];

        gbrframe->linesize[0] = frame->linesize[2];

        gbrframe->linesize[1] = frame->linesize[0];

        gbrframe->linesize[2] = frame->linesize[1];

        if (avctx->pix_fmt == AV_PIX_FMT_GBR24P) {

            cpyresult = libopenjpeg_copy_unpacked8(avctx, gbrframe, image);

        } else {

            cpyresult = libopenjpeg_copy_unpacked16(avctx, gbrframe, image);

        }

        av_frame_free(&gbrframe);

        break;

    case AV_PIX_FMT_GRAY8:

    case AV_PIX_FMT_YUV410P:

    case AV_PIX_FMT_YUV411P:

    case AV_PIX_FMT_YUV420P:

    case AV_PIX_FMT_YUV422P:

    case AV_PIX_FMT_YUV440P:

    case AV_PIX_FMT_YUV444P:

    case AV_PIX_FMT_YUVA420P:

    case AV_PIX_FMT_YUVA422P:

    case AV_PIX_FMT_YUVA444P:

        cpyresult = libopenjpeg_copy_unpacked8(avctx, frame, image);

        break;

    case AV_PIX_FMT_GRAY16:

    case AV_PIX_FMT_YUV420P9:

    case AV_PIX_FMT_YUV422P9:

    case AV_PIX_FMT_YUV444P9:

    case AV_PIX_FMT_YUVA420P9:

    case AV_PIX_FMT_YUVA422P9:

    case AV_PIX_FMT_YUVA444P9:

    case AV_PIX_FMT_YUV444P10:

    case AV_PIX_FMT_YUV422P10:

    case AV_PIX_FMT_YUV420P10:

    case AV_PIX_FMT_YUVA444P10:

    case AV_PIX_FMT_YUVA422P10:

    case AV_PIX_FMT_YUVA420P10:

    case AV_PIX_FMT_YUV420P12:

    case AV_PIX_FMT_YUV422P12:

    case AV_PIX_FMT_YUV444P12:

    case AV_PIX_FMT_YUV420P14:

    case AV_PIX_FMT_YUV422P14:

    case AV_PIX_FMT_YUV444P14:

    case AV_PIX_FMT_YUV444P16:

    case AV_PIX_FMT_YUV422P16:

    case AV_PIX_FMT_YUV420P16:

    case AV_PIX_FMT_YUVA444P16:

    case AV_PIX_FMT_YUVA422P16:

    case AV_PIX_FMT_YUVA420P16:

        cpyresult = libopenjpeg_copy_unpacked16(avctx, frame, image);

        break;

    default:

        av_log(avctx, AV_LOG_ERROR,

               "The frame's pixel format '%s' is not supported\n",

               av_get_pix_fmt_name(avctx->pix_fmt));

        return AVERROR(EINVAL);

        break;

    }

    if (!cpyresult) {

        av_log(avctx, AV_LOG_ERROR,

               "Could not copy the frame data to the internal image buffer\n");

        return -1;

    }

    cio_seek(stream, 0);

    if (!opj_encode(compress, stream, image, NULL)) {

        av_log(avctx, AV_LOG_ERROR, "Error during the opj encode\n");

        return -1;

    }

    len = cio_tell(stream);

    if ((ret = ff_alloc_packet2(avctx, pkt, len)) < 0) {

        return ret;

    }

    memcpy(pkt->data, stream->buffer, len);

    pkt->flags |= AV_PKT_FLAG_KEY;

    *got_packet = 1;

    return 0;

}


static void termsig_handler(int signum)

{

    state = TERMINATE;

    qemu_notify_event();

}


static int qxl_post_load(void *opaque, int version)

{

    PCIQXLDevice* d = opaque;

    uint8_t *ram_start = d->vga.vram_ptr;

    QXLCommandExt *cmds;

    int in, out, newmode;

    assert(d->last_release_offset < d->vga.vram_size);

    if (d->last_release_offset == 0) {

        d->last_release = NULL;

    } else {

        d->last_release = (QXLReleaseInfo *)(ram_start + d->last_release_offset);

    }

    d->modes = (QXLModes*)((uint8_t*)d->rom + d->rom->modes_offset);

    trace_qxl_post_load(d->id, qxl_mode_to_string(d->mode));

    newmode = d->mode;

    d->mode = QXL_MODE_UNDEFINED;

    switch (newmode) {

    case QXL_MODE_UNDEFINED:

        qxl_create_memslots(d);

        break;

    case QXL_MODE_VGA:

        qxl_create_memslots(d);

        qxl_enter_vga_mode(d);

        break;

    case QXL_MODE_NATIVE:

        qxl_create_memslots(d);

        qxl_create_guest_primary(d, 1, QXL_SYNC);

        /* replay surface-create and cursor-set commands */

        cmds = g_malloc0(sizeof(QXLCommandExt) * (d->ssd.num_surfaces + 1));

        for (in = 0, out = 0; in < d->ssd.num_surfaces; in++) {

            if (d->guest_surfaces.cmds[in] == 0) {

                continue;

            }

            cmds[out].cmd.data = d->guest_surfaces.cmds[in];

            cmds[out].cmd.type = QXL_CMD_SURFACE;

            cmds[out].group_id = MEMSLOT_GROUP_GUEST;

            out++;

        }

        if (d->guest_cursor) {

            cmds[out].cmd.data = d->guest_cursor;

            cmds[out].cmd.type = QXL_CMD_CURSOR;

            cmds[out].group_id = MEMSLOT_GROUP_GUEST;

            out++;

        }

        qxl_spice_loadvm_commands(d, cmds, out);

        g_free(cmds);

        if (d->guest_monitors_config) {

            qxl_spice_monitors_config_async(d, 1);

        }

        break;

    case QXL_MODE_COMPAT:

        /* note: no need to call qxl_create_memslots, qxl_set_mode

         * creates the mem slot. */

        qxl_set_mode(d, d->shadow_rom.mode, 1);

        break;

    }

    return 0;

}


static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt,

                                uint8_t **bufptr, int len)

{

    uint8_t *buf = bufptr ? *bufptr : NULL;

    int flags = 0;

    uint32_t timestamp;

    int rv = 0;

    if (!buf) {

        /* If parsing of the previous packet actually returned 0 or an error,

         * there's nothing more to be parsed from that packet, but we may have

         * indicated that we can return the next enqueued packet. */

        if (s->prev_ret <= 0)

            return rtp_parse_queued_packet(s, pkt);

        /* return the next packets, if any */

        if (s->handler && s->handler->parse_packet) {

            /* timestamp should be overwritten by parse_packet, if not,

             * the packet is left with pts == AV_NOPTS_VALUE */

            timestamp = RTP_NOTS_VALUE;

            rv        = s->handler->parse_packet(s->ic, s->dynamic_protocol_context,

                                                 s->st, pkt, &timestamp, NULL, 0, 0,

                                                 flags);

            finalize_packet(s, pkt, timestamp);

            return rv;

        }

    }

    if (len < 12)

        return -1;

    if ((buf[0] & 0xc0) != (RTP_VERSION << 6))

        return -1;

    if (RTP_PT_IS_RTCP(buf[1])) {

        return rtcp_parse_packet(s, buf, len);

    }

    if (s->st) {

        int64_t received = av_gettime_relative();

        uint32_t arrival_ts = av_rescale_q(received, AV_TIME_BASE_Q,

                                           s->st->time_base);

        timestamp = AV_RB32(buf + 4);

        // Calculate the jitter immediately, before queueing the packet

        // into the reordering queue.

        rtcp_update_jitter(&s->statistics, timestamp, arrival_ts);

    }

    if ((s->seq == 0 && !s->queue) || s->queue_size <= 1) {

        /* First packet, or no reordering */

        return rtp_parse_packet_internal(s, pkt, buf, len);

    } else {

        uint16_t seq = AV_RB16(buf + 2);

        int16_t diff = seq - s->seq;

        if (diff < 0) {

            /* Packet older than the previously emitted one, drop */

            av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,

                   "RTP: dropping old packet received too late\n");

            return -1;

        } else if (diff <= 1) {

            /* Correct packet */

            rv = rtp_parse_packet_internal(s, pkt, buf, len);

            return rv;

        } else {

            /* Still missing some packet, enqueue this one. */

            enqueue_packet(s, buf, len);

            *bufptr = NULL;

            /* Return the first enqueued packet if the queue is full,

             * even if we're missing something */

            if (s->queue_len >= s->queue_size) {

                av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,

                       "jitter buffer full\n");

                return rtp_parse_queued_packet(s, pkt);

            }

            return -1;

        }

    }

}


static inline void RENAME(rgb16to15)(const uint8_t *src,uint8_t *dst,long src_size)

{

  register const uint8_t* s=src;

  register uint8_t* d=dst;

  register const uint8_t *end;

  const uint8_t *mm_end;

  end = s + src_size;

#ifdef HAVE_MMX

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

  __asm __volatile("movq	%0, %%mm7"::"m"(mask15rg));

  __asm __volatile("movq	%0, %%mm6"::"m"(mask15b));

  mm_end = end - 15;

  while(s<mm_end)

  {

	__asm __volatile(

		PREFETCH"	32%1\n\t"

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

		"movq	8%1, %%mm2\n\t"

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

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

		"psrlq	$1, %%mm0\n\t"

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

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

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

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

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

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

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

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

		MOVNTQ"	%%mm2, 8%0"

		:"=m"(*d)

		:"m"(*s)

		);

	d+=16;

	s+=16;

  }

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

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

#endif

    mm_end = end - 3;

    while(s < mm_end)

    {

	register uint32_t x= *((uint32_t *)s);

	*((uint32_t *)d) = ((x>>1)&0x7FE07FE0) | (x&0x001F001F);

	s+=4;

	d+=4;

    }

    if(s < end)

    {

	register uint16_t x= *((uint16_t *)s);

	*((uint16_t *)d) = ((x>>1)&0x7FE0) | (x&0x001F);

	s+=2;

	d+=2;

    }

}


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

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    dc->realize = xics_realize;

    dc->props = xics_properties;

    dc->reset = xics_reset;

}


void acpi_memory_hotplug_init(MemoryRegion *as, Object *owner,

                              MemHotplugState *state)

{

    MachineState *machine = MACHINE(qdev_get_machine());

    state->dev_count = machine->ram_slots;

    if (!state->dev_count) {

        return;

    }

    state->devs = g_malloc0(sizeof(*state->devs) * state->dev_count);

    memory_region_init_io(&state->io, owner, &acpi_memory_hotplug_ops, state,

                          "acpi-mem-hotplug", ACPI_MEMORY_HOTPLUG_IO_LEN);

    memory_region_add_subregion(as, ACPI_MEMORY_HOTPLUG_BASE, &state->io);

}


static void test_qemu_strtoul_correct(void)

{

    const char *str = "12345 foo";

    char f = 'X';

    const char *endptr = &f;

    unsigned long res = 999;

    int err;

    err = qemu_strtoul(str, &endptr, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 12345);

    g_assert(endptr == str + 5);

}


Aml *aml_shiftleft(Aml *arg1, Aml *count)

{

    Aml *var = aml_opcode(0x79 /* ShiftLeftOp */);

    aml_append(var, arg1);

    aml_append(var, count);

    build_append_byte(var->buf, 0x00); /* NullNameOp */

    return var;

}


static void nfs_process_write(void *arg)

{

    NFSClient *client = arg;

    aio_context_acquire(client->aio_context);

    nfs_service(client->context, POLLOUT);

    nfs_set_events(client);

    aio_context_release(client->aio_context);

}


static inline void cpu_loop_exec_tb(CPUState *cpu, TranslationBlock *tb,

                                    TranslationBlock **last_tb, int *tb_exit)

{

    uintptr_t ret;

    int32_t insns_left;

    if (unlikely(atomic_read(&cpu->exit_request))) {

        return;

    }

    trace_exec_tb(tb, tb->pc);

    ret = cpu_tb_exec(cpu, tb);

    tb = (TranslationBlock *)(ret & ~TB_EXIT_MASK);

    *tb_exit = ret & TB_EXIT_MASK;

    if (*tb_exit != TB_EXIT_REQUESTED) {

        *last_tb = tb;

        return;

    }

    *last_tb = NULL;

    insns_left = atomic_read(&cpu->icount_decr.u32);

    atomic_set(&cpu->icount_decr.u16.high, 0);

    if (insns_left < 0) {

        /* Something asked us to stop executing

         * chained TBs; just continue round the main

         * loop. Whatever requested the exit will also

         * have set something else (eg exit_request or

         * interrupt_request) which we will handle

         * next time around the loop.  But we need to

         * ensure the zeroing of tcg_exit_req (see cpu_tb_exec)

         * comes before the next read of cpu->exit_request

         * or cpu->interrupt_request.

         */

        smp_mb();

        return;

    }

    /* Instruction counter expired.  */

    assert(use_icount);

#ifndef CONFIG_USER_ONLY

    if (cpu->icount_extra) {

        /* Refill decrementer and continue execution.  */

        cpu->icount_extra += insns_left;

        insns_left = MIN(0xffff, cpu->icount_extra);

        cpu->icount_extra -= insns_left;

        cpu->icount_decr.u16.low = insns_left;

    } else {

        /* Execute any remaining instructions, then let the main loop

         * handle the next event.

         */

        if (insns_left > 0) {

            cpu_exec_nocache(cpu, insns_left, tb, false);

        }

    }

#endif

}


static int xen_pt_byte_reg_read(XenPCIPassthroughState *s, XenPTReg *cfg_entry,

                                uint8_t *value, uint8_t valid_mask)

{

    XenPTRegInfo *reg = cfg_entry->reg;

    uint8_t valid_emu_mask = 0;

    /* emulate byte register */

    valid_emu_mask = reg->emu_mask & valid_mask;

    *value = XEN_PT_MERGE_VALUE(*value, cfg_entry->data, ~valid_emu_mask);

    return 0;

}


static int vfio_setup_pcie_cap(VFIOPCIDevice *vdev, int pos, uint8_t size)

{

    uint16_t flags;

    uint8_t type;

    flags = pci_get_word(vdev->pdev.config + pos + PCI_CAP_FLAGS);

    type = (flags & PCI_EXP_FLAGS_TYPE) >> 4;

    if (type != PCI_EXP_TYPE_ENDPOINT &&

        type != PCI_EXP_TYPE_LEG_END &&

        type != PCI_EXP_TYPE_RC_END) {

        error_report("vfio: Assignment of PCIe type 0x%x "

                     "devices is not currently supported", type);

        return -EINVAL;

    }

    if (!pci_bus_is_express(vdev->pdev.bus)) {

        /*

         * Use express capability as-is on PCI bus.  It doesn't make much

         * sense to even expose, but some drivers (ex. tg3) depend on it

         * and guests don't seem to be particular about it.  We'll need

         * to revist this or force express devices to express buses if we

         * ever expose an IOMMU to the guest.

         */

    } else if (pci_bus_is_root(vdev->pdev.bus)) {

        /*

         * On a Root Complex bus Endpoints become Root Complex Integrated

         * Endpoints, which changes the type and clears the LNK & LNK2 fields.

         */

        if (type == PCI_EXP_TYPE_ENDPOINT) {

            vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,

                                   PCI_EXP_TYPE_RC_END << 4,

                                   PCI_EXP_FLAGS_TYPE);

            /* Link Capabilities, Status, and Control goes away */

            if (size > PCI_EXP_LNKCTL) {

                vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP, 0, ~0);

                vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);

                vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA, 0, ~0);

#ifndef PCI_EXP_LNKCAP2

#define PCI_EXP_LNKCAP2 44

#endif

#ifndef PCI_EXP_LNKSTA2

#define PCI_EXP_LNKSTA2 50

#endif

                /* Link 2 Capabilities, Status, and Control goes away */

                if (size > PCI_EXP_LNKCAP2) {

                    vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP2, 0, ~0);

                    vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL2, 0, ~0);

                    vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA2, 0, ~0);

                }

            }

        } else if (type == PCI_EXP_TYPE_LEG_END) {

            /*

             * Legacy endpoints don't belong on the root complex.  Windows

             * seems to be happier with devices if we skip the capability.

             */

            return 0;

        }

    } else {

        /*

         * Convert Root Complex Integrated Endpoints to regular endpoints.

         * These devices don't support LNK/LNK2 capabilities, so make them up.

         */

        if (type == PCI_EXP_TYPE_RC_END) {

            vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,

                                   PCI_EXP_TYPE_ENDPOINT << 4,

                                   PCI_EXP_FLAGS_TYPE);

            vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP,

                                   PCI_EXP_LNK_MLW_1 | PCI_EXP_LNK_LS_25, ~0);

            vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);

        }

        /* Mark the Link Status bits as emulated to allow virtual negotiation */

        vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA,

                               pci_get_word(vdev->pdev.config + pos +

                                            PCI_EXP_LNKSTA),

                               PCI_EXP_LNKCAP_MLW | PCI_EXP_LNKCAP_SLS);

    }

    pos = pci_add_capability(&vdev->pdev, PCI_CAP_ID_EXP, pos, size);

    if (pos >= 0) {

        vdev->pdev.exp.exp_cap = pos;

    }

    return pos;

}


static UserDefNested *nested_struct_create(void)

{

    UserDefNested *udnp = g_malloc0(sizeof(*udnp));

    udnp->string0 = strdup("test_string0");

    udnp->dict1.string1 = strdup("test_string1");

    udnp->dict1.dict2.userdef1 = g_malloc0(sizeof(UserDefOne));

    udnp->dict1.dict2.userdef1->base = g_new0(UserDefZero, 1);

    udnp->dict1.dict2.userdef1->base->integer = 42;

    udnp->dict1.dict2.userdef1->string = strdup("test_string");

    udnp->dict1.dict2.string2 = strdup("test_string2");

    udnp->dict1.has_dict3 = true;

    udnp->dict1.dict3.userdef2 = g_malloc0(sizeof(UserDefOne));

    udnp->dict1.dict3.userdef2->base = g_new0(UserDefZero, 1);

    udnp->dict1.dict3.userdef2->base->integer = 43;

    udnp->dict1.dict3.userdef2->string = strdup("test_string");

    udnp->dict1.dict3.string3 = strdup("test_string3");

    return udnp;

}


static int qcow2_create(const char *filename, QEMUOptionParameter *options)

{

    const char *backing_file = NULL;

    const char *backing_fmt = NULL;

    uint64_t sectors = 0;

    int flags = 0;

    size_t cluster_size = DEFAULT_CLUSTER_SIZE;

    int prealloc = 0;

    /* Read out options */

    while (options && options->name) {

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

            sectors = options->value.n / 512;

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

            backing_file = options->value.s;

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

            backing_fmt = options->value.s;

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

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

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

            if (options->value.n) {

                cluster_size = options->value.n;

            }

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

            if (!options->value.s || !strcmp(options->value.s, "off")) {

                prealloc = 0;

            } else if (!strcmp(options->value.s, "metadata")) {

                prealloc = 1;

            } else {

                fprintf(stderr, "Invalid preallocation mode: '%s'\n",

                    options->value.s);

                return -EINVAL;

            }

        }

        options++;

    }

    if (backing_file && prealloc) {

        fprintf(stderr, "Backing file and preallocation cannot be used at "

            "the same time\n");

        return -EINVAL;

    }

    return qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,

                         cluster_size, prealloc, options);

}


static int rpza_decode_init(AVCodecContext *avctx)

{

    RpzaContext *s = avctx->priv_data;

    s->avctx = avctx;

    avctx->pix_fmt = PIX_FMT_RGB555;

    dsputil_init(&s->dsp, avctx);

    s->frame.data[0] = NULL;

    return 0;

}


static void qmp_output_type_str(Visitor *v, const char *name, char **obj,

                                Error **errp)

{

    QmpOutputVisitor *qov = to_qov(v);

    if (*obj) {

        qmp_output_add(qov, name, qstring_from_str(*obj));

    } else {

        qmp_output_add(qov, name, qstring_from_str(""));

    }

}


static void v9fs_open_post_lstat(V9fsState *s, V9fsOpenState *vs, int err)

{

    int flags;

    if (err) {

        err = -errno;

        goto out;

    }

    stat_to_qid(&vs->stbuf, &vs->qid);

    if (S_ISDIR(vs->stbuf.st_mode)) {

        vs->fidp->fs.dir = v9fs_do_opendir(s, &vs->fidp->path);

        v9fs_open_post_opendir(s, vs, err);

    } else {

        if (s->proto_version == V9FS_PROTO_2000L) {

            if (!valid_flags(vs->mode)) {

                err = -EINVAL;

                goto out;

            }

            flags = vs->mode;

        } else {

            flags = omode_to_uflags(vs->mode);

        }

        vs->fidp->fs.fd = v9fs_do_open(s, &vs->fidp->path, flags);

        v9fs_open_post_open(s, vs, err);

    }

    return;

out:

    complete_pdu(s, vs->pdu, err);

    qemu_free(vs);

}


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

{

    sPAPRCPUCore *sc = SPAPR_CPU_CORE(OBJECT(dev));

    sPAPRCPUCoreClass *scc = SPAPR_CPU_CORE_GET_CLASS(OBJECT(dev));

    size_t size = object_type_get_instance_size(scc->cpu_type);

    CPUCore *cc = CPU_CORE(dev);

    int i;

    for (i = 0; i < cc->nr_threads; i++) {

        void *obj = sc->threads + i * size;

        DeviceState *dev = DEVICE(obj);

        CPUState *cs = CPU(dev);

        PowerPCCPU *cpu = POWERPC_CPU(cs);

        spapr_cpu_destroy(cpu);

        object_unparent(cpu->intc);

        cpu_remove_sync(cs);

        object_unparent(obj);

    }

    g_free(sc->threads);

}


static uint32_t taihu_cpld_readw (void *opaque, hwaddr addr)

{

    uint32_t ret;

    ret = taihu_cpld_readb(opaque, addr) << 8;

    ret |= taihu_cpld_readb(opaque, addr + 1);

    return ret;

}


int vfio_container_ioctl(AddressSpace *as, int32_t groupid,

                         int req, void *param)

{

    /* We allow only certain ioctls to the container */

    switch (req) {

    case VFIO_CHECK_EXTENSION:

    case VFIO_IOMMU_SPAPR_TCE_GET_INFO:

    case VFIO_EEH_PE_OP:

        break;

    default:

        /* Return an error on unknown requests */

        error_report("vfio: unsupported ioctl %X", req);

        return -1;

    }

    return vfio_container_do_ioctl(as, groupid, req, param);

}


static void vtd_do_iommu_translate(VTDAddressSpace *vtd_as, PCIBus *bus,

                                   uint8_t devfn, hwaddr addr, bool is_write,

                                   IOMMUTLBEntry *entry)

{

    IntelIOMMUState *s = vtd_as->iommu_state;

    VTDContextEntry ce;

    uint8_t bus_num = pci_bus_num(bus);

    VTDContextCacheEntry *cc_entry = &vtd_as->context_cache_entry;

    uint64_t slpte;

    uint32_t level;

    uint16_t source_id = vtd_make_source_id(bus_num, devfn);

    int ret_fr;

    bool is_fpd_set = false;

    bool reads = true;

    bool writes = true;

    VTDIOTLBEntry *iotlb_entry;

    /* Check if the request is in interrupt address range */

    if (vtd_is_interrupt_addr(addr)) {

        if (is_write) {

            /* FIXME: since we don't know the length of the access here, we

             * treat Non-DWORD length write requests without PASID as

             * interrupt requests, too. Withoud interrupt remapping support,

             * we just use 1:1 mapping.

             */

            VTD_DPRINTF(MMU, "write request to interrupt address "

                        "gpa 0x%"PRIx64, addr);

            entry->iova = addr & VTD_PAGE_MASK_4K;

            entry->translated_addr = addr & VTD_PAGE_MASK_4K;

            entry->addr_mask = ~VTD_PAGE_MASK_4K;

            entry->perm = IOMMU_WO;

            return;

        } else {

            VTD_DPRINTF(GENERAL, "error: read request from interrupt address "

                        "gpa 0x%"PRIx64, addr);

            vtd_report_dmar_fault(s, source_id, addr, VTD_FR_READ, is_write);

            return;

        }

    }

    /* Try to fetch slpte form IOTLB */

    iotlb_entry = vtd_lookup_iotlb(s, source_id, addr);

    if (iotlb_entry) {

        VTD_DPRINTF(CACHE, "hit iotlb sid 0x%"PRIx16 " gpa 0x%"PRIx64

                    " slpte 0x%"PRIx64 " did 0x%"PRIx16, source_id, addr,

                    iotlb_entry->slpte, iotlb_entry->domain_id);

        slpte = iotlb_entry->slpte;

        reads = iotlb_entry->read_flags;

        writes = iotlb_entry->write_flags;

        goto out;

    }

    /* Try to fetch context-entry from cache first */

    if (cc_entry->context_cache_gen == s->context_cache_gen) {

        VTD_DPRINTF(CACHE, "hit context-cache bus %d devfn %d "

                    "(hi %"PRIx64 " lo %"PRIx64 " gen %"PRIu32 ")",

                    bus_num, devfn, cc_entry->context_entry.hi,

                    cc_entry->context_entry.lo, cc_entry->context_cache_gen);

        ce = cc_entry->context_entry;

        is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;

    } else {

        ret_fr = vtd_dev_to_context_entry(s, bus_num, devfn, &ce);

        is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD;

        if (ret_fr) {

            ret_fr = -ret_fr;

            if (is_fpd_set && vtd_is_qualified_fault(ret_fr)) {

                VTD_DPRINTF(FLOG, "fault processing is disabled for DMA "

                            "requests through this context-entry "

                            "(with FPD Set)");

            } else {

                vtd_report_dmar_fault(s, source_id, addr, ret_fr, is_write);

            }

            return;

        }

        /* Update context-cache */

        VTD_DPRINTF(CACHE, "update context-cache bus %d devfn %d "

                    "(hi %"PRIx64 " lo %"PRIx64 " gen %"PRIu32 "->%"PRIu32 ")",

                    bus_num, devfn, ce.hi, ce.lo,

                    cc_entry->context_cache_gen, s->context_cache_gen);

        cc_entry->context_entry = ce;

        cc_entry->context_cache_gen = s->context_cache_gen;

    }

    ret_fr = vtd_gpa_to_slpte(&ce, addr, is_write, &slpte, &level,

                              &reads, &writes);

    if (ret_fr) {

        ret_fr = -ret_fr;

        if (is_fpd_set && vtd_is_qualified_fault(ret_fr)) {

            VTD_DPRINTF(FLOG, "fault processing is disabled for DMA requests "

                        "through this context-entry (with FPD Set)");

        } else {

            vtd_report_dmar_fault(s, source_id, addr, ret_fr, is_write);

        }

        return;

    }

    vtd_update_iotlb(s, source_id, VTD_CONTEXT_ENTRY_DID(ce.hi), addr, slpte,

                     reads, writes);

out:

    entry->iova = addr & VTD_PAGE_MASK_4K;

    entry->translated_addr = vtd_get_slpte_addr(slpte) & VTD_PAGE_MASK_4K;

    entry->addr_mask = ~VTD_PAGE_MASK_4K;

    entry->perm = (writes ? 2 : 0) + (reads ? 1 : 0);

}


void call_pal (CPUState *env, int palcode)

{

    target_ulong ret;

    if (logfile != NULL)

        fprintf(logfile, "%s: palcode %02x\n", __func__, palcode);

    switch (palcode) {

    case 0x83:

        /* CALLSYS */

        if (logfile != NULL)

            fprintf(logfile, "CALLSYS n " TARGET_FMT_ld "\n", env->ir[0]);

        ret = do_syscall(env, env->ir[IR_V0], env->ir[IR_A0], env->ir[IR_A1],

                         env->ir[IR_A2], env->ir[IR_A3], env->ir[IR_A4],

                         env->ir[IR_A5]);

        if (ret >= 0) {

            env->ir[IR_A3] = 0;

            env->ir[IR_V0] = ret;

        } else {

            env->ir[IR_A3] = 1;

            env->ir[IR_V0] = -ret;

        }

        break;

    case 0x9E:

        /* RDUNIQUE */

        env->ir[IR_V0] = env->unique;

        if (logfile != NULL)

            fprintf(logfile, "RDUNIQUE: " TARGET_FMT_lx "\n", env->unique);

        break;

    case 0x9F:

        /* WRUNIQUE */

        env->unique = env->ir[IR_A0];

        if (logfile != NULL)

            fprintf(logfile, "WRUNIQUE: " TARGET_FMT_lx "\n", env->unique);

        break;

    default:

        if (logfile != NULL)

            fprintf(logfile, "%s: unhandled palcode %02x\n",

                    __func__, palcode);

        exit(1);

    }

}


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

                                  const uint16_t *ubuf0, const uint16_t *ubuf1,

                                  const uint16_t *vbuf0, const uint16_t *vbuf1,

                                  const uint16_t *abuf0, uint8_t *dest,

                                  int dstW, int uvalpha, enum PixelFormat dstFormat,

                                  int flags, int y)

{

    const uint16_t *buf1= buf0; //FIXME needed for RGB1/BGR1

    if (uvalpha < 2048) { // note this is not correct (shifts chrominance by 0.5 pixels) but it is a bit faster

        __asm__ volatile(

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

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

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

            YSCALEYUV2PACKED1(%%REGBP, %5)

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

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

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

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

               "a" (&c->redDither)

        );

    } else {

        __asm__ volatile(

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

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

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

            YSCALEYUV2PACKED1b(%%REGBP, %5)

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

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

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

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

               "a" (&c->redDither)

        );

    }

}


yuv2gray16_1_c_template(SwsContext *c, const uint16_t *buf0,

                        const uint16_t *ubuf0, const uint16_t *ubuf1,

                        const uint16_t *vbuf0, const uint16_t *vbuf1,

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

                        int uvalpha, enum PixelFormat dstFormat,

                        int flags, int y, enum PixelFormat target)

{

    int i;

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

        const int i2 = 2 * i;

        int Y1 = buf0[i2  ] << 1;

        int Y2 = buf0[i2+1] << 1;

        output_pixel(&dest[2 * i2 + 0], Y1);

        output_pixel(&dest[2 * i2 + 2], Y2);

    }

}


uint32_t helper_efdctuiz (uint64_t val)

{

    CPU_DoubleU u;

    u.ll = val;

    /* NaN are not treated the same way IEEE 754 does */

    if (unlikely(float64_is_nan(u.d)))

        return 0;

    return float64_to_uint32_round_to_zero(u.d, &env->vec_status);

}


int qcow2_zero_clusters(BlockDriverState *bs, uint64_t offset, int nb_sectors)

{

    BDRVQcow2State *s = bs->opaque;

    unsigned int nb_clusters;

    int ret;

    /* The zero flag is only supported by version 3 and newer */

    if (s->qcow_version < 3) {

        return -ENOTSUP;

    }

    /* Each L2 table is handled by its own loop iteration */

    nb_clusters = size_to_clusters(s, nb_sectors << BDRV_SECTOR_BITS);

    s->cache_discards = true;

    while (nb_clusters > 0) {

        ret = zero_single_l2(bs, offset, nb_clusters);

        if (ret < 0) {

            goto fail;

        }

        nb_clusters -= ret;

        offset += (ret * s->cluster_size);

    }

    ret = 0;

fail:

    s->cache_discards = false;

    qcow2_process_discards(bs, ret);

    return ret;

}


void async_context_push(void)

{

    struct AsyncContext *new = qemu_mallocz(sizeof(*new));

    new->parent = async_context;

    new->id = async_context->id + 1;

    async_context = new;

}


static int h264_extradata_to_annexb(AVCodecContext *avctx, const int padding)

{

    uint16_t unit_size;

    uint64_t total_size                 = 0;

    uint8_t *out                        = NULL, unit_nb, sps_done = 0,

             sps_seen                   = 0, pps_seen = 0;

    const uint8_t *extradata            = avctx->extradata + 4;

    static const uint8_t nalu_header[4] = { 0, 0, 0, 1 };

    int length_size = (*extradata++ & 0x3) + 1; // retrieve length coded size

    /* retrieve sps and pps unit(s) */

    unit_nb = *extradata++ & 0x1f; /* number of sps unit(s) */

    if (!unit_nb) {

        goto pps;

    } else {

        sps_seen = 1;

    }

    while (unit_nb--) {

        void *tmp;

        unit_size   = AV_RB16(extradata);

        total_size += unit_size + 4;

        if (total_size > INT_MAX - padding ||

            extradata + 2 + unit_size > avctx->extradata +

            avctx->extradata_size) {

            av_free(out);

            return AVERROR(EINVAL);

        }

        tmp = av_realloc(out, total_size + padding);

        if (!tmp) {

            av_free(out);

            return AVERROR(ENOMEM);

        }

        out = tmp;

        memcpy(out + total_size - unit_size - 4, nalu_header, 4);

        memcpy(out + total_size - unit_size, extradata + 2, unit_size);

        extradata += 2 + unit_size;

pps:

        if (!unit_nb && !sps_done++) {

            unit_nb = *extradata++; /* number of pps unit(s) */

            if (unit_nb)

                pps_seen = 1;

        }

    }

    if (out)

        memset(out + total_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);

    if (!sps_seen)

        av_log(avctx, AV_LOG_WARNING,

               "Warning: SPS NALU missing or invalid. "

               "The resulting stream may not play.\n");

    if (!pps_seen)

        av_log(avctx, AV_LOG_WARNING,

               "Warning: PPS NALU missing or invalid. "

               "The resulting stream may not play.\n");

    av_free(avctx->extradata);

    avctx->extradata      = out;

    avctx->extradata_size = total_size;

    return length_size;

}


static inline void stl_phys_internal(hwaddr addr, uint32_t val,

                                     enum device_endian endian)

{

    uint8_t *ptr;

    MemoryRegionSection *section;

    hwaddr l = 4;

    hwaddr addr1;

    section = address_space_translate(&address_space_memory, addr, &addr1, &l,

                                      true);

    if (l < 4 || !memory_region_is_ram(section->mr) || section->readonly) {

        if (memory_region_is_ram(section->mr)) {

            section = &phys_sections[phys_section_rom];

        }

#if defined(TARGET_WORDS_BIGENDIAN)

        if (endian == DEVICE_LITTLE_ENDIAN) {

            val = bswap32(val);

        }

#else

        if (endian == DEVICE_BIG_ENDIAN) {

            val = bswap32(val);

        }

#endif

        io_mem_write(section->mr, addr1, val, 4);

    } else {

        /* RAM case */

        addr1 += memory_region_get_ram_addr(section->mr) & TARGET_PAGE_MASK;

        ptr = qemu_get_ram_ptr(addr1);

        switch (endian) {

        case DEVICE_LITTLE_ENDIAN:

            stl_le_p(ptr, val);

            break;

        case DEVICE_BIG_ENDIAN:

            stl_be_p(ptr, val);

            break;

        default:

            stl_p(ptr, val);

            break;

        }

        invalidate_and_set_dirty(addr1, 4);

    }

}


static int vmdk_write(BlockDriverState *bs, int64_t sector_num,

                     const uint8_t *buf, int nb_sectors)

{

    BDRVVmdkState *s = bs->opaque;

    VmdkExtent *extent = NULL;

    int n;

    int64_t index_in_cluster;

    uint64_t cluster_offset;

    VmdkMetaData m_data;

    if (sector_num > bs->total_sectors) {

        fprintf(stderr,

                "(VMDK) Wrong offset: sector_num=0x%" PRIx64

                " total_sectors=0x%" PRIx64 "\n",

                sector_num, bs->total_sectors);

        return -1;

    }

    while (nb_sectors > 0) {

        extent = find_extent(s, sector_num, extent);

        if (!extent) {

            return -EIO;

        }

        cluster_offset = get_cluster_offset(

                                bs,

                                extent,

                                &m_data,

                                sector_num << 9, 1);

        if (!cluster_offset) {

            return -1;

        }

        index_in_cluster = sector_num % extent->cluster_sectors;

        n = extent->cluster_sectors - index_in_cluster;

        if (n > nb_sectors) {

            n = nb_sectors;

        }

        if (bdrv_pwrite(bs->file,

                        cluster_offset + index_in_cluster * 512,

                        buf, n * 512)

                != n * 512) {

            return -1;

        }

        if (m_data.valid) {

            /* update L2 tables */

            if (vmdk_L2update(extent, &m_data) == -1) {

                return -1;

            }

        }

        nb_sectors -= n;

        sector_num += n;

        buf += n * 512;

        // update CID on the first write every time the virtual disk is opened

        if (!s->cid_updated) {

            vmdk_write_cid(bs, time(NULL));

            s->cid_updated = true;

        }

    }

    return 0;

}


static inline void gen_evfsabs(DisasContext *ctx)

{

    if (unlikely(!ctx->spe_enabled)) {

        gen_exception(ctx, POWERPC_EXCP_APU);

        return;

    }

#if defined(TARGET_PPC64)

    tcg_gen_andi_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)], ~0x8000000080000000LL);

#else

    tcg_gen_andi_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)], ~0x80000000);

    tcg_gen_andi_tl(cpu_gprh[rD(ctx->opcode)], cpu_gprh[rA(ctx->opcode)], ~0x80000000);

#endif

}


void usb_ep_reset(USBDevice *dev)

{

    int ep;

    dev->ep_ctl.nr = 0;

    dev->ep_ctl.type = USB_ENDPOINT_XFER_CONTROL;

    dev->ep_ctl.ifnum = 0;

    dev->ep_ctl.dev = dev;

    dev->ep_ctl.pipeline = false;

    for (ep = 0; ep < USB_MAX_ENDPOINTS; ep++) {

        dev->ep_in[ep].nr = ep + 1;

        dev->ep_out[ep].nr = ep + 1;

        dev->ep_in[ep].pid = USB_TOKEN_IN;

        dev->ep_out[ep].pid = USB_TOKEN_OUT;

        dev->ep_in[ep].type = USB_ENDPOINT_XFER_INVALID;

        dev->ep_out[ep].type = USB_ENDPOINT_XFER_INVALID;

        dev->ep_in[ep].ifnum = 0;

        dev->ep_out[ep].ifnum = 0;

        dev->ep_in[ep].dev = dev;

        dev->ep_out[ep].dev = dev;

        dev->ep_in[ep].pipeline = false;

        dev->ep_out[ep].pipeline = false;

    }

}


int qemu_v9fs_synth_mkdir(V9fsSynthNode *parent, int mode,

                          const char *name, V9fsSynthNode **result)

{

    int ret;

    V9fsSynthNode *node, *tmp;

    if (!v9fs_synth_fs) {

        return EAGAIN;

    }

    if (!name || (strlen(name) >= NAME_MAX)) {

        return EINVAL;

    }

    if (!parent) {

        parent = &v9fs_synth_root;

    }

    qemu_mutex_lock(&v9fs_synth_mutex);

    QLIST_FOREACH(tmp, &parent->child, sibling) {

        if (!strcmp(tmp->name, name)) {

            ret = EEXIST;

            goto err_out;

        }

    }

    /* Add the name */

    node = v9fs_add_dir_node(parent, mode, name, NULL, v9fs_synth_node_count++);

    v9fs_add_dir_node(node, parent->attr->mode, "..",

                      parent->attr, parent->attr->inode);

    v9fs_add_dir_node(node, node->attr->mode, ".",

                      node->attr, node->attr->inode);

    *result = node;

    ret = 0;

err_out:

    qemu_mutex_unlock(&v9fs_synth_mutex);

    return ret;

}


static void megasas_handle_frame(MegasasState *s, uint64_t frame_addr,

                                 uint32_t frame_count)

{

    uint8_t frame_status = MFI_STAT_INVALID_CMD;

    uint64_t frame_context;

    MegasasCmd *cmd;

    /*

     * Always read 64bit context, top bits will be

     * masked out if required in megasas_enqueue_frame()

     */

    frame_context = megasas_frame_get_context(s, frame_addr);

    cmd = megasas_enqueue_frame(s, frame_addr, frame_context, frame_count);

    if (!cmd) {

        /* reply queue full */

        trace_megasas_frame_busy(frame_addr);

        megasas_frame_set_scsi_status(s, frame_addr, BUSY);

        megasas_frame_set_cmd_status(s, frame_addr, MFI_STAT_SCSI_DONE_WITH_ERROR);

        megasas_complete_frame(s, frame_context);

        s->event_count++;

        return;

    }

    switch (cmd->frame->header.frame_cmd) {

    case MFI_CMD_INIT:

        frame_status = megasas_init_firmware(s, cmd);

        break;

    case MFI_CMD_DCMD:

        frame_status = megasas_handle_dcmd(s, cmd);

        break;

    case MFI_CMD_ABORT:

        frame_status = megasas_handle_abort(s, cmd);

        break;

    case MFI_CMD_PD_SCSI_IO:

        frame_status = megasas_handle_scsi(s, cmd, 0);

        break;

    case MFI_CMD_LD_SCSI_IO:

        frame_status = megasas_handle_scsi(s, cmd, 1);

        break;

    case MFI_CMD_LD_READ:

    case MFI_CMD_LD_WRITE:

        frame_status = megasas_handle_io(s, cmd);

        break;

    default:

        trace_megasas_unhandled_frame_cmd(cmd->index,

                                          cmd->frame->header.frame_cmd);

        s->event_count++;

        break;

    }

    if (frame_status != MFI_STAT_INVALID_STATUS) {

        if (cmd->frame) {

            cmd->frame->header.cmd_status = frame_status;

        } else {

            megasas_frame_set_cmd_status(s, frame_addr, frame_status);

        }

        megasas_unmap_frame(s, cmd);

        megasas_complete_frame(s, cmd->context);

    }

}


static void intel_hda_mmio_writew(void *opaque, target_phys_addr_t addr, uint32_t val)

{

    IntelHDAState *d = opaque;

    const IntelHDAReg *reg = intel_hda_reg_find(d, addr);

    intel_hda_reg_write(d, reg, val, 0xffff);

}


void pcnet_common_cleanup(PCNetState *d)

{

    d->nic = NULL;

}


static void lan9118_16bit_mode_write(void *opaque, target_phys_addr_t offset,

                                     uint64_t val, unsigned size)

{

    switch (size) {

    case 2:

        lan9118_writew(opaque, offset, (uint32_t)val);

        return;

    case 4:

        lan9118_writel(opaque, offset, val, size);

        return;

    }

    hw_error("lan9118_write: Bad size 0x%x\n", size);

}


av_cold int ff_h264_decode_init(AVCodecContext *avctx)

{

    H264Context *h = avctx->priv_data;

    int ret;

    ret = h264_init_context(avctx, h);

    if (ret < 0)

        return ret;

    memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));

    memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));

    /* set defaults */

    // s->decode_mb = ff_h263_decode_mb;

    if (!avctx->has_b_frames)

        h->low_delay = 1;

    ff_h264_decode_init_vlc();

    ff_init_cabac_states();

    if (avctx->codec_id == AV_CODEC_ID_H264) {

        if (avctx->ticks_per_frame == 1)

            h->avctx->framerate.num *= 2;

        avctx->ticks_per_frame = 2;

    }

    if (avctx->extradata_size > 0 && avctx->extradata) {

       ret = ff_h264_decode_extradata(h);

       if (ret < 0) {

           ff_h264_free_context(h);

           return ret;

       }

    }

    if (h->sps.bitstream_restriction_flag &&

        h->avctx->has_b_frames < h->sps.num_reorder_frames) {

        h->avctx->has_b_frames = h->sps.num_reorder_frames;

        h->low_delay           = 0;

    }

    avctx->internal->allocate_progress = 1;

    if (h->enable_er) {

        av_log(avctx, AV_LOG_WARNING,

               "Error resilience is enabled. It is unsafe and unsupported and may crash. "

               "Use it at your own risk\n");

    }

    return 0;

}


static void stream_desc_load(struct Stream *s, hwaddr addr)

{

    struct SDesc *d = &s->desc;

    int i;

    cpu_physical_memory_read(addr, (void *) d, sizeof *d);

    /* Convert from LE into host endianness.  */

    d->buffer_address = le64_to_cpu(d->buffer_address);

    d->nxtdesc = le64_to_cpu(d->nxtdesc);

    d->control = le32_to_cpu(d->control);

    d->status = le32_to_cpu(d->status);

    for (i = 0; i < ARRAY_SIZE(d->app); i++) {

        d->app[i] = le32_to_cpu(d->app[i]);

    }

}


static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)

{

    CharDriverState *chr;

    WinCharState *s;

    chr = g_malloc0(sizeof(CharDriverState));

    s = g_malloc0(sizeof(WinCharState));

    s->hcom = fd_out;

    chr->opaque = s;

    chr->chr_write = win_chr_write;

    return chr;

}


void gdb_exit(CPUState *env, int code)

{

  GDBState *s;

  char buf[4];

  s = &gdbserver_state;

  if (gdbserver_fd < 0 || s->fd < 0)

    return;

  snprintf(buf, sizeof(buf), "W%02x", code);

  put_packet(s, buf);

}


static int usb_uhci_piix4_initfn(PCIDevice *dev)

{

    UHCIState *s = DO_UPCAST(UHCIState, dev, dev);

    uint8_t *pci_conf = s->dev.config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_INTEL_82371AB_2);

    return usb_uhci_common_initfn(s);

}


static void pxa2xx_gpio_write(void *opaque, hwaddr offset,

                              uint64_t value, unsigned size)

{

    PXA2xxGPIOInfo *s = (PXA2xxGPIOInfo *) opaque;

    int bank;

    if (offset >= 0x200)

        return;

    bank = pxa2xx_gpio_regs[offset].bank;

    switch (pxa2xx_gpio_regs[offset].reg) {

    case GPDR:		/* GPIO Pin-Direction registers */

        s->dir[bank] = value;

        pxa2xx_gpio_handler_update(s);

        break;

    case GPSR:		/* GPIO Pin-Output Set registers */

        s->olevel[bank] |= value;

        pxa2xx_gpio_handler_update(s);

        break;

    case GPCR:		/* GPIO Pin-Output Clear registers */

        s->olevel[bank] &= ~value;

        pxa2xx_gpio_handler_update(s);

        break;

    case GRER:		/* GPIO Rising-Edge Detect Enable registers */

        s->rising[bank] = value;

        break;

    case GFER:		/* GPIO Falling-Edge Detect Enable registers */

        s->falling[bank] = value;

        break;

    case GAFR_L:	/* GPIO Alternate Function registers */

        s->gafr[bank * 2] = value;

        break;

    case GAFR_U:	/* GPIO Alternate Function registers */

        s->gafr[bank * 2 + 1] = value;

        break;

    case GEDR:		/* GPIO Edge Detect Status registers */

        s->status[bank] &= ~value;

        pxa2xx_gpio_irq_update(s);

        break;

    default:

        hw_error("%s: Bad offset " REG_FMT "\n", __FUNCTION__, offset);

    }

}


int cpu_signal_handler(int host_signum, void *pinfo, void *puc)

{

    siginfo_t *info = pinfo;

    ucontext_t *uc = puc;

    unsigned long ip;

    int is_write = 0;

    ip = uc->uc_mcontext.sc_ip;

    switch (host_signum) {

    case SIGILL:

    case SIGFPE:

    case SIGSEGV:

    case SIGBUS:

    case SIGTRAP:

        if (info->si_code && (info->si_segvflags & __ISR_VALID)) {

            /* ISR.W (write-access) is bit 33:  */

            is_write = (info->si_isr >> 33) & 1;

        }

        break;

    default:

        break;

    }

    return handle_cpu_signal(ip, (unsigned long)info->si_addr,

                             is_write,

                             (sigset_t *)&uc->uc_sigmask);

}


void virtio_blk_data_plane_start(VirtIOBlockDataPlane *s)

{

    BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(s->vdev)));

    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);

    VirtIOBlock *vblk = VIRTIO_BLK(s->vdev);

    VirtQueue *vq;

    int r;

    if (s->started || s->disabled) {

        return;

    }

    if (s->starting) {

        return;

    }

    s->starting = true;

    vq = virtio_get_queue(s->vdev, 0);

    if (!vring_setup(&s->vring, s->vdev, 0)) {

        goto fail_vring;

    }

    /* Set up guest notifier (irq) */

    r = k->set_guest_notifiers(qbus->parent, 1, true);

    if (r != 0) {

        fprintf(stderr, "virtio-blk failed to set guest notifier (%d), "

                "ensure -enable-kvm is set\n", r);

        goto fail_guest_notifiers;

    }

    s->guest_notifier = virtio_queue_get_guest_notifier(vq);

    /* Set up virtqueue notify */

    r = k->set_host_notifier(qbus->parent, 0, true);

    if (r != 0) {

        fprintf(stderr, "virtio-blk failed to set host notifier (%d)\n", r);

        goto fail_host_notifier;

    }

    s->host_notifier = *virtio_queue_get_host_notifier(vq);

    s->saved_complete_request = vblk->complete_request;

    vblk->complete_request = complete_request_vring;

    s->starting = false;

    s->started = true;

    trace_virtio_blk_data_plane_start(s);

    blk_set_aio_context(s->conf->conf.blk, s->ctx);

    /* Kick right away to begin processing requests already in vring */

    event_notifier_set(virtio_queue_get_host_notifier(vq));

    /* Get this show started by hooking up our callbacks */

    aio_context_acquire(s->ctx);

    aio_set_event_notifier(s->ctx, &s->host_notifier, true,

                           handle_notify);

    aio_context_release(s->ctx);

    return;

  fail_host_notifier:

    k->set_guest_notifiers(qbus->parent, 1, false);

  fail_guest_notifiers:

    vring_teardown(&s->vring, s->vdev, 0);

    s->disabled = true;

  fail_vring:

    s->starting = false;

}


static void qdm2_decode_fft_packets (QDM2Context *q)

{

    int i, j, min, max, value, type, unknown_flag;

    GetBitContext gb;

    if (q->sub_packet_list_B[0].packet == NULL)

        return;

    /* reset minimum indices for FFT coefficients */

    q->fft_coefs_index = 0;

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

        q->fft_coefs_min_index[i] = -1;

    /* process subpackets ordered by type, largest type first */

    for (i = 0, max = 256; i < q->sub_packets_B; i++) {

        QDM2SubPacket *packet;

        /* find subpacket with largest type less than max */

        for (j = 0, min = 0, packet = NULL; j < q->sub_packets_B; j++) {

            value = q->sub_packet_list_B[j].packet->type;

            if (value > min && value < max) {

                min = value;

                packet = q->sub_packet_list_B[j].packet;

            }

        }

        max = min;

        /* check for errors (?) */

        if (i == 0 && (packet->type < 16 || packet->type >= 48 || fft_subpackets[packet->type - 16]))

            return;

        /* decode FFT tones */

        init_get_bits (&gb, packet->data, packet->size*8);

        if (packet->type >= 32 && packet->type < 48 && !fft_subpackets[packet->type - 16])

            unknown_flag = 1;

        else

            unknown_flag = 0;

        type = packet->type;

        if ((type >= 17 && type < 24) || (type >= 33 && type < 40)) {

            int duration = q->sub_sampling + 5 - (type & 15);

            if (duration >= 0 && duration < 4)

                qdm2_fft_decode_tones(q, duration, &gb, unknown_flag);

        } else if (type == 31) {

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

                qdm2_fft_decode_tones(q, i, &gb, unknown_flag);

        } else if (type == 46) {

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

                q->fft_level_exp[i] = get_bits(&gb, 6);

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

            qdm2_fft_decode_tones(q, i, &gb, unknown_flag);

        }

    } // Loop on B packets

    /* calculate maximum indices for FFT coefficients */

    for (i = 0, j = -1; i < 5; i++)

        if (q->fft_coefs_min_index[i] >= 0) {

            if (j >= 0)

                q->fft_coefs_max_index[j] = q->fft_coefs_min_index[i];

            j = i;

        }

    if (j >= 0)

        q->fft_coefs_max_index[j] = q->fft_coefs_index;

}


void avcodec_get_channel_layout_string(char *buf, int buf_size, int nb_channels, int64_t channel_layout)

{

    int i;

    if (channel_layout==0)

        channel_layout = avcodec_guess_channel_layout(nb_channels, CODEC_ID_NONE, NULL);

    for (i=0; channel_layout_map[i].name; i++)

        if (nb_channels    == channel_layout_map[i].nb_channels &&

            channel_layout == channel_layout_map[i].layout) {

            snprintf(buf, buf_size, channel_layout_map[i].name);

            return;

        }

    snprintf(buf, buf_size, "%d channels", nb_channels);

    if (channel_layout) {

        int i,ch;

        av_strlcat(buf, " (", buf_size);

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

            if ((channel_layout & (1L<<i))) {

                const char *name = get_channel_name(i);

                if (name) {

                    if (ch>0) av_strlcat(buf, "|", buf_size);

                    av_strlcat(buf, name, buf_size);

                }

                ch++;

            }

        }

        av_strlcat(buf, ")", buf_size);

    }

}


int ff_h264_decode_ref_pic_list_reordering(H264Context *h, H264SliceContext *sl)

{

    int list, index, pic_structure;

    print_short_term(h);

    print_long_term(h);

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

        memcpy(sl->ref_list[list], h->default_ref_list[list], sl->ref_count[list] * sizeof(sl->ref_list[0][0]));

        if (get_bits1(&sl->gb)) {    // ref_pic_list_modification_flag_l[01]

            int pred = h->curr_pic_num;

            for (index = 0; ; index++) {

                unsigned int modification_of_pic_nums_idc = get_ue_golomb_31(&sl->gb);

                unsigned int pic_id;

                int i;

                H264Picture *ref = NULL;

                if (modification_of_pic_nums_idc == 3)

                    break;

                if (index >= sl->ref_count[list]) {

                    av_log(h->avctx, AV_LOG_ERROR, "reference count overflow\n");

                    return -1;

                }

                switch (modification_of_pic_nums_idc) {

                case 0:

                case 1: {

                    const unsigned int abs_diff_pic_num = get_ue_golomb(&sl->gb) + 1;

                    int frame_num;

                    if (abs_diff_pic_num > h->max_pic_num) {

                        av_log(h->avctx, AV_LOG_ERROR,

                               "abs_diff_pic_num overflow\n");

                        return AVERROR_INVALIDDATA;

                    }

                    if (modification_of_pic_nums_idc == 0)

                        pred -= abs_diff_pic_num;

                    else

                        pred += abs_diff_pic_num;

                    pred &= h->max_pic_num - 1;

                    frame_num = pic_num_extract(h, pred, &pic_structure);

                    for (i = h->short_ref_count - 1; i >= 0; i--) {

                        ref = h->short_ref[i];

                        assert(ref->reference);

                        assert(!ref->long_ref);

                        if (ref->frame_num == frame_num &&

                            (ref->reference & pic_structure))

                            break;

                    }

                    if (i >= 0)

                        ref->pic_id = pred;

                    break;

                }

                case 2: {

                    int long_idx;

                    pic_id = get_ue_golomb(&sl->gb); // long_term_pic_idx

                    long_idx = pic_num_extract(h, pic_id, &pic_structure);

                    if (long_idx > 31) {

                        av_log(h->avctx, AV_LOG_ERROR,

                               "long_term_pic_idx overflow\n");

                        return AVERROR_INVALIDDATA;

                    }

                    ref = h->long_ref[long_idx];

                    assert(!(ref && !ref->reference));

                    if (ref && (ref->reference & pic_structure)) {

                        ref->pic_id = pic_id;

                        assert(ref->long_ref);

                        i = 0;

                    } else {

                        i = -1;

                    }

                    break;

                }

                default:

                    av_log(h->avctx, AV_LOG_ERROR,

                           "illegal modification_of_pic_nums_idc %u\n",

                           modification_of_pic_nums_idc);

                    return AVERROR_INVALIDDATA;

                }

                if (i < 0) {

                    av_log(h->avctx, AV_LOG_ERROR,

                           "reference picture missing during reorder\n");

                    memset(&sl->ref_list[list][index], 0, sizeof(sl->ref_list[0][0])); // FIXME

                } else {

                    for (i = index; i + 1 < sl->ref_count[list]; i++) {

                        if (sl->ref_list[list][i].parent &&

                            ref->long_ref == sl->ref_list[list][i].parent->long_ref &&

                            ref->pic_id   == sl->ref_list[list][i].pic_id)

                            break;

                    }

                    for (; i > index; i--) {

                        sl->ref_list[list][i] = sl->ref_list[list][i - 1];

                    }

                    ref_from_h264pic(&sl->ref_list[list][index], ref);

                    if (FIELD_PICTURE(h)) {

                        pic_as_field(&sl->ref_list[list][index], pic_structure);

                    }

                }

            }

        }

    }

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

        for (index = 0; index < sl->ref_count[list]; index++) {

            if (   !sl->ref_list[list][index].parent

                || (!FIELD_PICTURE(h) && (sl->ref_list[list][index].reference&3) != 3)) {

                int i;

                av_log(h->avctx, AV_LOG_ERROR, "Missing reference picture, default is %d\n", h->default_ref_list[list][0].poc);

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

                    h->last_pocs[i] = INT_MIN;

                if (h->default_ref_list[list][0].parent

                    && !(!FIELD_PICTURE(h) && (h->default_ref_list[list][0].reference&3) != 3))

                    sl->ref_list[list][index] = h->default_ref_list[list][0];

                else

                    return -1;

            }

            av_assert0(av_buffer_get_ref_count(sl->ref_list[list][index].parent->f->buf[0]) > 0);

        }

    }

    return 0;

}


void FUNCC(ff_h264_chroma422_dc_dequant_idct)(int16_t *_block, int qmul){

    const int stride= 16*2;

    const int xStride= 16;

    int i;

    int temp[8];

    static const uint8_t x_offset[2]={0, 16};

    dctcoef *block = (dctcoef*)_block;

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

        temp[2*i+0] = block[stride*i + xStride*0] + block[stride*i + xStride*1];

        temp[2*i+1] = block[stride*i + xStride*0] - block[stride*i + xStride*1];

    }

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

        const int offset= x_offset[i];

        const int z0= temp[2*0+i] + temp[2*2+i];

        const int z1= temp[2*0+i] - temp[2*2+i];

        const int z2= temp[2*1+i] - temp[2*3+i];

        const int z3= temp[2*1+i] + temp[2*3+i];

        block[stride*0+offset]= ((z0 + z3)*qmul + 128) >> 8;

        block[stride*1+offset]= ((z1 + z2)*qmul + 128) >> 8;

        block[stride*2+offset]= ((z1 - z2)*qmul + 128) >> 8;

        block[stride*3+offset]= ((z0 - z3)*qmul + 128) >> 8;

    }

}


static int curl_open(BlockDriverState *bs, const char *filename, int flags)

{

    BDRVCURLState *s = bs->opaque;

    CURLState *state = NULL;

    double d;

    #define RA_OPTSTR ":readahead="

    char *file;

    char *ra;

    const char *ra_val;

    int parse_state = 0;

    static int inited = 0;

    file = strdup(filename);

    s->readahead_size = READ_AHEAD_SIZE;

    /* Parse a trailing ":readahead=#:" param, if present. */

    ra = file + strlen(file) - 1;

    while (ra >= file) {

        if (parse_state == 0) {

            if (*ra == ':')

                parse_state++;

            else

                break;

        } else if (parse_state == 1) {

            if (*ra > '9' || *ra < '0') {

                char *opt_start = ra - strlen(RA_OPTSTR) + 1;

                if (opt_start > file &&

                    strncmp(opt_start, RA_OPTSTR, strlen(RA_OPTSTR)) == 0) {

                    ra_val = ra + 1;

                    ra -= strlen(RA_OPTSTR) - 1;

                    *ra = '\0';

                    s->readahead_size = atoi(ra_val);

                    break;

                } else {

                    break;

                }

            }

        }

        ra--;

    }

    if ((s->readahead_size & 0x1ff) != 0) {

        fprintf(stderr, "HTTP_READAHEAD_SIZE %zd is not a multiple of 512\n",

                s->readahead_size);

        goto out_noclean;

    }

    if (!inited) {

        curl_global_init(CURL_GLOBAL_ALL);

        inited = 1;

    }

    DPRINTF("CURL: Opening %s\n", file);

    s->url = file;

    state = curl_init_state(s);

    if (!state)

        goto out_noclean;

    // Get file size

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

    curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION, (void *)curl_size_cb);

    if (curl_easy_perform(state->curl))

        goto out;

    curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d);

    curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION, (void *)curl_read_cb);

    curl_easy_setopt(state->curl, CURLOPT_NOBODY, 0);

    if (d)

        s->len = (size_t)d;

    else if(!s->len)

        goto out;

    DPRINTF("CURL: Size = %lld\n", (long long)s->len);

    curl_clean_state(state);

    curl_easy_cleanup(state->curl);

    state->curl = NULL;

    // Now we know the file exists and its size, so let's

    // initialize the multi interface!

    s->multi = curl_multi_init();

    curl_multi_setopt( s->multi, CURLMOPT_SOCKETDATA, s);

    curl_multi_setopt( s->multi, CURLMOPT_SOCKETFUNCTION, curl_sock_cb );

    curl_multi_do(s);

    return 0;

out:

    fprintf(stderr, "CURL: Error opening file: %s\n", state->errmsg);

    curl_easy_cleanup(state->curl);

    state->curl = NULL;

out_noclean:

    qemu_free(file);

    return -EINVAL;

}


static void cin_decode_rle(const unsigned char *src, int src_size, unsigned char *dst, int dst_size)

{

    int len, code;

    unsigned char *dst_end = dst + dst_size;

    const unsigned char *src_end = src + src_size;

    while (src < src_end && dst < dst_end) {

        code = *src++;

        if (code & 0x80) {

            len = code - 0x7F;

            memset(dst, *src++, FFMIN(len, dst_end - dst));

        } else {

            len = code + 1;

            memcpy(dst, src, FFMIN(len, dst_end - dst));

            src += len;

        }

        dst += len;

    }

}


static int64_t coroutine_fn iscsi_co_get_block_status(BlockDriverState *bs,

                                                  int64_t sector_num,

                                                  int nb_sectors, int *pnum,

                                                  BlockDriverState **file)

{

    IscsiLun *iscsilun = bs->opaque;

    struct scsi_get_lba_status *lbas = NULL;

    struct scsi_lba_status_descriptor *lbasd = NULL;

    struct IscsiTask iTask;

    uint64_t lba;

    int64_t ret;

    if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {

        ret = -EINVAL;

        goto out;

    }

    /* default to all sectors allocated */

    ret = BDRV_BLOCK_DATA;

    ret |= (sector_num << BDRV_SECTOR_BITS) | BDRV_BLOCK_OFFSET_VALID;

    *pnum = nb_sectors;

    /* LUN does not support logical block provisioning */

    if (!iscsilun->lbpme) {

        goto out;

    }

    lba = sector_qemu2lun(sector_num, iscsilun);

    iscsi_co_init_iscsitask(iscsilun, &iTask);

    qemu_mutex_lock(&iscsilun->mutex);

retry:

    if (iscsi_get_lba_status_task(iscsilun->iscsi, iscsilun->lun,

                                  lba, 8 + 16, iscsi_co_generic_cb,

                                  &iTask) == NULL) {

        ret = -ENOMEM;

        goto out_unlock;

    }

    while (!iTask.complete) {

        iscsi_set_events(iscsilun);

        qemu_mutex_unlock(&iscsilun->mutex);

        qemu_coroutine_yield();

        qemu_mutex_lock(&iscsilun->mutex);

    }

    if (iTask.do_retry) {

        if (iTask.task != NULL) {

            scsi_free_scsi_task(iTask.task);

            iTask.task = NULL;

        }

        iTask.complete = 0;

        goto retry;

    }

    if (iTask.status != SCSI_STATUS_GOOD) {

        /* in case the get_lba_status_callout fails (i.e.

         * because the device is busy or the cmd is not

         * supported) we pretend all blocks are allocated

         * for backwards compatibility */

        error_report("iSCSI GET_LBA_STATUS failed at lba %" PRIu64 ": %s",

                     lba, iTask.err_str);

        goto out_unlock;

    }

    lbas = scsi_datain_unmarshall(iTask.task);

    if (lbas == NULL) {

        ret = -EIO;

        goto out_unlock;

    }

    lbasd = &lbas->descriptors[0];

    if (sector_qemu2lun(sector_num, iscsilun) != lbasd->lba) {

        ret = -EIO;

        goto out_unlock;

    }

    *pnum = sector_lun2qemu(lbasd->num_blocks, iscsilun);

    if (lbasd->provisioning == SCSI_PROVISIONING_TYPE_DEALLOCATED ||

        lbasd->provisioning == SCSI_PROVISIONING_TYPE_ANCHORED) {

        ret &= ~BDRV_BLOCK_DATA;

        if (iscsilun->lbprz) {

            ret |= BDRV_BLOCK_ZERO;

        }

    }

    if (ret & BDRV_BLOCK_ZERO) {

        iscsi_allocmap_set_unallocated(iscsilun, sector_num, *pnum);

    } else {

        iscsi_allocmap_set_allocated(iscsilun, sector_num, *pnum);

    }

    if (*pnum > nb_sectors) {

        *pnum = nb_sectors;

    }

out_unlock:

    qemu_mutex_unlock(&iscsilun->mutex);

    g_free(iTask.err_str);

out:

    if (iTask.task != NULL) {

        scsi_free_scsi_task(iTask.task);

    }

    if (ret > 0 && ret & BDRV_BLOCK_OFFSET_VALID) {

        *file = bs;

    }

    return ret;

}


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

                                int *got_frame, AVPacket *avpkt)

{

    uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    DVVideoContext *s = avctx->priv_data;

    const uint8_t *vsc_pack;

    int apt, is16_9, ret;

    const AVDVProfile *sys;

    sys = av_dv_frame_profile(s->sys, buf, buf_size);

    if (!sys || buf_size < sys->frame_size) {

        av_log(avctx, AV_LOG_ERROR, "could not find dv frame profile\n");

        return -1; /* NOTE: we only accept several full frames */

    }

    if (sys != s->sys) {

        ret = ff_dv_init_dynamic_tables(s, sys);

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "Error initializing the work tables.\n");

            return ret;

        }

        s->sys = sys;

    }

    s->frame            = data;

    s->frame->key_frame = 1;

    s->frame->pict_type = AV_PICTURE_TYPE_I;

    avctx->pix_fmt      = s->sys->pix_fmt;

    avctx->framerate    = av_inv_q(s->sys->time_base);

    ret = ff_set_dimensions(avctx, s->sys->width, s->sys->height);

    if (ret < 0)

        return ret;

    /* Determine the codec's sample_aspect ratio from the packet */

    vsc_pack = buf + 80 * 5 + 48 + 5;

    if (*vsc_pack == dv_video_control) {

        apt    = buf[4] & 0x07;

        is16_9 = (vsc_pack && ((vsc_pack[2] & 0x07) == 0x02 ||

                               (!apt && (vsc_pack[2] & 0x07) == 0x07)));

        ff_set_sar(avctx, s->sys->sar[is16_9]);

    }

    if (ff_get_buffer(avctx, s->frame, 0) < 0) {

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

        return -1;

    }

    s->frame->interlaced_frame = 1;

    s->frame->top_field_first  = 0;

    s->buf = buf;

    avctx->execute(avctx, dv_decode_video_segment, s->work_chunks, NULL,

                   dv_work_pool_size(s->sys), sizeof(DVwork_chunk));

    emms_c();

    /* return image */

    *got_frame = 1;

    return s->sys->frame_size;

}


static int inc_refcounts(BlockDriverState *bs,

                          uint16_t *refcount_table,

                          int refcount_table_size,

                          int64_t offset, int64_t size)

{

    BDRVQcowState *s = bs->opaque;

    int64_t start, last, cluster_offset;

    int k;

    int errors = 0;

    if (size <= 0)

        return 0;

    start = offset & ~(s->cluster_size - 1);

    last = (offset + size - 1) & ~(s->cluster_size - 1);

    for(cluster_offset = start; cluster_offset <= last;

        cluster_offset += s->cluster_size) {

        k = cluster_offset >> s->cluster_bits;

        if (k < 0 || k >= refcount_table_size) {

            fprintf(stderr, "ERROR: invalid cluster offset=0x%" PRIx64 "\n",

                cluster_offset);

            errors++;

        } else {

            if (++refcount_table[k] == 0) {

                fprintf(stderr, "ERROR: overflow cluster offset=0x%" PRIx64

                    "\n", cluster_offset);

                errors++;

            }

        }

    }

    return errors;

}