static void virtio_ccw_device_realize(VirtioCcwDevice *dev, Error **errp)

{

    VirtIOCCWDeviceClass *k = VIRTIO_CCW_DEVICE_GET_CLASS(dev);

    CcwDevice *ccw_dev = CCW_DEVICE(dev);

    CCWDeviceClass *ck = CCW_DEVICE_GET_CLASS(ccw_dev);

    DeviceState *parent = DEVICE(ccw_dev);

    BusState *qbus = qdev_get_parent_bus(parent);

    VirtualCssBus *cbus = VIRTUAL_CSS_BUS(qbus);

    SubchDev *sch;

    Error *err = NULL;

    sch = css_create_sch(ccw_dev->devno, true, cbus->squash_mcss, errp);

    if (!sch) {

        return;

    }

    if (!virtio_ccw_rev_max(dev) && dev->force_revision_1) {

        error_setg(&err, "Invalid value of property max_rev "

                   "(is %d expected >= 1)", virtio_ccw_rev_max(dev));

        goto out_err;

    }

    sch->driver_data = dev;

    sch->ccw_cb = virtio_ccw_cb;

    sch->disable_cb = virtio_sch_disable_cb;

    sch->id.reserved = 0xff;

    sch->id.cu_type = VIRTIO_CCW_CU_TYPE;

    sch->do_subchannel_work = do_subchannel_work_virtual;

    ccw_dev->sch = sch;

    dev->indicators = NULL;

    dev->revision = -1;

    css_sch_build_virtual_schib(sch, 0, VIRTIO_CCW_CHPID_TYPE);

    trace_virtio_ccw_new_device(

        sch->cssid, sch->ssid, sch->schid, sch->devno,

        ccw_dev->devno.valid ? "user-configured" : "auto-configured");

    if (!kvm_eventfds_enabled()) {

        dev->flags &= ~VIRTIO_CCW_FLAG_USE_IOEVENTFD;

    }

    if (k->realize) {

        k->realize(dev, &err);

        if (err) {

            goto out_err;

        }

    }

    ck->realize(ccw_dev, &err);

    if (err) {

        goto out_err;

    }

    return;

out_err:

    error_propagate(errp, err);

    css_subch_assign(sch->cssid, sch->ssid, sch->schid, sch->devno, NULL);

    ccw_dev->sch = NULL;

    g_free(sch);

}


static void virtio_balloon_to_target(void *opaque, ram_addr_t target,

                                     MonitorCompletion cb, void *cb_data)

{

    VirtIOBalloon *dev = opaque;

    if (target > ram_size) {

        target = ram_size;

    }

    if (target) {

        dev->num_pages = (ram_size - target) >> VIRTIO_BALLOON_PFN_SHIFT;

        virtio_notify_config(&dev->vdev);

    } else {

        virtio_balloon_stat(opaque, cb, cb_data);

    }

}


void helper_rsm(CPUX86State *env)
{
    X86CPU *cpu = x86_env_get_cpu(env);
    CPUState *cs = CPU(cpu);
    target_ulong sm_state;
    int i, offset;
    uint32_t val;
    sm_state = env->smbase + 0x8000;
#ifdef TARGET_X86_64
    cpu_load_efer(env, x86_ldq_phys(cs, sm_state + 0x7ed0));
    env->gdt.base = x86_ldq_phys(cs, sm_state + 0x7e68);
    env->gdt.limit = x86_ldl_phys(cs, sm_state + 0x7e64);
    env->ldt.selector = x86_lduw_phys(cs, sm_state + 0x7e70);
    env->ldt.base = x86_ldq_phys(cs, sm_state + 0x7e78);
    env->ldt.limit = x86_ldl_phys(cs, sm_state + 0x7e74);
    env->ldt.flags = (x86_lduw_phys(cs, sm_state + 0x7e72) & 0xf0ff) << 8;
    env->idt.base = x86_ldq_phys(cs, sm_state + 0x7e88);
    env->idt.limit = x86_ldl_phys(cs, sm_state + 0x7e84);
    env->tr.selector = x86_lduw_phys(cs, sm_state + 0x7e90);
    env->tr.base = x86_ldq_phys(cs, sm_state + 0x7e98);
    env->tr.limit = x86_ldl_phys(cs, sm_state + 0x7e94);
    env->tr.flags = (x86_lduw_phys(cs, sm_state + 0x7e92) & 0xf0ff) << 8;
    env->regs[R_EAX] = x86_ldq_phys(cs, sm_state + 0x7ff8);
    env->regs[R_ECX] = x86_ldq_phys(cs, sm_state + 0x7ff0);
    env->regs[R_EDX] = x86_ldq_phys(cs, sm_state + 0x7fe8);
    env->regs[R_EBX] = x86_ldq_phys(cs, sm_state + 0x7fe0);
    env->regs[R_ESP] = x86_ldq_phys(cs, sm_state + 0x7fd8);
    env->regs[R_EBP] = x86_ldq_phys(cs, sm_state + 0x7fd0);
    env->regs[R_ESI] = x86_ldq_phys(cs, sm_state + 0x7fc8);
    env->regs[R_EDI] = x86_ldq_phys(cs, sm_state + 0x7fc0);
    for (i = 8; i < 16; i++) {
        env->regs[i] = x86_ldq_phys(cs, sm_state + 0x7ff8 - i * 8);
    }
    env->eip = x86_ldq_phys(cs, sm_state + 0x7f78);
    cpu_load_eflags(env, x86_ldl_phys(cs, sm_state + 0x7f70),
                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
    env->dr[6] = x86_ldl_phys(cs, sm_state + 0x7f68);
    env->dr[7] = x86_ldl_phys(cs, sm_state + 0x7f60);
    cpu_x86_update_cr4(env, x86_ldl_phys(cs, sm_state + 0x7f48));
    cpu_x86_update_cr3(env, x86_ldq_phys(cs, sm_state + 0x7f50));
    cpu_x86_update_cr0(env, x86_ldl_phys(cs, sm_state + 0x7f58));
    for (i = 0; i < 6; i++) {
        offset = 0x7e00 + i * 16;
        cpu_x86_load_seg_cache(env, i,
                               x86_lduw_phys(cs, sm_state + offset),
                               x86_ldq_phys(cs, sm_state + offset + 8),
                               x86_ldl_phys(cs, sm_state + offset + 4),
                               (x86_lduw_phys(cs, sm_state + offset + 2) &
                                0xf0ff) << 8);
    }
    val = x86_ldl_phys(cs, sm_state + 0x7efc); /* revision ID */
    if (val & 0x20000) {
        env->smbase = x86_ldl_phys(cs, sm_state + 0x7f00);
    }
#else
    cpu_x86_update_cr0(env, x86_ldl_phys(cs, sm_state + 0x7ffc));
    cpu_x86_update_cr3(env, x86_ldl_phys(cs, sm_state + 0x7ff8));
    cpu_load_eflags(env, x86_ldl_phys(cs, sm_state + 0x7ff4),
                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
    env->eip = x86_ldl_phys(cs, sm_state + 0x7ff0);
    env->regs[R_EDI] = x86_ldl_phys(cs, sm_state + 0x7fec);
    env->regs[R_ESI] = x86_ldl_phys(cs, sm_state + 0x7fe8);
    env->regs[R_EBP] = x86_ldl_phys(cs, sm_state + 0x7fe4);
    env->regs[R_ESP] = x86_ldl_phys(cs, sm_state + 0x7fe0);
    env->regs[R_EBX] = x86_ldl_phys(cs, sm_state + 0x7fdc);
    env->regs[R_EDX] = x86_ldl_phys(cs, sm_state + 0x7fd8);
    env->regs[R_ECX] = x86_ldl_phys(cs, sm_state + 0x7fd4);
    env->regs[R_EAX] = x86_ldl_phys(cs, sm_state + 0x7fd0);
    env->dr[6] = x86_ldl_phys(cs, sm_state + 0x7fcc);
    env->dr[7] = x86_ldl_phys(cs, sm_state + 0x7fc8);
    env->tr.selector = x86_ldl_phys(cs, sm_state + 0x7fc4) & 0xffff;
    env->tr.base = x86_ldl_phys(cs, sm_state + 0x7f64);
    env->tr.limit = x86_ldl_phys(cs, sm_state + 0x7f60);
    env->tr.flags = (x86_ldl_phys(cs, sm_state + 0x7f5c) & 0xf0ff) << 8;
    env->ldt.selector = x86_ldl_phys(cs, sm_state + 0x7fc0) & 0xffff;
    env->ldt.base = x86_ldl_phys(cs, sm_state + 0x7f80);
    env->ldt.limit = x86_ldl_phys(cs, sm_state + 0x7f7c);
    env->ldt.flags = (x86_ldl_phys(cs, sm_state + 0x7f78) & 0xf0ff) << 8;
    env->gdt.base = x86_ldl_phys(cs, sm_state + 0x7f74);
    env->gdt.limit = x86_ldl_phys(cs, sm_state + 0x7f70);
    env->idt.base = x86_ldl_phys(cs, sm_state + 0x7f58);
    env->idt.limit = x86_ldl_phys(cs, sm_state + 0x7f54);
    for (i = 0; i < 6; i++) {
        if (i < 3) {
            offset = 0x7f84 + i * 12;
        } else {
            offset = 0x7f2c + (i - 3) * 12;
        }
        cpu_x86_load_seg_cache(env, i,
                               x86_ldl_phys(cs,
                                        sm_state + 0x7fa8 + i * 4) & 0xffff,
                               x86_ldl_phys(cs, sm_state + offset + 8),
                               x86_ldl_phys(cs, sm_state + offset + 4),
                               (x86_ldl_phys(cs,
                                         sm_state + offset) & 0xf0ff) << 8);
    }
    cpu_x86_update_cr4(env, x86_ldl_phys(cs, sm_state + 0x7f14));
    val = x86_ldl_phys(cs, sm_state + 0x7efc); /* revision ID */
    if (val & 0x20000) {
        env->smbase = x86_ldl_phys(cs, sm_state + 0x7ef8);
    }
#endif
    if ((env->hflags2 & HF2_SMM_INSIDE_NMI_MASK) == 0) {
        env->hflags2 &= ~HF2_NMI_MASK;
    }
    env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
    env->hflags &= ~HF_SMM_MASK;
    cpu_smm_update(cpu);
    qemu_log_mask(CPU_LOG_INT, "SMM: after RSM\n");
    log_cpu_state_mask(CPU_LOG_INT, CPU(cpu), CPU_DUMP_CCOP);
}


bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)

{

    int i;

    for (i = 0; i < qiov->niov; i++) {

        if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {

            return false;

        }

        if (qiov->iov[i].iov_len % bs->buffer_alignment) {

            return false;

        }

    }

    return true;

}


static int read_key(void)

{

#if HAVE_TERMIOS_H

    int n = 1;

    unsigned char ch;

    struct timeval tv;

    fd_set rfds;

    FD_ZERO(&rfds);

    FD_SET(0, &rfds);

    tv.tv_sec = 0;

    tv.tv_usec = 0;

    n = select(1, &rfds, NULL, NULL, &tv);

    if (n > 0) {

        n = read(0, &ch, 1);

        if (n == 1)

            return ch;

        return n;

    }

#elif HAVE_CONIO_H

    if(kbhit())

        return(getch());

#endif

    return -1;

}


int main(int argc, char *argv[])

{

    int fd_in, fd_out, comp_len, uncomp_len, i, last_out;

    char buf_in[1024], buf_out[65536];

    z_stream zstream;

    struct stat statbuf;

    if (argc < 3) {

        printf("Usage: %s <infile.swf> <outfile.swf>\n", argv[0]);

        return 1;

    }

    fd_in = open(argv[1], O_RDONLY);

    if (fd_in < 0) {

        perror("Error opening input file");

        return 1;

    }

    fd_out = open(argv[2], O_WRONLY | O_CREAT, 00644);

    if (fd_out < 0) {

        perror("Error opening output file");

        close(fd_in);

        return 1;

    }

    if (read(fd_in, &buf_in, 8) != 8) {

        printf("Header error\n");

        close(fd_in);

        close(fd_out);

        return 1;

    }

    if (buf_in[0] != 'C' || buf_in[1] != 'W' || buf_in[2] != 'S') {

        printf("Not a compressed flash file\n");

        return 1;

    }

    fstat(fd_in, &statbuf);

    comp_len   = statbuf.st_size;

    uncomp_len = buf_in[4] | (buf_in[5] << 8) | (buf_in[6] << 16) | (buf_in[7] << 24);

    printf("Compressed size: %d Uncompressed size: %d\n",

           comp_len - 4, uncomp_len - 4);

    // write out modified header

    buf_in[0] = 'F';

    if (write(fd_out, &buf_in, 8) < 8) {

        perror("Error writing output file");

        return 1;

    }

    zstream.zalloc = NULL;

    zstream.zfree  = NULL;

    zstream.opaque = NULL;

    if (inflateInit(&zstream) != Z_OK) {

        fprintf(stderr, "inflateInit failed\n");

        return 1;

    }

    for (i = 0; i < comp_len - 8;) {

        int ret, len = read(fd_in, &buf_in, 1024);

        dbgprintf("read %d bytes\n", len);

        last_out = zstream.total_out;

        zstream.next_in   = &buf_in[0];

        zstream.avail_in  = len;

        zstream.next_out  = &buf_out[0];

        zstream.avail_out = 65536;

        ret = inflate(&zstream, Z_SYNC_FLUSH);

        if (ret != Z_STREAM_END && ret != Z_OK) {

            printf("Error while decompressing: %d\n", ret);

            inflateEnd(&zstream);

            return 1;

        }

        dbgprintf("a_in: %d t_in: %lu a_out: %d t_out: %lu -- %lu out\n",

                  zstream.avail_in, zstream.total_in, zstream.avail_out,

                  zstream.total_out, zstream.total_out - last_out);

        if (write(fd_out, &buf_out, zstream.total_out - last_out) <

            zstream.total_out - last_out) {

            perror("Error writing output file");

            return 1;

        }

        i += len;

        if (ret == Z_STREAM_END || ret == Z_BUF_ERROR)

            break;

    }

    if (zstream.total_out != uncomp_len - 8) {

        printf("Size mismatch (%lu != %d), updating header...\n",

               zstream.total_out, uncomp_len - 8);

        buf_in[0] =  (zstream.total_out + 8)        & 0xff;

        buf_in[1] = ((zstream.total_out + 8) >>  8) & 0xff;

        buf_in[2] = ((zstream.total_out + 8) >> 16) & 0xff;

        buf_in[3] = ((zstream.total_out + 8) >> 24) & 0xff;

        if (   lseek(fd_out, 4, SEEK_SET) < 0

            || write(fd_out, &buf_in, 4) < 4) {

            perror("Error writing output file");

            return 1;

        }

    }

    inflateEnd(&zstream);

    close(fd_in);

    close(fd_out);

    return 0;

}


static void os_host_main_loop_wait(int *timeout)

{

    int ret, ret2, i;

    PollingEntry *pe;

    /* XXX: need to suppress polling by better using win32 events */

    ret = 0;

    for (pe = first_polling_entry; pe != NULL; pe = pe->next) {

        ret |= pe->func(pe->opaque);

    }

    if (ret == 0) {

        int err;

        WaitObjects *w = &wait_objects;

        qemu_mutex_unlock_iothread();

        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);

        qemu_mutex_lock_iothread();

        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {

            if (w->func[ret - WAIT_OBJECT_0]) {

                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);

            }

            /* Check for additional signaled events */

            for (i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {

                /* Check if event is signaled */

                ret2 = WaitForSingleObject(w->events[i], 0);

                if (ret2 == WAIT_OBJECT_0) {

                    if (w->func[i]) {

                        w->func[i](w->opaque[i]);

                    }

                } else if (ret2 != WAIT_TIMEOUT) {

                    err = GetLastError();

                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);

                }

            }

        } else if (ret != WAIT_TIMEOUT) {

            err = GetLastError();

            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);

        }

    }

    *timeout = 0;

}


