DriveInfo *drive_init(QemuOpts *all_opts, BlockInterfaceType block_default_type) { const char *value; DriveInfo *dinfo = NULL; QDict *bs_opts; QemuOpts *legacy_opts; DriveMediaType media = MEDIA_DISK; BlockInterfaceType type; int cyls, heads, secs, translation; int max_devs, bus_id, unit_id, index; const char *devaddr; bool read_only = false; bool copy_on_read; const char *filename; Error *local_err = NULL; /* Change legacy command line options into QMP ones */ qemu_opt_rename(all_opts, "iops", "throttling.iops-total"); qemu_opt_rename(all_opts, "iops_rd", "throttling.iops-read"); qemu_opt_rename(all_opts, "iops_wr", "throttling.iops-write"); qemu_opt_rename(all_opts, "bps", "throttling.bps-total"); qemu_opt_rename(all_opts, "bps_rd", "throttling.bps-read"); qemu_opt_rename(all_opts, "bps_wr", "throttling.bps-write"); qemu_opt_rename(all_opts, "iops_max", "throttling.iops-total-max"); qemu_opt_rename(all_opts, "iops_rd_max", "throttling.iops-read-max"); qemu_opt_rename(all_opts, "iops_wr_max", "throttling.iops-write-max"); qemu_opt_rename(all_opts, "bps_max", "throttling.bps-total-max"); qemu_opt_rename(all_opts, "bps_rd_max", "throttling.bps-read-max"); qemu_opt_rename(all_opts, "bps_wr_max", "throttling.bps-write-max"); qemu_opt_rename(all_opts, "iops_size", "throttling.iops-size"); qemu_opt_rename(all_opts, "readonly", "read-only"); value = qemu_opt_get(all_opts, "cache"); if (value) { int flags = 0; if (bdrv_parse_cache_flags(value, &flags) != 0) { error_report("invalid cache option"); return NULL; } /* Specific options take precedence */ if (!qemu_opt_get(all_opts, "cache.writeback")) { qemu_opt_set_bool(all_opts, "cache.writeback", !!(flags & BDRV_O_CACHE_WB)); } if (!qemu_opt_get(all_opts, "cache.direct")) { qemu_opt_set_bool(all_opts, "cache.direct", !!(flags & BDRV_O_NOCACHE)); } if (!qemu_opt_get(all_opts, "cache.no-flush")) { qemu_opt_set_bool(all_opts, "cache.no-flush", !!(flags & BDRV_O_NO_FLUSH)); } qemu_opt_unset(all_opts, "cache"); } /* Get a QDict for processing the options */ bs_opts = qdict_new(); qemu_opts_to_qdict(all_opts, bs_opts); legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0, &error_abort); qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err); if (error_is_set(&local_err)) { qerror_report_err(local_err); error_free(local_err); goto fail; } /* Deprecated option boot=[on|off] */ if (qemu_opt_get(legacy_opts, "boot") != NULL) { fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be " "ignored. Future versions will reject this parameter. Please " "update your scripts.\n"); } /* Media type */ value = qemu_opt_get(legacy_opts, "media"); if (value) { if (!strcmp(value, "disk")) { media = MEDIA_DISK; } else if (!strcmp(value, "cdrom")) { media = MEDIA_CDROM; read_only = true; } else { error_report("'%s' invalid media", value); goto fail; } } /* copy-on-read is disabled with a warning for read-only devices */ read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false); copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false); if (read_only && copy_on_read) { error_report("warning: disabling copy-on-read on read-only drive"); copy_on_read = false; } qdict_put(bs_opts, "read-only", qstring_from_str(read_only ? "on" : "off")); qdict_put(bs_opts, "copy-on-read", qstring_from_str(copy_on_read ? "on" :"off")); /* Controller type */ value = qemu_opt_get(legacy_opts, "if"); if (value) { for (type = 0; type < IF_COUNT && strcmp(value, if_name[type]); type++) { } if (type == IF_COUNT) { error_report("unsupported bus type '%s'", value); goto fail; } } else { type = block_default_type; } /* Geometry */ cyls = qemu_opt_get_number(legacy_opts, "cyls", 0); heads = qemu_opt_get_number(legacy_opts, "heads", 0); secs = qemu_opt_get_number(legacy_opts, "secs", 0); if (cyls || heads || secs) { if (cyls < 1) { error_report("invalid physical cyls number"); goto fail; } if (heads < 1) { error_report("invalid physical heads number"); goto fail; } if (secs < 1) { error_report("invalid physical secs number"); goto fail; } } translation = BIOS_ATA_TRANSLATION_AUTO; value = qemu_opt_get(legacy_opts, "trans"); if (value != NULL) { if (!cyls) { error_report("'%s' trans must be used with cyls, heads and secs", value); goto fail; } if (!strcmp(value, "none")) { translation = BIOS_ATA_TRANSLATION_NONE; } else if (!strcmp(value, "lba")) { translation = BIOS_ATA_TRANSLATION_LBA; } else if (!strcmp(value, "auto")) { translation = BIOS_ATA_TRANSLATION_AUTO; } else { error_report("'%s' invalid translation type", value); goto fail; } } if (media == MEDIA_CDROM) { if (cyls || secs || heads) { error_report("CHS can't be set with media=cdrom"); goto fail; } } /* Device address specified by bus/unit or index. * If none was specified, try to find the first free one. */ bus_id = qemu_opt_get_number(legacy_opts, "bus", 0); unit_id = qemu_opt_get_number(legacy_opts, "unit", -1); index = qemu_opt_get_number(legacy_opts, "index", -1); max_devs = if_max_devs[type]; if (index != -1) { if (bus_id != 0 || unit_id != -1) { error_report("index cannot be used with bus and unit"); goto fail; } bus_id = drive_index_to_bus_id(type, index); unit_id = drive_index_to_unit_id(type, index); } if (unit_id == -1) { unit_id = 0; while (drive_get(type, bus_id, unit_id) != NULL) { unit_id++; if (max_devs && unit_id >= max_devs) { unit_id -= max_devs; bus_id++; } } } if (max_devs && unit_id >= max_devs) { error_report("unit %d too big (max is %d)", unit_id, max_devs - 1); goto fail; } if (drive_get(type, bus_id, unit_id) != NULL) { error_report("drive with bus=%d, unit=%d (index=%d) exists", bus_id, unit_id, index); goto fail; } /* no id supplied -> create one */ if (qemu_opts_id(all_opts) == NULL) { char *new_id; const char *mediastr = ""; if (type == IF_IDE || type == IF_SCSI) { mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd"; } if (max_devs) { new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id, mediastr, unit_id); } else { new_id = g_strdup_printf("%s%s%i", if_name[type], mediastr, unit_id); } qdict_put(bs_opts, "id", qstring_from_str(new_id)); g_free(new_id); } /* Add virtio block device */ devaddr = qemu_opt_get(legacy_opts, "addr"); if (devaddr && type != IF_VIRTIO) { error_report("addr is not supported by this bus type"); goto fail; } if (type == IF_VIRTIO) { QemuOpts *devopts; devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0, &error_abort); if (arch_type == QEMU_ARCH_S390X) { qemu_opt_set(devopts, "driver", "virtio-blk-s390"); } else { qemu_opt_set(devopts, "driver", "virtio-blk-pci"); } qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id")); if (devaddr) { qemu_opt_set(devopts, "addr", devaddr); } } filename = qemu_opt_get(legacy_opts, "file"); /* Actual block device init: Functionality shared with blockdev-add */ dinfo = blockdev_init(filename, bs_opts, type, &local_err); if (dinfo == NULL) { if (error_is_set(&local_err)) { qerror_report_err(local_err); error_free(local_err); } goto fail; } else { assert(!error_is_set(&local_err)); } /* Set legacy DriveInfo fields */ dinfo->enable_auto_del = true; dinfo->opts = all_opts; dinfo->cyls = cyls; dinfo->heads = heads; dinfo->secs = secs; dinfo->trans = translation; dinfo->bus = bus_id; dinfo->unit = unit_id; dinfo->devaddr = devaddr; switch(type) { case IF_IDE: case IF_SCSI: case IF_XEN: case IF_NONE: dinfo->media_cd = media == MEDIA_CDROM; break; default: break; } fail: qemu_opts_del(legacy_opts); return dinfo; }


static int cd_read_sector(IDEState *s, int lba, uint8_t *buf, int sector_size) { int ret; switch(sector_size) { case 2048: block_acct_start(bdrv_get_stats(s->bs), &s->acct, 4 * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ); ret = bdrv_read(s->bs, (int64_t)lba << 2, buf, 4); block_acct_done(bdrv_get_stats(s->bs), &s->acct); break; case 2352: block_acct_start(bdrv_get_stats(s->bs), &s->acct, 4 * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ); ret = bdrv_read(s->bs, (int64_t)lba << 2, buf + 16, 4); block_acct_done(bdrv_get_stats(s->bs), &s->acct); if (ret < 0) return ret; cd_data_to_raw(buf, lba); break; default: ret = -EIO; break; } return ret; }


static void av_always_inline filter_mb_edgecv( uint8_t *pix, int stride, const int16_t bS[4], unsigned int qp, H264Context *h, int intra ) { const int qp_bd_offset = 6 * (h->sps.bit_depth_luma - 8); const unsigned int index_a = qp - qp_bd_offset + h->slice_alpha_c0_offset; const int alpha = alpha_table[index_a]; const int beta = beta_table[qp - qp_bd_offset + h->slice_beta_offset]; if (alpha ==0 || beta == 0) return; if( bS[0] < 4 || !intra ) { int8_t tc[4]; tc[0] = tc0_table[index_a][bS[0]]+1; tc[1] = tc0_table[index_a][bS[1]]+1; tc[2] = tc0_table[index_a][bS[2]]+1; tc[3] = tc0_table[index_a][bS[3]]+1; h->h264dsp.h264_h_loop_filter_chroma(pix, stride, alpha, beta, tc); } else { h->h264dsp.h264_h_loop_filter_chroma_intra(pix, stride, alpha, beta); } }


e1000_can_receive(void *opaque) { E1000State *s = opaque; return (s->mac_reg[RCTL] & E1000_RCTL_EN); }


static uint32_t intel_hda_mmio_readl(void *opaque, target_phys_addr_t addr) { IntelHDAState *d = opaque; const IntelHDAReg *reg = intel_hda_reg_find(d, addr); return intel_hda_reg_read(d, reg, 0xffffffff); }


void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd) { if (backing_hd) { bdrv_ref(backing_hd); } if (bs->backing) { assert(bs->backing_blocker); bdrv_op_unblock_all(bs->backing->bs, bs->backing_blocker); bdrv_unref_child(bs, bs->backing); } else if (backing_hd) { error_setg(&bs->backing_blocker, "node is used as backing hd of '%s'", bdrv_get_device_or_node_name(bs)); } if (!backing_hd) { error_free(bs->backing_blocker); bs->backing_blocker = NULL; bs->backing = NULL; goto out; } bs->backing = bdrv_attach_child(bs, backing_hd, &child_backing); bs->open_flags &= ~BDRV_O_NO_BACKING; pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename); pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_hd->drv ? backing_hd->drv->format_name : ""); bdrv_op_block_all(backing_hd, bs->backing_blocker); /* Otherwise we won't be able to commit due to check in bdrv_commit */ bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET, bs->backing_blocker); out: bdrv_refresh_limits(bs, NULL); }


void bdrv_parent_drained_end(BlockDriverState *bs) { BdrvChild *c; QLIST_FOREACH(c, &bs->parents, next_parent) { if (c->role->drained_end) { c->role->drained_end(c); } } }


static void virtio_ccw_crypto_instance_init(Object *obj) { VirtIOCryptoCcw *dev = VIRTIO_CRYPTO_CCW(obj); VirtioCcwDevice *ccw_dev = VIRTIO_CCW_DEVICE(obj); ccw_dev->force_revision_1 = true; virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_CRYPTO); object_property_add_alias(obj, "cryptodev", OBJECT(&dev->vdev), "cryptodev", &error_abort); }


static void gen_bxx(DisasContext *dc, uint32_t code, uint32_t flags) { I_TYPE(instr, code); TCGLabel *l1 = gen_new_label(); tcg_gen_brcond_tl(flags, dc->cpu_R[instr.a], dc->cpu_R[instr.b], l1); gen_goto_tb(dc, 0, dc->pc + 4); gen_set_label(l1); gen_goto_tb(dc, 1, dc->pc + 4 + (instr.imm16s & -4)); dc->is_jmp = DISAS_TB_JUMP; }


