• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (C) 2024 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import {BigintMath as BIMath} from '../../base/bigint_math';
16import {search, searchEq, searchSegment} from '../../base/binary_search';
17import {assertExists, assertTrue} from '../../base/logging';
18import {Duration, duration, Time, time} from '../../base/time';
19import {
20  drawDoubleHeadedArrow,
21  drawIncompleteSlice,
22  drawTrackHoverTooltip,
23} from '../../base/canvas_utils';
24import {cropText} from '../../base/string_utils';
25import {Color} from '../../base/color';
26import {colorForThread} from '../../components/colorizer';
27import {TrackData} from '../../components/tracks/track_data';
28import {TimelineFetcher} from '../../components/tracks/track_helper';
29import {checkerboardExcept} from '../../components/checkerboard';
30import {Point2D} from '../../base/geom';
31import {TrackRenderer} from '../../public/track';
32import {LONG, NUM} from '../../trace_processor/query_result';
33import {uuidv4Sql} from '../../base/uuid';
34import {TrackMouseEvent, TrackRenderContext} from '../../public/track';
35import {TrackEventDetails} from '../../public/selection';
36import {asSchedSqlId} from '../../components/sql_utils/core_types';
37import {getSched, getSchedWakeupInfo} from '../../components/sql_utils/sched';
38import {SchedSliceDetailsPanel} from './sched_details_tab';
39import {Trace} from '../../public/trace';
40import {exists} from '../../base/utils';
41import {ThreadMap} from '../dev.perfetto.Thread/threads';
42import {SourceDataset} from '../../trace_processor/dataset';
43import {Cpu} from '../../base/multi_machine_trace';
44
45export interface Data extends TrackData {
46  // Slices are stored in a columnar fashion. All fields have the same length.
47  ids: Float64Array;
48  startQs: BigInt64Array;
49  endQs: BigInt64Array;
50  utids: Uint32Array;
51  flags: Uint8Array;
52  lastRowId: number;
53}
54
55const MARGIN_TOP = 3;
56const RECT_HEIGHT = 24;
57const TRACK_HEIGHT = MARGIN_TOP * 2 + RECT_HEIGHT;
58
59const CPU_SLICE_FLAGS_INCOMPLETE = 1;
60const CPU_SLICE_FLAGS_REALTIME = 2;
61
62export class CpuSliceTrack implements TrackRenderer {
63  private mousePos?: Point2D;
64  private utidHoveredInThisTrack?: number;
65  private fetcher = new TimelineFetcher<Data>(this.onBoundsChange.bind(this));
66
67  private lastRowId = -1;
68  private trackUuid = uuidv4Sql();
69
70  readonly rootTableName = 'sched_slice';
71
72  constructor(
73    private readonly trace: Trace,
74    private readonly uri: string,
75    private readonly cpu: Cpu,
76    private readonly threads: ThreadMap,
77  ) {}
78
79  async onCreate() {
80    await this.trace.engine.query(`
81      create virtual table cpu_slice_${this.trackUuid}
82      using __intrinsic_slice_mipmap((
83        select
84          id,
85          ts,
86          iif(dur = -1, lead(ts, 1, trace_end()) over (order by ts) - ts, dur),
87          0 as depth
88        from sched
89        where ucpu = ${this.cpu.ucpu} and
90          not utid in (select utid from thread where is_idle)
91      ));
92    `);
93    const it = await this.trace.engine.query(`
94      select coalesce(max(id), -1) as lastRowId
95      from sched
96      where ucpu = ${this.cpu.ucpu} and
97        not utid in (select utid from thread where is_idle)
98    `);
99    this.lastRowId = it.firstRow({lastRowId: NUM}).lastRowId;
100  }
101
102  getDataset() {
103    return new SourceDataset({
104      // TODO(stevegolton): Once we allow datasets to have more than one filter,
105      // move this where clause to a dataset filter and change this src to
106      // 'sched'.
107      src: `select id, ts, dur, ucpu, utid
108            from sched
109            where not utid in (select utid from thread where is_idle)`,
110      schema: {
111        id: NUM,
112        ts: LONG,
113        dur: LONG,
114        ucpu: NUM,
115        utid: NUM,
116      },
117      filter: {
118        col: 'ucpu',
119        eq: this.cpu.ucpu,
120      },
121    });
122  }
123
124  async onUpdate({
125    visibleWindow,
126    resolution,
127  }: TrackRenderContext): Promise<void> {
128    await this.fetcher.requestData(visibleWindow.toTimeSpan(), resolution);
129  }
130
131  async onBoundsChange(
132    start: time,
133    end: time,
134    resolution: duration,
135  ): Promise<Data> {
136    assertTrue(BIMath.popcount(resolution) === 1, `${resolution} not pow of 2`);
137
138    const queryRes = await this.trace.engine.query(`
139      select
140        (z.ts / ${resolution}) * ${resolution} as tsQ,
141        (((z.ts + z.dur) / ${resolution}) + 1) * ${resolution} as tsEndQ,
142        s.utid,
143        s.id,
144        s.dur = -1 as isIncomplete,
145        ifnull(s.priority < 100, 0) as isRealtime
146      from cpu_slice_${this.trackUuid}(${start}, ${end}, ${resolution}) z
147      cross join sched s using (id)
148    `);
149
150    const numRows = queryRes.numRows();
151    const slices: Data = {
152      start,
153      end,
154      resolution,
155      length: numRows,
156      lastRowId: this.lastRowId,
157      ids: new Float64Array(numRows),
158      startQs: new BigInt64Array(numRows),
159      endQs: new BigInt64Array(numRows),
160      utids: new Uint32Array(numRows),
161      flags: new Uint8Array(numRows),
162    };
163
164    const it = queryRes.iter({
165      tsQ: LONG,
166      tsEndQ: LONG,
167      utid: NUM,
168      id: NUM,
169      isIncomplete: NUM,
170      isRealtime: NUM,
171    });
172    for (let row = 0; it.valid(); it.next(), row++) {
173      slices.startQs[row] = it.tsQ;
174      slices.endQs[row] = it.tsEndQ;
175      slices.utids[row] = it.utid;
176      slices.ids[row] = it.id;
177
178      slices.flags[row] = 0;
179      if (it.isIncomplete) {
180        slices.flags[row] |= CPU_SLICE_FLAGS_INCOMPLETE;
181      }
182      if (it.isRealtime) {
183        slices.flags[row] |= CPU_SLICE_FLAGS_REALTIME;
184      }
185    }
186    return slices;
187  }
188
189  async onDestroy() {
190    await this.trace.engine.tryQuery(
191      `drop table if exists cpu_slice_${this.trackUuid}`,
192    );
193    this.fetcher[Symbol.dispose]();
194  }
195
196  getHeight(): number {
197    return TRACK_HEIGHT;
198  }
199
200  render(trackCtx: TrackRenderContext): void {
201    const {ctx, size, timescale} = trackCtx;
202
203    // TODO: fonts and colors should come from the CSS and not hardcoded here.
204    const data = this.fetcher.data;
205
206    if (data === undefined) return; // Can't possibly draw anything.
207
208    // If the cached trace slices don't fully cover the visible time range,
209    // show a gray rectangle with a "Loading..." label.
210    checkerboardExcept(
211      ctx,
212      this.getHeight(),
213      0,
214      size.width,
215      timescale.timeToPx(data.start),
216      timescale.timeToPx(data.end),
217    );
218
219    this.renderSlices(trackCtx, data);
220  }
221
222  renderSlices(
223    {ctx, timescale, size, visibleWindow}: TrackRenderContext,
224    data: Data,
225  ): void {
226    assertTrue(data.startQs.length === data.endQs.length);
227    assertTrue(data.startQs.length === data.utids.length);
228
229    const visWindowEndPx = size.width;
230
231    ctx.textAlign = 'center';
232    ctx.font = '12px Roboto Condensed';
233    const charWidth = ctx.measureText('dbpqaouk').width / 8;
234
235    const timespan = visibleWindow.toTimeSpan();
236
237    const startTime = timespan.start;
238    const endTime = timespan.end;
239
240    const rawStartIdx = data.endQs.findIndex((end) => end >= startTime);
241    const startIdx = rawStartIdx === -1 ? 0 : rawStartIdx;
242
243    const [, rawEndIdx] = searchSegment(data.startQs, endTime);
244    const endIdx = rawEndIdx === -1 ? data.startQs.length : rawEndIdx;
245
246    for (let i = startIdx; i < endIdx; i++) {
247      const tStart = Time.fromRaw(data.startQs[i]);
248      let tEnd = Time.fromRaw(data.endQs[i]);
249      const utid = data.utids[i];
250
251      // If the last slice is incomplete, it should end with the end of the
252      // window, else it might spill over the window and the end would not be
253      // visible as a zigzag line.
254      if (
255        data.ids[i] === data.lastRowId &&
256        data.flags[i] & CPU_SLICE_FLAGS_INCOMPLETE
257      ) {
258        tEnd = endTime;
259      }
260      const rectStart = timescale.timeToPx(tStart);
261      const rectEnd = timescale.timeToPx(tEnd);
262      const rectWidth = Math.max(1, rectEnd - rectStart);
263
264      const threadInfo = this.threads.get(utid);
265      // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
266      const pid = threadInfo && threadInfo.pid ? threadInfo.pid : -1;
267
268      const isHovering = this.trace.timeline.hoveredUtid !== undefined;
269      const isThreadHovered = this.trace.timeline.hoveredUtid === utid;
270      const isProcessHovered = this.trace.timeline.hoveredPid === pid;
271      const colorScheme = colorForThread(threadInfo);
272      let color: Color;
273      let textColor: Color;
274      if (isHovering && !isThreadHovered) {
275        if (!isProcessHovered) {
276          color = colorScheme.disabled;
277          textColor = colorScheme.textDisabled;
278        } else {
279          color = colorScheme.variant;
280          textColor = colorScheme.textVariant;
281        }
282      } else {
283        color = colorScheme.base;
284        textColor = colorScheme.textBase;
285      }
286      ctx.fillStyle = color.cssString;
287
288      if (data.flags[i] & CPU_SLICE_FLAGS_INCOMPLETE) {
289        drawIncompleteSlice(ctx, rectStart, MARGIN_TOP, rectWidth, RECT_HEIGHT);
290      } else {
291        ctx.fillRect(rectStart, MARGIN_TOP, rectWidth, RECT_HEIGHT);
292      }
293
294      // Don't render text when we have less than 5px to play with.
295      if (rectWidth < 5) continue;
296
297      // Stylize real-time threads. We don't do it when zoomed out as the
298      // fillRect is expensive.
299      if (data.flags[i] & CPU_SLICE_FLAGS_REALTIME) {
300        ctx.fillStyle = getHatchedPattern(ctx);
301        ctx.fillRect(rectStart, MARGIN_TOP, rectWidth, RECT_HEIGHT);
302      }
303
304      // TODO: consider de-duplicating this code with the copied one from
305      // chrome_slices/frontend.ts.
306      let title = `[utid:${utid}]`;
307      let subTitle = '';
308      if (threadInfo) {
309        if (threadInfo.pid !== undefined && threadInfo.pid !== 0) {
310          let procName = threadInfo.procName ?? '';
311          if (procName.startsWith('/')) {
312            // Remove folder paths from name
313            procName = procName.substring(procName.lastIndexOf('/') + 1);
314          }
315          title = `${procName} [${threadInfo.pid}]`;
316          subTitle = `${threadInfo.threadName} [${threadInfo.tid}]`;
317        } else {
318          title = `${threadInfo.threadName} [${threadInfo.tid}]`;
319        }
320      }
321
322      if (data.flags[i] & CPU_SLICE_FLAGS_REALTIME) {
323        subTitle = subTitle + ' (RT)';
324      }
325
326      const right = Math.min(visWindowEndPx, rectEnd);
327      const left = Math.max(rectStart, 0);
328      const visibleWidth = Math.max(right - left, 1);
329      title = cropText(title, charWidth, visibleWidth);
330      subTitle = cropText(subTitle, charWidth, visibleWidth);
331      const rectXCenter = left + visibleWidth / 2;
332      ctx.fillStyle = textColor.cssString;
333      ctx.font = '12px Roboto Condensed';
334      ctx.fillText(title, rectXCenter, MARGIN_TOP + RECT_HEIGHT / 2 - 1);
335      ctx.fillStyle = textColor.setAlpha(0.6).cssString;
336      ctx.font = '10px Roboto Condensed';
337      ctx.fillText(subTitle, rectXCenter, MARGIN_TOP + RECT_HEIGHT / 2 + 9);
338    }
339
340    const selection = this.trace.selection.selection;
341    if (selection.kind === 'track_event') {
342      if (selection.trackUri === this.uri) {
343        const [startIndex, endIndex] = searchEq(data.ids, selection.eventId);
344        if (startIndex !== endIndex) {
345          const tStart = Time.fromRaw(data.startQs[startIndex]);
346          const tEnd = Time.fromRaw(data.endQs[startIndex]);
347          const utid = data.utids[startIndex];
348          const color = colorForThread(this.threads.get(utid));
349          const rectStart = timescale.timeToPx(tStart);
350          const rectEnd = timescale.timeToPx(tEnd);
351          const rectWidth = Math.max(1, rectEnd - rectStart);
352
353          // Draw a rectangle around the slice that is currently selected.
354          ctx.strokeStyle = color.base.setHSL({l: 30}).cssString;
355          ctx.beginPath();
356          ctx.lineWidth = 3;
357          ctx.strokeRect(
358            rectStart,
359            MARGIN_TOP - 1.5,
360            rectWidth,
361            RECT_HEIGHT + 3,
362          );
363          ctx.closePath();
364          // Draw arrow from wakeup time of current slice.
365          if (selection.wakeupTs) {
366            const wakeupPos = timescale.timeToPx(selection.wakeupTs);
367            const latencyWidth = rectStart - wakeupPos;
368            drawDoubleHeadedArrow(
369              ctx,
370              wakeupPos,
371              MARGIN_TOP + RECT_HEIGHT,
372              latencyWidth,
373              latencyWidth >= 20,
374            );
375            // Latency time with a white semi-transparent background.
376            const latency = tStart - selection.wakeupTs;
377            const displayText = Duration.humanise(latency);
378            const measured = ctx.measureText(displayText);
379            if (latencyWidth >= measured.width + 2) {
380              ctx.fillStyle = 'rgba(255,255,255,0.7)';
381              ctx.fillRect(
382                wakeupPos + latencyWidth / 2 - measured.width / 2 - 1,
383                MARGIN_TOP + RECT_HEIGHT - 12,
384                measured.width + 2,
385                11,
386              );
387              ctx.textBaseline = 'bottom';
388              ctx.fillStyle = 'black';
389              ctx.fillText(
390                displayText,
391                wakeupPos + latencyWidth / 2,
392                MARGIN_TOP + RECT_HEIGHT - 1,
393              );
394            }
395          }
396        }
397      }
398
399      // Draw diamond if the track being drawn is the cpu of the waker.
400      if (this.cpu.cpu === selection.wakerCpu && selection.wakeupTs) {
401        const wakeupPos = Math.floor(timescale.timeToPx(selection.wakeupTs));
402        ctx.beginPath();
403        ctx.moveTo(wakeupPos, MARGIN_TOP + RECT_HEIGHT / 2 + 8);
404        ctx.fillStyle = 'black';
405        ctx.lineTo(wakeupPos + 6, MARGIN_TOP + RECT_HEIGHT / 2);
406        ctx.lineTo(wakeupPos, MARGIN_TOP + RECT_HEIGHT / 2 - 8);
407        ctx.lineTo(wakeupPos - 6, MARGIN_TOP + RECT_HEIGHT / 2);
408        ctx.fill();
409        ctx.closePath();
410      }
411
412      if (this.utidHoveredInThisTrack !== undefined) {
413        const hoveredThread = this.threads.get(this.utidHoveredInThisTrack);
414        if (hoveredThread && this.mousePos !== undefined) {
415          const tidText = `T: ${hoveredThread.threadName}
416          [${hoveredThread.tid}]`;
417          // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
418          if (hoveredThread.pid) {
419            const pidText = `P: ${hoveredThread.procName}
420            [${hoveredThread.pid}]`;
421            drawTrackHoverTooltip(ctx, this.mousePos, size, pidText, tidText);
422          } else {
423            drawTrackHoverTooltip(ctx, this.mousePos, size, tidText);
424          }
425        }
426      }
427    }
428  }
429
430  onMouseMove({x, y, timescale}: TrackMouseEvent) {
431    const data = this.fetcher.data;
432    this.mousePos = {x, y};
433    if (data === undefined) return;
434    if (y < MARGIN_TOP || y > MARGIN_TOP + RECT_HEIGHT) {
435      this.utidHoveredInThisTrack = undefined;
436      this.trace.timeline.hoveredUtid = undefined;
437      this.trace.timeline.hoveredPid = undefined;
438      return;
439    }
440    const t = timescale.pxToHpTime(x);
441    let hoveredUtid = undefined;
442
443    for (let i = 0; i < data.startQs.length; i++) {
444      const tStart = Time.fromRaw(data.startQs[i]);
445      const tEnd = Time.fromRaw(data.endQs[i]);
446      const utid = data.utids[i];
447      if (t.gte(tStart) && t.lt(tEnd)) {
448        hoveredUtid = utid;
449        break;
450      }
451    }
452    this.utidHoveredInThisTrack = hoveredUtid;
453    const threadInfo = exists(hoveredUtid) && this.threads.get(hoveredUtid);
454    // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
455    const hoveredPid = threadInfo ? (threadInfo.pid ? threadInfo.pid : -1) : -1;
456    this.trace.timeline.hoveredUtid = hoveredUtid;
457    this.trace.timeline.hoveredPid = hoveredPid;
458  }
459
460  onMouseOut() {
461    this.utidHoveredInThisTrack = -1;
462    this.trace.timeline.hoveredUtid = undefined;
463    this.trace.timeline.hoveredPid = undefined;
464    this.mousePos = undefined;
465  }
466
467  onMouseClick({x, timescale}: TrackMouseEvent) {
468    const data = this.fetcher.data;
469    if (data === undefined) return false;
470    const time = timescale.pxToHpTime(x);
471    const index = search(data.startQs, time.toTime());
472    const id = index === -1 ? undefined : data.ids[index];
473    // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
474    if (!id || this.utidHoveredInThisTrack === -1) return false;
475
476    this.trace.selection.selectTrackEvent(this.uri, id);
477    return true;
478  }
479
480  async getSelectionDetails?(
481    eventId: number,
482  ): Promise<TrackEventDetails | undefined> {
483    const sched = await getSched(this.trace.engine, asSchedSqlId(eventId));
484    if (sched === undefined) {
485      return undefined;
486    }
487    const wakeup = await getSchedWakeupInfo(this.trace.engine, sched);
488    return {
489      ts: sched.ts,
490      dur: sched.dur,
491      wakeupTs: wakeup?.wakeupTs,
492      wakerCpu: wakeup?.wakerCpu,
493    };
494  }
495
496  detailsPanel() {
497    return new SchedSliceDetailsPanel(this.trace, this.threads);
498  }
499}
500
501// Creates a diagonal hatched pattern to be used for distinguishing slices with
502// real-time priorities. The pattern is created once as an offscreen canvas and
503// is kept cached inside the Context2D of the main canvas, without making
504// assumptions on the lifetime of the main canvas.
505function getHatchedPattern(mainCtx: CanvasRenderingContext2D): CanvasPattern {
506  const mctx = mainCtx as CanvasRenderingContext2D & {
507    sliceHatchedPattern?: CanvasPattern;
508  };
509  if (mctx.sliceHatchedPattern !== undefined) return mctx.sliceHatchedPattern;
510  const canvas = document.createElement('canvas');
511  const SIZE = 8;
512  canvas.width = canvas.height = SIZE;
513  const ctx = assertExists(canvas.getContext('2d'));
514  ctx.strokeStyle = 'rgba(255,255,255,0.3)';
515  ctx.beginPath();
516  ctx.lineWidth = 1;
517  ctx.moveTo(0, SIZE);
518  ctx.lineTo(SIZE, 0);
519  ctx.stroke();
520  mctx.sliceHatchedPattern = assertExists(mctx.createPattern(canvas, 'repeat'));
521  return mctx.sliceHatchedPattern;
522}
523