static int v9fs_synth_get_dentry(V9fsSynthNode *dir, struct dirent *entry,

                                 struct dirent **result, off_t off)

{

    int i = 0;

    V9fsSynthNode *node;

    rcu_read_lock();

    QLIST_FOREACH(node, &dir->child, sibling) {

        /* This is the off child of the directory */

        if (i == off) {

            break;

        }

        i++;

    }

    rcu_read_unlock();

    if (!node) {

        /* end of directory */

        *result = NULL;

        return 0;

    }

    v9fs_synth_direntry(node, entry, off);

    *result = entry;

    return 0;

}


int float32_lt_quiet( float32 a, float32 b STATUS_PARAM )

{

    flag aSign, bSign;

    if (    ( ( extractFloat32Exp( a ) == 0xFF ) && extractFloat32Frac( a ) )

         || ( ( extractFloat32Exp( b ) == 0xFF ) && extractFloat32Frac( b ) )

       ) {

        if ( float32_is_signaling_nan( a ) || float32_is_signaling_nan( b ) ) {

            float_raise( float_flag_invalid STATUS_VAR);

        }

        return 0;

    }

    aSign = extractFloat32Sign( a );

    bSign = extractFloat32Sign( b );

    if ( aSign != bSign ) return aSign && ( (bits32) ( ( a | b )<<1 ) != 0 );

    return ( a != b ) && ( aSign ^ ( a < b ) );

}


static void utf8_string(void)

