• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
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  */
15 #ifndef HIPERF_PERF_EVENTS_H
16 #define HIPERF_PERF_EVENTS_H
17 
18 #include <atomic>
19 #include <cassert>
20 #include <chrono>
21 #include <cinttypes>
22 #include <condition_variable>
23 #include <deque>
24 #include <map>
25 #include <memory>
26 #include <string>
27 #include <thread>
28 #include <variant>
29 #include <vector>
30 #if !is_mingw
31 #include <poll.h>
32 #endif
33 
34 #include <sys/types.h>
35 #include <unique_fd.h>
36 #include <linux/perf_event.h>
37 
38 #include "debug_logger.h"
39 #include "perf_event_record.h"
40 #include "ring_buffer.h"
41 #include "tracked_command.h"
42 #include "utilities.h"
43 #include "virtual_runtime.h"
44 
45 // this for some performance debug
46 #define HIDEBUG_SKIP_CALLBACK 0
47 
48 namespace OHOS {
49 namespace Developtools {
50 namespace HiPerf {
51 using ConfigTable = std::map<__u64, const std::string>;
52 using SharedConfigTable = std::unique_ptr<ConfigTable>;
53 
54 static const std::string PERF_EVENT_PARANOID = "/proc/sys/kernel/perf_event_paranoid";
55 static const std::string PERF_DISABLE_PARAM = "security.perf_harden";
56 
57 // define convert from linux/perf_event.h
58 // description from https://man7.org/linux/man-pages/man2/perf_event_open.2.html
59 
60 static const ConfigTable PERF_HW_CONFIGS = {
61     {PERF_COUNT_HW_CPU_CYCLES, "hw-cpu-cycles"},
62     {PERF_COUNT_HW_INSTRUCTIONS, "hw-instructions"},
63     {PERF_COUNT_HW_CACHE_REFERENCES, "hw-cache-references"},
64     {PERF_COUNT_HW_CACHE_MISSES, "hw-cache-misses"},
65     {PERF_COUNT_HW_BRANCH_INSTRUCTIONS, "hw-branch-instructions"},
66     {PERF_COUNT_HW_BRANCH_MISSES, "hw-branch-misses"},
67     {PERF_COUNT_HW_BUS_CYCLES, "hw-bus-cycles"},
68     {PERF_COUNT_HW_STALLED_CYCLES_FRONTEND, "hw-stalled-cycles-frontend"},
69     {PERF_COUNT_HW_STALLED_CYCLES_BACKEND, "hw-stalled-cycles-backend"},
70     {PERF_COUNT_HW_REF_CPU_CYCLES, "hw-ref-cpu-cycles"},
71 };
72 static const ConfigTable PERF_HW_CACHE_CONFIGS = {
73     {PERF_COUNT_HW_CACHE_L1D, "hw-cache-l1d"},   {PERF_COUNT_HW_CACHE_L1I, "hw-cache-l1i"},
74     {PERF_COUNT_HW_CACHE_LL, "hw-cache-ll"},     {PERF_COUNT_HW_CACHE_DTLB, "hw-cache-dtlb"},
75     {PERF_COUNT_HW_CACHE_ITLB, "hw-cache-itlb"}, {PERF_COUNT_HW_CACHE_BPU, "hw-cache-bpu"},
76     {PERF_COUNT_HW_CACHE_NODE, "hw-cache-node"},
77 };
78 static const ConfigTable PERF_HW_CACHE_OP_CONFIGS = {
79     {PERF_COUNT_HW_CACHE_OP_READ, "hw-cache-op-read"},
80     {PERF_COUNT_HW_CACHE_OP_WRITE, "hw-cache-op-write"},
81     {PERF_COUNT_HW_CACHE_OP_PREFETCH, "hw-cache-op-prefetch"},
82 };
83 static const ConfigTable PERF_HW_CACHE_OP_RESULT_CONFIGS = {
84     {PERF_COUNT_HW_CACHE_RESULT_ACCESS, "hw-cache-result-access"},
85     {PERF_COUNT_HW_CACHE_RESULT_MISS, "hw-cache-result-miss"},
86 };
87 static const ConfigTable PERF_SW_CONFIGS = {
88     {PERF_COUNT_SW_CPU_CLOCK, "sw-cpu-clock"},
89     {PERF_COUNT_SW_TASK_CLOCK, "sw-task-clock"},
90     {PERF_COUNT_SW_PAGE_FAULTS, "sw-page-faults"},
91     {PERF_COUNT_SW_CONTEXT_SWITCHES, "sw-context-switches"},
92     {PERF_COUNT_SW_CPU_MIGRATIONS, "sw-cpu-migrations"},
93     {PERF_COUNT_SW_PAGE_FAULTS_MIN, "sw-page-faults-min"},
94     {PERF_COUNT_SW_PAGE_FAULTS_MAJ, "sw-page-faults-maj"},
95     {PERF_COUNT_SW_ALIGNMENT_FAULTS, "sw-alignment-faults"},
96     {PERF_COUNT_SW_EMULATION_FAULTS, "sw-emulation-faults"},
97     {PERF_COUNT_SW_DUMMY, "sw-dummy"},
98     {PERF_COUNT_SW_BPF_OUTPUT, "sw-bpf-output"},
99 };
100 static const ConfigTable PERF_RAW_CONFIGS = {
101     {0x0, "raw-sw-incr"},
102     {0x1, "raw-l1-icache-refill"},
103     {0x2, "raw-l1-itlb-refill"},
104     {0x3, "raw-l1-dcache-refill"},
105     {0x4, "raw-l1-dcache"},
106     {0x5, "raw-l1-dtlb-refill"},
107     {0x6, "raw-load-retired"},
108     {0x7, "raw-store-retired"},
109     {0x8, "raw-instruction-retired"},
110     {0x9, "raw-exception-taken"},
111     {0xa, "raw-exception-return"},
112     {0xb, "raw-cid-write-retired"},
113     {0xc, "raw-pc-write-retired"},
114     {0xd, "raw-br-immed-retired"},
115     {0xe, "raw-br-return-retired"},
116     {0xf, "raw-unaligned-ldst-retired"},
117     {0x10, "raw-br-mis-pred"},
118     {0x11, "raw-cpu-cycles"},
119     {0x12, "raw-br-pred"},
120     {0x13, "raw-mem-access"},
121     {0x14, "raw-l1-icache"},
122     {0x15, "raw-l1-dcache-wb"},
123     {0x16, "raw-l2-dcache"},
124     {0x17, "raw-l2-dcache-refill"},
125     {0x18, "raw-l2-dcache-wb"},
126     {0x19, "raw-bus-access"},
127     {0x1a, "raw-memory-error"},
128     {0x1b, "raw-inst-spec"},
129     {0x1c, "raw-ttbr-write-retired"},
130     {0x1d, "raw-bus-cycles"},
131     {0x1f, "raw-l1-dcache-allocate"},
132     {0x20, "raw-l2-dcache-allocate"},
133     {0x21, "raw-br-retired"},
134     {0x22, "raw-br-mis-pred-retired"},
135     {0x23, "raw-stall-frontend"},
136     {0x24, "raw-stall-backend"},
137     {0x25, "raw-l1-dtlb"},
138     {0x26, "raw-l1-itlb"},
139     {0x27, "raw-l2-icache"},
140     {0x28, "raw-l2-icache-refill"},
141     {0x29, "raw-l3-dcache-allocate"},
142     {0x2a, "raw-l3-dcache-refill"},
143     {0x2b, "raw-l3-dcache"},
144     {0x2c, "raw-l3-dcache-wb"},
145     {0x2d, "raw-l2-dtlb-refill"},
146     {0x2e, "raw-l2-itlb-refill"},
147     {0x2f, "raw-l2-dtlb"},
148     {0x30, "raw-l2-itlb"},
149 };
150 static ConfigTable PERF_TRACEPOINT_CONFIGS = {
151 
152 };
153 
154 static const std::map<perf_type_id, std::string> PERF_TYPES = {
155     {PERF_TYPE_HARDWARE, "hardware"},
156     {PERF_TYPE_SOFTWARE, "software"},
157     {PERF_TYPE_TRACEPOINT, "tracepoint"},
158     {PERF_TYPE_HW_CACHE, "hardware cache"},
159     {PERF_TYPE_RAW, "raw"},
160 };
161 
162 static std::map<perf_type_id, ConfigTable> TYPE_CONFIGS = {
163     {PERF_TYPE_HARDWARE, (PERF_HW_CONFIGS)},           {PERF_TYPE_SOFTWARE, (PERF_SW_CONFIGS)},
164     {PERF_TYPE_HW_CACHE, (PERF_HW_CACHE_CONFIGS)},     {PERF_TYPE_RAW, (PERF_RAW_CONFIGS)},
165     {PERF_TYPE_TRACEPOINT, (PERF_TRACEPOINT_CONFIGS)},
166 };
167 
168 // default config
169 static const std::vector<__u64> DEFAULT_HW_CONFIGS = {
170     PERF_COUNT_HW_CPU_CYCLES,
171 #if defined(__aarch64__)
172     PERF_COUNT_HW_STALLED_CYCLES_FRONTEND,
173     PERF_COUNT_HW_STALLED_CYCLES_BACKEND,
174 #endif
175     PERF_COUNT_HW_INSTRUCTIONS,
176     PERF_COUNT_HW_BRANCH_INSTRUCTIONS,
177     PERF_COUNT_HW_BRANCH_MISSES,
178 };
179 static const std::vector<__u64> DEFAULT_SW_CONFIGS = {
180     PERF_COUNT_SW_TASK_CLOCK,
181     PERF_COUNT_SW_CONTEXT_SWITCHES,
182     PERF_COUNT_SW_PAGE_FAULTS,
183 };
184 static const std::map<perf_type_id, std::vector<__u64>> DEFAULT_TYPE_CONFIGS = {
185     {PERF_TYPE_HARDWARE, DEFAULT_HW_CONFIGS},
186     {PERF_TYPE_SOFTWARE, DEFAULT_SW_CONFIGS},
187 };
188 
189 struct read_format_event {
190     __u64 value; /* The value of the event */
191     __u64 id;    /* if PERF_FORMAT_ID */
192 };
193 
194 struct read_format_group {
195     __u64 nr;           /* The number of events */
196     __u64 time_enabled; /* if PERF_FORMAT_TOTAL_TIME_ENABLED */
197     __u64 time_running; /* if PERF_FORMAT_TOTAL_TIME_RUNNING */
198     read_format_event events[1];
199 };
200 
201 struct read_format_no_group {
202     __u64 value;        /* The value of the event */
203     __u64 time_enabled; /* if PERF_FORMAT_TOTAL_TIME_ENABLED */
204     __u64 time_running; /* if PERF_FORMAT_TOTAL_TIME_RUNNING */
205     __u64 id;           /* if PERF_FORMAT_ID */
206 };
207 
208 class PerfEvents {
209 public:
210     static constexpr uint64_t DEFAULT_SAMPLE_FREQUNCY = 4000;
211     static constexpr uint64_t DEFAULT_SAMPLE_PERIOD = 1;
212     static constexpr uint64_t DEFAULT_TIMEOUT = 10 * 1000;
213     static constexpr size_t MIN_BUFFER_SIZE = 64 * 1024 * 1024;
214 #ifdef LITTLE_MEMORY
215     static constexpr size_t MAX_BUFFER_SIZE = 128 * 1024 * 1024;
216 #else
217     static constexpr size_t MAX_BUFFER_SIZE = 256 * 1024 * 1024;
218 #endif
219     static constexpr size_t BUFFER_LOW_LEVEL = 10 * 1024 * 1024;
220     static constexpr size_t BUFFER_CRITICAL_LEVEL = 5 * 1024 * 1024;
221 
222     PerfEvents();
223     ~PerfEvents();
224 
225     bool AddEvents(const std::vector<std::string> &eventStrings, bool group = false);
226     bool PrepareTracking(void);
227     bool StartTracking(bool immediately = true);
228     bool StopTracking(void);
229     bool PauseTracking(void);
230     bool ResumeTracking(void);
231     /* call sequence
232        1. setXXX
233        2. AddEvents()
234        3. PrepareTracking
235        4. StartTracking (blocking...)
236     */
237     bool EnableTracking();
238     bool IsTrackRunning();
239 
240     void SetSystemTarget(bool);
241     void SetCpu(const std::vector<pid_t> cpus); // cpu id must be [0~N]
242     void SetPid(const std::vector<pid_t> pids); // tis is same as pid in kernel
243     void SetTimeOut(float timeOut);
244     void SetTimeReport(int);
245     void SetVerboseReport(bool);
246     bool AddOffCpuEvent();
247 
SetTrackedCommand(const std::vector<std::string> & trackedCommand)248     inline void SetTrackedCommand(const std::vector<std::string> &trackedCommand)
249     {
250         if (!trackedCommand.empty()) {
251             trackedCommand_ = TrackedCommand::CreateInstance(trackedCommand);
252         }
253     }
254 
255     void SetSampleFrequency(unsigned int frequency);
256     void SetSamplePeriod(unsigned int period);
257 
258     enum SampleStackType {
259         NONE,
260         FP,
261         DWARF,
262     };
263     void SetSampleStackType(SampleStackType type);
264     void SetDwarfSampleStackSize(uint32_t stackSize);
265     void SetMmapPages(size_t mmapPages);
266     std::vector<AttrWithId> GetAttrWithId() const;
267 
SetInherit(bool inherit)268     void SetInherit(bool inherit)
269     {
270         inherit_ = inherit;
271     };
SetClockId(int clockId)272     void SetClockId(int clockId)
273     {
274         clockId_ = clockId;
275     };
276     bool SetBranchSampleType(uint64_t value);
277     bool AddDefaultEvent(perf_type_id type);
278 
279     std::map<__u64, std::string> GetSupportEvents(perf_type_id type);
280 
281     struct CountEvent {
282         bool userOnly = false;
283         bool kernelOnly = false;
284         __u64 eventCount = 0;
285         __u64 time_enabled = 0;
286         __u64 time_running = 0;
287         __u64 id = 0;
288         double used_cpus = 0;
289     };
290     using StatCallBack =
291         std::function<void(const std::map<std::string, std::unique_ptr<PerfEvents::CountEvent>> &)>;
292     using RecordCallBack = std::function<bool(std::unique_ptr<PerfEventRecord>)>;
293 
294     void SetStatCallBack(StatCallBack reportCallBack);
295     void SetRecordCallBack(RecordCallBack recordCallBack);
GetLostSamples(size_t & lostSamples,size_t & lostNonSamples)296     void GetLostSamples(size_t &lostSamples, size_t &lostNonSamples)
297     {
298         lostSamples = lostSamples_;
299         lostNonSamples = lostNonSamples_;
300     }
301 
302     // review: remove this function.
GetStaticConfigName(perf_type_id type_id,__u64 config_id)303     static const std::string GetStaticConfigName(perf_type_id type_id, __u64 config_id)
304     {
305         auto typeConfigs = TYPE_CONFIGS.find(type_id);
306         if (typeConfigs != TYPE_CONFIGS.end()) {
307             auto configs = typeConfigs->second;
308             auto config = configs.find(config_id);
309             if (config != configs.end()) {
310                 return config->second;
311             } else {
312                 HLOGW("config not found for %u:%lld in %zu:%zu", type_id, config_id,
313                       TYPE_CONFIGS.size(), configs.size());
314                 // dump all config size
315                 for (auto types : TYPE_CONFIGS) {
316                     HLOGV("type id %d %zu", types.first, types.second.size());
317                 }
318             }
319         } else {
320             HLOGW("type not found for %d  in %zu", type_id, TYPE_CONFIGS.size());
321         }
322         return "<not found>";
323     };
324 
GetTraceConfigName(__u64 config_id)325     const std::string GetTraceConfigName(__u64 config_id)
326     {
327         auto config = traceConfigTable.find(config_id);
328         if (config != traceConfigTable.end()) {
329             return config->second;
330         } else {
331             HLOGW("config not found for %lld in traceConfigTable.", config_id);
332         }
333         return "<not found>";
334     };
335 
336     static const std::string GetTypeName(perf_type_id type_id);
337     bool ParseEventName(const std::string &nameStr, std::string &name, bool &excludeUser,
338                         bool &excludeKernel, bool &isTracePoint);
339 
340     // mmap one fd for each cpu
341     struct MmapFd {
342         int fd;
343         perf_event_mmap_page *mmapPage = nullptr;
344         uint8_t *buf = nullptr;
345         size_t bufSize = 0;
346         // for read and sort
347         size_t dataSize = 0;
348         perf_event_header header;
349         uint64_t timestamp = 0;
350         const perf_event_attr *attr = nullptr;
351         size_t posCallChain = 0;
352     };
353 
354 private:
355     size_t recordEventCount_ = 0; // only for debug time
356 #ifdef HIPERF_DEBUG_TIME
357     std::chrono::microseconds recordCallBackTime_ = std::chrono::microseconds::zero();
358     std::chrono::microseconds recordWaitDataTime_ = std::chrono::microseconds::zero();
359     std::chrono::microseconds recordSleepTime_ = std::chrono::microseconds::zero();
360     std::chrono::microseconds recordKernelReadTime_ = std::chrono::microseconds::zero();
361 #endif
362     size_t lostSamples_ = 0;
363     size_t lostNonSamples_ = 0;
364 
365     std::unique_ptr<RingBuffer> recordBuf_ {nullptr};
366     bool recordBufReady_ = false;
367     std::mutex mtxRrecordBuf_;
368     std::condition_variable cvRecordBuf_;
369     std::thread readRecordBufThread_;
370     std::atomic_bool readRecordThreadRunning_ = false;
371     bool startedTracking_ = false;
372     bool isLowPriorityThread_ = false;
373     void RecordLoop();
374     void StatLoop();
375     bool IsRecordInMmap();
376     void ReadRecordsFromMmaps();
377     bool GetRecordFromMmap(MmapFd &mmap);
378     void GetRecordFieldFromMmap(MmapFd &mmap, void *dest, size_t pos, size_t size);
379     void MoveRecordToBuf(MmapFd &mmap);
380     size_t GetCallChainPosInSampleRecord(const perf_event_attr &attr);
381     size_t GetStackSizePosInSampleRecord(MmapFd &mmap);
382     bool CutStackAndMove(MmapFd &mmap);
383     void ReadRecordFromBuf();
384     size_t CalcBufferSize();
385     bool PrepareRecordThread();
386     void WaitRecordThread();
387     bool HaveTargetsExit(const std::chrono::steady_clock::time_point &startTime);
388     void ExitReadRecordBufThread();
389 
390     enum EventSpaceType {
391         UNKNOW = 0,
392         USER = 1,
393         KERNEL = 2,
394         USER_KERNEL = 3,
395     };
396     uint8_t eventSpaceType_ = EventSpaceType::UNKNOW;
397 
398     bool inherit_ = false;
399     std::vector<pid_t> pids_;
400     std::vector<pid_t> cpus_;
401     std::vector<OHOS::UniqueFd> groups_;
402     std::chrono::milliseconds timeOut_;    // milliseconds
403     std::chrono::milliseconds timeReport_; // means same as timeOut
404     bool verboseReport_ = false;
405     bool prepared_ = false;
406     ConfigTable traceConfigTable;
407 
408     unsigned int samplePeriod_ = 0;
409     unsigned int sampleFreq_ = 0;
410 
411     struct FdItem {
412         OHOS::UniqueFd fd;
413         int cpu;
414         pid_t pid;
415         __u64 eventCount;
416         mutable uint64_t perf_id_ = 0;
GetPrefIdFdItem417         uint64_t GetPrefId() const
418         {
419             if (perf_id_ == 0) {
420                 read_format_no_group readNoGroupValue;
421                 if (read(fd, &readNoGroupValue, sizeof(readNoGroupValue)) > 0) {
422                     perf_id_ = readNoGroupValue.id;
423                 } else {
424                     HLOGW("read failed with fd %d", fd.Get());
425                 }
426             }
427             return perf_id_;
428         }
429     };
430     struct EventItem {
431         std::string typeName;
432         std::string configName;
433         perf_event_attr attr = {};
434         std::vector<FdItem> fdItems;
435     };
436     struct EventGroupItem {
437         std::vector<EventItem> eventItems;
438     };
439     std::vector<EventGroupItem> eventGroupItem_;
440 
441     std::map<int, MmapFd> cpuMmap_;
442     std::vector<MmapFd *> MmapRecordHeap_;
443 
444 #if !is_mingw
445     std::vector<struct pollfd> pollFds_;
446 #endif
447     const int pollTimeOut_ = 500; // ms
448     size_t pageSize_ = 4096;
449     bool systemTarget_ = false;
450     bool excludeHiperf_ = false;
451     pid_t selfPid_ = -1;
452     unsigned int mmapPages_ = 0;
453     int clockId_ = -1;
454     uint64_t branchSampleType_ = 0;
455 
456     SampleStackType sampleStackType_ = SampleStackType::NONE;
457     uint32_t dwarfSampleStackSize_ = MAX_SAMPLE_STACK_SIZE;
458 
459     // read records from the ring buffer singleton
460     void ReadRecordFromBuffer();
461     void ReadRecordFromBufferThread();
462 
463     std::unique_ptr<TrackedCommand> trackedCommand_ = {};
464 
465     StatCallBack reportCallBack_;
466     RecordCallBack recordCallBack_;
467 
468     void LoadTracepointEventTypesFromSystem();
469     bool PerfEventsEnable(bool);
470     bool AddEvent(perf_type_id type, __u64 config, bool excludeUser = false,
471                   bool excludeKernel = false, bool followGroup = false);
472     bool AddEvent(const std::string &eventString, bool followGroup = false);
473     bool IsEventSupport(perf_type_id type, __u64 config);
474     bool IsEventAttrSupport(perf_event_attr &attr);
475 
476     std::chrono::time_point<std::chrono::steady_clock> trackingStartTime_;
477     std::chrono::time_point<std::chrono::steady_clock> trackingEndTime_;
478     std::chrono::time_point<std::chrono::steady_clock> readingStartTime_;
479 
480     std::map<std::string, std::unique_ptr<CountEvent>> countEvents_;
481 
482     void PutAllCpus();
483     bool PrepareFdEvents();
484     bool CreateFdEvents();
485     bool StatReport(const __u64 &durationInSec);
486     bool CreateMmap(const FdItem &item, const perf_event_attr &attr);
487 
GetDefaultAttr()488     const perf_event_attr *GetDefaultAttr()
489     {
490         HLOG_ASSERT(eventGroupItem_.size() > 0);
491         HLOG_ASSERT(eventGroupItem_[0].eventItems.size() > 0);
492         return &(eventGroupItem_.at(0).eventItems.at(0).attr);
493     };
494 
495     OHOS::UniqueFd Open(perf_event_attr &attr, pid_t pid = 0, int cpu = -1, int group_fd = -1,
496                         unsigned long flags = 0);
497     std::unique_ptr<perf_event_attr> CreateDefaultAttr(perf_type_id type, __u64 config);
498 };
499 } // namespace HiPerf
500 } // namespace Developtools
501 } // namespace OHOS
502 #endif // HIPERF_PERF_EVENTS_H
503