1 /* 2 // Copyright (c) 2017-2019 Intel Corporation 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 */ 16 17 #include <boost/algorithm/string.hpp> 18 #include <boost/container/flat_map.hpp> 19 #include <boost/process.hpp> 20 #include <commandutils.hpp> 21 #include <filesystem> 22 #include <functional> 23 #include <iostream> 24 #include <ipmi_to_redfish_hooks.hpp> 25 #include <ipmid/api.hpp> 26 #include <phosphor-ipmi-host/selutility.hpp> 27 #include <phosphor-logging/log.hpp> 28 #include <sdbusplus/message/types.hpp> 29 #include <sdbusplus/timer.hpp> 30 #include <sdrutils.hpp> 31 #include <stdexcept> 32 #include <storagecommands.hpp> 33 #include <string_view> 34 35 static constexpr bool DEBUG = false; 36 37 namespace intel_oem::ipmi::sel 38 { 39 static const std::filesystem::path selLogDir = "/var/log"; 40 static const std::string selLogFilename = "ipmi_sel"; 41 42 static int getFileTimestamp(const std::filesystem::path& file) 43 { 44 struct stat st; 45 46 if (stat(file.c_str(), &st) >= 0) 47 { 48 return st.st_mtime; 49 } 50 return ::ipmi::sel::invalidTimeStamp; 51 } 52 53 namespace erase_time 54 { 55 static constexpr const char* selEraseTimestamp = "/var/lib/ipmi/sel_erase_time"; 56 57 void save() 58 { 59 // open the file, creating it if necessary 60 int fd = open(selEraseTimestamp, O_WRONLY | O_CREAT | O_CLOEXEC, 0644); 61 if (fd < 0) 62 { 63 std::cerr << "Failed to open file\n"; 64 return; 65 } 66 67 // update the file timestamp to the current time 68 if (futimens(fd, NULL) < 0) 69 { 70 std::cerr << "Failed to update timestamp: " 71 << std::string(strerror(errno)); 72 } 73 close(fd); 74 } 75 76 int get() 77 { 78 return getFileTimestamp(selEraseTimestamp); 79 } 80 } // namespace erase_time 81 } // namespace intel_oem::ipmi::sel 82 83 namespace ipmi 84 { 85 86 namespace storage 87 { 88 89 constexpr static const size_t maxMessageSize = 64; 90 constexpr static const size_t maxFruSdrNameSize = 16; 91 using ManagedObjectType = boost::container::flat_map< 92 sdbusplus::message::object_path, 93 boost::container::flat_map< 94 std::string, boost::container::flat_map<std::string, DbusVariant>>>; 95 using ManagedEntry = std::pair< 96 sdbusplus::message::object_path, 97 boost::container::flat_map< 98 std::string, boost::container::flat_map<std::string, DbusVariant>>>; 99 100 constexpr static const char* fruDeviceServiceName = 101 "xyz.openbmc_project.FruDevice"; 102 constexpr static const char* entityManagerServiceName = 103 "xyz.openbmc_project.EntityManager"; 104 constexpr static const size_t cacheTimeoutSeconds = 10; 105 106 // event direction is bit[7] of eventType where 1b = Deassertion event 107 constexpr static const uint8_t deassertionEvent = 0x80; 108 109 static std::vector<uint8_t> fruCache; 110 static uint8_t cacheBus = 0xFF; 111 static uint8_t cacheAddr = 0XFF; 112 113 std::unique_ptr<phosphor::Timer> cacheTimer = nullptr; 114 115 // we unfortunately have to build a map of hashes in case there is a 116 // collision to verify our dev-id 117 boost::container::flat_map<uint8_t, std::pair<uint8_t, uint8_t>> deviceHashes; 118 119 void registerStorageFunctions() __attribute__((constructor)); 120 121 bool writeFru() 122 { 123 std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus(); 124 sdbusplus::message::message writeFru = dbus->new_method_call( 125 fruDeviceServiceName, "/xyz/openbmc_project/FruDevice", 126 "xyz.openbmc_project.FruDeviceManager", "WriteFru"); 127 writeFru.append(cacheBus, cacheAddr, fruCache); 128 try 129 { 130 sdbusplus::message::message writeFruResp = dbus->call(writeFru); 131 } 132 catch (sdbusplus::exception_t&) 133 { 134 // todo: log sel? 135 phosphor::logging::log<phosphor::logging::level::ERR>( 136 "error writing fru"); 137 return false; 138 } 139 return true; 140 } 141 142 void createTimer() 143 { 144 if (cacheTimer == nullptr) 145 { 146 cacheTimer = std::make_unique<phosphor::Timer>(writeFru); 147 } 148 } 149 150 ipmi_ret_t replaceCacheFru(uint8_t devId) 151 { 152 static uint8_t lastDevId = 0xFF; 153 154 bool timerRunning = (cacheTimer != nullptr) && !cacheTimer->isExpired(); 155 if (lastDevId == devId && timerRunning) 156 { 157 return IPMI_CC_OK; // cache already up to date 158 } 159 // if timer is running, stop it and writeFru manually 160 else if (timerRunning) 161 { 162 cacheTimer->stop(); 163 writeFru(); 164 } 165 166 std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus(); 167 sdbusplus::message::message getObjects = dbus->new_method_call( 168 fruDeviceServiceName, "/", "org.freedesktop.DBus.ObjectManager", 169 "GetManagedObjects"); 170 ManagedObjectType frus; 171 try 172 { 173 sdbusplus::message::message resp = dbus->call(getObjects); 174 resp.read(frus); 175 } 176 catch (sdbusplus::exception_t&) 177 { 178 phosphor::logging::log<phosphor::logging::level::ERR>( 179 "replaceCacheFru: error getting managed objects"); 180 return IPMI_CC_RESPONSE_ERROR; 181 } 182 183 deviceHashes.clear(); 184 185 // hash the object paths to create unique device id's. increment on 186 // collision 187 std::hash<std::string> hasher; 188 for (const auto& fru : frus) 189 { 190 auto fruIface = fru.second.find("xyz.openbmc_project.FruDevice"); 191 if (fruIface == fru.second.end()) 192 { 193 continue; 194 } 195 196 auto busFind = fruIface->second.find("BUS"); 197 auto addrFind = fruIface->second.find("ADDRESS"); 198 if (busFind == fruIface->second.end() || 199 addrFind == fruIface->second.end()) 200 { 201 phosphor::logging::log<phosphor::logging::level::INFO>( 202 "fru device missing Bus or Address", 203 phosphor::logging::entry("FRU=%s", fru.first.str.c_str())); 204 continue; 205 } 206 207 uint8_t fruBus = std::get<uint32_t>(busFind->second); 208 uint8_t fruAddr = std::get<uint32_t>(addrFind->second); 209 210 uint8_t fruHash = 0; 211 if (fruBus != 0 || fruAddr != 0) 212 { 213 fruHash = hasher(fru.first.str); 214 // can't be 0xFF based on spec, and 0 is reserved for baseboard 215 if (fruHash == 0 || fruHash == 0xFF) 216 { 217 fruHash = 1; 218 } 219 } 220 std::pair<uint8_t, uint8_t> newDev(fruBus, fruAddr); 221 222 bool emplacePassed = false; 223 while (!emplacePassed) 224 { 225 auto resp = deviceHashes.emplace(fruHash, newDev); 226 emplacePassed = resp.second; 227 if (!emplacePassed) 228 { 229 fruHash++; 230 // can't be 0xFF based on spec, and 0 is reserved for 231 // baseboard 232 if (fruHash == 0XFF) 233 { 234 fruHash = 0x1; 235 } 236 } 237 } 238 } 239 auto deviceFind = deviceHashes.find(devId); 240 if (deviceFind == deviceHashes.end()) 241 { 242 return IPMI_CC_SENSOR_INVALID; 243 } 244 245 fruCache.clear(); 246 sdbusplus::message::message getRawFru = dbus->new_method_call( 247 fruDeviceServiceName, "/xyz/openbmc_project/FruDevice", 248 "xyz.openbmc_project.FruDeviceManager", "GetRawFru"); 249 cacheBus = deviceFind->second.first; 250 cacheAddr = deviceFind->second.second; 251 getRawFru.append(cacheBus, cacheAddr); 252 try 253 { 254 sdbusplus::message::message getRawResp = dbus->call(getRawFru); 255 getRawResp.read(fruCache); 256 } 257 catch (sdbusplus::exception_t&) 258 { 259 lastDevId = 0xFF; 260 cacheBus = 0xFF; 261 cacheAddr = 0xFF; 262 return IPMI_CC_RESPONSE_ERROR; 263 } 264 265 lastDevId = devId; 266 return IPMI_CC_OK; 267 } 268 269 /** @brief implements the read FRU data command 270 * @param fruDeviceId - FRU Device ID 271 * @param fruInventoryOffset - FRU Inventory Offset to write 272 * @param countToRead - Count to read 273 * 274 * @returns ipmi completion code plus response data 275 * - countWritten - Count written 276 */ 277 ipmi::RspType<uint8_t, // Count 278 std::vector<uint8_t> // Requested data 279 > 280 ipmiStorageReadFruData(uint8_t fruDeviceId, uint16_t fruInventoryOffset, 281 uint8_t countToRead) 282 { 283 if (fruDeviceId == 0xFF) 284 { 285 return ipmi::responseInvalidFieldRequest(); 286 } 287 288 ipmi::Cc status = replaceCacheFru(fruDeviceId); 289 290 if (status != ipmi::ccSuccess) 291 { 292 return ipmi::response(status); 293 } 294 295 size_t fromFruByteLen = 0; 296 if (countToRead + fruInventoryOffset < fruCache.size()) 297 { 298 fromFruByteLen = countToRead; 299 } 300 else if (fruCache.size() > fruInventoryOffset) 301 { 302 fromFruByteLen = fruCache.size() - fruInventoryOffset; 303 } 304 else 305 { 306 return ipmi::responseInvalidFieldRequest(); 307 } 308 309 std::vector<uint8_t> requestedData; 310 311 requestedData.insert( 312 requestedData.begin(), fruCache.begin() + fruInventoryOffset, 313 fruCache.begin() + fruInventoryOffset + fromFruByteLen); 314 315 return ipmi::responseSuccess(countToRead, requestedData); 316 } 317 318 /** @brief implements the write FRU data command 319 * @param fruDeviceId - FRU Device ID 320 * @param fruInventoryOffset - FRU Inventory Offset to write 321 * @param dataToWrite - Data to write 322 * 323 * @returns ipmi completion code plus response data 324 * - countWritten - Count written 325 */ 326 ipmi::RspType<uint8_t> 327 ipmiStorageWriteFruData(uint8_t fruDeviceId, uint16_t fruInventoryOffset, 328 std::vector<uint8_t>& dataToWrite) 329 { 330 if (fruDeviceId == 0xFF) 331 { 332 return ipmi::responseInvalidFieldRequest(); 333 } 334 335 size_t writeLen = dataToWrite.size(); 336 337 ipmi::Cc status = replaceCacheFru(fruDeviceId); 338 if (status != ipmi::ccSuccess) 339 { 340 return ipmi::response(status); 341 } 342 int lastWriteAddr = fruInventoryOffset + writeLen; 343 if (fruCache.size() < lastWriteAddr) 344 { 345 fruCache.resize(fruInventoryOffset + writeLen); 346 } 347 348 std::copy(dataToWrite.begin(), dataToWrite.begin() + writeLen, 349 fruCache.begin() + fruInventoryOffset); 350 351 bool atEnd = false; 352 353 if (fruCache.size() >= sizeof(FRUHeader)) 354 { 355 FRUHeader* header = reinterpret_cast<FRUHeader*>(fruCache.data()); 356 357 int lastRecordStart = std::max( 358 header->internalOffset, 359 std::max(header->chassisOffset, 360 std::max(header->boardOffset, header->productOffset))); 361 // TODO: Handle Multi-Record FRUs? 362 363 lastRecordStart *= 8; // header starts in are multiples of 8 bytes 364 365 // get the length of the area in multiples of 8 bytes 366 if (lastWriteAddr > (lastRecordStart + 1)) 367 { 368 // second byte in record area is the length 369 int areaLength(fruCache[lastRecordStart + 1]); 370 areaLength *= 8; // it is in multiples of 8 bytes 371 372 if (lastWriteAddr >= (areaLength + lastRecordStart)) 373 { 374 atEnd = true; 375 } 376 } 377 } 378 uint8_t countWritten = 0; 379 if (atEnd) 380 { 381 // cancel timer, we're at the end so might as well send it 382 cacheTimer->stop(); 383 if (!writeFru()) 384 { 385 return ipmi::responseInvalidFieldRequest(); 386 } 387 countWritten = std::min(fruCache.size(), static_cast<size_t>(0xFF)); 388 } 389 else 390 { 391 // start a timer, if no further data is sent in cacheTimeoutSeconds 392 // seconds, check to see if it is valid 393 createTimer(); 394 cacheTimer->start(std::chrono::duration_cast<std::chrono::microseconds>( 395 std::chrono::seconds(cacheTimeoutSeconds))); 396 countWritten = 0; 397 } 398 399 return ipmi::responseSuccess(countWritten); 400 } 401 402 /** @brief implements the get FRU inventory area info command 403 * @param fruDeviceId - FRU Device ID 404 * 405 * @returns IPMI completion code plus response data 406 * - inventorySize - Number of possible allocation units 407 * - accessType - Allocation unit size in bytes. 408 */ 409 ipmi::RspType<uint16_t, // inventorySize 410 uint8_t> // accessType 411 ipmiStorageGetFruInvAreaInfo(uint8_t fruDeviceId) 412 { 413 if (fruDeviceId == 0xFF) 414 { 415 return ipmi::responseInvalidFieldRequest(); 416 } 417 418 ipmi::Cc status = replaceCacheFru(fruDeviceId); 419 420 if (status != IPMI_CC_OK) 421 { 422 return ipmi::response(status); 423 } 424 425 constexpr uint8_t accessType = 426 static_cast<uint8_t>(GetFRUAreaAccessType::byte); 427 428 return ipmi::responseSuccess(fruCache.size(), accessType); 429 } 430 431 ipmi_ret_t getFruSdrCount(size_t& count) 432 { 433 ipmi_ret_t ret = replaceCacheFru(0); 434 if (ret != IPMI_CC_OK) 435 { 436 return ret; 437 } 438 count = deviceHashes.size(); 439 return IPMI_CC_OK; 440 } 441 442 ipmi_ret_t getFruSdrs(size_t index, get_sdr::SensorDataFruRecord& resp) 443 { 444 ipmi_ret_t ret = replaceCacheFru(0); // this will update the hash list 445 if (ret != IPMI_CC_OK) 446 { 447 return ret; 448 } 449 if (deviceHashes.size() < index) 450 { 451 return IPMI_CC_INVALID_FIELD_REQUEST; 452 } 453 auto device = deviceHashes.begin() + index; 454 uint8_t& bus = device->second.first; 455 uint8_t& address = device->second.second; 456 457 ManagedObjectType frus; 458 459 std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus(); 460 sdbusplus::message::message getObjects = dbus->new_method_call( 461 fruDeviceServiceName, "/", "org.freedesktop.DBus.ObjectManager", 462 "GetManagedObjects"); 463 try 464 { 465 sdbusplus::message::message resp = dbus->call(getObjects); 466 resp.read(frus); 467 } 468 catch (sdbusplus::exception_t&) 469 { 470 return IPMI_CC_RESPONSE_ERROR; 471 } 472 boost::container::flat_map<std::string, DbusVariant>* fruData = nullptr; 473 auto fru = 474 std::find_if(frus.begin(), frus.end(), 475 [bus, address, &fruData](ManagedEntry& entry) { 476 auto findFruDevice = 477 entry.second.find("xyz.openbmc_project.FruDevice"); 478 if (findFruDevice == entry.second.end()) 479 { 480 return false; 481 } 482 fruData = &(findFruDevice->second); 483 auto findBus = findFruDevice->second.find("BUS"); 484 auto findAddress = 485 findFruDevice->second.find("ADDRESS"); 486 if (findBus == findFruDevice->second.end() || 487 findAddress == findFruDevice->second.end()) 488 { 489 return false; 490 } 491 if (std::get<uint32_t>(findBus->second) != bus) 492 { 493 return false; 494 } 495 if (std::get<uint32_t>(findAddress->second) != address) 496 { 497 return false; 498 } 499 return true; 500 }); 501 if (fru == frus.end()) 502 { 503 return IPMI_CC_RESPONSE_ERROR; 504 } 505 506 boost::container::flat_map<std::string, DbusVariant>* entityData = nullptr; 507 ManagedObjectType entities; 508 509 try 510 { 511 std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus(); 512 513 sdbusplus::message::message getObjects = dbus->new_method_call( 514 entityManagerServiceName, "/", "org.freedesktop.DBus.ObjectManager", 515 "GetManagedObjects"); 516 517 sdbusplus::message::message resp = dbus->call(getObjects); 518 resp.read(entities); 519 520 auto entity = std::find_if( 521 entities.begin(), entities.end(), 522 [bus, address, &entityData](ManagedEntry& entry) { 523 auto findFruDevice = entry.second.find( 524 "xyz.openbmc_project.Inventory.Decorator.FruDevice"); 525 if (findFruDevice == entry.second.end()) 526 { 527 return false; 528 } 529 530 // Integer fields added via Entity-Manager json are uint64_ts by 531 // default. 532 auto findBus = findFruDevice->second.find("Bus"); 533 auto findAddress = findFruDevice->second.find("Address"); 534 535 if (findBus == findFruDevice->second.end() || 536 findAddress == findFruDevice->second.end()) 537 { 538 return false; 539 } 540 if ((std::get<uint64_t>(findBus->second) != bus) || 541 (std::get<uint64_t>(findAddress->second) != address)) 542 { 543 return false; 544 } 545 546 auto findIpmiDevice = entry.second.find( 547 "xyz.openbmc_project.Inventory.Decorator.Ipmi"); 548 if (findIpmiDevice == entry.second.end()) 549 { 550 return false; 551 } 552 553 entityData = &(findIpmiDevice->second); 554 return true; 555 }); 556 557 if (entity == entities.end()) 558 { 559 if constexpr (DEBUG) 560 { 561 std::fprintf(stderr, "Ipmi or FruDevice Decorator interface " 562 "not found for Fru\n"); 563 } 564 } 565 } 566 catch (const std::exception& e) 567 { 568 std::fprintf( 569 stderr, 570 "Search for FruDevice+Ipmi Decorator Interface excepted: '%s'\n", 571 e.what()); 572 } 573 574 std::string name; 575 auto findProductName = fruData->find("BOARD_PRODUCT_NAME"); 576 auto findBoardName = fruData->find("PRODUCT_PRODUCT_NAME"); 577 if (findProductName != fruData->end()) 578 { 579 name = std::get<std::string>(findProductName->second); 580 } 581 else if (findBoardName != fruData->end()) 582 { 583 name = std::get<std::string>(findBoardName->second); 584 } 585 else 586 { 587 name = "UNKNOWN"; 588 } 589 if (name.size() > maxFruSdrNameSize) 590 { 591 name = name.substr(0, maxFruSdrNameSize); 592 } 593 size_t sizeDiff = maxFruSdrNameSize - name.size(); 594 595 resp.header.record_id_lsb = 0x0; // calling code is to implement these 596 resp.header.record_id_msb = 0x0; 597 resp.header.sdr_version = ipmiSdrVersion; 598 resp.header.record_type = get_sdr::SENSOR_DATA_FRU_RECORD; 599 resp.header.record_length = sizeof(resp.body) + sizeof(resp.key) - sizeDiff; 600 resp.key.deviceAddress = 0x20; 601 resp.key.fruID = device->first; 602 resp.key.accessLun = 0x80; // logical / physical fru device 603 resp.key.channelNumber = 0x0; 604 resp.body.reserved = 0x0; 605 resp.body.deviceType = 0x10; 606 resp.body.deviceTypeModifier = 0x0; 607 608 uint8_t entityID = 0; 609 uint8_t entityInstance = 0x1; 610 611 if (entityData) 612 { 613 auto entityIdProperty = entityData->find("EntityId"); 614 auto entityInstanceProperty = entityData->find("EntityInstance"); 615 616 if (entityIdProperty != entityData->end()) 617 { 618 entityID = static_cast<uint8_t>( 619 std::get<uint64_t>(entityIdProperty->second)); 620 } 621 if (entityInstanceProperty != entityData->end()) 622 { 623 entityInstance = static_cast<uint8_t>( 624 std::get<uint64_t>(entityInstanceProperty->second)); 625 } 626 } 627 628 resp.body.entityID = entityID; 629 resp.body.entityInstance = entityInstance; 630 631 resp.body.oem = 0x0; 632 resp.body.deviceIDLen = name.size(); 633 name.copy(resp.body.deviceID, name.size()); 634 635 return IPMI_CC_OK; 636 } 637 638 static bool getSELLogFiles(std::vector<std::filesystem::path>& selLogFiles) 639 { 640 // Loop through the directory looking for ipmi_sel log files 641 for (const std::filesystem::directory_entry& dirEnt : 642 std::filesystem::directory_iterator(intel_oem::ipmi::sel::selLogDir)) 643 { 644 std::string filename = dirEnt.path().filename(); 645 if (boost::starts_with(filename, intel_oem::ipmi::sel::selLogFilename)) 646 { 647 // If we find an ipmi_sel log file, save the path 648 selLogFiles.emplace_back(intel_oem::ipmi::sel::selLogDir / 649 filename); 650 } 651 } 652 // As the log files rotate, they are appended with a ".#" that is higher for 653 // the older logs. Since we don't expect more than 10 log files, we 654 // can just sort the list to get them in order from newest to oldest 655 std::sort(selLogFiles.begin(), selLogFiles.end()); 656 657 return !selLogFiles.empty(); 658 } 659 660 static int countSELEntries() 661 { 662 // Get the list of ipmi_sel log files 663 std::vector<std::filesystem::path> selLogFiles; 664 if (!getSELLogFiles(selLogFiles)) 665 { 666 return 0; 667 } 668 int numSELEntries = 0; 669 // Loop through each log file and count the number of logs 670 for (const std::filesystem::path& file : selLogFiles) 671 { 672 std::ifstream logStream(file); 673 if (!logStream.is_open()) 674 { 675 continue; 676 } 677 678 std::string line; 679 while (std::getline(logStream, line)) 680 { 681 numSELEntries++; 682 } 683 } 684 return numSELEntries; 685 } 686 687 static bool findSELEntry(const int recordID, 688 const std::vector<std::filesystem::path>& selLogFiles, 689 std::string& entry) 690 { 691 // Record ID is the first entry field following the timestamp. It is 692 // preceded by a space and followed by a comma 693 std::string search = " " + std::to_string(recordID) + ","; 694 695 // Loop through the ipmi_sel log entries 696 for (const std::filesystem::path& file : selLogFiles) 697 { 698 std::ifstream logStream(file); 699 if (!logStream.is_open()) 700 { 701 continue; 702 } 703 704 while (std::getline(logStream, entry)) 705 { 706 // Check if the record ID matches 707 if (entry.find(search) != std::string::npos) 708 { 709 return true; 710 } 711 } 712 } 713 return false; 714 } 715 716 static uint16_t 717 getNextRecordID(const uint16_t recordID, 718 const std::vector<std::filesystem::path>& selLogFiles) 719 { 720 uint16_t nextRecordID = recordID + 1; 721 std::string entry; 722 if (findSELEntry(nextRecordID, selLogFiles, entry)) 723 { 724 return nextRecordID; 725 } 726 else 727 { 728 return ipmi::sel::lastEntry; 729 } 730 } 731 732 static int fromHexStr(const std::string& hexStr, std::vector<uint8_t>& data) 733 { 734 for (unsigned int i = 0; i < hexStr.size(); i += 2) 735 { 736 try 737 { 738 data.push_back(static_cast<uint8_t>( 739 std::stoul(hexStr.substr(i, 2), nullptr, 16))); 740 } 741 catch (std::invalid_argument& e) 742 { 743 phosphor::logging::log<phosphor::logging::level::ERR>(e.what()); 744 return -1; 745 } 746 catch (std::out_of_range& e) 747 { 748 phosphor::logging::log<phosphor::logging::level::ERR>(e.what()); 749 return -1; 750 } 751 } 752 return 0; 753 } 754 755 ipmi::RspType<uint8_t, // SEL version 756 uint16_t, // SEL entry count 757 uint16_t, // free space 758 uint32_t, // last add timestamp 759 uint32_t, // last erase timestamp 760 uint8_t> // operation support 761 ipmiStorageGetSELInfo() 762 { 763 constexpr uint8_t selVersion = ipmi::sel::selVersion; 764 uint16_t entries = countSELEntries(); 765 uint32_t addTimeStamp = intel_oem::ipmi::sel::getFileTimestamp( 766 intel_oem::ipmi::sel::selLogDir / intel_oem::ipmi::sel::selLogFilename); 767 uint32_t eraseTimeStamp = intel_oem::ipmi::sel::erase_time::get(); 768 constexpr uint8_t operationSupport = 769 intel_oem::ipmi::sel::selOperationSupport; 770 constexpr uint16_t freeSpace = 771 0xffff; // Spec indicates that more than 64kB is free 772 773 return ipmi::responseSuccess(selVersion, entries, freeSpace, addTimeStamp, 774 eraseTimeStamp, operationSupport); 775 } 776 777 using systemEventType = std::tuple< 778 uint32_t, // Timestamp 779 uint16_t, // Generator ID 780 uint8_t, // EvM Rev 781 uint8_t, // Sensor Type 782 uint8_t, // Sensor Number 783 uint7_t, // Event Type 784 bool, // Event Direction 785 std::array<uint8_t, intel_oem::ipmi::sel::systemEventSize>>; // Event Data 786 using oemTsEventType = std::tuple< 787 uint32_t, // Timestamp 788 std::array<uint8_t, intel_oem::ipmi::sel::oemTsEventSize>>; // Event Data 789 using oemEventType = 790 std::array<uint8_t, intel_oem::ipmi::sel::oemEventSize>; // Event Data 791 792 ipmi::RspType<uint16_t, // Next Record ID 793 uint16_t, // Record ID 794 uint8_t, // Record Type 795 std::variant<systemEventType, oemTsEventType, 796 oemEventType>> // Record Content 797 ipmiStorageGetSELEntry(uint16_t reservationID, uint16_t targetID, 798 uint8_t offset, uint8_t size) 799 { 800 // Only support getting the entire SEL record. If a partial size or non-zero 801 // offset is requested, return an error 802 if (offset != 0 || size != ipmi::sel::entireRecord) 803 { 804 return ipmi::responseRetBytesUnavailable(); 805 } 806 807 // Check the reservation ID if one is provided or required (only if the 808 // offset is non-zero) 809 if (reservationID != 0 || offset != 0) 810 { 811 if (!checkSELReservation(reservationID)) 812 { 813 return ipmi::responseInvalidReservationId(); 814 } 815 } 816 817 // Get the ipmi_sel log files 818 std::vector<std::filesystem::path> selLogFiles; 819 if (!getSELLogFiles(selLogFiles)) 820 { 821 return ipmi::responseSensorInvalid(); 822 } 823 824 std::string targetEntry; 825 826 if (targetID == ipmi::sel::firstEntry) 827 { 828 // The first entry will be at the top of the oldest log file 829 std::ifstream logStream(selLogFiles.back()); 830 if (!logStream.is_open()) 831 { 832 return ipmi::responseUnspecifiedError(); 833 } 834 835 if (!std::getline(logStream, targetEntry)) 836 { 837 return ipmi::responseUnspecifiedError(); 838 } 839 } 840 else if (targetID == ipmi::sel::lastEntry) 841 { 842 // The last entry will be at the bottom of the newest log file 843 std::ifstream logStream(selLogFiles.front()); 844 if (!logStream.is_open()) 845 { 846 return ipmi::responseUnspecifiedError(); 847 } 848 849 std::string line; 850 while (std::getline(logStream, line)) 851 { 852 targetEntry = line; 853 } 854 } 855 else 856 { 857 if (!findSELEntry(targetID, selLogFiles, targetEntry)) 858 { 859 return ipmi::responseSensorInvalid(); 860 } 861 } 862 863 // The format of the ipmi_sel message is "<Timestamp> 864 // <ID>,<Type>,<EventData>,[<Generator ID>,<Path>,<Direction>]". 865 // First get the Timestamp 866 size_t space = targetEntry.find_first_of(" "); 867 if (space == std::string::npos) 868 { 869 return ipmi::responseUnspecifiedError(); 870 } 871 std::string entryTimestamp = targetEntry.substr(0, space); 872 // Then get the log contents 873 size_t entryStart = targetEntry.find_first_not_of(" ", space); 874 if (entryStart == std::string::npos) 875 { 876 return ipmi::responseUnspecifiedError(); 877 } 878 std::string_view entry(targetEntry); 879 entry.remove_prefix(entryStart); 880 // Use split to separate the entry into its fields 881 std::vector<std::string> targetEntryFields; 882 boost::split(targetEntryFields, entry, boost::is_any_of(","), 883 boost::token_compress_on); 884 if (targetEntryFields.size() < 3) 885 { 886 return ipmi::responseUnspecifiedError(); 887 } 888 std::string& recordIDStr = targetEntryFields[0]; 889 std::string& recordTypeStr = targetEntryFields[1]; 890 std::string& eventDataStr = targetEntryFields[2]; 891 892 uint16_t recordID; 893 uint8_t recordType; 894 try 895 { 896 recordID = std::stoul(recordIDStr); 897 recordType = std::stoul(recordTypeStr, nullptr, 16); 898 } 899 catch (const std::invalid_argument&) 900 { 901 return ipmi::responseUnspecifiedError(); 902 } 903 uint16_t nextRecordID = getNextRecordID(recordID, selLogFiles); 904 std::vector<uint8_t> eventDataBytes; 905 if (fromHexStr(eventDataStr, eventDataBytes) < 0) 906 { 907 return ipmi::responseUnspecifiedError(); 908 } 909 910 if (recordType == intel_oem::ipmi::sel::systemEvent) 911 { 912 // Get the timestamp 913 std::tm timeStruct = {}; 914 std::istringstream entryStream(entryTimestamp); 915 916 uint32_t timestamp = ipmi::sel::invalidTimeStamp; 917 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S")) 918 { 919 timestamp = std::mktime(&timeStruct); 920 } 921 922 // Set the event message revision 923 uint8_t evmRev = intel_oem::ipmi::sel::eventMsgRev; 924 925 uint16_t generatorID = 0; 926 uint8_t sensorType = 0; 927 uint8_t sensorNum = 0xFF; 928 uint7_t eventType = 0; 929 bool eventDir = 0; 930 // System type events should have six fields 931 if (targetEntryFields.size() >= 6) 932 { 933 std::string& generatorIDStr = targetEntryFields[3]; 934 std::string& sensorPath = targetEntryFields[4]; 935 std::string& eventDirStr = targetEntryFields[5]; 936 937 // Get the generator ID 938 try 939 { 940 generatorID = std::stoul(generatorIDStr, nullptr, 16); 941 } 942 catch (const std::invalid_argument&) 943 { 944 std::cerr << "Invalid Generator ID\n"; 945 } 946 947 // Get the sensor type, sensor number, and event type for the sensor 948 sensorType = getSensorTypeFromPath(sensorPath); 949 sensorNum = getSensorNumberFromPath(sensorPath); 950 eventType = getSensorEventTypeFromPath(sensorPath); 951 952 // Get the event direction 953 try 954 { 955 eventDir = std::stoul(eventDirStr) ? 0 : 1; 956 } 957 catch (const std::invalid_argument&) 958 { 959 std::cerr << "Invalid Event Direction\n"; 960 } 961 } 962 963 // Only keep the eventData bytes that fit in the record 964 std::array<uint8_t, intel_oem::ipmi::sel::systemEventSize> eventData{}; 965 std::copy_n(eventDataBytes.begin(), 966 std::min(eventDataBytes.size(), eventData.size()), 967 eventData.begin()); 968 969 return ipmi::responseSuccess( 970 nextRecordID, recordID, recordType, 971 systemEventType{timestamp, generatorID, evmRev, sensorType, 972 sensorNum, eventType, eventDir, eventData}); 973 } 974 else if (recordType >= intel_oem::ipmi::sel::oemTsEventFirst && 975 recordType <= intel_oem::ipmi::sel::oemTsEventLast) 976 { 977 // Get the timestamp 978 std::tm timeStruct = {}; 979 std::istringstream entryStream(entryTimestamp); 980 981 uint32_t timestamp = ipmi::sel::invalidTimeStamp; 982 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S")) 983 { 984 timestamp = std::mktime(&timeStruct); 985 } 986 987 // Only keep the bytes that fit in the record 988 std::array<uint8_t, intel_oem::ipmi::sel::oemTsEventSize> eventData{}; 989 std::copy_n(eventDataBytes.begin(), 990 std::min(eventDataBytes.size(), eventData.size()), 991 eventData.begin()); 992 993 return ipmi::responseSuccess(nextRecordID, recordID, recordType, 994 oemTsEventType{timestamp, eventData}); 995 } 996 else if (recordType >= intel_oem::ipmi::sel::oemEventFirst) 997 { 998 // Only keep the bytes that fit in the record 999 std::array<uint8_t, intel_oem::ipmi::sel::oemEventSize> eventData{}; 1000 std::copy_n(eventDataBytes.begin(), 1001 std::min(eventDataBytes.size(), eventData.size()), 1002 eventData.begin()); 1003 1004 return ipmi::responseSuccess(nextRecordID, recordID, recordType, 1005 eventData); 1006 } 1007 1008 return ipmi::responseUnspecifiedError(); 1009 } 1010 1011 ipmi::RspType<uint16_t> ipmiStorageAddSELEntry( 1012 uint16_t recordID, uint8_t recordType, uint32_t timestamp, 1013 uint16_t generatorID, uint8_t evmRev, uint8_t sensorType, uint8_t sensorNum, 1014 uint8_t eventType, uint8_t eventData1, uint8_t eventData2, 1015 uint8_t eventData3) 1016 { 1017 // Per the IPMI spec, need to cancel any reservation when a SEL entry is 1018 // added 1019 cancelSELReservation(); 1020 1021 // Send this request to the Redfish hooks to log it as a Redfish message 1022 // instead. There is no need to add it to the SEL, so just return success. 1023 intel_oem::ipmi::sel::checkRedfishHooks( 1024 recordID, recordType, timestamp, generatorID, evmRev, sensorType, 1025 sensorNum, eventType, eventData1, eventData2, eventData3); 1026 1027 uint16_t responseID = 0xFFFF; 1028 return ipmi::responseSuccess(responseID); 1029 } 1030 1031 ipmi::RspType<uint8_t> ipmiStorageClearSEL(ipmi::Context::ptr ctx, 1032 uint16_t reservationID, 1033 const std::array<uint8_t, 3>& clr, 1034 uint8_t eraseOperation) 1035 { 1036 if (!checkSELReservation(reservationID)) 1037 { 1038 return ipmi::responseInvalidReservationId(); 1039 } 1040 1041 static constexpr std::array<uint8_t, 3> clrExpected = {'C', 'L', 'R'}; 1042 if (clr != clrExpected) 1043 { 1044 return ipmi::responseInvalidFieldRequest(); 1045 } 1046 1047 // Erasure status cannot be fetched, so always return erasure status as 1048 // `erase completed`. 1049 if (eraseOperation == ipmi::sel::getEraseStatus) 1050 { 1051 return ipmi::responseSuccess(ipmi::sel::eraseComplete); 1052 } 1053 1054 // Check that initiate erase is correct 1055 if (eraseOperation != ipmi::sel::initiateErase) 1056 { 1057 return ipmi::responseInvalidFieldRequest(); 1058 } 1059 1060 // Per the IPMI spec, need to cancel any reservation when the SEL is 1061 // cleared 1062 cancelSELReservation(); 1063 1064 // Save the erase time 1065 intel_oem::ipmi::sel::erase_time::save(); 1066 1067 // Clear the SEL by deleting the log files 1068 std::vector<std::filesystem::path> selLogFiles; 1069 if (getSELLogFiles(selLogFiles)) 1070 { 1071 for (const std::filesystem::path& file : selLogFiles) 1072 { 1073 std::error_code ec; 1074 std::filesystem::remove(file, ec); 1075 } 1076 } 1077 1078 // Reload rsyslog so it knows to start new log files 1079 std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus(); 1080 sdbusplus::message::message rsyslogReload = dbus->new_method_call( 1081 "org.freedesktop.systemd1", "/org/freedesktop/systemd1", 1082 "org.freedesktop.systemd1.Manager", "ReloadUnit"); 1083 rsyslogReload.append("rsyslog.service", "replace"); 1084 try 1085 { 1086 sdbusplus::message::message reloadResponse = dbus->call(rsyslogReload); 1087 } 1088 catch (sdbusplus::exception_t& e) 1089 { 1090 phosphor::logging::log<phosphor::logging::level::ERR>(e.what()); 1091 } 1092 1093 return ipmi::responseSuccess(ipmi::sel::eraseComplete); 1094 } 1095 1096 ipmi::RspType<uint32_t> ipmiStorageGetSELTime() 1097 { 1098 struct timespec selTime = {}; 1099 1100 if (clock_gettime(CLOCK_REALTIME, &selTime) < 0) 1101 { 1102 return ipmi::responseUnspecifiedError(); 1103 } 1104 1105 return ipmi::responseSuccess(selTime.tv_sec); 1106 } 1107 1108 ipmi::RspType<> ipmiStorageSetSELTime(uint32_t selTime) 1109 { 1110 // Set SEL Time is not supported 1111 return ipmi::responseInvalidCommand(); 1112 } 1113 1114 std::vector<uint8_t> getType12SDRs(uint16_t index, uint16_t recordId) 1115 { 1116 std::vector<uint8_t> resp; 1117 if (index == 0) 1118 { 1119 Type12Record bmc = {}; 1120 bmc.header.record_id_lsb = recordId; 1121 bmc.header.record_id_msb = recordId >> 8; 1122 bmc.header.sdr_version = ipmiSdrVersion; 1123 bmc.header.record_type = 0x12; 1124 bmc.header.record_length = 0x1b; 1125 bmc.slaveAddress = 0x20; 1126 bmc.channelNumber = 0; 1127 bmc.powerStateNotification = 0; 1128 bmc.deviceCapabilities = 0xBF; 1129 bmc.reserved = 0; 1130 bmc.entityID = 0x2E; 1131 bmc.entityInstance = 1; 1132 bmc.oem = 0; 1133 bmc.typeLengthCode = 0xD0; 1134 std::string bmcName = "Basbrd Mgmt Ctlr"; 1135 std::copy(bmcName.begin(), bmcName.end(), bmc.name); 1136 uint8_t* bmcPtr = reinterpret_cast<uint8_t*>(&bmc); 1137 resp.insert(resp.end(), bmcPtr, bmcPtr + sizeof(Type12Record)); 1138 } 1139 else if (index == 1) 1140 { 1141 Type12Record me = {}; 1142 me.header.record_id_lsb = recordId; 1143 me.header.record_id_msb = recordId >> 8; 1144 me.header.sdr_version = ipmiSdrVersion; 1145 me.header.record_type = 0x12; 1146 me.header.record_length = 0x16; 1147 me.slaveAddress = 0x2C; 1148 me.channelNumber = 6; 1149 me.powerStateNotification = 0x24; 1150 me.deviceCapabilities = 0x21; 1151 me.reserved = 0; 1152 me.entityID = 0x2E; 1153 me.entityInstance = 2; 1154 me.oem = 0; 1155 me.typeLengthCode = 0xCB; 1156 std::string meName = "Mgmt Engine"; 1157 std::copy(meName.begin(), meName.end(), me.name); 1158 uint8_t* mePtr = reinterpret_cast<uint8_t*>(&me); 1159 resp.insert(resp.end(), mePtr, mePtr + sizeof(Type12Record)); 1160 } 1161 else 1162 { 1163 throw std::runtime_error("getType12SDRs:: Illegal index " + 1164 std::to_string(index)); 1165 } 1166 1167 return resp; 1168 } 1169 1170 void registerStorageFunctions() 1171 { 1172 // <Get FRU Inventory Area Info> 1173 ipmi::registerHandler(ipmi::prioOemBase, ipmi::netFnStorage, 1174 ipmi::storage::cmdGetFruInventoryAreaInfo, 1175 ipmi::Privilege::User, ipmiStorageGetFruInvAreaInfo); 1176 // <READ FRU Data> 1177 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage, 1178 ipmi::storage::cmdReadFruData, ipmi::Privilege::User, 1179 ipmiStorageReadFruData); 1180 1181 // <WRITE FRU Data> 1182 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage, 1183 ipmi::storage::cmdWriteFruData, 1184 ipmi::Privilege::Operator, ipmiStorageWriteFruData); 1185 1186 // <Get SEL Info> 1187 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage, 1188 ipmi::storage::cmdGetSelInfo, ipmi::Privilege::User, 1189 ipmiStorageGetSELInfo); 1190 1191 // <Get SEL Entry> 1192 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage, 1193 ipmi::storage::cmdGetSelEntry, ipmi::Privilege::User, 1194 ipmiStorageGetSELEntry); 1195 1196 // <Add SEL Entry> 1197 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage, 1198 ipmi::storage::cmdAddSelEntry, 1199 ipmi::Privilege::Operator, ipmiStorageAddSELEntry); 1200 1201 // <Clear SEL> 1202 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage, 1203 ipmi::storage::cmdClearSel, ipmi::Privilege::Operator, 1204 ipmiStorageClearSEL); 1205 1206 // <Get SEL Time> 1207 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage, 1208 ipmi::storage::cmdGetSelTime, ipmi::Privilege::User, 1209 ipmiStorageGetSELTime); 1210 1211 // <Set SEL Time> 1212 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage, 1213 ipmi::storage::cmdSetSelTime, 1214 ipmi::Privilege::Operator, ipmiStorageSetSELTime); 1215 } 1216 } // namespace storage 1217 } // namespace ipmi 1218