{

    /*

     * FIXME Current behavior for invalid UTF-8 sequences is

     * incorrect.  This test expects current, incorrect results.

     * They're all marked "bug:" below, and are to be replaced by

     * correct ones as the bugs get fixed.

     *

     * The JSON parser rejects some invalid sequences, but accepts

     * others without correcting the problem.

     *

     * The JSON formatter replaces some invalid sequences by U+FFFF (a

     * noncharacter), and goes wonky for others.

     *

     * For both directions, we should either reject all invalid

     * sequences, or minimize overlong sequences and replace all other

     * invalid sequences by a suitable replacement character.  A

     * common choice for replacement is U+FFFD.

     *

     * Problem: we can't easily deal with embedded U+0000.  Parsing

     * the JSON string "this \\u0000" is fun" yields "this \0 is fun",

     * which gets misinterpreted as NUL-terminated "this ".  We should

     * consider using overlong encoding \xC0\x80 for U+0000 ("modified

     * UTF-8").

     *

     * Test cases are scraped from Markus Kuhn's UTF-8 decoder

     * capability and stress test at

     * http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt

     */

    static const struct {

        const char *json_in;

        const char *utf8_out;

        const char *json_out;   /* defaults to @json_in */

        const char *utf8_in;    /* defaults to @utf8_out */

    } test_cases[] = {

        /*

         * Bug markers used here:

         * - bug: not corrected

         *   JSON parser fails to correct invalid sequence(s)

         * - bug: rejected

         *   JSON parser rejects invalid sequence(s)

         *   We may choose to define this as feature

         * - bug: want "\"...\""

         *   JSON formatter produces incorrect result, this is the

         *   correct one, assuming replacement character U+FFFF

         * - bug: want "..." (no \")

         *   JSON parser produces incorrect result, this is the

         *   correct one, assuming replacement character U+FFFF

         *   We may choose to reject instead of replace

         * Not marked explicitly, but trivial to find:

         * - JSON formatter replacing invalid sequence by \\uFFFF is a

         *   bug if we want it to fail for invalid sequences.

         */

        /* 1  Some correct UTF-8 text */

        {

            /* a bit of German */

            "\"Falsches \xC3\x9C" "ben von Xylophonmusik qu\xC3\xA4lt"

            " jeden gr\xC3\xB6\xC3\x9F" "eren Zwerg.\"",

            "Falsches \xC3\x9C" "ben von Xylophonmusik qu\xC3\xA4lt"

            " jeden gr\xC3\xB6\xC3\x9F" "eren Zwerg.",

            "\"Falsches \\u00DCben von Xylophonmusik qu\\u00E4lt"

            " jeden gr\\u00F6\\u00DFeren Zwerg.\"",

        },

        {

            /* a bit of Greek */

            "\"\xCE\xBA\xE1\xBD\xB9\xCF\x83\xCE\xBC\xCE\xB5\"",

            "\xCE\xBA\xE1\xBD\xB9\xCF\x83\xCE\xBC\xCE\xB5",

            "\"\\u03BA\\u1F79\\u03C3\\u03BC\\u03B5\"",

        },

        /* 2  Boundary condition test cases */

        /* 2.1  First possible sequence of a certain length */

        /* 2.1.1  1 byte U+0000 */

        {

            "\"\\u0000\"",

            "",                 /* bug: want overlong "\xC0\x80" */

            "\"\"",             /* bug: want "\"\\u0000\"" */

        },

        /* 2.1.2  2 bytes U+0080 */

        {

            "\"\xC2\x80\"",

            "\xC2\x80",

            "\"\\u0080\"",

        },

        /* 2.1.3  3 bytes U+0800 */

        {

            "\"\xE0\xA0\x80\"",

            "\xE0\xA0\x80",

            "\"\\u0800\"",

        },

        /* 2.1.4  4 bytes U+10000 */

        {

            "\"\xF0\x90\x80\x80\"",

            "\xF0\x90\x80\x80",

            "\"\\u0400\\uFFFF\"", /* bug: want "\"\\uD800\\uDC00\"" */

        },

        /* 2.1.5  5 bytes U+200000 */

        {

            "\"\xF8\x88\x80\x80\x80\"",

            NULL,                        /* bug: rejected */

            "\"\\u8200\\uFFFF\\uFFFF\"", /* bug: want "\"\\uFFFF\"" */

            "\xF8\x88\x80\x80\x80",

        },

        /* 2.1.6  6 bytes U+4000000 */

        {

            "\"\xFC\x84\x80\x80\x80\x80\"",

            NULL,                               /* bug: rejected */

            "\"\\uC100\\uFFFF\\uFFFF\\uFFFF\"", /* bug: want "\"\\uFFFF\"" */

            "\xFC\x84\x80\x80\x80\x80",

        },

        /* 2.2  Last possible sequence of a certain length */

        /* 2.2.1  1 byte U+007F */

        {

            "\"\x7F\"",

            "\x7F",

            "\"\177\"",

        },

        /* 2.2.2  2 bytes U+07FF */

        {

            "\"\xDF\xBF\"",

            "\xDF\xBF",

            "\"\\u07FF\"",

        },

        /* 2.2.3  3 bytes U+FFFF */

        {

            "\"\xEF\xBF\xBF\"",

            "\xEF\xBF\xBF",

            "\"\\uFFFF\"",

        },

        /* 2.2.4  4 bytes U+1FFFFF */

        {

            "\"\xF7\xBF\xBF\xBF\"",

            NULL,                 /* bug: rejected */

            "\"\\u7FFF\\uFFFF\"", /* bug: want "\"\\uFFFF\"" */

            "\xF7\xBF\xBF\xBF",

        },

        /* 2.2.5  5 bytes U+3FFFFFF */

        {

            "\"\xFB\xBF\xBF\xBF\xBF\"",

            NULL,                        /* bug: rejected */

            "\"\\uBFFF\\uFFFF\\uFFFF\"", /* bug: want "\"\\uFFFF\"" */

            "\xFB\xBF\xBF\xBF\xBF",

        },

        /* 2.2.6  6 bytes U+7FFFFFFF */

        {

            "\"\xFD\xBF\xBF\xBF\xBF\xBF\"",

            NULL,                               /* bug: rejected */

            "\"\\uDFFF\\uFFFF\\uFFFF\\uFFFF\"", /* bug: want "\"\\uFFFF\"" */

            "\xFD\xBF\xBF\xBF\xBF\xBF",

        },

        /* 2.3  Other boundary conditions */

        {

            /* U+D7FF */

            "\"\xED\x9F\xBF\"",

            "\xED\x9F\xBF",

            "\"\\uD7FF\"",

        },

        {

            /* U+E000 */

            "\"\xEE\x80\x80\"",

            "\xEE\x80\x80",

            "\"\\uE000\"",

        },

        {

            /* U+FFFD */

            "\"\xEF\xBF\xBD\"",

            "\xEF\xBF\xBD",

            "\"\\uFFFD\"",

        },

        {

            /* U+10FFFF */

            "\"\xF4\x8F\xBF\xBF\"",

            "\xF4\x8F\xBF\xBF",

            "\"\\u43FF\\uFFFF\"", /* bug: want "\"\\uDBFF\\uDFFF\"" */

        },

        {

            /* U+110000 */

            "\"\xF4\x90\x80\x80\"",

            "\xF4\x90\x80\x80",

            "\"\\u4400\\uFFFF\"", /* bug: want "\"\\uFFFF\"" */

        },

        /* 3  Malformed sequences */

        /* 3.1  Unexpected continuation bytes */

        /* 3.1.1  First continuation byte */

        {

            "\"\x80\"",

            "\x80",             /* bug: not corrected */

            "\"\\uFFFF\"",

        },

        /* 3.1.2  Last continuation byte */

        {

            "\"\xBF\"",

            "\xBF",             /* bug: not corrected */

            "\"\\uFFFF\"",

        },

        /* 3.1.3  2 continuation bytes */

        {

            "\"\x80\xBF\"",

            "\x80\xBF",         /* bug: not corrected */

            "\"\\uFFFF\\uFFFF\"",

        },

        /* 3.1.4  3 continuation bytes */

        {

            "\"\x80\xBF\x80\"",

            "\x80\xBF\x80",     /* bug: not corrected */

            "\"\\uFFFF\\uFFFF\\uFFFF\"",

        },

        /* 3.1.5  4 continuation bytes */

        {

            "\"\x80\xBF\x80\xBF\"",

            "\x80\xBF\x80\xBF", /* bug: not corrected */

            "\"\\uFFFF\\uFFFF\\uFFFF\\uFFFF\"",

        },

        /* 3.1.6  5 continuation bytes */

        {

            "\"\x80\xBF\x80\xBF\x80\"",

            "\x80\xBF\x80\xBF\x80", /* bug: not corrected */

            "\"\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\"",

        },

        /* 3.1.7  6 continuation bytes */

        {

            "\"\x80\xBF\x80\xBF\x80\xBF\"",

            "\x80\xBF\x80\xBF\x80\xBF", /* bug: not corrected */

            "\"\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\"",

        },

        /* 3.1.8  7 continuation bytes */

        {

            "\"\x80\xBF\x80\xBF\x80\xBF\x80\"",

            "\x80\xBF\x80\xBF\x80\xBF\x80", /* bug: not corrected */

            "\"\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\"",

        },

        /* 3.1.9  Sequence of all 64 possible continuation bytes */

        {

            "\"\x80\x81\x82\x83\x84\x85\x86\x87"

            "\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F"

            "\x90\x91\x92\x93\x94\x95\x96\x97"

            "\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F"

            "\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7"

            "\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF"

            "\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7"

            "\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\"",

             /* bug: not corrected */

            "\x80\x81\x82\x83\x84\x85\x86\x87"

            "\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F"

            "\x90\x91\x92\x93\x94\x95\x96\x97"

            "\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F"

            "\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7"

            "\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF"

            "\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7"

            "\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF",

            "\"\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF"

            "\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF"

            "\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF"

            "\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF"

            "\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF"

            "\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF"

            "\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF"

            "\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\""

        },

        /* 3.2  Lonely start characters */

        /* 3.2.1  All 32 first bytes of 2-byte sequences, followed by space */

        {

            "\"\xC0 \xC1 \xC2 \xC3 \xC4 \xC5 \xC6 \xC7 "

            "\xC8 \xC9 \xCA \xCB \xCC \xCD \xCE \xCF "

            "\xD0 \xD1 \xD2 \xD3 \xD4 \xD5 \xD6 \xD7 "

            "\xD8 \xD9 \xDA \xDB \xDC \xDD \xDE \xDF \"",

            NULL,               /* bug: rejected */

            "\"\\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF "

            "\\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF "

            "\\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF "

            "\\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \"",

            "\xC0 \xC1 \xC2 \xC3 \xC4 \xC5 \xC6 \xC7 "

            "\xC8 \xC9 \xCA \xCB \xCC \xCD \xCE \xCF "

            "\xD0 \xD1 \xD2 \xD3 \xD4 \xD5 \xD6 \xD7 "

            "\xD8 \xD9 \xDA \xDB \xDC \xDD \xDE \xDF ",

        },

        /* 3.2.2  All 16 first bytes of 3-byte sequences, followed by space */

        {

            "\"\xE0 \xE1 \xE2 \xE3 \xE4 \xE5 \xE6 \xE7 "

            "\xE8 \xE9 \xEA \xEB \xEC \xED \xEE \xEF \"",

            /* bug: not corrected */

            "\xE0 \xE1 \xE2 \xE3 \xE4 \xE5 \xE6 \xE7 "

            "\xE8 \xE9 \xEA \xEB \xEC \xED \xEE \xEF ",

            "\"\\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF "

            "\\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \"",

        },

        /* 3.2.3  All 8 first bytes of 4-byte sequences, followed by space */

        {

            "\"\xF0 \xF1 \xF2 \xF3 \xF4 \xF5 \xF6 \xF7 \"",

            NULL,               /* bug: rejected */

            "\"\\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \\uFFFF \"",

            "\xF0 \xF1 \xF2 \xF3 \xF4 \xF5 \xF6 \xF7 ",

        },

        /* 3.2.4  All 4 first bytes of 5-byte sequences, followed by space */

        {

            "\"\xF8 \xF9 \xFA \xFB \"",

            NULL,               /* bug: rejected */

            "\"\\uFFFF \\uFFFF \\uFFFF \\uFFFF \"",

            "\xF8 \xF9 \xFA \xFB ",

        },

        /* 3.2.5  All 2 first bytes of 6-byte sequences, followed by space */

        {

            "\"\xFC \xFD \"",

            NULL,               /* bug: rejected */

            "\"\\uFFFF \\uFFFF \"",

            "\xFC \xFD ",

        },

        /* 3.3  Sequences with last continuation byte missing */

        /* 3.3.1  2-byte sequence with last byte missing (U+0000) */

        {

            "\"\xC0\"",

            NULL,               /* bug: rejected */

            "\"\\uFFFF\"",

            "\xC0",

        },

        /* 3.3.2  3-byte sequence with last byte missing (U+0000) */

        {

            "\"\xE0\x80\"",

            "\xE0\x80",           /* bug: not corrected */

            "\"\\uFFFF\\uFFFF\"", /* bug: want "\"\\uFFFF\"" */

        },

        /* 3.3.3  4-byte sequence with last byte missing (U+0000) */

        {

            "\"\xF0\x80\x80\"",

            "\xF0\x80\x80",     /* bug: not corrected */

            "\"\\u0000\"",      /* bug: want "\"\\uFFFF\"" */

        },

        /* 3.3.4  5-byte sequence with last byte missing (U+0000) */

        {

            /* invalid */

            "\"\xF8\x80\x80\x80\"", /* bug: not corrected */

            NULL,                   /* bug: rejected */

            "\"\\u8000\\uFFFF\"",   /* bug: want "\"\\uFFFF\"" */

            "\xF8\x80\x80\x80",

        },

        /* 3.3.5  6-byte sequence with last byte missing (U+0000) */

        {

            "\"\xFC\x80\x80\x80\x80\"",

            NULL,                        /* bug: rejected */

            "\"\\uC000\\uFFFF\\uFFFF\"", /* bug: want "\"\\uFFFF\"" */

            "\xFC\x80\x80\x80\x80",

        },

        /* 3.3.6  2-byte sequence with last byte missing (U+07FF) */

        {

            "\"\xDF\"",

            "\xDF",             /* bug: not corrected */

            "\"\\uFFFF\"",

        },

        /* 3.3.7  3-byte sequence with last byte missing (U+FFFF) */

        {

            "\"\xEF\xBF\"",

            "\xEF\xBF",           /* bug: not corrected */

            "\"\\uFFFF\\uFFFF\"", /* bug: want "\"\\uFFFF\"" */

        },

        /* 3.3.8  4-byte sequence with last byte missing (U+1FFFFF) */

        {

            "\"\xF7\xBF\xBF\"",

            NULL,               /* bug: rejected */

            "\"\\u7FFF\"",      /* bug: want "\"\\uFFFF\"" */

            "\xF7\xBF\xBF",

        },

        /* 3.3.9  5-byte sequence with last byte missing (U+3FFFFFF) */

        {

            "\"\xFB\xBF\xBF\xBF\"",

            NULL,                 /* bug: rejected */

            "\"\\uBFFF\\uFFFF\"", /* bug: want "\"\\uFFFF\"" */

            "\xFB\xBF\xBF\xBF",

        },

        /* 3.3.10  6-byte sequence with last byte missing (U+7FFFFFFF) */

        {

            "\"\xFD\xBF\xBF\xBF\xBF\"",

            NULL,                        /* bug: rejected */

            "\"\\uDFFF\\uFFFF\\uFFFF\"", /* bug: want "\"\\uFFFF\"", */

            "\xFD\xBF\xBF\xBF\xBF",

        },

        /* 3.4  Concatenation of incomplete sequences */

        {

            "\"\xC0\xE0\x80\xF0\x80\x80\xF8\x80\x80\x80\xFC\x80\x80\x80\x80"

            "\xDF\xEF\xBF\xF7\xBF\xBF\xFB\xBF\xBF\xBF\xFD\xBF\xBF\xBF\xBF\"",

            NULL,               /* bug: rejected */

            /* bug: want "\"\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF"

               "\\uFFFF\\uFFFF\\uFFFF\\uFFFF\\uFFFF\"" */

            "\"\\u0020\\uFFFF\\u0000\\u8000\\uFFFF\\uC000\\uFFFF\\uFFFF"

            "\\u07EF\\uFFFF\\u7FFF\\uBFFF\\uFFFF\\uDFFF\\uFFFF\\uFFFF\"",

            "\xC0\xE0\x80\xF0\x80\x80\xF8\x80\x80\x80\xFC\x80\x80\x80\x80"

            "\xDF\xEF\xBF\xF7\xBF\xBF\xFB\xBF\xBF\xBF\xFD\xBF\xBF\xBF\xBF",

        },

        /* 3.5  Impossible bytes */

        {

            "\"\xFE\"",

            NULL,               /* bug: rejected */

            "\"\\uFFFF\"",

            "\xFE",

        },

        {

            "\"\xFF\"",

            NULL,               /* bug: rejected */

            "\"\\uFFFF\"",

            "\xFF",

        },

        {

            "\"\xFE\xFE\xFF\xFF\"",

            NULL,                 /* bug: rejected */

            /* bug: want "\"\\uFFFF\\uFFFF\\uFFFF\\uFFFF\"" */

            "\"\\uEFBF\\uFFFF\"",

            "\xFE\xFE\xFF\xFF",

        },

        /* 4  Overlong sequences */

        /* 4.1  Overlong '/' */

        {

            "\"\xC0\xAF\"",

            NULL,               /* bug: rejected */

            "\"\\u002F\"",      /* bug: want "\"/\"" */

            "\xC0\xAF",

        },

        {

            "\"\xE0\x80\xAF\"",

            "\xE0\x80\xAF",     /* bug: not corrected */

            "\"\\u002F\"",      /* bug: want "\"/\"" */

        },

        {

            "\"\xF0\x80\x80\xAF\"",

            "\xF0\x80\x80\xAF",  /* bug: not corrected */

            "\"\\u0000\\uFFFF\"" /* bug: want "\"/\"" */

        },

        {

            "\"\xF8\x80\x80\x80\xAF\"",

            NULL,                        /* bug: rejected */

            "\"\\u8000\\uFFFF\\uFFFF\"", /* bug: want "\"/\"" */

            "\xF8\x80\x80\x80\xAF",

        },

        {

            "\"\xFC\x80\x80\x80\x80\xAF\"",

            NULL,                               /* bug: rejected */

            "\"\\uC000\\uFFFF\\uFFFF\\uFFFF\"", /* bug: want "\"/\"" */

            "\xFC\x80\x80\x80\x80\xAF",

        },

        /* 4.2  Maximum overlong sequences */

        {

            /* \U+007F */

            "\"\xC1\xBF\"",

            NULL,               /* bug: rejected */

            "\"\\u007F\"",      /* bug: want "\"\177\"" */

            "\xC1\xBF",

        },

        {

            /* \U+07FF */

            "\"\xE0\x9F\xBF\"",

            "\xE0\x9F\xBF",     /* bug: not corrected */

            "\"\\u07FF\"",

        },

        {

            /* \U+FFFF */

            "\"\xF0\x8F\xBF\xBF\"",

            "\xF0\x8F\xBF\xBF",   /* bug: not corrected */

            "\"\\u03FF\\uFFFF\"", /* bug: want "\"\\uFFFF\"" */

        },

        {

            /* \U+1FFFFF */

            "\"\xF8\x87\xBF\xBF\xBF\"",

            NULL,                        /* bug: rejected */

            "\"\\u81FF\\uFFFF\\uFFFF\"", /* bug: want "\"\\uFFFF\"" */

            "\xF8\x87\xBF\xBF\xBF",

        },

        {

            /* \U+3FFFFFF */

            "\"\xFC\x83\xBF\xBF\xBF\xBF\"",

            NULL,                               /* bug: rejected */

            "\"\\uC0FF\\uFFFF\\uFFFF\\uFFFF\"", /* bug: want "\"\\uFFFF\"" */

            "\xFC\x83\xBF\xBF\xBF\xBF",

        },

        /* 4.3  Overlong representation of the NUL character */

        {

            /* \U+0000 */

            "\"\xC0\x80\"",

            NULL,               /* bug: rejected */

            "\"\\u0000\"",

            "\xC0\x80",

        },

        {

            /* \U+0000 */

            "\"\xE0\x80\x80\"",

            "\xE0\x80\x80",     /* bug: not corrected */

            "\"\\u0000\"",

        },

        {

            /* \U+0000 */

            "\"\xF0\x80\x80\x80\"",

            "\xF0\x80\x80\x80",   /* bug: not corrected */

            "\"\\u0000\\uFFFF\"", /* bug: want "\"\\u0000\"" */

        },

        {

            /* \U+0000 */

            "\"\xF8\x80\x80\x80\x80\"",

            NULL,                        /* bug: rejected */

            "\"\\u8000\\uFFFF\\uFFFF\"", /* bug: want "\"\\u0000\"" */

            "\xF8\x80\x80\x80\x80",

        },

        {

            /* \U+0000 */

            "\"\xFC\x80\x80\x80\x80\x80\"",

            NULL,                               /* bug: rejected */

            "\"\\uC000\\uFFFF\\uFFFF\\uFFFF\"", /* bug: want "\"\\u0000\"" */

            "\xFC\x80\x80\x80\x80\x80",

        },

        /* 5  Illegal code positions */

        /* 5.1  Single UTF-16 surrogates */

        {

            /* \U+D800 */

            "\"\xED\xA0\x80\"",

            "\xED\xA0\x80",     /* bug: not corrected */

            "\"\\uD800\"",      /* bug: want "\"\\uFFFF\"" */

        },

        {

            /* \U+DB7F */

            "\"\xED\xAD\xBF\"",

            "\xED\xAD\xBF",     /* bug: not corrected */

            "\"\\uDB7F\"",      /* bug: want "\"\\uFFFF\"" */

        },

        {

            /* \U+DB80 */

            "\"\xED\xAE\x80\"",

            "\xED\xAE\x80",     /* bug: not corrected */

            "\"\\uDB80\"",      /* bug: want "\"\\uFFFF\"" */

        },

        {

            /* \U+DBFF */

            "\"\xED\xAF\xBF\"",

            "\xED\xAF\xBF",     /* bug: not corrected */

            "\"\\uDBFF\"",      /* bug: want "\"\\uFFFF\"" */

        },

        {

            /* \U+DC00 */

            "\"\xED\xB0\x80\"",

            "\xED\xB0\x80",     /* bug: not corrected */

            "\"\\uDC00\"",      /* bug: want "\"\\uFFFF\"" */

        },

        {

            /* \U+DF80 */

            "\"\xED\xBE\x80\"",

            "\xED\xBE\x80",     /* bug: not corrected */

            "\"\\uDF80\"",      /* bug: want "\"\\uFFFF\"" */

        },

        {

            /* \U+DFFF */

            "\"\xED\xBF\xBF\"",

            "\xED\xBF\xBF",     /* bug: not corrected */

            "\"\\uDFFF\"",      /* bug: want "\"\\uFFFF\"" */

        },

        /* 5.2  Paired UTF-16 surrogates */

        {

            /* \U+D800\U+DC00 */

            "\"\xED\xA0\x80\xED\xB0\x80\"",

            "\xED\xA0\x80\xED\xB0\x80", /* bug: not corrected */

            "\"\\uD800\\uDC00\"", /* bug: want "\"\\uFFFF\\uFFFF\"" */

        },

        {

            /* \U+D800\U+DFFF */

            "\"\xED\xA0\x80\xED\xBF\xBF\"",

            "\xED\xA0\x80\xED\xBF\xBF", /* bug: not corrected */

            "\"\\uD800\\uDFFF\"", /* bug: want "\"\\uFFFF\\uFFFF\"" */

        },

        {

            /* \U+DB7F\U+DC00 */

            "\"\xED\xAD\xBF\xED\xB0\x80\"",

            "\xED\xAD\xBF\xED\xB0\x80", /* bug: not corrected */

            "\"\\uDB7F\\uDC00\"", /* bug: want "\"\\uFFFF\\uFFFF\"" */

        },

        {

            /* \U+DB7F\U+DFFF */

            "\"\xED\xAD\xBF\xED\xBF\xBF\"",

            "\xED\xAD\xBF\xED\xBF\xBF", /* bug: not corrected */

            "\"\\uDB7F\\uDFFF\"", /* bug: want "\"\\uFFFF\\uFFFF\"" */

        },

        {

            /* \U+DB80\U+DC00 */

            "\"\xED\xAE\x80\xED\xB0\x80\"",

            "\xED\xAE\x80\xED\xB0\x80", /* bug: not corrected */

            "\"\\uDB80\\uDC00\"", /* bug: want "\"\\uFFFF\\uFFFF\"" */

        },

        {

            /* \U+DB80\U+DFFF */

            "\"\xED\xAE\x80\xED\xBF\xBF\"",

            "\xED\xAE\x80\xED\xBF\xBF", /* bug: not corrected */

            "\"\\uDB80\\uDFFF\"", /* bug: want "\"\\uFFFF\\uFFFF\"" */

        },

        {

            /* \U+DBFF\U+DC00 */

            "\"\xED\xAF\xBF\xED\xB0\x80\"",

            "\xED\xAF\xBF\xED\xB0\x80", /* bug: not corrected */

            "\"\\uDBFF\\uDC00\"", /* bug: want "\"\\uFFFF\\uFFFF\"" */

        },

        {

            /* \U+DBFF\U+DFFF */

            "\"\xED\xAF\xBF\xED\xBF\xBF\"",

            "\xED\xAF\xBF\xED\xBF\xBF", /* bug: not corrected */

            "\"\\uDBFF\\uDFFF\"", /* bug: want "\"\\uFFFF\\uFFFF\"" */

        },

        /* 5.3  Other illegal code positions */

        {

            /* \U+FFFE */

            "\"\xEF\xBF\xBE\"",

            "\xEF\xBF\xBE",     /* bug: not corrected */

            "\"\\uFFFE\"",      /* bug: not corrected */

        },

        {

            /* \U+FFFF */

            "\"\xEF\xBF\xBF\"",

            "\xEF\xBF\xBF",     /* bug: not corrected */

            "\"\\uFFFF\"",      /* bug: not corrected */

        },

        {}

    };

    int i;

    QObject *obj;

    QString *str;

    const char *json_in, *utf8_out, *utf8_in, *json_out;

    for (i = 0; test_cases[i].json_in; i++) {

        json_in = test_cases[i].json_in;

        utf8_out = test_cases[i].utf8_out;

        utf8_in = test_cases[i].utf8_in ?: test_cases[i].utf8_out;

        json_out = test_cases[i].json_out ?: test_cases[i].json_in;

        obj = qobject_from_json(json_in);

        if (utf8_out) {

            g_assert(obj);

            g_assert(qobject_type(obj) == QTYPE_QSTRING);

            str = qobject_to_qstring(obj);

            g_assert_cmpstr(qstring_get_str(str), ==, utf8_out);

        } else {

            g_assert(!obj);

        }

        qobject_decref(obj);

        obj = QOBJECT(qstring_from_str(utf8_in));

        str = qobject_to_json(obj);

        if (json_out) {

            g_assert(str);

            g_assert_cmpstr(qstring_get_str(str), ==, json_out);

        } else {

            g_assert(!str);

        }

        QDECREF(str);

        qobject_decref(obj);

        /*

         * Disabled, because json_out currently contains the crap

         * qobject_to_json() produces.

         * FIXME Enable once these bugs have been fixed.

         */

        if (0 && json_out != json_in) {

            obj = qobject_from_json(json_out);

            g_assert(obj);

            g_assert(qobject_type(obj) == QTYPE_QSTRING);

            str = qobject_to_qstring(obj);

            g_assert_cmpstr(qstring_get_str(str), ==, utf8_out);

        }

    }

}


