1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef SIMPLE_PERF_EVENT_SELECTION_SET_H_
18 #define SIMPLE_PERF_EVENT_SELECTION_SET_H_
19 
20 #include <poll.h>
21 #include <functional>
22 #include <map>
23 #include <vector>
24 
25 #include <base/macros.h>
26 
27 #include "event_fd.h"
28 #include "perf_event.h"
29 
30 struct EventType;
31 
32 // EventSelectionSet helps to monitor events.
33 // Firstly, the user creates an EventSelectionSet, and adds the specific event types to monitor.
34 // Secondly, the user defines how to monitor the events (by setting enable_on_exec flag,
35 // sample frequency, etc).
36 // Then, the user can start monitoring by ordering the EventSelectionSet to open perf event files
37 // and enable events (if enable_on_exec flag isn't used).
38 // After that, the user can read counters or read mapped event records.
39 // At last, the EventSelectionSet will clean up resources at destruction automatically.
40 
41 class EventSelectionSet {
42  public:
EventSelectionSet()43   EventSelectionSet() {
44   }
45 
Empty()46   bool Empty() const {
47     return selections_.empty();
48   }
49 
50   void AddEventType(const EventType& event_type);
51 
52   void EnableOnExec();
53   void SampleIdAll();
54   void SetSampleFreq(uint64_t sample_freq);
55   void SetSamplePeriod(uint64_t sample_period);
56 
57   bool OpenEventFilesForAllCpus();
58   bool OpenEventFilesForProcess(pid_t pid);
59   bool EnableEvents();
60   bool ReadCounters(std::map<const EventType*, std::vector<PerfCounter>>* counters_map);
61   void PreparePollForEventFiles(std::vector<pollfd>* pollfds);
62   bool MmapEventFiles(size_t mmap_pages);
63   bool ReadMmapEventData(std::function<bool(const char*, size_t)> callback);
64 
65   std::string FindEventFileNameById(uint64_t id);
66   const perf_event_attr& FindEventAttrByType(const EventType& event_type);
67   const std::vector<std::unique_ptr<EventFd>>& FindEventFdsByType(const EventType& event_type);
68 
69  private:
70   struct EventSelection {
71     const EventType* event_type;
72     perf_event_attr event_attr;
73     std::vector<std::unique_ptr<EventFd>> event_fds;
74   };
75   EventSelection* FindSelectionByType(const EventType& event_type);
76 
77   std::vector<EventSelection> selections_;
78 
79   DISALLOW_COPY_AND_ASSIGN(EventSelectionSet);
80 };
81 
82 #endif  // SIMPLE_PERF_EVENT_SELECTION_SET_H_
83