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