static int flic_decode_frame_8BPP(AVCodecContext *avctx, void *data, int *got_frame, const uint8_t *buf, int buf_size) { FlicDecodeContext *s = avctx->priv_data; GetByteContext g2; int pixel_ptr; int palette_ptr; unsigned char palette_idx1; unsigned char palette_idx2; unsigned int frame_size; int num_chunks; unsigned int chunk_size; int chunk_type; int i, j, ret; int color_packets; int color_changes; int color_shift; unsigned char r, g, b; int lines; int compressed_lines; int starting_line; signed short line_packets; int y_ptr; int byte_run; int pixel_skip; int pixel_countdown; unsigned char *pixels; unsigned int pixel_limit; bytestream2_init(&g2, buf, buf_size); if ((ret = ff_reget_buffer(avctx, s->frame)) < 0) return ret; pixels = s->frame->data[0]; pixel_limit = s->avctx->height * s->frame->linesize[0]; if (buf_size < 16 || buf_size > INT_MAX - (3 * 256 + AV_INPUT_BUFFER_PADDING_SIZE)) frame_size = bytestream2_get_le32(&g2); if (frame_size > buf_size) frame_size = buf_size; bytestream2_skip(&g2, 2); /* skip the magic number */ num_chunks = bytestream2_get_le16(&g2); bytestream2_skip(&g2, 8); /* skip padding */ frame_size -= 16; /* iterate through the chunks */ while ((frame_size >= 6) && (num_chunks > 0) && bytestream2_get_bytes_left(&g2) >= 4) { int stream_ptr_after_chunk; chunk_size = bytestream2_get_le32(&g2); if (chunk_size > frame_size) { av_log(avctx, AV_LOG_WARNING, "Invalid chunk_size = %u > frame_size = %u\n", chunk_size, frame_size); chunk_size = frame_size; } stream_ptr_after_chunk = bytestream2_tell(&g2) - 4 + chunk_size; chunk_type = bytestream2_get_le16(&g2); switch (chunk_type) { case FLI_256_COLOR: case FLI_COLOR: /* check special case: If this file is from the Magic Carpet * game and uses 6-bit colors even though it reports 256-color * chunks in a 0xAF12-type file (fli_type is set to 0xAF13 during * initialization) */ if ((chunk_type == FLI_256_COLOR) && (s->fli_type != FLC_MAGIC_CARPET_SYNTHETIC_TYPE_CODE)) color_shift = 0; else color_shift = 2; /* set up the palette */ color_packets = bytestream2_get_le16(&g2); palette_ptr = 0; for (i = 0; i < color_packets; i++) { /* first byte is how many colors to skip */ palette_ptr += bytestream2_get_byte(&g2); /* next byte indicates how many entries to change */ color_changes = bytestream2_get_byte(&g2); /* if there are 0 color changes, there are actually 256 */ if (color_changes == 0) color_changes = 256; if (bytestream2_tell(&g2) + color_changes * 3 > stream_ptr_after_chunk) break; for (j = 0; j < color_changes; j++) { unsigned int entry; /* wrap around, for good measure */ if ((unsigned)palette_ptr >= 256) palette_ptr = 0; r = bytestream2_get_byte(&g2) << color_shift; g = bytestream2_get_byte(&g2) << color_shift; b = bytestream2_get_byte(&g2) << color_shift; entry = 0xFFU << 24 | r << 16 | g << 8 | b; if (color_shift == 2) entry |= entry >> 6 & 0x30303; if (s->palette[palette_ptr] != entry) s->new_palette = 1; s->palette[palette_ptr++] = entry; } } break; case FLI_DELTA: y_ptr = 0; compressed_lines = bytestream2_get_le16(&g2); while (compressed_lines > 0) { if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk) break; line_packets = bytestream2_get_le16(&g2); if ((line_packets & 0xC000) == 0xC000) { // line skip opcode line_packets = -line_packets; y_ptr += line_packets * s->frame->linesize[0]; } else if ((line_packets & 0xC000) == 0x4000) { av_log(avctx, AV_LOG_ERROR, "Undefined opcode (%x) in DELTA_FLI\n", line_packets); } else if ((line_packets & 0xC000) == 0x8000) { // "last byte" opcode pixel_ptr= y_ptr + s->frame->linesize[0] - 1; CHECK_PIXEL_PTR(0); pixels[pixel_ptr] = line_packets & 0xff; } else { compressed_lines--; pixel_ptr = y_ptr; CHECK_PIXEL_PTR(0); pixel_countdown = s->avctx->width; for (i = 0; i < line_packets; i++) { if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk) break; /* account for the skip bytes */ pixel_skip = bytestream2_get_byte(&g2); pixel_ptr += pixel_skip; pixel_countdown -= pixel_skip; byte_run = sign_extend(bytestream2_get_byte(&g2), 8); if (byte_run < 0) { byte_run = -byte_run; palette_idx1 = bytestream2_get_byte(&g2); palette_idx2 = bytestream2_get_byte(&g2); CHECK_PIXEL_PTR(byte_run * 2); for (j = 0; j < byte_run; j++, pixel_countdown -= 2) { pixels[pixel_ptr++] = palette_idx1; pixels[pixel_ptr++] = palette_idx2; } } else { CHECK_PIXEL_PTR(byte_run * 2); if (bytestream2_tell(&g2) + byte_run * 2 > stream_ptr_after_chunk) break; for (j = 0; j < byte_run * 2; j++, pixel_countdown--) { pixels[pixel_ptr++] = bytestream2_get_byte(&g2); } } } y_ptr += s->frame->linesize[0]; } } break; case FLI_LC: /* line compressed */ starting_line = bytestream2_get_le16(&g2); y_ptr = 0; y_ptr += starting_line * s->frame->linesize[0]; compressed_lines = bytestream2_get_le16(&g2); while (compressed_lines > 0) { pixel_ptr = y_ptr; CHECK_PIXEL_PTR(0); pixel_countdown = s->avctx->width; if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk) break; line_packets = bytestream2_get_byte(&g2); if (line_packets > 0) { for (i = 0; i < line_packets; i++) { /* account for the skip bytes */ if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk) break; pixel_skip = bytestream2_get_byte(&g2); pixel_ptr += pixel_skip; pixel_countdown -= pixel_skip; byte_run = sign_extend(bytestream2_get_byte(&g2),8); if (byte_run > 0) { CHECK_PIXEL_PTR(byte_run); if (bytestream2_tell(&g2) + byte_run > stream_ptr_after_chunk) break; for (j = 0; j < byte_run; j++, pixel_countdown--) { pixels[pixel_ptr++] = bytestream2_get_byte(&g2); } } else if (byte_run < 0) { byte_run = -byte_run; palette_idx1 = bytestream2_get_byte(&g2); CHECK_PIXEL_PTR(byte_run); for (j = 0; j < byte_run; j++, pixel_countdown--) { pixels[pixel_ptr++] = palette_idx1; } } } } y_ptr += s->frame->linesize[0]; compressed_lines--; } break; case FLI_BLACK: /* set the whole frame to color 0 (which is usually black) */ memset(pixels, 0, s->frame->linesize[0] * s->avctx->height); break; case FLI_BRUN: /* Byte run compression: This chunk type only occurs in the first * FLI frame and it will update the entire frame. */ y_ptr = 0; for (lines = 0; lines < s->avctx->height; lines++) { pixel_ptr = y_ptr; /* disregard the line packets; instead, iterate through all * pixels on a row */ bytestream2_skip(&g2, 1); pixel_countdown = s->avctx->width; while (pixel_countdown > 0) { if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk) break; byte_run = sign_extend(bytestream2_get_byte(&g2), 8); if (!byte_run) { av_log(avctx, AV_LOG_ERROR, "Invalid byte run value.\n"); } if (byte_run > 0) { palette_idx1 = bytestream2_get_byte(&g2); CHECK_PIXEL_PTR(byte_run); for (j = 0; j < byte_run; j++) { pixels[pixel_ptr++] = palette_idx1; pixel_countdown--; if (pixel_countdown < 0) av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) at line %d\n", pixel_countdown, lines); } } else { /* copy bytes if byte_run < 0 */ byte_run = -byte_run; CHECK_PIXEL_PTR(byte_run); if (bytestream2_tell(&g2) + byte_run > stream_ptr_after_chunk) break; for (j = 0; j < byte_run; j++) { pixels[pixel_ptr++] = bytestream2_get_byte(&g2); pixel_countdown--; if (pixel_countdown < 0) av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) at line %d\n", pixel_countdown, lines); } } } y_ptr += s->frame->linesize[0]; } break; case FLI_COPY: /* copy the chunk (uncompressed frame) */ if (chunk_size - 6 != FFALIGN(s->avctx->width, 4) * s->avctx->height) { av_log(avctx, AV_LOG_ERROR, "In chunk FLI_COPY : source data (%d bytes) " \ "has incorrect size, skipping chunk\n", chunk_size - 6); bytestream2_skip(&g2, chunk_size - 6); } else { for (y_ptr = 0; y_ptr < s->frame->linesize[0] * s->avctx->height; y_ptr += s->frame->linesize[0]) { bytestream2_get_buffer(&g2, &pixels[y_ptr], s->avctx->width); if (s->avctx->width & 3) bytestream2_skip(&g2, 4 - (s->avctx->width & 3)); } } break; case FLI_MINI: /* some sort of a thumbnail? disregard this chunk... */ break; default: av_log(avctx, AV_LOG_ERROR, "Unrecognized chunk type: %d\n", chunk_type); break; } if (stream_ptr_after_chunk - bytestream2_tell(&g2) >= 0) { bytestream2_skip(&g2, stream_ptr_after_chunk - bytestream2_tell(&g2)); } else { av_log(avctx, AV_LOG_ERROR, "Chunk overread\n"); break; } frame_size -= chunk_size; num_chunks--; } /* by the end of the chunk, the stream ptr should equal the frame * size (minus 1 or 2, possibly); if it doesn't, issue a warning */ if (bytestream2_get_bytes_left(&g2) > 2) av_log(avctx, AV_LOG_ERROR, "Processed FLI chunk where chunk size = %d " \ "and final chunk ptr = %d\n", buf_size, buf_size - bytestream2_get_bytes_left(&g2)); /* make the palette available on the way out */ memcpy(s->frame->data[1], s->palette, AVPALETTE_SIZE); if (s->new_palette) { s->frame->palette_has_changed = 1; s->new_palette = 0; } if ((ret = av_frame_ref(data, s->frame)) < 0) return ret; *got_frame = 1; return buf_size; }


static void print_type_size(Visitor *v, const char *name, uint64_t *obj, Error **errp) { StringOutputVisitor *sov = to_sov(v); static const char suffixes[] = { 'B', 'K', 'M', 'G', 'T', 'P', 'E' }; uint64_t div, val; char *out; int i; if (!sov->human) { out = g_strdup_printf("%"PRIu64, *obj); string_output_set(sov, out); return; } val = *obj; /* The exponent (returned in i) minus one gives us * floor(log2(val * 1024 / 1000). The correction makes us * switch to the higher power when the integer part is >= 1000. */ frexp(val / (1000.0 / 1024.0), &i); i = (i - 1) / 10; assert(i < ARRAY_SIZE(suffixes)); div = 1ULL << (i * 10); out = g_strdup_printf("%"PRIu64" (%0.3g %c%s)", val, (double)val/div, suffixes[i], i ? "iB" : ""); string_output_set(sov, out); }


static int cmp_color(const void *a, const void *b) { const struct range_box *box1 = a; const struct range_box *box2 = b; return box1->color - box2->color; }


static void iommu_config_write(void *opaque, hwaddr addr, uint64_t val, unsigned size) { IOMMUState *is = opaque; IOMMU_DPRINTF("IOMMU config write: 0x%" HWADDR_PRIx " val: %" PRIx64 " size: %d\n", addr, val, size); switch (addr) { case IOMMU_CTRL: if (size == 4) { is->regs[IOMMU_CTRL >> 3] &= 0xffffffffULL; is->regs[IOMMU_CTRL >> 3] |= val << 32; } else { is->regs[IOMMU_CTRL] = val; } break; case IOMMU_CTRL + 0x4: is->regs[IOMMU_CTRL >> 3] &= 0xffffffff00000000ULL; is->regs[IOMMU_CTRL >> 3] |= val & 0xffffffffULL; break; case IOMMU_BASE: if (size == 4) { is->regs[IOMMU_BASE >> 3] &= 0xffffffffULL; is->regs[IOMMU_BASE >> 3] |= val << 32; } else { is->regs[IOMMU_BASE] = val; } break; case IOMMU_BASE + 0x4: is->regs[IOMMU_BASE >> 3] &= 0xffffffff00000000ULL; is->regs[IOMMU_BASE >> 3] |= val & 0xffffffffULL; break; default: qemu_log_mask(LOG_UNIMP, "apb iommu: Unimplemented register write " "reg 0x%" HWADDR_PRIx " size 0x%x value 0x%" PRIx64 "\n", addr, size, val); break; } }


static void piix3_ide_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); k->no_hotplug = 1; k->init = pci_piix_ide_initfn; k->exit = pci_piix_ide_exitfn; k->vendor_id = PCI_VENDOR_ID_INTEL; k->device_id = PCI_DEVICE_ID_INTEL_82371SB_1; k->class_id = PCI_CLASS_STORAGE_IDE; set_bit(DEVICE_CATEGORY_STORAGE, dc->categories); dc->no_user = 1; }


static void reconstruct_stereo_16(int32_t *buffer[MAX_CHANNELS], int16_t *buffer_out, int numchannels, int numsamples, uint8_t interlacing_shift, uint8_t interlacing_leftweight) { int i; if (numsamples <= 0) return; /* weighted interlacing */ if (interlacing_leftweight) { for (i = 0; i < numsamples; i++) { int32_t a, b; a = buffer[0][i]; b = buffer[1][i]; a -= (b * interlacing_leftweight) >> interlacing_shift; b += a; buffer_out[i*numchannels] = b; buffer_out[i*numchannels + 1] = a; } return; } /* otherwise basic interlacing took place */ for (i = 0; i < numsamples; i++) { int16_t left, right; left = buffer[0][i]; right = buffer[1][i]; buffer_out[i*numchannels] = left; buffer_out[i*numchannels + 1] = right; } }


av_cold void ff_vp9_init_static(AVCodec *codec) { if ( vpx_codec_version_major() < 1 || (vpx_codec_version_major() == 1 && vpx_codec_version_minor() < 3)) codec->capabilities |= AV_CODEC_CAP_EXPERIMENTAL; codec->pix_fmts = vp9_pix_fmts_def; #if CONFIG_LIBVPX_VP9_ENCODER if ( vpx_codec_version_major() > 1 || (vpx_codec_version_major() == 1 && vpx_codec_version_minor() >= 4)) { #ifdef VPX_CODEC_CAP_HIGHBITDEPTH vpx_codec_caps_t codec_caps = vpx_codec_get_caps(vpx_codec_vp9_cx()); if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) codec->pix_fmts = vp9_pix_fmts_highbd; else #endif codec->pix_fmts = vp9_pix_fmts_highcol; } #endif }


void ioinst_handle_rsch(S390CPU *cpu, uint64_t reg1) { int cssid, ssid, schid, m; SubchDev *sch; int ret = -ENODEV; int cc; if (ioinst_disassemble_sch_ident(reg1, &m, &cssid, &ssid, &schid)) { program_interrupt(&cpu->env, PGM_OPERAND, 2); return; } trace_ioinst_sch_id("rsch", cssid, ssid, schid); sch = css_find_subch(m, cssid, ssid, schid); if (sch && css_subch_visible(sch)) { ret = css_do_rsch(sch); } switch (ret) { case -ENODEV: cc = 3; break; case -EINVAL: cc = 2; break; case 0: cc = 0; break; default: cc = 1; break; } setcc(cpu, cc); }


int kvm_arch_process_irqchip_events(CPUState *env) { return 0; }


static void decode_tones_amplitude(GetBitContext *gb, Atrac3pChanUnitCtx *ctx, int ch_num, int band_has_tones[]) { int mode, sb, j, i, diff, maxdiff, fi, delta, pred; Atrac3pWaveParam *wsrc, *wref; int refwaves[48]; Atrac3pWavesData *dst = ctx->channels[ch_num].tones_info; Atrac3pWavesData *ref = ctx->channels[0].tones_info; if (ch_num) { for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) { if (!band_has_tones[sb] || !dst[sb].num_wavs) continue; wsrc = &ctx->waves_info->waves[dst[sb].start_index]; wref = &ctx->waves_info->waves[ref[sb].start_index]; for (j = 0; j < dst[sb].num_wavs; j++) { for (i = 0, fi = 0, maxdiff = 1024; i < ref[sb].num_wavs; i++) { diff = FFABS(wsrc[j].freq_index - wref[i].freq_index); if (diff < maxdiff) { maxdiff = diff; fi = i; } } if (maxdiff < 8) refwaves[dst[sb].start_index + j] = fi + ref[sb].start_index; else if (j < ref[sb].num_wavs) refwaves[dst[sb].start_index + j] = j + ref[sb].start_index; else refwaves[dst[sb].start_index + j] = -1; } } } mode = get_bits(gb, ch_num + 1); switch (mode) { case 0: /** fixed-length coding */ for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) { if (!band_has_tones[sb] || !dst[sb].num_wavs) continue; if (ctx->waves_info->amplitude_mode) for (i = 0; i < dst[sb].num_wavs; i++) ctx->waves_info->waves[dst[sb].start_index + i].amp_sf = get_bits(gb, 6); else ctx->waves_info->waves[dst[sb].start_index].amp_sf = get_bits(gb, 6); } break; case 1: /** min + VLC delta */ for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) { if (!band_has_tones[sb] || !dst[sb].num_wavs) continue; if (ctx->waves_info->amplitude_mode) for (i = 0; i < dst[sb].num_wavs; i++) ctx->waves_info->waves[dst[sb].start_index + i].amp_sf = get_vlc2(gb, tone_vlc_tabs[3].table, tone_vlc_tabs[3].bits, 1) + 20; else ctx->waves_info->waves[dst[sb].start_index].amp_sf = get_vlc2(gb, tone_vlc_tabs[4].table, tone_vlc_tabs[4].bits, 1) + 24; } break; case 2: /** VLC modulo delta to master (slave only) */ for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) { if (!band_has_tones[sb] || !dst[sb].num_wavs) continue; for (i = 0; i < dst[sb].num_wavs; i++) { delta = get_vlc2(gb, tone_vlc_tabs[5].table, tone_vlc_tabs[5].bits, 1); delta = sign_extend(delta, 5); pred = refwaves[dst[sb].start_index + i] >= 0 ? ctx->waves_info->waves[refwaves[dst[sb].start_index + i]].amp_sf : 34; ctx->waves_info->waves[dst[sb].start_index + i].amp_sf = (pred + delta) & 0x3F; } } break; case 3: /** clone master (slave only) */ for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) { if (!band_has_tones[sb]) continue; for (i = 0; i < dst[sb].num_wavs; i++) ctx->waves_info->waves[dst[sb].start_index + i].amp_sf = refwaves[dst[sb].start_index + i] >= 0 ? ctx->waves_info->waves[refwaves[dst[sb].start_index + i]].amp_sf : 32; } break; } }