static void virtio_net_cleanup(NetClientState *nc)

{

    VirtIONet *n = qemu_get_nic_opaque(nc);

    n->nic = NULL;

}


static uint64_t exynos4210_uart_read(void *opaque, target_phys_addr_t offset,

                                  unsigned size)

{

    Exynos4210UartState *s = (Exynos4210UartState *)opaque;

    uint32_t res;

    switch (offset) {

    case UERSTAT: /* Read Only */

        res = s->reg[I_(UERSTAT)];

        s->reg[I_(UERSTAT)] = 0;

        return res;

    case UFSTAT: /* Read Only */

        s->reg[I_(UFSTAT)] = fifo_elements_number(&s->rx) & 0xff;

        if (fifo_empty_elements_number(&s->rx) == 0) {

            s->reg[I_(UFSTAT)] |= UFSTAT_Rx_FIFO_FULL;

            s->reg[I_(UFSTAT)] &= ~0xff;

        }

        return s->reg[I_(UFSTAT)];

    case URXH:

        if (s->reg[I_(UFCON)] & UFCON_FIFO_ENABLE) {

            if (fifo_elements_number(&s->rx)) {

                res = fifo_retrieve(&s->rx);

#if DEBUG_Rx_DATA

                fprintf(stderr, "%c", res);

#endif

                if (!fifo_elements_number(&s->rx)) {

                    s->reg[I_(UTRSTAT)] &= ~UTRSTAT_Rx_BUFFER_DATA_READY;

                } else {

                    s->reg[I_(UTRSTAT)] |= UTRSTAT_Rx_BUFFER_DATA_READY;

                }

            } else {

                s->reg[I_(UINTSP)] |= UINTSP_ERROR;

                exynos4210_uart_update_irq(s);

                res = 0;

            }

        } else {

            s->reg[I_(UTRSTAT)] &= ~UTRSTAT_Rx_BUFFER_DATA_READY;

            res = s->reg[I_(URXH)];

        }

        return res;

    case UTXH:

        PRINT_DEBUG("UART%d: Trying to read from WO register: %s [%04x]\n",

                    s->channel, exynos4210_uart_regname(offset), offset);

        break;

    default:

        return s->reg[I_(offset)];

    }

    return 0;

}


void i2c_end_transfer(I2CBus *bus)

{

    I2CSlaveClass *sc;

    I2CNode *node, *next;

    if (QLIST_EMPTY(&bus->current_devs)) {

        return;

    }

    QLIST_FOREACH_SAFE(node, &bus->current_devs, next, next) {

        sc = I2C_SLAVE_GET_CLASS(node->elt);

        if (sc->event) {

            sc->event(node->elt, I2C_FINISH);

        }

        QLIST_REMOVE(node, next);

        g_free(node);

    }

    bus->broadcast = false;

}


static av_cold int encode_end(AVCodecContext *avctx)

{

    LclEncContext *c = avctx->priv_data;

    av_freep(&avctx->extradata);

    deflateEnd(&c->zstream);

    av_frame_free(&avctx->coded_frame);

    return 0;

}


static void sysbus_mmio_map_common(SysBusDevice *dev, int n, hwaddr addr,

                                   bool may_overlap, unsigned priority)

{

    assert(n >= 0 && n < dev->num_mmio);

    if (dev->mmio[n].addr == addr) {

        /* ??? region already mapped here.  */

        return;

    }

    if (dev->mmio[n].addr != (hwaddr)-1) {

        /* Unregister previous mapping.  */

        memory_region_del_subregion(get_system_memory(), dev->mmio[n].memory);

    }

    dev->mmio[n].addr = addr;

    if (may_overlap) {

        memory_region_add_subregion_overlap(get_system_memory(),

                                            addr,

                                            dev->mmio[n].memory,

                                            priority);

    }

    else {

        memory_region_add_subregion(get_system_memory(),

                                    addr,

                                    dev->mmio[n].memory);

    }

}


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

                                  void *opaque, Error **errp)

