static void pc_init1(MachineState *machine,

                     const char *host_type, const char *pci_type)

{

    PCMachineState *pcms = PC_MACHINE(machine);

    PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);

    MemoryRegion *system_memory = get_system_memory();

    MemoryRegion *system_io = get_system_io();

    int i;

    PCIBus *pci_bus;

    ISABus *isa_bus;

    PCII440FXState *i440fx_state;

    int piix3_devfn = -1;

    qemu_irq *gsi;

    qemu_irq *i8259;

    qemu_irq smi_irq;

    GSIState *gsi_state;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    BusState *idebus[MAX_IDE_BUS];

    ISADevice *rtc_state;

    MemoryRegion *ram_memory;

    MemoryRegion *pci_memory;

    MemoryRegion *rom_memory;

    ram_addr_t lowmem;

    /*

     * Calculate ram split, for memory below and above 4G.  It's a bit

     * complicated for backward compatibility reasons ...

     *

     *  - Traditional split is 3.5G (lowmem = 0xe0000000).  This is the

     *    default value for max_ram_below_4g now.

     *

     *  - Then, to gigabyte align the memory, we move the split to 3G

     *    (lowmem = 0xc0000000).  But only in case we have to split in

     *    the first place, i.e. ram_size is larger than (traditional)

     *    lowmem.  And for new machine types (gigabyte_align = true)

     *    only, for live migration compatibility reasons.

     *

     *  - Next the max-ram-below-4g option was added, which allowed to

     *    reduce lowmem to a smaller value, to allow a larger PCI I/O

     *    window below 4G.  qemu doesn't enforce gigabyte alignment here,

     *    but prints a warning.

     *

     *  - Finally max-ram-below-4g got updated to also allow raising lowmem,

     *    so legacy non-PAE guests can get as much memory as possible in

     *    the 32bit address space below 4G.

     *

     *  - Note that Xen has its own ram setp code in xen_ram_init(),

     *    called via xen_hvm_init().

     *

     * Examples:

     *    qemu -M pc-1.7 -m 4G    (old default)    -> 3584M low,  512M high

     *    qemu -M pc -m 4G        (new default)    -> 3072M low, 1024M high

     *    qemu -M pc,max-ram-below-4g=2G -m 4G     -> 2048M low, 2048M high

     *    qemu -M pc,max-ram-below-4g=4G -m 3968M  -> 3968M low (=4G-128M)

     */

    if (xen_enabled()) {

        xen_hvm_init(pcms, &ram_memory);

    } else {

        if (!pcms->max_ram_below_4g) {

            pcms->max_ram_below_4g = 0xe0000000; /* default: 3.5G */

        }

        lowmem = pcms->max_ram_below_4g;

        if (machine->ram_size >= pcms->max_ram_below_4g) {

            if (pcmc->gigabyte_align) {

                if (lowmem > 0xc0000000) {

                    lowmem = 0xc0000000;

                }

                if (lowmem & ((1ULL << 30) - 1)) {

                    error_report("Warning: Large machine and max_ram_below_4g "

                                 "(%" PRIu64 ") not a multiple of 1G; "

                                 "possible bad performance.",

                                 pcms->max_ram_below_4g);

                }

            }

        }

        if (machine->ram_size >= lowmem) {

            pcms->above_4g_mem_size = machine->ram_size - lowmem;

            pcms->below_4g_mem_size = lowmem;

        } else {

            pcms->above_4g_mem_size = 0;

            pcms->below_4g_mem_size = machine->ram_size;

        }

    }

    pc_cpus_init(pcms);

    if (kvm_enabled() && pcmc->kvmclock_enabled) {

        kvmclock_create();

    }

    if (pcmc->pci_enabled) {

        pci_memory = g_new(MemoryRegion, 1);

        memory_region_init(pci_memory, NULL, "pci", UINT64_MAX);

        rom_memory = pci_memory;

    } else {

        pci_memory = NULL;

        rom_memory = system_memory;

    }

    pc_guest_info_init(pcms);

    if (pcmc->smbios_defaults) {

        MachineClass *mc = MACHINE_GET_CLASS(machine);

        /* These values are guest ABI, do not change */

        smbios_set_defaults("QEMU", "Standard PC (i440FX + PIIX, 1996)",

                            mc->name, pcmc->smbios_legacy_mode,

                            pcmc->smbios_uuid_encoded,

                            SMBIOS_ENTRY_POINT_21);

    }

    /* allocate ram and load rom/bios */

    if (!xen_enabled()) {

        pc_memory_init(pcms, system_memory,

                       rom_memory, &ram_memory);

    } else if (machine->kernel_filename != NULL) {

        /* For xen HVM direct kernel boot, load linux here */

        xen_load_linux(pcms);

    }

    gsi_state = g_malloc0(sizeof(*gsi_state));

    if (kvm_ioapic_in_kernel()) {

        kvm_pc_setup_irq_routing(pcmc->pci_enabled);

        gsi = qemu_allocate_irqs(kvm_pc_gsi_handler, gsi_state,

                                 GSI_NUM_PINS);

    } else {

        gsi = qemu_allocate_irqs(gsi_handler, gsi_state, GSI_NUM_PINS);

    }

    if (pcmc->pci_enabled) {

        pci_bus = i440fx_init(host_type,

                              pci_type,

                              &i440fx_state, &piix3_devfn, &isa_bus, gsi,

                              system_memory, system_io, machine->ram_size,

                              pcms->below_4g_mem_size,

                              pcms->above_4g_mem_size,

                              pci_memory, ram_memory);

        pcms->bus = pci_bus;

    } else {

        pci_bus = NULL;

        i440fx_state = NULL;

        isa_bus = isa_bus_new(NULL, get_system_memory(), system_io,

                              &error_abort);

        no_hpet = 1;

    }

    isa_bus_irqs(isa_bus, gsi);

    if (kvm_pic_in_kernel()) {

        i8259 = kvm_i8259_init(isa_bus);

    } else if (xen_enabled()) {

        i8259 = xen_interrupt_controller_init();

    } else {

        i8259 = i8259_init(isa_bus, pc_allocate_cpu_irq());

    }

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

        gsi_state->i8259_irq[i] = i8259[i];

    }

    g_free(i8259);

    if (pcmc->pci_enabled) {

        ioapic_init_gsi(gsi_state, "i440fx");

    }

    pc_register_ferr_irq(gsi[13]);

    pc_vga_init(isa_bus, pcmc->pci_enabled ? pci_bus : NULL);

    assert(pcms->vmport != ON_OFF_AUTO__MAX);

    if (pcms->vmport == ON_OFF_AUTO_AUTO) {

        pcms->vmport = xen_enabled() ? ON_OFF_AUTO_OFF : ON_OFF_AUTO_ON;

    }

    /* init basic PC hardware */

    pc_basic_device_init(isa_bus, gsi, &rtc_state, true,

                         (pcms->vmport != ON_OFF_AUTO_ON), 0x4);

    pc_nic_init(isa_bus, pci_bus);

    ide_drive_get(hd, ARRAY_SIZE(hd));

    if (pcmc->pci_enabled) {

        PCIDevice *dev;

        if (xen_enabled()) {

            dev = pci_piix3_xen_ide_init(pci_bus, hd, piix3_devfn + 1);

        } else {

            dev = pci_piix3_ide_init(pci_bus, hd, piix3_devfn + 1);

        }

        idebus[0] = qdev_get_child_bus(&dev->qdev, "ide.0");

        idebus[1] = qdev_get_child_bus(&dev->qdev, "ide.1");

    } else {

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

            ISADevice *dev;

            char busname[] = "ide.0";

            dev = isa_ide_init(isa_bus, ide_iobase[i], ide_iobase2[i],

                               ide_irq[i],

                               hd[MAX_IDE_DEVS * i], hd[MAX_IDE_DEVS * i + 1]);

            /*

             * The ide bus name is ide.0 for the first bus and ide.1 for the

             * second one.

             */

            busname[4] = '0' + i;

            idebus[i] = qdev_get_child_bus(DEVICE(dev), busname);

        }

    }

    pc_cmos_init(pcms, idebus[0], idebus[1], rtc_state);

    if (pcmc->pci_enabled && machine_usb(machine)) {

        pci_create_simple(pci_bus, piix3_devfn + 2, "piix3-usb-uhci");

    }

    if (pcmc->pci_enabled && acpi_enabled) {

        DeviceState *piix4_pm;

        I2CBus *smbus;

        smi_irq = qemu_allocate_irq(pc_acpi_smi_interrupt, first_cpu, 0);

        /* TODO: Populate SPD eeprom data.  */

        smbus = piix4_pm_init(pci_bus, piix3_devfn + 3, 0xb100,

                              gsi[9], smi_irq,

                              pc_machine_is_smm_enabled(pcms),

                              &piix4_pm);

        smbus_eeprom_init(smbus, 8, NULL, 0);

        object_property_add_link(OBJECT(machine), PC_MACHINE_ACPI_DEVICE_PROP,

                                 TYPE_HOTPLUG_HANDLER,

                                 (Object **)&pcms->acpi_dev,

                                 object_property_allow_set_link,

                                 OBJ_PROP_LINK_UNREF_ON_RELEASE, &error_abort);

        object_property_set_link(OBJECT(machine), OBJECT(piix4_pm),

                                 PC_MACHINE_ACPI_DEVICE_PROP, &error_abort);

    }

    if (pcmc->pci_enabled) {

        pc_pci_device_init(pci_bus);

    }

    if (pcms->acpi_nvdimm_state.is_enabled) {

        nvdimm_init_acpi_state(&pcms->acpi_nvdimm_state, system_io,

                               pcms->fw_cfg, OBJECT(pcms));

    }

}


static int do_cont(Monitor *mon, const QDict *qdict, QObject **ret_data)