static int vhost_net_set_vnet_endian(VirtIODevice *dev, NetClientState *peer, bool set) { int r = 0; if (virtio_has_feature(dev, VIRTIO_F_VERSION_1) || (virtio_legacy_is_cross_endian(dev) && !virtio_is_big_endian(dev))) { r = qemu_set_vnet_le(peer, set); if (r) { error_report("backend does not support LE vnet headers"); } } else if (virtio_legacy_is_cross_endian(dev)) { r = qemu_set_vnet_be(peer, set); if (r) { error_report("backend does not support BE vnet headers"); } } return r; }


static void virtio_net_add_queue(VirtIONet *n, int index) { VirtIODevice *vdev = VIRTIO_DEVICE(n); n->vqs[index].rx_vq = virtio_add_queue(vdev, n->net_conf.rx_queue_size, virtio_net_handle_rx); if (n->net_conf.tx && !strcmp(n->net_conf.tx, "timer")) { n->vqs[index].tx_vq = virtio_add_queue(vdev, 256, virtio_net_handle_tx_timer); n->vqs[index].tx_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, virtio_net_tx_timer, &n->vqs[index]); } else { n->vqs[index].tx_vq = virtio_add_queue(vdev, 256, virtio_net_handle_tx_bh); n->vqs[index].tx_bh = qemu_bh_new(virtio_net_tx_bh, &n->vqs[index]); } n->vqs[index].tx_waiting = 0; n->vqs[index].n = n; }


int virtqueue_avail_bytes(VirtQueue *vq, unsigned int in_bytes, unsigned int out_bytes) { unsigned int in_total, out_total; virtqueue_get_avail_bytes(vq, &in_total, &out_total); if ((in_bytes && in_bytes < in_total) || (out_bytes && out_bytes < out_total)) { return 1; } return 0; }


static always_inline void gen_load_spr(TCGv t, int reg) { tcg_gen_ld_tl(t, cpu_env, offsetof(CPUState, spr[reg])); }


void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs, BlockCompletionFunc *cb, void *opaque) { BlockAIOCB *acb; acb = g_slice_alloc(aiocb_info->aiocb_size); acb->aiocb_info = aiocb_info; acb->bs = bs; acb->cb = cb; acb->opaque = opaque; acb->refcnt = 1; return acb; }


char *socket_address_to_string(struct SocketAddress *addr, Error **errp) { char *buf; InetSocketAddress *inet; switch (addr->type) { case SOCKET_ADDRESS_KIND_INET: inet = addr->u.inet.data; if (strchr(inet->host, ':') == NULL) { buf = g_strdup_printf("%s:%s", inet->host, inet->port); } else { buf = g_strdup_printf("[%s]:%s", inet->host, inet->port); } break; case SOCKET_ADDRESS_KIND_UNIX: buf = g_strdup(addr->u.q_unix.data->path); break; case SOCKET_ADDRESS_KIND_FD: buf = g_strdup(addr->u.fd.data->str); break; case SOCKET_ADDRESS_KIND_VSOCK: buf = g_strdup_printf("%s:%s", addr->u.vsock.data->cid, addr->u.vsock.data->port); break; default: abort(); } return buf; }


static int local_mkdir(FsContext *fs_ctx, V9fsPath *dir_path, const char *name, FsCred *credp) { char *path; int err = -1; int serrno = 0; V9fsString fullname; char buffer[PATH_MAX]; v9fs_string_init(&fullname); v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name); path = fullname.data; /* Determine the security model */ if (fs_ctx->export_flags & V9FS_SM_MAPPED) { err = mkdir(rpath(fs_ctx, path, buffer), SM_LOCAL_DIR_MODE_BITS); if (err == -1) { goto out; } credp->fc_mode = credp->fc_mode|S_IFDIR; err = local_set_xattr(rpath(fs_ctx, path, buffer), credp); if (err == -1) { serrno = errno; goto err_end; } } else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) { err = mkdir(rpath(fs_ctx, path, buffer), SM_LOCAL_DIR_MODE_BITS); if (err == -1) { goto out; } credp->fc_mode = credp->fc_mode|S_IFDIR; err = local_set_mapped_file_attr(fs_ctx, path, credp); if (err == -1) { serrno = errno; goto err_end; } } else if ((fs_ctx->export_flags & V9FS_SM_PASSTHROUGH) || (fs_ctx->export_flags & V9FS_SM_NONE)) { err = mkdir(rpath(fs_ctx, path, buffer), credp->fc_mode); if (err == -1) { goto out; } err = local_post_create_passthrough(fs_ctx, path, credp); if (err == -1) { serrno = errno; goto err_end; } } goto out; err_end: remove(rpath(fs_ctx, path, buffer)); errno = serrno; out: v9fs_string_free(&fullname); return err; }


int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture, int *got_picture_ptr, const AVPacket *avpkt) { AVCodecInternal *avci = avctx->internal; int ret; // copy to ensure we do not change avpkt AVPacket tmp = *avpkt; if (!avctx->codec) return AVERROR(EINVAL); if (avctx->codec->type != AVMEDIA_TYPE_VIDEO) { av_log(avctx, AV_LOG_ERROR, "Invalid media type for video\n"); return AVERROR(EINVAL); } *got_picture_ptr = 0; if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx)) return AVERROR(EINVAL); avcodec_get_frame_defaults(picture); if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) { int did_split = av_packet_split_side_data(&tmp); ret = apply_param_change(avctx, &tmp); if (ret < 0) { av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n"); if (avctx->err_recognition & AV_EF_EXPLODE) goto fail; } avctx->internal->pkt = &tmp; if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr, &tmp); else { ret = avctx->codec->decode(avctx, picture, got_picture_ptr, &tmp); picture->pkt_dts = avpkt->dts; if(!avctx->has_b_frames){ av_frame_set_pkt_pos(picture, avpkt->pos); } //FIXME these should be under if(!avctx->has_b_frames) /* get_buffer is supposed to set frame parameters */ if (!(avctx->codec->capabilities & CODEC_CAP_DR1)) { if (!picture->sample_aspect_ratio.num) picture->sample_aspect_ratio = avctx->sample_aspect_ratio; if (!picture->width) picture->width = avctx->width; if (!picture->height) picture->height = avctx->height; if (picture->format == AV_PIX_FMT_NONE) picture->format = avctx->pix_fmt; } } add_metadata_from_side_data(avctx, picture); fail: emms_c(); //needed to avoid an emms_c() call before every return; avctx->internal->pkt = NULL; if (did_split) { av_packet_free_side_data(&tmp); if(ret == tmp.size) ret = avpkt->size; } if (*got_picture_ptr) { if (!avctx->refcounted_frames) { int err = unrefcount_frame(avci, picture); if (err < 0) return err; } avctx->frame_number++; av_frame_set_best_effort_timestamp(picture, guess_correct_pts(avctx, picture->pkt_pts, picture->pkt_dts)); } else av_frame_unref(picture); } else ret = 0; /* many decoders assign whole AVFrames, thus overwriting extended_data; * make sure it's set correctly */ picture->extended_data = picture->data; return ret; }


static void blk_mig_cleanup(Monitor *mon) { BlkMigDevState *bmds; BlkMigBlock *blk; set_dirty_tracking(0); while ((bmds = QSIMPLEQ_FIRST(&block_mig_state.bmds_list)) != NULL) { QSIMPLEQ_REMOVE_HEAD(&block_mig_state.bmds_list, entry); bdrv_set_in_use(bmds->bs, 0); drive_put_ref(drive_get_by_blockdev(bmds->bs)); g_free(bmds->aio_bitmap); g_free(bmds); } while ((blk = QSIMPLEQ_FIRST(&block_mig_state.blk_list)) != NULL) { QSIMPLEQ_REMOVE_HEAD(&block_mig_state.blk_list, entry); g_free(blk->buf); g_free(blk); } monitor_printf(mon, "\n"); }


void ram_control_load_hook(QEMUFile *f, uint64_t flags) { int ret = 0; if (f->ops->hook_ram_load) { ret = f->ops->hook_ram_load(f, f->opaque, flags); if (ret < 0) { qemu_file_set_error(f, ret); } } else { qemu_file_set_error(f, ret); } }


static void usb_host_handle_destroy(USBDevice *udev) { USBHostDevice *s = USB_HOST_DEVICE(udev); qemu_remove_exit_notifier(&s->exit); QTAILQ_REMOVE(&hostdevs, s, next); usb_host_close(s); }


static void *qpa_thread_out (void *arg) { PAVoiceOut *pa = arg; HWVoiceOut *hw = &pa->hw; int threshold; threshold = conf.divisor ? hw->samples / conf.divisor : 0; if (audio_pt_lock (&pa->pt, AUDIO_FUNC)) { return NULL; } for (;;) { int decr, to_mix, rpos; for (;;) { if (pa->done) { goto exit; } if (pa->live > threshold) { break; } if (audio_pt_wait (&pa->pt, AUDIO_FUNC)) { goto exit; } } decr = to_mix = pa->live; rpos = hw->rpos; if (audio_pt_unlock (&pa->pt, AUDIO_FUNC)) { return NULL; } while (to_mix) { int error; int chunk = audio_MIN (to_mix, hw->samples - rpos); struct st_sample *src = hw->mix_buf + rpos; hw->clip (pa->pcm_buf, src, chunk); if (pa_simple_write (pa->s, pa->pcm_buf, chunk << hw->info.shift, &error) < 0) { qpa_logerr (error, "pa_simple_write failed\n"); return NULL; } rpos = (rpos + chunk) % hw->samples; to_mix -= chunk; } if (audio_pt_lock (&pa->pt, AUDIO_FUNC)) { return NULL; } pa->live = 0; pa->rpos = rpos; pa->decr += decr; } exit: audio_pt_unlock (&pa->pt, AUDIO_FUNC); return NULL; }


static void bench_undrained_flush_cb(void *opaque, int ret) { if (ret < 0) { error_report("Failed flush request: %s\n", strerror(-ret)); exit(EXIT_FAILURE); } }


static uint32_t nabm_readw (void *opaque, uint32_t addr) { PCIAC97LinkState *d = opaque; AC97LinkState *s = &d->ac97; AC97BusMasterRegs *r = NULL; uint32_t index = addr - s->base[1]; uint32_t val = ~0U; switch (index) { case PI_SR: case PO_SR: case MC_SR: r = &s->bm_regs[GET_BM (index)]; val = r->sr; dolog ("SR[%d] -> %#x\n", GET_BM (index), val); break; case PI_PICB: case PO_PICB: case MC_PICB: r = &s->bm_regs[GET_BM (index)]; val = r->picb; dolog ("PICB[%d] -> %#x\n", GET_BM (index), val); break; default: dolog ("U nabm readw %#x -> %#x\n", addr, val); break; } return val; }


static int ehci_state_executing(EHCIQueue *q, int async) { int again = 0; int reload, nakcnt; ehci_execute_complete(q); if (q->usb_status == USB_RET_ASYNC) { goto out; } if (q->usb_status == USB_RET_PROCERR) { again = -1; goto out; } // 4.10.3 if (!async) { int transactCtr = get_field(q->qh.epcap, QH_EPCAP_MULT); transactCtr--; set_field(&q->qh.epcap, transactCtr, QH_EPCAP_MULT); // 4.10.3, bottom of page 82, should exit this state when transaction // counter decrements to 0 } reload = get_field(q->qh.epchar, QH_EPCHAR_RL); if (reload) { nakcnt = get_field(q->qh.altnext_qtd, QH_ALTNEXT_NAKCNT); if (q->usb_status == USB_RET_NAK) { if (nakcnt) { nakcnt--; } } else { nakcnt = reload; } set_field(&q->qh.altnext_qtd, nakcnt, QH_ALTNEXT_NAKCNT); } /* 4.10.5 */ if ((q->usb_status == USB_RET_NAK) || (q->qh.token & QTD_TOKEN_ACTIVE)) { ehci_set_state(q->ehci, async, EST_HORIZONTALQH); } else { ehci_set_state(q->ehci, async, EST_WRITEBACK); } again = 1; out: ehci_flush_qh(q); return again; }


static void gd_change_page(GtkNotebook *nb, gpointer arg1, guint arg2, gpointer data) { GtkDisplayState *s = data; VirtualConsole *vc; gboolean on_vga; if (!gtk_widget_get_realized(s->notebook)) { return; } vc = gd_vc_find_by_page(s, arg2); if (!vc) { return; } gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(vc->menu_item), TRUE); on_vga = (vc->type == GD_VC_GFX); if (!on_vga) { gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(s->grab_item), FALSE); } else if (s->full_screen) { gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(s->grab_item), TRUE); } gtk_widget_set_sensitive(s->grab_item, on_vga); gd_update_cursor(vc); }


