Object *object_new_with_propv(const char *typename, Object *parent, const char *id, Error **errp, va_list vargs) { Object *obj; ObjectClass *klass; Error *local_err = NULL; klass = object_class_by_name(typename); if (!klass) { error_setg(errp, "invalid object type: %s", typename); return NULL; } if (object_class_is_abstract(klass)) { error_setg(errp, "object type '%s' is abstract", typename); return NULL; } obj = object_new(typename); if (object_set_propv(obj, &local_err, vargs) < 0) { goto error; } object_property_add_child(parent, id, obj, &local_err); if (local_err) { goto error; } if (object_dynamic_cast(obj, TYPE_USER_CREATABLE)) { user_creatable_complete(obj, &local_err); if (local_err) { object_unparent(obj); goto error; } } object_unref(OBJECT(obj)); return obj; error: if (local_err) { error_propagate(errp, local_err); } object_unref(obj); return NULL; }


void start_auth_sasl(VncState *vs) { const char *mechlist = NULL; sasl_security_properties_t secprops; int err; char *localAddr, *remoteAddr; int mechlistlen; VNC_DEBUG("Initialize SASL auth %d\n", vs->csock); /* Get local & remote client addresses in form IPADDR;PORT */ if (!(localAddr = vnc_socket_local_addr("%s;%s", vs->csock))) goto authabort; if (!(remoteAddr = vnc_socket_remote_addr("%s;%s", vs->csock))) { free(localAddr); goto authabort; } err = sasl_server_new("vnc", NULL, /* FQDN - just delegates to gethostname */ NULL, /* User realm */ localAddr, remoteAddr, NULL, /* Callbacks, not needed */ SASL_SUCCESS_DATA, &vs->sasl.conn); free(localAddr); free(remoteAddr); localAddr = remoteAddr = NULL; if (err != SASL_OK) { VNC_DEBUG("sasl context setup failed %d (%s)", err, sasl_errstring(err, NULL, NULL)); vs->sasl.conn = NULL; goto authabort; } #ifdef CONFIG_VNC_TLS /* Inform SASL that we've got an external SSF layer from TLS/x509 */ if (vs->vd->auth == VNC_AUTH_VENCRYPT && vs->vd->subauth == VNC_AUTH_VENCRYPT_X509SASL) { gnutls_cipher_algorithm_t cipher; sasl_ssf_t ssf; cipher = gnutls_cipher_get(vs->tls.session); if (!(ssf = (sasl_ssf_t)gnutls_cipher_get_key_size(cipher))) { VNC_DEBUG("%s", "cannot TLS get cipher size\n"); sasl_dispose(&vs->sasl.conn); vs->sasl.conn = NULL; goto authabort; } ssf *= 8; /* tls key size is bytes, sasl wants bits */ err = sasl_setprop(vs->sasl.conn, SASL_SSF_EXTERNAL, &ssf); if (err != SASL_OK) { VNC_DEBUG("cannot set SASL external SSF %d (%s)\n", err, sasl_errstring(err, NULL, NULL)); sasl_dispose(&vs->sasl.conn); vs->sasl.conn = NULL; goto authabort; } } else #endif /* CONFIG_VNC_TLS */ vs->sasl.wantSSF = 1; memset (&secprops, 0, sizeof secprops); /* Inform SASL that we've got an external SSF layer from TLS */ if (strncmp(vs->vd->display, "unix:", 5) == 0 #ifdef CONFIG_VNC_TLS /* Disable SSF, if using TLS+x509+SASL only. TLS without x509 is not sufficiently strong */ || (vs->vd->auth == VNC_AUTH_VENCRYPT && vs->vd->subauth == VNC_AUTH_VENCRYPT_X509SASL) #endif /* CONFIG_VNC_TLS */ ) { /* If we've got TLS or UNIX domain sock, we don't care about SSF */ secprops.min_ssf = 0; secprops.max_ssf = 0; secprops.maxbufsize = 8192; secprops.security_flags = 0; } else { /* Plain TCP, better get an SSF layer */ secprops.min_ssf = 56; /* Good enough to require kerberos */ secprops.max_ssf = 100000; /* Arbitrary big number */ secprops.maxbufsize = 8192; /* Forbid any anonymous or trivially crackable auth */ secprops.security_flags = SASL_SEC_NOANONYMOUS | SASL_SEC_NOPLAINTEXT; } err = sasl_setprop(vs->sasl.conn, SASL_SEC_PROPS, &secprops); if (err != SASL_OK) { VNC_DEBUG("cannot set SASL security props %d (%s)\n", err, sasl_errstring(err, NULL, NULL)); sasl_dispose(&vs->sasl.conn); vs->sasl.conn = NULL; goto authabort; } err = sasl_listmech(vs->sasl.conn, NULL, /* Don't need to set user */ "", /* Prefix */ ",", /* Separator */ "", /* Suffix */ &mechlist, NULL, NULL); if (err != SASL_OK) { VNC_DEBUG("cannot list SASL mechanisms %d (%s)\n", err, sasl_errdetail(vs->sasl.conn)); sasl_dispose(&vs->sasl.conn); vs->sasl.conn = NULL; goto authabort; } VNC_DEBUG("Available mechanisms for client: '%s'\n", mechlist); if (!(vs->sasl.mechlist = strdup(mechlist))) { VNC_DEBUG("Out of memory"); sasl_dispose(&vs->sasl.conn); vs->sasl.conn = NULL; goto authabort; } mechlistlen = strlen(mechlist); vnc_write_u32(vs, mechlistlen); vnc_write(vs, mechlist, mechlistlen); vnc_flush(vs); VNC_DEBUG("Wait for client mechname length\n"); vnc_read_when(vs, protocol_client_auth_sasl_mechname_len, 4); return; authabort: vnc_client_error(vs); return; }


static void visitor_output_teardown(TestOutputVisitorData *data, const void *unused) { visit_free(data->ov); data->sov = NULL; data->ov = NULL; g_free(data->str); data->str = NULL; }


static void megasas_port_write(void *opaque, target_phys_addr_t addr, uint64_t val, unsigned size) { megasas_mmio_write(opaque, addr & 0xff, val, size); }


static inline void os_host_main_loop_wait(int *timeout) { }


uint32_t HELPER(ucf64_get_fpscr)(CPUUniCore32State *env) { int i; uint32_t fpscr; fpscr = (env->ucf64.xregs[UC32_UCF64_FPSCR] & UCF64_FPSCR_MASK); i = get_float_exception_flags(&env->ucf64.fp_status); fpscr |= ucf64_exceptbits_from_host(i); return fpscr; }


static int img_resize(int argc, char **argv) { int c, ret, relative; const char *filename, *fmt, *size; int64_t n, total_size; BlockDriverState *bs = NULL; QemuOpts *param; static QemuOptsList resize_options = { .name = "resize_options", .head = QTAILQ_HEAD_INITIALIZER(resize_options.head), .desc = { { .name = BLOCK_OPT_SIZE, .type = QEMU_OPT_SIZE, .help = "Virtual disk size" }, { /* end of list */ } }, }; /* Remove size from argv manually so that negative numbers are not treated * as options by getopt. */ if (argc < 3) { help(); return 1; } size = argv[--argc]; /* Parse getopt arguments */ fmt = NULL; for(;;) { c = getopt(argc, argv, "f:h"); if (c == -1) { break; } switch(c) { case '?': case 'h': help(); break; case 'f': fmt = optarg; break; } } if (optind >= argc) { help(); } filename = argv[optind++]; /* Choose grow, shrink, or absolute resize mode */ switch (size[0]) { case '+': relative = 1; size++; break; case '-': relative = -1; size++; break; default: relative = 0; break; } /* Parse size */ param = qemu_opts_create(&resize_options, NULL, 0, NULL); if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) { /* Error message already printed when size parsing fails */ ret = -1; qemu_opts_del(param); goto out; } n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0); qemu_opts_del(param); bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR); if (!bs) { ret = -1; goto out; } if (relative) { total_size = bdrv_getlength(bs) + n * relative; } else { total_size = n; } if (total_size <= 0) { error_report("New image size must be positive"); ret = -1; goto out; } ret = bdrv_truncate(bs, total_size); switch (ret) { case 0: printf("Image resized.\n"); break; case -ENOTSUP: error_report("This image does not support resize"); break; case -EACCES: error_report("Image is read-only"); break; default: error_report("Error resizing image (%d)", -ret); break; } out: if (bs) { bdrv_delete(bs); } if (ret) { return 1; } return 0; }


void dump_exec_info(FILE *f, fprintf_function cpu_fprintf) { int i, target_code_size, max_target_code_size; int direct_jmp_count, direct_jmp2_count, cross_page; TranslationBlock *tb; struct qht_stats hst; tb_lock(); if (!tcg_enabled()) { cpu_fprintf(f, "TCG not enabled\n"); return; } target_code_size = 0; max_target_code_size = 0; cross_page = 0; direct_jmp_count = 0; direct_jmp2_count = 0; for (i = 0; i < tcg_ctx.tb_ctx.nb_tbs; i++) { tb = tcg_ctx.tb_ctx.tbs[i]; target_code_size += tb->size; if (tb->size > max_target_code_size) { max_target_code_size = tb->size; } if (tb->page_addr[1] != -1) { cross_page++; } if (tb->jmp_reset_offset[0] != TB_JMP_RESET_OFFSET_INVALID) { direct_jmp_count++; if (tb->jmp_reset_offset[1] != TB_JMP_RESET_OFFSET_INVALID) { direct_jmp2_count++; } } } /* XXX: avoid using doubles ? */ cpu_fprintf(f, "Translation buffer state:\n"); cpu_fprintf(f, "gen code size %td/%zd\n", tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer, tcg_ctx.code_gen_highwater - tcg_ctx.code_gen_buffer); cpu_fprintf(f, "TB count %d\n", tcg_ctx.tb_ctx.nb_tbs); cpu_fprintf(f, "TB avg target size %d max=%d bytes\n", tcg_ctx.tb_ctx.nb_tbs ? target_code_size / tcg_ctx.tb_ctx.nb_tbs : 0, max_target_code_size); cpu_fprintf(f, "TB avg host size %td bytes (expansion ratio: %0.1f)\n", tcg_ctx.tb_ctx.nb_tbs ? (tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer) / tcg_ctx.tb_ctx.nb_tbs : 0, target_code_size ? (double) (tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer) / target_code_size : 0); cpu_fprintf(f, "cross page TB count %d (%d%%)\n", cross_page, tcg_ctx.tb_ctx.nb_tbs ? (cross_page * 100) / tcg_ctx.tb_ctx.nb_tbs : 0); cpu_fprintf(f, "direct jump count %d (%d%%) (2 jumps=%d %d%%)\n", direct_jmp_count, tcg_ctx.tb_ctx.nb_tbs ? (direct_jmp_count * 100) / tcg_ctx.tb_ctx.nb_tbs : 0, direct_jmp2_count, tcg_ctx.tb_ctx.nb_tbs ? (direct_jmp2_count * 100) / tcg_ctx.tb_ctx.nb_tbs : 0); qht_statistics_init(&tcg_ctx.tb_ctx.htable, &hst); print_qht_statistics(f, cpu_fprintf, hst); qht_statistics_destroy(&hst); cpu_fprintf(f, "\nStatistics:\n"); cpu_fprintf(f, "TB flush count %u\n", atomic_read(&tcg_ctx.tb_ctx.tb_flush_count)); cpu_fprintf(f, "TB invalidate count %d\n", tcg_ctx.tb_ctx.tb_phys_invalidate_count); cpu_fprintf(f, "TLB flush count %d\n", tlb_flush_count); tcg_dump_info(f, cpu_fprintf); tb_unlock(); }


build_fadt(GArray *table_data, BIOSLinker *linker, AcpiPmInfo *pm, unsigned facs, unsigned dsdt, const char *oem_id, const char *oem_table_id) { AcpiFadtDescriptorRev1 *fadt = acpi_data_push(table_data, sizeof(*fadt)); fadt->firmware_ctrl = cpu_to_le32(facs); /* FACS address to be filled by Guest linker */ bios_linker_loader_add_pointer(linker, ACPI_BUILD_TABLE_FILE, ACPI_BUILD_TABLE_FILE, &fadt->firmware_ctrl, sizeof fadt->firmware_ctrl); fadt->dsdt = cpu_to_le32(dsdt); /* DSDT address to be filled by Guest linker */ bios_linker_loader_add_pointer(linker, ACPI_BUILD_TABLE_FILE, ACPI_BUILD_TABLE_FILE, &fadt->dsdt, sizeof fadt->dsdt); fadt_setup(fadt, pm); build_header(linker, table_data, (void *)fadt, "FACP", sizeof(*fadt), 1, oem_id, oem_table_id); }


void arm_cpu_do_unaligned_access(CPUState *cs, vaddr vaddr, int is_write, int is_user, uintptr_t retaddr) { ARMCPU *cpu = ARM_CPU(cs); CPUARMState *env = &cpu->env; int target_el; bool same_el; if (retaddr) { /* now we have a real cpu fault */ cpu_restore_state(cs, retaddr); } target_el = exception_target_el(env); same_el = (arm_current_el(env) == target_el); env->exception.vaddress = vaddr; /* the DFSR for an alignment fault depends on whether we're using * the LPAE long descriptor format, or the short descriptor format */ if (arm_regime_using_lpae_format(env, cpu_mmu_index(env, false))) { env->exception.fsr = 0x21; } else { env->exception.fsr = 0x1; } if (is_write == 1 && arm_feature(env, ARM_FEATURE_V6)) { env->exception.fsr |= (1 << 11); } raise_exception(env, EXCP_DATA_ABORT, syn_data_abort(same_el, 0, 0, 0, is_write == 1, 0x21), target_el); }


static void flash_sync_page(Flash *s, int page) { int bdrv_sector, nb_sectors; QEMUIOVector iov; if (!s->bdrv || bdrv_is_read_only(s->bdrv)) { return; } bdrv_sector = (page * s->pi->page_size) / BDRV_SECTOR_SIZE; nb_sectors = DIV_ROUND_UP(s->pi->page_size, BDRV_SECTOR_SIZE); qemu_iovec_init(&iov, 1); qemu_iovec_add(&iov, s->storage + bdrv_sector * BDRV_SECTOR_SIZE, nb_sectors * BDRV_SECTOR_SIZE); bdrv_aio_writev(s->bdrv, bdrv_sector, &iov, nb_sectors, bdrv_sync_complete, NULL); }


static int proxy_lstat(FsContext *fs_ctx, V9fsPath *fs_path, struct stat *stbuf) { int retval; retval = v9fs_request(fs_ctx->private, T_LSTAT, stbuf, "s", fs_path); if (retval < 0) { errno = -retval; return -1; } return retval; }


void bios_linker_loader_add_checksum(GArray *linker, const char *file, GArray *table, void *start, unsigned size, uint8_t *checksum) { BiosLinkerLoaderEntry entry; ptrdiff_t checksum_offset = (gchar *)checksum - table->data; ptrdiff_t start_offset = (gchar *)start - table->data; assert(checksum_offset >= 0); assert(start_offset >= 0); assert(checksum_offset + 1 <= table->len); assert(start_offset + size <= table->len); assert(*checksum == 0x0); memset(&entry, 0, sizeof entry); strncpy(entry.cksum.file, file, sizeof entry.cksum.file - 1); entry.command = cpu_to_le32(BIOS_LINKER_LOADER_COMMAND_ADD_CHECKSUM); entry.cksum.offset = cpu_to_le32(checksum_offset); entry.cksum.start = cpu_to_le32(start_offset); entry.cksum.length = cpu_to_le32(size); g_array_append_vals(linker, &entry, sizeof entry); }


