blob: e8c42235cf00975624f0ca108d50b20cc571ddec [file] [log] [blame]
Willy Tude54f482021-01-26 15:59:09 -08001/*
2// Copyright (c) 2017-2019 Intel Corporation
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15*/
16
17#include "dbus-sdr/storagecommands.hpp"
18
19#include "dbus-sdr/sdrutils.hpp"
20#include "selutility.hpp"
21
22#include <boost/algorithm/string.hpp>
Ed Tanous98605052025-02-13 16:57:13 -080023#include <boost/asio/detached.hpp>
Willy Tude54f482021-01-26 15:59:09 -080024#include <boost/container/flat_map.hpp>
25#include <boost/process.hpp>
Willy Tude54f482021-01-26 15:59:09 -080026#include <ipmid/api.hpp>
27#include <ipmid/message.hpp>
28#include <ipmid/types.hpp>
George Liude1420d2025-03-03 15:14:25 +080029#include <ipmid/utils.hpp>
George Liude6694e2024-07-17 15:22:25 +080030#include <phosphor-logging/lg2.hpp>
Willy Tude54f482021-01-26 15:59:09 -080031#include <sdbusplus/message/types.hpp>
32#include <sdbusplus/timer.hpp>
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -050033
34#include <filesystem>
35#include <fstream>
36#include <functional>
37#include <iostream>
Willy Tude54f482021-01-26 15:59:09 -080038#include <stdexcept>
39#include <string_view>
40
41static constexpr bool DEBUG = false;
42
43namespace dynamic_sensors::ipmi::sel
44{
45static const std::filesystem::path selLogDir = "/var/log";
46static const std::string selLogFilename = "ipmi_sel";
47
48static int getFileTimestamp(const std::filesystem::path& file)
49{
50 struct stat st;
51
52 if (stat(file.c_str(), &st) >= 0)
53 {
54 return st.st_mtime;
55 }
56 return ::ipmi::sel::invalidTimeStamp;
57}
58
59namespace erase_time
60{
61static constexpr const char* selEraseTimestamp = "/var/lib/ipmi/sel_erase_time";
62
Willy Tude54f482021-01-26 15:59:09 -080063int get()
64{
65 return getFileTimestamp(selEraseTimestamp);
66}
67} // namespace erase_time
68} // namespace dynamic_sensors::ipmi::sel
69
70namespace ipmi
71{
72
73namespace storage
74{
75
Willy Tude54f482021-01-26 15:59:09 -080076constexpr static const size_t maxFruSdrNameSize = 16;
77using ObjectType =
78 boost::container::flat_map<std::string,
79 boost::container::flat_map<std::string, Value>>;
80using ManagedObjectType =
81 boost::container::flat_map<sdbusplus::message::object_path, ObjectType>;
82using ManagedEntry = std::pair<sdbusplus::message::object_path, ObjectType>;
83
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 {
Willy Tu48fe64e2022-08-01 23:23:46 +0000244 return {IPMI_CC_SENSOR_INVALID, {}};
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
Willy Tu11d68892022-01-20 10:37:34 -0800539ipmi_ret_t getFruSdrCount(ipmi::Context::ptr, size_t& count)
Willy Tude54f482021-01-26 15:59:09 -0800540{
541 count = deviceHashes.size();
542 return IPMI_CC_OK;
543}
544
Johnathan Mantey23a722c2023-05-12 08:18:54 -0700545ipmi_ret_t getFruSdrs([[maybe_unused]] ipmi::Context::ptr ctx, size_t index,
Willy Tude54f482021-01-26 15:59:09 -0800546 get_sdr::SensorDataFruRecord& resp)
547{
548 if (deviceHashes.size() < index)
549 {
550 return IPMI_CC_INVALID_FIELD_REQUEST;
551 }
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 {
586 return IPMI_CC_RESPONSE_ERROR;
587 }
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530588 std::string name;
Willy Tude54f482021-01-26 15:59:09 -0800589
590#ifdef USING_ENTITY_MANAGER_DECORATORS
591
592 boost::container::flat_map<std::string, Value>* entityData = nullptr;
593
594 // todo: this should really use caching, this is a very inefficient lookup
595 boost::system::error_code ec;
George Liude1420d2025-03-03 15:14:25 +0800596 ManagedObjectType entities = ipmi::callDbusMethod<ManagedObjectType>(
597 ctx, ec, "xyz.openbmc_project.EntityManager",
Nan Zhou947da1b2022-09-20 20:40:59 +0000598 "/xyz/openbmc_project/inventory", "org.freedesktop.DBus.ObjectManager",
599 "GetManagedObjects");
Willy Tude54f482021-01-26 15:59:09 -0800600
601 if (ec)
602 {
George Liude6694e2024-07-17 15:22:25 +0800603 lg2::error("GetMangagedObjects for ipmiStorageGetFruInvAreaInfo "
604 "failed: {ERROR}",
605 "ERROR", ec.message());
Willy Tude54f482021-01-26 15:59:09 -0800606
607 return ipmi::ccResponseError;
608 }
609
Patrick Williams1318a5e2024-08-16 15:19:54 -0400610 auto entity = std::find_if(
611 entities.begin(), entities.end(),
612 [bus, address, &entityData, &name](ManagedEntry& entry) {
613 auto findFruDevice = entry.second.find(
614 "xyz.openbmc_project.Inventory.Decorator.I2CDevice");
615 if (findFruDevice == entry.second.end())
616 {
617 return false;
618 }
Willy Tude54f482021-01-26 15:59:09 -0800619
Patrick Williams1318a5e2024-08-16 15:19:54 -0400620 // Integer fields added via Entity-Manager json are uint64_ts by
621 // default.
622 auto findBus = findFruDevice->second.find("Bus");
623 auto findAddress = findFruDevice->second.find("Address");
Willy Tude54f482021-01-26 15:59:09 -0800624
Patrick Williams1318a5e2024-08-16 15:19:54 -0400625 if (findBus == findFruDevice->second.end() ||
626 findAddress == findFruDevice->second.end())
627 {
628 return false;
629 }
630 if ((std::get<uint64_t>(findBus->second) != bus) ||
631 (std::get<uint64_t>(findAddress->second) != address))
632 {
633 return false;
634 }
Willy Tude54f482021-01-26 15:59:09 -0800635
Patrick Williams1318a5e2024-08-16 15:19:54 -0400636 auto fruName = findFruDevice->second.find("Name");
637 if (fruName != findFruDevice->second.end())
638 {
639 name = std::get<std::string>(fruName->second);
640 }
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530641
Patrick Williams1318a5e2024-08-16 15:19:54 -0400642 // At this point we found the device entry and should return
643 // true.
644 auto findIpmiDevice = entry.second.find(
645 "xyz.openbmc_project.Inventory.Decorator.Ipmi");
646 if (findIpmiDevice != entry.second.end())
647 {
648 entityData = &(findIpmiDevice->second);
649 }
Willy Tude54f482021-01-26 15:59:09 -0800650
Patrick Williams1318a5e2024-08-16 15:19:54 -0400651 return true;
652 });
Willy Tude54f482021-01-26 15:59:09 -0800653
654 if (entity == entities.end())
655 {
656 if constexpr (DEBUG)
657 {
658 std::fprintf(stderr, "Ipmi or FruDevice Decorator interface "
659 "not found for Fru\n");
660 }
661 }
662
663#endif
664
Alexander Hansenea46f3c2023-09-04 11:27:54 +0200665 std::vector<std::string> nameProperties = {
666 "PRODUCT_PRODUCT_NAME", "BOARD_PRODUCT_NAME", "PRODUCT_PART_NUMBER",
667 "BOARD_PART_NUMBER", "PRODUCT_MANUFACTURER", "BOARD_MANUFACTURER",
668 "PRODUCT_SERIAL_NUMBER", "BOARD_SERIAL_NUMBER"};
669
670 for (const std::string& prop : nameProperties)
671 {
672 auto findProp = fruData->find(prop);
673 if (findProp != fruData->end())
674 {
675 name = std::get<std::string>(findProp->second);
676 break;
677 }
678 }
679
Shakeeb Pashaeacad3c2021-06-28 20:25:17 +0530680 if (name.empty())
Willy Tude54f482021-01-26 15:59:09 -0800681 {
682 name = "UNKNOWN";
683 }
684 if (name.size() > maxFruSdrNameSize)
685 {
686 name = name.substr(0, maxFruSdrNameSize);
687 }
688 size_t sizeDiff = maxFruSdrNameSize - name.size();
689
690 resp.header.record_id_lsb = 0x0; // calling code is to implement these
691 resp.header.record_id_msb = 0x0;
692 resp.header.sdr_version = ipmiSdrVersion;
693 resp.header.record_type = get_sdr::SENSOR_DATA_FRU_RECORD;
694 resp.header.record_length = sizeof(resp.body) + sizeof(resp.key) - sizeDiff;
695 resp.key.deviceAddress = 0x20;
696 resp.key.fruID = device->first;
697 resp.key.accessLun = 0x80; // logical / physical fru device
698 resp.key.channelNumber = 0x0;
699 resp.body.reserved = 0x0;
700 resp.body.deviceType = 0x10;
701 resp.body.deviceTypeModifier = 0x0;
702
703 uint8_t entityID = 0;
704 uint8_t entityInstance = 0x1;
705
706#ifdef USING_ENTITY_MANAGER_DECORATORS
707 if (entityData)
708 {
709 auto entityIdProperty = entityData->find("EntityId");
710 auto entityInstanceProperty = entityData->find("EntityInstance");
711
712 if (entityIdProperty != entityData->end())
713 {
714 entityID = static_cast<uint8_t>(
715 std::get<uint64_t>(entityIdProperty->second));
716 }
717 if (entityInstanceProperty != entityData->end())
718 {
719 entityInstance = static_cast<uint8_t>(
720 std::get<uint64_t>(entityInstanceProperty->second));
721 }
722 }
723#endif
724
725 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
732 return IPMI_CC_OK;
733}
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();
743 if (boost::starts_with(filename,
744 dynamic_sensors::ipmi::sel::selLogFilename))
745 {
746 // If we find an ipmi_sel log file, save the path
Patrick Williams1318a5e2024-08-16 15:19:54 -0400747 selLogFiles.emplace_back(
748 dynamic_sensors::ipmi::sel::selLogDir / filename);
Willy Tude54f482021-01-26 15:59:09 -0800749 }
750 }
751 // As the log files rotate, they are appended with a ".#" that is higher for
752 // the older logs. Since we don't expect more than 10 log files, we
753 // can just sort the list to get them in order from newest to oldest
754 std::sort(selLogFiles.begin(), selLogFiles.end());
755
756 return !selLogFiles.empty();
757}
758
759static int countSELEntries()
760{
761 // Get the list of ipmi_sel log files
762 std::vector<std::filesystem::path> selLogFiles;
763 if (!getSELLogFiles(selLogFiles))
764 {
765 return 0;
766 }
767 int numSELEntries = 0;
768 // Loop through each log file and count the number of logs
769 for (const std::filesystem::path& file : selLogFiles)
770 {
771 std::ifstream logStream(file);
772 if (!logStream.is_open())
773 {
774 continue;
775 }
776
777 std::string line;
778 while (std::getline(logStream, line))
779 {
780 numSELEntries++;
781 }
782 }
783 return numSELEntries;
784}
785
786static bool findSELEntry(const int recordID,
787 const std::vector<std::filesystem::path>& selLogFiles,
788 std::string& entry)
789{
790 // Record ID is the first entry field following the timestamp. It is
791 // preceded by a space and followed by a comma
792 std::string search = " " + std::to_string(recordID) + ",";
793
794 // Loop through the ipmi_sel log entries
795 for (const std::filesystem::path& file : selLogFiles)
796 {
797 std::ifstream logStream(file);
798 if (!logStream.is_open())
799 {
800 continue;
801 }
802
803 while (std::getline(logStream, entry))
804 {
805 // Check if the record ID matches
806 if (entry.find(search) != std::string::npos)
807 {
808 return true;
809 }
810 }
811 }
812 return false;
813}
814
Patrick Williams69b4c282025-03-03 11:19:13 -0500815static uint16_t getNextRecordID(
816 const uint16_t recordID,
817 const std::vector<std::filesystem::path>& selLogFiles)
Willy Tude54f482021-01-26 15:59:09 -0800818{
819 uint16_t nextRecordID = recordID + 1;
820 std::string entry;
821 if (findSELEntry(nextRecordID, selLogFiles, entry))
822 {
823 return nextRecordID;
824 }
825 else
826 {
827 return ipmi::sel::lastEntry;
828 }
829}
830
831static int fromHexStr(const std::string& hexStr, std::vector<uint8_t>& data)
832{
833 for (unsigned int i = 0; i < hexStr.size(); i += 2)
834 {
835 try
836 {
837 data.push_back(static_cast<uint8_t>(
838 std::stoul(hexStr.substr(i, 2), nullptr, 16)));
839 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500840 catch (const std::invalid_argument& e)
Willy Tude54f482021-01-26 15:59:09 -0800841 {
George Liude6694e2024-07-17 15:22:25 +0800842 lg2::error("Invalid argument: {ERROR}", "ERROR", e);
Willy Tude54f482021-01-26 15:59:09 -0800843 return -1;
844 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500845 catch (const std::out_of_range& e)
Willy Tude54f482021-01-26 15:59:09 -0800846 {
George Liude6694e2024-07-17 15:22:25 +0800847 lg2::error("Out of range: {ERROR}", "ERROR", e);
Willy Tude54f482021-01-26 15:59:09 -0800848 return -1;
849 }
850 }
851 return 0;
852}
853
854ipmi::RspType<uint8_t, // SEL version
855 uint16_t, // SEL entry count
856 uint16_t, // free space
857 uint32_t, // last add timestamp
858 uint32_t, // last erase timestamp
859 uint8_t> // operation support
860 ipmiStorageGetSELInfo()
861{
862 constexpr uint8_t selVersion = ipmi::sel::selVersion;
863 uint16_t entries = countSELEntries();
864 uint32_t addTimeStamp = dynamic_sensors::ipmi::sel::getFileTimestamp(
865 dynamic_sensors::ipmi::sel::selLogDir /
866 dynamic_sensors::ipmi::sel::selLogFilename);
867 uint32_t eraseTimeStamp = dynamic_sensors::ipmi::sel::erase_time::get();
868 constexpr uint8_t operationSupport =
869 dynamic_sensors::ipmi::sel::selOperationSupport;
870 constexpr uint16_t freeSpace =
871 0xffff; // Spec indicates that more than 64kB is free
872
873 return ipmi::responseSuccess(selVersion, entries, freeSpace, addTimeStamp,
874 eraseTimeStamp, operationSupport);
875}
876
877using systemEventType = std::tuple<
878 uint32_t, // Timestamp
879 uint16_t, // Generator ID
880 uint8_t, // EvM Rev
881 uint8_t, // Sensor Type
882 uint8_t, // Sensor Number
883 uint7_t, // Event Type
884 bool, // Event Direction
885 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>>; // Event
886 // Data
887using oemTsEventType = std::tuple<
888 uint32_t, // Timestamp
889 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>>; // Event
890 // Data
891using oemEventType =
892 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>; // Event Data
893
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500894ipmi::RspType<uint16_t, // Next Record ID
895 uint16_t, // Record ID
896 uint8_t, // Record Type
Willy Tude54f482021-01-26 15:59:09 -0800897 std::variant<systemEventType, oemTsEventType,
898 oemEventType>> // Record Content
899 ipmiStorageGetSELEntry(uint16_t reservationID, uint16_t targetID,
900 uint8_t offset, uint8_t size)
901{
902 // Only support getting the entire SEL record. If a partial size or non-zero
903 // offset is requested, return an error
904 if (offset != 0 || size != ipmi::sel::entireRecord)
905 {
906 return ipmi::responseRetBytesUnavailable();
907 }
908
909 // Check the reservation ID if one is provided or required (only if the
910 // offset is non-zero)
911 if (reservationID != 0 || offset != 0)
912 {
913 if (!checkSELReservation(reservationID))
914 {
915 return ipmi::responseInvalidReservationId();
916 }
917 }
918
919 // Get the ipmi_sel log files
920 std::vector<std::filesystem::path> selLogFiles;
921 if (!getSELLogFiles(selLogFiles))
922 {
923 return ipmi::responseSensorInvalid();
924 }
925
926 std::string targetEntry;
927
928 if (targetID == ipmi::sel::firstEntry)
929 {
930 // The first entry will be at the top of the oldest log file
931 std::ifstream logStream(selLogFiles.back());
932 if (!logStream.is_open())
933 {
934 return ipmi::responseUnspecifiedError();
935 }
936
937 if (!std::getline(logStream, targetEntry))
938 {
939 return ipmi::responseUnspecifiedError();
940 }
941 }
942 else if (targetID == ipmi::sel::lastEntry)
943 {
944 // The last entry will be at the bottom of the newest log file
945 std::ifstream logStream(selLogFiles.front());
946 if (!logStream.is_open())
947 {
948 return ipmi::responseUnspecifiedError();
949 }
950
951 std::string line;
952 while (std::getline(logStream, line))
953 {
954 targetEntry = line;
955 }
956 }
957 else
958 {
959 if (!findSELEntry(targetID, selLogFiles, targetEntry))
960 {
961 return ipmi::responseSensorInvalid();
962 }
963 }
964
965 // The format of the ipmi_sel message is "<Timestamp>
966 // <ID>,<Type>,<EventData>,[<Generator ID>,<Path>,<Direction>]".
967 // First get the Timestamp
968 size_t space = targetEntry.find_first_of(" ");
969 if (space == std::string::npos)
970 {
971 return ipmi::responseUnspecifiedError();
972 }
973 std::string entryTimestamp = targetEntry.substr(0, space);
974 // Then get the log contents
975 size_t entryStart = targetEntry.find_first_not_of(" ", space);
976 if (entryStart == std::string::npos)
977 {
978 return ipmi::responseUnspecifiedError();
979 }
980 std::string_view entry(targetEntry);
981 entry.remove_prefix(entryStart);
982 // Use split to separate the entry into its fields
983 std::vector<std::string> targetEntryFields;
984 boost::split(targetEntryFields, entry, boost::is_any_of(","),
985 boost::token_compress_on);
986 if (targetEntryFields.size() < 3)
987 {
988 return ipmi::responseUnspecifiedError();
989 }
990 std::string& recordIDStr = targetEntryFields[0];
991 std::string& recordTypeStr = targetEntryFields[1];
992 std::string& eventDataStr = targetEntryFields[2];
993
994 uint16_t recordID;
995 uint8_t recordType;
996 try
997 {
998 recordID = std::stoul(recordIDStr);
999 recordType = std::stoul(recordTypeStr, nullptr, 16);
1000 }
1001 catch (const std::invalid_argument&)
1002 {
1003 return ipmi::responseUnspecifiedError();
1004 }
1005 uint16_t nextRecordID = getNextRecordID(recordID, selLogFiles);
1006 std::vector<uint8_t> eventDataBytes;
1007 if (fromHexStr(eventDataStr, eventDataBytes) < 0)
1008 {
1009 return ipmi::responseUnspecifiedError();
1010 }
1011
1012 if (recordType == dynamic_sensors::ipmi::sel::systemEvent)
1013 {
1014 // Get the timestamp
1015 std::tm timeStruct = {};
1016 std::istringstream entryStream(entryTimestamp);
1017
1018 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1019 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1020 {
Willy Tu7bb412f2023-09-25 11:30:45 -07001021 timeStruct.tm_isdst = -1;
Willy Tude54f482021-01-26 15:59:09 -08001022 timestamp = std::mktime(&timeStruct);
1023 }
1024
1025 // Set the event message revision
1026 uint8_t evmRev = dynamic_sensors::ipmi::sel::eventMsgRev;
1027
1028 uint16_t generatorID = 0;
1029 uint8_t sensorType = 0;
1030 uint16_t sensorAndLun = 0;
1031 uint8_t sensorNum = 0xFF;
1032 uint7_t eventType = 0;
1033 bool eventDir = 0;
1034 // System type events should have six fields
1035 if (targetEntryFields.size() >= 6)
1036 {
1037 std::string& generatorIDStr = targetEntryFields[3];
1038 std::string& sensorPath = targetEntryFields[4];
1039 std::string& eventDirStr = targetEntryFields[5];
1040
1041 // Get the generator ID
1042 try
1043 {
1044 generatorID = std::stoul(generatorIDStr, nullptr, 16);
1045 }
1046 catch (const std::invalid_argument&)
1047 {
1048 std::cerr << "Invalid Generator ID\n";
1049 }
1050
1051 // Get the sensor type, sensor number, and event type for the sensor
1052 sensorType = getSensorTypeFromPath(sensorPath);
1053 sensorAndLun = getSensorNumberFromPath(sensorPath);
1054 sensorNum = static_cast<uint8_t>(sensorAndLun);
Harvey.Wu4376cdf2021-11-16 19:40:55 +08001055 if ((generatorID & 0x0001) == 0)
1056 {
1057 // IPMB Address
1058 generatorID |= sensorAndLun & 0x0300;
1059 }
1060 else
1061 {
1062 // system software
1063 generatorID |= sensorAndLun >> 8;
1064 }
Willy Tude54f482021-01-26 15:59:09 -08001065 eventType = getSensorEventTypeFromPath(sensorPath);
1066
1067 // Get the event direction
1068 try
1069 {
1070 eventDir = std::stoul(eventDirStr) ? 0 : 1;
1071 }
1072 catch (const std::invalid_argument&)
1073 {
1074 std::cerr << "Invalid Event Direction\n";
1075 }
1076 }
1077
1078 // Only keep the eventData bytes that fit in the record
1079 std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>
1080 eventData{};
1081 std::copy_n(eventDataBytes.begin(),
1082 std::min(eventDataBytes.size(), eventData.size()),
1083 eventData.begin());
1084
1085 return ipmi::responseSuccess(
1086 nextRecordID, recordID, recordType,
1087 systemEventType{timestamp, generatorID, evmRev, sensorType,
1088 sensorNum, eventType, eventDir, eventData});
1089 }
1090
Thang Trane70c59b2023-09-21 13:54:28 +07001091 if (recordType >= dynamic_sensors::ipmi::sel::oemTsEventFirst &&
1092 recordType <= dynamic_sensors::ipmi::sel::oemTsEventLast)
1093 {
1094 // Get the timestamp
1095 std::tm timeStruct = {};
1096 std::istringstream entryStream(entryTimestamp);
1097
1098 uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1099 if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1100 {
1101 timeStruct.tm_isdst = -1;
1102 timestamp = std::mktime(&timeStruct);
1103 }
1104
1105 // Only keep the bytes that fit in the record
1106 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>
1107 eventData{};
1108 std::copy_n(eventDataBytes.begin(),
1109 std::min(eventDataBytes.size(), eventData.size()),
1110 eventData.begin());
1111
1112 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1113 oemTsEventType{timestamp, eventData});
1114 }
1115
1116 if (recordType >= dynamic_sensors::ipmi::sel::oemEventFirst)
1117 {
1118 // Only keep the bytes that fit in the record
1119 std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>
1120 eventData{};
1121 std::copy_n(eventDataBytes.begin(),
1122 std::min(eventDataBytes.size(), eventData.size()),
1123 eventData.begin());
1124
1125 return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1126 eventData);
1127 }
1128
Willy Tude54f482021-01-26 15:59:09 -08001129 return ipmi::responseUnspecifiedError();
1130}
1131
Willy Tu11d68892022-01-20 10:37:34 -08001132/*
1133Unused arguments
1134 uint16_t recordID, uint8_t recordType, uint32_t timestamp,
1135 uint16_t generatorID, uint8_t evmRev, uint8_t sensorType, uint8_t sensorNum,
1136 uint8_t eventType, uint8_t eventData1, uint8_t eventData2,
1137 uint8_t eventData3
1138*/
Patrick Williams69b4c282025-03-03 11:19:13 -05001139ipmi::RspType<uint16_t> ipmiStorageAddSELEntry(
1140 uint16_t, uint8_t, uint32_t, uint16_t, uint8_t, uint8_t, uint8_t, uint8_t,
1141 uint8_t, uint8_t, uint8_t)
Willy Tude54f482021-01-26 15:59:09 -08001142{
1143 // Per the IPMI spec, need to cancel any reservation when a SEL entry is
1144 // added
1145 cancelSELReservation();
1146
1147 uint16_t responseID = 0xFFFF;
1148 return ipmi::responseSuccess(responseID);
1149}
1150
Patrick Williams1318a5e2024-08-16 15:19:54 -04001151ipmi::RspType<uint8_t> ipmiStorageClearSEL(
1152 ipmi::Context::ptr ctx, uint16_t reservationID,
1153 const std::array<uint8_t, 3>& clr, uint8_t eraseOperation)
Willy Tude54f482021-01-26 15:59:09 -08001154{
1155 if (!checkSELReservation(reservationID))
1156 {
1157 return ipmi::responseInvalidReservationId();
1158 }
1159
1160 static constexpr std::array<uint8_t, 3> clrExpected = {'C', 'L', 'R'};
1161 if (clr != clrExpected)
1162 {
1163 return ipmi::responseInvalidFieldRequest();
1164 }
1165
1166 // Erasure status cannot be fetched, so always return erasure status as
1167 // `erase completed`.
1168 if (eraseOperation == ipmi::sel::getEraseStatus)
1169 {
1170 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1171 }
1172
1173 // Check that initiate erase is correct
1174 if (eraseOperation != ipmi::sel::initiateErase)
1175 {
1176 return ipmi::responseInvalidFieldRequest();
1177 }
1178
1179 // Per the IPMI spec, need to cancel any reservation when the SEL is
1180 // cleared
1181 cancelSELReservation();
1182
George Liude1420d2025-03-03 15:14:25 +08001183 boost::system::error_code ec =
1184 ipmi::callDbusMethod(ctx, "xyz.openbmc_project.Logging.IPMI",
1185 "/xyz/openbmc_project/Logging/IPMI",
1186 "xyz.openbmc_project.Logging.IPMI", "Clear");
Charles Boyer818bea12021-09-20 16:56:36 -05001187 if (ec)
1188 {
George Liude1420d2025-03-03 15:14:25 +08001189 std::cerr << "error in clear SEL: " << ec.message() << std::endl;
Charles Boyer818bea12021-09-20 16:56:36 -05001190 return ipmi::responseUnspecifiedError();
1191 }
Willy Tude54f482021-01-26 15:59:09 -08001192
1193 return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1194}
1195
Patrick Williams1318a5e2024-08-16 15:19:54 -04001196std::vector<uint8_t> getType8SDRs(
1197 ipmi::sensor::EntityInfoMap::const_iterator& entity, uint16_t recordId)
Harvey Wu05d17c02021-09-15 08:46:59 +08001198{
1199 std::vector<uint8_t> resp;
1200 get_sdr::SensorDataEntityRecord data{};
1201
1202 /* Header */
1203 get_sdr::header::set_record_id(recordId, &(data.header));
1204 // Based on IPMI Spec v2.0 rev 1.1
1205 data.header.sdr_version = SDR_VERSION;
1206 data.header.record_type = 0x08;
1207 data.header.record_length = sizeof(data.key) + sizeof(data.body);
1208
1209 /* Key */
1210 data.key.containerEntityId = entity->second.containerEntityId;
1211 data.key.containerEntityInstance = entity->second.containerEntityInstance;
1212 get_sdr::key::set_flags(entity->second.isList, entity->second.isLinked,
1213 &(data.key));
1214 data.key.entityId1 = entity->second.containedEntities[0].first;
1215 data.key.entityInstance1 = entity->second.containedEntities[0].second;
1216
1217 /* Body */
1218 data.body.entityId2 = entity->second.containedEntities[1].first;
1219 data.body.entityInstance2 = entity->second.containedEntities[1].second;
1220 data.body.entityId3 = entity->second.containedEntities[2].first;
1221 data.body.entityInstance3 = entity->second.containedEntities[2].second;
1222 data.body.entityId4 = entity->second.containedEntities[3].first;
1223 data.body.entityInstance4 = entity->second.containedEntities[3].second;
1224
1225 resp.insert(resp.end(), (uint8_t*)&data, ((uint8_t*)&data) + sizeof(data));
1226
1227 return resp;
1228}
1229
Willy Tude54f482021-01-26 15:59:09 -08001230std::vector<uint8_t> getType12SDRs(uint16_t index, uint16_t recordId)
1231{
1232 std::vector<uint8_t> resp;
1233 if (index == 0)
1234 {
Willy Tude54f482021-01-26 15:59:09 -08001235 std::string bmcName = "Basbrd Mgmt Ctlr";
Johnathan Manteycd1c4962021-09-22 12:58:08 -07001236 Type12Record bmc(recordId, 0x20, 0, 0, 0xbf, 0x2e, 1, 0, bmcName);
Willy Tude54f482021-01-26 15:59:09 -08001237 uint8_t* bmcPtr = reinterpret_cast<uint8_t*>(&bmc);
1238 resp.insert(resp.end(), bmcPtr, bmcPtr + sizeof(Type12Record));
1239 }
1240 else if (index == 1)
1241 {
Willy Tude54f482021-01-26 15:59:09 -08001242 std::string meName = "Mgmt Engine";
Johnathan Manteycd1c4962021-09-22 12:58:08 -07001243 Type12Record me(recordId, 0x2c, 6, 0x24, 0x21, 0x2e, 2, 0, meName);
Willy Tude54f482021-01-26 15:59:09 -08001244 uint8_t* mePtr = reinterpret_cast<uint8_t*>(&me);
1245 resp.insert(resp.end(), mePtr, mePtr + sizeof(Type12Record));
1246 }
1247 else
1248 {
Patrick Williams1318a5e2024-08-16 15:19:54 -04001249 throw std::runtime_error(
1250 "getType12SDRs:: Illegal index " + std::to_string(index));
Willy Tude54f482021-01-26 15:59:09 -08001251 }
1252
1253 return resp;
1254}
1255
1256void registerStorageFunctions()
1257{
1258 createTimers();
1259 startMatch();
1260
1261 // <Get FRU Inventory Area Info>
Willy Tud351a722021-08-12 14:33:40 -07001262 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
Willy Tude54f482021-01-26 15:59:09 -08001263 ipmi::storage::cmdGetFruInventoryAreaInfo,
1264 ipmi::Privilege::User, ipmiStorageGetFruInvAreaInfo);
1265 // <READ FRU Data>
1266 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1267 ipmi::storage::cmdReadFruData, ipmi::Privilege::User,
1268 ipmiStorageReadFruData);
1269
1270 // <WRITE FRU Data>
1271 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1272 ipmi::storage::cmdWriteFruData,
1273 ipmi::Privilege::Operator, ipmiStorageWriteFruData);
1274
1275 // <Get SEL Info>
1276 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1277 ipmi::storage::cmdGetSelInfo, ipmi::Privilege::User,
1278 ipmiStorageGetSELInfo);
1279
1280 // <Get SEL Entry>
1281 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1282 ipmi::storage::cmdGetSelEntry, ipmi::Privilege::User,
1283 ipmiStorageGetSELEntry);
1284
1285 // <Add SEL Entry>
1286 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1287 ipmi::storage::cmdAddSelEntry,
1288 ipmi::Privilege::Operator, ipmiStorageAddSELEntry);
1289
1290 // <Clear SEL>
1291 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1292 ipmi::storage::cmdClearSel, ipmi::Privilege::Operator,
1293 ipmiStorageClearSEL);
Willy Tude54f482021-01-26 15:59:09 -08001294}
1295} // namespace storage
1296} // namespace ipmi