{

    struct bdrv_iterate_context context = { mon, 0 };

    bdrv_iterate(encrypted_bdrv_it, &context);

    /* only resume the vm if all keys are set and valid */

    if (!context.err) {

        vm_start();

        return 0;

    } else {


static void colo_old_packet_check(void *opaque)

{

    CompareState *s = opaque;

    g_queue_foreach(&s->conn_list, colo_old_packet_check_one_conn, NULL);

}


int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,

                       uint8_t offset, uint8_t size)

{

    int ret;

    Error *local_err = NULL;

    ret = pci_add_capability2(pdev, cap_id, offset, size, &local_err);

    if (local_err) {

        assert(ret < 0);

        error_report_err(local_err);

    } else {

        /* success implies a positive offset in config space */

        assert(ret > 0);

    }

    return ret;

}


static void write_bootloader(uint8_t *base, int64_t run_addr,

                             int64_t kernel_entry)

{

    uint32_t *p;

    /* Small bootloader */

    p = (uint32_t *)base;

    stl_p(p++, 0x08000000 |                                      /* j 0x1fc00580 */

                 ((run_addr + 0x580) & 0x0fffffff) >> 2);

    stl_p(p++, 0x00000000);                                      /* nop */

    /* YAMON service vector */

    stl_p(base + 0x500, run_addr + 0x0580);      /* start: */

    stl_p(base + 0x504, run_addr + 0x083c);      /* print_count: */

    stl_p(base + 0x520, run_addr + 0x0580);      /* start: */

    stl_p(base + 0x52c, run_addr + 0x0800);      /* flush_cache: */

    stl_p(base + 0x534, run_addr + 0x0808);      /* print: */

    stl_p(base + 0x538, run_addr + 0x0800);      /* reg_cpu_isr: */

    stl_p(base + 0x53c, run_addr + 0x0800);      /* unred_cpu_isr: */

    stl_p(base + 0x540, run_addr + 0x0800);      /* reg_ic_isr: */

    stl_p(base + 0x544, run_addr + 0x0800);      /* unred_ic_isr: */

    stl_p(base + 0x548, run_addr + 0x0800);      /* reg_esr: */

    stl_p(base + 0x54c, run_addr + 0x0800);      /* unreg_esr: */

    stl_p(base + 0x550, run_addr + 0x0800);      /* getchar: */

    stl_p(base + 0x554, run_addr + 0x0800);      /* syscon_read: */

    /* Second part of the bootloader */

    p = (uint32_t *) (base + 0x580);

    if (semihosting_get_argc()) {

        /* Preserve a0 content as arguments have been passed */

        stl_p(p++, 0x00000000);                         /* nop */

    } else {

        stl_p(p++, 0x24040002);                         /* addiu a0, zero, 2 */

    }

    stl_p(p++, 0x3c1d0000 | (((ENVP_ADDR - 64) >> 16) & 0xffff)); /* lui sp, high(ENVP_ADDR) */

    stl_p(p++, 0x37bd0000 | ((ENVP_ADDR - 64) & 0xffff));        /* ori sp, sp, low(ENVP_ADDR) */

    stl_p(p++, 0x3c050000 | ((ENVP_ADDR >> 16) & 0xffff));       /* lui a1, high(ENVP_ADDR) */

    stl_p(p++, 0x34a50000 | (ENVP_ADDR & 0xffff));               /* ori a1, a1, low(ENVP_ADDR) */

    stl_p(p++, 0x3c060000 | (((ENVP_ADDR + 8) >> 16) & 0xffff)); /* lui a2, high(ENVP_ADDR + 8) */

    stl_p(p++, 0x34c60000 | ((ENVP_ADDR + 8) & 0xffff));         /* ori a2, a2, low(ENVP_ADDR + 8) */

    stl_p(p++, 0x3c070000 | (loaderparams.ram_low_size >> 16));     /* lui a3, high(ram_low_size) */

    stl_p(p++, 0x34e70000 | (loaderparams.ram_low_size & 0xffff));  /* ori a3, a3, low(ram_low_size) */

    /* Load BAR registers as done by YAMON */

    stl_p(p++, 0x3c09b400);                                      /* lui t1, 0xb400 */

#ifdef TARGET_WORDS_BIGENDIAN

    stl_p(p++, 0x3c08df00);                                      /* lui t0, 0xdf00 */

#else

    stl_p(p++, 0x340800df);                                      /* ori t0, r0, 0x00df */

#endif

    stl_p(p++, 0xad280068);                                      /* sw t0, 0x0068(t1) */

    stl_p(p++, 0x3c09bbe0);                                      /* lui t1, 0xbbe0 */

#ifdef TARGET_WORDS_BIGENDIAN

    stl_p(p++, 0x3c08c000);                                      /* lui t0, 0xc000 */

#else

    stl_p(p++, 0x340800c0);                                      /* ori t0, r0, 0x00c0 */

#endif

    stl_p(p++, 0xad280048);                                      /* sw t0, 0x0048(t1) */

#ifdef TARGET_WORDS_BIGENDIAN

    stl_p(p++, 0x3c084000);                                      /* lui t0, 0x4000 */

#else

    stl_p(p++, 0x34080040);                                      /* ori t0, r0, 0x0040 */

#endif

    stl_p(p++, 0xad280050);                                      /* sw t0, 0x0050(t1) */

#ifdef TARGET_WORDS_BIGENDIAN

    stl_p(p++, 0x3c088000);                                      /* lui t0, 0x8000 */

#else

    stl_p(p++, 0x34080080);                                      /* ori t0, r0, 0x0080 */

#endif

    stl_p(p++, 0xad280058);                                      /* sw t0, 0x0058(t1) */

#ifdef TARGET_WORDS_BIGENDIAN

    stl_p(p++, 0x3c083f00);                                      /* lui t0, 0x3f00 */

#else

    stl_p(p++, 0x3408003f);                                      /* ori t0, r0, 0x003f */

#endif

    stl_p(p++, 0xad280060);                                      /* sw t0, 0x0060(t1) */

#ifdef TARGET_WORDS_BIGENDIAN

    stl_p(p++, 0x3c08c100);                                      /* lui t0, 0xc100 */

#else

    stl_p(p++, 0x340800c1);                                      /* ori t0, r0, 0x00c1 */

#endif

    stl_p(p++, 0xad280080);                                      /* sw t0, 0x0080(t1) */

#ifdef TARGET_WORDS_BIGENDIAN

    stl_p(p++, 0x3c085e00);                                      /* lui t0, 0x5e00 */

#else

    stl_p(p++, 0x3408005e);                                      /* ori t0, r0, 0x005e */

#endif

    stl_p(p++, 0xad280088);                                      /* sw t0, 0x0088(t1) */

    /* Jump to kernel code */

    stl_p(p++, 0x3c1f0000 | ((kernel_entry >> 16) & 0xffff));    /* lui ra, high(kernel_entry) */

    stl_p(p++, 0x37ff0000 | (kernel_entry & 0xffff));            /* ori ra, ra, low(kernel_entry) */

    stl_p(p++, 0x03e00009);                                      /* jalr ra */

    stl_p(p++, 0x00000000);                                      /* nop */

    /* YAMON subroutines */

    p = (uint32_t *) (base + 0x800);

    stl_p(p++, 0x03e00009);                                     /* jalr ra */

    stl_p(p++, 0x24020000);                                     /* li v0,0 */

    /* 808 YAMON print */

    stl_p(p++, 0x03e06821);                                     /* move t5,ra */

    stl_p(p++, 0x00805821);                                     /* move t3,a0 */

    stl_p(p++, 0x00a05021);                                     /* move t2,a1 */

    stl_p(p++, 0x91440000);                                     /* lbu a0,0(t2) */

    stl_p(p++, 0x254a0001);                                     /* addiu t2,t2,1 */

    stl_p(p++, 0x10800005);                                     /* beqz a0,834 */

    stl_p(p++, 0x00000000);                                     /* nop */

    stl_p(p++, 0x0ff0021c);                                     /* jal 870 */

    stl_p(p++, 0x00000000);                                     /* nop */

    stl_p(p++, 0x08000205);                                     /* j 814 */

    stl_p(p++, 0x00000000);                                     /* nop */

    stl_p(p++, 0x01a00009);                                     /* jalr t5 */

    stl_p(p++, 0x01602021);                                     /* move a0,t3 */

    /* 0x83c YAMON print_count */

    stl_p(p++, 0x03e06821);                                     /* move t5,ra */

    stl_p(p++, 0x00805821);                                     /* move t3,a0 */

    stl_p(p++, 0x00a05021);                                     /* move t2,a1 */

    stl_p(p++, 0x00c06021);                                     /* move t4,a2 */

    stl_p(p++, 0x91440000);                                     /* lbu a0,0(t2) */

    stl_p(p++, 0x0ff0021c);                                     /* jal 870 */

    stl_p(p++, 0x00000000);                                     /* nop */

    stl_p(p++, 0x254a0001);                                     /* addiu t2,t2,1 */

    stl_p(p++, 0x258cffff);                                     /* addiu t4,t4,-1 */

    stl_p(p++, 0x1580fffa);                                     /* bnez t4,84c */

    stl_p(p++, 0x00000000);                                     /* nop */

    stl_p(p++, 0x01a00009);                                     /* jalr t5 */

    stl_p(p++, 0x01602021);                                     /* move a0,t3 */

    /* 0x870 */

    stl_p(p++, 0x3c08b800);                                     /* lui t0,0xb400 */

    stl_p(p++, 0x350803f8);                                     /* ori t0,t0,0x3f8 */

    stl_p(p++, 0x91090005);                                     /* lbu t1,5(t0) */

    stl_p(p++, 0x00000000);                                     /* nop */

    stl_p(p++, 0x31290040);                                     /* andi t1,t1,0x40 */

    stl_p(p++, 0x1120fffc);                                     /* beqz t1,878 <outch+0x8> */

    stl_p(p++, 0x00000000);                                     /* nop */

    stl_p(p++, 0x03e00009);                                     /* jalr ra */

    stl_p(p++, 0xa1040000);                                     /* sb a0,0(t0) */

}


static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)

{

    TCPCharDriver *s = chr->opaque;

    /* clear old pending fd array */

    g_free(s->write_msgfds);

    if (num) {

        s->write_msgfds = g_malloc(num * sizeof(int));

        memcpy(s->write_msgfds, fds, num * sizeof(int));

    }

    s->write_msgfds_num = num;

    return 0;

}


void ff_j2k_cleanup(Jpeg2000Component *comp, Jpeg2000CodingStyle *codsty)

{

    int reslevelno, bandno, precno;

    for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {

        Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;

        for (bandno = 0; bandno < reslevel->nbands; bandno++) {

            Jpeg2000Band *band = reslevel->band + bandno;

            for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++) {

                Jpeg2000Prec *prec = band->prec + precno;

                av_freep(&prec->zerobits);

                av_freep(&prec->cblkincl);

                av_freep(&prec->cblk);

            }

            av_freep(&band->prec);

        }

        av_freep(&reslevel->band);

    }

    ff_dwt_destroy(&comp->dwt);

    av_freep(&comp->reslevel);

    av_freep(&comp->data);

}


static int get_physical_address(CPUState *env, target_phys_addr_t *physical,

                                int *prot, int *access_index,

                                target_ulong address, int rw, int mmu_idx)

{

    int is_user = mmu_idx == MMU_USER_IDX;

    if (rw == 2)

        return get_physical_address_code(env, physical, prot, address,

                                         is_user);

    else

        return get_physical_address_data(env, physical, prot, address, rw,

                                         is_user);

}


void op_flush_icache_all(void) {

    CALL_FROM_TB1(tb_flush, env);

    RETURN();

}


static void test_visitor_in_struct_nested(TestInputVisitorData *data,

                                          const void *unused)

{

    UserDefTwo *udp = NULL;

    Visitor *v;

    v = visitor_input_test_init(data, "{ 'string0': 'string0', "

                                "'dict1': { 'string1': 'string1', "

                                "'dict2': { 'userdef': { 'integer': 42, "

                                "'string': 'string' }, 'string': 'string2'}}}");

    visit_type_UserDefTwo(v, NULL, &udp, &error_abort);

    g_assert_cmpstr(udp->string0, ==, "string0");

    g_assert_cmpstr(udp->dict1->string1, ==, "string1");

    g_assert_cmpint(udp->dict1->dict2->userdef->integer, ==, 42);

    g_assert_cmpstr(udp->dict1->dict2->userdef->string, ==, "string");

    g_assert_cmpstr(udp->dict1->dict2->string, ==, "string2");

    g_assert(udp->dict1->has_dict3 == false);

    qapi_free_UserDefTwo(udp);

}


static void qxl_log_cmd_draw_compat(PCIQXLDevice *qxl, QXLCompatDrawable *draw,

                                    int group_id)

{

    fprintf(stderr, ": type %s effect %s",

            qxl_name(qxl_draw_type, draw->type),

            qxl_name(qxl_draw_effect, draw->effect));

    if (draw->bitmap_offset) {

        fprintf(stderr, ": bitmap %d",

                draw->bitmap_offset);

        qxl_log_rect(&draw->bitmap_area);

    }

    switch (draw->type) {

    case QXL_DRAW_COPY:

        qxl_log_cmd_draw_copy(qxl, &draw->u.copy, group_id);

        break;

    }

}


int apic_init(CPUState *env)

{

    APICState *s;

    if (last_apic_idx >= MAX_APICS)

        return -1;

    s = qemu_mallocz(sizeof(APICState));

    env->apic_state = s;

    s->idx = last_apic_idx++;

    s->id = env->cpuid_apic_id;

    s->cpu_env = env;

    apic_reset(s);

    msix_supported = 1;

    /* XXX: mapping more APICs at the same memory location */

    if (apic_io_memory == 0) {

        /* NOTE: the APIC is directly connected to the CPU - it is not

           on the global memory bus. */

        apic_io_memory = cpu_register_io_memory(apic_mem_read,

                                                apic_mem_write, NULL);

        /* XXX: what if the base changes? */

        cpu_register_physical_memory(MSI_ADDR_BASE, MSI_ADDR_SIZE,

                                     apic_io_memory);

    }

    s->timer = qemu_new_timer(vm_clock, apic_timer, s);

    vmstate_register(s->idx, &vmstate_apic, s);

    qemu_register_reset(apic_reset, s);

    local_apics[s->idx] = s;

    return 0;

}


static Visitor *visitor_input_test_init_internal(TestInputVisitorData *data,

                                                 const char *json_string,

                                                 va_list *ap)

{

    visitor_input_teardown(data, NULL);

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

    g_assert(data->obj);

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

    g_assert(data->qiv);

    return data->qiv;

}


target_ulong helper_rdhwr_cc(CPUMIPSState *env)

{

    if ((env->hflags & MIPS_HFLAG_CP0) ||

        (env->CP0_HWREna & (1 << 2))) {

#ifdef CONFIG_USER_ONLY

        return env->CP0_Count;

#else

        return (int32_t)cpu_mips_get_count(env);

#endif

    } else {

        do_raise_exception(env, EXCP_RI, GETPC());

    }

    return 0;

}


static void prstatfs_to_statfs(struct statfs *stfs, ProxyStatFS *prstfs)

