blob: def889b927a408095c472783a51fd9be30c4c36d [file] [log] [blame]
James Feist139cb572018-09-10 15:26:18 -07001/*
2// Copyright (c) 2018 Intel Corporation
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#include <fcntl.h>
18#include <linux/peci-ioctl.h>
19
20#include <CPUSensor.hpp>
21#include <Utils.hpp>
22#include <VariantVisitors.hpp>
23#include <boost/algorithm/string/predicate.hpp>
24#include <boost/algorithm/string/replace.hpp>
25#include <boost/container/flat_set.hpp>
26#include <boost/date_time/posix_time/posix_time.hpp>
27#include <boost/process/child.hpp>
28#include <experimental/filesystem>
29#include <fstream>
30#include <regex>
31#include <sdbusplus/asio/connection.hpp>
32#include <sdbusplus/asio/object_server.hpp>
33
34static constexpr bool DEBUG = false;
35
36enum State
37{
38 OFF, // host powered down
39 ON, // host powered on
40 READY // host powered on and mem test passed - fully ready
41};
42
43struct CPUConfig
44{
45 CPUConfig(const int& address, const std::string& overlayName,
46 const State& st) :
47 addr(address),
48 ovName(overlayName), state(st)
49 {
50 }
51 int addr;
52 std::string ovName;
53 State state;
54
55 bool operator<(const CPUConfig& rhs) const
56 {
57 return (ovName < rhs.ovName);
58 }
59};
60
61static constexpr const char* DT_OVERLAY = "/usr/bin/dtoverlay";
62static constexpr const char* OVERLAY_DIR = "/tmp/overlays";
Yoo, Jae Hyunf033e672018-10-17 12:07:54 -070063static constexpr const char* PECI_DEV = "/dev/peci-0";
James Feist139cb572018-09-10 15:26:18 -070064static constexpr const unsigned int RANK_NUM_MAX = 8;
65
66namespace fs = std::experimental::filesystem;
67static constexpr const char* CONFIG_PREFIX =
68 "xyz.openbmc_project.Configuration.";
69static constexpr std::array<const char*, 3> SENSOR_TYPES = {
70 "SkylakeCPU", "BroadwellCPU", "HaswellCPU"};
71
72const static std::regex ILLEGAL_NAME_REGEX("[^A-Za-z0-9_]");
73
Yoo, Jae Hyun60e14d32018-10-10 11:03:11 -070074bool createSensors(
James Feist139cb572018-09-10 15:26:18 -070075 boost::asio::io_service& io, sdbusplus::asio::object_server& objectServer,
76 boost::container::flat_map<std::string, std::unique_ptr<CPUSensor>>&
77 sensors,
78 boost::container::flat_set<CPUConfig>& configs,
79 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
80{
81 bool available = false;
82 for (CPUConfig cpu : configs)
83 {
84 if (cpu.state != State::OFF)
85 {
86 available = true;
87 break;
88 }
89 }
90 if (!available)
91 {
Yoo, Jae Hyun60e14d32018-10-10 11:03:11 -070092 return false;
James Feist139cb572018-09-10 15:26:18 -070093 }
94
95 // use new data the first time, then refresh
96 ManagedObjectType sensorConfigurations;
97 bool useCache = false;
98 for (const char* type : SENSOR_TYPES)
99 {
100 if (!getSensorConfiguration(CONFIG_PREFIX + std::string(type),
101 dbusConnection, sensorConfigurations,
102 useCache))
103 {
104 std::cerr << "error communicating to entity manager\n";
Yoo, Jae Hyun60e14d32018-10-10 11:03:11 -0700105 return false;
James Feist139cb572018-09-10 15:26:18 -0700106 }
107 useCache = true;
108 }
109
110 std::vector<fs::path> oemNamePaths;
111 if (!find_files(fs::path(R"(/sys/bus/peci/devices)"),
112 R"(peci\d+/\d+-.+/of_node/oemname1$)", oemNamePaths, 2))
113 {
114 std::cerr << "No CPU sensors in system\n";
Yoo, Jae Hyun60e14d32018-10-10 11:03:11 -0700115 return true;
James Feist139cb572018-09-10 15:26:18 -0700116 }
117
118 for (fs::path& oemNamePath : oemNamePaths)
119 {
120 std::ifstream nameFile(oemNamePath);
121 if (!nameFile.good())
122 {
123 std::cerr << "Failure reading " << oemNamePath << "\n";
124 continue;
125 }
126 std::string oemName;
127 std::getline(nameFile, oemName);
128 nameFile.close();
129 if (!oemName.size())
130 {
131 // shouldn't have an empty name file
132 continue;
133 }
134 oemName.pop_back(); // remove trailing null
135 if (DEBUG)
136 std::cout << "Checking: " << oemNamePath << ": " << oemName << "\n";
137
138 const SensorData* sensorData = nullptr;
139 const std::string* interfacePath = nullptr;
140 for (const std::pair<sdbusplus::message::object_path, SensorData>&
141 sensor : sensorConfigurations)
142 {
143 if (!boost::ends_with(sensor.first.str, oemName))
144 {
145 continue;
146 }
147 sensorData = &(sensor.second);
148 interfacePath = &(sensor.first.str);
149 break;
150 }
151 if (sensorData == nullptr)
152 {
153 std::cerr << "failed to find match for " << oemName << "\n";
154 continue;
155 }
156 const std::pair<std::string, boost::container::flat_map<
157 std::string, BasicVariantType>>*
158 baseConfiguration = nullptr;
159 std::string sensorObjectType;
160 for (const char* type : SENSOR_TYPES)
161 {
162 sensorObjectType = CONFIG_PREFIX + std::string(type);
163 auto sensorBase = sensorData->find(sensorObjectType);
164 if (sensorBase != sensorData->end())
165 {
166 baseConfiguration = &(*sensorBase);
167 break;
168 }
169 }
170
171 if (baseConfiguration == nullptr)
172 {
173 std::cerr << "error finding base configuration for" << oemName
174 << "\n";
175 continue;
176 }
177
178 auto findCpuId = baseConfiguration->second.find("CpuID");
179 if (findCpuId == baseConfiguration->second.end())
180 {
181 std::cerr << "could not determine CPU ID for " << oemName << "\n";
182 continue;
183 }
184 int cpuId = mapbox::util::apply_visitor(VariantToIntVisitor(),
185 findCpuId->second);
186
187 auto directory = oemNamePath.parent_path().parent_path();
188 std::vector<fs::path> inputPaths;
189 if (!find_files(fs::path(directory),
190 R"(peci-.+/hwmon/hwmon\d+/temp\d+_input$)", inputPaths,
191 0))
192 {
193 std::cerr << "No temperature sensors in system\n";
194 continue;
195 }
196
197 // iterate through all found temp sensors
198 for (auto& inputPath : inputPaths)
199 {
200 auto inputPathStr = inputPath.string();
201 auto labelPath =
202 boost::replace_all_copy(inputPathStr, "input", "label");
203 std::ifstream labelFile(labelPath);
204 if (!labelFile.good())
205 {
206 std::cerr << "Failure reading " << labelPath << "\n";
207 continue;
208 }
209 std::string label;
210 std::getline(labelFile, label);
211 labelFile.close();
212 std::string sensorName = label + " CPU" + std::to_string(cpuId);
213 std::vector<thresholds::Threshold> sensorThresholds;
214 std::string labelHead = label.substr(0, label.find(" "));
Yoo, Jae Hyunac18e142018-10-09 16:38:58 -0700215 ParseThresholdsFromConfig(*sensorData, sensorThresholds,
216 &labelHead);
James Feist139cb572018-09-10 15:26:18 -0700217 if (!sensorThresholds.size())
218 {
219 if (!ParseThresholdsFromAttr(sensorThresholds, inputPathStr,
220 CPUSensor::SENSOR_SCALE_FACTOR))
221 {
Yoo, Jae Hyunac18e142018-10-09 16:38:58 -0700222 std::cerr << "error populating thresholds for "
223 << sensorName << "\n";
James Feist139cb572018-09-10 15:26:18 -0700224 }
225 }
226 sensors[sensorName] = std::make_unique<CPUSensor>(
227 inputPathStr, sensorObjectType, objectServer, dbusConnection,
228 io, sensorName, std::move(sensorThresholds), *interfacePath);
229 if (DEBUG)
230 std::cout << "Mapped: " << inputPath << " to " << sensorName
231 << "\n";
232 }
233 }
Yoo, Jae Hyun60e14d32018-10-10 11:03:11 -0700234
235 return true;
James Feist139cb572018-09-10 15:26:18 -0700236}
237
238void reloadOverlay(const std::string& overlay)
239{
240 boost::process::child c1(DT_OVERLAY, "-d", OVERLAY_DIR, "-r", overlay);
241 c1.wait();
242 if (c1.exit_code())
243 {
244 if (DEBUG)
245 {
246 std::cout << "DTOverlay unload error with file " << overlay
247 << ". error: " << c1.exit_code() << "\n";
248 }
249
250 /* fall through anyway */
251 }
252
253 boost::process::child c2(DT_OVERLAY, "-d", OVERLAY_DIR, overlay);
254 c2.wait();
255 if (c2.exit_code())
256 {
257 std::cerr << "DTOverlay load error with file " << overlay
258 << ". error: " << c2.exit_code() << "\n";
259 return;
260 }
261}
262
263void detectCpu(boost::asio::deadline_timer& timer, boost::asio::io_service& io,
264 sdbusplus::asio::object_server& objectServer,
265 boost::container::flat_map<std::string,
266 std::unique_ptr<CPUSensor>>& sensors,
267 boost::container::flat_set<CPUConfig>& configs,
268 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
269{
270 auto file = open(PECI_DEV, O_RDWR);
271 if (file < 0)
272 {
273 std::cerr << "unable to open " << PECI_DEV << "\n";
274 std::exit(EXIT_FAILURE);
275 }
276
277 size_t rescanDelaySeconds = 0;
278 bool keepPinging = false;
279 for (CPUConfig& config : configs)
280 {
281 State state;
282 struct peci_ping_msg msg;
283 msg.addr = config.addr;
284 if (!ioctl(file, PECI_IOC_PING, &msg))
285 {
286 bool dimmReady = false;
287 for (unsigned int rank = 0; rank < RANK_NUM_MAX; rank++)
288 {
289 struct peci_rd_pkg_cfg_msg msg;
290 msg.addr = config.addr;
291 msg.index = MBX_INDEX_DDR_DIMM_TEMP;
292 msg.param = rank;
293 msg.rx_len = 4;
294 if (!ioctl(file, PECI_IOC_RD_PKG_CFG, &msg))
295 {
296 if (msg.pkg_config[0] || msg.pkg_config[1] ||
297 msg.pkg_config[2])
298 {
299 dimmReady = true;
300 break;
301 }
302 }
303 else
304 {
305 break;
306 }
307 }
308 if (dimmReady)
309 {
310 state = State::READY;
311 }
312 else
313 {
314 state = State::ON;
315 }
316 }
317 else
318 {
319 state = State::OFF;
320 }
321
322 if (config.state != state)
323 {
324 if (config.state == State::OFF)
325 {
326 reloadOverlay(config.ovName);
327 }
James Feist139cb572018-09-10 15:26:18 -0700328 config.state = state;
329 }
330
Yoo, Jae Hyun60e14d32018-10-10 11:03:11 -0700331 if (config.state != State::OFF)
332 {
333 if (config.state == State::ON)
334 {
335 rescanDelaySeconds = 1;
336 }
337 else
338 {
339 rescanDelaySeconds = 5;
340 }
341 }
342
343 if (config.state != State::READY)
James Feist139cb572018-09-10 15:26:18 -0700344 {
345 keepPinging = true;
346 }
347
348 if (DEBUG)
Yoo, Jae Hyun60e14d32018-10-10 11:03:11 -0700349 std::cout << config.ovName << ", state: " << config.state << "\n";
James Feist139cb572018-09-10 15:26:18 -0700350 }
351
352 close(file);
353
354 if (rescanDelaySeconds)
355 {
356 std::this_thread::sleep_for(std::chrono::seconds(rescanDelaySeconds));
Yoo, Jae Hyun60e14d32018-10-10 11:03:11 -0700357 if (!createSensors(io, objectServer, sensors, configs, dbusConnection))
358 {
359 keepPinging = true;
360 }
James Feist139cb572018-09-10 15:26:18 -0700361 }
362
363 if (keepPinging)
364 {
365 timer.expires_from_now(boost::posix_time::seconds(1));
366 timer.async_wait([&](const boost::system::error_code& ec) {
367 if (ec == boost::asio::error::operation_aborted)
368 {
369 /* we were canceled*/
370 return;
371 }
372 else if (ec)
373 {
374 std::cerr << "timer error\n";
375 return;
376 }
377 detectCpu(timer, io, objectServer, sensors, configs,
378 dbusConnection);
379 });
380 }
381}
382
383void getCpuConfig(const std::shared_ptr<sdbusplus::asio::connection>& systemBus,
384 boost::container::flat_set<CPUConfig>& configs)
385{
386 ManagedObjectType sensorConfigurations;
387 bool useCache = false;
388 // use new data the first time, then refresh
389 for (const char* type : SENSOR_TYPES)
390 {
391 if (!getSensorConfiguration(CONFIG_PREFIX + std::string(type),
392 systemBus, sensorConfigurations, useCache))
393 {
394 std::cerr
395 << "getCpuConfig: error communicating to entity manager\n";
396 return;
397 }
398 useCache = true;
399 }
400
401 // check PECI client addresses and DT overlay names from CPU configuration
402 // before starting ping operation
403 for (const char* type : SENSOR_TYPES)
404 {
405 for (const std::pair<sdbusplus::message::object_path, SensorData>&
406 sensor : sensorConfigurations)
407 {
408 for (const std::pair<
409 std::string,
410 boost::container::flat_map<std::string, BasicVariantType>>&
411 config : sensor.second)
412 {
413 if ((CONFIG_PREFIX + std::string(type)) != config.first)
414 {
415 continue;
416 }
417
418 auto findAddress = config.second.find("Address");
419 if (findAddress == config.second.end())
420 {
421 continue;
422 }
423 std::string addrStr = mapbox::util::apply_visitor(
424 VariantToStringVisitor(), findAddress->second);
425 int addr = std::stoi(addrStr, 0, 16);
426
427 auto findName = config.second.find("Name");
428 if (findName == config.second.end())
429 {
430 continue;
431 }
432 std::string nameRaw = mapbox::util::apply_visitor(
433 VariantToStringVisitor(), findName->second);
434 std::string name =
435 std::regex_replace(nameRaw, ILLEGAL_NAME_REGEX, "_");
436 std::string overlayName = name + "_" + type;
437
438 if (DEBUG)
439 {
440 std::cout << "addr: " << addr << "\n";
441 std::cout << "name: " << name << "\n";
442 std::cout << "type: " << type << "\n";
443 std::cout << "overlayName: " << overlayName << "\n";
444 }
445
446 configs.emplace(addr, overlayName, State::OFF);
447 }
448 }
449 }
450}
451
452int main(int argc, char** argv)
453{
454 boost::asio::io_service io;
455 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
456 boost::container::flat_set<CPUConfig> configs;
457
458 systemBus->request_name("xyz.openbmc_project.CPUSensor");
459 sdbusplus::asio::object_server objectServer(systemBus);
460 boost::container::flat_map<std::string, std::unique_ptr<CPUSensor>> sensors;
461 std::vector<std::unique_ptr<sdbusplus::bus::match::match>> matches;
462 boost::asio::deadline_timer pingTimer(io);
463 getCpuConfig(systemBus, configs);
464 if (configs.size())
465 {
466 detectCpu(pingTimer, io, objectServer, sensors, configs, systemBus);
467 }
468
469 boost::asio::deadline_timer filterTimer(io);
470 std::function<void(sdbusplus::message::message&)> eventHandler =
471 [&](sdbusplus::message::message& message) {
472 if (message.is_method_error())
473 {
474 std::cerr << "callback method error\n";
475 return;
476 }
477 // this implicitly cancels the timer
478 filterTimer.expires_from_now(boost::posix_time::seconds(1));
479
480 filterTimer.async_wait([&](const boost::system::error_code& ec) {
481 if (ec == boost::asio::error::operation_aborted)
482 {
483 /* we were canceled*/
484 return;
485 }
486 else if (ec)
487 {
488 std::cerr << "timer error\n";
489 return;
490 }
491
492 getCpuConfig(systemBus, configs);
493
494 if (configs.size())
495 {
496 detectCpu(pingTimer, io, objectServer, sensors, configs,
497 systemBus);
498 }
499 });
500 };
501
502 for (const char* type : SENSOR_TYPES)
503 {
504 auto match = std::make_unique<sdbusplus::bus::match::match>(
505 static_cast<sdbusplus::bus::bus&>(*systemBus),
506 "type='signal',member='PropertiesChanged',path_namespace='" +
507 std::string(INVENTORY_PATH) + "',arg0namespace='" +
508 CONFIG_PREFIX + type + "'",
509 eventHandler);
510 matches.emplace_back(std::move(match));
511 }
512
513 io.run();
514}