{

    X86CPU *cpu = X86_CPU(obj);

    int64_t value = cpu->apic_id;

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

}


static int local_lsetxattr(FsContext *ctx, const char *path, const char *name,

                           void *value, size_t size, int flags)

{

    if ((ctx->fs_sm == SM_MAPPED) &&

        (strncmp(name, "user.virtfs.", 12) == 0)) {

        /*

         * Don't allow fetch of user.virtfs namesapce

         * in case of mapped security

         */

        errno = EACCES;

        return -1;

    }

    return lsetxattr(rpath(ctx, path), name, value, size, flags);

}


int xen_be_bind_evtchn(struct XenDevice *xendev)

{

    if (xendev->local_port != -1) {

        return 0;

    }

    xendev->local_port = xc_evtchn_bind_interdomain

        (xendev->evtchndev, xendev->dom, xendev->remote_port);

    if (xendev->local_port == -1) {

        xen_be_printf(xendev, 0, "xc_evtchn_bind_interdomain failed\n");

        return -1;

    }

    xen_be_printf(xendev, 2, "bind evtchn port %d\n", xendev->local_port);

    qemu_set_fd_handler(xc_evtchn_fd(xendev->evtchndev),

                        xen_be_evtchn_event, NULL, xendev);

    return 0;

}


BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,

                                    BlockDriverState *bs,

                                    QDict *options, int flags)

{

    assert(bs != NULL);

    BlockReopenQueueEntry *bs_entry;

    BdrvChild *child;

    QDict *old_options;

    if (bs_queue == NULL) {

        bs_queue = g_new0(BlockReopenQueue, 1);

        QSIMPLEQ_INIT(bs_queue);

    }

    if (!options) {

        options = qdict_new();

    }

    old_options = qdict_clone_shallow(bs->options);

    qdict_join(options, old_options, false);

    QDECREF(old_options);

    /* bdrv_open() masks this flag out */

    flags &= ~BDRV_O_PROTOCOL;

    QLIST_FOREACH(child, &bs->children, next) {

        int child_flags;

        if (child->bs->inherits_from != bs) {

            continue;

        }

        child_flags = child->role->inherit_flags(flags);

        /* TODO Pass down child flags (backing.*, extents.*, ...) */

        bdrv_reopen_queue(bs_queue, child->bs, NULL, child_flags);

    }

    bs_entry = g_new0(BlockReopenQueueEntry, 1);

    QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);

    bs_entry->state.bs = bs;

    bs_entry->state.options = options;

    bs_entry->state.flags = flags;

    return bs_queue;

}


static ssize_t test_block_read_func(QCryptoBlock *block,

                                    void *opaque,

                                    size_t offset,

                                    uint8_t *buf,

                                    size_t buflen,

                                    Error **errp)

{

    Buffer *header = opaque;

    g_assert_cmpint(offset + buflen, <=, header->capacity);

    memcpy(buf, header->buffer + offset, buflen);

    return buflen;

}


static void pollfds_cleanup(Notifier *n, void *unused)

{

    g_assert(npfd == 0);

    g_free(pollfds);

    g_free(nodes);

    nalloc = 0;

}


static void xen_domain_watcher(void)

{

    int qemu_running = 1;

    int fd[2], i, n, rc;

    char byte;

    pipe(fd);

    if (fork() != 0)

        return; /* not child */

    /* close all file handles, except stdio/out/err,

     * our watch pipe and the xen interface handle */

    n = getdtablesize();

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

        if (i == fd[0])

            continue;

        if (i == xen_xc)

            continue;

        close(i);

    }

    /* ignore term signals */

    signal(SIGINT,  SIG_IGN);

    signal(SIGTERM, SIG_IGN);

    /* wait for qemu exiting */

    while (qemu_running) {

        rc = read(fd[0], &byte, 1);

        switch (rc) {

        case -1:

            if (errno == EINTR)

                continue;

            qemu_log("%s: Huh? read error: %s\n", __FUNCTION__, strerror(errno));

            qemu_running = 0;

            break;

        case 0:

            /* EOF -> qemu exited */

            qemu_running = 0;

            break;

        default:

            qemu_log("%s: Huh? data on the watch pipe?\n", __FUNCTION__);

            break;

        }

    }

    /* cleanup */

    qemu_log("%s: destroy domain %d\n", __FUNCTION__, xen_domid);

    xc_domain_destroy(xen_xc, xen_domid);

    _exit(0);

}


static int decode_nal_units(H264Context *h, uint8_t *buf, int buf_size){

    MpegEncContext * const s = &h->s;

    AVCodecContext * const avctx= s->avctx;

    int buf_index=0;

#if 0

    int i;

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

        printf("%X ", buf[i]);

    }

#endif

    for(;;){

        int consumed;

        int dst_length;

        int bit_length;

        uint8_t *ptr;

        // start code prefix search

        for(; buf_index + 3 < buf_size; buf_index++){

            // this should allways succeed in the first iteration

            if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)

                break;

        }

        if(buf_index+3 >= buf_size) break;

        buf_index+=3;

        ptr= decode_nal(h, buf + buf_index, &dst_length, &consumed, buf_size - buf_index);

        if(ptr[dst_length - 1] == 0) dst_length--;

        bit_length= 8*dst_length - decode_rbsp_trailing(ptr + dst_length - 1);

        if(s->avctx->debug&FF_DEBUG_STARTCODE){

            av_log(h->s.avctx, AV_LOG_DEBUG, "NAL %d at %d length %d\n", h->nal_unit_type, buf_index, dst_length);

        }

        buf_index += consumed;

        if(h->nal_ref_idc < s->hurry_up)

            continue;

        switch(h->nal_unit_type){

        case NAL_IDR_SLICE:

            idr(h); //FIXME ensure we dont loose some frames if there is reordering

        case NAL_SLICE:

            init_get_bits(&s->gb, ptr, bit_length);

            h->intra_gb_ptr=

            h->inter_gb_ptr= &s->gb;

            s->data_partitioning = 0;

            if(decode_slice_header(h) < 0) return -1;

            if(h->redundant_pic_count==0)

                decode_slice(h);

            break;

        case NAL_DPA:

            init_get_bits(&s->gb, ptr, bit_length);

            h->intra_gb_ptr=

            h->inter_gb_ptr= NULL;

            s->data_partitioning = 1;

            if(decode_slice_header(h) < 0) return -1;

            break;

        case NAL_DPB:

            init_get_bits(&h->intra_gb, ptr, bit_length);

            h->intra_gb_ptr= &h->intra_gb;

            break;

        case NAL_DPC:

            init_get_bits(&h->inter_gb, ptr, bit_length);

            h->inter_gb_ptr= &h->inter_gb;

            if(h->redundant_pic_count==0 && h->intra_gb_ptr && s->data_partitioning)

                decode_slice(h);

            break;

        case NAL_SEI:

            break;

        case NAL_SPS:

            init_get_bits(&s->gb, ptr, bit_length);

            decode_seq_parameter_set(h);

            if(s->flags& CODEC_FLAG_LOW_DELAY)

                s->low_delay=1;

            avctx->has_b_frames= !s->low_delay;

            break;

        case NAL_PPS:

            init_get_bits(&s->gb, ptr, bit_length);

            decode_picture_parameter_set(h);

            break;

        case NAL_PICTURE_DELIMITER:

            break;

        case NAL_FILTER_DATA:

            break;

        }

        //FIXME move after where irt is set

        s->current_picture.pict_type= s->pict_type;

        s->current_picture.key_frame= s->pict_type == I_TYPE;

    }

    if(!s->current_picture_ptr) return buf_index; //no frame

    h->prev_frame_num_offset= h->frame_num_offset;

    h->prev_frame_num= h->frame_num;

    if(s->current_picture_ptr->reference){

        h->prev_poc_msb= h->poc_msb;

        h->prev_poc_lsb= h->poc_lsb;

    }

    if(s->current_picture_ptr->reference)

        execute_ref_pic_marking(h, h->mmco, h->mmco_index);

    else

        assert(h->mmco_index==0);

    ff_er_frame_end(s);

    if( h->disable_deblocking_filter_idc != 1 ) {

        filter_frame( h );

    }

    MPV_frame_end(s);

    return buf_index;

}


static int rd_frame(CinepakEncContext *s, const AVFrame *frame, int isakeyframe, unsigned char *buf, int buf_size)

{

    int num_strips, strip, i, y, nexty, size, temp_size, best_size;

    AVPicture last_pict, pict, scratch_pict;

    int64_t best_score = 0, score, score_temp;

#ifdef CINEPAK_REPORT_SERR

    int64_t best_serr = 0, serr, serr_temp;

#endif

    int best_nstrips;

    if(s->pix_fmt == AV_PIX_FMT_RGB24) {

        int x;

// build a copy of the given frame in the correct colorspace

        for(y = 0; y < s->h; y += 2) {

            for(x = 0; x < s->w; x += 2) {

                uint8_t *ir[2]; int32_t r, g, b, rr, gg, bb;

                ir[0] = ((AVPicture*)frame)->data[0] + x*3 + y*((AVPicture*)frame)->linesize[0];

                ir[1] = ir[0] + ((AVPicture*)frame)->linesize[0];

                get_sub_picture(s, x, y, (AVPicture*)s->input_frame, &scratch_pict);

                r = g = b = 0;

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

                    int i1, i2;

                    i1 = (i&1); i2 = (i>=2);

                    rr = ir[i2][i1*3+0];

                    gg = ir[i2][i1*3+1];

                    bb = ir[i2][i1*3+2];

                    r += rr; g += gg; b += bb;

// using fixed point arithmetic for portable repeatability, scaling by 2^23

// "Y"

//                    rr = 0.2857*rr + 0.5714*gg + 0.1429*bb;

                    rr = (2396625*rr + 4793251*gg + 1198732*bb) >> 23;

                    if(      rr <   0) rr =   0;

                    else if (rr > 255) rr = 255;

                    scratch_pict.data[0][i1 + i2*scratch_pict.linesize[0]] = rr;

                }

// let us scale down as late as possible

//                r /= 4; g /= 4; b /= 4;

// "U"

//                rr = -0.1429*r - 0.2857*g + 0.4286*b;

                rr = (-299683*r - 599156*g + 898839*b) >> 23;

                if(      rr < -128) rr = -128;

                else if (rr >  127) rr =  127;

                scratch_pict.data[1][0] = rr + 128; // quantize needs unsigned

// "V"

//                rr = 0.3571*r - 0.2857*g - 0.0714*b;

                rr = (748893*r - 599156*g - 149737*b) >> 23;

                if(      rr < -128) rr = -128;

                else if (rr >  127) rr =  127;

                scratch_pict.data[2][0] = rr + 128; // quantize needs unsigned

            }

        }

    }

    //would be nice but quite certainly incompatible with vintage players:

    // support encoding zero strips (meaning skip the whole frame)

    for(num_strips = s->min_strips; num_strips <= s->max_strips && num_strips <= s->h / MB_SIZE; num_strips++) {

        score = 0;

        size = 0;

#ifdef CINEPAK_REPORT_SERR

        serr = 0;

#endif

        for(y = 0, strip = 1; y < s->h; strip++, y = nexty) {

            int strip_height;

            nexty = strip * s->h / num_strips; // <= s->h

            //make nexty the next multiple of 4 if not already there

            if(nexty & 3)

                nexty += 4 - (nexty & 3);

            strip_height = nexty - y;

            if(strip_height <= 0) { // can this ever happen?

                av_log(s->avctx, AV_LOG_INFO, "skipping zero height strip %i of %i\n", strip, num_strips);

                continue;

            }

            if(s->pix_fmt == AV_PIX_FMT_RGB24)

                get_sub_picture(s, 0, y, (AVPicture*)s->input_frame,    &pict);

            else

                get_sub_picture(s, 0, y, (AVPicture*)frame,              &pict);

            get_sub_picture(s, 0, y, (AVPicture*)s->last_frame,    &last_pict);

            get_sub_picture(s, 0, y, (AVPicture*)s->scratch_frame, &scratch_pict);

            if((temp_size = rd_strip(s, y, strip_height, isakeyframe, &last_pict, &pict, &scratch_pict, s->frame_buf + size + CVID_HEADER_SIZE, &score_temp

#ifdef CINEPAK_REPORT_SERR

, &serr_temp

#endif

)) < 0)

                return temp_size;

            score += score_temp;

#ifdef CINEPAK_REPORT_SERR

            serr += serr_temp;

#endif

            size += temp_size;

            //av_log(s->avctx, AV_LOG_INFO, "strip %d, isakeyframe=%d", strip, isakeyframe);

            //av_log(s->avctx, AV_LOG_INFO, "\n");

        }

        if(best_score == 0 || score < best_score) {

            best_score = score;

#ifdef CINEPAK_REPORT_SERR

            best_serr = serr;

#endif

            best_size = size + write_cvid_header(s, s->frame_buf, num_strips, size, isakeyframe);

            //av_log(s->avctx, AV_LOG_INFO, "best number of strips so far: %2i, %12lli, %i B\n", num_strips, (long long int)score, best_size);

#ifdef CINEPAK_REPORT_SERR

            av_log(s->avctx, AV_LOG_INFO, "best number of strips so far: %2i, %12lli, %i B\n", num_strips, (long long int)serr, best_size);

#endif

            FFSWAP(AVFrame *, s->best_frame, s->scratch_frame);

            memcpy(buf, s->frame_buf, best_size);

            best_nstrips = num_strips;

        }

// avoid trying too many strip numbers without a real reason

// (this makes the processing of the very first frame faster)

        if(num_strips - best_nstrips > 4)

            break;

    }