{

    memset(stfs, 0, sizeof(*stfs));

    stfs->f_type = prstfs->f_type;

    stfs->f_bsize = prstfs->f_bsize;

    stfs->f_blocks = prstfs->f_blocks;

    stfs->f_bfree = prstfs->f_bfree;

    stfs->f_bavail = prstfs->f_bavail;

    stfs->f_files = prstfs->f_files;

    stfs->f_ffree = prstfs->f_ffree;

    stfs->f_fsid.__val[0] = prstfs->f_fsid[0] & 0xFFFFFFFFU;

    stfs->f_fsid.__val[1] = prstfs->f_fsid[1] >> 32 & 0xFFFFFFFFU;

    stfs->f_namelen = prstfs->f_namelen;

    stfs->f_frsize = prstfs->f_frsize;

}


static int decode_picture_header(AVCodecContext *avctx, const uint8_t *buf, const int buf_size)

{

    ProresContext *ctx = avctx->priv_data;

    int i, hdr_size, slice_count;

    unsigned pic_data_size;

    int log2_slice_mb_width, log2_slice_mb_height;

    int slice_mb_count, mb_x, mb_y;

    const uint8_t *data_ptr, *index_ptr;

    hdr_size = buf[0] >> 3;

    if (hdr_size < 8 || hdr_size > buf_size) {

        av_log(avctx, AV_LOG_ERROR, "error, wrong picture header size\n");

        return -1;

    }

    pic_data_size = AV_RB32(buf + 1);

    if (pic_data_size > buf_size) {

        av_log(avctx, AV_LOG_ERROR, "error, wrong picture data size\n");

        return -1;

    }

    log2_slice_mb_width  = buf[7] >> 4;

    log2_slice_mb_height = buf[7] & 0xF;

    if (log2_slice_mb_width > 3 || log2_slice_mb_height) {

        av_log(avctx, AV_LOG_ERROR, "unsupported slice resolution: %dx%d\n",

               1 << log2_slice_mb_width, 1 << log2_slice_mb_height);

        return -1;

    }

    ctx->mb_width  = (avctx->width  + 15) >> 4;

    ctx->mb_height = (avctx->height + 15) >> 4;

    slice_count = AV_RB16(buf + 5);

    if (ctx->slice_count != slice_count || !ctx->slices) {

        av_freep(&ctx->slices);

        ctx->slices = av_mallocz(slice_count * sizeof(*ctx->slices));

        if (!ctx->slices)

            return AVERROR(ENOMEM);

        ctx->slice_count = slice_count;

    }

    if (!slice_count)

        return AVERROR(EINVAL);

    if (hdr_size + slice_count*2 > buf_size) {

        av_log(avctx, AV_LOG_ERROR, "error, wrong slice count\n");

        return -1;

    }

    // parse slice information

    index_ptr = buf + hdr_size;

    data_ptr  = index_ptr + slice_count*2;

    slice_mb_count = 1 << log2_slice_mb_width;

    mb_x = 0;

    mb_y = 0;

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

        SliceContext *slice = &ctx->slices[i];

        slice->data = data_ptr;

        data_ptr += AV_RB16(index_ptr + i*2);

        while (ctx->mb_width - mb_x < slice_mb_count)

            slice_mb_count >>= 1;

        slice->mb_x = mb_x;

        slice->mb_y = mb_y;

        slice->mb_count = slice_mb_count;

        slice->data_size = data_ptr - slice->data;

        if (slice->data_size < 6) {

            av_log(avctx, AV_LOG_ERROR, "error, wrong slice data size\n");

            return -1;

        }

        mb_x += slice_mb_count;

        if (mb_x == ctx->mb_width) {

            slice_mb_count = 1 << log2_slice_mb_width;

            mb_x = 0;

            mb_y++;

        }

        if (data_ptr > buf + buf_size) {

            av_log(avctx, AV_LOG_ERROR, "error, slice out of bounds\n");

            return -1;

        }

    }

    return pic_data_size;

}


static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun,

                                     uint8_t *buf, void *hba_private)

{

    SCSIRequest *req;

    req = scsi_req_alloc(&scsi_generic_req_ops, d, tag, lun, hba_private);

    return req;

}


static int kvm_get_xcrs(CPUState *env)

{

#ifdef KVM_CAP_XCRS

    int i, ret;

    struct kvm_xcrs xcrs;

    if (!kvm_has_xcrs())

        return 0;

    ret = kvm_vcpu_ioctl(env, KVM_GET_XCRS, &xcrs);

    if (ret < 0)

        return ret;

    for (i = 0; i < xcrs.nr_xcrs; i++)

        /* Only support xcr0 now */

        if (xcrs.xcrs[0].xcr == 0) {

            env->xcr0 = xcrs.xcrs[0].value;

            break;

        }

    return 0;

#else

    return 0;

#endif

}


static int is_dup_page(uint8_t *page)

{

    VECTYPE *p = (VECTYPE *)page;

    VECTYPE val = SPLAT(page);

    int i;

    for (i = 0; i < TARGET_PAGE_SIZE / sizeof(VECTYPE); i++) {

        if (!ALL_EQ(val, p[i])) {

            return 0;

        }

    }

    return 1;

}


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

{

    sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());

    SysBusDevice *s = SYS_BUS_DEVICE(dev);

    sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(s);

    PCIHostState *phb = PCI_HOST_BRIDGE(s);

    char *namebuf;

    int i;

    PCIBus *bus;

    uint64_t msi_window_size = 4096;

    sPAPRTCETable *tcet;

    const unsigned windows_supported =

        sphb->ddw_enabled ? SPAPR_PCI_DMA_MAX_WINDOWS : 1;

    if (sphb->index != (uint32_t)-1) {

        sPAPRMachineClass *smc = SPAPR_MACHINE_GET_CLASS(spapr);

        Error *local_err = NULL;

        if ((sphb->buid != (uint64_t)-1) || (sphb->dma_liobn[0] != (uint32_t)-1)

            || (sphb->dma_liobn[1] != (uint32_t)-1 && windows_supported == 2)

            || (sphb->mem_win_addr != (hwaddr)-1)

            || (sphb->mem64_win_addr != (hwaddr)-1)

            || (sphb->io_win_addr != (hwaddr)-1)) {

            error_setg(errp, "Either \"index\" or other parameters must"

                       " be specified for PAPR PHB, not both");

            return;

        }

        smc->phb_placement(spapr, sphb->index,

                           &sphb->buid, &sphb->io_win_addr,

                           &sphb->mem_win_addr, &sphb->mem64_win_addr,

                           windows_supported, sphb->dma_liobn, &local_err);

        if (local_err) {

            error_propagate(errp, local_err);

            return;

        }

    }

    if (sphb->buid == (uint64_t)-1) {

        error_setg(errp, "BUID not specified for PHB");

        return;

    }

    if ((sphb->dma_liobn[0] == (uint32_t)-1) ||

        ((sphb->dma_liobn[1] == (uint32_t)-1) && (windows_supported > 1))) {

        error_setg(errp, "LIOBN(s) not specified for PHB");

        return;

    }

    if (sphb->mem_win_addr == (hwaddr)-1) {

        error_setg(errp, "Memory window address not specified for PHB");

        return;

    }

    if (sphb->io_win_addr == (hwaddr)-1) {

        error_setg(errp, "IO window address not specified for PHB");

        return;

    }

    if (sphb->mem64_win_size != 0) {

        if (sphb->mem64_win_addr == (hwaddr)-1) {

            error_setg(errp,

                       "64-bit memory window address not specified for PHB");

            return;

        }

        if (sphb->mem_win_size > SPAPR_PCI_MEM32_WIN_SIZE) {

            error_setg(errp, "32-bit memory window of size 0x%"HWADDR_PRIx

                       " (max 2 GiB)", sphb->mem_win_size);

            return;

        }

        if (sphb->mem64_win_pciaddr == (hwaddr)-1) {

            /* 64-bit window defaults to identity mapping */

            sphb->mem64_win_pciaddr = sphb->mem64_win_addr;

        }

    } else if (sphb->mem_win_size > SPAPR_PCI_MEM32_WIN_SIZE) {

        /*

         * For compatibility with old configuration, if no 64-bit MMIO

         * window is specified, but the ordinary (32-bit) memory

         * window is specified as > 2GiB, we treat it as a 2GiB 32-bit

         * window, with a 64-bit MMIO window following on immediately

         * afterwards

         */

        sphb->mem64_win_size = sphb->mem_win_size - SPAPR_PCI_MEM32_WIN_SIZE;

        sphb->mem64_win_addr = sphb->mem_win_addr + SPAPR_PCI_MEM32_WIN_SIZE;

        sphb->mem64_win_pciaddr =

            SPAPR_PCI_MEM_WIN_BUS_OFFSET + SPAPR_PCI_MEM32_WIN_SIZE;

        sphb->mem_win_size = SPAPR_PCI_MEM32_WIN_SIZE;

    }

    if (spapr_pci_find_phb(spapr, sphb->buid)) {

        error_setg(errp, "PCI host bridges must have unique BUIDs");

        return;

    }

    if (sphb->numa_node != -1 &&

        (sphb->numa_node >= MAX_NODES || !numa_info[sphb->numa_node].present)) {

        error_setg(errp, "Invalid NUMA node ID for PCI host bridge");

        return;

    }

    sphb->dtbusname = g_strdup_printf("pci@%" PRIx64, sphb->buid);

    /* Initialize memory regions */

    namebuf = g_strdup_printf("%s.mmio", sphb->dtbusname);

    memory_region_init(&sphb->memspace, OBJECT(sphb), namebuf, UINT64_MAX);

    g_free(namebuf);

    namebuf = g_strdup_printf("%s.mmio32-alias", sphb->dtbusname);

    memory_region_init_alias(&sphb->mem32window, OBJECT(sphb),

                             namebuf, &sphb->memspace,

                             SPAPR_PCI_MEM_WIN_BUS_OFFSET, sphb->mem_win_size);

    g_free(namebuf);

    memory_region_add_subregion(get_system_memory(), sphb->mem_win_addr,

                                &sphb->mem32window);

    if (sphb->mem64_win_pciaddr != (hwaddr)-1) {

        namebuf = g_strdup_printf("%s.mmio64-alias", sphb->dtbusname);

        memory_region_init_alias(&sphb->mem64window, OBJECT(sphb),

                                 namebuf, &sphb->memspace,

                                 sphb->mem64_win_pciaddr, sphb->mem64_win_size);

        g_free(namebuf);

        if (sphb->mem64_win_addr != (hwaddr)-1) {

            memory_region_add_subregion(get_system_memory(),

                                        sphb->mem64_win_addr,

                                        &sphb->mem64window);

        }

    }

    /* Initialize IO regions */

    namebuf = g_strdup_printf("%s.io", sphb->dtbusname);

    memory_region_init(&sphb->iospace, OBJECT(sphb),

                       namebuf, SPAPR_PCI_IO_WIN_SIZE);

    g_free(namebuf);

    namebuf = g_strdup_printf("%s.io-alias", sphb->dtbusname);

    memory_region_init_alias(&sphb->iowindow, OBJECT(sphb), namebuf,

                             &sphb->iospace, 0, SPAPR_PCI_IO_WIN_SIZE);

    g_free(namebuf);

    memory_region_add_subregion(get_system_memory(), sphb->io_win_addr,

                                &sphb->iowindow);

    bus = pci_register_bus(dev, NULL,

                           pci_spapr_set_irq, pci_spapr_map_irq, sphb,

                           &sphb->memspace, &sphb->iospace,

                           PCI_DEVFN(0, 0), PCI_NUM_PINS, TYPE_PCI_BUS);

    phb->bus = bus;

    qbus_set_hotplug_handler(BUS(phb->bus), DEVICE(sphb), NULL);

    /*

     * Initialize PHB address space.

     * By default there will be at least one subregion for default

     * 32bit DMA window.

     * Later the guest might want to create another DMA window

     * which will become another memory subregion.

     */

    namebuf = g_strdup_printf("%s.iommu-root", sphb->dtbusname);

    memory_region_init(&sphb->iommu_root, OBJECT(sphb),

                       namebuf, UINT64_MAX);

    g_free(namebuf);

    address_space_init(&sphb->iommu_as, &sphb->iommu_root,

                       sphb->dtbusname);

    /*

     * As MSI/MSIX interrupts trigger by writing at MSI/MSIX vectors,

     * we need to allocate some memory to catch those writes coming

     * from msi_notify()/msix_notify().

     * As MSIMessage:addr is going to be the same and MSIMessage:data

     * is going to be a VIRQ number, 4 bytes of the MSI MR will only

     * be used.

     *

     * For KVM we want to ensure that this memory is a full page so that

     * our memory slot is of page size granularity.

     */

#ifdef CONFIG_KVM

    if (kvm_enabled()) {

        msi_window_size = getpagesize();

    }

