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