// let the number of strips slowly adapt to the changes in the contents,

// compared to full bruteforcing every time this will occasionally lead

// to some r/d performance loss but makes encoding up to several times faster

    if(!s->strip_number_delta_range) {

        if(best_nstrips == s->max_strips) { // let us try to step up

            s->max_strips = best_nstrips + 1;

            if(s->max_strips >= s->max_max_strips)

                s->max_strips = s->max_max_strips;

        } else { // try to step down

            s->max_strips = best_nstrips;

        }

        s->min_strips = s->max_strips - 1;

        if(s->min_strips < s->min_min_strips)

            s->min_strips = s->min_min_strips;

    } else {

        s->max_strips = best_nstrips + s->strip_number_delta_range;

        if(s->max_strips >= s->max_max_strips)

            s->max_strips = s->max_max_strips;

        s->min_strips = best_nstrips - s->strip_number_delta_range;

        if(s->min_strips < s->min_min_strips)

            s->min_strips = s->min_min_strips;

    }

    return best_size;

}


static int vty_getchars(VIOsPAPRDevice *sdev, uint8_t *buf, int max)
{
    VIOsPAPRVTYDevice *dev = VIO_SPAPR_VTY_DEVICE(sdev);
    int n = 0;
    while ((n < max) && (dev->out != dev->in)) {
        buf[n++] = dev->buf[dev->out++ % VTERM_BUFSIZE];
    qemu_chr_fe_accept_input(&dev->chardev);
    return n;


int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,

                             uint64_t address, uint32_t data, PCIDevice *dev)

{

    S390PCIBusDevice *pbdev;

    uint32_t fid = data >> ZPCI_MSI_VEC_BITS;

    uint32_t vec = data & ZPCI_MSI_VEC_MASK;

    pbdev = s390_pci_find_dev_by_fid(fid);

    if (!pbdev) {

        DPRINTF("add_msi_route no dev\n");

        return -ENODEV;

    }

    pbdev->routes.adapter.ind_offset = vec;

    route->type = KVM_IRQ_ROUTING_S390_ADAPTER;

    route->flags = 0;

    route->u.adapter.summary_addr = pbdev->routes.adapter.summary_addr;

    route->u.adapter.ind_addr = pbdev->routes.adapter.ind_addr;

    route->u.adapter.summary_offset = pbdev->routes.adapter.summary_offset;

    route->u.adapter.ind_offset = pbdev->routes.adapter.ind_offset;

    route->u.adapter.adapter_id = pbdev->routes.adapter.adapter_id;

    return 0;

}


static void spapr_machine_device_plug(HotplugHandler *hotplug_dev,

                                      DeviceState *dev, Error **errp)

{

    sPAPRMachineClass *smc = SPAPR_MACHINE_GET_CLASS(qdev_get_machine());

    if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {

        uint32_t node;

        if (!smc->dr_lmb_enabled) {

            error_setg(errp, "Memory hotplug not supported for this machine");

            return;

        }

        node = object_property_get_int(OBJECT(dev), PC_DIMM_NODE_PROP, errp);

        if (*errp) {

            return;

        }

        spapr_memory_plug(hotplug_dev, dev, node, errp);

    }

}


void spapr_events_init(sPAPRMachineState *spapr)

{

    QTAILQ_INIT(&spapr->pending_events);

    spapr->check_exception_irq = xics_alloc(spapr->icp, 0, 0, false);

    spapr->epow_notifier.notify = spapr_powerdown_req;

    qemu_register_powerdown_notifier(&spapr->epow_notifier);

    spapr_rtas_register(RTAS_CHECK_EXCEPTION, "check-exception",

                        check_exception);

    spapr_rtas_register(RTAS_EVENT_SCAN, "event-scan", event_scan);

}


static void test_visitor_in_uint(TestInputVisitorData *data,

                                const void *unused)

{

    Error *err = NULL;

    uint64_t res = 0;

    int64_t i64;

    double dbl;

    int value = 42;

    Visitor *v;

    v = visitor_input_test_init(data, "%d", value);

    visit_type_uint64(v, NULL, &res, &error_abort);

    g_assert_cmpuint(res, ==, (uint64_t)value);

    visit_type_int(v, NULL, &i64, &error_abort);

    g_assert_cmpint(i64, ==, value);

    visit_type_number(v, NULL, &dbl, &error_abort);

    g_assert_cmpfloat(dbl, ==, value);

    /* BUG: value between INT64_MIN and -1 accepted modulo 2^64 */

    v = visitor_input_test_init(data, "%d", -value);

    visit_type_uint64(v, NULL, &res, &error_abort);

    g_assert_cmpuint(res, ==, (uint64_t)-value);

    /* BUG: value between INT64_MAX+1 and UINT64_MAX rejected */

    v = visitor_input_test_init(data, "18446744073709551574");

    visit_type_uint64(v, NULL, &res, &err);

    error_free_or_abort(&err);

    visit_type_number(v, NULL, &dbl, &error_abort);

    g_assert_cmpfloat(dbl, ==, 18446744073709552000.0);

}


static int kvm_check_many_ioeventfds(void)

{

    /* Userspace can use ioeventfd for io notification.  This requires a host

     * that supports eventfd(2) and an I/O thread; since eventfd does not

     * support SIGIO it cannot interrupt the vcpu.

     *

     * Older kernels have a 6 device limit on the KVM io bus.  Find out so we

     * can avoid creating too many ioeventfds.

     */

#if defined(CONFIG_EVENTFD) && defined(CONFIG_IOTHREAD)

    int ioeventfds[7];

    int i, ret = 0;

    for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {

        ioeventfds[i] = eventfd(0, EFD_CLOEXEC);

        if (ioeventfds[i] < 0) {

            break;

        }

        ret = kvm_set_ioeventfd_pio_word(ioeventfds[i], 0, i, true);

        if (ret < 0) {

            close(ioeventfds[i]);

            break;

        }

    }

    /* Decide whether many devices are supported or not */

    ret = i == ARRAY_SIZE(ioeventfds);

    while (i-- > 0) {

        kvm_set_ioeventfd_pio_word(ioeventfds[i], 0, i, false);

        close(ioeventfds[i]);

    }

    return ret;

#else

    return 0;

#endif

}


static int init_common(VC9Context *v)

{

    static int done = 0;

    int i;

    v->mv_type_mb_plane = v->direct_mb_plane = v->skip_mb_plane = NULL;

    v->pq = -1;

#if HAS_ADVANCED_PROFILE

    v->ac_pred_plane = v->over_flags_plane = NULL;

    v->hrd_rate = v->hrd_buffer = NULL;

#endif

#if 0 // spec -> actual tables converter

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

        int code= (vc9_norm6_spec[i][1] << vc9_norm6_spec[i][4]) + vc9_norm6_spec[i][3];

        av_log(NULL, AV_LOG_DEBUG, "0x%03X, ", code);

        if(i%16==15) av_log(NULL, AV_LOG_DEBUG, "\n");

    }

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

        int code= vc9_norm6_spec[i][2] + vc9_norm6_spec[i][4];

        av_log(NULL, AV_LOG_DEBUG, "%2d, ", code);

        if(i%16==15) av_log(NULL, AV_LOG_DEBUG, "\n");

    }

#endif

    if(!done)

    {

        done = 1;

        INIT_VLC(&vc9_bfraction_vlc, VC9_BFRACTION_VLC_BITS, 23,

                 vc9_bfraction_bits, 1, 1,

                 vc9_bfraction_codes, 1, 1, 1);

        INIT_VLC(&vc9_norm2_vlc, VC9_NORM2_VLC_BITS, 4,

                 vc9_norm2_bits, 1, 1,

                 vc9_norm2_codes, 1, 1, 1);

        INIT_VLC(&vc9_norm6_vlc, VC9_NORM6_VLC_BITS, 64,

                 vc9_norm6_bits, 1, 1,

                 vc9_norm6_codes, 2, 2, 1);

        INIT_VLC(&vc9_cbpcy_i_vlc, VC9_CBPCY_I_VLC_BITS, 64,

                 vc9_cbpcy_i_bits, 1, 1,

                 vc9_cbpcy_i_codes, 2, 2, 1);

        INIT_VLC(&vc9_imode_vlc, VC9_IMODE_VLC_BITS, 7,

                 vc9_imode_bits, 1, 1,

                 vc9_imode_codes, 1, 1, 1);

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

        {

            INIT_VLC(&vc9_4mv_block_pattern_vlc[i], VC9_4MV_BLOCK_PATTERN_VLC_BITS, 16,

                     vc9_4mv_block_pattern_bits[i], 1, 1,

                     vc9_4mv_block_pattern_codes[i], 1, 1, 1);

            INIT_VLC(&vc9_cbpcy_p_vlc[i], VC9_CBPCY_P_VLC_BITS, 64,

                     vc9_cbpcy_p_bits[i], 1, 1,

                     vc9_cbpcy_p_codes[i], 2, 2, 1);

        }

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

        {

            INIT_VLC(&vc9_mv_diff_vlc[i], VC9_MV_DIFF_VLC_BITS, 73,

                     vc9_mv_diff_bits[i], 1, 1,

                     vc9_mv_diff_codes[i], 2, 2, 1);

            INIT_VLC(&vc9_luma_dc_vlc[i], VC9_LUMA_DC_VLC_BITS, 120,

                     vc9_luma_dc_bits[i], 1, 1,

                     vc9_luma_dc_codes[i], 4, 4, 1);

            INIT_VLC(&vc9_ttmb_vlc[i], VC9_TTMB_VLC_BITS, 16,

                     vc9_ttmb_bits[i], 1, 1,

                     vc9_ttmb_codes[i], 2, 2, 1);

        }

    }

    return 0;

}


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

