PerfSensorGroup.cpp 11 KB
Newer Older
1
2
3
//================================================================================
// Name        : PerfSensorGroup.cpp
// Author      : Micha Mueller, Carla Guillen
Micha Müller's avatar
Micha Müller committed
4
// Contact     : info@dcdb.it
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Copyright   : Leibniz Supercomputing Centre
// Description : Source file for Perfevent sensor group class.
//================================================================================

//================================================================================
// This file is part of DCDB (DataCenter DataBase)
// Copyright (C) 2018-2019 Leibniz Supercomputing Centre
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//================================================================================
27

28
29
#include "PerfSensorGroup.h"

30
31
32
#include <algorithm>
#include <functional>
#include <limits.h>
33
#include <unistd.h>
34
35
36

#include <asm/unistd.h>

37
#include <linux/hw_breakpoint.h>
38
#include <linux/perf_event.h>
39
40
41

#include <sys/ioctl.h>
#include <sys/sysinfo.h>
42
43
44
45

//the read group data will have this format
struct read_format {
	uint64_t nr;
46
47
	uint64_t time_enabled; /* if PERF_FORMAT_TOTAL_TIME_ENABLED */
	uint64_t time_running; /* if PERF_FORMAT_TOTAL_TIME_RUNNING */
48
49
50
51
52
53
	struct {
		uint64_t value;
		uint64_t id;
	} values[];
};

54
55
56
57
58
59
PerfSensorGroup::PerfSensorGroup(const std::string &name)
    : SensorGroupTemplate(name),
      _htAggregation(0),
      _maxCorrection(20),
      _buf(nullptr),
      _bufSize(0) {
60
}
61

62
63
64
65
66
67
PerfSensorGroup::PerfSensorGroup(const PerfSensorGroup &other)
    : SensorGroupTemplate(other),
      _htAggregation(other._htAggregation),
      _maxCorrection(other._maxCorrection),
      _buf(nullptr),
      _bufSize(0) {
68
69
}

70
PerfSensorGroup::~PerfSensorGroup() {
71
72
73
74
75
	if (_buf) {
		delete[] _buf;
	}
}

76
77
78
79
80
81
PerfSensorGroup &PerfSensorGroup::operator=(const PerfSensorGroup &other) {
	SensorGroupTemplate::operator=(other);
	_htAggregation = other._htAggregation;
	_maxCorrection = other._maxCorrection;
	_buf = nullptr;
	_bufSize = 0;
82

83
	return *this;
84
85
}

86
void PerfSensorGroup::execOnInit() {
87
88
89
90
91
	//clear vectors in case this method gets called multiple times, although it shouldn't
	_sensorBins.clear();
	_cpuBinMapping.clear();

	for (int i = 0; i < get_nprocs(); i++) {
92
93
		_cpuBinMapping.push_back(-1);
	}
94
95
96

	//Sort sensors into bins. Every bin equals an perf-event group
	for (auto s : _sensors) {
97
98
99
100
101
102
103
104
105
106
		int cpu = s->getCpu();
		int bin = _cpuBinMapping[cpu];

		if (bin != -1) {
			_sensorBins[bin].sensors.push_back(s);
		} else {
			sensorBin bin(s, cpu);
			_sensorBins.push_back(bin);
			_cpuBinMapping[cpu] = _sensorBins.size() - 1;
		}
107
108
109
110
	}

	//sanity check: all bins should have the same number of sensors
	if (_sensorBins.size() == 0) {
111
112
		LOG(error) << "Sensorgroup " << _groupName << " failed to sort sensors!";
		return;
113
114
	}
	size_t binSensorSize = _sensorBins.front().sensors.size();
115
116
117
118
119
	for (auto &b : _sensorBins) {
		if (b.sensors.size() != binSensorSize) {
			LOG(error) << "Sensorgroup " << _groupName << " sensor number missmatch!";
			return;
		}
120
121
122
	}

	//sort bins, so that the sensor ordering is equal in every bin (useful in case of hyper-threading aggregation
123
124
125
126
127
128
129
130
	for (auto &b : _sensorBins) {
		std::sort(b.sensors.begin(), b.sensors.end(), [](const S_Ptr &lhs, const S_Ptr &rhs) {
			if (lhs->getType() == rhs->getType()) {
				return lhs->getConfig() < rhs->getConfig();
			} else {
				return lhs->getType() < rhs->getType();
			}
		});
131
132
133
	}

	_sensorBins.shrink_to_fit();
134
	_cpuBinMapping.shrink_to_fit();
135

136
137
138
139
140
141
142
143
144
145
146
147
148
149
	/* Allocate buffer to read in later. Reading struct has the following format:
	 *
	 *	struct read_format {
	 *		u64 nr;            // The number of events
	 *		u64 time_enabled;  // if PERF_FORMAT_TOTAL_TIME_ENABLED
	 *		u64 time_running;  // if PERF_FORMAT_TOTAL_TIME_RUNNING
	 *		struct {
	 *			u64 value;     // The value of the event
	 *			u64 id;        // if PERF_FORMAT_ID
	 *		} values[nr];
	 *	};
	 *
	 *	Therefore we require 16 byte per sensor plus an additional 8*3 byte
	 */
150
	std::size_t bufSize = binSensorSize * 16 + 24;
151
152
153
154
155
156
157
158
	if (!_buf) {
		_buf = new char[bufSize];
		_bufSize = bufSize;
	} else if (bufSize > _bufSize) {
		delete _buf;
		_buf = new char[bufSize];
		_bufSize = bufSize;
	}
159

160
	if (!_htAggregation) {
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
		return;
	}

	//set up convenience aggregator flags
	for (auto &b : _sensorBins) {
		int cpu = b.cpu;
		int mod = cpu % _htAggregation;

		//search bin with smallest multiple of mod as CPU. This bin will then aggregate us
		for (int agg = mod; agg < get_nprocs(); agg += _htAggregation) {
			int bin = _cpuBinMapping[agg];

			if (bin != -1) {
				//found bin aggregating us (could be ourselves)
				b.aggregator = false;
				_sensorBins[bin].aggregator = true;
177
178
179
180
181
				if(cpu != mod) {
					for(auto &sensor: b.sensors){
						sensor->setPublish(false);
					}
				}
182
183
184
				break;
			}
		}
185
	}
186
187
}