void backup_do_checkpoint(BlockJob *job, Error **errp) { BackupBlockJob *backup_job = container_of(job, BackupBlockJob, common); int64_t len; assert(job->driver->job_type == BLOCK_JOB_TYPE_BACKUP); if (backup_job->sync_mode != MIRROR_SYNC_MODE_NONE) { error_setg(errp, "The backup job only supports block checkpoint in" " sync=none mode"); return; } len = DIV_ROUND_UP(backup_job->common.len, backup_job->cluster_size); bitmap_zero(backup_job->done_bitmap, len); }


int floatx80_is_nan( floatx80 a1 ) { floatx80u u; u.f = a1; return ( ( u.i.high & 0x7FFF ) == 0x7FFF ) && (bits64) ( u.i.low<<1 ); }


static void taihu_cpld_writel (void *opaque, hwaddr addr, uint32_t value) { taihu_cpld_writel(opaque, addr, (value >> 24) & 0xFF); taihu_cpld_writel(opaque, addr + 1, (value >> 16) & 0xFF); taihu_cpld_writel(opaque, addr + 2, (value >> 8) & 0xFF); taihu_cpld_writeb(opaque, addr + 3, value & 0xFF); }


static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track) { MOVStts *stts_entries; uint32_t entries = -1; uint32_t atom_size; int i; if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) { stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */ if (!stts_entries) return AVERROR(ENOMEM); stts_entries[0].count = track->sample_count; stts_entries[0].duration = 1; entries = 1; } else { stts_entries = track->entry ? av_malloc_array(track->entry, sizeof(*stts_entries)) : /* worst case */ NULL; if (!stts_entries) return AVERROR(ENOMEM); for (i = 0; i < track->entry; i++) { int duration = get_cluster_duration(track, i); if (i && duration == stts_entries[entries].duration) { stts_entries[entries].count++; /* compress */ } else { entries++; stts_entries[entries].duration = duration; stts_entries[entries].count = 1; } } entries++; /* last one */ } atom_size = 16 + (entries * 8); avio_wb32(pb, atom_size); /* size */ ffio_wfourcc(pb, "stts"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, entries); /* entry count */ for (i = 0; i < entries; i++) { avio_wb32(pb, stts_entries[i].count); avio_wb32(pb, stts_entries[i].duration); } av_free(stts_entries); return atom_size; }


void qcrypto_cipher_free(QCryptoCipher *cipher) { QCryptoCipherBuiltin *ctxt = cipher->opaque; if (!cipher) { return; } ctxt->free(cipher); g_free(cipher); }


static uint64_t omap_wd_timer_read(void *opaque, target_phys_addr_t addr, unsigned size) { struct omap_watchdog_timer_s *s = (struct omap_watchdog_timer_s *) opaque; if (size != 2) { return omap_badwidth_read16(opaque, addr); } switch (addr) { case 0x00: /* CNTL_TIMER */ return (s->timer.ptv << 9) | (s->timer.ar << 8) | (s->timer.st << 7) | (s->free << 1); case 0x04: /* READ_TIMER */ return omap_timer_read(&s->timer); case 0x08: /* TIMER_MODE */ return s->mode << 15; } OMAP_BAD_REG(addr); return 0; }


static void do_commit(Monitor *mon, const QDict *qdict) { int all_devices; DriveInfo *dinfo; const char *device = qdict_get_str(qdict, "device"); all_devices = !strcmp(device, "all"); TAILQ_FOREACH(dinfo, &drives, next) { if (!all_devices) if (strcmp(bdrv_get_device_name(dinfo->bdrv), device)) continue; bdrv_commit(dinfo->bdrv); } }


