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