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