blob: e0e47e1b80f307f02bf049567a40e1362f421466 [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>
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -050032
33#include <filesystem>
34#include <fstream>
35#include <functional>
Willy Tu06ed9da2025-04-07 00:44:20 +000036#include <optional>
Willy Tude54f482021-01-26 15:59:09 -080037#include <stdexcept>
38#include <string_view>
39
40static constexpr bool DEBUG = false;
41
42namespace dynamic_sensors::ipmi::sel
43{
44static const std::filesystem::path selLogDir = "/var/log";
45static const std::string selLogFilename = "ipmi_sel";
46
47static int getFileTimestamp(const std::filesystem::path& file)
48{
49 struct stat st;
50
51 if (stat(file.c_str(), &st) >= 0)
52 {
53 return st.st_mtime;
54 }
55 return ::ipmi::sel::invalidTimeStamp;
56}
57
58namespace erase_time
59{
60static constexpr const char* selEraseTimestamp = "/var/lib/ipmi/sel_erase_time";
61
Willy Tude54f482021-01-26 15:59:09 -080062int get()
63{
64 return getFileTimestamp(selEraseTimestamp);
65}
66} // namespace erase_time
67} // namespace dynamic_sensors::ipmi::sel
68
69namespace ipmi
70{
71
72namespace storage
73{
74
Willy Tude54f482021-01-26 15:59:09 -080075constexpr static const size_t maxFruSdrNameSize = 16;
76using ObjectType =
77 boost::container::flat_map<std::string,
78 boost::container::flat_map<std::string, Value>>;
79using ManagedObjectType =
80 boost::container::flat_map<sdbusplus::message::object_path, ObjectType>;
81using ManagedEntry = std::pair<sdbusplus::message::object_path, ObjectType>;
Willy Tu06ed9da2025-04-07 00:44:20 +000082using Paths = std::vector<std::string>;
Willy Tude54f482021-01-26 15:59:09 -080083
84constexpr static const char* fruDeviceServiceName =
85 "xyz.openbmc_project.FruDevice";
Willy Tude54f482021-01-26 15:59:09 -080086constexpr static const size_t writeTimeoutSeconds = 10;
87constexpr static const char* chassisTypeRackMount = "23";
Zev Weissf38f9d12021-05-21 13:30:16 -050088constexpr static const char* chassisTypeMainServer = "17";
Willy Tude54f482021-01-26 15:59:09 -080089
Willy Tude54f482021-01-26 15:59:09 -080090static std::vector<uint8_t> fruCache;
krishnar4d90b3f02022-11-11 16:18:32 +053091static constexpr uint16_t invalidBus = 0xFFFF;
92static constexpr uint8_t invalidAddr = 0xFF;
Johnathan Manteyb99de182023-12-21 08:28:18 -080093static constexpr uint8_t typeASCIILatin8 = 0xC0;
krishnar4d90b3f02022-11-11 16:18:32 +053094static uint16_t cacheBus = invalidBus;
95static uint8_t cacheAddr = invalidAddr;
Willy Tude54f482021-01-26 15:59:09 -080096static uint8_t lastDevId = 0xFF;
97
krishnar4d90b3f02022-11-11 16:18:32 +053098static uint16_t writeBus = invalidBus;
99static uint8_t writeAddr = invalidAddr;
Willy Tude54f482021-01-26 15:59:09 -0800100
Patrick Williams95655222023-12-05 12:45:02 -0600101std::unique_ptr<sdbusplus::Timer> writeTimer = nullptr;
Patrick Williams5d82f472022-07-22 19:26:53 -0500102static std::vector<sdbusplus::bus::match_t> fruMatches;
Willy Tude54f482021-01-26 15:59:09 -0800103
104ManagedObjectType frus;
105
106// we unfortunately have to build a map of hashes in case there is a
107// collision to verify our dev-id
krishnar4d90b3f02022-11-11 16:18:32 +0530108boost::container::flat_map<uint8_t, std::pair<uint16_t, uint8_t>> deviceHashes;
Willy Tude54f482021-01-26 15:59:09 -0800109void registerStorageFunctions() __attribute__((constructor));
110
Willy Tu48fe64e2022-08-01 23:23:46 +0000111bool writeFru(const std::vector<uint8_t>& fru)
Willy Tude54f482021-01-26 15:59:09 -0800112{
krishnar4d90b3f02022-11-11 16:18:32 +0530113 if (writeBus == invalidBus && writeAddr == invalidAddr)
Willy Tude54f482021-01-26 15:59:09 -0800114 {
115 return true;
116 }
Thang Trand934be92021-12-08 10:13:50 +0700117 lastDevId = 0xFF;
Willy Tude54f482021-01-26 15:59:09 -0800118 std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus();
Patrick Williams5d82f472022-07-22 19:26:53 -0500119 sdbusplus::message_t writeFru = dbus->new_method_call(
Willy Tude54f482021-01-26 15:59:09 -0800120 fruDeviceServiceName, "/xyz/openbmc_project/FruDevice",
121 "xyz.openbmc_project.FruDeviceManager", "WriteFru");
Willy Tu48fe64e2022-08-01 23:23:46 +0000122 writeFru.append(writeBus, writeAddr, fru);
Willy Tude54f482021-01-26 15:59:09 -0800123 try
124 {
Patrick Williams5d82f472022-07-22 19:26:53 -0500125 sdbusplus::message_t writeFruResp = dbus->call(writeFru);
Willy Tude54f482021-01-26 15:59:09 -0800126 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500127 catch (const sdbusplus::exception_t&)
Willy Tude54f482021-01-26 15:59:09 -0800128 {
129 // todo: log sel?
George Liude6694e2024-07-17 15:22:25 +0800130 lg2::error("error writing fru");
Willy Tude54f482021-01-26 15:59:09 -0800131 return false;
132 }
krishnar4d90b3f02022-11-11 16:18:32 +0530133 writeBus = invalidBus;
134 writeAddr = invalidAddr;
Willy Tude54f482021-01-26 15:59:09 -0800135 return true;
136}
137
William A. Kennington III52535622022-11-28 18:28:22 -0800138void writeFruCache()
Willy Tu48fe64e2022-08-01 23:23:46 +0000139{
William A. Kennington III52535622022-11-28 18:28:22 -0800140 writeFru(fruCache);
Willy Tu48fe64e2022-08-01 23:23:46 +0000141}
142
Willy Tude54f482021-01-26 15:59:09 -0800143void createTimers()
144{
Patrick Williams95655222023-12-05 12:45:02 -0600145 writeTimer = std::make_unique<sdbusplus::Timer>(writeFruCache);
Willy Tude54f482021-01-26 15:59:09 -0800146}
147
148void recalculateHashes()
149{
Willy Tude54f482021-01-26 15:59:09 -0800150 deviceHashes.clear();
151 // hash the object paths to create unique device id's. increment on
152 // collision
153 std::hash<std::string> hasher;
154 for (const auto& fru : frus)
155 {
156 auto fruIface = fru.second.find("xyz.openbmc_project.FruDevice");
157 if (fruIface == fru.second.end())
158 {
159 continue;
160 }
161
162 auto busFind = fruIface->second.find("BUS");
163 auto addrFind = fruIface->second.find("ADDRESS");
164 if (busFind == fruIface->second.end() ||
165 addrFind == fruIface->second.end())
166 {
George Liude6694e2024-07-17 15:22:25 +0800167 lg2::info("fru device missing Bus or Address, fru: {FRU}", "FRU",
168 fru.first.str);
Willy Tude54f482021-01-26 15:59:09 -0800169 continue;
170 }
171
krishnar4d90b3f02022-11-11 16:18:32 +0530172 uint16_t fruBus = std::get<uint32_t>(busFind->second);
Willy Tude54f482021-01-26 15:59:09 -0800173 uint8_t fruAddr = std::get<uint32_t>(addrFind->second);
174 auto chassisFind = fruIface->second.find("CHASSIS_TYPE");
175 std::string chassisType;
176 if (chassisFind != fruIface->second.end())
177 {
178 chassisType = std::get<std::string>(chassisFind->second);
179 }
180
181 uint8_t fruHash = 0;
Zev Weissf38f9d12021-05-21 13:30:16 -0500182 if (chassisType.compare(chassisTypeRackMount) != 0 &&
183 chassisType.compare(chassisTypeMainServer) != 0)
Willy Tude54f482021-01-26 15:59:09 -0800184 {
185 fruHash = hasher(fru.first.str);
186 // can't be 0xFF based on spec, and 0 is reserved for baseboard
187 if (fruHash == 0 || fruHash == 0xFF)
188 {
189 fruHash = 1;
190 }
191 }
krishnar4d90b3f02022-11-11 16:18:32 +0530192 std::pair<uint16_t, uint8_t> newDev(fruBus, fruAddr);
Willy Tude54f482021-01-26 15:59:09 -0800193
194 bool emplacePassed = false;
195 while (!emplacePassed)
196 {
197 auto resp = deviceHashes.emplace(fruHash, newDev);
198 emplacePassed = resp.second;
199 if (!emplacePassed)
200 {
201 fruHash++;
202 // can't be 0xFF based on spec, and 0 is reserved for
203 // baseboard
204 if (fruHash == 0XFF)
205 {
206 fruHash = 0x1;
207 }
208 }
209 }
210 }
211}
212
Willy Tu11d68892022-01-20 10:37:34 -0800213void replaceCacheFru(
214 const std::shared_ptr<sdbusplus::asio::connection>& bus,
215 boost::asio::yield_context& yield,
216 [[maybe_unused]] const std::optional<std::string>& path = std::nullopt)
Willy Tude54f482021-01-26 15:59:09 -0800217{
218 boost::system::error_code ec;
219
220 frus = bus->yield_method_call<ManagedObjectType>(
221 yield, ec, fruDeviceServiceName, "/",
222 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
223 if (ec)
224 {
George Liude6694e2024-07-17 15:22:25 +0800225 lg2::error("GetMangagedObjects for replaceCacheFru failed: {ERROR}",
226 "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800227
228 return;
229 }
230 recalculateHashes();
231}
232
Patrick Williams69b4c282025-03-03 11:19:13 -0500233std::pair<ipmi::Cc, std::vector<uint8_t>> getFru(ipmi::Context::ptr ctx,
234 uint8_t devId)
Willy Tude54f482021-01-26 15:59:09 -0800235{
236 if (lastDevId == devId && devId != 0xFF)
237 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000238 return {ipmi::ccSuccess, fruCache};
Willy Tude54f482021-01-26 15:59:09 -0800239 }
240
Willy Tude54f482021-01-26 15:59:09 -0800241 auto deviceFind = deviceHashes.find(devId);
242 if (deviceFind == deviceHashes.end())
243 {
George Liu879c1d82025-07-03 09:36:57 +0800244 return {ipmi::ccSensorInvalid, {}};
Willy Tude54f482021-01-26 15:59:09 -0800245 }
246
Willy Tude54f482021-01-26 15:59:09 -0800247 cacheBus = deviceFind->second.first;
248 cacheAddr = deviceFind->second.second;
249
250 boost::system::error_code ec;
George Liude1420d2025-03-03 15:14:25 +0800251 std::vector<uint8_t> fru = ipmi::callDbusMethod<std::vector<uint8_t>>(
252 ctx, ec, fruDeviceServiceName, "/xyz/openbmc_project/FruDevice",
253 "xyz.openbmc_project.FruDeviceManager", "GetRawFru", cacheBus,
254 cacheAddr);
Willy Tude54f482021-01-26 15:59:09 -0800255
Willy Tude54f482021-01-26 15:59:09 -0800256 if (ec)
257 {
George Liude6694e2024-07-17 15:22:25 +0800258 lg2::error("Couldn't get raw fru: {ERROR}", "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800259
krishnar4d90b3f02022-11-11 16:18:32 +0530260 cacheBus = invalidBus;
261 cacheAddr = invalidAddr;
Willy Tu48fe64e2022-08-01 23:23:46 +0000262 return {ipmi::ccResponseError, {}};
Willy Tude54f482021-01-26 15:59:09 -0800263 }
264
Willy Tu48fe64e2022-08-01 23:23:46 +0000265 fruCache.clear();
Willy Tude54f482021-01-26 15:59:09 -0800266 lastDevId = devId;
Willy Tu48fe64e2022-08-01 23:23:46 +0000267 fruCache = fru;
268
269 return {ipmi::ccSuccess, fru};
Willy Tude54f482021-01-26 15:59:09 -0800270}
271
272void writeFruIfRunning()
273{
274 if (!writeTimer->isRunning())
275 {
276 return;
277 }
278 writeTimer->stop();
Willy Tu48fe64e2022-08-01 23:23:46 +0000279 writeFruCache();
Willy Tude54f482021-01-26 15:59:09 -0800280}
281
282void startMatch(void)
283{
284 if (fruMatches.size())
285 {
286 return;
287 }
288
289 fruMatches.reserve(2);
290
291 auto bus = getSdBus();
Patrick Williams1318a5e2024-08-16 15:19:54 -0400292 fruMatches.emplace_back(
293 *bus,
294 "type='signal',arg0path='/xyz/openbmc_project/"
295 "FruDevice/',member='InterfacesAdded'",
296 [](sdbusplus::message_t& message) {
297 sdbusplus::message::object_path path;
298 ObjectType object;
299 try
300 {
301 message.read(path, object);
302 }
303 catch (const sdbusplus::exception_t&)
304 {
305 return;
306 }
307 auto findType = object.find("xyz.openbmc_project.FruDevice");
308 if (findType == object.end())
309 {
310 return;
311 }
312 writeFruIfRunning();
313 frus[path] = object;
314 recalculateHashes();
315 lastDevId = 0xFF;
316 });
Willy Tude54f482021-01-26 15:59:09 -0800317
Patrick Williams1318a5e2024-08-16 15:19:54 -0400318 fruMatches.emplace_back(
319 *bus,
320 "type='signal',arg0path='/xyz/openbmc_project/"
321 "FruDevice/',member='InterfacesRemoved'",
322 [](sdbusplus::message_t& message) {
323 sdbusplus::message::object_path path;
324 std::set<std::string> interfaces;
325 try
326 {
327 message.read(path, interfaces);
328 }
329 catch (const sdbusplus::exception_t&)
330 {
331 return;
332 }
333 auto findType = interfaces.find("xyz.openbmc_project.FruDevice");
334 if (findType == interfaces.end())
335 {
336 return;
337 }
338 writeFruIfRunning();
339 frus.erase(path);
340 recalculateHashes();
341 lastDevId = 0xFF;
342 });
Willy Tude54f482021-01-26 15:59:09 -0800343
344 // call once to populate
Ed Tanous98605052025-02-13 16:57:13 -0800345 boost::asio::spawn(
346 *getIoContext(),
347 [](boost::asio::yield_context yield) {
348 replaceCacheFru(getSdBus(), yield);
349 },
350 boost::asio::detached);
Willy Tude54f482021-01-26 15:59:09 -0800351}
352
353/** @brief implements the read FRU data command
354 * @param fruDeviceId - FRU Device ID
355 * @param fruInventoryOffset - FRU Inventory Offset to write
356 * @param countToRead - Count to read
357 *
358 * @returns ipmi completion code plus response data
359 * - countWritten - Count written
360 */
361ipmi::RspType<uint8_t, // Count
362 std::vector<uint8_t> // Requested data
363 >
364 ipmiStorageReadFruData(ipmi::Context::ptr ctx, uint8_t fruDeviceId,
365 uint16_t fruInventoryOffset, uint8_t countToRead)
366{
367 if (fruDeviceId == 0xFF)
368 {
369 return ipmi::responseInvalidFieldRequest();
370 }
371
Willy Tu48fe64e2022-08-01 23:23:46 +0000372 auto [status, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800373 if (status != ipmi::ccSuccess)
374 {
375 return ipmi::response(status);
376 }
377
378 size_t fromFruByteLen = 0;
Willy Tu48fe64e2022-08-01 23:23:46 +0000379 if (countToRead + fruInventoryOffset < fru.size())
Willy Tude54f482021-01-26 15:59:09 -0800380 {
381 fromFruByteLen = countToRead;
382 }
Willy Tu48fe64e2022-08-01 23:23:46 +0000383 else if (fru.size() > fruInventoryOffset)
Willy Tude54f482021-01-26 15:59:09 -0800384 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000385 fromFruByteLen = fru.size() - fruInventoryOffset;
Willy Tude54f482021-01-26 15:59:09 -0800386 }
387 else
388 {
389 return ipmi::responseReqDataLenExceeded();
390 }
391
392 std::vector<uint8_t> requestedData;
393
Willy Tu48fe64e2022-08-01 23:23:46 +0000394 requestedData.insert(requestedData.begin(),
395 fru.begin() + fruInventoryOffset,
396 fru.begin() + fruInventoryOffset + fromFruByteLen);
Willy Tude54f482021-01-26 15:59:09 -0800397
398 return ipmi::responseSuccess(static_cast<uint8_t>(requestedData.size()),
399 requestedData);
400}
401
402/** @brief implements the write FRU data command
403 * @param fruDeviceId - FRU Device ID
404 * @param fruInventoryOffset - FRU Inventory Offset to write
405 * @param dataToWrite - Data to write
406 *
407 * @returns ipmi completion code plus response data
408 * - countWritten - Count written
409 */
Patrick Williams1318a5e2024-08-16 15:19:54 -0400410ipmi::RspType<uint8_t> ipmiStorageWriteFruData(
411 ipmi::Context::ptr ctx, uint8_t fruDeviceId, uint16_t fruInventoryOffset,
412 std::vector<uint8_t>& dataToWrite)
Willy Tude54f482021-01-26 15:59:09 -0800413{
414 if (fruDeviceId == 0xFF)
415 {
416 return ipmi::responseInvalidFieldRequest();
417 }
418
419 size_t writeLen = dataToWrite.size();
420
Willy Tu48fe64e2022-08-01 23:23:46 +0000421 auto [status, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800422 if (status != ipmi::ccSuccess)
423 {
424 return ipmi::response(status);
425 }
426 size_t lastWriteAddr = fruInventoryOffset + writeLen;
Willy Tu48fe64e2022-08-01 23:23:46 +0000427 if (fru.size() < lastWriteAddr)
Willy Tude54f482021-01-26 15:59:09 -0800428 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000429 fru.resize(fruInventoryOffset + writeLen);
Willy Tude54f482021-01-26 15:59:09 -0800430 }
431
432 std::copy(dataToWrite.begin(), dataToWrite.begin() + writeLen,
Willy Tu48fe64e2022-08-01 23:23:46 +0000433 fru.begin() + fruInventoryOffset);
Willy Tude54f482021-01-26 15:59:09 -0800434
435 bool atEnd = false;
436
Willy Tu48fe64e2022-08-01 23:23:46 +0000437 if (fru.size() >= sizeof(FRUHeader))
Willy Tude54f482021-01-26 15:59:09 -0800438 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000439 FRUHeader* header = reinterpret_cast<FRUHeader*>(fru.data());
Willy Tude54f482021-01-26 15:59:09 -0800440
441 size_t areaLength = 0;
442 size_t lastRecordStart = std::max(
443 {header->internalOffset, header->chassisOffset, header->boardOffset,
444 header->productOffset, header->multiRecordOffset});
445 lastRecordStart *= 8; // header starts in are multiples of 8 bytes
446
447 if (header->multiRecordOffset)
448 {
449 // This FRU has a MultiRecord Area
450 uint8_t endOfList = 0;
451 // Walk the MultiRecord headers until the last record
452 while (!endOfList)
453 {
454 // The MSB in the second byte of the MultiRecord header signals
455 // "End of list"
Willy Tu48fe64e2022-08-01 23:23:46 +0000456 endOfList = fru[lastRecordStart + 1] & 0x80;
Willy Tude54f482021-01-26 15:59:09 -0800457 // Third byte in the MultiRecord header is the length
Willy Tu48fe64e2022-08-01 23:23:46 +0000458 areaLength = fru[lastRecordStart + 2];
Willy Tude54f482021-01-26 15:59:09 -0800459 // This length is in bytes (not 8 bytes like other headers)
460 areaLength += 5; // The length omits the 5 byte header
461 if (!endOfList)
462 {
463 // Next MultiRecord header
464 lastRecordStart += areaLength;
465 }
466 }
467 }
468 else
469 {
470 // This FRU does not have a MultiRecord Area
471 // Get the length of the area in multiples of 8 bytes
472 if (lastWriteAddr > (lastRecordStart + 1))
473 {
474 // second byte in record area is the length
Willy Tu48fe64e2022-08-01 23:23:46 +0000475 areaLength = fru[lastRecordStart + 1];
Willy Tude54f482021-01-26 15:59:09 -0800476 areaLength *= 8; // it is in multiples of 8 bytes
477 }
478 }
479 if (lastWriteAddr >= (areaLength + lastRecordStart))
480 {
481 atEnd = true;
482 }
483 }
484 uint8_t countWritten = 0;
485
486 writeBus = cacheBus;
487 writeAddr = cacheAddr;
488 if (atEnd)
489 {
490 // cancel timer, we're at the end so might as well send it
491 writeTimer->stop();
Willy Tu48fe64e2022-08-01 23:23:46 +0000492 if (!writeFru(fru))
Willy Tude54f482021-01-26 15:59:09 -0800493 {
494 return ipmi::responseInvalidFieldRequest();
495 }
Willy Tu48fe64e2022-08-01 23:23:46 +0000496 countWritten = std::min(fru.size(), static_cast<size_t>(0xFF));
Willy Tude54f482021-01-26 15:59:09 -0800497 }
498 else
499 {
Sui Chen548d1a22022-09-14 07:41:17 -0700500 fruCache = fru; // Write-back
Willy Tude54f482021-01-26 15:59:09 -0800501 // start a timer, if no further data is sent to check to see if it is
502 // valid
503 writeTimer->start(std::chrono::duration_cast<std::chrono::microseconds>(
504 std::chrono::seconds(writeTimeoutSeconds)));
505 countWritten = 0;
506 }
507
508 return ipmi::responseSuccess(countWritten);
509}
510
511/** @brief implements the get FRU inventory area info command
512 * @param fruDeviceId - FRU Device ID
513 *
514 * @returns IPMI completion code plus response data
515 * - inventorySize - Number of possible allocation units
516 * - accessType - Allocation unit size in bytes.
517 */
518ipmi::RspType<uint16_t, // inventorySize
519 uint8_t> // accessType
520 ipmiStorageGetFruInvAreaInfo(ipmi::Context::ptr ctx, uint8_t fruDeviceId)
521{
522 if (fruDeviceId == 0xFF)
523 {
524 return ipmi::responseInvalidFieldRequest();
525 }
526
Willy Tu48fe64e2022-08-01 23:23:46 +0000527 auto [ret, fru] = getFru(ctx, fruDeviceId);
Willy Tude54f482021-01-26 15:59:09 -0800528 if (ret != ipmi::ccSuccess)
529 {
530 return ipmi::response(ret);
531 }
532
533 constexpr uint8_t accessType =
534 static_cast<uint8_t>(GetFRUAreaAccessType::byte);
535
Willy Tu48fe64e2022-08-01 23:23:46 +0000536 return ipmi::responseSuccess(fru.size(), accessType);
Willy Tude54f482021-01-26 15:59:09 -0800537}
538
George Liu23c868c2025-07-04 09:31:35 +0800539ipmi::Cc getFruSdrCount(ipmi::Context::ptr, size_t& count)
Willy Tude54f482021-01-26 15:59:09 -0800540{
541 count = deviceHashes.size();
George Liue8a97bd2024-12-05 17:26:46 +0800542 return ipmi::ccSuccess;
Willy Tude54f482021-01-26 15:59:09 -0800543}
544
George Liu23c868c2025-07-04 09:31:35 +0800545ipmi::Cc getFruSdrs([[maybe_unused]] ipmi::Context::ptr ctx, size_t index,
546 get_sdr::SensorDataFruRecord& resp)
Willy Tude54f482021-01-26 15:59:09 -0800547{
548 if (deviceHashes.size() < index)
549 {
George Liu879c1d82025-07-03 09:36:57 +0800550 return ipmi::ccInvalidFieldRequest;
Willy Tude54f482021-01-26 15:59:09 -0800551 }
552 auto device = deviceHashes.begin() + index;
krishnar4d90b3f02022-11-11 16:18:32 +0530553 uint16_t& bus = device->second.first;
Willy Tude54f482021-01-26 15:59:09 -0800554 uint8_t& address = device->second.second;
555
556 boost::container::flat_map<std::string, Value>* fruData = nullptr;
Patrick Williams1318a5e2024-08-16 15:19:54 -0400557 auto fru = std::find_if(
558 frus.begin(), frus.end(),
559 [bus, address, &fruData](ManagedEntry& entry) {
560 auto findFruDevice =
561 entry.second.find("xyz.openbmc_project.FruDevice");
562 if (findFruDevice == entry.second.end())
563 {
564 return false;
565 }
566 fruData = &(findFruDevice->second);
567 auto findBus = findFruDevice->second.find("BUS");
568 auto findAddress = findFruDevice->second.find("ADDRESS");
569 if (findBus == findFruDevice->second.end() ||
570 findAddress == findFruDevice->second.end())
571 {
572 return false;
573 }
574 if (std::get<uint32_t>(findBus->second) != bus)
575 {
576 return false;
577 }
578 if (std::get<uint32_t>(findAddress->second) != address)
579 {
580 return false;
581 }
582 return true;
583 });
Willy Tude54f482021-01-26 15:59:09 -0800584 if (fru == frus.end())
585 {
George Liu879c1d82025-07-03 09:36:57 +0800586 return ipmi::ccResponseError;
Willy Tude54f482021-01-26 15:59:09 -0800587 }
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530588 std::string name;
Willy Tu06ed9da2025-04-07 00:44:20 +0000589 uint8_t entityID = 0;
590 uint8_t entityInstance = 0x1;
Willy Tude54f482021-01-26 15:59:09 -0800591
592#ifdef USING_ENTITY_MANAGER_DECORATORS
Willy Tude54f482021-01-26 15:59:09 -0800593 boost::system::error_code ec;
Willy Tude54f482021-01-26 15:59:09 -0800594
Willy Tu06ed9da2025-04-07 00:44:20 +0000595 Paths subtreePaths = ipmi::callDbusMethod<Paths>(
596 ctx, ec, "xyz.openbmc_project.ObjectMapper",
597 "/xyz/openbmc_project/object_mapper",
598 "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths",
599 "/xyz/openbmc_project/inventory", 0,
600 std::array<const char*, 2>{
601 "xyz.openbmc_project.Inventory.Decorator.I2CDevice",
602 "xyz.openbmc_project.Inventory.Decorator.Ipmi",
603 });
Willy Tude54f482021-01-26 15:59:09 -0800604 if (ec)
605 {
Willy Tu06ed9da2025-04-07 00:44:20 +0000606 lg2::error(
607 "GetSubTreePaths for ipmiStorageGetFruInvAreaInfo failed: {ERROR}",
608 "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800609 return ipmi::ccResponseError;
610 }
611
Willy Tu06ed9da2025-04-07 00:44:20 +0000612 bool foundDevice = false;
613 for (const auto& path : subtreePaths)
614 {
615 ipmi::PropertyMap i2cProperties;
616 boost::system::error_code ec = ipmi::getAllDbusProperties(
617 ctx, "xyz.openbmc_project.EntityManager", path,
618 "xyz.openbmc_project.Inventory.Decorator.I2CDevice", i2cProperties);
619 if (ec)
620 {
621 continue;
622 }
623
624 std::optional<uint64_t> maybeBus;
625 std::optional<uint64_t> maybeAddress;
626 std::optional<std::string> maybeName;
627 for (const auto& [key, val] : i2cProperties)
628 {
629 if (key == "Bus")
Patrick Williams1318a5e2024-08-16 15:19:54 -0400630 {
Willy Tu06ed9da2025-04-07 00:44:20 +0000631 maybeBus = std::get<uint64_t>(val);
Patrick Williams1318a5e2024-08-16 15:19:54 -0400632 }
Willy Tu06ed9da2025-04-07 00:44:20 +0000633 else if (key == "Address")
Patrick Williams1318a5e2024-08-16 15:19:54 -0400634 {
Willy Tu06ed9da2025-04-07 00:44:20 +0000635 maybeAddress = std::get<uint64_t>(val);
Patrick Williams1318a5e2024-08-16 15:19:54 -0400636 }
Willy Tu06ed9da2025-04-07 00:44:20 +0000637 else if (key == "Name")
Patrick Williams1318a5e2024-08-16 15:19:54 -0400638 {
Willy Tu06ed9da2025-04-07 00:44:20 +0000639 maybeName = std::get<std::string>(val);
Patrick Williams1318a5e2024-08-16 15:19:54 -0400640 }
Willy Tu06ed9da2025-04-07 00:44:20 +0000641 }
642 if (!maybeBus || *maybeBus != bus || !maybeAddress ||
643 *maybeAddress != address)
644 {
645 continue;
646 }
647 // At this point we found the device entry and will populate the
648 // information if exist.
649 foundDevice = true;
Willy Tude54f482021-01-26 15:59:09 -0800650
Willy Tu06ed9da2025-04-07 00:44:20 +0000651 if (maybeName.has_value())
652 {
653 name = *maybeName;
654 }
655
656 ipmi::PropertyMap entityData;
657 ec = ipmi::getAllDbusProperties(
658 ctx, "xyz.openbmc_project.EntityManager", path,
659 "xyz.openbmc_project.Inventory.Decorator.Ipmi", entityData);
660 if (!ec)
661 {
662 for (const auto& [key, val] : entityData)
Patrick Williams1318a5e2024-08-16 15:19:54 -0400663 {
Willy Tu06ed9da2025-04-07 00:44:20 +0000664 if (key == "EntityId")
665 {
666 entityID = std::get<uint64_t>(val);
667 }
668 else if (key == "EntityInstance")
669 {
670 entityInstance = std::get<uint64_t>(val);
671 }
Patrick Williams1318a5e2024-08-16 15:19:54 -0400672 }
Willy Tu06ed9da2025-04-07 00:44:20 +0000673 }
674 break;
675 }
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530676
Willy Tu06ed9da2025-04-07 00:44:20 +0000677 if (!foundDevice)
Willy Tude54f482021-01-26 15:59:09 -0800678 {
679 if constexpr (DEBUG)
680 {
681 std::fprintf(stderr, "Ipmi or FruDevice Decorator interface "
682 "not found for Fru\n");
683 }
684 }
Willy Tude54f482021-01-26 15:59:09 -0800685#endif
686
Alexander Hansenea46f3c2023-09-04 11:27:54 +0200687 std::vector<std::string> nameProperties = {
Jitendra Tripathy1d881b52025-05-16 10:08:15 +0000688 "BOARD_PRODUCT_NAME", "PRODUCT_PRODUCT_NAME", "PRODUCT_PART_NUMBER",
Alexander Hansenea46f3c2023-09-04 11:27:54 +0200689 "BOARD_PART_NUMBER", "PRODUCT_MANUFACTURER", "BOARD_MANUFACTURER",
690 "PRODUCT_SERIAL_NUMBER", "BOARD_SERIAL_NUMBER"};
691
692 for (const std::string& prop : nameProperties)
693 {
694 auto findProp = fruData->find(prop);
695 if (findProp != fruData->end())
696 {
697 name = std::get<std::string>(findProp->second);
698 break;
699 }
700 }
701
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530702 if (name.empty())
Willy Tude54f482021-01-26 15:59:09 -0800703 {
704 name = "UNKNOWN";
705 }
706 if (name.size() > maxFruSdrNameSize)
707 {
708 name = name.substr(0, maxFruSdrNameSize);
709 }
710 size_t sizeDiff = maxFruSdrNameSize - name.size();
711
George Liuc7a4da52025-08-19 16:20:31 +0800712 resp.header.recordId = 0x0; // calling code is to implement these
Willy Tude54f482021-01-26 15:59:09 -0800713 resp.header.sdr_version = ipmiSdrVersion;
714 resp.header.record_type = get_sdr::SENSOR_DATA_FRU_RECORD;
715 resp.header.record_length = sizeof(resp.body) + sizeof(resp.key) - sizeDiff;
716 resp.key.deviceAddress = 0x20;
717 resp.key.fruID = device->first;
718 resp.key.accessLun = 0x80; // logical / physical fru device
719 resp.key.channelNumber = 0x0;
720 resp.body.reserved = 0x0;
721 resp.body.deviceType = 0x10;
722 resp.body.deviceTypeModifier = 0x0;
723
Willy Tude54f482021-01-26 15:59:09 -0800724 resp.body.entityID = entityID;
725 resp.body.entityInstance = entityInstance;
726
727 resp.body.oem = 0x0;
Johnathan Manteyb99de182023-12-21 08:28:18 -0800728 resp.body.deviceIDLen = ipmi::storage::typeASCIILatin8 | name.size();
Willy Tude54f482021-01-26 15:59:09 -0800729 name.copy(resp.body.deviceID, name.size());
730
George Liue8a97bd2024-12-05 17:26:46 +0800731 return ipmi::ccSuccess;
Willy Tude54f482021-01-26 15:59:09 -0800732}
733
734static bool getSELLogFiles(std::vector<std::filesystem::path>& selLogFiles)
735{
736 // Loop through the directory looking for ipmi_sel log files
737 for (const std::filesystem::directory_entry& dirEnt :
738 std::filesystem::directory_iterator(
739 dynamic_sensors::ipmi::sel::selLogDir))
740 {
741 std::string filename = dirEnt.path().filename();
George Liuc024b392025-08-21 16:38:58 +0800742 if (filename.starts_with(dynamic_sensors::ipmi::sel::selLogFilename))
Willy Tude54f482021-01-26 15:59:09 -0800743 {
744 // If we find an ipmi_sel log file, save the path
Patrick Williams1318a5e2024-08-16 15:19:54 -0400745 selLogFiles.emplace_back(
746 dynamic_sensors::ipmi::sel::selLogDir / filename);
Willy Tude54f482021-01-26 15:59:09 -0800747 }
748 }
749 // As the log files rotate, they are appended with a ".#" that is higher for
750 // the older logs. Since we don't expect more than 10 log files, we
751 // can just sort the list to get them in order from newest to oldest
752 std::sort(selLogFiles.begin(), selLogFiles.end());
753
754 return !selLogFiles.empty();
755}
756
757static int countSELEntries()
758{
759 // Get the list of ipmi_sel log files
760 std::vector<std::filesystem::path> selLogFiles;
761 if (!getSELLogFiles(selLogFiles))
762 {
763 return 0;
764 }
765 int numSELEntries = 0;
766 // Loop through each log file and count the number of logs
767 for (const std::filesystem::path& file : selLogFiles)
768 {
769 std::ifstream logStream(file);
770 if (!logStream.is_open())
771 {
772 continue;
773 }
774
775 std::string line;
776 while (std::getline(logStream, line))
777 {
778 numSELEntries++;
779 }
780 }
781 return numSELEntries;
782}
783
784static bool findSELEntry(const int recordID,
785 const std::vector<std::filesystem::path>& selLogFiles,
786 std::string& entry)
787{
788 // Record ID is the first entry field following the timestamp. It is
789 // preceded by a space and followed by a comma
790 std::string search = " " + std::to_string(recordID) + ",";
791
792 // Loop through the ipmi_sel log entries
793 for (const std::filesystem::path& file : selLogFiles)
794 {
795 std::ifstream logStream(file);
796 if (!logStream.is_open())
797 {
798 continue;
799 }
800
801 while (std::getline(logStream, entry))
802 {
803 // Check if the record ID matches
804 if (entry.find(search) != std::string::npos)
805 {
806 return true;
807 }
808 }
809 }
810 return false;
811}
812
Patrick Williams69b4c282025-03-03 11:19:13 -0500813static uint16_t getNextRecordID(
814 const uint16_t recordID,
815 const std::vector<std::filesystem::path>& selLogFiles)
Willy Tude54f482021-01-26 15:59:09 -0800816{
817 uint16_t nextRecordID = recordID + 1;
818 std::string entry;
819 if (findSELEntry(nextRecordID, selLogFiles, entry))
820 {
821 return nextRecordID;
822 }
823 else
824 {
825 return ipmi::sel::lastEntry;
826 }
827}
828
829static int fromHexStr(const std::string& hexStr, std::vector<uint8_t>& data)
830{
831 for (unsigned int i = 0; i < hexStr.size(); i += 2)
832 {
833 try
834 {
835 data.push_back(static_cast<uint8_t>(
836 std::stoul(hexStr.substr(i, 2), nullptr, 16)));
837 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500838 catch (const std::invalid_argument& e)
Willy Tude54f482021-01-26 15:59:09 -0800839 {
George Liude6694e2024-07-17 15:22:25 +0800840 lg2::error("Invalid argument: {ERROR}", "ERROR", e);
Willy Tude54f482021-01-26 15:59:09 -0800841 return -1;
842 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500843 catch (const std::out_of_range& e)
Willy Tude54f482021-01-26 15:59:09 -0800844 {
George Liude6694e2024-07-17 15:22:25 +0800845 lg2::error("Out of range: {ERROR}", "ERROR", e);
Willy Tude54f482021-01-26 15:59:09 -0800846 return -1;
847 }
848 }
849 return 0;
850}
851
852ipmi::RspType<uint8_t, // SEL version
853 uint16_t, // SEL entry count
854 uint16_t, // free space
855 uint32_t, // last add timestamp
856 uint32_t, // last erase timestamp
857 uint8_t> // operation support
858 ipmiStorageGetSELInfo()
859{
860 constexpr uint8_t selVersion = ipmi::sel::selVersion;
861 uint16_t entries = countSELEntries();
862 uint32_t addTimeStamp = dynamic_sensors::ipmi::sel::getFileTimestamp(
863 dynamic_sensors::ipmi::sel::selLogDir /
864 dynamic_sensors::ipmi::sel::selLogFilename);
865 uint32_t eraseTimeStamp = dynamic_sensors::ipmi::sel::erase_time::get();
866 constexpr uint8_t operationSupport =
867 dynamic_sensors::ipmi::sel::selOperationSupport;
868 constexpr uint16_t freeSpace =
869 0xffff; // Spec indicates that more than 64kB is free
870
871 return ipmi::responseSuccess(selVersion, entries, freeSpace, addTimeStamp,
872 eraseTimeStamp, operationSupport);
873}
874
875using systemEventType = std::tuple<
876 uint32_t, // Timestamp
877 uint16_t, // Generator ID
878 uint8_t, // EvM Rev
879 uint8_t, // Sensor Type
880 uint8_t, // Sensor Number
881 uint7_t, // Event Type
882 bool, // Event Direction
883 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>>; // Event
884 // Data
885using oemTsEventType = std::tuple<
886 uint32_t, // Timestamp
887 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>>; // Event
888 // Data
889using oemEventType =
890 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>; // Event Data
891
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500892ipmi::RspType<uint16_t, // Next Record ID
893 uint16_t, // Record ID
894 uint8_t, // Record Type
Willy Tude54f482021-01-26 15:59:09 -0800895 std::variant<systemEventType, oemTsEventType,
896 oemEventType>> // Record Content
897 ipmiStorageGetSELEntry(uint16_t reservationID, uint16_t targetID,
898 uint8_t offset, uint8_t size)
899{
900 // Only support getting the entire SEL record. If a partial size or non-zero
901 // offset is requested, return an error
902 if (offset != 0 || size != ipmi::sel::entireRecord)
903 {
904 return ipmi::responseRetBytesUnavailable();
905 }
906
907 // Check the reservation ID if one is provided or required (only if the
908 // offset is non-zero)
909 if (reservationID != 0 || offset != 0)
910 {
911 if (!checkSELReservation(reservationID))
912 {
913 return ipmi::responseInvalidReservationId();
914 }
915 }
916
917 // Get the ipmi_sel log files
918 std::vector<std::filesystem::path> selLogFiles;
919 if (!getSELLogFiles(selLogFiles))
920 {
921 return ipmi::responseSensorInvalid();
922 }
923
924 std::string targetEntry;
925
926 if (targetID == ipmi::sel::firstEntry)
927 {
928 // The first entry will be at the top of the oldest log file
929 std::ifstream logStream(selLogFiles.back());
930 if (!logStream.is_open())
931 {
932 return ipmi::responseUnspecifiedError();
933 }
934
935 if (!std::getline(logStream, targetEntry))
936 {
937 return ipmi::responseUnspecifiedError();
938 }
939 }
940 else if (targetID == ipmi::sel::lastEntry)
941 {
942 // The last entry will be at the bottom of the newest log file
943 std::ifstream logStream(selLogFiles.front());
944 if (!logStream.is_open())
945 {
946 return ipmi::responseUnspecifiedError();
947 }
948
949 std::string line;
950 while (std::getline(logStream, line))
951 {
952 targetEntry = line;
953 }
954 }
955 else
956 {
957 if (!findSELEntry(targetID, selLogFiles, targetEntry))
958 {
959 return ipmi::responseSensorInvalid();
960 }
961 }
962
963 // The format of the ipmi_sel message is "<Timestamp>
964 // <ID>,<Type>,<EventData>,[<Generator ID>,<Path>,<Direction>]".
965 // First get the Timestamp
966 size_t space = targetEntry.find_first_of(" ");
967 if (space == std::string::npos)
968 {
969 return ipmi::responseUnspecifiedError();
970 }
971 std::string entryTimestamp = targetEntry.substr(0, space);
972 // Then get the log contents
973 size_t entryStart = targetEntry.find_first_not_of(" ", space);
974 if (entryStart == std::string::npos)
975 {
976 return ipmi::responseUnspecifiedError();
977 }
978 std::string_view entry(targetEntry);
979 entry.remove_prefix(entryStart);
980 // Use split to separate the entry into its fields
981 std::vector<std::string> targetEntryFields;
982 boost::split(targetEntryFields, entry, boost::is_any_of(","),
983 boost::token_compress_on);
984 if (targetEntryFields.size() < 3)
985 {
986 return ipmi::responseUnspecifiedError();
987 }
988 std::string& recordIDStr = targetEntryFields[0];
989 std::string& recordTypeStr = targetEntryFields[1];
990 std::string& eventDataStr = targetEntryFields[2];
991
992 uint16_t recordID;
993 uint8_t recordType;
994 try
995 {
996 recordID = std::stoul(recordIDStr);
997 recordType = std::stoul(recordTypeStr, nullptr, 16);
998 }
999 catch (const std::invalid_argument&)
1000 {
1001 return ipmi::responseUnspecifiedError();
1002 }
1003 uint16_t nextRecordID = getNextRecordID(recordID, selLogFiles);
1004 std::vector<uint8_t> eventDataBytes;
1005 if (fromHexStr(eventDataStr, eventDataBytes) < 0)
1006 {
1007 return ipmi::responseUnspecifiedError();
1008 }
1009
1010 if (recordType == dynamic_sensors::ipmi::sel::systemEvent)
1011 {
1012 // Get the timestamp
1013 std::tm timeStruct = {};
1014 std::istringstream entryStream(entryTimestamp);
1015
1016 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1017 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1018 {
Willy Tu7bb412f2023-09-25 11:30:45 -07001019 timeStruct.tm_isdst = -1;
Willy Tude54f482021-01-26 15:59:09 -08001020 timestamp = std::mktime(&timeStruct);
1021 }
1022
1023 // Set the event message revision
1024 uint8_t evmRev = dynamic_sensors::ipmi::sel::eventMsgRev;
1025
1026 uint16_t generatorID = 0;
1027 uint8_t sensorType = 0;
1028 uint16_t sensorAndLun = 0;
1029 uint8_t sensorNum = 0xFF;
1030 uint7_t eventType = 0;
1031 bool eventDir = 0;
1032 // System type events should have six fields
1033 if (targetEntryFields.size() >= 6)
1034 {
1035 std::string& generatorIDStr = targetEntryFields[3];
1036 std::string& sensorPath = targetEntryFields[4];
1037 std::string& eventDirStr = targetEntryFields[5];
1038
1039 // Get the generator ID
1040 try
1041 {
1042 generatorID = std::stoul(generatorIDStr, nullptr, 16);
1043 }
1044 catch (const std::invalid_argument&)
1045 {
Haicheng Zhang041b3752025-07-14 17:13:45 +08001046 lg2::error("Invalid Generator ID");
Willy Tude54f482021-01-26 15:59:09 -08001047 }
1048
1049 // Get the sensor type, sensor number, and event type for the sensor
1050 sensorType = getSensorTypeFromPath(sensorPath);
1051 sensorAndLun = getSensorNumberFromPath(sensorPath);
1052 sensorNum = static_cast<uint8_t>(sensorAndLun);
Harvey.Wu4376cdf2021-11-16 19:40:55 +08001053 if ((generatorID & 0x0001) == 0)
1054 {
1055 // IPMB Address
1056 generatorID |= sensorAndLun & 0x0300;
1057 }
1058 else
1059 {
1060 // system software
1061 generatorID |= sensorAndLun >> 8;
1062 }
Willy Tude54f482021-01-26 15:59:09 -08001063 eventType = getSensorEventTypeFromPath(sensorPath);
1064
1065 // Get the event direction
1066 try
1067 {
1068 eventDir = std::stoul(eventDirStr) ? 0 : 1;
1069 }
1070 catch (const std::invalid_argument&)
1071 {
Haicheng Zhang041b3752025-07-14 17:13:45 +08001072 lg2::error("Invalid Event Direction");
Willy Tude54f482021-01-26 15:59:09 -08001073 }
1074 }
1075
1076 // Only keep the eventData bytes that fit in the record
1077 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>
1078 eventData{};
1079 std::copy_n(eventDataBytes.begin(),
1080 std::min(eventDataBytes.size(), eventData.size()),
1081 eventData.begin());
1082
1083 return ipmi::responseSuccess(
1084 nextRecordID, recordID, recordType,
1085 systemEventType{timestamp, generatorID, evmRev, sensorType,
1086 sensorNum, eventType, eventDir, eventData});
1087 }
1088
Thang Trane70c59b2023-09-21 13:54:28 +07001089 if (recordType >= dynamic_sensors::ipmi::sel::oemTsEventFirst &&
1090 recordType <= dynamic_sensors::ipmi::sel::oemTsEventLast)
1091 {
1092 // Get the timestamp
1093 std::tm timeStruct = {};
1094 std::istringstream entryStream(entryTimestamp);
1095
1096 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1097 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1098 {
1099 timeStruct.tm_isdst = -1;
1100 timestamp = std::mktime(&timeStruct);
1101 }
1102
1103 // Only keep the bytes that fit in the record
1104 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>
1105 eventData{};
1106 std::copy_n(eventDataBytes.begin(),
1107 std::min(eventDataBytes.size(), eventData.size()),
1108 eventData.begin());
1109
1110 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1111 oemTsEventType{timestamp, eventData});
1112 }
1113
1114 if (recordType >= dynamic_sensors::ipmi::sel::oemEventFirst)
1115 {
1116 // Only keep the bytes that fit in the record
1117 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>
1118 eventData{};
1119 std::copy_n(eventDataBytes.begin(),
1120 std::min(eventDataBytes.size(), eventData.size()),
1121 eventData.begin());
1122
1123 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1124 eventData);
1125 }
1126
Willy Tude54f482021-01-26 15:59:09 -08001127 return ipmi::responseUnspecifiedError();
1128}
1129
Willy Tu11d68892022-01-20 10:37:34 -08001130/*
1131Unused arguments
1132 uint16_t recordID, uint8_t recordType, uint32_t timestamp,
1133 uint16_t generatorID, uint8_t evmRev, uint8_t sensorType, uint8_t sensorNum,
1134 uint8_t eventType, uint8_t eventData1, uint8_t eventData2,
1135 uint8_t eventData3
1136*/
Patrick Williams69b4c282025-03-03 11:19:13 -05001137ipmi::RspType<uint16_t> ipmiStorageAddSELEntry(
1138 uint16_t, uint8_t, uint32_t, uint16_t, uint8_t, uint8_t, uint8_t, uint8_t,
1139 uint8_t, uint8_t, uint8_t)
Willy Tude54f482021-01-26 15:59:09 -08001140{
1141 // Per the IPMI spec, need to cancel any reservation when a SEL entry is
1142 // added
1143 cancelSELReservation();
1144
1145 uint16_t responseID = 0xFFFF;
1146 return ipmi::responseSuccess(responseID);
1147}
1148
Patrick Williams1318a5e2024-08-16 15:19:54 -04001149ipmi::RspType<uint8_t> ipmiStorageClearSEL(
1150 ipmi::Context::ptr ctx, uint16_t reservationID,
1151 const std::array<uint8_t, 3>& clr, uint8_t eraseOperation)
Willy Tude54f482021-01-26 15:59:09 -08001152{
1153 if (!checkSELReservation(reservationID))
1154 {
1155 return ipmi::responseInvalidReservationId();
1156 }
1157
1158 static constexpr std::array<uint8_t, 3> clrExpected = {'C', 'L', 'R'};
1159 if (clr != clrExpected)
1160 {
1161 return ipmi::responseInvalidFieldRequest();
1162 }
1163
1164 // Erasure status cannot be fetched, so always return erasure status as
1165 // `erase completed`.
1166 if (eraseOperation == ipmi::sel::getEraseStatus)
1167 {
1168 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1169 }
1170
1171 // Check that initiate erase is correct
1172 if (eraseOperation != ipmi::sel::initiateErase)
1173 {
1174 return ipmi::responseInvalidFieldRequest();
1175 }
1176
1177 // Per the IPMI spec, need to cancel any reservation when the SEL is
1178 // cleared
1179 cancelSELReservation();
1180
George Liude1420d2025-03-03 15:14:25 +08001181 boost::system::error_code ec =
1182 ipmi::callDbusMethod(ctx, "xyz.openbmc_project.Logging.IPMI",
1183 "/xyz/openbmc_project/Logging/IPMI",
1184 "xyz.openbmc_project.Logging.IPMI", "Clear");
Charles Boyer818bea12021-09-20 16:56:36 -05001185 if (ec)
1186 {
Haicheng Zhang041b3752025-07-14 17:13:45 +08001187 lg2::error("error in clear SEL: {MSG}", "MSG", ec.message());
Charles Boyer818bea12021-09-20 16:56:36 -05001188 return ipmi::responseUnspecifiedError();
1189 }
Willy Tude54f482021-01-26 15:59:09 -08001190
1191 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1192}
1193
Patrick Williams1318a5e2024-08-16 15:19:54 -04001194std::vector<uint8_t> getType8SDRs(
1195 ipmi::sensor::EntityInfoMap::const_iterator& entity, uint16_t recordId)
Harvey Wu05d17c02021-09-15 08:46:59 +08001196{
1197 std::vector<uint8_t> resp;
1198 get_sdr::SensorDataEntityRecord data{};
1199
1200 /* Header */
Harvey Wu05d17c02021-09-15 08:46:59 +08001201 // Based on IPMI Spec v2.0 rev 1.1
George Liuc7a4da52025-08-19 16:20:31 +08001202 data.header.recordId = recordId;
Harvey Wu05d17c02021-09-15 08:46:59 +08001203 data.header.sdr_version = SDR_VERSION;
1204 data.header.record_type = 0x08;
1205 data.header.record_length = sizeof(data.key) + sizeof(data.body);
1206
1207 /* Key */
1208 data.key.containerEntityId = entity->second.containerEntityId;
1209 data.key.containerEntityInstance = entity->second.containerEntityInstance;
1210 get_sdr::key::set_flags(entity->second.isList, entity->second.isLinked,
1211 &(data.key));
1212 data.key.entityId1 = entity->second.containedEntities[0].first;
1213 data.key.entityInstance1 = entity->second.containedEntities[0].second;
1214
1215 /* Body */
1216 data.body.entityId2 = entity->second.containedEntities[1].first;
1217 data.body.entityInstance2 = entity->second.containedEntities[1].second;
1218 data.body.entityId3 = entity->second.containedEntities[2].first;
1219 data.body.entityInstance3 = entity->second.containedEntities[2].second;
1220 data.body.entityId4 = entity->second.containedEntities[3].first;
1221 data.body.entityInstance4 = entity->second.containedEntities[3].second;
1222
1223 resp.insert(resp.end(), (uint8_t*)&data, ((uint8_t*)&data) + sizeof(data));
1224
1225 return resp;
1226}
1227
Willy Tude54f482021-01-26 15:59:09 -08001228std::vector<uint8_t> getType12SDRs(uint16_t index, uint16_t recordId)
1229{
1230 std::vector<uint8_t> resp;
1231 if (index == 0)
1232 {
Willy Tude54f482021-01-26 15:59:09 -08001233 std::string bmcName = "Basbrd Mgmt Ctlr";
Johnathan Manteycd1c4962021-09-22 12:58:08 -07001234 Type12Record bmc(recordId, 0x20, 0, 0, 0xbf, 0x2e, 1, 0, bmcName);
Willy Tude54f482021-01-26 15:59:09 -08001235 uint8_t* bmcPtr = reinterpret_cast<uint8_t*>(&bmc);
1236 resp.insert(resp.end(), bmcPtr, bmcPtr + sizeof(Type12Record));
1237 }
1238 else if (index == 1)
1239 {
Willy Tude54f482021-01-26 15:59:09 -08001240 std::string meName = "Mgmt Engine";
Johnathan Manteycd1c4962021-09-22 12:58:08 -07001241 Type12Record me(recordId, 0x2c, 6, 0x24, 0x21, 0x2e, 2, 0, meName);
Willy Tude54f482021-01-26 15:59:09 -08001242 uint8_t* mePtr = reinterpret_cast<uint8_t*>(&me);
1243 resp.insert(resp.end(), mePtr, mePtr + sizeof(Type12Record));
1244 }
1245 else
1246 {
Patrick Williams1318a5e2024-08-16 15:19:54 -04001247 throw std::runtime_error(
1248 "getType12SDRs:: Illegal index " + std::to_string(index));
Willy Tude54f482021-01-26 15:59:09 -08001249 }
1250
1251 return resp;
1252}
1253
1254void registerStorageFunctions()
1255{
1256 createTimers();
1257 startMatch();
1258
1259 // <Get FRU Inventory Area Info>
Willy Tud351a722021-08-12 14:33:40 -07001260 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
Willy Tude54f482021-01-26 15:59:09 -08001261 ipmi::storage::cmdGetFruInventoryAreaInfo,
1262 ipmi::Privilege::User, ipmiStorageGetFruInvAreaInfo);
1263 // <READ FRU Data>
1264 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1265 ipmi::storage::cmdReadFruData, ipmi::Privilege::User,
1266 ipmiStorageReadFruData);
1267
1268 // <WRITE FRU Data>
1269 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1270 ipmi::storage::cmdWriteFruData,
1271 ipmi::Privilege::Operator, ipmiStorageWriteFruData);
1272
1273 // <Get SEL Info>
1274 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1275 ipmi::storage::cmdGetSelInfo, ipmi::Privilege::User,
1276 ipmiStorageGetSELInfo);
1277
1278 // <Get SEL Entry>
1279 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1280 ipmi::storage::cmdGetSelEntry, ipmi::Privilege::User,
1281 ipmiStorageGetSELEntry);
1282
1283 // <Add SEL Entry>
1284 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1285 ipmi::storage::cmdAddSelEntry,
1286 ipmi::Privilege::Operator, ipmiStorageAddSELEntry);
1287
1288 // <Clear SEL>
1289 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1290 ipmi::storage::cmdClearSel, ipmi::Privilege::Operator,
1291 ipmiStorageClearSEL);
Willy Tude54f482021-01-26 15:59:09 -08001292}
1293} // namespace storage
1294} // namespace ipmi