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