static void address_space_update_topology(AddressSpace *as) { FlatView *old_view = as->current_map; FlatView *new_view = generate_memory_topology(as->root); address_space_update_topology_pass(as, old_view, new_view, false); address_space_update_topology_pass(as, old_view, new_view, true); as->current_map = new_view; flatview_destroy(old_view); address_space_update_ioeventfds(as); }


static void ptimer_reload(ptimer_state *s) { if (s->delta == 0) { ptimer_trigger(s); s->delta = s->limit; } if (s->delta == 0 || s->period == 0) { fprintf(stderr, "Timer with period zero, disabling\n"); s->enabled = 0; return; } s->last_event = s->next_event; s->next_event = s->last_event + s->delta * s->period; if (s->period_frac) { s->next_event += ((int64_t)s->period_frac * s->delta) >> 32; } timer_mod(s->timer, s->next_event); }


static int init(AVFilterContext *ctx, const char *args, void *opaque) { GraphContext *gctx = ctx->priv; if(!args) return 0; if(!(gctx->link_filter = avfilter_open(&vf_graph_dummy, NULL))) return -1; if(avfilter_init_filter(gctx->link_filter, NULL, ctx)) goto fail; return graph_load_chain_from_string(ctx, args, NULL, NULL); fail: avfilter_destroy(gctx->link_filter); return -1; }


void kvm_arch_init_irq_routing(KVMState *s) { if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) { /* If kernel can't do irq routing, interrupt source * override 0->2 cannot be set up as required by HPET. * So we have to disable it. */ no_hpet = 1; } /* We know at this point that we're using the in-kernel * irqchip, so we can use irqfds, and on x86 we know * we can use msi via irqfd and GSI routing. */ kvm_irqfds_allowed = true; kvm_msi_via_irqfd_allowed = true; kvm_gsi_routing_allowed = true; }


static void output_visitor_test_add(const char *testpath, TestOutputVisitorData *data, void (*test_func)(TestOutputVisitorData *data, const void *user_data)) { g_test_add(testpath, TestOutputVisitorData, data, visitor_output_setup, test_func, visitor_output_teardown); }


void cpu_loop (CPUState *env) { int trapnr; target_siginfo_t info; while (1) { trapnr = cpu_alpha_exec (env); switch (trapnr) { case EXCP_RESET: fprintf(stderr, "Reset requested. Exit\n"); exit(1); break; case EXCP_MCHK: fprintf(stderr, "Machine check exception. Exit\n"); exit(1); break; case EXCP_ARITH: fprintf(stderr, "Arithmetic trap.\n"); exit(1); break; case EXCP_HW_INTERRUPT: fprintf(stderr, "External interrupt. Exit\n"); exit(1); break; case EXCP_DFAULT: fprintf(stderr, "MMU data fault\n"); exit(1); break; case EXCP_DTB_MISS_PAL: fprintf(stderr, "MMU data TLB miss in PALcode\n"); exit(1); break; case EXCP_ITB_MISS: fprintf(stderr, "MMU instruction TLB miss\n"); exit(1); break; case EXCP_ITB_ACV: fprintf(stderr, "MMU instruction access violation\n"); exit(1); break; case EXCP_DTB_MISS_NATIVE: fprintf(stderr, "MMU data TLB miss\n"); exit(1); break; case EXCP_UNALIGN: fprintf(stderr, "Unaligned access\n"); exit(1); break; case EXCP_OPCDEC: fprintf(stderr, "Invalid instruction\n"); exit(1); break; case EXCP_FEN: fprintf(stderr, "Floating-point not allowed\n"); exit(1); break; case EXCP_CALL_PAL ... (EXCP_CALL_PALP - 1): call_pal(env, (trapnr >> 6) | 0x80); break; case EXCP_CALL_PALP ... (EXCP_CALL_PALE - 1): fprintf(stderr, "Privileged call to PALcode\n"); exit(1); break; case EXCP_DEBUG: { int sig; sig = gdb_handlesig (env, TARGET_SIGTRAP); if (sig) { info.si_signo = sig; info.si_errno = 0; info.si_code = TARGET_TRAP_BRKPT; queue_signal(env, info.si_signo, &info); } } break; default: printf ("Unhandled trap: 0x%x\n", trapnr); cpu_dump_state(env, stderr, fprintf, 0); exit (1); } process_pending_signals (env); } }


int rom_load_all(void) { target_phys_addr_t addr = 0; MemoryRegionSection section; Rom *rom; QTAILQ_FOREACH(rom, &roms, next) { if (rom->fw_file) { continue; } if (addr > rom->addr) { fprintf(stderr, "rom: requested regions overlap " "(rom %s. free=0x" TARGET_FMT_plx ", addr=0x" TARGET_FMT_plx ")\n", rom->name, addr, rom->addr); return -1; } addr = rom->addr; addr += rom->romsize; section = memory_region_find(get_system_memory(), rom->addr, 1); rom->isrom = section.size && memory_region_is_rom(section.mr); } qemu_register_reset(rom_reset, NULL); roms_loaded = 1; return 0; }


static int alsa_init_in (HWVoiceIn *hw, audsettings_t *as) { ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw; struct alsa_params_req req; struct alsa_params_obt obt; snd_pcm_t *handle; audsettings_t obt_as; req.fmt = aud_to_alsafmt (as->fmt); req.freq = as->freq; req.nchannels = as->nchannels; req.period_size = conf.period_size_in; req.buffer_size = conf.buffer_size_in; req.size_in_usec = conf.size_in_usec_in; req.override_mask = !!conf.period_size_in_overridden | (!!conf.buffer_size_in_overridden << 1); if (alsa_open (1, &req, &obt, &handle)) { return -1; } obt_as.freq = obt.freq; obt_as.nchannels = obt.nchannels; obt_as.fmt = obt.fmt; obt_as.endianness = obt.endianness; audio_pcm_init_info (&hw->info, &obt_as); hw->samples = obt.samples; alsa->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift); if (!alsa->pcm_buf) { dolog ("Could not allocate ADC buffer (%d samples, each %d bytes)\n", hw->samples, 1 << hw->info.shift); alsa_anal_close (&handle); return -1; } alsa->handle = handle; return 0; }


static void rtas_power_off(sPAPREnvironment *spapr, uint32_t token, uint32_t nargs, target_ulong args, uint32_t nret, target_ulong rets) { if (nargs != 2 || nret != 1) { rtas_st(rets, 0, -3); return; } qemu_system_shutdown_request(); rtas_st(rets, 0, 0); }


static uint64_t omap_id_read(void *opaque, target_phys_addr_t addr, unsigned size) { struct omap_mpu_state_s *s = (struct omap_mpu_state_s *) opaque; if (size != 4) { return omap_badwidth_read32(opaque, addr); } switch (addr) { case 0xfffe1800: /* DIE_ID_LSB */ return 0xc9581f0e; case 0xfffe1804: /* DIE_ID_MSB */ return 0xa8858bfa; case 0xfffe2000: /* PRODUCT_ID_LSB */ return 0x00aaaafc; case 0xfffe2004: /* PRODUCT_ID_MSB */ return 0xcafeb574; case 0xfffed400: /* JTAG_ID_LSB */ switch (s->mpu_model) { case omap310: return 0x03310315; case omap1510: return 0x03310115; default: hw_error("%s: bad mpu model\n", __FUNCTION__); } break; case 0xfffed404: /* JTAG_ID_MSB */ switch (s->mpu_model) { case omap310: return 0xfb57402f; case omap1510: return 0xfb47002f; default: hw_error("%s: bad mpu model\n", __FUNCTION__); } break; } OMAP_BAD_REG(addr); return 0; }


ram_addr_t xen_ram_addr_from_mapcache(void *ptr) { MapCacheEntry *entry = NULL; MapCacheRev *reventry; hwaddr paddr_index; hwaddr size; int found = 0; QTAILQ_FOREACH(reventry, &mapcache->locked_entries, next) { if (reventry->vaddr_req == ptr) { paddr_index = reventry->paddr_index; size = reventry->size; found = 1; break; } } if (!found) { fprintf(stderr, "%s, could not find %p\n", __func__, ptr); QTAILQ_FOREACH(reventry, &mapcache->locked_entries, next) { DPRINTF(" "TARGET_FMT_plx" -> %p is present\n", reventry->paddr_index, reventry->vaddr_req); } abort(); return 0; } entry = &mapcache->entry[paddr_index % mapcache->nr_buckets]; while (entry && (entry->paddr_index != paddr_index || entry->size != size)) { entry = entry->next; } if (!entry) { DPRINTF("Trying to find address %p that is not in the mapcache!\n", ptr); return 0; } return (reventry->paddr_index << MCACHE_BUCKET_SHIFT) + ((unsigned long) ptr - (unsigned long) entry->vaddr_base); }


static void hpdmc_write(void *opaque, target_phys_addr_t addr, uint64_t value, unsigned size) { MilkymistHpdmcState *s = opaque; trace_milkymist_hpdmc_memory_write(addr, value); addr >>= 2; switch (addr) { case R_SYSTEM: case R_BYPASS: case R_TIMING: s->regs[addr] = value; break; case R_IODELAY: /* ignore writes */ break; default: error_report("milkymist_hpdmc: write access to unknown register 0x" TARGET_FMT_plx, addr << 2); break; } }


static int write_elf32_note(DumpState *s) { target_phys_addr_t begin = s->memory_offset - s->note_size; Elf32_Phdr phdr; int endian = s->dump_info.d_endian; int ret; memset(&phdr, 0, sizeof(Elf32_Phdr)); phdr.p_type = cpu_convert_to_target32(PT_NOTE, endian); phdr.p_offset = cpu_convert_to_target32(begin, endian); phdr.p_paddr = 0; phdr.p_filesz = cpu_convert_to_target32(s->note_size, endian); phdr.p_memsz = cpu_convert_to_target32(s->note_size, endian); phdr.p_vaddr = 0; ret = fd_write_vmcore(&phdr, sizeof(Elf32_Phdr), s); if (ret < 0) { dump_error(s, "dump: failed to write program header table.\n"); return -1; } return 0; }


int rom_add_vga(const char *file) { if (!rom_enable_driver_roms) return 0; return rom_add_file(file, "vgaroms", file, 0); }


static void external_snapshot_prepare(BlkActionState *common, Error **errp) { int flags = 0, ret; QDict *options = NULL; Error *local_err = NULL; /* Device and node name of the image to generate the snapshot from */ const char *device; const char *node_name; /* Reference to the new image (for 'blockdev-snapshot') */ const char *snapshot_ref; /* File name of the new image (for 'blockdev-snapshot-sync') */ const char *new_image_file; ExternalSnapshotState *state = DO_UPCAST(ExternalSnapshotState, common, common); TransactionAction *action = common->action; /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar * purpose but a different set of parameters */ switch (action->type) { case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT: { BlockdevSnapshot *s = action->u.blockdev_snapshot; device = s->node; node_name = s->node; new_image_file = NULL; snapshot_ref = s->overlay; } break; case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC: { BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync; device = s->has_device ? s->device : NULL; node_name = s->has_node_name ? s->node_name : NULL; new_image_file = s->snapshot_file; snapshot_ref = NULL; } break; default: g_assert_not_reached(); } /* start processing */ if (action_check_completion_mode(common, errp) < 0) { return; } state->old_bs = bdrv_lookup_bs(device, node_name, errp); if (!state->old_bs) { return; } /* Acquire AioContext now so any threads operating on old_bs stop */ state->aio_context = bdrv_get_aio_context(state->old_bs); aio_context_acquire(state->aio_context); bdrv_drained_begin(state->old_bs); if (!bdrv_is_inserted(state->old_bs)) { error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device); return; } if (bdrv_op_is_blocked(state->old_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) { return; } if (!bdrv_is_read_only(state->old_bs)) { if (bdrv_flush(state->old_bs)) { error_setg(errp, QERR_IO_ERROR); return; } } if (!bdrv_is_first_non_filter(state->old_bs)) { error_setg(errp, QERR_FEATURE_DISABLED, "snapshot"); return; } if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) { BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync; const char *format = s->has_format ? s->format : "qcow2"; enum NewImageMode mode; const char *snapshot_node_name = s->has_snapshot_node_name ? s->snapshot_node_name : NULL; if (node_name && !snapshot_node_name) { error_setg(errp, "New snapshot node name missing"); return; } if (snapshot_node_name && bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) { error_setg(errp, "New snapshot node name already in use"); return; } flags = state->old_bs->open_flags; /* create new image w/backing file */ mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS; if (mode != NEW_IMAGE_MODE_EXISTING) { int64_t size = bdrv_getlength(state->old_bs); if (size < 0) { error_setg_errno(errp, -size, "bdrv_getlength failed"); return; } bdrv_img_create(new_image_file, format, state->old_bs->filename, state->old_bs->drv->format_name, NULL, size, flags, &local_err, false); if (local_err) { error_propagate(errp, local_err); return; } } options = qdict_new(); if (s->has_snapshot_node_name) { qdict_put(options, "node-name", qstring_from_str(snapshot_node_name)); } qdict_put(options, "driver", qstring_from_str(format)); flags |= BDRV_O_NO_BACKING; } assert(state->new_bs == NULL); ret = bdrv_open(&state->new_bs, new_image_file, snapshot_ref, options, flags, errp); /* We will manually add the backing_hd field to the bs later */ if (ret != 0) { return; } if (state->new_bs->blk != NULL) { error_setg(errp, "The snapshot is already in use by %s", blk_name(state->new_bs->blk)); return; } if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) { return; } if (state->new_bs->backing != NULL) { error_setg(errp, "The snapshot already has a backing image"); return; } if (!state->new_bs->drv->supports_backing) { error_setg(errp, "The snapshot does not support backing images"); } }


