1 #include "config.h"
2
3 #include "fruread.hpp"
4 #include "read_fru_data.hpp"
5 #include "selutility.hpp"
6 #include "sensorhandler.hpp"
7 #include "storageaddsel.hpp"
8
9 #include <arpa/inet.h>
10 #include <systemd/sd-bus.h>
11
12 #include <ipmid/api.hpp>
13 #include <ipmid/entity_map_json.hpp>
14 #include <ipmid/utils.hpp>
15 #include <phosphor-logging/elog-errors.hpp>
16 #include <phosphor-logging/elog.hpp>
17 #include <phosphor-logging/lg2.hpp>
18 #include <sdbusplus/server.hpp>
19 #include <xyz/openbmc_project/Common/error.hpp>
20 #include <xyz/openbmc_project/Logging/SEL/error.hpp>
21
22 #include <algorithm>
23 #include <chrono>
24 #include <cstdio>
25 #include <cstring>
26 #include <filesystem>
27 #include <optional>
28 #include <string>
29 #include <variant>
30
31 void registerNetFnStorageFunctions() __attribute__((constructor));
32
33 unsigned int g_sel_time = 0xFFFFFFFF;
34 namespace ipmi
35 {
36 namespace sensor
37 {
38 extern const IdInfoMap sensors;
39 } // namespace sensor
40 } // namespace ipmi
41 extern const ipmi::sensor::InvObjectIDMap invSensors;
42 extern const FruMap frus;
43 constexpr uint8_t eventDataSize = 3;
44 namespace
45 {
46 constexpr auto SystemdTimeService = "org.freedesktop.timedate1";
47 constexpr auto SystemdTimePath = "/org/freedesktop/timedate1";
48 constexpr auto SystemdTimeInterface = "org.freedesktop.timedate1";
49
50 constexpr auto TIME_INTERFACE = "xyz.openbmc_project.Time.EpochTime";
51 constexpr auto BMC_TIME_PATH = "/xyz/openbmc_project/time/bmc";
52 constexpr auto DBUS_PROPERTIES = "org.freedesktop.DBus.Properties";
53 constexpr auto PROPERTY_ELAPSED = "Elapsed";
54 } // namespace
55
56 using InternalFailure =
57 sdbusplus::error::xyz::openbmc_project::common::InternalFailure;
58 using namespace phosphor::logging;
59 using namespace ipmi::fru;
60 using namespace xyz::openbmc_project::logging::sel;
61 using SELCreated =
62 sdbusplus::error::xyz::openbmc_project::logging::sel::Created;
63
64 using SELRecordID = uint16_t;
65 using SELEntry = ipmi::sel::SELEventRecordFormat;
66 using SELCacheMap = std::map<SELRecordID, SELEntry>;
67
68 SELCacheMap selCacheMap __attribute__((init_priority(101)));
69 bool selCacheMapInitialized;
70 std::unique_ptr<sdbusplus::bus::match_t> selAddedMatch
71 __attribute__((init_priority(101)));
72 std::unique_ptr<sdbusplus::bus::match_t> selRemovedMatch
73 __attribute__((init_priority(101)));
74 std::unique_ptr<sdbusplus::bus::match_t> selUpdatedMatch
75 __attribute__((init_priority(101)));
76
getLoggingId(const std::string & p)77 static inline uint16_t getLoggingId(const std::string& p)
78 {
79 namespace fs = std::filesystem;
80 fs::path entryPath(p);
81 return std::stoul(entryPath.filename().string());
82 }
83
getLoggingObjPath(uint16_t id)84 static inline std::string getLoggingObjPath(uint16_t id)
85 {
86 return std::string(ipmi::sel::logBasePath) + "/" + std::to_string(id);
87 }
88
parseLoggingEntry(const std::string & p)89 std::optional<std::pair<uint16_t, SELEntry>> parseLoggingEntry(
90 const std::string& p)
91 {
92 try
93 {
94 auto id = getLoggingId(p);
95 ipmi::sel::GetSELEntryResponse record{};
96 record = ipmi::sel::convertLogEntrytoSEL(p);
97 return std::pair<uint16_t, SELEntry>({id, std::move(record.event)});
98 }
99 catch (const std::exception& e)
100 {
101 fprintf(stderr, "Failed to convert %s to SEL: %s\n", p.c_str(),
102 e.what());
103 }
104 return std::nullopt;
105 }
106
selAddedCallback(sdbusplus::message_t & m)107 static void selAddedCallback(sdbusplus::message_t& m)
108 {
109 sdbusplus::message::object_path objPath;
110 try
111 {
112 m.read(objPath);
113 }
114 catch (const sdbusplus::exception_t& e)
115 {
116 lg2::error("Failed to read object path");
117 return;
118 }
119 std::string p = objPath;
120 auto entry = parseLoggingEntry(p);
121 if (entry)
122 {
123 selCacheMap.insert(std::move(*entry));
124 }
125 }
126
selRemovedCallback(sdbusplus::message_t & m)127 static void selRemovedCallback(sdbusplus::message_t& m)
128 {
129 sdbusplus::message::object_path objPath;
130 try
131 {
132 m.read(objPath);
133 }
134 catch (const sdbusplus::exception_t& e)
135 {
136 lg2::error("Failed to read object path");
137 }
138 try
139 {
140 std::string p = objPath;
141 selCacheMap.erase(getLoggingId(p));
142 }
143 catch (const std::invalid_argument& e)
144 {
145 lg2::error("Invalid logging entry ID");
146 }
147 }
148
selUpdatedCallback(sdbusplus::message_t & m)149 static void selUpdatedCallback(sdbusplus::message_t& m)
150 {
151 std::string p = m.get_path();
152 auto entry = parseLoggingEntry(p);
153 if (entry)
154 {
155 selCacheMap.insert_or_assign(entry->first, std::move(entry->second));
156 }
157 }
158
registerSelCallbackHandler()159 void registerSelCallbackHandler()
160 {
161 using namespace sdbusplus::bus::match::rules;
162 sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
163 if (!selAddedMatch)
164 {
165 selAddedMatch = std::make_unique<sdbusplus::bus::match_t>(
166 bus, interfacesAdded(ipmi::sel::logWatchPath),
167 std::bind(selAddedCallback, std::placeholders::_1));
168 }
169 if (!selRemovedMatch)
170 {
171 selRemovedMatch = std::make_unique<sdbusplus::bus::match_t>(
172 bus, interfacesRemoved(ipmi::sel::logWatchPath),
173 std::bind(selRemovedCallback, std::placeholders::_1));
174 }
175 if (!selUpdatedMatch)
176 {
177 selUpdatedMatch = std::make_unique<sdbusplus::bus::match_t>(
178 bus,
179 type::signal() + member("PropertiesChanged"s) +
180 interface("org.freedesktop.DBus.Properties"s) +
181 argN(0, ipmi::sel::logEntryIntf),
182 std::bind(selUpdatedCallback, std::placeholders::_1));
183 }
184 }
185
initSELCache()186 void initSELCache()
187 {
188 registerSelCallbackHandler();
189 ipmi::sel::ObjectPaths paths;
190 try
191 {
192 ipmi::sel::readLoggingObjectPaths(paths);
193 }
194 catch (const sdbusplus::exception_t& e)
195 {
196 lg2::error("Failed to get logging object paths");
197 return;
198 }
199 for (const auto& p : paths)
200 {
201 auto entry = parseLoggingEntry(p);
202 if (entry)
203 {
204 selCacheMap.insert(std::move(*entry));
205 }
206 }
207 selCacheMapInitialized = true;
208 }
209
210 /**
211 * @enum Device access mode
212 */
213 enum class AccessMode
214 {
215 bytes, ///< Device is accessed by bytes
216 words ///< Device is accessed by words
217 };
218
219 /** @brief implements the get SEL Info command
220 * @returns IPMI completion code plus response data
221 * - selVersion - SEL revision
222 * - entries - Number of log entries in SEL.
223 * - freeSpace - Free Space in bytes.
224 * - addTimeStamp - Most recent addition timestamp
225 * - eraseTimeStamp - Most recent erase timestamp
226 * - operationSupport - Reserve & Delete SEL operations supported
227 */
228
229 ipmi::RspType<uint8_t, // SEL revision.
230 uint16_t, // number of log entries in SEL.
231 uint16_t, // free Space in bytes.
232 uint32_t, // most recent addition timestamp
233 uint32_t, // most recent erase timestamp.
234
235 bool, // SEL allocation info supported
236 bool, // reserve SEL supported
237 bool, // partial Add SEL Entry supported
238 bool, // delete SEL supported
239 uint3_t, // reserved
240 bool // overflow flag
241 >
ipmiStorageGetSelInfo()242 ipmiStorageGetSelInfo()
243 {
244 uint16_t entries = 0;
245 // Most recent addition timestamp.
246 uint32_t addTimeStamp = ipmi::sel::invalidTimeStamp;
247
248 if (!selCacheMapInitialized)
249 {
250 // In case the initSELCache() fails, try it again
251 initSELCache();
252 }
253 if (!selCacheMap.empty())
254 {
255 entries = static_cast<uint16_t>(selCacheMap.size());
256
257 try
258 {
259 auto objPath = getLoggingObjPath(selCacheMap.rbegin()->first);
260 addTimeStamp = static_cast<uint32_t>(
261 (ipmi::sel::getEntryTimeStamp(objPath).count()));
262 }
263 catch (const InternalFailure& e)
264 {}
265 catch (const std::runtime_error& e)
266 {
267 lg2::error("runtime error: {ERROR}", "ERROR", e);
268 }
269 }
270
271 constexpr uint8_t selVersion = ipmi::sel::selVersion;
272 constexpr uint16_t freeSpace = 0xFFFF;
273 constexpr uint32_t eraseTimeStamp = ipmi::sel::invalidTimeStamp;
274 constexpr uint3_t reserved{0};
275
276 return ipmi::responseSuccess(
277 selVersion, entries, freeSpace, addTimeStamp, eraseTimeStamp,
278 ipmi::sel::operationSupport::getSelAllocationInfo,
279 ipmi::sel::operationSupport::reserveSel,
280 ipmi::sel::operationSupport::partialAddSelEntry,
281 ipmi::sel::operationSupport::deleteSel, reserved,
282 ipmi::sel::operationSupport::overflow);
283 }
284
getSELEntry(ipmi_netfn_t,ipmi_cmd_t,ipmi_request_t request,ipmi_response_t response,ipmi_data_len_t data_len,ipmi_context_t)285 ipmi_ret_t getSELEntry(ipmi_netfn_t, ipmi_cmd_t, ipmi_request_t request,
286 ipmi_response_t response, ipmi_data_len_t data_len,
287 ipmi_context_t)
288 {
289 if (*data_len != sizeof(ipmi::sel::GetSELEntryRequest))
290 {
291 *data_len = 0;
292 return IPMI_CC_REQ_DATA_LEN_INVALID;
293 }
294
295 auto requestData =
296 reinterpret_cast<const ipmi::sel::GetSELEntryRequest*>(request);
297
298 if (requestData->reservationID != 0)
299 {
300 if (!checkSELReservation(requestData->reservationID))
301 {
302 *data_len = 0;
303 return IPMI_CC_INVALID_RESERVATION_ID;
304 }
305 }
306
307 if (!selCacheMapInitialized)
308 {
309 // In case the initSELCache() fails, try it again
310 initSELCache();
311 }
312
313 if (selCacheMap.empty())
314 {
315 *data_len = 0;
316 return IPMI_CC_SENSOR_INVALID;
317 }
318
319 SELCacheMap::const_iterator iter;
320
321 // Check for the requested SEL Entry.
322 if (requestData->selRecordID == ipmi::sel::firstEntry)
323 {
324 iter = selCacheMap.begin();
325 }
326 else if (requestData->selRecordID == ipmi::sel::lastEntry)
327 {
328 if (selCacheMap.size() > 1)
329 {
330 iter = selCacheMap.end();
331 --iter;
332 }
333 else
334 {
335 // Only one entry exists, return the first
336 iter = selCacheMap.begin();
337 }
338 }
339 else
340 {
341 iter = selCacheMap.find(requestData->selRecordID);
342 if (iter == selCacheMap.end())
343 {
344 *data_len = 0;
345 return IPMI_CC_SENSOR_INVALID;
346 }
347 }
348
349 ipmi::sel::GetSELEntryResponse record{0, iter->second};
350 // Identify the next SEL record ID
351 ++iter;
352 if (iter == selCacheMap.end())
353 {
354 record.nextRecordID = ipmi::sel::lastEntry;
355 }
356 else
357 {
358 record.nextRecordID = iter->first;
359 }
360
361 if (requestData->readLength == ipmi::sel::entireRecord)
362 {
363 std::memcpy(response, &record, sizeof(record));
364 *data_len = sizeof(record);
365 }
366 else
367 {
368 if (requestData->offset >= ipmi::sel::selRecordSize ||
369 requestData->readLength > ipmi::sel::selRecordSize)
370 {
371 *data_len = 0;
372 return IPMI_CC_INVALID_FIELD_REQUEST;
373 }
374
375 auto diff = ipmi::sel::selRecordSize - requestData->offset;
376 auto readLength =
377 std::min(diff, static_cast<int>(requestData->readLength));
378
379 std::memcpy(response, &record.nextRecordID,
380 sizeof(record.nextRecordID));
381 std::memcpy(static_cast<uint8_t*>(response) +
382 sizeof(record.nextRecordID),
383 &record.event.eventRecord.recordID + requestData->offset,
384 readLength);
385 *data_len = sizeof(record.nextRecordID) + readLength;
386 }
387
388 return IPMI_CC_OK;
389 }
390
391 /** @brief implements the delete SEL entry command
392 * @request
393 * - reservationID; // reservation ID.
394 * - selRecordID; // SEL record ID.
395 *
396 * @returns ipmi completion code plus response data
397 * - Record ID of the deleted record
398 */
399 ipmi::RspType<uint16_t // deleted record ID
400 >
deleteSELEntry(uint16_t reservationID,uint16_t selRecordID)401 deleteSELEntry(uint16_t reservationID, uint16_t selRecordID)
402 {
403 namespace fs = std::filesystem;
404
405 if (!checkSELReservation(reservationID))
406 {
407 return ipmi::responseInvalidReservationId();
408 }
409
410 // Per the IPMI spec, need to cancel the reservation when a SEL entry is
411 // deleted
412 cancelSELReservation();
413
414 if (!selCacheMapInitialized)
415 {
416 // In case the initSELCache() fails, try it again
417 initSELCache();
418 }
419
420 if (selCacheMap.empty())
421 {
422 return ipmi::responseSensorInvalid();
423 }
424
425 SELCacheMap::const_iterator iter;
426 uint16_t delRecordID = 0;
427
428 if (selRecordID == ipmi::sel::firstEntry)
429 {
430 delRecordID = selCacheMap.begin()->first;
431 }
432 else if (selRecordID == ipmi::sel::lastEntry)
433 {
434 delRecordID = selCacheMap.rbegin()->first;
435 }
436 else
437 {
438 delRecordID = selRecordID;
439 }
440
441 iter = selCacheMap.find(delRecordID);
442 if (iter == selCacheMap.end())
443 {
444 return ipmi::responseSensorInvalid();
445 }
446
447 sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
448 std::string service;
449
450 auto objPath = getLoggingObjPath(iter->first);
451 try
452 {
453 service = ipmi::getService(bus, ipmi::sel::logDeleteIntf, objPath);
454 }
455 catch (const std::runtime_error& e)
456 {
457 lg2::error("runtime error: {ERROR}", "ERROR", e);
458 return ipmi::responseUnspecifiedError();
459 }
460
461 auto methodCall = bus.new_method_call(service.c_str(), objPath.c_str(),
462 ipmi::sel::logDeleteIntf, "Delete");
463 try
464 {
465 auto reply = bus.call(methodCall);
466 }
467 catch (const std::exception& e)
468 {
469 return ipmi::responseUnspecifiedError();
470 }
471
472 return ipmi::responseSuccess(delRecordID);
473 }
474
475 /** @brief implements the Clear SEL command
476 * @request
477 * - reservationID // Reservation ID.
478 * - clr // char array { 'C'(0x43h), 'L'(0x4Ch), 'R'(0x52h) }
479 * - eraseOperation; // requested operation.
480 *
481 * @returns ipmi completion code plus response data
482 * - erase status
483 */
484
485 ipmi::RspType<uint8_t // erase status
486 >
clearSEL(uint16_t reservationID,const std::array<char,3> & clr,uint8_t eraseOperation)487 clearSEL(uint16_t reservationID, const std::array<char, 3>& clr,
488 uint8_t eraseOperation)
489 {
490 static constexpr std::array<char, 3> clrOk = {'C', 'L', 'R'};
491 if (clr != clrOk)
492 {
493 return ipmi::responseInvalidFieldRequest();
494 }
495
496 if (!checkSELReservation(reservationID))
497 {
498 return ipmi::responseInvalidReservationId();
499 }
500
501 /*
502 * Erasure status cannot be fetched from DBUS, so always return erasure
503 * status as `erase completed`.
504 */
505 if (eraseOperation == ipmi::sel::getEraseStatus)
506 {
507 return ipmi::responseSuccess(
508 static_cast<uint8_t>(ipmi::sel::eraseComplete));
509 }
510
511 // Check that initiate erase is correct
512 if (eraseOperation != ipmi::sel::initiateErase)
513 {
514 return ipmi::responseInvalidFieldRequest();
515 }
516
517 // Per the IPMI spec, need to cancel any reservation when the SEL is cleared
518 cancelSELReservation();
519
520 sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
521 auto service = ipmi::getService(bus, ipmi::sel::logIntf, ipmi::sel::logObj);
522 auto method =
523 bus.new_method_call(service.c_str(), ipmi::sel::logObj,
524 ipmi::sel::logIntf, ipmi::sel::logDeleteAllMethod);
525 try
526 {
527 bus.call_noreply(method);
528 }
529 catch (const sdbusplus::exception_t& e)
530 {
531 lg2::error("Error eraseAll: {ERROR}", "ERROR", e);
532 return ipmi::responseUnspecifiedError();
533 }
534
535 return ipmi::responseSuccess(
536 static_cast<uint8_t>(ipmi::sel::eraseComplete));
537 }
538
539 /** @brief implements the get SEL time command
540 * @returns IPMI completion code plus response data
541 * -current time
542 */
543 ipmi::RspType<uint32_t> // current time
ipmiStorageGetSelTime()544 ipmiStorageGetSelTime()
545 {
546 using namespace std::chrono;
547 uint64_t bmc_time_usec = 0;
548 std::stringstream bmcTime;
549
550 try
551 {
552 sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
553 auto service = ipmi::getService(bus, TIME_INTERFACE, BMC_TIME_PATH);
554 auto propValue = ipmi::getDbusProperty(
555 bus, service, BMC_TIME_PATH, TIME_INTERFACE, PROPERTY_ELAPSED);
556 bmc_time_usec = std::get<uint64_t>(propValue);
557 }
558 catch (const InternalFailure& e)
559 {
560 lg2::error("Internal Failure: {ERROR}", "ERROR", e);
561 return ipmi::responseUnspecifiedError();
562 }
563 catch (const std::exception& e)
564 {
565 lg2::error("exception message: {ERROR}", "ERROR", e);
566 return ipmi::responseUnspecifiedError();
567 }
568
569 lg2::debug("BMC time: {BMC_TIME}", "BMC_TIME",
570 duration_cast<seconds>(microseconds(bmc_time_usec)).count());
571
572 // Time is really long int but IPMI wants just uint32. This works okay until
573 // the number of seconds since 1970 overflows uint32 size.. Still a whole
574 // lot of time here to even think about that.
575 return ipmi::responseSuccess(
576 duration_cast<seconds>(microseconds(bmc_time_usec)).count());
577 }
578
579 /** @brief implements the set SEL time command
580 * @param selDeviceTime - epoch time
581 * -local time as the number of seconds from 00:00:00, January 1, 1970
582 * @returns IPMI completion code
583 */
ipmiStorageSetSelTime(uint32_t selDeviceTime)584 ipmi::RspType<> ipmiStorageSetSelTime(uint32_t selDeviceTime)
585 {
586 using namespace std::chrono;
587 microseconds usec{seconds(selDeviceTime)};
588
589 try
590 {
591 sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
592 bool ntp = std::get<bool>(
593 ipmi::getDbusProperty(bus, SystemdTimeService, SystemdTimePath,
594 SystemdTimeInterface, "NTP"));
595 if (ntp)
596 {
597 return ipmi::responseCommandNotAvailable();
598 }
599
600 auto service = ipmi::getService(bus, TIME_INTERFACE, BMC_TIME_PATH);
601 std::variant<uint64_t> value{(uint64_t)usec.count()};
602
603 // Set bmc time
604 auto method = bus.new_method_call(service.c_str(), BMC_TIME_PATH,
605 DBUS_PROPERTIES, "Set");
606
607 method.append(TIME_INTERFACE, PROPERTY_ELAPSED, value);
608 auto reply = bus.call(method);
609 }
610 catch (const InternalFailure& e)
611 {
612 lg2::error("Internal Failure: {ERROR}", "ERROR", e);
613 return ipmi::responseUnspecifiedError();
614 }
615 catch (const std::exception& e)
616 {
617 lg2::error("exception message: {ERROR}", "ERROR", e);
618 return ipmi::responseUnspecifiedError();
619 }
620
621 return ipmi::responseSuccess();
622 }
623
624 /** @brief implements the get SEL timezone command
625 * @returns IPMI completion code plus response data
626 * -current timezone
627 */
ipmiStorageGetSelTimeUtcOffset()628 ipmi::RspType<int16_t> ipmiStorageGetSelTimeUtcOffset()
629 {
630 time_t timep;
631 struct tm* gmTime;
632 struct tm* localTime;
633
634 time(&timep);
635 localTime = localtime(&timep);
636 auto validLocalTime = mktime(localTime);
637 gmTime = gmtime(&timep);
638 auto validGmTime = mktime(gmTime);
639 auto timeEquation = (validLocalTime - validGmTime) / 60;
640
641 return ipmi::responseSuccess(timeEquation);
642 }
643
644 /** @brief implements the reserve SEL command
645 * @returns IPMI completion code plus response data
646 * - SEL reservation ID.
647 */
ipmiStorageReserveSel()648 ipmi::RspType<uint16_t> ipmiStorageReserveSel()
649 {
650 return ipmi::responseSuccess(reserveSel());
651 }
652
653 /** @brief implements the Add SEL entry command
654 * @request
655 *
656 * - recordID ID used for SEL Record access
657 * - recordType Record Type
658 * - timeStamp Time when event was logged. LS byte first
659 * - generatorID software ID if event was generated from
660 * system software
661 * - evmRev event message format version
662 * - sensorType sensor type code for service that generated
663 * the event
664 * - sensorNumber number of sensors that generated the event
665 * - eventDir event dir
666 * - eventData event data field contents
667 *
668 * @returns ipmi completion code plus response data
669 * - RecordID of the Added SEL entry
670 */
671 ipmi::RspType<uint16_t // recordID of the Added SEL entry
672 >
ipmiStorageAddSEL(uint16_t recordID,uint8_t recordType,uint32_t timeStamp,uint16_t generatorID,uint8_t evmRev,uint8_t sensorType,uint8_t sensorNumber,uint8_t eventDir,std::array<uint8_t,eventDataSize> eventData)673 ipmiStorageAddSEL(uint16_t recordID, uint8_t recordType,
674 [[maybe_unused]] uint32_t timeStamp, uint16_t generatorID,
675 [[maybe_unused]] uint8_t evmRev,
676 [[maybe_unused]] uint8_t sensorType, uint8_t sensorNumber,
677 uint8_t eventDir,
678 std::array<uint8_t, eventDataSize> eventData)
679 {
680 std::string objpath;
681 static constexpr auto systemRecordType = 0x02;
682 #ifdef OPEN_POWER_SUPPORT
683 // Hostboot sends SEL with OEM record type 0xDE to indicate that there is
684 // a maintenance procedure associated with eSEL record.
685 static constexpr auto procedureType = 0xDE;
686 #endif
687 cancelSELReservation();
688 if (recordType == systemRecordType)
689 {
690 for (const auto& it : invSensors)
691 {
692 if (it.second.sensorID == sensorNumber)
693 {
694 objpath = it.first;
695 break;
696 }
697 }
698 auto selDataStr = ipmi::sel::toHexStr(eventData);
699
700 bool assert = (eventDir & 0x80) ? false : true;
701
702 recordID = report<SELCreated>(
703 Created::RECORD_TYPE(recordType),
704 Created::GENERATOR_ID(generatorID),
705 Created::SENSOR_DATA(selDataStr.c_str()),
706 Created::EVENT_DIR(assert), Created::SENSOR_PATH(objpath.c_str()));
707 }
708 #ifdef OPEN_POWER_SUPPORT
709 else if (recordType == procedureType)
710 {
711 // In the OEM record type 0xDE, byte 11 in the SEL record indicate the
712 // procedure number.
713 createProcedureLogEntry(sensorType);
714 }
715 #endif
716
717 return ipmi::responseSuccess(recordID);
718 }
719
isFruPresent(ipmi::Context::ptr & ctx,const std::string & fruPath)720 bool isFruPresent(ipmi::Context::ptr& ctx, const std::string& fruPath)
721 {
722 using namespace ipmi::fru;
723
724 std::string service;
725 boost::system::error_code ec =
726 getService(ctx, invItemInterface, invObjPath + fruPath, service);
727 if (!ec)
728 {
729 bool result;
730 ec = ipmi::getDbusProperty(ctx, service, invObjPath + fruPath,
731 invItemInterface, itemPresentProp, result);
732 if (!ec)
733 {
734 return result;
735 }
736 }
737
738 ipmi::ObjectValueTree managedObjects;
739 ec = getManagedObjects(ctx, "xyz.openbmc_project.EntityManager",
740 "/xyz/openbmc_project/inventory", managedObjects);
741 if (!ec)
742 {
743 auto connection = managedObjects.find(fruPath);
744 if (connection != managedObjects.end())
745 {
746 return true;
747 }
748 }
749
750 return false;
751 }
752
753 /** @brief implements the get FRU Inventory Area Info command
754 *
755 * @returns IPMI completion code plus response data
756 * - FRU Inventory area size in bytes,
757 * - access bit
758 **/
759 ipmi::RspType<uint16_t, // FRU Inventory area size in bytes,
760 uint8_t // access size (bytes / words)
761 >
ipmiStorageGetFruInvAreaInfo(ipmi::Context::ptr ctx,uint8_t fruID)762 ipmiStorageGetFruInvAreaInfo(ipmi::Context::ptr ctx, uint8_t fruID)
763 {
764 auto iter = frus.find(fruID);
765 if (iter == frus.end())
766 {
767 return ipmi::responseSensorInvalid();
768 }
769
770 auto path = iter->second[0].path;
771 if (!isFruPresent(ctx, path))
772 {
773 return ipmi::responseSensorInvalid();
774 }
775
776 try
777 {
778 return ipmi::responseSuccess(
779 static_cast<uint16_t>(getFruAreaData(fruID).size()),
780 static_cast<uint8_t>(AccessMode::bytes));
781 }
782 catch (const InternalFailure& e)
783 {
784 lg2::error("Internal Failure: {ERROR}", "ERROR", e);
785 return ipmi::responseUnspecifiedError();
786 }
787 }
788
789 /**@brief implements the Read FRU Data command
790 * @param fruDeviceId - FRU device ID. FFh = reserved
791 * @param offset - FRU inventory offset to read
792 * @param readCount - count to read
793 *
794 * @return IPMI completion code plus response data
795 * - returnCount - response data count.
796 * - data - response data
797 */
798 ipmi::RspType<uint8_t, // count returned
799 std::vector<uint8_t>> // FRU data
ipmiStorageReadFruData(uint8_t fruDeviceId,uint16_t offset,uint8_t readCount)800 ipmiStorageReadFruData(uint8_t fruDeviceId, uint16_t offset,
801 uint8_t readCount)
802 {
803 if (fruDeviceId == 0xFF)
804 {
805 return ipmi::responseInvalidFieldRequest();
806 }
807
808 auto iter = frus.find(fruDeviceId);
809 if (iter == frus.end())
810 {
811 return ipmi::responseSensorInvalid();
812 }
813
814 try
815 {
816 const auto& fruArea = getFruAreaData(fruDeviceId);
817 auto size = fruArea.size();
818
819 if (offset >= size)
820 {
821 return ipmi::responseParmOutOfRange();
822 }
823
824 // Write the count of response data.
825 uint8_t returnCount;
826 if ((offset + readCount) <= size)
827 {
828 returnCount = readCount;
829 }
830 else
831 {
832 returnCount = size - offset;
833 }
834
835 std::vector<uint8_t> fruData((fruArea.begin() + offset),
836 (fruArea.begin() + offset + returnCount));
837
838 return ipmi::responseSuccess(returnCount, fruData);
839 }
840 catch (const InternalFailure& e)
841 {
842 lg2::error("Internal Failure: {ERROR}", "ERROR", e);
843 return ipmi::responseUnspecifiedError();
844 }
845 }
846
847 ipmi::RspType<uint8_t, // SDR version
848 uint16_t, // record count LS first
849 uint16_t, // free space in bytes, LS first
850 uint32_t, // addition timestamp LS first
851 uint32_t, // deletion timestamp LS first
852 uint8_t> // operation Support
ipmiGetRepositoryInfo()853 ipmiGetRepositoryInfo()
854 {
855 constexpr uint8_t sdrVersion = 0x51;
856 constexpr uint16_t freeSpace = 0xFFFF;
857 constexpr uint32_t additionTimestamp = 0x0;
858 constexpr uint32_t deletionTimestamp = 0x0;
859 constexpr uint8_t operationSupport = 0;
860
861 // Get SDR count. This returns the total number of SDRs in the device.
862 const auto& entityRecords =
863 ipmi::sensor::EntityInfoMapContainer::getContainer()
864 ->getIpmiEntityRecords();
865 uint16_t records =
866 ipmi::sensor::sensors.size() + frus.size() + entityRecords.size();
867
868 return ipmi::responseSuccess(sdrVersion, records, freeSpace,
869 additionTimestamp, deletionTimestamp,
870 operationSupport);
871 }
872
registerNetFnStorageFunctions()873 void registerNetFnStorageFunctions()
874 {
875 selCacheMapInitialized = false;
876 initSELCache();
877 // Handlers with dbus-sdr handler implementation.
878 // Do not register the hander if it dynamic sensors stack is used.
879
880 #ifndef FEATURE_DYNAMIC_SENSORS
881
882 #ifndef FEATURE_DYNAMIC_STORAGES_ONLY
883 // <Get SEL Info>
884 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
885 ipmi::storage::cmdGetSelInfo, ipmi::Privilege::User,
886 ipmiStorageGetSelInfo);
887
888 // <Get SEL Timezone>
889 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
890 ipmi::storage::cmdGetSelTimeUtcOffset,
891 ipmi::Privilege::User,
892 ipmiStorageGetSelTimeUtcOffset);
893
894 // <Get SEL Entry>
895 ipmi_register_callback(NETFUN_STORAGE, ipmi::storage::cmdGetSelEntry, NULL,
896 getSELEntry, PRIVILEGE_USER);
897
898 // <Delete SEL Entry>
899 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
900 ipmi::storage::cmdDeleteSelEntry,
901 ipmi::Privilege::Operator, deleteSELEntry);
902
903 // <Add SEL Entry>
904 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
905 ipmi::storage::cmdAddSelEntry,
906 ipmi::Privilege::Operator, ipmiStorageAddSEL);
907
908 // <Clear SEL>
909 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
910 ipmi::storage::cmdClearSel, ipmi::Privilege::Operator,
911 clearSEL);
912
913 // <Get FRU Inventory Area Info>
914 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
915 ipmi::storage::cmdGetFruInventoryAreaInfo,
916 ipmi::Privilege::User, ipmiStorageGetFruInvAreaInfo);
917
918 // <READ FRU Data>
919 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
920 ipmi::storage::cmdReadFruData,
921 ipmi::Privilege::Operator, ipmiStorageReadFruData);
922
923 #endif // FEATURE_DYNAMIC_STORAGES_ONLY
924
925 // <Get Repository Info>
926 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
927 ipmi::storage::cmdGetSdrRepositoryInfo,
928 ipmi::Privilege::User, ipmiGetRepositoryInfo);
929
930 // <Reserve SDR Repository>
931 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
932 ipmi::storage::cmdReserveSdrRepository,
933 ipmi::Privilege::User, ipmiSensorReserveSdr);
934
935 // <Get SDR>
936 ipmi_register_callback(NETFUN_STORAGE, ipmi::storage::cmdGetSdr, nullptr,
937 ipmi_sen_get_sdr, PRIVILEGE_USER);
938
939 #endif
940
941 // Common Handers used by both implementation.
942
943 // <Reserve SEL>
944 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
945 ipmi::storage::cmdReserveSel, ipmi::Privilege::User,
946 ipmiStorageReserveSel);
947
948 // <Get SEL Time>
949 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
950 ipmi::storage::cmdGetSelTime, ipmi::Privilege::User,
951 ipmiStorageGetSelTime);
952
953 // <Set SEL Time>
954 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
955 ipmi::storage::cmdSetSelTime,
956 ipmi::Privilege::Operator, ipmiStorageSetSelTime);
957
958 ipmi::fru::registerCallbackHandler();
959 return;
960 }
961