#endif

    memory_region_init_io(&sphb->msiwindow, OBJECT(sphb), &spapr_msi_ops, spapr,

                          "msi", msi_window_size);

    memory_region_add_subregion(&sphb->iommu_root, SPAPR_PCI_MSI_WINDOW,

                                &sphb->msiwindow);

    pci_setup_iommu(bus, spapr_pci_dma_iommu, sphb);

    pci_bus_set_route_irq_fn(bus, spapr_route_intx_pin_to_irq);

    QLIST_INSERT_HEAD(&spapr->phbs, sphb, list);

    /* Initialize the LSI table */

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

        uint32_t irq;

        Error *local_err = NULL;

        irq = spapr_ics_alloc_block(spapr->ics, 1, true, false, &local_err);

        if (local_err) {

            error_propagate(errp, local_err);

            error_prepend(errp, "can't allocate LSIs: ");

            return;

        }

        sphb->lsi_table[i].irq = irq;

    }

    /* allocate connectors for child PCI devices */

    if (sphb->dr_enabled) {

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

            spapr_dr_connector_new(OBJECT(phb), TYPE_SPAPR_DRC_PCI,

                                   (sphb->index << 16) | i);

        }

    }

    /* DMA setup */

    if (((sphb->page_size_mask & qemu_getrampagesize()) == 0)

        && kvm_enabled()) {

        error_report("System page size 0x%lx is not enabled in page_size_mask "

                     "(0x%"PRIx64"). Performance may be slow",

                     qemu_getrampagesize(), sphb->page_size_mask);

    }

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

        tcet = spapr_tce_new_table(DEVICE(sphb), sphb->dma_liobn[i]);

        if (!tcet) {

            error_setg(errp, "Creating window#%d failed for %s",

                       i, sphb->dtbusname);

            return;

        }

        memory_region_add_subregion(&sphb->iommu_root, 0,

                                    spapr_tce_get_iommu(tcet));

    }

    sphb->msi = g_hash_table_new_full(g_int_hash, g_int_equal, g_free, g_free);

}


static inline int is_sector_in_chunk(BDRVDMGState* s,

		uint32_t chunk_num,int sector_num)

{

    if(chunk_num>=s->n_chunks || s->sectors[chunk_num]>sector_num ||

	    s->sectors[chunk_num]+s->sectorcounts[chunk_num]<=sector_num)

	return 0;

    else

	return -1;

}


void block_job_sleep_ns(BlockJob *job, QEMUClockType type, int64_t ns)

{

    assert(job->busy);

    /* Check cancellation *before* setting busy = false, too!  */

    if (block_job_is_cancelled(job)) {

        return;

    }

    job->busy = false;

    if (block_job_is_paused(job)) {

        qemu_coroutine_yield();

    } else {

        co_aio_sleep_ns(blk_get_aio_context(job->blk), type, ns);

    }

    job->busy = true;

}


void mixeng_clear (st_sample_t *buf, int len)

{

    memset (buf, 0, len * sizeof (st_sample_t));

}


static void slavio_set_timer_irq_cpu(void *opaque, int cpu, int level)

{

    SLAVIO_INTCTLState *s = opaque;

    DPRINTF("Set cpu %d local level %d\n", cpu, level);

    if (!s->cpu_envs[cpu])

        return;

    if (level) {

        s->intreg_pending[cpu] |= s->cputimer_bit;

    } else {

        s->intreg_pending[cpu] &= ~s->cputimer_bit;

    }

    slavio_check_interrupts(s);

}


void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)

{

    if (QTAILQ_EMPTY(&address_spaces)) {

        memory_init();

    }

    memory_region_transaction_begin();

    as->root = root;

    as->current_map = g_new(FlatView, 1);

    flatview_init(as->current_map);

    as->ioeventfd_nb = 0;

    as->ioeventfds = NULL;

    QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);

    as->name = g_strdup(name ? name : "anonymous");

    address_space_init_dispatch(as);

    memory_region_update_pending |= root->enabled;

    memory_region_transaction_commit();

}


int avpriv_dca_parse_core_frame_header(GetBitContext *gb, DCACoreFrameHeader *h)

{

    if (get_bits_long(gb, 32) != DCA_SYNCWORD_CORE_BE)

        return DCA_PARSE_ERROR_SYNC_WORD;

    h->normal_frame = get_bits1(gb);

    h->deficit_samples = get_bits(gb, 5) + 1;

    if (h->deficit_samples != DCA_PCMBLOCK_SAMPLES)

        return DCA_PARSE_ERROR_DEFICIT_SAMPLES;

    h->crc_present = get_bits1(gb);

    h->npcmblocks = get_bits(gb, 7) + 1;

    if (h->npcmblocks & (DCA_SUBBAND_SAMPLES - 1))

        return DCA_PARSE_ERROR_PCM_BLOCKS;

    h->frame_size = get_bits(gb, 14) + 1;

    if (h->frame_size < 96)

        return DCA_PARSE_ERROR_FRAME_SIZE;

    h->audio_mode = get_bits(gb, 6);

    if (h->audio_mode >= DCA_AMODE_COUNT)

        return DCA_PARSE_ERROR_AMODE;

    h->sr_code = get_bits(gb, 4);

    if (!avpriv_dca_sample_rates[h->sr_code])

        return DCA_PARSE_ERROR_SAMPLE_RATE;

    h->br_code = get_bits(gb, 5);

    if (get_bits1(gb))

        return DCA_PARSE_ERROR_RESERVED_BIT;

    h->drc_present = get_bits1(gb);

    h->ts_present = get_bits1(gb);

    h->aux_present = get_bits1(gb);

    h->hdcd_master = get_bits1(gb);

    h->ext_audio_type = get_bits(gb, 3);

    h->ext_audio_present = get_bits1(gb);

    h->sync_ssf = get_bits1(gb);

    h->lfe_present = get_bits(gb, 2);

    if (h->lfe_present == DCA_LFE_FLAG_INVALID)

        return DCA_PARSE_ERROR_LFE_FLAG;

    h->predictor_history = get_bits1(gb);

    if (h->crc_present)

        skip_bits(gb, 16);

    h->filter_perfect = get_bits1(gb);

    h->encoder_rev = get_bits(gb, 4);

    h->copy_hist = get_bits(gb, 2);

    h->pcmr_code = get_bits(gb, 3);

    if (!ff_dca_bits_per_sample[h->pcmr_code])

        return DCA_PARSE_ERROR_PCM_RES;

    h->sumdiff_front = get_bits1(gb);

    h->sumdiff_surround = get_bits1(gb);

    h->dn_code = get_bits(gb, 4);

    return 0;

}


static void padzero(unsigned long elf_bss)

{

        unsigned long nbyte;

        char * fpnt;

        nbyte = elf_bss & (host_page_size-1);	/* was TARGET_PAGE_SIZE - JRP */

        if (nbyte) {

	    nbyte = host_page_size - nbyte;

	    fpnt = (char *) elf_bss;

	    do {

		*fpnt++ = 0;

	    } while (--nbyte);

        }

}


static int vmdk_open(BlockDriverState *bs, int flags)

{

    int ret;

    BDRVVmdkState *s = bs->opaque;

    if (vmdk_open_sparse(bs, bs->file, flags) == 0) {

        s->desc_offset = 0x200;

    } else {

        ret = vmdk_open_desc_file(bs, flags, 0);

        if (ret) {

            goto fail;

        }

    }

    /* try to open parent images, if exist */

    ret = vmdk_parent_open(bs);

    if (ret) {

        goto fail;

    }

    s->parent_cid = vmdk_read_cid(bs, 1);

    qemu_co_mutex_init(&s->lock);

    return ret;

fail:

    vmdk_free_extents(bs);

    return ret;

}


static void coroutine_fn pdu_complete(V9fsPDU *pdu, ssize_t len)

{

    int8_t id = pdu->id + 1; /* Response */

    V9fsState *s = pdu->s;

    if (len < 0) {

        int err = -len;

        len = 7;

        if (s->proto_version != V9FS_PROTO_2000L) {

            V9fsString str;

            str.data = strerror(err);

            str.size = strlen(str.data);

            len += pdu_marshal(pdu, len, "s", &str);

            id = P9_RERROR;

        }

        len += pdu_marshal(pdu, len, "d", err);

        if (s->proto_version == V9FS_PROTO_2000L) {

            id = P9_RLERROR;

        }

        trace_v9fs_rerror(pdu->tag, pdu->id, err); /* Trace ERROR */

    }

    /* fill out the header */

    pdu_marshal(pdu, 0, "dbw", (int32_t)len, id, pdu->tag);

    /* keep these in sync */

    pdu->size = len;

    pdu->id = id;

    pdu_push_and_notify(pdu);

    /* Now wakeup anybody waiting in flush for this request */

    qemu_co_queue_next(&pdu->complete);

    pdu_free(pdu);

}


static QDict *parse_json_filename(const char *filename, Error **errp)

{

    QObject *options_obj;

    QDict *options;

    int ret;

    ret = strstart(filename, "json:", &filename);

    assert(ret);

    options_obj = qobject_from_json(filename);

    if (!options_obj) {

        error_setg(errp, "Could not parse the JSON options");

        return NULL;

    }

    if (qobject_type(options_obj) != QTYPE_QDICT) {

        qobject_decref(options_obj);

        error_setg(errp, "Invalid JSON object given");

        return NULL;

    }

    options = qobject_to_qdict(options_obj);

    qdict_flatten(options);

    return options;

}


static void gen_rlwnm(DisasContext *ctx)

{

    uint32_t mb, me;

    mb = MB(ctx->opcode);

    me = ME(ctx->opcode);

    if (likely(mb == 0 && me == 31)) {

        TCGv_i32 t0, t1;

        t0 = tcg_temp_new_i32();

        t1 = tcg_temp_new_i32();

        tcg_gen_trunc_tl_i32(t0, cpu_gpr[rB(ctx->opcode)]);

        tcg_gen_trunc_tl_i32(t1, cpu_gpr[rS(ctx->opcode)]);

        tcg_gen_andi_i32(t0, t0, 0x1f);

        tcg_gen_rotl_i32(t1, t1, t0);

        tcg_gen_extu_i32_tl(cpu_gpr[rA(ctx->opcode)], t1);

        tcg_temp_free_i32(t0);

        tcg_temp_free_i32(t1);

    } else {

        TCGv t0;

#if defined(TARGET_PPC64)

        TCGv t1;

#endif

        t0 = tcg_temp_new();

        tcg_gen_andi_tl(t0, cpu_gpr[rB(ctx->opcode)], 0x1f);

#if defined(TARGET_PPC64)

        t1 = tcg_temp_new_i64();

        tcg_gen_deposit_i64(t1, cpu_gpr[rS(ctx->opcode)],

                            cpu_gpr[rS(ctx->opcode)], 32, 32);

        tcg_gen_rotl_i64(t0, t1, t0);

        tcg_temp_free_i64(t1);

#else

        tcg_gen_rotl_i32(t0, cpu_gpr[rS(ctx->opcode)], t0);

#endif

        if (unlikely(mb != 0 || me != 31)) {

#if defined(TARGET_PPC64)

            mb += 32;

            me += 32;

#endif

            tcg_gen_andi_tl(cpu_gpr[rA(ctx->opcode)], t0, MASK(mb, me));

        } else {

            tcg_gen_andi_tl(t0, t0, MASK(32, 63));

            tcg_gen_mov_tl(cpu_gpr[rA(ctx->opcode)], t0);

        }

        tcg_temp_free(t0);

    }

    if (unlikely(Rc(ctx->opcode) != 0))

        gen_set_Rc0(ctx, cpu_gpr[rA(ctx->opcode)]);

}


static void test_native_list(TestOutputVisitorData *data,

                             const void *unused,

                             UserDefNativeListUnionKind kind)

{

    UserDefNativeListUnion *cvalue = g_new0(UserDefNativeListUnion, 1);

    QObject *obj;

    cvalue->type = kind;

    init_native_list(cvalue);

    visit_type_UserDefNativeListUnion(data->ov, NULL, &cvalue, &error_abort);

    obj = visitor_get(data);

    check_native_list(obj, cvalue->type);

    qapi_free_UserDefNativeListUnion(cvalue);

}


static void FUNCC(pred8x8l_horizontal_add)(uint8_t *_pix, const int16_t *_block,

                                           ptrdiff_t stride)

{

    int i;

    pixel *pix = (pixel*)_pix;

    const dctcoef *block = (const dctcoef*)_block;

    stride >>= sizeof(pixel)-1;

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

        pixel v = pix[-1];

        pix[0]= v += block[0];

        pix[1]= v += block[1];

        pix[2]= v += block[2];

        pix[3]= v += block[3];

        pix[4]= v += block[4];

        pix[5]= v += block[5];

        pix[6]= v += block[6];

        pix[7]= v +  block[7];

        pix+= stride;

        block+= 8;

    }

}


