1 /*
2 // Copyright (c) 2019 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 "DeviceMgmt.hpp"
18 #include "PSUEvent.hpp"
19 #include "PSUSensor.hpp"
20 #include "PwmSensor.hpp"
21 #include "SensorPaths.hpp"
22 #include "Thresholds.hpp"
23 #include "Utils.hpp"
24 #include "VariantVisitors.hpp"
25
26 #include <boost/algorithm/string/case_conv.hpp>
27 #include <boost/algorithm/string/replace.hpp>
28 #include <boost/asio/error.hpp>
29 #include <boost/asio/io_context.hpp>
30 #include <boost/asio/post.hpp>
31 #include <boost/asio/steady_timer.hpp>
32 #include <boost/container/flat_map.hpp>
33 #include <boost/container/flat_set.hpp>
34 #include <phosphor-logging/lg2.hpp>
35 #include <sdbusplus/asio/connection.hpp>
36 #include <sdbusplus/asio/object_server.hpp>
37 #include <sdbusplus/bus.hpp>
38 #include <sdbusplus/bus/match.hpp>
39 #include <sdbusplus/exception.hpp>
40 #include <sdbusplus/message.hpp>
41 #include <sdbusplus/message/native_types.hpp>
42
43 #include <algorithm>
44 #include <array>
45 #include <cctype>
46 #include <chrono>
47 #include <cmath>
48 #include <cstddef>
49 #include <cstdint>
50 #include <exception>
51 #include <filesystem>
52 #include <fstream>
53 #include <functional>
54 #include <iterator>
55 #include <memory>
56 #include <regex>
57 #include <stdexcept>
58 #include <string>
59 #include <string_view>
60 #include <utility>
61 #include <variant>
62 #include <vector>
63
64 static std::regex i2cDevRegex(R"((\/i2c\-\d+\/\d+-[a-fA-F0-9]{4,4})(\/|$))");
65
66 static const I2CDeviceTypeMap sensorTypes{
67 {"ADC128D818", I2CDeviceType{"adc128d818", true}},
68 {"ADM1266", I2CDeviceType{"adm1266", true}},
69 {"ADM1272", I2CDeviceType{"adm1272", true}},
70 {"ADM1275", I2CDeviceType{"adm1275", true}},
71 {"ADM1278", I2CDeviceType{"adm1278", true}},
72 {"ADM1293", I2CDeviceType{"adm1293", true}},
73 {"ADS1015", I2CDeviceType{"ads1015", true}},
74 {"ADS7830", I2CDeviceType{"ads7830", true}},
75 {"AHE50DC_FAN", I2CDeviceType{"ahe50dc_fan", true}},
76 {"BMR490", I2CDeviceType{"bmr490", true}},
77 {"cffps", I2CDeviceType{"cffps", true}},
78 {"cffps1", I2CDeviceType{"cffps", true}},
79 {"cffps2", I2CDeviceType{"cffps", true}},
80 {"cffps3", I2CDeviceType{"cffps", true}},
81 {"CRPS185", I2CDeviceType{"crps185", true}},
82 {"DPS800", I2CDeviceType{"dps800", true}},
83 {"INA219", I2CDeviceType{"ina219", true}},
84 {"INA226", I2CDeviceType{"ina226", true}},
85 {"INA230", I2CDeviceType{"ina230", true}},
86 {"INA233", I2CDeviceType{"ina233", true}},
87 {"INA238", I2CDeviceType{"ina238", true}},
88 {"IPSPS1", I2CDeviceType{"ipsps1", true}},
89 {"IR35221", I2CDeviceType{"ir35221", true}},
90 {"IR38060", I2CDeviceType{"ir38060", true}},
91 {"IR38164", I2CDeviceType{"ir38164", true}},
92 {"IR38263", I2CDeviceType{"ir38263", true}},
93 {"ISL28022", I2CDeviceType{"isl28022", true}},
94 {"ISL68137", I2CDeviceType{"isl68137", true}},
95 {"ISL68220", I2CDeviceType{"isl68220", true}},
96 {"ISL68223", I2CDeviceType{"isl68223", true}},
97 {"ISL69225", I2CDeviceType{"isl69225", true}},
98 {"ISL69243", I2CDeviceType{"isl69243", true}},
99 {"ISL69260", I2CDeviceType{"isl69260", true}},
100 {"LM25066", I2CDeviceType{"lm25066", true}},
101 {"LM5066I", I2CDeviceType{"lm5066i", true}},
102 {"LTC2945", I2CDeviceType{"ltc2945", true}},
103 {"LTC4286", I2CDeviceType{"ltc4286", true}},
104 {"LTC4287", I2CDeviceType{"ltc4287", true}},
105 {"MAX5970", I2CDeviceType{"max5970", true}},
106 {"MAX11607", I2CDeviceType{"max11607", false}},
107 {"MAX11615", I2CDeviceType{"max11615", false}},
108 {"MAX11617", I2CDeviceType{"max11617", false}},
109 {"MAX16601", I2CDeviceType{"max16601", true}},
110 {"MAX20710", I2CDeviceType{"max20710", true}},
111 {"MAX20730", I2CDeviceType{"max20730", true}},
112 {"MAX20734", I2CDeviceType{"max20734", true}},
113 {"MAX20796", I2CDeviceType{"max20796", true}},
114 {"MAX34451", I2CDeviceType{"max34451", true}},
115 {"MP2856", I2CDeviceType{"mp2856", true}},
116 {"MP2857", I2CDeviceType{"mp2857", true}},
117 {"MP2869", I2CDeviceType{"mp2869", true}},
118 {"MP2971", I2CDeviceType{"mp2971", true}},
119 {"MP2973", I2CDeviceType{"mp2973", true}},
120 {"MP2975", I2CDeviceType{"mp2975", true}},
121 {"MP5023", I2CDeviceType{"mp5023", true}},
122 {"MP5990", I2CDeviceType{"mp5990", true}},
123 {"MP5998", I2CDeviceType{"mp5998", true}},
124 {"MP9945", I2CDeviceType{"mp9945", true}},
125 {"MP29612", I2CDeviceType{"mp29612", true}},
126 {"MPQ8785", I2CDeviceType{"mpq8785", true}},
127 {"NCP4200", I2CDeviceType{"ncp4200", true}},
128 {"PLI1209BC", I2CDeviceType{"pli1209bc", true}},
129 {"pmbus", I2CDeviceType{"pmbus", true}},
130 {"PXE1610", I2CDeviceType{"pxe1610", true}},
131 {"SQ52206", I2CDeviceType{"sq52206", true}},
132 {"RAA228000", I2CDeviceType{"raa228000", true}},
133 {"RAA228004", I2CDeviceType{"raa228004", true}},
134 {"RAA228006", I2CDeviceType{"raa228006", true}},
135 {"RAA228228", I2CDeviceType{"raa228228", true}},
136 {"RAA228620", I2CDeviceType{"raa228620", true}},
137 {"RAA229001", I2CDeviceType{"raa229001", true}},
138 {"RAA229004", I2CDeviceType{"raa229004", true}},
139 {"RAA229126", I2CDeviceType{"raa229126", true}},
140 {"RTQ6056", I2CDeviceType{"rtq6056", false}},
141 {"SBRMI", I2CDeviceType{"sbrmi", true}},
142 {"smpro_hwmon", I2CDeviceType{"smpro", false}},
143 {"SY24655", I2CDeviceType{"sy24655", true}},
144 {"TDA38640", I2CDeviceType{"tda38640", true}},
145 {"TPS25990", I2CDeviceType{"tps25990", true}},
146 {"TPS53679", I2CDeviceType{"tps53679", true}},
147 {"TPS546D24", I2CDeviceType{"tps546d24", true}},
148 {"XDP710", I2CDeviceType{"xdp710", true}},
149 {"XDPE11280", I2CDeviceType{"xdpe11280", true}},
150 {"XDPE12284", I2CDeviceType{"xdpe12284", true}},
151 {"XDPE152C4", I2CDeviceType{"xdpe152c4", true}},
152 };
153
154 enum class DevTypes
155 {
156 Unknown = 0,
157 HWMON,
158 IIO
159 };
160
161 struct DevParams
162 {
163 unsigned int matchIndex = 0;
164 std::string matchRegEx;
165 std::string nameRegEx;
166 };
167
168 static boost::container::flat_map<std::string, std::shared_ptr<PSUSensor>>
169 sensors;
170 static boost::container::flat_map<std::string, std::unique_ptr<PSUCombineEvent>>
171 combineEvents;
172 static boost::container::flat_map<std::string, std::unique_ptr<PwmSensor>>
173 pwmSensors;
174 static boost::container::flat_map<std::string, std::string> sensorTable;
175 static boost::container::flat_map<std::string, PSUProperty> labelMatch;
176 static EventPathList eventMatch;
177 static EventPathList limitEventMatch;
178
179 static boost::container::flat_map<size_t, bool> cpuPresence;
180 static boost::container::flat_map<DevTypes, DevParams> devParamMap;
181
182 // Function CheckEvent will check each attribute from eventMatch table in the
183 // sysfs. If the attributes exists in sysfs, then store the complete path
184 // of the attribute into eventPathList.
checkEvent(const std::string & directory,const EventPathList & eventMatch,EventPathList & eventPathList)185 void checkEvent(const std::string& directory, const EventPathList& eventMatch,
186 EventPathList& eventPathList)
187 {
188 for (const auto& match : eventMatch)
189 {
190 const std::vector<std::string>& eventAttrs = match.second;
191 const std::string& eventName = match.first;
192 for (const auto& eventAttr : eventAttrs)
193 {
194 std::string eventPath = directory;
195 eventPath += "/";
196 eventPath += eventAttr;
197
198 std::ifstream eventFile(eventPath);
199 if (!eventFile.good())
200 {
201 continue;
202 }
203
204 eventPathList[eventName].push_back(eventPath);
205 }
206 }
207 }
208
209 // Check Group Events which contains more than one targets in each combine
210 // events.
checkGroupEvent(const std::string & directory,GroupEventPathList & groupEventPathList)211 void checkGroupEvent(const std::string& directory,
212 GroupEventPathList& groupEventPathList)
213 {
214 EventPathList pathList;
215 std::vector<std::filesystem::path> eventPaths;
216 if (!findFiles(std::filesystem::path(directory), R"(fan\d+_(alarm|fault))",
217 eventPaths))
218 {
219 return;
220 }
221
222 for (const auto& eventPath : eventPaths)
223 {
224 std::string attrName = eventPath.filename();
225 pathList[attrName.substr(0, attrName.find('_'))].push_back(eventPath);
226 }
227 groupEventPathList["FanFault"] = pathList;
228 }
229
230 // Function checkEventLimits will check all the psu related xxx_input attributes
231 // in sysfs to see if xxx_crit_alarm xxx_lcrit_alarm xxx_max_alarm
232 // xxx_min_alarm exist, then store the existing paths of the alarm attributes
233 // to eventPathList.
checkEventLimits(const std::string & sensorPathStr,const EventPathList & limitEventMatch,EventPathList & eventPathList)234 void checkEventLimits(const std::string& sensorPathStr,
235 const EventPathList& limitEventMatch,
236 EventPathList& eventPathList)
237 {
238 auto attributePartPos = sensorPathStr.find_last_of('_');
239 if (attributePartPos == std::string::npos)
240 {
241 // There is no '_' in the string, skip it
242 return;
243 }
244 auto attributePart =
245 std::string_view(sensorPathStr).substr(attributePartPos + 1);
246 if (attributePart != "input")
247 {
248 // If the sensor is not xxx_input, skip it
249 return;
250 }
251
252 auto prefixPart = sensorPathStr.substr(0, attributePartPos + 1);
253 for (const auto& limitMatch : limitEventMatch)
254 {
255 const std::vector<std::string>& limitEventAttrs = limitMatch.second;
256 const std::string& eventName = limitMatch.first;
257 for (const auto& limitEventAttr : limitEventAttrs)
258 {
259 auto limitEventPath = prefixPart + limitEventAttr;
260 std::ifstream eventFile(limitEventPath);
261 if (!eventFile.good())
262 {
263 continue;
264 }
265 eventPathList[eventName].push_back(limitEventPath);
266 }
267 }
268 }
269
checkPWMSensor(const std::filesystem::path & sensorPath,std::string & labelHead,const std::string & interfacePath,std::shared_ptr<sdbusplus::asio::connection> & dbusConnection,sdbusplus::asio::object_server & objectServer,const std::string & psuName)270 static void checkPWMSensor(
271 const std::filesystem::path& sensorPath, std::string& labelHead,
272 const std::string& interfacePath,
273 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection,
274 sdbusplus::asio::object_server& objectServer, const std::string& psuName)
275 {
276 if (!labelHead.starts_with("fan"))
277 {
278 return;
279 }
280 std::string labelHeadIndex = labelHead.substr(3);
281
282 const std::string& sensorPathStr = sensorPath.string();
283 const std::string& pwmPathStr =
284 boost::replace_all_copy(sensorPathStr, "input", "target");
285 std::ifstream pwmFile(pwmPathStr);
286 if (!pwmFile.good())
287 {
288 return;
289 }
290
291 auto findPWMSensor = pwmSensors.find(psuName + labelHead);
292 if (findPWMSensor != pwmSensors.end())
293 {
294 return;
295 }
296
297 std::string name = "Pwm_";
298 name += psuName;
299 name += "_Fan_";
300 name += labelHeadIndex;
301
302 std::string objPath = interfacePath;
303 objPath += "_Fan_";
304 objPath += labelHeadIndex;
305
306 pwmSensors[psuName + labelHead] = std::make_unique<PwmSensor>(
307 name, pwmPathStr, dbusConnection, objectServer, objPath, "PSU");
308 }
309
createSensorsCallback(boost::asio::io_context & io,sdbusplus::asio::object_server & objectServer,std::shared_ptr<sdbusplus::asio::connection> & dbusConnection,const ManagedObjectType & sensorConfigs,const std::shared_ptr<boost::container::flat_set<std::string>> & sensorsChanged,bool activateOnly)310 static void createSensorsCallback(
311 boost::asio::io_context& io, sdbusplus::asio::object_server& objectServer,
312 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection,
313 const ManagedObjectType& sensorConfigs,
314 const std::shared_ptr<boost::container::flat_set<std::string>>&
315 sensorsChanged,
316 bool activateOnly)
317 {
318 int numCreated = 0;
319 bool firstScan = sensorsChanged == nullptr;
320
321 auto devices = instantiateDevices(sensorConfigs, sensors, sensorTypes);
322
323 std::vector<std::filesystem::path> pmbusPaths;
324 findFiles(std::filesystem::path("/sys/bus/iio/devices"), "name",
325 pmbusPaths);
326 findFiles(std::filesystem::path("/sys/class/hwmon"), "name", pmbusPaths);
327 if (pmbusPaths.empty())
328 {
329 lg2::error("No PSU sensors in system");
330 return;
331 }
332
333 boost::container::flat_set<std::string> directories;
334 for (const auto& pmbusPath : pmbusPaths)
335 {
336 EventPathList eventPathList;
337 GroupEventPathList groupEventPathList;
338
339 std::ifstream nameFile(pmbusPath);
340 if (!nameFile.good())
341 {
342 lg2::error("Failure finding '{PATH}'", "PATH", pmbusPath);
343 continue;
344 }
345
346 std::string pmbusName;
347 std::getline(nameFile, pmbusName);
348 nameFile.close();
349
350 if (!sensorTypes.contains(pmbusName))
351 {
352 // To avoid this error message, add your driver name to
353 // the pmbusNames vector at the top of this file.
354 lg2::error("'{NAME}' not found in sensor whitelist", "NAME",
355 pmbusName);
356 continue;
357 }
358
359 auto directory = pmbusPath.parent_path();
360
361 auto ret = directories.insert(directory.string());
362 if (!ret.second)
363 {
364 lg2::error("Duplicate path: '{PATH}'", "PATH", directory);
365 continue; // check if path has already been searched
366 }
367
368 DevTypes devType = DevTypes::HWMON;
369 std::string deviceName;
370 if (directory.parent_path() == "/sys/class/hwmon")
371 {
372 std::string devicePath =
373 std::filesystem::canonical(directory / "device");
374 std::smatch match;
375 // Find /i2c-<bus>/<bus>-<address> match in device path
376 std::regex_search(devicePath, match, i2cDevRegex);
377 if (match.empty())
378 {
379 lg2::error("Found bad device path: '{PATH}'", "PATH",
380 devicePath);
381 continue;
382 }
383 // Extract <bus>-<address>
384 std::string matchStr = match[1];
385 deviceName = matchStr.substr(matchStr.find_last_of('/') + 1);
386 }
387 else
388 {
389 deviceName =
390 std::filesystem::canonical(directory).parent_path().stem();
391 devType = DevTypes::IIO;
392 }
393
394 size_t bus = 0;
395 size_t addr = 0;
396 if (!getDeviceBusAddr(deviceName, bus, addr))
397 {
398 continue;
399 }
400
401 const SensorBaseConfigMap* baseConfig = nullptr;
402 const SensorData* sensorData = nullptr;
403 const std::string* interfacePath = nullptr;
404 std::string sensorType;
405 size_t thresholdConfSize = 0;
406
407 for (const auto& [path, cfgData] : sensorConfigs)
408 {
409 sensorData = &cfgData;
410 for (const auto& [type, dt] : sensorTypes)
411 {
412 auto sensorBase = sensorData->find(configInterfaceName(type));
413 if (sensorBase != sensorData->end())
414 {
415 baseConfig = &sensorBase->second;
416 sensorType = type;
417 break;
418 }
419 }
420 if (baseConfig == nullptr)
421 {
422 lg2::error("error finding base configuration for '{NAME}'",
423 "NAME", deviceName);
424 continue;
425 }
426
427 auto configBus = baseConfig->find("Bus");
428 auto configAddress = baseConfig->find("Address");
429
430 if (configBus == baseConfig->end() ||
431 configAddress == baseConfig->end())
432 {
433 lg2::error("error finding necessary entry in configuration");
434 continue;
435 }
436
437 const uint64_t* confBus =
438 std::get_if<uint64_t>(&(configBus->second));
439 const uint64_t* confAddr =
440 std::get_if<uint64_t>(&(configAddress->second));
441 if (confBus == nullptr || confAddr == nullptr)
442 {
443 lg2::error("Cannot get bus or address, invalid configuration");
444 continue;
445 }
446
447 if ((*confBus != bus) || (*confAddr != addr))
448 {
449 lg2::debug(
450 "Configuration skipping '{CONFBUS}'-'{CONFADDR}' because not {BUS}-{ADDR}",
451 "CONFBUS", *confBus, "CONFADDR", *confAddr, "BUS", bus,
452 "ADDR", addr);
453 continue;
454 }
455
456 std::vector<thresholds::Threshold> confThresholds;
457 if (!parseThresholdsFromConfig(*sensorData, confThresholds))
458 {
459 lg2::error("error populating total thresholds");
460 }
461 thresholdConfSize = confThresholds.size();
462
463 interfacePath = &path.str;
464 break;
465 }
466 if (interfacePath == nullptr)
467 {
468 // To avoid this error message, add your export map entry,
469 // from Entity Manager, to sensorTypes at the top of this file.
470 lg2::error("failed to find match for '{NAME}'", "NAME", deviceName);
471 continue;
472 }
473
474 auto findI2CDev = devices.find(*interfacePath);
475
476 std::shared_ptr<I2CDevice> i2cDev;
477 if (findI2CDev != devices.end())
478 {
479 if (activateOnly && !findI2CDev->second.second)
480 {
481 continue;
482 }
483 i2cDev = findI2CDev->second.first;
484 }
485
486 auto findPSUName = baseConfig->find("Name");
487 if (findPSUName == baseConfig->end())
488 {
489 lg2::error("could not determine configuration name for '{NAME}'",
490 "NAME", deviceName);
491 continue;
492 }
493 const std::string* psuName =
494 std::get_if<std::string>(&(findPSUName->second));
495 if (psuName == nullptr)
496 {
497 lg2::error("Cannot find psu name, invalid configuration");
498 continue;
499 }
500
501 auto findCPU = baseConfig->find("CPURequired");
502 if (findCPU != baseConfig->end())
503 {
504 size_t index = std::visit(VariantToIntVisitor(), findCPU->second);
505 auto presenceFind = cpuPresence.find(index);
506 if (presenceFind == cpuPresence.end() || !presenceFind->second)
507 {
508 continue;
509 }
510 }
511
512 // on rescans, only update sensors we were signaled by
513 if (!firstScan)
514 {
515 std::string psuNameStr = "/" + escapeName(*psuName);
516 auto it =
517 std::find_if(sensorsChanged->begin(), sensorsChanged->end(),
518 [psuNameStr](std::string& s) {
519 return s.ends_with(psuNameStr);
520 });
521
522 if (it == sensorsChanged->end())
523 {
524 continue;
525 }
526 sensorsChanged->erase(it);
527 }
528 checkEvent(directory.string(), eventMatch, eventPathList);
529 checkGroupEvent(directory.string(), groupEventPathList);
530
531 PowerState readState = getPowerState(*baseConfig);
532
533 /* Check if there are more sensors in the same interface */
534 int i = 1;
535 std::vector<std::string> psuNames;
536 do
537 {
538 // Individual string fields: Name, Name1, Name2, Name3, ...
539 psuNames.push_back(
540 escapeName(std::get<std::string>(findPSUName->second)));
541 findPSUName = baseConfig->find("Name" + std::to_string(i++));
542 } while (findPSUName != baseConfig->end());
543
544 std::vector<std::filesystem::path> sensorPaths;
545 if (!findFiles(directory, devParamMap[devType].matchRegEx, sensorPaths,
546 0))
547 {
548 lg2::error("No PSU non-label sensor in PSU");
549 continue;
550 }
551
552 /* read max value in sysfs for in, curr, power, temp, ... */
553 if (!findFiles(directory, R"(\w\d+_max$)", sensorPaths, 0))
554 {
555 lg2::debug("No max name in PSU");
556 }
557
558 float pollRate = getPollRate(*baseConfig, PSUSensor::defaultSensorPoll);
559
560 /* Find array of labels to be exposed if it is defined in config */
561 std::vector<std::string> findLabels;
562 auto findLabelObj = baseConfig->find("Labels");
563 if (findLabelObj != baseConfig->end())
564 {
565 findLabels =
566 std::get<std::vector<std::string>>(findLabelObj->second);
567 }
568
569 std::regex sensorNameRegEx(devParamMap[devType].nameRegEx);
570 std::smatch matches;
571
572 for (const auto& sensorPath : sensorPaths)
573 {
574 bool maxLabel = false;
575 std::string labelHead;
576 std::string sensorPathStr = sensorPath.string();
577 std::string sensorNameStr = sensorPath.filename();
578 std::string sensorNameSubStr;
579 if (std::regex_search(sensorNameStr, matches, sensorNameRegEx))
580 {
581 // hwmon *_input filename without number:
582 // in, curr, power, temp, ...
583 // iio in_*_raw filename without number:
584 // voltage, temp, pressure, ...
585 sensorNameSubStr = matches[devParamMap[devType].matchIndex];
586 }
587 else
588 {
589 lg2::error("Could not extract the alpha prefix from '{NAME}'",
590 "NAME", sensorNameStr);
591 continue;
592 }
593
594 std::string labelPath;
595
596 if (devType == DevTypes::HWMON)
597 {
598 /* find and differentiate _max and _input to replace "label" */
599 size_t pos = sensorPathStr.find('_');
600 if (pos != std::string::npos)
601 {
602 std::string sensorPathStrMax = sensorPathStr.substr(pos);
603 if (sensorPathStrMax == "_max")
604 {
605 labelPath = boost::replace_all_copy(sensorPathStr,
606 "max", "label");
607 maxLabel = true;
608 }
609 else
610 {
611 labelPath = boost::replace_all_copy(sensorPathStr,
612 "input", "label");
613 maxLabel = false;
614 }
615 }
616 else
617 {
618 continue;
619 }
620
621 std::ifstream labelFile(labelPath);
622 if (!labelFile.good())
623 {
624 lg2::debug(
625 "Input file '{PATH}' has no corresponding label file",
626 "PATH", sensorPath.string());
627 // hwmon *_input filename with number:
628 // temp1, temp2, temp3, ...
629 labelHead =
630 sensorNameStr.substr(0, sensorNameStr.find('_'));
631 }
632 else
633 {
634 std::string label;
635 std::getline(labelFile, label);
636 labelFile.close();
637 auto findSensor = sensors.find(label);
638 if (findSensor != sensors.end())
639 {
640 continue;
641 }
642
643 // hwmon corresponding *_label file contents:
644 // vin1, vout1, ...
645 labelHead = label.substr(0, label.find(' '));
646 }
647
648 /* append "max" for labelMatch */
649 if (maxLabel)
650 {
651 labelHead.insert(0, "max");
652 }
653
654 // Don't add PWM sensors if it's not in label list
655 if (!findLabels.empty())
656 {
657 /* Check if this labelHead is enabled in config file */
658 if (std::find(findLabels.begin(), findLabels.end(),
659 labelHead) == findLabels.end())
660 {
661 lg2::debug("could not find {LABEL} in the Labels list",
662 "LABEL", labelHead);
663 continue;
664 }
665 }
666 checkPWMSensor(sensorPath, labelHead, *interfacePath,
667 dbusConnection, objectServer, psuNames[0]);
668 }
669 else if (devType == DevTypes::IIO)
670 {
671 auto findIIOHyphen = sensorNameStr.find_last_of('_');
672 labelHead = sensorNameStr.substr(0, findIIOHyphen);
673 }
674
675 lg2::debug("Sensor type: {NAME}, label: {LABEL}", "NAME",
676 sensorNameSubStr, "LABEL", labelHead);
677
678 if (!findLabels.empty())
679 {
680 /* Check if this labelHead is enabled in config file */
681 if (std::find(findLabels.begin(), findLabels.end(),
682 labelHead) == findLabels.end())
683 {
684 lg2::debug("could not find '{LABEL}' in the Labels list",
685 "LABEL", labelHead);
686 continue;
687 }
688 }
689 auto it = std::find_if(labelHead.begin(), labelHead.end(),
690 static_cast<int (*)(int)>(std::isdigit));
691 std::string_view labelHeadView(
692 labelHead.data(), std::distance(labelHead.begin(), it));
693 auto findProperty =
694 labelMatch.find(static_cast<std::string>(labelHeadView));
695 if (findProperty == labelMatch.end())
696 {
697 lg2::debug(
698 "Could not find matching default property for '{LABEL}'",
699 "LABEL", labelHead);
700 continue;
701 }
702
703 // Protect the hardcoded labelMatch list from changes,
704 // by making a copy and modifying that instead.
705 // Avoid bleedthrough of one device's customizations to
706 // the next device, as each should be independently customizable.
707 PSUProperty psuProperty = findProperty->second;
708
709 // Use label head as prefix for reading from config file,
710 // example if temp1: temp1_Name, temp1_Scale, temp1_Min, ...
711 std::string keyName = labelHead + "_Name";
712 std::string keyScale = labelHead + "_Scale";
713 std::string keyMin = labelHead + "_Min";
714 std::string keyMax = labelHead + "_Max";
715 std::string keyOffset = labelHead + "_Offset";
716 std::string keyPowerState = labelHead + "_PowerState";
717
718 bool customizedName = false;
719 auto findCustomName = baseConfig->find(keyName);
720 if (findCustomName != baseConfig->end())
721 {
722 try
723 {
724 psuProperty.labelTypeName = std::visit(
725 VariantToStringVisitor(), findCustomName->second);
726 }
727 catch (const std::invalid_argument&)
728 {
729 lg2::error("Unable to parse '{NAME}'", "NAME", keyName);
730 continue;
731 }
732
733 // All strings are valid, including empty string
734 customizedName = true;
735 }
736
737 bool customizedScale = false;
738 auto findCustomScale = baseConfig->find(keyScale);
739 if (findCustomScale != baseConfig->end())
740 {
741 try
742 {
743 psuProperty.sensorScaleFactor = std::visit(
744 VariantToUnsignedIntVisitor(), findCustomScale->second);
745 }
746 catch (const std::invalid_argument&)
747 {
748 lg2::error("Unable to parse '{SCALE}'", "SCALE", keyScale);
749 continue;
750 }
751
752 // Avoid later division by zero
753 if (psuProperty.sensorScaleFactor > 0)
754 {
755 customizedScale = true;
756 }
757 else
758 {
759 lg2::error("Unable to accept '{SCALE}'", "SCALE", keyScale);
760 continue;
761 }
762 }
763
764 auto findCustomMin = baseConfig->find(keyMin);
765 if (findCustomMin != baseConfig->end())
766 {
767 try
768 {
769 psuProperty.minReading = std::visit(
770 VariantToDoubleVisitor(), findCustomMin->second);
771 }
772 catch (const std::invalid_argument&)
773 {
774 lg2::error("Unable to parse '{MIN}'", "MIN", keyMin);
775 continue;
776 }
777 }
778
779 auto findCustomMax = baseConfig->find(keyMax);
780 if (findCustomMax != baseConfig->end())
781 {
782 try
783 {
784 psuProperty.maxReading = std::visit(
785 VariantToDoubleVisitor(), findCustomMax->second);
786 }
787 catch (const std::invalid_argument&)
788 {
789 lg2::error("Unable to parse '{MAX}'", "MAX", keyMax);
790 continue;
791 }
792 }
793
794 auto findCustomOffset = baseConfig->find(keyOffset);
795 if (findCustomOffset != baseConfig->end())
796 {
797 try
798 {
799 psuProperty.sensorOffset = std::visit(
800 VariantToDoubleVisitor(), findCustomOffset->second);
801 }
802 catch (const std::invalid_argument&)
803 {
804 lg2::error("Unable to parse '{OFFSET}'", "OFFSET",
805 keyOffset);
806 continue;
807 }
808 }
809
810 // if we find label head power state set ,override the powerstate.
811 auto findPowerState = baseConfig->find(keyPowerState);
812 if (findPowerState != baseConfig->end())
813 {
814 std::string powerState = std::visit(VariantToStringVisitor(),
815 findPowerState->second);
816 setReadState(powerState, readState);
817 }
818 if (!(psuProperty.minReading < psuProperty.maxReading))
819 {
820 lg2::error("Min must be less than Max");
821 continue;
822 }
823
824 // If the sensor name is being customized by config file,
825 // then prefix/suffix composition becomes not necessary,
826 // and in fact not wanted, because it gets in the way.
827 std::string psuNameFromIndex;
828 std::string nameIndexStr = "1";
829 if (!customizedName)
830 {
831 /* Find out sensor name index for this label */
832 std::regex rgx("[A-Za-z]+([0-9]+)");
833 size_t nameIndex{0};
834 if (std::regex_search(labelHead, matches, rgx))
835 {
836 nameIndexStr = matches[1];
837 nameIndex = std::stoi(nameIndexStr);
838
839 // Decrement to preserve alignment, because hwmon
840 // human-readable filenames and labels use 1-based
841 // numbering, but the "Name", "Name1", "Name2", etc. naming
842 // convention (the psuNames vector) uses 0-based numbering.
843 if (nameIndex > 0)
844 {
845 --nameIndex;
846 }
847 }
848 else
849 {
850 nameIndex = 0;
851 }
852
853 if (psuNames.size() <= nameIndex)
854 {
855 lg2::error("Could not pair '{LABEL}' with a Name field",
856 "LABEL", labelHead);
857 continue;
858 }
859
860 psuNameFromIndex = psuNames[nameIndex];
861
862 lg2::debug("'{LABEL}' paired with '{NAME}' at index '{INDEX}'",
863 "LABEL", labelHead, "NAME", psuNameFromIndex,
864 "INDEX", nameIndex);
865 }
866
867 if (devType == DevTypes::HWMON)
868 {
869 checkEventLimits(sensorPathStr, limitEventMatch, eventPathList);
870 }
871
872 // Similarly, if sensor scaling factor is being customized,
873 // then the below power-of-10 constraint becomes unnecessary,
874 // as config should be able to specify an arbitrary divisor.
875 unsigned int factor = psuProperty.sensorScaleFactor;
876 if (!customizedScale)
877 {
878 // Preserve existing usage of hardcoded labelMatch table below
879 factor = std::pow(10.0, factor);
880
881 /* Change first char of substring to uppercase */
882 char firstChar =
883 static_cast<char>(std::toupper(sensorNameSubStr[0]));
884 std::string strScaleFactor =
885 firstChar + sensorNameSubStr.substr(1) + "ScaleFactor";
886
887 // Preserve existing configs by accepting earlier syntax,
888 // example CurrScaleFactor, PowerScaleFactor, ...
889 auto findScaleFactor = baseConfig->find(strScaleFactor);
890 if (findScaleFactor != baseConfig->end())
891 {
892 factor = std::visit(VariantToIntVisitor(),
893 findScaleFactor->second);
894 }
895
896 lg2::debug(
897 "Sensor scaling factor '{FACTOR}' string '{SCALE_FACTOR}'",
898 "FACTOR", factor, "SCALE_FACTOR", strScaleFactor);
899 }
900
901 std::vector<thresholds::Threshold> sensorThresholds;
902 if (!parseThresholdsFromConfig(*sensorData, sensorThresholds,
903 &labelHead))
904 {
905 lg2::error("error populating thresholds for '{NAME}'", "NAME",
906 sensorNameSubStr);
907 }
908
909 auto findSensorUnit = sensorTable.find(sensorNameSubStr);
910 if (findSensorUnit == sensorTable.end())
911 {
912 lg2::error("'{NAME}' is not a recognized sensor type", "NAME",
913 sensorNameSubStr);
914 continue;
915 }
916
917 lg2::debug("Sensor properties - Name: {NAME}, Scale: {SCALE}, "
918 "Min: {MIN}, Max: {MAX}, Offset: {OFFSET}",
919 "NAME", psuProperty.labelTypeName, "SCALE",
920 psuProperty.sensorScaleFactor, "MIN",
921 psuProperty.minReading, "MAX", psuProperty.maxReading,
922 "OFFSET", psuProperty.sensorOffset);
923
924 std::string sensorName = psuProperty.labelTypeName;
925 if (customizedName)
926 {
927 if (sensorName.empty())
928 {
929 // Allow selective disabling of an individual sensor,
930 // by customizing its name to an empty string.
931 lg2::error("Sensor disabled, empty string");
932 continue;
933 }
934 }
935 else
936 {
937 // Sensor name not customized, do prefix/suffix composition,
938 // preserving default behavior by using psuNameFromIndex.
939 sensorName = psuNameFromIndex + " " + psuProperty.labelTypeName;
940
941 // The labelTypeName of a fan can be:
942 // "Fan Speed 1", "Fan Speed 2", "Fan Speed 3" ...
943 if (labelHead == "fan" + nameIndexStr)
944 {
945 sensorName += nameIndexStr;
946 }
947 }
948
949 lg2::debug("Sensor name: {NAME}, path: {PATH}, type: {TYPE}",
950 "NAME", sensorName, "PATH", sensorPathStr, "TYPE",
951 sensorType);
952 // destruct existing one first if already created
953
954 auto& sensor = sensors[sensorName];
955 if (!activateOnly)
956 {
957 sensor = nullptr;
958 }
959
960 if (sensor != nullptr)
961 {
962 sensor->activate(sensorPathStr, i2cDev);
963 }
964 else
965 {
966 sensors[sensorName] = std::make_shared<PSUSensor>(
967 sensorPathStr, sensorType, objectServer, dbusConnection, io,
968 sensorName, std::move(sensorThresholds), *interfacePath,
969 readState, findSensorUnit->second, factor,
970 psuProperty.maxReading, psuProperty.minReading,
971 psuProperty.sensorOffset, labelHead, thresholdConfSize,
972 pollRate, i2cDev);
973 sensors[sensorName]->setupRead();
974 ++numCreated;
975 lg2::debug("Created '{NUM}' sensors so far", "NUM", numCreated);
976 }
977 }
978
979 if (devType == DevTypes::HWMON)
980 {
981 // OperationalStatus event
982 combineEvents[*psuName + "OperationalStatus"] = nullptr;
983 combineEvents[*psuName + "OperationalStatus"] =
984 std::make_unique<PSUCombineEvent>(
985 objectServer, dbusConnection, io, *psuName, readState,
986 eventPathList, groupEventPathList, "OperationalStatus",
987 pollRate);
988 }
989 }
990
991 lg2::debug("Created total of '{NUM}' sensors", "NUM", numCreated);
992 }
993
getPresentCpus(std::shared_ptr<sdbusplus::asio::connection> & dbusConnection)994 static void getPresentCpus(
995 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
996 {
997 static const int depth = 2;
998 static const int numKeys = 1;
999 GetSubTreeType cpuSubTree;
1000
1001 try
1002 {
1003 auto getItems = dbusConnection->new_method_call(
1004 mapper::busName, mapper::path, mapper::interface, mapper::subtree);
1005 getItems.append(cpuInventoryPath, static_cast<int32_t>(depth),
1006 std::array<const char*, numKeys>{
1007 "xyz.openbmc_project.Inventory.Item"});
1008 auto getItemsResp = dbusConnection->call(getItems);
1009 getItemsResp.read(cpuSubTree);
1010 }
1011 catch (sdbusplus::exception_t& e)
1012 {
1013 lg2::error("error getting inventory item subtree: '{ERR}'", "ERR", e);
1014 return;
1015 }
1016
1017 for (const auto& [path, objDict] : cpuSubTree)
1018 {
1019 auto obj = sdbusplus::message::object_path(path).filename();
1020 boost::to_lower(obj);
1021
1022 if (!obj.starts_with("cpu") || objDict.empty())
1023 {
1024 continue;
1025 }
1026 const std::string& owner = objDict.begin()->first;
1027
1028 std::variant<bool> respValue;
1029 try
1030 {
1031 auto getPresence = dbusConnection->new_method_call(
1032 owner.c_str(), path.c_str(), "org.freedesktop.DBus.Properties",
1033 "Get");
1034 getPresence.append("xyz.openbmc_project.Inventory.Item", "Present");
1035 auto resp = dbusConnection->call(getPresence);
1036 resp.read(respValue);
1037 }
1038 catch (sdbusplus::exception_t& e)
1039 {
1040 lg2::error("Error in getting CPU presence: '{ERR}'", "ERR", e);
1041 continue;
1042 }
1043
1044 auto* present = std::get_if<bool>(&respValue);
1045 if (present != nullptr && *present)
1046 {
1047 int cpuIndex = 0;
1048 try
1049 {
1050 cpuIndex = std::stoi(obj.substr(obj.size() - 1));
1051 }
1052 catch (const std::exception& e)
1053 {
1054 lg2::error("Error converting CPU index: '{ERR}'", "ERR", e);
1055 continue;
1056 }
1057 cpuPresence[cpuIndex] = *present;
1058 }
1059 }
1060 }
1061
createSensors(boost::asio::io_context & io,sdbusplus::asio::object_server & objectServer,std::shared_ptr<sdbusplus::asio::connection> & dbusConnection,const std::shared_ptr<boost::container::flat_set<std::string>> & sensorsChanged,bool activateOnly)1062 void createSensors(
1063 boost::asio::io_context& io, sdbusplus::asio::object_server& objectServer,
1064 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection,
1065 const std::shared_ptr<boost::container::flat_set<std::string>>&
1066 sensorsChanged,
1067 bool activateOnly)
1068 {
1069 auto getter = std::make_shared<GetSensorConfiguration>(
1070 dbusConnection, [&io, &objectServer, &dbusConnection, sensorsChanged,
1071 activateOnly](const ManagedObjectType& sensorConfigs) {
1072 createSensorsCallback(io, objectServer, dbusConnection,
1073 sensorConfigs, sensorsChanged, activateOnly);
1074 });
1075 std::vector<std::string> types;
1076 types.reserve(sensorTypes.size());
1077 for (const auto& [type, dt] : sensorTypes)
1078 {
1079 types.push_back(type);
1080 }
1081 getter->getConfiguration(types);
1082 }
1083
propertyInitialize()1084 void propertyInitialize()
1085 {
1086 sensorTable = {{"power", sensor_paths::unitWatts},
1087 {"curr", sensor_paths::unitAmperes},
1088 {"temp", sensor_paths::unitDegreesC},
1089 {"in", sensor_paths::unitVolts},
1090 {"voltage", sensor_paths::unitVolts},
1091 {"fan", sensor_paths::unitRPMs}};
1092
1093 labelMatch = {
1094 {"pin", PSUProperty("Input Power", 3000, 0, 6, 0)},
1095 {"pout", PSUProperty("Output Power", 3000, 0, 6, 0)},
1096 {"power", PSUProperty("Output Power", 3000, 0, 6, 0)},
1097 {"maxpin", PSUProperty("Max Input Power", 3000, 0, 6, 0)},
1098 {"vin", PSUProperty("Input Voltage", 300, 0, 3, 0)},
1099 {"maxvin", PSUProperty("Max Input Voltage", 300, 0, 3, 0)},
1100 {"in_voltage", PSUProperty("Output Voltage", 255, 0, 3, 0)},
1101 {"voltage", PSUProperty("Output Voltage", 255, 0, 3, 0)},
1102 {"vout", PSUProperty("Output Voltage", 255, 0, 3, 0)},
1103 {"vmon", PSUProperty("Auxiliary Input Voltage", 255, 0, 3, 0)},
1104 {"in", PSUProperty("Output Voltage", 255, 0, 3, 0)},
1105 {"iin", PSUProperty("Input Current", 20, 0, 3, 0)},
1106 {"iout", PSUProperty("Output Current", 255, 0, 3, 0)},
1107 {"curr", PSUProperty("Output Current", 255, 0, 3, 0)},
1108 {"maxiout", PSUProperty("Max Output Current", 255, 0, 3, 0)},
1109 {"temp", PSUProperty("Temperature", 127, -128, 3, 0)},
1110 {"maxtemp", PSUProperty("Max Temperature", 127, -128, 3, 0)},
1111 {"fan", PSUProperty("Fan Speed ", 30000, 0, 0, 0)}};
1112
1113 limitEventMatch = {{"PredictiveFailure", {"max_alarm", "min_alarm"}},
1114 {"Failure", {"crit_alarm", "lcrit_alarm"}}};
1115
1116 eventMatch = {{"PredictiveFailure", {"power1_alarm"}},
1117 {"Failure", {"in2_alarm"}},
1118 {"ACLost", {"in1_beep"}},
1119 {"ConfigureError", {"in1_fault"}}};
1120
1121 devParamMap = {
1122 {DevTypes::HWMON, {1, R"(\w\d+_input$)", "([A-Za-z]+)[0-9]*_"}},
1123 {DevTypes::IIO,
1124 {2, R"(\w+_(raw|input)$)", "^(in|out)_([A-Za-z]+)[0-9]*_"}}};
1125 }
1126
powerStateChanged(PowerState type,bool newState,boost::container::flat_map<std::string,std::shared_ptr<PSUSensor>> & sensors,boost::asio::io_context & io,sdbusplus::asio::object_server & objectServer,std::shared_ptr<sdbusplus::asio::connection> & dbusConnection)1127 static void powerStateChanged(
1128 PowerState type, bool newState,
1129 boost::container::flat_map<std::string, std::shared_ptr<PSUSensor>>&
1130 sensors,
1131 boost::asio::io_context& io, sdbusplus::asio::object_server& objectServer,
1132 std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
1133 {
1134 if (newState)
1135 {
1136 createSensors(io, objectServer, dbusConnection, nullptr, true);
1137 }
1138 else
1139 {
1140 for (auto& [path, sensor] : sensors)
1141 {
1142 if (sensor != nullptr && sensor->readState == type)
1143 {
1144 sensor->deactivate();
1145 }
1146 }
1147 }
1148 }
1149
main()1150 int main()
1151 {
1152 boost::asio::io_context io;
1153 auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
1154
1155 sdbusplus::asio::object_server objectServer(systemBus, true);
1156 objectServer.add_manager("/xyz/openbmc_project/sensors");
1157 objectServer.add_manager("/xyz/openbmc_project/control");
1158 systemBus->request_name("xyz.openbmc_project.PSUSensor");
1159 auto sensorsChanged =
1160 std::make_shared<boost::container::flat_set<std::string>>();
1161
1162 propertyInitialize();
1163
1164 auto powerCallBack = [&io, &objectServer,
1165 &systemBus](PowerState type, bool state) {
1166 powerStateChanged(type, state, sensors, io, objectServer, systemBus);
1167 };
1168
1169 setupPowerMatchCallback(systemBus, powerCallBack);
1170
1171 boost::asio::post(io, [&]() {
1172 createSensors(io, objectServer, systemBus, nullptr, false);
1173 });
1174 boost::asio::steady_timer filterTimer(io);
1175 std::function<void(sdbusplus::message_t&)> eventHandler =
1176 [&](sdbusplus::message_t& message) {
1177 if (message.is_method_error())
1178 {
1179 lg2::error("callback method error");
1180 return;
1181 }
1182 sensorsChanged->insert(message.get_path());
1183 filterTimer.expires_after(std::chrono::seconds(3));
1184 filterTimer.async_wait([&](const boost::system::error_code& ec) {
1185 if (ec == boost::asio::error::operation_aborted)
1186 {
1187 return;
1188 }
1189 if (ec)
1190 {
1191 lg2::error("timer error");
1192 }
1193 createSensors(io, objectServer, systemBus, sensorsChanged,
1194 false);
1195 });
1196 };
1197
1198 boost::asio::steady_timer cpuFilterTimer(io);
1199 std::function<void(sdbusplus::message_t&)> cpuPresenceHandler =
1200 [&](sdbusplus::message_t& message) {
1201 std::string path = message.get_path();
1202 boost::to_lower(path);
1203
1204 sdbusplus::message::object_path cpuPath(path);
1205 std::string cpuName = cpuPath.filename();
1206 if (!cpuName.starts_with("cpu"))
1207 {
1208 return;
1209 }
1210 size_t index = 0;
1211 try
1212 {
1213 index = std::stoi(path.substr(path.size() - 1));
1214 }
1215 catch (const std::invalid_argument&)
1216 {
1217 lg2::error("Found invalid path: '{PATH}'", "PATH", path);
1218 return;
1219 }
1220
1221 std::string objectName;
1222 boost::container::flat_map<std::string, std::variant<bool>> values;
1223 message.read(objectName, values);
1224 auto findPresence = values.find("Present");
1225 if (findPresence == values.end())
1226 {
1227 return;
1228 }
1229 try
1230 {
1231 cpuPresence[index] = std::get<bool>(findPresence->second);
1232 }
1233 catch (const std::bad_variant_access& err)
1234 {
1235 return;
1236 }
1237
1238 if (!cpuPresence[index])
1239 {
1240 return;
1241 }
1242 cpuFilterTimer.expires_after(std::chrono::seconds(1));
1243 cpuFilterTimer.async_wait([&](const boost::system::error_code& ec) {
1244 if (ec == boost::asio::error::operation_aborted)
1245 {
1246 return;
1247 }
1248 if (ec)
1249 {
1250 lg2::error("timer error");
1251 return;
1252 }
1253 createSensors(io, objectServer, systemBus, nullptr, false);
1254 });
1255 };
1256
1257 std::vector<std::unique_ptr<sdbusplus::bus::match_t>> matches =
1258 setupPropertiesChangedMatches(*systemBus, sensorTypes, eventHandler);
1259
1260 matches.emplace_back(std::make_unique<sdbusplus::bus::match_t>(
1261 static_cast<sdbusplus::bus_t&>(*systemBus),
1262 "type='signal',member='PropertiesChanged',path_namespace='" +
1263 std::string(cpuInventoryPath) +
1264 "',arg0namespace='xyz.openbmc_project.Inventory.Item'",
1265 cpuPresenceHandler));
1266
1267 getPresentCpus(systemBus);
1268
1269 setupManufacturingModeMatch(*systemBus);
1270 io.run();
1271 }
1272