blob: 80f3f1c2b1b0f26ff5c0470fe8296aa4aa7f12cb [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";
63static constexpr const char* PECI_DEV = "/dev/peci0";
64static 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
74void createSensors(
75 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 {
92 return;
93 }
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";
105 return;
106 }
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";
115 return;
116 }
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 }
234}
235
236void reloadOverlay(const std::string& overlay)
237{
238 boost::process::child c1(DT_OVERLAY, "-d", OVERLAY_DIR, "-r", overlay);
239 c1.wait();
240 if (c1.exit_code())
241 {
242 if (DEBUG)
243 {
244 std::cout << "DTOverlay unload error with file " << overlay
245 << ". error: " << c1.exit_code() << "\n";
246 }
247
248 /* fall through anyway */
249 }
250
251 boost::process::child c2(DT_OVERLAY, "-d", OVERLAY_DIR, overlay);
252 c2.wait();
253 if (c2.exit_code())
254 {
255 std::cerr << "DTOverlay load error with file " << overlay
256 << ". error: " << c2.exit_code() << "\n";
257 return;
258 }
259}
260
261void detectCpu(boost::asio::deadline_timer& timer, boost::asio::io_service& io,
262 sdbusplus::asio::object_server& objectServer,
263 boost::container::flat_map<std::string,
264 std::unique_ptr<CPUSensor>>& sensors,
265 boost::container::flat_set<CPUConfig>& configs,
266 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
267{
268 auto file = open(PECI_DEV, O_RDWR);
269 if (file < 0)
270 {
271 std::cerr << "unable to open " << PECI_DEV << "\n";
272 std::exit(EXIT_FAILURE);
273 }
274
275 size_t rescanDelaySeconds = 0;
276 bool keepPinging = false;
277 for (CPUConfig& config : configs)
278 {
279 State state;
280 struct peci_ping_msg msg;
281 msg.addr = config.addr;
282 if (!ioctl(file, PECI_IOC_PING, &msg))
283 {
284 bool dimmReady = false;
285 for (unsigned int rank = 0; rank < RANK_NUM_MAX; rank++)
286 {
287 struct peci_rd_pkg_cfg_msg msg;
288 msg.addr = config.addr;
289 msg.index = MBX_INDEX_DDR_DIMM_TEMP;
290 msg.param = rank;
291 msg.rx_len = 4;
292 if (!ioctl(file, PECI_IOC_RD_PKG_CFG, &msg))
293 {
294 if (msg.pkg_config[0] || msg.pkg_config[1] ||
295 msg.pkg_config[2])
296 {
297 dimmReady = true;
298 break;
299 }
300 }
301 else
302 {
303 break;
304 }
305 }
306 if (dimmReady)
307 {
308 state = State::READY;
309 }
310 else
311 {
312 state = State::ON;
313 }
314 }
315 else
316 {
317 state = State::OFF;
318 }
319
320 if (config.state != state)
321 {
322 if (config.state == State::OFF)
323 {
324 reloadOverlay(config.ovName);
325 }
326 if (state != State::OFF)
327 {
328 if (state == State::ON)
329 {
330 rescanDelaySeconds = 1;
331 }
332 else
333 {
334 rescanDelaySeconds = 5;
335 }
336 }
337 config.state = state;
338 }
339
340 if (state != State::READY)
341 {
342 keepPinging = true;
343 }
344
345 if (DEBUG)
346 std::cout << config.ovName << ", state: " << state << "\n";
347 }
348
349 close(file);
350
351 if (rescanDelaySeconds)
352 {
353 std::this_thread::sleep_for(std::chrono::seconds(rescanDelaySeconds));
354 createSensors(io, objectServer, sensors, configs, dbusConnection);
355 }
356
357 if (keepPinging)
358 {
359 timer.expires_from_now(boost::posix_time::seconds(1));
360 timer.async_wait([&](const boost::system::error_code& ec) {
361 if (ec == boost::asio::error::operation_aborted)
362 {
363 /* we were canceled*/
364 return;
365 }
366 else if (ec)
367 {
368 std::cerr << "timer error\n";
369 return;
370 }
371 detectCpu(timer, io, objectServer, sensors, configs,
372 dbusConnection);
373 });
374 }
375}
376
377void getCpuConfig(const std::shared_ptr<sdbusplus::asio::connection>& systemBus,
378 boost::container::flat_set<CPUConfig>& configs)
379{
380 ManagedObjectType sensorConfigurations;
381 bool useCache = false;
382 // use new data the first time, then refresh
383 for (const char* type : SENSOR_TYPES)
384 {
385 if (!getSensorConfiguration(CONFIG_PREFIX + std::string(type),
386 systemBus, sensorConfigurations, useCache))
387 {
388 std::cerr
389 << "getCpuConfig: error communicating to entity manager\n";
390 return;
391 }
392 useCache = true;
393 }
394
395 // check PECI client addresses and DT overlay names from CPU configuration
396 // before starting ping operation
397 for (const char* type : SENSOR_TYPES)
398 {
399 for (const std::pair<sdbusplus::message::object_path, SensorData>&
400 sensor : sensorConfigurations)
401 {
402 for (const std::pair<
403 std::string,
404 boost::container::flat_map<std::string, BasicVariantType>>&
405 config : sensor.second)
406 {
407 if ((CONFIG_PREFIX + std::string(type)) != config.first)
408 {
409 continue;
410 }
411
412 auto findAddress = config.second.find("Address");
413 if (findAddress == config.second.end())
414 {
415 continue;
416 }
417 std::string addrStr = mapbox::util::apply_visitor(
418 VariantToStringVisitor(), findAddress->second);
419 int addr = std::stoi(addrStr, 0, 16);
420
421 auto findName = config.second.find("Name");
422 if (findName == config.second.end())
423 {
424 continue;
425 }
426 std::string nameRaw = mapbox::util::apply_visitor(
427 VariantToStringVisitor(), findName->second);
428 std::string name =
429 std::regex_replace(nameRaw, ILLEGAL_NAME_REGEX, "_");
430 std::string overlayName = name + "_" + type;
431
432 if (DEBUG)
433 {
434 std::cout << "addr: " << addr << "\n";
435 std::cout << "name: " << name << "\n";
436 std::cout << "type: " << type << "\n";
437 std::cout << "overlayName: " << overlayName << "\n";
438 }
439
440 configs.emplace(addr, overlayName, State::OFF);
441 }
442 }
443 }
444}
445
446int main(int argc, char** argv)
447{
448 boost::asio::io_service io;
449 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
450 boost::container::flat_set<CPUConfig> configs;
451
452 systemBus->request_name("xyz.openbmc_project.CPUSensor");
453 sdbusplus::asio::object_server objectServer(systemBus);
454 boost::container::flat_map<std::string, std::unique_ptr<CPUSensor>> sensors;
455 std::vector<std::unique_ptr<sdbusplus::bus::match::match>> matches;
456 boost::asio::deadline_timer pingTimer(io);
457 getCpuConfig(systemBus, configs);
458 if (configs.size())
459 {
460 detectCpu(pingTimer, io, objectServer, sensors, configs, systemBus);
461 }
462
463 boost::asio::deadline_timer filterTimer(io);
464 std::function<void(sdbusplus::message::message&)> eventHandler =
465 [&](sdbusplus::message::message& message) {
466 if (message.is_method_error())
467 {
468 std::cerr << "callback method error\n";
469 return;
470 }
471 // this implicitly cancels the timer
472 filterTimer.expires_from_now(boost::posix_time::seconds(1));
473
474 filterTimer.async_wait([&](const boost::system::error_code& ec) {
475 if (ec == boost::asio::error::operation_aborted)
476 {
477 /* we were canceled*/
478 return;
479 }
480 else if (ec)
481 {
482 std::cerr << "timer error\n";
483 return;
484 }
485
486 getCpuConfig(systemBus, configs);
487
488 if (configs.size())
489 {
490 detectCpu(pingTimer, io, objectServer, sensors, configs,
491 systemBus);
492 }
493 });
494 };
495
496 for (const char* type : SENSOR_TYPES)
497 {
498 auto match = std::make_unique<sdbusplus::bus::match::match>(
499 static_cast<sdbusplus::bus::bus&>(*systemBus),
500 "type='signal',member='PropertiesChanged',path_namespace='" +
501 std::string(INVENTORY_PATH) + "',arg0namespace='" +
502 CONFIG_PREFIX + type + "'",
503 eventHandler);
504 matches.emplace_back(std::move(match));
505 }
506
507 io.run();
508}