blob: f0c43c3cc7b21d117e1e930f769a2cf8d9f02f94 [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
712 resp.header.record_id_lsb = 0x0; // calling code is to implement these
713 resp.header.record_id_msb = 0x0;
714 resp.header.sdr_version = ipmiSdrVersion;
715 resp.header.record_type = get_sdr::SENSOR_DATA_FRU_RECORD;
716 resp.header.record_length = sizeof(resp.body) + sizeof(resp.key) - sizeDiff;
717 resp.key.deviceAddress = 0x20;
718 resp.key.fruID = device->first;
719 resp.key.accessLun = 0x80; // logical / physical fru device
720 resp.key.channelNumber = 0x0;
721 resp.body.reserved = 0x0;
722 resp.body.deviceType = 0x10;
723 resp.body.deviceTypeModifier = 0x0;
724
Willy Tude54f482021-01-26 15:59:09 -0800725 resp.body.entityID = entityID;
726 resp.body.entityInstance = entityInstance;
727
728 resp.body.oem = 0x0;
Johnathan Manteyb99de182023-12-21 08:28:18 -0800729 resp.body.deviceIDLen = ipmi::storage::typeASCIILatin8 | name.size();
Willy Tude54f482021-01-26 15:59:09 -0800730 name.copy(resp.body.deviceID, name.size());
731
George Liue8a97bd2024-12-05 17:26:46 +0800732 return ipmi::ccSuccess;
Willy Tude54f482021-01-26 15:59:09 -0800733}
734
735static bool getSELLogFiles(std::vector<std::filesystem::path>& selLogFiles)
736{
737 // Loop through the directory looking for ipmi_sel log files
738 for (const std::filesystem::directory_entry& dirEnt :
739 std::filesystem::directory_iterator(
740 dynamic_sensors::ipmi::sel::selLogDir))
741 {
742 std::string filename = dirEnt.path().filename();
George Liuc024b392025-08-21 16:38:58 +0800743 if (filename.starts_with(dynamic_sensors::ipmi::sel::selLogFilename))
Willy Tude54f482021-01-26 15:59:09 -0800744 {
745 // If we find an ipmi_sel log file, save the path
Patrick Williams1318a5e2024-08-16 15:19:54 -0400746 selLogFiles.emplace_back(
747 dynamic_sensors::ipmi::sel::selLogDir / filename);
Willy Tude54f482021-01-26 15:59:09 -0800748 }
749 }
750 // As the log files rotate, they are appended with a ".#" that is higher for
751 // the older logs. Since we don't expect more than 10 log files, we
752 // can just sort the list to get them in order from newest to oldest
753 std::sort(selLogFiles.begin(), selLogFiles.end());
754
755 return !selLogFiles.empty();
756}
757
758static int countSELEntries()
759{
760 // Get the list of ipmi_sel log files
761 std::vector<std::filesystem::path> selLogFiles;
762 if (!getSELLogFiles(selLogFiles))
763 {
764 return 0;
765 }
766 int numSELEntries = 0;
767 // Loop through each log file and count the number of logs
768 for (const std::filesystem::path& file : selLogFiles)
769 {
770 std::ifstream logStream(file);
771 if (!logStream.is_open())
772 {
773 continue;
774 }
775
776 std::string line;
777 while (std::getline(logStream, line))
778 {
779 numSELEntries++;
780 }
781 }
782 return numSELEntries;
783}
784
785static bool findSELEntry(const int recordID,
786 const std::vector<std::filesystem::path>& selLogFiles,
787 std::string& entry)
788{
789 // Record ID is the first entry field following the timestamp. It is
790 // preceded by a space and followed by a comma
791 std::string search = " " + std::to_string(recordID) + ",";
792
793 // Loop through the ipmi_sel log entries
794 for (const std::filesystem::path& file : selLogFiles)
795 {
796 std::ifstream logStream(file);
797 if (!logStream.is_open())
798 {
799 continue;
800 }
801
802 while (std::getline(logStream, entry))
803 {
804 // Check if the record ID matches
805 if (entry.find(search) != std::string::npos)
806 {
807 return true;
808 }
809 }
810 }
811 return false;
812}
813
Patrick Williams69b4c282025-03-03 11:19:13 -0500814static uint16_t getNextRecordID(
815 const uint16_t recordID,
816 const std::vector<std::filesystem::path>& selLogFiles)
Willy Tude54f482021-01-26 15:59:09 -0800817{
818 uint16_t nextRecordID = recordID + 1;
819 std::string entry;
820 if (findSELEntry(nextRecordID, selLogFiles, entry))
821 {
822 return nextRecordID;
823 }
824 else
825 {
826 return ipmi::sel::lastEntry;
827 }
828}
829
830static int fromHexStr(const std::string& hexStr, std::vector<uint8_t>& data)
831{
832 for (unsigned int i = 0; i < hexStr.size(); i += 2)
833 {
834 try
835 {
836 data.push_back(static_cast<uint8_t>(
837 std::stoul(hexStr.substr(i, 2), nullptr, 16)));
838 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500839 catch (const std::invalid_argument& e)
Willy Tude54f482021-01-26 15:59:09 -0800840 {
George Liude6694e2024-07-17 15:22:25 +0800841 lg2::error("Invalid argument: {ERROR}", "ERROR", e);
Willy Tude54f482021-01-26 15:59:09 -0800842 return -1;
843 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500844 catch (const std::out_of_range& e)
Willy Tude54f482021-01-26 15:59:09 -0800845 {
George Liude6694e2024-07-17 15:22:25 +0800846 lg2::error("Out of range: {ERROR}", "ERROR", e);
Willy Tude54f482021-01-26 15:59:09 -0800847 return -1;
848 }
849 }
850 return 0;
851}
852
853ipmi::RspType<uint8_t, // SEL version
854 uint16_t, // SEL entry count
855 uint16_t, // free space
856 uint32_t, // last add timestamp
857 uint32_t, // last erase timestamp
858 uint8_t> // operation support
859 ipmiStorageGetSELInfo()
860{
861 constexpr uint8_t selVersion = ipmi::sel::selVersion;
862 uint16_t entries = countSELEntries();
863 uint32_t addTimeStamp = dynamic_sensors::ipmi::sel::getFileTimestamp(
864 dynamic_sensors::ipmi::sel::selLogDir /
865 dynamic_sensors::ipmi::sel::selLogFilename);
866 uint32_t eraseTimeStamp = dynamic_sensors::ipmi::sel::erase_time::get();
867 constexpr uint8_t operationSupport =
868 dynamic_sensors::ipmi::sel::selOperationSupport;
869 constexpr uint16_t freeSpace =
870 0xffff; // Spec indicates that more than 64kB is free
871
872 return ipmi::responseSuccess(selVersion, entries, freeSpace, addTimeStamp,
873 eraseTimeStamp, operationSupport);
874}
875
876using systemEventType = std::tuple<
877 uint32_t, // Timestamp
878 uint16_t, // Generator ID
879 uint8_t, // EvM Rev
880 uint8_t, // Sensor Type
881 uint8_t, // Sensor Number
882 uint7_t, // Event Type
883 bool, // Event Direction
884 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>>; // Event
885 // Data
886using oemTsEventType = std::tuple<
887 uint32_t, // Timestamp
888 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>>; // Event
889 // Data
890using oemEventType =
891 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>; // Event Data
892
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500893ipmi::RspType<uint16_t, // Next Record ID
894 uint16_t, // Record ID
895 uint8_t, // Record Type
Willy Tude54f482021-01-26 15:59:09 -0800896 std::variant<systemEventType, oemTsEventType,
897 oemEventType>> // Record Content
898 ipmiStorageGetSELEntry(uint16_t reservationID, uint16_t targetID,
899 uint8_t offset, uint8_t size)
900{
901 // Only support getting the entire SEL record. If a partial size or non-zero
902 // offset is requested, return an error
903 if (offset != 0 || size != ipmi::sel::entireRecord)
904 {
905 return ipmi::responseRetBytesUnavailable();
906 }
907
908 // Check the reservation ID if one is provided or required (only if the
909 // offset is non-zero)
910 if (reservationID != 0 || offset != 0)
911 {
912 if (!checkSELReservation(reservationID))
913 {
914 return ipmi::responseInvalidReservationId();
915 }
916 }
917
918 // Get the ipmi_sel log files
919 std::vector<std::filesystem::path> selLogFiles;
920 if (!getSELLogFiles(selLogFiles))
921 {
922 return ipmi::responseSensorInvalid();
923 }
924
925 std::string targetEntry;
926
927 if (targetID == ipmi::sel::firstEntry)
928 {
929 // The first entry will be at the top of the oldest log file
930 std::ifstream logStream(selLogFiles.back());
931 if (!logStream.is_open())
932 {
933 return ipmi::responseUnspecifiedError();
934 }
935
936 if (!std::getline(logStream, targetEntry))
937 {
938 return ipmi::responseUnspecifiedError();
939 }
940 }
941 else if (targetID == ipmi::sel::lastEntry)
942 {
943 // The last entry will be at the bottom of the newest log file
944 std::ifstream logStream(selLogFiles.front());
945 if (!logStream.is_open())
946 {
947 return ipmi::responseUnspecifiedError();
948 }
949
950 std::string line;
951 while (std::getline(logStream, line))
952 {
953 targetEntry = line;
954 }
955 }
956 else
957 {
958 if (!findSELEntry(targetID, selLogFiles, targetEntry))
959 {
960 return ipmi::responseSensorInvalid();
961 }
962 }
963
964 // The format of the ipmi_sel message is "<Timestamp>
965 // <ID>,<Type>,<EventData>,[<Generator ID>,<Path>,<Direction>]".
966 // First get the Timestamp
967 size_t space = targetEntry.find_first_of(" ");
968 if (space == std::string::npos)
969 {
970 return ipmi::responseUnspecifiedError();
971 }
972 std::string entryTimestamp = targetEntry.substr(0, space);
973 // Then get the log contents
974 size_t entryStart = targetEntry.find_first_not_of(" ", space);
975 if (entryStart == std::string::npos)
976 {
977 return ipmi::responseUnspecifiedError();
978 }
979 std::string_view entry(targetEntry);
980 entry.remove_prefix(entryStart);
981 // Use split to separate the entry into its fields
982 std::vector<std::string> targetEntryFields;
983 boost::split(targetEntryFields, entry, boost::is_any_of(","),
984 boost::token_compress_on);
985 if (targetEntryFields.size() < 3)
986 {
987 return ipmi::responseUnspecifiedError();
988 }
989 std::string& recordIDStr = targetEntryFields[0];
990 std::string& recordTypeStr = targetEntryFields[1];
991 std::string& eventDataStr = targetEntryFields[2];
992
993 uint16_t recordID;
994 uint8_t recordType;
995 try
996 {
997 recordID = std::stoul(recordIDStr);
998 recordType = std::stoul(recordTypeStr, nullptr, 16);
999 }
1000 catch (const std::invalid_argument&)
1001 {
1002 return ipmi::responseUnspecifiedError();
1003 }
1004 uint16_t nextRecordID = getNextRecordID(recordID, selLogFiles);
1005 std::vector<uint8_t> eventDataBytes;
1006 if (fromHexStr(eventDataStr, eventDataBytes) < 0)
1007 {
1008 return ipmi::responseUnspecifiedError();
1009 }
1010
1011 if (recordType == dynamic_sensors::ipmi::sel::systemEvent)
1012 {
1013 // Get the timestamp
1014 std::tm timeStruct = {};
1015 std::istringstream entryStream(entryTimestamp);
1016
1017 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1018 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1019 {
Willy Tu7bb412f2023-09-25 11:30:45 -07001020 timeStruct.tm_isdst = -1;
Willy Tude54f482021-01-26 15:59:09 -08001021 timestamp = std::mktime(&timeStruct);
1022 }
1023
1024 // Set the event message revision
1025 uint8_t evmRev = dynamic_sensors::ipmi::sel::eventMsgRev;
1026
1027 uint16_t generatorID = 0;
1028 uint8_t sensorType = 0;
1029 uint16_t sensorAndLun = 0;
1030 uint8_t sensorNum = 0xFF;
1031 uint7_t eventType = 0;
1032 bool eventDir = 0;
1033 // System type events should have six fields
1034 if (targetEntryFields.size() >= 6)
1035 {
1036 std::string& generatorIDStr = targetEntryFields[3];
1037 std::string& sensorPath = targetEntryFields[4];
1038 std::string& eventDirStr = targetEntryFields[5];
1039
1040 // Get the generator ID
1041 try
1042 {
1043 generatorID = std::stoul(generatorIDStr, nullptr, 16);
1044 }
1045 catch (const std::invalid_argument&)
1046 {
Haicheng Zhang041b3752025-07-14 17:13:45 +08001047 lg2::error("Invalid Generator ID");
Willy Tude54f482021-01-26 15:59:09 -08001048 }
1049
1050 // Get the sensor type, sensor number, and event type for the sensor
1051 sensorType = getSensorTypeFromPath(sensorPath);
1052 sensorAndLun = getSensorNumberFromPath(sensorPath);
1053 sensorNum = static_cast<uint8_t>(sensorAndLun);
Harvey.Wu4376cdf2021-11-16 19:40:55 +08001054 if ((generatorID & 0x0001) == 0)
1055 {
1056 // IPMB Address
1057 generatorID |= sensorAndLun & 0x0300;
1058 }
1059 else
1060 {
1061 // system software
1062 generatorID |= sensorAndLun >> 8;
1063 }
Willy Tude54f482021-01-26 15:59:09 -08001064 eventType = getSensorEventTypeFromPath(sensorPath);
1065
1066 // Get the event direction
1067 try
1068 {
1069 eventDir = std::stoul(eventDirStr) ? 0 : 1;
1070 }
1071 catch (const std::invalid_argument&)
1072 {
Haicheng Zhang041b3752025-07-14 17:13:45 +08001073 lg2::error("Invalid Event Direction");
Willy Tude54f482021-01-26 15:59:09 -08001074 }
1075 }
1076
1077 // Only keep the eventData bytes that fit in the record
1078 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>
1079 eventData{};
1080 std::copy_n(eventDataBytes.begin(),
1081 std::min(eventDataBytes.size(), eventData.size()),
1082 eventData.begin());
1083
1084 return ipmi::responseSuccess(
1085 nextRecordID, recordID, recordType,
1086 systemEventType{timestamp, generatorID, evmRev, sensorType,
1087 sensorNum, eventType, eventDir, eventData});
1088 }
1089
Thang Trane70c59b2023-09-21 13:54:28 +07001090 if (recordType >= dynamic_sensors::ipmi::sel::oemTsEventFirst &&
1091 recordType <= dynamic_sensors::ipmi::sel::oemTsEventLast)
1092 {
1093 // Get the timestamp
1094 std::tm timeStruct = {};
1095 std::istringstream entryStream(entryTimestamp);
1096
1097 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1098 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1099 {
1100 timeStruct.tm_isdst = -1;
1101 timestamp = std::mktime(&timeStruct);
1102 }
1103
1104 // Only keep the bytes that fit in the record
1105 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>
1106 eventData{};
1107 std::copy_n(eventDataBytes.begin(),
1108 std::min(eventDataBytes.size(), eventData.size()),
1109 eventData.begin());
1110
1111 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1112 oemTsEventType{timestamp, eventData});
1113 }
1114
1115 if (recordType >= dynamic_sensors::ipmi::sel::oemEventFirst)
1116 {
1117 // Only keep the bytes that fit in the record
1118 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>
1119 eventData{};
1120 std::copy_n(eventDataBytes.begin(),
1121 std::min(eventDataBytes.size(), eventData.size()),
1122 eventData.begin());
1123
1124 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1125 eventData);
1126 }
1127
Willy Tude54f482021-01-26 15:59:09 -08001128 return ipmi::responseUnspecifiedError();
1129}
1130
Willy Tu11d68892022-01-20 10:37:34 -08001131/*
1132Unused arguments
1133 uint16_t recordID, uint8_t recordType, uint32_t timestamp,
1134 uint16_t generatorID, uint8_t evmRev, uint8_t sensorType, uint8_t sensorNum,
1135 uint8_t eventType, uint8_t eventData1, uint8_t eventData2,
1136 uint8_t eventData3
1137*/
Patrick Williams69b4c282025-03-03 11:19:13 -05001138ipmi::RspType<uint16_t> ipmiStorageAddSELEntry(
1139 uint16_t, uint8_t, uint32_t, uint16_t, uint8_t, uint8_t, uint8_t, uint8_t,
1140 uint8_t, uint8_t, uint8_t)
Willy Tude54f482021-01-26 15:59:09 -08001141{
1142 // Per the IPMI spec, need to cancel any reservation when a SEL entry is
1143 // added
1144 cancelSELReservation();
1145
1146 uint16_t responseID = 0xFFFF;
1147 return ipmi::responseSuccess(responseID);
1148}
1149
Patrick Williams1318a5e2024-08-16 15:19:54 -04001150ipmi::RspType<uint8_t> ipmiStorageClearSEL(
1151 ipmi::Context::ptr ctx, uint16_t reservationID,
1152 const std::array<uint8_t, 3>& clr, uint8_t eraseOperation)
Willy Tude54f482021-01-26 15:59:09 -08001153{
1154 if (!checkSELReservation(reservationID))
1155 {
1156 return ipmi::responseInvalidReservationId();
1157 }
1158
1159 static constexpr std::array<uint8_t, 3> clrExpected = {'C', 'L', 'R'};
1160 if (clr != clrExpected)
1161 {
1162 return ipmi::responseInvalidFieldRequest();
1163 }
1164
1165 // Erasure status cannot be fetched, so always return erasure status as
1166 // `erase completed`.
1167 if (eraseOperation == ipmi::sel::getEraseStatus)
1168 {
1169 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1170 }
1171
1172 // Check that initiate erase is correct
1173 if (eraseOperation != ipmi::sel::initiateErase)
1174 {
1175 return ipmi::responseInvalidFieldRequest();
1176 }
1177
1178 // Per the IPMI spec, need to cancel any reservation when the SEL is
1179 // cleared
1180 cancelSELReservation();
1181
George Liude1420d2025-03-03 15:14:25 +08001182 boost::system::error_code ec =
1183 ipmi::callDbusMethod(ctx, "xyz.openbmc_project.Logging.IPMI",
1184 "/xyz/openbmc_project/Logging/IPMI",
1185 "xyz.openbmc_project.Logging.IPMI", "Clear");
Charles Boyer818bea12021-09-20 16:56:36 -05001186 if (ec)
1187 {
Haicheng Zhang041b3752025-07-14 17:13:45 +08001188 lg2::error("error in clear SEL: {MSG}", "MSG", ec.message());
Charles Boyer818bea12021-09-20 16:56:36 -05001189 return ipmi::responseUnspecifiedError();
1190 }
Willy Tude54f482021-01-26 15:59:09 -08001191
1192 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1193}
1194
Patrick Williams1318a5e2024-08-16 15:19:54 -04001195std::vector<uint8_t> getType8SDRs(
1196 ipmi::sensor::EntityInfoMap::const_iterator& entity, uint16_t recordId)
Harvey Wu05d17c02021-09-15 08:46:59 +08001197{
1198 std::vector<uint8_t> resp;
1199 get_sdr::SensorDataEntityRecord data{};
1200
1201 /* Header */
1202 get_sdr::header::set_record_id(recordId, &(data.header));
1203 // Based on IPMI Spec v2.0 rev 1.1
1204 data.header.sdr_version = SDR_VERSION;
1205 data.header.record_type = 0x08;
1206 data.header.record_length = sizeof(data.key) + sizeof(data.body);
1207
1208 /* Key */
1209 data.key.containerEntityId = entity->second.containerEntityId;
1210 data.key.containerEntityInstance = entity->second.containerEntityInstance;
1211 get_sdr::key::set_flags(entity->second.isList, entity->second.isLinked,
1212 &(data.key));
1213 data.key.entityId1 = entity->second.containedEntities[0].first;
1214 data.key.entityInstance1 = entity->second.containedEntities[0].second;
1215
1216 /* Body */
1217 data.body.entityId2 = entity->second.containedEntities[1].first;
1218 data.body.entityInstance2 = entity->second.containedEntities[1].second;
1219 data.body.entityId3 = entity->second.containedEntities[2].first;
1220 data.body.entityInstance3 = entity->second.containedEntities[2].second;
1221 data.body.entityId4 = entity->second.containedEntities[3].first;
1222 data.body.entityInstance4 = entity->second.containedEntities[3].second;
1223
1224 resp.insert(resp.end(), (uint8_t*)&data, ((uint8_t*)&data) + sizeof(data));
1225
1226 return resp;
1227}
1228
Willy Tude54f482021-01-26 15:59:09 -08001229std::vector<uint8_t> getType12SDRs(uint16_t index, uint16_t recordId)
1230{
1231 std::vector<uint8_t> resp;
1232 if (index == 0)
1233 {
Willy Tude54f482021-01-26 15:59:09 -08001234 std::string bmcName = "Basbrd Mgmt Ctlr";
Johnathan Manteycd1c4962021-09-22 12:58:08 -07001235 Type12Record bmc(recordId, 0x20, 0, 0, 0xbf, 0x2e, 1, 0, bmcName);
Willy Tude54f482021-01-26 15:59:09 -08001236 uint8_t* bmcPtr = reinterpret_cast<uint8_t*>(&bmc);
1237 resp.insert(resp.end(), bmcPtr, bmcPtr + sizeof(Type12Record));
1238 }
1239 else if (index == 1)
1240 {
Willy Tude54f482021-01-26 15:59:09 -08001241 std::string meName = "Mgmt Engine";
Johnathan Manteycd1c4962021-09-22 12:58:08 -07001242 Type12Record me(recordId, 0x2c, 6, 0x24, 0x21, 0x2e, 2, 0, meName);
Willy Tude54f482021-01-26 15:59:09 -08001243 uint8_t* mePtr = reinterpret_cast<uint8_t*>(&me);
1244 resp.insert(resp.end(), mePtr, mePtr + sizeof(Type12Record));
1245 }
1246 else
1247 {
Patrick Williams1318a5e2024-08-16 15:19:54 -04001248 throw std::runtime_error(
1249 "getType12SDRs:: Illegal index " + std::to_string(index));
Willy Tude54f482021-01-26 15:59:09 -08001250 }
1251
1252 return resp;
1253}
1254
1255void registerStorageFunctions()
1256{
1257 createTimers();
1258 startMatch();
1259
1260 // <Get FRU Inventory Area Info>
Willy Tud351a722021-08-12 14:33:40 -07001261 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
Willy Tude54f482021-01-26 15:59:09 -08001262 ipmi::storage::cmdGetFruInventoryAreaInfo,
1263 ipmi::Privilege::User, ipmiStorageGetFruInvAreaInfo);
1264 // <READ FRU Data>
1265 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1266 ipmi::storage::cmdReadFruData, ipmi::Privilege::User,
1267 ipmiStorageReadFruData);
1268
1269 // <WRITE FRU Data>
1270 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1271 ipmi::storage::cmdWriteFruData,
1272 ipmi::Privilege::Operator, ipmiStorageWriteFruData);
1273
1274 // <Get SEL Info>
1275 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1276 ipmi::storage::cmdGetSelInfo, ipmi::Privilege::User,
1277 ipmiStorageGetSELInfo);
1278
1279 // <Get SEL Entry>
1280 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1281 ipmi::storage::cmdGetSelEntry, ipmi::Privilege::User,
1282 ipmiStorageGetSELEntry);
1283
1284 // <Add SEL Entry>
1285 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1286 ipmi::storage::cmdAddSelEntry,
1287 ipmi::Privilege::Operator, ipmiStorageAddSELEntry);
1288
1289 // <Clear SEL>
1290 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1291 ipmi::storage::cmdClearSel, ipmi::Privilege::Operator,
1292 ipmiStorageClearSEL);
Willy Tude54f482021-01-26 15:59:09 -08001293}
1294} // namespace storage
1295} // namespace ipmi