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 <cmath> 14 #include <cstdint> // uint8_t... 15 #include <fstream> 16 #include <regex> 17 #include <thread> // sleep_for() 18 19 namespace phosphor::power::psu 20 { 21 // Amount of time in milliseconds to delay between power supply going from 22 // missing to present before running the bind command(s). 23 constexpr auto bindDelay = 1000; 24 25 using namespace phosphor::logging; 26 using namespace sdbusplus::xyz::openbmc_project::Common::Device::Error; 27 28 PowerSupply::PowerSupply(sdbusplus::bus_t& bus, const std::string& invpath, 29 std::uint8_t i2cbus, std::uint16_t i2caddr, 30 const std::string& driver, 31 const std::string& gpioLineName, 32 std::function<bool()>&& callback) : 33 bus(bus), 34 inventoryPath(invpath), bindPath("/sys/bus/i2c/drivers/" + driver), 35 isPowerOn(std::move(callback)), driverName(driver) 36 { 37 if (inventoryPath.empty()) 38 { 39 throw std::invalid_argument{"Invalid empty inventoryPath"}; 40 } 41 42 if (gpioLineName.empty()) 43 { 44 throw std::invalid_argument{"Invalid empty gpioLineName"}; 45 } 46 47 shortName = findShortName(inventoryPath); 48 49 log<level::DEBUG>( 50 fmt::format("{} gpioLineName: {}", shortName, gpioLineName).c_str()); 51 presenceGPIO = createGPIO(gpioLineName); 52 53 std::ostringstream ss; 54 ss << std::hex << std::setw(4) << std::setfill('0') << i2caddr; 55 std::string addrStr = ss.str(); 56 std::string busStr = std::to_string(i2cbus); 57 bindDevice = busStr; 58 bindDevice.append("-"); 59 bindDevice.append(addrStr); 60 61 pmbusIntf = phosphor::pmbus::createPMBus(i2cbus, addrStr); 62 63 // Get the current state of the Present property. 64 try 65 { 66 updatePresenceGPIO(); 67 } 68 catch (...) 69 { 70 // If the above attempt to use the GPIO failed, it likely means that the 71 // GPIOs are in use by the kernel, meaning it is using gpio-keys. 72 // So, I should rely on phosphor-gpio-presence to update D-Bus, and 73 // work that way for power supply presence. 74 presenceGPIO = nullptr; 75 // Setup the functions to call when the D-Bus inventory path for the 76 // Present property changes. 77 presentMatch = std::make_unique<sdbusplus::bus::match_t>( 78 bus, 79 sdbusplus::bus::match::rules::propertiesChanged(inventoryPath, 80 INVENTORY_IFACE), 81 [this](auto& msg) { this->inventoryChanged(msg); }); 82 83 presentAddedMatch = std::make_unique<sdbusplus::bus::match_t>( 84 bus, 85 sdbusplus::bus::match::rules::interfacesAdded() + 86 sdbusplus::bus::match::rules::argNpath(0, inventoryPath), 87 [this](auto& msg) { this->inventoryAdded(msg); }); 88 89 updatePresence(); 90 updateInventory(); 91 setupSensors(); 92 } 93 94 setInputVoltageRating(); 95 } 96 97 void PowerSupply::bindOrUnbindDriver(bool present) 98 { 99 auto action = (present) ? "bind" : "unbind"; 100 auto path = bindPath / action; 101 102 if (present) 103 { 104 std::this_thread::sleep_for(std::chrono::milliseconds(bindDelay)); 105 log<level::INFO>( 106 fmt::format("Binding device driver. path: {} device: {}", 107 path.string(), bindDevice) 108 .c_str()); 109 } 110 else 111 { 112 log<level::INFO>( 113 fmt::format("Unbinding device driver. path: {} device: {}", 114 path.string(), bindDevice) 115 .c_str()); 116 } 117 118 std::ofstream file; 119 120 file.exceptions(std::ofstream::failbit | std::ofstream::badbit | 121 std::ofstream::eofbit); 122 123 try 124 { 125 file.open(path); 126 file << bindDevice; 127 file.close(); 128 } 129 catch (const std::exception& e) 130 { 131 auto err = errno; 132 133 log<level::ERR>( 134 fmt::format("Failed binding or unbinding device. errno={}", err) 135 .c_str()); 136 } 137 } 138 139 void PowerSupply::updatePresence() 140 { 141 try 142 { 143 present = getPresence(bus, inventoryPath); 144 } 145 catch (const sdbusplus::exception_t& e) 146 { 147 // Relying on property change or interface added to retry. 148 // Log an informational trace to the journal. 149 log<level::INFO>( 150 fmt::format("D-Bus property {} access failure exception", 151 inventoryPath) 152 .c_str()); 153 } 154 } 155 156 void PowerSupply::updatePresenceGPIO() 157 { 158 bool presentOld = present; 159 160 try 161 { 162 if (presenceGPIO->read() > 0) 163 { 164 present = true; 165 } 166 else 167 { 168 present = false; 169 } 170 } 171 catch (const std::exception& e) 172 { 173 log<level::ERR>( 174 fmt::format("presenceGPIO read fail: {}", e.what()).c_str()); 175 throw; 176 } 177 178 if (presentOld != present) 179 { 180 log<level::DEBUG>(fmt::format("{} presentOld: {} present: {}", 181 shortName, presentOld, present) 182 .c_str()); 183 184 auto invpath = inventoryPath.substr(strlen(INVENTORY_OBJ_PATH)); 185 186 bindOrUnbindDriver(present); 187 if (present) 188 { 189 // If the power supply was present, then missing, and present again, 190 // the hwmon path may have changed. We will need the correct/updated 191 // path before any reads or writes are attempted. 192 pmbusIntf->findHwmonDir(); 193 } 194 195 setPresence(bus, invpath, present, shortName); 196 setupSensors(); 197 updateInventory(); 198 199 // Need Functional to already be correct before calling this. 200 checkAvailability(); 201 202 if (present) 203 { 204 onOffConfig(phosphor::pmbus::ON_OFF_CONFIG_CONTROL_PIN_ONLY); 205 clearFaults(); 206 // Indicate that the input history data and timestamps between all 207 // the power supplies that are present in the system need to be 208 // synchronized. 209 syncHistoryRequired = true; 210 } 211 else 212 { 213 setSensorsNotAvailable(); 214 } 215 } 216 } 217 218 void PowerSupply::analyzeCMLFault() 219 { 220 if (statusWord & phosphor::pmbus::status_word::CML_FAULT) 221 { 222 if (cmlFault < DEGLITCH_LIMIT) 223 { 224 if (statusWord != statusWordOld) 225 { 226 log<level::ERR>( 227 fmt::format("{} CML fault: STATUS_WORD = {:#06x}, " 228 "STATUS_CML = {:#02x}", 229 shortName, statusWord, statusCML) 230 .c_str()); 231 } 232 cmlFault++; 233 } 234 } 235 else 236 { 237 cmlFault = 0; 238 } 239 } 240 241 void PowerSupply::analyzeInputFault() 242 { 243 if (statusWord & phosphor::pmbus::status_word::INPUT_FAULT_WARN) 244 { 245 if (inputFault < DEGLITCH_LIMIT) 246 { 247 if (statusWord != statusWordOld) 248 { 249 log<level::ERR>( 250 fmt::format("{} INPUT fault: STATUS_WORD = {:#06x}, " 251 "STATUS_MFR_SPECIFIC = {:#04x}, " 252 "STATUS_INPUT = {:#04x}", 253 shortName, statusWord, statusMFR, statusInput) 254 .c_str()); 255 } 256 inputFault++; 257 } 258 } 259 260 // If had INPUT/VIN_UV fault, and now off. 261 // Trace that odd behavior. 262 if (inputFault && 263 !(statusWord & phosphor::pmbus::status_word::INPUT_FAULT_WARN)) 264 { 265 log<level::INFO>( 266 fmt::format("{} INPUT fault cleared: STATUS_WORD = {:#06x}, " 267 "STATUS_MFR_SPECIFIC = {:#04x}, " 268 "STATUS_INPUT = {:#04x}", 269 shortName, statusWord, statusMFR, statusInput) 270 .c_str()); 271 inputFault = 0; 272 } 273 } 274 275 void PowerSupply::analyzeVoutOVFault() 276 { 277 if (statusWord & phosphor::pmbus::status_word::VOUT_OV_FAULT) 278 { 279 if (voutOVFault < DEGLITCH_LIMIT) 280 { 281 if (statusWord != statusWordOld) 282 { 283 log<level::ERR>( 284 fmt::format( 285 "{} VOUT_OV_FAULT fault: STATUS_WORD = {:#06x}, " 286 "STATUS_MFR_SPECIFIC = {:#04x}, " 287 "STATUS_VOUT = {:#02x}", 288 shortName, statusWord, statusMFR, statusVout) 289 .c_str()); 290 } 291 292 voutOVFault++; 293 } 294 } 295 else 296 { 297 voutOVFault = 0; 298 } 299 } 300 301 void PowerSupply::analyzeIoutOCFault() 302 { 303 if (statusWord & phosphor::pmbus::status_word::IOUT_OC_FAULT) 304 { 305 if (ioutOCFault < DEGLITCH_LIMIT) 306 { 307 if (statusWord != statusWordOld) 308 { 309 log<level::ERR>( 310 fmt::format("{} IOUT fault: STATUS_WORD = {:#06x}, " 311 "STATUS_MFR_SPECIFIC = {:#04x}, " 312 "STATUS_IOUT = {:#04x}", 313 shortName, statusWord, statusMFR, statusIout) 314 .c_str()); 315 } 316 317 ioutOCFault++; 318 } 319 } 320 else 321 { 322 ioutOCFault = 0; 323 } 324 } 325 326 void PowerSupply::analyzeVoutUVFault() 327 { 328 if ((statusWord & phosphor::pmbus::status_word::VOUT_FAULT) && 329 !(statusWord & phosphor::pmbus::status_word::VOUT_OV_FAULT)) 330 { 331 if (voutUVFault < DEGLITCH_LIMIT) 332 { 333 if (statusWord != statusWordOld) 334 { 335 log<level::ERR>( 336 fmt::format( 337 "{} VOUT_UV_FAULT fault: STATUS_WORD = {:#06x}, " 338 "STATUS_MFR_SPECIFIC = {:#04x}, " 339 "STATUS_VOUT = {:#04x}", 340 shortName, statusWord, statusMFR, statusVout) 341 .c_str()); 342 } 343 voutUVFault++; 344 } 345 } 346 else 347 { 348 voutUVFault = 0; 349 } 350 } 351 352 void PowerSupply::analyzeFanFault() 353 { 354 if (statusWord & phosphor::pmbus::status_word::FAN_FAULT) 355 { 356 if (fanFault < DEGLITCH_LIMIT) 357 { 358 if (statusWord != statusWordOld) 359 { 360 log<level::ERR>(fmt::format("{} FANS fault/warning: " 361 "STATUS_WORD = {:#06x}, " 362 "STATUS_MFR_SPECIFIC = {:#04x}, " 363 "STATUS_FANS_1_2 = {:#04x}", 364 shortName, statusWord, statusMFR, 365 statusFans12) 366 .c_str()); 367 } 368 fanFault++; 369 } 370 } 371 else 372 { 373 fanFault = 0; 374 } 375 } 376 377 void PowerSupply::analyzeTemperatureFault() 378 { 379 if (statusWord & phosphor::pmbus::status_word::TEMPERATURE_FAULT_WARN) 380 { 381 if (tempFault < DEGLITCH_LIMIT) 382 { 383 if (statusWord != statusWordOld) 384 { 385 log<level::ERR>(fmt::format("{} TEMPERATURE fault/warning: " 386 "STATUS_WORD = {:#06x}, " 387 "STATUS_MFR_SPECIFIC = {:#04x}, " 388 "STATUS_TEMPERATURE = {:#04x}", 389 shortName, statusWord, statusMFR, 390 statusTemperature) 391 .c_str()); 392 } 393 tempFault++; 394 } 395 } 396 else 397 { 398 tempFault = 0; 399 } 400 } 401 402 void PowerSupply::analyzePgoodFault() 403 { 404 if ((statusWord & phosphor::pmbus::status_word::POWER_GOOD_NEGATED) || 405 (statusWord & phosphor::pmbus::status_word::UNIT_IS_OFF)) 406 { 407 if (pgoodFault < PGOOD_DEGLITCH_LIMIT) 408 { 409 if (statusWord != statusWordOld) 410 { 411 log<level::ERR>(fmt::format("{} PGOOD fault: " 412 "STATUS_WORD = {:#06x}, " 413 "STATUS_MFR_SPECIFIC = {:#04x}", 414 shortName, statusWord, statusMFR) 415 .c_str()); 416 } 417 pgoodFault++; 418 } 419 } 420 else 421 { 422 pgoodFault = 0; 423 } 424 } 425 426 void PowerSupply::determineMFRFault() 427 { 428 if (bindPath.string().find(IBMCFFPS_DD_NAME) != std::string::npos) 429 { 430 // IBM MFR_SPECIFIC[4] is PS_Kill fault 431 if (statusMFR & 0x10) 432 { 433 if (psKillFault < DEGLITCH_LIMIT) 434 { 435 psKillFault++; 436 } 437 } 438 else 439 { 440 psKillFault = 0; 441 } 442 // IBM MFR_SPECIFIC[6] is 12Vcs fault. 443 if (statusMFR & 0x40) 444 { 445 if (ps12VcsFault < DEGLITCH_LIMIT) 446 { 447 ps12VcsFault++; 448 } 449 } 450 else 451 { 452 ps12VcsFault = 0; 453 } 454 // IBM MFR_SPECIFIC[7] is 12V Current-Share fault. 455 if (statusMFR & 0x80) 456 { 457 if (psCS12VFault < DEGLITCH_LIMIT) 458 { 459 psCS12VFault++; 460 } 461 } 462 else 463 { 464 psCS12VFault = 0; 465 } 466 } 467 } 468 469 void PowerSupply::analyzeMFRFault() 470 { 471 if (statusWord & phosphor::pmbus::status_word::MFR_SPECIFIC_FAULT) 472 { 473 if (mfrFault < DEGLITCH_LIMIT) 474 { 475 if (statusWord != statusWordOld) 476 { 477 log<level::ERR>(fmt::format("{} MFR fault: " 478 "STATUS_WORD = {:#06x} " 479 "STATUS_MFR_SPECIFIC = {:#04x}", 480 shortName, statusWord, statusMFR) 481 .c_str()); 482 } 483 mfrFault++; 484 } 485 486 determineMFRFault(); 487 } 488 else 489 { 490 mfrFault = 0; 491 } 492 } 493 494 void PowerSupply::analyzeVinUVFault() 495 { 496 if (statusWord & phosphor::pmbus::status_word::VIN_UV_FAULT) 497 { 498 if (vinUVFault < DEGLITCH_LIMIT) 499 { 500 if (statusWord != statusWordOld) 501 { 502 log<level::ERR>( 503 fmt::format("{} VIN_UV fault: STATUS_WORD = {:#06x}, " 504 "STATUS_MFR_SPECIFIC = {:#04x}, " 505 "STATUS_INPUT = {:#04x}", 506 shortName, statusWord, statusMFR, statusInput) 507 .c_str()); 508 } 509 vinUVFault++; 510 } 511 // Remember that this PSU has seen an AC fault 512 acFault = AC_FAULT_LIMIT; 513 } 514 else 515 { 516 if (vinUVFault != 0) 517 { 518 log<level::INFO>( 519 fmt::format("{} VIN_UV fault cleared: STATUS_WORD = {:#06x}, " 520 "STATUS_MFR_SPECIFIC = {:#04x}, " 521 "STATUS_INPUT = {:#04x}", 522 shortName, statusWord, statusMFR, statusInput) 523 .c_str()); 524 vinUVFault = 0; 525 } 526 // No AC fail, decrement counter 527 if (acFault != 0) 528 { 529 --acFault; 530 } 531 } 532 } 533 534 void PowerSupply::analyze() 535 { 536 using namespace phosphor::pmbus; 537 538 if (presenceGPIO) 539 { 540 updatePresenceGPIO(); 541 } 542 543 if (present) 544 { 545 try 546 { 547 statusWordOld = statusWord; 548 statusWord = pmbusIntf->read(STATUS_WORD, Type::Debug, 549 (readFail < LOG_LIMIT)); 550 // Read worked, reset the fail count. 551 readFail = 0; 552 553 if (statusWord) 554 { 555 statusInput = pmbusIntf->read(STATUS_INPUT, Type::Debug); 556 if (bindPath.string().find(IBMCFFPS_DD_NAME) != 557 std::string::npos) 558 { 559 statusMFR = pmbusIntf->read(STATUS_MFR, Type::Debug); 560 } 561 statusCML = pmbusIntf->read(STATUS_CML, Type::Debug); 562 auto status0Vout = pmbusIntf->insertPageNum(STATUS_VOUT, 0); 563 statusVout = pmbusIntf->read(status0Vout, Type::Debug); 564 statusIout = pmbusIntf->read(STATUS_IOUT, Type::Debug); 565 statusFans12 = pmbusIntf->read(STATUS_FANS_1_2, Type::Debug); 566 statusTemperature = pmbusIntf->read(STATUS_TEMPERATURE, 567 Type::Debug); 568 569 analyzeCMLFault(); 570 571 analyzeInputFault(); 572 573 analyzeVoutOVFault(); 574 575 analyzeIoutOCFault(); 576 577 analyzeVoutUVFault(); 578 579 analyzeFanFault(); 580 581 analyzeTemperatureFault(); 582 583 analyzePgoodFault(); 584 585 analyzeMFRFault(); 586 587 analyzeVinUVFault(); 588 } 589 else 590 { 591 if (statusWord != statusWordOld) 592 { 593 log<level::INFO>(fmt::format("{} STATUS_WORD = {:#06x}", 594 shortName, statusWord) 595 .c_str()); 596 } 597 598 // if INPUT/VIN_UV fault was on, it cleared, trace it. 599 if (inputFault) 600 { 601 log<level::INFO>( 602 fmt::format( 603 "{} INPUT fault cleared: STATUS_WORD = {:#06x}", 604 shortName, statusWord) 605 .c_str()); 606 } 607 608 if (vinUVFault) 609 { 610 log<level::INFO>( 611 fmt::format("{} VIN_UV cleared: STATUS_WORD = {:#06x}", 612 shortName, statusWord) 613 .c_str()); 614 } 615 616 if (pgoodFault > 0) 617 { 618 log<level::INFO>( 619 fmt::format("{} pgoodFault cleared", shortName) 620 .c_str()); 621 } 622 623 clearFaultFlags(); 624 // No AC fail, decrement counter 625 if (acFault != 0) 626 { 627 --acFault; 628 } 629 } 630 631 // Save off old inputVoltage value. 632 // Get latest inputVoltage. 633 // If voltage went from below minimum, and now is not, clear faults. 634 // Note: getInputVoltage() has its own try/catch. 635 int inputVoltageOld = inputVoltage; 636 double actualInputVoltageOld = actualInputVoltage; 637 getInputVoltage(actualInputVoltage, inputVoltage); 638 if ((inputVoltageOld == in_input::VIN_VOLTAGE_0) && 639 (inputVoltage != in_input::VIN_VOLTAGE_0)) 640 { 641 log<level::INFO>( 642 fmt::format( 643 "{} READ_VIN back in range: actualInputVoltageOld = {} " 644 "actualInputVoltage = {}", 645 shortName, actualInputVoltageOld, actualInputVoltage) 646 .c_str()); 647 clearVinUVFault(); 648 } 649 else if (vinUVFault && (inputVoltage != in_input::VIN_VOLTAGE_0)) 650 { 651 log<level::INFO>( 652 fmt::format( 653 "{} CLEAR_FAULTS: vinUVFault {} actualInputVoltage {}", 654 shortName, vinUVFault, actualInputVoltage) 655 .c_str()); 656 // Do we have a VIN_UV fault latched that can now be cleared 657 // due to voltage back in range? Attempt to clear the 658 // fault(s), re-check faults on next call. 659 clearVinUVFault(); 660 } 661 else if (std::abs(actualInputVoltageOld - actualInputVoltage) > 662 10.0) 663 { 664 log<level::INFO>( 665 fmt::format( 666 "{} actualInputVoltageOld = {} actualInputVoltage = {}", 667 shortName, actualInputVoltageOld, actualInputVoltage) 668 .c_str()); 669 } 670 671 monitorSensors(); 672 673 checkAvailability(); 674 } 675 catch (const ReadFailure& e) 676 { 677 if (readFail < SIZE_MAX) 678 { 679 readFail++; 680 } 681 if (readFail == LOG_LIMIT) 682 { 683 phosphor::logging::commit<ReadFailure>(); 684 } 685 } 686 } 687 } 688 689 void PowerSupply::onOffConfig(uint8_t data) 690 { 691 using namespace phosphor::pmbus; 692 693 if (present && driverName != ACBEL_FSG032_DD_NAME) 694 { 695 log<level::INFO>("ON_OFF_CONFIG write", entry("DATA=0x%02X", data)); 696 try 697 { 698 std::vector<uint8_t> configData{data}; 699 pmbusIntf->writeBinary(ON_OFF_CONFIG, configData, 700 Type::HwmonDeviceDebug); 701 } 702 catch (...) 703 { 704 // The underlying code in writeBinary will log a message to the 705 // journal if the write fails. If the ON_OFF_CONFIG is not setup 706 // as desired, later fault detection and analysis code should 707 // catch any of the fall out. We should not need to terminate 708 // the application if this write fails. 709 } 710 } 711 } 712 713 void PowerSupply::clearVinUVFault() 714 { 715 // Read in1_lcrit_alarm to clear bits 3 and 4 of STATUS_INPUT. 716 // The fault bits in STAUTS_INPUT roll-up to STATUS_WORD. Clearing those 717 // bits in STATUS_INPUT should result in the corresponding STATUS_WORD bits 718 // also clearing. 719 // 720 // Do not care about return value. Should be 1 if active, 0 if not. 721 if (driverName != ACBEL_FSG032_DD_NAME) 722 { 723 static_cast<void>( 724 pmbusIntf->read("in1_lcrit_alarm", phosphor::pmbus::Type::Hwmon)); 725 } 726 else 727 { 728 static_cast<void>( 729 pmbusIntf->read("curr1_crit_alarm", phosphor::pmbus::Type::Hwmon)); 730 } 731 vinUVFault = 0; 732 } 733 734 void PowerSupply::clearFaults() 735 { 736 log<level::DEBUG>( 737 fmt::format("clearFaults() inventoryPath: {}", inventoryPath).c_str()); 738 faultLogged = false; 739 // The PMBus device driver does not allow for writing CLEAR_FAULTS 740 // directly. However, the pmbus hwmon device driver code will send a 741 // CLEAR_FAULTS after reading from any of the hwmon "files" in sysfs, so 742 // reading in1_input should result in clearing the fault bits in 743 // STATUS_BYTE/STATUS_WORD. 744 // I do not care what the return value is. 745 if (present) 746 { 747 clearFaultFlags(); 748 checkAvailability(); 749 readFail = 0; 750 751 try 752 { 753 clearVinUVFault(); 754 static_cast<void>( 755 pmbusIntf->read("in1_input", phosphor::pmbus::Type::Hwmon)); 756 } 757 catch (const ReadFailure& e) 758 { 759 // Since I do not care what the return value is, I really do not 760 // care much if it gets a ReadFailure either. However, this 761 // should not prevent the application from continuing to run, so 762 // catching the read failure. 763 } 764 } 765 } 766 767 void PowerSupply::inventoryChanged(sdbusplus::message_t& msg) 768 { 769 std::string msgSensor; 770 std::map<std::string, std::variant<uint32_t, bool>> msgData; 771 msg.read(msgSensor, msgData); 772 773 // Check if it was the Present property that changed. 774 auto valPropMap = msgData.find(PRESENT_PROP); 775 if (valPropMap != msgData.end()) 776 { 777 if (std::get<bool>(valPropMap->second)) 778 { 779 present = true; 780 // TODO: Immediately trying to read or write the "files" causes 781 // read or write failures. 782 using namespace std::chrono_literals; 783 std::this_thread::sleep_for(20ms); 784 pmbusIntf->findHwmonDir(); 785 onOffConfig(phosphor::pmbus::ON_OFF_CONFIG_CONTROL_PIN_ONLY); 786 clearFaults(); 787 updateInventory(); 788 } 789 else 790 { 791 present = false; 792 793 // Clear out the now outdated inventory properties 794 updateInventory(); 795 } 796 checkAvailability(); 797 } 798 } 799 800 void PowerSupply::inventoryAdded(sdbusplus::message_t& msg) 801 { 802 sdbusplus::message::object_path path; 803 msg.read(path); 804 // Make sure the signal is for the PSU inventory path 805 if (path == inventoryPath) 806 { 807 std::map<std::string, std::map<std::string, std::variant<bool>>> 808 interfaces; 809 // Get map of interfaces and their properties 810 msg.read(interfaces); 811 812 auto properties = interfaces.find(INVENTORY_IFACE); 813 if (properties != interfaces.end()) 814 { 815 auto property = properties->second.find(PRESENT_PROP); 816 if (property != properties->second.end()) 817 { 818 present = std::get<bool>(property->second); 819 820 log<level::INFO>(fmt::format("Power Supply {} Present {}", 821 inventoryPath, present) 822 .c_str()); 823 824 updateInventory(); 825 checkAvailability(); 826 } 827 } 828 } 829 } 830 831 auto PowerSupply::readVPDValue(const std::string& vpdName, 832 const phosphor::pmbus::Type& type, 833 const std::size_t& vpdSize) 834 { 835 std::string vpdValue; 836 const std::regex illegalVPDRegex = std::regex("[^[:alnum:]]", 837 std::regex::basic); 838 839 try 840 { 841 vpdValue = pmbusIntf->readString(vpdName, type); 842 } 843 catch (const ReadFailure& e) 844 { 845 // Ignore the read failure, let pmbus code indicate failure, 846 // path... 847 // TODO - ibm918 848 // https://github.com/openbmc/docs/blob/master/designs/vpd-collection.md 849 // The BMC must log errors if any of the VPD cannot be properly 850 // parsed or fails ECC checks. 851 } 852 853 if (vpdValue.size() != vpdSize) 854 { 855 log<level::INFO>(fmt::format("{} {} resize needed. size: {}", shortName, 856 vpdName, vpdValue.size()) 857 .c_str()); 858 vpdValue.resize(vpdSize, ' '); 859 } 860 861 // Replace any illegal values with space(s). 862 std::regex_replace(vpdValue.begin(), vpdValue.begin(), vpdValue.end(), 863 illegalVPDRegex, " "); 864 865 return vpdValue; 866 } 867 868 void PowerSupply::updateInventory() 869 { 870 using namespace phosphor::pmbus; 871 872 #if IBM_VPD 873 std::string pn; 874 std::string fn; 875 std::string header; 876 std::string sn; 877 // The IBM power supply splits the full serial number into two parts. 878 // Each part is 6 bytes long, which should match up with SN_KW_SIZE. 879 const auto HEADER_SIZE = 6; 880 const auto SERIAL_SIZE = 6; 881 // The IBM PSU firmware version size is a bit complicated. It was originally 882 // 1-byte, per command. It was later expanded to 2-bytes per command, then 883 // up to 8-bytes per command. The device driver only reads up to 2 bytes per 884 // command, but combines all three of the 2-byte reads, or all 4 of the 885 // 1-byte reads into one string. So, the maximum size expected is 6 bytes. 886 // However, it is formatted by the driver as a hex string with two ASCII 887 // characters per byte. So the maximum ASCII string size is 12. 888 const auto IBMCFFPS_FW_VERSION_SIZE = 12; 889 const auto ACBEL_FSG032_FW_VERSION_SIZE = 6; 890 891 using PropertyMap = 892 std::map<std::string, 893 std::variant<std::string, std::vector<uint8_t>, bool>>; 894 PropertyMap assetProps; 895 PropertyMap operProps; 896 PropertyMap versionProps; 897 PropertyMap ipzvpdDINFProps; 898 PropertyMap ipzvpdVINIProps; 899 using InterfaceMap = std::map<std::string, PropertyMap>; 900 InterfaceMap interfaces; 901 using ObjectMap = std::map<sdbusplus::message::object_path, InterfaceMap>; 902 ObjectMap object; 903 #endif 904 log<level::DEBUG>( 905 fmt::format("updateInventory() inventoryPath: {}", inventoryPath) 906 .c_str()); 907 908 if (present) 909 { 910 // TODO: non-IBM inventory updates? 911 912 #if IBM_VPD 913 if (driverName == ACBEL_FSG032_DD_NAME) 914 { 915 getPsuVpdFromDbus("CC", modelName); 916 getPsuVpdFromDbus("PN", pn); 917 getPsuVpdFromDbus("FN", fn); 918 getPsuVpdFromDbus("SN", sn); 919 assetProps.emplace(SN_PROP, sn); 920 fwVersion = readVPDValue(FW_VERSION, Type::Debug, 921 ACBEL_FSG032_FW_VERSION_SIZE); 922 versionProps.emplace(VERSION_PROP, fwVersion); 923 } 924 else 925 { 926 modelName = readVPDValue(CCIN, Type::HwmonDeviceDebug, CC_KW_SIZE); 927 pn = readVPDValue(PART_NUMBER, Type::Debug, PN_KW_SIZE); 928 fn = readVPDValue(FRU_NUMBER, Type::Debug, FN_KW_SIZE); 929 930 header = readVPDValue(SERIAL_HEADER, Type::Debug, HEADER_SIZE); 931 sn = readVPDValue(SERIAL_NUMBER, Type::Debug, SERIAL_SIZE); 932 assetProps.emplace(SN_PROP, header + sn); 933 fwVersion = readVPDValue(FW_VERSION, Type::HwmonDeviceDebug, 934 IBMCFFPS_FW_VERSION_SIZE); 935 versionProps.emplace(VERSION_PROP, fwVersion); 936 } 937 938 assetProps.emplace(MODEL_PROP, modelName); 939 assetProps.emplace(PN_PROP, pn); 940 assetProps.emplace(SPARE_PN_PROP, fn); 941 942 ipzvpdVINIProps.emplace( 943 "CC", std::vector<uint8_t>(modelName.begin(), modelName.end())); 944 ipzvpdVINIProps.emplace("PN", 945 std::vector<uint8_t>(pn.begin(), pn.end())); 946 ipzvpdVINIProps.emplace("FN", 947 std::vector<uint8_t>(fn.begin(), fn.end())); 948 std::string header_sn = header + sn; 949 ipzvpdVINIProps.emplace( 950 "SN", std::vector<uint8_t>(header_sn.begin(), header_sn.end())); 951 std::string description = "IBM PS"; 952 ipzvpdVINIProps.emplace( 953 "DR", std::vector<uint8_t>(description.begin(), description.end())); 954 955 // Populate the VINI Resource Type (RT) keyword 956 ipzvpdVINIProps.emplace("RT", std::vector<uint8_t>{'V', 'I', 'N', 'I'}); 957 958 // Update the Resource Identifier (RI) keyword 959 // 2 byte FRC: 0x0003 960 // 2 byte RID: 0x1000, 0x1001... 961 std::uint8_t num = std::stoul( 962 inventoryPath.substr(inventoryPath.size() - 1, 1), nullptr, 0); 963 std::vector<uint8_t> ri{0x00, 0x03, 0x10, num}; 964 ipzvpdDINFProps.emplace("RI", ri); 965 966 // Fill in the FRU Label (FL) keyword. 967 std::string fl = "E"; 968 fl.push_back(inventoryPath.back()); 969 fl.resize(FL_KW_SIZE, ' '); 970 ipzvpdDINFProps.emplace("FL", 971 std::vector<uint8_t>(fl.begin(), fl.end())); 972 973 // Populate the DINF Resource Type (RT) keyword 974 ipzvpdDINFProps.emplace("RT", std::vector<uint8_t>{'D', 'I', 'N', 'F'}); 975 976 interfaces.emplace(ASSET_IFACE, std::move(assetProps)); 977 interfaces.emplace(VERSION_IFACE, std::move(versionProps)); 978 interfaces.emplace(DINF_IFACE, std::move(ipzvpdDINFProps)); 979 interfaces.emplace(VINI_IFACE, std::move(ipzvpdVINIProps)); 980 981 // Update the Functional 982 operProps.emplace(FUNCTIONAL_PROP, present); 983 interfaces.emplace(OPERATIONAL_STATE_IFACE, std::move(operProps)); 984 985 auto path = inventoryPath.substr(strlen(INVENTORY_OBJ_PATH)); 986 object.emplace(path, std::move(interfaces)); 987 988 try 989 { 990 auto service = util::getService(INVENTORY_OBJ_PATH, 991 INVENTORY_MGR_IFACE, bus); 992 993 if (service.empty()) 994 { 995 log<level::ERR>("Unable to get inventory manager service"); 996 return; 997 } 998 999 auto method = bus.new_method_call(service.c_str(), 1000 INVENTORY_OBJ_PATH, 1001 INVENTORY_MGR_IFACE, "Notify"); 1002 1003 method.append(std::move(object)); 1004 1005 auto reply = bus.call(method); 1006 } 1007 catch (const std::exception& e) 1008 { 1009 log<level::ERR>( 1010 std::string(e.what() + std::string(" PATH=") + inventoryPath) 1011 .c_str()); 1012 } 1013 #endif 1014 } 1015 } 1016 1017 auto PowerSupply::getMaxPowerOut() const 1018 { 1019 using namespace phosphor::pmbus; 1020 1021 auto maxPowerOut = 0; 1022 1023 if (present) 1024 { 1025 try 1026 { 1027 // Read max_power_out, should be direct format 1028 auto maxPowerOutStr = pmbusIntf->readString(MFR_POUT_MAX, 1029 Type::HwmonDeviceDebug); 1030 log<level::INFO>(fmt::format("{} MFR_POUT_MAX read {}", shortName, 1031 maxPowerOutStr) 1032 .c_str()); 1033 maxPowerOut = std::stod(maxPowerOutStr); 1034 } 1035 catch (const std::exception& e) 1036 { 1037 log<level::ERR>(fmt::format("{} MFR_POUT_MAX read error: {}", 1038 shortName, e.what()) 1039 .c_str()); 1040 } 1041 } 1042 1043 return maxPowerOut; 1044 } 1045 1046 void PowerSupply::setupSensors() 1047 { 1048 setupInputPowerPeakSensor(); 1049 } 1050 1051 void PowerSupply::setupInputPowerPeakSensor() 1052 { 1053 if (peakInputPowerSensor || !present || 1054 (bindPath.string().find(IBMCFFPS_DD_NAME) == std::string::npos)) 1055 { 1056 return; 1057 } 1058 1059 // This PSU has problems with the input_history command 1060 if (getMaxPowerOut() == phosphor::pmbus::IBM_CFFPS_1400W) 1061 { 1062 return; 1063 } 1064 1065 auto sensorPath = 1066 fmt::format("/xyz/openbmc_project/sensors/power/ps{}_input_power_peak", 1067 shortName.back()); 1068 1069 peakInputPowerSensor = std::make_unique<PowerSensorObject>( 1070 bus, sensorPath.c_str(), PowerSensorObject::action::defer_emit); 1071 1072 // The others can remain at the defaults. 1073 peakInputPowerSensor->functional(true, true); 1074 peakInputPowerSensor->available(true, true); 1075 peakInputPowerSensor->value(0, true); 1076 peakInputPowerSensor->unit( 1077 sdbusplus::xyz::openbmc_project::Sensor::server::Value::Unit::Watts, 1078 true); 1079 1080 auto associations = getSensorAssociations(); 1081 peakInputPowerSensor->associations(associations, true); 1082 1083 peakInputPowerSensor->emit_object_added(); 1084 } 1085 1086 void PowerSupply::setSensorsNotAvailable() 1087 { 1088 if (peakInputPowerSensor) 1089 { 1090 peakInputPowerSensor->value(std::numeric_limits<double>::quiet_NaN()); 1091 peakInputPowerSensor->available(false); 1092 } 1093 } 1094 1095 void PowerSupply::monitorSensors() 1096 { 1097 monitorPeakInputPowerSensor(); 1098 } 1099 1100 void PowerSupply::monitorPeakInputPowerSensor() 1101 { 1102 if (!peakInputPowerSensor) 1103 { 1104 return; 1105 } 1106 1107 constexpr size_t recordSize = 5; 1108 std::vector<uint8_t> data; 1109 1110 // Get the peak input power with input history command. 1111 // New data only shows up every 30s, but just try to read it every 1s 1112 // anyway so we always have the most up to date value. 1113 try 1114 { 1115 data = pmbusIntf->readBinary(INPUT_HISTORY, 1116 pmbus::Type::HwmonDeviceDebug, recordSize); 1117 } 1118 catch (const ReadFailure& e) 1119 { 1120 peakInputPowerSensor->value(std::numeric_limits<double>::quiet_NaN()); 1121 peakInputPowerSensor->functional(false); 1122 throw; 1123 } 1124 1125 if (data.size() != recordSize) 1126 { 1127 log<level::DEBUG>( 1128 fmt::format("Input history command returned {} bytes instead of 5", 1129 data.size()) 1130 .c_str()); 1131 peakInputPowerSensor->value(std::numeric_limits<double>::quiet_NaN()); 1132 peakInputPowerSensor->functional(false); 1133 return; 1134 } 1135 1136 // The format is SSAAAAPPPP: 1137 // SS = packet sequence number 1138 // AAAA = average power (linear format, little endian) 1139 // PPPP = peak power (linear format, little endian) 1140 auto peak = static_cast<uint16_t>(data[4]) << 8 | data[3]; 1141 auto peakPower = linearToInteger(peak); 1142 1143 peakInputPowerSensor->value(peakPower); 1144 peakInputPowerSensor->functional(true); 1145 peakInputPowerSensor->available(true); 1146 } 1147 1148 void PowerSupply::getInputVoltage(double& actualInputVoltage, 1149 int& inputVoltage) const 1150 { 1151 using namespace phosphor::pmbus; 1152 1153 actualInputVoltage = in_input::VIN_VOLTAGE_0; 1154 inputVoltage = in_input::VIN_VOLTAGE_0; 1155 1156 if (present) 1157 { 1158 try 1159 { 1160 // Read input voltage in millivolts 1161 auto inputVoltageStr = pmbusIntf->readString(READ_VIN, Type::Hwmon); 1162 1163 // Convert to volts 1164 actualInputVoltage = std::stod(inputVoltageStr) / 1000; 1165 1166 // Calculate the voltage based on voltage thresholds 1167 if (actualInputVoltage < in_input::VIN_VOLTAGE_MIN) 1168 { 1169 inputVoltage = in_input::VIN_VOLTAGE_0; 1170 } 1171 else if (actualInputVoltage < in_input::VIN_VOLTAGE_110_THRESHOLD) 1172 { 1173 inputVoltage = in_input::VIN_VOLTAGE_110; 1174 } 1175 else 1176 { 1177 inputVoltage = in_input::VIN_VOLTAGE_220; 1178 } 1179 } 1180 catch (const std::exception& e) 1181 { 1182 log<level::ERR>( 1183 fmt::format("{} READ_VIN read error: {}", shortName, e.what()) 1184 .c_str()); 1185 } 1186 } 1187 } 1188 1189 void PowerSupply::checkAvailability() 1190 { 1191 bool origAvailability = available; 1192 bool faulted = isPowerOn() && (hasPSKillFault() || hasIoutOCFault()); 1193 available = present && !hasInputFault() && !hasVINUVFault() && !faulted; 1194 1195 if (origAvailability != available) 1196 { 1197 auto invpath = inventoryPath.substr(strlen(INVENTORY_OBJ_PATH)); 1198 phosphor::power::psu::setAvailable(bus, invpath, available); 1199 1200 // Check if the health rollup needs to change based on the 1201 // new availability value. 1202 phosphor::power::psu::handleChassisHealthRollup(bus, inventoryPath, 1203 !available); 1204 } 1205 } 1206 1207 void PowerSupply::setInputVoltageRating() 1208 { 1209 if (!present) 1210 { 1211 if (inputVoltageRatingIface) 1212 { 1213 inputVoltageRatingIface->value(0); 1214 inputVoltageRatingIface.reset(); 1215 } 1216 return; 1217 } 1218 1219 double inputVoltageValue{}; 1220 int inputVoltageRating{}; 1221 getInputVoltage(inputVoltageValue, inputVoltageRating); 1222 1223 if (!inputVoltageRatingIface) 1224 { 1225 auto path = fmt::format( 1226 "/xyz/openbmc_project/sensors/voltage/ps{}_input_voltage_rating", 1227 shortName.back()); 1228 1229 inputVoltageRatingIface = std::make_unique<SensorObject>( 1230 bus, path.c_str(), SensorObject::action::defer_emit); 1231 1232 // Leave other properties at their defaults 1233 inputVoltageRatingIface->unit(SensorInterface::Unit::Volts, true); 1234 inputVoltageRatingIface->value(static_cast<double>(inputVoltageRating), 1235 true); 1236 1237 inputVoltageRatingIface->emit_object_added(); 1238 } 1239 else 1240 { 1241 inputVoltageRatingIface->value(static_cast<double>(inputVoltageRating)); 1242 } 1243 } 1244 1245 void PowerSupply::getPsuVpdFromDbus(const std::string& keyword, 1246 std::string& vpdStr) 1247 { 1248 try 1249 { 1250 std::vector<uint8_t> value; 1251 vpdStr.clear(); 1252 util::getProperty(VINI_IFACE, keyword, inventoryPath, 1253 INVENTORY_MGR_IFACE, bus, value); 1254 for (char c : value) 1255 { 1256 vpdStr += c; 1257 } 1258 } 1259 catch (const sdbusplus::exception_t& e) 1260 { 1261 log<level::ERR>( 1262 fmt::format("Failed getProperty error: {}", e.what()).c_str()); 1263 } 1264 } 1265 1266 double PowerSupply::linearToInteger(uint16_t data) 1267 { 1268 // The exponent is the first 5 bits, followed by 11 bits of mantissa. 1269 int8_t exponent = (data & 0xF800) >> 11; 1270 int16_t mantissa = (data & 0x07FF); 1271 1272 // If exponent's MSB on, then it's negative. 1273 // Convert from two's complement. 1274 if (exponent & 0x10) 1275 { 1276 exponent = (~exponent) & 0x1F; 1277 exponent = (exponent + 1) * -1; 1278 } 1279 1280 // If mantissa's MSB on, then it's negative. 1281 // Convert from two's complement. 1282 if (mantissa & 0x400) 1283 { 1284 mantissa = (~mantissa) & 0x07FF; 1285 mantissa = (mantissa + 1) * -1; 1286 } 1287 1288 auto value = static_cast<double>(mantissa) * pow(2, exponent); 1289 return value; 1290 } 1291 1292 std::vector<AssociationTuple> PowerSupply::getSensorAssociations() 1293 { 1294 std::vector<AssociationTuple> associations; 1295 1296 associations.emplace_back("inventory", "sensors", inventoryPath); 1297 1298 auto chassis = getChassis(bus, inventoryPath); 1299 associations.emplace_back("chassis", "all_sensors", std::move(chassis)); 1300 1301 return associations; 1302 } 1303 1304 } // namespace phosphor::power::psu 1305