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 uint16_t nextRecordID = record.nextRecordID;
380 std::memcpy(response, &nextRecordID, sizeof(nextRecordID));
381
382 const ipmi::sel::SELEventRecordFormat* evt = &record.event;
383 std::memcpy(static_cast<uint8_t*>(response) + sizeof(nextRecordID),
384 reinterpret_cast<const uint8_t*>(evt) + requestData->offset,
385 readLength);
386 *data_len = sizeof(nextRecordID) + readLength;
387 }
388
389 return IPMI_CC_OK;
390 }
391
392 /** @brief implements the delete SEL entry command
393 * @request
394 * - reservationID; // reservation ID.
395 * - selRecordID; // SEL record ID.
396 *
397 * @returns ipmi completion code plus response data
398 * - Record ID of the deleted record
399 */
400 ipmi::RspType<uint16_t // deleted record ID
401 >
deleteSELEntry(uint16_t reservationID,uint16_t selRecordID)402 deleteSELEntry(uint16_t reservationID, uint16_t selRecordID)
403 {
404 namespace fs = std::filesystem;
405
406 if (!checkSELReservation(reservationID))
407 {
408 return ipmi::responseInvalidReservationId();
409 }
410
411 // Per the IPMI spec, need to cancel the reservation when a SEL entry is
412 // deleted
413 cancelSELReservation();
414
415 if (!selCacheMapInitialized)
416 {
417 // In case the initSELCache() fails, try it again
418 initSELCache();
419 }
420
421 if (selCacheMap.empty())
422 {
423 return ipmi::responseSensorInvalid();
424 }
425
426 SELCacheMap::const_iterator iter;
427 uint16_t delRecordID = 0;
428
429 if (selRecordID == ipmi::sel::firstEntry)
430 {
431 delRecordID = selCacheMap.begin()->first;
432 }
433 else if (selRecordID == ipmi::sel::lastEntry)
434 {
435 delRecordID = selCacheMap.rbegin()->first;
436 }
437 else
438 {
439 delRecordID = selRecordID;
440 }
441
442 iter = selCacheMap.find(delRecordID);
443 if (iter == selCacheMap.end())
444 {
445 return ipmi::responseSensorInvalid();
446 }
447
448 sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
449 std::string service;
450
451 auto objPath = getLoggingObjPath(iter->first);
452 try
453 {
454 service = ipmi::getService(bus, ipmi::sel::logDeleteIntf, objPath);
455 }
456 catch (const std::runtime_error& e)
457 {
458 lg2::error("runtime error: {ERROR}", "ERROR", e);
459 return ipmi::responseUnspecifiedError();
460 }
461
462 auto methodCall = bus.new_method_call(service.c_str(), objPath.c_str(),
463 ipmi::sel::logDeleteIntf, "Delete");
464 try
465 {
466 auto reply = bus.call(methodCall);
467 }
468 catch (const std::exception& e)
469 {
470 return ipmi::responseUnspecifiedError();
471 }
472
473 return ipmi::responseSuccess(delRecordID);
474 }
475
476 /** @brief implements the Clear SEL command
477 * @request
478 * - reservationID // Reservation ID.
479 * - clr // char array { 'C'(0x43h), 'L'(0x4Ch), 'R'(0x52h) }
480 * - eraseOperation; // requested operation.
481 *
482 * @returns ipmi completion code plus response data
483 * - erase status
484 */
485
486 ipmi::RspType<uint8_t // erase status
487 >
clearSEL(uint16_t reservationID,const std::array<char,3> & clr,uint8_t eraseOperation)488 clearSEL(uint16_t reservationID, const std::array<char, 3>& clr,
489 uint8_t eraseOperation)
490 {
491 static constexpr std::array<char, 3> clrOk = {'C', 'L', 'R'};
492 if (clr != clrOk)
493 {
494 return ipmi::responseInvalidFieldRequest();
495 }
496
497 if (!checkSELReservation(reservationID))
498 {
499 return ipmi::responseInvalidReservationId();
500 }
501
502 /*
503 * Erasure status cannot be fetched from DBUS, so always return erasure
504 * status as `erase completed`.
505 */
506 if (eraseOperation == ipmi::sel::getEraseStatus)
507 {
508 return ipmi::responseSuccess(
509 static_cast<uint8_t>(ipmi::sel::eraseComplete));
510 }
511
512 // Check that initiate erase is correct
513 if (eraseOperation != ipmi::sel::initiateErase)
514 {
515 return ipmi::responseInvalidFieldRequest();
516 }
517
518 // Per the IPMI spec, need to cancel any reservation when the SEL is cleared
519 cancelSELReservation();
520
521 sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
522 auto service = ipmi::getService(bus, ipmi::sel::logIntf, ipmi::sel::logObj);
523 auto method =
524 bus.new_method_call(service.c_str(), ipmi::sel::logObj,
525 ipmi::sel::logIntf, ipmi::sel::logDeleteAllMethod);
526 try
527 {
528 bus.call_noreply(method);
529 }
530 catch (const sdbusplus::exception_t& e)
531 {
532 lg2::error("Error eraseAll: {ERROR}", "ERROR", e);
533 return ipmi::responseUnspecifiedError();
534 }
535
536 return ipmi::responseSuccess(
537 static_cast<uint8_t>(ipmi::sel::eraseComplete));
538 }
539
540 /** @brief implements the get SEL time command
541 * @returns IPMI completion code plus response data
542 * -current time
543 */
544 ipmi::RspType<uint32_t> // current time
ipmiStorageGetSelTime()545 ipmiStorageGetSelTime()
546 {
547 using namespace std::chrono;
548 uint64_t bmc_time_usec = 0;
549 std::stringstream bmcTime;
550
551 try
552 {
553 sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
554 auto service = ipmi::getService(bus, TIME_INTERFACE, BMC_TIME_PATH);
555 auto propValue = ipmi::getDbusProperty(
556 bus, service, BMC_TIME_PATH, TIME_INTERFACE, PROPERTY_ELAPSED);
557 bmc_time_usec = std::get<uint64_t>(propValue);
558 }
559 catch (const InternalFailure& e)
560 {
561 lg2::error("Internal Failure: {ERROR}", "ERROR", e);
562 return ipmi::responseUnspecifiedError();
563 }
564 catch (const std::exception& e)
565 {
566 lg2::error("exception message: {ERROR}", "ERROR", e);
567 return ipmi::responseUnspecifiedError();
568 }
569
570 lg2::debug("BMC time: {BMC_TIME}", "BMC_TIME",
571 duration_cast<seconds>(microseconds(bmc_time_usec)).count());
572
573 // Time is really long int but IPMI wants just uint32. This works okay until
574 // the number of seconds since 1970 overflows uint32 size.. Still a whole
575 // lot of time here to even think about that.
576 return ipmi::responseSuccess(
577 duration_cast<seconds>(microseconds(bmc_time_usec)).count());
578 }
579
580 /** @brief implements the set SEL time command
581 * @param selDeviceTime - epoch time
582 * -local time as the number of seconds from 00:00:00, January 1, 1970
583 * @returns IPMI completion code
584 */
ipmiStorageSetSelTime(uint32_t selDeviceTime)585 ipmi::RspType<> ipmiStorageSetSelTime(uint32_t selDeviceTime)
586 {
587 using namespace std::chrono;
588 microseconds usec{seconds(selDeviceTime)};
589
590 try
591 {
592 sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
593 bool ntp = std::get<bool>(
594 ipmi::getDbusProperty(bus, SystemdTimeService, SystemdTimePath,
595 SystemdTimeInterface, "NTP"));
596 if (ntp)
597 {
598 return ipmi::responseCommandNotAvailable();
599 }
600
601 auto service = ipmi::getService(bus, TIME_INTERFACE, BMC_TIME_PATH);
602 std::variant<uint64_t> value{(uint64_t)usec.count()};
603
604 // Set bmc time
605 auto method = bus.new_method_call(service.c_str(), BMC_TIME_PATH,
606 DBUS_PROPERTIES, "Set");
607
608 method.append(TIME_INTERFACE, PROPERTY_ELAPSED, value);
609 auto reply = bus.call(method);
610 }
611 catch (const InternalFailure& e)
612 {
613 lg2::error("Internal Failure: {ERROR}", "ERROR", e);
614 return ipmi::responseUnspecifiedError();
615 }
616 catch (const std::exception& e)
617 {
618 lg2::error("exception message: {ERROR}", "ERROR", e);
619 return ipmi::responseUnspecifiedError();
620 }
621
622 return ipmi::responseSuccess();
623 }
624
625 /** @brief implements the get SEL timezone command
626 * @returns IPMI completion code plus response data
627 * -current timezone
628 */
ipmiStorageGetSelTimeUtcOffset()629 ipmi::RspType<int16_t> ipmiStorageGetSelTimeUtcOffset()
630 {
631 time_t timep;
632 struct tm* gmTime;
633 struct tm* localTime;
634
635 time(&timep);
636 localTime = localtime(&timep);
637 auto validLocalTime = mktime(localTime);
638 gmTime = gmtime(&timep);
639 auto validGmTime = mktime(gmTime);
640 auto timeEquation = (validLocalTime - validGmTime) / 60;
641
642 return ipmi::responseSuccess(timeEquation);
643 }
644
645 /** @brief implements the reserve SEL command
646 * @returns IPMI completion code plus response data
647 * - SEL reservation ID.
648 */
ipmiStorageReserveSel()649 ipmi::RspType<uint16_t> ipmiStorageReserveSel()
650 {
651 return ipmi::responseSuccess(reserveSel());
652 }
653
654 /** @brief implements the Add SEL entry command
655 * @request
656 *
657 * - recordID ID used for SEL Record access
658 * - recordType Record Type
659 * - timeStamp Time when event was logged. LS byte first
660 * - generatorID software ID if event was generated from
661 * system software
662 * - evmRev event message format version
663 * - sensorType sensor type code for service that generated
664 * the event
665 * - sensorNumber number of sensors that generated the event
666 * - eventDir event dir
667 * - eventData event data field contents
668 *
669 * @returns ipmi completion code plus response data
670 * - RecordID of the Added SEL entry
671 */
672 ipmi::RspType<uint16_t // recordID of the Added SEL entry
673 >
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)674 ipmiStorageAddSEL(uint16_t recordID, uint8_t recordType,
675 [[maybe_unused]] uint32_t timeStamp, uint16_t generatorID,
676 [[maybe_unused]] uint8_t evmRev,
677 [[maybe_unused]] uint8_t sensorType, uint8_t sensorNumber,
678 uint8_t eventDir,
679 std::array<uint8_t, eventDataSize> eventData)
680 {
681 std::string objpath;
682 static constexpr auto systemRecordType = 0x02;
683 #ifdef OPEN_POWER_SUPPORT
684 // Hostboot sends SEL with OEM record type 0xDE to indicate that there is
685 // a maintenance procedure associated with eSEL record.
686 static constexpr auto procedureType = 0xDE;
687 #endif
688 cancelSELReservation();
689 if (recordType == systemRecordType)
690 {
691 for (const auto& it : invSensors)
692 {
693 if (it.second.sensorID == sensorNumber)
694 {
695 objpath = it.first;
696 break;
697 }
698 }
699 auto selDataStr = ipmi::sel::toHexStr(eventData);
700
701 bool assert = (eventDir & 0x80) ? false : true;
702
703 recordID = report<SELCreated>(
704 Created::RECORD_TYPE(recordType),
705 Created::GENERATOR_ID(generatorID),
706 Created::SENSOR_DATA(selDataStr.c_str()),
707 Created::EVENT_DIR(assert), Created::SENSOR_PATH(objpath.c_str()));
708 }
709 #ifdef OPEN_POWER_SUPPORT
710 else if (recordType == procedureType)
711 {
712 // In the OEM record type 0xDE, byte 11 in the SEL record indicate the
713 // procedure number.
714 createProcedureLogEntry(sensorType);
715 }
716 #endif
717
718 return ipmi::responseSuccess(recordID);
719 }
720
isFruPresent(ipmi::Context::ptr & ctx,const std::string & fruPath)721 bool isFruPresent(ipmi::Context::ptr& ctx, const std::string& fruPath)
722 {
723 using namespace ipmi::fru;
724
725 std::string service;
726 boost::system::error_code ec =
727 getService(ctx, invItemInterface, invObjPath + fruPath, service);
728 if (!ec)
729 {
730 bool result;
731 ec = ipmi::getDbusProperty(ctx, service, invObjPath + fruPath,
732 invItemInterface, itemPresentProp, result);
733 if (!ec)
734 {
735 return result;
736 }
737 }
738
739 ipmi::ObjectValueTree managedObjects;
740 ec = getManagedObjects(ctx, "xyz.openbmc_project.EntityManager",
741 "/xyz/openbmc_project/inventory", managedObjects);
742 if (!ec)
743 {
744 auto connection = managedObjects.find(fruPath);
745 if (connection != managedObjects.end())
746 {
747 return true;
748 }
749 }
750
751 return false;
752 }
753
754 /** @brief implements the get FRU Inventory Area Info command
755 *
756 * @returns IPMI completion code plus response data
757 * - FRU Inventory area size in bytes,
758 * - access bit
759 **/
760 ipmi::RspType<uint16_t, // FRU Inventory area size in bytes,
761 uint8_t // access size (bytes / words)
762 >
ipmiStorageGetFruInvAreaInfo(ipmi::Context::ptr ctx,uint8_t fruID)763 ipmiStorageGetFruInvAreaInfo(ipmi::Context::ptr ctx, uint8_t fruID)
764 {
765 auto iter = frus.find(fruID);
766 if (iter == frus.end())
767 {
768 return ipmi::responseSensorInvalid();
769 }
770
771 auto path = iter->second[0].path;
772 if (!isFruPresent(ctx, path))
773 {
774 return ipmi::responseSensorInvalid();
775 }
776
777 try
778 {
779 return ipmi::responseSuccess(
780 static_cast<uint16_t>(getFruAreaData(fruID).size()),
781 static_cast<uint8_t>(AccessMode::bytes));
782 }
783 catch (const InternalFailure& e)
784 {
785 lg2::error("Internal Failure: {ERROR}", "ERROR", e);
786 return ipmi::responseUnspecifiedError();
787 }
788 }
789
790 /**@brief implements the Read FRU Data command
791 * @param fruDeviceId - FRU device ID. FFh = reserved
792 * @param offset - FRU inventory offset to read
793 * @param readCount - count to read
794 *
795 * @return IPMI completion code plus response data
796 * - returnCount - response data count.
797 * - data - response data
798 */
799 ipmi::RspType<uint8_t, // count returned
800 std::vector<uint8_t>> // FRU data
ipmiStorageReadFruData(uint8_t fruDeviceId,uint16_t offset,uint8_t readCount)801 ipmiStorageReadFruData(uint8_t fruDeviceId, uint16_t offset,
802 uint8_t readCount)
803 {
804 if (fruDeviceId == 0xFF)
805 {
806 return ipmi::responseInvalidFieldRequest();
807 }
808
809 auto iter = frus.find(fruDeviceId);
810 if (iter == frus.end())
811 {
812 return ipmi::responseSensorInvalid();
813 }
814
815 try
816 {
817 const auto& fruArea = getFruAreaData(fruDeviceId);
818 auto size = fruArea.size();
819
820 if (offset >= size)
821 {
822 return ipmi::responseParmOutOfRange();
823 }
824
825 // Write the count of response data.
826 uint8_t returnCount;
827 if ((offset + readCount) <= size)
828 {
829 returnCount = readCount;
830 }
831 else
832 {
833 returnCount = size - offset;
834 }
835
836 std::vector<uint8_t> fruData((fruArea.begin() + offset),
837 (fruArea.begin() + offset + returnCount));
838
839 return ipmi::responseSuccess(returnCount, fruData);
840 }
841 catch (const InternalFailure& e)
842 {
843 lg2::error("Internal Failure: {ERROR}", "ERROR", e);
844 return ipmi::responseUnspecifiedError();
845 }
846 }
847
848 ipmi::RspType<uint8_t, // SDR version
849 uint16_t, // record count LS first
850 uint16_t, // free space in bytes, LS first
851 uint32_t, // addition timestamp LS first
852 uint32_t, // deletion timestamp LS first
853 uint8_t> // operation Support
ipmiGetRepositoryInfo()854 ipmiGetRepositoryInfo()
855 {
856 constexpr uint8_t sdrVersion = 0x51;
857 constexpr uint16_t freeSpace = 0xFFFF;
858 constexpr uint32_t additionTimestamp = 0x0;
859 constexpr uint32_t deletionTimestamp = 0x0;
860 constexpr uint8_t operationSupport = 0;
861
862 // Get SDR count. This returns the total number of SDRs in the device.
863 const auto& entityRecords =
864 ipmi::sensor::EntityInfoMapContainer::getContainer()
865 ->getIpmiEntityRecords();
866 uint16_t records =
867 ipmi::sensor::sensors.size() + frus.size() + entityRecords.size();
868
869 return ipmi::responseSuccess(sdrVersion, records, freeSpace,
870 additionTimestamp, deletionTimestamp,
871 operationSupport);
872 }
873
registerNetFnStorageFunctions()874 void registerNetFnStorageFunctions()
875 {
876 selCacheMapInitialized = false;
877 initSELCache();
878 // Handlers with dbus-sdr handler implementation.
879 // Do not register the hander if it dynamic sensors stack is used.
880
881 #ifndef FEATURE_DYNAMIC_SENSORS
882
883 #ifndef FEATURE_DYNAMIC_STORAGES_ONLY
884 // <Get SEL Info>
885 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
886 ipmi::storage::cmdGetSelInfo, ipmi::Privilege::User,
887 ipmiStorageGetSelInfo);
888
889 // <Get SEL Timezone>
890 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
891 ipmi::storage::cmdGetSelTimeUtcOffset,
892 ipmi::Privilege::User,
893 ipmiStorageGetSelTimeUtcOffset);
894
895 // <Get SEL Entry>
896 ipmi_register_callback(NETFUN_STORAGE, ipmi::storage::cmdGetSelEntry,
897 nullptr, getSELEntry, PRIVILEGE_USER);
898
899 // <Delete SEL Entry>
900 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
901 ipmi::storage::cmdDeleteSelEntry,
902 ipmi::Privilege::Operator, deleteSELEntry);
903
904 // <Add SEL Entry>
905 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
906 ipmi::storage::cmdAddSelEntry,
907 ipmi::Privilege::Operator, ipmiStorageAddSEL);
908
909 // <Clear SEL>
910 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
911 ipmi::storage::cmdClearSel, ipmi::Privilege::Operator,
912 clearSEL);
913
914 // <Get FRU Inventory Area Info>
915 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
916 ipmi::storage::cmdGetFruInventoryAreaInfo,
917 ipmi::Privilege::User, ipmiStorageGetFruInvAreaInfo);
918
919 // <READ FRU Data>
920 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
921 ipmi::storage::cmdReadFruData,
922 ipmi::Privilege::Operator, ipmiStorageReadFruData);
923
924 #endif // FEATURE_DYNAMIC_STORAGES_ONLY
925
926 // <Get Repository Info>
927 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
928 ipmi::storage::cmdGetSdrRepositoryInfo,
929 ipmi::Privilege::User, ipmiGetRepositoryInfo);
930
931 // <Reserve SDR Repository>
932 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
933 ipmi::storage::cmdReserveSdrRepository,
934 ipmi::Privilege::User, ipmiSensorReserveSdr);
935
936 // <Get SDR>
937 ipmi_register_callback(NETFUN_STORAGE, ipmi::storage::cmdGetSdr, nullptr,
938 ipmi_sen_get_sdr, PRIVILEGE_USER);
939
940 #endif
941
942 // Common Handers used by both implementation.
943
944 // <Reserve SEL>
945 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
946 ipmi::storage::cmdReserveSel, ipmi::Privilege::User,
947 ipmiStorageReserveSel);
948
949 // <Get SEL Time>
950 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
951 ipmi::storage::cmdGetSelTime, ipmi::Privilege::User,
952 ipmiStorageGetSelTime);
953
954 // <Set SEL Time>
955 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
956 ipmi::storage::cmdSetSelTime,
957 ipmi::Privilege::Operator, ipmiStorageSetSelTime);
958
959 ipmi::fru::registerCallbackHandler();
960 return;
961 }
962