long do_sigreturn(CPUPPCState *env) { struct target_sigcontext *sc = NULL; struct target_mcontext *sr = NULL; target_ulong sr_addr = 0, sc_addr; sigset_t blocked; target_sigset_t set; sc_addr = env->gpr[1] + SIGNAL_FRAMESIZE; if (!lock_user_struct(VERIFY_READ, sc, sc_addr, 1)) goto sigsegv; #if defined(TARGET_PPC64) set.sig[0] = sc->oldmask + ((long)(sc->_unused[3]) << 32); #else if(__get_user(set.sig[0], &sc->oldmask) || __get_user(set.sig[1], &sc->_unused[3])) goto sigsegv; #endif target_to_host_sigset_internal(&blocked, &set); sigprocmask(SIG_SETMASK, &blocked, NULL); if (__get_user(sr_addr, &sc->regs)) goto sigsegv; if (!lock_user_struct(VERIFY_READ, sr, sr_addr, 1)) goto sigsegv; if (restore_user_regs(env, sr, 1)) goto sigsegv; unlock_user_struct(sr, sr_addr, 1); unlock_user_struct(sc, sc_addr, 1); return -TARGET_QEMU_ESIGRETURN; sigsegv: unlock_user_struct(sr, sr_addr, 1); unlock_user_struct(sc, sc_addr, 1); qemu_log("segfaulting from do_sigreturn\n"); force_sig(TARGET_SIGSEGV); return 0; }


int kvm_arch_irqchip_create(MachineState *ms, KVMState *s) { int ret; if (machine_kernel_irqchip_split(ms)) { ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24); if (ret) { error_report("Could not enable split irqchip mode: %s\n", strerror(-ret)); exit(1); } else { DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n"); kvm_split_irqchip = true; return 1; } } else { return 0; } }


void aio_context_set_poll_params(AioContext *ctx, int64_t max_ns, int64_t grow, int64_t shrink, Error **errp) { /* No thread synchronization here, it doesn't matter if an incorrect value * is used once. */ ctx->poll_max_ns = max_ns; ctx->poll_ns = 0; ctx->poll_grow = grow; ctx->poll_shrink = shrink; aio_notify(ctx); }


static void rtas_ibm_change_msi(PowerPCCPU *cpu, sPAPREnvironment *spapr, uint32_t token, uint32_t nargs, target_ulong args, uint32_t nret, target_ulong rets) { uint32_t config_addr = rtas_ld(args, 0); uint64_t buid = ((uint64_t)rtas_ld(args, 1) << 32) | rtas_ld(args, 2); unsigned int func = rtas_ld(args, 3); unsigned int req_num = rtas_ld(args, 4); /* 0 == remove all */ unsigned int seq_num = rtas_ld(args, 5); unsigned int ret_intr_type; unsigned int irq, max_irqs = 0, num = 0; sPAPRPHBState *phb = NULL; PCIDevice *pdev = NULL; spapr_pci_msi *msi; int *config_addr_key; switch (func) { case RTAS_CHANGE_MSI_FN: case RTAS_CHANGE_FN: ret_intr_type = RTAS_TYPE_MSI; break; case RTAS_CHANGE_MSIX_FN: ret_intr_type = RTAS_TYPE_MSIX; break; default: error_report("rtas_ibm_change_msi(%u) is not implemented", func); rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR); return; } /* Fins sPAPRPHBState */ phb = find_phb(spapr, buid); if (phb) { pdev = find_dev(spapr, buid, config_addr); } if (!phb || !pdev) { rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR); return; } /* Releasing MSIs */ if (!req_num) { msi = (spapr_pci_msi *) g_hash_table_lookup(phb->msi, &config_addr); if (!msi) { trace_spapr_pci_msi("Releasing wrong config", config_addr); rtas_st(rets, 0, RTAS_OUT_HW_ERROR); return; } xics_free(spapr->icp, msi->first_irq, msi->num); if (msi_present(pdev)) { spapr_msi_setmsg(pdev, 0, false, 0, num); } if (msix_present(pdev)) { spapr_msi_setmsg(pdev, 0, true, 0, num); } g_hash_table_remove(phb->msi, &config_addr); trace_spapr_pci_msi("Released MSIs", config_addr); rtas_st(rets, 0, RTAS_OUT_SUCCESS); rtas_st(rets, 1, 0); return; } /* Enabling MSI */ /* Check if the device supports as many IRQs as requested */ if (ret_intr_type == RTAS_TYPE_MSI) { max_irqs = msi_nr_vectors_allocated(pdev); } else if (ret_intr_type == RTAS_TYPE_MSIX) { max_irqs = pdev->msix_entries_nr; } if (!max_irqs) { error_report("Requested interrupt type %d is not enabled for device %x", ret_intr_type, config_addr); rtas_st(rets, 0, -1); /* Hardware error */ return; } /* Correct the number if the guest asked for too many */ if (req_num > max_irqs) { trace_spapr_pci_msi_retry(config_addr, req_num, max_irqs); req_num = max_irqs; irq = 0; /* to avoid misleading trace */ goto out; } /* Allocate MSIs */ irq = xics_alloc_block(spapr->icp, 0, req_num, false, ret_intr_type == RTAS_TYPE_MSI); if (!irq) { error_report("Cannot allocate MSIs for device %x", config_addr); rtas_st(rets, 0, RTAS_OUT_HW_ERROR); return; } /* Setup MSI/MSIX vectors in the device (via cfgspace or MSIX BAR) */ spapr_msi_setmsg(pdev, SPAPR_PCI_MSI_WINDOW, ret_intr_type == RTAS_TYPE_MSIX, irq, req_num); /* Add MSI device to cache */ msi = g_new(spapr_pci_msi, 1); msi->first_irq = irq; msi->num = req_num; config_addr_key = g_new(int, 1); *config_addr_key = config_addr; g_hash_table_insert(phb->msi, config_addr_key, msi); out: rtas_st(rets, 0, RTAS_OUT_SUCCESS); rtas_st(rets, 1, req_num); rtas_st(rets, 2, ++seq_num); rtas_st(rets, 3, ret_intr_type); trace_spapr_pci_rtas_ibm_change_msi(config_addr, func, req_num, irq); }


START_TEST(simple_number) { int i; struct { const char *encoded; int64_t decoded; } test_cases[] = { { "0", 0 }, { "1234", 1234 }, { "1", 1 }, { "-32", -32 }, { "-0", 0 }, { }, }; for (i = 0; test_cases[i].encoded; i++) { QObject *obj; QInt *qint; obj = qobject_from_json(test_cases[i].encoded); fail_unless(obj != NULL); fail_unless(qobject_type(obj) == QTYPE_QINT); qint = qobject_to_qint(obj); fail_unless(qint_get_int(qint) == test_cases[i].decoded); QDECREF(qint); } }


static int v410_encode_frame(AVCodecContext *avctx, uint8_t *buf, int buf_size, void *data) { AVFrame *pic = data; uint8_t *dst = buf; uint16_t *y, *u, *v; uint32_t val; int i, j; int output_size = 0; if (buf_size < avctx->width * avctx->height * 3) { av_log(avctx, AV_LOG_ERROR, "Out buffer is too small.\n"); return AVERROR(ENOMEM); } avctx->coded_frame->reference = 0; avctx->coded_frame->key_frame = 1; avctx->coded_frame->pict_type = FF_I_TYPE; y = (uint16_t *)pic->data[0]; u = (uint16_t *)pic->data[1]; v = (uint16_t *)pic->data[2]; for (i = 0; i < avctx->height; i++) { for (j = 0; j < avctx->width; j++) { val = u[j] << 2; val |= y[j] << 12; val |= v[j] << 22; AV_WL32(dst, val); dst += 4; output_size += 4; } y += pic->linesize[0] >> 1; u += pic->linesize[1] >> 1; v += pic->linesize[2] >> 1; } return output_size; }


static void exynos4210_rtc_write(void *opaque, target_phys_addr_t offset, uint64_t value, unsigned size) { Exynos4210RTCState *s = (Exynos4210RTCState *)opaque; switch (offset) { case INTP: if (value & INTP_ALM_ENABLE) { qemu_irq_lower(s->alm_irq); s->reg_intp &= (~INTP_ALM_ENABLE); } if (value & INTP_TICK_ENABLE) { qemu_irq_lower(s->tick_irq); s->reg_intp &= (~INTP_TICK_ENABLE); } break; case RTCCON: if (value & RTC_ENABLE) { exynos4210_rtc_update_freq(s, value); } if ((value & RTC_ENABLE) > (s->reg_rtccon & RTC_ENABLE)) { /* clock timer */ ptimer_set_count(s->ptimer_1Hz, RTC_BASE_FREQ); ptimer_run(s->ptimer_1Hz, 1); DPRINTF("run clock timer\n"); } if ((value & RTC_ENABLE) < (s->reg_rtccon & RTC_ENABLE)) { /* tick timer */ ptimer_stop(s->ptimer); /* clock timer */ ptimer_stop(s->ptimer_1Hz); DPRINTF("stop all timers\n"); } if (value & RTC_ENABLE) { if ((value & TICK_TIMER_ENABLE) > (s->reg_rtccon & TICK_TIMER_ENABLE) && (s->reg_ticcnt)) { ptimer_set_count(s->ptimer, s->reg_ticcnt); ptimer_run(s->ptimer, 1); DPRINTF("run tick timer\n"); } if ((value & TICK_TIMER_ENABLE) < (s->reg_rtccon & TICK_TIMER_ENABLE)) { ptimer_stop(s->ptimer); } } s->reg_rtccon = value; break; case TICCNT: if (value > TICNT_THRESHHOLD) { s->reg_ticcnt = value; } else { fprintf(stderr, "[exynos4210.rtc: bad TICNT value %u ]\n", (uint32_t)value); } break; case RTCALM: s->reg_rtcalm = value; break; case ALMSEC: s->reg_almsec = (value & 0x7f); break; case ALMMIN: s->reg_almmin = (value & 0x7f); break; case ALMHOUR: s->reg_almhour = (value & 0x3f); break; case ALMDAY: s->reg_almday = (value & 0x3f); break; case ALMMON: s->reg_almmon = (value & 0x1f); break; case ALMYEAR: s->reg_almyear = (value & 0x0fff); break; case BCDSEC: if (s->reg_rtccon & RTC_ENABLE) { s->current_tm.tm_sec = (int)from_bcd((uint8_t)value); } break; case BCDMIN: if (s->reg_rtccon & RTC_ENABLE) { s->current_tm.tm_min = (int)from_bcd((uint8_t)value); } break; case BCDHOUR: if (s->reg_rtccon & RTC_ENABLE) { s->current_tm.tm_hour = (int)from_bcd((uint8_t)value); } break; case BCDDAYWEEK: if (s->reg_rtccon & RTC_ENABLE) { s->current_tm.tm_wday = (int)from_bcd((uint8_t)value); } break; case BCDDAY: if (s->reg_rtccon & RTC_ENABLE) { s->current_tm.tm_mday = (int)from_bcd((uint8_t)value); } break; case BCDMON: if (s->reg_rtccon & RTC_ENABLE) { s->current_tm.tm_mon = (int)from_bcd((uint8_t)value) - 1; } break; case BCDYEAR: if (s->reg_rtccon & RTC_ENABLE) { /* 3 digits */ s->current_tm.tm_year = (int)from_bcd((uint8_t)value) + (int)from_bcd((uint8_t)((value >> 8) & 0x0f)) * 100; } break; default: fprintf(stderr, "[exynos4210.rtc: bad write offset " TARGET_FMT_plx "]\n", offset); break; } }


static void dummy_m68k_init(QEMUMachineInitArgs *args) { ram_addr_t ram_size = args->ram_size; const char *cpu_model = args->cpu_model; const char *kernel_filename = args->kernel_filename; CPUM68KState *env; MemoryRegion *address_space_mem = get_system_memory(); MemoryRegion *ram = g_new(MemoryRegion, 1); int kernel_size; uint64_t elf_entry; target_phys_addr_t entry; if (!cpu_model) cpu_model = "cfv4e"; env = cpu_init(cpu_model); if (!env) { fprintf(stderr, "Unable to find m68k CPU definition\n"); exit(1); } /* Initialize CPU registers. */ env->vbr = 0; /* RAM at address zero */ memory_region_init_ram(ram, "dummy_m68k.ram", ram_size); vmstate_register_ram_global(ram); memory_region_add_subregion(address_space_mem, 0, ram); /* Load kernel. */ if (kernel_filename) { kernel_size = load_elf(kernel_filename, NULL, NULL, &elf_entry, NULL, NULL, 1, ELF_MACHINE, 0); entry = elf_entry; if (kernel_size < 0) { kernel_size = load_uimage(kernel_filename, &entry, NULL, NULL); } if (kernel_size < 0) { kernel_size = load_image_targphys(kernel_filename, KERNEL_LOAD_ADDR, ram_size - KERNEL_LOAD_ADDR); entry = KERNEL_LOAD_ADDR; } if (kernel_size < 0) { fprintf(stderr, "qemu: could not load kernel '%s'\n", kernel_filename); exit(1); } } else { entry = 0; } env->pc = entry; }


static void memory_dump(int count, int format, int wsize, target_phys_addr_t addr, int is_physical) { CPUState *env; int nb_per_line, l, line_size, i, max_digits, len; uint8_t buf[16]; uint64_t v; if (format == 'i') { int flags; flags = 0; env = mon_get_cpu(); if (!env && !is_physical) return; #ifdef TARGET_I386 if (wsize == 2) { flags = 1; } else if (wsize == 4) { flags = 0; } else { /* as default we use the current CS size */ flags = 0; if (env) { #ifdef TARGET_X86_64 if ((env->efer & MSR_EFER_LMA) && (env->segs[R_CS].flags & DESC_L_MASK)) flags = 2; else #endif if (!(env->segs[R_CS].flags & DESC_B_MASK)) flags = 1; } } #endif monitor_disas(env, addr, count, is_physical, flags); return; } len = wsize * count; if (wsize == 1) line_size = 8; else line_size = 16; nb_per_line = line_size / wsize; max_digits = 0; switch(format) { case 'o': max_digits = (wsize * 8 + 2) / 3; break; default: case 'x': max_digits = (wsize * 8) / 4; break; case 'u': case 'd': max_digits = (wsize * 8 * 10 + 32) / 33; break; case 'c': wsize = 1; break; } while (len > 0) { if (is_physical) term_printf(TARGET_FMT_plx ":", addr); else term_printf(TARGET_FMT_lx ":", (target_ulong)addr); l = len; if (l > line_size) l = line_size; if (is_physical) { cpu_physical_memory_rw(addr, buf, l, 0); } else { env = mon_get_cpu(); if (!env) break; cpu_memory_rw_debug(env, addr, buf, l, 0); } i = 0; while (i < l) { switch(wsize) { default: case 1: v = ldub_raw(buf + i); break; case 2: v = lduw_raw(buf + i); break; case 4: v = (uint32_t)ldl_raw(buf + i); break; case 8: v = ldq_raw(buf + i); break; } term_printf(" "); switch(format) { case 'o': term_printf("%#*" PRIo64, max_digits, v); break; case 'x': term_printf("0x%0*" PRIx64, max_digits, v); break; case 'u': term_printf("%*" PRIu64, max_digits, v); break; case 'd': term_printf("%*" PRId64, max_digits, v); break; case 'c': term_printc(v); break; } i += wsize; } term_printf("\n"); addr += l; len -= l; } }


void ide_sector_write(IDEState *s) { int64_t sector_num; int n; s->status = READY_STAT | SEEK_STAT | BUSY_STAT; sector_num = ide_get_sector(s); #if defined(DEBUG_IDE) printf("sector=%" PRId64 "\n", sector_num); #endif n = s->nsector; if (n > s->req_nb_sectors) { n = s->req_nb_sectors; } if (!ide_sect_range_ok(s, sector_num, n)) { ide_rw_error(s); return; } s->iov.iov_base = s->io_buffer; s->iov.iov_len = n * BDRV_SECTOR_SIZE; qemu_iovec_init_external(&s->qiov, &s->iov, 1); block_acct_start(bdrv_get_stats(s->bs), &s->acct, n * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ); s->pio_aiocb = bdrv_aio_writev(s->bs, sector_num, &s->qiov, n, ide_sector_write_cb, s); }


int bdrv_write(BlockDriverState *bs, int64_t sector_num, const uint8_t *buf, int nb_sectors) { return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0); }


static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov, int iovcnt) { TAPState *s = opaque; ssize_t len; do { len = writev(s->fd, iov, iovcnt); } while (len == -1 && (errno == EINTR || errno == EAGAIN)); return len; }


static void qemu_coroutine_thread_cleanup(void *opaque) { CoroutineThreadState *s = opaque; Coroutine *co; Coroutine *tmp; QLIST_FOREACH_SAFE(co, &s->pool, pool_next, tmp) { g_free(DO_UPCAST(CoroutineUContext, base, co)->stack); g_free(co); } g_free(s); }


static int ioh3420_initfn(PCIDevice *d) { PCIBridge* br = DO_UPCAST(PCIBridge, dev, d); PCIEPort *p = DO_UPCAST(PCIEPort, br, br); PCIESlot *s = DO_UPCAST(PCIESlot, port, p); int rc; int tmp; rc = pci_bridge_initfn(d); if (rc < 0) { return rc; } d->config[PCI_REVISION_ID] = PCI_DEVICE_ID_IOH_REV; pcie_port_init_reg(d); pci_config_set_vendor_id(d->config, PCI_VENDOR_ID_INTEL); pci_config_set_device_id(d->config, PCI_DEVICE_ID_IOH_EPORT); rc = pci_bridge_ssvid_init(d, IOH_EP_SSVID_OFFSET, IOH_EP_SSVID_SVID, IOH_EP_SSVID_SSID); if (rc < 0) { goto err_bridge; } rc = msi_init(d, IOH_EP_MSI_OFFSET, IOH_EP_MSI_NR_VECTOR, IOH_EP_MSI_SUPPORTED_FLAGS & PCI_MSI_FLAGS_64BIT, IOH_EP_MSI_SUPPORTED_FLAGS & PCI_MSI_FLAGS_MASKBIT); if (rc < 0) { goto err_bridge; } rc = pcie_cap_init(d, IOH_EP_EXP_OFFSET, PCI_EXP_TYPE_ROOT_PORT, p->port); if (rc < 0) { goto err_msi; } pcie_cap_deverr_init(d); pcie_cap_slot_init(d, s->slot); pcie_chassis_create(s->chassis); rc = pcie_chassis_add_slot(s); if (rc < 0) { goto err_pcie_cap; return rc; } pcie_cap_root_init(d); rc = pcie_aer_init(d, IOH_EP_AER_OFFSET); if (rc < 0) { goto err; } pcie_aer_root_init(d); ioh3420_aer_vector_update(d); return 0; err: pcie_chassis_del_slot(s); err_pcie_cap: pcie_cap_exit(d); err_msi: msi_uninit(d); err_bridge: tmp = pci_bridge_exitfn(d); assert(!tmp); return rc; }


static inline bool cpu_handle_interrupt(CPUState *cpu, TranslationBlock **last_tb) { CPUClass *cc = CPU_GET_CLASS(cpu); int interrupt_request = cpu->interrupt_request; if (unlikely(interrupt_request)) { if (unlikely(cpu->singlestep_enabled & SSTEP_NOIRQ)) { /* Mask out external interrupts for this step. */ interrupt_request &= ~CPU_INTERRUPT_SSTEP_MASK; } if (interrupt_request & CPU_INTERRUPT_DEBUG) { cpu->interrupt_request &= ~CPU_INTERRUPT_DEBUG; cpu->exception_index = EXCP_DEBUG; return true; } if (replay_mode == REPLAY_MODE_PLAY && !replay_has_interrupt()) { /* Do nothing */ } else if (interrupt_request & CPU_INTERRUPT_HALT) { replay_interrupt(); cpu->interrupt_request &= ~CPU_INTERRUPT_HALT; cpu->halted = 1; cpu->exception_index = EXCP_HLT; return true; } #if defined(TARGET_I386) else if (interrupt_request & CPU_INTERRUPT_INIT) { X86CPU *x86_cpu = X86_CPU(cpu); CPUArchState *env = &x86_cpu->env; replay_interrupt(); cpu_svm_check_intercept_param(env, SVM_EXIT_INIT, 0, 0); do_cpu_init(x86_cpu); cpu->exception_index = EXCP_HALTED; return true; } #else else if (interrupt_request & CPU_INTERRUPT_RESET) { replay_interrupt(); cpu_reset(cpu); return true; } #endif /* The target hook has 3 exit conditions: False when the interrupt isn't processed, True when it is, and we should restart on a new TB, and via longjmp via cpu_loop_exit. */ else { if (cc->cpu_exec_interrupt(cpu, interrupt_request)) { replay_interrupt(); *last_tb = NULL; } /* The target hook may have updated the 'cpu->interrupt_request'; * reload the 'interrupt_request' value */ interrupt_request = cpu->interrupt_request; } if (interrupt_request & CPU_INTERRUPT_EXITTB) { cpu->interrupt_request &= ~CPU_INTERRUPT_EXITTB; /* ensure that no TB jump will be modified as the program flow was changed */ *last_tb = NULL; } } if (unlikely(atomic_read(&cpu->exit_request) || replay_has_interrupt())) { atomic_set(&cpu->exit_request, 0); cpu->exception_index = EXCP_INTERRUPT; return true; } return false; }


void scsi_req_cancel(SCSIRequest *req) { trace_scsi_req_cancel(req->dev->id, req->lun, req->tag); if (!req->enqueued) { return; } scsi_req_ref(req); scsi_req_dequeue(req); req->io_canceled = true; if (req->aiocb) { bdrv_aio_cancel(req->aiocb); } }


static void test_visitor_in_int(TestInputVisitorData *data, const void *unused) { int64_t res = 0, value = -42; Visitor *v; v = visitor_input_test_init(data, "%" PRId64, value); visit_type_int(v, NULL, &res, &error_abort); g_assert_cmpint(res, ==, value); }


static int onenand_initfn(SysBusDevice *sbd) { DeviceState *dev = DEVICE(sbd); OneNANDState *s = ONE_NAND(dev); uint32_t size = 1 << (24 + ((s->id.dev >> 4) & 7)); void *ram; s->base = (hwaddr)-1; s->rdy = NULL; s->blocks = size >> BLOCK_SHIFT; s->secs = size >> 9; s->blockwp = g_malloc(s->blocks); s->density_mask = (s->id.dev & 0x08) ? (1 << (6 + ((s->id.dev >> 4) & 7))) : 0; memory_region_init_io(&s->iomem, OBJECT(s), &onenand_ops, s, "onenand", 0x10000 << s->shift); if (!s->bdrv) { s->image = memset(g_malloc(size + (size >> 5)), 0xff, size + (size >> 5)); } else { if (bdrv_is_read_only(s->bdrv)) { error_report("Can't use a read-only drive"); return -1; } s->bdrv_cur = s->bdrv; } s->otp = memset(g_malloc((64 + 2) << PAGE_SHIFT), 0xff, (64 + 2) << PAGE_SHIFT); memory_region_init_ram(&s->ram, OBJECT(s), "onenand.ram", 0xc000 << s->shift, &error_abort); vmstate_register_ram_global(&s->ram); ram = memory_region_get_ram_ptr(&s->ram); s->boot[0] = ram + (0x0000 << s->shift); s->boot[1] = ram + (0x8000 << s->shift); s->data[0][0] = ram + ((0x0200 + (0 << (PAGE_SHIFT - 1))) << s->shift); s->data[0][1] = ram + ((0x8010 + (0 << (PAGE_SHIFT - 6))) << s->shift); s->data[1][0] = ram + ((0x0200 + (1 << (PAGE_SHIFT - 1))) << s->shift); s->data[1][1] = ram + ((0x8010 + (1 << (PAGE_SHIFT - 6))) << s->shift); onenand_mem_setup(s); sysbus_init_irq(sbd, &s->intr); sysbus_init_mmio(sbd, &s->container); vmstate_register(dev, ((s->shift & 0x7f) << 24) | ((s->id.man & 0xff) << 16) | ((s->id.dev & 0xff) << 8) | (s->id.ver & 0xff), &vmstate_onenand, s); return 0; }


static void pxa2xx_lcdc_dma0_redraw_rot90(PXA2xxLCDState *s, hwaddr addr, int *miny, int *maxy) { DisplaySurface *surface = qemu_console_surface(s->con); int src_width, dest_width; drawfn fn = NULL; if (s->dest_width) fn = s->line_fn[s->transp][s->bpp]; if (!fn) return; src_width = (s->xres + 3) & ~3; /* Pad to a 4 pixels multiple */ if (s->bpp == pxa_lcdc_19pbpp || s->bpp == pxa_lcdc_18pbpp) src_width *= 3; else if (s->bpp > pxa_lcdc_16bpp) src_width *= 4; else if (s->bpp > pxa_lcdc_8bpp) src_width *= 2; dest_width = s->yres * s->dest_width; *miny = 0; framebuffer_update_display(surface, s->sysmem, addr, s->xres, s->yres, src_width, s->dest_width, -dest_width, s->invalidated, fn, s->dma_ch[0].palette, miny, maxy); }


static BlockBackend *bdrv_first_blk(BlockDriverState *bs) { BdrvChild *child; QLIST_FOREACH(child, &bs->parents, next_parent) { if (child->role == &child_root) { assert(bs->blk); return child->opaque; } } assert(!bs->blk); return NULL; }


static void s390_print_cpu_model_list_entry(gpointer data, gpointer user_data) { CPUListState *s = user_data; const S390CPUClass *scc = S390_CPU_CLASS((ObjectClass *)data); char *name = g_strdup(object_class_get_name((ObjectClass *)data)); const char *details = ""; if (scc->is_static) { details = "(static, migration-safe)"; } else if (scc->is_migration_safe) { details = "(migration-safe)"; } /* strip off the -s390-cpu */ g_strrstr(name, "-" TYPE_S390_CPU)[0] = 0; (*s->cpu_fprintf)(s->file, "s390 %-15s %-35s %s\n", name, scc->desc, details); g_free(name); }


static void simple_varargs(void) { QObject *embedded_obj; QObject *obj; LiteralQObject decoded = QLIT_QLIST(((LiteralQObject[]){ QLIT_QINT(1), QLIT_QINT(2), QLIT_QLIST(((LiteralQObject[]){ QLIT_QINT(32), QLIT_QINT(42), {}})), {}})); embedded_obj = qobject_from_json("[32, 42]"); g_assert(embedded_obj != NULL); obj = qobject_from_jsonf("[%d, 2, %p]", 1, embedded_obj); g_assert(obj != NULL); g_assert(compare_litqobj_to_qobj(&decoded, obj) == 1); qobject_decref(obj); }


static void add_device_config(int type, const char *cmdline) { struct device_config *conf; conf = qemu_mallocz(sizeof(*conf)); conf->type = type; conf->cmdline = cmdline; TAILQ_INSERT_TAIL(&device_configs, conf, next); }


static int compand_nodelay(AVFilterContext *ctx, AVFrame *frame) { CompandContext *s = ctx->priv; AVFilterLink *inlink = ctx->inputs[0]; const int channels = inlink->channels; const int nb_samples = frame->nb_samples; AVFrame *out_frame; int chan, i; if (av_frame_is_writable(frame)) { out_frame = frame; } else { out_frame = ff_get_audio_buffer(inlink, nb_samples); if (!out_frame) { av_frame_free(&frame); return AVERROR(ENOMEM); } av_frame_copy_props(out_frame, frame); } for (chan = 0; chan < channels; chan++) { const double *src = (double *)frame->extended_data[chan]; double *dst = (double *)out_frame->extended_data[chan]; ChanParam *cp = &s->channels[chan]; for (i = 0; i < nb_samples; i++) { update_volume(cp, fabs(src[i])); dst[i] = av_clipd(src[i] * get_volume(s, cp->volume), -1, 1); } } if (frame != out_frame) av_frame_free(&frame); return ff_filter_frame(ctx->outputs[0], out_frame); }


static int get_sot(Jpeg2000DecoderContext *s, int n) { Jpeg2000TilePart *tp; uint16_t Isot; uint32_t Psot; uint8_t TPsot; if (bytestream2_get_bytes_left(&s->g) < 8) return AVERROR_INVALIDDATA; s->curtileno = 0; Isot = bytestream2_get_be16u(&s->g); // Isot if (Isot >= s->numXtiles * s->numYtiles) return AVERROR_INVALIDDATA; s->curtileno = Isot; Psot = bytestream2_get_be32u(&s->g); // Psot TPsot = bytestream2_get_byteu(&s->g); // TPsot /* Read TNSot but not used */ bytestream2_get_byteu(&s->g); // TNsot if (!Psot) Psot = bytestream2_get_bytes_left(&s->g) + n + 2; if (Psot > bytestream2_get_bytes_left(&s->g) + n + 2) { av_log(s->avctx, AV_LOG_ERROR, "Psot %"PRIu32" too big\n", Psot); return AVERROR_INVALIDDATA; } if (TPsot >= FF_ARRAY_ELEMS(s->tile[Isot].tile_part)) { avpriv_request_sample(s->avctx, "Support for %"PRIu8" components", TPsot); return AVERROR_PATCHWELCOME; } s->tile[Isot].tp_idx = TPsot; tp = s->tile[Isot].tile_part + TPsot; tp->tile_index = Isot; tp->tp_end = s->g.buffer + Psot - n - 2; if (!TPsot) { Jpeg2000Tile *tile = s->tile + s->curtileno; /* copy defaults */ memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle)); memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle)); } return 0; }


int MPV_encode_picture(AVCodecContext *avctx, unsigned char *buf, int buf_size, void *data) { MpegEncContext *s = avctx->priv_data; AVFrame *pic_arg = data; int i, stuffing_count; for(i=0; i<avctx->thread_count; i++){ int start_y= s->thread_context[i]->start_mb_y; int end_y= s->thread_context[i]-> end_mb_y; int h= s->mb_height; uint8_t *start= buf + (size_t)(((int64_t) buf_size)*start_y/h); uint8_t *end = buf + (size_t)(((int64_t) buf_size)* end_y/h); init_put_bits(&s->thread_context[i]->pb, start, end - start); } s->picture_in_gop_number++; if(load_input_picture(s, pic_arg) < 0) return -1; select_input_picture(s); /* output? */ if(s->new_picture.data[0]){ s->pict_type= s->new_picture.pict_type; //emms_c(); //printf("qs:%f %f %d\n", s->new_picture.quality, s->current_picture.quality, s->qscale); MPV_frame_start(s, avctx); vbv_retry: if (encode_picture(s, s->picture_number) < 0) return -1; avctx->real_pict_num = s->picture_number; avctx->header_bits = s->header_bits; avctx->mv_bits = s->mv_bits; avctx->misc_bits = s->misc_bits; avctx->i_tex_bits = s->i_tex_bits; avctx->p_tex_bits = s->p_tex_bits; avctx->i_count = s->i_count; avctx->p_count = s->mb_num - s->i_count - s->skip_count; //FIXME f/b_count in avctx avctx->skip_count = s->skip_count; MPV_frame_end(s); if (s->out_format == FMT_MJPEG) mjpeg_picture_trailer(s); if(avctx->rc_buffer_size){ RateControlContext *rcc= &s->rc_context; int max_size= rcc->buffer_index/3; if(put_bits_count(&s->pb) > max_size && s->qscale < s->avctx->qmax){ s->next_lambda= s->lambda*(s->qscale+1) / s->qscale; s->mb_skipped = 0; //done in MPV_frame_start() if(s->pict_type==P_TYPE){ //done in encode_picture() so we must undo it if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4) s->no_rounding ^= 1; } // av_log(NULL, AV_LOG_ERROR, "R:%d ", s->next_lambda); for(i=0; i<avctx->thread_count; i++){ PutBitContext *pb= &s->thread_context[i]->pb; init_put_bits(pb, pb->buf, pb->buf_end - pb->buf); } goto vbv_retry; } assert(s->avctx->rc_max_rate); } if(s->flags&CODEC_FLAG_PASS1) ff_write_pass1_stats(s); for(i=0; i<4; i++){ s->current_picture_ptr->error[i]= s->current_picture.error[i]; avctx->error[i] += s->current_picture_ptr->error[i]; } if(s->flags&CODEC_FLAG_PASS1) assert(avctx->header_bits + avctx->mv_bits + avctx->misc_bits + avctx->i_tex_bits + avctx->p_tex_bits == put_bits_count(&s->pb)); flush_put_bits(&s->pb); s->frame_bits = put_bits_count(&s->pb); stuffing_count= ff_vbv_update(s, s->frame_bits); if(stuffing_count){ if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < stuffing_count + 50){ av_log(s->avctx, AV_LOG_ERROR, "stuffing too large\n"); return -1; } switch(s->codec_id){ case CODEC_ID_MPEG1VIDEO: case CODEC_ID_MPEG2VIDEO: while(stuffing_count--){ put_bits(&s->pb, 8, 0); } break; case CODEC_ID_MPEG4: put_bits(&s->pb, 16, 0); put_bits(&s->pb, 16, 0x1C3); stuffing_count -= 4; while(stuffing_count--){ put_bits(&s->pb, 8, 0xFF); } break; default: av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n"); } flush_put_bits(&s->pb); s->frame_bits = put_bits_count(&s->pb); } /* update mpeg1/2 vbv_delay for CBR */ if(s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate && s->out_format == FMT_MPEG1 && 90000LL * (avctx->rc_buffer_size-1) <= s->avctx->rc_max_rate*0xFFFFLL){ int vbv_delay; assert(s->repeat_first_field==0); vbv_delay= lrintf(90000 * s->rc_context.buffer_index / s->avctx->rc_max_rate); assert(vbv_delay < 0xFFFF); s->vbv_delay_ptr[0] &= 0xF8; s->vbv_delay_ptr[0] |= vbv_delay>>13; s->vbv_delay_ptr[1] = vbv_delay>>5; s->vbv_delay_ptr[2] &= 0x07; s->vbv_delay_ptr[2] |= vbv_delay<<3; } s->total_bits += s->frame_bits; avctx->frame_bits = s->frame_bits; }else{ assert((pbBufPtr(&s->pb) == s->pb.buf)); s->frame_bits=0; } assert((s->frame_bits&7)==0); return s->frame_bits/8; }


static int rtc_load_td(QEMUFile *f, void *opaque, int version_id) { RTCState *s = opaque; if (version_id != 1) return -EINVAL; s->irq_coalesced = qemu_get_be32(f); s->period = qemu_get_be32(f); rtc_coalesced_timer_update(s); return 0; }


static GtkWidget *gd_create_menu_view(GtkDisplayState *s, GtkAccelGroup *accel_group) { GSList *group = NULL; GtkWidget *view_menu; GtkWidget *separator; int i; view_menu = gtk_menu_new(); gtk_menu_set_accel_group(GTK_MENU(view_menu), accel_group); s->full_screen_item = gtk_image_menu_item_new_from_stock(GTK_STOCK_FULLSCREEN, NULL); gtk_menu_item_set_accel_path(GTK_MENU_ITEM(s->full_screen_item), "<QEMU>/View/Full Screen"); gtk_accel_map_add_entry("<QEMU>/View/Full Screen", GDK_KEY_f, GDK_CONTROL_MASK | GDK_MOD1_MASK); gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->full_screen_item); separator = gtk_separator_menu_item_new(); gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), separator); s->zoom_in_item = gtk_image_menu_item_new_from_stock(GTK_STOCK_ZOOM_IN, NULL); gtk_menu_item_set_accel_path(GTK_MENU_ITEM(s->zoom_in_item), "<QEMU>/View/Zoom In"); gtk_accel_map_add_entry("<QEMU>/View/Zoom In", GDK_KEY_plus, GDK_CONTROL_MASK | GDK_MOD1_MASK); gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->zoom_in_item); s->zoom_out_item = gtk_image_menu_item_new_from_stock(GTK_STOCK_ZOOM_OUT, NULL); gtk_menu_item_set_accel_path(GTK_MENU_ITEM(s->zoom_out_item), "<QEMU>/View/Zoom Out"); gtk_accel_map_add_entry("<QEMU>/View/Zoom Out", GDK_KEY_minus, GDK_CONTROL_MASK | GDK_MOD1_MASK); gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->zoom_out_item); s->zoom_fixed_item = gtk_image_menu_item_new_from_stock(GTK_STOCK_ZOOM_100, NULL); gtk_menu_item_set_accel_path(GTK_MENU_ITEM(s->zoom_fixed_item), "<QEMU>/View/Zoom Fixed"); gtk_accel_map_add_entry("<QEMU>/View/Zoom Fixed", GDK_KEY_0, GDK_CONTROL_MASK | GDK_MOD1_MASK); gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->zoom_fixed_item); s->zoom_fit_item = gtk_check_menu_item_new_with_mnemonic(_("Zoom To _Fit")); gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->zoom_fit_item); separator = gtk_separator_menu_item_new(); gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), separator); s->grab_on_hover_item = gtk_check_menu_item_new_with_mnemonic(_("Grab On _Hover")); gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->grab_on_hover_item); s->grab_item = gtk_check_menu_item_new_with_mnemonic(_("_Grab Input")); gtk_menu_item_set_accel_path(GTK_MENU_ITEM(s->grab_item), "<QEMU>/View/Grab Input"); gtk_accel_map_add_entry("<QEMU>/View/Grab Input", GDK_KEY_g, GDK_CONTROL_MASK | GDK_MOD1_MASK); gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->grab_item); separator = gtk_separator_menu_item_new(); gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), separator); s->vga_item = gtk_radio_menu_item_new_with_mnemonic(group, "_VGA"); group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(s->vga_item)); gtk_menu_item_set_accel_path(GTK_MENU_ITEM(s->vga_item), "<QEMU>/View/VGA"); gtk_accel_map_add_entry("<QEMU>/View/VGA", GDK_KEY_1, GDK_CONTROL_MASK | GDK_MOD1_MASK); gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->vga_item); for (i = 0; i < nb_vcs; i++) { VirtualConsole *vc = &s->vc[i]; group = gd_vc_init(s, vc, i, group, view_menu); s->nb_vcs++; } separator = gtk_separator_menu_item_new(); gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), separator); s->show_tabs_item = gtk_check_menu_item_new_with_mnemonic(_("Show _Tabs")); gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->show_tabs_item); return view_menu; }


