blob: 037e0187bf08153b1ee0b376c6249b65706cedda [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>
25#include <boost/process.hpp>
Willy Tude54f482021-01-26 15:59:09 -080026#include <ipmid/api.hpp>
27#include <ipmid/message.hpp>
28#include <ipmid/types.hpp>
George Liude1420d2025-03-03 15:14:25 +080029#include <ipmid/utils.hpp>
George Liude6694e2024-07-17 15:22:25 +080030#include <phosphor-logging/lg2.hpp>
Willy Tude54f482021-01-26 15:59:09 -080031#include <sdbusplus/message/types.hpp>
32#include <sdbusplus/timer.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
41static constexpr bool DEBUG = false;
42
43namespace dynamic_sensors::ipmi::sel
44{
45static const std::filesystem::path selLogDir = "/var/log";
46static const std::string selLogFilename = "ipmi_sel";
47
48static int getFileTimestamp(const std::filesystem::path& file)
49{
50 struct stat st;
51
52 if (stat(file.c_str(), &st) >= 0)
53 {
54 return st.st_mtime;
55 }
56 return ::ipmi::sel::invalidTimeStamp;
57}
58
59namespace erase_time
60{
61static constexpr const char* selEraseTimestamp = "/var/lib/ipmi/sel_erase_time";
62
Willy Tude54f482021-01-26 15:59:09 -080063int get()
64{
65 return getFileTimestamp(selEraseTimestamp);
66}
67} // namespace erase_time
68} // namespace dynamic_sensors::ipmi::sel
69
70namespace ipmi
71{
72
73namespace storage
74{
75
Willy Tude54f482021-01-26 15:59:09 -080076constexpr static const size_t maxFruSdrNameSize = 16;
77using ObjectType =
78 boost::container::flat_map<std::string,
79 boost::container::flat_map<std::string, Value>>;
80using ManagedObjectType =
81 boost::container::flat_map<sdbusplus::message::object_path, ObjectType>;
82using ManagedEntry = std::pair<sdbusplus::message::object_path, ObjectType>;
Willy Tu06ed9da2025-04-07 00:44:20 +000083using Paths = std::vector<std::string>;
Willy Tude54f482021-01-26 15:59:09 -080084
85constexpr static const char* fruDeviceServiceName =
86 "xyz.openbmc_project.FruDevice";
Willy Tude54f482021-01-26 15:59:09 -080087constexpr static const size_t writeTimeoutSeconds = 10;
88constexpr static const char* chassisTypeRackMount = "23";
Zev Weissf38f9d12021-05-21 13:30:16 -050089constexpr static const char* chassisTypeMainServer = "17";
Willy Tude54f482021-01-26 15:59:09 -080090
Willy Tude54f482021-01-26 15:59:09 -080091static std::vector<uint8_t> fruCache;
krishnar4d90b3f02022-11-11 16:18:32 +053092static constexpr uint16_t invalidBus = 0xFFFF;
93static constexpr uint8_t invalidAddr = 0xFF;
Johnathan Manteyb99de182023-12-21 08:28:18 -080094static constexpr uint8_t typeASCIILatin8 = 0xC0;
krishnar4d90b3f02022-11-11 16:18:32 +053095static uint16_t cacheBus = invalidBus;
96static uint8_t cacheAddr = invalidAddr;
Willy Tude54f482021-01-26 15:59:09 -080097static uint8_t lastDevId = 0xFF;
98
krishnar4d90b3f02022-11-11 16:18:32 +053099static uint16_t writeBus = invalidBus;
100static uint8_t writeAddr = invalidAddr;
Willy Tude54f482021-01-26 15:59:09 -0800101
Patrick Williams95655222023-12-05 12:45:02 -0600102std::unique_ptr<sdbusplus::Timer> writeTimer = nullptr;
Patrick Williams5d82f472022-07-22 19:26:53 -0500103static std::vector<sdbusplus::bus::match_t> fruMatches;
Willy Tude54f482021-01-26 15:59:09 -0800104
105ManagedObjectType frus;
106
107// we unfortunately have to build a map of hashes in case there is a
108// collision to verify our dev-id
krishnar4d90b3f02022-11-11 16:18:32 +0530109boost::container::flat_map<uint8_t, std::pair<uint16_t, uint8_t>> deviceHashes;
Willy Tude54f482021-01-26 15:59:09 -0800110void registerStorageFunctions() __attribute__((constructor));
111
Willy Tu48fe64e2022-08-01 23:23:46 +0000112bool writeFru(const std::vector<uint8_t>& fru)
Willy Tude54f482021-01-26 15:59:09 -0800113{
krishnar4d90b3f02022-11-11 16:18:32 +0530114 if (writeBus == invalidBus && writeAddr == invalidAddr)
Willy Tude54f482021-01-26 15:59:09 -0800115 {
116 return true;
117 }
Thang Trand934be92021-12-08 10:13:50 +0700118 lastDevId = 0xFF;
Willy Tude54f482021-01-26 15:59:09 -0800119 std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus();
Patrick Williams5d82f472022-07-22 19:26:53 -0500120 sdbusplus::message_t writeFru = dbus->new_method_call(
Willy Tude54f482021-01-26 15:59:09 -0800121 fruDeviceServiceName, "/xyz/openbmc_project/FruDevice",
122 "xyz.openbmc_project.FruDeviceManager", "WriteFru");
Willy Tu48fe64e2022-08-01 23:23:46 +0000123 writeFru.append(writeBus, writeAddr, fru);
Willy Tude54f482021-01-26 15:59:09 -0800124 try
125 {
Patrick Williams5d82f472022-07-22 19:26:53 -0500126 sdbusplus::message_t writeFruResp = dbus->call(writeFru);
Willy Tude54f482021-01-26 15:59:09 -0800127 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500128 catch (const sdbusplus::exception_t&)
Willy Tude54f482021-01-26 15:59:09 -0800129 {
130 // todo: log sel?
George Liude6694e2024-07-17 15:22:25 +0800131 lg2::error("error writing fru");
Willy Tude54f482021-01-26 15:59:09 -0800132 return false;
133 }
krishnar4d90b3f02022-11-11 16:18:32 +0530134 writeBus = invalidBus;
135 writeAddr = invalidAddr;
Willy Tude54f482021-01-26 15:59:09 -0800136 return true;
137}
138
William A. Kennington III52535622022-11-28 18:28:22 -0800139void writeFruCache()
Willy Tu48fe64e2022-08-01 23:23:46 +0000140{
William A. Kennington III52535622022-11-28 18:28:22 -0800141 writeFru(fruCache);
Willy Tu48fe64e2022-08-01 23:23:46 +0000142}
143
Willy Tude54f482021-01-26 15:59:09 -0800144void createTimers()
145{
Patrick Williams95655222023-12-05 12:45:02 -0600146 writeTimer = std::make_unique<sdbusplus::Timer>(writeFruCache);
Willy Tude54f482021-01-26 15:59:09 -0800147}
148
149void recalculateHashes()
150{
Willy Tude54f482021-01-26 15:59:09 -0800151 deviceHashes.clear();
152 // hash the object paths to create unique device id's. increment on
153 // collision
154 std::hash<std::string> hasher;
155 for (const auto& fru : frus)
156 {
157 auto fruIface = fru.second.find("xyz.openbmc_project.FruDevice");
158 if (fruIface == fru.second.end())
159 {
160 continue;
161 }
162
163 auto busFind = fruIface->second.find("BUS");
164 auto addrFind = fruIface->second.find("ADDRESS");
165 if (busFind == fruIface->second.end() ||
166 addrFind == fruIface->second.end())
167 {
George Liude6694e2024-07-17 15:22:25 +0800168 lg2::info("fru device missing Bus or Address, fru: {FRU}", "FRU",
169 fru.first.str);
Willy Tude54f482021-01-26 15:59:09 -0800170 continue;
171 }
172
krishnar4d90b3f02022-11-11 16:18:32 +0530173 uint16_t fruBus = std::get<uint32_t>(busFind->second);
Willy Tude54f482021-01-26 15:59:09 -0800174 uint8_t fruAddr = std::get<uint32_t>(addrFind->second);
175 auto chassisFind = fruIface->second.find("CHASSIS_TYPE");
176 std::string chassisType;
177 if (chassisFind != fruIface->second.end())
178 {
179 chassisType = std::get<std::string>(chassisFind->second);
180 }
181
182 uint8_t fruHash = 0;
Zev Weissf38f9d12021-05-21 13:30:16 -0500183 if (chassisType.compare(chassisTypeRackMount) != 0 &&
184 chassisType.compare(chassisTypeMainServer) != 0)
Willy Tude54f482021-01-26 15:59:09 -0800185 {
186 fruHash = hasher(fru.first.str);
187 // can't be 0xFF based on spec, and 0 is reserved for baseboard
188 if (fruHash == 0 || fruHash == 0xFF)
189 {
190 fruHash = 1;
191 }
192 }
krishnar4d90b3f02022-11-11 16:18:32 +0530193 std::pair<uint16_t, uint8_t> newDev(fruBus, fruAddr);
Willy Tude54f482021-01-26 15:59:09 -0800194
195 bool emplacePassed = false;
196 while (!emplacePassed)
197 {
198 auto resp = deviceHashes.emplace(fruHash, newDev);
199 emplacePassed = resp.second;
200 if (!emplacePassed)
201 {
202 fruHash++;
203 // can't be 0xFF based on spec, and 0 is reserved for
204 // baseboard
205 if (fruHash == 0XFF)
206 {
207 fruHash = 0x1;
208 }
209 }
210 }
211 }
212}
213
Willy Tu11d68892022-01-20 10:37:34 -0800214void replaceCacheFru(
215 const std::shared_ptr<sdbusplus::asio::connection>& bus,
216 boost::asio::yield_context& yield,
217 [[maybe_unused]] const std::optional<std::string>& path = std::nullopt)
Willy Tude54f482021-01-26 15:59:09 -0800218{
219 boost::system::error_code ec;
220
221 frus = bus->yield_method_call<ManagedObjectType>(
222 yield, ec, fruDeviceServiceName, "/",
223 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
224 if (ec)
225 {
George Liude6694e2024-07-17 15:22:25 +0800226 lg2::error("GetMangagedObjects for replaceCacheFru failed: {ERROR}",
227 "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800228
229 return;
230 }
231 recalculateHashes();
232}
233
Patrick Williams69b4c282025-03-03 11:19:13 -0500234std::pair<ipmi::Cc, std::vector<uint8_t>> getFru(ipmi::Context::ptr ctx,
235 uint8_t devId)
Willy Tude54f482021-01-26 15:59:09 -0800236{
237 if (lastDevId == devId && devId != 0xFF)
238 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000239 return {ipmi::ccSuccess, fruCache};
Willy Tude54f482021-01-26 15:59:09 -0800240 }
241
Willy Tude54f482021-01-26 15:59:09 -0800242 auto deviceFind = deviceHashes.find(devId);
243 if (deviceFind == deviceHashes.end())
244 {
George Liu879c1d82025-07-03 09:36:57 +0800245 return {ipmi::ccSensorInvalid, {}};
Willy Tude54f482021-01-26 15:59:09 -0800246 }
247
Willy Tude54f482021-01-26 15:59:09 -0800248 cacheBus = deviceFind->second.first;
249 cacheAddr = deviceFind->second.second;
250
251 boost::system::error_code ec;
George Liude1420d2025-03-03 15:14:25 +0800252 std::vector<uint8_t> fru = ipmi::callDbusMethod<std::vector<uint8_t>>(
253 ctx, ec, fruDeviceServiceName, "/xyz/openbmc_project/FruDevice",
254 "xyz.openbmc_project.FruDeviceManager", "GetRawFru", cacheBus,
255 cacheAddr);
Willy Tude54f482021-01-26 15:59:09 -0800256
Willy Tude54f482021-01-26 15:59:09 -0800257 if (ec)
258 {
George Liude6694e2024-07-17 15:22:25 +0800259 lg2::error("Couldn't get raw fru: {ERROR}", "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800260
krishnar4d90b3f02022-11-11 16:18:32 +0530261 cacheBus = invalidBus;
262 cacheAddr = invalidAddr;
Willy Tu48fe64e2022-08-01 23:23:46 +0000263 return {ipmi::ccResponseError, {}};
Willy Tude54f482021-01-26 15:59:09 -0800264 }
265
Willy Tu48fe64e2022-08-01 23:23:46 +0000266 fruCache.clear();
Willy Tude54f482021-01-26 15:59:09 -0800267 lastDevId = devId;
Willy Tu48fe64e2022-08-01 23:23:46 +0000268 fruCache = fru;
269
270 return {ipmi::ccSuccess, fru};
Willy Tude54f482021-01-26 15:59:09 -0800271}
272
273void writeFruIfRunning()
274{
275 if (!writeTimer->isRunning())
276 {
277 return;
278 }
279 writeTimer->stop();
Willy Tu48fe64e2022-08-01 23:23:46 +0000280 writeFruCache();
Willy Tude54f482021-01-26 15:59:09 -0800281}
282
283void startMatch(void)
284{
285 if (fruMatches.size())
286 {
287 return;
288 }
289
290 fruMatches.reserve(2);
291
292 auto bus = getSdBus();
Patrick Williams1318a5e2024-08-16 15:19:54 -0400293 fruMatches.emplace_back(
294 *bus,
295 "type='signal',arg0path='/xyz/openbmc_project/"
296 "FruDevice/',member='InterfacesAdded'",
297 [](sdbusplus::message_t& message) {
298 sdbusplus::message::object_path path;
299 ObjectType object;
300 try
301 {
302 message.read(path, object);
303 }
304 catch (const sdbusplus::exception_t&)
305 {
306 return;
307 }
308 auto findType = object.find("xyz.openbmc_project.FruDevice");
309 if (findType == object.end())
310 {
311 return;
312 }
313 writeFruIfRunning();
314 frus[path] = object;
315 recalculateHashes();
316 lastDevId = 0xFF;
317 });
Willy Tude54f482021-01-26 15:59:09 -0800318
Patrick Williams1318a5e2024-08-16 15:19:54 -0400319 fruMatches.emplace_back(
320 *bus,
321 "type='signal',arg0path='/xyz/openbmc_project/"
322 "FruDevice/',member='InterfacesRemoved'",
323 [](sdbusplus::message_t& message) {
324 sdbusplus::message::object_path path;
325 std::set<std::string> interfaces;
326 try
327 {
328 message.read(path, interfaces);
329 }
330 catch (const sdbusplus::exception_t&)
331 {
332 return;
333 }
334 auto findType = interfaces.find("xyz.openbmc_project.FruDevice");
335 if (findType == interfaces.end())
336 {
337 return;
338 }
339 writeFruIfRunning();
340 frus.erase(path);
341 recalculateHashes();
342 lastDevId = 0xFF;
343 });
Willy Tude54f482021-01-26 15:59:09 -0800344
345 // call once to populate
Ed Tanous98605052025-02-13 16:57:13 -0800346 boost::asio::spawn(
347 *getIoContext(),
348 [](boost::asio::yield_context yield) {
349 replaceCacheFru(getSdBus(), yield);
350 },
351 boost::asio::detached);
Willy Tude54f482021-01-26 15:59:09 -0800352}
353
354/** @brief implements the read FRU data command
355 * @param fruDeviceId - FRU Device ID
356 * @param fruInventoryOffset - FRU Inventory Offset to write
357 * @param countToRead - Count to read
358 *
359 * @returns ipmi completion code plus response data
360 * - countWritten - Count written
361 */
362ipmi::RspType<uint8_t, // Count
363 std::vector<uint8_t> // Requested data
364 >
365 ipmiStorageReadFruData(ipmi::Context::ptr ctx, uint8_t fruDeviceId,
366 uint16_t fruInventoryOffset, uint8_t countToRead)
367{
368 if (fruDeviceId == 0xFF)
369 {
370 return ipmi::responseInvalidFieldRequest();
371 }
372
Willy Tu48fe64e2022-08-01 23:23:46 +0000373 auto [status, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800374 if (status != ipmi::ccSuccess)
375 {
376 return ipmi::response(status);
377 }
378
379 size_t fromFruByteLen = 0;
Willy Tu48fe64e2022-08-01 23:23:46 +0000380 if (countToRead + fruInventoryOffset < fru.size())
Willy Tude54f482021-01-26 15:59:09 -0800381 {
382 fromFruByteLen = countToRead;
383 }
Willy Tu48fe64e2022-08-01 23:23:46 +0000384 else if (fru.size() > fruInventoryOffset)
Willy Tude54f482021-01-26 15:59:09 -0800385 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000386 fromFruByteLen = fru.size() - fruInventoryOffset;
Willy Tude54f482021-01-26 15:59:09 -0800387 }
388 else
389 {
390 return ipmi::responseReqDataLenExceeded();
391 }
392
393 std::vector<uint8_t> requestedData;
394
Willy Tu48fe64e2022-08-01 23:23:46 +0000395 requestedData.insert(requestedData.begin(),
396 fru.begin() + fruInventoryOffset,
397 fru.begin() + fruInventoryOffset + fromFruByteLen);
Willy Tude54f482021-01-26 15:59:09 -0800398
399 return ipmi::responseSuccess(static_cast<uint8_t>(requestedData.size()),
400 requestedData);
401}
402
403/** @brief implements the write FRU data command
404 * @param fruDeviceId - FRU Device ID
405 * @param fruInventoryOffset - FRU Inventory Offset to write
406 * @param dataToWrite - Data to write
407 *
408 * @returns ipmi completion code plus response data
409 * - countWritten - Count written
410 */
Patrick Williams1318a5e2024-08-16 15:19:54 -0400411ipmi::RspType<uint8_t> ipmiStorageWriteFruData(
412 ipmi::Context::ptr ctx, uint8_t fruDeviceId, uint16_t fruInventoryOffset,
413 std::vector<uint8_t>& dataToWrite)
Willy Tude54f482021-01-26 15:59:09 -0800414{
415 if (fruDeviceId == 0xFF)
416 {
417 return ipmi::responseInvalidFieldRequest();
418 }
419
420 size_t writeLen = dataToWrite.size();
421
Willy Tu48fe64e2022-08-01 23:23:46 +0000422 auto [status, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800423 if (status != ipmi::ccSuccess)
424 {
425 return ipmi::response(status);
426 }
427 size_t lastWriteAddr = fruInventoryOffset + writeLen;
Willy Tu48fe64e2022-08-01 23:23:46 +0000428 if (fru.size() < lastWriteAddr)
Willy Tude54f482021-01-26 15:59:09 -0800429 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000430 fru.resize(fruInventoryOffset + writeLen);
Willy Tude54f482021-01-26 15:59:09 -0800431 }
432
433 std::copy(dataToWrite.begin(), dataToWrite.begin() + writeLen,
Willy Tu48fe64e2022-08-01 23:23:46 +0000434 fru.begin() + fruInventoryOffset);
Willy Tude54f482021-01-26 15:59:09 -0800435
436 bool atEnd = false;
437
Willy Tu48fe64e2022-08-01 23:23:46 +0000438 if (fru.size() >= sizeof(FRUHeader))
Willy Tude54f482021-01-26 15:59:09 -0800439 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000440 FRUHeader* header = reinterpret_cast<FRUHeader*>(fru.data());
Willy Tude54f482021-01-26 15:59:09 -0800441
442 size_t areaLength = 0;
443 size_t lastRecordStart = std::max(
444 {header->internalOffset, header->chassisOffset, header->boardOffset,
445 header->productOffset, header->multiRecordOffset});
446 lastRecordStart *= 8; // header starts in are multiples of 8 bytes
447
448 if (header->multiRecordOffset)
449 {
450 // This FRU has a MultiRecord Area
451 uint8_t endOfList = 0;
452 // Walk the MultiRecord headers until the last record
453 while (!endOfList)
454 {
455 // The MSB in the second byte of the MultiRecord header signals
456 // "End of list"
Willy Tu48fe64e2022-08-01 23:23:46 +0000457 endOfList = fru[lastRecordStart + 1] & 0x80;
Willy Tude54f482021-01-26 15:59:09 -0800458 // Third byte in the MultiRecord header is the length
Willy Tu48fe64e2022-08-01 23:23:46 +0000459 areaLength = fru[lastRecordStart + 2];
Willy Tude54f482021-01-26 15:59:09 -0800460 // This length is in bytes (not 8 bytes like other headers)
461 areaLength += 5; // The length omits the 5 byte header
462 if (!endOfList)
463 {
464 // Next MultiRecord header
465 lastRecordStart += areaLength;
466 }
467 }
468 }
469 else
470 {
471 // This FRU does not have a MultiRecord Area
472 // Get the length of the area in multiples of 8 bytes
473 if (lastWriteAddr > (lastRecordStart + 1))
474 {
475 // second byte in record area is the length
Willy Tu48fe64e2022-08-01 23:23:46 +0000476 areaLength = fru[lastRecordStart + 1];
Willy Tude54f482021-01-26 15:59:09 -0800477 areaLength *= 8; // it is in multiples of 8 bytes
478 }
479 }
480 if (lastWriteAddr >= (areaLength + lastRecordStart))
481 {
482 atEnd = true;
483 }
484 }
485 uint8_t countWritten = 0;
486
487 writeBus = cacheBus;
488 writeAddr = cacheAddr;
489 if (atEnd)
490 {
491 // cancel timer, we're at the end so might as well send it
492 writeTimer->stop();
Willy Tu48fe64e2022-08-01 23:23:46 +0000493 if (!writeFru(fru))
Willy Tude54f482021-01-26 15:59:09 -0800494 {
495 return ipmi::responseInvalidFieldRequest();
496 }
Willy Tu48fe64e2022-08-01 23:23:46 +0000497 countWritten = std::min(fru.size(), static_cast<size_t>(0xFF));
Willy Tude54f482021-01-26 15:59:09 -0800498 }
499 else
500 {
Sui Chen548d1a22022-09-14 07:41:17 -0700501 fruCache = fru; // Write-back
Willy Tude54f482021-01-26 15:59:09 -0800502 // start a timer, if no further data is sent to check to see if it is
503 // valid
504 writeTimer->start(std::chrono::duration_cast<std::chrono::microseconds>(
505 std::chrono::seconds(writeTimeoutSeconds)));
506 countWritten = 0;
507 }
508
509 return ipmi::responseSuccess(countWritten);
510}
511
512/** @brief implements the get FRU inventory area info command
513 * @param fruDeviceId - FRU Device ID
514 *
515 * @returns IPMI completion code plus response data
516 * - inventorySize - Number of possible allocation units
517 * - accessType - Allocation unit size in bytes.
518 */
519ipmi::RspType<uint16_t, // inventorySize
520 uint8_t> // accessType
521 ipmiStorageGetFruInvAreaInfo(ipmi::Context::ptr ctx, uint8_t fruDeviceId)
522{
523 if (fruDeviceId == 0xFF)
524 {
525 return ipmi::responseInvalidFieldRequest();
526 }
527
Willy Tu48fe64e2022-08-01 23:23:46 +0000528 auto [ret, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800529 if (ret != ipmi::ccSuccess)
530 {
531 return ipmi::response(ret);
532 }
533
534 constexpr uint8_t accessType =
535 static_cast<uint8_t>(GetFRUAreaAccessType::byte);
536
Willy Tu48fe64e2022-08-01 23:23:46 +0000537 return ipmi::responseSuccess(fru.size(), accessType);
Willy Tude54f482021-01-26 15:59:09 -0800538}
539
George Liu23c868c2025-07-04 09:31:35 +0800540ipmi::Cc getFruSdrCount(ipmi::Context::ptr, size_t& count)
Willy Tude54f482021-01-26 15:59:09 -0800541{
542 count = deviceHashes.size();
George Liue8a97bd2024-12-05 17:26:46 +0800543 return ipmi::ccSuccess;
Willy Tude54f482021-01-26 15:59:09 -0800544}
545
George Liu23c868c2025-07-04 09:31:35 +0800546ipmi::Cc getFruSdrs([[maybe_unused]] ipmi::Context::ptr ctx, size_t index,
547 get_sdr::SensorDataFruRecord& resp)
Willy Tude54f482021-01-26 15:59:09 -0800548{
549 if (deviceHashes.size() < index)
550 {
George Liu879c1d82025-07-03 09:36:57 +0800551 return ipmi::ccInvalidFieldRequest;
Willy Tude54f482021-01-26 15:59:09 -0800552 }
553 auto device = deviceHashes.begin() + index;
krishnar4d90b3f02022-11-11 16:18:32 +0530554 uint16_t& bus = device->second.first;
Willy Tude54f482021-01-26 15:59:09 -0800555 uint8_t& address = device->second.second;
556
557 boost::container::flat_map<std::string, Value>* fruData = nullptr;
Patrick Williams1318a5e2024-08-16 15:19:54 -0400558 auto fru = std::find_if(
559 frus.begin(), frus.end(),
560 [bus, address, &fruData](ManagedEntry& entry) {
561 auto findFruDevice =
562 entry.second.find("xyz.openbmc_project.FruDevice");
563 if (findFruDevice == entry.second.end())
564 {
565 return false;
566 }
567 fruData = &(findFruDevice->second);
568 auto findBus = findFruDevice->second.find("BUS");
569 auto findAddress = findFruDevice->second.find("ADDRESS");
570 if (findBus == findFruDevice->second.end() ||
571 findAddress == findFruDevice->second.end())
572 {
573 return false;
574 }
575 if (std::get<uint32_t>(findBus->second) != bus)
576 {
577 return false;
578 }
579 if (std::get<uint32_t>(findAddress->second) != address)
580 {
581 return false;
582 }
583 return true;
584 });
Willy Tude54f482021-01-26 15:59:09 -0800585 if (fru == frus.end())
586 {
George Liu879c1d82025-07-03 09:36:57 +0800587 return ipmi::ccResponseError;
Willy Tude54f482021-01-26 15:59:09 -0800588 }
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530589 std::string name;
Willy Tu06ed9da2025-04-07 00:44:20 +0000590 uint8_t entityID = 0;
591 uint8_t entityInstance = 0x1;
Willy Tude54f482021-01-26 15:59:09 -0800592
593#ifdef USING_ENTITY_MANAGER_DECORATORS
Willy Tude54f482021-01-26 15:59:09 -0800594 boost::system::error_code ec;
Willy Tude54f482021-01-26 15:59:09 -0800595
Willy Tu06ed9da2025-04-07 00:44:20 +0000596 Paths subtreePaths = ipmi::callDbusMethod<Paths>(
597 ctx, ec, "xyz.openbmc_project.ObjectMapper",
598 "/xyz/openbmc_project/object_mapper",
599 "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths",
600 "/xyz/openbmc_project/inventory", 0,
601 std::array<const char*, 2>{
602 "xyz.openbmc_project.Inventory.Decorator.I2CDevice",
603 "xyz.openbmc_project.Inventory.Decorator.Ipmi",
604 });
Willy Tude54f482021-01-26 15:59:09 -0800605 if (ec)
606 {
Willy Tu06ed9da2025-04-07 00:44:20 +0000607 lg2::error(
608 "GetSubTreePaths for ipmiStorageGetFruInvAreaInfo failed: {ERROR}",
609 "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800610 return ipmi::ccResponseError;
611 }
612
Willy Tu06ed9da2025-04-07 00:44:20 +0000613 bool foundDevice = false;
614 for (const auto& path : subtreePaths)
615 {
616 ipmi::PropertyMap i2cProperties;
617 boost::system::error_code ec = ipmi::getAllDbusProperties(
618 ctx, "xyz.openbmc_project.EntityManager", path,
619 "xyz.openbmc_project.Inventory.Decorator.I2CDevice", i2cProperties);
620 if (ec)
621 {
622 continue;
623 }
624
625 std::optional<uint64_t> maybeBus;
626 std::optional<uint64_t> maybeAddress;
627 std::optional<std::string> maybeName;
628 for (const auto& [key, val] : i2cProperties)
629 {
630 if (key == "Bus")
Patrick Williams1318a5e2024-08-16 15:19:54 -0400631 {
Willy Tu06ed9da2025-04-07 00:44:20 +0000632 maybeBus = std::get<uint64_t>(val);
Patrick Williams1318a5e2024-08-16 15:19:54 -0400633 }
Willy Tu06ed9da2025-04-07 00:44:20 +0000634 else if (key == "Address")
Patrick Williams1318a5e2024-08-16 15:19:54 -0400635 {
Willy Tu06ed9da2025-04-07 00:44:20 +0000636 maybeAddress = std::get<uint64_t>(val);
Patrick Williams1318a5e2024-08-16 15:19:54 -0400637 }
Willy Tu06ed9da2025-04-07 00:44:20 +0000638 else if (key == "Name")
Patrick Williams1318a5e2024-08-16 15:19:54 -0400639 {
Willy Tu06ed9da2025-04-07 00:44:20 +0000640 maybeName = std::get<std::string>(val);
Patrick Williams1318a5e2024-08-16 15:19:54 -0400641 }
Willy Tu06ed9da2025-04-07 00:44:20 +0000642 }
643 if (!maybeBus || *maybeBus != bus || !maybeAddress ||
644 *maybeAddress != address)
645 {
646 continue;
647 }
648 // At this point we found the device entry and will populate the
649 // information if exist.
650 foundDevice = true;
Willy Tude54f482021-01-26 15:59:09 -0800651
Willy Tu06ed9da2025-04-07 00:44:20 +0000652 if (maybeName.has_value())
653 {
654 name = *maybeName;
655 }
656
657 ipmi::PropertyMap entityData;
658 ec = ipmi::getAllDbusProperties(
659 ctx, "xyz.openbmc_project.EntityManager", path,
660 "xyz.openbmc_project.Inventory.Decorator.Ipmi", entityData);
661 if (!ec)
662 {
663 for (const auto& [key, val] : entityData)
Patrick Williams1318a5e2024-08-16 15:19:54 -0400664 {
Willy Tu06ed9da2025-04-07 00:44:20 +0000665 if (key == "EntityId")
666 {
667 entityID = std::get<uint64_t>(val);
668 }
669 else if (key == "EntityInstance")
670 {
671 entityInstance = std::get<uint64_t>(val);
672 }
Patrick Williams1318a5e2024-08-16 15:19:54 -0400673 }
Willy Tu06ed9da2025-04-07 00:44:20 +0000674 }
675 break;
676 }
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530677
Willy Tu06ed9da2025-04-07 00:44:20 +0000678 if (!foundDevice)
Willy Tude54f482021-01-26 15:59:09 -0800679 {
680 if constexpr (DEBUG)
681 {
682 std::fprintf(stderr, "Ipmi or FruDevice Decorator interface "
683 "not found for Fru\n");
684 }
685 }
Willy Tude54f482021-01-26 15:59:09 -0800686#endif
687
Alexander Hansenea46f3c2023-09-04 11:27:54 +0200688 std::vector<std::string> nameProperties = {
Jitendra Tripathy1d881b52025-05-16 10:08:15 +0000689 "BOARD_PRODUCT_NAME", "PRODUCT_PRODUCT_NAME", "PRODUCT_PART_NUMBER",
Alexander Hansenea46f3c2023-09-04 11:27:54 +0200690 "BOARD_PART_NUMBER", "PRODUCT_MANUFACTURER", "BOARD_MANUFACTURER",
691 "PRODUCT_SERIAL_NUMBER", "BOARD_SERIAL_NUMBER"};
692
693 for (const std::string& prop : nameProperties)
694 {
695 auto findProp = fruData->find(prop);
696 if (findProp != fruData->end())
697 {
698 name = std::get<std::string>(findProp->second);
699 break;
700 }
701 }
702
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530703 if (name.empty())
Willy Tude54f482021-01-26 15:59:09 -0800704 {
705 name = "UNKNOWN";
706 }
707 if (name.size() > maxFruSdrNameSize)
708 {
709 name = name.substr(0, maxFruSdrNameSize);
710 }
711 size_t sizeDiff = maxFruSdrNameSize - name.size();
712
713 resp.header.record_id_lsb = 0x0; // calling code is to implement these
714 resp.header.record_id_msb = 0x0;
715 resp.header.sdr_version = ipmiSdrVersion;
716 resp.header.record_type = get_sdr::SENSOR_DATA_FRU_RECORD;
717 resp.header.record_length = sizeof(resp.body) + sizeof(resp.key) - sizeDiff;
718 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();
744 if (boost::starts_with(filename,
745 dynamic_sensors::ipmi::sel::selLogFilename))
746 {
747 // If we find an ipmi_sel log file, save the path
Patrick Williams1318a5e2024-08-16 15:19:54 -0400748 selLogFiles.emplace_back(
749 dynamic_sensors::ipmi::sel::selLogDir / filename);
Willy Tude54f482021-01-26 15:59:09 -0800750 }
751 }
752 // As the log files rotate, they are appended with a ".#" that is higher for
753 // the older logs. Since we don't expect more than 10 log files, we
754 // can just sort the list to get them in order from newest to oldest
755 std::sort(selLogFiles.begin(), selLogFiles.end());
756
757 return !selLogFiles.empty();
758}
759
760static int countSELEntries()
761{
762 // Get the list of ipmi_sel log files
763 std::vector<std::filesystem::path> selLogFiles;
764 if (!getSELLogFiles(selLogFiles))
765 {
766 return 0;
767 }
768 int numSELEntries = 0;
769 // Loop through each log file and count the number of logs
770 for (const std::filesystem::path& file : selLogFiles)
771 {
772 std::ifstream logStream(file);
773 if (!logStream.is_open())
774 {
775 continue;
776 }
777
778 std::string line;
779 while (std::getline(logStream, line))
780 {
781 numSELEntries++;
782 }
783 }
784 return numSELEntries;
785}
786
787static bool findSELEntry(const int recordID,
788 const std::vector<std::filesystem::path>& selLogFiles,
789 std::string& entry)
790{
791 // Record ID is the first entry field following the timestamp. It is
792 // preceded by a space and followed by a comma
793 std::string search = " " + std::to_string(recordID) + ",";
794
795 // Loop through the ipmi_sel log entries
796 for (const std::filesystem::path& file : selLogFiles)
797 {
798 std::ifstream logStream(file);
799 if (!logStream.is_open())
800 {
801 continue;
802 }
803
804 while (std::getline(logStream, entry))
805 {
806 // Check if the record ID matches
807 if (entry.find(search) != std::string::npos)
808 {
809 return true;
810 }
811 }
812 }
813 return false;
814}
815
Patrick Williams69b4c282025-03-03 11:19:13 -0500816static uint16_t getNextRecordID(
817 const uint16_t recordID,
818 const std::vector<std::filesystem::path>& selLogFiles)
Willy Tude54f482021-01-26 15:59:09 -0800819{
820 uint16_t nextRecordID = recordID + 1;
821 std::string entry;
822 if (findSELEntry(nextRecordID, selLogFiles, entry))
823 {
824 return nextRecordID;
825 }
826 else
827 {
828 return ipmi::sel::lastEntry;
829 }
830}
831
832static int fromHexStr(const std::string& hexStr, std::vector<uint8_t>& data)
833{
834 for (unsigned int i = 0; i < hexStr.size(); i += 2)
835 {
836 try
837 {
838 data.push_back(static_cast<uint8_t>(
839 std::stoul(hexStr.substr(i, 2), nullptr, 16)));
840 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500841 catch (const std::invalid_argument& e)
Willy Tude54f482021-01-26 15:59:09 -0800842 {
George Liude6694e2024-07-17 15:22:25 +0800843 lg2::error("Invalid argument: {ERROR}", "ERROR", e);
Willy Tude54f482021-01-26 15:59:09 -0800844 return -1;
845 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500846 catch (const std::out_of_range& e)
Willy Tude54f482021-01-26 15:59:09 -0800847 {
George Liude6694e2024-07-17 15:22:25 +0800848 lg2::error("Out of range: {ERROR}", "ERROR", e);
Willy Tude54f482021-01-26 15:59:09 -0800849 return -1;
850 }
851 }
852 return 0;
853}
854
855ipmi::RspType<uint8_t, // SEL version
856 uint16_t, // SEL entry count
857 uint16_t, // free space
858 uint32_t, // last add timestamp
859 uint32_t, // last erase timestamp
860 uint8_t> // operation support
861 ipmiStorageGetSELInfo()
862{
863 constexpr uint8_t selVersion = ipmi::sel::selVersion;
864 uint16_t entries = countSELEntries();
865 uint32_t addTimeStamp = dynamic_sensors::ipmi::sel::getFileTimestamp(
866 dynamic_sensors::ipmi::sel::selLogDir /
867 dynamic_sensors::ipmi::sel::selLogFilename);
868 uint32_t eraseTimeStamp = dynamic_sensors::ipmi::sel::erase_time::get();
869 constexpr uint8_t operationSupport =
870 dynamic_sensors::ipmi::sel::selOperationSupport;
871 constexpr uint16_t freeSpace =
872 0xffff; // Spec indicates that more than 64kB is free
873
874 return ipmi::responseSuccess(selVersion, entries, freeSpace, addTimeStamp,
875 eraseTimeStamp, operationSupport);
876}
877
878using systemEventType = std::tuple<
879 uint32_t, // Timestamp
880 uint16_t, // Generator ID
881 uint8_t, // EvM Rev
882 uint8_t, // Sensor Type
883 uint8_t, // Sensor Number
884 uint7_t, // Event Type
885 bool, // Event Direction
886 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>>; // Event
887 // Data
888using oemTsEventType = std::tuple<
889 uint32_t, // Timestamp
890 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>>; // Event
891 // Data
892using oemEventType =
893 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>; // Event Data
894
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500895ipmi::RspType<uint16_t, // Next Record ID
896 uint16_t, // Record ID
897 uint8_t, // Record Type
Willy Tude54f482021-01-26 15:59:09 -0800898 std::variant<systemEventType, oemTsEventType,
899 oemEventType>> // Record Content
900 ipmiStorageGetSELEntry(uint16_t reservationID, uint16_t targetID,
901 uint8_t offset, uint8_t size)
902{
903 // Only support getting the entire SEL record. If a partial size or non-zero
904 // offset is requested, return an error
905 if (offset != 0 || size != ipmi::sel::entireRecord)
906 {
907 return ipmi::responseRetBytesUnavailable();
908 }
909
910 // Check the reservation ID if one is provided or required (only if the
911 // offset is non-zero)
912 if (reservationID != 0 || offset != 0)
913 {
914 if (!checkSELReservation(reservationID))
915 {
916 return ipmi::responseInvalidReservationId();
917 }
918 }
919
920 // Get the ipmi_sel log files
921 std::vector<std::filesystem::path> selLogFiles;
922 if (!getSELLogFiles(selLogFiles))
923 {
924 return ipmi::responseSensorInvalid();
925 }
926
927 std::string targetEntry;
928
929 if (targetID == ipmi::sel::firstEntry)
930 {
931 // The first entry will be at the top of the oldest log file
932 std::ifstream logStream(selLogFiles.back());
933 if (!logStream.is_open())
934 {
935 return ipmi::responseUnspecifiedError();
936 }
937
938 if (!std::getline(logStream, targetEntry))
939 {
940 return ipmi::responseUnspecifiedError();
941 }
942 }
943 else if (targetID == ipmi::sel::lastEntry)
944 {
945 // The last entry will be at the bottom of the newest log file
946 std::ifstream logStream(selLogFiles.front());
947 if (!logStream.is_open())
948 {
949 return ipmi::responseUnspecifiedError();
950 }
951
952 std::string line;
953 while (std::getline(logStream, line))
954 {
955 targetEntry = line;
956 }
957 }
958 else
959 {
960 if (!findSELEntry(targetID, selLogFiles, targetEntry))
961 {
962 return ipmi::responseSensorInvalid();
963 }
964 }
965
966 // The format of the ipmi_sel message is "<Timestamp>
967 // <ID>,<Type>,<EventData>,[<Generator ID>,<Path>,<Direction>]".
968 // First get the Timestamp
969 size_t space = targetEntry.find_first_of(" ");
970 if (space == std::string::npos)
971 {
972 return ipmi::responseUnspecifiedError();
973 }
974 std::string entryTimestamp = targetEntry.substr(0, space);
975 // Then get the log contents
976 size_t entryStart = targetEntry.find_first_not_of(" ", space);
977 if (entryStart == std::string::npos)
978 {
979 return ipmi::responseUnspecifiedError();
980 }
981 std::string_view entry(targetEntry);
982 entry.remove_prefix(entryStart);
983 // Use split to separate the entry into its fields
984 std::vector<std::string> targetEntryFields;
985 boost::split(targetEntryFields, entry, boost::is_any_of(","),
986 boost::token_compress_on);
987 if (targetEntryFields.size() < 3)
988 {
989 return ipmi::responseUnspecifiedError();
990 }
991 std::string& recordIDStr = targetEntryFields[0];
992 std::string& recordTypeStr = targetEntryFields[1];
993 std::string& eventDataStr = targetEntryFields[2];
994
995 uint16_t recordID;
996 uint8_t recordType;
997 try
998 {
999 recordID = std::stoul(recordIDStr);
1000 recordType = std::stoul(recordTypeStr, nullptr, 16);
1001 }
1002 catch (const std::invalid_argument&)
1003 {
1004 return ipmi::responseUnspecifiedError();
1005 }
1006 uint16_t nextRecordID = getNextRecordID(recordID, selLogFiles);
1007 std::vector<uint8_t> eventDataBytes;
1008 if (fromHexStr(eventDataStr, eventDataBytes) < 0)
1009 {
1010 return ipmi::responseUnspecifiedError();
1011 }
1012
1013 if (recordType == dynamic_sensors::ipmi::sel::systemEvent)
1014 {
1015 // Get the timestamp
1016 std::tm timeStruct = {};
1017 std::istringstream entryStream(entryTimestamp);
1018
1019 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1020 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1021 {
Willy Tu7bb412f2023-09-25 11:30:45 -07001022 timeStruct.tm_isdst = -1;
Willy Tude54f482021-01-26 15:59:09 -08001023 timestamp = std::mktime(&timeStruct);
1024 }
1025
1026 // Set the event message revision
1027 uint8_t evmRev = dynamic_sensors::ipmi::sel::eventMsgRev;
1028
1029 uint16_t generatorID = 0;
1030 uint8_t sensorType = 0;
1031 uint16_t sensorAndLun = 0;
1032 uint8_t sensorNum = 0xFF;
1033 uint7_t eventType = 0;
1034 bool eventDir = 0;
1035 // System type events should have six fields
1036 if (targetEntryFields.size() >= 6)
1037 {
1038 std::string& generatorIDStr = targetEntryFields[3];
1039 std::string& sensorPath = targetEntryFields[4];
1040 std::string& eventDirStr = targetEntryFields[5];
1041
1042 // Get the generator ID
1043 try
1044 {
1045 generatorID = std::stoul(generatorIDStr, nullptr, 16);
1046 }
1047 catch (const std::invalid_argument&)
1048 {
Haicheng Zhang041b3752025-07-14 17:13:45 +08001049 lg2::error("Invalid Generator ID");
Willy Tude54f482021-01-26 15:59:09 -08001050 }
1051
1052 // Get the sensor type, sensor number, and event type for the sensor
1053 sensorType = getSensorTypeFromPath(sensorPath);
1054 sensorAndLun = getSensorNumberFromPath(sensorPath);
1055 sensorNum = static_cast<uint8_t>(sensorAndLun);
Harvey.Wu4376cdf2021-11-16 19:40:55 +08001056 if ((generatorID & 0x0001) == 0)
1057 {
1058 // IPMB Address
1059 generatorID |= sensorAndLun & 0x0300;
1060 }
1061 else
1062 {
1063 // system software
1064 generatorID |= sensorAndLun >> 8;
1065 }
Willy Tude54f482021-01-26 15:59:09 -08001066 eventType = getSensorEventTypeFromPath(sensorPath);
1067
1068 // Get the event direction
1069 try
1070 {
1071 eventDir = std::stoul(eventDirStr) ? 0 : 1;
1072 }
1073 catch (const std::invalid_argument&)
1074 {
Haicheng Zhang041b3752025-07-14 17:13:45 +08001075 lg2::error("Invalid Event Direction");
Willy Tude54f482021-01-26 15:59:09 -08001076 }
1077 }
1078
1079 // Only keep the eventData bytes that fit in the record
1080 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>
1081 eventData{};
1082 std::copy_n(eventDataBytes.begin(),
1083 std::min(eventDataBytes.size(), eventData.size()),
1084 eventData.begin());
1085
1086 return ipmi::responseSuccess(
1087 nextRecordID, recordID, recordType,
1088 systemEventType{timestamp, generatorID, evmRev, sensorType,
1089 sensorNum, eventType, eventDir, eventData});
1090 }
1091
Thang Trane70c59b2023-09-21 13:54:28 +07001092 if (recordType >= dynamic_sensors::ipmi::sel::oemTsEventFirst &&
1093 recordType <= dynamic_sensors::ipmi::sel::oemTsEventLast)
1094 {
1095 // Get the timestamp
1096 std::tm timeStruct = {};
1097 std::istringstream entryStream(entryTimestamp);
1098
1099 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1100 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1101 {
1102 timeStruct.tm_isdst = -1;
1103 timestamp = std::mktime(&timeStruct);
1104 }
1105
1106 // Only keep the bytes that fit in the record
1107 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>
1108 eventData{};
1109 std::copy_n(eventDataBytes.begin(),
1110 std::min(eventDataBytes.size(), eventData.size()),
1111 eventData.begin());
1112
1113 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1114 oemTsEventType{timestamp, eventData});
1115 }
1116
1117 if (recordType >= dynamic_sensors::ipmi::sel::oemEventFirst)
1118 {
1119 // Only keep the bytes that fit in the record
1120 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>
1121 eventData{};
1122 std::copy_n(eventDataBytes.begin(),
1123 std::min(eventDataBytes.size(), eventData.size()),
1124 eventData.begin());
1125
1126 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1127 eventData);
1128 }
1129
Willy Tude54f482021-01-26 15:59:09 -08001130 return ipmi::responseUnspecifiedError();
1131}
1132
Willy Tu11d68892022-01-20 10:37:34 -08001133/*
1134Unused arguments
1135 uint16_t recordID, uint8_t recordType, uint32_t timestamp,
1136 uint16_t generatorID, uint8_t evmRev, uint8_t sensorType, uint8_t sensorNum,
1137 uint8_t eventType, uint8_t eventData1, uint8_t eventData2,
1138 uint8_t eventData3
1139*/
Patrick Williams69b4c282025-03-03 11:19:13 -05001140ipmi::RspType<uint16_t> ipmiStorageAddSELEntry(
1141 uint16_t, uint8_t, uint32_t, uint16_t, uint8_t, uint8_t, uint8_t, uint8_t,
1142 uint8_t, uint8_t, uint8_t)
Willy Tude54f482021-01-26 15:59:09 -08001143{
1144 // Per the IPMI spec, need to cancel any reservation when a SEL entry is
1145 // added
1146 cancelSELReservation();
1147
1148 uint16_t responseID = 0xFFFF;
1149 return ipmi::responseSuccess(responseID);
1150}
1151
Patrick Williams1318a5e2024-08-16 15:19:54 -04001152ipmi::RspType<uint8_t> ipmiStorageClearSEL(
1153 ipmi::Context::ptr ctx, uint16_t reservationID,
1154 const std::array<uint8_t, 3>& clr, uint8_t eraseOperation)
Willy Tude54f482021-01-26 15:59:09 -08001155{
1156 if (!checkSELReservation(reservationID))
1157 {
1158 return ipmi::responseInvalidReservationId();
1159 }
1160
1161 static constexpr std::array<uint8_t, 3> clrExpected = {'C', 'L', 'R'};
1162 if (clr != clrExpected)
1163 {
1164 return ipmi::responseInvalidFieldRequest();
1165 }
1166
1167 // Erasure status cannot be fetched, so always return erasure status as
1168 // `erase completed`.
1169 if (eraseOperation == ipmi::sel::getEraseStatus)
1170 {
1171 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1172 }
1173
1174 // Check that initiate erase is correct
1175 if (eraseOperation != ipmi::sel::initiateErase)
1176 {
1177 return ipmi::responseInvalidFieldRequest();
1178 }
1179
1180 // Per the IPMI spec, need to cancel any reservation when the SEL is
1181 // cleared
1182 cancelSELReservation();
1183
George Liude1420d2025-03-03 15:14:25 +08001184 boost::system::error_code ec =
1185 ipmi::callDbusMethod(ctx, "xyz.openbmc_project.Logging.IPMI",
1186 "/xyz/openbmc_project/Logging/IPMI",
1187 "xyz.openbmc_project.Logging.IPMI", "Clear");
Charles Boyer818bea12021-09-20 16:56:36 -05001188 if (ec)
1189 {
Haicheng Zhang041b3752025-07-14 17:13:45 +08001190 lg2::error("error in clear SEL: {MSG}", "MSG", ec.message());
Charles Boyer818bea12021-09-20 16:56:36 -05001191 return ipmi::responseUnspecifiedError();
1192 }
Willy Tude54f482021-01-26 15:59:09 -08001193
1194 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1195}
1196
Patrick Williams1318a5e2024-08-16 15:19:54 -04001197std::vector<uint8_t> getType8SDRs(
1198 ipmi::sensor::EntityInfoMap::const_iterator& entity, uint16_t recordId)
Harvey Wu05d17c02021-09-15 08:46:59 +08001199{
1200 std::vector<uint8_t> resp;
1201 get_sdr::SensorDataEntityRecord data{};
1202
1203 /* Header */
1204 get_sdr::header::set_record_id(recordId, &(data.header));
1205 // Based on IPMI Spec v2.0 rev 1.1
1206 data.header.sdr_version = SDR_VERSION;
1207 data.header.record_type = 0x08;
1208 data.header.record_length = sizeof(data.key) + sizeof(data.body);
1209
1210 /* Key */
1211 data.key.containerEntityId = entity->second.containerEntityId;
1212 data.key.containerEntityInstance = entity->second.containerEntityInstance;
1213 get_sdr::key::set_flags(entity->second.isList, entity->second.isLinked,
1214 &(data.key));
1215 data.key.entityId1 = entity->second.containedEntities[0].first;
1216 data.key.entityInstance1 = entity->second.containedEntities[0].second;
1217
1218 /* Body */
1219 data.body.entityId2 = entity->second.containedEntities[1].first;
1220 data.body.entityInstance2 = entity->second.containedEntities[1].second;
1221 data.body.entityId3 = entity->second.containedEntities[2].first;
1222 data.body.entityInstance3 = entity->second.containedEntities[2].second;
1223 data.body.entityId4 = entity->second.containedEntities[3].first;
1224 data.body.entityInstance4 = entity->second.containedEntities[3].second;
1225
1226 resp.insert(resp.end(), (uint8_t*)&data, ((uint8_t*)&data) + sizeof(data));
1227
1228 return resp;
1229}
1230
Willy Tude54f482021-01-26 15:59:09 -08001231std::vector<uint8_t> getType12SDRs(uint16_t index, uint16_t recordId)
1232{
1233 std::vector<uint8_t> resp;
1234 if (index == 0)
1235 {
Willy Tude54f482021-01-26 15:59:09 -08001236 std::string bmcName = "Basbrd Mgmt Ctlr";
Johnathan Manteycd1c4962021-09-22 12:58:08 -07001237 Type12Record bmc(recordId, 0x20, 0, 0, 0xbf, 0x2e, 1, 0, bmcName);
Willy Tude54f482021-01-26 15:59:09 -08001238 uint8_t* bmcPtr = reinterpret_cast<uint8_t*>(&bmc);
1239 resp.insert(resp.end(), bmcPtr, bmcPtr + sizeof(Type12Record));
1240 }
1241 else if (index == 1)
1242 {
Willy Tude54f482021-01-26 15:59:09 -08001243 std::string meName = "Mgmt Engine";
Johnathan Manteycd1c4962021-09-22 12:58:08 -07001244 Type12Record me(recordId, 0x2c, 6, 0x24, 0x21, 0x2e, 2, 0, meName);
Willy Tude54f482021-01-26 15:59:09 -08001245 uint8_t* mePtr = reinterpret_cast<uint8_t*>(&me);
1246 resp.insert(resp.end(), mePtr, mePtr + sizeof(Type12Record));
1247 }
1248 else
1249 {
Patrick Williams1318a5e2024-08-16 15:19:54 -04001250 throw std::runtime_error(
1251 "getType12SDRs:: Illegal index " + std::to_string(index));
Willy Tude54f482021-01-26 15:59:09 -08001252 }
1253
1254 return resp;
1255}
1256
1257void registerStorageFunctions()
1258{
1259 createTimers();
1260 startMatch();
1261
1262 // <Get FRU Inventory Area Info>
Willy Tud351a722021-08-12 14:33:40 -07001263 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
Willy Tude54f482021-01-26 15:59:09 -08001264 ipmi::storage::cmdGetFruInventoryAreaInfo,
1265 ipmi::Privilege::User, ipmiStorageGetFruInvAreaInfo);
1266 // <READ FRU Data>
1267 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1268 ipmi::storage::cmdReadFruData, ipmi::Privilege::User,
1269 ipmiStorageReadFruData);
1270
1271 // <WRITE FRU Data>
1272 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1273 ipmi::storage::cmdWriteFruData,
1274 ipmi::Privilege::Operator, ipmiStorageWriteFruData);
1275
1276 // <Get SEL Info>
1277 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1278 ipmi::storage::cmdGetSelInfo, ipmi::Privilege::User,
1279 ipmiStorageGetSELInfo);
1280
1281 // <Get SEL Entry>
1282 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1283 ipmi::storage::cmdGetSelEntry, ipmi::Privilege::User,
1284 ipmiStorageGetSELEntry);
1285
1286 // <Add SEL Entry>
1287 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1288 ipmi::storage::cmdAddSelEntry,
1289 ipmi::Privilege::Operator, ipmiStorageAddSELEntry);
1290
1291 // <Clear SEL>
1292 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1293 ipmi::storage::cmdClearSel, ipmi::Privilege::Operator,
1294 ipmiStorageClearSEL);
Willy Tude54f482021-01-26 15:59:09 -08001295}
1296} // namespace storage
1297} // namespace ipmi