blob: 1ccb17427db9ec0f7243dec2d2f7699871801fac [file]
// Copyright (C) 2026 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import './styles.scss';
import {AsyncMemo, AtomicTaskQueue} from '../../base/async_memo';
import {LockContentionDetailsTab} from './lock_owner_details_panel';
import {LOCK_CONTENTION_SQL} from './lock_contention_sql';
import type {Selection} from '../../public/selection';
import {Time} from '../../base/time';
import {TrackNode} from '../../public/workspace';
import {
LONG,
NUM,
NUM_NULL,
STR,
STR_NULL,
} from '../../trace_processor/query_result';
import type {ArrowConnection} from '../../components/related_events/arrow_visualiser';
import {
getTrackUriForTrackId,
enrichDepths,
TrackPinningManager,
} from '../../components/related_events/utils';
import {SliceTrack} from '../../components/tracks/slice_track';
import {CounterTrack} from '../../components/tracks/counter_track';
import {SourceDataset} from '../../trace_processor/dataset';
import {addDebugSliceTrack} from '../../components/tracks/debug_tracks';
import type {PerfettoPlugin} from '../../public/plugin';
import type {Trace} from '../../public/trace';
import {RelatedEventsOverlay} from '../../components/related_events/related_events_overlay';
import TraceProcessorTrackPlugin from '../dev.perfetto.TraceProcessorTrack';
export default class AndroidLockContentionPlugin implements PerfettoPlugin {
static readonly id = 'com.android.AndroidLockContention';
static readonly description =
'Visualise lock contention events in the trace. You can navigate between contention events using ] and [';
static readonly dependencies = [TraceProcessorTrackPlugin];
private readonly connectionsTaskQueue = new AtomicTaskQueue();
private readonly connectionsSlot = new AsyncMemo<ArrowConnection[]>(
this.connectionsTaskQueue,
);
public highlightedTargetIds = new Set<number>();
public pinningManager!: TrackPinningManager;
public currentBlockedSlice?: {id: number; trackUri?: string};
public contentionSliceIds = new Set<number>();
private lastEventId?: number;
private async contextualJump(trace: Trace) {
const selection = trace.selection.selection;
if (selection.kind !== 'track_event') return;
if (
selection.trackUri.startsWith(
'com.android.AndroidLockContention#OwnerEvents_Slice',
)
) {
return;
}
const query = await trace.engine.query(`
SELECT id, owner_tid, blocked_utid
FROM __android_lock_contention_owner_events
WHERE id = ${selection.eventId}
LIMIT 1
`);
if (query.numRows() > 0) {
const row = query.firstRow({id: NUM, owner_tid: NUM, blocked_utid: NUM});
this.currentBlockedSlice = {
id: selection.eventId,
trackUri: selection.trackUri,
};
this.selectAndNavigate(
trace,
row.id,
`com.android.AndroidLockContention#OwnerEvents_Slice_${row.owner_tid}_${row.blocked_utid}`,
);
}
}
public readonly navigation = new LockContentionNavigation();
public selectAndNavigate(
trace: Trace,
eventId: number,
trackUri?: string,
isSqlEvent = false,
) {
const selection = trace.selection.selection;
if (selection !== undefined) {
this.navigation.push(selection, eventId, trackUri);
}
if (isSqlEvent) {
trace.selection.selectSqlEvent('slice', eventId, {
scrollToSelection: true,
switchToCurrentSelectionTab: false,
});
} else if (trackUri) {
trace.selection.selectTrackEvent(trackUri, eventId, {
scrollToSelection: true,
switchToCurrentSelectionTab: false,
});
}
}
async onTraceLoad(trace: Trace): Promise<void> {
this.pinningManager = new TrackPinningManager(trace);
await trace.engine.query(LOCK_CONTENTION_SQL);
const contentions = await trace.engine.query(
`SELECT id FROM android_all_lock_contentions`,
);
const it = contentions.iter({id: NUM});
for (; it.valid(); it.next()) {
this.contentionSliceIds.add(it.id);
}
trace.selection.registerTrackEventSelectionTab(
new LockContentionDetailsTab(trace, this),
);
trace.tracks.registerOverlay(
new RelatedEventsOverlay(trace, () => this.getConnections(trace)),
);
trace.commands.registerCommand({
id: 'com.android.AndroidLockContention:ToggleView',
name: 'Android Lock Contention: Toggle View',
defaultHotkey: ']',
callback: () => {
this.contextualJump(trace);
},
});
trace.commands.registerCommand({
id: 'com.android.AndroidLockContention:NavigateBackward',
name: 'Android Lock Contention: Navigate Backward',
defaultHotkey: '[',
callback: async () => {
await this.navigation.goBack(trace);
},
});
trace.commands.registerCommand({
id: 'com.android.visualiseHeldLocks',
name: 'Lock Contention: Visualise held locks',
callback: async () => {
await trace.engine.query('INCLUDE PERFETTO MODULE android.lock_held;');
await addDebugSliceTrack({
trace: trace,
data: {
// `slice_id` + `table_name` let DebugSliceTrackDetailsPanel resolve
// the underlying slice and render a link to it.
sqlSource: `
SELECT
h.id AS slice_id,
'slice' AS table_name,
t.name AS thread_name,
h.lock_name,
h.blocking_method,
utid,
h.ts,
iif(h.is_incomplete, -1, h.dur) AS dur
FROM android_lock_held AS h
JOIN thread AS t USING (utid)
`,
},
title: 'Held Lock',
columns: {
name: 'thread_name',
},
pivotOn: 'lock_name',
});
},
});
const tableName = '__android_lock_contention_owner_events';
const ownersQuery = await trace.engine.query(`
WITH unique_owners AS (
SELECT DISTINCT owner_tid
FROM __android_lock_contention_owner_events
WHERE owner_tid IS NOT NULL
)
SELECT
uo.owner_tid,
t.name,
tt.id as track_id
FROM unique_owners uo
LEFT JOIN thread t ON t.tid = uo.owner_tid
LEFT JOIN thread_track tt ON tt.utid = t.utid
GROUP BY uo.owner_tid
`);
const blockedQuery = await trace.engine.query(`
SELECT
owner_tid,
blocked_utid,
blocked_tid,
blocked_thread_name,
MAX(depth) AS max_depth
FROM __android_lock_contention_owner_events
WHERE owner_tid IS NOT NULL AND blocked_utid IS NOT NULL
GROUP BY owner_tid, blocked_utid
ORDER BY owner_tid, blocked_thread_name, blocked_tid
`);
const blockedMap = new Map<
number,
Array<{
blockedUtid: number;
blockedTid: number;
blockedThreadName: string | null;
maxDepth: number;
}>
>();
const blockedIt = blockedQuery.iter({
owner_tid: NUM,
blocked_utid: NUM,
blocked_tid: NUM,
blocked_thread_name: STR_NULL,
max_depth: NUM_NULL,
});
for (; blockedIt.valid(); blockedIt.next()) {
const ownerTid = blockedIt.owner_tid;
let list = blockedMap.get(ownerTid);
if (!list) {
list = [];
blockedMap.set(ownerTid, list);
}
list.push({
blockedUtid: blockedIt.blocked_utid,
blockedTid: blockedIt.blocked_tid,
blockedThreadName: blockedIt.blocked_thread_name,
maxDepth: blockedIt.max_depth ?? 0,
});
}
const ownersIt = ownersQuery.iter({
owner_tid: NUM,
name: STR_NULL,
track_id: NUM_NULL,
});
for (; ownersIt.valid(); ownersIt.next()) {
const tid = ownersIt.owner_tid;
if (tid === null) continue; // Skip invalid TIDs
this.registerOwnerTrack(
trace,
tid,
ownersIt.name || 'Unknown',
blockedMap.get(tid) ?? [],
ownersIt.track_id,
tableName,
);
}
}
private getConnections(trace: Trace): ArrowConnection[] {
const selection = trace.selection.selection;
if (selection.kind !== 'track_event') {
this.highlightedTargetIds.clear();
this.lastEventId = undefined;
return [];
}
if (this.lastEventId !== selection.eventId) {
this.highlightedTargetIds.clear();
this.highlightedTargetIds.add(selection.eventId);
this.lastEventId = selection.eventId;
}
const result = this.connectionsSlot.use({
key: {
eventId: selection.eventId,
highlightedTargetIds: Array.from(this.highlightedTargetIds)
.sort()
.join(','),
},
compute: () => this.fetchConnections(trace, selection),
});
return result.data ?? [];
}
private async fetchConnections(
trace: Trace,
selection: Selection & {kind: 'track_event'},
): Promise<ArrowConnection[]> {
const trackUri = selection.trackUri;
const eventId = selection.eventId;
if (
trackUri.startsWith('com.android.AndroidLockContention#OwnerEvents_Slice')
) {
const targetIds = new Set(this.highlightedTargetIds);
if (targetIds.size === 0) {
return [];
}
const idList = Array.from(targetIds).join(',');
const rawQuery = await trace.engine.query(`
SELECT id, ts, dur, depth FROM __android_lock_contention_owner_events
WHERE id IN (${idList})
`);
const targets: Array<{
id: number;
trackUri: string;
depth: number;
ts: bigint;
customDepth: number;
}> = [];
const rawIt = rawQuery.iter({id: NUM, ts: LONG, dur: LONG, depth: NUM});
for (; rawIt.valid(); rawIt.next()) {
const rawId = rawIt.id;
const rawTs = rawIt.ts;
const rawDur = rawIt.dur;
const middleTs = rawTs + rawDur / 2n;
const customDepth = rawIt.depth;
const sliceQuery = await trace.engine.query(`
SELECT track_id FROM slice WHERE id = ${rawId} LIMIT 1
`);
if (sliceQuery.numRows() === 0) continue;
const trackId = sliceQuery.firstRow({track_id: NUM}).track_id;
const origTrackUri = getTrackUriForTrackId(trace, trackId);
if (!origTrackUri) continue;
targets.push({
id: rawId,
trackUri: origTrackUri,
depth: 0,
ts: middleTs,
customDepth,
});
}
await enrichDepths(trace, targets);
const connections: ArrowConnection[] = [];
for (const target of targets) {
connections.push({
start: {
trackUri: trackUri,
ts: Time.fromRaw(target.ts),
depth: target.customDepth,
},
end: {
trackUri: target.trackUri,
ts: Time.fromRaw(target.ts),
depth: target.depth,
},
});
}
return connections;
}
const query = await trace.engine.query(`
SELECT owner_tid, blocked_utid, ts, dur, depth
FROM __android_lock_contention_owner_events
WHERE id = ${eventId}
LIMIT 1
`);
if (query.numRows() > 0) {
const row = query.firstRow({
owner_tid: NUM,
blocked_utid: NUM,
ts: LONG,
dur: LONG,
depth: NUM,
});
const middleTs = row.ts + row.dur / 2n;
const ownerTrackUri = `com.android.AndroidLockContention#OwnerEvents_Slice_${row.owner_tid}_${row.blocked_utid}`;
const targets = {id: eventId, trackUri: trackUri, depth: 0};
await enrichDepths(trace, [targets]);
return [
{
start: {
trackUri: trackUri,
ts: Time.fromRaw(middleTs),
depth: targets.depth,
},
end: {
trackUri: ownerTrackUri,
ts: Time.fromRaw(middleTs),
depth: row.depth,
},
},
];
}
return [];
}
private registerOwnerTrack(
trace: Trace,
tid: number,
threadName: string,
blockedThreads: Array<{
blockedUtid: number;
blockedTid: number;
blockedThreadName: string | null;
maxDepth: number;
}>,
trackId: number | null,
tableName: string,
) {
const counterTrackUri = `com.android.AndroidLockContention#OwnerEvents_Counter_${tid}`;
const groupTrackName = `${threadName} [${tid}] Blocking Contentions`;
// Create and Register the Counter Track (summary)
const counterTrack = CounterTrack.create({
trace,
uri: counterTrackUri,
sqlSource: `
SELECT ts, value
FROM __android_lock_contention_counters
WHERE owner_tid = ${tid}
`,
yMode: 'value',
unit: ' concurrent contention(s)',
});
trace.tracks.registerTrack({
uri: counterTrackUri,
renderer: counterTrack,
});
const groupNode = new TrackNode({
uri: counterTrackUri,
name: groupTrackName,
isSummary: true,
removable: true,
});
for (const blocked of blockedThreads) {
const sliceTrackUri = `com.android.AndroidLockContention#OwnerEvents_Slice_${tid}_${blocked.blockedUtid}`;
const name = blocked.blockedThreadName
? `${blocked.blockedThreadName} [${blocked.blockedTid}]`
: `Thread [${blocked.blockedTid}]`;
trace.tracks.registerTrack({
uri: sliceTrackUri,
description: `Shows slices representing when thread ${threadName} [${tid}] is blocking ${name}`,
renderer: SliceTrack.create({
trace,
uri: sliceTrackUri,
dataset: new SourceDataset({
schema: {
id: NUM,
ts: LONG,
dur: LONG,
name: STR,
depth: NUM,
},
src: tableName,
filter: {
col: 'owner_blocked_key',
eq: `${tid}_${blocked.blockedUtid}`,
},
}),
initialMaxDepth: blocked.maxDepth,
sliceName: (row) => row.name,
sliceLayout: {
sliceHeight: 14,
titleSizePx: 10,
},
}),
});
const sliceNode = new TrackNode({
uri: sliceTrackUri,
name: `Blocked: ${name}`,
});
groupNode.addChildLast(sliceNode);
}
if (trackId !== null) {
const track = trace.tracks.findTrack((t) =>
t.tags?.trackIds?.includes(trackId),
);
if (track) {
const threadNode = trace.currentWorkspace.getTrackByUri(track.uri);
threadNode?.parent?.addChildBefore(groupNode, threadNode);
}
}
}
}
function selectionsEqual(a: Selection, b: Selection): boolean {
if (a.kind !== b.kind) return false;
if (a.kind === 'track_event' && b.kind === 'track_event') {
return a.eventId === b.eventId && a.trackUri === b.trackUri;
}
if (a.kind === 'track' && b.kind === 'track') {
return a.trackUri === b.trackUri;
}
return false;
}
class LockContentionNavigation {
private stack: {
source: Selection;
targetEventId: number;
targetTrackUri?: string;
}[] = [];
push(source: Selection, targetEventId: number, targetTrackUri?: string) {
const top = this.stack[this.stack.length - 1];
if (top !== undefined && selectionsEqual(top.source, source)) {
return;
}
this.stack.push({source, targetEventId, targetTrackUri});
}
async goBack(trace: Trace) {
const currentSelection = trace.selection.selection;
const top = this.stack[this.stack.length - 1];
if (
top !== undefined &&
currentSelection.kind === 'track_event' &&
currentSelection.eventId === top.targetEventId &&
(top.targetTrackUri === undefined ||
currentSelection.trackUri === top.targetTrackUri ||
currentSelection.trackUri === 'unknown')
) {
this.stack.pop();
this.restore(trace, top.source);
return;
}
// Fallback: if we are on the owner track, try to go back to the original slice
if (
currentSelection.kind === 'track_event' &&
currentSelection.trackUri.startsWith(
'com.android.AndroidLockContention#OwnerEvents_Slice',
)
) {
const sliceQuery = await trace.engine.query(`
SELECT track_id FROM slice WHERE id = ${currentSelection.eventId} LIMIT 1
`);
if (sliceQuery.numRows() > 0) {
const trackId = sliceQuery.firstRow({track_id: NUM}).track_id;
const trackUri = getTrackUriForTrackId(trace, trackId);
if (trackUri) {
trace.selection.selectTrackEvent(trackUri, currentSelection.eventId, {
scrollToSelection: true,
switchToCurrentSelectionTab: false,
});
this.stack = [];
return;
}
}
trace.selection.selectSqlEvent('slice', currentSelection.eventId, {
scrollToSelection: true,
switchToCurrentSelectionTab: false,
});
this.stack = [];
return;
}
if (this.stack.length > 0) {
this.stack = [];
}
}
private restore(trace: Trace, selection: Selection) {
if (selection.kind === 'track_event') {
if (selection.trackUri === 'unknown' || selection.trackUri === '') {
trace.selection.selectSqlEvent('slice', selection.eventId, {
scrollToSelection: true,
switchToCurrentSelectionTab: false,
});
} else {
trace.selection.selectTrackEvent(
selection.trackUri,
selection.eventId,
{
scrollToSelection: true,
switchToCurrentSelectionTab: false,
},
);
}
} else if (selection.kind === 'track') {
trace.selection.selectTrack(selection.trackUri, {
scrollToSelection: true,
switchToCurrentSelectionTab: false,
});
}
}
has(selection: Selection) {
return this.stack.some((s) => selectionsEqual(s.source, selection));
}
}