xref: /openbmc/phosphor-power/phosphor-power-supply/power_supply.cpp (revision a2a830b1ffa327bd36dcca5c1cac462ae7737a25)
1 #include "config.h"
2 
3 #include "power_supply.hpp"
4 
5 #include "types.hpp"
6 #include "util.hpp"
7 
8 #include <fmt/format.h>
9 
10 #include <xyz/openbmc_project/Common/Device/error.hpp>
11 
12 #include <chrono>  // sleep_for()
13 #include <cstdint> // uint8_t...
14 #include <fstream>
15 #include <thread> // sleep_for()
16 
17 namespace phosphor::power::psu
18 {
19 // Amount of time in milliseconds to delay between power supply going from
20 // missing to present before running the bind command(s).
21 constexpr auto bindDelay = 1000;
22 
23 using namespace phosphor::logging;
24 using namespace sdbusplus::xyz::openbmc_project::Common::Device::Error;
25 
26 PowerSupply::PowerSupply(sdbusplus::bus::bus& bus, const std::string& invpath,
27                          std::uint8_t i2cbus, std::uint16_t i2caddr,
28                          const std::string& gpioLineName) :
29     bus(bus),
30     inventoryPath(invpath), bindPath("/sys/bus/i2c/drivers/ibm-cffps")
31 {
32     if (inventoryPath.empty())
33     {
34         throw std::invalid_argument{"Invalid empty inventoryPath"};
35     }
36 
37     if (gpioLineName.empty())
38     {
39         throw std::invalid_argument{"Invalid empty gpioLineName"};
40     }
41 
42     log<level::DEBUG>(fmt::format("gpioLineName: {}", gpioLineName).c_str());
43     presenceGPIO = createGPIO(gpioLineName);
44 
45     std::ostringstream ss;
46     ss << std::hex << std::setw(4) << std::setfill('0') << i2caddr;
47     std::string addrStr = ss.str();
48     std::string busStr = std::to_string(i2cbus);
49     bindDevice = busStr;
50     bindDevice.append("-");
51     bindDevice.append(addrStr);
52 
53     pmbusIntf = phosphor::pmbus::createPMBus(i2cbus, addrStr);
54 
55     // Get the current state of the Present property.
56     try
57     {
58         updatePresenceGPIO();
59     }
60     catch (...)
61     {
62         // If the above attempt to use the GPIO failed, it likely means that the
63         // GPIOs are in use by the kernel, meaning it is using gpio-keys.
64         // So, I should rely on phosphor-gpio-presence to update D-Bus, and
65         // work that way for power supply presence.
66         presenceGPIO = nullptr;
67         // Setup the functions to call when the D-Bus inventory path for the
68         // Present property changes.
69         presentMatch = std::make_unique<sdbusplus::bus::match_t>(
70             bus,
71             sdbusplus::bus::match::rules::propertiesChanged(inventoryPath,
72                                                             INVENTORY_IFACE),
73             [this](auto& msg) { this->inventoryChanged(msg); });
74 
75         presentAddedMatch = std::make_unique<sdbusplus::bus::match_t>(
76             bus,
77             sdbusplus::bus::match::rules::interfacesAdded() +
78                 sdbusplus::bus::match::rules::argNpath(0, inventoryPath),
79             [this](auto& msg) { this->inventoryAdded(msg); });
80 
81         updatePresence();
82         updateInventory();
83     }
84 }
85 
86 void PowerSupply::bindOrUnbindDriver(bool present)
87 {
88     auto action = (present) ? "bind" : "unbind";
89     auto path = bindPath / action;
90 
91     if (present)
92     {
93         log<level::INFO>(
94             fmt::format("Binding device driver. path: {} device: {}",
95                         path.string(), bindDevice)
96                 .c_str());
97     }
98     else
99     {
100         log<level::INFO>(
101             fmt::format("Unbinding device driver. path: {} device: {}",
102                         path.string(), bindDevice)
103                 .c_str());
104     }
105 
106     std::ofstream file;
107 
108     file.exceptions(std::ofstream::failbit | std::ofstream::badbit |
109                     std::ofstream::eofbit);
110 
111     try
112     {
113         file.open(path);
114         file << bindDevice;
115         file.close();
116     }
117     catch (const std::exception& e)
118     {
119         auto err = errno;
120 
121         log<level::ERR>(
122             fmt::format("Failed binding or unbinding device. errno={}", err)
123                 .c_str());
124     }
125 }
126 
127 void PowerSupply::updatePresence()
128 {
129     try
130     {
131         present = getPresence(bus, inventoryPath);
132     }
133     catch (const sdbusplus::exception::exception& e)
134     {
135         // Relying on property change or interface added to retry.
136         // Log an informational trace to the journal.
137         log<level::INFO>(
138             fmt::format("D-Bus property {} access failure exception",
139                         inventoryPath)
140                 .c_str());
141     }
142 }
143 
144 void PowerSupply::updatePresenceGPIO()
145 {
146     bool presentOld = present;
147 
148     try
149     {
150         if (presenceGPIO->read() > 0)
151         {
152             present = true;
153         }
154         else
155         {
156             present = false;
157         }
158     }
159     catch (const std::exception& e)
160     {
161         log<level::ERR>(
162             fmt::format("presenceGPIO read fail: {}", e.what()).c_str());
163         throw;
164     }
165 
166     if (presentOld != present)
167     {
168         log<level::DEBUG>(
169             fmt::format("presentOld: {} present: {}", presentOld, present)
170                 .c_str());
171         if (present)
172         {
173             std::this_thread::sleep_for(std::chrono::milliseconds(bindDelay));
174             bindOrUnbindDriver(present);
175             pmbusIntf->findHwmonDir();
176             onOffConfig(phosphor::pmbus::ON_OFF_CONFIG_CONTROL_PIN_ONLY);
177             clearFaults();
178         }
179         else
180         {
181             bindOrUnbindDriver(present);
182         }
183 
184         auto invpath = inventoryPath.substr(strlen(INVENTORY_OBJ_PATH));
185         auto const lastSlashPos = invpath.find_last_of('/');
186         std::string prettyName = invpath.substr(lastSlashPos + 1);
187         setPresence(bus, invpath, present, prettyName);
188         updateInventory();
189     }
190 }
191 
192 void PowerSupply::analyze()
193 {
194     using namespace phosphor::pmbus;
195 
196     if (presenceGPIO)
197     {
198         updatePresenceGPIO();
199     }
200 
201     if ((present) && (readFail < LOG_LIMIT))
202     {
203         try
204         {
205             statusWord = pmbusIntf->read(STATUS_WORD, Type::Debug);
206             // Read worked, reset the fail count.
207             readFail = 0;
208 
209             if (statusWord)
210             {
211                 statusInput = pmbusIntf->read(STATUS_INPUT, Type::Debug);
212                 statusMFR = pmbusIntf->read(STATUS_MFR, Type::Debug);
213                 statusCML = pmbusIntf->read(STATUS_CML, Type::Debug);
214                 auto status0Vout = pmbusIntf->insertPageNum(STATUS_VOUT, 0);
215                 statusVout = pmbusIntf->read(status0Vout, Type::Debug);
216                 if (statusWord & status_word::CML_FAULT)
217                 {
218                     if (!cmlFault)
219                     {
220                         log<level::ERR>(
221                             fmt::format("CML fault: STATUS_WORD = {:#04x}, "
222                                         "STATUS_CML = {:#02x}",
223                                         statusWord, statusCML)
224                                 .c_str());
225                     }
226                     faultFound = true;
227                     cmlFault = true;
228                 }
229 
230                 if (statusWord & status_word::INPUT_FAULT_WARN)
231                 {
232                     if (!inputFault)
233                     {
234                         log<level::ERR>(
235                             fmt::format("INPUT fault: STATUS_WORD = {:#04x}, "
236                                         "STATUS_MFR_SPECIFIC = {:#02x}, "
237                                         "STATUS_INPUT = {:#02x}",
238                                         statusWord, statusMFR, statusInput)
239                                 .c_str());
240                     }
241 
242                     faultFound = true;
243                     inputFault = true;
244                 }
245 
246                 if (statusWord & status_word::VOUT_OV_FAULT)
247                 {
248                     if (!voutOVFault)
249                     {
250                         log<level::ERR>(
251                             fmt::format("INPUT fault: STATUS_WORD = {:#04x}, "
252                                         "STATUS_MFR_SPECIFIC = {:#02x}, "
253                                         "STATUS_VOUT = {:#02x}",
254                                         statusWord, statusMFR, statusVout)
255                                 .c_str());
256                     }
257                     faultFound = true;
258                     voutOVFault = true;
259                 }
260 
261                 if (statusWord & status_word::MFR_SPECIFIC_FAULT)
262                 {
263                     if (!mfrFault)
264                     {
265                         log<level::ERR>(
266                             fmt::format("MFR fault: "
267                                         "STATUS_WORD = {:#04x} "
268                                         "STATUS_MFR_SPECIFIC = {:#02x}",
269                                         statusWord, statusMFR)
270                                 .c_str());
271                     }
272                     faultFound = true;
273                     mfrFault = true;
274                 }
275 
276                 if (statusWord & status_word::VIN_UV_FAULT)
277                 {
278                     if (!vinUVFault)
279                     {
280                         log<level::ERR>(
281                             fmt::format("VIN_UV fault: STATUS_WORD = {:#04x}, "
282                                         "STATUS_MFR_SPECIFIC = {:#02x}, "
283                                         "STATUS_INPUT = {:#02x}",
284                                         statusWord, statusMFR, statusInput)
285                                 .c_str());
286                     }
287 
288                     faultFound = true;
289                     vinUVFault = true;
290                 }
291             }
292             else
293             {
294                 faultFound = false;
295                 cmlFault = false;
296                 inputFault = false;
297                 mfrFault = false;
298                 vinUVFault = false;
299                 voutOVFault = false;
300             }
301         }
302         catch (const ReadFailure& e)
303         {
304             readFail++;
305             phosphor::logging::commit<ReadFailure>();
306         }
307     }
308 }
309 
310 void PowerSupply::onOffConfig(uint8_t data)
311 {
312     using namespace phosphor::pmbus;
313 
314     if (present)
315     {
316         log<level::INFO>("ON_OFF_CONFIG write", entry("DATA=0x%02X", data));
317         try
318         {
319             std::vector<uint8_t> configData{data};
320             pmbusIntf->writeBinary(ON_OFF_CONFIG, configData,
321                                    Type::HwmonDeviceDebug);
322         }
323         catch (...)
324         {
325             // The underlying code in writeBinary will log a message to the
326             // journal if the write fails. If the ON_OFF_CONFIG is not setup
327             // as desired, later fault detection and analysis code should
328             // catch any of the fall out. We should not need to terminate
329             // the application if this write fails.
330         }
331     }
332 }
333 
334 void PowerSupply::clearFaults()
335 {
336     faultLogged = false;
337     // The PMBus device driver does not allow for writing CLEAR_FAULTS
338     // directly. However, the pmbus hwmon device driver code will send a
339     // CLEAR_FAULTS after reading from any of the hwmon "files" in sysfs, so
340     // reading in1_input should result in clearing the fault bits in
341     // STATUS_BYTE/STATUS_WORD.
342     // I do not care what the return value is.
343     if (present)
344     {
345         faultFound = false;
346         inputFault = false;
347         mfrFault = false;
348         statusMFR = 0;
349         vinUVFault = false;
350         cmlFault = false;
351         voutOVFault = false;
352         readFail = 0;
353 
354         try
355         {
356             static_cast<void>(
357                 pmbusIntf->read("in1_input", phosphor::pmbus::Type::Hwmon));
358         }
359         catch (const ReadFailure& e)
360         {
361             // Since I do not care what the return value is, I really do not
362             // care much if it gets a ReadFailure either. However, this
363             // should not prevent the application from continuing to run, so
364             // catching the read failure.
365         }
366     }
367 }
368 
369 void PowerSupply::inventoryChanged(sdbusplus::message::message& msg)
370 {
371     std::string msgSensor;
372     std::map<std::string, std::variant<uint32_t, bool>> msgData;
373     msg.read(msgSensor, msgData);
374 
375     // Check if it was the Present property that changed.
376     auto valPropMap = msgData.find(PRESENT_PROP);
377     if (valPropMap != msgData.end())
378     {
379         if (std::get<bool>(valPropMap->second))
380         {
381             present = true;
382             // TODO: Immediately trying to read or write the "files" causes
383             // read or write failures.
384             using namespace std::chrono_literals;
385             std::this_thread::sleep_for(20ms);
386             pmbusIntf->findHwmonDir();
387             onOffConfig(phosphor::pmbus::ON_OFF_CONFIG_CONTROL_PIN_ONLY);
388             clearFaults();
389             updateInventory();
390         }
391         else
392         {
393             present = false;
394 
395             // Clear out the now outdated inventory properties
396             updateInventory();
397         }
398     }
399 }
400 
401 void PowerSupply::inventoryAdded(sdbusplus::message::message& msg)
402 {
403     sdbusplus::message::object_path path;
404     msg.read(path);
405     // Make sure the signal is for the PSU inventory path
406     if (path == inventoryPath)
407     {
408         std::map<std::string, std::map<std::string, std::variant<bool>>>
409             interfaces;
410         // Get map of interfaces and their properties
411         msg.read(interfaces);
412 
413         auto properties = interfaces.find(INVENTORY_IFACE);
414         if (properties != interfaces.end())
415         {
416             auto property = properties->second.find(PRESENT_PROP);
417             if (property != properties->second.end())
418             {
419                 present = std::get<bool>(property->second);
420 
421                 log<level::INFO>(fmt::format("Power Supply {} Present {}",
422                                              inventoryPath, present)
423                                      .c_str());
424 
425                 updateInventory();
426             }
427         }
428     }
429 }
430 
431 void PowerSupply::updateInventory()
432 {
433     using namespace phosphor::pmbus;
434 
435 #if IBM_VPD
436     std::string ccin;
437     std::string pn;
438     std::string fn;
439     std::string header;
440     std::string sn;
441     using PropertyMap =
442         std::map<std::string,
443                  std::variant<std::string, std::vector<uint8_t>, bool>>;
444     PropertyMap assetProps;
445     PropertyMap operProps;
446     PropertyMap versionProps;
447     PropertyMap ipzvpdDINFProps;
448     PropertyMap ipzvpdVINIProps;
449     using InterfaceMap = std::map<std::string, PropertyMap>;
450     InterfaceMap interfaces;
451     using ObjectMap = std::map<sdbusplus::message::object_path, InterfaceMap>;
452     ObjectMap object;
453 #endif
454     log<level::DEBUG>(
455         fmt::format("updateInventory() inventoryPath: {}", inventoryPath)
456             .c_str());
457 
458     if (present)
459     {
460         // TODO: non-IBM inventory updates?
461 
462 #if IBM_VPD
463         try
464         {
465             ccin = pmbusIntf->readString(CCIN, Type::HwmonDeviceDebug);
466             assetProps.emplace(MODEL_PROP, ccin);
467             modelName = ccin;
468         }
469         catch (const ReadFailure& e)
470         {
471             // Ignore the read failure, let pmbus code indicate failure,
472             // path...
473             // TODO - ibm918
474             // https://github.com/openbmc/docs/blob/master/designs/vpd-collection.md
475             // The BMC must log errors if any of the VPD cannot be properly
476             // parsed or fails ECC checks.
477         }
478 
479         try
480         {
481             pn = pmbusIntf->readString(PART_NUMBER, Type::HwmonDeviceDebug);
482             assetProps.emplace(PN_PROP, pn);
483         }
484         catch (const ReadFailure& e)
485         {
486             // Ignore the read failure, let pmbus code indicate failure,
487             // path...
488         }
489 
490         try
491         {
492             fn = pmbusIntf->readString(FRU_NUMBER, Type::HwmonDeviceDebug);
493         }
494         catch (const ReadFailure& e)
495         {
496             // Ignore the read failure, let pmbus code indicate failure,
497             // path...
498         }
499 
500         try
501         {
502             header =
503                 pmbusIntf->readString(SERIAL_HEADER, Type::HwmonDeviceDebug);
504             sn = pmbusIntf->readString(SERIAL_NUMBER, Type::HwmonDeviceDebug);
505             assetProps.emplace(SN_PROP, sn);
506         }
507         catch (const ReadFailure& e)
508         {
509             // Ignore the read failure, let pmbus code indicate failure,
510             // path...
511         }
512 
513         try
514         {
515             fwVersion =
516                 pmbusIntf->readString(FW_VERSION, Type::HwmonDeviceDebug);
517             versionProps.emplace(VERSION_PROP, fwVersion);
518         }
519         catch (const ReadFailure& e)
520         {
521             // Ignore the read failure, let pmbus code indicate failure,
522             // path...
523         }
524 
525         ipzvpdVINIProps.emplace("CC",
526                                 std::vector<uint8_t>(ccin.begin(), ccin.end()));
527         ipzvpdVINIProps.emplace("PN",
528                                 std::vector<uint8_t>(pn.begin(), pn.end()));
529         ipzvpdVINIProps.emplace("FN",
530                                 std::vector<uint8_t>(fn.begin(), fn.end()));
531         std::string header_sn = header + sn + '\0';
532         ipzvpdVINIProps.emplace(
533             "SN", std::vector<uint8_t>(header_sn.begin(), header_sn.end()));
534         std::string description = "IBM PS";
535         ipzvpdVINIProps.emplace(
536             "DR", std::vector<uint8_t>(description.begin(), description.end()));
537 
538         // Update the Resource Identifier (RI) keyword
539         // 2 byte FRC: 0x0003
540         // 2 byte RID: 0x1000, 0x1001...
541         std::uint8_t num = std::stoul(
542             inventoryPath.substr(inventoryPath.size() - 1, 1), nullptr, 0);
543         std::vector<uint8_t> ri{0x00, 0x03, 0x10, num};
544         ipzvpdDINFProps.emplace("RI", ri);
545 
546         // Fill in the FRU Label (FL) keyword.
547         std::string fl = "E";
548         fl.push_back(inventoryPath.back());
549         fl.resize(FL_KW_SIZE, ' ');
550         ipzvpdDINFProps.emplace("FL",
551                                 std::vector<uint8_t>(fl.begin(), fl.end()));
552 
553         interfaces.emplace(ASSET_IFACE, std::move(assetProps));
554         interfaces.emplace(VERSION_IFACE, std::move(versionProps));
555         interfaces.emplace(DINF_IFACE, std::move(ipzvpdDINFProps));
556         interfaces.emplace(VINI_IFACE, std::move(ipzvpdVINIProps));
557 
558         // Update the Functional
559         operProps.emplace(FUNCTIONAL_PROP, present);
560         interfaces.emplace(OPERATIONAL_STATE_IFACE, std::move(operProps));
561 
562         auto path = inventoryPath.substr(strlen(INVENTORY_OBJ_PATH));
563         object.emplace(path, std::move(interfaces));
564 
565         try
566         {
567             auto service =
568                 util::getService(INVENTORY_OBJ_PATH, INVENTORY_MGR_IFACE, bus);
569 
570             if (service.empty())
571             {
572                 log<level::ERR>("Unable to get inventory manager service");
573                 return;
574             }
575 
576             auto method =
577                 bus.new_method_call(service.c_str(), INVENTORY_OBJ_PATH,
578                                     INVENTORY_MGR_IFACE, "Notify");
579 
580             method.append(std::move(object));
581 
582             auto reply = bus.call(method);
583         }
584         catch (const std::exception& e)
585         {
586             log<level::ERR>(
587                 std::string(e.what() + std::string(" PATH=") + inventoryPath)
588                     .c_str());
589         }
590 #endif
591     }
592 }
593 
594 void PowerSupply::getInputVoltage(double& actualInputVoltage,
595                                   int& inputVoltage) const
596 {
597     using namespace phosphor::pmbus;
598 
599     actualInputVoltage = in_input::VIN_VOLTAGE_0;
600     inputVoltage = in_input::VIN_VOLTAGE_0;
601 
602     if (present)
603     {
604         try
605         {
606             // Read input voltage in millivolts
607             auto inputVoltageStr = pmbusIntf->readString(READ_VIN, Type::Hwmon);
608 
609             // Convert to volts
610             actualInputVoltage = std::stod(inputVoltageStr) / 1000;
611 
612             // Calculate the voltage based on voltage thresholds
613             if (actualInputVoltage < in_input::VIN_VOLTAGE_MIN)
614             {
615                 inputVoltage = in_input::VIN_VOLTAGE_0;
616             }
617             else if (actualInputVoltage < in_input::VIN_VOLTAGE_110_THRESHOLD)
618             {
619                 inputVoltage = in_input::VIN_VOLTAGE_110;
620             }
621             else
622             {
623                 inputVoltage = in_input::VIN_VOLTAGE_220;
624             }
625         }
626         catch (const std::exception& e)
627         {
628             log<level::ERR>(
629                 fmt::format("READ_VIN read error: {}", e.what()).c_str());
630         }
631     }
632 }
633 
634 } // namespace phosphor::power::psu
635