static int v9fs_synth_readdir_r(FsContext *ctx, V9fsFidOpenState *fs, struct dirent *entry, struct dirent **result) { int ret; V9fsSynthOpenState *synth_open = fs->private; V9fsSynthNode *node = synth_open->node; ret = v9fs_synth_get_dentry(node, entry, result, synth_open->offset); if (!ret && *result != NULL) { synth_open->offset++; } return ret; }


static ssize_t vnc_tls_push(gnutls_transport_ptr_t transport, const void *data, size_t len) { struct VncState *vs = (struct VncState *)transport; int ret; retry: ret = send(vs->csock, data, len, 0); if (ret < 0) { if (errno == EINTR) goto retry; return -1; } return ret; }


void aio_context_release(AioContext *ctx) { qemu_rec_mutex_unlock(&ctx->lock); }


static int parse_pair(JSONParserContext *ctxt, QDict *dict, va_list *ap) { QObject *key = NULL, *token = NULL, *value, *peek; JSONParserContext saved_ctxt = parser_context_save(ctxt); peek = parser_context_peek_token(ctxt); if (peek == NULL) { parse_error(ctxt, NULL, "premature EOI"); goto out; } key = parse_value(ctxt, ap); if (!key || qobject_type(key) != QTYPE_QSTRING) { parse_error(ctxt, peek, "key is not a string in object"); goto out; } token = parser_context_pop_token(ctxt); if (token == NULL) { parse_error(ctxt, NULL, "premature EOI"); goto out; } if (!token_is_operator(token, ':')) { parse_error(ctxt, token, "missing : in object pair"); goto out; } value = parse_value(ctxt, ap); if (value == NULL) { parse_error(ctxt, token, "Missing value in dict"); goto out; } qdict_put_obj(dict, qstring_get_str(qobject_to_qstring(key)), value); qobject_decref(key); return 0; out: parser_context_restore(ctxt, saved_ctxt); qobject_decref(key); return -1; }