void helper_ldl_data(uint64_t t0, uint64_t t1) { ldl_data(t1, t0); }


matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size, int64_t pos, uint64_t cluster_time, int is_keyframe, int *ptrack, AVPacket **ppkt) { int res = 0; int track; AVPacket *pkt; uint8_t *origdata = data; int16_t block_time; uint32_t *lace_size = NULL; int n, flags, laces = 0; uint64_t num; /* first byte(s): tracknum */ if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) { av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n"); av_free(origdata); return res; } data += n; size -= n; /* fetch track from num */ track = matroska_find_track_by_num(matroska, num); if (ptrack) *ptrack = track; if (size <= 3 || track < 0 || track >= matroska->num_tracks) { av_log(matroska->ctx, AV_LOG_INFO, "Invalid stream %d or size %u\n", track, size); av_free(origdata); return res; } if(matroska->ctx->streams[ matroska->tracks[track]->stream_index ]->discard >= AVDISCARD_ALL){ av_free(origdata); return res; } /* block_time (relative to cluster time) */ block_time = (data[0] << 8) | data[1]; data += 2; size -= 2; flags = *data; data += 1; size -= 1; if (is_keyframe == -1) is_keyframe = flags & 1 ? PKT_FLAG_KEY : 0; switch ((flags & 0x06) >> 1) { case 0x0: /* no lacing */ laces = 1; lace_size = av_mallocz(sizeof(int)); lace_size[0] = size; break; case 0x1: /* xiph lacing */ case 0x2: /* fixed-size lacing */ case 0x3: /* EBML lacing */ if (size == 0) { res = -1; break; } laces = (*data) + 1; data += 1; size -= 1; lace_size = av_mallocz(laces * sizeof(int)); switch ((flags & 0x06) >> 1) { case 0x1: /* xiph lacing */ { uint8_t temp; uint32_t total = 0; for (n = 0; res == 0 && n < laces - 1; n++) { while (1) { if (size == 0) { res = -1; break; } temp = *data; lace_size[n] += temp; data += 1; size -= 1; if (temp != 0xff) break; } total += lace_size[n]; } lace_size[n] = size - total; break; } case 0x2: /* fixed-size lacing */ for (n = 0; n < laces; n++) lace_size[n] = size / laces; break; case 0x3: /* EBML lacing */ { uint32_t total; n = matroska_ebmlnum_uint(data, size, &num); if (n < 0) { av_log(matroska->ctx, AV_LOG_INFO, "EBML block data error\n"); break; } data += n; size -= n; total = lace_size[0] = num; for (n = 1; res == 0 && n < laces - 1; n++) { int64_t snum; int r; r = matroska_ebmlnum_sint (data, size, &snum); if (r < 0) { av_log(matroska->ctx, AV_LOG_INFO, "EBML block data error\n"); break; } data += r; size -= r; lace_size[n] = lace_size[n - 1] + snum; total += lace_size[n]; } lace_size[n] = size - total; break; } } break; } if (res == 0) { int real_v = matroska->tracks[track]->flags & MATROSKA_TRACK_REAL_V; for (n = 0; n < laces; n++) { uint64_t timecode = AV_NOPTS_VALUE; int slice, slices = 1; if (real_v) { slices = *data++ + 1; lace_size[n]--; } if (cluster_time != (uint64_t)-1 && n == 0) { if (cluster_time + block_time >= 0) timecode = (cluster_time + block_time) * matroska->time_scale; } /* FIXME: duration */ for (slice=0; slice<slices; slice++) { int slice_size, slice_offset = 0; if (real_v) slice_offset = rv_offset(data, slice, slices); if (slice+1 == slices) slice_size = lace_size[n] - slice_offset; else slice_size = rv_offset(data, slice+1, slices) - slice_offset; pkt = av_mallocz(sizeof(AVPacket)); if (ppkt) *ppkt = pkt; /* XXX: prevent data copy... */ if (av_new_packet(pkt, slice_size) < 0) { res = AVERROR_NOMEM; n = laces-1; break; } memcpy (pkt->data, data+slice_offset, slice_size); if (n == 0) pkt->flags = is_keyframe; pkt->stream_index = matroska->tracks[track]->stream_index; pkt->pts = timecode; pkt->pos = pos; matroska_queue_packet(matroska, pkt); } data += lace_size[n]; } } av_free(lace_size); av_free(origdata); return res; }


Visitor *qmp_input_visitor_new(QObject *obj, bool strict) { QmpInputVisitor *v; assert(obj); v = g_malloc0(sizeof(*v)); v->visitor.type = VISITOR_INPUT; v->visitor.start_struct = qmp_input_start_struct; v->visitor.check_struct = qmp_input_check_struct; v->visitor.end_struct = qmp_input_pop; v->visitor.start_list = qmp_input_start_list; v->visitor.next_list = qmp_input_next_list; v->visitor.end_list = qmp_input_pop; v->visitor.start_alternate = qmp_input_start_alternate; v->visitor.type_int64 = qmp_input_type_int64; v->visitor.type_uint64 = qmp_input_type_uint64; v->visitor.type_bool = qmp_input_type_bool; v->visitor.type_str = qmp_input_type_str; v->visitor.type_number = qmp_input_type_number; v->visitor.type_any = qmp_input_type_any; v->visitor.type_null = qmp_input_type_null; v->visitor.optional = qmp_input_optional; v->visitor.free = qmp_input_free; v->strict = strict; v->root = obj; qobject_incref(obj); return &v->visitor; }


static gboolean tcp_chr_accept(QIOChannel *channel, GIOCondition cond, void *opaque) { CharDriverState *chr = opaque; TCPCharDriver *s = chr->opaque; QIOChannelSocket *sioc; sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel), NULL); if (!sioc) { return TRUE; } if (s->do_telnetopt) { tcp_chr_telnet_init(QIO_CHANNEL(sioc)); } tcp_chr_new_client(chr, sioc); object_unref(OBJECT(sioc)); return TRUE; }


void qemu_timer_notify_cb(void *opaque, QEMUClockType type) { qemu_notify_event(); }


static void return_frame(AVFilterContext *ctx, int is_second) { YADIFContext *yadif = ctx->priv; AVFilterLink *link= ctx->outputs[0]; int tff; if (yadif->parity == -1) { tff = yadif->cur->video->interlaced ? yadif->cur->video->top_field_first : 1; } else { tff = yadif->parity^1; } if (is_second) { yadif->out = ff_get_video_buffer(link, AV_PERM_WRITE | AV_PERM_PRESERVE | AV_PERM_REUSE, link->w, link->h); avfilter_copy_buffer_ref_props(yadif->out, yadif->cur); yadif->out->video->interlaced = 0; } if (!yadif->csp) yadif->csp = &av_pix_fmt_descriptors[link->format]; if (yadif->csp->comp[0].depth_minus1 / 8 == 1) yadif->filter_line = filter_line_c_16bit; filter(ctx, yadif->out, tff ^ !is_second, tff); if (is_second) { int64_t cur_pts = yadif->cur->pts; int64_t next_pts = yadif->next->pts; if (next_pts != AV_NOPTS_VALUE && cur_pts != AV_NOPTS_VALUE) { yadif->out->pts = cur_pts + next_pts; } else { yadif->out->pts = AV_NOPTS_VALUE; } ff_start_frame(ctx->outputs[0], yadif->out); } ff_draw_slice(ctx->outputs[0], 0, link->h, 1); ff_end_frame(ctx->outputs[0]); yadif->frame_pending = (yadif->mode&1) && !is_second; }


static void quantize_and_encode_band(struct AACEncContext *s, PutBitContext *pb, const float *in, int size, int scale_idx, int cb, const float lambda) { const float IQ = ff_aac_pow2sf_tab[200 + scale_idx - SCALE_ONE_POS + SCALE_DIV_512]; const float Q = ff_aac_pow2sf_tab[200 - scale_idx + SCALE_ONE_POS - SCALE_DIV_512]; const float CLIPPED_ESCAPE = 165140.0f*IQ; const int dim = (cb < FIRST_PAIR_BT) ? 4 : 2; int i, j, k; #ifndef USE_REALLY_FULL_SEARCH const float Q34 = sqrtf(Q * sqrtf(Q)); const int range = aac_cb_range[cb]; const int maxval = aac_cb_maxval[cb]; int offs[4]; float *scaled = s->scoefs; #endif /* USE_REALLY_FULL_SEARCH */ //START_TIMER if (!cb) return; #ifndef USE_REALLY_FULL_SEARCH offs[0] = 1; for (i = 1; i < dim; i++) offs[i] = offs[i-1]*range; abs_pow34_v(scaled, in, size); quantize_bands(s->qcoefs, in, scaled, size, Q34, !IS_CODEBOOK_UNSIGNED(cb), maxval); #endif /* USE_REALLY_FULL_SEARCH */ for (i = 0; i < size; i += dim) { float mincost; int minidx = 0; int minbits = 0; const float *vec; #ifndef USE_REALLY_FULL_SEARCH int (*quants)[2] = &s->qcoefs[i]; mincost = 0.0f; for (j = 0; j < dim; j++) mincost += in[i+j]*in[i+j]*lambda; minidx = IS_CODEBOOK_UNSIGNED(cb) ? 0 : 40; minbits = ff_aac_spectral_bits[cb-1][minidx]; mincost += minbits; for (j = 0; j < (1<<dim); j++) { float rd = 0.0f; int curbits; int curidx = IS_CODEBOOK_UNSIGNED(cb) ? 0 : 40; int same = 0; for (k = 0; k < dim; k++) { if ((j & (1 << k)) && quants[k][0] == quants[k][1]) { same = 1; break; } } if (same) continue; for (k = 0; k < dim; k++) curidx += quants[k][!!(j & (1 << k))] * offs[dim - 1 - k]; curbits = ff_aac_spectral_bits[cb-1][curidx]; vec = &ff_aac_codebook_vectors[cb-1][curidx*dim]; #else vec = ff_aac_codebook_vectors[cb-1]; mincost = INFINITY; for (j = 0; j < ff_aac_spectral_sizes[cb-1]; j++, vec += dim) { float rd = 0.0f; int curbits = ff_aac_spectral_bits[cb-1][j]; int curidx = j; #endif /* USE_REALLY_FULL_SEARCH */ if (IS_CODEBOOK_UNSIGNED(cb)) { for (k = 0; k < dim; k++) { float t = fabsf(in[i+k]); float di; //do not code with escape sequence small values if (vec[k] == 64.0f && t < 39.0f*IQ) { rd = INFINITY; break; } if (vec[k] == 64.0f) { //FIXME: slow if (t >= CLIPPED_ESCAPE) { di = t - CLIPPED_ESCAPE; curbits += 21; } else { int c = av_clip(quant(t, Q), 0, 8191); di = t - c*cbrt(c)*IQ; curbits += av_log2(c)*2 - 4 + 1; } } else { di = t - vec[k]*IQ; } if (vec[k] != 0.0f) curbits++; rd += di*di*lambda; } } else { for (k = 0; k < dim; k++) { float di = in[i+k] - vec[k]*IQ; rd += di*di*lambda; } } rd += curbits; if (rd < mincost) { mincost = rd; minidx = curidx; minbits = curbits; } } put_bits(pb, ff_aac_spectral_bits[cb-1][minidx], ff_aac_spectral_codes[cb-1][minidx]); if (IS_CODEBOOK_UNSIGNED(cb)) for (j = 0; j < dim; j++) if (ff_aac_codebook_vectors[cb-1][minidx*dim+j] != 0.0f) put_bits(pb, 1, in[i+j] < 0.0f); if (cb == ESC_BT) { for (j = 0; j < 2; j++) { if (ff_aac_codebook_vectors[cb-1][minidx*2+j] == 64.0f) { int coef = av_clip(quant(fabsf(in[i+j]), Q), 0, 8191); int len = av_log2(coef); put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2); put_bits(pb, len, coef & ((1 << len) - 1)); } } } } //STOP_TIMER("quantize_and_encode") }


static int seg_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt) { SegmentContext *seg = s->priv_data; AVFormatContext *oc = seg->avf; if (oc->oformat->check_bitstream) { int ret = oc->oformat->check_bitstream(oc, pkt); if (ret == 1) { AVStream *st = s->streams[pkt->stream_index]; AVStream *ost = oc->streams[pkt->stream_index]; st->internal->bsfcs = ost->internal->bsfcs; st->internal->nb_bsfcs = ost->internal->nb_bsfcs; ost->internal->bsfcs = NULL; ost->internal->nb_bsfcs = 0; } return ret; } return 1; }


static int gen_check_bw(URLContext *s, RTMPContext *rt) { RTMPPacket pkt; uint8_t *p; int ret; if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 21)) < 0) return ret; p = pkt.data; ff_amf_write_string(&p, "_checkbw"); ff_amf_write_number(&p, ++rt->nb_invokes); ff_amf_write_null(&p); ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]); ff_rtmp_packet_destroy(&pkt); return ret; }


static void scsi_generic_purge_requests(SCSIGenericState *s) { SCSIGenericReq *r; while (!QTAILQ_EMPTY(&s->qdev.requests)) { r = DO_UPCAST(SCSIGenericReq, req, QTAILQ_FIRST(&s->qdev.requests)); if (r->req.aiocb) { bdrv_aio_cancel(r->req.aiocb); } scsi_remove_request(r); } }


static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output) { AVFrame *decoded_frame, *f; int i, ret = 0, err = 0; if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc())) return AVERROR(ENOMEM); if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc())) return AVERROR(ENOMEM); decoded_frame = ist->decoded_frame; ret = decode(ist->dec_ctx, decoded_frame, got_output, pkt); if (!*got_output || ret < 0) return ret; ist->frames_decoded++; if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) { err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame); if (err < 0) goto fail; } ist->hwaccel_retrieved_pix_fmt = decoded_frame->format; decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pts, decoded_frame->pkt_dts); if (ist->framerate.num) decoded_frame->pts = ist->cfr_next_pts++; if (ist->st->sample_aspect_ratio.num) decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio; for (i = 0; i < ist->nb_filters; i++) { if (i < ist->nb_filters - 1) { f = ist->filter_frame; err = av_frame_ref(f, decoded_frame); if (err < 0) break; } else f = decoded_frame; err = ifilter_send_frame(ist->filters[i], f); if (err < 0) break; } fail: av_frame_unref(ist->filter_frame); av_frame_unref(decoded_frame); return err < 0 ? err : ret; }