static int vtenc_create_encoder(AVCodecContext   *avctx,

                                CMVideoCodecType codec_type,

                                CFStringRef      profile_level,

                                CFNumberRef      gamma_level,

                                CFDictionaryRef  enc_info,

                                CFDictionaryRef  pixel_buffer_info,

                                VTCompressionSessionRef *session)

{

    VTEncContext *vtctx = avctx->priv_data;

    SInt32       bit_rate = avctx->bit_rate;

    CFNumberRef  bit_rate_num;

    int status = VTCompressionSessionCreate(kCFAllocatorDefault,

                                            avctx->width,

                                            avctx->height,

                                            codec_type,

                                            enc_info,

                                            pixel_buffer_info,

                                            kCFAllocatorDefault,

                                            vtenc_output_callback,

                                            avctx,

                                            session);

    if (status || !vtctx->session) {

        av_log(avctx, AV_LOG_ERROR, "Error: cannot create compression session: %d\n", status);

#if !TARGET_OS_IPHONE

        if (!vtctx->allow_sw) {

            av_log(avctx, AV_LOG_ERROR, "Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");

        }

#endif

        return AVERROR_EXTERNAL;

    }

    bit_rate_num = CFNumberCreate(kCFAllocatorDefault,

                                  kCFNumberSInt32Type,

                                  &bit_rate);

    if (!bit_rate_num) return AVERROR(ENOMEM);

    status = VTSessionSetProperty(vtctx->session,

                                  kVTCompressionPropertyKey_AverageBitRate,

                                  bit_rate_num);

    CFRelease(bit_rate_num);

    if (status) {

        av_log(avctx, AV_LOG_ERROR, "Error setting bitrate property: %d\n", status);

        return AVERROR_EXTERNAL;

    }

    if (profile_level) {

        status = VTSessionSetProperty(vtctx->session,

                                      kVTCompressionPropertyKey_ProfileLevel,

                                      profile_level);

        if (status) {

            av_log(avctx, AV_LOG_ERROR, "Error setting profile/level property: %d\n", status);

            return AVERROR_EXTERNAL;

        }

    }

    if (avctx->gop_size > 0) {

        CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,

                                              kCFNumberIntType,

                                              &avctx->gop_size);

        if (!interval) {

            return AVERROR(ENOMEM);

        }

        status = VTSessionSetProperty(vtctx->session,

                                      kVTCompressionPropertyKey_MaxKeyFrameInterval,

                                      interval);

        CFRelease(interval);

        if (status) {

            av_log(avctx, AV_LOG_ERROR, "Error setting 'max key-frame interval' property: %d\n", status);

            return AVERROR_EXTERNAL;

        }

    }

    if (vtctx->frames_before) {

        status = VTSessionSetProperty(vtctx->session,

                                      kVTCompressionPropertyKey_MoreFramesBeforeStart,

                                      kCFBooleanTrue);

        if (status == kVTPropertyNotSupportedErr) {

            av_log(avctx, AV_LOG_WARNING, "frames_before property is not supported on this device. Ignoring.\n");

        } else if (status) {

            av_log(avctx, AV_LOG_ERROR, "Error setting frames_before property: %d\n", status);

        }

    }

    if (vtctx->frames_after) {

        status = VTSessionSetProperty(vtctx->session,

                                      kVTCompressionPropertyKey_MoreFramesAfterEnd,

                                      kCFBooleanTrue);

        if (status == kVTPropertyNotSupportedErr) {

            av_log(avctx, AV_LOG_WARNING, "frames_after property is not supported on this device. Ignoring.\n");

        } else if (status) {

            av_log(avctx, AV_LOG_ERROR, "Error setting frames_after property: %d\n", status);

        }

    }

    if (avctx->sample_aspect_ratio.num != 0) {

        CFNumberRef num;

        CFNumberRef den;

        CFMutableDictionaryRef par;

        AVRational *avpar = &avctx->sample_aspect_ratio;

        av_reduce(&avpar->num, &avpar->den,

                   avpar->num,  avpar->den,

                  0xFFFFFFFF);

        num = CFNumberCreate(kCFAllocatorDefault,

                             kCFNumberIntType,

                             &avpar->num);

        den = CFNumberCreate(kCFAllocatorDefault,

                             kCFNumberIntType,

                             &avpar->den);

        par = CFDictionaryCreateMutable(kCFAllocatorDefault,

                                        2,

                                        &kCFCopyStringDictionaryKeyCallBacks,

                                        &kCFTypeDictionaryValueCallBacks);

        if (!par || !num || !den) {

            if (par) CFRelease(par);

            if (num) CFRelease(num);

            if (den) CFRelease(den);

            return AVERROR(ENOMEM);

        }

        CFDictionarySetValue(

            par,

            kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,

            num);

        CFDictionarySetValue(

            par,

            kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,

            den);

        status = VTSessionSetProperty(vtctx->session,

                                      kVTCompressionPropertyKey_PixelAspectRatio,

                                      par);

        CFRelease(par);

        CFRelease(num);

        CFRelease(den);

        if (status) {

            av_log(avctx,

                   AV_LOG_ERROR,

                   "Error setting pixel aspect ratio to %d:%d: %d.\n",

                   avctx->sample_aspect_ratio.num,

                   avctx->sample_aspect_ratio.den,

                   status);

            return AVERROR_EXTERNAL;

        }

    }

    if (vtctx->transfer_function) {

        status = VTSessionSetProperty(vtctx->session,

                                      kVTCompressionPropertyKey_TransferFunction,

                                      vtctx->transfer_function);

        if (status) {

            av_log(avctx, AV_LOG_WARNING, "Could not set transfer function: %d\n", status);

        }

    }

    if (vtctx->ycbcr_matrix) {

        status = VTSessionSetProperty(vtctx->session,

                                      kVTCompressionPropertyKey_YCbCrMatrix,

                                      vtctx->ycbcr_matrix);

        if (status) {

            av_log(avctx, AV_LOG_WARNING, "Could not set ycbcr matrix: %d\n", status);

        }

    }

    if (vtctx->color_primaries) {

        status = VTSessionSetProperty(vtctx->session,

                                      kVTCompressionPropertyKey_ColorPrimaries,

                                      vtctx->color_primaries);

        if (status) {

            av_log(avctx, AV_LOG_WARNING, "Could not set color primaries: %d\n", status);

        }

    }

    if (gamma_level) {

        status = VTSessionSetProperty(vtctx->session,

                                      kCVImageBufferGammaLevelKey,

                                      gamma_level);

        if (status) {

            av_log(avctx, AV_LOG_WARNING, "Could not set gamma level: %d\n", status);

        }

    }

    if (!vtctx->has_b_frames) {

        status = VTSessionSetProperty(vtctx->session,

                                      kVTCompressionPropertyKey_AllowFrameReordering,

                                      kCFBooleanFalse);

        if (status) {

            av_log(avctx, AV_LOG_ERROR, "Error setting 'allow frame reordering' property: %d\n", status);

            return AVERROR_EXTERNAL;

        }

    }

    if (vtctx->entropy != VT_ENTROPY_NOT_SET) {

        CFStringRef entropy = vtctx->entropy == VT_CABAC ?

                                kVTH264EntropyMode_CABAC:

                                kVTH264EntropyMode_CAVLC;

        status = VTSessionSetProperty(vtctx->session,

                                      kVTCompressionPropertyKey_H264EntropyMode,

                                      entropy);

        if (status) {

            av_log(avctx, AV_LOG_ERROR, "Error setting entropy property: %d\n", status);

            return AVERROR_EXTERNAL;

        }

    }

    if (vtctx->realtime) {

        status = VTSessionSetProperty(vtctx->session,

                                      kVTCompressionPropertyKey_RealTime,

                                      kCFBooleanTrue);

        if (status) {

            av_log(avctx, AV_LOG_ERROR, "Error setting realtime property: %d\n", status);

        }

    }

    status = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);

    if (status) {

        av_log(avctx, AV_LOG_ERROR, "Error: cannot prepare encoder: %d\n", status);

        return AVERROR_EXTERNAL;

    }

    return 0;

}


static av_cold int libspeex_decode_init(AVCodecContext *avctx)

{

    LibSpeexContext *s = avctx->priv_data;

    const SpeexMode *mode;

    // defaults in the case of a missing header

    if (avctx->sample_rate <= 8000)

        mode = &speex_nb_mode;

    else if (avctx->sample_rate <= 16000)

        mode = &speex_wb_mode;

    else

        mode = &speex_uwb_mode;

    if (avctx->extradata_size >= 80)

        s->header = speex_packet_to_header(avctx->extradata, avctx->extradata_size);

    avctx->sample_fmt = AV_SAMPLE_FMT_S16;

    if (s->header) {

        avctx->sample_rate = s->header->rate;

        avctx->channels    = s->header->nb_channels;

        s->frame_size      = s->header->frame_size;

        mode = speex_lib_get_mode(s->header->mode);

        if (!mode) {

            av_log(avctx, AV_LOG_ERROR, "Unknown Speex mode %d", s->header->mode);

            return AVERROR_INVALIDDATA;

        }

    } else

        av_log(avctx, AV_LOG_INFO, "Missing Speex header, assuming defaults.\n");

    if (avctx->channels > 2) {

        av_log(avctx, AV_LOG_ERROR, "Only stereo and mono are supported.\n");

        return AVERROR(EINVAL);

    }

    speex_bits_init(&s->bits);

    s->dec_state = speex_decoder_init(mode);

    if (!s->dec_state) {

        av_log(avctx, AV_LOG_ERROR, "Error initializing libspeex decoder.\n");

        return -1;

    }

    if (!s->header) {

        speex_decoder_ctl(s->dec_state, SPEEX_GET_FRAME_SIZE, &s->frame_size);

    }

    if (avctx->channels == 2) {

        SpeexCallback callback;

        callback.callback_id = SPEEX_INBAND_STEREO;

        callback.func = speex_std_stereo_request_handler;

        callback.data = &s->stereo;

        s->stereo = (SpeexStereoState)SPEEX_STEREO_STATE_INIT;

        speex_decoder_ctl(s->dec_state, SPEEX_SET_HANDLER, &callback);

    }

    avcodec_get_frame_defaults(&s->frame);

    avctx->coded_frame = &s->frame;

    return 0;

}


static int mpegts_set_stream_info(AVStream *st, PESContext *pes,

                                  uint32_t stream_type, uint32_t prog_reg_desc)

{

    int old_codec_type= st->codec->codec_type;

    int old_codec_id  = st->codec->codec_id;

    if (old_codec_id != AV_CODEC_ID_NONE && avcodec_is_open(st->codec)) {

        av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");

        return 0;

    }

    avpriv_set_pts_info(st, 33, 1, 90000);

    st->priv_data = pes;

    st->codec->codec_type = AVMEDIA_TYPE_DATA;

    st->codec->codec_id   = AV_CODEC_ID_NONE;

    st->need_parsing = AVSTREAM_PARSE_FULL;

    pes->st = st;

    pes->stream_type = stream_type;

    av_log(pes->stream, AV_LOG_DEBUG,

           "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",

           st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);

    st->codec->codec_tag = pes->stream_type;

    mpegts_find_stream_type(st, pes->stream_type, ISO_types);

    if ((prog_reg_desc == AV_RL32("HDMV") ||

         prog_reg_desc == AV_RL32("HDPR")) &&

        st->codec->codec_id == AV_CODEC_ID_NONE) {

        mpegts_find_stream_type(st, pes->stream_type, HDMV_types);

        if (pes->stream_type == 0x83) {

            // HDMV TrueHD streams also contain an AC3 coded version of the

            // audio track - add a second stream for this

            AVStream *sub_st;

            // priv_data cannot be shared between streams

            PESContext *sub_pes = av_malloc(sizeof(*sub_pes));

            if (!sub_pes)

                return AVERROR(ENOMEM);

            memcpy(sub_pes, pes, sizeof(*sub_pes));

            sub_st = avformat_new_stream(pes->stream, NULL);

            if (!sub_st) {

                av_free(sub_pes);

                return AVERROR(ENOMEM);

            }

            sub_st->id = pes->pid;

            avpriv_set_pts_info(sub_st, 33, 1, 90000);

            sub_st->priv_data = sub_pes;

            sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

            sub_st->codec->codec_id   = AV_CODEC_ID_AC3;

            sub_st->need_parsing = AVSTREAM_PARSE_FULL;

            sub_pes->sub_st = pes->sub_st = sub_st;

        }

    }

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

        mpegts_find_stream_type(st, pes->stream_type, MISC_types);

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

        st->codec->codec_id  = old_codec_id;

        st->codec->codec_type= old_codec_type;

    }

    return 0;

}


