1 #include "config.h"
2 
3 #include "psu_manager.hpp"
4 
5 #include "utility.hpp"
6 
7 #include <fmt/format.h>
8 #include <sys/types.h>
9 #include <unistd.h>
10 
11 #include <xyz/openbmc_project/State/Chassis/server.hpp>
12 
13 #include <algorithm>
14 #include <regex>
15 #include <set>
16 
17 using namespace phosphor::logging;
18 
19 namespace phosphor::power::manager
20 {
21 constexpr auto managerBusName = "xyz.openbmc_project.Power.PSUMonitor";
22 constexpr auto objectManagerObjPath =
23     "/xyz/openbmc_project/power/power_supplies";
24 constexpr auto powerSystemsInputsObjPath =
25     "/xyz/openbmc_project/power/power_supplies/chassis0/psus";
26 
27 constexpr auto IBMCFFPSInterface =
28     "xyz.openbmc_project.Configuration.IBMCFFPSConnector";
29 constexpr auto i2cBusProp = "I2CBus";
30 constexpr auto i2cAddressProp = "I2CAddress";
31 constexpr auto psuNameProp = "Name";
32 constexpr auto presLineName = "NamedPresenceGpio";
33 
34 constexpr auto supportedConfIntf =
35     "xyz.openbmc_project.Configuration.SupportedConfiguration";
36 
37 const auto deviceDirPath = "/sys/bus/i2c/devices/";
38 const auto driverDirName = "/driver";
39 
40 constexpr auto INPUT_HISTORY_SYNC_DELAY = 5;
41 
42 PSUManager::PSUManager(sdbusplus::bus_t& bus, const sdeventplus::Event& e) :
43     bus(bus), powerSystemInputs(bus, powerSystemsInputsObjPath),
44     objectManager(bus, objectManagerObjPath),
45     sensorsObjManager(bus, "/xyz/openbmc_project/sensors")
46 {
47     // Subscribe to InterfacesAdded before doing a property read, otherwise
48     // the interface could be created after the read attempt but before the
49     // match is created.
50     entityManagerIfacesAddedMatch = std::make_unique<sdbusplus::bus::match_t>(
51         bus,
52         sdbusplus::bus::match::rules::interfacesAdded() +
53             sdbusplus::bus::match::rules::sender(
54                 "xyz.openbmc_project.EntityManager"),
55         std::bind(&PSUManager::entityManagerIfaceAdded, this,
56                   std::placeholders::_1));
57     getPSUConfiguration();
58     getSystemProperties();
59 
60     // Request the bus name before the analyze() function, which is the one that
61     // determines the brownout condition and sets the status d-bus property.
62     bus.request_name(managerBusName);
63 
64     using namespace sdeventplus;
65     auto interval = std::chrono::milliseconds(1000);
66     timer = std::make_unique<utility::Timer<ClockId::Monotonic>>(
67         e, std::bind(&PSUManager::analyze, this), interval);
68 
69     validationTimer = std::make_unique<utility::Timer<ClockId::Monotonic>>(
70         e, std::bind(&PSUManager::validateConfig, this));
71 
72     try
73     {
74         powerConfigGPIO = createGPIO("power-config-full-load");
75     }
76     catch (const std::exception& e)
77     {
78         // Ignore error, GPIO may not be implemented in this system.
79         powerConfigGPIO = nullptr;
80     }
81 
82     // Subscribe to power state changes
83     powerService = util::getService(POWER_OBJ_PATH, POWER_IFACE, bus);
84     powerOnMatch = std::make_unique<sdbusplus::bus::match_t>(
85         bus,
86         sdbusplus::bus::match::rules::propertiesChanged(POWER_OBJ_PATH,
87                                                         POWER_IFACE),
88         [this](auto& msg) { this->powerStateChanged(msg); });
89 
90     initialize();
91 }
92 
93 void PSUManager::initialize()
94 {
95     try
96     {
97         // pgood is the latest read of the chassis pgood
98         int pgood = 0;
99         util::getProperty<int>(POWER_IFACE, "pgood", POWER_OBJ_PATH,
100                                powerService, bus, pgood);
101 
102         // state is the latest requested power on / off transition
103         auto method = bus.new_method_call(powerService.c_str(), POWER_OBJ_PATH,
104                                           POWER_IFACE, "getPowerState");
105         auto reply = bus.call(method);
106         int state = 0;
107         reply.read(state);
108 
109         if (state)
110         {
111             // Monitor PSUs anytime state is on
112             powerOn = true;
113             // In the power fault window if pgood is off
114             powerFaultOccurring = !pgood;
115             validationTimer->restartOnce(validationTimeout);
116         }
117         else
118         {
119             // Power is off
120             powerOn = false;
121             powerFaultOccurring = false;
122             runValidateConfig = true;
123         }
124     }
125     catch (const std::exception& e)
126     {
127         log<level::INFO>(
128             fmt::format(
129                 "Failed to get power state, assuming it is off, error {}",
130                 e.what())
131                 .c_str());
132         powerOn = false;
133         powerFaultOccurring = false;
134         runValidateConfig = true;
135     }
136 
137     onOffConfig(phosphor::pmbus::ON_OFF_CONFIG_CONTROL_PIN_ONLY);
138     clearFaults();
139     updateMissingPSUs();
140     setPowerConfigGPIO();
141 
142     log<level::INFO>(
143         fmt::format("initialize: power on: {}, power fault occurring: {}",
144                     powerOn, powerFaultOccurring)
145             .c_str());
146 }
147 
148 void PSUManager::getPSUConfiguration()
149 {
150     using namespace phosphor::power::util;
151     auto depth = 0;
152     auto objects = getSubTree(bus, "/", IBMCFFPSInterface, depth);
153 
154     psus.clear();
155 
156     // I should get a map of objects back.
157     // Each object will have a path, a service, and an interface.
158     // The interface should match the one passed into this function.
159     for (const auto& [path, services] : objects)
160     {
161         auto service = services.begin()->first;
162 
163         if (path.empty() || service.empty())
164         {
165             continue;
166         }
167 
168         // For each object in the array of objects, I want to get properties
169         // from the service, path, and interface.
170         auto properties = getAllProperties(bus, path, IBMCFFPSInterface,
171                                            service);
172 
173         getPSUProperties(properties);
174     }
175 
176     if (psus.empty())
177     {
178         // Interface or properties not found. Let the Interfaces Added callback
179         // process the information once the interfaces are added to D-Bus.
180         log<level::INFO>(fmt::format("No power supplies to monitor").c_str());
181     }
182 }
183 
184 void PSUManager::getPSUProperties(util::DbusPropertyMap& properties)
185 {
186     // From passed in properties, I want to get: I2CBus, I2CAddress,
187     // and Name. Create a power supply object, using Name to build the inventory
188     // path.
189     const auto basePSUInvPath =
190         "/xyz/openbmc_project/inventory/system/chassis/motherboard/powersupply";
191     uint64_t* i2cbus = nullptr;
192     uint64_t* i2caddr = nullptr;
193     std::string* psuname = nullptr;
194     std::string* preslineptr = nullptr;
195 
196     for (const auto& property : properties)
197     {
198         try
199         {
200             if (property.first == i2cBusProp)
201             {
202                 i2cbus = std::get_if<uint64_t>(&properties[i2cBusProp]);
203             }
204             else if (property.first == i2cAddressProp)
205             {
206                 i2caddr = std::get_if<uint64_t>(&properties[i2cAddressProp]);
207             }
208             else if (property.first == psuNameProp)
209             {
210                 psuname = std::get_if<std::string>(&properties[psuNameProp]);
211             }
212             else if (property.first == presLineName)
213             {
214                 preslineptr =
215                     std::get_if<std::string>(&properties[presLineName]);
216             }
217         }
218         catch (const std::exception& e)
219         {}
220     }
221 
222     if ((i2cbus) && (i2caddr) && (psuname) && (!psuname->empty()))
223     {
224         std::string invpath = basePSUInvPath;
225         invpath.push_back(psuname->back());
226         std::string presline = "";
227 
228         log<level::DEBUG>(fmt::format("Inventory Path: {}", invpath).c_str());
229 
230         if (nullptr != preslineptr)
231         {
232             presline = *preslineptr;
233         }
234 
235         auto invMatch = std::find_if(psus.begin(), psus.end(),
236                                      [&invpath](auto& psu) {
237             return psu->getInventoryPath() == invpath;
238         });
239         if (invMatch != psus.end())
240         {
241             // This power supply has the same inventory path as the one with
242             // information just added to D-Bus.
243             // Changes to GPIO line name unlikely, so skip checking.
244             // Changes to the I2C bus and address unlikely, as that would
245             // require corresponding device tree updates.
246             // Return out to avoid duplicate object creation.
247             return;
248         }
249 
250         buildDriverName(*i2cbus, *i2caddr);
251         log<level::DEBUG>(
252             fmt::format("make PowerSupply bus: {} addr: {} presline: {}",
253                         *i2cbus, *i2caddr, presline)
254                 .c_str());
255         auto psu = std::make_unique<PowerSupply>(
256             bus, invpath, *i2cbus, *i2caddr, driverName, presline,
257             std::bind(
258                 std::mem_fn(&phosphor::power::manager::PSUManager::isPowerOn),
259                 this));
260         psus.emplace_back(std::move(psu));
261 
262         // Subscribe to power supply presence changes
263         auto presenceMatch = std::make_unique<sdbusplus::bus::match_t>(
264             bus,
265             sdbusplus::bus::match::rules::propertiesChanged(invpath,
266                                                             INVENTORY_IFACE),
267             [this](auto& msg) { this->presenceChanged(msg); });
268         presenceMatches.emplace_back(std::move(presenceMatch));
269     }
270 
271     if (psus.empty())
272     {
273         log<level::INFO>(fmt::format("No power supplies to monitor").c_str());
274     }
275     else
276     {
277         populateDriverName();
278     }
279 }
280 
281 void PSUManager::populateSysProperties(const util::DbusPropertyMap& properties)
282 {
283     try
284     {
285         auto propIt = properties.find("SupportedType");
286         if (propIt == properties.end())
287         {
288             return;
289         }
290         const std::string* type = std::get_if<std::string>(&(propIt->second));
291         if ((type == nullptr) || (*type != "PowerSupply"))
292         {
293             return;
294         }
295 
296         propIt = properties.find("SupportedModel");
297         if (propIt == properties.end())
298         {
299             return;
300         }
301         const std::string* model = std::get_if<std::string>(&(propIt->second));
302         if (model == nullptr)
303         {
304             return;
305         }
306 
307         sys_properties sys;
308         propIt = properties.find("RedundantCount");
309         if (propIt != properties.end())
310         {
311             const uint64_t* count = std::get_if<uint64_t>(&(propIt->second));
312             if (count != nullptr)
313             {
314                 sys.powerSupplyCount = *count;
315             }
316         }
317         propIt = properties.find("InputVoltage");
318         if (propIt != properties.end())
319         {
320             const std::vector<uint64_t>* voltage =
321                 std::get_if<std::vector<uint64_t>>(&(propIt->second));
322             if (voltage != nullptr)
323             {
324                 sys.inputVoltage = *voltage;
325             }
326         }
327 
328         // The PowerConfigFullLoad is an optional property, default it to false
329         // since that's the default value of the power-config-full-load GPIO.
330         sys.powerConfigFullLoad = false;
331         propIt = properties.find("PowerConfigFullLoad");
332         if (propIt != properties.end())
333         {
334             const bool* fullLoad = std::get_if<bool>(&(propIt->second));
335             if (fullLoad != nullptr)
336             {
337                 sys.powerConfigFullLoad = *fullLoad;
338             }
339         }
340 
341         supportedConfigs.emplace(*model, sys);
342     }
343     catch (const std::exception& e)
344     {}
345 }
346 
347 void PSUManager::getSystemProperties()
348 {
349     try
350     {
351         util::DbusSubtree subtree = util::getSubTree(bus, INVENTORY_OBJ_PATH,
352                                                      supportedConfIntf, 0);
353         if (subtree.empty())
354         {
355             throw std::runtime_error("Supported Configuration Not Found");
356         }
357 
358         for (const auto& [objPath, services] : subtree)
359         {
360             std::string service = services.begin()->first;
361             if (objPath.empty() || service.empty())
362             {
363                 continue;
364             }
365             auto properties = util::getAllProperties(
366                 bus, objPath, supportedConfIntf, service);
367             populateSysProperties(properties);
368         }
369     }
370     catch (const std::exception& e)
371     {
372         // Interface or property not found. Let the Interfaces Added callback
373         // process the information once the interfaces are added to D-Bus.
374     }
375 }
376 
377 void PSUManager::entityManagerIfaceAdded(sdbusplus::message_t& msg)
378 {
379     try
380     {
381         sdbusplus::message::object_path objPath;
382         std::map<std::string, std::map<std::string, util::DbusVariant>>
383             interfaces;
384         msg.read(objPath, interfaces);
385 
386         auto itIntf = interfaces.find(supportedConfIntf);
387         if (itIntf != interfaces.cend())
388         {
389             populateSysProperties(itIntf->second);
390             updateMissingPSUs();
391         }
392 
393         itIntf = interfaces.find(IBMCFFPSInterface);
394         if (itIntf != interfaces.cend())
395         {
396             log<level::INFO>(
397                 fmt::format("InterfacesAdded for: {}", IBMCFFPSInterface)
398                     .c_str());
399             getPSUProperties(itIntf->second);
400             updateMissingPSUs();
401         }
402 
403         // Call to validate the psu configuration if the power is on and both
404         // the IBMCFFPSConnector and SupportedConfiguration interfaces have been
405         // processed
406         if (powerOn && !psus.empty() && !supportedConfigs.empty())
407         {
408             validationTimer->restartOnce(validationTimeout);
409         }
410     }
411     catch (const std::exception& e)
412     {
413         // Ignore, the property may be of a different type than expected.
414     }
415 }
416 
417 void PSUManager::powerStateChanged(sdbusplus::message_t& msg)
418 {
419     std::string msgSensor;
420     std::map<std::string, std::variant<int>> msgData;
421     msg.read(msgSensor, msgData);
422 
423     // Check if it was the state property that changed.
424     auto valPropMap = msgData.find("state");
425     if (valPropMap != msgData.end())
426     {
427         int state = std::get<int>(valPropMap->second);
428         if (state)
429         {
430             // Power on requested
431             powerOn = true;
432             powerFaultOccurring = false;
433             validationTimer->restartOnce(validationTimeout);
434             clearFaults();
435             syncHistory();
436             setPowerConfigGPIO();
437             setInputVoltageRating();
438         }
439         else
440         {
441             // Power off requested
442             powerOn = false;
443             powerFaultOccurring = false;
444             runValidateConfig = true;
445         }
446     }
447 
448     // Check if it was the pgood property that changed.
449     valPropMap = msgData.find("pgood");
450     if (valPropMap != msgData.end())
451     {
452         int pgood = std::get<int>(valPropMap->second);
453         if (!pgood)
454         {
455             // Chassis power good has turned off
456             if (powerOn)
457             {
458                 // pgood is off but state is on, in power fault window
459                 powerFaultOccurring = true;
460             }
461         }
462     }
463     log<level::INFO>(
464         fmt::format(
465             "powerStateChanged: power on: {}, power fault occurring: {}",
466             powerOn, powerFaultOccurring)
467             .c_str());
468 }
469 
470 void PSUManager::presenceChanged(sdbusplus::message_t& msg)
471 {
472     std::string msgSensor;
473     std::map<std::string, std::variant<uint32_t, bool>> msgData;
474     msg.read(msgSensor, msgData);
475 
476     // Check if it was the Present property that changed.
477     auto valPropMap = msgData.find(PRESENT_PROP);
478     if (valPropMap != msgData.end())
479     {
480         if (std::get<bool>(valPropMap->second))
481         {
482             // A PSU became present, force the PSU validation to run.
483             runValidateConfig = true;
484             validationTimer->restartOnce(validationTimeout);
485         }
486     }
487 }
488 
489 void PSUManager::setPowerSupplyError(const std::string& psuErrorString)
490 {
491     using namespace sdbusplus::xyz::openbmc_project;
492     constexpr auto method = "setPowerSupplyError";
493 
494     try
495     {
496         // Call D-Bus method to inform pseq of PSU error
497         auto methodMsg = bus.new_method_call(
498             powerService.c_str(), POWER_OBJ_PATH, POWER_IFACE, method);
499         methodMsg.append(psuErrorString);
500         auto callReply = bus.call(methodMsg);
501     }
502     catch (const std::exception& e)
503     {
504         log<level::INFO>(
505             fmt::format("Failed calling setPowerSupplyError due to error {}",
506                         e.what())
507                 .c_str());
508     }
509 }
510 
511 void PSUManager::createError(const std::string& faultName,
512                              std::map<std::string, std::string>& additionalData)
513 {
514     using namespace sdbusplus::xyz::openbmc_project;
515     constexpr auto loggingObjectPath = "/xyz/openbmc_project/logging";
516     constexpr auto loggingCreateInterface =
517         "xyz.openbmc_project.Logging.Create";
518 
519     try
520     {
521         additionalData["_PID"] = std::to_string(getpid());
522 
523         auto service = util::getService(loggingObjectPath,
524                                         loggingCreateInterface, bus);
525 
526         if (service.empty())
527         {
528             log<level::ERR>("Unable to get logging manager service");
529             return;
530         }
531 
532         auto method = bus.new_method_call(service.c_str(), loggingObjectPath,
533                                           loggingCreateInterface, "Create");
534 
535         auto level = Logging::server::Entry::Level::Error;
536         method.append(faultName, level, additionalData);
537 
538         auto reply = bus.call(method);
539         setPowerSupplyError(faultName);
540     }
541     catch (const std::exception& e)
542     {
543         log<level::ERR>(
544             fmt::format(
545                 "Failed creating event log for fault {} due to error {}",
546                 faultName, e.what())
547                 .c_str());
548     }
549 }
550 
551 void PSUManager::syncHistory()
552 {
553     if (driverName != ACBEL_FSG032_DD_NAME)
554     {
555         if (!syncHistoryGPIO)
556         {
557             syncHistoryGPIO = createGPIO(INPUT_HISTORY_SYNC_GPIO);
558         }
559         if (syncHistoryGPIO)
560         {
561             const std::chrono::milliseconds delay{INPUT_HISTORY_SYNC_DELAY};
562             log<level::INFO>("Synchronize INPUT_HISTORY");
563             syncHistoryGPIO->toggleLowHigh(delay);
564             for (auto& psu : psus)
565             {
566                 psu->clearSyncHistoryRequired();
567             }
568             log<level::INFO>("Synchronize INPUT_HISTORY completed");
569         }
570     }
571 }
572 
573 void PSUManager::analyze()
574 {
575     auto syncHistoryRequired = std::any_of(
576         psus.begin(), psus.end(),
577         [](const auto& psu) { return psu->isSyncHistoryRequired(); });
578     if (syncHistoryRequired)
579     {
580         syncHistory();
581     }
582 
583     for (auto& psu : psus)
584     {
585         psu->analyze();
586     }
587 
588     analyzeBrownout();
589 
590     // Only perform individual PSU analysis if power is on and a brownout has
591     // not already been logged
592     if (powerOn && !brownoutLogged)
593     {
594         for (auto& psu : psus)
595         {
596             std::map<std::string, std::string> additionalData;
597 
598             if (!psu->isFaultLogged() && !psu->isPresent())
599             {
600                 std::map<std::string, std::string> requiredPSUsData;
601                 auto requiredPSUsPresent = hasRequiredPSUs(requiredPSUsData);
602                 if (!requiredPSUsPresent && isRequiredPSU(*psu))
603                 {
604                     additionalData.merge(requiredPSUsData);
605                     // Create error for power supply missing.
606                     additionalData["CALLOUT_INVENTORY_PATH"] =
607                         psu->getInventoryPath();
608                     additionalData["CALLOUT_PRIORITY"] = "H";
609                     createError(
610                         "xyz.openbmc_project.Power.PowerSupply.Error.Missing",
611                         additionalData);
612                 }
613                 psu->setFaultLogged();
614             }
615             else if (!psu->isFaultLogged() && psu->isFaulted())
616             {
617                 // Add STATUS_WORD and STATUS_MFR last response, in padded
618                 // hexadecimal format.
619                 additionalData["STATUS_WORD"] =
620                     fmt::format("{:#04x}", psu->getStatusWord());
621                 additionalData["STATUS_MFR"] = fmt::format("{:#02x}",
622                                                            psu->getMFRFault());
623                 // If there are faults being reported, they possibly could be
624                 // related to a bug in the firmware version running on the power
625                 // supply. Capture that data into the error as well.
626                 additionalData["FW_VERSION"] = psu->getFWVersion();
627 
628                 if (psu->hasCommFault())
629                 {
630                     additionalData["STATUS_CML"] =
631                         fmt::format("{:#02x}", psu->getStatusCML());
632                     /* Attempts to communicate with the power supply have
633                      * reached there limit. Create an error. */
634                     additionalData["CALLOUT_DEVICE_PATH"] =
635                         psu->getDevicePath();
636 
637                     createError(
638                         "xyz.openbmc_project.Power.PowerSupply.Error.CommFault",
639                         additionalData);
640 
641                     psu->setFaultLogged();
642                 }
643                 else if ((psu->hasInputFault() || psu->hasVINUVFault()))
644                 {
645                     // Include STATUS_INPUT for input faults.
646                     additionalData["STATUS_INPUT"] =
647                         fmt::format("{:#02x}", psu->getStatusInput());
648 
649                     /* The power supply location might be needed if the input
650                      * fault is due to a problem with the power supply itself.
651                      * Include the inventory path with a call out priority of
652                      * low.
653                      */
654                     additionalData["CALLOUT_INVENTORY_PATH"] =
655                         psu->getInventoryPath();
656                     additionalData["CALLOUT_PRIORITY"] = "L";
657                     createError("xyz.openbmc_project.Power.PowerSupply.Error."
658                                 "InputFault",
659                                 additionalData);
660                     psu->setFaultLogged();
661                 }
662                 else if (psu->hasPSKillFault())
663                 {
664                     createError(
665                         "xyz.openbmc_project.Power.PowerSupply.Error.PSKillFault",
666                         additionalData);
667                     psu->setFaultLogged();
668                 }
669                 else if (psu->hasVoutOVFault())
670                 {
671                     // Include STATUS_VOUT for Vout faults.
672                     additionalData["STATUS_VOUT"] =
673                         fmt::format("{:#02x}", psu->getStatusVout());
674 
675                     additionalData["CALLOUT_INVENTORY_PATH"] =
676                         psu->getInventoryPath();
677 
678                     createError(
679                         "xyz.openbmc_project.Power.PowerSupply.Error.Fault",
680                         additionalData);
681 
682                     psu->setFaultLogged();
683                 }
684                 else if (psu->hasIoutOCFault())
685                 {
686                     // Include STATUS_IOUT for Iout faults.
687                     additionalData["STATUS_IOUT"] =
688                         fmt::format("{:#02x}", psu->getStatusIout());
689 
690                     createError(
691                         "xyz.openbmc_project.Power.PowerSupply.Error.IoutOCFault",
692                         additionalData);
693 
694                     psu->setFaultLogged();
695                 }
696                 else if (psu->hasVoutUVFault() || psu->hasPS12VcsFault() ||
697                          psu->hasPSCS12VFault())
698                 {
699                     // Include STATUS_VOUT for Vout faults.
700                     additionalData["STATUS_VOUT"] =
701                         fmt::format("{:#02x}", psu->getStatusVout());
702 
703                     additionalData["CALLOUT_INVENTORY_PATH"] =
704                         psu->getInventoryPath();
705 
706                     createError(
707                         "xyz.openbmc_project.Power.PowerSupply.Error.Fault",
708                         additionalData);
709 
710                     psu->setFaultLogged();
711                 }
712                 // A fan fault should have priority over a temperature fault,
713                 // since a failed fan may lead to a temperature problem.
714                 // Only process if not in power fault window.
715                 else if (psu->hasFanFault() && !powerFaultOccurring)
716                 {
717                     // Include STATUS_TEMPERATURE and STATUS_FANS_1_2
718                     additionalData["STATUS_TEMPERATURE"] =
719                         fmt::format("{:#02x}", psu->getStatusTemperature());
720                     additionalData["STATUS_FANS_1_2"] =
721                         fmt::format("{:#02x}", psu->getStatusFans12());
722 
723                     additionalData["CALLOUT_INVENTORY_PATH"] =
724                         psu->getInventoryPath();
725 
726                     createError(
727                         "xyz.openbmc_project.Power.PowerSupply.Error.FanFault",
728                         additionalData);
729 
730                     psu->setFaultLogged();
731                 }
732                 else if (psu->hasTempFault())
733                 {
734                     // Include STATUS_TEMPERATURE for temperature faults.
735                     additionalData["STATUS_TEMPERATURE"] =
736                         fmt::format("{:#02x}", psu->getStatusTemperature());
737 
738                     additionalData["CALLOUT_INVENTORY_PATH"] =
739                         psu->getInventoryPath();
740 
741                     createError(
742                         "xyz.openbmc_project.Power.PowerSupply.Error.Fault",
743                         additionalData);
744 
745                     psu->setFaultLogged();
746                 }
747                 else if (psu->hasMFRFault())
748                 {
749                     /* This can represent a variety of faults that result in
750                      * calling out the power supply for replacement: Output
751                      * OverCurrent, Output Under Voltage, and potentially other
752                      * faults.
753                      *
754                      * Also plan on putting specific fault in AdditionalData,
755                      * along with register names and register values
756                      * (STATUS_WORD, STATUS_MFR, etc.).*/
757 
758                     additionalData["CALLOUT_INVENTORY_PATH"] =
759                         psu->getInventoryPath();
760 
761                     createError(
762                         "xyz.openbmc_project.Power.PowerSupply.Error.Fault",
763                         additionalData);
764 
765                     psu->setFaultLogged();
766                 }
767                 // Only process if not in power fault window.
768                 else if (psu->hasPgoodFault() && !powerFaultOccurring)
769                 {
770                     /* POWER_GOOD# is not low, or OFF is on */
771                     additionalData["CALLOUT_INVENTORY_PATH"] =
772                         psu->getInventoryPath();
773 
774                     createError(
775                         "xyz.openbmc_project.Power.PowerSupply.Error.Fault",
776                         additionalData);
777 
778                     psu->setFaultLogged();
779                 }
780             }
781         }
782     }
783 }
784 
785 void PSUManager::analyzeBrownout()
786 {
787     // Count number of power supplies failing
788     size_t presentCount = 0;
789     size_t notPresentCount = 0;
790     size_t acFailedCount = 0;
791     size_t pgoodFailedCount = 0;
792     for (const auto& psu : psus)
793     {
794         if (psu->isPresent())
795         {
796             ++presentCount;
797             if (psu->hasACFault())
798             {
799                 ++acFailedCount;
800             }
801             else if (psu->hasPgoodFault())
802             {
803                 ++pgoodFailedCount;
804             }
805         }
806         else
807         {
808             ++notPresentCount;
809         }
810     }
811 
812     // Only issue brownout failure if chassis pgood has failed, it has not
813     // already been logged, at least one PSU has seen an AC fail, and all
814     // present PSUs have an AC or pgood failure. Note an AC fail is only set if
815     // at least one PSU is present.
816     if (powerFaultOccurring && !brownoutLogged && acFailedCount &&
817         (presentCount == (acFailedCount + pgoodFailedCount)))
818     {
819         // Indicate that the system is in a brownout condition by creating an
820         // error log and setting the PowerSystemInputs status property to Fault.
821         powerSystemInputs.status(
822             sdbusplus::xyz::openbmc_project::State::Decorator::server::
823                 PowerSystemInputs::Status::Fault);
824 
825         std::map<std::string, std::string> additionalData;
826         additionalData.emplace("NOT_PRESENT_COUNT",
827                                std::to_string(notPresentCount));
828         additionalData.emplace("VIN_FAULT_COUNT",
829                                std::to_string(acFailedCount));
830         additionalData.emplace("PGOOD_FAULT_COUNT",
831                                std::to_string(pgoodFailedCount));
832         log<level::INFO>(
833             fmt::format(
834                 "Brownout detected, not present count: {}, AC fault count {}, pgood fault count: {}",
835                 notPresentCount, acFailedCount, pgoodFailedCount)
836                 .c_str());
837 
838         createError("xyz.openbmc_project.State.Shutdown.Power.Error.Blackout",
839                     additionalData);
840         brownoutLogged = true;
841     }
842     else
843     {
844         // If a brownout was previously logged but at least one PSU is not
845         // currently in AC fault, determine if the brownout condition can be
846         // cleared
847         if (brownoutLogged && (acFailedCount < presentCount))
848         {
849             // Chassis only recognizes the PowerSystemInputs change when it is
850             // off
851             try
852             {
853                 using PowerState = sdbusplus::xyz::openbmc_project::State::
854                     server::Chassis::PowerState;
855                 PowerState currentPowerState;
856                 util::getProperty<PowerState>(
857                     "xyz.openbmc_project.State.Chassis", "CurrentPowerState",
858                     "/xyz/openbmc_project/state/chassis0",
859                     "xyz.openbmc_project.State.Chassis", bus,
860                     currentPowerState);
861 
862                 if (currentPowerState == PowerState::Off)
863                 {
864                     // Indicate that the system is no longer in a brownout
865                     // condition by setting the PowerSystemInputs status
866                     // property to Good.
867                     log<level::INFO>(
868                         fmt::format(
869                             "Brownout cleared, not present count: {}, AC fault count {}, pgood fault count: {}",
870                             notPresentCount, acFailedCount, pgoodFailedCount)
871                             .c_str());
872                     powerSystemInputs.status(
873                         sdbusplus::xyz::openbmc_project::State::Decorator::
874                             server::PowerSystemInputs::Status::Good);
875                     brownoutLogged = false;
876                 }
877             }
878             catch (const std::exception& e)
879             {
880                 log<level::ERR>(
881                     fmt::format("Error trying to clear brownout, error: {}",
882                                 e.what())
883                         .c_str());
884             }
885         }
886     }
887 }
888 
889 void PSUManager::updateMissingPSUs()
890 {
891     if (supportedConfigs.empty() || psus.empty())
892     {
893         return;
894     }
895 
896     // Power supplies default to missing. If the power supply is present,
897     // the PowerSupply object will update the inventory Present property to
898     // true. If we have less than the required number of power supplies, and
899     // this power supply is missing, update the inventory Present property
900     // to false to indicate required power supply is missing. Avoid
901     // indicating power supply missing if not required.
902 
903     auto presentCount =
904         std::count_if(psus.begin(), psus.end(),
905                       [](const auto& psu) { return psu->isPresent(); });
906 
907     for (const auto& config : supportedConfigs)
908     {
909         for (const auto& psu : psus)
910         {
911             auto psuModel = psu->getModelName();
912             auto psuShortName = psu->getShortName();
913             auto psuInventoryPath = psu->getInventoryPath();
914             auto relativeInvPath =
915                 psuInventoryPath.substr(strlen(INVENTORY_OBJ_PATH));
916             auto psuPresent = psu->isPresent();
917             auto presProperty = false;
918             auto propReadFail = false;
919 
920             try
921             {
922                 presProperty = getPresence(bus, psuInventoryPath);
923                 propReadFail = false;
924             }
925             catch (const sdbusplus::exception_t& e)
926             {
927                 propReadFail = true;
928                 // Relying on property change or interface added to retry.
929                 // Log an informational trace to the journal.
930                 log<level::INFO>(
931                     fmt::format("D-Bus property {} access failure exception",
932                                 psuInventoryPath)
933                         .c_str());
934             }
935 
936             if (psuModel.empty())
937             {
938                 if (!propReadFail && (presProperty != psuPresent))
939                 {
940                     // We already have this property, and it is not false
941                     // set Present to false
942                     setPresence(bus, relativeInvPath, psuPresent, psuShortName);
943                 }
944                 continue;
945             }
946 
947             if (config.first != psuModel)
948             {
949                 continue;
950             }
951 
952             if ((presentCount < config.second.powerSupplyCount) && !psuPresent)
953             {
954                 setPresence(bus, relativeInvPath, psuPresent, psuShortName);
955             }
956         }
957     }
958 }
959 
960 void PSUManager::validateConfig()
961 {
962     if (!runValidateConfig || supportedConfigs.empty() || psus.empty())
963     {
964         return;
965     }
966 
967     for (const auto& psu : psus)
968     {
969         if ((psu->hasInputFault() || psu->hasVINUVFault()))
970         {
971             // Do not try to validate if input voltage fault present.
972             validationTimer->restartOnce(validationTimeout);
973             return;
974         }
975     }
976 
977     std::map<std::string, std::string> additionalData;
978     auto supported = hasRequiredPSUs(additionalData);
979     if (supported)
980     {
981         runValidateConfig = false;
982         double actualVoltage;
983         int inputVoltage;
984         int previousInputVoltage = 0;
985         bool voltageMismatch = false;
986 
987         for (const auto& psu : psus)
988         {
989             if (!psu->isPresent())
990             {
991                 // Only present PSUs report a valid input voltage
992                 continue;
993             }
994             psu->getInputVoltage(actualVoltage, inputVoltage);
995             if (previousInputVoltage && inputVoltage &&
996                 (previousInputVoltage != inputVoltage))
997             {
998                 additionalData["EXPECTED_VOLTAGE"] =
999                     std::to_string(previousInputVoltage);
1000                 additionalData["ACTUAL_VOLTAGE"] =
1001                     std::to_string(actualVoltage);
1002                 voltageMismatch = true;
1003             }
1004             if (!previousInputVoltage && inputVoltage)
1005             {
1006                 previousInputVoltage = inputVoltage;
1007             }
1008         }
1009         if (!voltageMismatch)
1010         {
1011             return;
1012         }
1013     }
1014 
1015     // Validation failed, create an error log.
1016     // Return without setting the runValidateConfig flag to false because
1017     // it may be that an additional supported configuration interface is
1018     // added and we need to validate it to see if it matches this system.
1019     createError("xyz.openbmc_project.Power.PowerSupply.Error.NotSupported",
1020                 additionalData);
1021 }
1022 
1023 bool PSUManager::hasRequiredPSUs(
1024     std::map<std::string, std::string>& additionalData)
1025 {
1026     std::string model{};
1027     if (!validateModelName(model, additionalData))
1028     {
1029         return false;
1030     }
1031 
1032     auto presentCount =
1033         std::count_if(psus.begin(), psus.end(),
1034                       [](const auto& psu) { return psu->isPresent(); });
1035 
1036     // Validate the supported configurations. A system may support more than one
1037     // power supply model configuration. Since all configurations need to be
1038     // checked, the additional data would contain only the information of the
1039     // last configuration that did not match.
1040     std::map<std::string, std::string> tmpAdditionalData;
1041     for (const auto& config : supportedConfigs)
1042     {
1043         if (config.first != model)
1044         {
1045             continue;
1046         }
1047 
1048         // Number of power supplies present should equal or exceed the expected
1049         // count
1050         if (presentCount < config.second.powerSupplyCount)
1051         {
1052             tmpAdditionalData.clear();
1053             tmpAdditionalData["EXPECTED_COUNT"] =
1054                 std::to_string(config.second.powerSupplyCount);
1055             tmpAdditionalData["ACTUAL_COUNT"] = std::to_string(presentCount);
1056             continue;
1057         }
1058 
1059         bool voltageValidated = true;
1060         for (const auto& psu : psus)
1061         {
1062             if (!psu->isPresent())
1063             {
1064                 // Only present PSUs report a valid input voltage
1065                 continue;
1066             }
1067 
1068             double actualInputVoltage;
1069             int inputVoltage;
1070             psu->getInputVoltage(actualInputVoltage, inputVoltage);
1071 
1072             if (std::find(config.second.inputVoltage.begin(),
1073                           config.second.inputVoltage.end(),
1074                           inputVoltage) == config.second.inputVoltage.end())
1075             {
1076                 tmpAdditionalData.clear();
1077                 tmpAdditionalData["ACTUAL_VOLTAGE"] =
1078                     std::to_string(actualInputVoltage);
1079                 for (const auto& voltage : config.second.inputVoltage)
1080                 {
1081                     tmpAdditionalData["EXPECTED_VOLTAGE"] +=
1082                         std::to_string(voltage) + " ";
1083                 }
1084                 tmpAdditionalData["CALLOUT_INVENTORY_PATH"] =
1085                     psu->getInventoryPath();
1086 
1087                 voltageValidated = false;
1088                 break;
1089             }
1090         }
1091         if (!voltageValidated)
1092         {
1093             continue;
1094         }
1095 
1096         return true;
1097     }
1098 
1099     additionalData.insert(tmpAdditionalData.begin(), tmpAdditionalData.end());
1100     return false;
1101 }
1102 
1103 unsigned int PSUManager::getRequiredPSUCount()
1104 {
1105     unsigned int requiredCount{0};
1106 
1107     // Verify we have the supported configuration and PSU information
1108     if (!supportedConfigs.empty() && !psus.empty())
1109     {
1110         // Find PSU models.  They should all be the same.
1111         std::set<std::string> models{};
1112         std::for_each(psus.begin(), psus.end(), [&models](const auto& psu) {
1113             if (!psu->getModelName().empty())
1114             {
1115                 models.insert(psu->getModelName());
1116             }
1117         });
1118 
1119         // If exactly one model was found, find corresponding configuration
1120         if (models.size() == 1)
1121         {
1122             const std::string& model = *(models.begin());
1123             auto it = supportedConfigs.find(model);
1124             if (it != supportedConfigs.end())
1125             {
1126                 requiredCount = it->second.powerSupplyCount;
1127             }
1128         }
1129     }
1130 
1131     return requiredCount;
1132 }
1133 
1134 bool PSUManager::isRequiredPSU(const PowerSupply& psu)
1135 {
1136     // Get required number of PSUs; if not found, we don't know if PSU required
1137     unsigned int requiredCount = getRequiredPSUCount();
1138     if (requiredCount == 0)
1139     {
1140         return false;
1141     }
1142 
1143     // If total PSU count <= the required count, all PSUs are required
1144     if (psus.size() <= requiredCount)
1145     {
1146         return true;
1147     }
1148 
1149     // We don't currently get information from EntityManager about which PSUs
1150     // are required, so we have to do some guesswork.  First check if this PSU
1151     // is present.  If so, assume it is required.
1152     if (psu.isPresent())
1153     {
1154         return true;
1155     }
1156 
1157     // This PSU is not present.  Count the number of other PSUs that are
1158     // present.  If enough other PSUs are present, assume the specified PSU is
1159     // not required.
1160     unsigned int psuCount =
1161         std::count_if(psus.begin(), psus.end(),
1162                       [](const auto& psu) { return psu->isPresent(); });
1163     if (psuCount >= requiredCount)
1164     {
1165         return false;
1166     }
1167 
1168     // Check if this PSU was previously present.  If so, assume it is required.
1169     // We know it was previously present if it has a non-empty model name.
1170     if (!psu.getModelName().empty())
1171     {
1172         return true;
1173     }
1174 
1175     // This PSU was never present.  Count the number of other PSUs that were
1176     // previously present.  If including those PSUs is enough, assume the
1177     // specified PSU is not required.
1178     psuCount += std::count_if(psus.begin(), psus.end(), [](const auto& psu) {
1179         return (!psu->isPresent() && !psu->getModelName().empty());
1180     });
1181     if (psuCount >= requiredCount)
1182     {
1183         return false;
1184     }
1185 
1186     // We still haven't found enough PSUs.  Sort the inventory paths of PSUs
1187     // that were never present.  PSU inventory paths typically end with the PSU
1188     // number (0, 1, 2, ...).  Assume that lower-numbered PSUs are required.
1189     std::vector<std::string> sortedPaths;
1190     std::for_each(psus.begin(), psus.end(), [&sortedPaths](const auto& psu) {
1191         if (!psu->isPresent() && psu->getModelName().empty())
1192         {
1193             sortedPaths.push_back(psu->getInventoryPath());
1194         }
1195     });
1196     std::sort(sortedPaths.begin(), sortedPaths.end());
1197 
1198     // Check if specified PSU is close enough to start of list to be required
1199     for (const auto& path : sortedPaths)
1200     {
1201         if (path == psu.getInventoryPath())
1202         {
1203             return true;
1204         }
1205         if (++psuCount >= requiredCount)
1206         {
1207             break;
1208         }
1209     }
1210 
1211     // PSU was not close to start of sorted list; assume not required
1212     return false;
1213 }
1214 
1215 bool PSUManager::validateModelName(
1216     std::string& model, std::map<std::string, std::string>& additionalData)
1217 {
1218     // Check that all PSUs have the same model name. Initialize the model
1219     // variable with the first PSU name found, then use it as a base to compare
1220     // against the rest of the PSUs and get its inventory path to use as callout
1221     // if needed.
1222     model.clear();
1223     std::string modelInventoryPath{};
1224     for (const auto& psu : psus)
1225     {
1226         auto psuModel = psu->getModelName();
1227         if (psuModel.empty())
1228         {
1229             continue;
1230         }
1231         if (model.empty())
1232         {
1233             model = psuModel;
1234             modelInventoryPath = psu->getInventoryPath();
1235             continue;
1236         }
1237         if (psuModel != model)
1238         {
1239             if (supportedConfigs.find(model) != supportedConfigs.end())
1240             {
1241                 // The base model is supported, callout the mismatched PSU. The
1242                 // mismatched PSU may or may not be supported.
1243                 additionalData["EXPECTED_MODEL"] = model;
1244                 additionalData["ACTUAL_MODEL"] = psuModel;
1245                 additionalData["CALLOUT_INVENTORY_PATH"] =
1246                     psu->getInventoryPath();
1247             }
1248             else if (supportedConfigs.find(psuModel) != supportedConfigs.end())
1249             {
1250                 // The base model is not supported, but the mismatched PSU is,
1251                 // callout the base PSU.
1252                 additionalData["EXPECTED_MODEL"] = psuModel;
1253                 additionalData["ACTUAL_MODEL"] = model;
1254                 additionalData["CALLOUT_INVENTORY_PATH"] = modelInventoryPath;
1255             }
1256             else
1257             {
1258                 // The base model and the mismatched PSU are not supported or
1259                 // could not be found in the supported configuration, callout
1260                 // the mismatched PSU.
1261                 additionalData["EXPECTED_MODEL"] = model;
1262                 additionalData["ACTUAL_MODEL"] = psuModel;
1263                 additionalData["CALLOUT_INVENTORY_PATH"] =
1264                     psu->getInventoryPath();
1265             }
1266             model.clear();
1267             return false;
1268         }
1269     }
1270     return true;
1271 }
1272 
1273 void PSUManager::setPowerConfigGPIO()
1274 {
1275     if (!powerConfigGPIO)
1276     {
1277         return;
1278     }
1279 
1280     std::string model{};
1281     std::map<std::string, std::string> additionalData;
1282     if (!validateModelName(model, additionalData))
1283     {
1284         return;
1285     }
1286 
1287     auto config = supportedConfigs.find(model);
1288     if (config != supportedConfigs.end())
1289     {
1290         // The power-config-full-load is an open drain GPIO. Set it to low (0)
1291         // if the supported configuration indicates that this system model
1292         // expects the maximum number of power supplies (full load set to true).
1293         // Else, set it to high (1), this is the default.
1294         auto powerConfigValue =
1295             (config->second.powerConfigFullLoad == true ? 0 : 1);
1296         auto flags = gpiod::line_request::FLAG_OPEN_DRAIN;
1297         powerConfigGPIO->write(powerConfigValue, flags);
1298     }
1299 }
1300 
1301 void PSUManager::buildDriverName(uint64_t i2cbus, uint64_t i2caddr)
1302 {
1303     namespace fs = std::filesystem;
1304     std::stringstream ss;
1305     ss << std::hex << std::setw(4) << std::setfill('0') << i2caddr;
1306     std::string symLinkPath = deviceDirPath + std::to_string(i2cbus) + "-" +
1307                               ss.str() + driverDirName;
1308     try
1309     {
1310         fs::path linkStrPath = fs::read_symlink(symLinkPath);
1311         driverName = linkStrPath.filename();
1312     }
1313     catch (const std::exception& e)
1314     {
1315         log<level::ERR>(fmt::format("Failed to find device driver {}, error {}",
1316                                     symLinkPath, e.what())
1317                             .c_str());
1318     }
1319 }
1320 
1321 void PSUManager::populateDriverName()
1322 {
1323     std::string driverName;
1324     // Search in PSUs for driver name
1325     std::for_each(psus.begin(), psus.end(), [&driverName](auto& psu) {
1326         if (!psu->getDriverName().empty())
1327         {
1328             driverName = psu->getDriverName();
1329         }
1330     });
1331     // Assign driver name to all PSUs
1332     std::for_each(psus.begin(), psus.end(),
1333                   [=](auto& psu) { psu->setDriverName(driverName); });
1334 }
1335 } // namespace phosphor::power::manager
1336