{

    AVStream *st = s->streams[pkt->stream_index];

    AVIOContext *pb = s->pb;

    AVFrame *frame;

    int* first_pkt = s->priv_data;

    int width, height, h_chroma_shift, v_chroma_shift;

    int i;

    char buf2[Y4M_LINE_MAX + 1];

    uint8_t *ptr, *ptr1, *ptr2;

    frame = (AVFrame *)pkt->data;

    /* for the first packet we have to output the header as well */

    if (*first_pkt) {

        *first_pkt = 0;

        if (yuv4_generate_header(s, buf2) < 0) {

            av_log(s, AV_LOG_ERROR,

                   "Error. YUV4MPEG stream header write failed.\n");

            return AVERROR(EIO);

        } else {

            avio_write(pb, buf2, strlen(buf2));

        }

    }

    /* construct frame header */

    avio_printf(s->pb, "%s\n", Y4M_FRAME_MAGIC);

    width  = st->codecpar->width;

    height = st->codecpar->height;

    ptr = frame->data[0];

    switch (st->codecpar->format) {

    case AV_PIX_FMT_GRAY8:

    case AV_PIX_FMT_YUV411P:

    case AV_PIX_FMT_YUV420P:

    case AV_PIX_FMT_YUV422P:

    case AV_PIX_FMT_YUV444P:

        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_YUV420P10:

    case AV_PIX_FMT_YUV422P10:

    case AV_PIX_FMT_YUV444P10:

    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_YUV420P16:

    case AV_PIX_FMT_YUV422P16:

    case AV_PIX_FMT_YUV444P16:

        width *= 2;

        break;

    default:

        av_log(s, AV_LOG_ERROR, "The pixel format '%s' is not supported.\n",

               av_get_pix_fmt_name(st->codecpar->format));

        return AVERROR(EINVAL);

    }

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

        avio_write(pb, ptr, width);

        ptr += frame->linesize[0];

    }

    if (st->codecpar->format != AV_PIX_FMT_GRAY8 &&

        st->codecpar->format != AV_PIX_FMT_GRAY16) {

        // Adjust for smaller Cb and Cr planes

        av_pix_fmt_get_chroma_sub_sample(st->codecpar->format, &h_chroma_shift,

                                         &v_chroma_shift);

        // Shift right, rounding up

        width  = AV_CEIL_RSHIFT(width,  h_chroma_shift);

        height = AV_CEIL_RSHIFT(height, v_chroma_shift);

        ptr1 = frame->data[1];

        ptr2 = frame->data[2];

        for (i = 0; i < height; i++) {     /* Cb */

            avio_write(pb, ptr1, width);

            ptr1 += frame->linesize[1];

        }

        for (i = 0; i < height; i++) {     /* Cr */

            avio_write(pb, ptr2, width);

            ptr2 += frame->linesize[2];

        }

    }

    return 0;

}


static void FUNC(transquant_bypass4x4)(uint8_t *_dst, int16_t *coeffs,

                                       ptrdiff_t stride)

{

    int x, y;

    pixel *dst = (pixel *)_dst;

    stride /= sizeof(pixel);

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

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

            dst[x] += *coeffs;

            coeffs++;

        }

        dst += stride;

    }

}


static int RENAME(epzs_motion_search4)(MpegEncContext * s,

                             int *mx_ptr, int *my_ptr,

                             int P[10][2], int pred_x, int pred_y,

                             uint8_t *src_data[3],

                             uint8_t *ref_data[3], int stride, int uvstride, int16_t (*last_mv)[2],

                             int ref_mv_scale, uint8_t * const mv_penalty)

{

    int best[2]={0, 0};

    int d, dmin;

    const int shift= 1+s->quarter_sample;

    uint32_t *map= s->me.map;

    int map_generation;

    const int penalty_factor= s->me.penalty_factor;

    const int size=1;

    const int h=8;

    const int ref_mv_stride= s->mb_stride;

    const int ref_mv_xy= s->mb_x + s->mb_y *ref_mv_stride;

    me_cmp_func cmp, chroma_cmp;

    LOAD_COMMON

    cmp= s->dsp.me_cmp[size];

    chroma_cmp= s->dsp.me_cmp[size+1];

    map_generation= update_map_generation(s);

    dmin = 1000000;

//printf("%d %d %d %d //",xmin, ymin, xmax, ymax);

    /* first line */

    if (s->first_slice_line) {

	CHECK_MV(P_LEFT[0]>>shift, P_LEFT[1]>>shift)

        CHECK_CLIPED_MV((last_mv[ref_mv_xy][0]*ref_mv_scale + (1<<15))>>16,

                        (last_mv[ref_mv_xy][1]*ref_mv_scale + (1<<15))>>16)

        CHECK_MV(P_MV1[0]>>shift, P_MV1[1]>>shift)

    }else{

        CHECK_MV(P_MV1[0]>>shift, P_MV1[1]>>shift)

        //FIXME try some early stop

        if(dmin>64*2){

            CHECK_MV(P_MEDIAN[0]>>shift, P_MEDIAN[1]>>shift)

            CHECK_MV(P_LEFT[0]>>shift, P_LEFT[1]>>shift)

            CHECK_MV(P_TOP[0]>>shift, P_TOP[1]>>shift)

            CHECK_MV(P_TOPRIGHT[0]>>shift, P_TOPRIGHT[1]>>shift)

            CHECK_CLIPED_MV((last_mv[ref_mv_xy][0]*ref_mv_scale + (1<<15))>>16,

                            (last_mv[ref_mv_xy][1]*ref_mv_scale + (1<<15))>>16)

        }

    }

    if(dmin>64*4){

        CHECK_CLIPED_MV((last_mv[ref_mv_xy+1][0]*ref_mv_scale + (1<<15))>>16,

                        (last_mv[ref_mv_xy+1][1]*ref_mv_scale + (1<<15))>>16)

        if(s->end_mb_y == s->mb_height || s->mb_y+1<s->end_mb_y)  //FIXME replace at least with last_slice_line

            CHECK_CLIPED_MV((last_mv[ref_mv_xy+ref_mv_stride][0]*ref_mv_scale + (1<<15))>>16,

                            (last_mv[ref_mv_xy+ref_mv_stride][1]*ref_mv_scale + (1<<15))>>16)

    }

    if(s->me.dia_size==-1)

        dmin= RENAME(funny_diamond_search)(s, best, dmin, src_data, ref_data, stride, uvstride,

                                   pred_x, pred_y, penalty_factor,

				   shift, map, map_generation, size, h, mv_penalty);

    else if(s->me.dia_size<-1)

        dmin= RENAME(sab_diamond_search)(s, best, dmin, src_data, ref_data, stride, uvstride,

                                   pred_x, pred_y, penalty_factor,

				   shift, map, map_generation, size, h, mv_penalty);

    else if(s->me.dia_size<2)

        dmin= RENAME(small_diamond_search)(s, best, dmin, src_data, ref_data, stride, uvstride,

                                   pred_x, pred_y, penalty_factor,

				   shift, map, map_generation, size, h, mv_penalty);

    else

        dmin= RENAME(var_diamond_search)(s, best, dmin, src_data, ref_data, stride, uvstride,

                                   pred_x, pred_y, penalty_factor,

				   shift, map, map_generation, size, h, mv_penalty);

    *mx_ptr= best[0];

    *my_ptr= best[1];

//    printf("%d %d %d \n", best[0], best[1], dmin);

    return dmin;

}


static int ftp_passive_mode(FTPContext *s)

{

    char *res = NULL, *start, *end;

    int i;

    const char *command = "PASV\r\n";

    const int pasv_codes[] = {227, 0};

    if (!ftp_send_command(s, command, pasv_codes, &res))

        goto fail;

    start = NULL;

    for (i = 0; i < strlen(res); ++i) {

        if (res[i] == '(') {

            start = res + i + 1;

        } else if (res[i] == ')') {

            end = res + i;

            break;

        }

    }

    if (!start || !end)

        goto fail;

    *end  = '\0';

    /* skip ip */

    if (!av_strtok(start, ",", &end)) goto fail;

    if (!av_strtok(end, ",", &end)) goto fail;

    if (!av_strtok(end, ",", &end)) goto fail;

    if (!av_strtok(end, ",", &end)) goto fail;

    /* parse port number */

    start = av_strtok(end, ",", &end);

    if (!start) goto fail;

    s->server_data_port = atoi(start) * 256;

    start = av_strtok(end, ",", &end);

    if (!start) goto fail;

    s->server_data_port += atoi(start);

    av_dlog(s, "Server data port: %d\n", s->server_data_port);

    av_free(res);

    return 0;

  fail:

    av_free(res);

    s->server_data_port = -1;

    return AVERROR(EIO);

}


void virtio_blk_data_plane_create(VirtIODevice *vdev, VirtIOBlkConf *blk,

                                  VirtIOBlockDataPlane **dataplane,

                                  Error **errp)

{

    VirtIOBlockDataPlane *s;

    Error *local_err = NULL;

    *dataplane = NULL;

    if (!blk->data_plane) {

        return;

    }

    if (blk->scsi) {

        error_setg(errp,

                   "device is incompatible with x-data-plane, use scsi=off");

        return;

    }

    if (blk->config_wce) {

        error_setg(errp, "device is incompatible with x-data-plane, "

                         "use config-wce=off");

        return;

    }

    /* If dataplane is (re-)enabled while the guest is running there could be

     * block jobs that can conflict.

     */

    if (bdrv_op_is_blocked(blk->conf.bs, BLOCK_OP_TYPE_DATAPLANE, &local_err)) {

        error_report("cannot start dataplane thread: %s",

                      error_get_pretty(local_err));

        error_free(local_err);

        return;

    }

    s = g_new0(VirtIOBlockDataPlane, 1);

    s->vdev = vdev;

    s->blk = blk;

    if (blk->iothread) {

        s->iothread = blk->iothread;

        object_ref(OBJECT(s->iothread));

    } else {

        /* Create per-device IOThread if none specified.  This is for

         * x-data-plane option compatibility.  If x-data-plane is removed we

         * can drop this.

         */

        object_initialize(&s->internal_iothread_obj,

                          sizeof(s->internal_iothread_obj),

                          TYPE_IOTHREAD);

        user_creatable_complete(OBJECT(&s->internal_iothread_obj), &error_abort);

        s->iothread = &s->internal_iothread_obj;

    }

    s->ctx = iothread_get_aio_context(s->iothread);

    error_setg(&s->blocker, "block device is in use by data plane");

    bdrv_op_block_all(blk->conf.bs, s->blocker);

    *dataplane = s;

}


static Suite *QList_suite(void)

{

    Suite *s;

    TCase *qlist_public_tcase;

    s = suite_create("QList suite");

    qlist_public_tcase = tcase_create("Public Interface");

    suite_add_tcase(s, qlist_public_tcase);

    tcase_add_test(qlist_public_tcase, qlist_new_test);

    tcase_add_test(qlist_public_tcase, qlist_append_test);

    tcase_add_test(qlist_public_tcase, qobject_to_qlist_test);

    tcase_add_test(qlist_public_tcase, qlist_destroy_test);

    tcase_add_test(qlist_public_tcase, qlist_iter_test);

    return s;

}


static void spr_write_decr (DisasContext *ctx, int sprn, int gprn)

{

    if (use_icount) {

        gen_io_start();

    }

    gen_helper_store_decr(cpu_env, cpu_gpr[gprn]);

    if (use_icount) {

        gen_io_end();

        gen_stop_exception(ctx);

    }

}


static inline void IRQ_resetbit(IRQQueue *q, int n_IRQ)

{

    reset_bit(q->queue, n_IRQ);

}


static void rtas_write_pci_config(sPAPREnvironment *spapr,

                                  uint32_t token, uint32_t nargs,

                                  target_ulong args,

                                  uint32_t nret, target_ulong rets)

{

    uint32_t val, size, addr;

    PCIDevice *dev = find_dev(spapr, 0, rtas_ld(args, 0));

    if (!dev) {

        rtas_st(rets, 0, -1);

        return;

    }

    val = rtas_ld(args, 2);

    size = rtas_ld(args, 1);

    addr = rtas_pci_cfgaddr(rtas_ld(args, 0));

    pci_host_config_write_common(dev, addr, pci_config_size(dev), val, size);

    rtas_st(rets, 0, 0);

}


static void virtio_mmio_device_plugged(DeviceState *opaque)

{

    VirtIOMMIOProxy *proxy = VIRTIO_MMIO(opaque);

    proxy->host_features |= (0x1 << VIRTIO_F_NOTIFY_ON_EMPTY);

    proxy->host_features = virtio_bus_get_vdev_features(&proxy->bus,

                                                        proxy->host_features);

}


static void virtio_serial_class_init(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    k->init = virtio_serial_init_pci;

    k->exit = virtio_serial_exit_pci;

    k->vendor_id = PCI_VENDOR_ID_REDHAT_QUMRANET;

    k->device_id = PCI_DEVICE_ID_VIRTIO_CONSOLE;

    k->revision = VIRTIO_PCI_ABI_VERSION;

    k->class_id = PCI_CLASS_COMMUNICATION_OTHER;

    dc->alias = "virtio-serial";

    dc->reset = virtio_pci_reset;

    dc->props = virtio_serial_properties;

}


static VncServerInfo *vnc_server_info_get(VncDisplay *vd)

