xref: /openbmc/dbus-sensors/src/psu/PSUSensorMain.cpp (revision a205c6fae8ba05b86f9b04b4a5de47314fa9ba49)
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 <sdbusplus/asio/connection.hpp>
35 #include <sdbusplus/asio/object_server.hpp>
36 #include <sdbusplus/bus.hpp>
37 #include <sdbusplus/bus/match.hpp>
38 #include <sdbusplus/exception.hpp>
39 #include <sdbusplus/message.hpp>
40 #include <sdbusplus/message/native_types.hpp>
41 
42 #include <algorithm>
43 #include <array>
44 #include <cctype>
45 #include <chrono>
46 #include <cmath>
47 #include <cstddef>
48 #include <cstdint>
49 #include <exception>
50 #include <filesystem>
51 #include <fstream>
52 #include <functional>
53 #include <iostream>
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         std::cerr << "No PSU sensors in system\n";
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             std::cerr << "Failure finding pmbus path " << pmbusPath << "\n";
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             std::cerr << "Driver name " << pmbusName
345                       << " not found in sensor whitelist\n";
346             continue;
347         }
348 
349         auto directory = pmbusPath.parent_path();
350 
351         auto ret = directories.insert(directory.string());
352         if (!ret.second)
353         {
354             std::cerr << "Duplicate path " << directory.string() << "\n";
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                 std::cerr << "Found bad device path " << devicePath << "\n";
370                 continue;
371             }
372             // Extract <bus>-<address>
373             std::string matchStr = match[1];
374             deviceName = matchStr.substr(matchStr.find_last_of('/') + 1);
375         }
376         else
377         {
378             deviceName =
379                 std::filesystem::canonical(directory).parent_path().stem();
380             devType = DevTypes::IIO;
381         }
382 
383         size_t bus = 0;
384         size_t addr = 0;
385         if (!getDeviceBusAddr(deviceName, bus, addr))
386         {
387             continue;
388         }
389 
390         const SensorBaseConfigMap* baseConfig = nullptr;
391         const SensorData* sensorData = nullptr;
392         const std::string* interfacePath = nullptr;
393         std::string sensorType;
394         size_t thresholdConfSize = 0;
395 
396         for (const auto& [path, cfgData] : sensorConfigs)
397         {
398             sensorData = &cfgData;
399             for (const auto& [type, dt] : sensorTypes)
400             {
401                 auto sensorBase = sensorData->find(configInterfaceName(type));
402                 if (sensorBase != sensorData->end())
403                 {
404                     baseConfig = &sensorBase->second;
405                     sensorType = type;
406                     break;
407                 }
408             }
409             if (baseConfig == nullptr)
410             {
411                 std::cerr << "error finding base configuration for "
412                           << deviceName << "\n";
413                 continue;
414             }
415 
416             auto configBus = baseConfig->find("Bus");
417             auto configAddress = baseConfig->find("Address");
418 
419             if (configBus == baseConfig->end() ||
420                 configAddress == baseConfig->end())
421             {
422                 std::cerr << "error finding necessary entry in configuration\n";
423                 continue;
424             }
425 
426             const uint64_t* confBus =
427                 std::get_if<uint64_t>(&(configBus->second));
428             const uint64_t* confAddr =
429                 std::get_if<uint64_t>(&(configAddress->second));
430             if (confBus == nullptr || confAddr == nullptr)
431             {
432                 std::cerr
433                     << "Cannot get bus or address, invalid configuration\n";
434                 continue;
435             }
436 
437             if ((*confBus != bus) || (*confAddr != addr))
438             {
439                 if constexpr (debug)
440                 {
441                     std::cerr << "Configuration skipping " << *confBus << "-"
442                               << *confAddr << " because not " << bus << "-"
443                               << addr << "\n";
444                 }
445                 continue;
446             }
447 
448             std::vector<thresholds::Threshold> confThresholds;
449             if (!parseThresholdsFromConfig(*sensorData, confThresholds))
450             {
451                 std::cerr << "error populating total thresholds\n";
452             }
453             thresholdConfSize = confThresholds.size();
454 
455             interfacePath = &path.str;
456             break;
457         }
458         if (interfacePath == nullptr)
459         {
460             // To avoid this error message, add your export map entry,
461             // from Entity Manager, to sensorTypes at the top of this file.
462             std::cerr << "failed to find match for " << deviceName << "\n";
463             continue;
464         }
465 
466         auto findI2CDev = devices.find(*interfacePath);
467 
468         std::shared_ptr<I2CDevice> i2cDev;
469         if (findI2CDev != devices.end())
470         {
471             if (activateOnly && !findI2CDev->second.second)
472             {
473                 continue;
474             }
475             i2cDev = findI2CDev->second.first;
476         }
477 
478         auto findPSUName = baseConfig->find("Name");
479         if (findPSUName == baseConfig->end())
480         {
481             std::cerr << "could not determine configuration name for "
482                       << deviceName << "\n";
483             continue;
484         }
485         const std::string* psuName =
486             std::get_if<std::string>(&(findPSUName->second));
487         if (psuName == nullptr)
488         {
489             std::cerr << "Cannot find psu name, invalid configuration\n";
490             continue;
491         }
492 
493         auto findCPU = baseConfig->find("CPURequired");
494         if (findCPU != baseConfig->end())
495         {
496             size_t index = std::visit(VariantToIntVisitor(), findCPU->second);
497             auto presenceFind = cpuPresence.find(index);
498             if (presenceFind == cpuPresence.end() || !presenceFind->second)
499             {
500                 continue;
501             }
502         }
503 
504         // on rescans, only update sensors we were signaled by
505         if (!firstScan)
506         {
507             std::string psuNameStr = "/" + escapeName(*psuName);
508             auto it =
509                 std::find_if(sensorsChanged->begin(), sensorsChanged->end(),
510                              [psuNameStr](std::string& s) {
511                                  return s.ends_with(psuNameStr);
512                              });
513 
514             if (it == sensorsChanged->end())
515             {
516                 continue;
517             }
518             sensorsChanged->erase(it);
519         }
520         checkEvent(directory.string(), eventMatch, eventPathList);
521         checkGroupEvent(directory.string(), groupEventPathList);
522 
523         PowerState readState = getPowerState(*baseConfig);
524 
525         /* Check if there are more sensors in the same interface */
526         int i = 1;
527         std::vector<std::string> psuNames;
528         do
529         {
530             // Individual string fields: Name, Name1, Name2, Name3, ...
531             psuNames.push_back(
532                 escapeName(std::get<std::string>(findPSUName->second)));
533             findPSUName = baseConfig->find("Name" + std::to_string(i++));
534         } while (findPSUName != baseConfig->end());
535 
536         std::vector<std::filesystem::path> sensorPaths;
537         if (!findFiles(directory, devParamMap[devType].matchRegEx, sensorPaths,
538                        0))
539         {
540             std::cerr << "No PSU non-label sensor in PSU\n";
541             continue;
542         }
543 
544         /* read max value in sysfs for in, curr, power, temp, ... */
545         if (!findFiles(directory, R"(\w\d+_max$)", sensorPaths, 0))
546         {
547             if constexpr (debug)
548             {
549                 std::cerr << "No max name in PSU \n";
550             }
551         }
552 
553         float pollRate = getPollRate(*baseConfig, PSUSensor::defaultSensorPoll);
554 
555         /* Find array of labels to be exposed if it is defined in config */
556         std::vector<std::string> findLabels;
557         auto findLabelObj = baseConfig->find("Labels");
558         if (findLabelObj != baseConfig->end())
559         {
560             findLabels =
561                 std::get<std::vector<std::string>>(findLabelObj->second);
562         }
563 
564         std::regex sensorNameRegEx(devParamMap[devType].nameRegEx);
565         std::smatch matches;
566 
567         for (const auto& sensorPath : sensorPaths)
568         {
569             bool maxLabel = false;
570             std::string labelHead;
571             std::string sensorPathStr = sensorPath.string();
572             std::string sensorNameStr = sensorPath.filename();
573             std::string sensorNameSubStr;
574             if (std::regex_search(sensorNameStr, matches, sensorNameRegEx))
575             {
576                 // hwmon *_input filename without number:
577                 // in, curr, power, temp, ...
578                 // iio in_*_raw filename without number:
579                 // voltage, temp, pressure, ...
580                 sensorNameSubStr = matches[devParamMap[devType].matchIndex];
581             }
582             else
583             {
584                 std::cerr << "Could not extract the alpha prefix from "
585                           << sensorNameStr;
586                 continue;
587             }
588 
589             std::string labelPath;
590 
591             if (devType == DevTypes::HWMON)
592             {
593                 /* find and differentiate _max and _input to replace "label" */
594                 size_t pos = sensorPathStr.find('_');
595                 if (pos != std::string::npos)
596                 {
597                     std::string sensorPathStrMax = sensorPathStr.substr(pos);
598                     if (sensorPathStrMax == "_max")
599                     {
600                         labelPath = boost::replace_all_copy(sensorPathStr,
601                                                             "max", "label");
602                         maxLabel = true;
603                     }
604                     else
605                     {
606                         labelPath = boost::replace_all_copy(sensorPathStr,
607                                                             "input", "label");
608                         maxLabel = false;
609                     }
610                 }
611                 else
612                 {
613                     continue;
614                 }
615 
616                 std::ifstream labelFile(labelPath);
617                 if (!labelFile.good())
618                 {
619                     if constexpr (debug)
620                     {
621                         std::cerr << "Input file " << sensorPath
622                                   << " has no corresponding label file\n";
623                     }
624                     // hwmon *_input filename with number:
625                     // temp1, temp2, temp3, ...
626                     labelHead =
627                         sensorNameStr.substr(0, sensorNameStr.find('_'));
628                 }
629                 else
630                 {
631                     std::string label;
632                     std::getline(labelFile, label);
633                     labelFile.close();
634                     auto findSensor = sensors.find(label);
635                     if (findSensor != sensors.end())
636                     {
637                         continue;
638                     }
639 
640                     // hwmon corresponding *_label file contents:
641                     // vin1, vout1, ...
642                     labelHead = label.substr(0, label.find(' '));
643                 }
644 
645                 /* append "max" for labelMatch */
646                 if (maxLabel)
647                 {
648                     labelHead.insert(0, "max");
649                 }
650 
651                 checkPWMSensor(sensorPath, labelHead, *interfacePath,
652                                dbusConnection, objectServer, psuNames[0]);
653             }
654             else if (devType == DevTypes::IIO)
655             {
656                 auto findIIOHyphen = sensorNameStr.find_last_of('_');
657                 labelHead = sensorNameStr.substr(0, findIIOHyphen);
658             }
659 
660             if constexpr (debug)
661             {
662                 std::cerr << "Sensor type=\"" << sensorNameSubStr
663                           << "\" label=\"" << labelHead << "\"\n";
664             }
665 
666             if (!findLabels.empty())
667             {
668                 /* Check if this labelHead is enabled in config file */
669                 if (std::find(findLabels.begin(), findLabels.end(),
670                               labelHead) == findLabels.end())
671                 {
672                     if constexpr (debug)
673                     {
674                         std::cerr << "could not find " << labelHead
675                                   << " in the Labels list\n";
676                     }
677                     continue;
678                 }
679             }
680             auto it = std::find_if(labelHead.begin(), labelHead.end(),
681                                    static_cast<int (*)(int)>(std::isdigit));
682             std::string_view labelHeadView(
683                 labelHead.data(), std::distance(labelHead.begin(), it));
684             auto findProperty =
685                 labelMatch.find(static_cast<std::string>(labelHeadView));
686             if (findProperty == labelMatch.end())
687             {
688                 if constexpr (debug)
689                 {
690                     std::cerr << "Could not find matching default property for "
691                               << labelHead << "\n";
692                 }
693                 continue;
694             }
695 
696             // Protect the hardcoded labelMatch list from changes,
697             // by making a copy and modifying that instead.
698             // Avoid bleedthrough of one device's customizations to
699             // the next device, as each should be independently customizable.
700             PSUProperty psuProperty = findProperty->second;
701 
702             // Use label head as prefix for reading from config file,
703             // example if temp1: temp1_Name, temp1_Scale, temp1_Min, ...
704             std::string keyName = labelHead + "_Name";
705             std::string keyScale = labelHead + "_Scale";
706             std::string keyMin = labelHead + "_Min";
707             std::string keyMax = labelHead + "_Max";
708             std::string keyOffset = labelHead + "_Offset";
709             std::string keyPowerState = labelHead + "_PowerState";
710 
711             bool customizedName = false;
712             auto findCustomName = baseConfig->find(keyName);
713             if (findCustomName != baseConfig->end())
714             {
715                 try
716                 {
717                     psuProperty.labelTypeName = std::visit(
718                         VariantToStringVisitor(), findCustomName->second);
719                 }
720                 catch (const std::invalid_argument&)
721                 {
722                     std::cerr << "Unable to parse " << keyName << "\n";
723                     continue;
724                 }
725 
726                 // All strings are valid, including empty string
727                 customizedName = true;
728             }
729 
730             bool customizedScale = false;
731             auto findCustomScale = baseConfig->find(keyScale);
732             if (findCustomScale != baseConfig->end())
733             {
734                 try
735                 {
736                     psuProperty.sensorScaleFactor = std::visit(
737                         VariantToUnsignedIntVisitor(), findCustomScale->second);
738                 }
739                 catch (const std::invalid_argument&)
740                 {
741                     std::cerr << "Unable to parse " << keyScale << "\n";
742                     continue;
743                 }
744 
745                 // Avoid later division by zero
746                 if (psuProperty.sensorScaleFactor > 0)
747                 {
748                     customizedScale = true;
749                 }
750                 else
751                 {
752                     std::cerr << "Unable to accept " << keyScale << "\n";
753                     continue;
754                 }
755             }
756 
757             auto findCustomMin = baseConfig->find(keyMin);
758             if (findCustomMin != baseConfig->end())
759             {
760                 try
761                 {
762                     psuProperty.minReading = std::visit(
763                         VariantToDoubleVisitor(), findCustomMin->second);
764                 }
765                 catch (const std::invalid_argument&)
766                 {
767                     std::cerr << "Unable to parse " << keyMin << "\n";
768                     continue;
769                 }
770             }
771 
772             auto findCustomMax = baseConfig->find(keyMax);
773             if (findCustomMax != baseConfig->end())
774             {
775                 try
776                 {
777                     psuProperty.maxReading = std::visit(
778                         VariantToDoubleVisitor(), findCustomMax->second);
779                 }
780                 catch (const std::invalid_argument&)
781                 {
782                     std::cerr << "Unable to parse " << keyMax << "\n";
783                     continue;
784                 }
785             }
786 
787             auto findCustomOffset = baseConfig->find(keyOffset);
788             if (findCustomOffset != baseConfig->end())
789             {
790                 try
791                 {
792                     psuProperty.sensorOffset = std::visit(
793                         VariantToDoubleVisitor(), findCustomOffset->second);
794                 }
795                 catch (const std::invalid_argument&)
796                 {
797                     std::cerr << "Unable to parse " << keyOffset << "\n";
798                     continue;
799                 }
800             }
801 
802             // if we find label head power state set ,override the powerstate.
803             auto findPowerState = baseConfig->find(keyPowerState);
804             if (findPowerState != baseConfig->end())
805             {
806                 std::string powerState = std::visit(VariantToStringVisitor(),
807                                                     findPowerState->second);
808                 setReadState(powerState, readState);
809             }
810             if (!(psuProperty.minReading < psuProperty.maxReading))
811             {
812                 std::cerr << "Min must be less than Max\n";
813                 continue;
814             }
815 
816             // If the sensor name is being customized by config file,
817             // then prefix/suffix composition becomes not necessary,
818             // and in fact not wanted, because it gets in the way.
819             std::string psuNameFromIndex;
820             std::string nameIndexStr = "1";
821             if (!customizedName)
822             {
823                 /* Find out sensor name index for this label */
824                 std::regex rgx("[A-Za-z]+([0-9]+)");
825                 size_t nameIndex{0};
826                 if (std::regex_search(labelHead, matches, rgx))
827                 {
828                     nameIndexStr = matches[1];
829                     nameIndex = std::stoi(nameIndexStr);
830 
831                     // Decrement to preserve alignment, because hwmon
832                     // human-readable filenames and labels use 1-based
833                     // numbering, but the "Name", "Name1", "Name2", etc. naming
834                     // convention (the psuNames vector) uses 0-based numbering.
835                     if (nameIndex > 0)
836                     {
837                         --nameIndex;
838                     }
839                 }
840                 else
841                 {
842                     nameIndex = 0;
843                 }
844 
845                 if (psuNames.size() <= nameIndex)
846                 {
847                     std::cerr << "Could not pair " << labelHead
848                               << " with a Name field\n";
849                     continue;
850                 }
851 
852                 psuNameFromIndex = psuNames[nameIndex];
853 
854                 if constexpr (debug)
855                 {
856                     std::cerr << "Sensor label head " << labelHead
857                               << " paired with " << psuNameFromIndex
858                               << " at index " << nameIndex << "\n";
859                 }
860             }
861 
862             if (devType == DevTypes::HWMON)
863             {
864                 checkEventLimits(sensorPathStr, limitEventMatch, eventPathList);
865             }
866 
867             // Similarly, if sensor scaling factor is being customized,
868             // then the below power-of-10 constraint becomes unnecessary,
869             // as config should be able to specify an arbitrary divisor.
870             unsigned int factor = psuProperty.sensorScaleFactor;
871             if (!customizedScale)
872             {
873                 // Preserve existing usage of hardcoded labelMatch table below
874                 factor = std::pow(10.0, factor);
875 
876                 /* Change first char of substring to uppercase */
877                 char firstChar =
878                     static_cast<char>(std::toupper(sensorNameSubStr[0]));
879                 std::string strScaleFactor =
880                     firstChar + sensorNameSubStr.substr(1) + "ScaleFactor";
881 
882                 // Preserve existing configs by accepting earlier syntax,
883                 // example CurrScaleFactor, PowerScaleFactor, ...
884                 auto findScaleFactor = baseConfig->find(strScaleFactor);
885                 if (findScaleFactor != baseConfig->end())
886                 {
887                     factor = std::visit(VariantToIntVisitor(),
888                                         findScaleFactor->second);
889                 }
890 
891                 if constexpr (debug)
892                 {
893                     std::cerr << "Sensor scaling factor " << factor
894                               << " string " << strScaleFactor << "\n";
895                 }
896             }
897 
898             std::vector<thresholds::Threshold> sensorThresholds;
899             if (!parseThresholdsFromConfig(*sensorData, sensorThresholds,
900                                            &labelHead))
901             {
902                 std::cerr << "error populating thresholds for "
903                           << sensorNameSubStr << "\n";
904             }
905 
906             auto findSensorUnit = sensorTable.find(sensorNameSubStr);
907             if (findSensorUnit == sensorTable.end())
908             {
909                 std::cerr << sensorNameSubStr
910                           << " is not a recognized sensor type\n";
911                 continue;
912             }
913 
914             if constexpr (debug)
915             {
916                 std::cerr << "Sensor properties: Name \""
917                           << psuProperty.labelTypeName << "\" Scale "
918                           << psuProperty.sensorScaleFactor << " Min "
919                           << psuProperty.minReading << " Max "
920                           << psuProperty.maxReading << " Offset "
921                           << psuProperty.sensorOffset << "\n";
922             }
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                     std::cerr << "Sensor disabled, empty string\n";
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             if constexpr (debug)
950             {
951                 std::cerr << "Sensor name \"" << sensorName << "\" path \""
952                           << sensorPathStr << "\" type \"" << sensorType
953                           << "\"\n";
954             }
955             // destruct existing one first if already created
956 
957             auto& sensor = sensors[sensorName];
958             if (!activateOnly)
959             {
960                 sensor = nullptr;
961             }
962 
963             if (sensor != nullptr)
964             {
965                 sensor->activate(sensorPathStr, i2cDev);
966             }
967             else
968             {
969                 sensors[sensorName] = std::make_shared<PSUSensor>(
970                     sensorPathStr, sensorType, objectServer, dbusConnection, io,
971                     sensorName, std::move(sensorThresholds), *interfacePath,
972                     readState, findSensorUnit->second, factor,
973                     psuProperty.maxReading, psuProperty.minReading,
974                     psuProperty.sensorOffset, labelHead, thresholdConfSize,
975                     pollRate, i2cDev);
976                 sensors[sensorName]->setupRead();
977                 ++numCreated;
978                 if constexpr (debug)
979                 {
980                     std::cerr
981                         << "Created " << numCreated << " sensors so far\n";
982                 }
983             }
984         }
985 
986         if (devType == DevTypes::HWMON)
987         {
988             // OperationalStatus event
989             combineEvents[*psuName + "OperationalStatus"] = nullptr;
990             combineEvents[*psuName + "OperationalStatus"] =
991                 std::make_unique<PSUCombineEvent>(
992                     objectServer, dbusConnection, io, *psuName, readState,
993                     eventPathList, groupEventPathList, "OperationalStatus",
994                     pollRate);
995         }
996     }
997 
998     if constexpr (debug)
999     {
1000         std::cerr << "Created total of " << numCreated << " sensors\n";
1001     }
1002 }
1003 
getPresentCpus(std::shared_ptr<sdbusplus::asio::connection> & dbusConnection)1004 static void getPresentCpus(
1005     std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
1006 {
1007     static const int depth = 2;
1008     static const int numKeys = 1;
1009     GetSubTreeType cpuSubTree;
1010 
1011     try
1012     {
1013         auto getItems = dbusConnection->new_method_call(
1014             mapper::busName, mapper::path, mapper::interface, mapper::subtree);
1015         getItems.append(cpuInventoryPath, static_cast<int32_t>(depth),
1016                         std::array<const char*, numKeys>{
1017                             "xyz.openbmc_project.Inventory.Item"});
1018         auto getItemsResp = dbusConnection->call(getItems);
1019         getItemsResp.read(cpuSubTree);
1020     }
1021     catch (sdbusplus::exception_t& e)
1022     {
1023         std::cerr << "error getting inventory item subtree: " << e.what()
1024                   << "\n";
1025         return;
1026     }
1027 
1028     for (const auto& [path, objDict] : cpuSubTree)
1029     {
1030         auto obj = sdbusplus::message::object_path(path).filename();
1031         boost::to_lower(obj);
1032 
1033         if (!obj.starts_with("cpu") || objDict.empty())
1034         {
1035             continue;
1036         }
1037         const std::string& owner = objDict.begin()->first;
1038 
1039         std::variant<bool> respValue;
1040         try
1041         {
1042             auto getPresence = dbusConnection->new_method_call(
1043                 owner.c_str(), path.c_str(), "org.freedesktop.DBus.Properties",
1044                 "Get");
1045             getPresence.append("xyz.openbmc_project.Inventory.Item", "Present");
1046             auto resp = dbusConnection->call(getPresence);
1047             resp.read(respValue);
1048         }
1049         catch (sdbusplus::exception_t& e)
1050         {
1051             std::cerr << "Error in getting CPU presence: " << e.what() << "\n";
1052             continue;
1053         }
1054 
1055         auto* present = std::get_if<bool>(&respValue);
1056         if (present != nullptr && *present)
1057         {
1058             int cpuIndex = 0;
1059             try
1060             {
1061                 cpuIndex = std::stoi(obj.substr(obj.size() - 1));
1062             }
1063             catch (const std::exception& e)
1064             {
1065                 std::cerr << "Error converting CPU index, " << e.what() << '\n';
1066                 continue;
1067             }
1068             cpuPresence[cpuIndex] = *present;
1069         }
1070     }
1071 }
1072 
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)1073 void createSensors(
1074     boost::asio::io_context& io, sdbusplus::asio::object_server& objectServer,
1075     std::shared_ptr<sdbusplus::asio::connection>& dbusConnection,
1076     const std::shared_ptr<boost::container::flat_set<std::string>>&
1077         sensorsChanged,
1078     bool activateOnly)
1079 {
1080     auto getter = std::make_shared<GetSensorConfiguration>(
1081         dbusConnection, [&io, &objectServer, &dbusConnection, sensorsChanged,
1082                          activateOnly](const ManagedObjectType& sensorConfigs) {
1083             createSensorsCallback(io, objectServer, dbusConnection,
1084                                   sensorConfigs, sensorsChanged, activateOnly);
1085         });
1086     std::vector<std::string> types(sensorTypes.size());
1087     for (const auto& [type, dt] : sensorTypes)
1088     {
1089         types.push_back(type);
1090     }
1091     getter->getConfiguration(types);
1092 }
1093 
propertyInitialize()1094 void propertyInitialize()
1095 {
1096     sensorTable = {{"power", sensor_paths::unitWatts},
1097                    {"curr", sensor_paths::unitAmperes},
1098                    {"temp", sensor_paths::unitDegreesC},
1099                    {"in", sensor_paths::unitVolts},
1100                    {"voltage", sensor_paths::unitVolts},
1101                    {"fan", sensor_paths::unitRPMs}};
1102 
1103     labelMatch = {
1104         {"pin", PSUProperty("Input Power", 3000, 0, 6, 0)},
1105         {"pout", PSUProperty("Output Power", 3000, 0, 6, 0)},
1106         {"power", PSUProperty("Output Power", 3000, 0, 6, 0)},
1107         {"maxpin", PSUProperty("Max Input Power", 3000, 0, 6, 0)},
1108         {"vin", PSUProperty("Input Voltage", 300, 0, 3, 0)},
1109         {"maxvin", PSUProperty("Max Input Voltage", 300, 0, 3, 0)},
1110         {"in_voltage", PSUProperty("Output Voltage", 255, 0, 3, 0)},
1111         {"voltage", PSUProperty("Output Voltage", 255, 0, 3, 0)},
1112         {"vout", PSUProperty("Output Voltage", 255, 0, 3, 0)},
1113         {"vmon", PSUProperty("Auxiliary Input Voltage", 255, 0, 3, 0)},
1114         {"in", PSUProperty("Output Voltage", 255, 0, 3, 0)},
1115         {"iin", PSUProperty("Input Current", 20, 0, 3, 0)},
1116         {"iout", PSUProperty("Output Current", 255, 0, 3, 0)},
1117         {"curr", PSUProperty("Output Current", 255, 0, 3, 0)},
1118         {"maxiout", PSUProperty("Max Output Current", 255, 0, 3, 0)},
1119         {"temp", PSUProperty("Temperature", 127, -128, 3, 0)},
1120         {"maxtemp", PSUProperty("Max Temperature", 127, -128, 3, 0)},
1121         {"fan", PSUProperty("Fan Speed ", 30000, 0, 0, 0)}};
1122 
1123     limitEventMatch = {{"PredictiveFailure", {"max_alarm", "min_alarm"}},
1124                        {"Failure", {"crit_alarm", "lcrit_alarm"}}};
1125 
1126     eventMatch = {{"PredictiveFailure", {"power1_alarm"}},
1127                   {"Failure", {"in2_alarm"}},
1128                   {"ACLost", {"in1_beep"}},
1129                   {"ConfigureError", {"in1_fault"}}};
1130 
1131     devParamMap = {
1132         {DevTypes::HWMON, {1, R"(\w\d+_input$)", "([A-Za-z]+)[0-9]*_"}},
1133         {DevTypes::IIO,
1134          {2, R"(\w+_(raw|input)$)", "^(in|out)_([A-Za-z]+)[0-9]*_"}}};
1135 }
1136 
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)1137 static void powerStateChanged(
1138     PowerState type, bool newState,
1139     boost::container::flat_map<std::string, std::shared_ptr<PSUSensor>>&
1140         sensors,
1141     boost::asio::io_context& io, sdbusplus::asio::object_server& objectServer,
1142     std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
1143 {
1144     if (newState)
1145     {
1146         createSensors(io, objectServer, dbusConnection, nullptr, true);
1147     }
1148     else
1149     {
1150         for (auto& [path, sensor] : sensors)
1151         {
1152             if (sensor != nullptr && sensor->readState == type)
1153             {
1154                 sensor->deactivate();
1155             }
1156         }
1157     }
1158 }
1159 
main()1160 int main()
1161 {
1162     boost::asio::io_context io;
1163     auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
1164 
1165     sdbusplus::asio::object_server objectServer(systemBus, true);
1166     objectServer.add_manager("/xyz/openbmc_project/sensors");
1167     objectServer.add_manager("/xyz/openbmc_project/control");
1168     systemBus->request_name("xyz.openbmc_project.PSUSensor");
1169     auto sensorsChanged =
1170         std::make_shared<boost::container::flat_set<std::string>>();
1171 
1172     propertyInitialize();
1173 
1174     auto powerCallBack = [&io, &objectServer,
1175                           &systemBus](PowerState type, bool state) {
1176         powerStateChanged(type, state, sensors, io, objectServer, systemBus);
1177     };
1178 
1179     setupPowerMatchCallback(systemBus, powerCallBack);
1180 
1181     boost::asio::post(io, [&]() {
1182         createSensors(io, objectServer, systemBus, nullptr, false);
1183     });
1184     boost::asio::steady_timer filterTimer(io);
1185     std::function<void(sdbusplus::message_t&)> eventHandler =
1186         [&](sdbusplus::message_t& message) {
1187             if (message.is_method_error())
1188             {
1189                 std::cerr << "callback method error\n";
1190                 return;
1191             }
1192             sensorsChanged->insert(message.get_path());
1193             filterTimer.expires_after(std::chrono::seconds(3));
1194             filterTimer.async_wait([&](const boost::system::error_code& ec) {
1195                 if (ec == boost::asio::error::operation_aborted)
1196                 {
1197                     return;
1198                 }
1199                 if (ec)
1200                 {
1201                     std::cerr << "timer error\n";
1202                 }
1203                 createSensors(io, objectServer, systemBus, sensorsChanged,
1204                               false);
1205             });
1206         };
1207 
1208     boost::asio::steady_timer cpuFilterTimer(io);
1209     std::function<void(sdbusplus::message_t&)> cpuPresenceHandler =
1210         [&](sdbusplus::message_t& message) {
1211             std::string path = message.get_path();
1212             boost::to_lower(path);
1213 
1214             sdbusplus::message::object_path cpuPath(path);
1215             std::string cpuName = cpuPath.filename();
1216             if (!cpuName.starts_with("cpu"))
1217             {
1218                 return;
1219             }
1220             size_t index = 0;
1221             try
1222             {
1223                 index = std::stoi(path.substr(path.size() - 1));
1224             }
1225             catch (const std::invalid_argument&)
1226             {
1227                 std::cerr << "Found invalid path " << path << "\n";
1228                 return;
1229             }
1230 
1231             std::string objectName;
1232             boost::container::flat_map<std::string, std::variant<bool>> values;
1233             message.read(objectName, values);
1234             auto findPresence = values.find("Present");
1235             if (findPresence == values.end())
1236             {
1237                 return;
1238             }
1239             try
1240             {
1241                 cpuPresence[index] = std::get<bool>(findPresence->second);
1242             }
1243             catch (const std::bad_variant_access& err)
1244             {
1245                 return;
1246             }
1247 
1248             if (!cpuPresence[index])
1249             {
1250                 return;
1251             }
1252             cpuFilterTimer.expires_after(std::chrono::seconds(1));
1253             cpuFilterTimer.async_wait([&](const boost::system::error_code& ec) {
1254                 if (ec == boost::asio::error::operation_aborted)
1255                 {
1256                     return;
1257                 }
1258                 if (ec)
1259                 {
1260                     std::cerr << "timer error\n";
1261                     return;
1262                 }
1263                 createSensors(io, objectServer, systemBus, nullptr, false);
1264             });
1265         };
1266 
1267     std::vector<std::unique_ptr<sdbusplus::bus::match_t>> matches =
1268         setupPropertiesChangedMatches(*systemBus, sensorTypes, eventHandler);
1269 
1270     matches.emplace_back(std::make_unique<sdbusplus::bus::match_t>(
1271         static_cast<sdbusplus::bus_t&>(*systemBus),
1272         "type='signal',member='PropertiesChanged',path_namespace='" +
1273             std::string(cpuInventoryPath) +
1274             "',arg0namespace='xyz.openbmc_project.Inventory.Item'",
1275         cpuPresenceHandler));
1276 
1277     getPresentCpus(systemBus);
1278 
1279     setupManufacturingModeMatch(*systemBus);
1280     io.run();
1281 }
1282