1 #include "utils.hpp" 2 3 #include <libpldm/pdr.h> 4 #include <libpldm/pldm_types.h> 5 6 #include <phosphor-logging/lg2.hpp> 7 #include <xyz/openbmc_project/Common/error.hpp> 8 #include <xyz/openbmc_project/Logging/Create/client.hpp> 9 #include <xyz/openbmc_project/ObjectMapper/client.hpp> 10 11 #include <algorithm> 12 #include <array> 13 #include <cctype> 14 #include <ctime> 15 #include <fstream> 16 #include <iostream> 17 #include <map> 18 #include <stdexcept> 19 #include <string> 20 #include <vector> 21 22 PHOSPHOR_LOG2_USING; 23 24 namespace pldm 25 { 26 namespace utils 27 { 28 29 std::vector<std::vector<uint8_t>> findStateEffecterPDR(uint8_t /*tid*/, 30 uint16_t entityID, 31 uint16_t stateSetId, 32 const pldm_pdr* repo) 33 { 34 uint8_t* outData = nullptr; 35 uint32_t size{}; 36 const pldm_pdr_record* record{}; 37 std::vector<std::vector<uint8_t>> pdrs; 38 try 39 { 40 do 41 { 42 record = pldm_pdr_find_record_by_type(repo, PLDM_STATE_EFFECTER_PDR, 43 record, &outData, &size); 44 if (record) 45 { 46 auto pdr = reinterpret_cast<pldm_state_effecter_pdr*>(outData); 47 auto compositeEffecterCount = pdr->composite_effecter_count; 48 auto possible_states_start = pdr->possible_states; 49 50 for (auto effecters = 0x00; effecters < compositeEffecterCount; 51 effecters++) 52 { 53 auto possibleStates = 54 reinterpret_cast<state_effecter_possible_states*>( 55 possible_states_start); 56 auto setId = possibleStates->state_set_id; 57 auto possibleStateSize = 58 possibleStates->possible_states_size; 59 60 if (pdr->entity_type == entityID && setId == stateSetId) 61 { 62 std::vector<uint8_t> effecter_pdr(&outData[0], 63 &outData[size]); 64 pdrs.emplace_back(std::move(effecter_pdr)); 65 break; 66 } 67 possible_states_start += possibleStateSize + sizeof(setId) + 68 sizeof(possibleStateSize); 69 } 70 } 71 72 } while (record); 73 } 74 catch (const std::exception& e) 75 { 76 error("Failed to obtain a record, error - {ERROR}", "ERROR", e); 77 } 78 79 return pdrs; 80 } 81 82 std::vector<std::vector<uint8_t>> findStateSensorPDR(uint8_t /*tid*/, 83 uint16_t entityID, 84 uint16_t stateSetId, 85 const pldm_pdr* repo) 86 { 87 uint8_t* outData = nullptr; 88 uint32_t size{}; 89 const pldm_pdr_record* record{}; 90 std::vector<std::vector<uint8_t>> pdrs; 91 try 92 { 93 do 94 { 95 record = pldm_pdr_find_record_by_type(repo, PLDM_STATE_SENSOR_PDR, 96 record, &outData, &size); 97 if (record) 98 { 99 auto pdr = reinterpret_cast<pldm_state_sensor_pdr*>(outData); 100 auto compositeSensorCount = pdr->composite_sensor_count; 101 auto possible_states_start = pdr->possible_states; 102 103 for (auto sensors = 0x00; sensors < compositeSensorCount; 104 sensors++) 105 { 106 auto possibleStates = 107 reinterpret_cast<state_sensor_possible_states*>( 108 possible_states_start); 109 auto setId = possibleStates->state_set_id; 110 auto possibleStateSize = 111 possibleStates->possible_states_size; 112 113 if (pdr->entity_type == entityID && setId == stateSetId) 114 { 115 std::vector<uint8_t> sensor_pdr(&outData[0], 116 &outData[size]); 117 pdrs.emplace_back(std::move(sensor_pdr)); 118 break; 119 } 120 possible_states_start += possibleStateSize + sizeof(setId) + 121 sizeof(possibleStateSize); 122 } 123 } 124 125 } while (record); 126 } 127 catch (const std::exception& e) 128 { 129 error( 130 "Failed to obtain a record with entity ID '{ENTITYID}', error - {ERROR}", 131 "ENTITYID", entityID, "ERROR", e); 132 } 133 134 return pdrs; 135 } 136 137 uint8_t readHostEID() 138 { 139 uint8_t eid{}; 140 std::ifstream eidFile{HOST_EID_PATH}; 141 if (!eidFile.good()) 142 { 143 error("Failed to open remote terminus EID file at path '{PATH}'", 144 "PATH", static_cast<std::string>(HOST_EID_PATH)); 145 } 146 else 147 { 148 std::string eidStr; 149 eidFile >> eidStr; 150 if (!eidStr.empty()) 151 { 152 eid = atoi(eidStr.c_str()); 153 } 154 else 155 { 156 error("Remote terminus EID file was empty"); 157 } 158 } 159 160 return eid; 161 } 162 163 uint8_t getNumPadBytes(uint32_t data) 164 { 165 uint8_t pad; 166 pad = ((data % 4) ? (4 - data % 4) : 0); 167 return pad; 168 } // end getNumPadBytes 169 170 bool uintToDate(uint64_t data, uint16_t* year, uint8_t* month, uint8_t* day, 171 uint8_t* hour, uint8_t* min, uint8_t* sec) 172 { 173 constexpr uint64_t max_data = 29991231115959; 174 constexpr uint64_t min_data = 19700101000000; 175 if (data < min_data || data > max_data) 176 { 177 return false; 178 } 179 180 *year = data / 10000000000; 181 data = data % 10000000000; 182 *month = data / 100000000; 183 data = data % 100000000; 184 *day = data / 1000000; 185 data = data % 1000000; 186 *hour = data / 10000; 187 data = data % 10000; 188 *min = data / 100; 189 *sec = data % 100; 190 191 return true; 192 } 193 194 std::optional<std::vector<set_effecter_state_field>> 195 parseEffecterData(const std::vector<uint8_t>& effecterData, 196 uint8_t effecterCount) 197 { 198 std::vector<set_effecter_state_field> stateField; 199 200 if (effecterData.size() != effecterCount * 2) 201 { 202 return std::nullopt; 203 } 204 205 for (uint8_t i = 0; i < effecterCount; ++i) 206 { 207 uint8_t set_request = effecterData[i * 2] == PLDM_REQUEST_SET 208 ? PLDM_REQUEST_SET 209 : PLDM_NO_CHANGE; 210 set_effecter_state_field filed{set_request, effecterData[i * 2 + 1]}; 211 stateField.emplace_back(std::move(filed)); 212 } 213 214 return std::make_optional(std::move(stateField)); 215 } 216 217 std::string DBusHandler::getService(const char* path, 218 const char* interface) const 219 { 220 using DbusInterfaceList = std::vector<std::string>; 221 std::map<std::string, std::vector<std::string>> mapperResponse; 222 auto& bus = DBusHandler::getBus(); 223 224 auto mapper = bus.new_method_call(ObjectMapper::default_service, 225 ObjectMapper::instance_path, 226 ObjectMapper::interface, "GetObject"); 227 228 if (interface) 229 { 230 mapper.append(path, DbusInterfaceList({interface})); 231 } 232 else 233 { 234 mapper.append(path, DbusInterfaceList({})); 235 } 236 237 auto mapperResponseMsg = bus.call(mapper, dbusTimeout); 238 mapperResponseMsg.read(mapperResponse); 239 return mapperResponse.begin()->first; 240 } 241 242 GetSubTreeResponse 243 DBusHandler::getSubtree(const std::string& searchPath, int depth, 244 const std::vector<std::string>& ifaceList) const 245 { 246 auto& bus = pldm::utils::DBusHandler::getBus(); 247 auto method = bus.new_method_call(ObjectMapper::default_service, 248 ObjectMapper::instance_path, 249 ObjectMapper::interface, "GetSubTree"); 250 method.append(searchPath, depth, ifaceList); 251 auto reply = bus.call(method, dbusTimeout); 252 GetSubTreeResponse response; 253 reply.read(response); 254 return response; 255 } 256 257 GetSubTreePathsResponse DBusHandler::getSubTreePaths( 258 const std::string& objectPath, int depth, 259 const std::vector<std::string>& ifaceList) const 260 { 261 std::vector<std::string> paths; 262 auto& bus = pldm::utils::DBusHandler::getBus(); 263 auto method = bus.new_method_call( 264 ObjectMapper::default_service, ObjectMapper::instance_path, 265 ObjectMapper::interface, "GetSubTreePaths"); 266 method.append(objectPath, depth, ifaceList); 267 auto reply = bus.call(method, dbusTimeout); 268 269 reply.read(paths); 270 return paths; 271 } 272 273 void reportError(const char* errorMsg) 274 { 275 auto& bus = pldm::utils::DBusHandler::getBus(); 276 using LoggingCreate = 277 sdbusplus::client::xyz::openbmc_project::logging::Create<>; 278 try 279 { 280 using namespace sdbusplus::xyz::openbmc_project::Logging::server; 281 auto severity = 282 sdbusplus::xyz::openbmc_project::Logging::server::convertForMessage( 283 sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level:: 284 Error); 285 auto method = bus.new_method_call(LoggingCreate::default_service, 286 LoggingCreate::instance_path, 287 LoggingCreate::interface, "Create"); 288 289 std::map<std::string, std::string> addlData{}; 290 method.append(errorMsg, severity, addlData); 291 bus.call_noreply(method, dbusTimeout); 292 } 293 catch (const std::exception& e) 294 { 295 error( 296 "Failed to do dbus call for creating error log for '{ERRMSG}' at path '{PATH}' and interface '{INTERFACE}', error - {ERROR}", 297 "ERRMSG", errorMsg, "PATH", LoggingCreate::instance_path, 298 "INTERFACE", LoggingCreate::interface, "ERROR", e); 299 } 300 } 301 302 void DBusHandler::setDbusProperty(const DBusMapping& dBusMap, 303 const PropertyValue& value) const 304 { 305 auto setDbusValue = [&dBusMap, this](const auto& variant) { 306 auto& bus = getBus(); 307 auto service = getService(dBusMap.objectPath.c_str(), 308 dBusMap.interface.c_str()); 309 auto method = bus.new_method_call( 310 service.c_str(), dBusMap.objectPath.c_str(), dbusProperties, "Set"); 311 method.append(dBusMap.interface.c_str(), dBusMap.propertyName.c_str(), 312 variant); 313 bus.call_noreply(method, dbusTimeout); 314 }; 315 316 if (dBusMap.propertyType == "uint8_t") 317 { 318 std::variant<uint8_t> v = std::get<uint8_t>(value); 319 setDbusValue(v); 320 } 321 else if (dBusMap.propertyType == "bool") 322 { 323 std::variant<bool> v = std::get<bool>(value); 324 setDbusValue(v); 325 } 326 else if (dBusMap.propertyType == "int16_t") 327 { 328 std::variant<int16_t> v = std::get<int16_t>(value); 329 setDbusValue(v); 330 } 331 else if (dBusMap.propertyType == "uint16_t") 332 { 333 std::variant<uint16_t> v = std::get<uint16_t>(value); 334 setDbusValue(v); 335 } 336 else if (dBusMap.propertyType == "int32_t") 337 { 338 std::variant<int32_t> v = std::get<int32_t>(value); 339 setDbusValue(v); 340 } 341 else if (dBusMap.propertyType == "uint32_t") 342 { 343 std::variant<uint32_t> v = std::get<uint32_t>(value); 344 setDbusValue(v); 345 } 346 else if (dBusMap.propertyType == "int64_t") 347 { 348 std::variant<int64_t> v = std::get<int64_t>(value); 349 setDbusValue(v); 350 } 351 else if (dBusMap.propertyType == "uint64_t") 352 { 353 std::variant<uint64_t> v = std::get<uint64_t>(value); 354 setDbusValue(v); 355 } 356 else if (dBusMap.propertyType == "double") 357 { 358 std::variant<double> v = std::get<double>(value); 359 setDbusValue(v); 360 } 361 else if (dBusMap.propertyType == "string") 362 { 363 std::variant<std::string> v = std::get<std::string>(value); 364 setDbusValue(v); 365 } 366 else 367 { 368 error("Unsupported property type '{TYPE}'", "TYPE", 369 dBusMap.propertyType); 370 throw std::invalid_argument("UnSupported Dbus Type"); 371 } 372 } 373 374 PropertyValue DBusHandler::getDbusPropertyVariant( 375 const char* objPath, const char* dbusProp, const char* dbusInterface) const 376 { 377 auto& bus = DBusHandler::getBus(); 378 auto service = getService(objPath, dbusInterface); 379 auto method = bus.new_method_call(service.c_str(), objPath, dbusProperties, 380 "Get"); 381 method.append(dbusInterface, dbusProp); 382 return bus.call(method, dbusTimeout).unpack<PropertyValue>(); 383 } 384 385 ObjectValueTree DBusHandler::getManagedObj(const char* service, 386 const char* rootPath) 387 { 388 auto& bus = DBusHandler::getBus(); 389 auto method = bus.new_method_call(service, rootPath, 390 "org.freedesktop.DBus.ObjectManager", 391 "GetManagedObjects"); 392 return bus.call(method).unpack<ObjectValueTree>(); 393 } 394 395 PropertyMap 396 DBusHandler::getDbusPropertiesVariant(const char* serviceName, 397 const char* objPath, 398 const char* dbusInterface) const 399 { 400 auto& bus = DBusHandler::getBus(); 401 auto method = bus.new_method_call(serviceName, objPath, dbusProperties, 402 "GetAll"); 403 method.append(dbusInterface); 404 return bus.call(method, dbusTimeout).unpack<PropertyMap>(); 405 } 406 407 PropertyValue jsonEntryToDbusVal(std::string_view type, 408 const nlohmann::json& value) 409 { 410 PropertyValue propValue{}; 411 if (type == "uint8_t") 412 { 413 propValue = static_cast<uint8_t>(value); 414 } 415 else if (type == "uint16_t") 416 { 417 propValue = static_cast<uint16_t>(value); 418 } 419 else if (type == "uint32_t") 420 { 421 propValue = static_cast<uint32_t>(value); 422 } 423 else if (type == "uint64_t") 424 { 425 propValue = static_cast<uint64_t>(value); 426 } 427 else if (type == "int16_t") 428 { 429 propValue = static_cast<int16_t>(value); 430 } 431 else if (type == "int32_t") 432 { 433 propValue = static_cast<int32_t>(value); 434 } 435 else if (type == "int64_t") 436 { 437 propValue = static_cast<int64_t>(value); 438 } 439 else if (type == "bool") 440 { 441 propValue = static_cast<bool>(value); 442 } 443 else if (type == "double") 444 { 445 propValue = static_cast<double>(value); 446 } 447 else if (type == "string") 448 { 449 propValue = static_cast<std::string>(value); 450 } 451 else 452 { 453 error("Unknown D-Bus property type '{TYPE}'", "TYPE", type); 454 } 455 456 return propValue; 457 } 458 459 uint16_t findStateEffecterId(const pldm_pdr* pdrRepo, uint16_t entityType, 460 uint16_t entityInstance, uint16_t containerId, 461 uint16_t stateSetId, bool localOrRemote) 462 { 463 uint8_t* pdrData = nullptr; 464 uint32_t pdrSize{}; 465 const pldm_pdr_record* record{}; 466 do 467 { 468 record = pldm_pdr_find_record_by_type(pdrRepo, PLDM_STATE_EFFECTER_PDR, 469 record, &pdrData, &pdrSize); 470 if (record && (localOrRemote ^ pldm_pdr_record_is_remote(record))) 471 { 472 auto pdr = reinterpret_cast<pldm_state_effecter_pdr*>(pdrData); 473 auto compositeEffecterCount = pdr->composite_effecter_count; 474 auto possible_states_start = pdr->possible_states; 475 476 for (auto effecters = 0x00; effecters < compositeEffecterCount; 477 effecters++) 478 { 479 auto possibleStates = 480 reinterpret_cast<state_effecter_possible_states*>( 481 possible_states_start); 482 auto setId = possibleStates->state_set_id; 483 auto possibleStateSize = possibleStates->possible_states_size; 484 485 if (entityType == pdr->entity_type && 486 entityInstance == pdr->entity_instance && 487 containerId == pdr->container_id && stateSetId == setId) 488 { 489 return pdr->effecter_id; 490 } 491 possible_states_start += possibleStateSize + sizeof(setId) + 492 sizeof(possibleStateSize); 493 } 494 } 495 } while (record); 496 497 return PLDM_INVALID_EFFECTER_ID; 498 } 499 500 int emitStateSensorEventSignal(uint8_t tid, uint16_t sensorId, 501 uint8_t sensorOffset, uint8_t eventState, 502 uint8_t previousEventState) 503 { 504 try 505 { 506 auto& bus = DBusHandler::getBus(); 507 auto msg = bus.new_signal("/xyz/openbmc_project/pldm", 508 "xyz.openbmc_project.PLDM.Event", 509 "StateSensorEvent"); 510 msg.append(tid, sensorId, sensorOffset, eventState, previousEventState); 511 512 msg.signal_send(); 513 } 514 catch (const std::exception& e) 515 { 516 error("Failed to emit pldm event signal, error - {ERROR}", "ERROR", e); 517 return PLDM_ERROR; 518 } 519 520 return PLDM_SUCCESS; 521 } 522 523 uint16_t findStateSensorId(const pldm_pdr* pdrRepo, uint8_t tid, 524 uint16_t entityType, uint16_t entityInstance, 525 uint16_t containerId, uint16_t stateSetId) 526 { 527 auto pdrs = findStateSensorPDR(tid, entityType, stateSetId, pdrRepo); 528 for (auto pdr : pdrs) 529 { 530 auto sensorPdr = reinterpret_cast<pldm_state_sensor_pdr*>(pdr.data()); 531 auto compositeSensorCount = sensorPdr->composite_sensor_count; 532 auto possible_states_start = sensorPdr->possible_states; 533 534 for (auto sensors = 0x00; sensors < compositeSensorCount; sensors++) 535 { 536 auto possibleStates = 537 reinterpret_cast<state_sensor_possible_states*>( 538 possible_states_start); 539 auto setId = possibleStates->state_set_id; 540 auto possibleStateSize = possibleStates->possible_states_size; 541 if (entityType == sensorPdr->entity_type && 542 entityInstance == sensorPdr->entity_instance && 543 stateSetId == setId && containerId == sensorPdr->container_id) 544 { 545 return sensorPdr->sensor_id; 546 } 547 possible_states_start += possibleStateSize + sizeof(setId) + 548 sizeof(possibleStateSize); 549 } 550 } 551 return PLDM_INVALID_EFFECTER_ID; 552 } 553 554 void printBuffer(bool isTx, const std::vector<uint8_t>& buffer) 555 { 556 if (buffer.empty()) 557 { 558 return; 559 } 560 561 std::cout << (isTx ? "Tx: " : "Rx: "); 562 563 std::ranges::for_each(buffer, [](uint8_t byte) { 564 std::cout << std::format("{:02x} ", byte); 565 }); 566 567 std::cout << std::endl; 568 } 569 570 std::string toString(const struct variable_field& var) 571 { 572 if (var.ptr == nullptr || !var.length) 573 { 574 return ""; 575 } 576 577 std::string str(reinterpret_cast<const char*>(var.ptr), var.length); 578 std::replace_if( 579 str.begin(), str.end(), [](const char& c) { return !isprint(c); }, ' '); 580 return str; 581 } 582 583 std::vector<std::string> split(std::string_view srcStr, std::string_view delim, 584 std::string_view trimStr) 585 { 586 std::vector<std::string> out; 587 size_t start; 588 size_t end = 0; 589 590 while ((start = srcStr.find_first_not_of(delim, end)) != std::string::npos) 591 { 592 end = srcStr.find(delim, start); 593 std::string_view dstStr = srcStr.substr(start, end - start); 594 if (!trimStr.empty()) 595 { 596 dstStr.remove_prefix(dstStr.find_first_not_of(trimStr)); 597 dstStr.remove_suffix(dstStr.size() - 1 - 598 dstStr.find_last_not_of(trimStr)); 599 } 600 601 if (!dstStr.empty()) 602 { 603 out.push_back(std::string(dstStr)); 604 } 605 } 606 607 return out; 608 } 609 610 std::string getCurrentSystemTime() 611 { 612 const auto zonedTime{std::chrono::zoned_time{ 613 std::chrono::current_zone(), std::chrono::system_clock::now()}}; 614 return std::format("{:%F %Z %T}", zonedTime); 615 } 616 617 bool checkForFruPresence(const std::string& objPath) 618 { 619 bool isPresent = false; 620 static constexpr auto presentInterface = 621 "xyz.openbmc_project.Inventory.Item"; 622 static constexpr auto presentProperty = "Present"; 623 try 624 { 625 auto propVal = pldm::utils::DBusHandler().getDbusPropertyVariant( 626 objPath.c_str(), presentProperty, presentInterface); 627 isPresent = std::get<bool>(propVal); 628 } 629 catch (const sdbusplus::exception::SdBusError& e) 630 { 631 error("Failed to check for FRU presence at {PATH}, error - {ERROR}", 632 "PATH", objPath, "ERROR", e); 633 } 634 return isPresent; 635 } 636 637 bool checkIfLogicalBitSet(const uint16_t& containerId) 638 { 639 return !(containerId & 0x8000); 640 } 641 642 void setFruPresence(const std::string& fruObjPath, bool present) 643 { 644 pldm::utils::PropertyValue value{present}; 645 pldm::utils::DBusMapping dbusMapping; 646 dbusMapping.objectPath = fruObjPath; 647 dbusMapping.interface = "xyz.openbmc_project.Inventory.Item"; 648 dbusMapping.propertyName = "Present"; 649 dbusMapping.propertyType = "bool"; 650 try 651 { 652 pldm::utils::DBusHandler().setDbusProperty(dbusMapping, value); 653 } 654 catch (const std::exception& e) 655 { 656 error( 657 "Failed to set the present property on path '{PATH}', error - {ERROR}.", 658 "PATH", fruObjPath, "ERROR", e); 659 } 660 } 661 662 } // namespace utils 663 } // namespace pldm 664