Processor Counter Monitor
msr.h
1 // SPDX-License-Identifier: BSD-3-Clause
2 // Copyright (c) 2009-2012, Intel Corporation
3 // written by Roman Dementiev
4 // Austen Ott
5 
6 #ifndef CPUCounters_MSR_H
7 #define CPUCounters_MSR_H
8 
15 #include "types.h"
16 
17 #ifdef _MSC_VER
18 #include "windows.h"
19 #elif __APPLE__
20 #include <MSRAccessor.h>
21 #endif
22 
23 #include "mutex.h"
24 #include <memory>
25 
26 namespace pcm {
27 
28 bool noMSRMode();
29 
30 class MsrHandle
31 {
32 #ifdef _MSC_VER
33  HANDLE hDriver;
34 #elif __APPLE__
35  static MSRAccessor * driver;
36  static int num_handles;
37 #else
38  int32 fd;
39 #endif
40  uint32 cpu_id;
41  MsrHandle(); // forbidden
42  MsrHandle(const MsrHandle &); // forbidden
43  MsrHandle & operator = (const MsrHandle &); // forbidden
44 
45 public:
46  MsrHandle(uint32 cpu);
47  int32 read(uint64 msr_number, uint64 * value);
48  int32 write(uint64 msr_number, uint64 value);
49  int32 getCoreId() { return (int32)cpu_id; }
50 #ifdef __APPLE__
51  int32 buildTopology(uint32 num_cores, void *);
52  uint32 getNumInstances();
53  uint32 incrementNumInstances();
54  uint32 decrementNumInstances();
55 #endif
56  virtual ~MsrHandle();
57 };
58 
60 {
61  std::shared_ptr<MsrHandle> pHandle;
62  Mutex mutex;
63 
64  SafeMsrHandle(const SafeMsrHandle &); // forbidden
65  SafeMsrHandle & operator = (const SafeMsrHandle &); // forbidden
66 
67 public:
68  SafeMsrHandle() { }
69 
70  SafeMsrHandle(uint32 core_id) : pHandle(new MsrHandle(core_id))
71  { }
72 
73  int32 read(uint64 msr_number, uint64 * value)
74  {
75  if (pHandle)
76  return pHandle->read(msr_number, value);
77 
78  *value = 0;
79 
80  return (int32)sizeof(uint64);
81  }
82 
83  int32 write(uint64 msr_number, uint64 value)
84  {
85  if (pHandle)
86  return pHandle->write(msr_number, value);
87 
88  return (int32)sizeof(uint64);
89  }
90 
91  int32 getCoreId()
92  {
93  if (pHandle)
94  return pHandle->getCoreId();
95 
96  throw std::runtime_error("Core is offline");
97  }
98 
99  void lock()
100  {
101  mutex.lock();
102  }
103 
104  void unlock()
105  {
106  mutex.unlock();
107  }
108 
109 #ifdef __APPLE__
110  int32 buildTopology(uint32 num_cores, void * p)
111  {
112  if (pHandle)
113  return pHandle->buildTopology(num_cores, p);
114 
115  throw std::exception();
116  }
117  uint32 getNumInstances()
118  {
119  if (pHandle)
120  return pHandle->getNumInstances();
121 
122  throw std::exception();
123  }
124  uint32 incrementNumInstances()
125  {
126  if (pHandle)
127  return pHandle->incrementNumInstances();
128 
129  throw std::exception();
130  }
131  uint32 decrementNumInstances()
132  {
133  if (pHandle)
134  return pHandle->decrementNumInstances();
135 
136  throw std::exception();
137  }
138 #endif
139  virtual ~SafeMsrHandle()
140  { }
141 };
142 
143 } // namespace pcm
144 
145 #endif
Definition: MSRAccessor.h:10
Definition: msr.h:59
Internal type and constant definitions.
Definition: mutex.h:14
Definition: msr.h:30
Definition: bw.cpp:12