static int rd_strip(CinepakEncContext *s, int y, int h, int keyframe, AVPicture *last_pict, AVPicture *pict, AVPicture *scratch_pict, unsigned char *buf, int64_t *best_score) { int64_t score = 0; int best_size = 0, v1_size, v4_size, v4, mb_count = s->w * h / MB_AREA; strip_info info; CinepakMode best_mode; int v4_codebooks[CODEBOOK_NUM][CODEBOOK_MAX*VECTOR_MAX]; if(!keyframe) calculate_skip_errors(s, h, last_pict, pict, &info); //precompute V4 codebooks for(v4_size = 1, v4 = 0; v4_size <= 256; v4_size <<= 2, v4++) { info.v4_codebook = v4_codebooks[v4]; quantize(s, h, pict, 0, v4_size, v4, &info); } //try all powers of 4 for the size of the codebooks //constraint the v4 codebook to be no bigger than the v1 codebook for(v1_size = 1; v1_size <= 256; v1_size <<= 2) { //compute V1 codebook quantize(s, h, pict, 1, v1_size, -1, &info); for(v4_size = 0, v4 = -1; v4_size <= v1_size; v4_size = v4_size ? v4_size << 2 : v1_size >= 4 ? v1_size >> 2 : 1, v4++) { //try all modes for(CinepakMode mode = 0; mode < MODE_COUNT; mode++) { //don't allow MODE_MC in inter frames if(keyframe && mode == MODE_MC) continue; //only allow V1-only mode if v4 codebook is empty if(!v4_size && mode != MODE_V1_ONLY) continue; info.v4_codebook = v4 >= 0 ? v4_codebooks[v4] : NULL; score = calculate_mode_score(s, mode, h, v1_size, v4_size, v4, &info); //av_log(s->avctx, AV_LOG_INFO, "%3i %3i score = %li\n", v1_size, v4_size, score); if(best_size == 0 || score < *best_score) { *best_score = score; best_size = encode_mode(s, mode, h, v1_size, v4_size, v4, scratch_pict, &info, s->strip_buf + STRIP_HEADER_SIZE); best_mode = mode; av_log(s->avctx, AV_LOG_INFO, "mode %i, %3i, %3i: %18li %i B\n", mode, v1_size, v4_size, score, best_size); #ifdef CINEPAKENC_DEBUG //save MB encoding choices memcpy(s->best_mb, s->mb, mb_count*sizeof(mb_info)); #endif //memcpy(strip_temp + STRIP_HEADER_SIZE, strip_temp, best_size); write_strip_header(s, y, h, keyframe, s->strip_buf, best_size); } } } } #ifdef CINEPAKENC_DEBUG //gather stats. this will only work properly of MAX_STRIPS == 1 if(best_mode == MODE_V1_ONLY) { s->num_v1_mode++; s->num_v1_encs += s->w*h/MB_AREA; } else { if(best_mode == MODE_V1_V4) s->num_v4_mode++; else s->num_mc_mode++; int x; for(x = 0; x < s->w*h/MB_AREA; x++) if(s->best_mb[x].best_encoding == ENC_V1) s->num_v1_encs++; else if(s->best_mb[x].best_encoding == ENC_V4) s->num_v4_encs++; else s->num_skips++; } #endif best_size += STRIP_HEADER_SIZE; memcpy(buf, s->strip_buf, best_size); return best_size; }


void ide_sector_read(IDEState *s) { int64_t sector_num; int n; s->status = READY_STAT | SEEK_STAT; s->error = 0; /* not needed by IDE spec, but needed by Windows */ sector_num = ide_get_sector(s); n = s->nsector; if (n == 0) { ide_transfer_stop(s); s->status |= BUSY_STAT; if (n > s->req_nb_sectors) { n = s->req_nb_sectors; #if defined(DEBUG_IDE) printf("sector=%" PRId64 "\n", sector_num); #endif s->iov.iov_base = s->io_buffer; s->iov.iov_len = n * BDRV_SECTOR_SIZE; qemu_iovec_init_external(&s->qiov, &s->iov, 1); bdrv_acct_start(s->bs, &s->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ); s->pio_aiocb = bdrv_aio_readv(s->bs, sector_num, &s->qiov, n, ide_sector_read_cb, s);


static void pc_compat_1_5(QEMUMachineInitArgs *args) { pc_compat_1_6(args); has_pvpanic = true; }


int ff_v4l2_m2m_codec_init(AVCodecContext *avctx) { int ret = AVERROR(EINVAL); struct dirent *entry; char node[PATH_MAX]; DIR *dirp; V4L2m2mContext *s = avctx->priv_data; s->avctx = avctx; dirp = opendir("/dev"); if (!dirp) return AVERROR(errno); for (entry = readdir(dirp); entry; entry = readdir(dirp)) { if (strncmp(entry->d_name, "video", 5)) continue; snprintf(node, sizeof(node), "/dev/%s", entry->d_name); av_log(s->avctx, AV_LOG_DEBUG, "probing device %s\n", node); strncpy(s->devname, node, strlen(node) + 1); ret = v4l2_probe_driver(s); if (!ret) break; } closedir(dirp); if (ret) { av_log(s->avctx, AV_LOG_ERROR, "Could not find a valid device\n"); memset(s->devname, 0, sizeof(s->devname)); return ret; } av_log(s->avctx, AV_LOG_INFO, "Using device %s\n", node); return v4l2_configure_contexts(s); }


static int decode_frame_ilbm(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt) { IffContext *s = avctx->priv_data; const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; const uint8_t *buf_end = buf+buf_size; int y, plane; if (avctx->reget_buffer(avctx, &s->frame) < 0){ av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return -1; } for(y = 0; y < avctx->height; y++ ) { uint8_t *row = &s->frame.data[0][ y*s->frame.linesize[0] ]; memset(row, 0, avctx->pix_fmt == PIX_FMT_PAL8 ? avctx->width : (avctx->width * 4)); for (plane = 0; plane < avctx->bits_per_coded_sample && buf < buf_end; plane++) { if (avctx->pix_fmt == PIX_FMT_PAL8) { decodeplane8(row, buf, FFMIN(s->planesize, buf_end - buf), avctx->bits_per_coded_sample, plane); } else { // PIX_FMT_BGR32 decodeplane32(row, buf, FFMIN(s->planesize, buf_end - buf), avctx->bits_per_coded_sample, plane); } buf += s->planesize; } } *data_size = sizeof(AVFrame); *(AVFrame*)data = s->frame; return buf_size; }


static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { MP3DecContext *mp3 = s->priv_data; AVIndexEntry *ie, ie1; AVStream *st = s->streams[0]; int64_t ret = av_index_search_timestamp(st, timestamp, flags); int64_t best_pos; int fast_seek = (s->flags & AVFMT_FLAG_FAST_SEEK) ? 1 : 0; int64_t filesize = mp3->header_filesize; if (mp3->usetoc == 2) return -1; // generic index code if (filesize <= 0) { int64_t size = avio_size(s->pb); if (size > 0 && size > s->internal->data_offset) filesize = size - s->internal->data_offset; } if ( (mp3->is_cbr || fast_seek) && (mp3->usetoc == 0 || !mp3->xing_toc) && st->duration > 0 && filesize > 0) { ie = &ie1; timestamp = av_clip64(timestamp, 0, st->duration); ie->timestamp = timestamp; ie->pos = av_rescale(timestamp, filesize, st->duration) + s->internal->data_offset; } else if (mp3->xing_toc) { if (ret < 0) return ret; ie = &st->index_entries[ret]; } else { return -1; } best_pos = mp3_sync(s, ie->pos, flags); if (best_pos < 0) return best_pos; if (mp3->is_cbr && ie == &ie1 && mp3->frames) { int frame_duration = av_rescale(st->duration, 1, mp3->frames); ie1.timestamp = frame_duration * av_rescale(best_pos - s->internal->data_offset, mp3->frames, mp3->header_filesize); } ff_update_cur_dts(s, st, ie->timestamp); return 0; }


static int handle_secondary_tcp_pkt(NetFilterState *nf, Connection *conn, Packet *pkt) { struct tcphdr *tcp_pkt; tcp_pkt = (struct tcphdr *)pkt->transport_header; if (trace_event_get_state(TRACE_COLO_FILTER_REWRITER_DEBUG)) { char *sdebug, *ddebug; sdebug = strdup(inet_ntoa(pkt->ip->ip_src)); ddebug = strdup(inet_ntoa(pkt->ip->ip_dst)); trace_colo_filter_rewriter_pkt_info(__func__, sdebug, ddebug, ntohl(tcp_pkt->th_seq), ntohl(tcp_pkt->th_ack), tcp_pkt->th_flags); trace_colo_filter_rewriter_conn_offset(conn->offset); g_free(sdebug); g_free(ddebug); } if (((tcp_pkt->th_flags & (TH_ACK | TH_SYN)) == (TH_ACK | TH_SYN))) { /* * save offset = secondary_seq and then * in handle_primary_tcp_pkt make offset * = secondary_seq - primary_seq */ conn->offset = ntohl(tcp_pkt->th_seq); } if ((tcp_pkt->th_flags & (TH_ACK | TH_SYN)) == TH_ACK) { /* handle packets to the primary from the secondary*/ tcp_pkt->th_seq = htonl(ntohl(tcp_pkt->th_seq) - conn->offset); net_checksum_calculate((uint8_t *)pkt->data, pkt->size); } return 0; }


static inline bool cpu_handle_halt(CPUState *cpu) { if (cpu->halted) { #if defined(TARGET_I386) && !defined(CONFIG_USER_ONLY) if ((cpu->interrupt_request & CPU_INTERRUPT_POLL) && replay_interrupt()) { X86CPU *x86_cpu = X86_CPU(cpu); qemu_mutex_lock_iothread(); apic_poll_irq(x86_cpu->apic_state); cpu_reset_interrupt(cpu, CPU_INTERRUPT_POLL); qemu_mutex_unlock_iothread(); } #endif if (!cpu_has_work(cpu)) { current_cpu = NULL; return true; } cpu->halted = 0; } return false; }


static inline CopyRet copy_frame(AVCodecContext *avctx, BC_DTS_PROC_OUT *output, void *data, int *got_frame) { BC_STATUS ret; BC_DTS_STATUS decoder_status = { 0, }; uint8_t trust_interlaced; uint8_t interlaced; CHDContext *priv = avctx->priv_data; int64_t pkt_pts = AV_NOPTS_VALUE; uint8_t pic_type = 0; uint8_t bottom_field = (output->PicInfo.flags & VDEC_FLAG_BOTTOMFIELD) == VDEC_FLAG_BOTTOMFIELD; uint8_t bottom_first = !!(output->PicInfo.flags & VDEC_FLAG_BOTTOM_FIRST); int width = output->PicInfo.width; int height = output->PicInfo.height; int bwidth; uint8_t *src = output->Ybuff; int sStride; uint8_t *dst; int dStride; if (output->PicInfo.timeStamp != 0) { OpaqueList *node = opaque_list_pop(priv, output->PicInfo.timeStamp); if (node) { pkt_pts = node->reordered_opaque; pic_type = node->pic_type; av_free(node); } else { /* * We will encounter a situation where a timestamp cannot be * popped if a second field is being returned. In this case, * each field has the same timestamp and the first one will * cause it to be popped. To keep subsequent calculations * simple, pic_type should be set a FIELD value - doesn't * matter which, but I chose BOTTOM. */ pic_type = PICT_BOTTOM_FIELD; } av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n", output->PicInfo.timeStamp); av_log(avctx, AV_LOG_VERBOSE, "output picture type %d\n", pic_type); } ret = DtsGetDriverStatus(priv->dev, &decoder_status); if (ret != BC_STS_SUCCESS) { av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed: %u\n", ret); return RET_ERROR; } /* * For most content, we can trust the interlaced flag returned * by the hardware, but sometimes we can't. These are the * conditions under which we can trust the flag: * * 1) It's not h.264 content * 2) The UNKNOWN_SRC flag is not set * 3) We know we're expecting a second field * 4) The hardware reports this picture and the next picture * have the same picture number. * * Note that there can still be interlaced content that will * fail this check, if the hardware hasn't decoded the next * picture or if there is a corruption in the stream. (In either * case a 0 will be returned for the next picture number) */ trust_interlaced = avctx->codec->id != AV_CODEC_ID_H264 || !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) || priv->need_second_field || (decoder_status.picNumFlags & ~0x40000000) == output->PicInfo.picture_number; /* * If we got a false negative for trust_interlaced on the first field, * we will realise our mistake here when we see that the picture number is that * of the previous picture. We cannot recover the frame and should discard the * second field to keep the correct number of output frames. */ if (output->PicInfo.picture_number == priv->last_picture && !priv->need_second_field) { av_log(avctx, AV_LOG_WARNING, "Incorrectly guessed progressive frame. Discarding second field\n"); /* Returning without providing a picture. */ return RET_OK; } interlaced = (output->PicInfo.flags & VDEC_FLAG_INTERLACED_SRC) && trust_interlaced; if (!trust_interlaced && (decoder_status.picNumFlags & ~0x40000000) == 0) { av_log(avctx, AV_LOG_VERBOSE, "Next picture number unknown. Assuming progressive frame.\n"); } av_log(avctx, AV_LOG_VERBOSE, "Interlaced state: %d | trust_interlaced %d\n", interlaced, trust_interlaced); if (priv->pic->data[0] && !priv->need_second_field) av_frame_unref(priv->pic); priv->need_second_field = interlaced && !priv->need_second_field; if (!priv->pic->data[0]) { if (ff_get_buffer(avctx, priv->pic, AV_GET_BUFFER_FLAG_REF) < 0) return RET_ERROR; } bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0); if (priv->is_70012) { int pStride; if (width <= 720) pStride = 720; else if (width <= 1280) pStride = 1280; else pStride = 1920; sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0); } else { sStride = bwidth; } dStride = priv->pic->linesize[0]; dst = priv->pic->data[0]; av_log(priv->avctx, AV_LOG_VERBOSE, "CrystalHD: Copying out frame\n"); if (interlaced) { int dY = 0; int sY = 0; height /= 2; if (bottom_field) { av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n"); dY = 1; } else { av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n"); dY = 0; } for (sY = 0; sY < height; dY++, sY++) { memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth); dY++; } } else { av_image_copy_plane(dst, dStride, src, sStride, bwidth, height); } priv->pic->interlaced_frame = interlaced; if (interlaced) priv->pic->top_field_first = !bottom_first; priv->pic->pts = pkt_pts; #if FF_API_PKT_PTS FF_DISABLE_DEPRECATION_WARNINGS priv->pic->pkt_pts = pkt_pts; FF_ENABLE_DEPRECATION_WARNINGS #endif if (!priv->need_second_field) { *got_frame = 1; if ((ret = av_frame_ref(data, priv->pic)) < 0) { return ret; } } /* * Two types of PAFF content have been observed. One form causes the * hardware to return a field pair and the other individual fields, * even though the input is always individual fields. We must skip * copying on the next decode() call to maintain pipeline length in * the first case. */ if (!interlaced && (output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) && (pic_type == PICT_TOP_FIELD || pic_type == PICT_BOTTOM_FIELD)) { av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n"); return RET_SKIP_NEXT_COPY; } /* * The logic here is purely based on empirical testing with samples. * If we need a second field, it could come from a second input packet, * or it could come from the same field-pair input packet at the current * field. In the first case, we should return and wait for the next time * round to get the second field, while in the second case, we should * ask the decoder for it immediately. * * Testing has shown that we are dealing with the fieldpair -> two fields * case if the VDEC_FLAG_UNKNOWN_SRC is not set or if the input picture * type was PICT_FRAME (in this second case, the flag might still be set) */ return priv->need_second_field && (!(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) || pic_type == PICT_FRAME) ? RET_COPY_NEXT_FIELD : RET_OK; }


static av_cold int prores_encode_init(AVCodecContext *avctx) { int i; ProresContext* ctx = avctx->priv_data; if (avctx->pix_fmt != PIX_FMT_YUV422P10LE) { av_log(avctx, AV_LOG_ERROR, "need YUV422P10\n"); return -1; } if (avctx->width & 0x1) { av_log(avctx, AV_LOG_ERROR, "frame width needs to be multiple of 2\n"); return -1; } if ((avctx->height & 0xf) || (avctx->width & 0xf)) { ctx->fill_y = av_malloc(DEFAULT_SLICE_MB_WIDTH << 9); ctx->fill_u = av_malloc(DEFAULT_SLICE_MB_WIDTH << 8); ctx->fill_v = av_malloc(DEFAULT_SLICE_MB_WIDTH << 8); } if (avctx->profile == FF_PROFILE_UNKNOWN) { avctx->profile = FF_PROFILE_PRORES_STANDARD; av_log(avctx, AV_LOG_INFO, "encoding with ProRes standard (apcn) profile\n"); } else if (avctx->profile < FF_PROFILE_PRORES_PROXY || avctx->profile > FF_PROFILE_PRORES_HQ) { av_log( avctx, AV_LOG_ERROR, "unknown profile %d, use [0 - apco, 1 - apcs, 2 - apcn (default), 3 - apch]\n", avctx->profile); return -1; } avctx->codec_tag = AV_RL32((const uint8_t*)profiles[avctx->profile].name); for (i = 1; i <= 16; i++) { scale_mat(QMAT_LUMA[avctx->profile] , ctx->qmat_luma[i - 1] , i); scale_mat(QMAT_CHROMA[avctx->profile], ctx->qmat_chroma[i - 1], i); } avctx->coded_frame = avcodec_alloc_frame(); avctx->coded_frame->key_frame = 1; avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I; return 0; }


static void test_visitor_out_union_flat(TestOutputVisitorData *data, const void *unused) { QObject *arg; QDict *qdict; UserDefFlatUnion *tmp = g_malloc0(sizeof(UserDefFlatUnion)); tmp->enum1 = ENUM_ONE_VALUE1; tmp->string = g_strdup("str"); tmp->u.value1 = g_malloc0(sizeof(UserDefA)); tmp->integer = 41; tmp->u.value1->boolean = true; visit_type_UserDefFlatUnion(data->ov, NULL, &tmp, &error_abort); arg = qmp_output_get_qobject(data->qov); g_assert(qobject_type(arg) == QTYPE_QDICT); qdict = qobject_to_qdict(arg); g_assert_cmpstr(qdict_get_str(qdict, "enum1"), ==, "value1"); g_assert_cmpstr(qdict_get_str(qdict, "string"), ==, "str"); g_assert_cmpint(qdict_get_int(qdict, "integer"), ==, 41); g_assert_cmpint(qdict_get_bool(qdict, "boolean"), ==, true); qapi_free_UserDefFlatUnion(tmp); QDECREF(qdict); }


int estimate_motion(MpegEncContext * s, int mb_x, int mb_y, int *mx_ptr, int *my_ptr) { UINT8 *pix, *ppix; int sum, varc, vard, mx, my, range, dmin, xx, yy; int xmin, ymin, xmax, ymax; int rel_xmin, rel_ymin, rel_xmax, rel_ymax; int pred_x=0, pred_y=0; int P[5][2]; const int shift= 1+s->quarter_sample; range = 8 * (1 << (s->f_code - 1)); /* XXX: temporary kludge to avoid overflow for msmpeg4 */ if (s->out_format == FMT_H263 && !s->h263_msmpeg4) range = range * 2; if (s->unrestricted_mv) { xmin = -16; ymin = -16; if (s->h263_plus) range *= 2; if(s->avctx==NULL || s->avctx->codec->id!=CODEC_ID_MPEG4){ xmax = s->mb_width*16; ymax = s->mb_height*16; }else { /* XXX: dunno if this is correct but ffmpeg4 decoder wont like it otherwise (cuz the drawn edge isnt large enough))*/ xmax = s->width; ymax = s->height; } } else { xmin = 0; ymin = 0; xmax = s->mb_width*16 - 16; ymax = s->mb_height*16 - 16; } switch(s->full_search) { case ME_ZERO: default: no_motion_search(s, &mx, &my); dmin = 0; break; case ME_FULL: dmin = full_motion_search(s, &mx, &my, range, xmin, ymin, xmax, ymax); break; case ME_LOG: dmin = log_motion_search(s, &mx, &my, range / 2, xmin, ymin, xmax, ymax); break; case ME_PHODS: dmin = phods_motion_search(s, &mx, &my, range / 2, xmin, ymin, xmax, ymax); break; case ME_X1: // just reserving some space for experiments ... case ME_EPZS: rel_xmin= xmin - s->mb_x*16; rel_xmax= xmax - s->mb_x*16; rel_ymin= ymin - s->mb_y*16; rel_ymax= ymax - s->mb_y*16; if(s->out_format == FMT_H263){ static const int off[4]= {2, 1, 1, -1}; const int mot_stride = s->block_wrap[0]; const int mot_xy = s->block_index[0]; P[0][0] = s->motion_val[mot_xy ][0]; P[0][1] = s->motion_val[mot_xy ][1]; P[1][0] = s->motion_val[mot_xy - 1][0]; P[1][1] = s->motion_val[mot_xy - 1][1]; if(P[1][0] > (rel_xmax<<shift)) P[1][0]= (rel_xmax<<shift); /* special case for first line */ if ((s->mb_y == 0 || s->first_slice_line || s->first_gob_line)) { pred_x = P[1][0]; pred_y = P[1][1]; } else { P[2][0] = s->motion_val[mot_xy - mot_stride ][0]; P[2][1] = s->motion_val[mot_xy - mot_stride ][1]; P[3][0] = s->motion_val[mot_xy - mot_stride + off[0] ][0]; P[3][1] = s->motion_val[mot_xy - mot_stride + off[0] ][1]; if(P[2][1] > (rel_ymax<<shift)) P[2][1]= (rel_ymax<<shift); if(P[3][0] < (rel_xmin<<shift)) P[3][0]= (rel_xmin<<shift); if(P[3][1] > (rel_ymax<<shift)) P[3][1]= (rel_ymax<<shift); P[4][0]= pred_x = mid_pred(P[1][0], P[2][0], P[3][0]); P[4][1]= pred_y = mid_pred(P[1][1], P[2][1], P[3][1]); } }else { const int xy= s->mb_y*s->mb_width + s->mb_x; pred_x= s->last_mv[0][0][0]; pred_y= s->last_mv[0][0][1]; P[0][0]= s->mv_table[0][xy ]; P[0][1]= s->mv_table[1][xy ]; if(s->mb_x == 0){ P[1][0]= 0; P[1][1]= 0; }else{ P[1][0]= s->mv_table[0][xy-1]; P[1][1]= s->mv_table[1][xy-1]; if(P[1][0] > (rel_xmax<<shift)) P[1][0]= (rel_xmax<<shift); } if (!(s->mb_y == 0 || s->first_slice_line || s->first_gob_line)) { P[2][0] = s->mv_table[0][xy - s->mb_width]; P[2][1] = s->mv_table[1][xy - s->mb_width]; P[3][0] = s->mv_table[0][xy - s->mb_width+1]; P[3][1] = s->mv_table[1][xy - s->mb_width+1]; if(P[2][1] > (rel_ymax<<shift)) P[2][1]= (rel_ymax<<shift); if(P[3][0] > (rel_xmax<<shift)) P[3][0]= (rel_xmax<<shift); if(P[3][0] < (rel_xmin<<shift)) P[3][0]= (rel_xmin<<shift); if(P[3][1] > (rel_ymax<<shift)) P[3][1]= (rel_ymax<<shift); P[4][0]= mid_pred(P[1][0], P[2][0], P[3][0]); P[4][1]= mid_pred(P[1][1], P[2][1], P[3][1]); } } dmin = epzs_motion_search(s, &mx, &my, P, pred_x, pred_y, rel_xmin, rel_ymin, rel_xmax, rel_ymax); mx+= s->mb_x*16; my+= s->mb_y*16; break; } /* intra / predictive decision */ xx = mb_x * 16; yy = mb_y * 16; pix = s->new_picture[0] + (yy * s->linesize) + xx; /* At this point (mx,my) are full-pell and the absolute displacement */ ppix = s->last_picture[0] + (my * s->linesize) + mx; sum = pix_sum(pix, s->linesize); varc = pix_norm1(pix, s->linesize); vard = pix_norm(pix, ppix, s->linesize); vard = vard >> 8; sum = sum >> 8; varc = (varc >> 8) - (sum * sum); s->mb_var[s->mb_width * mb_y + mb_x] = varc; s->avg_mb_var += varc; s->mc_mb_var += vard; #if 0 printf("varc=%4d avg_var=%4d (sum=%4d) vard=%4d mx=%2d my=%2d\n", varc, s->avg_mb_var, sum, vard, mx - xx, my - yy); #endif if (vard <= 64 || vard < varc) { if (s->full_search != ME_ZERO) { halfpel_motion_search(s, &mx, &my, dmin, xmin, ymin, xmax, ymax, pred_x, pred_y); } else { mx -= 16 * s->mb_x; my -= 16 * s->mb_y; } *mx_ptr = mx; *my_ptr = my; return 0; } else { *mx_ptr = 0; *my_ptr = 0; return 1; } }


static int bad_mode_switch(CPUARMState *env, int mode) { /* Return true if it is not valid for us to switch to * this CPU mode (ie all the UNPREDICTABLE cases in * the ARM ARM CPSRWriteByInstr pseudocode). */ switch (mode) { case ARM_CPU_MODE_USR: case ARM_CPU_MODE_SYS: case ARM_CPU_MODE_SVC: case ARM_CPU_MODE_ABT: case ARM_CPU_MODE_UND: case ARM_CPU_MODE_IRQ: case ARM_CPU_MODE_FIQ: /* Note that we don't implement the IMPDEF NSACR.RFR which in v7 * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.) */ return 0; case ARM_CPU_MODE_HYP: return !arm_feature(env, ARM_FEATURE_EL2) || arm_current_el(env) < 2 || arm_is_secure(env); case ARM_CPU_MODE_MON: return !arm_is_secure(env); default: return 1; } }


static void scsi_write_complete(void * opaque, int ret) { SCSIDiskReq *r = (SCSIDiskReq *)opaque; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t n; if (r->req.aiocb != NULL) { r->req.aiocb = NULL; bdrv_acct_done(s->qdev.conf.bs, &r->acct); } if (ret < 0) { if (scsi_handle_rw_error(r, -ret)) { goto done; } } n = r->qiov.size / 512; r->sector += n; r->sector_count -= n; if (r->sector_count == 0) { scsi_req_complete(&r->req, GOOD); } else { scsi_init_iovec(r, SCSI_DMA_BUF_SIZE); DPRINTF("Write complete tag=0x%x more=%d\n", r->req.tag, r->qiov.size); scsi_req_data(&r->req, r->qiov.size); } done: if (!r->req.io_canceled) { scsi_req_unref(&r->req); } }


static void subband_scale(int *dst, int *src, int scale, int offset, int len) { int ssign = scale < 0 ? -1 : 1; int s = FFABS(scale); unsigned int round; int i, out, c = exp2tab[s & 3]; s = offset - (s >> 2); if (s > 31) { for (i=0; i<len; i++) { dst[i] = 0; } } else if (s > 0) { round = 1 << (s-1); for (i=0; i<len; i++) { out = (int)(((int64_t)src[i] * c) >> 32); dst[i] = ((int)(out+round) >> s) * ssign; } } else { s = s + 32; round = 1U << (s-1); for (i=0; i<len; i++) { out = (int)((int64_t)((int64_t)src[i] * c + round) >> s); dst[i] = out * ssign; } } }


static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value) { env->cp15.c5_insn = extended_mpu_ap_bits(value); }


qht_entry_move(struct qht_bucket *to, int i, struct qht_bucket *from, int j) { qht_debug_assert(!(to == from && i == j)); qht_debug_assert(to->pointers[i]); qht_debug_assert(from->pointers[j]); to->hashes[i] = from->hashes[j]; atomic_set(&to->pointers[i], from->pointers[j]); from->hashes[j] = 0; atomic_set(&from->pointers[j], NULL); }


static int atrac3_decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; ATRAC3Context *q = avctx->priv_data; int result = 0; const uint8_t* databuf; float *samples = data; if (buf_size < avctx->block_align) { av_log(avctx, AV_LOG_ERROR, "Frame too small (%d bytes). Truncated file?\n", buf_size); *data_size = 0; return buf_size; } /* Check if we need to descramble and what buffer to pass on. */ if (q->scrambled_stream) { decode_bytes(buf, q->decoded_bytes_buffer, avctx->block_align); databuf = q->decoded_bytes_buffer; } else { databuf = buf; } result = decodeFrame(q, databuf, q->channels == 2 ? q->outSamples : &samples); if (result != 0) { av_log(NULL,AV_LOG_ERROR,"Frame decoding error!\n"); return -1; } /* interleave */ if (q->channels == 2) { q->fmt_conv.float_interleave(samples, (const float **)q->outSamples, 1024, 2); } *data_size = 1024 * q->channels * av_get_bytes_per_sample(avctx->sample_fmt); return avctx->block_align; }


static int flic_probe(AVProbeData *p) { int magic_number; if (p->buf_size < 6) return 0; magic_number = AV_RL16(&p->buf[4]); if ((magic_number != FLIC_FILE_MAGIC_1) && (magic_number != FLIC_FILE_MAGIC_2) && (magic_number != FLIC_FILE_MAGIC_3)) return 0; return AVPROBE_SCORE_MAX; }


static int jp2_find_codestream(J2kDecoderContext *s) { uint32_t atom_size; int found_codestream = 0, search_range = 10; // skip jpeg2k signature atom s->buf += 12; while(!found_codestream && search_range && s->buf_end - s->buf >= 8) { atom_size = AV_RB32(s->buf); if(AV_RB32(s->buf + 4) == JP2_CODESTREAM) { found_codestream = 1; s->buf += 8; } else { if (s->buf_end - s->buf < atom_size) return 0; s->buf += atom_size; search_range--; } } if(found_codestream) return 1; return 0; }


static void tswap_siginfo(target_siginfo_t *tinfo, const target_siginfo_t *info) { int sig = info->si_signo; tinfo->si_signo = tswap32(sig); tinfo->si_errno = tswap32(info->si_errno); tinfo->si_code = tswap32(info->si_code); if (sig == TARGET_SIGILL || sig == TARGET_SIGFPE || sig == TARGET_SIGSEGV || sig == TARGET_SIGBUS || sig == TARGET_SIGTRAP) { tinfo->_sifields._sigfault._addr = tswapal(info->_sifields._sigfault._addr); } else if (sig == TARGET_SIGIO) { tinfo->_sifields._sigpoll._band = tswap32(info->_sifields._sigpoll._band); tinfo->_sifields._sigpoll._fd = tswap32(info->_sifields._sigpoll._fd); } else if (sig == TARGET_SIGCHLD) { tinfo->_sifields._sigchld._pid = tswap32(info->_sifields._sigchld._pid); tinfo->_sifields._sigchld._uid = tswap32(info->_sifields._sigchld._uid); tinfo->_sifields._sigchld._status = tswap32(info->_sifields._sigchld._status); tinfo->_sifields._sigchld._utime = tswapal(info->_sifields._sigchld._utime); tinfo->_sifields._sigchld._stime = tswapal(info->_sifields._sigchld._stime); } else if (sig >= TARGET_SIGRTMIN) { tinfo->_sifields._rt._pid = tswap32(info->_sifields._rt._pid); tinfo->_sifields._rt._uid = tswap32(info->_sifields._rt._uid); tinfo->_sifields._rt._sigval.sival_ptr = tswapal(info->_sifields._rt._sigval.sival_ptr); } }


void axisdev88_init (ram_addr_t ram_size, const char *boot_device, const char *kernel_filename, const char *kernel_cmdline, const char *initrd_filename, const char *cpu_model) { CPUState *env; DeviceState *dev; SysBusDevice *s; qemu_irq irq[30], nmi[2], *cpu_irq; void *etraxfs_dmac; struct etraxfs_dma_client *eth[2] = {NULL, NULL}; int kernel_size; int i; int nand_regs; int gpio_regs; ram_addr_t phys_ram; ram_addr_t phys_intmem; /* init CPUs */ if (cpu_model == NULL) { cpu_model = "crisv32"; } env = cpu_init(cpu_model); qemu_register_reset(main_cpu_reset, env); /* allocate RAM */ phys_ram = qemu_ram_alloc(ram_size); cpu_register_physical_memory(0x40000000, ram_size, phys_ram | IO_MEM_RAM); /* The ETRAX-FS has 128Kb on chip ram, the docs refer to it as the internal memory. */ phys_intmem = qemu_ram_alloc(INTMEM_SIZE); cpu_register_physical_memory(0x38000000, INTMEM_SIZE, phys_intmem | IO_MEM_RAM); /* Attach a NAND flash to CS1. */ nand_state.nand = nand_init(NAND_MFR_STMICRO, 0x39); nand_regs = cpu_register_io_memory(nand_read, nand_write, &nand_state); cpu_register_physical_memory(0x10000000, 0x05000000, nand_regs); gpio_state.nand = &nand_state; gpio_regs = cpu_register_io_memory(gpio_read, gpio_write, &gpio_state); cpu_register_physical_memory(0x3001a000, 0x5c, gpio_regs); cpu_irq = cris_pic_init_cpu(env); dev = qdev_create(NULL, "etraxfs,pic"); /* FIXME: Is there a proper way to signal vectors to the CPU core? */ qdev_prop_set_ptr(dev, "interrupt_vector", &env->interrupt_vector); qdev_init(dev); s = sysbus_from_qdev(dev); sysbus_mmio_map(s, 0, 0x3001c000); sysbus_connect_irq(s, 0, cpu_irq[0]); sysbus_connect_irq(s, 1, cpu_irq[1]); for (i = 0; i < 30; i++) { irq[i] = qdev_get_gpio_in(dev, i); } nmi[0] = qdev_get_gpio_in(dev, 30); nmi[1] = qdev_get_gpio_in(dev, 31); etraxfs_dmac = etraxfs_dmac_init(0x30000000, 10); for (i = 0; i < 10; i++) { /* On ETRAX, odd numbered channels are inputs. */ etraxfs_dmac_connect(etraxfs_dmac, i, irq + 7 + i, i & 1); } /* Add the two ethernet blocks. */ eth[0] = etraxfs_eth_init(&nd_table[0], 0x30034000, 1); if (nb_nics > 1) eth[1] = etraxfs_eth_init(&nd_table[1], 0x30036000, 2); /* The DMA Connector block is missing, hardwire things for now. */ etraxfs_dmac_connect_client(etraxfs_dmac, 0, eth[0]); etraxfs_dmac_connect_client(etraxfs_dmac, 1, eth[0] + 1); if (eth[1]) { etraxfs_dmac_connect_client(etraxfs_dmac, 6, eth[1]); etraxfs_dmac_connect_client(etraxfs_dmac, 7, eth[1] + 1); } /* 2 timers. */ sysbus_create_varargs("etraxfs,timer", 0x3001e000, irq[0x1b], nmi[1], NULL); sysbus_create_varargs("etraxfs,timer", 0x3005e000, irq[0x1b], nmi[1], NULL); for (i = 0; i < 4; i++) { sysbus_create_simple("etraxfs,serial", 0x30026000 + i * 0x2000, irq[0x14 + i]); } if (kernel_filename) { uint64_t entry, high; int kcmdline_len; /* Boots a kernel elf binary, os/linux-2.6/vmlinux from the axis devboard SDK. */ kernel_size = load_elf(kernel_filename, -0x80000000LL, &entry, NULL, &high, 0, ELF_MACHINE, 0); bootstrap_pc = entry; if (kernel_size < 0) { /* Takes a kimage from the axis devboard SDK. */ kernel_size = load_image_targphys(kernel_filename, 0x40004000, ram_size); bootstrap_pc = 0x40004000; env->regs[9] = 0x40004000 + kernel_size; } env->regs[8] = 0x56902387; /* RAM init magic. */ if (kernel_cmdline && (kcmdline_len = strlen(kernel_cmdline))) { if (kcmdline_len > 256) { fprintf(stderr, "Too long CRIS kernel cmdline (max 256)\n"); exit(1); } /* Let the kernel know we are modifying the cmdline. */ env->regs[10] = 0x87109563; env->regs[11] = 0x40000000; pstrcpy_targphys(env->regs[11], 256, kernel_cmdline); } } env->pc = bootstrap_pc; printf ("pc =%x\n", env->pc); printf ("ram size =%ld\n", ram_size); }


static int decode_pic_timing(HEVCContext *s) { GetBitContext *gb = &s->HEVClc->gb; HEVCSPS *sps = (HEVCSPS*)s->sps_list[s->active_seq_parameter_set_id]->data; if (!sps) return(AVERROR(ENOMEM)); if (sps->vui.frame_field_info_present_flag) { int pic_struct = get_bits(gb, 4); s->picture_struct = AV_PICTURE_STRUCTURE_UNKNOWN; if (pic_struct == 2) { av_log(s->avctx, AV_LOG_DEBUG, "BOTTOM Field\n"); s->picture_struct = AV_PICTURE_STRUCTURE_BOTTOM_FIELD; } else if (pic_struct == 1) { av_log(s->avctx, AV_LOG_DEBUG, "TOP Field\n"); s->picture_struct = AV_PICTURE_STRUCTURE_TOP_FIELD; } get_bits(gb, 2); // source_scan_type get_bits(gb, 1); // duplicate_flag } return 1; }


static void *circular_buffer_task( void *_URLContext) { URLContext *h = _URLContext; UDPContext *s = h->priv_data; fd_set rfds; struct timeval tv; while(!s->exit_thread) { int left; int ret; int len; if (ff_check_interrupt(&h->interrupt_callback)) { s->circular_buffer_error = AVERROR(EINTR); goto end; } FD_ZERO(&rfds); FD_SET(s->udp_fd, &rfds); tv.tv_sec = 1; tv.tv_usec = 0; ret = select(s->udp_fd + 1, &rfds, NULL, NULL, &tv); if (ret < 0) { if (ff_neterrno() == AVERROR(EINTR)) continue; s->circular_buffer_error = AVERROR(EIO); goto end; } if (!(ret > 0 && FD_ISSET(s->udp_fd, &rfds))) continue; /* How much do we have left to the end of the buffer */ /* Whats the minimum we can read so that we dont comletely fill the buffer */ left = av_fifo_space(s->fifo); /* No Space left, error, what do we do now */ if(left < UDP_MAX_PKT_SIZE + 4) { av_log(h, AV_LOG_ERROR, "circular_buffer: OVERRUN\n"); s->circular_buffer_error = AVERROR(EIO); goto end; } len = recv(s->udp_fd, s->tmp+4, sizeof(s->tmp)-4, 0); if (len < 0) { if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) { s->circular_buffer_error = AVERROR(EIO); goto end; } continue; } AV_WL32(s->tmp, len); pthread_mutex_lock(&s->mutex); av_fifo_generic_write(s->fifo, s->tmp, len+4, NULL); pthread_cond_signal(&s->cond); pthread_mutex_unlock(&s->mutex); } end: pthread_mutex_lock(&s->mutex); pthread_cond_signal(&s->cond); pthread_mutex_unlock(&s->mutex); return NULL; }


static int decode_rle(uint8_t *bitmap, int linesize, int w, int h, const uint8_t *buf, int start, int buf_size, int is_8bit) { GetBitContext gb; int bit_len; int x, y, len, color; uint8_t *d; if (start >= buf_size) bit_len = (buf_size - start) * 8; init_get_bits(&gb, buf + start, bit_len); x = 0; y = 0; d = bitmap; for(;;) { if (get_bits_count(&gb) > bit_len) if (is_8bit) len = decode_run_8bit(&gb, &color); else len = decode_run_2bit(&gb, &color); len = FFMIN(len, w - x); memset(d + x, color, len); x += len; if (x >= w) { y++; if (y >= h) break; d += linesize; x = 0; /* byte align */ align_get_bits(&gb); } } return 0; }


void bdrv_eject(BlockDriverState *bs, int eject_flag) { BlockDriver *drv = bs->drv; int ret; if (!drv || !drv->bdrv_eject) { ret = -ENOTSUP; } else { ret = drv->bdrv_eject(bs, eject_flag); } if (ret == -ENOTSUP) { if (eject_flag) bdrv_close(bs); } }


static MemTxResult memory_region_write_with_attrs_accessor(MemoryRegion *mr, hwaddr addr, uint64_t *value, unsigned size, unsigned shift, uint64_t mask, MemTxAttrs attrs) { uint64_t tmp; tmp = (*value >> shift) & mask; if (mr->subpage) { trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size); } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) { hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr); trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size); } return mr->ops->write_with_attrs(mr->opaque, addr, tmp, size, attrs); }


static void usbredir_realize(USBDevice *udev, Error **errp) { USBRedirDevice *dev = USB_REDIRECT(udev); int i; if (!qemu_chr_fe_get_driver(&dev->cs)) { error_setg(errp, QERR_MISSING_PARAMETER, "chardev"); return; } if (dev->filter_str) { i = usbredirfilter_string_to_rules(dev->filter_str, ":", "|", &dev->filter_rules, &dev->filter_rules_count); if (i) { error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "filter", "a usb device filter string"); return; } } dev->chardev_close_bh = qemu_bh_new(usbredir_chardev_close_bh, dev); dev->device_reject_bh = qemu_bh_new(usbredir_device_reject_bh, dev); dev->attach_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, usbredir_do_attach, dev); packet_id_queue_init(&dev->cancelled, dev, "cancelled"); packet_id_queue_init(&dev->already_in_flight, dev, "already-in-flight"); usbredir_init_endpoints(dev); /* We'll do the attach once we receive the speed from the usb-host */ udev->auto_attach = 0; /* Will be cleared during setup when we find conflicts */ dev->compatible_speedmask = USB_SPEED_MASK_FULL | USB_SPEED_MASK_HIGH; /* Let the backend know we are ready */ qemu_chr_fe_set_handlers(&dev->cs, usbredir_chardev_can_read, usbredir_chardev_read, usbredir_chardev_event, dev, NULL, true); qemu_add_vm_change_state_handler(usbredir_vm_state_change, dev); }


static void coroutine_fn v9fs_lcreate(void *opaque) { int32_t dfid, flags, mode; gid_t gid; ssize_t err = 0; ssize_t offset = 7; V9fsString name; V9fsFidState *fidp; struct stat stbuf; V9fsQID qid; int32_t iounit; V9fsPDU *pdu = opaque; v9fs_string_init(&name); err = pdu_unmarshal(pdu, offset, "dsddd", &dfid, &name, &flags, &mode, &gid); if (err < 0) { goto out_nofid; trace_v9fs_lcreate(pdu->tag, pdu->id, dfid, flags, mode, gid); if (name_is_illegal(name.data)) { err = -ENOENT; goto out_nofid; if (!strcmp(".", name.data) || !strcmp("..", name.data)) { err = -EEXIST; goto out_nofid; fidp = get_fid(pdu, dfid); if (fidp == NULL) { err = -ENOENT; goto out_nofid; flags = get_dotl_openflags(pdu->s, flags); err = v9fs_co_open2(pdu, fidp, &name, gid, flags | O_CREAT, mode, &stbuf); if (err < 0) { fidp->fid_type = P9_FID_FILE; fidp->open_flags = flags; if (flags & O_EXCL) { /* * We let the host file system do O_EXCL check * We should not reclaim such fd */ fidp->flags |= FID_NON_RECLAIMABLE; iounit = get_iounit(pdu, &fidp->path); stat_to_qid(&stbuf, &qid); err = pdu_marshal(pdu, offset, "Qd", &qid, iounit); if (err < 0) { err += offset; trace_v9fs_lcreate_return(pdu->tag, pdu->id, qid.type, qid.version, qid.path, iounit); out: put_fid(pdu, fidp); out_nofid: pdu_complete(pdu, err); v9fs_string_free(&name);


static inline int array_ensure_allocated(array_t* array, int index) { if((index + 1) * array->item_size > array->size) { int new_size = (index + 32) * array->item_size; array->pointer = g_realloc(array->pointer, new_size); if (!array->pointer) return -1; array->size = new_size; array->next = index + 1; } return 0; }


static inline TranslationBlock *tb_find_fast(void) { TranslationBlock *tb; target_ulong cs_base, pc; uint64_t flags; /* we record a subset of the CPU state. It will always be the same before a given translated block is executed. */ #if defined(TARGET_I386) flags = env->hflags; flags |= (env->eflags & (IOPL_MASK | TF_MASK | VM_MASK)); flags |= env->intercept; cs_base = env->segs[R_CS].base; pc = cs_base + env->eip; #elif defined(TARGET_ARM) flags = env->thumb | (env->vfp.vec_len << 1) | (env->vfp.vec_stride << 4); if ((env->uncached_cpsr & CPSR_M) != ARM_CPU_MODE_USR) flags |= (1 << 6); if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) flags |= (1 << 7); flags |= (env->condexec_bits << 8); cs_base = 0; pc = env->regs[15]; #elif defined(TARGET_SPARC) #ifdef TARGET_SPARC64 // Combined FPU enable bits . PRIV . DMMU enabled . IMMU enabled flags = (((env->pstate & PS_PEF) >> 1) | ((env->fprs & FPRS_FEF) << 2)) | (env->pstate & PS_PRIV) | ((env->lsu & (DMMU_E | IMMU_E)) >> 2); #else // FPU enable . Supervisor flags = (env->psref << 4) | env->psrs; #endif cs_base = env->npc; pc = env->pc; #elif defined(TARGET_PPC) flags = env->hflags; cs_base = 0; pc = env->nip; #elif defined(TARGET_MIPS) flags = env->hflags & (MIPS_HFLAG_TMASK | MIPS_HFLAG_BMASK); cs_base = 0; pc = env->PC[env->current_tc]; #elif defined(TARGET_M68K) flags = (env->fpcr & M68K_FPCR_PREC) /* Bit 6 */ | (env->sr & SR_S) /* Bit 13 */ | ((env->macsr >> 4) & 0xf); /* Bits 0-3 */ cs_base = 0; pc = env->pc; #elif defined(TARGET_SH4) flags = env->flags; cs_base = 0; pc = env->pc; #elif defined(TARGET_ALPHA) flags = env->ps; cs_base = 0; pc = env->pc; #elif defined(TARGET_CRIS) flags = env->pregs[PR_CCS] & (U_FLAG | X_FLAG); cs_base = 0; pc = env->pc; #else #error unsupported CPU #endif tb = env->tb_jmp_cache[tb_jmp_cache_hash_func(pc)]; if (__builtin_expect(!tb || tb->pc != pc || tb->cs_base != cs_base || tb->flags != flags, 0)) { tb = tb_find_slow(pc, cs_base, flags); /* Note: we do it here to avoid a gcc bug on Mac OS X when doing it in tb_find_slow */ if (tb_invalidated_flag) { /* as some TB could have been invalidated because of memory exceptions while generating the code, we must recompute the hash index here */ T0 = 0; } } return tb; }


static void arm_cpu_reset(CPUState *s) { ARMCPU *cpu = ARM_CPU(s); ARMCPUClass *acc = ARM_CPU_GET_CLASS(cpu); CPUARMState *env = &cpu->env; acc->parent_reset(s); memset(env, 0, offsetof(CPUARMState, end_reset_fields)); g_hash_table_foreach(cpu->cp_regs, cp_reg_reset, cpu); g_hash_table_foreach(cpu->cp_regs, cp_reg_check_reset, cpu); env->vfp.xregs[ARM_VFP_FPSID] = cpu->reset_fpsid; env->vfp.xregs[ARM_VFP_MVFR0] = cpu->mvfr0; env->vfp.xregs[ARM_VFP_MVFR1] = cpu->mvfr1; env->vfp.xregs[ARM_VFP_MVFR2] = cpu->mvfr2; cpu->powered_off = cpu->start_powered_off; s->halted = cpu->start_powered_off; if (arm_feature(env, ARM_FEATURE_IWMMXT)) { env->iwmmxt.cregs[ARM_IWMMXT_wCID] = 0x69051000 | 'Q'; } if (arm_feature(env, ARM_FEATURE_AARCH64)) { /* 64 bit CPUs always start in 64 bit mode */ env->aarch64 = 1; #if defined(CONFIG_USER_ONLY) env->pstate = PSTATE_MODE_EL0t; /* Userspace expects access to DC ZVA, CTL_EL0 and the cache ops */ env->cp15.sctlr_el[1] |= SCTLR_UCT | SCTLR_UCI | SCTLR_DZE; /* and to the FP/Neon instructions */ env->cp15.cpacr_el1 = deposit64(env->cp15.cpacr_el1, 20, 2, 3); #else /* Reset into the highest available EL */ if (arm_feature(env, ARM_FEATURE_EL3)) { env->pstate = PSTATE_MODE_EL3h; } else if (arm_feature(env, ARM_FEATURE_EL2)) { env->pstate = PSTATE_MODE_EL2h; } else { env->pstate = PSTATE_MODE_EL1h; } env->pc = cpu->rvbar; #endif } else { #if defined(CONFIG_USER_ONLY) /* Userspace expects access to cp10 and cp11 for FP/Neon */ env->cp15.cpacr_el1 = deposit64(env->cp15.cpacr_el1, 20, 4, 0xf); #endif } #if defined(CONFIG_USER_ONLY) env->uncached_cpsr = ARM_CPU_MODE_USR; /* For user mode we must enable access to coprocessors */ env->vfp.xregs[ARM_VFP_FPEXC] = 1 << 30; if (arm_feature(env, ARM_FEATURE_IWMMXT)) { env->cp15.c15_cpar = 3; } else if (arm_feature(env, ARM_FEATURE_XSCALE)) { env->cp15.c15_cpar = 1; } #else /* SVC mode with interrupts disabled. */ env->uncached_cpsr = ARM_CPU_MODE_SVC; env->daif = PSTATE_D | PSTATE_A | PSTATE_I | PSTATE_F; if (arm_feature(env, ARM_FEATURE_M)) { uint32_t initial_msp; /* Loaded from 0x0 */ uint32_t initial_pc; /* Loaded from 0x4 */ uint8_t *rom; /* For M profile we store FAULTMASK and PRIMASK in the * PSTATE F and I bits; these are both clear at reset. */ env->daif &= ~(PSTATE_I | PSTATE_F); /* The reset value of this bit is IMPDEF, but ARM recommends * that it resets to 1, so QEMU always does that rather than making * it dependent on CPU model. */ env->v7m.ccr = R_V7M_CCR_STKALIGN_MASK; /* Unlike A/R profile, M profile defines the reset LR value */ env->regs[14] = 0xffffffff; /* Load the initial SP and PC from the vector table at address 0 */ rom = rom_ptr(0); if (rom) { /* Address zero is covered by ROM which hasn't yet been * copied into physical memory. */ initial_msp = ldl_p(rom); initial_pc = ldl_p(rom + 4); } else { /* Address zero not covered by a ROM blob, or the ROM blob * is in non-modifiable memory and this is a second reset after * it got copied into memory. In the latter case, rom_ptr * will return a NULL pointer and we should use ldl_phys instead. */ initial_msp = ldl_phys(s->as, 0); initial_pc = ldl_phys(s->as, 4); } env->regs[13] = initial_msp & 0xFFFFFFFC; env->regs[15] = initial_pc & ~1; env->thumb = initial_pc & 1; } /* AArch32 has a hard highvec setting of 0xFFFF0000. If we are currently * executing as AArch32 then check if highvecs are enabled and * adjust the PC accordingly. */ if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) { env->regs[15] = 0xFFFF0000; } env->vfp.xregs[ARM_VFP_FPEXC] = 0; #endif set_flush_to_zero(1, &env->vfp.standard_fp_status); set_flush_inputs_to_zero(1, &env->vfp.standard_fp_status); set_default_nan_mode(1, &env->vfp.standard_fp_status); set_float_detect_tininess(float_tininess_before_rounding, &env->vfp.fp_status); set_float_detect_tininess(float_tininess_before_rounding, &env->vfp.standard_fp_status); #ifndef CONFIG_USER_ONLY if (kvm_enabled()) { kvm_arm_reset_vcpu(cpu); } #endif hw_breakpoint_update_all(cpu); hw_watchpoint_update_all(cpu); }


void tcg_add_target_add_op_defs(const TCGTargetOpDef *tdefs) { TCGOpcode op; TCGOpDef *def; const char *ct_str; int i, nb_args; for(;;) { if (tdefs->op == (TCGOpcode)-1) break; op = tdefs->op; assert(op >= 0 && op < NB_OPS); def = &tcg_op_defs[op]; #if defined(CONFIG_DEBUG_TCG) /* Duplicate entry in op definitions? */ assert(!def->used); def->used = 1; #endif nb_args = def->nb_iargs + def->nb_oargs; for(i = 0; i < nb_args; i++) { ct_str = tdefs->args_ct_str[i]; /* Incomplete TCGTargetOpDef entry? */ assert(ct_str != NULL); tcg_regset_clear(def->args_ct[i].u.regs); def->args_ct[i].ct = 0; if (ct_str[0] >= '0' && ct_str[0] <= '9') { int oarg; oarg = ct_str[0] - '0'; assert(oarg < def->nb_oargs); assert(def->args_ct[oarg].ct & TCG_CT_REG); /* TCG_CT_ALIAS is for the output arguments. The input argument is tagged with TCG_CT_IALIAS. */ def->args_ct[i] = def->args_ct[oarg]; def->args_ct[oarg].ct = TCG_CT_ALIAS; def->args_ct[oarg].alias_index = i; def->args_ct[i].ct |= TCG_CT_IALIAS; def->args_ct[i].alias_index = oarg; } else { for(;;) { if (*ct_str == '\0') break; switch(*ct_str) { case 'i': def->args_ct[i].ct |= TCG_CT_CONST; ct_str++; break; default: if (target_parse_constraint(&def->args_ct[i], &ct_str) < 0) { fprintf(stderr, "Invalid constraint '%s' for arg %d of operation '%s'\n", ct_str, i, def->name); exit(1); } } } } } /* TCGTargetOpDef entry with too much information? */ assert(i == TCG_MAX_OP_ARGS || tdefs->args_ct_str[i] == NULL); /* sort the constraints (XXX: this is just an heuristic) */ sort_constraints(def, 0, def->nb_oargs); sort_constraints(def, def->nb_oargs, def->nb_iargs); #if 0 { int i; printf("%s: sorted=", def->name); for(i = 0; i < def->nb_oargs + def->nb_iargs; i++) printf(" %d", def->sorted_args[i]); printf("\n"); } #endif tdefs++; } #if defined(CONFIG_DEBUG_TCG) i = 0; for (op = 0; op < ARRAY_SIZE(tcg_op_defs); op++) { if (op < INDEX_op_call || op == INDEX_op_debug_insn_start) { /* Wrong entry in op definitions? */ if (tcg_op_defs[op].used) { fprintf(stderr, "Invalid op definition for %s\n", tcg_op_defs[op].name); i = 1; } } else { /* Missing entry in op definitions? */ if (!tcg_op_defs[op].used) { fprintf(stderr, "Missing op definition for %s\n", tcg_op_defs[op].name); i = 1; } } } if (i == 1) { tcg_abort(); } #endif }


static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags) { AVStream *st = s->streams[stream_index]; int64_t seconds; if (!s->bit_rate) return AVERROR_INVALIDDATA; if (sample_time < 0) sample_time = 0; seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den); avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET); ff_update_cur_dts(s, st, sample_time); return 0; }


static inline int _find_pte (mmu_ctx_t *ctx, int is_64b, int h, int rw) { target_ulong base, pte0, pte1; int i, good = -1; int ret, r; ret = -1; /* No entry found */ base = ctx->pg_addr[h]; for (i = 0; i < 8; i++) { #if defined(TARGET_PPC64) if (is_64b) { pte0 = ldq_phys(base + (i * 16)); pte1 = ldq_phys(base + (i * 16) + 8); r = pte64_check(ctx, pte0, pte1, h, rw); } else #endif { pte0 = ldl_phys(base + (i * 8)); pte1 = ldl_phys(base + (i * 8) + 4); r = pte32_check(ctx, pte0, pte1, h, rw); } #if defined (DEBUG_MMU) if (loglevel != 0) { fprintf(logfile, "Load pte from 0x" ADDRX " => 0x" ADDRX " 0x" ADDRX " %d %d %d 0x" ADDRX "\n", base + (i * 8), pte0, pte1, (int)(pte0 >> 31), h, (int)((pte0 >> 6) & 1), ctx->ptem); } #endif switch (r) { case -3: /* PTE inconsistency */ return -1; case -2: /* Access violation */ ret = -2; good = i; break; case -1: default: /* No PTE match */ break; case 0: /* access granted */ /* XXX: we should go on looping to check all PTEs consistency * but if we can speed-up the whole thing as the * result would be undefined if PTEs are not consistent. */ ret = 0; good = i; goto done; } } if (good != -1) { done: #if defined (DEBUG_MMU) if (loglevel != 0) { fprintf(logfile, "found PTE at addr 0x" PADDRX " prot=0x%01x " "ret=%d\n", ctx->raddr, ctx->prot, ret); } #endif /* Update page flags */ pte1 = ctx->raddr; if (pte_update_flags(ctx, &pte1, ret, rw) == 1) { #if defined(TARGET_PPC64) if (is_64b) { stq_phys_notdirty(base + (good * 16) + 8, pte1); } else #endif { stl_phys_notdirty(base + (good * 8) + 4, pte1); } } } return ret; }


static int nbd_send_reply(int csock, struct nbd_reply *reply) { uint8_t buf[4 + 4 + 8]; /* Reply [ 0 .. 3] magic (NBD_REPLY_MAGIC) [ 4 .. 7] error (0 == no error) [ 7 .. 15] handle */ cpu_to_be32w((uint32_t*)buf, NBD_REPLY_MAGIC); cpu_to_be32w((uint32_t*)(buf + 4), reply->error); cpu_to_be64w((uint64_t*)(buf + 8), reply->handle); TRACE("Sending response to client"); if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) { LOG("writing to socket failed"); errno = EINVAL; return -1; } return 0; }


static int encode_apng(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *pict, int *got_packet) { PNGEncContext *s = avctx->priv_data; int ret; int enc_row_size; size_t max_packet_size; APNGFctlChunk fctl_chunk; if (pict && avctx->codec_id == AV_CODEC_ID_APNG && s->color_type == PNG_COLOR_TYPE_PALETTE) { uint32_t checksum = ~av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), ~0U, pict->data[1], 256 * sizeof(uint32_t)); if (avctx->frame_number == 0) { s->palette_checksum = checksum; } else if (checksum != s->palette_checksum) { av_log(avctx, AV_LOG_ERROR, "Input contains more than one unique palette. APNG does not support multiple palettes.\n"); return -1; } } enc_row_size = deflateBound(&s->zstream, (avctx->width * s->bits_per_pixel + 7) >> 3); max_packet_size = AV_INPUT_BUFFER_MIN_SIZE + // headers avctx->height * ( enc_row_size + (4 + 12) * (((int64_t)enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) // fdAT * ceil(enc_row_size / IOBUF_SIZE) ); if (max_packet_size > INT_MAX) return AVERROR(ENOMEM); if (avctx->frame_number == 0) { s->bytestream = avctx->extradata = av_malloc(FF_MIN_BUFFER_SIZE); if (!avctx->extradata) return AVERROR(ENOMEM); ret = encode_headers(avctx, pict); if (ret < 0) return ret; avctx->extradata_size = s->bytestream - avctx->extradata; s->last_frame_packet = av_malloc(max_packet_size); if (!s->last_frame_packet) return AVERROR(ENOMEM); } else if (s->last_frame) { ret = ff_alloc_packet2(avctx, pkt, max_packet_size, 0); if (ret < 0) return ret; memcpy(pkt->data, s->last_frame_packet, s->last_frame_packet_size); pkt->size = s->last_frame_packet_size; pkt->pts = pkt->dts = s->last_frame->pts; } if (pict) { s->bytestream_start = s->bytestream = s->last_frame_packet; s->bytestream_end = s->bytestream + max_packet_size; // We're encoding the frame first, so we have to do a bit of shuffling around // to have the image data write to the correct place in the buffer fctl_chunk.sequence_number = s->sequence_number; ++s->sequence_number; s->bytestream += 26 + 12; ret = apng_encode_frame(avctx, pict, &fctl_chunk, &s->last_frame_fctl); if (ret < 0) return ret; fctl_chunk.delay_num = 0; // delay filled in during muxing fctl_chunk.delay_den = 0; } else { s->last_frame_fctl.dispose_op = APNG_DISPOSE_OP_NONE; } if (s->last_frame) { uint8_t* last_fctl_chunk_start = pkt->data; uint8_t buf[26]; AV_WB32(buf + 0, s->last_frame_fctl.sequence_number); AV_WB32(buf + 4, s->last_frame_fctl.width); AV_WB32(buf + 8, s->last_frame_fctl.height); AV_WB32(buf + 12, s->last_frame_fctl.x_offset); AV_WB32(buf + 16, s->last_frame_fctl.y_offset); AV_WB16(buf + 20, s->last_frame_fctl.delay_num); AV_WB16(buf + 22, s->last_frame_fctl.delay_den); buf[24] = s->last_frame_fctl.dispose_op; buf[25] = s->last_frame_fctl.blend_op; png_write_chunk(&last_fctl_chunk_start, MKTAG('f', 'c', 'T', 'L'), buf, 26); *got_packet = 1; } if (pict) { if (!s->last_frame) { s->last_frame = av_frame_alloc(); if (!s->last_frame) return AVERROR(ENOMEM); } else if (s->last_frame_fctl.dispose_op != APNG_DISPOSE_OP_PREVIOUS) { if (!s->prev_frame) { s->prev_frame = av_frame_alloc(); if (!s->prev_frame) return AVERROR(ENOMEM); s->prev_frame->format = pict->format; s->prev_frame->width = pict->width; s->prev_frame->height = pict->height; if ((ret = av_frame_get_buffer(s->prev_frame, 32)) < 0) return ret; } // Do disposal, but not blending memcpy(s->prev_frame->data[0], s->last_frame->data[0], s->last_frame->linesize[0] * s->last_frame->height); if (s->last_frame_fctl.dispose_op == APNG_DISPOSE_OP_BACKGROUND) { uint32_t y; uint8_t bpp = (s->bits_per_pixel + 7) >> 3; for (y = s->last_frame_fctl.y_offset; y < s->last_frame_fctl.y_offset + s->last_frame_fctl.height; ++y) { size_t row_start = s->last_frame->linesize[0] * y + bpp * s->last_frame_fctl.x_offset; memset(s->prev_frame->data[0] + row_start, 0, bpp * s->last_frame_fctl.width); } } } av_frame_unref(s->last_frame); ret = av_frame_ref(s->last_frame, (AVFrame*)pict); if (ret < 0) return ret; s->last_frame_fctl = fctl_chunk; s->last_frame_packet_size = s->bytestream - s->bytestream_start; } else { av_frame_free(&s->last_frame); } return 0; }


static int tpm_passthrough_open_sysfs_cancel(TPMPassthruState *tpm_pt) { int fd = -1; char *dev; char path[PATH_MAX]; if (tpm_pt->options->cancel_path) { fd = qemu_open(tpm_pt->options->cancel_path, O_WRONLY); if (fd < 0) { error_report("Could not open TPM cancel path : %s", strerror(errno)); } return fd; } dev = strrchr(tpm_pt->tpm_dev, '/'); if (dev) { dev++; if (snprintf(path, sizeof(path), "/sys/class/misc/%s/device/cancel", dev) < sizeof(path)) { fd = qemu_open(path, O_WRONLY); if (fd >= 0) { tpm_pt->options->cancel_path = g_strdup(path); } else { error_report("tpm_passthrough: Could not open TPM cancel " "path %s : %s", path, strerror(errno)); } } } else { error_report("tpm_passthrough: Bad TPM device path %s", tpm_pt->tpm_dev); } return fd; }


int ff_combine_frame(ParseContext *pc, int next, const uint8_t **buf, int *buf_size) { if(pc->overread){ av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index); av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1], (*buf)[2], (*buf)[3]); } /* Copy overread bytes from last frame into buffer. */ for(; pc->overread>0; pc->overread--){ pc->buffer[pc->index++]= pc->buffer[pc->overread_index++]; } /* flush remaining if EOF */ if(!*buf_size && next == END_NOT_FOUND){ next= 0; } pc->last_index= pc->index; /* copy into buffer end return */ if(next == END_NOT_FOUND){ void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, (*buf_size) + pc->index + FF_INPUT_BUFFER_PADDING_SIZE); if(!new_buffer) return AVERROR(ENOMEM); pc->buffer = new_buffer; memcpy(&pc->buffer[pc->index], *buf, *buf_size); pc->index += *buf_size; return -1; } *buf_size= pc->overread_index= pc->index + next; /* append to buffer */ if(pc->index){ void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, next + pc->index + FF_INPUT_BUFFER_PADDING_SIZE); if(!new_buffer) return AVERROR(ENOMEM); pc->buffer = new_buffer; memcpy(&pc->buffer[pc->index], *buf, next + FF_INPUT_BUFFER_PADDING_SIZE ); pc->index = 0; *buf= pc->buffer; } /* store overread bytes */ for(;next < 0; next++){ pc->state = (pc->state<<8) | pc->buffer[pc->last_index + next]; pc->state64 = (pc->state64<<8) | pc->buffer[pc->last_index + next]; pc->overread++; } if(pc->overread){ av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index); av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]); } return 0; }


static void qtrle_decode_1bpp(QtrleContext *s, int stream_ptr, int row_ptr, int lines_to_change) { int rle_code; int pixel_ptr = 0; int row_inc = s->frame.linesize[0]; unsigned char pi0, pi1; /* 2 8-pixel values */ unsigned char *rgb = s->frame.data[0]; int pixel_limit = s->frame.linesize[0] * s->avctx->height; int skip; while (lines_to_change) { CHECK_STREAM_PTR(2); skip = s->buf[stream_ptr++]; rle_code = (signed char)s->buf[stream_ptr++]; if (rle_code == 0) break; if(skip & 0x80) { lines_to_change--; row_ptr += row_inc; pixel_ptr = row_ptr + 2 * (skip & 0x7f); } else pixel_ptr += 2 * skip; CHECK_PIXEL_PTR(0); /* make sure pixel_ptr is positive */ if (rle_code < 0) { /* decode the run length code */ rle_code = -rle_code; /* get the next 2 bytes from the stream, treat them as groups * of 8 pixels, and output them rle_code times */ CHECK_STREAM_PTR(2); pi0 = s->buf[stream_ptr++]; pi1 = s->buf[stream_ptr++]; CHECK_PIXEL_PTR(rle_code * 2); while (rle_code--) { rgb[pixel_ptr++] = pi0; rgb[pixel_ptr++] = pi1; } } else { /* copy the same pixel directly to output 2 times */ rle_code *= 2; CHECK_STREAM_PTR(rle_code); CHECK_PIXEL_PTR(rle_code); while (rle_code--) rgb[pixel_ptr++] = s->buf[stream_ptr++]; } } }


static void lm32_cpu_initfn(Object *obj) { CPUState *cs = CPU(obj); LM32CPU *cpu = LM32_CPU(obj); CPULM32State *env = &cpu->env; static bool tcg_initialized; cs->env_ptr = env; cpu_exec_init(cs, &error_abort); env->flags = 0; if (tcg_enabled() && !tcg_initialized) { tcg_initialized = true; lm32_translate_init(); } }


static int find_and_check_chardev(CharDriverState **chr, char *chr_name, Error **errp) { CompareChardevProps props; *chr = qemu_chr_find(chr_name); if (*chr == NULL) { error_setg(errp, "Device '%s' not found", chr_name); return 1; } memset(&props, 0, sizeof(props)); if (qemu_opt_foreach((*chr)->opts, compare_chardev_opts, &props, errp)) { return 1; } if (!props.is_socket) { error_setg(errp, "chardev \"%s\" is not a tcp socket", chr_name); return 1; } return 0; }


static void set_bit(Object *obj, Visitor *v, void *opaque, const char *name, Error **errp) { DeviceState *dev = DEVICE(obj); Property *prop = opaque; Error *local_err = NULL; bool value; if (dev->realized) { qdev_prop_set_after_realize(dev, name, errp); return; } visit_type_bool(v, &value, name, &local_err); if (local_err) { error_propagate(errp, local_err); return; } bit_prop_set(dev, prop, value); }


static inline void gen_goto_tb(DisasContext *s, int tb_num, target_ulong eip) { target_ulong pc = s->cs_base + eip; if (use_goto_tb(s, pc)) { /* jump to same page: we can use a direct jump */ tcg_gen_goto_tb(tb_num); gen_jmp_im(eip); tcg_gen_exit_tb((uintptr_t)s->tb + tb_num); } else { /* jump to another page: currently not optimized */ gen_jmp_im(eip); gen_eob(s); } }


static const char *target_parse_constraint(TCGArgConstraint *ct, const char *ct_str, TCGType type) { switch (*ct_str++) { case 'r': /* all registers */ ct->ct |= TCG_CT_REG; tcg_regset_set32(ct->u.regs, 0, 0xffff); break; case 'L': /* qemu_ld/st constraint */ ct->ct |= TCG_CT_REG; tcg_regset_set32(ct->u.regs, 0, 0xffff); tcg_regset_reset_reg (ct->u.regs, TCG_REG_R2); tcg_regset_reset_reg (ct->u.regs, TCG_REG_R3); tcg_regset_reset_reg (ct->u.regs, TCG_REG_R4); break; case 'a': /* force R2 for division */ ct->ct |= TCG_CT_REG; tcg_regset_clear(ct->u.regs); tcg_regset_set_reg(ct->u.regs, TCG_REG_R2); break; case 'b': /* force R3 for division */ ct->ct |= TCG_CT_REG; tcg_regset_clear(ct->u.regs); tcg_regset_set_reg(ct->u.regs, TCG_REG_R3); break; case 'A': ct->ct |= TCG_CT_CONST_S33; break; case 'I': ct->ct |= TCG_CT_CONST_S16; break; case 'J': ct->ct |= TCG_CT_CONST_S32; break; case 'O': ct->ct |= TCG_CT_CONST_ORI; break; case 'X': ct->ct |= TCG_CT_CONST_XORI; break; case 'C': /* ??? We have no insight here into whether the comparison is signed or unsigned. The COMPARE IMMEDIATE insn uses a 32-bit signed immediate, and the COMPARE LOGICAL IMMEDIATE insn uses a 32-bit unsigned immediate. If we were to use the (semi) obvious "val == (int32_t)val" we would be enabling unsigned comparisons vs very large numbers. The only solution is to take the intersection of the ranges. */ /* ??? Another possible solution is to simply lie and allow all constants here and force the out-of-range values into a temp register in tgen_cmp when we have knowledge of the actual comparison code in use. */ ct->ct |= TCG_CT_CONST_U31; break; case 'Z': ct->ct |= TCG_CT_CONST_ZERO; break; default: return NULL; } return ct_str; }


static uint64_t megasas_port_read(void *opaque, target_phys_addr_t addr, unsigned size) { return megasas_mmio_read(opaque, addr & 0xff, size); }


void arm_debug_excp_handler(CPUState *cs) { /* Called by core code when a watchpoint or breakpoint fires; * need to check which one and raise the appropriate exception. */ ARMCPU *cpu = ARM_CPU(cs); CPUARMState *env = &cpu->env; CPUWatchpoint *wp_hit = cs->watchpoint_hit; if (wp_hit) { if (wp_hit->flags & BP_CPU) { cs->watchpoint_hit = NULL; if (check_watchpoints(cpu)) { bool wnr = (wp_hit->flags & BP_WATCHPOINT_HIT_WRITE) != 0; bool same_el = arm_debug_target_el(env) == arm_current_el(env); if (extended_addresses_enabled(env)) { env->exception.fsr = (1 << 9) | 0x22; } else { env->exception.fsr = 0x2; } env->exception.vaddress = wp_hit->hitaddr; raise_exception(env, EXCP_DATA_ABORT, syn_watchpoint(same_el, 0, wnr), arm_debug_target_el(env)); } else { cpu_resume_from_signal(cs, NULL); } } } else { uint64_t pc = is_a64(env) ? env->pc : env->regs[15]; bool same_el = (arm_debug_target_el(env) == arm_current_el(env)); /* (1) GDB breakpoints should be handled first. * (2) Do not raise a CPU exception if no CPU breakpoint has fired, * since singlestep is also done by generating a debug internal * exception. */ if (cpu_breakpoint_test(cs, pc, BP_GDB) || !cpu_breakpoint_test(cs, pc, BP_CPU)) { return; } if (extended_addresses_enabled(env)) { env->exception.fsr = (1 << 9) | 0x22; } else { env->exception.fsr = 0x2; } /* FAR is UNKNOWN, so doesn't need setting */ raise_exception(env, EXCP_PREFETCH_ABORT, syn_breakpoint(same_el), arm_debug_target_el(env)); } }


int load_elf_as(const char *filename, uint64_t (*translate_fn)(void *, uint64_t), void *translate_opaque, uint64_t *pentry, uint64_t *lowaddr, uint64_t *highaddr, int big_endian, int elf_machine, int clear_lsb, int data_swab, AddressSpace *as) { int fd, data_order, target_data_order, must_swab, ret = ELF_LOAD_FAILED; uint8_t e_ident[EI_NIDENT]; fd = open(filename, O_RDONLY | O_BINARY); if (fd < 0) { perror(filename); return -1; } if (read(fd, e_ident, sizeof(e_ident)) != sizeof(e_ident)) goto fail; if (e_ident[0] != ELFMAG0 || e_ident[1] != ELFMAG1 || e_ident[2] != ELFMAG2 || e_ident[3] != ELFMAG3) { ret = ELF_LOAD_NOT_ELF; goto fail; } #ifdef HOST_WORDS_BIGENDIAN data_order = ELFDATA2MSB; #else data_order = ELFDATA2LSB; #endif must_swab = data_order != e_ident[EI_DATA]; if (big_endian) { target_data_order = ELFDATA2MSB; } else { target_data_order = ELFDATA2LSB; } if (target_data_order != e_ident[EI_DATA]) { ret = ELF_LOAD_WRONG_ENDIAN; goto fail; } lseek(fd, 0, SEEK_SET); if (e_ident[EI_CLASS] == ELFCLASS64) { ret = load_elf64(filename, fd, translate_fn, translate_opaque, must_swab, pentry, lowaddr, highaddr, elf_machine, clear_lsb, data_swab, as); } else { ret = load_elf32(filename, fd, translate_fn, translate_opaque, must_swab, pentry, lowaddr, highaddr, elf_machine, clear_lsb, data_swab, as); } fail: close(fd); return ret; }


static int vhost_net_start_one(struct vhost_net *net, VirtIODevice *dev, int vq_index) { struct vhost_vring_file file = { }; int r; if (net->dev.started) { return 0; } net->dev.nvqs = 2; net->dev.vqs = net->vqs; net->dev.vq_index = vq_index; r = vhost_dev_enable_notifiers(&net->dev, dev); if (r < 0) { goto fail_notifiers; } r = vhost_dev_start(&net->dev, dev); if (r < 0) { goto fail_start; } if (net->nc->info->poll) { net->nc->info->poll(net->nc, false); } if (net->nc->info->type == NET_CLIENT_OPTIONS_KIND_TAP) { qemu_set_fd_handler(net->backend, NULL, NULL, NULL); file.fd = net->backend; for (file.index = 0; file.index < net->dev.nvqs; ++file.index) { const VhostOps *vhost_ops = net->dev.vhost_ops; r = vhost_ops->vhost_call(&net->dev, VHOST_NET_SET_BACKEND, &file); if (r < 0) { r = -errno; goto fail; } } } return 0; fail: file.fd = -1; if (net->nc->info->type == NET_CLIENT_OPTIONS_KIND_TAP) { while (file.index-- > 0) { const VhostOps *vhost_ops = net->dev.vhost_ops; int r = vhost_ops->vhost_call(&net->dev, VHOST_NET_SET_BACKEND, &file); assert(r >= 0); } } if (net->nc->info->poll) { net->nc->info->poll(net->nc, true); } vhost_dev_stop(&net->dev, dev); fail_start: vhost_dev_disable_notifiers(&net->dev, dev); fail_notifiers: return r; }


mst_fpga_readb(void *opaque, target_phys_addr_t addr, unsigned size) { mst_irq_state *s = (mst_irq_state *) opaque; switch (addr) { case MST_LEDDAT1: return s->leddat1; case MST_LEDDAT2: return s->leddat2; case MST_LEDCTRL: return s->ledctrl; case MST_GPSWR: return s->gpswr; case MST_MSCWR1: return s->mscwr1; case MST_MSCWR2: return s->mscwr2; case MST_MSCWR3: return s->mscwr3; case MST_MSCRD: return s->mscrd; case MST_INTMSKENA: return s->intmskena; case MST_INTSETCLR: return s->intsetclr; case MST_PCMCIA0: return s->pcmcia0; case MST_PCMCIA1: return s->pcmcia1; default: printf("Mainstone - mst_fpga_readb: Bad register offset " "0x" TARGET_FMT_plx "\n", addr); } return 0; }


int ppcmas_tlb_check(CPUState *env, ppcmas_tlb_t *tlb, target_phys_addr_t *raddrp, target_ulong address, uint32_t pid) { target_ulong mask; uint32_t tlb_pid; /* Check valid flag */ if (!(tlb->mas1 & MAS1_VALID)) { return -1; } mask = ~(booke206_tlb_to_page_size(env, tlb) - 1); LOG_SWTLB("%s: TLB ADDR=0x" TARGET_FMT_lx " PID=0x%x MAS1=0x%x MAS2=0x%" PRIx64 " mask=0x" TARGET_FMT_lx " MAS7_3=0x%" PRIx64 " MAS8=%x\n", __func__, address, pid, tlb->mas1, tlb->mas2, mask, tlb->mas7_3, tlb->mas8); /* Check PID */ tlb_pid = (tlb->mas1 & MAS1_TID_MASK) >> MAS1_TID_SHIFT; if (tlb_pid != 0 && tlb_pid != pid) { return -1; } /* Check effective address */ if ((address & mask) != (tlb->mas2 & MAS2_EPN_MASK)) { return -1; } *raddrp = (tlb->mas7_3 & mask) | (address & ~mask); return 0; }


static int libopenjpeg_encode_frame(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *frame, int *got_packet) { LibOpenJPEGContext *ctx = avctx->priv_data; opj_cinfo_t *compress = ctx->compress; opj_image_t *image = ctx->image; opj_cio_t *stream = ctx->stream; int cpyresult = 0; int ret, len; AVFrame *gbrframe; switch (avctx->pix_fmt) { case AV_PIX_FMT_RGB24: case AV_PIX_FMT_RGBA: case AV_PIX_FMT_GRAY8A: cpyresult = libopenjpeg_copy_packed8(avctx, frame, image); break; case AV_PIX_FMT_XYZ12: cpyresult = libopenjpeg_copy_packed12(avctx, frame, image); break; case AV_PIX_FMT_RGB48: case AV_PIX_FMT_RGBA64: cpyresult = libopenjpeg_copy_packed16(avctx, frame, image); break; case AV_PIX_FMT_GBR24P: case AV_PIX_FMT_GBRP9: case AV_PIX_FMT_GBRP10: case AV_PIX_FMT_GBRP12: case AV_PIX_FMT_GBRP14: case AV_PIX_FMT_GBRP16: gbrframe = av_frame_alloc(); if (!gbrframe) return AVERROR(ENOMEM); av_frame_ref(gbrframe, frame); gbrframe->data[0] = frame->data[2]; // swap to be rgb gbrframe->data[1] = frame->data[0]; gbrframe->data[2] = frame->data[1]; gbrframe->linesize[0] = frame->linesize[2]; gbrframe->linesize[1] = frame->linesize[0]; gbrframe->linesize[2] = frame->linesize[1]; if (avctx->pix_fmt == AV_PIX_FMT_GBR24P) { cpyresult = libopenjpeg_copy_unpacked8(avctx, gbrframe, image); } else { cpyresult = libopenjpeg_copy_unpacked16(avctx, gbrframe, image); } av_frame_free(&gbrframe); break; case AV_PIX_FMT_GRAY8: case AV_PIX_FMT_YUV410P: case AV_PIX_FMT_YUV411P: case AV_PIX_FMT_YUV420P: case AV_PIX_FMT_YUV422P: case AV_PIX_FMT_YUV440P: case AV_PIX_FMT_YUV444P: case AV_PIX_FMT_YUVA420P: case AV_PIX_FMT_YUVA422P: case AV_PIX_FMT_YUVA444P: cpyresult = libopenjpeg_copy_unpacked8(avctx, frame, image); break; case AV_PIX_FMT_GRAY16: case AV_PIX_FMT_YUV420P9: case AV_PIX_FMT_YUV422P9: case AV_PIX_FMT_YUV444P9: case AV_PIX_FMT_YUVA420P9: case AV_PIX_FMT_YUVA422P9: case AV_PIX_FMT_YUVA444P9: case AV_PIX_FMT_YUV444P10: case AV_PIX_FMT_YUV422P10: case AV_PIX_FMT_YUV420P10: case AV_PIX_FMT_YUVA444P10: case AV_PIX_FMT_YUVA422P10: case AV_PIX_FMT_YUVA420P10: case AV_PIX_FMT_YUV420P12: case AV_PIX_FMT_YUV422P12: case AV_PIX_FMT_YUV444P12: case AV_PIX_FMT_YUV420P14: case AV_PIX_FMT_YUV422P14: case AV_PIX_FMT_YUV444P14: case AV_PIX_FMT_YUV444P16: case AV_PIX_FMT_YUV422P16: case AV_PIX_FMT_YUV420P16: case AV_PIX_FMT_YUVA444P16: case AV_PIX_FMT_YUVA422P16: case AV_PIX_FMT_YUVA420P16: cpyresult = libopenjpeg_copy_unpacked16(avctx, frame, image); break; default: av_log(avctx, AV_LOG_ERROR, "The frame's pixel format '%s' is not supported\n", av_get_pix_fmt_name(avctx->pix_fmt)); return AVERROR(EINVAL); break; } if (!cpyresult) { av_log(avctx, AV_LOG_ERROR, "Could not copy the frame data to the internal image buffer\n"); return -1; } cio_seek(stream, 0); if (!opj_encode(compress, stream, image, NULL)) { av_log(avctx, AV_LOG_ERROR, "Error during the opj encode\n"); return -1; } len = cio_tell(stream); if ((ret = ff_alloc_packet2(avctx, pkt, len)) < 0) { return ret; } memcpy(pkt->data, stream->buffer, len); pkt->flags |= AV_PKT_FLAG_KEY; *got_packet = 1; return 0; }


static VFIOGroup *vfio_get_group(int groupid, AddressSpace *as) { VFIOGroup *group; char path[32]; struct vfio_group_status status = { .argsz = sizeof(status) }; QLIST_FOREACH(group, &group_list, next) { if (group->groupid == groupid) { /* Found it. Now is it already in the right context? */ if (group->container->space->as == as) { return group; } else { error_report("vfio: group %d used in multiple address spaces", group->groupid); return NULL; } } } group = g_malloc0(sizeof(*group)); snprintf(path, sizeof(path), "/dev/vfio/%d", groupid); group->fd = qemu_open(path, O_RDWR); if (group->fd < 0) { error_report("vfio: error opening %s: %m", path); goto free_group_exit; } if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) { error_report("vfio: error getting group status: %m"); goto close_fd_exit; } if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) { error_report("vfio: error, group %d is not viable, please ensure " "all devices within the iommu_group are bound to their " "vfio bus driver.", groupid); goto close_fd_exit; } group->groupid = groupid; QLIST_INIT(&group->device_list); if (vfio_connect_container(group, as)) { error_report("vfio: failed to setup container for group %d", groupid); goto close_fd_exit; } if (QLIST_EMPTY(&group_list)) { qemu_register_reset(vfio_pci_reset_handler, NULL); } QLIST_INSERT_HEAD(&group_list, group, next); vfio_kvm_device_add_group(group); return group; close_fd_exit: close(group->fd); free_group_exit: g_free(group); return NULL; }


int main_loop_init(void) { int ret; qemu_mutex_lock_iothread(); ret = qemu_signal_init(); if (ret) { return ret; } /* Note eventfd must be drained before signalfd handlers run */ ret = qemu_event_init(); if (ret) { return ret; } return 0; }


bool aio_poll(AioContext *ctx, bool blocking) { AioHandler *node; int i; int ret = 0; bool progress; int64_t timeout; int64_t start = 0; /* aio_notify can avoid the expensive event_notifier_set if * everything (file descriptors, bottom halves, timers) will * be re-evaluated before the next blocking poll(). This is * already true when aio_poll is called with blocking == false; * if blocking == true, it is only true after poll() returns, * so disable the optimization now. */ if (blocking) { atomic_add(&ctx->notify_me, 2); } qemu_lockcnt_inc(&ctx->list_lock); if (ctx->poll_max_ns) { start = qemu_clock_get_ns(QEMU_CLOCK_REALTIME); } progress = try_poll_mode(ctx, blocking); if (!progress) { assert(npfd == 0); /* fill pollfds */ if (!aio_epoll_enabled(ctx)) { QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) { if (!node->deleted && node->pfd.events && aio_node_check(ctx, node->is_external)) { add_pollfd(node); } } } timeout = blocking ? aio_compute_timeout(ctx) : 0; /* wait until next event */ if (aio_epoll_check_poll(ctx, pollfds, npfd, timeout)) { AioHandler epoll_handler; epoll_handler.pfd.fd = ctx->epollfd; epoll_handler.pfd.events = G_IO_IN | G_IO_OUT | G_IO_HUP | G_IO_ERR; npfd = 0; add_pollfd(&epoll_handler); ret = aio_epoll(ctx, pollfds, npfd, timeout); } else { ret = qemu_poll_ns(pollfds, npfd, timeout); } } if (blocking) { atomic_sub(&ctx->notify_me, 2); } /* Adjust polling time */ if (ctx->poll_max_ns) { int64_t block_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - start; if (block_ns <= ctx->poll_ns) { /* This is the sweet spot, no adjustment needed */ } else if (block_ns > ctx->poll_max_ns) { /* We'd have to poll for too long, poll less */ int64_t old = ctx->poll_ns; if (ctx->poll_shrink) { ctx->poll_ns /= ctx->poll_shrink; } else { ctx->poll_ns = 0; } trace_poll_shrink(ctx, old, ctx->poll_ns); } else if (ctx->poll_ns < ctx->poll_max_ns && block_ns < ctx->poll_max_ns) { /* There is room to grow, poll longer */ int64_t old = ctx->poll_ns; int64_t grow = ctx->poll_grow; if (grow == 0) { grow = 2; } if (ctx->poll_ns) { ctx->poll_ns *= grow; } else { ctx->poll_ns = 4000; /* start polling at 4 microseconds */ } if (ctx->poll_ns > ctx->poll_max_ns) { ctx->poll_ns = ctx->poll_max_ns; } trace_poll_grow(ctx, old, ctx->poll_ns); } } aio_notify_accept(ctx); /* if we have any readable fds, dispatch event */ if (ret > 0) { for (i = 0; i < npfd; i++) { nodes[i]->pfd.revents = pollfds[i].revents; } } npfd = 0; qemu_lockcnt_dec(&ctx->list_lock); /* Run dispatch even if there were no readable fds to run timers */ if (aio_dispatch(ctx, ret > 0)) { progress = true; } return progress; }


void qio_channel_socket_listen_async(QIOChannelSocket *ioc, SocketAddress *addr, QIOTaskFunc callback, gpointer opaque, GDestroyNotify destroy) { QIOTask *task = qio_task_new( OBJECT(ioc), callback, opaque, destroy); SocketAddress *addrCopy; addrCopy = QAPI_CLONE(SocketAddress, addr); /* socket_listen() blocks in DNS lookups, so we must use a thread */ trace_qio_channel_socket_listen_async(ioc, addr); qio_task_run_in_thread(task, qio_channel_socket_listen_worker, addrCopy, (GDestroyNotify)qapi_free_SocketAddress); }