int boot_sector_init(const char *fname) { FILE *f = fopen(fname, "w"); size_t len = sizeof boot_sector; if (!f) { fprintf(stderr, "Couldn't open \"%s\": %s", fname, strerror(errno)); return 1; } /* For Open Firmware based system, we can use a Forth script instead */ if (strcmp(qtest_get_arch(), "ppc64") == 0) { len = sprintf((char *)boot_sector, "\\ Bootscript\n%x %x c! %x %x c!\n", LOW(SIGNATURE), BOOT_SECTOR_ADDRESS + SIGNATURE_OFFSET, HIGH(SIGNATURE), BOOT_SECTOR_ADDRESS + SIGNATURE_OFFSET + 1); } fwrite(boot_sector, 1, len, f); fclose(f); return 0; }


static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { AVIContext *avi = s->priv_data; AVStream *st; int i, index; int64_t pos, pos_min; AVIStream *ast; if (!avi->index_loaded) { /* we only load the index on demand */ avi_load_index(s); avi->index_loaded = 1; } assert(stream_index>= 0); st = s->streams[stream_index]; ast= st->priv_data; index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags); if(index<0) return -1; /* find the position */ pos = st->index_entries[index].pos; timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1); // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp); if (CONFIG_DV_DEMUXER && avi->dv_demux) { /* One and only one real stream for DV in AVI, and it has video */ /* offsets. Calling with other stream indexes should have failed */ /* the av_index_search_timestamp call above. */ assert(stream_index == 0); /* Feed the DV video stream version of the timestamp to the */ /* DV demux so it can synthesize correct timestamps. */ dv_offset_reset(avi->dv_demux, timestamp); avio_seek(s->pb, pos, SEEK_SET); avi->stream_index= -1; return 0; } pos_min= pos; for(i = 0; i < s->nb_streams; i++) { AVStream *st2 = s->streams[i]; AVIStream *ast2 = st2->priv_data; ast2->packet_size= ast2->remaining= 0; if (ast2->sub_ctx) { seek_subtitle(st, st2, timestamp); continue; } if (st2->nb_index_entries <= 0) continue; // assert(st2->codec->block_align); assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale); index = av_index_search_timestamp( st2, av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1), flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0)); if(index<0) index=0; ast2->seek_pos= st2->index_entries[index].pos; pos_min= FFMIN(pos_min,ast2->seek_pos); } for(i = 0; i < s->nb_streams; i++) { AVStream *st2 = s->streams[i]; AVIStream *ast2 = st2->priv_data; if (ast2->sub_ctx || st2->nb_index_entries <= 0) continue; index = av_index_search_timestamp( st2, av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1), flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0)); if(index<0) index=0; while(!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min) index--; ast2->frame_offset = st2->index_entries[index].timestamp; } /* do the seek */ avio_seek(s->pb, pos_min, SEEK_SET); avi->stream_index= -1; avi->dts_max= INT_MIN; return 0; }


static void timer_enable(struct xlx_timer *xt) { uint64_t count; D(printf("%s timer=%d down=%d\n", __func__, xt->nr, xt->regs[R_TCSR] & TCSR_UDT)); ptimer_stop(xt->ptimer); if (xt->regs[R_TCSR] & TCSR_UDT) count = xt->regs[R_TLR]; else count = ~0 - xt->regs[R_TLR]; ptimer_set_count(xt->ptimer, count); ptimer_run(xt->ptimer, 1); }


static int colo_packet_compare_tcp(Packet *spkt, Packet *ppkt) { struct tcphdr *ptcp, *stcp; int res; trace_colo_compare_main("compare tcp"); ptcp = (struct tcphdr *)ppkt->transport_header; stcp = (struct tcphdr *)spkt->transport_header; /* * The 'identification' field in the IP header is *very* random * it almost never matches. Fudge this by ignoring differences in * unfragmented packets; they'll normally sort themselves out if different * anyway, and it should recover at the TCP level. * An alternative would be to get both the primary and secondary to rewrite * somehow; but that would need some sync traffic to sync the state */ if (ntohs(ppkt->ip->ip_off) & IP_DF) { spkt->ip->ip_id = ppkt->ip->ip_id; /* and the sum will be different if the IDs were different */ spkt->ip->ip_sum = ppkt->ip->ip_sum; } /* * Check tcp header length for tcp option field. * th_off > 5 means this tcp packet have options field. * The tcp options maybe always different. * for example: * From RFC 7323. * TCP Timestamps option (TSopt): * Kind: 8 * * Length: 10 bytes * * +-------+-------+---------------------+---------------------+ * |Kind=8 | 10 | TS Value (TSval) |TS Echo Reply (TSecr)| * +-------+-------+---------------------+---------------------+ * 1 1 4 4 * * In this case the primary guest's timestamp always different with * the secondary guest's timestamp. COLO just focus on payload, * so we just need skip this field. */ if (ptcp->th_off > 5) { ptrdiff_t tcp_offset; tcp_offset = ppkt->transport_header - (uint8_t *)ppkt->data + (ptcp->th_off * 4) - ppkt->vnet_hdr_len; res = colo_packet_compare_common(ppkt, spkt, tcp_offset); } else if (ptcp->th_sum == stcp->th_sum) { res = colo_packet_compare_common(ppkt, spkt, ETH_HLEN); } else { res = -1; } if (res != 0 && trace_event_get_state(TRACE_COLO_COMPARE_MISCOMPARE)) { char pri_ip_src[20], pri_ip_dst[20], sec_ip_src[20], sec_ip_dst[20]; strcpy(pri_ip_src, inet_ntoa(ppkt->ip->ip_src)); strcpy(pri_ip_dst, inet_ntoa(ppkt->ip->ip_dst)); strcpy(sec_ip_src, inet_ntoa(spkt->ip->ip_src)); strcpy(sec_ip_dst, inet_ntoa(spkt->ip->ip_dst)); trace_colo_compare_ip_info(ppkt->size, pri_ip_src, pri_ip_dst, spkt->size, sec_ip_src, sec_ip_dst); trace_colo_compare_tcp_info("pri tcp packet", ntohl(ptcp->th_seq), ntohl(ptcp->th_ack), res, ptcp->th_flags, ppkt->size); trace_colo_compare_tcp_info("sec tcp packet", ntohl(stcp->th_seq), ntohl(stcp->th_ack), res, stcp->th_flags, spkt->size); qemu_hexdump((char *)ppkt->data, stderr, "colo-compare ppkt", ppkt->size); qemu_hexdump((char *)spkt->data, stderr, "colo-compare spkt", spkt->size); } return res; }


static int dfa_read_packet(AVFormatContext *s, AVPacket *pkt) { AVIOContext *pb = s->pb; uint32_t frame_size; int ret, first = 1; if (avio_feof(pb)) return AVERROR_EOF; if (av_get_packet(pb, pkt, 12) != 12) return AVERROR(EIO); while (!avio_feof(pb)) { if (!first) { ret = av_append_packet(pb, pkt, 12); if (ret < 0) { return ret; } } else first = 0; frame_size = AV_RL32(pkt->data + pkt->size - 8); if (frame_size > INT_MAX - 4) { av_log(s, AV_LOG_ERROR, "Too large chunk size: %"PRIu32"\n", frame_size); return AVERROR(EIO); } if (AV_RL32(pkt->data + pkt->size - 12) == MKTAG('E', 'O', 'F', 'R')) { if (frame_size) { av_log(s, AV_LOG_WARNING, "skipping %"PRIu32" bytes of end-of-frame marker chunk\n", frame_size); avio_skip(pb, frame_size); } return 0; } ret = av_append_packet(pb, pkt, frame_size); if (ret < 0) { return ret; } } return 0; }


static int nut_read_close(AVFormatContext *s) { NUTContext *nut = s->priv_data; av_freep(&nut->time_base); av_freep(&nut->stream); return 0; }


static int64_t pva_read_timestamp(struct AVFormatContext *s, int stream_index, int64_t *pos, int64_t pos_limit) { ByteIOContext *pb = s->pb; PVAContext *pvactx = s->priv_data; int length, streamid; int64_t res; pos_limit = FFMIN(*pos+PVA_MAX_PAYLOAD_LENGTH*8, (uint64_t)*pos+pos_limit); while (*pos < pos_limit) { res = AV_NOPTS_VALUE; url_fseek(pb, *pos, SEEK_SET); pvactx->continue_pes = 0; if (read_part_of_packet(s, &res, &length, &streamid, 0)) { (*pos)++; continue; } if (streamid - 1 != stream_index || res == AV_NOPTS_VALUE) { *pos = url_ftell(pb) + length; continue; } break; } pvactx->continue_pes = 0; return res; }


static ssize_t handle_aiocb_ioctl(struct qemu_paiocb *aiocb) { int ret; ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf); if (ret == -1) return -errno; /* * This looks weird, but the aio code only consideres a request * successful if it has written the number full number of bytes. * * Now we overload aio_nbytes as aio_ioctl_cmd for the ioctl command, * so in fact we return the ioctl command here to make posix_aio_read() * happy.. */ return aiocb->aio_nbytes; }


static int filter_slice(AVFilterContext *ctx, void *arg, int job, int nb_jobs) { FrameRateContext *s = ctx->priv; ThreadData *td = arg; uint16_t src1_factor = td->src1_factor; uint16_t src2_factor = td->src2_factor; int plane; for (plane = 0; plane < 4 && td->copy_src1->data[plane] && td->copy_src2->data[plane]; plane++) { int cpy_line_width = s->line_size[plane]; uint8_t *cpy_src1_data = td->copy_src1->data[plane]; int cpy_src1_line_size = td->copy_src1->linesize[plane]; uint8_t *cpy_src2_data = td->copy_src2->data[plane]; int cpy_src2_line_size = td->copy_src2->linesize[plane]; int cpy_src_h = (plane > 0 && plane < 3) ? (td->copy_src1->height >> s->vsub) : (td->copy_src1->height); uint8_t *cpy_dst_data = s->work->data[plane]; int cpy_dst_line_size = s->work->linesize[plane]; const int start = (cpy_src_h * job ) / nb_jobs; const int end = (cpy_src_h * (job+1)) / nb_jobs; cpy_src1_data += start * cpy_src1_line_size; cpy_src2_data += start * cpy_src2_line_size; cpy_dst_data += start * cpy_dst_line_size; s->blend(cpy_src1_data, cpy_src1_line_size, cpy_src2_data, cpy_src2_line_size, cpy_dst_data, cpy_dst_line_size, cpy_line_width, end - start, src1_factor, src2_factor, s->max / 2, s->bitdepth); } return 0; }


static void update_initial_timestamps(AVFormatContext *s, int stream_index, int64_t dts, int64_t pts, AVPacket *pkt) { AVStream *st = s->streams[stream_index]; AVPacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue; int64_t pts_buffer[MAX_REORDER_DELAY+1]; int64_t shift; int i, delay; if (st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE || is_relative(dts)) return; delay = st->codec->has_b_frames; st->first_dts = dts - (st->cur_dts - RELATIVE_TS_BASE); st->cur_dts = dts; shift = st->first_dts - RELATIVE_TS_BASE; for (i = 0; i<MAX_REORDER_DELAY+1; i++) pts_buffer[i] = AV_NOPTS_VALUE; if (is_relative(pts)) pts += shift; for (; pktl; pktl = get_next_pkt(s, st, pktl)) { if (pktl->pkt.stream_index != stream_index) continue; if (is_relative(pktl->pkt.pts)) pktl->pkt.pts += shift; if (is_relative(pktl->pkt.dts)) pktl->pkt.dts += shift; if (st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE) st->start_time = pktl->pkt.pts; if (pktl->pkt.pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY && has_decode_delay_been_guessed(st)) { pts_buffer[0] = pktl->pkt.pts; for (i = 0; i<delay && pts_buffer[i] > pts_buffer[i + 1]; i++) FFSWAP(int64_t, pts_buffer[i], pts_buffer[i + 1]); pktl->pkt.dts = select_from_pts_buffer(st, pts_buffer, pktl->pkt.dts); } } if (st->start_time == AV_NOPTS_VALUE) st->start_time = pts; }


static void ide_test_quit(void) { qtest_end(); }


static void mcf5208evb_init(MachineState *machine) { ram_addr_t ram_size = machine->ram_size; const char *cpu_model = machine->cpu_model; const char *kernel_filename = machine->kernel_filename; M68kCPU *cpu; CPUM68KState *env; int kernel_size; uint64_t elf_entry; hwaddr entry; qemu_irq *pic; MemoryRegion *address_space_mem = get_system_memory(); MemoryRegion *ram = g_new(MemoryRegion, 1); MemoryRegion *sram = g_new(MemoryRegion, 1); if (!cpu_model) { cpu_model = "m5208"; } cpu = M68K_CPU(cpu_generic_init(TYPE_M68K_CPU, cpu_model)); if (!cpu) { fprintf(stderr, "Unable to find m68k CPU definition\n"); exit(1); } env = &cpu->env; /* Initialize CPU registers. */ env->vbr = 0; /* TODO: Configure BARs. */ /* DRAM at 0x40000000 */ memory_region_allocate_system_memory(ram, NULL, "mcf5208.ram", ram_size); memory_region_add_subregion(address_space_mem, 0x40000000, ram); /* Internal SRAM. */ memory_region_init_ram(sram, NULL, "mcf5208.sram", 16384, &error_fatal); memory_region_add_subregion(address_space_mem, 0x80000000, sram); /* Internal peripherals. */ pic = mcf_intc_init(address_space_mem, 0xfc048000, cpu); mcf_uart_mm_init(0xfc060000, pic[26], serial_hds[0]); mcf_uart_mm_init(0xfc064000, pic[27], serial_hds[1]); mcf_uart_mm_init(0xfc068000, pic[28], serial_hds[2]); mcf5208_sys_init(address_space_mem, pic); if (nb_nics > 1) { fprintf(stderr, "Too many NICs\n"); exit(1); } if (nd_table[0].used) { mcf_fec_init(address_space_mem, &nd_table[0], 0xfc030000, pic + 36); } /* 0xfc000000 SCM. */ /* 0xfc004000 XBS. */ /* 0xfc008000 FlexBus CS. */ /* 0xfc030000 FEC. */ /* 0xfc040000 SCM + Power management. */ /* 0xfc044000 eDMA. */ /* 0xfc048000 INTC. */ /* 0xfc058000 I2C. */ /* 0xfc05c000 QSPI. */ /* 0xfc060000 UART0. */ /* 0xfc064000 UART0. */ /* 0xfc068000 UART0. */ /* 0xfc070000 DMA timers. */ /* 0xfc080000 PIT0. */ /* 0xfc084000 PIT1. */ /* 0xfc088000 EPORT. */ /* 0xfc08c000 Watchdog. */ /* 0xfc090000 clock module. */ /* 0xfc0a0000 CCM + reset. */ /* 0xfc0a4000 GPIO. */ /* 0xfc0a8000 SDRAM controller. */ /* Load kernel. */ if (!kernel_filename) { if (qtest_enabled()) { return; } fprintf(stderr, "Kernel image must be specified\n"); exit(1); } kernel_size = load_elf(kernel_filename, NULL, NULL, &elf_entry, NULL, NULL, 1, EM_68K, 0, 0); entry = elf_entry; if (kernel_size < 0) { kernel_size = load_uimage(kernel_filename, &entry, NULL, NULL, NULL, NULL); } if (kernel_size < 0) { kernel_size = load_image_targphys(kernel_filename, 0x40000000, ram_size); entry = 0x40000000; } if (kernel_size < 0) { fprintf(stderr, "qemu: could not load kernel '%s'\n", kernel_filename); exit(1); } env->pc = entry; }