gen_intermediate_code_internal (CPUState *env, TranslationBlock *tb, int search_pc) { DisasContext ctx; target_ulong pc_start; uint16_t *gen_opc_end; CPUBreakpoint *bp; int j, lj = -1; int num_insns; int max_insns; if (search_pc && loglevel) fprintf (logfile, "search pc %d\n", search_pc); pc_start = tb->pc; /* Leave some spare opc slots for branch handling. */ gen_opc_end = gen_opc_buf + OPC_MAX_SIZE - 16; ctx.pc = pc_start; ctx.saved_pc = -1; ctx.tb = tb; ctx.bstate = BS_NONE; /* Restore delay slot state from the tb context. */ ctx.hflags = (uint32_t)tb->flags; /* FIXME: maybe use 64 bits here? */ restore_cpu_state(env, &ctx); if (env->user_mode_only) ctx.mem_idx = MIPS_HFLAG_UM; else ctx.mem_idx = ctx.hflags & MIPS_HFLAG_KSU; num_insns = 0; max_insns = tb->cflags & CF_COUNT_MASK; if (max_insns == 0) max_insns = CF_COUNT_MASK; #ifdef DEBUG_DISAS if (loglevel & CPU_LOG_TB_CPU) { fprintf(logfile, "------------------------------------------------\n"); /* FIXME: This may print out stale hflags from env... */ cpu_dump_state(env, logfile, fprintf, 0); } #endif #ifdef MIPS_DEBUG_DISAS if (loglevel & CPU_LOG_TB_IN_ASM) fprintf(logfile, "\ntb %p idx %d hflags %04x\n", tb, ctx.mem_idx, ctx.hflags); #endif gen_icount_start(); while (ctx.bstate == BS_NONE) { if (unlikely(!TAILQ_EMPTY(&env->breakpoints))) { TAILQ_FOREACH(bp, &env->breakpoints, entry) { if (bp->pc == ctx.pc) { save_cpu_state(&ctx, 1); ctx.bstate = BS_BRANCH; gen_helper_0i(raise_exception, EXCP_DEBUG); /* Include the breakpoint location or the tb won't * be flushed when it must be. */ ctx.pc += 4; goto done_generating; } } } if (search_pc) { j = gen_opc_ptr - gen_opc_buf; if (lj < j) { lj++; while (lj < j) gen_opc_instr_start[lj++] = 0; } gen_opc_pc[lj] = ctx.pc; gen_opc_hflags[lj] = ctx.hflags & MIPS_HFLAG_BMASK; gen_opc_instr_start[lj] = 1; gen_opc_icount[lj] = num_insns; } if (num_insns + 1 == max_insns && (tb->cflags & CF_LAST_IO)) gen_io_start(); ctx.opcode = ldl_code(ctx.pc); decode_opc(env, &ctx); ctx.pc += 4; num_insns++; if (env->singlestep_enabled) break; if ((ctx.pc & (TARGET_PAGE_SIZE - 1)) == 0) break; if (gen_opc_ptr >= gen_opc_end) break; if (num_insns >= max_insns) break; #if defined (MIPS_SINGLE_STEP) break; #endif } if (tb->cflags & CF_LAST_IO) gen_io_end(); if (env->singlestep_enabled) { save_cpu_state(&ctx, ctx.bstate == BS_NONE); gen_helper_0i(raise_exception, EXCP_DEBUG); } else { switch (ctx.bstate) { case BS_STOP: gen_helper_interrupt_restart(); gen_goto_tb(&ctx, 0, ctx.pc); break; case BS_NONE: save_cpu_state(&ctx, 0); gen_goto_tb(&ctx, 0, ctx.pc); break; case BS_EXCP: gen_helper_interrupt_restart(); tcg_gen_exit_tb(0); break; case BS_BRANCH: default: break; } } done_generating: gen_icount_end(tb, num_insns); *gen_opc_ptr = INDEX_op_end; if (search_pc) { j = gen_opc_ptr - gen_opc_buf; lj++; while (lj <= j) gen_opc_instr_start[lj++] = 0; } else { tb->size = ctx.pc - pc_start; tb->icount = num_insns; } #ifdef DEBUG_DISAS #if defined MIPS_DEBUG_DISAS if (loglevel & CPU_LOG_TB_IN_ASM) fprintf(logfile, "\n"); #endif if (loglevel & CPU_LOG_TB_IN_ASM) { fprintf(logfile, "IN: %s\n", lookup_symbol(pc_start)); target_disas(logfile, pc_start, ctx.pc - pc_start, 0); fprintf(logfile, "\n"); } if (loglevel & CPU_LOG_TB_CPU) { fprintf(logfile, "---------------- %d %08x\n", ctx.bstate, ctx.hflags); } #endif }


static void *nbd_client_thread(void *arg) { int fd = *(int *)arg; off_t size; size_t blocksize; uint32_t nbdflags; int sock; int ret; pthread_t show_parts_thread; do { sock = unix_socket_outgoing(sockpath); if (sock == -1) { goto out; } } while (sock == -1); ret = nbd_receive_negotiate(sock, NULL, &nbdflags, &size, &blocksize); if (ret == -1) { goto out; } ret = nbd_init(fd, sock, nbdflags, size, blocksize); if (ret == -1) { goto out; } /* update partition table */ pthread_create(&show_parts_thread, NULL, show_parts, NULL); if (verbose) { fprintf(stderr, "NBD device %s is now connected to %s\n", device, srcpath); } else { /* Close stderr so that the qemu-nbd process exits. */ dup2(STDOUT_FILENO, STDERR_FILENO); } ret = nbd_client(fd); if (ret) { goto out; } close(fd); kill(getpid(), SIGTERM); return (void *) EXIT_SUCCESS; out: kill(getpid(), SIGTERM); return (void *) EXIT_FAILURE; }


static void gen_addq(DisasContext *s, TCGv val, int rlow, int rhigh) { TCGv tmp; TCGv tmpl; TCGv tmph; /* Load 64-bit value rd:rn. */ tmpl = load_reg(s, rlow); tmph = load_reg(s, rhigh); tmp = tcg_temp_new(TCG_TYPE_I64); tcg_gen_concat_i32_i64(tmp, tmpl, tmph); dead_tmp(tmpl); dead_tmp(tmph); tcg_gen_add_i64(val, val, tmp); }


static void onenand_reset(OneNANDState *s, int cold) { memset(&s->addr, 0, sizeof(s->addr)); s->command = 0; s->count = 1; s->bufaddr = 0; s->config[0] = 0x40c0; s->config[1] = 0x0000; onenand_intr_update(s); qemu_irq_raise(s->rdy); s->status = 0x0000; s->intstatus = cold ? 0x8080 : 0x8010; s->unladdr[0] = 0; s->unladdr[1] = 0; s->wpstatus = 0x0002; s->cycle = 0; s->otpmode = 0; s->bdrv_cur = s->bdrv; s->current = s->image; s->secs_cur = s->secs; if (cold) { /* Lock the whole flash */ memset(s->blockwp, ONEN_LOCK_LOCKED, s->blocks); if (s->bdrv_cur && bdrv_read(s->bdrv_cur, 0, s->boot[0], 8) < 0) { hw_error("%s: Loading the BootRAM failed.\n", __func__); } } }


static void qpi_mem_writew(void *opaque, target_phys_addr_t addr, uint32_t val) { }


static void RENAME(yuv2bgr24_1)(SwsContext *c, const uint16_t *buf0, const uint16_t *ubuf0, const uint16_t *ubuf1, const uint16_t *vbuf0, const uint16_t *vbuf1, const uint16_t *abuf0, uint8_t *dest, int dstW, int uvalpha, enum PixelFormat dstFormat, int flags, int y) { const uint16_t *buf1= buf0; //FIXME needed for RGB1/BGR1 if (uvalpha < 2048) { // note this is not correct (shifts chrominance by 0.5 pixels) but it is a bit faster __asm__ volatile( "mov %%"REG_b", "ESP_OFFSET"(%5) \n\t" "mov %4, %%"REG_b" \n\t" "push %%"REG_BP" \n\t" YSCALEYUV2RGB1(%%REGBP, %5) "pxor %%mm7, %%mm7 \n\t" WRITEBGR24(%%REGb, 8280(%5), %%REGBP) "pop %%"REG_BP" \n\t" "mov "ESP_OFFSET"(%5), %%"REG_b" \n\t" :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest), "a" (&c->redDither) ); } else { __asm__ volatile( "mov %%"REG_b", "ESP_OFFSET"(%5) \n\t" "mov %4, %%"REG_b" \n\t" "push %%"REG_BP" \n\t" YSCALEYUV2RGB1b(%%REGBP, %5) "pxor %%mm7, %%mm7 \n\t" WRITEBGR24(%%REGb, 8280(%5), %%REGBP) "pop %%"REG_BP" \n\t" "mov "ESP_OFFSET"(%5), %%"REG_b" \n\t" :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest), "a" (&c->redDither) ); } }


static void asf_build_simple_index(AVFormatContext *s, int stream_index) { ff_asf_guid g; ASFContext *asf = s->priv_data; int64_t current_pos= avio_tell(s->pb); int i; avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET); ff_get_guid(s->pb, &g); /* the data object can be followed by other top-level objects, skip them until the simple index object is reached */ while (ff_guidcmp(&g, &index_guid)) { int64_t gsize= avio_rl64(s->pb); if (gsize < 24 || url_feof(s->pb)) { avio_seek(s->pb, current_pos, SEEK_SET); return; } avio_skip(s->pb, gsize-24); ff_get_guid(s->pb, &g); } { int64_t itime, last_pos=-1; int pct, ict; int64_t av_unused gsize= avio_rl64(s->pb); ff_get_guid(s->pb, &g); itime=avio_rl64(s->pb); pct=avio_rl32(s->pb); ict=avio_rl32(s->pb); av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n",itime,pct,ict); for (i=0;i<ict;i++){ int pktnum=avio_rl32(s->pb); int pktct =avio_rl16(s->pb); int64_t pos = s->data_offset + s->packet_size*(int64_t)pktnum; int64_t index_pts= FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0); if(pos != last_pos){ av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d pts: %"PRId64"\n", pktnum, pktct, index_pts); av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME); last_pos=pos; } } asf->index_read= 1; } avio_seek(s->pb, current_pos, SEEK_SET); }


void spapr_drc_attach(sPAPRDRConnector *drc, DeviceState *d, void *fdt, int fdt_start_offset, Error **errp) { trace_spapr_drc_attach(spapr_drc_index(drc)); if (drc->isolation_state != SPAPR_DR_ISOLATION_STATE_ISOLATED) { error_setg(errp, "an attached device is still awaiting release"); return; } if (spapr_drc_type(drc) == SPAPR_DR_CONNECTOR_TYPE_PCI) { g_assert(drc->allocation_state == SPAPR_DR_ALLOCATION_STATE_USABLE); } g_assert(fdt); drc->dev = d; drc->fdt = fdt; drc->fdt_start_offset = fdt_start_offset; object_property_add_link(OBJECT(drc), "device", object_get_typename(OBJECT(drc->dev)), (Object **)(&drc->dev), NULL, 0, NULL); }


void qxl_guest_bug(PCIQXLDevice *qxl, const char *msg, ...) { #if SPICE_INTERFACE_QXL_MINOR >= 1 qxl_send_events(qxl, QXL_INTERRUPT_ERROR); #endif if (qxl->guestdebug) { va_list ap; va_start(ap, msg); fprintf(stderr, "qxl-%d: guest bug: ", qxl->id); vfprintf(stderr, msg, ap); fprintf(stderr, "\n"); va_end(ap); } }


static void rtas_get_time_of_day(sPAPREnvironment *spapr, uint32_t token, uint32_t nargs, target_ulong args, uint32_t nret, target_ulong rets) { struct tm tm; if (nret != 8) { rtas_st(rets, 0, -3); return; } qemu_get_timedate(&tm, spapr->rtc_offset); rtas_st(rets, 0, 0); /* Success */ rtas_st(rets, 1, tm.tm_year + 1900); rtas_st(rets, 2, tm.tm_mon + 1); rtas_st(rets, 3, tm.tm_mday); rtas_st(rets, 4, tm.tm_hour); rtas_st(rets, 5, tm.tm_min); rtas_st(rets, 6, tm.tm_sec); rtas_st(rets, 7, 0); /* we don't do nanoseconds */ }


static void qmp_input_type_uint64(Visitor *v, const char *name, uint64_t *obj, Error **errp) { /* FIXME: qobject_to_qint mishandles values over INT64_MAX */ QmpInputVisitor *qiv = to_qiv(v); QObject *qobj = qmp_input_get_object(qiv, name, true, errp); QInt *qint; if (!qobj) { return; } qint = qobject_to_qint(qobj); if (!qint) { error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name ? name : "null", "integer"); return; } *obj = qint_get_int(qint); }


static int do_info(Monitor *mon, const QDict *qdict, QObject **ret_data) { const mon_cmd_t *cmd; const char *item = qdict_get_try_str(qdict, "item"); if (!item) { goto help; } for (cmd = info_cmds; cmd->name != NULL; cmd++) { if (compare_cmd(item, cmd->name)) break; } if (cmd->name == NULL) { goto help; } if (monitor_handler_is_async(cmd)) { user_async_info_handler(mon, cmd); /* * Indicate that this command is asynchronous and will not return any * data (not even empty). Instead, the data will be returned via a * completion callback. */ *ret_data = qobject_from_jsonf("{ '__mon_async': 'return' }"); } else if (monitor_handler_ported(cmd)) { QObject *info_data = NULL; cmd->mhandler.info_new(mon, &info_data); if (info_data) { cmd->user_print(mon, info_data); qobject_decref(info_data); } } else { cmd->mhandler.info(mon); } return 0; help: help_cmd(mon, "info"); return 0; }


int tcp_fconnect(struct socket *so) { Slirp *slirp = so->slirp; int ret=0; DEBUG_CALL("tcp_fconnect"); DEBUG_ARG("so = %p", so); if( (ret = so->s = qemu_socket(AF_INET,SOCK_STREAM,0)) >= 0) { int opt, s=so->s; struct sockaddr_in addr; qemu_set_nonblock(s); socket_set_fast_reuse(s); opt = 1; qemu_setsockopt(s, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt)); addr.sin_family = AF_INET; if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) == slirp->vnetwork_addr.s_addr) { /* It's an alias */ if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) { if (get_dns_addr(&addr.sin_addr) < 0) addr.sin_addr = loopback_addr; } else { addr.sin_addr = loopback_addr; } } else addr.sin_addr = so->so_faddr; addr.sin_port = so->so_fport; DEBUG_MISC((dfd, " connect()ing, addr.sin_port=%d, " "addr.sin_addr.s_addr=%.16s\n", ntohs(addr.sin_port), inet_ntoa(addr.sin_addr))); /* We don't care what port we get */ ret = connect(s,(struct sockaddr *)&addr,sizeof (addr)); /* * If it's not in progress, it failed, so we just return 0, * without clearing SS_NOFDREF */ soisfconnecting(so); } return(ret); }


int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len, int flags, CPUWatchpoint **watchpoint) { CPUWatchpoint *wp; /* forbid ranges which are empty or run off the end of the address space */ if (len == 0 || (addr + len - 1) <= addr) { error_report("tried to set invalid watchpoint at %" VADDR_PRIx ", len=%" VADDR_PRIu, addr, len); return -EINVAL; } wp = g_malloc(sizeof(*wp)); wp->vaddr = addr; wp->len = len; wp->flags = flags; /* keep all GDB-injected watchpoints in front */ if (flags & BP_GDB) { QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry); } else { QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry); } tlb_flush_page(cpu, addr); if (watchpoint) *watchpoint = wp; return 0; }


static int unix_connect_saddr(UnixSocketAddress *saddr, NonBlockingConnectHandler *callback, void *opaque, Error **errp) { struct sockaddr_un un; ConnectState *connect_state = NULL; int sock, rc; if (saddr->path == NULL) { error_setg(errp, "unix connect: no path specified"); return -1; } sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0); if (sock < 0) { error_setg_errno(errp, errno, "Failed to create socket"); return -1; } if (callback != NULL) { connect_state = g_malloc0(sizeof(*connect_state)); connect_state->callback = callback; connect_state->opaque = opaque; qemu_set_nonblock(sock); } memset(&un, 0, sizeof(un)); un.sun_family = AF_UNIX; snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path); /* connect to peer */ do { rc = 0; if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) { rc = -errno; } } while (rc == -EINTR); if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) { connect_state->fd = sock; qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state); return sock; } else if (rc >= 0) { /* non blocking socket immediate success, call callback */ if (callback != NULL) { callback(sock, NULL, opaque); } } if (rc < 0) { error_setg_errno(errp, -rc, "Failed to connect socket"); close(sock); sock = -1; } g_free(connect_state); return sock; }