void ff_cavs_init_top_lines(AVSContext *h) {

    /* alloc top line of predictors */

    h->top_qp       = av_malloc( h->mb_width);

    h->top_mv[0]    = av_malloc((h->mb_width*2+1)*sizeof(cavs_vector));

    h->top_mv[1]    = av_malloc((h->mb_width*2+1)*sizeof(cavs_vector));

    h->top_pred_Y   = av_malloc( h->mb_width*2*sizeof(*h->top_pred_Y));

    h->top_border_y = av_malloc((h->mb_width+1)*16);

    h->top_border_u = av_malloc( h->mb_width * 10);

    h->top_border_v = av_malloc( h->mb_width * 10);

    /* alloc space for co-located MVs and types */

    h->col_mv       = av_malloc( h->mb_width*h->mb_height*4*sizeof(cavs_vector));

    h->col_type_base = av_malloc(h->mb_width*h->mb_height);

    h->block        = av_mallocz(64*sizeof(DCTELEM));

}


static void gen_dmfc0 (CPUState *env, DisasContext *ctx, int reg, int sel)

{

    const char *rn = "invalid";

    if (sel != 0)

        check_insn(env, ctx, ISA_MIPS64);

    switch (reg) {

    case 0:

        switch (sel) {

        case 0:

            gen_op_mfc0_index();

            rn = "Index";

            break;

        case 1:

            check_mips_mt(env, ctx);

            gen_op_mfc0_mvpcontrol();

            rn = "MVPControl";

            break;

        case 2:

            check_mips_mt(env, ctx);

            gen_op_mfc0_mvpconf0();

            rn = "MVPConf0";

            break;

        case 3:

            check_mips_mt(env, ctx);

            gen_op_mfc0_mvpconf1();

            rn = "MVPConf1";

            break;

        default:

            goto die;

        }

        break;

    case 1:

        switch (sel) {

        case 0:

            gen_op_mfc0_random();

            rn = "Random";

            break;

        case 1:

            check_mips_mt(env, ctx);

            gen_op_mfc0_vpecontrol();

            rn = "VPEControl";

            break;

        case 2:

            check_mips_mt(env, ctx);

            gen_op_mfc0_vpeconf0();

            rn = "VPEConf0";

            break;

        case 3:

            check_mips_mt(env, ctx);

            gen_op_mfc0_vpeconf1();

            rn = "VPEConf1";

            break;

        case 4:

            check_mips_mt(env, ctx);

            gen_op_dmfc0_yqmask();

            rn = "YQMask";

            break;

        case 5:

            check_mips_mt(env, ctx);

            gen_op_dmfc0_vpeschedule();

            rn = "VPESchedule";

            break;

        case 6:

            check_mips_mt(env, ctx);

            gen_op_dmfc0_vpeschefback();

            rn = "VPEScheFBack";

            break;

        case 7:

            check_mips_mt(env, ctx);

            gen_op_mfc0_vpeopt();

            rn = "VPEOpt";

            break;

        default:

            goto die;

        }

        break;

    case 2:

        switch (sel) {

        case 0:

            gen_op_dmfc0_entrylo0();

            rn = "EntryLo0";

            break;

        case 1:

            check_mips_mt(env, ctx);

            gen_op_mfc0_tcstatus();

            rn = "TCStatus";

            break;

        case 2:

            check_mips_mt(env, ctx);

            gen_op_mfc0_tcbind();

            rn = "TCBind";

            break;

        case 3:

            check_mips_mt(env, ctx);

            gen_op_dmfc0_tcrestart();

            rn = "TCRestart";

            break;

        case 4:

            check_mips_mt(env, ctx);

            gen_op_dmfc0_tchalt();

            rn = "TCHalt";

            break;

        case 5:

            check_mips_mt(env, ctx);

            gen_op_dmfc0_tccontext();

            rn = "TCContext";

            break;

        case 6:

            check_mips_mt(env, ctx);

            gen_op_dmfc0_tcschedule();

            rn = "TCSchedule";

            break;

        case 7:

            check_mips_mt(env, ctx);

            gen_op_dmfc0_tcschefback();

            rn = "TCScheFBack";

            break;

        default:

            goto die;

        }

        break;

    case 3:

        switch (sel) {

        case 0:

            gen_op_dmfc0_entrylo1();

            rn = "EntryLo1";

            break;

        default:

            goto die;

        }

        break;

    case 4:

        switch (sel) {

        case 0:

            gen_op_dmfc0_context();

            rn = "Context";

            break;

        case 1:

//            gen_op_dmfc0_contextconfig(); /* SmartMIPS ASE */

            rn = "ContextConfig";

//            break;

        default:

            goto die;

        }

        break;

    case 5:

        switch (sel) {

        case 0:

            gen_op_mfc0_pagemask();

            rn = "PageMask";

            break;

        case 1:

            check_insn(env, ctx, ISA_MIPS32R2);

            gen_op_mfc0_pagegrain();

            rn = "PageGrain";

            break;

        default:

            goto die;

        }

        break;

    case 6:

        switch (sel) {

        case 0:

            gen_op_mfc0_wired();

            rn = "Wired";

            break;

        case 1:

            check_insn(env, ctx, ISA_MIPS32R2);

            gen_op_mfc0_srsconf0();

            rn = "SRSConf0";

            break;

        case 2:

            check_insn(env, ctx, ISA_MIPS32R2);

            gen_op_mfc0_srsconf1();

            rn = "SRSConf1";

            break;

        case 3:

            check_insn(env, ctx, ISA_MIPS32R2);

            gen_op_mfc0_srsconf2();

            rn = "SRSConf2";

            break;

        case 4:

            check_insn(env, ctx, ISA_MIPS32R2);

            gen_op_mfc0_srsconf3();

            rn = "SRSConf3";

            break;

        case 5:

            check_insn(env, ctx, ISA_MIPS32R2);

            gen_op_mfc0_srsconf4();

            rn = "SRSConf4";

            break;

        default:

            goto die;

        }

        break;

    case 7:

        switch (sel) {

        case 0:

            check_insn(env, ctx, ISA_MIPS32R2);

            gen_op_mfc0_hwrena();

            rn = "HWREna";

            break;

        default:

            goto die;

        }

        break;

    case 8:

        switch (sel) {

        case 0:

            gen_op_dmfc0_badvaddr();

            rn = "BadVaddr";

            break;

        default:

            goto die;

        }

        break;

    case 9:

        switch (sel) {

        case 0:

            gen_op_mfc0_count();

            rn = "Count";

            break;

        /* 6,7 are implementation dependent */

        default:

            goto die;

        }

        break;

    case 10:

        switch (sel) {

        case 0:

            gen_op_dmfc0_entryhi();

            rn = "EntryHi";

            break;

        default:

            goto die;

        }

        break;

    case 11:

        switch (sel) {

        case 0:

            gen_op_mfc0_compare();

            rn = "Compare";

            break;

        /* 6,7 are implementation dependent */

        default:

            goto die;

        }

        break;

    case 12:

        switch (sel) {

        case 0:

            gen_op_mfc0_status();

            rn = "Status";

            break;

        case 1:

            check_insn(env, ctx, ISA_MIPS32R2);

            gen_op_mfc0_intctl();

            rn = "IntCtl";

            break;

        case 2:

            check_insn(env, ctx, ISA_MIPS32R2);

            gen_op_mfc0_srsctl();

            rn = "SRSCtl";

            break;

        case 3:

            check_insn(env, ctx, ISA_MIPS32R2);

            gen_op_mfc0_srsmap();

            rn = "SRSMap";

            break;

        default:

            goto die;

        }

        break;

    case 13:

        switch (sel) {

        case 0:

            gen_op_mfc0_cause();

            rn = "Cause";

            break;

        default:

            goto die;

        }

        break;

    case 14:

        switch (sel) {

        case 0:

            gen_op_dmfc0_epc();

            rn = "EPC";

            break;

        default:

            goto die;

        }

        break;

    case 15:

        switch (sel) {

        case 0:

            gen_op_mfc0_prid();

            rn = "PRid";

            break;

        case 1:

            check_insn(env, ctx, ISA_MIPS32R2);

            gen_op_mfc0_ebase();

            rn = "EBase";

            break;

        default:

            goto die;

        }

        break;

    case 16:

        switch (sel) {

        case 0:

            gen_op_mfc0_config0();

            rn = "Config";

            break;

        case 1:

            gen_op_mfc0_config1();

            rn = "Config1";

            break;

        case 2:

            gen_op_mfc0_config2();

            rn = "Config2";

            break;

        case 3:

            gen_op_mfc0_config3();

            rn = "Config3";

            break;

       /* 6,7 are implementation dependent */

        default:

            goto die;

        }

        break;

    case 17:

        switch (sel) {

        case 0:

            gen_op_dmfc0_lladdr();

            rn = "LLAddr";

            break;

        default:

            goto die;

        }

        break;

    case 18:

        switch (sel) {

        case 0 ... 7:

            gen_op_dmfc0_watchlo(sel);

            rn = "WatchLo";

            break;

        default:

            goto die;

        }

        break;

    case 19:

        switch (sel) {

        case 0 ... 7:

            gen_op_mfc0_watchhi(sel);

            rn = "WatchHi";

            break;

        default:

            goto die;

        }

        break;

    case 20:

        switch (sel) {

        case 0:

            check_insn(env, ctx, ISA_MIPS3);

            gen_op_dmfc0_xcontext();

            rn = "XContext";

            break;

        default:

            goto die;

        }

        break;

    case 21:

       /* Officially reserved, but sel 0 is used for R1x000 framemask */

        switch (sel) {

        case 0:

            gen_op_mfc0_framemask();

            rn = "Framemask";

            break;

        default:

            goto die;

        }

        break;

    case 22:

        /* ignored */

        rn = "'Diagnostic"; /* implementation dependent */

        break;

    case 23:

        switch (sel) {

        case 0:

            gen_op_mfc0_debug(); /* EJTAG support */

            rn = "Debug";

            break;

        case 1:

//            gen_op_dmfc0_tracecontrol(); /* PDtrace support */

            rn = "TraceControl";

//            break;

        case 2:

//            gen_op_dmfc0_tracecontrol2(); /* PDtrace support */

            rn = "TraceControl2";

//            break;

        case 3:

//            gen_op_dmfc0_usertracedata(); /* PDtrace support */

            rn = "UserTraceData";

//            break;

        case 4:

//            gen_op_dmfc0_debug(); /* PDtrace support */

            rn = "TraceBPC";

//            break;

        default:

            goto die;

        }

        break;

    case 24:

        switch (sel) {

        case 0:

            gen_op_dmfc0_depc(); /* EJTAG support */

            rn = "DEPC";

            break;

        default:

            goto die;

        }

        break;

    case 25:

        switch (sel) {

        case 0:

            gen_op_mfc0_performance0();

            rn = "Performance0";

            break;

        case 1:

//            gen_op_dmfc0_performance1();

            rn = "Performance1";

//            break;

        case 2:

//            gen_op_dmfc0_performance2();

            rn = "Performance2";

//            break;

        case 3:

//            gen_op_dmfc0_performance3();

            rn = "Performance3";

//            break;

        case 4:

//            gen_op_dmfc0_performance4();

            rn = "Performance4";

//            break;

        case 5:

//            gen_op_dmfc0_performance5();

            rn = "Performance5";

//            break;

        case 6:

//            gen_op_dmfc0_performance6();

            rn = "Performance6";

//            break;

        case 7:

//            gen_op_dmfc0_performance7();

            rn = "Performance7";

//            break;

        default:

            goto die;

        }

        break;

    case 26:

       rn = "ECC";

       break;

    case 27:

        switch (sel) {

        /* ignored */

        case 0 ... 3:

            rn = "CacheErr";

            break;

        default:

            goto die;

        }

        break;

    case 28:

        switch (sel) {

        case 0:

        case 2:

        case 4:

        case 6:

            gen_op_mfc0_taglo();

            rn = "TagLo";

            break;

        case 1:

        case 3:

        case 5:

        case 7:

            gen_op_mfc0_datalo();

            rn = "DataLo";

            break;

        default:

            goto die;

        }

        break;

    case 29:

        switch (sel) {

        case 0:

        case 2:

        case 4:

        case 6:

            gen_op_mfc0_taghi();

            rn = "TagHi";

            break;

        case 1:

        case 3:

        case 5:

        case 7:

            gen_op_mfc0_datahi();

            rn = "DataHi";

            break;

        default:

            goto die;

        }

        break;

    case 30:

        switch (sel) {

        case 0:

            gen_op_dmfc0_errorepc();

            rn = "ErrorEPC";

            break;

        default:

            goto die;

        }

        break;

    case 31:

        switch (sel) {

        case 0:

            gen_op_mfc0_desave(); /* EJTAG support */

            rn = "DESAVE";

            break;

        default:

            goto die;

        }

        break;

    default:

        goto die;

    }

#if defined MIPS_DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_IN_ASM) {

        fprintf(logfile, "dmfc0 %s (reg %d sel %d)\n",

                rn, reg, sel);

    }

