1// Copyright (C) 2018 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 {assertTrue} from '../../base/logging';
16import {slowlyCountRows} from '../../common/query_iterator';
17import {fromNs, toNs} from '../../common/time';
18import {
19  TrackController,
20  trackControllerRegistry
21} from '../../controller/track_controller';
22
23import {Config, CPU_SLICE_TRACK_KIND, Data} from './common';
24
25class CpuSliceTrackController extends TrackController<Config, Data> {
26  static readonly kind = CPU_SLICE_TRACK_KIND;
27
28  private cachedBucketNs = Number.MAX_SAFE_INTEGER;
29  private maxDurNs = 0;
30
31  async onSetup() {
32    await this.query(`
33      create view ${this.tableName('sched')} as
34      select
35        ts,
36        dur,
37        utid,
38        id
39      from sched
40      where cpu = ${this.config.cpu} and utid != 0
41    `);
42
43    const rawResult = await this.query(`
44      select max(dur), count(1)
45      from ${this.tableName('sched')}
46    `);
47    this.maxDurNs = rawResult.columns[0].longValues![0];
48
49    const rowCount = rawResult.columns[1].longValues![0];
50    const bucketNs = this.cachedBucketSizeNs(rowCount);
51    if (bucketNs === undefined) {
52      return;
53    }
54    await this.query(`
55      create table ${this.tableName('sched_cached')} as
56      select
57        (ts + ${bucketNs / 2}) / ${bucketNs} * ${bucketNs} as cached_tsq,
58        ts,
59        max(dur) as dur,
60        utid,
61        id
62      from ${this.tableName('sched')}
63      group by cached_tsq
64      order by cached_tsq
65    `);
66    this.cachedBucketNs = bucketNs;
67  }
68
69  async onBoundsChange(start: number, end: number, resolution: number):
70      Promise<Data> {
71    const resolutionNs = toNs(resolution);
72
73    // The resolution should always be a power of two for the logic of this
74    // function to make sense.
75    assertTrue(Math.log2(resolutionNs) % 1 === 0);
76
77    const startNs = toNs(start);
78    const endNs = toNs(end);
79
80    // ns per quantization bucket (i.e. ns per pixel). /2 * 2 is to force it to
81    // be an even number, so we can snap in the middle.
82    const bucketNs =
83        Math.max(Math.round(resolutionNs * this.pxSize() / 2) * 2, 1);
84
85    const isCached = this.cachedBucketNs <= bucketNs;
86    const queryTsq = isCached ?
87        `cached_tsq / ${bucketNs} * ${bucketNs}` :
88        `(ts + ${bucketNs / 2}) / ${bucketNs} * ${bucketNs}`;
89    const queryTable =
90        isCached ? this.tableName('sched_cached') : this.tableName('sched');
91    const constainColumn = isCached ? 'cached_tsq' : 'ts';
92
93    const rawResult = await this.query(`
94      select
95        ${queryTsq} as tsq,
96        ts,
97        max(dur) as dur,
98        utid,
99        id
100      from ${queryTable}
101      where
102        ${constainColumn} >= ${startNs - this.maxDurNs} and
103        ${constainColumn} <= ${endNs}
104      group by tsq
105      order by tsq
106    `);
107
108    const numRows = slowlyCountRows(rawResult);
109    const slices: Data = {
110      start,
111      end,
112      resolution,
113      length: numRows,
114      ids: new Float64Array(numRows),
115      starts: new Float64Array(numRows),
116      ends: new Float64Array(numRows),
117      utids: new Uint32Array(numRows),
118    };
119
120    const cols = rawResult.columns;
121    for (let row = 0; row < numRows; row++) {
122      const startNsQ = +cols[0].longValues![row];
123      const startNs = +cols[1].longValues![row];
124      const durNs = +cols[2].longValues![row];
125      const endNs = startNs + durNs;
126
127      let endNsQ = Math.floor((endNs + bucketNs / 2 - 1) / bucketNs) * bucketNs;
128      endNsQ = Math.max(endNsQ, startNsQ + bucketNs);
129
130      if (startNsQ === endNsQ) {
131        throw new Error('Should never happen');
132      }
133
134      slices.starts[row] = fromNs(startNsQ);
135      slices.ends[row] = fromNs(endNsQ);
136      slices.utids[row] = +cols[3].longValues![row];
137      slices.ids[row] = +cols[4].longValues![row];
138    }
139
140    return slices;
141  }
142
143  async onDestroy() {
144    await this.query(`drop table if exists ${this.tableName('sched_cached')}`);
145  }
146}
147
148trackControllerRegistry.register(CpuSliceTrackController);
149