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