#endif

    return;

die:

#if defined MIPS_DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_IN_ASM) {

        fprintf(logfile, "dmfc0 %s (reg %d sel %d)\n",

                rn, reg, sel);

    }

#endif

    generate_exception(ctx, EXCP_RI);

}


static BlockBackend *img_open(const char *id, const char *filename,

                              const char *fmt, int flags,

                              bool require_io, bool quiet)

{

    BlockBackend *blk;

    BlockDriverState *bs;

    char password[256];

    Error *local_err = NULL;

    QDict *options = NULL;

    if (fmt) {

        options = qdict_new();

        qdict_put(options, "driver", qstring_from_str(fmt));

    }

    blk = blk_new_open(id, filename, NULL, options, flags, &local_err);

    if (!blk) {

        error_report("Could not open '%s': %s", filename,

                     error_get_pretty(local_err));

        error_free(local_err);

        goto fail;

    }

    bs = blk_bs(blk);

    if (bdrv_is_encrypted(bs) && require_io) {

        qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);

        if (read_password(password, sizeof(password)) < 0) {

            error_report("No password given");

            goto fail;

        }

        if (bdrv_set_key(bs, password) < 0) {

            error_report("invalid password");

            goto fail;

        }

    }

    return blk;

fail:

    blk_unref(blk);

    return NULL;

}


static void do_boot_set(Monitor *mon, const QDict *qdict)

{

    int res;

    const char *bootdevice = qdict_get_str(qdict, "bootdevice");

    res = qemu_boot_set(bootdevice);

    if (res == 0) {

        monitor_printf(mon, "boot device list now set to %s\n", bootdevice);

    } else if (res > 0) {

        monitor_printf(mon, "setting boot device list failed\n");

    } else {

        monitor_printf(mon, "no function defined to set boot device list for "

                       "this architecture\n");

    }

}


void restore_state_to_opc(CPUARMState *env, TranslationBlock *tb, int pc_pos)

{

    if (is_a64(env)) {

        env->pc = tcg_ctx.gen_opc_pc[pc_pos];

    } else {

        env->regs[15] = tcg_ctx.gen_opc_pc[pc_pos];

    }

    env->condexec_bits = gen_opc_condexec_bits[pc_pos];

}


void kvm_set_phys_mem(target_phys_addr_t start_addr,

                      ram_addr_t size,

                      ram_addr_t phys_offset)

{

    KVMState *s = kvm_state;

    ram_addr_t flags = phys_offset & ~TARGET_PAGE_MASK;

    KVMSlot *mem;

    /* KVM does not support read-only slots */

    phys_offset &= ~IO_MEM_ROM;

    mem = kvm_lookup_slot(s, start_addr);

    if (mem) {

        if (flags == IO_MEM_UNASSIGNED) {

            mem->memory_size = 0;

            mem->guest_phys_addr = start_addr;

            mem->userspace_addr = 0;

            mem->flags = 0;

            kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, mem);

        } else if (start_addr >= mem->guest_phys_addr &&

                   (start_addr + size) <= (mem->guest_phys_addr + mem->memory_size))

            return;

    }

    /* KVM does not need to know about this memory */

    if (flags >= IO_MEM_UNASSIGNED)

        return;

    mem = kvm_alloc_slot(s);

    mem->memory_size = size;

    mem->guest_phys_addr = start_addr;

    mem->userspace_addr = (unsigned long)(phys_ram_base + phys_offset);

    mem->flags = 0;

    kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, mem);

    /* FIXME deal with errors */

}


static int virtio_pci_set_host_notifier(void *opaque, int n, bool assign)

{

    VirtIOPCIProxy *proxy = opaque;

    VirtQueue *vq = virtio_get_queue(proxy->vdev, n);

    EventNotifier *notifier = virtio_queue_get_host_notifier(vq);

    int r;

    if (assign) {

        r = event_notifier_init(notifier, 1);

        if (r < 0) {

            return r;

        }

        r = kvm_set_ioeventfd_pio_word(event_notifier_get_fd(notifier),

                                       proxy->addr + VIRTIO_PCI_QUEUE_NOTIFY,

                                       n, assign);

        if (r < 0) {

            event_notifier_cleanup(notifier);

        }

    } else {

        r = kvm_set_ioeventfd_pio_word(event_notifier_get_fd(notifier),

                                       proxy->addr + VIRTIO_PCI_QUEUE_NOTIFY,

                                       n, assign);

        if (r < 0) {

            return r;

        }

        event_notifier_cleanup(notifier);

    }

    return r;

}


static inline void neon_load_reg64(TCGv var, int reg)

{

    tcg_gen_ld_i64(var, cpu_env, vfp_reg_offset(1, reg));

}


static void encode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)

{

    int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);

    for (y0 = 0; y0 < height; y0 += 4)

        for (x = 0; x < width; x++)

            for (y = y0; y < height && y < y0+4; y++){

                if (!(t1->flags[y+1][x+1] & JPEG2000_T1_SIG) && (t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB)){

                    int ctxno = ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1], bandno),

                        bit = t1->data[y][x] & mask ? 1 : 0;

                    ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, bit);

                    if (bit){

                        int xorbit;

                        int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);

                        ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[y+1][x+1] >> 15) ^ xorbit);

                        *nmsedec += getnmsedec_sig(t1->data[y][x], bpno + NMSEDEC_FRACBITS);

                        ff_jpeg2000_set_significance(t1, x, y, t1->flags[y+1][x+1] >> 15);

                    }

                    t1->flags[y+1][x+1] |= JPEG2000_T1_VIS;

                }

            }

}


static void qdev_set_legacy_property(DeviceState *dev, Visitor *v, void *opaque,

                                     const char *name, Error **errp)

{

    Property *prop = opaque;

    if (dev->state != DEV_STATE_CREATED) {

        error_set(errp, QERR_PERMISSION_DENIED);

        return;

    }

    if (prop->info->parse) {

        Error *local_err = NULL;

        char *ptr = NULL;

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

        if (!local_err) {

            int ret;

            ret = prop->info->parse(dev, prop, ptr);

            if (ret != 0) {

                error_set(errp, QERR_INVALID_PARAMETER_VALUE,

                          name, prop->info->name);

            }

            g_free(ptr);

        } else {

            error_propagate(errp, local_err);

        }

    } else {

        error_set(errp, QERR_PERMISSION_DENIED);

    }

}


static void channel_load_d(struct fs_dma_ctrl *ctrl, int c)

{

	target_phys_addr_t addr = channel_reg(ctrl, c, RW_SAVED_DATA);

	/* Load and decode. FIXME: handle endianness.  */

	D(printf("%s ch=%d addr=" TARGET_FMT_plx "\n", __func__, c, addr));

	cpu_physical_memory_read (addr,

				  (void *) &ctrl->channels[c].current_d,

				  sizeof ctrl->channels[c].current_d);

	D(dump_d(c, &ctrl->channels[c].current_d));

	ctrl->channels[c].regs[RW_DATA] = addr;

}


static int xenfb_map_fb(struct XenFB *xenfb)

{

    struct xenfb_page *page = xenfb->c.page;

    char *protocol = xenfb->c.xendev.protocol;

    int n_fbdirs;

    unsigned long *pgmfns = NULL;

    unsigned long *fbmfns = NULL;

    void *map, *pd;

    int mode, ret = -1;

    /* default to native */

    pd = page->pd;

    mode = sizeof(unsigned long) * 8;

    if (!protocol) {

	/*

	 * Undefined protocol, some guesswork needed.

	 *

	 * Old frontends which don't set the protocol use

	 * one page directory only, thus pd[1] must be zero.

	 * pd[1] of the 32bit struct layout and the lower

	 * 32 bits of pd[0] of the 64bit struct layout have

	 * the same location, so we can check that ...

	 */

	uint32_t *ptr32 = NULL;

	uint32_t *ptr64 = NULL;

#if defined(__i386__)

	ptr32 = (void*)page->pd;

	ptr64 = ((void*)page->pd) + 4;

#elif defined(__x86_64__)

	ptr32 = ((void*)page->pd) - 4;

	ptr64 = (void*)page->pd;

#endif

	if (ptr32) {

	    if (ptr32[1] == 0) {

		mode = 32;

		pd   = ptr32;

	    } else {

		mode = 64;

		pd   = ptr64;

	    }

	}

#if defined(__x86_64__)

    } else if (strcmp(protocol, XEN_IO_PROTO_ABI_X86_32) == 0) {

	/* 64bit dom0, 32bit domU */

	mode = 32;

	pd   = ((void*)page->pd) - 4;

#elif defined(__i386__)

    } else if (strcmp(protocol, XEN_IO_PROTO_ABI_X86_64) == 0) {

	/* 32bit dom0, 64bit domU */

	mode = 64;

	pd   = ((void*)page->pd) + 4;

#endif

    }

    if (xenfb->pixels) {

        munmap(xenfb->pixels, xenfb->fbpages * XC_PAGE_SIZE);

        xenfb->pixels = NULL;

    }

    xenfb->fbpages = (xenfb->fb_len + (XC_PAGE_SIZE - 1)) / XC_PAGE_SIZE;

    n_fbdirs = xenfb->fbpages * mode / 8;

    n_fbdirs = (n_fbdirs + (XC_PAGE_SIZE - 1)) / XC_PAGE_SIZE;

    pgmfns = g_malloc0(sizeof(unsigned long) * n_fbdirs);

    fbmfns = g_malloc0(sizeof(unsigned long) * xenfb->fbpages);

    xenfb_copy_mfns(mode, n_fbdirs, pgmfns, pd);

    map = xc_map_foreign_pages(xen_xc, xenfb->c.xendev.dom,

			       PROT_READ, pgmfns, n_fbdirs);

    if (map == NULL)

	goto out;

    xenfb_copy_mfns(mode, xenfb->fbpages, fbmfns, map);

    munmap(map, n_fbdirs * XC_PAGE_SIZE);

    xenfb->pixels = xc_map_foreign_pages(xen_xc, xenfb->c.xendev.dom,

					 PROT_READ | PROT_WRITE, fbmfns, xenfb->fbpages);

    if (xenfb->pixels == NULL)

	goto out;

    ret = 0; /* all is fine */

out:

    g_free(pgmfns);

    g_free(fbmfns);

    return ret;

}


static int cpu_gdb_read_register(CPUState *env, uint8_t *mem_buf, int n)

{

    if (n < 32) {

        GET_REGL(env->active_tc.gpr[n]);

    }

    if (env->CP0_Config1 & (1 << CP0C1_FP)) {

        if (n >= 38 && n < 70) {

            if (env->CP0_Status & (1 << CP0St_FR))

		GET_REGL(env->active_fpu.fpr[n - 38].d);

            else

		GET_REGL(env->active_fpu.fpr[n - 38].w[FP_ENDIAN_IDX]);

        }

        switch (n) {

        case 70: GET_REGL((int32_t)env->active_fpu.fcr31);

        case 71: GET_REGL((int32_t)env->active_fpu.fcr0);

        }

    }

    switch (n) {

    case 32: GET_REGL((int32_t)env->CP0_Status);

    case 33: GET_REGL(env->active_tc.LO[0]);

    case 34: GET_REGL(env->active_tc.HI[0]);

    case 35: GET_REGL(env->CP0_BadVAddr);

    case 36: GET_REGL((int32_t)env->CP0_Cause);

    case 37: GET_REGL(env->active_tc.PC);

    case 72: GET_REGL(0); /* fp */

    case 89: GET_REGL((int32_t)env->CP0_PRid);

    }

    if (n >= 73 && n <= 88) {

	/* 16 embedded regs.  */

	GET_REGL(0);

    }

    return 0;

}


static int update_rom_mapping(VAPICROMState *s, CPUX86State *env, target_ulong ip)

