blob: d6d68ad16e2574f6482843c6fa160ab39db73673 [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(" "));
215 if (!ParseThresholdsFromConfig(*sensorData, sensorThresholds,
216 &labelHead))
217 {
218 continue;
219 }
220 if (!sensorThresholds.size())
221 {
222 if (!ParseThresholdsFromAttr(sensorThresholds, inputPathStr,
223 CPUSensor::SENSOR_SCALE_FACTOR))
224 {
225 continue;
226 }
227 }
228 sensors[sensorName] = std::make_unique<CPUSensor>(
229 inputPathStr, sensorObjectType, objectServer, dbusConnection,
230 io, sensorName, std::move(sensorThresholds), *interfacePath);
231 if (DEBUG)
232 std::cout << "Mapped: " << inputPath << " to " << sensorName
233 << "\n";
234 }
235 }
236}
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 }
328 if (state != State::OFF)
329 {
330 if (state == State::ON)
331 {
332 rescanDelaySeconds = 1;
333 }
334 else
335 {
336 rescanDelaySeconds = 5;
337 }
338 }
339 config.state = state;
340 }
341
342 if (state != State::READY)
343 {
344 keepPinging = true;
345 }
346
347 if (DEBUG)
348 std::cout << config.ovName << ", state: " << state << "\n";
349 }
350
351 close(file);
352
353 if (rescanDelaySeconds)
354 {
355 std::this_thread::sleep_for(std::chrono::seconds(rescanDelaySeconds));
356 createSensors(io, objectServer, sensors, configs, dbusConnection);
357 }
358
359 if (keepPinging)
360 {
361 timer.expires_from_now(boost::posix_time::seconds(1));
362 timer.async_wait([&](const boost::system::error_code& ec) {
363 if (ec == boost::asio::error::operation_aborted)
364 {
365 /* we were canceled*/
366 return;
367 }
368 else if (ec)
369 {
370 std::cerr << "timer error\n";
371 return;
372 }
373 detectCpu(timer, io, objectServer, sensors, configs,
374 dbusConnection);
375 });
376 }
377}
378
379void getCpuConfig(const std::shared_ptr<sdbusplus::asio::connection>& systemBus,
380 boost::container::flat_set<CPUConfig>& configs)
381{
382 ManagedObjectType sensorConfigurations;
383 bool useCache = false;
384 // use new data the first time, then refresh
385 for (const char* type : SENSOR_TYPES)
386 {
387 if (!getSensorConfiguration(CONFIG_PREFIX + std::string(type),
388 systemBus, sensorConfigurations, useCache))
389 {
390 std::cerr
391 << "getCpuConfig: error communicating to entity manager\n";
392 return;
393 }
394 useCache = true;
395 }
396
397 // check PECI client addresses and DT overlay names from CPU configuration
398 // before starting ping operation
399 for (const char* type : SENSOR_TYPES)
400 {
401 for (const std::pair<sdbusplus::message::object_path, SensorData>&
402 sensor : sensorConfigurations)
403 {
404 for (const std::pair<
405 std::string,
406 boost::container::flat_map<std::string, BasicVariantType>>&
407 config : sensor.second)
408 {
409 if ((CONFIG_PREFIX + std::string(type)) != config.first)
410 {
411 continue;
412 }
413
414 auto findAddress = config.second.find("Address");
415 if (findAddress == config.second.end())
416 {
417 continue;
418 }
419 std::string addrStr = mapbox::util::apply_visitor(
420 VariantToStringVisitor(), findAddress->second);
421 int addr = std::stoi(addrStr, 0, 16);
422
423 auto findName = config.second.find("Name");
424 if (findName == config.second.end())
425 {
426 continue;
427 }
428 std::string nameRaw = mapbox::util::apply_visitor(
429 VariantToStringVisitor(), findName->second);
430 std::string name =
431 std::regex_replace(nameRaw, ILLEGAL_NAME_REGEX, "_");
432 std::string overlayName = name + "_" + type;
433
434 if (DEBUG)
435 {
436 std::cout << "addr: " << addr << "\n";
437 std::cout << "name: " << name << "\n";
438 std::cout << "type: " << type << "\n";
439 std::cout << "overlayName: " << overlayName << "\n";
440 }
441
442 configs.emplace(addr, overlayName, State::OFF);
443 }
444 }
445 }
446}
447
448int main(int argc, char** argv)
449{
450 boost::asio::io_service io;
451 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
452 boost::container::flat_set<CPUConfig> configs;
453
454 systemBus->request_name("xyz.openbmc_project.CPUSensor");
455 sdbusplus::asio::object_server objectServer(systemBus);
456 boost::container::flat_map<std::string, std::unique_ptr<CPUSensor>> sensors;
457 std::vector<std::unique_ptr<sdbusplus::bus::match::match>> matches;
458 boost::asio::deadline_timer pingTimer(io);
459 getCpuConfig(systemBus, configs);
460 if (configs.size())
461 {
462 detectCpu(pingTimer, io, objectServer, sensors, configs, systemBus);
463 }
464
465 boost::asio::deadline_timer filterTimer(io);
466 std::function<void(sdbusplus::message::message&)> eventHandler =
467 [&](sdbusplus::message::message& message) {
468 if (message.is_method_error())
469 {
470 std::cerr << "callback method error\n";
471 return;
472 }
473 // this implicitly cancels the timer
474 filterTimer.expires_from_now(boost::posix_time::seconds(1));
475
476 filterTimer.async_wait([&](const boost::system::error_code& ec) {
477 if (ec == boost::asio::error::operation_aborted)
478 {
479 /* we were canceled*/
480 return;
481 }
482 else if (ec)
483 {
484 std::cerr << "timer error\n";
485 return;
486 }
487
488 getCpuConfig(systemBus, configs);
489
490 if (configs.size())
491 {
492 detectCpu(pingTimer, io, objectServer, sensors, configs,
493 systemBus);
494 }
495 });
496 };
497
498 for (const char* type : SENSOR_TYPES)
499 {
500 auto match = std::make_unique<sdbusplus::bus::match::match>(
501 static_cast<sdbusplus::bus::bus&>(*systemBus),
502 "type='signal',member='PropertiesChanged',path_namespace='" +
503 std::string(INVENTORY_PATH) + "',arg0namespace='" +
504 CONFIG_PREFIX + type + "'",
505 eventHandler);
506 matches.emplace_back(std::move(match));
507 }
508
509 io.run();
510}