188
bool PerfSensorGroup::execOnStart() {
189
	//setup
190
191
192
	int                    fd, lfd;
	uint64_t               id;
	S_Ptr                  pc;
193
194
195
196
197
	struct perf_event_attr pe;

	memset(&pe, 0, sizeof(struct perf_event_attr));
	pe.size = sizeof(struct perf_event_attr);
	pe.exclude_kernel = 0;
198
	pe.exclude_hv = 0;
199
	pe.read_format = PERF_FORMAT_GROUP | PERF_FORMAT_ID | PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING;
200

201
	//open perfevent groups
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
	for (const auto &b : _sensorBins) {
		//perf_event_open() first sensor for cpu as group leader
		pc = b.sensors.front();

		pe.type = pc->getType();
		pe.config = pc->getConfig();
		pe.disabled = 1;

		fd = syscall(__NR_perf_event_open, &pe, -1, pc->getCpu(), -1, 0);
		if (fd == -1) {
			LOG(error) << "Failed to open performance-counter group \"" << _groupName << "\":" << strerror(errno);
			this->stop();
			return false;
		}
		ioctl(fd, PERF_EVENT_IOC_ID, &id);
		//store fd and id to make sensor distinguishable when reading
		pc->setFd(fd);
		pc->setId(id);

		lfd = fd;

		LOG(debug) << "  " << _groupName << "::" << pc->getName() << " opened with ID " << std::to_string(id);

		pe.disabled = 0;
		//open all other counters for the same cpu and attach them to group leader
		for (unsigned i = 1; i < b.sensors.size(); i++) {
			pc = b.sensors[i];

			pe.type = pc->getType();
			pe.config = pc->getConfig();

			fd = syscall(__NR_perf_event_open, &pe, -1, pc->getCpu(), lfd, 0);
			//store id, so that we can match counters with values later (see read())
			if (fd != -1) {
				pc->setFd(fd);
				int rc;
				if ((rc = ioctl(fd, PERF_EVENT_IOC_ID, &id)) == 0) {
					pc->setId(id);
					LOG(debug) << "  " << _groupName << "::" << pc->getName() << " opened with ID " << std::to_string(id);
				} else {
					LOG(debug) << "  " << _groupName << "::" << pc->getName() << " error obtaining ID: " << strerror(rc);
				}
			} else {
				LOG(debug) << "  " << _groupName << "::" << pc->getName() << " error opening perf file descriptor: " << strerror(errno);
			}
		}
248
249
	}

250
251
252
	for (const auto &b : _sensorBins) {
		ioctl(b.sensors.front()->getFd(), PERF_EVENT_IOC_RESET, 0);
		ioctl(b.sensors.front()->getFd(), PERF_EVENT_IOC_ENABLE, 0);
253
	}
254
	return true;
255
256
}