static void vga_get_text_resolution(VGACommonState *s, int *pwidth, int *pheight, int *pcwidth, int *pcheight) { int width, cwidth, height, cheight; /* total width & height */ cheight = (s->cr[VGA_CRTC_MAX_SCAN] & 0x1f) + 1; cwidth = 8; if (!(s->sr[VGA_SEQ_CLOCK_MODE] & VGA_SR01_CHAR_CLK_8DOTS)) { cwidth = 9; } if (s->sr[VGA_SEQ_CLOCK_MODE] & 0x08) { cwidth = 16; /* NOTE: no 18 pixel wide */ } width = (s->cr[VGA_CRTC_H_DISP] + 1); if (s->cr[VGA_CRTC_V_TOTAL] == 100) { /* ugly hack for CGA 160x100x16 - explain me the logic */ height = 100; } else { height = s->cr[VGA_CRTC_V_DISP_END] | ((s->cr[VGA_CRTC_OVERFLOW] & 0x02) << 7) | ((s->cr[VGA_CRTC_OVERFLOW] & 0x40) << 3); height = (height + 1) / cheight; } *pwidth = width; *pheight = height; *pcwidth = cwidth; *pcheight = cheight; }


int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt, AVFormatContext *src) { AVPacket local_pkt; local_pkt = *pkt; local_pkt.stream_index = dst_stream; if (pkt->pts != AV_NOPTS_VALUE) local_pkt.pts = av_rescale_q(pkt->pts, src->streams[pkt->stream_index]->time_base, dst->streams[dst_stream]->time_base); if (pkt->dts != AV_NOPTS_VALUE) local_pkt.dts = av_rescale_q(pkt->dts, src->streams[pkt->stream_index]->time_base, dst->streams[dst_stream]->time_base); if (pkt->duration) local_pkt.duration = av_rescale_q(pkt->duration, src->streams[pkt->stream_index]->time_base, dst->streams[dst_stream]->time_base); return av_write_frame(dst, &local_pkt); }


static int tm2_read_stream(TM2Context *ctx, const uint8_t *buf, int stream_id, int buf_size) { int i; int skip = 0; int len, toks, pos; TM2Codes codes; GetByteContext gb; if (buf_size < 4) { av_log(ctx->avctx, AV_LOG_ERROR, "not enough space for len left\n"); return AVERROR_INVALIDDATA; } /* get stream length in dwords */ bytestream2_init(&gb, buf, buf_size); len = bytestream2_get_be32(&gb); skip = len * 4 + 4; if(len == 0) return 4; if (len >= INT_MAX/4-1 || len < 0 || skip > buf_size) { av_log(ctx->avctx, AV_LOG_ERROR, "invalid stream size\n"); return AVERROR_INVALIDDATA; } toks = bytestream2_get_be32(&gb); if(toks & 1) { len = bytestream2_get_be32(&gb); if(len == TM2_ESCAPE) { len = bytestream2_get_be32(&gb); } if(len > 0) { pos = bytestream2_tell(&gb); if (skip <= pos) return AVERROR_INVALIDDATA; init_get_bits(&ctx->gb, buf + pos, (skip - pos) * 8); if(tm2_read_deltas(ctx, stream_id) == -1) return AVERROR_INVALIDDATA; bytestream2_skip(&gb, ((get_bits_count(&ctx->gb) + 31) >> 5) << 2); } } /* skip unused fields */ len = bytestream2_get_be32(&gb); if(len == TM2_ESCAPE) { /* some unknown length - could be escaped too */ bytestream2_skip(&gb, 8); /* unused by decoder */ } else { bytestream2_skip(&gb, 4); /* unused by decoder */ } pos = bytestream2_tell(&gb); if (skip <= pos) return AVERROR_INVALIDDATA; init_get_bits(&ctx->gb, buf + pos, (skip - pos) * 8); if(tm2_build_huff_table(ctx, &codes) == -1) return AVERROR_INVALIDDATA; bytestream2_skip(&gb, ((get_bits_count(&ctx->gb) + 31) >> 5) << 2); toks >>= 1; /* check if we have sane number of tokens */ if((toks < 0) || (toks > 0xFFFFFF)){ av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect number of tokens: %i\n", toks); tm2_free_codes(&codes); return AVERROR_INVALIDDATA; } ctx->tokens[stream_id] = av_realloc(ctx->tokens[stream_id], toks * sizeof(int)); ctx->tok_lens[stream_id] = toks; len = bytestream2_get_be32(&gb); if(len > 0) { pos = bytestream2_tell(&gb); if (skip <= pos) return AVERROR_INVALIDDATA; init_get_bits(&ctx->gb, buf + pos, (skip - pos) * 8); for(i = 0; i < toks; i++) { if (get_bits_left(&ctx->gb) <= 0) { av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect number of tokens: %i\n", toks); return AVERROR_INVALIDDATA; } ctx->tokens[stream_id][i] = tm2_get_token(&ctx->gb, &codes); if (stream_id <= TM2_MOT && ctx->tokens[stream_id][i] >= TM2_DELTAS) { av_log(ctx->avctx, AV_LOG_ERROR, "Invalid delta token index %d for type %d, n=%d\n", ctx->tokens[stream_id][i], stream_id, i); return AVERROR_INVALIDDATA; } } } else { for(i = 0; i < toks; i++) { ctx->tokens[stream_id][i] = codes.recode[0]; if (stream_id <= TM2_MOT && ctx->tokens[stream_id][i] >= TM2_DELTAS) { av_log(ctx->avctx, AV_LOG_ERROR, "Invalid delta token index %d for type %d, n=%d\n", ctx->tokens[stream_id][i], stream_id, i); return AVERROR_INVALIDDATA; } } } tm2_free_codes(&codes); return skip; }


static int parse_section_header(GetByteContext *gbc, int *section_size, enum HapSectionType *section_type) { if (bytestream2_get_bytes_left(gbc) < 4) return AVERROR_INVALIDDATA; *section_size = bytestream2_get_le24(gbc); *section_type = bytestream2_get_byte(gbc); if (*section_size == 0) { if (bytestream2_get_bytes_left(gbc) < 4) return AVERROR_INVALIDDATA; *section_size = bytestream2_get_le32(gbc); } if (*section_size > bytestream2_get_bytes_left(gbc)) return AVERROR_INVALIDDATA; else return 0; }


static int pps_range_extensions(GetBitContext *gb, AVCodecContext *avctx, HEVCPPS *pps, HEVCSPS *sps) { int i; if (pps->transform_skip_enabled_flag) { pps->log2_max_transform_skip_block_size = get_ue_golomb_long(gb) + 2; } pps->cross_component_prediction_enabled_flag = get_bits1(gb); pps->chroma_qp_offset_list_enabled_flag = get_bits1(gb); if (pps->chroma_qp_offset_list_enabled_flag) { pps->diff_cu_chroma_qp_offset_depth = get_ue_golomb_long(gb); pps->chroma_qp_offset_list_len_minus1 = get_ue_golomb_long(gb); if (pps->chroma_qp_offset_list_len_minus1 && pps->chroma_qp_offset_list_len_minus1 >= 5) { av_log(avctx, AV_LOG_ERROR, "chroma_qp_offset_list_len_minus1 shall be in the range [0, 5].\n"); return AVERROR_INVALIDDATA; } for (i = 0; i <= pps->chroma_qp_offset_list_len_minus1; i++) { pps->cb_qp_offset_list[i] = get_se_golomb_long(gb); if (pps->cb_qp_offset_list[i]) { av_log(avctx, AV_LOG_WARNING, "cb_qp_offset_list not tested yet.\n"); } pps->cr_qp_offset_list[i] = get_se_golomb_long(gb); if (pps->cr_qp_offset_list[i]) { av_log(avctx, AV_LOG_WARNING, "cb_qp_offset_list not tested yet.\n"); } } } pps->log2_sao_offset_scale_luma = get_ue_golomb_long(gb); pps->log2_sao_offset_scale_chroma = get_ue_golomb_long(gb); return(0); }