{

    VncServerInfo *info;

    Error *err = NULL;

    info = g_malloc(sizeof(*info));

    info->base = g_malloc(sizeof(*info->base));

    vnc_init_basic_info_from_server_addr(vd->lsock, info->base, &err);

    info->has_auth = true;

    info->auth = g_strdup(vnc_auth_name(vd));

    if (err) {

        qapi_free_VncServerInfo(info);

        info = NULL;

        error_free(err);

    }

    return info;

}


static enum CodecID find_codec_or_die(const char *name, int type, int encoder, int strict)

{

    const char *codec_string = encoder ? "encoder" : "decoder";

    AVCodec *codec;

    if(!name)

        return CODEC_ID_NONE;

    codec = encoder ?

        avcodec_find_encoder_by_name(name) :

        avcodec_find_decoder_by_name(name);

    if(!codec) {

        fprintf(stderr, "Unknown %s '%s'\n", codec_string, name);

        ffmpeg_exit(1);

    }

    if(codec->type != type) {

        fprintf(stderr, "Invalid %s type '%s'\n", codec_string, name);

        ffmpeg_exit(1);

    }

    if(codec->capabilities & CODEC_CAP_EXPERIMENTAL &&

       strict > FF_COMPLIANCE_EXPERIMENTAL) {

        fprintf(stderr, "%s '%s' is experimental and might produce bad "

                "results.\nAdd '-strict experimental' if you want to use it.\n",

                codec_string, codec->name);

        codec = encoder ?

            avcodec_find_encoder(codec->id) :

            avcodec_find_decoder(codec->id);

        if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))

            fprintf(stderr, "Or use the non experimental %s '%s'.\n",

                    codec_string, codec->name);

        ffmpeg_exit(1);

    }

    return codec->id;

}


static void xen_ram_init(ram_addr_t ram_size)

{

    RAMBlock *new_block;

    ram_addr_t below_4g_mem_size, above_4g_mem_size = 0;

    new_block = qemu_mallocz(sizeof (*new_block));

    pstrcpy(new_block->idstr, sizeof (new_block->idstr), "xen.ram");

    new_block->host = NULL;

    new_block->offset = 0;

    new_block->length = ram_size;

    QLIST_INSERT_HEAD(&ram_list.blocks, new_block, next);

    ram_list.phys_dirty = qemu_realloc(ram_list.phys_dirty,

                                       new_block->length >> TARGET_PAGE_BITS);

    memset(ram_list.phys_dirty + (new_block->offset >> TARGET_PAGE_BITS),

           0xff, new_block->length >> TARGET_PAGE_BITS);

    if (ram_size >= 0xe0000000 ) {

        above_4g_mem_size = ram_size - 0xe0000000;

        below_4g_mem_size = 0xe0000000;

    } else {

        below_4g_mem_size = ram_size;

    }

    cpu_register_physical_memory(0, below_4g_mem_size, new_block->offset);

#if TARGET_PHYS_ADDR_BITS > 32

    if (above_4g_mem_size > 0) {

        cpu_register_physical_memory(0x100000000ULL, above_4g_mem_size,

                                     new_block->offset + below_4g_mem_size);

    }

#endif

}


static int tight_init_stream(VncState *vs, int stream_id,

                             int level, int strategy)

{

    z_streamp zstream = &vs->tight_stream[stream_id];

    if (zstream->opaque == NULL) {

        int err;

        VNC_DEBUG("VNC: TIGHT: initializing zlib stream %d\n", stream_id);

        VNC_DEBUG("VNC: TIGHT: opaque = %p | vs = %p\n", zstream->opaque, vs);

        zstream->zalloc = vnc_zlib_zalloc;

        zstream->zfree = vnc_zlib_zfree;

        err = deflateInit2(zstream, level, Z_DEFLATED, MAX_WBITS,

                           MAX_MEM_LEVEL, strategy);

        if (err != Z_OK) {

            fprintf(stderr, "VNC: error initializing zlib\n");

            return -1;

        }

        vs->tight_levels[stream_id] = level;

        zstream->opaque = vs;

    }

    if (vs->tight_levels[stream_id] != level) {

        if (deflateParams(zstream, level, strategy) != Z_OK) {

            return -1;

        }

        vs->tight_levels[stream_id] = level;

    }

    return 0;

}


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

{

    ReadInfo *read_info = (ReadInfo *) sccb;

    MachineState *machine = MACHINE(qdev_get_machine());

    sclpMemoryHotplugDev *mhd = get_sclp_memory_hotplug_dev();

    CPUState *cpu;

    int cpu_count = 0;

    int rnsize, rnmax;

    int slots = MIN(machine->ram_slots, s390_get_memslot_count(kvm_state));

    IplParameterBlock *ipib = s390_ipl_get_iplb();

    CPU_FOREACH(cpu) {

        cpu_count++;

    }

    /* CPU information */

    read_info->entries_cpu = cpu_to_be16(cpu_count);

    read_info->offset_cpu = cpu_to_be16(offsetof(ReadInfo, entries));

    read_info->highest_cpu = cpu_to_be16(max_cpus);

    read_info->ibc_val = cpu_to_be32(s390_get_ibc_val());

    /* Configuration Characteristic (Extension) */

    s390_get_feat_block(S390_FEAT_TYPE_SCLP_CONF_CHAR,

                         read_info->conf_char);

    s390_get_feat_block(S390_FEAT_TYPE_SCLP_CONF_CHAR_EXT,

                         read_info->conf_char_ext);

    prepare_cpu_entries(sclp, read_info->entries, cpu_count);

    read_info->facilities = cpu_to_be64(SCLP_HAS_CPU_INFO |

                                        SCLP_HAS_PCI_RECONFIG);

    /* Memory Hotplug is only supported for the ccw machine type */

    if (mhd) {

        mhd->standby_subregion_size = MEM_SECTION_SIZE;

        /* Deduct the memory slot already used for core */

        if (slots > 0) {

            while ((mhd->standby_subregion_size * (slots - 1)

                    < mhd->standby_mem_size)) {

                mhd->standby_subregion_size = mhd->standby_subregion_size << 1;

            }

        }

        /*

         * Initialize mapping of guest standby memory sections indicating which

         * are and are not online. Assume all standby memory begins offline.

         */

        if (mhd->standby_state_map == 0) {

            if (mhd->standby_mem_size % mhd->standby_subregion_size) {

                mhd->standby_state_map = g_malloc0((mhd->standby_mem_size /

                                             mhd->standby_subregion_size + 1) *

                                             (mhd->standby_subregion_size /

                                             MEM_SECTION_SIZE));

            } else {

                mhd->standby_state_map = g_malloc0(mhd->standby_mem_size /

                                                   MEM_SECTION_SIZE);

            }

        }

        mhd->padded_ram_size = ram_size + mhd->pad_size;

        mhd->rzm = 1 << mhd->increment_size;

        read_info->facilities |= cpu_to_be64(SCLP_FC_ASSIGN_ATTACH_READ_STOR);

    }

    read_info->mha_pow = s390_get_mha_pow();

    read_info->hmfai = cpu_to_be32(s390_get_hmfai());

    rnsize = 1 << (sclp->increment_size - 20);

    if (rnsize <= 128) {

        read_info->rnsize = rnsize;

    } else {

        read_info->rnsize = 0;

        read_info->rnsize2 = cpu_to_be32(rnsize);

    }

    rnmax = machine->maxram_size >> sclp->increment_size;

    if (rnmax < 0x10000) {

        read_info->rnmax = cpu_to_be16(rnmax);

    } else {

        read_info->rnmax = cpu_to_be16(0);

        read_info->rnmax2 = cpu_to_be64(rnmax);

    }

    if (ipib && ipib->flags & DIAG308_FLAGS_LP_VALID) {

        memcpy(&read_info->loadparm, &ipib->loadparm,

               sizeof(read_info->loadparm));

    } else {

        s390_ipl_set_loadparm(read_info->loadparm);

    }

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

}


static void init_proc_970GX (CPUPPCState *env)

{

    gen_spr_ne_601(env);

    gen_spr_7xx(env);

    /* Time base */

    gen_tbl(env);

    /* Hardware implementation registers */

    /* XXX : not implemented */

    spr_register(env, SPR_HID0, "HID0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_clear,

                 0x60000000);

    /* XXX : not implemented */

    spr_register(env, SPR_HID1, "HID1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_750_HID2, "HID2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_970_HID5, "HID5",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* Memory management */

    /* XXX: not correct */

    gen_low_BATs(env);

#if 0 // TODO

    env->slb_nr = 32;

#endif

    init_excp_970(env);

    env->dcache_line_size = 128;

    env->icache_line_size = 128;

    /* Allocate hardware IRQ controller */

    ppc970_irq_init(env);

#if !defined(CONFIG_USER_ONLY)

    /* Hardware reset vector */

    env->hreset_vector = 0x0000000000000100ULL;

#endif

}


static void QEMU_NORETURN force_sig(int sig)

{

    int host_sig;

    host_sig = target_to_host_signal(sig);

    fprintf(stderr, "qemu: uncaught target signal %d (%s) - exiting\n",

            sig, strsignal(host_sig));

#if 1

    gdb_signalled(thread_env, sig);

    _exit(-host_sig);

#else

    {

        struct sigaction act;

        sigemptyset(&act.sa_mask);

        act.sa_flags = SA_SIGINFO;

        act.sa_sigaction = SIG_DFL;

        sigaction(SIGABRT, &act, NULL);

        abort();

    }

#endif

}


static void sd_close(BlockDriverState *bs)

{

    Error *local_err = NULL;

    BDRVSheepdogState *s = bs->opaque;

    SheepdogVdiReq hdr;

    SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;

    unsigned int wlen, rlen = 0;

    int fd, ret;

    DPRINTF("%s\n", s->name);

    fd = connect_to_sdog(s, &local_err);

    if (fd < 0) {

        error_report_err(local_err);

        return;

    }

    memset(&hdr, 0, sizeof(hdr));

    hdr.opcode = SD_OP_RELEASE_VDI;

    hdr.type = LOCK_TYPE_NORMAL;

    hdr.base_vdi_id = s->inode.vdi_id;

    wlen = strlen(s->name) + 1;

    hdr.data_length = wlen;

    hdr.flags = SD_FLAG_CMD_WRITE;

    ret = do_req(fd, s->bs, (SheepdogReq *)&hdr,

                 s->name, &wlen, &rlen);

    closesocket(fd);

    if (!ret && rsp->result != SD_RES_SUCCESS &&

        rsp->result != SD_RES_VDI_NOT_LOCKED) {

        error_report("%s, %s", sd_strerror(rsp->result), s->name);

    }

    aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd,

                       false, NULL, NULL, NULL, NULL);

    closesocket(s->fd);

    qapi_free_SocketAddressLegacy(s->addr);

}


static uint64_t malta_fpga_read(void *opaque, hwaddr addr,

                                unsigned size)

{

    MaltaFPGAState *s = opaque;

    uint32_t val = 0;

    uint32_t saddr;

    saddr = (addr & 0xfffff);

    switch (saddr) {

    /* SWITCH Register */

    case 0x00200:

        val = 0x00000000;		/* All switches closed */

        break;

    /* STATUS Register */

    case 0x00208:

#ifdef TARGET_WORDS_BIGENDIAN

        val = 0x00000012;

#else

        val = 0x00000010;

#endif

        break;

    /* JMPRS Register */

    case 0x00210:

        val = 0x00;

        break;

    /* LEDBAR Register */

    case 0x00408:

        val = s->leds;

        break;

    /* BRKRES Register */

    case 0x00508:

        val = s->brk;

        break;

    /* UART Registers are handled directly by the serial device */

    /* GPOUT Register */

    case 0x00a00:

        val = s->gpout;

        break;

    /* XXX: implement a real I2C controller */

    /* GPINP Register */

    case 0x00a08:

        /* IN = OUT until a real I2C control is implemented */

        if (s->i2csel)

            val = s->i2cout;

        else

            val = 0x00;

        break;

    /* I2CINP Register */

    case 0x00b00:

        val = ((s->i2cin & ~1) | eeprom24c0x_read());

        break;

    /* I2COE Register */

    case 0x00b08:

        val = s->i2coe;

        break;

    /* I2COUT Register */

    case 0x00b10:

        val = s->i2cout;

        break;

    /* I2CSEL Register */

    case 0x00b18:

        val = s->i2csel;

        break;

    default:

#if 0

        printf ("malta_fpga_read: Bad register offset 0x" TARGET_FMT_lx "\n",

                addr);

#endif

        break;

    }

    return val;

}