257
void PerfSensorGroup::execOnStop() {
258
	for (auto s : _sensors) {
259
260
261
262
263
		if (s->getFd() != -1) {
			close(s->getFd());
		}
		s->setFd(-1);
		s->setId(0);
264
	}
265
266
}

267
void PerfSensorGroup::read() {
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
	ureading_t reading;
	reading.timestamp = getTimestamp();

	struct read_format *rf = (struct read_format *)_buf;

	for (auto &bin : _sensorBins) {

		if (::read(bin.sensors.front()->getFd(), _buf, _bufSize) < 0) {
			LOG(error) << "Sensorgroup" << _groupName << " could not read value";
			return;
		}

		double   correction = 1;
		bool     validMeasurement = true;
		uint64_t time_enabled = calculateIntervalValue(bin.latest_time_enabled, rf->time_enabled, ULLONG_MAX);
		uint64_t time_running = calculateIntervalValue(bin.latest_time_running, rf->time_running, ULLONG_MAX);

		//store latest times
		bin.latest_time_enabled = rf->time_enabled;
		bin.latest_time_running = rf->time_running;

		if (time_running) {
			correction = static_cast<double>(time_enabled) / time_running;
		} else {
292
			LOG(debug) << "PerfSensorGroup: Group: " << _groupName << "::CPU" << bin.cpu << " could not be measured. Time running==0";
293
294
295
			validMeasurement = false;
		}
		if (correction > _maxCorrection || correction < 1) {
296
			LOG(debug) << "PerfSensorGroup: Group: " << _groupName << "::CPU" << bin.cpu << " could not be measured. Correction factor ==" << correction;
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
			validMeasurement = false;
		}

		if (!validMeasurement) {
			bin.lastValid = false;
			bin.latestValueValid = false;
			continue;
		}
		//iterate over all values returned by ::read()
		for (size_t i = 0; i < rf->nr; i++) {
			reading.value = rf->values[i].value;

			//iterate over all counters and find the one with matching id
			for (const auto &s : bin.sensors) {
				if (rf->values[i].id == s->getId()) {
312
#ifdef DEBUG
313
					LOG(debug) << _groupName << "::" << s->getName() << " raw reading: \"" << reading.value << "\"";
314
#endif
315
316
					if (bin.lastValid) {
						//storeReading takes care of delta computation and applies correction value on the result
317
						s->storeReading(reading, correction, !_htAggregation);
318
319
320
321
322
323
324
325
326
327
328
329
						bin.latestValueValid = true;
					} else {
						//Before we can compute correct values again after an invalid reading we have to update the lastRawValue first
						s->setLastURaw(reading.value);
					}
					break;
				}
			}
		}
		if (validMeasurement) { //set valid for the next time to read
			bin.lastValid = true;
		}
330
	}
331
332
333

	//hyper-threading aggregation logic
	if (_htAggregation) {
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
		for (const auto &bin : _sensorBins) {
			if (!(bin.aggregator)) {
				//this cpu bin gets aggregated
				continue;
			}

			for (size_t i = 0; i < bin.sensors.size(); i++) {
				reading_t reading;
				reading.value = 0;
				reading.timestamp = 0;

				for (int j = bin.cpu; j < get_nprocs(); j += _htAggregation) {
					int b = _cpuBinMapping[j];
					if (b != -1) {
						S_Ptr &sensor2 = _sensorBins[b].sensors[i];
						if (_sensorBins[b].latestValueValid) {
							reading.value += sensor2->getLatestValue().value;
							reading.timestamp = sensor2->getLatestValue().timestamp;
						}
					}
				}

				if (reading.timestamp != 0) {
					bin.sensors[i]->storeReadingGlobal(reading);
				}
			}
		}
361
	}
362
363
}

364
365
uint64_t PerfSensorGroup::calculateIntervalValue(uint64_t previous, uint64_t current, uint64_t maxValue) {
	if (previous > current) { //overflow
366
367
368
369
		return current + (maxValue - previous);
	}
	return current - previous;
}
Micha Mueller's avatar
Micha Mueller committed
370

371
void PerfSensorGroup::printGroupConfig(LOG_LEVEL ll, unsigned int leadingSpaces) {
372
373
374
	std::string leading(leadingSpaces, ' ');
	LOG_VAR(ll) << leading << "HT aggregation: " << (_htAggregation ? "true" : "false");
	LOG_VAR(ll) << leading << "maxCorrection: " << _maxCorrection;
375
}