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