void qemu_thread_create(QemuThread *thread, void *(*start_routine)(void *), void *arg, int mode) { HANDLE hThread; assert(mode == QEMU_THREAD_DETACHED); struct QemuThreadData *data; qemu_thread_init(); data = g_malloc(sizeof *data); data->thread = thread; data->start_routine = start_routine; data->arg = arg; hThread = (HANDLE) _beginthreadex(NULL, 0, win32_start_routine, data, 0, NULL); if (!hThread) { error_exit(GetLastError(), __func__); } CloseHandle(hThread); }


uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function, uint32_t index, int reg) { struct kvm_cpuid2 *cpuid; uint32_t ret = 0; uint32_t cpuid_1_edx; bool found = false; cpuid = get_supported_cpuid(s); struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index); if (entry) { found = true; ret = cpuid_entry_get_reg(entry, reg); /* Fixups for the data returned by KVM, below */ if (function == 1 && reg == R_EDX) { /* KVM before 2.6.30 misreports the following features */ ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA; } else if (function == 1 && reg == R_ECX) { /* We can set the hypervisor flag, even if KVM does not return it on * GET_SUPPORTED_CPUID ret |= CPUID_EXT_HYPERVISOR; /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER, * and the irqchip is in the kernel. if (kvm_irqchip_in_kernel() && kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) { ret |= CPUID_EXT_TSC_DEADLINE_TIMER; } else if (function == 0x80000001 && reg == R_EDX) { /* On Intel, kvm returns cpuid according to the Intel spec, * so add missing bits according to the AMD spec: cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX); ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES; g_free(cpuid); /* fallback for older kernels */ if ((function == KVM_CPUID_FEATURES) && !found) { ret = get_para_features(s); return ret;


static uint16_t handle_write_event_buf(SCLPEventFacility *ef, EventBufferHeader *event_buf, SCCB *sccb) { uint16_t rc; BusChild *kid; SCLPEvent *event; SCLPEventClass *ec; QTAILQ_FOREACH(kid, &ef->sbus.qbus.children, sibling) { DeviceState *qdev = kid->child; event = (SCLPEvent *) qdev; ec = SCLP_EVENT_GET_CLASS(event); rc = SCLP_RC_INVALID_FUNCTION; if (ec->write_event_data && ec->event_type() == event_buf->type) { rc = ec->write_event_data(event, event_buf); break; } } return rc; }


static int mpl2_probe(AVProbeData *p) { int i; char c; int64_t start, end; const unsigned char *ptr = p->buf; const unsigned char *ptr_end = ptr + p->buf_size; for (i = 0; i < 2; i++) { if (sscanf(ptr, "[%"SCNd64"][%"SCNd64"]%c", &start, &end, &c) != 3 && sscanf(ptr, "[%"SCNd64"][]%c", &start, &c) != 2) return 0; ptr += strcspn(ptr, "\n") + 1; if (ptr >= ptr_end) return 0; } return AVPROBE_SCORE_MAX; }


static DWORD WINAPI do_suspend(LPVOID opaque) { GuestSuspendMode *mode = opaque; DWORD ret = 0; if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) { slog("failed to suspend guest, %s", GetLastError()); ret = -1; } g_free(mode); return ret; }


void qmp_block_commit(const char *device, bool has_base, const char *base, bool has_top, const char *top, bool has_backing_file, const char *backing_file, bool has_speed, int64_t speed, Error **errp) { BlockDriverState *bs; BlockDriverState *base_bs, *top_bs; AioContext *aio_context; Error *local_err = NULL; /* This will be part of the QMP command, if/when the * BlockdevOnError change for blkmirror makes it in */ BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT; if (!has_speed) { speed = 0; } /* Important Note: * libvirt relies on the DeviceNotFound error class in order to probe for * live commit feature versions; for this to work, we must make sure to * perform the device lookup before any generic errors that may occur in a * scenario in which all optional arguments are omitted. */ bs = bdrv_find(device); if (!bs) { error_set(errp, QERR_DEVICE_NOT_FOUND, device); return; } aio_context = bdrv_get_aio_context(bs); aio_context_acquire(aio_context); /* drain all i/o before commits */ bdrv_drain_all(); if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, errp)) { goto out; } /* default top_bs is the active layer */ top_bs = bs; if (has_top && top) { if (strcmp(bs->filename, top) != 0) { top_bs = bdrv_find_backing_image(bs, top); } } if (top_bs == NULL) { error_setg(errp, "Top image file %s not found", top ? top : "NULL"); goto out; } assert(bdrv_get_aio_context(top_bs) == aio_context); if (has_base && base) { base_bs = bdrv_find_backing_image(top_bs, base); } else { base_bs = bdrv_find_base(top_bs); } if (base_bs == NULL) { error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL"); goto out; } assert(bdrv_get_aio_context(base_bs) == aio_context); /* Do not allow attempts to commit an image into itself */ if (top_bs == base_bs) { error_setg(errp, "cannot commit an image into itself"); goto out; } if (top_bs == bs) { if (has_backing_file) { error_setg(errp, "'backing-file' specified," " but 'top' is the active layer"); goto out; } commit_active_start(bs, base_bs, speed, on_error, block_job_cb, bs, &local_err); } else { commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs, has_backing_file ? backing_file : NULL, &local_err); } if (local_err != NULL) { error_propagate(errp, local_err); goto out; } out: aio_context_release(aio_context); }


static target_ulong compute_tlbie_rb(target_ulong v, target_ulong r, target_ulong pte_index) { target_ulong rb, va_low; rb = (v & ~0x7fULL) << 16; /* AVA field */ va_low = pte_index >> 3; if (v & HPTE64_V_SECONDARY) { va_low = ~va_low; } /* xor vsid from AVA */ if (!(v & HPTE64_V_1TB_SEG)) { va_low ^= v >> 12; } else { va_low ^= v >> 24; } va_low &= 0x7ff; if (v & HPTE64_V_LARGE) { rb |= 1; /* L field */ #if 0 /* Disable that P7 specific bit for now */ if (r & 0xff000) { /* non-16MB large page, must be 64k */ /* (masks depend on page size) */ rb |= 0x1000; /* page encoding in LP field */ rb |= (va_low & 0x7f) << 16; /* 7b of VA in AVA/LP field */ rb |= (va_low & 0xfe); /* AVAL field */ } #endif } else { /* 4kB page */ rb |= (va_low & 0x7ff) << 12; /* remaining 11b of AVA */ } rb |= (v >> 54) & 0x300; /* B field */ return rb; }


static void toright(unsigned char *dst[3], unsigned char *src[3], int dststride[3], int srcstride[3], int w, int h, struct vf_priv_s* p) { int k; for (k = 0; k < 3; k++) { unsigned char* fromL = src[k]; unsigned char* fromR = src[k]; unsigned char* to = dst[k]; int src = srcstride[k]; int dst = dststride[k]; int ss; unsigned int dd; int i; if (k > 0) { i = h / 4 - p->skipline / 2; ss = src * (h / 4 + p->skipline / 2); dd = w / 4; } else { i = h / 2 - p->skipline; ss = src * (h / 2 + p->skipline); dd = w / 2; } fromR += ss; for ( ; i > 0; i--) { int j; unsigned char* t = to; unsigned char* sL = fromL; unsigned char* sR = fromR; if (p->scalew == 1) { for (j = dd; j > 0; j--) { *t++ = (sL[0] + sL[1]) / 2; sL+=2; } for (j = dd ; j > 0; j--) { *t++ = (sR[0] + sR[1]) / 2; sR+=2; } } else { for (j = dd * 2 ; j > 0; j--) *t++ = *sL++; for (j = dd * 2 ; j > 0; j--) *t++ = *sR++; } if (p->scaleh == 1) { fast_memcpy(to + dst, to, dst); to += dst; } to += dst; fromL += src; fromR += src; } //printf("K %d %d %d %d %d \n", k, w, h, src, dst); } }


static int xan_huffman_decode(uint8_t *dest, int dest_len, const uint8_t *src, int src_len) { uint8_t byte = *src++; uint8_t ival = byte + 0x16; const uint8_t * ptr = src + byte*2; int ptr_len = src_len - 1 - byte*2; uint8_t val = ival; uint8_t *dest_end = dest + dest_len; uint8_t *dest_start = dest; int ret; GetBitContext gb; if ((ret = init_get_bits8(&gb, ptr, ptr_len)) < 0) return ret; while (val != 0x16) { unsigned idx = val - 0x17 + get_bits1(&gb) * byte; if (idx >= 2 * byte) return AVERROR_INVALIDDATA; val = src[idx]; if (val < 0x16) { if (dest >= dest_end) return dest_len; *dest++ = val; val = ival; } } return dest - dest_start; }


static int ram_load(QEMUFile *f, void *opaque, int version_id) { int flags = 0, ret = 0, invalid_flags = 0; static uint64_t seq_iter; int len = 0; /* * If system is running in postcopy mode, page inserts to host memory must * be atomic */ bool postcopy_running = postcopy_state_get() >= POSTCOPY_INCOMING_LISTENING; /* ADVISE is earlier, it shows the source has the postcopy capability on */ bool postcopy_advised = postcopy_state_get() >= POSTCOPY_INCOMING_ADVISE; seq_iter++; if (version_id != 4) { ret = -EINVAL; } if (!migrate_use_compression()) { invalid_flags |= RAM_SAVE_FLAG_COMPRESS_PAGE; } /* This RCU critical section can be very long running. * When RCU reclaims in the code start to become numerous, * it will be necessary to reduce the granularity of this * critical section. */ rcu_read_lock(); if (postcopy_running) { ret = ram_load_postcopy(f); } while (!postcopy_running && !ret && !(flags & RAM_SAVE_FLAG_EOS)) { ram_addr_t addr, total_ram_bytes; void *host = NULL; uint8_t ch; addr = qemu_get_be64(f); flags = addr & ~TARGET_PAGE_MASK; addr &= TARGET_PAGE_MASK; if (flags & invalid_flags) { if (flags & invalid_flags & RAM_SAVE_FLAG_COMPRESS_PAGE) { error_report("Received an unexpected compressed page"); } ret = -EINVAL; break; } if (flags & (RAM_SAVE_FLAG_ZERO | RAM_SAVE_FLAG_PAGE | RAM_SAVE_FLAG_COMPRESS_PAGE | RAM_SAVE_FLAG_XBZRLE)) { RAMBlock *block = ram_block_from_stream(f, flags); host = host_from_ram_block_offset(block, addr); if (!host) { error_report("Illegal RAM offset " RAM_ADDR_FMT, addr); ret = -EINVAL; break; } ramblock_recv_bitmap_set(block, host); trace_ram_load_loop(block->idstr, (uint64_t)addr, flags, host); } switch (flags & ~RAM_SAVE_FLAG_CONTINUE) { case RAM_SAVE_FLAG_MEM_SIZE: /* Synchronize RAM block list */ total_ram_bytes = addr; while (!ret && total_ram_bytes) { RAMBlock *block; char id[256]; ram_addr_t length; len = qemu_get_byte(f); qemu_get_buffer(f, (uint8_t *)id, len); id[len] = 0; length = qemu_get_be64(f); block = qemu_ram_block_by_name(id); if (block) { if (length != block->used_length) { Error *local_err = NULL; ret = qemu_ram_resize(block, length, &local_err); if (local_err) { error_report_err(local_err); } } /* For postcopy we need to check hugepage sizes match */ if (postcopy_advised && block->page_size != qemu_host_page_size) { uint64_t remote_page_size = qemu_get_be64(f); if (remote_page_size != block->page_size) { error_report("Mismatched RAM page size %s " "(local) %zd != %" PRId64, id, block->page_size, remote_page_size); ret = -EINVAL; } } ram_control_load_hook(f, RAM_CONTROL_BLOCK_REG, block->idstr); } else { error_report("Unknown ramblock \"%s\", cannot " "accept migration", id); ret = -EINVAL; } total_ram_bytes -= length; } break; case RAM_SAVE_FLAG_ZERO: ch = qemu_get_byte(f); ram_handle_compressed(host, ch, TARGET_PAGE_SIZE); break; case RAM_SAVE_FLAG_PAGE: qemu_get_buffer(f, host, TARGET_PAGE_SIZE); break; case RAM_SAVE_FLAG_COMPRESS_PAGE: len = qemu_get_be32(f); if (len < 0 || len > compressBound(TARGET_PAGE_SIZE)) { error_report("Invalid compressed data length: %d", len); ret = -EINVAL; break; } decompress_data_with_multi_threads(f, host, len); break; case RAM_SAVE_FLAG_XBZRLE: if (load_xbzrle(f, addr, host) < 0) { error_report("Failed to decompress XBZRLE page at " RAM_ADDR_FMT, addr); ret = -EINVAL; break; } break; case RAM_SAVE_FLAG_EOS: /* normal exit */ break; default: if (flags & RAM_SAVE_FLAG_HOOK) { ram_control_load_hook(f, RAM_CONTROL_HOOK, NULL); } else { error_report("Unknown combination of migration flags: %#x", flags); ret = -EINVAL; } } if (!ret) { ret = qemu_file_get_error(f); } } wait_for_decompress_done(); rcu_read_unlock(); trace_ram_load_complete(ret, seq_iter); return ret; }


static int tak_decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr, AVPacket *pkt) { TAKDecContext *s = avctx->priv_data; AVFrame *frame = data; ThreadFrame tframe = { .f = data }; GetBitContext *gb = &s->gb; int chan, i, ret, hsize; if (pkt->size < TAK_MIN_FRAME_HEADER_BYTES) return AVERROR_INVALIDDATA; if ((ret = init_get_bits8(gb, pkt->data, pkt->size)) < 0) return ret; if ((ret = ff_tak_decode_frame_header(avctx, gb, &s->ti, 0)) < 0) return ret; if (avctx->err_recognition & (AV_EF_CRCCHECK|AV_EF_COMPLIANT)) { hsize = get_bits_count(gb) / 8; if (ff_tak_check_crc(pkt->data, hsize)) { av_log(avctx, AV_LOG_ERROR, "CRC error\n"); if (avctx->err_recognition & AV_EF_EXPLODE) return AVERROR_INVALIDDATA; } } if (s->ti.codec != TAK_CODEC_MONO_STEREO && s->ti.codec != TAK_CODEC_MULTICHANNEL) { av_log(avctx, AV_LOG_ERROR, "unsupported codec: %d\n", s->ti.codec); return AVERROR_PATCHWELCOME; } if (s->ti.data_type) { av_log(avctx, AV_LOG_ERROR, "unsupported data type: %d\n", s->ti.data_type); return AVERROR_INVALIDDATA; } if (s->ti.codec == TAK_CODEC_MONO_STEREO && s->ti.channels > 2) { av_log(avctx, AV_LOG_ERROR, "invalid number of channels: %d\n", s->ti.channels); return AVERROR_INVALIDDATA; } if (s->ti.channels > 6) { av_log(avctx, AV_LOG_ERROR, "unsupported number of channels: %d\n", s->ti.channels); return AVERROR_INVALIDDATA; } if (s->ti.frame_samples <= 0) { av_log(avctx, AV_LOG_ERROR, "unsupported/invalid number of samples\n"); return AVERROR_INVALIDDATA; } if (s->ti.bps != avctx->bits_per_raw_sample) { avctx->bits_per_raw_sample = s->ti.bps; if ((ret = set_bps_params(avctx)) < 0) return ret; } if (s->ti.sample_rate != avctx->sample_rate) { avctx->sample_rate = s->ti.sample_rate; set_sample_rate_params(avctx); } if (s->ti.ch_layout) avctx->channel_layout = s->ti.ch_layout; avctx->channels = s->ti.channels; s->nb_samples = s->ti.last_frame_samples ? s->ti.last_frame_samples : s->ti.frame_samples; frame->nb_samples = s->nb_samples; if ((ret = ff_thread_get_buffer(avctx, &tframe, 0)) < 0) return ret; ff_thread_finish_setup(avctx); if (avctx->bits_per_raw_sample <= 16) { int buf_size = av_samples_get_buffer_size(NULL, avctx->channels, s->nb_samples, AV_SAMPLE_FMT_S32P, 0); av_fast_malloc(&s->decode_buffer, &s->decode_buffer_size, buf_size); if (!s->decode_buffer) return AVERROR(ENOMEM); ret = av_samples_fill_arrays((uint8_t **)s->decoded, NULL, s->decode_buffer, avctx->channels, s->nb_samples, AV_SAMPLE_FMT_S32P, 0); if (ret < 0) return ret; } else { for (chan = 0; chan < avctx->channels; chan++) s->decoded[chan] = (int32_t *)frame->extended_data[chan]; } if (s->nb_samples < 16) { for (chan = 0; chan < avctx->channels; chan++) { int32_t *decoded = s->decoded[chan]; for (i = 0; i < s->nb_samples; i++) decoded[i] = get_sbits(gb, avctx->bits_per_raw_sample); } } else { if (s->ti.codec == TAK_CODEC_MONO_STEREO) { for (chan = 0; chan < avctx->channels; chan++) if (ret = decode_channel(s, chan)) return ret; if (avctx->channels == 2) { s->nb_subframes = get_bits(gb, 1) + 1; if (s->nb_subframes > 1) { s->subframe_len[1] = get_bits(gb, 6); } s->dmode = get_bits(gb, 3); if (ret = decorrelate(s, 0, 1, s->nb_samples - 1)) return ret; } } else if (s->ti.codec == TAK_CODEC_MULTICHANNEL) { if (get_bits1(gb)) { int ch_mask = 0; chan = get_bits(gb, 4) + 1; if (chan > avctx->channels) return AVERROR_INVALIDDATA; for (i = 0; i < chan; i++) { int nbit = get_bits(gb, 4); if (nbit >= avctx->channels) return AVERROR_INVALIDDATA; if (ch_mask & 1 << nbit) return AVERROR_INVALIDDATA; s->mcdparams[i].present = get_bits1(gb); if (s->mcdparams[i].present) { s->mcdparams[i].index = get_bits(gb, 2); s->mcdparams[i].chan2 = get_bits(gb, 4); if (s->mcdparams[i].index == 1) { if ((nbit == s->mcdparams[i].chan2) || (ch_mask & 1 << s->mcdparams[i].chan2)) return AVERROR_INVALIDDATA; ch_mask |= 1 << s->mcdparams[i].chan2; } else if (!(ch_mask & 1 << s->mcdparams[i].chan2)) { return AVERROR_INVALIDDATA; } } s->mcdparams[i].chan1 = nbit; ch_mask |= 1 << nbit; } } else { chan = avctx->channels; for (i = 0; i < chan; i++) { s->mcdparams[i].present = 0; s->mcdparams[i].chan1 = i; } } for (i = 0; i < chan; i++) { if (s->mcdparams[i].present && s->mcdparams[i].index == 1) if (ret = decode_channel(s, s->mcdparams[i].chan2)) return ret; if (ret = decode_channel(s, s->mcdparams[i].chan1)) return ret; if (s->mcdparams[i].present) { s->dmode = mc_dmodes[s->mcdparams[i].index]; if (ret = decorrelate(s, s->mcdparams[i].chan2, s->mcdparams[i].chan1, s->nb_samples - 1)) return ret; } } } for (chan = 0; chan < avctx->channels; chan++) { int32_t *decoded = s->decoded[chan]; if (s->lpc_mode[chan]) decode_lpc(decoded, s->lpc_mode[chan], s->nb_samples); if (s->sample_shift[chan] > 0) for (i = 0; i < s->nb_samples; i++) decoded[i] <<= s->sample_shift[chan]; } } align_get_bits(gb); skip_bits(gb, 24); if (get_bits_left(gb) < 0) av_log(avctx, AV_LOG_DEBUG, "overread\n"); else if (get_bits_left(gb) > 0) av_log(avctx, AV_LOG_DEBUG, "underread\n"); if (avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_COMPLIANT)) { if (ff_tak_check_crc(pkt->data + hsize, get_bits_count(gb) / 8 - hsize)) { av_log(avctx, AV_LOG_ERROR, "CRC error\n"); if (avctx->err_recognition & AV_EF_EXPLODE) return AVERROR_INVALIDDATA; } } /* convert to output buffer */ switch (avctx->sample_fmt) { case AV_SAMPLE_FMT_U8P: for (chan = 0; chan < avctx->channels; chan++) { uint8_t *samples = (uint8_t *)frame->extended_data[chan]; int32_t *decoded = s->decoded[chan]; for (i = 0; i < s->nb_samples; i++) samples[i] = decoded[i] + 0x80; } break; case AV_SAMPLE_FMT_S16P: for (chan = 0; chan < avctx->channels; chan++) { int16_t *samples = (int16_t *)frame->extended_data[chan]; int32_t *decoded = s->decoded[chan]; for (i = 0; i < s->nb_samples; i++) samples[i] = decoded[i]; } break; case AV_SAMPLE_FMT_S32P: for (chan = 0; chan < avctx->channels; chan++) { int32_t *samples = (int32_t *)frame->extended_data[chan]; for (i = 0; i < s->nb_samples; i++) samples[i] <<= 8; } break; } *got_frame_ptr = 1; return pkt->size; }


static BlockBackend *img_open_opts(const char *optstr, QemuOpts *opts, int flags, bool writethrough, bool quiet, bool force_share) { QDict *options; Error *local_err = NULL; BlockBackend *blk; options = qemu_opts_to_qdict(opts, NULL); if (force_share) { if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE) && !qdict_get_bool(options, BDRV_OPT_FORCE_SHARE)) { error_report("--force-share/-U conflicts with image options"); return NULL; } qdict_put(options, BDRV_OPT_FORCE_SHARE, qbool_from_bool(true)); } blk = blk_new_open(NULL, NULL, options, flags, &local_err); if (!blk) { error_reportf_err(local_err, "Could not open '%s': ", optstr); return NULL; } blk_set_enable_write_cache(blk, !writethrough); if (img_open_password(blk, optstr, flags, quiet) < 0) { blk_unref(blk); return NULL; } return blk; }


static void qmp_input_type_bool(Visitor *v, bool *obj, const char *name, Error **errp) { QmpInputVisitor *qiv = to_qiv(v); QObject *qobj = qmp_input_get_object(qiv, name, true); if (!qobj || qobject_type(qobj) != QTYPE_QBOOL) { error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name ? name : "null", "boolean"); return; } *obj = qbool_get_bool(qobject_to_qbool(qobj)); }


static int create_vorbis_context(vorbis_enc_context *venc, AVCodecContext *avccontext) { vorbis_enc_floor *fc; vorbis_enc_residue *rc; vorbis_enc_mapping *mc; int i, book, ret; venc->channels = avccontext->channels; venc->sample_rate = avccontext->sample_rate; venc->log2_blocksize[0] = venc->log2_blocksize[1] = 11; venc->ncodebooks = FF_ARRAY_ELEMS(cvectors); venc->codebooks = av_malloc(sizeof(vorbis_enc_codebook) * venc->ncodebooks); if (!venc->codebooks) return AVERROR(ENOMEM); // codebook 0..14 - floor1 book, values 0..255 // codebook 15 residue masterbook // codebook 16..29 residue for (book = 0; book < venc->ncodebooks; book++) { vorbis_enc_codebook *cb = &venc->codebooks[book]; int vals; cb->ndimensions = cvectors[book].dim; cb->nentries = cvectors[book].real_len; cb->min = cvectors[book].min; cb->delta = cvectors[book].delta; cb->lookup = cvectors[book].lookup; cb->seq_p = 0; cb->lens = av_malloc(sizeof(uint8_t) * cb->nentries); cb->codewords = av_malloc(sizeof(uint32_t) * cb->nentries); if (!cb->lens || !cb->codewords) return AVERROR(ENOMEM); memcpy(cb->lens, cvectors[book].clens, cvectors[book].len); memset(cb->lens + cvectors[book].len, 0, cb->nentries - cvectors[book].len); if (cb->lookup) { vals = cb_lookup_vals(cb->lookup, cb->ndimensions, cb->nentries); cb->quantlist = av_malloc(sizeof(int) * vals); if (!cb->quantlist) return AVERROR(ENOMEM); for (i = 0; i < vals; i++) cb->quantlist[i] = cvectors[book].quant[i]; } else { cb->quantlist = NULL; } if ((ret = ready_codebook(cb)) < 0) return ret; } venc->nfloors = 1; venc->floors = av_malloc(sizeof(vorbis_enc_floor) * venc->nfloors); if (!venc->floors) return AVERROR(ENOMEM); // just 1 floor fc = &venc->floors[0]; fc->partitions = NUM_FLOOR_PARTITIONS; fc->partition_to_class = av_malloc(sizeof(int) * fc->partitions); if (!fc->partition_to_class) return AVERROR(ENOMEM); fc->nclasses = 0; for (i = 0; i < fc->partitions; i++) { static const int a[] = {0, 1, 2, 2, 3, 3, 4, 4}; fc->partition_to_class[i] = a[i]; fc->nclasses = FFMAX(fc->nclasses, fc->partition_to_class[i]); } fc->nclasses++; fc->classes = av_malloc(sizeof(vorbis_enc_floor_class) * fc->nclasses); if (!fc->classes) return AVERROR(ENOMEM); for (i = 0; i < fc->nclasses; i++) { vorbis_enc_floor_class * c = &fc->classes[i]; int j, books; c->dim = floor_classes[i].dim; c->subclass = floor_classes[i].subclass; c->masterbook = floor_classes[i].masterbook; books = (1 << c->subclass); c->books = av_malloc(sizeof(int) * books); if (!c->books) return AVERROR(ENOMEM); for (j = 0; j < books; j++) c->books[j] = floor_classes[i].nbooks[j]; } fc->multiplier = 2; fc->rangebits = venc->log2_blocksize[0] - 1; fc->values = 2; for (i = 0; i < fc->partitions; i++) fc->values += fc->classes[fc->partition_to_class[i]].dim; fc->list = av_malloc(sizeof(vorbis_floor1_entry) * fc->values); if (!fc->list) return AVERROR(ENOMEM); fc->list[0].x = 0; fc->list[1].x = 1 << fc->rangebits; for (i = 2; i < fc->values; i++) { static const int a[] = { 93, 23,372, 6, 46,186,750, 14, 33, 65, 130,260,556, 3, 10, 18, 28, 39, 55, 79, 111,158,220,312,464,650,850 }; fc->list[i].x = a[i - 2]; } ff_vorbis_ready_floor1_list(fc->list, fc->values); venc->nresidues = 1; venc->residues = av_malloc(sizeof(vorbis_enc_residue) * venc->nresidues); if (!venc->residues) return AVERROR(ENOMEM); // single residue rc = &venc->residues[0]; rc->type = 2; rc->begin = 0; rc->end = 1600; rc->partition_size = 32; rc->classifications = 10; rc->classbook = 15; rc->books = av_malloc(sizeof(*rc->books) * rc->classifications); if (!rc->books) return AVERROR(ENOMEM); { static const int8_t a[10][8] = { { -1, -1, -1, -1, -1, -1, -1, -1, }, { -1, -1, 16, -1, -1, -1, -1, -1, }, { -1, -1, 17, -1, -1, -1, -1, -1, }, { -1, -1, 18, -1, -1, -1, -1, -1, }, { -1, -1, 19, -1, -1, -1, -1, -1, }, { -1, -1, 20, -1, -1, -1, -1, -1, }, { -1, -1, 21, -1, -1, -1, -1, -1, }, { 22, 23, -1, -1, -1, -1, -1, -1, }, { 24, 25, -1, -1, -1, -1, -1, -1, }, { 26, 27, 28, -1, -1, -1, -1, -1, }, }; memcpy(rc->books, a, sizeof a); } if ((ret = ready_residue(rc, venc)) < 0) return ret; venc->nmappings = 1; venc->mappings = av_malloc(sizeof(vorbis_enc_mapping) * venc->nmappings); if (!venc->mappings) return AVERROR(ENOMEM); // single mapping mc = &venc->mappings[0]; mc->submaps = 1; mc->mux = av_malloc(sizeof(int) * venc->channels); if (!mc->mux) return AVERROR(ENOMEM); for (i = 0; i < venc->channels; i++) mc->mux[i] = 0; mc->floor = av_malloc(sizeof(int) * mc->submaps); mc->residue = av_malloc(sizeof(int) * mc->submaps); if (!mc->floor || !mc->residue) return AVERROR(ENOMEM); for (i = 0; i < mc->submaps; i++) { mc->floor[i] = 0; mc->residue[i] = 0; } mc->coupling_steps = venc->channels == 2 ? 1 : 0; mc->magnitude = av_malloc(sizeof(int) * mc->coupling_steps); mc->angle = av_malloc(sizeof(int) * mc->coupling_steps); if (!mc->magnitude || !mc->angle) return AVERROR(ENOMEM); if (mc->coupling_steps) { mc->magnitude[0] = 0; mc->angle[0] = 1; } venc->nmodes = 1; venc->modes = av_malloc(sizeof(vorbis_enc_mode) * venc->nmodes); if (!venc->modes) return AVERROR(ENOMEM); // single mode venc->modes[0].blockflag = 0; venc->modes[0].mapping = 0; venc->have_saved = 0; venc->saved = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2); venc->samples = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1])); venc->floor = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2); venc->coeffs = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2); if (!venc->saved || !venc->samples || !venc->floor || !venc->coeffs) return AVERROR(ENOMEM); venc->win[0] = ff_vorbis_vwin[venc->log2_blocksize[0] - 6]; venc->win[1] = ff_vorbis_vwin[venc->log2_blocksize[1] - 6]; if ((ret = ff_mdct_init(&venc->mdct[0], venc->log2_blocksize[0], 0, 1.0)) < 0) return ret; if ((ret = ff_mdct_init(&venc->mdct[1], venc->log2_blocksize[1], 0, 1.0)) < 0) return ret; return 0; }


set_phy_ctrl(E1000State *s, int index, uint16_t val) { if ((val & MII_CR_AUTO_NEG_EN) && (val & MII_CR_RESTART_AUTO_NEG)) { qemu_get_queue(s->nic)->link_down = true; e1000_link_down(s); s->phy_reg[PHY_STATUS] &= ~MII_SR_AUTONEG_COMPLETE; DBGOUT(PHY, "Start link auto negotiation\n"); qemu_mod_timer(s->autoneg_timer, qemu_get_clock_ms(vm_clock) + 500); } }


PCIBus *i440fx_init(PCII440FXState **pi440fx_state, int *piix3_devfn, qemu_irq *pic) { DeviceState *dev; PCIBus *b; PCIDevice *d; I440FXState *s; PIIX3State *piix3; dev = qdev_create(NULL, "i440FX-pcihost"); s = FROM_SYSBUS(I440FXState, sysbus_from_qdev(dev)); b = pci_bus_new(&s->busdev.qdev, NULL, 0); s->bus = b; qdev_init(dev); d = pci_create_simple(b, 0, "i440FX"); *pi440fx_state = DO_UPCAST(PCII440FXState, dev, d); piix3 = DO_UPCAST(PIIX3State, dev, pci_create_simple(b, -1, "PIIX3")); piix3->pic = pic; pci_bus_irqs(b, piix3_set_irq, pci_slot_get_pirq, piix3, 4); (*pi440fx_state)->piix3 = piix3; *piix3_devfn = piix3->dev.devfn; return b; }


static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int64_t start; int i, nb_chapters, str_len, version; char str[256+1]; if ((atom.size -= 5) < 0) return 0; version = avio_r8(pb); avio_rb24(pb); if (version) avio_rb32(pb); // ??? nb_chapters = avio_r8(pb); for (i = 0; i < nb_chapters; i++) { if (atom.size < 9) return 0; start = avio_rb64(pb); str_len = avio_r8(pb); if ((atom.size -= 9+str_len) < 0) return 0; avio_read(pb, str, str_len); str[str_len] = 0; avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str); } return 0; }


static void do_wav_capture(Monitor *mon, const QDict *qdict) { const char *path = qdict_get_str(qdict, "path"); int has_freq = qdict_haskey(qdict, "freq"); int freq = qdict_get_try_int(qdict, "freq", -1); int has_bits = qdict_haskey(qdict, "bits"); int bits = qdict_get_try_int(qdict, "bits", -1); int has_channels = qdict_haskey(qdict, "nchannels"); int nchannels = qdict_get_try_int(qdict, "nchannels", -1); CaptureState *s; s = qemu_mallocz (sizeof (*s)); freq = has_freq ? freq : 44100; bits = has_bits ? bits : 16; nchannels = has_channels ? nchannels : 2; if (wav_start_capture (s, path, freq, bits, nchannels)) { monitor_printf(mon, "Faied to add wave capture\n"); qemu_free (s); } QLIST_INSERT_HEAD (&capture_head, s, entries); }


static int old_codec47(SANMVideoContext *ctx, int top, int left, int width, int height) { int i, j, seq, compr, new_rot, tbl_pos, skip; int stride = ctx->pitch; uint8_t *dst = ((uint8_t*)ctx->frm0) + left + top * stride; uint8_t *prev1 = (uint8_t*)ctx->frm1; uint8_t *prev2 = (uint8_t*)ctx->frm2; uint32_t decoded_size; tbl_pos = bytestream2_tell(&ctx->gb); seq = bytestream2_get_le16(&ctx->gb); compr = bytestream2_get_byte(&ctx->gb); new_rot = bytestream2_get_byte(&ctx->gb); skip = bytestream2_get_byte(&ctx->gb); bytestream2_skip(&ctx->gb, 9); decoded_size = bytestream2_get_le32(&ctx->gb); bytestream2_skip(&ctx->gb, 8); if (decoded_size > height * stride - left - top * stride) { decoded_size = height * stride - left - top * stride; av_log(ctx->avctx, AV_LOG_WARNING, "decoded size is too large\n"); } if (skip & 1) bytestream2_skip(&ctx->gb, 0x8080); if (!seq) { ctx->prev_seq = -1; memset(prev1, 0, ctx->height * stride); memset(prev2, 0, ctx->height * stride); } av_dlog(ctx->avctx, "compression %d\n", compr); switch (compr) { case 0: if (bytestream2_get_bytes_left(&ctx->gb) < width * height) return AVERROR_INVALIDDATA; for (j = 0; j < height; j++) { bytestream2_get_bufferu(&ctx->gb, dst, width); dst += stride; } break; case 1: if (bytestream2_get_bytes_left(&ctx->gb) < ((width + 1) >> 1) * ((height + 1) >> 1)) return AVERROR_INVALIDDATA; for (j = 0; j < height; j += 2) { for (i = 0; i < width; i += 2) { dst[i] = dst[i + 1] = dst[stride + i] = dst[stride + i + 1] = bytestream2_get_byteu(&ctx->gb); } dst += stride * 2; } break; case 2: if (seq == ctx->prev_seq + 1) { for (j = 0; j < height; j += 8) { for (i = 0; i < width; i += 8) { if (process_block(ctx, dst + i, prev1 + i, prev2 + i, stride, tbl_pos + 8, 8)) return AVERROR_INVALIDDATA; } dst += stride * 8; prev1 += stride * 8; prev2 += stride * 8; } } break; case 3: memcpy(ctx->frm0, ctx->frm2, ctx->pitch * ctx->height); break; case 4: memcpy(ctx->frm0, ctx->frm1, ctx->pitch * ctx->height); break; case 5: if (rle_decode(ctx, dst, decoded_size)) return AVERROR_INVALIDDATA; break; default: av_log(ctx->avctx, AV_LOG_ERROR, "subcodec 47 compression %d not implemented\n", compr); return AVERROR_PATCHWELCOME; } if (seq == ctx->prev_seq + 1) ctx->rotate_code = new_rot; else ctx->rotate_code = 0; ctx->prev_seq = seq; return 0; }


static av_cold int vtenc_close(AVCodecContext *avctx) { VTEncContext *vtctx = avctx->priv_data; if(!vtctx->session) return 0; VTCompressionSessionInvalidate(vtctx->session); pthread_cond_destroy(&vtctx->cv_sample_sent); pthread_mutex_destroy(&vtctx->lock); CFRelease(vtctx->session); vtctx->session = NULL; return 0; }


static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = av_q2d(find_fps(s, st)); if (!tag) tag = MKTAG('m', '2', 'v', '1'); //fallback tag if (track->par->format == AV_PIX_FMT_YUV420P) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','4'); else if (rate == 25) tag = MKTAG('x','d','v','5'); else if (rate == 30) tag = MKTAG('x','d','v','1'); else if (rate == 50) tag = MKTAG('x','d','v','a'); else if (rate == 60) tag = MKTAG('x','d','v','9'); } } else if (track->par->width == 1440 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','6'); else if (rate == 25) tag = MKTAG('x','d','v','7'); else if (rate == 30) tag = MKTAG('x','d','v','8'); } else { if (rate == 25) tag = MKTAG('x','d','v','3'); else if (rate == 30) tag = MKTAG('x','d','v','2'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','d'); else if (rate == 25) tag = MKTAG('x','d','v','e'); else if (rate == 30) tag = MKTAG('x','d','v','f'); } else { if (rate == 25) tag = MKTAG('x','d','v','c'); else if (rate == 30) tag = MKTAG('x','d','v','b'); } } } else if (track->par->format == AV_PIX_FMT_YUV422P) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','5','4'); else if (rate == 25) tag = MKTAG('x','d','5','5'); else if (rate == 30) tag = MKTAG('x','d','5','1'); else if (rate == 50) tag = MKTAG('x','d','5','a'); else if (rate == 60) tag = MKTAG('x','d','5','9'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','5','d'); else if (rate == 25) tag = MKTAG('x','d','5','e'); else if (rate == 30) tag = MKTAG('x','d','5','f'); } else { if (rate == 25) tag = MKTAG('x','d','5','c'); else if (rate == 30) tag = MKTAG('x','d','5','b'); } } } return tag; }


static int apply_color_indexing_transform(WebPContext *s) { ImageContext *img; ImageContext *pal; int i, x, y; uint8_t *p, *pi; img = &s->image[IMAGE_ROLE_ARGB]; pal = &s->image[IMAGE_ROLE_COLOR_INDEXING]; if (pal->size_reduction > 0) { GetBitContext gb_g; uint8_t *line; int pixel_bits = 8 >> pal->size_reduction; line = av_malloc(img->frame->linesize[0]); if (!line) return AVERROR(ENOMEM); for (y = 0; y < img->frame->height; y++) { p = GET_PIXEL(img->frame, 0, y); memcpy(line, p, img->frame->linesize[0]); init_get_bits(&gb_g, line, img->frame->linesize[0] * 8); skip_bits(&gb_g, 16); i = 0; for (x = 0; x < img->frame->width; x++) { p = GET_PIXEL(img->frame, x, y); p[2] = get_bits(&gb_g, pixel_bits); i++; if (i == 1 << pal->size_reduction) { skip_bits(&gb_g, 24); i = 0; } } } av_free(line); } for (y = 0; y < img->frame->height; y++) { for (x = 0; x < img->frame->width; x++) { p = GET_PIXEL(img->frame, x, y); i = p[2]; if (i >= pal->frame->width) { av_log(s->avctx, AV_LOG_ERROR, "invalid palette index %d\n", i); return AVERROR_INVALIDDATA; } pi = GET_PIXEL(pal->frame, i, 0); AV_COPY32(p, pi); } } return 0; }


static void pnv_chip_power8e_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); PnvChipClass *k = PNV_CHIP_CLASS(klass); k->cpu_model = "POWER8E"; k->chip_type = PNV_CHIP_POWER8E; k->chip_cfam_id = 0x221ef04980000000ull; /* P8 Murano DD2.1 */ k->cores_mask = POWER8E_CORE_MASK; k->core_pir = pnv_chip_core_pir_p8; dc->desc = "PowerNV Chip POWER8E"; }