{

    target_phys_addr_t paddr;

    uint32_t rom_state_vaddr;

    uint32_t pos, patch, offset;

    /* nothing to do if already activated */

    if (s->state == VAPIC_ACTIVE) {

        return 0;

    }

    /* bail out if ROM init code was not executed (missing ROM?) */

    if (s->state == VAPIC_INACTIVE) {

        return -1;

    }

    /* find out virtual address of the ROM */

    rom_state_vaddr = s->rom_state_paddr + (ip & 0xf0000000);

    paddr = cpu_get_phys_page_debug(env, rom_state_vaddr);

    if (paddr == -1) {

        return -1;

    }

    paddr += rom_state_vaddr & ~TARGET_PAGE_MASK;

    if (paddr != s->rom_state_paddr) {

        return -1;

    }

    read_guest_rom_state(s);

    if (memcmp(s->rom_state.signature, "kvm aPiC", 8) != 0) {

        return -1;

    }

    s->rom_state_vaddr = rom_state_vaddr;

    /* fixup addresses in ROM if needed */

    if (rom_state_vaddr == le32_to_cpu(s->rom_state.vaddr)) {

        return 0;

    }

    for (pos = le32_to_cpu(s->rom_state.fixup_start);

         pos < le32_to_cpu(s->rom_state.fixup_end);

         pos += 4) {

        cpu_physical_memory_rw(paddr + pos - s->rom_state.vaddr,

                               (void *)&offset, sizeof(offset), 0);

        offset = le32_to_cpu(offset);

        cpu_physical_memory_rw(paddr + offset, (void *)&patch,

                               sizeof(patch), 0);

        patch = le32_to_cpu(patch);

        patch += rom_state_vaddr - le32_to_cpu(s->rom_state.vaddr);

        patch = cpu_to_le32(patch);

        cpu_physical_memory_rw(paddr + offset, (void *)&patch,

                               sizeof(patch), 1);

    }

    read_guest_rom_state(s);

    s->vapic_paddr = paddr + le32_to_cpu(s->rom_state.vapic_vaddr) -

        le32_to_cpu(s->rom_state.vaddr);

    return 0;

}


void omap_badwidth_write32(void *opaque, target_phys_addr_t addr,

                uint32_t value)

{

    OMAP_32B_REG(addr);

    cpu_physical_memory_write(addr, (void *) &value, 4);

}


static void file_put_buffer(void *opaque, const uint8_t *buf,

                            int64_t pos, int size)

{

    QEMUFileStdio *s = opaque;

    fseek(s->outfile, pos, SEEK_SET);

    fwrite(buf, 1, size, s->outfile);

}


void qio_channel_socket_connect_async(QIOChannelSocket *ioc,

                                      SocketAddress *addr,

                                      QIOTaskFunc callback,

                                      gpointer opaque,

                                      GDestroyNotify destroy)

{

    QIOTask *task = qio_task_new(

        OBJECT(ioc), callback, opaque, destroy);

    SocketAddress *addrCopy;

    addrCopy = QAPI_CLONE(SocketAddress, addr);

    /* socket_connect() does a non-blocking connect(), but it

     * still blocks in DNS lookups, so we must use a thread */

    trace_qio_channel_socket_connect_async(ioc, addr);

    qio_task_run_in_thread(task,

                           qio_channel_socket_connect_worker,

                           addrCopy,

                           (GDestroyNotify)qapi_free_SocketAddress);

}


connect_to_qemu(

    const char *host,

    const char *port

) {

    struct addrinfo hints;

    struct addrinfo *server;

    int ret, sock;

    sock = qemu_socket(AF_INET, SOCK_STREAM, 0);

    if (sock < 0) {

        /* Error */

        fprintf(stderr, "Error opening socket!\n");

        return -1;

    }

    memset(&hints, 0, sizeof(struct addrinfo));

    hints.ai_family = AF_UNSPEC;

    hints.ai_socktype = SOCK_STREAM;

    hints.ai_flags = 0;

    hints.ai_protocol = 0;          /* Any protocol */

    ret = getaddrinfo(host, port, &hints, &server);

    if (ret != 0) {

        /* Error */

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

        goto cleanup_socket;

    }

    if (connect(sock, server->ai_addr, server->ai_addrlen) < 0) {

        /* Error */

        fprintf(stderr, "Could not connect\n");

        goto cleanup_socket;

    }

    if (verbose) {

        printf("Connected (sizeof Header=%zd)!\n", sizeof(VSCMsgHeader));

    }

    return sock;

cleanup_socket:

    closesocket(sock);

    return -1;

}


static inline uint32_t efsctuiz(uint32_t val)

{

    CPU_FloatU u;

    u.l = val;

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

    if (unlikely(float32_is_nan(u.f)))

        return 0;

    return float32_to_uint32_round_to_zero(u.f, &env->vec_status);

}


static int escape(char **dst, const char *src, const char *special_chars,

                  enum EscapeMode mode)

{

    AVBPrint dstbuf;

    av_bprint_init(&dstbuf, 1, AV_BPRINT_SIZE_UNLIMITED);

    switch (mode) {

    case ESCAPE_MODE_FULL:

    case ESCAPE_MODE_LAZY:

        /* \-escape characters */

        if (mode == ESCAPE_MODE_LAZY && strchr(WHITESPACES, *src))

            av_bprintf(&dstbuf, "\\%c", *src++);

        for (; *src; src++) {

            if ((special_chars && strchr(special_chars, *src)) ||

                strchr("'\\", *src) ||

                (mode == ESCAPE_MODE_FULL && strchr(WHITESPACES, *src)))

                av_bprintf(&dstbuf, "\\%c", *src);

            else

                av_bprint_chars(&dstbuf, *src, 1);

        }

        if (mode == ESCAPE_MODE_LAZY && strchr(WHITESPACES, dstbuf.str[dstbuf.len-1])) {

            char c = dstbuf.str[dstbuf.len-1];

            dstbuf.str[dstbuf.len-1] = '\\';

            av_bprint_chars(&dstbuf, c, 1);

        }

        break;

    case ESCAPE_MODE_QUOTE:

        /* enclose between '' the string */

        av_bprint_chars(&dstbuf, '\'', 1);

        for (; *src; src++) {

            if (*src == '\'')

                av_bprintf(&dstbuf, "'\\''");

            else

                av_bprint_chars(&dstbuf, *src, 1);

        }

        av_bprint_chars(&dstbuf, '\'', 1);

        break;

    default:

        /* unknown escape mode */

        return AVERROR(EINVAL);

    }

    if (!av_bprint_is_complete(&dstbuf)) {

        av_bprint_finalize(&dstbuf, NULL);

        return AVERROR(ENOMEM);

    } else {

        av_bprint_finalize(&dstbuf, dst);

        return 0;

    }

}


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

{

    MachineClass *mc = MACHINE_CLASS(oc);

    sPAPRMachineClass *smc = SPAPR_MACHINE_CLASS(oc);

    FWPathProviderClass *fwc = FW_PATH_PROVIDER_CLASS(oc);

    NMIClass *nc = NMI_CLASS(oc);

    HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc);

    mc->desc = "pSeries Logical Partition (PAPR compliant)";

    /*

     * We set up the default / latest behaviour here.  The class_init

     * functions for the specific versioned machine types can override

     * these details for backwards compatibility

     */

    mc->init = ppc_spapr_init;

    mc->reset = ppc_spapr_reset;

    mc->block_default_type = IF_SCSI;

    mc->max_cpus = MAX_CPUMASK_BITS;

    mc->no_parallel = 1;

    mc->default_boot_order = "";

    mc->default_ram_size = 512 * M_BYTE;

    mc->kvm_type = spapr_kvm_type;

    mc->has_dynamic_sysbus = true;

    mc->pci_allow_0_address = true;

    mc->get_hotplug_handler = spapr_get_hotplug_handler;

    hc->pre_plug = spapr_machine_device_pre_plug;

    hc->plug = spapr_machine_device_plug;

    hc->unplug = spapr_machine_device_unplug;

    mc->cpu_index_to_socket_id = spapr_cpu_index_to_socket_id;

    smc->dr_lmb_enabled = true;

    smc->tcg_default_cpu = "POWER8";

    mc->query_hotpluggable_cpus = spapr_query_hotpluggable_cpus;

    fwc->get_dev_path = spapr_get_fw_dev_path;

    nc->nmi_monitor_handler = spapr_nmi;

    smc->phb_placement = spapr_phb_placement;

}


static void xen_config_cleanup_dir(char *dir)

{

    struct xs_dirs *d;

    d = qemu_malloc(sizeof(*d));

    d->xs_dir = dir;

    TAILQ_INSERT_TAIL(&xs_cleanup, d, list);

}


void gen_intermediate_code(CPUSH4State * env, struct TranslationBlock *tb)

{

    SuperHCPU *cpu = sh_env_get_cpu(env);

    CPUState *cs = CPU(cpu);

    DisasContext ctx;

    target_ulong pc_start;

    int num_insns;

    int max_insns;

    pc_start = tb->pc;

    ctx.pc = pc_start;

    ctx.tbflags = (uint32_t)tb->flags;

    ctx.envflags = tb->flags & DELAY_SLOT_MASK;

    ctx.bstate = BS_NONE;

    ctx.memidx = (ctx.tbflags & (1u << SR_MD)) == 0 ? 1 : 0;

    /* We don't know if the delayed pc came from a dynamic or static branch,

       so assume it is a dynamic branch.  */

    ctx.delayed_pc = -1; /* use delayed pc from env pointer */

    ctx.tb = tb;

    ctx.singlestep_enabled = cs->singlestep_enabled;

    ctx.features = env->features;

    ctx.has_movcal = (ctx.tbflags & TB_FLAG_PENDING_MOVCA);

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0) {

        max_insns = CF_COUNT_MASK;

    }

    if (max_insns > TCG_MAX_INSNS) {

        max_insns = TCG_MAX_INSNS;

    }

    gen_tb_start(tb);

    while (ctx.bstate == BS_NONE && !tcg_op_buf_full()) {

        tcg_gen_insn_start(ctx.pc, ctx.envflags);

        num_insns++;

        if (unlikely(cpu_breakpoint_test(cs, ctx.pc, BP_ANY))) {

            /* We have hit a breakpoint - make sure PC is up-to-date */

            gen_save_cpu_state(&ctx, true);

            gen_helper_debug(cpu_env);

            ctx.bstate = BS_EXCP;

            /* The address covered by the breakpoint must be included in

               [tb->pc, tb->pc + tb->size) in order to for it to be

               properly cleared -- thus we increment the PC here so that

               the logic setting tb->size below does the right thing.  */

            ctx.pc += 2;

            break;

        }

        if (num_insns == max_insns && (tb->cflags & CF_LAST_IO)) {

            gen_io_start();

        }

        ctx.opcode = cpu_lduw_code(env, ctx.pc);

	decode_opc(&ctx);

	ctx.pc += 2;

	if ((ctx.pc & (TARGET_PAGE_SIZE - 1)) == 0)

	    break;

        if (cs->singlestep_enabled) {

	    break;

        }

        if (num_insns >= max_insns)

            break;

        if (singlestep)

            break;

    }

    if (tb->cflags & CF_LAST_IO)

        gen_io_end();

    if (cs->singlestep_enabled) {

        gen_save_cpu_state(&ctx, true);

        gen_helper_debug(cpu_env);

    } else {

	switch (ctx.bstate) {

        case BS_STOP:

            gen_save_cpu_state(&ctx, true);

            tcg_gen_exit_tb(0);

            break;

        case BS_NONE:

            gen_save_cpu_state(&ctx, false);

            gen_goto_tb(&ctx, 0, ctx.pc);

            break;

        case BS_EXCP:

            /* fall through */

        case BS_BRANCH:

        default:

            break;

	}

    }

    gen_tb_end(tb, num_insns);

    tb->size = ctx.pc - pc_start;

    tb->icount = num_insns;

#ifdef DEBUG_DISAS

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)

        && qemu_log_in_addr_range(pc_start)) {

        qemu_log_lock();

	qemu_log("IN:\n");	/* , lookup_symbol(pc_start)); */

        log_target_disas(cs, pc_start, ctx.pc - pc_start, 0);

	qemu_log("\n");

        qemu_log_unlock();

    }

#endif

}


void OPPROTO op_cli(void)

{

    raise_exception(EXCP0D_GPF);

}


static void tgen_ext16u(TCGContext *s, TCGType type, TCGReg dest, TCGReg src)

{

    if (facilities & FACILITY_EXT_IMM) {

        tcg_out_insn(s, RRE, LLGHR, dest, src);

        return;

    }

    if (dest == src) {

        tcg_out_movi(s, type, TCG_TMP0, 0xffff);

        src = TCG_TMP0;

    } else {

        tcg_out_movi(s, type, dest, 0xffff);

    }

    if (type == TCG_TYPE_I32) {

        tcg_out_insn(s, RR, NR, dest, src);

    } else {

        tcg_out_insn(s, RRE, NGR, dest, src);

    }

}