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