void uhci_port_test(struct qhc *hc, int port, uint16_t expect) { void *addr = hc->base + 0x10 + 2 * port; uint16_t value = qpci_io_readw(hc->dev, addr); uint16_t mask = ~(UHCI_PORT_WRITE_CLEAR | UHCI_PORT_RSVD1); g_assert((value & mask) == (expect & mask)); }


GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp) { PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr; DWORD length; GuestLogicalProcessorList *head, **link; Error *local_err = NULL; int64_t current; ptr = pslpi = NULL; length = 0; current = 0; head = NULL; link = &head; if ((GetLogicalProcessorInformation(pslpi, &length) == FALSE) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER) && (length > sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))) { ptr = pslpi = g_malloc0(length); if (GetLogicalProcessorInformation(pslpi, &length) == FALSE) { error_setg(&local_err, "Failed to get processor information: %d", (int)GetLastError()); } } else { error_setg(&local_err, "Failed to get processor information buffer length: %d", (int)GetLastError()); } while ((local_err == NULL) && (length > 0)) { if (pslpi->Relationship == RelationProcessorCore) { ULONG_PTR cpu_bits = pslpi->ProcessorMask; while (cpu_bits > 0) { if (!!(cpu_bits & 1)) { GuestLogicalProcessor *vcpu; GuestLogicalProcessorList *entry; vcpu = g_malloc0(sizeof *vcpu); vcpu->logical_id = current++; vcpu->online = true; vcpu->has_can_offline = false; entry = g_malloc0(sizeof *entry); entry->value = vcpu; *link = entry; link = &entry->next; } cpu_bits >>= 1; } } length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); pslpi++; /* next entry */ } g_free(ptr); if (local_err == NULL) { if (head != NULL) { return head; } /* there's no guest with zero VCPUs */ error_setg(&local_err, "Guest reported zero VCPUs"); } qapi_free_GuestLogicalProcessorList(head); error_propagate(errp, local_err); return NULL; }


