blob: c22828b005dd08d2ca08cb44907e599c3bb5ae44 [file] [log] [blame]
Willy Tude54f482021-01-26 15:59:09 -08001/*
2// Copyright (c) 2017-2019 Intel Corporation
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15*/
16
17#include "dbus-sdr/storagecommands.hpp"
18
19#include "dbus-sdr/sdrutils.hpp"
20#include "selutility.hpp"
21
22#include <boost/algorithm/string.hpp>
Ed Tanous98605052025-02-13 16:57:13 -080023#include <boost/asio/detached.hpp>
Willy Tude54f482021-01-26 15:59:09 -080024#include <boost/container/flat_map.hpp>
Willy Tude54f482021-01-26 15:59:09 -080025#include <ipmid/api.hpp>
26#include <ipmid/message.hpp>
27#include <ipmid/types.hpp>
George Liude1420d2025-03-03 15:14:25 +080028#include <ipmid/utils.hpp>
George Liude6694e2024-07-17 15:22:25 +080029#include <phosphor-logging/lg2.hpp>
Willy Tude54f482021-01-26 15:59:09 -080030#include <sdbusplus/message/types.hpp>
31#include <sdbusplus/timer.hpp>
Alexander Hansen93aa9832025-11-07 15:29:49 +010032#include <xyz/openbmc_project/ObjectMapper/common.hpp>
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -050033
34#include <filesystem>
35#include <fstream>
36#include <functional>
Willy Tu06ed9da2025-04-07 00:44:20 +000037#include <optional>
Willy Tude54f482021-01-26 15:59:09 -080038#include <stdexcept>
39#include <string_view>
40
Alexander Hansen93aa9832025-11-07 15:29:49 +010041using ObjectMapper = sdbusplus::common::xyz::openbmc_project::ObjectMapper;
42
Willy Tude54f482021-01-26 15:59:09 -080043static constexpr bool DEBUG = false;
44
45namespace dynamic_sensors::ipmi::sel
46{
47static const std::filesystem::path selLogDir = "/var/log";
48static const std::string selLogFilename = "ipmi_sel";
49
50static int getFileTimestamp(const std::filesystem::path& file)
51{
52 struct stat st;
53
54 if (stat(file.c_str(), &st) >= 0)
55 {
56 return st.st_mtime;
57 }
58 return ::ipmi::sel::invalidTimeStamp;
59}
60
61namespace erase_time
62{
63static constexpr const char* selEraseTimestamp = "/var/lib/ipmi/sel_erase_time";
64
Willy Tude54f482021-01-26 15:59:09 -080065int get()
66{
67 return getFileTimestamp(selEraseTimestamp);
68}
69} // namespace erase_time
70} // namespace dynamic_sensors::ipmi::sel
71
72namespace ipmi
73{
74
75namespace storage
76{
77
Willy Tude54f482021-01-26 15:59:09 -080078constexpr static const size_t maxFruSdrNameSize = 16;
79using ObjectType =
80 boost::container::flat_map<std::string,
81 boost::container::flat_map<std::string, Value>>;
82using ManagedObjectType =
83 boost::container::flat_map<sdbusplus::message::object_path, ObjectType>;
84using ManagedEntry = std::pair<sdbusplus::message::object_path, ObjectType>;
Willy Tu06ed9da2025-04-07 00:44:20 +000085using Paths = std::vector<std::string>;
Willy Tude54f482021-01-26 15:59:09 -080086
87constexpr static const char* fruDeviceServiceName =
88 "xyz.openbmc_project.FruDevice";
Willy Tude54f482021-01-26 15:59:09 -080089constexpr static const size_t writeTimeoutSeconds = 10;
90constexpr static const char* chassisTypeRackMount = "23";
Zev Weissf38f9d12021-05-21 13:30:16 -050091constexpr static const char* chassisTypeMainServer = "17";
Willy Tude54f482021-01-26 15:59:09 -080092
Willy Tude54f482021-01-26 15:59:09 -080093static std::vector<uint8_t> fruCache;
krishnar4d90b3f02022-11-11 16:18:32 +053094static constexpr uint16_t invalidBus = 0xFFFF;
95static constexpr uint8_t invalidAddr = 0xFF;
Johnathan Manteyb99de182023-12-21 08:28:18 -080096static constexpr uint8_t typeASCIILatin8 = 0xC0;
krishnar4d90b3f02022-11-11 16:18:32 +053097static uint16_t cacheBus = invalidBus;
98static uint8_t cacheAddr = invalidAddr;
Willy Tude54f482021-01-26 15:59:09 -080099static uint8_t lastDevId = 0xFF;
100
krishnar4d90b3f02022-11-11 16:18:32 +0530101static uint16_t writeBus = invalidBus;
102static uint8_t writeAddr = invalidAddr;
Willy Tude54f482021-01-26 15:59:09 -0800103
Patrick Williams95655222023-12-05 12:45:02 -0600104std::unique_ptr<sdbusplus::Timer> writeTimer = nullptr;
Patrick Williams5d82f472022-07-22 19:26:53 -0500105static std::vector<sdbusplus::bus::match_t> fruMatches;
Willy Tude54f482021-01-26 15:59:09 -0800106
107ManagedObjectType frus;
108
109// we unfortunately have to build a map of hashes in case there is a
110// collision to verify our dev-id
krishnar4d90b3f02022-11-11 16:18:32 +0530111boost::container::flat_map<uint8_t, std::pair<uint16_t, uint8_t>> deviceHashes;
Willy Tude54f482021-01-26 15:59:09 -0800112void registerStorageFunctions() __attribute__((constructor));
113
Willy Tu48fe64e2022-08-01 23:23:46 +0000114bool writeFru(const std::vector<uint8_t>& fru)
Willy Tude54f482021-01-26 15:59:09 -0800115{
krishnar4d90b3f02022-11-11 16:18:32 +0530116 if (writeBus == invalidBus && writeAddr == invalidAddr)
Willy Tude54f482021-01-26 15:59:09 -0800117 {
118 return true;
119 }
Thang Trand934be92021-12-08 10:13:50 +0700120 lastDevId = 0xFF;
Willy Tude54f482021-01-26 15:59:09 -0800121 std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus();
Patrick Williams5d82f472022-07-22 19:26:53 -0500122 sdbusplus::message_t writeFru = dbus->new_method_call(
Willy Tude54f482021-01-26 15:59:09 -0800123 fruDeviceServiceName, "/xyz/openbmc_project/FruDevice",
124 "xyz.openbmc_project.FruDeviceManager", "WriteFru");
Willy Tu48fe64e2022-08-01 23:23:46 +0000125 writeFru.append(writeBus, writeAddr, fru);
Willy Tude54f482021-01-26 15:59:09 -0800126 try
127 {
Patrick Williams5d82f472022-07-22 19:26:53 -0500128 sdbusplus::message_t writeFruResp = dbus->call(writeFru);
Willy Tude54f482021-01-26 15:59:09 -0800129 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500130 catch (const sdbusplus::exception_t&)
Willy Tude54f482021-01-26 15:59:09 -0800131 {
132 // todo: log sel?
George Liude6694e2024-07-17 15:22:25 +0800133 lg2::error("error writing fru");
Willy Tude54f482021-01-26 15:59:09 -0800134 return false;
135 }
krishnar4d90b3f02022-11-11 16:18:32 +0530136 writeBus = invalidBus;
137 writeAddr = invalidAddr;
Willy Tude54f482021-01-26 15:59:09 -0800138 return true;
139}
140
William A. Kennington III52535622022-11-28 18:28:22 -0800141void writeFruCache()
Willy Tu48fe64e2022-08-01 23:23:46 +0000142{
William A. Kennington III52535622022-11-28 18:28:22 -0800143 writeFru(fruCache);
Willy Tu48fe64e2022-08-01 23:23:46 +0000144}
145
Willy Tude54f482021-01-26 15:59:09 -0800146void createTimers()
147{
Patrick Williams95655222023-12-05 12:45:02 -0600148 writeTimer = std::make_unique<sdbusplus::Timer>(writeFruCache);
Willy Tude54f482021-01-26 15:59:09 -0800149}
150
151void recalculateHashes()
152{
Willy Tude54f482021-01-26 15:59:09 -0800153 deviceHashes.clear();
154 // hash the object paths to create unique device id's. increment on
155 // collision
156 std::hash<std::string> hasher;
157 for (const auto& fru : frus)
158 {
159 auto fruIface = fru.second.find("xyz.openbmc_project.FruDevice");
160 if (fruIface == fru.second.end())
161 {
162 continue;
163 }
164
165 auto busFind = fruIface->second.find("BUS");
166 auto addrFind = fruIface->second.find("ADDRESS");
167 if (busFind == fruIface->second.end() ||
168 addrFind == fruIface->second.end())
169 {
George Liude6694e2024-07-17 15:22:25 +0800170 lg2::info("fru device missing Bus or Address, fru: {FRU}", "FRU",
171 fru.first.str);
Willy Tude54f482021-01-26 15:59:09 -0800172 continue;
173 }
174
krishnar4d90b3f02022-11-11 16:18:32 +0530175 uint16_t fruBus = std::get<uint32_t>(busFind->second);
Willy Tude54f482021-01-26 15:59:09 -0800176 uint8_t fruAddr = std::get<uint32_t>(addrFind->second);
177 auto chassisFind = fruIface->second.find("CHASSIS_TYPE");
178 std::string chassisType;
179 if (chassisFind != fruIface->second.end())
180 {
181 chassisType = std::get<std::string>(chassisFind->second);
182 }
183
184 uint8_t fruHash = 0;
Zev Weissf38f9d12021-05-21 13:30:16 -0500185 if (chassisType.compare(chassisTypeRackMount) != 0 &&
186 chassisType.compare(chassisTypeMainServer) != 0)
Willy Tude54f482021-01-26 15:59:09 -0800187 {
188 fruHash = hasher(fru.first.str);
189 // can't be 0xFF based on spec, and 0 is reserved for baseboard
190 if (fruHash == 0 || fruHash == 0xFF)
191 {
192 fruHash = 1;
193 }
194 }
krishnar4d90b3f02022-11-11 16:18:32 +0530195 std::pair<uint16_t, uint8_t> newDev(fruBus, fruAddr);
Willy Tude54f482021-01-26 15:59:09 -0800196
197 bool emplacePassed = false;
198 while (!emplacePassed)
199 {
200 auto resp = deviceHashes.emplace(fruHash, newDev);
201 emplacePassed = resp.second;
202 if (!emplacePassed)
203 {
204 fruHash++;
205 // can't be 0xFF based on spec, and 0 is reserved for
206 // baseboard
207 if (fruHash == 0XFF)
208 {
209 fruHash = 0x1;
210 }
211 }
212 }
213 }
214}
215
Willy Tu11d68892022-01-20 10:37:34 -0800216void replaceCacheFru(
217 const std::shared_ptr<sdbusplus::asio::connection>& bus,
218 boost::asio::yield_context& yield,
219 [[maybe_unused]] const std::optional<std::string>& path = std::nullopt)
Willy Tude54f482021-01-26 15:59:09 -0800220{
221 boost::system::error_code ec;
222
223 frus = bus->yield_method_call<ManagedObjectType>(
224 yield, ec, fruDeviceServiceName, "/",
225 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
226 if (ec)
227 {
George Liude6694e2024-07-17 15:22:25 +0800228 lg2::error("GetMangagedObjects for replaceCacheFru failed: {ERROR}",
229 "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800230
231 return;
232 }
233 recalculateHashes();
234}
235
Patrick Williams69b4c282025-03-03 11:19:13 -0500236std::pair<ipmi::Cc, std::vector<uint8_t>> getFru(ipmi::Context::ptr ctx,
237 uint8_t devId)
Willy Tude54f482021-01-26 15:59:09 -0800238{
239 if (lastDevId == devId && devId != 0xFF)
240 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000241 return {ipmi::ccSuccess, fruCache};
Willy Tude54f482021-01-26 15:59:09 -0800242 }
243
Willy Tude54f482021-01-26 15:59:09 -0800244 auto deviceFind = deviceHashes.find(devId);
245 if (deviceFind == deviceHashes.end())
246 {
George Liu879c1d82025-07-03 09:36:57 +0800247 return {ipmi::ccSensorInvalid, {}};
Willy Tude54f482021-01-26 15:59:09 -0800248 }
249
Willy Tude54f482021-01-26 15:59:09 -0800250 cacheBus = deviceFind->second.first;
251 cacheAddr = deviceFind->second.second;
252
253 boost::system::error_code ec;
George Liude1420d2025-03-03 15:14:25 +0800254 std::vector<uint8_t> fru = ipmi::callDbusMethod<std::vector<uint8_t>>(
255 ctx, ec, fruDeviceServiceName, "/xyz/openbmc_project/FruDevice",
256 "xyz.openbmc_project.FruDeviceManager", "GetRawFru", cacheBus,
257 cacheAddr);
Willy Tude54f482021-01-26 15:59:09 -0800258
Willy Tude54f482021-01-26 15:59:09 -0800259 if (ec)
260 {
George Liude6694e2024-07-17 15:22:25 +0800261 lg2::error("Couldn't get raw fru: {ERROR}", "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800262
krishnar4d90b3f02022-11-11 16:18:32 +0530263 cacheBus = invalidBus;
264 cacheAddr = invalidAddr;
Willy Tu48fe64e2022-08-01 23:23:46 +0000265 return {ipmi::ccResponseError, {}};
Willy Tude54f482021-01-26 15:59:09 -0800266 }
267
Willy Tu48fe64e2022-08-01 23:23:46 +0000268 fruCache.clear();
Willy Tude54f482021-01-26 15:59:09 -0800269 lastDevId = devId;
Willy Tu48fe64e2022-08-01 23:23:46 +0000270 fruCache = fru;
271
272 return {ipmi::ccSuccess, fru};
Willy Tude54f482021-01-26 15:59:09 -0800273}
274
275void writeFruIfRunning()
276{
277 if (!writeTimer->isRunning())
278 {
279 return;
280 }
281 writeTimer->stop();
Willy Tu48fe64e2022-08-01 23:23:46 +0000282 writeFruCache();
Willy Tude54f482021-01-26 15:59:09 -0800283}
284
285void startMatch(void)
286{
287 if (fruMatches.size())
288 {
289 return;
290 }
291
292 fruMatches.reserve(2);
293
294 auto bus = getSdBus();
Patrick Williams1318a5e2024-08-16 15:19:54 -0400295 fruMatches.emplace_back(
296 *bus,
297 "type='signal',arg0path='/xyz/openbmc_project/"
298 "FruDevice/',member='InterfacesAdded'",
299 [](sdbusplus::message_t& message) {
300 sdbusplus::message::object_path path;
301 ObjectType object;
302 try
303 {
304 message.read(path, object);
305 }
306 catch (const sdbusplus::exception_t&)
307 {
308 return;
309 }
310 auto findType = object.find("xyz.openbmc_project.FruDevice");
311 if (findType == object.end())
312 {
313 return;
314 }
315 writeFruIfRunning();
316 frus[path] = object;
317 recalculateHashes();
318 lastDevId = 0xFF;
319 });
Willy Tude54f482021-01-26 15:59:09 -0800320
Patrick Williams1318a5e2024-08-16 15:19:54 -0400321 fruMatches.emplace_back(
322 *bus,
323 "type='signal',arg0path='/xyz/openbmc_project/"
324 "FruDevice/',member='InterfacesRemoved'",
325 [](sdbusplus::message_t& message) {
326 sdbusplus::message::object_path path;
327 std::set<std::string> interfaces;
328 try
329 {
330 message.read(path, interfaces);
331 }
332 catch (const sdbusplus::exception_t&)
333 {
334 return;
335 }
336 auto findType = interfaces.find("xyz.openbmc_project.FruDevice");
337 if (findType == interfaces.end())
338 {
339 return;
340 }
341 writeFruIfRunning();
342 frus.erase(path);
343 recalculateHashes();
344 lastDevId = 0xFF;
345 });
Willy Tude54f482021-01-26 15:59:09 -0800346
347 // call once to populate
Ed Tanous98605052025-02-13 16:57:13 -0800348 boost::asio::spawn(
349 *getIoContext(),
350 [](boost::asio::yield_context yield) {
351 replaceCacheFru(getSdBus(), yield);
352 },
353 boost::asio::detached);
Willy Tude54f482021-01-26 15:59:09 -0800354}
355
356/** @brief implements the read FRU data command
357 * @param fruDeviceId - FRU Device ID
358 * @param fruInventoryOffset - FRU Inventory Offset to write
359 * @param countToRead - Count to read
360 *
361 * @returns ipmi completion code plus response data
362 * - countWritten - Count written
363 */
364ipmi::RspType<uint8_t, // Count
365 std::vector<uint8_t> // Requested data
366 >
367 ipmiStorageReadFruData(ipmi::Context::ptr ctx, uint8_t fruDeviceId,
368 uint16_t fruInventoryOffset, uint8_t countToRead)
369{
370 if (fruDeviceId == 0xFF)
371 {
372 return ipmi::responseInvalidFieldRequest();
373 }
374
Willy Tu48fe64e2022-08-01 23:23:46 +0000375 auto [status, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800376 if (status != ipmi::ccSuccess)
377 {
378 return ipmi::response(status);
379 }
380
381 size_t fromFruByteLen = 0;
Willy Tu48fe64e2022-08-01 23:23:46 +0000382 if (countToRead + fruInventoryOffset < fru.size())
Willy Tude54f482021-01-26 15:59:09 -0800383 {
384 fromFruByteLen = countToRead;
385 }
Willy Tu48fe64e2022-08-01 23:23:46 +0000386 else if (fru.size() > fruInventoryOffset)
Willy Tude54f482021-01-26 15:59:09 -0800387 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000388 fromFruByteLen = fru.size() - fruInventoryOffset;
Willy Tude54f482021-01-26 15:59:09 -0800389 }
390 else
391 {
392 return ipmi::responseReqDataLenExceeded();
393 }
394
395 std::vector<uint8_t> requestedData;
396
Willy Tu48fe64e2022-08-01 23:23:46 +0000397 requestedData.insert(requestedData.begin(),
398 fru.begin() + fruInventoryOffset,
399 fru.begin() + fruInventoryOffset + fromFruByteLen);
Willy Tude54f482021-01-26 15:59:09 -0800400
401 return ipmi::responseSuccess(static_cast<uint8_t>(requestedData.size()),
402 requestedData);
403}
404
405/** @brief implements the write FRU data command
406 * @param fruDeviceId - FRU Device ID
407 * @param fruInventoryOffset - FRU Inventory Offset to write
408 * @param dataToWrite - Data to write
409 *
410 * @returns ipmi completion code plus response data
411 * - countWritten - Count written
412 */
Patrick Williams1318a5e2024-08-16 15:19:54 -0400413ipmi::RspType<uint8_t> ipmiStorageWriteFruData(
414 ipmi::Context::ptr ctx, uint8_t fruDeviceId, uint16_t fruInventoryOffset,
415 std::vector<uint8_t>& dataToWrite)
Willy Tude54f482021-01-26 15:59:09 -0800416{
417 if (fruDeviceId == 0xFF)
418 {
419 return ipmi::responseInvalidFieldRequest();
420 }
421
422 size_t writeLen = dataToWrite.size();
423
Willy Tu48fe64e2022-08-01 23:23:46 +0000424 auto [status, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800425 if (status != ipmi::ccSuccess)
426 {
427 return ipmi::response(status);
428 }
429 size_t lastWriteAddr = fruInventoryOffset + writeLen;
Willy Tu48fe64e2022-08-01 23:23:46 +0000430 if (fru.size() < lastWriteAddr)
Willy Tude54f482021-01-26 15:59:09 -0800431 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000432 fru.resize(fruInventoryOffset + writeLen);
Willy Tude54f482021-01-26 15:59:09 -0800433 }
434
435 std::copy(dataToWrite.begin(), dataToWrite.begin() + writeLen,
Willy Tu48fe64e2022-08-01 23:23:46 +0000436 fru.begin() + fruInventoryOffset);
Willy Tude54f482021-01-26 15:59:09 -0800437
438 bool atEnd = false;
439
Willy Tu48fe64e2022-08-01 23:23:46 +0000440 if (fru.size() >= sizeof(FRUHeader))
Willy Tude54f482021-01-26 15:59:09 -0800441 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000442 FRUHeader* header = reinterpret_cast<FRUHeader*>(fru.data());
Willy Tude54f482021-01-26 15:59:09 -0800443
444 size_t areaLength = 0;
445 size_t lastRecordStart = std::max(
446 {header->internalOffset, header->chassisOffset, header->boardOffset,
447 header->productOffset, header->multiRecordOffset});
448 lastRecordStart *= 8; // header starts in are multiples of 8 bytes
449
450 if (header->multiRecordOffset)
451 {
452 // This FRU has a MultiRecord Area
453 uint8_t endOfList = 0;
454 // Walk the MultiRecord headers until the last record
455 while (!endOfList)
456 {
457 // The MSB in the second byte of the MultiRecord header signals
458 // "End of list"
Willy Tu48fe64e2022-08-01 23:23:46 +0000459 endOfList = fru[lastRecordStart + 1] & 0x80;
Willy Tude54f482021-01-26 15:59:09 -0800460 // Third byte in the MultiRecord header is the length
Willy Tu48fe64e2022-08-01 23:23:46 +0000461 areaLength = fru[lastRecordStart + 2];
Willy Tude54f482021-01-26 15:59:09 -0800462 // This length is in bytes (not 8 bytes like other headers)
463 areaLength += 5; // The length omits the 5 byte header
464 if (!endOfList)
465 {
466 // Next MultiRecord header
467 lastRecordStart += areaLength;
468 }
469 }
470 }
471 else
472 {
473 // This FRU does not have a MultiRecord Area
474 // Get the length of the area in multiples of 8 bytes
475 if (lastWriteAddr > (lastRecordStart + 1))
476 {
477 // second byte in record area is the length
Willy Tu48fe64e2022-08-01 23:23:46 +0000478 areaLength = fru[lastRecordStart + 1];
Willy Tude54f482021-01-26 15:59:09 -0800479 areaLength *= 8; // it is in multiples of 8 bytes
480 }
481 }
482 if (lastWriteAddr >= (areaLength + lastRecordStart))
483 {
484 atEnd = true;
485 }
486 }
487 uint8_t countWritten = 0;
488
489 writeBus = cacheBus;
490 writeAddr = cacheAddr;
491 if (atEnd)
492 {
493 // cancel timer, we're at the end so might as well send it
494 writeTimer->stop();
Willy Tu48fe64e2022-08-01 23:23:46 +0000495 if (!writeFru(fru))
Willy Tude54f482021-01-26 15:59:09 -0800496 {
497 return ipmi::responseInvalidFieldRequest();
498 }
Willy Tu48fe64e2022-08-01 23:23:46 +0000499 countWritten = std::min(fru.size(), static_cast<size_t>(0xFF));
Willy Tude54f482021-01-26 15:59:09 -0800500 }
501 else
502 {
Sui Chen548d1a22022-09-14 07:41:17 -0700503 fruCache = fru; // Write-back
Willy Tude54f482021-01-26 15:59:09 -0800504 // start a timer, if no further data is sent to check to see if it is
505 // valid
506 writeTimer->start(std::chrono::duration_cast<std::chrono::microseconds>(
507 std::chrono::seconds(writeTimeoutSeconds)));
508 countWritten = 0;
509 }
510
511 return ipmi::responseSuccess(countWritten);
512}
513
514/** @brief implements the get FRU inventory area info command
515 * @param fruDeviceId - FRU Device ID
516 *
517 * @returns IPMI completion code plus response data
518 * - inventorySize - Number of possible allocation units
519 * - accessType - Allocation unit size in bytes.
520 */
521ipmi::RspType<uint16_t, // inventorySize
522 uint8_t> // accessType
523 ipmiStorageGetFruInvAreaInfo(ipmi::Context::ptr ctx, uint8_t fruDeviceId)
524{
525 if (fruDeviceId == 0xFF)
526 {
527 return ipmi::responseInvalidFieldRequest();
528 }
529
Willy Tu48fe64e2022-08-01 23:23:46 +0000530 auto [ret, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800531 if (ret != ipmi::ccSuccess)
532 {
533 return ipmi::response(ret);
534 }
535
536 constexpr uint8_t accessType =
537 static_cast<uint8_t>(GetFRUAreaAccessType::byte);
538
Willy Tu48fe64e2022-08-01 23:23:46 +0000539 return ipmi::responseSuccess(fru.size(), accessType);
Willy Tude54f482021-01-26 15:59:09 -0800540}
541
George Liu23c868c2025-07-04 09:31:35 +0800542ipmi::Cc getFruSdrCount(ipmi::Context::ptr, size_t& count)
Willy Tude54f482021-01-26 15:59:09 -0800543{
544 count = deviceHashes.size();
George Liue8a97bd2024-12-05 17:26:46 +0800545 return ipmi::ccSuccess;
Willy Tude54f482021-01-26 15:59:09 -0800546}
547
George Liu23c868c2025-07-04 09:31:35 +0800548ipmi::Cc getFruSdrs([[maybe_unused]] ipmi::Context::ptr ctx, size_t index,
549 get_sdr::SensorDataFruRecord& resp)
Willy Tude54f482021-01-26 15:59:09 -0800550{
551 if (deviceHashes.size() < index)
552 {
George Liu879c1d82025-07-03 09:36:57 +0800553 return ipmi::ccInvalidFieldRequest;
Willy Tude54f482021-01-26 15:59:09 -0800554 }
555 auto device = deviceHashes.begin() + index;
krishnar4d90b3f02022-11-11 16:18:32 +0530556 uint16_t& bus = device->second.first;
Willy Tude54f482021-01-26 15:59:09 -0800557 uint8_t& address = device->second.second;
558
559 boost::container::flat_map<std::string, Value>* fruData = nullptr;
Patrick Williams1318a5e2024-08-16 15:19:54 -0400560 auto fru = std::find_if(
561 frus.begin(), frus.end(),
562 [bus, address, &fruData](ManagedEntry& entry) {
563 auto findFruDevice =
564 entry.second.find("xyz.openbmc_project.FruDevice");
565 if (findFruDevice == entry.second.end())
566 {
567 return false;
568 }
569 fruData = &(findFruDevice->second);
570 auto findBus = findFruDevice->second.find("BUS");
571 auto findAddress = findFruDevice->second.find("ADDRESS");
572 if (findBus == findFruDevice->second.end() ||
573 findAddress == findFruDevice->second.end())
574 {
575 return false;
576 }
577 if (std::get<uint32_t>(findBus->second) != bus)
578 {
579 return false;
580 }
581 if (std::get<uint32_t>(findAddress->second) != address)
582 {
583 return false;
584 }
585 return true;
586 });
Willy Tude54f482021-01-26 15:59:09 -0800587 if (fru == frus.end())
588 {
George Liu879c1d82025-07-03 09:36:57 +0800589 return ipmi::ccResponseError;
Willy Tude54f482021-01-26 15:59:09 -0800590 }
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530591 std::string name;
Willy Tu06ed9da2025-04-07 00:44:20 +0000592 uint8_t entityID = 0;
593 uint8_t entityInstance = 0x1;
Willy Tude54f482021-01-26 15:59:09 -0800594
595#ifdef USING_ENTITY_MANAGER_DECORATORS
Willy Tude54f482021-01-26 15:59:09 -0800596 boost::system::error_code ec;
Willy Tude54f482021-01-26 15:59:09 -0800597
Willy Tu06ed9da2025-04-07 00:44:20 +0000598 Paths subtreePaths = ipmi::callDbusMethod<Paths>(
Alexander Hansen93aa9832025-11-07 15:29:49 +0100599 ctx, ec, ObjectMapper::default_service, ObjectMapper::instance_path,
600 ObjectMapper::interface, ObjectMapper::method_names::get_sub_tree_paths,
Willy Tu06ed9da2025-04-07 00:44:20 +0000601 "/xyz/openbmc_project/inventory", 0,
602 std::array<const char*, 2>{
603 "xyz.openbmc_project.Inventory.Decorator.I2CDevice",
604 "xyz.openbmc_project.Inventory.Decorator.Ipmi",
605 });
Willy Tude54f482021-01-26 15:59:09 -0800606 if (ec)
607 {
Willy Tu06ed9da2025-04-07 00:44:20 +0000608 lg2::error(
609 "GetSubTreePaths for ipmiStorageGetFruInvAreaInfo failed: {ERROR}",
610 "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800611 return ipmi::ccResponseError;
612 }
613
Willy Tu06ed9da2025-04-07 00:44:20 +0000614 bool foundDevice = false;
615 for (const auto& path : subtreePaths)
616 {
617 ipmi::PropertyMap i2cProperties;
618 boost::system::error_code ec = ipmi::getAllDbusProperties(
619 ctx, "xyz.openbmc_project.EntityManager", path,
620 "xyz.openbmc_project.Inventory.Decorator.I2CDevice", i2cProperties);
621 if (ec)
622 {
623 continue;
624 }
625
626 std::optional<uint64_t> maybeBus;
627 std::optional<uint64_t> maybeAddress;
628 std::optional<std::string> maybeName;
629 for (const auto& [key, val] : i2cProperties)
630 {
631 if (key == "Bus")
Patrick Williams1318a5e2024-08-16 15:19:54 -0400632 {
Willy Tu06ed9da2025-04-07 00:44:20 +0000633 maybeBus = std::get<uint64_t>(val);
Patrick Williams1318a5e2024-08-16 15:19:54 -0400634 }
Willy Tu06ed9da2025-04-07 00:44:20 +0000635 else if (key == "Address")
Patrick Williams1318a5e2024-08-16 15:19:54 -0400636 {
Willy Tu06ed9da2025-04-07 00:44:20 +0000637 maybeAddress = std::get<uint64_t>(val);
Patrick Williams1318a5e2024-08-16 15:19:54 -0400638 }
Willy Tu06ed9da2025-04-07 00:44:20 +0000639 else if (key == "Name")
Patrick Williams1318a5e2024-08-16 15:19:54 -0400640 {
Willy Tu06ed9da2025-04-07 00:44:20 +0000641 maybeName = std::get<std::string>(val);
Patrick Williams1318a5e2024-08-16 15:19:54 -0400642 }
Willy Tu06ed9da2025-04-07 00:44:20 +0000643 }
644 if (!maybeBus || *maybeBus != bus || !maybeAddress ||
645 *maybeAddress != address)
646 {
647 continue;
648 }
649 // At this point we found the device entry and will populate the
650 // information if exist.
651 foundDevice = true;
Willy Tude54f482021-01-26 15:59:09 -0800652
Willy Tu06ed9da2025-04-07 00:44:20 +0000653 if (maybeName.has_value())
654 {
655 name = *maybeName;
656 }
657
658 ipmi::PropertyMap entityData;
659 ec = ipmi::getAllDbusProperties(
660 ctx, "xyz.openbmc_project.EntityManager", path,
661 "xyz.openbmc_project.Inventory.Decorator.Ipmi", entityData);
662 if (!ec)
663 {
664 for (const auto& [key, val] : entityData)
Patrick Williams1318a5e2024-08-16 15:19:54 -0400665 {
Willy Tu06ed9da2025-04-07 00:44:20 +0000666 if (key == "EntityId")
667 {
668 entityID = std::get<uint64_t>(val);
669 }
670 else if (key == "EntityInstance")
671 {
672 entityInstance = std::get<uint64_t>(val);
673 }
Patrick Williams1318a5e2024-08-16 15:19:54 -0400674 }
Willy Tu06ed9da2025-04-07 00:44:20 +0000675 }
676 break;
677 }
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530678
Willy Tu06ed9da2025-04-07 00:44:20 +0000679 if (!foundDevice)
Willy Tude54f482021-01-26 15:59:09 -0800680 {
681 if constexpr (DEBUG)
682 {
683 std::fprintf(stderr, "Ipmi or FruDevice Decorator interface "
684 "not found for Fru\n");
685 }
686 }
Willy Tude54f482021-01-26 15:59:09 -0800687#endif
688
Alexander Hansenea46f3c2023-09-04 11:27:54 +0200689 std::vector<std::string> nameProperties = {
Jitendra Tripathy1d881b52025-05-16 10:08:15 +0000690 "BOARD_PRODUCT_NAME", "PRODUCT_PRODUCT_NAME", "PRODUCT_PART_NUMBER",
Alexander Hansenea46f3c2023-09-04 11:27:54 +0200691 "BOARD_PART_NUMBER", "PRODUCT_MANUFACTURER", "BOARD_MANUFACTURER",
692 "PRODUCT_SERIAL_NUMBER", "BOARD_SERIAL_NUMBER"};
693
694 for (const std::string& prop : nameProperties)
695 {
696 auto findProp = fruData->find(prop);
697 if (findProp != fruData->end())
698 {
699 name = std::get<std::string>(findProp->second);
700 break;
701 }
702 }
703
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530704 if (name.empty())
Willy Tude54f482021-01-26 15:59:09 -0800705 {
706 name = "UNKNOWN";
707 }
708 if (name.size() > maxFruSdrNameSize)
709 {
710 name = name.substr(0, maxFruSdrNameSize);
711 }
712 size_t sizeDiff = maxFruSdrNameSize - name.size();
713
George Liuc7a4da52025-08-19 16:20:31 +0800714 resp.header.recordId = 0x0; // calling code is to implement these
George Liu42247d22025-08-19 10:24:47 +0800715 resp.header.sdrVersion = ipmiSdrVersion;
716 resp.header.recordType = get_sdr::SENSOR_DATA_FRU_RECORD;
717 resp.header.recordLength = sizeof(resp.body) + sizeof(resp.key) - sizeDiff;
Willy Tude54f482021-01-26 15:59:09 -0800718 resp.key.deviceAddress = 0x20;
719 resp.key.fruID = device->first;
720 resp.key.accessLun = 0x80; // logical / physical fru device
721 resp.key.channelNumber = 0x0;
722 resp.body.reserved = 0x0;
723 resp.body.deviceType = 0x10;
724 resp.body.deviceTypeModifier = 0x0;
725
Willy Tude54f482021-01-26 15:59:09 -0800726 resp.body.entityID = entityID;
727 resp.body.entityInstance = entityInstance;
728
729 resp.body.oem = 0x0;
Johnathan Manteyb99de182023-12-21 08:28:18 -0800730 resp.body.deviceIDLen = ipmi::storage::typeASCIILatin8 | name.size();
Willy Tude54f482021-01-26 15:59:09 -0800731 name.copy(resp.body.deviceID, name.size());
732
George Liue8a97bd2024-12-05 17:26:46 +0800733 return ipmi::ccSuccess;
Willy Tude54f482021-01-26 15:59:09 -0800734}
735
736static bool getSELLogFiles(std::vector<std::filesystem::path>& selLogFiles)
737{
738 // Loop through the directory looking for ipmi_sel log files
739 for (const std::filesystem::directory_entry& dirEnt :
740 std::filesystem::directory_iterator(
741 dynamic_sensors::ipmi::sel::selLogDir))
742 {
743 std::string filename = dirEnt.path().filename();
George Liuc024b392025-08-21 16:38:58 +0800744 if (filename.starts_with(dynamic_sensors::ipmi::sel::selLogFilename))
Willy Tude54f482021-01-26 15:59:09 -0800745 {
746 // If we find an ipmi_sel log file, save the path
Patrick Williams1318a5e2024-08-16 15:19:54 -0400747 selLogFiles.emplace_back(
748 dynamic_sensors::ipmi::sel::selLogDir / filename);
Willy Tude54f482021-01-26 15:59:09 -0800749 }
750 }
751 // As the log files rotate, they are appended with a ".#" that is higher for
752 // the older logs. Since we don't expect more than 10 log files, we
753 // can just sort the list to get them in order from newest to oldest
754 std::sort(selLogFiles.begin(), selLogFiles.end());
755
756 return !selLogFiles.empty();
757}
758
759static int countSELEntries()
760{
761 // Get the list of ipmi_sel log files
762 std::vector<std::filesystem::path> selLogFiles;
763 if (!getSELLogFiles(selLogFiles))
764 {
765 return 0;
766 }
767 int numSELEntries = 0;
768 // Loop through each log file and count the number of logs
769 for (const std::filesystem::path& file : selLogFiles)
770 {
771 std::ifstream logStream(file);
772 if (!logStream.is_open())
773 {
774 continue;
775 }
776
777 std::string line;
778 while (std::getline(logStream, line))
779 {
780 numSELEntries++;
781 }
782 }
783 return numSELEntries;
784}
785
786static bool findSELEntry(const int recordID,
787 const std::vector<std::filesystem::path>& selLogFiles,
788 std::string& entry)
789{
790 // Record ID is the first entry field following the timestamp. It is
791 // preceded by a space and followed by a comma
792 std::string search = " " + std::to_string(recordID) + ",";
793
794 // Loop through the ipmi_sel log entries
795 for (const std::filesystem::path& file : selLogFiles)
796 {
797 std::ifstream logStream(file);
798 if (!logStream.is_open())
799 {
800 continue;
801 }
802
803 while (std::getline(logStream, entry))
804 {
805 // Check if the record ID matches
806 if (entry.find(search) != std::string::npos)
807 {
808 return true;
809 }
810 }
811 }
812 return false;
813}
814
Patrick Williams69b4c282025-03-03 11:19:13 -0500815static uint16_t getNextRecordID(
816 const uint16_t recordID,
817 const std::vector<std::filesystem::path>& selLogFiles)
Willy Tude54f482021-01-26 15:59:09 -0800818{
819 uint16_t nextRecordID = recordID + 1;
820 std::string entry;
821 if (findSELEntry(nextRecordID, selLogFiles, entry))
822 {
823 return nextRecordID;
824 }
825 else
826 {
827 return ipmi::sel::lastEntry;
828 }
829}
830
831static int fromHexStr(const std::string& hexStr, std::vector<uint8_t>& data)
832{
833 for (unsigned int i = 0; i < hexStr.size(); i += 2)
834 {
835 try
836 {
837 data.push_back(static_cast<uint8_t>(
838 std::stoul(hexStr.substr(i, 2), nullptr, 16)));
839 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500840 catch (const std::invalid_argument& e)
Willy Tude54f482021-01-26 15:59:09 -0800841 {
George Liude6694e2024-07-17 15:22:25 +0800842 lg2::error("Invalid argument: {ERROR}", "ERROR", e);
Willy Tude54f482021-01-26 15:59:09 -0800843 return -1;
844 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500845 catch (const std::out_of_range& e)
Willy Tude54f482021-01-26 15:59:09 -0800846 {
George Liude6694e2024-07-17 15:22:25 +0800847 lg2::error("Out of range: {ERROR}", "ERROR", e);
Willy Tude54f482021-01-26 15:59:09 -0800848 return -1;
849 }
850 }
851 return 0;
852}
853
854ipmi::RspType<uint8_t, // SEL version
855 uint16_t, // SEL entry count
856 uint16_t, // free space
857 uint32_t, // last add timestamp
858 uint32_t, // last erase timestamp
859 uint8_t> // operation support
860 ipmiStorageGetSELInfo()
861{
862 constexpr uint8_t selVersion = ipmi::sel::selVersion;
863 uint16_t entries = countSELEntries();
864 uint32_t addTimeStamp = dynamic_sensors::ipmi::sel::getFileTimestamp(
865 dynamic_sensors::ipmi::sel::selLogDir /
866 dynamic_sensors::ipmi::sel::selLogFilename);
867 uint32_t eraseTimeStamp = dynamic_sensors::ipmi::sel::erase_time::get();
868 constexpr uint8_t operationSupport =
869 dynamic_sensors::ipmi::sel::selOperationSupport;
870 constexpr uint16_t freeSpace =
871 0xffff; // Spec indicates that more than 64kB is free
872
873 return ipmi::responseSuccess(selVersion, entries, freeSpace, addTimeStamp,
874 eraseTimeStamp, operationSupport);
875}
876
877using systemEventType = std::tuple<
878 uint32_t, // Timestamp
879 uint16_t, // Generator ID
880 uint8_t, // EvM Rev
881 uint8_t, // Sensor Type
882 uint8_t, // Sensor Number
883 uint7_t, // Event Type
884 bool, // Event Direction
885 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>>; // Event
886 // Data
887using oemTsEventType = std::tuple<
888 uint32_t, // Timestamp
889 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>>; // Event
890 // Data
891using oemEventType =
892 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>; // Event Data
893
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500894ipmi::RspType<uint16_t, // Next Record ID
895 uint16_t, // Record ID
896 uint8_t, // Record Type
Willy Tude54f482021-01-26 15:59:09 -0800897 std::variant<systemEventType, oemTsEventType,
898 oemEventType>> // Record Content
899 ipmiStorageGetSELEntry(uint16_t reservationID, uint16_t targetID,
900 uint8_t offset, uint8_t size)
901{
902 // Only support getting the entire SEL record. If a partial size or non-zero
903 // offset is requested, return an error
904 if (offset != 0 || size != ipmi::sel::entireRecord)
905 {
906 return ipmi::responseRetBytesUnavailable();
907 }
908
909 // Check the reservation ID if one is provided or required (only if the
910 // offset is non-zero)
911 if (reservationID != 0 || offset != 0)
912 {
913 if (!checkSELReservation(reservationID))
914 {
915 return ipmi::responseInvalidReservationId();
916 }
917 }
918
919 // Get the ipmi_sel log files
920 std::vector<std::filesystem::path> selLogFiles;
921 if (!getSELLogFiles(selLogFiles))
922 {
923 return ipmi::responseSensorInvalid();
924 }
925
926 std::string targetEntry;
927
928 if (targetID == ipmi::sel::firstEntry)
929 {
930 // The first entry will be at the top of the oldest log file
931 std::ifstream logStream(selLogFiles.back());
932 if (!logStream.is_open())
933 {
934 return ipmi::responseUnspecifiedError();
935 }
936
937 if (!std::getline(logStream, targetEntry))
938 {
939 return ipmi::responseUnspecifiedError();
940 }
941 }
942 else if (targetID == ipmi::sel::lastEntry)
943 {
944 // The last entry will be at the bottom of the newest log file
945 std::ifstream logStream(selLogFiles.front());
946 if (!logStream.is_open())
947 {
948 return ipmi::responseUnspecifiedError();
949 }
950
951 std::string line;
952 while (std::getline(logStream, line))
953 {
954 targetEntry = line;
955 }
956 }
957 else
958 {
959 if (!findSELEntry(targetID, selLogFiles, targetEntry))
960 {
961 return ipmi::responseSensorInvalid();
962 }
963 }
964
965 // The format of the ipmi_sel message is "<Timestamp>
966 // <ID>,<Type>,<EventData>,[<Generator ID>,<Path>,<Direction>]".
967 // First get the Timestamp
968 size_t space = targetEntry.find_first_of(" ");
969 if (space == std::string::npos)
970 {
971 return ipmi::responseUnspecifiedError();
972 }
973 std::string entryTimestamp = targetEntry.substr(0, space);
974 // Then get the log contents
975 size_t entryStart = targetEntry.find_first_not_of(" ", space);
976 if (entryStart == std::string::npos)
977 {
978 return ipmi::responseUnspecifiedError();
979 }
980 std::string_view entry(targetEntry);
981 entry.remove_prefix(entryStart);
982 // Use split to separate the entry into its fields
983 std::vector<std::string> targetEntryFields;
984 boost::split(targetEntryFields, entry, boost::is_any_of(","),
985 boost::token_compress_on);
986 if (targetEntryFields.size() < 3)
987 {
988 return ipmi::responseUnspecifiedError();
989 }
990 std::string& recordIDStr = targetEntryFields[0];
991 std::string& recordTypeStr = targetEntryFields[1];
992 std::string& eventDataStr = targetEntryFields[2];
993
994 uint16_t recordID;
995 uint8_t recordType;
996 try
997 {
998 recordID = std::stoul(recordIDStr);
999 recordType = std::stoul(recordTypeStr, nullptr, 16);
1000 }
1001 catch (const std::invalid_argument&)
1002 {
1003 return ipmi::responseUnspecifiedError();
1004 }
1005 uint16_t nextRecordID = getNextRecordID(recordID, selLogFiles);
1006 std::vector<uint8_t> eventDataBytes;
1007 if (fromHexStr(eventDataStr, eventDataBytes) < 0)
1008 {
1009 return ipmi::responseUnspecifiedError();
1010 }
1011
1012 if (recordType == dynamic_sensors::ipmi::sel::systemEvent)
1013 {
1014 // Get the timestamp
1015 std::tm timeStruct = {};
1016 std::istringstream entryStream(entryTimestamp);
1017
1018 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1019 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1020 {
Willy Tu7bb412f2023-09-25 11:30:45 -07001021 timeStruct.tm_isdst = -1;
Willy Tude54f482021-01-26 15:59:09 -08001022 timestamp = std::mktime(&timeStruct);
1023 }
1024
1025 // Set the event message revision
1026 uint8_t evmRev = dynamic_sensors::ipmi::sel::eventMsgRev;
1027
1028 uint16_t generatorID = 0;
1029 uint8_t sensorType = 0;
1030 uint16_t sensorAndLun = 0;
1031 uint8_t sensorNum = 0xFF;
1032 uint7_t eventType = 0;
1033 bool eventDir = 0;
1034 // System type events should have six fields
1035 if (targetEntryFields.size() >= 6)
1036 {
1037 std::string& generatorIDStr = targetEntryFields[3];
1038 std::string& sensorPath = targetEntryFields[4];
1039 std::string& eventDirStr = targetEntryFields[5];
1040
1041 // Get the generator ID
1042 try
1043 {
1044 generatorID = std::stoul(generatorIDStr, nullptr, 16);
1045 }
1046 catch (const std::invalid_argument&)
1047 {
Haicheng Zhang041b3752025-07-14 17:13:45 +08001048 lg2::error("Invalid Generator ID");
Willy Tude54f482021-01-26 15:59:09 -08001049 }
1050
1051 // Get the sensor type, sensor number, and event type for the sensor
1052 sensorType = getSensorTypeFromPath(sensorPath);
1053 sensorAndLun = getSensorNumberFromPath(sensorPath);
1054 sensorNum = static_cast<uint8_t>(sensorAndLun);
Harvey.Wu4376cdf2021-11-16 19:40:55 +08001055 if ((generatorID & 0x0001) == 0)
1056 {
1057 // IPMB Address
1058 generatorID |= sensorAndLun & 0x0300;
1059 }
1060 else
1061 {
1062 // system software
1063 generatorID |= sensorAndLun >> 8;
1064 }
Willy Tude54f482021-01-26 15:59:09 -08001065 eventType = getSensorEventTypeFromPath(sensorPath);
1066
1067 // Get the event direction
1068 try
1069 {
1070 eventDir = std::stoul(eventDirStr) ? 0 : 1;
1071 }
1072 catch (const std::invalid_argument&)
1073 {
Haicheng Zhang041b3752025-07-14 17:13:45 +08001074 lg2::error("Invalid Event Direction");
Willy Tude54f482021-01-26 15:59:09 -08001075 }
1076 }
1077
1078 // Only keep the eventData bytes that fit in the record
1079 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>
1080 eventData{};
1081 std::copy_n(eventDataBytes.begin(),
1082 std::min(eventDataBytes.size(), eventData.size()),
1083 eventData.begin());
1084
1085 return ipmi::responseSuccess(
1086 nextRecordID, recordID, recordType,
1087 systemEventType{timestamp, generatorID, evmRev, sensorType,
1088 sensorNum, eventType, eventDir, eventData});
1089 }
1090
Thang Trane70c59b2023-09-21 13:54:28 +07001091 if (recordType >= dynamic_sensors::ipmi::sel::oemTsEventFirst &&
1092 recordType <= dynamic_sensors::ipmi::sel::oemTsEventLast)
1093 {
1094 // Get the timestamp
1095 std::tm timeStruct = {};
1096 std::istringstream entryStream(entryTimestamp);
1097
1098 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1099 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1100 {
1101 timeStruct.tm_isdst = -1;
1102 timestamp = std::mktime(&timeStruct);
1103 }
1104
1105 // Only keep the bytes that fit in the record
1106 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>
1107 eventData{};
1108 std::copy_n(eventDataBytes.begin(),
1109 std::min(eventDataBytes.size(), eventData.size()),
1110 eventData.begin());
1111
1112 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1113 oemTsEventType{timestamp, eventData});
1114 }
1115
1116 if (recordType >= dynamic_sensors::ipmi::sel::oemEventFirst)
1117 {
1118 // Only keep the bytes that fit in the record
1119 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>
1120 eventData{};
1121 std::copy_n(eventDataBytes.begin(),
1122 std::min(eventDataBytes.size(), eventData.size()),
1123 eventData.begin());
1124
1125 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1126 eventData);
1127 }
1128
Willy Tude54f482021-01-26 15:59:09 -08001129 return ipmi::responseUnspecifiedError();
1130}
1131
Willy Tu11d68892022-01-20 10:37:34 -08001132/*
1133Unused arguments
1134 uint16_t recordID, uint8_t recordType, uint32_t timestamp,
1135 uint16_t generatorID, uint8_t evmRev, uint8_t sensorType, uint8_t sensorNum,
1136 uint8_t eventType, uint8_t eventData1, uint8_t eventData2,
1137 uint8_t eventData3
1138*/
Patrick Williams69b4c282025-03-03 11:19:13 -05001139ipmi::RspType<uint16_t> ipmiStorageAddSELEntry(
1140 uint16_t, uint8_t, uint32_t, uint16_t, uint8_t, uint8_t, uint8_t, uint8_t,
1141 uint8_t, uint8_t, uint8_t)
Willy Tude54f482021-01-26 15:59:09 -08001142{
1143 // Per the IPMI spec, need to cancel any reservation when a SEL entry is
1144 // added
1145 cancelSELReservation();
1146
1147 uint16_t responseID = 0xFFFF;
1148 return ipmi::responseSuccess(responseID);
1149}
1150
Patrick Williams1318a5e2024-08-16 15:19:54 -04001151ipmi::RspType<uint8_t> ipmiStorageClearSEL(
1152 ipmi::Context::ptr ctx, uint16_t reservationID,
1153 const std::array<uint8_t, 3>& clr, uint8_t eraseOperation)
Willy Tude54f482021-01-26 15:59:09 -08001154{
1155 if (!checkSELReservation(reservationID))
1156 {
1157 return ipmi::responseInvalidReservationId();
1158 }
1159
1160 static constexpr std::array<uint8_t, 3> clrExpected = {'C', 'L', 'R'};
1161 if (clr != clrExpected)
1162 {
1163 return ipmi::responseInvalidFieldRequest();
1164 }
1165
1166 // Erasure status cannot be fetched, so always return erasure status as
1167 // `erase completed`.
1168 if (eraseOperation == ipmi::sel::getEraseStatus)
1169 {
1170 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1171 }
1172
1173 // Check that initiate erase is correct
1174 if (eraseOperation != ipmi::sel::initiateErase)
1175 {
1176 return ipmi::responseInvalidFieldRequest();
1177 }
1178
1179 // Per the IPMI spec, need to cancel any reservation when the SEL is
1180 // cleared
1181 cancelSELReservation();
1182
George Liude1420d2025-03-03 15:14:25 +08001183 boost::system::error_code ec =
1184 ipmi::callDbusMethod(ctx, "xyz.openbmc_project.Logging.IPMI",
1185 "/xyz/openbmc_project/Logging/IPMI",
1186 "xyz.openbmc_project.Logging.IPMI", "Clear");
Charles Boyer818bea12021-09-20 16:56:36 -05001187 if (ec)
1188 {
Haicheng Zhang041b3752025-07-14 17:13:45 +08001189 lg2::error("error in clear SEL: {MSG}", "MSG", ec.message());
Charles Boyer818bea12021-09-20 16:56:36 -05001190 return ipmi::responseUnspecifiedError();
1191 }
Willy Tude54f482021-01-26 15:59:09 -08001192
1193 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1194}
1195
Patrick Williams1318a5e2024-08-16 15:19:54 -04001196std::vector<uint8_t> getType8SDRs(
1197 ipmi::sensor::EntityInfoMap::const_iterator& entity, uint16_t recordId)
Harvey Wu05d17c02021-09-15 08:46:59 +08001198{
1199 std::vector<uint8_t> resp;
1200 get_sdr::SensorDataEntityRecord data{};
1201
1202 /* Header */
Harvey Wu05d17c02021-09-15 08:46:59 +08001203 // Based on IPMI Spec v2.0 rev 1.1
George Liuc7a4da52025-08-19 16:20:31 +08001204 data.header.recordId = recordId;
George Liu42247d22025-08-19 10:24:47 +08001205 data.header.sdrVersion = SDR_VERSION;
1206 data.header.recordType = 0x08;
1207 data.header.recordLength = sizeof(data.key) + sizeof(data.body);
Harvey Wu05d17c02021-09-15 08:46:59 +08001208
1209 /* Key */
1210 data.key.containerEntityId = entity->second.containerEntityId;
1211 data.key.containerEntityInstance = entity->second.containerEntityInstance;
George Liuf60be692025-08-19 11:28:42 +08001212 get_sdr::key::setFlags(entity->second.isList, entity->second.isLinked,
1213 data.key);
Harvey Wu05d17c02021-09-15 08:46:59 +08001214 data.key.entityId1 = entity->second.containedEntities[0].first;
1215 data.key.entityInstance1 = entity->second.containedEntities[0].second;
1216
1217 /* Body */
1218 data.body.entityId2 = entity->second.containedEntities[1].first;
1219 data.body.entityInstance2 = entity->second.containedEntities[1].second;
1220 data.body.entityId3 = entity->second.containedEntities[2].first;
1221 data.body.entityInstance3 = entity->second.containedEntities[2].second;
1222 data.body.entityId4 = entity->second.containedEntities[3].first;
1223 data.body.entityInstance4 = entity->second.containedEntities[3].second;
1224
1225 resp.insert(resp.end(), (uint8_t*)&data, ((uint8_t*)&data) + sizeof(data));
1226
1227 return resp;
1228}
1229
Willy Tude54f482021-01-26 15:59:09 -08001230std::vector<uint8_t> getType12SDRs(uint16_t index, uint16_t recordId)
1231{
1232 std::vector<uint8_t> resp;
1233 if (index == 0)
1234 {
Willy Tude54f482021-01-26 15:59:09 -08001235 std::string bmcName = "Basbrd Mgmt Ctlr";
Johnathan Manteycd1c4962021-09-22 12:58:08 -07001236 Type12Record bmc(recordId, 0x20, 0, 0, 0xbf, 0x2e, 1, 0, bmcName);
Willy Tude54f482021-01-26 15:59:09 -08001237 uint8_t* bmcPtr = reinterpret_cast<uint8_t*>(&bmc);
1238 resp.insert(resp.end(), bmcPtr, bmcPtr + sizeof(Type12Record));
1239 }
1240 else if (index == 1)
1241 {
Willy Tude54f482021-01-26 15:59:09 -08001242 std::string meName = "Mgmt Engine";
Johnathan Manteycd1c4962021-09-22 12:58:08 -07001243 Type12Record me(recordId, 0x2c, 6, 0x24, 0x21, 0x2e, 2, 0, meName);
Willy Tude54f482021-01-26 15:59:09 -08001244 uint8_t* mePtr = reinterpret_cast<uint8_t*>(&me);
1245 resp.insert(resp.end(), mePtr, mePtr + sizeof(Type12Record));
1246 }
1247 else
1248 {
Patrick Williams1318a5e2024-08-16 15:19:54 -04001249 throw std::runtime_error(
1250 "getType12SDRs:: Illegal index " + std::to_string(index));
Willy Tude54f482021-01-26 15:59:09 -08001251 }
1252
1253 return resp;
1254}
1255
1256void registerStorageFunctions()
1257{
1258 createTimers();
1259 startMatch();
1260
1261 // <Get FRU Inventory Area Info>
Willy Tud351a722021-08-12 14:33:40 -07001262 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
Willy Tude54f482021-01-26 15:59:09 -08001263 ipmi::storage::cmdGetFruInventoryAreaInfo,
1264 ipmi::Privilege::User, ipmiStorageGetFruInvAreaInfo);
1265 // <READ FRU Data>
1266 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1267 ipmi::storage::cmdReadFruData, ipmi::Privilege::User,
1268 ipmiStorageReadFruData);
1269
1270 // <WRITE FRU Data>
1271 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1272 ipmi::storage::cmdWriteFruData,
1273 ipmi::Privilege::Operator, ipmiStorageWriteFruData);
1274
1275 // <Get SEL Info>
1276 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1277 ipmi::storage::cmdGetSelInfo, ipmi::Privilege::User,
1278 ipmiStorageGetSELInfo);
1279
1280 // <Get SEL Entry>
1281 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1282 ipmi::storage::cmdGetSelEntry, ipmi::Privilege::User,
1283 ipmiStorageGetSELEntry);
1284
1285 // <Add SEL Entry>
1286 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1287 ipmi::storage::cmdAddSelEntry,
1288 ipmi::Privilege::Operator, ipmiStorageAddSELEntry);
1289
1290 // <Clear SEL>
1291 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1292 ipmi::storage::cmdClearSel, ipmi::Privilege::Operator,
1293 ipmiStorageClearSEL);
Willy Tude54f482021-01-26 15:59:09 -08001294}
1295} // namespace storage
1296} // namespace ipmi