blob: bc9e35c2d2cd95bd60f2739e6996fbcb252f30d3 [file] [log] [blame]
Brandon Wyman18a24d92022-04-19 22:48:34 +00001#include "config.h"
2
Brandon Wymana0f33ce2019-10-17 18:32:29 -05003#include "psu_manager.hpp"
4
5#include "utility.hpp"
6
Brandon Wymanb76ab242020-09-16 18:06:06 -05007#include <fmt/format.h>
8#include <sys/types.h>
9#include <unistd.h>
10
Jim Wright7f9288c2022-12-08 11:57:04 -060011#include <xyz/openbmc_project/State/Chassis/server.hpp>
12
Shawn McCarney9252b7e2022-06-10 12:47:38 -050013#include <algorithm>
Brandon Wymanecbecbc2021-08-31 22:53:21 +000014#include <regex>
Shawn McCarney9252b7e2022-06-10 12:47:38 -050015#include <set>
Brandon Wymanecbecbc2021-08-31 22:53:21 +000016
Brandon Wymanaed1f752019-11-25 18:10:52 -060017using namespace phosphor::logging;
18
Brandon Wyman63ea78b2020-09-24 16:49:09 -050019namespace phosphor::power::manager
Brandon Wymana0f33ce2019-10-17 18:32:29 -050020{
Adriana Kobylakc9b05732022-03-19 15:15:10 +000021constexpr auto managerBusName = "xyz.openbmc_project.Power.PSUMonitor";
22constexpr auto objectManagerObjPath =
23 "/xyz/openbmc_project/power/power_supplies";
24constexpr auto powerSystemsInputsObjPath =
25 "/xyz/openbmc_project/power/power_supplies/chassis0/psus";
Brandon Wymana0f33ce2019-10-17 18:32:29 -050026
Brandon Wyman510acaa2020-11-05 18:32:04 -060027constexpr auto IBMCFFPSInterface =
28 "xyz.openbmc_project.Configuration.IBMCFFPSConnector";
29constexpr auto i2cBusProp = "I2CBus";
30constexpr auto i2cAddressProp = "I2CAddress";
31constexpr auto psuNameProp = "Name";
B. J. Wyman681b2a32021-04-20 22:31:22 +000032constexpr auto presLineName = "NamedPresenceGpio";
Brandon Wyman510acaa2020-11-05 18:32:04 -060033
Adriana Kobylak9bab9e12021-02-24 15:32:03 -060034constexpr auto supportedConfIntf =
35 "xyz.openbmc_project.Configuration.SupportedConfiguration";
Adriana Kobylak9bab9e12021-02-24 15:32:03 -060036
Faisal Awadab66ae502023-04-01 18:30:32 -050037const auto deviceDirPath = "/sys/bus/i2c/devices/";
38const auto driverDirName = "/driver";
39
Brandon Wymanc9e840e2022-05-10 20:48:41 +000040constexpr auto INPUT_HISTORY_SYNC_DELAY = 5;
Brandon Wyman18a24d92022-04-19 22:48:34 +000041
Patrick Williams7354ce62022-07-22 19:26:56 -050042PSUManager::PSUManager(sdbusplus::bus_t& bus, const sdeventplus::Event& e) :
Adriana Kobylakc9b05732022-03-19 15:15:10 +000043 bus(bus), powerSystemInputs(bus, powerSystemsInputsObjPath),
Brandon Wymanc3324422022-03-24 20:30:57 +000044 objectManager(bus, objectManagerObjPath),
Matt Spinlera068f422023-03-10 13:06:49 -060045 sensorsObjManager(bus, "/xyz/openbmc_project/sensors")
Brandon Wyman510acaa2020-11-05 18:32:04 -060046{
Brandon Wyman510acaa2020-11-05 18:32:04 -060047 // 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
Adriana Kobylakc9b05732022-03-19 15:15:10 +000060 // 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
Brandon Wyman510acaa2020-11-05 18:32:04 -060064 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
Adriana Kobylaka4d38fa2021-10-05 19:57:47 +000069 validationTimer = std::make_unique<utility::Timer<ClockId::Monotonic>>(
70 e, std::bind(&PSUManager::validateConfig, this));
71
Adriana Kobylakc0a07582021-10-13 15:52:25 +000072 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
Brandon Wyman510acaa2020-11-05 18:32:04 -060082 // 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
Jim Wrightaca86d02022-06-10 12:01:39 -050093void 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
Jim Wright5c186c82022-11-17 17:09:33 -0600103 auto method = bus.new_method_call(powerService.c_str(), POWER_OBJ_PATH,
Jim Wrightaca86d02022-06-10 12:01:39 -0500104 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();
Jim Wrightaca86d02022-06-10 12:01:39 -0500140 setPowerConfigGPIO();
141
142 log<level::INFO>(
143 fmt::format("initialize: power on: {}, power fault occurring: {}",
144 powerOn, powerFaultOccurring)
145 .c_str());
146}
147
Brandon Wyman510acaa2020-11-05 18:32:04 -0600148void 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.
Patrick Williams48781ae2023-05-10 07:50:50 -0500170 auto properties = getAllProperties(bus, path, IBMCFFPSInterface,
171 service);
Brandon Wyman510acaa2020-11-05 18:32:04 -0600172
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
184void 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;
B. J. Wyman681b2a32021-04-20 22:31:22 +0000194 std::string* preslineptr = nullptr;
Brandon Wyman510acaa2020-11-05 18:32:04 -0600195
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 }
B. J. Wyman681b2a32021-04-20 22:31:22 +0000212 else if (property.first == presLineName)
213 {
214 preslineptr =
215 std::get_if<std::string>(&properties[presLineName]);
216 }
Brandon Wyman510acaa2020-11-05 18:32:04 -0600217 }
Patrick Williamsc1d4de52021-10-06 12:45:57 -0500218 catch (const std::exception& e)
Adriana Kobylak0c9a33d2021-09-13 18:05:09 +0000219 {}
Brandon Wyman510acaa2020-11-05 18:32:04 -0600220 }
221
222 if ((i2cbus) && (i2caddr) && (psuname) && (!psuname->empty()))
223 {
224 std::string invpath = basePSUInvPath;
225 invpath.push_back(psuname->back());
B. J. Wyman681b2a32021-04-20 22:31:22 +0000226 std::string presline = "";
Brandon Wyman510acaa2020-11-05 18:32:04 -0600227
228 log<level::DEBUG>(fmt::format("Inventory Path: {}", invpath).c_str());
229
B. J. Wyman681b2a32021-04-20 22:31:22 +0000230 if (nullptr != preslineptr)
231 {
232 presline = *preslineptr;
233 }
234
Patrick Williams48781ae2023-05-10 07:50:50 -0500235 auto invMatch = std::find_if(psus.begin(), psus.end(),
236 [&invpath](auto& psu) {
237 return psu->getInventoryPath() == invpath;
238 });
Brandon Wymanecbecbc2021-08-31 22:53:21 +0000239 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
Faisal Awadab66ae502023-04-01 18:30:32 -0500250 buildDriverName(*i2cbus, *i2caddr);
B. J. Wyman681b2a32021-04-20 22:31:22 +0000251 log<level::DEBUG>(
Faisal Awadab66ae502023-04-01 18:30:32 -0500252 fmt::format("make PowerSupply bus: {} addr: {} presline: {}",
253 *i2cbus, *i2caddr, presline)
B. J. Wyman681b2a32021-04-20 22:31:22 +0000254 .c_str());
George Liu9464c422023-02-27 14:30:27 +0800255 auto psu = std::make_unique<PowerSupply>(
Faisal Awadab66ae502023-04-01 18:30:32 -0500256 bus, invpath, *i2cbus, *i2caddr, driverName, presline,
George Liu9464c422023-02-27 14:30:27 +0800257 std::bind(
258 std::mem_fn(&phosphor::power::manager::PSUManager::isPowerOn),
259 this));
Brandon Wyman510acaa2020-11-05 18:32:04 -0600260 psus.emplace_back(std::move(psu));
Adriana Kobylak9ba38232021-11-16 20:27:45 +0000261
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));
Brandon Wyman510acaa2020-11-05 18:32:04 -0600269 }
270
271 if (psus.empty())
272 {
273 log<level::INFO>(fmt::format("No power supplies to monitor").c_str());
274 }
Faisal Awadab7131a12023-10-26 19:38:45 -0500275 else
276 {
277 populateDriverName();
278 }
Brandon Wyman510acaa2020-11-05 18:32:04 -0600279}
280
Adriana Kobylake1074d82021-03-16 20:46:44 +0000281void PSUManager::populateSysProperties(const util::DbusPropertyMap& properties)
282{
283 try
284 {
Adriana Kobylak9ea66a62021-03-24 17:54:14 +0000285 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
Adriana Kobylak9ea66a62021-03-24 17:54:14 +0000296 propIt = properties.find("SupportedModel");
297 if (propIt == properties.end())
298 {
299 return;
300 }
Adriana Kobylakd3a70d92021-06-04 16:24:45 +0000301 const std::string* model = std::get_if<std::string>(&(propIt->second));
302 if (model == nullptr)
Adriana Kobylak9ea66a62021-03-24 17:54:14 +0000303 {
304 return;
305 }
Adriana Kobylak9ea66a62021-03-24 17:54:14 +0000306
Adriana Kobylakd3a70d92021-06-04 16:24:45 +0000307 sys_properties sys;
Adriana Kobylak9ea66a62021-03-24 17:54:14 +0000308 propIt = properties.find("RedundantCount");
Adriana Kobylake1074d82021-03-16 20:46:44 +0000309 if (propIt != properties.end())
310 {
311 const uint64_t* count = std::get_if<uint64_t>(&(propIt->second));
312 if (count != nullptr)
313 {
Adriana Kobylakd3a70d92021-06-04 16:24:45 +0000314 sys.powerSupplyCount = *count;
Adriana Kobylake1074d82021-03-16 20:46:44 +0000315 }
316 }
Adriana Kobylak9ea66a62021-03-24 17:54:14 +0000317 propIt = properties.find("InputVoltage");
318 if (propIt != properties.end())
319 {
Adriana Kobylakd3a70d92021-06-04 16:24:45 +0000320 const std::vector<uint64_t>* voltage =
321 std::get_if<std::vector<uint64_t>>(&(propIt->second));
Adriana Kobylak9ea66a62021-03-24 17:54:14 +0000322 if (voltage != nullptr)
323 {
324 sys.inputVoltage = *voltage;
325 }
326 }
327
Adriana Kobylak886574c2021-11-01 18:22:28 +0000328 // 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
Adriana Kobylakd3a70d92021-06-04 16:24:45 +0000341 supportedConfigs.emplace(*model, sys);
Adriana Kobylake1074d82021-03-16 20:46:44 +0000342 }
Patrick Williamsc1d4de52021-10-06 12:45:57 -0500343 catch (const std::exception& e)
Adriana Kobylak0c9a33d2021-09-13 18:05:09 +0000344 {}
Adriana Kobylake1074d82021-03-16 20:46:44 +0000345}
346
Adriana Kobylak9bab9e12021-02-24 15:32:03 -0600347void PSUManager::getSystemProperties()
348{
Adriana Kobylak9bab9e12021-02-24 15:32:03 -0600349 try
350 {
Patrick Williams48781ae2023-05-10 07:50:50 -0500351 util::DbusSubtree subtree = util::getSubTree(bus, INVENTORY_OBJ_PATH,
352 supportedConfIntf, 0);
Adriana Kobylake1074d82021-03-16 20:46:44 +0000353 if (subtree.empty())
Adriana Kobylak9bab9e12021-02-24 15:32:03 -0600354 {
355 throw std::runtime_error("Supported Configuration Not Found");
356 }
Adriana Kobylak9bab9e12021-02-24 15:32:03 -0600357
Adriana Kobylake1074d82021-03-16 20:46:44 +0000358 for (const auto& [objPath, services] : subtree)
359 {
360 std::string service = services.begin()->first;
361 if (objPath.empty() || service.empty())
362 {
363 continue;
Adriana Kobylak9bab9e12021-02-24 15:32:03 -0600364 }
Adriana Kobylake1074d82021-03-16 20:46:44 +0000365 auto properties = util::getAllProperties(
366 bus, objPath, supportedConfIntf, service);
367 populateSysProperties(properties);
Adriana Kobylak9bab9e12021-02-24 15:32:03 -0600368 }
369 }
Patrick Williamsc1d4de52021-10-06 12:45:57 -0500370 catch (const std::exception& e)
Adriana Kobylak9bab9e12021-02-24 15:32:03 -0600371 {
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
Patrick Williams7354ce62022-07-22 19:26:56 -0500377void PSUManager::entityManagerIfaceAdded(sdbusplus::message_t& msg)
Adriana Kobylak9bab9e12021-02-24 15:32:03 -0600378{
379 try
380 {
381 sdbusplus::message::object_path objPath;
Adriana Kobylake1074d82021-03-16 20:46:44 +0000382 std::map<std::string, std::map<std::string, util::DbusVariant>>
Adriana Kobylak9bab9e12021-02-24 15:32:03 -0600383 interfaces;
384 msg.read(objPath, interfaces);
385
386 auto itIntf = interfaces.find(supportedConfIntf);
Brandon Wyman510acaa2020-11-05 18:32:04 -0600387 if (itIntf != interfaces.cend())
Adriana Kobylak9bab9e12021-02-24 15:32:03 -0600388 {
Brandon Wyman510acaa2020-11-05 18:32:04 -0600389 populateSysProperties(itIntf->second);
Brandon Wymanf477eb72022-07-28 16:30:54 +0000390 updateMissingPSUs();
Adriana Kobylak9bab9e12021-02-24 15:32:03 -0600391 }
392
Brandon Wyman510acaa2020-11-05 18:32:04 -0600393 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);
Brandon Wymanf477eb72022-07-28 16:30:54 +0000400 updateMissingPSUs();
Brandon Wyman510acaa2020-11-05 18:32:04 -0600401 }
Adriana Kobylak8f16fb52021-03-31 15:50:15 +0000402
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 {
Adriana Kobylaka4d38fa2021-10-05 19:57:47 +0000408 validationTimer->restartOnce(validationTimeout);
Adriana Kobylak8f16fb52021-03-31 15:50:15 +0000409 }
Adriana Kobylak9bab9e12021-02-24 15:32:03 -0600410 }
Patrick Williamsc1d4de52021-10-06 12:45:57 -0500411 catch (const std::exception& e)
Adriana Kobylak9bab9e12021-02-24 15:32:03 -0600412 {
413 // Ignore, the property may be of a different type than expected.
414 }
415}
416
Patrick Williams7354ce62022-07-22 19:26:56 -0500417void PSUManager::powerStateChanged(sdbusplus::message_t& msg)
Brandon Wymana0f33ce2019-10-17 18:32:29 -0500418{
Brandon Wymana0f33ce2019-10-17 18:32:29 -0500419 std::string msgSensor;
Jim Wrightaca86d02022-06-10 12:01:39 -0500420 std::map<std::string, std::variant<int>> msgData;
Brandon Wymana0f33ce2019-10-17 18:32:29 -0500421 msg.read(msgSensor, msgData);
422
Jim Wrightaca86d02022-06-10 12:01:39 -0500423 // Check if it was the state property that changed.
Brandon Wymana0f33ce2019-10-17 18:32:29 -0500424 auto valPropMap = msgData.find("state");
425 if (valPropMap != msgData.end())
426 {
Jim Wrightaca86d02022-06-10 12:01:39 -0500427 int state = std::get<int>(valPropMap->second);
Brandon Wymana0f33ce2019-10-17 18:32:29 -0500428 if (state)
429 {
Jim Wrightaca86d02022-06-10 12:01:39 -0500430 // Power on requested
Brandon Wymana0f33ce2019-10-17 18:32:29 -0500431 powerOn = true;
Jim Wrightaca86d02022-06-10 12:01:39 -0500432 powerFaultOccurring = false;
Adriana Kobylaka4d38fa2021-10-05 19:57:47 +0000433 validationTimer->restartOnce(validationTimeout);
Brandon Wymana0f33ce2019-10-17 18:32:29 -0500434 clearFaults();
Brandon Wyman49b8ec42022-04-20 21:18:33 +0000435 syncHistory();
Adriana Kobylakc0a07582021-10-13 15:52:25 +0000436 setPowerConfigGPIO();
Matt Spinlera068f422023-03-10 13:06:49 -0600437 setInputVoltageRating();
Brandon Wymana0f33ce2019-10-17 18:32:29 -0500438 }
439 else
440 {
Jim Wrightaca86d02022-06-10 12:01:39 -0500441 // Power off requested
Brandon Wymana0f33ce2019-10-17 18:32:29 -0500442 powerOn = false;
Jim Wrightaca86d02022-06-10 12:01:39 -0500443 powerFaultOccurring = false;
Adriana Kobylak8f16fb52021-03-31 15:50:15 +0000444 runValidateConfig = true;
Brandon Wymana0f33ce2019-10-17 18:32:29 -0500445 }
446 }
Jim Wrightaca86d02022-06-10 12:01:39 -0500447
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());
Brandon Wymana0f33ce2019-10-17 18:32:29 -0500468}
469
Patrick Williams7354ce62022-07-22 19:26:56 -0500470void PSUManager::presenceChanged(sdbusplus::message_t& msg)
Adriana Kobylak9ba38232021-11-16 20:27:45 +0000471{
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
Brandon Wyman10fc6e82022-02-08 20:51:22 +0000489void PSUManager::setPowerSupplyError(const std::string& psuErrorString)
490{
491 using namespace sdbusplus::xyz::openbmc_project;
Brandon Wyman10fc6e82022-02-08 20:51:22 +0000492 constexpr auto method = "setPowerSupplyError";
493
494 try
495 {
496 // Call D-Bus method to inform pseq of PSU error
Jim Wright5c186c82022-11-17 17:09:33 -0600497 auto methodMsg = bus.new_method_call(
498 powerService.c_str(), POWER_OBJ_PATH, POWER_IFACE, method);
Brandon Wyman10fc6e82022-02-08 20:51:22 +0000499 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
Brandon Wyman8b662882021-10-08 17:31:51 +0000511void PSUManager::createError(const std::string& faultName,
512 std::map<std::string, std::string>& additionalData)
Brandon Wymanb76ab242020-09-16 18:06:06 -0500513{
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 {
Brandon Wyman8b662882021-10-08 17:31:51 +0000521 additionalData["_PID"] = std::to_string(getpid());
522
Patrick Williams48781ae2023-05-10 07:50:50 -0500523 auto service = util::getService(loggingObjectPath,
524 loggingCreateInterface, bus);
Brandon Wymanb76ab242020-09-16 18:06:06 -0500525
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);
Brandon Wyman10fc6e82022-02-08 20:51:22 +0000539 setPowerSupplyError(faultName);
Brandon Wymanb76ab242020-09-16 18:06:06 -0500540 }
Patrick Williamsc1d4de52021-10-06 12:45:57 -0500541 catch (const std::exception& e)
Brandon Wymanb76ab242020-09-16 18:06:06 -0500542 {
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
Brandon Wyman18a24d92022-04-19 22:48:34 +0000551void PSUManager::syncHistory()
552{
Faisal Awadae9b37262023-07-30 21:02:16 -0500553 if (driverName != ACBEL_FSG032_DD_NAME)
Brandon Wyman18a24d92022-04-19 22:48:34 +0000554 {
Faisal Awadae9b37262023-07-30 21:02:16 -0500555 if (!syncHistoryGPIO)
Brandon Wyman18a24d92022-04-19 22:48:34 +0000556 {
Faisal Awadae9b37262023-07-30 21:02:16 -0500557 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");
Brandon Wyman18a24d92022-04-19 22:48:34 +0000569 }
570 }
Brandon Wyman18a24d92022-04-19 22:48:34 +0000571}
572
Brandon Wyman63ea78b2020-09-24 16:49:09 -0500573void PSUManager::analyze()
574{
Patrick Williams319b0dd2023-10-20 11:19:11 -0500575 auto syncHistoryRequired = std::any_of(
576 psus.begin(), psus.end(),
577 [](const auto& psu) { return psu->isSyncHistoryRequired(); });
Brandon Wyman18a24d92022-04-19 22:48:34 +0000578 if (syncHistoryRequired)
579 {
580 syncHistory();
581 }
582
Brandon Wyman63ea78b2020-09-24 16:49:09 -0500583 for (auto& psu : psus)
584 {
585 psu->analyze();
586 }
587
Jim Wright7f9288c2022-12-08 11:57:04 -0600588 analyzeBrownout();
Adriana Kobylake5b1e082022-03-02 15:37:32 +0000589
Jim Wrightcefe85f2022-11-18 09:57:47 -0600590 // Only perform individual PSU analysis if power is on and a brownout has
591 // not already been logged
592 if (powerOn && !brownoutLogged)
Brandon Wyman63ea78b2020-09-24 16:49:09 -0500593 {
Brandon Wyman3180f4d2020-12-08 17:53:46 -0600594 for (auto& psu : psus)
Brandon Wyman63ea78b2020-09-24 16:49:09 -0500595 {
Jim Wright7f9288c2022-12-08 11:57:04 -0600596 std::map<std::string, std::string> additionalData;
Brandon Wyman39ea02b2021-11-23 23:22:23 +0000597
Faisal Awada03e2a022023-11-15 20:31:13 +0000598 if (!psu->isFaultLogged() && !psu->isPresent() &&
599 !validationTimer->isEnabled())
Brandon Wyman3180f4d2020-12-08 17:53:46 -0600600 {
Brandon Wymanda369c72021-10-08 18:43:30 +0000601 std::map<std::string, std::string> requiredPSUsData;
602 auto requiredPSUsPresent = hasRequiredPSUs(requiredPSUsData);
Shawn McCarney9252b7e2022-06-10 12:47:38 -0500603 if (!requiredPSUsPresent && isRequiredPSU(*psu))
Adriana Kobylakf2ba1462021-06-24 15:16:17 +0000604 {
Brandon Wymanda369c72021-10-08 18:43:30 +0000605 additionalData.merge(requiredPSUsData);
Adriana Kobylakf2ba1462021-06-24 15:16:17 +0000606 // Create error for power supply missing.
607 additionalData["CALLOUT_INVENTORY_PATH"] =
608 psu->getInventoryPath();
609 additionalData["CALLOUT_PRIORITY"] = "H";
610 createError(
611 "xyz.openbmc_project.Power.PowerSupply.Error.Missing",
612 additionalData);
613 }
Brandon Wyman3180f4d2020-12-08 17:53:46 -0600614 psu->setFaultLogged();
615 }
616 else if (!psu->isFaultLogged() && psu->isFaulted())
617 {
Brandon Wyman786b6f42021-10-12 20:21:41 +0000618 // Add STATUS_WORD and STATUS_MFR last response, in padded
619 // hexadecimal format.
Brandon Wyman3180f4d2020-12-08 17:53:46 -0600620 additionalData["STATUS_WORD"] =
Brandon Wyman786b6f42021-10-12 20:21:41 +0000621 fmt::format("{:#04x}", psu->getStatusWord());
Patrick Williams48781ae2023-05-10 07:50:50 -0500622 additionalData["STATUS_MFR"] = fmt::format("{:#02x}",
623 psu->getMFRFault());
Brandon Wyman3180f4d2020-12-08 17:53:46 -0600624 // If there are faults being reported, they possibly could be
625 // related to a bug in the firmware version running on the power
626 // supply. Capture that data into the error as well.
627 additionalData["FW_VERSION"] = psu->getFWVersion();
628
Brandon Wymanb85b9dd2021-10-19 21:25:17 +0000629 if (psu->hasCommFault())
630 {
Brandon Wyman85c7bf42021-10-19 22:28:48 +0000631 additionalData["STATUS_CML"] =
632 fmt::format("{:#02x}", psu->getStatusCML());
Brandon Wymanb85b9dd2021-10-19 21:25:17 +0000633 /* Attempts to communicate with the power supply have
634 * reached there limit. Create an error. */
635 additionalData["CALLOUT_DEVICE_PATH"] =
636 psu->getDevicePath();
637
638 createError(
639 "xyz.openbmc_project.Power.PowerSupply.Error.CommFault",
640 additionalData);
641
642 psu->setFaultLogged();
643 }
644 else if ((psu->hasInputFault() || psu->hasVINUVFault()))
Brandon Wyman3180f4d2020-12-08 17:53:46 -0600645 {
Brandon Wymanf07bc792021-10-12 19:00:35 +0000646 // Include STATUS_INPUT for input faults.
647 additionalData["STATUS_INPUT"] =
648 fmt::format("{:#02x}", psu->getStatusInput());
649
Brandon Wyman3180f4d2020-12-08 17:53:46 -0600650 /* The power supply location might be needed if the input
651 * fault is due to a problem with the power supply itself.
652 * Include the inventory path with a call out priority of
653 * low.
654 */
655 additionalData["CALLOUT_INVENTORY_PATH"] =
656 psu->getInventoryPath();
657 additionalData["CALLOUT_PRIORITY"] = "L";
658 createError("xyz.openbmc_project.Power.PowerSupply.Error."
659 "InputFault",
660 additionalData);
661 psu->setFaultLogged();
662 }
Brandon Wyman39ea02b2021-11-23 23:22:23 +0000663 else if (psu->hasPSKillFault())
664 {
665 createError(
666 "xyz.openbmc_project.Power.PowerSupply.Error.PSKillFault",
667 additionalData);
668 psu->setFaultLogged();
669 }
Brandon Wyman6710ba22021-10-27 17:39:31 +0000670 else if (psu->hasVoutOVFault())
671 {
672 // Include STATUS_VOUT for Vout faults.
673 additionalData["STATUS_VOUT"] =
674 fmt::format("{:#02x}", psu->getStatusVout());
675
676 additionalData["CALLOUT_INVENTORY_PATH"] =
677 psu->getInventoryPath();
678
679 createError(
680 "xyz.openbmc_project.Power.PowerSupply.Error.Fault",
681 additionalData);
682
683 psu->setFaultLogged();
684 }
Brandon Wymanb10b3be2021-11-09 22:12:15 +0000685 else if (psu->hasIoutOCFault())
686 {
687 // Include STATUS_IOUT for Iout faults.
688 additionalData["STATUS_IOUT"] =
689 fmt::format("{:#02x}", psu->getStatusIout());
690
691 createError(
692 "xyz.openbmc_project.Power.PowerSupply.Error.IoutOCFault",
693 additionalData);
694
695 psu->setFaultLogged();
696 }
Brandon Wyman39ea02b2021-11-23 23:22:23 +0000697 else if (psu->hasVoutUVFault() || psu->hasPS12VcsFault() ||
698 psu->hasPSCS12VFault())
Brandon Wyman2cf46942021-10-28 19:09:16 +0000699 {
700 // Include STATUS_VOUT for Vout faults.
701 additionalData["STATUS_VOUT"] =
702 fmt::format("{:#02x}", psu->getStatusVout());
703
704 additionalData["CALLOUT_INVENTORY_PATH"] =
705 psu->getInventoryPath();
706
707 createError(
708 "xyz.openbmc_project.Power.PowerSupply.Error.Fault",
709 additionalData);
710
711 psu->setFaultLogged();
712 }
Brandon Wyman7ee4d7e2021-11-19 20:48:23 +0000713 // A fan fault should have priority over a temperature fault,
714 // since a failed fan may lead to a temperature problem.
Jim Wrightaca86d02022-06-10 12:01:39 -0500715 // Only process if not in power fault window.
716 else if (psu->hasFanFault() && !powerFaultOccurring)
Brandon Wyman7ee4d7e2021-11-19 20:48:23 +0000717 {
718 // Include STATUS_TEMPERATURE and STATUS_FANS_1_2
719 additionalData["STATUS_TEMPERATURE"] =
720 fmt::format("{:#02x}", psu->getStatusTemperature());
721 additionalData["STATUS_FANS_1_2"] =
722 fmt::format("{:#02x}", psu->getStatusFans12());
723
724 additionalData["CALLOUT_INVENTORY_PATH"] =
725 psu->getInventoryPath();
726
727 createError(
728 "xyz.openbmc_project.Power.PowerSupply.Error.FanFault",
729 additionalData);
730
731 psu->setFaultLogged();
732 }
Brandon Wyman96893a42021-11-05 19:56:57 +0000733 else if (psu->hasTempFault())
734 {
735 // Include STATUS_TEMPERATURE for temperature faults.
736 additionalData["STATUS_TEMPERATURE"] =
737 fmt::format("{:#02x}", psu->getStatusTemperature());
738
739 additionalData["CALLOUT_INVENTORY_PATH"] =
740 psu->getInventoryPath();
741
742 createError(
743 "xyz.openbmc_project.Power.PowerSupply.Error.Fault",
744 additionalData);
745
746 psu->setFaultLogged();
747 }
Brandon Wyman3180f4d2020-12-08 17:53:46 -0600748 else if (psu->hasMFRFault())
749 {
750 /* This can represent a variety of faults that result in
751 * calling out the power supply for replacement: Output
752 * OverCurrent, Output Under Voltage, and potentially other
753 * faults.
754 *
755 * Also plan on putting specific fault in AdditionalData,
756 * along with register names and register values
757 * (STATUS_WORD, STATUS_MFR, etc.).*/
758
759 additionalData["CALLOUT_INVENTORY_PATH"] =
760 psu->getInventoryPath();
761
762 createError(
763 "xyz.openbmc_project.Power.PowerSupply.Error.Fault",
Brandon Wyman52e54e82020-10-08 14:44:58 -0500764 additionalData);
Brandon Wyman63ea78b2020-09-24 16:49:09 -0500765
Brandon Wyman3180f4d2020-12-08 17:53:46 -0600766 psu->setFaultLogged();
767 }
Jim Wrightaca86d02022-06-10 12:01:39 -0500768 // Only process if not in power fault window.
769 else if (psu->hasPgoodFault() && !powerFaultOccurring)
Brandon Wyman2916ea52021-11-06 03:31:18 +0000770 {
771 /* POWER_GOOD# is not low, or OFF is on */
772 additionalData["CALLOUT_INVENTORY_PATH"] =
773 psu->getInventoryPath();
774
775 createError(
776 "xyz.openbmc_project.Power.PowerSupply.Error.Fault",
777 additionalData);
778
779 psu->setFaultLogged();
780 }
Brandon Wyman4176d6b2020-10-07 17:41:06 -0500781 }
Brandon Wyman63ea78b2020-09-24 16:49:09 -0500782 }
783 }
784}
785
Jim Wright7f9288c2022-12-08 11:57:04 -0600786void PSUManager::analyzeBrownout()
787{
788 // Count number of power supplies failing
789 size_t presentCount = 0;
790 size_t notPresentCount = 0;
791 size_t acFailedCount = 0;
792 size_t pgoodFailedCount = 0;
793 for (const auto& psu : psus)
794 {
795 if (psu->isPresent())
796 {
797 ++presentCount;
798 if (psu->hasACFault())
799 {
800 ++acFailedCount;
801 }
802 else if (psu->hasPgoodFault())
803 {
804 ++pgoodFailedCount;
805 }
806 }
807 else
808 {
809 ++notPresentCount;
810 }
811 }
812
813 // Only issue brownout failure if chassis pgood has failed, it has not
814 // already been logged, at least one PSU has seen an AC fail, and all
815 // present PSUs have an AC or pgood failure. Note an AC fail is only set if
816 // at least one PSU is present.
817 if (powerFaultOccurring && !brownoutLogged && acFailedCount &&
818 (presentCount == (acFailedCount + pgoodFailedCount)))
819 {
820 // Indicate that the system is in a brownout condition by creating an
821 // error log and setting the PowerSystemInputs status property to Fault.
822 powerSystemInputs.status(
823 sdbusplus::xyz::openbmc_project::State::Decorator::server::
824 PowerSystemInputs::Status::Fault);
825
826 std::map<std::string, std::string> additionalData;
827 additionalData.emplace("NOT_PRESENT_COUNT",
828 std::to_string(notPresentCount));
829 additionalData.emplace("VIN_FAULT_COUNT",
830 std::to_string(acFailedCount));
831 additionalData.emplace("PGOOD_FAULT_COUNT",
832 std::to_string(pgoodFailedCount));
833 log<level::INFO>(
834 fmt::format(
835 "Brownout detected, not present count: {}, AC fault count {}, pgood fault count: {}",
836 notPresentCount, acFailedCount, pgoodFailedCount)
837 .c_str());
838
839 createError("xyz.openbmc_project.State.Shutdown.Power.Error.Blackout",
840 additionalData);
841 brownoutLogged = true;
842 }
843 else
844 {
845 // If a brownout was previously logged but at least one PSU is not
846 // currently in AC fault, determine if the brownout condition can be
847 // cleared
848 if (brownoutLogged && (acFailedCount < presentCount))
849 {
850 // Chassis only recognizes the PowerSystemInputs change when it is
851 // off
852 try
853 {
854 using PowerState = sdbusplus::xyz::openbmc_project::State::
855 server::Chassis::PowerState;
856 PowerState currentPowerState;
857 util::getProperty<PowerState>(
858 "xyz.openbmc_project.State.Chassis", "CurrentPowerState",
859 "/xyz/openbmc_project/state/chassis0",
860 "xyz.openbmc_project.State.Chassis", bus,
861 currentPowerState);
862
863 if (currentPowerState == PowerState::Off)
864 {
865 // Indicate that the system is no longer in a brownout
866 // condition by setting the PowerSystemInputs status
867 // property to Good.
868 log<level::INFO>(
869 fmt::format(
870 "Brownout cleared, not present count: {}, AC fault count {}, pgood fault count: {}",
871 notPresentCount, acFailedCount, pgoodFailedCount)
872 .c_str());
873 powerSystemInputs.status(
874 sdbusplus::xyz::openbmc_project::State::Decorator::
875 server::PowerSystemInputs::Status::Good);
876 brownoutLogged = false;
877 }
878 }
879 catch (const std::exception& e)
880 {
881 log<level::ERR>(
882 fmt::format("Error trying to clear brownout, error: {}",
883 e.what())
884 .c_str());
885 }
886 }
887 }
888}
889
Brandon Wyman64e97752022-06-03 23:50:13 +0000890void PSUManager::updateMissingPSUs()
891{
892 if (supportedConfigs.empty() || psus.empty())
893 {
894 return;
895 }
896
897 // Power supplies default to missing. If the power supply is present,
898 // the PowerSupply object will update the inventory Present property to
899 // true. If we have less than the required number of power supplies, and
900 // this power supply is missing, update the inventory Present property
901 // to false to indicate required power supply is missing. Avoid
902 // indicating power supply missing if not required.
903
904 auto presentCount =
905 std::count_if(psus.begin(), psus.end(),
906 [](const auto& psu) { return psu->isPresent(); });
907
908 for (const auto& config : supportedConfigs)
909 {
910 for (const auto& psu : psus)
911 {
912 auto psuModel = psu->getModelName();
913 auto psuShortName = psu->getShortName();
914 auto psuInventoryPath = psu->getInventoryPath();
915 auto relativeInvPath =
916 psuInventoryPath.substr(strlen(INVENTORY_OBJ_PATH));
917 auto psuPresent = psu->isPresent();
918 auto presProperty = false;
919 auto propReadFail = false;
920
921 try
922 {
923 presProperty = getPresence(bus, psuInventoryPath);
924 propReadFail = false;
925 }
Patrick Williams7354ce62022-07-22 19:26:56 -0500926 catch (const sdbusplus::exception_t& e)
Brandon Wyman64e97752022-06-03 23:50:13 +0000927 {
928 propReadFail = true;
929 // Relying on property change or interface added to retry.
930 // Log an informational trace to the journal.
931 log<level::INFO>(
932 fmt::format("D-Bus property {} access failure exception",
933 psuInventoryPath)
934 .c_str());
935 }
936
937 if (psuModel.empty())
938 {
939 if (!propReadFail && (presProperty != psuPresent))
940 {
941 // We already have this property, and it is not false
942 // set Present to false
943 setPresence(bus, relativeInvPath, psuPresent, psuShortName);
944 }
945 continue;
946 }
947
948 if (config.first != psuModel)
949 {
950 continue;
951 }
952
953 if ((presentCount < config.second.powerSupplyCount) && !psuPresent)
954 {
955 setPresence(bus, relativeInvPath, psuPresent, psuShortName);
956 }
957 }
958 }
959}
960
Adriana Kobylak8f16fb52021-03-31 15:50:15 +0000961void PSUManager::validateConfig()
962{
Adriana Kobylakb23e4432022-04-01 14:22:47 +0000963 if (!runValidateConfig || supportedConfigs.empty() || psus.empty())
Adriana Kobylak8f16fb52021-03-31 15:50:15 +0000964 {
965 return;
966 }
967
Brandon Wyman9666ddf2022-04-27 21:53:14 +0000968 for (const auto& psu : psus)
969 {
970 if ((psu->hasInputFault() || psu->hasVINUVFault()))
971 {
972 // Do not try to validate if input voltage fault present.
973 validationTimer->restartOnce(validationTimeout);
974 return;
975 }
976 }
977
Adriana Kobylak4d9aaf92021-06-30 15:27:42 +0000978 std::map<std::string, std::string> additionalData;
979 auto supported = hasRequiredPSUs(additionalData);
980 if (supported)
981 {
982 runValidateConfig = false;
Faisal Awadac6fa6662023-04-25 22:43:01 -0500983 double actualVoltage;
984 int inputVoltage;
985 int previousInputVoltage = 0;
986 bool voltageMismatch = false;
987
988 for (const auto& psu : psus)
989 {
990 if (!psu->isPresent())
991 {
992 // Only present PSUs report a valid input voltage
993 continue;
994 }
995 psu->getInputVoltage(actualVoltage, inputVoltage);
996 if (previousInputVoltage && inputVoltage &&
997 (previousInputVoltage != inputVoltage))
998 {
999 additionalData["EXPECTED_VOLTAGE"] =
1000 std::to_string(previousInputVoltage);
1001 additionalData["ACTUAL_VOLTAGE"] =
1002 std::to_string(actualVoltage);
1003 voltageMismatch = true;
1004 }
1005 if (!previousInputVoltage && inputVoltage)
1006 {
1007 previousInputVoltage = inputVoltage;
1008 }
1009 }
1010 if (!voltageMismatch)
1011 {
1012 return;
1013 }
Adriana Kobylak4d9aaf92021-06-30 15:27:42 +00001014 }
1015
1016 // Validation failed, create an error log.
1017 // Return without setting the runValidateConfig flag to false because
1018 // it may be that an additional supported configuration interface is
1019 // added and we need to validate it to see if it matches this system.
1020 createError("xyz.openbmc_project.Power.PowerSupply.Error.NotSupported",
1021 additionalData);
1022}
1023
1024bool PSUManager::hasRequiredPSUs(
1025 std::map<std::string, std::string>& additionalData)
1026{
Adriana Kobylak8f16fb52021-03-31 15:50:15 +00001027 std::string model{};
Adriana Kobylak523704d2021-09-21 15:55:41 +00001028 if (!validateModelName(model, additionalData))
Adriana Kobylak8f16fb52021-03-31 15:50:15 +00001029 {
Adriana Kobylak523704d2021-09-21 15:55:41 +00001030 return false;
Adriana Kobylak8f16fb52021-03-31 15:50:15 +00001031 }
Adriana Kobylak70e7f932021-06-10 18:53:56 +00001032
Adriana Kobylak4d9aaf92021-06-30 15:27:42 +00001033 auto presentCount =
1034 std::count_if(psus.begin(), psus.end(),
1035 [](const auto& psu) { return psu->isPresent(); });
1036
Adriana Kobylak70e7f932021-06-10 18:53:56 +00001037 // Validate the supported configurations. A system may support more than one
Adriana Kobylak4175ffb2021-08-02 14:51:05 +00001038 // power supply model configuration. Since all configurations need to be
1039 // checked, the additional data would contain only the information of the
1040 // last configuration that did not match.
1041 std::map<std::string, std::string> tmpAdditionalData;
Adriana Kobylak70e7f932021-06-10 18:53:56 +00001042 for (const auto& config : supportedConfigs)
1043 {
Adriana Kobylak4d9aaf92021-06-30 15:27:42 +00001044 if (config.first != model)
Adriana Kobylak70e7f932021-06-10 18:53:56 +00001045 {
1046 continue;
1047 }
Brandon Wyman64e97752022-06-03 23:50:13 +00001048
Jim Wright941b60d2022-10-19 16:22:17 -05001049 // Number of power supplies present should equal or exceed the expected
1050 // count
1051 if (presentCount < config.second.powerSupplyCount)
Adriana Kobylak70e7f932021-06-10 18:53:56 +00001052 {
Adriana Kobylak4175ffb2021-08-02 14:51:05 +00001053 tmpAdditionalData.clear();
1054 tmpAdditionalData["EXPECTED_COUNT"] =
Adriana Kobylak70e7f932021-06-10 18:53:56 +00001055 std::to_string(config.second.powerSupplyCount);
Adriana Kobylak4175ffb2021-08-02 14:51:05 +00001056 tmpAdditionalData["ACTUAL_COUNT"] = std::to_string(presentCount);
Adriana Kobylak70e7f932021-06-10 18:53:56 +00001057 continue;
1058 }
Adriana Kobylak4175ffb2021-08-02 14:51:05 +00001059
1060 bool voltageValidated = true;
1061 for (const auto& psu : psus)
1062 {
1063 if (!psu->isPresent())
1064 {
1065 // Only present PSUs report a valid input voltage
1066 continue;
1067 }
1068
1069 double actualInputVoltage;
1070 int inputVoltage;
1071 psu->getInputVoltage(actualInputVoltage, inputVoltage);
1072
1073 if (std::find(config.second.inputVoltage.begin(),
1074 config.second.inputVoltage.end(),
1075 inputVoltage) == config.second.inputVoltage.end())
1076 {
1077 tmpAdditionalData.clear();
1078 tmpAdditionalData["ACTUAL_VOLTAGE"] =
1079 std::to_string(actualInputVoltage);
1080 for (const auto& voltage : config.second.inputVoltage)
1081 {
1082 tmpAdditionalData["EXPECTED_VOLTAGE"] +=
1083 std::to_string(voltage) + " ";
1084 }
1085 tmpAdditionalData["CALLOUT_INVENTORY_PATH"] =
1086 psu->getInventoryPath();
1087
1088 voltageValidated = false;
1089 break;
1090 }
1091 }
1092 if (!voltageValidated)
1093 {
1094 continue;
1095 }
1096
Adriana Kobylak4d9aaf92021-06-30 15:27:42 +00001097 return true;
Adriana Kobylak70e7f932021-06-10 18:53:56 +00001098 }
Adriana Kobylak70e7f932021-06-10 18:53:56 +00001099
Adriana Kobylak4175ffb2021-08-02 14:51:05 +00001100 additionalData.insert(tmpAdditionalData.begin(), tmpAdditionalData.end());
Adriana Kobylak4d9aaf92021-06-30 15:27:42 +00001101 return false;
Adriana Kobylak8f16fb52021-03-31 15:50:15 +00001102}
1103
Shawn McCarney9252b7e2022-06-10 12:47:38 -05001104unsigned int PSUManager::getRequiredPSUCount()
1105{
1106 unsigned int requiredCount{0};
1107
1108 // Verify we have the supported configuration and PSU information
1109 if (!supportedConfigs.empty() && !psus.empty())
1110 {
1111 // Find PSU models. They should all be the same.
1112 std::set<std::string> models{};
1113 std::for_each(psus.begin(), psus.end(), [&models](const auto& psu) {
1114 if (!psu->getModelName().empty())
1115 {
1116 models.insert(psu->getModelName());
1117 }
1118 });
1119
1120 // If exactly one model was found, find corresponding configuration
1121 if (models.size() == 1)
1122 {
1123 const std::string& model = *(models.begin());
1124 auto it = supportedConfigs.find(model);
1125 if (it != supportedConfigs.end())
1126 {
1127 requiredCount = it->second.powerSupplyCount;
1128 }
1129 }
1130 }
1131
1132 return requiredCount;
1133}
1134
1135bool PSUManager::isRequiredPSU(const PowerSupply& psu)
1136{
1137 // Get required number of PSUs; if not found, we don't know if PSU required
1138 unsigned int requiredCount = getRequiredPSUCount();
1139 if (requiredCount == 0)
1140 {
1141 return false;
1142 }
1143
1144 // If total PSU count <= the required count, all PSUs are required
1145 if (psus.size() <= requiredCount)
1146 {
1147 return true;
1148 }
1149
1150 // We don't currently get information from EntityManager about which PSUs
1151 // are required, so we have to do some guesswork. First check if this PSU
1152 // is present. If so, assume it is required.
1153 if (psu.isPresent())
1154 {
1155 return true;
1156 }
1157
1158 // This PSU is not present. Count the number of other PSUs that are
1159 // present. If enough other PSUs are present, assume the specified PSU is
1160 // not required.
1161 unsigned int psuCount =
1162 std::count_if(psus.begin(), psus.end(),
1163 [](const auto& psu) { return psu->isPresent(); });
1164 if (psuCount >= requiredCount)
1165 {
1166 return false;
1167 }
1168
1169 // Check if this PSU was previously present. If so, assume it is required.
1170 // We know it was previously present if it has a non-empty model name.
1171 if (!psu.getModelName().empty())
1172 {
1173 return true;
1174 }
1175
1176 // This PSU was never present. Count the number of other PSUs that were
1177 // previously present. If including those PSUs is enough, assume the
1178 // specified PSU is not required.
1179 psuCount += std::count_if(psus.begin(), psus.end(), [](const auto& psu) {
1180 return (!psu->isPresent() && !psu->getModelName().empty());
1181 });
1182 if (psuCount >= requiredCount)
1183 {
1184 return false;
1185 }
1186
1187 // We still haven't found enough PSUs. Sort the inventory paths of PSUs
1188 // that were never present. PSU inventory paths typically end with the PSU
1189 // number (0, 1, 2, ...). Assume that lower-numbered PSUs are required.
1190 std::vector<std::string> sortedPaths;
1191 std::for_each(psus.begin(), psus.end(), [&sortedPaths](const auto& psu) {
1192 if (!psu->isPresent() && psu->getModelName().empty())
1193 {
1194 sortedPaths.push_back(psu->getInventoryPath());
1195 }
1196 });
1197 std::sort(sortedPaths.begin(), sortedPaths.end());
1198
1199 // Check if specified PSU is close enough to start of list to be required
1200 for (const auto& path : sortedPaths)
1201 {
1202 if (path == psu.getInventoryPath())
1203 {
1204 return true;
1205 }
1206 if (++psuCount >= requiredCount)
1207 {
1208 break;
1209 }
1210 }
1211
1212 // PSU was not close to start of sorted list; assume not required
1213 return false;
1214}
1215
Adriana Kobylak523704d2021-09-21 15:55:41 +00001216bool PSUManager::validateModelName(
1217 std::string& model, std::map<std::string, std::string>& additionalData)
1218{
1219 // Check that all PSUs have the same model name. Initialize the model
1220 // variable with the first PSU name found, then use it as a base to compare
Adriana Kobylakb70eae92022-01-20 22:09:56 +00001221 // against the rest of the PSUs and get its inventory path to use as callout
1222 // if needed.
Adriana Kobylak523704d2021-09-21 15:55:41 +00001223 model.clear();
Adriana Kobylakb70eae92022-01-20 22:09:56 +00001224 std::string modelInventoryPath{};
Adriana Kobylak523704d2021-09-21 15:55:41 +00001225 for (const auto& psu : psus)
1226 {
1227 auto psuModel = psu->getModelName();
1228 if (psuModel.empty())
1229 {
1230 continue;
1231 }
1232 if (model.empty())
1233 {
1234 model = psuModel;
Adriana Kobylakb70eae92022-01-20 22:09:56 +00001235 modelInventoryPath = psu->getInventoryPath();
Adriana Kobylak523704d2021-09-21 15:55:41 +00001236 continue;
1237 }
1238 if (psuModel != model)
1239 {
Adriana Kobylakb70eae92022-01-20 22:09:56 +00001240 if (supportedConfigs.find(model) != supportedConfigs.end())
1241 {
1242 // The base model is supported, callout the mismatched PSU. The
1243 // mismatched PSU may or may not be supported.
1244 additionalData["EXPECTED_MODEL"] = model;
1245 additionalData["ACTUAL_MODEL"] = psuModel;
1246 additionalData["CALLOUT_INVENTORY_PATH"] =
1247 psu->getInventoryPath();
1248 }
1249 else if (supportedConfigs.find(psuModel) != supportedConfigs.end())
1250 {
1251 // The base model is not supported, but the mismatched PSU is,
1252 // callout the base PSU.
1253 additionalData["EXPECTED_MODEL"] = psuModel;
1254 additionalData["ACTUAL_MODEL"] = model;
1255 additionalData["CALLOUT_INVENTORY_PATH"] = modelInventoryPath;
1256 }
1257 else
1258 {
1259 // The base model and the mismatched PSU are not supported or
1260 // could not be found in the supported configuration, callout
1261 // the mismatched PSU.
1262 additionalData["EXPECTED_MODEL"] = model;
1263 additionalData["ACTUAL_MODEL"] = psuModel;
1264 additionalData["CALLOUT_INVENTORY_PATH"] =
1265 psu->getInventoryPath();
1266 }
Adriana Kobylak523704d2021-09-21 15:55:41 +00001267 model.clear();
1268 return false;
1269 }
1270 }
1271 return true;
1272}
1273
Adriana Kobylakc0a07582021-10-13 15:52:25 +00001274void PSUManager::setPowerConfigGPIO()
1275{
1276 if (!powerConfigGPIO)
1277 {
1278 return;
1279 }
1280
1281 std::string model{};
1282 std::map<std::string, std::string> additionalData;
1283 if (!validateModelName(model, additionalData))
1284 {
1285 return;
1286 }
1287
1288 auto config = supportedConfigs.find(model);
1289 if (config != supportedConfigs.end())
1290 {
1291 // The power-config-full-load is an open drain GPIO. Set it to low (0)
1292 // if the supported configuration indicates that this system model
1293 // expects the maximum number of power supplies (full load set to true).
1294 // Else, set it to high (1), this is the default.
1295 auto powerConfigValue =
1296 (config->second.powerConfigFullLoad == true ? 0 : 1);
1297 auto flags = gpiod::line_request::FLAG_OPEN_DRAIN;
1298 powerConfigGPIO->write(powerConfigValue, flags);
1299 }
1300}
1301
Faisal Awadab66ae502023-04-01 18:30:32 -05001302void PSUManager::buildDriverName(uint64_t i2cbus, uint64_t i2caddr)
1303{
1304 namespace fs = std::filesystem;
1305 std::stringstream ss;
1306 ss << std::hex << std::setw(4) << std::setfill('0') << i2caddr;
Patrick Williams48781ae2023-05-10 07:50:50 -05001307 std::string symLinkPath = deviceDirPath + std::to_string(i2cbus) + "-" +
1308 ss.str() + driverDirName;
Faisal Awadab66ae502023-04-01 18:30:32 -05001309 try
1310 {
1311 fs::path linkStrPath = fs::read_symlink(symLinkPath);
1312 driverName = linkStrPath.filename();
1313 }
1314 catch (const std::exception& e)
1315 {
1316 log<level::ERR>(fmt::format("Failed to find device driver {}, error {}",
1317 symLinkPath, e.what())
1318 .c_str());
1319 }
1320}
Faisal Awadab7131a12023-10-26 19:38:45 -05001321
1322void PSUManager::populateDriverName()
1323{
1324 std::string driverName;
1325 // Search in PSUs for driver name
1326 std::for_each(psus.begin(), psus.end(), [&driverName](auto& psu) {
1327 if (!psu->getDriverName().empty())
1328 {
1329 driverName = psu->getDriverName();
1330 }
1331 });
1332 // Assign driver name to all PSUs
1333 std::for_each(psus.begin(), psus.end(),
1334 [=](auto& psu) { psu->setDriverName(driverName); });
1335}
Brandon Wyman63ea78b2020-09-24 16:49:09 -05001336} // namespace phosphor::power::manager