static bool bdrv_drain_poll(BlockDriverState *bs) { bool waited = false; while (atomic_read(&bs->in_flight) > 0) { aio_poll(bdrv_get_aio_context(bs), true); waited = true; } return waited; }


static void cpu_exec_step(CPUState *cpu) { CPUClass *cc = CPU_GET_CLASS(cpu); TranslationBlock *tb; target_ulong cs_base, pc; uint32_t flags; uint32_t cflags = 1 | CF_IGNORE_ICOUNT; if (sigsetjmp(cpu->jmp_env, 0) == 0) { tb = tb_lookup__cpu_state(cpu, &pc, &cs_base, &flags, cflags & CF_HASH_MASK); if (tb == NULL) { mmap_lock(); tb_lock(); tb = tb_gen_code(cpu, pc, cs_base, flags, cflags); tb_unlock(); mmap_unlock(); } cc->cpu_exec_enter(cpu); /* execute the generated code */ trace_exec_tb(tb, pc); cpu_tb_exec(cpu, tb); cc->cpu_exec_exit(cpu); } else { /* We may have exited due to another problem here, so we need * to reset any tb_locks we may have taken but didn't release. * The mmap_lock is dropped by tb_gen_code if it runs out of * memory. */ #ifndef CONFIG_SOFTMMU tcg_debug_assert(!have_mmap_lock()); #endif tb_lock_reset(); } }


static bool intel_hda_xfer(HDACodecDevice *dev, uint32_t stnr, bool output, uint8_t *buf, uint32_t len) { HDACodecBus *bus = DO_UPCAST(HDACodecBus, qbus, dev->qdev.parent_bus); IntelHDAState *d = container_of(bus, IntelHDAState, codecs); target_phys_addr_t addr; uint32_t s, copy, left; IntelHDAStream *st; bool irq = false; st = output ? d->st + 4 : d->st; for (s = 0; s < 4; s++) { if (stnr == ((st[s].ctl >> 20) & 0x0f)) { st = st + s; break; } } if (s == 4) { return false; } if (st->bpl == NULL) { return false; } if (st->ctl & (1 << 26)) { /* * Wait with the next DMA xfer until the guest * has acked the buffer completion interrupt */ return false; } left = len; while (left > 0) { copy = left; if (copy > st->bsize - st->lpib) copy = st->bsize - st->lpib; if (copy > st->bpl[st->be].len - st->bp) copy = st->bpl[st->be].len - st->bp; dprint(d, 3, "dma: entry %d, pos %d/%d, copy %d\n", st->be, st->bp, st->bpl[st->be].len, copy); pci_dma_rw(&d->pci, st->bpl[st->be].addr + st->bp, buf, copy, !output); st->lpib += copy; st->bp += copy; buf += copy; left -= copy; if (st->bpl[st->be].len == st->bp) { /* bpl entry filled */ if (st->bpl[st->be].flags & 0x01) { irq = true; } st->bp = 0; st->be++; if (st->be == st->bentries) { /* bpl wrap around */ st->be = 0; st->lpib = 0; } } } if (d->dp_lbase & 0x01) { addr = intel_hda_addr(d->dp_lbase & ~0x01, d->dp_ubase); stl_le_pci_dma(&d->pci, addr + 8*s, st->lpib); } dprint(d, 3, "dma: --\n"); if (irq) { st->ctl |= (1 << 26); /* buffer completion interrupt */ intel_hda_update_irq(d); } return true; }


int64_t qmp_guest_get_time(Error **errp) { int ret; qemu_timeval tq; int64_t time_ns; ret = qemu_gettimeofday(&tq); if (ret < 0) { error_setg_errno(errp, errno, "Failed to get time"); return -1; } time_ns = tq.tv_sec * 1000000000LL + tq.tv_usec * 1000; return time_ns; }


static int check_strtox_error(const char *nptr, char *ep, const char **endptr, int libc_errno) { if (libc_errno == 0 && ep == nptr) { libc_errno = EINVAL; } if (!endptr && *ep) { return -EINVAL; } if (endptr) { *endptr = ep; } return -libc_errno; }