av_cold int ff_wma_init(AVCodecContext *avctx, int flags2) { WMACodecContext *s = avctx->priv_data; int i; float bps1, high_freq; volatile float bps; int sample_rate1; int coef_vlc_table; if (avctx->sample_rate <= 0 || avctx->sample_rate > 50000 || avctx->channels <= 0 || avctx->channels > 2 || avctx->bit_rate <= 0) return -1; ff_fmt_convert_init(&s->fmt_conv, avctx); avpriv_float_dsp_init(&s->fdsp, avctx->flags & CODEC_FLAG_BITEXACT); if (avctx->codec->id == AV_CODEC_ID_WMAV1) s->version = 1; else s->version = 2; /* compute MDCT block size */ s->frame_len_bits = ff_wma_get_frame_len_bits(avctx->sample_rate, s->version, 0); s->next_block_len_bits = s->frame_len_bits; s->prev_block_len_bits = s->frame_len_bits; s->block_len_bits = s->frame_len_bits; s->frame_len = 1 << s->frame_len_bits; if (s->use_variable_block_len) { int nb_max, nb; nb = ((flags2 >> 3) & 3) + 1; if ((avctx->bit_rate / avctx->channels) >= 32000) nb += 2; nb_max = s->frame_len_bits - BLOCK_MIN_BITS; if (nb > nb_max) nb = nb_max; s->nb_block_sizes = nb + 1; } else s->nb_block_sizes = 1; /* init rate dependent parameters */ s->use_noise_coding = 1; high_freq = avctx->sample_rate * 0.5; /* if version 2, then the rates are normalized */ sample_rate1 = avctx->sample_rate; if (s->version == 2) { if (sample_rate1 >= 44100) sample_rate1 = 44100; else if (sample_rate1 >= 22050) sample_rate1 = 22050; else if (sample_rate1 >= 16000) sample_rate1 = 16000; else if (sample_rate1 >= 11025) sample_rate1 = 11025; else if (sample_rate1 >= 8000) sample_rate1 = 8000; } bps = (float) avctx->bit_rate / (float) (avctx->channels * avctx->sample_rate); s->byte_offset_bits = av_log2((int) (bps * s->frame_len / 8.0 + 0.5)) + 2; /* compute high frequency value and choose if noise coding should * be activated */ bps1 = bps; if (avctx->channels == 2) bps1 = bps * 1.6; if (sample_rate1 == 44100) { if (bps1 >= 0.61) s->use_noise_coding = 0; else high_freq = high_freq * 0.4; } else if (sample_rate1 == 22050) { if (bps1 >= 1.16) s->use_noise_coding = 0; else if (bps1 >= 0.72) high_freq = high_freq * 0.7; else high_freq = high_freq * 0.6; } else if (sample_rate1 == 16000) { if (bps > 0.5) high_freq = high_freq * 0.5; else high_freq = high_freq * 0.3; } else if (sample_rate1 == 11025) high_freq = high_freq * 0.7; else if (sample_rate1 == 8000) { if (bps <= 0.625) high_freq = high_freq * 0.5; else if (bps > 0.75) s->use_noise_coding = 0; else high_freq = high_freq * 0.65; } else { if (bps >= 0.8) high_freq = high_freq * 0.75; else if (bps >= 0.6) high_freq = high_freq * 0.6; else high_freq = high_freq * 0.5; } av_dlog(s->avctx, "flags2=0x%x\n", flags2); av_dlog(s->avctx, "version=%d channels=%d sample_rate=%d bitrate=%d block_align=%d\n", s->version, avctx->channels, avctx->sample_rate, avctx->bit_rate, avctx->block_align); av_dlog(s->avctx, "bps=%f bps1=%f high_freq=%f bitoffset=%d\n", bps, bps1, high_freq, s->byte_offset_bits); av_dlog(s->avctx, "use_noise_coding=%d use_exp_vlc=%d nb_block_sizes=%d\n", s->use_noise_coding, s->use_exp_vlc, s->nb_block_sizes); /* compute the scale factor band sizes for each MDCT block size */ { int a, b, pos, lpos, k, block_len, i, j, n; const uint8_t *table; if (s->version == 1) s->coefs_start = 3; else s->coefs_start = 0; for (k = 0; k < s->nb_block_sizes; k++) { block_len = s->frame_len >> k; if (s->version == 1) { lpos = 0; for (i = 0; i < 25; i++) { a = ff_wma_critical_freqs[i]; b = avctx->sample_rate; pos = ((block_len * 2 * a) + (b >> 1)) / b; if (pos > block_len) pos = block_len; s->exponent_bands[0][i] = pos - lpos; if (pos >= block_len) { i++; break; } lpos = pos; } s->exponent_sizes[0] = i; } else { /* hardcoded tables */ table = NULL; a = s->frame_len_bits - BLOCK_MIN_BITS - k; if (a < 3) { if (avctx->sample_rate >= 44100) table = exponent_band_44100[a]; else if (avctx->sample_rate >= 32000) table = exponent_band_32000[a]; else if (avctx->sample_rate >= 22050) table = exponent_band_22050[a]; } if (table) { n = *table++; for (i = 0; i < n; i++) s->exponent_bands[k][i] = table[i]; s->exponent_sizes[k] = n; } else { j = 0; lpos = 0; for (i = 0; i < 25; i++) { a = ff_wma_critical_freqs[i]; b = avctx->sample_rate; pos = ((block_len * 2 * a) + (b << 1)) / (4 * b); pos <<= 2; if (pos > block_len) pos = block_len; if (pos > lpos) s->exponent_bands[k][j++] = pos - lpos; if (pos >= block_len) break; lpos = pos; } s->exponent_sizes[k] = j; } } /* max number of coefs */ s->coefs_end[k] = (s->frame_len - ((s->frame_len * 9) / 100)) >> k; /* high freq computation */ s->high_band_start[k] = (int) ((block_len * 2 * high_freq) / avctx->sample_rate + 0.5); n = s->exponent_sizes[k]; j = 0; pos = 0; for (i = 0; i < n; i++) { int start, end; start = pos; pos += s->exponent_bands[k][i]; end = pos; if (start < s->high_band_start[k]) start = s->high_band_start[k]; if (end > s->coefs_end[k]) end = s->coefs_end[k]; if (end > start) s->exponent_high_bands[k][j++] = end - start; } s->exponent_high_sizes[k] = j; #if 0 tprintf(s->avctx, "%5d: coefs_end=%d high_band_start=%d nb_high_bands=%d: ", s->frame_len >> k, s->coefs_end[k], s->high_band_start[k], s->exponent_high_sizes[k]); for (j = 0; j < s->exponent_high_sizes[k]; j++) tprintf(s->avctx, " %d", s->exponent_high_bands[k][j]); tprintf(s->avctx, "\n"); #endif /* 0 */ } } #ifdef TRACE { int i, j; for (i = 0; i < s->nb_block_sizes; i++) { tprintf(s->avctx, "%5d: n=%2d:", s->frame_len >> i, s->exponent_sizes[i]); for (j = 0; j < s->exponent_sizes[i]; j++) tprintf(s->avctx, " %d", s->exponent_bands[i][j]); tprintf(s->avctx, "\n"); } } #endif /* TRACE */ /* init MDCT windows : simple sine window */ for (i = 0; i < s->nb_block_sizes; i++) { ff_init_ff_sine_windows(s->frame_len_bits - i); s->windows[i] = ff_sine_windows[s->frame_len_bits - i]; } s->reset_block_lengths = 1; if (s->use_noise_coding) { /* init the noise generator */ if (s->use_exp_vlc) s->noise_mult = 0.02; else s->noise_mult = 0.04; #ifdef TRACE for (i = 0; i < NOISE_TAB_SIZE; i++) s->noise_table[i] = 1.0 * s->noise_mult; #else { unsigned int seed; float norm; seed = 1; norm = (1.0 / (float) (1LL << 31)) * sqrt(3) * s->noise_mult; for (i = 0; i < NOISE_TAB_SIZE; i++) { seed = seed * 314159 + 1; s->noise_table[i] = (float) ((int) seed) * norm; } } #endif /* TRACE */ } /* choose the VLC tables for the coefficients */ coef_vlc_table = 2; if (avctx->sample_rate >= 32000) { if (bps1 < 0.72) coef_vlc_table = 0; else if (bps1 < 1.16) coef_vlc_table = 1; } s->coef_vlcs[0] = &coef_vlcs[coef_vlc_table * 2]; s->coef_vlcs[1] = &coef_vlcs[coef_vlc_table * 2 + 1]; init_coef_vlc(&s->coef_vlc[0], &s->run_table[0], &s->level_table[0], &s->int_table[0], s->coef_vlcs[0]); init_coef_vlc(&s->coef_vlc[1], &s->run_table[1], &s->level_table[1], &s->int_table[1], s->coef_vlcs[1]); return 0; }


void ff_put_h264_qpel4_mc13_msa(uint8_t *dst, const uint8_t *src, ptrdiff_t stride) { avc_luma_hv_qrt_4w_msa(src + stride - 2, src - (stride * 2), stride, dst, stride, 4); }


static int flv_same_audio_codec(AVCodecContext *acodec, int flags) { int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8; int flv_codecid = flags & FLV_AUDIO_CODECID_MASK; int codec_id; if (!acodec->codec_id && !acodec->codec_tag) return 1; if (acodec->bits_per_coded_sample != bits_per_coded_sample) return 0; switch(flv_codecid) { //no distinction between S16 and S8 PCM codec flags case FLV_CODECID_PCM: codec_id = bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 : #if HAVE_BIGENDIAN AV_CODEC_ID_PCM_S16BE; #else AV_CODEC_ID_PCM_S16LE; #endif return codec_id == acodec->codec_id; case FLV_CODECID_PCM_LE: codec_id = bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 : AV_CODEC_ID_PCM_S16LE; return codec_id == acodec->codec_id; case FLV_CODECID_AAC: return acodec->codec_id == AV_CODEC_ID_AAC; case FLV_CODECID_ADPCM: return acodec->codec_id == AV_CODEC_ID_ADPCM_SWF; case FLV_CODECID_SPEEX: return acodec->codec_id == AV_CODEC_ID_SPEEX; case FLV_CODECID_MP3: return acodec->codec_id == AV_CODEC_ID_MP3; case FLV_CODECID_NELLYMOSER_8KHZ_MONO: case FLV_CODECID_NELLYMOSER_16KHZ_MONO: case FLV_CODECID_NELLYMOSER: return acodec->codec_id == AV_CODEC_ID_NELLYMOSER; case FLV_CODECID_PCM_MULAW: return acodec->sample_rate == 8000 && acodec->codec_id == AV_CODEC_ID_PCM_MULAW; case FLV_CODECID_PCM_ALAW: return acodec->sample_rate = 8000 && acodec->codec_id == AV_CODEC_ID_PCM_ALAW; default: return acodec->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET); } }


static inline void gen_op_clear_ieee_excp_and_FTT(void) { tcg_gen_andi_tl(cpu_fsr, cpu_fsr, ~(FSR_FTT_MASK | FSR_CEXC_MASK)); }


int avpriv_mpeg4audio_get_config(MPEG4AudioConfig *c, const uint8_t *buf, int bit_size, int sync_extension) { GetBitContext gb; int specific_config_bitindex; if(bit_size<=0) return AVERROR_INVALIDDATA; init_get_bits(&gb, buf, bit_size); c->object_type = get_object_type(&gb); c->sample_rate = get_sample_rate(&gb, &c->sampling_index); c->chan_config = get_bits(&gb, 4); if (c->chan_config < FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) c->channels = ff_mpeg4audio_channels[c->chan_config]; c->sbr = -1; c->ps = -1; if (c->object_type == AOT_SBR || (c->object_type == AOT_PS && // check for W6132 Annex YYYY draft MP3onMP4 !(show_bits(&gb, 3) & 0x03 && !(show_bits(&gb, 9) & 0x3F)))) { if (c->object_type == AOT_PS) c->ps = 1; c->ext_object_type = AOT_SBR; c->sbr = 1; c->ext_sample_rate = get_sample_rate(&gb, &c->ext_sampling_index); c->object_type = get_object_type(&gb); if (c->object_type == AOT_ER_BSAC) c->ext_chan_config = get_bits(&gb, 4); } else { c->ext_object_type = AOT_NULL; c->ext_sample_rate = 0; } specific_config_bitindex = get_bits_count(&gb); if (c->object_type == AOT_ALS) { skip_bits(&gb, 5); if (show_bits_long(&gb, 24) != MKBETAG('\0','A','L','S')) skip_bits_long(&gb, 24); specific_config_bitindex = get_bits_count(&gb); if (parse_config_ALS(&gb, c)) return -1; } if (c->ext_object_type != AOT_SBR && sync_extension) { while (get_bits_left(&gb) > 15) { if (show_bits(&gb, 11) == 0x2b7) { // sync extension get_bits(&gb, 11); c->ext_object_type = get_object_type(&gb); if (c->ext_object_type == AOT_SBR && (c->sbr = get_bits1(&gb)) == 1) { c->ext_sample_rate = get_sample_rate(&gb, &c->ext_sampling_index); if (c->ext_sample_rate == c->sample_rate) c->sbr = -1; } if (get_bits_left(&gb) > 11 && get_bits(&gb, 11) == 0x548) c->ps = get_bits1(&gb); break; } else get_bits1(&gb); // skip 1 bit } } //PS requires SBR if (!c->sbr) c->ps = 0; //Limit implicit PS to the HE-AACv2 Profile if ((c->ps == -1 && c->object_type != AOT_AAC_LC) || c->channels & ~0x01) c->ps = 0; return specific_config_bitindex; }


static void object_set_link_property(Object *obj, Visitor *v, void *opaque, const char *name, Error **errp) { Object **child = opaque; bool ambiguous = false; const char *type; char *path; type = object_property_get_type(obj, name, NULL); visit_type_str(v, &path, name, errp); if (*child) { object_unref(*child); } if (strcmp(path, "") != 0) { Object *target; target = object_resolve_path(path, &ambiguous); if (target) { gchar *target_type; target_type = g_strdup(&type[5]); target_type[strlen(target_type) - 2] = 0; if (object_dynamic_cast(target, target_type)) { object_ref(target); *child = target; } else { error_set(errp, QERR_INVALID_PARAMETER_TYPE, name, type); } g_free(target_type); } else { error_set(errp, QERR_DEVICE_NOT_FOUND, path); } } else { *child = NULL; } g_free(path); }


vorbis_header (AVFormatContext * s, int idx) { ogg_t *ogg = s->priv_data; ogg_stream_t *os = ogg->streams + idx; AVStream *st = s->streams[idx]; oggvorbis_private_t *priv; if (os->seq > 2) return 0; if (os->seq == 0) { os->private = av_mallocz(sizeof(oggvorbis_private_t)); if (!os->private) return 0; } priv = os->private; priv->len[os->seq] = os->psize; priv->packet[os->seq] = av_mallocz(os->psize); memcpy(priv->packet[os->seq], os->buf + os->pstart, os->psize); if (os->buf[os->pstart] == 1) { uint8_t *p = os->buf + os->pstart + 11; //skip up to the audio channels st->codec->channels = *p++; st->codec->sample_rate = AV_RL32(p); p += 8; //skip maximum and and nominal bitrate st->codec->bit_rate = AV_RL32(p); //Minimum bitrate st->codec->codec_type = CODEC_TYPE_AUDIO; st->codec->codec_id = CODEC_ID_VORBIS; st->time_base.num = 1; st->time_base.den = st->codec->sample_rate; } else if (os->buf[os->pstart] == 3) { vorbis_comment (s, os->buf + os->pstart + 7, os->psize - 8); } else { st->codec->extradata_size = fixup_vorbis_headers(s, priv, &st->codec->extradata); } return os->seq < 3; }


static void json_message_process_token(JSONLexer *lexer, GString *input, JSONTokenType type, int x, int y) { JSONMessageParser *parser = container_of(lexer, JSONMessageParser, lexer); JSONToken *token; switch (type) { case JSON_LCURLY: parser->brace_count++; break; case JSON_RCURLY: parser->brace_count--; break; case JSON_LSQUARE: parser->bracket_count++; break; case JSON_RSQUARE: parser->bracket_count--; break; default: break; } token = g_malloc(sizeof(JSONToken) + input->len + 1); token->type = type; memcpy(token->str, input->str, input->len); token->str[input->len] = 0; token->x = x; token->y = y; parser->token_size += input->len; g_queue_push_tail(parser->tokens, token); if (type == JSON_ERROR) { goto out_emit_bad; } else if (parser->brace_count < 0 || parser->bracket_count < 0 || (parser->brace_count == 0 && parser->bracket_count == 0)) { goto out_emit; } else if (parser->token_size > MAX_TOKEN_SIZE || g_queue_get_length(parser->tokens) > MAX_TOKEN_COUNT || parser->bracket_count + parser->brace_count > MAX_NESTING) { /* Security consideration, we limit total memory allocated per object * and the maximum recursion depth that a message can force. */ goto out_emit_bad; } return; out_emit_bad: /* * Clear out token list and tell the parser to emit an error * indication by passing it a NULL list */ json_message_free_tokens(parser); out_emit: /* send current list of tokens to parser and reset tokenizer */ parser->brace_count = 0; parser->bracket_count = 0; /* parser->emit takes ownership of parser->tokens. */ parser->emit(parser, parser->tokens); parser->tokens = g_queue_new(); parser->token_size = 0; }


static void test_blk_write(BlockBackend *blk, long pattern, int64_t offset, int64_t count, bool expect_failed) { void *pattern_buf = NULL; QEMUIOVector qiov; int async_ret = NOT_DONE; pattern_buf = g_malloc(count); if (pattern) { memset(pattern_buf, pattern, count); } else { memset(pattern_buf, 0x00, count); } qemu_iovec_init(&qiov, 1); qemu_iovec_add(&qiov, pattern_buf, count); blk_aio_pwritev(blk, offset, &qiov, 0, blk_rw_done, &async_ret); while (async_ret == NOT_DONE) { main_loop_wait(false); } if (expect_failed) { g_assert(async_ret != 0); } else { g_assert(async_ret == 0); } g_free(pattern_buf); }


void usb_packet_set_state(USBPacket *p, USBPacketState state) { static const char *name[] = { [USB_PACKET_UNDEFINED] = "undef", [USB_PACKET_SETUP] = "setup", [USB_PACKET_QUEUED] = "queued", [USB_PACKET_ASYNC] = "async", [USB_PACKET_COMPLETE] = "complete", [USB_PACKET_CANCELED] = "canceled", }; USBDevice *dev = p->ep->dev; USBBus *bus = usb_bus_from_device(dev); trace_usb_packet_state_change(bus->busnr, dev->port->path, p->ep->nr, p, name[p->state], name[state]); p->state = state; }


static struct URLProtocol *url_find_protocol(const char *filename) { URLProtocol *up = NULL; char proto_str[128], proto_nested[128], *ptr; size_t proto_len = strspn(filename, URL_SCHEME_CHARS); if (filename[proto_len] != ':' && (filename[proto_len] != ',' || !strchr(filename + proto_len + 1, ':')) || is_dos_path(filename)) strcpy(proto_str, "file"); else av_strlcpy(proto_str, filename, FFMIN(proto_len + 1, sizeof(proto_str))); if ((ptr = strchr(proto_str, ','))) *ptr = '\0'; av_strlcpy(proto_nested, proto_str, sizeof(proto_nested)); if ((ptr = strchr(proto_nested, '+'))) *ptr = '\0'; while (up = ffurl_protocol_next(up)) { if (!strcmp(proto_str, up->name)) break; if (up->flags & URL_PROTOCOL_FLAG_NESTED_SCHEME && !strcmp(proto_nested, up->name)) break; } return up; }